query
stringlengths
7
3.85k
document
stringlengths
11
430k
metadata
dict
negatives
sequencelengths
0
101
negative_scores
sequencelengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
LockedCoins returns the set of coins that are not spendable (i.e. locked), defined as the vesting coins that are not delegated.
func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins { return plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime()))\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func (dcr *ExchangeWallet) lockedOutputs() ([]chainjson.TransactionInput, error) {\n\tvar locked []chainjson.TransactionInput\n\terr := dcr.nodeRawRequest(methodListLockUnspent, anylist{dcr.acct}, &locked)\n\treturn locked, err\n}", "func (w *rpcWallet) LockedOutputs(ctx context.Context, acctName string) ([]chainjson.TransactionInput, error) {\n\tvar locked []chainjson.TransactionInput\n\terr := w.rpcClientRawRequest(ctx, methodListLockUnspent, anylist{acctName}, &locked)\n\treturn locked, translateRPCCancelErr(err)\n}", "func (w *Wallet) LockedOutpoints() []btcjson.TransactionInput {\n\tlocked := make([]btcjson.TransactionInput, len(w.lockedOutpoints))\n\ti := 0\n\tfor op := range w.lockedOutpoints {\n\t\tlocked[i] = btcjson.TransactionInput{\n\t\t\tTxid: op.Hash.String(),\n\t\t\tVout: op.Index,\n\t\t}\n\t\ti++\n\t}\n\treturn locked\n}", "func (a *Account) LockedOutpoints() []btcjson.TransactionInput {\n\tlocked := make([]btcjson.TransactionInput, len(a.lockedOutpoints))\n\ti := 0\n\tfor op := range a.lockedOutpoints {\n\t\tlocked[i] = btcjson.TransactionInput{\n\t\t\tTxid: op.Hash.String(),\n\t\t\tVout: op.Index,\n\t\t}\n\t\ti++\n\t}\n\treturn locked\n}", "func (b *Bitcoind) ListLockUnspent() (unspendableOutputs []UnspendableOutput, err error) {\n\tr, err := b.client.call(\"listlockunspent\", nil)\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &unspendableOutputs)\n\treturn\n}", "func (btc *ExchangeWallet) lockedSats() (uint64, error) {\n\tlockedOutpoints, err := btc.wallet.ListLockUnspent()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar sum uint64\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, outPoint := range lockedOutpoints {\n\t\topID := outpointID(outPoint.TxID, outPoint.Vout)\n\t\tutxo, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tsum += utxo.amount\n\t\t\tcontinue\n\t\t}\n\t\ttxHash, err := chainhash.NewHashFromStr(outPoint.TxID)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttxOut, err := btc.node.GetTxOut(txHash, outPoint.Vout, true)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif txOut == nil {\n\t\t\t// Must be spent now?\n\t\t\tbtc.log.Debugf(\"ignoring output from listlockunspent that wasn't found with gettxout. %s\", opID)\n\t\t\tcontinue\n\t\t}\n\t\tsum += toSatoshi(txOut.Value)\n\t}\n\treturn sum, nil\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tlockedOutputs, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, output := range lockedOutputs {\n\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, output.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, output.Vout, true)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), translateRPCCancelErr(err))\n\t\t}\n\t\tvar address string\n\t\tif len(txOut.ScriptPubKey.Addresses) > 0 {\n\t\t\taddress = txOut.ScriptPubKey.Addresses[0]\n\t\t}\n\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\treturn coins, nil\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, txout := range unspents {\n\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: txout.Address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr = dcr.node.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\n\treturn coins, nil\n}", "func (bc *BlockChain) FindUnspentTransactions(addr string) []Transaction {\n\tvar unspentTXs []Transaction\n\tspentTXOutputs := make(map[string][]int)\n\titerator := bc.Iterator()\n\n\tfor {\n\t\t_block := iterator.Next()\n\n\t\tfor _, tx := range _block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.VOut {\n\t\t\t\tif spentTXOutputs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTXOutputs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlockedWith(addr) {\n\t\t\t\t\tunspentTXs = append(unspentTXs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !tx.isCoinBaseTx() {\n\t\t\t\tfor _, in := range tx.VIn {\n\t\t\t\t\tif in.CanUnlockOutputWith(addr) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.TxID)\n\t\t\t\t\t\tspentTXOutputs[inTxID] = append(spentTXOutputs[inTxID], in.VOut)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(_block.Prev) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTXs\n}", "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tlockedOutputs, err := dcr.wallet.LockedOutputs(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, output := range lockedOutputs {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, output.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, txHash, output.Vout, output.Tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), err)\n\t\t\t}\n\t\t\tvar address string\n\t\t\tif len(txOut.Addresses) > 0 {\n\t\t\t\taddress = txOut.Addresses[0]\n\t\t\t}\n\t\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\treturn coins, nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunspents, err := dcr.wallet.Unspents(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, txout := range unspents {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: txout.Address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return an error if some coins are still not found.\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn coins, nil\n}", "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (chain *BlockChain) FindUnspentTransactions(address string) []Transaction {\n\tvar unspentTxs []Transaction\n\n\tspentTxOs := make(map[string][]int)\n\n\titer := chain.Iterator()\n\n\tfor {\n\t\tblock := iter.Next()\n\n\t\tfor _, tx := range block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.Outputs {\n\t\t\t\tif spentTxOs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTxOs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlocked(address) {\n\t\t\t\t\tunspentTxs = append(unspentTxs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif tx.IsCoinbase() == false {\n\t\t\t\tfor _, in := range tx.Inputs {\n\t\t\t\t\tif in.CanUnlock(address) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.ID)\n\n\t\t\t\t\t\tspentTxOs[inTxID] = append(spentTxOs[inTxID], in.Out)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(block.PrevHash) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTxs\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (dcr *ExchangeWallet) lockFundingCoins(fCoins []*fundingCoin) error {\n\twireOPs := make([]*wire.OutPoint, 0, len(fCoins))\n\tfor _, c := range fCoins {\n\t\twireOPs = append(wireOPs, wire.NewOutPoint(c.op.txHash(), c.op.vout(), c.op.tree))\n\t}\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, wireOPs)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, c := range fCoins {\n\t\tdcr.fundingCoins[c.op.pt] = c\n\t}\n\treturn nil\n}", "func (b *Bitcoind) LockUnspent(lock bool, outputs []UnspendableOutput) (success bool, err error) {\n\tr, err := b.client.call(\"lockunspent\", []interface{}{lock, outputs})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &success)\n\treturn\n}", "func (va ClawbackVestingAccount) GetUnlockedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.LockupPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (dcr *ExchangeWallet) returnCoins(unspents asset.Coins) ([]*fundingCoin, error) {\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"cannot return zero coins\")\n\t}\n\n\tops := make([]*wire.OutPoint, 0, len(unspents))\n\tfundingCoins := make([]*fundingCoin, 0, len(unspents))\n\n\tdcr.log.Debugf(\"returning coins %s\", unspents)\n\tfor _, unspent := range unspents {\n\t\top, err := dcr.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error converting coin: %w\", err)\n\t\t}\n\t\tops = append(ops, op.wireOutPoint()) // op.tree may be wire.TxTreeUnknown, but that's fine since wallet.LockUnspent doesn't rely on it\n\t\tif fCoin, ok := dcr.fundingCoins[op.pt]; ok {\n\t\t\tfundingCoins = append(fundingCoins, fCoin)\n\t\t\tdelete(dcr.fundingCoins, op.pt)\n\t\t} else {\n\t\t\tdcr.log.Warnf(\"returning coin %s that is not cached as a funding coin\", op)\n\t\t\tfundingCoins = append(fundingCoins, &fundingCoin{op: op})\n\t\t}\n\t}\n\n\treturn fundingCoins, dcr.wallet.LockUnspent(dcr.ctx, true, ops)\n}", "func (w *Wallet) Locked() bool {\n\treturn <-w.lockState\n}", "func (dcr *ExchangeWallet) lockFundingCoins(fCoins []*fundingCoin) error {\n\twireOPs := make([]*wire.OutPoint, 0, len(fCoins))\n\tfor _, c := range fCoins {\n\t\twireOPs = append(wireOPs, wire.NewOutPoint(c.op.txHash(), c.op.vout(), c.op.tree))\n\t}\n\terr := dcr.node.LockUnspent(dcr.ctx, false, wireOPs)\n\tif err != nil {\n\t\treturn translateRPCCancelErr(err)\n\t}\n\tfor _, c := range fCoins {\n\t\tdcr.fundingCoins[c.op.pt] = c\n\t}\n\treturn nil\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (dcr *ExchangeWallet) returnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*wire.OutPoint, 0, len(unspents))\n\n\tdcr.log.Debugf(\"returning coins %s\", unspents)\n\tfor _, unspent := range unspents {\n\t\top, err := dcr.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %w\", err)\n\t\t}\n\t\tops = append(ops, wire.NewOutPoint(op.txHash(), op.vout(), op.tree))\n\t\tdelete(dcr.fundingCoins, op.pt)\n\t}\n\treturn translateRPCCancelErr(dcr.node.LockUnspent(dcr.ctx, true, ops))\n}", "func (dcr *ExchangeWallet) Locked() bool {\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunlocked, err := dcr.wallet.AccountUnlocked(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"error checking account lock status %v\", err)\n\t\t\tunlocked = false // assume wallet is unlocked?\n\t\t}\n\t\tif !unlocked {\n\t\t\treturn true // Locked is true if any of the funding accounts is locked.\n\t\t}\n\t}\n\treturn false\n}", "func (w *Wallet) ListUnspent(minconf, maxconf int32,\n\taddresses map[string]struct{}) ([]*btcjson.ListUnspentResult, er.R) {\n\n\tvar results []*btcjson.ListUnspentResult\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\taddrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)\n\t\ttxmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)\n\n\t\tsyncBlock := w.Manager.SyncedTo()\n\n\t\tfilter := len(addresses) != 0\n\t\tunspent, err := w.TxStore.GetUnspentOutputs(txmgrNs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsort.Sort(sort.Reverse(creditSlice(unspent)))\n\n\t\tdefaultAccountName := \"default\"\n\n\t\tresults = make([]*btcjson.ListUnspentResult, 0, len(unspent))\n\t\tfor i := range unspent {\n\t\t\toutput := unspent[i]\n\n\t\t\t// Outputs with fewer confirmations than the minimum or more\n\t\t\t// confs than the maximum are excluded.\n\t\t\tconfs := confirms(output.Height, syncBlock.Height)\n\t\t\tif confs < minconf || confs > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Only mature coinbase outputs are included.\n\t\t\tif output.FromCoinBase {\n\t\t\t\ttarget := int32(w.ChainParams().CoinbaseMaturity)\n\t\t\t\tif !confirmed(target, output.Height, syncBlock.Height) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Exclude locked outputs from the result set.\n\t\t\tif w.LockedOutpoint(output.OutPoint) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Lookup the associated account for the output. Use the\n\t\t\t// default account name in case there is no associated account\n\t\t\t// for some reason, although this should never happen.\n\t\t\t//\n\t\t\t// This will be unnecessary once transactions and outputs are\n\t\t\t// grouped under the associated account in the db.\n\t\t\tacctName := defaultAccountName\n\t\t\tsc, addrs, _, err := txscript.ExtractPkScriptAddrs(\n\t\t\t\toutput.PkScript, w.chainParams)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tsmgr, acct, err := w.Manager.AddrAccount(addrmgrNs, addrs[0])\n\t\t\t\tif err == nil {\n\t\t\t\t\ts, err := smgr.AccountName(addrmgrNs, acct)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tacctName = s\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\tinclude:\n\t\t\t// At the moment watch-only addresses are not supported, so all\n\t\t\t// recorded outputs that are not multisig are \"spendable\".\n\t\t\t// Multisig outputs are only \"spendable\" if all keys are\n\t\t\t// controlled by this wallet.\n\t\t\t//\n\t\t\t// TODO: Each case will need updates when watch-only addrs\n\t\t\t// is added. For P2PK, P2PKH, and P2SH, the address must be\n\t\t\t// looked up and not be watching-only. For multisig, all\n\t\t\t// pubkeys must belong to the manager with the associated\n\t\t\t// private key (currently it only checks whether the pubkey\n\t\t\t// exists, since the private key is required at the moment).\n\t\t\tvar spendable bool\n\t\tscSwitch:\n\t\t\tswitch sc {\n\t\t\tcase txscript.PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.PubKeyTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0ScriptHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.MultiSigTy:\n\t\t\t\tfor _, a := range addrs {\n\t\t\t\t\t_, err := w.Manager.Address(addrmgrNs, a)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif waddrmgr.ErrAddressNotFound.Is(err) {\n\t\t\t\t\t\tbreak scSwitch\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tspendable = true\n\t\t\t}\n\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxID: output.OutPoint.Hash.String(),\n\t\t\t\tVout: output.OutPoint.Index,\n\t\t\t\tAccount: acctName,\n\t\t\t\tScriptPubKey: hex.EncodeToString(output.PkScript),\n\t\t\t\tAmount: output.Amount.ToBTC(),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t\tSpendable: spendable,\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t\treturn nil\n\t})\n\treturn results, err\n}", "func (wt *Wallet) Locked() bool {\n\treturn <-wt.lockState\n}", "func NewQueryLockedCoinsParams(accountID types.AccountID) QueryLockedCoinsParams {\n\treturn QueryLockedCoinsParams{\n\t\tAccountID: accountID,\n\t}\n}", "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func GetLockedDistributionAddresses() []string {\n\t// TODO -- once we reach 30% distribution, we can hardcode the\n\t// initial timestamp for releasing more coins\n\taddrs := make([]string, DistributionAddressesTotal-InitialUnlockedCount)\n\tfor i := range distributionAddresses[InitialUnlockedCount:] {\n\t\taddrs[i] = distributionAddresses[InitialUnlockedCount+uint64(i)]\n\t}\n\n\treturn addrs\n}", "func (btc *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*output, 0, len(unspents))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, unspent := range unspents {\n\t\top, err := btc.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %v\", err)\n\t\t}\n\t\tops = append(ops, op)\n\t\tdelete(btc.fundingCoins, outpointID(op.txHash.String(), op.vout))\n\t}\n\treturn btc.wallet.LockUnspent(true, ops)\n}", "func (r *Ring) InPot() []Box {\n\treturn r.Where(func(s *Seat) bool {\n\t\treturn s.State == seat.Play || s.State == seat.Bet || s.State == seat.AllIn\n\t})\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock()\n\treturn dcr.returnCoins(unspents)\n}", "func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (txn TxnProbe) CollectLockedKeys() [][]byte {\n\treturn txn.collectLockedKeys()\n}", "func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func GetUnspentOutputCoinsExceptSpendingUTXO(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.InputCoin, error) {\n\tpublicKey := keyWallet.KeySet.PaymentAddress.Pk\n\n\t// check and remove utxo cache (these utxos in txs that were confirmed)\n\t//CheckAndRemoveUTXOFromCache(keyWallet.KeySet.PaymentAddress.Pk, inputCoins)\n\tCheckAndRemoveUTXOFromCacheV2(keyWallet.KeySet.PaymentAddress.Pk, rpcClient)\n\n\t// get unspent output coins from network\n\tutxos, err := GetUnspentOutputCoins(rpcClient, keyWallet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinputCoins := ConvertOutputCoinToInputCoin(utxos)\n\n\t// except spending utxos from unspent output coins\n\tutxosInCache := GetUTXOCacheByPublicKey(publicKey)\n\tfor serialNumberStr, _ := range utxosInCache {\n\t\tfor i, inputCoin := range inputCoins {\n\t\t\tsnStrTmp := base58.Base58Check{}.Encode(inputCoin.CoinDetails.GetSerialNumber().ToBytesS(), common.ZeroByte)\n\t\t\tif snStrTmp == serialNumberStr {\n\t\t\t\tinputCoins = removeElementFromSlice(inputCoins, i)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn inputCoins, nil\n}", "func (btc *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[string]struct{})\n\tbtc.fundingMtx.RLock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\tbtc.fundingMtx.RUnlock()\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tfundingCoin, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tcoins = append(coins, newOutput(btc.node, txHash, vout, fundingCoin.amount, fundingCoin.redeemScript))\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[opID] = struct{}{}\n\t}\n\tbtc.fundingMtx.RUnlock()\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\t_, utxoMap, _, err := btc.spendableUTXOs(0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlockers := make([]*output, 0, len(ids))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tutxo, found := utxoMap[opID]\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"funding coin %s not found\", opID)\n\t\t}\n\t\tbtc.fundingCoins[opID] = utxo\n\t\tcoin := newOutput(btc.node, utxo.txHash, utxo.vout, utxo.amount, utxo.redeemScript)\n\t\tcoins = append(coins, coin)\n\t\tlockers = append(lockers, coin)\n\t\tdelete(notFound, opID)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor opID := range notFound {\n\t\t\tids = append(ids, opID)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\terr = btc.wallet.LockUnspent(false, lockers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn coins, nil\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (o *AccountCollectionGetParams) SetLocked(locked *bool) {\n\to.Locked = locked\n}", "func (c *CoordinatorHelper) Coins(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) ([]*types.Coin, error) {\n\tcoins, _, err := c.coinStorage.GetCoinsTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: unable to get coins\", err)\n\t}\n\n\tcoinsToReturn := []*types.Coin{}\n\tfor _, coin := range coins {\n\t\tif types.Hash(coin.Amount.Currency) != types.Hash(currency) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcoinsToReturn = append(coinsToReturn, coin)\n\t}\n\n\treturn coinsToReturn, nil\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\treturnedCoins, err := dcr.returnCoins(unspents)\n\tdcr.fundingMtx.Unlock()\n\tif err != nil || dcr.unmixedAccount == \"\" {\n\t\treturn err\n\t}\n\n\t// If any of these coins belong to the trading account, transfer them to the\n\t// unmixed account to be re-mixed into the primary account before being\n\t// re-selected for funding future orders. This doesn't apply to unspent\n\t// split tx outputs, which should remain in the trading account and be\n\t// selected from there for funding future orders.\n\tvar coinsToTransfer []asset.Coin\n\tfor _, coin := range returnedCoins {\n\t\tif coin.addr == \"\" {\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, coin.op.txHash(), coin.op.vout(), coin.op.tree)\n\t\t\tif err != nil {\n\t\t\t\tdcr.log.Errorf(\"wallet.UnspentOutput error for returned coin %s: %v\", coin.op, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(txOut.Addresses) == 0 {\n\t\t\t\tdcr.log.Errorf(\"no address in gettxout response for returned coin %s\", coin.op)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoin.addr = txOut.Addresses[0]\n\t\t}\n\t\taddrInfo, err := dcr.wallet.AddressInfo(dcr.ctx, coin.addr)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"wallet.AddressInfo error for returned coin %s: %v\", coin.op, err)\n\t\t\tcontinue\n\t\t}\n\t\t// Move this coin to the unmixed account if it was sent to the internal\n\t\t// branch of the trading account. This excludes unspent split tx outputs\n\t\t// which are sent to the external branch of the trading account.\n\t\tif addrInfo.Branch == acctInternalBranch && addrInfo.Account == dcr.tradingAccount {\n\t\t\tcoinsToTransfer = append(coinsToTransfer, coin.op)\n\t\t}\n\t}\n\n\tif len(coinsToTransfer) > 0 {\n\t\ttx, totalSent, err := dcr.sendAll(coinsToTransfer, dcr.unmixedAccount)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"unable to transfer unlocked swapped change from temp trading \"+\n\t\t\t\t\"account to unmixed account: %v\", err)\n\t\t} else {\n\t\t\tdcr.log.Infof(\"Transferred %s from temp trading account to unmixed account in tx %s.\",\n\t\t\t\tdcrutil.Amount(totalSent), tx.TxHash())\n\t\t}\n\t}\n\n\treturn nil\n}", "func GetCoins(accCoins []types.Coin) AccountCoins {\n\tcoins := make(AccountCoins, 0)\n\tfor _, coin := range accCoins {\n\t\tcoins = append(coins, AccountCoin{Amount: uint64(coin.Amount), Denom: coin.Denom})\n\t}\n\treturn coins\n}", "func (keeper BaseViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (b *BlockChain) GetUnspentTxns(address string) []Transaction {\n\tvar unspentTxns []Transaction\n\tvar spentTxnMap = make(map[string][]int) // map txnID -> output index\n\n\t// go over blocks one by one\n\titer := b.GetIterator()\n\tfor {\n\t\tblck := iter.Next()\n\n\t\t// go over all Transactions in this block\n\t\tfor _, txn := range blck.Transactions {\n\t\t\t// get string identifying this transaction\n\t\t\ttxID := hex.EncodeToString(txn.ID)\n\n\t\tOutputLoop:\n\t\t\t// go over all outputs in this Txn\n\t\t\tfor outIndex, output := range txn.Out {\n\n\t\t\t\t// check if this output is spent.\n\t\t\t\tif spentTxnMap[txID] != nil {\n\t\t\t\t\tfor _, indx := range spentTxnMap[txID] {\n\t\t\t\t\t\tif indx == outIndex {\n\t\t\t\t\t\t\tcontinue OutputLoop\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// check if this output belongs to this address\n\t\t\t\tif output.CheckOutputUnlock(address) {\n\t\t\t\t\tunspentTxns = append(unspentTxns, *txn)\n\t\t\t\t}\n\n\t\t\t\t// if this is not genesis block, go over all inputs\n\t\t\t\t// that refers to output that belongs to this address\n\t\t\t\t// and mark them as unspent\n\t\t\t\tif txn.IsCoinbase() == false {\n\t\t\t\t\tfor _, inp := range txn.In {\n\t\t\t\t\t\tif inp.CheckInputUnlock(address) {\n\t\t\t\t\t\t\tspentTxnMap[txID] = append(spentTxnMap[txID], inp.Out)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(blck.PrevBlockHash) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn unspentTxns\n}", "func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (dcr *ExchangeWallet) Locked() bool {\n\twalletInfo, err := dcr.node.WalletInfo(dcr.ctx)\n\tif err != nil {\n\t\tdcr.log.Errorf(\"walletinfo error: %v\", err)\n\t\treturn false\n\t}\n\treturn !walletInfo.Unlocked\n}", "func GetUnspentOutputCoins(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.OutputCoin, error) {\n\tprivateKey := &keyWallet.KeySet.PrivateKey\n\tpaymentAddressStr := keyWallet.Base58CheckSerialize(wallet.PaymentAddressType)\n\tviewingKeyStr := keyWallet.Base58CheckSerialize(wallet.ReadonlyKeyType)\n\n\toutputCoins, err := GetListOutputCoins(rpcClient, paymentAddressStr, viewingKeyStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserialNumbers, err := DeriveSerialNumbers(privateKey, outputCoins)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tisExisted, err := CheckExistenceSerialNumber(rpcClient, paymentAddressStr, serialNumbers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tutxos := make([]*crypto.OutputCoin, 0)\n\tfor i, out := range outputCoins {\n\t\tif !isExisted[i] {\n\t\t\tutxos = append(utxos, out)\n\t\t}\n\t}\n\n\treturn utxos, nil\n}", "func (dcr *ExchangeWallet) lockedAtoms() (uint64, error) {\n\tlockedOutpoints, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar sum uint64\n\tfor _, op := range lockedOutpoints {\n\t\tsum += toAtoms(op.Amount)\n\t}\n\treturn sum, nil\n}", "func (u UTXOSet) FindUnspentTransactions(pubKeyHash []byte) []TxOutput {\n\tvar UTXOs []TxOutput\n\n\tdb := u.Blockchain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through UTXOS prefixes\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\t// get the value of each utxo prefixed item\n\t\t\tv := valueHash(it.Item())\n\t\t\touts := DeserializeOutputs(v)\n\n\t\t\t// iterate through each output, check to see if it is locked by the provided hash address\n\t\t\tfor _, out := range outs.Outputs {\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\thandle(err)\n\n\treturn UTXOs\n}", "func distributeLockedAmount(ctx coretypes.Sandbox, bets []*BetInfo, totalLockedAmount int64) bool {\n\tsumsByPlayers := make(map[coretypes.AgentID]int64)\n\ttotalWinningAmount := int64(0)\n\tfor _, bet := range bets {\n\t\tif _, ok := sumsByPlayers[bet.Player]; !ok {\n\t\t\tsumsByPlayers[bet.Player] = 0\n\t\t}\n\t\tsumsByPlayers[bet.Player] += bet.Sum\n\t\ttotalWinningAmount += bet.Sum\n\t}\n\n\t// NOTE 1: float64 was avoided for determinism reasons\n\t// NOTE 2: beware overflows\n\n\tfor player, sum := range sumsByPlayers {\n\t\tsumsByPlayers[player] = (totalLockedAmount * sum) / totalWinningAmount\n\t}\n\n\t// make deterministic sequence by sorting. Eliminate possible rounding effects\n\tseqPlayers := make([]coretypes.AgentID, 0, len(sumsByPlayers))\n\tresultSum := int64(0)\n\tfor player, sum := range sumsByPlayers {\n\t\tseqPlayers = append(seqPlayers, player)\n\t\tresultSum += sum\n\t}\n\tsort.Slice(seqPlayers, func(i, j int) bool {\n\t\treturn bytes.Compare(seqPlayers[i][:], seqPlayers[j][:]) < 0\n\t})\n\n\t// ensure we distribute not more than totalLockedAmount iotas\n\tif resultSum > totalLockedAmount {\n\t\tsumsByPlayers[seqPlayers[0]] -= resultSum - totalLockedAmount\n\t}\n\n\t// filter out those who proportionally got 0\n\tfinalWinners := seqPlayers[:0]\n\tfor _, player := range seqPlayers {\n\t\tif sumsByPlayers[player] <= 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfinalWinners = append(finalWinners, player)\n\t}\n\t// distribute iotas\n\tfor i := range finalWinners {\n\n\t\tavailable := ctx.Balance(balance.ColorIOTA)\n\t\tctx.Event(fmt.Sprintf(\"sending reward iotas %d to the winner %s. Available iotas: %d\",\n\t\t\tsumsByPlayers[finalWinners[i]], finalWinners[i].String(), available))\n\n\t\t//if !ctx.MoveTokens(finalWinners[i], balance.ColorIOTA, sumsByPlayers[finalWinners[i]]) {\n\t\t//\treturn false\n\t\t//}\n\t}\n\treturn true\n}", "func (w *rpcWallet) LockUnspent(ctx context.Context, unlock bool, ops []*wire.OutPoint) error {\n\treturn translateRPCCancelErr(w.client().LockUnspent(ctx, unlock, ops))\n}", "func (ck CoinKeeper) GetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Coins {\n\tacc := ck.am.GetAccount(ctx, addr)\n\treturn acc.GetCoins()\n}", "func GetUnlockedDistributionAddresses() []string {\n\t// The first InitialUnlockedCount (25) addresses are unlocked by default.\n\t// Subsequent addresses will be unlocked at a rate of UnlockAddressRate (5) per year,\n\t// after the InitialUnlockedCount (25) addresses have no remaining balance.\n\t// The unlock timer will be enabled manually once the\n\t// InitialUnlockedCount (25) addresses are distributed.\n\n\t// NOTE: To have automatic unlocking, transaction verification would have\n\t// to be handled in visor rather than in coin.Transactions.Visor(), because\n\t// the coin package is agnostic to the state of the blockchain and cannot reference it.\n\t// Instead of automatic unlocking, we can hardcode the timestamp at which the first 30%\n\t// is distributed, then compute the unlocked addresses easily here.\n\n\taddrs := make([]string, InitialUnlockedCount)\n\tfor i := range distributionAddresses[:InitialUnlockedCount] {\n\t\taddrs[i] = distributionAddresses[i]\n\t}\n\treturn addrs\n}", "func WithoutBlocking(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, nonBlockingTxnCtxKey, &nonBlockingTxnOpt{})\n}", "func (b *Bitcoind) ListUnspent(minconf, maxconf uint32) (transactions []Transaction, err error) {\n\tif maxconf > 999999 {\n\t\tmaxconf = 999999\n\t}\n\n\tr, err := b.client.call(\"listunspent\", []interface{}{minconf, maxconf})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &transactions)\n\treturn\n}", "func (am *AccountManager) ListUnspent(minconf, maxconf int,\n\taddresses map[string]bool) ([]*btcjson.ListUnspentResult, error) {\n\n\tbs, err := GetCurBlock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilter := len(addresses) != 0\n\n\tvar results []*btcjson.ListUnspentResult\n\tfor _, a := range am.AllAccounts() {\n\t\tunspent, err := a.TxStore.UnspentOutputs()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, credit := range unspent {\n\t\t\tconfs := credit.Confirmations(bs.Height)\n\t\t\tif int(confs) < minconf || int(confs) > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, addrs, _, _ := credit.Addresses(cfg.Net())\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\tinclude:\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxId: credit.Tx().Sha().String(),\n\t\t\t\tVout: credit.OutputIndex,\n\t\t\t\tAccount: a.Name(),\n\t\t\t\tScriptPubKey: hex.EncodeToString(credit.TxOut().PkScript),\n\t\t\t\tAmount: credit.Amount().ToUnit(btcutil.AmountBTC),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t}\n\n\treturn results, nil\n}", "func (w *Wallet) ResetLockedOutpoints() {\n\tw.lockedOutpoints = map[wire.OutPoint]struct{}{}\n}", "func (c *Channel) Locked() *big.Int {\n\treturn c.OurState.AmountLocked()\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (c *Channel) Locked() *big.Int {\n\treturn c.OurState.amountLocked()\n}", "func (s *Store) ListLockedOutputs(ns walletdb.ReadBucket) ([]*LockedOutput,\n\terror) {\n\n\tvar outputs []*LockedOutput\n\terr := forEachLockedOutput(\n\t\tns, func(op wire.OutPoint, id LockID, expiration time.Time) {\n\t\t\t// Skip expired leases. They will be cleaned up with the\n\t\t\t// next call to DeleteExpiredLockedOutputs.\n\t\t\tif !s.clock.Now().Before(expiration) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\toutputs = append(outputs, &LockedOutput{\n\t\t\t\tOutpoint: op,\n\t\t\t\tLockID: id,\n\t\t\t\tExpiration: expiration,\n\t\t\t})\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn outputs, nil\n}", "func coinSupplyHandler(gateway Gatewayer) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodGet {\n\t\t\twh.Error405(w)\n\t\t\treturn\n\t\t}\n\n\t\tallUnspents, err := gateway.GetUnspentOutputsSummary(nil)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"gateway.GetUnspentOutputsSummary failed: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tunlockedAddrs := params.GetUnlockedDistributionAddressesDecoded()\n\t\t// Search map of unlocked addresses, used to filter unspents\n\t\tunlockedAddrSet := newAddrSet(unlockedAddrs)\n\n\t\tvar unlockedSupply uint64\n\t\t// check confirmed unspents only\n\t\tfor _, u := range allUnspents.Confirmed {\n\t\t\t// check if address is an unlocked distribution address\n\t\t\tif _, ok := unlockedAddrSet[u.Body.Address]; ok {\n\t\t\t\tvar err error\n\t\t\t\tunlockedSupply, err = mathutil.AddUint64(unlockedSupply, u.Body.Coins)\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"uint64 overflow while adding up unlocked supply coins: %v\", err)\n\t\t\t\t\twh.Error500(w, err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// \"total supply\" is the number of coins unlocked.\n\t\t// Each distribution address was allocated params.DistributionAddressInitialBalance coins.\n\t\ttotalSupply := uint64(len(unlockedAddrs)) * params.DistributionAddressInitialBalance\n\t\ttotalSupply *= droplet.Multiplier\n\n\t\t// \"current supply\" is the number of coins distributed from the unlocked pool\n\t\tcurrentSupply := totalSupply - unlockedSupply\n\n\t\tcurrentSupplyStr, err := droplet.ToString(currentSupply)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\ttotalSupplyStr, err := droplet.ToString(totalSupply)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tmaxSupplyStr, err := droplet.ToString(params.MaxCoinSupply * droplet.Multiplier)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t// locked distribution addresses\n\t\tlockedAddrs := params.GetLockedDistributionAddressesDecoded()\n\t\tlockedAddrSet := newAddrSet(lockedAddrs)\n\n\t\t// get total coins hours which excludes locked distribution addresses\n\t\tvar totalCoinHours uint64\n\t\tfor _, out := range allUnspents.Confirmed {\n\t\t\tif _, ok := lockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\tvar err error\n\t\t\t\ttotalCoinHours, err = mathutil.AddUint64(totalCoinHours, out.CalculatedHours)\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"uint64 overflow while adding up total coin hours: %v\", err)\n\t\t\t\t\twh.Error500(w, err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// get current coin hours which excludes all distribution addresses\n\t\tvar currentCoinHours uint64\n\t\tfor _, out := range allUnspents.Confirmed {\n\t\t\t// check if address not in locked distribution addresses\n\t\t\tif _, ok := lockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\t// check if address not in unlocked distribution addresses\n\t\t\t\tif _, ok := unlockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\t\tcurrentCoinHours += out.CalculatedHours\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to get total coinhours: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tcs := CoinSupply{\n\t\t\tCurrentSupply: currentSupplyStr,\n\t\t\tTotalSupply: totalSupplyStr,\n\t\t\tMaxSupply: maxSupplyStr,\n\t\t\tCurrentCoinHourSupply: strconv.FormatUint(currentCoinHours, 10),\n\t\t\tTotalCoinHourSupply: strconv.FormatUint(totalCoinHours, 10),\n\t\t\tUnlockedAddresses: params.GetUnlockedDistributionAddresses(),\n\t\t\tLockedAddresses: params.GetLockedDistributionAddresses(),\n\t\t}\n\n\t\twh.SendJSONOr500(logger, w, cs)\n\t}\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in %q account\", dcr.acct)\n\t}\n\n\t// Parse utxos to include script size for spending input.\n\t// Returned utxos will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func (s *Store) UnspentOutputs(ns walletdb.ReadBucket) ([]Credit, error) {\n\tvar unspent []Credit\n\n\tvar op wire.OutPoint\n\tvar block Block\n\terr := ns.NestedReadBucket(bucketUnspent).ForEach(func(k, v []byte) error {\n\t\terr := readCanonicalOutPoint(k, &op)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip this k/v pair.\n\t\t\treturn nil\n\t\t}\n\n\t\terr = readUnspentBlock(v, &block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tblockTime, err := fetchBlockTime(ns, block.Height)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// TODO(jrick): reading the entire transaction should\n\t\t// be avoidable. Creating the credit only requires the\n\t\t// output amount and pkScript.\n\t\trec, err := fetchTxRecord(ns, &op.Hash, &block)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to retrieve transaction %v: \"+\n\t\t\t\t\"%v\", op.Hash, err)\n\t\t}\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: block,\n\t\t\t\tTime: blockTime,\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\tunspent = append(unspent, cred)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\tstr := \"failed iterating unspent bucket\"\n\t\treturn nil, storeError(ErrDatabase, str, err)\n\t}\n\n\terr = ns.NestedReadBucket(bucketUnminedCredits).ForEach(func(k, v []byte) error {\n\t\tif err := readCanonicalOutPoint(k, &op); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip to next unmined credit.\n\t\t\treturn nil\n\t\t}\n\n\t\t// TODO(jrick): Reading/parsing the entire transaction record\n\t\t// just for the output amount and script can be avoided.\n\t\trecVal := existsRawUnmined(ns, op.Hash[:])\n\t\tvar rec TxRecord\n\t\terr = readRawTxRecord(&op.Hash, recVal, &rec)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to retrieve raw transaction \"+\n\t\t\t\t\"%v: %v\", op.Hash, err)\n\t\t}\n\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: Block{Height: -1},\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\tunspent = append(unspent, cred)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\tstr := \"failed iterating unmined credits bucket\"\n\t\treturn nil, storeError(ErrDatabase, str, err)\n\t}\n\n\treturn unspent, nil\n}", "func (tx *Transaction) GetNewFromCoins() []FromCoin {\n\tnfcs := make([]FromCoin, 0)\n\tfor index, c := range tx.To.Coins {\n\t\tticket := Ticket{}\n\t\tticket.SetTxid(*tx.GetTxID())\n\t\tticket.SetIndex(uint32(index))\n\n\t\tnfc := FromCoin{}\n\t\tnfc.SetId(c.Id)\n\t\tnfc.AddTicket(&ticket)\n\n\t\tnfcs = append(nfcs, nfc)\n\t}\n\n\treturn nfcs\n}", "func (b *BlockChain) GetUnspentOutputs(address string) []TxOutput {\n\tvar unspentOuts []TxOutput\n\ttxns := b.GetUnspentTxns(address)\n\n\t// go over each txn and each output in it and collect ones which belongs to this address\n\tfor _, txn := range txns {\n\t\t// iterate over all outputs\n\t\tfor _, output := range txn.Out {\n\t\t\tif output.CheckOutputUnlock(address) {\n\t\t\t\tunspentOuts = append(unspentOuts, output)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn unspentOuts\n}", "func (serv *ExchangeServer) GetSupportCoins() []string {\n\tsymbols := make([]string, len(serv.coins))\n\ti := 0\n\tfor _, coin := range serv.coins {\n\t\tsymbols[i] = coin.Symbol()\n\t\ti++\n\t}\n\treturn symbols\n}", "func (o RunnerOutput) Locked() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v *Runner) pulumi.BoolOutput { return v.Locked }).(pulumi.BoolOutput)\n}", "func (cb CommitteeBits) FilterNonParticipants(committee []ValidatorIndex) []ValidatorIndex {\n\tbitLen := cb.BitLen()\n\tout := committee[:0]\n\tif bitLen != uint64(len(committee)) {\n\t\tpanic(\"committee mismatch, bitfield length does not match\")\n\t}\n\tfor i := uint64(0); i < bitLen; i++ {\n\t\tif !cb.GetBit(i) {\n\t\t\tout = append(out, committee[i])\n\t\t}\n\t}\n\treturn out\n}", "func (cm *coinsMempool) Get(maxTransactions uint64, s state.State) ([]*primitives.Tx, state.State) {\n\tcm.lock.RLock()\n\tdefer cm.lock.RUnlock()\n\tallTransactions := make([]*primitives.Tx, 0, maxTransactions)\n\nouter:\n\tfor _, addr := range cm.mempool {\n\t\tfor _, tx := range addr.transactions {\n\t\t\tif err := s.ApplyTransactionSingle(tx, [20]byte{}, cm.params); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tallTransactions = append(allTransactions, tx)\n\t\t\tif uint64(len(allTransactions)) >= maxTransactions {\n\t\t\t\tbreak outer\n\t\t\t}\n\t\t}\n\t}\n\n\t// we can prioritize here, but we aren't to keep it simple\n\treturn allTransactions, s\n}", "func (k Keeper) MintCoins(ctx sdk.Context, newCoins sdk.Coins) error {\n\tif newCoins.Empty() {\n\t\t// skip as no coins need to be minted\n\t\treturn nil\n\t}\n\treturn k.supplyKeeper.MintCoins(ctx, types.ModuleName, newCoins)\n}", "func (u UTXOSet) FindUnspentTransactionOutputs(pubKeyHash []byte) []TxOutput {\n\tvar UTXOs []TxOutput\n\n\tdb := u.BlockChain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through all transactions with UTXOs\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\titem := it.Item()\n\t\t\tv, err := item.Value()\n\t\t\tHandle(err)\n\t\t\touts := DeserializeOutputs(v)\n\t\t\t// go through all outputs of that transaction\n\t\t\tfor _, out := range outs.Outputs {\n\t\t\t\t// check the output was locked with this address (belongs to this receiver and can be unlocked by this address to use as new input)\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tHandle(err)\n\treturn UTXOs\n}", "func (_TokensNetwork *TokensNetworkCaller) QueryUnlockedLocks(opts *bind.CallOpts, token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _TokensNetwork.contract.Call(opts, out, \"queryUnlockedLocks\", token, participant, partner, lockhash)\n\treturn *ret0, err\n}", "func (rt *recvTxOut) SetLocked(locked bool) {\n\trt.locked = locked\n}", "func (rt *recvTxOut) Locked() bool {\n\treturn rt.locked\n}", "func (_TokensNetwork *TokensNetworkCallerSession) QueryUnlockedLocks(token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\treturn _TokensNetwork.Contract.QueryUnlockedLocks(&_TokensNetwork.CallOpts, token, participant, partner, lockhash)\n}", "func (tp *TXPool) GetUnverifiedTxs(txs []*types.Transaction,\n\theight uint32) *CheckBlkResult {\n\ttp.Lock()\n\tdefer tp.Unlock()\n\tres := &CheckBlkResult{\n\t\tVerifiedTxs: make([]*VerifyTxResult, 0, len(txs)),\n\t\tUnverifiedTxs: make([]*types.Transaction, 0),\n\t\tOldTxs: make([]*types.Transaction, 0),\n\t}\n\tfor _, tx := range txs {\n\t\ttxEntry := tp.txList[tx.Hash()]\n\t\tif txEntry == nil {\n\t\t\tres.UnverifiedTxs = append(res.UnverifiedTxs,\n\t\t\t\ttx)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !tp.compareTxHeight(txEntry, height) {\n\t\t\tdelete(tp.txList, tx.Hash())\n\t\t\tres.OldTxs = append(res.OldTxs, txEntry.Tx)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, v := range txEntry.Attrs {\n\t\t\tif v.Type == vt.Stateful {\n\t\t\t\tentry := &VerifyTxResult{\n\t\t\t\t\tTx: tx,\n\t\t\t\t\tHeight: v.Height,\n\t\t\t\t\tErrCode: v.ErrCode,\n\t\t\t\t}\n\t\t\t\tres.VerifiedTxs = append(res.VerifiedTxs,\n\t\t\t\t\tentry)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res\n}", "func (_TokensNetwork *TokensNetworkSession) QueryUnlockedLocks(token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\treturn _TokensNetwork.Contract.QueryUnlockedLocks(&_TokensNetwork.CallOpts, token, participant, partner, lockhash)\n}", "func (tb *transactionBuilder) FundCoins(amount types.Currency, refundAddress *types.UnlockHash, reuseRefundAddress bool) error {\n\ttb.wallet.mu.Lock()\n\tdefer tb.wallet.mu.Unlock()\n\n\tif !tb.wallet.unlocked {\n\t\treturn modules.ErrLockedWallet\n\t}\n\n\t// prepare fulfillable context\n\tctx := tb.wallet.getFulfillableContextForLatestBlock()\n\n\t// Collect a value-sorted set of fulfillable coin outputs.\n\tvar so sortedOutputs\n\tfor scoid, sco := range tb.wallet.coinOutputs {\n\t\tif !sco.Condition.Fulfillable(ctx) {\n\t\t\tcontinue\n\t\t}\n\t\tso.ids = append(so.ids, scoid)\n\t\tso.outputs = append(so.outputs, sco)\n\t}\n\t// Add all of the unconfirmed outputs as well.\n\tfor _, upt := range tb.wallet.unconfirmedProcessedTransactions {\n\t\tfor i, sco := range upt.Transaction.CoinOutputs {\n\t\t\tuh := sco.Condition.UnlockHash()\n\t\t\t// Determine if the output belongs to the wallet.\n\t\t\texists, err := tb.wallet.keyExists(uh)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !exists || !sco.Condition.Fulfillable(ctx) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tso.ids = append(so.ids, upt.Transaction.CoinOutputID(uint64(i)))\n\t\t\tso.outputs = append(so.outputs, sco)\n\t\t}\n\t}\n\tsort.Sort(sort.Reverse(so))\n\n\t// Create a transaction that will add the correct amount of coins to the\n\t// transaction.\n\tvar fund types.Currency\n\t// potentialFund tracks the balance of the wallet including outputs that\n\t// have been spent in other unconfirmed transactions recently. This is to\n\t// provide the user with a more useful error message in the event that they\n\t// are overspending.\n\tvar potentialFund types.Currency\n\tvar spentScoids []types.CoinOutputID\n\tfor i := range so.ids {\n\t\tscoid := so.ids[i]\n\t\tsco := so.outputs[i]\n\t\t// Check that this output has not recently been spent by the wallet.\n\t\tspendHeight := tb.wallet.spentOutputs[types.OutputID(scoid)]\n\t\t// Prevent an underflow error.\n\t\tallowedHeight := tb.wallet.consensusSetHeight - RespendTimeout\n\t\tif tb.wallet.consensusSetHeight < RespendTimeout {\n\t\t\tallowedHeight = 0\n\t\t}\n\t\tif spendHeight > allowedHeight {\n\t\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\t\tcontinue\n\t\t}\n\n\t\t// prepare fulfillment, matching the output\n\t\tuh := sco.Condition.UnlockHash()\n\t\tvar ff types.MarshalableUnlockFulfillment\n\t\tswitch sco.Condition.ConditionType() {\n\t\tcase types.ConditionTypeUnlockHash, types.ConditionTypeTimeLock:\n\t\t\t// ConditionTypeTimeLock is fine, as we know it's fulfillable,\n\t\t\t// and that can only mean for now that it is using an internal unlockHashCondition or nilCondition\n\t\t\tpk, _, err := tb.wallet.getKey(uh)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tff = types.NewSingleSignatureFulfillment(pk)\n\t\tdefault:\n\t\t\tbuild.Severe(fmt.Errorf(\"unexpected condition type: %[1]v (%[1]T)\", sco.Condition))\n\t\t\treturn types.ErrUnexpectedUnlockCondition\n\t\t}\n\t\t// Add a coin input for this output.\n\t\tsci := types.CoinInput{\n\t\t\tParentID: scoid,\n\t\t\tFulfillment: types.NewFulfillment(ff),\n\t\t}\n\t\ttb.coinInputs = append(tb.coinInputs, inputSignContext{\n\t\t\tInputIndex: len(tb.transaction.CoinInputs),\n\t\t\tUnlockHash: uh,\n\t\t})\n\t\ttb.transaction.CoinInputs = append(tb.transaction.CoinInputs, sci)\n\n\t\tspentScoids = append(spentScoids, scoid)\n\n\t\t// Add the output to the total fund\n\t\tfund = fund.Add(sco.Value)\n\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\tif fund.Cmp(amount) >= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif potentialFund.Cmp(amount) >= 0 && fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrIncompleteTransactions\n\t}\n\tif fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrLowBalance\n\t}\n\n\t// Create a refund output if needed.\n\tif !amount.Equals(fund) {\n\t\tvar refundUnlockHash types.UnlockHash\n\t\tif refundAddress != nil {\n\t\t\t// use specified refund address\n\t\t\trefundUnlockHash = *refundAddress\n\t\t} else if reuseRefundAddress {\n\t\t\t// use the fist coin input of this tx as refund address\n\t\t\tvar maxCoinAmount types.Currency\n\t\t\tfor _, ci := range tb.transaction.CoinInputs {\n\t\t\t\tco, exists := tb.wallet.coinOutputs[ci.ParentID]\n\t\t\t\tif !exists {\n\t\t\t\t\tco = tb.getCoFromUnconfirmedProcessedTransactions(ci.ParentID)\n\t\t\t\t}\n\t\t\t\tif maxCoinAmount.Cmp(co.Value) < 0 {\n\t\t\t\t\tmaxCoinAmount = co.Value\n\t\t\t\t\trefundUnlockHash = co.Condition.UnlockHash()\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// generate a new address\n\t\t\tvar err error\n\t\t\trefundUnlockHash, err = tb.wallet.nextPrimarySeedAddress()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\trefundOutput := types.CoinOutput{\n\t\t\tValue: fund.Sub(amount),\n\t\t\tCondition: types.NewCondition(types.NewUnlockHashCondition(refundUnlockHash)),\n\t\t}\n\t\ttb.transaction.CoinOutputs = append(tb.transaction.CoinOutputs, refundOutput)\n\t}\n\n\t// Mark all outputs that were spent as spent.\n\tfor _, scoid := range spentScoids {\n\t\ttb.wallet.spentOutputs[types.OutputID(scoid)] = tb.wallet.consensusSetHeight\n\t}\n\treturn nil\n}", "func (o AttachedDiskResponseOutput) Locked() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v AttachedDiskResponse) bool { return v.Locked }).(pulumi.BoolOutput)\n}", "func (b *rpcVestingBalance) unbonding() (sdk.Coins, sdk.Coins, error) {\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\tunbondingFree := sdk.MinInt(delegatedFree, unbonding)\n\tunbondingVesting := unbonding.Sub(unbondingFree)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(unbondingFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(unbondingVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (s *StakingKeeperMock) GetBondedValidatorsByPower(ctx sdk.Context) []stakingtypes.Validator {\n\treturn s.BondedValidators\n}", "func (s *Store) GetUnspentOutputs(ns walletdb.ReadBucket) ([]Credit, er.R) {\n\tvar unspent []Credit\n\terr := s.ForEachUnspentOutput(ns, nil, func(_ []byte, c *Credit) er.R {\n\t\tunspent = append(unspent, *c)\n\t\treturn nil\n\t})\n\treturn unspent, err\n}", "func (w *Wallet) GetUnspentBlockStakeOutputs() (unspent []types.UnspentBlockStakeOutput, err error) {\n\tw.mu.RLock()\n\tdefer w.mu.RUnlock()\n\n\tif !w.unlocked {\n\t\terr = modules.ErrLockedWallet\n\t\treturn\n\t}\n\n\tunspent = make([]types.UnspentBlockStakeOutput, 0)\n\n\t// prepare fulfillable context\n\tctx := w.getFulfillableContextForLatestBlock()\n\n\t// collect all fulfillable block stake outputs\n\tfor usbsoid, output := range w.blockstakeOutputs {\n\t\tif output.Condition.Fulfillable(ctx) {\n\t\t\tunspent = append(unspent, w.unspentblockstakeoutputs[usbsoid])\n\t\t}\n\t}\n\treturn\n}", "func (btc *ExchangeWallet) spendableUTXOs(confs uint32) ([]*compositeUTXO, map[string]*compositeUTXO, uint64, error) {\n\tunspents, err := btc.wallet.ListUnspent()\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\tsort.Slice(unspents, func(i, j int) bool { return unspents[i].Amount < unspents[j].Amount })\n\tvar sum uint64\n\tutxos := make([]*compositeUTXO, 0, len(unspents))\n\tutxoMap := make(map[string]*compositeUTXO, len(unspents))\n\tfor _, txout := range unspents {\n\t\tif txout.Confirmations >= confs && txout.Safe {\n\t\t\tnfo, err := dexbtc.InputInfo(txout.ScriptPubKey, txout.RedeemScript, btc.chainParams)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error reading asset info: %v\", err)\n\t\t\t}\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error decoding txid in ListUnspentResult: %v\", err)\n\t\t\t}\n\t\t\tutxo := &compositeUTXO{\n\t\t\t\ttxHash: txHash,\n\t\t\t\tvout: txout.Vout,\n\t\t\t\taddress: txout.Address,\n\t\t\t\tredeemScript: txout.RedeemScript,\n\t\t\t\tamount: toSatoshi(txout.Amount),\n\t\t\t\tinput: nfo,\n\t\t\t}\n\t\t\tutxos = append(utxos, utxo)\n\t\t\tutxoMap[outpointID(txout.TxID, txout.Vout)] = utxo\n\t\t\tsum += toSatoshi(txout.Amount)\n\t\t}\n\t}\n\treturn utxos, utxoMap, sum, nil\n}", "func newCoins() sdk.Coins {\n\treturn sdk.Coins{\n\t\tsdk.NewInt64Coin(\"atom\", 10000000),\n\t}\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.wallet.Unspents(dcr.ctx, dcr.primaryAcct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif dcr.tradingAccount != \"\" {\n\t\t// Trading account may contain spendable utxos such as unspent split tx\n\t\t// outputs that are unlocked/returned. TODO: Care should probably be\n\t\t// taken to ensure only unspent split tx outputs are selected and other\n\t\t// unmixed outputs in the trading account are ignored.\n\t\ttradingAcctSpendables, err := dcr.wallet.Unspents(dcr.ctx, dcr.tradingAccount)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tunspents = append(unspents, tradingAcctSpendables...)\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in account %q\", dcr.primaryAcct)\n\t}\n\n\t// Parse utxos to include script size for spending input. Returned utxos\n\t// will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func (m *Machine) ReturnCoins() {\n\tcoins := m.cashEngine.DropCoins()\n\n\ts := fmt.Sprintf(\"-> \")\n\tfor i, c := range coins {\n\t\tif i == len(coins)-1 {\n\t\t\ts += fmt.Sprintf(\"%s\", c.value.String())\n\t\t\tcontinue\n\t\t}\n\t\ts += fmt.Sprintf(\"%s, \", c.value.String())\n\t}\n\n\tm.logger.Println(s)\n}", "func (_DelegationController *DelegationControllerCaller) GetLockedInPendingDelegations(opts *bind.CallOpts, holder common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"getLockedInPendingDelegations\", holder)\n\treturn *ret0, err\n}" ]
[ "0.75121504", "0.74375194", "0.74270487", "0.7414589", "0.68385124", "0.6392496", "0.61917114", "0.6113071", "0.58873636", "0.58075583", "0.56814134", "0.56528914", "0.56135285", "0.5559344", "0.5548731", "0.54984355", "0.5480376", "0.54703814", "0.5414903", "0.5400289", "0.53920466", "0.53802407", "0.53664374", "0.53305", "0.52817136", "0.52767944", "0.52671874", "0.52554864", "0.5251496", "0.5227145", "0.52001727", "0.5187744", "0.5175647", "0.51450557", "0.514315", "0.5106849", "0.5097466", "0.50882727", "0.50755197", "0.5049093", "0.50267446", "0.4995233", "0.4961594", "0.49306652", "0.48910666", "0.48800844", "0.4870848", "0.4868697", "0.48480183", "0.4836659", "0.48171586", "0.48117325", "0.480943", "0.4802143", "0.47945446", "0.47932136", "0.47904304", "0.47546884", "0.47405586", "0.47136912", "0.471216", "0.46996582", "0.46983907", "0.46972474", "0.46938106", "0.4689896", "0.46788356", "0.46745017", "0.46591777", "0.4659012", "0.46546215", "0.46400502", "0.4612143", "0.45871246", "0.45714107", "0.45661086", "0.45525652", "0.45499128", "0.4538669", "0.45252737", "0.45235956", "0.45210218", "0.4514166", "0.4504932", "0.4503111", "0.44923684", "0.44883734", "0.44835222", "0.44804823", "0.44681153", "0.44532546", "0.44453686", "0.44362217", "0.4432046", "0.44253957", "0.44246426", "0.4424409", "0.44223616", "0.44217584", "0.441431" ]
0.73147166
4
TrackDelegation tracks a desired delegation amount by setting the appropriate values for the amount of delegated vesting, delegated free, and reducing the overall amount of base coins.
func (plva *PermanentLockedAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) { plva.BaseVestingAccount.TrackDelegation(balance, plva.OriginalVesting, amount) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (bva *BaseVestingAccount) TrackDelegation(balance, vestingCoins, amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\tbaseAmt := balance.AmountOf(coin.Denom)\n\t\tvestingAmt := vestingCoins.AmountOf(coin.Denom)\n\t\tdelVestingAmt := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// Panic if the delegation amount is zero or if the base coins does not\n\t\t// exceed the desired delegation amount.\n\t\tif coin.Amount.IsZero() || baseAmt.LT(coin.Amount) {\n\t\t\tpanic(\"delegation attempt with zero coins or insufficient funds\")\n\t\t}\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(max(V - DV, 0), D)\n\t\t// Y := D - X\n\t\tx := sdk.MinInt(sdk.MaxInt(vestingAmt.Sub(delVestingAmt), sdk.ZeroInt()), coin.Amount)\n\t\ty := coin.Amount.Sub(x)\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Add(xCoin)\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Add(yCoin)\n\t\t}\n\t}\n}", "func (dva *DelayedVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tdva.BaseVestingAccount.TrackDelegation(balance, dva.GetVestingCoins(blockTime), amount)\n}", "func (pva *PeriodicVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tpva.BaseVestingAccount.TrackDelegation(balance, pva.GetVestingCoins(blockTime), amount)\n}", "func (vva *ValidatorVestingAccount) TrackDelegation(blockTime time.Time, amount sdk.Coins) {\n\tvva.BaseVestingAccount.TrackDelegation(vva.GetVestingCoins(blockTime), amount)\n}", "func (cva *ContinuousVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tcva.BaseVestingAccount.TrackDelegation(balance, cva.GetVestingCoins(blockTime), amount)\n}", "func (va *ClawbackVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tva.BaseVestingAccount.TrackDelegation(balance, va.GetVestingCoins(blockTime), amount)\n}", "func (bva *BaseVestingAccount) TrackUndelegation(amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\t// panic if the undelegation amount is zero\n\t\tif coin.Amount.IsZero() {\n\t\t\tpanic(\"undelegation attempt with zero coins\")\n\t\t}\n\t\tdelegatedFree := bva.DelegatedFree.AmountOf(coin.Denom)\n\t\tdelegatedVesting := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(DF, D)\n\t\t// Y := min(DV, D - X)\n\t\tx := sdk.MinInt(delegatedFree, coin.Amount)\n\t\ty := sdk.MinInt(delegatedVesting, coin.Amount.Sub(x))\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Sub(sdk.Coins{xCoin})\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Sub(sdk.Coins{yCoin})\n\t\t}\n\t}\n}", "func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins {\n\tdelegated := bonded.Add(unbonding...)\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated))\n\ttotal := delegated.Add(unbonded...)\n\ttoClawBack = coinsMin(toClawBack, total) // might have been slashed\n\tnewDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...)\n\tva.DelegatedVesting = coinsMin(encumbered, newDelegated)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n\treturn toClawBack\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func (k Keeper) TransferDelegation(ctx sdk.Context, valAddr sdk.ValAddress, fromDelegator, toDelegator sdk.AccAddress, shares sdk.Dec) (sdk.Dec, error) {\n\t// Redelegations link a delegation to it's previous validator so slashes are propagated to the new validator.\n\t// If the delegation is transferred to a new owner, the redelegation object must be updated.\n\t// For expediency all transfers with redelegations are blocked.\n\tif k.stakingKeeper.HasReceivingRedelegation(ctx, fromDelegator, valAddr) {\n\t\treturn sdk.Dec{}, types.ErrRedelegationsNotCompleted\n\t}\n\n\tif shares.IsNil() || shares.LT(sdk.ZeroDec()) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"nil or negative shares\")\n\t}\n\tif shares.Equal(sdk.ZeroDec()) {\n\t\t// Block 0 transfers to reduce edge cases.\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"zero shares\")\n\t}\n\n\tfromDelegation, found := k.stakingKeeper.GetDelegation(ctx, fromDelegator, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoDelegatorForAddress\n\t}\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// Prevent validators from reducing their self delegation below the min.\n\tisValidatorOperator := fromDelegator.Equals(valAddr)\n\tif isValidatorOperator {\n\t\tif isBelowMinSelfDelegation(validator, fromDelegation.Shares.Sub(shares)) {\n\t\t\treturn sdk.Dec{}, types.ErrSelfDelegationBelowMinimum\n\t\t}\n\t}\n\n\treturnAmount, err := k.fastUndelegate(ctx, valAddr, fromDelegator, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\tif err := k.bankKeeper.SendCoins(ctx, fromDelegator, toDelegator, returnCoins); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treceivedShares, err := k.delegateFromAccount(ctx, valAddr, toDelegator, returnAmount)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\treturn receivedShares, nil\n}", "func (_DelegationController *DelegationControllerTransactor) Delegate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"delegate\", validatorId, amount, delegationPeriod, info)\n}", "func (_DelegationController *DelegationControllerSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (_DelegationController *DelegationControllerTransactorSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (broadcast *Broadcast) Delegate(ctx context.Context, delegator, voter, amount,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.DelegateMsg{\n\t\tDelegator: delegator,\n\t\tVoter: voter,\n\t\tAmount: amount,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (o OfflineNotaryRepository) AddDelegation(data.RoleName, []data.PublicKey, []string) error {\n\treturn nil\n}", "func Delegate(stub shim.ChaincodeStubInterface, args []string) error {\n\tvar vote entities.Vote\n\terr := json.Unmarshal([]byte(args[0]), &vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpoll, err := validateDelegate(stub, vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = addVoteToPoll(stub, poll, vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"saving delegate vote\")\n\tutil.UpdateObjectInChain(stub, vote.ID(), util.VotesIndexName, []byte(args[0]))\n\n\tfmt.Println(\"successfully delegated vote to \" + vote.Delegate + \"!\")\n\treturn nil\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (k Keeper) Delegation(ctx sdk.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) exported.DelegationI {\n\treturn nil\n}", "func (del Delegation) AmountDelegated() hexutil.Big {\n\tif del.Delegation.AmountDelegated == nil {\n\t\treturn hexutil.Big{}\n\t}\n\treturn *del.Delegation.AmountDelegated\n}", "func TestCallSimDelegate(t *testing.T) {\n\t// Roll up our sleeves and swear fealty to the witch-king\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tg, ctx := errgroup.WithContext(ctx)\n\n\tdb := dbm.NewMemDB()\n\tst, err := state.MakeGenesisState(db, genesisDoc)\n\trequire.NoError(t, err)\n\n\tfrom := crypto.PrivateKeyFromSecret(\"raaah\", crypto.CurveTypeEd25519)\n\tcontractAddress := crypto.Address{1, 2, 3, 4, 5}\n\tblockchain := &bcm.Blockchain{}\n\tsink := exec.NewNoopEventSink()\n\n\t// Function to set storage value for later\n\tsetDelegate := func(up state.Updatable, value crypto.Address) error {\n\t\tcall, _, err := abi.EncodeFunctionCall(string(solidity.Abi_DelegateProxy), \"setDelegate\", logger, value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcache := acmstate.NewCache(st)\n\t\t_, err = evm.Default().Execute(cache, blockchain, sink,\n\t\t\tengine.CallParams{\n\t\t\t\tCallType: exec.CallTypeCall,\n\t\t\t\tOrigin: from.GetAddress(),\n\t\t\t\tCaller: from.GetAddress(),\n\t\t\t\tCallee: contractAddress,\n\t\t\t\tInput: call,\n\t\t\t\tGas: big.NewInt(9999999),\n\t\t\t}, solidity.DeployedBytecode_DelegateProxy)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn cache.Sync(up)\n\t}\n\n\t// Initialise sender smart contract state\n\t_, _, err = st.Update(func(up state.Updatable) error {\n\t\terr = up.UpdateAccount(&acm.Account{\n\t\t\tAddress: from.GetAddress(),\n\t\t\tPublicKey: from.GetPublicKey(),\n\t\t\tBalance: 9999999,\n\t\t\tPermissions: permission.DefaultAccountPermissions,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn up.UpdateAccount(&acm.Account{\n\t\t\tAddress: contractAddress,\n\t\t\tEVMCode: solidity.DeployedBytecode_DelegateProxy,\n\t\t})\n\t})\n\trequire.NoError(t, err)\n\n\t// Set a series of values of storage slot so we get a deep version tree (which we need to trigger the bug)\n\tdelegate := crypto.Address{0xBE, 0xEF, 0, 0xFA, 0xCE, 0, 0xBA, 0}\n\tfor i := 0; i < 0xBF; i++ {\n\t\tdelegate[7] = byte(i)\n\t\t_, _, err = st.Update(func(up state.Updatable) error {\n\t\t\treturn setDelegate(up, delegate)\n\t\t})\n\t\trequire.NoError(t, err)\n\t}\n\n\t// This is important in order to illicit the former bug - we need a cold LRU tree cache in MutableForest\n\tst, err = state.LoadState(db, st.Version())\n\trequire.NoError(t, err)\n\n\tgetIntCall, _, err := abi.EncodeFunctionCall(string(solidity.Abi_DelegateProxy), \"getDelegate\", logger)\n\trequire.NoError(t, err)\n\tn := 1000\n\n\tfor i := 0; i < n; i++ {\n\t\tg.Go(func() error {\n\t\t\ttxe, err := CallSim(st, blockchain, from.GetAddress(), contractAddress, getIntCall, logger)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = txe.GetException().AsError()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\taddress, err := crypto.AddressFromBytes(txe.GetResult().Return[12:])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif address != delegate {\n\t\t\t\t// The bug for which this test was written will return the zero address here since it is accessing\n\t\t\t\t// an uninitialised tree\n\t\t\t\treturn fmt.Errorf(\"getDelegate returned %v but expected %v\", address, delegate)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\n\trequire.NoError(t, g.Wait())\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func (_TokensNetwork *TokensNetworkTransactor) UpdateBalanceProofDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"updateBalanceProofDelegate\", token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (k msgServer) CancelUnbondingDelegation(goCtx context.Context, msg *types.MsgCancelUnbondingDelegation) (*types.MsgCancelUnbondingDelegationResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\tvalAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\t// In some situations, the exchange rate becomes invalid, e.g. if\n\t// Validator loses all tokens due to slashing. In this case,\n\t// make all future delegations invalid.\n\tif validator.InvalidExRate() {\n\t\treturn nil, types.ErrDelegatorShareExRateInvalid\n\t}\n\n\tif validator.IsJailed() {\n\t\treturn nil, types.ErrValidatorJailed\n\t}\n\n\tubd, found := k.GetUnbondingDelegation(ctx, delegatorAddress, valAddr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"unbonding delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this undelegation was from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be incremented\n\ttokens := msg.Amount.Amount\n\tshares, err := validator.SharesFromTokens(tokens)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar (\n\t\tunbondEntry types.UnbondingDelegationEntry\n\t\tunbondEntryIndex int64 = -1\n\t)\n\n\tfor i, entry := range ubd.Entries {\n\t\tif entry.CreationHeight == msg.CreationHeight {\n\t\t\tunbondEntry = entry\n\t\t\tunbondEntryIndex = int64(i)\n\t\t\tbreak\n\t\t}\n\t}\n\tif unbondEntryIndex == -1 {\n\t\treturn nil, sdkerrors.ErrNotFound.Wrapf(\"unbonding delegation entry is not found at block height %d\", msg.CreationHeight)\n\t}\n\n\tif unbondEntry.Balance.LT(msg.Amount.Amount) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"amount is greater than the unbonding delegation entry balance\")\n\t}\n\n\tif unbondEntry.CompletionTime.Before(ctx.BlockTime()) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"unbonding delegation is already processed\")\n\t}\n\n\t// delegate back the unbonding delegation amount to the validator\n\t_, err = k.Keeper.Delegate(ctx, delegatorAddress, msg.Amount.Amount, types.Unbonding, validator, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tamount := unbondEntry.Balance.Sub(msg.Amount.Amount)\n\tif amount.IsZero() {\n\t\tubd.RemoveEntry(unbondEntryIndex)\n\t} else {\n\t\t// update the unbondingDelegationEntryBalance and InitialBalance for ubd entry\n\t\tunbondEntry.Balance = amount\n\t\tunbondEntry.InitialBalance = unbondEntry.InitialBalance.Sub(msg.Amount.Amount)\n\t\tubd.Entries[unbondEntryIndex] = unbondEntry\n\t}\n\n\t// set the unbonding delegation or remove it if there are no more entries\n\tif len(ubd.Entries) == 0 {\n\t\tk.RemoveUnbondingDelegation(ctx, ubd)\n\t} else {\n\t\tk.SetUnbondingDelegation(ctx, ubd)\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeCancelUnbondingDelegation,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCreationHeight, strconv.FormatInt(msg.CreationHeight, 10)),\n\t\t),\n\t)\n\n\treturn &types.MsgCancelUnbondingDelegationResponse{}, nil\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func (us *DelegationService) AddDelegation(delegation *models.Delegation) (*models.Delegation, error) {\n\t// TODO(tho) add CSR validation against template\n\treturn us.storeInterface.AddDelegation(delegation)\n}", "func (_TokensNetwork *TokensNetworkSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func NewDelegation(d *types.Delegation) *Delegation {\n\treturn &Delegation{Delegation: *d, cg: new(singleflight.Group)}\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (k Keeper) Delegation(ctx context.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) (types.DelegationI, error) {\n\tbond, err := k.Delegations.Get(ctx, collections.Join(addrDel, addrVal))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bond, nil\n}", "func (_TokensNetwork *TokensNetworkTransactor) UnlockDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"unlockDelegate\", token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func TestDelegatorProxyValidatorConstraints4Steps(t *testing.T) {\n\tcommon.InitConfig()\n\tparams := DefaultParams()\n\n\toriginVaSet := addrVals[1:]\n\tparams.MaxValidators = uint16(len(originVaSet))\n\tparams.Epoch = 2\n\tparams.UnbondingTime = time.Millisecond * 300\n\tstartUpValidator := NewValidator(StartUpValidatorAddr, StartUpValidatorPubkey, Description{}, types.DefaultMinSelfDelegation)\n\tstartUpStatus := baseValidatorStatus{startUpValidator}\n\torgValsLen := len(originVaSet)\n\tfullVaSet := make([]sdk.ValAddress, orgValsLen+1)\n\tcopy(fullVaSet, originVaSet)\n\tcopy(fullVaSet[orgValsLen:], []sdk.ValAddress{startUpStatus.getValidator().GetOperator()})\n\n\tbAction := baseAction{}\n\n\tstep1Actions := IActions{\n\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, true},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ProxiedDelegator}},\n\t\tdelegatorWithdrawAction{bAction, ProxiedDelegator, sdk.OneDec(), sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ProxiedDelegator, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ProxiedDelegator},\n\t}\n\n\tstep2Actions := IActions{\n\t\tdelegatorDepositAction{bAction, ValidDelegator1, DelegatedToken1, sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ValidDelegator1, ProxiedDelegator},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ValidDelegator1}},\n\t\tproxyUnBindAction{bAction, ValidDelegator1},\n\t\tdelegatorWithdrawAction{bAction, ValidDelegator1, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tstep3Actions := IActions{\n\t\tdelegatorDepositAction{bAction, ValidDelegator1, DelegatedToken1, sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ValidDelegator1, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ValidDelegator1},\n\t\tdelegatorWithdrawAction{bAction, ValidDelegator1, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tstep4Actions := IActions{\n\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, true},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ProxiedDelegator}},\n\t\tproxyBindAction{bAction, ProxiedDelegator, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ProxiedDelegator},\n\t\tdelegatorWithdrawAction{bAction, ProxiedDelegator, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tfor s1 := 0; s1 < len(step1Actions); s1++ {\n\t\tfor s2 := 0; s2 < len(step2Actions); s2++ {\n\t\t\tfor s3 := 0; s3 < len(step3Actions); s3++ {\n\t\t\t\tfor s4 := 0; s4 < len(step4Actions); s4++ {\n\t\t\t\t\tinputActions := []IAction{\n\t\t\t\t\t\tcreateValidatorAction{bAction, nil},\n\t\t\t\t\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ValidDelegator2}},\n\t\t\t\t\t\tdelegatorDepositAction{bAction, ProxiedDelegator, MaxDelegatedToken, sdk.DefaultBondDenom},\n\t\t\t\t\t\tstep1Actions[s1],\n\t\t\t\t\t\tstep2Actions[s2],\n\t\t\t\t\t\tstep3Actions[s3],\n\t\t\t\t\t\tstep4Actions[s4],\n\t\t\t\t\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, false},\n\t\t\t\t\t\tdestroyValidatorAction{bAction},\n\t\t\t\t\t}\n\n\t\t\t\t\tactionsAndChecker, caseName := generateActionsAndCheckers(inputActions, 3)\n\n\t\t\t\t\tt.Logf(\"============================================== indexes:[%d,%d,%d,%d] %s ==============================================\", s1, s2, s3, s4, caseName)\n\t\t\t\t\t_, _, mk := CreateTestInput(t, false, SufficientInitPower)\n\t\t\t\t\tsmTestCase := newValidatorSMTestCase(mk, params, startUpStatus, inputActions, actionsAndChecker, t)\n\t\t\t\t\tsmTestCase.SetupValidatorSetAndDelegatorSet(int(params.MaxValidators))\n\t\t\t\t\tsmTestCase.printParticipantSnapshot(t)\n\t\t\t\t\tsmTestCase.Run(t)\n\t\t\t\t\tt.Log(\"============================================================================================\")\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n}", "func (k Keeper) fastUndelegate(ctx sdk.Context, valAddr sdk.ValAddress, delegator sdk.AccAddress, shares sdk.Dec) (sdkmath.Int, error) {\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdkmath.Int{}, types.ErrNoDelegatorForAddress\n\t}\n\n\treturnAmount, err := k.stakingKeeper.Unbond(ctx, delegator, valAddr, shares)\n\tif err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\t// transfer the validator tokens to the not bonded pool\n\tif validator.IsBonded() {\n\t\tif err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, returnCoins); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tif err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, stakingtypes.NotBondedPoolName, delegator, returnCoins); err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturn returnAmount, nil\n}", "func (pva *PeriodicVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, pva.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, pva.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := pva.DelegatedVesting.Add(pva.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV+DF by capping slashed at the current unvested amount\n\tunvested := pva.GetVestingCoins(ctx.BlockTime())\n\tnewSlashed := coinsMin(unvested, slashed)\n\tnewTotalDelegated := delegated.Add(newSlashed...)\n\n\t// modify vesting schedule for the new grant\n\tnewStart, newEnd, newPeriods := DisjunctPeriods(pva.StartTime, grantStartTime,\n\t\tpva.GetVestingPeriods(), grantVestingPeriods)\n\tpva.StartTime = newStart\n\tpva.EndTime = newEnd\n\tpva.VestingPeriods = newPeriods\n\tpva.OriginalVesting = pva.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newTotalDelegated\n\tunvested2 := pva.GetVestingCoins(ctx.BlockTime())\n\tpva.DelegatedVesting = coinsMin(newTotalDelegated, unvested2)\n\tpva.DelegatedFree = newTotalDelegated.Sub(pva.DelegatedVesting)\n}", "func (k msgServer) Undelegate(goCtx context.Context, msg *types.MsgUndelegate) (*types.MsgUndelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\taddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttokens := msg.Amount.Amount\n\tshares, err := k.ValidateUnbondAmount(\n\t\tctx, delegatorAddress, addr, tokens,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, addr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegation, found := k.GetDelegation(ctx, delegatorAddress, addr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this is a validator self-bond, the new liquid delegation cannot fall below the self-bond * bond factor\n\tif delegation.ValidatorBond {\n\t\tif err := k.SafelyDecreaseValidatorBond(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be decremented\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.DecreaseTotalLiquidStakedTokens(ctx, tokens); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.DecreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tcompletionTime, err := k.Keeper.Undelegate(ctx, delegatorAddress, addr, shares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"undelegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeUnbond,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),\n\t\t),\n\t})\n\n\treturn &types.MsgUndelegateResponse{\n\t\tCompletionTime: completionTime,\n\t}, nil\n}", "func (p *Ledger) RecordPayment(destination types.NodeAddress, amount int64, confirmed chan bool) {\n\tok := <-confirmed\n\tif ok {\n\t\tp.l.Lock()\n\t\tp.incoming_debt[p.id] -= amount\n\t\tp.outgoing_debt[destination] -= amount\n\t\tp.l.Unlock()\n\t}\n}", "func (a *account) managedTrackDeposit(amount types.Currency) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\ta.pendingDeposits = a.pendingDeposits.Add(amount)\n}", "func NewDelegation(d *types.Delegation, repo repository.Repository) *Delegation {\n\treturn &Delegation{\n\t\tDelegation: *d,\n\t\trepo: repo,\n\t}\n}", "func (p *Protocol) NumDelegates() uint64 {\n\treturn p.numDelegates\n}", "func (rs *rootResolver) Delegation(args *struct {\n\tAddress common.Address\n\tStaker hexutil.Big\n}) (*Delegation, error) {\n\t// get the delegator detail from backend\n\td, err := repository.R().Delegation(&args.Address, &args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDelegation(d), nil\n}", "func (o OfflineNotaryRepository) AddDelegationPaths(data.RoleName, []string) error {\n\treturn nil\n}", "func (_TokensNetwork *TokensNetworkSession) UnlockDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UnlockDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (tracker *PeerTracker) Track(ci *types.ChainInfo) {\n\ttracker.mu.Lock()\n\tdefer tracker.mu.Unlock()\n\n\t_, tracking := tracker.peers[ci.Peer]\n\t_, trusted := tracker.trusted[ci.Peer]\n\ttracker.peers[ci.Peer] = ci\n\tlogPeerTracker.Infof(\"Tracking %s, new=%t, count=%d trusted=%t\", ci, !tracking, len(tracker.peers), trusted)\n}", "func TestSlashWithRedelegation(t *testing.T) {\n\tapp, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)\n\tconsAddr := sdk.ConsAddress(PKs[0].Address())\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\tbondDenom := app.StakingKeeper.BondDenom(ctx)\n\n\t// set a redelegation\n\trdTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 6)\n\trd := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11,\n\t\ttime.Unix(0, 0), rdTokens, rdTokens.ToDec())\n\tapp.StakingKeeper.SetRedelegation(ctx, rd)\n\n\t// set the associated delegation\n\tdel := types.NewDelegation(addrDels[0], addrVals[1], rdTokens.ToDec())\n\tapp.StakingKeeper.SetDelegation(ctx, del)\n\n\t// update bonded tokens\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)\n\trdCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, rdTokens.MulRaw(2)))\n\n\trequire.NoError(t, simapp.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), rdCoins))\n\n\tapp.AccountKeeper.SetModuleAccount(ctx, bondedPool)\n\n\toldBonded := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\toldNotBonded := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\n\t// slash validator\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction) })\n\tburnAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(fraction).TruncateInt()\n\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\t// burn bonded tokens from only from delegations\n\tbondedPoolBalance := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\t// power decreased by 2 - 4 stake originally bonded at the time of infraction\n\t// was still bonded at the time of discovery and was slashed by half, 4 stake\n\t// bonded at the time of discovery hadn't been bonded at the time of infraction\n\t// and wasn't slashed\n\trequire.Equal(t, int64(8), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash the validator again\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\tburnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 7)\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\t// seven bonded tokens burned\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\t// power decreased by 4\n\trequire.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash the validator again, by 100%\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\n\tburnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(sdk.OneDec()).TruncateInt()\n\tburnAmount = burnAmount.Sub(sdk.OneDec().MulInt(rdTokens).TruncateInt())\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// apply TM updates\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)\n\t// read updated validator\n\t// validator decreased to zero power, should be in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n\n\t// slash the validator again, by 100%\n\t// no stake remains to be slashed\n\tctx = ctx.WithBlockHeight(12)\n\t// validator still in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded, bondedPoolBalance))\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\t// power still zero, still in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n}", "func (m *MetricsProvider) SignerAddLinkedDataProof(value time.Duration) {\n}", "func (*CardanoSignTransactionRequest_Certificate_StakeDelegation) Descriptor() ([]byte, []int) {\n\treturn file_cardano_proto_rawDescGZIP(), []int{4, 3, 0}\n}", "func (_Bep20 *Bep20Transactor) DelegateBySig(opts *bind.TransactOpts, delegatee common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Bep20.contract.Transact(opts, \"delegateBySig\", delegatee, nonce, expiry, v, r, s)\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UnlockDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UnlockDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV + DF by capping slashed at the current unvested amount\n\tunvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime()))\n\tnewSlashed := coinsMin(slashed, unvested)\n\tnewDelegated := delegated.Add(newSlashed...)\n\n\t// modify schedules for the new grant\n\tnewLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods)\n\tnewVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime,\n\t\tva.GetVestingPeriods(), grantVestingPeriods)\n\tif newLockupStart != newVestingStart {\n\t\tpanic(\"bad start time calculation\")\n\t}\n\tva.StartTime = newLockupStart\n\tva.EndTime = max64(newLockupEnd, newVestingEnd)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\tva.OriginalVesting = va.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newDelegated\n\tunvested2 := va.GetVestingCoins(ctx.BlockTime())\n\tva.DelegatedVesting = coinsMin(newDelegated, unvested2)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n}", "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func (a *account) managedTrackWithdrawal(amount types.Currency) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\ta.pendingWithdrawals = a.pendingWithdrawals.Add(amount)\n}", "func (_OwnerProxyRegistry *OwnerProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _OwnerProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_OwnerProxyRegistry *OwnerProxyRegistryTransactor) AddDelegate(opts *bind.TransactOpts, from common.Address) (*types.Transaction, error) {\n\treturn _OwnerProxyRegistry.contract.Transact(opts, \"addDelegate\", from)\n}", "func TestSlashWithUnbondingDelegation(t *testing.T) {\n\tapp, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)\n\n\tconsAddr := sdk.ConsAddress(PKs[0].Address())\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\n\t// set an unbonding delegation with expiration timestamp beyond which the\n\t// unbonding delegation shouldn't be slashed\n\tubdTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 4)\n\tubd := types.NewUnbondingDelegation(addrDels[0], addrVals[0], 11, time.Unix(0, 0), ubdTokens)\n\tapp.StakingKeeper.SetUnbondingDelegation(ctx, ubd)\n\n\t// slash validator for the first time\n\tctx = ctx.WithBlockHeight(12)\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\toldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\n\tvalidator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction)\n\n\t// end block\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)\n\n\t// read updating unbonding delegation\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance decreased\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 2), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned\n\tnewBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 3), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 - 6 stake originally bonded at the time of infraction\n\t// was still bonded at the time of discovery and was slashed by half, 4 stake\n\t// bonded at the time of discovery hadn't been bonded at the time of infraction\n\t// and wasn't slashed\n\trequire.Equal(t, int64(7), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance decreased again\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned again\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 6), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 again\n\trequire.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\t// all originally bonded stake has been slashed, so this will have no effect\n\t// on the unbonding delegation, but it will slash stake bonded since the infraction\n\t// this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance unchanged\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned again\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 9), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 again\n\trequire.Equal(t, int64(1), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\t// all originally bonded stake has been slashed, so this will have no effect\n\t// on the unbonding delegation, but it will slash stake bonded since the infraction\n\t// this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance unchanged\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// just 1 bonded token burned again since that's all the validator now has\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 10), diffTokens)\n\n\t// apply TM updates\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)\n\n\t// read updated validator\n\t// power decreased by 1 again, validator is out of stake\n\t// validator should be in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n}", "func (_DelegationController *DelegationControllerTransactor) AcceptPendingDelegation(opts *bind.TransactOpts, delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"acceptPendingDelegation\", delegationId)\n}", "func (rs *rootResolver) Delegation(args *struct {\n\tAddress common.Address\n\tStaker hexutil.Uint64\n}) (*Delegation, error) {\n\t// get the delegator detail from backend\n\td, err := rs.repo.Delegation(args.Address, args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDelegation(d, rs.repo), nil\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateDelegatedAmount(opts *bind.TransactOpts, holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateDelegatedAmount\", holder)\n}", "func (del Delegation) Amount() (hexutil.Big, error) {\n\t// get the base amount delegated\n\tbase, err := repository.R().DelegationAmountStaked(&del.Address, del.Delegation.ToStakerId)\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\n\t// get the sum of all pending withdrawals\n\twd, err := del.pendingWithdrawalsValue()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\tval := new(big.Int).Add(base, wd)\n\treturn (hexutil.Big)(*val), nil\n}", "func distributeDelegatorRewards(ctx contract.Context, cachedDelegations *CachedDposStorage, formerValidatorTotals map[string]loom.BigUInt, delegatorRewards map[string]*loom.BigUInt, distributedRewards *loom.BigUInt) (map[string]*loom.BigUInt, error) {\n\tnewDelegationTotals := make(map[string]*loom.BigUInt)\n\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize delegation totals with whitelist amounts\n\tfor _, candidate := range candidates {\n\t\tstatistic, _ := GetStatistic(ctx, loom.UnmarshalAddressPB(candidate.Address))\n\n\t\tif statistic != nil && statistic.WhitelistAmount != nil && !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\tvalidatorKey := loom.UnmarshalAddressPB(statistic.Address).String()\n\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\tnewDelegationTotals[validatorKey] = &amount\n\t\t}\n\t}\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar currentDelegations = make(DelegationList, len(delegations))\n\tcopy(currentDelegations, delegations)\n\tfor _, d := range currentDelegations {\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalidatorKey := loom.UnmarshalAddressPB(delegation.Validator).String()\n\n\t\t// Do not distribute rewards to delegators of the Limbo validator\n\t\t// NOTE: because all delegations are sorted in reverse index order, the\n\t\t// 0-index delegation (for rewards) is handled last. Therefore, all\n\t\t// increases to reward delegations will be reflected in newDelegation\n\t\t// totals that are computed at the end of this for loop. (We do this to\n\t\t// avoid looping over all delegations twice)\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\t// allocating validator distributions to delegators\n\t\t\t// based on former validator delegation totals\n\t\t\tdelegationTotal := formerValidatorTotals[validatorKey]\n\t\t\trewardsTotal := delegatorRewards[validatorKey]\n\t\t\tif rewardsTotal != nil {\n\t\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\t\tdelegatorDistribution := calculateShare(weightedDelegation, delegationTotal, *rewardsTotal)\n\t\t\t\t// increase a delegator's distribution\n\t\t\t\tdistributedRewards.Add(distributedRewards, &delegatorDistribution)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, delegation.Validator, delegation.Delegator, delegatorDistribution)\n\n\t\t\t\t// If the reward delegation is updated by the\n\t\t\t\t// IncreaseRewardDelegation command, we must be sure to use this\n\t\t\t\t// updated version in the rest of the loop. No other delegations\n\t\t\t\t// (non-rewards) have the possibility of being updated outside\n\t\t\t\t// of this loop.\n\t\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) && d.Index == REWARD_DELEGATION_INDEX {\n\t\t\t\t\tdelegation, err = GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\tif err == contract.ErrNotFound {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdatedAmount := common.BigZero()\n\t\tif delegation.State == BONDING {\n\t\t\tupdatedAmount.Add(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t} else if delegation.State == UNBONDING {\n\t\t\tupdatedAmount.Sub(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t\tcoin, err := loadCoin(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\terr = coin.Transfer(loom.UnmarshalAddressPB(delegation.Delegator), &delegation.UpdateAmount.Value)\n\t\t\tif err != nil {\n\t\t\t\ttransferFromErr := fmt.Sprintf(\"Failed coin Transfer - distributeDelegatorRewards, %v, %s\", delegation.Delegator.String(), delegation.UpdateAmount.Value.String())\n\t\t\t\treturn nil, logDposError(ctx, err, transferFromErr)\n\t\t\t}\n\t\t} else if delegation.State == REDELEGATING {\n\t\t\tif err = cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Validator = delegation.UpdateValidator\n\t\t\tdelegation.Amount = delegation.UpdateAmount\n\t\t\tdelegation.LocktimeTier = delegation.UpdateLocktimeTier\n\n\t\t\tindex, err := GetNextDelegationIndex(ctx, *delegation.Validator, *delegation.Delegator)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Index = index\n\n\t\t\tvalidatorKey = loom.UnmarshalAddressPB(delegation.Validator).String()\n\t\t}\n\n\t\t// Delete any delegation whose full amount has been unbonded. In all\n\t\t// other cases, update the delegation state to BONDED and reset its\n\t\t// UpdateAmount\n\t\tif common.IsZero(delegation.Amount.Value) && delegation.State == UNBONDING {\n\t\t\tif err := cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\t// After a delegation update, zero out UpdateAmount\n\t\t\tdelegation.UpdateAmount = loom.BigZeroPB()\n\t\t\tdelegation.State = BONDED\n\n\t\t\tresetDelegationIfExpired(ctx, delegation)\n\t\t\tif err := cachedDelegations.SetDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Calculate delegation totals for all validators except the Limbo\n\t\t// validator\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\tnewTotal := common.BigZero()\n\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\tnewTotal.Add(newTotal, &weightedDelegation)\n\t\t\tif newDelegationTotals[validatorKey] != nil {\n\t\t\t\tnewTotal.Add(newTotal, newDelegationTotals[validatorKey])\n\t\t\t}\n\t\t\tnewDelegationTotals[validatorKey] = newTotal\n\t\t}\n\t}\n\n\treturn newDelegationTotals, nil\n}", "func (a *Account) Track() {\n\t// Request notifications for transactions sending to all wallet\n\t// addresses.\n\taddrs := a.ActiveAddresses()\n\taddrstrs := make([]string, len(addrs))\n\ti := 0\n\tfor addr := range addrs {\n\t\taddrstrs[i] = addr.EncodeAddress()\n\t\ti++\n\t}\n\n\terr := NotifyNewTXs(CurrentServerConn(), addrstrs)\n\tif err != nil {\n\t\tlog.Error(\"Unable to request transaction updates for address.\")\n\t}\n\n\tfor _, txout := range a.TxStore.UnspentOutputs() {\n\t\tReqSpentUtxoNtfn(txout)\n\t}\n}", "func (m *mParcelMockDelegationToken) Set(f func() (r insolar.DelegationToken)) *ParcelMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.DelegationTokenFunc = f\n\treturn m.mock\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func (n *Node) BecomeDelegator(genesisAmount uint64, seedAmount uint64, delegatorAmount uint64, txFee uint64, stakerNodeID string) *Node {\n\n\t// exports AVAX from the X Chain\n\texportTxID, err := n.client.XChainAPI().ExportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tseedAmount+txFee,\n\t\tn.PAddress,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to export AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the XChain\n\terr = chainhelper.XChain().AwaitTransactionAcceptance(n.client, exportTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// imports the amount to the P Chain\n\timportTxID, err := n.client.PChainAPI().ImportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tconstants.XChainID.String(),\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed import AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the PChain\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, importTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// verify the PChain balance (seedAmount+txFee-txFee)\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, seedAmount)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance of seedAmount exists in the PChain\"))\n\t\treturn n\n\t}\n\n\t// verify the XChain balance of genesisAmount - seedAmount - txFee - txFee (import PChain)\n\terr = chainhelper.XChain().CheckBalance(n.client, n.XAddress, \"AVAX\", genesisAmount-seedAmount-2*txFee)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance XChain balance of genesisAmount-seedAmount-txFee\"))\n\t\treturn n\n\t}\n\n\tdelegatorStartTime := time.Now().Add(20 * time.Second)\n\tstartTime := uint64(delegatorStartTime.Unix())\n\tendTime := uint64(delegatorStartTime.Add(36 * time.Hour).Unix())\n\taddDelegatorTxID, err := n.client.PChainAPI().AddDelegator(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tstakerNodeID,\n\t\tdelegatorAmount,\n\t\tstartTime,\n\t\tendTime,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to add delegator %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, addDelegatorTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to accept AddDelegator tx: %s\", addDelegatorTxID))\n\t\treturn n\n\t}\n\n\t// Sleep until delegator starts validating\n\ttime.Sleep(time.Until(delegatorStartTime) + 3*time.Second)\n\n\texpectedDelegatorBalance := seedAmount - delegatorAmount\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, expectedDelegatorBalance)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Unexpected P Chain Balance after adding a new delegator to the network.\"))\n\t\treturn n\n\t}\n\tlogrus.Infof(\"Added delegator to subnet and verified the expected P Chain balance.\")\n\n\treturn n\n}", "func (_DelegationController *DelegationControllerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_TransferProxyRegistry *TransferProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _TransferProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_DelegationController *DelegationControllerCallerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (a *Account) Track() {\n\trpcc, err := accessClient()\n\tif err != nil {\n\t\tlog.Errorf(\"No chain server client to track addresses.\")\n\t\treturn\n\t}\n\n\t// Request notifications for transactions sending to all wallet\n\t// addresses.\n\t//\n\t// TODO: return as slice? (doesn't have to be ordered, or\n\t// SortedActiveAddresses would be fine.)\n\taddrMap := a.KeyStore.ActiveAddresses()\n\taddrs := make([]btcutil.Address, 0, len(addrMap))\n\tfor addr := range addrMap {\n\t\taddrs = append(addrs, addr)\n\t}\n\n\tif err := rpcc.NotifyReceived(addrs); err != nil {\n\t\tlog.Error(\"Unable to request transaction updates for address.\")\n\t}\n\n\tunspent, err := a.TxStore.UnspentOutputs()\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to access unspent outputs: %v\", err)\n\t\treturn\n\t}\n\tReqSpentUtxoNtfns(unspent)\n}", "func (pm *DPoSProtocolManager) syncDelegatedNodeSafely() {\n\tif !pm.isDelegatedNode() {\n\t\t// only candidate node is able to participant to this process.\n\t\treturn;\n\t}\n\tpm.lock.Lock()\n\tdefer pm.lock.Unlock()\n\tlog.Info(\"Preparing for next big period...\");\n\t// pull the newest delegators from voting contract.\n\ta, b, err0 := VotingAccessor.Refresh()\n\tif err0 != nil {\n\t\tlog.Error(err0.Error())\n\t\treturn;\n\t}\n\tDelegatorsTable = a\n\tDelegatorNodeInfo = b\n\tif uint8(len(GigPeriodHistory)) >= BigPeriodHistorySize {\n\t\tGigPeriodHistory = GigPeriodHistory[1:] //remove the first old one.\n\t}\n\tif len(DelegatorsTable) == 0 || pm.ethManager.peers.Len() == 0 {\n\t\tlog.Info(\"Sorry, could not detect any delegator!\");\n\t\treturn;\n\t}\n\tround := uint64(1)\n\tactiveTime := uint64(time.Now().Unix() + int64(GigPeriodInterval))\n\tif NextGigPeriodInstance != nil {\n\t\tif !TestMode {\n\t\t\tgap := int64(NextGigPeriodInstance.activeTime) - time.Now().Unix()\n\t\t\tif gap > 2 || gap < -2 {\n\t\t\t\tlog.Warn(fmt.Sprintf(\"Scheduling of the new electing round is improper! current gap: %v seconds\", gap))\n\t\t\t\t//restart the scheduler\n\t\t\t\tNextElectionInfo = nil;\n\t\t\t\tgo pm.syncDelegatedNodeSafely();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tround = NextGigPeriodInstance.round + 1\n\t\tactiveTime = GigPeriodInstance.activeTime + uint64(GigPeriodInterval)\n\t\t// keep the big period history for block validation.\n\t\tGigPeriodHistory[len(GigPeriodHistory)-1] = *NextGigPeriodInstance;\n\n\t\tGigPeriodInstance = &GigPeriodTable{\n\t\t\tNextGigPeriodInstance.round,\n\t\t\tNextGigPeriodInstance.state,\n\t\t\tNextGigPeriodInstance.delegatedNodes,\n\t\t\tNextGigPeriodInstance.delegatedNodesSign,\n\t\t\tNextGigPeriodInstance.confirmedTickets,\n\t\t\tNextGigPeriodInstance.confirmedBestNode,\n\t\t\tNextGigPeriodInstance.activeTime,\n\t\t};\n\t\tlog.Info(fmt.Sprintf(\"Switched the new big period round. %d \", GigPeriodInstance.round));\n\t}\n\n\t// make sure all delegators are synced at this round.\n\tNextGigPeriodInstance = &GigPeriodTable{\n\t\tround,\n\t\tSTATE_LOOKING,\n\t\tDelegatorsTable,\n\t\tSignCandidates(DelegatorsTable),\n\t\tmake(map[string]uint32),\n\t\tmake(map[string]*GigPeriodTable),\n\t\tactiveTime,\n\t};\n\tpm.trySyncAllDelegators()\n}", "func (_DelegationController *DelegationControllerCaller) Delegations(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\tret := new(struct {\n\t\tHolder common.Address\n\t\tValidatorId *big.Int\n\t\tAmount *big.Int\n\t\tDelegationPeriod *big.Int\n\t\tCreated *big.Int\n\t\tStarted *big.Int\n\t\tFinished *big.Int\n\t\tInfo string\n\t})\n\tout := ret\n\terr := _DelegationController.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret, err\n}", "func (k Querier) Delegation(ctx context.Context, req *types.QueryDelegationRequest) (*types.QueryDelegationResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tif req.ValidatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"validator address cannot be empty\")\n\t}\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalAddr, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegation, err := k.Delegations.Get(ctx, collections.Join(sdk.AccAddress(delAddr), sdk.ValAddress(valAddr)))\n\tif err != nil {\n\t\tif errors.Is(err, collections.ErrNotFound) {\n\t\t\treturn nil, status.Errorf(\n\t\t\t\tcodes.NotFound,\n\t\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\t\treq.DelegatorAddr, req.ValidatorAddr)\n\t\t}\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tdelResponse, err := delegationToDelegationResponse(ctx, k.Keeper, delegation)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegationResponse{DelegationResponse: &delResponse}, nil\n}", "func (ac *Accumulator) WithTracking(max int) telegraf.TrackingAccumulator {\n\treturn &TrackingAccumulator{\n\t\tAccumulator: ac,\n\t\tdone: make(chan telegraf.DeliveryInfo, max),\n\t}\n}", "func (_DelegationController *DelegationControllerCaller) DelegationsByHolder(opts *bind.CallOpts, arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"delegationsByHolder\", arg0, arg1)\n\treturn *ret0, err\n}", "func (_DelegationController *DelegationControllerTransactorSession) AcceptPendingDelegation(delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.AcceptPendingDelegation(&_DelegationController.TransactOpts, delegationId)\n}", "func TestApplyChangelistCreatesDelegation(t *testing.T) {\n\trepo, cs, err := testutils.EmptyRepo(\"docker.com/notary\")\n\trequire.NoError(t, err)\n\n\tnewKey, err := cs.Create(\"targets/level1\", \"docker.com/notary\", data.ED25519Key)\n\trequire.NoError(t, err)\n\n\terr = repo.UpdateDelegationKeys(\"targets/level1\", []data.PublicKey{newKey}, []string{}, 1)\n\trequire.NoError(t, err)\n\terr = repo.UpdateDelegationPaths(\"targets/level1\", []string{\"\"}, []string{}, false)\n\trequire.NoError(t, err)\n\tdelete(repo.Targets, \"targets/level1\")\n\n\thash := sha256.Sum256([]byte{})\n\tf := &data.FileMeta{\n\t\tLength: 1,\n\t\tHashes: map[string][]byte{\n\t\t\t\"sha256\": hash[:],\n\t\t},\n\t}\n\tfjson, err := json.Marshal(f)\n\trequire.NoError(t, err)\n\n\tcl := changelist.NewMemChangelist()\n\trequire.NoError(t, cl.Add(&changelist.TUFChange{\n\t\tActn: changelist.ActionCreate,\n\t\tRole: \"targets/level1\",\n\t\tChangeType: \"target\",\n\t\tChangePath: \"latest\",\n\t\tData: fjson,\n\t}))\n\n\trequire.NoError(t, applyChangelist(repo, nil, cl))\n\t_, ok := repo.Targets[\"targets/level1\"]\n\trequire.True(t, ok, \"Failed to create the delegation target\")\n\t_, ok = repo.Targets[\"targets/level1\"].Signed.Targets[\"latest\"]\n\trequire.True(t, ok, \"Failed to write change to delegation target\")\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func (_Bep20 *Bep20Transactor) Delegate(opts *bind.TransactOpts, delegatee common.Address) (*types.Transaction, error) {\n\treturn _Bep20.contract.Transact(opts, \"delegate\", delegatee)\n}", "func (_Bep20 *Bep20Session) DelegateBySig(delegatee common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Bep20.Contract.DelegateBySig(&_Bep20.TransactOpts, delegatee, nonce, expiry, v, r, s)\n}", "func (_DelegationController *DelegationControllerSession) AcceptPendingDelegation(delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.AcceptPendingDelegation(&_DelegationController.TransactOpts, delegationId)\n}", "func UnmarshalDelegation(cdc *codec.Codec, key, value []byte) (delegation Delegation, err error) {\n\tvar storeValue delegationValue\n\terr = cdc.UnmarshalBinaryLengthPrefixed(value, &storeValue)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"%v: %v\", ErrNoDelegation(DefaultCodespace).Data(), err)\n\t\treturn\n\t}\n\n\taddrs := key[1:] // remove prefix bytes\n\tif len(addrs) != 2*sdk.AddrLen {\n\t\terr = fmt.Errorf(\"%v\", ErrBadDelegationAddr(DefaultCodespace).Data())\n\t\treturn\n\t}\n\n\tdelAddr := sdk.AccAddress(addrs[:sdk.AddrLen])\n\tvalAddr := sdk.ValAddress(addrs[sdk.AddrLen:])\n\n\treturn Delegation{\n\t\tDelegatorAddr: delAddr,\n\t\tValidatorAddr: valAddr,\n\t\tShares: storeValue.Shares,\n\t}, nil\n}", "func (_DelegationController *DelegationControllerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func SendPayments() {\n\tif !checkConfigSharingRatio() {\n\t\tlogger.Fatal(\"Unable to calculcate.\")\n\t}\n\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tvar payload core.TransactionPayload\n\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tp1, p2 := \"\", \"\"\n\tif _, err := os.Stat(\"/path/to/whatever\"); err == nil {\n\t\t// path/to/whatever exists\n\t} else {\n\t\tp1, p2 = readAccountData()\n\t}\n\n\tclearScreen()\n\n\tfor _, element := range votersEarnings {\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\n\t\t//transaction parameters\n\t\ttxAmount2Send := int64(element.EarnedAmountXX*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\t\ttx := core.CreateTransaction(element.Address, txAmount2Send, viper.GetString(\"voters.txdescription\"), p1, p2)\n\n\t\tpayload.Transactions = append(payload.Transactions, tx)\n\t}\n\n\t//Cost & reserve fund calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\n\t//summary and conversion checks\n\tif (costAmount + reserveAmount + sumShareEarned) != sumEarned {\n\t\tcolor.Set(color.FgHiRed)\n\t\tlog.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t\tlogger.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t}\n\n\tcostAmount2Send := int64(costAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\tcostAddress := viper.GetString(\"costs.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tcostAddress = viper.GetString(\"costs.Daddress\")\n\t}\n\ttxCosts := core.CreateTransaction(costAddress, costAmount2Send, viper.GetString(\"costs.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txCosts)\n\n\treserveAddress := viper.GetString(\"reserve.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\treserveAddress = viper.GetString(\"reserve.Daddress\")\n\t}\n\treserveAmount2Send := int64(reserveAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\n\ttxReserve := core.CreateTransaction(reserveAddress, reserveAmount2Send, viper.GetString(\"reserve.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txReserve)\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Transactions to be sent:\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tcolor.Set(color.FgHiCyan)\n\tfor _, el := range payload.Transactions {\n\t\ts := fmt.Sprintf(\"|%s|%15d| %-40s|\", el.RecipientID, el.Amount, el.VendorField)\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\t}\n\n\tcolor.Set(color.FgHiYellow)\n\tfmt.Println(\"\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Print(\"Send transactions and complete reward payments [Y/N]: \")\n\n\tc, _ := reader.ReadByte()\n\n\tif c == []byte(\"Y\")[0] || c == []byte(\"y\")[0] {\n\t\tfmt.Println(\"Sending rewards to voters and sharing accounts.............\")\n\n\t\tres, httpresponse, err := arkclient.PostTransaction(payload)\n\t\tif res.Success {\n\t\t\tcolor.Set(color.FgHiGreen)\n\t\t\tlogger.Println(\"Transactions sent with Success,\", httpresponse.Status, res.TransactionIDs)\n\t\t\tlog.Println(\"Transactions sent with Success,\", httpresponse.Status)\n\t\t\tlog.Println(\"Audit log of sent transactions is in file paymentLog.csv!\")\n\t\t\tlog2csv(payload, res.TransactionIDs, votersEarnings)\n\t\t} else {\n\t\t\tcolor.Set(color.FgHiRed)\n\t\t\tlogger.Println(res.Message, res.Error, httpresponse.Status, err.Error())\n\t\t\tfmt.Println()\n\t\t\tfmt.Println(\"Failed\", res.Error)\n\t\t}\n\t\treader.ReadString('\\n')\n\t\tpause()\n\t}\n}", "func (p *Protocol) NumCandidateDelegates() uint64 {\n\treturn p.numCandidateDelegates\n}", "func (_DelegationController *DelegationControllerRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.DelegationControllerTransactor.contract.Transfer(opts)\n}", "func MustMarshalDelegation(cdc *codec.Codec, delegation Delegation) []byte {\n\tval := delegationValue{\n\t\tdelegation.Shares,\n\t}\n\treturn cdc.MustMarshalBinaryLengthPrefixed(val)\n}", "func StoreDelegationFromMessage(\n\theight int64, msg *stakingtypes.MsgDelegate, stakingClient stakingtypes.QueryClient, db *database.Db,\n) error {\n\theader := client.GetHeightRequestHeader(height)\n\tres, err := stakingClient.Delegation(\n\t\tcontext.Background(),\n\t\t&stakingtypes.QueryDelegationRequest{\n\t\t\tDelegatorAddr: msg.DelegatorAddress,\n\t\t\tValidatorAddr: msg.ValidatorAddress,\n\t\t},\n\t\theader,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdelegation := ConvertDelegationResponse(height, *res.DelegationResponse)\n\treturn db.SaveDelegations([]types.Delegation{delegation})\n}", "func (_DelegationController *DelegationControllerTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.contract.Transfer(opts)\n}", "func (m *ParcelMock) DelegationTokenMinimockCounter() uint64 {\n\treturn atomic.LoadUint64(&m.DelegationTokenCounter)\n}", "func (s *ArkClient) GetDelegateVoteWeight(params DelegateQueryParams) (int, *http.Response, error) {\n\trespData := new(DelegateVoters)\n\trespError := new(ArkApiResponseError)\n\tresp, err := s.sling.New().Get(\"api/delegates/voters\").QueryStruct(&params).Receive(respData, respError)\n\tif err == nil {\n\t\terr = respError\n\t}\n\n\t//calculating vote weight\n\tbalance := 0\n\tif respData.Success {\n\t\tfor _, element := range respData.Accounts {\n\t\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\t\tbalance += intBalance\n\t\t}\n\t}\n\n\treturn balance, resp, err\n}", "func (_DelegationController *DelegationControllerTransactor) Confiscate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"confiscate\", validatorId, amount)\n}", "func (_Bep20 *Bep20TransactorSession) DelegateBySig(delegatee common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Bep20.Contract.DelegateBySig(&_Bep20.TransactOpts, delegatee, nonce, expiry, v, r, s)\n}", "func Transfer(\n\tctx *vm.Context, db vm.StateDB, sender, recipient types.AddressHash, amount *big.Int,\n) {\n\t// NOTE: amount is a re-used pointer varaible\n\tdb.SubBalance(sender, amount)\n\tdb.AddBalance(recipient, amount)\n\tif db.IsContractAddr(sender) && amount.Uint64() > 0 {\n\t\ttransferInfo := vm.NewTransferInfo(sender, recipient, amount.Uint64())\n\t\tlogger.Debugf(\"new transfer info: sender: %x, recipient: %x, amount: %d\",\n\t\t\tsender[:], recipient[:], amount)\n\t\tif v, ok := ctx.Transfers[sender]; ok {\n\t\t\t// if sender and recipient already exists in Transfers, update it instead\n\t\t\t// of append to it\n\t\t\tfor _, w := range v {\n\t\t\t\tif w.To == recipient {\n\t\t\t\t\t// NOTE: cannot miss 'w.value = '\n\t\t\t\t\tw.Value += amount.Uint64()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tctx.Transfers[sender] = append(ctx.Transfers[sender], transferInfo)\n\t}\n}", "func (o *Member) SetDelegateCur(v int32) {\n\to.DelegateCur = &v\n}", "func (_DelegationController *DelegationControllerCallerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func (vi *votedInfo) CalculateReward(multiplier, divider *big.Int, period int) {\n\tif multiplier.Sign() == 0 || period == 0 {\n\t\treturn\n\t}\n\tif divider.Sign() == 0 || vi.totalBondedDelegation.Sign() == 0 {\n\t\treturn\n\t}\n\t// reward = multiplier * period * bondedDelegation / (divider * totalBondedDelegation)\n\tbase := new(big.Int).Mul(multiplier, big.NewInt(int64(period)))\n\treward := new(big.Int)\n\tfor i, addrKey := range vi.rank {\n\t\tif i == vi.maxRankForReward {\n\t\t\tbreak\n\t\t}\n\t\tprep := vi.preps[addrKey]\n\t\tif prep.Enable() == false {\n\t\t\tcontinue\n\t\t}\n\n\t\treward.Mul(base, prep.GetBondedDelegation())\n\t\treward.Div(reward, divider)\n\t\treward.Div(reward, vi.totalBondedDelegation)\n\n\t\tlog.Tracef(\"VOTED REWARD %d = %d * %d * %d / (%d * %d)\",\n\t\t\treward, multiplier, period, prep.GetBondedDelegation(), divider, vi.totalBondedDelegation)\n\n\t\tprep.SetIScore(new(big.Int).Add(prep.IScore(), reward))\n\t}\n}", "func TestDonationCase1(t *testing.T) {\n\tassert := assert.New(t)\n\tstore := newReputationStoreOnMock()\n\trep := NewTestReputationImpl(store)\n\tt1 := time.Date(1995, time.February, 5, 11, 11, 0, 0, time.UTC)\n\tt3 := time.Date(1995, time.February, 6, 12, 11, 0, 0, time.UTC)\n\tt4 := time.Date(1995, time.February, 7, 13, 11, 1, 0, time.UTC)\n\tuser1 := \"user1\"\n\tpost1 := \"post1\"\n\tpost2 := \"post2\"\n\n\t// round 2\n\trep.Update(t1.Unix())\n\trep.DonateAt(user1, post1, big.NewInt(100*OneLinoCoin))\n\tassert.Equal(big.NewInt(100*OneLinoCoin), rep.store.GetRoundPostSumStake(2, post1))\n\tassert.Equal(rep.GetReputation(user1), big.NewInt(InitialCustomerScore))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.store.GetRoundSumDp(2)) // bounded by this user's dp\n\n\t// round 3\n\trep.Update(t3.Unix())\n\t// (1 * 9 + 100) / 10\n\tassert.Equal(big.NewInt(1090000), rep.GetReputation(user1))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.GetSumRep(post1))\n\trep.DonateAt(user1, post1, big.NewInt(1*OneLinoCoin)) // does not count\n\trep.DonateAt(user1, post2, big.NewInt(900*OneLinoCoin))\n\trep.Update(t4.Unix())\n\t// (10.9 * 9 + 900) / 10\n\tassert.Equal(big.NewInt(9981000), rep.GetReputation(user1))\n\tassert.Equal([]Pid{post2}, rep.store.GetRoundResult(3))\n\t// round 4\n}", "func (s *Streams) Delegate(data interface{}) {\n\tlisteners := s.Size()\n\n\tif listeners <= 0 {\n\t\treturn\n\t}\n\n\tif s.reverse {\n\t\ts.RevMunch(data)\n\t} else {\n\t\ts.Munch(data)\n\t}\n\n}", "func bindDelegationController(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(DelegationControllerABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func CheckPercentageSumForCycle(cycle int, delegatedContracts []DelegatedContract) float64{\n var sum float64\n sum = 0\n for x := 0; x < len(delegatedContracts); x++{\n counter := 0\n for y := 0; y < len(delegatedContracts[x].Contracts); y++{\n if (delegatedContracts[x].Contracts[y].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n\n sum = sum + delegatedContracts[x].Contracts[counter].SharePercentage\n }\n return sum\n}" ]
[ "0.8186424", "0.78992194", "0.7826971", "0.7759204", "0.7720231", "0.7715642", "0.68331814", "0.61249405", "0.57603174", "0.57438606", "0.5540563", "0.5494072", "0.5373377", "0.5255798", "0.5181217", "0.5127807", "0.5004754", "0.49716696", "0.48736444", "0.47637394", "0.47572365", "0.47441486", "0.47415286", "0.47170526", "0.47144836", "0.46762803", "0.4665858", "0.46413714", "0.46357104", "0.46282062", "0.46207032", "0.46174976", "0.45709854", "0.45557988", "0.45413628", "0.45049483", "0.4495502", "0.4473732", "0.4449344", "0.44417274", "0.44170544", "0.44156864", "0.44124243", "0.44088262", "0.43887216", "0.43861192", "0.43848553", "0.43848354", "0.43713954", "0.43558377", "0.435278", "0.43476027", "0.4344151", "0.4332731", "0.432678", "0.43134677", "0.4307876", "0.4304364", "0.42990726", "0.4283877", "0.42665523", "0.42636392", "0.42591867", "0.42550877", "0.42353064", "0.42281723", "0.42134857", "0.4212719", "0.4204074", "0.42036006", "0.41956878", "0.41940516", "0.41935286", "0.41853747", "0.41690361", "0.4162062", "0.4143749", "0.41329622", "0.41223946", "0.41171968", "0.4111449", "0.40986988", "0.40982163", "0.4095512", "0.4081912", "0.40817314", "0.40745437", "0.406955", "0.40690288", "0.40682822", "0.40601623", "0.40589195", "0.40515175", "0.4050353", "0.40455115", "0.40443146", "0.40415394", "0.40320256", "0.40303165", "0.40243965" ]
0.76592255
6
GetStartTime returns zero since a permanent locked vesting account has no start time.
func (plva PermanentLockedAccount) GetStartTime() int64 { return 0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (dva DelayedVestingAccount) GetStartTime() int64 {\n\treturn 0\n}", "func (va ClawbackVestingAccount) GetStartTime() int64 {\n\treturn va.StartTime\n}", "func (cva ContinuousVestingAccount) GetStartTime() int64 {\n\treturn cva.StartTime\n}", "func (pva PeriodicVestingAccount) GetStartTime() int64 {\n\treturn pva.StartTime\n}", "func GetStartTime() time.Time {\n\treturn startAtTime\n}", "func (this *SyncFlightInfo) GetStartTime() time.Time {\n\tthis.lock.RLock()\n\tdefer this.lock.RUnlock()\n\treturn this.startTime\n}", "func (o *UcsdBackupInfoAllOf) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (o *ApplianceSetupInfoAllOf) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (o *ApplianceClusterInstallPhase) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (req *StartWFSRequest) GetStartTime() time.Time {\n\treturn req.StartTime\n}", "func (txn TxnProbe) GetStartTime() time.Time {\n\treturn txn.startTime\n}", "func (o *OnpremUpgradePhase) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (v *Validator) StartTime() time.Time {\n\treturn time.Unix(int64(v.Start), 0)\n}", "func (mgr *Manager) StartTime() time.Time {\n\treturn mgr.startTime\n}", "func (o *WorkflowServiceItemActionInstance) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func StartTime() time.Time {\n\treturn processStartTime\n}", "func (s *Session) GetStartTime() time.Time {\n\treturn s.started\n}", "func (o *VirtualizationIweVirtualMachine) GetStartTime() string {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (c *Container) GetStartTime() time.Time {\n\treturn c.start\n}", "func (c *Context) StartTime() *time.Time {\n\treturn &c.startTime\n}", "func (s *Storage) StartTime() (int64, error) {\n\treturn int64(model.Latest), nil\n}", "func (o *Job) GetStartTime(ctx context.Context) (startTime uint64, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceJob, \"StartTime\").Store(&startTime)\n\treturn\n}", "func (m *UserExperienceAnalyticsDeviceStartupHistory) GetStartTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (b *fixedResolutionValues) StartTime() xtime.UnixNano {\n\treturn b.startTime\n}", "func (f *Filler) StartTime() time.Time {\n\treturn f.tp\n}", "func (m *BookingWorkTimeSlot) GetStart()(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly) {\n val, err := m.GetBackingStore().Get(\"start\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly)\n }\n return nil\n}", "func (o BeanstalkScheduledTaskOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BeanstalkScheduledTask) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ElastigroupScheduledTaskOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScheduledTask) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ReservedInstanceOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ReservedInstance) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (req *ServerHTTPRequest) StartTime() time.Time {\n\treturn req.startTime\n}", "func (gm GlobalManager) GetChainStartTime(ctx sdk.Context) (int64, sdk.Error) {\n\tglobalTime, err := gm.storage.GetGlobalTime(ctx)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn globalTime.ChainStartTime, nil\n}", "func (r *ScheduledAction) StartTime() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"startTime\"])\n}", "func (p *SASQueryParameters) StartTime() time.Time {\n\treturn p.startTime\n}", "func (o *KubernetesPodStatus) GetStartTime() string {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (instance *Instance) StartTime() time.Time {\n\tuptimeDuration := time.Duration(instance.Uptime) * time.Second\n\n\treturn time.Now().Add(-uptimeDuration)\n}", "func (o GoogleCloudRetailV2alphaConditionTimeRangeOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionTimeRange) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (m *ExternalActivity) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (m *RequestSchedule) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (o NodeGroupMaintenanceWindowPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *NodeGroupMaintenanceWindow) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o InstanceMaintenanceScheduleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceSchedule) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o InstanceMaintenanceScheduleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceSchedule) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (m *SimulationAutomationRun) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (o InstanceMaintenanceWindowOutput) StartTime() InstanceMaintenanceWindowStartTimeOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceWindow) InstanceMaintenanceWindowStartTime { return v.StartTime }).(InstanceMaintenanceWindowStartTimeOutput)\n}", "func (o *ModelsBackupJobStatusResponse) GetStartTime() string {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (o *ProjectDeploymentRuleResponse) GetStartTime() time.Time {\n\tif o == nil || o.StartTime.Get() == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime.Get()\n}", "func (m *MarketHoursMutation) StartTime() (r time.Time, exists bool) {\n\tv := m.start_time\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (o NodeGroupMaintenanceWindowOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v NodeGroupMaintenanceWindow) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (_LvRecording *LvRecordingCaller) StartTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _LvRecording.contract.Call(opts, &out, \"startTime\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (a *Auction) StartTime() time.Time {\n\treturn a.startTime\n}", "func (o ResourcePolicyDailyCycleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyDailyCycle) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o InstanceMaintenanceSchedulePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InstanceMaintenanceSchedule) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (n *ssvNode) getSlotStartTime(slot uint64) time.Time {\n\ttimeSinceGenesisStart := slot * uint64(n.ethNetwork.SlotDurationSec().Seconds())\n\tstart := time.Unix(int64(n.ethNetwork.MinGenesisTime()+timeSinceGenesisStart), 0)\n\treturn start\n}", "func (o ScanRunOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ScanRunOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o JobStatusPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ScanRunPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ScanRunPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o *WorkflowServiceItemActionInstance) GetStartTimeOk() (*time.Time, bool) {\n\tif o == nil || o.StartTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.StartTime, true\n}", "func (r Reservation) StartTime() string {\n\thr := r.Start / 60\n\tmin := r.Start % 60\n\tvar ampm string\n\tif ampm = \"AM\"; hr >= 12 {\n\t\tampm = \"PM\"\n\t}\n\tif hr > 12 {\n\t\thr = hr - 12\n\t}\n\tif hr == 0 {\n\t\thr = 12\n\t}\n\treturn fmt.Sprintf(\"%02d:%02d %s\", hr, min, ampm)\n}", "func (o TimelineOutput) StartTime() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *Timeline) pulumi.IntPtrOutput { return v.StartTime }).(pulumi.IntPtrOutput)\n}", "func (e *Event) StartTime() Time {\n\treturn e.start\n}", "func (c deploymentChecker) BeginTime() uint64 {\n\treturn c.deployment.StartTime\n}", "func (o KubernetesClusterMaintenanceWindowNodeOsOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterMaintenanceWindowNodeOs) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o *V0037JobProperties) GetBeginTime() int64 {\n\tif o == nil || o.BeginTime == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.BeginTime\n}", "func (o JobStatusOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o KubernetesClusterMaintenanceWindowNodeOsPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *KubernetesClusterMaintenanceWindowNodeOs) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o NodeGroupMaintenanceWindowResponsePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *NodeGroupMaintenanceWindowResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func StartTime() {\n\tstart = time.Now()\n}", "func (o *ApplianceClusterInstallPhase) GetStartTimeOk() (*time.Time, bool) {\n\tif o == nil || o.StartTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.StartTime, true\n}", "func (o ResourcePolicyDailyCyclePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyDailyCycle) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *Reminder) GetEventStartTime()(DateTimeTimeZoneable) {\n val, err := m.GetBackingStore().Get(\"eventStartTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(DateTimeTimeZoneable)\n }\n return nil\n}", "func (o InstanceMaintenanceWindowPtrOutput) StartTime() InstanceMaintenanceWindowStartTimePtrOutput {\n\treturn o.ApplyT(func(v *InstanceMaintenanceWindow) *InstanceMaintenanceWindowStartTime {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.StartTime\n\t}).(InstanceMaintenanceWindowStartTimePtrOutput)\n}", "func (o DataTransferConfigScheduleOptionsPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DataTransferConfigScheduleOptions) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *MobileAppInstallTimeSettings) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n return m.startDateTime\n}", "func (o ResourcePolicyInstanceSchedulePolicyOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyInstanceSchedulePolicy) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (f FakeContainerImpl) GetContainerStartTime(containerID string) (int64, error) {\n\tpanic(\"implement me\")\n}", "func (o InstanceMaintenancePolicyWeeklyMaintenanceWindowOutput) StartTime() InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput {\n\treturn o.ApplyT(func(v InstanceMaintenancePolicyWeeklyMaintenanceWindow) InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTime {\n\t\treturn v.StartTime\n\t}).(InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput)\n}", "func (o InstanceMaintenancePolicyWeeklyMaintenanceWindowOutput) StartTime() InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput {\n\treturn o.ApplyT(func(v InstanceMaintenancePolicyWeeklyMaintenanceWindow) InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTime {\n\t\treturn v.StartTime\n\t}).(InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput)\n}", "func (_LvRecordableStream *LvRecordableStreamCaller) StartTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _LvRecordableStream.contract.Call(opts, &out, \"startTime\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (m *GetSchedulePostRequestBody) GetStartTime()(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.DateTimeTimeZoneable) {\n return m.startTime\n}", "func (o ScanRunResponsePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRunResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ResourcePolicyHourlyCycleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyHourlyCycle) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o NodeGroupMaintenanceWindowResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v NodeGroupMaintenanceWindowResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o ResourcePolicyWeeklyCycleDayOfWeekOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyWeeklyCycleDayOfWeek) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o KubernetesClusterMaintenanceWindowAutoUpgradePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *KubernetesClusterMaintenanceWindowAutoUpgrade) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o *V0037Node) GetSlurmdStartTime() int64 {\n\tif o == nil || o.SlurmdStartTime == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.SlurmdStartTime\n}", "func (o DataTransferConfigScheduleOptionsOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DataTransferConfigScheduleOptions) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o *Run) GetStartedAt() time.Time {\n\tif o == nil || o.StartedAt == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartedAt\n}", "func (o TriggerBuildArtifactsObjectsTimingOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v TriggerBuildArtifactsObjectsTiming) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ResourcePolicyInstanceSchedulePolicyPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyInstanceSchedulePolicy) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o TriggerBuildArtifactsObjectsTimingPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TriggerBuildArtifactsObjectsTiming) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o *OnpremUpgradePhase) GetStartTimeOk() (*time.Time, bool) {\n\tif o == nil || o.StartTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.StartTime, true\n}", "func (o KubernetesClusterMaintenanceWindowAutoUpgradeOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterMaintenanceWindowAutoUpgrade) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (c *Clock) GetStart() time.Time {\n\tc.init()\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\treturn c.start\n}", "func (m *ConsensusCreateTopicTransactionBody) GetValidStartTime() *Timestamp {\n\tif m != nil {\n\t\treturn m.ValidStartTime\n\t}\n\treturn nil\n}", "func (m *ScheduleItem) GetStart()(DateTimeTimeZoneable) {\n val, err := m.GetBackingStore().Get(\"start\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(DateTimeTimeZoneable)\n }\n return nil\n}", "func (o StorageCapacityUnitOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *StorageCapacityUnit) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o *ApplianceSetupInfoAllOf) GetStartTimeOk() (*time.Time, bool) {\n\tif o == nil || o.StartTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.StartTime, true\n}", "func (o LookupJobResultOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupJobResult) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o GoogleCloudRetailV2alphaConditionTimeRangeResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionTimeRangeResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}" ]
[ "0.7989411", "0.77213776", "0.76390874", "0.7605982", "0.7384329", "0.7244314", "0.7236585", "0.7189344", "0.7175738", "0.7171928", "0.7160729", "0.7008172", "0.69832927", "0.6975663", "0.69752145", "0.695411", "0.69208306", "0.69165504", "0.6912835", "0.6835436", "0.6752777", "0.674334", "0.6660799", "0.66240734", "0.6618245", "0.6609172", "0.65879023", "0.6564642", "0.65571576", "0.6550238", "0.65228206", "0.65165055", "0.6487178", "0.6480315", "0.6458943", "0.6444386", "0.6424687", "0.64105546", "0.63850945", "0.63828355", "0.63828355", "0.6378862", "0.6359045", "0.6358781", "0.63544", "0.63504595", "0.6346177", "0.6345532", "0.6321708", "0.6295484", "0.6290065", "0.62897956", "0.62895054", "0.62895054", "0.6285061", "0.6281697", "0.6281697", "0.6267686", "0.62592524", "0.62577856", "0.62298524", "0.62197995", "0.62167805", "0.6216607", "0.6214464", "0.6212108", "0.62029207", "0.620115", "0.6198276", "0.6194738", "0.6190612", "0.61903775", "0.6179178", "0.617738", "0.61762244", "0.6167397", "0.6164916", "0.6164916", "0.6164526", "0.6154609", "0.61496806", "0.6147744", "0.61449105", "0.61411875", "0.6132521", "0.61237484", "0.61151797", "0.6104198", "0.6097349", "0.60873246", "0.60868675", "0.6074564", "0.6074094", "0.6071315", "0.60689956", "0.60677975", "0.6058576", "0.6057506", "0.60528153", "0.6050462" ]
0.82880247
0
GetEndTime returns a vesting account's end time, we return 0 to denote that a permanently locked vesting account has no end time.
func (plva PermanentLockedAccount) GetEndTime() int64 { return 0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (bva BaseVestingAccount) GetEndTime() int64 {\n\treturn bva.EndTime\n}", "func (o *ApplianceSetupInfoAllOf) GetEndTime() time.Time {\n\tif o == nil || o.EndTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.EndTime\n}", "func (o *ApplianceClusterInstallPhase) GetEndTime() time.Time {\n\tif o == nil || o.EndTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.EndTime\n}", "func (o *WorkflowServiceItemActionInstance) GetEndTime() time.Time {\n\tif o == nil || o.EndTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.EndTime\n}", "func (o *WorkflowCatalogServiceRequest) GetEndTime() time.Time {\n\tif o == nil || o.EndTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.EndTime\n}", "func (c *Container) GetEndTime() time.Time {\n\treturn c.end\n}", "func (o *OnpremUpgradePhase) GetEndTime() time.Time {\n\tif o == nil || o.EndTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.EndTime\n}", "func (o *AvailableBudget) GetEnd() time.Time {\n\tif o == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\n\treturn o.End\n}", "func (_Casper *CasperSession) EndTime() (*big.Int, error) {\n\treturn _Casper.Contract.EndTime(&_Casper.CallOpts)\n}", "func (req *StartWFSRequest) GetEndTime() time.Time {\n\treturn req.EndTime\n}", "func (m *BookingWorkTimeSlot) GetEnd()(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly) {\n val, err := m.GetBackingStore().Get(\"end\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly)\n }\n return nil\n}", "func (v *Validator) EndTime() time.Time {\n\treturn time.Unix(int64(v.End), 0)\n}", "func (_Casper *CasperCallerSession) EndTime() (*big.Int, error) {\n\treturn _Casper.Contract.EndTime(&_Casper.CallOpts)\n}", "func (m *GetSchedulePostRequestBody) GetEndTime()(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.DateTimeTimeZoneable) {\n return m.endTime\n}", "func (m *SimulationAutomationRun) GetEndDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"endDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (t *TimeDuration) GetEnd() time.Time {\n\tend := t.Start.Add(time.Duration(t.Duration) * time.Minute)\n\treturn end\n}", "func (m *DateDrivenRolloutSettings) GetEndDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"endDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (o *Job) GetExpectedEndTime(ctx context.Context) (expectedEndTime uint64, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceJob, \"ExpectedEndTime\").Store(&expectedEndTime)\n\treturn\n}", "func (r Reservation) EndTime() string {\n\thr := r.End / 60\n\tmin := r.End % 60\n\tvar ampm string\n\tif ampm = \"AM\"; hr >= 12 {\n\t\tampm = \"PM\"\n\t}\n\tif hr > 12 {\n\t\thr = hr - 12\n\t}\n\tif hr == 0 {\n\t\thr = 12\n\t}\n\treturn fmt.Sprintf(\"%02d:%02d %s\", hr, min, ampm)\n}", "func (m *ScheduleItem) GetEnd()(DateTimeTimeZoneable) {\n val, err := m.GetBackingStore().Get(\"end\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(DateTimeTimeZoneable)\n }\n return nil\n}", "func (m *Reminder) GetEventEndTime()(DateTimeTimeZoneable) {\n val, err := m.GetBackingStore().Get(\"eventEndTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(DateTimeTimeZoneable)\n }\n return nil\n}", "func (o *Giveaway) GetEndDate() time.Time {\n\tif o == nil || o.EndDate == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.EndDate\n}", "func (c deploymentChecker) EndTime() uint64 {\n\treturn c.deployment.ExpireTime\n}", "func (_Casper *CasperCaller) EndTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Casper.contract.Call(opts, out, \"endTime\")\n\treturn *ret0, err\n}", "func (m *IosUpdateConfiguration) GetActiveHoursEnd()(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly) {\n val, err := m.GetBackingStore().Get(\"activeHoursEnd\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly)\n }\n return nil\n}", "func (m TradingSessionStatus) GetTradSesEndTime() (v time.Time, err quickfix.MessageRejectError) {\n\tvar f field.TradSesEndTimeField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func (_LvRecording *LvRecordingCaller) EndTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _LvRecording.contract.Call(opts, &out, \"endTime\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (r *ScheduledAction) EndTime() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"endTime\"])\n}", "func (o *WorkflowServiceItemActionInstance) GetEndTimeOk() (*time.Time, bool) {\n\tif o == nil || o.EndTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.EndTime, true\n}", "func (o *ApplianceSetupInfoAllOf) SetEndTime(v time.Time) {\n\to.EndTime = &v\n}", "func CurrentTaskEndTime() time.Time {\n\tif !IsTaskRunning() {\n\t\treturn time.Unix(0, 0)\n\t}\n\treturn time.Unix(persist.GetValueInt(taskEndTimeKey), 0)\n}", "func (tcr *TestCaseReporter) SetEndTime(t time.Time) {\n\ttcr.endTime = t\n\n\tif tcr.testCase == nil {\n\t\treturn\n\t}\n\ttcr.testCase.TimeInSeconds = tcr.Duration().Seconds()\n}", "func (o *HealthIncident) GetEndDate() time.Time {\n\tif o == nil || o.EndDate.Get() == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.EndDate.Get()\n}", "func (o GoogleCloudRetailV2alphaConditionTimeRangeResponseOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionTimeRangeResponse) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (o GoogleCloudRetailV2alphaConditionTimeRangeOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionTimeRange) *string { return v.EndTime }).(pulumi.StringPtrOutput)\n}", "func (o DataTransferConfigScheduleOptionsPtrOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DataTransferConfigScheduleOptions) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.EndTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o TimelineOutput) EndTime() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *Timeline) pulumi.IntPtrOutput { return v.EndTime }).(pulumi.IntPtrOutput)\n}", "func (o *ApplianceSetupInfoAllOf) GetEndTimeOk() (*time.Time, bool) {\n\tif o == nil || o.EndTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.EndTime, true\n}", "func (o *ApplianceClusterInstallPhase) SetEndTime(v time.Time) {\n\to.EndTime = &v\n}", "func (m *MarketHoursMutation) EndTime() (r time.Time, exists bool) {\n\tv := m.end_time\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (o DataTransferConfigScheduleOptionsOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DataTransferConfigScheduleOptions) *string { return v.EndTime }).(pulumi.StringPtrOutput)\n}", "func (o *ApplianceClusterInstallPhase) GetEndTimeOk() (*time.Time, bool) {\n\tif o == nil || o.EndTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.EndTime, true\n}", "func (r *ReportTaskRequest) SetEndTime(endTime string) {\n r.EndTime = &endTime\n}", "func (s *GetProfileInput) SetEndTime(v time.Time) *GetProfileInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (o *WorkflowServiceItemActionInstance) SetEndTime(v time.Time) {\n\to.EndTime = &v\n}", "func (r *ModifyTaskRequest) SetEndTime(endTime string) {\n r.EndTime = &endTime\n}", "func (o *OnpremUpgradePhase) SetEndTime(v time.Time) {\n\to.EndTime = &v\n}", "func (o *ApplianceImageBundleAllOf) GetUpgradeEndTime() time.Time {\n\tif o == nil || o.UpgradeEndTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.UpgradeEndTime\n}", "func (o InstanceMaintenanceScheduleOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceSchedule) *string { return v.EndTime }).(pulumi.StringPtrOutput)\n}", "func (o InstanceMaintenanceScheduleOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceSchedule) *string { return v.EndTime }).(pulumi.StringPtrOutput)\n}", "func (c *PurchasesVoidedpurchasesListCall) EndTime(endTime int64) *PurchasesVoidedpurchasesListCall {\n\tc.urlParams_.Set(\"endTime\", fmt.Sprint(endTime))\n\treturn c\n}", "func (m *SharePostRequestBody) GetEndDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n return m.endDateTime\n}", "func (object Object) EndTime(value time.Time) Object {\n\treturn object.Property(as.PropertyEndTime, value)\n}", "func (m *sdt) EndHour() int32 {\n\treturn m.endHourField\n}", "func (o *WorkflowCatalogServiceRequest) SetEndTime(v time.Time) {\n\to.EndTime = &v\n}", "func (o *WorkflowCatalogServiceRequest) GetEndTimeOk() (*time.Time, bool) {\n\tif o == nil || o.EndTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.EndTime, true\n}", "func (m *VulnEvidence) SetEndTime(in *google_protobuf.Timestamp) {\n\tm.EndTime = in\n}", "func (s *GetMetricDataInput) SetEndTime(v time.Time) *GetMetricDataInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (o *OnpremUpgradePhase) GetEndTimeOk() (*time.Time, bool) {\n\tif o == nil || o.EndTime == nil {\n\t\treturn nil, false\n\t}\n\treturn o.EndTime, true\n}", "func (_LvRecording *LvRecordingTransactor) SetEndTime(opts *bind.TransactOpts, _endTime *big.Int) (*types.Transaction, error) {\n\treturn _LvRecording.contract.Transact(opts, \"setEndTime\", _endTime)\n}", "func (s *GetRecommendationsInput) SetEndTime(v time.Time) *GetRecommendationsInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (o RestoreResponseOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RestoreResponse) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (s *PrefetchRetrieval) SetEndTime(v time.Time) *PrefetchRetrieval {\n\ts.EndTime = &v\n\treturn s\n}", "func (o *AvailableBudget) GetEndOk() (*time.Time, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.End, true\n}", "func (o InstanceMaintenanceSchedulePtrOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InstanceMaintenanceSchedule) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.EndTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (s *TrialComponent) SetEndTime(v time.Time) *TrialComponent {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *GetMetricDataV2Input) SetEndTime(v time.Time) *GetMetricDataV2Input {\n\ts.EndTime = &v\n\treturn s\n}", "func (m *MarketHoursMutation) SetEndTime(t time.Time) {\n\tm.end_time = &t\n}", "func (o BaselineStrategyOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *BaselineStrategy) pulumi.StringOutput { return v.EndTime }).(pulumi.StringOutput)\n}", "func (s *UpdateTrialComponentInput) SetEndTime(v time.Time) *UpdateTrialComponentInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *DescribeTrialComponentOutput) SetEndTime(v time.Time) *DescribeTrialComponentOutput {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *ListProfileTimesInput) SetEndTime(v time.Time) *ListProfileTimesInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (o ScanRunResponseOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ScanRunResponse) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (o ScanRunResponseOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ScanRunResponse) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (m *SequentialActivationRenewalsAlertIncident) GetSequenceEndDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"sequenceEndDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (s *ListRecoveryPointsInput) SetEndTime(v time.Time) *ListRecoveryPointsInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *Recommendation) SetEndTime(v time.Time) *Recommendation {\n\ts.EndTime = &v\n\treturn s\n}", "func (m *sdt) EndDateTime() int64 {\n\treturn m.endDateTimeField\n}", "func (s *GetMetricStatisticsInput) SetEndTime(v time.Time) *GetMetricStatisticsInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *ListFindingsReportsInput) SetEndTime(v time.Time) *ListFindingsReportsInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *CreateTrialComponentInput) SetEndTime(v time.Time) *CreateTrialComponentInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *ConversationLogsDataSourceFilterBy) SetEndTime(v time.Time) *ConversationLogsDataSourceFilterBy {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *TrialComponentSummary) SetEndTime(v time.Time) *TrialComponentSummary {\n\ts.EndTime = &v\n\treturn s\n}", "func (tsr *TestSuiteReporter) SetEndTime(t time.Time) {\n\ttsr.endTime = t\n\n\tif tsr.testSuite == nil {\n\t\treturn\n\t}\n\ttsr.testSuite.TimeInSeconds = tsr.Duration().Seconds()\n}", "func (o MetadataExportResponseOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MetadataExportResponse) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (s *AutoMLCandidate) SetEndTime(v time.Time) *AutoMLCandidate {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *PrefetchConsumption) SetEndTime(v time.Time) *PrefetchConsumption {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *BatchGetFrameMetricDataInput) SetEndTime(v time.Time) *BatchGetFrameMetricDataInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *ListSnapshotsInput) SetEndTime(v time.Time) *ListSnapshotsInput {\n\ts.EndTime = &v\n\treturn s\n}", "func (s *InferenceExperimentSchedule) SetEndTime(v time.Time) *InferenceExperimentSchedule {\n\ts.EndTime = &v\n\treturn s\n}", "func (c *ProjectsTracesListCall) EndTime(endTime string) *ProjectsTracesListCall {\n\tc.urlParams_.Set(\"endTime\", endTime)\n\treturn c\n}", "func (s *ImportJobProperties) SetEndTime(v time.Time) *ImportJobProperties {\n\ts.EndTime = &v\n\treturn s\n}", "func (_LvRecordableStream *LvRecordableStreamCaller) EndTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _LvRecordableStream.contract.Call(opts, &out, \"endTime\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (o LookupJobResultOutput) EndTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupJobResult) string { return v.EndTime }).(pulumi.StringOutput)\n}", "func (t *Timer) End() time.Time {\n\treturn t.end\n}", "func (s *GetMatchingJobOutput) SetEndTime(v time.Time) *GetMatchingJobOutput {\n\ts.EndTime = &v\n\treturn s\n}", "func (r *Reporter) SetEndTime(t time.Time) {\n\tr.endTime = t\n\n\tif r.report == nil {\n\t\treturn\n\t}\n\tr.report.TimeInSeconds = t.Sub(r.startTime).Seconds()\n}", "func (c *Container) SetEndTime(newEnd time.Time) {\n\tc.end = newEnd\n}", "func (o ScanRunResponsePtrOutput) EndTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRunResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.EndTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o *ViewProjectBudget) GetEndDateTime() string {\n\tif o == nil || o.EndDateTime == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.EndDateTime\n}" ]
[ "0.8592755", "0.7491895", "0.7327237", "0.73128647", "0.7202728", "0.71574676", "0.7140883", "0.7082313", "0.7063966", "0.7059457", "0.69634634", "0.6931381", "0.6890082", "0.67958534", "0.6728343", "0.67127305", "0.67088944", "0.6631116", "0.6616934", "0.6547994", "0.6525623", "0.6488571", "0.64642924", "0.6463569", "0.6446536", "0.6428223", "0.6402636", "0.6368957", "0.6367753", "0.63654965", "0.63507515", "0.63374233", "0.6336237", "0.63300043", "0.6327515", "0.62935036", "0.62771714", "0.62760043", "0.6274604", "0.62711716", "0.6268429", "0.62558097", "0.62434036", "0.6215297", "0.6214315", "0.6212391", "0.620737", "0.62064326", "0.620588", "0.620588", "0.62001544", "0.6199933", "0.61961305", "0.6184114", "0.6183541", "0.61402124", "0.61151785", "0.6110377", "0.61076933", "0.6105413", "0.6100825", "0.6096354", "0.60956097", "0.60944843", "0.60784966", "0.6070895", "0.60647523", "0.60555965", "0.6041129", "0.6040183", "0.60397166", "0.6035819", "0.6029284", "0.6029284", "0.6028139", "0.60185987", "0.6017965", "0.60143626", "0.60129833", "0.60097545", "0.5997668", "0.59960014", "0.5994922", "0.5961401", "0.59608084", "0.59568775", "0.59552413", "0.59403473", "0.5940338", "0.593416", "0.5924543", "0.59233683", "0.5914819", "0.5908665", "0.5897975", "0.58969516", "0.58924824", "0.58882797", "0.5878576", "0.58777785" ]
0.8543022
1
Validate checks for errors on the account fields
func (plva PermanentLockedAccount) Validate() error { if plva.EndTime > 0 { return errors.New("permanently vested accounts cannot have an end-time") } return plva.BaseVestingAccount.Validate() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (account *Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Phone, \"+\") {\n\t\treturn u.Message(false, \"Phone Number address is required\"), false\n\t}\n\n\tif len(account.UserName) < 3 {\n\t\treturn u.Message(false, \"Username is required\"), false\n\t}\n\n\t//PhoneNumber must be unique\n\ttemp := &Account{}\n\n\t//check for errors and duplicate phones\n\terr := GetDB().Table(\"accounts\").Where(\"phone = ?\", account.Phone).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"+err.Error()), false\n\t}\n\tif temp.Phone != \"\" {\n\t\treturn u.Message(false, \"Phone Number address already in use by another user.\"), false\n\t}\n\n\t//check for errors and duplicate username\n\terr = GetDB().Table(\"accounts\").Where(\"user_name = ?\", account.UserName).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"+err.Error()), false\n\t}\n\tif temp.UserName != \"\" {\n\t\tresponse := fmt.Sprintf(\"Username: %d is already in use by another user.\", account.UserName)\n\t\treturn u.Message(false, response), false\n\t}\n\n\treturn u.Message(false, \"Requirement passed\"), true\n}", "func (account Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, ERROR_EMAIL), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, ERROR_PASSWORD_LENTH), false\n\t}\n\n\t// Email must be unique\n\ttemp := &Account{}\n\n\t// 数据类型合法时,查询数据表,GetDB return the configed db\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, ERROR_CONNECTION), false\n\t}\n\t// 存在该email\n\tif temp.Email != \"\" {\n\t\treturn u.Message(false, ERROR_EMAIL_USED), false\n\t}\n\n\treturn u.Message(false, GET_SUCCESS), true\n}", "func (a Account) Validate() error {\n\treturn validation.ValidateStruct(&a,\n\t\tvalidation.Field(&a.Name, validation.Required, validation.Length(3, 75)),\n\t)\n}", "func (m *Account) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccountID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAuditLogs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateParentAccountID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethodID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReferenceTime(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (account *Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, \"Email address is required\"), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, \"Password is required\"), false\n\t}\n\n\t//Email must be unique\n\ttemp := &Account{}\n\t//check for errors and duplicate emails\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"), false\n\t}\n\tif temp.Email != \"\" {\n\t\treturn u.Message(false, \"Email address already in use by another user.\"), false\n\t}\n\treturn u.Message(false, \"Requirement passed\"), true\n}", "func (a *Account) Validate() error {\n\treturn nil\n}", "func (mt *Account) Validate() (err error) {\n\tif mt.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"id\"))\n\t}\n\tif mt.Password == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"password\"))\n\t}\n\n\treturn\n}", "func (accountInfo *AccountInfo) Validate() error {\n\taccountSchema, _ := GetAccountSchema(accountInfo.Domain)\n\tif accountSchema == nil {\n\t\treturn errors.New(\"schema undefined for domain \" + accountInfo.Domain)\n\t}\n\n\t// Group\n\tif !accountSchema.IsGroupExist(accountInfo.Group) {\n\t\treturn errors.New(\"unknown group \" + accountInfo.Group)\n\t}\n\n\t// UserID\n\tif accountInfo.Uid == \"\" {\n\t\treturn errors.New(\"uid can not be empty\")\n\t}\n\n\t// LoginIDs\n\tif len(accountInfo.LoginIDs) == 0 {\n\t\treturn errors.New(\"should have at least one login id\")\n\t}\n\trequiredIDs := accountSchema.getRequiredLogIDs()\n\tfor _, requiredID := range requiredIDs {\n\t\tif _, ok := accountInfo.LoginIDs[requiredID]; !ok {\n\t\t\treturn errors.New(\"login id:\" + requiredID + \" is required but not specified\")\n\t\t}\n\t}\n\tfor k, v := range accountInfo.LoginIDs {\n\t\tloginIDSchema, _ := accountSchema.GetLoginIDSchema(k)\n\t\tif loginIDSchema == nil {\n\t\t\treturn errors.New(\"login id schema for \" + k + \" is not defined\")\n\t\t} else {\n\t\t\tif !loginIDSchema.NeedVerified {\n\t\t\t\tv.Verified = true\n\t\t\t\t// accountInfo.LoginIDs[k] = v\n\t\t\t}\n\t\t\tif !loginIDSchema.Validator.Validate(v.ID) {\n\t\t\t\treturn errors.New(\"invalid format of login id \" + k + \":\" + v.ID)\n\t\t\t}\n\t\t}\n\t}\n\n\t// options\n\toptionsMap := mergeMaps(accountInfo.Profiles, accountInfo.Others)\n\trequiredOptions := accountSchema.getRequiredOptions()\n\tfor _, requiredOption := range requiredOptions {\n\t\tif _, ok := optionsMap[requiredOption]; !ok {\n\t\t\treturn errors.New(\"option:\" + requiredOption + \" is required but not specified\")\n\t\t}\n\t}\n\n\tfor k, v := range optionsMap {\n\t\toptionSchema, _ := accountSchema.GetOptionSchema(k)\n\t\tif optionSchema == nil {\n\t\t\treturn errors.New(\"option schema for \" + k + \" is not defined\")\n\t\t} else {\n\t\t\tif !optionSchema.Validator.Validate(v) {\n\t\t\t\treturn errors.New(\"invalid format of option \" + k)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (mt *Account) Validate() (err error) {\n\n\tif mt.Href == \"\" {\n\t\terr = goa.MissingAttributeError(`response`, \"href\", err)\n\t}\n\tif mt.Name == \"\" {\n\t\terr = goa.MissingAttributeError(`response`, \"name\", err)\n\t}\n\n\tif mt.CreatedAt != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatDateTime, *mt.CreatedAt); err2 != nil {\n\t\t\terr = goa.InvalidFormatError(`response.created_at`, *mt.CreatedAt, goa.FormatDateTime, err2, err)\n\t\t}\n\t}\n\tif mt.CreatedBy != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *mt.CreatedBy); err2 != nil {\n\t\t\terr = goa.InvalidFormatError(`response.created_by`, *mt.CreatedBy, goa.FormatEmail, err2, err)\n\t\t}\n\t}\n\treturn\n}", "func (c *modAccountRun) validate(args []string) error {\n\tif len(args) < 2 {\n\t\treturn errors.New(\"not enough arguments\")\n\t}\n\n\tif len(args) > 2 {\n\t\treturn errors.New(\"too many arguments\")\n\t}\n\n\treturn nil\n}", "func (m *LedgerAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccount(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePostings(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (b *OGame) ValidateAccount(code string) error {\n\treturn b.validateAccount(code)\n}", "func (ut *accountInputPayload) Validate() (err error) {\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`response.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 1, true))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 30, false))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 1, true))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 30, false))\n\t\t}\n\t}\n\treturn\n}", "func (account *Account) ValidateUpdate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, \"Email address is required\"), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, \"Password is required\"), false\n\t}\n\n\t//Email must be unique\n\ttemp := &Account{}\n\t//check for errors and duplicate emails\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"), false\n\t}\n\tif temp.Email == \"\" {\n\t\treturn u.Message(false, \"Email address not found in database.\"), false\n\t}\n\treturn u.Message(true, \"Requirement passed\"), true\n}", "func (ut *AccountInputPayload) Validate() (err error) {\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`response.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 1, true))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 30, false))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 1, true))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 30, false))\n\t\t}\n\t}\n\treturn\n}", "func ValidateAccount(client httpclient.IHttpClient, ctx context.Context, lobby, code string) error {\n\tif len(code) != 36 {\n\t\treturn errors.New(\"invalid validation code\")\n\t}\n\treq, err := http.NewRequest(http.MethodPut, \"https://\"+lobby+\".ogame.gameforge.com/api/users/validate/\"+code, strings.NewReader(`{\"language\":\"en\"}`))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.WithContext(ctx)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\treturn nil\n}", "func (b *Builder) Validate() (*Account, error) {\n\tb.validate.SetTagName(b.essential.Country)\n\tif err := validateStruct(b.validate, b.essential); err != nil {\n\t\treturn nil, err\n\t}\n\tb.validate.SetTagName(\"validate\")\n\tif err := validateStruct(b.validate, b.essential); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := validateStruct(b.validate, b.optional); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Account{\n\t\tid: b.essential.ID,\n\t\torganizationID: b.essential.OrganizationID,\n\t\tversionIndex: b.optional.VersionIndex,\n\t\tcountry: b.essential.Country,\n\t\tbankIDCode: b.essential.BankIDCode,\n\t\tbankID: b.essential.BankID,\n\t\tbic: b.essential.Bic,\n\t\tiban: b.essential.Iban,\n\t\tbaseCurrency: b.optional.BaseCurrency,\n\t\taccountNumber: b.optional.AccountNumber,\n\t\tcustomerID: b.optional.CustomerID,\n\t\ttitle: b.optional.Title,\n\t\tfirstName: b.optional.FirstName,\n\t\tbankAccountName: b.optional.BankAccountName,\n\t\taltBankAccountNames: b.optional.AltBankAccountNames,\n\t\taccountClassification: b.optional.AccountClassification,\n\t\tjointAccount: b.optional.JointAccount,\n\t\taccountMatchingOptOut: b.optional.AccountMatchingOptOut,\n\t\tsecondaryIdentification: b.optional.SecondaryIdentification,\n\t}, nil\n}", "func (a *Account) Validate() error {\n\tvalidate := validator.New()\n\treturn validate.Struct(a)\n}", "func (ga GenesisAccount) Validate() error {\n\tif ethermint.IsZeroAddress(ga.Address) {\n\t\treturn fmt.Errorf(\"address cannot be the zero address %s\", ga.Address)\n\t}\n\tif len(ethcmn.Hex2Bytes(ga.Code)) == 0 {\n\t\treturn errors.New(\"code cannot be empty\")\n\t}\n\n\treturn ga.Storage.Validate()\n}", "func validate(user *customer_api.DbUser, allowEmpty bool) error {\n\tconst minNameLength, maxNameLength = 3, 20\n\tconst emailRegexString = \"^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$\"\n\tvar emailRegex = regexp.MustCompile(emailRegexString)\n\n\tif !(allowEmpty && user.Email == \"\") {\n\t\tif len(user.Email) < 5 || !emailRegex.MatchString(user.Email) {\n\t\t\treturn errors.New(\"invalid email\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.FirstName == \"\") {\n\t\tif len(user.FirstName) < minNameLength || len(user.FirstName) > maxNameLength {\n\t\t\treturn errors.New(\"first_name should be between 3 and 20 characters\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.LastName == \"\") {\n\t\tif len(user.LastName) < minNameLength || len(user.LastName) > maxNameLength {\n\t\t\treturn errors.New(\"last_name should be between 3 and 20 characters\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.Phone == 0) {\n\t\tif user.Phone < 1000000000 || user.Phone > 9999999999 {\n\t\t\treturn errors.New(\"invalid phone no\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.Id == \"\") {\n\t\tif user.Id == \"\" {\n\t\t\treturn errors.New(\"id cannot be empty\")\n\t\t}\n\t}\n\treturn nil\n}", "func (server *Server) checkValidAccount(ctx *gin.Context, id int64, curr string) (bool, db.Account) {\n\tacc, err := server.repository.GetAccount(ctx, id)\n\tif err != nil {\n\t\tctx.JSON(http.StatusNotFound, errorResponse(err))\n\t\treturn false, db.Account{}\n\t}\n\tif acc.Currency != curr {\n\t\terr = fmt.Errorf(\"invalid currency for account [%d]: expected %s received %s\", acc.ID, acc.Currency, curr)\n\t\tctx.JSON(http.StatusBadRequest, errorResponse(err))\n\t\treturn false, db.Account{}\n\t}\n\n\treturn true, acc\n}", "func (mt *EasypostCarrierAccounts) Validate() (err error) {\n\tif mt.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"id\"))\n\t}\n\tif mt.Object == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"object\"))\n\t}\n\n\tif ok := goa.ValidatePattern(`^CarrierAccount$`, mt.Object); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.object`, mt.Object, `^CarrierAccount$`))\n\t}\n\treturn\n}", "func (m *InfrastructureAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCostCenter(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCriticalityLevel(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEnvironment(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateExternalID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLifecycleStatus(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOwner(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *CloudAccountExtended) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with CloudAccount\n\tif err := m.CloudAccount.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateState(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (a *Account) Validate() error {\n\terr := validation.ValidateStruct(a,\n\t\tvalidation.Field(&a.AdminRoleArn, validateAdminRoleArn...),\n\t\tvalidation.Field(&a.ID, validateID...),\n\t\tvalidation.Field(&a.LastModifiedOn, validateInt64...),\n\t\tvalidation.Field(&a.Status, validateStatus...),\n\t\tvalidation.Field(&a.CreatedOn, validateInt64...),\n\t\tvalidation.Field(&a.PrincipalRoleArn, validatePrincipalRoleArn...),\n\t\tvalidation.Field(&a.PrincipalPolicyHash, validatePrincipalPolicyHash...),\n\t)\n\tif err != nil {\n\t\treturn errors.NewValidation(\"account\", err)\n\t}\n\treturn nil\n}", "func validRawAccount(accountName string) error {\n\t// param absence check\n\tif accountName == \"\" {\n\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name is empty\")\n\t}\n\n\t// account naming rule check\n\tif len(accountName) != accountSize {\n\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name length expect %d, actual: %d\", accountSize, len(accountName))\n\t}\n\n\tfor i := 0; i < accountSize; i++ {\n\t\tif accountName[i] >= '0' && accountName[i] <= '9' {\n\t\t\tcontinue\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name expect continuous %d number\", accountSize)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o *CloudSnapshotAccount) Validate() error {\n\n\terrors := elemental.Errors{}\n\trequiredErrors := elemental.Errors{}\n\n\tif err := ValidateTagsWithoutReservedPrefixes(\"associatedTags\", o.AssociatedTags); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif err := elemental.ValidateStringInList(\"cloudType\", string(o.CloudType), []string{\"AWS\", \"GCP\"}, false); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif len(requiredErrors) > 0 {\n\t\treturn requiredErrors\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (m *ProviderAccountRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDataset(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDatasetName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateField(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePreferences(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (uu *UserUpdate) check() error {\n\tif v, ok := uu.mutation.AccountName(); ok {\n\t\tif err := user.AccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"account_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"account_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.StaffType(); ok {\n\t\tif err := user.StaffTypeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_type\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_type\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.FamilyName(); ok {\n\t\tif err := user.FamilyNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"family_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"family_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.GivenName(); ok {\n\t\tif err := user.GivenNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"given_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"given_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.DisplayName(); ok {\n\t\tif err := user.DisplayNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"display_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"display_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.IDNumber(); ok {\n\t\tif err := user.IDNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"id_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Sex(); ok {\n\t\tif err := user.SexValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"sex\", err: fmt.Errorf(\"ent: validator failed for field \\\"sex\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.PhoneNumber(); ok {\n\t\tif err := user.PhoneNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Address(); ok {\n\t\tif err := user.AddressValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"address\", err: fmt.Errorf(\"ent: validator failed for field \\\"address\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.StaffID(); ok {\n\t\tif err := user.StaffIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_id\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_id\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.PersonalEmail(); ok {\n\t\tif err := user.PersonalEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"personal_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"personal_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.IntranetWorkEmail(); ok {\n\t\tif err := user.IntranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"intranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.ExtranetWorkEmail(); ok {\n\t\tif err := user.ExtranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"extranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"extranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (profileImport *ProfileImportRequest) Validate(tx *sql.Tx) error {\n\n\tprofile := profileImport.Profile\n\n\t// Profile fields are valid\n\terrs := tovalidate.ToErrors(validation.Errors{\n\t\t\"name\": validation.Validate(profile.Name, validation.By(\n\t\t\tfunc(value interface{}) error {\n\t\t\t\tname, ok := value.(*string)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn fmt.Errorf(\"wrong type, need: string, got: %T\", value)\n\t\t\t\t}\n\t\t\t\tif name == nil || *name == \"\" {\n\t\t\t\t\treturn errors.New(\"required and cannot be blank\")\n\t\t\t\t}\n\t\t\t\tif strings.Contains(*name, \" \") {\n\t\t\t\t\treturn errors.New(\"cannot contain spaces\")\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t)),\n\t\t\"description\": validation.Validate(profile.Description, validation.Required),\n\t\t\"cdnName\": validation.Validate(profile.CDNName, validation.Required),\n\t\t\"type\": validation.Validate(profile.Type, validation.Required),\n\t})\n\n\t// Validate CDN exist\n\tif profile.CDNName != nil {\n\t\tif ok, err := CDNExistsByName(*profile.CDNName, tx); err != nil {\n\t\t\terrString := fmt.Sprintf(\"checking cdn name %v existence\", *profile.CDNName)\n\t\t\tlog.Errorf(\"%v: %v\", errString, err.Error())\n\t\t\terrs = append(errs, errors.New(errString))\n\t\t} else if !ok {\n\t\t\terrs = append(errs, fmt.Errorf(\"%v CDN does not exist\", *profile.CDNName))\n\t\t}\n\t}\n\n\t// Validate profile does not already exist\n\tif profile.Name != nil {\n\t\tif ok, err := ProfileExistsByName(*profile.Name, tx); err != nil {\n\t\t\terrString := fmt.Sprintf(\"checking profile name %v existence\", *profile.Name)\n\t\t\tlog.Errorf(\"%v: %v\", errString, err.Error())\n\t\t\terrs = append(errs, errors.New(errString))\n\t\t} else if ok {\n\t\t\terrs = append(errs, fmt.Errorf(\"a profile with the name \\\"%s\\\" already exists\", *profile.Name))\n\t\t}\n\t}\n\n\t// Validate all parameters\n\t// export/import does not include secure flag\n\t// default value to not flag on validation\n\tsecure := 1\n\tfor i, pp := range profileImport.Parameters {\n\t\tif ppErrs := validateProfileParamPostFields(pp.ConfigFile, pp.Name, pp.Value, &secure); len(ppErrs) > 0 {\n\t\t\tfor _, err := range ppErrs {\n\t\t\t\terrs = append(errs, errors.New(\"parameter \"+strconv.Itoa(i)+\": \"+err.Error()))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errs) > 0 {\n\t\treturn util.JoinErrs(errs)\n\t}\n\n\treturn nil\n}", "func (u *Usecase) validFields(d *Device) error {\n\tif d.Name == \"\" {\n\t\treturn &InvalidError{\"attribute `Name` must not be empty\"}\n\t}\n\n\tif d.User == 0 {\n\t\treturn &InvalidError{\"invalid user\"}\n\t}\n\n\treturn nil\n}", "func (t *TokenAccount) Validate() error {\n\tv := validator.New()\n\terr := v.RegisterValidation(\"notblank\", validators.NotBlank)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = v.RegisterValidation(\"notall\", validation.NotAll)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn v.Struct(t)\n}", "func (v *Reg) Validate(ctx context.Context, f *reg.Form) error {\n\tvar es Errors\n\n\tif err := validation.Validate(f.Email, validation.Required, is.Email); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"email\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := validation.Validate(f.AccountID, validation.Required); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"account_id\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := v.Uniquer.Unique(ctx, f.Email); err != nil {\n\t\tswitch errors.Cause(err) {\n\t\tcase reg.ErrEmailExists:\n\t\t\tes = append(es, Error{\n\t\t\t\tField: \"email\",\n\t\t\t\tMessage: err.Error(),\n\t\t\t})\n\t\tdefault:\n\t\t\treturn errors.Wrap(err, \"unique\")\n\t\t}\n\t}\n\n\tfmt.Println(f.Password, f.PasswordConfirmation)\n\n\tif err := validation.Validate(f.Password, validation.Required, validation.Length(6, 32)); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"password\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := validation.Validate(f.PasswordConfirmation, validation.Required, validation.Length(6, 32)); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"password_confirmation\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif f.Password != f.PasswordConfirmation {\n\t\tes = append(es, Error{\n\t\t\tField: \"password_confirmation\",\n\t\t\tMessage: \"mismatch\",\n\t\t}, Error{\n\t\t\tField: \"password\",\n\t\t\tMessage: \"mismatch\",\n\t\t})\n\t}\n\n\tif len(es) > 0 {\n\t\treturn es\n\t}\n\n\treturn nil\n}", "func validateAccountName(accountName string) (string, error) {\n\treturn accountName, nil\n}", "func (rcv *controller) validate() error {\n\n\tif err := rcv.read(); err != nil {\n\t\treturn err\n\t}\n\n\t// If account does not exists\n\tif rcv.store.Email == \"\" {\n\t\treturn errors.New(rcv.Translate(\"text11\"))\n\t}\n\n\t// If time for activating account is expired\n\tif time.Now().Unix() > rcv.store.Expired {\n\t\t// Delete registered user from neo4j\n\t\tmaccount.Delete(rcv.store.Email, rcv.Local)\n\t\treturn &expiredError{rcv.Controller}\n\t}\n\n\treturn nil\n}", "func (acc *AccessControlCreate) check() error {\n\tif _, ok := acc.mutation.ServiceID(); !ok {\n\t\treturn &ValidationError{Name: \"service_id\", err: errors.New(\"ent: missing required field \\\"service_id\\\"\")}\n\t}\n\tif _, ok := acc.mutation.OpenAuth(); !ok {\n\t\treturn &ValidationError{Name: \"open_auth\", err: errors.New(\"ent: missing required field \\\"open_auth\\\"\")}\n\t}\n\tif _, ok := acc.mutation.BlackList(); !ok {\n\t\treturn &ValidationError{Name: \"black_list\", err: errors.New(\"ent: missing required field \\\"black_list\\\"\")}\n\t}\n\tif _, ok := acc.mutation.WhiteList(); !ok {\n\t\treturn &ValidationError{Name: \"white_list\", err: errors.New(\"ent: missing required field \\\"white_list\\\"\")}\n\t}\n\tif _, ok := acc.mutation.WhiteHostName(); !ok {\n\t\treturn &ValidationError{Name: \"white_host_name\", err: errors.New(\"ent: missing required field \\\"white_host_name\\\"\")}\n\t}\n\tif _, ok := acc.mutation.ClientipFlowLimit(); !ok {\n\t\treturn &ValidationError{Name: \"clientip_flow_limit\", err: errors.New(\"ent: missing required field \\\"clientip_flow_limit\\\"\")}\n\t}\n\tif _, ok := acc.mutation.ServiceFlowLimit(); !ok {\n\t\treturn &ValidationError{Name: \"service_flow_limit\", err: errors.New(\"ent: missing required field \\\"service_flow_limit\\\"\")}\n\t}\n\treturn nil\n}", "func (u *User) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\tvar err error\n\t//validate based on is agent\n\tif !u.IsAgent { //is not an agent\n\t\treturn validate.Validate(\n\t\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t\t&validators.StringIsPresent{Field: u.PasswordHash, Name: \"PasswordHash\"},\n\t\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t\t&validators.StringIsPresent{Field: u.Phone, Name: \"Phone\"},\n\t\t\t// check to see if the email address is already taken:\n\t\t\t&validators.FuncValidator{\n\t\t\t\tField: u.Email,\n\t\t\t\tName: \"Email\",\n\t\t\t\tMessage: \"%s is already taken\",\n\t\t\t\tFn: func() bool {\n\t\t\t\t\tvar b bool\n\t\t\t\t\tq := tx.Where(\"email = ?\", u.Email)\n\t\t\t\t\tif u.ID != uuid.Nil {\n\t\t\t\t\t\tq = q.Where(\"id != ?\", u.ID)\n\t\t\t\t\t}\n\t\t\t\t\tb, err = q.Exists(u)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\treturn !b\n\t\t\t\t},\n\t\t\t},\n\t\t), err\n\n\t} else { // trying to save agent\n\t\treturn validate.Validate(\n\t\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t\t&validators.StringIsPresent{Field: u.PasswordHash, Name: \"PasswordHash\"},\n\t\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t\t&validators.StringIsPresent{Field: u.Phone, Name: \"Phone\"},\n\t\t\t&validators.StringIsPresent{Field: u.PublicEmail.String, Name: \"PublicEmail\"},\n\t\t\t&validators.StringIsPresent{Field: u.Company.String, Name: \"Company\"},\n\t\t\t&validators.StringIsPresent{Field: u.Address1.String, Name: \"Address1\"},\n\t\t\t&validators.StringIsPresent{Field: u.City.String, Name: \"City\"},\n\t\t\t&validators.StringIsPresent{Field: u.State.String, Name: \"State\"},\n\t\t\t&validators.StringIsPresent{Field: u.Zipcode.String, Name: \"Zipcode\"},\n\t\t\t// check to see if the email address is already taken:\n\t\t\t&validators.FuncValidator{\n\t\t\t\tField: u.Email,\n\t\t\t\tName: \"Email\",\n\t\t\t\tMessage: \"%s is already taken\",\n\t\t\t\tFn: func() bool {\n\t\t\t\t\tvar b bool\n\t\t\t\t\tq := tx.Where(\"email = ?\", u.Email)\n\t\t\t\t\tif u.ID != uuid.Nil {\n\t\t\t\t\t\tq = q.Where(\"id != ?\", u.ID)\n\t\t\t\t\t}\n\t\t\t\t\tb, err = q.Exists(u)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\treturn !b\n\t\t\t\t},\n\t\t\t},\n\t\t), err\n\n\t}\n}", "func IsValidAccount(a string) bool {\n\t_, err := NewAccount(a)\n\treturn err == nil\n}", "func (u User) IsValid() []error{\n\tvar errs []error\n\tfirstname := strings.Trim(u.FirstName, \" \")\n\tlastname := strings.Trim(u.LastName, \" \")\n\n\tif firstname != \"\" {\n\t\tif strings.Contains(firstname, \" \"){\n\t\t\terrs = append(errs, errors.New(\"FirstName can't have spaces\"))\n\t\t}\n\t\tif len(firstname) < 2 {\n\t\t\terrs = append(errs, errors.New(\"FirstName must be at least 2 characters\"))\n\t\t}\n\t\tif !helper.IsLetter(firstname) {\n\t\t\terrs = append(errs, errors.New(\"Firstname contains a number\"))\n\t\t}\n\t}\n\n\tif lastname != \"\"{\n\t\tif strings.Contains(lastname, \" \"){\n\t\t\terrs = append(errs, errors.New(\"LastName can't have spaces\"))\n\t\t}\n\n\t\tif len(lastname) < 2 {\n\t\t\terrs = append(errs, errors.New(\"LastName must be at least 2 characters\"))\n\t\t}\n\n\t\tif !helper.IsLetter(lastname) {\n\t\t\terrs = append(errs, errors.New(\"Lastname contains a number\"))\n\t\t}\n\t}\n\n\tif u.Email != \"\" {\n\t\tre := regexp.MustCompile(\"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\")\n\n\t\tif !re.MatchString(u.Email) {\n\t\t\terrs = append(errs, errors.New(\"Email address is not valid\"))\n\t\t}\n\t}\n\n\n\tyear, _, _, _, _, _ := helper.DateDiff(u.DateOfBirth, time.Now())\n\tif year < 18 {\n\t\terrs = append(errs, errors.New(\"You must be 18 or more\"))\n\t}\n\tif len(errs) > 0 {\n\t\treturn errs\n\t}\n\treturn nil\n}", "func (m *BillingProfiles2) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAdviceOfCharge(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyLimit(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyLock(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyNotify(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalLimit(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalLock(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalNotify(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudUseResellerRates(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHandle(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalCharge(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalFreeCash(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalFreeTime(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePeaktimeSpecial(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePeaktimeWeekdays(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrepaid(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrepaidLibrary(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateResellerID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *conversionOptions) validate() error {\r\n\tif o.goalID == 0 && len(o.goalName) == 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute(s): %s or %s\", fieldID, fieldName)\r\n\t} else if o.goalID == 0 && o.tonicPowUserID > 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute: %s\", fieldID)\r\n\t} else if o.tonicPowUserID == 0 && len(o.tncpwSession) == 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute(s): %s or %s\", fieldVisitorSessionGUID, fieldUserID)\r\n\t}\r\n\treturn nil\r\n}", "func (m *CustomerTripletexAccount2) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccountType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAdministrator(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateChartOfAccountsType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateModules(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVatStatusType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (bva BaseVestingAccount) Validate() error {\n\tif !(bva.DelegatedVesting.IsAllLTE(bva.OriginalVesting)) {\n\t\treturn errors.New(\"delegated vesting amount cannot be greater than original vesting amount\")\n\t}\n\treturn bva.BaseAccount.Validate()\n}", "func (uuo *UserUpdateOne) check() error {\n\tif v, ok := uuo.mutation.AccountName(); ok {\n\t\tif err := user.AccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"account_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"account_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.StaffType(); ok {\n\t\tif err := user.StaffTypeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_type\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_type\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.FamilyName(); ok {\n\t\tif err := user.FamilyNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"family_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"family_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.GivenName(); ok {\n\t\tif err := user.GivenNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"given_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"given_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.DisplayName(); ok {\n\t\tif err := user.DisplayNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"display_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"display_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.IDNumber(); ok {\n\t\tif err := user.IDNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"id_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Sex(); ok {\n\t\tif err := user.SexValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"sex\", err: fmt.Errorf(\"ent: validator failed for field \\\"sex\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.PhoneNumber(); ok {\n\t\tif err := user.PhoneNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Address(); ok {\n\t\tif err := user.AddressValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"address\", err: fmt.Errorf(\"ent: validator failed for field \\\"address\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.StaffID(); ok {\n\t\tif err := user.StaffIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_id\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_id\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.PersonalEmail(); ok {\n\t\tif err := user.PersonalEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"personal_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"personal_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.IntranetWorkEmail(); ok {\n\t\tif err := user.IntranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"intranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.ExtranetWorkEmail(); ok {\n\t\tif err := user.ExtranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"extranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"extranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (m *DomainDiscoverAPIAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCid(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (msg MsgAddAdminAccount) ValidateBasic() sdk.Error {\n if msg.AdminAddress.Empty() {\n return sdk.ErrInvalidAddress(msg.AdminAddress.String())\n }\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n return nil\n}", "func init() {\n\taccountFields := schema.Account{}.Fields()\n\t_ = accountFields\n\t// accountDescProvider is the schema descriptor for provider field.\n\taccountDescProvider := accountFields[1].Descriptor()\n\t// account.ProviderValidator is a validator for the \"provider\" field. It is called by the builders before save.\n\taccount.ProviderValidator = accountDescProvider.Validators[0].(func(string) error)\n\t// accountDescEmail is the schema descriptor for email field.\n\taccountDescEmail := accountFields[2].Descriptor()\n\t// account.EmailValidator is a validator for the \"email\" field. It is called by the builders before save.\n\taccount.EmailValidator = accountDescEmail.Validators[0].(func(string) error)\n\t// accountDescPassword is the schema descriptor for password field.\n\taccountDescPassword := accountFields[3].Descriptor()\n\t// account.PasswordValidator is a validator for the \"password\" field. It is called by the builders before save.\n\taccount.PasswordValidator = func() func(string) error {\n\t\tvalidators := accountDescPassword.Validators\n\t\tfns := [...]func(string) error{\n\t\t\tvalidators[0].(func(string) error),\n\t\t\tvalidators[1].(func(string) error),\n\t\t}\n\t\treturn func(password string) error {\n\t\t\tfor _, fn := range fns {\n\t\t\t\tif err := fn(password); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}()\n\t// accountDescLocked is the schema descriptor for locked field.\n\taccountDescLocked := accountFields[4].Descriptor()\n\t// account.DefaultLocked holds the default value on creation for the locked field.\n\taccount.DefaultLocked = accountDescLocked.Default.(bool)\n\t// accountDescConfirmed is the schema descriptor for confirmed field.\n\taccountDescConfirmed := accountFields[5].Descriptor()\n\t// account.DefaultConfirmed holds the default value on creation for the confirmed field.\n\taccount.DefaultConfirmed = accountDescConfirmed.Default.(bool)\n\t// accountDescConfirmationToken is the schema descriptor for confirmation_token field.\n\taccountDescConfirmationToken := accountFields[7].Descriptor()\n\t// account.ConfirmationTokenValidator is a validator for the \"confirmation_token\" field. It is called by the builders before save.\n\taccount.ConfirmationTokenValidator = accountDescConfirmationToken.Validators[0].(func(string) error)\n\t// accountDescRecoveryToken is the schema descriptor for recovery_token field.\n\taccountDescRecoveryToken := accountFields[9].Descriptor()\n\t// account.RecoveryTokenValidator is a validator for the \"recovery_token\" field. It is called by the builders before save.\n\taccount.RecoveryTokenValidator = accountDescRecoveryToken.Validators[0].(func(string) error)\n\t// accountDescOtp is the schema descriptor for otp field.\n\taccountDescOtp := accountFields[11].Descriptor()\n\t// account.OtpValidator is a validator for the \"otp\" field. It is called by the builders before save.\n\taccount.OtpValidator = accountDescOtp.Validators[0].(func(string) error)\n\t// accountDescEmailChange is the schema descriptor for email_change field.\n\taccountDescEmailChange := accountFields[12].Descriptor()\n\t// account.EmailChangeValidator is a validator for the \"email_change\" field. It is called by the builders before save.\n\taccount.EmailChangeValidator = accountDescEmailChange.Validators[0].(func(string) error)\n\t// accountDescEmailChangeToken is the schema descriptor for email_change_token field.\n\taccountDescEmailChangeToken := accountFields[14].Descriptor()\n\t// account.EmailChangeTokenValidator is a validator for the \"email_change_token\" field. It is called by the builders before save.\n\taccount.EmailChangeTokenValidator = accountDescEmailChangeToken.Validators[0].(func(string) error)\n\t// accountDescCreatedAt is the schema descriptor for created_at field.\n\taccountDescCreatedAt := accountFields[18].Descriptor()\n\t// account.DefaultCreatedAt holds the default value on creation for the created_at field.\n\taccount.DefaultCreatedAt = accountDescCreatedAt.Default.(func() time.Time)\n\t// accountDescUpdatedAt is the schema descriptor for updated_at field.\n\taccountDescUpdatedAt := accountFields[19].Descriptor()\n\t// account.DefaultUpdatedAt holds the default value on creation for the updated_at field.\n\taccount.DefaultUpdatedAt = accountDescUpdatedAt.Default.(func() time.Time)\n\t// account.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.\n\taccount.UpdateDefaultUpdatedAt = accountDescUpdatedAt.UpdateDefault.(func() time.Time)\n\t// accountDescID is the schema descriptor for id field.\n\taccountDescID := accountFields[0].Descriptor()\n\t// account.DefaultID holds the default value on creation for the id field.\n\taccount.DefaultID = accountDescID.Default.(func() uuid.UUID)\n\tsessionFields := schema.Session{}.Fields()\n\t_ = sessionFields\n\t// sessionDescCreatedAt is the schema descriptor for created_at field.\n\tsessionDescCreatedAt := sessionFields[2].Descriptor()\n\t// session.DefaultCreatedAt holds the default value on creation for the created_at field.\n\tsession.DefaultCreatedAt = sessionDescCreatedAt.Default.(func() time.Time)\n\t// sessionDescUpdatedAt is the schema descriptor for updated_at field.\n\tsessionDescUpdatedAt := sessionFields[3].Descriptor()\n\t// session.DefaultUpdatedAt holds the default value on creation for the updated_at field.\n\tsession.DefaultUpdatedAt = sessionDescUpdatedAt.Default.(func() time.Time)\n\t// session.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.\n\tsession.UpdateDefaultUpdatedAt = sessionDescUpdatedAt.UpdateDefault.(func() time.Time)\n}", "func (mt AccountCollection) Validate() (err error) {\n\tfor _, e := range mt {\n\t\tif e != nil {\n\t\t\tif err2 := e.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (frm entryForm) Validate() (map[string]string, bool) {\n\terrs := map[string]string{}\n\tg1 := frm.Department != \"\"\n\tif !g1 {\n\t\terrs[\"department\"] = \"Missing department\"\n\t}\n\tg2 := frm.CheckThis\n\tif !g2 {\n\t\terrs[\"check_this\"] = \"You need to comply\"\n\t}\n\tg3 := frm.Items != \"\"\n\tif !g3 {\n\t\terrs[\"items\"] = \"No items\"\n\t}\n\treturn errs, g1 && g2 && g3\n}", "func (vva ValidatorVestingAccount) Validate() error {\n\tif vva.SigningThreshold > 100 || vva.SigningThreshold < 0 {\n\t\treturn errors.New(\"signing threshold must be between 0 and 100\")\n\t}\n\tif vva.ReturnAddress.Equals(vva.Address) {\n\t\treturn errors.New(\"return address cannot be the same as the account address\")\n\t}\n\treturn vva.PeriodicVestingAccount.Validate()\n}", "func (dva DelayedVestingAccount) Validate() error {\n\treturn dva.BaseVestingAccount.Validate()\n}", "func validate(msgs []*LogMsg) {\n\tif !validatePRAMRegistration(msgs) {\n\t\tlog.Fatalf(\"validatePRAMRegistration\\n\")\n\t}\n}", "func (_PermInterface *PermInterfaceCaller) ValidateAccount(opts *bind.CallOpts, _account common.Address, _orgId string) (bool, error) {\n\tvar out []interface{}\n\terr := _PermInterface.contract.Call(opts, &out, \"validateAccount\", _account, _orgId)\n\n\tif err != nil {\n\t\treturn *new(bool), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(bool)).(*bool)\n\n\treturn out0, err\n\n}", "func (ut *RegisterPayload) Validate() (err error) {\n\tif ut.Email == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"email\"))\n\t}\n\tif ut.Password == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"password\"))\n\t}\n\tif ut.FirstName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"first_name\"))\n\t}\n\tif ut.LastName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"last_name\"))\n\t}\n\tif err2 := goa.ValidateFormat(goa.FormatEmail, ut.Email); err2 != nil {\n\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`type.email`, ut.Email, goa.FormatEmail, err2))\n\t}\n\tif utf8.RuneCountInString(ut.Email) < 6 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 6, true))\n\t}\n\tif utf8.RuneCountInString(ut.Email) > 150 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 150, false))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.Password) < 5 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 5, true))\n\t}\n\tif utf8.RuneCountInString(ut.Password) > 100 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 100, false))\n\t}\n\treturn\n}", "func (a *Api) validateError() (err error) {\n\tif a.UserID == 0 {\n\t\treturn a.Errors(ErrorMissingValue, \"user_id\")\n\t}\n\n\tif a.Token == \"\" {\n\t\treturn a.Errors(ErrorMissingValue, \"token\")\n\t}\n\n\treturn\n}", "func (uc *UserCreate) check() error {\n\tif _, ok := uc.mutation.Firstname(); !ok {\n\t\treturn &ValidationError{Name: \"firstname\", err: errors.New(\"ent: missing required field \\\"firstname\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Lastname(); !ok {\n\t\treturn &ValidationError{Name: \"lastname\", err: errors.New(\"ent: missing required field \\\"lastname\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Username(); !ok {\n\t\treturn &ValidationError{Name: \"username\", err: errors.New(\"ent: missing required field \\\"username\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Password(); !ok {\n\t\treturn &ValidationError{Name: \"password\", err: errors.New(\"ent: missing required field \\\"password\\\"\")}\n\t}\n\treturn nil\n}", "func (ac *AreahistoryCreate) check() error {\n\tif _, ok := ac.mutation.WalletID(); !ok {\n\t\treturn &ValidationError{Name: \"WalletID\", err: errors.New(\"ent: missing required field \\\"WalletID\\\"\")}\n\t}\n\tif v, ok := ac.mutation.WalletID(); ok {\n\t\tif err := areahistory.WalletIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"WalletID\", err: fmt.Errorf(\"ent: validator failed for field \\\"WalletID\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.ProvinceNameTH(); ok {\n\t\tif err := areahistory.ProvinceNameTHValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"ProvinceNameTH\", err: fmt.Errorf(\"ent: validator failed for field \\\"ProvinceNameTH\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.DistrictNameTH(); ok {\n\t\tif err := areahistory.DistrictNameTHValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"DistrictNameTH\", err: fmt.Errorf(\"ent: validator failed for field \\\"DistrictNameTH\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.SubDistrict(); ok {\n\t\tif err := areahistory.SubDistrictValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"SubDistrict\", err: fmt.Errorf(\"ent: validator failed for field \\\"SubDistrict\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (_PermInterface *PermInterfaceSession) ValidateAccount(_account common.Address, _orgId string) (bool, error) {\n\treturn _PermInterface.Contract.ValidateAccount(&_PermInterface.CallOpts, _account, _orgId)\n}", "func (uu *UserUpdate) check() error {\n\tif v, ok := uu.mutation.Username(); ok {\n\t\tif err := user.UsernameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"username\", err: fmt.Errorf(\"ent: validator failed for field \\\"username\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Fullname(); ok {\n\t\tif err := user.FullnameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"fullname\", err: fmt.Errorf(\"ent: validator failed for field \\\"fullname\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Password(); ok {\n\t\tif err := user.PasswordValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"password\", err: fmt.Errorf(\"ent: validator failed for field \\\"password\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Email(); ok {\n\t\tif err := user.EmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"email\", err: fmt.Errorf(\"ent: validator failed for field \\\"email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Phone(); ok {\n\t\tif err := user.PhoneValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Bio(); ok {\n\t\tif err := user.BioValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"bio\", err: fmt.Errorf(\"ent: validator failed for field \\\"bio\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Intro(); ok {\n\t\tif err := user.IntroValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intro\", err: fmt.Errorf(\"ent: validator failed for field \\\"intro\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.GithubProfile(); ok {\n\t\tif err := user.GithubProfileValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"github_profile\", err: fmt.Errorf(\"ent: validator failed for field \\\"github_profile\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.ProfilePictureURL(); ok {\n\t\tif err := user.ProfilePictureURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"profile_picture_url\", err: fmt.Errorf(\"ent: validator failed for field \\\"profile_picture_url\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Status(); ok {\n\t\tif err := user.StatusValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"status\", err: fmt.Errorf(\"ent: validator failed for field \\\"status\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (uc *UserCreate) check() error {\n\tif _, ok := uc.mutation.Age(); !ok {\n\t\treturn &ValidationError{Name: \"age\", err: errors.New(\"ent: missing required field \\\"age\\\"\")}\n\t}\n\tif v, ok := uc.mutation.Age(); ok {\n\t\tif err := user.AgeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"age\", err: fmt.Errorf(\"ent: validator failed for field \\\"age\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := uc.mutation.Name(); !ok {\n\t\treturn &ValidationError{Name: \"name\", err: errors.New(\"ent: missing required field \\\"name\\\"\")}\n\t}\n\tif v, ok := uc.mutation.ID(); ok {\n\t\tif err := user.IDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id\", err: fmt.Errorf(\"ent: validator failed for field \\\"id\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (p *PaymentNeed) validate() error {\n\tif p.BeneficiaryID == 0 {\n\t\treturn fmt.Errorf(\"beneficiary ID nul\")\n\t}\n\tif p.Value == 0 {\n\t\treturn fmt.Errorf(\"value nul\")\n\t}\n\treturn nil\n}", "func (r *Result) validate(errMsg *[]string, parentField string) {\n\tjn := resultJsonMap\n\taddErrMessage(errMsg, len(r.Key) > 0 && hasNonEmptyKV(r.Key), \"field '%s' must be non-empty and must not have empty keys or values\", parentField+\".\"+jn[\"Key\"])\n\taddErrMessage(errMsg, hasNonEmptyKV(r.Options), \"field '%s' must not have empty keys or values\", parentField+\".\"+jn[\"Options\"])\n\taddErrMessage(errMsg, regExHexadecimal.MatchString(string(r.Digest)), \"field '%s' must be hexadecimal\", parentField+\".\"+jn[\"Digest\"])\n}", "func CheckAccountResponse(t *testing.T, resp *models.Account, expectedAccount *models.Account) {\n\tif resp.ID != expectedAccount.ID {\n\t\tt.Errorf(\"Response contains wrong ID, got %v expected %v\", resp.ID, expectedAccount.ID)\n\t}\n\tif resp.Type != expectedAccount.Type {\n\t\tt.Errorf(\"Response contains wrong Type, got %v expected %v\", resp.Type, expectedAccount.Type)\n\t}\n\tif resp.OrganisationID != expectedAccount.OrganisationID {\n\t\tt.Errorf(\"Response contains wrong OrganisationID, got %v expected %v\", resp.OrganisationID, expectedAccount.OrganisationID)\n\t}\n\tif resp.Version != expectedAccount.Version {\n\t\tt.Errorf(\"Response contains wrong Version, got %v expected %v\", resp.Version, expectedAccount.Version)\n\t}\n\tif resp.Attributes.Country != expectedAccount.Attributes.Country {\n\t\tt.Errorf(\"Response contains wrong Country, got %v expected %v\", resp.Attributes.Country, expectedAccount.Attributes.Country)\n\t}\n\tif resp.Attributes.BaseCurrency != expectedAccount.Attributes.BaseCurrency {\n\t\tt.Errorf(\"Response contains wrong BaseCurrency, got %v expected %v\", resp.Attributes.BaseCurrency, expectedAccount.Attributes.BaseCurrency)\n\t}\n\tif resp.Attributes.BankID != expectedAccount.Attributes.BankID {\n\t\tt.Errorf(\"Response contains wrong BankID, got %v expected %v\", resp.Attributes.BankID, expectedAccount.Attributes.BankID)\n\t}\n\tif resp.Attributes.BankIDCode != expectedAccount.Attributes.BankIDCode {\n\t\tt.Errorf(\"Response contains wrong BankIDCode, got %v expected %v\", resp.Attributes.BankIDCode, expectedAccount.Attributes.BankIDCode)\n\t}\n\tif resp.Attributes.Bic != expectedAccount.Attributes.Bic {\n\t\tt.Errorf(\"Response contains wrong Bic, got %v expected %v\", resp.Attributes.Bic, expectedAccount.Attributes.Bic)\n\t}\n\tif resp.Attributes.AccountNumber != expectedAccount.Attributes.AccountNumber {\n\t\tt.Errorf(\"Response contains wrong AccountNumber, got %v expected %v\", resp.Attributes.AccountNumber, expectedAccount.Attributes.AccountNumber)\n\t}\n\tif resp.Attributes.CustomerID != expectedAccount.Attributes.CustomerID {\n\t\tt.Errorf(\"Response contains wrong CustomerID, got %v expected %v\", resp.Attributes.CustomerID, expectedAccount.Attributes.CustomerID)\n\t}\n\tif resp.Attributes.FirstName != expectedAccount.Attributes.FirstName {\n\t\tt.Errorf(\"Response contains wrong FirstName, got %v expected %v\", resp.Attributes.FirstName, expectedAccount.Attributes.FirstName)\n\t}\n\tif resp.Attributes.BankAccountName != expectedAccount.Attributes.BankAccountName {\n\t\tt.Errorf(\"Response contains wrong BankAccountName, got %v expected %v\", resp.Attributes.BankAccountName, expectedAccount.Attributes.BankAccountName)\n\t}\n\n\tresponseLength := len(resp.Attributes.AlternativeBankAccountNames)\n\texpectedLength := len(expectedAccount.Attributes.AlternativeBankAccountNames)\n\n\tif responseLength != expectedLength {\n\t\tt.Errorf(\"AlternativeBankAccountNames array is wrong, got %v expected %v\", responseLength, expectedLength)\n\t} else {\n\t\ti := 0\n\t\tfor i < responseLength {\n\t\t\tif resp.Attributes.AlternativeBankAccountNames[i] != expectedAccount.Attributes.AlternativeBankAccountNames[i] {\n\t\t\t\tt.Errorf(\"Response contains wrong AlternativeBankAccountNames, got %v expected %v\", resp.Attributes.AlternativeBankAccountNames[i], expectedAccount.Attributes.AlternativeBankAccountNames[i])\n\t\t\t}\n\t\t\ti = i + 1\n\t\t}\n\t}\n\n\tif resp.Attributes.AlternativeBankAccountNames[0] != expectedAccount.Attributes.AlternativeBankAccountNames[0] {\n\t\tt.Errorf(\"Response contains wrong AlternativeBankAccountNames, got %v expected %v\", resp.Attributes.AlternativeBankAccountNames[0], expectedAccount.Attributes.AlternativeBankAccountNames[0])\n\t}\n\tif resp.Attributes.AccountClassification != expectedAccount.Attributes.AccountClassification {\n\t\tt.Errorf(\"Response contains wrong AccountClassification, got %v expected %v\", resp.Attributes.AccountClassification, expectedAccount.Attributes.AccountClassification)\n\t}\n\tif resp.Attributes.JointAccount != expectedAccount.Attributes.JointAccount {\n\t\tt.Errorf(\"Response contains wrong JointAccount, got %v expected %v\", resp.Attributes.JointAccount, expectedAccount.Attributes.JointAccount)\n\t}\n\tif resp.Attributes.Switched != expectedAccount.Attributes.Switched {\n\t\tt.Errorf(\"Response contains wrong Switched, got %v expected %v\", resp.Attributes.Switched, expectedAccount.Attributes.Switched)\n\t}\n\tif resp.Attributes.AccountMatchingOptOut != expectedAccount.Attributes.AccountMatchingOptOut {\n\t\tt.Errorf(\"Response contains wrong AccountMatchingOptOut, got %v expected %v\", resp.Attributes.AccountMatchingOptOut, expectedAccount.Attributes.AccountMatchingOptOut)\n\t}\n\tif resp.Attributes.Status != expectedAccount.Attributes.Status {\n\t\tt.Errorf(\"Response contains wrong Status, got %v expected %v\", resp.Attributes.Status, expectedAccount.Attributes.Status)\n\t}\n\tif resp.Attributes.SecondaryIdentification != expectedAccount.Attributes.SecondaryIdentification {\n\t\tt.Errorf(\"Response contains wrong SecondaryIdentification, got %v expected %v\", resp.Attributes.SecondaryIdentification, expectedAccount.Attributes.SecondaryIdentification)\n\t}\n}", "func (_PermInterface *PermInterfaceCallerSession) ValidateAccount(_account common.Address, _orgId string) (bool, error) {\n\treturn _PermInterface.Contract.ValidateAccount(&_PermInterface.CallOpts, _account, _orgId)\n}", "func (cfg fromCFN) validate() error {\n\tif cfg.isEmpty() {\n\t\treturn nil\n\t}\n\tif len(aws.StringValue(cfg.Name)) == 0 {\n\t\treturn errors.New(\"name cannot be an empty string\")\n\t}\n\treturn nil\n}", "func isAccountFlagsValid(accountId string) bool {\n\taccount := GetStellarAccount(accountId)\n\treturn account.Flags.AuthRequired && account.Flags.AuthRevocable\n}", "func validate(name, gender string) error {\n\tif name == \"\" {\n\t\treturn &inputError{message: \"name is missing\", missingField: \"name\"}\n\t}\n\tif gender == \"\" {\n\t\treturn &inputError{message: \"gender is missing\", missingField: \"gender\"}\n\t}\n\treturn nil\n}", "func (user *User) Validate() *errors.RestErr {\n\t// Delete spaces at first_name, last_name and email before saving\n\tuser.FirstName = strings.TrimSpace(user.FirstName)\n\tuser.LastName = strings.TrimSpace(user.LastName)\n\tuser.Email = strings.TrimSpace(strings.ToLower(user.Email))\n\n\tif user.Email == \"\"{\n\t\treturn errors.NewBadRequestError(\"Email addres is required\")\n\t}\n\tif !ValidateEmail(user.Email){\n\t\treturn errors.NewBadRequestError(\"Wrong email format\")\n\t}\n\tif strings.TrimSpace(user.Password)== \"\" || len(strings.TrimSpace(user.Password)) < 8{\n\t\treturn errors.NewBadRequestError(\"Password is required and password length must be higher than 8 characters\")\n\t}\n\n\n\treturn nil\n}", "func checkAccount(t *testing.T, tree *avl.Tree, id AccountID, expectedBalance, expectedReward, expectedStake *uint64) {\n\tvar balance, reward, stake uint64\n\tvar exist bool\n\n\tbalance, exist = ReadAccountBalance(tree, id)\n\tassert.Equal(t, expectedBalance != nil, exist, \"account ID: %x\", id)\n\treward, exist = ReadAccountReward(tree, id)\n\tassert.Equal(t, expectedReward != nil, exist, \"account ID: %x\", id)\n\tstake, exist = ReadAccountStake(tree, id)\n\tassert.Equal(t, expectedStake != nil, exist, \"account ID: %x\", id)\n\n\tif expectedBalance != nil {\n\t\tassert.Equal(t, balance, *expectedBalance, \"account ID: %x\", id)\n\t}\n\n\tif expectedReward != nil {\n\t\tassert.Equal(t, reward, *expectedReward, \"account ID: %x\", id)\n\t}\n\n\tif expectedStake != nil {\n\t\tassert.Equal(t, stake, *expectedStake, \"account ID: %x\", id)\n\t}\n}", "func ValidBaseInfo(ctx *gin.Context) {\n\tres := helper.Res{}\n\n\tvar baseInfo BaseInfo\n\tif err := ctx.Bind(&baseInfo); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\t// user does exist\n\tif _, err := models.FindOneByUsername(baseInfo.Username); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\t// the email of user does exist\n\tif _, err := models.FindOneByEmail(baseInfo.Email); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\tres.Success(gin.H{\n\t\t\"isValid\": true,\n\t}).Send(ctx)\n}", "func (w Warrant) Validate() error {\n\tif len(w.FirstName) == 0 {\n\t\treturn errors.New(\"missing first name element\")\n\t}\n\tif len(w.LastName) == 0 {\n\t\treturn errors.New(\"missing last name element\")\n\t}\n\tif len(w.Civility) == 0 {\n\t\treturn errors.New(\"missing civility element\")\n\t}\n\treturn nil\n}", "func (va ClawbackVestingAccount) Validate() error {\n\tif va.GetStartTime() >= va.GetEndTime() {\n\t\treturn errors.New(\"vesting start-time must be before end-time\")\n\t}\n\n\tlockupEnd := va.StartTime\n\tlockupCoins := sdk.NewCoins()\n\tfor _, p := range va.LockupPeriods {\n\t\tlockupEnd += p.Length\n\t\tlockupCoins = lockupCoins.Add(p.Amount...)\n\t}\n\tif lockupEnd > va.EndTime {\n\t\treturn errors.New(\"lockup schedule extends beyond account end time\")\n\t}\n\tif !coinEq(lockupCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in lockup periods\")\n\t}\n\n\tvestingEnd := va.StartTime\n\tvestingCoins := sdk.NewCoins()\n\tfor _, p := range va.VestingPeriods {\n\t\tvestingEnd += p.Length\n\t\tvestingCoins = vestingCoins.Add(p.Amount...)\n\t}\n\tif vestingEnd > va.EndTime {\n\t\treturn errors.New(\"vesting schedule exteds beyond account end time\")\n\t}\n\tif !coinEq(vestingCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in vesting periods\")\n\t}\n\n\treturn va.BaseVestingAccount.Validate()\n}", "func (ut *registerPayload) Validate() (err error) {\n\tif ut.Email == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"email\"))\n\t}\n\tif ut.Password == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"password\"))\n\t}\n\tif ut.FirstName == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"first_name\"))\n\t}\n\tif ut.LastName == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"last_name\"))\n\t}\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`request.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Email != nil {\n\t\tif utf8.RuneCountInString(*ut.Email) < 6 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.email`, *ut.Email, utf8.RuneCountInString(*ut.Email), 6, true))\n\t\t}\n\t}\n\tif ut.Email != nil {\n\t\tif utf8.RuneCountInString(*ut.Email) > 150 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.email`, *ut.Email, utf8.RuneCountInString(*ut.Email), 150, false))\n\t\t}\n\t}\n\tif ut.FirstName != nil {\n\t\tif utf8.RuneCountInString(*ut.FirstName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.first_name`, *ut.FirstName, utf8.RuneCountInString(*ut.FirstName), 1, true))\n\t\t}\n\t}\n\tif ut.FirstName != nil {\n\t\tif utf8.RuneCountInString(*ut.FirstName) > 200 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.first_name`, *ut.FirstName, utf8.RuneCountInString(*ut.FirstName), 200, false))\n\t\t}\n\t}\n\tif ut.LastName != nil {\n\t\tif utf8.RuneCountInString(*ut.LastName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.last_name`, *ut.LastName, utf8.RuneCountInString(*ut.LastName), 1, true))\n\t\t}\n\t}\n\tif ut.LastName != nil {\n\t\tif utf8.RuneCountInString(*ut.LastName) > 200 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.last_name`, *ut.LastName, utf8.RuneCountInString(*ut.LastName), 200, false))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) < 5 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 5, true))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) > 100 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 100, false))\n\t\t}\n\t}\n\treturn\n}", "func ValidateWarriorAccount(name string, email string, pwd1 string, pwd2 string) (WarriorName string, WarriorEmail string, WarriorPassword string, validateErr error) {\n\tv := validator.New()\n\ta := warriorAccount{\n\t\tName: name,\n\t\tEmail: email,\n\t\tPassword1: pwd1,\n\t\tPassword2: pwd2,\n\t}\n\terr := v.Struct(a)\n\n\treturn name, email, pwd1, err\n}", "func validateAttributes(attrs map[string]models.ValueType, allAttrs bool) error {\n\t// TBD: to finalize the attributes specifics\n\tattrsOK := false\n\tif vt, ok := attrs[AttrCred]; ok && vt.Kind == com.ValueTypeSecret {\n\t\tif !allAttrs {\n\t\t\tattrsOK = true\n\t\t} else if vt, ok := attrs[AttrZone]; ok && vt.Kind == com.ValueTypeString {\n\t\t\tattrsOK = true\n\t\t}\n\t}\n\tif !attrsOK {\n\t\tmsg := \"required domain attributes missing or invalid: need \" + AttrCred + \"[E]\"\n\t\tif allAttrs {\n\t\t\tmsg += \", \" + AttrZone + \"[S]\"\n\t\t}\n\t\treturn fmt.Errorf(msg)\n\t}\n\treturn nil\n}", "func (cc *CompanyCreate) check() error {\n\tif _, ok := cc.mutation.CreatedAt(); !ok {\n\t\treturn &ValidationError{Name: \"created_at\", err: errors.New(`ent: missing required field \"created_at\"`)}\n\t}\n\tif _, ok := cc.mutation.UpdatedAt(); !ok {\n\t\treturn &ValidationError{Name: \"updated_at\", err: errors.New(`ent: missing required field \"updated_at\"`)}\n\t}\n\tif _, ok := cc.mutation.Name(); !ok {\n\t\treturn &ValidationError{Name: \"name\", err: errors.New(`ent: missing required field \"name\"`)}\n\t}\n\tif v, ok := cc.mutation.Name(); ok {\n\t\tif err := company.NameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"name\", err: fmt.Errorf(`ent: validator failed for field \"name\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Overview(); !ok {\n\t\treturn &ValidationError{Name: \"overview\", err: errors.New(`ent: missing required field \"overview\"`)}\n\t}\n\tif v, ok := cc.mutation.Overview(); ok {\n\t\tif err := company.OverviewValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"overview\", err: fmt.Errorf(`ent: validator failed for field \"overview\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Website(); !ok {\n\t\treturn &ValidationError{Name: \"website\", err: errors.New(`ent: missing required field \"website\"`)}\n\t}\n\tif v, ok := cc.mutation.Website(); ok {\n\t\tif err := company.WebsiteValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"website\", err: fmt.Errorf(`ent: validator failed for field \"website\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.LogoURL(); !ok {\n\t\treturn &ValidationError{Name: \"logo_url\", err: errors.New(`ent: missing required field \"logo_url\"`)}\n\t}\n\tif v, ok := cc.mutation.LogoURL(); ok {\n\t\tif err := company.LogoURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"logo_url\", err: fmt.Errorf(`ent: validator failed for field \"logo_url\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Size(); !ok {\n\t\treturn &ValidationError{Name: \"size\", err: errors.New(`ent: missing required field \"size\"`)}\n\t}\n\tif v, ok := cc.mutation.Size(); ok {\n\t\tif err := company.SizeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"size\", err: fmt.Errorf(`ent: validator failed for field \"size\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.FoundedAt(); !ok {\n\t\treturn &ValidationError{Name: \"founded_at\", err: errors.New(`ent: missing required field \"founded_at\"`)}\n\t}\n\tif v, ok := cc.mutation.FoundedAt(); ok {\n\t\tif err := company.FoundedAtValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"founded_at\", err: fmt.Errorf(`ent: validator failed for field \"founded_at\": %w`, err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (m *ProviderAccountPreferences) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func ValidateGetAccountInternalResponseBody(body *GetAccountInternalResponseBody) (err error) {\n\tif body.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"name\", \"body\"))\n\t}\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Message == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"message\", \"body\"))\n\t}\n\tif body.Temporary == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"temporary\", \"body\"))\n\t}\n\tif body.Timeout == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"timeout\", \"body\"))\n\t}\n\tif body.Fault == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"fault\", \"body\"))\n\t}\n\treturn\n}", "func (o *Virtualserver) validate(dbRecord *common.DbRecord) (ok bool, err error) {\n\t////////////////////////////////////////////////////////////////////////////\n\t// Marshal data interface.\n\t////////////////////////////////////////////////////////////////////////////\n\tvar data virtualserver.Data\n\terr = shared.MarshalInterface(dbRecord.Data, &data)\n\tif err != nil {\n\t\treturn\n\t}\n\t////////////////////////////////////////////////////////////////////////////\n\t// Test required fields.\n\t////////////////////////////////////////////////////////////////////////////\n\tok = true\n\trequired := make(map[string]bool)\n\trequired[\"ProductCode\"] = false\n\trequired[\"IP\"] = false\n\trequired[\"Port\"] = false\n\trequired[\"LoadBalancerIP\"] = false\n\trequired[\"Name\"] = false\n\t////////////////////////////////////////////////////////////////////////////\n\tif data.ProductCode != 0 {\n\t\trequired[\"ProductCode\"] = true\n\t}\n\tif len(dbRecord.LoadBalancerIP) > 0 {\n\t\trequired[\"LoadBalancerIP\"] = true\n\t}\n\tif len(data.Ports) != 0 {\n\t\trequired[\"Port\"] = true\n\t}\n\tif data.IP != \"\" {\n\t\trequired[\"IP\"] = true\n\t}\n\tif data.Name != \"\" {\n\t\trequired[\"Name\"] = true\n\t}\n\tfor _, val := range required {\n\t\tif val == false {\n\t\t\tok = false\n\t\t}\n\t}\n\tif !ok {\n\t\terr = fmt.Errorf(\"missing required fields - %+v\", required)\n\t}\n\treturn\n}", "func (user *User) Validate(action string) map[string]string {\n\tvar errMessages = make(map[string]string)\n\tvar err error\n\n\tswitch strings.ToLower(action) {\n\tcase \"update\":\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"invalid email\"\n\t\t\t}\n\t\t}\n\tcase \"login\":\n\t\tif user.Password == \"\" {\n\t\t\terrMessages[\"password_required\"] = \"password is required\"\n\t\t}\n\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"invalid email\"\n\t\t\t}\n\t\t}\n\tcase \"forgotpassword\":\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"please provide a valid email\"\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tif user.FirstName == \"\" {\n\t\t\terrMessages[\"firstname_required\"] = \"first name is required\"\n\t\t}\n\n\t\tif user.LastName == \"\" {\n\t\t\terrMessages[\"lastname_required\"] = \"last name is required\"\n\t\t}\n\n\t\tif user.Password == \"\" {\n\t\t\terrMessages[\"password_required\"] = \"password is required\"\n\t\t}\n\n\t\tif user.Password != \"\" && len(user.Password) < 6 {\n\t\t\terrMessages[\"invalid_password\"] = \"password should be at least 6 characters\"\n\t\t}\n\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email is required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"please provide a valid email\"\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errMessages\n}", "func (a *Application) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: a.FirstName, Name: \"FirstName\"},\n\t\t&validators.StringIsPresent{Field: a.LastName, Name: \"LastName\"},\n\t), nil\n}", "func (uuo *UserUpdateOne) check() error {\n\tif v, ok := uuo.mutation.Username(); ok {\n\t\tif err := user.UsernameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"username\", err: fmt.Errorf(\"ent: validator failed for field \\\"username\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Fullname(); ok {\n\t\tif err := user.FullnameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"fullname\", err: fmt.Errorf(\"ent: validator failed for field \\\"fullname\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Password(); ok {\n\t\tif err := user.PasswordValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"password\", err: fmt.Errorf(\"ent: validator failed for field \\\"password\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Email(); ok {\n\t\tif err := user.EmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"email\", err: fmt.Errorf(\"ent: validator failed for field \\\"email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Phone(); ok {\n\t\tif err := user.PhoneValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Bio(); ok {\n\t\tif err := user.BioValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"bio\", err: fmt.Errorf(\"ent: validator failed for field \\\"bio\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Intro(); ok {\n\t\tif err := user.IntroValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intro\", err: fmt.Errorf(\"ent: validator failed for field \\\"intro\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.GithubProfile(); ok {\n\t\tif err := user.GithubProfileValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"github_profile\", err: fmt.Errorf(\"ent: validator failed for field \\\"github_profile\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.ProfilePictureURL(); ok {\n\t\tif err := user.ProfilePictureURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"profile_picture_url\", err: fmt.Errorf(\"ent: validator failed for field \\\"profile_picture_url\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Status(); ok {\n\t\tif err := user.StatusValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"status\", err: fmt.Errorf(\"ent: validator failed for field \\\"status\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (r updateReq) Validate() error {\n\terr := r.addReq.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif r.ServiceAccountID != r.Body.ID {\n\t\treturn fmt.Errorf(\"service account ID mismatch, you requested to update ServiceAccount = %s but body contains ServiceAccount = %s\", r.ServiceAccountID, r.Body.ID)\n\t}\n\treturn nil\n}", "func (bu *BankdetailUpdate) check() error {\n\tif v, ok := bu.mutation.BankAccountNo(); ok {\n\t\tif err := bankdetail.BankAccountNoValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_AccountNo\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_AccountNo\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := bu.mutation.BankName(); ok {\n\t\tif err := bankdetail.BankNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_Name\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_Name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := bu.mutation.BankAccountName(); ok {\n\t\tif err := bankdetail.BankAccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_AccountName\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_AccountName\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (rc *RentalCreate) check() error {\n\tif _, ok := rc.mutation.Date(); !ok {\n\t\treturn &ValidationError{Name: \"date\", err: errors.New(`ent: missing required field \"Rental.date\"`)}\n\t}\n\tif _, ok := rc.mutation.UserID(); !ok {\n\t\treturn &ValidationError{Name: \"user_id\", err: errors.New(`ent: missing required field \"Rental.user_id\"`)}\n\t}\n\tif _, ok := rc.mutation.CarID(); !ok {\n\t\treturn &ValidationError{Name: \"car_id\", err: errors.New(`ent: missing required field \"Rental.car_id\"`)}\n\t}\n\tif _, ok := rc.mutation.UserID(); !ok {\n\t\treturn &ValidationError{Name: \"user\", err: errors.New(`ent: missing required edge \"Rental.user\"`)}\n\t}\n\tif _, ok := rc.mutation.CarID(); !ok {\n\t\treturn &ValidationError{Name: \"car\", err: errors.New(`ent: missing required edge \"Rental.car\"`)}\n\t}\n\treturn nil\n}", "func (m *ContactAccountAttributesAccountWith) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *Customer) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAutoCollection(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBalances(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingAddress(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDateMode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDayOfWeek(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDayOfWeekMode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateContacts(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEntityCode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudFlag(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethod(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReferralUrls(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTaxability(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *OBWriteInternational3DataInitiationDebtorAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateIdentification(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSchemeName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSecondaryIdentification(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *ClusterVcenterAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (e *RetrieveBalance) Validate(\n\tr *http.Request,\n) error {\n\tctx := r.Context()\n\n\t// Validate id.\n\tid, owner, token, err := ValidateID(ctx, pat.Param(r, \"balance\"))\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\te.ID = *id\n\te.Token = *token\n\te.Owner = *owner\n\n\treturn nil\n}", "func (u *User) Validate() ([]app.Invalid, error) {\n\tvar inv []app.Invalid\n\n\tif u.UserType == 0 {\n\t\tinv = append(inv, app.Invalid{Fld: \"UserType\", Err: \"The value of UserType cannot be 0.\"})\n\t}\n\n\tif u.FirstName == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"FirstName\", Err: \"A value of FirstName cannot be empty.\"})\n\t}\n\n\tif u.LastName == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"LastName\", Err: \"A value of LastName cannot be empty.\"})\n\t}\n\n\tif u.Email == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"Email\", Err: \"A value of Email cannot be empty.\"})\n\t}\n\n\tif u.Company == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"Company\", Err: \"A value of Company cannot be empty.\"})\n\t}\n\n\tif len(u.Addresses) == 0 {\n\t\tinv = append(inv, app.Invalid{Fld: \"Addresses\", Err: \"There must be at least one address.\"})\n\t} else {\n\t\tfor _, ua := range u.Addresses {\n\t\t\tif va, err := ua.Validate(); err != nil {\n\t\t\t\tinv = append(inv, va...)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(inv) > 0 {\n\t\treturn inv, errors.New(\"Validation failures identified\")\n\t}\n\n\treturn nil, nil\n}", "func ValidateGetAccountResponseBody(body *GetAccountResponseBody) (err error) {\n\tif body.Account != nil {\n\t\tif err2 := ValidateRelayerAccountResponseBody(body.Account); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\treturn\n}", "func (p *Pass) FieldsValid() bool {\n\tfmt.Printf(\"validating: \")\n\tvalid := true\n\tfor k, v := range *p {\n\t\tfmt.Printf(\"%v...\", k)\n\t\tv := isFieldValid(k, v)\n\t\tvalid = valid && v\n\t\tif v {\n\t\t\tfmt.Printf(\"VALID \")\n\t\t} else {\n\t\t\tfmt.Printf(\"INVALID \")\n\t\t}\n\t}\n\n\tfmt.Println(\"\")\n\treturn valid\n}", "func (t AuthToken) Validate() error {\n\t// Holds names of empty fields\n\tempty := []string{}\n\n\t// Check user id\n\tif len(t.UserID) == 0 {\n\t\tempty = append(empty, \"UserID\")\n\t}\n\n\t// Check device id\n\tif len(t.DeviceID) == 0 {\n\t\tempty = append(empty, \"DeviceID\")\n\t}\n\n\t// Check if any empty fields\n\tif len(empty) != 0 {\n\t\treturn fmt.Errorf(\"the following fields were empty: %s\",\n\t\t\tStrings.join(empty))\n\t}\n\n\t// All good\n\treturn nil\n}", "func (p *Passport) ValidateStrict(input string) {\r\n\tbyr := regexp.MustCompile(`byr:(\\d*)`)\r\n\tif byr.MatchString(input) {\r\n\t\tmatches := byr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], byrMin, byrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.byr = f\r\n\t\t}\r\n\t}\r\n\r\n\tiyr := regexp.MustCompile(`iyr:(\\d*)`)\r\n\tif iyr.MatchString(input) {\r\n\t\tmatches := iyr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], iyrMin, iyrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.iyr = f\r\n\t\t}\r\n\t}\r\n\r\n\teyr := regexp.MustCompile(`eyr:(\\d*)`)\r\n\tif eyr.MatchString(input) {\r\n\t\tmatches := eyr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], eyrMin, eyrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.eyr = f\r\n\t\t}\r\n\t}\r\n\r\n\thgt := regexp.MustCompile(`hgt:(\\d*)(cm|in)?`)\r\n\tif hgt.MatchString(input) {\r\n\t\tmatches := hgt.FindStringSubmatch(input)\r\n\t\tf, err := NewHeightField(matches[1], matches[2])\r\n\t\tif err == nil {\r\n\t\t\tp.hgt = f\r\n\t\t}\r\n\t}\r\n\r\n\thcl := regexp.MustCompile(`hcl:(#[a-f0-9]*)`)\r\n\tif hcl.MatchString(input) {\r\n\t\tmatches := hcl.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], hclExp)\r\n\t\tif err == nil {\r\n\t\t\tp.hcl = f\r\n\t\t}\r\n\t}\r\n\r\n\tecl := regexp.MustCompile(`ecl:(\\w*)`)\r\n\tif ecl.MatchString(input) {\r\n\t\tmatches := ecl.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], eclExp)\r\n\t\tif err == nil {\r\n\t\t\tp.ecl = f\r\n\t\t}\r\n\t}\r\n\r\n\tpid := regexp.MustCompile(`pid:(\\d*)`)\r\n\tif pid.MatchString(input) {\r\n\t\tmatches := pid.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], pidExp)\r\n\t\tif err == nil {\r\n\t\t\tp.pid = f\r\n\t\t}\r\n\t}\r\n}", "func (u *User) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t&validators.StringIsPresent{Field: u.Nickname, Name: \"Nickname\"},\n\t\t&validators.UUIDIsPresent{Field: u.UUID, Name: \"UUID\"},\n\t\t&NullsStringIsURL{Field: u.AuthPhotoURL, Name: \"AuthPhotoURL\"},\n\t\t&domain.StringIsVisible{Field: u.Nickname, Name: \"Nickname\"},\n\t), nil\n}", "func (r *registrationRequest) isValid() error {\n\n\t//check recaptcha\n\trc := recaptcha.R{Secret: config.CaptchaSecretKey}\n\tif !rc.VerifyResponse(r.Captcha) {\n\t\treturn fmt.Errorf(\"ReCaptcha error: %s\", strings.Join(rc.LastError()[1:], \", \"))\n\t}\n\n\t// check if any of this is empty\n\tif r.Email == \"\" || r.Password == \"\" || r.PasswordConfirmation == \"\" ||\n\t\tr.First == \"\" || r.Last == \"\" {\n\t\treturn fmt.Errorf(\"%s\\n\", \"You entered incomplete data. First and last name, email and \"+\n\t\t\t\"password are mandatory fields.\")\n\t}\n\n\t// check if the password match and that the length is at least 8 chars\n\treturn passwordsAreValid(r.Password, r.PasswordConfirmation)\n}", "func (i *infoOptions) validate() error {\n\t// date-field required\n\tif len(i.DateField) == 0 {\n\t\treturn errors.New(`date-field required`)\n\t}\n\n\t// date-field index value if sep is present\n\tif len(i.Sep) > 0 {\n\t\t// attempt to convert DateField to int\n\t\tvar err error\n\t\t_, err = strconv.Atoi(i.DateField)\n\t\tif err != nil {\n\t\t\treturn errors.New(`date-field must be an integer when using a csv field separator`)\n\t\t}\n\t}\n\n\t// dest-template required\n\tif i.DestTemplate == \"\" {\n\t\treturn errors.New(`dest-template required`)\n\t}\n\n\treturn nil\n}", "func (p paymentJson) Validate() error {\n\tif p.AccountId == \"\" {\n\t\treturn errors.New(\"missing customer id\")\n\t}\n\tif p.Amount == 0 {\n\t\treturn errors.New(\"missing amount\")\n\t}\n\treturn nil\n}", "func Validation(a User) error {\n\tfmt.Println(\"user :: \", a)\n\tvar rxEmail = regexp.MustCompile(\"^[a-zA-Z0-9.!#$%&'*+\\\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\")\n\tswitch {\n\tcase len(strings.TrimSpace(a.Password)) == 0:\n\t\treturn ErrPasswordInvalid\n\tcase len(strings.TrimSpace(a.Email)) == 0 || !rxEmail.MatchString(a.Email):\n\t\treturn ErrEmailInvalid\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (account *DatabaseAccount) createValidations() []func() (admission.Warnings, error) {\n\treturn []func() (admission.Warnings, error){account.validateResourceReferences, account.validateSecretDestinations}\n}" ]
[ "0.6950377", "0.6660194", "0.6604518", "0.660115", "0.6589453", "0.6474401", "0.6469365", "0.6463922", "0.64215875", "0.63889915", "0.6362919", "0.63358384", "0.6252108", "0.62329525", "0.6229978", "0.61784095", "0.61675555", "0.61494285", "0.6107046", "0.6084981", "0.6062506", "0.6018709", "0.59835136", "0.5935781", "0.59250987", "0.5920425", "0.5918846", "0.5906061", "0.58879864", "0.5874278", "0.5862281", "0.5844713", "0.5843288", "0.58394945", "0.58318245", "0.58267343", "0.5805197", "0.5782027", "0.577867", "0.5762948", "0.57397187", "0.57109004", "0.567482", "0.5670878", "0.5664908", "0.5659827", "0.56587", "0.5648205", "0.5621579", "0.55948484", "0.55917954", "0.55910474", "0.5587459", "0.55859625", "0.55767894", "0.5549079", "0.5528815", "0.5525437", "0.5523396", "0.551239", "0.55084354", "0.55050844", "0.54942113", "0.54916596", "0.5487635", "0.5478365", "0.54646176", "0.54524314", "0.54512787", "0.5443251", "0.54331243", "0.5430431", "0.54267573", "0.54245096", "0.5422896", "0.54207206", "0.54192007", "0.54148257", "0.540501", "0.5398671", "0.5397307", "0.5396947", "0.5394909", "0.53946984", "0.53905594", "0.53878796", "0.5384738", "0.5380616", "0.53800863", "0.53762895", "0.5367286", "0.5357383", "0.5353596", "0.5347578", "0.5342094", "0.5340789", "0.53367335", "0.5334526", "0.5331692", "0.5330748", "0.532834" ]
0.0
-1
NewClawbackVestingAccount returns a new ClawbackVestingAccount
func NewClawbackVestingAccount(baseAcc *authtypes.BaseAccount, funder sdk.AccAddress, originalVesting sdk.Coins, startTime int64, lockupPeriods, vestingPeriods Periods) *ClawbackVestingAccount { // copy and align schedules to avoid mutating inputs lp := make(Periods, len(lockupPeriods)) copy(lp, lockupPeriods) vp := make(Periods, len(vestingPeriods)) copy(vp, vestingPeriods) _, endTime := AlignSchedules(startTime, startTime, lp, vp) baseVestingAcc := &BaseVestingAccount{ BaseAccount: baseAcc, OriginalVesting: originalVesting, EndTime: endTime, } return &ClawbackVestingAccount{ BaseVestingAccount: baseVestingAcc, FunderAddress: funder.String(), StartTime: startTime, LockupPeriods: lp, VestingPeriods: vp, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func MakeNewAccount(name string) (*MyAccount, error) {\n\tkeys, err := NewKeypair()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &MyAccount{\n\t\tFields: make(map[string]string),\n\t\tKeys: keys,\n\t\tName: name,\n\t}, nil\n}", "func (c *CoinTest) newAccount(stub shim.ChaincodeStubInterface, args []string) pb.Response {\r\n\tvar id string\r\n\tvar asset int\r\n\tvar err error\r\n\r\n\tif len(args) == 1{\r\n\t\tid = args[0]\r\n\t\tasset = 0\r\n\t}else if len(args) == 2{\r\n\t\tid = args[0]\r\n\t\t//asset, err = strconv.Atoi(args[1])\r\n\t\t//if err != nil{\r\n\t\t//\treturn shim.Error(\"Invalid asset amount, expecting a integer value\")\r\n\t\t//}\r\n\t\tasset = 0;\r\n\t}else{\r\n\t\treturn shim.Error(\"Incorrect number of arguments.\")\r\n\t}\r\n\r\n\t//deliver 0 number of TolakCoin to user\r\n\ttolakCoin.Token.Deliver(token.Address(id), int(asset))\r\n\r\n\t//write to ledger\r\n\terr = stub.PutState(id, []byte(strconv.Itoa(asset)))\r\n\tif err != nil{\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\treturn shim.Success(nil)\r\n}", "func newAccount() *Account {\n\treturn &Account{\n\t\tblocks: make(map[string]uint64),\n\t}\n}", "func (ws *WebServer) NewAccount(c *gin.Context) {\n\tnetwork := ws.nodeConfig.GetNetwork()\n\tif network == \"\" {\n\t\tReturnError(c, 500, ErrorNoNetwork.Error())\n\t\treturn\n\t}\n\tn := sdk.Testnet\n\tif network == \"bitmark\" {\n\t\tn = sdk.Livenet\n\t}\n\tseedFile := filepath.Join(ws.rootPath, \"bitmarkd\", network, \"proof.sign\")\n\tif _, err := os.Stat(seedFile); err == nil {\n\t\tReturnError(c, 500, ErrorNoSeedFile.Error())\n\t\treturn\n\t}\n\n\ta, err := sdk.NewAccount(n)\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorCreateAccount.Error())\n\t\treturn\n\t}\n\tseed := a.Seed()\n\n\tf, err := os.OpenFile(seedFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600)\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorOpenSeedFile.Error())\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\t_, err = f.WriteString(fmt.Sprintf(\"SEED:%s\", seed))\n\tif err != nil {\n\t\tReturnError(c, 500, ErrorToWriteSeedFile.Error())\n\t\treturn\n\t}\n\tws.SetAccount(a.AccountNumber(), seed, network) // Record in AccountInfo in memory\n\terr = ws.saveAcct()\n\tif nil != err {\n\t\tReturnError(c, 500, ErrorAutoSaveAccount.Error())\n\t\treturn\n\n\t}\n\tc.JSON(200, map[string]interface{}{\n\t\t\"ok\": 1,\n\t})\n}", "func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc exported.Account) exported.Account {\n\t// FIXME: update account number\n\treturn acc\n}", "func NewBaseVestingAccount(baseAccount *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *BaseVestingAccount {\n\treturn &BaseVestingAccount{\n\t\tBaseAccount: baseAccount,\n\t\tOriginalVesting: originalVesting,\n\t\tDelegatedFree: sdk.NewCoins(),\n\t\tDelegatedVesting: sdk.NewCoins(),\n\t\tEndTime: endTime,\n\t}\n}", "func NewFundedAccount() *keypair.Full {\n\tkp, err := keypair.Random()\n\tif err != nil {\n\t\tlog.Fatal(err, \"generating random keypair\")\n\t}\n\terr = FundAccount(kp.Address())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"successfully funded %s\", kp.Address())\n\treturn kp\n}", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func (e Account) EntNew() ent.Ent { return &Account{} }", "func NewAccount(user, apiKey string) *Account {\n\treturn &Account{user: user, apiKey: apiKey}\n}", "func NewDelayedVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *DelayedVestingAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &DelayedVestingAccount{baseVestingAcc}\n}", "func (w *Wallet) NewAccount(index *uint32) (a *Account, err error) {\n\tindex2 := w.nextIndex\n\tif index != nil {\n\t\tindex2 = *index\n\t}\n\ta = &Account{w: w, index: index2}\n\tif err = w.impl.deriveAccount(a); err != nil {\n\t\treturn\n\t}\n\tpubkeyToAddress := util.PubkeyToAddress\n\tif w.isBanano {\n\t\tpubkeyToAddress = util.PubkeyToBananoAddress\n\t}\n\tif a.address, err = pubkeyToAddress(a.pubkey); err != nil {\n\t\treturn\n\t}\n\tif index == nil {\n\t\tw.nextIndex++\n\t}\n\tif _, ok := w.accounts[a.address]; !ok {\n\t\tw.accounts[a.address] = a\n\t} else if index == nil {\n\t\treturn w.NewAccount(nil)\n\t}\n\treturn\n}", "func (*ACMEIssuer) newAccount(email string) (acme.Account, error) {\n\tvar acct acme.Account\n\tif email != \"\" {\n\t\tacct.Contact = []string{\"mailto:\" + email} // TODO: should we abstract the contact scheme?\n\t}\n\tprivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tif err != nil {\n\t\treturn acct, fmt.Errorf(\"generating private key: %v\", err)\n\t}\n\tacct.PrivateKey = privateKey\n\treturn acct, nil\n}", "func NewContinuousVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime, endTime int64) *ContinuousVestingAccount {\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ContinuousVestingAccount{\n\t\tStartTime: startTime,\n\t\tBaseVestingAccount: baseVestingAcc,\n\t}\n}", "func NewAccount(\n\tconfig *accounts.AccountConfig,\n\taccountCoin *Coin,\n\thttpClient *http.Client,\n\tlog *logrus.Entry,\n) *Account {\n\tlog = log.WithField(\"group\", \"eth\").\n\t\tWithFields(logrus.Fields{\"coin\": accountCoin.String(), \"code\": config.Config.Code, \"name\": config.Config.Name})\n\tlog.Debug(\"Creating new account\")\n\n\taccount := &Account{\n\t\tBaseAccount: accounts.NewBaseAccount(config, accountCoin, log),\n\t\tcoin: accountCoin,\n\t\tdbSubfolder: \"\", // set in Initialize()\n\t\tsigningConfiguration: nil,\n\t\thttpClient: httpClient,\n\t\tbalance: coin.NewAmountFromInt64(0),\n\n\t\tenqueueUpdateCh: make(chan struct{}),\n\t\tquitChan: make(chan struct{}),\n\n\t\tlog: log,\n\t}\n\n\treturn account\n}", "func NewAccount(val string) AccountField {\n\treturn AccountField{quickfix.FIXString(val)}\n}", "func NewAccount(id string, name string, primary bool, type_ string, currency Currency, balance AccountBalance, createdAt time.Time, updatedAt time.Time, resource string, resourcePath string, ready bool) *Account {\n\tthis := Account{}\n\tthis.Id = id\n\tthis.Name = name\n\tthis.Primary = primary\n\tthis.Type = type_\n\tthis.Currency = currency\n\tthis.Balance = balance\n\tthis.CreatedAt = createdAt\n\tthis.UpdatedAt = updatedAt\n\tthis.Resource = resource\n\tthis.ResourcePath = resourcePath\n\tthis.Ready = ready\n\treturn &this\n}", "func NewAccount(txr *repository.Transactioner) repository.Account {\n\treturn &account{txr: txr}\n}", "func NewAccount(acc *types.Account) *Account {\n\treturn &Account{\n\t\tAccount: *acc,\n\t}\n}", "func CreateFaucetSubAccount(faucetName, faucetPasswd, faucetAddr string, subAccNum int) ([]types.AccountInfo, error) {\n\tvar (\n\t\tmethod = \"CreateFaucetSubAccount\"\n\t\tcreatedAccs, subAccs []types.AccountInfo\n\t)\n\n\tkeyChan := make(chan types.AccountInfo)\n\n\t// create sub account\n\tfor i := 1; i <= subAccNum; i++ {\n\t\tkeyName := fmt.Sprintf(\"%v_%v\", faucetName, i)\n\t\tgo CreateKey(keyName, keyChan)\n\t}\n\n\tcounter := 0\n\tfor {\n\t\taccInfo := <-keyChan\n\t\tif accInfo.Address != \"\" {\n\t\t\tcreatedAccs = append(createdAccs, accInfo)\n\t\t}\n\t\tcounter++\n\t\tif counter == subAccNum {\n\t\t\tlog.Printf(\"%v: all create sub faucet key goroutine over\\n\", method)\n\t\t\tlog.Printf(\"%v: except create %v accounts, successful create %v accounts\",\n\t\t\t\tmethod, subAccNum, len(createdAccs))\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// distribute token\n\n\t// get sender info\n\tsenderInfo := types.AccountInfo{\n\t\tLocalAccountName: faucetName,\n\t\tPassword: faucetPasswd,\n\t\tAddress: faucetAddr,\n\t}\n\taccInfo, err := account.GetAccountInfo(senderInfo.Address)\n\tif err != nil {\n\t\tlog.Printf(\"%v: get faucet info fail: %v\\n\", method, err)\n\t\treturn subAccs, err\n\t}\n\tsenderInfo.AccountNumber = accInfo.AccountNumber\n\tsenderSequence, err := helper.ConvertStrToInt64(accInfo.Sequence)\n\tif err != nil {\n\t\tlog.Printf(\"%v: convert sequence to int64 fail: %v\\n\", method, err)\n\t\treturn subAccs, err\n\t}\n\n\t// get transfer amount which equal senderBalance / subAccNum\n\tamt, err := parseCoins(accInfo.Coins)\n\tif err != nil {\n\t\tlog.Printf(\"%v: parse coin failed: %v\\n\", method, err)\n\t\treturn subAccs, err\n\t}\n\ttransferAmt := fmt.Sprintf(\"%v%s\", parseFloat64ToStr(amt/float64(subAccNum+1)), constants.Denom)\n\n\t// distribute token to created accounts\n\tfor _, acc := range createdAccs {\n\t\tsenderInfo.Sequence = fmt.Sprintf(\"%v\", senderSequence)\n\t\tacc, err := DistributeToken(senderInfo, acc, transferAmt)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"%v: distribute token to %v failed: %v\\n\",\n\t\t\t\tmethod, acc.LocalAccountName, err)\n\t\t} else {\n\t\t\tsubAccs = append(subAccs, acc)\n\t\t\tsenderSequence += 1\n\t\t}\n\t}\n\n\treturn subAccs, err\n}", "func newServiceAccount(cr *argoprojv1a1.ArgoCD) *corev1.ServiceAccount {\n\treturn &corev1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tLabels: argoutil.LabelsForCluster(cr),\n\t\t},\n\t}\n}", "func (va *ClawbackVestingAccount) computeClawback(clawbackTime int64) sdk.Coins {\n\t// Compute the truncated vesting schedule and amounts.\n\t// Work with the schedule as the primary data and recompute derived fields, e.g. OriginalVesting.\n\tvestTime := va.StartTime\n\ttotalVested := sdk.NewCoins()\n\ttotalUnvested := sdk.NewCoins()\n\tunvestedIdx := 0\n\tfor i, period := range va.VestingPeriods {\n\t\tvestTime += period.Length\n\t\t// tie in time goes to clawback\n\t\tif vestTime < clawbackTime {\n\t\t\ttotalVested = totalVested.Add(period.Amount...)\n\t\t\tunvestedIdx = i + 1\n\t\t} else {\n\t\t\ttotalUnvested = totalUnvested.Add(period.Amount...)\n\t\t}\n\t}\n\tlastVestTime := vestTime\n\tnewVestingPeriods := va.VestingPeriods[:unvestedIdx]\n\n\t// To cap the unlocking schedule to the new total vested, conjunct with a limiting schedule\n\tcapPeriods := []Period{\n\t\t{\n\t\t\tLength: 0,\n\t\t\tAmount: totalVested,\n\t\t},\n\t}\n\t_, lastLockTime, newLockupPeriods := ConjunctPeriods(va.StartTime, va.StartTime, va.LockupPeriods, capPeriods)\n\n\t// Now construct the new account state\n\tva.OriginalVesting = totalVested\n\tva.EndTime = max64(lastVestTime, lastLockTime)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\t// DelegatedVesting and DelegatedFree will be adjusted elsewhere\n\n\treturn totalUnvested\n}", "func newServiceAccount(cr *storagev1.CSIPowerMaxRevProxy) *v1.ServiceAccount {\n\treturn &v1.ServiceAccount{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ReverseProxyName,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tOwnerReferences: getOwnerReferences(cr),\n\t\t},\n\t}\n}", "func (va *ClawbackVestingAccount) clawback(ctx sdk.Context, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) error {\n\t// Compute the clawback based on the account state only, and update account\n\ttoClawBack := va.computeClawback(ctx.BlockTime().Unix())\n\tif toClawBack.IsZero() {\n\t\treturn nil\n\t}\n\taddr := va.GetAddress()\n\tbondDenom := sk.BondDenom(ctx)\n\n\t// Compute the clawback based on bank balance and delegation, and update account\n\tencumbered := va.GetVestingCoins(ctx.BlockTime())\n\tbondedAmt := sk.GetDelegatorBonded(ctx, addr)\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, addr)\n\tbonded := sdk.NewCoins(sdk.NewCoin(bondDenom, bondedAmt))\n\tunbonding := sdk.NewCoins(sdk.NewCoin(bondDenom, unbondingAmt))\n\tunbonded := bk.GetAllBalances(ctx, addr)\n\ttoClawBack = va.updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded)\n\n\t// Write now now so that the bank module sees unvested tokens are unlocked.\n\t// Note that all store writes are aborted if there is a panic, so there is\n\t// no danger in writing incomplete results.\n\tak.SetAccount(ctx, va)\n\n\t// Now that future vesting events (and associated lockup) are removed,\n\t// the balance of the account is unlocked and can be freely transferred.\n\tspendable := bk.SpendableCoins(ctx, addr)\n\ttoXfer := coinsMin(toClawBack, spendable)\n\terr := bk.SendCoins(ctx, addr, dest, toXfer)\n\tif err != nil {\n\t\treturn err // shouldn't happen, given spendable check\n\t}\n\ttoClawBack = toClawBack.Sub(toXfer)\n\n\t// We need to traverse the staking data structures to update the\n\t// vesting account bookkeeping, and to recover more funds if necessary.\n\t// Staking is the only way unvested tokens should be missing from the bank balance.\n\n\t// If we need more, transfer UnbondingDelegations.\n\twant := toClawBack.AmountOf(bondDenom)\n\tunbondings := sk.GetUnbondingDelegations(ctx, addr, math.MaxUint16)\n\tfor _, unbonding := range unbondings {\n\t\tvalAddr, err := sdk.ValAddressFromBech32(unbonding.ValidatorAddress)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttransferred := sk.TransferUnbonding(ctx, addr, dest, valAddr, want)\n\t\twant = want.Sub(transferred)\n\t\tif !want.IsPositive() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If we need more, transfer Delegations.\n\tif want.IsPositive() {\n\t\tdelegations := sk.GetDelegatorDelegations(ctx, addr, math.MaxUint16)\n\t\tfor _, delegation := range delegations {\n\t\t\tvalidatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // shouldn't happen\n\t\t\t}\n\t\t\tvalidator, found := sk.GetValidator(ctx, validatorAddr)\n\t\t\tif !found {\n\t\t\t\t// validator has been removed\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twantShares, err := validator.SharesFromTokensTruncated(want)\n\t\t\tif err != nil {\n\t\t\t\t// validator has no tokens\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttransferredShares := sk.TransferDelegation(ctx, addr, dest, delegation.GetValidatorAddr(), wantShares)\n\t\t\t// to be conservative in what we're clawing back, round transferred shares up\n\t\t\ttransferred := validator.TokensFromSharesRoundUp(transferredShares).RoundInt()\n\t\t\twant = want.Sub(transferred)\n\t\t\tif !want.IsPositive() {\n\t\t\t\t// Could be slightly negative, due to rounding?\n\t\t\t\t// Don't think so, due to the precautions above.\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we've transferred everything and still haven't transferred the desired clawback amount,\n\t// then the account must have most some unvested tokens from slashing.\n\treturn nil\n}", "func NewAccount(owner string) *Account {\n\treturn &Account{owner: owner, balance: 0}\n}", "func newPeriodicVestingAccount(address sdk.AccAddress, periods vestingtypes.Periods, firstPeriodStartTimestamp int64) *vestingtypes.PeriodicVestingAccount {\n\tbaseAccount := authtypes.NewBaseAccount(address, nil, 0, 0)\n\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range periods {\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\n\tvar totalPeriods int64\n\tfor _, p := range periods {\n\t\ttotalPeriods += p.Length\n\t}\n\tendTime := firstPeriodStartTimestamp + totalPeriods\n\n\tbaseVestingAccount := vestingtypes.NewBaseVestingAccount(baseAccount, originalVesting, endTime)\n\treturn vestingtypes.NewPeriodicVestingAccountRaw(baseVestingAccount, firstPeriodStartTimestamp, periods)\n}", "func NewAccount(firstName string) *Account {\n\tthis := Account{}\n\tthis.FirstName = firstName\n\treturn &this\n}", "func tNewUser(lbl string) *tUser {\n\tintBytes := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(intBytes, acctCounter)\n\tacctID := account.AccountID{}\n\tcopy(acctID[:], acctTemplate[:])\n\tcopy(acctID[account.HashSize-4:], intBytes)\n\taddr := strconv.Itoa(int(acctCounter))\n\tsig := []byte{0xab} // Just to differentiate from the addr.\n\tsig = append(sig, intBytes...)\n\tsigHex := hex.EncodeToString(sig)\n\tacctCounter++\n\treturn &tUser{\n\t\tsig: sig,\n\t\tsigHex: sigHex,\n\t\tacct: acctID,\n\t\taddr: addr,\n\t\tlbl: lbl,\n\t}\n}", "func (policy *ticketPolicy) OnCreateNewAccount(acc *types.Account) {\n}", "func NewAccount(instanceID uuid.UUID, name, aud string) (*Account, error) {\n\tid, err := uuid.NewV4()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Error generating unique id\")\n\t}\n\n\taccount := &Account{\n\t\tInstanceID: instanceID,\n\t\tID: id,\n\t\tAud: aud,\n\t\tName: name,\n\t}\n\treturn account, nil\n}", "func NewTrainCar() TrainCar {\n c := TrainCar{name: \"TrainCar\", vehicle: \"TrainCar\", speed: 30, capacity: 30, railway: \"CNR\"}\n return c\n}", "func NewUserTeamwork()(*UserTeamwork) {\n m := &UserTeamwork{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewAccount(email string) *Account {\n\treturn &Account{email: email}\n}", "func (as *Service) Create(name, iamRole, externalID string) (*Account, error) {\n\n\tbody := map[string]map[string]string{\n\t\t\"account\": {\"name\": name},\n\t}\n\n\tlog.Printf(\"Making request %v\\n\", body)\n\treq, err := as.httpClient.NewRequest(http.MethodPost, \"/setup/account\", &body)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar v common.Response\n\t_, err = as.httpClient.Do(req, &v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(v.Response.Items) == 0 {\n\t\treturn nil, errors.New(\"Couldn't create account\")\n\t}\n\tvar account Account\n\n\tfmt.Println(string(v.Response.Items[0]))\n\n\terr = json.Unmarshal(v.Response.Items[0], &account)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttime.Sleep(time.Second * 5)\n\n\terr = as.setupCloudCredentials(account.ID, iamRole, externalID)\n\n\tif err != nil {\n\t\t_ = as.Delete(account.ID)\n\t\treturn nil, err\n\t}\n\n\treturn &account, nil\n}", "func NewGenesisAccount(aa *UserAccount) *GenesisAccount {\n\treturn &GenesisAccount{\n\t\tId: aa.Id,\n\t\tAddress: aa.Address,\n\t\tCoins: aa.Coins.Sort(),\n\t}\n}", "func MakeAccount(owner string) *Account {\n\taccount := Account{owner: owner, balance: 0}\n\treturn &account\n}", "func NewAccount(newid AccountIDType, newemail string) *Account {\n\treturn &Account{\n\t\tid: newid,\n\t\temail: newemail,\n\t}\n}", "func NewAccount(opts ...AccountCreationOption) (*Account, error) {\n\taccount := &Account{\n\t\tBalance: big.NewInt(0),\n\t\tvotingWeight: big.NewInt(0),\n\t\taccountType: 1,\n\t}\n\tfor _, opt := range opts {\n\t\tif err := opt(account); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to apply account creation option\")\n\t\t}\n\t}\n\treturn account, nil\n}", "func makeAccount(){\n\toperatorSecret, err := hedera.SecretKeyFromString(secret)\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\n\tsecretKey, _ := hedera.GenerateSecretKey()\n\tpublic := secretKey.Public()\n\n\tfmt.Printf(\"secret = %v\\n\", secretKey)\n\tfmt.Printf(\"public = %v\\n\", public)\n\n\tclient, err := hedera.Dial(server)\n\tif err !=nil{\n\t\tpanic(err)\n\t}\n\tdefer client.Close()\n\n\tnodeAccountID := hedera.AccountID{Account: 3}\n\toperatorAccountID := hedera.AccountID{Account: 1001}\n\ttime.Sleep(2* time.Second)\n\tresponse, err := client.CreateAccount().Key(public).InitialBalance(0).Operator(operatorAccountID).Node(nodeAccountID).Memo(\"Test make Account\").Sign(operatorSecret).Execute()\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\n\ttransactionID := response.ID\n\tfmt.Printf(\"Created account; transaction = %v\\n\", transactionID)\n\ttime.Sleep(2* time.Second)\n \n\treceipt,err := client.Transaction(*transactionID).Receipt().Get()\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"Account = %v\\n\", *receipt.AccountID)\n\n}", "func (ba *BankAccount) New() Resource {\n\tvar obj = &BankAccount{}\n\treturn obj\n}", "func (a *Account) CreateAcct(password string) (*Account, *http.Response, []error) {\n\tk := kumoru.New()\n\n\tk.Put(fmt.Sprintf(\"%s/v1/accounts/%s\", k.EndPoint.Authorization, a.Email))\n\tk.Send(fmt.Sprintf(\"given_name=%s&surname=%s&password=%s\", a.GivenName, a.Surname, password))\n\n\tresp, body, errs := k.End()\n\n\tif len(errs) > 0 {\n\t\treturn a, resp, errs\n\t}\n\n\tif resp.StatusCode >= 400 {\n\t\terrs = append(errs, fmt.Errorf(\"%s\", resp.Status))\n\t}\n\n\terr := json.Unmarshal([]byte(body), &a)\n\n\tif err != nil {\n\t\terrs = append(errs, err)\n\t\treturn a, resp, errs\n\t}\n\n\treturn a, resp, nil\n}", "func (c Client) NewAccount(privateKey crypto.Signer, onlyReturnExisting, termsOfServiceAgreed bool, contact ...string) (Account, error) {\n\tvar opts []NewAccountOptionFunc\n\tif onlyReturnExisting {\n\t\topts = append(opts, NewAcctOptOnlyReturnExisting())\n\t}\n\tif termsOfServiceAgreed {\n\t\topts = append(opts, NewAcctOptAgreeTOS())\n\t}\n\tif contact != nil && len(contact) > 0 {\n\t\topts = append(opts, NewAcctOptWithContacts(contact...))\n\t}\n\n\treturn c.NewAccountOptions(privateKey, opts...)\n}", "func NewAccount(file string) (*AccountRoot, error) {\n\tif file == \"\" {\n\t\treturn nil, errors.New(\"config file should be passed\")\n\t}\n\n\tvar err error\n\tconf, err := loadAccount(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// debug\n\t// grok.Value(conf)\n\n\t// validate\n\tif err = conf.validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn conf, nil\n}", "func (biz *BizAccountAccess) newAccountAccess(ctx context.Context, tx *sql.Tx,\n\tu coremodel.User, accType coremodel.AccountAccessType,\n) (*coremodel.AccountAccess, error) {\n\tac, err := coremodel.NewAccountAccess(u, accType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err = biz.dal.Insert(ctx, tx, ac); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ac, nil\n}", "func (controller *AccountController) NewAccount(ctx *gin.Context) {\n\tname, ok := ctx.GetPostForm(\"name\")\n\tif !ok {\n\t\tlog.WithFields(log.Fields{\"URL\": ctx.Request.URL.String()}).Warn(\"No name found in postform\")\n\n\t\terrResp, _ := restapi.NewErrorResponse(\"No name given\").Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(errResp))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\n\tinfo, err := authStuff.GetLoginInfoFromCtx(ctx)\n\tif err != nil {\n\t\tresponse, _ := restapi.NewErrorResponse(err.Error()).Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(response))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\n\tacc, err := controller.service.CreateAdd(name, info.Name, permissions.CRUD)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"user\": info.Name}).WithError(err).Error(\"Account Error New\")\n\n\t\tresponse, _ := restapi.NewErrorResponse(\"Couldn't create account: \" + err.Error()).Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(response))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\tresponse, _ := restapi.NewOkResponse(acc).Marshal()\n\tfmt.Fprint(ctx.Writer, string(response))\n\tctx.Next()\n}", "func NewAccount(addr, amount string) *Account {\n\tam := big.NewInt(0)\n\tam.SetString(amount, 0)\n\treturn &Account{Address: addr, Amount: am}\n}", "func newTicket(\n\tbeaconOutput []byte, // V_i\n\tstakerValue []byte, // Q_j\n\tvirtualStakerIndex *big.Int, // vs\n) (*ticket, error) {\n\tvalue, err := calculateTicketValue(beaconOutput, stakerValue, virtualStakerIndex)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ticket value calculation failed [%v]\", err)\n\t}\n\n\treturn &ticket{\n\t\tvalue: value,\n\t\tproof: &proof{\n\t\t\tstakerValue: stakerValue,\n\t\t\tvirtualStakerIndex: virtualStakerIndex,\n\t\t},\n\t}, nil\n}", "func NewBookingBusiness()(*BookingBusiness) {\n m := &BookingBusiness{\n Entity: *NewEntity(),\n }\n return m\n}", "func create_account_ (stub shim.ChaincodeStubInterface, account *Account) error {\n var old_account Account\n row_was_found,err := util.InsertTableRow(stub, ACCOUNT_TABLE, row_keys_of_Account(account), account, util.FAIL_BEFORE_OVERWRITE, &old_account)\n if err != nil {\n return err\n }\n if row_was_found {\n return fmt.Errorf(\"Could not create account %v because an account with that Name already exists\", *account)\n }\n return nil // success\n}", "func NewValidatorVestingAccount(baseAcc *authtypes.BaseAccount, startTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &vestingtypes.BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: baseAcc.Coins,\n\t\tEndTime: endTime,\n\t}\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func (c *AccountController) Create(ctx echo.Context) error {\n\tmodel := account.Account{}\n\terr := ctx.Bind(&model)\n\tif err != nil {\n\t\treturn ctx.JSON(http.StatusUnprocessableEntity, err.Error())\n\t}\n\n\tres, err := c.AccountUsecase.Create(&model)\n\tif err != nil {\n\t\treturn ctx.JSON(http.StatusInternalServerError, err.Error())\n\t}\n\n\treturn ctx.JSON(http.StatusCreated, res)\n}", "func newServiceAccountWithName(name string, cr *argoprojv1a1.ArgoCD) *corev1.ServiceAccount {\n\tsa := newServiceAccount(cr)\n\tsa.ObjectMeta.Name = getServiceAccountName(cr.Name, name)\n\n\tlbls := sa.ObjectMeta.Labels\n\tlbls[common.ArgoCDKeyName] = name\n\tsa.ObjectMeta.Labels = lbls\n\n\treturn sa\n}", "func (account *Account) New() {\n\n\tparams, _ := pbc.NewParamsFromString(crypto.Params)\n\tpairing := params.NewPairing()\n\n\tA := pairing.NewG1()\n\tAT := pairing.NewG1()\n\ta := pairing.NewZr()\n\n\ta.Rand()\n\n\tG := pairing.NewG1()\n\tT := pairing.NewG1()\n\tG.SetString(crypto.G, 10)\n\tT.SetString(crypto.T, 10)\n\n\tA.PowZn(G, a)\n\tAT.PowZn(T, a)\n\n\taccount.a = a.String()\n\taccount.A = A.String()\n\taccount.AT = AT.String()\n}", "func New(accessKey string, secretKey string) *Coinsbank {\n\treturn &Coinsbank{\n\t\tAccessKey: accessKey,\n\t\tSecretKey: secretKey,\n\t}\n}", "func NewAccount(addr *Address) *Account {\n\treturn &Account{\n\t\taccount: common.NewAccount(common.BytesToAddress(addr.Bytes())),\n\t}\n}", "func (controller *Auth) CreateNewAccount() {\n\tpage := \"register-form-page\"\n\tcontroller.RegisterCaptchaAction(page)\n\n\tif !controller.IsCaptchaValid(page) {\n\t\tcontroller.DisplaySimpleError(\"Please enter a valid code!\")\n\t} else {\n\t\tcontroller.createNewAccount()\n\t}\n}", "func (ga *GenesisAccount) ToAccount() auth.Account {\n\tbacc := &auth.BaseAccount{\n\t\tAddress: ga.Address,\n\t\tCoins: ga.Coins.Sort(),\n\t\tAccountNumber: ga.AccountNumber,\n\t\tSequence: ga.Sequence,\n\t}\n\n\tif !ga.OriginalVesting.IsZero() {\n\t\tbaseVestingAcc := &auth.BaseVestingAccount{\n\t\t\tBaseAccount: bacc,\n\t\t\tOriginalVesting: ga.OriginalVesting,\n\t\t\tDelegatedFree: ga.DelegatedFree,\n\t\t\tDelegatedVesting: ga.DelegatedVesting,\n\t\t\tEndTime: ga.EndTime,\n\t\t}\n\n\t\tif ga.StartTime != 0 && ga.EndTime != 0 {\n\t\t\treturn &auth.ContinuousVestingAccount{\n\t\t\t\tBaseVestingAccount: baseVestingAcc,\n\t\t\t\tStartTime: ga.StartTime,\n\t\t\t}\n\t\t} else if ga.EndTime != 0 {\n\t\t\treturn &auth.DelayedVestingAccount{\n\t\t\t\tBaseVestingAccount: baseVestingAcc,\n\t\t\t}\n\t\t} else {\n\t\t\tpanic(fmt.Sprintf(\"invalid genesis vesting account: %+v\", ga))\n\t\t}\n\t}\n\n\treturn bacc\n}", "func NewPeriodicVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime int64, periods Periods) *PeriodicVestingAccount {\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func CreateTestAccount(t *testing.T, store SimpleStore) api.Account {\n\tt.Helper()\n\n\tcreateQuery := `INSERT INTO accounts (username, email, status, form_type, form_version, external_id) VALUES ($1, $1, $2, $3, $4, $5) RETURNING id, username, email, status, form_type, form_version, external_id`\n\n\temail := randomEmail()\n\n\tresult := api.Account{}\n\n\texternalID := uuid.New().String()\n\n\tcreateErr := store.db.Get(&result, createQuery, email, api.StatusIncomplete, \"SF86\", \"2017-07\", externalID)\n\tif createErr != nil {\n\t\tt.Log(\"Failed to create Account\", createErr)\n\t\tt.Fatal()\n\t}\n\n\treturn result\n}", "func accountCreate(ctx *cli.Context) error {\n\n\tdataDir := ctx.GlobalString(utils.DataDirFlag.Name)\n\t//get keyStoreDir from KeyStoreDirFlag, if not use the default value\n\tkeyStoreDir := ctx.GlobalString(utils.KeyStoreDirFlag.Name)\n\tif keyStoreDir == \"\" {\n\t\tkeyStoreDir = keystore.KeyStoreScheme\n\t}\n\tkeyStoreDir = filepath.Join(dataDir, keyStoreDir)\n\tpassword := getPassPhrase(\"Your new account is locked with a password. Please give a password. Do not forget this password.\", true, 0, utils.MakePasswordList(ctx))\n\t_, err := utils.NewAccount(keyStoreDir, password)\n\n\treturn err\n}", "func (s *Service) CreateAccount(budgetID string, accountPayload PayloadAccount) (*Account, error) {\n\tresModel := struct {\n\t\tData struct {\n\t\t\tAccount *Account `json:\"account\"`\n\t\t} `json:\"data\"`\n\t}{}\n\n\tpayload := struct {\n\t\tAccount PayloadAccount `json:\"account\"`\n\t}{\n\t\taccountPayload,\n\t}\n\n\tbuf, err := json.Marshal(&payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\turl := fmt.Sprintf(\"/budgets/%s/accounts/\", budgetID)\n\tif err := s.c.POST(url, &resModel, buf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resModel.Data.Account, nil\n}", "func NewAccount(address string) *Account {\n\treturn &Account{\n\t\tAddress: address,\n\t\tHeight: \"0\",\n\t\tGoldTokenBalance: \"0\",\n\t\tTotalLockedGoldBalance: \"0\",\n\t\tNonVotingLockedGoldBalance: \"0\",\n\t\tVotingLockedGoldBalance: \"0\",\n\t\tPendingWithdrawalBalance: \"0\",\n\t\tCeloUSDValue: \"0\",\n\t\tDelegations: []*Delegation{},\n\t}\n\n}", "func NewAllocAccount(val string) AllocAccountField {\n\treturn AllocAccountField{quickfix.FIXString(val)}\n}", "func generateNewAccount() string {\n\taccount := crypto.GenerateAccount()\n\tpassphrase, err := mnemonic.FromPrivateKey(account.PrivateKey)\n\tif err != nil {\n\t\tfmt.Printf(\"Error creating new account: %s\\n\", err)\n\t} else {\n\t\tfmt.Printf(\"Created new account: %s\\n\", account.Address)\n\t\tfmt.Printf(\"Generated mnemonic: \\\"%s\\\"\\n\", passphrase)\n\t}\n\treturn account.Address.String()\n}", "func newBkCli() (*bkCli, error) {\n\tconfig := config.CurrentConfig()\n\n\tclient, err := newClient(config)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &bkCli{config, client}, nil\n}", "func NewAccount() *Account {\n\n\tcreatedAccount := Account{}\n\n\tnewPrivateKey, err := generatePrivateKey(4096)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating rsa private key \", err)\n\t}\n\tnewPublicKey, err := generatePublicKey(&newPrivateKey.PublicKey)\n\tif err != nil {\n\t\tlog.Fatal(\"Error generating rsa public key \", err)\n\t}\n\tcreatedAccount.privateKey = newPrivateKey\n\tcreatedAccount.Address = string(newPublicKey)\n\tcreatedAccount.Amount = 0\n\n\treturn &createdAccount\n}", "func New(token string) (*GAB, error) {\n\tbot, err := tapi.NewBotAPI(token)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not create new bot with provided token: %v\", err)\n\t}\n\tlog.Printf(\"Authorized on account %s\", bot.Self.UserName)\n\treturn &GAB{\n\t\tTelBot: bot,\n\t}, nil\n}", "func (cga clawbackGrantAction) AddToAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported,\n\t\t\t\"account %s must be a ClawbackVestingAccount, got %T\",\n\t\t\trawAccount.GetAddress(), rawAccount)\n\t}\n\tif cga.funderAddress != cva.FunderAddress {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"account %s can only accept grants from account %s\",\n\t\t\trawAccount.GetAddress(), cva.FunderAddress)\n\t}\n\tcva.addGrant(ctx, cga.sk, cga.grantStartTime, cga.grantLockupPeriods, cga.grantVestingPeriods, cga.grantCoins)\n\treturn nil\n}", "func NewAccount() *Account {\n\tacc := &Account{}\n\tpriv, pub := newKeyPair()\n\tacc.PriKey = priv\n\tacc.PubKey = pub\n\treturn acc\n}", "func newTestContext() (tc *testContext, err error) {\n\ttc = new(testContext)\n\n\tconst genesisHash = \"0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206\"\n\tif tc.netParams, err = tc.createNetParams(genesisHash); err != nil {\n\t\treturn\n\t}\n\n\tconst block1Hex = \"0000002006226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910fadbb20ea41a8423ea937e76e8151636bf6093b70eaff942930d20576600521fdc30f9858ffff7f20000000000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff03510101ffffffff0100f2052a010000001976a9143ca33c2e4446f4a305f23c80df8ad1afdcf652f988ac00000000\"\n\tif tc.block1, err = blockFromHex(block1Hex); err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized block: %v\", err)\n\t\treturn\n\t}\n\n\tconst fundingInputPrivKeyHex = \"6bd078650fcee8444e4e09825227b801a1ca928debb750eb36e6d56124bb20e8\"\n\ttc.fundingInputPrivKey, err = privkeyFromHex(fundingInputPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localFundingPrivKeyHex = \"30ff4956bbdd3222d44cc5e8a1261dab1e07957bdac5ae88fe3261ef321f3749\"\n\ttc.localFundingPrivKey, err = privkeyFromHex(localFundingPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentPrivKeyHex = \"bb13b121cdc357cd2e608b0aea294afca36e2b34cf958e2e6451a2f274694491\"\n\ttc.localPaymentPrivKey, err = privkeyFromHex(localPaymentPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localFundingPubKeyHex = \"023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb\"\n\ttc.localFundingPubKey, err = pubkeyFromHex(localFundingPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remoteFundingPubKeyHex = \"030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c1\"\n\ttc.remoteFundingPubKey, err = pubkeyFromHex(remoteFundingPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localRevocationPubKeyHex = \"0212a140cd0c6539d07cd08dfe09984dec3251ea808b892efeac3ede9402bf2b19\"\n\ttc.localRevocationPubKey, err = pubkeyFromHex(localRevocationPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentPubKeyHex = \"030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e7\"\n\ttc.localPaymentPubKey, err = pubkeyFromHex(localPaymentPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remotePaymentPubKeyHex = \"0394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b\"\n\ttc.remotePaymentPubKey, err = pubkeyFromHex(remotePaymentPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localDelayPubKeyHex = \"03fd5960528dc152014952efdb702a88f71e3c1653b2314431701ec77e57fde83c\"\n\ttc.localDelayPubKey, err = pubkeyFromHex(localDelayPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst commitmentPointHex = \"025f7117a78150fe2ef97db7cfc83bd57b2e2c0d0dd25eaf467a4a1c2a45ce1486\"\n\ttc.commitmentPoint, err = pubkeyFromHex(commitmentPointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentBasePointHex = \"034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa\"\n\ttc.localPaymentBasePoint, err = pubkeyFromHex(localPaymentBasePointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remotePaymentBasePointHex = \"032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991\"\n\ttc.remotePaymentBasePoint, err = pubkeyFromHex(remotePaymentBasePointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst fundingChangeAddressStr = \"bcrt1qgyeqfmptyh780dsk32qawsvdffc2g5q5sxamg0\"\n\ttc.fundingChangeAddress, err = btcutil.DecodeAddress(\n\t\tfundingChangeAddressStr, tc.netParams)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse address: %v\", err)\n\t\treturn\n\t}\n\n\ttc.fundingInputUtxo, tc.fundingInputTxOut, err = tc.extractFundingInput()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconst fundingTxHex = \"0200000001adbb20ea41a8423ea937e76e8151636bf6093b70eaff942930d20576600521fd000000006b48304502210090587b6201e166ad6af0227d3036a9454223d49a1f11839c1a362184340ef0240220577f7cd5cca78719405cbf1de7414ac027f0239ef6e214c90fcaab0454d84b3b012103535b32d5eb0a6ed0982a0479bbadc9868d9836f6ba94dd5a63be16d875069184ffffffff028096980000000000220020c015c4a6be010e21657068fc2e6a9d02b27ebe4d490a25846f7237f104d1a3cd20256d29010000001600143ca33c2e4446f4a305f23c80df8ad1afdcf652f900000000\"\n\tif tc.fundingTx, err = txFromHex(fundingTxHex); err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized tx: %v\", err)\n\t\treturn\n\t}\n\n\ttc.fundingOutpoint = wire.OutPoint{\n\t\tHash: *tc.fundingTx.Hash(),\n\t\tIndex: 0,\n\t}\n\n\ttc.shortChanID = lnwire.ShortChannelID{\n\t\tBlockHeight: 1,\n\t\tTxIndex: 0,\n\t\tTxPosition: 0,\n\t}\n\n\thtlcData := []struct {\n\t\tincoming bool\n\t\tamount lnwire.MilliSatoshi\n\t\texpiry uint32\n\t\tpreimage string\n\t}{\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 1000000,\n\t\t\texpiry: 500,\n\t\t\tpreimage: \"0000000000000000000000000000000000000000000000000000000000000000\",\n\t\t},\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 2000000,\n\t\t\texpiry: 501,\n\t\t\tpreimage: \"0101010101010101010101010101010101010101010101010101010101010101\",\n\t\t},\n\t\t{\n\t\t\tincoming: false,\n\t\t\tamount: 2000000,\n\t\t\texpiry: 502,\n\t\t\tpreimage: \"0202020202020202020202020202020202020202020202020202020202020202\",\n\t\t},\n\t\t{\n\t\t\tincoming: false,\n\t\t\tamount: 3000000,\n\t\t\texpiry: 503,\n\t\t\tpreimage: \"0303030303030303030303030303030303030303030303030303030303030303\",\n\t\t},\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 4000000,\n\t\t\texpiry: 504,\n\t\t\tpreimage: \"0404040404040404040404040404040404040404040404040404040404040404\",\n\t\t},\n\t}\n\n\ttc.htlcs = make([]channeldb.HTLC, len(htlcData))\n\tfor i, htlc := range htlcData {\n\t\tpreimage, decodeErr := hex.DecodeString(htlc.preimage)\n\t\tif decodeErr != nil {\n\t\t\terr = fmt.Errorf(\"Failed to decode HTLC preimage: %v\", decodeErr)\n\t\t\treturn\n\t\t}\n\n\t\ttc.htlcs[i].RHash = sha256.Sum256(preimage)\n\t\ttc.htlcs[i].Amt = htlc.amount\n\t\ttc.htlcs[i].RefundTimeout = htlc.expiry\n\t\ttc.htlcs[i].Incoming = htlc.incoming\n\t}\n\n\ttc.localCsvDelay = 144\n\ttc.fundingAmount = 10000000\n\ttc.dustLimit = 546\n\ttc.feePerKW = 15000\n\n\treturn\n}", "func NewAccountClient(subscriptionID string) AccountClient {\n return NewAccountClientWithBaseURI(DefaultBaseURI, subscriptionID)\n}", "func (m *MockIAccountController) NewAccount(c *gin.Context) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"NewAccount\", c)\n}", "func (s Service) CreateNewAccount(ctx context.Context, acc *account.Account, password string) (id, url, tmpToken string, err error) {\n\tspan := s.tracer.MakeSpan(ctx, \"CreateNewAccount\")\n\tdefer span.Finish()\n\n\t// pass data in context\n\ts.passContext(&ctx)\n\n\tacc.FirstName = strings.TrimSpace(acc.FirstName)\n\tacc.Lastname = strings.TrimSpace(acc.Lastname)\n\tacc.Emails[0].Email = strings.TrimSpace(acc.Emails[0].Email)\n\tacc.Emails[0].Email = strings.ToLower(acc.Emails[0].Email)\n\tacc.Username = strings.ToLower(acc.Username)\n\tacc.Username = strings.TrimSpace(acc.Username)\n\n\tyear, month, day := acc.Birthday.Birthday.Date()\n\tacc.BirthdayDate = account.Date{\n\t\tDay: day,\n\t\tMonth: int(month),\n\t\tYear: year,\n\t}\n\n\terr = emptyValidator(acc.FirstName, acc.Lastname, acc.Username)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\terr = fromTwoToSixtyFour(acc.FirstName)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\terr = fromTwoToHundredTwentyEight(acc.Lastname)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\n\terr = userNameValidator(acc.Username)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\tif len(acc.Emails) > 0 {\n\t\terr = emailValidator(acc.Emails[0].Email)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", \"\", err\n\t\t}\n\t} else {\n\t\treturn \"\", \"\", \"\", errors.New(\"Please Enter Email\")\n\t}\n\terr = validPassword(password)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\n\t// TODO: trim data!\n\t// TODO: make first letter capital in some fields!\n\n\t// check if email is not busy\n\tinUse, err := s.repository.Users.IsEmailAlreadyInUse(ctx, acc.Emails[0].Email)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\tif inUse {\n\t\terr = errors.New(\"this_email_already_in_use\") // TODO: how it return as gRPC status?\n\t\treturn\n\t}\n\n\t// check if usernmae is not busy\n\tusernameInUse, err := s.repository.Users.IsUsernameBusy(ctx, acc.Username)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\tif usernameInUse {\n\t\terr = errors.New(\"this_username_already_in_use\") // TODO: how it return as gRPC status?\n\t\treturn\n\t}\n\n\t// TODO: check phone is not busy yet (in future)\n\n\t// define location by IP address\n\tvar ip string\n\tmd, ok := metadata.FromIncomingContext(ctx)\n\tif !ok {\n\t\ts.tracer.LogError(span, errors.New(\"coudn't resolve ip address\"))\n\t} else {\n\t\tstrArr := md.Get(\"ip\")\n\t\tif len(strArr) > 0 {\n\t\t\tip = strArr[0]\n\t\t}\n\t}\n\tcountry, err := s.repository.GeoIP.GetCountryISOCode(net.ParseIP(ip))\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\tif country != \"\" {\n\t\tacc.Location = &account.UserLocation{\n\t\t\tLocation: location.Location{\n\t\t\t\tCountry: &location.Country{\n\t\t\t\t\tID: country,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\tid = acc.GenerateID()\n\turl = acc.GenerateURL()\n\tacc.Status = status.UserStatusNotActivated // set not_activated status\n\tacc.CreatedAt = time.Now() // set date of registration\n\tacc.Emails[0].Primary = true // set email as primary\n\tacc.Emails[0].GenerateID()\n\n\t// encode password\n\tencryptedPass, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\n\terr = s.repository.Users.SaveNewAccount(ctx, acc, string(encryptedPass))\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\n\temptyString := \"\"\n\n\terr = s.repository.arrangoRepo.SaveUser(ctx, &arangorepo.User{\n\t\tID: acc.GetID(),\n\t\tCreatedAt: time.Now(),\n\t\tFirstname: acc.FirstName,\n\t\tLastname: acc.Lastname,\n\t\tStatus: \"ACTIVATED\",\n\t\tURL: acc.URL,\n\t\tPrimaryEmail: acc.Emails[0].Email,\n\t\tGender: arangorepo.Gender{\n\t\t\tGender: acc.Gender.Gender,\n\t\t\tType: &emptyString,\n\t\t},\n\t})\n\tif err != nil {\n\t\tlog.Println(\"arrangoRepo.SaveUser:\", err)\n\t}\n\n\tif acc.GetInvitedByID() != \"\" {\n\t\ts.AddGoldCoinsToWallet(ctx, acc.GetInvitedByID(), 1)\n\t}\n\n\t// generate tmp code for activation\n\ttmpCode, err := s.repository.Cache.CreateTemporaryCodeForEmailActivation(ctx, id, acc.Emails[0].Email)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\n\t// log.Println(\"activation code:\", tmpCode) // TODO: delete later\n\t// log.Println(\"user id:\", id) // TODO: delete later\n\n\t// send email\n\t// err = s.mailRPC.SendEmail(\n\t// \tctx,\n\t// \tacc.Emails[0].Email,\n\t// \tfmt.Sprint(\"<html><body><a target='_blank' href='https://\"+s.Host+\"/api/activate/user?token=\", tmpCode, \"&user_id=\", id, \"'>Activate</a></body></html>\")) // TODO: write template for message\n\t// if err != nil {\n\t// \ts.tracer.LogError(span, err)\n\t// }\n\t// // fmt.Println(fmt.Sprint(\"https://\"+s.Host+\"/api/activate/user?token=\", tmpCode, \"&user_id=\", id)) // TODO: delete later\n\n\t// emailMessage := fmt.Sprint(\"<html><body><a target='_blank' href='https://\"+s.Host+\"/api/activate/user?token=\", tmpCode, \"&user_id=\", id, \"'>Activate</a></body></html>\")\n\temailMessage := s.tpl.GetActivationMessage(fmt.Sprint( /*\"https://\"+s.Host+\"/api/activate/user?token=\", tmpCode, \"&user_id=\", id)*/ tmpCode))\n\t// log.Println(acc.Emails[0].Email, emailMessage)\n\n\terr = s.mq.SendEmail(acc.Emails[0].Email, \"Activation\", emailMessage)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\n\t// generate tmp token for not activated user\n\ttmpToken, err = s.repository.Cache.CreateTemporaryCodeForNotActivatedUser(id)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\n\terr = s.CreateWalletAccount(ctx, id)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\n\treturn id, url, tmpToken, nil\n}", "func (ks *KeyStore) NewAccount(passphrase string) (accounts.Account, error) {\n\t_, account, err := storeNewKey(ks.storage, crand.Reader, passphrase)\n\tif err != nil {\n\t\treturn accounts.Account{}, err\n\t}\n\treturn account, nil\n}", "func NewTestAccount(sb *collections.SchemaBuilder) (TestAccount, error) {\n\tta := TestAccount{\n\t\tItem: collections.NewItem(sb, itemPrefix, \"test\", collections.Uint64Value),\n\t}\n\treturn ta, nil\n}", "func Create(w http.ResponseWriter, r *http.Request) {\n\n\taccountDecoder := json.NewDecoder(r.Body)\n\tvar accData Account\n\terr := accountDecoder.Decode(&accData)\n\tif err != nil {\n\t\tlog.Fatalln(\"error:\", err)\n\t}\n\taccData.CreateAccount()\n\tfmt.Fprintf(w, \"Account added successfully\")\n}", "func newReconciledServiceAccount() *corev1.ServiceAccount {\n\treturn NewServiceAccount(newEventSource())()\n}", "func NewAccount(email string, password string) (*Account, error) {\n\taccount := &Account{Email: email}\n\tencryptedPassword, err := utils.Encrypt(password)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taccount.ID = primitive.NewObjectID()\n\taccount.Password = string(encryptedPassword)\n\ttNow := time.Now()\n\taccount.CreatedAt = &tNow\n\taccount.repo = repoimpl.GetAccountRepo()\n\treturn account, nil\n}", "func CreateAccount (owner string) *Account {\n\taccount := Account{owner: owner, balance: 0}\n\treturn &account\n}", "func createAccountAndChangePassword(ctx context.Context, cryptohome *hwsec.CryptohomeClient, testPassword string, changePasswordShouldFail bool) error {\n\t// Create the account.\n\tif err := cryptohome.MountVault(ctx, util.PasswordLabel, hwsec.NewPassAuthConfig(username, oldPassword), true, hwsec.NewVaultConfig()); err != nil {\n\t\treturn errors.Wrap(err, \"failed to mount vault\")\n\t}\n\tif _, err := cryptohome.Unmount(ctx, username); err != nil {\n\t\treturn errors.Wrap(err, \"failed to unmount vault\")\n\t}\n\n\terr := cryptohome.ChangeVaultPassword(ctx, username, testPassword, util.PasswordLabel, newPassword)\n\tif !changePasswordShouldFail && err != nil {\n\t\treturn errors.Wrap(err, \"failed to change vault password\")\n\t}\n\tif changePasswordShouldFail && err == nil {\n\t\treturn errors.New(\"changing password unexpectedly succeeded\")\n\t}\n\treturn nil\n}", "func (m *MegaCorp) createAccount(firstName, lastName string) (acct *Account, err error) {\n\tacct = &Account{ID: util.UUID4(), FirstName: firstName, LastName: lastName}\n\t_, err = Me.Put(Ledger, fmt.Sprintf(\"account.%s\", acct.ID), ToJSON(acct))\n\treturn\n}", "func NewFund(initialBalance int) *Fund {\n\t// We can return a pointer to a new struct without worrying about\n\t// whether it's on the stack or heap: Go figures that out for us.\n\treturn &Fund{\n\t\tbalance: initialBalance,\n\t}\n}", "func NewFund(initialBalance int) *Fund {\n\t// We can return a pointer to a new struct without worrying about\n\t// whether it's on the stack or heap: Go figures that out for us.\n\treturn &Fund{\n\t\tbalance: initialBalance,\n\t}\n}", "func createAccount(gm *gomatrix.Client) (accessToken, userID string, err error) {\n username := \"testing-\" + randString(5)\n // Get the session token\n req := &gomatrix.ReqRegister{\n Username: username,\n Password: testPass,\n }\n _, respInt, err := gm.Register(req)\n if err != nil {\n return\n }\n\n // Make a dummy register request\n req = &gomatrix.ReqRegister{\n Username: username,\n Password: testPass,\n Auth: struct {\n Session string\n }{\n Session: respInt.Session,\n },\n }\n resp, err := gm.RegisterDummy(req)\n if err != nil {\n return\n }\n\n // Save the access token and UserID\n accessToken = resp.AccessToken\n userID = resp.UserID\n return\n}", "func (s SecureValueTypeRentalAgreement) construct() SecureValueTypeClass { return &s }", "func NewAccount(id, entityID string) *Account {\n\treturn &Account{\n\t\tID: id,\n\t\tEntityID: entityID,\n\t\tWallets: make([]Wallet, 0),\n\t}\n}", "func NewCoinbase(proof, score, R []byte) *Coinbase {\n\treturn &Coinbase{\n\t\tProof: proof,\n\t\tScore: score,\n\t\tR: R,\n\t}\n}", "func NewBusinessScenarioPlanner()(*BusinessScenarioPlanner) {\n m := &BusinessScenarioPlanner{\n Entity: *NewEntity(),\n }\n return m\n}", "func createRequestAccount() *data.Account {\n\taccount := test.NewAccountDataFromFile(\"create-request.json\")\n\treturn &account.Account\n}", "func New(OrganisationID string, BaseURL string) *Client {\n\tconfig := config{\n\t\tURL: BaseURL,\n\t\tOrganisationID: OrganisationID,\n\t\tclient: &http.Client{},\n\t}\n\treturn &Client{\n\t\tAccount: AccountEndpoint{\n\t\t\tconfig: &config,\n\t\t},\n\t}\n}", "func NewRBACAccount(accountName string, config *model.Configuration, settings ExportSettings) ([]helm.Node, error) {\n\tvar resources []helm.Node\n\tblock := authModeRBAC(settings)\n\n\taccount, ok := config.Authorization.Accounts[accountName]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Account %s not found\", accountName)\n\t}\n\n\tif len(account.UsedBy) < 1 {\n\t\t// Nothing uses this account\n\t\t// Possibly, we generated a privileged version instead\n\t\treturn nil, nil\n\t}\n\n\t// If we want to modify the default account, there's no need to create it\n\t// first -- it already exists\n\tif accountName != \"default\" {\n\t\tvar instanceGroupNames []string\n\t\tfor instanceGroupName := range account.UsedBy {\n\t\t\tinstanceGroupNames = append(instanceGroupNames, fmt.Sprintf(\"- %s\", instanceGroupName))\n\t\t}\n\t\tsort.Strings(instanceGroupNames)\n\t\tdescription := fmt.Sprintf(\n\t\t\t\"Service account \\\"%s\\\" is used by the following instance groups:\\n%s\",\n\t\t\taccountName,\n\t\t\tstrings.Join(instanceGroupNames, \"\\n\"))\n\n\t\tcb := NewConfigBuilder().\n\t\t\tSetSettings(&settings).\n\t\t\tSetAPIVersion(\"v1\").\n\t\t\tSetKind(\"ServiceAccount\").\n\t\t\tSetName(accountName).\n\t\t\tAddModifier(block).\n\t\t\tAddModifier(helm.Comment(description))\n\t\tserviceAccount, err := cb.Build()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to build a new kube config: %v\", err)\n\t\t}\n\t\tresources = append(resources, serviceAccount)\n\t}\n\n\t// For each role, create a role binding\n\tfor _, roleName := range account.Roles {\n\t\t// Embed the role first, if it's only used by this binding\n\t\tvar usedByAccounts []string\n\t\tfor accountName := range config.Authorization.RoleUsedBy[roleName] {\n\t\t\tusedByAccounts = append(usedByAccounts, fmt.Sprintf(\"- %s\", accountName))\n\t\t}\n\t\tif len(usedByAccounts) < 2 {\n\t\t\trole, err := NewRBACRole(\n\t\t\t\troleName,\n\t\t\t\tRBACRoleKindRole,\n\t\t\t\tconfig.Authorization.Roles[roleName],\n\t\t\t\tsettings)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\trole.Set(helm.Comment(fmt.Sprintf(`Role \"%s\" only used by account \"%s\"`, roleName, usedByAccounts)))\n\t\t\tresources = append(resources, role)\n\t\t}\n\n\t\tcb := NewConfigBuilder().\n\t\t\tSetSettings(&settings).\n\t\t\tSetAPIVersion(\"rbac.authorization.k8s.io/v1\").\n\t\t\tSetKind(\"RoleBinding\").\n\t\t\tSetName(fmt.Sprintf(\"%s-%s-binding\", accountName, roleName)).\n\t\t\tAddModifier(block).\n\t\t\tAddModifier(helm.Comment(fmt.Sprintf(`Role binding for service account \"%s\" and role \"%s\"`,\n\t\t\t\taccountName,\n\t\t\t\troleName)))\n\t\tbinding, err := cb.Build()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to build a new kube config: %v\", err)\n\t\t}\n\t\tsubjects := helm.NewList(helm.NewMapping(\n\t\t\t\"kind\", \"ServiceAccount\",\n\t\t\t\"name\", accountName))\n\t\tbinding.Add(\"subjects\", subjects)\n\t\tbinding.Add(\"roleRef\", helm.NewMapping(\n\t\t\t\"apiGroup\", \"rbac.authorization.k8s.io\",\n\t\t\t\"kind\", \"Role\",\n\t\t\t\"name\", roleName))\n\t\tresources = append(resources, binding)\n\t}\n\n\t// We have no proper namespace default for kube configuration.\n\tnamespace := \"~\"\n\tif settings.CreateHelmChart {\n\t\tnamespace = \"{{ .Release.Namespace }}\"\n\t}\n\n\t// For each cluster role, create a cluster role binding\n\t// And if the cluster role is only used here, embed that too\n\tfor _, clusterRoleName := range account.ClusterRoles {\n\t\t// Embed the cluster role first, if it's only used by this binding\n\t\tvar accountNames []string\n\t\tfor accountName := range config.Authorization.ClusterRoleUsedBy[clusterRoleName] {\n\t\t\taccountNames = append(accountNames, accountName)\n\t\t}\n\t\tif len(accountNames) < 2 {\n\t\t\trole, err := NewRBACRole(\n\t\t\t\tclusterRoleName,\n\t\t\t\tRBACRoleKindClusterRole,\n\t\t\t\tconfig.Authorization.ClusterRoles[clusterRoleName],\n\t\t\t\tsettings)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\trole.Set(helm.Comment(fmt.Sprintf(`Cluster role \"%s\" only used by account \"%s\"`, clusterRoleName, accountNames)))\n\t\t\tresources = append(resources, role)\n\t\t}\n\n\t\tcb := NewConfigBuilder().\n\t\t\tSetSettings(&settings).\n\t\t\tSetAPIVersion(\"rbac.authorization.k8s.io/v1\").\n\t\t\tSetKind(\"ClusterRoleBinding\").\n\t\t\tAddModifier(block).\n\t\t\tAddModifier(helm.Comment(fmt.Sprintf(`Cluster role binding for service account \"%s\" and cluster role \"%s\"`,\n\t\t\t\taccountName,\n\t\t\t\tclusterRoleName)))\n\t\tif settings.CreateHelmChart {\n\t\t\tcb.SetNameHelmExpression(\n\t\t\t\tfmt.Sprintf(`{{ template \"fissile.SanitizeName\" (printf \"%%s-%s-%s-cluster-binding\" .Release.Namespace) }}`,\n\t\t\t\t\taccountName,\n\t\t\t\t\tclusterRoleName))\n\t\t} else {\n\t\t\tcb.SetName(fmt.Sprintf(\"%s-%s-cluster-binding\", accountName, clusterRoleName))\n\t\t}\n\t\tbinding, err := cb.Build()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to build a new kube config: %v\", err)\n\t\t}\n\t\tsubjects := helm.NewList(helm.NewMapping(\n\t\t\t\"kind\", \"ServiceAccount\",\n\t\t\t\"name\", accountName,\n\t\t\t\"namespace\", namespace))\n\t\tbinding.Add(\"subjects\", subjects)\n\t\troleRef := helm.NewMapping(\n\t\t\t\"kind\", \"ClusterRole\",\n\t\t\t\"apiGroup\", \"rbac.authorization.k8s.io\")\n\t\tif settings.CreateHelmChart {\n\t\t\troleRef.Add(\"name\", fmt.Sprintf(`{{ template \"fissile.SanitizeName\" (printf \"%%s-cluster-role-%s\" .Release.Namespace) }}`, clusterRoleName))\n\t\t} else {\n\t\t\troleRef.Add(\"name\", clusterRoleName)\n\t\t}\n\t\tbinding.Add(\"roleRef\", roleRef)\n\t\tresources = append(resources, binding)\n\t}\n\n\treturn resources, nil\n}", "func NewAccount(username string) (*AccountRow, error) {\n\tquery := `\n\t\tinsert into accounts (user_name)\n\t\t\tvalues ($1)\n\t\t\ton conflict (user_name)\n\t\t\t\tdo nothing\n\t\treturning\n\t\t\tid, user_name`\n\n\trowData := &AccountRow{}\n\trow := GlobalConn.QueryRow(query, username)\n\n\tif err := row.Scan(&rowData.ID, &rowData.Name); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rowData, nil\n}", "func CreateAccount(w http.ResponseWriter, r *http.Request) {\n\tvar acc models.Account\n\t_ = json.NewDecoder(r.Body).Decode(&acc)\n\n\tracc, err := models.CreateAccount(acc)\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t_, _ = fmt.Fprintf(w, err.Error())\n\t} else {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t_ = json.NewEncoder(w).Encode(racc)\n\t}\n}", "func (account *Account) create(accountType string) *Account {\n\tfmt.Println(\"account creation with type\")\n\taccount.accountType = accountType\n\treturn account\n}", "func (r *Reconciler) CreateNooBaaAccount() error {\n\tlog := r.Logger\n\n\tif r.NooBaaAccount == nil {\n\t\treturn fmt.Errorf(\"NooBaaAccount not loaded %#v\", r)\n\t}\n\n\tcreateAccountParams := nb.CreateAccountParams{\n\t\tName: r.NooBaaAccount.Name,\n\t\tEmail: r.NooBaaAccount.Name,\n\t\tDefaultResource: r.NooBaaAccount.Spec.DefaultResource,\n\t\tHasLogin: false,\n\t\tS3Access: true,\n\t\tAllowBucketCreate: r.NooBaaAccount.Spec.AllowBucketCreate,\n\t}\n\n\tif r.NooBaaAccount.Spec.NsfsAccountConfig != nil {\n\t\tcreateAccountParams.NsfsAccountConfig = &nbv1.AccountNsfsConfig{\n\t\t\tUID: r.NooBaaAccount.Spec.NsfsAccountConfig.UID,\n\t\t\tGID: r.NooBaaAccount.Spec.NsfsAccountConfig.GID,\n\t\t\tNewBucketsPath: r.NooBaaAccount.Spec.NsfsAccountConfig.NewBucketsPath,\n\t\t\tNsfsOnly: r.NooBaaAccount.Spec.NsfsAccountConfig.NsfsOnly,\n\t\t}\n\t}\n\n\taccountInfo, err := r.NBClient.CreateAccountAPI(createAccountParams)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar accessKeys nb.S3AccessKeys\n\t// if we didn't get the access keys in the create_account reply we might be talking to an older noobaa version (prior to 5.1)\n\t// in that case try to get it using read account\n\tif len(accountInfo.AccessKeys) == 0 {\n\t\tlog.Info(\"CreateAccountAPI did not return access keys. calling ReadAccountAPI to get keys..\")\n\t\treadAccountReply, err := r.NBClient.ReadAccountAPI(nb.ReadAccountParams{Email: r.NooBaaAccount.Name})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\taccessKeys = readAccountReply.AccessKeys[0]\n\t} else {\n\t\taccessKeys = accountInfo.AccessKeys[0]\n\t}\n\tr.Secret.StringData = map[string]string{}\n\tr.Secret.StringData[\"AWS_ACCESS_KEY_ID\"] = accessKeys.AccessKey\n\tr.Secret.StringData[\"AWS_SECRET_ACCESS_KEY\"] = accessKeys.SecretKey\n\tr.Own(r.Secret)\n\terr = r.Client.Create(r.Ctx, r.Secret)\n\tif err != nil {\n\t\tr.Logger.Errorf(\"got error on NooBaaAccount creation. error: %v\", err)\n\t\treturn err\n\t}\n\n\tlog.Infof(\"✅ Successfully created account %q\", r.NooBaaAccount.Name)\n\treturn nil\n}", "func NewAccount() *Account {\n\tpriv, _ := ecdsa.GenerateKey(crypto.S256(), cryptorand.Reader)\n\tpub := base64.URLEncoding.EncodeToString(\n\t\tcrypto.FromECDSAPub(&priv.PublicKey))\n\taddr := hex.EncodeToString(crypto.PubkeyToAddress(priv.PublicKey).Bytes())\n\treturn &Account{\n\t\tID: NewUUID(),\n\t\tEthAddr: addr,\n\t\tPublicKey: pub,\n\t\tPrivateKey: base64.URLEncoding.EncodeToString(crypto.FromECDSA(priv)),\n\t}\n}", "func newPerson(name string,class string, nationality string ) *Person {\n\treturn &Person{name: name,job: class, nationality: nationality}\n\n}", "func NewClawbackGrantAction(\n\tfunderAddress string,\n\tsk StakingKeeper,\n\tgrantStartTime int64,\n\tgrantLockupPeriods, grantVestingPeriods []Period,\n\tgrantCoins sdk.Coins,\n) exported.AddGrantAction {\n\treturn clawbackGrantAction{\n\t\tfunderAddress: funderAddress,\n\t\tsk: sk,\n\t\tgrantStartTime: grantStartTime,\n\t\tgrantLockupPeriods: grantLockupPeriods,\n\t\tgrantVestingPeriods: grantVestingPeriods,\n\t\tgrantCoins: grantCoins,\n\t}\n}", "func NewAccount(email, password string) (*Account, error) {\n\thashedPassword, err := hash(password)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Account{\n\t\tEmail: email,\n\t\tPassword: hashedPassword,\n\t\tVerified: false,\n\t\tVerificationID: uuid.New().String(),\n\t}, nil\n}", "func new(master_key string) Ca {\n\tcatls, err := tls.LoadX509KeyPair(\"../storage/root-certificate/ca_cert.pem\", \"../storage/root-certificate/ca_key.pem\")\n\tcheck(err)\n\tfirst_start_time := time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC).AddDate(0, 0, 0)\n\treturn Ca{catls, master_key, first_start_time}\n}" ]
[ "0.63165385", "0.62145144", "0.6156019", "0.6112193", "0.60393506", "0.6007511", "0.5856643", "0.58285093", "0.58285093", "0.5770267", "0.56909066", "0.561485", "0.551723", "0.5479558", "0.54709643", "0.54680747", "0.5435082", "0.54297704", "0.5414012", "0.54114395", "0.54044974", "0.54028434", "0.53938144", "0.5376972", "0.5375555", "0.5357546", "0.5350232", "0.53483385", "0.53322136", "0.5318299", "0.5315906", "0.5282893", "0.52680606", "0.526588", "0.5253027", "0.52391535", "0.5237239", "0.5231092", "0.52102333", "0.5208385", "0.52044654", "0.52017343", "0.51992774", "0.51855445", "0.5182337", "0.51620185", "0.51544577", "0.5117961", "0.5104099", "0.5101882", "0.5093717", "0.5089297", "0.508741", "0.50854784", "0.508262", "0.50777924", "0.5066441", "0.50594157", "0.50582904", "0.5055537", "0.5054489", "0.5051452", "0.5046636", "0.50377655", "0.50345886", "0.5033626", "0.5021296", "0.5017964", "0.50127566", "0.50118977", "0.5010847", "0.5001309", "0.49991637", "0.49952903", "0.49897137", "0.4981563", "0.4971323", "0.49693838", "0.49655354", "0.49554536", "0.49532548", "0.49493697", "0.49493697", "0.4947169", "0.49416807", "0.493833", "0.49324596", "0.49222118", "0.48960105", "0.48875386", "0.48835057", "0.4882358", "0.48815426", "0.48782998", "0.48764876", "0.4876422", "0.48762697", "0.48731366", "0.48709914", "0.48674107" ]
0.75940603
0
GetVestedCoins returns the total number of vested coins. If no coins are vested, nil is returned.
func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins { // It's likely that one or the other schedule will be nearly trivial, // so there should be little overhead in recomputing the conjunction each time. coins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime)) if coins.IsZero() { return nil } return coins }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (keeper BaseViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"crypto\"`\n\t}\n\tjsonData, err := doTauRequest(1, \"GET\", \"data/coins\", nil)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\treturn d.Crypto, nil\n}", "func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime()))\n}", "func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (ck CoinKeeper) GetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Coins {\n\tacc := ck.am.GetAccount(ctx, addr)\n\treturn acc.GetCoins()\n}", "func (t *TauAPI) GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"cryto\"` //typo from api\n\t\tFiat []Coin `json:\"fiat\"`\n\t}\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"GET\",\n\t\tPath: \"coins\",\n\t})\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\tc = append(d.Crypto, d.Fiat...)\n\treturn c, nil\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (candidate *Candidate) GetTotalBipStake() *big.Int {\n\tcandidate.lock.RLock()\n\tdefer candidate.lock.RUnlock()\n\n\treturn big.NewInt(0).Set(candidate.totalBipStake)\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func (k Keeper) GetWinnerIncentives(ctx sdk.Context) float32 {\n\tgames := float32(k.GetGames(ctx))\n\tvotes := float32(k.GetVotes(ctx))\n\tgVR := float32(k.GetParams(ctx).GameVoteRatio) / 100\n\treturn games / (votes*gVR + games)\n}", "func (m *Client) GetCoins() ([]string, error) {\n\tresp, err := m.Service.GetCoins()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error requesting coin list: %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tvar response []string\n\terr = json.NewDecoder(resp.Body).Decode(&response)\n\tif err != nil {\n\t\tmsg, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"error decoding coin list: %s: %s\", msg, err)\n\t}\n\n\treturn response, nil\n}", "func (r *ParseResult) GetVoutAmount(vout int) (*big.Int, error) {\n\tamt := big.NewInt(0)\n\n\tif !(r.TokenType == TokenTypeFungible01 ||\n\t\tr.TokenType == TokenTypeNft1Child41 ||\n\t\tr.TokenType == TokenTypeNft1Group81) {\n\t\treturn nil, errors.New(\"cannot extract amount for not type 1 or NFT1 token\")\n\t}\n\n\tif vout == 0 {\n\t\treturn amt, nil\n\t}\n\n\tif r.TransactionType == TransactionTypeSend {\n\t\tif vout > len(r.Data.(SlpSend).Amounts) {\n\t\t\treturn amt, nil\n\t\t}\n\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpSend).Amounts[vout-1])), nil\n\t} else if r.TransactionType == TransactionTypeMint {\n\t\tif vout == 1 {\n\t\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpMint).Qty)), nil\n\t\t}\n\t\treturn amt, nil\n\t} else if r.TransactionType == TransactionTypeGenesis {\n\t\tif vout == 1 {\n\t\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpGenesis).Qty)), nil\n\t\t}\n\t\treturn amt, nil\n\t}\n\treturn nil, errors.New(\"unknown error getting vout amount\")\n}", "func (_TokenVesting *TokenVestingCaller) VestedAmount(opts *bind.CallOpts, _token common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenVesting.contract.Call(opts, out, \"vestedAmount\", _token)\n\treturn *ret0, err\n}", "func (_TokenVesting *TokenVestingCallerSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (_TokenVesting *TokenVestingSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (_Bindings *BindingsCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func coins(a int) int {\n\tif a == 0 {\n\t\treturn 0\n\t}\n\treturn doCoins(a, 25)\n}", "func GetCoins(accCoins []types.Coin) AccountCoins {\n\tcoins := make(AccountCoins, 0)\n\tfor _, coin := range accCoins {\n\t\tcoins = append(coins, AccountCoin{Amount: uint64(coin.Amount), Denom: coin.Denom})\n\t}\n\treturn coins\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (o *LoyaltySubLedger) GetTotalSpentPoints() float32 {\n\tif o == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\n\treturn o.TotalSpentPoints\n}", "func (r *Repository) GetAmountsOfManageCandidates(ctx context.Context, companyID string) (int32, int32, error) {\n\tobjCompanyID, err := primitive.ObjectIDFromHex(companyID)\n\tif err != nil {\n\t\treturn 0, 0, errors.New(`wrong_id`)\n\t}\n\n\tamount := struct {\n\t\tSaved int32 `bson:\"saved_candidates\"`\n\t\tSkipped int32 `bson:\"skipped_candidates\"`\n\t\t// Alerts int32 `bson:\"alerts\"`\n\t}{}\n\n\tcursor, err := r.companiesCollection.Aggregate(\n\t\tctx,\n\t\t[]bson.M{\n\t\t\t{\n\t\t\t\t\"$match\": bson.M{\n\t\t\t\t\t\"company_id\": objCompanyID,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$addFields\": bson.M{\n\t\t\t\t\t\"saved_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$saved_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t\"skipped_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$skipped_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t// \"alerts\": bson.M{\n\t\t\t\t\t// \t\"$size\": \"$alerts\", // TODO:\n\t\t\t\t\t// },\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$project\": bson.M{\n\t\t\t\t\t\"saved_candidates\": 1,\n\t\t\t\t\t\"skipped_candidates\": 1,\n\t\t\t\t\t// \"alerts\": 1,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tif err == mongo.ErrNoDocuments {\n\t\t\treturn 0, 0, errors.New(`not_found`)\n\t\t}\n\t\treturn 0, 0, err\n\t}\n\tdefer cursor.Close(ctx)\n\n\tif cursor.Next(ctx) {\n\t\terr = cursor.Decode(&amount)\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\t}\n\n\treturn amount.Saved, amount.Skipped, nil\n}", "func (_Bindings *BindingsSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func (o *Transaction) GetCounterparties() []TransactionCounterparty {\n\tif o == nil || o.Counterparties == nil {\n\t\tvar ret []TransactionCounterparty\n\t\treturn ret\n\t}\n\treturn *o.Counterparties\n}", "func (_CrToken *CrTokenCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (_Bindings *BindingsCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"totalReserves\")\n\treturn *ret0, err\n}", "func (c Cart) GetVoucherSavings() domain.Price {\n\tprice := domain.Price{}\n\tvar err error\n\n\tfor _, item := range c.Totalitems {\n\t\tif item.Type == TotalsTypeVoucher {\n\t\t\tprice, err = price.Add(item.Price)\n\t\t\tif err != nil {\n\t\t\t\treturn price\n\t\t\t}\n\t\t}\n\t}\n\n\tif price.IsNegative() {\n\t\treturn domain.Price{}\n\t}\n\n\treturn price\n}", "func (_CrToken *CrTokenCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _CrToken.contract.Call(opts, &out, \"totalReserves\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_CrToken *CrTokenSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (p *Player) CashSpentTotal() int {\n\treturn p.AdditionalPlayerInformation.TotalCashSpent\n}", "func (keeper ViewKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (keeper BaseViewKeeper) HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (keeper Keeper) SubtractCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\treturn subtractCoins(ctx, keeper.am, addr, amt)\n}", "func (cm *ConnectionManager) sumDeposits() *big.Int {\n\tchs := cm.openChannels()\n\tvar sum = big.NewInt(0)\n\tfor _, c := range chs {\n\t\tsum.Add(sum, c.OurContractBalance)\n\t}\n\treturn sum\n}", "func (_Vault *VaultCaller) GetDecimals(opts *bind.CallOpts, token common.Address) (uint8, error) {\n\tvar (\n\t\tret0 = new(uint8)\n\t)\n\tout := ret0\n\terr := _Vault.contract.Call(opts, out, \"getDecimals\", token)\n\treturn *ret0, err\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func (o *AllocationList) GetInvested() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Invested\n}", "func (e *Election) Votes() int {\n\tcount := 0\n\tfor _, ballot := range e.ballots {\n\t\tif ballot {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}", "func (_Vault *VaultCallerSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func (_Vault *VaultSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock()\n\treturn dcr.returnCoins(unspents)\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (_Contracts *ContractsCaller) VotersCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contracts.contract.Call(opts, out, \"votersCount\")\n\treturn *ret0, err\n}", "func (cs *Coins) CoinSelect(amount uint64, asset string) (unspents []explorer.Utxo, change uint64, err error) {\n\tchange = 0\n\tunspents = []explorer.Utxo{}\n\tavailableSats := uint64(0)\n\n\tfor index, unspent := range cs.Utxos {\n\t\tu := unspent\n\t\tassetHash := u.Asset()\n\t\tamountSatoshis := u.Value()\n\t\tif len(u.AssetCommitment()) > 0 && len(u.ValueCommitment()) > 0 {\n\t\t\tbk := cs.BlindingKey\n\t\t\tif len(cs.BlindingKeys) > 0 {\n\t\t\t\tbk = cs.BlindingKeys[index]\n\t\t\t}\n\t\t\tav, err := unblindUxto(u, bk)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t\tassetHash = av.asset\n\t\t\tamountSatoshis = av.value\n\t\t}\n\t\tif asset == assetHash {\n\t\t\tunspents = append(unspents, unspent)\n\t\t\tavailableSats += amountSatoshis\n\n\t\t\tif availableSats >= amount {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif availableSats < amount {\n\t\treturn nil, 0, errors.New(\"You do not have enough coins\")\n\t}\n\n\tchange = availableSats - amount\n\n\treturn unspents, change, nil\n}", "func (_Cakevault *CakevaultSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func (_Contracts *ContractsCaller) VotesCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contracts.contract.Call(opts, out, \"votesCount\")\n\treturn *ret0, err\n}", "func (_Cakevault *CakevaultCallerSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func (keeper Keeper) GetVotes(ctx sdk.Context, proposalID uint64) (votes types.Votes) {\n\tkeeper.IterateVotes(ctx, proposalID, func(vote types.Vote) bool {\n\t\tvotes = append(votes, vote)\n\t\treturn false\n\t})\n\treturn\n}", "func TotalCoinsInvariant(ak auth.AccountKeeper, totalSupplyFn func() sdk.Coins) sdk.Invariant {\n\treturn func(ctx sdk.Context) error {\n\t\ttotalCoins := sdk.NewCoins()\n\n\t\tchkAccount := func(acc auth.Account) bool {\n\t\t\tcoins := acc.GetCoins()\n\t\t\ttotalCoins = totalCoins.Add(coins)\n\t\t\treturn false\n\t\t}\n\n\t\tak.IterateAccounts(ctx, chkAccount)\n\t\tif !totalSupplyFn().IsEqual(totalCoins) {\n\t\t\treturn errors.New(\"total calculated coins doesn't equal expected coins\")\n\t\t}\n\t\treturn nil\n\t}\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tlockedOutputs, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, output := range lockedOutputs {\n\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, output.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, output.Vout, true)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), translateRPCCancelErr(err))\n\t\t}\n\t\tvar address string\n\t\tif len(txOut.ScriptPubKey.Addresses) > 0 {\n\t\t\taddress = txOut.ScriptPubKey.Addresses[0]\n\t\t}\n\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\treturn coins, nil\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, txout := range unspents {\n\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: txout.Address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr = dcr.node.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\n\treturn coins, nil\n}", "func (o *Transaction) GetCounterpartiesOk() (*[]TransactionCounterparty, bool) {\n\tif o == nil || o.Counterparties == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Counterparties, true\n}", "func (_MonsterOwnership *MonsterOwnershipSession) TotalSupply() (*big.Int, error) {\n\treturn _MonsterOwnership.Contract.TotalSupply(&_MonsterOwnership.CallOpts)\n}", "func (gc *GovernanceContract) TotalVotingPower() (hexutil.Big, error) {\n\treturn gc.repo.GovernanceTotalWeight(&gc.Address)\n}", "func (o *AvailableBudget) GetSpentInBudgets() []BudgetSpent {\n\tif o == nil || o.SpentInBudgets == nil {\n\t\tvar ret []BudgetSpent\n\t\treturn ret\n\t}\n\treturn *o.SpentInBudgets\n}", "func (_Gatekeeper *GatekeeperCaller) GetRootsCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Gatekeeper.contract.Call(opts, out, \"GetRootsCount\")\n\treturn *ret0, err\n}", "func (c *CoordinatorHelper) Coins(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) ([]*types.Coin, error) {\n\tcoins, _, err := c.coinStorage.GetCoinsTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: unable to get coins\", err)\n\t}\n\n\tcoinsToReturn := []*types.Coin{}\n\tfor _, coin := range coins {\n\t\tif types.Hash(coin.Amount.Currency) != types.Hash(currency) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcoinsToReturn = append(coinsToReturn, coin)\n\t}\n\n\treturn coinsToReturn, nil\n}", "func (s *Store) GetTotalSupply() *big.Int {\n\tamountBytes, err := s.table.TotalSupply.Get([]byte(\"c\"))\n\tif err != nil {\n\t\ts.Log.Crit(\"Failed to get key-value\", \"err\", err)\n\t}\n\tif amountBytes == nil {\n\t\treturn big.NewInt(0)\n\t}\n\treturn new(big.Int).SetBytes(amountBytes)\n}", "func (a *Account) TotalReceived(confirms int) (float64, error) {\n\tbs, err := GetCurBlock()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar totalSatoshis int64\n\tfor _, record := range a.TxStore.SortedRecords() {\n\t\ttxout, ok := record.(*tx.RecvTxOut)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ignore change.\n\t\tif txout.Change() {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Tally if the appropiate number of block confirmations have passed.\n\t\tif confirmed(confirms, txout.Height(), bs.Height) {\n\t\t\ttotalSatoshis += txout.Value()\n\t\t}\n\t}\n\n\treturn float64(totalSatoshis) / float64(btcutil.SatoshiPerBitcoin), nil\n}", "func (r SlpSend) GetVoutValue(vout int) (*big.Int, bool) {\n\tif vout == 0 {\n\t\treturn nil, false\n\t}\n\n\tif vout > len(r.Amounts) {\n\t\treturn nil, false\n\t}\n\n\treturn new(big.Int).SetUint64(r.Amounts[vout-1]), false\n}", "func (m *TeamSummary) GetGuestsCount()(*int32) {\n return m.guestsCount\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tlockedOutputs, err := dcr.wallet.LockedOutputs(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, output := range lockedOutputs {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, output.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, txHash, output.Vout, output.Tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), err)\n\t\t\t}\n\t\t\tvar address string\n\t\t\tif len(txOut.Addresses) > 0 {\n\t\t\t\taddress = txOut.Addresses[0]\n\t\t\t}\n\t\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\treturn coins, nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunspents, err := dcr.wallet.Unspents(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, txout := range unspents {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: txout.Address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return an error if some coins are still not found.\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn coins, nil\n}", "func (_BtlCoin *BtlCoinSession) TotalSupply() (*big.Int, error) {\n\treturn _BtlCoin.Contract.TotalSupply(&_BtlCoin.CallOpts)\n}", "func (u *User) GetTotalPrivateRepos() int {\n\tif u == nil || u.TotalPrivateRepos == nil {\n\t\treturn 0\n\t}\n\treturn *u.TotalPrivateRepos\n}", "func (k Keeper) GetTotalSupply(ctx sdk.Context, denom string) uint64 {\n\tstore := ctx.KVStore(k.storeKey)\n\tbz := store.Get(types.KeyCollection(denom))\n\tif len(bz) == 0 {\n\t\treturn 0\n\t}\n\n\tvar supply uint64\n\tk.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &supply)\n\treturn supply\n}", "func (c Checkout) Total() int {\n\ttotal := 0\n\tfor code, quantity := range c.basket {\n\t\toffer, exists := offers[code]\n\t\tif exists {\n\t\t\ttotal += calculateOfferPrice(code, quantity, offer)\n\t\t} else {\n\t\t\ttotal += calculatePrice(code, quantity)\n\t\t}\n\t}\n\treturn total\n}", "func (keeper Keeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (supply Supply) GetTotal() sdk.Coins {\n\treturn supply.Total\n}", "func (k *Keeper) GetVaultTotalShares(\n\tctx sdk.Context,\n\tdenom string,\n) (types.VaultShare, bool) {\n\tvault, found := k.GetVaultRecord(ctx, denom)\n\tif !found {\n\t\treturn types.VaultShare{}, false\n\t}\n\n\treturn vault.TotalShares, true\n}", "func (keeper SendKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (k Keeper) GetVotes(ctx sdk.Context) int64 {\n\treturn k.GetRunningAverageTotal(ctx, Votes24ValueKey)\n}", "func (_MonsterOwnership *MonsterOwnershipCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _MonsterOwnership.contract.Call(opts, out, \"totalSupply\")\n\treturn *ret0, err\n}", "func subtractCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\toldCoins := getCoins(ctx, am, addr)\n\tnewCoins := oldCoins.Minus(amt)\n\tif !newCoins.IsNotNegative() {\n\t\treturn amt, sdk.ErrInsufficientCoins(fmt.Sprintf(\"%s < %s\", oldCoins, amt))\n\t}\n\terr := setCoins(ctx, am, addr, newCoins)\n\treturn newCoins, err\n}", "func (_Cakevault *CakevaultCaller) TotalShares(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"totalShares\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_Bindings *BindingsSession) TotalSupply() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalSupply(&_Bindings.CallOpts)\n}", "func (_MonsterOwnership *MonsterOwnershipCallerSession) TotalSupply() (*big.Int, error) {\n\treturn _MonsterOwnership.Contract.TotalSupply(&_MonsterOwnership.CallOpts)\n}", "func (btc *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*output, 0, len(unspents))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, unspent := range unspents {\n\t\top, err := btc.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %v\", err)\n\t\t}\n\t\tops = append(ops, op)\n\t\tdelete(btc.fundingCoins, outpointID(op.txHash.String(), op.vout))\n\t}\n\treturn btc.wallet.LockUnspent(true, ops)\n}", "func (_Lmc *LmcSession) TotalStaked() (*big.Int, error) {\n\treturn _Lmc.Contract.TotalStaked(&_Lmc.CallOpts)\n}", "func (_Contracts *ContractsCallerSession) VotersCount() (*big.Int, error) {\n\treturn _Contracts.Contract.VotersCount(&_Contracts.CallOpts)\n}", "func (a *Agent) GetPeersCount() uint32 {\n\treturn atomic.LoadUint32(&a.peersCount)\n}", "func (_Bep20 *Bep20Caller) GetCurrentVotes(opts *bind.CallOpts, account common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Bep20.contract.Call(opts, &out, \"getCurrentVotes\", account)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_Contract *ContractSession) TotalSupply() (*big.Int, error) {\n\treturn _Contract.Contract.TotalSupply(&_Contract.CallOpts)\n}", "func (v *Vending) Get(c echo.Context) error {\n\tif v.chocolate == 0 {\n\t\treturn c.String(http.StatusOK, \"Out of chocolate please refill\")\n\t}\n\treturn c.String(http.StatusOK, fmt.Sprintf(\"There are %v pieces of chocolate left.\", v.chocolate))\n}", "func (p *PostgresDb) GetDueAmount(customerID int) (float64, error) {\n\tvar dueAmount float64\n\tpaymentsQuery := `\n\t\tSELECT COALESCE(SUM(amount), 0) \n\t\tFROM payment \n\t\tWHERE customer_id=$1 \n\t\tGROUP BY customer_id\n\t`\n\tvar sumPayments float64\n\terr := p.dbConn.Get(&sumPayments, paymentsQuery, customerID)\n\tif err != nil {\n\t\tlog.Println(\"Error getting sum payments:\", err)\n\t}\n\n\tcreditsQuery := `\t\n\t\tSELECT COALESCE(SUM(amount), 0) \n\t\tFROM credit \n\t\tWHERE customer_id=$1 \n\t\tGROUP BY customer_id\n\t`\n\tvar sumCredits float64\n\terr = p.dbConn.Get(&sumCredits, creditsQuery, customerID)\n\tif err != nil {\n\t\tlog.Println(\"Error getting sum credits:\", err)\n\t}\n\tdueAmount = sumCredits - sumPayments\n\n\treturn dueAmount, nil\n}", "func (_BtlCoin *BtlCoinCallerSession) TotalSupply() (*big.Int, error) {\n\treturn _BtlCoin.Contract.TotalSupply(&_BtlCoin.CallOpts)\n}" ]
[ "0.74722266", "0.73172396", "0.72161824", "0.706704", "0.6925188", "0.6750736", "0.67176706", "0.66681737", "0.6615126", "0.660531", "0.64609796", "0.5631008", "0.5568076", "0.55106115", "0.54429114", "0.5325035", "0.52657974", "0.5237786", "0.51828796", "0.51632583", "0.5131893", "0.5112448", "0.5034458", "0.50276333", "0.5009796", "0.49392068", "0.48955312", "0.48939472", "0.48603842", "0.480383", "0.47884604", "0.47869483", "0.47596708", "0.47185344", "0.47026804", "0.469894", "0.46980315", "0.46951202", "0.4693267", "0.46835077", "0.46667764", "0.4664738", "0.46454957", "0.46109292", "0.4594738", "0.45692697", "0.45509595", "0.45486528", "0.45296547", "0.45183954", "0.45005184", "0.44967303", "0.4495673", "0.44947934", "0.44895285", "0.44857046", "0.44737414", "0.4461048", "0.44524297", "0.44379947", "0.4424603", "0.43966484", "0.43455324", "0.4332168", "0.43264398", "0.4281783", "0.4278638", "0.42721552", "0.42706445", "0.426794", "0.42653513", "0.42525", "0.4250256", "0.42379352", "0.42303318", "0.4228896", "0.42206216", "0.42203066", "0.421838", "0.4215596", "0.42036572", "0.4202401", "0.4197216", "0.41959214", "0.41877368", "0.41693115", "0.41637418", "0.41631967", "0.41557708", "0.41531467", "0.41506422", "0.4140594", "0.41404185", "0.4140399", "0.4137555", "0.4136874", "0.4121365", "0.411603", "0.41088894", "0.41004112" ]
0.72799873
2
GetVestingCoins returns the total number of vesting coins. If no coins are vesting, nil is returned.
func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins { return va.OriginalVesting.Sub(va.GetVestedCoins(blockTime)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"crypto\"`\n\t}\n\tjsonData, err := doTauRequest(1, \"GET\", \"data/coins\", nil)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\treturn d.Crypto, nil\n}", "func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (keeper BaseViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime()))\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (t *TauAPI) GetCoins() (coins []Coin, error error) {\n\tvar c = []Coin{}\n\tvar d struct {\n\t\tCrypto []Coin `json:\"cryto\"` //typo from api\n\t\tFiat []Coin `json:\"fiat\"`\n\t}\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"GET\",\n\t\tPath: \"coins\",\n\t})\n\tif err != nil {\n\t\treturn c, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn c, err\n\t}\n\tc = append(d.Crypto, d.Fiat...)\n\treturn c, nil\n}", "func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func coins(a int) int {\n\tif a == 0 {\n\t\treturn 0\n\t}\n\treturn doCoins(a, 25)\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func GetCoins(accCoins []types.Coin) AccountCoins {\n\tcoins := make(AccountCoins, 0)\n\tfor _, coin := range accCoins {\n\t\tcoins = append(coins, AccountCoin{Amount: uint64(coin.Amount), Denom: coin.Denom})\n\t}\n\treturn coins\n}", "func (m *Client) GetCoins() ([]string, error) {\n\tresp, err := m.Service.GetCoins()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error requesting coin list: %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tvar response []string\n\terr = json.NewDecoder(resp.Body).Decode(&response)\n\tif err != nil {\n\t\tmsg, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"error decoding coin list: %s: %s\", msg, err)\n\t}\n\n\treturn response, nil\n}", "func (ck CoinKeeper) GetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Coins {\n\tacc := ck.am.GetAccount(ctx, addr)\n\treturn acc.GetCoins()\n}", "func (bva BaseVestingAccount) GetOriginalVesting() sdk.Coins {\n\treturn bva.OriginalVesting\n}", "func (k Keeper) GetWinnerIncentives(ctx sdk.Context) float32 {\n\tgames := float32(k.GetGames(ctx))\n\tvotes := float32(k.GetVotes(ctx))\n\tgVR := float32(k.GetParams(ctx).GameVoteRatio) / 100\n\treturn games / (votes*gVR + games)\n}", "func (o *Transaction) GetCounterparties() []TransactionCounterparty {\n\tif o == nil || o.Counterparties == nil {\n\t\tvar ret []TransactionCounterparty\n\t\treturn ret\n\t}\n\treturn *o.Counterparties\n}", "func (cs *Coins) CoinSelect(amount uint64, asset string) (unspents []explorer.Utxo, change uint64, err error) {\n\tchange = 0\n\tunspents = []explorer.Utxo{}\n\tavailableSats := uint64(0)\n\n\tfor index, unspent := range cs.Utxos {\n\t\tu := unspent\n\t\tassetHash := u.Asset()\n\t\tamountSatoshis := u.Value()\n\t\tif len(u.AssetCommitment()) > 0 && len(u.ValueCommitment()) > 0 {\n\t\t\tbk := cs.BlindingKey\n\t\t\tif len(cs.BlindingKeys) > 0 {\n\t\t\t\tbk = cs.BlindingKeys[index]\n\t\t\t}\n\t\t\tav, err := unblindUxto(u, bk)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t\tassetHash = av.asset\n\t\t\tamountSatoshis = av.value\n\t\t}\n\t\tif asset == assetHash {\n\t\t\tunspents = append(unspents, unspent)\n\t\t\tavailableSats += amountSatoshis\n\n\t\t\tif availableSats >= amount {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif availableSats < amount {\n\t\treturn nil, 0, errors.New(\"You do not have enough coins\")\n\t}\n\n\tchange = availableSats - amount\n\n\treturn unspents, change, nil\n}", "func (candidate *Candidate) GetTotalBipStake() *big.Int {\n\tcandidate.lock.RLock()\n\tdefer candidate.lock.RUnlock()\n\n\treturn big.NewInt(0).Set(candidate.totalBipStake)\n}", "func (_TokenVesting *TokenVestingCaller) VestedAmount(opts *bind.CallOpts, _token common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenVesting.contract.Call(opts, out, \"vestedAmount\", _token)\n\treturn *ret0, err\n}", "func (m *TeamSummary) GetGuestsCount()(*int32) {\n return m.guestsCount\n}", "func (_TokenVesting *TokenVestingSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (_Contracts *ContractsCaller) VotersCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contracts.contract.Call(opts, out, \"votersCount\")\n\treturn *ret0, err\n}", "func (_TokenVesting *TokenVestingCallerSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (gc *GovernanceContract) TotalVotingPower() (hexutil.Big, error) {\n\treturn gc.repo.GovernanceTotalWeight(&gc.Address)\n}", "func (m *TeamSummary) GetOwnersCount()(*int32) {\n return m.ownersCount\n}", "func (o *Transaction) GetCounterpartiesOk() (*[]TransactionCounterparty, bool) {\n\tif o == nil || o.Counterparties == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Counterparties, true\n}", "func (r *ParseResult) GetVoutAmount(vout int) (*big.Int, error) {\n\tamt := big.NewInt(0)\n\n\tif !(r.TokenType == TokenTypeFungible01 ||\n\t\tr.TokenType == TokenTypeNft1Child41 ||\n\t\tr.TokenType == TokenTypeNft1Group81) {\n\t\treturn nil, errors.New(\"cannot extract amount for not type 1 or NFT1 token\")\n\t}\n\n\tif vout == 0 {\n\t\treturn amt, nil\n\t}\n\n\tif r.TransactionType == TransactionTypeSend {\n\t\tif vout > len(r.Data.(SlpSend).Amounts) {\n\t\t\treturn amt, nil\n\t\t}\n\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpSend).Amounts[vout-1])), nil\n\t} else if r.TransactionType == TransactionTypeMint {\n\t\tif vout == 1 {\n\t\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpMint).Qty)), nil\n\t\t}\n\t\treturn amt, nil\n\t} else if r.TransactionType == TransactionTypeGenesis {\n\t\tif vout == 1 {\n\t\t\treturn amt.Add(amt, new(big.Int).SetUint64(r.Data.(SlpGenesis).Qty)), nil\n\t\t}\n\t\treturn amt, nil\n\t}\n\treturn nil, errors.New(\"unknown error getting vout amount\")\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (r *Repository) GetAmountsOfManageCandidates(ctx context.Context, companyID string) (int32, int32, error) {\n\tobjCompanyID, err := primitive.ObjectIDFromHex(companyID)\n\tif err != nil {\n\t\treturn 0, 0, errors.New(`wrong_id`)\n\t}\n\n\tamount := struct {\n\t\tSaved int32 `bson:\"saved_candidates\"`\n\t\tSkipped int32 `bson:\"skipped_candidates\"`\n\t\t// Alerts int32 `bson:\"alerts\"`\n\t}{}\n\n\tcursor, err := r.companiesCollection.Aggregate(\n\t\tctx,\n\t\t[]bson.M{\n\t\t\t{\n\t\t\t\t\"$match\": bson.M{\n\t\t\t\t\t\"company_id\": objCompanyID,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$addFields\": bson.M{\n\t\t\t\t\t\"saved_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$saved_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t\"skipped_candidates\": bson.M{\n\t\t\t\t\t\t\"$size\": \"$skipped_candidates\",\n\t\t\t\t\t},\n\t\t\t\t\t// \"alerts\": bson.M{\n\t\t\t\t\t// \t\"$size\": \"$alerts\", // TODO:\n\t\t\t\t\t// },\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"$project\": bson.M{\n\t\t\t\t\t\"saved_candidates\": 1,\n\t\t\t\t\t\"skipped_candidates\": 1,\n\t\t\t\t\t// \"alerts\": 1,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tif err == mongo.ErrNoDocuments {\n\t\t\treturn 0, 0, errors.New(`not_found`)\n\t\t}\n\t\treturn 0, 0, err\n\t}\n\tdefer cursor.Close(ctx)\n\n\tif cursor.Next(ctx) {\n\t\terr = cursor.Decode(&amount)\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\t}\n\n\treturn amount.Saved, amount.Skipped, nil\n}", "func distributeCoins(root *TreeNode) int {\n\tres := 0\n\tif root.Left != nil {\n\t\tres += distributeCoins(root.Left)\n\t\troot.Val += root.Left.Val - 1\n\t\tres += int(math.Abs(float64(root.Left.Val - 1)))\n\t}\n\tif root.Right != nil {\n\t\tres += distributeCoins(root.Right)\n\t\troot.Val += root.Right.Val - 1\n\t\tres += int(math.Abs(float64(root.Right.Val - 1)))\n\t}\n\treturn res\n}", "func TestGetSupportCoins(t *testing.T) {\n\tt.Parallel()\n\tif _, err := ok.GetSupportCoins(context.Background()); err != nil {\n\t\tt.Error(\"Okx GetSupportCoins() error\", err)\n\t}\n}", "func (keeper BaseViewKeeper) HasCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func (c *CoordinatorHelper) Coins(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) ([]*types.Coin, error) {\n\tcoins, _, err := c.coinStorage.GetCoinsTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: unable to get coins\", err)\n\t}\n\n\tcoinsToReturn := []*types.Coin{}\n\tfor _, coin := range coins {\n\t\tif types.Hash(coin.Amount.Currency) != types.Hash(currency) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcoinsToReturn = append(coinsToReturn, coin)\n\t}\n\n\treturn coinsToReturn, nil\n}", "func (n Network) VestingAccounts(ctx context.Context, launchID uint64) (vestingAccs []networktypes.VestingAccount, err error) {\n\tn.ev.Send(events.New(events.StatusOngoing, \"Fetching genesis vesting accounts\"))\n\tres, err := n.launchQuery.\n\t\tVestingAccountAll(ctx,\n\t\t\t&launchtypes.QueryAllVestingAccountRequest{\n\t\t\t\tLaunchID: launchID,\n\t\t\t},\n\t\t)\n\tif err != nil {\n\t\treturn vestingAccs, err\n\t}\n\n\tfor i, acc := range res.VestingAccount {\n\t\tparsedAcc, err := networktypes.ToVestingAccount(acc)\n\t\tif err != nil {\n\t\t\treturn vestingAccs, errors.Wrapf(err, \"error parsing vesting account %d\", i)\n\t\t}\n\n\t\tvestingAccs = append(vestingAccs, parsedAcc)\n\t}\n\n\treturn vestingAccs, nil\n}", "func (_Contracts *ContractsCaller) VotesCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contracts.contract.Call(opts, out, \"votesCount\")\n\treturn *ret0, err\n}", "func (c Cart) GetVoucherSavings() domain.Price {\n\tprice := domain.Price{}\n\tvar err error\n\n\tfor _, item := range c.Totalitems {\n\t\tif item.Type == TotalsTypeVoucher {\n\t\t\tprice, err = price.Add(item.Price)\n\t\t\tif err != nil {\n\t\t\t\treturn price\n\t\t\t}\n\t\t}\n\t}\n\n\tif price.IsNegative() {\n\t\treturn domain.Price{}\n\t}\n\n\treturn price\n}", "func (keeper ViewKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func distributeCoins(root *TreeNode) int {\n\tres := 0\n\tvar dfs func(root *TreeNode) int\n\tabs := func(a int) int {\n\t\tif a < 0 {\n\t\t\treturn -a\n\t\t}\n\t\treturn a\n\t}\n\tdfs = func(root *TreeNode) int {\n\t\tif root == nil {\n\t\t\treturn 0\n\t\t}\n\t\tleft := dfs(root.Left)\n\t\tright := dfs(root.Right)\n\t\tres += abs(left) + abs(right)\n\t\treturn left + right + root.Val - 1\n\t}\n\tdfs(root)\n\treturn res\n}", "func (_Bindings *BindingsCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func newCoins() sdk.Coins {\n\treturn sdk.Coins{\n\t\tsdk.NewInt64Coin(\"atom\", 10000000),\n\t}\n}", "func (_Gatekeeper *GatekeeperCaller) GetRootsCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Gatekeeper.contract.Call(opts, out, \"GetRootsCount\")\n\treturn *ret0, err\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tlockedOutputs, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, output := range lockedOutputs {\n\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, output.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, output.Vout, true)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), translateRPCCancelErr(err))\n\t\t}\n\t\tvar address string\n\t\tif len(txOut.ScriptPubKey.Addresses) > 0 {\n\t\t\taddress = txOut.ScriptPubKey.Addresses[0]\n\t\t}\n\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\treturn coins, nil\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, txout := range unspents {\n\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: txout.Address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr = dcr.node.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\n\treturn coins, nil\n}", "func (_Bindings *BindingsSession) TotalReserves() (*big.Int, error) {\n\treturn _Bindings.Contract.TotalReserves(&_Bindings.CallOpts)\n}", "func (cm *ConnectionManager) sumDeposits() *big.Int {\n\tchs := cm.openChannels()\n\tvar sum = big.NewInt(0)\n\tfor _, c := range chs {\n\t\tsum.Add(sum, c.OurContractBalance)\n\t}\n\treturn sum\n}", "func (_Bep20 *Bep20Caller) GetCurrentVotes(opts *bind.CallOpts, account common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Bep20.contract.Call(opts, &out, \"getCurrentVotes\", account)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func drawCoins() int {\n\treturn rand.Intn(maxCoins+1-minCoins) + minCoins\n}", "func (_Contracts *ContractsCallerSession) VotersCount() (*big.Int, error) {\n\treturn _Contracts.Contract.VotersCount(&_Contracts.CallOpts)\n}", "func (_CrToken *CrTokenCallerSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tlockedOutputs, err := dcr.wallet.LockedOutputs(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, output := range lockedOutputs {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, output.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, txHash, output.Vout, output.Tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), err)\n\t\t\t}\n\t\t\tvar address string\n\t\t\tif len(txOut.Addresses) > 0 {\n\t\t\t\taddress = txOut.Addresses[0]\n\t\t\t}\n\t\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\treturn coins, nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunspents, err := dcr.wallet.Unspents(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, txout := range unspents {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: txout.Address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return an error if some coins are still not found.\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn coins, nil\n}", "func (e *Election) Votes() int {\n\tcount := 0\n\tfor _, ballot := range e.ballots {\n\t\tif ballot {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}", "func (keeper Keeper) SubtractCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\treturn subtractCoins(ctx, keeper.am, addr, amt)\n}", "func (_Contracts *ContractsSession) VotersCount() (*big.Int, error) {\n\treturn _Contracts.Contract.VotersCount(&_Contracts.CallOpts)\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func getOVMETHTotalSupply(inStateDB *state.StateDB) *big.Int {\n\tposition := common.Big2\n\tkey := common.BytesToHash(common.LeftPadBytes(position.Bytes(), 32))\n\treturn inStateDB.GetState(OVMETHAddress, key).Big()\n}", "func (p *Player) CashSpentTotal() int {\n\treturn p.AdditionalPlayerInformation.TotalCashSpent\n}", "func (_CrToken *CrTokenSession) TotalReserves() (*big.Int, error) {\n\treturn _CrToken.Contract.TotalReserves(&_CrToken.CallOpts)\n}", "func (c Checkout) Total() int {\n\ttotal := 0\n\tfor code, quantity := range c.basket {\n\t\toffer, exists := offers[code]\n\t\tif exists {\n\t\t\ttotal += calculateOfferPrice(code, quantity, offer)\n\t\t} else {\n\t\t\ttotal += calculatePrice(code, quantity)\n\t\t}\n\t}\n\treturn total\n}", "func (a *Agent) GetPeersCount() uint32 {\n\treturn atomic.LoadUint32(&a.peersCount)\n}", "func (btc *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[string]struct{})\n\tbtc.fundingMtx.RLock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\tbtc.fundingMtx.RUnlock()\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tfundingCoin, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tcoins = append(coins, newOutput(btc.node, txHash, vout, fundingCoin.amount, fundingCoin.redeemScript))\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[opID] = struct{}{}\n\t}\n\tbtc.fundingMtx.RUnlock()\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\t_, utxoMap, _, err := btc.spendableUTXOs(0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlockers := make([]*output, 0, len(ids))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tutxo, found := utxoMap[opID]\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"funding coin %s not found\", opID)\n\t\t}\n\t\tbtc.fundingCoins[opID] = utxo\n\t\tcoin := newOutput(btc.node, utxo.txHash, utxo.vout, utxo.amount, utxo.redeemScript)\n\t\tcoins = append(coins, coin)\n\t\tlockers = append(lockers, coin)\n\t\tdelete(notFound, opID)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor opID := range notFound {\n\t\t\tids = append(ids, opID)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\terr = btc.wallet.LockUnspent(false, lockers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn coins, nil\n}", "func (_Vault *VaultSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func (_Bindings *BindingsCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"totalReserves\")\n\treturn *ret0, err\n}", "func arrangeCoins(n int) int {\n\tcount := 1\n\tfor n >= count {\n\t\tn -= count\n\t\tcount++\n\t}\n\treturn count - 1\n}", "func (_Vault *VaultCaller) GetDecimals(opts *bind.CallOpts, token common.Address) (uint8, error) {\n\tvar (\n\t\tret0 = new(uint8)\n\t)\n\tout := ret0\n\terr := _Vault.contract.Call(opts, out, \"getDecimals\", token)\n\treturn *ret0, err\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock()\n\treturn dcr.returnCoins(unspents)\n}", "func (_Vault *VaultCallerSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func (_Cakevault *CakevaultSession) TotalShares() (*big.Int, error) {\n\treturn _Cakevault.Contract.TotalShares(&_Cakevault.CallOpts)\n}", "func getMoneyAmount(n int) int {\n \n}", "func (_Bep20 *Bep20CallerSession) GetCurrentVotes(account common.Address) (*big.Int, error) {\n\treturn _Bep20.Contract.GetCurrentVotes(&_Bep20.CallOpts, account)\n}", "func TotalCoinsInvariant(ak auth.AccountKeeper, totalSupplyFn func() sdk.Coins) sdk.Invariant {\n\treturn func(ctx sdk.Context) error {\n\t\ttotalCoins := sdk.NewCoins()\n\n\t\tchkAccount := func(acc auth.Account) bool {\n\t\t\tcoins := acc.GetCoins()\n\t\t\ttotalCoins = totalCoins.Add(coins)\n\t\t\treturn false\n\t\t}\n\n\t\tak.IterateAccounts(ctx, chkAccount)\n\t\tif !totalSupplyFn().IsEqual(totalCoins) {\n\t\t\treturn errors.New(\"total calculated coins doesn't equal expected coins\")\n\t\t}\n\t\treturn nil\n\t}\n}", "func ChooseBestOutCoinsToSpent(utxos []*crypto.InputCoin, amount uint64) (\n\tresultOutputCoins []*crypto.InputCoin,\n\tremainOutputCoins []*crypto.InputCoin,\n\ttotalResultOutputCoinAmount uint64, err error) {\n\n\tresultOutputCoins = make([]*crypto.InputCoin, 0)\n\tremainOutputCoins = make([]*crypto.InputCoin, 0)\n\ttotalResultOutputCoinAmount = uint64(0)\n\n\t// either take the smallest coins, or a single largest one\n\tvar outCoinOverLimit *crypto.InputCoin\n\toutCoinsUnderLimit := make([]*crypto.InputCoin, 0)\n\tfor _, outCoin := range utxos {\n\t\tif outCoin.CoinDetails.GetValue() < amount {\n\t\t\toutCoinsUnderLimit = append(outCoinsUnderLimit, outCoin)\n\t\t} else if outCoinOverLimit == nil {\n\t\t\toutCoinOverLimit = outCoin\n\t\t} else if outCoinOverLimit.CoinDetails.GetValue() > outCoin.CoinDetails.GetValue() {\n\t\t\tremainOutputCoins = append(remainOutputCoins, outCoin)\n\t\t} else {\n\t\t\tremainOutputCoins = append(remainOutputCoins, outCoinOverLimit)\n\t\t\toutCoinOverLimit = outCoin\n\t\t}\n\t}\n\tsort.Slice(outCoinsUnderLimit, func(i, j int) bool {\n\t\treturn outCoinsUnderLimit[i].CoinDetails.GetValue() < outCoinsUnderLimit[j].CoinDetails.GetValue()\n\t})\n\tfor _, outCoin := range outCoinsUnderLimit {\n\t\tif totalResultOutputCoinAmount < amount {\n\t\t\ttotalResultOutputCoinAmount += outCoin.CoinDetails.GetValue()\n\t\t\tresultOutputCoins = append(resultOutputCoins, outCoin)\n\t\t} else {\n\t\t\tremainOutputCoins = append(remainOutputCoins, outCoin)\n\t\t}\n\t}\n\tif outCoinOverLimit != nil && (outCoinOverLimit.CoinDetails.GetValue() > 2*amount || totalResultOutputCoinAmount < amount) {\n\t\tremainOutputCoins = append(remainOutputCoins, resultOutputCoins...)\n\t\tresultOutputCoins = []*crypto.InputCoin{outCoinOverLimit}\n\t\ttotalResultOutputCoinAmount = outCoinOverLimit.CoinDetails.GetValue()\n\t} else if outCoinOverLimit != nil {\n\t\tremainOutputCoins = append(remainOutputCoins, outCoinOverLimit)\n\t}\n\tif totalResultOutputCoinAmount < amount {\n\t\treturn resultOutputCoins, remainOutputCoins, totalResultOutputCoinAmount, errors.New(\"Not enough coin\")\n\t} else {\n\t\treturn resultOutputCoins, remainOutputCoins, totalResultOutputCoinAmount, nil\n\t}\n}", "func (_CrToken *CrTokenCaller) TotalReserves(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _CrToken.contract.Call(opts, &out, \"totalReserves\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func GetTotalVestingPeriodLength(periods vesting.Periods) int64 {\n\tlength := int64(0)\n\tfor _, period := range periods {\n\t\tlength += period.Length\n\t}\n\treturn length\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigCaller) GetTransactionCount(opts *bind.CallOpts, pending bool, executed bool) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ReserveSpenderMultiSig.contract.Call(opts, out, \"getTransactionCount\", pending, executed)\n\treturn *ret0, err\n}", "func GetTotalVestingPeriodLength(periods vestingtypes.Periods) int64 {\n\tlength := int64(0)\n\tfor _, period := range periods {\n\t\tlength += period.Length\n\t}\n\treturn length\n}", "func (m *Machine) ReturnCoins() {\n\tcoins := m.cashEngine.DropCoins()\n\n\ts := fmt.Sprintf(\"-> \")\n\tfor i, c := range coins {\n\t\tif i == len(coins)-1 {\n\t\t\ts += fmt.Sprintf(\"%s\", c.value.String())\n\t\t\tcontinue\n\t\t}\n\t\ts += fmt.Sprintf(\"%s, \", c.value.String())\n\t}\n\n\tm.logger.Println(s)\n}", "func (_Bep20 *Bep20Session) GetCurrentVotes(account common.Address) (*big.Int, error) {\n\treturn _Bep20.Contract.GetCurrentVotes(&_Bep20.CallOpts, account)\n}", "func (keeper SendKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (serv *ExchangeServer) GetSupportCoins() []string {\n\tsymbols := make([]string, len(serv.coins))\n\ti := 0\n\tfor _, coin := range serv.coins {\n\t\tsymbols[i] = coin.Symbol()\n\t\ti++\n\t}\n\treturn symbols\n}", "func (o *AllocationList) GetInvested() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Invested\n}", "func (o *LoyaltySubLedger) GetTotalSpentPoints() float32 {\n\tif o == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\n\treturn o.TotalSpentPoints\n}", "func (_Gatekeeper *GatekeeperCaller) GetTransactionCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Gatekeeper.contract.Call(opts, out, \"GetTransactionCount\")\n\treturn *ret0, err\n}", "func (t *TezTracker) GetStakingRatio() (float64, error) {\n\tlockedBalanceEstimate, err := t.getLockedBalance()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tar := t.repoProvider.GetAccount()\n\tliquidBalance, err := ar.TotalBalance()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tbr := t.repoProvider.GetBaker()\n\tstakedBalance, err := br.TotalStakingBalance()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tsupply := liquidBalance + lockedBalanceEstimate\n\tif supply == 0 {\n\t\treturn 0, nil\n\t}\n\n\tlastBlock, err := t.repoProvider.GetBlock().Last()\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\n\tbakingRewards, err := br.TotalBakingRewards(\"\", lastBlock.MetaCycle-PreservedCycles, lastBlock.MetaCycle)\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\n\tendorsementRewards, err := br.TotalEndorsementRewards(\"\", lastBlock.MetaCycle-PreservedCycles, lastBlock.MetaCycle)\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\n\tstakedBalance = stakedBalance - bakingRewards - endorsementRewards\n\tratio := float64(stakedBalance) / float64(supply)\n\n\treturn ratio, nil\n}", "func ConvertSdkCoinsToWasmCoins(coins []sdk.Coin) wasmvmtypes.Coins {\n\tconverted := make(wasmvmtypes.Coins, len(coins))\n\tfor i, c := range coins {\n\t\tconverted[i] = ConvertSdkCoinToWasmCoin(c)\n\t}\n\treturn converted\n}" ]
[ "0.74396104", "0.726373", "0.714508", "0.7126855", "0.7010945", "0.670897", "0.66787076", "0.66363263", "0.6620459", "0.65084815", "0.6413031", "0.5598332", "0.55388", "0.5478214", "0.5397174", "0.535151", "0.53034747", "0.5291319", "0.5265547", "0.5263068", "0.52396154", "0.52286416", "0.5193281", "0.50844795", "0.5011713", "0.49284658", "0.49219754", "0.4904928", "0.48519877", "0.48489055", "0.48284203", "0.47899073", "0.47672805", "0.4611372", "0.45811477", "0.45748222", "0.45643818", "0.4546548", "0.45288718", "0.45240188", "0.45172656", "0.4512356", "0.44718787", "0.44657588", "0.4456784", "0.44515997", "0.4415981", "0.4414714", "0.44144577", "0.44108146", "0.4405778", "0.44037047", "0.44000402", "0.43852434", "0.43783808", "0.4366527", "0.43438405", "0.43292856", "0.4327142", "0.432488", "0.43184718", "0.43085203", "0.4295404", "0.42843035", "0.42677224", "0.425481", "0.4251709", "0.42239136", "0.422126", "0.42055273", "0.41869", "0.4186892", "0.41824117", "0.41807854", "0.4179897", "0.4177675", "0.41754848", "0.4172519", "0.41715524", "0.41699547", "0.4166136", "0.4165427", "0.41619334", "0.41605112", "0.41544116", "0.41536543", "0.41494378", "0.41377124", "0.41337442", "0.4130032", "0.412577", "0.4120538", "0.41203645", "0.41160396", "0.4106734", "0.41003996", "0.40959004", "0.4094604", "0.4094378", "0.40940142" ]
0.72693485
1
LockedCoins returns the set of coins that are not spendable (i.e. locked), defined as the vesting coins that are not delegated.
func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins { return va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime())) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime()))\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func (dcr *ExchangeWallet) lockedOutputs() ([]chainjson.TransactionInput, error) {\n\tvar locked []chainjson.TransactionInput\n\terr := dcr.nodeRawRequest(methodListLockUnspent, anylist{dcr.acct}, &locked)\n\treturn locked, err\n}", "func (w *rpcWallet) LockedOutputs(ctx context.Context, acctName string) ([]chainjson.TransactionInput, error) {\n\tvar locked []chainjson.TransactionInput\n\terr := w.rpcClientRawRequest(ctx, methodListLockUnspent, anylist{acctName}, &locked)\n\treturn locked, translateRPCCancelErr(err)\n}", "func (w *Wallet) LockedOutpoints() []btcjson.TransactionInput {\n\tlocked := make([]btcjson.TransactionInput, len(w.lockedOutpoints))\n\ti := 0\n\tfor op := range w.lockedOutpoints {\n\t\tlocked[i] = btcjson.TransactionInput{\n\t\t\tTxid: op.Hash.String(),\n\t\t\tVout: op.Index,\n\t\t}\n\t\ti++\n\t}\n\treturn locked\n}", "func (a *Account) LockedOutpoints() []btcjson.TransactionInput {\n\tlocked := make([]btcjson.TransactionInput, len(a.lockedOutpoints))\n\ti := 0\n\tfor op := range a.lockedOutpoints {\n\t\tlocked[i] = btcjson.TransactionInput{\n\t\t\tTxid: op.Hash.String(),\n\t\t\tVout: op.Index,\n\t\t}\n\t\ti++\n\t}\n\treturn locked\n}", "func (b *Bitcoind) ListLockUnspent() (unspendableOutputs []UnspendableOutput, err error) {\n\tr, err := b.client.call(\"listlockunspent\", nil)\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &unspendableOutputs)\n\treturn\n}", "func (btc *ExchangeWallet) lockedSats() (uint64, error) {\n\tlockedOutpoints, err := btc.wallet.ListLockUnspent()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar sum uint64\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, outPoint := range lockedOutpoints {\n\t\topID := outpointID(outPoint.TxID, outPoint.Vout)\n\t\tutxo, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tsum += utxo.amount\n\t\t\tcontinue\n\t\t}\n\t\ttxHash, err := chainhash.NewHashFromStr(outPoint.TxID)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttxOut, err := btc.node.GetTxOut(txHash, outPoint.Vout, true)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif txOut == nil {\n\t\t\t// Must be spent now?\n\t\t\tbtc.log.Debugf(\"ignoring output from listlockunspent that wasn't found with gettxout. %s\", opID)\n\t\t\tcontinue\n\t\t}\n\t\tsum += toSatoshi(txOut.Value)\n\t}\n\treturn sum, nil\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tlockedOutputs, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, output := range lockedOutputs {\n\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, output.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, output.Vout, true)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), translateRPCCancelErr(err))\n\t\t}\n\t\tvar address string\n\t\tif len(txOut.ScriptPubKey.Addresses) > 0 {\n\t\t\taddress = txOut.ScriptPubKey.Addresses[0]\n\t\t}\n\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\treturn coins, nil\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, txout := range unspents {\n\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: txout.Address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr = dcr.node.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\n\treturn coins, nil\n}", "func (bc *BlockChain) FindUnspentTransactions(addr string) []Transaction {\n\tvar unspentTXs []Transaction\n\tspentTXOutputs := make(map[string][]int)\n\titerator := bc.Iterator()\n\n\tfor {\n\t\t_block := iterator.Next()\n\n\t\tfor _, tx := range _block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.VOut {\n\t\t\t\tif spentTXOutputs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTXOutputs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlockedWith(addr) {\n\t\t\t\t\tunspentTXs = append(unspentTXs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !tx.isCoinBaseTx() {\n\t\t\t\tfor _, in := range tx.VIn {\n\t\t\t\t\tif in.CanUnlockOutputWith(addr) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.TxID)\n\t\t\t\t\t\tspentTXOutputs[inTxID] = append(spentTXOutputs[inTxID], in.VOut)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(_block.Prev) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTXs\n}", "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tlockedOutputs, err := dcr.wallet.LockedOutputs(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, output := range lockedOutputs {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, output.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, txHash, output.Vout, output.Tree)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), err)\n\t\t\t}\n\t\t\tvar address string\n\t\t\tif len(txOut.Addresses) > 0 {\n\t\t\t\taddress = txOut.Addresses[0]\n\t\t\t}\n\t\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\treturn coins, nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunspents, err := dcr.wallet.Unspents(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, txout := range unspents {\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t\t}\n\t\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\t\tif !notFound[pt] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\t\tcoins = append(coins, coin)\n\t\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\t\top: coin,\n\t\t\t\taddr: txout.Address,\n\t\t\t}\n\t\t\tdelete(notFound, pt)\n\t\t\tif len(notFound) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return an error if some coins are still not found.\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn coins, nil\n}", "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (chain *BlockChain) FindUnspentTransactions(address string) []Transaction {\n\tvar unspentTxs []Transaction\n\n\tspentTxOs := make(map[string][]int)\n\n\titer := chain.Iterator()\n\n\tfor {\n\t\tblock := iter.Next()\n\n\t\tfor _, tx := range block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.Outputs {\n\t\t\t\tif spentTxOs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTxOs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlocked(address) {\n\t\t\t\t\tunspentTxs = append(unspentTxs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif tx.IsCoinbase() == false {\n\t\t\t\tfor _, in := range tx.Inputs {\n\t\t\t\t\tif in.CanUnlock(address) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.ID)\n\n\t\t\t\t\t\tspentTxOs[inTxID] = append(spentTxOs[inTxID], in.Out)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(block.PrevHash) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTxs\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (dcr *ExchangeWallet) lockFundingCoins(fCoins []*fundingCoin) error {\n\twireOPs := make([]*wire.OutPoint, 0, len(fCoins))\n\tfor _, c := range fCoins {\n\t\twireOPs = append(wireOPs, wire.NewOutPoint(c.op.txHash(), c.op.vout(), c.op.tree))\n\t}\n\terr := dcr.wallet.LockUnspent(dcr.ctx, false, wireOPs)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, c := range fCoins {\n\t\tdcr.fundingCoins[c.op.pt] = c\n\t}\n\treturn nil\n}", "func (b *Bitcoind) LockUnspent(lock bool, outputs []UnspendableOutput) (success bool, err error) {\n\tr, err := b.client.call(\"lockunspent\", []interface{}{lock, outputs})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &success)\n\treturn\n}", "func (va ClawbackVestingAccount) GetUnlockedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.LockupPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (dcr *ExchangeWallet) returnCoins(unspents asset.Coins) ([]*fundingCoin, error) {\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"cannot return zero coins\")\n\t}\n\n\tops := make([]*wire.OutPoint, 0, len(unspents))\n\tfundingCoins := make([]*fundingCoin, 0, len(unspents))\n\n\tdcr.log.Debugf(\"returning coins %s\", unspents)\n\tfor _, unspent := range unspents {\n\t\top, err := dcr.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error converting coin: %w\", err)\n\t\t}\n\t\tops = append(ops, op.wireOutPoint()) // op.tree may be wire.TxTreeUnknown, but that's fine since wallet.LockUnspent doesn't rely on it\n\t\tif fCoin, ok := dcr.fundingCoins[op.pt]; ok {\n\t\t\tfundingCoins = append(fundingCoins, fCoin)\n\t\t\tdelete(dcr.fundingCoins, op.pt)\n\t\t} else {\n\t\t\tdcr.log.Warnf(\"returning coin %s that is not cached as a funding coin\", op)\n\t\t\tfundingCoins = append(fundingCoins, &fundingCoin{op: op})\n\t\t}\n\t}\n\n\treturn fundingCoins, dcr.wallet.LockUnspent(dcr.ctx, true, ops)\n}", "func (w *Wallet) Locked() bool {\n\treturn <-w.lockState\n}", "func (dcr *ExchangeWallet) lockFundingCoins(fCoins []*fundingCoin) error {\n\twireOPs := make([]*wire.OutPoint, 0, len(fCoins))\n\tfor _, c := range fCoins {\n\t\twireOPs = append(wireOPs, wire.NewOutPoint(c.op.txHash(), c.op.vout(), c.op.tree))\n\t}\n\terr := dcr.node.LockUnspent(dcr.ctx, false, wireOPs)\n\tif err != nil {\n\t\treturn translateRPCCancelErr(err)\n\t}\n\tfor _, c := range fCoins {\n\t\tdcr.fundingCoins[c.op.pt] = c\n\t}\n\treturn nil\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (dcr *ExchangeWallet) returnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*wire.OutPoint, 0, len(unspents))\n\n\tdcr.log.Debugf(\"returning coins %s\", unspents)\n\tfor _, unspent := range unspents {\n\t\top, err := dcr.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %w\", err)\n\t\t}\n\t\tops = append(ops, wire.NewOutPoint(op.txHash(), op.vout(), op.tree))\n\t\tdelete(dcr.fundingCoins, op.pt)\n\t}\n\treturn translateRPCCancelErr(dcr.node.LockUnspent(dcr.ctx, true, ops))\n}", "func (dcr *ExchangeWallet) Locked() bool {\n\tfor _, acct := range dcr.fundingAccounts() {\n\t\tunlocked, err := dcr.wallet.AccountUnlocked(dcr.ctx, acct)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"error checking account lock status %v\", err)\n\t\t\tunlocked = false // assume wallet is unlocked?\n\t\t}\n\t\tif !unlocked {\n\t\t\treturn true // Locked is true if any of the funding accounts is locked.\n\t\t}\n\t}\n\treturn false\n}", "func (w *Wallet) ListUnspent(minconf, maxconf int32,\n\taddresses map[string]struct{}) ([]*btcjson.ListUnspentResult, er.R) {\n\n\tvar results []*btcjson.ListUnspentResult\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\taddrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)\n\t\ttxmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)\n\n\t\tsyncBlock := w.Manager.SyncedTo()\n\n\t\tfilter := len(addresses) != 0\n\t\tunspent, err := w.TxStore.GetUnspentOutputs(txmgrNs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsort.Sort(sort.Reverse(creditSlice(unspent)))\n\n\t\tdefaultAccountName := \"default\"\n\n\t\tresults = make([]*btcjson.ListUnspentResult, 0, len(unspent))\n\t\tfor i := range unspent {\n\t\t\toutput := unspent[i]\n\n\t\t\t// Outputs with fewer confirmations than the minimum or more\n\t\t\t// confs than the maximum are excluded.\n\t\t\tconfs := confirms(output.Height, syncBlock.Height)\n\t\t\tif confs < minconf || confs > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Only mature coinbase outputs are included.\n\t\t\tif output.FromCoinBase {\n\t\t\t\ttarget := int32(w.ChainParams().CoinbaseMaturity)\n\t\t\t\tif !confirmed(target, output.Height, syncBlock.Height) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Exclude locked outputs from the result set.\n\t\t\tif w.LockedOutpoint(output.OutPoint) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Lookup the associated account for the output. Use the\n\t\t\t// default account name in case there is no associated account\n\t\t\t// for some reason, although this should never happen.\n\t\t\t//\n\t\t\t// This will be unnecessary once transactions and outputs are\n\t\t\t// grouped under the associated account in the db.\n\t\t\tacctName := defaultAccountName\n\t\t\tsc, addrs, _, err := txscript.ExtractPkScriptAddrs(\n\t\t\t\toutput.PkScript, w.chainParams)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tsmgr, acct, err := w.Manager.AddrAccount(addrmgrNs, addrs[0])\n\t\t\t\tif err == nil {\n\t\t\t\t\ts, err := smgr.AccountName(addrmgrNs, acct)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tacctName = s\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\tinclude:\n\t\t\t// At the moment watch-only addresses are not supported, so all\n\t\t\t// recorded outputs that are not multisig are \"spendable\".\n\t\t\t// Multisig outputs are only \"spendable\" if all keys are\n\t\t\t// controlled by this wallet.\n\t\t\t//\n\t\t\t// TODO: Each case will need updates when watch-only addrs\n\t\t\t// is added. For P2PK, P2PKH, and P2SH, the address must be\n\t\t\t// looked up and not be watching-only. For multisig, all\n\t\t\t// pubkeys must belong to the manager with the associated\n\t\t\t// private key (currently it only checks whether the pubkey\n\t\t\t// exists, since the private key is required at the moment).\n\t\t\tvar spendable bool\n\t\tscSwitch:\n\t\t\tswitch sc {\n\t\t\tcase txscript.PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.PubKeyTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0ScriptHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.MultiSigTy:\n\t\t\t\tfor _, a := range addrs {\n\t\t\t\t\t_, err := w.Manager.Address(addrmgrNs, a)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif waddrmgr.ErrAddressNotFound.Is(err) {\n\t\t\t\t\t\tbreak scSwitch\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tspendable = true\n\t\t\t}\n\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxID: output.OutPoint.Hash.String(),\n\t\t\t\tVout: output.OutPoint.Index,\n\t\t\t\tAccount: acctName,\n\t\t\t\tScriptPubKey: hex.EncodeToString(output.PkScript),\n\t\t\t\tAmount: output.Amount.ToBTC(),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t\tSpendable: spendable,\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t\treturn nil\n\t})\n\treturn results, err\n}", "func (wt *Wallet) Locked() bool {\n\treturn <-wt.lockState\n}", "func NewQueryLockedCoinsParams(accountID types.AccountID) QueryLockedCoinsParams {\n\treturn QueryLockedCoinsParams{\n\t\tAccountID: accountID,\n\t}\n}", "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func GetLockedDistributionAddresses() []string {\n\t// TODO -- once we reach 30% distribution, we can hardcode the\n\t// initial timestamp for releasing more coins\n\taddrs := make([]string, DistributionAddressesTotal-InitialUnlockedCount)\n\tfor i := range distributionAddresses[InitialUnlockedCount:] {\n\t\taddrs[i] = distributionAddresses[InitialUnlockedCount+uint64(i)]\n\t}\n\n\treturn addrs\n}", "func (btc *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tif len(unspents) == 0 {\n\t\treturn fmt.Errorf(\"cannot return zero coins\")\n\t}\n\tops := make([]*output, 0, len(unspents))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, unspent := range unspents {\n\t\top, err := btc.convertCoin(unspent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error converting coin: %v\", err)\n\t\t}\n\t\tops = append(ops, op)\n\t\tdelete(btc.fundingCoins, outpointID(op.txHash.String(), op.vout))\n\t}\n\treturn btc.wallet.LockUnspent(true, ops)\n}", "func (r *Ring) InPot() []Box {\n\treturn r.Where(func(s *Seat) bool {\n\t\treturn s.State == seat.Play || s.State == seat.Bet || s.State == seat.AllIn\n\t})\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock()\n\treturn dcr.returnCoins(unspents)\n}", "func (keeper SendKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (txn TxnProbe) CollectLockedKeys() [][]byte {\n\treturn txn.collectLockedKeys()\n}", "func (keeper ViewKeeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func GetUnspentOutputCoinsExceptSpendingUTXO(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.InputCoin, error) {\n\tpublicKey := keyWallet.KeySet.PaymentAddress.Pk\n\n\t// check and remove utxo cache (these utxos in txs that were confirmed)\n\t//CheckAndRemoveUTXOFromCache(keyWallet.KeySet.PaymentAddress.Pk, inputCoins)\n\tCheckAndRemoveUTXOFromCacheV2(keyWallet.KeySet.PaymentAddress.Pk, rpcClient)\n\n\t// get unspent output coins from network\n\tutxos, err := GetUnspentOutputCoins(rpcClient, keyWallet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinputCoins := ConvertOutputCoinToInputCoin(utxos)\n\n\t// except spending utxos from unspent output coins\n\tutxosInCache := GetUTXOCacheByPublicKey(publicKey)\n\tfor serialNumberStr, _ := range utxosInCache {\n\t\tfor i, inputCoin := range inputCoins {\n\t\t\tsnStrTmp := base58.Base58Check{}.Encode(inputCoin.CoinDetails.GetSerialNumber().ToBytesS(), common.ZeroByte)\n\t\t\tif snStrTmp == serialNumberStr {\n\t\t\t\tinputCoins = removeElementFromSlice(inputCoins, i)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn inputCoins, nil\n}", "func (btc *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[string]struct{})\n\tbtc.fundingMtx.RLock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\tbtc.fundingMtx.RUnlock()\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tfundingCoin, found := btc.fundingCoins[opID]\n\t\tif found {\n\t\t\tcoins = append(coins, newOutput(btc.node, txHash, vout, fundingCoin.amount, fundingCoin.redeemScript))\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[opID] = struct{}{}\n\t}\n\tbtc.fundingMtx.RUnlock()\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\t_, utxoMap, _, err := btc.spendableUTXOs(0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlockers := make([]*output, 0, len(ids))\n\tbtc.fundingMtx.Lock()\n\tdefer btc.fundingMtx.Unlock()\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topID := outpointID(txHash.String(), vout)\n\t\tutxo, found := utxoMap[opID]\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"funding coin %s not found\", opID)\n\t\t}\n\t\tbtc.fundingCoins[opID] = utxo\n\t\tcoin := newOutput(btc.node, utxo.txHash, utxo.vout, utxo.amount, utxo.redeemScript)\n\t\tcoins = append(coins, coin)\n\t\tlockers = append(lockers, coin)\n\t\tdelete(notFound, opID)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor opID := range notFound {\n\t\t\tids = append(ids, opID)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\terr = btc.wallet.LockUnspent(false, lockers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn coins, nil\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (o *AccountCollectionGetParams) SetLocked(locked *bool) {\n\to.Locked = locked\n}", "func (c *CoordinatorHelper) Coins(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) ([]*types.Coin, error) {\n\tcoins, _, err := c.coinStorage.GetCoinsTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: unable to get coins\", err)\n\t}\n\n\tcoinsToReturn := []*types.Coin{}\n\tfor _, coin := range coins {\n\t\tif types.Hash(coin.Amount.Currency) != types.Hash(currency) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcoinsToReturn = append(coinsToReturn, coin)\n\t}\n\n\treturn coinsToReturn, nil\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\treturnedCoins, err := dcr.returnCoins(unspents)\n\tdcr.fundingMtx.Unlock()\n\tif err != nil || dcr.unmixedAccount == \"\" {\n\t\treturn err\n\t}\n\n\t// If any of these coins belong to the trading account, transfer them to the\n\t// unmixed account to be re-mixed into the primary account before being\n\t// re-selected for funding future orders. This doesn't apply to unspent\n\t// split tx outputs, which should remain in the trading account and be\n\t// selected from there for funding future orders.\n\tvar coinsToTransfer []asset.Coin\n\tfor _, coin := range returnedCoins {\n\t\tif coin.addr == \"\" {\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, coin.op.txHash(), coin.op.vout(), coin.op.tree)\n\t\t\tif err != nil {\n\t\t\t\tdcr.log.Errorf(\"wallet.UnspentOutput error for returned coin %s: %v\", coin.op, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(txOut.Addresses) == 0 {\n\t\t\t\tdcr.log.Errorf(\"no address in gettxout response for returned coin %s\", coin.op)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoin.addr = txOut.Addresses[0]\n\t\t}\n\t\taddrInfo, err := dcr.wallet.AddressInfo(dcr.ctx, coin.addr)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"wallet.AddressInfo error for returned coin %s: %v\", coin.op, err)\n\t\t\tcontinue\n\t\t}\n\t\t// Move this coin to the unmixed account if it was sent to the internal\n\t\t// branch of the trading account. This excludes unspent split tx outputs\n\t\t// which are sent to the external branch of the trading account.\n\t\tif addrInfo.Branch == acctInternalBranch && addrInfo.Account == dcr.tradingAccount {\n\t\t\tcoinsToTransfer = append(coinsToTransfer, coin.op)\n\t\t}\n\t}\n\n\tif len(coinsToTransfer) > 0 {\n\t\ttx, totalSent, err := dcr.sendAll(coinsToTransfer, dcr.unmixedAccount)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"unable to transfer unlocked swapped change from temp trading \"+\n\t\t\t\t\"account to unmixed account: %v\", err)\n\t\t} else {\n\t\t\tdcr.log.Infof(\"Transferred %s from temp trading account to unmixed account in tx %s.\",\n\t\t\t\tdcrutil.Amount(totalSent), tx.TxHash())\n\t\t}\n\t}\n\n\treturn nil\n}", "func GetCoins(accCoins []types.Coin) AccountCoins {\n\tcoins := make(AccountCoins, 0)\n\tfor _, coin := range accCoins {\n\t\tcoins = append(coins, AccountCoin{Amount: uint64(coin.Amount), Denom: coin.Denom})\n\t}\n\treturn coins\n}", "func (keeper BaseViewKeeper) GetCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (b *BlockChain) GetUnspentTxns(address string) []Transaction {\n\tvar unspentTxns []Transaction\n\tvar spentTxnMap = make(map[string][]int) // map txnID -> output index\n\n\t// go over blocks one by one\n\titer := b.GetIterator()\n\tfor {\n\t\tblck := iter.Next()\n\n\t\t// go over all Transactions in this block\n\t\tfor _, txn := range blck.Transactions {\n\t\t\t// get string identifying this transaction\n\t\t\ttxID := hex.EncodeToString(txn.ID)\n\n\t\tOutputLoop:\n\t\t\t// go over all outputs in this Txn\n\t\t\tfor outIndex, output := range txn.Out {\n\n\t\t\t\t// check if this output is spent.\n\t\t\t\tif spentTxnMap[txID] != nil {\n\t\t\t\t\tfor _, indx := range spentTxnMap[txID] {\n\t\t\t\t\t\tif indx == outIndex {\n\t\t\t\t\t\t\tcontinue OutputLoop\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// check if this output belongs to this address\n\t\t\t\tif output.CheckOutputUnlock(address) {\n\t\t\t\t\tunspentTxns = append(unspentTxns, *txn)\n\t\t\t\t}\n\n\t\t\t\t// if this is not genesis block, go over all inputs\n\t\t\t\t// that refers to output that belongs to this address\n\t\t\t\t// and mark them as unspent\n\t\t\t\tif txn.IsCoinbase() == false {\n\t\t\t\t\tfor _, inp := range txn.In {\n\t\t\t\t\t\tif inp.CheckInputUnlock(address) {\n\t\t\t\t\t\t\tspentTxnMap[txID] = append(spentTxnMap[txID], inp.Out)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(blck.PrevBlockHash) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn unspentTxns\n}", "func (keeper Keeper) GetCoins(ctx sdk.Context, addr sdk.Address) sdk.Coins {\n\treturn getCoins(ctx, keeper.am, addr)\n}", "func (dcr *ExchangeWallet) Locked() bool {\n\twalletInfo, err := dcr.node.WalletInfo(dcr.ctx)\n\tif err != nil {\n\t\tdcr.log.Errorf(\"walletinfo error: %v\", err)\n\t\treturn false\n\t}\n\treturn !walletInfo.Unlocked\n}", "func GetUnspentOutputCoins(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.OutputCoin, error) {\n\tprivateKey := &keyWallet.KeySet.PrivateKey\n\tpaymentAddressStr := keyWallet.Base58CheckSerialize(wallet.PaymentAddressType)\n\tviewingKeyStr := keyWallet.Base58CheckSerialize(wallet.ReadonlyKeyType)\n\n\toutputCoins, err := GetListOutputCoins(rpcClient, paymentAddressStr, viewingKeyStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserialNumbers, err := DeriveSerialNumbers(privateKey, outputCoins)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tisExisted, err := CheckExistenceSerialNumber(rpcClient, paymentAddressStr, serialNumbers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tutxos := make([]*crypto.OutputCoin, 0)\n\tfor i, out := range outputCoins {\n\t\tif !isExisted[i] {\n\t\t\tutxos = append(utxos, out)\n\t\t}\n\t}\n\n\treturn utxos, nil\n}", "func (dcr *ExchangeWallet) lockedAtoms() (uint64, error) {\n\tlockedOutpoints, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar sum uint64\n\tfor _, op := range lockedOutpoints {\n\t\tsum += toAtoms(op.Amount)\n\t}\n\treturn sum, nil\n}", "func (u UTXOSet) FindUnspentTransactions(pubKeyHash []byte) []TxOutput {\n\tvar UTXOs []TxOutput\n\n\tdb := u.Blockchain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through UTXOS prefixes\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\t// get the value of each utxo prefixed item\n\t\t\tv := valueHash(it.Item())\n\t\t\touts := DeserializeOutputs(v)\n\n\t\t\t// iterate through each output, check to see if it is locked by the provided hash address\n\t\t\tfor _, out := range outs.Outputs {\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\thandle(err)\n\n\treturn UTXOs\n}", "func distributeLockedAmount(ctx coretypes.Sandbox, bets []*BetInfo, totalLockedAmount int64) bool {\n\tsumsByPlayers := make(map[coretypes.AgentID]int64)\n\ttotalWinningAmount := int64(0)\n\tfor _, bet := range bets {\n\t\tif _, ok := sumsByPlayers[bet.Player]; !ok {\n\t\t\tsumsByPlayers[bet.Player] = 0\n\t\t}\n\t\tsumsByPlayers[bet.Player] += bet.Sum\n\t\ttotalWinningAmount += bet.Sum\n\t}\n\n\t// NOTE 1: float64 was avoided for determinism reasons\n\t// NOTE 2: beware overflows\n\n\tfor player, sum := range sumsByPlayers {\n\t\tsumsByPlayers[player] = (totalLockedAmount * sum) / totalWinningAmount\n\t}\n\n\t// make deterministic sequence by sorting. Eliminate possible rounding effects\n\tseqPlayers := make([]coretypes.AgentID, 0, len(sumsByPlayers))\n\tresultSum := int64(0)\n\tfor player, sum := range sumsByPlayers {\n\t\tseqPlayers = append(seqPlayers, player)\n\t\tresultSum += sum\n\t}\n\tsort.Slice(seqPlayers, func(i, j int) bool {\n\t\treturn bytes.Compare(seqPlayers[i][:], seqPlayers[j][:]) < 0\n\t})\n\n\t// ensure we distribute not more than totalLockedAmount iotas\n\tif resultSum > totalLockedAmount {\n\t\tsumsByPlayers[seqPlayers[0]] -= resultSum - totalLockedAmount\n\t}\n\n\t// filter out those who proportionally got 0\n\tfinalWinners := seqPlayers[:0]\n\tfor _, player := range seqPlayers {\n\t\tif sumsByPlayers[player] <= 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfinalWinners = append(finalWinners, player)\n\t}\n\t// distribute iotas\n\tfor i := range finalWinners {\n\n\t\tavailable := ctx.Balance(balance.ColorIOTA)\n\t\tctx.Event(fmt.Sprintf(\"sending reward iotas %d to the winner %s. Available iotas: %d\",\n\t\t\tsumsByPlayers[finalWinners[i]], finalWinners[i].String(), available))\n\n\t\t//if !ctx.MoveTokens(finalWinners[i], balance.ColorIOTA, sumsByPlayers[finalWinners[i]]) {\n\t\t//\treturn false\n\t\t//}\n\t}\n\treturn true\n}", "func (w *rpcWallet) LockUnspent(ctx context.Context, unlock bool, ops []*wire.OutPoint) error {\n\treturn translateRPCCancelErr(w.client().LockUnspent(ctx, unlock, ops))\n}", "func (ck CoinKeeper) GetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Coins {\n\tacc := ck.am.GetAccount(ctx, addr)\n\treturn acc.GetCoins()\n}", "func GetUnlockedDistributionAddresses() []string {\n\t// The first InitialUnlockedCount (25) addresses are unlocked by default.\n\t// Subsequent addresses will be unlocked at a rate of UnlockAddressRate (5) per year,\n\t// after the InitialUnlockedCount (25) addresses have no remaining balance.\n\t// The unlock timer will be enabled manually once the\n\t// InitialUnlockedCount (25) addresses are distributed.\n\n\t// NOTE: To have automatic unlocking, transaction verification would have\n\t// to be handled in visor rather than in coin.Transactions.Visor(), because\n\t// the coin package is agnostic to the state of the blockchain and cannot reference it.\n\t// Instead of automatic unlocking, we can hardcode the timestamp at which the first 30%\n\t// is distributed, then compute the unlocked addresses easily here.\n\n\taddrs := make([]string, InitialUnlockedCount)\n\tfor i := range distributionAddresses[:InitialUnlockedCount] {\n\t\taddrs[i] = distributionAddresses[i]\n\t}\n\treturn addrs\n}", "func WithoutBlocking(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, nonBlockingTxnCtxKey, &nonBlockingTxnOpt{})\n}", "func (b *Bitcoind) ListUnspent(minconf, maxconf uint32) (transactions []Transaction, err error) {\n\tif maxconf > 999999 {\n\t\tmaxconf = 999999\n\t}\n\n\tr, err := b.client.call(\"listunspent\", []interface{}{minconf, maxconf})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &transactions)\n\treturn\n}", "func (am *AccountManager) ListUnspent(minconf, maxconf int,\n\taddresses map[string]bool) ([]*btcjson.ListUnspentResult, error) {\n\n\tbs, err := GetCurBlock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilter := len(addresses) != 0\n\n\tvar results []*btcjson.ListUnspentResult\n\tfor _, a := range am.AllAccounts() {\n\t\tunspent, err := a.TxStore.UnspentOutputs()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, credit := range unspent {\n\t\t\tconfs := credit.Confirmations(bs.Height)\n\t\t\tif int(confs) < minconf || int(confs) > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, addrs, _, _ := credit.Addresses(cfg.Net())\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\tinclude:\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxId: credit.Tx().Sha().String(),\n\t\t\t\tVout: credit.OutputIndex,\n\t\t\t\tAccount: a.Name(),\n\t\t\t\tScriptPubKey: hex.EncodeToString(credit.TxOut().PkScript),\n\t\t\t\tAmount: credit.Amount().ToUnit(btcutil.AmountBTC),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t}\n\n\treturn results, nil\n}", "func (w *Wallet) ResetLockedOutpoints() {\n\tw.lockedOutpoints = map[wire.OutPoint]struct{}{}\n}", "func (c *Channel) Locked() *big.Int {\n\treturn c.OurState.AmountLocked()\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (c *Channel) Locked() *big.Int {\n\treturn c.OurState.amountLocked()\n}", "func (s *Store) ListLockedOutputs(ns walletdb.ReadBucket) ([]*LockedOutput,\n\terror) {\n\n\tvar outputs []*LockedOutput\n\terr := forEachLockedOutput(\n\t\tns, func(op wire.OutPoint, id LockID, expiration time.Time) {\n\t\t\t// Skip expired leases. They will be cleaned up with the\n\t\t\t// next call to DeleteExpiredLockedOutputs.\n\t\t\tif !s.clock.Now().Before(expiration) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\toutputs = append(outputs, &LockedOutput{\n\t\t\t\tOutpoint: op,\n\t\t\t\tLockID: id,\n\t\t\t\tExpiration: expiration,\n\t\t\t})\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn outputs, nil\n}", "func coinSupplyHandler(gateway Gatewayer) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodGet {\n\t\t\twh.Error405(w)\n\t\t\treturn\n\t\t}\n\n\t\tallUnspents, err := gateway.GetUnspentOutputsSummary(nil)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"gateway.GetUnspentOutputsSummary failed: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tunlockedAddrs := params.GetUnlockedDistributionAddressesDecoded()\n\t\t// Search map of unlocked addresses, used to filter unspents\n\t\tunlockedAddrSet := newAddrSet(unlockedAddrs)\n\n\t\tvar unlockedSupply uint64\n\t\t// check confirmed unspents only\n\t\tfor _, u := range allUnspents.Confirmed {\n\t\t\t// check if address is an unlocked distribution address\n\t\t\tif _, ok := unlockedAddrSet[u.Body.Address]; ok {\n\t\t\t\tvar err error\n\t\t\t\tunlockedSupply, err = mathutil.AddUint64(unlockedSupply, u.Body.Coins)\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"uint64 overflow while adding up unlocked supply coins: %v\", err)\n\t\t\t\t\twh.Error500(w, err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// \"total supply\" is the number of coins unlocked.\n\t\t// Each distribution address was allocated params.DistributionAddressInitialBalance coins.\n\t\ttotalSupply := uint64(len(unlockedAddrs)) * params.DistributionAddressInitialBalance\n\t\ttotalSupply *= droplet.Multiplier\n\n\t\t// \"current supply\" is the number of coins distributed from the unlocked pool\n\t\tcurrentSupply := totalSupply - unlockedSupply\n\n\t\tcurrentSupplyStr, err := droplet.ToString(currentSupply)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\ttotalSupplyStr, err := droplet.ToString(totalSupply)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tmaxSupplyStr, err := droplet.ToString(params.MaxCoinSupply * droplet.Multiplier)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t// locked distribution addresses\n\t\tlockedAddrs := params.GetLockedDistributionAddressesDecoded()\n\t\tlockedAddrSet := newAddrSet(lockedAddrs)\n\n\t\t// get total coins hours which excludes locked distribution addresses\n\t\tvar totalCoinHours uint64\n\t\tfor _, out := range allUnspents.Confirmed {\n\t\t\tif _, ok := lockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\tvar err error\n\t\t\t\ttotalCoinHours, err = mathutil.AddUint64(totalCoinHours, out.CalculatedHours)\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"uint64 overflow while adding up total coin hours: %v\", err)\n\t\t\t\t\twh.Error500(w, err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// get current coin hours which excludes all distribution addresses\n\t\tvar currentCoinHours uint64\n\t\tfor _, out := range allUnspents.Confirmed {\n\t\t\t// check if address not in locked distribution addresses\n\t\t\tif _, ok := lockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\t// check if address not in unlocked distribution addresses\n\t\t\t\tif _, ok := unlockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\t\tcurrentCoinHours += out.CalculatedHours\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to get total coinhours: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tcs := CoinSupply{\n\t\t\tCurrentSupply: currentSupplyStr,\n\t\t\tTotalSupply: totalSupplyStr,\n\t\t\tMaxSupply: maxSupplyStr,\n\t\t\tCurrentCoinHourSupply: strconv.FormatUint(currentCoinHours, 10),\n\t\t\tTotalCoinHourSupply: strconv.FormatUint(totalCoinHours, 10),\n\t\t\tUnlockedAddresses: params.GetUnlockedDistributionAddresses(),\n\t\t\tLockedAddresses: params.GetLockedDistributionAddresses(),\n\t\t}\n\n\t\twh.SendJSONOr500(logger, w, cs)\n\t}\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in %q account\", dcr.acct)\n\t}\n\n\t// Parse utxos to include script size for spending input.\n\t// Returned utxos will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func (s *Store) UnspentOutputs(ns walletdb.ReadBucket) ([]Credit, error) {\n\tvar unspent []Credit\n\n\tvar op wire.OutPoint\n\tvar block Block\n\terr := ns.NestedReadBucket(bucketUnspent).ForEach(func(k, v []byte) error {\n\t\terr := readCanonicalOutPoint(k, &op)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip this k/v pair.\n\t\t\treturn nil\n\t\t}\n\n\t\terr = readUnspentBlock(v, &block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tblockTime, err := fetchBlockTime(ns, block.Height)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// TODO(jrick): reading the entire transaction should\n\t\t// be avoidable. Creating the credit only requires the\n\t\t// output amount and pkScript.\n\t\trec, err := fetchTxRecord(ns, &op.Hash, &block)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to retrieve transaction %v: \"+\n\t\t\t\t\"%v\", op.Hash, err)\n\t\t}\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: block,\n\t\t\t\tTime: blockTime,\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\tunspent = append(unspent, cred)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\tstr := \"failed iterating unspent bucket\"\n\t\treturn nil, storeError(ErrDatabase, str, err)\n\t}\n\n\terr = ns.NestedReadBucket(bucketUnminedCredits).ForEach(func(k, v []byte) error {\n\t\tif err := readCanonicalOutPoint(k, &op); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip to next unmined credit.\n\t\t\treturn nil\n\t\t}\n\n\t\t// TODO(jrick): Reading/parsing the entire transaction record\n\t\t// just for the output amount and script can be avoided.\n\t\trecVal := existsRawUnmined(ns, op.Hash[:])\n\t\tvar rec TxRecord\n\t\terr = readRawTxRecord(&op.Hash, recVal, &rec)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to retrieve raw transaction \"+\n\t\t\t\t\"%v: %v\", op.Hash, err)\n\t\t}\n\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: Block{Height: -1},\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\tunspent = append(unspent, cred)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\tstr := \"failed iterating unmined credits bucket\"\n\t\treturn nil, storeError(ErrDatabase, str, err)\n\t}\n\n\treturn unspent, nil\n}", "func (tx *Transaction) GetNewFromCoins() []FromCoin {\n\tnfcs := make([]FromCoin, 0)\n\tfor index, c := range tx.To.Coins {\n\t\tticket := Ticket{}\n\t\tticket.SetTxid(*tx.GetTxID())\n\t\tticket.SetIndex(uint32(index))\n\n\t\tnfc := FromCoin{}\n\t\tnfc.SetId(c.Id)\n\t\tnfc.AddTicket(&ticket)\n\n\t\tnfcs = append(nfcs, nfc)\n\t}\n\n\treturn nfcs\n}", "func (b *BlockChain) GetUnspentOutputs(address string) []TxOutput {\n\tvar unspentOuts []TxOutput\n\ttxns := b.GetUnspentTxns(address)\n\n\t// go over each txn and each output in it and collect ones which belongs to this address\n\tfor _, txn := range txns {\n\t\t// iterate over all outputs\n\t\tfor _, output := range txn.Out {\n\t\t\tif output.CheckOutputUnlock(address) {\n\t\t\t\tunspentOuts = append(unspentOuts, output)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn unspentOuts\n}", "func (serv *ExchangeServer) GetSupportCoins() []string {\n\tsymbols := make([]string, len(serv.coins))\n\ti := 0\n\tfor _, coin := range serv.coins {\n\t\tsymbols[i] = coin.Symbol()\n\t\ti++\n\t}\n\treturn symbols\n}", "func (o RunnerOutput) Locked() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v *Runner) pulumi.BoolOutput { return v.Locked }).(pulumi.BoolOutput)\n}", "func (cb CommitteeBits) FilterNonParticipants(committee []ValidatorIndex) []ValidatorIndex {\n\tbitLen := cb.BitLen()\n\tout := committee[:0]\n\tif bitLen != uint64(len(committee)) {\n\t\tpanic(\"committee mismatch, bitfield length does not match\")\n\t}\n\tfor i := uint64(0); i < bitLen; i++ {\n\t\tif !cb.GetBit(i) {\n\t\t\tout = append(out, committee[i])\n\t\t}\n\t}\n\treturn out\n}", "func (cm *coinsMempool) Get(maxTransactions uint64, s state.State) ([]*primitives.Tx, state.State) {\n\tcm.lock.RLock()\n\tdefer cm.lock.RUnlock()\n\tallTransactions := make([]*primitives.Tx, 0, maxTransactions)\n\nouter:\n\tfor _, addr := range cm.mempool {\n\t\tfor _, tx := range addr.transactions {\n\t\t\tif err := s.ApplyTransactionSingle(tx, [20]byte{}, cm.params); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tallTransactions = append(allTransactions, tx)\n\t\t\tif uint64(len(allTransactions)) >= maxTransactions {\n\t\t\t\tbreak outer\n\t\t\t}\n\t\t}\n\t}\n\n\t// we can prioritize here, but we aren't to keep it simple\n\treturn allTransactions, s\n}", "func (k Keeper) MintCoins(ctx sdk.Context, newCoins sdk.Coins) error {\n\tif newCoins.Empty() {\n\t\t// skip as no coins need to be minted\n\t\treturn nil\n\t}\n\treturn k.supplyKeeper.MintCoins(ctx, types.ModuleName, newCoins)\n}", "func (u UTXOSet) FindUnspentTransactionOutputs(pubKeyHash []byte) []TxOutput {\n\tvar UTXOs []TxOutput\n\n\tdb := u.BlockChain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through all transactions with UTXOs\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\titem := it.Item()\n\t\t\tv, err := item.Value()\n\t\t\tHandle(err)\n\t\t\touts := DeserializeOutputs(v)\n\t\t\t// go through all outputs of that transaction\n\t\t\tfor _, out := range outs.Outputs {\n\t\t\t\t// check the output was locked with this address (belongs to this receiver and can be unlocked by this address to use as new input)\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tHandle(err)\n\treturn UTXOs\n}", "func (_TokensNetwork *TokensNetworkCaller) QueryUnlockedLocks(opts *bind.CallOpts, token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _TokensNetwork.contract.Call(opts, out, \"queryUnlockedLocks\", token, participant, partner, lockhash)\n\treturn *ret0, err\n}", "func (rt *recvTxOut) SetLocked(locked bool) {\n\trt.locked = locked\n}", "func (rt *recvTxOut) Locked() bool {\n\treturn rt.locked\n}", "func (_TokensNetwork *TokensNetworkCallerSession) QueryUnlockedLocks(token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\treturn _TokensNetwork.Contract.QueryUnlockedLocks(&_TokensNetwork.CallOpts, token, participant, partner, lockhash)\n}", "func (tp *TXPool) GetUnverifiedTxs(txs []*types.Transaction,\n\theight uint32) *CheckBlkResult {\n\ttp.Lock()\n\tdefer tp.Unlock()\n\tres := &CheckBlkResult{\n\t\tVerifiedTxs: make([]*VerifyTxResult, 0, len(txs)),\n\t\tUnverifiedTxs: make([]*types.Transaction, 0),\n\t\tOldTxs: make([]*types.Transaction, 0),\n\t}\n\tfor _, tx := range txs {\n\t\ttxEntry := tp.txList[tx.Hash()]\n\t\tif txEntry == nil {\n\t\t\tres.UnverifiedTxs = append(res.UnverifiedTxs,\n\t\t\t\ttx)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !tp.compareTxHeight(txEntry, height) {\n\t\t\tdelete(tp.txList, tx.Hash())\n\t\t\tres.OldTxs = append(res.OldTxs, txEntry.Tx)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, v := range txEntry.Attrs {\n\t\t\tif v.Type == vt.Stateful {\n\t\t\t\tentry := &VerifyTxResult{\n\t\t\t\t\tTx: tx,\n\t\t\t\t\tHeight: v.Height,\n\t\t\t\t\tErrCode: v.ErrCode,\n\t\t\t\t}\n\t\t\t\tres.VerifiedTxs = append(res.VerifiedTxs,\n\t\t\t\t\tentry)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res\n}", "func (_TokensNetwork *TokensNetworkSession) QueryUnlockedLocks(token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\treturn _TokensNetwork.Contract.QueryUnlockedLocks(&_TokensNetwork.CallOpts, token, participant, partner, lockhash)\n}", "func (tb *transactionBuilder) FundCoins(amount types.Currency, refundAddress *types.UnlockHash, reuseRefundAddress bool) error {\n\ttb.wallet.mu.Lock()\n\tdefer tb.wallet.mu.Unlock()\n\n\tif !tb.wallet.unlocked {\n\t\treturn modules.ErrLockedWallet\n\t}\n\n\t// prepare fulfillable context\n\tctx := tb.wallet.getFulfillableContextForLatestBlock()\n\n\t// Collect a value-sorted set of fulfillable coin outputs.\n\tvar so sortedOutputs\n\tfor scoid, sco := range tb.wallet.coinOutputs {\n\t\tif !sco.Condition.Fulfillable(ctx) {\n\t\t\tcontinue\n\t\t}\n\t\tso.ids = append(so.ids, scoid)\n\t\tso.outputs = append(so.outputs, sco)\n\t}\n\t// Add all of the unconfirmed outputs as well.\n\tfor _, upt := range tb.wallet.unconfirmedProcessedTransactions {\n\t\tfor i, sco := range upt.Transaction.CoinOutputs {\n\t\t\tuh := sco.Condition.UnlockHash()\n\t\t\t// Determine if the output belongs to the wallet.\n\t\t\texists, err := tb.wallet.keyExists(uh)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !exists || !sco.Condition.Fulfillable(ctx) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tso.ids = append(so.ids, upt.Transaction.CoinOutputID(uint64(i)))\n\t\t\tso.outputs = append(so.outputs, sco)\n\t\t}\n\t}\n\tsort.Sort(sort.Reverse(so))\n\n\t// Create a transaction that will add the correct amount of coins to the\n\t// transaction.\n\tvar fund types.Currency\n\t// potentialFund tracks the balance of the wallet including outputs that\n\t// have been spent in other unconfirmed transactions recently. This is to\n\t// provide the user with a more useful error message in the event that they\n\t// are overspending.\n\tvar potentialFund types.Currency\n\tvar spentScoids []types.CoinOutputID\n\tfor i := range so.ids {\n\t\tscoid := so.ids[i]\n\t\tsco := so.outputs[i]\n\t\t// Check that this output has not recently been spent by the wallet.\n\t\tspendHeight := tb.wallet.spentOutputs[types.OutputID(scoid)]\n\t\t// Prevent an underflow error.\n\t\tallowedHeight := tb.wallet.consensusSetHeight - RespendTimeout\n\t\tif tb.wallet.consensusSetHeight < RespendTimeout {\n\t\t\tallowedHeight = 0\n\t\t}\n\t\tif spendHeight > allowedHeight {\n\t\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\t\tcontinue\n\t\t}\n\n\t\t// prepare fulfillment, matching the output\n\t\tuh := sco.Condition.UnlockHash()\n\t\tvar ff types.MarshalableUnlockFulfillment\n\t\tswitch sco.Condition.ConditionType() {\n\t\tcase types.ConditionTypeUnlockHash, types.ConditionTypeTimeLock:\n\t\t\t// ConditionTypeTimeLock is fine, as we know it's fulfillable,\n\t\t\t// and that can only mean for now that it is using an internal unlockHashCondition or nilCondition\n\t\t\tpk, _, err := tb.wallet.getKey(uh)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tff = types.NewSingleSignatureFulfillment(pk)\n\t\tdefault:\n\t\t\tbuild.Severe(fmt.Errorf(\"unexpected condition type: %[1]v (%[1]T)\", sco.Condition))\n\t\t\treturn types.ErrUnexpectedUnlockCondition\n\t\t}\n\t\t// Add a coin input for this output.\n\t\tsci := types.CoinInput{\n\t\t\tParentID: scoid,\n\t\t\tFulfillment: types.NewFulfillment(ff),\n\t\t}\n\t\ttb.coinInputs = append(tb.coinInputs, inputSignContext{\n\t\t\tInputIndex: len(tb.transaction.CoinInputs),\n\t\t\tUnlockHash: uh,\n\t\t})\n\t\ttb.transaction.CoinInputs = append(tb.transaction.CoinInputs, sci)\n\n\t\tspentScoids = append(spentScoids, scoid)\n\n\t\t// Add the output to the total fund\n\t\tfund = fund.Add(sco.Value)\n\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\tif fund.Cmp(amount) >= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif potentialFund.Cmp(amount) >= 0 && fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrIncompleteTransactions\n\t}\n\tif fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrLowBalance\n\t}\n\n\t// Create a refund output if needed.\n\tif !amount.Equals(fund) {\n\t\tvar refundUnlockHash types.UnlockHash\n\t\tif refundAddress != nil {\n\t\t\t// use specified refund address\n\t\t\trefundUnlockHash = *refundAddress\n\t\t} else if reuseRefundAddress {\n\t\t\t// use the fist coin input of this tx as refund address\n\t\t\tvar maxCoinAmount types.Currency\n\t\t\tfor _, ci := range tb.transaction.CoinInputs {\n\t\t\t\tco, exists := tb.wallet.coinOutputs[ci.ParentID]\n\t\t\t\tif !exists {\n\t\t\t\t\tco = tb.getCoFromUnconfirmedProcessedTransactions(ci.ParentID)\n\t\t\t\t}\n\t\t\t\tif maxCoinAmount.Cmp(co.Value) < 0 {\n\t\t\t\t\tmaxCoinAmount = co.Value\n\t\t\t\t\trefundUnlockHash = co.Condition.UnlockHash()\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// generate a new address\n\t\t\tvar err error\n\t\t\trefundUnlockHash, err = tb.wallet.nextPrimarySeedAddress()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\trefundOutput := types.CoinOutput{\n\t\t\tValue: fund.Sub(amount),\n\t\t\tCondition: types.NewCondition(types.NewUnlockHashCondition(refundUnlockHash)),\n\t\t}\n\t\ttb.transaction.CoinOutputs = append(tb.transaction.CoinOutputs, refundOutput)\n\t}\n\n\t// Mark all outputs that were spent as spent.\n\tfor _, scoid := range spentScoids {\n\t\ttb.wallet.spentOutputs[types.OutputID(scoid)] = tb.wallet.consensusSetHeight\n\t}\n\treturn nil\n}", "func (o AttachedDiskResponseOutput) Locked() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v AttachedDiskResponse) bool { return v.Locked }).(pulumi.BoolOutput)\n}", "func (b *rpcVestingBalance) unbonding() (sdk.Coins, sdk.Coins, error) {\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\tunbondingFree := sdk.MinInt(delegatedFree, unbonding)\n\tunbondingVesting := unbonding.Sub(unbondingFree)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(unbondingFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(unbondingVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (s *StakingKeeperMock) GetBondedValidatorsByPower(ctx sdk.Context) []stakingtypes.Validator {\n\treturn s.BondedValidators\n}", "func (s *Store) GetUnspentOutputs(ns walletdb.ReadBucket) ([]Credit, er.R) {\n\tvar unspent []Credit\n\terr := s.ForEachUnspentOutput(ns, nil, func(_ []byte, c *Credit) er.R {\n\t\tunspent = append(unspent, *c)\n\t\treturn nil\n\t})\n\treturn unspent, err\n}", "func (w *Wallet) GetUnspentBlockStakeOutputs() (unspent []types.UnspentBlockStakeOutput, err error) {\n\tw.mu.RLock()\n\tdefer w.mu.RUnlock()\n\n\tif !w.unlocked {\n\t\terr = modules.ErrLockedWallet\n\t\treturn\n\t}\n\n\tunspent = make([]types.UnspentBlockStakeOutput, 0)\n\n\t// prepare fulfillable context\n\tctx := w.getFulfillableContextForLatestBlock()\n\n\t// collect all fulfillable block stake outputs\n\tfor usbsoid, output := range w.blockstakeOutputs {\n\t\tif output.Condition.Fulfillable(ctx) {\n\t\t\tunspent = append(unspent, w.unspentblockstakeoutputs[usbsoid])\n\t\t}\n\t}\n\treturn\n}", "func (btc *ExchangeWallet) spendableUTXOs(confs uint32) ([]*compositeUTXO, map[string]*compositeUTXO, uint64, error) {\n\tunspents, err := btc.wallet.ListUnspent()\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\tsort.Slice(unspents, func(i, j int) bool { return unspents[i].Amount < unspents[j].Amount })\n\tvar sum uint64\n\tutxos := make([]*compositeUTXO, 0, len(unspents))\n\tutxoMap := make(map[string]*compositeUTXO, len(unspents))\n\tfor _, txout := range unspents {\n\t\tif txout.Confirmations >= confs && txout.Safe {\n\t\t\tnfo, err := dexbtc.InputInfo(txout.ScriptPubKey, txout.RedeemScript, btc.chainParams)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error reading asset info: %v\", err)\n\t\t\t}\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error decoding txid in ListUnspentResult: %v\", err)\n\t\t\t}\n\t\t\tutxo := &compositeUTXO{\n\t\t\t\ttxHash: txHash,\n\t\t\t\tvout: txout.Vout,\n\t\t\t\taddress: txout.Address,\n\t\t\t\tredeemScript: txout.RedeemScript,\n\t\t\t\tamount: toSatoshi(txout.Amount),\n\t\t\t\tinput: nfo,\n\t\t\t}\n\t\t\tutxos = append(utxos, utxo)\n\t\t\tutxoMap[outpointID(txout.TxID, txout.Vout)] = utxo\n\t\t\tsum += toSatoshi(txout.Amount)\n\t\t}\n\t}\n\treturn utxos, utxoMap, sum, nil\n}", "func newCoins() sdk.Coins {\n\treturn sdk.Coins{\n\t\tsdk.NewInt64Coin(\"atom\", 10000000),\n\t}\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.wallet.Unspents(dcr.ctx, dcr.primaryAcct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif dcr.tradingAccount != \"\" {\n\t\t// Trading account may contain spendable utxos such as unspent split tx\n\t\t// outputs that are unlocked/returned. TODO: Care should probably be\n\t\t// taken to ensure only unspent split tx outputs are selected and other\n\t\t// unmixed outputs in the trading account are ignored.\n\t\ttradingAcctSpendables, err := dcr.wallet.Unspents(dcr.ctx, dcr.tradingAccount)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tunspents = append(unspents, tradingAcctSpendables...)\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in account %q\", dcr.primaryAcct)\n\t}\n\n\t// Parse utxos to include script size for spending input. Returned utxos\n\t// will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func (m *Machine) ReturnCoins() {\n\tcoins := m.cashEngine.DropCoins()\n\n\ts := fmt.Sprintf(\"-> \")\n\tfor i, c := range coins {\n\t\tif i == len(coins)-1 {\n\t\t\ts += fmt.Sprintf(\"%s\", c.value.String())\n\t\t\tcontinue\n\t\t}\n\t\ts += fmt.Sprintf(\"%s, \", c.value.String())\n\t}\n\n\tm.logger.Println(s)\n}", "func (_DelegationController *DelegationControllerCaller) GetLockedInPendingDelegations(opts *bind.CallOpts, holder common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"getLockedInPendingDelegations\", holder)\n\treturn *ret0, err\n}" ]
[ "0.75121504", "0.74375194", "0.74270487", "0.73147166", "0.68385124", "0.6392496", "0.61917114", "0.6113071", "0.58873636", "0.58075583", "0.56814134", "0.56528914", "0.56135285", "0.5559344", "0.5548731", "0.54984355", "0.5480376", "0.54703814", "0.5414903", "0.5400289", "0.53920466", "0.53802407", "0.53664374", "0.53305", "0.52817136", "0.52767944", "0.52671874", "0.52554864", "0.5251496", "0.5227145", "0.52001727", "0.5187744", "0.5175647", "0.51450557", "0.514315", "0.5106849", "0.5097466", "0.50882727", "0.50755197", "0.5049093", "0.50267446", "0.4995233", "0.4961594", "0.49306652", "0.48910666", "0.48800844", "0.4870848", "0.4868697", "0.48480183", "0.4836659", "0.48171586", "0.48117325", "0.480943", "0.4802143", "0.47945446", "0.47932136", "0.47904304", "0.47546884", "0.47405586", "0.47136912", "0.471216", "0.46996582", "0.46983907", "0.46972474", "0.46938106", "0.4689896", "0.46788356", "0.46745017", "0.46591777", "0.4659012", "0.46546215", "0.46400502", "0.4612143", "0.45871246", "0.45714107", "0.45661086", "0.45525652", "0.45499128", "0.4538669", "0.45252737", "0.45235956", "0.45210218", "0.4514166", "0.4504932", "0.4503111", "0.44923684", "0.44883734", "0.44835222", "0.44804823", "0.44681153", "0.44532546", "0.44453686", "0.44362217", "0.4432046", "0.44253957", "0.44246426", "0.4424409", "0.44223616", "0.44217584", "0.441431" ]
0.7414589
3
TrackDelegation tracks a desired delegation amount by setting the appropriate values for the amount of delegated vesting, delegated free, and reducing the overall amount of base coins.
func (va *ClawbackVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) { va.BaseVestingAccount.TrackDelegation(balance, va.GetVestingCoins(blockTime), amount) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (bva *BaseVestingAccount) TrackDelegation(balance, vestingCoins, amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\tbaseAmt := balance.AmountOf(coin.Denom)\n\t\tvestingAmt := vestingCoins.AmountOf(coin.Denom)\n\t\tdelVestingAmt := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// Panic if the delegation amount is zero or if the base coins does not\n\t\t// exceed the desired delegation amount.\n\t\tif coin.Amount.IsZero() || baseAmt.LT(coin.Amount) {\n\t\t\tpanic(\"delegation attempt with zero coins or insufficient funds\")\n\t\t}\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(max(V - DV, 0), D)\n\t\t// Y := D - X\n\t\tx := sdk.MinInt(sdk.MaxInt(vestingAmt.Sub(delVestingAmt), sdk.ZeroInt()), coin.Amount)\n\t\ty := coin.Amount.Sub(x)\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Add(xCoin)\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Add(yCoin)\n\t\t}\n\t}\n}", "func (dva *DelayedVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tdva.BaseVestingAccount.TrackDelegation(balance, dva.GetVestingCoins(blockTime), amount)\n}", "func (pva *PeriodicVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tpva.BaseVestingAccount.TrackDelegation(balance, pva.GetVestingCoins(blockTime), amount)\n}", "func (vva *ValidatorVestingAccount) TrackDelegation(blockTime time.Time, amount sdk.Coins) {\n\tvva.BaseVestingAccount.TrackDelegation(vva.GetVestingCoins(blockTime), amount)\n}", "func (cva *ContinuousVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tcva.BaseVestingAccount.TrackDelegation(balance, cva.GetVestingCoins(blockTime), amount)\n}", "func (plva *PermanentLockedAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tplva.BaseVestingAccount.TrackDelegation(balance, plva.OriginalVesting, amount)\n}", "func (bva *BaseVestingAccount) TrackUndelegation(amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\t// panic if the undelegation amount is zero\n\t\tif coin.Amount.IsZero() {\n\t\t\tpanic(\"undelegation attempt with zero coins\")\n\t\t}\n\t\tdelegatedFree := bva.DelegatedFree.AmountOf(coin.Denom)\n\t\tdelegatedVesting := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(DF, D)\n\t\t// Y := min(DV, D - X)\n\t\tx := sdk.MinInt(delegatedFree, coin.Amount)\n\t\ty := sdk.MinInt(delegatedVesting, coin.Amount.Sub(x))\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Sub(sdk.Coins{xCoin})\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Sub(sdk.Coins{yCoin})\n\t\t}\n\t}\n}", "func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins {\n\tdelegated := bonded.Add(unbonding...)\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated))\n\ttotal := delegated.Add(unbonded...)\n\ttoClawBack = coinsMin(toClawBack, total) // might have been slashed\n\tnewDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...)\n\tva.DelegatedVesting = coinsMin(encumbered, newDelegated)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n\treturn toClawBack\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func (k Keeper) TransferDelegation(ctx sdk.Context, valAddr sdk.ValAddress, fromDelegator, toDelegator sdk.AccAddress, shares sdk.Dec) (sdk.Dec, error) {\n\t// Redelegations link a delegation to it's previous validator so slashes are propagated to the new validator.\n\t// If the delegation is transferred to a new owner, the redelegation object must be updated.\n\t// For expediency all transfers with redelegations are blocked.\n\tif k.stakingKeeper.HasReceivingRedelegation(ctx, fromDelegator, valAddr) {\n\t\treturn sdk.Dec{}, types.ErrRedelegationsNotCompleted\n\t}\n\n\tif shares.IsNil() || shares.LT(sdk.ZeroDec()) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"nil or negative shares\")\n\t}\n\tif shares.Equal(sdk.ZeroDec()) {\n\t\t// Block 0 transfers to reduce edge cases.\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"zero shares\")\n\t}\n\n\tfromDelegation, found := k.stakingKeeper.GetDelegation(ctx, fromDelegator, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoDelegatorForAddress\n\t}\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// Prevent validators from reducing their self delegation below the min.\n\tisValidatorOperator := fromDelegator.Equals(valAddr)\n\tif isValidatorOperator {\n\t\tif isBelowMinSelfDelegation(validator, fromDelegation.Shares.Sub(shares)) {\n\t\t\treturn sdk.Dec{}, types.ErrSelfDelegationBelowMinimum\n\t\t}\n\t}\n\n\treturnAmount, err := k.fastUndelegate(ctx, valAddr, fromDelegator, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\tif err := k.bankKeeper.SendCoins(ctx, fromDelegator, toDelegator, returnCoins); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treceivedShares, err := k.delegateFromAccount(ctx, valAddr, toDelegator, returnAmount)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\treturn receivedShares, nil\n}", "func (_DelegationController *DelegationControllerTransactor) Delegate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"delegate\", validatorId, amount, delegationPeriod, info)\n}", "func (_DelegationController *DelegationControllerSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (_DelegationController *DelegationControllerTransactorSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (broadcast *Broadcast) Delegate(ctx context.Context, delegator, voter, amount,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.DelegateMsg{\n\t\tDelegator: delegator,\n\t\tVoter: voter,\n\t\tAmount: amount,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (o OfflineNotaryRepository) AddDelegation(data.RoleName, []data.PublicKey, []string) error {\n\treturn nil\n}", "func Delegate(stub shim.ChaincodeStubInterface, args []string) error {\n\tvar vote entities.Vote\n\terr := json.Unmarshal([]byte(args[0]), &vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpoll, err := validateDelegate(stub, vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = addVoteToPoll(stub, poll, vote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"saving delegate vote\")\n\tutil.UpdateObjectInChain(stub, vote.ID(), util.VotesIndexName, []byte(args[0]))\n\n\tfmt.Println(\"successfully delegated vote to \" + vote.Delegate + \"!\")\n\treturn nil\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (k Keeper) Delegation(ctx sdk.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) exported.DelegationI {\n\treturn nil\n}", "func (del Delegation) AmountDelegated() hexutil.Big {\n\tif del.Delegation.AmountDelegated == nil {\n\t\treturn hexutil.Big{}\n\t}\n\treturn *del.Delegation.AmountDelegated\n}", "func TestCallSimDelegate(t *testing.T) {\n\t// Roll up our sleeves and swear fealty to the witch-king\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tg, ctx := errgroup.WithContext(ctx)\n\n\tdb := dbm.NewMemDB()\n\tst, err := state.MakeGenesisState(db, genesisDoc)\n\trequire.NoError(t, err)\n\n\tfrom := crypto.PrivateKeyFromSecret(\"raaah\", crypto.CurveTypeEd25519)\n\tcontractAddress := crypto.Address{1, 2, 3, 4, 5}\n\tblockchain := &bcm.Blockchain{}\n\tsink := exec.NewNoopEventSink()\n\n\t// Function to set storage value for later\n\tsetDelegate := func(up state.Updatable, value crypto.Address) error {\n\t\tcall, _, err := abi.EncodeFunctionCall(string(solidity.Abi_DelegateProxy), \"setDelegate\", logger, value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcache := acmstate.NewCache(st)\n\t\t_, err = evm.Default().Execute(cache, blockchain, sink,\n\t\t\tengine.CallParams{\n\t\t\t\tCallType: exec.CallTypeCall,\n\t\t\t\tOrigin: from.GetAddress(),\n\t\t\t\tCaller: from.GetAddress(),\n\t\t\t\tCallee: contractAddress,\n\t\t\t\tInput: call,\n\t\t\t\tGas: big.NewInt(9999999),\n\t\t\t}, solidity.DeployedBytecode_DelegateProxy)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn cache.Sync(up)\n\t}\n\n\t// Initialise sender smart contract state\n\t_, _, err = st.Update(func(up state.Updatable) error {\n\t\terr = up.UpdateAccount(&acm.Account{\n\t\t\tAddress: from.GetAddress(),\n\t\t\tPublicKey: from.GetPublicKey(),\n\t\t\tBalance: 9999999,\n\t\t\tPermissions: permission.DefaultAccountPermissions,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn up.UpdateAccount(&acm.Account{\n\t\t\tAddress: contractAddress,\n\t\t\tEVMCode: solidity.DeployedBytecode_DelegateProxy,\n\t\t})\n\t})\n\trequire.NoError(t, err)\n\n\t// Set a series of values of storage slot so we get a deep version tree (which we need to trigger the bug)\n\tdelegate := crypto.Address{0xBE, 0xEF, 0, 0xFA, 0xCE, 0, 0xBA, 0}\n\tfor i := 0; i < 0xBF; i++ {\n\t\tdelegate[7] = byte(i)\n\t\t_, _, err = st.Update(func(up state.Updatable) error {\n\t\t\treturn setDelegate(up, delegate)\n\t\t})\n\t\trequire.NoError(t, err)\n\t}\n\n\t// This is important in order to illicit the former bug - we need a cold LRU tree cache in MutableForest\n\tst, err = state.LoadState(db, st.Version())\n\trequire.NoError(t, err)\n\n\tgetIntCall, _, err := abi.EncodeFunctionCall(string(solidity.Abi_DelegateProxy), \"getDelegate\", logger)\n\trequire.NoError(t, err)\n\tn := 1000\n\n\tfor i := 0; i < n; i++ {\n\t\tg.Go(func() error {\n\t\t\ttxe, err := CallSim(st, blockchain, from.GetAddress(), contractAddress, getIntCall, logger)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = txe.GetException().AsError()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\taddress, err := crypto.AddressFromBytes(txe.GetResult().Return[12:])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif address != delegate {\n\t\t\t\t// The bug for which this test was written will return the zero address here since it is accessing\n\t\t\t\t// an uninitialised tree\n\t\t\t\treturn fmt.Errorf(\"getDelegate returned %v but expected %v\", address, delegate)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\n\trequire.NoError(t, g.Wait())\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func (_TokensNetwork *TokensNetworkTransactor) UpdateBalanceProofDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"updateBalanceProofDelegate\", token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (k msgServer) CancelUnbondingDelegation(goCtx context.Context, msg *types.MsgCancelUnbondingDelegation) (*types.MsgCancelUnbondingDelegationResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\tvalAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\t// In some situations, the exchange rate becomes invalid, e.g. if\n\t// Validator loses all tokens due to slashing. In this case,\n\t// make all future delegations invalid.\n\tif validator.InvalidExRate() {\n\t\treturn nil, types.ErrDelegatorShareExRateInvalid\n\t}\n\n\tif validator.IsJailed() {\n\t\treturn nil, types.ErrValidatorJailed\n\t}\n\n\tubd, found := k.GetUnbondingDelegation(ctx, delegatorAddress, valAddr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"unbonding delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this undelegation was from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be incremented\n\ttokens := msg.Amount.Amount\n\tshares, err := validator.SharesFromTokens(tokens)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar (\n\t\tunbondEntry types.UnbondingDelegationEntry\n\t\tunbondEntryIndex int64 = -1\n\t)\n\n\tfor i, entry := range ubd.Entries {\n\t\tif entry.CreationHeight == msg.CreationHeight {\n\t\t\tunbondEntry = entry\n\t\t\tunbondEntryIndex = int64(i)\n\t\t\tbreak\n\t\t}\n\t}\n\tif unbondEntryIndex == -1 {\n\t\treturn nil, sdkerrors.ErrNotFound.Wrapf(\"unbonding delegation entry is not found at block height %d\", msg.CreationHeight)\n\t}\n\n\tif unbondEntry.Balance.LT(msg.Amount.Amount) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"amount is greater than the unbonding delegation entry balance\")\n\t}\n\n\tif unbondEntry.CompletionTime.Before(ctx.BlockTime()) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"unbonding delegation is already processed\")\n\t}\n\n\t// delegate back the unbonding delegation amount to the validator\n\t_, err = k.Keeper.Delegate(ctx, delegatorAddress, msg.Amount.Amount, types.Unbonding, validator, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tamount := unbondEntry.Balance.Sub(msg.Amount.Amount)\n\tif amount.IsZero() {\n\t\tubd.RemoveEntry(unbondEntryIndex)\n\t} else {\n\t\t// update the unbondingDelegationEntryBalance and InitialBalance for ubd entry\n\t\tunbondEntry.Balance = amount\n\t\tunbondEntry.InitialBalance = unbondEntry.InitialBalance.Sub(msg.Amount.Amount)\n\t\tubd.Entries[unbondEntryIndex] = unbondEntry\n\t}\n\n\t// set the unbonding delegation or remove it if there are no more entries\n\tif len(ubd.Entries) == 0 {\n\t\tk.RemoveUnbondingDelegation(ctx, ubd)\n\t} else {\n\t\tk.SetUnbondingDelegation(ctx, ubd)\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeCancelUnbondingDelegation,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCreationHeight, strconv.FormatInt(msg.CreationHeight, 10)),\n\t\t),\n\t)\n\n\treturn &types.MsgCancelUnbondingDelegationResponse{}, nil\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func (us *DelegationService) AddDelegation(delegation *models.Delegation) (*models.Delegation, error) {\n\t// TODO(tho) add CSR validation against template\n\treturn us.storeInterface.AddDelegation(delegation)\n}", "func (_TokensNetwork *TokensNetworkSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func NewDelegation(d *types.Delegation) *Delegation {\n\treturn &Delegation{Delegation: *d, cg: new(singleflight.Group)}\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (k Keeper) Delegation(ctx context.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) (types.DelegationI, error) {\n\tbond, err := k.Delegations.Get(ctx, collections.Join(addrDel, addrVal))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bond, nil\n}", "func (_TokensNetwork *TokensNetworkTransactor) UnlockDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"unlockDelegate\", token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func TestDelegatorProxyValidatorConstraints4Steps(t *testing.T) {\n\tcommon.InitConfig()\n\tparams := DefaultParams()\n\n\toriginVaSet := addrVals[1:]\n\tparams.MaxValidators = uint16(len(originVaSet))\n\tparams.Epoch = 2\n\tparams.UnbondingTime = time.Millisecond * 300\n\tstartUpValidator := NewValidator(StartUpValidatorAddr, StartUpValidatorPubkey, Description{}, types.DefaultMinSelfDelegation)\n\tstartUpStatus := baseValidatorStatus{startUpValidator}\n\torgValsLen := len(originVaSet)\n\tfullVaSet := make([]sdk.ValAddress, orgValsLen+1)\n\tcopy(fullVaSet, originVaSet)\n\tcopy(fullVaSet[orgValsLen:], []sdk.ValAddress{startUpStatus.getValidator().GetOperator()})\n\n\tbAction := baseAction{}\n\n\tstep1Actions := IActions{\n\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, true},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ProxiedDelegator}},\n\t\tdelegatorWithdrawAction{bAction, ProxiedDelegator, sdk.OneDec(), sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ProxiedDelegator, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ProxiedDelegator},\n\t}\n\n\tstep2Actions := IActions{\n\t\tdelegatorDepositAction{bAction, ValidDelegator1, DelegatedToken1, sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ValidDelegator1, ProxiedDelegator},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ValidDelegator1}},\n\t\tproxyUnBindAction{bAction, ValidDelegator1},\n\t\tdelegatorWithdrawAction{bAction, ValidDelegator1, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tstep3Actions := IActions{\n\t\tdelegatorDepositAction{bAction, ValidDelegator1, DelegatedToken1, sdk.DefaultBondDenom},\n\t\tproxyBindAction{bAction, ValidDelegator1, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ValidDelegator1},\n\t\tdelegatorWithdrawAction{bAction, ValidDelegator1, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tstep4Actions := IActions{\n\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, true},\n\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ProxiedDelegator}},\n\t\tproxyBindAction{bAction, ProxiedDelegator, ProxiedDelegator},\n\t\tproxyUnBindAction{bAction, ProxiedDelegator},\n\t\tdelegatorWithdrawAction{bAction, ProxiedDelegator, sdk.OneDec(), sdk.DefaultBondDenom},\n\t}\n\n\tfor s1 := 0; s1 < len(step1Actions); s1++ {\n\t\tfor s2 := 0; s2 < len(step2Actions); s2++ {\n\t\t\tfor s3 := 0; s3 < len(step3Actions); s3++ {\n\t\t\t\tfor s4 := 0; s4 < len(step4Actions); s4++ {\n\t\t\t\t\tinputActions := []IAction{\n\t\t\t\t\t\tcreateValidatorAction{bAction, nil},\n\t\t\t\t\t\tdelegatorsAddSharesAction{bAction, false, true, 0, []sdk.AccAddress{ValidDelegator2}},\n\t\t\t\t\t\tdelegatorDepositAction{bAction, ProxiedDelegator, MaxDelegatedToken, sdk.DefaultBondDenom},\n\t\t\t\t\t\tstep1Actions[s1],\n\t\t\t\t\t\tstep2Actions[s2],\n\t\t\t\t\t\tstep3Actions[s3],\n\t\t\t\t\t\tstep4Actions[s4],\n\t\t\t\t\t\tdelegatorRegProxyAction{bAction, ProxiedDelegator, false},\n\t\t\t\t\t\tdestroyValidatorAction{bAction},\n\t\t\t\t\t}\n\n\t\t\t\t\tactionsAndChecker, caseName := generateActionsAndCheckers(inputActions, 3)\n\n\t\t\t\t\tt.Logf(\"============================================== indexes:[%d,%d,%d,%d] %s ==============================================\", s1, s2, s3, s4, caseName)\n\t\t\t\t\t_, _, mk := CreateTestInput(t, false, SufficientInitPower)\n\t\t\t\t\tsmTestCase := newValidatorSMTestCase(mk, params, startUpStatus, inputActions, actionsAndChecker, t)\n\t\t\t\t\tsmTestCase.SetupValidatorSetAndDelegatorSet(int(params.MaxValidators))\n\t\t\t\t\tsmTestCase.printParticipantSnapshot(t)\n\t\t\t\t\tsmTestCase.Run(t)\n\t\t\t\t\tt.Log(\"============================================================================================\")\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n}", "func (k Keeper) fastUndelegate(ctx sdk.Context, valAddr sdk.ValAddress, delegator sdk.AccAddress, shares sdk.Dec) (sdkmath.Int, error) {\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdkmath.Int{}, types.ErrNoDelegatorForAddress\n\t}\n\n\treturnAmount, err := k.stakingKeeper.Unbond(ctx, delegator, valAddr, shares)\n\tif err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\t// transfer the validator tokens to the not bonded pool\n\tif validator.IsBonded() {\n\t\tif err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, returnCoins); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tif err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, stakingtypes.NotBondedPoolName, delegator, returnCoins); err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturn returnAmount, nil\n}", "func (pva *PeriodicVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, pva.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, pva.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := pva.DelegatedVesting.Add(pva.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV+DF by capping slashed at the current unvested amount\n\tunvested := pva.GetVestingCoins(ctx.BlockTime())\n\tnewSlashed := coinsMin(unvested, slashed)\n\tnewTotalDelegated := delegated.Add(newSlashed...)\n\n\t// modify vesting schedule for the new grant\n\tnewStart, newEnd, newPeriods := DisjunctPeriods(pva.StartTime, grantStartTime,\n\t\tpva.GetVestingPeriods(), grantVestingPeriods)\n\tpva.StartTime = newStart\n\tpva.EndTime = newEnd\n\tpva.VestingPeriods = newPeriods\n\tpva.OriginalVesting = pva.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newTotalDelegated\n\tunvested2 := pva.GetVestingCoins(ctx.BlockTime())\n\tpva.DelegatedVesting = coinsMin(newTotalDelegated, unvested2)\n\tpva.DelegatedFree = newTotalDelegated.Sub(pva.DelegatedVesting)\n}", "func (k msgServer) Undelegate(goCtx context.Context, msg *types.MsgUndelegate) (*types.MsgUndelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\taddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttokens := msg.Amount.Amount\n\tshares, err := k.ValidateUnbondAmount(\n\t\tctx, delegatorAddress, addr, tokens,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, addr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegation, found := k.GetDelegation(ctx, delegatorAddress, addr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this is a validator self-bond, the new liquid delegation cannot fall below the self-bond * bond factor\n\tif delegation.ValidatorBond {\n\t\tif err := k.SafelyDecreaseValidatorBond(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be decremented\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.DecreaseTotalLiquidStakedTokens(ctx, tokens); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.DecreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tcompletionTime, err := k.Keeper.Undelegate(ctx, delegatorAddress, addr, shares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"undelegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeUnbond,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),\n\t\t),\n\t})\n\n\treturn &types.MsgUndelegateResponse{\n\t\tCompletionTime: completionTime,\n\t}, nil\n}", "func (p *Ledger) RecordPayment(destination types.NodeAddress, amount int64, confirmed chan bool) {\n\tok := <-confirmed\n\tif ok {\n\t\tp.l.Lock()\n\t\tp.incoming_debt[p.id] -= amount\n\t\tp.outgoing_debt[destination] -= amount\n\t\tp.l.Unlock()\n\t}\n}", "func (a *account) managedTrackDeposit(amount types.Currency) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\ta.pendingDeposits = a.pendingDeposits.Add(amount)\n}", "func NewDelegation(d *types.Delegation, repo repository.Repository) *Delegation {\n\treturn &Delegation{\n\t\tDelegation: *d,\n\t\trepo: repo,\n\t}\n}", "func (p *Protocol) NumDelegates() uint64 {\n\treturn p.numDelegates\n}", "func (rs *rootResolver) Delegation(args *struct {\n\tAddress common.Address\n\tStaker hexutil.Big\n}) (*Delegation, error) {\n\t// get the delegator detail from backend\n\td, err := repository.R().Delegation(&args.Address, &args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDelegation(d), nil\n}", "func (o OfflineNotaryRepository) AddDelegationPaths(data.RoleName, []string) error {\n\treturn nil\n}", "func (_TokensNetwork *TokensNetworkSession) UnlockDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UnlockDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (tracker *PeerTracker) Track(ci *types.ChainInfo) {\n\ttracker.mu.Lock()\n\tdefer tracker.mu.Unlock()\n\n\t_, tracking := tracker.peers[ci.Peer]\n\t_, trusted := tracker.trusted[ci.Peer]\n\ttracker.peers[ci.Peer] = ci\n\tlogPeerTracker.Infof(\"Tracking %s, new=%t, count=%d trusted=%t\", ci, !tracking, len(tracker.peers), trusted)\n}", "func TestSlashWithRedelegation(t *testing.T) {\n\tapp, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)\n\tconsAddr := sdk.ConsAddress(PKs[0].Address())\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\tbondDenom := app.StakingKeeper.BondDenom(ctx)\n\n\t// set a redelegation\n\trdTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 6)\n\trd := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11,\n\t\ttime.Unix(0, 0), rdTokens, rdTokens.ToDec())\n\tapp.StakingKeeper.SetRedelegation(ctx, rd)\n\n\t// set the associated delegation\n\tdel := types.NewDelegation(addrDels[0], addrVals[1], rdTokens.ToDec())\n\tapp.StakingKeeper.SetDelegation(ctx, del)\n\n\t// update bonded tokens\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)\n\trdCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, rdTokens.MulRaw(2)))\n\n\trequire.NoError(t, simapp.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), rdCoins))\n\n\tapp.AccountKeeper.SetModuleAccount(ctx, bondedPool)\n\n\toldBonded := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\toldNotBonded := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\n\t// slash validator\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction) })\n\tburnAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(fraction).TruncateInt()\n\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\t// burn bonded tokens from only from delegations\n\tbondedPoolBalance := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\t// power decreased by 2 - 4 stake originally bonded at the time of infraction\n\t// was still bonded at the time of discovery and was slashed by half, 4 stake\n\t// bonded at the time of discovery hadn't been bonded at the time of infraction\n\t// and wasn't slashed\n\trequire.Equal(t, int64(8), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash the validator again\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\tburnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 7)\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\t// seven bonded tokens burned\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\t// power decreased by 4\n\trequire.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash the validator again, by 100%\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\n\tburnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(sdk.OneDec()).TruncateInt()\n\tburnAmount = burnAmount.Sub(sdk.OneDec().MulInt(rdTokens).TruncateInt())\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// apply TM updates\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)\n\t// read updated validator\n\t// validator decreased to zero power, should be in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n\n\t// slash the validator again, by 100%\n\t// no stake remains to be slashed\n\tctx = ctx.WithBlockHeight(12)\n\t// validator still in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded, bondedPoolBalance))\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\t// power still zero, still in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n}", "func (m *MetricsProvider) SignerAddLinkedDataProof(value time.Duration) {\n}", "func (*CardanoSignTransactionRequest_Certificate_StakeDelegation) Descriptor() ([]byte, []int) {\n\treturn file_cardano_proto_rawDescGZIP(), []int{4, 3, 0}\n}", "func (_Bep20 *Bep20Transactor) DelegateBySig(opts *bind.TransactOpts, delegatee common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Bep20.contract.Transact(opts, \"delegateBySig\", delegatee, nonce, expiry, v, r, s)\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UnlockDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UnlockDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, expiration, amount, secret_hash, merkle_proof, participant_signature)\n}", "func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV + DF by capping slashed at the current unvested amount\n\tunvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime()))\n\tnewSlashed := coinsMin(slashed, unvested)\n\tnewDelegated := delegated.Add(newSlashed...)\n\n\t// modify schedules for the new grant\n\tnewLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods)\n\tnewVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime,\n\t\tva.GetVestingPeriods(), grantVestingPeriods)\n\tif newLockupStart != newVestingStart {\n\t\tpanic(\"bad start time calculation\")\n\t}\n\tva.StartTime = newLockupStart\n\tva.EndTime = max64(newLockupEnd, newVestingEnd)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\tva.OriginalVesting = va.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newDelegated\n\tunvested2 := va.GetVestingCoins(ctx.BlockTime())\n\tva.DelegatedVesting = coinsMin(newDelegated, unvested2)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n}", "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func (a *account) managedTrackWithdrawal(amount types.Currency) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\ta.pendingWithdrawals = a.pendingWithdrawals.Add(amount)\n}", "func (_OwnerProxyRegistry *OwnerProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _OwnerProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_OwnerProxyRegistry *OwnerProxyRegistryTransactor) AddDelegate(opts *bind.TransactOpts, from common.Address) (*types.Transaction, error) {\n\treturn _OwnerProxyRegistry.contract.Transact(opts, \"addDelegate\", from)\n}", "func TestSlashWithUnbondingDelegation(t *testing.T) {\n\tapp, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)\n\n\tconsAddr := sdk.ConsAddress(PKs[0].Address())\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\n\t// set an unbonding delegation with expiration timestamp beyond which the\n\t// unbonding delegation shouldn't be slashed\n\tubdTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 4)\n\tubd := types.NewUnbondingDelegation(addrDels[0], addrVals[0], 11, time.Unix(0, 0), ubdTokens)\n\tapp.StakingKeeper.SetUnbondingDelegation(ctx, ubd)\n\n\t// slash validator for the first time\n\tctx = ctx.WithBlockHeight(12)\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\toldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\n\tvalidator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction)\n\n\t// end block\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)\n\n\t// read updating unbonding delegation\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance decreased\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 2), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned\n\tnewBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 3), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 - 6 stake originally bonded at the time of infraction\n\t// was still bonded at the time of discovery and was slashed by half, 4 stake\n\t// bonded at the time of discovery hadn't been bonded at the time of infraction\n\t// and wasn't slashed\n\trequire.Equal(t, int64(7), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance decreased again\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned again\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 6), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 again\n\trequire.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\t// all originally bonded stake has been slashed, so this will have no effect\n\t// on the unbonding delegation, but it will slash stake bonded since the infraction\n\t// this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance unchanged\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned again\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 9), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 again\n\trequire.Equal(t, int64(1), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\t// all originally bonded stake has been slashed, so this will have no effect\n\t// on the unbonding delegation, but it will slash stake bonded since the infraction\n\t// this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance unchanged\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// just 1 bonded token burned again since that's all the validator now has\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 10), diffTokens)\n\n\t// apply TM updates\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)\n\n\t// read updated validator\n\t// power decreased by 1 again, validator is out of stake\n\t// validator should be in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n}", "func (_DelegationController *DelegationControllerTransactor) AcceptPendingDelegation(opts *bind.TransactOpts, delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"acceptPendingDelegation\", delegationId)\n}", "func (rs *rootResolver) Delegation(args *struct {\n\tAddress common.Address\n\tStaker hexutil.Uint64\n}) (*Delegation, error) {\n\t// get the delegator detail from backend\n\td, err := rs.repo.Delegation(args.Address, args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDelegation(d, rs.repo), nil\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateDelegatedAmount(opts *bind.TransactOpts, holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateDelegatedAmount\", holder)\n}", "func (del Delegation) Amount() (hexutil.Big, error) {\n\t// get the base amount delegated\n\tbase, err := repository.R().DelegationAmountStaked(&del.Address, del.Delegation.ToStakerId)\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\n\t// get the sum of all pending withdrawals\n\twd, err := del.pendingWithdrawalsValue()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\tval := new(big.Int).Add(base, wd)\n\treturn (hexutil.Big)(*val), nil\n}", "func distributeDelegatorRewards(ctx contract.Context, cachedDelegations *CachedDposStorage, formerValidatorTotals map[string]loom.BigUInt, delegatorRewards map[string]*loom.BigUInt, distributedRewards *loom.BigUInt) (map[string]*loom.BigUInt, error) {\n\tnewDelegationTotals := make(map[string]*loom.BigUInt)\n\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize delegation totals with whitelist amounts\n\tfor _, candidate := range candidates {\n\t\tstatistic, _ := GetStatistic(ctx, loom.UnmarshalAddressPB(candidate.Address))\n\n\t\tif statistic != nil && statistic.WhitelistAmount != nil && !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\tvalidatorKey := loom.UnmarshalAddressPB(statistic.Address).String()\n\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\tnewDelegationTotals[validatorKey] = &amount\n\t\t}\n\t}\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar currentDelegations = make(DelegationList, len(delegations))\n\tcopy(currentDelegations, delegations)\n\tfor _, d := range currentDelegations {\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalidatorKey := loom.UnmarshalAddressPB(delegation.Validator).String()\n\n\t\t// Do not distribute rewards to delegators of the Limbo validator\n\t\t// NOTE: because all delegations are sorted in reverse index order, the\n\t\t// 0-index delegation (for rewards) is handled last. Therefore, all\n\t\t// increases to reward delegations will be reflected in newDelegation\n\t\t// totals that are computed at the end of this for loop. (We do this to\n\t\t// avoid looping over all delegations twice)\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\t// allocating validator distributions to delegators\n\t\t\t// based on former validator delegation totals\n\t\t\tdelegationTotal := formerValidatorTotals[validatorKey]\n\t\t\trewardsTotal := delegatorRewards[validatorKey]\n\t\t\tif rewardsTotal != nil {\n\t\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\t\tdelegatorDistribution := calculateShare(weightedDelegation, delegationTotal, *rewardsTotal)\n\t\t\t\t// increase a delegator's distribution\n\t\t\t\tdistributedRewards.Add(distributedRewards, &delegatorDistribution)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, delegation.Validator, delegation.Delegator, delegatorDistribution)\n\n\t\t\t\t// If the reward delegation is updated by the\n\t\t\t\t// IncreaseRewardDelegation command, we must be sure to use this\n\t\t\t\t// updated version in the rest of the loop. No other delegations\n\t\t\t\t// (non-rewards) have the possibility of being updated outside\n\t\t\t\t// of this loop.\n\t\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) && d.Index == REWARD_DELEGATION_INDEX {\n\t\t\t\t\tdelegation, err = GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\tif err == contract.ErrNotFound {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdatedAmount := common.BigZero()\n\t\tif delegation.State == BONDING {\n\t\t\tupdatedAmount.Add(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t} else if delegation.State == UNBONDING {\n\t\t\tupdatedAmount.Sub(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t\tcoin, err := loadCoin(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\terr = coin.Transfer(loom.UnmarshalAddressPB(delegation.Delegator), &delegation.UpdateAmount.Value)\n\t\t\tif err != nil {\n\t\t\t\ttransferFromErr := fmt.Sprintf(\"Failed coin Transfer - distributeDelegatorRewards, %v, %s\", delegation.Delegator.String(), delegation.UpdateAmount.Value.String())\n\t\t\t\treturn nil, logDposError(ctx, err, transferFromErr)\n\t\t\t}\n\t\t} else if delegation.State == REDELEGATING {\n\t\t\tif err = cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Validator = delegation.UpdateValidator\n\t\t\tdelegation.Amount = delegation.UpdateAmount\n\t\t\tdelegation.LocktimeTier = delegation.UpdateLocktimeTier\n\n\t\t\tindex, err := GetNextDelegationIndex(ctx, *delegation.Validator, *delegation.Delegator)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Index = index\n\n\t\t\tvalidatorKey = loom.UnmarshalAddressPB(delegation.Validator).String()\n\t\t}\n\n\t\t// Delete any delegation whose full amount has been unbonded. In all\n\t\t// other cases, update the delegation state to BONDED and reset its\n\t\t// UpdateAmount\n\t\tif common.IsZero(delegation.Amount.Value) && delegation.State == UNBONDING {\n\t\t\tif err := cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\t// After a delegation update, zero out UpdateAmount\n\t\t\tdelegation.UpdateAmount = loom.BigZeroPB()\n\t\t\tdelegation.State = BONDED\n\n\t\t\tresetDelegationIfExpired(ctx, delegation)\n\t\t\tif err := cachedDelegations.SetDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Calculate delegation totals for all validators except the Limbo\n\t\t// validator\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\tnewTotal := common.BigZero()\n\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\tnewTotal.Add(newTotal, &weightedDelegation)\n\t\t\tif newDelegationTotals[validatorKey] != nil {\n\t\t\t\tnewTotal.Add(newTotal, newDelegationTotals[validatorKey])\n\t\t\t}\n\t\t\tnewDelegationTotals[validatorKey] = newTotal\n\t\t}\n\t}\n\n\treturn newDelegationTotals, nil\n}", "func (a *Account) Track() {\n\t// Request notifications for transactions sending to all wallet\n\t// addresses.\n\taddrs := a.ActiveAddresses()\n\taddrstrs := make([]string, len(addrs))\n\ti := 0\n\tfor addr := range addrs {\n\t\taddrstrs[i] = addr.EncodeAddress()\n\t\ti++\n\t}\n\n\terr := NotifyNewTXs(CurrentServerConn(), addrstrs)\n\tif err != nil {\n\t\tlog.Error(\"Unable to request transaction updates for address.\")\n\t}\n\n\tfor _, txout := range a.TxStore.UnspentOutputs() {\n\t\tReqSpentUtxoNtfn(txout)\n\t}\n}", "func (m *mParcelMockDelegationToken) Set(f func() (r insolar.DelegationToken)) *ParcelMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.DelegationTokenFunc = f\n\treturn m.mock\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func (n *Node) BecomeDelegator(genesisAmount uint64, seedAmount uint64, delegatorAmount uint64, txFee uint64, stakerNodeID string) *Node {\n\n\t// exports AVAX from the X Chain\n\texportTxID, err := n.client.XChainAPI().ExportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tseedAmount+txFee,\n\t\tn.PAddress,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to export AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the XChain\n\terr = chainhelper.XChain().AwaitTransactionAcceptance(n.client, exportTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// imports the amount to the P Chain\n\timportTxID, err := n.client.PChainAPI().ImportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tconstants.XChainID.String(),\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed import AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the PChain\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, importTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// verify the PChain balance (seedAmount+txFee-txFee)\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, seedAmount)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance of seedAmount exists in the PChain\"))\n\t\treturn n\n\t}\n\n\t// verify the XChain balance of genesisAmount - seedAmount - txFee - txFee (import PChain)\n\terr = chainhelper.XChain().CheckBalance(n.client, n.XAddress, \"AVAX\", genesisAmount-seedAmount-2*txFee)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance XChain balance of genesisAmount-seedAmount-txFee\"))\n\t\treturn n\n\t}\n\n\tdelegatorStartTime := time.Now().Add(20 * time.Second)\n\tstartTime := uint64(delegatorStartTime.Unix())\n\tendTime := uint64(delegatorStartTime.Add(36 * time.Hour).Unix())\n\taddDelegatorTxID, err := n.client.PChainAPI().AddDelegator(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tstakerNodeID,\n\t\tdelegatorAmount,\n\t\tstartTime,\n\t\tendTime,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to add delegator %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, addDelegatorTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to accept AddDelegator tx: %s\", addDelegatorTxID))\n\t\treturn n\n\t}\n\n\t// Sleep until delegator starts validating\n\ttime.Sleep(time.Until(delegatorStartTime) + 3*time.Second)\n\n\texpectedDelegatorBalance := seedAmount - delegatorAmount\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, expectedDelegatorBalance)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Unexpected P Chain Balance after adding a new delegator to the network.\"))\n\t\treturn n\n\t}\n\tlogrus.Infof(\"Added delegator to subnet and verified the expected P Chain balance.\")\n\n\treturn n\n}", "func (_DelegationController *DelegationControllerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (_TransferProxyRegistry *TransferProxyRegistryCaller) CountDelegates(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _TransferProxyRegistry.contract.Call(opts, &out, \"countDelegates\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_DelegationController *DelegationControllerCallerSession) Delegations(arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\treturn _DelegationController.Contract.Delegations(&_DelegationController.CallOpts, arg0)\n}", "func (a *Account) Track() {\n\trpcc, err := accessClient()\n\tif err != nil {\n\t\tlog.Errorf(\"No chain server client to track addresses.\")\n\t\treturn\n\t}\n\n\t// Request notifications for transactions sending to all wallet\n\t// addresses.\n\t//\n\t// TODO: return as slice? (doesn't have to be ordered, or\n\t// SortedActiveAddresses would be fine.)\n\taddrMap := a.KeyStore.ActiveAddresses()\n\taddrs := make([]btcutil.Address, 0, len(addrMap))\n\tfor addr := range addrMap {\n\t\taddrs = append(addrs, addr)\n\t}\n\n\tif err := rpcc.NotifyReceived(addrs); err != nil {\n\t\tlog.Error(\"Unable to request transaction updates for address.\")\n\t}\n\n\tunspent, err := a.TxStore.UnspentOutputs()\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to access unspent outputs: %v\", err)\n\t\treturn\n\t}\n\tReqSpentUtxoNtfns(unspent)\n}", "func (pm *DPoSProtocolManager) syncDelegatedNodeSafely() {\n\tif !pm.isDelegatedNode() {\n\t\t// only candidate node is able to participant to this process.\n\t\treturn;\n\t}\n\tpm.lock.Lock()\n\tdefer pm.lock.Unlock()\n\tlog.Info(\"Preparing for next big period...\");\n\t// pull the newest delegators from voting contract.\n\ta, b, err0 := VotingAccessor.Refresh()\n\tif err0 != nil {\n\t\tlog.Error(err0.Error())\n\t\treturn;\n\t}\n\tDelegatorsTable = a\n\tDelegatorNodeInfo = b\n\tif uint8(len(GigPeriodHistory)) >= BigPeriodHistorySize {\n\t\tGigPeriodHistory = GigPeriodHistory[1:] //remove the first old one.\n\t}\n\tif len(DelegatorsTable) == 0 || pm.ethManager.peers.Len() == 0 {\n\t\tlog.Info(\"Sorry, could not detect any delegator!\");\n\t\treturn;\n\t}\n\tround := uint64(1)\n\tactiveTime := uint64(time.Now().Unix() + int64(GigPeriodInterval))\n\tif NextGigPeriodInstance != nil {\n\t\tif !TestMode {\n\t\t\tgap := int64(NextGigPeriodInstance.activeTime) - time.Now().Unix()\n\t\t\tif gap > 2 || gap < -2 {\n\t\t\t\tlog.Warn(fmt.Sprintf(\"Scheduling of the new electing round is improper! current gap: %v seconds\", gap))\n\t\t\t\t//restart the scheduler\n\t\t\t\tNextElectionInfo = nil;\n\t\t\t\tgo pm.syncDelegatedNodeSafely();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tround = NextGigPeriodInstance.round + 1\n\t\tactiveTime = GigPeriodInstance.activeTime + uint64(GigPeriodInterval)\n\t\t// keep the big period history for block validation.\n\t\tGigPeriodHistory[len(GigPeriodHistory)-1] = *NextGigPeriodInstance;\n\n\t\tGigPeriodInstance = &GigPeriodTable{\n\t\t\tNextGigPeriodInstance.round,\n\t\t\tNextGigPeriodInstance.state,\n\t\t\tNextGigPeriodInstance.delegatedNodes,\n\t\t\tNextGigPeriodInstance.delegatedNodesSign,\n\t\t\tNextGigPeriodInstance.confirmedTickets,\n\t\t\tNextGigPeriodInstance.confirmedBestNode,\n\t\t\tNextGigPeriodInstance.activeTime,\n\t\t};\n\t\tlog.Info(fmt.Sprintf(\"Switched the new big period round. %d \", GigPeriodInstance.round));\n\t}\n\n\t// make sure all delegators are synced at this round.\n\tNextGigPeriodInstance = &GigPeriodTable{\n\t\tround,\n\t\tSTATE_LOOKING,\n\t\tDelegatorsTable,\n\t\tSignCandidates(DelegatorsTable),\n\t\tmake(map[string]uint32),\n\t\tmake(map[string]*GigPeriodTable),\n\t\tactiveTime,\n\t};\n\tpm.trySyncAllDelegators()\n}", "func (_DelegationController *DelegationControllerCaller) Delegations(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tHolder common.Address\n\tValidatorId *big.Int\n\tAmount *big.Int\n\tDelegationPeriod *big.Int\n\tCreated *big.Int\n\tStarted *big.Int\n\tFinished *big.Int\n\tInfo string\n}, error) {\n\tret := new(struct {\n\t\tHolder common.Address\n\t\tValidatorId *big.Int\n\t\tAmount *big.Int\n\t\tDelegationPeriod *big.Int\n\t\tCreated *big.Int\n\t\tStarted *big.Int\n\t\tFinished *big.Int\n\t\tInfo string\n\t})\n\tout := ret\n\terr := _DelegationController.contract.Call(opts, out, \"delegations\", arg0)\n\treturn *ret, err\n}", "func (k Querier) Delegation(ctx context.Context, req *types.QueryDelegationRequest) (*types.QueryDelegationResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tif req.ValidatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"validator address cannot be empty\")\n\t}\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalAddr, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegation, err := k.Delegations.Get(ctx, collections.Join(sdk.AccAddress(delAddr), sdk.ValAddress(valAddr)))\n\tif err != nil {\n\t\tif errors.Is(err, collections.ErrNotFound) {\n\t\t\treturn nil, status.Errorf(\n\t\t\t\tcodes.NotFound,\n\t\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\t\treq.DelegatorAddr, req.ValidatorAddr)\n\t\t}\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tdelResponse, err := delegationToDelegationResponse(ctx, k.Keeper, delegation)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegationResponse{DelegationResponse: &delResponse}, nil\n}", "func (ac *Accumulator) WithTracking(max int) telegraf.TrackingAccumulator {\n\treturn &TrackingAccumulator{\n\t\tAccumulator: ac,\n\t\tdone: make(chan telegraf.DeliveryInfo, max),\n\t}\n}", "func (_DelegationController *DelegationControllerCaller) DelegationsByHolder(opts *bind.CallOpts, arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegationController.contract.Call(opts, out, \"delegationsByHolder\", arg0, arg1)\n\treturn *ret0, err\n}", "func (_DelegationController *DelegationControllerTransactorSession) AcceptPendingDelegation(delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.AcceptPendingDelegation(&_DelegationController.TransactOpts, delegationId)\n}", "func TestApplyChangelistCreatesDelegation(t *testing.T) {\n\trepo, cs, err := testutils.EmptyRepo(\"docker.com/notary\")\n\trequire.NoError(t, err)\n\n\tnewKey, err := cs.Create(\"targets/level1\", \"docker.com/notary\", data.ED25519Key)\n\trequire.NoError(t, err)\n\n\terr = repo.UpdateDelegationKeys(\"targets/level1\", []data.PublicKey{newKey}, []string{}, 1)\n\trequire.NoError(t, err)\n\terr = repo.UpdateDelegationPaths(\"targets/level1\", []string{\"\"}, []string{}, false)\n\trequire.NoError(t, err)\n\tdelete(repo.Targets, \"targets/level1\")\n\n\thash := sha256.Sum256([]byte{})\n\tf := &data.FileMeta{\n\t\tLength: 1,\n\t\tHashes: map[string][]byte{\n\t\t\t\"sha256\": hash[:],\n\t\t},\n\t}\n\tfjson, err := json.Marshal(f)\n\trequire.NoError(t, err)\n\n\tcl := changelist.NewMemChangelist()\n\trequire.NoError(t, cl.Add(&changelist.TUFChange{\n\t\tActn: changelist.ActionCreate,\n\t\tRole: \"targets/level1\",\n\t\tChangeType: \"target\",\n\t\tChangePath: \"latest\",\n\t\tData: fjson,\n\t}))\n\n\trequire.NoError(t, applyChangelist(repo, nil, cl))\n\t_, ok := repo.Targets[\"targets/level1\"]\n\trequire.True(t, ok, \"Failed to create the delegation target\")\n\t_, ok = repo.Targets[\"targets/level1\"].Signed.Targets[\"latest\"]\n\trequire.True(t, ok, \"Failed to write change to delegation target\")\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func (_Bep20 *Bep20Transactor) Delegate(opts *bind.TransactOpts, delegatee common.Address) (*types.Transaction, error) {\n\treturn _Bep20.contract.Transact(opts, \"delegate\", delegatee)\n}", "func (_Bep20 *Bep20Session) DelegateBySig(delegatee common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Bep20.Contract.DelegateBySig(&_Bep20.TransactOpts, delegatee, nonce, expiry, v, r, s)\n}", "func (_DelegationController *DelegationControllerSession) AcceptPendingDelegation(delegationId *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.AcceptPendingDelegation(&_DelegationController.TransactOpts, delegationId)\n}", "func UnmarshalDelegation(cdc *codec.Codec, key, value []byte) (delegation Delegation, err error) {\n\tvar storeValue delegationValue\n\terr = cdc.UnmarshalBinaryLengthPrefixed(value, &storeValue)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"%v: %v\", ErrNoDelegation(DefaultCodespace).Data(), err)\n\t\treturn\n\t}\n\n\taddrs := key[1:] // remove prefix bytes\n\tif len(addrs) != 2*sdk.AddrLen {\n\t\terr = fmt.Errorf(\"%v\", ErrBadDelegationAddr(DefaultCodespace).Data())\n\t\treturn\n\t}\n\n\tdelAddr := sdk.AccAddress(addrs[:sdk.AddrLen])\n\tvalAddr := sdk.ValAddress(addrs[sdk.AddrLen:])\n\n\treturn Delegation{\n\t\tDelegatorAddr: delAddr,\n\t\tValidatorAddr: valAddr,\n\t\tShares: storeValue.Shares,\n\t}, nil\n}", "func (_DelegationController *DelegationControllerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func SendPayments() {\n\tif !checkConfigSharingRatio() {\n\t\tlogger.Fatal(\"Unable to calculcate.\")\n\t}\n\n\tpubKey := viper.GetString(\"delegate.pubkey\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tpubKey = viper.GetString(\"delegate.Dpubkey\")\n\t}\n\n\tparams := core.DelegateQueryParams{PublicKey: pubKey}\n\tvar payload core.TransactionPayload\n\n\tvotersEarnings := arkclient.CalculateVotersProfit(params, viper.GetFloat64(\"voters.shareratio\"))\n\n\tsumEarned := 0.0\n\tsumRatio := 0.0\n\tsumShareEarned := 0.0\n\n\tp1, p2 := \"\", \"\"\n\tif _, err := os.Stat(\"/path/to/whatever\"); err == nil {\n\t\t// path/to/whatever exists\n\t} else {\n\t\tp1, p2 = readAccountData()\n\t}\n\n\tclearScreen()\n\n\tfor _, element := range votersEarnings {\n\t\tsumEarned += element.EarnedAmount100\n\t\tsumShareEarned += element.EarnedAmountXX\n\t\tsumRatio += element.VoteWeightShare\n\n\t\t//transaction parameters\n\t\ttxAmount2Send := int64(element.EarnedAmountXX*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\t\ttx := core.CreateTransaction(element.Address, txAmount2Send, viper.GetString(\"voters.txdescription\"), p1, p2)\n\n\t\tpayload.Transactions = append(payload.Transactions, tx)\n\t}\n\n\t//Cost & reserve fund calculation\n\tcostAmount := sumEarned * viper.GetFloat64(\"costs.shareratio\")\n\treserveAmount := sumEarned * viper.GetFloat64(\"reserve.shareratio\")\n\n\t//summary and conversion checks\n\tif (costAmount + reserveAmount + sumShareEarned) != sumEarned {\n\t\tcolor.Set(color.FgHiRed)\n\t\tlog.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t\tlogger.Println(\"Calculation of ratios NOT OK - overall summary failing\")\n\t}\n\n\tcostAmount2Send := int64(costAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\tcostAddress := viper.GetString(\"costs.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\tcostAddress = viper.GetString(\"costs.Daddress\")\n\t}\n\ttxCosts := core.CreateTransaction(costAddress, costAmount2Send, viper.GetString(\"costs.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txCosts)\n\n\treserveAddress := viper.GetString(\"reserve.address\")\n\tif core.EnvironmentParams.Network.Type == core.DEVNET {\n\t\treserveAddress = viper.GetString(\"reserve.Daddress\")\n\t}\n\treserveAmount2Send := int64(reserveAmount*core.SATOSHI) - core.EnvironmentParams.Fees.Send\n\n\ttxReserve := core.CreateTransaction(reserveAddress, reserveAmount2Send, viper.GetString(\"reserve.txdescription\"), p1, p2)\n\tpayload.Transactions = append(payload.Transactions, txReserve)\n\n\tcolor.Set(color.FgHiGreen)\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Println(\"Transactions to be sent:\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tcolor.Set(color.FgHiCyan)\n\tfor _, el := range payload.Transactions {\n\t\ts := fmt.Sprintf(\"|%s|%15d| %-40s|\", el.RecipientID, el.Amount, el.VendorField)\n\t\tfmt.Println(s)\n\t\tlogger.Println(s)\n\t}\n\n\tcolor.Set(color.FgHiYellow)\n\tfmt.Println(\"\")\n\tfmt.Println(\"--------------------------------------------------------------------------------------------------------------\")\n\tfmt.Print(\"Send transactions and complete reward payments [Y/N]: \")\n\n\tc, _ := reader.ReadByte()\n\n\tif c == []byte(\"Y\")[0] || c == []byte(\"y\")[0] {\n\t\tfmt.Println(\"Sending rewards to voters and sharing accounts.............\")\n\n\t\tres, httpresponse, err := arkclient.PostTransaction(payload)\n\t\tif res.Success {\n\t\t\tcolor.Set(color.FgHiGreen)\n\t\t\tlogger.Println(\"Transactions sent with Success,\", httpresponse.Status, res.TransactionIDs)\n\t\t\tlog.Println(\"Transactions sent with Success,\", httpresponse.Status)\n\t\t\tlog.Println(\"Audit log of sent transactions is in file paymentLog.csv!\")\n\t\t\tlog2csv(payload, res.TransactionIDs, votersEarnings)\n\t\t} else {\n\t\t\tcolor.Set(color.FgHiRed)\n\t\t\tlogger.Println(res.Message, res.Error, httpresponse.Status, err.Error())\n\t\t\tfmt.Println()\n\t\t\tfmt.Println(\"Failed\", res.Error)\n\t\t}\n\t\treader.ReadString('\\n')\n\t\tpause()\n\t}\n}", "func (p *Protocol) NumCandidateDelegates() uint64 {\n\treturn p.numCandidateDelegates\n}", "func (_DelegationController *DelegationControllerRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.DelegationControllerTransactor.contract.Transfer(opts)\n}", "func MustMarshalDelegation(cdc *codec.Codec, delegation Delegation) []byte {\n\tval := delegationValue{\n\t\tdelegation.Shares,\n\t}\n\treturn cdc.MustMarshalBinaryLengthPrefixed(val)\n}", "func StoreDelegationFromMessage(\n\theight int64, msg *stakingtypes.MsgDelegate, stakingClient stakingtypes.QueryClient, db *database.Db,\n) error {\n\theader := client.GetHeightRequestHeader(height)\n\tres, err := stakingClient.Delegation(\n\t\tcontext.Background(),\n\t\t&stakingtypes.QueryDelegationRequest{\n\t\t\tDelegatorAddr: msg.DelegatorAddress,\n\t\t\tValidatorAddr: msg.ValidatorAddress,\n\t\t},\n\t\theader,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdelegation := ConvertDelegationResponse(height, *res.DelegationResponse)\n\treturn db.SaveDelegations([]types.Delegation{delegation})\n}", "func (_DelegationController *DelegationControllerTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.contract.Transfer(opts)\n}", "func (m *ParcelMock) DelegationTokenMinimockCounter() uint64 {\n\treturn atomic.LoadUint64(&m.DelegationTokenCounter)\n}", "func (s *ArkClient) GetDelegateVoteWeight(params DelegateQueryParams) (int, *http.Response, error) {\n\trespData := new(DelegateVoters)\n\trespError := new(ArkApiResponseError)\n\tresp, err := s.sling.New().Get(\"api/delegates/voters\").QueryStruct(&params).Receive(respData, respError)\n\tif err == nil {\n\t\terr = respError\n\t}\n\n\t//calculating vote weight\n\tbalance := 0\n\tif respData.Success {\n\t\tfor _, element := range respData.Accounts {\n\t\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\t\tbalance += intBalance\n\t\t}\n\t}\n\n\treturn balance, resp, err\n}", "func (_DelegationController *DelegationControllerTransactor) Confiscate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"confiscate\", validatorId, amount)\n}", "func (_Bep20 *Bep20TransactorSession) DelegateBySig(delegatee common.Address, nonce *big.Int, expiry *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Bep20.Contract.DelegateBySig(&_Bep20.TransactOpts, delegatee, nonce, expiry, v, r, s)\n}", "func Transfer(\n\tctx *vm.Context, db vm.StateDB, sender, recipient types.AddressHash, amount *big.Int,\n) {\n\t// NOTE: amount is a re-used pointer varaible\n\tdb.SubBalance(sender, amount)\n\tdb.AddBalance(recipient, amount)\n\tif db.IsContractAddr(sender) && amount.Uint64() > 0 {\n\t\ttransferInfo := vm.NewTransferInfo(sender, recipient, amount.Uint64())\n\t\tlogger.Debugf(\"new transfer info: sender: %x, recipient: %x, amount: %d\",\n\t\t\tsender[:], recipient[:], amount)\n\t\tif v, ok := ctx.Transfers[sender]; ok {\n\t\t\t// if sender and recipient already exists in Transfers, update it instead\n\t\t\t// of append to it\n\t\t\tfor _, w := range v {\n\t\t\t\tif w.To == recipient {\n\t\t\t\t\t// NOTE: cannot miss 'w.value = '\n\t\t\t\t\tw.Value += amount.Uint64()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tctx.Transfers[sender] = append(ctx.Transfers[sender], transferInfo)\n\t}\n}", "func (o *Member) SetDelegateCur(v int32) {\n\to.DelegateCur = &v\n}", "func (_DelegationController *DelegationControllerCallerSession) DelegationsByHolder(arg0 common.Address, arg1 *big.Int) (*big.Int, error) {\n\treturn _DelegationController.Contract.DelegationsByHolder(&_DelegationController.CallOpts, arg0, arg1)\n}", "func (vi *votedInfo) CalculateReward(multiplier, divider *big.Int, period int) {\n\tif multiplier.Sign() == 0 || period == 0 {\n\t\treturn\n\t}\n\tif divider.Sign() == 0 || vi.totalBondedDelegation.Sign() == 0 {\n\t\treturn\n\t}\n\t// reward = multiplier * period * bondedDelegation / (divider * totalBondedDelegation)\n\tbase := new(big.Int).Mul(multiplier, big.NewInt(int64(period)))\n\treward := new(big.Int)\n\tfor i, addrKey := range vi.rank {\n\t\tif i == vi.maxRankForReward {\n\t\t\tbreak\n\t\t}\n\t\tprep := vi.preps[addrKey]\n\t\tif prep.Enable() == false {\n\t\t\tcontinue\n\t\t}\n\n\t\treward.Mul(base, prep.GetBondedDelegation())\n\t\treward.Div(reward, divider)\n\t\treward.Div(reward, vi.totalBondedDelegation)\n\n\t\tlog.Tracef(\"VOTED REWARD %d = %d * %d * %d / (%d * %d)\",\n\t\t\treward, multiplier, period, prep.GetBondedDelegation(), divider, vi.totalBondedDelegation)\n\n\t\tprep.SetIScore(new(big.Int).Add(prep.IScore(), reward))\n\t}\n}", "func TestDonationCase1(t *testing.T) {\n\tassert := assert.New(t)\n\tstore := newReputationStoreOnMock()\n\trep := NewTestReputationImpl(store)\n\tt1 := time.Date(1995, time.February, 5, 11, 11, 0, 0, time.UTC)\n\tt3 := time.Date(1995, time.February, 6, 12, 11, 0, 0, time.UTC)\n\tt4 := time.Date(1995, time.February, 7, 13, 11, 1, 0, time.UTC)\n\tuser1 := \"user1\"\n\tpost1 := \"post1\"\n\tpost2 := \"post2\"\n\n\t// round 2\n\trep.Update(t1.Unix())\n\trep.DonateAt(user1, post1, big.NewInt(100*OneLinoCoin))\n\tassert.Equal(big.NewInt(100*OneLinoCoin), rep.store.GetRoundPostSumStake(2, post1))\n\tassert.Equal(rep.GetReputation(user1), big.NewInt(InitialCustomerScore))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.store.GetRoundSumDp(2)) // bounded by this user's dp\n\n\t// round 3\n\trep.Update(t3.Unix())\n\t// (1 * 9 + 100) / 10\n\tassert.Equal(big.NewInt(1090000), rep.GetReputation(user1))\n\tassert.Equal(big.NewInt(OneLinoCoin), rep.GetSumRep(post1))\n\trep.DonateAt(user1, post1, big.NewInt(1*OneLinoCoin)) // does not count\n\trep.DonateAt(user1, post2, big.NewInt(900*OneLinoCoin))\n\trep.Update(t4.Unix())\n\t// (10.9 * 9 + 900) / 10\n\tassert.Equal(big.NewInt(9981000), rep.GetReputation(user1))\n\tassert.Equal([]Pid{post2}, rep.store.GetRoundResult(3))\n\t// round 4\n}", "func (s *Streams) Delegate(data interface{}) {\n\tlisteners := s.Size()\n\n\tif listeners <= 0 {\n\t\treturn\n\t}\n\n\tif s.reverse {\n\t\ts.RevMunch(data)\n\t} else {\n\t\ts.Munch(data)\n\t}\n\n}", "func bindDelegationController(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(DelegationControllerABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func CheckPercentageSumForCycle(cycle int, delegatedContracts []DelegatedContract) float64{\n var sum float64\n sum = 0\n for x := 0; x < len(delegatedContracts); x++{\n counter := 0\n for y := 0; y < len(delegatedContracts[x].Contracts); y++{\n if (delegatedContracts[x].Contracts[y].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n\n sum = sum + delegatedContracts[x].Contracts[counter].SharePercentage\n }\n return sum\n}" ]
[ "0.8186424", "0.78992194", "0.7826971", "0.7759204", "0.7720231", "0.76592255", "0.68331814", "0.61249405", "0.57603174", "0.57438606", "0.5540563", "0.5494072", "0.5373377", "0.5255798", "0.5181217", "0.5127807", "0.5004754", "0.49716696", "0.48736444", "0.47637394", "0.47572365", "0.47441486", "0.47415286", "0.47170526", "0.47144836", "0.46762803", "0.4665858", "0.46413714", "0.46357104", "0.46282062", "0.46207032", "0.46174976", "0.45709854", "0.45557988", "0.45413628", "0.45049483", "0.4495502", "0.4473732", "0.4449344", "0.44417274", "0.44170544", "0.44156864", "0.44124243", "0.44088262", "0.43887216", "0.43861192", "0.43848553", "0.43848354", "0.43713954", "0.43558377", "0.435278", "0.43476027", "0.4344151", "0.4332731", "0.432678", "0.43134677", "0.4307876", "0.4304364", "0.42990726", "0.4283877", "0.42665523", "0.42636392", "0.42591867", "0.42550877", "0.42353064", "0.42281723", "0.42134857", "0.4212719", "0.4204074", "0.42036006", "0.41956878", "0.41940516", "0.41935286", "0.41853747", "0.41690361", "0.4162062", "0.4143749", "0.41329622", "0.41223946", "0.41171968", "0.4111449", "0.40986988", "0.40982163", "0.4095512", "0.4081912", "0.40817314", "0.40745437", "0.406955", "0.40690288", "0.40682822", "0.40601623", "0.40589195", "0.40515175", "0.4050353", "0.40455115", "0.40443146", "0.40415394", "0.40320256", "0.40303165", "0.40243965" ]
0.7715642
5
GetStartTime returns the time when vesting starts for a periodic vesting account.
func (va ClawbackVestingAccount) GetStartTime() int64 { return va.StartTime }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pva PeriodicVestingAccount) GetStartTime() int64 {\n\treturn pva.StartTime\n}", "func (dva DelayedVestingAccount) GetStartTime() int64 {\n\treturn 0\n}", "func (cva ContinuousVestingAccount) GetStartTime() int64 {\n\treturn cva.StartTime\n}", "func GetStartTime() time.Time {\n\treturn startAtTime\n}", "func (txn TxnProbe) GetStartTime() time.Time {\n\treturn txn.startTime\n}", "func (plva PermanentLockedAccount) GetStartTime() int64 {\n\treturn 0\n}", "func (this *SyncFlightInfo) GetStartTime() time.Time {\n\tthis.lock.RLock()\n\tdefer this.lock.RUnlock()\n\treturn this.startTime\n}", "func (o *ApplianceSetupInfoAllOf) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (req *StartWFSRequest) GetStartTime() time.Time {\n\treturn req.StartTime\n}", "func (instance *Instance) StartTime() time.Time {\n\tuptimeDuration := time.Duration(instance.Uptime) * time.Second\n\n\treturn time.Now().Add(-uptimeDuration)\n}", "func (o ReservedInstanceOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ReservedInstance) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (m *RequestSchedule) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (o *ApplianceClusterInstallPhase) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (o *UcsdBackupInfoAllOf) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (f *Filler) StartTime() time.Time {\n\treturn f.tp\n}", "func (o BeanstalkScheduledTaskOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BeanstalkScheduledTask) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (s *Session) GetStartTime() time.Time {\n\treturn s.started\n}", "func (o *OnpremUpgradePhase) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (a *Auction) StartTime() time.Time {\n\treturn a.startTime\n}", "func StartTime() time.Time {\n\treturn processStartTime\n}", "func (o ElastigroupScheduledTaskOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScheduledTask) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (m *SimulationAutomationRun) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (o ResourcePolicyInstanceSchedulePolicyOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyInstanceSchedulePolicy) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (v *Validator) StartTime() time.Time {\n\treturn time.Unix(int64(v.Start), 0)\n}", "func (o *VirtualizationIweVirtualMachine) GetStartTime() string {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (r Reservation) StartTime() string {\n\thr := r.Start / 60\n\tmin := r.Start % 60\n\tvar ampm string\n\tif ampm = \"AM\"; hr >= 12 {\n\t\tampm = \"PM\"\n\t}\n\tif hr > 12 {\n\t\thr = hr - 12\n\t}\n\tif hr == 0 {\n\t\thr = 12\n\t}\n\treturn fmt.Sprintf(\"%02d:%02d %s\", hr, min, ampm)\n}", "func (o ResourcePolicyWeeklyCycleDayOfWeekOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyWeeklyCycleDayOfWeek) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (r *ScheduledAction) StartTime() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"startTime\"])\n}", "func (c *Context) StartTime() *time.Time {\n\treturn &c.startTime\n}", "func (o InstanceMaintenanceScheduleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceSchedule) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o InstanceMaintenanceScheduleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceSchedule) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ResourcePolicyDailyCycleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyDailyCycle) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (c *Container) GetStartTime() time.Time {\n\treturn c.start\n}", "func (mgr *Manager) StartTime() time.Time {\n\treturn mgr.startTime\n}", "func (o *WorkflowServiceItemActionInstance) GetStartTime() time.Time {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (o *Job) GetStartTime(ctx context.Context) (startTime uint64, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceJob, \"StartTime\").Store(&startTime)\n\treturn\n}", "func (o ResourcePolicyHourlyCycleOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyHourlyCycle) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ResourcePolicyInstanceSchedulePolicyResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourcePolicyInstanceSchedulePolicyResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (m *GetSchedulePostRequestBody) GetStartTime()(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.DateTimeTimeZoneable) {\n return m.startTime\n}", "func (req *ServerHTTPRequest) StartTime() time.Time {\n\treturn req.startTime\n}", "func (b *fixedResolutionValues) StartTime() xtime.UnixNano {\n\treturn b.startTime\n}", "func (o ResourcePolicyInstanceSchedulePolicyPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyInstanceSchedulePolicy) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o GoogleCloudRetailV2alphaConditionTimeRangeOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionTimeRange) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ResourcePolicyWeeklyCycleDayOfWeekResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourcePolicyWeeklyCycleDayOfWeekResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (p *SASQueryParameters) StartTime() time.Time {\n\treturn p.startTime\n}", "func (_LvRecording *LvRecordingCaller) StartTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _LvRecording.contract.Call(opts, &out, \"startTime\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (gm GlobalManager) GetChainStartTime(ctx sdk.Context) (int64, sdk.Error) {\n\tglobalTime, err := gm.storage.GetGlobalTime(ctx)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn globalTime.ChainStartTime, nil\n}", "func (o DataTransferConfigScheduleOptionsOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DataTransferConfigScheduleOptions) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (m *BookingWorkTimeSlot) GetStart()(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly) {\n val, err := m.GetBackingStore().Get(\"start\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.TimeOnly)\n }\n return nil\n}", "func (o InstanceMaintenanceSchedulePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InstanceMaintenanceSchedule) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o InstanceMaintenanceWindowOutput) StartTime() InstanceMaintenanceWindowStartTimeOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceWindow) InstanceMaintenanceWindowStartTime { return v.StartTime }).(InstanceMaintenanceWindowStartTimeOutput)\n}", "func (o JobScheduleOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *JobSchedule) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o InstanceMaintenancePolicyWeeklyMaintenanceWindowOutput) StartTime() InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput {\n\treturn o.ApplyT(func(v InstanceMaintenancePolicyWeeklyMaintenanceWindow) InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTime {\n\t\treturn v.StartTime\n\t}).(InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput)\n}", "func (o InstanceMaintenancePolicyWeeklyMaintenanceWindowOutput) StartTime() InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput {\n\treturn o.ApplyT(func(v InstanceMaintenancePolicyWeeklyMaintenanceWindow) InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTime {\n\t\treturn v.StartTime\n\t}).(InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput)\n}", "func (m *ExternalActivity) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startDateTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func StartTime() {\n\tstart = time.Now()\n}", "func (o ResourcePolicyDailyCycleResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourcePolicyDailyCycleResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (e *Event) StartTime() Time {\n\treturn e.start\n}", "func (o ResourcePolicyDailyCyclePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyDailyCycle) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o DataTransferConfigScheduleOptionsPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DataTransferConfigScheduleOptions) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *UserExperienceAnalyticsDeviceStartupHistory) GetStartTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n val, err := m.GetBackingStore().Get(\"startTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)\n }\n return nil\n}", "func (m *MobileAppInstallTimeSettings) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n return m.startDateTime\n}", "func (o *ProjectDeploymentRuleResponse) GetStartTime() time.Time {\n\tif o == nil || o.StartTime.Get() == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartTime.Get()\n}", "func (pb *Bar) StartTime() time.Time {\n\tpb.mu.RLock()\n\tdefer pb.mu.RUnlock()\n\treturn pb.startTime\n}", "func (o BaselineStrategyOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *BaselineStrategy) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o StorageCapacityUnitOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *StorageCapacityUnit) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (s *Storage) StartTime() (int64, error) {\n\treturn int64(model.Latest), nil\n}", "func (o GoogleCloudRetailV2alphaConditionTimeRangeResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionTimeRangeResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (m *TermsExpiration) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n return m.startDateTime\n}", "func (o ScanRunResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ScanRunResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o ScanRunResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ScanRunResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o ScanRunOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o ScanRunOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ScanRun) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o *KubernetesPodStatus) GetStartTime() string {\n\tif o == nil || o.StartTime == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.StartTime\n}", "func (o ResourcePolicyHourlyCycleResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourcePolicyHourlyCycleResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o LicenseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *License) pulumi.StringOutput { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o ResourcePolicyHourlyCyclePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyHourlyCycle) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (c *Clock) GetStart() time.Time {\n\tc.init()\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\treturn c.start\n}", "func (o ResourcePolicyInstanceSchedulePolicyResponsePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyInstanceSchedulePolicyResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *Reminder) GetEventStartTime()(DateTimeTimeZoneable) {\n val, err := m.GetBackingStore().Get(\"eventStartTime\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(DateTimeTimeZoneable)\n }\n return nil\n}", "func (o KubernetesClusterMaintenanceWindowAutoUpgradeOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterMaintenanceWindowAutoUpgrade) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o TriggerBuildArtifactsObjectsTimingOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v TriggerBuildArtifactsObjectsTiming) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o NodeGroupMaintenanceWindowResponseOutput) StartTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v NodeGroupMaintenanceWindowResponse) string { return v.StartTime }).(pulumi.StringOutput)\n}", "func (o NodeGroupMaintenanceWindowOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v NodeGroupMaintenanceWindow) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (p *protocol) TimeSlotStart() time.Time {\n\treturn p.refTime().Truncate(TruncateDuration)\n}", "func GetBeginningOfDay(t time.Time) time.Time {\n\tyear, month, day := t.Date()\n\tstartOfDay := time.Date(year, month, day, 0, 0, 0, 0, t.Location())\n\treturn startOfDay\n}", "func (o JobStatusPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func (o JobStatusOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *string { return v.StartTime }).(pulumi.StringPtrOutput)\n}", "func GetBeginningOfDay(t time.Time) time.Time {\n\ty, m, d := t.Date()\n\ttimeBOD := time.Date(y, m, d, 0, 0, 0, 0, t.Location())\n\treturn timeBOD\n}", "func (n *ssvNode) getSlotStartTime(slot uint64) time.Time {\n\ttimeSinceGenesisStart := slot * uint64(n.ethNetwork.SlotDurationSec().Seconds())\n\tstart := time.Unix(int64(n.ethNetwork.MinGenesisTime()+timeSinceGenesisStart), 0)\n\treturn start\n}", "func (o *Run) GetStartedAt() time.Time {\n\tif o == nil || o.StartedAt == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.StartedAt\n}", "func (o KubernetesClusterMaintenanceWindowAutoUpgradePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *KubernetesClusterMaintenanceWindowAutoUpgrade) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (q *Queries) EventStartTime(ctx context.Context, id models.EventID) (time.Time, error) {\n\tdefer daoSpan(&ctx)()\n\treturn q.dbc.EventStartTime(ctx, id)\n}", "func (o ResourcePolicyDailyCycleResponsePtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyDailyCycleResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ScanRunPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ScanRunPtrOutput) StartTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScanRun) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StartTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (c deploymentChecker) BeginTime() uint64 {\n\treturn c.deployment.StartTime\n}", "func (o *AvailableBudget) GetStart() time.Time {\n\tif o == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\n\treturn o.Start\n}", "func (c *PurchasesVoidedpurchasesListCall) StartTime(startTime int64) *PurchasesVoidedpurchasesListCall {\n\tc.urlParams_.Set(\"startTime\", fmt.Sprint(startTime))\n\treturn c\n}", "func (o TimelineOutput) StartTime() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *Timeline) pulumi.IntPtrOutput { return v.StartTime }).(pulumi.IntPtrOutput)\n}" ]
[ "0.7675311", "0.7655725", "0.7410766", "0.72879225", "0.7022617", "0.6954567", "0.6840737", "0.6801517", "0.6740562", "0.66733193", "0.6625888", "0.6578882", "0.65752226", "0.656922", "0.6512452", "0.64991933", "0.6462216", "0.6451606", "0.64373773", "0.6424162", "0.64052635", "0.640403", "0.63828415", "0.6364371", "0.63640296", "0.6359827", "0.63552314", "0.63549674", "0.6350873", "0.63249874", "0.63249874", "0.63210994", "0.6288855", "0.6282087", "0.6264101", "0.6258634", "0.6216077", "0.618918", "0.6187674", "0.6173102", "0.61671615", "0.61419374", "0.6133627", "0.6132435", "0.6131833", "0.6127392", "0.61044765", "0.6101002", "0.6096408", "0.608021", "0.60764295", "0.6071824", "0.6066885", "0.6066885", "0.60595244", "0.6059168", "0.60523576", "0.60438174", "0.6043017", "0.6031664", "0.6031102", "0.6018824", "0.6003526", "0.59914106", "0.59864056", "0.59642994", "0.5962534", "0.5958823", "0.5953968", "0.5952293", "0.5952293", "0.59412116", "0.59412116", "0.5940697", "0.5937747", "0.593637", "0.5926876", "0.59205025", "0.590706", "0.5879856", "0.58658546", "0.58589894", "0.58487236", "0.58470243", "0.5836404", "0.5834474", "0.58306277", "0.58159024", "0.58080256", "0.57926774", "0.57911175", "0.5771486", "0.5769003", "0.5765021", "0.5748508", "0.5748508", "0.57314533", "0.57267237", "0.5725302", "0.5716983" ]
0.7509543
2
GetVestingPeriods returns vesting periods associated with periodic vesting account.
func (va ClawbackVestingAccount) GetVestingPeriods() Periods { return va.VestingPeriods }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pva PeriodicVestingAccount) GetVestingPeriods() Periods {\n\treturn pva.VestingPeriods\n}", "func NewPeriodicVestingAccount(baseAcc *authtypes.BaseAccount, originalVesting sdk.Coins, startTime int64, periods Periods) *PeriodicVestingAccount {\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func (pva PeriodicVestingAccount) Validate() error {\n\tif pva.GetStartTime() >= pva.GetEndTime() {\n\t\treturn errors.New(\"vesting start-time cannot be before end-time\")\n\t}\n\tendTime := pva.StartTime\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range pva.VestingPeriods {\n\t\tendTime += p.Length\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\tif endTime != pva.EndTime {\n\t\treturn errors.New(\"vesting end time does not match length of all vesting periods\")\n\t}\n\tif !originalVesting.IsEqual(pva.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in vesting periods\")\n\t}\n\n\treturn pva.BaseVestingAccount.Validate()\n}", "func newPeriodicVestingAccount(address sdk.AccAddress, periods vestingtypes.Periods, firstPeriodStartTimestamp int64) *vestingtypes.PeriodicVestingAccount {\n\tbaseAccount := authtypes.NewBaseAccount(address, nil, 0, 0)\n\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range periods {\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\n\tvar totalPeriods int64\n\tfor _, p := range periods {\n\t\ttotalPeriods += p.Length\n\t}\n\tendTime := firstPeriodStartTimestamp + totalPeriods\n\n\tbaseVestingAccount := vestingtypes.NewBaseVestingAccount(baseAccount, originalVesting, endTime)\n\treturn vestingtypes.NewPeriodicVestingAccountRaw(baseVestingAccount, firstPeriodStartTimestamp, periods)\n}", "func (n Network) VestingAccounts(ctx context.Context, launchID uint64) (vestingAccs []networktypes.VestingAccount, err error) {\n\tn.ev.Send(events.New(events.StatusOngoing, \"Fetching genesis vesting accounts\"))\n\tres, err := n.launchQuery.\n\t\tVestingAccountAll(ctx,\n\t\t\t&launchtypes.QueryAllVestingAccountRequest{\n\t\t\t\tLaunchID: launchID,\n\t\t\t},\n\t\t)\n\tif err != nil {\n\t\treturn vestingAccs, err\n\t}\n\n\tfor i, acc := range res.VestingAccount {\n\t\tparsedAcc, err := networktypes.ToVestingAccount(acc)\n\t\tif err != nil {\n\t\t\treturn vestingAccs, errors.Wrapf(err, \"error parsing vesting account %d\", i)\n\t\t}\n\n\t\tvestingAccs = append(vestingAccs, parsedAcc)\n\t}\n\n\treturn vestingAccs, nil\n}", "func (db *DB) GetAllPeriods() ([]string, error) {\n\tvar allPeriods []string\n\n\tconn, err := redishelper.GetRedisConn(db.RedisServer, db.RedisPassword)\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\tdefer conn.Close()\n\n\tk := \"ming:campuses\"\n\tcampuses, err := redis.Strings(conn.Do(\"ZRANGE\", k, 0, -1))\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tfor _, campus := range campuses {\n\t\tk = fmt.Sprintf(\"ming:%v:categories\", campus)\n\t\tcategories, err := redis.Strings(conn.Do(\"ZRANGE\", k, 0, -1))\n\t\tif err != nil {\n\t\t\treturn []string{}, err\n\t\t}\n\n\t\tfor _, category := range categories {\n\t\t\tk = fmt.Sprintf(\"ming:%v:%v:periods\", campus, category)\n\t\t\tperiods, err := redis.Strings(conn.Do(\"ZRANGE\", k, 0, -1))\n\t\t\tif err != nil {\n\t\t\t\treturn []string{}, err\n\t\t\t}\n\n\t\t\tfor _, period := range periods {\n\t\t\t\tallPeriods = append(allPeriods, fmt.Sprintf(\"%v:%v:%v\", campus, category, period))\n\t\t\t}\n\n\t\t}\n\t}\n\treturn allPeriods, nil\n}", "func (vp Periods) String() string {\n\tperiodsListString := make([]string, len(vp))\n\tfor _, period := range vp {\n\t\tperiodsListString = append(periodsListString, period.String())\n\t}\n\n\treturn strings.TrimSpace(fmt.Sprintf(`Vesting Periods:\n\t\t%s`, strings.Join(periodsListString, \", \")))\n}", "func PeriodGET(w http.ResponseWriter, r *http.Request) {\n\tsess := model.Instance(r)\n lisPeriods, _ := model.Periods()\n\tv := view.New(r)\n\tv.Name = \"periodo/period\"\n\tv.Vars[\"token\"] = csrfbanana.Token(w, r, sess)\n v.Vars[\"LisPeriods\"] = lisPeriods\n// Refill any form fields\n// view.Repopulate([]string{\"name\"}, r.Form, v.Vars)\n\tv.Render(w)\n }", "func NewValidatorVestingAccount(baseAcc *authtypes.BaseAccount, startTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tendTime := startTime\n\tfor _, p := range periods {\n\t\tendTime += p.Length\n\t}\n\tbaseVestingAcc := &vestingtypes.BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: baseAcc.Coins,\n\t\tEndTime: endTime,\n\t}\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func (c *UptimeCommand) GetPeriodOptions() []string {\n\treturn []string{\n\t\t\"Today\",\n\t\t\"Yesterday\",\n\t\t\"ThisWeek\",\n\t\t\"LastWeek\",\n\t\t\"ThisMonth\",\n\t\t\"LastMonth\",\n\t\t\"ThisYear\",\n\t\t\"LastYear\",\n\t}\n}", "func LoadPeriods(api *eos.API, includePast, includeFuture bool) []Period {\n\n\tvar periods []Period\n\tvar periodRequest eos.GetTableRowsRequest\n\tperiodRequest.Code = \"dao.hypha\"\n\tperiodRequest.Scope = \"dao.hypha\"\n\tperiodRequest.Table = \"periods\"\n\tperiodRequest.Limit = 1000\n\tperiodRequest.JSON = true\n\n\tperiodResponse, err := api.GetTableRows(context.Background(), periodRequest)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tperiodResponse.JSONToStructs(&periods)\n\n\tvar returnPeriods []Period\n\tcurrentPeriod, err := CurrentPeriod(&periods)\n\tif (includePast || includeFuture) && err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor _, period := range periods {\n\t\tif includePast || includeFuture {\n\t\t\tif includePast && period.PeriodID <= uint64(currentPeriod) {\n\t\t\t\treturnPeriods = append(returnPeriods, period)\n\t\t\t} else if includeFuture && period.PeriodID >= uint64(currentPeriod) {\n\t\t\t\treturnPeriods = append(returnPeriods, period)\n\t\t\t}\n\t\t}\n\t}\n\treturn returnPeriods\n}", "func NewPeriodicVestingAccountRaw(bva *BaseVestingAccount, startTime int64, periods Periods) *PeriodicVestingAccount {\n\treturn &PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n}", "func vestingDataToEvents(data cli.VestingData) ([]event, error) {\n\tstartTime := time.Unix(data.StartTime, 0)\n\tevents := []event{}\n\tlastTime := startTime\n\tfor _, p := range data.Periods {\n\t\tcoins, err := sdk.ParseCoinsNormalized(p.Coins)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnewTime := lastTime.Add(time.Duration(p.Length) * time.Second)\n\t\te := event{\n\t\t\tTime: newTime,\n\t\t\tCoins: coins,\n\t\t}\n\t\tevents = append(events, e)\n\t\tlastTime = newTime\n\t}\n\treturn events, nil\n}", "func GetTotalVestingPeriodLength(periods vestingtypes.Periods) int64 {\n\tlength := int64(0)\n\tfor _, period := range periods {\n\t\tlength += period.Length\n\t}\n\treturn length\n}", "func (o *GetOutagesParams) WithPeriod(period *float64) *GetOutagesParams {\n\to.SetPeriod(period)\n\treturn o\n}", "func GetTotalVestingPeriodLength(periods vesting.Periods) int64 {\n\tlength := int64(0)\n\tfor _, period := range periods {\n\t\tlength += period.Length\n\t}\n\treturn length\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func monthlyVestTimes(startTime time.Time, months int, timeOfDay time.Time) ([]time.Time, error) {\n\tif months < 1 {\n\t\treturn nil, fmt.Errorf(\"must have at least one vesting period\")\n\t}\n\tlocation := startTime.Location()\n\thour := timeOfDay.Hour()\n\tminute := timeOfDay.Minute()\n\tsecond := timeOfDay.Second()\n\ttimes := make([]time.Time, months)\n\tfor i := 1; i <= months; i++ {\n\t\ttm := startTime.AddDate(0, i, 0)\n\t\tif tm.Day() != startTime.Day() {\n\t\t\t// The starting day-of-month cannot fit in this month,\n\t\t\t// and we've wrapped to the next month. Back up to the\n\t\t\t// end of the previous month.\n\t\t\ttm = tm.AddDate(0, 0, -tm.Day())\n\t\t}\n\t\ttimes[i-1] = time.Date(tm.Year(), tm.Month(), tm.Day(), hour, minute, second, 0, location)\n\t}\n\t// Integrity check: dates must be sequential and 26-33 days apart.\n\tlastTime := startTime\n\tfor _, tm := range times {\n\t\tduration := tm.Sub(lastTime)\n\t\tif duration < 26*24*time.Hour {\n\t\t\treturn nil, fmt.Errorf(\"vesting dates too close: %v and %v\", lastTime, tm)\n\t\t}\n\t\tif duration > 33*24*time.Hour {\n\t\t\treturn nil, fmt.Errorf(\"vesting dates too distant: %v and %v\", lastTime, tm)\n\t\t}\n\t\tlastTime = tm\n\t}\n\treturn times, nil\n}", "func (thisCalendar *Calendar) GetEventsByPeriod(start string, end string) ([]*Event, error) {\n\tvar startTime, endTime *entities.EventTime\n\tvar err error\n\n\tif start != \"\" {\n\t\tstartTime, err = ConvertToCalendarEventTime(start)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif end != \"\" {\n\t\tendTime, err = ConvertToCalendarEventTime(end)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tcalendarEvents, err := thisCalendar.storage.GetEventsByPeriod(startTime, endTime)\n\tif len(calendarEvents) == 0 {\n\t\treturn nil, err\n\t}\n\tvar events []*Event\n\tfor _, calendarEvent := range calendarEvents {\n\t\tevents = append(events, ConvertFromCalendarEvent(calendarEvent))\n\t}\n\treturn events, nil\n}", "func (h *Periods) Index(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\n\tclaims, err := auth.ClaimsFromContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t} \n\n\tfields := []datatable.DisplayField{\n\t\t{Field: \"id\", Title: \"ID\", Visible: false, Searchable: true, Orderable: true, Filterable: false},\n\t\t{Field: \"period\", Title: \"Period\", Visible: true, Orderable: true, },\n\t\t{Field: \"start_hour\", Title: \"Start Hour\", Visible: true, Orderable: true, },\n\t\t{Field: \"start_minute\", Title: \"Start Minute\", Visible: true, Orderable: true, },\n\t\t{Field: \"end_hour\", Title: \"End Hour\", Visible: true, Orderable: true, },\n\t\t{Field: \"end_minute\", Title: \"End Minute\", Visible: true, Orderable: true, },\n\t}\n\n\tmapFunc := func(q *period.Period, cols []datatable.DisplayField) (resp []datatable.ColumnValue, err error) {\n\t\tfor i := 0; i < len(cols); i++ {\n\t\t\tcol := cols[i]\n\t\t\tvar v datatable.ColumnValue\n\t\t\tswitch col.Field {\n\t\t\tcase \"id\":\n\t\t\t\tv.Value = fmt.Sprintf(\"%s\", q.ID)\n\t\t\tcase \"period\":\n\t\t\t\tv.Value = q.String()\n\t\t\t\tv.Formatted = fmt.Sprintf(\"<a href='%s'>%s</a>\", urlPeriodsView(q.ID), v.Value)\n\t\t\tcase \"start_hour\":\n\t\t\t\tv.Value = fmt.Sprintf(\"%d\", q.StartHour)\n\t\t\t\tv.Formatted = v.Value\n\t\t\tcase \"start_minute\":\n\t\t\t\tv.Value = fmt.Sprintf(\"%20d\", q.StartMinute)\n\t\t\t\tv.Formatted = v.Value\n\t\t\tcase \"end_hour\":\n\t\t\t\tv.Value = fmt.Sprintf(\"%d\", q.EndHour)\n\t\t\t\tv.Formatted = v.Value\n\t\t\tcase \"end_minute\":\n\t\t\t\tv.Value = fmt.Sprintf(\"%20d\", q.EndMinute)\n\t\t\t\tv.Formatted = v.Value\n\t\t\tdefault:\n\t\t\t\treturn resp, errors.Errorf(\"Failed to map value for %s.\", col.Field)\n\t\t\t}\n\t\t\tresp = append(resp, v)\n\t\t}\n\n\t\treturn resp, nil\n\t}\n\n\tloadFunc := func(ctx context.Context, sorting string, fields []datatable.DisplayField) (resp [][]datatable.ColumnValue, err error) {\n\t\tres, err := h.Repo.Find(ctx, claims, period.FindRequest{\n\t\t\tOrder: strings.Split(sorting, \",\"),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn resp, err\n\t\t}\n\n\t\tfor _, a := range res {\n\t\t\tl, err := mapFunc(a, fields)\n\t\t\tif err != nil {\n\t\t\t\treturn resp, errors.Wrapf(err, \"Failed to map checklist for display.\")\n\t\t\t}\n\n\t\t\tresp = append(resp, l)\n\t\t}\n\n\t\treturn resp, nil\n\t}\n\n\tdt, err := datatable.New(ctx, w, r, h.Redis, fields, loadFunc)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif dt.HasCache() {\n\t\treturn nil\n\t}\n\n\tif ok, err := dt.Render(); ok {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\tdata := map[string]interface{}{\n\t\t\"datatable\": dt.Response(),\n\t\t\"urlPeriodsCreate\": urlPeriodsCreate(),\n\t\t\"urlPeriodsIndex\": urlPeriodsIndex(),\n\t}\n\n\treturn h.Renderer.Render(ctx, w, r, TmplLayoutBase, \"admin-periods-index.gohtml\", web.MIMETextHTMLCharsetUTF8, http.StatusOK, data)\n}", "func GetTeamsByVID(v int64) ([]TeamID, error) {\n\tvar teams []TeamID\n\n\trow, err := db.Query(\"SELECT teamID FROM team WHERE vteam = ?\", v)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn teams, err\n\t}\n\tdefer row.Close()\n\n\tfor row.Next() {\n\t\tvar teamID TeamID\n\t\terr = row.Scan(&teamID)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tcontinue\n\t\t}\n\t\tteams = append(teams, teamID)\n\t}\n\treturn teams, nil\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func NewPeriod(amount sdk.Coins, length int64) vestingtypes.Period {\n\treturn vestingtypes.Period{Amount: amount, Length: length}\n}", "func NewSLAGetExclusionPeriodsParams() *SLAGetExclusionPeriodsParams {\n\tvar ()\n\treturn &SLAGetExclusionPeriodsParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (o MrScalarTerminationPolicyStatementOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v MrScalarTerminationPolicyStatement) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func (v *visitor) GetPolicies() []*rbac.Policy {\n\tif v.ctx.IsSysAdmin() {\n\t\treturn GetAllPolicies(v.namespace)\n\t}\n\n\tif v.namespace.IsPublic() {\n\t\treturn PoliciesForPublicProject(v.namespace)\n\t}\n\n\treturn nil\n}", "func (v *visitor) GetPolicies() []*rbac.Policy {\n\tif v.ctx.IsSysAdmin() {\n\t\treturn GetAllPolicies(v.namespace)\n\t}\n\n\tif v.namespace.IsPublic() {\n\t\treturn PoliciesForPublicProject(v.namespace)\n\t}\n\n\treturn nil\n}", "func (_Vault *VaultSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func DefaultListPeriod(ctx context.Context, db *gorm.DB) ([]*Period, error) {\n\tin := Period{}\n\tormObj, err := in.ToORM(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif hook, ok := interface{}(&ormObj).(PeriodORMWithBeforeListApplyQuery); ok {\n\t\tif db, err = hook.BeforeListApplyQuery(ctx, db); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tdb, err = gorm1.ApplyCollectionOperators(ctx, db, &PeriodORM{}, &Period{}, nil, nil, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif hook, ok := interface{}(&ormObj).(PeriodORMWithBeforeListFind); ok {\n\t\tif db, err = hook.BeforeListFind(ctx, db); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tdb = db.Where(&ormObj)\n\tdb = db.Order(\"id\")\n\tormResponse := []PeriodORM{}\n\tif err := db.Find(&ormResponse).Error; err != nil {\n\t\treturn nil, err\n\t}\n\tif hook, ok := interface{}(&ormObj).(PeriodORMWithAfterListFind); ok {\n\t\tif err = hook.AfterListFind(ctx, db, &ormResponse); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tpbResponse := []*Period{}\n\tfor _, responseEntry := range ormResponse {\n\t\ttemp, err := responseEntry.ToPB(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpbResponse = append(pbResponse, &temp)\n\t}\n\treturn pbResponse, nil\n}", "func (c *JobConfig) AllPeriodics() []Periodic {\n\tlistPeriodic := func(ps []Periodic) []Periodic {\n\t\tvar res []Periodic\n\t\tres = append(res, ps...)\n\t\treturn res\n\t}\n\n\treturn listPeriodic(c.Periodics)\n}", "func (c Cart) GetVoucherSavings() domain.Price {\n\tprice := domain.Price{}\n\tvar err error\n\n\tfor _, item := range c.Totalitems {\n\t\tif item.Type == TotalsTypeVoucher {\n\t\t\tprice, err = price.Add(item.Price)\n\t\t\tif err != nil {\n\t\t\t\treturn price\n\t\t\t}\n\t\t}\n\t}\n\n\tif price.IsNegative() {\n\t\treturn domain.Price{}\n\t}\n\n\treturn price\n}", "func (o ElastigroupScalingDownPolicyOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingDownPolicy) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func (o UsagePlanQuotaSettingsOutput) Period() pulumi.StringOutput {\n\treturn o.ApplyT(func(v UsagePlanQuotaSettings) string { return v.Period }).(pulumi.StringOutput)\n}", "func PeriodsDynamic(first map[types.Category]types.Money, second map[types.Category]types.Money) map[types.Category]types.Money {\n\tresult := map[types.Category]types.Money{}\n\tfor k := range second {\n\t\tif _, ok := first[k]; ok {\n\t\t\tresult[k] = second[k] - first[k]\n\t\t} else {\n\t\t\tresult[k] = second[k]\n\t\t}\n\t}\n\tfor k := range first {\n\t\tif _, ok := second[k]; !ok {\n\t\t\tresult[k] = -first[k]\n\t\t}\n\t}\n\treturn result\n}", "func (w *rpcWallet) VotingPreferences(ctx context.Context) ([]*walletjson.VoteChoice, []*asset.TBTreasurySpend, []*walletjson.TreasuryPolicyResult, error) {\n\t// Get consensus vote choices.\n\tchoices, err := w.rpcClient.GetVoteChoices(ctx)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"unable to get vote choices: %v\", err)\n\t}\n\tvoteChoices := make([]*walletjson.VoteChoice, len(choices.Choices))\n\tfor i, v := range choices.Choices {\n\t\tvc := v\n\t\tvoteChoices[i] = &vc\n\t}\n\t// Get tspend voting policy.\n\tconst tSpendPolicyMethod = \"tspendpolicy\"\n\tvar tSpendRes []walletjson.TSpendPolicyResult\n\terr = w.rpcClientRawRequest(ctx, tSpendPolicyMethod, nil, &tSpendRes)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"unable to get treasury spend policy: %v\", err)\n\t}\n\ttSpendPolicy := make([]*asset.TBTreasurySpend, len(tSpendRes))\n\tfor i, tp := range tSpendRes {\n\t\t// TODO: Find a way to get the tspend total value? Probably only\n\t\t// possible with a full node and txindex.\n\t\ttSpendPolicy[i] = &asset.TBTreasurySpend{\n\t\t\tHash: tp.Hash,\n\t\t\tCurrentPolicy: tp.Policy,\n\t\t}\n\t}\n\t// Get treasury voting policy.\n\tconst treasuryPolicyMethod = \"treasurypolicy\"\n\tvar treasuryRes []walletjson.TreasuryPolicyResult\n\terr = w.rpcClientRawRequest(ctx, treasuryPolicyMethod, nil, &treasuryRes)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"unable to get treasury policy: %v\", err)\n\t}\n\ttreasuryPolicy := make([]*walletjson.TreasuryPolicyResult, len(treasuryRes))\n\tfor i, v := range treasuryRes {\n\t\ttp := v\n\t\ttreasuryPolicy[i] = &tp\n\t}\n\treturn voteChoices, tSpendPolicy, treasuryPolicy, nil\n}", "func (p Period) Days() []LocalDate {\n\tvar days []LocalDate\n\tfor current := p.from; current.BeforeOrEqual(p.to); current = current.Next() {\n\t\tdays = append(days, current)\n\t}\n\treturn days\n}", "func (o *SLAGetExclusionPeriodsParams) WithContext(ctx context.Context) *SLAGetExclusionPeriodsParams {\n\to.SetContext(ctx)\n\treturn o\n}", "func (api *tenantAPI) List(ctx context.Context, opts *api.ListWatchOptions) ([]*Tenant, error) {\n\tvar objlist []*Tenant\n\tobjs, err := api.ct.List(\"Tenant\", ctx, opts)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, obj := range objs {\n\t\tswitch tp := obj.(type) {\n\t\tcase *Tenant:\n\t\t\teobj := obj.(*Tenant)\n\t\t\tobjlist = append(objlist, eobj)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Got invalid object type %v while looking for Tenant\", tp)\n\t\t}\n\t}\n\n\treturn objlist, nil\n}", "func (pva *PeriodicVestingAccount) UnmarshalJSON(bz []byte) error {\n\tvar alias vestingAccountJSON\n\tif err := legacy.Cdc.UnmarshalJSON(bz, &alias); err != nil {\n\t\treturn err\n\t}\n\n\tpva.BaseVestingAccount = &BaseVestingAccount{\n\t\tBaseAccount: NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence),\n\t\tOriginalVesting: alias.OriginalVesting,\n\t\tDelegatedFree: alias.DelegatedFree,\n\t\tDelegatedVesting: alias.DelegatedVesting,\n\t\tEndTime: alias.EndTime,\n\t}\n\tpva.StartTime = alias.StartTime\n\tpva.VestingPeriods = alias.VestingPeriods\n\n\treturn nil\n}", "func NewSLAGetExclusionPeriodsParamsWithTimeout(timeout time.Duration) *SLAGetExclusionPeriodsParams {\n\tvar ()\n\treturn &SLAGetExclusionPeriodsParams{\n\n\t\ttimeout: timeout,\n\t}\n}", "func (g Graph) GetDrives(w http.ResponseWriter, r *http.Request) {\n\tg.getDrives(w, r, false)\n}", "func (v PingSlotPeriod) MarshalJSON() ([]byte, error) {\n\treturn marshalJSONEnum(PingSlotPeriod_name, int32(v))\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (m *MongoDB) GetEnabledVehicles() ([]model.Vehicle, error) {\n\tvar vehicles []model.Vehicle\n\terr := m.vehicles.Find(bson.M{\"enabled\": true}).All(&vehicles)\n\treturn vehicles, err\n}", "func (h *stubDriveHandler) GetDrives() []models.Drive {\n\treturn h.drives\n}", "func (builder *AuthBankGenesisBuilder) WithSimplePeriodicVestingAccount(address sdk.AccAddress, balance sdk.Coins, periods vestingtypes.Periods, firstPeriodStartTimestamp int64) *AuthBankGenesisBuilder {\n\tvestingAccount := newPeriodicVestingAccount(address, periods, firstPeriodStartTimestamp)\n\n\treturn builder.\n\t\tWithAccounts(vestingAccount).\n\t\tWithBalances(banktypes.Balance{Address: address.String(), Coins: balance})\n}", "func (o ElastigroupIntegrationEcsAutoscaleDownOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupIntegrationEcsAutoscaleDown) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func GetTimings(c *gin.Context) {\n\t// parse input\n\tvar input models.TimingSearchInput\n\tif err := c.ShouldBindQuery(&input); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Check input fields\"})\n\t\tfmt.Println(\"Error in getting date and venues. \" + err.Error() + \"\\n\")\n\t\treturn\n\t}\n\n\toperatingHours, err := GetOperatingHours(DB, input)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Error in querying for unavailable timings.\"})\n\t\tfmt.Println(\"Check tempQuery \" + err.Error() + \"\\n\")\n\t}\n\n\tstatusIDArr, err := GetAllBookingStatusCodes(DB)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Error in querying for booking statusID.\"})\n\t\tfmt.Println(\"Check bookingstatus query \" + err.Error() + \"\\n\")\n\t}\n\n\tvenue, err := GetVenueIDAndMaxCapacity(DB, input)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Error in querying for venueID.\"})\n\t\tfmt.Println(\"Check venueQuery. \" + err.Error() + \"\\n\")\n\t}\n\n\ttimingWithPax, err := GetBookingsOfDay(DB, input, venue, statusIDArr)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Error in querying for unavailable timings.\"})\n\t\tfmt.Println(\"Check timingsQuery \" + err.Error() + \"\\n\")\n\t}\n\n\ttimeslots := MakeTimeslotArr(operatingHours, timingWithPax, input, venue)\n\n\tc.JSON(http.StatusOK, gin.H{\"data\": timeslots})\n\tfmt.Println(\"Return successful!\")\n}", "func (b *Poloniex) GetVolumes() (vc VolumeCollection, err error) {\n\tr, err := b.client.do(\"GET\", \"public?command=return24hVolume\", nil, false)\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = json.Unmarshal(r, &vc); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func (db *DB) GetClassesPeriods() (map[string]string, error) {\n\tm := map[string]string{}\n\n\tconn, err := redishelper.GetRedisConn(db.RedisServer, db.RedisPassword)\n\tif err != nil {\n\t\treturn map[string]string{}, err\n\t}\n\tdefer conn.Close()\n\n\tk := \"ming:campuses\"\n\tcampuses, err := redis.Strings(conn.Do(\"ZRANGE\", k, 0, -1))\n\tif err != nil {\n\t\treturn map[string]string{}, err\n\t}\n\n\tfor _, campus := range campuses {\n\t\tk = fmt.Sprintf(\"ming:%v:categories\", campus)\n\t\tcategories, err := redis.Strings(conn.Do(\"ZRANGE\", k, 0, -1))\n\t\tif err != nil {\n\t\t\treturn map[string]string{}, err\n\t\t}\n\n\t\tfor _, category := range categories {\n\t\t\tk = fmt.Sprintf(\"ming:%v:%v:classes\", campus, category)\n\t\t\tclasses, err := redis.Strings(conn.Do(\"ZRANGE\", k, 0, -1))\n\t\t\tif err != nil {\n\t\t\t\treturn map[string]string{}, err\n\t\t\t}\n\n\t\t\tfor _, class := range classes {\n\t\t\t\tperiod, err := db.GetClassPeriod(campus, category, class)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn map[string]string{}, err\n\t\t\t\t}\n\n\t\t\t\tk := fmt.Sprintf(\"%v:%v:%v\", campus, category, class)\n\t\t\t\tm[k] = period\n\t\t\t}\n\n\t\t}\n\t}\n\treturn m, nil\n}", "func (o ElastigroupIntegrationEcsAutoscaleDownPtrOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ElastigroupIntegrationEcsAutoscaleDown) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.EvaluationPeriods\n\t}).(pulumi.IntPtrOutput)\n}", "func (k Keeper) DeleteValidatorSlashingPeriods(ctx sdk.Context) {\n\tstore := ctx.KVStore(k.storeKey)\n\titer := sdk.KVStorePrefixIterator(store, ValidatorSlashingPeriodKey)\n\tfor ; iter.Valid(); iter.Next() {\n\t\tstore.Delete(iter.Key())\n\t}\n\titer.Close()\n}", "func (_Vault *VaultCallerSession) GetDecimals(token common.Address) (uint8, error) {\n\treturn _Vault.Contract.GetDecimals(&_Vault.CallOpts, token)\n}", "func (r Virtual_PlacementGroup) GetGuests() (resp []datatypes.Virtual_Guest, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_PlacementGroup\", \"getGuests\", nil, &r.Options, &resp)\n\treturn\n}", "func (o *GetOutagesParams) SetPeriod(period *float64) {\n\to.Period = period\n}", "func (o ElastigroupScalingUpPolicyOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingUpPolicy) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func (o ElastigroupIntegrationKubernetesAutoscaleDownOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupIntegrationKubernetesAutoscaleDown) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (s *intervalSegment) GetSegments(timeRange models.TimeRange) []Segment {\n\tvar segments []Segment\n\tcalc := interval.GetCalculator(s.intervalType)\n\tstart := calc.CalSegmentTime(timeRange.Start)\n\tend := calc.CalSegmentTime(timeRange.End)\n\ts.segments.Range(func(k, v interface{}) bool {\n\t\tsegment, ok := v.(Segment)\n\t\tif ok {\n\t\t\tbaseTime := segment.BaseTime()\n\t\t\tif start >= baseTime && end <= baseTime {\n\t\t\t\tsegments = append(segments, segment)\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\treturn segments\n}", "func (o MrScalarTaskScalingDownPolicyOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingDownPolicy) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func AggregationPeriod_Values() []string {\n\treturn []string{\n\t\tAggregationPeriodPt5m,\n\t\tAggregationPeriodPt1h,\n\t\tAggregationPeriodP1d,\n\t}\n}", "func (m *GroupPolicyDefinition) GetPresentations()([]GroupPolicyPresentationable) {\n val, err := m.GetBackingStore().Get(\"presentations\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]GroupPolicyPresentationable)\n }\n return nil\n}", "func (o InstanceOutput) Period() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.IntOutput { return v.Period }).(pulumi.IntOutput)\n}", "func (o ElastigroupIntegrationNomadAutoscaleDownOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupIntegrationNomadAutoscaleDown) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func (api *tenantAPI) ApisrvList(ctx context.Context, opts *api.ListWatchOptions) ([]*cluster.Tenant, error) {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn apicl.ClusterV1().Tenant().List(context.Background(), opts)\n\t}\n\n\t// List from local cache\n\tctkitObjs, err := api.List(ctx, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar ret []*cluster.Tenant\n\tfor _, obj := range ctkitObjs {\n\t\tret = append(ret, &obj.Tenant)\n\t}\n\treturn ret, nil\n}", "func (o ElastigroupIntegrationKubernetesAutoscaleDownPtrOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ElastigroupIntegrationKubernetesAutoscaleDown) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.EvaluationPeriods\n\t}).(pulumi.IntPtrOutput)\n}", "func NewValidatorVestingAccountRaw(bva *vestingtypes.BaseVestingAccount,\n\tstartTime int64, periods vestingtypes.Periods, validatorAddress sdk.ConsAddress, returnAddress sdk.AccAddress, signingThreshold int64) *ValidatorVestingAccount {\n\n\tpva := &vestingtypes.PeriodicVestingAccount{\n\t\tBaseVestingAccount: bva,\n\t\tStartTime: startTime,\n\t\tVestingPeriods: periods,\n\t}\n\tvar vestingPeriodProgress []VestingProgress\n\tfor i := 0; i < len(periods); i++ {\n\t\tvestingPeriodProgress = append(vestingPeriodProgress, VestingProgress{false, false})\n\t}\n\n\treturn &ValidatorVestingAccount{\n\t\tPeriodicVestingAccount: pva,\n\t\tValidatorAddress: validatorAddress,\n\t\tReturnAddress: returnAddress,\n\t\tSigningThreshold: signingThreshold,\n\t\tCurrentPeriodProgress: CurrentPeriodProgress{0, 0},\n\t\tVestingPeriodProgress: vestingPeriodProgress,\n\t\tDebtAfterFailedVesting: sdk.NewCoins(),\n\t}\n}", "func (h *Hosts) Period() time.Duration {\n\tif h.Stopped() {\n\t\treturn -1\n\t}\n\n\th.mux.RLock()\n\tdefer h.mux.RUnlock()\n\n\treturn h.period\n}", "func (vva ValidatorVestingAccount) Validate() error {\n\tif vva.SigningThreshold > 100 || vva.SigningThreshold < 0 {\n\t\treturn errors.New(\"signing threshold must be between 0 and 100\")\n\t}\n\tif vva.ReturnAddress.Equals(vva.Address) {\n\t\treturn errors.New(\"return address cannot be the same as the account address\")\n\t}\n\treturn vva.PeriodicVestingAccount.Validate()\n}", "func (msg MsgCreatePeriodicVestingAccount) GetSigners() []sdk.AccAddress {\n\tfrom, err := sdk.AccAddressFromBech32(msg.FromAddress)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn []sdk.AccAddress{from}\n}", "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (di *RealDataitem) GetKVPs() []DataKVP {\n\treturn di.kvps\n}", "func (o *User) GetDrives() []MicrosoftGraphDrive {\n\tif o == nil || o.Drives == nil {\n\t\tvar ret []MicrosoftGraphDrive\n\t\treturn ret\n\t}\n\treturn *o.Drives\n}", "func (o ElastigroupScalingTargetPolicyOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingTargetPolicy) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func (o ElastigroupIntegrationNomadAutoscaleDownPtrOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ElastigroupIntegrationNomadAutoscaleDown) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.EvaluationPeriods\n\t}).(pulumi.IntPtrOutput)\n}", "func PeriodUpGET(w http.ResponseWriter, r *http.Request) {\n\tsess := model.Instance(r)\n var period model.Periodo\n\tvar params httprouter.Params\n\tparams = context.Get(r, \"params\").(httprouter.Params)\n\tid,_ := atoi32(params.ByName(\"id\"))\n period.Id = id\n path := \"/period/list\"\n err := (&period).PeriodById()\n\tif err != nil { // Si no existe el periodo\n log.Println(err)\n sess.AddFlash(view.Flash{\"Es raro. No tenemos periodo.\", view.FlashError})\n sess.Save(r, w)\n http.Redirect(w, r, path, http.StatusFound)\n return\n\t}\n\tv := view.New(r)\n\tv.Name = \"periodo/periodupdate\"\n\tv.Vars[\"token\"] = csrfbanana.Token(w, r, sess)\n v.Vars[\"Period\"] = period\n//\tview.Repopulate([]string{\"name\"}, r.Form, v.Vars)\n v.Render(w)\n }", "func (_DetailedTestToken *DetailedTestTokenSession) Decimals() (uint8, error) {\n\treturn _DetailedTestToken.Contract.Decimals(&_DetailedTestToken.CallOpts)\n}", "func (rs *StatsPeriodResultSet) All() ([]*StatsPeriod, error) {\n\tvar result []*StatsPeriod\n\tfor rs.Next() {\n\t\trecord, err := rs.Get()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult = append(result, record)\n\t}\n\treturn result, nil\n}", "func DescribePVs() {\n\tlist, err := Get()\n\tif err != nil {\n\t\tlog.Printf(\"Unable to get pvs: %s\", err)\n\t}\n\tif list != nil {\n\t\tfor _, pv := range list.PersistentVolumes {\n\t\t\terr := pv.Describe()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Unable to describe pv %s: %s\", pv.Metadata.Name, err)\n\t\t\t}\n\t\t}\n\t}\n}", "func (v PingSlotPeriod) MarshalJSONPB(m *jsonpb.Marshaler) ([]byte, error) {\n\treturn marshalJSONPBEnum(m, PingSlotPeriod_name, int32(v))\n}", "func (o *SLAGetExclusionPeriodsParams) WithTimeout(timeout time.Duration) *SLAGetExclusionPeriodsParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func (o MrScalarTaskScalingUpPolicyOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingUpPolicy) *int { return v.EvaluationPeriods }).(pulumi.IntPtrOutput)\n}", "func (o ReservedInstanceOutput) Period() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ReservedInstance) pulumi.IntPtrOutput { return v.Period }).(pulumi.IntPtrOutput)\n}", "func (_Bep20 *Bep20Session) Decimals() (uint8, error) {\n\treturn _Bep20.Contract.Decimals(&_Bep20.CallOpts)\n}", "func (_TTFT20 *TTFT20Session) Decimals() (uint8, error) {\n\treturn _TTFT20.Contract.Decimals(&_TTFT20.CallOpts)\n}", "func (o ResponsePlanIntegrationOutput) Pagerduties() ResponsePlanIntegrationPagerdutyArrayOutput {\n\treturn o.ApplyT(func(v ResponsePlanIntegration) []ResponsePlanIntegrationPagerduty { return v.Pagerduties }).(ResponsePlanIntegrationPagerdutyArrayOutput)\n}", "func (o *User) GetDrives() []Drive {\n\tif o == nil || o.Drives == nil {\n\t\tvar ret []Drive\n\t\treturn ret\n\t}\n\treturn o.Drives\n}", "func (db *DB) GetAllPeriodsOfCategory(category string) (map[string][]string, error) {\n\tconn, err := redishelper.GetRedisConn(db.RedisServer, db.RedisPassword)\n\tif err != nil {\n\t\treturn map[string][]string{}, err\n\t}\n\tdefer conn.Close()\n\n\tk := fmt.Sprintf(\"ming:%v:campuses\", category)\n\tcampuses, err := redis.Strings(conn.Do(\"ZRANGE\", k, 0, -1))\n\tif err != nil {\n\t\treturn map[string][]string{}, err\n\t}\n\n\tperiodsMap := map[string][]string{}\n\tfor _, campus := range campuses {\n\t\tk = fmt.Sprintf(\"ming:%v:%v:periods\", campus, category)\n\t\tperiods, err := redis.Strings(conn.Do(\"ZRANGE\", k, 0, -1))\n\t\tif err != nil {\n\t\t\treturn map[string][]string{}, err\n\t\t}\n\n\t\tif len(periods) > 0 {\n\t\t\tperiodsMap[campus] = append(periodsMap[campus], periods...)\n\t\t}\n\t}\n\n\treturn periodsMap, nil\n}", "func (env *Env) GetPayments(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"GET payments\")\n\n\ttxs, err := env.db.GetAllTX()\n\n\tif err != nil {\n\t\tlog.Printf(\"Error retrieving payments: %v\\n\", err)\n\t\trender.Status(r, http.StatusNotFound)\n\t\treturn\n\t}\n\trender.JSON(w, r, txs)\n}", "func GetDeploymentVolumes(item interface{}) []corev1.Volume {\n\treturn item.(appsv1.Deployment).Spec.Template.Spec.Volumes\n}", "func (test *Test) GetDomains(projectName string) ([]models.Domain, error) {\n\treturn tests.NormalDomains, nil\n}", "func (o ElastigroupIntegrationDockerSwarmAutoscaleDownPtrOutput) EvaluationPeriods() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ElastigroupIntegrationDockerSwarmAutoscaleDown) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.EvaluationPeriods\n\t}).(pulumi.IntPtrOutput)\n}", "func (me *XsdGoPkgHasElems_PeriodsequenceTxsdGeneralLedgerEntriesSequenceJournalSequenceTransactionTransactionsequenceTxsdGeneralLedgerEntriesSequenceJournalJournalsequenceTxsdGeneralLedgerEntriesGeneralLedgerEntriesschema_Period_TSAFPTAccountingPeriod_) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElems_PeriodsequenceTxsdGeneralLedgerEntriesSequenceJournalSequenceTransactionTransactionsequenceTxsdGeneralLedgerEntriesSequenceJournalJournalsequenceTxsdGeneralLedgerEntriesGeneralLedgerEntriesschema_Period_TSAFPTAccountingPeriod_; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (o GetResponsePlanIntegrationOutput) Pagerduties() GetResponsePlanIntegrationPagerdutyArrayOutput {\n\treturn o.ApplyT(func(v GetResponsePlanIntegration) []GetResponsePlanIntegrationPagerduty { return v.Pagerduties }).(GetResponsePlanIntegrationPagerdutyArrayOutput)\n}", "func (o InstanceOutput) ServiceAccountScopes() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringArrayOutput { return v.ServiceAccountScopes }).(pulumi.StringArrayOutput)\n}", "func getVolunteers(c *gin.Context) {\n\tvar vols []Volunteer\n\t//Read volunteers from database\n\tif err := db.Find(&vols).Error; err != nil {\n\t\tcreateNotFoundResponse(c)\n\t\treturn\n\t}\n\n\t//Authorization if user is reporter\n\tif !reporterAuth(c) {\n\t\treturn\n\t}\n\tc.JSON(200, vols)\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (d *portworx) GetPoolDrives(n *node.Node) (map[string][]string, error) {\n\tsystemOpts := node.SystemctlOpts{\n\t\tConnectionOpts: node.ConnectionOpts{\n\t\t\tTimeout: startDriverTimeout,\n\t\t\tTimeBeforeRetry: defaultRetryInterval,\n\t\t},\n\t\tAction: \"start\",\n\t}\n\tpoolDrives := make(map[string][]string, 0)\n\tlog.Infof(\"Getting available block drives on node [%s]\", n.Name)\n\tblockDrives, err := d.nodeDriver.GetBlockDrives(*n, systemOpts)\n\n\tif err != nil {\n\t\treturn poolDrives, err\n\t}\n\tfor _, v := range blockDrives {\n\t\tlabelsMap := v.Labels\n\t\tif pm, ok := labelsMap[\"pxpool\"]; ok {\n\t\t\tpoolDrives[pm] = append(poolDrives[pm], v.Path)\n\t\t}\n\t}\n\treturn poolDrives, nil\n}" ]
[ "0.82607967", "0.53933996", "0.51751536", "0.5136177", "0.5023484", "0.49357113", "0.4917464", "0.47208306", "0.47143596", "0.45715773", "0.45275274", "0.45155838", "0.44273278", "0.44169536", "0.44071308", "0.43515027", "0.42970163", "0.41897523", "0.41696903", "0.41315487", "0.40534994", "0.4024805", "0.3987746", "0.39256877", "0.39178488", "0.39072612", "0.39072612", "0.38997084", "0.38981694", "0.38896894", "0.38864052", "0.3884726", "0.38830853", "0.3860149", "0.38553673", "0.38529113", "0.38482285", "0.38334394", "0.38258576", "0.38249928", "0.3821619", "0.3813515", "0.38066056", "0.38053465", "0.37828732", "0.37766388", "0.37707412", "0.37658718", "0.3765389", "0.37535924", "0.37509766", "0.3742345", "0.37401107", "0.37369865", "0.37331843", "0.37278366", "0.3720804", "0.37195626", "0.37173465", "0.37105906", "0.37092373", "0.37053418", "0.36950052", "0.36942267", "0.36917034", "0.36850712", "0.3683275", "0.36812162", "0.36787438", "0.36743674", "0.36697808", "0.3665709", "0.36652938", "0.3657308", "0.3655877", "0.36511636", "0.3648951", "0.3635065", "0.36324564", "0.3628458", "0.36277944", "0.36268395", "0.362216", "0.3618688", "0.3618097", "0.36128396", "0.361273", "0.3604821", "0.3601217", "0.35980293", "0.35937566", "0.3593497", "0.35911334", "0.35883754", "0.35852683", "0.35820916", "0.35753784", "0.3555677", "0.35535908", "0.35534784" ]
0.8009713
1
coinEq returns whether two Coins are equal. The IsEqual() method can panic.
func coinEq(a, b sdk.Coins) bool { return a.IsAllLTE(b) && b.IsAllLTE(a) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (coin Coin) IsEqual(other Coin) bool {\n\treturn coin.Amount.Equal(other.Amount)\n}", "func (v Coin) Equal(o Coin) bool {\n\treturn v.Amount.Equal(o.Amount) &&\n\t\tv.CoinIdentifier.Equal(o.CoinIdentifier)\n}", "func (n *Uint256) Eq(n2 *Uint256) bool {\n\treturn n.n[0] == n2.n[0] && n.n[1] == n2.n[1] && n.n[2] == n2.n[2] &&\n\t\tn.n[3] == n2.n[3]\n}", "func (v Currency) Equal(o Currency) bool {\n\treturn v.Decimals == o.Decimals &&\n\t\tstring(v.Metadata) == string(o.Metadata) &&\n\t\tv.Symbol == o.Symbol\n}", "func (v CoinChange) Equal(o CoinChange) bool {\n\treturn v.CoinAction == o.CoinAction &&\n\t\tv.CoinIdentifier.Equal(o.CoinIdentifier)\n}", "func (x *Money) Equal(y *Money) bool {\n\tif x.Currency != y.Currency {\n\t\treturn false\n\t}\n\treturn x.Amount.Equal(y.Amount)\n}", "func (x *Secp256k1N) Eq(y *Secp256k1N) bool {\n\t// TODO: More efficient implementation/\n\tvar xNorm, yNorm = *x, *y\n\txNorm.Normalize()\n\tyNorm.Normalize()\n\treturn xNorm.limbs[0] == yNorm.limbs[0] &&\n\t\txNorm.limbs[1] == yNorm.limbs[1] &&\n\t\txNorm.limbs[2] == yNorm.limbs[2] &&\n\t\txNorm.limbs[3] == yNorm.limbs[3] &&\n\t\txNorm.limbs[4] == yNorm.limbs[4]\n}", "func (v AccountCoinsRequest) Equal(o AccountCoinsRequest) bool {\n\treturn v.AccountIdentifier.Equal(o.AccountIdentifier) &&\n\t\tlen(v.Currencies) == len(o.Currencies) &&\n\t\tcurrencySliceEqual(v.Currencies, o.Currencies) &&\n\t\tv.IncludeMempool == o.IncludeMempool\n}", "func (bal Balance) Equals(other Balance) bool {\r\n\treturn bal.Coins == other.Coins && bal.Hours == other.Hours\r\n}", "func (m *Money) Equals(n *Money) bool {\n\treturn m.Amount() == n.Amount() && m.Currency() == n.Currency()\n}", "func (c *Coinbase) Equals(t Transaction) bool {\n\n\tother, ok := t.(*Coinbase)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tif !bytes.Equal(c.R, other.R) {\n\t\treturn false\n\t}\n\n\tif !bytes.Equal(c.Score, other.Score) {\n\t\treturn false\n\t}\n\n\tif !bytes.Equal(c.Proof, other.Proof) {\n\t\treturn false\n\t}\n\n\tif !c.Rewards.Equals(other.Rewards) {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (c *Currency) Equals(other *Currency) bool {\n\treturn c == other ||\n\t\t(c.Decimals == other.Decimals && c.Symbol == other.Symbol && c.Name == other.Name)\n}", "func (v AccountCoinsResponse) Equal(o AccountCoinsResponse) bool {\n\treturn v.BlockIdentifier.Equal(o.BlockIdentifier) &&\n\t\tlen(v.Coins) == len(o.Coins) &&\n\t\tcoinSliceEqual(v.Coins, o.Coins) &&\n\t\tstring(v.Metadata) == string(o.Metadata)\n}", "func (m Money) Equals(other Money) bool {\n\treturn m.currency.Equals(other.currency) && m.Amount().Equals(other.Amount())\n}", "func (c1 *Certificate) Equal(c2 *Certificate) bool {\n\treturn reflect.DeepEqual(c1.Certificate, c2.Certificate)\n}", "func Eq(one, other interface{}) bool {\n\treturn reflect.DeepEqual(one, other)\n}", "func (tx *Transaction) IsCoinbase() bool {\n\treturn len(tx.Vin) == 1 && len(tx.Vin[0].Txid) == 0 && tx.Vin[0].Vout == -1\n}", "func (tx Transaction) IsCoinbase() bool {\n\treturn len(tx.Vin) == 1 && len(tx.Vin[0].Txid) == 0 && tx.Vin[0].Vout == -1\n}", "func (b Balance) Equal(b2 Balance) bool {\n\treturn b.Int != nil && b2.Int != nil && b.Int.Cmp(b2.Int) == 0\n}", "func Eq(a, b interface{}, f Func) bool {\n\treturn f(a, b) == 0\n}", "func (backend *Backend) Coin(code coinpkg.Code) (coinpkg.Coin, error) {\n\tdefer backend.coinsLock.Lock()()\n\tcoin, ok := backend.coins[code]\n\tif ok {\n\t\treturn coin, nil\n\t}\n\tdbFolder := backend.arguments.CacheDirectoryPath()\n\n\terc20Token := erc20TokenByCode(code)\n\tbtcFormatUnit := backend.config.AppConfig().Backend.BtcUnit\n\tswitch {\n\tcase code == coinpkg.CodeRBTC:\n\t\tservers := backend.defaultElectrumXServers(code)\n\t\tcoin = btc.NewCoin(coinpkg.CodeRBTC, \"Bitcoin Regtest\", \"RBTC\", coinpkg.BtcUnitDefault, &chaincfg.RegressionNetParams, dbFolder, servers, \"\", backend.socksProxy)\n\tcase code == coinpkg.CodeTBTC:\n\t\tservers := backend.defaultElectrumXServers(code)\n\t\tcoin = btc.NewCoin(coinpkg.CodeTBTC, \"Bitcoin Testnet\", \"TBTC\", btcFormatUnit, &chaincfg.TestNet3Params, dbFolder, servers,\n\t\t\t\"https://blockstream.info/testnet/tx/\", backend.socksProxy)\n\tcase code == coinpkg.CodeBTC:\n\t\tservers := backend.defaultElectrumXServers(code)\n\t\tcoin = btc.NewCoin(coinpkg.CodeBTC, \"Bitcoin\", \"BTC\", btcFormatUnit, &chaincfg.MainNetParams, dbFolder, servers,\n\t\t\t\"https://blockstream.info/tx/\", backend.socksProxy)\n\tcase code == coinpkg.CodeTLTC:\n\t\tservers := backend.defaultElectrumXServers(code)\n\t\tcoin = btc.NewCoin(coinpkg.CodeTLTC, \"Litecoin Testnet\", \"TLTC\", coinpkg.BtcUnitDefault, &ltc.TestNet4Params, dbFolder, servers,\n\t\t\t\"https://sochain.com/tx/LTCTEST/\", backend.socksProxy)\n\tcase code == coinpkg.CodeLTC:\n\t\tservers := backend.defaultElectrumXServers(code)\n\t\tcoin = btc.NewCoin(coinpkg.CodeLTC, \"Litecoin\", \"LTC\", coinpkg.BtcUnitDefault, &ltc.MainNetParams, dbFolder, servers,\n\t\t\t\"https://blockchair.com/litecoin/transaction/\", backend.socksProxy)\n\tcase code == coinpkg.CodeETH:\n\t\tetherScan := etherscan.NewEtherScan(\"https://api.etherscan.io/api\", backend.etherScanHTTPClient)\n\t\tcoin = eth.NewCoin(etherScan, code, \"Ethereum\", \"ETH\", \"ETH\", params.MainnetChainConfig,\n\t\t\t\"https://etherscan.io/tx/\",\n\t\t\tetherScan,\n\t\t\tnil)\n\tcase code == coinpkg.CodeGOETH:\n\t\tetherScan := etherscan.NewEtherScan(\"https://api-goerli.etherscan.io/api\", backend.etherScanHTTPClient)\n\t\tcoin = eth.NewCoin(etherScan, code, \"Ethereum Goerli\", \"GOETH\", \"GOETH\", params.GoerliChainConfig,\n\t\t\t\"https://goerli.etherscan.io/tx/\",\n\t\t\tetherScan,\n\t\t\tnil)\n\tcase erc20Token != nil:\n\t\tetherScan := etherscan.NewEtherScan(\"https://api.etherscan.io/api\", backend.etherScanHTTPClient)\n\t\tcoin = eth.NewCoin(etherScan, erc20Token.code, erc20Token.name, erc20Token.unit, \"ETH\", params.MainnetChainConfig,\n\t\t\t\"https://etherscan.io/tx/\",\n\t\t\tetherScan,\n\t\t\terc20Token.token,\n\t\t)\n\tdefault:\n\t\treturn nil, errp.Newf(\"unknown coin code %s\", code)\n\t}\n\tbackend.coins[code] = coin\n\tcoin.Observe(backend.Notify)\n\treturn coin, nil\n}", "func (d Decimal) Equal(d2 Decimal) bool {\n\treturn d.Cmp(d2) == 0\n}", "func (d Decimal) Equal(d2 Decimal) bool {\n\treturn d.Cmp(d2) == 0\n}", "func EqDeeply(got, expected any) bool {\n\treturn deepValueEqualOK(reflect.ValueOf(got), reflect.ValueOf(expected))\n}", "func (mm MoneyMarket) Equal(mmCompareTo MoneyMarket) bool {\n\tif mm.Denom != mmCompareTo.Denom {\n\t\treturn false\n\t}\n\tif !mm.BorrowLimit.Equal(mmCompareTo.BorrowLimit) {\n\t\treturn false\n\t}\n\tif mm.SpotMarketID != mmCompareTo.SpotMarketID {\n\t\treturn false\n\t}\n\tif !mm.ConversionFactor.Equal(mmCompareTo.ConversionFactor) {\n\t\treturn false\n\t}\n\tif !mm.InterestRateModel.Equal(mmCompareTo.InterestRateModel) {\n\t\treturn false\n\t}\n\tif !mm.ReserveFactor.Equal(mmCompareTo.ReserveFactor) {\n\t\treturn false\n\t}\n\tif !mm.AuctionSize.Equal(mmCompareTo.AuctionSize) {\n\t\treturn false\n\t}\n\tif !mm.KeeperRewardPercentage.Equal(mmCompareTo.KeeperRewardPercentage) {\n\t\treturn false\n\t}\n\treturn true\n}", "func (m *Money) Equals(tm *Money) bool {\n\tif m.currency != tm.currency {\n\t\treturn false\n\t}\n\tif m.amount != tm.amount {\n\t\treturn false\n\t}\n\treturn true\n}", "func (t *Transaction) IsCoinbase() bool {\n\treturn len(t.Vint) == 1 && len(t.Vint[0].TxHash) == 0 && t.Vint[0].Index == -1\n}", "func (txn *Transaction) IsCoinbase() bool {\n\treturn len(txn.Inputs) == 1 && len(txn.Inputs[0].ID) == 0 && txn.Inputs[0].OutIndex == -1\n}", "func (v CoinIdentifier) Equal(o CoinIdentifier) bool {\n\treturn v.Identifier == o.Identifier\n}", "func (tx *Transaction) IsCoinbase() bool {\n\treturn len(tx.Inputs) == 1 && len(tx.Inputs[0].ID) == 0 && tx.Inputs[0].Out == -1\n}", "func (tx *Transaction) IsCoinbase() bool {\n\treturn len(tx.Inputs) == 1 && len(tx.Inputs[0].ID) == 0 && tx.Inputs[0].Out == -1\n}", "func (s Balance) Equal(t Balance, opts ...Options) bool {\n\tif !equalPointers(s.Algorithm, t.Algorithm) {\n\t\treturn false\n\t}\n\n\tif s.HashExpression != t.HashExpression {\n\t\treturn false\n\t}\n\n\tif s.HdrName != t.HdrName {\n\t\treturn false\n\t}\n\n\tif s.HdrUseDomainOnly != t.HdrUseDomainOnly {\n\t\treturn false\n\t}\n\n\tif s.RandomDraws != t.RandomDraws {\n\t\treturn false\n\t}\n\n\tif s.RdpCookieName != t.RdpCookieName {\n\t\treturn false\n\t}\n\n\tif s.URIDepth != t.URIDepth {\n\t\treturn false\n\t}\n\n\tif s.URILen != t.URILen {\n\t\treturn false\n\t}\n\n\tif s.URIPathOnly != t.URIPathOnly {\n\t\treturn false\n\t}\n\n\tif s.URIWhole != t.URIWhole {\n\t\treturn false\n\t}\n\n\tif s.URLParam != t.URLParam {\n\t\treturn false\n\t}\n\n\tif s.URLParamCheckPost != t.URLParamCheckPost {\n\t\treturn false\n\t}\n\n\tif s.URLParamMaxWait != t.URLParamMaxWait {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (recv *ParamSpecUChar) Equals(other *ParamSpecUChar) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (c1 city) Equal(c2 city) bool {\n\tif c1.name != c2.name {\n\t\treturn false\n\t}\n\tif c1.population != c2.population {\n\t\treturn false\n\t}\n\tif c1.cost != c2.cost {\n\t\treturn false\n\t}\n\tif c1.climate != c2.climate {\n\t\treturn false\n\t}\n\treturn true\n}", "func (k *PrivateKey) Equal(x crypto.PrivateKey) bool {\n\txx, ok := x.(*PrivateKey)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn k.curve == xx.curve &&\n\t\tsubtle.ConstantTimeCompare(k.privateKey, xx.privateKey) == 1\n}", "func (t *Transaction) IsCoinbase() bool {\n\t// Check to see there is just 1 input and that it is not linked to any other transactions\n\treturn len(t.Inputs) == 1 && len(t.Inputs[0].ID) == 0 && t.Inputs[0].Out == -1\n}", "func equal(lhs, rhs semantic.Expression) semantic.Expression {\n\treturn &semantic.BinaryOp{Type: semantic.BoolType, LHS: lhs, Operator: ast.OpEQ, RHS: rhs}\n}", "func (peer *peerImp) Equal(otherPeer Peer) bool {\n\treturn peer.id.Equal(otherPeer.GetID())\n}", "func TestCoinChange(t *testing.T) {\n\ttest(t, coinChange)\n}", "func rcEqEq(p *TCompiler, code *TCode) (*value.Value, error) {\n\tv := value.EqEq(p.regGet(code.B), p.regGet(code.C))\n\tp.regSet(code.A, v)\n\tp.moveNext()\n\treturn v, nil\n}", "func (state VPCState) Equal(b VPCState) (result bool) {\n\tif bytes.Equal(state.ID, b.ID) &&\n\t\tstate.Version.Cmp(b.Version) == 0 &&\n\t\tstate.BlockedReceiver.Cmp(b.BlockedReceiver) == 0 &&\n\t\tstate.BlockedSender.Cmp(b.BlockedSender) == 0 {\n\t\treturn true\n\t}\n\treturn false\n}", "func NewCoin(\n\tname string,\n\tunit string,\n\tnet *chaincfg.Params,\n\tdbFolder string,\n\tservers []*rpc.ServerInfo,\n\tblockExplorerTxPrefix string,\n\tratesUpdater coinpkg.RatesUpdater,\n) *Coin {\n\tcoin := &Coin{\n\t\tname: name,\n\t\tunit: unit,\n\t\tnet: net,\n\t\tdbFolder: dbFolder,\n\t\tservers: servers,\n\t\tblockExplorerTxPrefix: blockExplorerTxPrefix,\n\t\tratesUpdater: ratesUpdater,\n\n\t\tlog: logging.Get().WithGroup(\"coin\").WithField(\"name\", name),\n\t}\n\treturn coin\n}", "func (rt *RecvTxOut) IsCoinbase() bool {\n\tif rt.recvTxOut.block == nil {\n\t\treturn false\n\t}\n\treturn rt.recvTxOut.block.Index == 0\n}", "func NewCoin(\n\tcode string,\n\tunit string,\n\tfeeUnit string,\n\tnet *params.ChainConfig,\n\tblockExplorerTxPrefix string,\n\tetherScanURL string,\n\tnodeURL string,\n\terc20Token *erc20.Token,\n) *Coin {\n\treturn &Coin{\n\t\tcode: code,\n\t\tunit: unit,\n\t\tfeeUnit: feeUnit,\n\t\tnet: net,\n\t\tblockExplorerTxPrefix: blockExplorerTxPrefix,\n\t\tnodeURL: nodeURL,\n\t\tetherScanURL: etherScanURL,\n\t\terc20Token: erc20Token,\n\n\t\tlog: logging.Get().WithGroup(\"coin\").WithField(\"code\", code),\n\t}\n}", "func (bits *BitArray) Eq(obits *BitArray) bool {\n\tif bits.length != obits.length {\n\t\treturn false\n\t}\n\n\tfor i := 0; i < bits.lenpad; i += _BytesPW {\n\t\twself := bytes2word(bits.bytes[i : i+_BytesPW])\n\t\twother := bytes2word(obits.bytes[i : i+_BytesPW])\n\t\tif wself != wother {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func DeepEq(a, b Value) bool {\n\treturn reflect.DeepEqual(a, b)\n}", "func DeepEq(a, b Value) bool {\n\treturn reflect.DeepEqual(a, b)\n}", "func (r *Repo) CommitsEquivalent(c1 string, c2 string) (bool, error) {\n\tif c1 == \"\" {\n\t\treturn c2 == \"\", nil\n\t} else if c2 == \"\" {\n\t\treturn false, nil\n\t}\n\n\tcommits, err := r.downloader.CommitsFor(r.Path(), c1)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfor _, c := range commits {\n\t\tif c == c2 {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}", "func (recv *InitiallyUnowned) Equals(other *InitiallyUnowned) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func TestIsCoinbaseTx(t *testing.T) {\n\ttests := []struct {\n\t\tname string // test description\n\t\ttx string // transaction to test\n\t\twantPreTrsy bool // expected coinbase result before treasury active\n\t\twantPostTrsy bool // expected coinbase result after treasury active\n\t}{{\n\t\tname: \"mainnet block 2 coinbase\",\n\t\ttx: \"010000000100000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"00000000000ffffffff00ffffffff03fa1a981200000000000017a914f59161\" +\n\t\t\t\"58e3e2c4551c1796708db8367207ed13bb8700000000000000000000266a240\" +\n\t\t\t\"2000000000000000000000000000000000000000000000000000000ffa310d9\" +\n\t\t\t\"a6a9588edea1906f0000000000001976a9148ffe7a49ecf0f4858e7a5215530\" +\n\t\t\t\"2177398d2296988ac000000000000000001d8bc28820000000000000000ffff\" +\n\t\t\t\"ffff0800002f646372642f\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: false,\n\t}, {\n\t\tname: \"modified mainnet block 2 coinbase: tx version 3\",\n\t\ttx: \"030000000100000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"00000000000ffffffff00ffffffff02fa1a981200000000000017a914f59161\" +\n\t\t\t\"58e3e2c4551c1796708db8367207ed13bb8700000000000000000000266a240\" +\n\t\t\t\"2000000000000000000000000000000000000000000000000000000ffa310d9\" +\n\t\t\t\"a6a9588e000000000000000001d8bc28820000000000000000ffffffff08000\" +\n\t\t\t\"02f646372642f\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: true,\n\t}, {\n\t\tname: \"modified mainnet block 2 coinbase: tx version 3, no miner payout\",\n\t\ttx: \"030000000100000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"00000000000ffffffff00ffffffff02fa1a981200000000000017a914f59161\" +\n\t\t\t\"58e3e2c4551c1796708db8367207ed13bb8700000000000000000000266a240\" +\n\t\t\t\"2000000000000000000000000000000000000000000000000000000ffa310d9\" +\n\t\t\t\"a6a9588e000000000000000001d8bc28820000000000000000ffffffff08000\" +\n\t\t\t\"02f646372642f\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: true,\n\t}, {\n\t\tname: \"mainnet block 3, tx[1] (one input), not coinbase\",\n\t\ttx: \"0100000001e68bcb9222c7f6336e865c81d7fd3e4b3244cd83998ac9767efcb\" +\n\t\t\t\"355b3cd295efe02000000ffffffff01105ba3940600000000001976a914dcfd\" +\n\t\t\t\"20801304752f618295dfe0a4c044afcfde3a88ac000000000000000001e04aa\" +\n\t\t\t\"7940600000001000000000000006b48304502210089d763b0c28314b5eb0d4c\" +\n\t\t\t\"97e0183a78bb4a656dcbcd293d29d91921a64c55af02203554e76f432f73862\" +\n\t\t\t\"edd4f2ed80a4599141b13c6ac2406158b05a97c6867a1ba01210244709193c0\" +\n\t\t\t\"5a649df0fb0a96180ec1a8e3cbcc478dc9c4a69a3ec5aba1e97a79\",\n\t\twantPreTrsy: false,\n\t\twantPostTrsy: false,\n\t}, {\n\t\tname: \"mainnet block 373, tx[5] (two inputs), not coinbase\",\n\t\ttx: \"010000000201261057a5ecaf6edede86c5446c62f067f30d654117668325090\" +\n\t\t\t\"9ac3e45bec00100000000ffffffff03c65ad19cb990cc916e38dc94f0255f34\" +\n\t\t\t\"4c5e9b7af3b69bfa19931f6027e44c0100000000ffffffff02c1c5760000000\" +\n\t\t\t\"00000001976a914e07c0b2a499312f5d95e3bd4f126e618087a15a588ac402c\" +\n\t\t\t\"42060000000000001976a91411f2b3135e457259009bdd14cfcb942eec58bd7\" +\n\t\t\t\"a88ac0000000000000000023851f6050000000073010000040000006a473044\" +\n\t\t\t\"022009ff5aed5d2e5eeec89319d0a700b7abdf842e248641804c82dee17df44\" +\n\t\t\t\"6c24202207c252cc36199ea8a6cc71d2252a3f7e61f9cce272dff82c5818e3b\" +\n\t\t\t\"f08167e3a6012102773925f9ee53837aa0efba2212f71ee8ab20aeb603fa732\" +\n\t\t\t\"4a8c2555efe5c482709ec0e010000000025010000050000006a473044022011\" +\n\t\t\t\"65136a2b792cc6d7e75f576ed64e1919cbf954afb989f8590844a628e58def0\" +\n\t\t\t\"2206ba7e60f5ae9810794297359cc883e7ff97ecd21bc7177fcc668a84f64a4\" +\n\t\t\t\"b9120121026a4151513b4e6650e3d213451037cd6b78ed829d12ed1d43d5d34\" +\n\t\t\t\"ce0834831e9\",\n\t\twantPreTrsy: false,\n\t\twantPostTrsy: false,\n\t}, {\n\t\tname: \"simnet block 32 coinbase (treasury active)\",\n\t\ttx: \"0300000001000000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"0000000000ffffffff00ffffffff02000000000000000000000e6a0c20000000\" +\n\t\t\t\"93c1b2181e4cd3b100ac23fc0600000000001976a91423d4150eb4332733b5bf\" +\n\t\t\t\"88e5d9cea3897bc09dbc88ac00000000000000000100ac23fc06000000000000\" +\n\t\t\t\"00ffffffff0800002f646372642f\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: true,\n\t}, {\n\t\tname: \"modified simnet block 32 coinbase (treasury active): no miner payout\",\n\t\ttx: \"030000000100000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"00000000000ffffffff00ffffffff01000000000000000000000e6a0c200000\" +\n\t\t\t\"0093c1b2181e4cd3b100000000000000000100ac23fc0600000000000000fff\" +\n\t\t\t\"fffff0800002f646372642f\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: true,\n\t}, {\n\t\tname: \"random simnet treasury spend\",\n\t\ttx: \"030000000100000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"00000000000ffffffff00ffffffff0200000000000000000000226a20b63c13\" +\n\t\t\t\"400000000045c279dd8870eff33bc219a4c9a39a9190960601d8fccdefc0321\" +\n\t\t\t\"3400000000000001ac376a914c945ac8cdbf5e37ad4bfde5dc92f65e13ff5c6\" +\n\t\t\t\"7488ac000000008201000001b63c13400000000000000000ffffffff6440650\" +\n\t\t\t\"063174184d0438b26d05a2f6d3190d020994ef3c18ac110bf70df3d1ed7066c\" +\n\t\t\t\"8c62c349b8ae86862d04ee94d2bddc42bd33d449c1ba53ed37a2c8d1e8f8f62\" +\n\t\t\t\"102a36b785d584555696b69d1b2bbeff4010332b301e3edd316d79438554cac\" +\n\t\t\t\"b3e7c2\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: false,\n\t}, {\n\t\t// This is neither a valid coinbase nor a valid treasury spend, but\n\t\t// since the coinbase identification function is only a fast heuristic,\n\t\t// this is crafted to test that.\n\t\tname: \"modified random simnet treasury spend: missing signature script\",\n\t\ttx: \"0300000001000000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"0000000000ffffffff00ffffffff0200000000000000000000226a20b63c1340\" +\n\t\t\t\"0000000045c279dd8870eff33bc219a4c9a39a9190960601d8fccdefc0321340\" +\n\t\t\t\"0000000000001ac376a914c945ac8cdbf5e37ad4bfde5dc92f65e13ff5c67488\" +\n\t\t\t\"ac000000008201000001b63c13400000000000000000ffffffff00\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: true,\n\t}}\n\n\tfor _, test := range tests {\n\t\ttxBytes, err := hex.DecodeString(test.tx)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%q: unexpected err parsing tx hex %q: %v\", test.name,\n\t\t\t\ttest.tx, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar tx wire.MsgTx\n\t\tif err := tx.FromBytes(txBytes); err != nil {\n\t\t\tt.Errorf(\"%q: unexpected err parsing tx: %v\", test.name, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tresult := IsCoinBaseTx(&tx, noTreasury)\n\t\tif result != test.wantPreTrsy {\n\t\t\tt.Errorf(\"%s: unexpected result pre treasury -- got %v, want %v\",\n\t\t\t\ttest.name, result, test.wantPreTrsy)\n\t\t\tcontinue\n\t\t}\n\n\t\tresult = IsCoinBaseTx(&tx, withTreasury)\n\t\tif result != test.wantPostTrsy {\n\t\t\tt.Errorf(\"%s: unexpected result post treasury -- got %v, want %v\",\n\t\t\t\ttest.name, result, test.wantPostTrsy)\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func eq(o1, o2 interface{}) bool {\n\n\tf1, ok1 := ToFloat(o1)\n\tf2, ok2 := ToFloat(o2)\n\tif ok1 && ok2 {\n\t\treturn f1 == f2\n\t}\n\n\tb1, ok1 := ToBool(o1)\n\tb2, ok1 := ToBool(o2)\n\tif ok1 && ok2 {\n\t\treturn b1 == b2\n\t}\n\n\treturn o1 == o2\n}", "func (in *CiliumLoadBalancerIPPoolSpec) DeepEqual(other *CiliumLoadBalancerIPPoolSpec) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\n\tif (in.ServiceSelector == nil) != (other.ServiceSelector == nil) {\n\t\treturn false\n\t} else if in.ServiceSelector != nil {\n\t\tif !in.ServiceSelector.DeepEqual(other.ServiceSelector) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif ((in.Cidrs != nil) && (other.Cidrs != nil)) || ((in.Cidrs == nil) != (other.Cidrs == nil)) {\n\t\tin, other := &in.Cidrs, &other.Cidrs\n\t\tif other == nil {\n\t\t\treturn false\n\t\t}\n\n\t\tif len(*in) != len(*other) {\n\t\t\treturn false\n\t\t} else {\n\t\t\tfor i, inElement := range *in {\n\t\t\t\tif !inElement.DeepEqual(&(*other)[i]) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif in.Disabled != other.Disabled {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (c clock) equals(other clock) bool {\n\treturn reflect.DeepEqual(c, other)\n}", "func equal(a, b float64) bool {\n\treturn math.Abs(a-b) <= equalityThreshold\n}", "func (in *CiliumBGPVirtualRouter) DeepEqual(other *CiliumBGPVirtualRouter) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\n\tif in.LocalASN != other.LocalASN {\n\t\treturn false\n\t}\n\tif (in.ExportPodCIDR == nil) != (other.ExportPodCIDR == nil) {\n\t\treturn false\n\t} else if in.ExportPodCIDR != nil {\n\t\tif *in.ExportPodCIDR != *other.ExportPodCIDR {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif (in.ServiceSelector == nil) != (other.ServiceSelector == nil) {\n\t\treturn false\n\t} else if in.ServiceSelector != nil {\n\t\tif !in.ServiceSelector.DeepEqual(other.ServiceSelector) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif ((in.Neighbors != nil) && (other.Neighbors != nil)) || ((in.Neighbors == nil) != (other.Neighbors == nil)) {\n\t\tin, other := &in.Neighbors, &other.Neighbors\n\t\tif other == nil {\n\t\t\treturn false\n\t\t}\n\n\t\tif len(*in) != len(*other) {\n\t\t\treturn false\n\t\t} else {\n\t\t\tfor i, inElement := range *in {\n\t\t\t\tif !inElement.DeepEqual(&(*other)[i]) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func (d BigDecimal) Equal(ref BigDecimal) bool {\n\tif d.Cmp(ref) != 0 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (GoVersion) Eq(version string) bool { return boolResult }", "func (v Vect) Equals(other Vect) bool {\n\treturn int(C.cpveql(toC(v), toC(other))) == 1\n}", "func HasStableCoin(PublicKey string) bool {\n\taccount, err := TestNetClient.LoadAccount(PublicKey)\n\tif err != nil {\n\t\t// account does not exist\n\t\treturn false\n\t}\n\n\tfor _, balance := range account.Balances {\n\t\tif balance.Asset.Code == \"STABLEUSD\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func equal(z1, z2 *big.Int) bool {\n\treturn z1.Cmp(z2) == 0\n}", "func FlipCoin(p float64) bool {\n\tif p == 1.0 {\n\t\treturn true\n\t}\n\tif p == 0.0 {\n\t\treturn false\n\t}\n\tif rand.Float64() <= p {\n\t\treturn true\n\t}\n\treturn false\n}", "func (a *Asserter) BalanceEq(addr address.Address, expected abi.TokenAmount) {\n\tst := a.suppliers.stateTracker()\n\tactor, err := st.StateTree.GetActor(addr)\n\ta.NoError(err, \"failed to fetch actor %s from state\", addr)\n\ta.Equal(expected, actor.Balance, \"balances mismatch for address %s\", addr)\n}", "func (d Decimal) Equals(d2 Decimal) bool {\n\treturn d.Equal(d2)\n}", "func (d Decimal) Equals(d2 Decimal) bool {\n\treturn d.Equal(d2)\n}", "func (coin Coin) IsZero() bool {\n\treturn coin.Amount.Sign() == 0\n}", "func (keeper SendKeeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (p Point) Eq(q Point) bool {\n\treturn p == q\n}", "func (in *CiliumBGPNeighbor) DeepEqual(other *CiliumBGPNeighbor) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\n\tif in.PeerAddress != other.PeerAddress {\n\t\treturn false\n\t}\n\tif (in.PeerPort == nil) != (other.PeerPort == nil) {\n\t\treturn false\n\t} else if in.PeerPort != nil {\n\t\tif *in.PeerPort != *other.PeerPort {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif in.PeerASN != other.PeerASN {\n\t\treturn false\n\t}\n\tif (in.EBGPMultihopTTL == nil) != (other.EBGPMultihopTTL == nil) {\n\t\treturn false\n\t} else if in.EBGPMultihopTTL != nil {\n\t\tif *in.EBGPMultihopTTL != *other.EBGPMultihopTTL {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif (in.ConnectRetryTimeSeconds == nil) != (other.ConnectRetryTimeSeconds == nil) {\n\t\treturn false\n\t} else if in.ConnectRetryTimeSeconds != nil {\n\t\tif *in.ConnectRetryTimeSeconds != *other.ConnectRetryTimeSeconds {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif (in.HoldTimeSeconds == nil) != (other.HoldTimeSeconds == nil) {\n\t\treturn false\n\t} else if in.HoldTimeSeconds != nil {\n\t\tif *in.HoldTimeSeconds != *other.HoldTimeSeconds {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif (in.KeepAliveTimeSeconds == nil) != (other.KeepAliveTimeSeconds == nil) {\n\t\treturn false\n\t} else if in.KeepAliveTimeSeconds != nil {\n\t\tif *in.KeepAliveTimeSeconds != *other.KeepAliveTimeSeconds {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif (in.GracefulRestart == nil) != (other.GracefulRestart == nil) {\n\t\treturn false\n\t} else if in.GracefulRestart != nil {\n\t\tif !in.GracefulRestart.DeepEqual(other.GracefulRestart) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif ((in.Families != nil) && (other.Families != nil)) || ((in.Families == nil) != (other.Families == nil)) {\n\t\tin, other := &in.Families, &other.Families\n\t\tif other == nil {\n\t\t\treturn false\n\t\t}\n\n\t\tif len(*in) != len(*other) {\n\t\t\treturn false\n\t\t} else {\n\t\t\tfor i, inElement := range *in {\n\t\t\t\tif !inElement.DeepEqual(&(*other)[i]) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func Equals(a, b interface{}) bool {\n\treturn neogointernal.Opcode2(\"EQUAL\", a, b).(bool)\n}", "func EqFn(a interface{}, b interface{}) bool {\n\treturn a == b\n}", "func Eq(f1, f2 Formula) Formula {\n\treturn and{or{not{f1}, f2}, or{f1, not{f2}}}\n}", "func TestPriceCompareInverse(t *testing.T) {\n\tnormalPrice := &Price{\n\t\tAmountWant: uint64(505763),\n\t\tAmountHave: uint64(37049),\n\t}\n\tinversePrice := &Price{\n\t\tAmountWant: uint64(37049),\n\t\tAmountHave: uint64(505763),\n\t}\n\n\tif leftSide := normalPrice.Cmp(inversePrice); leftSide != 1 {\n\t\tt.Errorf(\"A price that is greater than 1 should not be less than or equal to its inverse\")\n\t\treturn\n\t}\n\tif rightSide := inversePrice.Cmp(normalPrice); rightSide != -1 {\n\t\tt.Errorf(\"The inverse of a price greater than 1 should not be greater than or equal to the original price\")\n\t\treturn\n\t}\n\treturn\n}", "func (v Peer) Equal(o Peer) bool {\n\treturn string(v.Metadata) == string(o.Metadata) &&\n\t\tv.PeerID == o.PeerID\n}", "func (s *Struct) Eq(rhs interface{}) bool {\n\treturn s == rhs || eqMapLike(s, rhs)\n}", "func (oc *ObjectComprehension) Equal(other Value) bool {\n\treturn Compare(oc, other) == 0\n}", "func eq128(a0, a1, b0, b1 uint64) bool {\n\treturn (a0 == b0) && (a1 == b1)\n}", "func (v ConstructionHashRequest) Equal(o ConstructionHashRequest) bool {\n\treturn v.SignedTransaction == o.SignedTransaction\n}", "func (recv *ObjectConstructParam) Equals(other *ObjectConstructParam) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (v Amount) Equal(o Amount) bool {\n\treturn v.Currency.Equal(o.Currency) &&\n\t\tstring(v.Metadata) == string(o.Metadata) &&\n\t\tv.Value == o.Value\n}", "func (utxo ExtBtcCompatUTXO) Equal(other Value) bool {\n\totherUTXO, ok := other.(ExtBtcCompatUTXO)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn utxo.TxHash.Equal(otherUTXO.TxHash) &&\n\t\tutxo.VOut.Equal(otherUTXO.VOut) &&\n\t\tutxo.ScriptPubKey.Equal(otherUTXO.ScriptPubKey) &&\n\t\tutxo.Amount.Equal(otherUTXO.Amount) &&\n\t\tutxo.GHash.Equal(otherUTXO.GHash)\n}", "func WriteCoin(slug string, v interface{}, d interface{}) bool {\n\tdc := mod.Cache{Data: d}\n\treturn DB.Write(cfg.Web+\"/coins\", slug, v) == nil &&\n\t\tDB.Write(cfg.Web+\"/data/\"+slug, \"info\", dc) == nil\n}", "func StatesEq(a *State, b *State) bool {\n\treturn reflect.DeepEqual(a, b)\n}", "func (in *CoreCiliumEndpoint) DeepEqual(other *CoreCiliumEndpoint) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\n\tif in.Name != other.Name {\n\t\treturn false\n\t}\n\tif in.IdentityID != other.IdentityID {\n\t\treturn false\n\t}\n\tif (in.Networking == nil) != (other.Networking == nil) {\n\t\treturn false\n\t} else if in.Networking != nil {\n\t\tif !in.Networking.DeepEqual(other.Networking) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif in.Encryption != other.Encryption {\n\t\treturn false\n\t}\n\n\tif ((in.NamedPorts != nil) && (other.NamedPorts != nil)) || ((in.NamedPorts == nil) != (other.NamedPorts == nil)) {\n\t\tin, other := &in.NamedPorts, &other.NamedPorts\n\t\tif other == nil {\n\t\t\treturn false\n\t\t}\n\n\t\tif len(*in) != len(*other) {\n\t\t\treturn false\n\t\t} else {\n\t\t\tfor i, inElement := range *in {\n\t\t\t\tif !inElement.DeepEqual((*other)[i]) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func (in *CoreCiliumEndpoint) DeepEqual(other *CoreCiliumEndpoint) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\n\tif in.Name != other.Name {\n\t\treturn false\n\t}\n\tif in.IdentityID != other.IdentityID {\n\t\treturn false\n\t}\n\tif (in.Networking == nil) != (other.Networking == nil) {\n\t\treturn false\n\t} else if in.Networking != nil {\n\t\tif !in.Networking.DeepEqual(other.Networking) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif in.Encryption != other.Encryption {\n\t\treturn false\n\t}\n\n\tif ((in.NamedPorts != nil) && (other.NamedPorts != nil)) || ((in.NamedPorts == nil) != (other.NamedPorts == nil)) {\n\t\tin, other := &in.NamedPorts, &other.NamedPorts\n\t\tif other == nil || !in.DeepEqual(other) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (recv *ParamSpecUInt) Equals(other *ParamSpecUInt) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (in *IPPoolSpec) DeepEqual(other *IPPoolSpec) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\n\tif (in.IPv4 == nil) != (other.IPv4 == nil) {\n\t\treturn false\n\t} else if in.IPv4 != nil {\n\t\tif !in.IPv4.DeepEqual(other.IPv4) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif (in.IPv6 == nil) != (other.IPv6 == nil) {\n\t\treturn false\n\t} else if in.IPv6 != nil {\n\t\tif !in.IPv6.DeepEqual(other.IPv6) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (recv *ParamSpecPool) Equals(other *ParamSpecPool) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (tx ExtEthCompatTx) Equal(other Value) bool {\n\totherTx, ok := other.(ExtEthCompatTx)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn tx.TxHash.Equal(otherTx.TxHash)\n}", "func (w *Wallet) Equal(z *Wallet) bool {\n\tif w != nil && z != nil {\n\t\treturn w.Currency == z.Currency && w.Balance == z.Balance && w.Sequence == z.Sequence\n\t}\n\treturn w == z\n}", "func (coins DecCoins) IsValid() bool {\n\tswitch len(coins) {\n\tcase 0:\n\t\treturn true\n\n\tcase 1:\n\t\tif err := validateDenom(coins[0].Denom); err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn coins[0].IsPositive()\n\n\tdefault:\n\t\t// check single coin case\n\t\tif !(DecCoins{coins[0]}).IsValid() {\n\t\t\treturn false\n\t\t}\n\n\t\tlowDenom := coins[0].Denom\n\t\tfor _, coin := range coins[1:] {\n\t\t\tif strings.ToLower(coin.Denom) != coin.Denom {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif coin.Denom <= lowDenom {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif !coin.IsPositive() {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// we compare each coin against the last denom\n\t\t\tlowDenom = coin.Denom\n\t\t}\n\n\t\treturn true\n\t}\n}", "func (c *Credentials) Equal(other *Credentials) bool {\n\treturn c != nil &&\n\t\tother != nil &&\n\t\tc.Key == other.Key &&\n\t\tc.ClientID == other.ClientID &&\n\t\t(c.SubAccount == other.SubAccount || c.SubAccount == \"\" && other.SubAccount == \"main\" || c.SubAccount == \"main\" && other.SubAccount == \"\")\n}", "func (keeper Keeper) HasCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) bool {\n\treturn hasCoins(ctx, keeper.am, addr, amt)\n}", "func (ip1 IP6u128) Eq(ip2 IP6u128) bool {\n\treturn ip1.Cmp(ip2) == 0\n}", "func (recv *ParamSpecUInt64) Equals(other *ParamSpecUInt64) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (m Money) Cmp(other Money) (int, error) {\n\tif !m.currency.Equals(other.currency) {\n\t\treturn 0, &ErrDifferentCurrency{m.currency, other.currency}\n\t}\n\treturn m.amount.Cmp(other.amount), nil\n}", "func eq(args ...interface{}) bool {\n\tif len(args) == 0 {\n\t\treturn false\n\t}\n\tx := args[0]\n\tswitch x := x.(type) {\n\tcase string, int, int64, byte, float32, float64:\n\t\tfor _, y := range args[1:] {\n\t\t\tif x == y {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\tfor _, y := range args[1:] {\n\t\tif reflect.DeepEqual(x, y) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func eq(args ...interface{}) bool {\n\tif len(args) == 0 {\n\t\treturn false\n\t}\n\tx := args[0]\n\tswitch x := x.(type) {\n\tcase string, int, int64, byte, float32, float64:\n\t\tfor _, y := range args[1:] {\n\t\t\tif x == y {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\tfor _, y := range args[1:] {\n\t\tif reflect.DeepEqual(x, y) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (c *Candidate) Equal(b *Candidate) bool {\n\tif !c.ConnectionAddress.Equal(b.ConnectionAddress) {\n\t\treturn false\n\t}\n\tif c.Port != b.Port {\n\t\treturn false\n\t}\n\tif c.Transport != b.Transport {\n\t\treturn false\n\t}\n\tif !bytes.Equal(c.TransportValue, b.TransportValue) {\n\t\treturn false\n\t}\n\tif c.Foundation != b.Foundation {\n\t\treturn false\n\t}\n\tif c.ComponentID != b.ComponentID {\n\t\treturn false\n\t}\n\tif c.Priority != b.Priority {\n\t\treturn false\n\t}\n\tif c.Type != b.Type {\n\t\treturn false\n\t}\n\tif c.NetworkCost != b.NetworkCost {\n\t\treturn false\n\t}\n\tif c.Generation != b.Generation {\n\t\treturn false\n\t}\n\tif !c.Attributes.Equal(b.Attributes) {\n\t\treturn false\n\t}\n\treturn true\n}", "func (e *ConstantExpr) Eq(other *ConstantExpr) *ConstantExpr {\n\tassert(e.Width == other.Width, \"eq: width mismatch: %d != %d\", e.Width, other.Width)\n\tif e.Value == other.Value {\n\t\treturn NewConstantExpr(1, WidthBool)\n\t}\n\treturn NewConstantExpr(0, WidthBool)\n}", "func (ref Ref) Equal(other Value) bool {\n\treturn Compare(ref, other) == 0\n}" ]
[ "0.70465946", "0.6923523", "0.60608363", "0.60347974", "0.6028179", "0.60094017", "0.5901305", "0.58853287", "0.58778554", "0.5840299", "0.58085173", "0.5762222", "0.5661418", "0.5580482", "0.5563641", "0.5520213", "0.54485756", "0.5405266", "0.54030937", "0.5394832", "0.53687775", "0.5358282", "0.5358282", "0.53297544", "0.5285027", "0.52763593", "0.5269229", "0.52658004", "0.5256752", "0.52444196", "0.52444196", "0.5241736", "0.52380437", "0.5233506", "0.5223962", "0.5217641", "0.52020293", "0.52005714", "0.51921785", "0.5171367", "0.51511294", "0.5142358", "0.5135082", "0.51301533", "0.5121962", "0.5120579", "0.5120579", "0.50980514", "0.5094809", "0.50912344", "0.50887793", "0.5087059", "0.50729936", "0.50661296", "0.50606203", "0.5051528", "0.5043822", "0.5027348", "0.5020527", "0.5012831", "0.50101197", "0.4993227", "0.49923995", "0.49923995", "0.49623585", "0.49393642", "0.4929838", "0.49195057", "0.4917329", "0.49130696", "0.49125868", "0.49090534", "0.489253", "0.48865768", "0.48839483", "0.48678032", "0.48629662", "0.48548287", "0.48536664", "0.48526335", "0.48479125", "0.48470655", "0.48448437", "0.48430103", "0.48373693", "0.4834056", "0.48332107", "0.48310193", "0.48242226", "0.48237783", "0.48121655", "0.48119923", "0.48066574", "0.4806234", "0.4802984", "0.48009723", "0.48009723", "0.47996268", "0.4798124", "0.47978717" ]
0.74850535
0
Validate checks for errors on the account fields
func (va ClawbackVestingAccount) Validate() error { if va.GetStartTime() >= va.GetEndTime() { return errors.New("vesting start-time must be before end-time") } lockupEnd := va.StartTime lockupCoins := sdk.NewCoins() for _, p := range va.LockupPeriods { lockupEnd += p.Length lockupCoins = lockupCoins.Add(p.Amount...) } if lockupEnd > va.EndTime { return errors.New("lockup schedule extends beyond account end time") } if !coinEq(lockupCoins, va.OriginalVesting) { return errors.New("original vesting coins does not match the sum of all coins in lockup periods") } vestingEnd := va.StartTime vestingCoins := sdk.NewCoins() for _, p := range va.VestingPeriods { vestingEnd += p.Length vestingCoins = vestingCoins.Add(p.Amount...) } if vestingEnd > va.EndTime { return errors.New("vesting schedule exteds beyond account end time") } if !coinEq(vestingCoins, va.OriginalVesting) { return errors.New("original vesting coins does not match the sum of all coins in vesting periods") } return va.BaseVestingAccount.Validate() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (account *Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Phone, \"+\") {\n\t\treturn u.Message(false, \"Phone Number address is required\"), false\n\t}\n\n\tif len(account.UserName) < 3 {\n\t\treturn u.Message(false, \"Username is required\"), false\n\t}\n\n\t//PhoneNumber must be unique\n\ttemp := &Account{}\n\n\t//check for errors and duplicate phones\n\terr := GetDB().Table(\"accounts\").Where(\"phone = ?\", account.Phone).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"+err.Error()), false\n\t}\n\tif temp.Phone != \"\" {\n\t\treturn u.Message(false, \"Phone Number address already in use by another user.\"), false\n\t}\n\n\t//check for errors and duplicate username\n\terr = GetDB().Table(\"accounts\").Where(\"user_name = ?\", account.UserName).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"+err.Error()), false\n\t}\n\tif temp.UserName != \"\" {\n\t\tresponse := fmt.Sprintf(\"Username: %d is already in use by another user.\", account.UserName)\n\t\treturn u.Message(false, response), false\n\t}\n\n\treturn u.Message(false, \"Requirement passed\"), true\n}", "func (account Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, ERROR_EMAIL), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, ERROR_PASSWORD_LENTH), false\n\t}\n\n\t// Email must be unique\n\ttemp := &Account{}\n\n\t// 数据类型合法时,查询数据表,GetDB return the configed db\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, ERROR_CONNECTION), false\n\t}\n\t// 存在该email\n\tif temp.Email != \"\" {\n\t\treturn u.Message(false, ERROR_EMAIL_USED), false\n\t}\n\n\treturn u.Message(false, GET_SUCCESS), true\n}", "func (a Account) Validate() error {\n\treturn validation.ValidateStruct(&a,\n\t\tvalidation.Field(&a.Name, validation.Required, validation.Length(3, 75)),\n\t)\n}", "func (m *Account) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccountID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAuditLogs(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateParentAccountID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethodID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReferenceTime(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (account *Account) Validate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, \"Email address is required\"), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, \"Password is required\"), false\n\t}\n\n\t//Email must be unique\n\ttemp := &Account{}\n\t//check for errors and duplicate emails\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"), false\n\t}\n\tif temp.Email != \"\" {\n\t\treturn u.Message(false, \"Email address already in use by another user.\"), false\n\t}\n\treturn u.Message(false, \"Requirement passed\"), true\n}", "func (a *Account) Validate() error {\n\treturn nil\n}", "func (mt *Account) Validate() (err error) {\n\tif mt.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"id\"))\n\t}\n\tif mt.Password == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"password\"))\n\t}\n\n\treturn\n}", "func (accountInfo *AccountInfo) Validate() error {\n\taccountSchema, _ := GetAccountSchema(accountInfo.Domain)\n\tif accountSchema == nil {\n\t\treturn errors.New(\"schema undefined for domain \" + accountInfo.Domain)\n\t}\n\n\t// Group\n\tif !accountSchema.IsGroupExist(accountInfo.Group) {\n\t\treturn errors.New(\"unknown group \" + accountInfo.Group)\n\t}\n\n\t// UserID\n\tif accountInfo.Uid == \"\" {\n\t\treturn errors.New(\"uid can not be empty\")\n\t}\n\n\t// LoginIDs\n\tif len(accountInfo.LoginIDs) == 0 {\n\t\treturn errors.New(\"should have at least one login id\")\n\t}\n\trequiredIDs := accountSchema.getRequiredLogIDs()\n\tfor _, requiredID := range requiredIDs {\n\t\tif _, ok := accountInfo.LoginIDs[requiredID]; !ok {\n\t\t\treturn errors.New(\"login id:\" + requiredID + \" is required but not specified\")\n\t\t}\n\t}\n\tfor k, v := range accountInfo.LoginIDs {\n\t\tloginIDSchema, _ := accountSchema.GetLoginIDSchema(k)\n\t\tif loginIDSchema == nil {\n\t\t\treturn errors.New(\"login id schema for \" + k + \" is not defined\")\n\t\t} else {\n\t\t\tif !loginIDSchema.NeedVerified {\n\t\t\t\tv.Verified = true\n\t\t\t\t// accountInfo.LoginIDs[k] = v\n\t\t\t}\n\t\t\tif !loginIDSchema.Validator.Validate(v.ID) {\n\t\t\t\treturn errors.New(\"invalid format of login id \" + k + \":\" + v.ID)\n\t\t\t}\n\t\t}\n\t}\n\n\t// options\n\toptionsMap := mergeMaps(accountInfo.Profiles, accountInfo.Others)\n\trequiredOptions := accountSchema.getRequiredOptions()\n\tfor _, requiredOption := range requiredOptions {\n\t\tif _, ok := optionsMap[requiredOption]; !ok {\n\t\t\treturn errors.New(\"option:\" + requiredOption + \" is required but not specified\")\n\t\t}\n\t}\n\n\tfor k, v := range optionsMap {\n\t\toptionSchema, _ := accountSchema.GetOptionSchema(k)\n\t\tif optionSchema == nil {\n\t\t\treturn errors.New(\"option schema for \" + k + \" is not defined\")\n\t\t} else {\n\t\t\tif !optionSchema.Validator.Validate(v) {\n\t\t\t\treturn errors.New(\"invalid format of option \" + k)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (mt *Account) Validate() (err error) {\n\n\tif mt.Href == \"\" {\n\t\terr = goa.MissingAttributeError(`response`, \"href\", err)\n\t}\n\tif mt.Name == \"\" {\n\t\terr = goa.MissingAttributeError(`response`, \"name\", err)\n\t}\n\n\tif mt.CreatedAt != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatDateTime, *mt.CreatedAt); err2 != nil {\n\t\t\terr = goa.InvalidFormatError(`response.created_at`, *mt.CreatedAt, goa.FormatDateTime, err2, err)\n\t\t}\n\t}\n\tif mt.CreatedBy != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *mt.CreatedBy); err2 != nil {\n\t\t\terr = goa.InvalidFormatError(`response.created_by`, *mt.CreatedBy, goa.FormatEmail, err2, err)\n\t\t}\n\t}\n\treturn\n}", "func (c *modAccountRun) validate(args []string) error {\n\tif len(args) < 2 {\n\t\treturn errors.New(\"not enough arguments\")\n\t}\n\n\tif len(args) > 2 {\n\t\treturn errors.New(\"too many arguments\")\n\t}\n\n\treturn nil\n}", "func (m *LedgerAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccount(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePostings(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (b *OGame) ValidateAccount(code string) error {\n\treturn b.validateAccount(code)\n}", "func (ut *accountInputPayload) Validate() (err error) {\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`response.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 1, true))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 30, false))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 1, true))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 30, false))\n\t\t}\n\t}\n\treturn\n}", "func (account *Account) ValidateUpdate() (map[string]interface{}, bool) {\n\n\tif !strings.Contains(account.Email, \"@\") {\n\t\treturn u.Message(false, \"Email address is required\"), false\n\t}\n\n\tif len(account.Password) < 6 {\n\t\treturn u.Message(false, \"Password is required\"), false\n\t}\n\n\t//Email must be unique\n\ttemp := &Account{}\n\t//check for errors and duplicate emails\n\terr := GetDB().Table(\"accounts\").Where(\"email = ?\", account.Email).First(temp).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn u.Message(false, \"Connection error. Please retry\"), false\n\t}\n\tif temp.Email == \"\" {\n\t\treturn u.Message(false, \"Email address not found in database.\"), false\n\t}\n\treturn u.Message(true, \"Requirement passed\"), true\n}", "func (ut *AccountInputPayload) Validate() (err error) {\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`response.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 1, true))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 30, false))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 1, true))\n\t\t}\n\t}\n\tif ut.Surname != nil {\n\t\tif utf8.RuneCountInString(*ut.Surname) > 30 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.surname`, *ut.Surname, utf8.RuneCountInString(*ut.Surname), 30, false))\n\t\t}\n\t}\n\treturn\n}", "func ValidateAccount(client httpclient.IHttpClient, ctx context.Context, lobby, code string) error {\n\tif len(code) != 36 {\n\t\treturn errors.New(\"invalid validation code\")\n\t}\n\treq, err := http.NewRequest(http.MethodPut, \"https://\"+lobby+\".ogame.gameforge.com/api/users/validate/\"+code, strings.NewReader(`{\"language\":\"en\"}`))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.WithContext(ctx)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\treturn nil\n}", "func (b *Builder) Validate() (*Account, error) {\n\tb.validate.SetTagName(b.essential.Country)\n\tif err := validateStruct(b.validate, b.essential); err != nil {\n\t\treturn nil, err\n\t}\n\tb.validate.SetTagName(\"validate\")\n\tif err := validateStruct(b.validate, b.essential); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := validateStruct(b.validate, b.optional); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Account{\n\t\tid: b.essential.ID,\n\t\torganizationID: b.essential.OrganizationID,\n\t\tversionIndex: b.optional.VersionIndex,\n\t\tcountry: b.essential.Country,\n\t\tbankIDCode: b.essential.BankIDCode,\n\t\tbankID: b.essential.BankID,\n\t\tbic: b.essential.Bic,\n\t\tiban: b.essential.Iban,\n\t\tbaseCurrency: b.optional.BaseCurrency,\n\t\taccountNumber: b.optional.AccountNumber,\n\t\tcustomerID: b.optional.CustomerID,\n\t\ttitle: b.optional.Title,\n\t\tfirstName: b.optional.FirstName,\n\t\tbankAccountName: b.optional.BankAccountName,\n\t\taltBankAccountNames: b.optional.AltBankAccountNames,\n\t\taccountClassification: b.optional.AccountClassification,\n\t\tjointAccount: b.optional.JointAccount,\n\t\taccountMatchingOptOut: b.optional.AccountMatchingOptOut,\n\t\tsecondaryIdentification: b.optional.SecondaryIdentification,\n\t}, nil\n}", "func (a *Account) Validate() error {\n\tvalidate := validator.New()\n\treturn validate.Struct(a)\n}", "func (ga GenesisAccount) Validate() error {\n\tif ethermint.IsZeroAddress(ga.Address) {\n\t\treturn fmt.Errorf(\"address cannot be the zero address %s\", ga.Address)\n\t}\n\tif len(ethcmn.Hex2Bytes(ga.Code)) == 0 {\n\t\treturn errors.New(\"code cannot be empty\")\n\t}\n\n\treturn ga.Storage.Validate()\n}", "func validate(user *customer_api.DbUser, allowEmpty bool) error {\n\tconst minNameLength, maxNameLength = 3, 20\n\tconst emailRegexString = \"^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$\"\n\tvar emailRegex = regexp.MustCompile(emailRegexString)\n\n\tif !(allowEmpty && user.Email == \"\") {\n\t\tif len(user.Email) < 5 || !emailRegex.MatchString(user.Email) {\n\t\t\treturn errors.New(\"invalid email\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.FirstName == \"\") {\n\t\tif len(user.FirstName) < minNameLength || len(user.FirstName) > maxNameLength {\n\t\t\treturn errors.New(\"first_name should be between 3 and 20 characters\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.LastName == \"\") {\n\t\tif len(user.LastName) < minNameLength || len(user.LastName) > maxNameLength {\n\t\t\treturn errors.New(\"last_name should be between 3 and 20 characters\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.Phone == 0) {\n\t\tif user.Phone < 1000000000 || user.Phone > 9999999999 {\n\t\t\treturn errors.New(\"invalid phone no\")\n\t\t}\n\t}\n\n\tif !(allowEmpty && user.Id == \"\") {\n\t\tif user.Id == \"\" {\n\t\t\treturn errors.New(\"id cannot be empty\")\n\t\t}\n\t}\n\treturn nil\n}", "func (server *Server) checkValidAccount(ctx *gin.Context, id int64, curr string) (bool, db.Account) {\n\tacc, err := server.repository.GetAccount(ctx, id)\n\tif err != nil {\n\t\tctx.JSON(http.StatusNotFound, errorResponse(err))\n\t\treturn false, db.Account{}\n\t}\n\tif acc.Currency != curr {\n\t\terr = fmt.Errorf(\"invalid currency for account [%d]: expected %s received %s\", acc.ID, acc.Currency, curr)\n\t\tctx.JSON(http.StatusBadRequest, errorResponse(err))\n\t\treturn false, db.Account{}\n\t}\n\n\treturn true, acc\n}", "func (mt *EasypostCarrierAccounts) Validate() (err error) {\n\tif mt.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"id\"))\n\t}\n\tif mt.Object == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"object\"))\n\t}\n\n\tif ok := goa.ValidatePattern(`^CarrierAccount$`, mt.Object); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.object`, mt.Object, `^CarrierAccount$`))\n\t}\n\treturn\n}", "func (m *InfrastructureAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCostCenter(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCriticalityLevel(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEnvironment(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateExternalID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLifecycleStatus(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOwner(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *CloudAccountExtended) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// validation for a type composition with CloudAccount\n\tif err := m.CloudAccount.Validate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateState(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (a *Account) Validate() error {\n\terr := validation.ValidateStruct(a,\n\t\tvalidation.Field(&a.AdminRoleArn, validateAdminRoleArn...),\n\t\tvalidation.Field(&a.ID, validateID...),\n\t\tvalidation.Field(&a.LastModifiedOn, validateInt64...),\n\t\tvalidation.Field(&a.Status, validateStatus...),\n\t\tvalidation.Field(&a.CreatedOn, validateInt64...),\n\t\tvalidation.Field(&a.PrincipalRoleArn, validatePrincipalRoleArn...),\n\t\tvalidation.Field(&a.PrincipalPolicyHash, validatePrincipalPolicyHash...),\n\t)\n\tif err != nil {\n\t\treturn errors.NewValidation(\"account\", err)\n\t}\n\treturn nil\n}", "func validRawAccount(accountName string) error {\n\t// param absence check\n\tif accountName == \"\" {\n\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name is empty\")\n\t}\n\n\t// account naming rule check\n\tif len(accountName) != accountSize {\n\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name length expect %d, actual: %d\", accountSize, len(accountName))\n\t}\n\n\tfor i := 0; i < accountSize; i++ {\n\t\tif accountName[i] >= '0' && accountName[i] <= '9' {\n\t\t\tcontinue\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"invoke NewAccount failed, account name expect continuous %d number\", accountSize)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o *CloudSnapshotAccount) Validate() error {\n\n\terrors := elemental.Errors{}\n\trequiredErrors := elemental.Errors{}\n\n\tif err := ValidateTagsWithoutReservedPrefixes(\"associatedTags\", o.AssociatedTags); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif err := elemental.ValidateStringInList(\"cloudType\", string(o.CloudType), []string{\"AWS\", \"GCP\"}, false); err != nil {\n\t\terrors = errors.Append(err)\n\t}\n\n\tif len(requiredErrors) > 0 {\n\t\treturn requiredErrors\n\t}\n\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\n\treturn nil\n}", "func (m *ProviderAccountRequest) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateDataset(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDatasetName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateField(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePreferences(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (uu *UserUpdate) check() error {\n\tif v, ok := uu.mutation.AccountName(); ok {\n\t\tif err := user.AccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"account_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"account_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.StaffType(); ok {\n\t\tif err := user.StaffTypeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_type\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_type\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.FamilyName(); ok {\n\t\tif err := user.FamilyNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"family_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"family_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.GivenName(); ok {\n\t\tif err := user.GivenNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"given_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"given_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.DisplayName(); ok {\n\t\tif err := user.DisplayNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"display_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"display_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.IDNumber(); ok {\n\t\tif err := user.IDNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"id_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Sex(); ok {\n\t\tif err := user.SexValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"sex\", err: fmt.Errorf(\"ent: validator failed for field \\\"sex\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.PhoneNumber(); ok {\n\t\tif err := user.PhoneNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Address(); ok {\n\t\tif err := user.AddressValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"address\", err: fmt.Errorf(\"ent: validator failed for field \\\"address\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.StaffID(); ok {\n\t\tif err := user.StaffIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_id\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_id\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.PersonalEmail(); ok {\n\t\tif err := user.PersonalEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"personal_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"personal_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.IntranetWorkEmail(); ok {\n\t\tif err := user.IntranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"intranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.ExtranetWorkEmail(); ok {\n\t\tif err := user.ExtranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"extranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"extranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (profileImport *ProfileImportRequest) Validate(tx *sql.Tx) error {\n\n\tprofile := profileImport.Profile\n\n\t// Profile fields are valid\n\terrs := tovalidate.ToErrors(validation.Errors{\n\t\t\"name\": validation.Validate(profile.Name, validation.By(\n\t\t\tfunc(value interface{}) error {\n\t\t\t\tname, ok := value.(*string)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn fmt.Errorf(\"wrong type, need: string, got: %T\", value)\n\t\t\t\t}\n\t\t\t\tif name == nil || *name == \"\" {\n\t\t\t\t\treturn errors.New(\"required and cannot be blank\")\n\t\t\t\t}\n\t\t\t\tif strings.Contains(*name, \" \") {\n\t\t\t\t\treturn errors.New(\"cannot contain spaces\")\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t)),\n\t\t\"description\": validation.Validate(profile.Description, validation.Required),\n\t\t\"cdnName\": validation.Validate(profile.CDNName, validation.Required),\n\t\t\"type\": validation.Validate(profile.Type, validation.Required),\n\t})\n\n\t// Validate CDN exist\n\tif profile.CDNName != nil {\n\t\tif ok, err := CDNExistsByName(*profile.CDNName, tx); err != nil {\n\t\t\terrString := fmt.Sprintf(\"checking cdn name %v existence\", *profile.CDNName)\n\t\t\tlog.Errorf(\"%v: %v\", errString, err.Error())\n\t\t\terrs = append(errs, errors.New(errString))\n\t\t} else if !ok {\n\t\t\terrs = append(errs, fmt.Errorf(\"%v CDN does not exist\", *profile.CDNName))\n\t\t}\n\t}\n\n\t// Validate profile does not already exist\n\tif profile.Name != nil {\n\t\tif ok, err := ProfileExistsByName(*profile.Name, tx); err != nil {\n\t\t\terrString := fmt.Sprintf(\"checking profile name %v existence\", *profile.Name)\n\t\t\tlog.Errorf(\"%v: %v\", errString, err.Error())\n\t\t\terrs = append(errs, errors.New(errString))\n\t\t} else if ok {\n\t\t\terrs = append(errs, fmt.Errorf(\"a profile with the name \\\"%s\\\" already exists\", *profile.Name))\n\t\t}\n\t}\n\n\t// Validate all parameters\n\t// export/import does not include secure flag\n\t// default value to not flag on validation\n\tsecure := 1\n\tfor i, pp := range profileImport.Parameters {\n\t\tif ppErrs := validateProfileParamPostFields(pp.ConfigFile, pp.Name, pp.Value, &secure); len(ppErrs) > 0 {\n\t\t\tfor _, err := range ppErrs {\n\t\t\t\terrs = append(errs, errors.New(\"parameter \"+strconv.Itoa(i)+\": \"+err.Error()))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errs) > 0 {\n\t\treturn util.JoinErrs(errs)\n\t}\n\n\treturn nil\n}", "func (u *Usecase) validFields(d *Device) error {\n\tif d.Name == \"\" {\n\t\treturn &InvalidError{\"attribute `Name` must not be empty\"}\n\t}\n\n\tif d.User == 0 {\n\t\treturn &InvalidError{\"invalid user\"}\n\t}\n\n\treturn nil\n}", "func (t *TokenAccount) Validate() error {\n\tv := validator.New()\n\terr := v.RegisterValidation(\"notblank\", validators.NotBlank)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = v.RegisterValidation(\"notall\", validation.NotAll)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn v.Struct(t)\n}", "func (v *Reg) Validate(ctx context.Context, f *reg.Form) error {\n\tvar es Errors\n\n\tif err := validation.Validate(f.Email, validation.Required, is.Email); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"email\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := validation.Validate(f.AccountID, validation.Required); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"account_id\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := v.Uniquer.Unique(ctx, f.Email); err != nil {\n\t\tswitch errors.Cause(err) {\n\t\tcase reg.ErrEmailExists:\n\t\t\tes = append(es, Error{\n\t\t\t\tField: \"email\",\n\t\t\t\tMessage: err.Error(),\n\t\t\t})\n\t\tdefault:\n\t\t\treturn errors.Wrap(err, \"unique\")\n\t\t}\n\t}\n\n\tfmt.Println(f.Password, f.PasswordConfirmation)\n\n\tif err := validation.Validate(f.Password, validation.Required, validation.Length(6, 32)); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"password\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif err := validation.Validate(f.PasswordConfirmation, validation.Required, validation.Length(6, 32)); err != nil {\n\t\tes = append(es, Error{\n\t\t\tField: \"password_confirmation\",\n\t\t\tMessage: err.Error(),\n\t\t})\n\t}\n\n\tif f.Password != f.PasswordConfirmation {\n\t\tes = append(es, Error{\n\t\t\tField: \"password_confirmation\",\n\t\t\tMessage: \"mismatch\",\n\t\t}, Error{\n\t\t\tField: \"password\",\n\t\t\tMessage: \"mismatch\",\n\t\t})\n\t}\n\n\tif len(es) > 0 {\n\t\treturn es\n\t}\n\n\treturn nil\n}", "func validateAccountName(accountName string) (string, error) {\n\treturn accountName, nil\n}", "func (rcv *controller) validate() error {\n\n\tif err := rcv.read(); err != nil {\n\t\treturn err\n\t}\n\n\t// If account does not exists\n\tif rcv.store.Email == \"\" {\n\t\treturn errors.New(rcv.Translate(\"text11\"))\n\t}\n\n\t// If time for activating account is expired\n\tif time.Now().Unix() > rcv.store.Expired {\n\t\t// Delete registered user from neo4j\n\t\tmaccount.Delete(rcv.store.Email, rcv.Local)\n\t\treturn &expiredError{rcv.Controller}\n\t}\n\n\treturn nil\n}", "func (acc *AccessControlCreate) check() error {\n\tif _, ok := acc.mutation.ServiceID(); !ok {\n\t\treturn &ValidationError{Name: \"service_id\", err: errors.New(\"ent: missing required field \\\"service_id\\\"\")}\n\t}\n\tif _, ok := acc.mutation.OpenAuth(); !ok {\n\t\treturn &ValidationError{Name: \"open_auth\", err: errors.New(\"ent: missing required field \\\"open_auth\\\"\")}\n\t}\n\tif _, ok := acc.mutation.BlackList(); !ok {\n\t\treturn &ValidationError{Name: \"black_list\", err: errors.New(\"ent: missing required field \\\"black_list\\\"\")}\n\t}\n\tif _, ok := acc.mutation.WhiteList(); !ok {\n\t\treturn &ValidationError{Name: \"white_list\", err: errors.New(\"ent: missing required field \\\"white_list\\\"\")}\n\t}\n\tif _, ok := acc.mutation.WhiteHostName(); !ok {\n\t\treturn &ValidationError{Name: \"white_host_name\", err: errors.New(\"ent: missing required field \\\"white_host_name\\\"\")}\n\t}\n\tif _, ok := acc.mutation.ClientipFlowLimit(); !ok {\n\t\treturn &ValidationError{Name: \"clientip_flow_limit\", err: errors.New(\"ent: missing required field \\\"clientip_flow_limit\\\"\")}\n\t}\n\tif _, ok := acc.mutation.ServiceFlowLimit(); !ok {\n\t\treturn &ValidationError{Name: \"service_flow_limit\", err: errors.New(\"ent: missing required field \\\"service_flow_limit\\\"\")}\n\t}\n\treturn nil\n}", "func (u *User) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\tvar err error\n\t//validate based on is agent\n\tif !u.IsAgent { //is not an agent\n\t\treturn validate.Validate(\n\t\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t\t&validators.StringIsPresent{Field: u.PasswordHash, Name: \"PasswordHash\"},\n\t\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t\t&validators.StringIsPresent{Field: u.Phone, Name: \"Phone\"},\n\t\t\t// check to see if the email address is already taken:\n\t\t\t&validators.FuncValidator{\n\t\t\t\tField: u.Email,\n\t\t\t\tName: \"Email\",\n\t\t\t\tMessage: \"%s is already taken\",\n\t\t\t\tFn: func() bool {\n\t\t\t\t\tvar b bool\n\t\t\t\t\tq := tx.Where(\"email = ?\", u.Email)\n\t\t\t\t\tif u.ID != uuid.Nil {\n\t\t\t\t\t\tq = q.Where(\"id != ?\", u.ID)\n\t\t\t\t\t}\n\t\t\t\t\tb, err = q.Exists(u)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\treturn !b\n\t\t\t\t},\n\t\t\t},\n\t\t), err\n\n\t} else { // trying to save agent\n\t\treturn validate.Validate(\n\t\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t\t&validators.StringIsPresent{Field: u.PasswordHash, Name: \"PasswordHash\"},\n\t\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t\t&validators.StringIsPresent{Field: u.Phone, Name: \"Phone\"},\n\t\t\t&validators.StringIsPresent{Field: u.PublicEmail.String, Name: \"PublicEmail\"},\n\t\t\t&validators.StringIsPresent{Field: u.Company.String, Name: \"Company\"},\n\t\t\t&validators.StringIsPresent{Field: u.Address1.String, Name: \"Address1\"},\n\t\t\t&validators.StringIsPresent{Field: u.City.String, Name: \"City\"},\n\t\t\t&validators.StringIsPresent{Field: u.State.String, Name: \"State\"},\n\t\t\t&validators.StringIsPresent{Field: u.Zipcode.String, Name: \"Zipcode\"},\n\t\t\t// check to see if the email address is already taken:\n\t\t\t&validators.FuncValidator{\n\t\t\t\tField: u.Email,\n\t\t\t\tName: \"Email\",\n\t\t\t\tMessage: \"%s is already taken\",\n\t\t\t\tFn: func() bool {\n\t\t\t\t\tvar b bool\n\t\t\t\t\tq := tx.Where(\"email = ?\", u.Email)\n\t\t\t\t\tif u.ID != uuid.Nil {\n\t\t\t\t\t\tq = q.Where(\"id != ?\", u.ID)\n\t\t\t\t\t}\n\t\t\t\t\tb, err = q.Exists(u)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\treturn !b\n\t\t\t\t},\n\t\t\t},\n\t\t), err\n\n\t}\n}", "func IsValidAccount(a string) bool {\n\t_, err := NewAccount(a)\n\treturn err == nil\n}", "func (u User) IsValid() []error{\n\tvar errs []error\n\tfirstname := strings.Trim(u.FirstName, \" \")\n\tlastname := strings.Trim(u.LastName, \" \")\n\n\tif firstname != \"\" {\n\t\tif strings.Contains(firstname, \" \"){\n\t\t\terrs = append(errs, errors.New(\"FirstName can't have spaces\"))\n\t\t}\n\t\tif len(firstname) < 2 {\n\t\t\terrs = append(errs, errors.New(\"FirstName must be at least 2 characters\"))\n\t\t}\n\t\tif !helper.IsLetter(firstname) {\n\t\t\terrs = append(errs, errors.New(\"Firstname contains a number\"))\n\t\t}\n\t}\n\n\tif lastname != \"\"{\n\t\tif strings.Contains(lastname, \" \"){\n\t\t\terrs = append(errs, errors.New(\"LastName can't have spaces\"))\n\t\t}\n\n\t\tif len(lastname) < 2 {\n\t\t\terrs = append(errs, errors.New(\"LastName must be at least 2 characters\"))\n\t\t}\n\n\t\tif !helper.IsLetter(lastname) {\n\t\t\terrs = append(errs, errors.New(\"Lastname contains a number\"))\n\t\t}\n\t}\n\n\tif u.Email != \"\" {\n\t\tre := regexp.MustCompile(\"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\")\n\n\t\tif !re.MatchString(u.Email) {\n\t\t\terrs = append(errs, errors.New(\"Email address is not valid\"))\n\t\t}\n\t}\n\n\n\tyear, _, _, _, _, _ := helper.DateDiff(u.DateOfBirth, time.Now())\n\tif year < 18 {\n\t\terrs = append(errs, errors.New(\"You must be 18 or more\"))\n\t}\n\tif len(errs) > 0 {\n\t\treturn errs\n\t}\n\treturn nil\n}", "func (m *BillingProfiles2) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAdviceOfCharge(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateCurrency(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyLimit(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyLock(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudDailyNotify(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalLimit(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalLock(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudIntervalNotify(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudUseResellerRates(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateHandle(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalCharge(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalFreeCash(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIntervalFreeTime(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePeaktimeSpecial(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePeaktimeWeekdays(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrepaid(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePrepaidLibrary(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateResellerID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *conversionOptions) validate() error {\r\n\tif o.goalID == 0 && len(o.goalName) == 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute(s): %s or %s\", fieldID, fieldName)\r\n\t} else if o.goalID == 0 && o.tonicPowUserID > 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute: %s\", fieldID)\r\n\t} else if o.tonicPowUserID == 0 && len(o.tncpwSession) == 0 {\r\n\t\treturn fmt.Errorf(\"missing required attribute(s): %s or %s\", fieldVisitorSessionGUID, fieldUserID)\r\n\t}\r\n\treturn nil\r\n}", "func (m *CustomerTripletexAccount2) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAccountType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateAdministrator(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateChartOfAccountsType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateModules(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVatStatusType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (bva BaseVestingAccount) Validate() error {\n\tif !(bva.DelegatedVesting.IsAllLTE(bva.OriginalVesting)) {\n\t\treturn errors.New(\"delegated vesting amount cannot be greater than original vesting amount\")\n\t}\n\treturn bva.BaseAccount.Validate()\n}", "func (uuo *UserUpdateOne) check() error {\n\tif v, ok := uuo.mutation.AccountName(); ok {\n\t\tif err := user.AccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"account_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"account_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.StaffType(); ok {\n\t\tif err := user.StaffTypeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_type\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_type\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.FamilyName(); ok {\n\t\tif err := user.FamilyNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"family_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"family_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.GivenName(); ok {\n\t\tif err := user.GivenNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"given_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"given_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.DisplayName(); ok {\n\t\tif err := user.DisplayNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"display_name\", err: fmt.Errorf(\"ent: validator failed for field \\\"display_name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.IDNumber(); ok {\n\t\tif err := user.IDNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"id_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Sex(); ok {\n\t\tif err := user.SexValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"sex\", err: fmt.Errorf(\"ent: validator failed for field \\\"sex\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.PhoneNumber(); ok {\n\t\tif err := user.PhoneNumberValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone_number\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone_number\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Address(); ok {\n\t\tif err := user.AddressValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"address\", err: fmt.Errorf(\"ent: validator failed for field \\\"address\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.StaffID(); ok {\n\t\tif err := user.StaffIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"staff_id\", err: fmt.Errorf(\"ent: validator failed for field \\\"staff_id\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.PersonalEmail(); ok {\n\t\tif err := user.PersonalEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"personal_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"personal_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.IntranetWorkEmail(); ok {\n\t\tif err := user.IntranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"intranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.ExtranetWorkEmail(); ok {\n\t\tif err := user.ExtranetWorkEmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"extranet_work_email\", err: fmt.Errorf(\"ent: validator failed for field \\\"extranet_work_email\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (m *DomainDiscoverAPIAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCid(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (msg MsgAddAdminAccount) ValidateBasic() sdk.Error {\n if msg.AdminAddress.Empty() {\n return sdk.ErrInvalidAddress(msg.AdminAddress.String())\n }\n if msg.Owner.Empty() {\n return sdk.ErrInvalidAddress(msg.Owner.String())\n }\n return nil\n}", "func init() {\n\taccountFields := schema.Account{}.Fields()\n\t_ = accountFields\n\t// accountDescProvider is the schema descriptor for provider field.\n\taccountDescProvider := accountFields[1].Descriptor()\n\t// account.ProviderValidator is a validator for the \"provider\" field. It is called by the builders before save.\n\taccount.ProviderValidator = accountDescProvider.Validators[0].(func(string) error)\n\t// accountDescEmail is the schema descriptor for email field.\n\taccountDescEmail := accountFields[2].Descriptor()\n\t// account.EmailValidator is a validator for the \"email\" field. It is called by the builders before save.\n\taccount.EmailValidator = accountDescEmail.Validators[0].(func(string) error)\n\t// accountDescPassword is the schema descriptor for password field.\n\taccountDescPassword := accountFields[3].Descriptor()\n\t// account.PasswordValidator is a validator for the \"password\" field. It is called by the builders before save.\n\taccount.PasswordValidator = func() func(string) error {\n\t\tvalidators := accountDescPassword.Validators\n\t\tfns := [...]func(string) error{\n\t\t\tvalidators[0].(func(string) error),\n\t\t\tvalidators[1].(func(string) error),\n\t\t}\n\t\treturn func(password string) error {\n\t\t\tfor _, fn := range fns {\n\t\t\t\tif err := fn(password); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}()\n\t// accountDescLocked is the schema descriptor for locked field.\n\taccountDescLocked := accountFields[4].Descriptor()\n\t// account.DefaultLocked holds the default value on creation for the locked field.\n\taccount.DefaultLocked = accountDescLocked.Default.(bool)\n\t// accountDescConfirmed is the schema descriptor for confirmed field.\n\taccountDescConfirmed := accountFields[5].Descriptor()\n\t// account.DefaultConfirmed holds the default value on creation for the confirmed field.\n\taccount.DefaultConfirmed = accountDescConfirmed.Default.(bool)\n\t// accountDescConfirmationToken is the schema descriptor for confirmation_token field.\n\taccountDescConfirmationToken := accountFields[7].Descriptor()\n\t// account.ConfirmationTokenValidator is a validator for the \"confirmation_token\" field. It is called by the builders before save.\n\taccount.ConfirmationTokenValidator = accountDescConfirmationToken.Validators[0].(func(string) error)\n\t// accountDescRecoveryToken is the schema descriptor for recovery_token field.\n\taccountDescRecoveryToken := accountFields[9].Descriptor()\n\t// account.RecoveryTokenValidator is a validator for the \"recovery_token\" field. It is called by the builders before save.\n\taccount.RecoveryTokenValidator = accountDescRecoveryToken.Validators[0].(func(string) error)\n\t// accountDescOtp is the schema descriptor for otp field.\n\taccountDescOtp := accountFields[11].Descriptor()\n\t// account.OtpValidator is a validator for the \"otp\" field. It is called by the builders before save.\n\taccount.OtpValidator = accountDescOtp.Validators[0].(func(string) error)\n\t// accountDescEmailChange is the schema descriptor for email_change field.\n\taccountDescEmailChange := accountFields[12].Descriptor()\n\t// account.EmailChangeValidator is a validator for the \"email_change\" field. It is called by the builders before save.\n\taccount.EmailChangeValidator = accountDescEmailChange.Validators[0].(func(string) error)\n\t// accountDescEmailChangeToken is the schema descriptor for email_change_token field.\n\taccountDescEmailChangeToken := accountFields[14].Descriptor()\n\t// account.EmailChangeTokenValidator is a validator for the \"email_change_token\" field. It is called by the builders before save.\n\taccount.EmailChangeTokenValidator = accountDescEmailChangeToken.Validators[0].(func(string) error)\n\t// accountDescCreatedAt is the schema descriptor for created_at field.\n\taccountDescCreatedAt := accountFields[18].Descriptor()\n\t// account.DefaultCreatedAt holds the default value on creation for the created_at field.\n\taccount.DefaultCreatedAt = accountDescCreatedAt.Default.(func() time.Time)\n\t// accountDescUpdatedAt is the schema descriptor for updated_at field.\n\taccountDescUpdatedAt := accountFields[19].Descriptor()\n\t// account.DefaultUpdatedAt holds the default value on creation for the updated_at field.\n\taccount.DefaultUpdatedAt = accountDescUpdatedAt.Default.(func() time.Time)\n\t// account.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.\n\taccount.UpdateDefaultUpdatedAt = accountDescUpdatedAt.UpdateDefault.(func() time.Time)\n\t// accountDescID is the schema descriptor for id field.\n\taccountDescID := accountFields[0].Descriptor()\n\t// account.DefaultID holds the default value on creation for the id field.\n\taccount.DefaultID = accountDescID.Default.(func() uuid.UUID)\n\tsessionFields := schema.Session{}.Fields()\n\t_ = sessionFields\n\t// sessionDescCreatedAt is the schema descriptor for created_at field.\n\tsessionDescCreatedAt := sessionFields[2].Descriptor()\n\t// session.DefaultCreatedAt holds the default value on creation for the created_at field.\n\tsession.DefaultCreatedAt = sessionDescCreatedAt.Default.(func() time.Time)\n\t// sessionDescUpdatedAt is the schema descriptor for updated_at field.\n\tsessionDescUpdatedAt := sessionFields[3].Descriptor()\n\t// session.DefaultUpdatedAt holds the default value on creation for the updated_at field.\n\tsession.DefaultUpdatedAt = sessionDescUpdatedAt.Default.(func() time.Time)\n\t// session.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.\n\tsession.UpdateDefaultUpdatedAt = sessionDescUpdatedAt.UpdateDefault.(func() time.Time)\n}", "func (mt AccountCollection) Validate() (err error) {\n\tfor _, e := range mt {\n\t\tif e != nil {\n\t\t\tif err2 := e.Validate(); err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, err2)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (frm entryForm) Validate() (map[string]string, bool) {\n\terrs := map[string]string{}\n\tg1 := frm.Department != \"\"\n\tif !g1 {\n\t\terrs[\"department\"] = \"Missing department\"\n\t}\n\tg2 := frm.CheckThis\n\tif !g2 {\n\t\terrs[\"check_this\"] = \"You need to comply\"\n\t}\n\tg3 := frm.Items != \"\"\n\tif !g3 {\n\t\terrs[\"items\"] = \"No items\"\n\t}\n\treturn errs, g1 && g2 && g3\n}", "func (vva ValidatorVestingAccount) Validate() error {\n\tif vva.SigningThreshold > 100 || vva.SigningThreshold < 0 {\n\t\treturn errors.New(\"signing threshold must be between 0 and 100\")\n\t}\n\tif vva.ReturnAddress.Equals(vva.Address) {\n\t\treturn errors.New(\"return address cannot be the same as the account address\")\n\t}\n\treturn vva.PeriodicVestingAccount.Validate()\n}", "func (dva DelayedVestingAccount) Validate() error {\n\treturn dva.BaseVestingAccount.Validate()\n}", "func validate(msgs []*LogMsg) {\n\tif !validatePRAMRegistration(msgs) {\n\t\tlog.Fatalf(\"validatePRAMRegistration\\n\")\n\t}\n}", "func (_PermInterface *PermInterfaceCaller) ValidateAccount(opts *bind.CallOpts, _account common.Address, _orgId string) (bool, error) {\n\tvar out []interface{}\n\terr := _PermInterface.contract.Call(opts, &out, \"validateAccount\", _account, _orgId)\n\n\tif err != nil {\n\t\treturn *new(bool), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(bool)).(*bool)\n\n\treturn out0, err\n\n}", "func (ut *RegisterPayload) Validate() (err error) {\n\tif ut.Email == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"email\"))\n\t}\n\tif ut.Password == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"password\"))\n\t}\n\tif ut.FirstName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"first_name\"))\n\t}\n\tif ut.LastName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"last_name\"))\n\t}\n\tif err2 := goa.ValidateFormat(goa.FormatEmail, ut.Email); err2 != nil {\n\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`type.email`, ut.Email, goa.FormatEmail, err2))\n\t}\n\tif utf8.RuneCountInString(ut.Email) < 6 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 6, true))\n\t}\n\tif utf8.RuneCountInString(ut.Email) > 150 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 150, false))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.Password) < 5 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 5, true))\n\t}\n\tif utf8.RuneCountInString(ut.Password) > 100 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 100, false))\n\t}\n\treturn\n}", "func (a *Api) validateError() (err error) {\n\tif a.UserID == 0 {\n\t\treturn a.Errors(ErrorMissingValue, \"user_id\")\n\t}\n\n\tif a.Token == \"\" {\n\t\treturn a.Errors(ErrorMissingValue, \"token\")\n\t}\n\n\treturn\n}", "func (uc *UserCreate) check() error {\n\tif _, ok := uc.mutation.Firstname(); !ok {\n\t\treturn &ValidationError{Name: \"firstname\", err: errors.New(\"ent: missing required field \\\"firstname\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Lastname(); !ok {\n\t\treturn &ValidationError{Name: \"lastname\", err: errors.New(\"ent: missing required field \\\"lastname\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Username(); !ok {\n\t\treturn &ValidationError{Name: \"username\", err: errors.New(\"ent: missing required field \\\"username\\\"\")}\n\t}\n\tif _, ok := uc.mutation.Password(); !ok {\n\t\treturn &ValidationError{Name: \"password\", err: errors.New(\"ent: missing required field \\\"password\\\"\")}\n\t}\n\treturn nil\n}", "func (ac *AreahistoryCreate) check() error {\n\tif _, ok := ac.mutation.WalletID(); !ok {\n\t\treturn &ValidationError{Name: \"WalletID\", err: errors.New(\"ent: missing required field \\\"WalletID\\\"\")}\n\t}\n\tif v, ok := ac.mutation.WalletID(); ok {\n\t\tif err := areahistory.WalletIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"WalletID\", err: fmt.Errorf(\"ent: validator failed for field \\\"WalletID\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.ProvinceNameTH(); ok {\n\t\tif err := areahistory.ProvinceNameTHValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"ProvinceNameTH\", err: fmt.Errorf(\"ent: validator failed for field \\\"ProvinceNameTH\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.DistrictNameTH(); ok {\n\t\tif err := areahistory.DistrictNameTHValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"DistrictNameTH\", err: fmt.Errorf(\"ent: validator failed for field \\\"DistrictNameTH\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := ac.mutation.SubDistrict(); ok {\n\t\tif err := areahistory.SubDistrictValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"SubDistrict\", err: fmt.Errorf(\"ent: validator failed for field \\\"SubDistrict\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (_PermInterface *PermInterfaceSession) ValidateAccount(_account common.Address, _orgId string) (bool, error) {\n\treturn _PermInterface.Contract.ValidateAccount(&_PermInterface.CallOpts, _account, _orgId)\n}", "func (uu *UserUpdate) check() error {\n\tif v, ok := uu.mutation.Username(); ok {\n\t\tif err := user.UsernameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"username\", err: fmt.Errorf(\"ent: validator failed for field \\\"username\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Fullname(); ok {\n\t\tif err := user.FullnameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"fullname\", err: fmt.Errorf(\"ent: validator failed for field \\\"fullname\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Password(); ok {\n\t\tif err := user.PasswordValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"password\", err: fmt.Errorf(\"ent: validator failed for field \\\"password\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Email(); ok {\n\t\tif err := user.EmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"email\", err: fmt.Errorf(\"ent: validator failed for field \\\"email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Phone(); ok {\n\t\tif err := user.PhoneValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Bio(); ok {\n\t\tif err := user.BioValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"bio\", err: fmt.Errorf(\"ent: validator failed for field \\\"bio\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Intro(); ok {\n\t\tif err := user.IntroValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intro\", err: fmt.Errorf(\"ent: validator failed for field \\\"intro\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.GithubProfile(); ok {\n\t\tif err := user.GithubProfileValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"github_profile\", err: fmt.Errorf(\"ent: validator failed for field \\\"github_profile\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.ProfilePictureURL(); ok {\n\t\tif err := user.ProfilePictureURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"profile_picture_url\", err: fmt.Errorf(\"ent: validator failed for field \\\"profile_picture_url\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uu.mutation.Status(); ok {\n\t\tif err := user.StatusValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"status\", err: fmt.Errorf(\"ent: validator failed for field \\\"status\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (uc *UserCreate) check() error {\n\tif _, ok := uc.mutation.Age(); !ok {\n\t\treturn &ValidationError{Name: \"age\", err: errors.New(\"ent: missing required field \\\"age\\\"\")}\n\t}\n\tif v, ok := uc.mutation.Age(); ok {\n\t\tif err := user.AgeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"age\", err: fmt.Errorf(\"ent: validator failed for field \\\"age\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := uc.mutation.Name(); !ok {\n\t\treturn &ValidationError{Name: \"name\", err: errors.New(\"ent: missing required field \\\"name\\\"\")}\n\t}\n\tif v, ok := uc.mutation.ID(); ok {\n\t\tif err := user.IDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"id\", err: fmt.Errorf(\"ent: validator failed for field \\\"id\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (p *PaymentNeed) validate() error {\n\tif p.BeneficiaryID == 0 {\n\t\treturn fmt.Errorf(\"beneficiary ID nul\")\n\t}\n\tif p.Value == 0 {\n\t\treturn fmt.Errorf(\"value nul\")\n\t}\n\treturn nil\n}", "func (r *Result) validate(errMsg *[]string, parentField string) {\n\tjn := resultJsonMap\n\taddErrMessage(errMsg, len(r.Key) > 0 && hasNonEmptyKV(r.Key), \"field '%s' must be non-empty and must not have empty keys or values\", parentField+\".\"+jn[\"Key\"])\n\taddErrMessage(errMsg, hasNonEmptyKV(r.Options), \"field '%s' must not have empty keys or values\", parentField+\".\"+jn[\"Options\"])\n\taddErrMessage(errMsg, regExHexadecimal.MatchString(string(r.Digest)), \"field '%s' must be hexadecimal\", parentField+\".\"+jn[\"Digest\"])\n}", "func CheckAccountResponse(t *testing.T, resp *models.Account, expectedAccount *models.Account) {\n\tif resp.ID != expectedAccount.ID {\n\t\tt.Errorf(\"Response contains wrong ID, got %v expected %v\", resp.ID, expectedAccount.ID)\n\t}\n\tif resp.Type != expectedAccount.Type {\n\t\tt.Errorf(\"Response contains wrong Type, got %v expected %v\", resp.Type, expectedAccount.Type)\n\t}\n\tif resp.OrganisationID != expectedAccount.OrganisationID {\n\t\tt.Errorf(\"Response contains wrong OrganisationID, got %v expected %v\", resp.OrganisationID, expectedAccount.OrganisationID)\n\t}\n\tif resp.Version != expectedAccount.Version {\n\t\tt.Errorf(\"Response contains wrong Version, got %v expected %v\", resp.Version, expectedAccount.Version)\n\t}\n\tif resp.Attributes.Country != expectedAccount.Attributes.Country {\n\t\tt.Errorf(\"Response contains wrong Country, got %v expected %v\", resp.Attributes.Country, expectedAccount.Attributes.Country)\n\t}\n\tif resp.Attributes.BaseCurrency != expectedAccount.Attributes.BaseCurrency {\n\t\tt.Errorf(\"Response contains wrong BaseCurrency, got %v expected %v\", resp.Attributes.BaseCurrency, expectedAccount.Attributes.BaseCurrency)\n\t}\n\tif resp.Attributes.BankID != expectedAccount.Attributes.BankID {\n\t\tt.Errorf(\"Response contains wrong BankID, got %v expected %v\", resp.Attributes.BankID, expectedAccount.Attributes.BankID)\n\t}\n\tif resp.Attributes.BankIDCode != expectedAccount.Attributes.BankIDCode {\n\t\tt.Errorf(\"Response contains wrong BankIDCode, got %v expected %v\", resp.Attributes.BankIDCode, expectedAccount.Attributes.BankIDCode)\n\t}\n\tif resp.Attributes.Bic != expectedAccount.Attributes.Bic {\n\t\tt.Errorf(\"Response contains wrong Bic, got %v expected %v\", resp.Attributes.Bic, expectedAccount.Attributes.Bic)\n\t}\n\tif resp.Attributes.AccountNumber != expectedAccount.Attributes.AccountNumber {\n\t\tt.Errorf(\"Response contains wrong AccountNumber, got %v expected %v\", resp.Attributes.AccountNumber, expectedAccount.Attributes.AccountNumber)\n\t}\n\tif resp.Attributes.CustomerID != expectedAccount.Attributes.CustomerID {\n\t\tt.Errorf(\"Response contains wrong CustomerID, got %v expected %v\", resp.Attributes.CustomerID, expectedAccount.Attributes.CustomerID)\n\t}\n\tif resp.Attributes.FirstName != expectedAccount.Attributes.FirstName {\n\t\tt.Errorf(\"Response contains wrong FirstName, got %v expected %v\", resp.Attributes.FirstName, expectedAccount.Attributes.FirstName)\n\t}\n\tif resp.Attributes.BankAccountName != expectedAccount.Attributes.BankAccountName {\n\t\tt.Errorf(\"Response contains wrong BankAccountName, got %v expected %v\", resp.Attributes.BankAccountName, expectedAccount.Attributes.BankAccountName)\n\t}\n\n\tresponseLength := len(resp.Attributes.AlternativeBankAccountNames)\n\texpectedLength := len(expectedAccount.Attributes.AlternativeBankAccountNames)\n\n\tif responseLength != expectedLength {\n\t\tt.Errorf(\"AlternativeBankAccountNames array is wrong, got %v expected %v\", responseLength, expectedLength)\n\t} else {\n\t\ti := 0\n\t\tfor i < responseLength {\n\t\t\tif resp.Attributes.AlternativeBankAccountNames[i] != expectedAccount.Attributes.AlternativeBankAccountNames[i] {\n\t\t\t\tt.Errorf(\"Response contains wrong AlternativeBankAccountNames, got %v expected %v\", resp.Attributes.AlternativeBankAccountNames[i], expectedAccount.Attributes.AlternativeBankAccountNames[i])\n\t\t\t}\n\t\t\ti = i + 1\n\t\t}\n\t}\n\n\tif resp.Attributes.AlternativeBankAccountNames[0] != expectedAccount.Attributes.AlternativeBankAccountNames[0] {\n\t\tt.Errorf(\"Response contains wrong AlternativeBankAccountNames, got %v expected %v\", resp.Attributes.AlternativeBankAccountNames[0], expectedAccount.Attributes.AlternativeBankAccountNames[0])\n\t}\n\tif resp.Attributes.AccountClassification != expectedAccount.Attributes.AccountClassification {\n\t\tt.Errorf(\"Response contains wrong AccountClassification, got %v expected %v\", resp.Attributes.AccountClassification, expectedAccount.Attributes.AccountClassification)\n\t}\n\tif resp.Attributes.JointAccount != expectedAccount.Attributes.JointAccount {\n\t\tt.Errorf(\"Response contains wrong JointAccount, got %v expected %v\", resp.Attributes.JointAccount, expectedAccount.Attributes.JointAccount)\n\t}\n\tif resp.Attributes.Switched != expectedAccount.Attributes.Switched {\n\t\tt.Errorf(\"Response contains wrong Switched, got %v expected %v\", resp.Attributes.Switched, expectedAccount.Attributes.Switched)\n\t}\n\tif resp.Attributes.AccountMatchingOptOut != expectedAccount.Attributes.AccountMatchingOptOut {\n\t\tt.Errorf(\"Response contains wrong AccountMatchingOptOut, got %v expected %v\", resp.Attributes.AccountMatchingOptOut, expectedAccount.Attributes.AccountMatchingOptOut)\n\t}\n\tif resp.Attributes.Status != expectedAccount.Attributes.Status {\n\t\tt.Errorf(\"Response contains wrong Status, got %v expected %v\", resp.Attributes.Status, expectedAccount.Attributes.Status)\n\t}\n\tif resp.Attributes.SecondaryIdentification != expectedAccount.Attributes.SecondaryIdentification {\n\t\tt.Errorf(\"Response contains wrong SecondaryIdentification, got %v expected %v\", resp.Attributes.SecondaryIdentification, expectedAccount.Attributes.SecondaryIdentification)\n\t}\n}", "func (_PermInterface *PermInterfaceCallerSession) ValidateAccount(_account common.Address, _orgId string) (bool, error) {\n\treturn _PermInterface.Contract.ValidateAccount(&_PermInterface.CallOpts, _account, _orgId)\n}", "func (cfg fromCFN) validate() error {\n\tif cfg.isEmpty() {\n\t\treturn nil\n\t}\n\tif len(aws.StringValue(cfg.Name)) == 0 {\n\t\treturn errors.New(\"name cannot be an empty string\")\n\t}\n\treturn nil\n}", "func isAccountFlagsValid(accountId string) bool {\n\taccount := GetStellarAccount(accountId)\n\treturn account.Flags.AuthRequired && account.Flags.AuthRevocable\n}", "func validate(name, gender string) error {\n\tif name == \"\" {\n\t\treturn &inputError{message: \"name is missing\", missingField: \"name\"}\n\t}\n\tif gender == \"\" {\n\t\treturn &inputError{message: \"gender is missing\", missingField: \"gender\"}\n\t}\n\treturn nil\n}", "func (user *User) Validate() *errors.RestErr {\n\t// Delete spaces at first_name, last_name and email before saving\n\tuser.FirstName = strings.TrimSpace(user.FirstName)\n\tuser.LastName = strings.TrimSpace(user.LastName)\n\tuser.Email = strings.TrimSpace(strings.ToLower(user.Email))\n\n\tif user.Email == \"\"{\n\t\treturn errors.NewBadRequestError(\"Email addres is required\")\n\t}\n\tif !ValidateEmail(user.Email){\n\t\treturn errors.NewBadRequestError(\"Wrong email format\")\n\t}\n\tif strings.TrimSpace(user.Password)== \"\" || len(strings.TrimSpace(user.Password)) < 8{\n\t\treturn errors.NewBadRequestError(\"Password is required and password length must be higher than 8 characters\")\n\t}\n\n\n\treturn nil\n}", "func checkAccount(t *testing.T, tree *avl.Tree, id AccountID, expectedBalance, expectedReward, expectedStake *uint64) {\n\tvar balance, reward, stake uint64\n\tvar exist bool\n\n\tbalance, exist = ReadAccountBalance(tree, id)\n\tassert.Equal(t, expectedBalance != nil, exist, \"account ID: %x\", id)\n\treward, exist = ReadAccountReward(tree, id)\n\tassert.Equal(t, expectedReward != nil, exist, \"account ID: %x\", id)\n\tstake, exist = ReadAccountStake(tree, id)\n\tassert.Equal(t, expectedStake != nil, exist, \"account ID: %x\", id)\n\n\tif expectedBalance != nil {\n\t\tassert.Equal(t, balance, *expectedBalance, \"account ID: %x\", id)\n\t}\n\n\tif expectedReward != nil {\n\t\tassert.Equal(t, reward, *expectedReward, \"account ID: %x\", id)\n\t}\n\n\tif expectedStake != nil {\n\t\tassert.Equal(t, stake, *expectedStake, \"account ID: %x\", id)\n\t}\n}", "func ValidBaseInfo(ctx *gin.Context) {\n\tres := helper.Res{}\n\n\tvar baseInfo BaseInfo\n\tif err := ctx.Bind(&baseInfo); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\t// user does exist\n\tif _, err := models.FindOneByUsername(baseInfo.Username); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\t// the email of user does exist\n\tif _, err := models.FindOneByEmail(baseInfo.Email); err != nil {\n\t\tres.Status(http.StatusBadRequest).Error(err).Send(ctx)\n\t\treturn\n\t}\n\n\tres.Success(gin.H{\n\t\t\"isValid\": true,\n\t}).Send(ctx)\n}", "func (w Warrant) Validate() error {\n\tif len(w.FirstName) == 0 {\n\t\treturn errors.New(\"missing first name element\")\n\t}\n\tif len(w.LastName) == 0 {\n\t\treturn errors.New(\"missing last name element\")\n\t}\n\tif len(w.Civility) == 0 {\n\t\treturn errors.New(\"missing civility element\")\n\t}\n\treturn nil\n}", "func (ut *registerPayload) Validate() (err error) {\n\tif ut.Email == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"email\"))\n\t}\n\tif ut.Password == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"password\"))\n\t}\n\tif ut.FirstName == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"first_name\"))\n\t}\n\tif ut.LastName == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"last_name\"))\n\t}\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`request.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Email != nil {\n\t\tif utf8.RuneCountInString(*ut.Email) < 6 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.email`, *ut.Email, utf8.RuneCountInString(*ut.Email), 6, true))\n\t\t}\n\t}\n\tif ut.Email != nil {\n\t\tif utf8.RuneCountInString(*ut.Email) > 150 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.email`, *ut.Email, utf8.RuneCountInString(*ut.Email), 150, false))\n\t\t}\n\t}\n\tif ut.FirstName != nil {\n\t\tif utf8.RuneCountInString(*ut.FirstName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.first_name`, *ut.FirstName, utf8.RuneCountInString(*ut.FirstName), 1, true))\n\t\t}\n\t}\n\tif ut.FirstName != nil {\n\t\tif utf8.RuneCountInString(*ut.FirstName) > 200 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.first_name`, *ut.FirstName, utf8.RuneCountInString(*ut.FirstName), 200, false))\n\t\t}\n\t}\n\tif ut.LastName != nil {\n\t\tif utf8.RuneCountInString(*ut.LastName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.last_name`, *ut.LastName, utf8.RuneCountInString(*ut.LastName), 1, true))\n\t\t}\n\t}\n\tif ut.LastName != nil {\n\t\tif utf8.RuneCountInString(*ut.LastName) > 200 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.last_name`, *ut.LastName, utf8.RuneCountInString(*ut.LastName), 200, false))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) < 5 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 5, true))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) > 100 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 100, false))\n\t\t}\n\t}\n\treturn\n}", "func ValidateWarriorAccount(name string, email string, pwd1 string, pwd2 string) (WarriorName string, WarriorEmail string, WarriorPassword string, validateErr error) {\n\tv := validator.New()\n\ta := warriorAccount{\n\t\tName: name,\n\t\tEmail: email,\n\t\tPassword1: pwd1,\n\t\tPassword2: pwd2,\n\t}\n\terr := v.Struct(a)\n\n\treturn name, email, pwd1, err\n}", "func validateAttributes(attrs map[string]models.ValueType, allAttrs bool) error {\n\t// TBD: to finalize the attributes specifics\n\tattrsOK := false\n\tif vt, ok := attrs[AttrCred]; ok && vt.Kind == com.ValueTypeSecret {\n\t\tif !allAttrs {\n\t\t\tattrsOK = true\n\t\t} else if vt, ok := attrs[AttrZone]; ok && vt.Kind == com.ValueTypeString {\n\t\t\tattrsOK = true\n\t\t}\n\t}\n\tif !attrsOK {\n\t\tmsg := \"required domain attributes missing or invalid: need \" + AttrCred + \"[E]\"\n\t\tif allAttrs {\n\t\t\tmsg += \", \" + AttrZone + \"[S]\"\n\t\t}\n\t\treturn fmt.Errorf(msg)\n\t}\n\treturn nil\n}", "func (cc *CompanyCreate) check() error {\n\tif _, ok := cc.mutation.CreatedAt(); !ok {\n\t\treturn &ValidationError{Name: \"created_at\", err: errors.New(`ent: missing required field \"created_at\"`)}\n\t}\n\tif _, ok := cc.mutation.UpdatedAt(); !ok {\n\t\treturn &ValidationError{Name: \"updated_at\", err: errors.New(`ent: missing required field \"updated_at\"`)}\n\t}\n\tif _, ok := cc.mutation.Name(); !ok {\n\t\treturn &ValidationError{Name: \"name\", err: errors.New(`ent: missing required field \"name\"`)}\n\t}\n\tif v, ok := cc.mutation.Name(); ok {\n\t\tif err := company.NameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"name\", err: fmt.Errorf(`ent: validator failed for field \"name\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Overview(); !ok {\n\t\treturn &ValidationError{Name: \"overview\", err: errors.New(`ent: missing required field \"overview\"`)}\n\t}\n\tif v, ok := cc.mutation.Overview(); ok {\n\t\tif err := company.OverviewValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"overview\", err: fmt.Errorf(`ent: validator failed for field \"overview\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Website(); !ok {\n\t\treturn &ValidationError{Name: \"website\", err: errors.New(`ent: missing required field \"website\"`)}\n\t}\n\tif v, ok := cc.mutation.Website(); ok {\n\t\tif err := company.WebsiteValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"website\", err: fmt.Errorf(`ent: validator failed for field \"website\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.LogoURL(); !ok {\n\t\treturn &ValidationError{Name: \"logo_url\", err: errors.New(`ent: missing required field \"logo_url\"`)}\n\t}\n\tif v, ok := cc.mutation.LogoURL(); ok {\n\t\tif err := company.LogoURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"logo_url\", err: fmt.Errorf(`ent: validator failed for field \"logo_url\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.Size(); !ok {\n\t\treturn &ValidationError{Name: \"size\", err: errors.New(`ent: missing required field \"size\"`)}\n\t}\n\tif v, ok := cc.mutation.Size(); ok {\n\t\tif err := company.SizeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"size\", err: fmt.Errorf(`ent: validator failed for field \"size\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := cc.mutation.FoundedAt(); !ok {\n\t\treturn &ValidationError{Name: \"founded_at\", err: errors.New(`ent: missing required field \"founded_at\"`)}\n\t}\n\tif v, ok := cc.mutation.FoundedAt(); ok {\n\t\tif err := company.FoundedAtValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"founded_at\", err: fmt.Errorf(`ent: validator failed for field \"founded_at\": %w`, err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (m *ProviderAccountPreferences) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func ValidateGetAccountInternalResponseBody(body *GetAccountInternalResponseBody) (err error) {\n\tif body.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"name\", \"body\"))\n\t}\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Message == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"message\", \"body\"))\n\t}\n\tif body.Temporary == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"temporary\", \"body\"))\n\t}\n\tif body.Timeout == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"timeout\", \"body\"))\n\t}\n\tif body.Fault == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"fault\", \"body\"))\n\t}\n\treturn\n}", "func (o *Virtualserver) validate(dbRecord *common.DbRecord) (ok bool, err error) {\n\t////////////////////////////////////////////////////////////////////////////\n\t// Marshal data interface.\n\t////////////////////////////////////////////////////////////////////////////\n\tvar data virtualserver.Data\n\terr = shared.MarshalInterface(dbRecord.Data, &data)\n\tif err != nil {\n\t\treturn\n\t}\n\t////////////////////////////////////////////////////////////////////////////\n\t// Test required fields.\n\t////////////////////////////////////////////////////////////////////////////\n\tok = true\n\trequired := make(map[string]bool)\n\trequired[\"ProductCode\"] = false\n\trequired[\"IP\"] = false\n\trequired[\"Port\"] = false\n\trequired[\"LoadBalancerIP\"] = false\n\trequired[\"Name\"] = false\n\t////////////////////////////////////////////////////////////////////////////\n\tif data.ProductCode != 0 {\n\t\trequired[\"ProductCode\"] = true\n\t}\n\tif len(dbRecord.LoadBalancerIP) > 0 {\n\t\trequired[\"LoadBalancerIP\"] = true\n\t}\n\tif len(data.Ports) != 0 {\n\t\trequired[\"Port\"] = true\n\t}\n\tif data.IP != \"\" {\n\t\trequired[\"IP\"] = true\n\t}\n\tif data.Name != \"\" {\n\t\trequired[\"Name\"] = true\n\t}\n\tfor _, val := range required {\n\t\tif val == false {\n\t\t\tok = false\n\t\t}\n\t}\n\tif !ok {\n\t\terr = fmt.Errorf(\"missing required fields - %+v\", required)\n\t}\n\treturn\n}", "func (user *User) Validate(action string) map[string]string {\n\tvar errMessages = make(map[string]string)\n\tvar err error\n\n\tswitch strings.ToLower(action) {\n\tcase \"update\":\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"invalid email\"\n\t\t\t}\n\t\t}\n\tcase \"login\":\n\t\tif user.Password == \"\" {\n\t\t\terrMessages[\"password_required\"] = \"password is required\"\n\t\t}\n\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"invalid email\"\n\t\t\t}\n\t\t}\n\tcase \"forgotpassword\":\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email required\"\n\t\t}\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"please provide a valid email\"\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tif user.FirstName == \"\" {\n\t\t\terrMessages[\"firstname_required\"] = \"first name is required\"\n\t\t}\n\n\t\tif user.LastName == \"\" {\n\t\t\terrMessages[\"lastname_required\"] = \"last name is required\"\n\t\t}\n\n\t\tif user.Password == \"\" {\n\t\t\terrMessages[\"password_required\"] = \"password is required\"\n\t\t}\n\n\t\tif user.Password != \"\" && len(user.Password) < 6 {\n\t\t\terrMessages[\"invalid_password\"] = \"password should be at least 6 characters\"\n\t\t}\n\n\t\tif user.Email == \"\" {\n\t\t\terrMessages[\"email_required\"] = \"email is required\"\n\t\t}\n\n\t\tif user.Email != \"\" {\n\t\t\tif err = checkmail.ValidateFormat(user.Email); err != nil {\n\t\t\t\terrMessages[\"invalid_email\"] = \"please provide a valid email\"\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errMessages\n}", "func (a *Application) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: a.FirstName, Name: \"FirstName\"},\n\t\t&validators.StringIsPresent{Field: a.LastName, Name: \"LastName\"},\n\t), nil\n}", "func (uuo *UserUpdateOne) check() error {\n\tif v, ok := uuo.mutation.Username(); ok {\n\t\tif err := user.UsernameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"username\", err: fmt.Errorf(\"ent: validator failed for field \\\"username\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Fullname(); ok {\n\t\tif err := user.FullnameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"fullname\", err: fmt.Errorf(\"ent: validator failed for field \\\"fullname\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Password(); ok {\n\t\tif err := user.PasswordValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"password\", err: fmt.Errorf(\"ent: validator failed for field \\\"password\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Email(); ok {\n\t\tif err := user.EmailValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"email\", err: fmt.Errorf(\"ent: validator failed for field \\\"email\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Phone(); ok {\n\t\tif err := user.PhoneValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"phone\", err: fmt.Errorf(\"ent: validator failed for field \\\"phone\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Bio(); ok {\n\t\tif err := user.BioValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"bio\", err: fmt.Errorf(\"ent: validator failed for field \\\"bio\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Intro(); ok {\n\t\tif err := user.IntroValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"intro\", err: fmt.Errorf(\"ent: validator failed for field \\\"intro\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.GithubProfile(); ok {\n\t\tif err := user.GithubProfileValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"github_profile\", err: fmt.Errorf(\"ent: validator failed for field \\\"github_profile\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.ProfilePictureURL(); ok {\n\t\tif err := user.ProfilePictureURLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"profile_picture_url\", err: fmt.Errorf(\"ent: validator failed for field \\\"profile_picture_url\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := uuo.mutation.Status(); ok {\n\t\tif err := user.StatusValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"status\", err: fmt.Errorf(\"ent: validator failed for field \\\"status\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (r updateReq) Validate() error {\n\terr := r.addReq.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif r.ServiceAccountID != r.Body.ID {\n\t\treturn fmt.Errorf(\"service account ID mismatch, you requested to update ServiceAccount = %s but body contains ServiceAccount = %s\", r.ServiceAccountID, r.Body.ID)\n\t}\n\treturn nil\n}", "func (bu *BankdetailUpdate) check() error {\n\tif v, ok := bu.mutation.BankAccountNo(); ok {\n\t\tif err := bankdetail.BankAccountNoValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_AccountNo\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_AccountNo\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := bu.mutation.BankName(); ok {\n\t\tif err := bankdetail.BankNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_Name\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_Name\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := bu.mutation.BankAccountName(); ok {\n\t\tif err := bankdetail.BankAccountNameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"Bank_AccountName\", err: fmt.Errorf(\"ent: validator failed for field \\\"Bank_AccountName\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (rc *RentalCreate) check() error {\n\tif _, ok := rc.mutation.Date(); !ok {\n\t\treturn &ValidationError{Name: \"date\", err: errors.New(`ent: missing required field \"Rental.date\"`)}\n\t}\n\tif _, ok := rc.mutation.UserID(); !ok {\n\t\treturn &ValidationError{Name: \"user_id\", err: errors.New(`ent: missing required field \"Rental.user_id\"`)}\n\t}\n\tif _, ok := rc.mutation.CarID(); !ok {\n\t\treturn &ValidationError{Name: \"car_id\", err: errors.New(`ent: missing required field \"Rental.car_id\"`)}\n\t}\n\tif _, ok := rc.mutation.UserID(); !ok {\n\t\treturn &ValidationError{Name: \"user\", err: errors.New(`ent: missing required edge \"Rental.user\"`)}\n\t}\n\tif _, ok := rc.mutation.CarID(); !ok {\n\t\treturn &ValidationError{Name: \"car\", err: errors.New(`ent: missing required edge \"Rental.car\"`)}\n\t}\n\treturn nil\n}", "func (m *ContactAccountAttributesAccountWith) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *Customer) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAutoCollection(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBalances(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingAddress(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDateMode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDayOfWeek(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateBillingDayOfWeekMode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateContacts(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEntityCode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFraudFlag(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePaymentMethod(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateReferralUrls(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTaxability(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *OBWriteInternational3DataInitiationDebtorAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateIdentification(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSchemeName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSecondaryIdentification(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *ClusterVcenterAccount) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (e *RetrieveBalance) Validate(\n\tr *http.Request,\n) error {\n\tctx := r.Context()\n\n\t// Validate id.\n\tid, owner, token, err := ValidateID(ctx, pat.Param(r, \"balance\"))\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\te.ID = *id\n\te.Token = *token\n\te.Owner = *owner\n\n\treturn nil\n}", "func (u *User) Validate() ([]app.Invalid, error) {\n\tvar inv []app.Invalid\n\n\tif u.UserType == 0 {\n\t\tinv = append(inv, app.Invalid{Fld: \"UserType\", Err: \"The value of UserType cannot be 0.\"})\n\t}\n\n\tif u.FirstName == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"FirstName\", Err: \"A value of FirstName cannot be empty.\"})\n\t}\n\n\tif u.LastName == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"LastName\", Err: \"A value of LastName cannot be empty.\"})\n\t}\n\n\tif u.Email == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"Email\", Err: \"A value of Email cannot be empty.\"})\n\t}\n\n\tif u.Company == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"Company\", Err: \"A value of Company cannot be empty.\"})\n\t}\n\n\tif len(u.Addresses) == 0 {\n\t\tinv = append(inv, app.Invalid{Fld: \"Addresses\", Err: \"There must be at least one address.\"})\n\t} else {\n\t\tfor _, ua := range u.Addresses {\n\t\t\tif va, err := ua.Validate(); err != nil {\n\t\t\t\tinv = append(inv, va...)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(inv) > 0 {\n\t\treturn inv, errors.New(\"Validation failures identified\")\n\t}\n\n\treturn nil, nil\n}", "func ValidateGetAccountResponseBody(body *GetAccountResponseBody) (err error) {\n\tif body.Account != nil {\n\t\tif err2 := ValidateRelayerAccountResponseBody(body.Account); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\treturn\n}", "func (p *Pass) FieldsValid() bool {\n\tfmt.Printf(\"validating: \")\n\tvalid := true\n\tfor k, v := range *p {\n\t\tfmt.Printf(\"%v...\", k)\n\t\tv := isFieldValid(k, v)\n\t\tvalid = valid && v\n\t\tif v {\n\t\t\tfmt.Printf(\"VALID \")\n\t\t} else {\n\t\t\tfmt.Printf(\"INVALID \")\n\t\t}\n\t}\n\n\tfmt.Println(\"\")\n\treturn valid\n}", "func (t AuthToken) Validate() error {\n\t// Holds names of empty fields\n\tempty := []string{}\n\n\t// Check user id\n\tif len(t.UserID) == 0 {\n\t\tempty = append(empty, \"UserID\")\n\t}\n\n\t// Check device id\n\tif len(t.DeviceID) == 0 {\n\t\tempty = append(empty, \"DeviceID\")\n\t}\n\n\t// Check if any empty fields\n\tif len(empty) != 0 {\n\t\treturn fmt.Errorf(\"the following fields were empty: %s\",\n\t\t\tStrings.join(empty))\n\t}\n\n\t// All good\n\treturn nil\n}", "func (p *Passport) ValidateStrict(input string) {\r\n\tbyr := regexp.MustCompile(`byr:(\\d*)`)\r\n\tif byr.MatchString(input) {\r\n\t\tmatches := byr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], byrMin, byrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.byr = f\r\n\t\t}\r\n\t}\r\n\r\n\tiyr := regexp.MustCompile(`iyr:(\\d*)`)\r\n\tif iyr.MatchString(input) {\r\n\t\tmatches := iyr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], iyrMin, iyrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.iyr = f\r\n\t\t}\r\n\t}\r\n\r\n\teyr := regexp.MustCompile(`eyr:(\\d*)`)\r\n\tif eyr.MatchString(input) {\r\n\t\tmatches := eyr.FindStringSubmatch(input)\r\n\t\tf, err := NewYearField(matches[1], eyrMin, eyrMax)\r\n\t\tif err == nil {\r\n\t\t\tp.eyr = f\r\n\t\t}\r\n\t}\r\n\r\n\thgt := regexp.MustCompile(`hgt:(\\d*)(cm|in)?`)\r\n\tif hgt.MatchString(input) {\r\n\t\tmatches := hgt.FindStringSubmatch(input)\r\n\t\tf, err := NewHeightField(matches[1], matches[2])\r\n\t\tif err == nil {\r\n\t\t\tp.hgt = f\r\n\t\t}\r\n\t}\r\n\r\n\thcl := regexp.MustCompile(`hcl:(#[a-f0-9]*)`)\r\n\tif hcl.MatchString(input) {\r\n\t\tmatches := hcl.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], hclExp)\r\n\t\tif err == nil {\r\n\t\t\tp.hcl = f\r\n\t\t}\r\n\t}\r\n\r\n\tecl := regexp.MustCompile(`ecl:(\\w*)`)\r\n\tif ecl.MatchString(input) {\r\n\t\tmatches := ecl.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], eclExp)\r\n\t\tif err == nil {\r\n\t\t\tp.ecl = f\r\n\t\t}\r\n\t}\r\n\r\n\tpid := regexp.MustCompile(`pid:(\\d*)`)\r\n\tif pid.MatchString(input) {\r\n\t\tmatches := pid.FindStringSubmatch(input)\r\n\t\tf, err := NewTextField(matches[1], pidExp)\r\n\t\tif err == nil {\r\n\t\t\tp.pid = f\r\n\t\t}\r\n\t}\r\n}", "func (u *User) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: u.Email, Name: \"Email\"},\n\t\t&validators.StringIsPresent{Field: u.FirstName, Name: \"FirstName\"},\n\t\t&validators.StringIsPresent{Field: u.LastName, Name: \"LastName\"},\n\t\t&validators.StringIsPresent{Field: u.Nickname, Name: \"Nickname\"},\n\t\t&validators.UUIDIsPresent{Field: u.UUID, Name: \"UUID\"},\n\t\t&NullsStringIsURL{Field: u.AuthPhotoURL, Name: \"AuthPhotoURL\"},\n\t\t&domain.StringIsVisible{Field: u.Nickname, Name: \"Nickname\"},\n\t), nil\n}", "func (r *registrationRequest) isValid() error {\n\n\t//check recaptcha\n\trc := recaptcha.R{Secret: config.CaptchaSecretKey}\n\tif !rc.VerifyResponse(r.Captcha) {\n\t\treturn fmt.Errorf(\"ReCaptcha error: %s\", strings.Join(rc.LastError()[1:], \", \"))\n\t}\n\n\t// check if any of this is empty\n\tif r.Email == \"\" || r.Password == \"\" || r.PasswordConfirmation == \"\" ||\n\t\tr.First == \"\" || r.Last == \"\" {\n\t\treturn fmt.Errorf(\"%s\\n\", \"You entered incomplete data. First and last name, email and \"+\n\t\t\t\"password are mandatory fields.\")\n\t}\n\n\t// check if the password match and that the length is at least 8 chars\n\treturn passwordsAreValid(r.Password, r.PasswordConfirmation)\n}", "func (i *infoOptions) validate() error {\n\t// date-field required\n\tif len(i.DateField) == 0 {\n\t\treturn errors.New(`date-field required`)\n\t}\n\n\t// date-field index value if sep is present\n\tif len(i.Sep) > 0 {\n\t\t// attempt to convert DateField to int\n\t\tvar err error\n\t\t_, err = strconv.Atoi(i.DateField)\n\t\tif err != nil {\n\t\t\treturn errors.New(`date-field must be an integer when using a csv field separator`)\n\t\t}\n\t}\n\n\t// dest-template required\n\tif i.DestTemplate == \"\" {\n\t\treturn errors.New(`dest-template required`)\n\t}\n\n\treturn nil\n}", "func (p paymentJson) Validate() error {\n\tif p.AccountId == \"\" {\n\t\treturn errors.New(\"missing customer id\")\n\t}\n\tif p.Amount == 0 {\n\t\treturn errors.New(\"missing amount\")\n\t}\n\treturn nil\n}", "func Validation(a User) error {\n\tfmt.Println(\"user :: \", a)\n\tvar rxEmail = regexp.MustCompile(\"^[a-zA-Z0-9.!#$%&'*+\\\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\")\n\tswitch {\n\tcase len(strings.TrimSpace(a.Password)) == 0:\n\t\treturn ErrPasswordInvalid\n\tcase len(strings.TrimSpace(a.Email)) == 0 || !rxEmail.MatchString(a.Email):\n\t\treturn ErrEmailInvalid\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (account *DatabaseAccount) createValidations() []func() (admission.Warnings, error) {\n\treturn []func() (admission.Warnings, error){account.validateResourceReferences, account.validateSecretDestinations}\n}" ]
[ "0.6950377", "0.6660194", "0.6604518", "0.660115", "0.6589453", "0.6474401", "0.6469365", "0.6463922", "0.64215875", "0.63889915", "0.6362919", "0.63358384", "0.6252108", "0.62329525", "0.6229978", "0.61784095", "0.61675555", "0.61494285", "0.6107046", "0.6084981", "0.6062506", "0.6018709", "0.59835136", "0.5935781", "0.59250987", "0.5920425", "0.5918846", "0.5906061", "0.58879864", "0.5874278", "0.5862281", "0.5844713", "0.5843288", "0.58394945", "0.58318245", "0.58267343", "0.5805197", "0.5782027", "0.577867", "0.5762948", "0.57397187", "0.57109004", "0.567482", "0.5670878", "0.5664908", "0.5659827", "0.56587", "0.5648205", "0.5621579", "0.55948484", "0.55917954", "0.55910474", "0.5587459", "0.55859625", "0.55767894", "0.5549079", "0.5528815", "0.5525437", "0.5523396", "0.551239", "0.55084354", "0.55050844", "0.54942113", "0.54916596", "0.5487635", "0.5478365", "0.54646176", "0.54524314", "0.54512787", "0.5443251", "0.54331243", "0.54267573", "0.54245096", "0.5422896", "0.54207206", "0.54192007", "0.54148257", "0.540501", "0.5398671", "0.5397307", "0.5396947", "0.5394909", "0.53946984", "0.53905594", "0.53878796", "0.5384738", "0.5380616", "0.53800863", "0.53762895", "0.5367286", "0.5357383", "0.5353596", "0.5347578", "0.5342094", "0.5340789", "0.53367335", "0.5334526", "0.5331692", "0.5330748", "0.532834" ]
0.5430431
71
MarshalYAML returns the YAML representation of a ClawbackVestingAccount.
func (va ClawbackVestingAccount) MarshalYAML() (interface{}, error) { accAddr, err := sdk.AccAddressFromBech32(va.Address) if err != nil { return nil, err } out := vestingAccountYAML{ Address: accAddr, AccountNumber: va.AccountNumber, PubKey: getPKString(va), Sequence: va.Sequence, OriginalVesting: va.OriginalVesting, DelegatedFree: va.DelegatedFree, DelegatedVesting: va.DelegatedVesting, EndTime: va.EndTime, StartTime: va.StartTime, VestingPeriods: va.VestingPeriods, } return marshalYaml(out) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(bva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: bva.AccountNumber,\n\t\tPubKey: getPKString(bva),\n\t\tSequence: bva.Sequence,\n\t\tOriginalVesting: bva.OriginalVesting,\n\t\tDelegatedFree: bva.DelegatedFree,\n\t\tDelegatedVesting: bva.DelegatedVesting,\n\t\tEndTime: bva.EndTime,\n\t}\n\treturn marshalYaml(out)\n}", "func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(cva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: cva.AccountNumber,\n\t\tPubKey: getPKString(cva),\n\t\tSequence: cva.Sequence,\n\t\tOriginalVesting: cva.OriginalVesting,\n\t\tDelegatedFree: cva.DelegatedFree,\n\t\tDelegatedVesting: cva.DelegatedVesting,\n\t\tEndTime: cva.EndTime,\n\t\tStartTime: cva.StartTime,\n\t}\n\treturn marshalYaml(out)\n}", "func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(pva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: pva.AccountNumber,\n\t\tPubKey: getPKString(pva),\n\t\tSequence: pva.Sequence,\n\t\tOriginalVesting: pva.OriginalVesting,\n\t\tDelegatedFree: pva.DelegatedFree,\n\t\tDelegatedVesting: pva.DelegatedVesting,\n\t\tEndTime: pva.EndTime,\n\t\tStartTime: pva.StartTime,\n\t\tVestingPeriods: pva.VestingPeriods,\n\t}\n\treturn marshalYaml(out)\n}", "func (vva ValidatorVestingAccount) MarshalYAML() (interface{}, error) {\n\tvar bs []byte\n\tvar err error\n\tvar pubkey string\n\n\tif vva.PubKey != nil {\n\t\tpubkey, err = sdk.Bech32ifyAccPub(vva.PubKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbs, err = yaml.Marshal(struct {\n\t\tAddress sdk.AccAddress\n\t\tCoins sdk.Coins\n\t\tPubKey string\n\t\tAccountNumber uint64\n\t\tSequence uint64\n\t\tOriginalVesting sdk.Coins\n\t\tDelegatedFree sdk.Coins\n\t\tDelegatedVesting sdk.Coins\n\t\tEndTime int64\n\t\tStartTime int64\n\t\tVestingPeriods vestingtypes.Periods\n\t\tValidatorAddress sdk.ConsAddress\n\t\tReturnAddress sdk.AccAddress\n\t\tSigningThreshold int64\n\t\tCurrentPeriodProgress CurrentPeriodProgress\n\t\tVestingPeriodProgress []VestingProgress\n\t\tDebtAfterFailedVesting sdk.Coins\n\t}{\n\t\tAddress: vva.Address,\n\t\tCoins: vva.Coins,\n\t\tPubKey: pubkey,\n\t\tAccountNumber: vva.AccountNumber,\n\t\tSequence: vva.Sequence,\n\t\tOriginalVesting: vva.OriginalVesting,\n\t\tDelegatedFree: vva.DelegatedFree,\n\t\tDelegatedVesting: vva.DelegatedVesting,\n\t\tEndTime: vva.EndTime,\n\t\tStartTime: vva.StartTime,\n\t\tVestingPeriods: vva.VestingPeriods,\n\t\tValidatorAddress: vva.ValidatorAddress,\n\t\tReturnAddress: vva.ReturnAddress,\n\t\tSigningThreshold: vva.SigningThreshold,\n\t\tCurrentPeriodProgress: vva.CurrentPeriodProgress,\n\t\tVestingPeriodProgress: vva.VestingPeriodProgress,\n\t\tDebtAfterFailedVesting: vva.DebtAfterFailedVesting,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), err\n}", "func (b *Backend) MarshalYAML() (interface{}, error) {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\n\tpayload := struct {\n\t\tAddress string\n\t\tDisabledUntil time.Time `yaml:\"disabledUntil\"`\n\t\tForcePromotionsAfter time.Duration `yaml:\"forcePromotionsAfter\"`\n\t\tLatency time.Duration `yaml:\"latency\"`\n\t\tMaxConnections int `yaml:\"maxConnections\"`\n\t\tTier int `yaml:\"tier\"`\n\t}{\n\t\tAddress: b.addr.String(),\n\t\tDisabledUntil: b.mu.disabledUntil,\n\t\tForcePromotionsAfter: b.mu.forcePromotionAfter,\n\t\tLatency: b.mu.lastLatency,\n\t\tMaxConnections: b.mu.maxConnections,\n\t\tTier: b.mu.tier,\n\t}\n\treturn payload, nil\n}", "func (i Instance) MarshalYAML() (interface{}, error) {\n\treturn i.Vars, nil\n}", "func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(o, o.low)\n\treturn nb.Render(), nil\n}", "func (r RetryConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyRetryConfig{\n\t\tOutput: r.Output,\n\t\tConfig: r.Config,\n\t}\n\tif r.Output == nil {\n\t\tdummy.Output = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func (a ApprovalStrategy) MarshalYAML() (interface{}, error) {\n\treturn approvalStrategyToString[a], nil\n\t//buffer := bytes.NewBufferString(`\"`)\n\t//buffer.WriteString(approvalStrategyToString[*s])\n\t//buffer.WriteString(`\"`)\n\t//return buffer.Bytes(), nil\n}", "func (v Validator) MarshalYAML() (interface{}, error) {\n\tbs, err := yaml.Marshal(struct {\n\t\tStatus sdk.BondStatus\n\t\tJailed bool\n\t\tUnbondingHeight int64\n\t\tConsPubKey string\n\t\tOperatorAddress sdk.ValAddress\n\t\tTokens sdk.Int\n\t\tDelegatorShares sdk.Dec\n\t\tDescription Description\n\t\tUnbondingCompletionTime time.Time\n\t\tCommission Commission\n\t\tMinSelfDelegation sdk.Dec\n\t}{\n\t\tOperatorAddress: v.OperatorAddress,\n\t\tConsPubKey: MustBech32ifyConsPub(v.ConsPubKey),\n\t\tJailed: v.Jailed,\n\t\tStatus: v.Status,\n\t\tTokens: v.Tokens,\n\t\tDelegatorShares: v.DelegatorShares,\n\t\tDescription: v.Description,\n\t\tUnbondingHeight: v.UnbondingHeight,\n\t\tUnbondingCompletionTime: v.UnbondingCompletionTime,\n\t\tCommission: v.Commission,\n\t\tMinSelfDelegation: v.MinSelfDelegation,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), nil\n}", "func (key PrivateKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}", "func (r OAuthFlow) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"authorizationUrl\"] = r.AuthorizationURL\n\n\tobj[\"tokenUrl\"] = r.TokenURL\n\n\tif r.RefreshURL != \"\" {\n\t\tobj[\"refreshUrl\"] = r.RefreshURL\n\t}\n\n\tobj[\"scopes\"] = r.Scopes\n\n\tfor key, val := range r.Extensions {\n\t\tobj[key] = val\n\t}\n\n\treturn obj, nil\n}", "func (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\n\treturn export.ToData(), nil\n}", "func (p *Parameter) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(p, p.low)\n\treturn nb.Render(), nil\n}", "func (key PublicKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}", "func (c *Components) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(c, c.low)\n\treturn nb.Render(), nil\n}", "func (d *WebAuthnDevice) MarshalYAML() (any, error) {\n\treturn d.ToData(), nil\n}", "func (i ChannelName) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func Marshal(v interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tenc := yaml.NewEncoder(&buf)\n\tenc.SetIndent(2)\n\terr := enc.Encode(v)\n\treturn buf.Bytes(), err\n}", "func (m MixinDeclaration) MarshalYAML() (interface{}, error) {\n\tif m.Config == nil {\n\t\treturn m.Name, nil\n\t}\n\n\traw := map[string]interface{}{\n\t\tm.Name: m.Config,\n\t}\n\treturn raw, nil\n}", "func (z Z) MarshalYAML() (interface{}, error) {\n\ttype Z struct {\n\t\tS string `json:\"s\"`\n\t\tI int32 `json:\"iVal\"`\n\t\tHash string\n\t\tMultiplyIByTwo int64 `json:\"multipliedByTwo\"`\n\t}\n\tvar enc Z\n\tenc.S = z.S\n\tenc.I = z.I\n\tenc.Hash = z.Hash()\n\tenc.MultiplyIByTwo = int64(z.MultiplyIByTwo())\n\treturn &enc, nil\n}", "func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyReadUntilConfig{\n\t\tInput: r.Input,\n\t\tRestart: r.Restart,\n\t\tCheck: r.Check,\n\t}\n\tif r.Input == nil {\n\t\tdummy.Input = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\n\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\n}", "func (f Fixed8) MarshalYAML() (interface{}, error) {\n\treturn f.String(), nil\n}", "func (d *Discriminator) MarshalYAML() (interface{}, error) {\n\tnb := low2.NewNodeBuilder(d, d.low)\n\treturn nb.Render(), nil\n}", "func (n Nil) MarshalYAML() (interface{}, error) {\n\treturn nil, nil\n}", "func (s GitEvent) MarshalYAML() (interface{}, error) {\n\treturn toString[s], nil\n}", "func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\n\treturn m.String(), nil\n}", "func (ep Endpoint) MarshalYAML() (interface{}, error) {\n\ts, err := ep.toString()\n\treturn s, err\n}", "func (bc *ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(AtomicLoadByteCount(bc)), nil\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (d Rate) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (o *OpenAPI3SchemaExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (p Params) MarshalYAML() (interface{}, error) {\n\treturn p.String(), nil\n}", "func (f Flag) MarshalYAML() (interface{}, error) {\n\treturn f.Name, nil\n}", "func (op OpRetain) MarshalYAML() (interface{}, error) {\n\treturn op.Fields, nil\n}", "func (o *OpenAPI3PathExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (ss StdSignature) MarshalYAML() (interface{}, error) {\n\tpk := \"\"\n\tif ss.PubKey != nil {\n\t\tpk = ss.PubKey.String()\n\t}\n\n\tbz, err := yaml.Marshal(struct {\n\t\tPubKey string `json:\"pub_key\"`\n\t\tSignature string `json:\"signature\"`\n\t}{\n\t\tpk,\n\t\tfmt.Sprintf(\"%X\", ss.Signature),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bz), err\n}", "func (b ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(b), nil\n}", "func (r Discriminator) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"propertyName\"] = r.PropertyName\n\n\tif len(r.Mapping) > 0 {\n\t\tobj[\"mapping\"] = r.Mapping\n\t}\n\n\treturn obj, nil\n}", "func (v *VersionInfo) MarshalYAML() (interface{}, error) {\n\n\treturn &struct {\n\t\tSemVer string `yaml:\"semver\"`\n\t\tShaLong string `yaml:\"shaLong\"`\n\t\tBuildTimestamp int64 `yaml:\"buildTimestamp\"`\n\t\tBranch string `yaml:\"branch\"`\n\t\tArch string `yaml:\"arch\"`\n\t}{\n\t\tSemVer: v.SemVer,\n\t\tShaLong: v.ShaLong,\n\t\tBuildTimestamp: v.BuildTimestamp.Unix(),\n\t\tBranch: v.Branch,\n\t\tArch: v.Arch,\n\t}, nil\n}", "func (v *Int8) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func (o *OpenAPI3ResponseExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (k *Kluster) YAML() ([]byte, error) {\n\treturn yaml.Marshal(k)\n}", "func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\n\treturn ec.String(), nil\n}", "func (op OpFlatten) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}", "func (i Interface) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (d LegacyDec) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (f BodyField) MarshalYAML() (interface{}, error) {\n\treturn toJSONDot(f), nil\n}", "func (cp *CertPool) MarshalYAML() (interface{}, error) {\n\treturn cp.Files, nil\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (d *DefaultOptions) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(d)\n}", "func (i Int) MarshalYAML() (interface{}, error) {\n\tif !i.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn i.value, nil\n}", "func (r *Regexp) MarshalYAML() (interface{}, error) {\n\treturn r.String(), nil\n}", "func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {\n\tif len(extensions) == 0 {\n\t\treturn v, nil\n\t}\n\tmarshaled, err := yaml.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar unmarshaled map[string]interface{}\n\tif err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range extensions {\n\t\tunmarshaled[k] = v\n\t}\n\treturn unmarshaled, nil\n}", "func (o *OpenAPI3Options) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (s SensitiveString) MarshalYAML() (interface{}, error) {\n\treturn s.String(), nil\n}", "func (b Bool) MarshalYAML() (interface{}, error) {\n\tif !b.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn b.value, nil\n}", "func (schema SchemaType) MarshalYAML() (interface{}, error) {\n\treturn schema.String(), nil\n}", "func (i UOM) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func ToYAML(v interface{}) ([]byte, error) {\n\treturn yaml.Marshal(v)\n}", "func (o Op) MarshalYAML() (interface{}, error) {\n\treturn map[string]interface{}{\n\t\to.Type(): o.OpApplier,\n\t}, nil\n}", "func (o *Output) MarshalYAML() (interface{}, error) {\n\tif o.ShowValue {\n\t\treturn withvalue(*o), nil\n\t}\n\to.Value = nil // explicitly make empty\n\to.Sensitive = false // explicitly make empty\n\treturn *o, nil\n}", "func (c CompressionType) MarshalYAML() (interface{}, error) {\n\treturn compressionTypeID[c], nil\n}", "func (c *Configmap) AsYAML() []byte {\n\tresult, err := yaml.Marshal(*c)\n\tif err != nil {\n\t\tlog.Printf(\"error marshaling YAML: %s\", err)\n\t}\n\treturn result\n}", "func (d Document) MarshalYAML() (interface{}, error) {\n\treturn d.raw, nil\n}", "func (c *Config) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}", "func (c Configuration) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}", "func (v *Uint16) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func (a *Account) Marshal() ([]byte, error) {\n\treturn a.account.Bytes()\n}", "func (m OrderedMap[K, V]) MarshalYAML() ([]byte, error) {\n\tvar s yaml.MapSlice\n\tfor _, item := range m.ToSlice() {\n\t\ts = append(s, yaml.MapItem{\n\t\t\tKey: item.Key,\n\t\t\tValue: item.Value,\n\t\t})\n\t}\n\treturn yaml.Marshal(s)\n}", "func (r ParseKind) MarshalYAML() ([]byte, error) {\n\tif s, ok := interface{}(r).(fmt.Stringer); ok {\n\t\treturn yaml.Marshal(s.String())\n\t}\n\ts, ok := _ParseKindValueToName[r]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid ParseKind: %d\", r)\n\t}\n\treturn yaml.Marshal(s)\n}", "func FormatAsYAML(obj interface{}, indent int) string {\n\tif obj == nil {\n\t\treturn \"none\"\n\t}\n\tdata, err := yaml.Marshal(obj)\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error during yaml serialization: %s\", err.Error())\n\t}\n\t// add an additional newline to properly inline\n\treturn ApplyIdent(\"\\n\"+string(data), indent)\n}", "func (u *URL) MarshalYAML() (interface{}, error) {\n\treturn u.String(), nil\n}", "func toYAML(v interface{}) string {\n\tdata, err := yaml.Marshal(v)\n\tif err != nil {\n\t\t// Swallow errors inside of a template.\n\t\treturn \"\"\n\t}\n\n\treturn strings.TrimSuffix(string(data), \"\\n\")\n}", "func (s DescribeAccountAuditConfigurationOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.AuditCheckConfigurations != nil {\n\t\tv := s.AuditCheckConfigurations\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"auditCheckConfigurations\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.AuditNotificationTargetConfigurations != nil {\n\t\tv := s.AuditNotificationTargetConfigurations\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"auditNotificationTargetConfigurations\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RoleArn != nil {\n\t\tv := *s.RoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"roleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (cfg frozenConfig) MarshalIndent(val interface{}, prefix, indent string) ([]byte, error) {\n return encoder.EncodeIndented(val, prefix, indent, cfg.encoderOpts)\n}", "func (s *spiff) Marshal(node Node) ([]byte, error) {\n\treturn yaml.Marshal(node)\n}", "func SortYAML(in io.Reader, out io.Writer, indent int) error {\n\n\tincomingYAML, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't read input: %v\", err)\n\t}\n\n\tvar hasNoStartingLabel bool\n\trootIndent, err := detectRootIndent(incomingYAML)\n\tif err != nil {\n\t\tif !errors.Is(err, ErrNoStartingLabel) {\n\t\t\tfmt.Fprint(out, string(incomingYAML))\n\t\t\treturn fmt.Errorf(\"can't detect root indentation: %v\", err)\n\t\t}\n\n\t\thasNoStartingLabel = true\n\t}\n\n\tif hasNoStartingLabel {\n\t\tincomingYAML = append([]byte(CustomLabel+\"\\n\"), incomingYAML...)\n\t}\n\n\tvar value map[string]interface{}\n\tif err := yaml.Unmarshal(incomingYAML, &value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\n\t\treturn fmt.Errorf(\"can't decode YAML: %v\", err)\n\t}\n\n\tvar outgoingYAML bytes.Buffer\n\tencoder := yaml.NewEncoder(&outgoingYAML)\n\tencoder.SetIndent(indent)\n\n\tif err := encoder.Encode(&value); err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-encode YAML: %v\", err)\n\t}\n\n\treindentedYAML, err := indentYAML(outgoingYAML.String(), rootIndent, indent, hasNoStartingLabel)\n\tif err != nil {\n\t\tfmt.Fprint(out, string(incomingYAML))\n\t\treturn fmt.Errorf(\"can't re-indent YAML: %v\", err)\n\t}\n\n\tfmt.Fprint(out, reindentedYAML)\n\treturn nil\n}", "func (vm ValidationMap) AsYAML() (string, error) {\n\tdata, err := yaml.Marshal(vm)\n\treturn string(data), err\n}", "func Dump(cfg interface{}, dst io.Writer) error {\n\treturn yaml.NewEncoder(dst).Encode(cfg)\n}", "func (f *Fzp) ToYAML() ([]byte, error) {\n\tdata, err := yaml.Marshal(f)\n\treturn data, err\n}", "func (c Config) ToYAML() string {\n\tdata, _ := yaml.Marshal(c)\n\treturn string(data)\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func Dump(v interface{}) ([]byte, error) {\n\treturn yaml.Marshal(v)\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.Duration.String(), nil\n}", "func Marshal(o interface{}) ([]byte, error) {\n\tj, err := json.Marshal(o)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshaling into JSON: %v\", err)\n\t}\n\n\ty, err := JSONToYAML(j)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error converting JSON to YAML: %v\", err)\n\t}\n\n\treturn y, nil\n}", "func (date Date) MarshalYAML() (interface{}, error) {\n\tvar d = string(date)\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn nil, err\n\t}\n\treturn d, nil\n}", "func (a Account) Save(filePath string) error {\n\td, err := yaml.Marshal(a)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(filePath, d, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (t TimeUnixSeconds) MarshalYAML() (interface{}, error) {\n\tif !t.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn t.value.Unix(), nil\n}", "func (d DurationMillis) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Millisecond), nil\n}", "func ContainerazureAlphaClusterWorkloadIdentityConfigToProto(o *alpha.ClusterWorkloadIdentityConfig) *alphapb.ContainerazureAlphaClusterWorkloadIdentityConfig {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &alphapb.ContainerazureAlphaClusterWorkloadIdentityConfig{}\n\tp.SetIssuerUri(dcl.ValueOrEmptyString(o.IssuerUri))\n\tp.SetWorkloadPool(dcl.ValueOrEmptyString(o.WorkloadPool))\n\tp.SetIdentityProvider(dcl.ValueOrEmptyString(o.IdentityProvider))\n\treturn p\n}", "func (s *Siegfried) YAML() string {\n\tversion := config.Version()\n\tstr := fmt.Sprintf(\n\t\t\"---\\nsiegfried : %d.%d.%d\\nscandate : %v\\nsignature : %s\\ncreated : %v\\nidentifiers : \\n\",\n\t\tversion[0], version[1], version[2],\n\t\ttime.Now().Format(time.RFC3339),\n\t\tconfig.SignatureBase(),\n\t\ts.C.Format(time.RFC3339))\n\tfor _, id := range s.ids {\n\t\td := id.Describe()\n\t\tstr += fmt.Sprintf(\" - name : '%v'\\n details : '%v'\\n\", d[0], d[1])\n\t}\n\treturn str\n}", "func (u *URL) MarshalYAML() (interface{}, error) {\n\tif u.url == nil {\n\t\treturn nil, nil\n\t}\n\treturn u.url.String(), nil\n}", "func (c *Config) Dump() ([]byte, error) {\n\tb, err := yaml.Marshal(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}", "func SPrintYAML(a interface{}) (string, error) {\n\tb, err := MarshalJSON(a)\n\t// doing yaml this way because at times you have nested proto structs\n\t// that need to be cleaned.\n\tyam, err := yamlconv.JSONToYAML(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(yam), nil\n}", "func (acc *Account) Serialize() ([]byte, error) {\n\treturn json.Marshal(acc)\n}" ]
[ "0.81687456", "0.8013179", "0.78075606", "0.77150255", "0.63062006", "0.6222024", "0.61517715", "0.6118727", "0.60633063", "0.60269654", "0.5953029", "0.5952517", "0.5855554", "0.5855083", "0.5827823", "0.5779316", "0.5734564", "0.571303", "0.5689044", "0.5630494", "0.5589824", "0.5582469", "0.55512136", "0.5445769", "0.54448503", "0.54265296", "0.5421635", "0.5409735", "0.54024094", "0.53555834", "0.5349621", "0.534485", "0.534485", "0.5342051", "0.53394437", "0.53357315", "0.53289723", "0.53286994", "0.53280103", "0.5316041", "0.5310311", "0.5301155", "0.52899104", "0.5277522", "0.52707964", "0.52627325", "0.52564955", "0.5249496", "0.52154136", "0.521424", "0.5206155", "0.5189614", "0.51094496", "0.51094496", "0.50685984", "0.50638443", "0.50474495", "0.5035644", "0.5026148", "0.5020545", "0.49739468", "0.49523404", "0.49467063", "0.49260494", "0.49075344", "0.48836628", "0.48808745", "0.48713064", "0.48423284", "0.4828866", "0.47944242", "0.4790343", "0.4789781", "0.47636038", "0.47567108", "0.4735841", "0.47084555", "0.4693027", "0.46878573", "0.46787977", "0.4677704", "0.46720177", "0.46664992", "0.46597022", "0.46551752", "0.4646939", "0.46306318", "0.4623652", "0.46223155", "0.460824", "0.45978552", "0.4576248", "0.45351648", "0.45339996", "0.45329022", "0.4524215", "0.44933507", "0.4490635", "0.44768015", "0.44752574" ]
0.848191
0
NewClawbackGrantAction returns an AddGrantAction for a ClawbackVestingAccount.
func NewClawbackGrantAction( funderAddress string, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins, ) exported.AddGrantAction { return clawbackGrantAction{ funderAddress: funderAddress, sk: sk, grantStartTime: grantStartTime, grantLockupPeriods: grantLockupPeriods, grantVestingPeriods: grantVestingPeriods, grantCoins: grantCoins, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewClawbackAction(requestor, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) exported.ClawbackAction {\n\treturn clawbackAction{\n\t\trequestor: requestor,\n\t\tdest: dest,\n\t\tak: ak,\n\t\tbk: bk,\n\t\tsk: sk,\n\t}\n}", "func NewClawbackRewardAction(ak AccountKeeper, bk BankKeeper, sk StakingKeeper) exported.RewardAction {\n\treturn clawbackRewardAction{\n\t\tak: ak,\n\t\tbk: bk,\n\t\tsk: sk,\n\t}\n}", "func (cga clawbackGrantAction) AddToAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported,\n\t\t\t\"account %s must be a ClawbackVestingAccount, got %T\",\n\t\t\trawAccount.GetAddress(), rawAccount)\n\t}\n\tif cga.funderAddress != cva.FunderAddress {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"account %s can only accept grants from account %s\",\n\t\t\trawAccount.GetAddress(), cva.FunderAddress)\n\t}\n\tcva.addGrant(ctx, cga.sk, cga.grantStartTime, cga.grantLockupPeriods, cga.grantVestingPeriods, cga.grantCoins)\n\treturn nil\n}", "func NewPeriodicGrantAction(\n\tsk StakingKeeper,\n\tgrantStartTime int64,\n\tgrantVestingPeriods []Period,\n\tgrantCoins sdk.Coins,\n) exported.AddGrantAction {\n\treturn periodicGrantAction{\n\t\tsk: sk,\n\t\tgrantStartTime: grantStartTime,\n\t\tgrantVestingPeriods: grantVestingPeriods,\n\t\tgrantCoins: grantCoins,\n\t}\n}", "func NewClawbackVestingAccount(baseAcc *authtypes.BaseAccount, funder sdk.AccAddress, originalVesting sdk.Coins, startTime int64, lockupPeriods, vestingPeriods Periods) *ClawbackVestingAccount {\n\t// copy and align schedules to avoid mutating inputs\n\tlp := make(Periods, len(lockupPeriods))\n\tcopy(lp, lockupPeriods)\n\tvp := make(Periods, len(vestingPeriods))\n\tcopy(vp, vestingPeriods)\n\t_, endTime := AlignSchedules(startTime, startTime, lp, vp)\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ClawbackVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tFunderAddress: funder.String(),\n\t\tStartTime: startTime,\n\t\tLockupPeriods: lp,\n\t\tVestingPeriods: vp,\n\t}\n}", "func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV + DF by capping slashed at the current unvested amount\n\tunvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime()))\n\tnewSlashed := coinsMin(slashed, unvested)\n\tnewDelegated := delegated.Add(newSlashed...)\n\n\t// modify schedules for the new grant\n\tnewLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods)\n\tnewVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime,\n\t\tva.GetVestingPeriods(), grantVestingPeriods)\n\tif newLockupStart != newVestingStart {\n\t\tpanic(\"bad start time calculation\")\n\t}\n\tva.StartTime = newLockupStart\n\tva.EndTime = max64(newLockupEnd, newVestingEnd)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\tva.OriginalVesting = va.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newDelegated\n\tunvested2 := va.GetVestingCoins(ctx.BlockTime())\n\tva.DelegatedVesting = coinsMin(newDelegated, unvested2)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n}", "func NewCollateralizeAction(c *Collateralize, tx *types.Transaction, index int) *Action {\n\thash := tx.Hash()\n\tfromaddr := tx.From()\n\tcfg := c.GetAPI().GetConfig()\n\ttokenDb, err := account.NewAccountDB(cfg, tokenE.GetName(), pty.CCNYTokenName, c.GetStateDB())\n\tif err != nil {\n\t\tclog.Error(\"NewCollateralizeAction\", \"Get Account DB error\", \"error\", err)\n\t\treturn nil\n\t}\n\n\treturn &Action{\n\t\tcoinsAccount: c.GetCoinsAccount(), tokenAccount: tokenDb, db: c.GetStateDB(), localDB: c.GetLocalDB(),\n\t\ttxhash: hash, fromaddr: fromaddr, blocktime: c.GetBlockTime(), height: c.GetHeight(),\n\t\texecaddr: dapp.ExecAddress(string(tx.Execer)), difficulty: c.GetDifficulty(), index: index, Collateralize: c}\n}", "func (pva *PeriodicVestingAccount) AddGrant(ctx sdk.Context, action exported.AddGrantAction) error {\n\treturn action.AddToAccount(ctx, pva)\n}", "func NewAction(h *Hashlock, tx *types.Transaction, execaddr string) *Action {\n\thash := tx.Hash()\n\tfromaddr := tx.From()\n\treturn &Action{h.GetCoinsAccount(), h.GetStateDB(), hash, fromaddr, h.GetBlockTime(), h.GetHeight(), execaddr, h.GetAPI()}\n}", "func (r *jsiiProxy_Repository) Grant(grantee awsiam.IGrantable, actions ...*string) awsiam.Grant {\n\targs := []interface{}{grantee}\n\tfor _, a := range actions {\n\t\targs = append(args, a)\n\t}\n\n\tvar returns awsiam.Grant\n\n\t_jsii_.Invoke(\n\t\tr,\n\t\t\"grant\",\n\t\targs,\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (r *jsiiProxy_RepositoryBase) Grant(grantee awsiam.IGrantable, actions ...*string) awsiam.Grant {\n\targs := []interface{}{grantee}\n\tfor _, a := range actions {\n\t\targs = append(args, a)\n\t}\n\n\tvar returns awsiam.Grant\n\n\t_jsii_.Invoke(\n\t\tr,\n\t\t\"grant\",\n\t\targs,\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func NewAuthorizeAction(ctx context.Context, viper *viper.Viper, authMode string,\n\tlocalAuthController *local.Controller, bkiamAuthController *bkiam.Controller,\n\treq *pb.AuthorizeReq, resp *pb.AuthorizeResp) *AuthorizeAction {\n\n\taction := &AuthorizeAction{\n\t\tctx: ctx,\n\t\tviper: viper,\n\t\tauthMode: authMode,\n\t\tlocalAuthController: localAuthController,\n\t\tbkiamAuthController: bkiamAuthController,\n\t\treq: req,\n\t\tresp: resp,\n\t}\n\n\taction.resp.Seq = req.Seq\n\taction.resp.Code = pbcommon.ErrCode_E_OK\n\taction.resp.Message = \"OK\"\n\n\treturn action\n}", "func NewChallengeAction(msg *Message) (*ChallengeAction, error) {\n\taction := &ChallengeAction{*msg}\n\n\treturn action, nil\n}", "func CreateAction(\n\tcmd, keyB, id, secretKey string,\n\targs ...interface{}) *types.Action {\n\n\tmac := hmac.New(sha1.New, []byte(secretKey))\n\tmac.Write([]byte(cmd))\n\tmac.Write([]byte(keyB))\n\tmac.Write([]byte(id))\n\tsum := mac.Sum(nil)\n\tsumhex := hex.EncodeToString(sum)\n\n\treturn &types.Action{\n\t\tCommand: cmd,\n\t\tStorageKey: keyB,\n\t\tArgs: args,\n\t\tId: id,\n\t\tSecret: sumhex,\n\t}\n}", "func NewTriggerAction(agentName string, propertyName string, propertyValue string) *TriggerAction {\n instance := new(TriggerAction)\n instance.agentName = agentName\n instance.propertyName = propertyName\n instance.propertyValue = propertyValue\n return instance\n}", "func NewAction(name string, arg interface{}) {\n\tDefaultActionRegistry.Post(name, arg)\n}", "func AccountGrant() GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tgrantType: accountType,\n\t}\n}", "func (h *Handler) NewAction(act action.Action, settings map[string]interface{}) *Action {\n\n\tvalue := reflect.ValueOf(act)\n\tvalue = value.Elem()\n\tref := value.Type().PkgPath()\n\n\tnewAct := &Action{ref: ref, settings: settings}\n\th.actions = append(h.actions, newAct)\n\n\treturn newAct\n}", "func CreateAction(r *Raptor) *Action {\n\treturn &Action{\n\t\tRaptor: r,\n\t}\n}", "func (va *ClawbackVestingAccount) clawback(ctx sdk.Context, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) error {\n\t// Compute the clawback based on the account state only, and update account\n\ttoClawBack := va.computeClawback(ctx.BlockTime().Unix())\n\tif toClawBack.IsZero() {\n\t\treturn nil\n\t}\n\taddr := va.GetAddress()\n\tbondDenom := sk.BondDenom(ctx)\n\n\t// Compute the clawback based on bank balance and delegation, and update account\n\tencumbered := va.GetVestingCoins(ctx.BlockTime())\n\tbondedAmt := sk.GetDelegatorBonded(ctx, addr)\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, addr)\n\tbonded := sdk.NewCoins(sdk.NewCoin(bondDenom, bondedAmt))\n\tunbonding := sdk.NewCoins(sdk.NewCoin(bondDenom, unbondingAmt))\n\tunbonded := bk.GetAllBalances(ctx, addr)\n\ttoClawBack = va.updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded)\n\n\t// Write now now so that the bank module sees unvested tokens are unlocked.\n\t// Note that all store writes are aborted if there is a panic, so there is\n\t// no danger in writing incomplete results.\n\tak.SetAccount(ctx, va)\n\n\t// Now that future vesting events (and associated lockup) are removed,\n\t// the balance of the account is unlocked and can be freely transferred.\n\tspendable := bk.SpendableCoins(ctx, addr)\n\ttoXfer := coinsMin(toClawBack, spendable)\n\terr := bk.SendCoins(ctx, addr, dest, toXfer)\n\tif err != nil {\n\t\treturn err // shouldn't happen, given spendable check\n\t}\n\ttoClawBack = toClawBack.Sub(toXfer)\n\n\t// We need to traverse the staking data structures to update the\n\t// vesting account bookkeeping, and to recover more funds if necessary.\n\t// Staking is the only way unvested tokens should be missing from the bank balance.\n\n\t// If we need more, transfer UnbondingDelegations.\n\twant := toClawBack.AmountOf(bondDenom)\n\tunbondings := sk.GetUnbondingDelegations(ctx, addr, math.MaxUint16)\n\tfor _, unbonding := range unbondings {\n\t\tvalAddr, err := sdk.ValAddressFromBech32(unbonding.ValidatorAddress)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttransferred := sk.TransferUnbonding(ctx, addr, dest, valAddr, want)\n\t\twant = want.Sub(transferred)\n\t\tif !want.IsPositive() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If we need more, transfer Delegations.\n\tif want.IsPositive() {\n\t\tdelegations := sk.GetDelegatorDelegations(ctx, addr, math.MaxUint16)\n\t\tfor _, delegation := range delegations {\n\t\t\tvalidatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // shouldn't happen\n\t\t\t}\n\t\t\tvalidator, found := sk.GetValidator(ctx, validatorAddr)\n\t\t\tif !found {\n\t\t\t\t// validator has been removed\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twantShares, err := validator.SharesFromTokensTruncated(want)\n\t\t\tif err != nil {\n\t\t\t\t// validator has no tokens\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttransferredShares := sk.TransferDelegation(ctx, addr, dest, delegation.GetValidatorAddr(), wantShares)\n\t\t\t// to be conservative in what we're clawing back, round transferred shares up\n\t\t\ttransferred := validator.TokensFromSharesRoundUp(transferredShares).RoundInt()\n\t\t\twant = want.Sub(transferred)\n\t\t\tif !want.IsPositive() {\n\t\t\t\t// Could be slightly negative, due to rounding?\n\t\t\t\t// Don't think so, due to the precautions above.\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we've transferred everything and still haven't transferred the desired clawback amount,\n\t// then the account must have most some unvested tokens from slashing.\n\treturn nil\n}", "func NewApprove(proposer uos.AccountName, proposalName uos.Name, level uos.PermissionLevel) *uos.Action {\n\treturn &uos.Action{\n\t\tAccount: uos.AccountName(\"wxbio.msig\"),\n\t\tName: uos.ActionName(\"approve\"),\n\t\tAuthorization: []uos.PermissionLevel{level},\n\t\tActionData: uos.NewActionData(Approve{proposer, proposalName, level}),\n\t}\n}", "func AddActionAction(c *gin.Context) {\n\tresult := render.NewResult()\n\tdefer c.JSON(http.StatusOK, result)\n\n\taction := &model.Action{}\n\tif err := c.BindJSON(action); nil != err {\n\t\tresult.Error(err)\n\n\t\treturn\n\t}\n\n\tsrv := service.FromContext(c)\n\tif err := srv.Actions.Create(c, action); nil != err {\n\t\tresult.Error(err)\n\t}\n}", "func NewSecretAction(logger logrus.FieldLogger, client client.Client) *SecretAction {\n\treturn &SecretAction{\n\t\tlogger: logger,\n\t\tclient: client,\n\t}\n}", "func NewCreateGoalController(cgtRepos *persistence.Services, logger *log.Logger, authorizationService authorization.JwtService) Controller {\n\tcreateGoalUsecase := usecase.NewCreateGoalUsecase(&cgtRepos.Achiever, &cgtRepos.Goal, authorizationService)\n\n\tctrl := &createGoalController{\n\t\tUsecase: createGoalUsecase,\n\t\tLogger: logger,\n\t\tAuthorization: authorizationService,\n\t}\n\treturn ctrl\n}", "func (qiu *QueueItemUpdate) AddAction(i int) *QueueItemUpdate {\n\tqiu.mutation.AddAction(i)\n\treturn qiu\n}", "func NewRollbackAction(kit kit.Kit, viper *viper.Viper,\n\tauthSvrCli pbauthserver.AuthClient, dataMgrCli pbdatamanager.DataManagerClient,\n\tgseControllerCli pbgsecontroller.GSEControllerClient,\n\treq *pb.RollbackReleaseReq, resp *pb.RollbackReleaseResp) *RollbackAction {\n\n\taction := &RollbackAction{\n\t\tkit: kit,\n\t\tviper: viper,\n\t\tauthSvrCli: authSvrCli,\n\t\tdataMgrCli: dataMgrCli,\n\t\tgseControllerCli: gseControllerCli,\n\t\treq: req,\n\t\tresp: resp,\n\t}\n\n\taction.resp.Result = true\n\taction.resp.Code = pbcommon.ErrCode_E_OK\n\taction.resp.Message = \"OK\"\n\n\treturn action\n}", "func (c *ContractBackend) NewTransactor(ctx context.Context, gasLimit uint64,\n\tacc accounts.Account) (*bind.TransactOpts, error) {\n\tc.nonceMtx.Lock()\n\tdefer c.nonceMtx.Unlock()\n\texpectedNextNonce, found := c.expectedNextNonce[acc.Address]\n\tif !found {\n\t\tc.expectedNextNonce[acc.Address] = 0\n\t}\n\n\tauth, err := c.tr.NewTransactor(acc)\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"creating transactor\")\n\t}\n\n\tauth.GasLimit = gasLimit\n\tauth.Context = ctx\n\n\tnonce, err := c.PendingNonceAt(ctx, acc.Address)\n\tif err != nil {\n\t\terr = cherrors.CheckIsChainNotReachableError(err)\n\t\treturn nil, errors.WithMessage(err, \"fetching nonce\")\n\t}\n\tif nonce < expectedNextNonce {\n\t\tnonce = expectedNextNonce\n\t}\n\n\tauth.Nonce = big.NewInt(int64(nonce))\n\tc.expectedNextNonce[acc.Address] = nonce + 1\n\n\treturn auth, nil\n}", "func NewBcBotAction(j *bot.Jobs) *BcBotAction {\n\t// client := resty.New()\n\t// client.\n\t// \tSetRetryCount(3).\n\t// \tSetRetryWaitTime(10 * time.Second)\n\treturn &BcBotAction{jobs: j, client: nil, mutex: new(sync.RWMutex)}\n}", "func (qiuo *QueueItemUpdateOne) AddAction(i int) *QueueItemUpdateOne {\n\tqiuo.mutation.AddAction(i)\n\treturn qiuo\n}", "func NewRecoverableAction(supervisor *Supervisor) *RecoverableAction {\n\tra := &RecoverableAction{\n\t\tactionChan: make(chan Action),\n\t\treplyChan: make(chan string, 5),\n\t\tsupervisor: supervisor,\n\t}\n\n\tra.heartbeat = NewHeartbeat(ra, 1e8)\n\n\tgo ra.backend()\n\n\treturn ra\n}", "func (c *Client) Grant(email string) {\n\tif c.CI {\n\t\temail = strings.ToLower(email)\n\t}\n\tc.mu.Lock()\n\tc.whitelist[email] = struct{}{}\n\tc.mu.Unlock()\n}", "func NewGrantCheck(check GrantChecker, handler GrantHandler, errorHandler GrantErrorHandler) osinserver.AuthorizeHandler {\n\treturn &GrantCheck{check, handler, errorHandler}\n}", "func NewAccessControl(address common.Address, backend bind.ContractBackend) (*AccessControl, error) {\n\tcontract, err := bindAccessControl(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AccessControl{AccessControlCaller: AccessControlCaller{contract: contract}, AccessControlTransactor: AccessControlTransactor{contract: contract}, AccessControlFilterer: AccessControlFilterer{contract: contract}}, nil\n}", "func NewAccessControl(address common.Address, backend bind.ContractBackend) (*AccessControl, error) {\n\tcontract, err := bindAccessControl(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AccessControl{AccessControlCaller: AccessControlCaller{contract: contract}, AccessControlTransactor: AccessControlTransactor{contract: contract}, AccessControlFilterer: AccessControlFilterer{contract: contract}}, nil\n}", "func (va *ClawbackVestingAccount) computeClawback(clawbackTime int64) sdk.Coins {\n\t// Compute the truncated vesting schedule and amounts.\n\t// Work with the schedule as the primary data and recompute derived fields, e.g. OriginalVesting.\n\tvestTime := va.StartTime\n\ttotalVested := sdk.NewCoins()\n\ttotalUnvested := sdk.NewCoins()\n\tunvestedIdx := 0\n\tfor i, period := range va.VestingPeriods {\n\t\tvestTime += period.Length\n\t\t// tie in time goes to clawback\n\t\tif vestTime < clawbackTime {\n\t\t\ttotalVested = totalVested.Add(period.Amount...)\n\t\t\tunvestedIdx = i + 1\n\t\t} else {\n\t\t\ttotalUnvested = totalUnvested.Add(period.Amount...)\n\t\t}\n\t}\n\tlastVestTime := vestTime\n\tnewVestingPeriods := va.VestingPeriods[:unvestedIdx]\n\n\t// To cap the unlocking schedule to the new total vested, conjunct with a limiting schedule\n\tcapPeriods := []Period{\n\t\t{\n\t\t\tLength: 0,\n\t\t\tAmount: totalVested,\n\t\t},\n\t}\n\t_, lastLockTime, newLockupPeriods := ConjunctPeriods(va.StartTime, va.StartTime, va.LockupPeriods, capPeriods)\n\n\t// Now construct the new account state\n\tva.OriginalVesting = totalVested\n\tva.EndTime = max64(lastVestTime, lastLockTime)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\t// DelegatedVesting and DelegatedFree will be adjusted elsewhere\n\n\treturn totalUnvested\n}", "func AddAction(c *gin.Context) {\n\tvar action = models.Action{}.MapRequestToAction(c)\n\n\tvar user models.User\n\tresult := models.DB.First(&user, action.CreatedBy)\n\n\tif result.RowsAffected == 0 {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"data\": \"created_by is not a valid user id\"})\n\t\treturn\n\t}\n\n\tresult = models.DB.Create(&action)\n\n\tif result.Error != nil {\n\t\tc.JSON(http.StatusBadRequest, helpers.BadRequest())\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\"data\": helpers.Results{\n\t\tCount: 1,\n\t\tResults: action,\n\t}})\n}", "func NewRedirectGrant(url string) GrantHandler {\n\treturn &redirectGrant{url}\n}", "func (pva *PeriodicVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, pva.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, pva.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := pva.DelegatedVesting.Add(pva.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV+DF by capping slashed at the current unvested amount\n\tunvested := pva.GetVestingCoins(ctx.BlockTime())\n\tnewSlashed := coinsMin(unvested, slashed)\n\tnewTotalDelegated := delegated.Add(newSlashed...)\n\n\t// modify vesting schedule for the new grant\n\tnewStart, newEnd, newPeriods := DisjunctPeriods(pva.StartTime, grantStartTime,\n\t\tpva.GetVestingPeriods(), grantVestingPeriods)\n\tpva.StartTime = newStart\n\tpva.EndTime = newEnd\n\tpva.VestingPeriods = newPeriods\n\tpva.OriginalVesting = pva.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newTotalDelegated\n\tunvested2 := pva.GetVestingCoins(ctx.BlockTime())\n\tpva.DelegatedVesting = coinsMin(newTotalDelegated, unvested2)\n\tpva.DelegatedFree = newTotalDelegated.Sub(pva.DelegatedVesting)\n}", "func NewShowAction() *ShowAction {\n\treturn &ShowAction{}\n}", "func CreateBackupAction(service *pgCommon.PostgresServiceInformations) action.IAction {\n\treturn action.FormAction{\n\t\tName: \"Backup\",\n\t\tUniqueCommand: \"cmd_pg_create_backup\",\n\t\tPlaceholder: nil,\n\t\tActionExecuteCallback: func(placeholder interface{}) (interface{}, error) {\n\t\t\treturn nil, CreateBackup(service)\n\t\t},\n\t}\n}", "func NewAction(t *Pos33Ticket, tx *types.Transaction) *Action {\n\thash := tx.Hash()\n\tfromaddr := tx.From()\n\treturn &Action{t.GetCoinsAccount(), t.GetStateDB(), hash, fromaddr,\n\t\tt.GetBlockTime(), t.GetHeight(), dapp.ExecAddress(string(tx.Execer)), t.GetAPI()}\n}", "func NewAction() actions.Action {\n\treturn &Action{}\n}", "func NewAction() actions.Action {\n\treturn &Action{}\n}", "func NewAutoGrant() GrantHandler {\n\treturn &autoGrant{}\n}", "func (n *noopRules) Grant(rule *Rule) error {\n\treturn nil\n}", "func NewAction() actions.Action {\n\treturn &action{}\n}", "func CreateAction(action func(*cli.Context) error) func(*cli.Context) error {\n\treturn func(c *cli.Context) error {\n\t\terr := action(c)\n\t\tif err != nil {\n\t\t\tiocli.Error(\"%s\", err)\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func NewBaseAccessWalletFactoryTransactor(address common.Address, transactor bind.ContractTransactor) (*BaseAccessWalletFactoryTransactor, error) {\n\tcontract, err := bindBaseAccessWalletFactory(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BaseAccessWalletFactoryTransactor{contract: contract}, nil\n}", "func (_BaseAccessWalletFactory *BaseAccessWalletFactoryTransactor) CreateAccessWallet(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BaseAccessWalletFactory.contract.Transact(opts, \"createAccessWallet\")\n}", "func Grant(ctx context.Context, i grantRequest) error {\n\tclient, err := New(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn client.Grant(ctx, i)\n}", "func (_BaseContentSpace *BaseContentSpaceTransactor) CreateAccessWallet(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BaseContentSpace.contract.Transact(opts, \"createAccessWallet\")\n}", "func New() Action {\n\treturn &action{}\n}", "func (biz *BizAccountAccess) newAccountAccess(ctx context.Context, tx *sql.Tx,\n\tu coremodel.User, accType coremodel.AccountAccessType,\n) (*coremodel.AccountAccess, error) {\n\tac, err := coremodel.NewAccountAccess(u, accType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err = biz.dal.Insert(ctx, tx, ac); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ac, nil\n}", "func (pr *replica) addAction(act action) {\n\tif err := pr.actions.Put(act); err != nil {\n\t\treturn\n\t}\n\tpr.notifyWorker()\n}", "func NewAction(payload interface{}) Action {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error: %v\\n\", r)\n\t\t\tfmt.Fprintf(os.Stderr, \"Payload: %v\\n\", payload)\n\t\t}\n\t}()\n\n\tvar a Action\n\ta.payload = payload\n\ta.headers = make(map[string]string)\n\n\tfor k, v := range payload.(map[interface{}]interface{}) {\n\t\tswitch k {\n\t\tcase \"catch\":\n\t\t\ta.catch = v.(string)\n\t\tcase \"warnings\":\n\t\t\t// TODO\n\t\t\tcontinue\n\t\tcase \"allowed_warnings\":\n\t\t\t// TODO\n\t\t\tcontinue\n\t\tcase \"node_selector\":\n\t\t\tcontinue\n\t\tcase \"headers\":\n\t\t\tfor kk, vv := range v.(map[interface{}]interface{}) {\n\t\t\t\ta.headers[kk.(string)] = vv.(string)\n\t\t\t}\n\t\tdefault:\n\t\t\ta.method = k.(string)\n\t\t\ta.params = v.(map[interface{}]interface{})\n\t\t}\n\t}\n\n\treturn a\n}", "func NewCheck() beekeeper.Action {\n\treturn &Check{}\n}", "func (alias *Alias) AddAction(operation, index, name string) *Alias {\n\tif alias.dict[ACTIONS] == nil {\n\t\talias.dict[ACTIONS] = []Dict{}\n\t}\n\taction := make(Dict)\n\taction[operation] = Dict{\"index\": index, \"alias\": name}\n\talias.dict[ACTIONS] = append(alias.dict[ACTIONS].([]Dict), action)\n\treturn alias\n}", "func NewAccessControlTransactor(address common.Address, transactor bind.ContractTransactor) (*AccessControlTransactor, error) {\n\tcontract, err := bindAccessControl(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AccessControlTransactor{contract: contract}, nil\n}", "func NewAccessControlTransactor(address common.Address, transactor bind.ContractTransactor) (*AccessControlTransactor, error) {\n\tcontract, err := bindAccessControl(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AccessControlTransactor{contract: contract}, nil\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupTransactor) GrantAccess(opts *bind.TransactOpts, candidate common.Address) (*types.Transaction, error) {\n\treturn _BaseAccessControlGroup.contract.Transact(opts, \"grantAccess\", candidate)\n}", "func (ge *CurrentGrantExecutable) Grant(p string) string {\n\tvar template string\n\tif p == `OWNERSHIP` {\n\t\ttemplate = `GRANT %v ON %v %v TO %v \"%v\" COPY CURRENT GRANTS`\n\t} else {\n\t\ttemplate = `GRANT %v ON %v %v TO %v \"%v\"`\n\t}\n\treturn fmt.Sprintf(template,\n\t\tp, ge.grantType, ge.grantName, ge.granteeType, ge.granteeName)\n}", "func NewSendAction(serviceType, actionName string, args any) *Action {\n\treturn &Action{\n\t\tXMLName: xml.Name{Space: serviceType, Local: actionName},\n\t\tArgs: args,\n\t}\n}", "func (g *projectGateway) CreateProjectAction(params project.CreateProjectParams) middleware.Responder {\n\trsp, err := g.projectClient.Create(context.TODO(), &proto.CreateRequest{\n\t\tName: params.Body.Name,\n\t\tDescription: params.Body.Description,\n\t})\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn project.NewCreateProjectInternalServerError()\n\t}\n\n\tif uint32(codes.OK) == rsp.Status {\n\t\tfmt.Println(fmt.Sprintf(\"project.client: ok. Id = %v\", rsp.Uuid))\n\t} else {\n\t\tfmt.Println(\"project.client: create fail. \")\n\t}\n\n\treadRsp, err := g.projectClient.Read(context.TODO(), &proto.ReadRequest{\n\t\tUuid: rsp.Uuid,\n\t})\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn project.NewCreateProjectInternalServerError()\n\t}\n\n\tpr := &models.Project{\n\t\tUUID: strfmt.UUID(readRsp.Project.Uuid),\n\t\tName: readRsp.Project.Name,\n\t\tDescription: readRsp.Project.Description,\n\t}\n\n\treturn project.NewCreateProjectCreated().WithPayload(pr)\n}", "func NewCreateAction(model store.ClusterManagerModel) *CreateAction {\n\treturn &CreateAction{\n\t\tmodel: model,\n\t}\n}", "func NewAction(app *buffalo.App) *Action {\n\tas := &Action{\n\t\tApp: app,\n\t\tModel: NewModel(),\n\t}\n\treturn as\n}", "func (a *Agent) startNewAction() {\n\tactionTypes := a.mind.actionTypes()\n\n\thighestValue := 0.0\n\tvar bestActionTypes []actionType\n\tfor _, t := range actionTypes {\n\t\tisActive := false\n\t\t// if we currently have an active action, we do not want to start a new action\n\t\tfor _, ac := range a.activity.activeActions {\n\t\t\tif ac.getState() == actionStateActive {\n\t\t\t\tisActive = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif isActive {\n\t\t\treturn\n\t\t}\n\n\t\t// TODO what if an action cannot be started\n\t\t// highest value is to eat an apple, but there is no apple, we should somehow start thinking\n\t\t// about how to obtain an apple\n\n\t\tv := actionTypeValue(t)\n\t\tif v >= highestValue {\n\t\t\tcanStart := true\n\t\t\tfor startCond := range t.getConditions()[actionConditionTypeStart] {\n\t\t\t\tif !startCond.isSatisfied(a) {\n\t\t\t\t\tcanStart = false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif canStart {\n\t\t\t\tif v > highestValue {\n\t\t\t\t\thighestValue = v\n\t\t\t\t\tbestActionTypes = []actionType{}\n\t\t\t\t}\n\t\t\t\tbestActionTypes = append(bestActionTypes, t)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(bestActionTypes) == 0 {\n\t\treturn\n\t}\n\n\tbestActionType := bestActionTypes[rand.Intn(len(bestActionTypes))]\n\tfor startCondition := range bestActionType.getConditions()[actionConditionTypeStart] {\n\t\tif !startCondition.isSatisfied(a) {\n\t\t\treturn\n\t\t}\n\t}\n\n\tnewAction := bestActionType.instantiate().(action)\n\ta.activity.activeActions = append(a.activity.activeActions, newAction)\n\ta.mind.addItem(bestActionType, 1.0)\n\n\t// add pre-action conditions for hypothesis training\n\tfor cond := range a.getConditions() {\n\t\tpreActionConditions := newAction.getType().getConditions()[actionConditionTypeObservedAtStart]\n\t\tpreActionConditions[cond] = true\n\t\tnewAction.getPreConditions()[cond] = true\n\t}\n}", "func createPayback(args []string) {\n\n\tpaybackRepo := payback.NewRepository(persistence.GetGormClient())\n\ttxnRepo := transaction.NewRepository(persistence.GetGormClient())\n\tpaybackSVC := payback.NewPaybackService(paybackRepo, txnRepo)\n\terr := paybackSVC.CreatePayback(context.Background(), args)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\tfmt.Println(\"Successfully added payback\")\n}", "func NewCreateAction(kit kit.Kit, viper *viper.Viper,\n\tauthSvrCli pbauthserver.AuthClient, dataMgrCli pbdatamanager.DataManagerClient,\n\treq *pb.CreateStrategyReq, resp *pb.CreateStrategyResp) *CreateAction {\n\n\taction := &CreateAction{\n\t\tkit: kit,\n\t\tviper: viper,\n\t\tauthSvrCli: authSvrCli,\n\t\tdataMgrCli: dataMgrCli,\n\t\treq: req,\n\t\tresp: resp,\n\t}\n\n\taction.resp.Result = true\n\taction.resp.Code = pbcommon.ErrCode_E_OK\n\taction.resp.Message = \"OK\"\n\n\taction.labelsOr = []map[string]string{}\n\taction.labelsAnd = []map[string]string{}\n\n\treturn action\n}", "func NewBaseAccessWalletTransactor(address common.Address, transactor bind.ContractTransactor) (*BaseAccessWalletTransactor, error) {\n\tcontract, err := bindBaseAccessWallet(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BaseAccessWalletTransactor{contract: contract}, nil\n}", "func (e *ExpectedClusterSetup) WithAction(action interface{}) *ExpectedClusterSetup {\n\te.arg0 = action\n\treturn e\n}", "func (r *refreshTokenGranter) Grant(_ context.Context, requestedScopes []string) grants.Grant {\n\treturn grants.Grant{\n\t\tSourceType: \"refresh_token\",\n\t\tSourceID: r.token.ID,\n\t\tScopes: requestedScopes,\n\t\tAccountID: r.token.AccountID,\n\t\tProfileID: r.token.ProfileID,\n\t\tClientID: r.token.ClientID,\n\t\tUsed: false,\n\t}\n}", "func (k *Kerberos) Grant(encTGT, appID, encAuthenticator string) (*KerberosGrantResult, error) {\n\ttgt := &kerberosTGT{}\n\tif err := k.decrypt(encTGT, k.tgsSecretKey, tgt); err != nil {\n\t\treturn nil, errTGTInvalid\n\t}\n\tif tgt.Expired < time.Now().Unix() {\n\t\treturn nil, errTGTInvalid\n\t}\n\tauthenticator := &kerberosAuthenticator{}\n\tif err := k.decrypt(encAuthenticator, tgt.CTSK, authenticator); err != nil {\n\t\treturn nil, errAuthenticatorInvalid\n\t}\n\n\tvar appSecret string\n\tif appID == \"cell\" {\n\t\tappSecret = k.appSecretKey\n\t} else {\n\t\terr := k.db.QueryRowContext(\n\t\t\tdbCtx(),\n\t\t\t\"SELECT `secret` FROM `app` WHERE `app_id`=? LIMIT 1\",\n\t\t\tappID,\n\t\t).Scan(&appSecret)\n\t\tswitch {\n\t\tcase err == sql.ErrNoRows:\n\t\t\treturn nil, errAppNotExist\n\t\tcase err != nil:\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tst := &kerberosServiceTicket{\n\t\tCSSK: RandToken(),\n\t\tUsername: authenticator.Username,\n\t\tExpired: time.Now().Add(2 * time.Hour).Unix(),\n\t}\n\n\tencCSSK := k.encrypt(st.CSSK, tgt.CTSK)\n\tencST := k.encrypt(st, appSecret)\n\n\tres := &KerberosGrantResult{\n\t\tencCSSK,\n\t\tencST,\n\t}\n\treturn res, nil\n}", "func NewAction(cmd Command) Action {\n\tswitch cmd.name {\n\tcase buildCommand:\n\t\treturn NewBuildAction(afero.NewOsFs(), cmd.helmRepoName, cmd.artifactsPath)\n\tdefault:\n\t\treturn ShowAction{}\n\t}\n}", "func NewRegisterAction(dispatch Dispatch, executor cf.Executor) *HTTPRegisterAction {\n\treturn &HTTPRegisterAction{dispatch, executor}\n}", "func NewWorkloadAgent() *cobra.Command {\n\to := spoke.NewWorkloadAgentOptions()\n\tcmd := controllercmd.\n\t\tNewControllerCommandConfig(\"work-agent\", version.Get(), o.RunWorkloadAgent).\n\t\tNewCommand()\n\tcmd.Use = \"agent\"\n\tcmd.Short = \"Start the Cluster Registration Agent\"\n\n\to.AddFlags(cmd)\n\treturn cmd\n}", "func (m *GraphBaseServiceClient) AgreementAcceptances()(*i3e9b5129e2bb8b32b0374f7afe2536be6674d73df6c41d7c529f5a5432c4e0aa.AgreementAcceptancesRequestBuilder) {\n return i3e9b5129e2bb8b32b0374f7afe2536be6674d73df6c41d7c529f5a5432c4e0aa.NewAgreementAcceptancesRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) AgreementAcceptances()(*i3e9b5129e2bb8b32b0374f7afe2536be6674d73df6c41d7c529f5a5432c4e0aa.AgreementAcceptancesRequestBuilder) {\n return i3e9b5129e2bb8b32b0374f7afe2536be6674d73df6c41d7c529f5a5432c4e0aa.NewAgreementAcceptancesRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func newBreachArbiter(wallet *lnwallet.LightningWallet, db *channeldb.DB,\n\tnotifier chainntnfs.ChainNotifier, h *htlcswitch.Switch,\n\tchain lnwallet.BlockChainIO, fe lnwallet.FeeEstimator) *breachArbiter {\n\n\treturn &breachArbiter{\n\t\twallet: wallet,\n\t\tdb: db,\n\t\tnotifier: notifier,\n\t\tchainIO: chain,\n\t\thtlcSwitch: h,\n\t\testimator: fe,\n\n\t\tbreachObservers: make(map[wire.OutPoint]chan struct{}),\n\t\tbreachedContracts: make(chan *retributionInfo),\n\t\tnewContracts: make(chan *lnwallet.LightningChannel),\n\t\tsettledContracts: make(chan *wire.OutPoint),\n\t\tquit: make(chan struct{}),\n\t}\n}", "func (secretsManager *SecretsManagerV2) CreateSecretAction(createSecretActionOptions *CreateSecretActionOptions) (result SecretActionIntf, response *core.DetailedResponse, err error) {\n\treturn secretsManager.CreateSecretActionWithContext(context.Background(), createSecretActionOptions)\n}", "func NewCheckmate(winner Colour) Outcome { return Outcome{Winner: winner, Reason: checkmate} }", "func (c *Client) CreateCustomActionType(ctx context.Context, params *CreateCustomActionTypeInput, optFns ...func(*Options)) (*CreateCustomActionTypeOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateCustomActionTypeInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateCustomActionType\", params, optFns, addOperationCreateCustomActionTypeMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateCustomActionTypeOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func NewGetConsentActionForbidden() *GetConsentActionForbidden {\n\treturn &GetConsentActionForbidden{}\n}", "func NewRecvAction(args any) *Action {\n\treturn &Action{Args: args}\n}", "func NewAliasAddAction(alias string) *AliasAddAction {\n\treturn &AliasAddAction{\n\t\talias: alias,\n\t}\n}", "func New() *Action {\n\treturn &Action{}\n}", "func AccountGrant() *TerraformGrantResource {\n\treturn &TerraformGrantResource{\n\t\tResource: &schema.Resource{\n\t\t\tCreate: CreateAccountGrant,\n\t\t\tRead: ReadAccountGrant,\n\t\t\tDelete: DeleteAccountGrant,\n\t\t\tUpdate: UpdateAccountGrant,\n\n\t\t\tSchema: accountGrantSchema,\n\t\t\tImporter: &schema.ResourceImporter{\n\t\t\t\tStateContext: schema.ImportStatePassthroughContext,\n\t\t\t},\n\t\t},\n\t\tValidPrivs: validAccountPrivileges,\n\t}\n}", "func (c *Client) Grant(ctx context.Context, i grantRequest) error {\n\tif i == nil {\n\t\treturn fmt.Errorf(\"missing request\")\n\t}\n\n\tswitch t := i.(type) {\n\tcase *SecretManagerGrantRequest:\n\t\treturn c.secretManagerGrant(ctx, t)\n\tcase *StorageGrantRequest:\n\t\treturn c.storageGrant(ctx, t)\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown grant type %T\", t)\n\t}\n}", "func NewActionAgent(\n\ttabletAlias topo.TabletAlias,\n\tdbcfgs *dbconfigs.DBConfigs,\n\tmycnf *mysqlctl.Mycnf,\n\tport, securePort int,\n\toverridesFile string,\n) (agent *ActionAgent, err error) {\n\tschemaOverrides := loadSchemaOverrides(overridesFile)\n\n\ttopoServer := topo.GetServer()\n\tmysqld := mysqlctl.NewMysqld(\"Dba\", mycnf, &dbcfgs.Dba, &dbcfgs.Repl)\n\n\tagent = &ActionAgent{\n\t\tTopoServer: topoServer,\n\t\tTabletAlias: tabletAlias,\n\t\tMysqld: mysqld,\n\t\tDBConfigs: dbcfgs,\n\t\tSchemaOverrides: schemaOverrides,\n\t\tdone: make(chan struct{}),\n\t\tHistory: history.New(historyLength),\n\t\tchangeItems: make(chan tabletChangeItem, 100),\n\t}\n\n\t// Start the binlog player services, not playing at start.\n\tagent.BinlogPlayerMap = NewBinlogPlayerMap(topoServer, &dbcfgs.App.ConnectionParams, mysqld)\n\tRegisterBinlogPlayerMap(agent.BinlogPlayerMap)\n\n\t// try to figure out the mysql port\n\tmysqlPort := mycnf.MysqlPort\n\tif mysqlPort == 0 {\n\t\t// we don't know the port, try to get it from mysqld\n\t\tvar err error\n\t\tmysqlPort, err = mysqld.GetMysqlPort()\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"Cannot get current mysql port, will use 0 for now: %v\", err)\n\t\t}\n\t}\n\n\tif err := agent.Start(mysqlPort, port, securePort); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// register the RPC services from the agent\n\tagent.registerQueryService()\n\n\t// start health check if needed\n\tagent.initHeathCheck()\n\n\treturn agent, nil\n}", "func (a *ManagementApiService) CreateAdditionalCost(ctx _context.Context) apiCreateAdditionalCostRequest {\n\treturn apiCreateAdditionalCostRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (policy *ticketPolicy) OnCreateNewAccount(acc *types.Account) {\n}", "func NewAction(fn ActionFn) *Action {\n\treturn &Action{\n\t\tfn: fn,\n\t\tdoneCh: make(chan struct{}),\n\t}\n}", "func NewCreateAction(viper *viper.Viper, dataMgrCli pbdatamanager.DataManagerClient,\n\treq *pb.CreateAppReq, resp *pb.CreateAppResp) *CreateAction {\n\taction := &CreateAction{viper: viper, dataMgrCli: dataMgrCli, req: req, resp: resp}\n\n\taction.resp.Seq = req.Seq\n\taction.resp.ErrCode = pbcommon.ErrCode_E_OK\n\taction.resp.ErrMsg = \"OK\"\n\n\treturn action\n}", "func NewWatcherAction() *WatcherAction {\n\tr := &WatcherAction{}\n\n\treturn r\n}", "func (_Bep20 *Bep20Transactor) IncreaseAllowance(opts *bind.TransactOpts, spender common.Address, addedValue *big.Int) (*types.Transaction, error) {\n\treturn _Bep20.contract.Transact(opts, \"increaseAllowance\", spender, addedValue)\n}", "func DeployAccessControl(auth *bind.TransactOpts, backend bind.ContractBackend, newCooAddress common.Address, newCfoAddress common.Address) (common.Address, *types.Transaction, *AccessControl, error) {\n\tparsed, err := abi.JSON(strings.NewReader(AccessControlABI))\n\tif err != nil {\n\t\treturn common.Address{}, nil, nil, err\n\t}\n\n\taddress, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(AccessControlBin), backend, newCooAddress, newCfoAddress)\n\tif err != nil {\n\t\treturn common.Address{}, nil, nil, err\n\t}\n\treturn address, tx, &AccessControl{AccessControlCaller: AccessControlCaller{contract: contract}, AccessControlTransactor: AccessControlTransactor{contract: contract}, AccessControlFilterer: AccessControlFilterer{contract: contract}}, nil\n}", "func (_ERC20Mintable *ERC20MintableTransactor) IncreaseAllowance(opts *bind.TransactOpts, spender common.Address, addedValue *big.Int) (*types.Transaction, error) {\n\treturn _ERC20Mintable.contract.Transact(opts, \"increaseAllowance\", spender, addedValue)\n}", "func WarehouseGrant(w string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: w,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\"`, w),\n\t\tgrantType: warehouseType,\n\t}\n}", "func NewActionDrop(from ID, y, x, z int, target ID, cost time.Duration) *ActionDrop {\n\treturn &ActionDrop{\n\t\t// FIXME: Figure out the actual base costs of grabbing. Probably based on the weight + size of the item vs. the character's own strength.\n\t\tAction: Action{\n\t\t\tchannel: cost / 4,\n\t\t\trecovery: cost - cost/4,\n\t\t},\n\t\tFromContainer: from,\n\t\tY: y,\n\t\tX: x,\n\t\tZ: z,\n\t\tTarget: target,\n\t}\n}", "func (_PoC *PoCTransactor) GrantAccess(opts *bind.TransactOpts, _to common.Address) (*types.Transaction, error) {\n\treturn _PoC.contract.Transact(opts, \"grantAccess\", _to)\n}", "func CreateAction(req *http.Request) (interface{}, error) {\n\tparam, err := newCreateParam4Create(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn createActionProcess(req, param)\n}" ]
[ "0.64638203", "0.61863166", "0.5534939", "0.529289", "0.5087931", "0.50345194", "0.47454304", "0.46657106", "0.4555626", "0.4545793", "0.45320782", "0.44856998", "0.4456182", "0.4451843", "0.43959028", "0.43657944", "0.43611333", "0.4357266", "0.43521774", "0.43518445", "0.4342636", "0.4329987", "0.43060848", "0.42648292", "0.42588392", "0.4252665", "0.42193332", "0.41813338", "0.41631073", "0.41591522", "0.414936", "0.4148485", "0.4148031", "0.4148031", "0.41458014", "0.41381583", "0.41272053", "0.41251236", "0.4120189", "0.4117049", "0.41026032", "0.409719", "0.409719", "0.4089132", "0.40850285", "0.4067299", "0.40628877", "0.40519452", "0.4044426", "0.40214482", "0.40111047", "0.39920577", "0.39909425", "0.3972872", "0.397195", "0.39714217", "0.39708492", "0.39696768", "0.39696768", "0.3968721", "0.39663094", "0.3965848", "0.3961613", "0.39577794", "0.39468104", "0.3944364", "0.39432076", "0.3938256", "0.3932838", "0.39273572", "0.39171672", "0.39135587", "0.38784057", "0.38568297", "0.38341925", "0.38304314", "0.38304314", "0.38224214", "0.38212886", "0.38017103", "0.37991813", "0.37962076", "0.37957823", "0.37827736", "0.37799823", "0.37791502", "0.37763605", "0.37529483", "0.37504405", "0.3749062", "0.37438357", "0.37399977", "0.37374473", "0.3736979", "0.37366566", "0.37342247", "0.37339973", "0.37281507", "0.37269688", "0.3720736" ]
0.7976986
0
AddToAccount implements the exported.AddGrantAction interface. It checks that rawAccount is a ClawbackVestingAccount with the same funder and adds the described Grant to it.
func (cga clawbackGrantAction) AddToAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error { cva, ok := rawAccount.(*ClawbackVestingAccount) if !ok { return sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "account %s must be a ClawbackVestingAccount, got %T", rawAccount.GetAddress(), rawAccount) } if cga.funderAddress != cva.FunderAddress { return sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "account %s can only accept grants from account %s", rawAccount.GetAddress(), cva.FunderAddress) } cva.addGrant(ctx, cga.sk, cga.grantStartTime, cga.grantLockupPeriods, cga.grantVestingPeriods, cga.grantCoins) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pga periodicGrantAction) AddToAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tpva, ok := rawAccount.(*PeriodicVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported,\n\t\t\t\"account %s must be a PeriodicVestingAccount, got %T\",\n\t\t\trawAccount.GetAddress(), rawAccount)\n\t}\n\tpva.addGrant(ctx, pga.sk, pga.grantStartTime, pga.grantVestingPeriods, pga.grantCoins)\n\treturn nil\n}", "func (_Storage *StorageTransactor) AddAccount(opts *bind.TransactOpts, addr common.Address, kind uint8, isFrozen bool, parent common.Address) (*types.Transaction, error) {\n\treturn _Storage.contract.Transact(opts, \"addAccount\", addr, kind, isFrozen, parent)\n}", "func (_Storage *StorageTransactorSession) AddAccount(addr common.Address, kind uint8, isFrozen bool, parent common.Address) (*types.Transaction, error) {\n\treturn _Storage.Contract.AddAccount(&_Storage.TransactOpts, addr, kind, isFrozen, parent)\n}", "func (pva *PeriodicVestingAccount) AddGrant(ctx sdk.Context, action exported.AddGrantAction) error {\n\treturn action.AddToAccount(ctx, pva)\n}", "func (_Storage *StorageSession) AddAccount(addr common.Address, kind uint8, isFrozen bool, parent common.Address) (*types.Transaction, error) {\n\treturn _Storage.Contract.AddAccount(&_Storage.TransactOpts, addr, kind, isFrozen, parent)\n}", "func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV + DF by capping slashed at the current unvested amount\n\tunvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime()))\n\tnewSlashed := coinsMin(slashed, unvested)\n\tnewDelegated := delegated.Add(newSlashed...)\n\n\t// modify schedules for the new grant\n\tnewLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods)\n\tnewVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime,\n\t\tva.GetVestingPeriods(), grantVestingPeriods)\n\tif newLockupStart != newVestingStart {\n\t\tpanic(\"bad start time calculation\")\n\t}\n\tva.StartTime = newLockupStart\n\tva.EndTime = max64(newLockupEnd, newVestingEnd)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\tva.OriginalVesting = va.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newDelegated\n\tunvested2 := va.GetVestingCoins(ctx.BlockTime())\n\tva.DelegatedVesting = coinsMin(newDelegated, unvested2)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n}", "func (trd *trxDispatcher) pushAccount(at string, adr *common.Address, blk *types.Block, trx *types.Transaction, wg *sync.WaitGroup) bool {\n\twg.Add(1)\n\tselect {\n\tcase trd.outAccount <- &eventAcc{\n\t\twatchDog: wg,\n\t\taddr: adr,\n\t\tact: at,\n\t\tblk: blk,\n\t\ttrx: trx,\n\t\tdeploy: nil,\n\t}:\n\tcase <-trd.sigStop:\n\t\treturn false\n\t}\n\treturn true\n}", "func (t *SimpleChaincode) add_account(stub *shim.ChaincodeStub, args []string) ([]byte, error) {\n\n\t//Args\n\t//\t\t\t0\t\t\t\t1\n\t//\t\t index\t\taccount JSON object (as string)\n\n\tid, err := append_id(stub, accountIndexStr, args[0], false)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Error creating new id for user \" + args[0])\n\t}\n\n\terr = stub.PutState(string(id), []byte(args[1]))\n\tif err != nil {\n\t\treturn nil, errors.New(\"Error putting user data on ledger\")\n\t}\n\n\treturn nil, nil\n}", "func (_TxRelay *TxRelayTransactor) AddToWhitelist(opts *bind.TransactOpts, addr common.Address) (*types.Transaction, error) {\n\treturn _TxRelay.contract.Transact(opts, \"addToWhitelist\", addr)\n}", "func (m *MockupAccountProvider) Add(account entities.Account) derrors.Error {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tif !m.unsafeExists(account.AccountId) {\n\t\tm.accounts[account.AccountId] = account\n\t\tm.accountNames[account.Name] = true\n\t\treturn nil\n\t}\n\treturn derrors.NewAlreadyExistsError(account.AccountId)\n}", "func (ca clawbackAction) TakeFromAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported, \"clawback expects *ClawbackVestingAccount, got %T\", rawAccount)\n\t}\n\tif ca.requestor.String() != cva.FunderAddress {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"clawback can only be requested by original funder %s\", cva.FunderAddress)\n\t}\n\treturn cva.clawback(ctx, ca.dest, ca.ak, ca.bk, ca.sk)\n}", "func (pva *PeriodicVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, pva.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, pva.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := pva.DelegatedVesting.Add(pva.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV+DF by capping slashed at the current unvested amount\n\tunvested := pva.GetVestingCoins(ctx.BlockTime())\n\tnewSlashed := coinsMin(unvested, slashed)\n\tnewTotalDelegated := delegated.Add(newSlashed...)\n\n\t// modify vesting schedule for the new grant\n\tnewStart, newEnd, newPeriods := DisjunctPeriods(pva.StartTime, grantStartTime,\n\t\tpva.GetVestingPeriods(), grantVestingPeriods)\n\tpva.StartTime = newStart\n\tpva.EndTime = newEnd\n\tpva.VestingPeriods = newPeriods\n\tpva.OriginalVesting = pva.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newTotalDelegated\n\tunvested2 := pva.GetVestingCoins(ctx.BlockTime())\n\tpva.DelegatedVesting = coinsMin(newTotalDelegated, unvested2)\n\tpva.DelegatedFree = newTotalDelegated.Sub(pva.DelegatedVesting)\n}", "func (e *copyS2SMigrationFileEnumerator) addTransferFromAccount(ctx context.Context,\n\tsrcServiceURL azfile.ServiceURL, destBaseURL url.URL,\n\tsharePrefix, fileOrDirectoryPrefix, fileNamePattern string, cca *cookedCopyCmdArgs) error {\n\treturn enumerateSharesInAccount(\n\t\tctx,\n\t\tsrcServiceURL,\n\t\tsharePrefix,\n\t\tfunc(shareItem azfile.ShareItem) error {\n\t\t\t// Whatever the destination type is, it should be equivalent to account level,\n\t\t\t// so directly append share name to it.\n\t\t\ttmpDestURL := urlExtension{URL: destBaseURL}.generateObjectPath(shareItem.Name)\n\t\t\t// create bucket for destination, in case bucket doesn't exist.\n\t\t\tif err := e.createDestBucket(ctx, tmpDestURL, nil); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Two cases for exclude/include which need to match share names in account:\n\t\t\t// a. https://<fileservice>/share*/file*.vhd\n\t\t\t// b. https://<fileservice>/ which equals to https://<fileservice>/*\n\t\t\treturn e.addTransfersFromDirectory(\n\t\t\t\tctx,\n\t\t\t\tsrcServiceURL.NewShareURL(shareItem.Name).NewRootDirectoryURL(),\n\t\t\t\ttmpDestURL,\n\t\t\t\tfileOrDirectoryPrefix,\n\t\t\t\tfileNamePattern,\n\t\t\t\t\"\",\n\t\t\t\ttrue,\n\t\t\t\ttrue,\n\t\t\t\tcca)\n\t\t})\n}", "func (client *Client) GrantAccountPrivilegeWithOptions(request *GrantAccountPrivilegeRequest, runtime *util.RuntimeOptions) (_result *GrantAccountPrivilegeResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tquery := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.AccountName)) {\n\t\tquery[\"AccountName\"] = request.AccountName\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.AccountPrivilege)) {\n\t\tquery[\"AccountPrivilege\"] = request.AccountPrivilege\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.InstanceId)) {\n\t\tquery[\"InstanceId\"] = request.InstanceId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerAccount)) {\n\t\tquery[\"OwnerAccount\"] = request.OwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerId)) {\n\t\tquery[\"OwnerId\"] = request.OwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerAccount)) {\n\t\tquery[\"ResourceOwnerAccount\"] = request.ResourceOwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerId)) {\n\t\tquery[\"ResourceOwnerId\"] = request.ResourceOwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.SecurityToken)) {\n\t\tquery[\"SecurityToken\"] = request.SecurityToken\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tQuery: openapiutil.Query(query),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"GrantAccountPrivilege\"),\n\t\tVersion: tea.String(\"2015-01-01\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &GrantAccountPrivilegeResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func (auth Authenticate) RegisterAccount(session *types.Session, newAccount *types.Account) (string, error) {\n\taccount, err := auth.CheckAccountSession(session)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t//Get Account Roles\n\taccount = account.GetAccountPermissions()\n\n\t//Only Accounts with ADMIN privliges can make this request\n\tif !utils.Contains(\"ADMIN\", account.Roles) {\n\t\treturn \"\", errors.New(\"Invalid Privilges: \" + account.Name)\n\t}\n\n\t//Get newAccount Roles\n\tnewAccount = newAccount.GetAccountPermissions()\n\n\tres, err := manager.AccountManager{}.CreateAccount(newAccount, account, auth.DB)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn res, nil\n}", "func (_PermInterface *PermInterfaceTransactor) AddAdminAccount(opts *bind.TransactOpts, _acct common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"addAdminAccount\", _acct)\n}", "func (e *copyS2SMigrationBlobEnumerator) addTransferFromAccount(ctx context.Context,\n\tsrcServiceURL azblob.ServiceURL, destBaseURL url.URL,\n\tcontainerPrefix, blobPrefix, blobNamePattern string, cca *cookedCopyCmdArgs) error {\n\treturn enumerateContainersInAccount(\n\t\tctx,\n\t\tsrcServiceURL,\n\t\tcontainerPrefix,\n\t\tfunc(containerItem azblob.ContainerItem) error {\n\t\t\t// Whatever the destination type is, it should be equivalent to account level,\n\t\t\t// so directly append container name to it.\n\t\t\ttmpDestURL := urlExtension{URL: destBaseURL}.generateObjectPath(containerItem.Name)\n\t\t\t// create bucket for destination, in case bucket doesn't exist.\n\t\t\tif err := e.createDestBucket(ctx, tmpDestURL, nil); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Two cases for exclude/include which need to match container names in account:\n\t\t\t// a. https://<blobservice>/container*/blob*.vhd\n\t\t\t// b. https://<blobservice>/ which equals to https://<blobservice>/*\n\t\t\treturn e.addTransfersFromContainer(\n\t\t\t\tctx,\n\t\t\t\tsrcServiceURL.NewContainerURL(containerItem.Name),\n\t\t\t\ttmpDestURL,\n\t\t\t\tblobPrefix,\n\t\t\t\tblobNamePattern,\n\t\t\t\t\"\",\n\t\t\t\ttrue,\n\t\t\t\ttrue,\n\t\t\t\tcca)\n\t\t})\n}", "func (service *AccountService) AddAccount(ctx context.Context, req *protoAccount.NewAccountRequest, res *protoAccount.AccountResponse) error {\n\t// supported exchange keys check\n\tif !supportedExchange(req.Exchange) {\n\t\tres.Status = constRes.Fail\n\t\tres.Message = fmt.Sprintf(\"%s is not supported\", req.Exchange)\n\t\treturn nil\n\t}\n\tif !supportedType(req.AccountType) {\n\t\tres.Status = constRes.Fail\n\t\tres.Message = fmt.Sprintf(\"accountType must be paper or real\")\n\t\treturn nil\n\t}\n\n\taccountID := uuid.New().String()\n\tnow := string(pq.FormatTimestamp(time.Now().UTC()))\n\tbalances := make([]*protoBalance.Balance, 0, len(req.Balances))\n\n\t// user specified balances will be ignored if a\n\t// valid public/secret is send in with request\n\tfor _, b := range req.Balances {\n\t\tbalance := protoBalance.Balance{\n\t\t\tUserID: req.UserID,\n\t\t\tAccountID: accountID,\n\t\t\tCurrencySymbol: b.CurrencySymbol,\n\t\t\tAvailable: b.Available,\n\t\t\tLocked: 0,\n\t\t\tCreatedOn: now,\n\t\t\tUpdatedOn: now,\n\t\t}\n\t\tbalances = append(balances, &balance)\n\t}\n\n\t// assume account valid\n\taccount := protoAccount.Account{\n\t\tAccountID: accountID,\n\t\tAccountType: req.AccountType,\n\t\tUserID: req.UserID,\n\t\tExchange: req.Exchange,\n\t\tKeyPublic: req.KeyPublic,\n\t\tKeySecret: util.Rot32768(req.KeySecret),\n\t\tTitle: req.Title,\n\t\tColor: req.Color,\n\t\tDescription: req.Description,\n\t\tStatus: constAccount.AccountValid,\n\t\tCreatedOn: now,\n\t\tUpdatedOn: now,\n\t\tBalances: balances,\n\t}\n\n\t// validate account request when keys are present\n\tswitch {\n\tcase account.KeyPublic != \"\" && account.KeySecret == \"\":\n\t\tres.Status = constRes.Fail\n\t\tres.Message = \"keySecret required with keyPublic!\"\n\t\treturn nil\n\tcase account.KeyPublic == \"\" && account.KeySecret != \"\":\n\t\tres.Status = constRes.Fail\n\t\tres.Message = \"keyPublic required with keySecret!\"\n\t\treturn nil\n\tcase account.Color == \"\":\n\t\tres.Status = constRes.Fail\n\t\tres.Message = \"color required\"\n\t\treturn nil\n\t}\n\n\tswitch {\n\tcase account.Exchange == constExch.Binance && account.AccountType == constAccount.AccountReal:\n\t\t// if api key ask exchange for balances\n\t\tif account.KeyPublic == \"\" || account.KeySecret == \"\" {\n\t\t\tres.Status = constRes.Fail\n\t\t\tres.Message = \"keyPublic and keySecret required!\"\n\t\t\treturn nil\n\t\t}\n\t\treqBal := protoBinanceBal.BalanceRequest{\n\t\t\tUserID: account.UserID,\n\t\t\tKeyPublic: account.KeyPublic,\n\t\t\tKeySecret: util.Rot32768(account.KeySecret),\n\t\t}\n\t\tresBal, _ := service.BinanceClient.GetBalances(ctx, &reqBal)\n\n\t\t// reponse to client on invalid key\n\t\tif resBal.Status != constRes.Success {\n\t\t\tres.Status = resBal.Status\n\t\t\tres.Message = resBal.Message\n\t\t\treturn nil\n\t\t}\n\n\t\texBalances := make([]*protoBalance.Balance, 0)\n\t\tfor _, b := range resBal.Data.Balances {\n\t\t\ttotal := b.Free + b.Locked\n\n\t\t\t// only add non-zero balances\n\t\t\tif total > 0 {\n\t\t\t\tbalance := protoBalance.Balance{\n\t\t\t\t\tUserID: account.UserID,\n\t\t\t\t\tAccountID: account.AccountID,\n\t\t\t\t\tCurrencySymbol: b.CurrencySymbol,\n\t\t\t\t\tAvailable: b.Free,\n\t\t\t\t\tLocked: 0.0,\n\t\t\t\t\tExchangeTotal: total,\n\t\t\t\t\tExchangeAvailable: b.Free,\n\t\t\t\t\tExchangeLocked: b.Locked,\n\t\t\t\t\tCreatedOn: now,\n\t\t\t\t\tUpdatedOn: now,\n\t\t\t\t}\n\n\t\t\t\texBalances = append(exBalances, &balance)\n\t\t\t}\n\t\t}\n\t\taccount.Balances = exBalances\n\t}\n\n\tif err := repoAccount.InsertAccount(service.DB, &account); err != nil {\n\t\tmsg := fmt.Sprintf(\"insert account failed %s\", err.Error())\n\t\tlog.Println(msg)\n\n\t\tres.Status = constRes.Error\n\t\tres.Message = msg\n\t}\n\n\tres.Status = constRes.Success\n\tres.Data = &protoAccount.UserAccount{Account: &account}\n\n\treturn nil\n}", "func create_account_ (stub shim.ChaincodeStubInterface, account *Account) error {\n var old_account Account\n row_was_found,err := util.InsertTableRow(stub, ACCOUNT_TABLE, row_keys_of_Account(account), account, util.FAIL_BEFORE_OVERWRITE, &old_account)\n if err != nil {\n return err\n }\n if row_was_found {\n return fmt.Errorf(\"Could not create account %v because an account with that Name already exists\", *account)\n }\n return nil // success\n}", "func (policy *ticketPolicy) OnCreateNewAccount(acc *types.Account) {\n}", "func AddAccountReference(user *jenkinsv1.User, gitProviderKey string, id string) *jenkinsv1.User {\n\tif user.Spec.Accounts == nil {\n\t\tuser.Spec.Accounts = make([]jenkinsv1.AccountReference, 0)\n\t}\n\tuser.Spec.Accounts = append(user.Spec.Accounts, jenkinsv1.AccountReference{\n\t\tProvider: gitProviderKey,\n\t\tID: id,\n\t})\n\tif user.ObjectMeta.Labels == nil {\n\t\tuser.ObjectMeta.Labels = make(map[string]string)\n\t}\n\tuser.ObjectMeta.Labels[gitProviderKey] = id\n\treturn user\n}", "func (_TxRelay *TxRelayTransactorSession) AddToWhitelist(addr common.Address) (*types.Transaction, error) {\n\treturn _TxRelay.Contract.AddToWhitelist(&_TxRelay.TransactOpts, addr)\n}", "func addFoundryToAccount(state kv.KVStore, agentID isc.AgentID, sn uint32) {\n\tkey := codec.EncodeUint32(sn)\n\tfoundries := accountFoundriesMap(state, agentID)\n\tif foundries.HasAt(key) {\n\t\tpanic(ErrRepeatingFoundrySerialNumber)\n\t}\n\tfoundries.SetAt(key, codec.EncodeBool(true))\n}", "func (_TxRelay *TxRelaySession) AddToWhitelist(addr common.Address) (*types.Transaction, error) {\n\treturn _TxRelay.Contract.AddToWhitelist(&_TxRelay.TransactOpts, addr)\n}", "func (_PermInterface *PermInterfaceTransactorSession) AddAdminAccount(_acct common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.AddAdminAccount(&_PermInterface.TransactOpts, _acct)\n}", "func AddAccount(ctx context.Context, tconn *chrome.TestConn, email, password string) error {\n\t// Set up keyboard.\n\tkb, err := input.VirtualKeyboard(ctx)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get keyboard\")\n\t}\n\tdefer kb.Close()\n\n\tui := uiauto.New(tconn).WithTimeout(DefaultUITimeout)\n\n\tif err := startAddAccount(ctx, kb, ui, email); err != nil {\n\t\treturn errors.Wrap(err, \"failed to start account addition\")\n\t}\n\n\t// All nodes in the dialog should be inside the `root`.\n\troot := AddAccountDialog()\n\n\tpasswordField := nodewith.Name(\"Enter your password\").Role(role.TextField).Ancestor(root)\n\tnextButton := nodewith.Name(\"Next\").Role(role.Button).Ancestor(root)\n\tiAgreeButton := nodewith.Name(\"I agree\").Role(role.Button).Ancestor(root)\n\n\tif err := uiauto.Combine(\"Enter email and password\",\n\t\t// Enter the User Name.\n\t\tkb.TypeAction(email+\"\\n\"),\n\t\tui.WaitUntilExists(passwordField),\n\t\tui.LeftClick(passwordField),\n\t\t// Enter the Password.\n\t\tkb.TypeAction(password),\n\t\tui.LeftClick(nextButton),\n\t\t// We need to focus the button first to click at right location\n\t\t// as it returns wrong coordinates when button is offscreen.\n\t\tui.FocusAndWait(iAgreeButton),\n\t\tui.LeftClick(iAgreeButton),\n\t)(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to enter email and password\")\n\t}\n\n\treturn nil\n}", "func (am *AccountManager) AddAccount(a *Account) {\n\tam.cmdChan <- &addAccountCmd{\n\t\ta: a,\n\t}\n}", "func AddLightweightAccountScope(role authpb.Role, scopes map[string]*authpb.Scope) (map[string]*authpb.Scope, error) {\n\tref := &provider.Reference{Path: \"/\"}\n\tval, err := utils.MarshalProtoV1ToJSON(ref)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif scopes == nil {\n\t\tscopes = make(map[string]*authpb.Scope)\n\t}\n\tscopes[\"lightweight\"] = &authpb.Scope{\n\t\tResource: &types.OpaqueEntry{\n\t\t\tDecoder: \"json\",\n\t\t\tValue: val,\n\t\t},\n\t\tRole: role,\n\t}\n\treturn scopes, nil\n}", "func (r Runner) AddAccount(ctx context.Context, name, mnemonic string) (Account, error) {\n\tb := &bytes.Buffer{}\n\n\t// check if account already exists.\n\tvar accounts []Account\n\tif err := r.run(ctx, runOptions{stdout: b}, r.cc.ListKeysCommand()); err != nil {\n\t\treturn Account{}, err\n\t}\n\tif err := json.NewDecoder(b).Decode(&accounts); err != nil {\n\t\treturn Account{}, err\n\t}\n\tfor _, account := range accounts {\n\t\tif account.Name == name {\n\t\t\treturn Account{}, ErrAccountAlreadyExists\n\t\t}\n\t}\n\tb.Reset()\n\n\taccount := Account{\n\t\tName: name,\n\t\tMnemonic: mnemonic,\n\t}\n\n\t// import the account when mnemonic is provided, otherwise create a new one.\n\tif mnemonic != \"\" {\n\t\tinput := &bytes.Buffer{}\n\t\tfmt.Fprintln(input, mnemonic)\n\n\t\tif r.cc.KeyringPassword != \"\" {\n\t\t\tfmt.Fprintln(input, r.cc.KeyringPassword)\n\t\t\tfmt.Fprintln(input, r.cc.KeyringPassword)\n\t\t}\n\n\t\tif err := r.run(\n\t\t\tctx,\n\t\t\trunOptions{},\n\t\t\tr.cc.ImportKeyCommand(name),\n\t\t\tstep.Write(input.Bytes()),\n\t\t); err != nil {\n\t\t\treturn Account{}, err\n\t\t}\n\t} else {\n\t\t// note that, launchpad prints account output from stderr.\n\t\tif err := r.run(ctx, runOptions{stdout: b, stderr: b}, r.cc.AddKeyCommand(name)); err != nil {\n\t\t\treturn Account{}, err\n\t\t}\n\t\tif err := json.NewDecoder(b).Decode(&account); err != nil {\n\t\t\treturn Account{}, err\n\t\t}\n\n\t\tb.Reset()\n\t}\n\n\t// get full details of the account.\n\topt := []step.Option{\n\t\tr.cc.ShowKeyAddressCommand(name),\n\t}\n\n\tif r.cc.KeyringPassword != \"\" {\n\t\tinput := &bytes.Buffer{}\n\t\tfmt.Fprintln(input, r.cc.KeyringPassword)\n\t\topt = append(opt, step.Write(input.Bytes()))\n\t}\n\n\tif err := r.run(ctx, runOptions{stdout: b}, opt...); err != nil {\n\t\treturn Account{}, err\n\t}\n\taccount.Address = strings.TrimSpace(b.String())\n\n\treturn account, nil\n}", "func (r *RBAC) AddToWhiteList(system, uid string, permissions ...string) error {\n\tr.Cache.RemoveUser(system, uid)\n\treturn r.User.AddToWhiteList(system, uid, permissions...)\n}", "func (mam *MockAccountModel) AddAccount(email, password string) error {\n\targs := mam.Called(email, password)\n\n\treturn args.Error(0)\n}", "func (s *Service) AddAccount(acc *entity.Account) (*entity.Account, error) {\n\t_, err := govalidator.ValidateStruct(acc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.repo.AddAccount(acc)\n}", "func (_ChpRegistry *ChpRegistryTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _ChpRegistry.contract.Transact(opts, \"addPauser\", account)\n}", "func (client *Client) GrantAccountPrivilege(request *GrantAccountPrivilegeRequest) (_result *GrantAccountPrivilegeResponse, _err error) {\n\truntime := &util.RuntimeOptions{}\n\t_result = &GrantAccountPrivilegeResponse{}\n\t_body, _err := client.GrantAccountPrivilegeWithOptions(request, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_result = _body\n\treturn _result, _err\n}", "func (a *Client) AddWhitelist(params *AddWhitelistParams) (*AddWhitelistOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewAddWhitelistParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"addWhitelist\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/asset/tokens/{symbol}/forbidden/whitelist\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &AddWhitelistReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*AddWhitelistOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for addWhitelist: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (s *Service) CreateAccount(budgetID string, accountPayload PayloadAccount) (*Account, error) {\n\tresModel := struct {\n\t\tData struct {\n\t\t\tAccount *Account `json:\"account\"`\n\t\t} `json:\"data\"`\n\t}{}\n\n\tpayload := struct {\n\t\tAccount PayloadAccount `json:\"account\"`\n\t}{\n\t\taccountPayload,\n\t}\n\n\tbuf, err := json.Marshal(&payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\turl := fmt.Sprintf(\"/budgets/%s/accounts/\", budgetID)\n\tif err := s.c.POST(url, &resModel, buf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resModel.Data.Account, nil\n}", "func CreateAccount(u usecase.UseCase) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar a presenter.Account\n\t\terr := c.BindJSON(&a)\n\t\tif err != nil {\n\t\t\tresponseFailure(c, http.StatusText(http.StatusInternalServerError),\n\t\t\t\t\"Account can't be created\",\n\t\t\t\t\"Error when converting the parameters sent to json\", \"\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tacc, err := u.NewAccount(&account.Account{\n\t\t\tID: a.ID, DocumentNumber: a.DocumentNumber,\n\t\t\tAvailableCreditLimit: a.AvailableCreditLimit,\n\t\t})\n\t\tif err != nil {\n\t\t\tresponseFailure(c, http.StatusText(http.StatusInternalServerError),\n\t\t\t\t\"Account can't be created\",\n\t\t\t\tfmt.Sprintf(\"Internal server error when creating a new account - datails err: %s\", err.Error()), \"\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusCreated, acc)\n\t}\n}", "func (_OwnedUpgradeableTokenStorage *OwnedUpgradeableTokenStorageTransactor) AddOwner(opts *bind.TransactOpts, _newOwner common.Address) (*types.Transaction, error) {\n\treturn _OwnedUpgradeableTokenStorage.contract.Transact(opts, \"addOwner\", _newOwner)\n}", "func (c *AccountController) Create(ctx echo.Context) error {\n\tmodel := account.Account{}\n\terr := ctx.Bind(&model)\n\tif err != nil {\n\t\treturn ctx.JSON(http.StatusUnprocessableEntity, err.Error())\n\t}\n\n\tres, err := c.AccountUsecase.Create(&model)\n\tif err != nil {\n\t\treturn ctx.JSON(http.StatusInternalServerError, err.Error())\n\t}\n\n\treturn ctx.JSON(http.StatusCreated, res)\n}", "func (cl *CustodianLedger) AddAccountToLedger(account *Bankaccount) {\n\tnewData := account\n\tcl.Ledger = append(cl.Ledger, newData)\n}", "func AdditionalAccount(cluster string, tier toolchainv1alpha1.NSTemplateTier, modifiers ...UaInMurModifier) MurModifier {\n\treturn func(mur *toolchainv1alpha1.MasterUserRecord) error {\n\t\ttemplates := nstemplateSetFromTier(tier)\n\t\tua := toolchainv1alpha1.UserAccountEmbedded{\n\t\t\tTargetCluster: cluster,\n\t\t\tSyncIndex: \"123abc\", // default value\n\t\t\tSpec: toolchainv1alpha1.UserAccountSpecEmbedded{\n\t\t\t\tUserAccountSpecBase: toolchainv1alpha1.UserAccountSpecBase{\n\t\t\t\t\tNSLimit: tier.Name,\n\t\t\t\t\tNSTemplateSet: templates,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\t// set the user account\n\t\tmur.Spec.UserAccounts = append(mur.Spec.UserAccounts, ua)\n\t\tfor _, modify := range modifiers {\n\t\t\tmodify(cluster, mur)\n\t\t}\n\t\t// set the labels for the tier templates in use\n\t\thash, err := computeTemplateRefsHash(tier)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmur.ObjectMeta.Labels = map[string]string{\n\t\t\ttoolchainv1alpha1.LabelKeyPrefix + tier.Name + \"-tier-hash\": hash,\n\t\t}\n\t\treturn nil\n\t}\n}", "func (b *OGame) AddAccount(number int, lang string) (*AddAccountRes, error) {\n\treturn b.addAccount(number, lang)\n}", "func (_TTFT20 *TTFT20Transactor) RegisterWithdrawalAddress(opts *bind.TransactOpts, addr common.Address) (*types.Transaction, error) {\n\treturn _TTFT20.contract.Transact(opts, \"registerWithdrawalAddress\", addr)\n}", "func (Mutation) UpsertAccount(\n\tctx context.Context,\n\tinput generated.UpsertAccountInput,\n) (*generated.UpsertAccountPayload, error) {\n\tdbi := db.GetDB(ctx)\n\ta := auth.GetAuth(ctx)\n\tif a == nil {\n\t\treturn nil, auth.ErrNoToken\n\t}\n\n\tmodel := models.Account{\n\t\tAuthID: a.AuthID,\n\t\tName: input.Name,\n\t\tSurname: input.Surname,\n\t\tEmail: input.Email,\n\t}\n\n\tif err := model.Upsert(ctx, dbi, true, []string{\"auth_id\"}, boil.Infer(), boil.Infer()); err != nil {\n\t\traven.CaptureError(err, nil)\n\t\treturn nil, db.ErrDefault\n\t}\n\n\tres := generated.UpsertAccountPayload{\n\t\tAccount: &schemas.Account{Account: model},\n\t\tClientMutationID: input.ClientMutationID,\n\t}\n\n\treturn &res, nil\n}", "func (_Token *TokenTransactor) AddWhitelisted(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _Token.contract.Transact(opts, \"addWhitelisted\", account)\n}", "func (_PermInterface *PermInterfaceSession) AddAdminAccount(_acct common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.AddAdminAccount(&_PermInterface.TransactOpts, _acct)\n}", "func Create(w http.ResponseWriter, r *http.Request) {\n\n\taccountDecoder := json.NewDecoder(r.Body)\n\tvar accData Account\n\terr := accountDecoder.Decode(&accData)\n\tif err != nil {\n\t\tlog.Fatalln(\"error:\", err)\n\t}\n\taccData.CreateAccount()\n\tfmt.Fprintf(w, \"Account added successfully\")\n}", "func Account(cluster string, tier toolchainv1alpha1.NSTemplateTier, modifiers ...UaInMurModifier) MurModifier {\n\treturn func(mur *toolchainv1alpha1.MasterUserRecord) error {\n\t\tmur.Spec.UserAccounts = []toolchainv1alpha1.UserAccountEmbedded{}\n\t\treturn AdditionalAccount(cluster, tier, modifiers...)(mur)\n\t}\n}", "func (_BREMFactory *BREMFactoryTransactor) AddAuditor(opts *bind.TransactOpts, _newAuditor common.Address) (*types.Transaction, error) {\n\treturn _BREMFactory.contract.Transact(opts, \"addAuditor\", _newAuditor)\n}", "func CreateAccount(w http.ResponseWriter, r *http.Request) {\n\tvar acc models.Account\n\t_ = json.NewDecoder(r.Body).Decode(&acc)\n\n\tracc, err := models.CreateAccount(acc)\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t_, _ = fmt.Fprintf(w, err.Error())\n\t} else {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t_ = json.NewEncoder(w).Encode(racc)\n\t}\n}", "func (_TTFT20 *TTFT20Transactor) AddOwner(opts *bind.TransactOpts, _newOwner common.Address) (*types.Transaction, error) {\n\treturn _TTFT20.contract.Transact(opts, \"addOwner\", _newOwner)\n}", "func (_Pausable *PausableTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _Pausable.contract.Transact(opts, \"addPauser\", account)\n}", "func handleACCOUNT(c *Client, e Event) {\n\tif len(e.Params) != 1 {\n\t\treturn\n\t}\n\n\taccount := e.Params[0]\n\tif account == \"*\" {\n\t\taccount = \"\"\n\t}\n\n\tc.state.Lock()\n\tuser := c.state.lookupUser(e.Source.Name)\n\tif user != nil {\n\t\tuser.Extras.Account = account\n\t}\n\tc.state.Unlock()\n\tc.state.notify(c, UPDATE_STATE)\n}", "func (p *Person) AddNameRaw(fullName string) error {\n\n\t// Do we have a valid name?\n\tif len(fullName) <= 5 {\n\t\treturn ErrNameTooShort\n\t}\n\n\t// Start the name\n\tnewName := new(Name)\n\tnewName.Raw = fullName\n\tp.Names = append(p.Names, *newName)\n\treturn nil\n}", "func (_Upgradeable *UpgradeableTransactor) AddOwner(opts *bind.TransactOpts, _newOwner common.Address) (*types.Transaction, error) {\n\treturn _Upgradeable.contract.Transact(opts, \"addOwner\", _newOwner)\n}", "func (_ERC20Pausable *ERC20PausableTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _ERC20Pausable.contract.Transact(opts, \"addPauser\", account)\n}", "func Create(w http.ResponseWriter, r *http.Request) {\n\tauthUser, err := auth.GetUserFromJWT(w, r)\n\tif err != nil {\n\t\tresponse.FormatStandardResponse(false, \"error-auth\", \"\", err.Error(), w)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\n\t// Decode the JSON body\n\tacct := datastore.Account{}\n\terr = json.NewDecoder(r.Body).Decode(&acct)\n\tswitch {\n\t// Check we have some data\n\tcase err == io.EOF:\n\t\tresponse.FormatStandardResponse(false, \"error-account-data\", \"\", \"No account data supplied.\", w)\n\t\treturn\n\t\t// Check for parsing errors\n\tcase err != nil:\n\t\tresponse.FormatStandardResponse(false, \"error-decode-json\", \"\", err.Error(), w)\n\t\treturn\n\t}\n\n\tcreateHandler(w, authUser, false, acct)\n}", "func (_Owned *OwnedTransactor) AddOwner(opts *bind.TransactOpts, _newOwner common.Address) (*types.Transaction, error) {\n\treturn _Owned.contract.Transact(opts, \"addOwner\", _newOwner)\n}", "func (c *Client) Grant(email string) {\n\tif c.CI {\n\t\temail = strings.ToLower(email)\n\t}\n\tc.mu.Lock()\n\tc.whitelist[email] = struct{}{}\n\tc.mu.Unlock()\n}", "func (e *EscrowAccount) AddStakeClaim(tm map[ThresholdKind]quantity.Quantity, claim StakeClaim, thresholds []ThresholdKind) error {\n\t// Compute total amount of claims excluding the claim that we are just adding. This is needed\n\t// in case the claim is being updated to avoid counting it twice.\n\ttotalClaims, err := e.StakeAccumulator.TotalClaims(tm, &claim)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, kind := range thresholds {\n\t\tq := tm[kind]\n\t\tif err := totalClaims.Add(&q); err != nil {\n\t\t\treturn fmt.Errorf(\"staking: failed to accumulate threshold: %w\", err)\n\t\t}\n\t}\n\n\t// Make sure there is sufficient stake to satisfy the claim.\n\tif e.Active.Balance.Cmp(totalClaims) < 0 {\n\t\treturn ErrInsufficientStake\n\t}\n\n\te.StakeAccumulator.AddClaimUnchecked(claim, thresholds)\n\treturn nil\n}", "func (repo *Repository) Create(ctx context.Context, claims auth.Claims, req UserAccountCreateRequest, now time.Time) (*UserAccount, error) {\n\tspan, ctx := tracer.StartSpanFromContext(ctx, \"internal.user_account.Create\")\n\tdefer span.Finish()\n\n\t// Validate the request.\n\tv := webcontext.Validator()\n\terr := v.Struct(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Ensure the claims can modify the account specified in the request.\n\terr = repo.CanModifyAccount(ctx, claims, req.AccountID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If now empty set it to the current time.\n\tif now.IsZero() {\n\t\tnow = time.Now()\n\t}\n\n\t// Always store the time as UTC.\n\tnow = now.UTC()\n\n\t// Postgres truncates times to milliseconds when storing. We and do the same\n\t// here so the value we return is consistent with what we store.\n\tnow = now.Truncate(time.Millisecond)\n\n\t// Check to see if there is an existing user account, including archived.\n\texistQuery := selectQuery()\n\texistQuery.Where(existQuery.And(\n\t\texistQuery.Equal(\"account_id\", req.AccountID),\n\t\texistQuery.Equal(\"user_id\", req.UserID),\n\t))\n\texisting, err := find(ctx, claims, repo.DbConn, existQuery, []interface{}{}, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If there is an existing entry, then update instead of insert.\n\tvar ua UserAccount\n\tif len(existing) > 0 {\n\t\tupReq := UserAccountUpdateRequest{\n\t\t\tUserID: req.UserID,\n\t\t\tAccountID: req.AccountID,\n\t\t\tRoles: &req.Roles,\n\t\t\tunArchive: true,\n\t\t}\n\t\terr = repo.Update(ctx, claims, upReq, now)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tua = *existing[0]\n\t\tua.Roles = req.Roles\n\t\tua.UpdatedAt = now\n\t\tua.ArchivedAt = nil\n\t} else {\n\t\tuaID := uuid.NewRandom().String()\n\n\t\tua = UserAccount{\n\t\t\t//ID: uaID,\n\t\t\tUserID: req.UserID,\n\t\t\tAccountID: req.AccountID,\n\t\t\tRoles: req.Roles,\n\t\t\tStatus: UserAccountStatus_Active,\n\t\t\tCreatedAt: now,\n\t\t\tUpdatedAt: now,\n\t\t}\n\n\t\tif req.Status != nil {\n\t\t\tua.Status = *req.Status\n\t\t}\n\n\t\t// Build the insert SQL statement.\n\t\tquery := sqlbuilder.NewInsertBuilder()\n\t\tquery.InsertInto(userAccountTableName)\n\t\tquery.Cols(\"id\", \"user_id\", \"account_id\", \"roles\", \"status\", \"created_at\", \"updated_at\")\n\t\tquery.Values(uaID, ua.UserID, ua.AccountID, ua.Roles, ua.Status.String(), ua.CreatedAt, ua.UpdatedAt)\n\n\t\t// Execute the query with the provided context.\n\t\tsql, args := query.Build()\n\t\tsql = repo.DbConn.Rebind(sql)\n\t\t_, err = repo.DbConn.ExecContext(ctx, sql, args...)\n\t\tif err != nil {\n\t\t\terr = errors.Wrapf(err, \"query - %s\", query.String())\n\t\t\terr = errors.WithMessagef(err, \"add account %s to user %s failed\", req.AccountID, req.UserID)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &ua, nil\n}", "func (_Userable *UserableTransactor) AddAuditor(opts *bind.TransactOpts, _newAuditor common.Address) (*types.Transaction, error) {\n\treturn _Userable.contract.Transact(opts, \"addAuditor\", _newAuditor)\n}", "func (s *Service) Create(newAccountDefinition *model.NewAccountDefinition) *CreateOp {\n\treturn &CreateOp{\n\t\tCredential: s.credential,\n\t\tMethod: \"POST\",\n\t\tPath: \"/v2/accounts\",\n\t\tPayload: newAccountDefinition,\n\t\tQueryOpts: make(url.Values),\n\t\tVersion: esign.APIv2,\n\t}\n}", "func (ge *CurrentGrantExecutable) Grant(p string) string {\n\tvar template string\n\tif p == `OWNERSHIP` {\n\t\ttemplate = `GRANT %v ON %v %v TO %v \"%v\" COPY CURRENT GRANTS`\n\t} else {\n\t\ttemplate = `GRANT %v ON %v %v TO %v \"%v\"`\n\t}\n\treturn fmt.Sprintf(template,\n\t\tp, ge.grantType, ge.grantName, ge.granteeType, ge.granteeName)\n}", "func (a *StoragePowerActorCode_I) AddBalance(rt Runtime, minerAddr addr.Address) {\n\tRT_MinerEntry_ValidateCaller_DetermineFundsLocation(rt, minerAddr, vmr.MinerEntrySpec_MinerOnly)\n\n\tmsgValue := rt.ValueReceived()\n\n\th, st := a.State(rt)\n\tnewTable, ok := autil.BalanceTable_WithAdd(st.EscrowTable(), minerAddr, msgValue)\n\tif !ok {\n\t\trt.AbortStateMsg(\"Escrow operation failed\")\n\t}\n\tst.Impl().EscrowTable_ = newTable\n\tUpdateRelease(rt, h, st)\n}", "func (a *Account) CreateAcct(password string) (*Account, *http.Response, []error) {\n\tk := kumoru.New()\n\n\tk.Put(fmt.Sprintf(\"%s/v1/accounts/%s\", k.EndPoint.Authorization, a.Email))\n\tk.Send(fmt.Sprintf(\"given_name=%s&surname=%s&password=%s\", a.GivenName, a.Surname, password))\n\n\tresp, body, errs := k.End()\n\n\tif len(errs) > 0 {\n\t\treturn a, resp, errs\n\t}\n\n\tif resp.StatusCode >= 400 {\n\t\terrs = append(errs, fmt.Errorf(\"%s\", resp.Status))\n\t}\n\n\terr := json.Unmarshal([]byte(body), &a)\n\n\tif err != nil {\n\t\terrs = append(errs, err)\n\t\treturn a, resp, errs\n\t}\n\n\treturn a, resp, nil\n}", "func (s *Service) AccountCreate(c *gin.Context, roleID model.AccessRole) error {\n\treturn s.IsLowerRole(c, roleID)\n}", "func (manager *OpenIdManager) RegisterAccount(providerId string, oauth2Token *oauth2.Token, oidToken *oidc.IDToken) (*models.UserAccount, error) {\n\tclient, err := manager.GetOIdClient(providerId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpayload, err := client.FetchProfilePayload(oauth2Token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taccount, err := models.RegisterUser(payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = models.RegisterOIdAccount(providerId, oidToken.Subject, account.Id)\n\tif err != nil {\n\t\t_ = account.Delete()\n\t\treturn nil, err\n\t}\n\n\treturn account, nil\n}", "func AccountGrant() GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tgrantType: accountType,\n\t}\n}", "func (a SubAccountClient) PostSubAccountTransfer(req *rest3.RequestForSubAccountTransfer) (rest3.ResponseForSubAccountTransfer, error) {\n\tpanic(\"implement me\")\n}", "func (r *CompanyAccountsCollectionRequest) Add(ctx context.Context, reqObj *Account) (resObj *Account, err error) {\n\terr = r.JSONRequest(ctx, \"POST\", \"\", reqObj, &resObj)\n\treturn\n}", "func CreateAccount(ee engine.Exchange) sknet.HandlerFunc {\n\treturn func(c *sknet.Context) error {\n\t\terrRlt := &pp.EmptyRes{}\n\t\tfor {\n\t\t\treq := pp.CreateAccountReq{}\n\t\t\tif err := c.BindJSON(&req); err != nil {\n\t\t\t\tlogger.Error(err.Error())\n\t\t\t\terrRlt = pp.MakeErrResWithCode(pp.ErrCode_WrongRequest)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// validate pubkey.\n\t\t\tif err := validatePubkey(req.GetPubkey()); err != nil {\n\t\t\t\tlogger.Error(err.Error())\n\t\t\t\terrRlt = pp.MakeErrResWithCode(pp.ErrCode_WrongPubkey)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// create account with pubkey.\n\t\t\tif _, err := ee.CreateAccountWithPubkey(req.GetPubkey()); err != nil {\n\t\t\t\tlogger.Error(err.Error())\n\t\t\t\terrRlt = pp.MakeErrResWithCode(pp.ErrCode_WrongRequest)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tres := pp.CreateAccountRes{\n\t\t\t\tResult: pp.MakeResultWithCode(pp.ErrCode_Success),\n\t\t\t\tPubkey: req.Pubkey,\n\t\t\t\tCreatedAt: pp.PtrInt64(time.Now().Unix()),\n\t\t\t}\n\n\t\t\treturn c.SendJSON(&res)\n\t\t}\n\n\t\treturn c.Error(errRlt)\n\t}\n}", "func (s *Subscription) AttachAccount(a Account) (e error) {\n\tif s.UUID != \"\" {\n\t\treturn RecurlyError{statusCode: 400, Description: \"Subscription Already in Use and can't attach another account to it\"}\n\t}\n\ts.EmbedAccount = new(Account)\n\ta.CreatedAt = nil\n\ta.State = \"\"\n\t//some more may need to be blanked out\n\ta.HostedLoginToken = \"\"\n\ts.EmbedAccount = &a\n\treturn\n}", "func (me *AccountController) RegisterAccount(r *http.Request) (*account.Account, error) {\n\tvar registrant account.Registrant\n\terr := me.decoder.DecodeBodyAndValidate(r, &registrant)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tregisteredAccount, err := me.accountService.RegisterAccount(r.Context(), &registrant)\n\treturn registeredAccount, err\n}", "func (bal *bucketAccessListener) Add(ctx context.Context, obj *v1alpha1.BucketAccess) error {\n\tklog.V(1).Infof(\"bucketAccessListener: add called for bucket access %s\", obj.Name)\n\n\t// Verify this bucket access is for this provisioner\n\tif !strings.EqualFold(obj.Spec.Provisioner, bal.provisionerName) {\n\t\treturn nil\n\t}\n\n\tbucketInstanceName := obj.Spec.BucketInstanceName\n\tbucket, err := bal.bucketAccessClient.ObjectstorageV1alpha1().Buckets().Get(ctx, bucketInstanceName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to get bucket instance %s: %+v\", bucketInstanceName, err)\n\t}\n\n\treq := osspec.ProvisionerGrantBucketAccessRequest{\n\t\tPrincipal: obj.Spec.Principal,\n\t\tAccessPolicy: obj.Spec.PolicyActionsConfigMapData,\n\t\tBucketContext: map[string]string{},\n\t}\n\n\tswitch bucket.Spec.Protocol.Name {\n\tcase v1alpha1.ProtocolNameS3:\n\t\treq.BucketName = bucket.Spec.Protocol.S3.BucketName\n\t\treq.Region = bucket.Spec.Protocol.S3.Region\n\t\treq.BucketContext[\"Version\"] = bucket.Spec.Protocol.S3.Version\n\t\treq.BucketContext[\"SignatureVersion\"] = string(bucket.Spec.Protocol.S3.SignatureVersion)\n\t\treq.BucketContext[\"Endpoint\"] = bucket.Spec.Protocol.S3.Endpoint\n\tcase v1alpha1.ProtocolNameAzure:\n\t\treq.BucketName = bucket.Spec.Protocol.AzureBlob.ContainerName\n\t\treq.BucketContext[\"StorageAccount\"] = bucket.Spec.Protocol.AzureBlob.StorageAccount\n\tcase v1alpha1.ProtocolNameGCS:\n\t\treq.BucketName = bucket.Spec.Protocol.GCS.BucketName\n\t\treq.BucketContext[\"ServiceAccount\"] = bucket.Spec.Protocol.GCS.ServiceAccount\n\t\treq.BucketContext[\"PrivateKeyName\"] = bucket.Spec.Protocol.GCS.PrivateKeyName\n\t\treq.BucketContext[\"ProjectID\"] = bucket.Spec.Protocol.GCS.ProjectID\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown protocol: %s\", bucket.Spec.Protocol.Name)\n\t}\n\n\t// TODO set grpc timeout\n\trsp, err := bal.provisionerClient.ProvisionerGrantBucketAccess(ctx, &req)\n\tif err != nil {\n\t\tklog.Errorf(\"error calling ProvisionerGrantBucketAccess: %v\", err)\n\t\treturn err\n\t}\n\tklog.V(1).Infof(\"provisioner returned grant bucket access response %v\", rsp)\n\n\t// Only update the principal in the BucketAccess if it wasn't set because\n\t// that means that the provisioner created one\n\tif len(obj.Spec.Principal) == 0 {\n\t\terr = bal.updatePrincipal(ctx, obj.Name, *rsp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Only create the secret with credentials if serviveAccount isn't set.\n\t// If serviceAccount is set then authorization happens out of band in the\n\t// cloud provider\n\tif len(obj.Spec.ServiceAccount) == 0 {\n\t\tsecret := v1.Secret{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: generateSecretName(obj.UID),\n\t\t\t},\n\t\t\tStringData: map[string]string{\n\t\t\t\t\"CredentialsFilePath\": rsp.CredentialsFilePath,\n\t\t\t\t\"CredentialsFileContents\": rsp.CredentialsFileContents,\n\t\t\t},\n\t\t\tType: v1.SecretTypeOpaque,\n\t\t}\n\t\t// It's unlikely but should probably handle retries on rare case of collision\n\t\t_, err = bal.kubeClient.CoreV1().Secrets(\"objectstorage-system\").Create(ctx, &secret, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// update bucket access status to granted\n\treturn bal.updateStatus(ctx, obj.Name, \"Permissions Granted\", true)\n}", "func (_TokenVesting *TokenVestingTransactor) AddToken(opts *bind.TransactOpts, _token common.Address, _vestingBeneficiary common.Address, _vestingPeriodInWeeks *big.Int) (*types.Transaction, error) {\n\treturn _TokenVesting.contract.Transact(opts, \"addToken\", _token, _vestingBeneficiary, _vestingPeriodInWeeks)\n}", "func (client *Client) GrantInstanceToVbr(request *GrantInstanceToVbrRequest) (response *GrantInstanceToVbrResponse, err error) {\n\tresponse = CreateGrantInstanceToVbrResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (s *StateDB) CreateAccount(addr types.AddressHash) {\n\tnew, prev := s.createObject(addr)\n\tif prev != nil {\n\t\tnew.setBalance(prev.data.Balance)\n\t}\n}", "func AddAccount(name string) (ethcmn.Address, error) {\n\tdir := getDir(accountDir)\n\tdb, err := leveldb.OpenFile(dir, nil)\n\tif err != nil {\n\t\treturn ethcmn.Address{}, err\n\t}\n\tdefer db.Close()\n\n\tkey := []byte(name)\n\tif _, err = db.Get(key, nil); err == nil {\n\t\treturn ethcmn.Address{}, errors.New(\"you are trying to override an existing private key name. Please delete it first\")\n\t}\n\n\tbuf := cosmoscli.BufferStdin()\n\tpassword, err := cosmoscli.GetCheckPassword(NewPassphrasePrompt, NewPassphrasePromptRepeat, buf)\n\tif err != nil {\n\t\treturn ethcmn.Address{}, err\n\t}\n\n\tacc, err := ks.NewAccount(password)\n\tif err != nil {\n\t\treturn ethcmn.Address{}, err\n\t}\n\n\tif err = db.Put(key, acc.Address.Bytes(), nil); err != nil {\n\t\treturn ethcmn.Address{}, err\n\t}\n\n\treturn acc.Address, nil\n}", "func (ec *executionContext) field_Mutation_createAccount_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\tvar err error\n\targs := map[string]interface{}{}\n\tvar arg0 model.NewAccount\n\tif tmp, ok := rawArgs[\"input\"]; ok {\n\t\tctx := graphql.WithPathContext(ctx, graphql.NewPathWithField(\"input\"))\n\t\targ0, err = ec.unmarshalNNewAccount2githubᚗcomᚋannoyingᚑorangeᚋecpᚑapiᚋgraphᚋmodelᚐNewAccount(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"input\"] = arg0\n\treturn args, nil\n}", "func (kb *Keybase) CreateAccount(name, mnemonic, bip39Passwd, encryptPasswd, hdPath string, algo keys.SigningAlgo) (keys.Info, error) {\n\tkb.mx.Lock()\n\tdefer kb.mx.Unlock()\n\treturn kb.kb.CreateAccount(name, mnemonic, bip39Passwd, encryptPasswd, hdPath, algo)\n}", "func (s *Scim) SaveAccount(oldAcct, newAcct *cpb.Account, desc, subject, realm string, r *http.Request, tx storage.Tx) error {\n\tnewAcct.Revision++\n\tnewAcct.Properties.Modified = float64(time.Now().UnixNano()) / 1e9\n\tif newAcct.Properties.Created == 0 {\n\t\tif oldAcct != nil && oldAcct.Properties.Created != 0 {\n\t\t\tnewAcct.Properties.Created = oldAcct.Properties.Created\n\t\t} else {\n\t\t\tnewAcct.Properties.Created = newAcct.Properties.Modified\n\t\t}\n\t}\n\n\tif err := s.store.WriteTx(storage.AccountDatatype, realm, storage.DefaultUser, newAcct.Properties.Subject, newAcct.Revision, newAcct, storage.MakeConfigHistory(desc, storage.AccountDatatype, newAcct.Revision, newAcct.Properties.Modified, r, subject, oldAcct, newAcct), tx); err != nil {\n\t\treturn fmt.Errorf(\"service storage unavailable: %v, retry later\", err)\n\t}\n\treturn nil\n}", "func (r Runner) AddGenesisAccount(ctx context.Context, address, coins string) error {\n\treturn r.run(ctx, runOptions{}, r.cc.AddGenesisAccountCommand(address, coins))\n}", "func (c *TransferRouter) postAccountTransaction(userID id.User, origDep *model.Depository, recDep *model.Depository, amount model.Amount, transferType model.TransferType, requestID string) (*accounts.Transaction, error) {\n\tif c.accountsClient == nil {\n\t\treturn nil, errors.New(\"accounts enabled but nil client\")\n\t}\n\n\t// Let's lookup both accounts. Either account can be \"external\" (meaning of a RoutingNumber Accounts doesn't control).\n\t// When the routing numbers don't match we can't do much verify the remote account as we likely don't have Account-level access.\n\t//\n\t// TODO(adam): What about an FI that handles multiple routing numbers? Should Accounts expose which routing numbers it currently supports?\n\treceiverAccount, err := c.accountsClient.SearchAccounts(requestID, userID, recDep)\n\tif err != nil || receiverAccount == nil {\n\t\treturn nil, fmt.Errorf(\"error reading account user=%s receiver depository=%s: %v\", userID, recDep.ID, err)\n\t}\n\torigAccount, err := c.accountsClient.SearchAccounts(requestID, userID, origDep)\n\tif err != nil || origAccount == nil {\n\t\treturn nil, fmt.Errorf(\"error reading account user=%s originator depository=%s: %v\", userID, origDep.ID, err)\n\t}\n\t// Submit the transactions to Accounts (only after can we go ahead and save off the Transfer)\n\ttransaction, err := c.accountsClient.PostTransaction(requestID, userID, createTransactionLines(origAccount, receiverAccount, amount, transferType))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating transaction for transfer user=%s: %v\", userID, err)\n\t}\n\tc.logger.Log(\"transfers\", fmt.Sprintf(\"created transaction=%s for user=%s amount=%s\", transaction.ID, userID, amount.String()))\n\treturn transaction, nil\n}", "func (tt *BlockTestTable) AddAccountBlock(priv *rsa.PrivateKey, b *tradeblocks.AccountBlock) *tradeblocks.AccountBlock {\n\tsignBlock(tt.t, priv, b)\n\ttt.AccountBlocks = append(tt.AccountBlocks, b)\n\treturn b\n}", "func CreateAccount(w http.ResponseWriter, r *http.Request) {\n\n\tbodyR, erro := ioutil.ReadAll(r.Body)\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusUnprocessableEntity, erro)\n\t\treturn\n\t}\n\tvar account model.Account\n\tif erro = json.Unmarshal(bodyR, &account); erro != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, erro)\n\t\treturn\n\t}\n\tfmt.Println(account)\n\tif erro = account.Prepare(\"cadastro\"); erro != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, erro)\n\t\treturn\n\t}\n\n\tdb, erro := database.Connect()\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\tdefer db.Close()\n\n\trepository := repositories.NewAccountRepository(db)\n\t_, erro = repository.FindByCPF(account.Cpf)\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusConflict, erro)\n\t}\n\n\taccount.ID, erro = repository.Save(account)\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\n\tresponses.JSON(w, http.StatusCreated, account)\n}", "func (sd *StateDB) CreateAccount(addr types.Address) {\n\tnewstate := NewStateObject(addr, sd)\n\toldstate := sd.getStateObject(addr)\n\tif oldstate != nil {\n\t\tsd.journal.append(&resetObjectChange{\n\t\t\tprev: oldstate,\n\t\t})\n\t} else {\n\t\tsd.journal.append(&createObjectChange{\n\t\t\taccount: &addr,\n\t\t})\n\t}\n\tsd.states[addr] = newstate\n\tsd.beats[addr] = time.Now()\n\n}", "func AddAccount(username string, email string, password string, phone string, showname string, birthday string) error {\r\n\tsqlprepare, err := ConnectDB().Prepare(\"INSERT INTO account(username,email,`password`,`phone`,showname,birthday) VALUES(?,?,?,?,?,?)\")\r\n\tdefer ConnectDB().Close()\r\n\tif err != nil {\r\n\t\tpanic(err.Error())\r\n\t}\r\n\t_, err = sqlprepare.Exec(username, email, password, phone, showname, birthday)\r\n\treturn err\r\n}", "func (_ElvToken *ElvTokenTransactor) AddPauser(opts *bind.TransactOpts, account common.Address) (*types.Transaction, error) {\n\treturn _ElvToken.contract.Transact(opts, \"addPauser\", account)\n}", "func (_SimpleSavingsWallet *SimpleSavingsWalletTransactor) ClaimHeirOwnership(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SimpleSavingsWallet.contract.Transact(opts, \"claimHeirOwnership\")\n}", "func (_TTFT20 *TTFT20TransactorSession) RegisterWithdrawalAddress(addr common.Address) (*types.Transaction, error) {\n\treturn _TTFT20.Contract.RegisterWithdrawalAddress(&_TTFT20.TransactOpts, addr)\n}", "func (smartContract) invoke_AddClaim(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\r\n\tmessage := fmt.Sprintf(\"invokeAddClaim called with args: %s\\n\", args)\r\n\tlog.Debugf(message)\r\n\r\n\t// Check arguments\r\n\tif len(args) < 3 {\r\n\t\tlog.Errorf(message)\r\n\t\treturn nil, errors.New(message)\r\n\t}\r\n\tfrom, err := strconv.Atoi(args[0])\r\n\tif err != nil {\r\n\t\tlog.Errorf(\"strconv.Atoi(args[0]) error: %s\", err.Error())\r\n\t\treturn nil, err\r\n\t}\r\n\tto, err := strconv.Atoi(args[1])\r\n\tif err != nil {\r\n\t\tlog.Errorf(\"strconv.Atoi(args[1]) error: %s\", err.Error())\r\n\t\treturn nil, err\r\n\t}\r\n\tvalue, err := strconv.ParseFloat(args[2], 64)\r\n\tif err != nil {\r\n\t\tlog.Errorf(\"strconv.ParseFloat(args[2], 64) error: %s\", err.Error())\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\t// We are not interested in \"negative claims\"\r\n\tif value < 0.0 {\r\n\t\treturn nil, nil\r\n\t}\r\n\r\n\t// Load existing data\r\n\tnettingTable, err := load(stub)\r\n\tcheckCriticalError(err)\r\n\r\n\tnettingTable.AddClaim(from, to, value)\r\n\r\n\t// Save new data\r\n\terr = save(nettingTable, stub)\r\n\tcheckCriticalError(err)\r\n\r\n\treturn nil, nil\r\n}", "func (service AccountsService) Create(a Account) (*Response, Account, error) {\n\treq, err := service.client.newRequest(\"POST\", \"accounts\", nil, a)\n\tif err != nil {\n\t\treturn nil, Account{}, err\n\t}\n\n\tvar dest Account\n\tres, err := service.client.do(req, &dest)\n\n\tdest.BillingInfo = nil\n\n\treturn res, dest, err\n}", "func (_ChpRegistry *ChpRegistryTransactorSession) AddPauser(account common.Address) (*types.Transaction, error) {\n\treturn _ChpRegistry.Contract.AddPauser(&_ChpRegistry.TransactOpts, account)\n}", "func (n *noopRules) Grant(rule *Rule) error {\n\treturn nil\n}", "func Claim(cfg *setting.Setting, param *ClaimParam, debug bool) error {\n\tmutex.Lock()\n\tdest, err := wallet.NewAddress(&cfg.DBConfig, pwd, true)\n\tif err != nil {\n\t\tmutex.Unlock()\n\t\treturn err\n\t}\n\tmutex.Unlock()\n\tadrstr := strings.ToUpper(hex.EncodeToString(dest.Address(cfg.Config)))\n\tenc := make([]rune, len(adrstr)+1)\n\tfor i, c := range adrstr {\n\t\tif c >= '0' && c <= '8' {\n\t\t\tc = c - '0' + 'G'\n\t\t}\n\t\tenc[i] = c\n\t}\n\tenc[len(adrstr)] = 'Z'\n\tapis := getOldAPIs(oldServers)\n\ttr := gadk.Transfer{\n\t\tAddress: pobAddress,\n\t\tValue: param.Amount,\n\t\tMessage: gadk.Trytes(enc),\n\t}\n\t_, f := gadk.GetBestPoW()\n\tif debug {\n\t\tf = nil\n\t}\n\tfor _, api := range apis {\n\t\t_, err = gadk.Send(api, param.Seed, 2, []gadk.Transfer{tr}, f)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn err\n}", "func (db *boltDB) createAccount(pa providerAccount) error {\n\treturn db.Update(func(tx *bolt.Tx) error {\n\t\tbucket, err := tx.CreateBucketIfNotExists(pa.key())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"create bucket %s: %v\", pa.key(), err)\n\t\t}\n\t\tfor _, b := range bucketNames {\n\t\t\t_, err := bucket.CreateBucketIfNotExists([]byte(b))\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"create account bucket %s: %v\", b, err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func NewBaseVestingAccount(baseAccount *authtypes.BaseAccount, originalVesting sdk.Coins, endTime int64) *BaseVestingAccount {\n\treturn &BaseVestingAccount{\n\t\tBaseAccount: baseAccount,\n\t\tOriginalVesting: originalVesting,\n\t\tDelegatedFree: sdk.NewCoins(),\n\t\tDelegatedVesting: sdk.NewCoins(),\n\t\tEndTime: endTime,\n\t}\n}", "func (r *RBAC) AddToBlackList(system, uid string, permissions ...string) error {\n\tr.Cache.RemoveUser(system, uid)\n\treturn r.User.AddToBlackList(system, uid, permissions...)\n}", "func (c *Client) AddAccount(ctx context.Context, id string) error {\n\tif id == \"\" {\n\t\treturn &ErrorMissingID{}\n\t}\n\n\tinput := &dynamodb.PutItemInput{\n\t\tItem: map[string]*dynamodb.AttributeValue{\n\t\t\taccountIDKey: {\n\t\t\t\tS: aws.String(id),\n\t\t\t},\n\t\t},\n\t\tTableName: aws.String(tableName),\n\t}\n\n\t_, err := c.dynamoDBClient.PutItem(input)\n\tif err != nil {\n\t\treturn &ErrorPutItem{err: err}\n\t}\n\n\treturn nil\n}" ]
[ "0.70387936", "0.6084376", "0.58506024", "0.5656218", "0.5626727", "0.5414569", "0.5300817", "0.51898015", "0.511495", "0.50976485", "0.5083623", "0.5055534", "0.49965897", "0.48901007", "0.48723358", "0.48572427", "0.48206356", "0.4800977", "0.4778801", "0.47696823", "0.47692096", "0.47624657", "0.47552904", "0.4735677", "0.4697048", "0.4689067", "0.46874264", "0.46766818", "0.46751824", "0.46681306", "0.4662258", "0.46585393", "0.46585217", "0.46509168", "0.46393386", "0.4626084", "0.46128264", "0.45912176", "0.4524454", "0.45233998", "0.4514737", "0.45099247", "0.4499597", "0.449856", "0.44962323", "0.44956273", "0.44858536", "0.44815806", "0.44797269", "0.44795346", "0.44583756", "0.44481325", "0.4445018", "0.44355434", "0.44228953", "0.44228613", "0.44120368", "0.4410376", "0.4409666", "0.44011837", "0.4390004", "0.43855053", "0.43809003", "0.43780956", "0.43677598", "0.43529293", "0.43515024", "0.43426096", "0.43418363", "0.43366686", "0.4328826", "0.4328809", "0.43241587", "0.4320327", "0.43151334", "0.43144467", "0.43131888", "0.43097508", "0.4307694", "0.43003067", "0.43000188", "0.42974287", "0.42959964", "0.42932743", "0.42913035", "0.42820525", "0.4278522", "0.42763773", "0.42620042", "0.4259967", "0.4259799", "0.42589027", "0.4258176", "0.42568356", "0.42560223", "0.4255191", "0.42520204", "0.42490008", "0.42459285", "0.42436308" ]
0.7568594
0
addGrant merges a new clawback vesting grant into an existing ClawbackVestingAccount.
func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) { // how much is really delegated? bondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress()) unbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress()) delegatedAmt := bondedAmt.Add(unbondingAmt) delegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt)) // discover what has been slashed oldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...) slashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated)) // rebase the DV + DF by capping slashed at the current unvested amount unvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime())) newSlashed := coinsMin(slashed, unvested) newDelegated := delegated.Add(newSlashed...) // modify schedules for the new grant newLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods) newVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.GetVestingPeriods(), grantVestingPeriods) if newLockupStart != newVestingStart { panic("bad start time calculation") } va.StartTime = newLockupStart va.EndTime = max64(newLockupEnd, newVestingEnd) va.LockupPeriods = newLockupPeriods va.VestingPeriods = newVestingPeriods va.OriginalVesting = va.OriginalVesting.Add(grantCoins...) // cap DV at the current unvested amount, DF rounds out to newDelegated unvested2 := va.GetVestingCoins(ctx.BlockTime()) va.DelegatedVesting = coinsMin(newDelegated, unvested2) va.DelegatedFree = newDelegated.Sub(va.DelegatedVesting) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pva *PeriodicVestingAccount) AddGrant(ctx sdk.Context, action exported.AddGrantAction) error {\n\treturn action.AddToAccount(ctx, pva)\n}", "func (pva *PeriodicVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, pva.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, pva.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := pva.DelegatedVesting.Add(pva.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV+DF by capping slashed at the current unvested amount\n\tunvested := pva.GetVestingCoins(ctx.BlockTime())\n\tnewSlashed := coinsMin(unvested, slashed)\n\tnewTotalDelegated := delegated.Add(newSlashed...)\n\n\t// modify vesting schedule for the new grant\n\tnewStart, newEnd, newPeriods := DisjunctPeriods(pva.StartTime, grantStartTime,\n\t\tpva.GetVestingPeriods(), grantVestingPeriods)\n\tpva.StartTime = newStart\n\tpva.EndTime = newEnd\n\tpva.VestingPeriods = newPeriods\n\tpva.OriginalVesting = pva.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newTotalDelegated\n\tunvested2 := pva.GetVestingCoins(ctx.BlockTime())\n\tpva.DelegatedVesting = coinsMin(newTotalDelegated, unvested2)\n\tpva.DelegatedFree = newTotalDelegated.Sub(pva.DelegatedVesting)\n}", "func StageGrant(db, schema, stage string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: stage,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\".\"%v\".\"%v\"`, db, schema, stage),\n\t\tgrantType: stageType,\n\t}\n}", "func (ag *AccessGrant) MergeAdd(other AccessGrant) error {\n\tif err := other.Validate(); err != nil {\n\t\treturn err\n\t}\n\tif other.Address != ag.Address {\n\t\treturn fmt.Errorf(\"cannot merge in AccessGrant for different address\")\n\t}\n\tfor _, p := range other.GetAccessList() {\n\t\tif !ag.HasAccess(p) {\n\t\t\tag.Permissions = append(ag.Permissions, p)\n\t\t}\n\t}\n\treturn nil\n}", "func (cga clawbackGrantAction) AddToAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported,\n\t\t\t\"account %s must be a ClawbackVestingAccount, got %T\",\n\t\t\trawAccount.GetAddress(), rawAccount)\n\t}\n\tif cga.funderAddress != cva.FunderAddress {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"account %s can only accept grants from account %s\",\n\t\t\trawAccount.GetAddress(), cva.FunderAddress)\n\t}\n\tcva.addGrant(ctx, cga.sk, cga.grantStartTime, cga.grantLockupPeriods, cga.grantVestingPeriods, cga.grantCoins)\n\treturn nil\n}", "func (u *user) grant(ctx context.Context, db Database, access string) error {\n\tescapedDbName := pathEscape(db.Name())\n\treq, err := u.conn.NewRequest(\"PUT\", path.Join(u.relPath(), \"database\", escapedDbName))\n\tif err != nil {\n\t\treturn WithStack(err)\n\t}\n\tinput := struct {\n\t\tGrant string `arangodb:\"grant\" json:\"grant\"`\n\t}{\n\t\tGrant: access,\n\t}\n\tif _, err := req.SetBody(input); err != nil {\n\t\treturn WithStack(err)\n\t}\n\tresp, err := u.conn.Do(ctx, req)\n\tif err != nil {\n\t\treturn WithStack(err)\n\t}\n\tif err := resp.CheckStatus(200); err != nil {\n\t\treturn WithStack(err)\n\t}\n\treturn nil\n}", "func (s *Session) GrantDB(database, user, grant string) error {\n\tok, err := s.client.UserExists(context.Background(), user)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in finding user %s\", err)\n\t}\n\tif !ok {\n\t\treturn fmt.Errorf(\"user %s does not exist\", user)\n\t}\n\tdbuser, err := s.client.User(context.Background(), user)\n\tif err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"error in getting user %s from database %s\",\n\t\t\tuser,\n\t\t\terr,\n\t\t)\n\t}\n\tdbh, err := s.client.Database(context.Background(), database)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot get a database instance %s\", err)\n\t}\n\terr = dbuser.SetDatabaseAccess(context.Background(), dbh, getGrant(grant))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in setting database access %s\", err)\n\t}\n\n\treturn nil\n}", "func (_LvRecording *LvRecordingTransactor) RunGrant(opts *bind.TransactOpts, arg0 *big.Int, arg1 bool) (*types.Transaction, error) {\n\treturn _LvRecording.contract.Transact(opts, \"runGrant\", arg0, arg1)\n}", "func Grant(ctx context.Context, i grantRequest) error {\n\tclient, err := New(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn client.Grant(ctx, i)\n}", "func (k *Kerberos) Grant(encTGT, appID, encAuthenticator string) (*KerberosGrantResult, error) {\n\ttgt := &kerberosTGT{}\n\tif err := k.decrypt(encTGT, k.tgsSecretKey, tgt); err != nil {\n\t\treturn nil, errTGTInvalid\n\t}\n\tif tgt.Expired < time.Now().Unix() {\n\t\treturn nil, errTGTInvalid\n\t}\n\tauthenticator := &kerberosAuthenticator{}\n\tif err := k.decrypt(encAuthenticator, tgt.CTSK, authenticator); err != nil {\n\t\treturn nil, errAuthenticatorInvalid\n\t}\n\n\tvar appSecret string\n\tif appID == \"cell\" {\n\t\tappSecret = k.appSecretKey\n\t} else {\n\t\terr := k.db.QueryRowContext(\n\t\t\tdbCtx(),\n\t\t\t\"SELECT `secret` FROM `app` WHERE `app_id`=? LIMIT 1\",\n\t\t\tappID,\n\t\t).Scan(&appSecret)\n\t\tswitch {\n\t\tcase err == sql.ErrNoRows:\n\t\t\treturn nil, errAppNotExist\n\t\tcase err != nil:\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tst := &kerberosServiceTicket{\n\t\tCSSK: RandToken(),\n\t\tUsername: authenticator.Username,\n\t\tExpired: time.Now().Add(2 * time.Hour).Unix(),\n\t}\n\n\tencCSSK := k.encrypt(st.CSSK, tgt.CTSK)\n\tencST := k.encrypt(st, appSecret)\n\n\tres := &KerberosGrantResult{\n\t\tencCSSK,\n\t\tencST,\n\t}\n\treturn res, nil\n}", "func (ge *CurrentGrantExecutable) Grant(p string) string {\n\tvar template string\n\tif p == `OWNERSHIP` {\n\t\ttemplate = `GRANT %v ON %v %v TO %v \"%v\" COPY CURRENT GRANTS`\n\t} else {\n\t\ttemplate = `GRANT %v ON %v %v TO %v \"%v\"`\n\t}\n\treturn fmt.Sprintf(template,\n\t\tp, ge.grantType, ge.grantName, ge.granteeType, ge.granteeName)\n}", "func AccountGrant() GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tgrantType: accountType,\n\t}\n}", "func (_Content *ContentTransactor) RunGrant(opts *bind.TransactOpts, arg0 *big.Int, arg1 bool) (*types.Transaction, error) {\n\treturn _Content.contract.Transact(opts, \"runGrant\", arg0, arg1)\n}", "func (c *Client) Grant(ctx context.Context, i grantRequest) error {\n\tif i == nil {\n\t\treturn fmt.Errorf(\"missing request\")\n\t}\n\n\tswitch t := i.(type) {\n\tcase *SecretManagerGrantRequest:\n\t\treturn c.secretManagerGrant(ctx, t)\n\tcase *StorageGrantRequest:\n\t\treturn c.storageGrant(ctx, t)\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown grant type %T\", t)\n\t}\n}", "func ViewGrant(db, schema, view string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: view,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\".\"%v\".\"%v\"`, db, schema, view),\n\t\tgrantType: viewType,\n\t}\n}", "func (r *jsiiProxy_RepositoryBase) Grant(grantee awsiam.IGrantable, actions ...*string) awsiam.Grant {\n\targs := []interface{}{grantee}\n\tfor _, a := range actions {\n\t\targs = append(args, a)\n\t}\n\n\tvar returns awsiam.Grant\n\n\t_jsii_.Invoke(\n\t\tr,\n\t\t\"grant\",\n\t\targs,\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (s *BasePlSqlParserListener) EnterGrant_statement(ctx *Grant_statementContext) {}", "func (_LvRecordableStream *LvRecordableStreamTransactor) RunGrant(opts *bind.TransactOpts, arg0 *big.Int, arg1 bool) (*types.Transaction, error) {\n\treturn _LvRecordableStream.contract.Transact(opts, \"runGrant\", arg0, arg1)\n}", "func (n *noopRules) Grant(rule *Rule) error {\n\treturn nil\n}", "func (r *jsiiProxy_Repository) Grant(grantee awsiam.IGrantable, actions ...*string) awsiam.Grant {\n\targs := []interface{}{grantee}\n\tfor _, a := range actions {\n\t\targs = append(args, a)\n\t}\n\n\tvar returns awsiam.Grant\n\n\t_jsii_.Invoke(\n\t\tr,\n\t\t\"grant\",\n\t\targs,\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func WarehouseGrant(w string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: w,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\"`, w),\n\t\tgrantType: warehouseType,\n\t}\n}", "func (r *refreshTokenGranter) Grant(_ context.Context, requestedScopes []string) grants.Grant {\n\treturn grants.Grant{\n\t\tSourceType: \"refresh_token\",\n\t\tSourceID: r.token.ID,\n\t\tScopes: requestedScopes,\n\t\tAccountID: r.token.AccountID,\n\t\tProfileID: r.token.ProfileID,\n\t\tClientID: r.token.ClientID,\n\t\tUsed: false,\n\t}\n}", "func (c *Client) Grant(email string) {\n\tif c.CI {\n\t\temail = strings.ToLower(email)\n\t}\n\tc.mu.Lock()\n\tc.whitelist[email] = struct{}{}\n\tc.mu.Unlock()\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCaller) TokenGrant(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _TokenStakingEscrow.contract.Call(opts, out, \"tokenGrant\")\n\treturn *ret0, err\n}", "func (_LvStreamRightsHolder *LvStreamRightsHolderTransactor) RunGrant(opts *bind.TransactOpts, arg0 *big.Int, arg1 bool) (*types.Transaction, error) {\n\treturn _LvStreamRightsHolder.contract.Transact(opts, \"runGrant\", arg0, arg1)\n}", "func (pga periodicGrantAction) AddToAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tpva, ok := rawAccount.(*PeriodicVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported,\n\t\t\t\"account %s must be a PeriodicVestingAccount, got %T\",\n\t\t\trawAccount.GetAddress(), rawAccount)\n\t}\n\tpva.addGrant(ctx, pga.sk, pga.grantStartTime, pga.grantVestingPeriods, pga.grantCoins)\n\treturn nil\n}", "func (_BaseContent *BaseContentTransactor) AccessGrant(opts *bind.TransactOpts, request_ID *big.Int, access_granted bool, re_key string, encrypted_AES_key string) (*types.Transaction, error) {\n\treturn _BaseContent.contract.Transact(opts, \"accessGrant\", request_ID, access_granted, re_key, encrypted_AES_key)\n}", "func IntegrationGrant(w string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: w,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\"`, w),\n\t\tgrantType: integrationType,\n\t}\n}", "func (_TokenVesting *TokenVestingTransactor) AddToken(opts *bind.TransactOpts, _token common.Address, _vestingBeneficiary common.Address, _vestingPeriodInWeeks *big.Int) (*types.Transaction, error) {\n\treturn _TokenVesting.contract.Transact(opts, \"addToken\", _token, _vestingBeneficiary, _vestingPeriodInWeeks)\n}", "func NewClawbackGrantAction(\n\tfunderAddress string,\n\tsk StakingKeeper,\n\tgrantStartTime int64,\n\tgrantLockupPeriods, grantVestingPeriods []Period,\n\tgrantCoins sdk.Coins,\n) exported.AddGrantAction {\n\treturn clawbackGrantAction{\n\t\tfunderAddress: funderAddress,\n\t\tsk: sk,\n\t\tgrantStartTime: grantStartTime,\n\t\tgrantLockupPeriods: grantLockupPeriods,\n\t\tgrantVestingPeriods: grantVestingPeriods,\n\t\tgrantCoins: grantCoins,\n\t}\n}", "func ResourceMonitorGrant(w string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: w,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\"`, w),\n\t\tgrantType: resourceMonitorType,\n\t}\n}", "func (client GovernanceClient) addGovernance(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/organizations/{organizationId}/tenancies/{organizationTenancyId}/actions/addGovernance\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response AddGovernanceResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\tapiReferenceLink := \"https://docs.oracle.com/iaas/api/#/en/organizations/20230401/OrganizationTenancy/AddGovernance\"\n\t\terr = common.PostProcessServiceError(err, \"Governance\", \"AddGovernance\", apiReferenceLink)\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (e *EscrowAccount) AddStakeClaim(tm map[ThresholdKind]quantity.Quantity, claim StakeClaim, thresholds []ThresholdKind) error {\n\t// Compute total amount of claims excluding the claim that we are just adding. This is needed\n\t// in case the claim is being updated to avoid counting it twice.\n\ttotalClaims, err := e.StakeAccumulator.TotalClaims(tm, &claim)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, kind := range thresholds {\n\t\tq := tm[kind]\n\t\tif err := totalClaims.Add(&q); err != nil {\n\t\t\treturn fmt.Errorf(\"staking: failed to accumulate threshold: %w\", err)\n\t\t}\n\t}\n\n\t// Make sure there is sufficient stake to satisfy the claim.\n\tif e.Active.Balance.Cmp(totalClaims) < 0 {\n\t\treturn ErrInsufficientStake\n\t}\n\n\te.StakeAccumulator.AddClaimUnchecked(claim, thresholds)\n\treturn nil\n}", "func (obj *Facility) AppendTransact(transact *Transaction) bool {\n\tif obj.tb.Len() != 0 {\n\t\t// Facility is busy\n\t\treturn false\n\t}\n\tobj.BaseObj.AppendTransact(transact)\n\ttransact.SetHolder(obj.name)\n\tadvance := obj.GenerateAdvance()\n\tobj.sumAdvance += float64(advance)\n\ttransact.SetTiсks(advance)\n\tif transact.GetParameter(\"Facility\") != nil {\n\t\tobj.bakupFacilityName = transact.GetParameter(\"Facility\").(string)\n\t}\n\ttransact.SetParameter(\"Facility\", obj.name)\n\tobj.HoldedTransactID = transact.GetID()\n\tobj.tb.Push(transact)\n\tobj.cntTransact++\n\treturn true\n}", "func AddTenant(m *Tenant) (id int64, err error) {\n\to := orm.NewOrm()\n\tid, err = o.Insert(m)\n\treturn\n}", "func AccountGrant() *TerraformGrantResource {\n\treturn &TerraformGrantResource{\n\t\tResource: &schema.Resource{\n\t\t\tCreate: CreateAccountGrant,\n\t\t\tRead: ReadAccountGrant,\n\t\t\tDelete: DeleteAccountGrant,\n\t\t\tUpdate: UpdateAccountGrant,\n\n\t\t\tSchema: accountGrantSchema,\n\t\t\tImporter: &schema.ResourceImporter{\n\t\t\t\tStateContext: schema.ImportStatePassthroughContext,\n\t\t\t},\n\t\t},\n\t\tValidPrivs: validAccountPrivileges,\n\t}\n}", "func SchemaGrant(db, schema string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: schema,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\".\"%v\"`, db, schema),\n\t\tgrantType: schemaType,\n\t}\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupTransactor) GrantAccess(opts *bind.TransactOpts, candidate common.Address) (*types.Transaction, error) {\n\treturn _BaseAccessControlGroup.contract.Transact(opts, \"grantAccess\", candidate)\n}", "func Add(mgr manager.Manager) error {\n\tr := newReconciler(mgr)\n\treturn add(mgr, r, r.SecretTriggerCertMerge)\n}", "func (p *ResourceCondition) addTenantToFilter(action string, tenant tenantMatcher) {\n\tp.actionTenantFilter[action] = append(p.actionTenantFilter[action], tenant)\n}", "func (s *BasePlSqlParserListener) EnterGrant_object_name(ctx *Grant_object_nameContext) {}", "func (_WELV9 *WELV9Transactor) Withdraw(opts *bind.TransactOpts, wad *big.Int) (*types.Transaction, error) {\n\treturn _WELV9.contract.Transact(opts, \"withdraw\", wad)\n}", "func NewRedirectGrant(url string) GrantHandler {\n\treturn &redirectGrant{url}\n}", "func (p *jsiiProxy_ProfilingGroup) GrantPublish(grantee awsiam.IGrantable) awsiam.Grant {\n\tvar returns awsiam.Grant\n\n\t_jsii_.Invoke(\n\t\tp,\n\t\t\"grantPublish\",\n\t\t[]interface{}{grantee},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (_BaseLibrary *BaseLibraryTransactor) AddReviewerGroup(opts *bind.TransactOpts, group common.Address) (*types.Transaction, error) {\n\treturn _BaseLibrary.contract.Transact(opts, \"addReviewerGroup\", group)\n}", "func DatabaseGrant(name string) GrantBuilder {\n\treturn &CurrentGrantBuilder{\n\t\tname: name,\n\t\tqualifiedName: fmt.Sprintf(`\"%v\"`, name),\n\t\tgrantType: databaseType,\n\t}\n}", "func (_BREMFactory *BREMFactoryTransactor) AddAuditor(opts *bind.TransactOpts, _newAuditor common.Address) (*types.Transaction, error) {\n\treturn _BREMFactory.contract.Transact(opts, \"addAuditor\", _newAuditor)\n}", "func (_DelegateProfile *DelegateProfileTransactor) Withdraw(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DelegateProfile.contract.Transact(opts, \"withdraw\")\n}", "func NewGrantCheck(check GrantChecker, handler GrantHandler, errorHandler GrantErrorHandler) osinserver.AuthorizeHandler {\n\treturn &GrantCheck{check, handler, errorHandler}\n}", "func AddTenantHook(hookPoint boil.HookPoint, tenantHook TenantHook) {\n\tswitch hookPoint {\n\tcase boil.AfterSelectHook:\n\t\ttenantAfterSelectHooks = append(tenantAfterSelectHooks, tenantHook)\n\tcase boil.BeforeInsertHook:\n\t\ttenantBeforeInsertHooks = append(tenantBeforeInsertHooks, tenantHook)\n\tcase boil.AfterInsertHook:\n\t\ttenantAfterInsertHooks = append(tenantAfterInsertHooks, tenantHook)\n\tcase boil.BeforeUpdateHook:\n\t\ttenantBeforeUpdateHooks = append(tenantBeforeUpdateHooks, tenantHook)\n\tcase boil.AfterUpdateHook:\n\t\ttenantAfterUpdateHooks = append(tenantAfterUpdateHooks, tenantHook)\n\tcase boil.BeforeDeleteHook:\n\t\ttenantBeforeDeleteHooks = append(tenantBeforeDeleteHooks, tenantHook)\n\tcase boil.AfterDeleteHook:\n\t\ttenantAfterDeleteHooks = append(tenantAfterDeleteHooks, tenantHook)\n\tcase boil.BeforeUpsertHook:\n\t\ttenantBeforeUpsertHooks = append(tenantBeforeUpsertHooks, tenantHook)\n\tcase boil.AfterUpsertHook:\n\t\ttenantAfterUpsertHooks = append(tenantAfterUpsertHooks, tenantHook)\n\t}\n}", "func (_TokenStakingEscrow *TokenStakingEscrowTransactor) WithdrawToManagedGrantee(opts *bind.TransactOpts, operator common.Address) (*types.Transaction, error) {\n\treturn _TokenStakingEscrow.contract.Transact(opts, \"withdrawToManagedGrantee\", operator)\n}", "func DatabaseGrant() *TerraformGrantResource {\n\treturn &TerraformGrantResource{\n\t\tResource: &schema.Resource{\n\t\t\tCreate: CreateDatabaseGrant,\n\t\t\tRead: ReadDatabaseGrant,\n\t\t\tDelete: DeleteDatabaseGrant,\n\t\t\tUpdate: UpdateDatabaseGrant,\n\n\t\t\tSchema: databaseGrantSchema,\n\t\t\tImporter: &schema.ResourceImporter{\n\t\t\t\tStateContext: schema.ImportStatePassthroughContext,\n\t\t\t},\n\t\t},\n\t\tValidPrivs: validDatabasePrivileges,\n\t}\n}", "func (_TokenVesting *TokenVestingTransactorSession) AddToken(_token common.Address, _vestingBeneficiary common.Address, _vestingPeriodInWeeks *big.Int) (*types.Transaction, error) {\n\treturn _TokenVesting.Contract.AddToken(&_TokenVesting.TransactOpts, _token, _vestingBeneficiary, _vestingPeriodInWeeks)\n}", "func AddTenant(t Tenant, db *database.DB) (*Tenant, error) {\n\n\tvar temp Tenant\n\n\tsearchres := db.Client.Where(\"name = ?\", t.Name).First(&temp)\n\tif searchres.Error == nil {\n\t\t// setting tenant ID to object found in DB\n\t\t// for error handling\n\t\tfmt.Println(\"found %v\", temp)\n\n\t\treturn &temp, &TenantAlreadyExist{Err: errors.New(\"error creating tenant\"), FoundID: temp.ID.String()}\n\t}\n\n\t// Create new entry\n\tresult := db.Client.Create(&t)\n\tif result.Error != nil {\n\t\t// log.Fatal(result.Error)\n\t\treturn nil, result.Error\n\t}\n\treturn &t, nil\n}", "func (_IWETH *IWETHTransactor) Withdraw(opts *bind.TransactOpts, arg0 *big.Int) (*types.Transaction, error) {\r\n\treturn _IWETH.contract.Transact(opts, \"withdraw\", arg0)\r\n}", "func (_Wmatic *WmaticTransactor) Withdraw(opts *bind.TransactOpts, wad *big.Int) (*types.Transaction, error) {\n\treturn _Wmatic.contract.Transact(opts, \"withdraw\", wad)\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"projectclaim-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource ProjectClaim\n\terr = c.Watch(&source.Kind{Type: &gcpv1alpha1.ProjectClaim{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (_SingleAuto *SingleAutoTransactor) Add(opts *bind.TransactOpts, _allocPoint *big.Int, _want common.Address, _withUpdate bool, _strat common.Address) (*types.Transaction, error) {\n\treturn _SingleAuto.contract.Transact(opts, \"add\", _allocPoint, _want, _withUpdate, _strat)\n}", "func (f *fabric) addClaim(id, x, y, w, h int) {\n\tif f.m == nil { // Harita bos ise olusturuluyor\n\t\tf.m = make(map[xy]int)\n\t}\n\n\tfor i := 0; i < w; i++ {\n\t\tfor j := 0; j < h; j++ {\n\t\t\tf.m[xy{x + i, y + j}]++ // Cizme islemi karenin degeri bir arttiliyor kesisim bulmak icin ideal\n\t\t}\n\t}\n}", "func (c *managementServiceClient) UpdateProjectGrantUserGrant(ctx context.Context, in *ProjectGrantUserGrantUpdate, opts ...grpc.CallOption) (*UserGrant, error) {\n\tout := new(UserGrant)\n\terr := c.cc.Invoke(ctx, \"/caos.zitadel.management.api.v1.ManagementService/UpdateProjectGrantUserGrant\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func (r *AWSAccountBindingApprovalReconciler) addFinalizer(ctx context.Context) (*ctrl.Result, error) {\n\tlgr := r.Log.WithValues(\"task\", \"addFinalizer\")\n\tlgr.Info(\"starting\")\n\tdefer lgr.Info(\"ending\")\n\n\t// call handler\n\tif res, err := r.handleFinalizer(ctx, controllerutil.AddFinalizer); reconc.ShouldHaltOrRequeue(res, err) {\n\t\tif err != nil {\n\t\t\tlgr.Error(err, \"error handling finalizer\")\n\t\t}\n\t\treturn res, err\n\t}\n\n\treturn reconc.ContinueReconciling()\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) Withdraw(opts *bind.TransactOpts, _member common.Address) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"withdraw\", _member)\n}", "func (m *LeaseMutation) AddAgetenant(i int) {\n\tif m.addagetenant != nil {\n\t\t*m.addagetenant += i\n\t} else {\n\t\tm.addagetenant = &i\n\t}\n}", "func (_BaseContent *BaseContentFilterer) WatchAccessGrant(opts *bind.WatchOpts, sink chan<- *BaseContentAccessGrant) (event.Subscription, error) {\n\n\tlogs, sub, err := _BaseContent.contract.WatchLogs(opts, \"AccessGrant\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(BaseContentAccessGrant)\n\t\t\t\tif err := _BaseContent.contract.UnpackLog(event, \"AccessGrant\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}", "func (p *program) addCost(cost types.Currency) error {\n\tif !p.staticBudget.Withdraw(cost) {\n\t\treturn modules.ErrMDMInsufficientBudget\n\t}\n\tp.executionCost = p.executionCost.Add(cost)\n\treturn nil\n}", "func (m *MockFormatter) AccessGrant(e entity.OauthAccessGrant) entity.OauthAccessGrantJSON {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AccessGrant\", e)\n\tret0, _ := ret[0].(entity.OauthAccessGrantJSON)\n\treturn ret0\n}", "func Grant(uid int, ip, mac string) {\n\tif res, e := exec.Command(*iptables,\n\t\t\"-t mangle -I internet 1 -m mac --mac-source\", mac, \"-s\", ip,\n\t\t\"-j RETURN\").Output(); e != nil {\n\n\t\tlog.Printf(\"[EE] %s: %s\", e.Error(), string(res))\n\t\treturn\n\t}\n\n\tvar ttl time.Duration // TODO: calculate and set\n\ttimers[uid] = time.AfterFunc(ttl, func() {\n\t\tblock(uid, ip, mac)\n\t})\n}", "func (c *managementServiceClient) ReactivateProjectGrantUserGrant(ctx context.Context, in *ProjectGrantUserGrantID, opts ...grpc.CallOption) (*UserGrant, error) {\n\tout := new(UserGrant)\n\terr := c.cc.Invoke(ctx, \"/caos.zitadel.management.api.v1.ManagementService/ReactivateProjectGrantUserGrant\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func (this *Handler) AddCred(cred scanners.Credential) error {\n\tthis.creds = append(this.creds, cred)\n\treturn nil\n}", "func (g *autoGrant) GrantNeeded(user user.Info, grant *api.Grant, w http.ResponseWriter, req *http.Request) (bool, bool, error) {\n\treturn true, false, nil\n}", "func (r ResourceGrantsType) Extend(ac AccessControl, subject SubjectType) ResourceGrantsType {\n\tif !subject.IsZero() && ac.Grants[subject] == nil {\n\t\tac.Grants[subject] = make(ResourceGrantsType)\n\t}\n\tac.Grants[subject] = r\n\treturn r\n}", "func (_TokenStakingEscrow *TokenStakingEscrowSession) TokenGrant() (common.Address, error) {\n\treturn _TokenStakingEscrow.Contract.TokenGrant(&_TokenStakingEscrow.CallOpts)\n}", "func (_PermInterface *PermInterfaceTransactor) AddOrg(opts *bind.TransactOpts, _orgId string, _enodeId string, _ip string, _port uint16, _raftport uint16, _account common.Address) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"addOrg\", _orgId, _enodeId, _ip, _port, _raftport, _account)\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(ControllerName, mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource KeycloakClient\n\terr = c.Watch(&source.Kind{Type: &kc.KeycloakClient{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Make sure to watch the credential secrets\n\terr = c.Watch(&source.Kind{Type: &corev1.Secret{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &kc.KeycloakClient{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (p *SharePool) Withdraw(tokenDst, shareSrc, shareAmount *quantity.Quantity) error {\n\ttokens, err := p.tokensForShares(shareAmount)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = shareSrc.Sub(shareAmount); err != nil {\n\t\treturn err\n\t}\n\n\tif err = p.TotalShares.Sub(shareAmount); err != nil {\n\t\treturn err\n\t}\n\n\tif err = quantity.Move(tokenDst, &p.Balance, tokens); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\n \t// minimumRefreshRate = os.Getenv(\"MINIMUM_REFRESH_RATE\")\n\n\t// Create a new controller\n\tc, err := controller.New(\"vaultsecret-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource VaultSecret\n\terr = c.Watch(&source.Kind{Type: &crdv1alpha1.VaultSecret{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO(user): Modify this to be the types you create that are owned by the primary resource\n\t// Watch for changes to secondary resource Secrets and requeue the owner VaultSecret\n\terr = c.Watch(&source.Kind{Type: &corev1.Secret{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &crdv1alpha1.VaultSecret{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (_TokenVesting *TokenVestingSession) AddToken(_token common.Address, _vestingBeneficiary common.Address, _vestingPeriodInWeeks *big.Int) (*types.Transaction, error) {\n\treturn _TokenVesting.Contract.AddToken(&_TokenVesting.TransactOpts, _token, _vestingBeneficiary, _vestingPeriodInWeeks)\n}", "func Seal(secret config.SecretsManager, ref *reference.Ref, spec *Spec) (*Grant, error) {\n\tgrt := &Grant{Spec: spec}\n\n\tif s := spec.GetPlaintext(); s != nil {\n\t\tgrt.EncryptedReference = PlaintextGrant(ref)\n\t} else if s := spec.GetSymmetric(); s != nil {\n\t\tsecret, err := secret.Provider(s.PublicID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tencRef, err := SymmetricGrant(ref, secret)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgrt.EncryptedReference = encRef\n\t} else if s := spec.GetOpenPGP(); s != nil {\n\t\tencRef, err := OpenPGPGrant(ref, s.PublicKey, secret.OpenPGP)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgrt.EncryptedReference = encRef\n\t} else {\n\t\treturn nil, fmt.Errorf(\"grant type %v not recognised\", s)\n\t}\n\n\treturn grt, nil\n}", "func (_Smartchef *SmartchefTransactor) Withdraw(opts *bind.TransactOpts, _amount *big.Int) (*types.Transaction, error) {\n\treturn _Smartchef.contract.Transact(opts, \"withdraw\", _amount)\n}", "func AddGuestTransaction(m *Guests, o orm.Ormer) (id int64, err error) {\n\tid, err = o.Insert(m)\n\treturn\n}", "func (_Lmc *LmcTransactor) Withdraw(opts *bind.TransactOpts, _tokenAmount *big.Int) (*types.Transaction, error) {\n\treturn _Lmc.contract.Transact(opts, \"withdraw\", _tokenAmount)\n}", "func (a AuthorizerFunc) GrantLogin(user string, hostID string, hostIDType string, action string) (bool, error) {\n\treturn a(user, hostID, hostIDType, action)\n}", "func (_Wmatic *WmaticTransactorSession) Withdraw(wad *big.Int) (*types.Transaction, error) {\n\treturn _Wmatic.Contract.Withdraw(&_Wmatic.TransactOpts, wad)\n}", "func (_TxRelay *TxRelayTransactor) AddToWhitelist(opts *bind.TransactOpts, addr common.Address) (*types.Transaction, error) {\n\treturn _TxRelay.contract.Transact(opts, \"addToWhitelist\", addr)\n}", "func (s *Scope) AddBaggage(key string, value string) {\n\ttracergo.AddBaggage(s.Span, key, value)\n}", "func (client *Client) GrantInstanceToVbr(request *GrantInstanceToVbrRequest) (response *GrantInstanceToVbrResponse, err error) {\n\tresponse = CreateGrantInstanceToVbrResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (g *redirectGrant) GrantNeeded(user user.Info, grant *api.Grant, w http.ResponseWriter, req *http.Request) (bool, bool, error) {\n\tredirectURL, err := url.Parse(g.url)\n\tif err != nil {\n\t\treturn false, false, err\n\t}\n\tredirectURL.RawQuery = url.Values{\n\t\t\"then\": {req.URL.String()},\n\t\t\"client_id\": {grant.Client.GetId()},\n\t\t\"scope\": {grant.Scope},\n\t\t\"redirect_uri\": {grant.RedirectURI},\n\t}.Encode()\n\thttp.Redirect(w, req, redirectURL.String(), http.StatusFound)\n\treturn false, true, nil\n}", "func (s *StashList) AddStash(ctx context.Context, vw types.ValueWriter, stashAddr hash.Hash) (hash.Hash, error) {\n\tstashID := strconv.Itoa(s.lastIdx + 1)\n\n\tame := s.am.Editor()\n\terr := ame.Add(ctx, stashID, stashAddr)\n\tif err != nil {\n\t\treturn hash.Hash{}, err\n\t}\n\n\ts.am, err = ame.Flush(ctx)\n\tif err != nil {\n\t\treturn hash.Hash{}, err\n\t}\n\treturn s.updateStashListMap(ctx, vw)\n}", "func GrantByName(name string) Grant {\n\tfor g, grantName := range grantNameMap {\n\t\tif grantName == name {\n\t\t\treturn g\n\t\t}\n\t}\n\n\treturn GrantNone\n}", "func DeployGatekeeper(auth *bind.TransactOpts, backend bind.ContractBackend, _token common.Address) (common.Address, *types.Transaction, *Gatekeeper, error) {\n\tparsed, err := abi.JSON(strings.NewReader(GatekeeperABI))\n\tif err != nil {\n\t\treturn common.Address{}, nil, nil, err\n\t}\n\taddress, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(GatekeeperBin), backend, _token)\n\tif err != nil {\n\t\treturn common.Address{}, nil, nil, err\n\t}\n\treturn address, tx, &Gatekeeper{GatekeeperCaller: GatekeeperCaller{contract: contract}, GatekeeperTransactor: GatekeeperTransactor{contract: contract}, GatekeeperFilterer: GatekeeperFilterer{contract: contract}}, nil\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCallerSession) TokenGrant() (common.Address, error) {\n\treturn _TokenStakingEscrow.Contract.TokenGrant(&_TokenStakingEscrow.CallOpts)\n}", "func (k *Oauth2CredsCollection) Add(oauth2Cred Oauth2Credential) error {\n\ttxn := k.db.Txn(true)\n\tdefer txn.Abort()\n\terr := txn.Insert(oauth2CredTableName, &oauth2Cred)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"insert failed\")\n\t}\n\ttxn.Commit()\n\treturn nil\n}", "func (_BaseLibrary *BaseLibraryTransactor) AddContributorGroup(opts *bind.TransactOpts, group common.Address) (*types.Transaction, error) {\n\treturn _BaseLibrary.contract.Transact(opts, \"addContributorGroup\", group)\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"gatlingtask-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource GatlingTask\n\terr = c.Watch(&source.Kind{Type: &tpokkiv1alpha1.GatlingTask{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource Pods and requeue the owner GatlingTask\n\terr = c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &tpokkiv1alpha1.GatlingTask{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource ConfigMap and requeue the owner GatlingTask\n\terr = c.Watch(&source.Kind{Type: &corev1.ConfigMap{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &tpokkiv1alpha1.GatlingTask{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (_TokenStakingEscrow *TokenStakingEscrowTransactor) Withdraw(opts *bind.TransactOpts, operator common.Address) (*types.Transaction, error) {\n\treturn _TokenStakingEscrow.contract.Transact(opts, \"withdraw\", operator)\n}", "func (c *context) WgAdd(delta int) {\n\tc.waitGroup.Add(delta)\n}", "func (_Logger *LoggerTransactor) LogStakeWithdraw(opts *bind.TransactOpts, committed common.Address, amount *big.Int, batch_id *big.Int) (*types.Transaction, error) {\n\treturn _Logger.contract.Transact(opts, \"logStakeWithdraw\", committed, amount, batch_id)\n}", "func (n *Node) DeleteGrant(ctx context.Context, g *provider.Grant, acquireLock bool) (err error) {\n\n\tvar attr string\n\tif g.Grantee.Type == provider.GranteeType_GRANTEE_TYPE_GROUP {\n\t\tattr = prefixes.GrantGroupAcePrefix + g.Grantee.GetGroupId().OpaqueId\n\t} else {\n\t\tattr = prefixes.GrantUserAcePrefix + g.Grantee.GetUserId().OpaqueId\n\t}\n\n\tif err = n.RemoveXattr(ctx, attr, acquireLock); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func addStagedSigner(notaryRepo client.Repository, newSigner data.RoleName, signerKeys []data.PublicKey) {\n\t// create targets/<username>\n\tnotaryRepo.AddDelegationRoleAndKeys(newSigner, signerKeys)\n\tnotaryRepo.AddDelegationPaths(newSigner, []string{\"\"})\n\n\t// create targets/releases\n\tnotaryRepo.AddDelegationRoleAndKeys(trust.ReleasesRole, signerKeys)\n\tnotaryRepo.AddDelegationPaths(trust.ReleasesRole, []string{\"\"})\n}", "func (b *PlanBuilder) AddConnectPhase(plan *storage.OperationPlan, trustedCluster storage.TrustedCluster) error {\n\tbytes, err := storage.MarshalTrustedCluster(trustedCluster)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tplan.Phases = append(plan.Phases, storage.OperationPhase{\n\t\tID: phases.ConnectPhase,\n\t\tDescription: fmt.Sprintf(\"Connect to Gravity Hub %v\",\n\t\t\ttrustedCluster.GetName()),\n\t\tData: &storage.OperationPhaseData{\n\t\t\tServer: &b.Master,\n\t\t\tTrustedCluster: bytes,\n\t\t},\n\t\tRequires: []string{ossphases.RuntimePhase},\n\t\tStep: 8,\n\t})\n\treturn nil\n}" ]
[ "0.7331163", "0.7113666", "0.55019873", "0.5447035", "0.54171383", "0.539944", "0.53757775", "0.528504", "0.5252317", "0.52441466", "0.52223444", "0.5207451", "0.5137339", "0.51206416", "0.50980806", "0.5086144", "0.49832323", "0.49606624", "0.4951147", "0.49187273", "0.4871348", "0.48374197", "0.4823577", "0.47955072", "0.4794888", "0.4776616", "0.47117308", "0.4669261", "0.4666374", "0.46568024", "0.46529588", "0.46432397", "0.46197397", "0.45933405", "0.4589699", "0.4575584", "0.45622855", "0.45452762", "0.45407313", "0.44730878", "0.44706523", "0.44515884", "0.44418055", "0.4440541", "0.44367248", "0.4423879", "0.43928018", "0.43833715", "0.4382374", "0.43594477", "0.43562815", "0.43516108", "0.4351475", "0.43473408", "0.4329847", "0.4321245", "0.43165305", "0.43152043", "0.4292013", "0.42914504", "0.42889822", "0.42867324", "0.42866", "0.42828035", "0.4279926", "0.42754656", "0.42739725", "0.4269549", "0.4262396", "0.4243173", "0.42424712", "0.42352143", "0.422736", "0.42208287", "0.42205748", "0.4217174", "0.4216062", "0.4194851", "0.41897792", "0.4188728", "0.41874108", "0.4171279", "0.4166087", "0.4165034", "0.4163577", "0.41632545", "0.4158633", "0.41584706", "0.4154709", "0.4152258", "0.4149887", "0.4149555", "0.41487604", "0.41242623", "0.41209364", "0.4120907", "0.41203383", "0.41157416", "0.41112125", "0.41105625" ]
0.73836535
0
GetFunder implements the exported.ClawbackVestingAccountI interface.
func (va ClawbackVestingAccount) GetFunder() sdk.AccAddress { addr, err := sdk.AccAddressFromBech32(va.FunderAddress) if err != nil { panic(err) } return addr }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (svc *Service) GetFundsForProposalByFunder(req client.GetFundsForProposalByFunderRequest, reply *client.GetFundsForProposalByFunderReply) error {\n\t// Validate parameters\n\terr := req.Funder.Err()\n\tif err != nil {\n\t\treturn errors.New(\"invalid funder address\")\n\t}\n\n\tamount := svc.proposalMaster.ProposalFund.GetFundsForProposalByFunder(req.ProposalId, req.Funder)\n\t*reply = client.GetFundsForProposalByFunderReply{\n\t\tAmount: *amount,\n\t}\n\n\treturn nil\n}", "func GetFactionLedger(hc *http.Client, rc string, f string) (FactionLedger, error) {\n\tl := log.WithFields(log.Fields{\n\t\t\"action\": \"sotapi.GetFactionLedger\",\n\t})\n\n\tfactionBandTitle := BandTitle{\n\t\tAthenasFortune: []string{\"Legend\", \"Guardian\", \"Voyager\", \"Seeker\"},\n\t\tGoldHoarder: []string{\"Captain\", \"Marauder\", \"Seafarer\", \"Castaway\"},\n\t\tMerchantAlliance: []string{\"Admiral\", \"Commander\", \"Cadet\", \"Sailor\"},\n\t\tOrderOfSouls: []string{\"Grandee\", \"Chief\", \"Mercenary\", \"Apprentice\"},\n\t\tReapersBone: []string{\"Master\", \"Keeper\", \"Servant\", \"Follower\"},\n\t}\n\n\tvar apiUrl string\n\tapiBase := \"https://www.seaofthieves.com/api/ledger/friends/\"\n\n\tswitch f {\n\tcase \"athena\":\n\t\tapiUrl = fmt.Sprintf(\"%v%v?count=10\", apiBase, \"AthenasFortune\")\n\tcase \"hoarder\":\n\t\tapiUrl = fmt.Sprintf(\"%v%v?count=10\", apiBase, \"GoldHoarders\")\n\tcase \"merchant\":\n\t\tapiUrl = fmt.Sprintf(\"%v%v?count=10\", apiBase, \"MerchantAlliance\")\n\tcase \"order\":\n\t\tapiUrl = fmt.Sprintf(\"%v%v?count=10\", apiBase, \"OrderOfSouls\")\n\tcase \"reaper\":\n\t\tapiUrl = fmt.Sprintf(\"%v%v?count=10\", apiBase, \"ReapersBones\")\n\tdefault:\n\t\treturn FactionLedger{}, fmt.Errorf(\"Unknown faction\")\n\t}\n\n\tl.Debugf(\"Fetching user ledger position in %v faction from API...\", f)\n\tvar userApiLedger ApiLedger\n\thttpResp, err := httpclient.HttpReqGet(apiUrl, hc, &rc, nil, false)\n\tif err != nil {\n\t\treturn FactionLedger{}, err\n\t}\n\tif err := json.Unmarshal(httpResp, &userApiLedger); err != nil {\n\t\tl.Errorf(\"Failed to unmarshal API response: %v\", err)\n\t\treturn FactionLedger{}, err\n\t}\n\n\tuserFactionLedger := userApiLedger.Current.Friends.User\n\tswitch f {\n\tcase \"athena\":\n\t\tuserFactionLedger.Name = \"Athenas Fortune\"\n\t\tuserFactionLedger.BandTitle = factionBandTitle.AthenasFortune[userFactionLedger.Band]\n\tcase \"hoarder\":\n\t\tuserFactionLedger.Name = \"Gold Hoarders\"\n\t\tuserFactionLedger.BandTitle = factionBandTitle.GoldHoarder[userFactionLedger.Band]\n\tcase \"merchant\":\n\t\tuserFactionLedger.Name = \"Merchant Alliance\"\n\t\tuserFactionLedger.BandTitle = factionBandTitle.MerchantAlliance[userFactionLedger.Band]\n\tcase \"order\":\n\t\tuserFactionLedger.Name = \"Order of Souls\"\n\t\tuserFactionLedger.BandTitle = factionBandTitle.OrderOfSouls[userFactionLedger.Band]\n\tcase \"reaper\":\n\t\tuserFactionLedger.Name = \"Reaper's Bones\"\n\t\tuserFactionLedger.BandTitle = factionBandTitle.ReapersBone[userFactionLedger.Band]\n\t}\n\n\treturn userFactionLedger, nil\n}", "func (player *Athelete) Fine(amount float32) {\n\tplayer.AccountBalance -= amount\n}", "func (o *Tier) GetFamily() string {\n\tif o == nil || o.Family == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Family\n}", "func (f *Fund) Balance() int {\r\n\treturn f.balance\r\n}", "func NewFundedAccount() *keypair.Full {\n\tkp, err := keypair.Random()\n\tif err != nil {\n\t\tlog.Fatal(err, \"generating random keypair\")\n\t}\n\terr = FundAccount(kp.Address())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"successfully funded %s\", kp.Address())\n\treturn kp\n}", "func (o *TransactionSplit) GetForeignAmount() string {\n\tif o == nil || o.ForeignAmount.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ForeignAmount.Get()\n}", "func (f *Fund) Balance() int {\n\treturn f.balance\n}", "func (f *Fund) Balance() int {\n\treturn f.balance\n}", "func (f *Fund) Balance() int {\n\treturn f.balance\n}", "func (_BREMICO *BREMICOCallerSession) WithdrawFeePercent() (*big.Int, error) {\n\treturn _BREMICO.Contract.WithdrawFeePercent(&_BREMICO.CallOpts)\n}", "func (m *Message) FAC() (*FAC, error) {\n\tps, err := m.Parse(\"FAC\")\n\tpst, ok := ps.(*FAC)\n\tif ok {\n\t\treturn pst, err\n\t}\n\treturn nil, err\n}", "func (m FailingFunder) Fund(ctx context.Context, req channel.FundingReq) error {\n\treturn errors.New(\"funding failed\")\n}", "func NewClawbackVestingAccount(baseAcc *authtypes.BaseAccount, funder sdk.AccAddress, originalVesting sdk.Coins, startTime int64, lockupPeriods, vestingPeriods Periods) *ClawbackVestingAccount {\n\t// copy and align schedules to avoid mutating inputs\n\tlp := make(Periods, len(lockupPeriods))\n\tcopy(lp, lockupPeriods)\n\tvp := make(Periods, len(vestingPeriods))\n\tcopy(vp, vestingPeriods)\n\t_, endTime := AlignSchedules(startTime, startTime, lp, vp)\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ClawbackVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tFunderAddress: funder.String(),\n\t\tStartTime: startTime,\n\t\tLockupPeriods: lp,\n\t\tVestingPeriods: vp,\n\t}\n}", "func (o *W2) GetDependentCareBenefits() string {\n\tif o == nil || o.DependentCareBenefits.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DependentCareBenefits.Get()\n}", "func (_BREMICO *BREMICOCaller) WithdrawFeePercent(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BREMICO.contract.Call(opts, out, \"withdrawFeePercent\")\n\treturn *ret0, err\n}", "func (cg *ConsumerGroup) GetUserFacingResourceRef() *metav1.OwnerReference {\n\tfor i, or := range cg.OwnerReferences {\n\t\t// TODO hardcoded resource kinds.\n\t\tif strings.EqualFold(or.Kind, \"trigger\") ||\n\t\t\tstrings.EqualFold(or.Kind, \"kafkasource\") ||\n\t\t\tstrings.EqualFold(or.Kind, \"kafkachannel\") {\n\t\t\treturn &cg.OwnerReferences[i]\n\t\t}\n\t}\n\treturn nil\n}", "func (x ThirdPartyServiceEntity) GetAccount() accounts.AccountOutline {\n\treturn x.Account\n}", "func (m Message) UnderlyingCashAmount() (*field.UnderlyingCashAmountField, quickfix.MessageRejectError) {\n\tf := &field.UnderlyingCashAmountField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (a *Account) Funnel(id int) (*Funnel, error) {\n\tassert(a.id > 0, \"find funnel on unsaved account: %d\", a.id)\n\tf, err := a.Tx.Funnel(id)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if f.AccountID != a.ID() {\n\t\treturn nil, ErrFunnelNotFound\n\t}\n\treturn f, nil\n}", "func (inst *DeprecatedPopulateParticipationPrintingAccount) GetPayerWithRefundAccount() *ag_solanago.AccountMeta {\n\treturn inst.AccountMetaSlice[16]\n}", "func (k King) Fight() string {\n\tif k.Weapon == nil {\n\t\treturn fmt.Sprintf(\"King %s does not have any weapon, provide one !!\", k.Name)\n\t}\n\treturn fmt.Sprintf(\"King %s fights with %s\", k.Name, k.Weapon.Attack())\n}", "func (_FCToken *FCTokenCallerSession) GetBalance() (*big.Int, error) {\n\treturn _FCToken.Contract.GetBalance(&_FCToken.CallOpts)\n}", "func (e *Huobi) GetAccount() interface{} {\n\taccounts, err := services.GetAccounts()\n\tif err != nil {\n\t\te.logger.Log(constant.ERROR, \"\", 0.0, 0.0, \"GetAccount() error, \", err)\n\t\treturn false\n\t}\n\tif accounts.Status != \"ok\" {\n\t\te.logger.Log(constant.ERROR, \"\", 0.0, 0.0, \"GetAccount() error, \", accounts.ErrMsg)\n\t\treturn false\n\t}\n\taccountID := int64(-1)\n\tcount := len(accounts.Data)\n\tfor i := 0; i < count; i++ {\n\t\tactData := accounts.Data[i]\n\t\tif actData.State == \"working\" && actData.Type == \"spot\" {\n\t\t\taccountID = actData.ID\n\t\t\tbreak\n\t\t}\n\t}\n\tif accountID == -1 {\n\t\te.logger.Log(constant.ERROR, \"\", 0.0, 0.0, \"GetAccount() error, \", \"all account locked\")\n\t\treturn false\n\t}\n\tbalance, err := services.GetAccountBalance(strconv.FormatInt(accountID, 10))\n\tif err != nil {\n\t\te.logger.Log(constant.ERROR, \"\", 0.0, 0.0, \"GetAccount() error, \", err)\n\t\treturn false\n\t}\n\tif balance.Status != \"ok\" {\n\t\te.logger.Log(constant.ERROR, \"\", 0.0, 0.0, \"GetAccount() error, \", balance.ErrMsg)\n\t\treturn false\n\t}\n\tresult := make(map[string]float64)\n\tcount = len(balance.Data.List)\n\tfor i := 0; i < count; i++ {\n\t\tsubAcc := balance.Data.List[i]\n\t\tif subAcc.Type == \"trade\" {\n\t\t\tresult[strings.ToUpper(subAcc.Currency)] = conver.Float64Must(subAcc.Balance)\n\t\t} else if subAcc.Type == \"frozen\" {\n\t\t\tresult[\"Frozen\"+strings.ToUpper(subAcc.Currency)] = conver.Float64Must(subAcc.Balance)\n\t\t}\n\t}\n\t//...\n\tconfig.ACCOUNT_ID = strconv.FormatInt(accountID, 10)\n\t//...\n\treturn result\n}", "func (f *Fortune) Withdrawal(amount decimal.Decimal) {\n\tf.active = f.active.Sub(amount)\n}", "func (_BREMFactory *BREMFactoryCallerSession) WithdrawFeePercent() (*big.Int, error) {\n\treturn _BREMFactory.Contract.WithdrawFeePercent(&_BREMFactory.CallOpts)\n}", "func (_Cakevault *CakevaultCallerSession) WithdrawFee() (*big.Int, error) {\n\treturn _Cakevault.Contract.WithdrawFee(&_Cakevault.CallOpts)\n}", "func (u *User) WithdrawCash(amount int) int {\n\tif amount <= 0 {\n\t\treturn u.cash\n\t}\n\n\tif amount > u.cash {\n\t\treturn u.cash\n\t}\n\n\tu.cash -= amount\n\treturn u.cash\n}", "func (c *Client) GetFullName() string {\n\tif c != nil {\n\t\treturn fmt.Sprintf(\"%s %s\", c.GetFirstName(), c.GetLastName())\n\t}\n\treturn \"\"\n}", "func (va *ClawbackVestingAccount) clawback(ctx sdk.Context, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) error {\n\t// Compute the clawback based on the account state only, and update account\n\ttoClawBack := va.computeClawback(ctx.BlockTime().Unix())\n\tif toClawBack.IsZero() {\n\t\treturn nil\n\t}\n\taddr := va.GetAddress()\n\tbondDenom := sk.BondDenom(ctx)\n\n\t// Compute the clawback based on bank balance and delegation, and update account\n\tencumbered := va.GetVestingCoins(ctx.BlockTime())\n\tbondedAmt := sk.GetDelegatorBonded(ctx, addr)\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, addr)\n\tbonded := sdk.NewCoins(sdk.NewCoin(bondDenom, bondedAmt))\n\tunbonding := sdk.NewCoins(sdk.NewCoin(bondDenom, unbondingAmt))\n\tunbonded := bk.GetAllBalances(ctx, addr)\n\ttoClawBack = va.updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded)\n\n\t// Write now now so that the bank module sees unvested tokens are unlocked.\n\t// Note that all store writes are aborted if there is a panic, so there is\n\t// no danger in writing incomplete results.\n\tak.SetAccount(ctx, va)\n\n\t// Now that future vesting events (and associated lockup) are removed,\n\t// the balance of the account is unlocked and can be freely transferred.\n\tspendable := bk.SpendableCoins(ctx, addr)\n\ttoXfer := coinsMin(toClawBack, spendable)\n\terr := bk.SendCoins(ctx, addr, dest, toXfer)\n\tif err != nil {\n\t\treturn err // shouldn't happen, given spendable check\n\t}\n\ttoClawBack = toClawBack.Sub(toXfer)\n\n\t// We need to traverse the staking data structures to update the\n\t// vesting account bookkeeping, and to recover more funds if necessary.\n\t// Staking is the only way unvested tokens should be missing from the bank balance.\n\n\t// If we need more, transfer UnbondingDelegations.\n\twant := toClawBack.AmountOf(bondDenom)\n\tunbondings := sk.GetUnbondingDelegations(ctx, addr, math.MaxUint16)\n\tfor _, unbonding := range unbondings {\n\t\tvalAddr, err := sdk.ValAddressFromBech32(unbonding.ValidatorAddress)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttransferred := sk.TransferUnbonding(ctx, addr, dest, valAddr, want)\n\t\twant = want.Sub(transferred)\n\t\tif !want.IsPositive() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If we need more, transfer Delegations.\n\tif want.IsPositive() {\n\t\tdelegations := sk.GetDelegatorDelegations(ctx, addr, math.MaxUint16)\n\t\tfor _, delegation := range delegations {\n\t\t\tvalidatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // shouldn't happen\n\t\t\t}\n\t\t\tvalidator, found := sk.GetValidator(ctx, validatorAddr)\n\t\t\tif !found {\n\t\t\t\t// validator has been removed\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twantShares, err := validator.SharesFromTokensTruncated(want)\n\t\t\tif err != nil {\n\t\t\t\t// validator has no tokens\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttransferredShares := sk.TransferDelegation(ctx, addr, dest, delegation.GetValidatorAddr(), wantShares)\n\t\t\t// to be conservative in what we're clawing back, round transferred shares up\n\t\t\ttransferred := validator.TokensFromSharesRoundUp(transferredShares).RoundInt()\n\t\t\twant = want.Sub(transferred)\n\t\t\tif !want.IsPositive() {\n\t\t\t\t// Could be slightly negative, due to rounding?\n\t\t\t\t// Don't think so, due to the precautions above.\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we've transferred everything and still haven't transferred the desired clawback amount,\n\t// then the account must have most some unvested tokens from slashing.\n\treturn nil\n}", "func (o *AUMPortfolioRisk) GetBalance() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Balance\n}", "func (a ArtifactSpec_Name) Family() ArtifactSpec_Name {\n\tif a.ArtifactType() == ArtifactSpec_STONE_INGREDIENT {\n\t\treturn a.CorrespondingStone()\n\t}\n\treturn a\n}", "func (_BREMFactory *BREMFactoryCaller) WithdrawFeePercent(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BREMFactory.contract.Call(opts, out, \"withdrawFeePercent\")\n\treturn *ret0, err\n}", "func (_BREM *BREMCallerSession) WithdrawFeePercent() (*big.Int, error) {\n\treturn _BREM.Contract.WithdrawFeePercent(&_BREM.CallOpts)\n}", "func (c *Controller) getFunds() float64 {\n\treturn c.broker.GetAvailableFunds() / 10\n}", "func (x ThirdPartyServiceEntityOutline) GetAccount() accounts.AccountOutline {\n\treturn x.Account\n}", "func (o *Transfer) GetFundingAccountId() string {\n\tif o == nil || o.FundingAccountId.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn *o.FundingAccountId.Get()\n}", "func (o *W2) GetFederalIncomeTaxWithheld() string {\n\tif o == nil || o.FederalIncomeTaxWithheld.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.FederalIncomeTaxWithheld.Get()\n}", "func (m *AgedAccountsPayable) GetBalanceDue()(*float64) {\n val, err := m.GetBackingStore().Get(\"balanceDue\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*float64)\n }\n return nil\n}", "func (k *PrivateKey) GetFRElement() *bls.FR {\n\treturn k.PrivKey.GetFRElement()\n}", "func (_BondedECDSAKeep *BondedECDSAKeepCaller) GetMemberETHBalance(opts *bind.CallOpts, _member common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BondedECDSAKeep.contract.Call(opts, out, \"getMemberETHBalance\", _member)\n\treturn *ret0, err\n}", "func GetFrob() (*FrobRecord, error) {\n\targs := map[string]string{\n\t\t\"api_key\": api.APIKey,\n\t}\n\n\tvar frobResponse FrobRecord\n\tunmarshal := func(body []byte) error {\n\t\treturn json.Unmarshal(body, &frobResponse)\n\t}\n\n\terr := api.GetMethod(\"rtm.auth.getFrob\", args, unmarshal)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &frobResponse, nil\n\n}", "func (o *Wireless) GetFamily() string {\n\tif o == nil || o.Family == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Family\n}", "func FundAccount(address string) error {\n\tresp, err := http.Get(\"https://friendbot.zion.info/?addr=\" + address)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"requesting friendbot lumens\")\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"reading response from bad friendbot request %d\", resp.StatusCode)\n\t\t}\n\t\treturn fmt.Errorf(\"error funding address through friendbot. got bad status code %d, response %s\", resp.StatusCode, body)\n\t}\n\treturn nil\n}", "func (_Cakevault *CakevaultCallerSession) MAXWITHDRAWFEE() (*big.Int, error) {\n\treturn _Cakevault.Contract.MAXWITHDRAWFEE(&_Cakevault.CallOpts)\n}", "func (_BREM *BREMCaller) WithdrawFeePercent(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BREM.contract.Call(opts, out, \"withdrawFeePercent\")\n\treturn *ret0, err\n}", "func (t *TezTracker) GetAccount(id string) (acc models.AccountListView, err error) {\n\tr := t.repoProvider.GetAccount()\n\n\tfilter := models.Account{AccountID: null.StringFrom(id)}\n\n\tfound, acc, err := r.Find(filter)\n\tif err != nil {\n\t\treturn acc, err\n\t}\n\tif !found {\n\t\treturn acc, ErrNotFound\n\t}\n\n\tcounts, err := t.repoProvider.GetOperation().AccountOperationCount(acc.AccountID.String)\n\tif err != nil {\n\t\treturn acc, err\n\t}\n\n\tvar total int64\n\tfor i := range counts {\n\t\tif counts[i].Kind == \"transaction\" {\n\t\t\tacc.Transactions = counts[i].Count\n\t\t}\n\t\tif counts[i].Kind == \"reveal\" {\n\t\t\tacc.IsRevealed = true\n\t\t}\n\n\t\ttotal += counts[i].Count\n\t}\n\n\tacc.Operations = total\n\n\tbi, err := t.GetBakerInfo(id)\n\tif err != nil {\n\t\treturn acc, err\n\t}\n\n\tacc.BakerInfo = bi\n\n\t//Account identified as baker\n\tif bi != nil {\n\t\t//Set real value for front\n\t\tacc.IsBaker = true\n\t}\n\n\treturn acc, nil\n}", "func (t *TezTracker) GetAccount(id string) (acc models.AccountListView, err error) {\n\tr := t.repoProvider.GetAccount()\n\n\tfilter := models.Account{AccountID: null.StringFrom(id)}\n\n\tfound, acc, err := r.Find(filter)\n\tif err != nil {\n\t\treturn acc, err\n\t}\n\tif !found {\n\t\treturn acc, ErrNotFound\n\t}\n\n\tcounts, err := t.repoProvider.GetOperation().AccountOperationCount(acc.AccountID.String)\n\tif err != nil {\n\t\treturn acc, err\n\t}\n\n\tvar total int64\n\tfor i := range counts {\n\t\tif counts[i].Kind == \"transaction\" {\n\t\t\tacc.Transactions = counts[i].Count\n\t\t}\n\t\tif counts[i].Kind == \"reveal\" {\n\t\t\tacc.IsRevealed = true\n\t\t}\n\n\t\ttotal += counts[i].Count\n\t}\n\n\tacc.Operations = total\n\n\tbi, err := t.GetBakerInfo(id)\n\tif err != nil {\n\t\treturn acc, err\n\t}\n\n\tacc.BakerInfo = bi\n\n\t//Account identified as baker\n\tif bi != nil {\n\t\t//Set real value for front\n\t\tacc.IsBaker = true\n\t}\n\n\treturn acc, nil\n}", "func (_Cakevault *CakevaultSession) WithdrawFee() (*big.Int, error) {\n\treturn _Cakevault.Contract.WithdrawFee(&_Cakevault.CallOpts)\n}", "func (_BREMICO *BREMICOSession) WithdrawFeePercent() (*big.Int, error) {\n\treturn _BREMICO.Contract.WithdrawFeePercent(&_BREMICO.CallOpts)\n}", "func (_BREMFactory *BREMFactorySession) WithdrawFeePercent() (*big.Int, error) {\n\treturn _BREMFactory.Contract.WithdrawFeePercent(&_BREMFactory.CallOpts)\n}", "func (m Message) GetAccount(f *field.AccountField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}", "func (o PartnerAccountOutput) Fingerprint() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PartnerAccount) pulumi.StringOutput { return v.Fingerprint }).(pulumi.StringOutput)\n}", "func (k Knight) Fight() string {\n\tif k.Weapon == nil {\n\t\treturn fmt.Sprintf(\"Kight %s does not have any weapon, provide one !!\", k.Name)\n\t}\n\treturn fmt.Sprintf(\"Kight %s fights with %s\", k.Name, k.Weapon.Attack())\n}", "func (x UnavailableEntity) GetAccount() accounts.AccountOutline {\n\treturn x.Account\n}", "func (_class PIFClass) GetUUID(sessionID SessionRef, self PIFRef) (_retval string, _err error) {\n\t_method := \"PIF.get_uuid\"\n\t_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf(\"%s(%s)\", _method, \"session_id\"), sessionID)\n\tif _err != nil {\n\t\treturn\n\t}\n\t_selfArg, _err := convertPIFRefToXen(fmt.Sprintf(\"%s(%s)\", _method, \"self\"), self)\n\tif _err != nil {\n\t\treturn\n\t}\n\t_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)\n\tif _err != nil {\n\t\treturn\n\t}\n\t_retval, _err = convertStringToGo(_method + \" -> \", _result.Value)\n\treturn\n}", "func (s *SubsetFontObj) GetFamily() string {\n\treturn s.Family\n}", "func (_BurnableToken *BurnableTokenSession) BurnForRefund(_burner common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BurnableToken.Contract.BurnForRefund(&_BurnableToken.TransactOpts, _burner, _value)\n}", "func (o SkuPtrOutput) Family() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Sku) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Family\n\t}).(pulumi.StringPtrOutput)\n}", "func (_Cakevault *CakevaultCaller) WithdrawFee(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"withdrawFee\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (a SubAccountClient) GetSubAccountBalance(req *rest3.RequestForSubAccountBalance) (rest3.ResponseForSubAccountBalance, error) {\n\tpanic(\"implement me\")\n}", "func (_BREMToken *BREMTokenSession) BurnForRefund(_burner common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BREMToken.Contract.BurnForRefund(&_BREMToken.TransactOpts, _burner, _value)\n}", "func (_BurnableToken *BurnableTokenTransactorSession) BurnForRefund(_burner common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BurnableToken.Contract.BurnForRefund(&_BurnableToken.TransactOpts, _burner, _value)\n}", "func (m *User) GetFaxNumber()(*string) {\n return m.faxNumber\n}", "func (_FCToken *FCTokenCaller) GetBalance(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _FCToken.contract.Call(opts, &out, \"getBalance\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (m Message) UnderlyingFXRate() (*field.UnderlyingFXRateField, quickfix.MessageRejectError) {\n\tf := &field.UnderlyingFXRateField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (me *XsdGoPkgHasElem_GetAccountBalance) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_GetAccountBalance; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.GetAccountBalance.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func getItem(Curr string) (*ForexData, error) {\n\t// Prepare the input for the query.\n\tinput := &dynamodb.GetItemInput{\n\t\tTableName: aws.String(\"Forextable\"),\n\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\"Curr\": {\n\t\t\t\tS: aws.String(Curr),\n\t\t\t},\n\t\t},\n\t}\n\n\t// Retrieving the item from DynamoDB. If no matching item is found, return nil.\n\tresult, err := db.GetItem(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif result.Item == nil {\n\t\treturn nil, nil\n\t}\n\n\t// The result.Item object returned has the underlying type map[string]*AttributeValue.\n\t// UnmarshalMap helper to parse this straight into the fields of a struct. Note:\n\tforexitem := new(ForexData)\n\terr = dynamodbattribute.UnmarshalMap(result.Item, forexitem)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn forexitem, nil\n}", "func (s *Service) GetWithdraw(c context.Context, dateVersion string, from, limit int) (count int, withdrawVos []*model.WithdrawVo, err error) {\n\tcount, upAccounts, err := s.UpWithdraw(c, dateVersion, from, limit)\n\tif err != nil {\n\t\tlog.Error(\"s.UpWithdraw error(%v)\", err)\n\t\treturn\n\t}\n\n\tmids := make([]int64, len(upAccounts))\n\tfor i, up := range upAccounts {\n\t\tmids[i] = up.MID\n\t}\n\n\twithdrawVos = make([]*model.WithdrawVo, 0)\n\tif len(mids) == 0 {\n\t\treturn\n\t}\n\n\tupIncomeWithdrawMap, err := s.dao.QueryUpWithdrawByMids(c, mids, dateVersion)\n\tif err != nil {\n\t\tlog.Error(\"s.dao.QueryUpWithdrawByMids error(%v)\", err)\n\t\treturn\n\t}\n\n\tfor _, up := range upAccounts {\n\t\tif upIncomeWithdraw, ok := upIncomeWithdrawMap[up.MID]; ok && upIncomeWithdraw.State == _withdrawing {\n\t\t\tvo := &model.WithdrawVo{\n\t\t\t\tMID: up.MID,\n\t\t\t\tThirdCoin: float64(up.TotalUnwithdrawIncome) * float64(0.01),\n\t\t\t\tThirdOrderNo: strconv.FormatInt(upIncomeWithdraw.ID, 10),\n\t\t\t\tCTime: time.Unix(int64(upIncomeWithdraw.CTime), 0).Format(\"2006-01-02 15:04:05\"),\n\t\t\t\tNotifyURL: \"http://up-profit.bilibili.co/allowance/api/x/internal/growup/up/withdraw/success\",\n\t\t\t}\n\n\t\t\twithdrawVos = append(withdrawVos, vo)\n\t\t}\n\t}\n\n\treturn\n}", "func (pr *ProvenAccountResource) GetBalance() uint64 {\n\tif !pr.proven {\n\t\tpanic(\"not valid proven account resource\")\n\t}\n\treturn pr.accountResource.Balance\n}", "func (o *TransactionSplit) GetForeignCurrencyCode() string {\n\tif o == nil || o.ForeignCurrencyCode.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ForeignCurrencyCode.Get()\n}", "func (_BREMToken *BREMTokenTransactorSession) BurnForRefund(_burner common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BREMToken.Contract.BurnForRefund(&_BREMToken.TransactOpts, _burner, _value)\n}", "func (o *Object) GetTier() string {\n\tdo, ok := o.Object.(fs.GetTierer)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn do.GetTier()\n}", "func (o *Object) GetTier() string {\n\tdo, ok := o.Object.(fs.GetTierer)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn do.GetTier()\n}", "func (client *Client) GetOwnUser() (*User, error) {\n\tif len(client.bearer) < 1 {\n\t\treturn nil, errors.New(\"a bearer token is required to use this endpoint\")\n\t}\n\tusers, err := client.GetUsers(UserOpts{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(users.Data) < 1 {\n\t\treturn nil, errors.New(\"unable to get user\")\n\t}\n\tuser := users.Data[0]\n\tclient.Self = user\n\treturn &user, nil\n}", "func (x ExternalEntity) GetAccount() accounts.AccountOutline {\n\treturn x.Account\n}", "func (_Fibonacci *FibonacciCallerSession) GetFib(n *big.Int) (*big.Int, error) {\n\treturn _Fibonacci.Contract.GetFib(&_Fibonacci.CallOpts, n)\n}", "func (m Message) UnderlyingFactor() (*field.UnderlyingFactorField, quickfix.MessageRejectError) {\n\tf := &field.UnderlyingFactorField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) UnderlyingFactor() (*field.UnderlyingFactorField, quickfix.MessageRejectError) {\n\tf := &field.UnderlyingFactorField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func getAffiliation(affiliation, orgName string, sdk *fabsdk.FabricSDK) (*msp.AffiliationResponse, error) {\n\tmspClient, err := msp.New(sdk.Context(), msp.WithOrg(orgName))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn mspClient.GetAffiliation(affiliation)\n}", "func (o *Tier) GetFamilyOk() (*string, bool) {\n\tif o == nil || o.Family == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Family, true\n}", "func getMember(client *chef.Client, member string) chef.User {\n\tmemberInfo, err := client.Users.Get(member)\n\tif err != nil {\n\t\tfmt.Println(\"Issue getting: \"+member, err)\n\t\tpanic(err.Error()) // proper error handling instead of panic in your app\n\t}\n\treturn memberInfo\n}", "func (_BREM *BREMSession) WithdrawFeePercent() (*big.Int, error) {\n\treturn _BREM.Contract.WithdrawFeePercent(&_BREM.CallOpts)\n}", "func (d *Dao) FavDisplay(c context.Context, mid int64) (bangumi, cinema int, err error) {\n\tip := metadata.String(c, metadata.RemoteIP)\n\tparams := url.Values{}\n\tparams.Set(\"mid\", strconv.FormatInt(mid, 10))\n\tvar res struct {\n\t\tCode int `json:\"code\"`\n\t\tResult struct {\n\t\t\tBangumi int `json:\"bangumi\"`\n\t\t\tCinema int `json:\"cinema\"`\n\t\t} `json:\"result\"`\n\t}\n\tif err = d.client.Get(c, d.favDisplay, ip, params, &res); err != nil {\n\t\treturn\n\t}\n\tif res.Code != ecode.OK.Code() {\n\t\terr = errors.Wrap(ecode.Int(res.Code), d.favDisplay+\"?\"+params.Encode())\n\t\treturn\n\t}\n\tbangumi = res.Result.Bangumi\n\tcinema = res.Result.Cinema\n\treturn\n}", "func (_Cakevault *CakevaultSession) MAXWITHDRAWFEE() (*big.Int, error) {\n\treturn _Cakevault.Contract.MAXWITHDRAWFEE(&_Cakevault.CallOpts)\n}", "func (_ElvTradableLocal *ElvTradableLocalCaller) GetTransferFee(opts *bind.CallOpts, _tokenId *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _ElvTradableLocal.contract.Call(opts, &out, \"getTransferFee\", _tokenId)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (t *SimpleChaincode) getFinancialInstitutionDetails(stub shim.ChaincodeStubInterface, finInst string) ([]byte, error) {\n\n\tfmt.Println(\"Start find getFinancialInstitutionDetails\")\n\tfmt.Println(\"Looking for \" + finInst)\n\n\t//get the finInst index\n\tfdAsBytes, err := stub.GetState(finInst)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to get Financial Institution\")\n\t}\n\n\treturn fdAsBytes, nil\n\n}", "func (client *WANPOTSLinkConfig1) GetFclass() (NewFclass string, err error) {\n\treturn client.GetFclassCtx(context.Background())\n}", "func (x UnavailableEntityOutline) GetAccount() accounts.AccountOutline {\n\treturn x.Account\n}", "func (sc Funcs) AccountNFTAmount(ctx wasmlib.ScViewClientContext) *AccountNFTAmountCall {\n\tf := &AccountNFTAmountCall{Func: wasmlib.NewScView(ctx, HScName, HViewAccountNFTAmount)}\n\tf.Params.Proxy = wasmlib.NewCallParamsProxy(f.Func)\n\twasmlib.NewCallResultsProxy(f.Func, &f.Results.Proxy)\n\treturn f\n}", "func (a *FastlyIntegrationApi) GetFastlyAccount(ctx _context.Context, accountId string) (FastlyAccountResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarReturnValue FastlyAccountResponse\n\t)\n\n\tlocalBasePath, err := a.Client.Cfg.ServerURLWithContext(ctx, \"v2.FastlyIntegrationApi.GetFastlyAccount\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, datadog.GenericOpenAPIError{ErrorMessage: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v2/integrations/fastly/accounts/{account_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"account_id\"+\"}\", _neturl.PathEscape(datadog.ParameterToString(accountId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tlocalVarHeaderParams[\"Accept\"] = \"application/json\"\n\n\tdatadog.SetAuthKeys(\n\t\tctx,\n\t\t&localVarHeaderParams,\n\t\t[2]string{\"apiKeyAuth\", \"DD-API-KEY\"},\n\t\t[2]string{\"appKeyAuth\", \"DD-APPLICATION-KEY\"},\n\t)\n\treq, err := a.Client.PrepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, nil)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.Client.CallAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := datadog.ReadBody(localVarHTTPResponse)\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := datadog.GenericOpenAPIError{\n\t\t\tErrorBody: localVarBody,\n\t\t\tErrorMessage: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 || localVarHTTPResponse.StatusCode == 403 || localVarHTTPResponse.StatusCode == 404 || localVarHTTPResponse.StatusCode == 429 {\n\t\t\tvar v APIErrorResponse\n\t\t\terr = a.Client.Decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.ErrorModel = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.Client.Decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := datadog.GenericOpenAPIError{\n\t\t\tErrorBody: localVarBody,\n\t\t\tErrorMessage: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (a *SingleAwaitility) GetKubeFedCluster(expNs string, clusterType cluster.Type, condition *v1beta1.ClusterCondition) (v1beta1.KubeFedCluster, bool, error) {\n\tclusters := &v1beta1.KubeFedClusterList{}\n\tif err := a.Client.List(context.TODO(), &client.ListOptions{Namespace: a.Ns}, clusters); err != nil {\n\t\treturn v1beta1.KubeFedCluster{}, false, err\n\t}\n\tfor _, cl := range clusters.Items {\n\t\tif cl.Labels[\"namespace\"] == expNs && cluster.Type(cl.Labels[\"type\"]) == clusterType {\n\t\t\tif containsClusterCondition(cl.Status.Conditions, condition) {\n\t\t\t\ta.T.Logf(\"found %s KubeFedCluster running in namespace '%s'\", clusterType, expNs)\n\t\t\t\treturn cl, true, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn v1beta1.KubeFedCluster{}, false, nil\n}", "func (o *AUMEvoluation) GetBalance() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Balance\n}", "func FFNet(url string) FfInfo {\n\tvar res FfInfo\n\tdoc, err := goquery.NewDocument(url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tprof := doc.Find(\"div[id='profile_top']\")\n\tres.Title = prof.Find(\"b\").Text()\n\tres.Author = prof.Find(\"a\").First().Text()\t\n\tres.AuthorURL,_ = prof.Find(\"a\").First().Attr(\"href\")\n\tres.AuthorURL = strings.Join([]string{\"https://www.fanfiction.net\", res.AuthorURL}, \"\")\n\tres.Desc = prof.Find(\"div[class='xcontrast_txt']\").First().Text()\n\tres.Stats = prof.Find(\"span[class='xgray xcontrast_txt']\").First().Text()\n\n\treturn res\n}", "func (me *XHasElem_ForeName) Walk() (err error) {\n\tif fn := WalkHandlers.XHasElem_ForeName; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (_Cakevault *CakevaultCallerSession) WithdrawFeePeriod() (*big.Int, error) {\n\treturn _Cakevault.Contract.WithdrawFeePeriod(&_Cakevault.CallOpts)\n}", "func (m NoSides) GetAccount() (v string, err quickfix.MessageRejectError) {\n\tvar f field.AccountField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func (afric africaTimeZones) Freetown() string {return \"Africa/Freetown\" }", "func TestFundRecovery( //nolint:revive // test.Test... stutters but this is OK in this special case.\n\tctx context.Context,\n\tt *testing.T,\n\tparams FundSetup,\n\tsetup func(*rand.Rand) ([2]RoleSetup, channel.Asset),\n) {\n\trng := test.Prng(t)\n\n\tt.Run(\"failing funder proposer\", func(t *testing.T) {\n\t\troles, asset := setup(rng)\n\t\troles[0].Funder = FailingFunder{}\n\n\t\trunFredFridaTest(ctx, t, rng, params, roles, asset)\n\t})\n\n\tt.Run(\"failing funder proposee\", func(t *testing.T) {\n\t\troles, asset := setup(rng)\n\t\troles[1].Funder = FailingFunder{}\n\n\t\trunFredFridaTest(ctx, t, rng, params, roles, asset)\n\t})\n\n\tt.Run(\"failing funder both sides\", func(t *testing.T) {\n\t\troles, asset := setup(rng)\n\t\troles[0].Funder = FailingFunder{}\n\t\troles[1].Funder = FailingFunder{}\n\n\t\trunFredFridaTest(ctx, t, rng, params, roles, asset)\n\t})\n}", "func (_DevUtils *DevUtilsTransactor) GetBalance(opts *bind.TransactOpts, ownerAddress common.Address, assetData []byte) (*types.Transaction, error) {\n\treturn _DevUtils.contract.Transact(opts, \"getBalance\", ownerAddress, assetData)\n}" ]
[ "0.52361333", "0.5219271", "0.5107116", "0.49333978", "0.48144346", "0.47565222", "0.47532547", "0.46947348", "0.46947348", "0.46947348", "0.46271998", "0.46200928", "0.45988363", "0.4598473", "0.45913786", "0.4580138", "0.45723897", "0.4563494", "0.45597363", "0.45284525", "0.4526007", "0.45206016", "0.45175213", "0.45161673", "0.45069033", "0.450624", "0.44924933", "0.44722432", "0.44629595", "0.4449418", "0.44223243", "0.44178563", "0.4392868", "0.43869686", "0.4384785", "0.4384156", "0.43814567", "0.43802556", "0.43766004", "0.4374173", "0.43653074", "0.436296", "0.43593392", "0.4349146", "0.43490437", "0.43410623", "0.43396723", "0.43396723", "0.4338768", "0.4337269", "0.43348047", "0.4329167", "0.432783", "0.4323576", "0.43143478", "0.43100563", "0.4300747", "0.42969733", "0.42956355", "0.42942148", "0.4293392", "0.4277509", "0.42710158", "0.42696622", "0.4267931", "0.42678544", "0.42584097", "0.4257051", "0.42566228", "0.42499503", "0.4248918", "0.42449108", "0.42447865", "0.42447865", "0.42431274", "0.42413914", "0.42403877", "0.4239459", "0.4239459", "0.42360914", "0.42337206", "0.42253372", "0.4222151", "0.4221585", "0.42190096", "0.42152774", "0.4212886", "0.42123386", "0.42112887", "0.42067716", "0.42022982", "0.4201986", "0.41877705", "0.41794845", "0.4179112", "0.41726908", "0.41723734", "0.41716912", "0.41684014", "0.41683123" ]
0.82736015
0
GetUnlockedOnly implements the exported.ClawbackVestingAccountI interface. It returns the unlocking schedule at blockTIme. Like GetVestedCoins, but only for the lockup component.
func (va ClawbackVestingAccount) GetUnlockedOnly(blockTime time.Time) sdk.Coins { return ReadSchedule(va.StartTime, va.EndTime, va.LockupPeriods, va.OriginalVesting, blockTime.Unix()) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (_Constants *ConstantsCallerSession) UnstakeLockPeriod() (*big.Int, error) {\n\treturn _Constants.Contract.UnstakeLockPeriod(&_Constants.CallOpts)\n}", "func (_Constants *ConstantsCaller) UnstakeLockPeriod(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Constants.contract.Call(opts, &out, \"unstakeLockPeriod\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_Constants *ConstantsSession) UnstakeLockPeriod() (*big.Int, error) {\n\treturn _Constants.Contract.UnstakeLockPeriod(&_Constants.CallOpts)\n}", "func (m *AndroidWorkProfileGeneralDeviceConfiguration) GetWorkProfilePasswordBlockFingerprintUnlock()(*bool) {\n return m.workProfilePasswordBlockFingerprintUnlock\n}", "func (b *Bitcoind) ListLockUnspent() (unspendableOutputs []UnspendableOutput, err error) {\n\tr, err := b.client.call(\"listlockunspent\", nil)\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &unspendableOutputs)\n\treturn\n}", "func (w *xcWallet) unlocked() bool {\n\tif w.isDisabled() {\n\t\treturn false\n\t}\n\ta, is := w.Wallet.(asset.Authenticator)\n\tif !is {\n\t\treturn w.locallyUnlocked()\n\t}\n\tif w.parent != nil {\n\t\treturn w.parent.unlocked()\n\t}\n\tif !w.connected() {\n\t\treturn false\n\t}\n\treturn w.locallyUnlocked() && !a.Locked()\n}", "func (d *Dot) UnlockedGet(key string) (interface{}, bool) {\n\t//\td.l.Lock() // protect me, and ...\n\t//\tdefer d.l.Unlock() // release me, let me go ...\n\tc := d.getChild(key)\n\treturn c, true // bool avoids usage from templates!\n}", "func (m *InformationProtection) GetBitlocker()(Bitlockerable) {\n val, err := m.GetBackingStore().Get(\"bitlocker\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(Bitlockerable)\n }\n return nil\n}", "func (o *Block) GetReadOnly(ctx context.Context) (readOnly bool, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceBlock, \"ReadOnly\").Store(&readOnly)\n\treturn\n}", "func (m *AndroidWorkProfileGeneralDeviceConfiguration) GetPasswordBlockFingerprintUnlock()(*bool) {\n return m.passwordBlockFingerprintUnlock\n}", "func (_TokensNetwork *TokensNetworkCaller) QueryUnlockedLocks(opts *bind.CallOpts, token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _TokensNetwork.contract.Call(opts, out, \"queryUnlockedLocks\", token, participant, partner, lockhash)\n\treturn *ret0, err\n}", "func (m *AndroidWorkProfileGeneralDeviceConfiguration) GetWorkProfileBlockNotificationsWhileDeviceLocked()(*bool) {\n return m.workProfileBlockNotificationsWhileDeviceLocked\n}", "func (rt *recvTxOut) Locked() bool {\n\treturn rt.locked\n}", "func (_Onesplitaudit *OnesplitauditCallerSession) FLAGDISABLEWETH() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLEWETH(&_Onesplitaudit.CallOpts)\n}", "func (o BucketIamConfigurationBucketPolicyOnlyOutput) LockedTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketIamConfigurationBucketPolicyOnly) *string { return v.LockedTime }).(pulumi.StringPtrOutput)\n}", "func (txo *TxOutput) CanBeUnlockedWith(unlockingData string) bool {\n\treturn txo.ScriptPubKey == unlockingData\n}", "func (m *MailboxMemoryCache) GetBlocked() []Mailbox {\n\tvar result []Mailbox\n\tfor _, mailbox := range m.Data {\n\t\tif mailbox.Blocked {\n\t\t\tresult = append(result, mailbox)\n\t\t}\n\t}\n\treturn result\n}", "func (_Onesplitaudit *OnesplitauditSession) FLAGDISABLEWETH() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLEWETH(&_Onesplitaudit.CallOpts)\n}", "func (out *TxOutput) CanBeUnlocked(data string) bool {\n\treturn out.PublicKey == data\n}", "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (_TokensNetwork *TokensNetworkCallerSession) QueryUnlockedLocks(token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\treturn _TokensNetwork.Contract.QueryUnlockedLocks(&_TokensNetwork.CallOpts, token, participant, partner, lockhash)\n}", "func (_Onesplitaudit *OnesplitauditCallerSession) FLAGDISABLEKYBER() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLEKYBER(&_Onesplitaudit.CallOpts)\n}", "func (wt *Wallet) Locked() bool {\n\treturn <-wt.lockState\n}", "func (sqlStore *SQLStore) GetUnlockedClusterInstallationsPendingWork() ([]*model.ClusterInstallation, error) {\n\n\tbuilder := clusterInstallationSelect.\n\t\tWhere(sq.Eq{\n\t\t\t\"State\": model.AllClusterInstallationStatesPendingWork,\n\t\t}).\n\t\tWhere(\"LockAcquiredAt = 0\").\n\t\tOrderBy(\"CreateAt ASC\")\n\n\tvar clusterInstallations []*model.ClusterInstallation\n\terr := sqlStore.selectBuilder(sqlStore.db, &clusterInstallations, builder)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get cluster installations pending work\")\n\t}\n\n\treturn clusterInstallations, nil\n}", "func (c *Client) RenterInactiveContractsGet() (rc api.RenterContracts, err error) {\n\tquery := fmt.Sprintf(\"?inactive=%v\", true)\n\terr = c.get(\"/renter/contracts\"+query, &rc)\n\treturn\n}", "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (w *rpcWallet) AccountUnlocked(ctx context.Context, acctName string) (bool, error) {\n\t// First return locked status of the account, falling back to walletinfo if\n\t// the account is not individually password protected.\n\tres, err := w.rpcClient.AccountUnlocked(ctx, acctName)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif res.Encrypted {\n\t\treturn *res.Unlocked, nil\n\t}\n\t// The account is not individually encrypted, so check wallet lock status.\n\twalletInfo, err := w.rpcClient.WalletInfo(ctx)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"walletinfo error: %w\", err)\n\t}\n\treturn walletInfo.Unlocked, nil\n}", "func (w *Wallet) Locked() bool {\n\treturn <-w.lockState\n}", "func (_Onesplitaudit *OnesplitauditSession) FLAGDISABLEKYBER() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLEKYBER(&_Onesplitaudit.CallOpts)\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (p *Policy) GetBlockedAccountsInternal(dao dao.DAO) (BlockedAccounts, error) {\n\tp.lock.RLock()\n\tdefer p.lock.RUnlock()\n\tif p.isValid {\n\t\treturn p.blockedAccounts, nil\n\t}\n\tsi := dao.GetStorageItem(p.ContractID, blockedAccountsKey)\n\tif si == nil {\n\t\treturn nil, errors.New(\"BlockedAccounts uninitialized\")\n\t}\n\tba, err := BlockedAccountsFromBytes(si.Value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ba, nil\n}", "func (db *merkleDB) getValueWithoutLock(key path) ([]byte, error) {\n\tif db.closed {\n\t\treturn nil, database.ErrClosed\n\t}\n\n\tn, err := db.getNode(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif n.value.IsNothing() {\n\t\treturn nil, database.ErrNotFound\n\t}\n\treturn n.value.Value(), nil\n}", "func (o *DriveAta) GetSecurityFrozen(ctx context.Context) (securityFrozen bool, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDriveAta, \"SecurityFrozen\").Store(&securityFrozen)\n\treturn\n}", "func (w *Wallet) GetUnspentBlockStakeOutputs() (unspent []types.UnspentBlockStakeOutput, err error) {\n\tw.mu.RLock()\n\tdefer w.mu.RUnlock()\n\n\tif !w.unlocked {\n\t\terr = modules.ErrLockedWallet\n\t\treturn\n\t}\n\n\tunspent = make([]types.UnspentBlockStakeOutput, 0)\n\n\t// prepare fulfillable context\n\tctx := w.getFulfillableContextForLatestBlock()\n\n\t// collect all fulfillable block stake outputs\n\tfor usbsoid, output := range w.blockstakeOutputs {\n\t\tif output.Condition.Fulfillable(ctx) {\n\t\t\tunspent = append(unspent, w.unspentblockstakeoutputs[usbsoid])\n\t\t}\n\t}\n\treturn\n}", "func (out *TxOutput) CanBeUnlocked(data string) bool {\n\treturn out.PubKey == data //PubKey is the data that is used in the PubKey\n}", "func (_TokensNetwork *TokensNetworkSession) QueryUnlockedLocks(token common.Address, participant common.Address, partner common.Address, lockhash [32]byte) (bool, error) {\n\treturn _TokensNetwork.Contract.QueryUnlockedLocks(&_TokensNetwork.CallOpts, token, participant, partner, lockhash)\n}", "func (m *AndroidWorkProfileGeneralDeviceConfiguration) GetWorkProfileBlockAddingAccounts()(*bool) {\n return m.workProfileBlockAddingAccounts\n}", "func (o BucketIamConfigurationBucketPolicyOnlyPtrOutput) LockedTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketIamConfigurationBucketPolicyOnly) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.LockedTime\n\t}).(pulumi.StringPtrOutput)\n}", "func testNonNilTimeoutLock(ctx context.Context, t *testing.T, w *Wallet) {\n\ttimeChan := make(chan time.Time)\n\terr := w.Unlock(ctx, testPrivPass, timeChan)\n\tif err != nil {\n\t\tt.Fatal(\"failed to unlock wallet\")\n\t}\n\ttimeChan <- time.Time{}\n\ttime.Sleep(100 * time.Millisecond) // Allow time for lock in background\n\tif !w.Locked() {\n\t\tt.Fatal(\"wallet should have locked after timeout\")\n\t}\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateLockedAmount(opts *bind.TransactOpts, wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateLockedAmount\", wallet)\n}", "func (_Distributor *DistributorCaller) GetAndUpdateEarnedBountyAmountReadOnly(opts *bind.CallOpts, validatorId *big.Int) error {\n\ttype Bounty struct {\n\t\tearned *big.Int\n\t\tendMonth *big.Int\n\t}\n\tvar bounty Bounty\n\terr := _Distributor.contract.Call(opts, &bounty, \"getAndUpdateEarnedBountyAmount\", validatorId)\n\treturn err\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (o BucketIamConfigurationBucketPolicyOnlyResponseOutput) LockedTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketIamConfigurationBucketPolicyOnlyResponse) string { return v.LockedTime }).(pulumi.StringOutput)\n}", "func (w *xcWallet) locallyUnlocked() bool {\n\tif w.isDisabled() {\n\t\treturn false\n\t}\n\tif w.parent != nil {\n\t\treturn w.parent.locallyUnlocked()\n\t}\n\tw.mtx.RLock()\n\tdefer w.mtx.RUnlock()\n\tif len(w.encPass) == 0 {\n\t\treturn true // unencrypted wallet\n\t}\n\treturn len(w.pw) > 0 // cached password for encrypted wallet\n}", "func (o BucketIamConfigurationUniformBucketLevelAccessOutput) LockedTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketIamConfigurationUniformBucketLevelAccess) *string { return v.LockedTime }).(pulumi.StringPtrOutput)\n}", "func GetUnfreezeClockDeferFunc(t *testing.T) func() {\n\treturn func() {\n\t\tr := recover()\n\t\tUnfreezeClock(t)\n\t\tif r != nil {\n\t\t\tpanic(r)\n\t\t}\n\t}\n}", "func Without(l sync.Locker, f func()) {\n\tl.Unlock()\n\tdefer l.Lock()\n\tf()\n}", "func (cli *Cli) GetFrozenTime(addr string) (int64, error) {\n\tinstance, err := ytc.NewYtc(cli.ytaContractAddr, cli.client)\n\tif err != nil {\n\t\t//log.Fatalf(\"error when create instance of yottacoin stub: %s\\n\", err.Error())\n\t\treturn 0, err\n\t}\n\ttimestamp, err := instance.GetFrozenTimestamp(nil, common.HexToAddress(addr))\n\tif err != nil {\n\t\t//log.Fatalf(\"error when get frozen timestamp of address %s: %s\\n\", addr, err.Error())\n\t\treturn 0, err\n\t}\n\treturn timestamp.Int64(), nil\n}", "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func (m *OnlineMeetingInfo) GetTollFreeNumbers()([]string) {\n val, err := m.GetBackingStore().Get(\"tollFreeNumbers\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]string)\n }\n return nil\n}", "func UnfreezeClock(t *testing.T) {\n\tif t == nil {\n\t\tpanic(\"nice try\")\n\t}\n\tc = &DefaultClock{}\n}", "func TestGetLock(t *testing.T) {\n\tlockfile := lockOrFail(t)\n\tdefer removeTestLock(lockfile)\n}", "func (del Delegation) UnlockedAmount() (hexutil.Big, error) {\n\treturn repository.R().DelegationAmountUnlocked(&del.Address, (*big.Int)(del.Delegation.ToStakerId))\n}", "func (m *ManagedDeviceItemRequestBuilder) BypassActivationLock()(*if245b21847517f2bdf21fefeaac5356812b1d5b2cad61e07f1e97c61a72adfeb.BypassActivationLockRequestBuilder) {\n return if245b21847517f2bdf21fefeaac5356812b1d5b2cad61e07f1e97c61a72adfeb.NewBypassActivationLockRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func testNoNilTimeoutReplacement(ctx context.Context, t *testing.T, w *Wallet) {\n\terr := w.Unlock(ctx, testPrivPass, nil)\n\tif err != nil {\n\t\tt.Fatal(\"failed to unlock wallet\")\n\t}\n\ttimeChan := make(chan time.Time)\n\terr = w.Unlock(ctx, testPrivPass, timeChan)\n\tif err != nil {\n\t\tt.Fatal(\"failed to unlock wallet with time channel\")\n\t}\n\tselect {\n\tcase timeChan <- time.Time{}:\n\tcase <-time.After(100 * time.Millisecond):\n\t\tt.Fatal(\"time channel was not read in 100ms\")\n\t}\n\tif w.Locked() {\n\t\tt.Fatal(\"expected wallet to remain unlocked due to previous unlock without timeout\")\n\t}\n}", "func excludeByIsolation(container *container.Snapshot, ctx *listContext) iterationAction {\n\treturn includeContainer\n}", "func (_Onesplitaudit *OnesplitauditCaller) FLAGDISABLEKYBER(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Onesplitaudit.contract.Call(opts, &out, \"FLAG_DISABLE_KYBER\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (r *reader) GetSurveillanceBlocking() (blocking bool, err error) {\n\t// Retro-compatibility\n\ts, err := r.envParams.GetEnv(\"BLOCK_NSA\")\n\tif err != nil {\n\t\treturn false, err\n\t} else if len(s) != 0 {\n\t\tr.logger.Warn(\"You are using the old environment variable BLOCK_NSA, please consider changing it to BLOCK_SURVEILLANCE\")\n\t\treturn r.envParams.GetOnOff(\"BLOCK_NSA\", libparams.Compulsory())\n\t}\n\treturn r.envParams.GetOnOff(\"BLOCK_SURVEILLANCE\", libparams.Default(\"off\"))\n}", "func (r *Radix) getNonBlocking() interface{} {\n\treturn r.value\n}", "func (f *FakePrivilegedProjectProvider) GetUnsecured(projectInternalName string, options *provider.ProjectGetOptions) (*kubermaticapiv1.Project, error) {\n\tif NoExistingFakeProjectID == projectInternalName {\n\t\treturn nil, createError(http.StatusNotFound, \"\")\n\t}\n\tif ForbiddenFakeProjectID == projectInternalName {\n\t\treturn nil, createError(http.StatusForbidden, \"\")\n\t}\n\n\treturn nil, nil\n}", "func WithoutBlocking(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, nonBlockingTxnCtxKey, &nonBlockingTxnOpt{})\n}", "func UnLock(worktree string) func(*types.Cmd) {\n\treturn func(g *types.Cmd) {\n\t\tg.AddOptions(\"unlock\")\n\t\tg.AddOptions(worktree)\n\t}\n}", "func getUnspent(addr string, page int) (string, error) {\n\turl := bitcoinCashAPI + \"/address/\" + addr + \"/unspent?pagesize=\" +\n\t\tstrconv.Itoa(defaultPageSize) + \"&page=\" + strconv.Itoa(page)\n\n\tres, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif res.StatusCode != 200 {\n\t\treturn \"\", errors.New(\"request failed\")\n\t}\n\n\tcontent, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(content), nil\n}", "func (policy *ticketPolicy) OnWalletUnlocked(param *types.WalletUnLock) {\n\tif param.WalletOrTicket {\n\t\tatomic.CompareAndSwapInt32(&policy.isTicketLocked, 1, 0)\n\t\tif param.Timeout != 0 {\n\t\t\tpolicy.resetTimeout(param.Timeout)\n\t\t}\n\t}\n\t// 钱包解锁时,需要刷新,通知挖矿\n\tFlushTicket(policy.getAPI())\n}", "func (o BucketIamConfigurationUniformBucketLevelAccessPtrOutput) LockedTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketIamConfigurationUniformBucketLevelAccess) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.LockedTime\n\t}).(pulumi.StringPtrOutput)\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (dcr *ExchangeWallet) Locked() bool {\n\twalletInfo, err := dcr.node.WalletInfo(dcr.ctx)\n\tif err != nil {\n\t\tdcr.log.Errorf(\"walletinfo error: %v\", err)\n\t\treturn false\n\t}\n\treturn !walletInfo.Unlocked\n}", "func (m *DeviceEnrollmentWindowsHelloForBusinessConfiguration) GetUnlockWithBiometricsEnabled()(*bool) {\n val, err := m.GetBackingStore().Get(\"unlockWithBiometricsEnabled\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func (w *rpcWallet) LockUnspent(ctx context.Context, unlock bool, ops []*wire.OutPoint) error {\n\treturn translateRPCCancelErr(w.client().LockUnspent(ctx, unlock, ops))\n}", "func (ks *CSA) Unsafe_GetUnlockedPrivateKey(pubkey crypto.PublicKey) ([]byte, error) {\n\treturn ks.keys[pubkey.String()].Unsafe_GetPrivateKey()\n}", "func (o BucketIamConfigurationUniformBucketLevelAccessResponseOutput) LockedTime() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketIamConfigurationUniformBucketLevelAccessResponse) string { return v.LockedTime }).(pulumi.StringOutput)\n}", "func (cb *CircuitBreaker) Unblock() {\n\tcb.Lock()\n\tcb.blocked = false\n\tcb.Unlock()\n}", "func (_Onesplitaudit *OnesplitauditCaller) FLAGDISABLEWETH(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Onesplitaudit.contract.Call(opts, &out, \"FLAG_DISABLE_WETH\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func getWallet() walletStruct {\n\n\ts := \"START getWallet() - Gets the wallet\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\ts = \"END getWallet() - Gets the wallet\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\treturn wallet\n}", "func (transaction *TokenUpdateTransaction) GetFreezeKey() Key {\n\treturn transaction.freezeKey\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (prof *Profiles) Blocked() ([]BlockedUser, error) {\n\tbody, err := prof.insta.sendSimpleRequest(urlBlockedList)\n\tif err == nil {\n\t\tresp := blockedListResp{}\n\t\terr = json.Unmarshal(body, &resp)\n\t\treturn resp.BlockedList, err\n\t}\n\treturn nil, err\n}", "func GetActiveUniformBlockiv(program uint32, uniformBlockIndex uint32, pname uint32, params *int32) {\n\tsyscall.Syscall6(gpGetActiveUniformBlockiv, 4, uintptr(program), uintptr(uniformBlockIndex), uintptr(pname), uintptr(unsafe.Pointer(params)), 0, 0)\n}", "func (m *neighborEntryRWMutex) RUnlockBypass() {\n\tm.mu.RUnlock()\n}", "func GetBlockTime(slot int64, cfg *config.Config) (types.BlockTime, error) {\n\tlog.Println(\"Getting block time...\")\n\tvar result types.BlockTime\n\tops := types.HTTPOptions{\n\t\tEndpoint: cfg.Endpoints.RPCEndpoint,\n\t\tMethod: http.MethodPost,\n\t\tBody: types.Payload{Jsonrpc: \"2.0\", Method: \"getBlockTime\", ID: 1, Params: []interface{}{slot}},\n\t}\n\n\tresp, err := HitHTTPTarget(ops)\n\tif err != nil {\n\t\tlog.Printf(\"Error while getting block time: %v\", err)\n\t\treturn result, err\n\t}\n\n\terr = json.Unmarshal(resp.Body, &result)\n\tif err != nil {\n\t\tlog.Printf(\"Error while unmarshelling block time res: %v\", err)\n\t\treturn result, err\n\t}\n\treturn result, nil\n}", "func Unlock() {\n\t// TO DO\n}", "func (w *Wallet) holdUnlock() (heldUnlock, er.R) {\n\treq := make(chan heldUnlock)\n\tw.holdUnlockRequests <- req\n\thl, ok := <-req\n\tif !ok {\n\t\t// TODO(davec): This should be defined and exported from\n\t\t// waddrmgr.\n\t\treturn nil, waddrmgr.ErrLocked.New(\"address manager is locked\", nil)\n\t}\n\treturn hl, nil\n}", "func (tp *TXPool) GetUnverifiedTxs(txs []*types.Transaction,\n\theight uint32) *CheckBlkResult {\n\ttp.Lock()\n\tdefer tp.Unlock()\n\tres := &CheckBlkResult{\n\t\tVerifiedTxs: make([]*VerifyTxResult, 0, len(txs)),\n\t\tUnverifiedTxs: make([]*types.Transaction, 0),\n\t\tOldTxs: make([]*types.Transaction, 0),\n\t}\n\tfor _, tx := range txs {\n\t\ttxEntry := tp.txList[tx.Hash()]\n\t\tif txEntry == nil {\n\t\t\tres.UnverifiedTxs = append(res.UnverifiedTxs,\n\t\t\t\ttx)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !tp.compareTxHeight(txEntry, height) {\n\t\t\tdelete(tp.txList, tx.Hash())\n\t\t\tres.OldTxs = append(res.OldTxs, txEntry.Tx)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, v := range txEntry.Attrs {\n\t\t\tif v.Type == vt.Stateful {\n\t\t\t\tentry := &VerifyTxResult{\n\t\t\t\t\tTx: tx,\n\t\t\t\t\tHeight: v.Height,\n\t\t\t\t\tErrCode: v.ErrCode,\n\t\t\t\t}\n\t\t\t\tres.VerifiedTxs = append(res.VerifiedTxs,\n\t\t\t\t\tentry)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (p *Policy) getBlockedAccounts(ic *interop.Context, _ []stackitem.Item) stackitem.Item {\n\tba, err := p.GetBlockedAccountsInternal(ic.DAO)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ba.ToStackItem()\n}", "func (d *Dam) Unlock() {\n\td.freeze.Unlock()\n}", "func (m *ScheduleItem) GetIsPrivate()(*bool) {\n val, err := m.GetBackingStore().Get(\"isPrivate\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func (o *LocalDatabaseProvider) GetUserLockoutThreshold() int32 {\n\tif o == nil || o.UserLockoutThreshold == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.UserLockoutThreshold\n}", "func (c *Channel) Locked() *big.Int {\n\treturn c.OurState.AmountLocked()\n}", "func (m *Office365ServicesUserCounts) GetTeamsInactive()(*int64) {\n val, err := m.GetBackingStore().Get(\"teamsInactive\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int64)\n }\n return nil\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (_Constants *ConstantsCaller) WithdrawLockPeriod(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Constants.contract.Call(opts, &out, \"withdrawLockPeriod\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (p *PrivilegedProjectProvider) GetUnsecured(projectInternalName string, options *provider.ProjectGetOptions) (*kubermaticapiv1.Project, error) {\n\tif options == nil {\n\t\toptions = &provider.ProjectGetOptions{IncludeUninitialized: true}\n\t}\n\tproject := &kubermaticapiv1.Project{}\n\tif err := p.clientPrivileged.Get(context.Background(), ctrlruntimeclient.ObjectKey{Name: projectInternalName}, project); err != nil {\n\t\treturn nil, err\n\t}\n\tif !options.IncludeUninitialized && project.Status.Phase != kubermaticapiv1.ProjectActive {\n\t\treturn nil, kerrors.NewServiceUnavailable(\"Project is not initialized yet\")\n\t}\n\treturn project, nil\n}", "func (_TokensNetwork *TokensNetworkFilterer) FilterChannelUnlocked(opts *bind.FilterOpts, channel_identifier [][32]byte) (*TokensNetworkChannelUnlockedIterator, error) {\n\n\tvar channel_identifierRule []interface{}\n\tfor _, channel_identifierItem := range channel_identifier {\n\t\tchannel_identifierRule = append(channel_identifierRule, channel_identifierItem)\n\t}\n\n\tlogs, sub, err := _TokensNetwork.contract.FilterLogs(opts, \"ChannelUnlocked\", channel_identifierRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TokensNetworkChannelUnlockedIterator{contract: _TokensNetwork.contract, event: \"ChannelUnlocked\", logs: logs, sub: sub}, nil\n}", "func (p *BailServiceClient) UnfreezeBail(dealerId int64, amount float64, orderId int64) (r *Bail, err error) {\n\tif err = p.sendUnfreezeBail(dealerId, amount, orderId); err != nil {\n\t\treturn\n\t}\n\treturn p.recvUnfreezeBail()\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (m *Office365ServicesUserCounts) GetYammerInactive()(*int64) {\n val, err := m.GetBackingStore().Get(\"yammerInactive\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int64)\n }\n return nil\n}", "func (del Delegation) LockedUntil() hexutil.Uint64 {\n\t// get the lock\n\tlock := del.DelegationLock()\n\tif lock == nil {\n\t\treturn hexutil.Uint64(0)\n\t}\n\n\t// return the lock release time stamp\n\treturn lock.LockedUntil\n}" ]
[ "0.67690635", "0.5902726", "0.5877758", "0.5756858", "0.5283301", "0.5265267", "0.5147104", "0.5132386", "0.5092646", "0.50746304", "0.50555545", "0.50017166", "0.49906853", "0.49503067", "0.49447116", "0.49404284", "0.4913754", "0.49131387", "0.4903401", "0.4901039", "0.49005738", "0.489135", "0.48793608", "0.48700368", "0.48635647", "0.4853582", "0.4849924", "0.48494932", "0.4841779", "0.4829426", "0.48100948", "0.4793952", "0.47920567", "0.47825015", "0.476242", "0.4756044", "0.47538084", "0.47502637", "0.47366622", "0.47205278", "0.4717631", "0.47143462", "0.47109076", "0.47079387", "0.470761", "0.4705741", "0.47021186", "0.46997285", "0.4672197", "0.46687815", "0.46662334", "0.46560487", "0.4639467", "0.46383357", "0.46241945", "0.46235907", "0.4620516", "0.46190238", "0.46170768", "0.46047163", "0.45988044", "0.4592583", "0.45886755", "0.4586585", "0.4584408", "0.45799574", "0.45770323", "0.45700407", "0.45485908", "0.45452395", "0.45414785", "0.45386648", "0.45333552", "0.45295835", "0.4528283", "0.45195046", "0.45182505", "0.45161438", "0.44972518", "0.4489341", "0.44854432", "0.44826284", "0.4481232", "0.44788578", "0.44705737", "0.4468897", "0.446855", "0.44679388", "0.44637713", "0.44636708", "0.44631022", "0.445897", "0.44522637", "0.44473958", "0.44417134", "0.4437727", "0.44331262", "0.44103894", "0.44058967", "0.4404951" ]
0.8647829
0
GetVestedOnly implements the exported.ClawbackVestingAccountI interface. It returns the vesting schedule and blockTime. Like GetVestedCoins, but only for the vesting (in the clawback sense) component.
func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins { return ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix()) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (pva PeriodicVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tcoins := ReadSchedule(pva.StartTime, pva.EndTime, pva.VestingPeriods, pva.OriginalVesting, blockTime.Unix())\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (plva PermanentLockedAccount) GetVestedCoins(_ time.Time) sdk.Coins {\n\treturn nil\n}", "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (plva PermanentLockedAccount) GetVestingCoins(_ time.Time) sdk.Coins {\n\treturn plva.OriginalVesting\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (va ClawbackVestingAccount) GetUnlockedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.LockupPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (va ClawbackVestingAccount) GetVestingPeriods() Periods {\n\treturn va.VestingPeriods\n}", "func (pva PeriodicVestingAccount) GetVestingPeriods() Periods {\n\treturn pva.VestingPeriods\n}", "func (bva BaseVestingAccount) LockedCoinsFromVesting(vestingCoins sdk.Coins) sdk.Coins {\n\tlockedCoins := vestingCoins.Sub(vestingCoins.Min(bva.DelegatedVesting))\n\tif lockedCoins == nil {\n\t\treturn sdk.Coins{}\n\t}\n\treturn lockedCoins\n}", "func (sm *StateManager) GetFilVested(ctx context.Context, height abi.ChainEpoch, st *state.StateTree) (abi.TokenAmount, error) {\n\tvf := big.Zero()\n\tif height <= build.UpgradeIgnitionHeight {\n\t\tfor _, v := range sm.preIgnitionGenInfos.genesisMsigs {\n\t\t\tau := big.Sub(v.InitialBalance, v.AmountLocked(height))\n\t\t\tvf = big.Add(vf, au)\n\t\t}\n\t} else {\n\t\tfor _, v := range sm.postIgnitionGenInfos.genesisMsigs {\n\t\t\t// In the pre-ignition logic, we simply called AmountLocked(height), assuming startEpoch was 0.\n\t\t\t// The start epoch changed in the Ignition upgrade.\n\t\t\tau := big.Sub(v.InitialBalance, v.AmountLocked(height-v.StartEpoch))\n\t\t\tvf = big.Add(vf, au)\n\t\t}\n\t}\n\n\t// there should not be any such accounts in testnet (and also none in mainnet?)\n\t// continue to use preIgnitionGenInfos, nothing changed at the Ignition epoch\n\tfor _, v := range sm.preIgnitionGenInfos.genesisActors {\n\t\tact, err := st.GetActor(v.addr)\n\t\tif err != nil {\n\t\t\treturn big.Zero(), xerrors.Errorf(\"failed to get actor: %w\", err)\n\t\t}\n\n\t\tdiff := big.Sub(v.initBal, act.Balance)\n\t\tif diff.GreaterThan(big.Zero()) {\n\t\t\tvf = big.Add(vf, diff)\n\t\t}\n\t}\n\n\t// continue to use preIgnitionGenInfos, nothing changed at the Ignition epoch\n\tvf = big.Add(vf, sm.preIgnitionGenInfos.genesisPledge)\n\t// continue to use preIgnitionGenInfos, nothing changed at the Ignition epoch\n\tvf = big.Add(vf, sm.preIgnitionGenInfos.genesisMarketFunds)\n\n\treturn vf, nil\n}", "func (bva BaseVestingAccount) GetOriginalVesting() sdk.Coins {\n\treturn bva.OriginalVesting\n}", "func (_TokenVesting *TokenVestingCallerSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (o *AllocationList) GetInvested() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Invested\n}", "func (_TokenVesting *TokenVestingSession) VestedAmount(_token common.Address) (*big.Int, error) {\n\treturn _TokenVesting.Contract.VestedAmount(&_TokenVesting.CallOpts, _token)\n}", "func (bva BaseVestingAccount) GetDelegatedVesting() sdk.Coins {\n\treturn bva.DelegatedVesting\n}", "func (pva PeriodicVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn pva.BaseVestingAccount.LockedCoinsFromVesting(pva.GetVestingCoins(ctx.BlockTime()))\n}", "func (va ClawbackVestingAccount) Validate() error {\n\tif va.GetStartTime() >= va.GetEndTime() {\n\t\treturn errors.New(\"vesting start-time must be before end-time\")\n\t}\n\n\tlockupEnd := va.StartTime\n\tlockupCoins := sdk.NewCoins()\n\tfor _, p := range va.LockupPeriods {\n\t\tlockupEnd += p.Length\n\t\tlockupCoins = lockupCoins.Add(p.Amount...)\n\t}\n\tif lockupEnd > va.EndTime {\n\t\treturn errors.New(\"lockup schedule extends beyond account end time\")\n\t}\n\tif !coinEq(lockupCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in lockup periods\")\n\t}\n\n\tvestingEnd := va.StartTime\n\tvestingCoins := sdk.NewCoins()\n\tfor _, p := range va.VestingPeriods {\n\t\tvestingEnd += p.Length\n\t\tvestingCoins = vestingCoins.Add(p.Amount...)\n\t}\n\tif vestingEnd > va.EndTime {\n\t\treturn errors.New(\"vesting schedule exteds beyond account end time\")\n\t}\n\tif !coinEq(vestingCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in vesting periods\")\n\t}\n\n\treturn va.BaseVestingAccount.Validate()\n}", "func (_TokenVesting *TokenVestingCaller) VestedAmount(opts *bind.CallOpts, _token common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenVesting.contract.Call(opts, out, \"vestedAmount\", _token)\n\treturn *ret0, err\n}", "func (va ClawbackVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn va.BaseVestingAccount.LockedCoinsFromVesting(va.GetVestingCoins(ctx.BlockTime()))\n}", "func (vva ValidatorVestingAccount) GetFailedVestedCoins() sdk.Coins {\n\tvar failedVestedCoins sdk.Coins\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\tif !vva.VestingPeriodProgress[i].VestingSuccessful {\n\t\t\t\tfailedVestedCoins = failedVestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn failedVestedCoins\n}", "func (_TokenVesting *TokenVestingCallerSession) VestingInfo(arg0 common.Address) (struct {\n\tVestingBeneficiary common.Address\n\tReleasedSupply *big.Int\n\tStart *big.Int\n\tDuration *big.Int\n}, error) {\n\treturn _TokenVesting.Contract.VestingInfo(&_TokenVesting.CallOpts, arg0)\n}", "func (_Token *TokenCallerSession) GetStakeDeposit() (struct {\n\tAmount *big.Int\n\tStartDate *big.Int\n\tEndDate *big.Int\n\tStartCheckpointIndex *big.Int\n\tEndCheckpointIndex *big.Int\n}, error) {\n\treturn _Token.Contract.GetStakeDeposit(&_Token.CallOpts)\n}", "func (dva DelayedVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn dva.BaseVestingAccount.LockedCoinsFromVesting(dva.GetVestingCoins(ctx.BlockTime()))\n}", "func (vva ValidatorVestingAccount) SpendableCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.BaseVestingAccount.SpendableCoinsVestingAccount(vva.GetVestingCoins(blockTime))\n}", "func (_TokenVesting *TokenVestingSession) VestingInfo(arg0 common.Address) (struct {\n\tVestingBeneficiary common.Address\n\tReleasedSupply *big.Int\n\tStart *big.Int\n\tDuration *big.Int\n}, error) {\n\treturn _TokenVesting.Contract.VestingInfo(&_TokenVesting.CallOpts, arg0)\n}", "func (_Token *TokenSession) GetStakeDeposit() (struct {\n\tAmount *big.Int\n\tStartDate *big.Int\n\tEndDate *big.Int\n\tStartCheckpointIndex *big.Int\n\tEndCheckpointIndex *big.Int\n}, error) {\n\treturn _Token.Contract.GetStakeDeposit(&_Token.CallOpts)\n}", "func (a *adapter) GetInterestedEvents() ([]*pb.Interest, error) {\n\treturn []*pb.Interest{{EventType: pb.EventType_BLOCK}}, nil\n}", "func (va ClawbackVestingAccount) GetStartTime() int64 {\n\treturn va.StartTime\n}", "func (cva ContinuousVestingAccount) LockedCoins(ctx sdk.Context) sdk.Coins {\n\treturn cva.BaseVestingAccount.LockedCoinsFromVesting(cva.GetVestingCoins(ctx.BlockTime()))\n}", "func (va *ClawbackVestingAccount) computeClawback(clawbackTime int64) sdk.Coins {\n\t// Compute the truncated vesting schedule and amounts.\n\t// Work with the schedule as the primary data and recompute derived fields, e.g. OriginalVesting.\n\tvestTime := va.StartTime\n\ttotalVested := sdk.NewCoins()\n\ttotalUnvested := sdk.NewCoins()\n\tunvestedIdx := 0\n\tfor i, period := range va.VestingPeriods {\n\t\tvestTime += period.Length\n\t\t// tie in time goes to clawback\n\t\tif vestTime < clawbackTime {\n\t\t\ttotalVested = totalVested.Add(period.Amount...)\n\t\t\tunvestedIdx = i + 1\n\t\t} else {\n\t\t\ttotalUnvested = totalUnvested.Add(period.Amount...)\n\t\t}\n\t}\n\tlastVestTime := vestTime\n\tnewVestingPeriods := va.VestingPeriods[:unvestedIdx]\n\n\t// To cap the unlocking schedule to the new total vested, conjunct with a limiting schedule\n\tcapPeriods := []Period{\n\t\t{\n\t\t\tLength: 0,\n\t\t\tAmount: totalVested,\n\t\t},\n\t}\n\t_, lastLockTime, newLockupPeriods := ConjunctPeriods(va.StartTime, va.StartTime, va.LockupPeriods, capPeriods)\n\n\t// Now construct the new account state\n\tva.OriginalVesting = totalVested\n\tva.EndTime = max64(lastVestTime, lastLockTime)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\t// DelegatedVesting and DelegatedFree will be adjusted elsewhere\n\n\treturn totalUnvested\n}", "func (er *EventRelay) GetInterestedEvents() ([]*pb.Interest, error) {\n\tlogger.Infof(\"Returning InterestedEvents - Block & FilteredBlock.\\n\")\n\treturn []*pb.Interest{\n\t\t&pb.Interest{EventType: pb.EventType_BLOCK},\n\t\t&pb.Interest{EventType: pb.EventType_FILTEREDBLOCK},\n\t}, nil\n}", "func (pva PeriodicVestingAccount) GetStartTime() int64 {\n\treturn pva.StartTime\n}", "func (_Token *TokenCaller) GetStakeDeposit(opts *bind.CallOpts) (struct {\n\tAmount *big.Int\n\tStartDate *big.Int\n\tEndDate *big.Int\n\tStartCheckpointIndex *big.Int\n\tEndCheckpointIndex *big.Int\n}, error) {\n\tret := new(struct {\n\t\tAmount *big.Int\n\t\tStartDate *big.Int\n\t\tEndDate *big.Int\n\t\tStartCheckpointIndex *big.Int\n\t\tEndCheckpointIndex *big.Int\n\t})\n\tout := ret\n\terr := _Token.contract.Call(opts, out, \"getStakeDeposit\")\n\treturn *ret, err\n}", "func (_Cakevault *CakevaultCallerSession) LastHarvestedTime() (*big.Int, error) {\n\treturn _Cakevault.Contract.LastHarvestedTime(&_Cakevault.CallOpts)\n}", "func (_Cakevault *CakevaultSession) LastHarvestedTime() (*big.Int, error) {\n\treturn _Cakevault.Contract.LastHarvestedTime(&_Cakevault.CallOpts)\n}", "func (s *PublicSfcAPI) GetDowntime(ctx context.Context, stakerID hexutil.Uint) (map[string]interface{}, error) {\n\tblocks, period, err := s.b.GetDowntime(ctx, idx.StakerID(stakerID))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn map[string]interface{}{\n\t\t\"missedBlocks\": hexutil.Uint64(blocks),\n\t\t\"downtime\": hexutil.Uint64(period),\n\t}, nil\n}", "func LicensedAtGTE(v time.Time) predicate.Pet {\n\treturn predicate.Pet(sql.FieldGTE(FieldLicensedAt, v))\n}", "func (_Onesplitaudit *OnesplitauditCallerSession) FLAGDISABLEWETH() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLEWETH(&_Onesplitaudit.CallOpts)\n}", "func getWallet() walletStruct {\n\n\ts := \"START getWallet() - Gets the wallet\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\ts = \"END getWallet() - Gets the wallet\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\treturn wallet\n}", "func (_Univ2 *Univ2CallerSession) GetReserves() (struct {\n\tReserve0 *big.Int\n\tReserve1 *big.Int\n\tBlockTimestampLast uint32\n}, error) {\n\treturn _Univ2.Contract.GetReserves(&_Univ2.CallOpts)\n}", "func (o *AllocationList) GetInvestedOk() (*float64, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Invested, true\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (dva DelayedVestingAccount) GetStartTime() int64 {\n\treturn 0\n}", "func (o *AllocationList) SetInvested(v float64) {\n\to.Invested = v\n}", "func (cva ContinuousVestingAccount) GetStartTime() int64 {\n\treturn cva.StartTime\n}", "func NotInvoicedGTE(v float32) predicate.Order {\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldNotInvoiced), v))\n\t})\n}", "func (_TrialRulesAbstract *TrialRulesAbstractTransactor) GetWitness(opts *bind.TransactOpts, trialStatus uint8) (*types.Transaction, error) {\n\treturn _TrialRulesAbstract.contract.Transact(opts, \"getWitness\", trialStatus)\n}", "func (_Cakevault *CakevaultTransactor) InCaseTokensGetStuck(opts *bind.TransactOpts, _token common.Address) (*types.Transaction, error) {\n\treturn _Cakevault.contract.Transact(opts, \"inCaseTokensGetStuck\", _token)\n}", "func (_TokenVesting *TokenVestingCaller) VestingInfo(opts *bind.CallOpts, arg0 common.Address) (struct {\n\tVestingBeneficiary common.Address\n\tReleasedSupply *big.Int\n\tStart *big.Int\n\tDuration *big.Int\n}, error) {\n\tret := new(struct {\n\t\tVestingBeneficiary common.Address\n\t\tReleasedSupply *big.Int\n\t\tStart *big.Int\n\t\tDuration *big.Int\n\t})\n\tout := ret\n\terr := _TokenVesting.contract.Call(opts, out, \"vestingInfo\", arg0)\n\treturn *ret, err\n}", "func (_Onesplitaudit *OnesplitauditSession) FLAGDISABLEWETH() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLEWETH(&_Onesplitaudit.CallOpts)\n}", "func (_Cakevault *CakevaultCaller) LastHarvestedTime(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"lastHarvestedTime\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (c Cart) GetVoucherSavings() domain.Price {\n\tprice := domain.Price{}\n\tvar err error\n\n\tfor _, item := range c.Totalitems {\n\t\tif item.Type == TotalsTypeVoucher {\n\t\t\tprice, err = price.Add(item.Price)\n\t\t\tif err != nil {\n\t\t\t\treturn price\n\t\t\t}\n\t\t}\n\t}\n\n\tif price.IsNegative() {\n\t\treturn domain.Price{}\n\t}\n\n\treturn price\n}", "func (pva PeriodicVestingAccount) Validate() error {\n\tif pva.GetStartTime() >= pva.GetEndTime() {\n\t\treturn errors.New(\"vesting start-time cannot be before end-time\")\n\t}\n\tendTime := pva.StartTime\n\toriginalVesting := sdk.NewCoins()\n\tfor _, p := range pva.VestingPeriods {\n\t\tendTime += p.Length\n\t\toriginalVesting = originalVesting.Add(p.Amount...)\n\t}\n\tif endTime != pva.EndTime {\n\t\treturn errors.New(\"vesting end time does not match length of all vesting periods\")\n\t}\n\tif !originalVesting.IsEqual(pva.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in vesting periods\")\n\t}\n\n\treturn pva.BaseVestingAccount.Validate()\n}", "func (m *Vulnerability) GetActiveExploitsObserved()(*bool) {\n val, err := m.GetBackingStore().Get(\"activeExploitsObserved\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}", "func (plva PermanentLockedAccount) LockedCoins(_ sdk.Context) sdk.Coins {\n\treturn plva.BaseVestingAccount.LockedCoinsFromVesting(plva.OriginalVesting)\n}", "func (_Contracts *ContractsCaller) GetEligibleVoters(opts *bind.CallOpts, _proposal *big.Int, _voterAddr common.Address) (struct {\n\tVoterId *big.Int\n\tVoterAddr common.Address\n\tPositionId *big.Int\n\tIsVerified bool\n\tIsVoted bool\n}, error) {\n\tret := new(struct {\n\t\tVoterId *big.Int\n\t\tVoterAddr common.Address\n\t\tPositionId *big.Int\n\t\tIsVerified bool\n\t\tIsVoted bool\n\t})\n\tout := ret\n\terr := _Contracts.contract.Call(opts, out, \"getEligibleVoters\", _proposal, _voterAddr)\n\treturn *ret, err\n}", "func (_Contracts *ContractsCallerSession) GetEligibleVoters(_proposal *big.Int, _voterAddr common.Address) (struct {\n\tVoterId *big.Int\n\tVoterAddr common.Address\n\tPositionId *big.Int\n\tIsVerified bool\n\tIsVoted bool\n}, error) {\n\treturn _Contracts.Contract.GetEligibleVoters(&_Contracts.CallOpts, _proposal, _voterAddr)\n}", "func (_Onesplitaudit *OnesplitauditCallerSession) FLAGDISABLEKYBER() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLEKYBER(&_Onesplitaudit.CallOpts)\n}", "func (t *TezTracker) GetStakingRatio() (float64, error) {\n\tlockedBalanceEstimate, err := t.getLockedBalance()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tar := t.repoProvider.GetAccount()\n\tliquidBalance, err := ar.TotalBalance()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tbr := t.repoProvider.GetBaker()\n\tstakedBalance, err := br.TotalStakingBalance()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tsupply := liquidBalance + lockedBalanceEstimate\n\tif supply == 0 {\n\t\treturn 0, nil\n\t}\n\n\tlastBlock, err := t.repoProvider.GetBlock().Last()\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\n\tbakingRewards, err := br.TotalBakingRewards(\"\", lastBlock.MetaCycle-PreservedCycles, lastBlock.MetaCycle)\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\n\tendorsementRewards, err := br.TotalEndorsementRewards(\"\", lastBlock.MetaCycle-PreservedCycles, lastBlock.MetaCycle)\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\n\tstakedBalance = stakedBalance - bakingRewards - endorsementRewards\n\tratio := float64(stakedBalance) / float64(supply)\n\n\treturn ratio, nil\n}", "func (c *TestClient) GetGuestAttributes(project, zone, name, queryPath, variableKey string) (*compute.GuestAttributes, error) {\n\tif c.GetGuestAttributesFn != nil {\n\t\treturn c.GetGuestAttributesFn(project, zone, name, queryPath, variableKey)\n\t}\n\treturn c.client.GetGuestAttributes(project, zone, name, queryPath, variableKey)\n}", "func (_Cakevault *CakevaultSession) Harvest() (*types.Transaction, error) {\n\treturn _Cakevault.Contract.Harvest(&_Cakevault.TransactOpts)\n}", "func (_Cakevault *CakevaultTransactorSession) Harvest() (*types.Transaction, error) {\n\treturn _Cakevault.Contract.Harvest(&_Cakevault.TransactOpts)\n}", "func (r Virtual_ReservedCapacityGroup_Instance) GetGuest() (resp datatypes.Virtual_Guest, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_ReservedCapacityGroup_Instance\", \"getGuest\", nil, &r.Options, &resp)\n\treturn\n}", "func (_Distributor *DistributorCaller) GetAndUpdateEarnedBountyAmountReadOnly(opts *bind.CallOpts, validatorId *big.Int) error {\n\ttype Bounty struct {\n\t\tearned *big.Int\n\t\tendMonth *big.Int\n\t}\n\tvar bounty Bounty\n\terr := _Distributor.contract.Call(opts, &bounty, \"getAndUpdateEarnedBountyAmount\", validatorId)\n\treturn err\n}", "func (_Onesplitaudit *OnesplitauditSession) FLAGDISABLEKYBER() (*big.Int, error) {\n\treturn _Onesplitaudit.Contract.FLAGDISABLEKYBER(&_Onesplitaudit.CallOpts)\n}", "func harvest(ctx iscp.Sandbox) (dict.Dict, error) {\n\ta := assert.NewAssert(ctx.Log())\n\ta.RequireChainOwner(ctx, \"harvest\")\n\n\tstate := ctx.State()\n\tmustCheckLedger(state, \"accounts.withdraw.begin\")\n\tdefer mustCheckLedger(state, \"accounts.withdraw.exit\")\n\n\tpar := kvdecoder.New(ctx.Params(), ctx.Log())\n\t// if ParamWithdrawAmount > 0, take it as exact amount to withdraw\n\t// otherwise assume harvest all\n\tamount, err := par.GetUint64(ParamWithdrawAmount)\n\tharvestAll := true\n\tif err == nil && amount > 0 {\n\t\tharvestAll = false\n\t}\n\t// if dummyColor not specified and amount is specified, default is harvest specified amount of iotas\n\tcol := par.MustGetColor(ParamWithdrawColor, colored.IOTA)\n\n\tsourceAccount := commonaccount.Get(ctx.ChainID())\n\tbals, ok := GetAccountBalances(state, sourceAccount)\n\tif !ok {\n\t\t// empty balance, nothing to withdraw\n\t\treturn nil, nil\n\t}\n\ttokensToSend := bals\n\tif !harvestAll {\n\t\tbalCol := bals[col]\n\t\ta.Require(balCol >= amount, \"accounts.harvest.error: not enough tokens\")\n\t\ttokensToSend = colored.NewBalancesForColor(col, amount)\n\t}\n\ta.Require(MoveBetweenAccounts(state, sourceAccount, ctx.Caller(), tokensToSend),\n\t\t\"accounts.harvest.inconsistency. failed to move tokens to owner's account\")\n\treturn nil, nil\n}", "func GetBlockTime(chain uint64) uint64 {\n\tvar pStat BaseInfo\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\treturn pStat.Time\n}", "func (_Univ2 *Univ2Session) GetReserves() (struct {\n\tReserve0 *big.Int\n\tReserve1 *big.Int\n\tBlockTimestampLast uint32\n}, error) {\n\treturn _Univ2.Contract.GetReserves(&_Univ2.CallOpts)\n}", "func (p *ClockPolicy) Victim() CacheKey {\n\tvar victimKey CacheKey\n\tvar nodeItem *ClockItem\n\tfor {\n\t\tcurrentNode := (*p.clockHand)\n\t\tnodeItem = currentNode.Value.(*ClockItem)\n\t\tif nodeItem.bit {\n\t\t\tnodeItem.bit = false\n\t\t\tcurrentNode.Value = nodeItem\n\t\t\tp.clockHand = currentNode.Next()\n\t\t} else {\n\t\t\tvictimKey = nodeItem.key\n\t\t\tp.list.Move(p.clockHand.Prev())\n\t\t\tp.clockHand = nil\n\t\t\tp.list.Remove(&currentNode)\n\t\t\tdelete(p.keyNode, victimKey)\n\t\t\treturn victimKey\n\t\t}\n\t}\n}", "func (a *adapter) GetInterestedEvents() ([]*pb.Interest, error) {\n\tif a.chaincodeID != \"\" {\n\t\treturn []*pb.Interest{\n\t\t\t{EventType: pb.EventType_BLOCK},\n\t\t\t{EventType: pb.EventType_REJECTION},\n\t\t\t{EventType: pb.EventType_CHAINCODE,\n\t\t\t\tRegInfo: &pb.Interest_ChaincodeRegInfo{\n\t\t\t\t\tChaincodeRegInfo: &pb.ChaincodeReg{\n\t\t\t\t\t\tChaincodeID: a.chaincodeID,\n\t\t\t\t\t\tEventName: \"\"}}}}, nil\n\t}\n\treturn []*pb.Interest{{EventType: pb.EventType_BLOCK}, {EventType: pb.EventType_REJECTION}}, nil\n}", "func (c *PartorderClient) Get(ctx context.Context, id int) (*Partorder, error) {\n\treturn c.Query().Where(partorder.ID(id)).Only(ctx)\n}", "func (r Virtual_Guest) GetActiveTransaction() (resp datatypes.Provisioning_Version1_Transaction, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getActiveTransaction\", nil, &r.Options, &resp)\n\treturn\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateLockedAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateLockedAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (_TrialRulesAbstract *TrialRulesAbstractTransactorSession) GetWitness(trialStatus uint8) (*types.Transaction, error) {\n\treturn _TrialRulesAbstract.Contract.GetWitness(&_TrialRulesAbstract.TransactOpts, trialStatus)\n}", "func (o *Drive) GetSeat(ctx context.Context) (seat string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceDrive, \"Seat\").Store(&seat)\n\treturn\n}", "func (_Cakevault *CakevaultTransactor) Harvest(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Cakevault.contract.Transact(opts, \"harvest\")\n}", "func (g *Graph) FindEligibleCritical(difficulty byte) *Transaction {\n\tvar pending []*sortBySeedTX\n\tvar critical *Transaction\n\n\tg.Lock()\n\n\tg.seedIndex.Ascend(func(i btree.Item) bool {\n\t\ttx := i.(*sortBySeedTX)\n\n\t\tif tx.Depth <= g.rootDepth {\n\t\t\tpending = append(pending, tx)\n\t\t\treturn true\n\t\t}\n\n\t\tif !(*Transaction)(tx).IsCritical(difficulty) {\n\t\t\tpending = append(pending, tx)\n\t\t\treturn true\n\t\t}\n\n\t\tcritical = (*Transaction)(tx)\n\n\t\treturn false\n\t})\n\n\tfor _, i := range pending {\n\t\tg.seedIndex.Delete(i)\n\t}\n\n\tg.Unlock()\n\n\treturn critical\n}", "func (_Crowdsale *CrowdsaleCallerSession) SoftCapEth() (*big.Int, error) {\n\treturn _Crowdsale.Contract.SoftCapEth(&_Crowdsale.CallOpts)\n}", "func GetGuest(c *gin.Context) *group.Guest {\n\treturn c.MustGet(\"guest\").(*group.Guest)\n}", "func (r Virtual_Guest) GetBlockCancelBecauseDisconnectedFlag() (resp bool, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getBlockCancelBecauseDisconnectedFlag\", nil, &r.Options, &resp)\n\treturn\n}", "func (x *ValidatorParticipation) GetEligibleEther() uint64 {\n\tif x != nil {\n\t\treturn x.EligibleEther\n\t}\n\treturn 0\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateLockedAmount(opts *bind.TransactOpts, wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateLockedAmount\", wallet)\n}", "func (_BaseContentSpace *BaseContentSpaceFilterer) FilterGetAccessWallet(opts *bind.FilterOpts) (*BaseContentSpaceGetAccessWalletIterator, error) {\n\n\tlogs, sub, err := _BaseContentSpace.contract.FilterLogs(opts, \"GetAccessWallet\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BaseContentSpaceGetAccessWalletIterator{contract: _BaseContentSpace.contract, event: \"GetAccessWallet\", logs: logs, sub: sub}, nil\n}", "func (c *Client) RenterInactiveContractsGet() (rc api.RenterContracts, err error) {\n\tquery := fmt.Sprintf(\"?inactive=%v\", true)\n\terr = c.get(\"/renter/contracts\"+query, &rc)\n\treturn\n}", "func (_IUniswapV2Pair *IUniswapV2PairCallerSession) GetReserves() (struct {\r\n\tReserve0 *big.Int\r\n\tReserve1 *big.Int\r\n\tBlockTimestampLast uint32\r\n}, error) {\r\n\treturn _IUniswapV2Pair.Contract.GetReserves(&_IUniswapV2Pair.CallOpts)\r\n}", "func getVolunteers(c *gin.Context) {\n\tvar vols []Volunteer\n\t//Read volunteers from database\n\tif err := db.Find(&vols).Error; err != nil {\n\t\tcreateNotFoundResponse(c)\n\t\treturn\n\t}\n\n\t//Authorization if user is reporter\n\tif !reporterAuth(c) {\n\t\treturn\n\t}\n\tc.JSON(200, vols)\n}", "func (w *Wallet) Balance() Shivcoin {\n\treturn w.balance\n}", "func (_SingleAuto *SingleAutoTransactor) InCaseTokensGetStuck(opts *bind.TransactOpts, _token common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _SingleAuto.contract.Transact(opts, \"inCaseTokensGetStuck\", _token, _amount)\n}", "func (m MarketDataSnapshotFullRefresh) GetTotalVolumeTraded() (v decimal.Decimal, err quickfix.MessageRejectError) {\n\tvar f field.TotalVolumeTradedField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func GetBlockTime(slot int64, cfg *config.Config) (types.BlockTime, error) {\n\tlog.Println(\"Getting block time...\")\n\tvar result types.BlockTime\n\tops := types.HTTPOptions{\n\t\tEndpoint: cfg.Endpoints.RPCEndpoint,\n\t\tMethod: http.MethodPost,\n\t\tBody: types.Payload{Jsonrpc: \"2.0\", Method: \"getBlockTime\", ID: 1, Params: []interface{}{slot}},\n\t}\n\n\tresp, err := HitHTTPTarget(ops)\n\tif err != nil {\n\t\tlog.Printf(\"Error while getting block time: %v\", err)\n\t\treturn result, err\n\t}\n\n\terr = json.Unmarshal(resp.Body, &result)\n\tif err != nil {\n\t\tlog.Printf(\"Error while unmarshelling block time res: %v\", err)\n\t\treturn result, err\n\t}\n\treturn result, nil\n}", "func (c *Channel) Locked() *big.Int {\n\treturn c.OurState.AmountLocked()\n}", "func (_Crowdsale *CrowdsaleSession) SoftCapEth() (*big.Int, error) {\n\treturn _Crowdsale.Contract.SoftCapEth(&_Crowdsale.CallOpts)\n}", "func GoVet() error { return mageextras.GoVetShadow() }" ]
[ "0.67785037", "0.67503226", "0.66144603", "0.6596947", "0.65359217", "0.6487381", "0.64839846", "0.64474326", "0.64271235", "0.64212775", "0.6202558", "0.61998135", "0.6146275", "0.5791093", "0.52322394", "0.50997275", "0.5037106", "0.5030548", "0.49749142", "0.49297792", "0.4850394", "0.4826826", "0.48186716", "0.4778215", "0.47771907", "0.47614315", "0.47485176", "0.45306152", "0.45206457", "0.45144087", "0.45083815", "0.44658473", "0.44457582", "0.44181493", "0.44095033", "0.4406303", "0.42371973", "0.42295703", "0.42082724", "0.41976905", "0.4174322", "0.41733423", "0.41671607", "0.4157489", "0.4156242", "0.41466704", "0.41441852", "0.4143005", "0.41401413", "0.4124294", "0.4120631", "0.4119975", "0.41163003", "0.4110513", "0.41049707", "0.40868425", "0.4079489", "0.40732512", "0.4067565", "0.4059058", "0.40540963", "0.4053563", "0.4038872", "0.4031694", "0.4011384", "0.39803436", "0.3961656", "0.3954626", "0.39533064", "0.39491567", "0.3946973", "0.39447957", "0.39288107", "0.39186966", "0.39009076", "0.389847", "0.38824442", "0.38725668", "0.38693336", "0.3852837", "0.38506177", "0.38494286", "0.384712", "0.38459203", "0.38451993", "0.38430762", "0.38424253", "0.3837632", "0.38371766", "0.3835657", "0.38352433", "0.38344082", "0.38268152", "0.38246965", "0.38203377", "0.3818424", "0.38151017", "0.38134283", "0.38077626", "0.38063157" ]
0.8709211
0
computeClawback removes all future vesting events from the account, returns the total sum of these events. When removing the future vesting events, the lockup schedule will also have to be capped to keep the total sums the same. (But future unlocking events might be preserved if they unlock currently vested coins.) If the amount returned is zero, then the returned account should be unchanged. Does not adjust DelegatedVesting
func (va *ClawbackVestingAccount) computeClawback(clawbackTime int64) sdk.Coins { // Compute the truncated vesting schedule and amounts. // Work with the schedule as the primary data and recompute derived fields, e.g. OriginalVesting. vestTime := va.StartTime totalVested := sdk.NewCoins() totalUnvested := sdk.NewCoins() unvestedIdx := 0 for i, period := range va.VestingPeriods { vestTime += period.Length // tie in time goes to clawback if vestTime < clawbackTime { totalVested = totalVested.Add(period.Amount...) unvestedIdx = i + 1 } else { totalUnvested = totalUnvested.Add(period.Amount...) } } lastVestTime := vestTime newVestingPeriods := va.VestingPeriods[:unvestedIdx] // To cap the unlocking schedule to the new total vested, conjunct with a limiting schedule capPeriods := []Period{ { Length: 0, Amount: totalVested, }, } _, lastLockTime, newLockupPeriods := ConjunctPeriods(va.StartTime, va.StartTime, va.LockupPeriods, capPeriods) // Now construct the new account state va.OriginalVesting = totalVested va.EndTime = max64(lastVestTime, lastLockTime) va.LockupPeriods = newLockupPeriods va.VestingPeriods = newVestingPeriods // DelegatedVesting and DelegatedFree will be adjusted elsewhere return totalUnvested }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (va *ClawbackVestingAccount) clawback(ctx sdk.Context, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) error {\n\t// Compute the clawback based on the account state only, and update account\n\ttoClawBack := va.computeClawback(ctx.BlockTime().Unix())\n\tif toClawBack.IsZero() {\n\t\treturn nil\n\t}\n\taddr := va.GetAddress()\n\tbondDenom := sk.BondDenom(ctx)\n\n\t// Compute the clawback based on bank balance and delegation, and update account\n\tencumbered := va.GetVestingCoins(ctx.BlockTime())\n\tbondedAmt := sk.GetDelegatorBonded(ctx, addr)\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, addr)\n\tbonded := sdk.NewCoins(sdk.NewCoin(bondDenom, bondedAmt))\n\tunbonding := sdk.NewCoins(sdk.NewCoin(bondDenom, unbondingAmt))\n\tunbonded := bk.GetAllBalances(ctx, addr)\n\ttoClawBack = va.updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded)\n\n\t// Write now now so that the bank module sees unvested tokens are unlocked.\n\t// Note that all store writes are aborted if there is a panic, so there is\n\t// no danger in writing incomplete results.\n\tak.SetAccount(ctx, va)\n\n\t// Now that future vesting events (and associated lockup) are removed,\n\t// the balance of the account is unlocked and can be freely transferred.\n\tspendable := bk.SpendableCoins(ctx, addr)\n\ttoXfer := coinsMin(toClawBack, spendable)\n\terr := bk.SendCoins(ctx, addr, dest, toXfer)\n\tif err != nil {\n\t\treturn err // shouldn't happen, given spendable check\n\t}\n\ttoClawBack = toClawBack.Sub(toXfer)\n\n\t// We need to traverse the staking data structures to update the\n\t// vesting account bookkeeping, and to recover more funds if necessary.\n\t// Staking is the only way unvested tokens should be missing from the bank balance.\n\n\t// If we need more, transfer UnbondingDelegations.\n\twant := toClawBack.AmountOf(bondDenom)\n\tunbondings := sk.GetUnbondingDelegations(ctx, addr, math.MaxUint16)\n\tfor _, unbonding := range unbondings {\n\t\tvalAddr, err := sdk.ValAddressFromBech32(unbonding.ValidatorAddress)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttransferred := sk.TransferUnbonding(ctx, addr, dest, valAddr, want)\n\t\twant = want.Sub(transferred)\n\t\tif !want.IsPositive() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If we need more, transfer Delegations.\n\tif want.IsPositive() {\n\t\tdelegations := sk.GetDelegatorDelegations(ctx, addr, math.MaxUint16)\n\t\tfor _, delegation := range delegations {\n\t\t\tvalidatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // shouldn't happen\n\t\t\t}\n\t\t\tvalidator, found := sk.GetValidator(ctx, validatorAddr)\n\t\t\tif !found {\n\t\t\t\t// validator has been removed\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twantShares, err := validator.SharesFromTokensTruncated(want)\n\t\t\tif err != nil {\n\t\t\t\t// validator has no tokens\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttransferredShares := sk.TransferDelegation(ctx, addr, dest, delegation.GetValidatorAddr(), wantShares)\n\t\t\t// to be conservative in what we're clawing back, round transferred shares up\n\t\t\ttransferred := validator.TokensFromSharesRoundUp(transferredShares).RoundInt()\n\t\t\twant = want.Sub(transferred)\n\t\t\tif !want.IsPositive() {\n\t\t\t\t// Could be slightly negative, due to rounding?\n\t\t\t\t// Don't think so, due to the precautions above.\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we've transferred everything and still haven't transferred the desired clawback amount,\n\t// then the account must have most some unvested tokens from slashing.\n\treturn nil\n}", "func NewClawbackVestingAccount(baseAcc *authtypes.BaseAccount, funder sdk.AccAddress, originalVesting sdk.Coins, startTime int64, lockupPeriods, vestingPeriods Periods) *ClawbackVestingAccount {\n\t// copy and align schedules to avoid mutating inputs\n\tlp := make(Periods, len(lockupPeriods))\n\tcopy(lp, lockupPeriods)\n\tvp := make(Periods, len(vestingPeriods))\n\tcopy(vp, vestingPeriods)\n\t_, endTime := AlignSchedules(startTime, startTime, lp, vp)\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ClawbackVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tFunderAddress: funder.String(),\n\t\tStartTime: startTime,\n\t\tLockupPeriods: lp,\n\t\tVestingPeriods: vp,\n\t}\n}", "func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins {\n\tdelegated := bonded.Add(unbonding...)\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated))\n\ttotal := delegated.Add(unbonded...)\n\ttoClawBack = coinsMin(toClawBack, total) // might have been slashed\n\tnewDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...)\n\tva.DelegatedVesting = coinsMin(encumbered, newDelegated)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n\treturn toClawBack\n}", "func (t *TDigest) Decay(decayValue, decayLimit float64) {\n\tt.processIt(false) // don't update cumulative as we'll do that below inline\n\tvar weight float64\n\tvar remove []int\n\tt.cumulative = t.cumulative[:0]\n\tprev := 0.0\n\n\tmin := t.processed[0].Mean\n\tmax := t.processed[len(t.processed)-1].Mean\n\n\tfor i := range t.processed {\n\t\tc := &t.processed[i]\n\t\tc.Weight *= decayValue\n\t\tif c.Weight < decayLimit {\n\t\t\tremove = append(remove, i)\n\t\t} else {\n\t\t\tweight += c.Weight\n\t\t\t// do cumulative work inline\n\t\t\tt.cumulative = append(t.cumulative, prev+c.Weight/2.0)\n\t\t\tprev += c.Weight\n\t\t}\n\t}\n\tt.cumulative = append(t.cumulative, prev)\n\n\tif len(remove) > 0 {\n\t\tfor i, c := range remove {\n\t\t\tcalculated := c - i\n\t\t\tt.processed = append(t.processed[:calculated], t.processed[calculated+1:]...)\n\t\t}\n\t\tif len(t.processed) > 0 {\n\t\t\t// only set these if we've removed those centroids\n\t\t\tif min != t.processed[0].Mean {\n\t\t\t\tt.min = t.processed[0].Mean\n\t\t\t}\n\t\t\tif max != t.processed[len(t.processed)-1].Mean {\n\t\t\t\tt.max = t.processed[len(t.processed)-1].Mean\n\t\t\t}\n\t\t} else {\n\t\t\tt.min = math.MaxFloat64\n\t\t\tt.max = -math.MaxFloat64\n\t\t}\n\t}\n\n\tt.processedWeight = weight\n}", "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func (va ClawbackVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\t// It's likely that one or the other schedule will be nearly trivial,\n\t// so there should be little overhead in recomputing the conjunction each time.\n\tcoins := coinsMin(va.GetUnlockedOnly(blockTime), va.GetVestedOnly(blockTime))\n\tif coins.IsZero() {\n\t\treturn nil\n\t}\n\treturn coins\n}", "func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\n}", "func (va ClawbackVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn va.OriginalVesting.Sub(va.GetVestedCoins(blockTime))\n}", "func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error) {\n var err error\n var balance float64\n delegationsForCycle, _ := GetDelegatedContractsForCycle(cycle, delegateAddr)\n\n for index, delegation := range delegatedContracts{\n balance, err = GetAccountBalanceAtSnapshot(delegation.Address, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycle \" + strconv.Itoa(cycle) + \":GetAccountBalanceAtSnapshot(tezosAddr string, cycle int) failed: \" + err.Error())\n }\n if (isDelegationInGroup(delegatedContracts[index].Address, delegationsForCycle, delegatedContracts[index].Delegate)){\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:balance})\n } else{\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:0})\n }\n //fmt.Println(delegatedContracts[index].Contracts)\n }\n\n delegatedContracts, err = CalculatePercentageSharesForCycle(delegatedContracts, cycle, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) failed: \" + err.Error())\n }\n return delegatedContracts, nil\n}", "func TotalStaked(ctx contract.StaticContext, bootstrapNodes map[string]bool) (*types.BigUInt, error) {\n\tvalidatorStats, err := getValidatorStatistics(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstatistics := map[string]*ValidatorStatistic{}\n\tfor _, statistic := range validatorStats {\n\t\tnodeAddr := loom.UnmarshalAddressPB(statistic.Address)\n\t\tif _, ok := bootstrapNodes[strings.ToLower(nodeAddr.String())]; !ok {\n\t\t\tstatistics[statistic.Address.String()] = statistic\n\t\t}\n\t}\n\n\tcandidateList := map[string]bool{}\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, candidate := range candidates {\n\t\tcandidateAddr := loom.UnmarshalAddressPB(candidate.Address)\n\t\tif _, ok := bootstrapNodes[strings.ToLower(candidateAddr.String())]; !ok {\n\t\t\tcandidateList[candidate.Address.String()] = true\n\t\t}\n\t}\n\n\tdelegationList, err := loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttotalStaked := &types.BigUInt{Value: *loom.NewBigUIntFromInt(0)}\n\t// Sum all delegations\n\tfor _, d := range delegationList {\n\t\tif _, ok := candidateList[d.Validator.String()]; ok {\n\t\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\tif err == contract.ErrNotFound {\n\t\t\t\tcontinue\n\t\t\t} else if err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\ttotalStaked.Value.Add(&totalStaked.Value, &delegation.Amount.Value)\n\t\t}\n\t}\n\t// Sum all whitelist amounts of validators except bootstrap validators\n\tfor _, candidate := range candidates {\n\t\tif statistic, ok := statistics[candidate.Address.String()]; ok {\n\t\t\tif statistic.WhitelistAmount != nil {\n\t\t\t\ttotalStaked.Value.Add(&totalStaked.Value, &statistic.WhitelistAmount.Value)\n\t\t\t}\n\t\t}\n\t}\n\treturn totalStaked, nil\n}", "func (_Cakevault *CakevaultCaller) CalculateTotalPendingCakeRewards(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"calculateTotalPendingCakeRewards\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (va ClawbackVestingAccount) Validate() error {\n\tif va.GetStartTime() >= va.GetEndTime() {\n\t\treturn errors.New(\"vesting start-time must be before end-time\")\n\t}\n\n\tlockupEnd := va.StartTime\n\tlockupCoins := sdk.NewCoins()\n\tfor _, p := range va.LockupPeriods {\n\t\tlockupEnd += p.Length\n\t\tlockupCoins = lockupCoins.Add(p.Amount...)\n\t}\n\tif lockupEnd > va.EndTime {\n\t\treturn errors.New(\"lockup schedule extends beyond account end time\")\n\t}\n\tif !coinEq(lockupCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in lockup periods\")\n\t}\n\n\tvestingEnd := va.StartTime\n\tvestingCoins := sdk.NewCoins()\n\tfor _, p := range va.VestingPeriods {\n\t\tvestingEnd += p.Length\n\t\tvestingCoins = vestingCoins.Add(p.Amount...)\n\t}\n\tif vestingEnd > va.EndTime {\n\t\treturn errors.New(\"vesting schedule exteds beyond account end time\")\n\t}\n\tif !coinEq(vestingCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in vesting periods\")\n\t}\n\n\treturn va.BaseVestingAccount.Validate()\n}", "func (_Cakevault *CakevaultSession) CalculateTotalPendingCakeRewards() (*big.Int, error) {\n\treturn _Cakevault.Contract.CalculateTotalPendingCakeRewards(&_Cakevault.CallOpts)\n}", "func (_Cakevault *CakevaultCallerSession) CalculateTotalPendingCakeRewards() (*big.Int, error) {\n\treturn _Cakevault.Contract.CalculateTotalPendingCakeRewards(&_Cakevault.CallOpts)\n}", "func (sch *Scheduler) CalClusterBalance(podUsed *[PHYNUM][DIMENSION]float64, podReq []PodRequest) {\n\t//cal the pod sum and used rate\n\tpodLen := len(podReq)\n\tvar podNum [PHYNUM]int\n\tvar podSum int\n\tfor i := 0; i < podLen; i++ {\n\t\tif podReq[i].nodeName != -1 {\n\t\t\tpodSum++\n\t\t\tpodNum[podReq[i].nodeName]++\n\t\t}\n\t}\n\n\tvar podIdle [PHYNUM]float64\n\tvar resIdle [PHYNUM][DIMENSION]float64\n\tvar podVal float64\n\tvar resVal [DIMENSION]float64 // cal the sum and mean value\n\n\tfor i := 0; i < PHYNUM; i++ {\n\t\tpodIdle[i] = 1.0 - (float64)(podNum[i])/(float64)(podSum)\n\t\tpodVal = podVal + podIdle[i]\n\t\tfor j := 0; j < DIMENSION; j++ {\n\t\t\tresIdle[i][j] = (sch.reTotal[j] - podUsed[i][j]) / sch.reTotal[j]\n\t\t\tresVal[j] = resVal[j] + resIdle[i][j]\n\t\t}\n\t}\n\t// cal the balance value\n\tpodMean := podVal / (float64)(podSum)\n\tvar resMean [DIMENSION]float64\n\tfor j := 0; j < DIMENSION; j++ {\n\t\tresMean[j] = resVal[j] / (float64)(PHYNUM)\n\t}\n\tvar baIdle float64\n\tfor i := 0; i < PHYNUM; i++ {\n\t\tfor j := 0; j < DIMENSION; j++ {\n\t\t\tbaIdle = baIdle + math.Pow((resIdle[i][j]-resMean[j]), 2)\n\t\t}\n\t\tbaIdle = baIdle + math.Pow((podIdle[i]-podMean), 2)\n\t}\n\tbaIdle = math.Sqrt(baIdle)\n\tfmt.Printf(\"The balance value is %.3f \\n\", baIdle)\n}", "func CalculateAllTotalPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n for index, delegatedContract := range delegatedContracts{\n delegatedContracts[index] = CalculateTotalPayout(delegatedContract)\n }\n\n return delegatedContracts\n}", "func getBalanceTotal(recordCollection []record) (totalBalance time.Duration) {\n\tfor _, r := range recordCollection {\n\t\t_, balance := getWorkedHours(&r)\n\t\ttotalBalance += balance\n\t}\n\treturn totalBalance\n}", "func CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{\n for _, contract := range delegatedContract.Contracts{\n delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout\n }\n return delegatedContract\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func applyCliff(events []event, cliff time.Time) ([]event, error) {\n\tnewEvents := []event{}\n\tcoins := sdk.NewCoins()\n\tfor _, e := range events {\n\t\tif !e.Time.After(cliff) {\n\t\t\tcoins = coins.Add(e.Coins...)\n\t\t\tcontinue\n\t\t}\n\t\tif !coins.IsZero() {\n\t\t\tcliffEvent := event{Time: cliff, Coins: coins}\n\t\t\tnewEvents = append(newEvents, cliffEvent)\n\t\t\tcoins = sdk.NewCoins()\n\t\t}\n\t\tnewEvents = append(newEvents, e)\n\t}\n\tif !coins.IsZero() {\n\t\t// special case if all events are before the cliff\n\t\tcliffEvent := event{Time: cliff, Coins: coins}\n\t\tnewEvents = append(newEvents, cliffEvent)\n\t}\n\t// integrity check\n\toldTotal := sdk.NewCoins()\n\tfor _, e := range events {\n\t\toldTotal = oldTotal.Add(e.Coins...)\n\t}\n\tnewTotal := sdk.NewCoins()\n\tfor _, e := range newEvents {\n\t\tnewTotal = newTotal.Add(e.Coins...)\n\t}\n\tif !oldTotal.IsEqual(newTotal) {\n\t\treturn nil, fmt.Errorf(\"applying vesting cliff changed total from %s to %s\", oldTotal, newTotal)\n\t}\n\treturn newEvents, nil\n}", "func (s *Store) Balance(ns walletdb.ReadBucket, minConf int32, syncHeight int32) (btcutil.Amount, error) {\n\tbal, err := fetchMinedBalance(ns)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// Subtract the balance for each credit that is spent by an unmined\n\t// transaction.\n\tvar op wire.OutPoint\n\tvar block Block\n\terr = ns.NestedReadBucket(bucketUnspent).ForEach(func(k, v []byte) error {\n\t\terr := readCanonicalOutPoint(k, &op)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = readUnspentBlock(v, &block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Subtract the output's amount if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\t_, v := existsCredit(ns, &op.Hash, op.Index, &block)\n\t\t\tamt, err := fetchRawCreditAmount(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbal -= amt\n\n\t\t\t// To prevent decrementing the balance twice if the\n\t\t\t// output has an unconfirmed spend, return now.\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t_, v := existsCredit(ns, &op.Hash, op.Index, &block)\n\t\t\tamt, err := fetchRawCreditAmount(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbal -= amt\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn 0, err\n\t\t}\n\t\tstr := \"failed iterating unspent outputs\"\n\t\treturn 0, storeError(ErrDatabase, str, err)\n\t}\n\n\t// Decrement the balance for any unspent credit with less than\n\t// minConf confirmations and any (unspent) immature coinbase credit.\n\tcoinbaseMaturity := int32(s.chainParams.CoinbaseMaturity)\n\tstopConf := minConf\n\tif coinbaseMaturity > stopConf {\n\t\tstopConf = coinbaseMaturity\n\t}\n\tlastHeight := syncHeight - stopConf\n\tblockIt := makeReadReverseBlockIterator(ns)\n\tfor blockIt.prev() {\n\t\tblock := &blockIt.elem\n\n\t\tif block.Height < lastHeight {\n\t\t\tbreak\n\t\t}\n\n\t\tfor i := range block.transactions {\n\t\t\ttxHash := &block.transactions[i]\n\t\t\trec, err := fetchTxRecord(ns, txHash, &block.Block)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tnumOuts := uint32(len(rec.MsgTx.TxOut))\n\t\t\tfor i := uint32(0); i < numOuts; i++ {\n\t\t\t\t// Avoid double decrementing the credit amount\n\t\t\t\t// if it was already removed for being spent by\n\t\t\t\t// an unmined tx or being locked.\n\t\t\t\top = wire.OutPoint{Hash: *txHash, Index: i}\n\t\t\t\t_, _, isLocked := isLockedOutput(\n\t\t\t\t\tns, op, s.clock.Now(),\n\t\t\t\t)\n\t\t\t\tif isLocked {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\topKey := canonicalOutPoint(txHash, i)\n\t\t\t\tif existsRawUnminedInput(ns, opKey) != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t_, v := existsCredit(ns, txHash, i, &block.Block)\n\t\t\t\tif v == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tamt, spent, err := fetchRawCreditAmountSpent(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, err\n\t\t\t\t}\n\t\t\t\tif spent {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconfs := syncHeight - block.Height + 1\n\t\t\t\tif confs < minConf || (blockchain.IsCoinBaseTx(&rec.MsgTx) &&\n\t\t\t\t\tconfs < coinbaseMaturity) {\n\t\t\t\t\tbal -= amt\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif blockIt.err != nil {\n\t\treturn 0, blockIt.err\n\t}\n\n\t// If unmined outputs are included, increment the balance for each\n\t// output that is unspent.\n\tif minConf == 0 {\n\t\terr = ns.NestedReadBucket(bucketUnminedCredits).ForEach(func(k, v []byte) error {\n\t\t\tif err := readCanonicalOutPoint(k, &op); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Skip adding the balance for this output if it's\n\t\t\t// locked.\n\t\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\t\tif isLocked {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t\t// Output is spent by an unmined transaction.\n\t\t\t\t// Skip to next unmined credit.\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tamount, err := fetchRawUnminedCreditAmount(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbal += amount\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\tif _, ok := err.(Error); ok {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tstr := \"failed to iterate over unmined credits bucket\"\n\t\t\treturn 0, storeError(ErrDatabase, str, err)\n\t\t}\n\t}\n\n\treturn bal, nil\n}", "func (va ClawbackVestingAccount) distributeReward(ctx sdk.Context, ak AccountKeeper, bondDenom string, reward sdk.Coins) {\n\tnow := ctx.BlockTime().Unix()\n\tt := va.StartTime\n\tfirstUnvestedPeriod := 0\n\tunvestedTokens := sdk.ZeroInt()\n\tfor i, period := range va.VestingPeriods {\n\t\tt += period.Length\n\t\tif t <= now {\n\t\t\tfirstUnvestedPeriod = i + 1\n\t\t\tcontinue\n\t\t}\n\t\tunvestedTokens = unvestedTokens.Add(period.Amount.AmountOf(bondDenom))\n\t}\n\n\trunningTotReward := sdk.NewCoins()\n\trunningTotStaking := sdk.ZeroInt()\n\tfor i := firstUnvestedPeriod; i < len(va.VestingPeriods); i++ {\n\t\tperiod := va.VestingPeriods[i]\n\t\trunningTotStaking = runningTotStaking.Add(period.Amount.AmountOf(bondDenom))\n\t\trunningTotRatio := runningTotStaking.ToDec().Quo(unvestedTokens.ToDec())\n\t\ttargetCoins := scaleCoins(reward, runningTotRatio)\n\t\tthisReward := targetCoins.Sub(runningTotReward)\n\t\trunningTotReward = targetCoins\n\t\tperiod.Amount = period.Amount.Add(thisReward...)\n\t\tva.VestingPeriods[i] = period\n\t}\n\n\tva.OriginalVesting = va.OriginalVesting.Add(reward...)\n\tak.SetAccount(ctx, &va)\n}", "func (_ChpRegistry *ChpRegistryCallerSession) CORESTAKINGAMOUNT() (*big.Int, error) {\n\treturn _ChpRegistry.Contract.CORESTAKINGAMOUNT(&_ChpRegistry.CallOpts)\n}", "func balance(w *model.Wal, n int64) int64 {\n\t// Invariant 1\n\t// (this loop will run at most once)\n\tfor w.Cur.Resv < n {\n\t\tm := w.Cur.Resv\n\t\tif needFree(w, m) != m {\n\t\t\tutils.Log.Warnln(\"need free\")\n\t\t\treturn 0\n\t\t}\n\n\t\tmoveResv(w.Tail, w.Cur, m)\n\t\tuseNext(w)\n\t}\n\treturn balanceRest(w, w.Cur, n)\n}", "func (fc *appendFlowControl) debit() {\n\tvar d = min64(fc.balance, fc.charge)\n\tfc.balance -= d\n\tfc.charge -= d\n\tfc.spent = min64(fc.spent+d, fc.minRate) // Add |d| bytes to |spent|, capping at |minRate|.\n\n\tif fc.maxRate == 0 {\n\t\t// |balance| is effectively infinite.\n\t\tfc.spent = min64(fc.spent+fc.charge, fc.minRate)\n\t\tfc.charge = 0\n\t}\n}", "func (_ChpRegistry *ChpRegistryCaller) CORESTAKINGAMOUNT(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ChpRegistry.contract.Call(opts, out, \"CORE_STAKING_AMOUNT\")\n\treturn *ret0, err\n}", "func DeductFees(blockTime time.Time, acc Account, fee StdFee) (Account, sdk.Result) {\n\tcoins := acc.GetCoins()\n\tfeeAmount := fee.Amount()\n\n\tif !feeAmount.IsValid() {\n\t\treturn nil, sdk.ErrInsufficientFee(fmt.Sprintf(\"invalid fee amount: %s\", feeAmount)).Result()\n\t}\n\n\t// get the resulting coins deducting the fees\n\tnewCoins, ok := coins.SafeSub(feeAmount)\n\tif ok {\n\t\treturn nil, sdk.ErrInsufficientFunds(\n\t\t\tfmt.Sprintf(\"insufficient funds to pay for fees; %s < %s\", coins, feeAmount),\n\t\t).Result()\n\t}\n\n\t// Validate the account has enough \"spendable\" coins as this will cover cases\n\t// such as vesting accounts.\n\tspendableCoins := acc.SpendableCoins(blockTime)\n\tif _, hasNeg := spendableCoins.SafeSub(feeAmount); hasNeg {\n\t\treturn nil, sdk.ErrInsufficientFunds(\n\t\t\tfmt.Sprintf(\"insufficient funds to pay for fees; %s < %s\", spendableCoins, feeAmount),\n\t\t).Result()\n\t}\n\n\tif err := acc.SetCoins(newCoins); err != nil {\n\t\treturn nil, sdk.ErrInternal(err.Error()).Result()\n\t}\n\n\treturn acc, sdk.Result{}\n}", "func (_ChpRegistry *ChpRegistrySession) CORESTAKINGAMOUNT() (*big.Int, error) {\n\treturn _ChpRegistry.Contract.CORESTAKINGAMOUNT(&_ChpRegistry.CallOpts)\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func sumCashloan(l *models.Loan, m *models.Message, db *gorm.DB, nc float32) error {\n\tvar uc models.UserCollection\n\tuc.CodUser = l.CodUser\n\terr := getLoan(l, db)\n\tif err != nil {\n\t\tm.Code = http.StatusBadRequest\n\t\tm.Message = \"no se encontro Prestamo\"\n\t\treturn err\n\t}\n\tl.Balance += nc\n\terr = updateLoan(l, db)\n\tif err != nil {\n\t\tm.Code = http.StatusBadGateway\n\t\tm.Message = \"no se pudo actualizar\"\n\t\treturn err\n\t}\n\tvar c models.Collection\n\tc.ID = l.CodCollection\n\terr = sumBalanceCollection(&c, m, db, nc)\n\tif err != nil {\n\t\treturn err\n\t}\n\tuc.CodCollection = l.CodCollection\n\terr = sumCashUserCollection(&uc, m, db, -nc)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (_Cakevault *CakevaultCallerSession) MAXWITHDRAWFEE() (*big.Int, error) {\n\treturn _Cakevault.Contract.MAXWITHDRAWFEE(&_Cakevault.CallOpts)\n}", "func (_GameJam *GameJamCaller) Balance(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _GameJam.contract.Call(opts, out, \"balance\")\n\treturn *ret0, err\n}", "func (_Cakevault *CakevaultSession) MAXWITHDRAWFEE() (*big.Int, error) {\n\treturn _Cakevault.Contract.MAXWITHDRAWFEE(&_Cakevault.CallOpts)\n}", "func (t *TaskChaincode) getBalance(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\t// 0\n\t// \"$account\"\n\tif len(args) != 1 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\tfmt.Println(\"cacluate begins!\");\n\tif len(args[0]) <= 0 {\n\t\treturn shim.Error(\"1st argument must be a non-empty string\")\n\t}\n\n\taccount := args[0]\n\n\tqueryString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"objectType\\\":\\\"PayTX\\\",\\\"payer\\\":\\\"%s\\\"}}\", account)\n\tqueryResults, err := getResultForQueryString(stub, queryString)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tvar payerTXs []payTX\n\terr = json.Unmarshal(queryResults, &payerTXs)\n\tif err != nil {\n\t\tshim.Error(err.Error())\n\t}\n\n\t//fmt.Println(len(payTXs))\n\tvar i int\n\toutcomeVal := 0.0\n for i=0;i<len(payerTXs);i=i+1 {\n\t\tpayerTX := payerTXs[i]\n\t\toutcomeVal = outcomeVal + payerTX.Value\n\t}\n //fmt.Println(outcomeVal)\n\n\tqueryString = fmt.Sprintf(\"{\\\"selector\\\":{\\\"objectType\\\":\\\"PayTX\\\",\\\"payee\\\":\\\"%s\\\"}}\", account)\n\tqueryResults, err = getResultForQueryString(stub, queryString)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tvar payeeTXs []payTX\n\terr = json.Unmarshal(queryResults, &payeeTXs)\n\tif err != nil {\n\t\tshim.Error(err.Error())\n\t}\n\n\tincomeVal := 0.0\n for i=0;i<len(payeeTXs);i=i+1 {\n\t\tpayeeTX := payeeTXs[i]\n\t\tincomeVal = incomeVal + payeeTX.Value\n\t}\n //fmt.Println(incomeVal)\n\n\tbalance := incomeVal - outcomeVal\n\t//fmt.Println(balance)\n balanceStr := strconv.FormatFloat(balance, 'f', 6, 64)\n\n return shim.Success([]byte(balanceStr))\n}", "func determineChurn(prevConsensus, newConsensus *tor.Consensus) Churn {\n\n\tgoneRelays := prevConsensus.Subtract(newConsensus)\n\tnewRelays := newConsensus.Subtract(prevConsensus)\n\n\tmax := math.Max(float64(prevConsensus.Length()), float64(newConsensus.Length()))\n\tnewChurn := (float64(newRelays.Length()) / max)\n\tgoneChurn := (float64(goneRelays.Length()) / max)\n\n\treturn Churn{newChurn, goneChurn}\n}", "func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV + DF by capping slashed at the current unvested amount\n\tunvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime()))\n\tnewSlashed := coinsMin(slashed, unvested)\n\tnewDelegated := delegated.Add(newSlashed...)\n\n\t// modify schedules for the new grant\n\tnewLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods)\n\tnewVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime,\n\t\tva.GetVestingPeriods(), grantVestingPeriods)\n\tif newLockupStart != newVestingStart {\n\t\tpanic(\"bad start time calculation\")\n\t}\n\tva.StartTime = newLockupStart\n\tva.EndTime = max64(newLockupEnd, newVestingEnd)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\tva.OriginalVesting = va.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newDelegated\n\tunvested2 := va.GetVestingCoins(ctx.BlockTime())\n\tva.DelegatedVesting = coinsMin(newDelegated, unvested2)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n}", "func (_DogsOfRome *DogsOfRomeCaller) Balance(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DogsOfRome.contract.Call(opts, out, \"balance\", arg0)\n\treturn *ret0, err\n}", "func (cva ContinuousVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn cva.OriginalVesting.Sub(cva.GetVestedCoins(blockTime))\n}", "func (bc *Blockchain) ProofOfWorkCalc(proof int, previous_proof int, Timestamp int64) string {\n // calculate the proof of work function\n var hash_PoW = sha256.New()\n result := (proof * proof) - (previous_proof * previous_proof) - int(Timestamp)\n hash_PoW.Write([]byte(strconv.Itoa(result)))\n hashed_PoW := hash_PoW.Sum(nil)\n result_hash := hex.EncodeToString(hashed_PoW)\n return result_hash\n}", "func (c *CheckpointAdvancer) CalculateGlobalCheckpoint(ctx context.Context) (uint64, error) {\n\tvar (\n\t\tcp = uint64(math.MaxInt64)\n\t\tthisRun []kv.KeyRange = c.taskRange\n\t\tnextRun []kv.KeyRange\n\t)\n\tdefer c.recordTimeCost(\"record all\")\n\tfor {\n\t\tcoll := NewClusterCollector(ctx, c.env)\n\t\tcoll.setOnSuccessHook(c.cache.InsertRange)\n\t\tfor _, u := range thisRun {\n\t\t\terr := c.GetCheckpointInRange(ctx, u.StartKey, u.EndKey, coll)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t}\n\t\tresult, err := coll.Finish(ctx)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tlog.Debug(\"full: a run finished\", zap.Any(\"checkpoint\", result))\n\n\t\tnextRun = append(nextRun, result.FailureSubRanges...)\n\t\tif cp > result.Checkpoint {\n\t\t\tcp = result.Checkpoint\n\t\t}\n\t\tif len(nextRun) == 0 {\n\t\t\treturn cp, nil\n\t\t}\n\t\tthisRun = nextRun\n\t\tnextRun = nil\n\t\tlog.Debug(\"backoffing with subranges\", zap.Int(\"subranges\", len(thisRun)))\n\t\ttime.Sleep(c.cfg.BackoffTime)\n\t}\n}", "func (_Cakevault *CakevaultCaller) MAXWITHDRAWFEE(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"MAX_WITHDRAW_FEE\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (c *Channel) Balance() *big.Int {\n\tx := new(big.Int)\n\tx.Sub(c.OurState.ContractBalance, c.OurState.TransferAmount())\n\tx.Add(x, c.PartnerState.TransferAmount())\n\treturn x\n}", "func (c *Channel) Balance() *big.Int {\n\tx := new(big.Int)\n\tx.Sub(c.OurState.ContractBalance, c.OurState.TransferAmount())\n\tx.Add(x, c.PartnerState.TransferAmount())\n\treturn x\n}", "func (c BaseController) Balance(store weave.KVStore, src weave.Address) (coin.Coins, error) {\n\tstate, err := c.bucket.Get(store, src)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"cannot get account state\")\n\t}\n\tif state == nil {\n\t\treturn nil, errors.Wrap(errors.ErrNotFound, \"no account\")\n\t}\n\treturn AsCoins(state), nil\n}", "func GenerateGetTotalCommitmentBalanceWithoutDelegatorsScript(env Environment) []byte {\n\tcode := assets.MustAssetString(getTotalCommitmentWithoutDelegatorsFilename)\n\n\treturn []byte(replaceAddresses(code, env))\n}", "func nextBalance(balance Balance, c *AccountConfig, elapsedSecs float32, runningJobs []int) Balance {\n\tvar runningJobsArray [NumPriorities]int\n\tcopy(runningJobsArray[:], runningJobs)\n\tfor priority := 0; priority < NumPriorities; priority++ {\n\t\tval := balance[priority]\n\t\tval -= elapsedSecs * float32(runningJobsArray[priority])\n\t\tchargeRate := c.ChargeRate[priority]\n\n\t\tmaxBalance := chargeRate * c.MaxChargeSeconds\n\t\t// Check for value overflow prior to recharging or capping, because\n\t\t// if the account value is already above cap we want to leave it there.\n\t\t// It likley got over cap due to preemption reimbursement.\n\t\tif val < maxBalance {\n\t\t\tval += elapsedSecs * chargeRate\n\t\t\tif val > maxBalance {\n\t\t\t\tval = maxBalance\n\t\t\t}\n\t\t}\n\t\tbalance[priority] = val\n\t}\n\n\treturn balance\n}", "func (sc Funcs) AccountNFTAmount(ctx wasmlib.ScViewClientContext) *AccountNFTAmountCall {\n\tf := &AccountNFTAmountCall{Func: wasmlib.NewScView(ctx, HScName, HViewAccountNFTAmount)}\n\tf.Params.Proxy = wasmlib.NewCallParamsProxy(f.Func)\n\twasmlib.NewCallResultsProxy(f.Func, &f.Results.Proxy)\n\treturn f\n}", "func NewClawbackGrantAction(\n\tfunderAddress string,\n\tsk StakingKeeper,\n\tgrantStartTime int64,\n\tgrantLockupPeriods, grantVestingPeriods []Period,\n\tgrantCoins sdk.Coins,\n) exported.AddGrantAction {\n\treturn clawbackGrantAction{\n\t\tfunderAddress: funderAddress,\n\t\tsk: sk,\n\t\tgrantStartTime: grantStartTime,\n\t\tgrantLockupPeriods: grantLockupPeriods,\n\t\tgrantVestingPeriods: grantVestingPeriods,\n\t\tgrantCoins: grantCoins,\n\t}\n}", "func calcTotalBalance(chromoinfo []bybBalance) (totalBalace big.Int) {\n\n\tfor _, x := range chromoinfo {\n\t\ttotalBalace = Add(totalBalace, x.Value)\n\t}\n\treturn\n\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func (s *skill) currentCoolDown() float64 {\n\ts.m.Lock()\n\tdefer s.m.Unlock()\n\treturn s.internalCD\n}", "func (va ClawbackVestingAccount) GetVestedOnly(blockTime time.Time) sdk.Coins {\n\treturn ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, blockTime.Unix())\n}", "func deleteActorWithBeneficiary(actorFunds big.Int, beneficiaryAddr address.Address, expectedCode exitcode.ExitCode) func(v *MessageVectorBuilder) {\n\treturn func(v *MessageVectorBuilder) {\n\t\tv.Messages.SetDefaults(GasLimit(1_000_000_000), GasPremium(1), GasFeeCap(200))\n\n\t\tsender := v.Actors.Account(address.SECP256K1, big.Add(big.NewInt(1_000_000_000_000_000), actorFunds))\n\n\t\tbeneficiaryAddr := beneficiaryAddr // capture\n\t\tif beneficiaryAddr == address.Undef {\n\t\t\tbeneficiaryAddr = v.Actors.Account(address.SECP256K1, big.Zero()).ID\n\t\t}\n\n\t\tv.CommitPreconditions()\n\n\t\tv.Assert.ActorExists(chaos.Address)\n\t\tv.Assert.BalanceEq(chaos.Address, big.Zero())\n\n\t\t// transfer required funds to the actor that will be deleted\n\t\tm := v.Messages.Sugar().Transfer(sender.ID, chaos.Address, Value(actorFunds), Nonce(0))\n\t\tv.Messages.ApplyOne(m)\n\t\tv.Assert.EveryMessageResultSatisfies(ExitCode(exitcode.Ok))\n\n\t\t// if this is will succeed, record the current balance so we can check funds\n\t\t// were transferred to the beneficiary\n\t\tvar bal big.Int\n\t\tif expectedCode == exitcode.Ok {\n\t\t\tbal = v.StateTracker.Balance(beneficiaryAddr)\n\t\t}\n\n\t\tv.Messages.Raw(\n\t\t\tsender.ID,\n\t\t\tchaos.Address,\n\t\t\tchaos.MethodDeleteActor,\n\t\t\tMustSerialize(&beneficiaryAddr),\n\t\t\tValue(big.Zero()),\n\t\t\tNonce(1),\n\t\t)\n\t\tv.CommitApplies()\n\n\t\tv.Assert.LastMessageResultSatisfies(ExitCode(expectedCode))\n\n\t\t// check beneficiary received funds if it succeeded\n\t\tif expectedCode == exitcode.Ok && beneficiaryAddr != chaos.Address {\n\t\t\tv.Assert.ActorMissing(chaos.Address)\n\t\t\tv.Assert.BalanceEq(beneficiaryAddr, big.Add(bal, actorFunds))\n\t\t}\n\t}\n}", "func (bva *BaseVestingAccount) TrackUndelegation(amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\t// panic if the undelegation amount is zero\n\t\tif coin.Amount.IsZero() {\n\t\t\tpanic(\"undelegation attempt with zero coins\")\n\t\t}\n\t\tdelegatedFree := bva.DelegatedFree.AmountOf(coin.Denom)\n\t\tdelegatedVesting := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(DF, D)\n\t\t// Y := min(DV, D - X)\n\t\tx := sdk.MinInt(delegatedFree, coin.Amount)\n\t\ty := sdk.MinInt(delegatedVesting, coin.Amount.Sub(x))\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Sub(sdk.Coins{xCoin})\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Sub(sdk.Coins{yCoin})\n\t\t}\n\t}\n}", "func (sc Funcs) Balance(ctx wasmlib.ScViewClientContext) *BalanceCall {\n\tf := &BalanceCall{Func: wasmlib.NewScView(ctx, HScName, HViewBalance)}\n\tf.Params.Proxy = wasmlib.NewCallParamsProxy(f.Func)\n\twasmlib.NewCallResultsProxy(f.Func, &f.Results.Proxy)\n\treturn f\n}", "func totalFees(block *model.Block, receipts []*model.Receipt) *big.Float {\n\tfeesWei := new(big.Int)\n\tfor i, tx := range block.Transactions() {\n\t\tminerFee, _ := tx.EffectiveGasTip(block.BaseFee())\n\t\tfeesWei.Add(feesWei, new(big.Int).Mul(new(big.Int).SetUint64(receipts[i].GasUsed), minerFee))\n\t}\n\treturn new(big.Float).Quo(new(big.Float).SetInt(feesWei), new(big.Float).SetInt(big.NewInt(config.Ether)))\n}", "func (s *ArkClient) CalculateVotersProfit(params DelegateQueryParams, shareRatio float64, blocklist string, whitelist string, capBalance bool, balanceCapAmount float64, blockBalanceCap bool) []DelegateDataProfit {\n\tdelegateRes, _, _ := s.GetDelegate(params)\n\tvoters, _, _ := s.GetDelegateVoters(params)\n\taccountRes, _, _ := s.GetAccount(AccountQueryParams{Address: delegateRes.SingleDelegate.Address})\n\n\tdelegateBalance, _ := strconv.ParseFloat(accountRes.Account.Balance, 64)\n\tdelegateBalance = float64(delegateBalance) / SATOSHI\n\n\t//calculating vote weight\n\tvotersProfit := []DelegateDataProfit{}\n\tdelelgateVoteWeight := 0\n\n\t//computing summ of all votes\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tintBalance, _ := strconv.Atoi(element.Balance)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tintBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tintBalance = int(balanceCapAmount)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdelelgateVoteWeight += intBalance\n\t}\n\n\t//calculating\n\tfor _, element := range voters.Accounts {\n\t\t//skipping blocked ones\n\t\tif isBlockedAddress(blocklist, element.Address) {\n\t\t\tcontinue\n\t\t}\n\n\t\t//skip balanceCap unless whitelisted\n\t\tcurrentVoterBalance, _ := strconv.ParseFloat(element.Balance, 64)\n\t\tif capBalance && currentVoterBalance > balanceCapAmount {\n\t\t\tif !isAllowedAddress(whitelist, element.Address) {\n\t\t\t\tif blockBalanceCap {\n\t\t\t\t\tcurrentVoterBalance = 0\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tcurrentVoterBalance = balanceCapAmount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdeleProfit := DelegateDataProfit{\n\t\t\tAddress: element.Address,\n\t\t}\n\t\tdeleProfit.VoteWeight = currentVoterBalance / SATOSHI\n\t\tdeleProfit.VoteWeightShare = float64(currentVoterBalance) / float64(delelgateVoteWeight)\n\t\tdeleProfit.EarnedAmount100 = float64(delegateBalance) * deleProfit.VoteWeightShare\n\t\tdeleProfit.EarnedAmountXX = float64(delegateBalance) * deleProfit.VoteWeightShare * shareRatio\n\t\tdeleProfit.VoteDuration = s.GetVoteDuration(element.Address)\n\t\tvotersProfit = append(votersProfit, deleProfit)\n\t}\n\n\treturn votersProfit\n}", "func (cva ContinuousVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\n\t// We must handle the case where the start time for a vesting account has\n\t// been set into the future or when the start of the chain is not exactly\n\t// known.\n\tif blockTime.Unix() <= cva.StartTime {\n\t\treturn vestedCoins\n\t} else if blockTime.Unix() >= cva.EndTime {\n\t\treturn cva.OriginalVesting\n\t}\n\n\t// calculate the vesting scalar\n\tx := blockTime.Unix() - cva.StartTime\n\ty := cva.EndTime - cva.StartTime\n\ts := sdk.NewDec(x).Quo(sdk.NewDec(y))\n\n\tfor _, ovc := range cva.OriginalVesting {\n\t\tvestedAmt := ovc.Amount.ToDec().Mul(s).RoundInt()\n\t\tvestedCoins = append(vestedCoins, sdk.NewCoin(ovc.Denom, vestedAmt))\n\t}\n\n\treturn vestedCoins\n}", "func (_GameJam *GameJamCallerSession) Balance() (*big.Int, error) {\n\treturn _GameJam.Contract.Balance(&_GameJam.CallOpts)\n}", "func (w *worker) externSyncAccountBalanceToHost() {\n\t// Spin/block until the worker has no jobs in motion. This should only be\n\t// called from the primary loop of the worker, meaning that no new jobs will\n\t// be launched while we spin.\n\tisIdle := func() bool {\n\t\tsls := w.staticLoopState\n\t\ta := atomic.LoadUint64(&sls.atomicSerialJobRunning) == 0\n\t\tb := atomic.LoadUint64(&sls.atomicAsyncJobsRunning) == 0\n\t\treturn a && b\n\t}\n\tstart := time.Now()\n\tfor !isIdle() {\n\t\tif time.Since(start) > accountIdleMaxWait {\n\t\t\t// The worker failed to go idle for too long. Print the loop state,\n\t\t\t// so we know what kind of task is keeping it busy.\n\t\t\tw.renter.log.Printf(\"Worker static loop state: %+v\\n\\n\", w.staticLoopState)\n\t\t\t// Get the stack traces of all running goroutines.\n\t\t\tbuf := make([]byte, modules.StackSize) // 64MB\n\t\t\tn := runtime.Stack(buf, true)\n\t\t\tw.renter.log.Println(string(buf[:n]))\n\t\t\tw.renter.log.Critical(fmt.Sprintf(\"worker has taken more than %v minutes to go idle\", accountIdleMaxWait.Minutes()))\n\t\t\treturn\n\t\t}\n\t\tawake := w.renter.tg.Sleep(accountIdleCheckFrequency)\n\t\tif !awake {\n\t\t\treturn\n\t\t}\n\t}\n\t// Do a check to ensure that the worker is still idle after the function is\n\t// complete. This should help to catch any situation where the worker is\n\t// spinning up new jobs, even though it is not supposed to be spinning up\n\t// new jobs while it is performing the sync operation.\n\tdefer func() {\n\t\tif !isIdle() {\n\t\t\tw.renter.log.Critical(\"worker appears to be spinning up new jobs during managedSyncAccountBalanceToHost\")\n\t\t}\n\t}()\n\n\t// Sanity check the account's deltas are zero, indicating there are no\n\t// in-progress jobs\n\tw.staticAccount.mu.Lock()\n\tdeltasAreZero := w.staticAccount.pendingDeposits.IsZero() && w.staticAccount.pendingWithdrawals.IsZero()\n\tw.staticAccount.mu.Unlock()\n\tif !deltasAreZero {\n\t\tbuild.Critical(\"managedSyncAccountBalanceToHost is called on a worker with an account that has non-zero deltas, indicating in-progress jobs\")\n\t}\n\n\t// Track the outcome of the account sync - this ensures a proper working of\n\t// the maintenance cooldown mechanism.\n\tbalance, err := w.staticHostAccountBalance()\n\tw.managedTrackAccountSyncErr(err)\n\tif err != nil {\n\t\tw.renter.log.Debugf(\"ERROR: failed to check account balance on host %v failed, err: %v\\n\", w.staticHostPubKeyStr, err)\n\t\treturn\n\t}\n\n\t// If our account balance is lower than the balance indicated by the host,\n\t// we want to sync our balance by resetting it.\n\tif w.staticAccount.managedAvailableBalance().Cmp(balance) < 0 {\n\t\tw.staticAccount.managedResetBalance(balance)\n\t}\n\n\t// Determine how long to wait before attempting to sync again, and then\n\t// update the syncAt time. There is significant randomness in the waiting\n\t// because syncing with the host requires freezing up the worker. We do not\n\t// want to freeze up a large number of workers at once, nor do we want to\n\t// freeze them frequently.\n\twaitTime := time.Duration(fastrand.Intn(accountSyncRandWaitMilliseconds)) * time.Millisecond\n\twaitTime += accountSyncMinWaitTime\n\tw.staticAccount.callSetSyncAt(time.Now().Add(waitTime))\n\n\t// TODO perform a thorough balance comparison to decide whether the drift in\n\t// the account balance is warranted. If not the host needs to be penalized\n\t// accordingly. Perform this check at startup and periodically.\n}", "func (_Cakevault *CakevaultSession) CalculateHarvestCakeRewards() (*big.Int, error) {\n\treturn _Cakevault.Contract.CalculateHarvestCakeRewards(&_Cakevault.CallOpts)\n}", "func testWithdrawZeroBalance(t *testing.T, n int) {\n\trng := pkgtest.Prng(t)\n\ts := test.NewSetup(t, rng, n)\n\t// create valid state and params\n\tparams, state := channeltest.NewRandomParamsAndState(rng, channeltest.WithParts(s.Parts...), channeltest.WithAssets((*ethchannel.Asset)(&s.Asset)), channeltest.WithIsFinal(true))\n\tagreement := state.Balances.Clone()\n\n\tfor i := range params.Parts {\n\t\tif i%2 == 0 {\n\t\t\tstate.Balances[0][i].SetInt64(0)\n\t\t\tagreement[0][i].SetInt64(0)\n\t\t} // is != 0 otherwise\n\t\tt.Logf(\"Part: %d ShouldFund: %t Bal: %v\", i, i%2 == 1, state.Balances[0][i])\n\t}\n\n\t// fund\n\tct := pkgtest.NewConcurrent(t)\n\tfor i, funder := range s.Funders {\n\t\ti, funder := i, funder\n\t\tgo ct.StageN(\"funding loop\", n, func(rt pkgtest.ConcT) {\n\t\t\treq := channel.NewFundingReq(params, state, channel.Index(i), agreement)\n\t\t\trequire.NoError(rt, funder.Fund(context.Background(), *req), \"funding should succeed\")\n\t\t})\n\t}\n\tct.Wait(\"funding loop\")\n\n\t// register\n\treq := channel.AdjudicatorReq{\n\t\tParams: params,\n\t\tAcc: s.Accs[0],\n\t\tTx: testSignState(t, s.Accs, params, state),\n\t\tIdx: 0,\n\t}\n\trequire.NoError(t, s.Adjs[0].Register(context.Background(), req))\n\t// we don't need to wait for a timeout since we registered a final state\n\n\t// withdraw\n\tfor i, _adj := range s.Adjs {\n\t\tadj := _adj\n\t\treq.Acc = s.Accs[i]\n\t\treq.Idx = channel.Index(i)\n\t\t// check that the nonce stays the same for zero balance withdrawals\n\t\tdiff, err := test.NonceDiff(s.Accs[i].Address(), adj, func() error {\n\t\t\treturn adj.Withdraw(context.Background(), req, nil)\n\t\t})\n\t\trequire.NoError(t, err)\n\t\tif i%2 == 0 {\n\t\t\tassert.Zero(t, diff, \"Nonce should stay the same\")\n\t\t} else {\n\t\t\tassert.Equal(t, 1, diff, \"Nonce should increase by 1\")\n\t\t}\n\t}\n\tassertHoldingsZero(context.Background(), t, s.CB, params, state.Assets)\n}", "func (dva DelayedVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn dva.OriginalVesting.Sub(dva.GetVestedCoins(blockTime))\n}", "func (cm *ConnectionManager) fundsRemaining() *big.Int {\n\tif cm.funds.Cmp(utils.BigInt0) > 0 {\n\t\tremaining := new(big.Int)\n\t\tremaining.Sub(cm.funds, cm.sumDeposits())\n\t\treturn remaining\n\t}\n\treturn utils.BigInt0\n}", "func (w *Wallet) VacuumDb(startKey string, maxTime time.Duration) (*btcjson.VacuumDbRes, er.R) {\n\tdeadline := time.Now().Add(maxTime)\n\tstats := btcjson.VacuumDbRes{}\n\tif sk, errr := hex.DecodeString(startKey); errr != nil {\n\t\treturn nil, er.E(errr)\n\t} else if chainClient, err := w.requireChainClient(); err != nil {\n\t\treturn nil, err\n\t} else if bs, err := chainClient.BlockStamp(); err != nil {\n\t\treturn nil, err\n\t} else if err := walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) er.R {\n\t\ttxNs := tx.ReadWriteBucket(wtxmgrNamespaceKey)\n\t\tvar badOutputs []wtxmgr.Credit\n\t\ti := 0\n\t\tif err := w.TxStore.ForEachUnspentOutput(txNs, sk, func(k []byte, op *wtxmgr.Credit) er.R {\n\t\t\tif maxTime > 0 && time.Now().After(deadline) {\n\t\t\t\tstats.EndKey = hex.EncodeToString(k)\n\t\t\t\treturn er.LoopBreak\n\t\t\t}\n\t\t\ti++\n\t\t\tif txrules.IsBurned(op, w.chainParams, bs.Height) {\n\t\t\t\tlog.Debugf(\"Removing tx [%s] which has burned\",\n\t\t\t\t\top.OutPoint.Hash.String())\n\t\t\t\tbadOutputs = append(badOutputs, *op)\n\t\t\t\tstats.Burned++\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif op.Height < 0 {\n\t\t\t} else if _, err := chainClient.GetBlockHeader(&op.Block.Hash); err != nil {\n\t\t\t\tlog.Debugf(\"Removing tx [%s] because it references orphan block [%s]\",\n\t\t\t\t\top.OutPoint.Hash.String(), op.Block.Hash)\n\t\t\t\tbadOutputs = append(badOutputs, *op)\n\t\t\t\tstats.Orphaned++\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn nil\n\t\t}); err != nil && !er.IsLoopBreak(err) {\n\t\t\treturn err\n\t\t}\n\t\tstats.VisitedUtxos = i\n\t\tfor _, op := range badOutputs {\n\t\t\tif err := wtxmgr.RollbackTransaction(txNs, &op.OutPoint.Hash, &op.Block); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\treturn &stats, err\n\t}\n\treturn &stats, nil\n}", "func (u *User) WithdrawCash(amount int) int {\n\tif amount <= 0 {\n\t\treturn u.cash\n\t}\n\n\tif amount > u.cash {\n\t\treturn u.cash\n\t}\n\n\tu.cash -= amount\n\treturn u.cash\n}", "func calculateTicketValue(\n\tbeaconOutput []byte,\n\tstakerValue []byte,\n\tvirtualStakerIndex *big.Int,\n) ([8]byte, error) {\n\tvar combinedValue []byte\n\tvar ticketValue [8]byte\n\n\tbeaconOutputPadded, err := byteutils.LeftPadTo32Bytes(beaconOutput)\n\tif err != nil {\n\t\treturn ticketValue, fmt.Errorf(\"cannot pad a becon output, [%v]\", err)\n\t}\n\n\tstakerValuePadded, err := byteutils.LeftPadTo32Bytes(stakerValue)\n\tif err != nil {\n\t\treturn ticketValue, fmt.Errorf(\"cannot pad a staker value, [%v]\", err)\n\t}\n\n\tvirtualStakerIndexPadded, err := byteutils.LeftPadTo32Bytes(virtualStakerIndex.Bytes())\n\tif err != nil {\n\t\treturn ticketValue, fmt.Errorf(\"cannot pad a virtual staker index, [%v]\", err)\n\t}\n\n\tcombinedValue = append(combinedValue, beaconOutputPadded...)\n\tcombinedValue = append(combinedValue, stakerValuePadded...)\n\tcombinedValue = append(combinedValue, virtualStakerIndexPadded...)\n\n\tcopy(ticketValue[:], crypto.Keccak256(combinedValue[:])[:8])\n\n\treturn ticketValue, nil\n}", "func NewClawbackAction(requestor, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) exported.ClawbackAction {\n\treturn clawbackAction{\n\t\trequestor: requestor,\n\t\tdest: dest,\n\t\tak: ak,\n\t\tbk: bk,\n\t\tsk: sk,\n\t}\n}", "func (s *State) applyContractMaintenance(td *TransactionDiff) (diffs []OutputDiff) {\n\t// Scan all open contracts and perform any required maintenance on each.\n\tvar contractsToDelete []ContractID\n\tfor _, openContract := range s.openContracts {\n\t\t// Check if the window index is changing.\n\t\tcontract := openContract.FileContract\n\t\tcontractProgress := s.height() - contract.Start\n\t\tif s.height() > contract.Start && contractProgress%contract.ChallengeWindow == 0 {\n\t\t\t// If the proof was missed for this window, add an output.\n\t\t\tcd := ContractDiff{\n\t\t\t\tContract: openContract.FileContract,\n\t\t\t\tContractID: openContract.ContractID,\n\t\t\t\tNew: false,\n\t\t\t\tTerminated: false,\n\t\t\t\tPreviousOpenContract: *openContract,\n\t\t\t}\n\t\t\tif openContract.WindowSatisfied == false {\n\t\t\t\tdiff := s.applyMissedProof(openContract)\n\t\t\t\tdiffs = append(diffs, diff)\n\t\t\t} else {\n\t\t\t\ts.currentBlockNode().SuccessfulWindows = append(s.currentBlockNode().SuccessfulWindows, openContract.ContractID)\n\t\t\t}\n\t\t\topenContract.WindowSatisfied = false\n\t\t\tcd.NewOpenContract = *openContract\n\t\t\ttd.ContractDiffs = append(td.ContractDiffs, cd)\n\t\t}\n\n\t\t// Check for a terminated contract.\n\t\tif openContract.FundsRemaining == 0 || contract.End == s.height() || contract.Tolerance == openContract.Failures {\n\t\t\tif openContract.FundsRemaining != 0 {\n\t\t\t\t// Create a new output that terminates the contract.\n\t\t\t\toutput := Output{\n\t\t\t\t\tValue: openContract.FundsRemaining,\n\t\t\t\t}\n\n\t\t\t\t// Get the output address.\n\t\t\t\tcontractSuccess := openContract.Failures != openContract.FileContract.Tolerance\n\t\t\t\tif contractSuccess {\n\t\t\t\t\toutput.SpendHash = contract.ValidProofAddress\n\t\t\t\t} else {\n\t\t\t\t\toutput.SpendHash = contract.MissedProofAddress\n\t\t\t\t}\n\n\t\t\t\t// Create the output.\n\t\t\t\toutputID := ContractTerminationOutputID(openContract.ContractID, contractSuccess)\n\t\t\t\ts.unspentOutputs[outputID] = output\n\t\t\t\tdiff := OutputDiff{New: true, ID: outputID, Output: output}\n\t\t\t\tdiffs = append(diffs, diff)\n\t\t\t}\n\n\t\t\t// Add the contract to contract terminations.\n\t\t\ts.currentBlockNode().ContractTerminations = append(s.currentBlockNode().ContractTerminations, openContract)\n\n\t\t\t// Mark contract for deletion (can't delete from a map while\n\t\t\t// iterating through it - results in undefined behavior of the\n\t\t\t// iterator.\n\t\t\tcontractsToDelete = append(contractsToDelete, openContract.ContractID)\n\t\t}\n\t}\n\n\t// Delete all of the contracts that terminated.\n\tfor _, contractID := range contractsToDelete {\n\t\tdelete(s.openContracts, contractID)\n\t}\n\treturn\n}", "func CheckPercentageSumForCycle(cycle int, delegatedContracts []DelegatedContract) float64{\n var sum float64\n sum = 0\n for x := 0; x < len(delegatedContracts); x++{\n counter := 0\n for y := 0; y < len(delegatedContracts[x].Contracts); y++{\n if (delegatedContracts[x].Contracts[y].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n\n sum = sum + delegatedContracts[x].Contracts[counter].SharePercentage\n }\n return sum\n}", "func Balance() int {\n\treturn <-balances\n}", "func (vva ValidatorVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn vva.OriginalVesting.Sub(vva.GetVestedCoins(blockTime))\n}", "func (_Cakevault *CakevaultCaller) CalculateHarvestCakeRewards(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"calculateHarvestCakeRewards\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (b *breachArbiter) contractObserver(activeChannels []*lnwallet.LightningChannel) {\n\tdefer b.wg.Done()\n\n\t// For each active channel found within the database, we launch a\n\t// detected breachObserver goroutine for that channel and also track\n\t// the new goroutine within the breachObservers map so we can cancel it\n\t// later if necessary.\n\tfor _, channel := range activeChannels {\n\t\tsettleSignal := make(chan struct{})\n\t\tchanPoint := channel.ChannelPoint()\n\t\tb.breachObservers[*chanPoint] = settleSignal\n\n\t\tb.wg.Add(1)\n\t\tgo b.breachObserver(channel, settleSignal)\n\t}\n\n\t// TODO(roasbeef): need to ensure currentHeight passed in doesn't\n\t// result in lost notification\n\nout:\n\tfor {\n\t\tselect {\n\t\tcase breachInfo := <-b.breachedContracts:\n\t\t\t_, currentHeight, err := b.chainIO.GetBestBlock()\n\t\t\tif err != nil {\n\t\t\t\tbrarLog.Errorf(\"unable to get best height: %v\", err)\n\t\t\t}\n\n\t\t\t// A new channel contract has just been breached! We\n\t\t\t// first register for a notification to be dispatched\n\t\t\t// once the breach transaction (the revoked commitment\n\t\t\t// transaction) has been confirmed in the chain to\n\t\t\t// ensure we're not dealing with a moving target.\n\t\t\tbreachTXID := &breachInfo.commitHash\n\t\t\tconfChan, err := b.notifier.RegisterConfirmationsNtfn(\n\t\t\t\tbreachTXID, 1, uint32(currentHeight),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tbrarLog.Errorf(\"unable to register for conf for txid: %v\",\n\t\t\t\t\tbreachTXID)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tbrarLog.Warnf(\"A channel has been breached with tx: %v. \"+\n\t\t\t\t\"Waiting for confirmation, then justice will be served!\",\n\t\t\t\tbreachTXID)\n\n\t\t\t// With the notification registered, we launch a new\n\t\t\t// goroutine which will finalize the channel\n\t\t\t// retribution after the breach transaction has been\n\t\t\t// confirmed.\n\t\t\tb.wg.Add(1)\n\t\t\tgo b.exactRetribution(confChan, breachInfo)\n\n\t\t\tdelete(b.breachObservers, breachInfo.chanPoint)\n\t\tcase contract := <-b.newContracts:\n\t\t\t// A new channel has just been opened within the\n\t\t\t// daemon, so we launch a new breachObserver to handle\n\t\t\t// the detection of attempted contract breaches.\n\t\t\tsettleSignal := make(chan struct{})\n\t\t\tchanPoint := contract.ChannelPoint()\n\n\t\t\t// If the contract is already being watched, then an\n\t\t\t// additional send indicates we have a stale version of\n\t\t\t// the contract. So we'll cancel active watcher\n\t\t\t// goroutine to create a new instance with the latest\n\t\t\t// contract reference.\n\t\t\tif oldSignal, ok := b.breachObservers[*chanPoint]; ok {\n\t\t\t\tbrarLog.Infof(\"ChannelPoint(%v) is now live, \"+\n\t\t\t\t\t\"abandoning state contract for live \"+\n\t\t\t\t\t\"version\", chanPoint)\n\t\t\t\tclose(oldSignal)\n\t\t\t}\n\n\t\t\tb.breachObservers[*chanPoint] = settleSignal\n\n\t\t\tbrarLog.Debugf(\"New contract detected, launching \" +\n\t\t\t\t\"breachObserver\")\n\n\t\t\tb.wg.Add(1)\n\t\t\tgo b.breachObserver(contract, settleSignal)\n\n\t\t\t// TODO(roasbeef): add doneChan to signal to peer continue\n\t\t\t// * peer send over to us on loadActiveChanenls, sync\n\t\t\t// until we're aware so no state transitions\n\t\tcase chanPoint := <-b.settledContracts:\n\t\t\t// A new channel has been closed either unilaterally or\n\t\t\t// cooperatively, as a result we no longer need a\n\t\t\t// breachObserver detected to the channel.\n\t\t\tkillSignal, ok := b.breachObservers[*chanPoint]\n\t\t\tif !ok {\n\t\t\t\tbrarLog.Errorf(\"Unable to find contract: %v\",\n\t\t\t\t\tchanPoint)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tbrarLog.Debugf(\"ChannelPoint(%v) has been settled, \"+\n\t\t\t\t\"cancelling breachObserver\", chanPoint)\n\n\t\t\t// If we had a breachObserver active, then we signal it\n\t\t\t// for exit and also delete its state from our tracking\n\t\t\t// map.\n\t\t\tclose(killSignal)\n\t\t\tdelete(b.breachObservers, *chanPoint)\n\t\tcase <-b.quit:\n\t\t\tbreak out\n\t\t}\n\t}\n\n\treturn\n}", "func (_Cakevault *CakevaultCallerSession) WithdrawFee() (*big.Int, error) {\n\treturn _Cakevault.Contract.WithdrawFee(&_Cakevault.CallOpts)\n}", "func (s *State) returnDeposit(tx *types.Transaction, height uint32) {\n\tvar inputValue common.Fixed64\n\tfor _, input := range tx.Inputs {\n\t\tinputValue += s.DepositOutputs[input.ReferKey()]\n\t}\n\n\treturnAction := func(producer *Producer) {\n\t\ts.history.Append(height, func() {\n\t\t\tif height >= s.chainParams.CRVotingStartHeight {\n\t\t\t\tproducer.depositAmount -= inputValue\n\t\t\t}\n\t\t\tproducer.state = Returned\n\t\t}, func() {\n\t\t\tif height >= s.chainParams.CRVotingStartHeight {\n\t\t\t\tproducer.depositAmount += inputValue\n\t\t\t}\n\t\t\tproducer.state = Canceled\n\t\t})\n\t}\n\n\tfor _, program := range tx.Programs {\n\t\tpk := program.Code[1 : len(program.Code)-1]\n\t\tif producer := s.getProducer(pk); producer != nil && producer.state == Canceled {\n\t\t\treturnAction(producer)\n\t\t}\n\t}\n}", "func (f *FinalizedChain) ColdEnd() Step {\n\tf.RLock()\n\tdefer f.RUnlock()\n\treturn f.end()\n}", "func (a *account) maxExpectedBalance() types.Currency {\n\t// NOTE: negativeBalance will never be larger than the sum of the pending\n\t// deposits. If that does happen, this will build.Critical which indicates\n\t// that something is incorrect within the worker's internal accounting.\n\treturn a.balance.Add(a.pendingDeposits).Sub(a.negativeBalance)\n}", "func (c *client) updateGiftConfidence(island shared.ClientID) int {\n\tturn := c.gameState().Turn\n\tpastConfidence := c.confidence(\"Gifts\", island)\n\n\tvar bufferLen = 0\n\tif turn < 10 {\n\t\tbufferLen = int(turn)\n\t} else {\n\t\tbufferLen = 10\n\t}\n\n\trunMeanTheyReq := 0.0\n\trunMeanTheyDon := 0.0\n\trunMeanWeReq := 0.0\n\trunMeanWeDon := 0.0\n\n\tourReqMap := c.giftHist[island].OurRequest\n\ttheirReqMap := c.giftHist[island].IslandRequest\n\n\tourKeys := make([]int, 0)\n\tfor k, _ := range ourReqMap {\n\t\tourKeys = append(ourKeys, int(k))\n\t}\n\n\ttheirKeys := make([]int, 0)\n\tfor k, _ := range theirReqMap {\n\t\ttheirKeys = append(theirKeys, int(k))\n\t}\n\n\t// Sort the keys in decreasing order\n\tsort.Ints(ourKeys)\n\tsort.Ints(theirKeys)\n\n\t// Take running average of the interactions\n\t// The individual turn values will be scaled wrt to the \"distance\" from the current turn\n\t// ie transactions further in the past are valued less\n\tif MinInt(len(ourKeys), len(theirKeys)) == 0 {\n\t\treturn pastConfidence\n\t}\n\tc.Logf(\"Bufferlen %v\", bufferLen)\n\tfor i := 0; i < MinInt(bufferLen, len(ourKeys)); i++ {\n\t\t// Get the transaction distance to the previous transaction\n\t\tourTransDist := turn - uint(ourKeys[i])\n\t\t// Update the respective running mean factoring in the transactionDistance (inv proportioanl to transactionDistance so farther transactions are weighted less)\n\t\trunMeanTheyDon = runMeanTheyDon + (float64(ourReqMap[uint(ourKeys[i])].gifted)/float64(ourTransDist)-float64(runMeanTheyDon))/float64(i+1)\n\t\trunMeanWeReq = runMeanWeReq + (float64(ourReqMap[uint(ourKeys[i])].requested)/float64(ourTransDist)-float64(runMeanWeReq))/float64(i+1)\n\t}\n\tfor i := 0; i < MinInt(bufferLen, len(theirKeys)); i++ {\n\t\t// Get the transaction distance to the previous transaction\n\t\ttheirTransDist := turn - uint(theirKeys[i])\n\t\t// Update the respective running mean factoring in the transactionDistance (inv proportioanl to transactionDistance so farther transactions are weighted less)\n\t\trunMeanTheyReq = runMeanTheyReq + (float64(theirReqMap[uint(theirKeys[i])].requested)/float64(theirTransDist)-float64(runMeanTheyReq))/float64(i+1)\n\t\trunMeanWeDon = runMeanWeDon + (float64(theirReqMap[uint(theirKeys[i])].gifted))/float64(theirTransDist) - float64(runMeanWeDon)/float64(i+1)\n\t}\n\n\t// TODO: is there a potential divide by 0 here?\n\tusRatio := runMeanTheyDon / runMeanWeReq // between 0 and 1\n\tthemRatio := runMeanWeDon / runMeanTheyReq // between 0 and 1\n\n\tdiff := usRatio - themRatio // between -1 and 1\n\t// confidence increases if usRatio >= themRatio\n\t// confidence decreases if not\n\n\t// e.g. 1 pastConfidnece = 50%\n\t// diff = 100% in our favour 1.0\n\t// inc pastConfidence = (50 + 100)/2 = 75\n\n\t// e.g. 2 pastConfidence = 90%\n\t// diff = 70% in our favour\n\t// inc pastConfidence = (90 + 70)/2 = 80\n\n\t// e.g. 3 pastConfidence = 80%\n\t// diff = 30% against us\n\t// inc pastConfidence = (80 - 30)/2 = 25\n\n\t// e.g. 4 pastConfidence = 100%\n\t// diff = 100% against us\n\t// inc pastConfidence = (100 - 100)/2 = 0\n\n\t// e.g. 5 pastConfidence = 0%\n\t// diff = 100% in our favour\n\t// inc pastConfidence = (0 + 100)/2 = 50\n\n\t// TODO: improve how ratios are used to improve pastConfidence\n\t// pastConfidence = (pastConfidence + sensitivity*diff*100) / 2\n\tpastConfidence = int((pastConfidence + int(diff*100)) / 2)\n\n\treturn pastConfidence\n}", "func (_Cakevault *CakevaultCallerSession) CalculateHarvestCakeRewards() (*big.Int, error) {\n\treturn _Cakevault.Contract.CalculateHarvestCakeRewards(&_Cakevault.CallOpts)\n}", "func (_Cakevault *CakevaultSession) WithdrawFee() (*big.Int, error) {\n\treturn _Cakevault.Contract.WithdrawFee(&_Cakevault.CallOpts)\n}", "func (dva DelayedVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tif blockTime.Unix() >= dva.EndTime {\n\t\treturn dva.OriginalVesting\n\t}\n\n\treturn nil\n}", "func (vva ValidatorVestingAccount) GetVestedCoins(blockTime time.Time) sdk.Coins {\n\tvar vestedCoins sdk.Coins\n\tif blockTime.Unix() <= vva.StartTime {\n\t\treturn vestedCoins\n\t}\n\tcurrentPeriodStartTime := vva.StartTime\n\tnumberPeriods := len(vva.VestingPeriods)\n\tfor i := 0; i < numberPeriods; i++ {\n\t\tx := blockTime.Unix() - currentPeriodStartTime\n\t\tif x >= vva.VestingPeriods[i].Length {\n\t\t\tif vva.VestingPeriodProgress[i].PeriodComplete {\n\t\t\t\tvestedCoins = vestedCoins.Add(vva.VestingPeriods[i].Amount)\n\t\t\t}\n\t\t\tcurrentPeriodStartTime += vva.VestingPeriods[i].Length\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn vestedCoins\n\n}", "func (_Cakevault *CakevaultCaller) WithdrawFee(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"withdrawFee\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func TestFundsStateChangeRollback(t *testing.T) {\n\tcleanAndPrepare()\n\n\trandVar := rand.New(rand.NewSource(time.Now().Unix()))\n\n\taccAHash := protocol.SerializeHashContent(accA.Address)\n\taccBHash := protocol.SerializeHashContent(accB.Address)\n\tminerAccHash := protocol.SerializeHashContent(validatorAcc.Address)\n\n\tvar testSize uint32\n\ttestSize = 1000\n\n\tb := newBlock([32]byte{}, [crypto.COMM_PROOF_LENGTH]byte{}, 1)\n\tvar funds []*protocol.FundsTx\n\n\tvar feeA, feeB uint64\n\n\t//State snapshot\n\trollBackA := accA.Balance\n\trollBackB := accB.Balance\n\n\t//Record transaction amounts in this variables\n\tbalanceA := accA.Balance\n\tbalanceB := accB.Balance\n\n\tloopMax := int(randVar.Uint32()%testSize + 1)\n\tfor i := 0; i < loopMax+1; i++ {\n\t\tftx, _ := protocol.ConstrFundsTx(0x01, randVar.Uint64()%1000000+1, randVar.Uint64()%100+1, uint32(i), accAHash, accBHash, PrivKeyAccA, PrivKeyMultiSig, nil)\n\t\tif addTx(b, ftx) == nil {\n\t\t\tfunds = append(funds, ftx)\n\t\t\tbalanceA -= ftx.Amount\n\t\t\tfeeA += ftx.Fee\n\n\t\t\tbalanceB += ftx.Amount\n\t\t} else {\n\t\t\tt.Errorf(\"Block rejected a valid transaction: %v\\n\", ftx)\n\t\t}\n\n\t\tftx2, _ := protocol.ConstrFundsTx(0x01, randVar.Uint64()%1000+1, randVar.Uint64()%100+1, uint32(i), accBHash, accAHash, PrivKeyAccB, PrivKeyMultiSig, nil)\n\t\tif addTx(b, ftx2) == nil {\n\t\t\tfunds = append(funds, ftx2)\n\t\t\tbalanceB -= ftx2.Amount\n\t\t\tfeeB += ftx2.Fee\n\n\t\t\tbalanceA += ftx2.Amount\n\t\t} else {\n\t\t\tt.Errorf(\"Block rejected a valid transaction: %v\\n\", ftx2)\n\t\t}\n\t}\n\tfundsStateChange(funds)\n\tif accA.Balance != balanceA || accB.Balance != balanceB {\n\t\tt.Error(\"State update failed!\")\n\t}\n\tfundsStateChangeRollback(funds)\n\tif accA.Balance != rollBackA || accB.Balance != rollBackB {\n\t\tt.Error(\"Rollback failed!\")\n\t}\n\n\t//collectTxFees is checked below in its own test (to additionally cover overflow scenario)\n\tbalBeforeRew := validatorAcc.Balance\n\treward := 5\n\tcollectBlockReward(uint64(reward), minerAccHash)\n\tif validatorAcc.Balance != balBeforeRew+uint64(reward) {\n\t\tt.Error(\"Block reward collection failed!\")\n\t}\n\tcollectBlockRewardRollback(uint64(reward), minerAccHash)\n\tif validatorAcc.Balance != balBeforeRew {\n\t\tt.Error(\"Block reward collection rollback failed!\")\n\t}\n}", "func (w *Wallet) CalculateBalance(confirms int32) (btcutil.Amount, er.R) {\n\tvar balance btcutil.Amount\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\ttxmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)\n\t\tvar err er.R\n\t\tblk := w.Manager.SyncedTo()\n\t\tbalance, err = w.TxStore.Balance(txmgrNs, confirms, blk.Height)\n\t\treturn err\n\t})\n\treturn balance, err\n}", "func (e *engineImpl) Finalize(\n\tchain engine.ChainReader, header *block.Header,\n\tstate *state.DB, txs []*types.Transaction,\n\treceipts []*types.Receipt, outcxs []*types.CXReceipt,\n\tincxs []*types.CXReceiptsProof, stks []*staking.StakingTransaction,\n) (*types.Block, *big.Int, error) {\n\n\t// Accumulate any block and uncle rewards and commit the final state root\n\t// Header seems complete, assemble into a block and return\n\tpayout, err := AccumulateRewards(\n\t\tchain, state, header, e.Rewarder(), e.Slasher(), e.Beaconchain(),\n\t)\n\tif err != nil {\n\t\treturn nil, nil, ctxerror.New(\"cannot pay block reward\").WithCause(err)\n\t}\n\n\t// Withdraw unlocked tokens to the delegators' accounts\n\t// Only do such at the last block of an epoch\n\tif header.ShardID() == shard.BeaconChainShardID && len(header.ShardState()) > 0 {\n\t\tvalidators, err := chain.ReadValidatorList()\n\t\tif err != nil {\n\t\t\treturn nil, nil, ctxerror.New(\"[Finalize] failed to read active validators\").WithCause(err)\n\t\t}\n\t\t// Payout undelegated/unlocked tokens\n\t\tfor _, validator := range validators {\n\t\t\twrapper := state.GetStakingInfo(validator)\n\t\t\tif wrapper != nil {\n\t\t\t\tfor i := range wrapper.Delegations {\n\t\t\t\t\tdelegation := &wrapper.Delegations[i]\n\t\t\t\t\ttotalWithdraw := delegation.RemoveUnlockedUndelegations(header.Epoch(), wrapper.LastEpochInCommittee)\n\t\t\t\t\tstate.AddBalance(delegation.DelegatorAddress, totalWithdraw)\n\t\t\t\t}\n\t\t\t\tif err := state.UpdateStakingInfo(validator, wrapper); err != nil {\n\t\t\t\t\treturn nil, nil, ctxerror.New(\"[Finalize] failed update validator info\").WithCause(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr = errors.New(\"[Finalize] validator came back empty \" + common2.MustAddressToBech32(validator))\n\t\t\t\treturn nil, nil, ctxerror.New(\"[Finalize] failed getting validator info\").WithCause(err)\n\t\t\t}\n\t\t}\n\n\t\t// Set the LastEpochInCommittee field for all external validators in the upcoming epoch.\n\t\tnewShardState, err := header.GetShardState()\n\t\tif err != nil {\n\t\t\treturn nil, nil, ctxerror.New(\"[Finalize] failed to read shard state\").WithCause(err)\n\t\t}\n\t\tprocessed := make(map[common.Address]struct{})\n\t\tfor i := range newShardState.Shards {\n\t\t\tshard := newShardState.Shards[i]\n\t\t\tfor j := range shard.Slots {\n\t\t\t\tslot := shard.Slots[j]\n\t\t\t\tif slot.EffectiveStake != nil { // For external validator\n\t\t\t\t\t_, ok := processed[slot.EcdsaAddress]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tprocessed[slot.EcdsaAddress] = struct{}{}\n\t\t\t\t\t\twrapper := state.GetStakingInfo(slot.EcdsaAddress)\n\t\t\t\t\t\twrapper.LastEpochInCommittee = newShardState.Epoch\n\n\t\t\t\t\t\tif err := state.UpdateStakingInfo(slot.EcdsaAddress, wrapper); err != nil {\n\t\t\t\t\t\t\treturn nil, nil, ctxerror.New(\"[Finalize] failed update validator info\").WithCause(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\theader.SetRoot(state.IntermediateRoot(chain.Config().IsS3(header.Epoch())))\n\treturn types.NewBlock(header, txs, receipts, outcxs, incxs, stks), payout, nil\n}", "func (c *ClaimPayment) TotalDue() decimal.Decimal {\n\ttotalDue := decimal.Zero\n\tfor _, sc := range c.ClaimsPayed {\n\t\ttotalDue = totalDue.Add(sc.EventSlot.Cost)\n\t}\n\treturn totalDue\n}", "func (pva PeriodicVestingAccount) GetVestingCoins(blockTime time.Time) sdk.Coins {\n\treturn pva.OriginalVesting.Sub(pva.GetVestedCoins(blockTime))\n}", "func FixFreezeLookupMigration(db *IndexerDb, state *MigrationState) error {\n\t// Technically with this query no transactions are needed, and the accounting state doesn't need to be locked.\n\tupdateQuery := \"INSERT INTO txn_participation (addr, round, intra) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING\"\n\tquery := fmt.Sprintf(\"select decode(txn.txn->'txn'->>'fadd','base64'),round,intra from txn where typeenum = %d AND txn.txn->'txn'->'snd' != txn.txn->'txn'->'fadd'\", idb.TypeEnumAssetFreeze)\n\trows, err := db.db.Query(query)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to query transactions: %v\", err)\n\t}\n\tdefer rows.Close()\n\n\ttxprows := make([][]interface{}, 0)\n\n\t// Loop through all transactions and compute account data.\n\tdb.log.Print(\"loop through all freeze transactions\")\n\tfor rows.Next() {\n\t\tvar addr []byte\n\t\tvar round, intra uint64\n\t\terr = rows.Scan(&addr, &round, &intra)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error scanning row: %v\", err)\n\t\t}\n\n\t\ttxprows = append(txprows, []interface{}{addr, round, intra})\n\n\t\tif len(txprows) > 5000 {\n\t\t\terr = updateBatch(db, updateQuery, txprows)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"updating batch: %v\", err)\n\t\t\t}\n\t\t\ttxprows = txprows[:0]\n\t\t}\n\t}\n\n\tif rows.Err() != nil {\n\t\treturn fmt.Errorf(\"error while processing freeze transactions: %v\", rows.Err())\n\t}\n\n\t// Commit any leftovers\n\tif len(txprows) > 0 {\n\t\terr = updateBatch(db, updateQuery, txprows)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"updating batch: %v\", err)\n\t\t}\n\t}\n\n\t// Update migration state\n\treturn upsertMigrationState(db, state, true)\n}", "func calcHostRemoveCriteria(info storage.HostInfo, currentBlockHeight uint64) float64 {\n\ttimeDiff := float64(currentBlockHeight - info.FirstSeen)\n\tcriteria := uptimeCap - (uptimeCap-critIntercept)/(timeDiff/float64(critRemoveBase)+1)\n\treturn criteria\n}", "func (e *Event) CalculateTotalFee() {\n\tvar total float64\n\n\tfor _, reservation := range e.Reservations {\n\t\ttotal += reservation.totalFee()\n\t}\n\n\te.TotalFee = total\n}", "func (_DogsOfRome *DogsOfRomeCallerSession) Balance(arg0 common.Address) (*big.Int, error) {\n\treturn _DogsOfRome.Contract.Balance(&_DogsOfRome.CallOpts, arg0)\n}", "func (a *Account) CalculateBalance(confirms int) (btcutil.Amount, error) {\n\trpcc, err := accessClient()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tbs, err := rpcc.BlockStamp()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn a.TxStore.Balance(confirms, bs.Height)\n}", "func (b *rpcVestingBalance) unbonding() (sdk.Coins, sdk.Coins, error) {\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\tunbondingFree := sdk.MinInt(delegatedFree, unbonding)\n\tunbondingVesting := unbonding.Sub(unbondingFree)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(unbondingFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(unbondingVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func TestDebitCampaignAccountWithEnoughRemainingDailyBudgetInMicroCents(t *testing.T) {\n\tb := NewRedisBanker(testDataAccess)\n\tcp := NewRedisCampaignProvider(testDataAccess, b)\n\n\tcampaignId := int64(313)\n\tbidCpmInMicroCents := int64(100)\n\tdailyBudgetInMicroCents := int64(100)\n\ttarget := rtb.Target{Type: rtb.Placement, Value: \"Words With Friends 2 iPad\"}\n\ttargets := []rtb.Target{target}\n\n\tdailyBudgetExpiration := time.Now().UTC().AddDate(0, 0, 1)\n\n\tamount := int64(32)\n\n\tcp.CreateCampaign(campaignId, bidCpmInMicroCents, dailyBudgetInMicroCents, targets)\n\n\texpectedRemainingDailyBudgetInMicroCents := dailyBudgetInMicroCents - amount\n\n\tb.SetRemainingDailyBudgetInMicroCents(campaignId, dailyBudgetInMicroCents, dailyBudgetExpiration)\n\n\tresult, err := cp.DebitCampaign(campaignId, amount, dailyBudgetExpiration)\n\n\tupdatedRemainingDailyBudgetInMicroCents := b.RemainingDailyBudgetInMicroCents(campaignId)\n\n\tif err != nil {\n\t\tt.Fail()\n\t}\n\n\tif result != expectedRemainingDailyBudgetInMicroCents {\n\t\tt.Fail()\n\t}\n\n\tif updatedRemainingDailyBudgetInMicroCents != expectedRemainingDailyBudgetInMicroCents {\n\t\tt.Fail()\n\t}\n}", "func GetBlockCumulativeGas(clientCtx client.Context, block *tmtypes.Block, idx int) uint64 {\n\tvar gasUsed uint64\n\ttxDecoder := clientCtx.TxConfig.TxDecoder()\n\n\tfor i := 0; i < idx && i < len(block.Txs); i++ {\n\t\ttxi, err := txDecoder(block.Txs[i])\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch tx := txi.(type) {\n\t\tcase *evmtypes.MsgEthereumTx:\n\t\t\tgasUsed += tx.GetGas()\n\t\tcase sdk.FeeTx:\n\t\t\tgasUsed += tx.GetGas()\n\t\t}\n\t}\n\treturn gasUsed\n}", "func (s *Store) Balance(minConf int, chainHeight int32) int64 {\n\tbal := int64(0)\n\tfor _, rt := range s.unspent {\n\t\tif confirmed(minConf, rt.Height(), chainHeight) {\n\t\t\ttx := s.txs[rt.blockTx()]\n\t\t\tmsgTx := tx.MsgTx()\n\t\t\ttxOut := msgTx.TxOut[rt.outpoint.Index]\n\t\t\tbal += txOut.Value\n\t\t}\n\t}\n\treturn bal\n}", "func (a *Account) CalculateBalance(confirms int) float64 {\n\tbs, err := GetCurBlock()\n\tif bs.Height == int32(btcutil.BlockHeightUnknown) || err != nil {\n\t\treturn 0.\n\t}\n\n\tbal := a.TxStore.Balance(confirms, bs.Height)\n\treturn float64(bal) / float64(btcutil.SatoshiPerBitcoin)\n}" ]
[ "0.6719768", "0.5626019", "0.5324699", "0.52189773", "0.5140744", "0.50596994", "0.5059033", "0.504977", "0.48822775", "0.48712832", "0.4870118", "0.48615333", "0.48471743", "0.4828697", "0.48089796", "0.4786879", "0.47522268", "0.4720129", "0.47145593", "0.47144145", "0.4701087", "0.46928984", "0.4690911", "0.46656278", "0.46534956", "0.46191686", "0.4610419", "0.46066105", "0.4583699", "0.45719275", "0.4566916", "0.45563477", "0.45557", "0.45552716", "0.4538513", "0.45368183", "0.45175794", "0.45020607", "0.4484064", "0.44784787", "0.44721258", "0.44609022", "0.44390386", "0.44390386", "0.4432514", "0.44055024", "0.43981206", "0.43944976", "0.43932492", "0.43769056", "0.4371576", "0.4370408", "0.43625018", "0.43522725", "0.43513757", "0.43500715", "0.43459055", "0.43447885", "0.43431884", "0.43398416", "0.43331942", "0.4315339", "0.43148404", "0.43121624", "0.43113363", "0.43068358", "0.4303899", "0.42985645", "0.4296866", "0.4288285", "0.4283617", "0.4281233", "0.4273122", "0.42724922", "0.42704847", "0.42652234", "0.4264584", "0.4262074", "0.42611495", "0.42578867", "0.4253606", "0.42450407", "0.42388657", "0.4231197", "0.4223479", "0.42224342", "0.42212832", "0.4202203", "0.42013258", "0.41999215", "0.41969192", "0.41968453", "0.41941792", "0.4191857", "0.41916093", "0.41892928", "0.4186268", "0.41820365", "0.41803595", "0.4175398" ]
0.80608404
0
updateDelegation returns an account with its delegation bookkeeping modified for clawback, given the current disposition of the account's bank and staking state. Also returns the modified amount to claw back. Computation steps: first, compute the total amount in bonded and unbonding states, used for BaseAccount bookkeeping; based on the old bookkeeping, determine the amount lost to slashing since origin; clip the amount to claw back to be at most the full funds in the account; first claw back the unbonded funds, then go after what's delegated; to the remaining delegated amount, add what's slashed; the "encumbered" (locked up and/or vesting) amount of this goes in DV; the remainder of the new delegated amount goes in DF.
func (va *ClawbackVestingAccount) updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded sdk.Coins) sdk.Coins { delegated := bonded.Add(unbonding...) oldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...) slashed := oldDelegated.Sub(coinsMin(delegated, oldDelegated)) total := delegated.Add(unbonded...) toClawBack = coinsMin(toClawBack, total) // might have been slashed newDelegated := coinsMin(delegated, total.Sub(toClawBack)).Add(slashed...) va.DelegatedVesting = coinsMin(encumbered, newDelegated) va.DelegatedFree = newDelegated.Sub(va.DelegatedVesting) return toClawBack }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (k Keeper) TransferDelegation(ctx sdk.Context, valAddr sdk.ValAddress, fromDelegator, toDelegator sdk.AccAddress, shares sdk.Dec) (sdk.Dec, error) {\n\t// Redelegations link a delegation to it's previous validator so slashes are propagated to the new validator.\n\t// If the delegation is transferred to a new owner, the redelegation object must be updated.\n\t// For expediency all transfers with redelegations are blocked.\n\tif k.stakingKeeper.HasReceivingRedelegation(ctx, fromDelegator, valAddr) {\n\t\treturn sdk.Dec{}, types.ErrRedelegationsNotCompleted\n\t}\n\n\tif shares.IsNil() || shares.LT(sdk.ZeroDec()) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"nil or negative shares\")\n\t}\n\tif shares.Equal(sdk.ZeroDec()) {\n\t\t// Block 0 transfers to reduce edge cases.\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrUntransferableShares, \"zero shares\")\n\t}\n\n\tfromDelegation, found := k.stakingKeeper.GetDelegation(ctx, fromDelegator, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoDelegatorForAddress\n\t}\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// Prevent validators from reducing their self delegation below the min.\n\tisValidatorOperator := fromDelegator.Equals(valAddr)\n\tif isValidatorOperator {\n\t\tif isBelowMinSelfDelegation(validator, fromDelegation.Shares.Sub(shares)) {\n\t\t\treturn sdk.Dec{}, types.ErrSelfDelegationBelowMinimum\n\t\t}\n\t}\n\n\treturnAmount, err := k.fastUndelegate(ctx, valAddr, fromDelegator, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\tif err := k.bankKeeper.SendCoins(ctx, fromDelegator, toDelegator, returnCoins); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treceivedShares, err := k.delegateFromAccount(ctx, valAddr, toDelegator, returnAmount)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\treturn receivedShares, nil\n}", "func consolidateDelegations(ctx contract.Context, validator, delegator *types.Address) (*Delegation, []*Delegation, int, error) {\n\t// cycle through all delegations and delete those which are BONDED and\n\t// unlocked while accumulating their amounts\n\tdelegations, err := returnMatchingDelegations(ctx, validator, delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\tunconsolidatedDelegationsCount := 0\n\ttotalDelegationAmount := common.BigZero()\n\tvar consolidatedDelegations []*Delegation\n\tfor _, delegation := range delegations {\n\t\tif delegation.LockTime > uint64(ctx.Now().Unix()) || delegation.State != BONDED {\n\t\t\tunconsolidatedDelegationsCount++\n\t\t\tcontinue\n\t\t}\n\n\t\ttotalDelegationAmount.Add(totalDelegationAmount, &delegation.Amount.Value)\n\t\tconsolidatedDelegations = append(consolidatedDelegations, delegation)\n\n\t\tif err = DeleteDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, nil, -1, err\n\t\t}\n\t}\n\n\tindex, err := GetNextDelegationIndex(ctx, *validator, *delegator)\n\tif err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\n\t// create new conolidated delegation\n\tdelegation := &Delegation{\n\t\tValidator: validator,\n\t\tDelegator: delegator,\n\t\tAmount: &types.BigUInt{Value: *totalDelegationAmount},\n\t\tUpdateAmount: loom.BigZeroPB(),\n\t\tLocktimeTier: 0,\n\t\tLockTime: 0,\n\t\tState: BONDED,\n\t\tIndex: index,\n\t}\n\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\treturn nil, nil, -1, err\n\t}\n\treturn delegation, consolidatedDelegations, unconsolidatedDelegationsCount, nil\n}", "func (bva *BaseVestingAccount) TrackDelegation(balance, vestingCoins, amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\tbaseAmt := balance.AmountOf(coin.Denom)\n\t\tvestingAmt := vestingCoins.AmountOf(coin.Denom)\n\t\tdelVestingAmt := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// Panic if the delegation amount is zero or if the base coins does not\n\t\t// exceed the desired delegation amount.\n\t\tif coin.Amount.IsZero() || baseAmt.LT(coin.Amount) {\n\t\t\tpanic(\"delegation attempt with zero coins or insufficient funds\")\n\t\t}\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(max(V - DV, 0), D)\n\t\t// Y := D - X\n\t\tx := sdk.MinInt(sdk.MaxInt(vestingAmt.Sub(delVestingAmt), sdk.ZeroInt()), coin.Amount)\n\t\ty := coin.Amount.Sub(x)\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Add(xCoin)\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Add(yCoin)\n\t\t}\n\t}\n}", "func (_TokensNetwork *TokensNetworkTransactor) UpdateBalanceProofDelegate(opts *bind.TransactOpts, token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"updateBalanceProofDelegate\", token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (k Keeper) WithdrawDelegationRewards(ctx sdk.Context, delAddr chainTypes.AccountID, valAddr chainTypes.AccountID) (Coins, error) {\n\n\tval := k.stakingKeeper.Validator(ctx, valAddr)\n\tctx.Logger().Debug(\"WithdrawDelegationRewards\", \"val:\", val)\n\tif val == nil {\n\t\treturn nil, types.ErrNoValidatorDistInfo\n\t}\n\n\tdel := k.stakingKeeper.Delegation(ctx, delAddr, valAddr)\n\tctx.Logger().Debug(\"WithdrawDelegationRewards\", \"del:\", del)\n\tif del == nil {\n\t\treturn nil, types.ErrEmptyDelegationDistInfo\n\t}\n\n\t// withdraw rewards\n\trewards, err := k.withdrawDelegationRewards(ctx, val, del)\n\tif err != nil {\n\t\tctx.Logger().Debug(\"WithdrawDelegationRewards\", \"err:\", err)\n\t\treturn nil, err\n\t}\n\tctx.Logger().Debug(\"WithdrawDelegationRewards\", \"rewards:\", rewards)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeWithdrawRewards,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, rewards.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, valAddr.String()),\n\t\t),\n\t)\n\n\t// reinitialize the delegation\n\tk.initializeDelegation(ctx, valAddr, delAddr)\n\treturn rewards, nil\n}", "func (va *ClawbackVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tva.BaseVestingAccount.TrackDelegation(balance, va.GetVestingCoins(blockTime), amount)\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (_TokensNetwork *TokensNetworkSession) UpdateBalanceProofDelegate(token common.Address, partner common.Address, participant common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte, participant_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProofDelegate(&_TokensNetwork.TransactOpts, token, partner, participant, transferred_amount, locksroot, nonce, additional_hash, partner_signature, participant_signature)\n}", "func (dva *DelayedVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tdva.BaseVestingAccount.TrackDelegation(balance, dva.GetVestingCoins(blockTime), amount)\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateDelegatedAmount(opts *bind.TransactOpts, holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateDelegatedAmount\", holder)\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func (k msgServer) CancelUnbondingDelegation(goCtx context.Context, msg *types.MsgCancelUnbondingDelegation) (*types.MsgCancelUnbondingDelegationResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\tvalAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\t// In some situations, the exchange rate becomes invalid, e.g. if\n\t// Validator loses all tokens due to slashing. In this case,\n\t// make all future delegations invalid.\n\tif validator.InvalidExRate() {\n\t\treturn nil, types.ErrDelegatorShareExRateInvalid\n\t}\n\n\tif validator.IsJailed() {\n\t\treturn nil, types.ErrValidatorJailed\n\t}\n\n\tubd, found := k.GetUnbondingDelegation(ctx, delegatorAddress, valAddr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"unbonding delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this undelegation was from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be incremented\n\ttokens := msg.Amount.Amount\n\tshares, err := validator.SharesFromTokens(tokens)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar (\n\t\tunbondEntry types.UnbondingDelegationEntry\n\t\tunbondEntryIndex int64 = -1\n\t)\n\n\tfor i, entry := range ubd.Entries {\n\t\tif entry.CreationHeight == msg.CreationHeight {\n\t\t\tunbondEntry = entry\n\t\t\tunbondEntryIndex = int64(i)\n\t\t\tbreak\n\t\t}\n\t}\n\tif unbondEntryIndex == -1 {\n\t\treturn nil, sdkerrors.ErrNotFound.Wrapf(\"unbonding delegation entry is not found at block height %d\", msg.CreationHeight)\n\t}\n\n\tif unbondEntry.Balance.LT(msg.Amount.Amount) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"amount is greater than the unbonding delegation entry balance\")\n\t}\n\n\tif unbondEntry.CompletionTime.Before(ctx.BlockTime()) {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(\"unbonding delegation is already processed\")\n\t}\n\n\t// delegate back the unbonding delegation amount to the validator\n\t_, err = k.Keeper.Delegate(ctx, delegatorAddress, msg.Amount.Amount, types.Unbonding, validator, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tamount := unbondEntry.Balance.Sub(msg.Amount.Amount)\n\tif amount.IsZero() {\n\t\tubd.RemoveEntry(unbondEntryIndex)\n\t} else {\n\t\t// update the unbondingDelegationEntryBalance and InitialBalance for ubd entry\n\t\tunbondEntry.Balance = amount\n\t\tunbondEntry.InitialBalance = unbondEntry.InitialBalance.Sub(msg.Amount.Amount)\n\t\tubd.Entries[unbondEntryIndex] = unbondEntry\n\t}\n\n\t// set the unbonding delegation or remove it if there are no more entries\n\tif len(ubd.Entries) == 0 {\n\t\tk.RemoveUnbondingDelegation(ctx, ubd)\n\t} else {\n\t\tk.SetUnbondingDelegation(ctx, ubd)\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeCancelUnbondingDelegation,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyDelegator, msg.DelegatorAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCreationHeight, strconv.FormatInt(msg.CreationHeight, 10)),\n\t\t),\n\t)\n\n\treturn &types.MsgCancelUnbondingDelegationResponse{}, nil\n}", "func (cva *ContinuousVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tcva.BaseVestingAccount.TrackDelegation(balance, cva.GetVestingCoins(blockTime), amount)\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateDelegatedAmount(holder common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateDelegatedAmount(&_DelegationController.TransactOpts, holder)\n}", "func (pva *PeriodicVestingAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tpva.BaseVestingAccount.TrackDelegation(balance, pva.GetVestingCoins(blockTime), amount)\n}", "func (plva *PermanentLockedAccount) TrackDelegation(blockTime time.Time, balance, amount sdk.Coins) {\n\tplva.BaseVestingAccount.TrackDelegation(balance, plva.OriginalVesting, amount)\n}", "func (acc *Account) delegationsTotal() (amount *big.Int, inWithdraw *big.Int, rewards *big.Int, err error) {\n\t// pull all the delegations of the account\n\tlist, err := repository.R().DelegationsByAddressAll(&acc.Address)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// prep containers for calculation and loop all delegations found\n\tamount = new(big.Int)\n\trewards = new(big.Int)\n\tinWithdraw = new(big.Int)\n\tfor _, dlg := range list {\n\t\t// any active delegated amount?\n\t\tif 0 < dlg.AmountDelegated.ToInt().Uint64() {\n\t\t\tamount = new(big.Int).Add(amount, dlg.AmountDelegated.ToInt())\n\t\t}\n\n\t\t// get pending rewards for this delegation (can be stashed)\n\t\trw, err := repository.R().PendingRewards(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// any rewards?\n\t\tif 0 < rw.Amount.ToInt().Uint64() {\n\t\t\trewards = new(big.Int).Add(rewards, rw.Amount.ToInt())\n\t\t}\n\n\t\t// get pending withdrawals\n\t\twd, err := repository.R().WithdrawRequestsPendingTotal(&acc.Address, dlg.ToStakerId)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// add pending withdrawals value\n\t\tif 0 < wd.Uint64() {\n\t\t\tinWithdraw = new(big.Int).Add(inWithdraw, wd)\n\t\t}\n\t}\n\n\treturn amount, rewards, inWithdraw, nil\n}", "func distributeDelegatorRewards(ctx contract.Context, cachedDelegations *CachedDposStorage, formerValidatorTotals map[string]loom.BigUInt, delegatorRewards map[string]*loom.BigUInt, distributedRewards *loom.BigUInt) (map[string]*loom.BigUInt, error) {\n\tnewDelegationTotals := make(map[string]*loom.BigUInt)\n\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize delegation totals with whitelist amounts\n\tfor _, candidate := range candidates {\n\t\tstatistic, _ := GetStatistic(ctx, loom.UnmarshalAddressPB(candidate.Address))\n\n\t\tif statistic != nil && statistic.WhitelistAmount != nil && !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\tvalidatorKey := loom.UnmarshalAddressPB(statistic.Address).String()\n\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\tnewDelegationTotals[validatorKey] = &amount\n\t\t}\n\t}\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar currentDelegations = make(DelegationList, len(delegations))\n\tcopy(currentDelegations, delegations)\n\tfor _, d := range currentDelegations {\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalidatorKey := loom.UnmarshalAddressPB(delegation.Validator).String()\n\n\t\t// Do not distribute rewards to delegators of the Limbo validator\n\t\t// NOTE: because all delegations are sorted in reverse index order, the\n\t\t// 0-index delegation (for rewards) is handled last. Therefore, all\n\t\t// increases to reward delegations will be reflected in newDelegation\n\t\t// totals that are computed at the end of this for loop. (We do this to\n\t\t// avoid looping over all delegations twice)\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\t// allocating validator distributions to delegators\n\t\t\t// based on former validator delegation totals\n\t\t\tdelegationTotal := formerValidatorTotals[validatorKey]\n\t\t\trewardsTotal := delegatorRewards[validatorKey]\n\t\t\tif rewardsTotal != nil {\n\t\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\t\tdelegatorDistribution := calculateShare(weightedDelegation, delegationTotal, *rewardsTotal)\n\t\t\t\t// increase a delegator's distribution\n\t\t\t\tdistributedRewards.Add(distributedRewards, &delegatorDistribution)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, delegation.Validator, delegation.Delegator, delegatorDistribution)\n\n\t\t\t\t// If the reward delegation is updated by the\n\t\t\t\t// IncreaseRewardDelegation command, we must be sure to use this\n\t\t\t\t// updated version in the rest of the loop. No other delegations\n\t\t\t\t// (non-rewards) have the possibility of being updated outside\n\t\t\t\t// of this loop.\n\t\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) && d.Index == REWARD_DELEGATION_INDEX {\n\t\t\t\t\tdelegation, err = GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\tif err == contract.ErrNotFound {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdatedAmount := common.BigZero()\n\t\tif delegation.State == BONDING {\n\t\t\tupdatedAmount.Add(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t} else if delegation.State == UNBONDING {\n\t\t\tupdatedAmount.Sub(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t\tcoin, err := loadCoin(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\terr = coin.Transfer(loom.UnmarshalAddressPB(delegation.Delegator), &delegation.UpdateAmount.Value)\n\t\t\tif err != nil {\n\t\t\t\ttransferFromErr := fmt.Sprintf(\"Failed coin Transfer - distributeDelegatorRewards, %v, %s\", delegation.Delegator.String(), delegation.UpdateAmount.Value.String())\n\t\t\t\treturn nil, logDposError(ctx, err, transferFromErr)\n\t\t\t}\n\t\t} else if delegation.State == REDELEGATING {\n\t\t\tif err = cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Validator = delegation.UpdateValidator\n\t\t\tdelegation.Amount = delegation.UpdateAmount\n\t\t\tdelegation.LocktimeTier = delegation.UpdateLocktimeTier\n\n\t\t\tindex, err := GetNextDelegationIndex(ctx, *delegation.Validator, *delegation.Delegator)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Index = index\n\n\t\t\tvalidatorKey = loom.UnmarshalAddressPB(delegation.Validator).String()\n\t\t}\n\n\t\t// Delete any delegation whose full amount has been unbonded. In all\n\t\t// other cases, update the delegation state to BONDED and reset its\n\t\t// UpdateAmount\n\t\tif common.IsZero(delegation.Amount.Value) && delegation.State == UNBONDING {\n\t\t\tif err := cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\t// After a delegation update, zero out UpdateAmount\n\t\t\tdelegation.UpdateAmount = loom.BigZeroPB()\n\t\t\tdelegation.State = BONDED\n\n\t\t\tresetDelegationIfExpired(ctx, delegation)\n\t\t\tif err := cachedDelegations.SetDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Calculate delegation totals for all validators except the Limbo\n\t\t// validator\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\tnewTotal := common.BigZero()\n\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\tnewTotal.Add(newTotal, &weightedDelegation)\n\t\t\tif newDelegationTotals[validatorKey] != nil {\n\t\t\t\tnewTotal.Add(newTotal, newDelegationTotals[validatorKey])\n\t\t\t}\n\t\t\tnewDelegationTotals[validatorKey] = newTotal\n\t\t}\n\t}\n\n\treturn newDelegationTotals, nil\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV + DF by capping slashed at the current unvested amount\n\tunvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime()))\n\tnewSlashed := coinsMin(slashed, unvested)\n\tnewDelegated := delegated.Add(newSlashed...)\n\n\t// modify schedules for the new grant\n\tnewLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods)\n\tnewVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime,\n\t\tva.GetVestingPeriods(), grantVestingPeriods)\n\tif newLockupStart != newVestingStart {\n\t\tpanic(\"bad start time calculation\")\n\t}\n\tva.StartTime = newLockupStart\n\tva.EndTime = max64(newLockupEnd, newVestingEnd)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\tva.OriginalVesting = va.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newDelegated\n\tunvested2 := va.GetVestingCoins(ctx.BlockTime())\n\tva.DelegatedVesting = coinsMin(newDelegated, unvested2)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n}", "func TestSlashWithRedelegation(t *testing.T) {\n\tapp, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)\n\tconsAddr := sdk.ConsAddress(PKs[0].Address())\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\tbondDenom := app.StakingKeeper.BondDenom(ctx)\n\n\t// set a redelegation\n\trdTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 6)\n\trd := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11,\n\t\ttime.Unix(0, 0), rdTokens, rdTokens.ToDec())\n\tapp.StakingKeeper.SetRedelegation(ctx, rd)\n\n\t// set the associated delegation\n\tdel := types.NewDelegation(addrDels[0], addrVals[1], rdTokens.ToDec())\n\tapp.StakingKeeper.SetDelegation(ctx, del)\n\n\t// update bonded tokens\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)\n\trdCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, rdTokens.MulRaw(2)))\n\n\trequire.NoError(t, simapp.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), rdCoins))\n\n\tapp.AccountKeeper.SetModuleAccount(ctx, bondedPool)\n\n\toldBonded := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\toldNotBonded := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\n\t// slash validator\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction) })\n\tburnAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(fraction).TruncateInt()\n\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\t// burn bonded tokens from only from delegations\n\tbondedPoolBalance := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\t// power decreased by 2 - 4 stake originally bonded at the time of infraction\n\t// was still bonded at the time of discovery and was slashed by half, 4 stake\n\t// bonded at the time of discovery hadn't been bonded at the time of infraction\n\t// and wasn't slashed\n\trequire.Equal(t, int64(8), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash the validator again\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\tburnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 7)\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\t// seven bonded tokens burned\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\t// power decreased by 4\n\trequire.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash the validator again, by 100%\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\n\tburnAmount = app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(sdk.OneDec()).TruncateInt()\n\tburnAmount = burnAmount.Sub(sdk.OneDec().MulInt(rdTokens).TruncateInt())\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnAmount), bondedPoolBalance))\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\toldBonded = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// apply TM updates\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)\n\t// read updated validator\n\t// validator decreased to zero power, should be in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n\n\t// slash the validator again, by 100%\n\t// no stake remains to be slashed\n\tctx = ctx.WithBlockHeight(12)\n\t// validator still in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n\n\trequire.NotPanics(t, func() { app.StakingKeeper.Slash(ctx, consAddr, 10, 10, sdk.OneDec()) })\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\tbondedPoolBalance = app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded, bondedPoolBalance))\n\tnotBondedPoolBalance = app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded, notBondedPoolBalance))\n\n\t// read updating redelegation\n\trd, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rd.Entries, 1)\n\t// read updated validator\n\t// power still zero, still in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n}", "func TestSlashWithUnbondingDelegation(t *testing.T) {\n\tapp, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)\n\n\tconsAddr := sdk.ConsAddress(PKs[0].Address())\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\n\t// set an unbonding delegation with expiration timestamp beyond which the\n\t// unbonding delegation shouldn't be slashed\n\tubdTokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 4)\n\tubd := types.NewUnbondingDelegation(addrDels[0], addrVals[0], 11, time.Unix(0, 0), ubdTokens)\n\tapp.StakingKeeper.SetUnbondingDelegation(ctx, ubd)\n\n\t// slash validator for the first time\n\tctx = ctx.WithBlockHeight(12)\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\toldBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\n\tvalidator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 10, 10, fraction)\n\n\t// end block\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, 1)\n\n\t// read updating unbonding delegation\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance decreased\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 2), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned\n\tnewBondedPoolBalances := app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens := oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 3), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 - 6 stake originally bonded at the time of infraction\n\t// was still bonded at the time of discovery and was slashed by half, 4 stake\n\t// bonded at the time of discovery hadn't been bonded at the time of infraction\n\t// and wasn't slashed\n\trequire.Equal(t, int64(7), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance decreased again\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned again\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 6), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 again\n\trequire.Equal(t, int64(4), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\t// all originally bonded stake has been slashed, so this will have no effect\n\t// on the unbonding delegation, but it will slash stake bonded since the infraction\n\t// this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance unchanged\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// bonded tokens burned again\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 9), diffTokens)\n\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.True(t, found)\n\n\t// power decreased by 3 again\n\trequire.Equal(t, int64(1), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n\n\t// slash validator again\n\t// all originally bonded stake has been slashed, so this will have no effect\n\t// on the unbonding delegation, but it will slash stake bonded since the infraction\n\t// this may not be the desirable behaviour, ref https://github.com/cosmos/cosmos-sdk/issues/1440\n\tctx = ctx.WithBlockHeight(13)\n\tapp.StakingKeeper.Slash(ctx, consAddr, 9, 10, fraction)\n\n\tubd, found = app.StakingKeeper.GetUnbondingDelegation(ctx, addrDels[0], addrVals[0])\n\trequire.True(t, found)\n\trequire.Len(t, ubd.Entries, 1)\n\n\t// balance unchanged\n\trequire.Equal(t, sdk.NewInt(0), ubd.Entries[0].Balance)\n\n\t// just 1 bonded token burned again since that's all the validator now has\n\tnewBondedPoolBalances = app.BankKeeper.GetAllBalances(ctx, bondedPool.GetAddress())\n\tdiffTokens = oldBondedPoolBalances.Sub(newBondedPoolBalances).AmountOf(app.StakingKeeper.BondDenom(ctx))\n\trequire.Equal(t, app.StakingKeeper.TokensFromConsensusPower(ctx, 10), diffTokens)\n\n\t// apply TM updates\n\tapplyValidatorSetUpdates(t, ctx, app.StakingKeeper, -1)\n\n\t// read updated validator\n\t// power decreased by 1 again, validator is out of stake\n\t// validator should be in unbonding period\n\tvalidator, _ = app.StakingKeeper.GetValidatorByConsAddr(ctx, consAddr)\n\trequire.Equal(t, validator.GetStatus(), types.Unbonding)\n}", "func (k msgServer) Delegate(goCtx context.Context, msg *types.MsgDelegate) (*types.MsgDelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\tvalAddr, valErr := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif valErr != nil {\n\t\treturn nil, valErr\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\ttokens := msg.Amount.Amount\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), it cannot exceed the global or validator bond cap\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tshares, err := validator.SharesFromTokens(tokens)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseTotalLiquidStakedTokens(ctx, tokens, false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// NOTE: source funds are always unbonded\n\tnewShares, err := k.Keeper.Delegate(ctx, delegatorAddress, tokens, types.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"delegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeDelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyNewShares, newShares.String()),\n\t\t),\n\t})\n\n\treturn &types.MsgDelegateResponse{}, nil\n}", "func (va *ClawbackVestingAccount) clawback(ctx sdk.Context, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) error {\n\t// Compute the clawback based on the account state only, and update account\n\ttoClawBack := va.computeClawback(ctx.BlockTime().Unix())\n\tif toClawBack.IsZero() {\n\t\treturn nil\n\t}\n\taddr := va.GetAddress()\n\tbondDenom := sk.BondDenom(ctx)\n\n\t// Compute the clawback based on bank balance and delegation, and update account\n\tencumbered := va.GetVestingCoins(ctx.BlockTime())\n\tbondedAmt := sk.GetDelegatorBonded(ctx, addr)\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, addr)\n\tbonded := sdk.NewCoins(sdk.NewCoin(bondDenom, bondedAmt))\n\tunbonding := sdk.NewCoins(sdk.NewCoin(bondDenom, unbondingAmt))\n\tunbonded := bk.GetAllBalances(ctx, addr)\n\ttoClawBack = va.updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded)\n\n\t// Write now now so that the bank module sees unvested tokens are unlocked.\n\t// Note that all store writes are aborted if there is a panic, so there is\n\t// no danger in writing incomplete results.\n\tak.SetAccount(ctx, va)\n\n\t// Now that future vesting events (and associated lockup) are removed,\n\t// the balance of the account is unlocked and can be freely transferred.\n\tspendable := bk.SpendableCoins(ctx, addr)\n\ttoXfer := coinsMin(toClawBack, spendable)\n\terr := bk.SendCoins(ctx, addr, dest, toXfer)\n\tif err != nil {\n\t\treturn err // shouldn't happen, given spendable check\n\t}\n\ttoClawBack = toClawBack.Sub(toXfer)\n\n\t// We need to traverse the staking data structures to update the\n\t// vesting account bookkeeping, and to recover more funds if necessary.\n\t// Staking is the only way unvested tokens should be missing from the bank balance.\n\n\t// If we need more, transfer UnbondingDelegations.\n\twant := toClawBack.AmountOf(bondDenom)\n\tunbondings := sk.GetUnbondingDelegations(ctx, addr, math.MaxUint16)\n\tfor _, unbonding := range unbondings {\n\t\tvalAddr, err := sdk.ValAddressFromBech32(unbonding.ValidatorAddress)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttransferred := sk.TransferUnbonding(ctx, addr, dest, valAddr, want)\n\t\twant = want.Sub(transferred)\n\t\tif !want.IsPositive() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If we need more, transfer Delegations.\n\tif want.IsPositive() {\n\t\tdelegations := sk.GetDelegatorDelegations(ctx, addr, math.MaxUint16)\n\t\tfor _, delegation := range delegations {\n\t\t\tvalidatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // shouldn't happen\n\t\t\t}\n\t\t\tvalidator, found := sk.GetValidator(ctx, validatorAddr)\n\t\t\tif !found {\n\t\t\t\t// validator has been removed\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twantShares, err := validator.SharesFromTokensTruncated(want)\n\t\t\tif err != nil {\n\t\t\t\t// validator has no tokens\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttransferredShares := sk.TransferDelegation(ctx, addr, dest, delegation.GetValidatorAddr(), wantShares)\n\t\t\t// to be conservative in what we're clawing back, round transferred shares up\n\t\t\ttransferred := validator.TokensFromSharesRoundUp(transferredShares).RoundInt()\n\t\t\twant = want.Sub(transferred)\n\t\t\tif !want.IsPositive() {\n\t\t\t\t// Could be slightly negative, due to rounding?\n\t\t\t\t// Don't think so, due to the precautions above.\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we've transferred everything and still haven't transferred the desired clawback amount,\n\t// then the account must have most some unvested tokens from slashing.\n\treturn nil\n}", "func (b *rpcVestingBalance) delegated() (sdk.Coins, sdk.Coins, error) {\n\tdelegatedCoins, err := b.totalDelegated()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tunbondingCoins, err := b.totalUnbondingDelegations()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdelegated := delegatedCoins.AmountOf(stakingDenom)\n\tunbonding := unbondingCoins.AmountOf(stakingDenom)\n\ttotalStaked := delegated.Add(unbonding)\n\tdelegatedFree := b.vacc.GetDelegatedFree().AmountOf(stakingDenom)\n\n\t// total number of staked and unbonding tokens considered to be liquid\n\ttotalFree := sdk.MinInt(totalStaked, delegatedFree)\n\t// any coins that are not considered liquid, are vesting up to a maximum of delegated\n\tstakedVesting := sdk.MinInt(totalStaked.Sub(totalFree), delegated)\n\t// staked free coins are left over\n\tstakedFree := delegated.Sub(stakedVesting)\n\n\tliquidCoins := sdk.NewCoins(newKavaCoin(stakedFree))\n\tvestingCoins := sdk.NewCoins(newKavaCoin(stakedVesting))\n\treturn liquidCoins, vestingCoins, nil\n}", "func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\n}", "func (k Keeper) BurnDerivative(ctx sdk.Context, delegatorAddr sdk.AccAddress, valAddr sdk.ValAddress, amount sdk.Coin) (sdk.Dec, error) {\n\n\tif amount.Denom != k.GetLiquidStakingTokenDenom(valAddr) {\n\t\treturn sdk.Dec{}, errorsmod.Wrap(types.ErrInvalidDenom, \"derivative denom does not match validator\")\n\t}\n\n\tif err := k.burnCoins(ctx, delegatorAddr, sdk.NewCoins(amount)); err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\tmodAcc := k.accountKeeper.GetModuleAccount(ctx, types.ModuleAccountName)\n\tshares := sdk.NewDecFromInt(amount.Amount)\n\treceivedShares, err := k.TransferDelegation(ctx, valAddr, modAcc.GetAddress(), delegatorAddr, shares)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeBurnDerivative,\n\t\t\tsdk.NewAttribute(types.AttributeKeyDelegator, delegatorAddr.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, valAddr.String()),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeySharesTransferred, shares.String()),\n\t\t),\n\t)\n\treturn receivedShares, nil\n}", "func (bva *BaseVestingAccount) TrackUndelegation(amount sdk.Coins) {\n\tfor _, coin := range amount {\n\t\t// panic if the undelegation amount is zero\n\t\tif coin.Amount.IsZero() {\n\t\t\tpanic(\"undelegation attempt with zero coins\")\n\t\t}\n\t\tdelegatedFree := bva.DelegatedFree.AmountOf(coin.Denom)\n\t\tdelegatedVesting := bva.DelegatedVesting.AmountOf(coin.Denom)\n\n\t\t// compute x and y per the specification, where:\n\t\t// X := min(DF, D)\n\t\t// Y := min(DV, D - X)\n\t\tx := sdk.MinInt(delegatedFree, coin.Amount)\n\t\ty := sdk.MinInt(delegatedVesting, coin.Amount.Sub(x))\n\n\t\tif !x.IsZero() {\n\t\t\txCoin := sdk.NewCoin(coin.Denom, x)\n\t\t\tbva.DelegatedFree = bva.DelegatedFree.Sub(sdk.Coins{xCoin})\n\t\t}\n\n\t\tif !y.IsZero() {\n\t\t\tyCoin := sdk.NewCoin(coin.Denom, y)\n\t\t\tbva.DelegatedVesting = bva.DelegatedVesting.Sub(sdk.Coins{yCoin})\n\t\t}\n\t}\n}", "func (vva *ValidatorVestingAccount) TrackDelegation(blockTime time.Time, amount sdk.Coins) {\n\tvva.BaseVestingAccount.TrackDelegation(vva.GetVestingCoins(blockTime), amount)\n}", "func bindDelegationController(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(DelegationControllerABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func (k Keeper) UpdateDelegatorsBeforeSlashing(ctx sdk.Context, valAddr sdk.ValAddress) {\n\tdelegations := k.stakingKeeper.GetValidatorDelegations(ctx, valAddr)\n\n\tdefaultCoin := coins.GetDefaultCoin()\n\n\tfor _, delegation := range delegations {\n\t\tk.SavePosmined(ctx, delegation.DelegatorAddress, defaultCoin)\n\t}\n}", "func (a *Accounting) callUpdateAccounting() (modules.AccountingInfo, error) {\n\tvar ai modules.AccountingInfo\n\n\t// Get Renter information\n\t//\n\t// NOTE: renter is optional so can be nil\n\tvar renterErr error\n\tif a.staticRenter != nil {\n\t\tvar spending modules.ContractorSpending\n\t\tspending, renterErr = a.staticRenter.PeriodSpending()\n\t\tif renterErr == nil {\n\t\t\t_, _, unspentUnallocated := spending.SpendingBreakdown()\n\t\t\tai.Renter.UnspentUnallocated = unspentUnallocated\n\t\t\tai.Renter.WithheldFunds = spending.WithheldFunds\n\t\t}\n\t}\n\n\t// Get Wallet information\n\tsc, sf, _, walletErr := a.staticWallet.ConfirmedBalance()\n\tif walletErr == nil {\n\t\tai.Wallet.ConfirmedSiacoinBalance = sc\n\t\tai.Wallet.ConfirmedSiafundBalance = sf\n\t}\n\n\t// Update the Accounting state\n\terr := errors.Compose(renterErr, walletErr)\n\tif err == nil {\n\t\ta.mu.Lock()\n\t\ta.persistence.Renter = ai.Renter\n\t\ta.persistence.Wallet = ai.Wallet\n\t\ta.persistence.Timestamp = time.Now().Unix()\n\t\ta.mu.Unlock()\n\t}\n\treturn ai, err\n}", "func updateAccountData(address types.Address, round uint32, assetID uint32, stxn types.SignedTxnWithAD, accountData *m7AccountData, assetDataMap map[uint32]createClose) {\n\t// Transactions are ordered most recent to oldest, so this makes sure created is set to the\n\t// oldest transaction.\n\taccountData.account.createdValid = true\n\taccountData.account.created = uint32(round)\n\n\t// When the account is closed rewards reset to zero.\n\t// Because transactions are newest to oldest, stop accumulating once we see a close.\n\tif !accountData.account.closedValid {\n\t\tif accounting.AccountCloseTxn(address, stxn) {\n\t\t\taccountData.account.closedValid = true\n\t\t\taccountData.account.closed = uint32(round)\n\n\t\t\tif !accountData.account.deletedValid {\n\t\t\t\taccountData.account.deletedValid = true\n\t\t\t\taccountData.account.deleted = true\n\t\t\t}\n\t\t} else {\n\t\t\tif !accountData.account.deletedValid {\n\t\t\t\taccountData.account.deletedValid = true\n\t\t\t\taccountData.account.deleted = false\n\t\t\t}\n\n\t\t\tif stxn.Txn.Sender == address {\n\t\t\t\taccountData.cumulativeRewards += stxn.ApplyData.SenderRewards\n\t\t\t}\n\n\t\t\tif stxn.Txn.Receiver == address {\n\t\t\t\taccountData.cumulativeRewards += stxn.ApplyData.ReceiverRewards\n\t\t\t}\n\n\t\t\tif stxn.Txn.CloseRemainderTo == address {\n\t\t\t\taccountData.cumulativeRewards += stxn.ApplyData.CloseRewards\n\t\t\t}\n\t\t}\n\t}\n\n\tif accounting.AssetCreateTxn(stxn) {\n\t\tmaybeInitializeAdditionalAccountData(accountData)\n\t\tcc := updateCreate(round, assetDataMap[assetID])\n\t\tassetDataMap[assetID] = cc\n\t\taccountData.additional.asset[assetID] = struct{}{}\n\t\t// Special handling of asset holding since creating and deleting an asset also creates and\n\t\t// deletes an asset holding for the creator, but a different manager address can delete an\n\t\t// asset.\n\t\taccountData.assetHolding[assetID] = cc\n\t}\n\n\tif accounting.AssetDestroyTxn(stxn) {\n\t\tassetDataMap[assetID] = updateClose(round, assetDataMap[assetID])\n\t}\n\n\tif accounting.AssetOptInTxn(stxn) {\n\t\taccountData.assetHolding[assetID] = updateCreate(round, accountData.assetHolding[assetID])\n\t}\n\n\tif accounting.AssetOptOutTxn(stxn) && (stxn.Txn.Sender == address) {\n\t\taccountData.assetHolding[assetID] = updateClose(round, accountData.assetHolding[assetID])\n\t}\n\n\tif accounting.AppCreateTxn(stxn) {\n\t\tmaybeInitializeAdditionalAccountData(accountData)\n\t\taccountData.additional.app[assetID] = updateCreate(round, accountData.additional.app[assetID])\n\t}\n\n\tif accounting.AppDestroyTxn(stxn) {\n\t\tmaybeInitializeAdditionalAccountData(accountData)\n\t\taccountData.additional.app[assetID] = updateClose(round, accountData.additional.app[assetID])\n\t}\n\n\tif accounting.AppOptInTxn(stxn) {\n\t\tmaybeInitializeAdditionalAccountData(accountData)\n\t\taccountData.additional.appLocal[assetID] =\n\t\t\tupdateCreate(round, accountData.additional.appLocal[assetID])\n\t}\n\n\tif accounting.AppOptOutTxn(stxn) {\n\t\tmaybeInitializeAdditionalAccountData(accountData)\n\t\taccountData.additional.appLocal[assetID] =\n\t\t\tupdateClose(round, accountData.additional.appLocal[assetID])\n\t}\n}", "func (k Keeper) Delegation(ctx context.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) (types.DelegationI, error) {\n\tbond, err := k.Delegations.Get(ctx, collections.Join(addrDel, addrVal))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bond, nil\n}", "func (del Delegation) AmountDelegated() hexutil.Big {\n\tif del.Delegation.AmountDelegated == nil {\n\t\treturn hexutil.Big{}\n\t}\n\treturn *del.Delegation.AmountDelegated\n}", "func (o OfflineNotaryRepository) AddDelegation(data.RoleName, []data.PublicKey, []string) error {\n\treturn nil\n}", "func (k Keeper) Delegation(ctx sdk.Context, addrDel sdk.AccAddress, addrVal sdk.ValAddress) exported.DelegationI {\n\treturn nil\n}", "func (_DelegationController *DelegationControllerSession) Confiscate(validatorId *big.Int, amount *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Confiscate(&_DelegationController.TransactOpts, validatorId, amount)\n}", "func CalculateDelegateNetPayout(delegatedContracts []DelegatedContract) []DelegatedContract{\n var delegateIndex int\n\n for index, delegate := range delegatedContracts{\n if (delegate.Delegate){\n delegateIndex = index\n }\n }\n\n for _, delegate := range delegatedContracts{\n if (!delegate.Delegate){\n delegatedContracts[delegateIndex].TotalPayout = delegatedContracts[delegateIndex].TotalPayout + delegate.Fee\n }\n }\n return delegatedContracts\n}", "func (t *ManageAccount) updateAccountBalance(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tvar jsonResp string\n\tvar err error\n\n\t//set amountPaid\n\tamountPaid := args[2]\n\n\t// input sanitation\n\tif len(args) != 4 {\n\t\terrMsg := \"{ \\\"message\\\" : \\\"Incorrect number of arguments. Expecting \\\"Customer Account Id, Service Provider Account Id, Amount paid\\\" and \\\" operation\\\" as an argument.\\\", \\\"code\\\" : \\\"503\\\"}\"\n\t\terr = stub.SetEvent(\"errEvent\", []byte(errMsg))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfmt.Println(errMsg)\t\n\t\treturn nil, errors.New(errMsg)\n\t}\n\n\tfmt.Println(\"Updating the account balance of\"+ args[0] + \" and \" + args[1])\n\t// convert string to float\n\t_amountPaid, _ := strconv.ParseFloat(amountPaid, 64)\n\toperation := args[3]\n\taccount := Account{}\n\tfor i := 0; i < 2; i++ {\n\t\taccountAsBytes, err := stub.GetState(args[i])\t\t\t\t\t\t\t\t\t//get the var from chaincode state\n\t\tif err != nil {\n\t\t\tjsonResp = \"{\\\"Error\\\":\\\"Failed to get state for \" + args[i] + \"\\\"}\"\n\t\t\treturn nil, errors.New(jsonResp)\n\t\t}\n\t\tjson.Unmarshal(accountAsBytes, &account)\n\t\tif account.AccountOwnerId == args[i]{\n\t\t\tif account.AccountName == \"Customer\" {\n\t\t\t\tfmt.Println(\"Customer Account found with account Owner Id : \" + args[i])\n\t\t\t\tfmt.Println(account);\n\t\t\t\tif operation == \"Initial\" || operation == \"Final\" {\n\t\t\t\t\taccount.AccountBalance = account.AccountBalance - _amountPaid\n\t\t\t\t}else{\n\t\t\t\t\taccount.AccountBalance = account.AccountBalance + _amountPaid\n\t\t\t\t}\n\t\t\t} else if account.AccountName == \"Service Provider\" {\n\t\t\t\tfmt.Println(\"Service Provider Account found with account Owner Id : \" + args[i])\n\t\t\t\tfmt.Println(account);\n\t\t\t\tif operation == \"Final\" || operation == \"Initial\"{\n\t\t\t\t\taccount.AccountBalance = account.AccountBalance + _amountPaid\n\t\t\t\t}else {\n\t\t\t\t\taccount.AccountBalance = account.AccountBalance - _amountPaid\n\t\t\t\t}\n\t\t\t}\n\t\t}else {\n\t\t\terrMsg := \"{ \\\"message\\\" : \\\"\"+ args[i]+ \" Not Found.\\\", \\\"code\\\" : \\\"503\\\"}\"\n\t\t\terr = stub.SetEvent(\"errEvent\", []byte(errMsg))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfmt.Println(errMsg); \n\t\t}\n\t\t\n\t\t//build the Payment json string\n\t\taccountJson := &Account{account.AccountOwnerId,account.AccountName,account.AccountBalance}\n\t\t// convert *Account to []byte\n\t\taccountJsonasBytes, err := json.Marshal(accountJson)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t//store account Owner Id as key\n\t\terr = stub.PutState(account.AccountOwnerId, accountJsonasBytes)\t\t\t\t\t\t\t\t\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// event message to set on successful account updation\n\t\ttosend := \"{ \\\"Account Owner Id\\\" : \\\"\"+account.AccountOwnerId+\"\\\", \\\"message\\\" : \\\"Account updated succcessfully\\\", \\\"code\\\" : \\\"200\\\"}\"\n\t\terr = stub.SetEvent(\"evtsender\", []byte(tosend))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfmt.Println(tosend); \t\n\t}\n\tfmt.Println(\"Account balance Updated Successfully.\")\n\treturn nil, nil\n}", "func (_DelegationController *DelegationControllerTransactor) Confiscate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"confiscate\", validatorId, amount)\n}", "func (n *Node) BecomeDelegator(genesisAmount uint64, seedAmount uint64, delegatorAmount uint64, txFee uint64, stakerNodeID string) *Node {\n\n\t// exports AVAX from the X Chain\n\texportTxID, err := n.client.XChainAPI().ExportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tseedAmount+txFee,\n\t\tn.PAddress,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to export AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the XChain\n\terr = chainhelper.XChain().AwaitTransactionAcceptance(n.client, exportTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// imports the amount to the P Chain\n\timportTxID, err := n.client.PChainAPI().ImportAVAX(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tconstants.XChainID.String(),\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed import AVAX to pchainAddress %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\t// waits Tx acceptance in the PChain\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, importTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn n\n\t}\n\n\t// verify the PChain balance (seedAmount+txFee-txFee)\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, seedAmount)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance of seedAmount exists in the PChain\"))\n\t\treturn n\n\t}\n\n\t// verify the XChain balance of genesisAmount - seedAmount - txFee - txFee (import PChain)\n\terr = chainhelper.XChain().CheckBalance(n.client, n.XAddress, \"AVAX\", genesisAmount-seedAmount-2*txFee)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"expected balance XChain balance of genesisAmount-seedAmount-txFee\"))\n\t\treturn n\n\t}\n\n\tdelegatorStartTime := time.Now().Add(20 * time.Second)\n\tstartTime := uint64(delegatorStartTime.Unix())\n\tendTime := uint64(delegatorStartTime.Add(36 * time.Hour).Unix())\n\taddDelegatorTxID, err := n.client.PChainAPI().AddDelegator(\n\t\tn.UserPass,\n\t\tnil, // from addrs\n\t\t\"\", // change addr\n\t\tn.PAddress,\n\t\tstakerNodeID,\n\t\tdelegatorAmount,\n\t\tstartTime,\n\t\tendTime,\n\t)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to add delegator %s\", n.PAddress))\n\t\treturn n\n\t}\n\n\terr = chainhelper.PChain().AwaitTransactionAcceptance(n.client, addDelegatorTxID, constants.TimeoutDuration)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Failed to accept AddDelegator tx: %s\", addDelegatorTxID))\n\t\treturn n\n\t}\n\n\t// Sleep until delegator starts validating\n\ttime.Sleep(time.Until(delegatorStartTime) + 3*time.Second)\n\n\texpectedDelegatorBalance := seedAmount - delegatorAmount\n\terr = chainhelper.PChain().CheckBalance(n.client, n.PAddress, expectedDelegatorBalance)\n\tif err != nil {\n\t\tpanic(stacktrace.Propagate(err, \"Unexpected P Chain Balance after adding a new delegator to the network.\"))\n\t\treturn n\n\t}\n\tlogrus.Infof(\"Added delegator to subnet and verified the expected P Chain balance.\")\n\n\treturn n\n}", "func TestApplyChangelistCreatesDelegation(t *testing.T) {\n\trepo, cs, err := testutils.EmptyRepo(\"docker.com/notary\")\n\trequire.NoError(t, err)\n\n\tnewKey, err := cs.Create(\"targets/level1\", \"docker.com/notary\", data.ED25519Key)\n\trequire.NoError(t, err)\n\n\terr = repo.UpdateDelegationKeys(\"targets/level1\", []data.PublicKey{newKey}, []string{}, 1)\n\trequire.NoError(t, err)\n\terr = repo.UpdateDelegationPaths(\"targets/level1\", []string{\"\"}, []string{}, false)\n\trequire.NoError(t, err)\n\tdelete(repo.Targets, \"targets/level1\")\n\n\thash := sha256.Sum256([]byte{})\n\tf := &data.FileMeta{\n\t\tLength: 1,\n\t\tHashes: map[string][]byte{\n\t\t\t\"sha256\": hash[:],\n\t\t},\n\t}\n\tfjson, err := json.Marshal(f)\n\trequire.NoError(t, err)\n\n\tcl := changelist.NewMemChangelist()\n\trequire.NoError(t, cl.Add(&changelist.TUFChange{\n\t\tActn: changelist.ActionCreate,\n\t\tRole: \"targets/level1\",\n\t\tChangeType: \"target\",\n\t\tChangePath: \"latest\",\n\t\tData: fjson,\n\t}))\n\n\trequire.NoError(t, applyChangelist(repo, nil, cl))\n\t_, ok := repo.Targets[\"targets/level1\"]\n\trequire.True(t, ok, \"Failed to create the delegation target\")\n\t_, ok = repo.Targets[\"targets/level1\"].Signed.Targets[\"latest\"]\n\trequire.True(t, ok, \"Failed to write change to delegation target\")\n}", "func (_DelegationController *DelegationControllerTransactorSession) Confiscate(validatorId *big.Int, amount *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Confiscate(&_DelegationController.TransactOpts, validatorId, amount)\n}", "func (rs *rootResolver) Delegation(args *struct {\n\tAddress common.Address\n\tStaker hexutil.Big\n}) (*Delegation, error) {\n\t// get the delegator detail from backend\n\td, err := repository.R().Delegation(&args.Address, &args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDelegation(d), nil\n}", "func (rs *rootResolver) Delegation(args *struct {\n\tAddress common.Address\n\tStaker hexutil.Uint64\n}) (*Delegation, error) {\n\t// get the delegator detail from backend\n\td, err := rs.repo.Delegation(args.Address, args.Staker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewDelegation(d, rs.repo), nil\n}", "func (va *ClawbackVestingAccount) computeClawback(clawbackTime int64) sdk.Coins {\n\t// Compute the truncated vesting schedule and amounts.\n\t// Work with the schedule as the primary data and recompute derived fields, e.g. OriginalVesting.\n\tvestTime := va.StartTime\n\ttotalVested := sdk.NewCoins()\n\ttotalUnvested := sdk.NewCoins()\n\tunvestedIdx := 0\n\tfor i, period := range va.VestingPeriods {\n\t\tvestTime += period.Length\n\t\t// tie in time goes to clawback\n\t\tif vestTime < clawbackTime {\n\t\t\ttotalVested = totalVested.Add(period.Amount...)\n\t\t\tunvestedIdx = i + 1\n\t\t} else {\n\t\t\ttotalUnvested = totalUnvested.Add(period.Amount...)\n\t\t}\n\t}\n\tlastVestTime := vestTime\n\tnewVestingPeriods := va.VestingPeriods[:unvestedIdx]\n\n\t// To cap the unlocking schedule to the new total vested, conjunct with a limiting schedule\n\tcapPeriods := []Period{\n\t\t{\n\t\t\tLength: 0,\n\t\t\tAmount: totalVested,\n\t\t},\n\t}\n\t_, lastLockTime, newLockupPeriods := ConjunctPeriods(va.StartTime, va.StartTime, va.LockupPeriods, capPeriods)\n\n\t// Now construct the new account state\n\tva.OriginalVesting = totalVested\n\tva.EndTime = max64(lastVestTime, lastLockTime)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\t// DelegatedVesting and DelegatedFree will be adjusted elsewhere\n\n\treturn totalUnvested\n}", "func rewardAndSlash(ctx contract.Context, cachedDelegations *CachedDposStorage, state *State) ([]*DelegationResult, error) {\n\tformerValidatorTotals := make(map[string]loom.BigUInt)\n\tdelegatorRewards := make(map[string]*loom.BigUInt)\n\tdistributedRewards := common.BigZero()\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, validator := range state.Validators {\n\t\tcandidate := GetCandidateByPubKey(ctx, validator.PubKey)\n\n\t\tif candidate == nil {\n\t\t\tctx.Logger().Info(\"Attempted to reward validator no longer on candidates list.\", \"validator\", validator)\n\t\t\tcontinue\n\t\t}\n\n\t\tcandidateAddress := loom.UnmarshalAddressPB(candidate.Address)\n\t\tvalidatorKey := candidateAddress.String()\n\t\tstatistic, _ := GetStatistic(ctx, candidateAddress)\n\n\t\tif statistic == nil {\n\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t} else {\n\t\t\t// If a validator is jailed, don't calculate and distribute rewards\n\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_3, false) {\n\t\t\t\tif statistic.Jailed {\n\t\t\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If a validator's SlashPercentage is 0, the validator is\n\t\t\t// rewarded for avoiding faults during the last slashing period\n\t\t\tif common.IsZero(statistic.SlashPercentage.Value) {\n\t\t\t\tdistributionTotal := calculateRewards(statistic.DelegationTotal.Value, state.Params, state.TotalValidatorDelegations.Value)\n\n\t\t\t\t// The validator share, equal to validator_fee * total_validotor_reward\n\t\t\t\t// is to be split between the referrers and the validator\n\t\t\t\tvalidatorShare := CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, distributionTotal)\n\n\t\t\t\t// delegatorsShare is what fraction of the total rewards will be\n\t\t\t\t// distributed to delegators\n\t\t\t\tdelegatorsShare := common.BigZero()\n\t\t\t\tdelegatorsShare.Sub(&distributionTotal, &validatorShare)\n\t\t\t\tdelegatorRewards[validatorKey] = delegatorsShare\n\n\t\t\t\t// Distribute rewards to referrers\n\t\t\t\tfor _, d := range delegations {\n\t\t\t\t\tif loom.UnmarshalAddressPB(d.Validator).Compare(loom.UnmarshalAddressPB(candidate.Address)) == 0 {\n\t\t\t\t\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\t\t// if the delegation is not found OR if the delegation\n\t\t\t\t\t\t// has no referrer, we do not need to attempt to\n\t\t\t\t\t\t// distribute the referrer rewards\n\t\t\t\t\t\tif err == contract.ErrNotFound || len(delegation.Referrer) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// if referrer is not found, do not distribute the reward\n\t\t\t\t\t\treferrerAddress := getReferrer(ctx, delegation.Referrer)\n\t\t\t\t\t\tif referrerAddress == nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// calculate referrerReward\n\t\t\t\t\t\treferrerReward := calculateRewards(delegation.Amount.Value, state.Params, state.TotalValidatorDelegations.Value)\n\t\t\t\t\t\treferrerReward = CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, referrerReward)\n\t\t\t\t\t\treferrerReward = CalculateFraction(defaultReferrerFee, referrerReward)\n\n\t\t\t\t\t\t// referrer fees are delegater to limbo validator\n\t\t\t\t\t\tdistributedRewards.Add(distributedRewards, &referrerReward)\n\t\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, LimboValidatorAddress(ctx).MarshalPB(), referrerAddress, referrerReward)\n\n\t\t\t\t\t\t// any referrer bonus amount is subtracted from the validatorShare\n\t\t\t\t\t\tvalidatorShare.Sub(&validatorShare, &referrerReward)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdistributedRewards.Add(distributedRewards, &validatorShare)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, validatorShare)\n\n\t\t\t\t// If a validator has some non-zero WhitelistAmount,\n\t\t\t\t// calculate the validator's reward based on whitelist amount\n\t\t\t\tif !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\t\t\twhitelistDistribution := calculateShare(amount, statistic.DelegationTotal.Value, *delegatorsShare)\n\t\t\t\t\t// increase a delegator's distribution\n\t\t\t\t\tdistributedRewards.Add(distributedRewards, &whitelistDistribution)\n\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, whitelistDistribution)\n\t\t\t\t}\n\n\t\t\t\t// Keeping track of cumulative distributed rewards by adding\n\t\t\t\t// every validator's total rewards to\n\t\t\t\t// `state.TotalRewardDistribution`\n\t\t\t\t// NOTE: because we round down in every `calculateRewards` call,\n\t\t\t\t// we expect `state.TotalRewardDistribution` to be a slight\n\t\t\t\t// overestimate of what was actually distributed. We could be\n\t\t\t\t// exact with our record keeping by incrementing\n\t\t\t\t// `state.TotalRewardDistribution` each time\n\t\t\t\t// `IncreaseRewardDelegation` is called, but because we will not\n\t\t\t\t// use `state.TotalRewardDistributions` as part of any invariants,\n\t\t\t\t// we will live with this situation.\n\t\t\t\tif !ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\t\t\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, &distributionTotal)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := slashValidatorDelegations(ctx, cachedDelegations, statistic, candidateAddress); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif err := SetStatistic(ctx, statistic); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tformerValidatorTotals[validatorKey] = statistic.DelegationTotal.Value\n\t\t}\n\t}\n\n\tnewDelegationTotals, err := distributeDelegatorRewards(ctx, cachedDelegations, formerValidatorTotals, delegatorRewards, distributedRewards)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, distributedRewards)\n\t}\n\n\tdelegationResults := make([]*DelegationResult, 0, len(newDelegationTotals))\n\tfor validator := range newDelegationTotals {\n\t\tdelegationResults = append(delegationResults, &DelegationResult{\n\t\t\tValidatorAddress: loom.MustParseAddress(validator),\n\t\t\tDelegationTotal: *newDelegationTotals[validator],\n\t\t})\n\t}\n\tsort.Sort(byDelegationTotal(delegationResults))\n\n\treturn delegationResults, nil\n}", "func CalculatePercentageSharesForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error){\n var stakingBalance float64\n //var balance float64\n var err error\n\n spillAlert := false\n\n stakingBalance, err = GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := stakingBalance - mod\n balanceCheck := stakingBalance - mod\n\n for index, delegation := range delegatedContracts{\n counter := 0\n for i, _ := range delegation.Contracts {\n if (delegatedContracts[index].Contracts[i].Cycle == cycle){\n break\n }\n counter = counter + 1\n }\n balanceCheck = balanceCheck - delegatedContracts[index].Contracts[counter].Amount\n //fmt.Println(stakingBalance)\n if (spillAlert){\n delegatedContracts[index].Contracts[counter].SharePercentage = 0\n delegatedContracts[index].Contracts[counter].RollInclusion = 0\n } else if (balanceCheck < 0 && spillage){\n spillAlert = true\n delegatedContracts[index].Contracts[counter].SharePercentage = (delegatedContracts[index].Contracts[counter].Amount + stakingBalance) / sum\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount + stakingBalance\n } else{\n delegatedContracts[index].Contracts[counter].SharePercentage = delegatedContracts[index].Contracts[counter].Amount / stakingBalance\n delegatedContracts[index].Contracts[counter].RollInclusion = delegatedContracts[index].Contracts[counter].Amount\n }\n delegatedContracts[index].Contracts[counter] = CalculatePayoutForContract(delegatedContracts[index].Contracts[counter], rate, delegatedContracts[index].Delegate)\n delegatedContracts[index].Fee = delegatedContracts[index].Fee + delegatedContracts[index].Contracts[counter].Fee\n }\n\n return delegatedContracts, nil\n}", "func TestSlashBoth(t *testing.T) {\n\tapp, ctx, addrDels, addrVals := bootstrapSlashTest(t, 10)\n\tfraction := sdk.NewDecWithPrec(5, 1)\n\tbondDenom := app.StakingKeeper.BondDenom(ctx)\n\n\t// set a redelegation with expiration timestamp beyond which the\n\t// redelegation shouldn't be slashed\n\trdATokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 6)\n\trdA := types.NewRedelegation(addrDels[0], addrVals[0], addrVals[1], 11,\n\t\ttime.Unix(0, 0), rdATokens,\n\t\trdATokens.ToDec())\n\tapp.StakingKeeper.SetRedelegation(ctx, rdA)\n\n\t// set the associated delegation\n\tdelA := types.NewDelegation(addrDels[0], addrVals[1], rdATokens.ToDec())\n\tapp.StakingKeeper.SetDelegation(ctx, delA)\n\n\t// set an unbonding delegation with expiration timestamp (beyond which the\n\t// unbonding delegation shouldn't be slashed)\n\tubdATokens := app.StakingKeeper.TokensFromConsensusPower(ctx, 4)\n\tubdA := types.NewUnbondingDelegation(addrDels[0], addrVals[0], 11,\n\t\ttime.Unix(0, 0), ubdATokens)\n\tapp.StakingKeeper.SetUnbondingDelegation(ctx, ubdA)\n\n\tbondedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, rdATokens.MulRaw(2)))\n\tnotBondedCoins := sdk.NewCoins(sdk.NewCoin(bondDenom, ubdATokens))\n\n\t// update bonded tokens\n\tbondedPool := app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool := app.StakingKeeper.GetNotBondedPool(ctx)\n\n\trequire.NoError(t, simapp.FundModuleAccount(app.BankKeeper, ctx, bondedPool.GetName(), bondedCoins))\n\trequire.NoError(t, simapp.FundModuleAccount(app.BankKeeper, ctx, notBondedPool.GetName(), notBondedCoins))\n\n\tapp.AccountKeeper.SetModuleAccount(ctx, bondedPool)\n\tapp.AccountKeeper.SetModuleAccount(ctx, notBondedPool)\n\n\toldBonded := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\toldNotBonded := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\t// slash validator\n\tctx = ctx.WithBlockHeight(12)\n\tvalidator, found := app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0]))\n\trequire.True(t, found)\n\tconsAddr0 := sdk.ConsAddress(PKs[0].Address())\n\tapp.StakingKeeper.Slash(ctx, consAddr0, 10, 10, fraction)\n\n\tburnedNotBondedAmount := fraction.MulInt(ubdATokens).TruncateInt()\n\tburnedBondAmount := app.StakingKeeper.TokensFromConsensusPower(ctx, 10).ToDec().Mul(fraction).TruncateInt()\n\tburnedBondAmount = burnedBondAmount.Sub(burnedNotBondedAmount)\n\n\t// read updated pool\n\tbondedPool = app.StakingKeeper.GetBondedPool(ctx)\n\tnotBondedPool = app.StakingKeeper.GetNotBondedPool(ctx)\n\n\tbondedPoolBalance := app.BankKeeper.GetBalance(ctx, bondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldBonded.Sub(burnedBondAmount), bondedPoolBalance))\n\n\tnotBondedPoolBalance := app.BankKeeper.GetBalance(ctx, notBondedPool.GetAddress(), bondDenom).Amount\n\trequire.True(sdk.IntEq(t, oldNotBonded.Sub(burnedNotBondedAmount), notBondedPoolBalance))\n\n\t// read updating redelegation\n\trdA, found = app.StakingKeeper.GetRedelegation(ctx, addrDels[0], addrVals[0], addrVals[1])\n\trequire.True(t, found)\n\trequire.Len(t, rdA.Entries, 1)\n\t// read updated validator\n\tvalidator, found = app.StakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(PKs[0]))\n\trequire.True(t, found)\n\t// power not decreased, all stake was bonded since\n\trequire.Equal(t, int64(10), validator.GetConsensusPower(app.StakingKeeper.PowerReduction(ctx)))\n}", "func (k Keeper) DelegateCoinsFromAccountToModule(\n\tctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins,\n) error {\n\n\trecipientAcc := k.GetModuleAccount(ctx, recipientModule)\n\tif recipientAcc == nil {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, \"module account %s does not exist\", recipientModule))\n\t}\n\n\tif !recipientAcc.HasPermission(types.Staking) {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, \"module account %s does not have permissions to receive delegated coins\", recipientModule))\n\t}\n\n\treturn k.bk.DelegateCoins(ctx, senderAddr, recipientAcc.GetAddress(), amt)\n}", "func UnmarshalDelegation(cdc *codec.Codec, key, value []byte) (delegation Delegation, err error) {\n\tvar storeValue delegationValue\n\terr = cdc.UnmarshalBinaryLengthPrefixed(value, &storeValue)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"%v: %v\", ErrNoDelegation(DefaultCodespace).Data(), err)\n\t\treturn\n\t}\n\n\taddrs := key[1:] // remove prefix bytes\n\tif len(addrs) != 2*sdk.AddrLen {\n\t\terr = fmt.Errorf(\"%v\", ErrBadDelegationAddr(DefaultCodespace).Data())\n\t\treturn\n\t}\n\n\tdelAddr := sdk.AccAddress(addrs[:sdk.AddrLen])\n\tvalAddr := sdk.ValAddress(addrs[sdk.AddrLen:])\n\n\treturn Delegation{\n\t\tDelegatorAddr: delAddr,\n\t\tValidatorAddr: valAddr,\n\t\tShares: storeValue.Shares,\n\t}, nil\n}", "func AnnualBalanceUpdate(balance float64) float64 {\n\treturn balance + Interest(balance)\n}", "func (_DelegationController *DelegationControllerTransactor) Delegate(opts *bind.TransactOpts, validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"delegate\", validatorId, amount, delegationPeriod, info)\n}", "func CalculateTotalPayout(delegatedContract DelegatedContract) DelegatedContract{\n for _, contract := range delegatedContract.Contracts{\n delegatedContract.TotalPayout = delegatedContract.TotalPayout + contract.NetPayout\n }\n return delegatedContract\n}", "func (pva *PeriodicVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, pva.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, pva.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := pva.DelegatedVesting.Add(pva.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV+DF by capping slashed at the current unvested amount\n\tunvested := pva.GetVestingCoins(ctx.BlockTime())\n\tnewSlashed := coinsMin(unvested, slashed)\n\tnewTotalDelegated := delegated.Add(newSlashed...)\n\n\t// modify vesting schedule for the new grant\n\tnewStart, newEnd, newPeriods := DisjunctPeriods(pva.StartTime, grantStartTime,\n\t\tpva.GetVestingPeriods(), grantVestingPeriods)\n\tpva.StartTime = newStart\n\tpva.EndTime = newEnd\n\tpva.VestingPeriods = newPeriods\n\tpva.OriginalVesting = pva.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newTotalDelegated\n\tunvested2 := pva.GetVestingCoins(ctx.BlockTime())\n\tpva.DelegatedVesting = coinsMin(newTotalDelegated, unvested2)\n\tpva.DelegatedFree = newTotalDelegated.Sub(pva.DelegatedVesting)\n}", "func (k Querier) UnbondingDelegation(ctx context.Context, req *types.QueryUnbondingDelegationRequest) (*types.QueryUnbondingDelegationResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tif req.ValidatorAddr == \"\" {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"validator address cannot be empty\")\n\t}\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalAddr, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tunbond, err := k.GetUnbondingDelegation(ctx, delAddr, valAddr)\n\tif err != nil {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"unbonding delegation with delegator %s not found for validator %s\",\n\t\t\treq.DelegatorAddr, req.ValidatorAddr)\n\t}\n\n\treturn &types.QueryUnbondingDelegationResponse{Unbond: unbond}, nil\n}", "func (_Bindings *BindingsSession) RepayBorrowBehalf(borrower common.Address) (*types.Transaction, error) {\n\treturn _Bindings.Contract.RepayBorrowBehalf(&_Bindings.TransactOpts, borrower)\n}", "func (k Keeper) ClaimDelegatorReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tclaim, found := k.GetDelegatorClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, err := k.SynchronizeDelegatorClaim(ctx, claim)\n\tif err != nil {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetDelegatorClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateForbiddenForDelegationAmount(opts *bind.TransactOpts, wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateForbiddenForDelegationAmount\", wallet)\n}", "func (_DelegationController *DelegationControllerSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (wallet *Wallet) refreshWallet(acc *account.Account, adr *wallet_address.WalletAddress) (err error) {\n\n\tif acc == nil {\n\t\treturn\n\t}\n\n\tif adr.DelegatedStake != nil && acc.DelegatedStake == nil {\n\t\tadr.DelegatedStake = nil\n\t\treturn\n\t}\n\n\tif (adr.DelegatedStake != nil && acc.DelegatedStake != nil && !bytes.Equal(adr.DelegatedStake.PublicKeyHash, acc.DelegatedStake.DelegatedPublicKeyHash)) ||\n\t\t(adr.DelegatedStake == nil && acc.DelegatedStake != nil) {\n\n\t\tif adr.IsMine {\n\n\t\t\tif acc.DelegatedStake != nil {\n\n\t\t\t\tlastKnownNonce := uint32(0)\n\t\t\t\tif adr.DelegatedStake != nil {\n\t\t\t\t\tlastKnownNonce = adr.DelegatedStake.LastKnownNonce\n\t\t\t\t}\n\n\t\t\t\tvar delegatedStake *wallet_address.WalletAddressDelegatedStake\n\t\t\t\tif delegatedStake, err = adr.FindDelegatedStake(uint32(acc.Nonce), lastKnownNonce, acc.DelegatedStake.DelegatedPublicKeyHash); err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif delegatedStake != nil {\n\t\t\t\t\tadr.DelegatedStake = delegatedStake\n\t\t\t\t\twallet.forging.Wallet.AddWallet(adr.DelegatedStake.PrivateKey.Key, adr.Address.PublicKeyHash)\n\t\t\t\t\treturn wallet.saveWalletAddress(adr)\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tadr.DelegatedStake = nil\n\t\twallet.forging.Wallet.AddWallet(nil, adr.Address.PublicKeyHash)\n\t\treturn wallet.saveWalletAddress(adr)\n\t}\n\n\treturn\n}", "func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) ([]DelegatedContract, error) {\n var err error\n var balance float64\n delegationsForCycle, _ := GetDelegatedContractsForCycle(cycle, delegateAddr)\n\n for index, delegation := range delegatedContracts{\n balance, err = GetAccountBalanceAtSnapshot(delegation.Address, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"Could not calculate all commitments for cycle \" + strconv.Itoa(cycle) + \":GetAccountBalanceAtSnapshot(tezosAddr string, cycle int) failed: \" + err.Error())\n }\n if (isDelegationInGroup(delegatedContracts[index].Address, delegationsForCycle, delegatedContracts[index].Delegate)){\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:balance})\n } else{\n delegatedContracts[index].Contracts = append(delegatedContracts[index].Contracts, Contract{Cycle:cycle, Amount:0})\n }\n //fmt.Println(delegatedContracts[index].Contracts)\n }\n\n delegatedContracts, err = CalculatePercentageSharesForCycle(delegatedContracts, cycle, rate, spillage, delegateAddr)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateAllContractsForCycle(delegatedContracts []DelegatedContract, cycle int, rate float64, spillage bool, delegateAddr string) failed: \" + err.Error())\n }\n return delegatedContracts, nil\n}", "func (k Keeper) DelegateCoinsFromAccountToModule(\n\tctx sdk.Context, recipientModule string, amt Coins,\n) error {\n\trecipientAcc := k.GetModuleAccount(ctx, recipientModule)\n\tif recipientAcc == nil {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, \"module account %s does not exist\", recipientModule))\n\t}\n\n\tif !recipientAcc.HasPermission(types.Staking) {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, \"module account %s does not have permissions to receive delegated coins\", recipientModule))\n\t}\n\n\t// Delegate will first send coins to ModuleAccountID\n\tif err := k.bk.CoinsToPower(ctx, stakingTypes.ModuleAccountID, recipientAcc.GetID(), amt); err != nil {\n\t\treturn sdkerrors.Wrapf(err,\n\t\t\t\"DelegateCoinsFromAccountToModule %s by %s\", recipientModule, amt.String())\n\t}\n\n\treturn nil\n}", "func (m *Mantle) replenishBalance(w *botWallet) {\n\t// Get the Balance from the user in case it changed while while this note\n\t// was in the notification pipeline.\n\tbal, err := m.AssetBalance(w.assetID)\n\tif err != nil {\n\t\tm.fatalError(\"error updating %s balance: %v\", w.symbol, err)\n\t\treturn\n\t}\n\n\tm.log.Debugf(\"Balance note received for %s (minFunds = %s, maxFunds = %s): %s\",\n\t\tw.symbol, valString(w.minFunds), valString(w.maxFunds), mustJSON(bal))\n\n\teffectiveMax := w.maxFunds + (w.maxFunds - w.minFunds)\n\n\tif bal.Available < w.minFunds {\n\t\tchunk := (w.maxFunds - bal.Available) / uint64(w.numCoins)\n\t\tfor i := 0; i < w.numCoins; i++ {\n\t\t\tm.log.Debugf(\"Requesting %s from %s alpha node\", valString(chunk), w.symbol)\n\t\t\tcmdOut := <-harnessCtl(w.symbol, \"./alpha\", \"sendtoaddress\", w.address, valString(chunk))\n\t\t\tif cmdOut.err != nil {\n\t\t\t\tm.fatalError(\"error refreshing balance for %s: %v\", w.symbol, cmdOut.err)\n\t\t\t}\n\t\t}\n\t} else if bal.Available > effectiveMax {\n\t\t// Send some back to the alpha address.\n\t\tamt := bal.Available - w.maxFunds\n\t\tm.log.Debugf(\"Sending %s back to %s alpha node\", valString(amt), w.symbol)\n\t\t_, err := m.Withdraw(pass, w.assetID, amt, returnAddress(w.symbol, alpha))\n\t\tif err != nil {\n\t\t\tm.fatalError(\"failed to withdraw funds to alpha: %v\", err)\n\t\t}\n\t}\n}", "func (del Delegation) Amount() (hexutil.Big, error) {\n\t// get the base amount delegated\n\tbase, err := repository.R().DelegationAmountStaked(&del.Address, del.Delegation.ToStakerId)\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\n\t// get the sum of all pending withdrawals\n\twd, err := del.pendingWithdrawalsValue()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\tval := new(big.Int).Add(base, wd)\n\treturn (hexutil.Big)(*val), nil\n}", "func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string, cycle int) ([]DelegatedContract, error) {\n stakingBalance, err := GetDelegateStakingBalance(delegateAddr, cycle)\n if (err != nil){\n return delegatedContracts, errors.New(\"func CalculateRollSpillage(delegatedContracts []DelegatedContract, delegateAddr string) failed: \" + err.Error())\n }\n\n mod := math.Mod(stakingBalance, 10000)\n sum := mod * 10000\n\n for index, delegatedContract := range delegatedContracts{\n for i, contract := range delegatedContract.Contracts{\n if (contract.Cycle == cycle){\n stakingBalance = stakingBalance - contract.Amount\n if (stakingBalance < 0){\n delegatedContracts[index].Contracts[i].SharePercentage = (contract.Amount - stakingBalance) / sum\n }\n }\n }\n }\n\n return delegatedContracts, nil\n}", "func (k Keeper) RepayPrincipal(ctx sdk.Context, owner sdk.AccAddress, denom string, payment sdk.Coins) error {\n\t// validation\n\tcdp, found := k.GetCdpByOwnerAndDenom(ctx, owner, denom)\n\tif !found {\n\t\treturn sdkerrors.Wrapf(types.ErrCdpNotFound, \"owner %s, denom %s\", owner, denom)\n\t}\n\n\terr := k.ValidatePaymentCoins(ctx, cdp, payment, cdp.Principal.Add(cdp.AccumulatedFees...))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// calculate fee and principal payment\n\tfeePayment, principalPayment := k.calculatePayment(ctx, cdp.Principal.Add(cdp.AccumulatedFees...), cdp.AccumulatedFees, payment)\n\n\t// send the payment from the sender to the cpd module\n\terr = k.supplyKeeper.SendCoinsFromAccountToModule(ctx, owner, types.ModuleName, feePayment.Add(principalPayment...))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// burn the payment coins\n\terr = k.supplyKeeper.BurnCoins(ctx, types.ModuleName, feePayment.Add(principalPayment...))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// burn the corresponding amount of debt coins\n\tcdpDebt := k.getModAccountDebt(ctx, types.ModuleName)\n\tpaymentAmount := sdk.ZeroInt()\n\tfor _, c := range feePayment.Add(principalPayment...) {\n\t\tpaymentAmount = paymentAmount.Add(c.Amount)\n\t}\n\tcoinsToBurn := sdk.NewCoins(sdk.NewCoin(k.GetDebtDenom(ctx), paymentAmount))\n\tif paymentAmount.GT(cdpDebt) {\n\t\tcoinsToBurn = sdk.NewCoins(sdk.NewCoin(k.GetDebtDenom(ctx), cdpDebt))\n\t}\n\terr = k.BurnDebtCoins(ctx, types.ModuleName, k.GetDebtDenom(ctx), coinsToBurn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// emit repayment event\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeCdpRepay,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, feePayment.Add(principalPayment...).String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf(\"%d\", cdp.ID)),\n\t\t),\n\t)\n\n\t// remove the old collateral:debt ratio index\n\toldCollateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Principal.Add(cdp.AccumulatedFees...))\n\tk.RemoveCdpCollateralRatioIndex(ctx, denom, cdp.ID, oldCollateralToDebtRatio)\n\n\t// update cdp state\n\tif !principalPayment.IsZero() {\n\t\tcdp.Principal = cdp.Principal.Sub(principalPayment)\n\t}\n\tcdp.AccumulatedFees = cdp.AccumulatedFees.Sub(feePayment)\n\tcdp.FeesUpdated = ctx.BlockTime()\n\n\t// decrement the total principal for the input collateral type\n\tk.DecrementTotalPrincipal(ctx, denom, feePayment.Add(principalPayment...))\n\n\t// if the debt is fully paid, return collateral to depositors,\n\t// and remove the cdp and indexes from the store\n\tif cdp.Principal.IsZero() && cdp.AccumulatedFees.IsZero() {\n\t\tk.ReturnCollateral(ctx, cdp)\n\t\tk.DeleteCDP(ctx, cdp)\n\t\tk.RemoveCdpOwnerIndex(ctx, cdp)\n\n\t\t// emit cdp close event\n\t\tctx.EventManager().EmitEvent(\n\t\t\tsdk.NewEvent(\n\t\t\t\ttypes.EventTypeCdpClose,\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf(\"%d\", cdp.ID)),\n\t\t\t),\n\t\t)\n\t\treturn nil\n\t}\n\n\t// set cdp state and update indexes\n\tcollateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Principal.Add(cdp.AccumulatedFees...))\n\tk.SetCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio)\n\treturn nil\n}", "func (_TokensNetwork *TokensNetworkTransactor) UpdateBalanceProof(opts *bind.TransactOpts, token common.Address, partner common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"updateBalanceProof\", token, partner, transferred_amount, locksroot, nonce, additional_hash, partner_signature)\n}", "func (k Keeper) fastUndelegate(ctx sdk.Context, valAddr sdk.ValAddress, delegator sdk.AccAddress, shares sdk.Dec) (sdkmath.Int, error) {\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdkmath.Int{}, types.ErrNoDelegatorForAddress\n\t}\n\n\treturnAmount, err := k.stakingKeeper.Unbond(ctx, delegator, valAddr, shares)\n\tif err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturnCoins := sdk.NewCoins(sdk.NewCoin(k.stakingKeeper.BondDenom(ctx), returnAmount))\n\n\t// transfer the validator tokens to the not bonded pool\n\tif validator.IsBonded() {\n\t\tif err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, stakingtypes.BondedPoolName, stakingtypes.NotBondedPoolName, returnCoins); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tif err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, stakingtypes.NotBondedPoolName, delegator, returnCoins); err != nil {\n\t\treturn sdkmath.Int{}, err\n\t}\n\treturn returnAmount, nil\n}", "func DeployDelegationController(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, *types.Transaction, *DelegationController, error) {\n\tparsed, err := abi.JSON(strings.NewReader(DelegationControllerABI))\n\tif err != nil {\n\t\treturn common.Address{}, nil, nil, err\n\t}\n\n\taddress, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(DelegationControllerBin), backend)\n\tif err != nil {\n\t\treturn common.Address{}, nil, nil, err\n\t}\n\treturn address, tx, &DelegationController{DelegationControllerCaller: DelegationControllerCaller{contract: contract}, DelegationControllerTransactor: DelegationControllerTransactor{contract: contract}, DelegationControllerFilterer: DelegationControllerFilterer{contract: contract}}, nil\n}", "func (va ClawbackVestingAccount) distributeReward(ctx sdk.Context, ak AccountKeeper, bondDenom string, reward sdk.Coins) {\n\tnow := ctx.BlockTime().Unix()\n\tt := va.StartTime\n\tfirstUnvestedPeriod := 0\n\tunvestedTokens := sdk.ZeroInt()\n\tfor i, period := range va.VestingPeriods {\n\t\tt += period.Length\n\t\tif t <= now {\n\t\t\tfirstUnvestedPeriod = i + 1\n\t\t\tcontinue\n\t\t}\n\t\tunvestedTokens = unvestedTokens.Add(period.Amount.AmountOf(bondDenom))\n\t}\n\n\trunningTotReward := sdk.NewCoins()\n\trunningTotStaking := sdk.ZeroInt()\n\tfor i := firstUnvestedPeriod; i < len(va.VestingPeriods); i++ {\n\t\tperiod := va.VestingPeriods[i]\n\t\trunningTotStaking = runningTotStaking.Add(period.Amount.AmountOf(bondDenom))\n\t\trunningTotRatio := runningTotStaking.ToDec().Quo(unvestedTokens.ToDec())\n\t\ttargetCoins := scaleCoins(reward, runningTotRatio)\n\t\tthisReward := targetCoins.Sub(runningTotReward)\n\t\trunningTotReward = targetCoins\n\t\tperiod.Amount = period.Amount.Add(thisReward...)\n\t\tva.VestingPeriods[i] = period\n\t}\n\n\tva.OriginalVesting = va.OriginalVesting.Add(reward...)\n\tak.SetAccount(ctx, &va)\n}", "func (k Keeper) RepayPrincipal(ctx sdk.Context, owner sdk.AccAddress, collateralType string, payment sdk.Coin) error {\n\t// validation\n\tcdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrCdpNotFound, \"owner %s, denom %s\", owner, collateralType)\n\t}\n\n\terr := k.ValidatePaymentCoins(ctx, cdp, payment)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = k.ValidateBalance(ctx, payment, owner)\n\tif err != nil {\n\t\treturn err\n\t}\n\tk.hooks.BeforeCDPModified(ctx, cdp)\n\tcdp = k.SynchronizeInterest(ctx, cdp)\n\n\t// Note: assumes cdp.Principal and cdp.AccumulatedFees don't change during calculations\n\ttotalPrincipal := cdp.GetTotalPrincipal()\n\n\t// calculate fee and principal payment\n\tfeePayment, principalPayment := k.calculatePayment(ctx, totalPrincipal, cdp.AccumulatedFees, payment)\n\n\terr = k.validatePrincipalPayment(ctx, cdp, principalPayment)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// send the payment from the sender to the cpd module\n\terr = k.bankKeeper.SendCoinsFromAccountToModule(ctx, owner, types.ModuleName, sdk.NewCoins(feePayment.Add(principalPayment)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// burn the payment coins\n\terr = k.bankKeeper.BurnCoins(ctx, types.ModuleName, sdk.NewCoins(feePayment.Add(principalPayment)))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// burn the corresponding amount of debt coins\n\tcdpDebt := k.getModAccountDebt(ctx, types.ModuleName)\n\tpaymentAmount := feePayment.Add(principalPayment).Amount\n\n\tdebtDenom := k.GetDebtDenom(ctx)\n\tcoinsToBurn := sdk.NewCoin(debtDenom, paymentAmount)\n\n\tif paymentAmount.GT(cdpDebt) {\n\t\tcoinsToBurn = sdk.NewCoin(debtDenom, cdpDebt)\n\t}\n\n\terr = k.BurnDebtCoins(ctx, types.ModuleName, debtDenom, coinsToBurn)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// emit repayment event\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeCdpRepay,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, feePayment.Add(principalPayment).String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf(\"%d\", cdp.ID)),\n\t\t),\n\t)\n\n\t// remove the old collateral:debt ratio index\n\n\t// update cdp state\n\tif !principalPayment.IsZero() {\n\t\tcdp.Principal = cdp.Principal.Sub(principalPayment)\n\t}\n\tcdp.AccumulatedFees = cdp.AccumulatedFees.Sub(feePayment)\n\n\t// decrement the total principal for the input collateral type\n\tk.DecrementTotalPrincipal(ctx, cdp.Type, feePayment.Add(principalPayment))\n\n\t// if the debt is fully paid, return collateral to depositors,\n\t// and remove the cdp and indexes from the store\n\tif cdp.Principal.IsZero() && cdp.AccumulatedFees.IsZero() {\n\t\tk.ReturnCollateral(ctx, cdp)\n\t\tk.RemoveCdpOwnerIndex(ctx, cdp)\n\t\terr := k.DeleteCdpAndCollateralRatioIndex(ctx, cdp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// emit cdp close event\n\t\tctx.EventManager().EmitEvent(\n\t\t\tsdk.NewEvent(\n\t\t\t\ttypes.EventTypeCdpClose,\n\t\t\t\tsdk.NewAttribute(types.AttributeKeyCdpID, fmt.Sprintf(\"%d\", cdp.ID)),\n\t\t\t),\n\t\t)\n\t\treturn nil\n\t}\n\n\t// set cdp state and update indexes\n\tcollateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, cdp.Collateral, cdp.Type, cdp.GetTotalPrincipal())\n\treturn k.UpdateCdpAndCollateralRatioIndex(ctx, cdp, collateralToDebtRatio)\n}", "func (theAccount *Account) Deposit(amount int) {\n\ttheAccount.balance += amount\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateForbiddenForDelegationAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateForbiddenForDelegationAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (_DelegationController *DelegationControllerTransactorSession) Delegate(validatorId *big.Int, amount *big.Int, delegationPeriod *big.Int, info string) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.Delegate(&_DelegationController.TransactOpts, validatorId, amount, delegationPeriod, info)\n}", "func (bva BaseVestingAccount) GetDelegatedFree() sdk.Coins {\n\treturn bva.DelegatedFree\n}", "func (k msgServer) Undelegate(goCtx context.Context, msg *types.MsgUndelegate) (*types.MsgUndelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\taddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttokens := msg.Amount.Amount\n\tshares, err := k.ValidateUnbondAmount(\n\t\tctx, delegatorAddress, addr, tokens,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalidator, found := k.GetValidator(ctx, addr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\n\tdelegation, found := k.GetDelegation(ctx, delegatorAddress, addr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorAddress,\n\t\t)\n\t}\n\n\t// if this is a validator self-bond, the new liquid delegation cannot fall below the self-bond * bond factor\n\tif delegation.ValidatorBond {\n\t\tif err := k.SafelyDecreaseValidatorBond(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// if this delegation is from a liquid staking provider (identified if the delegator\n\t// is an ICA account), the global and validator liquid totals should be decremented\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.DecreaseTotalLiquidStakedTokens(ctx, tokens); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.DecreaseValidatorLiquidShares(ctx, &validator, shares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tcompletionTime, err := k.Keeper.Undelegate(ctx, delegatorAddress, addr, shares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif tokens.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"undelegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(tokens.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeUnbond,\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, msg.ValidatorAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),\n\t\t),\n\t})\n\n\treturn &types.MsgUndelegateResponse{\n\t\tCompletionTime: completionTime,\n\t}, nil\n}", "func calculateRewards(delegationTotal loom.BigUInt, params *Params, totalValidatorDelegations loom.BigUInt) loom.BigUInt {\n\tcycleSeconds := params.ElectionCycleLength\n\treward := CalculateFraction(blockRewardPercentage, delegationTotal)\n\n\t// If totalValidator Delegations are high enough to make simple reward\n\t// calculations result in more rewards given out than the value of `MaxYearlyReward`,\n\t// scale the rewards appropriately\n\tyearlyRewardTotal := CalculateFraction(blockRewardPercentage, totalValidatorDelegations)\n\tif yearlyRewardTotal.Cmp(&params.MaxYearlyReward.Value) > 0 {\n\t\treward.Mul(&reward, &params.MaxYearlyReward.Value)\n\t\treward.Div(&reward, &yearlyRewardTotal)\n\t}\n\n\t// When election cycle = 0, estimate block time at 2 sec\n\tif cycleSeconds == 0 {\n\t\tcycleSeconds = 2\n\t}\n\treward.Mul(&reward, &loom.BigUInt{big.NewInt(cycleSeconds)})\n\treward.Div(&reward, &secondsInYear)\n\n\treturn reward\n}", "func (k msgServer) BeginRedelegate(goCtx context.Context, msg *types.MsgBeginRedelegate) (*types.MsgBeginRedelegateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(goCtx)\n\n\tvalSrcAddr, err := sdk.ValAddressFromBech32(msg.ValidatorSrcAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvalDstAddr, err := sdk.ValAddressFromBech32(msg.ValidatorDstAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsrcValidator, found := k.GetValidator(ctx, valSrcAddr)\n\tif !found {\n\t\treturn nil, types.ErrNoValidatorFound\n\t}\n\tdstValidator, found := k.GetValidator(ctx, valDstAddr)\n\tif !found {\n\t\treturn nil, types.ErrBadRedelegationDst\n\t}\n\n\tdelegatorAddress, err := sdk.AccAddressFromBech32(msg.DelegatorAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegation, found := k.GetDelegation(ctx, delegatorAddress, valSrcAddr)\n\tif !found {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.NotFound,\n\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\tmsg.DelegatorAddress, msg.ValidatorSrcAddress,\n\t\t)\n\t}\n\n\tsrcShares, err := k.ValidateUnbondAmount(ctx, delegatorAddress, valSrcAddr, msg.Amount.Amount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdstShares, err := dstValidator.SharesFromTokensTruncated(msg.Amount.Amount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// if this is a validator self-bond, the new liquid delegation cannot fall below the self-bond * bond factor\n\tif delegation.ValidatorBond {\n\t\tif err := k.SafelyDecreaseValidatorBond(ctx, &srcValidator, srcShares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// If this delegation from a liquid staker, the delegation on the new validator\n\t// cannot exceed that validator's self-bond cap\n\t// The liquid shares from the source validator should get moved to the destination validator\n\tif k.DelegatorIsLiquidStaker(delegatorAddress) {\n\t\tif err := k.SafelyIncreaseValidatorLiquidShares(ctx, &dstValidator, dstShares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := k.DecreaseValidatorLiquidShares(ctx, &srcValidator, srcShares); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbondDenom := k.BondDenom(ctx)\n\tif msg.Amount.Denom != bondDenom {\n\t\treturn nil, sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidRequest, \"invalid coin denomination: got %s, expected %s\", msg.Amount.Denom, bondDenom,\n\t\t)\n\t}\n\n\tcompletionTime, err := k.BeginRedelegation(\n\t\tctx, delegatorAddress, valSrcAddr, valDstAddr, srcShares,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif msg.Amount.Amount.IsInt64() {\n\t\tdefer func() {\n\t\t\ttelemetry.IncrCounter(1, types.ModuleName, \"redelegate\")\n\t\t\ttelemetry.SetGaugeWithLabels(\n\t\t\t\t[]string{\"tx\", \"msg\", msg.Type()},\n\t\t\t\tfloat32(msg.Amount.Amount.Int64()),\n\t\t\t\t[]metrics.Label{telemetry.NewLabel(\"denom\", msg.Amount.Denom)},\n\t\t\t)\n\t\t}()\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeRedelegate,\n\t\t\tsdk.NewAttribute(types.AttributeKeySrcValidator, msg.ValidatorSrcAddress),\n\t\t\tsdk.NewAttribute(types.AttributeKeyDstValidator, msg.ValidatorDstAddress),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, msg.Amount.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyCompletionTime, completionTime.Format(time.RFC3339)),\n\t\t),\n\t})\n\n\treturn &types.MsgBeginRedelegateResponse{\n\t\tCompletionTime: completionTime,\n\t}, nil\n}", "func (broadcast *Broadcast) DelegatorWithdraw(ctx context.Context, delegator, voter, amount,\n\tprivKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tmsg := model.DelegatorWithdrawMsg{\n\t\tDelegator: delegator,\n\t\tVoter: voter,\n\t\tAmount: amount,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func (_CrToken *CrTokenTransactor) RepayBorrowBehalf(opts *bind.TransactOpts, borrower common.Address, repayAmount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.contract.Transact(opts, \"repayBorrowBehalf\", borrower, repayAmount)\n}", "func (account *Account) Deposit(amount int) {\r\n\taccount.balance += amount\r\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) UpdateBalanceProof(token common.Address, partner common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.UpdateBalanceProof(&_TokensNetwork.TransactOpts, token, partner, transferred_amount, locksroot, nonce, additional_hash, partner_signature)\n}", "func (_DelegationController *DelegationControllerTransactorSession) GetAndUpdateForbiddenForDelegationAmount(wallet common.Address) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateForbiddenForDelegationAmount(&_DelegationController.TransactOpts, wallet)\n}", "func (del Delegation) UnlockPenalty(args struct{ Amount hexutil.Big }) (hexutil.Big, error) {\n\treturn repository.R().DelegationUnlockPenalty(&del.Address, (*big.Int)(del.Delegation.ToStakerId), (*big.Int)(&args.Amount))\n}", "func (_CrToken *CrTokenSession) RepayBorrowBehalf(borrower common.Address, repayAmount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.Contract.RepayBorrowBehalf(&_CrToken.TransactOpts, borrower, repayAmount)\n}", "func (k Keeper) delegateFromAccount(ctx sdk.Context, valAddr sdk.ValAddress, delegator sdk.AccAddress, amount sdkmath.Int) (sdk.Dec, error) {\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// source tokens are from an account, so subtractAccount true and tokenSrc unbonded\n\tnewShares, err := k.stakingKeeper.Delegate(ctx, delegator, amount, stakingtypes.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturn newShares, nil\n}", "func (_Bindings *BindingsTransactor) RepayBorrowBehalf(opts *bind.TransactOpts, borrower common.Address) (*types.Transaction, error) {\n\treturn _Bindings.contract.Transact(opts, \"repayBorrowBehalf\", borrower)\n}", "func (_Caller *CallerTransactor) WithdrawFees(opts *bind.TransactOpts, to common.Address) (*types.Transaction, error) {\n\treturn _Caller.contract.Transact(opts, \"withdrawFees\", to)\n}", "func (_DelegationController *DelegationControllerTransactor) GetAndUpdateEffectiveDelegatedByHolderToValidator(opts *bind.TransactOpts, holder common.Address, validatorId *big.Int, month *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.contract.Transact(opts, \"getAndUpdateEffectiveDelegatedByHolderToValidator\", holder, validatorId, month)\n}", "func (a *Account) Deposit(amt int64) (newBal int64, ok bool) {\n\tif a.defunct == 1 {\n\t\treturn 0, false\n\t}\n\n\t// deposits are safe; just add them atomically\n\tif amt >= 0 {\n\t\treturn atomic.AddInt64(&a.amt, amt), true\n\t}\n\n\t// withdrawal; make sure decision is based on fresh value\n\tconclusive := false\n\tvar bal int64\n\tfor !conclusive {\n\t\tbal = a.amt // work on a copy, not the hot original\n\t\tif -amt > bal {\n\t\t\treturn a.amt, false\n\t\t}\n\t\tconclusive = atomic.CompareAndSwapInt64(&a.amt, bal, amt+bal)\n\t}\n\treturn (bal + amt), true\n}", "func (_DelegationController *DelegationControllerSession) GetAndUpdateEffectiveDelegatedByHolderToValidator(holder common.Address, validatorId *big.Int, month *big.Int) (*types.Transaction, error) {\n\treturn _DelegationController.Contract.GetAndUpdateEffectiveDelegatedByHolderToValidator(&_DelegationController.TransactOpts, holder, validatorId, month)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowCaller) DepositRedelegatedAmount(opts *bind.CallOpts, operator common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokenStakingEscrow.contract.Call(opts, out, \"depositRedelegatedAmount\", operator)\n\treturn *ret0, err\n}", "func (k Querier) Delegation(ctx context.Context, req *types.QueryDelegationRequest) (*types.QueryDelegationResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"empty request\")\n\t}\n\n\tif req.DelegatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"delegator address cannot be empty\")\n\t}\n\tif req.ValidatorAddr == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"validator address cannot be empty\")\n\t}\n\n\tdelAddr, err := k.authKeeper.AddressCodec().StringToBytes(req.DelegatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalAddr, err := k.validatorAddressCodec.StringToBytes(req.ValidatorAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelegation, err := k.Delegations.Get(ctx, collections.Join(sdk.AccAddress(delAddr), sdk.ValAddress(valAddr)))\n\tif err != nil {\n\t\tif errors.Is(err, collections.ErrNotFound) {\n\t\t\treturn nil, status.Errorf(\n\t\t\t\tcodes.NotFound,\n\t\t\t\t\"delegation with delegator %s not found for validator %s\",\n\t\t\t\treq.DelegatorAddr, req.ValidatorAddr)\n\t\t}\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tdelResponse, err := delegationToDelegationResponse(ctx, k.Keeper, delegation)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryDelegationResponse{DelegationResponse: &delResponse}, nil\n}", "func (c *Client) PropagateBalance(\n\tctx context.Context,\n\tid string,\n\tmint string,\n) (*BalanceResource, error) {\n\treq, err := http.NewRequest(\"POST\",\n\t\tFullMintURL(ctx, mint,\n\t\t\tfmt.Sprintf(\"/balances/%s\", id), url.Values{}).String(), nil)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\treq.Header.Add(\"Mint-Protocol-Version\", ProtocolVersion)\n\tr, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tdefer r.Body.Close()\n\n\tvar raw svc.Resp\n\tif err := json.NewDecoder(r.Body).Decode(&raw); err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tif r.StatusCode != http.StatusOK && r.StatusCode != http.StatusCreated {\n\t\tvar e errors.ConcreteUserError\n\t\terr = raw.Extract(\"error\", &e)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\treturn nil, errors.Trace(ErrMintClient{\n\t\t\tr.StatusCode, e.ErrCode, e.ErrMessage,\n\t\t})\n\t}\n\n\tvar balance BalanceResource\n\tif err := raw.Extract(\"balance\", &balance); err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treturn &balance, nil\n}", "func (a *Account) Deposit (amount int) {\n\ta.balance += amount\n}", "func (k Keeper) SetWithdrawAddr(ctx sdk.Context, delegatorId chainTypes.AccountID, withdrawId chainTypes.AccountID) error {\n\tif k.blacklistedAddrs[withdrawId.String()] {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, \"%s is blacklisted from receiving external funds\", withdrawId)\n\t}\n\n\tif !k.GetWithdrawAddrEnabled(ctx) {\n\t\treturn types.ErrSetWithdrawAddrDisabled\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeSetWithdrawAddress,\n\t\t\tsdk.NewAttribute(types.AttributeKeyWithdrawAddress, withdrawId.String()),\n\t\t),\n\t)\n\n\tk.SetDelegatorWithdrawAddr(ctx, delegatorId, withdrawId)\n\treturn nil\n}", "func (s *State) AdvanceUpdate(ua UpdateAdvancement) (err error) {\n\tw, err := s.LoadWallet(ua.WalletID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor i := range w.Sector.ActiveUpdates {\n\t\tif w.Sector.ActiveUpdates[i].Event.UpdateIndex == ua.UpdateIndex {\n\t\t\tw.Sector.ActiveUpdates[i].Confirmations[ua.SiblingIndex] = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\terr = s.SaveWallet(w)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (a *Account) Deposit(amount int) {\n\ta.balance += amount\n}" ]
[ "0.63843423", "0.6348469", "0.63280714", "0.6127292", "0.6099896", "0.59851784", "0.5903084", "0.5901659", "0.58393365", "0.57900774", "0.5761572", "0.5679458", "0.5625733", "0.562472", "0.55934227", "0.5562052", "0.55510765", "0.5547109", "0.55152845", "0.55124575", "0.5427714", "0.53968793", "0.5304026", "0.529983", "0.5286176", "0.5281452", "0.5228556", "0.5206727", "0.5188", "0.51672626", "0.5164376", "0.5146589", "0.51269794", "0.5070188", "0.50552267", "0.5046415", "0.5042505", "0.5038563", "0.5010161", "0.49685147", "0.49684387", "0.49561948", "0.49232695", "0.4907573", "0.4905251", "0.49020055", "0.48969635", "0.4892147", "0.48862943", "0.487867", "0.4849024", "0.48318028", "0.48290014", "0.4828362", "0.4806713", "0.48037153", "0.480348", "0.47881603", "0.47571716", "0.47515076", "0.47296995", "0.4724797", "0.47204968", "0.47176188", "0.47148028", "0.47049314", "0.46647286", "0.46538943", "0.46441612", "0.46438286", "0.46375227", "0.46301252", "0.46250084", "0.4619643", "0.4614884", "0.4612812", "0.46021104", "0.45953768", "0.45928022", "0.45914862", "0.45818037", "0.45769206", "0.45756292", "0.45722038", "0.45695314", "0.45660195", "0.45551983", "0.45551953", "0.45551834", "0.4554903", "0.45540223", "0.45500895", "0.45451683", "0.4531914", "0.4516473", "0.45037776", "0.44993067", "0.44921425", "0.44859782", "0.4483" ]
0.8535179
0
NewClawbackAction returns an exported.ClawbackAction for ClawbackVestingAccount.
func NewClawbackAction(requestor, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) exported.ClawbackAction { return clawbackAction{ requestor: requestor, dest: dest, ak: ak, bk: bk, sk: sk, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewClawbackGrantAction(\n\tfunderAddress string,\n\tsk StakingKeeper,\n\tgrantStartTime int64,\n\tgrantLockupPeriods, grantVestingPeriods []Period,\n\tgrantCoins sdk.Coins,\n) exported.AddGrantAction {\n\treturn clawbackGrantAction{\n\t\tfunderAddress: funderAddress,\n\t\tsk: sk,\n\t\tgrantStartTime: grantStartTime,\n\t\tgrantLockupPeriods: grantLockupPeriods,\n\t\tgrantVestingPeriods: grantVestingPeriods,\n\t\tgrantCoins: grantCoins,\n\t}\n}", "func NewClawbackRewardAction(ak AccountKeeper, bk BankKeeper, sk StakingKeeper) exported.RewardAction {\n\treturn clawbackRewardAction{\n\t\tak: ak,\n\t\tbk: bk,\n\t\tsk: sk,\n\t}\n}", "func NewClawbackVestingAccount(baseAcc *authtypes.BaseAccount, funder sdk.AccAddress, originalVesting sdk.Coins, startTime int64, lockupPeriods, vestingPeriods Periods) *ClawbackVestingAccount {\n\t// copy and align schedules to avoid mutating inputs\n\tlp := make(Periods, len(lockupPeriods))\n\tcopy(lp, lockupPeriods)\n\tvp := make(Periods, len(vestingPeriods))\n\tcopy(vp, vestingPeriods)\n\t_, endTime := AlignSchedules(startTime, startTime, lp, vp)\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ClawbackVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tFunderAddress: funder.String(),\n\t\tStartTime: startTime,\n\t\tLockupPeriods: lp,\n\t\tVestingPeriods: vp,\n\t}\n}", "func NewCollateralizeAction(c *Collateralize, tx *types.Transaction, index int) *Action {\n\thash := tx.Hash()\n\tfromaddr := tx.From()\n\tcfg := c.GetAPI().GetConfig()\n\ttokenDb, err := account.NewAccountDB(cfg, tokenE.GetName(), pty.CCNYTokenName, c.GetStateDB())\n\tif err != nil {\n\t\tclog.Error(\"NewCollateralizeAction\", \"Get Account DB error\", \"error\", err)\n\t\treturn nil\n\t}\n\n\treturn &Action{\n\t\tcoinsAccount: c.GetCoinsAccount(), tokenAccount: tokenDb, db: c.GetStateDB(), localDB: c.GetLocalDB(),\n\t\ttxhash: hash, fromaddr: fromaddr, blocktime: c.GetBlockTime(), height: c.GetHeight(),\n\t\texecaddr: dapp.ExecAddress(string(tx.Execer)), difficulty: c.GetDifficulty(), index: index, Collateralize: c}\n}", "func (va *ClawbackVestingAccount) clawback(ctx sdk.Context, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) error {\n\t// Compute the clawback based on the account state only, and update account\n\ttoClawBack := va.computeClawback(ctx.BlockTime().Unix())\n\tif toClawBack.IsZero() {\n\t\treturn nil\n\t}\n\taddr := va.GetAddress()\n\tbondDenom := sk.BondDenom(ctx)\n\n\t// Compute the clawback based on bank balance and delegation, and update account\n\tencumbered := va.GetVestingCoins(ctx.BlockTime())\n\tbondedAmt := sk.GetDelegatorBonded(ctx, addr)\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, addr)\n\tbonded := sdk.NewCoins(sdk.NewCoin(bondDenom, bondedAmt))\n\tunbonding := sdk.NewCoins(sdk.NewCoin(bondDenom, unbondingAmt))\n\tunbonded := bk.GetAllBalances(ctx, addr)\n\ttoClawBack = va.updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded)\n\n\t// Write now now so that the bank module sees unvested tokens are unlocked.\n\t// Note that all store writes are aborted if there is a panic, so there is\n\t// no danger in writing incomplete results.\n\tak.SetAccount(ctx, va)\n\n\t// Now that future vesting events (and associated lockup) are removed,\n\t// the balance of the account is unlocked and can be freely transferred.\n\tspendable := bk.SpendableCoins(ctx, addr)\n\ttoXfer := coinsMin(toClawBack, spendable)\n\terr := bk.SendCoins(ctx, addr, dest, toXfer)\n\tif err != nil {\n\t\treturn err // shouldn't happen, given spendable check\n\t}\n\ttoClawBack = toClawBack.Sub(toXfer)\n\n\t// We need to traverse the staking data structures to update the\n\t// vesting account bookkeeping, and to recover more funds if necessary.\n\t// Staking is the only way unvested tokens should be missing from the bank balance.\n\n\t// If we need more, transfer UnbondingDelegations.\n\twant := toClawBack.AmountOf(bondDenom)\n\tunbondings := sk.GetUnbondingDelegations(ctx, addr, math.MaxUint16)\n\tfor _, unbonding := range unbondings {\n\t\tvalAddr, err := sdk.ValAddressFromBech32(unbonding.ValidatorAddress)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttransferred := sk.TransferUnbonding(ctx, addr, dest, valAddr, want)\n\t\twant = want.Sub(transferred)\n\t\tif !want.IsPositive() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If we need more, transfer Delegations.\n\tif want.IsPositive() {\n\t\tdelegations := sk.GetDelegatorDelegations(ctx, addr, math.MaxUint16)\n\t\tfor _, delegation := range delegations {\n\t\t\tvalidatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // shouldn't happen\n\t\t\t}\n\t\t\tvalidator, found := sk.GetValidator(ctx, validatorAddr)\n\t\t\tif !found {\n\t\t\t\t// validator has been removed\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twantShares, err := validator.SharesFromTokensTruncated(want)\n\t\t\tif err != nil {\n\t\t\t\t// validator has no tokens\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttransferredShares := sk.TransferDelegation(ctx, addr, dest, delegation.GetValidatorAddr(), wantShares)\n\t\t\t// to be conservative in what we're clawing back, round transferred shares up\n\t\t\ttransferred := validator.TokensFromSharesRoundUp(transferredShares).RoundInt()\n\t\t\twant = want.Sub(transferred)\n\t\t\tif !want.IsPositive() {\n\t\t\t\t// Could be slightly negative, due to rounding?\n\t\t\t\t// Don't think so, due to the precautions above.\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we've transferred everything and still haven't transferred the desired clawback amount,\n\t// then the account must have most some unvested tokens from slashing.\n\treturn nil\n}", "func NewBcBotAction(j *bot.Jobs) *BcBotAction {\n\t// client := resty.New()\n\t// client.\n\t// \tSetRetryCount(3).\n\t// \tSetRetryWaitTime(10 * time.Second)\n\treturn &BcBotAction{jobs: j, client: nil, mutex: new(sync.RWMutex)}\n}", "func (va *ClawbackVestingAccount) computeClawback(clawbackTime int64) sdk.Coins {\n\t// Compute the truncated vesting schedule and amounts.\n\t// Work with the schedule as the primary data and recompute derived fields, e.g. OriginalVesting.\n\tvestTime := va.StartTime\n\ttotalVested := sdk.NewCoins()\n\ttotalUnvested := sdk.NewCoins()\n\tunvestedIdx := 0\n\tfor i, period := range va.VestingPeriods {\n\t\tvestTime += period.Length\n\t\t// tie in time goes to clawback\n\t\tif vestTime < clawbackTime {\n\t\t\ttotalVested = totalVested.Add(period.Amount...)\n\t\t\tunvestedIdx = i + 1\n\t\t} else {\n\t\t\ttotalUnvested = totalUnvested.Add(period.Amount...)\n\t\t}\n\t}\n\tlastVestTime := vestTime\n\tnewVestingPeriods := va.VestingPeriods[:unvestedIdx]\n\n\t// To cap the unlocking schedule to the new total vested, conjunct with a limiting schedule\n\tcapPeriods := []Period{\n\t\t{\n\t\t\tLength: 0,\n\t\t\tAmount: totalVested,\n\t\t},\n\t}\n\t_, lastLockTime, newLockupPeriods := ConjunctPeriods(va.StartTime, va.StartTime, va.LockupPeriods, capPeriods)\n\n\t// Now construct the new account state\n\tva.OriginalVesting = totalVested\n\tva.EndTime = max64(lastVestTime, lastLockTime)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\t// DelegatedVesting and DelegatedFree will be adjusted elsewhere\n\n\treturn totalUnvested\n}", "func (h *Handler) NewAction(act action.Action, settings map[string]interface{}) *Action {\n\n\tvalue := reflect.ValueOf(act)\n\tvalue = value.Elem()\n\tref := value.Type().PkgPath()\n\n\tnewAct := &Action{ref: ref, settings: settings}\n\th.actions = append(h.actions, newAct)\n\n\treturn newAct\n}", "func NewRecoverableAction(supervisor *Supervisor) *RecoverableAction {\n\tra := &RecoverableAction{\n\t\tactionChan: make(chan Action),\n\t\treplyChan: make(chan string, 5),\n\t\tsupervisor: supervisor,\n\t}\n\n\tra.heartbeat = NewHeartbeat(ra, 1e8)\n\n\tgo ra.backend()\n\n\treturn ra\n}", "func NewAction(h *Hashlock, tx *types.Transaction, execaddr string) *Action {\n\thash := tx.Hash()\n\tfromaddr := tx.From()\n\treturn &Action{h.GetCoinsAccount(), h.GetStateDB(), hash, fromaddr, h.GetBlockTime(), h.GetHeight(), execaddr, h.GetAPI()}\n}", "func CreateAction(action func(*cli.Context) error) func(*cli.Context) error {\n\treturn func(c *cli.Context) error {\n\t\terr := action(c)\n\t\tif err != nil {\n\t\t\tiocli.Error(\"%s\", err)\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func NewCheck() beekeeper.Action {\n\treturn &Check{}\n}", "func NewAction(app *buffalo.App) *Action {\n\tas := &Action{\n\t\tApp: app,\n\t\tModel: NewModel(),\n\t}\n\treturn as\n}", "func New() Action {\n\treturn &action{}\n}", "func NewAction(name string, arg interface{}) {\n\tDefaultActionRegistry.Post(name, arg)\n}", "func NewRollbackAction(kit kit.Kit, viper *viper.Viper,\n\tauthSvrCli pbauthserver.AuthClient, dataMgrCli pbdatamanager.DataManagerClient,\n\tgseControllerCli pbgsecontroller.GSEControllerClient,\n\treq *pb.RollbackReleaseReq, resp *pb.RollbackReleaseResp) *RollbackAction {\n\n\taction := &RollbackAction{\n\t\tkit: kit,\n\t\tviper: viper,\n\t\tauthSvrCli: authSvrCli,\n\t\tdataMgrCli: dataMgrCli,\n\t\tgseControllerCli: gseControllerCli,\n\t\treq: req,\n\t\tresp: resp,\n\t}\n\n\taction.resp.Result = true\n\taction.resp.Code = pbcommon.ErrCode_E_OK\n\taction.resp.Message = \"OK\"\n\n\treturn action\n}", "func NewChallengeAction(msg *Message) (*ChallengeAction, error) {\n\taction := &ChallengeAction{*msg}\n\n\treturn action, nil\n}", "func NewAction(t *Pos33Ticket, tx *types.Transaction) *Action {\n\thash := tx.Hash()\n\tfromaddr := tx.From()\n\treturn &Action{t.GetCoinsAccount(), t.GetStateDB(), hash, fromaddr,\n\t\tt.GetBlockTime(), t.GetHeight(), dapp.ExecAddress(string(tx.Execer)), t.GetAPI()}\n}", "func NewAction(payload interface{}) Action {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error: %v\\n\", r)\n\t\t\tfmt.Fprintf(os.Stderr, \"Payload: %v\\n\", payload)\n\t\t}\n\t}()\n\n\tvar a Action\n\ta.payload = payload\n\ta.headers = make(map[string]string)\n\n\tfor k, v := range payload.(map[interface{}]interface{}) {\n\t\tswitch k {\n\t\tcase \"catch\":\n\t\t\ta.catch = v.(string)\n\t\tcase \"warnings\":\n\t\t\t// TODO\n\t\t\tcontinue\n\t\tcase \"allowed_warnings\":\n\t\t\t// TODO\n\t\t\tcontinue\n\t\tcase \"node_selector\":\n\t\t\tcontinue\n\t\tcase \"headers\":\n\t\t\tfor kk, vv := range v.(map[interface{}]interface{}) {\n\t\t\t\ta.headers[kk.(string)] = vv.(string)\n\t\t\t}\n\t\tdefault:\n\t\t\ta.method = k.(string)\n\t\t\ta.params = v.(map[interface{}]interface{})\n\t\t}\n\t}\n\n\treturn a\n}", "func CreateAction(\n\tcmd, keyB, id, secretKey string,\n\targs ...interface{}) *types.Action {\n\n\tmac := hmac.New(sha1.New, []byte(secretKey))\n\tmac.Write([]byte(cmd))\n\tmac.Write([]byte(keyB))\n\tmac.Write([]byte(id))\n\tsum := mac.Sum(nil)\n\tsumhex := hex.EncodeToString(sum)\n\n\treturn &types.Action{\n\t\tCommand: cmd,\n\t\tStorageKey: keyB,\n\t\tArgs: args,\n\t\tId: id,\n\t\tSecret: sumhex,\n\t}\n}", "func NewAction() actions.Action {\n\treturn &Action{}\n}", "func NewAction() actions.Action {\n\treturn &Action{}\n}", "func NewAction() actions.Action {\n\treturn &action{}\n}", "func NewRecvAction(args any) *Action {\n\treturn &Action{Args: args}\n}", "func New() *Action {\n\treturn &Action{}\n}", "func NewTriggerAction(agentName string, propertyName string, propertyValue string) *TriggerAction {\n instance := new(TriggerAction)\n instance.agentName = agentName\n instance.propertyName = propertyName\n instance.propertyValue = propertyValue\n return instance\n}", "func NewCheckmate(winner Colour) Outcome { return Outcome{Winner: winner, Reason: checkmate} }", "func (cga clawbackGrantAction) AddToAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported,\n\t\t\t\"account %s must be a ClawbackVestingAccount, got %T\",\n\t\t\trawAccount.GetAddress(), rawAccount)\n\t}\n\tif cga.funderAddress != cva.FunderAddress {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"account %s can only accept grants from account %s\",\n\t\t\trawAccount.GetAddress(), cva.FunderAddress)\n\t}\n\tcva.addGrant(ctx, cga.sk, cga.grantStartTime, cga.grantLockupPeriods, cga.grantVestingPeriods, cga.grantCoins)\n\treturn nil\n}", "func NewAuthorizeAction(ctx context.Context, viper *viper.Viper, authMode string,\n\tlocalAuthController *local.Controller, bkiamAuthController *bkiam.Controller,\n\treq *pb.AuthorizeReq, resp *pb.AuthorizeResp) *AuthorizeAction {\n\n\taction := &AuthorizeAction{\n\t\tctx: ctx,\n\t\tviper: viper,\n\t\tauthMode: authMode,\n\t\tlocalAuthController: localAuthController,\n\t\tbkiamAuthController: bkiamAuthController,\n\t\treq: req,\n\t\tresp: resp,\n\t}\n\n\taction.resp.Seq = req.Seq\n\taction.resp.Code = pbcommon.ErrCode_E_OK\n\taction.resp.Message = \"OK\"\n\n\treturn action\n}", "func New() *Action {\n\treturn &Action{w: os.Stdout}\n}", "func CreateAction(r *Raptor) *Action {\n\treturn &Action{\n\t\tRaptor: r,\n\t}\n}", "func NewAction(cmd Command) Action {\n\tswitch cmd.name {\n\tcase buildCommand:\n\t\treturn NewBuildAction(afero.NewOsFs(), cmd.helmRepoName, cmd.artifactsPath)\n\tdefault:\n\t\treturn ShowAction{}\n\t}\n}", "func NewSecretAction(logger logrus.FieldLogger, client client.Client) *SecretAction {\n\treturn &SecretAction{\n\t\tlogger: logger,\n\t\tclient: client,\n\t}\n}", "func NewAction(fn ActionFn) *Action {\n\treturn &Action{\n\t\tfn: fn,\n\t\tdoneCh: make(chan struct{}),\n\t}\n}", "func NewCreateAction(model store.ClusterManagerModel) *CreateAction {\n\treturn &CreateAction{\n\t\tmodel: model,\n\t}\n}", "func NewAction(conf config.Server) Action {\n\treturn Action{\n\t\ttcp: tcp.NewService(conf),\n\t\tudp: udp.NewService(conf),\n\t}\n}", "func NewEvictAction() Action {\n\treturn &evictAction{}\n}", "func New() *Clac {\n\tc := &Clac{keepHist: true}\n\tc.Reset()\n\treturn c\n}", "func (act *ActionTrace) Action() (*ActionTrace, error) {\n\treturn act, nil\n}", "func (t tSessions) newC(w http.ResponseWriter, r *http.Request, ctr, act string) *contr.Sessions {\n\t// Allocate a new controller. Set values of special fields, if necessary.\n\tc := &contr.Sessions{\n\n\t\tRequest: r,\n\n\t\tResponse: w,\n\t}\n\n\treturn c\n}", "func NewCreateAction(kit kit.Kit, viper *viper.Viper,\n\tauthSvrCli pbauthserver.AuthClient, dataMgrCli pbdatamanager.DataManagerClient,\n\treq *pb.CreateStrategyReq, resp *pb.CreateStrategyResp) *CreateAction {\n\n\taction := &CreateAction{\n\t\tkit: kit,\n\t\tviper: viper,\n\t\tauthSvrCli: authSvrCli,\n\t\tdataMgrCli: dataMgrCli,\n\t\treq: req,\n\t\tresp: resp,\n\t}\n\n\taction.resp.Result = true\n\taction.resp.Code = pbcommon.ErrCode_E_OK\n\taction.resp.Message = \"OK\"\n\n\taction.labelsOr = []map[string]string{}\n\taction.labelsAnd = []map[string]string{}\n\n\treturn action\n}", "func NewCreateAction(model store.ClusterManagerModel, k8sop *clusterops.K8SOperator) *CreateAction {\n\treturn &CreateAction{\n\t\tmodel: model,\n\t\tk8sop: k8sop,\n\t}\n}", "func NewLabelActionBase()(*LabelActionBase) {\n m := &LabelActionBase{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func NewCreateAction(viper *viper.Viper, dataMgrCli pbdatamanager.DataManagerClient,\n\treq *pb.CreateAppReq, resp *pb.CreateAppResp) *CreateAction {\n\taction := &CreateAction{viper: viper, dataMgrCli: dataMgrCli, req: req, resp: resp}\n\n\taction.resp.Seq = req.Seq\n\taction.resp.ErrCode = pbcommon.ErrCode_E_OK\n\taction.resp.ErrMsg = \"OK\"\n\n\treturn action\n}", "func CreateUserAction(context *web.AppContext) *web.AppError {\n\n\tdb := context.MDB\n\tvar input model.CayUserAction\n\tjson.NewDecoder(context.Body).Decode(&input)\n\n\tinput.ID = bson.NewObjectId()\n\tinput.Date = time.Now()\n\tif input.Release == \"\" {\n\t\tinput.Release = \"0.1.0\"\n\t}\n\terr := db.DB.C(model.CayUserActions).Insert(input)\n\tif err != nil {\n\t\tmessage := fmt.Sprintf(\"Error creating user-action [%s]\", err)\n\t\treturn &web.AppError{err, message, http.StatusInternalServerError}\n\t}\n\n\treturn nil\n}", "func CiActionInstall(parent interface{}) error {\n\tthis := parent.(*ActionSaver)\n\tthis.SetParam(\"success\", \"ciserver\")\n\terr, _, _, _ := executeCommand(makeArgsFromString(\"systemctl enable citool\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tthis.SetParam(\"success\", \"ciserver_en\")\n\n\tdata0, err := data.Asset(\"cisetup/src/data/sudoers\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(\"/etc/sudoers\", data0, 0440)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr, _, _, _ = executeCommand(makeArgsFromString(\"setcap cap_sys_chroot+ep /usr/sbin/chroot\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr, _, _, _ = executeCommand(makeArgsFromString(\"setcap cap_sys_chroot+ep /usr/sbin/citool\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata2_2_tmp, err := data.Asset(\"cisetup/src/data/citool.ini\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata2_2 := replace_string(data2_2_tmp, \"sonarPASSSWD\", db_passwd)\n\terr = ioutil.WriteFile(\"/etc/citool.ini\", data2_2, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr, _, _, _ = executeCommand(makeArgsFromString(\"systemctl start citool\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr, _, _, _ = executeCommand(makeArgsFromString(\"/usr/bin/chown checker:checker /etc/citool.ini\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tthis.SetParam(\"success\", \"ciserver_st\")\n\n\tdata3_3, err := data.Asset(\"cisetup/src/data/config\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(\"/root/config\", data3_3, 0400)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Create(\n\tcontext contexts.Contextable,\n\tlogger *logger.Logger,\n\tconnection *golastic.Connection,\n\tqueue *notifications.Queue,\n\tctx context.Context,\n) (Actionable, error) {\n\taction, err := build(context.Action())\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := action.Init(context, logger, connection, queue, ctx); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := action.ApplyOptions().ApplyFilters(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn action, nil\n}", "func (ca clawbackAction) TakeFromAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported, \"clawback expects *ClawbackVestingAccount, got %T\", rawAccount)\n\t}\n\tif ca.requestor.String() != cva.FunderAddress {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"clawback can only be requested by original funder %s\", cva.FunderAddress)\n\t}\n\treturn cva.clawback(ctx, ca.dest, ca.ak, ca.bk, ca.sk)\n}", "func newKubeadmConfigAction() Action {\n\treturn &kubeadmConfigAction{}\n}", "func (e *ExpectedClusterSetup) WithAction(action interface{}) *ExpectedClusterSetup {\n\te.arg0 = action\n\treturn e\n}", "func CreateBackupAction(service *pgCommon.PostgresServiceInformations) action.IAction {\n\treturn action.FormAction{\n\t\tName: \"Backup\",\n\t\tUniqueCommand: \"cmd_pg_create_backup\",\n\t\tPlaceholder: nil,\n\t\tActionExecuteCallback: func(placeholder interface{}) (interface{}, error) {\n\t\t\treturn nil, CreateBackup(service)\n\t\t},\n\t}\n}", "func (t tApp) newC(w http.ResponseWriter, r *http.Request, ctr, act string) *contr.App {\n\t// Allocate a new controller. Set values of special fields, if necessary.\n\tc := &contr.App{}\n\n\t// Allocate its parents. Make sure controller of every type\n\t// is allocated just once, then reused.\n\tc.Controllers = &contr.Controllers{}\n\tc.Controllers.Templates = c.Controllers.Errors.Templates\n\tc.Controllers.Errors = &c5.Errors{}\n\tc.Controllers.Static = &c3.Static{}\n\tc.Controllers.Sessions = &c2.Sessions{\n\n\t\tRequest: r,\n\n\t\tResponse: w,\n\t}\n\tc.Controllers.Requests = &c1.Requests{\n\n\t\tRequest: r,\n\n\t\tResponse: w,\n\t}\n\tc.Controllers.Global = &c0.Global{\n\n\t\tCurrentAction: act,\n\n\t\tCurrentController: ctr,\n\t}\n\tc.Controllers.Errors.Templates = &c4.Templates{}\n\tc.Controllers.Errors.Templates.Requests = c.Controllers.Requests\n\tc.Controllers.Errors.Templates.Global = c.Controllers.Global\n\tc.Controllers.Templates.Requests = c.Controllers.Requests\n\tc.Controllers.Templates.Global = c.Controllers.Global\n\n\treturn c\n}", "func NewActions(a ...Action) {\n\tDefaultActionRegistry.PostBatch(a...)\n}", "func NewAction(name string) *Action {\n\ta := &Action{\n\t\tName: name,\n\t\tEnabled: true,\n\t}\n\treturn a\n}", "func NewGetAction(model store.ClusterManagerModel) *GetAction {\n\treturn &GetAction{\n\t\tmodel: model,\n\t}\n}", "func GetAction(client *whisk.Client, actionName string) func() (*whisk.Action, error) {\n\treturn func() (*whisk.Action, error) {\n\t\taction, _, err := client.Actions.Get(actionName, true)\n\t\tif err == nil {\n\t\t\treturn action, nil\n\t\t}\n\t\treturn nil, err\n\t}\n}", "func NewWebhook() *NamespaceWebhook {\n\tscheme := runtime.NewScheme()\n\terr := admissionv1.AddToScheme(scheme)\n\tif err != nil {\n\t\tlog.Error(err, \"Fail adding admissionsv1 scheme to NamespaceWebhook\")\n\t\tos.Exit(1)\n\t}\n\n\terr = corev1.AddToScheme(scheme)\n\tif err != nil {\n\t\tlog.Error(err, \"Fail adding corev1 scheme to NamespaceWebhook\")\n\t\tos.Exit(1)\n\t}\n\n\treturn &NamespaceWebhook{\n\t\ts: *scheme,\n\t}\n}", "func newClaBuilder(clusterName string, dropPercents []uint32) *claBuilder {\n\tvar drops []*v3endpointpb.ClusterLoadAssignment_Policy_DropOverload\n\tfor i, d := range dropPercents {\n\t\tdrops = append(drops, &v3endpointpb.ClusterLoadAssignment_Policy_DropOverload{\n\t\t\tCategory: fmt.Sprintf(\"test-drop-%d\", i),\n\t\t\tDropPercentage: &v3typepb.FractionalPercent{\n\t\t\t\tNumerator: d,\n\t\t\t\tDenominator: v3typepb.FractionalPercent_HUNDRED,\n\t\t\t},\n\t\t})\n\t}\n\n\treturn &claBuilder{\n\t\tv: &v3endpointpb.ClusterLoadAssignment{\n\t\t\tClusterName: clusterName,\n\t\t\tPolicy: &v3endpointpb.ClusterLoadAssignment_Policy{\n\t\t\t\tDropOverloads: drops,\n\t\t\t},\n\t\t},\n\t}\n}", "func NewListAction(model store.ClusterManagerModel) *ListAction {\n\treturn &ListAction{\n\t\tmodel: model,\n\t}\n}", "func FactoryAction(factory CommandFactory, log logging.Logger, cmdName string) func(*cli.Context) {\n\treturn func(c *cli.Context) {\n\t\tcmd := factory(c, log, cmdName)\n\t\texit, err := cmd.Run()\n\n\t\t// For API reasons, we may return an error but a zero exit code. So we want\n\t\t// to check and log both.\n\t\tif exit != 0 || err != nil {\n\t\t\tlog.Error(\n\t\t\t\t\"Command encountered error. command:%s, exit:%d, err:%s\",\n\t\t\t\tcmdName, exit, err,\n\t\t\t)\n\t\t}\n\n\t\tos.Exit(exit)\n\t}\n}", "func (m *Client) CreateWebhook(arg0 context.Context, arg1 *zendesk.Webhook) (*zendesk.Webhook, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateWebhook\", arg0, arg1)\n\tret0, _ := ret[0].(*zendesk.Webhook)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewActionResultPart()(*ActionResultPart) {\n m := &ActionResultPart{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}", "func NewWatcherAction() *WatcherAction {\n\tr := &WatcherAction{}\n\n\treturn r\n}", "func NewSendAction(serviceType, actionName string, args any) *Action {\n\treturn &Action{\n\t\tXMLName: xml.Name{Space: serviceType, Local: actionName},\n\t\tArgs: args,\n\t}\n}", "func NewAccessControl(address common.Address, backend bind.ContractBackend) (*AccessControl, error) {\n\tcontract, err := bindAccessControl(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AccessControl{AccessControlCaller: AccessControlCaller{contract: contract}, AccessControlTransactor: AccessControlTransactor{contract: contract}, AccessControlFilterer: AccessControlFilterer{contract: contract}}, nil\n}", "func NewAccessControl(address common.Address, backend bind.ContractBackend) (*AccessControl, error) {\n\tcontract, err := bindAccessControl(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AccessControl{AccessControlCaller: AccessControlCaller{contract: contract}, AccessControlTransactor: AccessControlTransactor{contract: contract}, AccessControlFilterer: AccessControlFilterer{contract: contract}}, nil\n}", "func NewAction(action EngineAction) *PacketUnstable {\n\tpkt := &PacketUnstable{}\n\tswitch action := action.(type) {\n\tcase ButtonPressedAction:\n\t\tpkt.Cmd = CmdButtonPressedAction\n\tcase ButtonReleasedAction:\n\t\tpkt.Cmd = CmdButtonReleasedAction\n\tdefault:\n\t\tpanic(fmt.Errorf(\"support for action %T not yet implemented\", action))\n\t}\n\tbuf := &bytes.Buffer{}\n\tif err := binary.Write(buf, binary.LittleEndian, action); err != nil {\n\t\tdie(err)\n\t}\n\tpkt.Data = buf.Bytes()\n\treturn pkt\n}", "func NewListAction(model store.ProjectModel) *ListAction {\n\treturn &ListAction{\n\t\tmodel: model,\n\t}\n}", "func NewController(bucket WalletBucket) BaseController {\n\tValidateWalletBucket(bucket)\n\treturn BaseController{bucket: bucket}\n}", "func (c WafAction) ToPtr() *WafAction {\n\treturn &c\n}", "func (t tApp) New(w http.ResponseWriter, r *http.Request, ctr, act string) *contr.App {\n\tc := &contr.App{}\n\tc.Controllers = Controllers.New(w, r, ctr, act)\n\treturn c\n}", "func NewActionAgent(\n\ttabletAlias topo.TabletAlias,\n\tdbcfgs *dbconfigs.DBConfigs,\n\tmycnf *mysqlctl.Mycnf,\n\tport, securePort int,\n\toverridesFile string,\n) (agent *ActionAgent, err error) {\n\tschemaOverrides := loadSchemaOverrides(overridesFile)\n\n\ttopoServer := topo.GetServer()\n\tmysqld := mysqlctl.NewMysqld(\"Dba\", mycnf, &dbcfgs.Dba, &dbcfgs.Repl)\n\n\tagent = &ActionAgent{\n\t\tTopoServer: topoServer,\n\t\tTabletAlias: tabletAlias,\n\t\tMysqld: mysqld,\n\t\tDBConfigs: dbcfgs,\n\t\tSchemaOverrides: schemaOverrides,\n\t\tdone: make(chan struct{}),\n\t\tHistory: history.New(historyLength),\n\t\tchangeItems: make(chan tabletChangeItem, 100),\n\t}\n\n\t// Start the binlog player services, not playing at start.\n\tagent.BinlogPlayerMap = NewBinlogPlayerMap(topoServer, &dbcfgs.App.ConnectionParams, mysqld)\n\tRegisterBinlogPlayerMap(agent.BinlogPlayerMap)\n\n\t// try to figure out the mysql port\n\tmysqlPort := mycnf.MysqlPort\n\tif mysqlPort == 0 {\n\t\t// we don't know the port, try to get it from mysqld\n\t\tvar err error\n\t\tmysqlPort, err = mysqld.GetMysqlPort()\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"Cannot get current mysql port, will use 0 for now: %v\", err)\n\t\t}\n\t}\n\n\tif err := agent.Start(mysqlPort, port, securePort); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// register the RPC services from the agent\n\tagent.registerQueryService()\n\n\t// start health check if needed\n\tagent.initHeathCheck()\n\n\treturn agent, nil\n}", "func NewCookie(subCommands []*cobra.Command) *cobra.Command {\n\tvar cmd = cobra.Command{\n\t\tUse: \"cookie <command>\",\n\t\tShort: \"Cookie command group\",\n\t\tSilenceUsage: true,\n\t\tSilenceErrors: true,\n\t}\n\n\tcmd.AddCommand(subCommands...)\n\n\treturn &cmd\n}", "func CreateAction(req *http.Request) (interface{}, error) {\n\tparam, err := newCreateParam4Create(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn createActionProcess(req, param)\n}", "func NewFileAction(action string, path string) (*FileAction, error) {\n\tfa := new(FileAction)\n\tif err := fa.SetAction(action); err != nil {\n\t\treturn nil, err\n\t}\n\tfa.Path = path\n\treturn fa, nil\n}", "func NewCAPI(quit qu.C, timeout ...time.Duration) (c *CAPI) {\n\tc = &CAPI{quit: quit}\n\tif len(timeout)>0 {\n\t\tc.Timeout = timeout[0]\n\t} else {\n\t\tc.Timeout = time.Second * 5\n\t}\n\treturn \n}", "func newXactLLC(t cluster.Target, uuid string, bck cmn.Bck) *xactLLC {\n\treturn &xactLLC{xactBckBase: *newXactBckBase(uuid, cmn.ActLoadLomCache, bck, &mpather.JoggerGroupOpts{\n\t\tT: t,\n\t\tBck: bck,\n\t\tCTs: []string{fs.ObjectType},\n\t\tVisitObj: func(_ *cluster.LOM, _ []byte) error { return nil },\n\t\tDoLoad: mpather.Load,\n\t})}\n}", "func NewCreateGoalController(cgtRepos *persistence.Services, logger *log.Logger, authorizationService authorization.JwtService) Controller {\n\tcreateGoalUsecase := usecase.NewCreateGoalUsecase(&cgtRepos.Achiever, &cgtRepos.Goal, authorizationService)\n\n\tctrl := &createGoalController{\n\t\tUsecase: createGoalUsecase,\n\t\tLogger: logger,\n\t\tAuthorization: authorizationService,\n\t}\n\treturn ctrl\n}", "func NewCtrlJob(perfJob *perfv1alpha1.PerfJob, action string) *batchv1.Job {\n\tpodTemplate := makePodTemplate(perfJob.Spec.ControlImage, perfJob.Spec.Target, corev1.EnvVar{\n\t\tName: \"ACTION\",\n\t\tValue: action,\n\t})\n\treturn &batchv1.Job{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tGenerateName: \"ct-\" + perfJob.Name + \"-\",\n\t\t\tNamespace: perfJob.Namespace,\n\t\t\tLabels: JobLabels(perfJob.Name, action),\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t*metav1.NewControllerRef(perfJob, perfv1alpha1.SchemeGroupVersion.WithKind(\"PerfJob\")),\n\t\t\t},\n\t\t},\n\t\tSpec: batchv1.JobSpec{\n\t\t\tTemplate: *podTemplate,\n\t\t},\n\t}\n}", "func (policy *ticketPolicy) OnCreateNewAccount(acc *types.Account) {\n}", "func (c *Clair) NewClairV3Layer(ctx context.Context, r *registry.Registry, image string, fsLayer distribution.Descriptor) (*clairpb.PostAncestryRequest_PostLayer, error) {\n\t// Form the path.\n\tp := strings.Join([]string{r.URL, \"v2\", image, \"blobs\", fsLayer.Digest.String()}, \"/\")\n\n\t// Get the headers.\n\th, err := r.Headers(ctx, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &clairpb.PostAncestryRequest_PostLayer{\n\t\tHash: fsLayer.Digest.String(),\n\t\tPath: p,\n\t\tHeaders: h,\n\t}, nil\n}", "func NewWebhook(client kubernetes.Interface, resources *WebhookResources, controllerNamespace string, noInitContainer bool) (*Webhook, error) {\n\tvar (\n\t\tscheme = runtime.NewScheme()\n\t\tcodecs = serializer.NewCodecFactory(scheme)\n\t)\n\n\treturn &Webhook{\n\t\tdeserializer: codecs.UniversalDeserializer(),\n\t\tcontrollerNamespace: controllerNamespace,\n\t\tresources: resources,\n\t\tnoInitContainer: noInitContainer,\n\t}, nil\n}", "func CreateClanHandler(app *App) func(c echo.Context) error {\n\treturn func(c echo.Context) error {\n\t\tc.Set(\"route\", \"CreateClan\")\n\t\tstart := time.Now()\n\t\tgameID := c.Param(\"gameID\")\n\n\t\tlogger := app.Logger.With(\n\t\t\tzap.String(\"source\", \"clanHandler\"),\n\t\t\tzap.String(\"operation\", \"createClan\"),\n\t\t\tzap.String(\"gameID\", gameID),\n\t\t)\n\n\t\tvar payload CreateClanPayload\n\t\tif err := LoadJSONPayload(&payload, c, logger); err != nil {\n\t\t\tlog.E(logger, \"Failed to parse json payload.\", func(cm log.CM) {\n\t\t\t\tcm.Write(zap.Error(err))\n\t\t\t})\n\t\t\treturn FailWith(400, err.Error(), c)\n\t\t}\n\n\t\tgame, err := app.GetGame(c.StdContext(), gameID)\n\t\tif err != nil {\n\t\t\tlog.W(logger, \"Could not find game.\", func(cm log.CM) {\n\t\t\t\tcm.Write(zap.Error(err))\n\t\t\t})\n\t\t\treturn FailWith(404, err.Error(), c)\n\t\t}\n\n\t\tvar clan *models.Clan\n\t\tvar tx interfaces.Transaction\n\n\t\trollback := func(err error) error {\n\t\t\ttxErr := app.Rollback(tx, \"Creating clan failed\", c, logger, err)\n\t\t\tif txErr != nil {\n\t\t\t\treturn txErr\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\n\t\ttx, err = app.BeginTrans(c.StdContext(), logger)\n\t\tif err != nil {\n\t\t\treturn FailWithError(err, c)\n\t\t}\n\n\t\tlog.D(logger, \"DB Tx begun successful.\")\n\n\t\tlog.D(logger, \"Creating clan...\")\n\t\tclan, err = models.CreateClan(\n\t\t\ttx,\n\t\t\tapp.EncryptionKey,\n\t\t\tgameID,\n\t\t\tpayload.PublicID,\n\t\t\tpayload.Name,\n\t\t\tpayload.OwnerPublicID,\n\t\t\tpayload.Metadata,\n\t\t\tpayload.AllowApplication,\n\t\t\tpayload.AutoJoin,\n\t\t\tgame.MaxClansPerPlayer,\n\t\t)\n\n\t\tif err != nil {\n\t\t\ttxErr := rollback(err)\n\t\t\tif txErr == nil {\n\t\t\t\tlog.E(logger, \"Create clan failed.\", func(cm log.CM) {\n\t\t\t\t\tcm.Write(zap.Error(err))\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn FailWithError(err, c)\n\t\t}\n\n\t\tclanJSON := map[string]interface{}{\n\t\t\t\"publicID\": clan.PublicID,\n\t\t\t\"name\": clan.Name,\n\t\t\t\"membershipCount\": clan.MembershipCount,\n\t\t\t\"ownerPublicID\": payload.OwnerPublicID,\n\t\t\t\"metadata\": clan.Metadata,\n\t\t\t\"allowApplication\": clan.AllowApplication,\n\t\t\t\"autoJoin\": clan.AutoJoin,\n\t\t}\n\n\t\tresult := map[string]interface{}{\n\t\t\t\"gameID\": gameID,\n\t\t\t\"clan\": clanJSON,\n\t\t}\n\n\t\tlog.D(logger, \"Dispatching hooks\")\n\t\terr = app.DispatchHooks(gameID, models.ClanCreatedHook, result)\n\t\tif err != nil {\n\t\t\ttxErr := rollback(err)\n\t\t\tif txErr == nil {\n\t\t\t\tlog.E(logger, \"Clan created hook dispatch failed.\", func(cm log.CM) {\n\t\t\t\t\tcm.Write(zap.Error(err))\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn FailWith(500, err.Error(), c)\n\t\t}\n\t\tlog.D(logger, \"Hook dispatched successfully.\")\n\n\t\terr = app.Commit(tx, \"Clan created\", c, logger)\n\t\tif err != nil {\n\t\t\treturn FailWith(500, err.Error(), c)\n\t\t}\n\n\t\tlog.D(logger, \"Clan created successfully.\", func(cm log.CM) {\n\t\t\tcm.Write(\n\t\t\t\tzap.String(\"clanPublicID\", clan.PublicID),\n\t\t\t\tzap.Duration(\"duration\", time.Now().Sub(start)),\n\t\t\t)\n\t\t})\n\n\t\treturn SucceedWith(map[string]interface{}{\n\t\t\t\"publicID\": clan.PublicID,\n\t\t}, c)\n\t}\n}", "func (c *Controller) AfterAction(action string) {\n}", "func (c *Controller) AfterAction(action string) {\n}", "func (o JobTemplateAbortCriteriaOutput) Action() JobTemplateActionOutput {\n\treturn o.ApplyT(func(v JobTemplateAbortCriteria) JobTemplateAction { return v.Action }).(JobTemplateActionOutput)\n}", "func NewFundedAccount() *keypair.Full {\n\tkp, err := keypair.Random()\n\tif err != nil {\n\t\tlog.Fatal(err, \"generating random keypair\")\n\t}\n\terr = FundAccount(kp.Address())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"successfully funded %s\", kp.Address())\n\treturn kp\n}", "func NewCampaignType(campaignTypeName, args string, cf *httpcli.Factory) (CampaignType, error) {\n\tcampaignTypeName = strings.ToLower(campaignTypeName)\n\n\tif cf == nil {\n\t\tcf = httpcli.NewFactory(\n\t\t\thttpcli.NewMiddleware(httpcli.ContextErrorMiddleware),\n\t\t\thttpcli.TracedTransportOpt,\n\t\t\thttpcli.NewCachedTransportOpt(httputil.Cache, true),\n\t\t)\n\t}\n\n\tcli, err := cf.Doer()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnormalizedArgs, err := validateArgs(campaignTypeName, args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar ct CampaignType\n\n\tswitch campaignTypeName {\n\tcase \"comby\":\n\t\tc := &comby{\n\t\t\treplacerURL: graphqlbackend.ReplacerURL,\n\t\t\thttpClient: cli,\n\t\t\tfetchTimeout: defaultFetchTimeout,\n\t\t}\n\n\t\tif err := json.Unmarshal(normalizedArgs, &c.args); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tct = c\n\n\tcase \"credentials\":\n\t\tc := &credentials{newSearch: graphqlbackend.NewSearchImplementer}\n\n\t\tif err := json.Unmarshal(normalizedArgs, &c.args); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tct = c\n\n\tcase patchCampaignType:\n\t\t// Prefer the more specific createCampaignPlanFromPatches GraphQL API for creating campaigns\n\t\t// from patches computed by the caller, to avoid having multiple ways to do the same thing.\n\t\treturn nil, errors.New(\"use createCampaignPlanFromPatches for patch campaign types\")\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown campaign type: %s\", campaignTypeName)\n\t}\n\n\treturn ct, nil\n}", "func NewShowAction() *ShowAction {\n\treturn &ShowAction{}\n}", "func newWoc() *wfOperationCtx {\n\twf := &wfv1.Workflow{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"test-wf\",\n\t\t\tNamespace: \"default\",\n\t\t},\n\t}\n\twoc := wfOperationCtx{\n\t\twf: wf,\n\t\torig: wf.DeepCopyObject().(*wfv1.Workflow),\n\t\tupdated: false,\n\t\tlog: log.WithFields(log.Fields{\n\t\t\t\"workflow\": wf.ObjectMeta.Name,\n\t\t\t\"namespace\": wf.ObjectMeta.Namespace,\n\t\t}),\n\t\tcontroller: &WorkflowController{\n\t\t\tConfig: WorkflowControllerConfig{\n\t\t\t\tExecutorImage: \"executor:latest\",\n\t\t\t},\n\t\t\tclientset: fake.NewSimpleClientset(),\n\t\t},\n\t\tcompletedPods: make(map[string]bool),\n\t}\n\treturn &woc\n}", "func newBkCli() (*bkCli, error) {\n\tconfig := config.CurrentConfig()\n\n\tclient, err := newClient(config)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &bkCli{config, client}, nil\n}", "func (a *Agent) startNewAction() {\n\tactionTypes := a.mind.actionTypes()\n\n\thighestValue := 0.0\n\tvar bestActionTypes []actionType\n\tfor _, t := range actionTypes {\n\t\tisActive := false\n\t\t// if we currently have an active action, we do not want to start a new action\n\t\tfor _, ac := range a.activity.activeActions {\n\t\t\tif ac.getState() == actionStateActive {\n\t\t\t\tisActive = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif isActive {\n\t\t\treturn\n\t\t}\n\n\t\t// TODO what if an action cannot be started\n\t\t// highest value is to eat an apple, but there is no apple, we should somehow start thinking\n\t\t// about how to obtain an apple\n\n\t\tv := actionTypeValue(t)\n\t\tif v >= highestValue {\n\t\t\tcanStart := true\n\t\t\tfor startCond := range t.getConditions()[actionConditionTypeStart] {\n\t\t\t\tif !startCond.isSatisfied(a) {\n\t\t\t\t\tcanStart = false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif canStart {\n\t\t\t\tif v > highestValue {\n\t\t\t\t\thighestValue = v\n\t\t\t\t\tbestActionTypes = []actionType{}\n\t\t\t\t}\n\t\t\t\tbestActionTypes = append(bestActionTypes, t)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(bestActionTypes) == 0 {\n\t\treturn\n\t}\n\n\tbestActionType := bestActionTypes[rand.Intn(len(bestActionTypes))]\n\tfor startCondition := range bestActionType.getConditions()[actionConditionTypeStart] {\n\t\tif !startCondition.isSatisfied(a) {\n\t\t\treturn\n\t\t}\n\t}\n\n\tnewAction := bestActionType.instantiate().(action)\n\ta.activity.activeActions = append(a.activity.activeActions, newAction)\n\ta.mind.addItem(bestActionType, 1.0)\n\n\t// add pre-action conditions for hypothesis training\n\tfor cond := range a.getConditions() {\n\t\tpreActionConditions := newAction.getType().getConditions()[actionConditionTypeObservedAtStart]\n\t\tpreActionConditions[cond] = true\n\t\tnewAction.getPreConditions()[cond] = true\n\t}\n}", "func createPayback(args []string) {\n\n\tpaybackRepo := payback.NewRepository(persistence.GetGormClient())\n\ttxnRepo := transaction.NewRepository(persistence.GetGormClient())\n\tpaybackSVC := payback.NewPaybackService(paybackRepo, txnRepo)\n\terr := paybackSVC.CreatePayback(context.Background(), args)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\tfmt.Println(\"Successfully added payback\")\n}", "func newChallengeValidationController(client *http.Client, webhooks []*Webhook) *challengeValidationController {\n\tscepHooks := []*Webhook{}\n\tfor _, wh := range webhooks {\n\t\tif wh.Kind != linkedca.Webhook_SCEPCHALLENGE.String() {\n\t\t\tcontinue\n\t\t}\n\t\tif !isCertTypeOK(wh) {\n\t\t\tcontinue\n\t\t}\n\t\tscepHooks = append(scepHooks, wh)\n\t}\n\treturn &challengeValidationController{\n\t\tclient: client,\n\t\twebhooks: scepHooks,\n\t}\n}", "func (l *ActionListener) Spawn(shutdown <-chan interface{}, actionID string) {\n\tdefer func() {\n\t\tglog.V(2).Infof(\"Action %s complete: \", actionID)\n\t\tif err := l.conn.Delete(l.GetPath(actionID)); err != nil {\n\t\t\tglog.Errorf(\"Could not delete %s: %s\", l.GetPath(actionID), err)\n\t\t}\n\t}()\n\n\tvar action Action\n\tif err := l.conn.Get(l.GetPath(actionID), &action); err != nil {\n\t\tglog.V(1).Infof(\"Could not get action %s: %s\", l.GetPath(actionID), err)\n\t\treturn\n\t}\n\n\tresult, err := l.handler.AttachAndRun(action.DockerID, action.Command)\n\tif result != nil && len(result) > 0 {\n\t\tglog.Info(string(result))\n\t}\n\tif err != nil {\n\t\tglog.Warningf(\"Error running command `%s` on container %s: %s\", action.Command, action.DockerID, err)\n\t} else {\n\t\tglog.V(1).Infof(\"Successfully ran command `%s` on container %s\", action.Command, action.DockerID)\n\t}\n}", "func generateAction(c *cli.Context) error {\n\tif c.NArg() != 1 {\n\t\treturn cli.NewExitError(fmt.Sprintf(\"%v %v requires exactly 1 argument\", c.App.Name, c.Command.Name), 1)\n\t}\n\n\tfilename, err := builder.CreateSkeletonFile(c.Args().First())\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\n\tfmt.Printf(\"successfully created template file %v\\n\", filename)\n\n\treturn nil\n}", "func (c *CoinTest) newAccount(stub shim.ChaincodeStubInterface, args []string) pb.Response {\r\n\tvar id string\r\n\tvar asset int\r\n\tvar err error\r\n\r\n\tif len(args) == 1{\r\n\t\tid = args[0]\r\n\t\tasset = 0\r\n\t}else if len(args) == 2{\r\n\t\tid = args[0]\r\n\t\t//asset, err = strconv.Atoi(args[1])\r\n\t\t//if err != nil{\r\n\t\t//\treturn shim.Error(\"Invalid asset amount, expecting a integer value\")\r\n\t\t//}\r\n\t\tasset = 0;\r\n\t}else{\r\n\t\treturn shim.Error(\"Incorrect number of arguments.\")\r\n\t}\r\n\r\n\t//deliver 0 number of TolakCoin to user\r\n\ttolakCoin.Token.Deliver(token.Address(id), int(asset))\r\n\r\n\t//write to ledger\r\n\terr = stub.PutState(id, []byte(strconv.Itoa(asset)))\r\n\tif err != nil{\r\n\t\treturn shim.Error(err.Error())\r\n\t}\r\n\r\n\treturn shim.Success(nil)\r\n}", "func NewHelloWorldAction(a application.HelloWorldApp) HelloWorldAction {\n\treturn &helloWorldAction{a: a}\n}", "func NewCleanProposal(cleaner potato.AccountName, proposalName potato.Name, maxCount uint64) *potato.Action {\n\ta := &potato.Action{\n\t\tAccount: ForumAN,\n\t\tName: ActN(\"clnproposal\"),\n\t\tAuthorization: []potato.PermissionLevel{\n\t\t\t{Actor: cleaner, Permission: potato.PermissionName(\"active\")},\n\t\t},\n\t\tActionData: potato.NewActionData(CleanProposal{\n\t\t\tProposalName: proposalName,\n\t\t\tMaxCount: maxCount,\n\t\t}),\n\t}\n\treturn a\n}", "func NewLogAction() Action {\n\treturn &logAction{}\n}" ]
[ "0.734408", "0.724161", "0.60927427", "0.5704581", "0.54267293", "0.5386312", "0.51870364", "0.5036263", "0.50139284", "0.49548915", "0.4951062", "0.49484608", "0.4876492", "0.48602346", "0.4833887", "0.48318735", "0.48297027", "0.47833982", "0.4767467", "0.47623938", "0.4719289", "0.4719289", "0.4697493", "0.46889588", "0.46835467", "0.4650522", "0.46418753", "0.4610552", "0.45990443", "0.4586414", "0.45854706", "0.45840746", "0.4554537", "0.45249128", "0.45164615", "0.44934005", "0.44514048", "0.44480854", "0.44468114", "0.44123504", "0.44041947", "0.43918198", "0.43844375", "0.43844274", "0.43667564", "0.43622604", "0.43574134", "0.4345762", "0.4343362", "0.43261817", "0.43113953", "0.430129", "0.42819157", "0.42723078", "0.4269948", "0.42578772", "0.42309302", "0.4218569", "0.4213352", "0.41987923", "0.41984352", "0.41715", "0.41679296", "0.4166326", "0.41608194", "0.41608194", "0.415489", "0.41412455", "0.4133739", "0.41255498", "0.4124562", "0.4113519", "0.4101679", "0.4100867", "0.4098282", "0.40980357", "0.40954185", "0.40933782", "0.40907773", "0.40756607", "0.40686998", "0.40665975", "0.4052688", "0.40465444", "0.40465444", "0.40409407", "0.403487", "0.40228257", "0.4017329", "0.40139058", "0.40070403", "0.40066713", "0.4003158", "0.39966774", "0.399393", "0.39925623", "0.39839995", "0.39767155", "0.39744112", "0.39734283" ]
0.8150347
0
TakeFromAccount implements the exported.ClawbackAction interface. It returns an error if the account is not at ClawbackVestingAccount or if the funder does not match.
func (ca clawbackAction) TakeFromAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error { cva, ok := rawAccount.(*ClawbackVestingAccount) if !ok { return sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "clawback expects *ClawbackVestingAccount, got %T", rawAccount) } if ca.requestor.String() != cva.FunderAddress { return sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "clawback can only be requested by original funder %s", cva.FunderAddress) } return cva.clawback(ctx, ca.dest, ca.ak, ca.bk, ca.sk) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (va *ClawbackVestingAccount) clawback(ctx sdk.Context, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) error {\n\t// Compute the clawback based on the account state only, and update account\n\ttoClawBack := va.computeClawback(ctx.BlockTime().Unix())\n\tif toClawBack.IsZero() {\n\t\treturn nil\n\t}\n\taddr := va.GetAddress()\n\tbondDenom := sk.BondDenom(ctx)\n\n\t// Compute the clawback based on bank balance and delegation, and update account\n\tencumbered := va.GetVestingCoins(ctx.BlockTime())\n\tbondedAmt := sk.GetDelegatorBonded(ctx, addr)\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, addr)\n\tbonded := sdk.NewCoins(sdk.NewCoin(bondDenom, bondedAmt))\n\tunbonding := sdk.NewCoins(sdk.NewCoin(bondDenom, unbondingAmt))\n\tunbonded := bk.GetAllBalances(ctx, addr)\n\ttoClawBack = va.updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded)\n\n\t// Write now now so that the bank module sees unvested tokens are unlocked.\n\t// Note that all store writes are aborted if there is a panic, so there is\n\t// no danger in writing incomplete results.\n\tak.SetAccount(ctx, va)\n\n\t// Now that future vesting events (and associated lockup) are removed,\n\t// the balance of the account is unlocked and can be freely transferred.\n\tspendable := bk.SpendableCoins(ctx, addr)\n\ttoXfer := coinsMin(toClawBack, spendable)\n\terr := bk.SendCoins(ctx, addr, dest, toXfer)\n\tif err != nil {\n\t\treturn err // shouldn't happen, given spendable check\n\t}\n\ttoClawBack = toClawBack.Sub(toXfer)\n\n\t// We need to traverse the staking data structures to update the\n\t// vesting account bookkeeping, and to recover more funds if necessary.\n\t// Staking is the only way unvested tokens should be missing from the bank balance.\n\n\t// If we need more, transfer UnbondingDelegations.\n\twant := toClawBack.AmountOf(bondDenom)\n\tunbondings := sk.GetUnbondingDelegations(ctx, addr, math.MaxUint16)\n\tfor _, unbonding := range unbondings {\n\t\tvalAddr, err := sdk.ValAddressFromBech32(unbonding.ValidatorAddress)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttransferred := sk.TransferUnbonding(ctx, addr, dest, valAddr, want)\n\t\twant = want.Sub(transferred)\n\t\tif !want.IsPositive() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If we need more, transfer Delegations.\n\tif want.IsPositive() {\n\t\tdelegations := sk.GetDelegatorDelegations(ctx, addr, math.MaxUint16)\n\t\tfor _, delegation := range delegations {\n\t\t\tvalidatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // shouldn't happen\n\t\t\t}\n\t\t\tvalidator, found := sk.GetValidator(ctx, validatorAddr)\n\t\t\tif !found {\n\t\t\t\t// validator has been removed\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twantShares, err := validator.SharesFromTokensTruncated(want)\n\t\t\tif err != nil {\n\t\t\t\t// validator has no tokens\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttransferredShares := sk.TransferDelegation(ctx, addr, dest, delegation.GetValidatorAddr(), wantShares)\n\t\t\t// to be conservative in what we're clawing back, round transferred shares up\n\t\t\ttransferred := validator.TokensFromSharesRoundUp(transferredShares).RoundInt()\n\t\t\twant = want.Sub(transferred)\n\t\t\tif !want.IsPositive() {\n\t\t\t\t// Could be slightly negative, due to rounding?\n\t\t\t\t// Don't think so, due to the precautions above.\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we've transferred everything and still haven't transferred the desired clawback amount,\n\t// then the account must have most some unvested tokens from slashing.\n\treturn nil\n}", "func (cga clawbackGrantAction) AddToAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported,\n\t\t\t\"account %s must be a ClawbackVestingAccount, got %T\",\n\t\t\trawAccount.GetAddress(), rawAccount)\n\t}\n\tif cga.funderAddress != cva.FunderAddress {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"account %s can only accept grants from account %s\",\n\t\t\trawAccount.GetAddress(), cva.FunderAddress)\n\t}\n\tcva.addGrant(ctx, cga.sk, cga.grantStartTime, cga.grantLockupPeriods, cga.grantVestingPeriods, cga.grantCoins)\n\treturn nil\n}", "func NewClawbackVestingAccount(baseAcc *authtypes.BaseAccount, funder sdk.AccAddress, originalVesting sdk.Coins, startTime int64, lockupPeriods, vestingPeriods Periods) *ClawbackVestingAccount {\n\t// copy and align schedules to avoid mutating inputs\n\tlp := make(Periods, len(lockupPeriods))\n\tcopy(lp, lockupPeriods)\n\tvp := make(Periods, len(vestingPeriods))\n\tcopy(vp, vestingPeriods)\n\t_, endTime := AlignSchedules(startTime, startTime, lp, vp)\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ClawbackVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tFunderAddress: funder.String(),\n\t\tStartTime: startTime,\n\t\tLockupPeriods: lp,\n\t\tVestingPeriods: vp,\n\t}\n}", "func (_Token *TokenTransactorSession) BurnFrom(account common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _Token.Contract.BurnFrom(&_Token.TransactOpts, account, amount)\n}", "func (_Token *TokenTransactor) BurnFrom(opts *bind.TransactOpts, account common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _Token.contract.Transact(opts, \"burnFrom\", account, amount)\n}", "func (sc Funcs) TransferAccountToChain(ctx wasmlib.ScFuncClientContext) *TransferAccountToChainCall {\n\tf := &TransferAccountToChainCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncTransferAccountToChain)}\n\tf.Params.Proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView)\n\treturn f\n}", "func (_ERC721Token *ERC721TokenTransactor) TakeOwnership(opts *bind.TransactOpts, _tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ERC721Token.contract.Transact(opts, \"takeOwnership\", _tokenId)\n}", "func (_Token *TokenSession) BurnFrom(account common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _Token.Contract.BurnFrom(&_Token.TransactOpts, account, amount)\n}", "func (k Keeper) delegateFromAccount(ctx sdk.Context, valAddr sdk.ValAddress, delegator sdk.AccAddress, amount sdkmath.Int) (sdk.Dec, error) {\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn sdk.Dec{}, types.ErrNoValidatorFound\n\t}\n\t// source tokens are from an account, so subtractAccount true and tokenSrc unbonded\n\tnewShares, err := k.stakingKeeper.Delegate(ctx, delegator, amount, stakingtypes.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn sdk.Dec{}, err\n\t}\n\treturn newShares, nil\n}", "func (va ClawbackVestingAccount) Validate() error {\n\tif va.GetStartTime() >= va.GetEndTime() {\n\t\treturn errors.New(\"vesting start-time must be before end-time\")\n\t}\n\n\tlockupEnd := va.StartTime\n\tlockupCoins := sdk.NewCoins()\n\tfor _, p := range va.LockupPeriods {\n\t\tlockupEnd += p.Length\n\t\tlockupCoins = lockupCoins.Add(p.Amount...)\n\t}\n\tif lockupEnd > va.EndTime {\n\t\treturn errors.New(\"lockup schedule extends beyond account end time\")\n\t}\n\tif !coinEq(lockupCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in lockup periods\")\n\t}\n\n\tvestingEnd := va.StartTime\n\tvestingCoins := sdk.NewCoins()\n\tfor _, p := range va.VestingPeriods {\n\t\tvestingEnd += p.Length\n\t\tvestingCoins = vestingCoins.Add(p.Amount...)\n\t}\n\tif vestingEnd > va.EndTime {\n\t\treturn errors.New(\"vesting schedule exteds beyond account end time\")\n\t}\n\tif !coinEq(vestingCoins, va.OriginalVesting) {\n\t\treturn errors.New(\"original vesting coins does not match the sum of all coins in vesting periods\")\n\t}\n\n\treturn va.BaseVestingAccount.Validate()\n}", "func (s *Server) Transfer(ctx context.Context, req *pb.TransferRequest) (rep *pb.TransferReply, err error) {\n\trep = &pb.TransferReply{}\n\n\t// Get originator account and confirm it belongs to this RVASP\n\tvar account Account\n\tif err = LookupAccount(s.db, req.Account).First(&account).Error; err != nil {\n\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\tlog.Info().Str(\"account\", req.Account).Msg(\"not found\")\n\t\t\treturn nil, status.Error(codes.NotFound, \"account not found\")\n\t\t}\n\t\tlog.Error().Err(err).Msg(\"could not lookup account\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not lookup account: %s\", err)\n\t}\n\n\t// Identify the beneficiary either using the demo database or the directory service\n\tvar beneficiary Wallet\n\tif req.ExternalDemo {\n\t\tif req.BeneficiaryVasp == \"\" {\n\t\t\treturn nil, status.Error(codes.InvalidArgument, \"if external demo is true, must specify beneficiary vasp\")\n\t\t}\n\n\t\tbeneficiary = Wallet{\n\t\t\tProvider: VASP{\n\t\t\t\tName: req.BeneficiaryVasp,\n\t\t\t},\n\t\t}\n\t} else {\n\t\t// Lookup beneficiary wallet and confirm it belongs to a remote RVASP\n\t\tif err = LookupBeneficiary(s.db, req.Beneficiary).First(&beneficiary).Error; err != nil {\n\t\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\t\tlog.Info().Str(\"beneficiary\", req.Beneficiary).Msg(\"not found\")\n\t\t\t\treturn nil, status.Error(codes.NotFound, \"beneficiary not found (use external_demo?)\")\n\t\t\t}\n\t\t\tlog.Error().Err(err).Msg(\"could not lookup beneficiary\")\n\t\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not lookup beneficiary: %s\", err)\n\t\t}\n\n\t\tif req.CheckBeneficiary {\n\t\t\tif req.BeneficiaryVasp != beneficiary.Provider.Name {\n\t\t\t\tlog.Warn().\n\t\t\t\t\tStr(\"expected\", req.BeneficiaryVasp).\n\t\t\t\t\tStr(\"actual\", beneficiary.Provider.Name).\n\t\t\t\t\tMsg(\"check beneficiary failed\")\n\t\t\t\treturn nil, status.Error(codes.InvalidArgument, \"beneficiary wallet does not match beneficiary VASP\")\n\t\t\t}\n\n\t\t}\n\t}\n\n\t// Conduct a TRISADS lookup if necessary to get the endpoint\n\tvar peer *peers.Peer\n\tif peer, err = s.peers.Search(beneficiary.Provider.Name); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not search peer from directory service\")\n\t\treturn nil, status.Errorf(codes.Internal, \"could not search peer from directory service: %s\", err)\n\t}\n\n\t// Ensure that the local RVASP has signing keys for the remote, otherwise perform key exchange\n\tvar signKey *rsa.PublicKey\n\tif signKey, err = peer.ExchangeKeys(true); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not exchange keys with remote peer\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not exchange keys with remote peer: %s\", err)\n\t}\n\n\t// Save the pending transaction and increment the accounts pending field\n\txfer := Transaction{\n\t\tEnvelope: uuid.New().String(),\n\t\tAccount: account,\n\t\tAmount: decimal.NewFromFloat32(req.Amount),\n\t\tDebit: true,\n\t\tCompleted: false,\n\t}\n\n\tif err = s.db.Save(&xfer).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not save transaction: %s\", err)\n\t}\n\n\t// Save the pending transaction on the account\n\t// TODO: remove pending transactions\n\taccount.Pending++\n\tif err = s.db.Save(&account).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save originator account\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not save originator account: %s\", err)\n\t}\n\n\t// Create an identity and transaction payload for TRISA exchange\n\ttransaction := &generic.Transaction{\n\t\tTxid: fmt.Sprintf(\"%d\", xfer.ID),\n\t\tOriginator: account.WalletAddress,\n\t\tBeneficiary: beneficiary.Address,\n\t\tAmount: float64(req.Amount),\n\t\tNetwork: \"TestNet\",\n\t\tTimestamp: xfer.Timestamp.Format(time.RFC3339),\n\t}\n\tidentity := &ivms101.IdentityPayload{\n\t\tOriginator: &ivms101.Originator{},\n\t\tOriginatingVasp: &ivms101.OriginatingVasp{},\n\t}\n\tif identity.OriginatingVasp.OriginatingVasp, err = s.vasp.LoadIdentity(); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not load originator vasp\")\n\t\treturn nil, status.Errorf(codes.Internal, \"could not load originator vasp: %s\", err)\n\t}\n\n\tidentity.Originator = &ivms101.Originator{\n\t\tOriginatorPersons: make([]*ivms101.Person, 0, 1),\n\t\tAccountNumbers: []string{account.WalletAddress},\n\t}\n\tvar originator *ivms101.Person\n\tif originator, err = account.LoadIdentity(); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not load originator identity\")\n\t\treturn nil, status.Errorf(codes.Internal, \"could not load originator identity: %s\", err)\n\t}\n\tidentity.Originator.OriginatorPersons = append(identity.Originator.OriginatorPersons, originator)\n\n\tpayload := &protocol.Payload{}\n\tif payload.Transaction, err = anypb.New(transaction); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not dump payload transaction\")\n\t\treturn nil, status.Errorf(codes.Internal, \"could not dump payload transaction: %s\", err)\n\t}\n\tif payload.Identity, err = anypb.New(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not dump payload identity\")\n\t\treturn nil, status.Errorf(codes.Internal, \"could not dump payload identity: %s\", err)\n\t}\n\n\t// Secure the envelope with the remote beneficiary's signing keys\n\tvar envelope *protocol.SecureEnvelope\n\tif envelope, err = handler.New(xfer.Envelope, payload, nil).Seal(signKey); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not create or sign secure envelope\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not create or sign secure envelope: %s\", err)\n\t}\n\n\t// Conduct the TRISA transaction, handle errors and send back to user\n\tif envelope, err = peer.Transfer(envelope); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not perform TRISA exchange\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not perform TRISA exchange: %s\", err)\n\t}\n\n\t// Open the response envelope with local private keys\n\tvar opened *handler.Envelope\n\tif opened, err = handler.Open(envelope, s.trisa.sign); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unseal TRISA response\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not unseal TRISA response: %s\", err)\n\t}\n\n\t// Verify the contents of the response\n\tpayload = opened.Payload\n\tif payload.Identity == nil || payload.Transaction == nil {\n\t\tlog.Warn().Msg(\"did not receive identity or transaction\")\n\t\treturn nil, status.Error(codes.FailedPrecondition, \"no identity or transaction returned\")\n\t}\n\n\tif payload.Identity.TypeUrl != \"type.googleapis.com/ivms101.IdentityPayload\" {\n\t\tlog.Warn().Str(\"type\", payload.Identity.TypeUrl).Msg(\"unsupported identity type\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"unsupported identity type for rVASP: %q\", payload.Identity.TypeUrl)\n\t}\n\n\tif payload.Transaction.TypeUrl != \"type.googleapis.com/trisa.data.generic.v1beta1.Transaction\" {\n\t\tlog.Warn().Str(\"type\", payload.Transaction.TypeUrl).Msg(\"unsupported transaction type\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"unsupported identity type for rVASP: %q\", payload.Transaction.TypeUrl)\n\t}\n\n\tidentity = &ivms101.IdentityPayload{}\n\ttransaction = &generic.Transaction{}\n\tif err = payload.Identity.UnmarshalTo(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unmarshal identity\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not unmarshal identity: %s\", err)\n\t}\n\tif err = payload.Transaction.UnmarshalTo(transaction); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unmarshal transaction\")\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"could not unmarshal transaction: %s\", err)\n\t}\n\n\t// Update the completed transaction and save to disk\n\txfer.Beneficiary = Identity{\n\t\tWalletAddress: transaction.Beneficiary,\n\t}\n\txfer.Completed = true\n\txfer.Timestamp, _ = time.Parse(time.RFC3339, transaction.Timestamp)\n\n\t// Serialize the identity information as JSON data\n\tvar data []byte\n\tif data, err = json.Marshal(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not marshal IVMS 101 identity\")\n\t\treturn nil, status.Errorf(codes.Internal, \"could not marshal IVMS 101 identity: %s\", err)\n\t}\n\txfer.Identity = string(data)\n\n\tif err = s.db.Save(&xfer).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn nil, status.Errorf(codes.Internal, \"could not save transaction: %s\", err)\n\t}\n\n\t// Save the pending transaction on the account\n\t// TODO: remove pending transactions\n\taccount.Pending--\n\taccount.Completed++\n\taccount.Balance.Sub(xfer.Amount)\n\tif err = s.db.Save(&account).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save originator account\")\n\t\treturn nil, status.Errorf(codes.Internal, \"could not save originator account: %s\", err)\n\t}\n\n\t// Return the transfer response\n\trep.Transaction = xfer.Proto()\n\treturn rep, nil\n}", "func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\n}", "func (_Registry *RegistryTransactor) SafeTransferAndClaimFrom(opts *bind.TransactOpts, _from common.Address, _to common.Address, _id *big.Int, _value *big.Int, _data []byte, _claimData []byte) (*types.Transaction, error) {\n\treturn _Registry.contract.Transact(opts, \"safeTransferAndClaimFrom\", _from, _to, _id, _value, _data, _claimData)\n}", "func (_ZKOnacci *ZKOnacciTransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ZKOnacci.Contract.SafeTransferFrom(&_ZKOnacci.TransactOpts, from, to, tokenId)\n}", "func Transfertobankaccount(v float64) predicate.Bulk {\n\treturn predicate.Bulk(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldTransfertobankaccount), v))\n\t})\n}", "func (_CraftingI *CraftingITransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _CraftingI.Contract.SafeTransferFrom(&_CraftingI.TransactOpts, from, to, tokenId)\n}", "func transfer_ (stub shim.ChaincodeStubInterface, from_account_name string, to_account_name string, amount int) error {\n if amount < 0 {\n return fmt.Errorf(\"Can't transfer a negative amount (%d)\", amount)\n }\n from_account,err := get_account_(stub, from_account_name)\n if err != nil {\n return fmt.Errorf(\"Error in retrieving \\\"from\\\" account \\\"%s\\\"; %v\", from_account_name, err.Error())\n }\n to_account,err := get_account_(stub, to_account_name)\n if err != nil {\n return fmt.Errorf(\"Error in retrieving \\\"to\\\" account \\\"%s\\\"; %v\", to_account_name, err.Error())\n }\n if from_account.Balance < amount {\n return fmt.Errorf(\"Can't transfer; \\\"from\\\" account balance (%d) is less than transfer amount (%d)\", from_account.Balance, amount)\n }\n\n from_account.Balance -= amount\n to_account.Balance += amount\n\n err = overwrite_account_(stub, from_account)\n if err != nil {\n return fmt.Errorf(\"Could not transfer from account %v; error was %v\", *from_account, err.Error())\n }\n\n err = overwrite_account_(stub, to_account)\n if err != nil {\n return fmt.Errorf(\"Could not transfer to account %v; error was %v\", *to_account, err.Error())\n }\n\n return nil\n}", "func (s *SmartContract) TransferFrom(ctx contractapi.TransactionContextInterface, from string, to string, value int) error {\n\n\t// Get ID of submitting client identity\n\tspender, err := ctx.GetClientIdentity().GetID()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get client id: %v\", err)\n\t}\n\n\t// Create allowanceKey\n\tallowanceKey, err := ctx.GetStub().CreateCompositeKey(allowancePrefix, []string{from, spender})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create the composite key for prefix %s: %v\", allowancePrefix, err)\n\t}\n\n\t// Retrieve the allowance of the spender\n\tcurrentAllowanceBytes, err := ctx.GetStub().GetState(allowanceKey)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to retrieve the allowance for %s from world state: %v\", allowanceKey, err)\n\t}\n\n\tvar currentAllowance int\n\tcurrentAllowance, _ = strconv.Atoi(string(currentAllowanceBytes)) // Error handling not needed since Itoa() was used when setting the totalSupply, guaranteeing it was an integer.\n\n\t// Check if transferred value is less than allowance\n\tif currentAllowance < value {\n\t\treturn fmt.Errorf(\"spender does not have enough allowance for transfer\")\n\t}\n\n\t// Initiate the transfer\n\terr = transferHelper(ctx, from, to, value)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to transfer: %v\", err)\n\t}\n\n\t// Decrease the allowance\n\tupdatedAllowance := currentAllowance - value\n\terr = ctx.GetStub().PutState(allowanceKey, []byte(strconv.Itoa(updatedAllowance)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Emit the Transfer event\n\ttransferEvent := event{from, to, value}\n\ttransferEventJSON, err := json.Marshal(transferEvent)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to obtain JSON encoding: %v\", err)\n\t}\n\terr = ctx.GetStub().SetEvent(\"Transfer\", transferEventJSON)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to set event: %v\", err)\n\t}\n\n\tlog.Printf(\"spender %s allowance updated from %d to %d\", spender, currentAllowance, updatedAllowance)\n\n\treturn nil\n}", "func (_ZKOnacci *ZKOnacciTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ZKOnacci.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId)\n}", "func (_CraftingI *CraftingISession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _CraftingI.Contract.SafeTransferFrom(&_CraftingI.TransactOpts, from, to, tokenId)\n}", "func (va *ClawbackVestingAccount) computeClawback(clawbackTime int64) sdk.Coins {\n\t// Compute the truncated vesting schedule and amounts.\n\t// Work with the schedule as the primary data and recompute derived fields, e.g. OriginalVesting.\n\tvestTime := va.StartTime\n\ttotalVested := sdk.NewCoins()\n\ttotalUnvested := sdk.NewCoins()\n\tunvestedIdx := 0\n\tfor i, period := range va.VestingPeriods {\n\t\tvestTime += period.Length\n\t\t// tie in time goes to clawback\n\t\tif vestTime < clawbackTime {\n\t\t\ttotalVested = totalVested.Add(period.Amount...)\n\t\t\tunvestedIdx = i + 1\n\t\t} else {\n\t\t\ttotalUnvested = totalUnvested.Add(period.Amount...)\n\t\t}\n\t}\n\tlastVestTime := vestTime\n\tnewVestingPeriods := va.VestingPeriods[:unvestedIdx]\n\n\t// To cap the unlocking schedule to the new total vested, conjunct with a limiting schedule\n\tcapPeriods := []Period{\n\t\t{\n\t\t\tLength: 0,\n\t\t\tAmount: totalVested,\n\t\t},\n\t}\n\t_, lastLockTime, newLockupPeriods := ConjunctPeriods(va.StartTime, va.StartTime, va.LockupPeriods, capPeriods)\n\n\t// Now construct the new account state\n\tva.OriginalVesting = totalVested\n\tva.EndTime = max64(lastVestTime, lastLockTime)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\t// DelegatedVesting and DelegatedFree will be adjusted elsewhere\n\n\treturn totalUnvested\n}", "func (_ZKOnacci *ZKOnacciSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ZKOnacci.Contract.SafeTransferFrom(&_ZKOnacci.TransactOpts, from, to, tokenId)\n}", "func (_SweetToken *SweetTokenTransactorSession) TransferFrom(src common.Address, dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.Contract.TransferFrom(&_SweetToken.TransactOpts, src, dst, wad)\n}", "func (_Registry *RegistryTransactorSession) SafeTransferAndClaimFrom(_from common.Address, _to common.Address, _id *big.Int, _value *big.Int, _data []byte, _claimData []byte) (*types.Transaction, error) {\n\treturn _Registry.Contract.SafeTransferAndClaimFrom(&_Registry.TransactOpts, _from, _to, _id, _value, _data, _claimData)\n}", "func (_MainnetCryptoCardsContract *MainnetCryptoCardsContractTransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _MainnetCryptoCardsContract.Contract.SafeTransferFrom(&_MainnetCryptoCardsContract.TransactOpts, from, to, tokenId, _data)\n}", "func (_MainnetCryptoCardsContract *MainnetCryptoCardsContractTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _MainnetCryptoCardsContract.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId, _data)\n}", "func (e *copyS2SMigrationFileEnumerator) addTransferFromAccount(ctx context.Context,\n\tsrcServiceURL azfile.ServiceURL, destBaseURL url.URL,\n\tsharePrefix, fileOrDirectoryPrefix, fileNamePattern string, cca *cookedCopyCmdArgs) error {\n\treturn enumerateSharesInAccount(\n\t\tctx,\n\t\tsrcServiceURL,\n\t\tsharePrefix,\n\t\tfunc(shareItem azfile.ShareItem) error {\n\t\t\t// Whatever the destination type is, it should be equivalent to account level,\n\t\t\t// so directly append share name to it.\n\t\t\ttmpDestURL := urlExtension{URL: destBaseURL}.generateObjectPath(shareItem.Name)\n\t\t\t// create bucket for destination, in case bucket doesn't exist.\n\t\t\tif err := e.createDestBucket(ctx, tmpDestURL, nil); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Two cases for exclude/include which need to match share names in account:\n\t\t\t// a. https://<fileservice>/share*/file*.vhd\n\t\t\t// b. https://<fileservice>/ which equals to https://<fileservice>/*\n\t\t\treturn e.addTransfersFromDirectory(\n\t\t\t\tctx,\n\t\t\t\tsrcServiceURL.NewShareURL(shareItem.Name).NewRootDirectoryURL(),\n\t\t\t\ttmpDestURL,\n\t\t\t\tfileOrDirectoryPrefix,\n\t\t\t\tfileNamePattern,\n\t\t\t\t\"\",\n\t\t\t\ttrue,\n\t\t\t\ttrue,\n\t\t\t\tcca)\n\t\t})\n}", "func (e *copyS2SMigrationBlobEnumerator) addTransferFromAccount(ctx context.Context,\n\tsrcServiceURL azblob.ServiceURL, destBaseURL url.URL,\n\tcontainerPrefix, blobPrefix, blobNamePattern string, cca *cookedCopyCmdArgs) error {\n\treturn enumerateContainersInAccount(\n\t\tctx,\n\t\tsrcServiceURL,\n\t\tcontainerPrefix,\n\t\tfunc(containerItem azblob.ContainerItem) error {\n\t\t\t// Whatever the destination type is, it should be equivalent to account level,\n\t\t\t// so directly append container name to it.\n\t\t\ttmpDestURL := urlExtension{URL: destBaseURL}.generateObjectPath(containerItem.Name)\n\t\t\t// create bucket for destination, in case bucket doesn't exist.\n\t\t\tif err := e.createDestBucket(ctx, tmpDestURL, nil); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Two cases for exclude/include which need to match container names in account:\n\t\t\t// a. https://<blobservice>/container*/blob*.vhd\n\t\t\t// b. https://<blobservice>/ which equals to https://<blobservice>/*\n\t\t\treturn e.addTransfersFromContainer(\n\t\t\t\tctx,\n\t\t\t\tsrcServiceURL.NewContainerURL(containerItem.Name),\n\t\t\t\ttmpDestURL,\n\t\t\t\tblobPrefix,\n\t\t\t\tblobNamePattern,\n\t\t\t\t\"\",\n\t\t\t\ttrue,\n\t\t\t\ttrue,\n\t\t\t\tcca)\n\t\t})\n}", "func (controller *Auth) safeRedilectAccount(sendMe string) {\n\tvar safeAddress string\n\tsafeAddress = controller.getSafeURL(sendMe)\n\tcontroller.Redirect(safeAddress, 302)\n}", "func (oc *contractTransmitter) FromAccount() (ocrtypes.Account, error) {\n\treturn ocrtypes.Account(oc.transmitter.FromAddress().String()), nil\n}", "func (_CraftingI *CraftingITransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _CraftingI.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId)\n}", "func (_Registry *RegistrySession) SafeTransferAndClaimFrom(_from common.Address, _to common.Address, _id *big.Int, _value *big.Int, _data []byte, _claimData []byte) (*types.Transaction, error) {\n\treturn _Registry.Contract.SafeTransferAndClaimFrom(&_Registry.TransactOpts, _from, _to, _id, _value, _data, _claimData)\n}", "func (_MainnetCryptoCardsContract *MainnetCryptoCardsContractSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _MainnetCryptoCardsContract.Contract.SafeTransferFrom(&_MainnetCryptoCardsContract.TransactOpts, from, to, tokenId, _data)\n}", "func (_SweetToken *SweetTokenSession) TransferFrom(src common.Address, dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.Contract.TransferFrom(&_SweetToken.TransactOpts, src, dst, wad)\n}", "func (_SweetToken *SweetTokenTransactor) TransferFrom(opts *bind.TransactOpts, src common.Address, dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.contract.Transact(opts, \"transferFrom\", src, dst, wad)\n}", "func (sc Funcs) TransferAllowanceTo(ctx wasmlib.ScFuncClientContext) *TransferAllowanceToCall {\n\tf := &TransferAllowanceToCall{Func: wasmlib.NewScFunc(ctx, HScName, HFuncTransferAllowanceTo)}\n\tf.Params.Proxy = wasmlib.NewCallParamsProxy(&f.Func.ScView)\n\treturn f\n}", "func (_DetailedTestToken *DetailedTestTokenTransactorSession) Burn(_from common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.Contract.Burn(&_DetailedTestToken.TransactOpts, _from, _amount)\n}", "func (_DetailedTestToken *DetailedTestTokenTransactor) Burn(opts *bind.TransactOpts, _from common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.contract.Transact(opts, \"burn\", _from, _amount)\n}", "func NewClawbackAction(requestor, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) exported.ClawbackAction {\n\treturn clawbackAction{\n\t\trequestor: requestor,\n\t\tdest: dest,\n\t\tak: ak,\n\t\tbk: bk,\n\t\tsk: sk,\n\t}\n}", "func (va ClawbackVestingAccount) GetFunder() sdk.AccAddress {\n\taddr, err := sdk.AccAddressFromBech32(va.FunderAddress)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn addr\n}", "func BankAccount(val string) Argument {\n\treturn func(request *requests.Request) error {\n\t\trequest.AddArgument(\"bank_account\", val)\n\t\treturn nil\n\t}\n}", "func (_DetailedTestToken *DetailedTestTokenSession) Burn(_from common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.Contract.Burn(&_DetailedTestToken.TransactOpts, _from, _amount)\n}", "func (_ElvTradable *ElvTradableTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ElvTradable.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId)\n}", "func (_Wmatic *WmaticTransactorSession) TransferFrom(src common.Address, dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _Wmatic.Contract.TransferFrom(&_Wmatic.TransactOpts, src, dst, wad)\n}", "func (s *StorageInMemory) Transfer(accountFrom, accountTo storage.AccountID, amountToTransfer storage.AccountBalance) error {\n\tbalanceFrom, err := s.getBalance(accountFrom)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbalanceTo, err := s.getBalance(accountTo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbalanceFrom.mu.Lock()\n\tbalanceTo.mu.Lock()\n\tdefer balanceFrom.mu.Unlock()\n\tdefer balanceTo.mu.Unlock()\n\n\tif balanceFrom.amount < amountToTransfer {\n\t\treturn ErrNotEnoughBalance\n\t}\n\t// todo del (для отладки)\n\t// fmt.Println(\"операция: \", balanceFrom.amount, balanceTo.amount, balanceFrom.amount+balanceTo.amount)\n\tbalanceFrom.amount -= amountToTransfer\n\tbalanceTo.amount += amountToTransfer\n\treturn nil\n}", "func Transfer(from, to string, amount int64) error {\n\tif amount <= 0 {\n\t\treturn fmt.Errorf(\"invalid amount; %d\", amount)\n\t}\n\n\tvar accs []*share.Account\n\terr := client.GetByNames(ctx, share.KindAccount, []string{from, to}, &accs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"get accounts error; %v\", err)\n\t}\n\n\tif accs[0].Balance < amount {\n\t\treturn fmt.Errorf(\"balance of account %s is %d, not enough for withdraw %d\", from, accs[0].Balance, amount)\n\t}\n\n\taccs[0].Balance -= amount\n\taccs[1].Balance += amount\n\ttrans := []*share.Transaction{\n\t\t{Type: share.TransactionTypeWithdraw, AccountID: from, Amount: -amount},\n\t\t{Type: share.TransactionTypeDeposit, AccountID: to, Amount: amount},\n\t}\n\tfor _, tran := range trans {\n\t\ttran.NewKey(share.KindTransaction)\n\t}\n\terr = client.SaveModels(ctx, \"\", []interface{}{accs[0], accs[1], trans[0], trans[1]})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"save models error; %v\", err)\n\t}\n\treturn nil\n}", "func Burn(ctx contractapi.TransactionContextInterface, amount int) error {\n\n\t// Check minter authorization - this sample assumes Org1 is the central banker with privilege to burn new tokens\n\tclientMSPID, err := ctx.GetClientIdentity().GetMSPID()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get MSPID: %v\", err)\n\t}\n\tif clientMSPID != \"Org1MSP\" {\n\t\treturn fmt.Errorf(\"client is not authorized to mint new tokens\")\n\t}\n\n\t// Get ID of submitting client identity\n\tburner, err := ctx.GetClientIdentity().GetID()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get client id: %v\", err)\n\t}\n\n\tif amount <= 0 {\n\t\treturn errors.New(\"burn amount must be a positive integer\")\n\t}\n\n\tcurrentBalanceBytes, err := ctx.GetStub().GetState(burner)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read burner account %s from world state: %v\", burner, err)\n\t}\n\n\tvar currentBalance int\n\n\t// Check if burner current balance exists\n\tif currentBalanceBytes == nil {\n\t\treturn errors.New(\"the balance does not exist\")\n\t}\n\n\tcurrentBalance, _ = strconv.Atoi(string(currentBalanceBytes)) // Error handling not needed since Itoa() was used when setting the account balance, guaranteeing it was an integer.\n\n\tupdatedBalance := currentBalance - amount\n\n\terr = ctx.GetStub().PutState(burner, []byte(strconv.Itoa(updatedBalance)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Update the totalSupply\n\ttotalSupplyBytes, err := ctx.GetStub().GetState(totalSupplyKey)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to retrieve total token supply: %v\", err)\n\t}\n\n\t// If no tokens have been burned, throw error\n\tif totalSupplyBytes == nil {\n\t\treturn errors.New(\"totalSupply does not exist\")\n\t}\n\n\ttotalSupply, _ := strconv.Atoi(string(totalSupplyBytes)) // Error handling not needed since Itoa() was used when setting the totalSupply, guaranteeing it was an integer.\n\n\t// Subtract the burn amount to the total supply and update the state\n\ttotalSupply -= amount\n\terr = ctx.GetStub().PutState(totalSupplyKey, []byte(strconv.Itoa(totalSupply)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Emit the Transfer event\n\ttransferEvent := event{burner, \"0x0\", amount}\n\ttransferEventJSON, err := json.Marshal(transferEvent)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to obtain JSON encoding: %v\", err)\n\t}\n\terr = ctx.GetStub().SetEvent(\"Transfer\", transferEventJSON)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to set event: %v\", err)\n\t}\n\n\tlog.Printf(\"burner account %s balance updated from %d to %d\", burner, currentBalance, updatedBalance)\n\n\treturn nil\n}", "func (_ERC721Token *ERC721TokenTransactorSession) TakeOwnership(_tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ERC721Token.Contract.TakeOwnership(&_ERC721Token.TransactOpts, _tokenId)\n}", "func (_Cakevault *CakevaultSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) {\n\treturn _Cakevault.Contract.TransferOwnership(&_Cakevault.TransactOpts, newOwner)\n}", "func (_Harberger *HarbergerTransactor) TransferToVault(opts *bind.TransactOpts, _token common.Address) (*types.Transaction, error) {\n\treturn _Harberger.contract.Transact(opts, \"transferToVault\", _token)\n}", "func (trd *trxDispatcher) pushAccount(at string, adr *common.Address, blk *types.Block, trx *types.Transaction, wg *sync.WaitGroup) bool {\n\twg.Add(1)\n\tselect {\n\tcase trd.outAccount <- &eventAcc{\n\t\twatchDog: wg,\n\t\taddr: adr,\n\t\tact: at,\n\t\tblk: blk,\n\t\ttrx: trx,\n\t\tdeploy: nil,\n\t}:\n\tcase <-trd.sigStop:\n\t\treturn false\n\t}\n\treturn true\n}", "func (_IERC721 *IERC721TransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _IERC721.Contract.SafeTransferFrom(&_IERC721.TransactOpts, from, to, tokenId)\n}", "func (_IERC721 *IERC721TransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _IERC721.Contract.SafeTransferFrom(&_IERC721.TransactOpts, from, to, tokenId)\n}", "func (_StakingToken *StakingTokenTransactorSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _StakingToken.Contract.TransferFrom(&_StakingToken.TransactOpts, sender, recipient, amount)\n}", "func (_DetailedTestToken *DetailedTestTokenTransactorSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.Contract.TransferFrom(&_DetailedTestToken.TransactOpts, sender, recipient, amount)\n}", "func (_ERC721Token *ERC721TokenSession) TakeOwnership(_tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ERC721Token.Contract.TakeOwnership(&_ERC721Token.TransactOpts, _tokenId)\n}", "func (_Cakevault *CakevaultTransactorSession) TransferOwnership(newOwner common.Address) (*types.Transaction, error) {\n\treturn _Cakevault.Contract.TransferOwnership(&_Cakevault.TransactOpts, newOwner)\n}", "func (_CrToken *CrTokenTransactorSession) TransferFrom(src common.Address, dst common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.Contract.TransferFrom(&_CrToken.TransactOpts, src, dst, amount)\n}", "func (_ERC721 *ERC721TransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ERC721.Contract.SafeTransferFrom(&_ERC721.TransactOpts, from, to, tokenId)\n}", "func (_Harberger *HarbergerTransactorSession) TransferToVault(_token common.Address) (*types.Transaction, error) {\n\treturn _Harberger.Contract.TransferToVault(&_Harberger.TransactOpts, _token)\n}", "func (_Cakevault *CakevaultTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) {\n\treturn _Cakevault.contract.Transact(opts, \"transferOwnership\", newOwner)\n}", "func (_Contract *ContractTransactorSession) SafeTransferFrom(_from common.Address, _to common.Address, _tokenId *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _Contract.Contract.SafeTransferFrom(&_Contract.TransactOpts, _from, _to, _tokenId, _data)\n}", "func (_ElvTradableLocal *ElvTradableLocalTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ElvTradableLocal.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId)\n}", "func (_Wmatic *WmaticSession) TransferFrom(src common.Address, dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _Wmatic.Contract.TransferFrom(&_Wmatic.TransactOpts, src, dst, wad)\n}", "func (_MainnetCryptoCardsContract *MainnetCryptoCardsContractTransactorSession) TransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _MainnetCryptoCardsContract.Contract.TransferFrom(&_MainnetCryptoCardsContract.TransactOpts, from, to, tokenId)\n}", "func (_ProjectWalletAuthoriser *ProjectWalletAuthoriserTransactor) TransferOwnership(opts *bind.TransactOpts, _newOwner common.Address) (*types.Transaction, error) {\n\treturn _ProjectWalletAuthoriser.contract.Transact(opts, \"transferOwnership\", _newOwner)\n}", "func (_FixedSupplyToken *FixedSupplyTokenTransactor) TransferOwnership(opts *bind.TransactOpts, _newOwner common.Address) (*types.Transaction, error) {\n\treturn _FixedSupplyToken.contract.Transact(opts, \"transferOwnership\", _newOwner)\n}", "func (_DetailedTestToken *DetailedTestTokenTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) {\n\treturn _DetailedTestToken.contract.Transact(opts, \"transferOwnership\", newOwner)\n}", "func transfer(w http.ResponseWriter, r *http.Request) {\n\tpayload, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\twriteErrorResponse(w, http.StatusBadRequest, \"failed to read request body: %s\", err)\n\t\treturn\n\t}\n\n\tvar transfer api.Transfer\n\tif err := json.Unmarshal(payload, &transfer); err != nil {\n\t\twriteErrorResponse(w, http.StatusBadRequest, \"failed to parse payload json: %s\", err)\n\t\treturn\n\t}\n\n\targs := []string{\n\t\t\"set_owner\",\n\t\ttransfer.MarbleId,\n\t\ttransfer.ToOwnerId,\n\t}\n\n\tdata, err := fc.InvokeCC(ConsortiumChannelID, MarblesCC, args, nil)\n\tif err != nil {\n\t\twriteErrorResponse(w, http.StatusInternalServerError, \"cc invoke failed: %s: %v\", err, args)\n\t\treturn\n\t}\n\tresponse := api.Response{\n\t\tId: transfer.MarbleId,\n\t\tTxId: data.FabricTxnID,\n\t}\n\twriteJSONResponse(w, http.StatusOK, response)\n}", "func (_IERC721Metadata *IERC721MetadataTransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _IERC721Metadata.Contract.SafeTransferFrom(&_IERC721Metadata.TransactOpts, from, to, tokenId)\n}", "func (_DetailedTestToken *DetailedTestTokenSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.Contract.TransferFrom(&_DetailedTestToken.TransactOpts, sender, recipient, amount)\n}", "func (_CraftingI *CraftingITransactorSession) TransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _CraftingI.Contract.TransferFrom(&_CraftingI.TransactOpts, from, to, tokenId)\n}", "func (_Harberger *HarbergerSession) TransferToVault(_token common.Address) (*types.Transaction, error) {\n\treturn _Harberger.Contract.TransferToVault(&_Harberger.TransactOpts, _token)\n}", "func (_MainnetCryptoCardsContract *MainnetCryptoCardsContractTransactor) TransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _MainnetCryptoCardsContract.contract.Transact(opts, \"transferFrom\", from, to, tokenId)\n}", "func (_FixedSupplyToken *FixedSupplyTokenTransactorSession) TransferFrom(from common.Address, to common.Address, tokens *big.Int) (*types.Transaction, error) {\n\treturn _FixedSupplyToken.Contract.TransferFrom(&_FixedSupplyToken.TransactOpts, from, to, tokens)\n}", "func (_ERC721Enumerable *ERC721EnumerableTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ERC721Enumerable.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId)\n}", "func (_SimpleReadAccessController *SimpleReadAccessControllerTransactor) TransferOwnership(opts *bind.TransactOpts, _to common.Address) (*types.Transaction, error) {\n\treturn _SimpleReadAccessController.contract.Transact(opts, \"transferOwnership\", _to)\n}", "func (_WELV9 *WELV9Transactor) TransferFrom(opts *bind.TransactOpts, src common.Address, dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _WELV9.contract.Transact(opts, \"transferFrom\", src, dst, wad)\n}", "func (_StakingToken *StakingTokenSession) TransferFrom(sender common.Address, recipient common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _StakingToken.Contract.TransferFrom(&_StakingToken.TransactOpts, sender, recipient, amount)\n}", "func (_ERC721 *ERC721TransactorSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _ERC721.Contract.SafeTransferFrom(&_ERC721.TransactOpts, from, to, tokenId, _data)\n}", "func (_BurnableToken *BurnableTokenTransactorSession) TransferFrom(_from common.Address, _to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BurnableToken.Contract.TransferFrom(&_BurnableToken.TransactOpts, _from, _to, _value)\n}", "func (_Contract *ContractSession) SafeTransferFrom(_from common.Address, _to common.Address, _tokenId *big.Int, _data []byte) (*types.Transaction, error) {\n\treturn _Contract.Contract.SafeTransferFrom(&_Contract.TransactOpts, _from, _to, _tokenId, _data)\n}", "func (_IERC721 *IERC721Session) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _IERC721.Contract.SafeTransferFrom(&_IERC721.TransactOpts, from, to, tokenId)\n}", "func (_IERC721 *IERC721Session) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _IERC721.Contract.SafeTransferFrom(&_IERC721.TransactOpts, from, to, tokenId)\n}", "func Withdraw(card types.Card, amount types.Money) types.Card {\n \n if (card.Active) && (card.Balance >= amount) && (amount > 0) && (amount <= 2_000_000) {\n\t\tcard.Balance = card.Balance - amount \n }\n\n return card\n}", "func FundAccount(address string) error {\n\tresp, err := http.Get(\"https://friendbot.zion.info/?addr=\" + address)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"requesting friendbot lumens\")\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"reading response from bad friendbot request %d\", resp.StatusCode)\n\t\t}\n\t\treturn fmt.Errorf(\"error funding address through friendbot. got bad status code %d, response %s\", resp.StatusCode, body)\n\t}\n\treturn nil\n}", "func (_BaseAccessWalletFactory *BaseAccessWalletFactoryTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) {\n\treturn _BaseAccessWalletFactory.contract.Transact(opts, \"transferOwnership\", newOwner)\n}", "func (_IERC721Metadata *IERC721MetadataSession) SafeTransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _IERC721Metadata.Contract.SafeTransferFrom(&_IERC721Metadata.TransactOpts, from, to, tokenId)\n}", "func (theAccount *Account) Withdraw(amount int) error {\n\tif theAccount.balance < amount {\n\t\treturn errNoMoney\n\t}\n\ttheAccount.balance -= amount\n\treturn nil\n}", "func (ga *GenesisAccount) ToAccount() auth.Account {\n\tbacc := &auth.BaseAccount{\n\t\tAddress: ga.Address,\n\t\tCoins: ga.Coins.Sort(),\n\t\tAccountNumber: ga.AccountNumber,\n\t\tSequence: ga.Sequence,\n\t}\n\n\tif !ga.OriginalVesting.IsZero() {\n\t\tbaseVestingAcc := &auth.BaseVestingAccount{\n\t\t\tBaseAccount: bacc,\n\t\t\tOriginalVesting: ga.OriginalVesting,\n\t\t\tDelegatedFree: ga.DelegatedFree,\n\t\t\tDelegatedVesting: ga.DelegatedVesting,\n\t\t\tEndTime: ga.EndTime,\n\t\t}\n\n\t\tif ga.StartTime != 0 && ga.EndTime != 0 {\n\t\t\treturn &auth.ContinuousVestingAccount{\n\t\t\t\tBaseVestingAccount: baseVestingAcc,\n\t\t\t\tStartTime: ga.StartTime,\n\t\t\t}\n\t\t} else if ga.EndTime != 0 {\n\t\t\treturn &auth.DelayedVestingAccount{\n\t\t\t\tBaseVestingAccount: baseVestingAcc,\n\t\t\t}\n\t\t} else {\n\t\t\tpanic(fmt.Sprintf(\"invalid genesis vesting account: %+v\", ga))\n\t\t}\n\t}\n\n\treturn bacc\n}", "func (_FeeCurrencyWhitelist *FeeCurrencyWhitelistTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) {\n\treturn _FeeCurrencyWhitelist.contract.Transact(opts, \"transferOwnership\", newOwner)\n}", "func (_SimpleSavingsWallet *SimpleSavingsWalletTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) {\n\treturn _SimpleSavingsWallet.contract.Transact(opts, \"transferOwnership\", newOwner)\n}", "func (o *Filesystem) TakeOwnership(ctx context.Context, options map[string]dbus.Variant) (err error) {\n\terr = o.object.CallWithContext(ctx, InterfaceFilesystem+\".TakeOwnership\", 0, options).Store()\n\treturn\n}", "func (_StaticCallProxy *StaticCallProxyCallerSession) TransferFrom(assetData []byte, from common.Address, to common.Address, amount *big.Int) error {\n\treturn _StaticCallProxy.Contract.TransferFrom(&_StaticCallProxy.CallOpts, assetData, from, to, amount)\n}", "func (_ERC721 *ERC721Transactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ERC721.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId)\n}", "func (_ERC721 *ERC721Transactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ERC721.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId)\n}", "func (_MainnetCryptoCardsContract *MainnetCryptoCardsContractSession) TransferFrom(from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _MainnetCryptoCardsContract.Contract.TransferFrom(&_MainnetCryptoCardsContract.TransactOpts, from, to, tokenId)\n}", "func (_BurnableToken *BurnableTokenTransactor) TransferOwnership(opts *bind.TransactOpts, newOwner common.Address) (*types.Transaction, error) {\n\treturn _BurnableToken.contract.Transact(opts, \"transferOwnership\", newOwner)\n}", "func (account *Account) Withdraw(amount int) error {\r\n\tif account.balance < amount {\r\n\t\t// return errors.New(\"Can't widthdraw amount is more than yout balance\")\r\n\t\treturn errNoMoney\r\n\t}\r\n\taccount.balance -= amount\r\n\treturn nil\r\n\t// nill is null or None\r\n\r\n}", "func (_IERC721Enumerable *IERC721EnumerableTransactor) SafeTransferFrom(opts *bind.TransactOpts, from common.Address, to common.Address, tokenId *big.Int) (*types.Transaction, error) {\n\treturn _IERC721Enumerable.contract.Transact(opts, \"safeTransferFrom\", from, to, tokenId)\n}" ]
[ "0.6373067", "0.61946815", "0.52225226", "0.5115219", "0.5063567", "0.50280553", "0.50247216", "0.5002626", "0.49813092", "0.49658814", "0.4900447", "0.48946452", "0.48875058", "0.48761022", "0.48605388", "0.48496777", "0.48311484", "0.48254326", "0.48169035", "0.48071176", "0.48055145", "0.47890434", "0.4785375", "0.4783107", "0.4761969", "0.47608122", "0.4742863", "0.47302884", "0.47296655", "0.4724775", "0.4707527", "0.47068688", "0.46969882", "0.46838152", "0.46719366", "0.4662192", "0.46529555", "0.4639384", "0.46223053", "0.4611176", "0.46052802", "0.45961925", "0.45717075", "0.45622805", "0.45550978", "0.4554389", "0.45536426", "0.4552938", "0.45240572", "0.45093474", "0.45085338", "0.4489931", "0.4489931", "0.4487042", "0.44748864", "0.44681934", "0.4463701", "0.44635332", "0.44627368", "0.44619653", "0.44586185", "0.4453211", "0.44306096", "0.4424686", "0.4418643", "0.44108614", "0.44090188", "0.44063455", "0.4405336", "0.44042626", "0.4403091", "0.44001493", "0.4399725", "0.4396146", "0.4393432", "0.4382249", "0.43819675", "0.43806216", "0.4373875", "0.4370931", "0.4370198", "0.43660256", "0.43658015", "0.43658015", "0.4357969", "0.43576732", "0.43557364", "0.43541232", "0.43538067", "0.43534416", "0.4353307", "0.4350261", "0.4349803", "0.434891", "0.43478632", "0.43478632", "0.43455395", "0.4344903", "0.43447274", "0.4344153" ]
0.8336627
0
Clawback transfers unvested tokens in a ClawbackVestingAccount to dest. Future vesting events are removed. Unstaked tokens are simply sent. Unbonding and staked tokens are transferred with their staking state intact. Account state is updated to reflect the removals.
func (va *ClawbackVestingAccount) clawback(ctx sdk.Context, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) error { // Compute the clawback based on the account state only, and update account toClawBack := va.computeClawback(ctx.BlockTime().Unix()) if toClawBack.IsZero() { return nil } addr := va.GetAddress() bondDenom := sk.BondDenom(ctx) // Compute the clawback based on bank balance and delegation, and update account encumbered := va.GetVestingCoins(ctx.BlockTime()) bondedAmt := sk.GetDelegatorBonded(ctx, addr) unbondingAmt := sk.GetDelegatorUnbonding(ctx, addr) bonded := sdk.NewCoins(sdk.NewCoin(bondDenom, bondedAmt)) unbonding := sdk.NewCoins(sdk.NewCoin(bondDenom, unbondingAmt)) unbonded := bk.GetAllBalances(ctx, addr) toClawBack = va.updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded) // Write now now so that the bank module sees unvested tokens are unlocked. // Note that all store writes are aborted if there is a panic, so there is // no danger in writing incomplete results. ak.SetAccount(ctx, va) // Now that future vesting events (and associated lockup) are removed, // the balance of the account is unlocked and can be freely transferred. spendable := bk.SpendableCoins(ctx, addr) toXfer := coinsMin(toClawBack, spendable) err := bk.SendCoins(ctx, addr, dest, toXfer) if err != nil { return err // shouldn't happen, given spendable check } toClawBack = toClawBack.Sub(toXfer) // We need to traverse the staking data structures to update the // vesting account bookkeeping, and to recover more funds if necessary. // Staking is the only way unvested tokens should be missing from the bank balance. // If we need more, transfer UnbondingDelegations. want := toClawBack.AmountOf(bondDenom) unbondings := sk.GetUnbondingDelegations(ctx, addr, math.MaxUint16) for _, unbonding := range unbondings { valAddr, err := sdk.ValAddressFromBech32(unbonding.ValidatorAddress) if err != nil { panic(err) } transferred := sk.TransferUnbonding(ctx, addr, dest, valAddr, want) want = want.Sub(transferred) if !want.IsPositive() { break } } // If we need more, transfer Delegations. if want.IsPositive() { delegations := sk.GetDelegatorDelegations(ctx, addr, math.MaxUint16) for _, delegation := range delegations { validatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) if err != nil { panic(err) // shouldn't happen } validator, found := sk.GetValidator(ctx, validatorAddr) if !found { // validator has been removed continue } wantShares, err := validator.SharesFromTokensTruncated(want) if err != nil { // validator has no tokens continue } transferredShares := sk.TransferDelegation(ctx, addr, dest, delegation.GetValidatorAddr(), wantShares) // to be conservative in what we're clawing back, round transferred shares up transferred := validator.TokensFromSharesRoundUp(transferredShares).RoundInt() want = want.Sub(transferred) if !want.IsPositive() { // Could be slightly negative, due to rounding? // Don't think so, due to the precautions above. break } } } // If we've transferred everything and still haven't transferred the desired clawback amount, // then the account must have most some unvested tokens from slashing. return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_SweetToken *SweetTokenTransactor) Transfer(opts *bind.TransactOpts, dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.contract.Transact(opts, \"transfer\", dst, wad)\n}", "func (_SweetToken *SweetTokenSession) Transfer(dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.Contract.Transfer(&_SweetToken.TransactOpts, dst, wad)\n}", "func (_SweetToken *SweetTokenTransactorSession) Transfer(dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.Contract.Transfer(&_SweetToken.TransactOpts, dst, wad)\n}", "func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\n}", "func (_CrToken *CrTokenSession) Transfer(dst common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.Contract.Transfer(&_CrToken.TransactOpts, dst, amount)\n}", "func (_CrToken *CrTokenTransactorSession) Transfer(dst common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.Contract.Transfer(&_CrToken.TransactOpts, dst, amount)\n}", "func (_CrToken *CrTokenTransactor) Transfer(opts *bind.TransactOpts, dst common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _CrToken.contract.Transact(opts, \"transfer\", dst, amount)\n}", "func (_TokenVesting *TokenVestingRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _TokenVesting.Contract.TokenVestingTransactor.contract.Transfer(opts)\n}", "func (_StakingToken *StakingTokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _StakingToken.Contract.contract.Transfer(opts)\n}", "func (_StakingToken *StakingTokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _StakingToken.Contract.StakingTokenTransactor.contract.Transfer(opts)\n}", "func (_ElvToken *ElvTokenTransactor) Transfer(opts *bind.TransactOpts, to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _ElvToken.contract.Transact(opts, \"transfer\", to, value)\n}", "func (_TokenVesting *TokenVestingTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _TokenVesting.Contract.contract.Transfer(opts)\n}", "func (_CrToken *CrTokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _CrToken.Contract.CrTokenTransactor.contract.Transfer(opts)\n}", "func (_SweetToken *SweetTokenTransactorSession) TransferFrom(src common.Address, dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.Contract.TransferFrom(&_SweetToken.TransactOpts, src, dst, wad)\n}", "func (_BurnableToken *BurnableTokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BurnableToken.Contract.BurnableTokenTransactor.contract.Transfer(opts)\n}", "func (_BurnableToken *BurnableTokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BurnableToken.Contract.BurnableTokenTransactor.contract.Transfer(opts)\n}", "func (_StakingToken *StakingTokenTransactor) Transfer(opts *bind.TransactOpts, recipient common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _StakingToken.contract.Transact(opts, \"transfer\", recipient, amount)\n}", "func (_SweetToken *SweetTokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SweetToken.Contract.SweetTokenTransactor.contract.Transfer(opts)\n}", "func (_DetailedTestToken *DetailedTestTokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DetailedTestToken.Contract.DetailedTestTokenTransactor.contract.Transfer(opts)\n}", "func (_SweetToken *SweetTokenSession) TransferFrom(src common.Address, dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.Contract.TransferFrom(&_SweetToken.TransactOpts, src, dst, wad)\n}", "func (_BurnableToken *BurnableTokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BurnableToken.Contract.contract.Transfer(opts)\n}", "func (_BurnableToken *BurnableTokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BurnableToken.Contract.contract.Transfer(opts)\n}", "func (_Token *TokenTransactor) Transfer(opts *bind.TransactOpts, to common.Address, value *big.Int, data []byte) (*types.Transaction, error) {\n\treturn _Token.contract.Transact(opts, \"transfer\", to, value, data)\n}", "func (_CrToken *CrTokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _CrToken.Contract.contract.Transfer(opts)\n}", "func (_Token *TokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _Token.contract.Transact(opts, \"transfer\", _to, _value)\n}", "func (_DetailedTestToken *DetailedTestTokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _DetailedTestToken.Contract.contract.Transfer(opts)\n}", "func (_SweetToken *SweetTokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _SweetToken.Contract.contract.Transfer(opts)\n}", "func (_BurnableToken *BurnableTokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BurnableToken.contract.Transact(opts, \"transfer\", _to, _value)\n}", "func (_BurnableToken *BurnableTokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BurnableToken.contract.Transact(opts, \"transfer\", _to, _value)\n}", "func (ca clawbackAction) TakeFromAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported, \"clawback expects *ClawbackVestingAccount, got %T\", rawAccount)\n\t}\n\tif ca.requestor.String() != cva.FunderAddress {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"clawback can only be requested by original funder %s\", cva.FunderAddress)\n\t}\n\treturn cva.clawback(ctx, ca.dest, ca.ak, ca.bk, ca.sk)\n}", "func (_StandardToken *StandardTokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _StandardToken.contract.Transact(opts, \"transfer\", _to, _value)\n}", "func (_StandardToken *StandardTokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _StandardToken.contract.Transact(opts, \"transfer\", _to, _value)\n}", "func (_ERC721Token *ERC721TokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ERC721Token.contract.Transact(opts, \"transfer\", _to, _tokenId)\n}", "func (_FCToken *FCTokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _FCToken.Contract.FCTokenTransactor.contract.Transfer(opts)\n}", "func (_ERC721Token *ERC721TokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _ERC721Token.Contract.ERC721TokenTransactor.contract.Transfer(opts)\n}", "func (_BREMToken *BREMTokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BREMToken.contract.Transact(opts, \"transfer\", _to, _value)\n}", "func (_BasicToken *BasicTokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BasicToken.contract.Transact(opts, \"transfer\", _to, _value)\n}", "func (_BasicToken *BasicTokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BasicToken.contract.Transact(opts, \"transfer\", _to, _value)\n}", "func (_Token *TokenTransactor) Transfer(opts *bind.TransactOpts, recipient common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _Token.contract.Transact(opts, \"transfer\", recipient, amount)\n}", "func (_FixedSupplyToken *FixedSupplyTokenTransactor) Transfer(opts *bind.TransactOpts, to common.Address, tokens *big.Int) (*types.Transaction, error) {\n\treturn _FixedSupplyToken.contract.Transact(opts, \"transfer\", to, tokens)\n}", "func (_DetailedTestToken *DetailedTestTokenTransactor) Transfer(opts *bind.TransactOpts, recipient common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.contract.Transact(opts, \"transfer\", recipient, amount)\n}", "func (_ERC20Interface *ERC20InterfaceSession) Transfer(to common.Address, tokens *big.Int) (*types.Transaction, error) {\n\treturn _ERC20Interface.Contract.Transfer(&_ERC20Interface.TransactOpts, to, tokens)\n}", "func (_PausableToken *PausableTokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _PausableToken.contract.Transact(opts, \"transfer\", _to, _value)\n}", "func (_FixedSupplyToken *FixedSupplyTokenSession) Transfer(to common.Address, tokens *big.Int) (*types.Transaction, error) {\n\treturn _FixedSupplyToken.Contract.Transfer(&_FixedSupplyToken.TransactOpts, to, tokens)\n}", "func (token *Token) Transfer(caller crypto.Address, addr crypto.Address, amount uint64, memo uint64) ([]*crypto.Event, error) {\n\targs := []string{\n\t\taddr.String(),\n\t\tstrconv.FormatUint(amount, 10),\n\t\tstrconv.FormatUint(memo, 10),\n\t}\n\t_, events, err := token.invokeContract(caller, \"transfer\", args)\n\treturn events, err\n}", "func (_FixedSupplyToken *FixedSupplyTokenTransactorSession) Transfer(to common.Address, tokens *big.Int) (*types.Transaction, error) {\n\treturn _FixedSupplyToken.Contract.Transfer(&_FixedSupplyToken.TransactOpts, to, tokens)\n}", "func (_Token *TokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Token.Contract.contract.Transfer(opts)\n}", "func (_Token *TokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Token.Contract.contract.Transfer(opts)\n}", "func (_Token *TokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Token.Contract.contract.Transfer(opts)\n}", "func (_Token *TokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Token.Contract.contract.Transfer(opts)\n}", "func (_Token *TokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Token.Contract.contract.Transfer(opts)\n}", "func (_MintableToken *MintableTokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _MintableToken.contract.Transact(opts, \"transfer\", _to, _value)\n}", "func (_SweetToken *SweetTokenTransactor) TransferFrom(opts *bind.TransactOpts, src common.Address, dst common.Address, wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.contract.Transact(opts, \"transferFrom\", src, dst, wad)\n}", "func (_FCToken *FCTokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _FCToken.contract.Transact(opts, \"transfer\", _to, _value)\n}", "func (_FCToken *FCTokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _FCToken.Contract.contract.Transfer(opts)\n}", "func (_Token *TokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Token.Contract.TokenTransactor.contract.Transfer(opts)\n}", "func (_Token *TokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Token.Contract.TokenTransactor.contract.Transfer(opts)\n}", "func (_Token *TokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Token.Contract.TokenTransactor.contract.Transfer(opts)\n}", "func (_Token *TokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Token.Contract.TokenTransactor.contract.Transfer(opts)\n}", "func (_Token *TokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Token.Contract.TokenTransactor.contract.Transfer(opts)\n}", "func (_MintableToken *MintableTokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _MintableToken.Contract.contract.Transfer(opts)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _TokenStakingEscrow.Contract.TokenStakingEscrowTransactor.contract.Transfer(opts)\n}", "func (_ERC20Interface *ERC20InterfaceTransactorSession) Transfer(to common.Address, tokens *big.Int) (*types.Transaction, error) {\n\treturn _ERC20Interface.Contract.Transfer(&_ERC20Interface.TransactOpts, to, tokens)\n}", "func (_StakingToken *StakingTokenSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _StakingToken.Contract.Transfer(&_StakingToken.TransactOpts, recipient, amount)\n}", "func (_Token *TokenTransactorSession) Transfer(to common.Address, value *big.Int, data []byte) (*types.Transaction, error) {\n\treturn _Token.Contract.Transfer(&_Token.TransactOpts, to, value, data)\n}", "func (_MintableToken *MintableTokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _MintableToken.Contract.MintableTokenTransactor.contract.Transfer(opts)\n}", "func (_PausableToken *PausableTokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _PausableToken.Contract.contract.Transfer(opts)\n}", "func (_BREMToken *BREMTokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BREMToken.Contract.contract.Transfer(opts)\n}", "func (_Token *TokenSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _Token.Contract.Transfer(&_Token.TransactOpts, recipient, amount)\n}", "func (_BREMToken *BREMTokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BREMToken.Contract.BREMTokenTransactor.contract.Transfer(opts)\n}", "func (_Token *TokenSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _Token.Contract.Transfer(&_Token.TransactOpts, _to, _value)\n}", "func (_Token *TokenSession) Transfer(to common.Address, value *big.Int, data []byte) (*types.Transaction, error) {\n\treturn _Token.Contract.Transfer(&_Token.TransactOpts, to, value, data)\n}", "func (_BurnableToken *BurnableTokenSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BurnableToken.Contract.Transfer(&_BurnableToken.TransactOpts, _to, _value)\n}", "func (_BurnableToken *BurnableTokenSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BurnableToken.Contract.Transfer(&_BurnableToken.TransactOpts, _to, _value)\n}", "func (_ERC721Token *ERC721TokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _ERC721Token.Contract.contract.Transfer(opts)\n}", "func (_StakingToken *StakingTokenTransactorSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _StakingToken.Contract.Transfer(&_StakingToken.TransactOpts, recipient, amount)\n}", "func (_Token *TokenTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _Token.Contract.Transfer(&_Token.TransactOpts, _to, _value)\n}", "func (_DetailedTestToken *DetailedTestTokenSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.Contract.Transfer(&_DetailedTestToken.TransactOpts, recipient, amount)\n}", "func (_PausableToken *PausableTokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _PausableToken.Contract.PausableTokenTransactor.contract.Transfer(opts)\n}", "func (_TokenStakingEscrow *TokenStakingEscrowTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _TokenStakingEscrow.Contract.contract.Transfer(opts)\n}", "func (_UpkeepRegistrationRequests *UpkeepRegistrationRequestsTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _UpkeepRegistrationRequests.Contract.contract.Transfer(opts)\n}", "func (_LifToken *LifTokenTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _LifToken.contract.Transact(opts, \"transfer\", _to, _value)\n}", "func (_StandardToken *StandardTokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _StandardToken.Contract.contract.Transfer(opts)\n}", "func (_StandardToken *StandardTokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _StandardToken.Contract.contract.Transfer(opts)\n}", "func (_BasicToken *BasicTokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BasicToken.Contract.contract.Transfer(opts)\n}", "func (_BasicToken *BasicTokenTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BasicToken.Contract.contract.Transfer(opts)\n}", "func (_MonsterOwnership *MonsterOwnershipTransactor) Transfer(opts *bind.TransactOpts, _to common.Address, _tokenId *big.Int) (*types.Transaction, error) {\n\treturn _MonsterOwnership.contract.Transact(opts, \"transfer\", _to, _tokenId)\n}", "func (_StandardToken *StandardTokenTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _StandardToken.Contract.Transfer(&_StandardToken.TransactOpts, _to, _value)\n}", "func (_StandardToken *StandardTokenTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _StandardToken.Contract.Transfer(&_StandardToken.TransactOpts, _to, _value)\n}", "func (_BasicToken *BasicTokenTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BasicToken.Contract.Transfer(&_BasicToken.TransactOpts, _to, _value)\n}", "func (_BasicToken *BasicTokenTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BasicToken.Contract.Transfer(&_BasicToken.TransactOpts, _to, _value)\n}", "func (_Token *TokenTransactorSession) Transfer(recipient common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _Token.Contract.Transfer(&_Token.TransactOpts, recipient, amount)\n}", "func (_UpkeepRegistrationRequests *UpkeepRegistrationRequestsRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _UpkeepRegistrationRequests.Contract.UpkeepRegistrationRequestsTransactor.contract.Transfer(opts)\n}", "func (_BurnableToken *BurnableTokenTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BurnableToken.Contract.Transfer(&_BurnableToken.TransactOpts, _to, _value)\n}", "func (_BurnableToken *BurnableTokenTransactorSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BurnableToken.Contract.Transfer(&_BurnableToken.TransactOpts, _to, _value)\n}", "func (_BasicToken *BasicTokenSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BasicToken.Contract.Transfer(&_BasicToken.TransactOpts, _to, _value)\n}", "func (_BasicToken *BasicTokenSession) Transfer(_to common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BasicToken.Contract.Transfer(&_BasicToken.TransactOpts, _to, _value)\n}", "func transferAllToAddress(v *visor.Visor, gb visor.SignedBlock,\n dest coin.Address) (visor.SignedBlock, error) {\n sb := visor.SignedBlock{}\n if gb.Block.Head.BkSeq != uint64(0) {\n return sb, errors.New(\"Must be genesis block\")\n }\n // Send the entire genesis block to dest\n if len(gb.Block.Body.Transactions) != 1 {\n log.Panic(\"Genesis block has only 1 txn\")\n }\n tx := gb.Block.Body.Transactions[0]\n if len(tx.Out) != 1 {\n log.Panic(\"Genesis block has only 1 output\")\n }\n amt := visor.NewBalance(tx.Out[0].Coins, tx.Out[0].Hours)\n tx, err := v.Spend(amt, 0, dest)\n if err != nil {\n return sb, err\n }\n // Add the tx to the unconfirmed pool so it can get picked up\n err, _ = v.RecordTxn(tx)\n if err != nil {\n return sb, err\n }\n // Put the tx in a block and commit\n sb, err = v.CreateBlock(gb.Block.Head.Time + 1)\n if err != nil {\n return sb, err\n }\n err = v.ExecuteSignedBlock(sb)\n if err != nil {\n return sb, err\n }\n return sb, nil\n}", "func (_StandardToken *StandardTokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _StandardToken.Contract.StandardTokenTransactor.contract.Transfer(opts)\n}", "func (_StandardToken *StandardTokenRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _StandardToken.Contract.StandardTokenTransactor.contract.Transfer(opts)\n}" ]
[ "0.59044206", "0.58445424", "0.58438736", "0.5824221", "0.5764436", "0.5750469", "0.5714623", "0.5655064", "0.5607176", "0.5605843", "0.55872256", "0.5583866", "0.556326", "0.55429995", "0.5541394", "0.5541394", "0.55385965", "0.5532491", "0.552686", "0.55218875", "0.5501367", "0.5501367", "0.5489908", "0.54887724", "0.54875374", "0.5485329", "0.54844683", "0.54658014", "0.54658014", "0.54606676", "0.5451256", "0.5451256", "0.5449692", "0.5447463", "0.5444774", "0.5440246", "0.5435657", "0.5435657", "0.5429156", "0.54163516", "0.5414415", "0.541325", "0.5410836", "0.5409507", "0.53993887", "0.53941935", "0.5386609", "0.5386609", "0.5386609", "0.5386609", "0.5386609", "0.53855896", "0.53740394", "0.53727275", "0.53718907", "0.5371623", "0.5371623", "0.5371623", "0.5371623", "0.5371623", "0.53676325", "0.5360512", "0.5350895", "0.5349053", "0.5345894", "0.53301364", "0.53281593", "0.5327457", "0.5327446", "0.53235084", "0.53212756", "0.53197896", "0.5313883", "0.5313883", "0.5313493", "0.53110015", "0.5307408", "0.5306541", "0.53056705", "0.5304144", "0.5296921", "0.52916163", "0.528993", "0.528993", "0.5284711", "0.5284711", "0.52636784", "0.5260305", "0.5260305", "0.5258181", "0.5258181", "0.5257015", "0.5245206", "0.5241699", "0.5241699", "0.5237689", "0.5237689", "0.5234008", "0.5233751", "0.5233751" ]
0.61959475
0
distributeReward adds the reward to the future vesting schedule in proportion to the future vesting staking tokens.
func (va ClawbackVestingAccount) distributeReward(ctx sdk.Context, ak AccountKeeper, bondDenom string, reward sdk.Coins) { now := ctx.BlockTime().Unix() t := va.StartTime firstUnvestedPeriod := 0 unvestedTokens := sdk.ZeroInt() for i, period := range va.VestingPeriods { t += period.Length if t <= now { firstUnvestedPeriod = i + 1 continue } unvestedTokens = unvestedTokens.Add(period.Amount.AmountOf(bondDenom)) } runningTotReward := sdk.NewCoins() runningTotStaking := sdk.ZeroInt() for i := firstUnvestedPeriod; i < len(va.VestingPeriods); i++ { period := va.VestingPeriods[i] runningTotStaking = runningTotStaking.Add(period.Amount.AmountOf(bondDenom)) runningTotRatio := runningTotStaking.ToDec().Quo(unvestedTokens.ToDec()) targetCoins := scaleCoins(reward, runningTotRatio) thisReward := targetCoins.Sub(runningTotReward) runningTotReward = targetCoins period.Amount = period.Amount.Add(thisReward...) va.VestingPeriods[i] = period } va.OriginalVesting = va.OriginalVesting.Add(reward...) ak.SetAccount(ctx, &va) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) DistributeETHReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"distributeETHReward\")\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) DistributeERC20Reward(opts *bind.TransactOpts, _tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"distributeERC20Reward\", _tokenAddress, _value)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\n}", "func distributeDelegatorRewards(ctx contract.Context, cachedDelegations *CachedDposStorage, formerValidatorTotals map[string]loom.BigUInt, delegatorRewards map[string]*loom.BigUInt, distributedRewards *loom.BigUInt) (map[string]*loom.BigUInt, error) {\n\tnewDelegationTotals := make(map[string]*loom.BigUInt)\n\n\tcandidates, err := LoadCandidateList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize delegation totals with whitelist amounts\n\tfor _, candidate := range candidates {\n\t\tstatistic, _ := GetStatistic(ctx, loom.UnmarshalAddressPB(candidate.Address))\n\n\t\tif statistic != nil && statistic.WhitelistAmount != nil && !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\tvalidatorKey := loom.UnmarshalAddressPB(statistic.Address).String()\n\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\tnewDelegationTotals[validatorKey] = &amount\n\t\t}\n\t}\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar currentDelegations = make(DelegationList, len(delegations))\n\tcopy(currentDelegations, delegations)\n\tfor _, d := range currentDelegations {\n\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\tif err == contract.ErrNotFound {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalidatorKey := loom.UnmarshalAddressPB(delegation.Validator).String()\n\n\t\t// Do not distribute rewards to delegators of the Limbo validator\n\t\t// NOTE: because all delegations are sorted in reverse index order, the\n\t\t// 0-index delegation (for rewards) is handled last. Therefore, all\n\t\t// increases to reward delegations will be reflected in newDelegation\n\t\t// totals that are computed at the end of this for loop. (We do this to\n\t\t// avoid looping over all delegations twice)\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\t// allocating validator distributions to delegators\n\t\t\t// based on former validator delegation totals\n\t\t\tdelegationTotal := formerValidatorTotals[validatorKey]\n\t\t\trewardsTotal := delegatorRewards[validatorKey]\n\t\t\tif rewardsTotal != nil {\n\t\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\t\tdelegatorDistribution := calculateShare(weightedDelegation, delegationTotal, *rewardsTotal)\n\t\t\t\t// increase a delegator's distribution\n\t\t\t\tdistributedRewards.Add(distributedRewards, &delegatorDistribution)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, delegation.Validator, delegation.Delegator, delegatorDistribution)\n\n\t\t\t\t// If the reward delegation is updated by the\n\t\t\t\t// IncreaseRewardDelegation command, we must be sure to use this\n\t\t\t\t// updated version in the rest of the loop. No other delegations\n\t\t\t\t// (non-rewards) have the possibility of being updated outside\n\t\t\t\t// of this loop.\n\t\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) && d.Index == REWARD_DELEGATION_INDEX {\n\t\t\t\t\tdelegation, err = GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\tif err == contract.ErrNotFound {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tupdatedAmount := common.BigZero()\n\t\tif delegation.State == BONDING {\n\t\t\tupdatedAmount.Add(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t} else if delegation.State == UNBONDING {\n\t\t\tupdatedAmount.Sub(&delegation.Amount.Value, &delegation.UpdateAmount.Value)\n\t\t\tdelegation.Amount = &types.BigUInt{Value: *updatedAmount}\n\t\t\tcoin, err := loadCoin(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\terr = coin.Transfer(loom.UnmarshalAddressPB(delegation.Delegator), &delegation.UpdateAmount.Value)\n\t\t\tif err != nil {\n\t\t\t\ttransferFromErr := fmt.Sprintf(\"Failed coin Transfer - distributeDelegatorRewards, %v, %s\", delegation.Delegator.String(), delegation.UpdateAmount.Value.String())\n\t\t\t\treturn nil, logDposError(ctx, err, transferFromErr)\n\t\t\t}\n\t\t} else if delegation.State == REDELEGATING {\n\t\t\tif err = cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Validator = delegation.UpdateValidator\n\t\t\tdelegation.Amount = delegation.UpdateAmount\n\t\t\tdelegation.LocktimeTier = delegation.UpdateLocktimeTier\n\n\t\t\tindex, err := GetNextDelegationIndex(ctx, *delegation.Validator, *delegation.Delegator)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdelegation.Index = index\n\n\t\t\tvalidatorKey = loom.UnmarshalAddressPB(delegation.Validator).String()\n\t\t}\n\n\t\t// Delete any delegation whose full amount has been unbonded. In all\n\t\t// other cases, update the delegation state to BONDED and reset its\n\t\t// UpdateAmount\n\t\tif common.IsZero(delegation.Amount.Value) && delegation.State == UNBONDING {\n\t\t\tif err := cachedDelegations.DeleteDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\t// After a delegation update, zero out UpdateAmount\n\t\t\tdelegation.UpdateAmount = loom.BigZeroPB()\n\t\t\tdelegation.State = BONDED\n\n\t\t\tresetDelegationIfExpired(ctx, delegation)\n\t\t\tif err := cachedDelegations.SetDelegation(ctx, delegation); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// Calculate delegation totals for all validators except the Limbo\n\t\t// validator\n\t\tif loom.UnmarshalAddressPB(delegation.Validator).Compare(LimboValidatorAddress(ctx)) != 0 {\n\t\t\tnewTotal := common.BigZero()\n\t\t\tweightedDelegation := calculateWeightedDelegationAmount(*delegation)\n\t\t\tnewTotal.Add(newTotal, &weightedDelegation)\n\t\t\tif newDelegationTotals[validatorKey] != nil {\n\t\t\t\tnewTotal.Add(newTotal, newDelegationTotals[validatorKey])\n\t\t\t}\n\t\t\tnewDelegationTotals[validatorKey] = newTotal\n\t\t}\n\t}\n\n\treturn newDelegationTotals, nil\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\n}", "func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\n}", "func (a Actor) AwardBlockReward(rt vmr.Runtime, params *AwardBlockRewardParams) *adt.EmptyValue {\n\trt.ValidateImmediateCallerIs(builtin.SystemActorAddr)\n\tAssertMsg(rt.CurrentBalance().GreaterThanEqual(params.GasReward),\n\t\t\"actor current balance %v insufficient to pay gas reward %v\", rt.CurrentBalance(), params.GasReward)\n\n\tAssertMsg(params.TicketCount > 0, \"cannot give block reward for zero tickets\")\n\n\tminer, ok := rt.ResolveAddress(params.Miner)\n\tif !ok {\n\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to resolve given owner address\")\n\t}\n\n\tpriorBalance := rt.CurrentBalance()\n\n\tvar penalty abi.TokenAmount\n\tvar st State\n\trt.State().Transaction(&st, func() interface{} {\n\t\tblockReward := a.computeBlockReward(&st, big.Sub(priorBalance, params.GasReward), params.TicketCount)\n\t\ttotalReward := big.Add(blockReward, params.GasReward)\n\n\t\t// Cap the penalty at the total reward value.\n\t\tpenalty = big.Min(params.Penalty, totalReward)\n\n\t\t// Reduce the payable reward by the penalty.\n\t\trewardPayable := big.Sub(totalReward, penalty)\n\n\t\tAssertMsg(big.Add(rewardPayable, penalty).LessThanEqual(priorBalance),\n\t\t\t\"reward payable %v + penalty %v exceeds balance %v\", rewardPayable, penalty, priorBalance)\n\n\t\t// Record new reward into reward map.\n\t\tif rewardPayable.GreaterThan(abi.NewTokenAmount(0)) {\n\t\t\tnewReward := Reward{\n\t\t\t\tStartEpoch: rt.CurrEpoch(),\n\t\t\t\tEndEpoch: rt.CurrEpoch() + rewardVestingPeriod,\n\t\t\t\tValue: rewardPayable,\n\t\t\t\tAmountWithdrawn: abi.NewTokenAmount(0),\n\t\t\t\tVestingFunction: rewardVestingFunction,\n\t\t\t}\n\t\t\tif err := st.addReward(adt.AsStore(rt), miner, &newReward); err != nil {\n\t\t\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to add reward to rewards map: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\t// Burn the penalty amount.\n\t_, code := rt.Send(builtin.BurntFundsActorAddr, builtin.MethodSend, nil, penalty)\n\tbuiltin.RequireSuccess(rt, code, \"failed to send penalty to BurntFundsActor\")\n\n\treturn nil\n}", "func (s *MutableState) AddRewards(time epochtime.EpochTime, factor *quantity.Quantity, accounts []signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tfor _, id := range accounts {\n\t\tent := s.Account(id)\n\n\t\tq := ent.Escrow.Active.Balance.Clone()\n\t\t// Multiply first.\n\t\tif err := q.Mul(factor); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t\t}\n\t\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t\t}\n\t\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t\t}\n\n\t\tif q.IsZero() {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar com *quantity.Quantity\n\t\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\t\tif rate != nil {\n\t\t\tcom = q.Clone()\n\t\t\t// Multiply first.\n\t\t\tif err := com.Mul(rate); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t\t}\n\t\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t\t}\n\n\t\t\tif err := q.Sub(com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t\t}\n\t\t}\n\n\t\tif !q.IsZero() {\n\t\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t\t}\n\t\t}\n\n\t\tif com != nil && !com.IsZero() {\n\t\t\tdelegation := s.Delegation(id, id)\n\n\t\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t\t}\n\n\t\t\ts.SetDelegation(id, id, delegation)\n\t\t}\n\n\t\ts.SetAccount(id, ent)\n\t}\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func (s *MutableState) AddRewardSingleAttenuated(time epochtime.EpochTime, factor *quantity.Quantity, attenuationNumerator, attenuationDenominator int, account signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tvar numQ, denQ quantity.Quantity\n\tif err = numQ.FromInt64(int64(attenuationNumerator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation numerator %d\", attenuationNumerator)\n\t}\n\tif err = denQ.FromInt64(int64(attenuationDenominator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation denominator %d\", attenuationDenominator)\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tent := s.Account(account)\n\n\tq := ent.Escrow.Active.Balance.Clone()\n\t// Multiply first.\n\tif err := q.Mul(factor); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t}\n\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t}\n\tif err := q.Mul(&numQ); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by attenuation numerator\")\n\t}\n\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t}\n\tif err := q.Quo(&denQ); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by attenuation denominator\")\n\t}\n\n\tif q.IsZero() {\n\t\treturn nil\n\t}\n\n\tvar com *quantity.Quantity\n\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\tif rate != nil {\n\t\tcom = q.Clone()\n\t\t// Multiply first.\n\t\tif err := com.Mul(rate); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t}\n\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t}\n\n\t\tif err := q.Sub(com); err != nil {\n\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t}\n\t}\n\n\tif !q.IsZero() {\n\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t}\n\t}\n\n\tif com != nil && !com.IsZero() {\n\t\tdelegation := s.Delegation(account, account)\n\n\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t}\n\n\t\ts.SetDelegation(account, account, delegation)\n\t}\n\n\ts.SetAccount(account, ent)\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func weighted_reward(w map[int]float64, allocation vrp.Allocation) float64 {\n\tvar reward float64\n\tfor id, _ := range allocation {\n\t\treward += w[id] * allocation[id]\n\t}\n\treturn reward\n}", "func (d *Dao) AddReward(c context.Context, iRewardID int64, uid int64, iSource int64, iRoomid int64, iLifespan int64) (err error) {\n\t//aReward, _ := getRewardConfByLid(iRewardID)\n\n\tm, _ := time.ParseDuration(fmt.Sprintf(\"+%dh\", iLifespan))\n\n\targ := &AnchorTaskModel.AnchorReward{\n\t\tUid: uid,\n\t\tRewardId: iRewardID,\n\t\tRoomid: iRoomid,\n\t\tSource: iSource,\n\t\tAchieveTime: xtime.Time(time.Now().Unix()),\n\t\tExpireTime: xtime.Time(time.Now().Add(m).Unix()),\n\t\tStatus: model.RewardUnUsed,\n\t}\n\n\t//spew.Dump\n\t// (arg)\n\tif err := d.orm.Create(arg).Error; err != nil {\n\t\tlog.Error(\"addReward(%v) error(%v)\", arg, err)\n\t\treturn err\n\t}\n\n\tif err := d.SetNewReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"addRewardMc(%v) error(%v)\", uid, err)\n\t}\n\n\tif err := d.SetHasReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"SetHasReward(%v) error(%v)\", uid, err)\n\t}\n\n\tlog.Info(\"addReward (%v) succ\", arg)\n\n\treturn\n}", "func (_XStaking *XStakingCaller) RewardsDistribution(opts *bind.CallOpts) (common.Address, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewardsDistribution\")\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func distributeLockedAmount(ctx coretypes.Sandbox, bets []*BetInfo, totalLockedAmount int64) bool {\n\tsumsByPlayers := make(map[coretypes.AgentID]int64)\n\ttotalWinningAmount := int64(0)\n\tfor _, bet := range bets {\n\t\tif _, ok := sumsByPlayers[bet.Player]; !ok {\n\t\t\tsumsByPlayers[bet.Player] = 0\n\t\t}\n\t\tsumsByPlayers[bet.Player] += bet.Sum\n\t\ttotalWinningAmount += bet.Sum\n\t}\n\n\t// NOTE 1: float64 was avoided for determinism reasons\n\t// NOTE 2: beware overflows\n\n\tfor player, sum := range sumsByPlayers {\n\t\tsumsByPlayers[player] = (totalLockedAmount * sum) / totalWinningAmount\n\t}\n\n\t// make deterministic sequence by sorting. Eliminate possible rounding effects\n\tseqPlayers := make([]coretypes.AgentID, 0, len(sumsByPlayers))\n\tresultSum := int64(0)\n\tfor player, sum := range sumsByPlayers {\n\t\tseqPlayers = append(seqPlayers, player)\n\t\tresultSum += sum\n\t}\n\tsort.Slice(seqPlayers, func(i, j int) bool {\n\t\treturn bytes.Compare(seqPlayers[i][:], seqPlayers[j][:]) < 0\n\t})\n\n\t// ensure we distribute not more than totalLockedAmount iotas\n\tif resultSum > totalLockedAmount {\n\t\tsumsByPlayers[seqPlayers[0]] -= resultSum - totalLockedAmount\n\t}\n\n\t// filter out those who proportionally got 0\n\tfinalWinners := seqPlayers[:0]\n\tfor _, player := range seqPlayers {\n\t\tif sumsByPlayers[player] <= 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfinalWinners = append(finalWinners, player)\n\t}\n\t// distribute iotas\n\tfor i := range finalWinners {\n\n\t\tavailable := ctx.Balance(balance.ColorIOTA)\n\t\tctx.Event(fmt.Sprintf(\"sending reward iotas %d to the winner %s. Available iotas: %d\",\n\t\t\tsumsByPlayers[finalWinners[i]], finalWinners[i].String(), available))\n\n\t\t//if !ctx.MoveTokens(finalWinners[i], balance.ColorIOTA, sumsByPlayers[finalWinners[i]]) {\n\t\t//\treturn false\n\t\t//}\n\t}\n\treturn true\n}", "func (vi *votedInfo) CalculateReward(multiplier, divider *big.Int, period int) {\n\tif multiplier.Sign() == 0 || period == 0 {\n\t\treturn\n\t}\n\tif divider.Sign() == 0 || vi.totalBondedDelegation.Sign() == 0 {\n\t\treturn\n\t}\n\t// reward = multiplier * period * bondedDelegation / (divider * totalBondedDelegation)\n\tbase := new(big.Int).Mul(multiplier, big.NewInt(int64(period)))\n\treward := new(big.Int)\n\tfor i, addrKey := range vi.rank {\n\t\tif i == vi.maxRankForReward {\n\t\t\tbreak\n\t\t}\n\t\tprep := vi.preps[addrKey]\n\t\tif prep.Enable() == false {\n\t\t\tcontinue\n\t\t}\n\n\t\treward.Mul(base, prep.GetBondedDelegation())\n\t\treward.Div(reward, divider)\n\t\treward.Div(reward, vi.totalBondedDelegation)\n\n\t\tlog.Tracef(\"VOTED REWARD %d = %d * %d * %d / (%d * %d)\",\n\t\t\treward, multiplier, period, prep.GetBondedDelegation(), divider, vi.totalBondedDelegation)\n\n\t\tprep.SetIScore(new(big.Int).Add(prep.IScore(), reward))\n\t}\n}", "func accumulateRewards(config *params.ChainConfig, state *state.DB, header *types.Header) {\n\t// TODO: implement mining rewards\n}", "func EstimateReward(reward, pr, gamma float64) float64 {\n\tret := reward / (pr + gamma)\n\tlog.Logf(MABLogLevel, \"MAB Estimate Reward: %v / (%v + %v) = %v\\n\",\n\t\treward, pr, gamma, ret)\n\treturn ret\n}", "func rewardAndSlash(ctx contract.Context, cachedDelegations *CachedDposStorage, state *State) ([]*DelegationResult, error) {\n\tformerValidatorTotals := make(map[string]loom.BigUInt)\n\tdelegatorRewards := make(map[string]*loom.BigUInt)\n\tdistributedRewards := common.BigZero()\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, validator := range state.Validators {\n\t\tcandidate := GetCandidateByPubKey(ctx, validator.PubKey)\n\n\t\tif candidate == nil {\n\t\t\tctx.Logger().Info(\"Attempted to reward validator no longer on candidates list.\", \"validator\", validator)\n\t\t\tcontinue\n\t\t}\n\n\t\tcandidateAddress := loom.UnmarshalAddressPB(candidate.Address)\n\t\tvalidatorKey := candidateAddress.String()\n\t\tstatistic, _ := GetStatistic(ctx, candidateAddress)\n\n\t\tif statistic == nil {\n\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t} else {\n\t\t\t// If a validator is jailed, don't calculate and distribute rewards\n\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_3, false) {\n\t\t\t\tif statistic.Jailed {\n\t\t\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If a validator's SlashPercentage is 0, the validator is\n\t\t\t// rewarded for avoiding faults during the last slashing period\n\t\t\tif common.IsZero(statistic.SlashPercentage.Value) {\n\t\t\t\tdistributionTotal := calculateRewards(statistic.DelegationTotal.Value, state.Params, state.TotalValidatorDelegations.Value)\n\n\t\t\t\t// The validator share, equal to validator_fee * total_validotor_reward\n\t\t\t\t// is to be split between the referrers and the validator\n\t\t\t\tvalidatorShare := CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, distributionTotal)\n\n\t\t\t\t// delegatorsShare is what fraction of the total rewards will be\n\t\t\t\t// distributed to delegators\n\t\t\t\tdelegatorsShare := common.BigZero()\n\t\t\t\tdelegatorsShare.Sub(&distributionTotal, &validatorShare)\n\t\t\t\tdelegatorRewards[validatorKey] = delegatorsShare\n\n\t\t\t\t// Distribute rewards to referrers\n\t\t\t\tfor _, d := range delegations {\n\t\t\t\t\tif loom.UnmarshalAddressPB(d.Validator).Compare(loom.UnmarshalAddressPB(candidate.Address)) == 0 {\n\t\t\t\t\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\t\t// if the delegation is not found OR if the delegation\n\t\t\t\t\t\t// has no referrer, we do not need to attempt to\n\t\t\t\t\t\t// distribute the referrer rewards\n\t\t\t\t\t\tif err == contract.ErrNotFound || len(delegation.Referrer) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// if referrer is not found, do not distribute the reward\n\t\t\t\t\t\treferrerAddress := getReferrer(ctx, delegation.Referrer)\n\t\t\t\t\t\tif referrerAddress == nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// calculate referrerReward\n\t\t\t\t\t\treferrerReward := calculateRewards(delegation.Amount.Value, state.Params, state.TotalValidatorDelegations.Value)\n\t\t\t\t\t\treferrerReward = CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, referrerReward)\n\t\t\t\t\t\treferrerReward = CalculateFraction(defaultReferrerFee, referrerReward)\n\n\t\t\t\t\t\t// referrer fees are delegater to limbo validator\n\t\t\t\t\t\tdistributedRewards.Add(distributedRewards, &referrerReward)\n\t\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, LimboValidatorAddress(ctx).MarshalPB(), referrerAddress, referrerReward)\n\n\t\t\t\t\t\t// any referrer bonus amount is subtracted from the validatorShare\n\t\t\t\t\t\tvalidatorShare.Sub(&validatorShare, &referrerReward)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdistributedRewards.Add(distributedRewards, &validatorShare)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, validatorShare)\n\n\t\t\t\t// If a validator has some non-zero WhitelistAmount,\n\t\t\t\t// calculate the validator's reward based on whitelist amount\n\t\t\t\tif !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\t\t\twhitelistDistribution := calculateShare(amount, statistic.DelegationTotal.Value, *delegatorsShare)\n\t\t\t\t\t// increase a delegator's distribution\n\t\t\t\t\tdistributedRewards.Add(distributedRewards, &whitelistDistribution)\n\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, whitelistDistribution)\n\t\t\t\t}\n\n\t\t\t\t// Keeping track of cumulative distributed rewards by adding\n\t\t\t\t// every validator's total rewards to\n\t\t\t\t// `state.TotalRewardDistribution`\n\t\t\t\t// NOTE: because we round down in every `calculateRewards` call,\n\t\t\t\t// we expect `state.TotalRewardDistribution` to be a slight\n\t\t\t\t// overestimate of what was actually distributed. We could be\n\t\t\t\t// exact with our record keeping by incrementing\n\t\t\t\t// `state.TotalRewardDistribution` each time\n\t\t\t\t// `IncreaseRewardDelegation` is called, but because we will not\n\t\t\t\t// use `state.TotalRewardDistributions` as part of any invariants,\n\t\t\t\t// we will live with this situation.\n\t\t\t\tif !ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\t\t\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, &distributionTotal)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := slashValidatorDelegations(ctx, cachedDelegations, statistic, candidateAddress); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif err := SetStatistic(ctx, statistic); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tformerValidatorTotals[validatorKey] = statistic.DelegationTotal.Value\n\t\t}\n\t}\n\n\tnewDelegationTotals, err := distributeDelegatorRewards(ctx, cachedDelegations, formerValidatorTotals, delegatorRewards, distributedRewards)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, distributedRewards)\n\t}\n\n\tdelegationResults := make([]*DelegationResult, 0, len(newDelegationTotals))\n\tfor validator := range newDelegationTotals {\n\t\tdelegationResults = append(delegationResults, &DelegationResult{\n\t\t\tValidatorAddress: loom.MustParseAddress(validator),\n\t\t\tDelegationTotal: *newDelegationTotals[validator],\n\t\t})\n\t}\n\tsort.Sort(byDelegationTotal(delegationResults))\n\n\treturn delegationResults, nil\n}", "func (node *TreeNode) backpropagateReward(scores [2]float64) {\n\tcurrentNode := node\n\tfor currentNode.Parent != nil {\n\t\tcurrentNode.VisitCount += 1.0\n\t\tcurrentNode.CumulativeScore[0] += scores[0]\n\t\tcurrentNode.CumulativeScore[1] += scores[1]\n\t\tcurrentNode = currentNode.Parent\n\t}\n\t//Increment root node counter\n\tcurrentNode.VisitCount += 1.0\n}", "func (k Keeper) ClaimEarnReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedEarnClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetEarnClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func computeReward(epoch abi.ChainEpoch, prevTheta, currTheta, simpleTotal, baselineTotal big.Int) abi.TokenAmount {\n\tsimpleReward := big.Mul(simpleTotal, ExpLamSubOne) //Q.0 * Q.128 => Q.128\n\tepochLam := big.Mul(big.NewInt(int64(epoch)), Lambda) // Q.0 * Q.128 => Q.128\n\n\tsimpleReward = big.Mul(simpleReward, big.NewFromGo(math.ExpNeg(epochLam.Int))) // Q.128 * Q.128 => Q.256\n\tsimpleReward = big.Rsh(simpleReward, math.Precision128) // Q.256 >> 128 => Q.128\n\n\tbaselineReward := big.Sub(computeBaselineSupply(currTheta, baselineTotal), computeBaselineSupply(prevTheta, baselineTotal)) // Q.128\n\n\treward := big.Add(simpleReward, baselineReward) // Q.128\n\n\treturn big.Rsh(reward, math.Precision128) // Q.128 => Q.0\n}", "func ApplyRewardTx(tx *types.Transaction, statedb *state.Statedb) (*types.Receipt, error) {\n\tstatedb.CreateAccount(tx.Data.To)\n\tstatedb.AddBalance(tx.Data.To, tx.Data.Amount)\n\n\thash, err := statedb.Hash()\n\tif err != nil {\n\t\treturn nil, errors.NewStackedError(err, \"failed to get statedb root hash\")\n\t}\n\n\treceipt := &types.Receipt{\n\t\tTxHash: tx.Hash,\n\t\tPostState: hash,\n\t}\n\n\treturn receipt, nil\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.NotifyRewardAmount(&_RewardsDistributionRecipient.TransactOpts, reward)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientTransactorSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.NotifyRewardAmount(&_RewardsDistributionRecipient.TransactOpts, reward)\n}", "func (e *engineImpl) Rewarder() reward.Distributor {\n\treturn e.d\n}", "func (_XStaking *XStakingSession) RewardsDistribution() (common.Address, error) {\n\treturn _XStaking.Contract.RewardsDistribution(&_XStaking.CallOpts)\n}", "func (_XStaking *XStakingTransactor) SetRewardsDistribution(opts *bind.TransactOpts, _rewardsDistribution common.Address) (*types.Transaction, error) {\n\treturn _XStaking.contract.Transact(opts, \"setRewardsDistribution\", _rewardsDistribution)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientCaller) RewardsDistribution(opts *bind.CallOpts) (common.Address, error) {\n\tvar out []interface{}\n\terr := _RewardsDistributionRecipient.contract.Call(opts, &out, \"rewardsDistribution\")\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (_RandomBeacon *RandomBeaconTransactor) UpdateRewardParameters(opts *bind.TransactOpts, sortitionPoolRewardsBanDuration *big.Int, relayEntryTimeoutNotificationRewardMultiplier *big.Int, unauthorizedSigningNotificationRewardMultiplier *big.Int, dkgMaliciousResultNotificationRewardMultiplier *big.Int) (*types.Transaction, error) {\n\treturn _RandomBeacon.contract.Transact(opts, \"updateRewardParameters\", sortitionPoolRewardsBanDuration, relayEntryTimeoutNotificationRewardMultiplier, unauthorizedSigningNotificationRewardMultiplier, dkgMaliciousResultNotificationRewardMultiplier)\n}", "func (k Keeper) AllocateTokens(ctx sdk.Context, percentVotes sdk.Dec, proposer sdk.ConsAddress) {\n\tlogger := ctx.Logger()\n\t// get the proposer of this block\n\tproposerValidator := k.stakeKeeper.ValidatorByConsAddr(ctx, proposer)\n\n\tif proposerValidator == nil {\n\t\tpanic(fmt.Sprintf(\"Can't find proposer %s in validator set\", proposerValidator.GetConsAddr()))\n\t}\n\n\tproposerDist := k.GetValidatorDistInfo(ctx, proposerValidator.GetOperator())\n\n\t// get the fees which have been getting collected through all the\n\t// transactions in the block\n\tfeesCollected := k.feeKeeper.GetCollectedFees(ctx)\n\tfeesCollectedDec := types.NewDecCoins(feesCollected)\n\n\tlogger.Info(\"Get collected transaction fee token and minted token\", \"collected_token\", feesCollected)\n\n\tfeePool := k.GetFeePool(ctx)\n\tif k.stakeKeeper.GetLastTotalPower(ctx).IsZero() {\n\t\tk.bankKeeper.AddCoins(ctx, auth.CommunityTaxCoinsAccAddr, feesCollected)\n\t\t//\t\tfeePool.CommunityPool = feePool.CommunityPool.Add(feesCollectedDec)\n\t\t//\t\tk.SetFeePool(ctx, feePool)\n\t\tk.feeKeeper.ClearCollectedFees(ctx)\n\t\tctx.CoinFlowTags().AppendCoinFlowTag(ctx, \"\", auth.CommunityTaxCoinsAccAddr.String(), feesCollected.String(), sdk.CommunityTaxCollectFlow, \"\")\n\t\treturn\n\t}\n\n\tvar proposerReward types.DecCoins\n\t// If a validator is jailed, distribute no reward to it\n\t// The jailed validator happen to be a proposer which is a very corner case\n\tvalidator := k.stakeKeeper.Validator(ctx, proposerValidator.GetOperator())\n\tif !validator.GetJailed() {\n\t\t// allocated rewards to proposer\n\t\tlogger.Info(\"Allocate reward to proposer\", \"proposer_address\", proposerValidator.GetOperator().String())\n\t\tbaseProposerReward := k.GetBaseProposerReward(ctx)\n\t\tbonusProposerReward := k.GetBonusProposerReward(ctx)\n\t\tproposerMultiplier := baseProposerReward.Add(bonusProposerReward.Mul(percentVotes))\n\t\tproposerReward = feesCollectedDec.MulDec(proposerMultiplier)\n\n\t\t// apply commission\n\t\tcommission := proposerReward.MulDec(proposerValidator.GetCommission())\n\t\tremaining := proposerReward.Minus(commission)\n\t\tproposerDist.ValCommission = proposerDist.ValCommission.Plus(commission)\n\t\tproposerDist.DelPool = proposerDist.DelPool.Plus(remaining)\n\t\tlogger.Info(\"Allocate commission to proposer commission pool\", \"commission\", commission.ToString())\n\t\tlogger.Info(\"Allocate reward to proposer delegation reward pool\", \"delegation_reward\", remaining.ToString())\n\n\t\t// save validator distribution info\n\t\tk.SetValidatorDistInfo(ctx, proposerDist)\n\t} else {\n\t\tlogger.Info(\"The block proposer is jailed, distribute no reward to it\", \"proposer_address\", proposerValidator.GetOperator().String())\n\t}\n\n\t// allocate community funding\n\tcommunityTax := k.GetCommunityTax(ctx)\n\tcommunityFunding := feesCollectedDec.MulDec(communityTax)\n\n\t//\tfeePool.CommunityPool = feePool.CommunityPool.Add(communityFunding)\n\tfundingCoins, change := communityFunding.TruncateDecimal()\n\tk.bankKeeper.AddCoins(ctx, auth.CommunityTaxCoinsAccAddr, fundingCoins)\n\tctx.CoinFlowTags().AppendCoinFlowTag(ctx, \"\", auth.CommunityTaxCoinsAccAddr.String(), fundingCoins.String(), sdk.CommunityTaxCollectFlow, \"\")\n\n\tcommunityTaxCoins := k.bankKeeper.GetCoins(ctx, auth.CommunityTaxCoinsAccAddr)\n\tcommunityTaxDec := sdk.NewDecFromInt(communityTaxCoins.AmountOf(sdk.IrisAtto))\n\tcommunityTaxFloat, err := strconv.ParseFloat(communityTaxDec.QuoInt(sdk.AttoScaleFactor).String(), 64)\n\t//communityTaxAmount, err := strconv.ParseFloat(feePool.CommunityPool.AmountOf(sdk.IrisAtto).QuoInt(sdk.AttoScaleFactor).String(), 64)\n\tif err == nil {\n\t\tk.metrics.CommunityTax.Set(communityTaxFloat)\n\t}\n\n\tlogger.Info(\"Allocate reward to community tax fund\", \"allocate_amount\", fundingCoins.String(), \"total_community_tax\", communityTaxCoins.String())\n\n\t// set the global pool within the distribution module\n\tpoolReceived := feesCollectedDec.Minus(proposerReward).Minus(communityFunding).Plus(change)\n\tfeePool.ValPool = feePool.ValPool.Plus(poolReceived)\n\tk.SetFeePool(ctx, feePool)\n\n\tlogger.Info(\"Allocate reward to global validator pool\", \"allocate_amount\", poolReceived.ToString(), \"total_global_validator_pool\", feePool.ValPool.ToString())\n\n\t// clear the now distributed fees\n\tk.feeKeeper.ClearCollectedFees(ctx)\n}", "func (_XStaking *XStakingSession) SetRewardsDistribution(_rewardsDistribution common.Address) (*types.Transaction, error) {\n\treturn _XStaking.Contract.SetRewardsDistribution(&_XStaking.TransactOpts, _rewardsDistribution)\n}", "func (_XStaking *XStakingTransactorSession) SetRewardsDistribution(_rewardsDistribution common.Address) (*types.Transaction, error) {\n\treturn _XStaking.Contract.SetRewardsDistribution(&_XStaking.TransactOpts, _rewardsDistribution)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientTransactor) NotifyRewardAmount(opts *bind.TransactOpts, reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.contract.Transact(opts, \"notifyRewardAmount\", reward)\n}", "func (t *trusteeImpl) NewMiningRewardTx(block consensus.Block) *consensus.Transaction {\n\tvar tx *consensus.Transaction\n\t// build list of miner nodes for uncle blocks\n\tuncleMiners := make([][]byte, len(block.UncleMiners()))\n\tfor i, uncleMiner := range block.UncleMiners() {\n\t\tuncleMiners[i] = uncleMiner\n\t}\n\t\n\tops := make([]Op, 1 + len(uncleMiners))\n\t// first add self's mining reward\n\tops[0] = *t.myReward\n\t\n\t// now add award for each uncle\n\tfor i, uncleMiner := range uncleMiners {\n\t\top := NewOp(OpReward)\n\t\top.Params[ParamUncle] = bytesToHexString(uncleMiner)\n\t\top.Params[ParamAward] = UncleAward\n\t\tops[i+1] = *op \n\t}\n\t// serialize ops into payload\n\tif payload,err := common.Serialize(ops); err != nil {\n\t\tt.log.Error(\"Failed to serialize ops into payload: %s\", err)\n\t\treturn nil\n\t} else {\n\t\t// make a signed transaction out of payload\n\t\tif signature := t.sign(payload); len(signature) > 0 {\n\t\t\t// return the signed transaction\n\t\t\ttx = consensus.NewTransaction(payload, signature, t.myAddress)\n\t\t\tblock.AddTransaction(tx)\n\t\t\tt.process(block, tx)\n\t\t}\n\t}\n\treturn tx\n}", "func (k Querier) Rewards(c context.Context, req *types.QueryRewardsRequest) (*types.QueryRewardsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"invalid request\")\n\t}\n\n\tif req.StakingCoinDenom != \"\" {\n\t\tif err := sdk.ValidateDenom(req.StakingCoinDenom); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tctx := sdk.UnwrapSDKContext(c)\n\tstore := ctx.KVStore(k.storeKey)\n\tvar rewards []types.Reward\n\tvar pageRes *query.PageResponse\n\tvar err error\n\n\tif req.Farmer != \"\" {\n\t\tvar farmerAcc sdk.AccAddress\n\t\tfarmerAcc, err = sdk.AccAddressFromBech32(req.Farmer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tstorePrefix := types.GetRewardsByFarmerIndexKey(farmerAcc)\n\t\tindexStore := prefix.NewStore(store, storePrefix)\n\t\tpageRes, err = query.FilteredPaginate(indexStore, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) {\n\t\t\t_, stakingCoinDenom := types.ParseRewardsByFarmerIndexKey(append(storePrefix, key...))\n\t\t\tif req.StakingCoinDenom != \"\" {\n\t\t\t\tif stakingCoinDenom != req.StakingCoinDenom {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treward, found := k.GetReward(ctx, stakingCoinDenom, farmerAcc)\n\t\t\tif !found { // TODO: remove this check\n\t\t\t\treturn false, fmt.Errorf(\"reward not found\")\n\t\t\t}\n\t\t\tif accumulate {\n\t\t\t\trewards = append(rewards, reward)\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n\t} else {\n\t\tvar storePrefix []byte\n\t\tif req.StakingCoinDenom != \"\" {\n\t\t\tstorePrefix = types.GetRewardsByStakingCoinDenomKey(req.StakingCoinDenom)\n\t\t} else {\n\t\t\tstorePrefix = types.RewardKeyPrefix\n\t\t}\n\t\trewardStore := prefix.NewStore(store, storePrefix)\n\n\t\tpageRes, err = query.Paginate(rewardStore, req.Pagination, func(key, value []byte) error {\n\t\t\tstakingCoinDenom, farmerAcc := types.ParseRewardKey(append(storePrefix, key...))\n\t\t\trewardCoins, err := k.UnmarshalRewardCoins(value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\trewards = append(rewards, types.Reward{\n\t\t\t\tFarmer: farmerAcc.String(),\n\t\t\t\tStakingCoinDenom: stakingCoinDenom,\n\t\t\t\tRewardCoins: rewardCoins.RewardCoins,\n\t\t\t})\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryRewardsResponse{Rewards: rewards, Pagination: pageRes}, nil\n}", "func (path *Path) AddRewards(rewards map[*Reward]int) {\n\tfor key, value := range rewards {\n\t\tpath.rewards[key] += value\n\t}\n}", "func rewardRate(pool sdk.Coins, blocks int64) sdk.Coins {\n\tcoins := make([]sdk.Coin, 0)\n\tif blocks > 0 {\n\t\tfor _, coin := range pool {\n\t\t\tif coin.IsZero() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// divide by blocks, rounding fractions up\n\t\t\t// (coin.Amount - 1)/blocks + 1\n\t\t\trate := coin.Amount.SubRaw(1).QuoRaw(blocks).AddRaw(1)\n\t\t\tcoins = append(coins, sdk.NewCoin(coin.GetDenom(), rate))\n\t\t}\n\t}\n\treturn sdk.NewCoins(coins...)\n}", "func (_XStaking *XStakingCallerSession) RewardsDistribution() (common.Address, error) {\n\treturn _XStaking.Contract.RewardsDistribution(&_XStaking.CallOpts)\n}", "func (_RandomBeacon *RandomBeaconTransactorSession) UpdateRewardParameters(sortitionPoolRewardsBanDuration *big.Int, relayEntryTimeoutNotificationRewardMultiplier *big.Int, unauthorizedSigningNotificationRewardMultiplier *big.Int, dkgMaliciousResultNotificationRewardMultiplier *big.Int) (*types.Transaction, error) {\n\treturn _RandomBeacon.Contract.UpdateRewardParameters(&_RandomBeacon.TransactOpts, sortitionPoolRewardsBanDuration, relayEntryTimeoutNotificationRewardMultiplier, unauthorizedSigningNotificationRewardMultiplier, dkgMaliciousResultNotificationRewardMultiplier)\n}", "func (k Keeper) ClaimSwapReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedSwapClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetSwapClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_RandomBeacon *RandomBeaconSession) UpdateRewardParameters(sortitionPoolRewardsBanDuration *big.Int, relayEntryTimeoutNotificationRewardMultiplier *big.Int, unauthorizedSigningNotificationRewardMultiplier *big.Int, dkgMaliciousResultNotificationRewardMultiplier *big.Int) (*types.Transaction, error) {\n\treturn _RandomBeacon.Contract.UpdateRewardParameters(&_RandomBeacon.TransactOpts, sortitionPoolRewardsBanDuration, relayEntryTimeoutNotificationRewardMultiplier, unauthorizedSigningNotificationRewardMultiplier, dkgMaliciousResultNotificationRewardMultiplier)\n}", "func (k Keeper) ClaimSavingsReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tk.SynchronizeSavingsClaim(ctx, owner)\n\n\tsyncedClaim, found := k.GetSavingsClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetSavingsClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (c *Calculator) votingReward(\n\tmultiplier *big.Int,\n\tdivider *big.Int,\n\tfrom int,\n\tto int,\n\tprepInfo map[string]*pRepEnable,\n\titer icstate.VotingIterator,\n) *big.Int {\n\ttotal := new(big.Int)\n\tcheckMinVoting := c.global.GetIISSVersion() == icstate.IISSVersion2\n\tfor ; iter.Has(); iter.Next() {\n\t\tif voting, err := iter.Get(); err != nil {\n\t\t\tc.log.Errorf(\"Failed to iterate votings err=%+v\", err)\n\t\t} else {\n\t\t\tif checkMinVoting && voting.Amount().Cmp(BigIntMinDelegation) < 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts := from\n\t\t\te := to\n\t\t\tif prep, ok := prepInfo[icutils.ToKey(voting.To())]; ok {\n\t\t\t\tif prep.StartOffset() != 0 && prep.StartOffset() > s {\n\t\t\t\t\ts = prep.StartOffset()\n\t\t\t\t}\n\t\t\t\tif prep.EndOffset() != 0 && prep.EndOffset() < e {\n\t\t\t\t\te = prep.EndOffset()\n\t\t\t\t}\n\t\t\t\tperiod := e - s\n\t\t\t\tif period <= 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treward := new(big.Int).Mul(multiplier, voting.Amount())\n\t\t\t\treward.Mul(reward, big.NewInt(int64(period)))\n\t\t\t\treward.Div(reward, divider)\n\t\t\t\ttotal.Add(total, reward)\n\t\t\t\tc.log.Tracef(\"VotingReward %s: %s = %s * %s * %d / %s\",\n\t\t\t\t\tvoting.To(), reward, multiplier, voting.Amount(), period, divider)\n\t\t\t}\n\t\t}\n\t}\n\treturn total\n}", "func (c *Coinbase) AddReward(output *Output) {\n\toutput.EncryptedMask = make([]byte, 1)\n\tc.Rewards = append(c.Rewards, output)\n}", "func (d *RandomWalkDistribution) Advance() {\n\td.Step.Advance()\n\td.State += d.Step.Get()\n}", "func MakeReweigh(db *pop.Connection, assertions Assertions) models.Reweigh {\n\tshipment := assertions.MTOShipment\n\tif isZeroUUID(shipment.ID) {\n\t\tassertions.MTOShipment.Status = models.MTOShipmentStatusApproved\n\t\tshipment = MakeMTOShipment(db, assertions)\n\t}\n\n\treweigh := models.Reweigh{\n\t\tRequestedAt: time.Now(),\n\t\tRequestedBy: models.ReweighRequesterTOO,\n\t\tShipment: shipment,\n\t\tShipmentID: shipment.ID,\n\t}\n\n\tmergeModels(&reweigh, assertions.Reweigh)\n\n\tmustCreate(db, &reweigh, assertions.Stub)\n\n\treturn reweigh\n}", "func (ant *Ant) spreadFerment() {\n\tdistance := ant.GetPassedDistance()\n\tdelta := tripWeight / distance\n\tfor i := 0; i < len(ant.visited)-1; i++ {\n\t\tcurrentCity := ant.visited[i]\n\t\tnextCity := ant.visited[i+1]\n\t\toldFerment := (currentCity.Neighbours()[nextCity]).Ferment\n\n\t\t(currentCity.Neighbours()[nextCity]).Ferment = oldFerment*forgetCoefficient + delta\n\t\t(nextCity.Neighbours()[currentCity]).Ferment = oldFerment*forgetCoefficient + delta\n\t}\n}", "func calculateRewards(delegationTotal loom.BigUInt, params *Params, totalValidatorDelegations loom.BigUInt) loom.BigUInt {\n\tcycleSeconds := params.ElectionCycleLength\n\treward := CalculateFraction(blockRewardPercentage, delegationTotal)\n\n\t// If totalValidator Delegations are high enough to make simple reward\n\t// calculations result in more rewards given out than the value of `MaxYearlyReward`,\n\t// scale the rewards appropriately\n\tyearlyRewardTotal := CalculateFraction(blockRewardPercentage, totalValidatorDelegations)\n\tif yearlyRewardTotal.Cmp(&params.MaxYearlyReward.Value) > 0 {\n\t\treward.Mul(&reward, &params.MaxYearlyReward.Value)\n\t\treward.Div(&reward, &yearlyRewardTotal)\n\t}\n\n\t// When election cycle = 0, estimate block time at 2 sec\n\tif cycleSeconds == 0 {\n\t\tcycleSeconds = 2\n\t}\n\treward.Mul(&reward, &loom.BigUInt{big.NewInt(cycleSeconds)})\n\treward.Div(&reward, &secondsInYear)\n\n\treturn reward\n}", "func getRewardForValidator(totalPower *big.Int, validatorPower *big.Int, totalRewards *balance.Amount) *balance.Amount {\n\tnumerator := big.NewInt(0).Mul(totalRewards.BigInt(), validatorPower)\n\treward := balance.NewAmountFromBigInt(big.NewInt(0).Div(numerator, totalPower))\n\treturn reward\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientSession) RewardsDistribution() (common.Address, error) {\n\treturn _RewardsDistributionRecipient.Contract.RewardsDistribution(&_RewardsDistributionRecipient.CallOpts)\n}", "func (k Keeper) DeleteReward(ctx sdk.Context, stakingCoinDenom string, farmerAcc sdk.AccAddress) {\n\tstore := ctx.KVStore(k.storeKey)\n\tstore.Delete(types.GetRewardKey(stakingCoinDenom, farmerAcc))\n\tstore.Delete(types.GetRewardByFarmerAndStakingCoinDenomIndexKey(farmerAcc, stakingCoinDenom))\n}", "func (d *Dao) UseReward(id int64, usePlat string) (rst bool, err error) {\n\tif err := d.orm.\n\t\tModel(&model.AnchorReward{}).\n\t\tWhere(\"id=?\", id).\n\t\tUpdate(map[string]interface{}{\"status\": model.RewardUsed, \"use_plat\": usePlat, \"use_time\": xtime.Time(time.Now().Unix())}).Error; err != nil {\n\t\tlog.Error(\"useReward (%v) error(%v)\", id, err)\n\t\treturn rst, err\n\t}\n\trst = true\n\treturn\n}", "func (b *EpsilonGreedy) Update(arm, reward int) {\n\t// Update the frequency\n\tb.counts[arm]++\n\tn := float64(b.counts[arm])\n\n\tvalue := b.values[arm]\n\tb.values[arm] = ((n-1)/n)*value + (1/n)*float64(reward)\n}", "func (k Keeper) ClaimUSDXMintingReward(ctx sdk.Context, owner, receiver sdk.AccAddress, multiplierName string) error {\n\tclaim, found := k.GetUSDXMintingClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, types.USDXMintingRewardDenom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", types.USDXMintingRewardDenom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tclaim, err := k.SynchronizeUSDXMintingClaim(ctx, claim)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trewardAmount := sdk.NewDecFromInt(claim.Reward.Amount).Mul(multiplier.Factor).RoundInt()\n\tif rewardAmount.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\trewardCoin := sdk.NewCoin(claim.Reward.Denom, rewardAmount)\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, sdk.NewCoins(rewardCoin), length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tk.ZeroUSDXMintingClaim(ctx, claim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claim.Reward.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, claim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientTransactor) SetRewardsDistribution(opts *bind.TransactOpts, _rewardsDistribution common.Address) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.contract.Transact(opts, \"setRewardsDistribution\", _rewardsDistribution)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientCallerSession) RewardsDistribution() (common.Address, error) {\n\treturn _RewardsDistributionRecipient.Contract.RewardsDistribution(&_RewardsDistributionRecipient.CallOpts)\n}", "func (s *BlocksService) Reward(ctx context.Context) (*BlocksReward, *http.Response, error) {\n\tvar responseStruct *BlocksReward\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"blocks/getReward\", nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (k Keeper) ClaimDelegatorReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tclaim, found := k.GetDelegatorClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, err := k.SynchronizeDelegatorClaim(ctx, claim)\n\tif err != nil {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetDelegatorClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func MeanReward(r []*Rollout) float64 {\n\tvar sum float64\n\tfor _, x := range r {\n\t\tsum += x.Reward\n\t}\n\treturn sum / float64(len(r))\n}", "func (_Token *TokenSession) SetupRewards(multiplier *big.Int, anualRewardRates []*big.Int, lowerBounds []*big.Int, upperBounds []*big.Int) (*types.Transaction, error) {\n\treturn _Token.Contract.SetupRewards(&_Token.TransactOpts, multiplier, anualRewardRates, lowerBounds, upperBounds)\n}", "func (_Token *TokenTransactorSession) SetupRewards(multiplier *big.Int, anualRewardRates []*big.Int, lowerBounds []*big.Int, upperBounds []*big.Int) (*types.Transaction, error) {\n\treturn _Token.Contract.SetupRewards(&_Token.TransactOpts, multiplier, anualRewardRates, lowerBounds, upperBounds)\n}", "func (_Token *TokenSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (_Token *TokenCallerSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (q querier) RewardWeight(c context.Context, req *types.QueryRewardWeightRequest) (*types.QueryRewardWeightResponse, error) {\n\tctx := sdk.UnwrapSDKContext(c)\n\treturn &types.QueryRewardWeightResponse{RewardWeight: q.GetRewardWeight(ctx)}, nil\n}", "func (_XStaking *XStakingCaller) Rewards(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewards\", arg0)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (as AccountStorage) SetReward(ctx sdk.Context, accKey types.AccountKey, reward *Reward) sdk.Error {\n\tstore := ctx.KVStore(as.key)\n\trewardByte, err := as.cdc.MarshalJSON(*reward)\n\tif err != nil {\n\t\treturn ErrFailedToMarshalReward(err)\n\t}\n\tstore.Set(getRewardKey(accKey), rewardByte)\n\treturn nil\n}", "func (c RewardsController) CollectReward(id string) revel.Result {\n\tif !c.GetCurrentUser() {\n\t\treturn c.ForbiddenResponse()\n\t}\n\n\tif !bson.IsObjectIdHex(id) {\n\t\treturn c.ErrorResponse(nil, c.Message(\"error.invalid\", \"\"), core.ModelStatus[core.StatusInvalidID])\n\t}\n\n\tvar selector = []bson.M{\n\t\tbson.M{\"user_id\": c.CurrentUser.GetID().Hex()},\n\t\tbson.M{\"_id\": id},\n\t\tbson.M{\"multi\": false},\n\t}\n\tvar query = bson.M{\"$set\": []bson.M{\n\t\tbson.M{\"status.name\": core.StatusObtained},\n\t\tbson.M{\"status.code\": core.ValidationStatus[core.StatusObtained]},\n\t}}\n\n\t// Get pending Rewards for the user\n\tif Reward, ok := app.Mapper.GetModel(&models.Reward{}); ok {\n\t\tif err := Reward.UpdateQuery(selector, query, false); err != nil {\n\t\t\trevel.ERROR.Print(\"ERROR Find\")\n\t\t\treturn c.ErrorResponse(err, err.Error(), 400)\n\t\t}\n\t\treturn c.SuccessResponse(bson.M{\"data\": \"Reward collected successfully\"}, \"success\", core.ModelsType[core.ModelSimpleResponse], nil)\n\t}\n\n\treturn c.ServerErrorResponse()\n}", "func (b *AnnealingEpsilonGreedy) Update(arm, reward int) {\n\t// Update the frequency\n\tb.counts[arm]++\n\tn := float64(b.counts[arm])\n\n\tvalue := b.values[arm]\n\tb.values[arm] = ((n-1)/n)*value + (1/n)*float64(reward)\n}", "func GetReward(a Action, feedback Action) float64 {\n\tif a == feedback {\n\t\treturn 1\n\t}\n\treturn -1\n}", "func ViewReward(rw http.ResponseWriter, r *http.Request) {\n\t// get the token\n\treqToken := r.Header.Get(\"Authorization\")\n\t\n\t// get the claims\n\tclaims, isNotValid := GetClaims(reqToken, rw)\n\tif isNotValid {\n\t\treturn\n\t}\n\n\tdt, err := db.GetUserRewards(claims.Roll)\n\tif err != nil {\n\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\trw.Write(Rsp(err.Error(), \"Server Error\"))\n\t\treturn\n\t}\n\trw.WriteHeader(http.StatusOK)\n\tres := c.RespData{\n\t\tMessage: \"All data\",\n\t\tData: dt,\n\t}\n\tjson.NewEncoder(rw).Encode(res)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepFilterer) WatchETHRewardDistributed(opts *bind.WatchOpts, sink chan<- *BondedECDSAKeepETHRewardDistributed) (event.Subscription, error) {\n\n\tlogs, sub, err := _BondedECDSAKeep.contract.WatchLogs(opts, \"ETHRewardDistributed\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(BondedECDSAKeepETHRewardDistributed)\n\t\t\t\tif err := _BondedECDSAKeep.contract.UnpackLog(event, \"ETHRewardDistributed\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}", "func (k Keeper) DistributeSavingsRate(ctx sdk.Context, debtDenom string) error {\n\tdp, found := k.GetDebtParam(ctx, debtDenom)\n\tif !found {\n\t\treturn sdkerrors.Wrap(types.ErrDebtNotSupported, debtDenom)\n\t}\n\tsavingsRateMacc := k.supplyKeeper.GetModuleAccount(ctx, types.SavingsRateMacc)\n\tsurplusToDistribute := savingsRateMacc.GetCoins().AmountOf(dp.Denom)\n\tif surplusToDistribute.IsZero() {\n\t\treturn nil\n\t}\n\n\tmodAccountCoins := k.getModuleAccountCoins(ctx, dp.Denom)\n\ttotalSupplyLessModAccounts := k.supplyKeeper.GetSupply(ctx).GetTotal().Sub(modAccountCoins)\n\tsurplusDistributed := sdk.ZeroInt()\n\tvar iterationErr error\n\tk.accountKeeper.IterateAccounts(ctx, func(acc authexported.Account) (stop bool) {\n\t\t_, ok := acc.(supplyexported.ModuleAccountI)\n\t\tif ok {\n\t\t\t// don't distribute savings rate to module accounts\n\t\t\treturn false\n\t\t}\n\t\tdebtAmount := acc.GetCoins().AmountOf(debtDenom)\n\t\tif !debtAmount.IsPositive() {\n\t\t\treturn false\n\t\t}\n\t\t// (balance * rewardToDisribute) / totalSupply\n\t\t// interest is the ratable fraction of savings rate owed to that account, rounded using bankers rounding\n\t\tinterest := (sdk.NewDecFromInt(debtAmount).Mul(sdk.NewDecFromInt(surplusToDistribute))).Quo(sdk.NewDecFromInt(totalSupplyLessModAccounts.AmountOf(debtDenom))).RoundInt()\n\t\t// sanity check, if we are going to over-distribute due to rounding, distribute only the remaining savings rate that hasn't been distributed.\n\t\tif interest.GT(surplusToDistribute.Sub(surplusDistributed)) {\n\t\t\tinterest = surplusToDistribute.Sub(surplusDistributed)\n\t\t}\n\t\t// sanity check - don't send saving rate if the rounded amount is zero\n\t\tif !interest.IsPositive() {\n\t\t\treturn false\n\t\t}\n\t\tinterestCoins := sdk.NewCoins(sdk.NewCoin(debtDenom, interest))\n\t\terr := k.supplyKeeper.SendCoinsFromModuleToAccount(ctx, types.SavingsRateMacc, acc.GetAddress(), interestCoins)\n\t\tif err != nil {\n\t\t\titerationErr = err\n\t\t\treturn true\n\t\t}\n\t\tsurplusDistributed = surplusDistributed.Add(interest)\n\t\treturn false\n\t})\n\treturn iterationErr\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientTransactorSession) SetRewardsDistribution(_rewardsDistribution common.Address) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.SetRewardsDistribution(&_RewardsDistributionRecipient.TransactOpts, _rewardsDistribution)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.RewardsDistributionRecipientTransactor.contract.Transfer(opts)\n}", "func (_RandomBeacon *RandomBeaconCaller) RewardParameters(opts *bind.CallOpts) (struct {\n\tSortitionPoolRewardsBanDuration *big.Int\n\tRelayEntryTimeoutNotificationRewardMultiplier *big.Int\n\tUnauthorizedSigningNotificationRewardMultiplier *big.Int\n\tDkgMaliciousResultNotificationRewardMultiplier *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _RandomBeacon.contract.Call(opts, &out, \"rewardParameters\")\n\n\toutstruct := new(struct {\n\t\tSortitionPoolRewardsBanDuration *big.Int\n\t\tRelayEntryTimeoutNotificationRewardMultiplier *big.Int\n\t\tUnauthorizedSigningNotificationRewardMultiplier *big.Int\n\t\tDkgMaliciousResultNotificationRewardMultiplier *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.SortitionPoolRewardsBanDuration = *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\toutstruct.RelayEntryTimeoutNotificationRewardMultiplier = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\toutstruct.UnauthorizedSigningNotificationRewardMultiplier = *abi.ConvertType(out[2], new(*big.Int)).(**big.Int)\n\toutstruct.DkgMaliciousResultNotificationRewardMultiplier = *abi.ConvertType(out[3], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (k Keeper) ClaimHardReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tk.SynchronizeHardLiquidityProviderClaim(ctx, owner)\n\n\tsyncedClaim, found := k.GetHardLiquidityProviderClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetHardLiquidityProviderClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func ValidateRewardTx(tx *types.Transaction, header *types.BlockHeader) error {\n\tif tx.Data.Type != types.TxTypeReward || !tx.Data.From.IsEmpty() || tx.Data.AccountNonce != 0 || tx.Data.GasPrice.Cmp(common.Big0) != 0 || tx.Data.GasLimit != 0 || len(tx.Data.Payload) != 0 {\n\t\treturn errInvalidReward\n\t}\n\n\t// validate to address\n\tto := tx.Data.To\n\tif to.IsEmpty() {\n\t\treturn errEmptyToAddress\n\t}\n\n\tif !to.Equal(header.Creator) {\n\t\treturn errCoinbaseMismatch\n\t}\n\n\t// validate reward\n\tamount := tx.Data.Amount\n\tif err := validateReward(amount); err != nil {\n\t\treturn err\n\t}\n\n\treward := consensus.GetReward(header.Height)\n\tif reward == nil || reward.Cmp(amount) != 0 {\n\t\treturn fmt.Errorf(\"invalid reward Amount, block height %d, want %s, got %s\", header.Height, reward, amount)\n\t}\n\n\t// validate timestamp\n\tif tx.Data.Timestamp != header.CreateTimestamp.Uint64() {\n\t\treturn errTimestampMismatch\n\t}\n\n\treturn nil\n}", "func (me *XsdGoPkgHasElem_RewardsequenceCreateHITRequestschema_Reward_TPrice_) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_RewardsequenceCreateHITRequestschema_Reward_TPrice_; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.Reward.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (_Token *TokenTransactor) SetupRewards(opts *bind.TransactOpts, multiplier *big.Int, anualRewardRates []*big.Int, lowerBounds []*big.Int, upperBounds []*big.Int) (*types.Transaction, error) {\n\treturn _Token.contract.Transact(opts, \"setupRewards\", multiplier, anualRewardRates, lowerBounds, upperBounds)\n}", "func (cra clawbackRewardAction) ProcessReward(ctx sdk.Context, reward sdk.Coins, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported, \"expected *ClawbackVestingAccount, got %T\", rawAccount)\n\t}\n\tcva.postReward(ctx, reward, cra.ak, cra.bk, cra.sk)\n\treturn nil\n}", "func (d *ClampedRandomWalkDistribution) Advance() {\n\td.Step.Advance()\n\td.State += d.Step.Get()\n\tif d.State > d.Max {\n\t\td.State = d.Max\n\t}\n\tif d.State < d.Min {\n\t\td.State = d.Min\n\t}\n}", "func (_XStaking *XStakingTransactorSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.NotifyRewardAmount(&_XStaking.TransactOpts, reward)\n}", "func (_XStaking *XStakingFilterer) WatchRewardPaid(opts *bind.WatchOpts, sink chan<- *XStakingRewardPaid, user []common.Address) (event.Subscription, error) {\n\n\tvar userRule []interface{}\n\tfor _, userItem := range user {\n\t\tuserRule = append(userRule, userItem)\n\t}\n\n\tlogs, sub, err := _XStaking.contract.WatchLogs(opts, \"RewardPaid\", userRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(XStakingRewardPaid)\n\t\t\t\tif err := _XStaking.contract.UnpackLog(event, \"RewardPaid\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}", "func (c *DPOS) ClaimRewardsFromAllValidators(ctx contract.Context, req *ClaimDelegatorRewardsRequest) (*ClaimDelegatorRewardsResponse, error) {\n\tif ctx.FeatureEnabled(features.DPOSVersion3_6, false) {\n\t\treturn c.claimRewardsFromAllValidators2(ctx, req)\n\t}\n\n\tdelegator := ctx.Message().Sender\n\tvalidators, err := ValidatorList(ctx)\n\tif err != nil {\n\t\treturn nil, logStaticDposError(ctx, err, req.String())\n\t}\n\n\ttotal := big.NewInt(0)\n\tchainID := ctx.Block().ChainID\n\tvar claimedFromValidators []*types.Address\n\tvar amounts []*types.BigUInt\n\tfor _, v := range validators {\n\t\tvalAddress := loom.Address{ChainID: chainID, Local: loom.LocalAddressFromPublicKey(v.PubKey)}\n\t\tdelegation, err := GetDelegation(ctx, REWARD_DELEGATION_INDEX, *valAddress.MarshalPB(), *delegator.MarshalPB())\n\t\tif err == contract.ErrNotFound {\n\t\t\t// Skip reward delegations that were not found.\n\t\t\tctx.Logger().Error(\"DPOS ClaimRewardsFromAllValidators\", \"error\", err, \"delegator\", delegator)\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to load delegation\")\n\t\t}\n\n\t\tclaimedFromValidators = append(claimedFromValidators, valAddress.MarshalPB())\n\t\tamounts = append(amounts, delegation.Amount)\n\n\t\t// Set to UNBONDING and UpdateAmount == Amount, to fully unbond it.\n\t\tdelegation.State = UNBONDING\n\t\tdelegation.UpdateAmount = delegation.Amount\n\n\t\tif err := SetDelegation(ctx, delegation); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to update delegation\")\n\t\t}\n\n\t\terr = c.emitDelegatorUnbondsEvent(ctx, delegation)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Add to the sum\n\t\ttotal.Add(total, delegation.Amount.Value.Int)\n\t}\n\n\tamount := &types.BigUInt{Value: *loom.NewBigUInt(total)}\n\n\terr = c.emitDelegatorClaimsRewardsEvent(ctx, delegator.MarshalPB(), claimedFromValidators, amounts, amount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ClaimDelegatorRewardsResponse{\n\t\tAmount: amount,\n\t}, nil\n}", "func (_Lmc *LmcCaller) RewardPerBlock(opts *bind.CallOpts, arg0 *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Lmc.contract.Call(opts, &out, \"rewardPerBlock\", arg0)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (d *UniformDistribution) Advance() {\n\tx := rand.Float64() // uniform\n\tx *= d.High - d.Low\n\tx += d.Low\n\td.value = x\n}", "func (_XStaking *XStakingSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.NotifyRewardAmount(&_XStaking.TransactOpts, reward)\n}", "func (policy *PolicySvc) distributePolicy(policyDoc *common.Policy) error {\n\thosts, err := policy.client.ListHosts()\n\tif err != nil {\n\t\treturn err\n\t}\n\terrStr := make([]string, 0)\n\tfor _, host := range hosts {\n\t\t// TODO make schema configurable\n\t\turl := fmt.Sprintf(\"http://%s:%d/policies\", host.Ip, host.AgentPort)\n\t\tlog.Printf(\"Sending policy %s to agent at %s\", policyDoc.Name, url)\n\t\tresult := make(map[string]interface{})\n\t\terr = policy.client.Post(url, policyDoc, &result)\n\t\tlog.Printf(\"Agent at %s returned %v\", host.Ip, result)\n\t\tif err != nil {\n\t\t\terrStr = append(errStr, fmt.Sprintf(\"Error applying policy %d to host %s: %v. \", policyDoc.ID, host.Ip, err))\n\t\t}\n\t}\n\tif len(errStr) > 0 {\n\t\treturn common.NewError500(errStr)\n\t}\n\treturn nil\n}", "func (m *MemoryRewardStorage) Update(reward rewards.Reward) {\n\tfor index, r := range m.rewards {\n\t\tif r.ID == reward.ID {\n\t\t\tm.rewards[index] = reward\n\t\t}\n\t}\n}", "func (_RandomBeacon *RandomBeaconCallerSession) RewardParameters() (struct {\n\tSortitionPoolRewardsBanDuration *big.Int\n\tRelayEntryTimeoutNotificationRewardMultiplier *big.Int\n\tUnauthorizedSigningNotificationRewardMultiplier *big.Int\n\tDkgMaliciousResultNotificationRewardMultiplier *big.Int\n}, error) {\n\treturn _RandomBeacon.Contract.RewardParameters(&_RandomBeacon.CallOpts)\n}", "func playAndDistribute(ctx coretypes.Sandbox) error {\n\tctx.Event(\"playAndDistribute\")\n\n\tscAddr := coretypes.NewAgentIDFromContractID(ctx.ContractID())\n\tif ctx.Caller() != scAddr {\n\t\t// ignore if request is not from itself\n\t\treturn fmt.Errorf(\"playAndDistribute from the wrong sender\")\n\t}\n\tstate := ctx.State()\n\n\tlockedBetsArray := collections.NewArray(state, StateVarLockedBets)\n\tnumLockedBets := lockedBetsArray.MustLen()\n\tif numLockedBets == 0 {\n\t\t// nothing to play. Should not happen\n\t\treturn fmt.Errorf(\"internal error. Nothing to play\")\n\t}\n\n\t// take the entropy from the signing of the locked bets\n\t// it was saved by some 'place bet' request or otherwise it is taken from\n\t// the current context\n\tentropy, ok, _ := codec.DecodeHashValue(state.MustGet(StateVarEntropyFromLocking))\n\tif !ok {\n\t\th := ctx.GetEntropy()\n\t\tentropy = &h\n\t}\n\n\t// 'playing the wheel' means taking first 8 bytes of the entropy as uint64 number and\n\t// calculating it modulo NumColors.\n\twinningColor := byte(util.MustUint64From8Bytes(entropy[:8]) % NumColors)\n\tctx.State().Set(StateVarLastWinningColor, codec.EncodeInt64(int64(winningColor)))\n\n\tctx.Event(fmt.Sprintf(\"$$$$$$$$$$ winning color is = %d\", winningColor))\n\n\taddToWinsPerColor(ctx, winningColor)\n\n\t// take locked bets from the array\n\ttotalLockedAmount := int64(0)\n\tlockedBets := make([]*BetInfo, numLockedBets)\n\tfor i := range lockedBets {\n\t\tbi, err := DecodeBetInfo(lockedBetsArray.MustGetAt(uint16(i)))\n\t\tif err != nil {\n\t\t\t// inconsistency. Even more sad\n\t\t\tpanic(err)\n\t\t}\n\t\ttotalLockedAmount += bi.Sum\n\t\tlockedBets[i] = bi\n\t}\n\n\tctx.Event(fmt.Sprintf(\"$$$$$$$$$$ totalLockedAmount = %d\", totalLockedAmount))\n\n\t// select bets on winning Color\n\twinningBets := lockedBets[:0] // same underlying array\n\tfor _, bet := range lockedBets {\n\t\tif bet.Color == winningColor {\n\t\t\twinningBets = append(winningBets, bet)\n\t\t}\n\t}\n\n\tctx.Event(fmt.Sprintf(\"$$$$$$$$$$ winningBets: %d\", len(winningBets)))\n\n\t// locked bets neither entropy are not needed anymore\n\tlockedBetsArray.MustErase()\n\tstate.Del(StateVarEntropyFromLocking)\n\n\tif len(winningBets) == 0 {\n\n\t\tctx.Event(fmt.Sprintf(\"$$$$$$$$$$ nobody wins: amount of %d stays in the smart contract\", totalLockedAmount))\n\n\t\t// nobody played on winning Color -> all sums stay in the smart contract\n\t\t// move tokens to itself.\n\t\t// It is not necessary because all tokens are in the own account anyway.\n\t\t// However, it is healthy to compress number of outputs in the address\n\n\t\t//agent := coretypes.NewAgentIDFromContractID(ctx.ContractID())\n\t\t//if !ctx.MoveTokens(agent, balance.ColorIOTA, totalLockedAmount) {\n\t\t//\t// inconsistency. A disaster\n\t\t//\tctx.Event(fmt.Sprintf(\"$$$$$$$$$$ something went wrong 1\"))\n\t\t//\tctx.Log().Panicf(\"MoveTokens failed\")\n\t\t//}\n\t}\n\n\t// distribute total staked amount to players\n\tif !distributeLockedAmount(ctx, winningBets, totalLockedAmount) {\n\t\tctx.Event(fmt.Sprintf(\"$$$$$$$$$$ something went wrong 2\"))\n\t\tctx.Log().Panicf(\"distributeLockedAmount failed\")\n\t}\n\n\tfor _, betInfo := range winningBets {\n\t\terr := withPlayerStats(ctx, &betInfo.Player, func(ps *PlayerStats) {\n\t\t\tps.Wins += 1\n\t\t})\n\t\tif err != nil {\n\t\t\tctx.Log().Panicf(\"%v\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func (_BondedECDSAKeep *BondedECDSAKeepFilterer) FilterETHRewardDistributed(opts *bind.FilterOpts) (*BondedECDSAKeepETHRewardDistributedIterator, error) {\n\n\tlogs, sub, err := _BondedECDSAKeep.contract.FilterLogs(opts, \"ETHRewardDistributed\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BondedECDSAKeepETHRewardDistributedIterator{contract: _BondedECDSAKeep.contract, event: \"ETHRewardDistributed\", logs: logs, sub: sub}, nil\n}", "func (k Keeper) DistributeDrops(ctx sdk.Context, height int64, DistributionName string, runner sdk.AccAddress, distributionType types.DistributionType) (types.DistributionRecords, error) {\n\t// TODO replace 10 with a variable declared in genesis or a constant in keys.go.\n\tpendingRecords := k.GetRecordsForNamePendingLimited(ctx, DistributionName, 10, runner, distributionType)\n\tfor _, record := range pendingRecords {\n\t\terr := k.GetSupplyKeeper().SendCoinsFromModuleToAccount(ctx, types.ModuleName, record.RecipientAddress, record.Coins)\n\t\tif err != nil {\n\t\t\terr := errors.Wrapf(err, \"Distribution failed for address : %s\", record.RecipientAddress.String())\n\t\t\tctx.Logger().Error(err.Error())\n\t\t\terr = k.MoveRecordToFailed(ctx, record)\n\t\t\tif err != nil {\n\t\t\t\treturn pendingRecords, errors.Wrapf(err, \"Unable to set Distribution Records to Failed : %s\", record.String())\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\trecord.DistributionStatus = types.Completed\n\t\trecord.DistributionCompletedHeight = height\n\t\terr = k.SetDistributionRecord(ctx, record)\n\t\tif err != nil {\n\t\t\terr := errors.Wrapf(types.ErrFailedOutputs, \"error setting distibution record : %s\", record.String())\n\t\t\tctx.Logger().Error(err.Error())\n\t\t\t// If the SetDistributionRecord returns error , that would mean the required amount was transferred to the user , but the record was not set to completed .\n\t\t\t// In this case we try to take the funds back from the user , and attempt the withdrawal later .\n\t\t\terr = k.GetSupplyKeeper().SendCoinsFromAccountToModule(ctx, record.RecipientAddress, types.ModuleName, record.Coins)\n\t\t\tif err != nil {\n\t\t\t\treturn pendingRecords, errors.Wrapf(err, \"Unable to set Distribution Records to completed : %s\", record.String())\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t// Use record details to delete associated claim\n\t\t// The claim should always be locked at this point in time .\n\t\tif record.DoesClaimExist() {\n\t\t\tk.DeleteClaim(ctx, record.RecipientAddress.String(), record.DistributionType)\n\t\t}\n\t\tctx.Logger().Info(fmt.Sprintf(\"Distributed to : %s | At height : %d | Amount :%s \\n\", record.RecipientAddress.String(), height, record.Coins.String()))\n\t}\n\treturn pendingRecords, nil\n}", "func bindRewardsDistributionRecipient(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) {\n\tparsed, err := abi.JSON(strings.NewReader(RewardsDistributionRecipientABI))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil\n}", "func NewRewardTx(coinbase common.Address, reward *big.Int, timestamp uint64) (*types.Transaction, error) {\n\tif err := validateReward(reward); err != nil {\n\t\treturn nil, err\n\t}\n\n\ttxData := types.TransactionData{\n\t\tType: types.TxTypeReward,\n\t\tFrom: common.EmptyAddress,\n\t\tTo: coinbase,\n\t\tAmount: new(big.Int).Set(reward),\n\t\tGasPrice: common.Big0,\n\t\tTimestamp: timestamp,\n\t\tPayload: emptyPayload,\n\t}\n\n\ttx := types.Transaction{\n\t\tHash: crypto.MustHash(txData),\n\t\tData: txData,\n\t\tSignature: emptySig,\n\t}\n\n\treturn &tx, nil\n}", "func (_Smartchef *SmartchefCaller) RewardPerBlock(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Smartchef.contract.Call(opts, out, \"rewardPerBlock\")\n\treturn *ret0, err\n}", "func (_XStaking *XStakingFilterer) FilterRewardPaid(opts *bind.FilterOpts, user []common.Address) (*XStakingRewardPaidIterator, error) {\n\n\tvar userRule []interface{}\n\tfor _, userItem := range user {\n\t\tuserRule = append(userRule, userItem)\n\t}\n\n\tlogs, sub, err := _XStaking.contract.FilterLogs(opts, \"RewardPaid\", userRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &XStakingRewardPaidIterator{contract: _XStaking.contract, event: \"RewardPaid\", logs: logs, sub: sub}, nil\n}", "func (rig *testRig) redeem_taker(checkStatus bool) error {\n\tmatchInfo := rig.matchInfo\n\tmatchInfo.db.takerRedeem = rig.redeem(matchInfo.taker, matchInfo.takerOID)\n\ttracker := rig.getTracker()\n\t// Check the match status\n\tif checkStatus {\n\t\tif tracker != nil {\n\t\t\treturn fmt.Errorf(\"expected match to be removed, found it, in status %v\", tracker.Status)\n\t\t}\n\t\terr := rig.checkResponse(matchInfo.taker, \"redeem\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (d *MonotonicRandomWalkDistribution) Advance() {\n\td.Step.Advance()\n\td.State += math.Abs(d.Step.Get())\n}" ]
[ "0.6758821", "0.64290905", "0.6397762", "0.63100404", "0.60241735", "0.59990525", "0.59793544", "0.5928813", "0.585137", "0.57938814", "0.5633375", "0.5522693", "0.54059565", "0.537793", "0.5369064", "0.5322376", "0.5290096", "0.52899516", "0.5289859", "0.52838886", "0.5282563", "0.5234018", "0.5166412", "0.5163699", "0.51494277", "0.5144747", "0.50842685", "0.50770324", "0.5039137", "0.50101125", "0.49886718", "0.4988388", "0.49669877", "0.49592102", "0.4948811", "0.494178", "0.49381617", "0.493457", "0.49325964", "0.49171472", "0.48805666", "0.48743045", "0.48628837", "0.48465478", "0.48309922", "0.4829738", "0.4823581", "0.48001027", "0.4750146", "0.47495374", "0.47492865", "0.47134227", "0.46927372", "0.46913937", "0.46752006", "0.466761", "0.46651492", "0.46616465", "0.46527112", "0.46466953", "0.4635468", "0.4629587", "0.46258375", "0.462531", "0.46225235", "0.46146473", "0.46126884", "0.46081883", "0.46007314", "0.45919257", "0.45816714", "0.45802513", "0.45751968", "0.45697722", "0.4567867", "0.45586684", "0.45576894", "0.4543228", "0.45253262", "0.45234728", "0.4519767", "0.45107132", "0.4508761", "0.44949284", "0.44897395", "0.44887808", "0.4485532", "0.4482852", "0.44771755", "0.44762224", "0.44708928", "0.44706833", "0.4467554", "0.44598237", "0.44569808", "0.44539884", "0.44505754", "0.44497564", "0.44492695", "0.44488573" ]
0.7879191
0
scaleCoins scales the given coins, rounding down.
func scaleCoins(coins sdk.Coins, scale sdk.Dec) sdk.Coins { scaledCoins := sdk.NewCoins() for _, coin := range coins { amt := coin.Amount.ToDec().Mul(scale).TruncateInt() // round down scaledCoins = scaledCoins.Add(sdk.NewCoin(coin.Denom, amt)) } return scaledCoins }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (blk *Block) Scale(sx, sy float64) {\n\tops := contentstream.NewContentCreator().\n\t\tScale(sx, sy).\n\t\tOperations()\n\n\t*blk.contents = append(*ops, *blk.contents...)\n\tblk.contents.WrapIfNeeded()\n\n\tblk.width *= sx\n\tblk.height *= sy\n}", "func (k Keeper) MintCoins(ctx sdk.Context, newCoins sdk.Coins) error {\n\tif newCoins.Empty() {\n\t\t// skip as no coins need to be minted\n\t\treturn nil\n\t}\n\treturn k.supplyKeeper.MintCoins(ctx, types.ModuleName, newCoins)\n}", "func (c *LinehaulCostComputation) Scale(factor float64) {\n\tc.BaseLinehaul = c.BaseLinehaul.MultiplyFloat64(factor)\n\tc.OriginLinehaulFactor = c.OriginLinehaulFactor.MultiplyFloat64(factor)\n\tc.DestinationLinehaulFactor = c.DestinationLinehaulFactor.MultiplyFloat64(factor)\n\tc.ShorthaulCharge = c.ShorthaulCharge.MultiplyFloat64(factor)\n\tc.LinehaulChargeTotal = c.LinehaulChargeTotal.MultiplyFloat64(factor)\n}", "func scale(dst *block, src *[4]block) {\n\tfor i := 0; i < 4; i++ {\n\t\tdstOff := (i&2)<<4 | (i&1)<<2\n\t\tfor y := 0; y < 4; y++ {\n\t\t\tfor x := 0; x < 4; x++ {\n\t\t\t\tj := 16*y + 2*x\n\t\t\t\tsum := src[i][j] + src[i][j+1] + src[i][j+8] + src[i][j+9]\n\t\t\t\tdst[8*y+x+dstOff] = (sum + 2) >> 2\n\t\t\t}\n\t\t}\n\t}\n}", "func scale(val float64, min float64, max float64, outMin float64, outMax float64) float64 {\r\n\tdenom := 1.0\r\n\ty := 0.0\r\n\tif outMin - min != 0 {\r\n\t\tdenom = outMin - min\r\n\t\ty = (outMax - max) / denom * val - min + outMin\r\n\t} else {\r\n\t\ty = outMax / max * val - min + outMin\r\n\t}\r\n\treturn y\r\n}", "func (canvas *Canvas) Scale(x, y float32) {\n\twriteCommand(canvas.contents, \"cm\", x, 0, 0, y, 0, 0)\n}", "func ScaleRecipe(amounts []float64, portions int) []float64 {\n\tscale := float64(portions) / 2.0\n\tscaledAmounts := make([]float64, len(amounts))\n\tfor ingredient, amount := range amounts {\n\t\tscaledAmounts[ingredient] = amount * scale\n\t}\n\treturn scaledAmounts\n}", "func Scale(zoom float64) float64 {\n\treturn 256 * math.Pow(2, zoom)\n}", "func (v Vector) Scale(c float64) Vector {\n\tfor i, x := range v {\n\t\tv[i] = x * c\n\t}\n\treturn v\n}", "func (s SamplesC64) Scale(r float32) {\n\tsimd.ScaleComplex(r, s)\n}", "func scale(bytes int64) (scaled int64, scale string) {\n\tif bytes < 0 {\n\t\tscaled, scale = uscale(uint64(bytes * -1))\n\t\tscaled *= -1\n\t} else {\n\t\tscaled, scale = uscale(uint64(bytes))\n\t}\n\treturn\n}", "func (keeper Keeper) SetCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) sdk.Error {\n\treturn setCoins(ctx, keeper.am, addr, amt)\n}", "func (c *Circle) Scale(f float64) {\n\tc.radius *= f\n}", "func (c Charset) Scale(factor int) {\n\tif factor <= 1 {\n\t\t// A factor of zero results in zero-sized glyphs and\n\t\t// is therefore not valid. A factor of 1 does not change\n\t\t// the glyphs, so we can ignore it.\n\t\treturn\n\t}\n\n\t// Multiply each glyph field by the given factor\n\t// to scale them up to the new size.\n\tfor i := range c {\n\t\tc[i].X *= factor\n\t\tc[i].Y *= factor\n\t\tc[i].Width *= factor\n\t\tc[i].Height *= factor\n\t\tc[i].Advance *= factor\n\t}\n}", "func (m *mover) EarnCoins(tx *TX, limits, coins map[string]int) error {\n\tbank, err := tx.GetCoins()\n\tif err != nil {\n\t\treturn err\n\t}\n\tpurse, err := tx.GetPlayerCoins(m.userID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor color, limit := range limits {\n\t\tif bank[color] < limit {\n\t\t\treturn ErrInsufficientCoins\n\t\t}\n\t}\n\n\tnewbank := map[string]int{}\n\tnewpurse := map[string]int{}\n\n\tfor color, count := range coins {\n\t\tnewbank[color] = bank[color] - count\n\t\tnewpurse[color] = purse[color] + count\n\t}\n\n\tif err := tx.UpdateCoins(newbank); err != nil {\n\t\treturn err\n\t}\n\tif err := tx.UpdatePlayerCoins(m.userID, newpurse); err != nil {\n\t\treturn err\n\t}\n\n\t// TODO: If player has more than 10 coins now, make then give some back.\n\n\treturn nil\n}", "func (v *Vector) ScaleTo(s float64) {\n\tv.X = s * v.X\n\tv.Y = s * v.Y\n\tv.Z = s * v.Z\n}", "func Scale(A float64, x *Matrix) (*Matrix, error) {\n\tout, _ := New(x.RowCount, x.ColCount, nil)\n\n\tfor rowID := 0; rowID < x.RowCount; rowID++ {\n\t\tfor colID := 0; colID < x.ColCount; colID++ {\n\t\t\tout.Matrix[rowID][colID] = A * x.Matrix[rowID][colID]\n\t\t}\n\t}\n\n\treturn out, nil\n}", "func intScale(val int, val_range int, out_range int) int {\n\tnum := val*(out_range-1)*2 + (val_range - 1)\n\tdem := (val_range - 1) * 2\n\treturn num / dem\n}", "func (dw *DrawingWand) Scale(x, y float64) {\n\tC.MagickDrawScale(dw.dw, C.double(x), C.double(y))\n}", "func (t *Transform) Scale(sx, sy float64) {\n\tout := fmt.Sprintf(\"scale(%g,%g)\", sx, sy)\n\n\tt.transforms = append(t.transforms, out)\n}", "func (c2d *C2DMatrix) Scale(xScale, yScale float64) {\n\tvar mat Matrix\n\n\tmat.m11 = xScale\n\tmat.m12 = 0\n\tmat.m13 = 0\n\n\tmat.m21 = 0\n\tmat.m22 = yScale\n\tmat.m23 = 0\n\n\tmat.m31 = 0\n\tmat.m32 = 0\n\tmat.m33 = 1\n\n\t//and multiply\n\tc2d.MatrixMultiply(mat)\n}", "func (q1 Quat) Scale(c float32) Quat {\n\treturn Quat{q1.W * c, Vec3{q1.V[0] * c, q1.V[1] * c, q1.V[2] * c}}\n}", "func (wv *Spectrum) Scale(s float32) {\n\twv.C[0] *= s\n\twv.C[1] *= s\n\twv.C[2] *= s\n\twv.C[3] *= s\n}", "func Change(money int, coins []int) int {\n\tminNumCoins := make([]int, money+1)\n\n\t// range over all relevant values of k\n\tfor k := 1; k <= money; k++ {\n\t\t// take minimum of all relevant values at each step\n\t\tvar currentMin int\n\t\tfor i := range coins {\n\t\t\t// make sure that current coin isn't too big\n\t\t\tif k-coins[i] >= 0 {\n\t\t\t\tif minNumCoins[k-coins[i]] == 0 && k-coins[i] != 0 {\n\t\t\t\t\tpanic(\"Bad\")\n\t\t\t\t}\n\t\t\t\t//we're OK\n\t\t\t\tif i == 0 || minNumCoins[k-coins[i]] < currentMin {\n\t\t\t\t\tcurrentMin = minNumCoins[k-coins[i]]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// update my minNumCoins[k] value\n\t\tminNumCoins[k] = currentMin + 1\n\t}\n\n\treturn minNumCoins[money]\n}", "func ScaleResources(resourceName corev1.ResourceName, quantity *resource.Quantity, factor float32) {\n\tswitch resourceName {\n\tcase corev1.ResourceCPU:\n\t\t// use millis\n\t\tquantity.SetScaled(int64(float32(quantity.MilliValue())*factor), resource.Milli)\n\tcase corev1.ResourceMemory:\n\t\t// use mega\n\t\tquantity.SetScaled(int64(float32(quantity.ScaledValue(resource.Mega))*factor), resource.Mega)\n\tdefault:\n\t\tquantity.Set(int64(float32(quantity.Value()) * factor))\n\t}\n}", "func (m *Matrix3) Scale(s float64) {\n\tfor i, x := range m {\n\t\tm[i] = x * s\n\t}\n}", "func (ex *ExampleMNIST3D) scaleSprites() {\n\n\tfor i := 0; i < len(ex.sprites); i++ {\n\t\tex.sprites[i].SetScale(ex.spriteScale, ex.spriteScale, ex.spriteScale)\n\t}\n}", "func coinChange(coins []int, amount int) int {\n\tmin := func(x, y int) int {\n\t\tif x < y {\n\t\t\treturn x\n\t\t}\n\t\treturn y\n\t}\n\n\tsums := make([]int, amount+1)\n\tfor i := 1; i <= amount; i++ {\n\t\tsums[i] = math.MaxInt32\n\t\tfor j := 0; j < len(coins); j++ {\n\t\t\tif coins[j] <= i {\n\t\t\t\tsums[i] = min(sums[i], sums[i-coins[j]]+1)\n\t\t\t}\n\t\t}\n\t}\n\n\tif sums[amount] == math.MaxInt32 {\n\t\treturn -1\n\t}\n\n\treturn sums[amount]\n}", "func (dcr *ExchangeWallet) sendCoins(addr dcrutil.Address, coins asset.Coins, val, feeRate uint64, subtract bool) (*wire.MsgTx, uint64, error) {\n\tbaseTx := wire.NewMsgTx()\n\t_, err := dcr.addInputCoins(baseTx, coins)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tpayScript, err := txscript.PayToAddrScript(addr)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"error creating P2SH script: %w\", err)\n\t}\n\n\ttxOut := wire.NewTxOut(int64(val), payScript)\n\tbaseTx.AddTxOut(txOut)\n\n\tvar feeSource int32 // subtract from vout 0\n\tif !subtract {\n\t\tfeeSource = -1 // subtract from change\n\t}\n\n\ttx, _, _, _, err := dcr.sendWithReturn(baseTx, feeRate, feeSource)\n\treturn tx, uint64(txOut.Value), err\n}", "func (p *Proc) Scale(x, y float64) {\n\tp.stk.scale(x, y)\n}", "func scale(a, maxA, maxB int) float64 {\n\treturn (float64(a) / float64(maxA)) * float64(maxB) + 1\n}", "func Scale(value float64) *SimpleElement { return newSEFloat(\"scale\", value) }", "func (c *canvasRenderer) Scale(amount sprec.Vec2) {\n\tc.currentLayer.Transform = sprec.Mat4Prod(\n\t\tc.currentLayer.Transform,\n\t\tsprec.ScaleMat4(amount.X, amount.Y, 1.0),\n\t)\n}", "func coins(a int) int {\n\tif a == 0 {\n\t\treturn 0\n\t}\n\treturn doCoins(a, 25)\n}", "func (s *Simulator) FormatCoins(coins sdk.Coins) string {\n\tout := make([]string, 0, len(coins))\n\tfor _, coin := range coins {\n\t\tout = append(out, s.FormatIntDecimals(coin.Amount, s.stakingAmountDecimalsRatio)+coin.Denom)\n\t}\n\n\treturn strings.Join(out, \",\")\n}", "func (v Vec3) Scale(s float64) Vec3 {\n\treturn Vec3{v[0] * s, v[1] * s, v[2] * s}\n}", "func (dcr *ExchangeWallet) sendCoins(addr stdaddr.Address, coins asset.Coins, val, feeRate uint64, subtract bool) (*wire.MsgTx, uint64, error) {\n\tbaseTx := wire.NewMsgTx()\n\t_, err := dcr.addInputCoins(baseTx, coins)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tpayScriptVer, payScript := addr.PaymentScript()\n\ttxOut := newTxOut(int64(val), payScriptVer, payScript)\n\tbaseTx.AddTxOut(txOut)\n\n\tvar feeSource int32 // subtract from vout 0\n\tif !subtract {\n\t\tfeeSource = -1 // subtract from change\n\t}\n\n\ttx, err := dcr.sendWithReturn(baseTx, feeRate, feeSource)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\treturn tx, uint64(tx.TxOut[0].Value), err\n}", "func ratScale(x *big.Rat, exp int) {\n\tif exp < 0 {\n\t\tx.Inv(x)\n\t\tratScale(x, -exp)\n\t\tx.Inv(x)\n\t\treturn\n\t}\n\tfor exp >= 9 {\n\t\tx.Quo(x, bigRatBillion)\n\t\texp -= 9\n\t}\n\tfor exp >= 1 {\n\t\tx.Quo(x, bigRatTen)\n\t\texp--\n\t}\n}", "func generateScale(adx *header, samplesPerBlock byte, scaledSampleErrorNibbles []int32) []uint16 {\n\n\tscale := make([]uint16, adx.channelCount)\n\n\tfor i := byte(0); i < adx.channelCount; i++ {\n\n\t\t// Get max reach\n\t\tminAbsErr := scaledSampleErrorNibbles[samplesPerBlock*i+0]\n\t\tmaxAbsErr := scaledSampleErrorNibbles[samplesPerBlock*i+0]\n\t\tfor j := byte(0); j < samplesPerBlock; j++ {\n\n\t\t\tv := scaledSampleErrorNibbles[samplesPerBlock*i+j]\n\n\t\t\tif v > maxAbsErr {\n\t\t\t\tmaxAbsErr = v\n\t\t\t}\n\t\t\tif v < minAbsErr {\n\t\t\t\tminAbsErr = v\n\t\t\t}\n\t\t}\n\n\t\t// Calculate scale\n\t\tif maxAbsErr > 0 && minAbsErr < 0 {\n\t\t\tif maxAbsErr > -minAbsErr {\n\t\t\t\tscale[i] = uint16(maxAbsErr / 7)\n\t\t\t} else {\n\t\t\t\tscale[i] = uint16(minAbsErr / -8)\n\t\t\t}\n\t\t} else if minAbsErr > 0 {\n\t\t\tscale[i] = uint16(maxAbsErr / 7)\n\t\t} else if maxAbsErr < 0 {\n\t\t\tscale[i] = uint16(minAbsErr / -8)\n\t\t}\n\t}\n\n\treturn scale\n}", "func scale(v []int, x int) []int {\n\ty := make([]int, len(v))\n\tfor i := range v {\n\t\ty[i] = v[i] * x\n\t}\n\treturn y\n}", "func (ki *KernelInfo) Scale(scale float64, normalizeType KernelNormalizeType) {\n\tC.ScaleKernelInfo(ki.info, C.double(scale), C.GeometryFlags(normalizeType))\n\truntime.KeepAlive(ki)\n}", "func (dev *pwm_context) Scale(value int) error {\n\tif dev.period == -1 {\n\t\tif err := dev.ReadPeriod(); err != nil {\n\t\t\treturn fmt.Errorf(\"pwm: error running Scale: %s\", err)\n\t\t}\n\t}\n\n\tduty := (float64(value) - dev.min) / dev.span\n\tfmt.Printf(\"pwm: Scaling pin[%d] from value: %d to duty: %f\\n\", dev.pin, value, duty)\n\treturn dev.WriteDuty(int(float64(dev.period) * duty))\n}", "func (t *Tree) Scale(s float32) {\n\tif t.Leaf != nil {\n\t\tfor i, x := range t.Leaf.OutputDelta {\n\t\t\tt.Leaf.OutputDelta[i] = x * s\n\t\t}\n\t} else {\n\t\tt.Branch.FalseBranch.Scale(s)\n\t\tt.Branch.TrueBranch.Scale(s)\n\t}\n}", "func (c *nodePools) Scale(id string, req *types.NodePoolScaleRequest) (*types.NodePool, error) {\n\tpath := fmt.Sprintf(\"/v3/organizations/%s/clusters/%s/node-pools/%s\", c.organizationID, c.clusterID, id)\n\tvar out types.NodePool\n\treturn &out, c.client.Patch(path, req, &out)\n}", "func coinChange(coins []int, amount int) int {\n\tdp := make([]int, amount+1)\n\tfor i := 0; i < len(dp); i++ {\n\t\tdp[i] = amount + 1\n\t}\n\tdp[0] = 0\n\tfor i := 1; i <= amount; i++ {\n\t\tfor _, coin := range coins {\n\t\t\tif coin <= i {\n\t\t\t\tdp[i] = utils.Min(dp[i-coin]+1, dp[i])\n\t\t\t}\n\t\t}\n\t}\n\tif dp[amount] > amount {\n\t\treturn -1\n\t}\n\treturn dp[amount]\n}", "func Scale(s Frac, m M) M {\n\tm = CopyMatrix(m)\n\n\tfor r := 1; r <= m.Rows(); r++ {\n\t\tm.MultiplyRow(r, s)\n\t}\n\n\treturn m\n}", "func (v *V_elem) Scale(ofs, scale *[3]float32) *[3]int {\n\treturn &[3]int{\n\t\tint((v.x[0] + ofs[0]) * scale[0]),\n\t\tint((v.x[1] + ofs[1]) * scale[1]),\n\t\tint((v.x[2] + ofs[2]) * scale[2]),\n\t}\n}", "func (mw *MagickWand) Scale(cols, rows uint) error {\n\treturn mw.ScaleImage(cols, rows)\n}", "func Scale(w, h int) int {\n\ta := w / WIDTH\n\tb := h / HEIGHT\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Quat2Scale(out, a []float64, b float64) []float64 {\n\tout[0] = a[0] * b\n\tout[1] = a[1] * b\n\tout[2] = a[2] * b\n\tout[3] = a[3] * b\n\tout[4] = a[4] * b\n\tout[5] = a[5] * b\n\tout[6] = a[6] * b\n\tout[7] = a[7] * b\n\treturn out\n}", "func coinChange(coins []int, amount int) int {\n\t// dp[i]: The minimum changes needed for money: i.\n\tdp := make([]int, amount+1)\n\tdp[0] = 0\n\n\t// Initialize dynamic programming boundary.\n\tfor i := 1; i <= amount; i++ {\n\t\tdp[i] = amount + 1\n\t}\n\n\tfor m := 1; m <= amount; m++ {\n\t\t// Reset minChanges.\n\t\tminChanges := amount + 1\n\n\t\t// For money: m\n\t\t// dp[m] = Minimum changes needed for money: m - coins[j] + 1.\n\t\t// i.e. dp[m] = min(m - coins[j]) + 1, where j = 0 -> len(coins)-1.\n\t\tfor _, c := range coins {\n\t\t\tchange := m - c\n\n\t\t\tif change < 0 {\n\t\t\t\t// Cannot make change, continue.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Update minChanges.\n\t\t\tif dp[change] < minChanges {\n\t\t\t\tminChanges = dp[change]\n\t\t\t}\n\t\t}\n\n\t\tdp[m] = minChanges + 1\n\t}\n\n\t// Nothing can be changed, return -1.\n\tif dp[amount] > amount {\n\t\treturn -1\n\t}\n\n\treturn dp[amount]\n}", "func (s *Surface) Scale(x, y float64) {\n\ts.Ctx.Call(\"scale\", x, y)\n}", "func (blk *Block) ScaleToWidth(w float64) {\n\tratio := w / blk.width\n\tblk.Scale(ratio, ratio)\n}", "func linearScale(value, min, max float64) float64 {\n\treturn (value - min) * (1 / (max - min))\n}", "func (c *RGB) Scale(f float32) {\n\tfor k := range c {\n\t\tc[k] *= f\n\t}\n}", "func (ct *Ciphertext) SetScalingFactor(scale float64) {\n\tct.Scale = scale\n}", "func (p *point) scaleBy(factor int) {\n\tp.x *= factor\n\tp.y *= factor\n}", "func (blk *Block) ScaleToHeight(h float64) {\n\tratio := h / blk.height\n\tblk.Scale(ratio, ratio)\n}", "func sendCoins(ctx sdk.Context, am sdk.AccountMapper, fromAddr sdk.Address, toAddr sdk.Address, amt sdk.Coins) sdk.Error {\n\t_, err := subtractCoins(ctx, am, fromAddr, amt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = addCoins(ctx, am, toAddr, amt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (k Keeper) BurnCoins(ctx sdk.Context, moduleName types.AccountID, amt Coins) error {\n\tacc := k.GetModuleAccount(ctx, moduleName.String())\n\tif acc == nil {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, \"module account %s does not exist\", moduleName))\n\t}\n\n\tif !acc.HasPermission(types.Burner) {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, \"module account %s does not have permissions to burn tokens\", moduleName))\n\t}\n\n\terr := k.SendCoinsFromModuleToModule(ctx, moduleName.String(), types.BlackHole, amt)\n\tif err != nil {\n\t\treturn sdkerrors.Wrapf(err, \"burn coins error by sub coin power\")\n\t}\n\n\tk.Logger(ctx).Info(fmt.Sprintf(\"burned %s from %s module account\", amt.String(), moduleName))\n\n\treturn nil\n}", "func (k Keeper) BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error {\n\tacc := k.GetModuleAccount(ctx, moduleName)\n\tif acc == nil {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, \"module account %s does not exist\", moduleName))\n\t}\n\n\tif !acc.HasPermission(types.Burner) {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, \"module account %s does not have permissions to burn tokens\", moduleName))\n\t}\n\n\t_, err := k.bk.SubtractCoins(ctx, acc.GetAddress(), amt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// update total supply\n\tsupply := k.GetSupply(ctx)\n\tsupply = supply.Deflate(amt)\n\tk.SetSupply(ctx, supply)\n\n\tlogger := k.Logger(ctx)\n\tlogger.Info(fmt.Sprintf(\"burned %s from %s module account\", amt.String(), moduleName))\n\n\treturn nil\n}", "func (x *Big) Scale() int { return -x.exp }", "func flipCoins(n int) int {\n\tvar i int\n\tfor i = 0; n > 1; i++ {\n\t\tn = round(n)\n\t}\n\treturn i\n}", "func drawCoins() int {\n\treturn rand.Intn(maxCoins+1-minCoins) + minCoins\n}", "func (s Size) ScaleUp(x, y int) Size {\n\ts.W *= x\n\ts.H *= y\n\treturn s\n}", "func (o ContainerOutput) Scale() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *Container) pulumi.IntOutput { return v.Scale }).(pulumi.IntOutput)\n}", "func Scale(s float64) Matrix {\n\treturn Matrix{s, 0, 0, s, 0, 0}\n}", "func ConvertSdkCoinsToWasmCoins(coins []sdk.Coin) wasmvmtypes.Coins {\n\tconverted := make(wasmvmtypes.Coins, len(coins))\n\tfor i, c := range coins {\n\t\tconverted[i] = ConvertSdkCoinToWasmCoin(c)\n\t}\n\treturn converted\n}", "func subtractCoins(ctx sdk.Context, am sdk.AccountMapper, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\toldCoins := getCoins(ctx, am, addr)\n\tnewCoins := oldCoins.Minus(amt)\n\tif !newCoins.IsNotNegative() {\n\t\treturn amt, sdk.ErrInsufficientCoins(fmt.Sprintf(\"%s < %s\", oldCoins, amt))\n\t}\n\terr := setCoins(ctx, am, addr, newCoins)\n\treturn newCoins, err\n}", "func (k Keeper) MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error {\n\tacc := k.GetModuleAccount(ctx, moduleName)\n\tif acc == nil {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, \"module account %s does not exist\", moduleName))\n\t}\n\n\tif !acc.HasPermission(types.Minter) {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, \"module account %s does not have permissions to mint tokens\", moduleName))\n\t}\n\n\t_, err := k.bk.AddCoins(ctx, acc.GetAddress(), amt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// update total supply\n\tsupply := k.GetSupply(ctx)\n\tsupply = supply.Inflate(amt)\n\n\tk.SetSupply(ctx, supply)\n\n\tlogger := k.Logger(ctx)\n\tlogger.Info(fmt.Sprintf(\"minted %s from %s module account\", amt.String(), moduleName))\n\n\treturn nil\n}", "func (keeper Keeper) SubtractCoins(ctx sdk.Context, addr sdk.Address, amt sdk.Coins) (sdk.Coins, sdk.Error) {\n\treturn subtractCoins(ctx, keeper.am, addr, amt)\n}", "func Scale(out *NArray, in *NArray, c float32) *NArray {\n\n\tif out == nil {\n\t\tout = New(in.Shape...)\n\t} else {\n\t\tif !EqualShape(out, in) {\n\t\t\tpanic(\"narrays must have equal shape.\")\n\t\t}\n\t}\n\tcmulSlice(out.Data, in.Data, c)\n\treturn out\n}", "func ScaleSprite(src *ebiten.Image, x, y float64) (*ebiten.Image, error) {\n\tspriteW, spriteH := src.Size()\n\tsSprite, sSpriteErr := ebiten.NewImage(\n\t\tint(float64(spriteW)*x),\n\t\tint(float64(spriteH)*y),\n\t\tebiten.FilterDefault)\n\tif sSpriteErr != nil {\n\t\treturn nil, sSpriteErr\n\t}\n\n\tops := &ebiten.DrawImageOptions{}\n\tops.GeoM.Scale(x, y)\n\tif drawErr := sSprite.DrawImage(src, ops); drawErr != nil {\n\t\treturn nil, drawErr\n\t}\n\n\treturn sSprite, nil\n}", "func change(amount int, coins []int) int {\n\tmemo := make([][]int, len(coins)+1)\n\tfor x := range memo {\n\t\tmemo[x] = make([]int, amount+1)\n\t}\n\n\tmemo[0][0] = 1\n\n\tfor x, coin := range coins {\n\t\tmemo[x+1][0] = 1\n\t\tfor y := 1; y <= amount; y++ {\n\t\t\tmemo[x+1][y] = memo[x][y] // exclude current coin - take the amount of previous coin\n\t\t\tif coin <= y {\n\t\t\t\tmemo[x+1][y] += memo[x+1][y-coin] // try to include current coin\n\t\t\t}\n\t\t}\n\t}\n\n\treturn memo[len(coins)][amount]\n}", "func (k Keeper) SwapDecCoins(ctx sdk.Context, offerCoin sdk.DecCoin, askDenom string) (sdk.DecCoin, sdk.Error) {\n\tofferRate, err := k.ok.GetLunaSwapRate(ctx, offerCoin.Denom)\n\tif err != nil {\n\t\treturn sdk.DecCoin{}, ErrNoEffectivePrice(DefaultCodespace, offerCoin.Denom)\n\t}\n\n\taskRate, err := k.ok.GetLunaSwapRate(ctx, askDenom)\n\tif err != nil {\n\t\treturn sdk.DecCoin{}, ErrNoEffectivePrice(DefaultCodespace, askDenom)\n\t}\n\n\tretAmount := offerCoin.Amount.Mul(askRate).Quo(offerRate)\n\tif retAmount.LTE(sdk.ZeroDec()) {\n\t\treturn sdk.DecCoin{}, ErrInsufficientSwapCoins(DefaultCodespace, offerCoin.Amount.TruncateInt())\n\t}\n\n\treturn sdk.NewDecCoinFromDec(askDenom, retAmount), nil\n}", "func Scale(appName string, webCount int, workerCount int) error {\n\targs := []string{\"dokku\", \"ps:scale\", appName}\n\n\tif webCount > 0 {\n\t\twebPart := fmt.Sprintf(\"web=%v\", webCount)\n\t\targs = append(args, webPart)\n\t}\n\n\tif workerCount > 0 {\n\t\tworkerPart := fmt.Sprintf(\"worker=%v\", workerCount)\n\t\targs = append(args, workerPart)\n\t}\n\n\tlog.GeneralLogger.Println(args)\n\tcmd := common.NewShellCmd(strings.Join(args, \" \"))\n\tcmd.ShowOutput = false\n\tout, err := cmd.Output()\n\n\tif err != nil {\n\t\tlog.ErrorLogger.Println(\"Dokku ps:scale error:\", err.Error())\n\t\tlog.ErrorLogger.Println(\"Dokku ps:scale output:\", string(out))\n\t\treturn err\n\t}\n\tlog.GeneralLogger.Println(\"Dokku ps:scale output:\", string(out))\n\treturn nil\n}", "func CoinChange(coins []int, amount int) int {\n\tdp := make([]int, amount+1)\n\tdp[0] = 0\n\tfor i := 1; i < len(dp); i++ {\n\t\tdp[i] = -1\n\t}\n\n\tfor i := 0; i <= amount; i++ {\n\t\tminChange := math.MaxInt16\n\t\tfor _, coin := range coins {\n\t\t\tif i-coin < 0 || dp[i-coin] == -1 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tminChange = min([]int{dp[i-coin], minChange})\n\t\t}\n\n\t\tif minChange != math.MaxInt16 {\n\t\t\tdp[i] = 1 + minChange\n\t\t}\n\t}\n\treturn dp[amount]\n}", "func (m *Manager) Scale(shardIDs []int, shardCount int) (err error) {\n\tsg, err := NewShardGroup(m, shardIDs, shardCount)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = sg.Start()\n\treturn\n}", "func (dc *DeploymentController) scale(ctx context.Context, deployment *apps.Deployment, newRS *apps.ReplicaSet, oldRSs []*apps.ReplicaSet) error {\n\t// If there is only one active replica set then we should scale that up to the full count of the\n\t// deployment. If there is no active replica set, then we should scale up the newest replica set.\n\tif activeOrLatest := deploymentutil.FindActiveOrLatest(newRS, oldRSs); activeOrLatest != nil {\n\t\tif *(activeOrLatest.Spec.Replicas) == *(deployment.Spec.Replicas) {\n\t\t\treturn nil\n\t\t}\n\t\t_, _, err := dc.scaleReplicaSetAndRecordEvent(ctx, activeOrLatest, *(deployment.Spec.Replicas), deployment)\n\t\treturn err\n\t}\n\n\t// If the new replica set is saturated, old replica sets should be fully scaled down.\n\t// This case handles replica set adoption during a saturated new replica set.\n\tif deploymentutil.IsSaturated(deployment, newRS) {\n\t\tfor _, old := range controller.FilterActiveReplicaSets(oldRSs) {\n\t\t\tif _, _, err := dc.scaleReplicaSetAndRecordEvent(ctx, old, 0, deployment); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\t// There are old replica sets with pods and the new replica set is not saturated.\n\t// We need to proportionally scale all replica sets (new and old) in case of a\n\t// rolling deployment.\n\tif deploymentutil.IsRollingUpdate(deployment) {\n\t\tallRSs := controller.FilterActiveReplicaSets(append(oldRSs, newRS))\n\t\tallRSsReplicas := deploymentutil.GetReplicaCountForReplicaSets(allRSs)\n\n\t\tallowedSize := int32(0)\n\t\tif *(deployment.Spec.Replicas) > 0 {\n\t\t\tallowedSize = *(deployment.Spec.Replicas) + deploymentutil.MaxSurge(*deployment)\n\t\t}\n\n\t\t// Number of additional replicas that can be either added or removed from the total\n\t\t// replicas count. These replicas should be distributed proportionally to the active\n\t\t// replica sets.\n\t\tdeploymentReplicasToAdd := allowedSize - allRSsReplicas\n\n\t\t// The additional replicas should be distributed proportionally amongst the active\n\t\t// replica sets from the larger to the smaller in size replica set. Scaling direction\n\t\t// drives what happens in case we are trying to scale replica sets of the same size.\n\t\t// In such a case when scaling up, we should scale up newer replica sets first, and\n\t\t// when scaling down, we should scale down older replica sets first.\n\t\tvar scalingOperation string\n\t\tswitch {\n\t\tcase deploymentReplicasToAdd > 0:\n\t\t\tsort.Sort(controller.ReplicaSetsBySizeNewer(allRSs))\n\t\t\tscalingOperation = \"up\"\n\n\t\tcase deploymentReplicasToAdd < 0:\n\t\t\tsort.Sort(controller.ReplicaSetsBySizeOlder(allRSs))\n\t\t\tscalingOperation = \"down\"\n\t\t}\n\n\t\t// Iterate over all active replica sets and estimate proportions for each of them.\n\t\t// The absolute value of deploymentReplicasAdded should never exceed the absolute\n\t\t// value of deploymentReplicasToAdd.\n\t\tdeploymentReplicasAdded := int32(0)\n\t\tnameToSize := make(map[string]int32)\n\t\tlogger := klog.FromContext(ctx)\n\t\tfor i := range allRSs {\n\t\t\trs := allRSs[i]\n\n\t\t\t// Estimate proportions if we have replicas to add, otherwise simply populate\n\t\t\t// nameToSize with the current sizes for each replica set.\n\t\t\tif deploymentReplicasToAdd != 0 {\n\t\t\t\tproportion := deploymentutil.GetProportion(logger, rs, *deployment, deploymentReplicasToAdd, deploymentReplicasAdded)\n\n\t\t\t\tnameToSize[rs.Name] = *(rs.Spec.Replicas) + proportion\n\t\t\t\tdeploymentReplicasAdded += proportion\n\t\t\t} else {\n\t\t\t\tnameToSize[rs.Name] = *(rs.Spec.Replicas)\n\t\t\t}\n\t\t}\n\n\t\t// Update all replica sets\n\t\tfor i := range allRSs {\n\t\t\trs := allRSs[i]\n\n\t\t\t// Add/remove any leftovers to the largest replica set.\n\t\t\tif i == 0 && deploymentReplicasToAdd != 0 {\n\t\t\t\tleftover := deploymentReplicasToAdd - deploymentReplicasAdded\n\t\t\t\tnameToSize[rs.Name] = nameToSize[rs.Name] + leftover\n\t\t\t\tif nameToSize[rs.Name] < 0 {\n\t\t\t\t\tnameToSize[rs.Name] = 0\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// TODO: Use transactions when we have them.\n\t\t\tif _, _, err := dc.scaleReplicaSet(ctx, rs, nameToSize[rs.Name], deployment, scalingOperation); err != nil {\n\t\t\t\t// Return as soon as we fail, the deployment is requeued\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (v *Vertex) scale(factor float64) {\n\tv.X = v.X * factor\n\tv.Y = v.Y * factor\n}", "func (self *Rectangle) Scale(x int) *Rectangle{\n return &Rectangle{self.Object.Call(\"scale\", x)}\n}", "func scale_pixel(x, y int) (float64, float64) {\n\tnewx := float64(x)/(float64(maxX)/3) - 2.0\n\tnewy := float64(y)/(float64(maxY)/2) - 0.0 \n\treturn newx, newy\n}", "func (k Keeper) MintCoins(ctx sdk.Context, moduleName string, amt *Coins) error {\n\tacc := k.GetModuleAccount(ctx, moduleName)\n\tif acc == nil {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, \"module account %s does not exist\", moduleName))\n\t}\n\n\tif !acc.HasPermission(types.Minter) {\n\t\tpanic(sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, \"module account %s does not have permissions to mint tokens\", moduleName))\n\t}\n\n\t_, err := k.bk.IssueCoinPower(ctx, acc.GetID(), *amt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tk.Logger(ctx).Info(fmt.Sprintf(\"minted %s from %s module account\", amt.String(), moduleName))\n\n\treturn nil\n}", "func Scale(p point, factor int) point {\n\treturn point{p.x * factor, p.y * factor, p.z * factor}\n}", "func (c BaseController) MoveCoins(store weave.KVStore,\n\tsrc weave.Address, dest weave.Address, amount coin.Coin) error {\n\n\tif amount.IsZero() {\n\t\treturn errors.Wrap(errors.ErrAmount, \"zero value\")\n\t}\n\tif !amount.IsPositive() {\n\t\treturn errors.Wrapf(errors.ErrAmount, \"non-positive SendMsg: %#v\", &amount)\n\t}\n\n\t// load sender, subtract funds, and save\n\tsender, err := c.bucket.Get(store, src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif sender == nil {\n\t\treturn errors.Wrapf(errors.ErrEmpty, \"empty account %s\", src)\n\t}\n\tif !AsCoins(sender).Contains(amount) {\n\t\treturn errors.Wrap(errors.ErrAmount, \"funds\")\n\t}\n\terr = Subtract(AsCoinage(sender), amount)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = c.bucket.Save(store, sender)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// load/create recipient, add funds, save\n\trecipient, err := c.bucket.GetOrCreate(store, dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = Add(AsCoinage(recipient), amount)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.bucket.Save(store, recipient)\n}", "func (r Rectangle) Scale(factor float64) Rectangle {\n\treturn Rectangle{\n\t\tMin: r.Min.Mul(factor),\n\t\tMax: r.Max.Mul(factor),\n\t}\n}", "func (proof *PaymentProofV2) SetOutputCoins(v []coin.Coin) error {\n\tvar err error\n\tproof.outputCoins = make([]*coin.CoinV2, len(v))\n\tfor i := 0; i < len(v); i += 1 {\n\t\tproof.outputCoins[i] = new(coin.CoinV2)\n\t\tb := v[i].Bytes()\n\t\tif err = proof.outputCoins[i].SetBytes(b); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (g *GameObject) SetScale(scale float64) {\r\n\tg.Hitbox.maxX *= scale / g.Scale\r\n\tg.Hitbox.maxY *= scale / g.Scale\r\n\tg.Scale = scale\r\n}", "func (k Keeper) BurnCoinsForChallenges(ctx sdk.Ctx, relays int64, toAddr sdk.Address) {\n\tk.posKeeper.BurnForChallenge(ctx, sdk.NewInt(relays), toAddr)\n}", "func (dcr *ExchangeWallet) addInputCoins(msgTx *wire.MsgTx, coins asset.Coins) (uint64, error) {\n\tvar totalIn uint64\n\tfor _, coin := range coins {\n\t\top, err := dcr.convertCoin(coin)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif op.value == 0 {\n\t\t\treturn 0, fmt.Errorf(\"zero-valued output detected for %s:%d\", op.txHash(), op.vout())\n\t\t}\n\t\ttotalIn += op.value\n\t\tprevOut := op.wireOutPoint()\n\t\ttxIn := wire.NewTxIn(prevOut, int64(op.value), []byte{})\n\t\tmsgTx.AddTxIn(txIn)\n\t}\n\treturn totalIn, nil\n}", "func (s *Service) scale(replicas int) {\n\tlog.WithField(\"replicas\", replicas).Debug(\"Service scaling\")\n\ts.state = StateScaling\n\tif s.CurrentReplicas != replicas {\n\t\ts.auklet.scaleService(s.ServiceID, replicas)\n\t\ts.auklet.Lock()\n\t\ts.auklet.metrics[MetricServiceScaleEventsTotal].(prometheus.Counter).Inc()\n\t\tif replicas > s.CurrentReplicas {\n\t\t\ts.auklet.serviceMetrics[s.ServiceID][MetricScaleUpEventsCount].(prometheus.Counter).Inc()\n\t\t} else {\n\t\t\ts.auklet.serviceMetrics[s.ServiceID][MetricScaleDownEventsCount].(prometheus.Counter).Inc()\n\t\t}\n\t\ts.auklet.Unlock()\n\t}\n\n\t// after scaling return to stable state\n\ts.stable()\n}", "func coinChange(coins []int, amount int) int {\n\t// let a(i, j) be the result for first i coins to get j amount.\n\t// then a(i, j) = min( a(i-1, j), a(i, j-coins[i])+1)\n\t// base case a(i, 0)=0, a(i, coins[i])=1\n\tif amount == 0 {\n\t\treturn 0\n\t}\n\ta0 := make([]int, amount+1)\n\ta1 := make([]int, amount+1)\n\tfor i := 0; i < len(coins); i++ {\n\t\ta1[0] = 0 // a(i, 0) = 0\n\t\tfor j := 1; j <= amount; j++ {\n\t\t\tif j == coins[i] {\n\t\t\t\ta1[j] = 1 // a(i, coins[i]) = 1\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ta1[j] = a0[j] // a(i, j) = a(i-1, j)\n\t\t\tif j-coins[i] > 0 && a1[j-coins[i]] > 0 {\n\t\t\t\tif a0[j] == 0 || a1[j-coins[i]]+1 < a0[j] {\n\t\t\t\t\ta1[j] = a1[j-coins[i]] + 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//fmt.Println(a1)\n\t\ta0, a1 = a1, a0\n\t}\n\tif a0[amount] == 0 {\n\t\treturn -1\n\t}\n\treturn a0[amount]\n}", "func (p *Point) Scale(v float64) {\n\tp.x *= v\n\tp.y *= v\n}", "func uscale(bytes uint64) (scaled int64, scale string) {\n\ti := 0\n\tfor bytes > 1023 {\n\t\ti++\n\t\tbytes = bytes >> 10\n\t}\n\treturn int64(bytes), unitPrefixs[i]\n}", "func (dcr *ExchangeWallet) addInputCoins(msgTx *wire.MsgTx, coins asset.Coins) (uint64, error) {\n\tvar totalIn uint64\n\tfor _, coin := range coins {\n\t\top, err := dcr.convertCoin(coin)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif op.value == 0 {\n\t\t\treturn 0, fmt.Errorf(\"zero-valued output detected for %s:%d\", op.txHash(), op.vout())\n\t\t}\n\t\tif op.tree == wire.TxTreeUnknown { // Set the correct prevout tree if unknown.\n\t\t\tunspentPrevOut, err := dcr.wallet.UnspentOutput(dcr.ctx, op.txHash(), op.vout(), op.tree)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, fmt.Errorf(\"unable to determine tree for prevout %s: %v\", op.pt, err)\n\t\t\t}\n\t\t\top.tree = unspentPrevOut.Tree\n\t\t}\n\t\ttotalIn += op.value\n\t\tprevOut := op.wireOutPoint()\n\t\ttxIn := wire.NewTxIn(prevOut, int64(op.value), []byte{})\n\t\tmsgTx.AddTxIn(txIn)\n\t}\n\treturn totalIn, nil\n}", "func TestDecimal_Scale(t *testing.T) {\n\ta := New(1234, -3)\n\tif a.Scale() != -3 {\n\t\tt.Errorf(\"error\")\n\t}\n}", "func (w *windowImpl) Scale(dr image.Rectangle, src screen.Texture, sr image.Rectangle, op draw.Op, opts *screen.DrawOptions) {\n\tpanic(\"not implemented\") // TODO: Implement\n}", "func (self *ComponentScaleMinMax) SetScaleMinMax(minX interface{}, minY interface{}, maxX interface{}, maxY interface{}) {\n self.Object.Call(\"setScaleMinMax\", minX, minY, maxX, maxY)\n}", "func scale(n int) string {\n\tswitch n {\n\tcase 1:\n\t\treturn \"Celcius\"\n\tcase 2:\n\t\treturn \"Fahrenheit\"\n\tdefault:\n\t\treturn \"\"\n\t}\n}", "func Change(amount int) map[int]int {\n\tusedCoins := map[int]int{25: 0, 10: 0, 5: 0, 1: 0}\n\n\tif amount == 0 {\n\t\treturn usedCoins\n\t}\n\n\tremain := amount\n\n\tfor _, coin := range coins {\n\t\tif remain == 0 {\n\t\t\treturn usedCoins\n\t\t}\n\n\t\tmod := remain % coin\n\t\tif mod != remain {\n\t\t\tusedCoins[coin] = int(remain / coin)\n\t\t\tremain = mod\n\t\t}\n\t}\n\n\treturn usedCoins\n}" ]
[ "0.53646266", "0.5312407", "0.5284086", "0.5185207", "0.51215756", "0.50750524", "0.5065373", "0.50019264", "0.49968642", "0.49823198", "0.49739826", "0.48987997", "0.4869174", "0.48599055", "0.4815493", "0.48011187", "0.47879016", "0.47696072", "0.47589323", "0.47524524", "0.47524124", "0.47338954", "0.46928", "0.46884242", "0.4672732", "0.46711504", "0.46469107", "0.46466094", "0.46434674", "0.4632861", "0.4632501", "0.46298173", "0.4629572", "0.46288264", "0.46010748", "0.45794138", "0.45748407", "0.4549467", "0.4549313", "0.45438683", "0.45384747", "0.45303962", "0.45238942", "0.451829", "0.45029402", "0.44626173", "0.44610244", "0.44574344", "0.4448427", "0.44392017", "0.44345808", "0.44313297", "0.44290796", "0.44281232", "0.4420486", "0.4417458", "0.44163188", "0.4407654", "0.44073337", "0.43749264", "0.43722826", "0.43633652", "0.43608886", "0.4347979", "0.43368405", "0.4333907", "0.4331032", "0.4319784", "0.43092752", "0.43044642", "0.42930454", "0.4272178", "0.42508784", "0.42473167", "0.42461073", "0.4234278", "0.4229713", "0.42251295", "0.42188358", "0.42171898", "0.420896", "0.42082766", "0.42048904", "0.4199404", "0.41961703", "0.41953552", "0.41904944", "0.41844538", "0.4181977", "0.41809413", "0.41770405", "0.41757047", "0.4175097", "0.41732293", "0.41612554", "0.41608053", "0.41592807", "0.4157955", "0.4155872", "0.4149927" ]
0.8575942
0
intMin returns the minimum of its arguments.
func intMin(a, b sdk.Int) sdk.Int { if a.GT(b) { return b } return a }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func MinInt(a ...int) int {\n\tswitch len(a) {\n\tcase 0:\n\t\treturn 0\n\tcase 1:\n\t\treturn a[0]\n\tcase 2:\n\t\tif a[0] > a[1] {\n\t\t\treturn a[1]\n\t\t} else {\n\t\t\treturn a[0]\n\t\t}\n\tdefault:\n\t\tmin := math.MaxInt32\n\t\tfor _, i := range a {\n\t\t\tif i < min {\n\t\t\t\tmin = i\n\t\t\t}\n\t\t}\n\t\treturn min\n\t}\n}", "func MinInt(input ...int) int {\n\tif len(input) == 0 {\n\t\treturn 0\n\t}\n\n\tmin := input[0]\n\tfor _, in := range input {\n\t\tif in < min {\n\t\t\tmin = in\n\t\t}\n\t}\n\n\treturn min\n}", "func (m mathUtil) MinInt(values ...int) int {\n\tmin := math.MaxInt32\n\tfor _, v := range values {\n\t\tif v < min {\n\t\t\tmin = v\n\t\t}\n\t}\n\treturn min\n}", "func MinInt(values ...int) (min int) {\n\tmin, _ = MinMaxInt(values...)\n\treturn\n}", "func MinInt(xs ...int) int {\n\tm := xs[0]\n\tfor i := 1; i < len(xs); i++ {\n\t\tif xs[i] < m {\n\t\t\tm = xs[i]\n\t\t}\n\t}\n\n\treturn m\n}", "func minInt(x ...int) int {\n\tvar index int // Index of minimum value in x\n\tfor i := range x {\n\t\tif x[i] < x[index] {\n\t\t\tindex = i\n\t\t}\n\t}\n\treturn x[index]\n}", "func MinInt(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\n\treturn b\n}", "func MinInt(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func MinInt(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func MinInt(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func MinInt(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t} else {\n\t\treturn y\n\t}\n}", "func MinInt(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\n\treturn y\n}", "func IntMin(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func IntMin(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func MinInt(x, y int) int {\n\tif x > y {\n\t\treturn y\n\t}\n\treturn x\n}", "func IntMin(a int, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func MinInt(a, b int64) int64 {\n\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func minInt(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func minInt(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func minInt(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func minInt(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func minInt(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func minInt(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func MinInt(a, b int) int {\n\tmin := b\n\tif a < b {\n\t\tmin = a\n\t}\n\treturn min\n}", "func IntMin(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}", "func IntMin(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}", "func IntMin(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}", "func IntMin(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}", "func MinInt(nums ...int) int {\n\tif len(nums) == 0 {\n\t\treturn 0\n\t}\n\n\tmin := nums[0]\n\tfor _, num := range nums {\n\t\tif num < min {\n\t\t\tmin = num\n\t\t}\n\t}\n\n\treturn min\n}", "func IntMin(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\n\treturn y\n}", "func Min(x, min int) int { return x }", "func Min(a ...int) (min int) {\n\tfor i, ai := range a {\n\t\tif i == 0 || ai < min {\n\t\t\tmin = ai\n\t\t}\n\t}\n\treturn min\n}", "func MinInt(vals ...int) int {\n\tmin := vals[0]\n\tfor i := 1; i < len(vals); i++ {\n\t\tif vals[i] < min {\n\t\t\tmin = vals[i]\n\t\t}\n\t}\n\treturn min\n}", "func minint(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func MinInt(v1, v2 int) (m int) {\n\tif LTInt(v2, v1) {\n\t\tm = v2\n\t} else {\n\t\tm = v1\n\t}\n\treturn\n}", "func Min(a ...int) int {\n\tmin := int(^uint(0) >> 1) // largest int\n\tfor _, i := range a {\n\t\tif i < min {\n\t\t\tmin = i\n\t\t}\n\t}\n\treturn min\n}", "func min(integers ...int) int {\n\tm := integers[0]\n\tfor i, integer := range integers {\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif m > integer {\n\t\t\tm = integer\n\t\t}\n\t}\n\treturn m\n}", "func Min(a, b int) int {\n\treturn neogointernal.Opcode2(\"MIN\", a, b).(int)\n}", "func MinInt(i1, i2 Int) Int {\n\treturn Int{min(i1.BigInt(), i2.BigInt())}\n}", "func minInt(a, b int) int {\n if a < b {\n return a\n }\n return b\n}", "func Min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Min(a int, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Min(a int, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Min(a, b int) int {\n\tif b < a {\n\t\treturn b\n\t}\n\treturn a\n}", "func Min(a, b int) int {\r\n\tif a < b {\r\n\t\treturn a\r\n\t}\r\n\treturn b\r\n}", "func Min(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}", "func Min(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}", "func Min(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}", "func Min(numbers ...int) int {\n\tmin := numbers[0]\n\tfor _, num := range numbers {\n\t\tif num < min {\n\t\t\tmin = num\n\t\t}\n\t}\n\treturn min\n}", "func Min(a int, b int) int {\n\tif (a > b) {\n\t\treturn b\n\t}\n\n\treturn a\n}", "func MinI(n ...int) int {\n\tmin := math.MaxInt64\n\tfor _, v := range n {\n\t\tif v < min {\n\t\t\tmin = v\n\t\t}\n\t}\n\treturn min\n}", "func min(n int, rest ...int) int {\n\tm := n\n\tfor _, v := range rest {\n\t\tif v < m {\n\t\t\tm = v\n\t\t}\n\t}\n\treturn m\n}", "func MinInt32(x, min int32) int32 { return x }", "func ValidateIntMin(optIf interface{}, paramIf interface{}) error {\n\topt := optIf.(argumentOption.Option)\n\tmin := paramIf.(ParamInt).Min\n\tval, err := opt.GetValue()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif val.(int) < min {\n\t\treturn errors.New(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"Invalid value of --%v -%v %v. Value %v is smaller than min %v.\",\n\t\t\t\topt.LongKey, opt.ShortKey, val.(int),\n\t\t\t\tval.(int), min))\n\t}\n\treturn nil\n}", "func Min(nums ...int) int {\n\tmin := nums[0]\n\tfor _, i := range nums {\n\t\tif i < min {\n\t\t\tmin = i\n\t\t}\n\t}\n\treturn min\n}", "func Min(x int, other ...int) int {\n\tmin := x\n\n\tfor _, y := range other {\n\t\tif y < min {\n\t\t\tmin = y\n\t\t}\n\t}\n\treturn min\n}", "func MIN(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Min(x int, y int) int {\n\tif x < y { return x }\n\treturn y\n}", "func Min(a, b int) int {\n\tif a-b < 0 {\n\t\treturn a\n\t}\n\n\treturn b\n}", "func min(v ...int) int {\n\tout := 0\n\tif len(v) >= 1 {\n\t\tout = v[0]\n\t}\n\tfor i := range v {\n\t\tif v[i] < out {\n\t\t\tout = v[i]\n\t\t}\n\t}\n\treturn out\n}", "func Min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}", "func Min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}", "func Min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}", "func minInt(arr []int) int {\n\tmin := arr[0]\n\n\tfor _, v := range arr {\n\t\tif min > v {\n\t\t\tmin = v\n\t\t}\n\t}\n\n\treturn min\n}", "func Min(a int, b int) int {\n\tif a <= b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Min(a, operand int) int {\n\tif a < operand {\n\t\treturn a\n\t}\n\treturn operand\n}", "func min(a, b int) int {\r\n\tif a < b {\r\n\t\treturn a\r\n\t}\r\n\treturn b\r\n}", "func min(a, b int) int {\r\n\tif a < b {\r\n\t\treturn a\r\n\t}\r\n\treturn b\r\n}", "func min(a int, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\n\treturn b\n}", "func min(a, b int) (int) {\n\tif a < b {\n\t\treturn a\n\t}\n\n\treturn b\n}", "func Min(numbers ...cty.Value) (cty.Value, error) {\n\treturn MinFunc.Call(numbers)\n}", "func min(a int, b int) (res int) {\n\tif a < b {\n\t\tres = a\n\t} else {\n\t\tres = b\n\t}\n\n\treturn\n}", "func min(a, b int) int {\n\tif b < a {\n\t\treturn b\n\t}\n\treturn a\n}", "func min(a, b int) int {\n\tif b < a {\n\t\treturn b\n\t}\n\treturn a\n}", "func min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t} else {\n\t\treturn y\n\t}\n}", "func min(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}", "func TestMinInt(t *testing.T) {\n\tvar cases = []struct {\n\t\ta, b int\n\t\tout int\n\t}{\n\t\t{a: 0, b: 0, out: 0},\n\t\t{a: 1, b: 0, out: 1},\n\t}\n\n\tfor _, c := range cases {\n\t\tif out := MinInt(c.a, c.b); out != c.out {\n\t\t\tt.Errorf(\"got %v, want %v\", out, c.out)\n\t\t}\n\t}\n}", "func MinInt64(x, min int64) int64 { return x }", "func min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}", "func min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}", "func min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}", "func SmallestInt(iarr ...int) int {\n\ts := iarr[0]\n\n\tfor i := 1; i < len(iarr); i++ {\n\t\tif iarr[i] < s {\n\t\t\ts = iarr[i]\n\t\t}\n\t}\n\n\treturn s\n}" ]
[ "0.84761566", "0.83848757", "0.83676636", "0.8266599", "0.8205421", "0.8192152", "0.8164177", "0.8159744", "0.8159744", "0.8159744", "0.81228924", "0.80882347", "0.8054223", "0.8054223", "0.8051462", "0.8035539", "0.80338305", "0.80289274", "0.80289274", "0.80289274", "0.80289274", "0.80289274", "0.80289274", "0.80264294", "0.80178964", "0.80178964", "0.80178964", "0.80178964", "0.80126816", "0.7970963", "0.79650664", "0.79276025", "0.79071605", "0.7895244", "0.78790677", "0.7837896", "0.7776571", "0.76310015", "0.7621244", "0.7601292", "0.7587097", "0.7587097", "0.7587097", "0.7587097", "0.7587097", "0.7587097", "0.7587097", "0.75575864", "0.75575864", "0.7544529", "0.752908", "0.7527486", "0.7527486", "0.7527486", "0.75264645", "0.75241", "0.74916476", "0.74719626", "0.746777", "0.744127", "0.74388105", "0.73928803", "0.7389897", "0.7369741", "0.7360995", "0.7358808", "0.7356634", "0.7356634", "0.7356634", "0.7349462", "0.7333666", "0.7327413", "0.7286542", "0.7286542", "0.72831184", "0.7282949", "0.7282949", "0.7282949", "0.7282949", "0.7282949", "0.7282949", "0.7282949", "0.7282949", "0.7282949", "0.7282949", "0.7282949", "0.7277774", "0.72731656", "0.72554606", "0.72319317", "0.7223655", "0.7223655", "0.7183255", "0.7181891", "0.7173904", "0.7142582", "0.7090552", "0.7090552", "0.7090552", "0.7089386" ]
0.78345966
36
NewClawbackRewardAction returns an exported.RewardAction for a ClawbackVestingAccount.
func NewClawbackRewardAction(ak AccountKeeper, bk BankKeeper, sk StakingKeeper) exported.RewardAction { return clawbackRewardAction{ ak: ak, bk: bk, sk: sk, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewClawbackAction(requestor, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) exported.ClawbackAction {\n\treturn clawbackAction{\n\t\trequestor: requestor,\n\t\tdest: dest,\n\t\tak: ak,\n\t\tbk: bk,\n\t\tsk: sk,\n\t}\n}", "func NewClawbackGrantAction(\n\tfunderAddress string,\n\tsk StakingKeeper,\n\tgrantStartTime int64,\n\tgrantLockupPeriods, grantVestingPeriods []Period,\n\tgrantCoins sdk.Coins,\n) exported.AddGrantAction {\n\treturn clawbackGrantAction{\n\t\tfunderAddress: funderAddress,\n\t\tsk: sk,\n\t\tgrantStartTime: grantStartTime,\n\t\tgrantLockupPeriods: grantLockupPeriods,\n\t\tgrantVestingPeriods: grantVestingPeriods,\n\t\tgrantCoins: grantCoins,\n\t}\n}", "func NewBcBotAction(j *bot.Jobs) *BcBotAction {\n\t// client := resty.New()\n\t// client.\n\t// \tSetRetryCount(3).\n\t// \tSetRetryWaitTime(10 * time.Second)\n\treturn &BcBotAction{jobs: j, client: nil, mutex: new(sync.RWMutex)}\n}", "func NewRecvAction(args any) *Action {\n\treturn &Action{Args: args}\n}", "func (cra clawbackRewardAction) ProcessReward(ctx sdk.Context, reward sdk.Coins, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported, \"expected *ClawbackVestingAccount, got %T\", rawAccount)\n\t}\n\tcva.postReward(ctx, reward, cra.ak, cra.bk, cra.sk)\n\treturn nil\n}", "func NewRollbackAction(kit kit.Kit, viper *viper.Viper,\n\tauthSvrCli pbauthserver.AuthClient, dataMgrCli pbdatamanager.DataManagerClient,\n\tgseControllerCli pbgsecontroller.GSEControllerClient,\n\treq *pb.RollbackReleaseReq, resp *pb.RollbackReleaseResp) *RollbackAction {\n\n\taction := &RollbackAction{\n\t\tkit: kit,\n\t\tviper: viper,\n\t\tauthSvrCli: authSvrCli,\n\t\tdataMgrCli: dataMgrCli,\n\t\tgseControllerCli: gseControllerCli,\n\t\treq: req,\n\t\tresp: resp,\n\t}\n\n\taction.resp.Result = true\n\taction.resp.Code = pbcommon.ErrCode_E_OK\n\taction.resp.Message = \"OK\"\n\n\treturn action\n}", "func NewCollateralizeAction(c *Collateralize, tx *types.Transaction, index int) *Action {\n\thash := tx.Hash()\n\tfromaddr := tx.From()\n\tcfg := c.GetAPI().GetConfig()\n\ttokenDb, err := account.NewAccountDB(cfg, tokenE.GetName(), pty.CCNYTokenName, c.GetStateDB())\n\tif err != nil {\n\t\tclog.Error(\"NewCollateralizeAction\", \"Get Account DB error\", \"error\", err)\n\t\treturn nil\n\t}\n\n\treturn &Action{\n\t\tcoinsAccount: c.GetCoinsAccount(), tokenAccount: tokenDb, db: c.GetStateDB(), localDB: c.GetLocalDB(),\n\t\ttxhash: hash, fromaddr: fromaddr, blocktime: c.GetBlockTime(), height: c.GetHeight(),\n\t\texecaddr: dapp.ExecAddress(string(tx.Execer)), difficulty: c.GetDifficulty(), index: index, Collateralize: c}\n}", "func NewAction(h *Hashlock, tx *types.Transaction, execaddr string) *Action {\n\thash := tx.Hash()\n\tfromaddr := tx.From()\n\treturn &Action{h.GetCoinsAccount(), h.GetStateDB(), hash, fromaddr, h.GetBlockTime(), h.GetHeight(), execaddr, h.GetAPI()}\n}", "func (va *ClawbackVestingAccount) PostReward(ctx sdk.Context, reward sdk.Coins, action exported.RewardAction) error {\n\treturn action.ProcessReward(ctx, reward, va)\n}", "func NewRecoverableAction(supervisor *Supervisor) *RecoverableAction {\n\tra := &RecoverableAction{\n\t\tactionChan: make(chan Action),\n\t\treplyChan: make(chan string, 5),\n\t\tsupervisor: supervisor,\n\t}\n\n\tra.heartbeat = NewHeartbeat(ra, 1e8)\n\n\tgo ra.backend()\n\n\treturn ra\n}", "func NewCheckmate(winner Colour) Outcome { return Outcome{Winner: winner, Reason: checkmate} }", "func GetReward(a Action, feedback Action) float64 {\n\tif a == feedback {\n\t\treturn 1\n\t}\n\treturn -1\n}", "func NewChallengeAction(msg *Message) (*ChallengeAction, error) {\n\taction := &ChallengeAction{*msg}\n\n\treturn action, nil\n}", "func NewAction(name string, arg interface{}) {\n\tDefaultActionRegistry.Post(name, arg)\n}", "func New() Action {\n\treturn &action{}\n}", "func (_Token *TokenCallerSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\n}", "func (va ClawbackVestingAccount) distributeReward(ctx sdk.Context, ak AccountKeeper, bondDenom string, reward sdk.Coins) {\n\tnow := ctx.BlockTime().Unix()\n\tt := va.StartTime\n\tfirstUnvestedPeriod := 0\n\tunvestedTokens := sdk.ZeroInt()\n\tfor i, period := range va.VestingPeriods {\n\t\tt += period.Length\n\t\tif t <= now {\n\t\t\tfirstUnvestedPeriod = i + 1\n\t\t\tcontinue\n\t\t}\n\t\tunvestedTokens = unvestedTokens.Add(period.Amount.AmountOf(bondDenom))\n\t}\n\n\trunningTotReward := sdk.NewCoins()\n\trunningTotStaking := sdk.ZeroInt()\n\tfor i := firstUnvestedPeriod; i < len(va.VestingPeriods); i++ {\n\t\tperiod := va.VestingPeriods[i]\n\t\trunningTotStaking = runningTotStaking.Add(period.Amount.AmountOf(bondDenom))\n\t\trunningTotRatio := runningTotStaking.ToDec().Quo(unvestedTokens.ToDec())\n\t\ttargetCoins := scaleCoins(reward, runningTotRatio)\n\t\tthisReward := targetCoins.Sub(runningTotReward)\n\t\trunningTotReward = targetCoins\n\t\tperiod.Amount = period.Amount.Add(thisReward...)\n\t\tva.VestingPeriods[i] = period\n\t}\n\n\tva.OriginalVesting = va.OriginalVesting.Add(reward...)\n\tak.SetAccount(ctx, &va)\n}", "func NewTriggerAction(agentName string, propertyName string, propertyValue string) *TriggerAction {\n instance := new(TriggerAction)\n instance.agentName = agentName\n instance.propertyName = propertyName\n instance.propertyValue = propertyValue\n return instance\n}", "func NewClawbackVestingAccount(baseAcc *authtypes.BaseAccount, funder sdk.AccAddress, originalVesting sdk.Coins, startTime int64, lockupPeriods, vestingPeriods Periods) *ClawbackVestingAccount {\n\t// copy and align schedules to avoid mutating inputs\n\tlp := make(Periods, len(lockupPeriods))\n\tcopy(lp, lockupPeriods)\n\tvp := make(Periods, len(vestingPeriods))\n\tcopy(vp, vestingPeriods)\n\t_, endTime := AlignSchedules(startTime, startTime, lp, vp)\n\tbaseVestingAcc := &BaseVestingAccount{\n\t\tBaseAccount: baseAcc,\n\t\tOriginalVesting: originalVesting,\n\t\tEndTime: endTime,\n\t}\n\n\treturn &ClawbackVestingAccount{\n\t\tBaseVestingAccount: baseVestingAcc,\n\t\tFunderAddress: funder.String(),\n\t\tStartTime: startTime,\n\t\tLockupPeriods: lp,\n\t\tVestingPeriods: vp,\n\t}\n}", "func New() *Action {\n\treturn &Action{}\n}", "func NewAction(app *buffalo.App) *Action {\n\tas := &Action{\n\t\tApp: app,\n\t\tModel: NewModel(),\n\t}\n\treturn as\n}", "func (va *ClawbackVestingAccount) clawback(ctx sdk.Context, dest sdk.AccAddress, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) error {\n\t// Compute the clawback based on the account state only, and update account\n\ttoClawBack := va.computeClawback(ctx.BlockTime().Unix())\n\tif toClawBack.IsZero() {\n\t\treturn nil\n\t}\n\taddr := va.GetAddress()\n\tbondDenom := sk.BondDenom(ctx)\n\n\t// Compute the clawback based on bank balance and delegation, and update account\n\tencumbered := va.GetVestingCoins(ctx.BlockTime())\n\tbondedAmt := sk.GetDelegatorBonded(ctx, addr)\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, addr)\n\tbonded := sdk.NewCoins(sdk.NewCoin(bondDenom, bondedAmt))\n\tunbonding := sdk.NewCoins(sdk.NewCoin(bondDenom, unbondingAmt))\n\tunbonded := bk.GetAllBalances(ctx, addr)\n\ttoClawBack = va.updateDelegation(encumbered, toClawBack, bonded, unbonding, unbonded)\n\n\t// Write now now so that the bank module sees unvested tokens are unlocked.\n\t// Note that all store writes are aborted if there is a panic, so there is\n\t// no danger in writing incomplete results.\n\tak.SetAccount(ctx, va)\n\n\t// Now that future vesting events (and associated lockup) are removed,\n\t// the balance of the account is unlocked and can be freely transferred.\n\tspendable := bk.SpendableCoins(ctx, addr)\n\ttoXfer := coinsMin(toClawBack, spendable)\n\terr := bk.SendCoins(ctx, addr, dest, toXfer)\n\tif err != nil {\n\t\treturn err // shouldn't happen, given spendable check\n\t}\n\ttoClawBack = toClawBack.Sub(toXfer)\n\n\t// We need to traverse the staking data structures to update the\n\t// vesting account bookkeeping, and to recover more funds if necessary.\n\t// Staking is the only way unvested tokens should be missing from the bank balance.\n\n\t// If we need more, transfer UnbondingDelegations.\n\twant := toClawBack.AmountOf(bondDenom)\n\tunbondings := sk.GetUnbondingDelegations(ctx, addr, math.MaxUint16)\n\tfor _, unbonding := range unbondings {\n\t\tvalAddr, err := sdk.ValAddressFromBech32(unbonding.ValidatorAddress)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttransferred := sk.TransferUnbonding(ctx, addr, dest, valAddr, want)\n\t\twant = want.Sub(transferred)\n\t\tif !want.IsPositive() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// If we need more, transfer Delegations.\n\tif want.IsPositive() {\n\t\tdelegations := sk.GetDelegatorDelegations(ctx, addr, math.MaxUint16)\n\t\tfor _, delegation := range delegations {\n\t\t\tvalidatorAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err) // shouldn't happen\n\t\t\t}\n\t\t\tvalidator, found := sk.GetValidator(ctx, validatorAddr)\n\t\t\tif !found {\n\t\t\t\t// validator has been removed\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twantShares, err := validator.SharesFromTokensTruncated(want)\n\t\t\tif err != nil {\n\t\t\t\t// validator has no tokens\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttransferredShares := sk.TransferDelegation(ctx, addr, dest, delegation.GetValidatorAddr(), wantShares)\n\t\t\t// to be conservative in what we're clawing back, round transferred shares up\n\t\t\ttransferred := validator.TokensFromSharesRoundUp(transferredShares).RoundInt()\n\t\t\twant = want.Sub(transferred)\n\t\t\tif !want.IsPositive() {\n\t\t\t\t// Could be slightly negative, due to rounding?\n\t\t\t\t// Don't think so, due to the precautions above.\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we've transferred everything and still haven't transferred the desired clawback amount,\n\t// then the account must have most some unvested tokens from slashing.\n\treturn nil\n}", "func NewAction() actions.Action {\n\treturn &Action{}\n}", "func NewAction() actions.Action {\n\treturn &Action{}\n}", "func (a Actor) AwardBlockReward(rt vmr.Runtime, params *AwardBlockRewardParams) *adt.EmptyValue {\n\trt.ValidateImmediateCallerIs(builtin.SystemActorAddr)\n\tAssertMsg(rt.CurrentBalance().GreaterThanEqual(params.GasReward),\n\t\t\"actor current balance %v insufficient to pay gas reward %v\", rt.CurrentBalance(), params.GasReward)\n\n\tAssertMsg(params.TicketCount > 0, \"cannot give block reward for zero tickets\")\n\n\tminer, ok := rt.ResolveAddress(params.Miner)\n\tif !ok {\n\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to resolve given owner address\")\n\t}\n\n\tpriorBalance := rt.CurrentBalance()\n\n\tvar penalty abi.TokenAmount\n\tvar st State\n\trt.State().Transaction(&st, func() interface{} {\n\t\tblockReward := a.computeBlockReward(&st, big.Sub(priorBalance, params.GasReward), params.TicketCount)\n\t\ttotalReward := big.Add(blockReward, params.GasReward)\n\n\t\t// Cap the penalty at the total reward value.\n\t\tpenalty = big.Min(params.Penalty, totalReward)\n\n\t\t// Reduce the payable reward by the penalty.\n\t\trewardPayable := big.Sub(totalReward, penalty)\n\n\t\tAssertMsg(big.Add(rewardPayable, penalty).LessThanEqual(priorBalance),\n\t\t\t\"reward payable %v + penalty %v exceeds balance %v\", rewardPayable, penalty, priorBalance)\n\n\t\t// Record new reward into reward map.\n\t\tif rewardPayable.GreaterThan(abi.NewTokenAmount(0)) {\n\t\t\tnewReward := Reward{\n\t\t\t\tStartEpoch: rt.CurrEpoch(),\n\t\t\t\tEndEpoch: rt.CurrEpoch() + rewardVestingPeriod,\n\t\t\t\tValue: rewardPayable,\n\t\t\t\tAmountWithdrawn: abi.NewTokenAmount(0),\n\t\t\t\tVestingFunction: rewardVestingFunction,\n\t\t\t}\n\t\t\tif err := st.addReward(adt.AsStore(rt), miner, &newReward); err != nil {\n\t\t\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to add reward to rewards map: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\t// Burn the penalty amount.\n\t_, code := rt.Send(builtin.BurntFundsActorAddr, builtin.MethodSend, nil, penalty)\n\tbuiltin.RequireSuccess(rt, code, \"failed to send penalty to BurntFundsActor\")\n\n\treturn nil\n}", "func (cga clawbackGrantAction) AddToAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported,\n\t\t\t\"account %s must be a ClawbackVestingAccount, got %T\",\n\t\t\trawAccount.GetAddress(), rawAccount)\n\t}\n\tif cga.funderAddress != cva.FunderAddress {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"account %s can only accept grants from account %s\",\n\t\t\trawAccount.GetAddress(), cva.FunderAddress)\n\t}\n\tcva.addGrant(ctx, cga.sk, cga.grantStartTime, cga.grantLockupPeriods, cga.grantVestingPeriods, cga.grantCoins)\n\treturn nil\n}", "func (_Token *TokenSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func NewAction() actions.Action {\n\treturn &action{}\n}", "func (_Token *TokenCaller) BaseReward(opts *bind.CallOpts, index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t\tret1 = new(*big.Int)\n\t\tret2 = new(*big.Int)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t}\n\terr := _Token.contract.Call(opts, out, \"baseReward\", index)\n\treturn *ret0, *ret1, *ret2, err\n}", "func CreateAction(\n\tcmd, keyB, id, secretKey string,\n\targs ...interface{}) *types.Action {\n\n\tmac := hmac.New(sha1.New, []byte(secretKey))\n\tmac.Write([]byte(cmd))\n\tmac.Write([]byte(keyB))\n\tmac.Write([]byte(id))\n\tsum := mac.Sum(nil)\n\tsumhex := hex.EncodeToString(sum)\n\n\treturn &types.Action{\n\t\tCommand: cmd,\n\t\tStorageKey: keyB,\n\t\tArgs: args,\n\t\tId: id,\n\t\tSecret: sumhex,\n\t}\n}", "func CreateAction(r *Raptor) *Action {\n\treturn &Action{\n\t\tRaptor: r,\n\t}\n}", "func GetAction(client *whisk.Client, actionName string) func() (*whisk.Action, error) {\n\treturn func() (*whisk.Action, error) {\n\t\taction, _, err := client.Actions.Get(actionName, true)\n\t\tif err == nil {\n\t\t\treturn action, nil\n\t\t}\n\t\treturn nil, err\n\t}\n}", "func NewAction(t *Pos33Ticket, tx *types.Transaction) *Action {\n\thash := tx.Hash()\n\tfromaddr := tx.From()\n\treturn &Action{t.GetCoinsAccount(), t.GetStateDB(), hash, fromaddr,\n\t\tt.GetBlockTime(), t.GetHeight(), dapp.ExecAddress(string(tx.Execer)), t.GetAPI()}\n}", "func (x *fastReflection_MsgWithdrawDelegatorReward) New() protoreflect.Message {\n\treturn new(fastReflection_MsgWithdrawDelegatorReward)\n}", "func (h *Handler) NewAction(act action.Action, settings map[string]interface{}) *Action {\n\n\tvalue := reflect.ValueOf(act)\n\tvalue = value.Elem()\n\tref := value.Type().PkgPath()\n\n\tnewAct := &Action{ref: ref, settings: settings}\n\th.actions = append(h.actions, newAct)\n\n\treturn newAct\n}", "func NewActionAgent(\n\ttabletAlias topo.TabletAlias,\n\tdbcfgs *dbconfigs.DBConfigs,\n\tmycnf *mysqlctl.Mycnf,\n\tport, securePort int,\n\toverridesFile string,\n) (agent *ActionAgent, err error) {\n\tschemaOverrides := loadSchemaOverrides(overridesFile)\n\n\ttopoServer := topo.GetServer()\n\tmysqld := mysqlctl.NewMysqld(\"Dba\", mycnf, &dbcfgs.Dba, &dbcfgs.Repl)\n\n\tagent = &ActionAgent{\n\t\tTopoServer: topoServer,\n\t\tTabletAlias: tabletAlias,\n\t\tMysqld: mysqld,\n\t\tDBConfigs: dbcfgs,\n\t\tSchemaOverrides: schemaOverrides,\n\t\tdone: make(chan struct{}),\n\t\tHistory: history.New(historyLength),\n\t\tchangeItems: make(chan tabletChangeItem, 100),\n\t}\n\n\t// Start the binlog player services, not playing at start.\n\tagent.BinlogPlayerMap = NewBinlogPlayerMap(topoServer, &dbcfgs.App.ConnectionParams, mysqld)\n\tRegisterBinlogPlayerMap(agent.BinlogPlayerMap)\n\n\t// try to figure out the mysql port\n\tmysqlPort := mycnf.MysqlPort\n\tif mysqlPort == 0 {\n\t\t// we don't know the port, try to get it from mysqld\n\t\tvar err error\n\t\tmysqlPort, err = mysqld.GetMysqlPort()\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"Cannot get current mysql port, will use 0 for now: %v\", err)\n\t\t}\n\t}\n\n\tif err := agent.Start(mysqlPort, port, securePort); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// register the RPC services from the agent\n\tagent.registerQueryService()\n\n\t// start health check if needed\n\tagent.initHeathCheck()\n\n\treturn agent, nil\n}", "func newBreachArbiter(wallet *lnwallet.LightningWallet, db *channeldb.DB,\n\tnotifier chainntnfs.ChainNotifier, h *htlcswitch.Switch,\n\tchain lnwallet.BlockChainIO, fe lnwallet.FeeEstimator) *breachArbiter {\n\n\treturn &breachArbiter{\n\t\twallet: wallet,\n\t\tdb: db,\n\t\tnotifier: notifier,\n\t\tchainIO: chain,\n\t\thtlcSwitch: h,\n\t\testimator: fe,\n\n\t\tbreachObservers: make(map[wire.OutPoint]chan struct{}),\n\t\tbreachedContracts: make(chan *retributionInfo),\n\t\tnewContracts: make(chan *lnwallet.LightningChannel),\n\t\tsettledContracts: make(chan *wire.OutPoint),\n\t\tquit: make(chan struct{}),\n\t}\n}", "func NewAction(payload interface{}) Action {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error: %v\\n\", r)\n\t\t\tfmt.Fprintf(os.Stderr, \"Payload: %v\\n\", payload)\n\t\t}\n\t}()\n\n\tvar a Action\n\ta.payload = payload\n\ta.headers = make(map[string]string)\n\n\tfor k, v := range payload.(map[interface{}]interface{}) {\n\t\tswitch k {\n\t\tcase \"catch\":\n\t\t\ta.catch = v.(string)\n\t\tcase \"warnings\":\n\t\t\t// TODO\n\t\t\tcontinue\n\t\tcase \"allowed_warnings\":\n\t\t\t// TODO\n\t\t\tcontinue\n\t\tcase \"node_selector\":\n\t\t\tcontinue\n\t\tcase \"headers\":\n\t\t\tfor kk, vv := range v.(map[interface{}]interface{}) {\n\t\t\t\ta.headers[kk.(string)] = vv.(string)\n\t\t\t}\n\t\tdefault:\n\t\t\ta.method = k.(string)\n\t\t\ta.params = v.(map[interface{}]interface{})\n\t\t}\n\t}\n\n\treturn a\n}", "func (act *ActionTrace) Action() (*ActionTrace, error) {\n\treturn act, nil\n}", "func New() *Action {\n\treturn &Action{w: os.Stdout}\n}", "func (_Token *TokenCaller) CurrentReward(opts *bind.CallOpts, account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\tret := new(struct {\n\t\tInitialDeposit *big.Int\n\t\tReward *big.Int\n\t})\n\tout := ret\n\terr := _Token.contract.Call(opts, out, \"currentReward\", account)\n\treturn *ret, err\n}", "func NewAction(fn ActionFn) *Action {\n\treturn &Action{\n\t\tfn: fn,\n\t\tdoneCh: make(chan struct{}),\n\t}\n}", "func (t *trusteeImpl) NewMiningRewardTx(block consensus.Block) *consensus.Transaction {\n\tvar tx *consensus.Transaction\n\t// build list of miner nodes for uncle blocks\n\tuncleMiners := make([][]byte, len(block.UncleMiners()))\n\tfor i, uncleMiner := range block.UncleMiners() {\n\t\tuncleMiners[i] = uncleMiner\n\t}\n\t\n\tops := make([]Op, 1 + len(uncleMiners))\n\t// first add self's mining reward\n\tops[0] = *t.myReward\n\t\n\t// now add award for each uncle\n\tfor i, uncleMiner := range uncleMiners {\n\t\top := NewOp(OpReward)\n\t\top.Params[ParamUncle] = bytesToHexString(uncleMiner)\n\t\top.Params[ParamAward] = UncleAward\n\t\tops[i+1] = *op \n\t}\n\t// serialize ops into payload\n\tif payload,err := common.Serialize(ops); err != nil {\n\t\tt.log.Error(\"Failed to serialize ops into payload: %s\", err)\n\t\treturn nil\n\t} else {\n\t\t// make a signed transaction out of payload\n\t\tif signature := t.sign(payload); len(signature) > 0 {\n\t\t\t// return the signed transaction\n\t\t\ttx = consensus.NewTransaction(payload, signature, t.myAddress)\n\t\t\tblock.AddTransaction(tx)\n\t\t\tt.process(block, tx)\n\t\t}\n\t}\n\treturn tx\n}", "func NewEvictAction() Action {\n\treturn &evictAction{}\n}", "func NewAuthorizeAction(ctx context.Context, viper *viper.Viper, authMode string,\n\tlocalAuthController *local.Controller, bkiamAuthController *bkiam.Controller,\n\treq *pb.AuthorizeReq, resp *pb.AuthorizeResp) *AuthorizeAction {\n\n\taction := &AuthorizeAction{\n\t\tctx: ctx,\n\t\tviper: viper,\n\t\tauthMode: authMode,\n\t\tlocalAuthController: localAuthController,\n\t\tbkiamAuthController: bkiamAuthController,\n\t\treq: req,\n\t\tresp: resp,\n\t}\n\n\taction.resp.Seq = req.Seq\n\taction.resp.Code = pbcommon.ErrCode_E_OK\n\taction.resp.Message = \"OK\"\n\n\treturn action\n}", "func NewSecretAction(logger logrus.FieldLogger, client client.Client) *SecretAction {\n\treturn &SecretAction{\n\t\tlogger: logger,\n\t\tclient: client,\n\t}\n}", "func (dm *DelveMode) RestAction() data.Action {\n\treturn func(e *data.Entity) {\n\t\te.NextTurn += 1\n\t}\n}", "func (ca clawbackAction) TakeFromAccount(ctx sdk.Context, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported, \"clawback expects *ClawbackVestingAccount, got %T\", rawAccount)\n\t}\n\tif ca.requestor.String() != cva.FunderAddress {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"clawback can only be requested by original funder %s\", cva.FunderAddress)\n\t}\n\treturn cva.clawback(ctx, ca.dest, ca.ak, ca.bk, ca.sk)\n}", "func (va *ClawbackVestingAccount) computeClawback(clawbackTime int64) sdk.Coins {\n\t// Compute the truncated vesting schedule and amounts.\n\t// Work with the schedule as the primary data and recompute derived fields, e.g. OriginalVesting.\n\tvestTime := va.StartTime\n\ttotalVested := sdk.NewCoins()\n\ttotalUnvested := sdk.NewCoins()\n\tunvestedIdx := 0\n\tfor i, period := range va.VestingPeriods {\n\t\tvestTime += period.Length\n\t\t// tie in time goes to clawback\n\t\tif vestTime < clawbackTime {\n\t\t\ttotalVested = totalVested.Add(period.Amount...)\n\t\t\tunvestedIdx = i + 1\n\t\t} else {\n\t\t\ttotalUnvested = totalUnvested.Add(period.Amount...)\n\t\t}\n\t}\n\tlastVestTime := vestTime\n\tnewVestingPeriods := va.VestingPeriods[:unvestedIdx]\n\n\t// To cap the unlocking schedule to the new total vested, conjunct with a limiting schedule\n\tcapPeriods := []Period{\n\t\t{\n\t\t\tLength: 0,\n\t\t\tAmount: totalVested,\n\t\t},\n\t}\n\t_, lastLockTime, newLockupPeriods := ConjunctPeriods(va.StartTime, va.StartTime, va.LockupPeriods, capPeriods)\n\n\t// Now construct the new account state\n\tva.OriginalVesting = totalVested\n\tva.EndTime = max64(lastVestTime, lastLockTime)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\t// DelegatedVesting and DelegatedFree will be adjusted elsewhere\n\n\treturn totalUnvested\n}", "func (qiu *QueueItemUpdate) AddAction(i int) *QueueItemUpdate {\n\tqiu.mutation.AddAction(i)\n\treturn qiu\n}", "func NewStalemate() Outcome { return Outcome{Winner: Transparent, Reason: stalemate} }", "func NewSendAction(serviceType, actionName string, args any) *Action {\n\treturn &Action{\n\t\tXMLName: xml.Name{Space: serviceType, Local: actionName},\n\t\tArgs: args,\n\t}\n}", "func NewCheck() beekeeper.Action {\n\treturn &Check{}\n}", "func (_IStakingRewards *IStakingRewardsTransactor) GetReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _IStakingRewards.contract.Transact(opts, \"getReward\")\n}", "func NewShowAction() *ShowAction {\n\treturn &ShowAction{}\n}", "func (_Smartchef *SmartchefTransactor) StopReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Smartchef.contract.Transact(opts, \"stopReward\")\n}", "func NewEventRuleAction() *EventRuleAction {\n\tthis := EventRuleAction{}\n\tvar actionTaken WafRuleAction = \"BLOCK\"\n\tthis.ActionTaken = &actionTaken\n\tvar requestType EventWafRequestType = \"CHALLENGE\"\n\tthis.RequestType = &requestType\n\tvar result RuleActionResultType = \"RESULT_TYPE_UNSPECIFIED\"\n\tthis.Result = &result\n\treturn &this\n}", "func NewActionInspect(target ID, cost time.Duration) *ActionInspect {\n\treturn &ActionInspect{\n\t\t// FIXME: Figure out the actual base costs of inspection.\n\t\tAction: Action{\n\t\t\tchannel: cost / 4,\n\t\t\trecovery: cost - cost/4,\n\t\t},\n\t\tTarget: target,\n\t}\n}", "func MakeReweigh(db *pop.Connection, assertions Assertions) models.Reweigh {\n\tshipment := assertions.MTOShipment\n\tif isZeroUUID(shipment.ID) {\n\t\tassertions.MTOShipment.Status = models.MTOShipmentStatusApproved\n\t\tshipment = MakeMTOShipment(db, assertions)\n\t}\n\n\treweigh := models.Reweigh{\n\t\tRequestedAt: time.Now(),\n\t\tRequestedBy: models.ReweighRequesterTOO,\n\t\tShipment: shipment,\n\t\tShipmentID: shipment.ID,\n\t}\n\n\tmergeModels(&reweigh, assertions.Reweigh)\n\n\tmustCreate(db, &reweigh, assertions.Stub)\n\n\treturn reweigh\n}", "func (x *fastReflection_MsgWithdrawDelegatorRewardResponse) New() protoreflect.Message {\n\treturn new(fastReflection_MsgWithdrawDelegatorRewardResponse)\n}", "func (_Token *TokenCallerSession) CurrentReward(account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\treturn _Token.Contract.CurrentReward(&_Token.CallOpts, account)\n}", "func (_SweetToken *SweetTokenTransactor) Burn(opts *bind.TransactOpts, wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.contract.Transact(opts, \"burn\", wad)\n}", "func (s *MutableState) AddRewards(time epochtime.EpochTime, factor *quantity.Quantity, accounts []signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tfor _, id := range accounts {\n\t\tent := s.Account(id)\n\n\t\tq := ent.Escrow.Active.Balance.Clone()\n\t\t// Multiply first.\n\t\tif err := q.Mul(factor); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t\t}\n\t\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t\t}\n\t\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t\t}\n\n\t\tif q.IsZero() {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar com *quantity.Quantity\n\t\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\t\tif rate != nil {\n\t\t\tcom = q.Clone()\n\t\t\t// Multiply first.\n\t\t\tif err := com.Mul(rate); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t\t}\n\t\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t\t}\n\n\t\t\tif err := q.Sub(com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t\t}\n\t\t}\n\n\t\tif !q.IsZero() {\n\t\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t\t}\n\t\t}\n\n\t\tif com != nil && !com.IsZero() {\n\t\t\tdelegation := s.Delegation(id, id)\n\n\t\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t\t}\n\n\t\t\ts.SetDelegation(id, id, delegation)\n\t\t}\n\n\t\ts.SetAccount(id, ent)\n\t}\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func (c *Coinbase) AddReward(output *Output) {\n\toutput.EncryptedMask = make([]byte, 1)\n\tc.Rewards = append(c.Rewards, output)\n}", "func (_Smartchef *SmartchefTransactorSession) StopReward() (*types.Transaction, error) {\n\treturn _Smartchef.Contract.StopReward(&_Smartchef.TransactOpts)\n}", "func (_Token *TokenSession) CurrentReward(account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\treturn _Token.Contract.CurrentReward(&_Token.CallOpts, account)\n}", "func NewRewardTx(coinbase common.Address, reward *big.Int, timestamp uint64) (*types.Transaction, error) {\n\tif err := validateReward(reward); err != nil {\n\t\treturn nil, err\n\t}\n\n\ttxData := types.TransactionData{\n\t\tType: types.TxTypeReward,\n\t\tFrom: common.EmptyAddress,\n\t\tTo: coinbase,\n\t\tAmount: new(big.Int).Set(reward),\n\t\tGasPrice: common.Big0,\n\t\tTimestamp: timestamp,\n\t\tPayload: emptyPayload,\n\t}\n\n\ttx := types.Transaction{\n\t\tHash: crypto.MustHash(txData),\n\t\tData: txData,\n\t\tSignature: emptySig,\n\t}\n\n\treturn &tx, nil\n}", "func (qiuo *QueueItemUpdateOne) AddAction(i int) *QueueItemUpdateOne {\n\tqiuo.mutation.AddAction(i)\n\treturn qiuo\n}", "func NewAction(name string) *Action {\n\ta := &Action{\n\t\tName: name,\n\t\tEnabled: true,\n\t}\n\treturn a\n}", "func (_SweetToken *SweetTokenTransactorSession) Burn(wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.Contract.Burn(&_SweetToken.TransactOpts, wad)\n}", "func NewLogAction() Action {\n\treturn &logAction{}\n}", "func toAction(actionInput string) (GameAction, error) {\n\tnormalised := strings.ToUpper(strings.TrimSuffix(actionInput, \"\\n\"))\n\tif len(normalised) < 1 {\n\t\treturn -1, errors.New(\"No action specified\")\n\t}\n\n\tswitch normalised[0] {\n\tcase 'E':\n\t\treturn Explore, nil\n\n\tcase 'F':\n\t\treturn Flag, nil\n\n\tdefault:\n\t\treturn -1, errors.New(\"Invalid action\")\n\t}\n}", "func CreateBackupAction(service *pgCommon.PostgresServiceInformations) action.IAction {\n\treturn action.FormAction{\n\t\tName: \"Backup\",\n\t\tUniqueCommand: \"cmd_pg_create_backup\",\n\t\tPlaceholder: nil,\n\t\tActionExecuteCallback: func(placeholder interface{}) (interface{}, error) {\n\t\t\treturn nil, CreateBackup(service)\n\t\t},\n\t}\n}", "func (ra *RecoverableAction) Action(action Action) string {\n\tra.actionChan <- action\n\n\treturn <-ra.replyChan\n}", "func (a *Agent) Action(state, goal *tensor.Dense) (action int, err error) {\n\ta.steps++\n\tdefer func() { a.epsilon.Set(a.Epsilon.Value()) }()\n\tif rand.Float64() < a.epsilon.Scalar() {\n\t\t// explore\n\t\taction, err = a.env.SampleAction()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tlog.Infov(\"taking random action\", action)\n\t\treturn\n\t}\n\taction, err = a.action(state, goal)\n\tlog.Infov(\"taking action\", action)\n\treturn\n}", "func CreateAction(action func(*cli.Context) error) func(*cli.Context) error {\n\treturn func(c *cli.Context) error {\n\t\terr := action(c)\n\t\tif err != nil {\n\t\t\tiocli.Error(\"%s\", err)\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func (_Smartchef *SmartchefSession) StopReward() (*types.Transaction, error) {\n\treturn _Smartchef.Contract.StopReward(&_Smartchef.TransactOpts)\n}", "func (_IERC20Minter *IERC20MinterTransactor) Burn(opts *bind.TransactOpts, amount *big.Int) (*types.Transaction, error) {\n\treturn _IERC20Minter.contract.Transact(opts, \"burn\", amount)\n}", "func (_IStakingRewards *IStakingRewardsTransactorSession) GetReward() (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.GetReward(&_IStakingRewards.TransactOpts)\n}", "func (_XStaking *XStakingTransactor) GetReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _XStaking.contract.Transact(opts, \"getReward\")\n}", "func claim(args []string) (string, error) {\n\tamount, err := util.StringToRau(args[0], util.IotxDecimalNum)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tpayload := make([]byte, 0)\n\tif len(args) == 2 {\n\t\tpayload = []byte(args[1])\n\t}\n\tsender, err := alias.Address(signer)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif gasLimit == 0 {\n\t\tgasLimit = action.ClaimFromRewardingFundBaseGas +\n\t\t\taction.ClaimFromRewardingFundGasPerByte*uint64(len(payload))\n\t}\n\tvar gasPriceRau *big.Int\n\tif len(gasPrice) == 0 {\n\t\tgasPriceRau, err = GetGasPrice()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t} else {\n\t\tgasPriceRau, err = util.StringToRau(gasPrice, util.GasPriceDecimalNum)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tif nonce == 0 {\n\t\taccountMeta, err := account.GetAccountMeta(sender)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tnonce = accountMeta.PendingNonce\n\t}\n\tb := &action.ClaimFromRewardingFundBuilder{}\n\tact := b.SetAmount(amount).SetData(payload).Build()\n\tbd := &action.EnvelopeBuilder{}\n\telp := bd.SetNonce(nonce).\n\t\tSetGasPrice(gasPriceRau).\n\t\tSetGasLimit(gasLimit).\n\t\tSetAction(&act).Build()\n\treturn sendAction(elp)\n}", "func NewDrawByAgreement() Outcome { return Outcome{Winner: Transparent, Reason: drawByAgreement} }", "func ActionFromInt(st int) Action {\n\tact := Action{}\n\tif st%2 == 1 {\n\t\tact.PlayRecent = true\n\t}\n\n\tst = (st & 0xF) >> 1\n\t// Now st is the TargetPlayerOffset or SelectedCard. We don't know which, but if *any* card was selected,\n\t// then the other player must be targeted (since the played card is a guard), so for 2 players the offset is 1.\n\tif st > 0 {\n\t\tact.TargetPlayerOffset = 1\n\t}\n\tact.SelectedCard = Card(st + 1)\n\treturn act\n}", "func NewAction(cmd Command) Action {\n\tswitch cmd.name {\n\tcase buildCommand:\n\t\treturn NewBuildAction(afero.NewOsFs(), cmd.helmRepoName, cmd.artifactsPath)\n\tdefault:\n\t\treturn ShowAction{}\n\t}\n}", "func (_DetailedTestToken *DetailedTestTokenTransactorSession) Burn(_from common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.Contract.Burn(&_DetailedTestToken.TransactOpts, _from, _amount)\n}", "func (b *AccessReviewRequestBuilder) Action(value string) *AccessReviewRequestBuilder {\n\tb.action = value\n\tb.bitmap_ |= 2\n\treturn b\n}", "func (c RewardsController) CollectReward(id string) revel.Result {\n\tif !c.GetCurrentUser() {\n\t\treturn c.ForbiddenResponse()\n\t}\n\n\tif !bson.IsObjectIdHex(id) {\n\t\treturn c.ErrorResponse(nil, c.Message(\"error.invalid\", \"\"), core.ModelStatus[core.StatusInvalidID])\n\t}\n\n\tvar selector = []bson.M{\n\t\tbson.M{\"user_id\": c.CurrentUser.GetID().Hex()},\n\t\tbson.M{\"_id\": id},\n\t\tbson.M{\"multi\": false},\n\t}\n\tvar query = bson.M{\"$set\": []bson.M{\n\t\tbson.M{\"status.name\": core.StatusObtained},\n\t\tbson.M{\"status.code\": core.ValidationStatus[core.StatusObtained]},\n\t}}\n\n\t// Get pending Rewards for the user\n\tif Reward, ok := app.Mapper.GetModel(&models.Reward{}); ok {\n\t\tif err := Reward.UpdateQuery(selector, query, false); err != nil {\n\t\t\trevel.ERROR.Print(\"ERROR Find\")\n\t\t\treturn c.ErrorResponse(err, err.Error(), 400)\n\t\t}\n\t\treturn c.SuccessResponse(bson.M{\"data\": \"Reward collected successfully\"}, \"success\", core.ModelsType[core.ModelSimpleResponse], nil)\n\t}\n\n\treturn c.ServerErrorResponse()\n}", "func (s SubTransaction) ForwardAction() Action {\n\treturn s.forward\n}", "func Create(\n\tcontext contexts.Contextable,\n\tlogger *logger.Logger,\n\tconnection *golastic.Connection,\n\tqueue *notifications.Queue,\n\tctx context.Context,\n) (Actionable, error) {\n\taction, err := build(context.Action())\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := action.Init(context, logger, connection, queue, ctx); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := action.ApplyOptions().ApplyFilters(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn action, nil\n}", "func (_SweetToken *SweetTokenSession) Burn(wad *big.Int) (*types.Transaction, error) {\n\treturn _SweetToken.Contract.Burn(&_SweetToken.TransactOpts, wad)\n}", "func ViewReward(rw http.ResponseWriter, r *http.Request) {\n\t// get the token\n\treqToken := r.Header.Get(\"Authorization\")\n\t\n\t// get the claims\n\tclaims, isNotValid := GetClaims(reqToken, rw)\n\tif isNotValid {\n\t\treturn\n\t}\n\n\tdt, err := db.GetUserRewards(claims.Roll)\n\tif err != nil {\n\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\trw.Write(Rsp(err.Error(), \"Server Error\"))\n\t\treturn\n\t}\n\trw.WriteHeader(http.StatusOK)\n\tres := c.RespData{\n\t\tMessage: \"All data\",\n\t\tData: dt,\n\t}\n\tjson.NewEncoder(rw).Encode(res)\n}", "func (a *ReturnTrolleyAction) DeepCopyAction() Action {\n\treturn a.DeepCopy()\n}", "func NewEventRuleActionWithDefaults() *EventRuleAction {\n\tthis := EventRuleAction{}\n\tvar actionTaken WafRuleAction = \"BLOCK\"\n\tthis.ActionTaken = &actionTaken\n\tvar requestType EventWafRequestType = \"CHALLENGE\"\n\tthis.RequestType = &requestType\n\tvar result RuleActionResultType = \"RESULT_TYPE_UNSPECIFIED\"\n\tthis.Result = &result\n\treturn &this\n}", "func MiningRewardBalance(block consensus.Block, account []byte) *RTU {\n//\tif bytes, err := block.Lookup([]byte(bytesToHexString(account))); err == nil {\n\tif bytes, err := block.Lookup(account); err == nil {\n\t\treturn BytesToRtu(bytes)\n\t}\n\treturn BytesToRtu(nil)\n}", "func (_XStaking *XStakingTransactorSession) GetReward() (*types.Transaction, error) {\n\treturn _XStaking.Contract.GetReward(&_XStaking.TransactOpts)\n}", "func NewWithWriter(w io.Writer) *Action {\n\treturn &Action{w: w}\n}", "func NewOutcomeNotCompleted() Outcome { return Outcome{Winner: Transparent, Reason: notCompleted} }", "func NewListAction(model store.ProjectModel) *ListAction {\n\treturn &ListAction{\n\t\tmodel: model,\n\t}\n}", "func (_DetailedTestToken *DetailedTestTokenTransactor) Burn(opts *bind.TransactOpts, _from common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.contract.Transact(opts, \"burn\", _from, _amount)\n}" ]
[ "0.7404201", "0.6953166", "0.5464461", "0.53948647", "0.5364549", "0.52774936", "0.5242982", "0.51873976", "0.5161824", "0.51156837", "0.5114475", "0.5087842", "0.5044298", "0.4955228", "0.49131867", "0.48881137", "0.4860685", "0.48492974", "0.48389384", "0.48261693", "0.48073062", "0.4806934", "0.47948968", "0.47775978", "0.47775978", "0.47685742", "0.4763258", "0.47577775", "0.4755035", "0.4744198", "0.47240314", "0.47206163", "0.47000334", "0.46924087", "0.46889618", "0.4676094", "0.46661752", "0.46485558", "0.45820913", "0.4581459", "0.45421323", "0.4524639", "0.4506681", "0.4499991", "0.44623595", "0.44439712", "0.44408196", "0.44202092", "0.44117185", "0.437283", "0.43673515", "0.43633744", "0.43479988", "0.43374288", "0.43325737", "0.43264967", "0.4321511", "0.43210125", "0.43131346", "0.43083677", "0.42984998", "0.42921782", "0.42878333", "0.42831647", "0.4270413", "0.42682657", "0.42569688", "0.42564178", "0.42544532", "0.42497995", "0.42399403", "0.423938", "0.42342055", "0.42323777", "0.42239317", "0.42190844", "0.42179886", "0.42167017", "0.4210979", "0.42095917", "0.41938713", "0.41894215", "0.4184966", "0.4183407", "0.41826695", "0.41709533", "0.41607255", "0.41501132", "0.41435888", "0.41435602", "0.41292846", "0.4124662", "0.412181", "0.41193622", "0.41142455", "0.4112855", "0.41126797", "0.4112431", "0.41072062", "0.4106683" ]
0.8147421
0
ProcessReward implements the exported.RewardAction interface.
func (cra clawbackRewardAction) ProcessReward(ctx sdk.Context, reward sdk.Coins, rawAccount exported.VestingAccount) error { cva, ok := rawAccount.(*ClawbackVestingAccount) if !ok { return sdkerrors.Wrapf(sdkerrors.ErrNotSupported, "expected *ClawbackVestingAccount, got %T", rawAccount) } cva.postReward(ctx, reward, cra.ak, cra.bk, cra.sk) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (vi *votedInfo) CalculateReward(multiplier, divider *big.Int, period int) {\n\tif multiplier.Sign() == 0 || period == 0 {\n\t\treturn\n\t}\n\tif divider.Sign() == 0 || vi.totalBondedDelegation.Sign() == 0 {\n\t\treturn\n\t}\n\t// reward = multiplier * period * bondedDelegation / (divider * totalBondedDelegation)\n\tbase := new(big.Int).Mul(multiplier, big.NewInt(int64(period)))\n\treward := new(big.Int)\n\tfor i, addrKey := range vi.rank {\n\t\tif i == vi.maxRankForReward {\n\t\t\tbreak\n\t\t}\n\t\tprep := vi.preps[addrKey]\n\t\tif prep.Enable() == false {\n\t\t\tcontinue\n\t\t}\n\n\t\treward.Mul(base, prep.GetBondedDelegation())\n\t\treward.Div(reward, divider)\n\t\treward.Div(reward, vi.totalBondedDelegation)\n\n\t\tlog.Tracef(\"VOTED REWARD %d = %d * %d * %d / (%d * %d)\",\n\t\t\treward, multiplier, period, prep.GetBondedDelegation(), divider, vi.totalBondedDelegation)\n\n\t\tprep.SetIScore(new(big.Int).Add(prep.IScore(), reward))\n\t}\n}", "func (c RewardsController) CollectReward(id string) revel.Result {\n\tif !c.GetCurrentUser() {\n\t\treturn c.ForbiddenResponse()\n\t}\n\n\tif !bson.IsObjectIdHex(id) {\n\t\treturn c.ErrorResponse(nil, c.Message(\"error.invalid\", \"\"), core.ModelStatus[core.StatusInvalidID])\n\t}\n\n\tvar selector = []bson.M{\n\t\tbson.M{\"user_id\": c.CurrentUser.GetID().Hex()},\n\t\tbson.M{\"_id\": id},\n\t\tbson.M{\"multi\": false},\n\t}\n\tvar query = bson.M{\"$set\": []bson.M{\n\t\tbson.M{\"status.name\": core.StatusObtained},\n\t\tbson.M{\"status.code\": core.ValidationStatus[core.StatusObtained]},\n\t}}\n\n\t// Get pending Rewards for the user\n\tif Reward, ok := app.Mapper.GetModel(&models.Reward{}); ok {\n\t\tif err := Reward.UpdateQuery(selector, query, false); err != nil {\n\t\t\trevel.ERROR.Print(\"ERROR Find\")\n\t\t\treturn c.ErrorResponse(err, err.Error(), 400)\n\t\t}\n\t\treturn c.SuccessResponse(bson.M{\"data\": \"Reward collected successfully\"}, \"success\", core.ModelsType[core.ModelSimpleResponse], nil)\n\t}\n\n\treturn c.ServerErrorResponse()\n}", "func GetReward(a Action, feedback Action) float64 {\n\tif a == feedback {\n\t\treturn 1\n\t}\n\treturn -1\n}", "func (c *Coinbase) AddReward(output *Output) {\n\toutput.EncryptedMask = make([]byte, 1)\n\tc.Rewards = append(c.Rewards, output)\n}", "func (va *ClawbackVestingAccount) PostReward(ctx sdk.Context, reward sdk.Coins, action exported.RewardAction) error {\n\treturn action.ProcessReward(ctx, reward, va)\n}", "func (a Actor) AwardBlockReward(rt vmr.Runtime, params *AwardBlockRewardParams) *adt.EmptyValue {\n\trt.ValidateImmediateCallerIs(builtin.SystemActorAddr)\n\tAssertMsg(rt.CurrentBalance().GreaterThanEqual(params.GasReward),\n\t\t\"actor current balance %v insufficient to pay gas reward %v\", rt.CurrentBalance(), params.GasReward)\n\n\tAssertMsg(params.TicketCount > 0, \"cannot give block reward for zero tickets\")\n\n\tminer, ok := rt.ResolveAddress(params.Miner)\n\tif !ok {\n\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to resolve given owner address\")\n\t}\n\n\tpriorBalance := rt.CurrentBalance()\n\n\tvar penalty abi.TokenAmount\n\tvar st State\n\trt.State().Transaction(&st, func() interface{} {\n\t\tblockReward := a.computeBlockReward(&st, big.Sub(priorBalance, params.GasReward), params.TicketCount)\n\t\ttotalReward := big.Add(blockReward, params.GasReward)\n\n\t\t// Cap the penalty at the total reward value.\n\t\tpenalty = big.Min(params.Penalty, totalReward)\n\n\t\t// Reduce the payable reward by the penalty.\n\t\trewardPayable := big.Sub(totalReward, penalty)\n\n\t\tAssertMsg(big.Add(rewardPayable, penalty).LessThanEqual(priorBalance),\n\t\t\t\"reward payable %v + penalty %v exceeds balance %v\", rewardPayable, penalty, priorBalance)\n\n\t\t// Record new reward into reward map.\n\t\tif rewardPayable.GreaterThan(abi.NewTokenAmount(0)) {\n\t\t\tnewReward := Reward{\n\t\t\t\tStartEpoch: rt.CurrEpoch(),\n\t\t\t\tEndEpoch: rt.CurrEpoch() + rewardVestingPeriod,\n\t\t\t\tValue: rewardPayable,\n\t\t\t\tAmountWithdrawn: abi.NewTokenAmount(0),\n\t\t\t\tVestingFunction: rewardVestingFunction,\n\t\t\t}\n\t\t\tif err := st.addReward(adt.AsStore(rt), miner, &newReward); err != nil {\n\t\t\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to add reward to rewards map: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\t// Burn the penalty amount.\n\t_, code := rt.Send(builtin.BurntFundsActorAddr, builtin.MethodSend, nil, penalty)\n\tbuiltin.RequireSuccess(rt, code, \"failed to send penalty to BurntFundsActor\")\n\n\treturn nil\n}", "func EstimateReward(reward, pr, gamma float64) float64 {\n\tret := reward / (pr + gamma)\n\tlog.Logf(MABLogLevel, \"MAB Estimate Reward: %v / (%v + %v) = %v\\n\",\n\t\treward, pr, gamma, ret)\n\treturn ret\n}", "func (s *BlocksService) Reward(ctx context.Context) (*BlocksReward, *http.Response, error) {\n\tvar responseStruct *BlocksReward\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"blocks/getReward\", nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (_Token *TokenCallerSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (_Token *TokenCaller) BaseReward(opts *bind.CallOpts, index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t\tret1 = new(*big.Int)\n\t\tret2 = new(*big.Int)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t}\n\terr := _Token.contract.Call(opts, out, \"baseReward\", index)\n\treturn *ret0, *ret1, *ret2, err\n}", "func (d *Dao) AddReward(c context.Context, iRewardID int64, uid int64, iSource int64, iRoomid int64, iLifespan int64) (err error) {\n\t//aReward, _ := getRewardConfByLid(iRewardID)\n\n\tm, _ := time.ParseDuration(fmt.Sprintf(\"+%dh\", iLifespan))\n\n\targ := &AnchorTaskModel.AnchorReward{\n\t\tUid: uid,\n\t\tRewardId: iRewardID,\n\t\tRoomid: iRoomid,\n\t\tSource: iSource,\n\t\tAchieveTime: xtime.Time(time.Now().Unix()),\n\t\tExpireTime: xtime.Time(time.Now().Add(m).Unix()),\n\t\tStatus: model.RewardUnUsed,\n\t}\n\n\t//spew.Dump\n\t// (arg)\n\tif err := d.orm.Create(arg).Error; err != nil {\n\t\tlog.Error(\"addReward(%v) error(%v)\", arg, err)\n\t\treturn err\n\t}\n\n\tif err := d.SetNewReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"addRewardMc(%v) error(%v)\", uid, err)\n\t}\n\n\tif err := d.SetHasReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"SetHasReward(%v) error(%v)\", uid, err)\n\t}\n\n\tlog.Info(\"addReward (%v) succ\", arg)\n\n\treturn\n}", "func (k Querier) Rewards(c context.Context, req *types.QueryRewardsRequest) (*types.QueryRewardsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"invalid request\")\n\t}\n\n\tif req.StakingCoinDenom != \"\" {\n\t\tif err := sdk.ValidateDenom(req.StakingCoinDenom); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tctx := sdk.UnwrapSDKContext(c)\n\tstore := ctx.KVStore(k.storeKey)\n\tvar rewards []types.Reward\n\tvar pageRes *query.PageResponse\n\tvar err error\n\n\tif req.Farmer != \"\" {\n\t\tvar farmerAcc sdk.AccAddress\n\t\tfarmerAcc, err = sdk.AccAddressFromBech32(req.Farmer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tstorePrefix := types.GetRewardsByFarmerIndexKey(farmerAcc)\n\t\tindexStore := prefix.NewStore(store, storePrefix)\n\t\tpageRes, err = query.FilteredPaginate(indexStore, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) {\n\t\t\t_, stakingCoinDenom := types.ParseRewardsByFarmerIndexKey(append(storePrefix, key...))\n\t\t\tif req.StakingCoinDenom != \"\" {\n\t\t\t\tif stakingCoinDenom != req.StakingCoinDenom {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treward, found := k.GetReward(ctx, stakingCoinDenom, farmerAcc)\n\t\t\tif !found { // TODO: remove this check\n\t\t\t\treturn false, fmt.Errorf(\"reward not found\")\n\t\t\t}\n\t\t\tif accumulate {\n\t\t\t\trewards = append(rewards, reward)\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n\t} else {\n\t\tvar storePrefix []byte\n\t\tif req.StakingCoinDenom != \"\" {\n\t\t\tstorePrefix = types.GetRewardsByStakingCoinDenomKey(req.StakingCoinDenom)\n\t\t} else {\n\t\t\tstorePrefix = types.RewardKeyPrefix\n\t\t}\n\t\trewardStore := prefix.NewStore(store, storePrefix)\n\n\t\tpageRes, err = query.Paginate(rewardStore, req.Pagination, func(key, value []byte) error {\n\t\t\tstakingCoinDenom, farmerAcc := types.ParseRewardKey(append(storePrefix, key...))\n\t\t\trewardCoins, err := k.UnmarshalRewardCoins(value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\trewards = append(rewards, types.Reward{\n\t\t\t\tFarmer: farmerAcc.String(),\n\t\t\t\tStakingCoinDenom: stakingCoinDenom,\n\t\t\t\tRewardCoins: rewardCoins.RewardCoins,\n\t\t\t})\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryRewardsResponse{Rewards: rewards, Pagination: pageRes}, nil\n}", "func ViewReward(rw http.ResponseWriter, r *http.Request) {\n\t// get the token\n\treqToken := r.Header.Get(\"Authorization\")\n\t\n\t// get the claims\n\tclaims, isNotValid := GetClaims(reqToken, rw)\n\tif isNotValid {\n\t\treturn\n\t}\n\n\tdt, err := db.GetUserRewards(claims.Roll)\n\tif err != nil {\n\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\trw.Write(Rsp(err.Error(), \"Server Error\"))\n\t\treturn\n\t}\n\trw.WriteHeader(http.StatusOK)\n\tres := c.RespData{\n\t\tMessage: \"All data\",\n\t\tData: dt,\n\t}\n\tjson.NewEncoder(rw).Encode(res)\n}", "func (_Token *TokenSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (node *TreeNode) backpropagateReward(scores [2]float64) {\n\tcurrentNode := node\n\tfor currentNode.Parent != nil {\n\t\tcurrentNode.VisitCount += 1.0\n\t\tcurrentNode.CumulativeScore[0] += scores[0]\n\t\tcurrentNode.CumulativeScore[1] += scores[1]\n\t\tcurrentNode = currentNode.Parent\n\t}\n\t//Increment root node counter\n\tcurrentNode.VisitCount += 1.0\n}", "func (d *Dao) UseReward(id int64, usePlat string) (rst bool, err error) {\n\tif err := d.orm.\n\t\tModel(&model.AnchorReward{}).\n\t\tWhere(\"id=?\", id).\n\t\tUpdate(map[string]interface{}{\"status\": model.RewardUsed, \"use_plat\": usePlat, \"use_time\": xtime.Time(time.Now().Unix())}).Error; err != nil {\n\t\tlog.Error(\"useReward (%v) error(%v)\", id, err)\n\t\treturn rst, err\n\t}\n\trst = true\n\treturn\n}", "func accumulateRewards(config *params.ChainConfig, state *state.DB, header *types.Header) {\n\t// TODO: implement mining rewards\n}", "func (va ClawbackVestingAccount) distributeReward(ctx sdk.Context, ak AccountKeeper, bondDenom string, reward sdk.Coins) {\n\tnow := ctx.BlockTime().Unix()\n\tt := va.StartTime\n\tfirstUnvestedPeriod := 0\n\tunvestedTokens := sdk.ZeroInt()\n\tfor i, period := range va.VestingPeriods {\n\t\tt += period.Length\n\t\tif t <= now {\n\t\t\tfirstUnvestedPeriod = i + 1\n\t\t\tcontinue\n\t\t}\n\t\tunvestedTokens = unvestedTokens.Add(period.Amount.AmountOf(bondDenom))\n\t}\n\n\trunningTotReward := sdk.NewCoins()\n\trunningTotStaking := sdk.ZeroInt()\n\tfor i := firstUnvestedPeriod; i < len(va.VestingPeriods); i++ {\n\t\tperiod := va.VestingPeriods[i]\n\t\trunningTotStaking = runningTotStaking.Add(period.Amount.AmountOf(bondDenom))\n\t\trunningTotRatio := runningTotStaking.ToDec().Quo(unvestedTokens.ToDec())\n\t\ttargetCoins := scaleCoins(reward, runningTotRatio)\n\t\tthisReward := targetCoins.Sub(runningTotReward)\n\t\trunningTotReward = targetCoins\n\t\tperiod.Amount = period.Amount.Add(thisReward...)\n\t\tva.VestingPeriods[i] = period\n\t}\n\n\tva.OriginalVesting = va.OriginalVesting.Add(reward...)\n\tak.SetAccount(ctx, &va)\n}", "func (_Contract *ContractCaller) TaskHandlingReward(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"taskHandlingReward\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_Lmc *LmcCaller) GetUserAccumulatedReward(opts *bind.CallOpts, _userAddress common.Address, tokenIndex *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Lmc.contract.Call(opts, &out, \"getUserAccumulatedReward\", _userAddress, tokenIndex)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_XStaking *XStakingFilterer) FilterRewardPaid(opts *bind.FilterOpts, user []common.Address) (*XStakingRewardPaidIterator, error) {\n\n\tvar userRule []interface{}\n\tfor _, userItem := range user {\n\t\tuserRule = append(userRule, userItem)\n\t}\n\n\tlogs, sub, err := _XStaking.contract.FilterLogs(opts, \"RewardPaid\", userRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &XStakingRewardPaidIterator{contract: _XStaking.contract, event: \"RewardPaid\", logs: logs, sub: sub}, nil\n}", "func (s *MutableState) AddRewardSingleAttenuated(time epochtime.EpochTime, factor *quantity.Quantity, attenuationNumerator, attenuationDenominator int, account signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tvar numQ, denQ quantity.Quantity\n\tif err = numQ.FromInt64(int64(attenuationNumerator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation numerator %d\", attenuationNumerator)\n\t}\n\tif err = denQ.FromInt64(int64(attenuationDenominator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation denominator %d\", attenuationDenominator)\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tent := s.Account(account)\n\n\tq := ent.Escrow.Active.Balance.Clone()\n\t// Multiply first.\n\tif err := q.Mul(factor); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t}\n\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t}\n\tif err := q.Mul(&numQ); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by attenuation numerator\")\n\t}\n\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t}\n\tif err := q.Quo(&denQ); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by attenuation denominator\")\n\t}\n\n\tif q.IsZero() {\n\t\treturn nil\n\t}\n\n\tvar com *quantity.Quantity\n\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\tif rate != nil {\n\t\tcom = q.Clone()\n\t\t// Multiply first.\n\t\tif err := com.Mul(rate); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t}\n\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t}\n\n\t\tif err := q.Sub(com); err != nil {\n\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t}\n\t}\n\n\tif !q.IsZero() {\n\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t}\n\t}\n\n\tif com != nil && !com.IsZero() {\n\t\tdelegation := s.Delegation(account, account)\n\n\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t}\n\n\t\ts.SetDelegation(account, account, delegation)\n\t}\n\n\ts.SetAccount(account, ent)\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func (_XStaking *XStakingFilterer) FilterRewardAdded(opts *bind.FilterOpts) (*XStakingRewardAddedIterator, error) {\n\n\tlogs, sub, err := _XStaking.contract.FilterLogs(opts, \"RewardAdded\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &XStakingRewardAddedIterator{contract: _XStaking.contract, event: \"RewardAdded\", logs: logs, sub: sub}, nil\n}", "func (_IStakingRewards *IStakingRewardsTransactor) GetReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _IStakingRewards.contract.Transact(opts, \"getReward\")\n}", "func ValidateRewardTx(tx *types.Transaction, header *types.BlockHeader) error {\n\tif tx.Data.Type != types.TxTypeReward || !tx.Data.From.IsEmpty() || tx.Data.AccountNonce != 0 || tx.Data.GasPrice.Cmp(common.Big0) != 0 || tx.Data.GasLimit != 0 || len(tx.Data.Payload) != 0 {\n\t\treturn errInvalidReward\n\t}\n\n\t// validate to address\n\tto := tx.Data.To\n\tif to.IsEmpty() {\n\t\treturn errEmptyToAddress\n\t}\n\n\tif !to.Equal(header.Creator) {\n\t\treturn errCoinbaseMismatch\n\t}\n\n\t// validate reward\n\tamount := tx.Data.Amount\n\tif err := validateReward(amount); err != nil {\n\t\treturn err\n\t}\n\n\treward := consensus.GetReward(header.Height)\n\tif reward == nil || reward.Cmp(amount) != 0 {\n\t\treturn fmt.Errorf(\"invalid reward Amount, block height %d, want %s, got %s\", header.Height, reward, amount)\n\t}\n\n\t// validate timestamp\n\tif tx.Data.Timestamp != header.CreateTimestamp.Uint64() {\n\t\treturn errTimestampMismatch\n\t}\n\n\treturn nil\n}", "func (_Smartchef *SmartchefTransactor) StopReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Smartchef.contract.Transact(opts, \"stopReward\")\n}", "func (_XStaking *XStakingCaller) Rewards(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewards\", arg0)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (as AccountStorage) SetReward(ctx sdk.Context, accKey types.AccountKey, reward *Reward) sdk.Error {\n\tstore := ctx.KVStore(as.key)\n\trewardByte, err := as.cdc.MarshalJSON(*reward)\n\tif err != nil {\n\t\treturn ErrFailedToMarshalReward(err)\n\t}\n\tstore.Set(getRewardKey(accKey), rewardByte)\n\treturn nil\n}", "func (_Lmc *LmcCallerSession) GetUserAccumulatedReward(_userAddress common.Address, tokenIndex *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.GetUserAccumulatedReward(&_Lmc.CallOpts, _userAddress, tokenIndex)\n}", "func (t *Transaction) Reward() string {\n\treturn t.reward\n}", "func (_XStaking *XStakingTransactor) GetReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _XStaking.contract.Transact(opts, \"getReward\")\n}", "func (_Smartchef *SmartchefCaller) PendingReward(opts *bind.CallOpts, _user common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Smartchef.contract.Call(opts, out, \"pendingReward\", _user)\n\treturn *ret0, err\n}", "func (_Lmc *LmcSession) GetUserAccumulatedReward(_userAddress common.Address, tokenIndex *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.GetUserAccumulatedReward(&_Lmc.CallOpts, _userAddress, tokenIndex)\n}", "func (m *EntitlementLootBoxReward) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (c4 *Connect4) GetReward() int {\n\tif c4.Winner == nil {\n\t\treturn 0\n\t} else if *c4.Winner == 1 {\n\t\treturn 1\n\t}\n\treturn -1\n}", "func computeReward(epoch abi.ChainEpoch, prevTheta, currTheta, simpleTotal, baselineTotal big.Int) abi.TokenAmount {\n\tsimpleReward := big.Mul(simpleTotal, ExpLamSubOne) //Q.0 * Q.128 => Q.128\n\tepochLam := big.Mul(big.NewInt(int64(epoch)), Lambda) // Q.0 * Q.128 => Q.128\n\n\tsimpleReward = big.Mul(simpleReward, big.NewFromGo(math.ExpNeg(epochLam.Int))) // Q.128 * Q.128 => Q.256\n\tsimpleReward = big.Rsh(simpleReward, math.Precision128) // Q.256 >> 128 => Q.128\n\n\tbaselineReward := big.Sub(computeBaselineSupply(currTheta, baselineTotal), computeBaselineSupply(prevTheta, baselineTotal)) // Q.128\n\n\treward := big.Add(simpleReward, baselineReward) // Q.128\n\n\treturn big.Rsh(reward, math.Precision128) // Q.128 => Q.0\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) DistributeETHReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"distributeETHReward\")\n}", "func (_Token *TokenCaller) CurrentReward(opts *bind.CallOpts, account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\tret := new(struct {\n\t\tInitialDeposit *big.Int\n\t\tReward *big.Int\n\t})\n\tout := ret\n\terr := _Token.contract.Call(opts, out, \"currentReward\", account)\n\treturn *ret, err\n}", "func (k Keeper) DeleteReward(ctx sdk.Context, stakingCoinDenom string, farmerAcc sdk.AccAddress) {\n\tstore := ctx.KVStore(k.storeKey)\n\tstore.Delete(types.GetRewardKey(stakingCoinDenom, farmerAcc))\n\tstore.Delete(types.GetRewardByFarmerAndStakingCoinDenomIndexKey(farmerAcc, stakingCoinDenom))\n}", "func (k Keeper) ClaimEarnReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedEarnClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetEarnClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (k Keeper) ClaimUSDXMintingReward(ctx sdk.Context, owner, receiver sdk.AccAddress, multiplierName string) error {\n\tclaim, found := k.GetUSDXMintingClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, types.USDXMintingRewardDenom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", types.USDXMintingRewardDenom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tclaim, err := k.SynchronizeUSDXMintingClaim(ctx, claim)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trewardAmount := sdk.NewDecFromInt(claim.Reward.Amount).Mul(multiplier.Factor).RoundInt()\n\tif rewardAmount.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\trewardCoin := sdk.NewCoin(claim.Reward.Denom, rewardAmount)\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, sdk.NewCoins(rewardCoin), length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tk.ZeroUSDXMintingClaim(ctx, claim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claim.Reward.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, claim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (k Keeper) ClaimSwapReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedSwapClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetSwapClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_IStakingRewards *IStakingRewardsTransactorSession) GetReward() (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.GetReward(&_IStakingRewards.TransactOpts)\n}", "func rewardAndSlash(ctx contract.Context, cachedDelegations *CachedDposStorage, state *State) ([]*DelegationResult, error) {\n\tformerValidatorTotals := make(map[string]loom.BigUInt)\n\tdelegatorRewards := make(map[string]*loom.BigUInt)\n\tdistributedRewards := common.BigZero()\n\n\tdelegations, err := cachedDelegations.loadDelegationList(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, validator := range state.Validators {\n\t\tcandidate := GetCandidateByPubKey(ctx, validator.PubKey)\n\n\t\tif candidate == nil {\n\t\t\tctx.Logger().Info(\"Attempted to reward validator no longer on candidates list.\", \"validator\", validator)\n\t\t\tcontinue\n\t\t}\n\n\t\tcandidateAddress := loom.UnmarshalAddressPB(candidate.Address)\n\t\tvalidatorKey := candidateAddress.String()\n\t\tstatistic, _ := GetStatistic(ctx, candidateAddress)\n\n\t\tif statistic == nil {\n\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t} else {\n\t\t\t// If a validator is jailed, don't calculate and distribute rewards\n\t\t\tif ctx.FeatureEnabled(features.DPOSVersion3_3, false) {\n\t\t\t\tif statistic.Jailed {\n\t\t\t\t\tdelegatorRewards[validatorKey] = common.BigZero()\n\t\t\t\t\tformerValidatorTotals[validatorKey] = *common.BigZero()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If a validator's SlashPercentage is 0, the validator is\n\t\t\t// rewarded for avoiding faults during the last slashing period\n\t\t\tif common.IsZero(statistic.SlashPercentage.Value) {\n\t\t\t\tdistributionTotal := calculateRewards(statistic.DelegationTotal.Value, state.Params, state.TotalValidatorDelegations.Value)\n\n\t\t\t\t// The validator share, equal to validator_fee * total_validotor_reward\n\t\t\t\t// is to be split between the referrers and the validator\n\t\t\t\tvalidatorShare := CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, distributionTotal)\n\n\t\t\t\t// delegatorsShare is what fraction of the total rewards will be\n\t\t\t\t// distributed to delegators\n\t\t\t\tdelegatorsShare := common.BigZero()\n\t\t\t\tdelegatorsShare.Sub(&distributionTotal, &validatorShare)\n\t\t\t\tdelegatorRewards[validatorKey] = delegatorsShare\n\n\t\t\t\t// Distribute rewards to referrers\n\t\t\t\tfor _, d := range delegations {\n\t\t\t\t\tif loom.UnmarshalAddressPB(d.Validator).Compare(loom.UnmarshalAddressPB(candidate.Address)) == 0 {\n\t\t\t\t\t\tdelegation, err := GetDelegation(ctx, d.Index, *d.Validator, *d.Delegator)\n\t\t\t\t\t\t// if the delegation is not found OR if the delegation\n\t\t\t\t\t\t// has no referrer, we do not need to attempt to\n\t\t\t\t\t\t// distribute the referrer rewards\n\t\t\t\t\t\tif err == contract.ErrNotFound || len(delegation.Referrer) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// if referrer is not found, do not distribute the reward\n\t\t\t\t\t\treferrerAddress := getReferrer(ctx, delegation.Referrer)\n\t\t\t\t\t\tif referrerAddress == nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// calculate referrerReward\n\t\t\t\t\t\treferrerReward := calculateRewards(delegation.Amount.Value, state.Params, state.TotalValidatorDelegations.Value)\n\t\t\t\t\t\treferrerReward = CalculateFraction(loom.BigUInt{big.NewInt(int64(candidate.Fee))}, referrerReward)\n\t\t\t\t\t\treferrerReward = CalculateFraction(defaultReferrerFee, referrerReward)\n\n\t\t\t\t\t\t// referrer fees are delegater to limbo validator\n\t\t\t\t\t\tdistributedRewards.Add(distributedRewards, &referrerReward)\n\t\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, LimboValidatorAddress(ctx).MarshalPB(), referrerAddress, referrerReward)\n\n\t\t\t\t\t\t// any referrer bonus amount is subtracted from the validatorShare\n\t\t\t\t\t\tvalidatorShare.Sub(&validatorShare, &referrerReward)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdistributedRewards.Add(distributedRewards, &validatorShare)\n\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, validatorShare)\n\n\t\t\t\t// If a validator has some non-zero WhitelistAmount,\n\t\t\t\t// calculate the validator's reward based on whitelist amount\n\t\t\t\tif !common.IsZero(statistic.WhitelistAmount.Value) {\n\t\t\t\t\tamount := calculateWeightedWhitelistAmount(*statistic)\n\t\t\t\t\twhitelistDistribution := calculateShare(amount, statistic.DelegationTotal.Value, *delegatorsShare)\n\t\t\t\t\t// increase a delegator's distribution\n\t\t\t\t\tdistributedRewards.Add(distributedRewards, &whitelistDistribution)\n\t\t\t\t\tcachedDelegations.IncreaseRewardDelegation(ctx, candidate.Address, candidate.Address, whitelistDistribution)\n\t\t\t\t}\n\n\t\t\t\t// Keeping track of cumulative distributed rewards by adding\n\t\t\t\t// every validator's total rewards to\n\t\t\t\t// `state.TotalRewardDistribution`\n\t\t\t\t// NOTE: because we round down in every `calculateRewards` call,\n\t\t\t\t// we expect `state.TotalRewardDistribution` to be a slight\n\t\t\t\t// overestimate of what was actually distributed. We could be\n\t\t\t\t// exact with our record keeping by incrementing\n\t\t\t\t// `state.TotalRewardDistribution` each time\n\t\t\t\t// `IncreaseRewardDelegation` is called, but because we will not\n\t\t\t\t// use `state.TotalRewardDistributions` as part of any invariants,\n\t\t\t\t// we will live with this situation.\n\t\t\t\tif !ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\t\t\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, &distributionTotal)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := slashValidatorDelegations(ctx, cachedDelegations, statistic, candidateAddress); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif err := SetStatistic(ctx, statistic); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tformerValidatorTotals[validatorKey] = statistic.DelegationTotal.Value\n\t\t}\n\t}\n\n\tnewDelegationTotals, err := distributeDelegatorRewards(ctx, cachedDelegations, formerValidatorTotals, delegatorRewards, distributedRewards)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif ctx.FeatureEnabled(features.DPOSVersion3_1, false) {\n\t\tstate.TotalRewardDistribution.Value.Add(&state.TotalRewardDistribution.Value, distributedRewards)\n\t}\n\n\tdelegationResults := make([]*DelegationResult, 0, len(newDelegationTotals))\n\tfor validator := range newDelegationTotals {\n\t\tdelegationResults = append(delegationResults, &DelegationResult{\n\t\t\tValidatorAddress: loom.MustParseAddress(validator),\n\t\t\tDelegationTotal: *newDelegationTotals[validator],\n\t\t})\n\t}\n\tsort.Sort(byDelegationTotal(delegationResults))\n\n\treturn delegationResults, nil\n}", "func (s *MutableState) AddRewards(time epochtime.EpochTime, factor *quantity.Quantity, accounts []signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tfor _, id := range accounts {\n\t\tent := s.Account(id)\n\n\t\tq := ent.Escrow.Active.Balance.Clone()\n\t\t// Multiply first.\n\t\tif err := q.Mul(factor); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t\t}\n\t\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t\t}\n\t\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t\t}\n\n\t\tif q.IsZero() {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar com *quantity.Quantity\n\t\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\t\tif rate != nil {\n\t\t\tcom = q.Clone()\n\t\t\t// Multiply first.\n\t\t\tif err := com.Mul(rate); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t\t}\n\t\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t\t}\n\n\t\t\tif err := q.Sub(com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t\t}\n\t\t}\n\n\t\tif !q.IsZero() {\n\t\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t\t}\n\t\t}\n\n\t\tif com != nil && !com.IsZero() {\n\t\t\tdelegation := s.Delegation(id, id)\n\n\t\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t\t}\n\n\t\t\ts.SetDelegation(id, id, delegation)\n\t\t}\n\n\t\ts.SetAccount(id, ent)\n\t}\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func (k Keeper) ClaimDelegatorReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tclaim, found := k.GetDelegatorClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, err := k.SynchronizeDelegatorClaim(ctx, claim)\n\tif err != nil {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetDelegatorClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func ApplyRewardTx(tx *types.Transaction, statedb *state.Statedb) (*types.Receipt, error) {\n\tstatedb.CreateAccount(tx.Data.To)\n\tstatedb.AddBalance(tx.Data.To, tx.Data.Amount)\n\n\thash, err := statedb.Hash()\n\tif err != nil {\n\t\treturn nil, errors.NewStackedError(err, \"failed to get statedb root hash\")\n\t}\n\n\treceipt := &types.Receipt{\n\t\tTxHash: tx.Hash,\n\t\tPostState: hash,\n\t}\n\n\treturn receipt, nil\n}", "func (n Network) ChainReward(ctx context.Context, launchID uint64) (rewardtypes.RewardPool, error) {\n\tres, err := n.rewardQuery.\n\t\tRewardPool(ctx,\n\t\t\t&rewardtypes.QueryGetRewardPoolRequest{\n\t\t\t\tLaunchID: launchID,\n\t\t\t},\n\t\t)\n\n\tif cosmoserror.Unwrap(err) == cosmoserror.ErrNotFound {\n\t\treturn rewardtypes.RewardPool{}, ErrObjectNotFound\n\t} else if err != nil {\n\t\treturn rewardtypes.RewardPool{}, err\n\t}\n\treturn res.RewardPool, nil\n}", "func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\n}", "func (_Smartchef *SmartchefCallerSession) PendingReward(_user common.Address) (*big.Int, error) {\n\treturn _Smartchef.Contract.PendingReward(&_Smartchef.CallOpts, _user)\n}", "func (_IStakingRewards *IStakingRewardsSession) GetReward() (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.GetReward(&_IStakingRewards.TransactOpts)\n}", "func (_Smartchef *SmartchefTransactorSession) StopReward() (*types.Transaction, error) {\n\treturn _Smartchef.Contract.StopReward(&_Smartchef.TransactOpts)\n}", "func (me TGetReviewableHITsSortProperty) IsReward() bool { return me.String() == \"Reward\" }", "func (m *MemoryRewardStorage) Update(reward rewards.Reward) {\n\tfor index, r := range m.rewards {\n\t\tif r.ID == reward.ID {\n\t\t\tm.rewards[index] = reward\n\t\t}\n\t}\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientTransactorSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.NotifyRewardAmount(&_RewardsDistributionRecipient.TransactOpts, reward)\n}", "func (_Token *TokenCallerSession) CurrentReward(account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\treturn _Token.Contract.CurrentReward(&_Token.CallOpts, account)\n}", "func (_TrialRulesAbstract *TrialRulesAbstractCaller) GetReward(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TrialRulesAbstract.contract.Call(opts, out, \"getReward\")\n\treturn *ret0, err\n}", "func (del Delegation) ClaimedReward() (hexutil.Big, error) {\n\tval, err := repository.R().RewardsClaimed(&del.Address, (*big.Int)(del.Delegation.ToStakerId), nil, nil)\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\treturn (hexutil.Big)(*val), nil\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.NotifyRewardAmount(&_RewardsDistributionRecipient.TransactOpts, reward)\n}", "func (_Contract *ContractCaller) TaskErasingReward(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"taskErasingReward\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (k Keeper) GetReward(ctx sdk.Context, stakingCoinDenom string, farmerAcc sdk.AccAddress) (reward types.Reward, found bool) {\n\tstore := ctx.KVStore(k.storeKey)\n\tbz := store.Get(types.GetRewardKey(stakingCoinDenom, farmerAcc))\n\tif bz == nil {\n\t\treturn reward, false\n\t}\n\tvar rewardCoins types.RewardCoins\n\tk.cdc.MustUnmarshal(bz, &rewardCoins)\n\treturn types.Reward{\n\t\tFarmer: farmerAcc.String(),\n\t\tStakingCoinDenom: stakingCoinDenom,\n\t\tRewardCoins: rewardCoins.RewardCoins,\n\t}, true\n}", "func (_Dospayment *DospaymentTransactor) ClaimGuardianReward(opts *bind.TransactOpts, guardianAddr common.Address) (*types.Transaction, error) {\n\treturn _Dospayment.contract.Transact(opts, \"claimGuardianReward\", guardianAddr)\n}", "func (_Smartchef *SmartchefSession) PendingReward(_user common.Address) (*big.Int, error) {\n\treturn _Smartchef.Contract.PendingReward(&_Smartchef.CallOpts, _user)\n}", "func (_Smartchef *SmartchefSession) StopReward() (*types.Transaction, error) {\n\treturn _Smartchef.Contract.StopReward(&_Smartchef.TransactOpts)\n}", "func (_TrialRulesAbstract *TrialRulesAbstractCallerSession) GetReward() (*big.Int, error) {\n\treturn _TrialRulesAbstract.Contract.GetReward(&_TrialRulesAbstract.CallOpts)\n}", "func (_Contract *ContractCallerSession) TaskHandlingReward() (*big.Int, error) {\n\treturn _Contract.Contract.TaskHandlingReward(&_Contract.CallOpts)\n}", "func (q querier) RewardWeight(c context.Context, req *types.QueryRewardWeightRequest) (*types.QueryRewardWeightResponse, error) {\n\tctx := sdk.UnwrapSDKContext(c)\n\treturn &types.QueryRewardWeightResponse{RewardWeight: q.GetRewardWeight(ctx)}, nil\n}", "func (_Token *TokenSession) CurrentReward(account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\treturn _Token.Contract.CurrentReward(&_Token.CallOpts, account)\n}", "func (c *Calculator) votingReward(\n\tmultiplier *big.Int,\n\tdivider *big.Int,\n\tfrom int,\n\tto int,\n\tprepInfo map[string]*pRepEnable,\n\titer icstate.VotingIterator,\n) *big.Int {\n\ttotal := new(big.Int)\n\tcheckMinVoting := c.global.GetIISSVersion() == icstate.IISSVersion2\n\tfor ; iter.Has(); iter.Next() {\n\t\tif voting, err := iter.Get(); err != nil {\n\t\t\tc.log.Errorf(\"Failed to iterate votings err=%+v\", err)\n\t\t} else {\n\t\t\tif checkMinVoting && voting.Amount().Cmp(BigIntMinDelegation) < 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts := from\n\t\t\te := to\n\t\t\tif prep, ok := prepInfo[icutils.ToKey(voting.To())]; ok {\n\t\t\t\tif prep.StartOffset() != 0 && prep.StartOffset() > s {\n\t\t\t\t\ts = prep.StartOffset()\n\t\t\t\t}\n\t\t\t\tif prep.EndOffset() != 0 && prep.EndOffset() < e {\n\t\t\t\t\te = prep.EndOffset()\n\t\t\t\t}\n\t\t\t\tperiod := e - s\n\t\t\t\tif period <= 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treward := new(big.Int).Mul(multiplier, voting.Amount())\n\t\t\t\treward.Mul(reward, big.NewInt(int64(period)))\n\t\t\t\treward.Div(reward, divider)\n\t\t\t\ttotal.Add(total, reward)\n\t\t\t\tc.log.Tracef(\"VotingReward %s: %s = %s * %s * %d / %s\",\n\t\t\t\t\tvoting.To(), reward, multiplier, voting.Amount(), period, divider)\n\t\t\t}\n\t\t}\n\t}\n\treturn total\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (_Lmc *LmcCaller) RewardPerBlock(opts *bind.CallOpts, arg0 *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Lmc.contract.Call(opts, &out, \"rewardPerBlock\", arg0)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (me *XsdGoPkgHasElem_RewardsequenceCreateHITRequestschema_Reward_TPrice_) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_RewardsequenceCreateHITRequestschema_Reward_TPrice_; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.Reward.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (_XStaking *XStakingFilterer) ParseRewardPaid(log types.Log) (*XStakingRewardPaid, error) {\n\tevent := new(XStakingRewardPaid)\n\tif err := _XStaking.contract.UnpackLog(event, \"RewardPaid\", log); err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}", "func (_XStaking *XStakingTransactorSession) GetReward() (*types.Transaction, error) {\n\treturn _XStaking.Contract.GetReward(&_XStaking.TransactOpts)\n}", "func MeanReward(r []*Rollout) float64 {\n\tvar sum float64\n\tfor _, x := range r {\n\t\tsum += x.Reward\n\t}\n\treturn sum / float64(len(r))\n}", "func (p *Protocol) updateRewardHistory(tx *sql.Tx, epochNumber uint64, actionHash string, rewardInfoMap map[string]*RewardInfo) error {\n\tvalStrs := make([]string, 0, len(rewardInfoMap))\n\tvalArgs := make([]interface{}, 0, len(rewardInfoMap)*7)\n\tfor rewardAddress, rewards := range rewardInfoMap {\n\t\tblockReward := rewards.BlockReward.String()\n\t\tepochReward := rewards.EpochReward.String()\n\t\tfoundationBonus := rewards.FoundationBonus.String()\n\n\t\tvar candidateName string\n\t\t// If more than one candidates share the same reward address, just use the first candidate as their delegate\n\t\tif len(p.RewardAddrToName[rewardAddress]) > 0 {\n\t\t\tcandidateName = p.RewardAddrToName[rewardAddress][0]\n\t\t}\n\n\t\tvalStrs = append(valStrs, \"(?, ?, ?, ?, CAST(? as DECIMAL(65, 0)), CAST(? as DECIMAL(65, 0)), CAST(? as DECIMAL(65, 0)))\")\n\t\tvalArgs = append(valArgs, epochNumber, actionHash, rewardAddress, candidateName, blockReward, epochReward, foundationBonus)\n\t}\n\tinsertQuery := fmt.Sprintf(insertRewardHistory, RewardHistoryTableName, strings.Join(valStrs, \",\"))\n\n\tif _, err := tx.Exec(insertQuery, valArgs...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (_XStaking *XStakingCaller) RewardRate(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewardRate\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_XStaking *XStakingFilterer) WatchRewardPaid(opts *bind.WatchOpts, sink chan<- *XStakingRewardPaid, user []common.Address) (event.Subscription, error) {\n\n\tvar userRule []interface{}\n\tfor _, userItem := range user {\n\t\tuserRule = append(userRule, userItem)\n\t}\n\n\tlogs, sub, err := _XStaking.contract.WatchLogs(opts, \"RewardPaid\", userRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(XStakingRewardPaid)\n\t\t\t\tif err := _XStaking.contract.UnpackLog(event, \"RewardPaid\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}", "func (_XStaking *XStakingSession) GetReward() (*types.Transaction, error) {\n\treturn _XStaking.Contract.GetReward(&_XStaking.TransactOpts)\n}", "func (d *Dao) HasReward(c context.Context, uid int64) (r int64, err error) {\n\trst, err := d.GetHasReward(c, uid)\n\tif err != nil {\n\t\tif err == memcache.ErrNotFound {\n\t\t\treward, err2 := d.findByUid(uid, true)\n\t\t\tif err2 != nil {\n\t\t\t\treturn rst, err2\n\t\t\t}\n\t\t\tif reward != nil {\n\t\t\t\trst = int64(1)\n\t\t\t\td.SetHasReward(c, uid, rst)\n\t\t\t} else {\n\t\t\t\trst = int64(0)\n\t\t\t\td.SetHasReward(c, uid, rst)\n\t\t\t}\n\t\t\treturn rst, err\n\t\t}\n\t\tlog.Error(\"HasReward(%v) error(%v)\", uid, err)\n\t\treturn rst, err\n\t}\n\treturn rst, err\n}", "func (_XStaking *XStakingCallerSession) UserRewardPerTokenPaid(arg0 common.Address) (*big.Int, error) {\n\treturn _XStaking.Contract.UserRewardPerTokenPaid(&_XStaking.CallOpts, arg0)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (_XStaking *XStakingCallerSession) Rewards(arg0 common.Address) (*big.Int, error) {\n\treturn _XStaking.Contract.Rewards(&_XStaking.CallOpts, arg0)\n}", "func (httpServer *HttpServer) handleListRewardAmount(params interface{}, closeChan <-chan struct{}) (interface{}, *rpcservice.RPCError) {\n\tresult := httpServer.databaseService.ListRewardAmount()\n\treturn result, nil\n}", "func (as AccountStorage) GetReward(ctx sdk.Context, accKey types.AccountKey) (*Reward, sdk.Error) {\n\tstore := ctx.KVStore(as.key)\n\trewardByte := store.Get(getRewardKey(accKey))\n\tif rewardByte == nil {\n\t\treturn nil, ErrRewardNotFound()\n\t}\n\treward := new(Reward)\n\tif err := as.cdc.UnmarshalJSON(rewardByte, reward); err != nil {\n\t\treturn nil, ErrFailedToUnmarshalReward(err)\n\t}\n\treturn reward, nil\n}", "func (_Lmc *LmcCallerSession) GetUserRewardDebt(_userAddress common.Address, _index *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.GetUserRewardDebt(&_Lmc.CallOpts, _userAddress, _index)\n}", "func (m *DestinyDefinitionsMilestonesDestinyMilestoneQuestRewardItem) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (_Lmc *LmcCallerSession) RewardPerBlock(arg0 *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.RewardPerBlock(&_Lmc.CallOpts, arg0)\n}", "func (_XStaking *XStakingSession) Rewards(arg0 common.Address) (*big.Int, error) {\n\treturn _XStaking.Contract.Rewards(&_XStaking.CallOpts, arg0)\n}", "func (me TSearchHITsSortProperty) IsReward() bool { return me.String() == \"Reward\" }", "func (_Lmc *LmcSession) RewardPerBlock(arg0 *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.RewardPerBlock(&_Lmc.CallOpts, arg0)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\n}", "func (_TrialRulesAbstract *TrialRulesAbstractSession) GetReward() (*big.Int, error) {\n\treturn _TrialRulesAbstract.Contract.GetReward(&_TrialRulesAbstract.CallOpts)\n}", "func (_XStaking *XStakingFilterer) WatchRewardAdded(opts *bind.WatchOpts, sink chan<- *XStakingRewardAdded) (event.Subscription, error) {\n\n\tlogs, sub, err := _XStaking.contract.WatchLogs(opts, \"RewardAdded\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(XStakingRewardAdded)\n\t\t\t\tif err := _XStaking.contract.UnpackLog(event, \"RewardAdded\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}", "func (_Contract *ContractSession) TaskHandlingReward() (*big.Int, error) {\n\treturn _Contract.Contract.TaskHandlingReward(&_Contract.CallOpts)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientTransactor) NotifyRewardAmount(opts *bind.TransactOpts, reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.contract.Transact(opts, \"notifyRewardAmount\", reward)\n}", "func (msg MsgClaimUSDXMintingReward) Type() string { return TypeMsgClaimUSDXMintingReward }", "func (r *Rewarding) BlockReward() *big.Int {\n\tval, ok := new(big.Int).SetString(r.BlockRewardStr, 10)\n\tif !ok {\n\t\tlog.S().Panicf(\"Error when casting block reward string %s into big int\", r.BlockRewardStr)\n\t}\n\treturn val\n}", "func (_Lmc *LmcSession) GetUserRewardDebt(_userAddress common.Address, _index *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.GetUserRewardDebt(&_Lmc.CallOpts, _userAddress, _index)\n}", "func (_XStaking *XStakingSession) UserRewardPerTokenPaid(arg0 common.Address) (*big.Int, error) {\n\treturn _XStaking.Contract.UserRewardPerTokenPaid(&_XStaking.CallOpts, arg0)\n}" ]
[ "0.6228627", "0.6163718", "0.60478336", "0.603172", "0.6024607", "0.5981112", "0.5969014", "0.59682953", "0.59496", "0.59159184", "0.5895051", "0.5894164", "0.5851955", "0.5822973", "0.57389563", "0.56443095", "0.5625199", "0.5603768", "0.5591688", "0.55578643", "0.5497458", "0.54913", "0.5485651", "0.54785264", "0.5459176", "0.5456478", "0.5455661", "0.5433399", "0.5428552", "0.5421066", "0.5400683", "0.53939676", "0.53790295", "0.5357424", "0.53563786", "0.53321487", "0.5329579", "0.52970684", "0.5296688", "0.5289166", "0.5286446", "0.5265115", "0.52425015", "0.52381027", "0.52209747", "0.5220343", "0.5220156", "0.52146167", "0.5206164", "0.5193927", "0.51557475", "0.5139185", "0.51309204", "0.5128314", "0.51251996", "0.5115334", "0.51144314", "0.51130533", "0.5105608", "0.50974107", "0.50949985", "0.509375", "0.50915396", "0.5073", "0.50704926", "0.5068857", "0.50632036", "0.5058857", "0.5056796", "0.50554484", "0.5054147", "0.5047337", "0.50439477", "0.5022599", "0.5020046", "0.4997247", "0.4988397", "0.49864525", "0.49767706", "0.49717173", "0.4961796", "0.4961348", "0.49515942", "0.49492058", "0.49430174", "0.49401253", "0.49275827", "0.49239883", "0.49234566", "0.491311", "0.49102077", "0.49084952", "0.490803", "0.49062353", "0.4902244", "0.489186", "0.4877863", "0.48679137", "0.48677853", "0.48640245" ]
0.78040135
0
PostReward implements the exported.ClawbackVestingAccountI interface.
func (va *ClawbackVestingAccount) PostReward(ctx sdk.Context, reward sdk.Coins, action exported.RewardAction) error { return action.ProcessReward(ctx, reward, va) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) {\n\t// Find the scheduled amount of vested and unvested staking tokens\n\tbondDenom := sk.BondDenom(ctx)\n\tvested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom)\n\tunvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested)\n\n\tif unvested.IsZero() {\n\t\t// no need to adjust the vesting schedule\n\t\treturn\n\t}\n\n\tif vested.IsZero() {\n\t\t// all staked tokens must be unvested\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\n\t// Find current split of account balance on staking axis\n\tbonded := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegated := bonded.Add(unbonding)\n\n\t// discover what has been slashed and remove from delegated amount\n\toldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom))\n\tslashed := oldDelegated.Sub(intMin(oldDelegated, delegated))\n\tdelegated = delegated.Sub(intMin(delegated, slashed))\n\n\t// Prefer delegated tokens to be unvested\n\tunvested = intMin(unvested, delegated)\n\tvested = delegated.Sub(unvested)\n\n\t// Compute the unvested amount of reward and add to vesting schedule\n\tif unvested.IsZero() {\n\t\treturn\n\t}\n\tif vested.IsZero() {\n\t\tva.distributeReward(ctx, ak, bondDenom, reward)\n\t\treturn\n\t}\n\tunvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down\n\tunvestedReward := scaleCoins(reward, unvestedRatio)\n\tva.distributeReward(ctx, ak, bondDenom, unvestedReward)\n}", "func (cra clawbackRewardAction) ProcessReward(ctx sdk.Context, reward sdk.Coins, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported, \"expected *ClawbackVestingAccount, got %T\", rawAccount)\n\t}\n\tcva.postReward(ctx, reward, cra.ak, cra.bk, cra.sk)\n\treturn nil\n}", "func (va ClawbackVestingAccount) distributeReward(ctx sdk.Context, ak AccountKeeper, bondDenom string, reward sdk.Coins) {\n\tnow := ctx.BlockTime().Unix()\n\tt := va.StartTime\n\tfirstUnvestedPeriod := 0\n\tunvestedTokens := sdk.ZeroInt()\n\tfor i, period := range va.VestingPeriods {\n\t\tt += period.Length\n\t\tif t <= now {\n\t\t\tfirstUnvestedPeriod = i + 1\n\t\t\tcontinue\n\t\t}\n\t\tunvestedTokens = unvestedTokens.Add(period.Amount.AmountOf(bondDenom))\n\t}\n\n\trunningTotReward := sdk.NewCoins()\n\trunningTotStaking := sdk.ZeroInt()\n\tfor i := firstUnvestedPeriod; i < len(va.VestingPeriods); i++ {\n\t\tperiod := va.VestingPeriods[i]\n\t\trunningTotStaking = runningTotStaking.Add(period.Amount.AmountOf(bondDenom))\n\t\trunningTotRatio := runningTotStaking.ToDec().Quo(unvestedTokens.ToDec())\n\t\ttargetCoins := scaleCoins(reward, runningTotRatio)\n\t\tthisReward := targetCoins.Sub(runningTotReward)\n\t\trunningTotReward = targetCoins\n\t\tperiod.Amount = period.Amount.Add(thisReward...)\n\t\tva.VestingPeriods[i] = period\n\t}\n\n\tva.OriginalVesting = va.OriginalVesting.Add(reward...)\n\tak.SetAccount(ctx, &va)\n}", "func (a Actor) AwardBlockReward(rt vmr.Runtime, params *AwardBlockRewardParams) *adt.EmptyValue {\n\trt.ValidateImmediateCallerIs(builtin.SystemActorAddr)\n\tAssertMsg(rt.CurrentBalance().GreaterThanEqual(params.GasReward),\n\t\t\"actor current balance %v insufficient to pay gas reward %v\", rt.CurrentBalance(), params.GasReward)\n\n\tAssertMsg(params.TicketCount > 0, \"cannot give block reward for zero tickets\")\n\n\tminer, ok := rt.ResolveAddress(params.Miner)\n\tif !ok {\n\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to resolve given owner address\")\n\t}\n\n\tpriorBalance := rt.CurrentBalance()\n\n\tvar penalty abi.TokenAmount\n\tvar st State\n\trt.State().Transaction(&st, func() interface{} {\n\t\tblockReward := a.computeBlockReward(&st, big.Sub(priorBalance, params.GasReward), params.TicketCount)\n\t\ttotalReward := big.Add(blockReward, params.GasReward)\n\n\t\t// Cap the penalty at the total reward value.\n\t\tpenalty = big.Min(params.Penalty, totalReward)\n\n\t\t// Reduce the payable reward by the penalty.\n\t\trewardPayable := big.Sub(totalReward, penalty)\n\n\t\tAssertMsg(big.Add(rewardPayable, penalty).LessThanEqual(priorBalance),\n\t\t\t\"reward payable %v + penalty %v exceeds balance %v\", rewardPayable, penalty, priorBalance)\n\n\t\t// Record new reward into reward map.\n\t\tif rewardPayable.GreaterThan(abi.NewTokenAmount(0)) {\n\t\t\tnewReward := Reward{\n\t\t\t\tStartEpoch: rt.CurrEpoch(),\n\t\t\t\tEndEpoch: rt.CurrEpoch() + rewardVestingPeriod,\n\t\t\t\tValue: rewardPayable,\n\t\t\t\tAmountWithdrawn: abi.NewTokenAmount(0),\n\t\t\t\tVestingFunction: rewardVestingFunction,\n\t\t\t}\n\t\t\tif err := st.addReward(adt.AsStore(rt), miner, &newReward); err != nil {\n\t\t\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to add reward to rewards map: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\t// Burn the penalty amount.\n\t_, code := rt.Send(builtin.BurntFundsActorAddr, builtin.MethodSend, nil, penalty)\n\tbuiltin.RequireSuccess(rt, code, \"failed to send penalty to BurntFundsActor\")\n\n\treturn nil\n}", "func (c *Coinbase) AddReward(output *Output) {\n\toutput.EncryptedMask = make([]byte, 1)\n\tc.Rewards = append(c.Rewards, output)\n}", "func (vi *votedInfo) CalculateReward(multiplier, divider *big.Int, period int) {\n\tif multiplier.Sign() == 0 || period == 0 {\n\t\treturn\n\t}\n\tif divider.Sign() == 0 || vi.totalBondedDelegation.Sign() == 0 {\n\t\treturn\n\t}\n\t// reward = multiplier * period * bondedDelegation / (divider * totalBondedDelegation)\n\tbase := new(big.Int).Mul(multiplier, big.NewInt(int64(period)))\n\treward := new(big.Int)\n\tfor i, addrKey := range vi.rank {\n\t\tif i == vi.maxRankForReward {\n\t\t\tbreak\n\t\t}\n\t\tprep := vi.preps[addrKey]\n\t\tif prep.Enable() == false {\n\t\t\tcontinue\n\t\t}\n\n\t\treward.Mul(base, prep.GetBondedDelegation())\n\t\treward.Div(reward, divider)\n\t\treward.Div(reward, vi.totalBondedDelegation)\n\n\t\tlog.Tracef(\"VOTED REWARD %d = %d * %d * %d / (%d * %d)\",\n\t\t\treward, multiplier, period, prep.GetBondedDelegation(), divider, vi.totalBondedDelegation)\n\n\t\tprep.SetIScore(new(big.Int).Add(prep.IScore(), reward))\n\t}\n}", "func (_Token *TokenCaller) BaseReward(opts *bind.CallOpts, index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t\tret1 = new(*big.Int)\n\t\tret2 = new(*big.Int)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t}\n\terr := _Token.contract.Call(opts, out, \"baseReward\", index)\n\treturn *ret0, *ret1, *ret2, err\n}", "func (_Token *TokenCallerSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (_Token *TokenSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (d *Dao) AddReward(c context.Context, iRewardID int64, uid int64, iSource int64, iRoomid int64, iLifespan int64) (err error) {\n\t//aReward, _ := getRewardConfByLid(iRewardID)\n\n\tm, _ := time.ParseDuration(fmt.Sprintf(\"+%dh\", iLifespan))\n\n\targ := &AnchorTaskModel.AnchorReward{\n\t\tUid: uid,\n\t\tRewardId: iRewardID,\n\t\tRoomid: iRoomid,\n\t\tSource: iSource,\n\t\tAchieveTime: xtime.Time(time.Now().Unix()),\n\t\tExpireTime: xtime.Time(time.Now().Add(m).Unix()),\n\t\tStatus: model.RewardUnUsed,\n\t}\n\n\t//spew.Dump\n\t// (arg)\n\tif err := d.orm.Create(arg).Error; err != nil {\n\t\tlog.Error(\"addReward(%v) error(%v)\", arg, err)\n\t\treturn err\n\t}\n\n\tif err := d.SetNewReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"addRewardMc(%v) error(%v)\", uid, err)\n\t}\n\n\tif err := d.SetHasReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"SetHasReward(%v) error(%v)\", uid, err)\n\t}\n\n\tlog.Info(\"addReward (%v) succ\", arg)\n\n\treturn\n}", "func (as AccountStorage) SetReward(ctx sdk.Context, accKey types.AccountKey, reward *Reward) sdk.Error {\n\tstore := ctx.KVStore(as.key)\n\trewardByte, err := as.cdc.MarshalJSON(*reward)\n\tif err != nil {\n\t\treturn ErrFailedToMarshalReward(err)\n\t}\n\tstore.Set(getRewardKey(accKey), rewardByte)\n\treturn nil\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) DistributeETHReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"distributeETHReward\")\n}", "func (_Smartchef *SmartchefTransactor) StopReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Smartchef.contract.Transact(opts, \"stopReward\")\n}", "func (c *Client) RenterPostAllowance(allowance modules.Allowance) (err error) {\n\tvalues := url.Values{}\n\tvalues.Set(\"funds\", allowance.Funds.String())\n\tvalues.Set(\"hosts\", strconv.FormatUint(allowance.Hosts, 10))\n\tvalues.Set(\"period\", strconv.FormatUint(uint64(allowance.Period), 10))\n\tvalues.Set(\"renewwindow\", strconv.FormatUint(uint64(allowance.RenewWindow), 10))\n\terr = c.post(\"/renter\", values.Encode(), nil)\n\treturn\n}", "func EstimateReward(reward, pr, gamma float64) float64 {\n\tret := reward / (pr + gamma)\n\tlog.Logf(MABLogLevel, \"MAB Estimate Reward: %v / (%v + %v) = %v\\n\",\n\t\treward, pr, gamma, ret)\n\treturn ret\n}", "func (_Dospayment *DospaymentTransactor) ClaimGuardianReward(opts *bind.TransactOpts, guardianAddr common.Address) (*types.Transaction, error) {\n\treturn _Dospayment.contract.Transact(opts, \"claimGuardianReward\", guardianAddr)\n}", "func ViewReward(rw http.ResponseWriter, r *http.Request) {\n\t// get the token\n\treqToken := r.Header.Get(\"Authorization\")\n\t\n\t// get the claims\n\tclaims, isNotValid := GetClaims(reqToken, rw)\n\tif isNotValid {\n\t\treturn\n\t}\n\n\tdt, err := db.GetUserRewards(claims.Roll)\n\tif err != nil {\n\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\trw.Write(Rsp(err.Error(), \"Server Error\"))\n\t\treturn\n\t}\n\trw.WriteHeader(http.StatusOK)\n\tres := c.RespData{\n\t\tMessage: \"All data\",\n\t\tData: dt,\n\t}\n\tjson.NewEncoder(rw).Encode(res)\n}", "func (s *MutableState) AddRewards(time epochtime.EpochTime, factor *quantity.Quantity, accounts []signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tfor _, id := range accounts {\n\t\tent := s.Account(id)\n\n\t\tq := ent.Escrow.Active.Balance.Clone()\n\t\t// Multiply first.\n\t\tif err := q.Mul(factor); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t\t}\n\t\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t\t}\n\t\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t\t}\n\n\t\tif q.IsZero() {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar com *quantity.Quantity\n\t\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\t\tif rate != nil {\n\t\t\tcom = q.Clone()\n\t\t\t// Multiply first.\n\t\t\tif err := com.Mul(rate); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t\t}\n\t\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t\t}\n\n\t\t\tif err := q.Sub(com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t\t}\n\t\t}\n\n\t\tif !q.IsZero() {\n\t\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t\t}\n\t\t}\n\n\t\tif com != nil && !com.IsZero() {\n\t\t\tdelegation := s.Delegation(id, id)\n\n\t\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t\t}\n\n\t\t\ts.SetDelegation(id, id, delegation)\n\t\t}\n\n\t\ts.SetAccount(id, ent)\n\t}\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func (node *TreeNode) backpropagateReward(scores [2]float64) {\n\tcurrentNode := node\n\tfor currentNode.Parent != nil {\n\t\tcurrentNode.VisitCount += 1.0\n\t\tcurrentNode.CumulativeScore[0] += scores[0]\n\t\tcurrentNode.CumulativeScore[1] += scores[1]\n\t\tcurrentNode = currentNode.Parent\n\t}\n\t//Increment root node counter\n\tcurrentNode.VisitCount += 1.0\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (k Keeper) ClaimSwapReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedSwapClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetSwapClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (k Keeper) ClaimEarnReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedEarnClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetEarnClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (client CloudEndpointsClient) PostBackupResponder(resp *http.Response) (result PostBackupResponse, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (_Smartchef *SmartchefCaller) PendingReward(opts *bind.CallOpts, _user common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Smartchef.contract.Call(opts, out, \"pendingReward\", _user)\n\treturn *ret0, err\n}", "func (_Smartchef *SmartchefTransactorSession) StopReward() (*types.Transaction, error) {\n\treturn _Smartchef.Contract.StopReward(&_Smartchef.TransactOpts)\n}", "func ApplyRewardTx(tx *types.Transaction, statedb *state.Statedb) (*types.Receipt, error) {\n\tstatedb.CreateAccount(tx.Data.To)\n\tstatedb.AddBalance(tx.Data.To, tx.Data.Amount)\n\n\thash, err := statedb.Hash()\n\tif err != nil {\n\t\treturn nil, errors.NewStackedError(err, \"failed to get statedb root hash\")\n\t}\n\n\treceipt := &types.Receipt{\n\t\tTxHash: tx.Hash,\n\t\tPostState: hash,\n\t}\n\n\treturn receipt, nil\n}", "func computeReward(epoch abi.ChainEpoch, prevTheta, currTheta, simpleTotal, baselineTotal big.Int) abi.TokenAmount {\n\tsimpleReward := big.Mul(simpleTotal, ExpLamSubOne) //Q.0 * Q.128 => Q.128\n\tepochLam := big.Mul(big.NewInt(int64(epoch)), Lambda) // Q.0 * Q.128 => Q.128\n\n\tsimpleReward = big.Mul(simpleReward, big.NewFromGo(math.ExpNeg(epochLam.Int))) // Q.128 * Q.128 => Q.256\n\tsimpleReward = big.Rsh(simpleReward, math.Precision128) // Q.256 >> 128 => Q.128\n\n\tbaselineReward := big.Sub(computeBaselineSupply(currTheta, baselineTotal), computeBaselineSupply(prevTheta, baselineTotal)) // Q.128\n\n\treward := big.Add(simpleReward, baselineReward) // Q.128\n\n\treturn big.Rsh(reward, math.Precision128) // Q.128 => Q.0\n}", "func (_Smartchef *SmartchefSession) StopReward() (*types.Transaction, error) {\n\treturn _Smartchef.Contract.StopReward(&_Smartchef.TransactOpts)\n}", "func (_Token *TokenCaller) CurrentReward(opts *bind.CallOpts, account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\tret := new(struct {\n\t\tInitialDeposit *big.Int\n\t\tReward *big.Int\n\t})\n\tout := ret\n\terr := _Token.contract.Call(opts, out, \"currentReward\", account)\n\treturn *ret, err\n}", "func (_XStaking *XStakingCaller) Rewards(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewards\", arg0)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (s *MutableState) AddRewardSingleAttenuated(time epochtime.EpochTime, factor *quantity.Quantity, attenuationNumerator, attenuationDenominator int, account signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tvar numQ, denQ quantity.Quantity\n\tif err = numQ.FromInt64(int64(attenuationNumerator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation numerator %d\", attenuationNumerator)\n\t}\n\tif err = denQ.FromInt64(int64(attenuationDenominator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation denominator %d\", attenuationDenominator)\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tent := s.Account(account)\n\n\tq := ent.Escrow.Active.Balance.Clone()\n\t// Multiply first.\n\tif err := q.Mul(factor); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t}\n\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t}\n\tif err := q.Mul(&numQ); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by attenuation numerator\")\n\t}\n\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t}\n\tif err := q.Quo(&denQ); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by attenuation denominator\")\n\t}\n\n\tif q.IsZero() {\n\t\treturn nil\n\t}\n\n\tvar com *quantity.Quantity\n\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\tif rate != nil {\n\t\tcom = q.Clone()\n\t\t// Multiply first.\n\t\tif err := com.Mul(rate); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t}\n\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t}\n\n\t\tif err := q.Sub(com); err != nil {\n\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t}\n\t}\n\n\tif !q.IsZero() {\n\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t}\n\t}\n\n\tif com != nil && !com.IsZero() {\n\t\tdelegation := s.Delegation(account, account)\n\n\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t}\n\n\t\ts.SetDelegation(account, account, delegation)\n\t}\n\n\ts.SetAccount(account, ent)\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func (_Contract *ContractCaller) TaskHandlingReward(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"taskHandlingReward\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (d *Dao) UseReward(id int64, usePlat string) (rst bool, err error) {\n\tif err := d.orm.\n\t\tModel(&model.AnchorReward{}).\n\t\tWhere(\"id=?\", id).\n\t\tUpdate(map[string]interface{}{\"status\": model.RewardUsed, \"use_plat\": usePlat, \"use_time\": xtime.Time(time.Now().Unix())}).Error; err != nil {\n\t\tlog.Error(\"useReward (%v) error(%v)\", id, err)\n\t\treturn rst, err\n\t}\n\trst = true\n\treturn\n}", "func (s *BlocksService) Reward(ctx context.Context) (*BlocksReward, *http.Response, error) {\n\tvar responseStruct *BlocksReward\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"blocks/getReward\", nil, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (c *Calculator) votingReward(\n\tmultiplier *big.Int,\n\tdivider *big.Int,\n\tfrom int,\n\tto int,\n\tprepInfo map[string]*pRepEnable,\n\titer icstate.VotingIterator,\n) *big.Int {\n\ttotal := new(big.Int)\n\tcheckMinVoting := c.global.GetIISSVersion() == icstate.IISSVersion2\n\tfor ; iter.Has(); iter.Next() {\n\t\tif voting, err := iter.Get(); err != nil {\n\t\t\tc.log.Errorf(\"Failed to iterate votings err=%+v\", err)\n\t\t} else {\n\t\t\tif checkMinVoting && voting.Amount().Cmp(BigIntMinDelegation) < 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts := from\n\t\t\te := to\n\t\t\tif prep, ok := prepInfo[icutils.ToKey(voting.To())]; ok {\n\t\t\t\tif prep.StartOffset() != 0 && prep.StartOffset() > s {\n\t\t\t\t\ts = prep.StartOffset()\n\t\t\t\t}\n\t\t\t\tif prep.EndOffset() != 0 && prep.EndOffset() < e {\n\t\t\t\t\te = prep.EndOffset()\n\t\t\t\t}\n\t\t\t\tperiod := e - s\n\t\t\t\tif period <= 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treward := new(big.Int).Mul(multiplier, voting.Amount())\n\t\t\t\treward.Mul(reward, big.NewInt(int64(period)))\n\t\t\t\treward.Div(reward, divider)\n\t\t\t\ttotal.Add(total, reward)\n\t\t\t\tc.log.Tracef(\"VotingReward %s: %s = %s * %s * %d / %s\",\n\t\t\t\t\tvoting.To(), reward, multiplier, voting.Amount(), period, divider)\n\t\t\t}\n\t\t}\n\t}\n\treturn total\n}", "func (owner *WalletOwnerAPI) PostTx(slate slateversions.SlateV4, fluff bool) error {\n\tparams := struct {\n\t\tToken string `json:\"token\"`\n\t\tSlate slateversions.SlateV4 `json:\"slate\"`\n\t\tFluff bool `json:\"fluff\"`\n\t}{\n\t\tToken: owner.token,\n\t\tSlate: slate,\n\t\tFluff: fluff,\n\t}\n\tparamsBytes, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn err\n\t}\n\tenvl, err := owner.client.EncryptedRequest(\"post_tx\", paramsBytes, owner.sharedSecret)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif envl == nil {\n\t\treturn errors.New(\"WalletOwnerAPI: Empty RPC Response from grin-wallet\")\n\t}\n\tif envl.Error != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"code\": envl.Error.Code,\n\t\t\t\"message\": envl.Error.Message,\n\t\t}).Error(\"WalletOwnerAPI: RPC Error during PostTx\")\n\t\treturn errors.New(string(envl.Error.Code) + \"\" + envl.Error.Message)\n\t}\n\tvar result Result\n\tif err = json.Unmarshal(envl.Result, &result); err != nil {\n\t\treturn err\n\t}\n\tif result.Err != nil {\n\t\treturn errors.New(string(result.Err))\n\t}\n\treturn nil\n}", "func (_Lmc *LmcCallerSession) GetUserRewardDebt(_userAddress common.Address, _index *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.GetUserRewardDebt(&_Lmc.CallOpts, _userAddress, _index)\n}", "func (k Keeper) ClaimDelegatorReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tclaim, found := k.GetDelegatorClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, err := k.SynchronizeDelegatorClaim(ctx, claim)\n\tif err != nil {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetDelegatorClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func GetReward(a Action, feedback Action) float64 {\n\tif a == feedback {\n\t\treturn 1\n\t}\n\treturn -1\n}", "func (del Delegation) ClaimedReward() (hexutil.Big, error) {\n\tval, err := repository.R().RewardsClaimed(&del.Address, (*big.Int)(del.Delegation.ToStakerId), nil, nil)\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\treturn (hexutil.Big)(*val), nil\n}", "func (k Keeper) ClaimUSDXMintingReward(ctx sdk.Context, owner, receiver sdk.AccAddress, multiplierName string) error {\n\tclaim, found := k.GetUSDXMintingClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, types.USDXMintingRewardDenom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", types.USDXMintingRewardDenom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tclaim, err := k.SynchronizeUSDXMintingClaim(ctx, claim)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trewardAmount := sdk.NewDecFromInt(claim.Reward.Amount).Mul(multiplier.Factor).RoundInt()\n\tif rewardAmount.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\trewardCoin := sdk.NewCoin(claim.Reward.Denom, rewardAmount)\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, sdk.NewCoins(rewardCoin), length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tk.ZeroUSDXMintingClaim(ctx, claim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claim.Reward.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, claim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_Lmc *LmcSession) GetUserRewardDebt(_userAddress common.Address, _index *big.Int) (*big.Int, error) {\n\treturn _Lmc.Contract.GetUserRewardDebt(&_Lmc.CallOpts, _userAddress, _index)\n}", "func (_Smartchef *SmartchefCallerSession) PendingReward(_user common.Address) (*big.Int, error) {\n\treturn _Smartchef.Contract.PendingReward(&_Smartchef.CallOpts, _user)\n}", "func (_Smartchef *SmartchefSession) PendingReward(_user common.Address) (*big.Int, error) {\n\treturn _Smartchef.Contract.PendingReward(&_Smartchef.CallOpts, _user)\n}", "func (_XStaking *XStakingTransactorSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.NotifyRewardAmount(&_XStaking.TransactOpts, reward)\n}", "func (_Token *TokenSession) CurrentReward(account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\treturn _Token.Contract.CurrentReward(&_Token.CallOpts, account)\n}", "func (c RewardsController) CollectReward(id string) revel.Result {\n\tif !c.GetCurrentUser() {\n\t\treturn c.ForbiddenResponse()\n\t}\n\n\tif !bson.IsObjectIdHex(id) {\n\t\treturn c.ErrorResponse(nil, c.Message(\"error.invalid\", \"\"), core.ModelStatus[core.StatusInvalidID])\n\t}\n\n\tvar selector = []bson.M{\n\t\tbson.M{\"user_id\": c.CurrentUser.GetID().Hex()},\n\t\tbson.M{\"_id\": id},\n\t\tbson.M{\"multi\": false},\n\t}\n\tvar query = bson.M{\"$set\": []bson.M{\n\t\tbson.M{\"status.name\": core.StatusObtained},\n\t\tbson.M{\"status.code\": core.ValidationStatus[core.StatusObtained]},\n\t}}\n\n\t// Get pending Rewards for the user\n\tif Reward, ok := app.Mapper.GetModel(&models.Reward{}); ok {\n\t\tif err := Reward.UpdateQuery(selector, query, false); err != nil {\n\t\t\trevel.ERROR.Print(\"ERROR Find\")\n\t\t\treturn c.ErrorResponse(err, err.Error(), 400)\n\t\t}\n\t\treturn c.SuccessResponse(bson.M{\"data\": \"Reward collected successfully\"}, \"success\", core.ModelsType[core.ModelSimpleResponse], nil)\n\t}\n\n\treturn c.ServerErrorResponse()\n}", "func (_XStaking *XStakingSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.Contract.NotifyRewardAmount(&_XStaking.TransactOpts, reward)\n}", "func (_Lmc *LmcCaller) GetUserRewardDebt(opts *bind.CallOpts, _userAddress common.Address, _index *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Lmc.contract.Call(opts, &out, \"getUserRewardDebt\", _userAddress, _index)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.NotifyRewardAmount(&_RewardsDistributionRecipient.TransactOpts, reward)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientTransactorSession) NotifyRewardAmount(reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.Contract.NotifyRewardAmount(&_RewardsDistributionRecipient.TransactOpts, reward)\n}", "func postAnswer(c *gin.Context) {\n\tplayer := c.PostForm(\"player\")\n\tslide, err := strconv.Atoi(c.Param(\"slide\"))\n\tif err != nil {\n\t\tc.String(http.StatusBadRequest, fmt.Sprintf(\"Invalid slide param: %v: %v\", c.Param(\"slide\"), err))\n\t\treturn\n\t}\n\tanswer, err := strconv.Atoi(c.PostForm(\"answer\"))\n\tif err != nil {\n\t\tc.String(http.StatusBadRequest, fmt.Sprintf(\"Invalid answer param: %v: %v\", c.PostForm(\"answer\"), err))\n\t\treturn\n\t}\n\n\tmessage := fmt.Sprintf(\"%v answered slide %v with %v\", player, slide, answer)\n\tfmt.Println(message)\n\n\t// add player if they don't exist\n\t_, found := game_data.FindPlayer(player)\n\tif !found {\n\t\tgame_data.AddPlayer(trivia.Player{Name: player})\n\t}\n\n\tif err := game_data.AddAnswer(player, slide, answer); err != nil {\n\t\tc.String(http.StatusBadRequest, fmt.Sprintf(\"Could not set answer: %v: %v\", message, err))\n\t\treturn\n\t}\n\tmyGame(c, player)\n}", "func (_Contract *ContractCaller) TaskErasingReward(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"taskErasingReward\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (v *Vending) Post(c echo.Context) error {\n\trefill, err := strconv.Atoi(c.Param(\"amount\"))\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Please fill with chocolate\")\n\t}\n\tv.chocolate += refill\n\treturn c.String(http.StatusOK, \"Vending machine refilled\")\n}", "func post(withTransfer bool, color colored.Color, amount uint64,\n\trequesterKeyPair *ed25519.KeyPair, chain *solo.Chain, contractName string,\n\tfunctionName string, params ...interface{}) (dict.Dict, error) {\n\trequest := solo.NewCallParams(contractName, functionName, params...)\n\tif withTransfer {\n\t\trequest = request.WithTransfer(color, amount)\n\t} else {\n\t\trequest = request.WithTransfer(colored.IOTA, uint64(1))\n\t}\n\tresponse, err := chain.PostRequestSync(request, requesterKeyPair)\n\treturn response, err\n}", "func (_XStaking *XStakingTransactor) NotifyRewardAmount(opts *bind.TransactOpts, reward *big.Int) (*types.Transaction, error) {\n\treturn _XStaking.contract.Transact(opts, \"notifyRewardAmount\", reward)\n}", "func (k Keeper) DeleteReward(ctx sdk.Context, stakingCoinDenom string, farmerAcc sdk.AccAddress) {\n\tstore := ctx.KVStore(k.storeKey)\n\tstore.Delete(types.GetRewardKey(stakingCoinDenom, farmerAcc))\n\tstore.Delete(types.GetRewardByFarmerAndStakingCoinDenomIndexKey(farmerAcc, stakingCoinDenom))\n}", "func (s *Spammer) PostTransaction(tx *devnetvm.Transaction, clt evilwallet.Client) {\n\tif tx == nil {\n\t\ts.log.Debug(ErrTransactionIsNil)\n\t\ts.ErrCounter.CountError(ErrTransactionIsNil)\n\t}\n\tallSolid := s.handleSolidityForReuseOutputs(clt, tx)\n\tif !allSolid {\n\t\ts.log.Debug(ErrInputsNotSolid)\n\t\ts.ErrCounter.CountError(errors.WithMessagef(ErrInputsNotSolid, \"txID: %s\", tx.ID().Base58()))\n\t\treturn\n\t}\n\n\tif err := evilwallet.RateSetterSleep(clt, s.UseRateSetter); err != nil {\n\t\treturn\n\t}\n\ttxID, blockID, err := clt.PostTransaction(tx)\n\tif err != nil {\n\t\ts.log.Debug(ErrFailPostTransaction)\n\t\ts.ErrCounter.CountError(errors.WithMessage(ErrFailPostTransaction, err.Error()))\n\t\treturn\n\t}\n\tif s.EvilScenario.OutputWallet.Type() == evilwallet.Reuse {\n\t\ts.EvilWallet.SetTxOutputsSolid(tx.Essence().Outputs(), clt.URL())\n\t}\n\n\tcount := s.State.txSent.Add(1)\n\ts.log.Debugf(\"%s: Last transaction sent, ID: %s, txCount: %d\", blockID.Base58(), txID.Base58(), count)\n}", "func (c *Contract) Payback(ctx TransactionContextInterface, jeweler string, paperNumber string, paidbackDateTime string) (*InventoryFinancingPaper, error) {\r\n\tpaper, err := ctx.GetPaperList().GetPaper(jeweler, paperNumber)\r\n\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tif paper.IsPaidBack() {\r\n\t\treturn nil, fmt.Errorf(\"paper %s:%s is already PaidBack\", jeweler, paperNumber)\r\n\t}\r\n\r\n\tpaper.SetPaidBack()\r\n\r\n\terr = ctx.GetPaperList().UpdatePaper(paper)\r\n\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tfmt.Printf(\"inventory paper %q:%q is paid back by %q,The paidback date is %q. Current state = %q\", jeweler, paperNumber, jeweler, paidbackDateTime, paper.GetState())\r\n\treturn paper, nil\r\n}", "func (msg MsgClaimUSDXMintingReward) Type() string { return TypeMsgClaimUSDXMintingReward }", "func (_Token *TokenCallerSession) CurrentReward(account common.Address) (struct {\n\tInitialDeposit *big.Int\n\tReward *big.Int\n}, error) {\n\treturn _Token.Contract.CurrentReward(&_Token.CallOpts, account)\n}", "func (k Querier) Rewards(c context.Context, req *types.QueryRewardsRequest) (*types.QueryRewardsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"invalid request\")\n\t}\n\n\tif req.StakingCoinDenom != \"\" {\n\t\tif err := sdk.ValidateDenom(req.StakingCoinDenom); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tctx := sdk.UnwrapSDKContext(c)\n\tstore := ctx.KVStore(k.storeKey)\n\tvar rewards []types.Reward\n\tvar pageRes *query.PageResponse\n\tvar err error\n\n\tif req.Farmer != \"\" {\n\t\tvar farmerAcc sdk.AccAddress\n\t\tfarmerAcc, err = sdk.AccAddressFromBech32(req.Farmer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tstorePrefix := types.GetRewardsByFarmerIndexKey(farmerAcc)\n\t\tindexStore := prefix.NewStore(store, storePrefix)\n\t\tpageRes, err = query.FilteredPaginate(indexStore, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) {\n\t\t\t_, stakingCoinDenom := types.ParseRewardsByFarmerIndexKey(append(storePrefix, key...))\n\t\t\tif req.StakingCoinDenom != \"\" {\n\t\t\t\tif stakingCoinDenom != req.StakingCoinDenom {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treward, found := k.GetReward(ctx, stakingCoinDenom, farmerAcc)\n\t\t\tif !found { // TODO: remove this check\n\t\t\t\treturn false, fmt.Errorf(\"reward not found\")\n\t\t\t}\n\t\t\tif accumulate {\n\t\t\t\trewards = append(rewards, reward)\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n\t} else {\n\t\tvar storePrefix []byte\n\t\tif req.StakingCoinDenom != \"\" {\n\t\t\tstorePrefix = types.GetRewardsByStakingCoinDenomKey(req.StakingCoinDenom)\n\t\t} else {\n\t\t\tstorePrefix = types.RewardKeyPrefix\n\t\t}\n\t\trewardStore := prefix.NewStore(store, storePrefix)\n\n\t\tpageRes, err = query.Paginate(rewardStore, req.Pagination, func(key, value []byte) error {\n\t\t\tstakingCoinDenom, farmerAcc := types.ParseRewardKey(append(storePrefix, key...))\n\t\t\trewardCoins, err := k.UnmarshalRewardCoins(value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\trewards = append(rewards, types.Reward{\n\t\t\t\tFarmer: farmerAcc.String(),\n\t\t\t\tStakingCoinDenom: stakingCoinDenom,\n\t\t\t\tRewardCoins: rewardCoins.RewardCoins,\n\t\t\t})\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryRewardsResponse{Rewards: rewards, Pagination: pageRes}, nil\n}", "func (client CloudEndpointsClient) PostRestoreResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (_IStakingRewards *IStakingRewardsTransactor) GetReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _IStakingRewards.contract.Transact(opts, \"getReward\")\n}", "func (tf TestFixture) PostTest(ctx context.Context, s *testing.FixtTestState) {\n}", "func sendMsgAddPostReaction(\n\tr *rand.Rand, app *baseapp.BaseApp, ak authkeeper.AccountKeeper, bk bankkeeper.Keeper,\n\tmsg *types.MsgAddPostReaction, ctx sdk.Context, chainID string, privkeys []cryptotypes.PrivKey,\n) error {\n\taddr, _ := sdk.AccAddressFromBech32(msg.User)\n\taccount := ak.GetAccount(ctx, addr)\n\tcoins := bk.SpendableCoins(ctx, account.GetAddress())\n\n\tfees, err := simtypes.RandomFees(r, ctx, coins)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttxGen := simappparams.MakeTestEncodingConfig().TxConfig\n\ttx, err := helpers.GenTx(\n\t\ttxGen,\n\t\t[]sdk.Msg{msg},\n\t\tfees,\n\t\tDefaultGasValue,\n\t\tchainID,\n\t\t[]uint64{account.GetAccountNumber()},\n\t\t[]uint64{account.GetSequence()},\n\t\tprivkeys...,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, _, err = app.Deliver(txGen.TxEncoder(), tx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (t *Transaction) Reward() string {\n\treturn t.reward\n}", "func (_IStakingRewards *IStakingRewardsTransactorSession) GetReward() (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.GetReward(&_IStakingRewards.TransactOpts)\n}", "func (c *GetUserPostClosestController) Post() {\n\tc.EnableXSRF = false\n\n\tcookiekey := beego.AppConfig.String(\"passid\")\n\n\t//get from cache\n\tpassId, _ := c.GetSecureCookie(cookiekey, \"passid\")\n\tif len(passId) <= 0 {\n\t\tpassId = c.GetString(\"passid\", \"\")\n\t\tif len(passId) < 1{\n\t\t\toutput, _ := library.ReturnJsonWithError(library.GetUserFail, \"ref\", nil)\n\t\t\tc.Ctx.WriteString(output)\n\t\t\treturn\n\t\t}\n\t}\n\tcahchedUser, err := models.GetUserFromCache(passId, true)\n\tif err != nil {\n\t\toutput, _ := library.ReturnJsonWithError(library.GetUserFail, \"ref\", err.Error())\n\t\tc.Ctx.WriteString(output)\n\t\treturn\n\t}\n\tuid := cahchedUser.UserProfile.Id\n\n\toption := c.GetString(\"option\")\n\tvar isNext bool = false\n\tif option == \"next\"{\n\t\tisNext = true\n\t}\n\tdate := c.GetString(\"date\")\n\tdateCorrect := strings.Replace(date, \"/\", \"\", -1)\n\tintDate ,_ := strconv.Atoi(dateCorrect)\n\tvar newPostDb = models.NewPost()\n\t//var getUser = newUser.GetUserProfile()\n\t//logs.Warning(getUser)\n\tpostList, err := newPostDb.GetUserClosestPost(uid, intDate, isNext)\n\n\tvar output string\n\n\tif err != nil{\n\t\toutput, _ = library.ReturnJsonWithError(library.CodeErrCommen, err.Error(), nil)\n\n\t}else {\n\t\toutput, _ = library.ReturnJsonWithError(library.CodeSucc, \"ref\", postList)\n\t}\n\n\tc.Ctx.WriteString(output)\n}", "func (_IStakingRewards *IStakingRewardsTransactorSession) Exit() (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.Exit(&_IStakingRewards.TransactOpts)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\n}", "func (m *MockPostDecorator) PostHandle(ctx types.Context, tx types.Tx, simulate, success bool, next types.PostHandler) (types.Context, error) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"PostHandle\", ctx, tx, simulate, success, next)\n\t// NOTE: we need to edit the generated code to call the \"next handler\"\n\treturn next(ctx, tx, simulate, success)\n}", "func (_Dospayment *DospaymentSession) ClaimGuardianReward(guardianAddr common.Address) (*types.Transaction, error) {\n\treturn _Dospayment.Contract.ClaimGuardianReward(&_Dospayment.TransactOpts, guardianAddr)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) DistributeERC20Reward(opts *bind.TransactOpts, _tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"distributeERC20Reward\", _tokenAddress, _value)\n}", "func (s *BasemumpsListener) EnterPostcondition(ctx *PostconditionContext) {}", "func (_Dospayment *DospaymentTransactorSession) ClaimGuardianReward(guardianAddr common.Address) (*types.Transaction, error) {\n\treturn _Dospayment.Contract.ClaimGuardianReward(&_Dospayment.TransactOpts, guardianAddr)\n}", "func MoveBtcCoinRewardNumber(btcidx int64) int64 {\n\tvar lvn = 21\n\tif btcidx == 1 {\n\t\treturn powf2(lvn - 1)\n\t}\n\tif btcidx > powf2(lvn)-1 {\n\t\treturn 1 // Finally, always issue an additional one\n\t}\n\tvar tarlv int\n\tfor i := 0; i < lvn; i++ {\n\t\tl := powf2(i) - 1\n\t\tr := powf2(i+1) - 1\n\t\tif btcidx > l && btcidx <= r {\n\t\t\ttarlv = i + 1\n\t\t\tbreak\n\t\t}\n\t}\n\treturn powf2(lvn - tarlv)\n}", "func (s *PostSvc) RmvPost(ctx context.Context, req *pb.RmvPostReq) (*pb.RmvPostResp, error) {\n\treturn s.db.RmvPost(ctx, req)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\n}", "func ValidateRewardTx(tx *types.Transaction, header *types.BlockHeader) error {\n\tif tx.Data.Type != types.TxTypeReward || !tx.Data.From.IsEmpty() || tx.Data.AccountNonce != 0 || tx.Data.GasPrice.Cmp(common.Big0) != 0 || tx.Data.GasLimit != 0 || len(tx.Data.Payload) != 0 {\n\t\treturn errInvalidReward\n\t}\n\n\t// validate to address\n\tto := tx.Data.To\n\tif to.IsEmpty() {\n\t\treturn errEmptyToAddress\n\t}\n\n\tif !to.Equal(header.Creator) {\n\t\treturn errCoinbaseMismatch\n\t}\n\n\t// validate reward\n\tamount := tx.Data.Amount\n\tif err := validateReward(amount); err != nil {\n\t\treturn err\n\t}\n\n\treward := consensus.GetReward(header.Height)\n\tif reward == nil || reward.Cmp(amount) != 0 {\n\t\treturn fmt.Errorf(\"invalid reward Amount, block height %d, want %s, got %s\", header.Height, reward, amount)\n\t}\n\n\t// validate timestamp\n\tif tx.Data.Timestamp != header.CreateTimestamp.Uint64() {\n\t\treturn errTimestampMismatch\n\t}\n\n\treturn nil\n}", "func (transaction *AccountCreateTransaction) SetDeclineStakingReward(decline bool) *AccountCreateTransaction {\n\ttransaction._RequireNotFrozen()\n\ttransaction.declineReward = decline\n\treturn transaction\n}", "func (_IStakingRewards *IStakingRewardsSession) GetReward() (*types.Transaction, error) {\n\treturn _IStakingRewards.Contract.GetReward(&_IStakingRewards.TransactOpts)\n}", "func (_Lmc *LmcCaller) GetUserAccumulatedReward(opts *bind.CallOpts, _userAddress common.Address, tokenIndex *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Lmc.contract.Call(opts, &out, \"getUserAccumulatedReward\", _userAddress, tokenIndex)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (am *AS3Manager) postAgentResponse(msgRsp MessageResponse) {\n\tselect {\n\tcase am.RspChan <- msgRsp:\n\tcase <-am.RspChan:\n\t\tam.RspChan <- msgRsp\n\t}\n}", "func (am *AS3Manager) postAgentResponse(msgRsp MessageResponse) {\n\tselect {\n\tcase am.RspChan <- msgRsp:\n\tcase <-am.RspChan:\n\t\tam.RspChan <- msgRsp\n\t}\n}", "func (_IStakingRewards *IStakingRewardsCaller) LastTimeRewardApplicable(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _IStakingRewards.contract.Call(opts, &out, \"lastTimeRewardApplicable\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (k Keeper) ClaimHardReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tk.SynchronizeHardLiquidityProviderClaim(ctx, owner)\n\n\tsyncedClaim, found := k.GetHardLiquidityProviderClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetHardLiquidityProviderClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_Smartchef *SmartchefCaller) RewardPerBlock(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Smartchef.contract.Call(opts, out, \"rewardPerBlock\")\n\treturn *ret0, err\n}", "func (e *EvaluationHandler) PostTestResult(c *gin.Context) {\n\t// User session\n\tloggedIn := e.Middleware.GetLoggedInUser(c)\n\n\t// Result\n\tresult := e.EvaluationUsecase.PostTestResult(loggedIn.Username)\n\n\t// Post test status\n\tpostTestStatus := 1\n\tcourses := e.LearningUsecase.GetCourseList()\n\tfor _, course := range courses {\n\t\t_, statusCode := course.GetParticipantStatus(loggedIn.Username)\n\t\tif statusCode < 2 {\n\t\t\tpostTestStatus = 0\n\t\t}\n\t}\n\n\t// User complete past test\n\tcertificate := \"\"\n\tif result.Pass && postTestStatus == 1 {\n\t\tpostTestStatus = 2\n\t\tcertificate = \"Coursera%20XZS4R52UDZFN.pdf\"\n\t}\n\n\t// Response\n\tgrade := fmt.Sprintf(\"%.f\", result.Grade)\n\tmsg := \"To Pass get 80%\"\n\tres := PostTestResultResponse{\n\t\tGrade: grade + \"%\",\n\t\tPass: result.Pass,\n\t\tStatus: postTestStatus,\n\t\tCertificateUrl: certificate,\n\t}\n\tresponse.RespondSuccessJSON(c.Writer, res, msg)\n}", "func (c4 *Connect4) GetReward() int {\n\tif c4.Winner == nil {\n\t\treturn 0\n\t} else if *c4.Winner == 1 {\n\t\treturn 1\n\t}\n\treturn -1\n}", "func (client ManagementClient) PostUserRequestaudittrailResponder(resp *http.Response) (result autorest.Response, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByClosing())\n result.Response = resp\n return\n }", "func (_XStaking *XStakingTransactor) GetReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _XStaking.contract.Transact(opts, \"getReward\")\n}", "func (_Contract *ContractCallerSession) TaskHandlingReward() (*big.Int, error) {\n\treturn _Contract.Contract.TaskHandlingReward(&_Contract.CallOpts)\n}", "func (_RewardsDistributionRecipient *RewardsDistributionRecipientTransactor) NotifyRewardAmount(opts *bind.TransactOpts, reward *big.Int) (*types.Transaction, error) {\n\treturn _RewardsDistributionRecipient.contract.Transact(opts, \"notifyRewardAmount\", reward)\n}", "func redeem (stub shim.ChaincodeStubInterface, args []string) ([]byte,error){\n\n\tif len(args) != 5 {\n\t\t\tfmt.Println(\" Incorrect number of arguments sent to redeem. Expecting 5. Received \" + strconv.Itoa(len(args)))\n\t\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 5\")\n\t\t}\n\n\t\t_, err := LoyaltyPkg.RedeemPoints(stub, args)\n\n\tif err != nil {\n\n\t\tfmt.Println(err)\n\t\treturn nil, errors.New(\"Errors while creating wallet for user \" + args[0])\n\t}\n\n\tlogger.Info(\"Successfully redeemed points for user \" + args[0])\n\n\treturn nil, nil\n\n}", "func (client ManagementClient) PostUserRefreshtokenforuseraccountResponder(resp *http.Response) (result autorest.Response, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByClosing())\n result.Response = resp\n return\n }", "func (_Ethdkg *EthdkgTransactor) SubmitDispute(opts *bind.TransactOpts, issuer common.Address, issuer_list_idx *big.Int, disputer_list_idx *big.Int, encrypted_shares []*big.Int, commitments [][2]*big.Int, shared_key [2]*big.Int, shared_key_correctness_proof [2]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.contract.Transact(opts, \"submit_dispute\", issuer, issuer_list_idx, disputer_list_idx, encrypted_shares, commitments, shared_key, shared_key_correctness_proof)\n}", "func (_XStaking *XStakingCaller) RewardRate(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewardRate\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (b *Builder) StartPost(ctx context.Context, rewardAddress types.Address, dataDir string, space uint64) error {\n\tlogger := b.log.WithContext(ctx)\n\tif !atomic.CompareAndSwapInt32(&b.initStatus, InitIdle, InitInProgress) {\n\t\tswitch atomic.LoadInt32(&b.initStatus) {\n\t\tcase InitDone:\n\t\t\treturn fmt.Errorf(\"already initialized\")\n\t\tcase InitInProgress:\n\t\t\treturn fmt.Errorf(\"already started\")\n\t\t}\n\t}\n\n\tif err := b.postProver.SetParams(dataDir, space); err != nil {\n\t\treturn err\n\t}\n\tb.SetCoinbaseAccount(rewardAddress)\n\n\tinitialized, _, err := b.postProver.IsInitialized()\n\tif err != nil {\n\t\tatomic.StoreInt32(&b.initStatus, InitIdle)\n\t\treturn err\n\t}\n\n\tif !initialized {\n\t\tif err := b.postProver.VerifyInitAllowed(); err != nil {\n\t\t\tatomic.StoreInt32(&b.initStatus, InitIdle)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlogger.With().Info(\"starting post initialization\",\n\t\tlog.String(\"datadir\", dataDir),\n\t\tlog.String(\"space\", fmt.Sprintf(\"%d\", space)),\n\t\tlog.String(\"rewardAddress\", fmt.Sprintf(\"%x\", rewardAddress)),\n\t)\n\n\tgo func() {\n\t\tif initialized {\n\t\t\t// If initialized, run the execution phase with zero-challenge,\n\t\t\t// to create the initial proof (the commitment).\n\t\t\tb.commitment, err = b.postProver.Execute(shared.ZeroChallenge)\n\t\t\tif err != nil {\n\t\t\t\tlogger.With().Error(\"post execution failed\", log.Err(err))\n\t\t\t\tatomic.StoreInt32(&b.initStatus, InitIdle)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\t// If not initialized, run the initialization phase.\n\t\t\t// This would create the initial proof (the commitment) as well.\n\t\t\tb.commitment, err = b.postProver.Initialize()\n\t\t\tif err != nil {\n\t\t\t\tlogger.With().Error(\"post initialization failed\", log.Err(err))\n\t\t\t\tatomic.StoreInt32(&b.initStatus, InitIdle)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tlogger.With().Info(\"post initialization completed\",\n\t\t\tlog.String(\"datadir\", dataDir),\n\t\t\tlog.String(\"space\", fmt.Sprintf(\"%d\", space)),\n\t\t\tlog.String(\"commitment merkle root\", fmt.Sprintf(\"%x\", b.commitment.MerkleRoot)),\n\t\t)\n\n\t\tatomic.StoreInt32(&b.initStatus, InitDone)\n\t\tclose(b.initDone)\n\t}()\n\n\treturn nil\n}" ]
[ "0.7498109", "0.6607101", "0.5900165", "0.574824", "0.5748048", "0.5657382", "0.5594524", "0.5589504", "0.55825084", "0.54884845", "0.54612577", "0.525241", "0.5206265", "0.5183272", "0.5154278", "0.5114508", "0.510423", "0.5094205", "0.5076016", "0.5053601", "0.5036061", "0.5011486", "0.50109583", "0.49988496", "0.49979222", "0.49852508", "0.49648166", "0.49568868", "0.49563044", "0.4950898", "0.494989", "0.4947571", "0.4938006", "0.49285802", "0.492693", "0.48947155", "0.48879582", "0.4877172", "0.4859275", "0.48472297", "0.48414806", "0.48300937", "0.4822483", "0.4814368", "0.47971287", "0.47770178", "0.47758803", "0.4770533", "0.47610724", "0.47584832", "0.47434106", "0.47418407", "0.47324914", "0.47269446", "0.47238335", "0.4720381", "0.47202805", "0.47197434", "0.47197115", "0.47119817", "0.46994978", "0.46976933", "0.46962345", "0.4693751", "0.4689654", "0.4685987", "0.467774", "0.46753466", "0.46740383", "0.46686044", "0.4664151", "0.4660877", "0.46599", "0.4653724", "0.4649478", "0.46435764", "0.4640306", "0.4639294", "0.46145603", "0.46028376", "0.45844007", "0.45768958", "0.4575707", "0.45695782", "0.45616046", "0.45616046", "0.45600158", "0.45588917", "0.4551121", "0.45502904", "0.45496023", "0.45460382", "0.45449683", "0.45362064", "0.4526416", "0.45238832", "0.4514642", "0.45107612", "0.45067087", "0.450342" ]
0.85944164
0
postReward encumbers a previouslydeposited reward according to the current vesting apportionment of staking. Note that rewards might be unvested, but are unlocked.
func (va ClawbackVestingAccount) postReward(ctx sdk.Context, reward sdk.Coins, ak AccountKeeper, bk BankKeeper, sk StakingKeeper) { // Find the scheduled amount of vested and unvested staking tokens bondDenom := sk.BondDenom(ctx) vested := ReadSchedule(va.StartTime, va.EndTime, va.VestingPeriods, va.OriginalVesting, ctx.BlockTime().Unix()).AmountOf(bondDenom) unvested := va.OriginalVesting.AmountOf(bondDenom).Sub(vested) if unvested.IsZero() { // no need to adjust the vesting schedule return } if vested.IsZero() { // all staked tokens must be unvested va.distributeReward(ctx, ak, bondDenom, reward) return } // Find current split of account balance on staking axis bonded := sk.GetDelegatorBonded(ctx, va.GetAddress()) unbonding := sk.GetDelegatorUnbonding(ctx, va.GetAddress()) delegated := bonded.Add(unbonding) // discover what has been slashed and remove from delegated amount oldDelegated := va.DelegatedVesting.AmountOf(bondDenom).Add(va.DelegatedFree.AmountOf(bondDenom)) slashed := oldDelegated.Sub(intMin(oldDelegated, delegated)) delegated = delegated.Sub(intMin(delegated, slashed)) // Prefer delegated tokens to be unvested unvested = intMin(unvested, delegated) vested = delegated.Sub(unvested) // Compute the unvested amount of reward and add to vesting schedule if unvested.IsZero() { return } if vested.IsZero() { va.distributeReward(ctx, ak, bondDenom, reward) return } unvestedRatio := unvested.ToDec().QuoTruncate(bonded.ToDec()) // round down unvestedReward := scaleCoins(reward, unvestedRatio) va.distributeReward(ctx, ak, bondDenom, unvestedReward) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (va *ClawbackVestingAccount) PostReward(ctx sdk.Context, reward sdk.Coins, action exported.RewardAction) error {\n\treturn action.ProcessReward(ctx, reward, va)\n}", "func (va ClawbackVestingAccount) distributeReward(ctx sdk.Context, ak AccountKeeper, bondDenom string, reward sdk.Coins) {\n\tnow := ctx.BlockTime().Unix()\n\tt := va.StartTime\n\tfirstUnvestedPeriod := 0\n\tunvestedTokens := sdk.ZeroInt()\n\tfor i, period := range va.VestingPeriods {\n\t\tt += period.Length\n\t\tif t <= now {\n\t\t\tfirstUnvestedPeriod = i + 1\n\t\t\tcontinue\n\t\t}\n\t\tunvestedTokens = unvestedTokens.Add(period.Amount.AmountOf(bondDenom))\n\t}\n\n\trunningTotReward := sdk.NewCoins()\n\trunningTotStaking := sdk.ZeroInt()\n\tfor i := firstUnvestedPeriod; i < len(va.VestingPeriods); i++ {\n\t\tperiod := va.VestingPeriods[i]\n\t\trunningTotStaking = runningTotStaking.Add(period.Amount.AmountOf(bondDenom))\n\t\trunningTotRatio := runningTotStaking.ToDec().Quo(unvestedTokens.ToDec())\n\t\ttargetCoins := scaleCoins(reward, runningTotRatio)\n\t\tthisReward := targetCoins.Sub(runningTotReward)\n\t\trunningTotReward = targetCoins\n\t\tperiod.Amount = period.Amount.Add(thisReward...)\n\t\tva.VestingPeriods[i] = period\n\t}\n\n\tva.OriginalVesting = va.OriginalVesting.Add(reward...)\n\tak.SetAccount(ctx, &va)\n}", "func (a Actor) AwardBlockReward(rt vmr.Runtime, params *AwardBlockRewardParams) *adt.EmptyValue {\n\trt.ValidateImmediateCallerIs(builtin.SystemActorAddr)\n\tAssertMsg(rt.CurrentBalance().GreaterThanEqual(params.GasReward),\n\t\t\"actor current balance %v insufficient to pay gas reward %v\", rt.CurrentBalance(), params.GasReward)\n\n\tAssertMsg(params.TicketCount > 0, \"cannot give block reward for zero tickets\")\n\n\tminer, ok := rt.ResolveAddress(params.Miner)\n\tif !ok {\n\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to resolve given owner address\")\n\t}\n\n\tpriorBalance := rt.CurrentBalance()\n\n\tvar penalty abi.TokenAmount\n\tvar st State\n\trt.State().Transaction(&st, func() interface{} {\n\t\tblockReward := a.computeBlockReward(&st, big.Sub(priorBalance, params.GasReward), params.TicketCount)\n\t\ttotalReward := big.Add(blockReward, params.GasReward)\n\n\t\t// Cap the penalty at the total reward value.\n\t\tpenalty = big.Min(params.Penalty, totalReward)\n\n\t\t// Reduce the payable reward by the penalty.\n\t\trewardPayable := big.Sub(totalReward, penalty)\n\n\t\tAssertMsg(big.Add(rewardPayable, penalty).LessThanEqual(priorBalance),\n\t\t\t\"reward payable %v + penalty %v exceeds balance %v\", rewardPayable, penalty, priorBalance)\n\n\t\t// Record new reward into reward map.\n\t\tif rewardPayable.GreaterThan(abi.NewTokenAmount(0)) {\n\t\t\tnewReward := Reward{\n\t\t\t\tStartEpoch: rt.CurrEpoch(),\n\t\t\t\tEndEpoch: rt.CurrEpoch() + rewardVestingPeriod,\n\t\t\t\tValue: rewardPayable,\n\t\t\t\tAmountWithdrawn: abi.NewTokenAmount(0),\n\t\t\t\tVestingFunction: rewardVestingFunction,\n\t\t\t}\n\t\t\tif err := st.addReward(adt.AsStore(rt), miner, &newReward); err != nil {\n\t\t\t\trt.Abortf(exitcode.ErrIllegalState, \"failed to add reward to rewards map: %w\", err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\t// Burn the penalty amount.\n\t_, code := rt.Send(builtin.BurntFundsActorAddr, builtin.MethodSend, nil, penalty)\n\tbuiltin.RequireSuccess(rt, code, \"failed to send penalty to BurntFundsActor\")\n\n\treturn nil\n}", "func (s *Spammer) PostTransaction(tx *devnetvm.Transaction, clt evilwallet.Client) {\n\tif tx == nil {\n\t\ts.log.Debug(ErrTransactionIsNil)\n\t\ts.ErrCounter.CountError(ErrTransactionIsNil)\n\t}\n\tallSolid := s.handleSolidityForReuseOutputs(clt, tx)\n\tif !allSolid {\n\t\ts.log.Debug(ErrInputsNotSolid)\n\t\ts.ErrCounter.CountError(errors.WithMessagef(ErrInputsNotSolid, \"txID: %s\", tx.ID().Base58()))\n\t\treturn\n\t}\n\n\tif err := evilwallet.RateSetterSleep(clt, s.UseRateSetter); err != nil {\n\t\treturn\n\t}\n\ttxID, blockID, err := clt.PostTransaction(tx)\n\tif err != nil {\n\t\ts.log.Debug(ErrFailPostTransaction)\n\t\ts.ErrCounter.CountError(errors.WithMessage(ErrFailPostTransaction, err.Error()))\n\t\treturn\n\t}\n\tif s.EvilScenario.OutputWallet.Type() == evilwallet.Reuse {\n\t\ts.EvilWallet.SetTxOutputsSolid(tx.Essence().Outputs(), clt.URL())\n\t}\n\n\tcount := s.State.txSent.Add(1)\n\ts.log.Debugf(\"%s: Last transaction sent, ID: %s, txCount: %d\", blockID.Base58(), txID.Base58(), count)\n}", "func (c *Client) RenterPostAllowance(allowance modules.Allowance) (err error) {\n\tvalues := url.Values{}\n\tvalues.Set(\"funds\", allowance.Funds.String())\n\tvalues.Set(\"hosts\", strconv.FormatUint(allowance.Hosts, 10))\n\tvalues.Set(\"period\", strconv.FormatUint(uint64(allowance.Period), 10))\n\tvalues.Set(\"renewwindow\", strconv.FormatUint(uint64(allowance.RenewWindow), 10))\n\terr = c.post(\"/renter\", values.Encode(), nil)\n\treturn\n}", "func post(withTransfer bool, color colored.Color, amount uint64,\n\trequesterKeyPair *ed25519.KeyPair, chain *solo.Chain, contractName string,\n\tfunctionName string, params ...interface{}) (dict.Dict, error) {\n\trequest := solo.NewCallParams(contractName, functionName, params...)\n\tif withTransfer {\n\t\trequest = request.WithTransfer(color, amount)\n\t} else {\n\t\trequest = request.WithTransfer(colored.IOTA, uint64(1))\n\t}\n\tresponse, err := chain.PostRequestSync(request, requesterKeyPair)\n\treturn response, err\n}", "func (owner *WalletOwnerAPI) PostTx(slate slateversions.SlateV4, fluff bool) error {\n\tparams := struct {\n\t\tToken string `json:\"token\"`\n\t\tSlate slateversions.SlateV4 `json:\"slate\"`\n\t\tFluff bool `json:\"fluff\"`\n\t}{\n\t\tToken: owner.token,\n\t\tSlate: slate,\n\t\tFluff: fluff,\n\t}\n\tparamsBytes, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn err\n\t}\n\tenvl, err := owner.client.EncryptedRequest(\"post_tx\", paramsBytes, owner.sharedSecret)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif envl == nil {\n\t\treturn errors.New(\"WalletOwnerAPI: Empty RPC Response from grin-wallet\")\n\t}\n\tif envl.Error != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"code\": envl.Error.Code,\n\t\t\t\"message\": envl.Error.Message,\n\t\t}).Error(\"WalletOwnerAPI: RPC Error during PostTx\")\n\t\treturn errors.New(string(envl.Error.Code) + \"\" + envl.Error.Message)\n\t}\n\tvar result Result\n\tif err = json.Unmarshal(envl.Result, &result); err != nil {\n\t\treturn err\n\t}\n\tif result.Err != nil {\n\t\treturn errors.New(string(result.Err))\n\t}\n\treturn nil\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) DistributeETHReward(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"distributeETHReward\")\n}", "func (vi *votedInfo) CalculateReward(multiplier, divider *big.Int, period int) {\n\tif multiplier.Sign() == 0 || period == 0 {\n\t\treturn\n\t}\n\tif divider.Sign() == 0 || vi.totalBondedDelegation.Sign() == 0 {\n\t\treturn\n\t}\n\t// reward = multiplier * period * bondedDelegation / (divider * totalBondedDelegation)\n\tbase := new(big.Int).Mul(multiplier, big.NewInt(int64(period)))\n\treward := new(big.Int)\n\tfor i, addrKey := range vi.rank {\n\t\tif i == vi.maxRankForReward {\n\t\t\tbreak\n\t\t}\n\t\tprep := vi.preps[addrKey]\n\t\tif prep.Enable() == false {\n\t\t\tcontinue\n\t\t}\n\n\t\treward.Mul(base, prep.GetBondedDelegation())\n\t\treward.Div(reward, divider)\n\t\treward.Div(reward, vi.totalBondedDelegation)\n\n\t\tlog.Tracef(\"VOTED REWARD %d = %d * %d * %d / (%d * %d)\",\n\t\t\treward, multiplier, period, prep.GetBondedDelegation(), divider, vi.totalBondedDelegation)\n\n\t\tprep.SetIScore(new(big.Int).Add(prep.IScore(), reward))\n\t}\n}", "func (requestManager *RequestManager) PostWithTransfer(requesterKeyPair *ed25519.KeyPair, color colored.Color, amount uint64,\n\tchain *solo.Chain, contractName string, functionName string, params ...interface{}) (dict.Dict, error) {\n\tresponse, err := post(true, color, amount, requesterKeyPair, chain, contractName, functionName, params...)\n\treturn response, err\n}", "func ApplyRewardTx(tx *types.Transaction, statedb *state.Statedb) (*types.Receipt, error) {\n\tstatedb.CreateAccount(tx.Data.To)\n\tstatedb.AddBalance(tx.Data.To, tx.Data.Amount)\n\n\thash, err := statedb.Hash()\n\tif err != nil {\n\t\treturn nil, errors.NewStackedError(err, \"failed to get statedb root hash\")\n\t}\n\n\treceipt := &types.Receipt{\n\t\tTxHash: tx.Hash,\n\t\tPostState: hash,\n\t}\n\n\treturn receipt, nil\n}", "func (k Keeper) ClaimSwapReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedSwapClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetSwapClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (transaction *AccountCreateTransaction) SetDeclineStakingReward(decline bool) *AccountCreateTransaction {\n\ttransaction._RequireNotFrozen()\n\ttransaction.declineReward = decline\n\treturn transaction\n}", "func (c *Coinbase) AddReward(output *Output) {\n\toutput.EncryptedMask = make([]byte, 1)\n\tc.Rewards = append(c.Rewards, output)\n}", "func (k Keeper) ClaimSavingsReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tk.SynchronizeSavingsClaim(ctx, owner)\n\n\tsyncedClaim, found := k.GetSavingsClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetSavingsClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeETHReward() (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeETHReward(&_BondedECDSAKeep.TransactOpts)\n}", "func (k Keeper) ClaimEarnReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, found := k.GetSynchronizedEarnClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetEarnClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (s *MutableState) AddRewardSingleAttenuated(time epochtime.EpochTime, factor *quantity.Quantity, attenuationNumerator, attenuationDenominator int, account signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tvar numQ, denQ quantity.Quantity\n\tif err = numQ.FromInt64(int64(attenuationNumerator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation numerator %d\", attenuationNumerator)\n\t}\n\tif err = denQ.FromInt64(int64(attenuationDenominator)); err != nil {\n\t\treturn errors.Wrapf(err, \"importing attenuation denominator %d\", attenuationDenominator)\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tent := s.Account(account)\n\n\tq := ent.Escrow.Active.Balance.Clone()\n\t// Multiply first.\n\tif err := q.Mul(factor); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t}\n\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t}\n\tif err := q.Mul(&numQ); err != nil {\n\t\treturn errors.Wrap(err, \"multiplying by attenuation numerator\")\n\t}\n\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t}\n\tif err := q.Quo(&denQ); err != nil {\n\t\treturn errors.Wrap(err, \"dividing by attenuation denominator\")\n\t}\n\n\tif q.IsZero() {\n\t\treturn nil\n\t}\n\n\tvar com *quantity.Quantity\n\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\tif rate != nil {\n\t\tcom = q.Clone()\n\t\t// Multiply first.\n\t\tif err := com.Mul(rate); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t}\n\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t}\n\n\t\tif err := q.Sub(com); err != nil {\n\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t}\n\t}\n\n\tif !q.IsZero() {\n\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t}\n\t}\n\n\tif com != nil && !com.IsZero() {\n\t\tdelegation := s.Delegation(account, account)\n\n\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t}\n\n\t\ts.SetDelegation(account, account, delegation)\n\t}\n\n\ts.SetAccount(account, ent)\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func (as AccountStorage) SetReward(ctx sdk.Context, accKey types.AccountKey, reward *Reward) sdk.Error {\n\tstore := ctx.KVStore(as.key)\n\trewardByte, err := as.cdc.MarshalJSON(*reward)\n\tif err != nil {\n\t\treturn ErrFailedToMarshalReward(err)\n\t}\n\tstore.Set(getRewardKey(accKey), rewardByte)\n\treturn nil\n}", "func (cra clawbackRewardAction) ProcessReward(ctx sdk.Context, reward sdk.Coins, rawAccount exported.VestingAccount) error {\n\tcva, ok := rawAccount.(*ClawbackVestingAccount)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrNotSupported, \"expected *ClawbackVestingAccount, got %T\", rawAccount)\n\t}\n\tcva.postReward(ctx, reward, cra.ak, cra.bk, cra.sk)\n\treturn nil\n}", "func (_Ethdkg *EthdkgTransactor) SubmitDispute(opts *bind.TransactOpts, issuer common.Address, issuer_list_idx *big.Int, disputer_list_idx *big.Int, encrypted_shares []*big.Int, commitments [][2]*big.Int, shared_key [2]*big.Int, shared_key_correctness_proof [2]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.contract.Transact(opts, \"submit_dispute\", issuer, issuer_list_idx, disputer_list_idx, encrypted_shares, commitments, shared_key, shared_key_correctness_proof)\n}", "func (k Keeper) ClaimUSDXMintingReward(ctx sdk.Context, owner, receiver sdk.AccAddress, multiplierName string) error {\n\tclaim, found := k.GetUSDXMintingClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, types.USDXMintingRewardDenom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", types.USDXMintingRewardDenom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tclaim, err := k.SynchronizeUSDXMintingClaim(ctx, claim)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trewardAmount := sdk.NewDecFromInt(claim.Reward.Amount).Mul(multiplier.Factor).RoundInt()\n\tif rewardAmount.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\trewardCoin := sdk.NewCoin(claim.Reward.Denom, rewardAmount)\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, sdk.NewCoins(rewardCoin), length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tk.ZeroUSDXMintingClaim(ctx, claim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claim.Reward.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, claim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (v *Vending) Post(c echo.Context) error {\n\trefill, err := strconv.Atoi(c.Param(\"amount\"))\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Please fill with chocolate\")\n\t}\n\tv.chocolate += refill\n\treturn c.String(http.StatusOK, \"Vending machine refilled\")\n}", "func (rig *testRig) redeem_taker(checkStatus bool) error {\n\tmatchInfo := rig.matchInfo\n\tmatchInfo.db.takerRedeem = rig.redeem(matchInfo.taker, matchInfo.takerOID)\n\ttracker := rig.getTracker()\n\t// Check the match status\n\tif checkStatus {\n\t\tif tracker != nil {\n\t\t\treturn fmt.Errorf(\"expected match to be removed, found it, in status %v\", tracker.Status)\n\t\t}\n\t\terr := rig.checkResponse(matchInfo.taker, \"redeem\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func placeBet(ctx coretypes.Sandbox) error {\n\tctx.Event(\"placeBet\")\n\tparams := ctx.Params()\n\n\tstate := ctx.State()\n\n\t// if there are some bets locked, save the entropy derived immediately from it.\n\t// it is not predictable at the moment of locking and this saving makes it not playable later\n\t// entropy saved this way is derived (hashed) from the locking transaction hash\n\t// we do this trick to be able to deterministically check if smart contract is really fair.\n\t// The played color is a deterministic function of the hash of transaction which locked the bets\n\tif collections.NewArray(state, StateVarLockedBets).MustLen() > 0 {\n\t\tok := state.MustHas(StateVarEntropyFromLocking)\n\t\tif !ok {\n\t\t\tehv := ctx.GetEntropy()\n\t\t\tstate.Set(StateVarEntropyFromLocking, codec.EncodeHashValue(&ehv))\n\t\t}\n\t}\n\n\t// take input addresses of the request transaction. Must be exactly 1 otherwise.\n\t// Theoretically the transaction may have several addresses in inputs, then it is ignored\n\tsender := ctx.Caller()\n\n\t// look if there're some iotas left for the bet after minimum rewards are already taken.\n\t// Here we are accessing only the part of the UTXOs which the ones which are coming with the current request\n\tsum := ctx.IncomingTransfer().Balance(balance.ColorIOTA)\n\tif sum == 0 {\n\t\t// nothing to bet\n\t\treturn fmt.Errorf(\"placeBet: sum == 0: nothing to bet\")\n\t}\n\t// check if there's a Color variable among args. If not, ignore the request\n\tcol, ok, _ := codec.DecodeInt64(params.MustGet(ReqVarColor))\n\tif !ok {\n\t\treturn fmt.Errorf(\"wrong request, no Color specified\")\n\t}\n\tfirstBet := collections.NewArray(state, StateVarBets).MustLen() == 0\n\n\treqid := ctx.RequestID()\n\tbetInfo := &BetInfo{\n\t\tPlayer: sender,\n\t\tSum: sum,\n\t\treqId: reqid,\n\t\tColor: byte(col % NumColors),\n\t}\n\n\t// save the bet info in the array\n\tcollections.NewArray(state, StateVarBets).MustPush(encodeBetInfo(betInfo))\n\n\tctx.Event(fmt.Sprintf(\"Place bet: player: %s sum: %d color: %d req: %s\", sender.String(), sum, col, reqid.Short()))\n\n\terr := withPlayerStats(ctx, &betInfo.Player, func(ps *PlayerStats) {\n\t\tps.Bets += 1\n\t})\n\tif err != nil {\n\t\tctx.Log().Panicf(\"%v\", err)\n\t}\n\n\t// if it is the first bet in the array, send time locked 'LockBets' request to itself.\n\t// it will be time-locked by default for the next 2 minutes, the it will be processed by smart contract\n\tif firstBet {\n\t\tperiod, ok, _ := codec.DecodeInt64(state.MustGet(ReqVarPlayPeriodSec))\n\t\tif !ok || period < 10 {\n\t\t\tperiod = DefaultPlaySecondsAfterFirstBet\n\t\t}\n\n\t\tnextPlayTimestamp := (time.Duration(ctx.GetTimestamp())*time.Nanosecond + time.Duration(period)*time.Second).Nanoseconds()\n\t\tstate.Set(StateVarNextPlayTimestamp, codec.EncodeInt64(nextPlayTimestamp))\n\n\t\tctx.Event(fmt.Sprintf(\"PostRequestToSelfWithDelay period = %d\", period))\n\n\t\t// send the timelocked Lock request to self. TimeLock is for number of seconds taken from the state variable\n\t\t// By default it is 2 minutes, i.e. Lock request will be processed after 2 minutes.\n\t\tif ctx.PostRequest(coretypes.PostRequestParams{\n\t\t\tTargetContractID: ctx.ContractID(),\n\t\t\tEntryPoint: RequestLockBets,\n\t\t\tTimeLock: uint32(period),\n\t\t}) {\n\t\t\tctx.Event(fmt.Sprintf(\"play deadline is set after %d seconds\", period))\n\t\t} else {\n\t\t\tctx.Event(fmt.Sprintf(\"failed to set play deadline\"))\n\t\t}\n\t}\n\treturn nil\n}", "func (_Ethdkg *EthdkgSession) SubmitDispute(issuer common.Address, issuer_list_idx *big.Int, disputer_list_idx *big.Int, encrypted_shares []*big.Int, commitments [][2]*big.Int, shared_key [2]*big.Int, shared_key_correctness_proof [2]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.Contract.SubmitDispute(&_Ethdkg.TransactOpts, issuer, issuer_list_idx, disputer_list_idx, encrypted_shares, commitments, shared_key, shared_key_correctness_proof)\n}", "func (w *worker) postSideBlock(event blockchain.ChainSideEvent) {\n\tselect {\n\tcase w.chainSideCh <- event:\n\tcase <-w.exitCh:\n\t}\n}", "func Redeem(contract []byte, contractTx wire.MsgTx, secret []byte, currency string, autopublish bool) (api.RedeemResponse, error) {\n\tnetwork := RetrieveNetwork(currency)\n\tclient := GetRPCClient(currency)\n\n\tdefer func() {\n\t\tclient.Shutdown()\n\t\tclient.WaitForShutdown()\n\t}()\n\n\tpushes, err := txscript.ExtractAtomicSwapDataPushes(0, contract)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\tif pushes == nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, errors.New(\"contract is not an atomic swap script recognized by this tool\")\n\t}\n\n\trecipientAddr, err := diviutil.NewAddressPubKeyHash(pushes.RecipientHash160[:], network)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\tcontractHash := diviutil.Hash160(contract)\n\tcontractOut := -1\n\tfor i, out := range contractTx.TxOut {\n\t\tsc, addrs, _, _ := txscript.ExtractPkScriptAddrs(out.PkScript, network)\n\t\tif sc == txscript.ScriptHashTy &&\n\t\t\tbytes.Equal(addrs[0].(*diviutil.AddressScriptHash).Hash160()[:], contractHash) {\n\t\t\tcontractOut = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif contractOut == -1 {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, errors.New(\"transaction does not contain a contract output\")\n\t}\n\n\taddr, err := RawChangeAddress(client, currency)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\toutScript, err := txscript.PayToAddrScript(addr)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\n\tcontractTxHash := contractTx.TxHash()\n\tcontractOutPoint := wire.OutPoint{\n\t\tHash: contractTxHash,\n\t\tIndex: uint32(contractOut),\n\t}\n\n\tfeePerKb, minFeePerKb, err := GetFees(client, currency)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\n\tredeemTx := wire.NewMsgTx(util.TXVersion)\n\tredeemTx.LockTime = uint32(pushes.LockTime)\n\tredeemTx.AddTxIn(wire.NewTxIn(&contractOutPoint, nil, nil))\n\tredeemTx.AddTxOut(wire.NewTxOut(0, outScript)) // amount set below\n\tredeemSize := util.EstimateRedeemSerializeSize(contract, redeemTx.TxOut)\n\tfee := txrules.FeeForSerializeSize(feePerKb, redeemSize)\n\tredeemTx.TxOut[0].Value = contractTx.TxOut[contractOut].Value - int64(fee)\n\tif txrules.IsDustOutput(redeemTx.TxOut[0], minFeePerKb) {\n\t\tpanic(fmt.Errorf(\"redeem output value of %v is dust\", diviutil.Amount(redeemTx.TxOut[0].Value)))\n\t}\n\n\tredeemSig, redeemPubKey, err := CreateSig(redeemTx, 0, contract, recipientAddr, client)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\tredeemSigScript, err := RedeemP2SHContract(contract, redeemSig, redeemPubKey, secret)\n\tif err != nil {\n\t\treturn api.RedeemResponse{\"\", \"\", struct{}{}, nil, 51200}, err\n\t}\n\tredeemTx.TxIn[0].SignatureScript = redeemSigScript\n\n\tredeemTxHash := redeemTx.TxHash()\n\tredeemFeePerKb := CalcFeePerKb(fee, redeemTx.SerializeSize())\n\n\tvar buf bytes.Buffer\n\tbuf.Grow(redeemTx.SerializeSize())\n\tredeemTx.Serialize(&buf)\n\n\tif autopublish == false {\n\t\tfmt.Printf(\"Redeem fee: %v (%0.8f BTC/kB)\\n\\n\", fee, redeemFeePerKb)\n\t\tfmt.Printf(\"Redeem transaction (%v):\\n\", &redeemTxHash)\n\t\tfmt.Printf(\"%x\\n\\n\", buf.Bytes())\n\t}\n\n\tif util.Verify {\n\t\te, err := txscript.NewEngine(contractTx.TxOut[contractOutPoint.Index].PkScript,\n\t\t\tredeemTx, 0, txscript.StandardVerifyFlags, txscript.NewSigCache(10),\n\t\t\ttxscript.NewTxSigHashes(redeemTx), contractTx.TxOut[contractOut].Value)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\terr = e.Execute()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tPromptPublishTx(client, redeemTx, \"redeem\", autopublish)\n\n\treturn api.RedeemResponse{\n\t\tfee.String(),\n\t\tredeemTxHash.String(),\n\t\tstruct{}{},\n\t\tnil,\n\t\t51200,\n\t}, nil\n}", "func (k Keeper) ClaimHardReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tk.SynchronizeHardLiquidityProviderClaim(ctx, owner)\n\n\tsyncedClaim, found := k.GetHardLiquidityProviderClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr := k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetHardLiquidityProviderClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func (_Ethdkg *EthdkgTransactorSession) SubmitDispute(issuer common.Address, issuer_list_idx *big.Int, disputer_list_idx *big.Int, encrypted_shares []*big.Int, commitments [][2]*big.Int, shared_key [2]*big.Int, shared_key_correctness_proof [2]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.Contract.SubmitDispute(&_Ethdkg.TransactOpts, issuer, issuer_list_idx, disputer_list_idx, encrypted_shares, commitments, shared_key, shared_key_correctness_proof)\n}", "func PostHandleMsgStakeUpdate(ctx sdk.Context, k keeper.Keeper, msg types.MsgStakeUpdate, sideTxResult tmprototypes.SideTxResultType) (*sdk.Result, error) {\n\t// Skip handler if stakeUpdate is not approved\n\tif sideTxResult != tmprototypes.SideTxResultType_YES {\n\t\tk.Logger(ctx).Debug(\"Skipping stake update since side-tx didn't get yes votes\")\n\t\treturn nil, hmCommon.ErrSideTxValidation\n\t}\n\n\t// Check for replay attack\n\tblockNumber := new(big.Int).SetUint64(msg.BlockNumber)\n\tsequence := new(big.Int).Mul(blockNumber, big.NewInt(hmTypes.DefaultLogIndexUnit))\n\tsequence.Add(sequence, new(big.Int).SetUint64(msg.LogIndex))\n\n\t// check if incoming tx is older\n\tif k.HasStakingSequence(ctx, sequence.String()) {\n\t\tk.Logger(ctx).Error(\"Older invalid tx found\")\n\t\treturn nil, hmCommon.ErrOldTx\n\t}\n\n\tk.Logger(ctx).Debug(\"Updating validator stake\", \"sideTxResult\", sideTxResult)\n\n\t// pull validator from store\n\tvalidator, ok := k.GetValidatorFromValID(ctx, msg.ID)\n\tif !ok {\n\t\tk.Logger(ctx).Error(\"Fetching of validator from store failed\", \"validatorId\", msg.ID)\n\t\treturn nil, hmCommon.ErrNoValidator\n\t}\n\n\t// update last updated\n\tvalidator.LastUpdated = sequence.String()\n\n\t// update nonce\n\tvalidator.Nonce = msg.Nonce\n\n\t// set validator amount\n\tp, err := helper.GetPowerFromAmount(msg.NewAmount.BigInt())\n\tif err != nil {\n\t\treturn nil, hmCommon.ErrInvalidMsg\n\t}\n\tvalidator.VotingPower = p.Int64()\n\n\t// save validator\n\terr = k.AddValidator(ctx, validator)\n\tif err != nil {\n\t\tk.Logger(ctx).Error(\"Unable to update signer\", \"error\", err, \"ValidatorID\", validator.ID)\n\t\treturn nil, hmCommon.ErrSignerUpdateError\n\t}\n\n\t// save staking sequence\n\tk.SetStakingSequence(ctx, sequence.String())\n\n\t// TX bytes\n\ttxBytes := ctx.TxBytes()\n\thash := tmTypes.Tx(txBytes).Hash()\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeStakeUpdate,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAction, msg.Type()),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),\n\t\t\tsdk.NewAttribute(hmTypes.AttributeKeyTxHash, hmCommonTypes.BytesToHeimdallHash(hash).Hex()), // tx hash\n\t\t\tsdk.NewAttribute(hmTypes.AttributeKeySideTxResult, sideTxResult.String()), // result\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidatorID, strconv.FormatUint(validator.ID.Uint64(), 10)),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidatorNonce, strconv.FormatUint(msg.Nonce, 10)),\n\t\t),\n\t})\n\n\treturn &sdk.Result{\n\t\tEvents: ctx.EventManager().ABCIEvents(),\n\t}, nil\n}", "func (node *TreeNode) backpropagateReward(scores [2]float64) {\n\tcurrentNode := node\n\tfor currentNode.Parent != nil {\n\t\tcurrentNode.VisitCount += 1.0\n\t\tcurrentNode.CumulativeScore[0] += scores[0]\n\t\tcurrentNode.CumulativeScore[1] += scores[1]\n\t\tcurrentNode = currentNode.Parent\n\t}\n\t//Increment root node counter\n\tcurrentNode.VisitCount += 1.0\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactor) DistributeERC20Reward(opts *bind.TransactOpts, _tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.contract.Transact(opts, \"distributeERC20Reward\", _tokenAddress, _value)\n}", "func (c *Calculator) votingReward(\n\tmultiplier *big.Int,\n\tdivider *big.Int,\n\tfrom int,\n\tto int,\n\tprepInfo map[string]*pRepEnable,\n\titer icstate.VotingIterator,\n) *big.Int {\n\ttotal := new(big.Int)\n\tcheckMinVoting := c.global.GetIISSVersion() == icstate.IISSVersion2\n\tfor ; iter.Has(); iter.Next() {\n\t\tif voting, err := iter.Get(); err != nil {\n\t\t\tc.log.Errorf(\"Failed to iterate votings err=%+v\", err)\n\t\t} else {\n\t\t\tif checkMinVoting && voting.Amount().Cmp(BigIntMinDelegation) < 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts := from\n\t\t\te := to\n\t\t\tif prep, ok := prepInfo[icutils.ToKey(voting.To())]; ok {\n\t\t\t\tif prep.StartOffset() != 0 && prep.StartOffset() > s {\n\t\t\t\t\ts = prep.StartOffset()\n\t\t\t\t}\n\t\t\t\tif prep.EndOffset() != 0 && prep.EndOffset() < e {\n\t\t\t\t\te = prep.EndOffset()\n\t\t\t\t}\n\t\t\t\tperiod := e - s\n\t\t\t\tif period <= 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treward := new(big.Int).Mul(multiplier, voting.Amount())\n\t\t\t\treward.Mul(reward, big.NewInt(int64(period)))\n\t\t\t\treward.Div(reward, divider)\n\t\t\t\ttotal.Add(total, reward)\n\t\t\t\tc.log.Tracef(\"VotingReward %s: %s = %s * %s * %d / %s\",\n\t\t\t\t\tvoting.To(), reward, multiplier, voting.Amount(), period, divider)\n\t\t\t}\n\t\t}\n\t}\n\treturn total\n}", "func (dcr *ExchangeWallet) Redeem(redemptions []*asset.Redemption) ([]dex.Bytes, asset.Coin, uint64, error) {\n\t// Create a transaction that spends the referenced contract.\n\tmsgTx := wire.NewMsgTx()\n\tvar totalIn uint64\n\tvar contracts [][]byte\n\tvar addresses []dcrutil.Address\n\tfor _, r := range redemptions {\n\t\tcinfo, ok := r.Spends.(*auditInfo)\n\t\tif !ok {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"Redemption contract info of wrong type\")\n\t\t}\n\t\t// Extract the swap contract recipient and secret hash and check the secret\n\t\t// hash against the hash of the provided secret.\n\t\tcontract := r.Spends.Contract()\n\t\t_, receiver, _, secretHash, err := dexdcr.ExtractSwapDetails(contract, chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"error extracting swap addresses: %w\", err)\n\t\t}\n\t\tcheckSecretHash := sha256.Sum256(r.Secret)\n\t\tif !bytes.Equal(checkSecretHash[:], secretHash) {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"secret hash mismatch. %x != %x\", checkSecretHash[:], secretHash)\n\t\t}\n\t\taddresses = append(addresses, receiver)\n\t\tcontracts = append(contracts, contract)\n\t\tprevOut := cinfo.output.wireOutPoint()\n\t\ttxIn := wire.NewTxIn(prevOut, int64(cinfo.output.value), []byte{})\n\t\t// Sequence = 0xffffffff - 1 is special value that marks the transaction as\n\t\t// irreplaceable and enables the use of lock time.\n\t\t//\n\t\t// https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki#Spending_wallet_policy\n\t\ttxIn.Sequence = wire.MaxTxInSequenceNum - 1\n\t\tmsgTx.AddTxIn(txIn)\n\t\ttotalIn += cinfo.output.value\n\t}\n\n\t// Calculate the size and the fees.\n\tsize := msgTx.SerializeSize() + dexdcr.RedeemSwapSigScriptSize*len(redemptions) + dexdcr.P2PKHOutputSize\n\tfeeRate := dcr.feeRateWithFallback(dcr.redeemConfTarget)\n\tfee := feeRate * uint64(size)\n\tif fee > totalIn {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redeem tx not worth the fees\")\n\t}\n\t// Send the funds back to the exchange wallet.\n\ttxOut, _, err := dcr.makeChangeOut(totalIn - fee)\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\t// One last check for dust.\n\tif dexdcr.IsDust(txOut, feeRate) {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redeem output is dust\")\n\t}\n\tmsgTx.AddTxOut(txOut)\n\t// Sign the inputs.\n\tfor i, r := range redemptions {\n\t\tcontract := contracts[i]\n\t\tredeemSig, redeemPubKey, err := dcr.createSig(msgTx, i, contract, addresses[i])\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, err\n\t\t}\n\t\tredeemSigScript, err := dexdcr.RedeemP2SHContract(contract, redeemSig, redeemPubKey, r.Secret)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, err\n\t\t}\n\t\tmsgTx.TxIn[i].SignatureScript = redeemSigScript\n\t}\n\t// Send the transaction.\n\tcheckHash := msgTx.TxHash()\n\ttxHash, err := dcr.node.SendRawTransaction(dcr.ctx, msgTx, false)\n\tif err != nil {\n\t\treturn nil, nil, 0, translateRPCCancelErr(err)\n\t}\n\tif *txHash != checkHash {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redemption sent, but received unexpected transaction ID back from RPC server. \"+\n\t\t\t\"expected %s, got %s\", *txHash, checkHash)\n\t}\n\tcoinIDs := make([]dex.Bytes, 0, len(redemptions))\n\tfor i := range redemptions {\n\t\tcoinIDs = append(coinIDs, toCoinID(txHash, uint32(i)))\n\t}\n\n\treturn coinIDs, newOutput(txHash, 0, uint64(txOut.Value), wire.TxTreeRegular), fee, nil\n}", "func (s *MutableState) AddRewards(time epochtime.EpochTime, factor *quantity.Quantity, accounts []signature.PublicKey) error {\n\tsteps, err := s.RewardSchedule()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar activeStep *staking.RewardStep\n\tfor _, step := range steps {\n\t\tif time < step.Until {\n\t\t\tactiveStep = &step\n\t\t\tbreak\n\t\t}\n\t}\n\tif activeStep == nil {\n\t\t// We're past the end of the schedule.\n\t\treturn nil\n\t}\n\n\tcommonPool, err := s.CommonPool()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"loading common pool\")\n\t}\n\n\tfor _, id := range accounts {\n\t\tent := s.Account(id)\n\n\t\tq := ent.Escrow.Active.Balance.Clone()\n\t\t// Multiply first.\n\t\tif err := q.Mul(factor); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward factor\")\n\t\t}\n\t\tif err := q.Mul(&activeStep.Scale); err != nil {\n\t\t\treturn errors.Wrap(err, \"multiplying by reward step scale\")\n\t\t}\n\t\tif err := q.Quo(staking.RewardAmountDenominator); err != nil {\n\t\t\treturn errors.Wrap(err, \"dividing by reward amount denominator\")\n\t\t}\n\n\t\tif q.IsZero() {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar com *quantity.Quantity\n\t\trate := ent.Escrow.CommissionSchedule.CurrentRate(time)\n\t\tif rate != nil {\n\t\t\tcom = q.Clone()\n\t\t\t// Multiply first.\n\t\t\tif err := com.Mul(rate); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"multiplying by commission rate\")\n\t\t\t}\n\t\t\tif err := com.Quo(staking.CommissionRateDenominator); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"dividing by commission rate denominator\")\n\t\t\t}\n\n\t\t\tif err := q.Sub(com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"subtracting commission\")\n\t\t\t}\n\t\t}\n\n\t\tif !q.IsZero() {\n\t\t\tif err := quantity.Move(&ent.Escrow.Active.Balance, commonPool, q); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"transferring to active escrow balance from common pool\")\n\t\t\t}\n\t\t}\n\n\t\tif com != nil && !com.IsZero() {\n\t\t\tdelegation := s.Delegation(id, id)\n\n\t\t\tif err := ent.Escrow.Active.Deposit(&delegation.Shares, commonPool, com); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"depositing commission\")\n\t\t\t}\n\n\t\t\ts.SetDelegation(id, id, delegation)\n\t\t}\n\n\t\ts.SetAccount(id, ent)\n\t}\n\n\ts.SetCommonPool(commonPool)\n\n\treturn nil\n}", "func (t *trusteeImpl) NewMiningRewardTx(block consensus.Block) *consensus.Transaction {\n\tvar tx *consensus.Transaction\n\t// build list of miner nodes for uncle blocks\n\tuncleMiners := make([][]byte, len(block.UncleMiners()))\n\tfor i, uncleMiner := range block.UncleMiners() {\n\t\tuncleMiners[i] = uncleMiner\n\t}\n\t\n\tops := make([]Op, 1 + len(uncleMiners))\n\t// first add self's mining reward\n\tops[0] = *t.myReward\n\t\n\t// now add award for each uncle\n\tfor i, uncleMiner := range uncleMiners {\n\t\top := NewOp(OpReward)\n\t\top.Params[ParamUncle] = bytesToHexString(uncleMiner)\n\t\top.Params[ParamAward] = UncleAward\n\t\tops[i+1] = *op \n\t}\n\t// serialize ops into payload\n\tif payload,err := common.Serialize(ops); err != nil {\n\t\tt.log.Error(\"Failed to serialize ops into payload: %s\", err)\n\t\treturn nil\n\t} else {\n\t\t// make a signed transaction out of payload\n\t\tif signature := t.sign(payload); len(signature) > 0 {\n\t\t\t// return the signed transaction\n\t\t\ttx = consensus.NewTransaction(payload, signature, t.myAddress)\n\t\t\tblock.AddTransaction(tx)\n\t\t\tt.process(block, tx)\n\t\t}\n\t}\n\treturn tx\n}", "func sendMsgEditPost(\n\tr *rand.Rand, app *baseapp.BaseApp, ak auth.AccountKeeper,\n\tmsg types.MsgEditPost, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey,\n) error {\n\n\taccount := ak.GetAccount(ctx, msg.Editor)\n\tcoins := account.SpendableCoins(ctx.BlockTime())\n\n\tfees, err := sim.RandomFees(r, ctx, coins)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttx := helpers.GenTx(\n\t\t[]sdk.Msg{msg},\n\t\tfees,\n\t\tDefaultGasValue,\n\t\tchainID,\n\t\t[]uint64{account.GetAccountNumber()},\n\t\t[]uint64{account.GetSequence()},\n\t\tprivkeys...,\n\t)\n\n\t_, _, err = app.Deliver(tx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func redeem (stub shim.ChaincodeStubInterface, args []string) ([]byte,error){\n\n\tif len(args) != 5 {\n\t\t\tfmt.Println(\" Incorrect number of arguments sent to redeem. Expecting 5. Received \" + strconv.Itoa(len(args)))\n\t\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 5\")\n\t\t}\n\n\t\t_, err := LoyaltyPkg.RedeemPoints(stub, args)\n\n\tif err != nil {\n\n\t\tfmt.Println(err)\n\t\treturn nil, errors.New(\"Errors while creating wallet for user \" + args[0])\n\t}\n\n\tlogger.Info(\"Successfully redeemed points for user \" + args[0])\n\n\treturn nil, nil\n\n}", "func (va *ClawbackVestingAccount) addGrant(ctx sdk.Context, sk StakingKeeper, grantStartTime int64, grantLockupPeriods, grantVestingPeriods []Period, grantCoins sdk.Coins) {\n\t// how much is really delegated?\n\tbondedAmt := sk.GetDelegatorBonded(ctx, va.GetAddress())\n\tunbondingAmt := sk.GetDelegatorUnbonding(ctx, va.GetAddress())\n\tdelegatedAmt := bondedAmt.Add(unbondingAmt)\n\tdelegated := sdk.NewCoins(sdk.NewCoin(sk.BondDenom(ctx), delegatedAmt))\n\n\t// discover what has been slashed\n\toldDelegated := va.DelegatedVesting.Add(va.DelegatedFree...)\n\tslashed := oldDelegated.Sub(coinsMin(oldDelegated, delegated))\n\n\t// rebase the DV + DF by capping slashed at the current unvested amount\n\tunvested := va.OriginalVesting.Sub(va.GetVestedOnly(ctx.BlockTime()))\n\tnewSlashed := coinsMin(slashed, unvested)\n\tnewDelegated := delegated.Add(newSlashed...)\n\n\t// modify schedules for the new grant\n\tnewLockupStart, newLockupEnd, newLockupPeriods := DisjunctPeriods(va.StartTime, grantStartTime, va.LockupPeriods, grantLockupPeriods)\n\tnewVestingStart, newVestingEnd, newVestingPeriods := DisjunctPeriods(va.StartTime, grantStartTime,\n\t\tva.GetVestingPeriods(), grantVestingPeriods)\n\tif newLockupStart != newVestingStart {\n\t\tpanic(\"bad start time calculation\")\n\t}\n\tva.StartTime = newLockupStart\n\tva.EndTime = max64(newLockupEnd, newVestingEnd)\n\tva.LockupPeriods = newLockupPeriods\n\tva.VestingPeriods = newVestingPeriods\n\tva.OriginalVesting = va.OriginalVesting.Add(grantCoins...)\n\n\t// cap DV at the current unvested amount, DF rounds out to newDelegated\n\tunvested2 := va.GetVestingCoins(ctx.BlockTime())\n\tva.DelegatedVesting = coinsMin(newDelegated, unvested2)\n\tva.DelegatedFree = newDelegated.Sub(va.DelegatedVesting)\n}", "func PostVault(c *gin.Context) {\n\tdbmap := c.MustGet(\"DBmap\").(*gorp.DbMap)\n\tverbose := c.MustGet(\"Verbose\").(bool)\n\n\tvar vault Vault\n\tc.Bind(&vault)\n\n\tif verbose == true {\n\t\tfmt.Println(vault)\n\t\tfmt.Println(len(vault.VaultName))\n\t}\n\n\tif len(vault.VaultName) >= 3 { // XXX Check mandatory fields\n\t\terr := dbmap.Insert(&vault)\n\t\tif err == nil {\n\t\t\tc.JSON(201, vault)\n\t\t} else {\n\t\t\tcheckErr(err, \"Insert failed\")\n\t\t}\n\n\t} else {\n\t\tc.JSON(400, gin.H{\"error\": \"Mandatory fields are empty\"})\n\t}\n\n\t// curl -i -X POST -H \"Content-Type: application/json\" -d \"{ \\\"firstname\\\": \\\"Thea\\\", \\\"lastname\\\": \\\"Queen\\\" }\" http://localhost:8080/api/v1/vaults\n}", "func (d *Dao) AddReward(c context.Context, iRewardID int64, uid int64, iSource int64, iRoomid int64, iLifespan int64) (err error) {\n\t//aReward, _ := getRewardConfByLid(iRewardID)\n\n\tm, _ := time.ParseDuration(fmt.Sprintf(\"+%dh\", iLifespan))\n\n\targ := &AnchorTaskModel.AnchorReward{\n\t\tUid: uid,\n\t\tRewardId: iRewardID,\n\t\tRoomid: iRoomid,\n\t\tSource: iSource,\n\t\tAchieveTime: xtime.Time(time.Now().Unix()),\n\t\tExpireTime: xtime.Time(time.Now().Add(m).Unix()),\n\t\tStatus: model.RewardUnUsed,\n\t}\n\n\t//spew.Dump\n\t// (arg)\n\tif err := d.orm.Create(arg).Error; err != nil {\n\t\tlog.Error(\"addReward(%v) error(%v)\", arg, err)\n\t\treturn err\n\t}\n\n\tif err := d.SetNewReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"addRewardMc(%v) error(%v)\", uid, err)\n\t}\n\n\tif err := d.SetHasReward(c, uid, int64(1)); err != nil {\n\t\tlog.Error(\"SetHasReward(%v) error(%v)\", uid, err)\n\t}\n\n\tlog.Info(\"addReward (%v) succ\", arg)\n\n\treturn\n}", "func (n *Notary) PostPersist() {\n\tacc := n.getAccount()\n\tif acc == nil {\n\t\treturn\n\t}\n\n\tn.reqMtx.Lock()\n\tdefer n.reqMtx.Unlock()\n\tcurrHeight := n.Config.Chain.BlockHeight()\n\tfor h, r := range n.requests {\n\t\tif !r.isSent && r.isMainCompleted() && r.minNotValidBefore > currHeight {\n\t\t\tif err := n.finalize(acc, r.main, h); err != nil {\n\t\t\t\tn.Config.Log.Error(\"failed to finalize main transaction\", zap.Error(err))\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif r.minNotValidBefore <= currHeight { // then at least one of the fallbacks can already be sent.\n\t\t\tfor _, fb := range r.fallbacks {\n\t\t\t\tif nvb := fb.GetAttributes(transaction.NotValidBeforeT)[0].Value.(*transaction.NotValidBefore).Height; nvb <= currHeight {\n\t\t\t\t\t// Ignore the error, wait for the next block to resend them\n\t\t\t\t\t_ = n.finalize(acc, fb, h)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (dcr *ExchangeWallet) Redeem(form *asset.RedeemForm) ([]dex.Bytes, asset.Coin, uint64, error) {\n\t// Create a transaction that spends the referenced contract.\n\tmsgTx := wire.NewMsgTx()\n\tvar totalIn uint64\n\tvar contracts [][]byte\n\tvar addresses []stdaddr.Address\n\tfor _, r := range form.Redemptions {\n\t\tif r.Spends == nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"no audit info\")\n\t\t}\n\n\t\tcinfo, err := convertAuditInfo(r.Spends, dcr.chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, err\n\t\t}\n\n\t\t// Extract the swap contract recipient and secret hash and check the secret\n\t\t// hash against the hash of the provided secret.\n\t\tcontract := cinfo.contract\n\t\t_, receiver, _, secretHash, err := dexdcr.ExtractSwapDetails(contract, dcr.chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"error extracting swap addresses: %w\", err)\n\t\t}\n\t\tcheckSecretHash := sha256.Sum256(r.Secret)\n\t\tif !bytes.Equal(checkSecretHash[:], secretHash) {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"secret hash mismatch. %x != %x\", checkSecretHash[:], secretHash)\n\t\t}\n\t\taddresses = append(addresses, receiver)\n\t\tcontracts = append(contracts, contract)\n\t\tprevOut := cinfo.output.wireOutPoint()\n\t\ttxIn := wire.NewTxIn(prevOut, int64(cinfo.output.value), []byte{})\n\t\tmsgTx.AddTxIn(txIn)\n\t\ttotalIn += cinfo.output.value\n\t}\n\n\t// Calculate the size and the fees.\n\tsize := msgTx.SerializeSize() + dexdcr.RedeemSwapSigScriptSize*len(form.Redemptions) + dexdcr.P2PKHOutputSize\n\n\tcustomCfg := new(redeemOptions)\n\terr := config.Unmapify(form.Options, customCfg)\n\tif err != nil {\n\t\treturn nil, nil, 0, fmt.Errorf(\"error parsing selected swap options: %w\", err)\n\t}\n\n\trawFeeRate := dcr.targetFeeRateWithFallback(dcr.redeemConfTarget, form.FeeSuggestion)\n\tfeeRate, err := calcBumpedRate(rawFeeRate, customCfg.FeeBump)\n\tif err != nil {\n\t\tdcr.log.Errorf(\"calcBumpRate error: %v\", err)\n\t}\n\tfee := feeRate * uint64(size)\n\tif fee > totalIn {\n\t\t// Double check that the fee bump isn't the issue.\n\t\tfeeRate = rawFeeRate\n\t\tfee = feeRate * uint64(size)\n\t\tif fee > totalIn {\n\t\t\treturn nil, nil, 0, fmt.Errorf(\"redeem tx not worth the fees\")\n\t\t}\n\t\tdcr.log.Warnf(\"Ignoring fee bump (%v) resulting in fees > redemption\", float64PtrStr(customCfg.FeeBump))\n\t}\n\n\t// Send the funds back to the exchange wallet.\n\ttxOut, _, err := dcr.makeChangeOut(dcr.depositAccount(), totalIn-fee)\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\t// One last check for dust.\n\tif dexdcr.IsDust(txOut, feeRate) {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redeem output is dust\")\n\t}\n\tmsgTx.AddTxOut(txOut)\n\t// Sign the inputs.\n\tfor i, r := range form.Redemptions {\n\t\tcontract := contracts[i]\n\t\tredeemSig, redeemPubKey, err := dcr.createSig(msgTx, i, contract, addresses[i])\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, err\n\t\t}\n\t\tredeemSigScript, err := dexdcr.RedeemP2SHContract(contract, redeemSig, redeemPubKey, r.Secret)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, err\n\t\t}\n\t\tmsgTx.TxIn[i].SignatureScript = redeemSigScript\n\t}\n\t// Send the transaction.\n\tcheckHash := msgTx.TxHash()\n\ttxHash, err := dcr.wallet.SendRawTransaction(dcr.ctx, msgTx, false)\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\tif *txHash != checkHash {\n\t\treturn nil, nil, 0, fmt.Errorf(\"redemption sent, but received unexpected transaction ID back from RPC server. \"+\n\t\t\t\"expected %s, got %s\", *txHash, checkHash)\n\t}\n\tcoinIDs := make([]dex.Bytes, 0, len(form.Redemptions))\n\tfor i := range form.Redemptions {\n\t\tcoinIDs = append(coinIDs, toCoinID(txHash, uint32(i)))\n\t}\n\n\treturn coinIDs, newOutput(txHash, 0, uint64(txOut.Value), wire.TxTreeRegular), fee, nil\n}", "func (c *Client) RenterPostRateLimit(readBPS, writeBPS int64) (err error) {\n\tvalues := url.Values{}\n\tvalues.Set(\"maxdownloadspeed\", strconv.FormatInt(readBPS, 10))\n\tvalues.Set(\"maxuploadspeed\", strconv.FormatInt(writeBPS, 10))\n\terr = c.post(\"/renter\", values.Encode(), nil)\n\treturn\n}", "func (btc *ExchangeWallet) Redeem(redemptions []*asset.Redemption) ([]dex.Bytes, asset.Coin, error) {\n\t// Create a transaction that spends the referenced contract.\n\tmsgTx := wire.NewMsgTx(wire.TxVersion)\n\tvar totalIn uint64\n\tvar contracts [][]byte\n\tvar addresses []btcutil.Address\n\tfor _, r := range redemptions {\n\t\tcinfo, ok := r.Spends.(*auditInfo)\n\t\tif !ok {\n\t\t\treturn nil, nil, fmt.Errorf(\"Redemption contract info of wrong type\")\n\t\t}\n\t\t// Extract the swap contract recipient and secret hash and check the secret\n\t\t// hash against the hash of the provided secret.\n\t\t_, receiver, _, secretHash, err := dexbtc.ExtractSwapDetails(cinfo.output.redeem, btc.chainParams)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"error extracting swap addresses: %v\", err)\n\t\t}\n\t\tcheckSecretHash := sha256.Sum256(r.Secret)\n\t\tif !bytes.Equal(checkSecretHash[:], secretHash) {\n\t\t\treturn nil, nil, fmt.Errorf(\"secret hash mismatch\")\n\t\t}\n\t\taddresses = append(addresses, receiver)\n\t\tcontracts = append(contracts, cinfo.output.redeem)\n\t\tprevOut := wire.NewOutPoint(&cinfo.output.txHash, cinfo.output.vout)\n\t\ttxIn := wire.NewTxIn(prevOut, []byte{}, nil)\n\t\t// Enable locktime\n\t\t// https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki#Spending_wallet_policy\n\t\ttxIn.Sequence = wire.MaxTxInSequenceNum - 1\n\t\tmsgTx.AddTxIn(txIn)\n\t\ttotalIn += cinfo.output.value\n\t}\n\n\t// Calculate the size and the fees.\n\tsize := msgTx.SerializeSize() + dexbtc.RedeemSwapSigScriptSize*len(redemptions) + dexbtc.P2WPKHOutputSize\n\tfeeRate := btc.feeRateWithFallback()\n\tfee := feeRate * uint64(size)\n\tif fee > totalIn {\n\t\treturn nil, nil, fmt.Errorf(\"redeem tx not worth the fees\")\n\t}\n\t// Send the funds back to the exchange wallet.\n\tredeemAddr, err := btc.wallet.ChangeAddress()\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error getting new address from the wallet: %v\", err)\n\t}\n\tpkScript, err := txscript.PayToAddrScript(redeemAddr)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error creating change script: %v\", err)\n\t}\n\ttxOut := wire.NewTxOut(int64(totalIn-fee), pkScript)\n\t// One last check for dust.\n\tif dexbtc.IsDust(txOut, feeRate) {\n\t\treturn nil, nil, fmt.Errorf(\"redeem output is dust\")\n\t}\n\tmsgTx.AddTxOut(txOut)\n\t// Sign the inputs.\n\tfor i, r := range redemptions {\n\t\tcontract := contracts[i]\n\t\tredeemSig, redeemPubKey, err := btc.createSig(msgTx, i, contract, addresses[i])\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tredeemSigScript, err := dexbtc.RedeemP2SHContract(contract, redeemSig, redeemPubKey, r.Secret)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tmsgTx.TxIn[i].SignatureScript = redeemSigScript\n\t}\n\t// Send the transaction.\n\tcheckHash := msgTx.TxHash()\n\ttxHash, err := btc.node.SendRawTransaction(msgTx, false)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif *txHash != checkHash {\n\t\treturn nil, nil, fmt.Errorf(\"redemption sent, but received unexpected transaction ID back from RPC server. \"+\n\t\t\t\"expected %s, got %s\", *txHash, checkHash)\n\t}\n\t// Log the change output.\n\tbtc.addChange(txHash.String(), 0)\n\tcoinIDs := make([]dex.Bytes, 0, len(redemptions))\n\tfor i := range redemptions {\n\t\tcoinIDs = append(coinIDs, toCoinID(txHash, uint32(i)))\n\t}\n\treturn coinIDs, newOutput(btc.node, txHash, 0, uint64(txOut.Value), nil), nil\n}", "func (_XStaking *XStakingCaller) Rewards(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewards\", arg0)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func PostTimeAdjustment(\n\telapseTime int64, paras *param.EvaluateOfContentValueParam) float64 {\n\treturn (1.0 / (1.0 + math.Exp(\n\t\t(float64(elapseTime)/float64(paras.ConsumptionTimeAdjustBase) -\n\t\t\tfloat64(paras.ConsumptionTimeAdjustOffset)))))\n}", "func (_Smartchef *SmartchefCaller) RewardPerBlock(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Smartchef.contract.Call(opts, out, \"rewardPerBlock\")\n\treturn *ret0, err\n}", "func (k Keeper) ClaimDelegatorReward(ctx sdk.Context, owner, receiver sdk.AccAddress, denom string, multiplierName string) error {\n\tclaim, found := k.GetDelegatorClaim(ctx, owner)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tmultiplier, found := k.GetMultiplierByDenom(ctx, denom, multiplierName)\n\tif !found {\n\t\treturn errorsmod.Wrapf(types.ErrInvalidMultiplier, \"denom '%s' has no multiplier '%s'\", denom, multiplierName)\n\t}\n\n\tclaimEnd := k.GetClaimEnd(ctx)\n\n\tif ctx.BlockTime().After(claimEnd) {\n\t\treturn errorsmod.Wrapf(types.ErrClaimExpired, \"block time %s > claim end time %s\", ctx.BlockTime(), claimEnd)\n\t}\n\n\tsyncedClaim, err := k.SynchronizeDelegatorClaim(ctx, claim)\n\tif err != nil {\n\t\treturn errorsmod.Wrapf(types.ErrClaimNotFound, \"address: %s\", owner)\n\t}\n\n\tamt := syncedClaim.Reward.AmountOf(denom)\n\n\tclaimingCoins := sdk.NewCoins(sdk.NewCoin(denom, amt))\n\trewardCoins := sdk.NewCoins(sdk.NewCoin(denom, sdk.NewDecFromInt(amt).Mul(multiplier.Factor).RoundInt()))\n\tif rewardCoins.IsZero() {\n\t\treturn types.ErrZeroClaim\n\t}\n\n\tlength := k.GetPeriodLength(ctx.BlockTime(), multiplier.MonthsLockup)\n\n\terr = k.SendTimeLockedCoinsToAccount(ctx, types.IncentiveMacc, receiver, rewardCoins, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// remove claimed coins (NOT reward coins)\n\tsyncedClaim.Reward = syncedClaim.Reward.Sub(claimingCoins...)\n\tk.SetDelegatorClaim(ctx, syncedClaim)\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeClaim,\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimedBy, owner.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimAmount, claimingCoins.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyClaimType, syncedClaim.GetType()),\n\t\t),\n\t)\n\treturn nil\n}", "func CalculatePayoutForContract(contract Contract, rate float64, delegate bool) Contract{\n ////-------------JUST FOR TESTING -------------////\n totalNodeRewards := 378 //Amount of rewards for my delegation in cycle 11\n ////--------------END TESTING ------------------////\n\n grossRewards := contract.SharePercentage * float64(totalNodeRewards)\n contract.GrossPayout = grossRewards\n fee := rate * grossRewards\n contract.Fee = fee\n var netRewards float64\n if (delegate){\n netRewards = grossRewards\n contract.NetPayout = netRewards\n contract.Fee = 0\n } else {\n netRewards = grossRewards - fee\n contract.NetPayout = contract.NetPayout + netRewards\n }\n\n return contract\n}", "func (_Token *TokenCallerSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (_Token *TokenSession) BaseReward(index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\treturn _Token.Contract.BaseReward(&_Token.CallOpts, index)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepTransactorSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\n}", "func (_BondedECDSAKeep *BondedECDSAKeepSession) DistributeERC20Reward(_tokenAddress common.Address, _value *big.Int) (*types.Transaction, error) {\n\treturn _BondedECDSAKeep.Contract.DistributeERC20Reward(&_BondedECDSAKeep.TransactOpts, _tokenAddress, _value)\n}", "func (_Univ2 *Univ2Transactor) Permit(opts *bind.TransactOpts, owner common.Address, spender common.Address, value *big.Int, deadline *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Univ2.contract.Transact(opts, \"permit\", owner, spender, value, deadline, v, r, s)\n}", "func (d *Dao) UseReward(id int64, usePlat string) (rst bool, err error) {\n\tif err := d.orm.\n\t\tModel(&model.AnchorReward{}).\n\t\tWhere(\"id=?\", id).\n\t\tUpdate(map[string]interface{}{\"status\": model.RewardUsed, \"use_plat\": usePlat, \"use_time\": xtime.Time(time.Now().Unix())}).Error; err != nil {\n\t\tlog.Error(\"useReward (%v) error(%v)\", id, err)\n\t\treturn rst, err\n\t}\n\trst = true\n\treturn\n}", "func (_Contract *ContractCaller) TaskErasingReward(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"taskErasingReward\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (m *Mantle) replenishBalance(w *botWallet) {\n\t// Get the Balance from the user in case it changed while while this note\n\t// was in the notification pipeline.\n\tbal, err := m.AssetBalance(w.assetID)\n\tif err != nil {\n\t\tm.fatalError(\"error updating %s balance: %v\", w.symbol, err)\n\t\treturn\n\t}\n\n\tm.log.Debugf(\"Balance note received for %s (minFunds = %s, maxFunds = %s): %s\",\n\t\tw.symbol, valString(w.minFunds), valString(w.maxFunds), mustJSON(bal))\n\n\teffectiveMax := w.maxFunds + (w.maxFunds - w.minFunds)\n\n\tif bal.Available < w.minFunds {\n\t\tchunk := (w.maxFunds - bal.Available) / uint64(w.numCoins)\n\t\tfor i := 0; i < w.numCoins; i++ {\n\t\t\tm.log.Debugf(\"Requesting %s from %s alpha node\", valString(chunk), w.symbol)\n\t\t\tcmdOut := <-harnessCtl(w.symbol, \"./alpha\", \"sendtoaddress\", w.address, valString(chunk))\n\t\t\tif cmdOut.err != nil {\n\t\t\t\tm.fatalError(\"error refreshing balance for %s: %v\", w.symbol, cmdOut.err)\n\t\t\t}\n\t\t}\n\t} else if bal.Available > effectiveMax {\n\t\t// Send some back to the alpha address.\n\t\tamt := bal.Available - w.maxFunds\n\t\tm.log.Debugf(\"Sending %s back to %s alpha node\", valString(amt), w.symbol)\n\t\t_, err := m.Withdraw(pass, w.assetID, amt, returnAddress(w.symbol, alpha))\n\t\tif err != nil {\n\t\t\tm.fatalError(\"failed to withdraw funds to alpha: %v\", err)\n\t\t}\n\t}\n}", "func payout(delegate string, operator string) string {\n\t// get operator's address\n\toperator_addr, err := alias.Address(operator)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// get delegate's name to 12-byte array\n\tdelegate_name := delegateName(delegate)\n\n\trs := calculateRewardShares(operator_addr, delegate_name, epochToQuery)\n\n\t// prepare input for multisend\n\t// https://member.iotex.io/multi-send\n\tvar voters []string\n\tvar rewards []string\n\n\tstradd := func(a string, b string, c string) string {\n\t\taa, _ := new(big.Int).SetString(a, 10)\n\t\tbb, _ := new(big.Int).SetString(b, 10)\n\t\tcc, _ := new(big.Int).SetString(c, 10)\n\t\treturn cc.Add(aa.Add(aa, bb), cc).Text(10)\n\t}\n\n\tfor _, share := range rs.Shares {\n\t\tvoters = append(voters, \"0x\" + share.ETHAddr)\n\t\trewards = append(rewards, stradd(\n\t\t\t\t\t\tshare.Reward.Block,\n\t\t\t\t\t\tshare.Reward.FoundationBonus,\n\t\t\t\t\t\tshare.Reward.EpochBonus))\n\t}\n\n\tvar sent []MultisendReward\n\tfor i, a := range rewards {\n\t\tamount, _ := new(big.Int).SetString(a, 10)\n\t\tsent = append(sent, MultisendReward{voters[i],\n\t\t\t\t\tutil.RauToString(amount, util.IotxDecimalNum)})\n\t}\n\ts, _ := json.Marshal(sent)\n\tfmt.Println(string(s))\n\n\treturn rs.String()\n}", "func (c *Contract) Payback(ctx TransactionContextInterface, jeweler string, paperNumber string, paidbackDateTime string) (*InventoryFinancingPaper, error) {\r\n\tpaper, err := ctx.GetPaperList().GetPaper(jeweler, paperNumber)\r\n\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tif paper.IsPaidBack() {\r\n\t\treturn nil, fmt.Errorf(\"paper %s:%s is already PaidBack\", jeweler, paperNumber)\r\n\t}\r\n\r\n\tpaper.SetPaidBack()\r\n\r\n\terr = ctx.GetPaperList().UpdatePaper(paper)\r\n\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tfmt.Printf(\"inventory paper %q:%q is paid back by %q,The paidback date is %q. Current state = %q\", jeweler, paperNumber, jeweler, paidbackDateTime, paper.GetState())\r\n\treturn paper, nil\r\n}", "func sendMsgAddPostReaction(\n\tr *rand.Rand, app *baseapp.BaseApp, ak authkeeper.AccountKeeper, bk bankkeeper.Keeper,\n\tmsg *types.MsgAddPostReaction, ctx sdk.Context, chainID string, privkeys []cryptotypes.PrivKey,\n) error {\n\taddr, _ := sdk.AccAddressFromBech32(msg.User)\n\taccount := ak.GetAccount(ctx, addr)\n\tcoins := bk.SpendableCoins(ctx, account.GetAddress())\n\n\tfees, err := simtypes.RandomFees(r, ctx, coins)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttxGen := simappparams.MakeTestEncodingConfig().TxConfig\n\ttx, err := helpers.GenTx(\n\t\ttxGen,\n\t\t[]sdk.Msg{msg},\n\t\tfees,\n\t\tDefaultGasValue,\n\t\tchainID,\n\t\t[]uint64{account.GetAccountNumber()},\n\t\t[]uint64{account.GetSequence()},\n\t\tprivkeys...,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, _, err = app.Deliver(txGen.TxEncoder(), tx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (_Dospayment *DospaymentTransactor) ClaimGuardianReward(opts *bind.TransactOpts, guardianAddr common.Address) (*types.Transaction, error) {\n\treturn _Dospayment.contract.Transact(opts, \"claimGuardianReward\", guardianAddr)\n}", "func (s *BasemumpsListener) EnterPostcondition(ctx *PostconditionContext) {}", "func PostConsumptionTimesAdjustment(\n\tnumOfConsumptionOnAuthor int64, paras *param.EvaluateOfContentValueParam) float64 {\n\treturn (1.0/(1.0+math.Exp(\n\t\t(float64(numOfConsumptionOnAuthor)-float64(paras.NumOfConsumptionOnAuthorOffset)))) + 1.0) + 1.0\n}", "func accumulateRewards(config *params.ChainConfig, state *state.DB, header *types.Header) {\n\t// TODO: implement mining rewards\n}", "func (_Token *TokenCaller) BaseReward(opts *bind.CallOpts, index *big.Int) (*big.Int, *big.Int, *big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t\tret1 = new(*big.Int)\n\t\tret2 = new(*big.Int)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t}\n\terr := _Token.contract.Call(opts, out, \"baseReward\", index)\n\treturn *ret0, *ret1, *ret2, err\n}", "func (b *Builder) StartPost(ctx context.Context, rewardAddress types.Address, dataDir string, space uint64) error {\n\tlogger := b.log.WithContext(ctx)\n\tif !atomic.CompareAndSwapInt32(&b.initStatus, InitIdle, InitInProgress) {\n\t\tswitch atomic.LoadInt32(&b.initStatus) {\n\t\tcase InitDone:\n\t\t\treturn fmt.Errorf(\"already initialized\")\n\t\tcase InitInProgress:\n\t\t\treturn fmt.Errorf(\"already started\")\n\t\t}\n\t}\n\n\tif err := b.postProver.SetParams(dataDir, space); err != nil {\n\t\treturn err\n\t}\n\tb.SetCoinbaseAccount(rewardAddress)\n\n\tinitialized, _, err := b.postProver.IsInitialized()\n\tif err != nil {\n\t\tatomic.StoreInt32(&b.initStatus, InitIdle)\n\t\treturn err\n\t}\n\n\tif !initialized {\n\t\tif err := b.postProver.VerifyInitAllowed(); err != nil {\n\t\t\tatomic.StoreInt32(&b.initStatus, InitIdle)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlogger.With().Info(\"starting post initialization\",\n\t\tlog.String(\"datadir\", dataDir),\n\t\tlog.String(\"space\", fmt.Sprintf(\"%d\", space)),\n\t\tlog.String(\"rewardAddress\", fmt.Sprintf(\"%x\", rewardAddress)),\n\t)\n\n\tgo func() {\n\t\tif initialized {\n\t\t\t// If initialized, run the execution phase with zero-challenge,\n\t\t\t// to create the initial proof (the commitment).\n\t\t\tb.commitment, err = b.postProver.Execute(shared.ZeroChallenge)\n\t\t\tif err != nil {\n\t\t\t\tlogger.With().Error(\"post execution failed\", log.Err(err))\n\t\t\t\tatomic.StoreInt32(&b.initStatus, InitIdle)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\t// If not initialized, run the initialization phase.\n\t\t\t// This would create the initial proof (the commitment) as well.\n\t\t\tb.commitment, err = b.postProver.Initialize()\n\t\t\tif err != nil {\n\t\t\t\tlogger.With().Error(\"post initialization failed\", log.Err(err))\n\t\t\t\tatomic.StoreInt32(&b.initStatus, InitIdle)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tlogger.With().Info(\"post initialization completed\",\n\t\t\tlog.String(\"datadir\", dataDir),\n\t\t\tlog.String(\"space\", fmt.Sprintf(\"%d\", space)),\n\t\t\tlog.String(\"commitment merkle root\", fmt.Sprintf(\"%x\", b.commitment.MerkleRoot)),\n\t\t)\n\n\t\tatomic.StoreInt32(&b.initStatus, InitDone)\n\t\tclose(b.initDone)\n\t}()\n\n\treturn nil\n}", "func PostHandleMsgValidatorExit(ctx sdk.Context, k keeper.Keeper, msg types.MsgValidatorExit, sideTxResult tmprototypes.SideTxResultType) (*sdk.Result, error) {\n\t// Skip handler if validator exit is not approved\n\tif sideTxResult != tmprototypes.SideTxResultType_YES {\n\t\tk.Logger(ctx).Debug(\"Skipping validator exit since side-tx didn't get yes votes\")\n\t\treturn nil, common.ErrSideTxValidation\n\t}\n\n\t// Check for replay attack\n\tblockNumber := new(big.Int).SetUint64(msg.BlockNumber)\n\tsequence := new(big.Int).Mul(blockNumber, big.NewInt(hmTypes.DefaultLogIndexUnit))\n\tsequence.Add(sequence, new(big.Int).SetUint64(msg.LogIndex))\n\n\t// check if incoming tx is older\n\tif k.HasStakingSequence(ctx, sequence.String()) {\n\t\tk.Logger(ctx).Error(\"Older invalid tx found\")\n\t\treturn nil, hmCommon.ErrOldTx\n\t}\n\n\tk.Logger(ctx).Debug(\"Persisting validator exit\", \"sideTxResult\", sideTxResult)\n\n\tvalidator, ok := k.GetValidatorFromValID(ctx, msg.ID)\n\tif !ok {\n\t\tk.Logger(ctx).Error(\"Fetching of validator from store failed\", \"validatorID\", msg.ID)\n\t\treturn nil, hmCommon.ErrNoValidator\n\t}\n\n\t// set end epoch\n\tvalidator.EndEpoch = msg.DeactivationEpoch\n\n\t// update last updated\n\tvalidator.LastUpdated = sequence.String()\n\n\t// update nonce\n\tvalidator.Nonce = msg.Nonce\n\n\t// Add deactivation time for validator\n\tif err := k.AddValidator(ctx, validator); err != nil {\n\t\tk.Logger(ctx).Error(\"Error while setting deactivation epoch to validator\", \"error\", err, \"validatorID\", validator.ID.String())\n\t\treturn nil, hmCommon.ErrValidatorNotDeactivated\n\t}\n\n\t// save staking sequence\n\tk.SetStakingSequence(ctx, sequence.String())\n\n\t// TX bytes\n\ttxBytes := ctx.TxBytes()\n\thash := tmTypes.Tx(txBytes).Hash()\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeValidatorExit,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAction, msg.Type()), // action\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), // module name\n\t\t\tsdk.NewAttribute(hmTypes.AttributeKeyTxHash, hmCommonTypes.BytesToHeimdallHash(hash).Hex()), // tx hash\n\t\t\tsdk.NewAttribute(hmTypes.AttributeKeySideTxResult, sideTxResult.String()), // result\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidatorID, validator.ID.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidatorNonce, strconv.FormatUint(msg.Nonce, 10)),\n\t\t),\n\t})\n\n\treturn &sdk.Result{\n\t\tEvents: ctx.EventManager().ABCIEvents(),\n\t}, nil\n}", "func (client CloudEndpointsClient) PostBackupResponder(resp *http.Response) (result PostBackupResponse, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (_Univ2 *Univ2TransactorSession) Permit(owner common.Address, spender common.Address, value *big.Int, deadline *big.Int, v uint8, r [32]byte, s [32]byte) (*types.Transaction, error) {\n\treturn _Univ2.Contract.Permit(&_Univ2.TransactOpts, owner, spender, value, deadline, v, r, s)\n}", "func (_Vault *VaultSession) SubmitBurnProof(inst []byte, heights *big.Int, instPaths [][32]byte, instPathIsLefts []bool, instRoots [32]byte, blkData [32]byte, sigIdxs []*big.Int, sigVs []uint8, sigRs [][32]byte, sigSs [][32]byte) (*types.Transaction, error) {\n\treturn _Vault.Contract.SubmitBurnProof(&_Vault.TransactOpts, inst, heights, instPaths, instPathIsLefts, instRoots, blkData, sigIdxs, sigVs, sigRs, sigSs)\n}", "func (k Keeper) PerformStake(ctx sdk.Context, vendorID uint32, postID curatingtypes.PostID, delAddr sdk.AccAddress,\n\tvalAddr sdk.ValAddress, amount sdk.Int) error {\n\n\tp, found, err := k.curatingKeeper.GetPost(ctx, vendorID, postID)\n\tif !found {\n\t\treturn curatingtypes.ErrPostNotFound\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif ctx.BlockTime().Before(p.CuratingEndTime) {\n\t\treturn types.ErrCurationNotExpired\n\t}\n\n\tstake, found, err := k.GetStake(ctx, vendorID, postID, delAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tamt := amount\n\tif found {\n\t\tamt = stake.Amount.Add(amount)\n\t\t// shadow valAddr so we don't mix validators when adding stake\n\t\tvalAddr, err = sdk.ValAddressFromBech32(stake.Validator)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvalidator, found := k.stakingKeeper.GetValidator(ctx, valAddr)\n\tif !found {\n\t\treturn stakingtypes.ErrNoValidatorFound\n\t}\n\n\tstake = types.NewStake(vendorID, postID, delAddr, valAddr, amt)\n\tk.SetStake(ctx, delAddr, stake)\n\n\t_, err = k.stakingKeeper.Delegate(ctx, delAddr, amount, stakingtypes.Unbonded, validator, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeStake,\n\t\t\tsdk.NewAttribute(types.AttributeKeyVendorID, fmt.Sprintf(\"%d\", vendorID)),\n\t\t\tsdk.NewAttribute(types.AttributeKeyPostID, postID.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyDelegator, delAddr.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidator, valAddr.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyAmount, amt.String()),\n\t\t),\n\t})\n\n\treturn nil\n}", "func (rig *testRig) ackRedemption_taker(checkSig bool) error {\n\tmatchInfo := rig.matchInfo\n\terr := rig.ackRedemption(matchInfo.taker, matchInfo.takerOID, matchInfo.db.makerRedeem)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif checkSig {\n\t\ttracker := rig.getTracker()\n\t\tif !bytes.Equal(tracker.Sigs.TakerRedeem, matchInfo.taker.sig) {\n\t\t\treturn fmt.Errorf(\"expected taker redemption signature '%x', got '%x'\", matchInfo.taker.sig, tracker.Sigs.TakerRedeem)\n\t\t}\n\t}\n\treturn nil\n}", "func EstimateReward(reward, pr, gamma float64) float64 {\n\tret := reward / (pr + gamma)\n\tlog.Logf(MABLogLevel, \"MAB Estimate Reward: %v / (%v + %v) = %v\\n\",\n\t\treward, pr, gamma, ret)\n\treturn ret\n}", "func (k Querier) Rewards(c context.Context, req *types.QueryRewardsRequest) (*types.QueryRewardsResponse, error) {\n\tif req == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"invalid request\")\n\t}\n\n\tif req.StakingCoinDenom != \"\" {\n\t\tif err := sdk.ValidateDenom(req.StakingCoinDenom); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tctx := sdk.UnwrapSDKContext(c)\n\tstore := ctx.KVStore(k.storeKey)\n\tvar rewards []types.Reward\n\tvar pageRes *query.PageResponse\n\tvar err error\n\n\tif req.Farmer != \"\" {\n\t\tvar farmerAcc sdk.AccAddress\n\t\tfarmerAcc, err = sdk.AccAddressFromBech32(req.Farmer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tstorePrefix := types.GetRewardsByFarmerIndexKey(farmerAcc)\n\t\tindexStore := prefix.NewStore(store, storePrefix)\n\t\tpageRes, err = query.FilteredPaginate(indexStore, req.Pagination, func(key, value []byte, accumulate bool) (bool, error) {\n\t\t\t_, stakingCoinDenom := types.ParseRewardsByFarmerIndexKey(append(storePrefix, key...))\n\t\t\tif req.StakingCoinDenom != \"\" {\n\t\t\t\tif stakingCoinDenom != req.StakingCoinDenom {\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treward, found := k.GetReward(ctx, stakingCoinDenom, farmerAcc)\n\t\t\tif !found { // TODO: remove this check\n\t\t\t\treturn false, fmt.Errorf(\"reward not found\")\n\t\t\t}\n\t\t\tif accumulate {\n\t\t\t\trewards = append(rewards, reward)\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n\t} else {\n\t\tvar storePrefix []byte\n\t\tif req.StakingCoinDenom != \"\" {\n\t\t\tstorePrefix = types.GetRewardsByStakingCoinDenomKey(req.StakingCoinDenom)\n\t\t} else {\n\t\t\tstorePrefix = types.RewardKeyPrefix\n\t\t}\n\t\trewardStore := prefix.NewStore(store, storePrefix)\n\n\t\tpageRes, err = query.Paginate(rewardStore, req.Pagination, func(key, value []byte) error {\n\t\t\tstakingCoinDenom, farmerAcc := types.ParseRewardKey(append(storePrefix, key...))\n\t\t\trewardCoins, err := k.UnmarshalRewardCoins(value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\trewards = append(rewards, types.Reward{\n\t\t\t\tFarmer: farmerAcc.String(),\n\t\t\t\tStakingCoinDenom: stakingCoinDenom,\n\t\t\t\tRewardCoins: rewardCoins.RewardCoins,\n\t\t\t})\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &types.QueryRewardsResponse{Rewards: rewards, Pagination: pageRes}, nil\n}", "func (_Bindings *BindingsTransactor) Redeem(opts *bind.TransactOpts, redeemTokens *big.Int) (*types.Transaction, error) {\n\treturn _Bindings.contract.Transact(opts, \"redeem\", redeemTokens)\n}", "func computeReward(epoch abi.ChainEpoch, prevTheta, currTheta, simpleTotal, baselineTotal big.Int) abi.TokenAmount {\n\tsimpleReward := big.Mul(simpleTotal, ExpLamSubOne) //Q.0 * Q.128 => Q.128\n\tepochLam := big.Mul(big.NewInt(int64(epoch)), Lambda) // Q.0 * Q.128 => Q.128\n\n\tsimpleReward = big.Mul(simpleReward, big.NewFromGo(math.ExpNeg(epochLam.Int))) // Q.128 * Q.128 => Q.256\n\tsimpleReward = big.Rsh(simpleReward, math.Precision128) // Q.256 >> 128 => Q.128\n\n\tbaselineReward := big.Sub(computeBaselineSupply(currTheta, baselineTotal), computeBaselineSupply(prevTheta, baselineTotal)) // Q.128\n\n\treward := big.Add(simpleReward, baselineReward) // Q.128\n\n\treturn big.Rsh(reward, math.Precision128) // Q.128 => Q.0\n}", "func (g *Group) POST(path string, h Handler, gases ...Gas) {\n\tg.Air.POST(g.Prefix+path, h, append(g.Gases, gases...)...)\n}", "func (transaction *AccountCreateTransaction) GetDeclineStakingReward() bool {\n\treturn transaction.declineReward\n}", "func Submit(\n\tt *testing.T,\n\tb *emulator.Blockchain,\n\ttx *flow.Transaction,\n\tshouldRevert bool,\n) {\n\t// submit the signed transaction\n\terr := b.AddTransaction(*tx)\n\trequire.NoError(t, err)\n\n\tresult, err := b.ExecuteNextTransaction()\n\trequire.NoError(t, err)\n\n\tif shouldRevert {\n\t\tassert.True(t, result.Reverted())\n\t} else {\n\t\tif !assert.True(t, result.Succeeded()) {\n\t\t\tt.Log(result.Error.Error())\n\t\t}\n\t}\n\n\t_, err = b.CommitBlock()\n\tassert.NoError(t, err)\n}", "func Submit(\n\tt *testing.T,\n\tb *emulator.Blockchain,\n\ttx *flow.Transaction,\n\tshouldRevert bool,\n) {\n\t// submit the signed transaction\n\terr := b.AddTransaction(*tx)\n\trequire.NoError(t, err)\n\n\tresult, err := b.ExecuteNextTransaction()\n\trequire.NoError(t, err)\n\n\tif shouldRevert {\n\t\tassert.True(t, result.Reverted())\n\t} else {\n\t\tif !assert.True(t, result.Succeeded()) {\n\t\t\tt.Log(result.Error.Error())\n\t\t}\n\t}\n\n\t_, err = b.CommitBlock()\n\tassert.NoError(t, err)\n}", "func claim(args []string) (string, error) {\n\tamount, err := util.StringToRau(args[0], util.IotxDecimalNum)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tpayload := make([]byte, 0)\n\tif len(args) == 2 {\n\t\tpayload = []byte(args[1])\n\t}\n\tsender, err := alias.Address(signer)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif gasLimit == 0 {\n\t\tgasLimit = action.ClaimFromRewardingFundBaseGas +\n\t\t\taction.ClaimFromRewardingFundGasPerByte*uint64(len(payload))\n\t}\n\tvar gasPriceRau *big.Int\n\tif len(gasPrice) == 0 {\n\t\tgasPriceRau, err = GetGasPrice()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t} else {\n\t\tgasPriceRau, err = util.StringToRau(gasPrice, util.GasPriceDecimalNum)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tif nonce == 0 {\n\t\taccountMeta, err := account.GetAccountMeta(sender)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tnonce = accountMeta.PendingNonce\n\t}\n\tb := &action.ClaimFromRewardingFundBuilder{}\n\tact := b.SetAmount(amount).SetData(payload).Build()\n\tbd := &action.EnvelopeBuilder{}\n\telp := bd.SetNonce(nonce).\n\t\tSetGasPrice(gasPriceRau).\n\t\tSetGasLimit(gasLimit).\n\t\tSetAction(&act).Build()\n\treturn sendAction(elp)\n}", "func (_Vault *VaultTransactorSession) SubmitBurnProof(inst []byte, heights *big.Int, instPaths [][32]byte, instPathIsLefts []bool, instRoots [32]byte, blkData [32]byte, sigIdxs []*big.Int, sigVs []uint8, sigRs [][32]byte, sigSs [][32]byte) (*types.Transaction, error) {\n\treturn _Vault.Contract.SubmitBurnProof(&_Vault.TransactOpts, inst, heights, instPaths, instPathIsLefts, instRoots, blkData, sigIdxs, sigVs, sigRs, sigSs)\n}", "func (dcr *ExchangeWallet) PreRedeem(req *asset.PreRedeemForm) (*asset.PreRedeem, error) {\n\tfeeRate := req.FeeSuggestion\n\tif feeRate == 0 { // or just document that the caller must set it?\n\t\tfeeRate = dcr.targetFeeRateWithFallback(dcr.redeemConfTarget, req.FeeSuggestion)\n\t}\n\t// Best is one transaction with req.Lots inputs and 1 output.\n\tvar best uint64 = dexdcr.MsgTxOverhead\n\t// Worst is req.Lots transactions, each with one input and one output.\n\tvar worst uint64 = dexdcr.MsgTxOverhead * req.Lots\n\tvar inputSize uint64 = dexdcr.TxInOverhead + dexdcr.RedeemSwapSigScriptSize\n\tvar outputSize uint64 = dexdcr.P2PKHOutputSize\n\tbest += inputSize*req.Lots + outputSize\n\tworst += (inputSize + outputSize) * req.Lots\n\n\t// Read the order options.\n\tcustomCfg := new(redeemOptions)\n\terr := config.Unmapify(req.SelectedOptions, customCfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing selected options: %w\", err)\n\t}\n\n\t// Parse the configured fee bump.\n\tvar currentBump float64 = 1.0\n\tif customCfg.FeeBump != nil {\n\t\tbump := *customCfg.FeeBump\n\t\tif bump < 1.0 || bump > 2.0 {\n\t\t\treturn nil, fmt.Errorf(\"invalid fee bump: %f\", bump)\n\t\t}\n\t\tcurrentBump = bump\n\t}\n\n\topts := []*asset.OrderOption{{\n\t\tConfigOption: asset.ConfigOption{\n\t\t\tKey: redeemFeeBumpFee,\n\t\t\tDisplayName: \"Faster Redemption\",\n\t\t\tDescription: \"Bump the redemption transaction fees up to 2x for faster confirmations on your redemption transaction.\",\n\t\t\tDefaultValue: 1.0,\n\t\t},\n\t\tXYRange: &asset.XYRange{\n\t\t\tStart: asset.XYRangePoint{\n\t\t\t\tLabel: \"1X\",\n\t\t\t\tX: 1.0,\n\t\t\t\tY: float64(feeRate),\n\t\t\t},\n\t\t\tEnd: asset.XYRangePoint{\n\t\t\t\tLabel: \"2X\",\n\t\t\t\tX: 2.0,\n\t\t\t\tY: float64(feeRate * 2),\n\t\t\t},\n\t\t\tYUnit: \"atoms/B\",\n\t\t\tXUnit: \"X\",\n\t\t},\n\t}}\n\n\treturn &asset.PreRedeem{\n\t\tEstimate: &asset.RedeemEstimate{\n\t\t\tRealisticWorstCase: uint64(math.Round(float64(worst*feeRate) * currentBump)),\n\t\t\tRealisticBestCase: uint64(math.Round(float64(best*feeRate) * currentBump)),\n\t\t},\n\t\tOptions: opts,\n\t}, nil\n}", "func (bc *blockchain) TransferBurst(senderPublicKey []byte, receiverId uint64, amount, fee int64) error {\n\ttotalAmount := amount + fee\n\treturn bc.db.Update(func(txn *badger.Txn) error {\n\t\t// senderPublicKey nil -> block forge\n\t\tif senderPublicKey != nil {\n\t\t\tsender, err := bc.getAccountByPublicKey(txn, senderPublicKey)\n\t\t\tswitch err {\n\t\t\tcase nil:\n\t\t\tcase badger.ErrKeyNotFound:\n\t\t\t\t// an account only gets a public key on its first outgoing transaction\n\t\t\t\t// so we need to check if we can find it by numeric id\n\t\t\t\t_, id := crypto.BytesToHashAndID(senderPublicKey)\n\t\t\t\tswitch sender, err = bc.getAccountById(txn, id); err {\n\t\t\t\tcase nil:\n\t\t\t\t\t// we found the account by numeric id, but not by public key\n\t\t\t\t\t// this is the account's first outgoing transaction\n\t\t\t\t\t// we can no activate it by setting its public key\n\t\t\t\t\tsender.PublicKey = senderPublicKey\n\n\t\t\t\t\t// to be retrievable by public key we need to add it to\n\t\t\t\t\t// the account index\n\t\t\t\t\tif err := bc.indexAccountsPublicKey(txn, sender); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\tcase badger.ErrKeyNotFound:\n\t\t\t\t\treturn ErrUnknownAccount\n\t\t\t\tdefault:\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn err\n\n\t\t\t}\n\n\t\t\tif sender.Balance < totalAmount {\n\t\t\t\treturn ErrBalanceTooLow\n\t\t\t}\n\t\t\tsender.Balance -= totalAmount\n\t\t\tif err := bc.updateAccount(txn, sender); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treceiver, err := bc.getAccountById(txn, receiverId)\n\t\tswitch err {\n\t\tcase nil:\n\t\t\t// if this is a block forge transfer -> reward recipient handling\n\t\t\tif senderPublicKey == nil && receiver.RewardRecipient != receiver.Id {\n\t\t\t\treceiver, err = bc.getAccountById(txn, receiverId)\n\t\t\t\tswitch err {\n\t\t\t\tcase nil:\n\t\t\t\tcase badger.ErrKeyNotFound:\n\t\t\t\t\treceiver = account.NewAccount(receiverId)\n\t\t\t\tdefault:\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\tcase badger.ErrKeyNotFound:\n\t\t\t// receiver did not exist yet, so its a new account that still\n\t\t\t// needs to get activated with an outgoing transaction\n\t\t\treceiver = account.NewAccount(receiverId)\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t\treceiver.Balance += amount\n\n\t\treturn bc.updateAccount(txn, receiver)\n\t})\n}", "func ApprovePost(id string) error {\n\t_, err := db.Query(\"UPDATE furmpost SET adApproval=? WHERE entryID=?\", 1, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func PostHandleMsgSignerUpdate(ctx sdk.Context, k keeper.Keeper, msg types.MsgSignerUpdate, sideTxResult tmprototypes.SideTxResultType) (*sdk.Result, error) {\n\t// Skip handler if signer update is not approved\n\tif sideTxResult != tmprototypes.SideTxResultType_YES {\n\t\tk.Logger(ctx).Debug(\"Skipping signer update since side-tx didn't get yes votes\")\n\t\treturn nil, hmCommon.ErrSideTxValidation\n\t}\n\n\t// Check for replay attack\n\tblockNumber := new(big.Int).SetUint64(msg.BlockNumber)\n\tsequence := new(big.Int).Mul(blockNumber, big.NewInt(hmTypes.DefaultLogIndexUnit))\n\tsequence.Add(sequence, new(big.Int).SetUint64(msg.LogIndex))\n\t// check if incoming tx is older\n\tif k.HasStakingSequence(ctx, sequence.String()) {\n\t\tk.Logger(ctx).Error(\"Older invalid tx found\")\n\t\treturn nil, hmCommon.ErrOldTx\n\t}\n\n\tk.Logger(ctx).Debug(\"Persisting signer update\", \"sideTxResult\", sideTxResult)\n\n\t// new pubkey and signer\n\tnewPubKey := msg.GetNewSignerPubKey()\n\tnewSigner := newPubKey.Address()\n\n\t// pull validator from store\n\tvalidator, ok := k.GetValidatorFromValID(ctx, msg.ID)\n\tif !ok {\n\t\tk.Logger(ctx).Error(\"Fetching of validator from store failed\", \"validatorId\", msg.ID)\n\t\treturn nil, hmCommon.ErrNoValidator\n\t}\n\toldValidator := validator.Copy()\n\n\t// update last updated\n\tvalidator.LastUpdated = sequence.String()\n\n\t// update nonce\n\tvalidator.Nonce = msg.Nonce\n\n\t// check if we are actually updating signer\n\tif !bytes.Equal(newSigner.Bytes(), []byte(validator.Signer)) {\n\t\t// Update signer in prev Validator\n\t\tvalidator.Signer = newSigner.String()\n\t\tvalidator.PubKey = newPubKey.String()\n\t\tk.Logger(ctx).Debug(\"Updating new signer\", \"newSigner\", newSigner, \"oldSigner\", oldValidator.Signer, \"validatorID\", msg.ID)\n\t} else {\n\t\tk.Logger(ctx).Error(\"No signer change\", \"newSigner\", newSigner, \"oldSigner\", oldValidator.Signer, \"validatorID\", msg.ID)\n\t\treturn nil, hmCommon.ErrSignerUpdateError\n\t}\n\n\tk.Logger(ctx).Debug(\"Removing old validator\", \"validator\", oldValidator.String())\n\n\t// remove old validator from HM\n\toldValidator.EndEpoch = k.ModuleCommunicator.GetACKCount(ctx)\n\n\t// remove old validator from TM\n\toldValidator.VotingPower = 0\n\t// updated last\n\toldValidator.LastUpdated = sequence.String()\n\n\t// updated nonce\n\toldValidator.Nonce = msg.Nonce\n\n\t// save old validator\n\tif err := k.AddValidator(ctx, *oldValidator); err != nil {\n\t\tk.Logger(ctx).Error(\"Unable to update signer\", \"error\", err, \"validatorId\", validator.ID)\n\t\treturn nil, hmCommon.ErrSignerUpdateError\n\t}\n\n\t// adding new validator\n\tk.Logger(ctx).Debug(\"Adding new validator\", \"validator\", validator.String())\n\n\t// save validator\n\terr := k.AddValidator(ctx, validator)\n\tif err != nil {\n\t\tk.Logger(ctx).Error(\"Unable to update signer\", \"error\", err, \"ValidatorID\", validator.ID)\n\t\treturn nil, hmCommon.ErrSignerUpdateError\n\t}\n\n\t// save staking sequence\n\tk.SetStakingSequence(ctx, sequence.String())\n\n\t// TX bytes\n\ttxBytes := ctx.TxBytes()\n\thash := tmTypes.Tx(txBytes).Hash()\n\n\t//\n\t// Move heimdall fee to new signer\n\t//\n\n\t// check if fee is already withdrawn\n\tmaticBalance := k.BankKeeper.GetBalance(ctx, sdk.AccAddress([]byte(oldValidator.Signer)), types.FeeToken)\n\tif !maticBalance.IsZero() {\n\t\tk.Logger(ctx).Info(\"Transferring fee\", \"from\", oldValidator.Signer, \"to\", validator.Signer, \"balance\", maticBalance.String())\n\t\tmaticCoins := sdk.Coins{maticBalance}\n\t\tif err := k.BankKeeper.SendCoins(ctx, sdk.AccAddress([]byte(oldValidator.Signer)), sdk.AccAddress([]byte(validator.Signer)), maticCoins); err != nil {\n\t\t\tk.Logger(ctx).Info(\"Error while transferring fee\", \"from\", oldValidator.Signer, \"to\", validator.Signer, \"balance\", maticBalance.String())\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tctx.EventManager().EmitEvents(sdk.Events{\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeSignerUpdate,\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAction, msg.Type()), // action\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), // module name\n\t\t\tsdk.NewAttribute(hmTypes.AttributeKeyTxHash, hmCommonTypes.BytesToHeimdallHash(hash).Hex()), // tx hash\n\t\t\tsdk.NewAttribute(hmTypes.AttributeKeySideTxResult, sideTxResult.String()), // result\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidatorID, validator.ID.String()),\n\t\t\tsdk.NewAttribute(types.AttributeKeyValidatorNonce, strconv.FormatUint(msg.Nonce, 10)),\n\t\t),\n\t})\n\n\treturn &sdk.Result{\n\t\tEvents: ctx.EventManager().ABCIEvents(),\n\t}, nil\n}", "func (_Contract *ContractCaller) TaskHandlingReward(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"taskHandlingReward\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func PostSlotTransition(ctx context.Context, spec *Spec, epc *EpochsContext, state BeaconState, benv *BeaconBlockEnvelope, validateResult bool) error {\n\tslot, err := state.Slot()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif slot != benv.Slot {\n\t\treturn fmt.Errorf(\"transition of block, post-slot-processing, must run on state with same slot\")\n\t}\n\tif validateResult {\n\t\t// TODO: tests have invalid fork version in state\n\t\tfork, err := state.Fork()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t//version := spec.ForkVersion(benv.Slot)\n\t\t//if fork.CurrentVersion != version {\n\t\t//\treturn fmt.Errorf(\"state does not have expected fork version of block slot: %s <> %s (slot %d)\",\n\t\t//\t\tfork.CurrentVersion, version, benv.Slot)\n\t\t//}\n\t\tproposer, err := epc.GetBeaconProposer(benv.Slot)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgenValRoot, err := state.GenesisValidatorsRoot()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpub, ok := epc.ValidatorPubkeyCache.Pubkey(proposer)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown pubkey for proposer %d\", proposer)\n\t\t}\n\t\tif !benv.VerifySignatureVersioned(spec, fork.CurrentVersion, genValRoot, proposer, pub) {\n\t\t\treturn errors.New(\"block has invalid signature\")\n\t\t}\n\t}\n\tif err := state.ProcessBlock(ctx, spec, epc, benv); err != nil {\n\t\treturn err\n\t}\n\n\t// State root verification\n\tif validateResult && benv.StateRoot != state.HashTreeRoot(tree.GetHashFn()) {\n\t\treturn errors.New(\"block has invalid state root\")\n\t}\n\treturn nil\n}", "func (a *StoragePowerActorCode_I) AddBalance(rt Runtime, minerAddr addr.Address) {\n\tRT_MinerEntry_ValidateCaller_DetermineFundsLocation(rt, minerAddr, vmr.MinerEntrySpec_MinerOnly)\n\n\tmsgValue := rt.ValueReceived()\n\n\th, st := a.State(rt)\n\tnewTable, ok := autil.BalanceTable_WithAdd(st.EscrowTable(), minerAddr, msgValue)\n\tif !ok {\n\t\trt.AbortStateMsg(\"Escrow operation failed\")\n\t}\n\tst.Impl().EscrowTable_ = newTable\n\tUpdateRelease(rt, h, st)\n}", "func SenderHtlcSpendRedeem(signer Signer, signDesc *SignDescriptor,\n\tsweepTx *wire.MsgTx, paymentPreimage []byte) (wire.TxWitness, error) {\n\n\tsweepSig, err := signer.SignOutputRaw(sweepTx, signDesc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// The stack required to spend this output is simply the signature\n\t// generated above under the receiver's public key, and the payment\n\t// pre-image.\n\twitnessStack := wire.TxWitness(make([][]byte, 3))\n\twitnessStack[0] = append(sweepSig.Serialize(), byte(signDesc.HashType))\n\twitnessStack[1] = paymentPreimage\n\twitnessStack[2] = signDesc.WitnessScript\n\n\treturn witnessStack, nil\n}", "func (client CloudEndpointsClient) PostRestoreResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (sp *SimulatedPlayer) Redeem(cs *markets.ContractSet, m *markets.Market, v bool) {\n\tsp.mp.Redeem(cs, m, v)\n}", "func (b *Builder) Post(addr value.Pointer, size uint64, p Postback) {\n\tif !addr.IsValid() {\n\t\tpanic(fmt.Errorf(\"Pointer address %v is not valid\", addr))\n\t}\n\tb.instructions = append(b.instructions, asm.Post{\n\t\tSource: b.remap(addr),\n\t\tSize: size,\n\t})\n\tb.decoders = append(b.decoders, postBackDecoder{\n\t\texpectedSize: int(size),\n\t\tdecode: p,\n\t})\n}", "func (s *State) returnDeposit(tx *types.Transaction, height uint32) {\n\tvar inputValue common.Fixed64\n\tfor _, input := range tx.Inputs {\n\t\tinputValue += s.DepositOutputs[input.ReferKey()]\n\t}\n\n\treturnAction := func(producer *Producer) {\n\t\ts.history.Append(height, func() {\n\t\t\tif height >= s.chainParams.CRVotingStartHeight {\n\t\t\t\tproducer.depositAmount -= inputValue\n\t\t\t}\n\t\t\tproducer.state = Returned\n\t\t}, func() {\n\t\t\tif height >= s.chainParams.CRVotingStartHeight {\n\t\t\t\tproducer.depositAmount += inputValue\n\t\t\t}\n\t\t\tproducer.state = Canceled\n\t\t})\n\t}\n\n\tfor _, program := range tx.Programs {\n\t\tpk := program.Code[1 : len(program.Code)-1]\n\t\tif producer := s.getProducer(pk); producer != nil && producer.state == Canceled {\n\t\t\treturnAction(producer)\n\t\t}\n\t}\n}", "func (_RandomBeacon *RandomBeaconTransactor) WithdrawRewards(opts *bind.TransactOpts, stakingProvider common.Address) (*types.Transaction, error) {\n\treturn _RandomBeacon.contract.Transact(opts, \"withdrawRewards\", stakingProvider)\n}", "func (_Smartchef *SmartchefTransactor) EmergencyRewardWithdraw(opts *bind.TransactOpts, _amount *big.Int) (*types.Transaction, error) {\n\treturn _Smartchef.contract.Transact(opts, \"emergencyRewardWithdraw\", _amount)\n}", "func (testSuite *MainTestSuite) flipStockPost(gameStateID uuid.UUID) {\n\tresp, err := testSuite.client.Post(\n\t\taddGameStateIdToURL(testSuite.server.URL+\"/flipstock\", gameStateID),\n\t\t\"text/json\", nil)\n\t_ = err // silence warning about using defer before checking err\n\tdefer resp.Body.Close()\n\tcheckResponse(testSuite.T(), resp, err)\n}" ]
[ "0.7543883", "0.6046861", "0.59213", "0.5888484", "0.569692", "0.5377273", "0.53159016", "0.51158017", "0.5068981", "0.49706677", "0.49703842", "0.49670628", "0.49598822", "0.49169713", "0.49141806", "0.49058503", "0.49056473", "0.48940882", "0.48806125", "0.4861055", "0.48592457", "0.48581138", "0.4853659", "0.4821137", "0.4811574", "0.4793853", "0.478681", "0.47858256", "0.47816804", "0.47714853", "0.4768141", "0.47667566", "0.47511724", "0.4748677", "0.47452414", "0.4744874", "0.47343495", "0.47282892", "0.47150448", "0.47117317", "0.47064444", "0.46983626", "0.46933407", "0.46906152", "0.46857974", "0.4685569", "0.46759397", "0.46676412", "0.46427146", "0.4630347", "0.46227887", "0.46189213", "0.46159413", "0.46077064", "0.4600528", "0.45919168", "0.45901904", "0.45850074", "0.458095", "0.4578385", "0.45707613", "0.4567512", "0.45659444", "0.4543624", "0.4539644", "0.4531277", "0.45096242", "0.45085186", "0.45051596", "0.449541", "0.44850242", "0.44830614", "0.4480382", "0.44769728", "0.44707495", "0.44684407", "0.44483754", "0.4441326", "0.44314894", "0.4431174", "0.4428727", "0.4423487", "0.4423487", "0.44230554", "0.44195634", "0.44194564", "0.44081748", "0.4402279", "0.43986595", "0.43875456", "0.43864027", "0.4386081", "0.43761623", "0.43570605", "0.43476427", "0.43471706", "0.4342304", "0.43381238", "0.43370718", "0.43354195" ]
0.7991568
0
handle first http connect, and convert connect to websocket
func (ws *WS)HandleConn(conn net.Conn, authConn *AuthConns, dealmsg func([]byte)bool){ defer conn.Close() buf := make([]byte, 1024) bufChan := make(chan []byte, 10) defer close(bufChan) go ws.HandleWS(bufChan, authConn, dealmsg) for{ _, err := conn.Read(buf) if err != nil{ if err != io.EOF{ //if client ws closed abnormally, close ws log.Println("conn read failed: ", err) //ws.Close() mu.Lock() authConn.Conns[conn] = false mu.Unlock() return } continue } //if conn is in authConn, start websocket handle if authConn.Conns[conn]{ //websocket.HandleWS(buf[:],ws) bufChan <- buf[:] select{ //if websocket closed, delete conn from authConn case <- ws.Closed: //delete(authConn, conn) mu.Lock() authConn.Conns[conn] = false mu.Unlock() return default: } continue } //get sec-websocket-key key,err := AuthorizeHeaders(string(buf)) if err != nil{ log.Println("auth failed: ", err) return } nkey := PrepareKey(key) nheader := PrepareHeaders(nkey) _, err = conn.Write(nheader) if err != nil{ log.Println("new header send failed: ", err) } //if handshake success, add conn into authConn mu.Lock() authConn.Conns[conn] = true mu.Unlock() log.Println("new websocket from ",conn.RemoteAddr().String()) err = ws.SendWelcome() if err != nil{ log.Println("welcome failed: ", err) } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func serveWebSocket(w http.ResponseWriter, r *http.Request){\n if r.Method != \"GET\" {\n http.Error(w, \"Method not allowed\", 405)\n return\n }\n ws, err := upgrader.Upgrade(w, r, nil)\n if err != nil {\n log.Println(err)\n return\n }\n c := &Connection{send: make(chan []byte, 256), ws: ws}\n h.register <- c\n go c.writePump()\n c.readPump()\n}", "func connectWebsocket(port string) {\n\tfor {\n\t\tvar err error\n\t\tServerIP = utils.DiscoverServer()\n\t\tif ServerIP == \"\" {\n\t\t\tlogger.WithFields(logger.Fields{}).Debugf(\"Wait 5 seconds to redail...\")\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t\tcontinue\n\t\t}\n\t\tu := url.URL{Scheme: \"ws\", Host: ServerIP + \":\" + os.Getenv(\"CASA_SERVER_PORT\"), Path: \"/v1/ws\"}\n\t\tWS, _, err = websocket.DefaultDialer.Dial(u.String(), nil)\n\t\tif err != nil {\n\t\t\tlogger.WithFields(logger.Fields{\"code\": \"CGGWCCW001\"}).Errorf(\"%s\", err.Error())\n\t\t\tlogger.WithFields(logger.Fields{}).Debugf(\"Wait 5 seconds to redail...\")\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\taddr := strings.Split(WS.LocalAddr().String(), \":\")[0]\n\tmessage := WebsocketMessage{\n\t\tAction: \"newConnection\",\n\t\tBody: []byte(addr + \":\" + port),\n\t}\n\tbyteMessage, _ := json.Marshal(message)\n\terr := WS.WriteMessage(websocket.TextMessage, byteMessage)\n\tif err != nil {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CGGWCCW002\"}).Errorf(\"%s\", err.Error())\n\t\treturn\n\t}\n\tlogger.WithFields(logger.Fields{}).Debugf(\"Websocket connected!\")\n}", "func wsHttpConnect(proxy, url_ string) (io.ReadWriteCloser, error) {\n\tlog.Printf(\"[%s] proxy =\", __FILE__, proxy)\n\tproxy_tcp_conn, err := net.Dial(\"tcp\", proxy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[%s] proxy_tcp_conn =\", __FILE__, proxy_tcp_conn)\n\tlog.Printf(\"[%s] url_ =\", __FILE__, url_)\n\n\tturl, err := url.Parse(url_)\n\tif err != nil {\n\t\tlog.Printf(\"[%s] Parse : \", __FILE__, err)\n\t\treturn nil, err\n\t}\n\n\tlog.Printf(\"[%s] proxy turl.Host =\", __FILE__, string(turl.Host))\n\n\treq := http.Request{\n\t\tMethod: \"CONNECT\",\n\t\tURL: &url.URL{},\n\t\tHost: turl.Host,\n\t}\n\n\tproxy_http_conn := httputil.NewProxyClientConn(proxy_tcp_conn, nil)\n\t//cc := http.NewClientConn(proxy_tcp_conn, nil)\n\n\tlog.Printf(\"[%s] proxy_http_conn =\", __FILE__, proxy_http_conn)\n\n\tresp, err := proxy_http_conn.Do(&req)\n\tif err != nil && err != httputil.ErrPersistEOF {\n\t\tlog.Printf(\"[%s] ErrPersistEOF : \", __FILE__, err)\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[%s] proxy_http_conn<resp> =\", __FILE__, (resp))\n\n\trwc, _ := proxy_http_conn.Hijack()\n\n\treturn rwc, nil\n\n}", "func serveWs(w http.ResponseWriter, r *http.Request) {\n fmt.Println(r.Host)\n\n // upgrade this connection to a WebSocket\n // connection\n ws, err := upgrader.Upgrade(w, r, nil)\n if err != nil {\n log.Println(err)\n }\n // listen indefinitely for new messages coming\n // through on our WebSocket connection\n reader(ws)\n}", "func serveWs(h func(*Client), upgrader *websocket.Upgrader, w http.ResponseWriter, r *http.Request) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tclient := &Client{\n\t\tconn: conn,\n\t\tonConnectedHandler: h,\n\t\tsend: make(chan []byte, 256),\n\t\treceive: make(chan []byte, 256),\n\t\tconnQuit: make(chan struct{}, 1),\n\t\tchanQuit: make(chan struct{}, 1),\n\t}\n\tclient.Run()\n}", "func (st *state) connectStream(path string, attrs url.Values, extraHeaders http.Header) (base.Stream, error) {\n\ttarget := url.URL{\n\t\tScheme: \"wss\",\n\t\tHost: st.addr,\n\t\tPath: path,\n\t\tRawQuery: attrs.Encode(),\n\t}\n\t// TODO(macgreagoir) IPv6. Ubuntu still always provides IPv4 loopback,\n\t// and when/if this changes localhost should resolve to IPv6 loopback\n\t// in any case (lp:1644009). Review.\n\tcfg, err := websocket.NewConfig(target.String(), \"http://localhost/\")\n\t// Add any cookies because they will not be sent to websocket\n\t// connections by default.\n\tfor header, values := range extraHeaders {\n\t\tfor _, value := range values {\n\t\t\tcfg.Header.Add(header, value)\n\t\t}\n\t}\n\n\tconnection, err := websocketDialConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := readInitialStreamError(connection); err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treturn connection, nil\n}", "func ws_Server_Connect(server_url string) (ws *websocket.Conn, err error) {\n\n\tvar wss_server_url = wss_prefix + server_url\n\tws, err = wsProxyDial(wss_server_url, \"tcp\", wss_server_url)\n\n\tif err != nil {\n\t\tlog.Printf(\"[%s] wsProxyDial : \", __FILE__, err)\n\t\treturn nil, err\n\t}\n\n\tname := getUniqueID()\n\n\terr = wsReqeustConnection(ws, name)\n\tif err != nil {\n\t\tlog.Printf(\"[%s] ws_Server_Connect error = \", err)\n\t\treturn ws, err\n\t}\n\n\treturn ws, nil\n\n}", "func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) {\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(lib.PrettyError(\"[WEBSOCKET] Get websocket connection from Upgrade failed - \" + err.Error()))\n\t\treturn\n\t}\n\t/* ======== Get data ======== */\n\tvars := mux.Vars(r)\n\tclaims, err := lib.AnalyseJWT(vars[\"jwt\"])\n\tif err != nil || claims[\"username\"].(string) == \"\" {\n\t\terrorWS(ws, \"Failed to collect jwt data\")\n\t\treturn\n\t}\n\t/* ========================== */\n\tc := &connection{ws: ws, send: make(chan []byte, 255)}\n\ts := subscription{conn: c, username: claims[\"username\"].(string)}\n\thub.register <- s\n\tgo s.writePump()\n\ts.readPump()\n}", "func Upgrade(w http.ResponseWriter, r *http.Request) (*readwrite.Conn, error) {\n\tfmt.Println(\"start to Upgrade\")\n\tif r.Method != \"GET\" {\n\t\thttp.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)\n\t\treturn nil, fmt.Errorf(\"the method not GET\")\n\t}\n\tfmt.Println(r.Header)\n\n\tif values := r.Header[\"Sec-Websocket-Version\"]; len(values) == 0 || values[0] != \"13\" {\n\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\treturn nil, fmt.Errorf(\"the Sec-Websocket-Version != 13\")\n\t}\n\t// 检查Connection和Upgrade\n\tif !(readwrite.TokenListContainsValue(r.Header, \"Connection\", \"upgrade\")) {\n\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\treturn nil, fmt.Errorf(\"the Connection != upgrade\")\n\t}\n\tif !readwrite.TokenListContainsValue(r.Header, \"Upgrade\", \"websocket\") {\n\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\treturn nil, fmt.Errorf(\"the Upgrade != websocket\")\n\t}\n\t//计算Sec-websocket-Accept的值\n\tchallengkey := r.Header.Get(\"Sec-Websocket-Key\")\n\tif challengkey == \"\" {\n\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\treturn nil, fmt.Errorf(\"the Sec-websocket-Accept if NULL\")\n\t}\n\tvar (\n\t\tconn net.Conn\n\t\tbr *bufio.Reader\n\t)\n\n\th, ok := w.(http.Hijacker)\n\tif !ok {\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn nil, fmt.Errorf(\"websocket: response dose not implement http.Hijacker\")\n\t}\n\tvar rw *bufio.ReadWriter\n\tconn, rw, err := h.Hijack()\n\tif err != nil {\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn nil, fmt.Errorf(\"websocket: get http.Hijacker error : %v\", err)\n\t}\n\tbr = rw.Reader\n\tif br.Buffered() > 0 {\n\t\tconn.Close()\n\t\treturn nil, fmt.Errorf(\"websocket: client sent data before handshake is complete\")\n\t}\n\t//完成后就返回response\n\tvar p = []byte{}\n\tp = ([]byte)(\"HTTP/1.1 101 Switching Protocols\\r\\nUpgrade: websocket\\r\\nConnection: Upgrade\\r\\nSec-WebSocket-Accept:\")\n\n\tp = append(p, readwrite.KeyAndSecToSha1(challengkey)...)\n\tp = append(p, \"\\r\\n\\r\\n\"...)\n\tif _, err = conn.Write(p); err != nil {\n\t\tconn.Close()\n\t\treturn nil, fmt.Errorf(\"net.conn to send message find error\")\n\t}\n\tlog.Println(\"Upgrade http to webcosket success\")\n\tnetconn := readwrite.Newconn(conn)\n\treturn netconn, nil\n}", "func serveWs(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"GET\" {\n\t\thttp.Error(w, \"Method not allowed\", 405)\n\t\treturn\n\t}\n\tif r.Header.Get(\"Origin\") != \"http://\"+r.Host {\n\t\thttp.Error(w, \"Origin not allowed\", 403)\n\t\treturn\n\t}\n\tws, err := websocket.Upgrade(w, r.Header, nil, 1024, 1024)\n\tif _, ok := err.(websocket.HandshakeError); ok {\n\t\thttp.Error(w, \"Not a websocket handshake\", 400)\n\t\treturn\n\t} else if err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tc := &connection{send: make(chan []byte, 256), ws: ws}\n\th.register <- c\n\tgo c.writePump()\n\tc.readPump()\n}", "func (w *BaseWebsocketClient) OnConnecting() {}", "func StartWebsocketClient(port string) {\n\tconnectWebsocket(port)\n\n\t// Handle response from server\n\tgo func() {\n\t\tfor {\n\t\t\t_, readMessage, err := WS.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tlogger.WithFields(logger.Fields{\"code\": \"CGGWCSWC001\"}).Errorf(\"%s\", err.Error())\n\n\t\t\t\t// When read error is 1006, retry connection\n\t\t\t\tif strings.Contains(err.Error(), \"close 1006\") || strings.Contains(err.Error(), \"reset by peer\") {\n\t\t\t\t\tconnectWebsocket(port)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar parsedMessage WebsocketMessage\n\t\t\terr = json.Unmarshal(readMessage, &parsedMessage)\n\t\t\tif err != nil {\n\t\t\t\tlogger.WithFields(logger.Fields{\"code\": \"CGGWCSWC002\"}).Errorf(\"%s\", err.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch parsedMessage.Action {\n\t\t\tcase \"callAction\":\n\t\t\t\tvar action ActionMessage\n\t\t\t\terr = json.Unmarshal(parsedMessage.Body, &action)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.WithFields(logger.Fields{\"code\": \"CGGWCSWC005\"}).Errorf(\"%s\", err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif PluginFromName(action.Plugin) != nil && PluginFromName(action.Plugin).CallAction != nil {\n\t\t\t\t\tlogger.WithFields(logger.Fields{}).Debugf(\"Send action to plugin %s\", action.Plugin)\n\t\t\t\t\tgo PluginFromName(action.Plugin).CallAction(action.PhysicalID, action.Call, []byte(action.Params), []byte(action.Config))\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\tdefault:\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}()\n}", "func (gs *Service) initializeSessionWebsocket(sessionPort string) string {\n\terrorMsg := \"\"\n\tmux := http.NewServeMux()\n\tvar sessionId = gs.sessionIDIndex\n\tmux.HandleFunc(fmt.Sprintf(\"/session/%v\", sessionId), func(w http.ResponseWriter, r *http.Request) {\n\t\tr.Header.Add(\"Connection\", \"Upgrade\")\n\t\tr.Header.Add(\"Upgrade\", \"websocket\")\n\t\tr.Header.Add(\"Sec-WebSocket-Version\", \"13\")\n\t\tr.Header.Add(\"Sec-WebSocket-Key\", \"1234\")\n\n\t\tconn, err := upgrader.Upgrade(w, r, nil)\n\t\tif err != nil {\n\t\t\tmsg := fmt.Sprintf(\"Error while creating socket connection: %v\", err)\n\t\t\tlogger.Infof(msg)\n\t\t\terrorMsg = msg\n\t\t}\n\t\tclient := &Client{Conn: conn, Send: make(chan []byte, 256)}\n\t\tsession, ok := gs.sessions[sessionId]\n\t\tif ok {\n\t\t\tsession.hub.Register <- client\n\t\t\tgo gs.writeToSocket(*client)\n\t\t} else {\n\t\t\terrorMsg = fmt.Sprintf(\"Cant find session with id: %v\", sessionId)\n\t\t}\n\t})\n\tc := cors.New(cors.Options{\n\t\tAllowedOrigins: []string{\"*\"},\n\t\tAllowCredentials: true,\n\t})\n\n\thandler := cors.Default().Handler(mux)\n\t// Decorate existing handler with cors functionality set in c\n\thandler = c.Handler(handler)\n\tgo startServer(sessionPort, handler)\n\treturn errorMsg\n}", "func serveWs(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"GET\" {\n\t\thttp.Error(w, \"Method not allowed\", 405)\n\t\treturn\n\t}\n\n\tchatroomId := r.FormValue(\"chatroomId\")\n\n\tvar upgrader = websocket.Upgrader{\n\t\tReadBufferSize: 4096,\n\t\tWriteBufferSize: 4096,\t\n\t\tCheckOrigin: func(r *http.Request) bool { return true },\n\t}\n\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\th := chatIdToHub[chatroomId]\n\tif h == nil{\n\t\tfmt.Println(\"Couldn't find hub.\")\n\t}\n\n\tc := &connection{chatroomId: chatroomId, nicknameId: \"sadf\", hub: h, send: make(chan []byte, 256), ws: ws}\n\tc.hub.register <- c\n\tgo c.writePump()\n\tc.readPump()\n}", "func (w *Httpproxy) WebsocketProxy(rw http.ResponseWriter, req *http.Request) {\n\n\tbackendURL := CovertHTTPURL(req.URL, w.BackendHost, \"ws\")\n\tdialer := DefaultDialer\n\t// Pass headers from the incoming request to the dialer to forward them to\n\t// the final destinations.\n\trequestHeader := *CreateProxyRequestHeader(req)\n\trequestHeader.Del(\"Connection\")\n\trequestHeader.Del(\"Upgrade\")\n\tfor k := range requestHeader {\n\t\tif len(k) > 13 && k[:13] == \"Sec-Websocket\" && k != \"Sec-WebSocket-Protocol\" {\n\t\t\trequestHeader.Del(k)\n\t\t}\n\t}\n\n\t// Connect to the backend URL, also pass the headers we get from the requst\n\t// together with the Forwarded headers we prepared above.\n\t// TODO: support multiplexing on the same backend connection instead of\n\t// opening a new TCP connection time for each request. This should be\n\t// optional:\n\t// http://tools.ietf.org/html/draft-ietf-hybi-websocket-multiplexing-01\n\tconnBackend, resp, err := dialer.Dial(backendURL, requestHeader)\n\tif err != nil {\n\t\tlog.Printf(\"websocketproxy: couldn't dial to remote backend url %s\", err)\n\t\tif resp != nil {\n\t\t\t// If the WebSocket handshake fails, ErrBadHandshake is returned\n\t\t\t// along with a non-nil *http.Response so that callers can handle\n\t\t\t// redirects, authentication, etcetera.\n\t\t\tif err := copyResponse(rw, resp); err != nil {\n\t\t\t\tlog.Printf(\"websocketproxy: couldn't write response after failed remote backend handshake: %s\", err)\n\t\t\t}\n\t\t} else {\n\t\t\thttp.Error(rw, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)\n\t\t}\n\t\treturn\n\t}\n\tdefer connBackend.Close()\n\n\tupgrader := DefaultUpgrader\n\n\t// Only pass those headers to the upgrader.\n\tupgradeHeader := http.Header{}\n\tif hdr := resp.Header.Get(\"Sec-Websocket-Protocol\"); hdr != \"\" {\n\t\tupgradeHeader.Set(\"Sec-Websocket-Protocol\", hdr)\n\t}\n\tif hdr := resp.Header.Get(\"Set-Cookie\"); hdr != \"\" {\n\t\tupgradeHeader.Set(\"Set-Cookie\", hdr)\n\t}\n\n\t// Now upgrade the existing incoming request to a WebSocket connection.\n\t// Also pass the header that we gathered from the Dial handshake.\n\tconnPub, err := upgrader.Upgrade(rw, req, upgradeHeader)\n\tif err != nil {\n\t\tlog.Printf(\"websocketproxy: couldn't upgrade %s\", err)\n\t\treturn\n\t}\n\tdefer connPub.Close()\n\n\terrClient := make(chan error, 1)\n\terrBackend := make(chan error, 1)\n\treplicateWebsocketConn := func(dst, src *websocket.Conn, errc chan error) {\n\t\tfor {\n\t\t\tmsgType, msg, err := src.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tm := websocket.FormatCloseMessage(websocket.CloseNormalClosure, fmt.Sprintf(\"%v\", err))\n\t\t\t\tif e, ok := err.(*websocket.CloseError); ok {\n\t\t\t\t\tif e.Code != websocket.CloseNoStatusReceived {\n\t\t\t\t\t\tm = websocket.FormatCloseMessage(e.Code, e.Text)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\terrc <- err\n\t\t\t\tdst.WriteMessage(websocket.CloseMessage, m)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\terr = dst.WriteMessage(msgType, msg)\n\t\t\tif err != nil {\n\t\t\t\terrc <- err\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tgo replicateWebsocketConn(connPub, connBackend, errClient)\n\tgo replicateWebsocketConn(connBackend, connPub, errBackend)\n\n\tvar message string\n\tselect {\n\tcase err = <-errClient:\n\t\tmessage = \"websocketproxy: Error when copying from backend to client: %v\"\n\tcase err = <-errBackend:\n\t\tmessage = \"websocketproxy: Error when copying from client to backend: %v\"\n\n\t}\n\tif e, ok := err.(*websocket.CloseError); !ok || e.Code == websocket.CloseAbnormalClosure {\n\t\tlog.Printf(message, err)\n\t}\n}", "func connectConsumer(client *http.Client) (*websocket.Conn, error) {\n\n\ttransport, ok := client.Transport.(*http.Transport)\n\tif !ok {\n\t\treturn nil, errors.New(\"HTTP client doens't have http.Transport\")\n\t}\n\n\tsocket := &websocket.Dialer{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tRootCAs: transport.TLSClientConfig.RootCAs,\n\t\t\tCertificates: []tls.Certificate{\n\t\t\t\ttransport.TLSClientConfig.Certificates[0]},\n\t\t\tServerName: common.Cfg.EaaCommonName,\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t},\n\t}\n\n\thostHeader := http.Header{}\n\thostHeader.Add(\"Host\", common.Cfg.Namespace+\":\"+common.Cfg.ConsumerAppID)\n\n\tconn, resp, err := socket.Dial(\"wss://\"+common.Cfg.EdgeNodeEndpoint+\n\t\t\"/notifications\", hostHeader)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Couldn't dial to wss\")\n\t}\n\tdefer func() {\n\t\tif err := resp.Body.Close(); err != nil {\n\t\t\tlog.Println(\"Failed to close response body\")\n\t\t}\n\t}()\n\n\treturn conn, nil\n}", "func HttpHandler(ws *websocket.Conn) {\r\n\r\n\t// Here I will create the new connection...\r\n\tc := NewWebSocketConnection()\r\n\tc.m_socket = ws\r\n\tc.m_isOpen = true\r\n\tc.send = make(chan []byte)\r\n\r\n\t// Register the connection with the hub.\r\n\tGetServer().getHub().register <- c\r\n\r\n\tdefer func(c *WebSocketConnection) {\r\n\t\t// I will remove all sub-connection associated with the connection\r\n\t\tGetServer().removeAllOpenSubConnections(c.GetUuid())\r\n\t\tc.Close()\r\n\t\tLogInfo(\"--> connection \", c.GetUuid(), \"is close!\")\r\n\t}(c)\r\n\r\n\t// Start the writing loop...\r\n\tgo c.Writer()\r\n\r\n\t// we stay it stay in reader loop until the connection is close.\r\n\tc.Reader()\r\n}", "func handleClientSocket(w http.ResponseWriter, r *http.Request) {\n\tupgrader := websocket.Upgrader{}\n\tupgrader.CheckOrigin = func(r *http.Request) bool { return true }\n\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Fatal(\"Upgrading To Websocket Error : \", err)\n\t\treturn\n\t}\n\t// add the new client connection to the map of connection\n\tclientConnections <- conn\n\n\t// read from connection, only to check if connection is alive\n\tgo readClientSocket(conn)\n\t// write from connection\n}", "func (ws *WS) Connect(send, receive chan *RawMessage, stop chan bool) error {\n\turl, err := ws.getWebsocketURL(false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"ws Connect:\", url)\n\n\tconn, _, err := websocket.DefaultDialer.Dial(url, http.Header{\n\t\t// Origin is important, it won't connect otherwise\n\t\t\"Origin\": {\"https://6obcy.org\"},\n\t\t// User-Agent can be ommited, but we want to look legit\n\t\t\"User-Agent\": {\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36\"},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tdoneCh := make(chan bool)\n\tsetupCh := make(chan *setupMessage)\n\n\t// start recv goroutine\n\tgo func() {\n\t\tinitialized := false\n\t\tdefer close(doneCh)\n\t\tfor {\n\t\t\tmsgType, msgBytes, err := conn.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Failed to read:\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tprefix, msg := rawToTypeAndJSON(msgBytes)\n\t\t\tif !initialized {\n\t\t\t\tif prefix == setup {\n\t\t\t\t\tsm := &setupMessage{}\n\t\t\t\t\terr := json.Unmarshal([]byte(msg), sm)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatalf(\"Failed to parse setup message %s %s\\n\", err, msg)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tsetupCh <- sm\n\t\t\t\t\tinitialized = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif prefix == pong {\n\t\t\t\tif ws.Debug {\n\t\t\t\t\tfmt.Println(\"pong\")\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif ws.Debug {\n\t\t\t\tfmt.Println(\"ws ->:\", string(msgBytes))\n\t\t\t}\n\n\t\t\treceive <- &RawMessage{\n\t\t\t\tType: msgType,\n\t\t\t\tPayload: msgBytes,\n\t\t\t}\n\t\t}\n\t}()\n\n\t// start send goroutine\n\tgo func() {\n\t\tfor {\n\t\t\trm := <-send\n\n\t\t\tif rm == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ws.Debug {\n\t\t\t\tfmt.Println(\"ws <-:\", string(rm.Payload))\n\t\t\t}\n\n\t\t\terr := conn.WriteMessage(rm.Type, rm.Payload)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Failed to write:\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tvar setupMsg *setupMessage\n\n\tselect {\n\tcase sm := <-setupCh:\n\t\tsetupMsg = sm\n\tcase <-time.After(5 * time.Second):\n\t\tlog.Println(\"Waited 5 seconds for setup message\")\n\t}\n\n\t// create a ticker and take care of sending pings\n\tticker := time.NewTicker(time.Millisecond * time.Duration(setupMsg.PingInterval))\n\tdefer ticker.Stop()\n\n\t// start main ws goroutine\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif ws.Debug {\n\t\t\t\tfmt.Println(\"ping\")\n\t\t\t}\n\t\t\terr := conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(\"%d\", ping)))\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Failed to ping\", err)\n\t\t\t}\n\t\tcase <-stop:\n\t\t\terr := conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, \"\"))\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"write close:\", err)\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase <-doneCh:\n\t\t\tcase <-time.After(time.Second):\n\t\t\t}\n\t\t\tstop <- true\n\t\t\treturn nil\n\t\tcase <-doneCh:\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (f *httpForwarder) serveWebSocket(w http.ResponseWriter, req *http.Request, ctx *handlerContext) {\n\tif f.log.GetLevel() >= log.DebugLevel {\n\t\tlogEntry := f.log.WithField(\"Request\", utils.DumpHttpRequest(req))\n\t\tlogEntry.Debug(\"vulcand/oxy/forward/websocket: begin ServeHttp on request\")\n\t\tdefer logEntry.Debug(\"vulcand/oxy/forward/websocket: completed ServeHttp on request\")\n\t}\n\n\toutReq := f.copyWebSocketRequest(req)\n\n\ttargetConn, resp, err := f.websocketDialer.DialContext(outReq.Context(), outReq.URL.String(), outReq.Header)\n\tif err != nil {\n\t\tif resp == nil {\n\t\t\tctx.errHandler.ServeHTTP(w, req, err)\n\t\t} else {\n\t\t\tf.log.Errorf(\"vulcand/oxy/forward/websocket: Error dialing %q: %v with resp: %d %s\", outReq.Host, err, resp.StatusCode, resp.Status)\n\t\t\thijacker, ok := w.(http.Hijacker)\n\t\t\tif !ok {\n\t\t\t\tf.log.Errorf(\"vulcand/oxy/forward/websocket: %s can not be hijack\", reflect.TypeOf(w))\n\t\t\t\tctx.errHandler.ServeHTTP(w, req, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconn, _, errHijack := hijacker.Hijack()\n\t\t\tif errHijack != nil {\n\t\t\t\tf.log.Errorf(\"vulcand/oxy/forward/websocket: Failed to hijack responseWriter\")\n\t\t\t\tctx.errHandler.ServeHTTP(w, req, errHijack)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\tconn.Close()\n\t\t\t\tif f.websocketConnectionClosedHook != nil {\n\t\t\t\t\tf.websocketConnectionClosedHook(req, conn)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\terrWrite := resp.Write(conn)\n\t\t\tif errWrite != nil {\n\t\t\t\tf.log.Errorf(\"vulcand/oxy/forward/websocket: Failed to forward response\")\n\t\t\t\tctx.errHandler.ServeHTTP(w, req, errWrite)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\t// Only the targetConn choose to CheckOrigin or not\n\tupgrader := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool {\n\t\treturn true\n\t}}\n\n\tutils.RemoveHeaders(resp.Header, WebsocketUpgradeHeaders...)\n\tutils.CopyHeaders(resp.Header, w.Header())\n\n\tunderlyingConn, err := upgrader.Upgrade(w, req, resp.Header)\n\tif err != nil {\n\t\tf.log.Errorf(\"vulcand/oxy/forward/websocket: Error while upgrading connection : %v\", err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tunderlyingConn.Close()\n\t\ttargetConn.Close()\n\t\tif f.websocketConnectionClosedHook != nil {\n\t\t\tf.websocketConnectionClosedHook(req, underlyingConn.UnderlyingConn())\n\t\t}\n\t}()\n\n\terrClient := make(chan error, 1)\n\terrBackend := make(chan error, 1)\n\treplicateWebsocketConn := func(dst, src *websocket.Conn, errc chan error) {\n\n\t\tforward := func(messageType int, reader io.Reader) error {\n\t\t\twriter, err := dst.NextWriter(messageType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_, err = io.Copy(writer, reader)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn writer.Close()\n\t\t}\n\n\t\tsrc.SetPingHandler(func(data string) error {\n\t\t\tif err := forward(websocket.PingMessage, bytes.NewReader([]byte(data))); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn src.SetReadDeadline(time.Now().Add(f.websocketPongWait))\n\t\t})\n\n\t\tsrc.SetPongHandler(func(data string) error {\n\t\t\tif err := forward(websocket.PongMessage, bytes.NewReader([]byte(data))); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn src.SetReadDeadline(time.Now().Add(f.websocketPongWait))\n\t\t})\n\n\t\tfor {\n\n\t\t\tsrc.SetReadDeadline(time.Now().Add(f.websocketPongWait))\n\n\t\t\tmsgType, reader, err := src.NextReader()\n\n\t\t\tif err != nil {\n\t\t\t\tm := websocket.FormatCloseMessage(websocket.CloseNormalClosure, fmt.Sprintf(\"%v\", err))\n\t\t\t\tif e, ok := err.(*websocket.CloseError); ok {\n\t\t\t\t\tif e.Code != websocket.CloseNoStatusReceived {\n\t\t\t\t\t\tm = nil\n\t\t\t\t\t\t// Following codes are not valid on the wire so just close the\n\t\t\t\t\t\t// underlying TCP connection without sending a close frame.\n\t\t\t\t\t\tif e.Code != websocket.CloseAbnormalClosure &&\n\t\t\t\t\t\t\te.Code != websocket.CloseTLSHandshake {\n\n\t\t\t\t\t\t\tm = websocket.FormatCloseMessage(e.Code, e.Text)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\terrc <- err\n\t\t\t\tif m != nil {\n\t\t\t\t\tforward(websocket.CloseMessage, bytes.NewReader([]byte(m)))\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\terr = forward(msgType, reader)\n\t\t\tif err != nil {\n\t\t\t\terrc <- err\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tgo replicateWebsocketConn(underlyingConn, targetConn, errClient)\n\tgo replicateWebsocketConn(targetConn, underlyingConn, errBackend)\n\n\tvar message string\n\tselect {\n\tcase err = <-errClient:\n\t\tmessage = \"vulcand/oxy/forward/websocket: Error when copying from backend to client: %v\"\n\tcase err = <-errBackend:\n\t\tmessage = \"vulcand/oxy/forward/websocket: Error when copying from client to backend: %v\"\n\n\t}\n\tif e, ok := err.(*websocket.CloseError); !ok || e.Code == websocket.CloseAbnormalClosure {\n\t\tf.log.Errorf(message, err)\n\t}\n}", "func serveWs(w http.ResponseWriter, r *http.Request) {\r\n\t// fmt.Println(\"socket start!\")\r\n\tconn, err := upgrader.Upgrade(w, r, nil)\r\n\tif err != nil {\r\n\t\tlogger.Error(err.Error())\r\n\t\treturn\r\n\t}\r\n\tclient := &Client{conn: conn, send: make(chan []byte, 256), UID: 0}\r\n\t// client.hub.register <- client\r\n\r\n\t// Allow collection of memory referenced by the caller by doing all work in\r\n\t// new goroutines.\r\n\tgo client.writePump()\r\n\tgo client.readPump()\r\n}", "func (client *Client) ListenAndServe(record *ConnRecord, wsc []*WebSocketClient, address string, onConnected func()) error {\n\tnetListener, err := net.Listen(\"tcp\", address)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttcpl, ok := (netListener).(*net.TCPListener)\n\tif !ok {\n\t\treturn errors.New(\"not a tcp listener\")\n\t}\n\tclient.tcpl = tcpl\n\n\t// 在client刚启动,连上ws server以后要做的事\n\tonConnected()\n\tfor {\n\t\t// 先检查stop 如果已经被close 不再接收新请求\n\t\tselect {\n\t\tcase <-client.stop:\n\t\t\treturn StoppedError\n\t\tdefault:\n\t\t\t// if the channel is still open, continue as normal\n\t\t}\n\n\t\tc, err := tcpl.Accept()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"tcp accept error: %w\", err)\n\t\t}\n\n\t\tgo func() {\n\t\t\tconn := c.(*net.TCPConn)\n\t\t\t// defer c.Close()\n\t\t\tdefer conn.Close()\n\t\t\t// In reply, we can get proxy type, target address and first send data.\n\t\t\tfirstSendData, proxyType, addr, err := client.Reply(conn)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"reply error: \", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// 在client.Close中使用wait等待\n\t\t\tclient.wgClose.Add(1)\n\t\t\tdefer client.wgClose.Done()\n\n\t\t\tswitch proxyType {\n\t\t\tcase ProxyTypeSocks5:\n\t\t\t\tconn.Write([]byte{0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})\n\t\t\tcase ProxyTypeHttps:\n\t\t\t\tconn.Write([]byte(\"HTTP/1.0 200 Connection Established\\r\\nProxy-agent: wssocks\\r\\n\\r\\n\"))\n\t\t\t}\n\n\t\t\t// 更新输出区域的连接数据\n\t\t\trecord.Update(ConnStatus{IsNew: true, Address: addr, Type: proxyType})\n\t\t\tdefer record.Update(ConnStatus{IsNew: false, Address: addr, Type: proxyType})\n\n\t\t\t// 检查addr或addr的解析地址是不是私有地址等\n\t\t\tif checkAddrPrivite(addr) {\n\t\t\t\tif err := client.localVisit(conn, firstSendData, addr); err != nil {\n\t\t\t\t\tlog.Error(\"visit error: \", err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// 传输数据\n\t\t\t// on connection established, copy data now.\n\t\t\tif err := client.transData(wsc, conn, firstSendData, addr); err != nil {\n\t\t\t\tlog.Error(\"trans error: \", err)\n\t\t\t}\n\t\t}()\n\t}\n}", "func handleWebsocketEndpoint(w http.ResponseWriter, r *http.Request) {\n\tconn, _ := upgrader.Upgrade(w, r, nil) // error ignored for sake of simplicity\n\tfor {\n\t\t// Read message from client\n\t\tmsgType, msg, err := conn.ReadMessage()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// Print the message to the console\n\t\tfmt.Printf(\"%s sent: %s\\n\", conn.RemoteAddr(), string(msg))\n\n\t\t// Write message back to client\n\t\tif err = conn.WriteMessage(msgType, msg); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n}", "func serveWs(pool *websocket.Pool, w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"WebSocket Endpoint Hit\")\n\tconn, err := websocket.Upgrade(w, r)\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"%+v\\n\", err)\n\t}\n\n\tclient := &websocket.Client {\n\t\tConn: conn,\n\t\tPool: pool,\n\t}\n\n\tpool.Register <- client\n\tclient.Read()\n}", "func (s *Streamer) ConnectWS() error {\n\tscheme := \"wss\"\n\tif strings.HasPrefix(s.serverAddr, \"http://\") {\n\t\tscheme = \"ws\"\n\t}\n\n\thost := strings.Replace(strings.Replace(s.serverAddr, \"http://\", \"\", 1), \"https://\", \"\", 1)\n\turl := url.URL{Scheme: scheme, Host: host, Path: fmt.Sprintf(\"/ws/%s\", s.username)}\n\tlog.Printf(\"Openning socket at %s\", url.String())\n\n\tconn, _, err := websocket.DefaultDialer.Dial(url.String(), nil)\n\ts.conn = conn\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to connect to server\")\n\t}\n\n\t//Handle server ping\n\tconn.SetPingHandler(func(appData string) error {\n\t\treturn s.conn.WriteControl(websocket.PongMessage, emptyByteArray, time.Time{})\n\t})\n\n\t// Handle server ping\n\tconn.SetCloseHandler(func(code int, text string) error {\n\t\ts.Stop(\"Closed connection by server\")\n\t\treturn nil\n\t})\n\n\t// send client info so server can verify\n\tclientInfo := message.ClientInfo{\n\t\tName: s.username,\n\t\tRole: message.RStreamer,\n\t\tSecret: s.secret,\n\t}\n\n\tpayload := message.Wrapper{\n\t\tType: message.TClientInfo,\n\t\tData: clientInfo,\n\t}\n\terr = conn.WriteJSON(payload)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to connect to server\")\n\t}\n\n\t// Verify server's response\n\tmsg := message.Wrapper{}\n\terr = conn.ReadJSON(&msg)\n\tif msg.Type == message.TStreamerUnauthorized {\n\t\treturn fmt.Errorf(\"Unauthorized connection\")\n\t} else if msg.Type != message.TStreamerAuthorized {\n\t\treturn fmt.Errorf(\"Expect connect confirmation from server\")\n\t}\n\treturn nil\n}", "func serveWs(w http.ResponseWriter, r *http.Request) {\n\n\t// only GET requests can be upgraded\n\tif r.Method != \"GET\" {\n\t\t// return http response code 405\n\t\thttp.Error(w, \"Method not allowed\", 405)\n\t\treturn\n\t}\n\n\t// upgrade connection\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tl.Error.Println(err)\n\t\treturn\n\t}\n\n\t// if connection was upgraded\n\t// create new instance of client,\n\t// register it with the hub and\n\t// launch coroutines for reading and writting\n\tc := NewClient(ws)\n\n\th.register <- c\n\tgo c.writePump()\n\tc.readPump()\n}", "func (c *Client) websocket(endpoint string, q *QueryOptions) (*websocket.Conn, *http.Response, error) {\n\n\ttransport, ok := c.httpClient.Transport.(*http.Transport)\n\tif !ok {\n\t\treturn nil, nil, fmt.Errorf(\"unsupported transport\")\n\t}\n\tdialer := websocket.Dialer{\n\t\tReadBufferSize: 4096,\n\t\tWriteBufferSize: 4096,\n\t\tHandshakeTimeout: c.httpClient.Timeout,\n\n\t\t// values to inherit from http client configuration\n\t\tNetDial: transport.Dial,\n\t\tNetDialContext: transport.DialContext,\n\t\tProxy: transport.Proxy,\n\t\tTLSClientConfig: transport.TLSClientConfig,\n\t}\n\n\t// build request object for header and parameters\n\tr, err := c.newRequest(\"GET\", endpoint)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tr.setQueryOptions(q)\n\n\trhttp, err := r.toHTTP()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// convert scheme\n\twsScheme := \"\"\n\tswitch rhttp.URL.Scheme {\n\tcase \"http\":\n\t\twsScheme = \"ws\"\n\tcase \"https\":\n\t\twsScheme = \"wss\"\n\tdefault:\n\t\treturn nil, nil, fmt.Errorf(\"unsupported scheme: %v\", rhttp.URL.Scheme)\n\t}\n\trhttp.URL.Scheme = wsScheme\n\n\tconn, resp, err := dialer.Dial(rhttp.URL.String(), rhttp.Header)\n\n\t// check resp status code, as it's more informative than handshake error we get from ws library\n\tif resp != nil && resp.StatusCode != 101 {\n\t\tvar buf bytes.Buffer\n\n\t\tif resp.Header.Get(\"Content-Encoding\") == \"gzip\" {\n\t\t\tgreader, err := gzip.NewReader(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"Unexpected response code: %d\", resp.StatusCode)\n\t\t\t}\n\t\t\tio.Copy(&buf, greader)\n\t\t} else {\n\t\t\tio.Copy(&buf, resp.Body)\n\t\t}\n\t\tresp.Body.Close()\n\n\t\treturn nil, nil, fmt.Errorf(\"Unexpected response code: %d (%s)\", resp.StatusCode, buf.Bytes())\n\t}\n\n\treturn conn, resp, err\n}", "func wsProxyDial(url_, protocol, origin string) (ws *websocket.Conn, err error) {\n\n\tlog.Printf(\"[%s] http_proxy {%s}\\n\", __FILE__, os.Getenv(\"http_proxy\"))\n\n\t// comment out in case of testing without proxy(internal server)\n\tif strings.Contains(url_, \"10.113.\") {\n\t\treturn websocket.Dial(url_, protocol, origin)\n\t}\n\n\tif os.Getenv(\"http_proxy\") == \"\" {\n\t\treturn websocket.Dial(url_, protocol, origin)\n\t}\n\n\tpurl, err := url.Parse(os.Getenv(\"http_proxy\"))\n\tif err != nil {\n\t\tlog.Printf(\"[%s] Parse : \", __FILE__, err)\n\t\treturn nil, err\n\t}\n\n\tlog.Printf(\"====================================\")\n\tlog.Printf(\" websocket.NewConfig\")\n\tlog.Printf(\"====================================\")\n\tconfig, err := websocket.NewConfig(url_, origin)\n\tif err != nil {\n\t\tlog.Printf(\"[%s] NewConfig : \", __FILE__, err)\n\t\treturn nil, err\n\t}\n\n\tif protocol != \"\" {\n\t\tconfig.Protocol = []string{protocol}\n\t}\n\n\tlog.Printf(\"====================================\")\n\tlog.Printf(\" HttpConnect\")\n\tlog.Printf(\"====================================\")\n\tclient, err := wsHttpConnect(purl.Host, url_)\n\tif err != nil {\n\t\tlog.Printf(\"[%s] HttpConnect : \", __FILE__, err)\n\t\treturn nil, err\n\t}\n\n\tlog.Printf(\"====================================\")\n\tlog.Printf(\" websocket.NewClient\")\n\tlog.Printf(\"====================================\")\n\n\tret_ws, err := websocket.NewClient(config, client)\n\tif err != nil {\n\t\tlog.Printf(\"[%s] NewCliet error : \", __FILE__, err)\n\t}\n\n\treturn ret_ws, err\n}", "func handleConnections(w http.ResponseWriter, r *http.Request) {\n\tws, err := upgrader.Upgrade(w, r, nil) // upgrade get to websocket\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer ws.Close() // close connection when function returns\n\n\tclients[ws] = true // register client\n\n\tfor {\n\t\tvar msg Message\n\t\terr := ws.ReadJSON(&msg)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error: %v\", err)\n\t\t\tdelete(clients, ws)\n\t\t\tbreak\n\t\t}\n\t\tbroadcast <- msg // broadcast message\n\t}\n}", "func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn\n\t}\n\tclient := &Client{hub: hub, conn: conn, send: make(chan []byte, 256)}\n\tclient.hub.register <- client\n\tgo client.writePump()\n\tclient.readPump()\n}", "func (w *BaseWebsocketClient) OnConnect(conn *websocket.Conn, r *http.Response) {\n\tw.Conn = conn\n}", "func (o *Server) WS(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"A user is connecting...\")\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.Println(\"Warn: Something wrong. Recovered in \", r)\n\t\t}\n\t}()\n\n\t// be aware of ReadBufferSize, WriteBufferSize (default 4096)\n\t// https://pkg.go.dev/github.com/gorilla/websocket?tab=doc#Upgrader\n\tc, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(\"Coordinator: [!] WS upgrade:\", err)\n\t\treturn\n\t}\n\n\t// Generate sessionID for browserClient\n\tvar sessionID string\n\tfor {\n\t\tsessionID = uuid.Must(uuid.NewV4()).String()\n\t\t// check duplicate\n\t\tif _, ok := o.clients[sessionID]; !ok {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Create browserClient instance\n\tclient := NewClient(c, sessionID)\n\t// Run browser listener first (to capture ping)\n\tgo func(client *Client) {\n\t\tclient.Listen()\n\t\tdelete(o.clients, client.SessionID)\n\t}(client)\n}", "func (s *server) wsHandler(ws *websocket.Conn) {\n\t// If the client initially attempts to connect directly using\n\t// WebSocket transport, the session ID parameter will be empty.\n\t// Otherwise, the connection with the given session ID will\n\t// need to be upgraded.\n\tglog.Infoln(\"Starting websocket handler...\")\n\tvar c *conn\n\twsEncoder, wsDecoder := newPacketEncoder(ws), newPacketDecoder(ws)\n\tfor {\n\t\tif c != nil {\n\t\t\tvar pkt packet\n\t\t\tif err := wsDecoder.decode(&pkt); err != nil {\n\t\t\t\tglog.Errorf(\"could not decode packet: %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tglog.Infof(\"WS: got packet type: %c, data: %s\", pkt.typ, pkt.data)\n\t\t\tif pkt.typ == packetTypeUpgrade {\n\t\t\t\t// Upgrade the connection to use this WebSocket Conn.\n\t\t\t\tc.upgrade(ws)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := s.handlePacket(pkt, c); err != nil {\n\t\t\t\tglog.Errorf(\"could not handle packet: %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tid := ws.Request().FormValue(paramSessionID)\n\t\tc = s.clients.get(id)\n\t\tif len(id) > 0 && c == nil {\n\t\t\tserverError(ws, errorUnknownSID)\n\t\t\tbreak\n\t\t} else if len(id) > 0 && c != nil {\n\t\t\t// The initial handshake requires a ping (2) and pong (3) echo.\n\t\t\tvar pkt packet\n\t\t\tif err := wsDecoder.decode(&pkt); err != nil {\n\t\t\t\tglog.Errorf(\"could not decode packet: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tglog.Infof(\"WS: got packet type: %c, data: %s\", pkt.typ, pkt.data)\n\t\t\tif pkt.typ == packetTypePing {\n\t\t\t\tglog.Infof(\"got ping packet with data %s\", pkt.data)\n\t\t\t\tif err := wsEncoder.encode(packet{typ: packetTypePong, data: pkt.data}); err != nil {\n\t\t\t\t\tglog.Errorf(\"could not encode pong packet: %v\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// Force a polling cycle to ensure a fast upgrade.\n\t\t\t\tglog.Infoln(\"forcing polling cycle\")\n\t\t\t\tpayload := []packet{packet{typ: packetTypeNoop}}\n\t\t\t\tif err := newPayloadEncoder(c).encode(payload); err != nil {\n\t\t\t\t\tglog.Errorf(\"could not encode packet to force polling cycle: %v\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t} else if len(id) == 0 && c == nil {\n\t\t\t// Create a new connection with this WebSocket Conn.\n\t\t\tc = newConn()\n\t\t\tc.ws = ws\n\t\t\ts.clients.add(c)\n\t\t\tb, err := handshakeData(c)\n\t\t\tif err != nil {\n\t\t\t\tglog.Errorf(\"could not get handshake data: %v\", err)\n\t\t\t}\n\t\t\tif err := wsEncoder.encode(packet{typ: packetTypeOpen, data: b}); err != nil {\n\t\t\t\tglog.Errorf(\"could not encode open packet: %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif s.Handler != nil {\n\t\t\t\tgo s.Handler(c.pubConn)\n\t\t\t}\n\t\t}\n\t}\n\tglog.Infof(\"closing websocket connection %p\", ws)\n\tc.Close()\n}", "func wsHandler(w http.ResponseWriter, r *http.Request) {\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"New client connected\")\n\tclients[ws] = true\n}", "func connect() *websocket.Conn {\n\turl := url.URL{Scheme: \"ws\", Host: *addr, Path: \"/ws\"}\n\tlog.Info(\"Connecting to \", url.String())\n\tconn, _, err := dialer.Dial(url.String(), nil)\n\tcheckError(err)\n\tlog.Info(\"Connected to \", url.String())\n\n\t// Read the message from server with deadline of ResponseWait(30) seconds\n\tconn.SetReadDeadline(time.Now().Add(utils.ResponseWait * time.Second))\n\n\treturn conn\n}", "func startDialWebsocket(try *parallel.Try, addr, path string, opts DialOpts) error {\n\t// origin is required by the WebSocket API, used for \"origin policy\"\n\t// in websockets. We pass localhost to satisfy the API; it is\n\t// inconsequential to us.\n\tconst origin = \"http://localhost/\"\n\t//cfg, err := websocket.NewConfig(\"wss://\"+addr+path, origin)\n\tcfg, err := websocket.NewConfig(\"ws://\"+addr+path, origin)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\treturn try.Start(newWebsocketDialer(cfg, opts))\n}", "func WsEndPoint(w http.ResponseWriter, r *http.Request) {\n\tws, err := upgradeConnection.Upgrade(w, r, nil) // we aren't going to worry about the response header right now\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tlog.Println(\"Client connected to endpoint\")\n\n\t// send back a response back to the client using JSON so it is easy to parse\n\tvar response WSJSONResponse\n\tresponse.Message = `<em><small>Connected to Server</small></em>`\n\n\t// when someone new joins the chatroom, add them to the clients map\n\tconn := WebSocketConnection{Conn: ws}\n\tclients[conn] = \"\" // initialize with 0 clients connected\n\n\terr = ws.WriteJSON(response)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\t// take everyone who is in our clients map and put them in a new goroutine\n\t// goroutines always start with the go keyword\n\tgo ListenForWS(&conn)\n}", "func WebsocketChl(hub *Hub, w http.ResponseWriter, r *http.Request) {\n\tclientIP := utils.IPAddress(r)\n\n\tconn, err := Upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tklog.Error(err)\n\t\treturn\n\t}\n\tclient := &Client{Hub: hub, Conn: conn, Send: make(chan []byte, 256), IPAddress: clientIP, Accounts: []string{}}\n\tclient.Hub.Register <- client\n\n\t// Allow collection of memory referenced by the caller by doing all work in\n\t// new goroutines.\n\tgo client.writePump()\n\tgo client.readPump()\n}", "func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request) (*Conn, error) {\n\tif !tokenListContainsValue(r.Header, \"Connection\", \"upgrade\") {\n\t\treturn nil, fmt.Errorf(\"'upgrade' token not found in 'Connection' header\")\n\t}\n\n\tif !tokenListContainsValue(r.Header, \"Upgrade\", \"websocket\") {\n\t\treturn nil, fmt.Errorf(\"'websocket' token not found in 'Upgrade' header\")\n\t}\n\n\tif r.Method != \"GET\" {\n\t\treturn nil, fmt.Errorf(\"request method is not GET\")\n\t}\n\n\tif !tokenListContainsValue(r.Header, \"Sec-Websocket-Version\", \"13\") {\n\t\treturn nil, fmt.Errorf(\"websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header\")\n\t}\n\n\th, ok := w.(http.Hijacker)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"websocket: response does not implement http.Hijacker\")\n\t}\n\n\tvar brw *bufio.ReadWriter\n\tnetConn, brw, err := h.Hijack()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif brw.Reader.Buffered() > 0 {\n\t\tnetConn.Close()\n\t\treturn nil, fmt.Errorf(\"websocket: client sent data before handshake is complete\")\n\t}\n\n\tc := newConn(netConn)\n\n\tchallengeKey := r.Header.Get(\"Sec-Websocket-Key\")\n\tif challengeKey == \"\" {\n\t\tnetConn.Close()\n\t\treturn nil, fmt.Errorf(\"websocket: not a websocket handshake: 'Sec-WebSocket-Key' header is missing or blank\")\n\t}\n\n\tvar p []byte = nil\n\tp = append(p, \"HTTP/1.1 101 Switching Protocols\\r\\nUpgrade: websocket\\r\\nConnection: Upgrade\\r\\nSec-WebSocket-Accept: \"...)\n\tp = append(p, computeAcceptKey(challengeKey)...)\n\tp = append(p, \"\\r\\n\"...)\n\tp = append(p, \"\\r\\n\"...)\n\n\t// Clear deadlines set by HTTP server.\n\tnetConn.SetDeadline(time.Time{})\n\n\tif _, err = netConn.Write(p); err != nil {\n\t\tnetConn.Close()\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}", "func establishSocketConn(w http.ResponseWriter, r *http.Request, ut string) {\n\tc, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Warn(\"upgrade:\", err)\n\t\treturn\n\t}\n\tsocketConnMap[ut] = c\n\tlog.Info(\"new socket conn:\", ut)\n\tdefer c.Close()\n\tdefer delete(socketConnMap, ut)\n\tfor {\n\t\t_, message, err := c.ReadMessage()\n\t\tif err != nil {\n\t\t\tlog.Warn(\"read:\", err)\n\t\t\tbreak\n\t\t}\n\t\tlog.Debug(\"rec: %s\", message)\n\t\tgo handlerMsg(message)\n\t}\n}", "func connectToHost(ctx context.Context, tc *client.TeleportClient, webSession *webSession, host string) (io.ReadWriteCloser, error) {\n\treq := web.TerminalRequest{\n\t\tServer: host,\n\t\tLogin: tc.HostLogin,\n\t\tTerm: session.TerminalParams{\n\t\t\tW: 100,\n\t\t\tH: 100,\n\t\t},\n\t}\n\n\tdata, err := json.Marshal(req)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tu := url.URL{\n\t\tHost: tc.WebProxyAddr,\n\t\tScheme: client.WSS,\n\t\tPath: fmt.Sprintf(\"/v1/webapi/sites/%v/connect\", tc.SiteName),\n\t\tRawQuery: url.Values{\n\t\t\t\"params\": []string{string(data)},\n\t\t\troundtrip.AccessTokenQueryParam: []string{webSession.getToken()},\n\t\t}.Encode(),\n\t}\n\n\tdialer := websocket.Dialer{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: tc.InsecureSkipVerify},\n\t\tJar: webSession.getCookieJar(),\n\t}\n\n\tws, resp, err := dialer.DialContext(ctx, u.String(), http.Header{\n\t\t\"Origin\": []string{\"http://localhost\"},\n\t})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tdefer resp.Body.Close()\n\n\tty, _, err := ws.ReadMessage()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tif ty != websocket.BinaryMessage {\n\t\treturn nil, trace.BadParameter(\"unexpected websocket message received %d\", ty)\n\t}\n\n\tstream := web.NewTerminalStream(ctx, ws, utils.NewLogger())\n\treturn stream, trace.Wrap(err)\n}", "func (a *API) Upgrade(w http.ResponseWriter, req *http.Request) {\n\tif req.Method != \"GET\" {\n\t\thttp.Error(w, \"Method not allowed\", 405)\n\t\treturn\n\t}\n\tif req.Header.Get(\"Origin\") != \"http://\"+req.Host {\n\t\thttp.Error(w, \"Origin not allowed\", 403)\n\t\treturn\n\t}\n\t// Create a net.Conn from the websocket\n\tconn, err := websocket.NewConn(w, req, req.Header, 4096, 4096)\n\tif err != nil {\n\t\t// TODO(inhies): Figure out a way to return an error from this\n\t\tfmt.Println(\"error getting websocket conn:\", err)\n\t\treturn\n\t}\n\n\t// Send this connection to our STOMP server\n\ta.listener <- conn\n}", "func serveWs(w http.ResponseWriter, req *http.Request) {\n\tfmt.Println(\"Registering client to WS\")\n\tif req.Method != \"GET\" {\n\t\thttp.Error(w, \"Method not allowed\", 405)\n\t\treturn\n\t}\n\tws, err := upgrader.Upgrade(w, req, nil)\n\tif err != nil {\n\t\tfmt.Printf(\"Error %+v\\n\", err)\n\t\treturn\n\t}\n\tc := &connection{send: make(chan []byte, 256), ws: ws}\n\th.register <- c\n\tgo c.writePump()\n}", "func handshake(conn net.Conn, validUri string) (res http.Response, retErr error) {\n var b64ConnKey string\n\n // Properly set the status code text on exit\n defer func() {\n res.Status = http.StatusText(res.StatusCode)\n }()\n\n // Set initial response, just in case...\n res.StatusCode = http.StatusForbidden\n res.Proto = \"HTTP/1.0\"\n res.ProtoMajor = 1\n res.ProtoMinor = 0\n\n req, err := http.ReadRequest(bufio.NewReader(conn))\n if err != nil {\n retErr = errors.Wrap(err, \"Failed to receive client handshake\")\n return\n }\n\n res.Proto = req.Proto\n res.ProtoMajor = req.ProtoMajor\n res.ProtoMinor = req.ProtoMinor\n\n // 4.2.1 Reading the Client's Opening Handshake\n\n // 1. Check that it's a HTTP/1.1 or higher GET\n // (ignore \"Request-URI\" but check its presence)\n if !strings.HasPrefix(req.Proto, \"HTTP/\") {\n retErr = errors.New(fmt.Sprintf(\"Non HTTP request: '%s'\", req.Proto))\n return\n } else if req.ProtoMajor == 1 && req.ProtoMinor < 1 ||\n req.ProtoMajor < 1 {\n\n retErr = errors.New(\"Non HTTP/1.1 or higher\")\n return\n } else if req.Method != \"GET\" {\n retErr = errors.New(\"Non GET request\")\n return\n } else if req.RequestURI == \"\" {\n retErr = errors.New(\"Missing RequestURI in request\")\n return\n } else if req.RequestURI != validUri {\n retErr = errors.New(\"Invalid RequestURI\")\n return\n }\n\n // 2. Check for a |Host| header with server's authority\n if host := req.Header.Get(\"Host\"); len(host) == 0 {\n retErr = errors.New(\"Missing |Host| header field\")\n if Strict {\n return\n } else {\n fmt.Printf(\" Ignoring: %s\\n\", retErr.Error())\n retErr = nil\n }\n }\n\n // 3. Check for an |Upgrade| header == \"websocket\"\n if want, got := \"websocket\", req.Header.Get(\"Upgrade\"); want != got {\n retErr = errors.New(fmt.Sprintf(\n \"Invalid |Upgrade| header field: wanted '%s', got '%s'\\n\",\n want, got))\n return\n }\n\n // 4. Check for a |Connection| header == \"Upgrade\"\n if want, got := \"Upgrade\", req.Header.Get(\"Connection\"); !strings.Contains(got, want) {\n retErr = errors.New(fmt.Sprintf(\n \"Invalid |Connection| header field: wanted '%s', got '%s'\\n\",\n want, got))\n return\n }\n\n // 5. Check for a |Sec-WebSocket-Key| with the base-64 key\n if b64ConnKey = req.Header.Get(\"Sec-WebSocket-Key\"); len(b64ConnKey) == 0{\n retErr = errors.New(\"Missing |Sec-WebSocket-Key| header field\")\n return\n }\n\n // 6..10 are optional (and, therefore, ignored)\n\n // 4.2.2 Sending the Server's Opening Handshake\n\n res.Header = make (http.Header)\n\n // 1. Connection isn't HTTPS, so ignore it\n // 2. Stuff that the server can do... ignore (as it isn't a MUST)\n // 3. \"The server MAY...\": NOPE\n // 4. Maybe later\n\n // 5. Set fields required to accept the connection\n\n // 5.1 Set status as Switching Protocols\n res.StatusCode = http.StatusSwitchingProtocols\n\n // 5.2 Set |Upgrade| = \"websocket\"\n res.Header.Set(\"Upgrade\", \"websocket\")\n\n // 5.3 Set |Connection| = \"Upgrade\"\n res.Header.Set(\"Connection\", \"Upgrade\")\n\n // 5.4 Set |Sec-WebSocket-Accept| with the base_64(SHA_1(key+UIGD))\n serverKey := calculateServerResponseKey(b64ConnKey)\n res.Header.Set(\"Sec-WebSocket-Accept\", serverKey)\n\n // 5.5 Later\n // 5.6 Later\n\n return\n}", "func (c *Notification2Client) connect() error {\n\tif c.dialer == nil {\n\t\tpanic(\"Missing dialer for realtime client\")\n\t}\n\tws, err := c.createWebsocket()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.mtx.Lock()\n\tdefer c.mtx.Unlock()\n\n\tc.ws = ws\n\tif c.tomb == nil {\n\t\tc.tomb = &tomb.Tomb{}\n\t\tc.tomb.Go(c.worker)\n\t}\n\tc.connected = true\n\n\treturn nil\n}", "func socketHandler(ws *websocket.Conn) {\n\tvar err error\n\tfor {\n\t\tvar reply string\n\n\t\tif err = websocket.Message.Receive(ws, &reply); err != nil {\n\t\t\tfmt.Println(\"Can't receive\")\n\t\t\tbreak\n\t\t}\n\n\t\tif debug {\n\t\t\tfmt.Println(\"Received from client: \" + reply)\n\t\t}\n\n\t\t// Json decode\n\t\tvar req = AOWRequest{}\n\t\tif err := json.Unmarshal([]byte(reply), &req); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t// Get client from pool\n\t\tpclient := clientPool.Get().(*http.Client)\n\n\t\t// Prepare request\n\t\tpreq, perr := http.NewRequest(req.Method, fmt.Sprintf(\"%s\", req.URI), nil)\n\t\tfor k, v := range req.Headers {\n\t\t\tpreq.Header.Add(k, v)\n\t\t}\n\t\tpresp, perr := pclient.Do(preq)\n\t\tif perr != nil {\n\t\t\tlog.Printf(\"%s\\n\", perr)\n\n\t\t\t// Return client to pool\n\t\t\tclientPool.Put(pclient)\n\t\t\treturn\n\t\t}\n\t\tdefer presp.Body.Close()\n\t\tbody, readErr := ioutil.ReadAll(presp.Body)\n\t\tif readErr != nil {\n\t\t\tlog.Printf(\"%s\\n\", readErr)\n\t\t}\n\n\t\t// Response wrapper\n\t\tvar resp = AOWResponse{}\n\t\tresp.Id = req.Id\n\t\tresp.Text = string(body)\n\t\tresp.Status = presp.StatusCode\n\t\tresp.Headers = presp.Header\n\t\trespBytes, jErr := json.Marshal(resp)\n\t\tif jErr != nil {\n\t\t\tpanic(jErr)\n\t\t}\n\n\t\t// Return client to pool\n\t\tclientPool.Put(pclient)\n\n\t\t// Msg\n\t\tmsg := string(respBytes)\n\n\t\t// Send to client\n\t\tif debug {\n\t\t\tfmt.Println(\"Sending to client: \" + msg)\n\t\t}\n\t\tif err = websocket.Message.Send(ws, msg); err != nil {\n\t\t\tfmt.Println(\"Can't send\")\n\t\t\tbreak\n\t\t}\n\t}\n}", "func handleWebsocket(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"GET\" {\n\t\thttp.Error(w, \"Niedozwolona metoda\", 405)\n\t\treturn\n\t}\n\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.WithField(\"err\", err).Println(\"Przejście do Websocket\")\n\t\thttp.Error(w, \"Error Upgrading to websockets\", 400)\n\t\treturn\n\t}\n\n\tid := rr.register(ws)\n\n\tfor {\n\t\tmt, data, err := ws.ReadMessage()\n\t\tctx := log.Fields{\"mt\": mt, \"data\": data, \"err\": err}\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tlog.WithFields(ctx).Info(\"Połączenie websocket zamknięte\")\n\t\t\t} else {\n\t\t\t\tlog.WithFields(ctx).Error(\"Błąd odczytu wiadomości websocket\")\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tswitch mt {\n\t\tcase websocket.TextMessage:\n\t\t\tmsg, err := validateMessage(data)\n\t\t\tif err != nil {\n\t\t\t\tctx[\"msg\"] = msg\n\t\t\t\tctx[\"err\"] = err\n\t\t\t\tlog.WithFields(ctx).Error(\"Niepoprawna wiadomość\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\trw.publish(data)\n\t\tdefault:\n\t\t\tlog.WithFields(ctx).Warning(\"Nieznana wiadomość\")\n\t\t}\n\t}\n\n\trr.deRegister(id)\n\n\tws.WriteMessage(websocket.CloseMessage, []byte{})\n}", "func connectWS(host string, port int) (*websocket.Conn, error) {\n\turl := fmt.Sprintf(\"ws://%s:%d\", host, port)\n\tLogger.Println(\"connecting to\", url)\n\tconn, _, err := websocket.DefaultDialer.Dial(url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn conn, nil\n}", "func NewClient(netConn net.Conn, host, path string, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error) {\n\tchallengeKey, err := generateChallengeKey()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tacceptKey := computeAcceptKey(challengeKey)\n\n\tc = newConn(netConn, false, readBufSize, writeBufSize)\n\tp := c.writeBuf[:0]\n\tp = append(p, \"GET \"...)\n\tp = append(p, path...)\n\tp = append(p, \" HTTP/1.1\\r\\nHost: \"...)\n\tp = append(p, host...)\n\t// \"Upgrade\" is capitalized for servers that do not use case insensitive\n\t// comparisons on header tokens.\n\tp = append(p, \"\\r\\nUpgrade: websocket\\r\\nConnection: Upgrade\\r\\nSec-WebSocket-Version: 13\\r\\nSec-WebSocket-Key: \"...)\n\tp = append(p, challengeKey...)\n\tp = append(p, \"\\r\\n\"...)\n\tfor k, vs := range requestHeader {\n\t\tfor _, v := range vs {\n\t\t\tp = append(p, k...)\n\t\t\tp = append(p, \": \"...)\n\t\t\tp = append(p, v...)\n\t\t\tp = append(p, \"\\r\\n\"...)\n\t\t}\n\t}\n\tp = append(p, \"\\r\\n\"...)\n\n\tif _, err := netConn.Write(p); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tu := &url.URL{Scheme: \"ws\", Host: host, Path: path}\n\tresp, err := http.ReadResponse(c.br, &http.Request{Method: \"GET\", URL: u})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif resp.StatusCode != 101 ||\n\t\t!strings.EqualFold(resp.Header.Get(\"Upgrade\"), \"websocket\") ||\n\t\t!strings.EqualFold(resp.Header.Get(\"Connection\"), \"upgrade\") ||\n\t\tresp.Header.Get(\"Sec-Websocket-Accept\") != acceptKey {\n\t\treturn nil, resp, ErrBadHandshake\n\t}\n\tc.subprotocol = resp.Header.Get(\"Sec-Websocket-Protocol\")\n\treturn c, resp, nil\n}", "func connectWS(host string, port int) (*websocket.Conn, error) {\n\turl := fmt.Sprintf(\"ws://%s:%d\", host, port)\n\tglobal.LOG.Info(\"connecting to\", zap.String(\"url\", url))\n\tconn, _, err := websocket.DefaultDialer.Dial(url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn conn, nil\n}", "func (g *Gemini) WsConnect() error {\n\tif !g.Websocket.IsEnabled() || !g.IsEnabled() {\n\t\treturn errors.New(stream.WebsocketNotEnabled)\n\t}\n\n\tvar dialer websocket.Dialer\n\terr := g.Websocket.Conn.Dial(&dialer, http.Header{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tg.Websocket.Wg.Add(2)\n\tgo g.wsReadData()\n\tgo g.wsFunnelConnectionData(g.Websocket.Conn)\n\n\tif g.Websocket.CanUseAuthenticatedEndpoints() {\n\t\terr := g.WsAuth(context.TODO(), &dialer)\n\t\tif err != nil {\n\t\t\tlog.Errorf(log.ExchangeSys, \"%v - websocket authentication failed: %v\\n\", g.Name, err)\n\t\t\tg.Websocket.SetCanUseAuthenticatedEndpoints(false)\n\t\t}\n\t}\n\treturn nil\n}", "func handleConnections(w http.ResponseWriter, r *http.Request) {\n\t// Upgrade initial GET request to a websocket\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// Make sure we close the connection when the function returns\n\tdefer ws.Close()\n\n\t// Register our new client\n\tclients[ws] = true\n\n\tfor {\n\t\tvar msg Message\n\t\t// Read in a new message as JSON and map it to a Message object\n\t\terr := ws.ReadJSON(&msg)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error: %v\", err)\n\t\t\tdelete(clients, ws)\n\t\t\tbreak\n\t\t}\n\t\t// If the username not null, store the sent message\n\t\tif msg.Username != \"\" {\n\t\t\tstoreMessage(msg)\n\t\t}\n\t\t// Send the newly received message to the broadcast channel\n\t\tbroadcast <- msg\n\t}\n}", "func (by *Bybit) WsConnect() error {\n\tif !by.Websocket.IsEnabled() || !by.IsEnabled() || !by.IsAssetWebsocketSupported(asset.Spot) {\n\t\treturn errors.New(stream.WebsocketNotEnabled)\n\t}\n\tvar dialer websocket.Dialer\n\terr := by.Websocket.Conn.Dial(&dialer, http.Header{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tby.Websocket.Conn.SetupPingHandler(stream.PingHandler{\n\t\tMessageType: websocket.TextMessage,\n\t\tMessage: []byte(`{\"op\":\"ping\"}`),\n\t\tDelay: bybitWebsocketTimer,\n\t})\n\n\tby.Websocket.Wg.Add(1)\n\tgo by.wsReadData(by.Websocket.Conn)\n\tif by.IsWebsocketAuthenticationSupported() {\n\t\terr = by.WsAuth(context.TODO())\n\t\tif err != nil {\n\t\t\tby.Websocket.DataHandler <- err\n\t\t\tby.Websocket.SetCanUseAuthenticatedEndpoints(false)\n\t\t}\n\t}\n\n\tby.Websocket.Wg.Add(1)\n\tgo by.WsDataHandler()\n\treturn nil\n}", "func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tclient := &Client{hub: hub, conn: conn, send: make(chan []byte, 256)}\n\tclient.hub.register <- client\n\n\t// Allow collection of memory referenced by the caller by doing all work in\n\t// new goroutines.\n\tgo client.writePump()\n\tgo client.readPump()\n}", "func (c *GatewayClient) connect() error {\n\tif !c.ready {\n\t\treturn errors.New(\"already tried to connect and failed\")\n\t}\n\n\tc.ready = false\n\tc.resuming = false\n\tc.heartbeatAcknowledged = true\n\tc.lastIdentify = time.Time{}\n\n\tc.Logf(\"connecting\")\n\t// TODO Need to set read deadline for hello packet and I also need to set write deadlines.\n\t// TODO also max message\n\tvar err error\n\tc.wsConn, _, err = websocket.DefaultDialer.Dial(c.GatewayURL, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo c.manager()\n\n\treturn nil\n}", "func handleConnections(w http.ResponseWriter, r *http.Request){\r\n\t// upgrade initial GET request to a websocket\r\n\tws, err := upgrader.Upgrade(w, r, nil)\r\n\r\n\tif err != nil{\r\n\t\tlog.Fatal(err)\r\n\t}\r\n\r\n\t// make sure to close the connection when function returns\r\n\tdefer ws.Close()\r\n\r\n\t// register new client\r\n\tclients[ws] = true\r\n\r\n\t// infinite loop to wait for new messages\r\n\tfor{\r\n\t\tvar msg Message\r\n\r\n\t\t// read in a new message as a JSON and map it to a Message object\r\n\t\terr := ws.ReadJSON(&msg)\r\n\r\n\t\t// if error occurs: assume client has disconnected, remove, and end \r\n\t\tif err != nil{\r\n\t\t\tlog.Println(\"@ handleConnections()\");\r\n\t\t\tlog.Printf(\"error: %v\", err)\r\n\t\t\tdelete(clients, ws)\r\n\t\t\tbreak\r\n\t\t}\r\n\r\n\t\t// send newly received message to the broadcast channel\r\n\t\tbroadcast <- msg\r\n\t}\r\n}", "func wsEndpoint(w http.ResponseWriter, r *http.Request) {\n\tupgrader.CheckOrigin = func(r *http.Request) bool { return true }\n\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tlog.Println(\"Client connected sucessfully...\")\n\treader(ws)\n}", "func (HelloSocket) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tconn, err := websocket.Upgrade(w, r, nil, 1024, 1024)\n\tif err != nil {\n\t\tlog.Println(\"/hellosocket websocket upgrade failed.\")\n\t\treturn\n\t}\n\n\tlog.Println(\"Client connected.\")\n\treader(conn)\n\n}", "func (a *App) serveWs(pool *Pool, w http.ResponseWriter, r *http.Request) {\n\tfmt.Printf(r.Host)\n\tconn, err := upgrade(w, r)\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tclient := &Client{\n\t\tConn: conn,\n\t\tPool: pool,\n\t}\n\n\tpool.Register <- client\n\tclient.read(a)\n\tfmt.Printf(\"Client Connected\")\n}", "func connectHandler(ca *pki.CA, hub *chat.Hub) http.HandlerFunc {\n\treturn func(res http.ResponseWriter, req *http.Request) {\n\t\t// Verify header is present\n\t\tif req.Header.Get(\"X-user-certificate\") == \"\" {\n\t\t\tlog.Println(\"missing user certificate\")\n\t\t\treturn\n\t\t}\n\n\t\t// Decode header\n\t\tcert, err := base64.StdEncoding.DecodeString(req.Header.Get(\"X-user-certificate\"))\n\t\tif err != nil {\n\t\t\tlog.Println(\"failed to decode provided certificate\")\n\t\t\treturn\n\t\t}\n\n\t\t// Validate certificate\n\t\tif err = ca.VerifyCertificate(cert, &pki.VerifyOptions{ProfileName: \"user\"}); err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t// Establish socket connection\n\t\tserveWS(hub, res, req)\n\t}\n}", "func wsHandler(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tchannel := params[\"channel\"]\n\tclientServer := params[\"clientServer\"]\n\n\tvar fromServer bool\n\n\tswitch clientServer {\n\tcase \"client\":\n\t\tfromServer = false\n\tcase \"server\":\n\t\tfromServer = true\n\tdefault:\n\t\thttp.Error(w, \"bad path not /x/client or /x/server\", http.StatusNotFound)\n\t\treturn\n\n\t}\n\n\tupgraderMutex.Lock()\n\tc, err := upgrader.Upgrade(w, r, nil)\n\tupgraderMutex.Unlock()\n\tcheck(err)\n\tdefer func() {\n\t\tcheck(c.Close())\n\t}()\n\n\tconnections[key{channel, fromServer}] = connection{myconn: c, paired: nil}\n\n\tglog.Warningln(\"connection from \", c.RemoteAddr())\n\n\tfor {\n\t\tmtype, msg, err := c.ReadMessage()\n\t\tif websocket.IsCloseError(err) {\n\t\t\tglog.Warningln(\"remote conn closed, dropping off\")\n\t\t\treturn\n\t\t}\n\t\tcheck(err)\n\n\t\tmessages <- message{channel, mtype, msg, fromServer, c}\n\t}\n}", "func handleWebsocket(w http.ResponseWriter, r *http.Request) (err error) {\n\troomQuery, ok := r.URL.Query()[\"domain\"]\n\tif !ok || len(roomQuery[0]) < 1 {\n\t\terr = fmt.Errorf(\"no domain parameter\")\n\t\treturn\n\t}\n\troom := roomQuery[0]\n\n\tlog.Debugf(\"[%s] new connection\", room)\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\tc := &connection{\n\t\tsend: make(chan Payload, 256),\n\t\tws: ws,\n\t\tid: strings.Split(guuid.New().String(), \"-\")[0],\n\t\tdomain: room,\n\t}\n\ts := subscription{c, room}\n\th.register <- s\n\tgo s.writePump()\n\ts.readPump()\n\n\tlog.Debugf(\"[%s] finished serving\", room)\n\treturn\n}", "func websocketRead(wsConn *websocket.Conn, integraClient *integra.Client) {\n\tfor {\n\t\t_, m, err := wsConn.ReadMessage()\n\t\tif err != nil {\n\t\t\t// Log errors, except for logging websocket\n\t\t\t// going away errors (they happen every time a\n\t\t\t// browser tab is closed).\n\t\t\tif !websocket.IsCloseError(err, websocket.CloseGoingAway) {\n\t\t\t\tlog.Println(\"ReadMessage failed:\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tvar message integra.Message\n\t\terr = json.Unmarshal(m, &message)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Unmarshall failed:\", err)\n\t\t}\n\n\t\terr = integraClient.Send(&message)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Send failed:\", err)\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func (w *BaseWebsocketClient) OnOpen() {}", "func SetupWebsocketClient(ctx context.Context, c *roundtrip.Client, endpoint string, localDialer Dialer) (io.ReadCloser, error) {\n\tu, err := url.Parse(endpoint)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tif u.Scheme == \"http\" {\n\t\tu.Scheme = \"ws\"\n\t} else {\n\t\tu.Scheme = \"wss\"\n\t}\n\t// TODO(klizhentas) fix origin\n\twscfg, err := websocket.NewConfig(u.String(), \"http://localhost\")\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\t//nolint:gosec // TODO(klizhentas) fix insecure config\n\ttlsConfig := &tls.Config{InsecureSkipVerify: true}\n\twscfg.TlsConfig = tlsConfig\n\tc.SetAuthHeader(wscfg.Header)\n\ttransport, ok := c.HTTPClient().Transport.(*http.Transport)\n\tif !ok {\n\t\ttransport = &http.Transport{}\n\t}\n\tdial := transport.DialContext\n\tif dial == nil {\n\t\tdial = (&net.Dialer{}).DialContext\n\t}\n\tconn, err := dial(ctx, \"tcp\", u.Host)\n\tif err != nil {\n\t\t// try to dial using local resolver in case of error\n\t\tlog.Warningf(\"got error, re-dialing with local resolver: %v\", trace.DebugReport(err))\n\t\tconn, err = localDialer(ctx, \"tcp\", u.Host)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t}\n\tif u.Scheme == \"ws\" {\n\t\tclt, err := websocket.NewClient(wscfg, conn)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn clt, nil\n\t}\n\n\ttlsConn := tls.Client(conn, wscfg.TlsConfig)\n\terrC := make(chan error, 2)\n\ttimer := time.AfterFunc(defaults.DialTimeout, func() {\n\t\terrC <- trace.ConnectionProblem(nil, \"handshake timeout\")\n\t})\n\tgo func() {\n\t\terr := tlsConn.Handshake()\n\t\tif timer != nil {\n\t\t\ttimer.Stop()\n\t\t}\n\t\terrC <- err\n\t}()\n\tif err := <-errC; err != nil {\n\t\tconn.Close()\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tclt, err := websocket.NewClient(wscfg, tlsConn)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn clt, nil\n}", "func handleRequest(conn *net.TCPConn, session quic.Session) {\n\tlog.Println(\"handleRequest new request\")\n\tdefer conn.Close()\n\n\tstream, err := session.OpenStreamSync(context.Background())\n\tif err != nil {\n\t\tlog.Println(\"handleRequest session.OpenStreamSync failed:\", err)\n\t\treturn\n\t}\n\n\tdefer stream.Close()\n\n\tlog.Println(\"handleRequest session.OpenStreamSync ok\")\n\tquicbuf := make([]byte, 64*1024)\n\t// read websocket message and forward to tcp\n\tgo func() {\n\t\tdefer conn.Close()\n\t\tfor {\n\t\t\tn, err := stream.Read(quicbuf)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"handleRequest stream read error:\", err)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif n == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// log.Println(\"handleRequest, ws message len:\", len(message))\n\t\t\terr = protoj.WriteAll(conn, quicbuf[:n])\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\n\t// read tcp message and forward to websocket\n\ttcpbuf := make([]byte, 8192)\n\tfor {\n\t\tn, err := conn.Read(tcpbuf)\n\t\tif err != nil {\n\t\t\tlog.Println(\"handleRequest tcp read error:\", err)\n\t\t\tbreak\n\t\t}\n\n\t\t_, err = stream.Write(tcpbuf[:n])\n\t\tif err != nil {\n\t\t\tlog.Println(\"handleRequest ws write error:\", err)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tlog.Println(\"handleRequest new request end\")\n}", "func OnConnect(c websocket.Connection) {\n\t//Join 线程隔离\n\tfmt.Println(c.Context().String())\n\n\tfmt.Println(c.Context().GetHeader(\"Connection\"))\n\tfmt.Println(c.Context().GetHeader(\"Sec-Websocket-Key\"))\n\tfmt.Println(c.Context().GetHeader(\"Sec-Websocket-Version\"))\n\tfmt.Println(c.Context().GetHeader(\"Upgrade\"))\n\n\t//Join将此连接注册到房间,如果它不存在则会创建一个新房间。一个房间可以有一个或多个连接。一个连接可以连接到许多房间。所有连接都自动连接到由“ID”指定的房间。\n\tc.Join(\"room1\")\n\t// Leave从房间中删除此连接条目//如果连接实际上已离开特定房间,则返回true。\n\tdefer c.Leave(\"room1\")\n\n\t//获取路径中的query数据\n\tfmt.Println(\"namespace:\",c.Context().FormValue(\"namespace\"))\n\tfmt.Println(\"nam:\",c.Context().FormValue(\"name\"))\n\n\t//收到消息的事件。bytes=收到客户端发送的消息\n\tc.OnMessage(func(bytes []byte) {\n\t\tfmt.Println(\"client:\",string(bytes))\n\n\t\t//循环向连接的客户端发送数据\n\t\tvar i int\n\t\tfor {\n\t\t\ti++\n\t\t\tc.EmitMessage([]byte(fmt.Sprintf(\"=============%d==========\",i))) // ok works too\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t})\n}", "func (c *client) Connect(ctx context.Context) error {\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tc.ctx = ctx\n\n\tremote := c.cfg.GetURL()\n\n\tvar subList []string\n\n\tfor topic := range c.SubscribedTopics {\n\t\tif IsPublicTopic(topic) {\n\t\t\tc.createCache(topic)\n\n\t\t\tsubList = append(subList, c.normalizeTopic(topic))\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif IsPrivateTopic(topic) && c.hasAuth() {\n\t\t\tc.createCache(topic)\n\n\t\t\tsubList = append(subList, c.normalizeTopic(topic))\n\t\t}\n\t}\n\n\tif len(subList) > 0 {\n\t\tremote.RawQuery = \"subscribe=\" + strings.Join(subList, \",\")\n\t}\n\n\tlog.Info(\"Connecting to: \", remote.String())\n\n\tconn, rsp, err := websocket.DefaultDialer.DialContext(\n\t\tctx, remote.String(), c.getHeader())\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Fail to connect[%s]: %v, %v\",\n\t\t\tremote.String(), err, rsp)\n\t}\n\n\tdefer func() {\n\t\tgo c.messageHandler()\n\t\tgo c.heartbeatHandler()\n\t}()\n\n\tc.ws = conn\n\tc.connected = true\n\tc.ws.SetCloseHandler(c.closeHandler)\n\n\treturn nil\n}", "func (s *Server) handleWsConn(w http.ResponseWriter, r *http.Request) {\n\tusername := r.URL.Query().Get(\"username\")\n\tif username == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\ts.userMu.RLock()\n\t_, ok := s.users[username]\n\ts.userMu.RUnlock()\n\n\tif ok {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tc, err := websocket.Accept(w, r, nil)\n\tif err != nil {\n\t\ts.log.Warn().Err(err).Msg(\"cannot upgrade connection\")\n\t\treturn\n\t}\n\tdefer c.Close(websocket.StatusInternalError, \"internal error\")\n\n\ts.userMu.Lock()\n\ts.users[username] = c\n\ts.userMu.Unlock()\n\n\ts.log.Info().Msg(\"connection established\")\n\tdefer s.log.Info().Msg(\"connection closed\")\n\n\tctx := context.Background()\n\n\ts.writerMu.RLock()\n\tif !s.writerEnabled {\n\t\tgo s.handleWrite(ctx)\n\t}\n\ts.writerMu.RUnlock()\n\n\tfor {\n\t\tif err := s.handleRead(ctx, username, c); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n}", "func newWSCon(t *testing.T) *websocket.Conn {\n\tdialer := websocket.DefaultDialer\n\trHeader := http.Header{}\n\tcon, r, err := dialer.Dial(websocketAddr, rHeader)\n\tfmt.Println(\"response\", r)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn con\n}", "func handlerClientTTYMsg(isFirst *bool, ws *websocket.Conn, sConn *websocket.Conn, msgType int, connectContext *RequestCommand, ID string) (conn *websocket.Conn, id string) {\n\tr := &TTYResponse{}\n\tif *isFirst {\n\t\t// check token\n\t\tok, username := tools.GetUserNameFromToken(connectContext.JWT, AuthRedisClient)\n\t\tconnectContext.username = username\n\t\tif !ok {\n\t\t\tfmt.Fprintln(os.Stderr, \"Can not get user token information\")\n\t\t\tr.OK = false\n\t\t\tr.Id = \"\"\n\t\t\tr.Msg = \"Invalid token\"\n\t\t\tws.WriteJSON(r)\n\t\t\tws.Close()\n\t\t\tconn = nil\n\t\t\treturn\n\t\t}\n\n\t\t// Get project information\n\t\tsession := MysqlEngine.NewSession()\n\t\tu := userModel.User{Username: username}\n\t\tok, err := u.GetWithUsername(session)\n\t\tif !ok {\n\t\t\tfmt.Fprintln(os.Stderr, \"Can not get user information\")\n\t\t\tr.OK = false\n\t\t\tr.Id = \"\"\n\t\t\tr.Msg = \"Invalid user information\"\n\t\t\tws.WriteJSON(r)\n\t\t\tws.Close()\n\t\t\tconn = nil\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tr.OK = false\n\t\t\tr.Id = \"\"\n\t\t\tr.Msg = err.Error()\n\t\t\tws.WriteJSON(r)\n\t\t\tws.Close()\n\t\t\tconn = nil\n\t\t\treturn\n\t\t}\n\t\tp := projectModel.Project{Name: connectContext.Project, UserID: u.ID}\n\t\thas, err := p.GetWithUserIDAndName(session)\n\t\tif !has {\n\t\t\tfmt.Fprintln(os.Stderr, \"Can not get project information\")\n\t\t\tr.OK = false\n\t\t\tr.Id = \"\"\n\t\t\tr.Msg = \"Can not get project information\"\n\t\t\tws.WriteJSON(r)\n\t\t\tws.Close()\n\t\t\tconn = nil\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tr.OK = false\n\t\t\tr.Id = \"\"\n\t\t\tr.Msg = err.Error()\n\t\t\tws.WriteJSON(r)\n\t\t\tws.Close()\n\t\t\tconn = nil\n\t\t\treturn\n\t\t}\n\n\t\t// send request for start a container\n\t\tuserHome := filepath.Join(\"/home\", username, \"projects\")\n\t\t// get image name from language\n\t\tvar image string\n\t\tuserLanguage := connectContext.Language\n\t\tswitch userLanguage {\n\t\tcase 0:\n\t\t\timage = \"txzdream/go-online-golang_image\"\n\t\tcase 1:\n\t\t\timage = \"txzdream/go-online-cpp_image\"\n\t\tcase 2:\n\t\t\timage = \"txzdream/go-online-python_image\"\n\t\tcase 3:\n\t\t\timage = \"ubuntu\"\n\t\tdefault:\n\t\t\timage = \"txzdream/go-online-golang_image\"\n\t\t}\n\t\t// get project root dir\n\t\tCONTAINER_USER_NAME := os.Getenv(\"CONTAINER_USER_NAME\")\n\t\tif CONTAINER_USER_NAME == \"\" {\n\t\t\tCONTAINER_USER_NAME = \"root\"\n\t\t}\n\t\tpwd := filepath.Join(\"/home\", CONTAINER_USER_NAME, p.Path, p.Name)\n\t\trootDir := filepath.Join(\"/home\", CONTAINER_USER_NAME)\n\t\tbody := NewContainer{\n\t\t\tImage: image,\n\t\t\tPWD: pwd,\n\t\t\tENV: []string{\"GOPATH=/home/ubuntu/go\"},\n\t\t\tMnt: []string{userHome},\n\t\t\tTargetDir: []string{rootDir},\n\t\t\tNetwork: []string{},\n\t\t}\n\n\t\tb, err := json.Marshal(body)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tr.OK = false\n\t\t\tr.Id = \"\"\n\t\t\tr.Msg = err.Error()\n\t\t\tws.WriteJSON(r)\n\t\t\tws.Close()\n\t\t\tconn = nil\n\t\t\treturn\n\t\t}\n\t\tid, err = startContainer(b)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tr.OK = false\n\t\t\tr.Id = \"\"\n\t\t\tr.Msg = err.Error()\n\t\t\tws.WriteJSON(r)\n\t\t\tws.Close()\n\t\t\tconn = nil\n\t\t\treturn\n\t\t}\n\t\tID = id\n\n\t\t// TODO: write container information to the redis\n\t\t// connect to the container\n\t\ttmp, err := initDockerConnection(\"tty\", id)\n\t\tsConn = tmp\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Can not connect to the docker service\")\n\t\t\tr.OK = false\n\t\t\tr.Id = \"\"\n\t\t\tr.Msg = \"Server error\"\n\t\t\tws.WriteJSON(r)\n\t\t\tws.Close()\n\t\t\treturn\n\t\t}\n\t\tID = id\n\t\t// Listen message from docker service and send to client connection\n\t\tgo sendTTYMsgToClient(ws, sConn)\n\t}\n\n\tif sConn == nil {\n\t\tfmt.Fprintf(os.Stderr, \"Invalid command.\")\n\t\tws.WriteMessage(msgType, []byte(\"Invalid Command\"))\n\t\tws.Close()\n\t\tconn = nil\n\t\treturn\n\t}\n\n\t// resize tty window\n\tif connectContext.Width > 0 && connectContext.Height > 0 {\n\t\tr := ResizeContainer{\n\t\t\tID: ID,\n\t\t\tWidth: connectContext.Width,\n\t\t\tHeight: connectContext.Height,\n\t\t}\n\t\tresizeContainer(&r)\n\t}\n\n\t// Send message to docker service\n\t//switch connectContext.Type {\n\t//case 0:\n\t// user input stream\n\thandleTTYMessage(msgType, sConn, id, connectContext.Message)\n\t//case 1:\n\t//resize the window\n\t//}\n\t*isFirst = false\n\tconn = sConn\n\treturn\n}", "func (h *handler) handle(c goetty.IOSession) error {\n\th.logger.Info(\"new connection comes\", zap.Uint64(\"session ID\", c.ID()))\n\n\th.counterSet.connAccepted.Add(1)\n\th.counterSet.connTotal.Add(1)\n\tdefer h.counterSet.connTotal.Add(-1)\n\n\t// Create a new tunnel to manage client connection and server connection.\n\tt := newTunnel(h.ctx, h.logger, h.counterSet)\n\tdefer func() {\n\t\t_ = t.Close()\n\t}()\n\n\tcc, err := newClientConn(\n\t\th.ctx, &h.config, h.logger, h.counterSet, c, h.haKeeperClient, h.moCluster, h.router, t,\n\t)\n\tif err != nil {\n\t\th.logger.Error(\"failed to create client conn\", zap.Error(err))\n\t\treturn err\n\t}\n\th.logger.Info(\"client conn created\")\n\tdefer func() { _ = cc.Close() }()\n\n\t// client builds connections with a best CN server and returns\n\t// the server connection.\n\tsc, err := cc.BuildConnWithServer(true)\n\tif err != nil {\n\t\th.logger.Error(\"failed to create server conn\", zap.Error(err))\n\t\th.counterSet.updateWithErr(err)\n\t\tcc.SendErrToClient(err.Error())\n\t\treturn err\n\t}\n\th.logger.Info(\"server conn created\")\n\tdefer func() { _ = sc.Close() }()\n\n\th.logger.Info(\"build connection successfully\",\n\t\tzap.String(\"client\", cc.RawConn().RemoteAddr().String()),\n\t\tzap.String(\"server\", sc.RawConn().RemoteAddr().String()),\n\t)\n\n\tst := stopper.NewStopper(\"proxy-conn-handle\", stopper.WithLogger(h.logger.RawLogger()))\n\tdefer st.Stop()\n\t// Starts the event handler go-routine to handle the events comes from tunnel data flow,\n\t// such as, kill connection event.\n\tif err := st.RunNamedTask(\"event-handler\", func(ctx context.Context) {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase e := <-t.reqC:\n\t\t\t\tif err := cc.HandleEvent(ctx, e, t.respC); err != nil {\n\t\t\t\t\th.logger.Error(\"failed to handle event\",\n\t\t\t\t\t\tzap.Any(\"event\", e), zap.Error(err))\n\t\t\t\t}\n\t\t\tcase r := <-t.respC:\n\t\t\t\tif len(r) > 0 {\n\t\t\t\t\tt.mu.Lock()\n\t\t\t\t\t// We must call this method because it locks writeMu.\n\t\t\t\t\tif err := t.mu.serverConn.writeDataDirectly(cc.RawConn(), r); err != nil {\n\t\t\t\t\t\th.logger.Error(\"failed to write event response\",\n\t\t\t\t\t\t\tzap.Any(\"response\", r), zap.Error(err))\n\t\t\t\t\t}\n\t\t\t\t\tt.mu.Unlock()\n\t\t\t\t}\n\t\t\tcase <-ctx.Done():\n\t\t\t\th.logger.Debug(\"event handler stopped.\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tif err := t.run(cc, sc); err != nil {\n\t\treturn err\n\t}\n\n\tselect {\n\tcase <-h.ctx.Done():\n\t\treturn h.ctx.Err()\n\tcase err := <-t.errC:\n\t\tif !isEOFErr(err) {\n\t\t\th.counterSet.updateWithErr(err)\n\t\t\th.logger.Error(\"proxy handle error\", zap.Error(err))\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n}", "func (service WebsocketProcessor) HandleNewConnection(websocketConn *websocket.Conn) {\n\tconnIO := NewWebsocketJSONConnIO(websocketConn, service.websocketSettings.WriteWait)\n\tconnection := common.NewConnection(websocketConn, connIO)\n\n\twebsocketConn.SetReadLimit(service.websocketSettings.MaxMessageSize)\n\twebsocketConn.SetPongHandler(service.pongHandler(websocketConn))\n\terr := websocketConn.SetReadDeadline(time.Now().Add(service.websocketSettings.PongWait))\n\tif err != nil {\n\t\tfmt.Println(\"Websocket handle new connection error at setting read deadline\", err)\n\t}\n\n\tgo service.ping(websocketConn)\n\n\tservice.WebSocketConn <- connection\n}", "func client(wsUri string) {\n\n\ttlsConfig := tls.Config{}\n\ttlsConfig.InsecureSkipVerify = true\n\tdialer := websocket.Dialer{TLSClientConfig: &tlsConfig}\n\trequestHeader := http.Header{}\n\trequestHeader.Set(\"origin\", \"http://localhost/\")\n\tconn, _, err := dialer.Dial(wsUri, requestHeader)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"The gowebsock client is connected to %s\\n\", wsUri)\n\n\treaderResultChan := make(chan readerResult)\n\tgo reader(conn, readerResultChan)\n\n\twriterCommandChan := make(chan writerCommand)\n\tgo writer(conn, writerCommandChan)\n\n\tstdinReaderChan := make(chan string)\n\tgo stdinReader(stdinReaderChan)\n\n\tfor {\n\t\tselect {\n\t\tcase stdinMessage := <-stdinReaderChan:\n\t\t\tvar messageType int\n\t\t\tdata := \"\"\n\t\t\tswitch stdinMessage {\n\t\t\tcase \"close\":\n\t\t\t\tmessageType = 8\n\t\t\tcase \"ping\":\n\t\t\t\tmessageType = 9\n\t\t\tcase \"pong\":\n\t\t\t\tmessageType = 10\n\t\t\tdefault:\n\t\t\t\tmessageType = 1\n\t\t\t\tdata = stdinMessage\n\t\t\t}\n\t\t\twriterCommandChan <- writerCommand{false, messageType, []byte(data)}\n\t\tcase readerResult := <-readerResultChan:\n\t\t\tif readerResult.err == nil {\n\t\t\t\toutput := \"Server: type = \" + messageTypeString(readerResult.messageType) + \", data = \" + string(readerResult.data) + \"\\n\"\n\t\t\t\tfmt.Printf(output)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"%s\\n\", readerResult.err)\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\t\t}\n\t}\n}", "func Upgrade(w http.ResponseWriter, r *http.Request) (*websocket.Conn, error) {\n\n\t// required to handle CORS i.e. check if request from a different domain is allowed to connect\n\tupgrader.CheckOrigin = func(r *http.Request) bool { // the anonymous function returns a true or false i.e. true being allowed\n\t\treturn true //let's assume for testing purposes that the requesting domain is allowed, reqgardless of origin/source\n\t}\n\n\twsConn, err := upgrader.Upgrade(w, r, nil) //convert the http to ws i.e. convert the w to wsConn\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn wsConn, err\n\t}\n\treturn wsConn, nil\n}", "func (srv *Server) ServeHTTP(\n\tresp http.ResponseWriter,\n\treq *http.Request,\n) {\n\tswitch req.Method {\n\tcase \"OPTIONS\":\n\t\tsrv.hooks.OnOptions(resp)\n\t\treturn\n\tcase \"WEBWIRE\":\n\t\tsrv.handleMetadata(resp)\n\t\treturn\n\t}\n\n\t// Establish connection\n\tconn, err := srv.upgrader.Upgrade(resp, req, nil)\n\tif err != nil {\n\t\tsrv.errorLog.Print(\"Upgrade failed:\", err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\t// Register connected client\n\tnewClient := &Client{\n\t\tsrv,\n\t\t&sync.Mutex{},\n\t\tconn,\n\t\ttime.Now(),\n\t\treq.Header.Get(\"User-Agent\"),\n\t\tnil,\n\t}\n\n\tsrv.clientsLock.Lock()\n\tsrv.clients = append(srv.clients, newClient)\n\tsrv.clientsLock.Unlock()\n\n\t// Call hook on successful connection\n\tsrv.hooks.OnClientConnected(newClient)\n\n\tfor {\n\t\t// Await message\n\t\t_, message, err := conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tif newClient.Session != nil {\n\t\t\t\t// Mark session as inactive\n\t\t\t\tsrv.SessionRegistry.deregister(newClient)\n\t\t\t}\n\n\t\t\tif websocket.IsUnexpectedCloseError(\n\t\t\t\terr,\n\t\t\t\twebsocket.CloseGoingAway,\n\t\t\t\twebsocket.CloseAbnormalClosure,\n\t\t\t) {\n\t\t\t\tsrv.warnLog.Printf(\"Reading failed: %s\", err)\n\t\t\t}\n\n\t\t\tsrv.hooks.OnClientDisconnected(newClient)\n\t\t\treturn\n\t\t}\n\n\t\t// Parse message\n\t\tvar msg Message\n\t\tif err := msg.Parse(message); err != nil {\n\t\t\tsrv.errorLog.Println(\"Failed parsing message:\", err)\n\t\t\tbreak\n\t\t}\n\n\t\t// Prepare message\n\t\t// Reference the client associated with this message\n\t\tmsg.Client = newClient\n\n\t\tmsg.createReplyCallback(newClient, srv)\n\t\tmsg.createFailCallback(newClient, srv)\n\n\t\t// Handle message\n\t\tif err := srv.handleMessage(&msg); err != nil {\n\t\t\tsrv.errorLog.Printf(\"CRITICAL FAILURE: %s\", err)\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (o *Okcoin) WsConnect() error {\n\tif !o.Websocket.IsEnabled() || !o.IsEnabled() {\n\t\treturn errors.New(stream.WebsocketNotEnabled)\n\t}\n\tvar dialer websocket.Dialer\n\tdialer.ReadBufferSize = 8192\n\tdialer.WriteBufferSize = 8192\n\terr := o.Websocket.Conn.Dial(&dialer, http.Header{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif o.Verbose {\n\t\tlog.Debugf(log.ExchangeSys, \"Successful connection to %v\\n\",\n\t\t\to.Websocket.GetWebsocketURL())\n\t}\n\to.Websocket.Conn.SetupPingHandler(stream.PingHandler{\n\t\tDelay: time.Second * 25,\n\t\tMessage: []byte(\"ping\"),\n\t\tMessageType: websocket.TextMessage,\n\t})\n\n\to.Websocket.Wg.Add(1)\n\tgo o.WsReadData(o.Websocket.Conn)\n\n\tif o.IsWebsocketAuthenticationSupported() {\n\t\terr = o.WsLogin(context.TODO(), &dialer)\n\t\tif err != nil {\n\t\t\tlog.Errorf(log.ExchangeSys,\n\t\t\t\t\"%v - authentication failed: %v\\n\",\n\t\t\t\to.Name,\n\t\t\t\terr)\n\t\t}\n\t}\n\treturn nil\n}", "func (c *client) serveWs(s *server, w http.ResponseWriter, r *http.Request) {\n\tconn,err := upgrader.Upgrade(w,r,nil)\n\tif err != nil {\n\t\tlog.Println(\"error upgrading to websocket:\",err.Error())\n\t\treturn\n\t}\n\tc.Server = s\n\tc.conn = conn\n\tc.send = make(chan[]byte, 256)\n\n\tc.Server.register <- c\n\n\tgo c.writePump()\n\tgo c.readPump()\n}", "func (wh *websocketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\twsConn, err := wh.upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer wsConn.Close()\n\n\t// handle Websocket request\n\tsock := NewSocket(wsConn)\n\t//logger.Debug(\" >>>>>>>>>>>>> connected\", userID)\n\t// bind\n\twh.binder.Bind(sock.GetID(), sock)\n\tsock.AfterReadFunc = func(messageType int, rmessage []byte) {\n\t\tif wh.connecter != nil {\n\t\t\twh.connecter.SendToServer(proto.MsgTypeSignle, sock.GetID(), rmessage)\n\t\t}\n\n\t\t// userID := sock.GetID() //rm.Token\n\t\t// //logger.Debug(\" >>>>>>>>>>>>> message\", userID)\n\t\t// // bind\n\t\t// wh.binder.Bind(userID, sock)\n\t}\n\tsock.BeforeCloseFunc = func() {\n\t\t// unbind\n\t\twh.binder.Unbind(sock)\n\t\t//logger.Debug(\" <<<<<<<<<<<<<<< closed\", sock.GetID())\n\t}\n\n\tsock.Listen()\n\t//disconnect\n\twh.binder.Unbind(sock)\n\t//logger.Debug(\" <<<<<<<<<<<<<<< disconnect\", sock.GetID())\n\tif err := sock.Close(); err != nil {\n\t\tlogger.Error(err)\n\t}\n}", "func (s *WebsocketServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tvar authDict wamp.Dict\n\tvar nextCookie *http.Cookie\n\n\t// If tracking cookie is enabled, then read the tracking cookie from the\n\t// request header, if it contains the cookie. Generate a new tracking\n\t// cookie for next time and put it in the response header.\n\tif s.EnableTrackingCookie {\n\t\tif authDict == nil {\n\t\t\tauthDict = wamp.Dict{}\n\t\t}\n\t\tconst cookieName = \"nexus-wamp-cookie\"\n\t\tif reqCk, err := r.Cookie(cookieName); err == nil {\n\t\t\tauthDict[\"cookie\"] = reqCk\n\t\t\t//fmt.Println(\"===> Received tracking cookie: \", reqCk)\n\t\t}\n\t\tb := make([]byte, 18)\n\t\t_, err := rand.Read(b)\n\t\tif err == nil {\n\t\t\t// Create new auth cookie with 20 byte random value.\n\t\t\tnextCookie = &http.Cookie{\n\t\t\t\tName: cookieName,\n\t\t\t\tValue: base64.URLEncoding.EncodeToString(b),\n\t\t\t}\n\t\t\thttp.SetCookie(w, nextCookie)\n\t\t\tauthDict[\"nextcookie\"] = nextCookie\n\t\t\t//fmt.Println(\"===> Sent Next tracking cookie:\", nextCookie)\n\t\t\t//fmt.Println()\n\t\t}\n\t}\n\n\t// If request capture is enabled, then save the HTTP upgrade http.Request\n\t// in the HELLO and session details as transport.auth details.request.\n\tif s.EnableRequestCapture {\n\t\tif authDict == nil {\n\t\t\tauthDict = wamp.Dict{}\n\t\t}\n\t\tauthDict[\"request\"] = r\n\t}\n\n\tconn, err := s.Upgrader.Upgrade(w, r, w.Header())\n\tif err != nil {\n\t\ts.router.Logger().Println(\"Error upgrading to websocket connection:\", err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\ts.handleWebsocket(conn, wamp.Dict{\"auth\": authDict})\n}", "func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request, cleanup func()) *Client {\n\tupgrader.CheckOrigin = func(r *http.Request) bool {\n\t\treturn true\n\t}\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil\n\t}\n\tc := &Client{\n\t\thub: hub,\n\t\tconn: conn,\n\t\tsend: make(chan []byte, 256),\n\t\tcleanup: cleanup,\n\t}\n\tc.hub.register <- c\n\n\t// Allow collection of memory referenced by the caller by doing all work in\n\t// new goroutines.\n\tgo c.writePump()\n\tgo c.readPump()\n\treturn c\n}", "func wsHandler(w http.ResponseWriter, r *http.Request) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tclient := &models.Client{Conn: conn}\n\tclients[conn] = client\n\tgo receiveMessages(conn)\n\n\toutboundResponses <- &models.Message{Body: \"Welcome to the chat room!\", Client: &models.Client{Handle: \"Server\", Conn: client.GetConn()}}\n\n\tfmt.Println(\"Client connected\")\n}", "func (r *ProtocolIncus) rawWebsocket(url string) (*websocket.Conn, error) {\n\t// Grab the http transport handler\n\thttpTransport, err := r.getUnderlyingHTTPTransport()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Setup a new websocket dialer based on it\n\tdialer := websocket.Dialer{\n\t\tNetDialContext: httpTransport.DialContext,\n\t\tTLSClientConfig: httpTransport.TLSClientConfig,\n\t\tProxy: httpTransport.Proxy,\n\t\tHandshakeTimeout: time.Second * 5,\n\t}\n\n\t// Create temporary http.Request using the http url, not the ws one, so that we can add the client headers\n\t// for the websocket request.\n\treq := &http.Request{URL: &r.httpBaseURL, Header: http.Header{}}\n\tr.addClientHeaders(req)\n\n\t// Establish the connection\n\tconn, resp, err := dialer.Dial(url, req.Header)\n\tif err != nil {\n\t\tif resp != nil {\n\t\t\t_, _, err = incusParseResponse(resp)\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\t// Set TCP timeout options.\n\tremoteTCP, _ := tcp.ExtractConn(conn.UnderlyingConn())\n\tif remoteTCP != nil {\n\t\terr = tcp.SetTimeouts(remoteTCP, 0)\n\t\tif err != nil {\n\t\t\tlogger.Warn(\"Failed setting TCP timeouts on remote connection\", logger.Ctx{\"err\": err})\n\t\t}\n\t}\n\n\t// Log the data\n\tlogger.Debugf(\"Connected to the websocket: %v\", url)\n\n\treturn conn, nil\n}", "func connect() (*websocket.Conn, error) {\n\thost := fmt.Sprintf(\"%s:%s\", configuration.TV.Host, *configuration.TV.Port)\n\tpath := \"/api/v2/channels/samsung.remote.control\"\n\tquery := fmt.Sprintf(\"name=%s\", base64.StdEncoding.EncodeToString([]byte(configuration.Controller.Name)))\n\tu := url.URL{Scheme: *configuration.TV.Protocol, Host: host, Path: path, RawQuery: query}\n\n\tlog.Infof(\"Opening connection to %s ...\", u.String())\n\n\twebsocket.DefaultDialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\n\tconnection, _, err := websocket.DefaultDialer.Dial(u.String(), nil)\n\tif err != nil {\n\t\tlog.Debugf(\"%v\", err)\n\t\treturn nil, err\n\t}\n\n\tlog.Infof(\"Connection is established.\")\n\n\treturn connection, nil\n}", "func ServeWs(hub *Hub, w http.ResponseWriter, r *http.Request, appKey, client, version, protocolStr string) {\n\tprotocol, _ := Str2Int(protocolStr)\n\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\n\tif appKey != viper.GetString(\"APP_KEY\") {\n\t\tlog.Error(\"Error app key\", appKey)\n\t\t_ = conn.SetWriteDeadline(time.Now().Add(time.Second))\n\t\t_ = conn.WriteMessage(websocket.TextMessage, ErrPack(4001))\n\t\t_ = conn.Close()\n\t\treturn\n\t}\n\n\tif !funk.Contains(SupportedProtocolVersions, protocol) {\n\t\tlog.Error(\"Unsupported protocol version\", protocol)\n\t\t_ = conn.SetWriteDeadline(time.Now().Add(time.Second))\n\t\t_ = conn.WriteMessage(websocket.TextMessage, ErrPack(4007))\n\t\t_ = conn.Close()\n\t\treturn\n\t}\n\n\tsocketID := GenerateSocketID()\n\tsession := &Session{hub: hub, conn: conn, client: client, version: version, protocol: protocol, send: make(chan []byte, maxMessageSize), subscriptions: make(map[string]bool), pubSub: new(redis.PubSub), socketID: socketID, closed: false}\n\tsession.hub.register <- session\n\n\tsession.pubSub = db.Redis().Subscribe()\n\tgo session.subscribePump()\n\tgo session.writePump()\n\tgo session.readPump()\n\n\tsession.send <- EstablishPack(socketID)\n}", "func (sio *SocketIO) handle(t Transport, w http.ResponseWriter, req *http.Request) {\n\tvar parts []string\n\tvar c *Conn\n\tvar err os.Error\n\n\tif origin, ok := req.Header[\"Origin\"]; ok {\n\t\tif _, ok = sio.verifyOrigin(origin); !ok {\n\t\t\tsio.Log(\"sio/handle: unauthorized origin:\", origin)\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\n\t\tw.SetHeader(\"Access-Control-Allow-Origin\", origin)\n\t\tw.SetHeader(\"Access-Control-Allow-Credentials\", \"true\")\n\t\tw.SetHeader(\"Access-Control-Allow-Methods\", \"POST, GET\")\n\t}\n\n\tswitch req.Method {\n\tcase \"OPTIONS\":\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn\n\n\tcase \"GET\", \"POST\":\n\t\tbreak\n\n\tdefault:\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t// TODO: fails if the session id matches the transport\n\tif i := strings.LastIndex(req.URL.Path, t.Resource()); i >= 0 {\n\t\tpathLen := len(req.URL.Path)\n\t\tif req.URL.Path[pathLen-1] == '/' {\n\t\t\tpathLen--\n\t\t}\n\n\t\tparts = strings.Split(req.URL.Path[i:pathLen], \"/\", -1)\n\t}\n\n\tswitch len(parts) {\n\tcase 1:\n\t\t// only resource was present, so create a new connection\n\t\tc, err = newConn(sio)\n\t\tif err != nil {\n\t\t\tsio.Log(\"sio/handle: unable to create a new connection:\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\tcase 2:\n\t\tfallthrough\n\n\tcase 3:\n\t\t// session id was present\n\t\tc = sio.GetConn(SessionID(parts[1]))\n\t}\n\n\t// we should now have a connection\n\tif c == nil {\n\t\tsio.Log(\"sio/handle: unable to map request to connection:\", req.RawURL)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// pass the http conn/req pair to the connection\n\tif err = c.handle(t, w, req); err != nil {\n\t\tsio.Logf(\"sio/handle: conn/handle: %s: %s\", c, err)\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t}\n}", "func (a *api) SocketHandler() http.Handler {\n\treturn http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {\n\t\tvar upgrader = websocket.Upgrader{\n\t\t\tReadBufferSize: 1024,\n\t\t\tWriteBufferSize: 1024,\n\t\t}\n\n\t\tupgrader.CheckOrigin = func(req *http.Request) bool { return true }\n\n\t\tconn, err := upgrader.Upgrade(res, req, nil)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\treturn\n\t\t}\n\n\t\ta.sockets = append(a.sockets, conn)\n\t\tlog.Print(\"New socket opened, open socket count: \" + strconv.Itoa(len(a.sockets)))\n\n\t\tfor {\n\t\t\t_, msg, err := conn.ReadMessage()\n\n\t\t\tif err != nil {\n\t\t\t\ta.removeSocket(conn)\n\t\t\t\tlog.Print(err)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tmessage := Message{}\n\t\t\terr = json.Unmarshal(msg, &message)\n\t\t\tif err != nil {\n\t\t\t\ta.removeSocket(conn)\n\t\t\t\tlog.Print(err)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif message.Time.IsZero() {\n\t\t\t\tmessage.Time = time.Now()\n\t\t\t}\n\n\t\t\tfmt.Println(message)\n\n\t\t\tswitch message.Type {\n\t\t\tcase \"message\":\n\t\t\t\tbyteB, err := json.Marshal(&message)\n\t\t\t\tif err != nil {\n\t\t\t\t\ta.removeSocket(conn)\n\t\t\t\t\tlog.Print(err)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ta.p2p.Broadcast(byteB)\n\t\t\tcase \"ping\":\n\t\t\t\tpong := Message{Type: \"pong\"}\n\t\t\t\tbytePong, _ := json.Marshal(pong)\n\t\t\t\tconn.WriteMessage(websocket.BinaryMessage, bytePong)\n\t\t\tdefault:\n\t\t\t\tlog.Println(\"Unsupported message.\")\n\t\t\t\tlog.Println(string(msg))\n\t\t\t}\n\t\t}\n\t})\n}", "func websocketHandler(s *state.State, w http.ResponseWriter, r *http.Request) {\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\ts.Log.Errorln(err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"failed to establish websocket connection\"))\n\t\treturn\n\t}\n\t// register client\n\tclients[ws] = true\n}", "func serveWebsocket(c *gin.Context) {\n\tsessionId := uuid.NewV4()\n\t// upgrade connection to websocket\n\tconn, err := upgrader.Upgrade(c.Writer, c.Request, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tconn.EnableWriteCompression(true)\n\n\t// create two channels for read write concurrency\n\tcWrite := make(chan []byte)\n\tcRead := make(chan []byte)\n\n\tclient := &Client{conn: conn, write: cWrite, read: cRead}\n\n\t// get scene width and height from url query params\n\t// default to 800 if they are not set\n\theight := getParameterDefault(c, \"h\", 800)\n\twidth := getParameterDefault(c, \"w\", 800)\n\n\tmodelPath := \"models/\"\n\tdefaultModel := \"Cathedral.glb\"\n\tmodel := c.Request.URL.Query().Get(\"model\")\n\tif model == \"\" {\n\t\tmodel = defaultModel\n\t}\n\tif _, err := os.Stat(modelPath + model); os.IsNotExist(err) {\n\t\tmodel = defaultModel\n\t}\n\n\t// run 3d application in separate go routine\n\tgo renderer.LoadRenderingApp(&client.app, sessionId.String(), height, width, cWrite, cRead, modelPath+model)\n\n\t// run reader and writer in two different go routines\n\t// so they can act concurrently\n\tgo client.streamReader()\n\tgo client.streamWriter()\n}", "func (r *ProtocolIncus) websocket(path string) (*websocket.Conn, error) {\n\t// Generate the URL\n\tvar url string\n\tif r.httpBaseURL.Scheme == \"https\" {\n\t\turl = fmt.Sprintf(\"wss://%s/1.0%s\", r.httpBaseURL.Host, path)\n\t} else {\n\t\turl = fmt.Sprintf(\"ws://%s/1.0%s\", r.httpBaseURL.Host, path)\n\t}\n\n\treturn r.rawWebsocket(url)\n}", "func serveWs(w http.ResponseWriter, r *http.Request) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\t_, p, err := conn.ReadMessage()\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn\n\t}\n\turi := string(p)\n\tarticleInfo := articleInfoFromUrl(uri)\n\tif articleInfo == nil {\n\t\tfmt.Printf(\"serveWs: didn't find article for uri %s\\n\", uri)\n\t\treturn\n\t}\n\n\tarticle := articleInfo.this\n\tfmt.Printf(\"serveWs: started watching %s for uri %s\\n\", article.Path, uri)\n\n\tc := AddWatch(article.Path)\n\tdefer RemoveWatch(c)\n\tdone := make(chan struct{})\n\n\tgo func() {\n\t\tfor {\n\t\t\t_, _, err := conn.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"serveWs: closing for %s\\n\", uri)\n\t\t\t\tclose(done)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-c:\n\t\t\treloadArticle(article)\n\t\t\terr := conn.WriteMessage(websocket.TextMessage, nil)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tbreak loop\n\t\t\t}\n\t\tcase <-done:\n\t\t\tbreak loop\n\t\t}\n\t}\n}", "func websocketEchoHandler(w http.ResponseWriter, r *http.Request) {\n\tc, err := webSocketUpgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\terrorf(w, http.StatusInternalServerError, \"websocket upgrade failed: %v\", err)\n\t\treturn\n\t}\n\tdefer c.Close()\n\tfor {\n\t\tmt, message, err := c.ReadMessage()\n\t\tif err != nil {\n\t\t\terrorf(w, http.StatusInternalServerError, \"websocket read failed: %v\", err)\n\t\t\tbreak\n\t\t}\n\t\tlog.Printf(\"recv: %s\", message)\n\t\terr = c.WriteMessage(mt, message)\n\t\tif err != nil {\n\t\t\terrorf(w, http.StatusInternalServerError, \"websocket write failed: %v\", err)\n\t\t\tbreak\n\t\t}\n\t}\n}", "func HandleWs(hub *Hub, w http.ResponseWriter, r *http.Request) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tc := &Client{conn: conn, send: make(chan []byte, 256)}\n\thub.register <- c\n\n\tgo c.writeLoop()\n}", "func (network *tcp_net) handle_connection(index int, conn *net.TCPConn, handshake []byte) {\n\terr := network.write(handshake, conn)\n\tif err != nil {\n\t\t// if we got error during handshake write\n\t\t// just closing connection\n\t\tnetwork.close_connection(index)\n\t\treturn\n\t}\n\n\t// keeping 4 bytes for reading first 4 bytes\n\tendian_data := make([]byte, 4)\n\n\t// after writing handshake, we need to read server handshake also\n\t// first reading API version as a BigEndian 4 bytes\n\tapi_version, close_conn := read_endian(conn, endian_data)\n\tif close_conn {\n\t\tnetwork.close_connection(index)\n\t\treturn\n\t}\n\n\t// checking if we got valid API version\n\tif api_version > MAX_API_VERSION || api_version == 0 {\n\t\tgo network.api.trigger_local(EVENT_ON_ERROR, []byte(fmt.Sprintf(\"Invalid API version %d from TCP channel\", api_version)))\n\t\tnetwork.close_connection(index)\n\t\treturn\n\t}\n\n\t// reading token and value from endpoint\n\ttoken_value_buf, close_conn := read_message(conn, endian_data)\n\tif close_conn {\n\t\tnetwork.close_connection(index)\n\t\treturn\n\t}\n\n\ttv_len := len(token_value_buf)\n\ttoken := string(token_value_buf[:tv_len-8])\n\tvalue := binary.BigEndian.Uint64(token_value_buf[tv_len-8:])\n\t// if we got new API value and token, then probably this is a new connection\n\t// so setting up new endpoint values and triggering event\n\tnetwork.api.endpoint_info_locker.Lock()\n\tif network.api.endpoint_value != value || network.api.endpoint_token != token {\n\t\tnetwork.api.endpoint_value = value\n\t\tnetwork.api.endpoint_token = token\n\t\tgo network.api.trigger_local(EVENT_ON_CONNECTION, []byte(fmt.Sprintf(\"%s|%d\", token, value)))\n\t}\n\tnetwork.api.endpoint_info_locker.Unlock()\n\n\tvar data []byte\n\n\tfor {\n\t\tdata, close_conn = read_message(conn, endian_data)\n\t\tif close_conn {\n\t\t\tnetwork.close_connection(index)\n\t\t\treturn\n\t\t}\n\n\t\tgo network.api.handle_data(data)\n\t}\n}", "func Connect(url string) {\n\tendpoint := \"/8455b565159ec51f74d50b19944d4caaef7adbed\"\n\n\tif strings.Index(url, \":\") > 0 {\n\t\tws := js.Global.Get(\"WebSocket\").New(\"ws://\" + url + endpoint)\n\n\t\tws.Set(\"onopen\", func(evt *js.Object) {\n\t\t\tsocketm.Lock()\n\t\t\tsockets = append(sockets, client{ws})\n\t\t\tsocketm.Unlock()\n\t\t})\n\n\t\tws.Set(\"onmessage\", func(evt *js.Object) { go read(evt.Get(\"data\").String()) })\n\t} else {\n\t\ts := &server{websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}}\n\t\thttp.HandleFunc(endpoint, s.onConnection)\n\n\t\tgo func() {\n\t\t\terr := http.ListenAndServe(url, nil)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}()\n\t}\n\n\tgo write()\n}", "func serveWs(hub *Hub, c echo.Context) error {\n\n\tuser := c.Get(\"user\").(*jwt.Token)\n\tclaims := user.Claims.(*auth.JWTUserClaims)\n\tname := claims.Name\n\n\n\tconn, err := upgrader.Upgrade(c.Response(), c.Request(), nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tclient := &Client{name: name, hub: hub, conn: conn, send: make(chan Command)}\n\tclient.hub.register <- client\n\tgo client.writePump()\n\ttime.AfterFunc(1*time.Second, func() {\n\t\tclient.hub.broadcast <- enterRoomCommand(client.name)\n\t})\n\tclient.readPump()\n\ttime.AfterFunc(1*time.Second, func() {\n\t\tclient.hub.broadcast <- leaveRoomCommand(client.name)\n\t})\n\treturn nil\n}", "func Upgrade(w http.ResponseWriter, r *http.Request, h http.Header, upgrader *websocket.Upgrader) (*Conn, error) {\n\tif upgrader == nil {\n\t\tupgrader = DefaultUpgrader\n\t}\n\tws, err := upgrader.Upgrade(w, r, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn := &Conn{\n\t\tws: ws,\n\t\tbuf: newSafeBuffer(),\n\t\tdone: make(chan struct{}),\n\t}\n\n\t// Set read deadline to detect failed clients.\n\tif err = conn.ws.SetReadDeadline(time.Now().Add(PongTimeout)); err != nil {\n\t\treturn nil, err\n\t}\n\t// Reset read deadline on Pong.\n\tconn.ws.SetPongHandler(func(string) error {\n\t\treturn conn.ws.SetReadDeadline(time.Now().Add(PongTimeout))\n\t})\n\n\t// Start ping loop for client keep-alive.\n\tgo conn.pinger()\n\n\treturn conn, nil\n}", "func (s *server) wsHandler(w http.ResponseWriter, r *http.Request) {\n\t// Upgrade the HTTP connection.\n\tc, err := s.upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\ts.log.Error(\"error upgrading connection\")\n\t\treturn\n\t}\n\tdefer c.Close()\n\n\t// Client has connected, save its connection in clients struct.\n\t// Remove the connection once the client is disconected.\n\ts.clients.add(c)\n\tdefer s.clients.remove(c)\n\n\ts.log.Info(\"client connected\", zap.Any(\"address\", c.RemoteAddr()))\n\n\t// Wait for messages\n\tfor {\n\t\tselect {\n\t\tcase <-s.ctx.Done():\n\t\t\ts.log.Info(\"closing context\")\n\t\t\treturn\n\t\tdefault:\n\t\t\t_, msg, err := c.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\ts.log.Error(\"error reading message\", zap.Error(err))\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\ts.log.Info(\"message received\", zap.String(\"msg\", string(msg)))\n\n\t\t\t// Publish the message to redis\n\t\t\terr = s.redis.Publish(s.ctx, s.channel, msg).Err()\n\t\t\tif err != nil {\n\t\t\t\ts.log.Error(\"error publishing message to redis\", zap.Error(err))\n\t\t\t}\n\n\t\t\ts.log.Info(\"message published\")\n\t\t}\n\t}\n}", "func SubscribeHttp(ctx *ServerContext) func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tc, err := upgrader.Upgrade(w, r, nil)\n\t\tif err != nil {\n\t\t\tlog.Print(\"upgrade:\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer c.Close()\n\t\tfor {\n\t\t\tmt, message, err := c.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"read:\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlog.Printf(\"recv: %s\", message)\n\t\t\terr = c.WriteMessage(mt, message)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"write:\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}", "func websocketWrite(wsConn *websocket.Conn, integraClient *integra.Client) {\n\tfor {\n\t\tmessage, err := integraClient.Receive()\n\t\tif err != nil {\n\t\t\tif *verbose {\n\t\t\t\tlog.Println(\"Receive failed:\", err)\n\t\t\t\tlog.Println(\"Closing websocket\")\n\t\t\t}\n\t\t\t_ = wsConn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\treturn\n\t\t}\n\t\terr = wsConn.WriteJSON(message)\n\t\tif err != nil {\n\t\t\tlog.Println(\"WriteJSON failed:\", err)\n\t\t\tlog.Println(\"Closing websocket\")\n\t\t\t_ = wsConn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\treturn\n\t\t}\n\t}\n}" ]
[ "0.6909302", "0.68113315", "0.6766838", "0.6753222", "0.6626202", "0.66035175", "0.6556864", "0.6526347", "0.65038013", "0.64528245", "0.64516246", "0.6439596", "0.6414564", "0.6411506", "0.6399498", "0.63830733", "0.6383055", "0.63786024", "0.63679075", "0.6355151", "0.63472146", "0.63457376", "0.6327721", "0.63255095", "0.6312541", "0.6312366", "0.63108015", "0.6309334", "0.63015884", "0.626201", "0.6235054", "0.62215257", "0.6215689", "0.61799526", "0.6176832", "0.61740726", "0.6166632", "0.61647177", "0.61603385", "0.61602414", "0.61484045", "0.614239", "0.6140614", "0.61366504", "0.61337674", "0.6129595", "0.6105717", "0.61011386", "0.60999197", "0.6091537", "0.607768", "0.60729355", "0.6067264", "0.6063744", "0.605758", "0.6036927", "0.60356945", "0.60335284", "0.6028499", "0.6018651", "0.6013781", "0.60019004", "0.60015607", "0.60010266", "0.59892386", "0.59848017", "0.5980482", "0.59785247", "0.5978015", "0.59753215", "0.5972979", "0.5972589", "0.59613425", "0.59602815", "0.5957154", "0.5956528", "0.5946028", "0.5945396", "0.5937698", "0.5926337", "0.59226197", "0.5918543", "0.5911304", "0.5902749", "0.5900002", "0.58979964", "0.58959544", "0.5894329", "0.58928114", "0.58793956", "0.58690464", "0.58689266", "0.58665586", "0.5857521", "0.5855297", "0.5852949", "0.58503234", "0.58453035", "0.58434963", "0.5838446" ]
0.58464557
97
NewDiamond builds a new diamond instance. The default diamond gets populated with a random KSUID as diamondID. Default diamond has cnflicts handling enabled.
func NewDiamond(repo string, stores context2.Stores, opts ...DiamondOption) *Diamond { diamond := defaultDiamond(repo, stores) for _, apply := range opts { apply(diamond) } if diamond.deconflicter == nil { // points to the appropriate metadata path rendering function from model, // depending on the conflicts handling mode selected. switch diamond.DiamondDescriptor.Mode { case model.EnableCheckpoints: diamond.deconflicter = model.GenerateCheckpointPath case model.ForbidConflicts: diamond.deconflicter = func(a, b string) string { diamond.l.Error("dev error: deconflicter called in inadequate context", zap.String("arg", a), zap.String("arg", b)) panic("dev error: must not call deconflicter") } case model.EnableConflicts: fallthrough default: diamond.deconflicter = model.GenerateConflictPath } } if diamond.DiamondDescriptor.Tag != "" { diamond.l = diamond.l.With(zap.String("tag", diamond.DiamondDescriptor.Tag)) diamond.Bundle.l = diamond.l } if diamond.MetricsEnabled() { diamond.m = diamond.EnsureMetrics("core", &M{}).(*M) } return diamond }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CreateDiamond(repo string, stores context2.Stores, opts ...DiamondOption) (model.DiamondDescriptor, error) {\n\tvar err error\n\td := NewDiamond(repo, stores, opts...)\n\n\tdefer func(t0 time.Time) {\n\t\tif d.MetricsEnabled() {\n\t\t\td.m.Usage.UsedAll(t0, \"CreateDiamond\")(err)\n\t\t}\n\t}(time.Now())\n\n\tif d.DiamondDescriptor.DiamondID == \"\" {\n\t\treturn model.DiamondDescriptor{}, errors.New(\"a diamond must have a diamondID\")\n\t}\n\n\tif err = RepoExists(repo, stores); err != nil {\n\t\treturn model.DiamondDescriptor{}, err\n\t}\n\n\terr = d.uploadDescriptor()\n\tif err != nil {\n\t\treturn model.DiamondDescriptor{},\n\t\t\terrors.New(\"cannot update diamond descriptor\").Wrap(err)\n\t}\n\treturn d.DiamondDescriptor, nil\n}", "func buildDiamond(cfgraph *CFG, start int) int {\n\tbb0 := start\n\tNewBasicBlockEdge(cfgraph, bb0, bb0+1)\n\tNewBasicBlockEdge(cfgraph, bb0, bb0+2)\n\tNewBasicBlockEdge(cfgraph, bb0+1, bb0+3)\n\tNewBasicBlockEdge(cfgraph, bb0+2, bb0+3)\n\n\treturn bb0 + 3\n}", "func (in *Diamond) DeepCopy() *Diamond {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Diamond)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func DiamondID(id string) DiamondDescriptorOption {\n\treturn func(d *DiamondDescriptor) {\n\t\tif id != \"\" {\n\t\t\td.DiamondID = id\n\t\t}\n\t}\n}", "func GetDiamond(repo, diamondID string, stores context2.Stores, opts ...DiamondOption) (model.DiamondDescriptor, error) {\n\tvar err error\n\n\tgetOpts := []DiamondOption{\n\t\tDiamondDescriptor(\n\t\t\tmodel.NewDiamondDescriptor(model.DiamondID(diamondID)),\n\t\t),\n\t}\n\tgetOpts = append(getOpts, opts...)\n\n\td := NewDiamond(repo, stores, getOpts...)\n\n\tdefer func(t0 time.Time) {\n\t\tif d.MetricsEnabled() {\n\t\t\td.m.Usage.UsedAll(t0, \"GetDiamond\")(err)\n\t\t}\n\t}(time.Now())\n\n\tif err = RepoExists(repo, stores); err != nil {\n\t\treturn model.DiamondDescriptor{}, err\n\t}\n\n\tif err = d.downloadDescriptor(); err != nil {\n\t\treturn model.DiamondDescriptor{}, err\n\t}\n\treturn d.DiamondDescriptor, nil\n}", "func NewGarden(diagram string, children []string) (*Garden, error) {\n\t// Normalize the diagram.\n\tdiagramTrimmed := strings.Trim(diagram, \"\\n\")\n\tif diagramTrimmed == diagram {\n\t\treturn nil, errors.New(\"diagram didn't start with a newline\")\n\t}\n\trows := strings.Split(diagramTrimmed, \"\\n\")\n\tif len(rows) != 2 {\n\t\treturn nil, errors.New(\"invalid number of rows in diagram\")\n\t}\n\tif len(rows[0]) != len(rows[1]) {\n\t\treturn nil, errors.New(\"diagram row lengths do not match\")\n\t}\n\tif len(rows[0]) != 2*len(children) {\n\t\treturn nil, errors.New(\"diagram rows are not the correct length\")\n\t}\n\tfor i := 0; i < len(rows[0]); i++ {\n\t\tc1 := rows[0][i]\n\t\tc2 := rows[1][i]\n\t\tif c1 != 'G' && c1 != 'C' && c1 != 'R' && c1 != 'V' {\n\t\t\treturn nil, errors.New(\"invalid symbol in diagram\")\n\t\t}\n\t\tif c2 != 'G' && c2 != 'C' && c2 != 'R' && c2 != 'V' {\n\t\t\treturn nil, errors.New(\"invalid symbol in diagram\")\n\t\t}\n\t}\n\t// Make a copy of the input array and sort it.\n\tchildrenCopy := make([]string, len(children))\n\tcopy(childrenCopy, children)\n\tsort.Strings(childrenCopy)\n\t// Make sure all children are unique.\n\tfor i := 1; i < len(childrenCopy); i++ {\n\t\tif childrenCopy[i-1] == childrenCopy[i] {\n\t\t\treturn nil, errors.New(\"same child name seen more than once\")\n\t\t}\n\t}\n\t// Add each child to the Garden, and their plants.\n\tg := make(Garden)\n\tfor i, r := range rows[0] {\n\t\tchildName := childrenCopy[i/2]\n\t\tg[childName] = append(g[childName], lookupPlant(r))\n\t}\n\tfor i, r := range rows[1] {\n\t\tchildName := childrenCopy[i/2]\n\t\tg[childName] = append(g[childName], lookupPlant(r))\n\t}\n\treturn &g, nil\n}", "func NewGarden(diagram string, children []string) (*Garden, error) {\n\tg := &Garden{}\n\n\tg.children = make([]string, len(children))\n\tcopy(g.children, children)\n\tsort.Strings(g.children)\n\n\tg.diagram = strings.Split(diagram, \"\\n\")\n\tif len(g.diagram) != 3 {\n\t\treturn nil, errors.New(\"bad diagram\")\n\t}\n\n\tif len(g.diagram[1])%2 != 0 || len(g.diagram[2])%2 != 0 {\n\t\treturn nil, errors.New(\"bad len diagram\")\n\t}\n\n\tif strings.ToLower(g.diagram[1]) == g.diagram[1] || strings.ToLower(g.diagram[2]) == g.diagram[2] {\n\t\treturn nil, errors.New(\"bad caps diagram\")\n\t}\n\n\tg.indexes = make(map[string]int, len(g.children))\n\tfor i, c := range g.children {\n\t\tif c == \"\" {\n\t\t\treturn nil, errors.New(\"no children\")\n\t\t}\n\t\tif _, ok := g.indexes[c]; ok {\n\t\t\treturn nil, errors.New(\"children exists\")\n\t\t}\n\t\tg.indexes[c] = i + 1\n\t}\n\n\treturn g, nil\n}", "func NewDrand(s key.Store, g *key.Group, c *Config) (*Drand, error) {\n\td, err := initDrand(s, c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdkgConf := &dkg.Config{\n\t\tSuite: key.G2.(dkg.Suite),\n\t\tGroup: g,\n\t\tTimeout: d.opts.dkgTimeout,\n\t}\n\td.dkg, err = dkg.NewHandler(d.priv, dkgConf, d.dkgNetwork())\n\td.group = g\n\treturn d, err\n}", "func New(id string) (*D, error) {\n\tc := &mdcD.D{}\n\tif id == \"\" {\n\t\tid = DefaultID\n\t}\n\treturn &D{\n\t\tD: c,\n\t\tIdentity: id,\n\t\tRole: \"dialog\",\n\t\tAcceptBtn: \"Accept\",\n\t\tCancelBtn: \"Deny\",\n\t}, nil\n}", "func newDam() *dam {\n\treturn &dam{\n\t\tlock: sync.RWMutex{},\n\t\tbarrier: make(chan error),\n\t}\n}", "func NewDiamClient(opt *DiamOpt) *DiamClient {\n\tcfg := &sm.Settings{\n\t\tOriginHost: datatype.DiameterIdentity(opt.originHost),\n\t\tOriginRealm: datatype.DiameterIdentity(opt.originRealm),\n\t\tVendorID: datatype.Unsigned32(opt.vendorID),\n\t\tProductName: datatype.UTF8String(opt.productName),\n\t\tOriginStateID: datatype.Unsigned32(time.Now().Unix()),\n\t\tFirmwareRevision: datatype.Unsigned32(opt.firmwareRevision),\n\t\tHostIPAddresses: []datatype.Address{\n\t\t\tdatatype.Address(net.ParseIP(opt.hostAddress)),\n\t\t},\n\t}\n\n\tmux := sm.New(cfg)\n\n\tcli := &sm.Client{\n\t\tDict: dict.Default,\n\t\tHandler: mux,\n\t\tMaxRetransmits: 0,\n\t\tRetransmitInterval: time.Second,\n\t\tEnableWatchdog: true,\n\t\tWatchdogInterval: time.Duration(opt.watchdogInterval) * time.Second,\n\t\tSupportedVendorID: []*diam.AVP{\n\t\t\tdiam.NewAVP(avp.SupportedVendorID, avp.Mbit, 0, datatype.Unsigned32(opt.vendorID)),\n\t\t},\n\t\tVendorSpecificApplicationID: []*diam.AVP{\n\t\t\tdiam.NewAVP(avp.VendorSpecificApplicationID, avp.Mbit, 0, &diam.GroupedAVP{\n\t\t\t\tAVP: []*diam.AVP{\n\t\t\t\t\tdiam.NewAVP(avp.AuthApplicationID, avp.Mbit, 0, datatype.Unsigned32(opt.AppID())),\n\t\t\t\t\tdiam.NewAVP(avp.VendorID, avp.Mbit, 0, datatype.Unsigned32(opt.vendorID)),\n\t\t\t\t},\n\t\t\t}),\n\t\t},\n\t}\n\n\tdone := make(chan struct{}, 1000)\n\tmux.HandleIdx(\n\t\tdiam.CommandIndex{AppID: diam.TGPP_S6A_APP_ID, Code: diam.AuthenticationInformation, Request: false},\n\t\thandleAuthenticationInformationAnswer(done))\n\tmux.HandleIdx(\n\t\tdiam.CommandIndex{AppID: diam.TGPP_S6A_APP_ID, Code: diam.UpdateLocation, Request: false},\n\t\thandleUpdateLocationAnswer(done))\n\tmux.HandleIdx(diam.ALL_CMD_INDEX, handleAll())\n\n\treturn &DiamClient{\n\t\tcli: cli,\n\t\topt: opt,\n\t\tcfg: cfg,\n\t\tdone: done,\n\t}\n}", "func (d *DiamondMiner) doAutoBidForMyDiamond() {\n\t//fmt.Println(\"- doAutoBidForMyDiamond\")\n\n\tfirstFeeTxs := d.txpool.GetDiamondCreateTxs(1) // 取出第一枚钻石挖掘交易\n\tif firstFeeTxs == nil || len(firstFeeTxs) == 0 {\n\t\treturn // No diamonds\n\t}\n\tfirstFeeTx := firstFeeTxs[0]\n\t// Address to give up competition\n\tfor _, iaddr := range d.Config.AutoBidIgnoreAddresses {\n\t\tif bytes.Compare(firstFeeTx.GetAddress(), *iaddr) == 0 {\n\t\t\tif !d.Config.Continued {\n\t\t\t\t// In case of discontinuous mining, stop the mining of this machine\n\t\t\t\t//fmt.Println(\"diamond miner stop all, because fee addr:\", iaddr.ToReadable())\n\t\t\t\td.StopAll()\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\t// I came first\n\tif bytes.Compare(firstFeeTx.GetAddress(), d.Config.FeeAccount.Address) == 0 {\n\t\tif !d.Config.Continued {\n\t\t\t// In case of discontinuous mining, stop the mining of this machine\n\t\t\t//fmt.Println(\"diamond miner stop all, because fee addr:\", firstFeeTx.GetAddress().ToReadable())\n\t\t\td.StopAll()\n\t\t}\n\t\treturn\n\t}\n\tif d.currentSuccessMiningDiamondTx == nil {\n\t\treturn\n\t}\n\t// Compare diamond serial numbers\n\tcuract := transactions.CheckoutAction_4_DiamondCreateFromTx(d.currentSuccessMiningDiamondTx)\n\tfirstact := transactions.CheckoutAction_4_DiamondCreateFromTx(firstFeeTx.(interfacev2.Transaction))\n\tif curact == nil || firstact == nil {\n\t\treturn\n\t}\n\tif curact.Number != firstact.Number {\n\t\td.currentSuccessMiningDiamondTx = nil // Invalid mining\n\t\treturn\n\t}\n\n\t// Start bidding\n\ttopfee := firstFeeTx.GetFee()\n\tmyfee, e1 := topfee.Add(d.Config.AutoBidMarginFee)\n\tif e1 != nil {\n\t\tfmt.Println(\"doAutoBidForMyDiamond Error:\", e1)\n\t\treturn\n\t}\n\tif newmyfee, _, e2 := myfee.CompressForMainNumLen(4, true); e2 == nil && newmyfee != nil {\n\t\tmyfee = newmyfee // Up compression length\n\t}\n\t// Is it higher than the maximum price I set\n\tif d.Config.AutoBidMaxFee.LessThan(topfee) {\n\t\treturn\n\t}\n\tif d.Config.AutoBidMaxFee.LessThan(myfee) {\n\t\tmyfee = d.Config.AutoBidMaxFee // The highest price has been reached\n\t}\n\n\t// Update transaction fee\n\tnewtx := d.currentSuccessMiningDiamondTx\n\tnewtx.SetFee(myfee)\n\tnewtx.ClearHash() // Reset hash cache\n\t// Private key\n\tallPrivateKeyBytes := make(map[string][]byte, 1)\n\tallPrivateKeyBytes[string(d.Config.FeeAccount.Address)] = d.Config.FeeAccount.PrivateKey\n\t// do sign\n\tnewtx.FillNeedSigns(allPrivateKeyBytes, nil)\n\t// add to pool\n\terr4 := d.txpool.AddTx(newtx.(interfaces.Transaction))\n\tif err4 != nil {\n\t\tfmt.Println(\"doAutoBidForMyDiamond Add to Tx Pool, Error: \", err4.Error())\n\t\treturn\n\t}\n\n\t// success\n\tfmt.Printf(\"diamond auto bid name: <%s>, tx: <%s>, fee: %s => %s \\n\",\n\t\tstring(curact.Diamond), newtx.Hash().ToHex(),\n\t\ttopfee.ToFinString(), myfee.ToFinString(),\n\t)\n}", "func DiamondClone(m DiamondDescriptor) DiamondDescriptorOption {\n\treturn func(d *DiamondDescriptor) {\n\t\t*d = m\n\t}\n}", "func NewDiscriminator(disc *low.Discriminator) *Discriminator {\n\td := new(Discriminator)\n\td.low = disc\n\td.PropertyName = disc.PropertyName.Value\n\tmapping := make(map[string]string)\n\tfor k, v := range disc.Mapping.Value {\n\t\tmapping[k.Value] = v.Value\n\t}\n\td.Mapping = mapping\n\treturn d\n}", "func NewDI() DIer {\n\td := new(DI)\n\td.store = make(map[string]interface{})\n\treturn d\n}", "func NewD(opts ...Option) *D {\n\td := &D{\n\t\tconfig: DefaultConfig(),\n\t\tdata: newData(),\n\t\tstopCh: make(chan struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(d)\n\t}\n\n\treturn d\n}", "func newDiseaseMutation(c config, op Op, opts ...diseaseOption) *DiseaseMutation {\n\tm := &DiseaseMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeDisease,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func newDiseaseMutation(c config, op Op, opts ...diseaseOption) *DiseaseMutation {\n\tm := &DiseaseMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeDisease,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func NewDog(color string, height int, name string) Dog {\n\treturn Dog{color: color, height: height, name: name}\n}", "func NewDex(creator Name, staking Coins, description string) *Dex {\n\treturn &Dex{\n\t\tCreator: creator,\n\t\tStaking: staking,\n\t\tDescription: description,\n\t}\n}", "func (in *DiamondSpec) DeepCopy() *DiamondSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DiamondSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DiamondConfig) DeepCopy() *DiamondConfig {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DiamondConfig)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func DiamondTag(tag string) DiamondDescriptorOption {\n\treturn func(d *DiamondDescriptor) {\n\t\td.Tag = tag\n\t}\n}", "func NewForkingDigesterMock(t minimock.Tester) *ForkingDigesterMock {\n\tm := &ForkingDigesterMock{t: t}\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.AddNextMock = mForkingDigesterMockAddNext{mock: m}\n\tm.AddNextMock.callArgs = []*ForkingDigesterMockAddNextParams{}\n\n\tm.FinishSequenceMock = mForkingDigesterMockFinishSequence{mock: m}\n\n\tm.ForkSequenceMock = mForkingDigesterMockForkSequence{mock: m}\n\n\tm.GetDigestMethodMock = mForkingDigesterMockGetDigestMethod{mock: m}\n\n\tm.GetDigestSizeMock = mForkingDigesterMockGetDigestSize{mock: m}\n\n\treturn m\n}", "func New() ID {\n\treturn dgen.New()\n}", "func New(\n\tdatabaseContext model.DBReader,\n\tdagTopologyManager model.DAGTopologyManager,\n\tghostdagDataStore model.GHOSTDAGDataStore,\n\theaderStore model.BlockHeaderStore,\n\tk model.KType) model.GHOSTDAGManager {\n\n\treturn &ghostdagHelper{\n\t\tdbAccess: databaseContext,\n\t\tdagTopologyManager: dagTopologyManager,\n\t\tdataStore: ghostdagDataStore,\n\t\theaderStore: headerStore,\n\t\tk: k,\n\t}\n}", "func NewIGD() (igd IGD, err error) {\n\tigd, err = NewUpnpIGD()\n\tif err != nil {\n\t\tlog.Debugf(\"Unable to initialize UPnP IGD, falling back to NAT-PMP: %s\", err)\n\t\tigd, err = NewNATPMPIGD()\n\t}\n\treturn\n}", "func newDHT(r *Router) *dht {\n\td := &dht{\n\t\tr: r,\n\t\tfinger: make(map[types.PublicKey]dhtEntry),\n\t}\n\treturn d\n}", "func New(pc chan []string) *Drawer {\n\td := Drawer{nil, nil, nil, nil}\n\td.list = ld.New(pc)\n\td.sparkline = sd.New(pc)\n\td.table = td.New(pc)\n\td.packetChannel = pc\n\n\treturn &d\n}", "func NewDigester(opts ...digester.Option) (*Digester, error) {\n\tropts := digester.Options{}\n\tfor _, apply := range opts {\n\t\tapply(&ropts)\n\t}\n\n\treturn &Digester{\n\t\topts: ropts,\n\t}, nil\n}", "func New() *deck.Deck {\n\tn := *d\n\treturn &n\n}", "func newHammer() *cobra.Command {\n\tvar cluster []string\n\tvar dbName string\n\tvar id int\n\tvar count int\n\n\tcmd := &cobra.Command{\n\t\tUse: \"hammer\",\n\t\tShort: \"load test the database.\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tfmt.Println(\"defaultLogLevel:\", defaultLogLevel)\n\t\t\tlogger := NewLogFunc(defaultLogLevel, \"hammy:: \", log.Writer())\n\t\t\tlogger(LogDebug, \"checking hammer logger\")\n\t\t\thammer(&globalKeys, id, count, logger, dbName, cluster...)\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\tflags.StringSliceVarP(&cluster, \"cluster\", \"c\", clusterList(), \"addresses of existing cluster nodes\")\n\tflags.StringVarP(&dbName, \"database\", \"d\", envy.StringDefault(\"DQLITED_DB\", defaultDatabase), \"name of database to use\")\n\tflags.IntVarP(&count, \"count\", \"n\", 10000, \"how many times to repeat\")\n\tflags.IntVarP(&id, \"id\", \"i\", envy.IntDefault(\"DQLITED_ID\", 1), \"server id\")\n\n\treturn cmd\n}", "func NewDn(value string) Dn {\n\tdn := Dn{\n\t\tValue: value,\n\t}\n\n\treturn dn\n}", "func (in *DiamondList) DeepCopy() *DiamondList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DiamondList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func NewDGraph(adjacencyList AdjacencyList) (*DGraph, error) {\n\tresult := new(DGraph)\n\tresult.Set = make(Set, len(adjacencyList))\n\n\t// two phases:\n\t//\n\t// Phase 1: create nodes for all the keys in the adjacencyList and\n\t// store them in result.nodes. They wont have any children yet.\n\tfor nodeKey, _ := range adjacencyList {\n\t\tresult.Add(&Node{\n\t\t\tKey: nodeKey,\n\t\t})\n\t}\n\n\t// Phase 2: go again over every key in the adjacencyList, adding\n\t// children to each node.\n\tfor parentKey, childrenKeys := range adjacencyList {\n\t\tparent, _ := result.Get(parentKey)\n\t\tparent.Children = make(Set, len(childrenKeys))\n\n\t\tfor _, k := range childrenKeys {\n\t\t\tchildren, ok := result.Get(k)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unknown children %s in node %s\",\n\t\t\t\t\tk, parentKey)\n\t\t\t}\n\n\t\t\tparent.Children.Add(children)\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func NewDMG(path string, opts ...DMGOption) (*DMG, error) {\n\td := &DMG{\n\t\tdmgpath: path,\n\t\tlogger: log.New(os.Stderr, \"test\", 1),\n\t}\n\tfor _, opt := range opts {\n\t\topt(d)\n\t}\n\n\targs := []string{\"imageinfo\", d.dmgpath, \"-plist\"}\n\tout, err := exec.Command(\"/usr/bin/hdiutil\", args...).Output()\n\tdata := bytes.Replace(out, []byte(`<integer>-1</integer>`), []byte(`<string>-1</string>`), -1)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to get the info from dmg : %s\", err)\n\t}\n\tvar diskInfo BackingStoreInfo\n\terr = plist.Unmarshal(data, &diskInfo)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to read disk info: %s\", err)\n\t}\n\td.ImageInfo = diskInfo\n\treturn d, nil\n}", "func (f *Framework) NewDiagnosis(name, ns, nodeName, operationSet string) *diagnosisv1.Diagnosis {\n\n\treturn &diagnosisv1.Diagnosis{\n\t\tTypeMeta: metav1.TypeMeta{},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: fmt.Sprintf(\"%v-%v\", name, RandomSuffix()),\n\t\t\tNamespace: ns,\n\t\t\tLabels: map[string]string{\n\t\t\t\tf.SelectorKey: name,\n\t\t\t},\n\t\t},\n\t\tSpec: diagnosisv1.DiagnosisSpec{NodeName: nodeName, OperationSet: operationSet},\n\t\tStatus: diagnosisv1.DiagnosisStatus{},\n\t}\n}", "func DiamondExists(repo, diamondID string, stores context2.Stores) error {\n\texists, err := GetDiamondStore(stores).Has(context.Background(), model.GetArchivePathToInitialDiamond(repo, diamondID))\n\tif err != nil {\n\t\treturn errors.New(\"failed to retrieve diamond from store\").Wrap(err)\n\t}\n\tif !exists {\n\t\treturn errors.New(\"diamond validation\").WrapMessage(\"diamond %s doesn't exist for repo %s \", diamondID, repo)\n\t}\n\treturn nil\n}", "func NewDialedKlient(opts KlientOptions) (*Klient, error) {\n\tc, err := CreateKlientClient(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := c.Dial(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewKlient(c), nil\n}", "func New() *Dqueue {\n\treturn &Dqueue{\n\t\tdqueue: &doublelinkedlist.DoubleLinkedList{},\n\t}\n}", "func NewDkgGroup(dishonestThreshold int, size int) *Group {\n\tmemberIDs := make([]MemberIndex, size)\n\tfor i := 0; i < size; i++ {\n\t\tmemberIDs[i] = MemberIndex(i + 1)\n\t}\n\n\treturn &Group{\n\t\tdishonestThreshold: dishonestThreshold,\n\t\tdisqualifiedMemberIDs: []MemberIndex{},\n\t\tinactiveMemberIDs: []MemberIndex{},\n\t\tmemberIDs: memberIDs,\n\t}\n}", "func NewGenerateTransportDgd(name string, gorillaMux bool, transport string, methods []string) Gen {\n\ti := &GenerateTransportDgd{\n\t\tname: name,\n\t\tgorillaMux: gorillaMux,\n\t\tinterfaceName: utils.ToCamelCase(name + \"Service\"),\n\t\tdestPath: fmt.Sprintf(viper.GetString(\"gk_service_path_format\"), utils.ToLowerSnakeCase2(name)),\n\t\tmethods: methods,\n\t}\n\ti.filePath = path.Join(i.destPath, viper.GetString(\"gk_service_file_name\"))\n\ti.transport = transport\n\t// Not used.\n\ti.srcFile = jen.NewFilePath(\"\")\n\ti.InitPg()\n\t//\n\ti.fs = fs.Get()\n\treturn i\n}", "func NewDfdd(context *Context, timeSource common.TimeSource) Dfdd {\n\tdfdd := &dfddImpl{\n\t\tcontext: context,\n\t\ttimeSource: timeSource,\n\t\tshutdownC: make(chan struct{}),\n\t\tinputListenerCh: make(chan *common.RingpopListenerEvent, listenerChannelSize),\n\t\tstoreListenerCh: make(chan *common.RingpopListenerEvent, listenerChannelSize),\n\t}\n\tdfdd.inputHosts.Store(make(map[string]dfddHost, 8))\n\tdfdd.storeHosts.Store(make(map[string]dfddHost, 8))\n\treturn dfdd\n}", "func NewContainerd() (*Containerd, error) {\n client := new(Containerd)\n\n Logger.Info(\"Connecting to containerd\")\n if c, err := containerd.New(ContainerdSocketPath); err != nil {\n return nil, err\n } else {\n Logger.Info(\"Connected to containerd as client\")\n client.Client = c\n }\n\n Logger.Info(\"Creating containerd client context\")\n client.Context = namespaces.WithNamespace(context.Background(),\n ContainerdNamespace)\n\n return client, nil\n}", "func DiamondMode(mode ConflictMode) DiamondDescriptorOption {\n\treturn func(d *DiamondDescriptor) {\n\t\td.Mode = mode\n\t}\n}", "func New(me protocol.PeerAddress, codec protocol.PeerAddressCodec, store kv.Table, bootstrapAddrs ...protocol.PeerAddress) (DHT, error) {\n\t// Validate input parameters\n\tif me == nil {\n\t\tpanic(\"pre-condition violation: self PeerAddress cannot be nil\")\n\t}\n\tif codec == nil {\n\t\tpanic(\"pre-condition violation: PeerAddressCodec cannot be nil\")\n\t}\n\n\t// Create a in-memory store if user doesn't provide one.\n\tif store == nil {\n\t\tstore = kv.NewTable(kv.NewMemDB(kv.GobCodec), \"dht\")\n\t}\n\n\tdht := &dht{\n\t\tme: me,\n\t\tcodec: codec,\n\t\tstore: store,\n\n\t\tgroupsMu: new(sync.RWMutex),\n\t\tgroups: map[protocol.GroupID]protocol.PeerIDs{},\n\n\t\tinMemCacheMu: new(sync.RWMutex),\n\t\tinMemCache: map[string]protocol.PeerAddress{},\n\t}\n\n\tif err := dht.fillInMemCache(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn dht, dht.addBootstrapNodes(bootstrapAddrs)\n}", "func TestTransactionGraphDiamond(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\t// Create a transaction pool tester.\n\ttpt, err := createTpoolTester(t.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer tpt.Close()\n\n\t// Create a transaction sending money to an output that TransactionGraph can\n\t// spent (the empty UnlockConditions).\n\ttxns, err := tpt.wallet.SendSiacoins(types.SiacoinPrecision.Mul64(100), types.UnlockConditions{}.UnlockHash())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Get the output of that transaction.\n\tgraphSourceOutputID := txns[len(txns)-1].SiacoinOutputID(0)\n\tvar edges []types.TransactionGraphEdge\n\tsources := []int{0, 0, 1, 2}\n\tdests := []int{1, 2, 3, 3}\n\tvalues := []uint64{40, 40, 30, 30}\n\tfees := []uint64{10, 10, 10, 10}\n\tfor i := range sources {\n\t\tedges = append(edges, types.TransactionGraphEdge{\n\t\t\tDest: dests[i],\n\t\t\tFee: types.SiacoinPrecision.Mul64(fees[i]),\n\t\t\tSource: sources[i],\n\t\t\tValue: types.SiacoinPrecision.Mul64(values[i]),\n\t\t})\n\t}\n\tgraphTxns, err := types.TransactionGraph(graphSourceOutputID, edges)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(graphTxns) != 3 {\n\t\tt.Fatal(\"wrong number of tranasctions produced\")\n\t}\n\terr = tpt.tpool.AcceptTransactionSet(graphTxns)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func NewDaisyInflater(args ImportArguments, fileInspector imagefile.Inspector) (Inflater, error) {\n\tdiskName := \"disk-\" + args.ExecutionID\n\tvar wfPath string\n\tvar vars map[string]string\n\tvar inflationDiskIndex int\n\tif isImage(args.Source) {\n\t\twfPath = inflateImagePath\n\t\tvars = map[string]string{\n\t\t\t\"source_image\": args.Source.Path(),\n\t\t\t\"disk_name\": diskName,\n\t\t}\n\t\tinflationDiskIndex = 0 // Workflow only uses one disk.\n\t} else {\n\t\twfPath = inflateFilePath\n\t\tvars = createDaisyVarsForFile(args, fileInspector, diskName)\n\t\tinflationDiskIndex = 1 // First disk is for the worker\n\t}\n\n\twf, err := daisycommon.ParseWorkflow(path.Join(args.WorkflowDir, wfPath), vars,\n\t\targs.Project, args.Zone, args.ScratchBucketGcsPath, args.Oauth, args.Timeout.String(), args.ComputeEndpoint,\n\t\targs.GcsLogsDisabled, args.CloudLogsDisabled, args.StdoutLogsDisabled)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor k, v := range vars {\n\t\twf.AddVar(k, v)\n\t}\n\n\tdaisyUtils.UpdateAllInstanceNoExternalIP(wf, args.NoExternalIP)\n\tif args.UefiCompatible {\n\t\taddFeatureToDisk(wf, \"UEFI_COMPATIBLE\", inflationDiskIndex)\n\t}\n\tif strings.Contains(args.OS, \"windows\") {\n\t\taddFeatureToDisk(wf, \"WINDOWS\", inflationDiskIndex)\n\t}\n\n\t// Temporary fix to ensure gcloud shows daisy's output.\n\t// A less fragile approach is tracked in b/161567644.\n\twf.Name = LogPrefix\n\treturn &daisyInflater{\n\t\twf: wf,\n\t\tinflatedDiskURI: fmt.Sprintf(\"zones/%s/disks/%s\", args.Zone, diskName),\n\t}, nil\n}", "func NewHdd() *Hdd {\n\tthis := Hdd{}\n\treturn &this\n}", "func (g Generator) NewDoctor(c *pathway.Consultant) *ir.Doctor {\n\tif c == nil {\n\t\treturn g.doctors.GetRandomDoctor()\n\t}\n\tif doctor := g.doctors.GetByID(*c.ID); doctor != nil {\n\t\treturn doctor\n\t}\n\tnewDoctor := &ir.Doctor{\n\t\t// A valid pathway.Consultant has all the fields set, so we can just dereference.\n\t\tID: *c.ID,\n\t\tSurname: *c.Surname,\n\t\tPrefix: *c.Prefix,\n\t\tFirstName: *c.FirstName,\n\t\tSpecialty: g.messageConfig.HospitalService,\n\t}\n\tg.doctors.Add(newDoctor)\n\treturn newDoctor\n}", "func MockDiamondWorkflow(hd *hood.Hood) *Workflow {\n\tworkflow := MockWorkflow(hd)\n\tj1 := MockProtojob(hd, workflow)\n\tj2 := MockProtojob(hd, workflow)\n\tj3 := MockProtojob(hd, workflow)\n\tj4 := MockProtojob(hd, workflow)\n\te1 := MockWorkflowEdge(hd, j1, j2)\n\te2 := MockWorkflowEdge(hd, j1, j3)\n\te3 := MockWorkflowEdge(hd, j2, j4)\n\te4 := MockWorkflowEdge(hd, j3, j4)\n\n\tworkflowBatch := MockWorkflowBatch(hd, workflow)\n\trdd1 := MockRdd(hd, workflowBatch, j1)\n\trdd2 := MockRdd(hd, workflowBatch, j2)\n\trdd3 := MockRdd(hd, workflowBatch, j3)\n\trdd4 := MockRdd(hd, workflowBatch, j4)\n\tMockRddEdge(hd, rdd1, rdd2, e1)\n\tMockRddEdge(hd, rdd1, rdd3, e2)\n\tMockRddEdge(hd, rdd2, rdd4, e3)\n\tMockRddEdge(hd, rdd3, rdd4, e4)\n\n\tw1 := MockWorker(hd)\n\tw2 := MockWorker(hd)\n\n\t// Place a segment for every rdd on every worker\n\trdds := []*Rdd{rdd1, rdd2, rdd3, rdd4}\n\tworkers := []*Worker{w1, w2}\n\tfor _, rdd := range rdds {\n\t\tfor _, worker := range workers {\n\t\t\tMockSegment(hd, rdd, worker)\n\t\t}\n\t}\n\n\treturn workflow\n}", "func New(hasher func(v interface{}) uint32) *Dtrie {\n\tif hasher == nil {\n\t\thasher = defaultHasher\n\t}\n\treturn &Dtrie{\n\t\troot: emptyNode(0, 32),\n\t\thasher: hasher,\n\t}\n}", "func NewDijkstra(g *graph, s, t int) *Dijkstra {\n\treturn &Dijkstra{\n\t\tgraph: g,\n\t\tsource: s,\n\t\ttarget: t,\n\t\tfrontier: make(map[int]graphEdge),\n\t\tcost: make(map[int]float32),\n\t\tspt: make(map[int]graphEdge),\n\t}\n}", "func NewClientD(server string) pb.GPNSClient {\n\tconn, err := grpc.Dial(server, grpc.WithInsecure())\n\tif err != nil {\n\t\tlog.Fatal(\"connect to domestic rpc server failed\")\n\t}\n\tgo receiveChat()\n\treturn pb.NewGPNSClient(conn)\n}", "func newCommandDisconn(cli *client.Client) command {\n\treturn &commandDisconn{\n\t\tcli: cli,\n\t}\n}", "func NewDaddy() *Daddy {\n\treturn &Daddy{\n\t\tSon: make(map[string]*Assassin),\n\t\tSibling: make(map[string]*Sibling),\n\t}\n}", "func New(duration time.Duration) *Dam {\n\td := &Dam{\n\t\tstorage: make(map[string]*element),\n\t\ttickerDone: make(chan struct{}),\n\t}\n\tif duration > time.Duration(0) {\n\t\td.ticker = time.NewTicker(duration)\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-d.ticker.C:\n\t\t\t\t\td.Purge()\n\t\t\t\tcase <-d.tickerDone:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\treturn d\n}", "func NewDelegation(d *types.Delegation) *Delegation {\n\treturn &Delegation{Delegation: *d, cg: new(singleflight.Group)}\n}", "func (mdhdBoxFactory) New(box bmfcommon.Box) (cb bmfcommon.CommonBox, childBoxSeriesOffset int, err error) {\n\tdefer func() {\n\t\tif errRaw := recover(); errRaw != nil {\n\t\t\terr = log.Wrap(errRaw.(error))\n\t\t}\n\t}()\n\n\tmdhdBox := &MdhdBox{\n\t\tBox: box,\n\t}\n\n\terr = mdhdBox.parse()\n\tlog.PanicIf(err)\n\n\treturn mdhdBox, -1, nil\n}", "func NewKingdom(name string, emblem string) *kingdom {\n\treturn &kingdom{Name: name, Emblem: emblem}\n}", "func (d *devicelib) NewMigDeviceByUUID(uuid string) (MigDevice, error) {\n\tdev, ret := d.nvml.DeviceGetHandleByUUID(uuid)\n\tif ret != nvml.SUCCESS {\n\t\treturn nil, fmt.Errorf(\"error getting device handle for uuid '%v': %v\", uuid, ret)\n\t}\n\treturn d.NewMigDevice(dev)\n}", "func NewDefaultDialedKlient() (*Klient, error) {\n\treturn NewDialedKlient(NewKlientOptions())\n}", "func NewDfdd(context *Context) Dfdd {\n\treturn &dfddImpl{\n\t\tcontext: context,\n\t\tshutdownC: make(chan struct{}),\n\t\tinputListenerCh: make(chan *common.RingpopListenerEvent, listenerChannelSize),\n\t\tstoreListenerCh: make(chan *common.RingpopListenerEvent, listenerChannelSize),\n\t\tunhealthyStores: make(map[string]time.Time),\n\t\tunhealthyInputs: make(map[string]time.Time),\n\t\thostDownPeriodForStage2: hostDownPeriodForStage2,\n\t\thealthCheckInterval: healthCheckInterval,\n\t}\n}", "func DbGetPKIDsThatDiamondedYouMap(handle *badger.DB, yourPKID *PKID, fetchYouDiamonded bool) (\n\t_pkidToDiamondsMap map[PKID][]*DiamondEntry, _err error) {\n\n\tprefix := _dbSeekPrefixForPKIDsThatDiamondedYou(yourPKID)\n\tdiamondSenderStartIdx := 1 + btcec.PubKeyBytesLenCompressed\n\tdiamondSenderEndIdx := 1 + 2*btcec.PubKeyBytesLenCompressed\n\tdiamondReceiverStartIdx := 1\n\tdiamondReceiverEndIdx := 1 + btcec.PubKeyBytesLenCompressed\n\tif fetchYouDiamonded {\n\t\tprefix = _dbSeekPrefixForPKIDsThatYouDiamonded(yourPKID)\n\t\tdiamondSenderStartIdx = 1\n\t\tdiamondSenderEndIdx = 1 + btcec.PubKeyBytesLenCompressed\n\t\tdiamondReceiverStartIdx = 1 + btcec.PubKeyBytesLenCompressed\n\t\tdiamondReceiverEndIdx = 1 + 2*btcec.PubKeyBytesLenCompressed\n\t}\n\tkeysFound, valsFound := _enumerateKeysForPrefix(handle, prefix)\n\n\tpkidsToDiamondEntryMap := make(map[PKID][]*DiamondEntry)\n\tfor ii, keyBytes := range keysFound {\n\t\t// The DiamondEntry found must not be nil.\n\t\tdiamondEntry := _DbDiamondEntryForDbBuf(valsFound[ii])\n\t\tif diamondEntry == nil {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"DbGetPKIDsThatDiamondedYouMap: Found nil DiamondEntry for public key %v \"+\n\t\t\t\t\t\"and key bytes %#v when seeking; this should never happen\",\n\t\t\t\tPkToStringMainnet(yourPKID[:]), keyBytes)\n\t\t}\n\t\texpectedDiamondKeyLen := 1 + 2*btcec.PubKeyBytesLenCompressed + HashSizeBytes\n\t\tif len(keyBytes) != expectedDiamondKeyLen {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"DbGetPKIDsThatDiamondedYouMap: Invalid key length %v should be %v\",\n\t\t\t\tlen(keyBytes), expectedDiamondKeyLen)\n\t\t}\n\n\t\t// Note: The code below is mainly just sanity-checking. Checking the key isn't actually\n\t\t// needed in this function, since all the information is duplicated in the entry.\n\n\t\t// Chop out the diamond sender PKID.\n\t\tdiamondSenderPKIDBytes := keyBytes[diamondSenderStartIdx:diamondSenderEndIdx]\n\t\tdiamondSenderPKID := &PKID{}\n\t\tcopy(diamondSenderPKID[:], diamondSenderPKIDBytes)\n\t\t// It must match what's in the DiamondEntry\n\t\tif !reflect.DeepEqual(diamondSenderPKID, diamondEntry.SenderPKID) {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"DbGetPKIDsThatDiamondedYouMap: Sender PKID in DB %v did not \"+\n\t\t\t\t\t\"match Sender PKID in DiamondEntry %v; this should never happen\",\n\t\t\t\tPkToStringBoth(diamondSenderPKID[:]), PkToStringBoth(diamondEntry.SenderPKID[:]))\n\t\t}\n\n\t\t// Chop out the diamond receiver PKID\n\t\tdiamondReceiverPKIDBytes := keyBytes[diamondReceiverStartIdx:diamondReceiverEndIdx]\n\t\tdiamondReceiverPKID := &PKID{}\n\t\tcopy(diamondReceiverPKID[:], diamondReceiverPKIDBytes)\n\t\t// It must match what's in the DiamondEntry\n\t\tif !reflect.DeepEqual(diamondReceiverPKID, diamondEntry.ReceiverPKID) {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"DbGetPKIDsThatDiamondedYouMap: Receiver PKID in DB %v did not \"+\n\t\t\t\t\t\"match Receiver PKID in DiamondEntry %v; this should never happen\",\n\t\t\t\tPkToStringBoth(diamondReceiverPKID[:]), PkToStringBoth(diamondEntry.ReceiverPKID[:]))\n\t\t}\n\n\t\t// Chop out the diamond post hash.\n\t\tdiamondPostHashBytes := keyBytes[1+2*btcec.PubKeyBytesLenCompressed:]\n\t\tdiamondPostHash := &BlockHash{}\n\t\tcopy(diamondPostHash[:], diamondPostHashBytes)\n\t\t// It must match what's in the entry\n\t\tif *diamondPostHash != *diamondEntry.DiamondPostHash {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"DbGetPKIDsThatDiamondedYouMap: Post hash found in DB key %v \"+\n\t\t\t\t\t\"did not match post hash in DiamondEntry %v; this should never happen\",\n\t\t\t\tdiamondPostHash, diamondEntry.DiamondPostHash)\n\t\t}\n\n\t\t// If a map entry doesn't exist for this sender, create one.\n\t\tnewListOfEntrys := pkidsToDiamondEntryMap[*diamondSenderPKID]\n\t\tnewListOfEntrys = append(newListOfEntrys, diamondEntry)\n\t\tpkidsToDiamondEntryMap[*diamondSenderPKID] = newListOfEntrys\n\t}\n\n\treturn pkidsToDiamondEntryMap, nil\n}", "func New(\n\tdatabaseContext model.DBReader,\n\tdagTopologyManager model.DAGTopologyManager,\n\tghostdagDataStore model.GHOSTDAGDataStore,\n\theaderStore model.BlockHeaderStore,\n\tk externalapi.KType,\n\tgenesisHash *externalapi.DomainHash) model.GHOSTDAGManager {\n\n\treturn &ghostdagManager{\n\t\tdatabaseContext: databaseContext,\n\t\tdagTopologyManager: dagTopologyManager,\n\t\tghostdagDataStore: ghostdagDataStore,\n\t\theaderStore: headerStore,\n\t\tk: k,\n\t\tgenesisHash: genesisHash,\n\t}\n}", "func New() (*Containerd, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n\tdefer cancel()\n\n\tconn, err := grpc.DialContext(ctx, defaultContainerdAddress, grpc.WithInsecure(), grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(1024*1024*16)), grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {\n\t\treturn (&net.Dialer{}).DialContext(ctx, \"unix\", addr)\n\t}))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Containerd{\n\t\tconn: conn,\n\t}, nil\n}", "func New(configurator PackageConfigurator, store ScriptPersister) *Ankiddie {\n\tankiddie := &Ankiddie{\n\t\tenvs: make(map[uint]*Environment),\n\t\tstore: store,\n\t}\n\n\t// TODO because of how anko works, this will actually mess with the packages\n\t// for all envs on all Ankiddies, and not just this one\n\tif configurator != nil {\n\t\tconfigurator.ConfigurePackages(env.Packages, env.PackageTypes)\n\t}\n\treturn ankiddie\n}", "func NewDirectedGraph() *DirectedGraph {\n\treturn &DirectedGraph{make(map[string]value)}\n}", "func GenTxOutfeeQuantityDiamondTransfer(ctx ctx.Context, params []string) {\n\tif len(params) < 5 {\n\t\tfmt.Println(\"params not enough\")\n\t\treturn\n\t}\n\n\tfromAddressArgv := params[0]\n\ttoAddressArgv := params[1]\n\tdiamondsArgv := params[2]\n\tfeeAddressArgv := params[3]\n\tfeeArgv := params[4]\n\n\t// Check field\n\tdiamonds := strings.Split(diamondsArgv, \",\")\n\tif len(diamonds) > 200 {\n\t\tfmt.Printf(\"diamonds number is too much.\\n\")\n\t\treturn\n\t}\n\n\tfor _, diamond := range diamonds {\n\t\t_, dddok := x16rs.IsDiamondHashResultString(\"0000000000\" + diamond)\n\t\tif !dddok {\n\t\t\tfmt.Printf(\"%s is not diamond value.\\n\", diamond)\n\t\t\treturn\n\t\t}\n\t}\n\n\tfromaddress := ctx.IsInvalidAccountAddress(fromAddressArgv)\n\tif fromaddress == nil {\n\t\treturn\n\t}\n\n\ttoaddress := ctx.IsInvalidAccountAddress(toAddressArgv)\n\tif toaddress == nil {\n\t\treturn\n\t}\n\n\tfeeAddress := ctx.IsInvalidAccountAddress(feeAddressArgv)\n\tif feeAddress == nil {\n\t\treturn\n\t}\n\n\tfeeAmount := ctx.IsInvalidAmountString(feeArgv)\n\tif feeAmount == nil {\n\t\treturn\n\t}\n\n\t// Create action\n\tvar dimtransfer actions.Action_6_OutfeeQuantityDiamondTransfer\n\tdimtransfer.FromAddress = *fromaddress\n\tdimtransfer.ToAddress = *toaddress\n\tdimtransfer.DiamondList.Count = fields.VarUint1(len(diamonds))\n\tdimtransfer.DiamondList.Diamonds = make([]fields.DiamondName, len(diamonds))\n\tfor i, v := range diamonds {\n\t\tdimtransfer.DiamondList.Diamonds[i] = fields.DiamondName(v)\n\t}\n\n\t// Create transaction\n\tnewTrs, e5 := transactions.NewEmptyTransaction_2_Simple(*feeAddress)\n\tnewTrs.Timestamp = fields.BlockTxTimestamp(ctx.UseTimestamp()) // Use the timestamp of hold\n\tif e5 != nil {\n\t\tfmt.Println(\"create transaction error, \" + e5.Error())\n\t\treturn\n\t}\n\tnewTrs.Fee = *feeAmount // set fee\n\n\t// Put in action\n\tnewTrs.AppendAction(&dimtransfer)\n\n\t// sign\n\te6 := newTrs.FillNeedSigns(ctx.GetAllPrivateKeyBytes(), nil)\n\tif e6 != nil {\n\t\tfmt.Println(\"sign transaction error, \" + e6.Error())\n\t\treturn\n\t}\n\n\t// Check signature\n\tsigok, sigerr := newTrs.VerifyAllNeedSigns()\n\tif sigerr != nil || !sigok {\n\t\tfmt.Println(\"transaction VerifyAllNeedSigns fail\")\n\t\treturn\n\t}\n\n\t// Datalization\n\tbodybytes, e7 := newTrs.Serialize()\n\tif e7 != nil {\n\t\tfmt.Println(\"transaction serialize error, \" + e7.Error())\n\t\treturn\n\t}\n\n\t// ok\n\tctx.Println(\"transaction create success! \")\n\tctx.Println(\"hash: <\" + hex.EncodeToString(newTrs.Hash()) + \">, hash_with_fee: <\" + hex.EncodeToString(newTrs.HashWithFee()) + \">\")\n\tctx.Println(\"body length \" + strconv.Itoa(len(bodybytes)) + \" bytes, hex body is:\")\n\tctx.Println(\"-------- TRANSACTION BODY START --------\")\n\tctx.Println(hex.EncodeToString(bodybytes))\n\tctx.Println(\"-------- TRANSACTION BODY END --------\")\n\n\t// record\n\tctx.SetTxToRecord(newTrs.Hash(), newTrs)\n}", "func New() *d.Client {\n\tvar err error\n\tif os.Getenv(\"DOCKER_HOST\") != \"\" {\n\t\tclient, err = d.NewClient(os.Getenv(\"DOCKER_HOST\"))\n\t} else {\n\t\tclient, err = d.NewClient(\"DEFAULTHERE\")\n\t}\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn nil\n\t}\n\n\treturn client\n}", "func createDog() *Dog {\n\treturn NewDog(\"Hachi\")\n}", "func NewDistKeeper(d float64) *DistKeeper { return &DistKeeper{Heap{{Dist: d}}} }", "func NewDiscovery(hwaddr net.HardwareAddr, modifiers ...Modifier) (*DHCPv4, error) {\n\treturn New(PrependModifiers(modifiers,\n\t\tWithHwAddr(hwaddr),\n\t\tWithRequestedOptions(\n\t\t\tOptionSubnetMask,\n\t\t\tOptionRouter,\n\t\t\tOptionDomainName,\n\t\t\tOptionDomainNameServer,\n\t\t),\n\t\tWithMessageType(MessageTypeDiscover),\n\t)...)\n}", "func NewDHT(store Store, options *Options) (*DHT, error) {\n\t// validate the options, if it's invalid, set them to default value\n\tif options.IP == \"\" {\n\t\toptions.IP = defaultNetworkAddr\n\t}\n\tif options.Port <= 0 {\n\t\toptions.Port = defaultNetworkPort\n\t}\n\n\ts := &DHT{\n\t\tstore: store,\n\t\toptions: options,\n\t\tdone: make(chan struct{}),\n\t}\n\t// new a hashtable with options\n\tht, err := NewHashTable(options)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"new hashtable: %v\", err)\n\t}\n\ts.ht = ht\n\n\t// new network service for dht\n\tnetwork, err := NewNetwork(s, ht.self)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"new network: %v\", err)\n\t}\n\ts.network = network\n\n\treturn s, nil\n}", "func newDupper() *dupper {\n\treturn &dupper{\n\t\tdts: make(map[string]*UserTypeDefinition),\n\t\tdmts: make(map[string]*MediaTypeDefinition),\n\t}\n}", "func NewDig(licenseID int32, posX int32, posY int32, depth int32) *Dig {\n\tthis := Dig{}\n\tthis.LicenseID = licenseID\n\tthis.PosX = posX\n\tthis.PosY = posY\n\tthis.Depth = depth\n\treturn &this\n}", "func NewGateway(c GatewayConfig, d *Daemon) *Gateway {\n\treturn &Gateway{\n\t\tConfig: c,\n\t\td: d,\n\t\tv: d.visor,\n\t\trequests: make(chan strand.Request, c.BufferSize),\n\t\tquit: make(chan struct{}),\n\t}\n}", "func New(node string, receivePort uint16, bits uint64) (*DHT, error) { // configuration\n\tcaller, err := chord.NewNodeCaller(receivePort)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DHT{\n\t\tnode: node,\n\t\tbits: bits,\n\t\tcaller: caller,\n\t}, nil\n}", "func NewDefaultPlusDi() (indicator *PlusDi, err error) {\n\ttimePeriod := 14\n\treturn NewPlusDi(timePeriod)\n}", "func NewDClient(stdClient *http.Client, username string, password string) *DClient {\n\treturn &DClient{\n\t\tclient: stdClient,\n\t\tusername: username,\n\t\tpassword: password,\n\t}\n}", "func NewDenom(id, name, schema string, creator sdk.AccAddress) Denom {\n\treturn Denom{\n\t\tId: id,\n\t\tName: name,\n\t\tSchema: schema,\n\t\tCreator: creator.String(),\n\t}\n}", "func NewXDG() (*XDG, error) {\n\trv := &XDG{}\n\n\tdataHome, err := parseDataHome()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trv.dataHome = dataHome\n\trv.dataDirs = parseDataDirs()\n\n\treturn rv, nil\n}", "func NewDeposit(ctx *middleware.Context, handler DepositHandler) *Deposit {\n\treturn &Deposit{Context: ctx, Handler: handler}\n}", "func NewDeleteSingleBeadSimulationDefault(code int) *DeleteSingleBeadSimulationDefault {\n\treturn &DeleteSingleBeadSimulationDefault{\n\t\t_statusCode: code,\n\t}\n}", "func NewDataWare() Dataware {\n\tconf := config.MyConfig()\n\tif conf.Develop.DatawareFake {\n\t\tlogrus.Info(\"in dataware fake mode so use faked dataware\")\n\t\treturn newDwFake()\n\t}\n\n\tinitGorm()\n\tdialect, dsn := conf.Database.Dsn()\n\tdb, err := gorm.Open(dialect, dsn)\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\tinitDB(db)\n\tlogrus.Infof(\"connect database(%s) by dsn: %s\", dialect, dsn)\n\n\treturn newDwGorm(db)\n}", "func New(modifiers ...Modifier) (*DHCPv4, error) {\n\txid, err := GenerateTransactionID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\td := DHCPv4{\n\t\tOpCode: OpcodeBootRequest,\n\t\tHWType: iana.HWTypeEthernet,\n\t\tClientHWAddr: make(net.HardwareAddr, 6),\n\t\tHopCount: 0,\n\t\tTransactionID: xid,\n\t\tNumSeconds: 0,\n\t\tFlags: 0,\n\t\tClientIPAddr: net.IPv4zero,\n\t\tYourIPAddr: net.IPv4zero,\n\t\tServerIPAddr: net.IPv4zero,\n\t\tGatewayIPAddr: net.IPv4zero,\n\t\tOptions: make(Options),\n\t}\n\tfor _, mod := range modifiers {\n\t\tmod(&d)\n\t}\n\treturn &d, nil\n}", "func NewDefragCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"defrag\",\n\t\tShort: \"Defragments the storage of the etcd\",\n\t\tRun: defragCommandFunc,\n\t}\n\tcmd.Flags().StringVar(&defragDataDir, \"data-dir\", \"\", \"Required. Defragments a data directory not in use by etcd.\")\n\tcmd.MarkFlagRequired(\"data-dir\")\n\tcmd.MarkFlagDirname(\"data-dir\")\n\treturn cmd\n}", "func NewDC() Defector {\n\tonce.Do(func() {\n\t\tinstance = new(Defects)\n\t\tinstance.coll = make([]*Defect, 0)\n\t\tinstance.enabled = true\n\t\tinstance.Headers = []string{\n\t\t\t\"Column\",\n\t\t\t\"Row\",\n\t\t\t\"Message\",\n\t\t}\n\t})\n\treturn instance\n}", "func NewHydra(ctx context.Context, options Options) (*Hydra, error) {\n\tif options.Name != \"\" {\n\t\tnctx, err := tag.New(ctx, tag.Insert(metrics.KeyName, options.Name))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tctx = nctx\n\t}\n\n\tvar ds datastore.Batching\n\tvar err error\n\tif strings.HasPrefix(options.DatastorePath, \"postgresql://\") {\n\t\tfmt.Fprintf(os.Stderr, \"🐘 Using PostgreSQL datastore\\n\")\n\t\tds, err = hyds.NewPostgreSQLDatastore(ctx, options.DatastorePath, !options.DisableDBCreate)\n\t} else if strings.HasPrefix(options.DatastorePath, \"dynamodb://\") {\n\t\toptsStr := strings.TrimPrefix(options.DatastorePath, \"dynamodb://\")\n\t\ttable, err := parseDDBTable(optsStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfmt.Fprintf(os.Stderr, \"Using DynamoDB datastore with table '%s'\\n\", table)\n\t\tddbClient := ddbv1.New(session.Must(session.NewSession()))\n\t\tddbDS := ddbds.New(ddbClient, table, ddbds.WithScanParallelism(5))\n\t\tds = ddbDS\n\t\tperiodictasks.RunTasks(ctx, []periodictasks.PeriodicTask{metricstasks.NewIPNSRecordsTask(ddbDS, ipnsRecordsTaskInterval)})\n\t} else {\n\t\tfmt.Fprintf(os.Stderr, \"🥞 Using LevelDB datastore\\n\")\n\t\tds, err = leveldb.NewDatastore(options.DatastorePath, nil)\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create datastore: %w\", err)\n\t}\n\n\tvar hds []*head.Head\n\n\tif options.PeerstorePath == \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"💭 Using in-memory peerstore\\n\")\n\t} else {\n\t\tfmt.Fprintf(os.Stderr, \"🥞 Using LevelDB peerstore (EXPERIMENTAL)\\n\")\n\t}\n\n\tif options.IDGenerator == nil {\n\t\toptions.IDGenerator = idgen.HydraIdentityGenerator\n\t}\n\tfmt.Fprintf(os.Stderr, \"🐲 Spawning %d heads: \\n\", options.NHeads)\n\n\tvar hyperLock sync.Mutex\n\thyperlog := hyperloglog.New()\n\n\t// What is a limiter?\n\tlimiter := make(chan struct{}, options.BsCon)\n\n\t// Increase per-host connection pool since we are making lots of concurrent requests to a small number of hosts.\n\ttransport := http.DefaultTransport.(*http.Transport).Clone()\n\ttransport.MaxIdleConns = 500\n\ttransport.MaxIdleConnsPerHost = 100\n\tlimitedTransport := &client.ResponseBodyLimitedTransport{RoundTripper: transport, LimitBytes: 1 << 20}\n\n\tdelegateHTTPClient := &http.Client{\n\t\tTimeout: options.DelegateTimeout,\n\t\tTransport: limitedTransport,\n\t}\n\n\tproviderStoreBuilder, err := newProviderStoreBuilder(ctx, delegateHTTPClient, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprovidersFinder := hproviders.NewAsyncProvidersFinder(5*time.Second, 1000, 1*time.Hour)\n\tprovidersFinder.Run(ctx, 1000)\n\n\t// Reuse the HTTP client across all the heads.\n\tfor i := 0; i < options.NHeads; i++ {\n\t\ttime.Sleep(options.Stagger)\n\t\tfmt.Fprintf(os.Stderr, \".\")\n\n\t\tport := options.GetPort()\n\t\ttcpAddr, _ := multiaddr.NewMultiaddr(fmt.Sprintf(\"/ip4/0.0.0.0/tcp/%d\", port))\n\t\tquicAddr, _ := multiaddr.NewMultiaddr(fmt.Sprintf(\"/ip4/0.0.0.0/udp/%d/quic\", port))\n\t\tpriv, err := options.IDGenerator.AddBalanced()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to generate balanced private key %w\", err)\n\t\t}\n\t\thdOpts := []opts.Option{\n\t\t\topts.Datastore(ds),\n\t\t\topts.ProviderStoreBuilder(providerStoreBuilder),\n\t\t\topts.Addrs([]multiaddr.Multiaddr{tcpAddr, quicAddr}),\n\t\t\topts.ProtocolPrefix(options.ProtocolPrefix),\n\t\t\topts.BucketSize(options.BucketSize),\n\t\t\topts.Limiter(limiter),\n\t\t\topts.ID(priv),\n\t\t\topts.BootstrapPeers(options.BootstrapPeers),\n\t\t\topts.DelegateHTTPClient(delegateHTTPClient),\n\t\t\topts.DisableResourceManager(options.DisableResourceManager),\n\t\t\topts.ResourceManagerLimitsFile(options.ResourceManagerLimitsFile),\n\t\t\topts.ConnMgrHighWater(options.ConnMgrHighWater),\n\t\t\topts.ConnMgrLowWater(options.ConnMgrLowWater),\n\t\t\topts.ConnMgrGracePeriod(options.ConnMgrGracePeriod),\n\t\t}\n\t\tif options.EnableRelay {\n\t\t\thdOpts = append(hdOpts, opts.EnableRelay())\n\t\t}\n\t\tif options.DisableProviders {\n\t\t\thdOpts = append(hdOpts, opts.DisableProviders())\n\t\t}\n\t\tif options.DisableValues {\n\t\t\thdOpts = append(hdOpts, opts.DisableValues())\n\t\t}\n\t\tif options.DisableProvGC || i > 0 {\n\t\t\t// the first head GCs, if it's enabled\n\t\t\thdOpts = append(hdOpts, opts.DisableProvGC())\n\t\t}\n\t\tif options.DisableProvCounts || i > 0 {\n\t\t\t// the first head counts providers, if it's enabled\n\t\t\thdOpts = append(hdOpts, opts.DisableProvCounts())\n\t\t}\n\t\tif !options.DisablePrefetch {\n\t\t\thdOpts = append(hdOpts, opts.ProvidersFinder(providersFinder))\n\t\t}\n\t\tif options.PeerstorePath != \"\" {\n\t\t\tpstoreDs, err := leveldb.NewDatastore(fmt.Sprintf(\"%s/head-%d\", options.PeerstorePath, i), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to create peerstore datastore: %w\", err)\n\t\t\t}\n\t\t\tpstore, err := pstoreds.NewPeerstore(ctx, pstoreDs, pstoreds.DefaultOpts())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to create peerstore: %w\", err)\n\t\t\t}\n\t\t\thdOpts = append(hdOpts, opts.Peerstore(pstore))\n\t\t}\n\n\t\thd, bsCh, err := head.NewHead(ctx, hdOpts...)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to spawn node with swarm addresses %v %v: %w\", tcpAddr, quicAddr, err)\n\t\t}\n\n\t\thdCtx, err := tag.New(ctx, tag.Insert(metrics.KeyPeerID, hd.Host.ID().String()))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tstats.Record(hdCtx, metrics.Heads.M(1))\n\n\t\thd.Host.Network().Notify(&network.NotifyBundle{\n\t\t\tConnectedF: func(n network.Network, v network.Conn) {\n\t\t\t\thyperLock.Lock()\n\t\t\t\thyperlog.Insert([]byte(v.RemotePeer()))\n\t\t\t\thyperLock.Unlock()\n\t\t\t\tstats.Record(hdCtx, metrics.ConnectedPeers.M(1))\n\t\t\t},\n\t\t\tDisconnectedF: func(n network.Network, v network.Conn) {\n\t\t\t\tstats.Record(hdCtx, metrics.ConnectedPeers.M(-1))\n\t\t\t},\n\t\t})\n\n\t\tgo handleBootstrapStatus(hdCtx, bsCh)\n\n\t\thds = append(hds, hd)\n\t}\n\tfmt.Fprintf(os.Stderr, \"\\n\")\n\n\tfor _, hd := range hds {\n\t\tfmt.Fprintf(os.Stderr, \"🆔 %v\\n\", hd.Host.ID())\n\t\tfor _, addr := range hd.Host.Addrs() {\n\t\t\tfmt.Fprintf(os.Stderr, \"🐝 Swarm listening on %v\\n\", addr)\n\t\t}\n\t}\n\n\thydra := Hydra{\n\t\tHeads: hds,\n\t\tSharedDatastore: ds,\n\t\thyperLock: &hyperLock,\n\t\thyperlog: hyperlog,\n\t}\n\n\ttasks := []periodictasks.PeriodicTask{\n\t\tmetricstasks.NewRoutingTableSizeTask(hydra.GetRoutingTableSize, routingTableSizeTaskInterval),\n\t\tmetricstasks.NewUniquePeersTask(hydra.GetUniquePeersCount, uniquePeersTaskInterval),\n\t}\n\n\tperiodictasks.RunTasks(ctx, tasks)\n\n\treturn &hydra, nil\n}", "func NewDHTDistributor(cfg *DHTDistributorConfig, dClient *docker.Client) (*DefaultDistributor, error) {\n\tmu := &sync.Mutex{}\n\tactive := make(map[string]*torrent.Torrent)\n\n\tdist := &DefaultDistributor{\n\t\tcfg: cfg,\n\t\tdClient: dClient,\n\t\tmutex: mu,\n\t\tactive: active,\n\t}\n\n\t// preparing torrent client\n\ttc, err := dist.getTorrentClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdist.tClinet = tc\n\treturn dist, nil\n}", "func (d *ActivityDiagram) Decide() *shape.Diamond {\n\tnext := shape.NewDecision()\n\tadj := d.Diagram.Place(next)\n\tadj.Below(d.last, d.Spacing+next.Height()/2)\n\td.VAlignCenter(d.last, next)\n\td.Link(d.last, next)\n\td.last = next\n\treturn next\n}", "func New(ctx context.Context) (*CrosDisks, error) {\n\tconn, obj, err := dbusutil.Connect(ctx, dbusName, dbusPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &CrosDisks{conn, obj}, nil\n}", "func NewDump(d MyDB, inputDir string, jobs int) Dump {\n\tdumpDir := filepath.Join(inputDir, \"gni-dump\")\n\tdmp := Dump{InputDir: inputDir, DumpDir: dumpDir, JobsNum: jobs}\n\tdmp.DB = d.NewDb()\n\treturn dmp\n}", "func NewDentistClient(c config) *DentistClient {\n\treturn &DentistClient{config: c}\n}", "func GetDiamondStore(stores context2.Stores) storage.Store {\n\treturn getVMetaStore(stores)\n}", "func NewAdder(ctx context.Context, p pin.Pinner, bs bstore.GCLocker, ds ipld.DAGService) (*Adder, error) {\n\tbufferedDS := ipld.NewBufferedDAG(ctx, ds)\n\n\treturn &Adder{\n\t\tctx: ctx,\n\t\tpinning: p,\n\t\tgcLocker: bs,\n\t\tdagService: ds,\n\t\tbufferedDS: bufferedDS,\n\t\tProgress: false,\n\t\tPin: true,\n\t\tTrickle: false,\n\t\tMetaForDirectory: false,\n\t\tMetaDagToAdd: false,\n\t\tMetadataDag: nil,\n\t\tdb: nil,\n\t\tChunker: \"\",\n\t\tTokenMetadata: \"\",\n\t\tPinDuration: 0,\n\t}, nil\n}", "func NewDeduper(n int, factory func() boom.Filter) *Deduper {\n\td := &Deduper{\n\t\tring: ring.New(n),\n\t\tfactory: factory,\n\t}\n\n\t// init each element to an empty bloom filter\n\tfor i := 0; i < n; i++ {\n\t\t// expect 100k items, allow fp rate of 1%\n\t\td.ring.Value = d.factory()\n\t\td.ring = d.ring.Next()\n\t}\n\n\treturn d\n}", "func newDiseasetypeMutation(c config, op Op, opts ...diseasetypeOption) *DiseasetypeMutation {\n\tm := &DiseasetypeMutation{\n\t\tconfig: c,\n\t\top: op,\n\t\ttyp: TypeDiseasetype,\n\t\tclearedFields: make(map[string]struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(m)\n\t}\n\treturn m\n}", "func (d *devicelib) NewMigDevice(handle nvml.Device) (MigDevice, error) {\n\tisMig, ret := handle.IsMigDeviceHandle()\n\tif ret != nvml.SUCCESS {\n\t\treturn nil, fmt.Errorf(\"error checking if device is a MIG device: %v\", ret)\n\t}\n\tif !isMig {\n\t\treturn nil, fmt.Errorf(\"not a MIG device\")\n\t}\n\treturn &migdevice{handle, d, nil}, nil\n}", "func (a *DatumAlloc) NewDInt(v tree.DInt) *tree.DInt {\n\tif a.AllocSize == 0 {\n\t\ta.AllocSize = defaultDatumAllocSize\n\t}\n\tbuf := &a.dintAlloc\n\tif len(*buf) == 0 {\n\t\t*buf = make([]tree.DInt, a.AllocSize)\n\t}\n\tr := &(*buf)[0]\n\t*r = v\n\t*buf = (*buf)[1:]\n\treturn r\n}" ]
[ "0.6531112", "0.6350572", "0.62973064", "0.58797884", "0.5780172", "0.5770052", "0.5733969", "0.5599219", "0.55495274", "0.5385128", "0.52965933", "0.5290076", "0.5282357", "0.5248779", "0.5212722", "0.5211248", "0.51848173", "0.51848173", "0.5163079", "0.51546043", "0.50907695", "0.5080854", "0.5063953", "0.50460225", "0.50451255", "0.5043775", "0.5009722", "0.4995005", "0.4975695", "0.4974775", "0.4970688", "0.49655285", "0.49599037", "0.49325702", "0.49114838", "0.49085268", "0.4906497", "0.48336807", "0.4815352", "0.4808435", "0.47895822", "0.47848392", "0.47839358", "0.47441664", "0.47360998", "0.47127584", "0.47084585", "0.47074932", "0.46979958", "0.46828485", "0.46768826", "0.46708784", "0.46640152", "0.46584448", "0.46434772", "0.4636287", "0.46325234", "0.4616651", "0.46080187", "0.4602339", "0.4596302", "0.45955017", "0.4592103", "0.45920178", "0.4588758", "0.4588071", "0.4574635", "0.45730808", "0.45513874", "0.45460314", "0.45419657", "0.45380074", "0.4535831", "0.4526938", "0.4522224", "0.45196655", "0.45142716", "0.45098916", "0.44993848", "0.448612", "0.44856018", "0.4469613", "0.4469098", "0.44659936", "0.44609532", "0.44538823", "0.4451244", "0.44483194", "0.4445657", "0.4435726", "0.44325083", "0.44294563", "0.44187427", "0.44154754", "0.4415434", "0.44027054", "0.44024494", "0.43980616", "0.439604", "0.43959874" ]
0.76206434
0
basenameKeyFilter applies a filter on results from some iterator (e.g. the KeysPrefix store function). This is useful to filter out items located deeper in the metadata tree, but for which the simple separator rule cannot be applied.
func basenameKeyFilter(filter string) func([]string, string, error) ([]string, string, error) { return func(keys []string, next string, err error) ([]string, string, error) { if err != nil { return keys, next, err } filtered := make([]string, 0, len(keys)) for _, key := range keys { if !strings.HasPrefix(path.Base(key), filter) { continue } filtered = append(filtered, key) } return filtered, next, err } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func KeyHasSuffix(v string) predicate.Blob {\n\treturn predicate.Blob(\n\t\tfunc(s *sql.Selector) {\n\t\t\ts.Where(sql.HasSuffix(s.C(FieldKey), v))\n\t\t},\n\t)\n}", "func KeyHasPrefix(v string) predicate.Blob {\n\treturn predicate.Blob(\n\t\tfunc(s *sql.Selector) {\n\t\t\ts.Where(sql.HasPrefix(s.C(FieldKey), v))\n\t\t},\n\t)\n}", "func SubHasPrefix(v string) predicate.Account {\n\treturn predicate.Account(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldSub), v))\n\t})\n}", "func IterateKey(prefix string) []string {\n\tvar results []string\n\n\tdb.View(func(tx *bolt.Tx) error {\n\t\tc := tx.Bucket([]byte(DefaultBucket)).Cursor()\n\n\t\tpre := []byte(prefix)\n\t\tfor k, _ := c.Seek(pre); k != nil && bytes.HasPrefix(k, pre); k, _ = c.Next() {\n\t\t\tresults = append(results, string(k))\n\t\t}\n\t\treturn nil\n\t})\n\treturn results\n}", "func (o BucketNotificationLambdaFunctionOutput) FilterSuffix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketNotificationLambdaFunction) *string { return v.FilterSuffix }).(pulumi.StringPtrOutput)\n}", "func (v *Verb) Filter(prefix string) (result []*Verb) {\n\tfor _, child := range v.verbs {\n\t\tif strings.HasPrefix(child.Name, prefix) {\n\t\t\tresult = append(result, child)\n\t\t}\n\t}\n\treturn result\n}", "func BunameHasPrefix(v string) predicate.Building {\n\treturn predicate.Building(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldBuname), v))\n\t})\n}", "func PrefixFilter(prefix string) FilterFunc {\n\treturn func(m *MountInfo) (bool, bool) {\n\t\tskip := !strings.HasPrefix(m.MountPoint, prefix)\n\t\treturn skip, false\n\t}\n}", "func LastnameHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldLastname), v))\n\t})\n}", "func LastNameHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldLastName), v))\n\t})\n}", "func (o BucketNotificationTopicOutput) FilterSuffix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketNotificationTopic) *string { return v.FilterSuffix }).(pulumi.StringPtrOutput)\n}", "func (o FolderBucketViewOutput) Filter() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FolderBucketView) pulumi.StringOutput { return v.Filter }).(pulumi.StringOutput)\n}", "func ExtractKeySuffix(key string) (string, error) {\n\tsubs := strings.Split(key, \"/\")\n\tif len(subs) < 2 {\n\t\treturn \"\", errors.Errorf(\"invalid key: %s\", key)\n\t}\n\treturn subs[len(subs)-1], nil\n}", "func BioHasPrefix(v string) predicate.User {\n\treturn predicate.User(sql.FieldHasPrefix(FieldBio, v))\n}", "func (e FlatMap) Filter(r ...*regexp.Regexp) (res FlatMap) {\n\tres = FlatMap{}\nLOOP:\n\tfor k, v := range e {\n\t\tfor _, r1 := range r {\n\t\t\tif r1.MatchString(k) {\n\t\t\t\tcontinue LOOP\n\t\t\t}\n\t\t\tres[k] = v\n\t\t}\n\t}\n\treturn\n}", "func FilterPrefix(stringSet sets.String, prefix string, ignoreCase bool) sets.String {\n\tif prefix == \"\" {\n\t\treturn stringSet\n\t}\n\treturn filterSet(stringSet, prefix, ignoreCase, strings.HasPrefix)\n}", "func BaseHasSuffix(v string) predicate.MetaSchema {\n\treturn predicate.MetaSchema(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldBase), v))\n\t},\n\t)\n}", "func KinNameHasSuffix(v string) predicate.Rent {\n\treturn predicate.Rent(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldKinName), v))\n\t})\n}", "func SplitMetaResourceNamespaceKeyFunc(key string) (kind, namespace, name string, err error) {\n\tparts := strings.Split(key, \"/\")\n\tswitch len(parts) {\n\tcase 2:\n\t\t// kind and name only\n\t\treturn parts[0], \"\", parts[1], nil\n\tcase 3:\n\t\t// kind, namespace and name\n\t\treturn parts[0], parts[1], parts[2], nil\n\t}\n\n\treturn \"\", \"\", \"\", fmt.Errorf(\"unexpected key format: %q\", key)\n}", "func filterObjectPasses(b string, k string, filter *[]string) bool {\n\n\tif !theConfig[\"oneBucket\"].BoolVal {\n\t\treturn false // never delete when we are scanning all the buckets\n\t}\n\n\t// wildcard\n\tif theConfig[\"listFilesMatchingPrefix\"].StrVal == \"*\" &&\n\t\tlen(theConfig[\"ListFilesMatchingExclude\"].StrVal) > 0 &&\n\t\t!strings.Contains(k, theConfig[\"ListFilesMatchingExclude\"].StrVal) {\n\t\treturn true // only that special case of matching\n\t}\n\n\t// now tickier cases\n\t// 1. In matching files but not in exclude list\n\tif strings.HasPrefix(k, theConfig[\"listFilesMatchingPrefix\"].StrVal) &&\n\t\tlen(theConfig[\"ListFilesMatchingExclude\"].StrVal) > 0 &&\n\t\t!strings.Contains(k, theConfig[\"listFilesMatchingExclude\"].StrVal) { // but never if the exclude thing matches\n\n\t\treturn true\n\t}\n\tif filter != nil {\n\t\tfor _, s := range *filter {\n\t\t\tif strings.HasPrefix(k, s) {\n\t\t\t\treturn true // so delete all the things in the delete file\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func BunameHasSuffix(v string) predicate.Building {\n\treturn predicate.Building(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldBuname), v))\n\t})\n}", "func NameHasPrefix(v string) predicate.Watchlist {\n\treturn predicate.Watchlist(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func KinNameHasPrefix(v string) predicate.Rent {\n\treturn predicate.Rent(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldKinName), v))\n\t})\n}", "func NameHasPrefix(v string) predicate.Product {\n\treturn predicate.Product(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func (o BucketNotificationQueueOutput) FilterSuffix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketNotificationQueue) *string { return v.FilterSuffix }).(pulumi.StringPtrOutput)\n}", "func (_Bucket *BucketFilterer) FilterFileRename(opts *bind.FilterOpts, entity []common.Address) (*BucketFileRenameIterator, error) {\n\n\tvar entityRule []interface{}\n\tfor _, entityItem := range entity {\n\t\tentityRule = append(entityRule, entityItem)\n\t}\n\n\tlogs, sub, err := _Bucket.contract.FilterLogs(opts, \"FileRename\", entityRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BucketFileRenameIterator{contract: _Bucket.contract, event: \"FileRename\", logs: logs, sub: sub}, nil\n}", "func BucketGetKeysWithPrefix(tx *bolt.Tx, bucket string, prefix string, stripPrefix bool) []string {\n\tb := tx.Bucket([]byte(bucket))\n\tif b == nil {\n\t\treturn nil\n\t}\n\tc := b.Cursor()\n\tvar results []string\n\tprefixBytes := []byte(prefix)\n\tfor k, _ := c.Seek(prefixBytes); k != nil && bytes.HasPrefix(k, prefixBytes); k, _ = c.Next() {\n\t\tif stripPrefix {\n\t\t\tk = k[len(prefix):]\n\t\t}\n\t\tresults = append(results, string(k))\n\t}\n\treturn results\n}", "func (o *Options) ObjectKeyFilterFn() ObjectKeyFilterFn { return o.objectKeyFilterFn }", "func NameHasPrefix(v string) predicate.Conversion {\n\treturn predicate.Conversion(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func NameHasPrefix(v string) predicate.Book {\n\treturn predicate.Book(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func filterListedVdiskID(key string) (string, bool) {\n\tparts := listStorageKeyPrefixRex.FindStringSubmatch(key)\n\tif len(parts) == 3 {\n\t\treturn parts[2], true\n\t}\n\n\treturn \"\", false\n}", "func (o BucketReplicationConfigRuleFilterTagOutput) Key() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketReplicationConfigRuleFilterTag) string { return v.Key }).(pulumi.StringOutput)\n}", "func filterFilenames(bctx build.Context, inputs []string) ([]string, error) {\n\toutputs := []string{}\n\n\tfor _, filename := range inputs {\n\t\tfullPath, err := filepath.Abs(filename)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdir, base := filepath.Split(fullPath)\n\n\t\tmatches, err := bctx.MatchFile(dir, base)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif matches {\n\t\t\toutputs = append(outputs, filename)\n\t\t}\n\t}\n\treturn outputs, nil\n}", "func NameHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func NameHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func NameHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func (b *Bucket) GetFileEncryptionKeysForPrefix(pre string) (map[string][]byte, error) {\n\tif b.Version == 0 {\n\t\treturn map[string][]byte{\"\": b.GetLinkEncryptionKey()}, nil\n\t}\n\n\tkeys := make(map[string][]byte)\n\tfor p := range b.Metadata {\n\t\tif strings.HasPrefix(p, pre) {\n\t\t\tmd, _, ok := b.GetMetadataForPath(p, true)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"could not resolve path: %s\", p)\n\t\t\t}\n\t\t\tkeys[p] = keyBytes(md.Key)\n\t\t}\n\t}\n\treturn keys, nil\n}", "func NameHasPrefix(v string) predicate.Watchlisthistory {\n\treturn predicate.Watchlisthistory(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func SecretHasPrefix(v string) predicate.Account {\n\treturn predicate.Account(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldSecret), v))\n\t})\n}", "func AuthorHasPrefix(v string) predicate.Book {\n\treturn predicate.Book(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldAuthor), v))\n\t})\n}", "func NameHasPrefix(v string) predicate.Project {\n\treturn predicate.Project(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func NameHasPrefix(v string) predicate.Project {\n\treturn predicate.Project(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func fileRkfilter(line []string) []string {\n\tvar cleanfile []string\n\tfor _, l := range line {\n\t\tif len(l) > 0 && l[0] != '#' {\n\t\t\tcleanfile = append(cleanfile, l)\n\t\t}\n\t}\n\treturn cleanfile\n}", "func NameHasPrefix(v string) predicate.AllocationStrategy {\n\treturn predicate.AllocationStrategy(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func (dbm *DBManager) GetKeyList(bucket, prefix string) ([]string, error) {\n\tvar err error\n\tvar results []string\n\tif err = dbm.openDB(); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer dbm.closeDB()\n\n\tresults = make([]string, 0)\n\n\tseekPrefix := func(tx *boltsecTx) error {\n\t\tprefixKey := []byte(prefix)\n\n\t\tbkt := tx.Bucket([]byte(bucket))\n\n\t\tif bkt == nil {\n\t\t\treturn bolt.ErrBucketNotFound\n\t\t}\n\n\t\tcursor := bkt.Cursor()\n\t\tfor k, _ := cursor.Seek(prefixKey); k != nil && bytes.HasPrefix(k, prefixKey); k, _ = cursor.Next() {\n\t\t\tresults = append(results, string(k))\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err = dbm.db.view(seekPrefix); err != nil {\n\t\tLogger.Printf(\"GetByPrefix return %s\", err)\n\t}\n\n\treturn results, err\n}", "func NameHasPrefix(v string) predicate.Ref {\n\treturn predicate.Ref(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func Key(parts ...string) (k string) {\n\tfor _, v := range parts {\n\t\tif v = strings.TrimSpace(v); v == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif k != \"\" {\n\t\t\tk += \"_\"\n\t\t}\n\t\tk += v\n\t}\n\treturn strings.ToUpper(k)\n}", "func SubHasSuffix(v string) predicate.Account {\n\treturn predicate.Account(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldSub), v))\n\t})\n}", "func BaseHasPrefix(v string) predicate.MetaSchema {\n\treturn predicate.MetaSchema(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldBase), v))\n\t},\n\t)\n}", "func (d *BackupDescriptor) Filter(pred func(s string) bool) {\n\tcs := make([]ClassDescriptor, 0, len(d.Classes))\n\tfor _, dest := range d.Classes {\n\t\tif pred(dest.Name) {\n\t\t\tcs = append(cs, dest)\n\t\t}\n\t}\n\td.Classes = cs\n}", "func BenefitsHasPrefix(v string) predicate.Job {\n\treturn predicate.Job(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldBenefits), v))\n\t})\n}", "func UserUploadHasSuffix(v string) predicate.Watchlist {\n\treturn predicate.Watchlist(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldUserUpload), v))\n\t})\n}", "func (c StringArrayCollection) Filter(cb CB) Collection {\n\tvar d = make([]string, 0)\n\tfor key, value := range c.value {\n\t\tif cb(key, value) {\n\t\t\td = append(d, value)\n\t\t}\n\t}\n\treturn StringArrayCollection{\n\t\tvalue: d,\n\t}\n}", "func SubtypeHasPrefix(v string) predicate.Block {\n\treturn predicate.Block(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldSubtype), v))\n\t})\n}", "func BuyerHasPrefix(v string) predicate.Order {\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldBuyer), v))\n\t})\n}", "func (r RawValues) FilterPrefix(prefix string) RawValues {\n\tfiltered := make(RawValues, 0)\n\tfor _, r := range r {\n\t\tif match.HasPrefix(r.Value, prefix) {\n\t\t\tfiltered = append(filtered, r)\n\t\t}\n\t}\n\treturn filtered\n}", "func basename(s string) string {\n\n\t// discard the last '/' and everything before it\n\tfor i := len(s) - 1; i >= 0; i-- {\n\t\tif s[i] == '/' {\n\t\t\ts = s[i+1:]\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// preserve everything before the last '.'\n\tfor i := len(s) - 1; i >= 0; i-- {\n\t\tif s[i] == '.' {\n\t\t\ts = s[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn s\n}", "func (blt Bolt) KeyIterator(query func([]byte) error) error {\n\tboltQuery := func(k, v []byte) error {\n\t\treturn query(k)\n\t}\n\treturn blt.db.View(func(tx *b.Tx) error {\n\t\treturn tx.Bucket(blt.Bucket).ForEach(boltQuery)\n\t})\n}", "func FilterEntriesByPrefix(prefix string, entries []string) []string {\n\tvar result []string\n\tfor _, entry := range entries {\n\t\tif strings.HasPrefix(entry, prefix) {\n\t\t\tresult = append(result, entry)\n\t\t}\n\t}\n\treturn result\n}", "func (b *Bucket) Iter(_ context.Context, dir string, f func(string) error) error {\n\tunique := map[string]struct{}{}\n\n\tfor filename := range b.objects {\n\t\tif !strings.HasPrefix(filename, dir) {\n\t\t\tcontinue\n\t\t}\n\t\tparts := strings.SplitAfter(filename, \"/\")\n\t\tunique[parts[0]] = struct{}{}\n\t}\n\tvar keys []string\n\tfor n := range unique {\n\t\tkeys = append(keys, n)\n\t}\n\tsort.Strings(keys)\n\n\tfor _, k := range keys {\n\t\tif err := f(k); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func PrefixMatch(key string) (res []interface{}) {\n\tglobalStore.RLock()\n\tdefer globalStore.RUnlock()\n\n\tfor k, v := range globalStore.store {\n\t\tif strings.HasPrefix(k, key) {\n\t\t\tres = append(res, v)\n\t\t}\n\t}\n\n\treturn\n}", "func filterUpper(ctx stick.Context, val stick.Value, args ...stick.Value) stick.Value {\n\treturn strings.ToUpper(stick.CoerceString(val))\n}", "func attributeSuffixSelector(key, val string) Selector {\n\treturn attributeSelector(key,\n\t\tfunc(s string) bool {\n\t\t\tif strings.TrimSpace(s) == \"\" {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn strings.HasSuffix(s, val)\n\t\t})\n}", "func NameHasPrefix(v string) predicate.Location {\n\treturn predicate.Location(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t},\n\t)\n}", "func NameHasPrefix(v string) predicate.ValidMessage {\n\treturn predicate.ValidMessage(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func (o BucketLifecycleConfigurationV2RuleFilterTagOutput) Key() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketLifecycleConfigurationV2RuleFilterTag) string { return v.Key }).(pulumi.StringOutput)\n}", "func (g AnnotationGetter) Filter(rn *RNode) (*RNode, error) {\n\tv, err := rn.Pipe(PathGetter{Path: []string{\"metadata\", \"annotations\", g.Key}})\n\tif v == nil || err != nil {\n\t\treturn v, err\n\t}\n\tif g.Value == \"\" || v.value.Value == g.Value {\n\t\treturn v, err\n\t}\n\treturn nil, err\n}", "func DenomMetadataKey(denom string) []byte {\n\td := []byte(denom)\n\treturn append(DenomMetadataPrefix, d...)\n}", "func (f *Filter) getKey(key string) string {\n\tif f.HashKeys {\n\t\th := sha1.New()\n\t\ts := h.Sum([]byte(key))\n\t\treturn fmt.Sprintf(\"%x\", s)\n\t}\n\treturn key\n}", "func NameHasPrefix(v string) predicate.Patient {\n\treturn predicate.Patient(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func FirstnameHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldFirstname), v))\n\t})\n}", "func PhotoHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldPhoto), v))\n\t})\n}", "func youtrackBranchNameFilter(branchName string) string {\n\tmatches := youtrackBranchNameRegEx.FindStringSubmatch(branchName)\n\tif matches != nil {\n\t\treturn fmt.Sprintf(\"%s-%s\", strings.ToUpper(matches[1]), matches[2])\n\t}\n\treturn \"\"\n}", "func (b *Bucket) RotateFileEncryptionKeysForPrefix(pre string) error {\n\tif b.Version == 0 {\n\t\treturn nil\n\t}\n\n\tfor p, md := range b.Metadata {\n\t\tif strings.HasPrefix(p, pre) {\n\t\t\tif md.Key != \"\" {\n\t\t\t\tkey, err := dcrypto.NewKey()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tmd.SetFileEncryptionKey(key)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func filterCallback(branch Branch, search []string) bool {\n\tfor i := 0; i < len(search); i++ {\n\t\tif s.Contains(branch.Name, search[i]) {\t\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func NameHasPrefix(v string) predicate.GameServer {\n\treturn predicate.GameServer(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldName), v))\n\t})\n}", "func NameHasSuffix(v string) predicate.Watchlist {\n\treturn predicate.Watchlist(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldName), v))\n\t})\n}", "func ExampleBucket_MapPrefix() {\n\tbx, _ := buckets.Open(tempfile())\n\tdefer os.Remove(bx.Path())\n\tdefer bx.Close()\n\n\t// Create a new things bucket.\n\tthings, _ := bx.New([]byte(\"things\"))\n\n\t// Setup items to insert.\n\titems := []struct {\n\t\tKey, Value []byte\n\t}{\n\t\t{[]byte(\"A\"), []byte(\"1\")}, // `A` prefix match\n\t\t{[]byte(\"AA\"), []byte(\"2\")}, // match\n\t\t{[]byte(\"AAA\"), []byte(\"3\")}, // match\n\t\t{[]byte(\"AAB\"), []byte(\"2\")}, // match\n\t\t{[]byte(\"B\"), []byte(\"O\")},\n\t\t{[]byte(\"BA\"), []byte(\"0\")},\n\t\t{[]byte(\"BAA\"), []byte(\"0\")},\n\t}\n\n\t// Insert 'em.\n\tif err := things.Insert(items); err != nil {\n\t\tfmt.Printf(\"could not insert items in `things` bucket: %v\\n\", err)\n\t}\n\n\t// Now collect each item whose key starts with \"A\".\n\tprefix := []byte(\"A\")\n\n\t// Setup slice of items.\n\ttype item struct {\n\t\tKey, Value []byte\n\t}\n\tresults := []item{}\n\n\t// Anon func to map over matched keys.\n\tdo := func(k, v []byte) error {\n\t\tresults = append(results, item{k, v})\n\t\treturn nil\n\t}\n\n\tif err := things.MapPrefix(do, prefix); err != nil {\n\t\tfmt.Printf(\"could not map items with prefix %s: %v\\n\", prefix, err)\n\t}\n\n\tfor _, item := range results {\n\t\tfmt.Printf(\"%s -> %s\\n\", item.Key, item.Value)\n\t}\n\t// Output:\n\t// A -> 1\n\t// AA -> 2\n\t// AAA -> 3\n\t// AAB -> 2\n}", "func filterByPrefix[T types.ResourceWithLabels](resources []T, prefix string, altNameFns ...altNameFn[T]) []T {\n\treturn filterResources(resources, func(r T) bool {\n\t\tif strings.HasPrefix(r.GetName(), prefix) {\n\t\t\treturn true\n\t\t}\n\t\tfor _, altName := range altNameFns {\n\t\t\tif strings.HasPrefix(altName(r), prefix) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t})\n}", "func PictureHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldPicture), v))\n\t})\n}", "func PhotoHasSuffix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldPhoto), v))\n\t})\n}", "func CreateWorkbookFilterFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWorkbookFilter(), nil\n}", "func TestTrimKafkaChannelServiceNameSuffix(t *testing.T) {\n\n\t// Test Data\n\tchannelName := \"TestChannelName\"\n\tchannelServiceName := fmt.Sprintf(\"%s-%s\", channelName, constants.KafkaChannelServiceNameSuffix)\n\n\t// Perform The Test\n\tactualResult := TrimKafkaChannelServiceNameSuffix(channelServiceName)\n\n\t// Verify The Results\n\texpectedResult := channelName\n\tassert.Equal(t, expectedResult, actualResult)\n}", "func (s *s3) List(key string) ([]string, error) {\n\tif key != \"\" && !strings.HasSuffix(key, \"/\") {\n\t\tkey += \"/\"\n\t}\n\n\tresult, err := s.client.ListObjectsV2(&awss3.ListObjectsV2Input{\n\t\tPrefix: aws.String(key),\n\t\tBucket: aws.String(s.bucket),\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfiles := []string{}\n\tfor _, obj := range result.Contents {\n\t\t_, file := path.Split(*obj.Key)\n\t\tfiles = append(files, file)\n\t}\n\treturn files, nil\n}", "func FundTitleHasPrefix(v string) predicate.CoveredPerson {\n\treturn predicate.CoveredPerson(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldFundTitle), v))\n\t})\n}", "func TaxIDHasPrefix(v string) predicate.Watchlist {\n\treturn predicate.Watchlist(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldTaxID), v))\n\t})\n}", "func extractKey(key string, content *string) string {\n\tif loc := strings.Index(*content, key); loc != -1 {\n\t\tv := (*content)[loc+len(key):]\n\t\tsep := v[:1]\n\t\tv = v[1:][:strings.Index(v[1:], sep)]\n\t\treturn v\n\t}\n\treturn \"\"\n}", "func (r *Registry) filter(glob string, fn func(element interface{})) RangeFunc {\n\treturn func(key, value interface{}) bool {\n\t\tif ok, err := filepath.Match(glob, key.(string)); ok {\n\t\t\tfn(value)\n\t\t} else if err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn true\n\t}\n}", "func SocialNameHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldSocialName), v))\n\t})\n}", "func TestMapPrefix(t *testing.T) {\n\tbx := NewTestDB()\n\tdefer bx.Close()\n\n\t// Create a new things bucket.\n\tthings, err := bx.New([]byte(\"things\"))\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t// Setup items to insert.\n\titems := []struct {\n\t\tKey, Value []byte\n\t}{\n\t\t{[]byte(\"A\"), []byte(\"1\")}, // `A` prefix match\n\t\t{[]byte(\"AA\"), []byte(\"2\")}, // match\n\t\t{[]byte(\"AAA\"), []byte(\"3\")}, // match\n\t\t{[]byte(\"AAB\"), []byte(\"2\")}, // match\n\t\t{[]byte(\"B\"), []byte(\"O\")},\n\t\t{[]byte(\"BA\"), []byte(\"0\")},\n\t\t{[]byte(\"BAA\"), []byte(\"0\")},\n\t}\n\n\t// Insert 'em.\n\tif err := things.Insert(items); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t// Now collect each item whose key starts with \"A\".\n\tprefix := []byte(\"A\")\n\n\t// Expected items for keys with prefix \"A\".\n\texpected := []struct {\n\t\tKey, Value []byte\n\t}{\n\t\t{[]byte(\"A\"), []byte(\"1\")},\n\t\t{[]byte(\"AA\"), []byte(\"2\")},\n\t\t{[]byte(\"AAA\"), []byte(\"3\")},\n\t\t{[]byte(\"AAB\"), []byte(\"2\")},\n\t}\n\n\t// Setup slice of items to collect results.\n\ttype item struct {\n\t\tKey, Value []byte\n\t}\n\tresults := []item{}\n\n\t// Anon func to map over matched keys.\n\tdo := func(k, v []byte) error {\n\t\tresults = append(results, item{k, v})\n\t\treturn nil\n\t}\n\n\tif err := things.MapPrefix(do, prefix); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\tfor i, want := range expected {\n\t\tgot := results[i]\n\t\tif !bytes.Equal(got.Key, want.Key) {\n\t\t\tt.Errorf(\"got %v, want %v\", got.Key, want.Key)\n\t\t}\n\t\tif !bytes.Equal(got.Value, want.Value) {\n\t\t\tt.Errorf(\"got %v, want %v\", got.Value, want.Value)\n\t\t}\n\t}\n}", "func DetialHasPrefix(v string) predicate.Medicalfile {\n\treturn predicate.Medicalfile(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldDetial), v))\n\t})\n}", "func (s *ServiceRecordedTestsSuite) TestAccountFilterBlobs() {\n\t_require := require.New(s.T())\n\tsvcClient, err := testcommon.GetServiceClient(s.T(), testcommon.TestAccountDefault, nil)\n\t_require.NoError(err)\n\n\tfilter := \"\\\"key\\\"='value'\"\n\tresp, err := svcClient.FilterBlobs(context.Background(), filter, &service.FilterBlobsOptions{})\n\t_require.Nil(err)\n\t_require.Len(resp.FilterBlobSegment.Blobs, 0)\n}", "func FirstNameHasPrefix(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldFirstName), v))\n\t})\n}", "func BuildRemoveLabelFilter(predicate func(key string) bool) (yaml.Filter, error) {\n\tfieldPaths, err := xform.ParseFieldPaths(\n\t\t[]string{\n\t\t\t\"metadata.labels\",\n\t\t\t\"spec.selector\",\n\t\t\t\"spec.selector.matchLabels\",\n\t\t\t\"spec.template.metadata.labels\",\n\t\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &xform.FieldClearer{\n\t\tFieldPaths: fieldPaths,\n\t\tPredicate: predicate,\n\t}, nil\n}", "func SplitKey(key string) (string, string) {\n\tif !strings.Contains(key, \"/\") {\n\t\treturn key, \"\"\n\t}\n\tkeyParts := strings.SplitN(key, \"/\", 2)\n\treturn keyParts[0], keyParts[1]\n}", "func normalizeResourceName(inKey string) string {\n\n\toutKey := \"\"\n\tre := regexp.MustCompile(\"^[a-zA-Z0-9_-]*$\")\n\tfor i, char := range inKey {\n\t\tschar := string(char)\n\t\tif i == 0 {\n\t\t\tfc := regexp.MustCompile(\"^[a-zA-Z_]*$\")\n\t\t\tif !fc.MatchString(schar) {\n\t\t\t\toutKey += \"_\"\n\t\t\t}\n\t\t}\n\t\tif re.MatchString(schar) {\n\t\t\toutKey += schar\n\t\t} else {\n\t\t\toutKey += \"_\"\n\t\t}\n\t}\n\treturn outKey\n\n}", "func (g *gbkBinCollator) KeyWithoutTrimRightSpace(str string) []byte {\n\tbuf := make([]byte, 0, len(str))\n\tfor len(str) > 0 {\n\t\tl := runeLen(str[0])\n\t\tgbk, err := g.e.Bytes(hack.Slice(str[:l]))\n\t\tif err != nil {\n\t\t\tbuf = append(buf, byte('?'))\n\t\t} else {\n\t\t\tbuf = append(buf, gbk...)\n\t\t}\n\t\tstr = str[l:]\n\t}\n\n\treturn buf\n}", "func UserUploadHasPrefix(v string) predicate.Watchlist {\n\treturn predicate.Watchlist(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldUserUpload), v))\n\t})\n}", "func SecretHasSuffix(v string) predicate.Account {\n\treturn predicate.Account(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldSecret), v))\n\t})\n}", "func (o BucketNotificationLambdaFunctionOutput) FilterPrefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketNotificationLambdaFunction) *string { return v.FilterPrefix }).(pulumi.StringPtrOutput)\n}" ]
[ "0.52340424", "0.4928137", "0.4894693", "0.4847061", "0.47071567", "0.46861228", "0.4669897", "0.46603027", "0.46325058", "0.4622332", "0.46086925", "0.4532329", "0.45094556", "0.44940478", "0.4484004", "0.44813517", "0.4467792", "0.44648084", "0.44573885", "0.4454603", "0.4444005", "0.44415364", "0.43906486", "0.43894365", "0.43863362", "0.43743628", "0.43710116", "0.43668833", "0.43644872", "0.43558052", "0.43514878", "0.43453282", "0.43114075", "0.43071324", "0.43071324", "0.43071324", "0.42884612", "0.42785546", "0.4269324", "0.42678303", "0.4260513", "0.4260513", "0.42490265", "0.4246136", "0.42402586", "0.42390937", "0.42375287", "0.42355996", "0.4233639", "0.42134", "0.4202226", "0.41974056", "0.41924983", "0.4191894", "0.41914374", "0.4191122", "0.41744962", "0.41728833", "0.41724458", "0.41654408", "0.41464183", "0.4141171", "0.41402188", "0.4135609", "0.41352314", "0.41157433", "0.41103798", "0.41084903", "0.41064742", "0.40963835", "0.40906423", "0.40883255", "0.4082987", "0.40809464", "0.4077835", "0.40650398", "0.40585554", "0.40564835", "0.40460217", "0.40451545", "0.4040305", "0.40403005", "0.40330538", "0.4023306", "0.40193436", "0.4015472", "0.40116563", "0.40113947", "0.40110296", "0.40100732", "0.40035397", "0.40024048", "0.39983034", "0.3997722", "0.39964375", "0.39952242", "0.3992893", "0.39928058", "0.39914528", "0.39896727" ]
0.81313115
0
write a plain text message
func writeString(w http.ResponseWriter, body string, status int) { writeBody(w, []byte(body), status, "text/plain") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func writePlainText(statusCode int, text string, w http.ResponseWriter) {\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.WriteHeader(statusCode)\n\tfmt.Fprintln(w, text)\n}", "func (s *Status) WriteText(w http.ResponseWriter) error {\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.WriteHeader(s.Code)\n\t_, err := io.WriteString(w, s.String())\n\treturn err\n}", "func sendText(msg string, s *discordgo.Session, m *discordgo.MessageCreate) {\n\t_, _ = s.ChannelMessageSend(m.ChannelID, msg)\n\tfmt.Printf(\"Sending %q\\n\", msg)\n}", "func (c *Client) Write(message *Message) {\n\tfmt.Fprintf(c.Conn, message.ToString())\n}", "func Write(w http.ResponseWriter, status int, text string) {\n\tWriteBytes(w, status, []byte(text))\n}", "func plainText(h http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Add(\"Content-Type\", \"text/plain; charset=utf-8\")\n\t\th(w, r)\n\t}\n}", "func sendTextResponse(w http.ResponseWriter, msg string) {\n\tw.Write([]byte(msg))\n}", "func writeText(w io.Writer, text []byte, html bool) {\n\tif html {\n\t\ttemplate.HTMLEscape(w, text);\n\t\treturn;\n\t}\n\tw.Write(text);\n}", "func Text(resp http.ResponseWriter, content string, code int) error {\n\tresp.Header().Add(\"Content-Type\", \"text/plain\")\n\tresp.WriteHeader(code)\n\t_, err := resp.Write([]byte(content))\n\treturn maskAny(err)\n}", "func SendPlainText(w http.ResponseWriter, text string, code int) {\n\tw.WriteHeader(code)\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Write([]byte(text))\n}", "func WritePlainEmail(subject, bodyMessage string) string {\n\n\treturn WriteEmail(\"text/plain\", subject, bodyMessage)\n}", "func sendTextMsg(data map[string]string, conn *websocket.Conn) error {\n\tdataB, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconn.SetWriteDeadline(time.Now().Add(writeWait))\n\n\tw, err := conn.NextWriter(websocket.TextMessage)\n\tif err != nil {\n\t\treturn err\n\t}\n\tw.Write(dataB)\n\n\treturn w.Close()\n}", "func (sc *SnowthClient) WriteText(data []TextData, nodes ...*SnowthNode) error {\n\treturn sc.WriteTextContext(context.Background(), data, nodes...)\n}", "func (b *Builder) Plain(s string) *Builder {\n\tb.message.WriteString(s)\n\treturn b\n}", "func (client *Client) Write(message string) error {\n\terr := client.conn.WriteMessage(websocket.TextMessage, []byte(message))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (f *Sender) SimpleText(text string) error {\n\tbotMsg := f.msgFactory()\n\ttoSent := tgbotapi.NewMessage(f.session.ChatId(), text)\n\tif f.bot != nil {\n\t\tif sentMsg, err := f.bot.Send(toSent); err == nil {\n\t\t\tbotMsg.SetID(int64(sentMsg.MessageID))\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\tbotMsg.Save()\n\treturn nil\n}", "func (c *SodaClient) Write(sendMsg string) {\n\tmsg := strings.TrimSpace(sendMsg)\n\n\tbuf := []byte(msg)\n\n\t_, err := c.conn.Write(buf) // returns string length of write and potential write errors\n\n\tif err != nil {\n\t\tfmt.Println(msg, err)\n\t}\n}", "func (w *SlackResponseWriter) Write(text string) error {\n\tw.rtm.SendMessage(w.rtm.NewOutgoingMessage(text, w.msg.Channel))\n\n\treturn nil\n}", "func PlainText(h http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\t\th.ServeHTTP(w, r)\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func PlainText(w http.ResponseWriter, r *http.Request, v string) {\n\trender.PlainText(w, r, v)\n}", "func (connection *SSEConnection) SendText(payload []byte) {\n\tconnection.messageSendChannel <- payload\n}", "func (c *Conn) TextMessage(text string) *pivo.Message {\n\treturn pivo.TextMessage(c, text)\n}", "func sendRequest(conn net.Conn, text string) {\n message := text;\n \n if _,err := conn.Write([]byte(message + \"\\n\")); err != nil {\n log.Fatal(err)\n }\n}", "func createPlaintextAttachment(msg string) nntpAttachment {\n buff := new(bytes.Buffer)\n _, _ = io.WriteString(buff, msg)\n header := make(textproto.MIMEHeader)\n mime := \"text/plain; charset=UTF-8\"\n header.Set(\"Content-Type\", mime)\n return nntpAttachment{\n mime: mime,\n ext: \".txt\",\n body: *buff,\n header: header,\n }\n}", "func (a *AppController) Plaintext() {\n\ta.Reply().Text(helloWorldMsg)\n}", "func Write(m *Message) error {\n\treturn system.Write(m)\n}", "func (t TerminalSession) Write(p []byte) (int, error) {\n\terr := t.sockConn.WriteMessage(websocket.TextMessage, p)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn len(p), nil\n}", "func (w *CLIResponseWriter) Write(text string) error {\n\tfmt.Println(\">> \", text)\n\n\treturn nil\n}", "func WriteText(text string, path string) error {\n fileHandle, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND, 0666)\n\n if err != nil {\n return err\n }\n defer fileHandle.Close()\n\n writer := bufio.NewWriter(fileHandle)\n fmt.Fprintln(writer, text)\n \n return writer.Flush()\n}", "func PlainText(toSynthesize string, voiceID string) Response {\n\tvar res Response\n\tsess, err := session.NewSession()\n\tif err != nil {\n\t\tres.Error = err\n\t\treturn res\n\t}\n\n\tsvc := polly.New(sess, &aws.Config{Region: aws.String(\"us-east-1\")})\n\n\tparams := &polly.SynthesizeSpeechInput{\n\t\tOutputFormat: aws.String(\"mp3\"),\n\t\tText: aws.String(toSynthesize),\n\t\tVoiceId: aws.String(voiceID),\n\t\tTextType: aws.String(\"text\"),\n\t}\n\tresp, err := svc.SynthesizeSpeech(params)\n\n\tif err != nil {\n\t\tres.Error = err\n\t\treturn res\n\t}\n\n\tb, err := ioutil.ReadAll(resp.AudioStream)\n\tif err != nil {\n\t\tres.Error = err\n\t\treturn res\n\t}\n\t/*if err == nil {\n\t\terr := ioutil.WriteFile(\"./testfiles/test.mp3\", b, 0644)\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t}\n\t}*/\n\n\tres.Audio = b\n\tres.Error = nil\n\n\treturn res\n}", "func (client *Client) Text() (out string, err error) {\n\tif err = client.init(); err != nil {\n\t\treturn\n\t}\n\tout = C.GoString(C.UTF8Text(client.api))\n\tif client.Trim {\n\t\tout = strings.Trim(out, \"\\n\")\n\t}\n\treturn out, err\n}", "func (client *Client) SendText(msg []byte) error {\n\treturn client.Channel.sendMessage(websocket.TextMessage, msg)\n}", "func (b *Bot) Writeln(server, message string) error {\n\tb.serversProtect.RLock()\n\tdefer b.serversProtect.RUnlock()\n\n\tif srv, ok := b.servers[server]; !ok {\n\t\treturn errUnknownServerId\n\t} else {\n\t\treturn srv.Writeln(message)\n\t}\n}", "func (r *Reply) Text(format string, values ...interface{}) *Reply {\n\tr.ContentType(ahttp.ContentTypePlainText.String())\n\tr.Render(&textRender{Format: format, Values: values})\n\treturn r\n}", "func TextResp(w http.ResponseWriter, code int, text string) {\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.WriteHeader(code)\n\tw.Write([]byte(text))\n}", "func (cb *printcb) outputText(data string) error {\n\treturn cb.outputBinary([]byte(data))\n}", "func (c *Ctx) Text(code int, s string) error {\n\treturn c.TextBytes(code, []byte(s))\n}", "func (m *display) Text(data string) (int) {\n\tn := m.Send([]byte(data))\n\treturn n\n}", "func (tc *TestClient) SendText(data string) error {\n\treturn tc.Send(&common.WsMessage{MessageType: websocket.TextMessage, Data: []byte(data)})\n}", "func genericTextOutput(doppelgangerState *userInfo, theMessage messageFromChatChannelToDoppelganger) bool {\n\tvar err error\n\tif theMessage.originator == doppelgangerState.userID {\n\t\t// Our own message -- don't backspace out.\n\t\terr = backspaceOut(doppelgangerState, doppelgangerState.promptLen+doppelgangerState.cursorColumn)\n\t\t_, err = oi.LongWrite(doppelgangerState.writer, []byte(theMessage.parameter+\"\\r\\n\"))\n\t} else {\n\t\t//\n\t\t// Backspace out before outputting message\n\t\t//\n\t\terr = backspaceOut(doppelgangerState, doppelgangerState.promptLen+doppelgangerState.cursorColumn)\n\t\tif err != nil {\n\t\t\t//\n\t\t\t// We are assuming if we got an error, the network connection is\n\t\t\t// closed, and we need to exit the doppelganger because we are\n\t\t\t// done, too.\n\t\t\t//\n\t\t\treturn true\n\t\t}\n\t\t_, err = oi.LongWrite(doppelgangerState.writer, []byte(theMessage.parameter+\"\\r\\n\"))\n\t}\n\tif err != nil {\n\t\t//\n\t\t// We are assuming if we got an error, the network connection is closed,\n\t\t// and we need to exit the doppelganger because we are done, too.\n\t\t//\n\t\treturn true\n\t}\n\treturn false\n}", "func (m *MatrixMessage) Write(data []byte) (n int, err error) {\n\tn = len(data)\n\tm.Text = string(data)\n\treturn n, nil\n}", "func (h *Salute) RespondText(c *gomatrix.Client, ev *gomatrix.Event, _, post string) error {\n\treturn SendText(c, ev.RoomID, h.Process(ev.Sender, post))\n}", "func (r *RabbitMQ) publishText(exchange, key, text string) (err error) {\n\terr = r.channel.Publish(exchange, key, false, false,\n\t\tamqp.Publishing{\n\t\t\tContentType: \"text/plain\",\n\t\t\tCorrelationId: \"\",\n\t\t\tReplyTo: \"\",\n\t\t\tBody: []byte(text),\n\t\t},\n\t)\n\tif err != nil {\n\t\tlog.Info(\"[amqp] publish message error: %s\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t TerminalSession) Toast(p string) error {\n\tif err := t.sockConn.WriteMessage(websocket.TextMessage, []byte(p)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func SendMessageWithRichContent() {}", "func (ce CustomEvent) WriteText(tf logger.TextFormatter, buf *bytes.Buffer) {\n\tbuf.WriteString(ce.UserID)\n\tbuf.WriteRune(logger.RuneSpace)\n\tbuf.WriteString(ce.SessionID)\n\tbuf.WriteRune(logger.RuneSpace)\n\tbuf.WriteString(ce.Context)\n}", "func CreatePlainMessage(t string) Message {\n\treturn Message{\n\t\tPayload: string(t),\n\t\tType: 0,\n\t}\n}", "func WriteMessage(lcd *device.Lcd, str string, line device.ShowOptions) {\n\tm.Lock()\n\terr := lcd.ShowMessage(str, line)\n\tm.Unlock()\n\tif err != nil {\n\t\tlg.Fatalf(\"WriteMessage: %s\", err)\n\t}\n\treturn\n}", "func (t *DynamicMessageType) Text() string {\n\treturn t.spec.Text\n}", "func (r renderer) NormalText(out *bytes.Buffer, text []byte) {\n\tout.Write(text)\n}", "func (ctx *Context) SendTextMessage(text string, a ...interface{}) (int, error) {\n\treturn ctx.Send(ctx.NewMessage(fmt.Sprintf(text, a...)))\n}", "func (s *kabuta) writeToFrontend(str string) {\n\tn, err := os.Stdout.WriteString(str)\n\tif err != nil {\n\t\ts.log(\"Error sending %s: %v\\n\", str, err)\n\t\tpanic(err)\n\t}\n\ts.log(\"SENT>%s\", str)\n}", "func (c *Context) String(s string) {\n\tconst eom = \"\\n\"\n\tif !strings.HasSuffix(s, eom) {\n\t\t// sends it now, ending the message.\n\t\ts += eom\n\t}\n\t_, err := c.writer.WriteString(s)\n\tif err != nil {\n\t\tc.Error(err)\n\t}\n}", "func (t *Texter) SendText(destination, message string) error {\n\treader := t.buildPayload(destination, message)\n\n\treq, err := t.buildRequest(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif t.reallySend {\n\t\tif err := t.sendRequest(req); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tlog.Printf(\"Would have sent %s the following\\n\\t%s\", destination, message)\n\t}\n\treturn nil\n}", "func WriteMsg(w http.ResponseWriter, str string) {\n\t//Todo: Format nicely\n\tfmt.Fprintf(w, str)\n}", "func (ce CustomEvent) WriteText(tf logger.TextFormatter, wr io.Writer) {\n\tio.WriteString(wr, ce.UserID)\n\tio.WriteString(wr, logger.Space)\n\tio.WriteString(wr, ce.SessionID)\n\tio.WriteString(wr, logger.Space)\n\tio.WriteString(wr, ce.Context)\n}", "func (m Message) Text() string {\r\n\treturn m.Message\r\n}", "func (s PlainTextMessage) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (c *DingTalkClient) SendRobotTextMessage(accessToken string, msg string) error {\n\tvar data OAPIResponse\n params := url.Values{}\n params.Add(\"access_token\", accessToken)\t\n\trequest := map[string]interface{}{\n\t\t\"msgtype\": \"text\",\n\t\t\"text\": map[string]interface{}{\n\t\t\t\"content\": msg,\n\t\t},\n\t}\n\terr := c.httpRPC(\"robot/send\", params, request, &data)\n\treturn err\n}", "func (s *Websocket) system(text string) {\n\tmsg := models.Message{\n\t\tID: 0,\n\t\tSender: \"system\",\n\t\tReceiver: \"\",\n\t\tText: text,\n\t\tCreatedAt: time.Now(),\n\t}\n\n\ts.hmu.RLock()\n\n\tfor _, receiver := range s.hub {\n\t\tif err := receiver.Conn.WriteJSON(msg); err != nil {\n\t\t\ts.logger.Errorf(\"error sending message: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t}\n\n\ts.hmu.RUnlock()\n}", "func (t Session) Write(p []byte) (int, error) {\n\tmsg, err := json.Marshal(Message{\n\t\tOp: \"stdout\",\n\t\tData: string(p),\n\t})\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif err = t.WebSocket.WriteMessage(websocket.TextMessage, msg); err != nil {\n\t\treturn 0, err\n\t}\n\treturn len(p), nil\n}", "func (license *License) WriteText(filePath string) error {\n\tif err := os.WriteFile(filePath, []byte(license.LicenseText), os.FileMode(0o644)); err != nil {\n\t\treturn fmt.Errorf(\"while writing license to text file: %w\", err)\n\t}\n\treturn nil\n}", "func PlainText(s string) Response {\n\treturn stringResponse{s}\n}", "func (t *trs80) writeMessages() {\n\tfor i := 0; i < int(t.pb.Header.NumMessages); i++ {\n\t\tfmt.Fprintf(t.out, \"\\\"%s\\\"\\n\", t.pb.Messages[i])\n\t}\n}", "func (c *Client) Publish(subject string, data []byte) error {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tmsgh := []byte(\"PUB \")\n\tmsgh = append(msgh, subject...)\n\tmsgh = append(msgh, ' ')\n\n\t// msgh = strconv.AppendInt(msgh, int64(len(data)), 10)\n\n\t// faster alternative\n\tvar b [12]byte\n\tvar i = len(b)\n\tif len(data) > 0 {\n\t\tfor l := len(data); l > 0; l /= 10 {\n\t\t\ti -= 1\n\t\t\tb[i] = digits[l%10]\n\t\t}\n\t} else {\n\t\ti -= 1\n\t\tb[i] = digits[0]\n\t}\n\tmsgh = append(msgh, b[i:]...)\n\tmsgh = append(msgh, _CRLF_...)\n\t_, err := c.w.Write(msgh)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = c.w.Write(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = c.w.WriteString(\"\\r\\n\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(c.fch) == 0 {\n\t\tc.fch <- struct{}{}\n\t}\n\n\treturn nil\n}", "func (s *SocketModeAdapter) SendText(ctx context.Context, channelID string, message string) error {\n\treturn SendText(ctx, s.client, s, channelID, message)\n}", "func putMsg(conn net.Conn, msg string){\n\tfmt.Printf(\"C %s\\n\", msg)\n\tio.WriteString(conn, msg)//send our message\n}", "func writeSuccess(w http.ResponseWriter, targetLanguage language.Tag, targetPhrase string) {\n\theaders := w.Header()\n\n\theaders.Set(\"Content-Type\", \"text/plain\")\n\theaders.Set(\"Content-Language\", targetLanguage.String())\n\tw.WriteHeader(http.StatusOK)\n\tio.WriteString(w, targetPhrase)\n}", "func (adapter *Shell) WriteMessage(message string) {\n\tfmt.Fprintln(adapter.output, message)\n}", "func (sc *SnowthClient) WriteTextContext(ctx context.Context,\n\tdata []TextData, nodes ...*SnowthNode,\n) error {\n\tvar node *SnowthNode\n\tif len(nodes) > 0 && nodes[0] != nil {\n\t\tnode = nodes[0]\n\t} else if len(data) > 0 {\n\t\tnode = sc.GetActiveNode(sc.FindMetricNodeIDs(data[0].ID,\n\t\t\tdata[0].Metric))\n\t}\n\n\tif node == nil {\n\t\treturn fmt.Errorf(\"unable to get active node\")\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tif err := json.NewEncoder(buf).Encode(data); err != nil {\n\t\treturn fmt.Errorf(\"failed to encode TextData for write: %w\", err)\n\t}\n\n\t_, _, err := sc.DoRequestContext(ctx, node, \"POST\", \"/write/text\", buf, nil)\n\n\treturn err\n}", "func (c *client) write() {\n\tfor msg := range c.send {\n\t\tif err := c.socket.WriteMessage(websocket.TextMessage, msg); err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tc.socket.Close()\n}", "func WriteString(w http.ResponseWriter, str string) {\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.WriteHeader(http.StatusOK)\n\t_, err := w.Write([]byte(str))\n\tif err != nil {\n\t\tLogWarning(errors.WrapPrefix(err, \"failed to write response\", 0))\n\t}\n}", "func (c *Ctx) TextBytes(code int, b []byte) (err error) {\n\n\tc.response.Header().Set(ContentType, TextPlainCharsetUTF8)\n\tc.response.WriteHeader(code)\n\t_, err = c.response.Write(b)\n\treturn\n}", "func TestSendTextMessage(t *testing.T) {\n\t// TODO(inhies): Create an internal rate limiting system and do away with\n\t// this hacky 1 second delay.\n\ttime.Sleep(1 * time.Second) // Sleep 1 second due to API limitation\n\tif TEST_PHONE_NUMBER == \"\" {\n\t\tt.Fatal(\"No test phone number specified. Please set NEXMO_NUM\")\n\t}\n\tnexmo, err := NewClientFromAPI(API_KEY, API_SECRET)\n\tif err != nil {\n\t\tt.Error(\"Failed to create Client with error:\", err)\n\t}\n\n\tmessage := &SMSMessage{\n\t\tFrom: TEST_FROM,\n\t\tTo: TEST_PHONE_NUMBER,\n\t\tType: Text,\n\t\tText: \"Gonexmo test SMS message, sent at \" + time.Now().String(),\n\t\tClientReference: \"gonexmo-test \" + strconv.FormatInt(time.Now().Unix(), 10),\n\t\tClass: Standard,\n\t}\n\n\tmessageResponse, err := nexmo.SMS.Send(message)\n\tif err != nil {\n\t\tt.Error(\"Failed to send text message with error:\", err)\n\t}\n\n\tt.Logf(\"Sent SMS, response was: %#v\\n\", messageResponse)\n}", "func (w *Writer) Notice(m string) error {}", "func (s *smlWriter) Text(text string) error {\n\tt := strings.Replace(text, \"^\", \"^^\", -1)\n\tt = strings.Replace(t, \"{\", \"^{\", -1)\n\tt = strings.Replace(t, \"}\", \"^}\", -1)\n\ts.writeIndent(false)\n\ts.writer.WriteString(t)\n\treturn nil\n}", "func (m *BaseMessage) Text() string {\n\treturn m.MsgText\n}", "func (payload *Payload) Text() string {\n\treturn string(payload.Data)\n}", "func sendCommand(conn net.Conn, command string, text string) {\n\tfmt.Fprintf(conn, \"%s %s\\r\\n\", command, text)\n fmt.Printf(\"%s %s\\n\", command, text)\n}", "func String(w http.ResponseWriter, status int, format string,\n\targs ...interface{}) error {\n\tSetContentType(w, TextPlainCharsetUTF8)\n\tw.WriteHeader(status)\n\t_, err := fmt.Fprintf(w, format, args...)\n\treturn err\n}", "func (m *message) Type() int { return WRITE }", "func (b *Bot) Write(line string) {\n\tb.client.Write(line)\n}", "func writeMessage(w io.Writer, msg []byte) error {\n\tlength := uint16(len(msg))\n\tif int(length) != len(msg) {\n\t\tpanic(len(msg))\n\t}\n\terr := binary.Write(w, binary.BigEndian, length)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = w.Write(msg)\n\treturn err\n}", "func SendText(item string, config config.TwilioConfig, client *http.Client) error {\n\tendpoint := fmt.Sprintf(\"https://api.twilio.com/2010-04-01/Accounts/%s/Messages\", config.AccountSID)\n\n\tmsgData := url.Values{}\n\tmsgData.Set(\"To\", config.DestinationNumber)\n\tmsgData.Set(\"From\", config.SourceNumber)\n\tmsgData.Set(\"Body\", fmt.Sprintf(\"%s Ready for Purchase\", item))\n\tmsgDataReader := *strings.NewReader(msgData.Encode())\n\n\treq, _ := http.NewRequest(\"POST\", endpoint, &msgDataReader)\n\treq.SetBasicAuth(config.AccountSID, config.Token)\n\treq.Header.Add(\"Accept\", \"application/json\")\n\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n\tresp, _ := client.Do(req)\n\tif resp.StatusCode >= 200 && resp.StatusCode < 300 {\n\t\tvar data map[string]interface{}\n\t\tdecoder := json.NewDecoder(resp.Body)\n\t\terr := decoder.Decode(&data)\n\t\tif err == nil {\n\t\t\tfmt.Println(data[\"sid\"])\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tfmt.Println(resp.Body)\n\t}\n\n\treturn nil\n}", "func add_message(uname string, new_message string) (string, bool) {\n\tfilename := uname + \".txt\"\n\tcreate_and_lock(filename) // lock user message file for editing\n\tdefer lock_for_files_map[filename].Unlock()\n\n\tmessage_file, open_err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)\n\tdefer message_file.Close()\n\tif open_err != nil {\n\t\treturn fmt.Sprintf(\"error: Server open error%s\\n\", END_TAG), false\n\t}\n\n\t//write new message to file\n\tnewline := \"\\r\\n\"\n\ttext_to_write := new_message + newline + USER_MESSAGE_SEPERATOR + newline\n\tif _, write_err := message_file.WriteString(text_to_write); write_err != nil {\n\t\treturn fmt.Sprintf(\"error: server failed to write.%s\\n\", END_TAG), false\n\t} else {\n\t\treturn fmt.Sprintf(\"success: added message for %s.%s\\n\", uname, END_TAG), true\n\t}\n\n}", "func (h *Handler) SendText(ctx context.Context, text string, toID string) error {\n\tmsg, err := makeText(h.r, text)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error making message: %s\", err)\n\t}\n\n\tto, err := h.getPeer(toID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting peer: %s\", err)\n\t}\n\n\tif err := h.sendMessage(ctx, to, msg); err != nil {\n\t\treturn fmt.Errorf(\"error sending a text: %s\", err)\n\t}\n\n\th.sent <- fromProto(h.self, to, msg)\n\n\treturn nil\n}", "func (h *Beer) RespondText(c *gomatrix.Client, ev *gomatrix.Event, _, post string) error {\n\treturn SendText(c, ev.RoomID, h.Process(ev.Sender, post))\n}", "func (c *Conn) SendPlainText(to []string, from, subj, plaintext string) error {\n\treturn c.conn.SendPlainText(to, from, subj, plaintext)\n}", "func (client *Client) SendMessage(channel, text string) error {\n\tmsg := struct {\n\t\tID int `json:\"id\"`\n\t\tType string `json:\"type\"`\n\t\tChannel string `json:\"channel\"`\n\t\tText string `json:\"text\"`\n\t}{client.messageID, \"message\", channel, text}\n\n\tif err := client.conn.WriteJSON(msg); err != nil {\n\t\treturn err\n\t}\n\n\tclient.messageID++\n\n\treturn nil\n}", "func (t *TelegramMessage) Text() string {\n\treturn t.Message.Text\n}", "func (c *Client) Send(format string, args ...interface{}) (err error) {\n\tif _, err = c.w.WriteString(fmt.Sprintf(format, args...)); err != nil {\n\t\treturn\n\t}\n\treturn c.w.Flush()\n}", "func (c *Client) Write(msgType int, message []byte) error {\n\n\tif msgType == 0 {\n\t\treturn errors.New(\"Message type 0 is reserved\")\n\t}\n\n\tif c.status != Connected {\n\t\treturn errors.New(c.status.String())\n\t}\n\n\tmlen := len(message)\n\tif mlen > c.maxMsgSize {\n\t\treturn errors.New(\"Message exceeds maximum message length\")\n\t}\n\n\tc.toWrite <- &Message{MsgType: msgType, Data: message}\n\n\treturn nil\n}", "func (c *Cell) PlainText(b *bytes.Buffer) string {\n\tn := len(c.P)\n\tif n == 1 {\n\t\treturn c.P[0].PlainText(b)\n\t}\n\n\tb.Reset()\n\tfor i := range c.P {\n\t\tif i != n-1 {\n\t\t\tc.P[i].writePlainText(b)\n\t\t\tb.WriteByte('\\n')\n\t\t} else {\n\t\t\tc.P[i].writePlainText(b)\n\t\t}\n\t}\n\treturn b.String()\n}", "func Plaintext(ctx *fasthttp.RequestCtx) {\n\tctx.Response.SetBodyString(helloWorldStr)\n}", "func Plaintext(ctx *fasthttp.RequestCtx) {\n\tctx.Response.SetBodyString(helloWorldStr)\n}", "func PrintMessage(texto string) {\n\tfmt.Println(texto)\n}", "func Standard(w io.Writer, text string) {\n\tStandardFormat.Fprintln(w, text)\n}", "func (v *ViewView) writeln(msg string) {\n\tfmt.Fprintln(v.Writer, msg)\n}", "func main() {\n\tmyMessage := `Hello! I'm a raw-string!\n I can do this, and it's pretty\n cool!`\n\n\tfmt.Println(myMessage)\n}", "func (client *Client) EditMessageText(text string) *VoidResponse {\n\tbody := JSON{\n\t\t\"text\": text,\n\t}\n\tendpoint := client.baseURL + fmt.Sprintf(EndpointEditMessageText, client.accessToken)\n\trequest := gorequest.New().Type(gorequest.TypeJSON).Post(endpoint).Set(UserAgentHeader, UserAgent+\"/\"+Version).Send(body)\n\n\treturn &VoidResponse{\n\t\tClient: client,\n\t\tRequest: request,\n\t}\n}" ]
[ "0.6655747", "0.632213", "0.6149622", "0.6030877", "0.60090363", "0.5999739", "0.59934056", "0.5987086", "0.5954685", "0.59016705", "0.5841889", "0.58273524", "0.58256876", "0.5818543", "0.5768177", "0.57515097", "0.5703201", "0.5698121", "0.56870776", "0.56831807", "0.56763875", "0.56377196", "0.56354296", "0.5586818", "0.5580088", "0.557468", "0.5559139", "0.5546783", "0.5543407", "0.552855", "0.5523424", "0.551485", "0.5507457", "0.54797125", "0.5476503", "0.5472716", "0.54646283", "0.54556894", "0.544298", "0.5442737", "0.54271764", "0.540847", "0.5374632", "0.5372046", "0.5364331", "0.535355", "0.5332249", "0.53215444", "0.5317217", "0.5290765", "0.5287809", "0.5278951", "0.5274605", "0.526979", "0.5256776", "0.52563465", "0.5252358", "0.5241469", "0.5234856", "0.5225108", "0.5222471", "0.521509", "0.5209551", "0.52077866", "0.51994354", "0.5195307", "0.5194763", "0.51867926", "0.5179082", "0.51790684", "0.5169369", "0.5152203", "0.5142952", "0.513822", "0.51352334", "0.5126366", "0.5124527", "0.5110369", "0.51059115", "0.5102921", "0.510058", "0.5100189", "0.50969464", "0.50907344", "0.50860256", "0.5066275", "0.5059815", "0.50544584", "0.50495344", "0.50333697", "0.50285923", "0.50241554", "0.50183374", "0.5017311", "0.5017311", "0.5016192", "0.5010647", "0.50090384", "0.49956247", "0.4992054" ]
0.6367332
1
NewRolloutBlockLister returns a new RolloutBlockLister.
func NewRolloutBlockLister(indexer cache.Indexer) RolloutBlockLister { return &rolloutBlockLister{indexer: indexer} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s rolloutBlockNamespaceLister) Get(name string) (*v1alpha1.RolloutBlock, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"rolloutblock\"), name)\n\t}\n\treturn obj.(*v1alpha1.RolloutBlock), nil\n}", "func (s rolloutBlockNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.RolloutBlock, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RolloutBlock))\n\t})\n\treturn ret, err\n}", "func (s *rolloutBlockLister) RolloutBlocks(namespace string) RolloutBlockNamespaceLister {\n\treturn rolloutBlockNamespaceLister{indexer: s.indexer, namespace: namespace}\n}", "func (s *rolloutBlockLister) List(selector labels.Selector) (ret []*v1alpha1.RolloutBlock, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RolloutBlock))\n\t})\n\treturn ret, err\n}", "func New() *Blockstream {\n\treturn &Blockstream{}\n}", "func New(storage Storage) *Block {\n\tb := Block{\n\t\tstorage: storage,\n\t}\n\tb.Transactions = make([]transaction.Transaction, 0, 0)\n\treturn &b\n}", "func NewBlock(object dbus.BusObject) *Block {\n\treturn &Block{object}\n}", "func NewBlock(tx *Transaction) *Block {\n\t\n\treturn nil\n}", "func NewBundleLister(indexer cache.Indexer) BundleLister {\n\treturn &bundleLister{indexer: indexer}\n}", "func NewBlock() *Block {\n\treturn &Block{}\n}", "func New() *block {\n\treturn &block{\n\t\tbroadcastChan: make(chan Message, broadcastChanSize),\n\t\tbroadcastMsgSeen: map[string]struct{}{},\n\t}\n}", "func (t *Blockchain) New() *Blockchain {\n\tt = new(Blockchain)\n\tt.NewBlock(100, \"1\")\n\treturn t\n}", "func (c *Client) NewBlockFilter() (*QuantityResponse, error) {\n\trequest := c.newRequest(EthNewBlockFilter)\n\n\tresponse := &QuantityResponse{}\n\n\treturn response, c.send(request, response)\n}", "func NewBlock(typeName string, labels []string) *Block {\n\tblock := newBlock()\n\tblock.init(typeName, labels)\n\treturn block\n}", "func NewBlock(typeName string, labels []string) *Block {\n\tblock := newBlock()\n\tblock.init(typeName, labels)\n\treturn block\n}", "func NewBlock(index idx.Block, time Timestamp, events hash.Events, prevHash hash.Event) *Block {\n\treturn &Block{\n\t\tIndex: index,\n\t\tTime: time,\n\t\tEvents: events,\n\t\tPrevHash: prevHash,\n\t\tSkippedTxs: make([]uint, 0),\n\t}\n}", "func NewBlock(statements []sql.Node) *Block {\n\treturn &Block{statements: statements}\n}", "func NewBlockFilter(\n\tlogger log.Logger,\n\tlabelSelector labels.Selector,\n\tresolutionLevel compact.ResolutionLevel,\n\tcompactionLevel int,\n) *BlockFilter {\n\treturn &BlockFilter{\n\t\tlabelSelector: labelSelector,\n\t\tlogger: logger,\n\t\tresolutionLevel: resolutionLevel,\n\t\tcompactionLevel: compactionLevel,\n\t}\n}", "func NewBlock(b *block.Block, chain blockchainer.Blockchainer) Block {\n\tres := Block{\n\t\tBlock: *b,\n\t\tBlockMetadata: BlockMetadata{\n\t\t\tSize: io.GetVarSize(b),\n\t\t\tConfirmations: chain.BlockHeight() - b.Index + 1,\n\t\t},\n\t}\n\n\thash := chain.GetHeaderHash(int(b.Index) + 1)\n\tif !hash.Equals(util.Uint256{}) {\n\t\tres.NextBlockHash = &hash\n\t}\n\n\treturn res\n}", "func NewBlock() (*Block, error) {\n\tn, err := findLast()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th, err := ftoh(n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Hash: \" + h)\n\n\treturn &Block{Number: n + 1, PreviousHash: h}, nil\n}", "func NewLister() Lister {\n\treturn _lister{\n\t\tioUtil: iioutil.New(),\n\t\tdotYmlUnmarshaller: dotyml.NewUnmarshaller(),\n\t}\n}", "func NewHookLister(indexer cache.Indexer) HookLister {\n\treturn &hookLister{indexer: indexer}\n}", "func (*llcFactory) New(args *xreg.XactArgs) xreg.BucketEntry {\n\treturn &llcFactory{t: args.T, uuid: args.UUID}\n}", "func NewBlock(data *models.Block, opts ...options.Option[Block]) (newBlock *Block) {\n\treturn options.Apply(&Block{\n\t\tstrongChildren: make([]*Block, 0),\n\t\tweakChildren: make([]*Block, 0),\n\t\tlikedInsteadChildren: make([]*Block, 0),\n\t\tModelsBlock: data,\n\t}, opts)\n}", "func NewBlockchain() *Blockchain {\n\treturn CreateBlockchain()\n}", "func New(ctx context.Context, now NowFunc) *Blockchain {\n\tvar b = Blockchain{\n\t\tnow: now,\n\t}\n\n\tgenesisBlock := Block{\n\t\t0,\n\t\tb.now().String(),\n\t\t0,\n\t\t\"\",\n\t\t\"\",\n\t}\n\n\tb.Blocks = append(b.Blocks, genesisBlock)\n\n\treturn &b\n}", "func (bc *Blockchain) chainNewBlock(nonce int, previousHash [32]byte) *Block {\n\tb := NewBlock(nonce, previousHash, bc.transactionPool)\n\tbc.chain = append(bc.chain, b)\n\tbc.transactionPool = []*Transaction{}\n\treturn b\n}", "func NewBlockTranslator(cfg Config, client evmclient.Client, lggr logger.Logger) BlockTranslator {\n\tswitch cfg.ChainType() {\n\tcase config.ChainArbitrum:\n\t\treturn NewArbitrumBlockTranslator(client, lggr)\n\tcase config.ChainXDai, config.ChainMetis, config.ChainOptimismBedrock:\n\t\tfallthrough\n\tdefault:\n\t\treturn &l1BlockTranslator{}\n\t}\n}", "func NewBlockCache(capacity uint32) *BlockCache {\n\t// TODO: Fetch latest block number every 15s to know what can be cached\n\t// https://eth.wiki/json-rpc/API#eth_blocknumber\n\t// curl https://cloudflare-eth.com --data '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}'\n\treturn &BlockCache{\n\t\tentries: make(blockByNumberMap, capacity),\n\t\tcallCount: 0,\n\t\tcapacity: capacity,\n\t}\n}", "func NewBlockFilter() Filter {\n\treturn &blockFilter{}\n}", "func NewBlock(index int, data interface{}, date time.Time) *Block {\n\treturn &Block{\n\t\tIndex: index,\n\t\tDate: date,\n\t\tData: data,\n\t}\n}", "func NewBlock(version uint32,\n\tprevBlock []byte,\n\tmerkleRoot []byte,\n\ttimestamp uint32,\n\tbits []byte,\n\tnonce []byte,\n\ttotal uint32,\n\thashes [][]byte,\n\tflags []byte) *Block {\n\tresult := &Block{\n\t\tVersion: version,\n\t\tTimestamp: timestamp,\n\t\tTotal: total,\n\t\tHashes: hashes,\n\t\tFlags: flags,\n\t}\n\tcopy(result.PrevBlock[:32], prevBlock)\n\tcopy(result.MerkleRoot[:32], merkleRoot)\n\tcopy(result.Bits[:4], bits)\n\tcopy(result.Nonce[:4], nonce)\n\treturn result\n}", "func NewBlockchain(chain ...Block) *Blockchain {\n\treturn &Blockchain{chain}\n}", "func (I *Blockchain) NewBlock(proof uint64, previousHash string) {\n\t// In order to be able to create the first block\n\tif previousHash == \"\" {\n\t\tpreviousHash = \"1\"\n\t}\n\t// Create the block\n\tb := block{\n\t\tindex: I.currentIndex,\n\t\ttimestamp: time.Now().UnixNano(),\n\t\tproof: proof,\n\t\tpreviousHash: previousHash,\n\t\ttransactions: I.currentTransactions,\n\t}\n\t// Append the new block\n\tI.blocks = append(I.blocks, b)\n\t// Reset the transactions\n\tI.currentTransactions = make([]transaction, 0)\n\t// Update the index\n\tI.currentIndex += 1\n\t// Modify the last block variable\n\tI.lastBlock = b\n}", "func (blockchain *Blockchain) MineNewBlock(originalTxs []*Transaction) *Block {\n\t// Reward of mining a block\n\tcoinBaseTransaction := NewRewardTransacion()\n\ttxs := []*Transaction{coinBaseTransaction}\n\ttxs = append(txs, originalTxs...)\n\t// Verify transactions\n\tfor _, tx := range txs {\n\t\tif !tx.IsCoinBaseTransaction() {\n\t\t\tif blockchain.VerifityTransaction(tx, txs) == false {\n\t\t\t\tlog.Panic(\"Verify transaction failed...\")\n\t\t\t}\n\t\t}\n\t}\n\n\tDBName := fmt.Sprintf(DBName, os.Getenv(\"NODE_ID\"))\n\tdb, err := bolt.Open(DBName, 0600, nil)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tdefer db.Close()\n\t// Get the latest block\n\tvar block Block\n\terr = db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(BlockBucketName))\n\t\tif b != nil {\n\t\t\thash := b.Get([]byte(\"l\"))\n\t\t\tblockBytes := b.Get(hash)\n\t\t\tgobDecode(blockBytes, &block)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\t// Mine a new block\n\tnewBlock := NewBlock(txs, block.Height+1, block.BlockHash)\n\n\treturn newBlock\n}", "func NewBlockCache() *BlockCache {\n\treturn &BlockCache{\n\t\tm: make(map[string]bool),\n\t}\n}", "func (a *insight) NewBlock(id interface{}) *block {\n\tb := new(block)\n\tb.insight = a\n\tswitch v := id.(type) {\n\tcase int:\n\t\tb.Height = int(v)\n\t\tb.hash()\n\t\tb.pages()\n\t\tb.info()\n\t\treturn b\n\tcase string:\n\t\tb.Hash = string(v)\n\t\tb.pages()\n\t\tb.info()\n\t\treturn b\n\tcase nil:\n\t\treturn b.latestBlock()\n\t}\n\treturn nil\n}", "func newBlockfileMgr(id string, conf *Conf, indexConfig *blkstorage.IndexConfig, indexStore *leveldbhelper.DBHandle) *blockfileMgr {\n\tlogger.Debugf(\"newBlockfileMgr() initializing file-based block storage for ledger: %s \", id)\n\tvar rwMutexs []*sync.RWMutex\n\n\t//Determine the root directory for the blockfile storage, if it does not exist create it\n\trootDir := conf.getLedgerBlockDir(id)\n\t_, err := util.CreateDirIfMissing(rootDir)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error: %s\", err))\n\t}\n\t// Instantiate the manager, i.e. blockFileMgr structure\n\tmgr := &blockfileMgr{rootDir: rootDir, conf: conf, db: indexStore, rwMutexs: rwMutexs}\n\n\t// cp = checkpointInfo, retrieve from the database the file suffix or number of where blocks were stored.\n\t// It also retrieves the current size of that file and the last block number that was written to that file.\n\t// At init checkpointInfo:latestFileChunkSuffixNum=[0], latestFileChunksize=[0], lastBlockNumber=[0]\n\tcpInfo, err := mgr.loadCurrentInfo()\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Could not get block file info for current block file from db: %s\", err))\n\t}\n\tif cpInfo == nil {\n\t\tlogger.Info(`Getting block information from block storage`)\n\t\tif cpInfo, err = constructCheckpointInfoFromBlockFiles(rootDir); err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Could not build checkpoint info from block files: %s\", err))\n\t\t}\n\t\tlogger.Debugf(\"Info constructed by scanning the blocks dir = %s\", spew.Sdump(cpInfo))\n\t} else {\n\t\tlogger.Debug(`Synching block information from block storage (if needed)`)\n\t\tsyncCPInfoFromFS(rootDir, cpInfo)\n\t}\n\terr = mgr.saveCurrentInfo(cpInfo, true)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Could not save next block file info to db: %s\", err))\n\t}\n\n\tmgr.oldestFileChunkSuffixNum = syncOldestFileNum(rootDir)\n\t//If start up is a restart of an existing storage,new the rwMutex for the files\n\tif conf.dumpConf.Enabled {\n\t\tfor i := 0; i <= cpInfo.latestFileChunkSuffixNum; i++ {\n\t\t\trwMutex := new(sync.RWMutex)\n\t\t\tmgr.rwMutexs = append(mgr.rwMutexs, rwMutex)\n\t\t}\n\t}\n\tmgr.dumpMutex = new(sync.Mutex)\n\n\t//Open a writer to the file identified by the number and truncate it to only contain the latest block\n\t// that was completely saved (file system, index, cpinfo, etc)\n\tcurrentFileWriter, err := newBlockfileWriter(deriveBlockfilePath(rootDir, cpInfo.latestFileChunkSuffixNum))\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Could not open writer to current file: %s\", err))\n\t}\n\t//Truncate the file to remove excess past last block\n\terr = currentFileWriter.truncateFile(cpInfo.latestFileChunksize)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Could not truncate current file to known size in db: %s\", err))\n\t}\n\n\t// Create a new KeyValue store database handler for the blocks index in the keyvalue database\n\tmgr.index = newBlockIndex(indexConfig, indexStore)\n\n\t// Update the manager with the checkpoint info and the file writer\n\tmgr.cpInfo = cpInfo\n\tmgr.currentFileWriter = currentFileWriter\n\t// Create a checkpoint condition (event) variable, for the goroutine waiting for\n\t// or announcing the occurrence of an event.\n\tmgr.cpInfoCond = sync.NewCond(&sync.Mutex{})\n\n\t// init BlockchainInfo for external API's\n\tbcInfo := &common.BlockchainInfo{\n\t\tHeight: 0,\n\t\tCurrentBlockHash: nil,\n\t\tPreviousBlockHash: nil}\n\n\tif !cpInfo.isChainEmpty {\n\t\t//If start up is a restart of an existing storage, sync the index from block storage and update BlockchainInfo for external API's\n\t\tmgr.syncIndex()\n\t\tlastBlockHeader, err := mgr.retrieveBlockHeaderByNumber(cpInfo.lastBlockNumber)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Could not retrieve header of the last block form file: %s\", err))\n\t\t}\n\t\tlastBlockHash := lastBlockHeader.Hash()\n\t\tpreviousBlockHash := lastBlockHeader.PreviousHash\n\t\tbcInfo = &common.BlockchainInfo{\n\t\t\tHeight: cpInfo.lastBlockNumber + 1,\n\t\t\tCurrentBlockHash: lastBlockHash,\n\t\t\tPreviousBlockHash: previousBlockHash}\n\t}\n\tmgr.bcInfo.Store(bcInfo)\n\treturn mgr\n}", "func NewBlock(blk *types.Block, repo repository.Repository) *Block {\n\treturn &Block{\n\t\trepo: repo,\n\t\tBlock: *blk,\n\t}\n}", "func NewSMBLister(indexer cache.Indexer) SMBLister {\n\treturn &sMBLister{indexer: indexer}\n}", "func NewBlock(oldBlock Block, data string) Block {\n\t// fmt.Println(\"******TODO: IMPLEMENT NewBlock!******\")\n\tblock := Block{Data: data, Timestamp: time.Now().Unix(), PrevHash: oldBlock.Hash, Hash: []byte{}}\n\tblock.Hash = block.calculateHash()\n\t// fmt.Println(\"data: \" + block.Data)\n\t// fmt.Printf(\"timestamp: %d\", block.Timestamp)\n\t// fmt.Println()\n\t// fmt.Printf(\"preHash: %x\", block.PrevHash)\n\t// fmt.Println()\n\t// fmt.Printf(\"currentHash: %x\", block.Hash)\n\t// fmt.Println()\n\t// fmt.Println(\"******TODO: END NewBlock!******\")\n\t// fmt.Println()\n\t// fmt.Println()\n\t// fmt.Println()\n\treturn block\n}", "func NewBlockTranslator(chain Chain, client eth.Client) BlockTranslator {\n\tif chain.IsArbitrum() {\n\t\treturn NewArbitrumBlockTranslator(client)\n\t} else if chain.IsOptimism() {\n\t\treturn newOptimismBlockTranslator()\n\t}\n\treturn &l1BlockTranslator{}\n}", "func NewBlock(t *testing.T, bc blockchainer.Blockchainer, offset uint32, primary uint32, txs ...*transaction.Transaction) *block.Block {\n\twitness := transaction.Witness{VerificationScript: MultisigVerificationScript()}\n\theight := bc.BlockHeight()\n\th := bc.GetHeaderHash(int(height))\n\thdr, err := bc.GetHeader(h)\n\trequire.NoError(t, err)\n\tb := &block.Block{\n\t\tHeader: block.Header{\n\t\t\tPrevHash: hdr.Hash(),\n\t\t\tTimestamp: (uint64(time.Now().UTC().Unix()) + uint64(hdr.Index)) * 1000,\n\t\t\tIndex: hdr.Index + offset,\n\t\t\tPrimaryIndex: byte(primary),\n\t\t\tNextConsensus: witness.ScriptHash(),\n\t\t\tScript: witness,\n\t\t},\n\t\tTransactions: txs,\n\t}\n\tb.RebuildMerkleRoot()\n\n\tb.Script.InvocationScript = Sign(b)\n\treturn b\n}", "func NewBlock(hash string) *pfs.Block {\n\treturn &pfs.Block{\n\t\tHash: hash,\n\t}\n}", "func (cm *chainManager) MintNewBlock(timestamp time.Time) (*block.Block, error) {\n\treturn cm.bc.MintNewBlock(timestamp)\n}", "func (s *service) MineNewBlock(lastBlock *Block, data []Transaction) (*Block, error) {\n\t// validations\n\tif lastBlock == nil {\n\t\treturn nil, ErrMissingLastBlock\n\t}\n\n\tdifficulty := lastBlock.Difficulty\n\tvar nonce uint32\n\tvar timestamp int64\n\tvar hash string\n\tfor {\n\t\tnonce++\n\t\ttimestamp = time.Now().UnixNano()\n\t\tdifficulty = adjustBlockDifficulty(*lastBlock, timestamp, s.MineRate)\n\t\thash = hashing.SHA256Hash(timestamp, *lastBlock.Hash, data, nonce, difficulty)\n\t\tif hexStringToBinary(hash)[:difficulty] == strings.Repeat(\"0\", int(difficulty)) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn yieldBlock(timestamp, lastBlock.Hash, &hash, data, nonce, difficulty), nil\n}", "func (self *BlockChain) NewBlock(proof int, previous_hash string) {\n\n\t// check if previous hash matches self.hash(self.chain[-1])\n\tt := time.Now()\n\n\tblock := Block{\n\t\tIndex: len(self.Chain) + 1,\n\t\tTimestamp: t.UnixNano(),\n\t\tTransactions: self.CurrentTransactions,\n\t\tProof: proof,\n\t\tPreviousHash: previous_hash}\n\n\t// Reset the current list of transactions\n\tself.CurrentTransactions = nil\n\tself.Chain = append(self.Chain, block)\n}", "func NewBlock(transactions []*Transaction, prevBlockHash []byte, height int) *Block {\n\tblock := &Block{time.Now().Unix(), transactions, prevBlockHash, []byte{}, 0, height}\n\tblock.POW()\n\treturn block\n}", "func NewBlock(data *SPOTuple, prevBlockHash string) (*Block, error) {\n\n\tblock := &Block{\n\t\tBlockId: nuid.Next(),\n\t\tData: data,\n\t\tPrevBlockHash: prevBlockHash,\n\t\tHash: \"\",\n\t\tSig: \"\",\n\t\tAuthor: cs.PublicID(),\n\t\tSender: cs.PublicID(),\n\t}\n\n\t// assign new hash\n\tblock.setHash()\n\n\t// now sign the completed block\n\terr := block.sign()\n\tif err != nil {\n\t\tlog.Println(\"unable to sign block: \", err)\n\t\treturn nil, err\n\t}\n\n\treturn block, nil\n}", "func NewRawBlock() *RawBlock {\n\treturn &RawBlock{}\n}", "func (s Store) GetBlock (hash string) (*types.FullSignedBlock, error) {\r\n\t// Open badger\r\n\tstor, err := badger.Open(badger.DefaultOptions(s.StorFileLocation))\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tdefer stor.Close()\r\n\r\n\tvar block types.FullSignedBlock\r\n\terr = stor.Update(func(txn *badger.Txn) error {\r\n\t\tbytes, err := readStringIndex (txn, hash, HashKeyPrefix)\r\n\t\tif err != nil{\r\n\t\t\treturn err\r\n\t\t}\r\n\t\terr = json.Unmarshal(bytes, &block)\r\n\r\n\t\treturn err\r\n\t})\r\n\r\n\treturn &block, err\r\n}", "func NewBlockHandler(state *state.State, blockRefeeder *BlockRefeeder) *BlockHandler {\r\n\tresult := BlockHandler{\r\n\t\tstate: state,\r\n\t\tblockRefeeder: blockRefeeder,\r\n\t}\r\n\treturn &result\r\n}", "func (brf *BlockReaderFactory) newBlockReader(peer DomainPeer) (BlockReader, error) {\n\n\t// A read request to a datanode:\n\t// +-----------------------------------------------------------+\n\t// | Data Transfer Protocol Version, int16 |\n\t// +-----------------------------------------------------------+\n\t// | Op code, 1 byte (READ_BLOCK = 0x51) |\n\t// +-----------------------------------------------------------+\n\t// | varint length + OpReadBlockProto |\n\t// +-----------------------------------------------------------+\n\n\tproto := &OpReadBlockProto{\n\t\tHeader: &ClientOperationHeaderProto{\n\t\t\tBaseHeader: &BaseHeaderProto{\n\t\t\t\tBlock: &brf.block,\n\t\t\t\tToken: &brf.blockToken,\n\t\t\t},\n\t\t\tClientName: proto.String(brf.clientName),\n\t\t},\n\t\tOffset: proto.Uint64(uint64(brf.startOffset)),\n\t\tLen: proto.Uint64(uint64(brf.length)),\n\t\tSendChecksums: proto.Bool(brf.verifyChecksum),\n\t}\n\tif err := WriteBlockOpRequest(peer.out, ReadBlockOp, proto); err != nil {\n\t\t//todo\n\t\treturn nil, err\n\t} else {\n\t\tif status, err := ReadBlockOpResponse(peer.in); err != nil {\n\t\t\t//todo\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tif *status.Status != Status_SUCCESS {\n\t\t\t\tif *status.Status == Status_ERROR_ACCESS_TOKEN {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Got access token error,status message %s \\n\", status.GetMessage())\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Got error,status message %s \\n\", status.GetMessage())\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tchecksumInfo := status.GetReadOpChecksumInfo()\n\t\t\t\tchecksum := checksumInfo.GetChecksum()\n\n\t\t\t\tfirstChunkOffset := int64(checksumInfo.GetChunkOffset())\n\n\t\t\t\tif firstChunkOffset < 0 || firstChunkOffset > brf.startOffset || firstChunkOffset <= (brf.startOffset-int64(checksum.GetBytesPerChecksum())) {\n\t\t\t\t\t//todo\n\t\t\t\t\treturn nil, fmt.Errorf(\"BlockReader: error in first chunk offset ( %d ) startOffset is %d for file %s\\n\", firstChunkOffset, brf.startOffset, brf.fileName)\n\t\t\t\t}\n\n\t\t\t\tif dataChecksum, err := NewDataChecksum(checksum); err != nil {\n\t\t\t\t\t//todo\n\t\t\t\t\treturn nil, fmt.Errorf(\"BlockReader: error in NewDataChecksum err is %s \\n\", err)\n\t\t\t\t} else {\n\t\t\t\t\tblockReader := NewRemoteBlockReader(brf.fileName, int64(brf.block.GetBlockId()), dataChecksum, brf.verifyChecksum,\n\t\t\t\t\t\tbrf.startOffset, firstChunkOffset, brf.length, peer, *brf.datanode.GetId())\n\t\t\t\t\treturn blockReader, nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}", "func (wc *WalletClient) NewBlock(b Block) error {\n\t_, err := wc.POST(\"/new-block\", b.Json())\n\treturn err\n}", "func newBlock(lastBlock Block, seed int, npeer string, transactions []SignedTransaction) Block {\n\tvar newBlock Block\n\n\tnewBlock.Seed = seed\n\tnewBlock.Index = lastBlock.Index + 1\n\tnewBlock.LastHash = lastBlock.Hash\n\tnewBlock.Peer = npeer\n\tnewBlock.SpecialAccounts = lastBlock.SpecialAccounts\n\tnewBlock.Transactions = transactions\n\tnewBlock.Hash = blockHash(newBlock)\n\treturn newBlock\n}", "func NewBlockReader(salt crypto.Salt, pass []byte, cipher crypto.Cipher) BlockReader {\n\tkey := salt.Apply(pass, cipher.KeySize())\n\treturn BlockReaderFn(func(b secret.Block) ([]byte, error) {\n\t\treturn b.Decrypt(key)\n\t})\n}", "func NewBlock(index uint64, ordered Events) *Block {\n\tevents := make(hash.EventsSlice, len(ordered))\n\tfor i, e := range ordered {\n\t\tevents[i] = e.Hash()\n\t}\n\n\treturn &Block{\n\t\tIndex: index,\n\t\tEvents: events,\n\t}\n}", "func NewBlock(chain uint64, producer Address) *StBlock {\n\tvar hashPowerLimit uint64\n\tvar blockInterval uint64\n\tvar pStat BaseInfo\n\tout := new(StBlock)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatHashPower}, &hashPowerLimit)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBlockInterval}, &blockInterval)\n\n\tif pStat.ID == 0 {\n\t\tlog.Println(\"fail to get the last block. chain:\", chain)\n\t\treturn nil\n\t}\n\n\thashPowerLimit = hashPowerLimit / 1000\n\tif hashPowerLimit < minHPLimit {\n\t\thashPowerLimit = minHPLimit\n\t}\n\n\tout.HashpowerLimit = hashPowerLimit\n\n\tif pStat.ID == 1 && chain > 1 {\n\t\tpStat.Time = pStat.Time + blockSyncMax + blockSyncMin + TimeSecond\n\t} else {\n\t\tpStat.Time += blockInterval\n\t}\n\n\tout.Previous = pStat.Key\n\tout.Producer = producer\n\tout.Time = pStat.Time\n\n\tout.Chain = chain\n\tout.Index = pStat.ID + 1\n\n\tif pStat.Chain > 1 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID+1), &key)\n\t\tgetDataFormLog(chain/2, logBlockInfo{}, key[:], &tmp)\n\t\tif out.Index != 2 && !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID+2), &key2)\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.Parent = key2\n\t\t\t} else {\n\t\t\t\tout.Parent = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else {\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID), &key)\n\t\t\tout.Parent = key\n\t\t}\n\t}\n\tif pStat.LeftChildID > 0 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID+1), &key)\n\t\tgetDataFormLog(2*chain, logBlockInfo{}, key[:], &tmp)\n\t\tif !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID+2), &key2)\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.LeftChild = key2\n\t\t\t} else {\n\t\t\t\tout.LeftChild = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else if pStat.LeftChildID == 1 {\n\t\t\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID), &key)\n\t\t\tout.LeftChild = key\n\t\t} else {\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID), &key)\n\t\t\tout.LeftChild = key\n\t\t}\n\t}\n\tif pStat.RightChildID > 0 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID+1), &key)\n\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, key[:], &tmp)\n\t\tif !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID+2), &key2)\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.RightChild = key2\n\t\t\t} else {\n\t\t\t\tout.RightChild = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else if pStat.RightChildID == 1 {\n\t\t\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(pStat.RightChildID), &key)\n\t\t\tout.RightChild = key\n\t\t} else {\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID), &key)\n\t\t\tout.RightChild = key\n\t\t}\n\t}\n\n\treturn out\n}", "func generateNewBlock(oldBlock Block, dataPayload string) (Block, error) {\n\n\tvar newBlock Block\n\ttimeNow := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = timeNow.String()\n\n\tnewEvent, err := dataPayloadtoServiceEvent(dataPayload)\n\n\tif err != nil {\n\t\tlog.Println(\"ERROR: Unable to convert data payload into ServiceEvent for new block generation.\")\n\t}\n\n\tnewBlock.Event = newEvent\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Hash = calculateHash(newBlock)\n\n\treturn newBlock, nil\n}", "func newBlockstoreManager(bs bstore.Blockstore, workerCount int) *blockstoreManager {\n\treturn &blockstoreManager{\n\t\tbs: bs,\n\t\tworkerCount: workerCount,\n\t\tjobs: make(chan func()),\n\t}\n}", "func NewBlockWriter(rand io.Reader, orgId, streamId uuid.UUID, salt crypto.Salt, pass []byte, cipher crypto.Cipher) BlockWriter {\n\tidx, key := 0, salt.Apply(pass, cipher.KeySize())\n\treturn BlockWriterFn(func(data []byte) (next secret.Block, err error) {\n\t\tdefer func() {\n\t\t\tidx++\n\t\t}()\n\n\t\tct, err := cipher.Apply(rand, key, data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tnext = secret.Block{orgId, streamId, idx, ct}\n\t\treturn\n\t})\n}", "func (*blockR) NewStruct() *blockR {\n\treturn &blockR{}\n}", "func NewBlock(header *Header, txs []*Transaction, receipts []*Receipt, signs []*PbftSign) *Block {\n\tb := &Block{header: CopyHeader(header)}\n\n\t// TODO: panic if len(txs) != len(receipts)\n\tif len(txs) == 0 {\n\t\tb.header.TxHash = EmptyRootHash\n\t} else {\n\t\tb.header.TxHash = DeriveSha(Transactions(txs))\n\t\tb.transactions = make(Transactions, len(txs))\n\t\tcopy(b.transactions, txs)\n\t}\n\n\tif len(receipts) == 0 {\n\t\tb.header.ReceiptHash = EmptyRootHash\n\t} else {\n\t\tb.header.ReceiptHash = DeriveSha(Receipts(receipts))\n\t\tb.header.Bloom = CreateBloom(receipts)\n\t}\n\n\tif len(receipts) == 0 {\n\t\tb.header.ReceiptHash = EmptyRootHash\n\t} else {\n\t\tb.header.ReceiptHash = DeriveSha(Receipts(receipts))\n\t\tb.header.Bloom = CreateBloom(receipts)\n\t}\n\n\tif len(signs) != 0 {\n\t\tb.signs = make(PbftSigns, len(signs))\n\t\tcopy(b.signs, signs)\n\t}\n\n\treturn b\n}", "func NewBlockRetriever(\n\topts BlockRetrieverOptions,\n\tfsOpts Options,\n) BlockRetriever {\n\tsegmentReaderPool := opts.SegmentReaderPool()\n\treqPoolOpts := opts.RequestPoolOptions()\n\treqPool := newRetrieveRequestPool(segmentReaderPool, reqPoolOpts)\n\treqPool.Init()\n\treturn &blockRetriever{\n\t\topts: opts,\n\t\tfsOpts: fsOpts,\n\t\tnewSeekerMgrFn: NewSeekerManager,\n\t\treqPool: reqPool,\n\t\tbytesPool: opts.BytesPool(),\n\t\tstatus: blockRetrieverNotOpen,\n\t\tnotifyFetch: make(chan struct{}, 1),\n\t}\n}", "func (w *Writer) newBlockWriter(typ byte) *blockWriter {\n\tblock := w.block\n\n\tvar blockStart uint32\n\tif w.next == 0 {\n\t\thb := w.headerBytes()\n\t\tblockStart = uint32(copy(block, hb))\n\t}\n\n\tbw := newBlockWriter(typ, block, blockStart)\n\tbw.restartInterval = w.opts.RestartInterval\n\treturn bw\n}", "func (ts *Tipset) Block(miner Miner, winCount int64, msgs ...*ApplicableMessage) {\n\tblock := Block{\n\t\tMinerAddr: miner.MinerActorAddr.ID,\n\t\tWinCount: winCount,\n\t}\n\tfor _, am := range msgs {\n\t\tblock.Messages = append(block.Messages, MustSerialize(am.Message))\n\n\t\t// if we see this message for the first time, add it to the `msgIdx` map and to the `orderMsgs` slice.\n\t\tif _, ok := ts.tss.msgIdx[am.Message.Cid()]; !ok {\n\t\t\tts.tss.msgIdx[am.Message.Cid()] = am\n\t\t\tts.tss.orderedMsgs = append(ts.tss.orderedMsgs, am)\n\t\t}\n\t}\n\n\tts.Blocks = append(ts.Blocks, block)\n}", "func NewBeeLister(indexer cache.Indexer) BeeLister {\n\treturn &beeLister{indexer: indexer}\n}", "func newBlockImporter(db database.DB, r io.ReadSeeker) (*blockImporter, error) {\n\t// Create the transaction and address indexes if needed.\n\t//\n\t// CAUTION: the txindex needs to be first in the indexes array because\n\t// the addrindex uses data from the txindex during catchup. If the\n\t// addrindex is run first, it may not have the transactions from the\n\t// current block indexed.\n\tvar indexes []indexers.Indexer\n\tif cfg.TxIndex || cfg.AddrIndex {\n\t\t// Enable transaction index if address index is enabled since it\n\t\t// requires it.\n\t\tif !cfg.TxIndex {\n\t\t\tlog.Infof(\"Transaction index enabled because it is \" +\n\t\t\t\t\"required by the address index\")\n\t\t\tcfg.TxIndex = true\n\t\t} else {\n\t\t\tlog.Info(\"Transaction index is enabled\")\n\t\t}\n\t\tindexes = append(indexes, indexers.NewTxIndex(db))\n\t}\n\tif cfg.AddrIndex {\n\t\tlog.Info(\"Address index is enabled\")\n\t\tindexes = append(indexes, indexers.NewAddrIndex(db, activeNetParams))\n\t}\n\n\t// Create an index manager if any of the optional indexes are enabled.\n\tvar indexManager blockchain.IndexManager\n\tif len(indexes) > 0 {\n\t\tindexManager = indexers.NewManager(db, indexes)\n\t}\n\n\tchain, err := blockchain.New(&blockchain.Config{\n\t\tDB: db,\n\t\tChainParams: activeNetParams,\n\t\tTimeSource: blockchain.NewMedianTime(),\n\t\tIndexManager: indexManager,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &blockImporter{\n\t\tdb: db,\n\t\tr: r,\n\t\tprocessQueue: make(chan []byte, 2),\n\t\tdoneChan: make(chan bool),\n\t\terrChan: make(chan error),\n\t\tquit: make(chan struct{}),\n\t\tchain: chain,\n\t\tlastLogTime: time.Now(),\n\t}, nil\n}", "func NewBlock(data string, transactions []*Tx, prevBlockHash []byte) *Block {\n\tblock := &Block{\n\t\tIdentifier: internal.GenerateID(),\n\t\tData: []byte(data),\n\t\tTransactions: transactions,\n\t\tPrevBlockHash: prevBlockHash,\n\t\tTimestamp: time.Now().Unix(),\n\t}\n\n\tpow := NewPow(block)\n\tnonce, hash := pow.Run()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\treturn block\n}", "func newBlock(prevHash [32]byte, prevHashWithoutTx [32]byte, commitmentProof [crypto.COMM_PROOF_LENGTH]byte, height uint32) *protocol.Block {\n\tblock := new(protocol.Block)\n\tblock.PrevHash = prevHash\n\tblock.PrevHashWithoutTx = prevHashWithoutTx\n\tblock.CommitmentProof = commitmentProof\n\tblock.Height = height\n\tblock.StateCopy = make(map[[32]byte]*protocol.Account)\n\tblock.Aggregated = false\n\n\treturn block\n}", "func NewBlock(transactions []*Transaction, preBlockHash []byte) *Block {\n\tb := &Block{time.Now().Unix(), transactions, preBlockHash, []byte{}, 252, 0}\n\n\tpow := NewProofOfWork(b)\n\tnonce, hash := pow.Run()\n\n\tb.Nonce = nonce\n\tb.Hash = hash[:]\n\n\treturn b\n}", "func NewBlock(width float64, height float64) *Block {\n\tb := &Block{}\n\tb.contents = &contentstream.ContentStreamOperations{}\n\tb.resources = model.NewPdfPageResources()\n\tb.width = width\n\tb.height = height\n\treturn b\n}", "func NewBlock(seqNum uint64, previousHash []byte) *cb.Block {\n\tblock := &cb.Block{}\n\tblock.Header = &cb.BlockHeader{}\n\tblock.Header.Number = seqNum\n\tblock.Header.PreviousHash = previousHash\n\tblock.Header.DataHash = []byte{}\n\tblock.Data = &cb.BlockData{}\n\n\tvar metadataContents [][]byte\n\tfor i := 0; i < len(cb.BlockMetadataIndex_name); i++ {\n\t\tmetadataContents = append(metadataContents, []byte{})\n\t}\n\tblock.Metadata = &cb.BlockMetadata{Metadata: metadataContents}\n\n\treturn block\n}", "func New(workers *workerpool.Group, evictionState *eviction.State, slotTimeProviderFunc func() *slot.TimeProvider, latestCommitmentFunc func(slot.Index) (*commitment.Commitment, error), opts ...options.Option[BlockDAG]) (newBlockDAG *BlockDAG) {\n\treturn options.Apply(&BlockDAG{\n\t\tevents: blockdag.NewEvents(),\n\t\tevictionState: evictionState,\n\t\tslotTimeProviderFunc: slotTimeProviderFunc,\n\t\tmemStorage: memstorage.NewSlotStorage[models.BlockID, *blockdag.Block](),\n\t\tcommitmentFunc: latestCommitmentFunc,\n\t\tfutureBlocks: memstorage.NewSlotStorage[commitment.ID, *advancedset.AdvancedSet[*blockdag.Block]](),\n\t\tWorkers: workers,\n\t\t// do not use workerpool to make sure things run synchronously\n\t\t//workerPool: workers.CreatePool(\"Solidifier\", 2),\n\n\t}, opts,\n\t\tfunc(b *BlockDAG) {\n\t\t\tb.solidifier = causalordersync.New(\n\t\t\t\tb.workerPool,\n\t\t\t\tb.Block,\n\t\t\t\t(*blockdag.Block).IsSolid,\n\t\t\t\tb.markSolid,\n\t\t\t\tb.markInvalid,\n\t\t\t\t(*blockdag.Block).Parents,\n\t\t\t\tcausalordersync.WithReferenceValidator[models.BlockID](checkReference),\n\t\t\t)\n\n\t\t\tevictionState.Events.SlotEvicted.Hook(b.evictSlot /*, event.WithWorkerPool(b.workerPool)*/)\n\t\t},\n\t\t(*BlockDAG).TriggerConstructed,\n\t\t(*BlockDAG).TriggerInitialized,\n\t)\n}", "func (c *Client) Block() *Block {\n\treturn &Block{c}\n}", "func NewBlockchain() (*Blockchain, error) {\n\tdb, rel, err := OpenBlockChain()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = db.Get([]byte(\"l\"), nil)\n\tif err == leveldb.ErrNotFound {\n\t\tb := Blockchain{}\n\t\tgenesis := GenesisBlock()\n\t\t//TODO: use add block instead\n\t\tb.Tip = genesis\n\t\tb.GenesisHash = genesis.Hash\n\t\traw, _ := proto.Marshal(genesis)\n\t\terr = db.Put(\n\t\t\tbytes.Join([][]byte{\n\t\t\t\t[]byte(\"b\"), genesis.Hash}, []byte{}), raw, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = db.Put([]byte(\"l\"), genesis.Hash, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = rel.Put(genesis.Hash, []byte{}, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tb.DB = db\n\t\tb.Relation = rel\n\t\treturn &b, nil\n\t}\n\treturn nil, Consts.ErrBlockchainExists\n}", "func NewBlock(_data string, _prevHash []byte) *Block {\n\t_block := &Block{\n\t\tTimestamp: time.Now().Unix(),\n\t\tData: []byte(_data),\n\t\tPrevHash: _prevHash,\n\t\tHash: []byte{},\n\t}\n\n\tpow := NewProofOfWork(_block)\n\tnonce, hash := pow.Run()\n\n\t_block.Nonce = nonce\n\t_block.Hash = hash[:]\n\n\treturn _block\n}", "func newBlock(t nbt.Tag) BlockState {\r\n\tblock := BlockState{}\r\n\tblock.Name = t.Compound()[\"Name\"].String()\r\n\tblock.parseProperties(t)\r\n\treturn block\r\n}", "func NewTestBlocklist() *blocklist.Blocklist {\n\tlist := blocklist.New()\n\tlist.Name = \"test\"\n\tlist.Domains = []string{\"www.reddit.com\", \"news.ycombinator.com\"}\n\n\treturn list\n}", "func NewBlock(tlvType uint32, value []byte) *Block {\n\tvar block Block\n\tblock.tlvType = tlvType\n\tblock.value = value\n\t// copy(block.value, value)\n\treturn &block\n}", "func NewBlock(version uint32, prevBlock []byte, merkleRoot []byte, timestamp uint32, bits []byte, nonce []byte, txHashes [][]byte) *Block {\n\tblock := &Block{Version: version, Timestamp: timestamp}\n\tcopy(block.PrevBlock[:32], prevBlock)\n\tcopy(block.MerkleRoot[:32], merkleRoot)\n\tcopy(block.Bits[:4], bits)\n\tcopy(block.Nonce[:4], nonce)\n\tblock.TxHashes = txHashes\n\treturn block\n}", "func NewBlockCache(dbPath string, chainName string, startHeight int, syncFromHeight int) *BlockCache {\n\tc := &BlockCache{}\n\tc.firstBlock = startHeight\n\tc.nextBlock = startHeight\n\tc.lengthsName, c.blocksName = dbFileNames(dbPath, chainName)\n\tvar err error\n\tif err := os.MkdirAll(filepath.Join(dbPath, chainName), 0755); err != nil {\n\t\tLog.Fatal(\"mkdir \", dbPath, \" failed: \", err)\n\t}\n\tc.blocksFile, err = os.OpenFile(c.blocksName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)\n\tif err != nil {\n\t\tLog.Fatal(\"open \", c.blocksName, \" failed: \", err)\n\t}\n\tc.lengthsFile, err = os.OpenFile(c.lengthsName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)\n\tif err != nil {\n\t\tLog.Fatal(\"open \", c.lengthsName, \" failed: \", err)\n\t}\n\tlengths, err := ioutil.ReadFile(c.lengthsName)\n\tif err != nil {\n\t\tLog.Fatal(\"read \", c.lengthsName, \" failed: \", err)\n\t}\n\t// 4 bytes per lengths[] value (block length)\n\tif syncFromHeight >= 0 {\n\t\tif syncFromHeight < startHeight {\n\t\t\tsyncFromHeight = startHeight\n\t\t}\n\t\tif (syncFromHeight-startHeight)*4 < len(lengths) {\n\t\t\t// discard the entries at and beyond (newer than) the specified height\n\t\t\tlengths = lengths[:(syncFromHeight-startHeight)*4]\n\t\t}\n\t}\n\n\t// The last entry in starts[] is where to write the next block.\n\tvar offset int64\n\tc.starts = nil\n\tc.starts = append(c.starts, 0)\n\tnBlocks := len(lengths) / 4\n\tLog.Info(\"Reading \", nBlocks, \" blocks (since Sapling activation) from disk cache ...\")\n\tfor i := 0; i < nBlocks; i++ {\n\t\tif len(lengths[:4]) < 4 {\n\t\t\tLog.Warning(\"lengths file has a partial entry\")\n\t\t\tc.recoverFromCorruption(c.nextBlock)\n\t\t\tbreak\n\t\t}\n\t\tlength := binary.LittleEndian.Uint32(lengths[i*4 : (i+1)*4])\n\t\tif length < 74 || length > 4*1000*1000 {\n\t\t\tLog.Warning(\"lengths file has impossible value \", length)\n\t\t\tc.recoverFromCorruption(c.nextBlock)\n\t\t\tbreak\n\t\t}\n\t\toffset += int64(length) + 8\n\t\tc.starts = append(c.starts, offset)\n\t\t// Check for corruption.\n\t\tblock := c.readBlock(c.nextBlock)\n\t\tif block == nil {\n\t\t\tLog.Warning(\"error reading block\")\n\t\t\tc.recoverFromCorruption(c.nextBlock)\n\t\t\tbreak\n\t\t}\n\t\tc.nextBlock++\n\t}\n\tc.setDbFiles(c.nextBlock)\n\tLog.Info(\"Done reading \", c.nextBlock-c.firstBlock, \" blocks from disk cache\")\n\treturn c\n}", "func NewBlock(\n\tblockStart xtime.UnixNano,\n\tmd namespace.Metadata,\n\tblockOpts BlockOptions,\n\tnamespaceRuntimeOptsMgr namespace.RuntimeOptionsManager,\n\topts Options,\n) (Block, error) {\n\tblockSize := md.Options().IndexOptions().BlockSize()\n\tiopts := opts.InstrumentOptions()\n\tscope := iopts.MetricsScope().SubScope(\"index\").SubScope(\"block\")\n\tiopts = iopts.SetMetricsScope(scope)\n\n\tcpus := int(math.Max(1, math.Ceil(0.25*float64(runtime.GOMAXPROCS(0)))))\n\tcachedSearchesWorkers := xsync.NewWorkerPool(cpus)\n\tcachedSearchesWorkers.Init()\n\n\tsegs := newMutableSegments(\n\t\tmd,\n\t\tblockStart,\n\t\topts,\n\t\tblockOpts,\n\t\tcachedSearchesWorkers,\n\t\tnamespaceRuntimeOptsMgr,\n\t\tiopts,\n\t)\n\n\tcoldSegs := newMutableSegments(\n\t\tmd,\n\t\tblockStart,\n\t\topts,\n\t\tblockOpts,\n\t\tcachedSearchesWorkers,\n\t\tnamespaceRuntimeOptsMgr,\n\t\tiopts,\n\t)\n\n\t// NB(bodu): The length of coldMutableSegments is always at least 1.\n\tcoldMutableSegments := []*mutableSegments{coldSegs}\n\tb := &block{\n\t\tstate: blockStateOpen,\n\t\tblockStart: blockStart,\n\t\tblockEnd: blockStart.Add(blockSize),\n\t\tblockSize: blockSize,\n\t\tblockOpts: blockOpts,\n\t\tcachedSearchesWorkers: cachedSearchesWorkers,\n\t\tmutableSegments: segs,\n\t\tcoldMutableSegments: coldMutableSegments,\n\t\tshardRangesSegmentsByVolumeType: make(shardRangesSegmentsByVolumeType),\n\t\topts: opts,\n\t\tiopts: iopts,\n\t\tnsMD: md,\n\t\tnamespaceRuntimeOptsMgr: namespaceRuntimeOptsMgr,\n\t\tmetrics: newBlockMetrics(scope),\n\t\tlogger: iopts.Logger(),\n\t\tfetchDocsLimit: opts.QueryLimits().FetchDocsLimit(),\n\t\taggDocsLimit: opts.QueryLimits().AggregateDocsLimit(),\n\t}\n\tb.newFieldsAndTermsIteratorFn = newFieldsAndTermsIterator\n\tb.newExecutorWithRLockFn = b.executorWithRLock\n\tb.addAggregateResultsFn = b.addAggregateResults\n\n\treturn b, nil\n}", "func NewMockAergoRPCService_ListBlockStreamServer(ctrl *gomock.Controller) *MockAergoRPCService_ListBlockStreamServer {\n\tmock := &MockAergoRPCService_ListBlockStreamServer{ctrl: ctrl}\n\tmock.recorder = &MockAergoRPCService_ListBlockStreamServerMockRecorder{mock}\n\treturn mock\n}", "func New(api API) *LotusChain {\n\treturn &LotusChain{\n\t\tapi: api,\n\t}\n}", "func NewBlock(filename string, blockNum int) *Block {\n\treturn &Block{FileName: filename, BlockNum: blockNum}\n}", "func NewBlockWriter(block *hdfs.LocatedBlockProto, namenode *NamenodeConnection, blockSize int64) *BlockWriter {\n\tpm := newPipelineManager(namenode, block)\n\n\ts := &BlockWriter{\n\t\tpm: pm,\n\t\tblock: block,\n\t\tblockSize: blockSize,\n\t}\n\n\treturn s\n}", "func NewBlock(prev Block, currentTime uint64, uxHash cipher.SHA256, txns Transactions, calc FeeCalculator) (*Block, error) {\n\tif len(txns) == 0 {\n\t\treturn nil, fmt.Errorf(\"Refusing to create block with no transactions\")\n\t}\n\n\tfee, err := txns.Fees(calc)\n\tif err != nil {\n\t\t// This should have been caught earlier\n\t\treturn nil, fmt.Errorf(\"Invalid transaction fees: %v\", err)\n\t}\n\n\tbody := BlockBody{txns}\n\thead := NewBlockHeader(prev.Head, uxHash, currentTime, fee, body)\n\treturn &Block{\n\t\tHead: head,\n\t\tBody: body,\n\t}, nil\n}", "func NewBlock(data string, prevBlockHash []byte) *Block {\n\tblock := &Block{time.Now().Unix(), []byte(data), prevBlockHash, []byte{}, 0}\n\tpow := NewProofOfWork(block)\n\n\tnonce, hash := pow.Run()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\n\treturn block\n}", "func New(cfg *config.Config, hub *component.ComponentHub) (*SimpleBlockFactory, error) {\n\tconsensus.InitBlockInterval(cfg.Consensus.BlockInterval)\n\n\ts := &SimpleBlockFactory{\n\t\tComponentHub: hub,\n\t\tjobQueue: make(chan interface{}, slotQueueMax),\n\t\tblockInterval: consensus.BlockInterval,\n\t\tmaxBlockBodySize: chain.MaxBlockBodySize(),\n\t\tquit: make(chan interface{}),\n\t}\n\n\ts.txOp = chain.NewCompTxOp(\n\t\tchain.TxOpFn(func(txIn *types.Tx) (*types.BlockState, error) {\n\t\t\tselect {\n\t\t\tcase <-s.quit:\n\t\t\t\treturn nil, chain.ErrQuit\n\t\t\tdefault:\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t}),\n\t)\n\n\treturn s, nil\n}", "func (s *SimpleBlockFactory) BlockFactory() consensus.BlockFactory {\n\treturn s\n}", "func NewBlock(prev Block, currentTime uint64, uxHash cipher.SHA256, txns Transactions, calc FeeCalculator) (*Block, error) {\n\tif len(txns) == 0 {\n\t\treturn nil, fmt.Errorf(\"Refusing to create block with no transactions\")\n\t}\n\n\tfee, err := txns.Fees(calc)\n\tif err != nil {\n\t\t// This should have been caught earlier\n\t\treturn nil, fmt.Errorf(\"Invalid transaction fees: %v\", err)\n\t}\n\n\tbody := BlockBody{txns}\n\treturn &Block{\n\t\tHead: NewBlockHeader(prev.Head, uxHash, currentTime, fee, body),\n\t\tBody: body,\n\t}, nil\n}", "func NewBlock(previousBlock Block, data string) (Block, error) {\n\tvar newBlock Block\n\n\tnewBlock.Index = previousBlock.Index + 1\n\tnewBlock.Timestamp = time.Now().String()\n\tnewBlock.Data = data\n\tnewBlock.PrevHash = previousBlock.Hash\n\tnewBlock.Difficulty = GetDifficulty()\n\n\tif !isCandidateBlockValid(newBlock, previousBlock) {\n\t\treturn newBlock, errors.New(\"Candidate block is not valid\")\n\t}\n\n\tmineBlock(&newBlock)\n\n\treturn newBlock, nil\n}", "func NewBlockHandler(cfg Config, m mesh, v blockValidator, lg log.Log) *BlockHandler {\n\treturn &BlockHandler{\n\t\tLog: lg,\n\t\ttraverse: m.ForBlockInView,\n\t\tdepth: cfg.Depth,\n\t\tmesh: m,\n\t\tvalidator: v,\n\t\tgoldenATXID: cfg.GoldenATXID,\n\t}\n}", "func (b *Block) List(input *BlockCursorInput) (*Blocks, error) {\n\tparams := make(map[string]string)\n\tparams[\"cursor\"] = input.Cursor\n\tresp, err := b.c.Request(http.MethodGet, \"/blocks\", new(bytes.Buffer), params)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar blocks *Blocks\n\terr = json.NewDecoder(resp.Body).Decode(&blocks)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\treturn blocks, nil\n}", "func NewBlock(data string, prevBlockHash []byte) *Block {\n\tblock := &Block{\n\t\tTimestamp: time.Now().Unix(),\n\t\tData: []byte(data),\n\t\tPrevBlockHash: prevBlockHash,\n\t\tHash: []byte{},\n\t}\n\tpow := NewProofOfWork(block)\n\tnonce, hash := pow.Run()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\n\treturn block\n}", "func NewBlockChain(address string) *BlockChain {\n\t//return \t&BlockClain{\n\t//\t[]*Block{genesisBlock},\n\t//}\n\n\tvar lastHash []byte\n\tdb, err := bolt.Open(BlockChainDB, 0600, nil)\n\t//defer db.Close()\n\tif err != nil {\n\t\tlog.Fatal(\"create database failed\")\n\t}\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket([]byte(BlockBucket))\n\t\tif bucket == nil{\n\t\t\tbucket,err = tx.CreateBucket([]byte(BlockBucket))\n\t\t\tif err != nil{\n\t\t\t\tlog.Fatal(\"create bucket failed\")\n\t\t\t}\n\n\t\t\t//Create genesis block\n\t\t\tgenesisBlock := GenesisBlock(address)\n\n\t\t\t//Write message into database\n\t\t\tbucket.Put(genesisBlock.Hash,genesisBlock.Serialize())\n\t\t\tbucket.Put([]byte(\"LastHashKey\"),genesisBlock.Hash)\n\t\t\tlastHash = genesisBlock.Hash\n\t\t}else{\n\t\t\tlastHash = bucket.Get([]byte(\"LastHashKey\"))\n\t\t}\n\n\t\treturn nil\n\t})\n\treturn &BlockChain{db,lastHash}\n}", "func NewBlock(data string, prevBlockHash []byte) *Block {\n\tblock := &Block{\n\t\tTimestamp: time.Now().UTC().Unix(),\n\t\tPrevBlockHash: prevBlockHash,\n\t\tHash: []byte{},\n\t\tData: []byte(data),\n\t}\n\n\tpow := NewProofOfWork(block)\n\tnonce, hash := pow.Run()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\n\treturn block\n}", "func NewLister(tableName string, selectedColumns []string) Lister {\n\treturn &universalLister{\n\t\ttableName: tableName,\n\t\tselectedColumns: strings.Join(selectedColumns, \", \"),\n\t\torderByParams: NoOrderBy,\n\t}\n}", "func (obj Events) Block() Block {\n\treturn Block(obj)\n}" ]
[ "0.6314954", "0.6238325", "0.6161388", "0.61283696", "0.5824281", "0.55151194", "0.520106", "0.51907414", "0.5156084", "0.5144187", "0.51403826", "0.5134927", "0.50486195", "0.5025212", "0.5025212", "0.5023222", "0.5006356", "0.49875388", "0.49786118", "0.49344215", "0.49330792", "0.49155775", "0.4910406", "0.49064437", "0.488934", "0.48796088", "0.48437902", "0.4824231", "0.4805415", "0.48010796", "0.47782475", "0.47504488", "0.4737139", "0.4730701", "0.47051713", "0.46741652", "0.46665058", "0.46619573", "0.46582708", "0.46582112", "0.46577087", "0.46451235", "0.463314", "0.46313232", "0.46253932", "0.461637", "0.46125263", "0.46013114", "0.46008408", "0.46002826", "0.45911735", "0.45746672", "0.4573626", "0.45578954", "0.45552456", "0.45517176", "0.45416215", "0.45379454", "0.45326343", "0.45104796", "0.45006105", "0.45003283", "0.44983888", "0.44842848", "0.44813633", "0.44685465", "0.44667336", "0.44618955", "0.44567356", "0.4453754", "0.44484168", "0.44450137", "0.44416794", "0.44373575", "0.44355655", "0.44280574", "0.44150883", "0.4406206", "0.43997657", "0.43975884", "0.43859822", "0.43806827", "0.43703875", "0.4362323", "0.43621016", "0.4359465", "0.43580246", "0.43485993", "0.43397093", "0.43391466", "0.4336746", "0.4333372", "0.43333033", "0.43309826", "0.43271306", "0.4321909", "0.4321051", "0.432026", "0.43069863", "0.4305192" ]
0.84841317
0
List lists all RolloutBlocks in the indexer.
func (s *rolloutBlockLister) List(selector labels.Selector) (ret []*v1alpha1.RolloutBlock, err error) { err = cache.ListAll(s.indexer, selector, func(m interface{}) { ret = append(ret, m.(*v1alpha1.RolloutBlock)) }) return ret, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s rolloutBlockNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.RolloutBlock, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RolloutBlock))\n\t})\n\treturn ret, err\n}", "func (s *rolloutBlockLister) RolloutBlocks(namespace string) RolloutBlockNamespaceLister {\n\treturn rolloutBlockNamespaceLister{indexer: s.indexer, namespace: namespace}\n}", "func NewRolloutBlockLister(indexer cache.Indexer) RolloutBlockLister {\n\treturn &rolloutBlockLister{indexer: indexer}\n}", "func (s *Server) List(ctx context.Context, in *proto.GetBlockRequest) (*proto.GetBlockResponse, error) {\n\ti, err := metrics.Gauge(\"List\", func() (interface{}, error) {\n\t\tresp := new(proto.GetBlockResponse)\n\n\t\tfor _, b := range s.Blockchain.Blocks {\n\t\t\tresp.Blocks = append(resp.Blocks, &proto.Block{\n\t\t\t\tPrevBlockHash: b.PrevBlockHash,\n\t\t\t\tData: b.Data,\n\t\t\t\tHash: b.Hash,\n\t\t\t})\n\t\t}\n\n\t\treturn resp, nil\n\t})\n\treturn i.(*proto.GetBlockResponse), err\n}", "func (b *Block) List(input *BlockCursorInput) (*Blocks, error) {\n\tparams := make(map[string]string)\n\tparams[\"cursor\"] = input.Cursor\n\tresp, err := b.c.Request(http.MethodGet, \"/blocks\", new(bytes.Buffer), params)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar blocks *Blocks\n\terr = json.NewDecoder(resp.Body).Decode(&blocks)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\treturn blocks, nil\n}", "func (a *DefaultClient) List(l vfs.Location) ([]string, error) {\n\tURL, err := url.Parse(l.(*Location).ContainerURL())\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tcontainerURL := azblob.NewContainerURL(*URL, a.pipeline)\n\tctx := context.Background()\n\tvar list []string\n\tfor marker := (azblob.Marker{}); marker.NotDone(); {\n\t\tlistBlob, err := containerURL.ListBlobsHierarchySegment(ctx, marker, \"/\",\n\t\t\tazblob.ListBlobsSegmentOptions{Prefix: utils.RemoveLeadingSlash(l.Path())})\n\t\tif err != nil {\n\t\t\treturn []string{}, err\n\t\t}\n\n\t\tmarker = listBlob.NextMarker\n\n\t\tfor i := range listBlob.Segment.BlobItems {\n\t\t\tlist = append(list, listBlob.Segment.BlobItems[i].Name)\n\t\t}\n\t}\n\treturn list, nil\n}", "func (s *BlockService) List(limit int, cursor string) (models.BlockPage, error) {\n\tif limit > 100 {\n\t\tlimit = 100\n\t}\n\tif limit == 0 {\n\t\tlimit = 10\n\t}\n\treturn s.dao.Find(bson.M{}, limit, cursor)\n}", "func (s rolloutBlockNamespaceLister) Get(name string) (*v1alpha1.RolloutBlock, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"rolloutblock\"), name)\n\t}\n\treturn obj.(*v1alpha1.RolloutBlock), nil\n}", "func (c *BlockVolumeClient) List(params *BlockVolumeParams) (*BlockVolumeList, error) {\n\tlist := &BlockVolumeList{}\n\n\terr := c.Backend.CallIntoInterface(\"v1/Storage/Block/Volume/list\", params, list)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn list, nil\n}", "func Blocks(offset, count uint) ([]BlockItem, error) {\n\tjsonBlocks := []struct {\n\t\tNumber uint `json:\"number\"`\n\t\tHash string `json:\"hash\"`\n\t\tDate Time `json:\"date\"`\n\t\tDifficulty uint64 `json:\"difficulty\"`\n\t\tMiner string `json:\"miner\"`\n\t}{}\n\tif err := fetch(&jsonBlocks, blockEndpoint, offset, count); err != nil {\n\t\treturn nil, err\n\t}\n\tblocks := make([]BlockItem, len(jsonBlocks))\n\tfor i, b := range jsonBlocks {\n\t\tblocks[i] = BlockItem(b)\n\t}\n\treturn blocks, nil\n}", "func (l *LessonTut) Blocks() []*BlockTut { return l.blocks }", "func (s *bundleLister) List(selector labels.Selector) (ret []*v1alpha1.Bundle, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Bundle))\n\t})\n\treturn ret, err\n}", "func (s *wafregionalRuleLister) List(selector labels.Selector) (ret []*v1alpha1.WafregionalRule, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.WafregionalRule))\n\t})\n\treturn ret, err\n}", "func (b *indexBlock) Blocks() ([]blockHandle, error) {\n\tvar lastKey []byte\n\tkb := make([]byte, 0, MaxSstKeySize)\n\tvar blocks []blockHandle\n\n\tfor b.r.Len() > 0 {\n\t\teKey, err := prefixDecodeFrom(b.r, lastKey, kb)\n\t\tlastKey = eKey\n\t\tif _, err := binary.ReadUvarint(b.r); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbh, err := newBlockHandle(b.r)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tblocks = append(blocks, bh)\n\t}\n\n\treturn blocks, nil\n}", "func (c *MockLoadBalancersClient) List(ctx context.Context, resourceGroupName string) ([]network.LoadBalancer, error) {\n\tvar l []network.LoadBalancer\n\tfor _, lb := range c.LBs {\n\t\tl = append(l, lb)\n\t}\n\treturn l, nil\n}", "func printBlockList(blobClient *storage.BlobStorageClient, containerName, blockBlobName string) error {\n\tfmt.Println(\"Get block list...\")\n\tlist, err := blobClient.GetBlockList(containerName, blockBlobName, storage.BlockListTypeAll)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"Block blob '%v' block list\\n\", blockBlobName)\n\tfmt.Println(\"\\tCommitted Blocks' IDs\")\n\tfor _, b := range list.CommittedBlocks {\n\t\tfmt.Printf(\"\\t\\t%v\\n\", b.Name)\n\t}\n\tfmt.Println(\"\\tUncommited Blocks' IDs\")\n\tfor _, b := range list.UncommittedBlocks {\n\t\tfmt.Printf(\"\\t\\t%v\\n\", b.Name)\n\t}\n\treturn nil\n}", "func (h *Handler) List() ([]*unstructured.Unstructured, error) {\n\treturn h.ListAll()\n}", "func List(client *golangsdk.ServiceClient, clusterId string) (r ListResult) {\n\t_, r.Err = client.Get(listURL(client, clusterId), &r.Body, nil)\n\treturn\n}", "func (s bundleNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Bundle, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Bundle))\n\t})\n\treturn ret, err\n}", "func (s beeNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Bee, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Bee))\n\t})\n\treturn ret, err\n}", "func (i *Index) List() List {\n\t// prepare list\n\tlist := make(List, 0, i.btree.Len())\n\n\t// walk index\n\ti.btree.Scan(func(item Doc) bool {\n\t\tlist = append(list, item)\n\t\treturn true\n\t})\n\n\treturn list\n}", "func (client Client) List() (result ListResult, err error) {\n\treq, err := client.ListPreparer()\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"redis.Client\", \"List\", nil, \"Failure preparing request\")\n\t}\n\n\tresp, err := client.ListSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(err, \"redis.Client\", \"List\", resp, \"Failure sending request\")\n\t}\n\n\tresult, err = client.ListResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"redis.Client\", \"List\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (s *hookLister) List(selector labels.Selector) (ret []*v1alpha1.Hook, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Hook))\n\t})\n\treturn ret, err\n}", "func (c *ClusterResourceClient) List(ctx context.Context, opts metav1.ListOptions) (*metav1.PartialObjectMetadataList, error) {\n\treturn c.clientCache.ClusterOrDie(logicalcluster.Wildcard).Resource(c.resource).List(ctx, opts)\n}", "func (s hookNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Hook, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Hook))\n\t})\n\treturn ret, err\n}", "func (api *snapshotrestoreAPI) List(ctx context.Context, opts *api.ListWatchOptions) ([]*SnapshotRestore, error) {\n\tvar objlist []*SnapshotRestore\n\tobjs, err := api.ct.List(\"SnapshotRestore\", ctx, opts)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, obj := range objs {\n\t\tswitch tp := obj.(type) {\n\t\tcase *SnapshotRestore:\n\t\t\teobj := obj.(*SnapshotRestore)\n\t\t\tobjlist = append(objlist, eobj)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Got invalid object type %v while looking for SnapshotRestore\", tp)\n\t\t}\n\t}\n\n\treturn objlist, nil\n}", "func (c *Client) List(ctx context.Context, p *ListPayload) (res *ListResult, err error) {\n\tvar ires interface{}\n\tires, err = c.ListEndpoint(ctx, p)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ires.(*ListResult), nil\n}", "func (s *awsApiGatewayBasePathMappingLister) List(selector labels.Selector) (ret []*v1.AwsApiGatewayBasePathMapping, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.AwsApiGatewayBasePathMapping))\n\t})\n\treturn ret, err\n}", "func (c *MockRouteTablesClient) List(ctx context.Context, resourceGroupName string) ([]network.RouteTable, error) {\n\tvar l []network.RouteTable\n\tfor _, rt := range c.RTs {\n\t\tl = append(l, rt)\n\t}\n\treturn l, nil\n}", "func (c *Client) ListChangedBlocks(ctx context.Context, params *ListChangedBlocksInput, optFns ...func(*Options)) (*ListChangedBlocksOutput, error) {\n\tif params == nil {\n\t\tparams = &ListChangedBlocksInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"ListChangedBlocks\", params, optFns, addOperationListChangedBlocksMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*ListChangedBlocksOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (r *RestService) List(relativeURL string, offset int64, limit int64) ([]byte, error) {\n\tqueryParams := fmt.Sprintf(\"?offset=%v&limit=%v\", offset, limit)\n\tfullURL := *r.Bitmovin.APIBaseURL + relativeURL + queryParams\n\n\treq, err := http.NewRequest(\"GET\", fullURL, nil)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"X-Api-Key\", *r.Bitmovin.APIKey)\n\tif r.Bitmovin.OrganizationID != nil {\n\t\treq.Header.Set(\"X-Tenant-Org-Id\", *r.Bitmovin.OrganizationID)\n\t}\n\treq.Header.Set(\"X-Api-Client\", ClientName)\n\treq.Header.Set(\"X-Api-Client-Version\", Version)\n\n\tresp, err := r.Bitmovin.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn body, nil\n}", "func (h *Handler) List() ([]*corev1.Node, error) {\n\treturn h.ListAll()\n}", "func (c *MockVirtualNetworksClient) List(ctx context.Context, resourceGroupName string) ([]network.VirtualNetwork, error) {\n\tvar l []network.VirtualNetwork\n\tfor _, vnet := range c.VNets {\n\t\tl = append(l, vnet)\n\t}\n\treturn l, nil\n}", "func (s *beeLister) List(selector labels.Selector) (ret []*v1beta1.Bee, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Bee))\n\t})\n\treturn ret, err\n}", "func BlockAll(ctx context.Context) schema.Block {\n\treturn Block(ctx, Opts{\n\t\tCreate: true,\n\t\tRead: true,\n\t\tUpdate: true,\n\t\tDelete: true,\n\t})\n}", "func BlockStats(offset, count uint) ([]BlockStatItem, error) {\n\tjsonStats := []struct {\n\t\tDate Time `json:\"date\"`\n\t\tDifficulty uint64 `json:\"difficulty\"`\n\t\tBlockTime float64 `json:\"block_time\"`\n\t}{}\n\tif err := fetch(&jsonStats, blockStatsEndpoint, offset, count); err != nil {\n\t\treturn nil, err\n\t}\n\tstats := make([]BlockStatItem, len(jsonStats))\n\tfor i, s := range jsonStats {\n\t\tstats[i] = BlockStatItem(s)\n\t}\n\treturn stats, nil\n}", "func (_PlasmaFramework *PlasmaFrameworkSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _PlasmaFramework.Contract.Blocks(&_PlasmaFramework.CallOpts, arg0)\n}", "func (tt *BlockTestTable) GetAll() []TypedBlock {\n\tvar result []TypedBlock\n\tfor _, b := range tt.AccountBlocks {\n\t\tresult = append(result, TypedBlock{\n\t\t\tAccountBlock: b,\n\t\t\tT: \"account\",\n\t\t})\n\t}\n\tfor _, b := range tt.SwapBlocks {\n\t\tresult = append(result, TypedBlock{\n\t\t\tSwapBlock: b,\n\t\t\tT: \"swap\",\n\t\t})\n\t}\n\tfor _, b := range tt.OrderBlocks {\n\t\tresult = append(result, TypedBlock{\n\t\t\tOrderBlock: b,\n\t\t\tT: \"order\",\n\t\t})\n\t}\n\treturn result\n}", "func (api *configurationsnapshotAPI) List(ctx context.Context, opts *api.ListWatchOptions) ([]*ConfigurationSnapshot, error) {\n\tvar objlist []*ConfigurationSnapshot\n\tobjs, err := api.ct.List(\"ConfigurationSnapshot\", ctx, opts)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, obj := range objs {\n\t\tswitch tp := obj.(type) {\n\t\tcase *ConfigurationSnapshot:\n\t\t\teobj := obj.(*ConfigurationSnapshot)\n\t\t\tobjlist = append(objlist, eobj)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Got invalid object type %v while looking for ConfigurationSnapshot\", tp)\n\t\t}\n\t}\n\n\treturn objlist, nil\n}", "func List() {\n\tvar name string\n\tisGroup := false\n\n\tfmt.Printf(\"\\nShowing %v conversation(s):\\n\", len(jsonData))\n\n\t//jsonDataList := *jsonDatap\n\n\tfor i, block := range jsonData {\n\n\t\tfor _, participant := range block.Participants {\n\t\t\tif participant == master {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(block.Participants) >= 3 {\n\t\t\t\tisGroup = true\n\t\t\t}\n\t\t\tname = participant\n\t\t}\n\t\tif !isGroup {\n\t\t\tfmt.Printf(\"[%v] - %v\\n\", i, name)\n\t\t} else {\n\t\t\tfmt.Printf(\"[%v] - group: participants %+v\\n\", i, block.Participants)\n\t\t\tisGroup = false\n\t\t}\n\t}\n\n\tfmt.Println(\"\")\n}", "func (ccv *CCV) List(label string) []Section {\n\treturn ccv.Sections\n}", "func (c *Client) ListAll(ctx context.Context, p *ListAllPayload) (res *PageOfStations, err error) {\n\tvar ires interface{}\n\tires, err = c.ListAllEndpoint(ctx, p)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ires.(*PageOfStations), nil\n}", "func (s sMBNamespaceLister) List(selector labels.Selector) (ret []*v1.SMB, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.SMB))\n\t})\n\treturn ret, err\n}", "func (r *Repository) List(filter models.RightFilter, limit, offset uint) (rights []models.FutureEndorsementRight, err error) {\n\tdb := r.getDb(filter)\n\terr = db.Order(\"block_level asc\").\n\t\tOffset(offset).\n\t\tLimit(limit).\n\t\tFind(&rights).Error\n\n\treturn rights, err\n}", "func (l *Location) List() ([]string, error) {\n\n\tvar filenames []string\n\tclient, err := l.fileSystem.Client(l.Authority)\n\tif err != nil {\n\t\treturn filenames, err\n\t}\n\t// start timer once action is completed\n\tdefer l.fileSystem.connTimerStart()\n\n\tfileinfos, err := client.ReadDir(l.Path())\n\tif err != nil {\n\t\tif err == os.ErrNotExist {\n\t\t\treturn filenames, nil\n\t\t}\n\t\treturn filenames, err\n\t}\n\tfor _, fileinfo := range fileinfos {\n\t\tif !fileinfo.IsDir() {\n\t\t\tfilenames = append(filenames, fileinfo.Name())\n\t\t}\n\t}\n\n\treturn filenames, nil\n}", "func (h *Handler) ListAll() ([]*corev1.Node, error) {\n\treturn h.ListByLabel(\"\")\n}", "func (s *sMBLister) List(selector labels.Selector) (ret []*v1.SMB, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.SMB))\n\t})\n\treturn ret, err\n}", "func (s *LocationsService) List(ctx context.Context) ([]Location, *Response, error) {\n\tpath := fmt.Sprintf(\"%v/\", locationsBasePath)\n\n\treq, err := s.client.NewRequest(http.MethodGet, path, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\troot := new(locationsRoot)\n\tresp, err := s.client.Do(ctx, req, root)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\tif m := root.Meta; m != nil {\n\t\tresp.Meta = m\n\t}\n\n\treturn root.Locations, resp, nil\n}", "func (a *IqnpoolApiService) GetIqnpoolBlockList(ctx context.Context) ApiGetIqnpoolBlockListRequest {\n\treturn ApiGetIqnpoolBlockListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (c *Client) ListSnapshotRollOwners(ctx context.Context, id BlockID, cycle, index int64) (*SnapshotOwners, error) {\n\towners := &SnapshotOwners{Cycle: cycle, Index: index}\n\tu := fmt.Sprintf(\"chains/main/blocks/%s/context/raw/json/rolls/owner/snapshot/%d/%d?depth=1\", id, cycle, index)\n\tif err := c.Get(ctx, u, &owners.Rolls); err != nil {\n\t\treturn nil, err\n\t}\n\treturn owners, nil\n}", "func (c *MultiClusterController) List(clusterName string, opts ...client.ListOption) (interface{}, error) {\n\tcluster := c.GetCluster(clusterName)\n\tif cluster == nil {\n\t\treturn nil, errors.NewClusterNotFound(clusterName)\n\t}\n\tinstanceList := utilscheme.Scheme.NewObjectList(c.objectType)\n\tdelegatingClient, err := cluster.GetDelegatingClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = delegatingClient.List(context.TODO(), instanceList, opts...)\n\treturn instanceList, err\n}", "func (s *monitorMetricAlertruleLister) List(selector labels.Selector) (ret []*v1alpha1.MonitorMetricAlertrule, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.MonitorMetricAlertrule))\n\t})\n\treturn ret, err\n}", "func (s awsApiGatewayBasePathMappingNamespaceLister) List(selector labels.Selector) (ret []*v1.AwsApiGatewayBasePathMapping, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.AwsApiGatewayBasePathMapping))\n\t})\n\treturn ret, err\n}", "func (c *Client) List() ([]string, error) {\n\t// delegate to concrete implementation of lister entirely.\n\treturn c.lister.List()\n}", "func (_PlasmaFramework *PlasmaFrameworkCallerSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _PlasmaFramework.Contract.Blocks(&_PlasmaFramework.CallOpts, arg0)\n}", "func (n *namespaceClient) List() ([]ns.Metadata, error) {\n\turl := fmt.Sprintf(\"%s%s\", n.url, nsh.GetURL)\n\tresp, err := n.client.DoHTTPRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata := &admin.NamespaceGetResponse{}\n\tdefer func() {\n\t\tioutil.ReadAll(resp.Body)\n\t\tresp.Body.Close()\n\t}()\n\tif err := jsonpb.Unmarshal(resp.Body, data); err != nil {\n\t\treturn nil, err\n\t}\n\tnsMetas := []ns.Metadata{}\n\tfor nsID, nsOpts := range data.GetRegistry().GetNamespaces() {\n\t\tmd, err := ns.ToMetadata(nsID, nsOpts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnsMetas = append(nsMetas, md)\n\t}\n\tn.logger.Info(\"namespace retrieved\")\n\treturn nsMetas, nil\n}", "func (s *kylinNodeLister) List(selector labels.Selector) (ret []*v1.KylinNode, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.KylinNode))\n\t})\n\treturn ret, err\n}", "func (client *Client) List(path string) ([]*api.LsLink, error) {\n\treturn client.client.List(path)\n}", "func (v *VaultAccessor) List() (PathList, error) {\n\treturn v.list(v.basePath)\n}", "func (c *SubresourceClient) List(namespace string, labels map[string]string) (result []metav1.Object, e error) {\n\tif c.Error != \"\" {\n\t\te = fmt.Errorf(c.Error)\n\t} else {\n\t\tresult = []metav1.Object{c.Subresource}\n\t}\n\treturn\n}", "func (h HTTPHandler) CollectionList(w http.ResponseWriter, r *http.Request) {\n\terr := processJWT(r, false, h.secret)\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"\"+err.Error()+\"\\\"}\", 401)\n\t\treturn\n\t}\n\n\tvar indexNames []string\n\tfor name := range h.bf.Local.Search.BlockchainIndices {\n\t\tindexNames = append(indexNames, name)\n\t}\n\n\trv := struct {\n\t\tMessage string `json:\"message\"`\n\t\tIndexes []string `json:\"collections\"`\n\t}{\n\t\tMessage: \"ok\",\n\t\tIndexes: indexNames,\n\t}\n\n\tmustEncode(w, rv)\n}", "func (_Bfs *BfsCallerSession) List(absolutePath string, offset *big.Int, limit *big.Int) (*big.Int, []BfsInfo, error) {\n\treturn _Bfs.Contract.List(&_Bfs.CallOpts, absolutePath, offset, limit)\n}", "func (core *coreService) RawBlocks(startHeight uint64, count uint64, withReceipts bool, withTransactionLogs bool) ([]*iotexapi.BlockInfo, error) {\n\tif count == 0 || count > core.cfg.RangeQueryLimit {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"range exceeds the limit\")\n\t}\n\n\ttipHeight := core.bc.TipHeight()\n\tif startHeight > tipHeight {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"start height should not exceed tip height\")\n\t}\n\tendHeight := startHeight + count - 1\n\tif endHeight > tipHeight {\n\t\tendHeight = tipHeight\n\t}\n\tvar res []*iotexapi.BlockInfo\n\tfor height := startHeight; height <= endHeight; height++ {\n\t\tblk, err := core.dao.GetBlockByHeight(height)\n\t\tif err != nil {\n\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t}\n\t\tvar receiptsPb []*iotextypes.Receipt\n\t\tif withReceipts && height > 0 {\n\t\t\treceipts, err := core.dao.GetReceipts(height)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t\t}\n\t\t\tfor _, receipt := range receipts {\n\t\t\t\treceiptsPb = append(receiptsPb, receipt.ConvertToReceiptPb())\n\t\t\t}\n\t\t}\n\t\tvar transactionLogs *iotextypes.TransactionLogs\n\t\tif withTransactionLogs {\n\t\t\tif transactionLogs, err = core.dao.TransactionLogs(height); err != nil {\n\t\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t\t}\n\t\t}\n\t\tres = append(res, &iotexapi.BlockInfo{\n\t\t\tBlock: blk.ConvertToBlockPb(),\n\t\t\tReceipts: receiptsPb,\n\t\t\tTransactionLogs: transactionLogs,\n\t\t})\n\t}\n\treturn res, nil\n}", "func (w *WebhookServiceOp) List(options interface{}) ([]Webhook, error) {\n\tpath := fmt.Sprintf(\"%s\", webhooksBasePath)\n\tresource := make([]Webhook, 0)\n\terr := w.client.Get(path, &resource, options)\n\treturn resource, err\n}", "func (c *MockNatGatewaysClient) List(ctx context.Context, resourceGroupName string) ([]network.NatGateway, error) {\n\tvar l []network.NatGateway\n\tfor _, ngw := range c.NGWs {\n\t\tl = append(l, ngw)\n\t}\n\treturn l, nil\n}", "func (r *MonitorNoneResource) ListAll() (*MonitorNoneList, error) {\n\tvar list MonitorNoneList\n\tif err := r.c.ReadQuery(BasePath+MonitorNoneEndpoint, &list); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &list, nil\n}", "func (lbq *LatestBlockQuery) All(ctx context.Context) ([]*LatestBlock, error) {\n\tif err := lbq.prepareQuery(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn lbq.sqlAll(ctx)\n}", "func (s wafregionalRuleNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.WafregionalRule, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.WafregionalRule))\n\t})\n\treturn ret, err\n}", "func (h *Handler) ListAll() ([]*unstructured.Unstructured, error) {\n\tlistOptions := h.Options.ListOptions.DeepCopy()\n\tlistOptions.LabelSelector = \"\"\n\n\tif err := h.getGVRAndNamespaceScope(); err != nil {\n\t\treturn nil, err\n\t}\n\tif h.isNamespaced {\n\t\treturn extractList(h.dynamicClient.Resource(h.gvr).Namespace(metav1.NamespaceAll).List(h.ctx, *listOptions))\n\t}\n\treturn extractList(h.dynamicClient.Resource(h.gvr).List(h.ctx, *listOptions))\n}", "func (c *Client) ListSnapshotBlocks(ctx context.Context, params *ListSnapshotBlocksInput, optFns ...func(*Options)) (*ListSnapshotBlocksOutput, error) {\n\tif params == nil {\n\t\tparams = &ListSnapshotBlocksInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"ListSnapshotBlocks\", params, optFns, addOperationListSnapshotBlocksMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*ListSnapshotBlocksOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (s *kubeletConfigLister) List(selector labels.Selector) (ret []*v1.KubeletConfig, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.KubeletConfig))\n\t})\n\treturn ret, err\n}", "func (p *Proxy) List(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\tlogger := mPkg.GetLogger(ctx)\n\n\topt, err := fromHTTPRequestToListOptions(r, p.maxListLimit)\n\tif err != nil {\n\t\tlogger.Error(\"could not parse filter\", zap.Error(err))\n\t\trender.Render(w, r, cHttp.ErrResponse(http.StatusBadRequest, err.Error()))\n\n\t\treturn\n\t}\n\n\tlogger.Debug(\"Retrieving info for load tests\")\n\n\tloadTests, err := p.kubeClient.ListLoadTest(ctx, *opt)\n\tif err != nil {\n\t\tlogger.Error(\"could not list load tests\", zap.Error(err))\n\t\trender.Render(w, r, cHttp.ErrResponse(http.StatusInternalServerError, err.Error()))\n\n\t\treturn\n\t}\n\n\titems := make([]LoadTestStatus, len(loadTests.Items))\n\tfor i, lt := range loadTests.Items {\n\t\titems[i] = LoadTestStatus{\n\t\t\tType: lt.Spec.Type.String(),\n\t\t\tDistributedPods: *lt.Spec.DistributedPods,\n\t\t\tNamespace: lt.Status.Namespace,\n\t\t\tPhase: lt.Status.Phase.String(),\n\t\t\tTags: lt.Spec.Tags,\n\t\t\tHasEnvVars: len(lt.Spec.EnvVars) != 0,\n\t\t\tHasTestData: len(lt.Spec.TestData) != 0,\n\t\t}\n\t}\n\n\trender.JSON(w, r, &LoadTestStatusPage{\n\t\tLimit: opt.Limit,\n\t\tContinue: loadTests.Continue,\n\t\tRemain: loadTests.RemainingItemCount,\n\t\tItems: items,\n\t})\n}", "func (s *sensuAssetLister) List(selector labels.Selector) (ret []*v1beta1.SensuAsset, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.SensuAsset))\n\t})\n\treturn ret, err\n}", "func (s *scyllaDBMonitoringLister) List(selector labels.Selector) (ret []*v1alpha1.ScyllaDBMonitoring, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ScyllaDBMonitoring))\n\t})\n\treturn ret, err\n}", "func (a *app) List(w http.ResponseWriter, request provider.Request, message rendererModel.Message) {\n\tfiles, err := a.storage.List(request.GetFilepath(\"\"))\n\tif err != nil {\n\t\ta.renderer.Error(w, request, provider.NewError(http.StatusInternalServerError, err))\n\t\treturn\n\t}\n\n\turi := request.GetURI(\"\")\n\n\titems := make([]provider.RenderItem, len(files))\n\tfor index, file := range files {\n\t\titems[index] = provider.RenderItem{\n\t\t\tID: sha.Sha1(file.Name),\n\t\t\tURI: uri,\n\t\t\tStorageItem: file,\n\t\t}\n\t}\n\n\tcontent := map[string]interface{}{\n\t\t\"Paths\": getPathParts(uri),\n\t\t\"Files\": items,\n\t\t\"Cover\": a.getCover(files),\n\t}\n\n\tif request.CanShare {\n\t\tcontent[\"Shares\"] = a.metadatas\n\t}\n\n\ta.renderer.Directory(w, request, content, message)\n}", "func (w *ClusterDynamicClient) List(opts metav1.ListOptions) (*unstructured.UnstructuredList, error) {\n\treturn w.dClient.Resource(w.resource).Namespace(w.namespace).List(w.ctx, opts)\n}", "func (obs *Observer) List(opts metav1.ListOptions) (*unstructured.UnstructuredList, error) {\n\treturn obs.client.Namespace(obs.namespace).List(opts)\n}", "func (ctl Controller) List() (*Info, *pitr.Error) {\n\tstdout, stderr, err := ctl.runner.Run(\"sudo --login --user postgres wal-g backup-list\")\n\n\tif err != nil {\n\t\treturn nil, &pitr.Error{\n\t\t\tMessage: err.Error(),\n\t\t\tStdout: stdout,\n\t\t\tStderr: stderr,\n\t\t}\n\t}\n\n\tinfos, err := ParseListOutput(stdout)\n\n\tif err != nil {\n\t\treturn nil, &pitr.Error{\n\t\t\tMessage: \"Parse error\",\n\t\t\tStdout: stderr,\n\t\t\tStderr: stderr,\n\t\t}\n\t}\n\n\treturn infos, nil\n}", "func (c *Client) List(ctx context.Context) (res StoredBottleCollection, err error) {\n\tvar ires any\n\tires, err = c.ListEndpoint(ctx, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ires.(StoredBottleCollection), nil\n}", "func (c *Client) List() goa.Endpoint {\n\treturn func(ctx context.Context, v interface{}) (interface{}, error) {\n\t\tinv := goagrpc.NewInvoker(\n\t\t\tBuildListFunc(c.grpccli, c.opts...),\n\t\t\tEncodeListRequest,\n\t\t\tDecodeListResponse)\n\t\tres, err := inv.Invoke(ctx, v)\n\t\tif err != nil {\n\t\t\treturn nil, goa.Fault(err.Error())\n\t\t}\n\t\treturn res, nil\n\t}\n}", "func (*OktetoClusterHelper) List() (map[string]string, error) {\n\treturn nil, ErrNotImplemented\n}", "func (h *kubeClient) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error {\n\treturn h.client.List(ctx, list, opts...)\n}", "func (s *tridentOrchestratorLister) List(selector labels.Selector) (ret []*v1.TridentOrchestrator, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.TridentOrchestrator))\n\t})\n\treturn ret, err\n}", "func (client *Client) LoadIndexersList() error {\n var result Indexers\n response, err := client.sendGetRequest(&result, \"indexers\", \"\", nil, nil)\n if err != nil {\n return errors.JackettUnableToLoadIndexers.ToError(err)\n }\n client.indexers = response.(*Indexers)\n configuredIndexers := make([]Indexer, 0)\n for _, indexer := range result {\n if indexer.Configured {\n configuredIndexers = append(configuredIndexers, indexer)\n }\n }\n client.configuredIndexers = configuredIndexers\n return nil\n}", "func (s scyllaDBMonitoringNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ScyllaDBMonitoring, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ScyllaDBMonitoring))\n\t})\n\treturn ret, err\n}", "func (r *FailoverResource) ListAll() (*FailoverConfigList, error) {\n\tvar list FailoverConfigList\n\tif err := r.c.ReadQuery(BasePath+FailoverEndpoint, &list); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &list, nil\n}", "func (c *aITrainingJobs) List(opts metav1.ListOptions) (result *v1.AITrainingJobList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = &v1.AITrainingJobList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"aitrainingjobs\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}", "func (k *kubeclient) List(opts metav1.ListOptions) (*apis.CStorVolumeReplicaList, error) {\n\tcli, err := k.getClientOrCached()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn k.list(cli, k.namespace, opts)\n}", "func (s monitorMetricAlertruleNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.MonitorMetricAlertrule, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.MonitorMetricAlertrule))\n\t})\n\treturn ret, err\n}", "func (c *TestProjectConfig) GetRolloutList() (rolloutList []entities.Rollout) {\n\tfor _, rollout := range c.RolloutMap {\n\t\trolloutList = append(rolloutList, rollout)\n\t}\n\treturn rolloutList\n}", "func (c *clbClient) Lbs() []string {\n\treturn c.loadBalancers\n}", "func (i *instrumentedListerWatcher) List(options metav1.ListOptions) (runtime.Object, error) {\n\ti.listTotal.Inc()\n\tret, err := i.next.List(options)\n\tif err != nil {\n\t\ti.listFailed.Inc()\n\t}\n\treturn ret, err\n}", "func (c *ConsulClient) List(ctx context.Context, prefix string) ([]Pair, error) {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"ConsulClient.List\")\n\tdefer span.Finish()\n\n\tregistryOperationCount.WithLabelValues(env, \"List\").Inc()\n\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tregistryOperationTimeTaken.WithLabelValues(env, \"List\").Observe(time.Now().Sub(startTime).Seconds())\n\t}()\n\n\tkvs, _, err := c.client.KV().List(prefix, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpairs := []Pair{}\n\n\tfor _, kv := range kvs {\n\t\tpairs = append(pairs, Pair{\n\t\t\tKey: kv.Key,\n\t\t\tValue: kv.Value,\n\t\t})\n\t}\n\n\treturn pairs, nil\n}", "func (t table) List() []string {\n\treturn t.ls[:]\n}", "func List(ctx context.Context, filters container.FilterBuilder) ([]*types.Node, error) {\n\tres := []*types.Node{}\n\tvisit := func(ctx context.Context, cluster string, node *types.Node) {\n\t\tres = append(res, node)\n\t}\n\treturn res, list(ctx, visit, filters)\n}", "func (s sealedSecretNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.SealedSecret, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.SealedSecret))\n\t})\n\treturn ret, err\n}", "func (w *Wallet) ListSinceBlock(start, end, syncHeight int32) ([]btcjson.ListTransactionsResult, er.R) {\n\ttxList := []btcjson.ListTransactionsResult{}\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\ttxmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)\n\n\t\trangeFn := func(details []wtxmgr.TxDetails) (bool, er.R) {\n\t\t\tfor _, detail := range details {\n\t\t\t\tjsonResults := listTransactions(tx, &detail,\n\t\t\t\t\tw.Manager, syncHeight, w.chainParams)\n\t\t\t\ttxList = append(txList, jsonResults...)\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn w.TxStore.RangeTransactions(txmgrNs, start, end, rangeFn)\n\t})\n\treturn txList, err\n}", "func (s *logicalNetworkLister) List(selector labels.Selector) (ret []*v1.LogicalNetwork, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.LogicalNetwork))\n\t})\n\treturn ret, err\n}", "func (s *seaOtterLister) List(selector labels.Selector) (ret []*v1alpha1.SeaOtter, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.SeaOtter))\n\t})\n\treturn ret, err\n}", "func (c *clientBackup) List(ctx context.Context, opt *BackupListOptions) (map[BackupID]BackupMeta, error) {\n\treq, err := c.conn.NewRequest(\"POST\", \"_admin/backup/list\")\n\tif err != nil {\n\t\treturn nil, WithStack(err)\n\t}\n\tapplyContextSettings(ctx, req)\n\tif opt != nil {\n\t\treq, err = req.SetBody(opt)\n\t\tif err != nil {\n\t\t\treturn nil, WithStack(err)\n\t\t}\n\t}\n\tresp, err := c.conn.Do(ctx, req)\n\tif err != nil {\n\t\treturn nil, WithStack(err)\n\t}\n\tif err := resp.CheckStatus(200); err != nil {\n\t\treturn nil, WithStack(err)\n\t}\n\tvar result struct {\n\t\tList map[BackupID]BackupMeta `json:\"list,omitempty\"`\n\t}\n\tif err := resp.ParseBody(\"result\", &result); err != nil {\n\t\treturn nil, WithStack(err)\n\t}\n\treturn result.List, nil\n}" ]
[ "0.7311063", "0.6322645", "0.60686725", "0.60537857", "0.58911", "0.552953", "0.5229831", "0.5191888", "0.51698", "0.51621276", "0.515386", "0.5137676", "0.5080767", "0.50736266", "0.5053302", "0.50126654", "0.4932627", "0.4914542", "0.4912257", "0.49045357", "0.49037486", "0.48964658", "0.4876176", "0.4875737", "0.4869453", "0.48463058", "0.48193884", "0.48145556", "0.48071375", "0.47808182", "0.47755313", "0.47655818", "0.47638363", "0.4755005", "0.47451144", "0.4743474", "0.47424784", "0.47391406", "0.47310314", "0.47306013", "0.47114918", "0.4705923", "0.4705104", "0.46999678", "0.46901548", "0.46881026", "0.46867", "0.46865544", "0.4684137", "0.4672462", "0.46717027", "0.46690086", "0.46675965", "0.46629792", "0.46573225", "0.4652886", "0.46419895", "0.4640344", "0.46390072", "0.46335837", "0.46313947", "0.46270344", "0.46199128", "0.46174735", "0.46169078", "0.46115476", "0.46080488", "0.459587", "0.45939606", "0.45886648", "0.45861307", "0.4585727", "0.45797417", "0.45772183", "0.45660332", "0.45622367", "0.4561131", "0.4559264", "0.45589057", "0.45572695", "0.45480615", "0.45460266", "0.4545805", "0.45427328", "0.45330673", "0.45318377", "0.45317084", "0.45297956", "0.45274433", "0.4522804", "0.452194", "0.45135522", "0.4502472", "0.44908348", "0.44840217", "0.44813263", "0.44808108", "0.44778928", "0.44770664", "0.44762596" ]
0.76020056
0
RolloutBlocks returns an object that can list and get RolloutBlocks.
func (s *rolloutBlockLister) RolloutBlocks(namespace string) RolloutBlockNamespaceLister { return rolloutBlockNamespaceLister{indexer: s.indexer, namespace: namespace} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewRolloutBlockLister(indexer cache.Indexer) RolloutBlockLister {\n\treturn &rolloutBlockLister{indexer: indexer}\n}", "func (l *LessonTut) Blocks() []*BlockTut { return l.blocks }", "func (s rolloutBlockNamespaceLister) Get(name string) (*v1alpha1.RolloutBlock, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"rolloutblock\"), name)\n\t}\n\treturn obj.(*v1alpha1.RolloutBlock), nil\n}", "func (s *rolloutBlockLister) List(selector labels.Selector) (ret []*v1alpha1.RolloutBlock, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RolloutBlock))\n\t})\n\treturn ret, err\n}", "func Block(b models.Block) *genModels.BlocksRow {\n\tts := b.Timestamp.Unix()\n\n\tgenBlock := genModels.BlocksRow{\n\t\tLevel: b.Level.Ptr(),\n\t\tProto: b.Proto.Ptr(),\n\t\tBlockTime: b.BlockTime,\n\t\tPredecessor: b.Predecessor.Ptr(),\n\t\tTimestamp: &ts,\n\t\tValidationPass: b.ValidationPass.Ptr(),\n\t\tFitness: b.Fitness.Ptr(),\n\t\tContext: b.Context,\n\t\tSignature: b.Signature,\n\t\tProtocol: b.Protocol.Ptr(),\n\t\tPriority: b.Priority.Ptr(),\n\t\tChainID: b.ChainID,\n\t\tHash: b.Hash.Ptr(),\n\t\tReward: &b.Reward,\n\t\tDeposit: b.Deposit,\n\t\tOperationsHash: b.OperationsHash,\n\t\tPeriodKind: b.PeriodKind,\n\t\tCurrentExpectedQuorum: b.CurrentExpectedQuorum,\n\t\tActiveProposal: b.ActiveProposal,\n\t\tBaker: b.Baker,\n\t\tBakerName: b.BakerName,\n\t\tNonceHash: b.NonceHash,\n\t\tConsumedGas: b.ConsumedGas,\n\t\tMetaLevel: b.MetaLevel,\n\t\tMetaLevelPosition: b.MetaLevelPosition,\n\t\tMetaCycle: b.MetaCycle,\n\t\tMetaCyclePosition: b.MetaCyclePosition,\n\t\tMetaVotingPeriod: b.MetaVotingPeriod,\n\t\tMetaVotingPeriodPosition: b.MetaVotingPeriodPosition,\n\t\tExpectedCommitment: b.ExpectedCommitment,\n\t}\n\n\tif b.BlockAggregation != nil {\n\t\tgenBlock.Volume = b.BlockAggregation.Volume\n\t\tgenBlock.Fees = b.BlockAggregation.Fees\n\t\tgenBlock.Endorsements = b.BlockAggregation.Endorsements\n\t\tgenBlock.Proposals = b.BlockAggregation.Proposals\n\t\tgenBlock.SeedNonceRevelations = b.BlockAggregation.SeedNonceRevelations\n\t\tgenBlock.Delegations = b.BlockAggregation.Delegations\n\t\tgenBlock.Transactions = b.BlockAggregation.Transactions\n\t\tgenBlock.ActivateAccounts = b.BlockAggregation.ActivateAccounts\n\t\tgenBlock.Ballots = b.BlockAggregation.Ballots\n\t\tgenBlock.Originations = b.BlockAggregation.Originations\n\t\tgenBlock.Reveals = b.BlockAggregation.Reveals\n\t\tgenBlock.DoubleBakingEvidence = b.BlockAggregation.DoubleBakingEvidences\n\t\tgenBlock.DoubleEndorsementEvidence = b.BlockAggregation.DoubleEndorsementEvidences\n\t\tgenBlock.NumberOfOperations = b.BlockAggregation.NumberOfOperations\n\t}\n\n\treturn &genBlock\n}", "func (s rolloutBlockNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.RolloutBlock, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RolloutBlock))\n\t})\n\treturn ret, err\n}", "func Blocks(offset, count uint) ([]BlockItem, error) {\n\tjsonBlocks := []struct {\n\t\tNumber uint `json:\"number\"`\n\t\tHash string `json:\"hash\"`\n\t\tDate Time `json:\"date\"`\n\t\tDifficulty uint64 `json:\"difficulty\"`\n\t\tMiner string `json:\"miner\"`\n\t}{}\n\tif err := fetch(&jsonBlocks, blockEndpoint, offset, count); err != nil {\n\t\treturn nil, err\n\t}\n\tblocks := make([]BlockItem, len(jsonBlocks))\n\tfor i, b := range jsonBlocks {\n\t\tblocks[i] = BlockItem(b)\n\t}\n\treturn blocks, nil\n}", "func (core *coreService) RawBlocks(startHeight uint64, count uint64, withReceipts bool, withTransactionLogs bool) ([]*iotexapi.BlockInfo, error) {\n\tif count == 0 || count > core.cfg.RangeQueryLimit {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"range exceeds the limit\")\n\t}\n\n\ttipHeight := core.bc.TipHeight()\n\tif startHeight > tipHeight {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"start height should not exceed tip height\")\n\t}\n\tendHeight := startHeight + count - 1\n\tif endHeight > tipHeight {\n\t\tendHeight = tipHeight\n\t}\n\tvar res []*iotexapi.BlockInfo\n\tfor height := startHeight; height <= endHeight; height++ {\n\t\tblk, err := core.dao.GetBlockByHeight(height)\n\t\tif err != nil {\n\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t}\n\t\tvar receiptsPb []*iotextypes.Receipt\n\t\tif withReceipts && height > 0 {\n\t\t\treceipts, err := core.dao.GetReceipts(height)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t\t}\n\t\t\tfor _, receipt := range receipts {\n\t\t\t\treceiptsPb = append(receiptsPb, receipt.ConvertToReceiptPb())\n\t\t\t}\n\t\t}\n\t\tvar transactionLogs *iotextypes.TransactionLogs\n\t\tif withTransactionLogs {\n\t\t\tif transactionLogs, err = core.dao.TransactionLogs(height); err != nil {\n\t\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t\t}\n\t\t}\n\t\tres = append(res, &iotexapi.BlockInfo{\n\t\t\tBlock: blk.ConvertToBlockPb(),\n\t\t\tReceipts: receiptsPb,\n\t\t\tTransactionLogs: transactionLogs,\n\t\t})\n\t}\n\treturn res, nil\n}", "func (_PlasmaFramework *PlasmaFrameworkCaller) Blocks(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\tret := new(struct {\n\t\tRoot [32]byte\n\t\tTimestamp *big.Int\n\t})\n\tout := ret\n\terr := _PlasmaFramework.contract.Call(opts, out, \"blocks\", arg0)\n\treturn *ret, err\n}", "func (_PlasmaFramework *PlasmaFrameworkSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _PlasmaFramework.Contract.Blocks(&_PlasmaFramework.CallOpts, arg0)\n}", "func (b *Block) List(input *BlockCursorInput) (*Blocks, error) {\n\tparams := make(map[string]string)\n\tparams[\"cursor\"] = input.Cursor\n\tresp, err := b.c.Request(http.MethodGet, \"/blocks\", new(bytes.Buffer), params)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar blocks *Blocks\n\terr = json.NewDecoder(resp.Body).Decode(&blocks)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\treturn blocks, nil\n}", "func (_PlasmaFramework *PlasmaFrameworkCallerSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _PlasmaFramework.Contract.Blocks(&_PlasmaFramework.CallOpts, arg0)\n}", "func Blocks(bs []models.Block) []*genModels.BlocksRow {\n\tblocks := make([]*genModels.BlocksRow, len(bs))\n\tfor i := range bs {\n\t\tblocks[i] = Block(bs[i])\n\t}\n\treturn blocks\n}", "func (nc *NSBClient) GetBlocks(rangeL, rangeR int64) (*BlocksInfo, error) {\n\tb, err := nc.handler.Group(\"/blockchain\").GetWithParams(request.Param{\n\t\t\"minHeight\": rangeL,\n\t\t\"maxHeight\": rangeR,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar bb []byte\n\tbb, err = nc.preloadJSONResponse(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar a BlocksInfo\n\terr = json.Unmarshal(bb, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &a, nil\n}", "func (m *BlocksMessage) GetBlocks() ([]*types.Block, error) {\n\tblocks := []*types.Block{}\n\tfor _, data := range m.RawBlocks {\n\t\tblock := &types.Block{}\n\t\tif err := json.Unmarshal(data, block); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tblocks = append(blocks, block)\n\t}\n\treturn blocks, nil\n}", "func (s *Service) GetExplorerBlocks(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfrom := r.FormValue(\"from\")\n\tto := r.FormValue(\"to\")\n\tpageParam := r.FormValue(\"page\")\n\toffsetParam := r.FormValue(\"offset\")\n\torder := r.FormValue(\"order\")\n\tdata := &Data{\n\t\tBlocks: []*Block{},\n\t}\n\tdefer func() {\n\t\tif err := json.NewEncoder(w).Encode(data.Blocks); err != nil {\n\t\t\tutils.Logger().Warn().Err(err).Msg(\"cannot JSON-encode blocks\")\n\t\t}\n\t}()\n\n\tif from == \"\" {\n\t\tutils.Logger().Warn().Msg(\"Missing from parameter\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tdb := s.Storage.GetDB()\n\tfromInt, err := strconv.Atoi(from)\n\tif err != nil {\n\t\tutils.Logger().Warn().Err(err).Msg(\"invalid from parameter\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tvar toInt int\n\tif to == \"\" {\n\t\ttoInt, err = func() (int, error) {\n\t\t\tbytes, err := db.Get([]byte(BlockHeightKey))\n\t\t\tif err == nil {\n\t\t\t\treturn strconv.Atoi(string(bytes))\n\t\t\t}\n\t\t\treturn toInt, err\n\t\t}()\n\t} else {\n\t\ttoInt, err = strconv.Atoi(to)\n\t}\n\tif err != nil {\n\t\tutils.Logger().Warn().Err(err).Msg(\"invalid to parameter\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tvar offset int\n\tif offsetParam != \"\" {\n\t\toffset, err = strconv.Atoi(offsetParam)\n\t\tif err != nil || offset < 1 {\n\t\t\tutils.Logger().Warn().Msg(\"invalid offset parameter\")\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\toffset = paginationOffset\n\t}\n\tvar page int\n\tif pageParam != \"\" {\n\t\tpage, err = strconv.Atoi(pageParam)\n\t\tif err != nil {\n\t\t\tutils.Logger().Warn().Err(err).Msg(\"invalid page parameter\")\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tpage = 0\n\t}\n\n\taccountBlocks := s.ReadBlocksFromDB(fromInt, toInt)\n\tfor id, accountBlock := range accountBlocks {\n\t\tif id == 0 || id == len(accountBlocks)-1 || accountBlock == nil {\n\t\t\tcontinue\n\t\t}\n\t\tblock := NewBlock(accountBlock, id+fromInt-1)\n\t\t// Populate transactions\n\t\tfor _, tx := range accountBlock.Transactions() {\n\t\t\ttransaction := GetTransaction(tx, accountBlock)\n\t\t\tif transaction != nil {\n\t\t\t\tblock.TXs = append(block.TXs, transaction)\n\t\t\t}\n\t\t}\n\t\tif accountBlocks[id-1] == nil {\n\t\t\tblock.BlockTime = int64(0)\n\t\t\tblock.PrevBlock = RefBlock{\n\t\t\t\tID: \"\",\n\t\t\t\tHeight: \"\",\n\t\t\t}\n\t\t} else {\n\t\t\tblock.BlockTime = accountBlock.Time().Int64() - accountBlocks[id-1].Time().Int64()\n\t\t\tblock.PrevBlock = RefBlock{\n\t\t\t\tID: accountBlocks[id-1].Hash().Hex(),\n\t\t\t\tHeight: strconv.Itoa(id + fromInt - 2),\n\t\t\t}\n\t\t}\n\t\tif accountBlocks[id+1] == nil {\n\t\t\tblock.NextBlock = RefBlock{\n\t\t\t\tID: \"\",\n\t\t\t\tHeight: \"\",\n\t\t\t}\n\t\t} else {\n\t\t\tblock.NextBlock = RefBlock{\n\t\t\t\tID: accountBlocks[id+1].Hash().Hex(),\n\t\t\t\tHeight: strconv.Itoa(id + fromInt),\n\t\t\t}\n\t\t}\n\t\tdata.Blocks = append(data.Blocks, block)\n\t}\n\tif offset*page >= len(data.Blocks) {\n\t\tdata.Blocks = []*Block{}\n\t} else if offset*page+offset > len(data.Blocks) {\n\t\tdata.Blocks = data.Blocks[offset*page:]\n\t} else {\n\t\tdata.Blocks = data.Blocks[offset*page : offset*page+offset]\n\t}\n\tif order == \"DESC\" {\n\t\tsort.Slice(data.Blocks[:], func(i, j int) bool {\n\t\t\treturn data.Blocks[i].Timestamp > data.Blocks[j].Timestamp\n\t\t})\n\t} else {\n\t\tsort.Slice(data.Blocks[:], func(i, j int) bool {\n\t\t\treturn data.Blocks[i].Timestamp < data.Blocks[j].Timestamp\n\t\t})\n\t}\n}", "func (obj Events) Block() Block {\n\treturn Block(obj)\n}", "func (t *Thread) Blocks(offsetId string, limit int) []repo.Block {\n\tlog.Debugf(\"listing blocks: offsetId: %s, limit: %d, thread: %s\", offsetId, limit, t.Name)\n\tquery := fmt.Sprintf(\"pk='%s' and type=%d\", t.Id, repo.PhotoBlock)\n\tlist := t.blocks().List(offsetId, limit, query)\n\tlog.Debugf(\"found %d photos in thread %s\", len(list), t.Name)\n\treturn list\n}", "func (_Rootchain *RootchainCaller) Blocks(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\tret := new(struct {\n\t\tRoot [32]byte\n\t\tTimestamp *big.Int\n\t})\n\tout := ret\n\terr := _Rootchain.contract.Call(opts, out, \"blocks\", arg0)\n\treturn *ret, err\n}", "func consensusBlocksGetFromBlock(b types.Block, h types.BlockHeight) ConsensusBlocksGet {\n\ttxns := make([]ConsensusBlocksGetTxn, 0, len(b.Transactions))\n\tfor _, t := range b.Transactions {\n\t\t// Get the transaction's SiacoinOutputs.\n\t\tscos := make([]ConsensusBlocksGetSiacoinOutput, 0, len(t.SiacoinOutputs))\n\t\tfor i, sco := range t.SiacoinOutputs {\n\t\t\tscos = append(scos, ConsensusBlocksGetSiacoinOutput{\n\t\t\t\tID: t.SiacoinOutputID(uint64(i)),\n\t\t\t\tValue: sco.Value,\n\t\t\t\tUnlockHash: sco.UnlockHash,\n\t\t\t})\n\t\t}\n\t\t// Get the transaction's SiafundOutputs.\n\t\tsfos := make([]ConsensusBlocksGetSiafundOutput, 0, len(t.SiafundOutputs))\n\t\tfor i, sfo := range t.SiafundOutputs {\n\t\t\tsfos = append(sfos, ConsensusBlocksGetSiafundOutput{\n\t\t\t\tID: t.SiafundOutputID(uint64(i)),\n\t\t\t\tValue: sfo.Value,\n\t\t\t\tUnlockHash: sfo.UnlockHash,\n\t\t\t})\n\t\t}\n\t\t// Get the transaction's FileContracts.\n\t\tfcos := make([]ConsensusBlocksGetFileContract, 0, len(t.FileContracts))\n\t\tfor i, fc := range t.FileContracts {\n\t\t\t// Get the FileContract's valid proof outputs.\n\t\t\tfcid := t.FileContractID(uint64(i))\n\t\t\tvpos := make([]ConsensusBlocksGetSiacoinOutput, 0, len(fc.ValidProofOutputs))\n\t\t\tfor j, vpo := range fc.ValidProofOutputs {\n\t\t\t\tvpos = append(vpos, ConsensusBlocksGetSiacoinOutput{\n\t\t\t\t\tID: fcid.StorageProofOutputID(types.ProofValid, uint64(j)),\n\t\t\t\t\tValue: vpo.Value,\n\t\t\t\t\tUnlockHash: vpo.UnlockHash,\n\t\t\t\t})\n\t\t\t}\n\t\t\t// Get the FileContract's missed proof outputs.\n\t\t\tmpos := make([]ConsensusBlocksGetSiacoinOutput, 0, len(fc.MissedProofOutputs))\n\t\t\tfor j, mpo := range fc.MissedProofOutputs {\n\t\t\t\tmpos = append(mpos, ConsensusBlocksGetSiacoinOutput{\n\t\t\t\t\tID: fcid.StorageProofOutputID(types.ProofMissed, uint64(j)),\n\t\t\t\t\tValue: mpo.Value,\n\t\t\t\t\tUnlockHash: mpo.UnlockHash,\n\t\t\t\t})\n\t\t\t}\n\t\t\tfcos = append(fcos, ConsensusBlocksGetFileContract{\n\t\t\t\tID: fcid,\n\t\t\t\tFileSize: fc.FileSize,\n\t\t\t\tFileMerkleRoot: fc.FileMerkleRoot,\n\t\t\t\tWindowStart: fc.WindowStart,\n\t\t\t\tWindowEnd: fc.WindowEnd,\n\t\t\t\tPayout: fc.Payout,\n\t\t\t\tValidProofOutputs: vpos,\n\t\t\t\tMissedProofOutputs: mpos,\n\t\t\t\tUnlockHash: fc.UnlockHash,\n\t\t\t\tRevisionNumber: fc.RevisionNumber,\n\t\t\t})\n\t\t}\n\t\ttxns = append(txns, ConsensusBlocksGetTxn{\n\t\t\tID: t.ID(),\n\t\t\tSiacoinInputs: t.SiacoinInputs,\n\t\t\tSiacoinOutputs: scos,\n\t\t\tFileContracts: fcos,\n\t\t\tFileContractRevisions: t.FileContractRevisions,\n\t\t\tStorageProofs: t.StorageProofs,\n\t\t\tSiafundInputs: t.SiafundInputs,\n\t\t\tSiafundOutputs: sfos,\n\t\t\tMinerFees: t.MinerFees,\n\t\t\tArbitraryData: t.ArbitraryData,\n\t\t\tTransactionSignatures: t.TransactionSignatures,\n\t\t})\n\t}\n\treturn ConsensusBlocksGet{\n\t\tID: b.ID(),\n\t\tHeight: h,\n\t\tParentID: b.ParentID,\n\t\tNonce: b.Nonce,\n\t\tTimestamp: b.Timestamp,\n\t\tMinerPayouts: b.MinerPayouts,\n\t\tTransactions: txns,\n\t}\n}", "func (ts *Tipset) Block(miner Miner, winCount int64, msgs ...*ApplicableMessage) {\n\tblock := Block{\n\t\tMinerAddr: miner.MinerActorAddr.ID,\n\t\tWinCount: winCount,\n\t}\n\tfor _, am := range msgs {\n\t\tblock.Messages = append(block.Messages, MustSerialize(am.Message))\n\n\t\t// if we see this message for the first time, add it to the `msgIdx` map and to the `orderMsgs` slice.\n\t\tif _, ok := ts.tss.msgIdx[am.Message.Cid()]; !ok {\n\t\t\tts.tss.msgIdx[am.Message.Cid()] = am\n\t\t\tts.tss.orderedMsgs = append(ts.tss.orderedMsgs, am)\n\t\t}\n\t}\n\n\tts.Blocks = append(ts.Blocks, block)\n}", "func (_Rootchain *RootchainSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _Rootchain.Contract.Blocks(&_Rootchain.CallOpts, arg0)\n}", "func (core *coreService) BlockByHeightRange(start uint64, count uint64) ([]*apitypes.BlockWithReceipts, error) {\n\tif count == 0 {\n\t\treturn nil, errors.Wrap(errInvalidFormat, \"count must be greater than zero\")\n\t}\n\tif count > core.cfg.RangeQueryLimit {\n\t\treturn nil, errors.Wrap(errInvalidFormat, \"range exceeds the limit\")\n\t}\n\n\tvar (\n\t\ttipHeight = core.bc.TipHeight()\n\t\tres = make([]*apitypes.BlockWithReceipts, 0)\n\t)\n\tif start > tipHeight {\n\t\treturn nil, errors.Wrap(errInvalidFormat, \"start height should not exceed tip height\")\n\t}\n\tfor height := start; height <= tipHeight && count > 0; height++ {\n\t\tblkStore, err := core.getBlockByHeight(height)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tres = append(res, blkStore)\n\t\tcount--\n\t}\n\treturn res, nil\n}", "func (c *Client) GetBlocks(height string) (resp *Blocks, e error) {\n\tif height == \"\" {\n\t\treturn nil, c.err(ErrBEW)\n\t}\n\n\tresp = &Blocks{}\n\treturn resp, c.Do(\"/blocks/\"+height, resp, nil)\n}", "func GetBlocks(hostURL string, hostPort int, height int) *bytes.Buffer {\n\tparams := make(map[string]interface{})\n\tparams[\"height\"] = height\n\treturn makePostRequest(hostURL, hostPort, \"f_blocks_list_json\", params)\n}", "func (_Rootchain *RootchainCallerSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _Rootchain.Contract.Blocks(&_Rootchain.CallOpts, arg0)\n}", "func (lp *logPoller) GetBlocksRange(ctx context.Context, numbers []uint64, qopts ...pg.QOpt) ([]LogPollerBlock, error) {\n\tvar blocks []LogPollerBlock\n\n\t// Do nothing if no blocks are requested.\n\tif len(numbers) == 0 {\n\t\treturn blocks, nil\n\t}\n\n\t// Assign the requested blocks to a mapping.\n\tblocksRequested := make(map[uint64]struct{})\n\tfor _, b := range numbers {\n\t\tblocksRequested[b] = struct{}{}\n\t}\n\n\t// Retrieve all blocks within this range from the log poller.\n\tblocksFound := make(map[uint64]LogPollerBlock)\n\tqopts = append(qopts, pg.WithParentCtx(ctx))\n\tminRequestedBlock := mathutil.Min(numbers[0], numbers[1:]...)\n\tmaxRequestedBlock := mathutil.Max(numbers[0], numbers[1:]...)\n\tlpBlocks, err := lp.orm.GetBlocksRange(minRequestedBlock, maxRequestedBlock, qopts...)\n\tif err != nil {\n\t\tlp.lggr.Warnw(\"Error while retrieving blocks from log pollers blocks table. Falling back to RPC...\", \"requestedBlocks\", numbers, \"err\", err)\n\t} else {\n\t\tfor _, b := range lpBlocks {\n\t\t\tif _, ok := blocksRequested[uint64(b.BlockNumber)]; ok {\n\t\t\t\t// Only fill requested blocks.\n\t\t\t\tblocksFound[uint64(b.BlockNumber)] = b\n\t\t\t}\n\t\t}\n\t\tlp.lggr.Debugw(\"Got blocks from log poller\", \"blockNumbers\", maps.Keys(blocksFound))\n\t}\n\n\t// Fill any remaining blocks from the client.\n\tblocksFoundFromRPC, err := lp.fillRemainingBlocksFromRPC(ctx, numbers, blocksFound)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor num, b := range blocksFoundFromRPC {\n\t\tblocksFound[num] = b\n\t}\n\n\tvar blocksNotFound []uint64\n\tfor _, num := range numbers {\n\t\tb, ok := blocksFound[num]\n\t\tif !ok {\n\t\t\tblocksNotFound = append(blocksNotFound, num)\n\t\t}\n\t\tblocks = append(blocks, b)\n\t}\n\n\tif len(blocksNotFound) > 0 {\n\t\treturn nil, errors.Errorf(\"blocks were not found in db or RPC call: %v\", blocksNotFound)\n\t}\n\n\treturn blocks, nil\n}", "func BlockStats(offset, count uint) ([]BlockStatItem, error) {\n\tjsonStats := []struct {\n\t\tDate Time `json:\"date\"`\n\t\tDifficulty uint64 `json:\"difficulty\"`\n\t\tBlockTime float64 `json:\"block_time\"`\n\t}{}\n\tif err := fetch(&jsonStats, blockStatsEndpoint, offset, count); err != nil {\n\t\treturn nil, err\n\t}\n\tstats := make([]BlockStatItem, len(jsonStats))\n\tfor i, s := range jsonStats {\n\t\tstats[i] = BlockStatItem(s)\n\t}\n\treturn stats, nil\n}", "func (c *Client) GetBlocks(ctx context.Context, pg *Pagination) ([]*Account, error) {\n\tvar accounts []*Account\n\terr := c.doAPI(ctx, http.MethodGet, \"/api/v1/blocks\", nil, &accounts, pg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn accounts, nil\n}", "func (d *Dataset) Blocks() []*Block {\n\treturn d.blocks\n}", "func BlocksBakingRights(bs []models.Block) []*genModels.BakingRightsPerBlock {\n\tblocks := make([]*genModels.BakingRightsPerBlock, len(bs))\n\tfor i := range bs {\n\t\tblocks[i] = BlockBakingRights(bs[i])\n\t}\n\treturn blocks\n}", "func (c *Client) Block() *Block {\n\treturn &Block{c}\n}", "func (c *RpcClient) GetBlocks(ctx context.Context, startSlot uint64, endSlot uint64) (GetBlocksResponse, error) {\n\treturn c.processGetBlocks(c.Call(ctx, \"getBlocks\", startSlot, endSlot))\n}", "func (w *FilteredBlockWrapper) Block() *pb.FilteredBlock {\r\n\treturn w.block\r\n}", "func (p *PageListOrderedItemBlocks) GetBlocks() (value []PageBlockClass) {\n\tif p == nil {\n\t\treturn\n\t}\n\treturn p.Blocks\n}", "func BlockAll(ctx context.Context) schema.Block {\n\treturn Block(ctx, Opts{\n\t\tCreate: true,\n\t\tRead: true,\n\t\tUpdate: true,\n\t\tDelete: true,\n\t})\n}", "func GetBlocks(w http.ResponseWriter, r *http.Request) {\n\t// Send a copy of this node's blockchain\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(b.blockchain)\n}", "func (ck *CertKey) CertBlocks() []*pem.Block { return ck.certBlocks }", "func (c *Client) Block() <-chan *types.Block {\n\treturn c.blocks\n}", "func (c *RPCClient) FilterBlocks(\n\treq *FilterBlocksRequest) (*FilterBlocksResponse, er.R) {\n\n\tblockFilterer := NewBlockFilterer(c.chainParams, req)\n\n\t// Construct the watchlist using the addresses and outpoints contained\n\t// in the filter blocks request.\n\twatchList, err := buildFilterBlocksWatchList(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Iterate over the requested blocks, fetching the compact filter for\n\t// each one, and matching it against the watchlist generated above. If\n\t// the filter returns a positive match, the full block is then requested\n\t// and scanned for addresses using the block filterer.\n\tfor i, blk := range req.Blocks {\n\t\trawFilter, err := c.GetCFilter(&blk.Hash, wire.GCSFilterRegular)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Ensure the filter is large enough to be deserialized.\n\t\tif len(rawFilter.Data) < 4 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfilter, err := gcs.FromNBytes(\n\t\t\tbuilder.DefaultP, builder.DefaultM, rawFilter.Data,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Skip any empty filters.\n\t\tif filter.N() == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tkey := builder.DeriveKey(&blk.Hash)\n\t\tmatched, err := filter.MatchAny(key, watchList)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t} else if !matched {\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Infof(\"Fetching block height=%d hash=%v\",\n\t\t\tblk.Height, blk.Hash)\n\n\t\trawBlock, err := c.GetBlock(&blk.Hash)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !blockFilterer.FilterBlock(rawBlock) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// If any external or internal addresses were detected in this\n\t\t// block, we return them to the caller so that the rescan\n\t\t// windows can widened with subsequent addresses. The\n\t\t// `BatchIndex` is returned so that the caller can compute the\n\t\t// *next* block from which to begin again.\n\t\tresp := &FilterBlocksResponse{\n\t\t\tBatchIndex: uint32(i),\n\t\t\tBlockMeta: blk,\n\t\t\tFoundExternalAddrs: blockFilterer.FoundExternal,\n\t\t\tFoundInternalAddrs: blockFilterer.FoundInternal,\n\t\t\tFoundOutPoints: blockFilterer.FoundOutPoints,\n\t\t\tRelevantTxns: blockFilterer.RelevantTxns,\n\t\t}\n\n\t\treturn resp, nil\n\t}\n\n\t// No addresses were found for this range.\n\treturn nil, nil\n}", "func (_Rootchain *RootchainCaller) HeaderBlocks(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tStart *big.Int\n\tEnd *big.Int\n\tCreatedAt *big.Int\n\tProposer common.Address\n}, error) {\n\tret := new(struct {\n\t\tRoot [32]byte\n\t\tStart *big.Int\n\t\tEnd *big.Int\n\t\tCreatedAt *big.Int\n\t\tProposer common.Address\n\t})\n\tout := ret\n\terr := _Rootchain.contract.Call(opts, out, \"headerBlocks\", arg0)\n\treturn *ret, err\n}", "func SeriesBlockToMultiSeriesBlocks(multiNamespaceSeriesList []MultiNamespaceSeries, seriesIteratorsPool encoding.MutableSeriesIteratorsPool) (MultiSeriesBlocks, error) {\n\t// todo(braskin): validate blocks size and aligment per namespace before creating []MultiNamespaceSeries\n\tvar multiSeriesBlocks MultiSeriesBlocks\n\tfor multiNamespaceSeriesIdx, multiNamespaceSeries := range multiNamespaceSeriesList {\n\t\tconsolidatedSeriesBlocks, err := newConsolidatedSeriesBlocks(multiNamespaceSeries, seriesIteratorsPool)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// once we get the length of consolidatedSeriesBlocks, we can create a\n\t\t// MultiSeriesBlocks list with the proper size\n\t\tif multiNamespaceSeriesIdx == 0 {\n\t\t\tmultiSeriesBlocks = make(MultiSeriesBlocks, len(consolidatedSeriesBlocks))\n\t\t}\n\n\t\tfor consolidatedSeriesBlockIdx, consolidatedSeriesBlock := range consolidatedSeriesBlocks {\n\t\t\t// we only want to set the start and end times once\n\t\t\tif multiNamespaceSeriesIdx == 0 {\n\t\t\t\tmultiSeriesBlocks[consolidatedSeriesBlockIdx].Start = consolidatedSeriesBlock.Start\n\t\t\t\tmultiSeriesBlocks[consolidatedSeriesBlockIdx].End = consolidatedSeriesBlock.End\n\t\t\t}\n\n\t\t\tif !consolidatedSeriesBlock.beyondBounds(multiSeriesBlocks[consolidatedSeriesBlockIdx]) {\n\t\t\t\treturn nil, errBlocksMisaligned\n\t\t\t}\n\n\t\t\tmultiSeriesBlocks[consolidatedSeriesBlockIdx].Blocks = append(multiSeriesBlocks[consolidatedSeriesBlockIdx].Blocks, consolidatedSeriesBlock)\n\t\t}\n\t}\n\n\treturn multiSeriesBlocks, nil\n}", "func (hlr *HandlerEnv) GetBlockWrites(c *gin.Context) {\n\tvar err error\n\tvar blkWrts []mdl.BlockWrite\n\tvar rsp = make(map[string]interface{})\n\n\t// Fetch the block writes from the database\n\topts := options.Find().SetSort(bson.D{{\"manifest.timestamp\", -1}})\n\tcsr, err := hlr.CollBlockWrites.Find(context.TODO(), bson.M{\"deleted\": bson.M{\"$ne\": true}}, opts)\n\tif err != nil {\n\t\t// error fetching blockwrites from the database\n\t\tlog.Printf(\"ERROR: %v - error fetching blockwrites from the database. See: %v\\n\",\n\t\t\tutils.FileLine(),\n\t\t\terr)\n\t\trsp[\"msg\"] = \"an error occurred, please try again\"\n\t\tc.JSON(http.StatusInternalServerError, rsp)\n\t\treturn\n\t}\n\n\t// Grab all blockwrites from the query\n\terr = csr.All(context.TODO(), &blkWrts)\n\tif err != nil {\n\t\t// error accessing blockwrite data\n\t\tlog.Printf(\"ERROR: %v - error accessing blockwrite data. See: %v\\n\",\n\t\t\tutils.FileLine(),\n\t\t\terr)\n\t\trsp[\"msg\"] = \"an error occurred, please try again\"\n\t\tc.JSON(http.StatusInternalServerError, rsp)\n\t\treturn\n\t}\n\n\t// Iterate through the query results and construct a response\n\tvar tmpCntArr []map[string]interface{}\n\tfor _, elm := range blkWrts {\n\t\tvar tmpCnt = make(map[string]interface{})\n\n\t\t// Construct a response array element\n\t\ttmpCnt[\"docid\"] = elm.RequestID\n\t\ttmpCnt[\"source\"] = elm.Source\n\t\ttmpCnt[\"event\"] = elm.Event\n\t\ttmpCnt[\"network\"] = elm.ChainNetwork\n\t\ttmpCnt[\"timestamp\"] = fmt.Sprintf(\"%v CST\", elm.Manifest.TimeStamp[:19])\n\t\ttmpCnt[\"block\"] = elm.BlockNumber\n\t\ttmpCnt[\"explorer_link\"] = fmt.Sprintf(\"%vblock/%v\",\n\t\t\tconfig.Consts[\"gochain_testnet_explorer\"],\n\t\t\telm.BlockNumber)\n\n\t\ttmpCnt[\"alert\"] = \"none\"\n\t\t// Set \"alert\" to highlight rows in the client\n\t\tif strings.Contains(strings.ToLower(elm.Event), \"alert\") {\n\t\t\ttmpCnt[\"alert\"] = \"alert\"\n\t\t}\n\n\t\t// Add element to the response\n\t\ttmpCntArr = append(tmpCntArr, tmpCnt)\n\t}\n\n\t// Construct the final response\n\trsp[\"msg\"] = \"blockwrites\"\n\trsp[\"content\"] = tmpCntArr\n\n\tc.JSON(http.StatusOK, rsp)\n}", "func New() *Blockstream {\n\treturn &Blockstream{}\n}", "func (m *GetBlocksMessage) GetBlockLocator() []*bc.Hash {\n\tblockLocator := []*bc.Hash{}\n\tfor _, rawHash := range m.RawBlockLocator {\n\t\thash := bc.NewHash(rawHash)\n\t\tblockLocator = append(blockLocator, &hash)\n\t}\n\treturn blockLocator\n}", "func (client *Client) QueryBlocks(query *Query) (*Response, error) {\n\tpath := \"/block\"\n\turi := fmt.Sprintf(\"%s%s\", client.apiBaseURL, path)\n\n\treq, err := http.NewRequest(\"GET\", uri, bytes.NewBuffer([]byte(\"\")))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuildQuery(req, query)\n\tresp, err := client.performRequest(req, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar results map[string][]Block\n\terr = json.Unmarshal(resp.Response.([]byte), &results)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Response = results\n\treturn resp, err\n}", "func (p *PageListOrderedItemBlocks) MapBlocks() (value PageBlockClassArray) {\n\treturn PageBlockClassArray(p.Blocks)\n}", "func (core *coreService) BlockByHeight(height uint64) (*apitypes.BlockWithReceipts, error) {\n\treturn core.getBlockByHeight(height)\n}", "func getBlock(res rpc.GetBlockResponse) (GetBlockResponse, error) {\n\ttxs := make([]GetBlockTransaction, 0, len(res.Result.Transactions))\n\tfor _, rTx := range res.Result.Transactions {\n\t\tdata, ok := rTx.Transaction.([]interface{})\n\t\tif !ok {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to cast raw response to []interface{}\")\n\t\t}\n\t\tif data[1] != string(rpc.GetTransactionConfigEncodingBase64) {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"encoding mistmatch\")\n\t\t}\n\t\trawTx, err := base64.StdEncoding.DecodeString(data[0].(string))\n\t\tif err != nil {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to base64 decode data, err: %v\", err)\n\t\t}\n\t\ttx, err := types.TransactionDeserialize(rawTx)\n\t\tif err != nil {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to deserialize transaction, err: %v\", err)\n\t\t}\n\n\t\tvar transactionMeta *TransactionMeta\n\t\tif rTx.Meta != nil {\n\t\t\tinnerInstructions := make([]TransactionMetaInnerInstruction, 0, len(rTx.Meta.InnerInstructions))\n\t\t\tfor _, metaInnerInstruction := range rTx.Meta.InnerInstructions {\n\t\t\t\tcompiledInstructions := make([]types.CompiledInstruction, 0, len(metaInnerInstruction.Instructions))\n\t\t\t\tfor _, innerInstruction := range metaInnerInstruction.Instructions {\n\t\t\t\t\tdata, err := base58.Decode(innerInstruction.Data)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to base58 decode data, data: %v, err: %v\", innerInstruction.Data, err)\n\t\t\t\t\t}\n\t\t\t\t\tcompiledInstructions = append(compiledInstructions, types.CompiledInstruction{\n\t\t\t\t\t\tProgramIDIndex: innerInstruction.ProgramIDIndex,\n\t\t\t\t\t\tAccounts: innerInstruction.Accounts,\n\t\t\t\t\t\tData: data,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tinnerInstructions = append(innerInstructions, TransactionMetaInnerInstruction{\n\t\t\t\t\tIndex: metaInnerInstruction.Index,\n\t\t\t\t\tInstructions: compiledInstructions,\n\t\t\t\t})\n\t\t\t}\n\t\t\ttransactionMeta = &TransactionMeta{\n\t\t\t\tErr: rTx.Meta.Err,\n\t\t\t\tFee: rTx.Meta.Fee,\n\t\t\t\tPreBalances: rTx.Meta.PreBalances,\n\t\t\t\tPostBalances: rTx.Meta.PostBalances,\n\t\t\t\tPreTokenBalances: rTx.Meta.PreTokenBalances,\n\t\t\t\tPostTokenBalances: rTx.Meta.PostTokenBalances,\n\t\t\t\tLogMessages: rTx.Meta.LogMessages,\n\t\t\t\tInnerInstructions: innerInstructions,\n\t\t\t}\n\t\t}\n\n\t\ttxs = append(txs,\n\t\t\tGetBlockTransaction{\n\t\t\t\tMeta: transactionMeta,\n\t\t\t\tTransaction: tx,\n\t\t\t},\n\t\t)\n\t}\n\treturn GetBlockResponse{\n\t\tBlockhash: res.Result.Blockhash,\n\t\tBlockTime: res.Result.BlockTime,\n\t\tBlockHeight: res.Result.BlockHeight,\n\t\tPreviousBlockhash: res.Result.PreviousBlockhash,\n\t\tParentSLot: res.Result.ParentSLot,\n\t\tRewards: res.Result.Rewards,\n\t\tTransactions: txs,\n\t}, nil\n}", "func (a *IqnpoolApiService) GetIqnpoolBlockList(ctx context.Context) ApiGetIqnpoolBlockListRequest {\n\treturn ApiGetIqnpoolBlockListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (bc BlockChain) deserializeBlock(o []byte) *Block {\r\n\tif !json.Valid(o) {\r\n\t\tpanic(\"Input is not a valid json object for block\")\r\n\t}\r\n\r\n\tvar jsonBlock Block\r\n\tvar b Block\r\n\t/**\r\n\tdec := json.NewDecoder(strings.NewReader(string(\to)))\r\n\tif err := dec.Decode(&jsonBlock); err == io.EOF {\r\n\t} else if err != nil {\r\n\t\tlog.Fatal(err)\r\n\t}\r\n\t**/\r\n\terr := json.Unmarshal(o, &jsonBlock)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\t//fmt.Println(\"new block is \" + jsonBlock.Serialize())\r\n\r\n\tbalances := make(map[string]int)\r\n\tchainLength := jsonBlock.ChainLength\r\n\ttimestamp := jsonBlock.Timestamp\r\n\r\n\tif jsonBlock.IsGenesisBlock() {\r\n\t\t//fmt.Println(\"setting balances\")\r\n\t\t//fmt.Println(jsonBlock.Balances)\r\n\t\tfor client, amount := range jsonBlock.Balances {\r\n\t\t\tbalances[client] = amount\r\n\t\t}\r\n\t\tb.Balances = balances\r\n\t} else {\r\n\t\tprevBlockHash := jsonBlock.PrevBlockHash\r\n\t\tproof := jsonBlock.Proof\r\n\t\trewardAddr := jsonBlock.RewardAddr\r\n\t\ttransactions := make(map[string]*Transaction)\r\n\t\tif jsonBlock.Transactions != nil {\r\n\t\t\tfor id, tx := range jsonBlock.Transactions {\r\n\t\t\t\ttransactions[id] = tx\r\n\t\t\t}\r\n\t\t}\r\n\t\t//GOTTA FIX THIS WHEN YOU IMPLEMENT CONSTANTS\r\n\t\tb = *bc.MakeBlock(rewardAddr, nil, nil, nil)\r\n\t\tb.ChainLength = chainLength\r\n\t\tb.Timestamp = timestamp\r\n\t\tb.PrevBlockHash = prevBlockHash\r\n\t\tb.Proof = proof\r\n\t\tb.Transactions = transactions\r\n\t}\r\n\treturn &b\r\n}", "func (c *RpcClient) GetBlocksWithConfig(ctx context.Context, startSlot uint64, endSlot uint64, cfg GetBlocksConfig) (GetBlocksResponse, error) {\n\treturn c.processGetBlocks(c.Call(ctx, \"getBlocks\", startSlot, endSlot, cfg))\n}", "func (be *ContentEnc) MergeBlocks(oldData []byte, newData []byte, offset int) []byte {\n\n\t// Make block of maximum size\n\tout := make([]byte, be.plainBS)\n\n\t// Copy old and new data into it\n\tcopy(out, oldData)\n\tl := len(newData)\n\tcopy(out[offset:offset+l], newData)\n\n\t// Crop to length\n\toutLen := len(oldData)\n\tnewLen := offset + len(newData)\n\tif outLen < newLen {\n\t\toutLen = newLen\n\t}\n\treturn out[0:outLen]\n}", "func (log *PbftLog) Blocks() mapset.Set {\n\treturn log.blocks\n}", "func (rt *recvTxOut) Block() *BlockDetails {\n\treturn rt.block\n}", "func (b *Builder) Block() *Builder {\n\treturn new(Builder)\n}", "func (s *BlocksService) Get(ctx context.Context, id string) (*GetBlock, *http.Response, error) {\n\tquery := &BlockIdQuery{Id: id}\n\n\tvar responseStruct *GetBlock\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"blocks/get\", query, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func GetRbBlocks1() int64 {\r\n\treturn SysInt64(RbBlocks1)\r\n}", "func NewBlock(statements []sql.Node) *Block {\n\treturn &Block{statements: statements}\n}", "func (m *GetHeadersMessage) GetBlockLocator() []*bc.Hash {\n\tblockLocator := []*bc.Hash{}\n\tfor _, rawHash := range m.RawBlockLocator {\n\t\thash := bc.NewHash(rawHash)\n\t\tblockLocator = append(blockLocator, &hash)\n\t}\n\treturn blockLocator\n}", "func (tt *BlockTestTable) GetAll() []TypedBlock {\n\tvar result []TypedBlock\n\tfor _, b := range tt.AccountBlocks {\n\t\tresult = append(result, TypedBlock{\n\t\t\tAccountBlock: b,\n\t\t\tT: \"account\",\n\t\t})\n\t}\n\tfor _, b := range tt.SwapBlocks {\n\t\tresult = append(result, TypedBlock{\n\t\t\tSwapBlock: b,\n\t\t\tT: \"swap\",\n\t\t})\n\t}\n\tfor _, b := range tt.OrderBlocks {\n\t\tresult = append(result, TypedBlock{\n\t\t\tOrderBlock: b,\n\t\t\tT: \"order\",\n\t\t})\n\t}\n\treturn result\n}", "func (_Rootchain *RootchainSession) HeaderBlocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tStart *big.Int\n\tEnd *big.Int\n\tCreatedAt *big.Int\n\tProposer common.Address\n}, error) {\n\treturn _Rootchain.Contract.HeaderBlocks(&_Rootchain.CallOpts, arg0)\n}", "func (b *BlockRaw) ToBlock() (*Block, StdError) {\n\tvar (\n\t\tNumber uint64\n\t\tAvgTime int64\n\t\tTxcounts uint64\n\t\tTransactions []TransactionInfo\n\t\terr error\n\t)\n\tif Number, err = strconv.ParseUint(b.Number, 0, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tif strings.Index(b.AvgTime, \"0x\") == 0 || strings.Index(b.AvgTime, \"-0x\") == 0 {\n\t\tb.AvgTime = strings.Replace(b.AvgTime, \"0x\", \"\", 1)\n\t}\n\tif AvgTime, err = strconv.ParseInt(b.AvgTime, 16, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tif Txcounts, err = strconv.ParseUint(b.TxCounts, 0, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tfor _, t := range b.Transactions {\n\t\ttransactionInfo, err := t.ToTransaction()\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn nil, NewSystemError(err)\n\t\t}\n\t\tTransactions = append(Transactions, *transactionInfo)\n\t}\n\treturn &Block{\n\t\tVersion: b.Version,\n\t\tNumber: Number,\n\t\tHash: b.Hash,\n\t\tParentHash: b.ParentHash,\n\t\tWriteTime: b.WriteTime,\n\t\tAvgTime: AvgTime,\n\t\tTxCounts: Txcounts,\n\t\tMerkleRoot: b.MerkleRoot,\n\t\tTransactions: Transactions,\n\t}, nil\n}", "func (r *Replicator) FetchBlocks(ctx context.Context) error {\n\theight, err := r.storage.Height(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.l.WithFields(logrus.Fields{\n\t\t\"height\": height,\n\t}).Info(\"Fetching blocks\")\n\tresp, err := r.GrpcClient.GetBlocks(ctx, &ccmsg.GetBlocksRequest{\n\t\tStartDepth: int64(height),\n\t\tLimit: 5,\n\t})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to fetch blocks\")\n\t}\n\n\tif len(resp.Blocks) == 0 {\n\t\tr.l.Info(\"No new blocks\")\n\t}\n\n\tfor _, block := range resp.Blocks {\n\t\tr.l.WithFields(logrus.Fields{\n\t\t\t\"height\": height,\n\t\t}).Info(\"Appending block\")\n\t\tif _, err := r.storage.AddBlock(ctx, block); err != nil {\n\t\t\treturn err\n\t\t}\n\t\theight++\n\t}\n\n\treturn nil\n}", "func mockBlock(height uint32, txs ...*types.Transaction) *types.Block {\n\treturn &types.Block{\n\t\tHeader: types.Header{\n\t\t\tHeight: height,\n\t\t},\n\t\tTransactions: txs,\n\t}\n}", "func (blockChain *BlockChain) Get(height int32) []Block {\n\treturn blockChain.Chain[height]\n}", "func MockBlock(txs []*types.Tx) *types.Block {\n\treturn &types.Block{\n\t\tBlockHeader: types.BlockHeader{Timestamp: uint64(time.Now().Nanosecond())},\n\t\tTransactions: txs,\n\t}\n}", "func NewBlock(object dbus.BusObject) *Block {\n\treturn &Block{object}\n}", "func (o SecurityGroupRuleOutput) CidrBlocks() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *SecurityGroupRule) pulumi.StringArrayOutput { return v.CidrBlocks }).(pulumi.StringArrayOutput)\n}", "func NewBlockchain(chain ...Block) *Blockchain {\n\treturn &Blockchain{chain}\n}", "func (b *indexBlock) Blocks() ([]blockHandle, error) {\n\tvar lastKey []byte\n\tkb := make([]byte, 0, MaxSstKeySize)\n\tvar blocks []blockHandle\n\n\tfor b.r.Len() > 0 {\n\t\teKey, err := prefixDecodeFrom(b.r, lastKey, kb)\n\t\tlastKey = eKey\n\t\tif _, err := binary.ReadUvarint(b.r); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbh, err := newBlockHandle(b.r)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tblocks = append(blocks, bh)\n\t}\n\n\treturn blocks, nil\n}", "func (l *Ledger) Dump() ([][]string, error) {\n\tl.mutex.RLock()\n\tdefer l.mutex.RUnlock()\n\tit := l.baseDB.NewIteratorWithPrefix([]byte(pb.BlocksTablePrefix))\n\tdefer it.Release()\n\tblocks := make([][]string, l.meta.TrunkHeight+1)\n\tfor it.Next() {\n\t\tblock := &pb.InternalBlock{}\n\t\tparserErr := proto.Unmarshal(it.Value(), block)\n\t\tif parserErr != nil {\n\t\t\treturn nil, parserErr\n\t\t}\n\t\theight := block.Height\n\t\tblockid := fmt.Sprintf(\"{ID:%x,TxCount:%d,InTrunk:%v, Tm:%d, Miner:%s}\", block.Blockid, block.TxCount, block.InTrunk, block.Timestamp/1000000000, block.Proposer)\n\t\tblocks[height] = append(blocks[height], blockid)\n\t}\n\treturn blocks, nil\n}", "func (a *insight) NewBlock(id interface{}) *block {\n\tb := new(block)\n\tb.insight = a\n\tswitch v := id.(type) {\n\tcase int:\n\t\tb.Height = int(v)\n\t\tb.hash()\n\t\tb.pages()\n\t\tb.info()\n\t\treturn b\n\tcase string:\n\t\tb.Hash = string(v)\n\t\tb.pages()\n\t\tb.info()\n\t\treturn b\n\tcase nil:\n\t\treturn b.latestBlock()\n\t}\n\treturn nil\n}", "func (synckerManager *SynckerManager) GetS2BBlocksForBeaconValidator(bestViewShardHash map[byte]common.Hash, list map[byte][]common.Hash) (map[byte][]interface{}, error) {\n\ts2bPoolLists := synckerManager.GetS2BBlocksForBeaconProducer(bestViewShardHash, list)\n\n\tmissingBlocks := compareLists(s2bPoolLists, list)\n\t// synckerManager.config.Server.\n\tif len(missingBlocks) > 0 {\n\t\tctx, _ := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tsynckerManager.StreamMissingShardToBeaconBlock(ctx, missingBlocks)\n\t\t//fmt.Println(\"debug finish stream missing s2b block\")\n\n\t\ts2bPoolLists = synckerManager.GetS2BBlocksForBeaconProducer(bestViewShardHash, list)\n\t\tmissingBlocks = compareLists(s2bPoolLists, list)\n\t\tif len(missingBlocks) > 0 {\n\t\t\treturn nil, errors.New(\"Unable to sync required block in time\")\n\t\t}\n\t}\n\n\tfor sid, heights := range list {\n\t\tif len(s2bPoolLists[sid]) != len(heights) {\n\t\t\treturn nil, fmt.Errorf(\"S2BPoolLists not match sid:%v pool:%v producer:%v\", sid, len(s2bPoolLists[sid]), len(heights))\n\t\t}\n\t}\n\n\treturn s2bPoolLists, nil\n}", "func (b *logEventBuffer) getBlocksInRange(start, end int) []fetchedBlock {\n\tvar blocksInRange []fetchedBlock\n\tstart, end = b.normalRange(start, end)\n\tif start == -1 || end == -1 {\n\t\t// invalid range\n\t\treturn blocksInRange\n\t}\n\tif start < end {\n\t\treturn b.blocks[start:end]\n\t}\n\t// in case we get circular range such as [0, 1, end, ... , start, ..., size-1]\n\t// we need to return the blocks in two ranges: [start, size-1] and [0, end]\n\tblocksInRange = append(blocksInRange, b.blocks[start:]...)\n\tblocksInRange = append(blocksInRange, b.blocks[:end]...)\n\n\treturn blocksInRange\n}", "func (s Store) GetBlock (hash string) (*types.FullSignedBlock, error) {\r\n\t// Open badger\r\n\tstor, err := badger.Open(badger.DefaultOptions(s.StorFileLocation))\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tdefer stor.Close()\r\n\r\n\tvar block types.FullSignedBlock\r\n\terr = stor.Update(func(txn *badger.Txn) error {\r\n\t\tbytes, err := readStringIndex (txn, hash, HashKeyPrefix)\r\n\t\tif err != nil{\r\n\t\t\treturn err\r\n\t\t}\r\n\t\terr = json.Unmarshal(bytes, &block)\r\n\r\n\t\treturn err\r\n\t})\r\n\r\n\treturn &block, err\r\n}", "func (s *BlockService) List(limit int, cursor string) (models.BlockPage, error) {\n\tif limit > 100 {\n\t\tlimit = 100\n\t}\n\tif limit == 0 {\n\t\tlimit = 10\n\t}\n\treturn s.dao.Find(bson.M{}, limit, cursor)\n}", "func (c *Client) GetBlocksByHeight(before, after uint64, noempty bool) (blocks *rpctypes.ResultBlockchainInfo, err error) {\n\tblocks = new(rpctypes.ResultBlockchainInfo)\n\tp := params{}\n\tif after > 0 {\n\t\tp[\"after\"] = after\n\t}\n\tif noempty {\n\t\tp[\"filter\"] = \"noempty\"\n\t}\n\terr = c.get(blocks, c.URLP(\n\t\tp,\n\t\t\"block/before/%d\", before,\n\t))\n\terr = errors.Wrap(err, \"getting blocks by height\")\n\treturn\n}", "func Block(statements ...ast.Stmt) *ast.BlockStmt {\n\treturn &ast.BlockStmt{\n\t\tList: statements,\n\t\tRbrace: statements[len(statements)-1].End(),\n\t}\n}", "func (_Rootchain *RootchainCallerSession) HeaderBlocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tStart *big.Int\n\tEnd *big.Int\n\tCreatedAt *big.Int\n\tProposer common.Address\n}, error) {\n\treturn _Rootchain.Contract.HeaderBlocks(&_Rootchain.CallOpts, arg0)\n}", "func Block(ctx context.Context, opts Opts) schema.Block {\n\treturn schema.SingleNestedBlock{\n\t\tAttributes: attributesMap(opts),\n\t\tCustomType: Type{\n\t\t\tObjectType: types.ObjectType{\n\t\t\t\tAttrTypes: attrTypesMap(opts),\n\t\t\t},\n\t\t},\n\t}\n}", "func GetBlock(x uint64) block.Block{\r\n\t\tvar block1 block.MinBlock\r\n\t\tvar block2 block.Block\r\n\t\tblock1.BlockNumber = x\r\n\t\tblock1.ChainYear = ChainYear\r\n\t\tfmt.Println(\"ChainYear\", block1.ChainYear)\r\n\t\tdata, err:= json.Marshal(block1)\r\n\t\tif err !=nil{\r\n\t\t\tfmt.Println(\"Error Reading Block\", err)\r\n\t\t}\r\n\t\tfmt.Println(\"Block as Json\", data)\r\n\t\ttheNodes := GetNodes(block1.BlockHash())\r\n\t\t\r\n\t\tcall := \"getBlock\"\r\n\t\t\r\n\t\tfor x:=0; x < len(theNodes); x +=1{\r\n\t\t\t\t\r\n\t\t\turl1 := \"http://\"+ MyNode.Ip+ MyNode.Port+\"/\"+ call\r\n\t\t\tfmt.Println(\"url:\", url1)\r\n\t\t\t resp, err := http.Post(url1, \"application/json\", bytes.NewBuffer(data))\r\n\r\n\t\t\tif err != nil {\r\n\t\t\t\tfmt.Println(\"Error connectig to node trying next node \", err)\r\n\t\t\t}else{\r\n\t\t\t\tfmt.Println(\"Block as Json\", data)\r\n\t\t\t\tjson.NewDecoder(resp.Body).Decode(&block2)\r\n\t\t\t\treturn block2\r\n\t\t\t}\r\n\t\t}\r\nreturn block2\r\n\t\t\r\n\t\t\r\n}", "func (gw *Gateway) GetBlocksInRange(start, end uint64) ([]coin.SignedBlock, error) {\n\tvar blocks []coin.SignedBlock\n\tvar err error\n\tgw.strand(\"GetBlocksInRange\", func() {\n\t\tblocks, err = gw.v.GetBlocksInRange(start, end)\n\t})\n\treturn blocks, err\n}", "func (gw *Gateway) GetBlocks(seqs []uint64) ([]coin.SignedBlock, error) {\n\tvar blocks []coin.SignedBlock\n\tvar err error\n\tgw.strand(\"GetBlocks\", func() {\n\t\tblocks, err = gw.v.GetBlocks(seqs)\n\t})\n\treturn blocks, err\n}", "func (c *Client) BlockAfterByHeight(height int64) ([]ExplorerBlockViewModel, error) {\n\ttimeout := time.Duration(10 * time.Second)\n\tclient := http.Client{\n\t\tTimeout: timeout,\n\t}\n\n\tpayload, err := json.Marshal(map[string]int64{\"height\": height})\n\tif err != nil {\n\t\treturn []ExplorerBlockViewModel{}, err\n\t}\n\n\tc.URL.Path = \"/local/chain/blocks-after\"\n\treq, err := c.buildReq(nil, payload, http.MethodPost)\n\tif err != nil {\n\t\treturn []ExplorerBlockViewModel{}, err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn []ExplorerBlockViewModel{}, err\n\t}\n\tdefer resp.Body.Close()\n\tbyteArray, err := ioutil.ReadAll(resp.Body)\n\tif resp.StatusCode != 200 {\n\t\terr := errors.New(string(byteArray))\n\t\treturn []ExplorerBlockViewModel{}, err\n\t}\n\n\tvar data struct {\n\t\tDatas []ExplorerBlockViewModel `json:\"data\"`\n\t}\n\tif err := json.Unmarshal(byteArray, &data); err != nil {\n\t\treturn []ExplorerBlockViewModel{}, err\n\t}\n\treturn data.Datas, nil\n}", "func (b *Block) Get(input *BlockInput) (*Block, error) {\n\tresp, err := b.c.Request(http.MethodGet, fmt.Sprintf(\"/blocks/%s\", input.ID), new(bytes.Buffer), nil)\n\tif err != nil {\n\t\treturn &Block{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar block *Block\n\terr = json.NewDecoder(resp.Body).Decode(&block)\n\tif err != nil {\n\t\treturn &Block{}, err\n\t}\n\treturn block, nil\n}", "func (s *Server) List(ctx context.Context, in *proto.GetBlockRequest) (*proto.GetBlockResponse, error) {\n\ti, err := metrics.Gauge(\"List\", func() (interface{}, error) {\n\t\tresp := new(proto.GetBlockResponse)\n\n\t\tfor _, b := range s.Blockchain.Blocks {\n\t\t\tresp.Blocks = append(resp.Blocks, &proto.Block{\n\t\t\t\tPrevBlockHash: b.PrevBlockHash,\n\t\t\t\tData: b.Data,\n\t\t\t\tHash: b.Hash,\n\t\t\t})\n\t\t}\n\n\t\treturn resp, nil\n\t})\n\treturn i.(*proto.GetBlockResponse), err\n}", "func BlockBakingRights(b models.Block) *genModels.BakingRightsPerBlock {\n\tbr := genModels.BakingRightsPerBlock{Baker: b.Baker, Level: b.Level.Int64, BlockHash: b.Hash.String, BakerPriority: b.Priority.Ptr()}\n\tbr.Rights = BakingRights(b.BakingRights)\n\treturn &br\n}", "func NewBlock() *Block {\n\treturn &Block{}\n}", "func TestBlocklist() *blocklist.Blocklist {\n\tlist := NewTestBlocklist()\n\n\tif err := list.Save(); err != nil {\n\t\tlog.Panic(\"error saving test blocklist: \", err.Error())\n\t}\n\n\treturn list\n}", "func (a *API) GetBlockRlp(number uint64) (hexutil.Bytes, error) {\n\tblock, err := a.backend.BlockByNumber(rpctypes.BlockNumber(number))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rlp.EncodeToBytes(block)\n}", "func New(storage Storage) *Block {\n\tb := Block{\n\t\tstorage: storage,\n\t}\n\tb.Transactions = make([]transaction.Transaction, 0, 0)\n\treturn &b\n}", "func DeserializeBlock(serializedBlock []byte) *Block {\n\tvar block Block\n\n\tdecoder := gob.NewDecoder(bytes.NewReader(serializedBlock))\n\tdecoder.Decode(&block)\n\n\treturn &block\n}", "func NewGetBlocksMessage(blockLocator []*bc.Hash, stopHash *bc.Hash) *GetBlocksMessage {\n\tmsg := &GetBlocksMessage{\n\t\tRawStopHash: stopHash.Byte32(),\n\t}\n\tfor _, hash := range blockLocator {\n\t\tmsg.RawBlockLocator = append(msg.RawBlockLocator, hash.Byte32())\n\t}\n\treturn msg\n}", "func getBlock(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {\n\n\thash, err := chainhash.NewHashFromStr(ps.ByName(\"hash\"))\n\tif err != nil {\n\t\tlog.Printf(\"could not convert string to hash: %s\\n\", err)\n\t}\n\n\tblock, err := dao.GetBlock(hash)\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Not found\")\n\t\treturn\n\t}\n\t//block.Confirmations = getBlockConfirmations(block)\n\t//block.Confirmations = getBlockConfirmations(*block) // needs dynamic calculation\n\n\t//apiblock, err := insight.ConvertToInsightBlock(block)\n\n\tjson.NewEncoder(w).Encode(&block)\n}", "func (s *SetMessageSenderBlockListRequest) GetBlockList() (value BlockListClass) {\n\tif s == nil {\n\t\treturn\n\t}\n\treturn s.BlockList\n}", "func (b *Block) Body() *Body { return &Body{b.transactions, b.signs} }", "func (itr *BlocksItr) Get() (ledger.QueryResult, error) {\n\tif itr.err != nil {\n\t\treturn nil, itr.err\n\t}\n\treturn &BlockHolder{itr.nextBlockBytes}, nil\n}", "func (c *Client) BlockByHeight(height int64) (Block, error) {\n\ttimeout := time.Duration(10 * time.Second)\n\tclient := http.Client{\n\t\tTimeout: timeout,\n\t}\n\n\tpayload, err := json.Marshal(map[string]int64{\"height\": height})\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\n\tc.URL.Path = \"/block/at/public\"\n\treq, err := c.buildReq(nil, payload, http.MethodPost)\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\tdefer resp.Body.Close()\n\tbyteArray, err := ioutil.ReadAll(resp.Body)\n\tif resp.StatusCode != 200 {\n\t\terr := errors.New(string(byteArray))\n\t\treturn Block{}, err\n\t}\n\n\tvar data Block\n\tif err := json.Unmarshal(byteArray, &data); err != nil {\n\t\treturn Block{}, err\n\t}\n\treturn data, nil\n}", "func Blocks(mods ...qm.QueryMod) blockQuery {\n\tmods = append(mods, qm.From(\"\\\"block\\\"\"))\n\treturn blockQuery{NewQuery(mods...)}\n}" ]
[ "0.66517174", "0.61137074", "0.6060496", "0.602393", "0.5799248", "0.57554275", "0.575131", "0.5643157", "0.5598307", "0.5551497", "0.55365604", "0.55362105", "0.5523253", "0.55167264", "0.5508807", "0.54773945", "0.54551417", "0.5453782", "0.54265654", "0.54017013", "0.53818685", "0.5380671", "0.5373953", "0.5337066", "0.5292631", "0.5261075", "0.5247651", "0.52451193", "0.51978517", "0.5185177", "0.5173542", "0.5152453", "0.5145422", "0.5141113", "0.5079533", "0.5069172", "0.50348306", "0.5027683", "0.5015273", "0.50121945", "0.49996543", "0.49879974", "0.49875718", "0.4958089", "0.495362", "0.49029714", "0.49027255", "0.48835933", "0.48753962", "0.48717535", "0.48669693", "0.48570132", "0.48529", "0.48525092", "0.48471007", "0.48460528", "0.4845479", "0.48404953", "0.48282313", "0.48269302", "0.4823273", "0.48174682", "0.48152804", "0.48124412", "0.4803201", "0.4803026", "0.4801392", "0.47930187", "0.4771898", "0.47642648", "0.47570327", "0.47567916", "0.47546145", "0.47517368", "0.47425187", "0.474021", "0.47327402", "0.47296172", "0.4719292", "0.4707597", "0.47043875", "0.4701573", "0.4700263", "0.46988285", "0.4691721", "0.4681538", "0.46808332", "0.46770248", "0.46751356", "0.46601865", "0.46599466", "0.46566957", "0.4649909", "0.46452472", "0.46373454", "0.46308485", "0.46306866", "0.46198225", "0.46178305", "0.46165496" ]
0.7300363
0
List lists all RolloutBlocks in the indexer for a given namespace.
func (s rolloutBlockNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.RolloutBlock, err error) { err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { ret = append(ret, m.(*v1alpha1.RolloutBlock)) }) return ret, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *rolloutBlockLister) List(selector labels.Selector) (ret []*v1alpha1.RolloutBlock, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RolloutBlock))\n\t})\n\treturn ret, err\n}", "func (s *rolloutBlockLister) RolloutBlocks(namespace string) RolloutBlockNamespaceLister {\n\treturn rolloutBlockNamespaceLister{indexer: s.indexer, namespace: namespace}\n}", "func (s rolloutBlockNamespaceLister) Get(name string) (*v1alpha1.RolloutBlock, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"rolloutblock\"), name)\n\t}\n\treturn obj.(*v1alpha1.RolloutBlock), nil\n}", "func (s bundleNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Bundle, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Bundle))\n\t})\n\treturn ret, err\n}", "func NewRolloutBlockLister(indexer cache.Indexer) RolloutBlockLister {\n\treturn &rolloutBlockLister{indexer: indexer}\n}", "func (s sMBNamespaceLister) List(selector labels.Selector) (ret []*v1.SMB, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.SMB))\n\t})\n\treturn ret, err\n}", "func (s beeNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Bee, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Bee))\n\t})\n\treturn ret, err\n}", "func (s hookNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Hook, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Hook))\n\t})\n\treturn ret, err\n}", "func (n *namespaceClient) List() ([]ns.Metadata, error) {\n\turl := fmt.Sprintf(\"%s%s\", n.url, nsh.GetURL)\n\tresp, err := n.client.DoHTTPRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata := &admin.NamespaceGetResponse{}\n\tdefer func() {\n\t\tioutil.ReadAll(resp.Body)\n\t\tresp.Body.Close()\n\t}()\n\tif err := jsonpb.Unmarshal(resp.Body, data); err != nil {\n\t\treturn nil, err\n\t}\n\tnsMetas := []ns.Metadata{}\n\tfor nsID, nsOpts := range data.GetRegistry().GetNamespaces() {\n\t\tmd, err := ns.ToMetadata(nsID, nsOpts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnsMetas = append(nsMetas, md)\n\t}\n\tn.logger.Info(\"namespace retrieved\")\n\treturn nsMetas, nil\n}", "func (s *Server) List(ctx context.Context, in *proto.GetBlockRequest) (*proto.GetBlockResponse, error) {\n\ti, err := metrics.Gauge(\"List\", func() (interface{}, error) {\n\t\tresp := new(proto.GetBlockResponse)\n\n\t\tfor _, b := range s.Blockchain.Blocks {\n\t\t\tresp.Blocks = append(resp.Blocks, &proto.Block{\n\t\t\t\tPrevBlockHash: b.PrevBlockHash,\n\t\t\t\tData: b.Data,\n\t\t\t\tHash: b.Hash,\n\t\t\t})\n\t\t}\n\n\t\treturn resp, nil\n\t})\n\treturn i.(*proto.GetBlockResponse), err\n}", "func (h *Handler) ListByNamespace(namespace string) ([]*unstructured.Unstructured, error) {\n\tlistOptions := h.Options.ListOptions.DeepCopy()\n\tlistOptions.LabelSelector = \"\"\n\n\tif err := h.getGVRAndNamespaceScope(); err != nil {\n\t\treturn nil, err\n\t}\n\tif h.isNamespaced {\n\t\treturn extractList(h.dynamicClient.Resource(h.gvr).Namespace(namespace).List(h.ctx, *listOptions))\n\t}\n\treturn nil, fmt.Errorf(\"%s is not namespace-scoped k8s resource\", h.gvr)\n}", "func (s sensuAssetNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.SensuAsset, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.SensuAsset))\n\t})\n\treturn ret, err\n}", "func (b *Block) List(input *BlockCursorInput) (*Blocks, error) {\n\tparams := make(map[string]string)\n\tparams[\"cursor\"] = input.Cursor\n\tresp, err := b.c.Request(http.MethodGet, \"/blocks\", new(bytes.Buffer), params)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar blocks *Blocks\n\terr = json.NewDecoder(resp.Body).Decode(&blocks)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\treturn blocks, nil\n}", "func (s awsApiGatewayBasePathMappingNamespaceLister) List(selector labels.Selector) (ret []*v1.AwsApiGatewayBasePathMapping, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.AwsApiGatewayBasePathMapping))\n\t})\n\treturn ret, err\n}", "func (s wafregionalRuleNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.WafregionalRule, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.WafregionalRule))\n\t})\n\treturn ret, err\n}", "func (s scyllaDBMonitoringNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ScyllaDBMonitoring, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ScyllaDBMonitoring))\n\t})\n\treturn ret, err\n}", "func (s cloudformationNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Cloudformation, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Cloudformation))\n\t})\n\treturn ret, err\n}", "func (s logicalNetworkNamespaceLister) List(selector labels.Selector) (ret []*v1.LogicalNetwork, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.LogicalNetwork))\n\t})\n\treturn ret, err\n}", "func (c *Module) ListNS() ([]string, error) {\n\tlog.Debug().Msg(\"list namespaces\")\n\n\tclient, err := containerd.New(c.containerd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer client.Close()\n\n\tctx := context.Background()\n\treturn client.NamespaceService().List(ctx)\n}", "func (s icecreamNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Icecream, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Icecream))\n\t})\n\treturn ret, err\n}", "func (s dynamoDBNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.DynamoDB, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.DynamoDB))\n\t})\n\treturn ret, err\n}", "func (s elasticBeanstalkConfigurationTemplateNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ElasticBeanstalkConfigurationTemplate, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ElasticBeanstalkConfigurationTemplate))\n\t})\n\treturn ret, err\n}", "func (s storageBucketNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.StorageBucket, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.StorageBucket))\n\t})\n\treturn ret, err\n}", "func RunList(cmd *cobra.Command, args []string) {\n\tlist := &nbv1.NamespaceStoreList{\n\t\tTypeMeta: metav1.TypeMeta{Kind: \"NamespaceStoreList\"},\n\t}\n\tif !util.KubeList(list, &client.ListOptions{Namespace: options.Namespace}) {\n\t\treturn\n\t}\n\tif len(list.Items) == 0 {\n\t\tfmt.Printf(\"No namespace stores found.\\n\")\n\t\treturn\n\t}\n\ttable := (&util.PrintTable{}).AddRow(\n\t\t\"NAME\",\n\t\t\"TYPE\",\n\t\t\"TARGET-BUCKET\",\n\t\t\"PHASE\",\n\t\t\"AGE\",\n\t)\n\tfor i := range list.Items {\n\t\tbs := &list.Items[i]\n\t\ttb, err := util.GetNamespaceStoreTargetBucket(bs)\n\t\tif err == nil {\n\t\t\ttable.AddRow(\n\t\t\t\tbs.Name,\n\t\t\t\tstring(bs.Spec.Type),\n\t\t\t\ttb,\n\t\t\t\tstring(bs.Status.Phase),\n\t\t\t\tutil.HumanizeDuration(time.Since(bs.CreationTimestamp.Time).Round(time.Second)),\n\t\t\t)\n\t\t}\n\t}\n\tfmt.Print(table.String())\n}", "func (s testRunNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.TestRun, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.TestRun))\n\t})\n\treturn ret, err\n}", "func (k8s *Client) ListNamespaces() []string {\n\treturn k8s.namespaceIndexer.ListIndexFuncValues(namespaceIndexName)\n}", "func (s monitorMetricAlertruleNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.MonitorMetricAlertrule, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.MonitorMetricAlertrule))\n\t})\n\treturn ret, err\n}", "func (s crdExampleNamespaceLister) List(selector labels.Selector) (ret []*v1.CrdExample, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.CrdExample))\n\t})\n\treturn ret, err\n}", "func (s sealedSecretNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.SealedSecret, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.SealedSecret))\n\t})\n\treturn ret, err\n}", "func (s volumeCloneSourceNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.VolumeCloneSource, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.VolumeCloneSource))\n\t})\n\treturn ret, err\n}", "func (s rBACDefinitionNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.RBACDefinition, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.RBACDefinition))\n\t})\n\treturn ret, err\n}", "func (s *bundleLister) List(selector labels.Selector) (ret []*v1alpha1.Bundle, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Bundle))\n\t})\n\treturn ret, err\n}", "func (s clientViewNamespaceLister) List(selector labels.Selector) (ret []*v1alpha.ClientView, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha.ClientView))\n\t})\n\treturn ret, err\n}", "func (s bindingTemplateNamespaceLister) List(selector labels.Selector) (ret []*experimental.BindingTemplate, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*experimental.BindingTemplate))\n\t})\n\treturn ret, err\n}", "func (r *resource) ListWithNamespace(ns string, list runtime.Object) error {\n\terr := r.client.ControlCli.List(context.TODO(), &runtimecli.ListOptions{Namespace: ns}, list)\n\tif err != nil {\n\t\tlog.Warn(\"Failed to list resource. \", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s elasticacheClusterNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ElasticacheCluster, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ElasticacheCluster))\n\t})\n\treturn ret, err\n}", "func (s kylinNodeNamespaceLister) List(selector labels.Selector) (ret []*v1.KylinNode, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.KylinNode))\n\t})\n\treturn ret, err\n}", "func (s oAuthClientNamespaceLister) List(selector labels.Selector) (ret []*api.OAuthClient, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*api.OAuthClient))\n\t})\n\treturn ret, err\n}", "func (s keyVaultKeyNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.KeyVaultKey, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.KeyVaultKey))\n\t})\n\treturn ret, err\n}", "func (s recoveryServicesProtectionContainerNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.RecoveryServicesProtectionContainer, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RecoveryServicesProtectionContainer))\n\t})\n\treturn ret, err\n}", "func (s cognitoResourceServerNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.CognitoResourceServer, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.CognitoResourceServer))\n\t})\n\treturn ret, err\n}", "func (s genericNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Generic, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Generic))\n\t})\n\treturn ret, err\n}", "func (s eCRRepositoryNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ECRRepository, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ECRRepository))\n\t})\n\treturn ret, err\n}", "func (s consumerNamespaceLister) List(selector labels.Selector) (ret []*arbv1.Consumer, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*arbv1.Consumer))\n\t})\n\treturn ret, err\n}", "func (s *API) ListNamespaces(req *ListNamespacesRequest, opts ...scw.RequestOption) (*ListNamespacesResponse, error) {\n\tvar err error\n\n\tif req.Region == \"\" {\n\t\tdefaultRegion, _ := s.client.GetDefaultRegion()\n\t\treq.Region = defaultRegion\n\t}\n\n\tdefaultPageSize, exist := s.client.GetDefaultPageSize()\n\tif (req.PageSize == nil || *req.PageSize == 0) && exist {\n\t\treq.PageSize = &defaultPageSize\n\t}\n\n\tquery := url.Values{}\n\tparameter.AddToQuery(query, \"page\", req.Page)\n\tparameter.AddToQuery(query, \"page_size\", req.PageSize)\n\tparameter.AddToQuery(query, \"order_by\", req.OrderBy)\n\tparameter.AddToQuery(query, \"organization_id\", req.OrganizationID)\n\tparameter.AddToQuery(query, \"project_id\", req.ProjectID)\n\tparameter.AddToQuery(query, \"name\", req.Name)\n\n\tif fmt.Sprint(req.Region) == \"\" {\n\t\treturn nil, errors.New(\"field Region cannot be empty in request\")\n\t}\n\n\tscwReq := &scw.ScalewayRequest{\n\t\tMethod: \"GET\",\n\t\tPath: \"/registry/v1/regions/\" + fmt.Sprint(req.Region) + \"/namespaces\",\n\t\tQuery: query,\n\t\tHeaders: http.Header{},\n\t}\n\n\tvar resp ListNamespacesResponse\n\n\terr = s.client.Do(scwReq, &resp, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func (client OccMetricsClient) listNamespaces(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/namespaces\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListNamespacesResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\tapiReferenceLink := \"https://docs.oracle.com/iaas/api/#/en/occ/20230515/NamespaceCollection/ListNamespaces\"\n\t\terr = common.PostProcessServiceError(err, \"OccMetrics\", \"ListNamespaces\", apiReferenceLink)\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func RunNamespacesListRegions(c *CmdConfig) error {\n\tif len(c.Args) > 0 {\n\t\treturn doctl.NewTooManyArgsErr(c.NS)\n\t}\n\tfmt.Fprintf(c.Out, \"%+v\\n\", getValidRegions())\n\treturn nil\n}", "func (s appsyncDatasourceNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.AppsyncDatasource, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.AppsyncDatasource))\n\t})\n\treturn ret, err\n}", "func (s democrdNamespaceLister) List(selector labels.Selector) (ret []*v1.Democrd, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Democrd))\n\t})\n\treturn ret, err\n}", "func (s targetNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Target, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Target))\n\t})\n\treturn ret, err\n}", "func (s awsIamPolicyAttachmentNamespaceLister) List(selector labels.Selector) (ret []*v1.AwsIamPolicyAttachment, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.AwsIamPolicyAttachment))\n\t})\n\treturn ret, err\n}", "func (s trialNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Trial, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.Trial))\n\t})\n\treturn ret, err\n}", "func (s seaOtterNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.SeaOtter, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.SeaOtter))\n\t})\n\treturn ret, err\n}", "func (a *DefaultClient) List(l vfs.Location) ([]string, error) {\n\tURL, err := url.Parse(l.(*Location).ContainerURL())\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tcontainerURL := azblob.NewContainerURL(*URL, a.pipeline)\n\tctx := context.Background()\n\tvar list []string\n\tfor marker := (azblob.Marker{}); marker.NotDone(); {\n\t\tlistBlob, err := containerURL.ListBlobsHierarchySegment(ctx, marker, \"/\",\n\t\t\tazblob.ListBlobsSegmentOptions{Prefix: utils.RemoveLeadingSlash(l.Path())})\n\t\tif err != nil {\n\t\t\treturn []string{}, err\n\t\t}\n\n\t\tmarker = listBlob.NextMarker\n\n\t\tfor i := range listBlob.Segment.BlobItems {\n\t\t\tlist = append(list, listBlob.Segment.BlobItems[i].Name)\n\t\t}\n\t}\n\treturn list, nil\n}", "func (client IdentityClient) listTagNamespaces(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/tagNamespaces\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListTagNamespacesResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (s *BlockService) List(limit int, cursor string) (models.BlockPage, error) {\n\tif limit > 100 {\n\t\tlimit = 100\n\t}\n\tif limit == 0 {\n\t\tlimit = 10\n\t}\n\treturn s.dao.Find(bson.M{}, limit, cursor)\n}", "func (c *MockVirtualNetworksClient) List(ctx context.Context, resourceGroupName string) ([]network.VirtualNetwork, error) {\n\tvar l []network.VirtualNetwork\n\tfor _, vnet := range c.VNets {\n\t\tl = append(l, vnet)\n\t}\n\treturn l, nil\n}", "func (c *MockLoadBalancersClient) List(ctx context.Context, resourceGroupName string) ([]network.LoadBalancer, error) {\n\tvar l []network.LoadBalancer\n\tfor _, lb := range c.LBs {\n\t\tl = append(l, lb)\n\t}\n\treturn l, nil\n}", "func (s gameliftFleetNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.GameliftFleet, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.GameliftFleet))\n\t})\n\treturn ret, err\n}", "func (client OccMetricsClient) ListNamespaces(ctx context.Context, request ListNamespacesRequest) (response ListNamespacesResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.DefaultRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.listNamespaces, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = ListNamespacesResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ListNamespacesResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListNamespacesResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListNamespacesResponse\")\n\t}\n\treturn\n}", "func (s vulnerabilityNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Vulnerability, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Vulnerability))\n\t})\n\treturn ret, err\n}", "func (s pipelineResourceNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.PipelineResource, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.PipelineResource))\n\t})\n\treturn ret, err\n}", "func (s ingressListenerNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.IngressListener, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.IngressListener))\n\t})\n\treturn ret, err\n}", "func (s computeRouterInterfaceNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ComputeRouterInterface, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ComputeRouterInterface))\n\t})\n\treturn ret, err\n}", "func (s databaseClusterNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.DatabaseCluster, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.DatabaseCluster))\n\t})\n\treturn ret, err\n}", "func (s routeGroupNamespaceLister) List(selector labels.Selector) (ret []*v1.RouteGroup, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.RouteGroup))\n\t})\n\treturn ret, err\n}", "func (s rabbitmqSourceNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.RabbitmqSource, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RabbitmqSource))\n\t})\n\treturn ret, err\n}", "func (s knativeEventingNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.KnativeEventing, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.KnativeEventing))\n\t})\n\treturn ret, err\n}", "func (s elasticDLJobNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ElasticDLJob, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ElasticDLJob))\n\t})\n\treturn ret, err\n}", "func (s kogitoSourceNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.KogitoSource, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.KogitoSource))\n\t})\n\treturn ret, err\n}", "func (c *Client) Namespace(ns string, onlyLeaf bool) ([]string, error) {\n\tvar res []string\n\tfullURL := fmt.Sprintf(\"%s/router/ns?ns=%s&format=list\", c.Addr, ns)\n\tresp, err := http.Get(fullURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode/100 != 2 {\n\t\treturn nil, fmt.Errorf(\"HTTP status error: %d\", resp.Status)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar data namespace\n\tif err := json.Unmarshal(body, &data); err != nil {\n\t\treturn nil, err\n\t}\n\n\tres = data.Data\n\n\tif !onlyLeaf {\n\t\ttmp := make(map[string]bool)\n\t\tfor _, leaf := range data.Data {\n\t\t\tarr := strings.SplitAfterN(leaf, \".\", 2)\n\t\t\tif len(arr) > 1 {\n\t\t\t\ttmp[arr[1]] = true\n\t\t\t}\n\t\t}\n\n\t\tfor k := range tmp {\n\t\t\tres = append(res, k)\n\t\t}\n\t}\n\n\treturn res, nil\n}", "func (s backendConfigNamespaceLister) List(selector labels.Selector) (ret []*v1.BackendConfig, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.BackendConfig))\n\t})\n\treturn ret, err\n}", "func (s apiGatewayModelNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ApiGatewayModel, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ApiGatewayModel))\n\t})\n\treturn ret, err\n}", "func (s ssmPatchGroupNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.SsmPatchGroup, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.SsmPatchGroup))\n\t})\n\treturn ret, err\n}", "func (s computeRegionInstanceGroupManagerNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ComputeRegionInstanceGroupManager, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.ComputeRegionInstanceGroupManager))\n\t})\n\treturn ret, err\n}", "func (s *wafregionalRuleLister) List(selector labels.Selector) (ret []*v1alpha1.WafregionalRule, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.WafregionalRule))\n\t})\n\treturn ret, err\n}", "func (c *SubresourceClient) List(namespace string, labels map[string]string) (result []metav1.Object, e error) {\n\tif c.Error != \"\" {\n\t\te = fmt.Errorf(c.Error)\n\t} else {\n\t\tresult = []metav1.Object{c.Subresource}\n\t}\n\treturn\n}", "func List(client *golangsdk.ServiceClient, clusterId string) (r ListResult) {\n\t_, r.Err = client.Get(listURL(client, clusterId), &r.Body, nil)\n\treturn\n}", "func (k *KV) List(ctx context.Context, namespace, path string) ([]string, error) {\n\tpath, err := getKVPath(namespace, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn k.b.List(ctx, path)\n}", "func (obs *Observer) List(opts metav1.ListOptions) (*unstructured.UnstructuredList, error) {\n\treturn obs.client.Namespace(obs.namespace).List(opts)\n}", "func (s routeClaimNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.RouteClaim, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RouteClaim))\n\t})\n\treturn ret, err\n}", "func (c *sandboxes) List(ctx context.Context, opts metav1.ListOptions) (result *v1.SandboxList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = &v1.SandboxList{}\n\terr = c.client.Get().\n\t\tResource(\"sandboxes\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}", "func (h Client) list(namespace string, extraArgs ...string) (string, error) {\n\targs := []string{\"list\", \"--namespace\", namespace}\n\targs = append(args, extraArgs...)\n\tstdOut, stdErr, err := h.Exec(args...)\n\tif err != nil && stdErr != \"\" {\n\t\treturn \"\", errors.New(stdErr)\n\t}\n\treturn stdOut, nil\n}", "func (a *IqnpoolApiService) GetIqnpoolBlockList(ctx context.Context) ApiGetIqnpoolBlockListRequest {\n\treturn ApiGetIqnpoolBlockListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (s passwordNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Password, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Password))\n\t})\n\treturn ret, err\n}", "func (s tagRouteNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.TagRoute, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.TagRoute))\n\t})\n\treturn ret, err\n}", "func (client *NamespacesClient) GetList(limit, skip int) (*schema.Namespaces, error) {\n\tif limit <= 0 {\n\t\tlimit = 10\n\t}\n\tif skip < 0 {\n\t\tskip = 0\n\t}\n\n\tresponse, err := client.http.execute(\"GET\", fmt.Sprintf(\"%s?limit=%d&skip=%d\", endpointNamespaces, limit, skip), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnamespaces := new(schema.Namespaces)\n\tif err := json.Unmarshal(response, namespaces); err != nil {\n\t\treturn nil, err\n\t}\n\treturn namespaces, nil\n}", "func (d *namespaceHandlerImpl) ListNamespaces(\n\tctx context.Context,\n\tlistRequest *workflowservice.ListNamespacesRequest,\n) (*workflowservice.ListNamespacesResponse, error) {\n\n\tpageSize := 100\n\tif listRequest.GetPageSize() != 0 {\n\t\tpageSize = int(listRequest.GetPageSize())\n\t}\n\n\tresp, err := d.metadataMgr.ListNamespaces(ctx, &persistence.ListNamespacesRequest{\n\t\tPageSize: pageSize,\n\t\tNextPageToken: listRequest.NextPageToken,\n\t\tIncludeDeleted: listRequest.GetNamespaceFilter().GetIncludeDeleted(),\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar namespaces []*workflowservice.DescribeNamespaceResponse\n\tfor _, namespace := range resp.Namespaces {\n\t\tdesc := &workflowservice.DescribeNamespaceResponse{\n\t\t\tIsGlobalNamespace: namespace.IsGlobalNamespace,\n\t\t\tFailoverVersion: namespace.Namespace.FailoverVersion,\n\t\t}\n\t\tdesc.NamespaceInfo, desc.Config, desc.ReplicationConfig, desc.FailoverHistory =\n\t\t\td.createResponse(\n\t\t\t\tnamespace.Namespace.Info,\n\t\t\t\tnamespace.Namespace.Config,\n\t\t\t\tnamespace.Namespace.ReplicationConfig)\n\t\tnamespaces = append(namespaces, desc)\n\t}\n\n\tresponse := &workflowservice.ListNamespacesResponse{\n\t\tNamespaces: namespaces,\n\t\tNextPageToken: resp.NextPageToken,\n\t}\n\n\treturn response, nil\n}", "func (s spannerInstanceIamBindingNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.SpannerInstanceIamBinding, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.SpannerInstanceIamBinding))\n\t})\n\treturn ret, err\n}", "func (s messagingInfrastructureNamespaceLister) List(selector labels.Selector) (ret []*v1.MessagingInfrastructure, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.MessagingInfrastructure))\n\t})\n\treturn ret, err\n}", "func (c *BlockVolumeClient) List(params *BlockVolumeParams) (*BlockVolumeList, error) {\n\tlist := &BlockVolumeList{}\n\n\terr := c.Backend.CallIntoInterface(\"v1/Storage/Block/Volume/list\", params, list)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn list, nil\n}", "func RunNamespacesList(c *CmdConfig) error {\n\tif len(c.Args) > 0 {\n\t\treturn doctl.NewTooManyArgsErr(c.NS)\n\t}\n\tlist, err := c.Serverless().ListNamespaces(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.Display(&displayers.Namespaces{Info: list.Namespaces})\n}", "func (c *MockRouteTablesClient) List(ctx context.Context, resourceGroupName string) ([]network.RouteTable, error) {\n\tvar l []network.RouteTable\n\tfor _, rt := range c.RTs {\n\t\tl = append(l, rt)\n\t}\n\treturn l, nil\n}", "func BlockStats(offset, count uint) ([]BlockStatItem, error) {\n\tjsonStats := []struct {\n\t\tDate Time `json:\"date\"`\n\t\tDifficulty uint64 `json:\"difficulty\"`\n\t\tBlockTime float64 `json:\"block_time\"`\n\t}{}\n\tif err := fetch(&jsonStats, blockStatsEndpoint, offset, count); err != nil {\n\t\treturn nil, err\n\t}\n\tstats := make([]BlockStatItem, len(jsonStats))\n\tfor i, s := range jsonStats {\n\t\tstats[i] = BlockStatItem(s)\n\t}\n\treturn stats, nil\n}", "func (s awsCustomerGatewayNamespaceLister) List(selector labels.Selector) (ret []*v1.AwsCustomerGateway, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.AwsCustomerGateway))\n\t})\n\treturn ret, err\n}", "func (s bucketRequestNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.BucketRequest, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.BucketRequest))\n\t})\n\treturn ret, err\n}", "func (c *MockNatGatewaysClient) List(ctx context.Context, resourceGroupName string) ([]network.NatGateway, error) {\n\tvar l []network.NatGateway\n\tfor _, ngw := range c.NGWs {\n\t\tl = append(l, ngw)\n\t}\n\treturn l, nil\n}", "func (s shareManagerNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.ShareManager, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1beta1.ShareManager))\n\t})\n\treturn ret, err\n}", "func (s chaosNamespaceLister) List(selector labels.Selector) (ret []*v1.Chaos, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.Chaos))\n\t})\n\treturn ret, err\n}", "func (s virtualHubNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.VirtualHub, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.VirtualHub))\n\t})\n\treturn ret, err\n}" ]
[ "0.70668423", "0.6486759", "0.59354115", "0.58971703", "0.58813244", "0.5809516", "0.5714969", "0.56303203", "0.55635107", "0.5493994", "0.5447972", "0.54354554", "0.54354066", "0.5417491", "0.53622055", "0.5223752", "0.5200587", "0.51956224", "0.5188562", "0.51839614", "0.51690185", "0.51596916", "0.51514935", "0.5148788", "0.5135959", "0.5121471", "0.5120799", "0.5108839", "0.51078004", "0.5106584", "0.51009744", "0.50907606", "0.50813645", "0.5078766", "0.5075793", "0.50652", "0.50600624", "0.50401723", "0.50324005", "0.50180435", "0.499617", "0.4990094", "0.49713722", "0.4967371", "0.496105", "0.49585378", "0.49427384", "0.49221405", "0.49217427", "0.49100912", "0.49099103", "0.48983333", "0.48940027", "0.48896435", "0.48865807", "0.48844427", "0.48744005", "0.48698214", "0.48641545", "0.48579645", "0.4840469", "0.48329124", "0.48302022", "0.48290154", "0.48283204", "0.48241305", "0.4823285", "0.48225576", "0.4809655", "0.48047125", "0.47859463", "0.47847125", "0.4783148", "0.4780255", "0.47788945", "0.47776496", "0.47769684", "0.47756767", "0.477124", "0.47645542", "0.4757949", "0.4754976", "0.47482017", "0.47452405", "0.47421414", "0.47393233", "0.47382417", "0.4735205", "0.47315958", "0.4725929", "0.4725348", "0.4724894", "0.47227582", "0.47181523", "0.4715999", "0.47148082", "0.4713132", "0.47030097", "0.46834278", "0.46811578" ]
0.81074965
0
Get retrieves the RolloutBlock from the indexer for a given namespace and name.
func (s rolloutBlockNamespaceLister) Get(name string) (*v1alpha1.RolloutBlock, error) { obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err } if !exists { return nil, errors.NewNotFound(v1alpha1.Resource("rolloutblock"), name) } return obj.(*v1alpha1.RolloutBlock), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s beeNamespaceLister) Get(name string) (*v1beta1.Bee, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"bee\"), name)\n\t}\n\treturn obj.(*v1beta1.Bee), nil\n}", "func (s bundleNamespaceLister) Get(name string) (*v1alpha1.Bundle, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"bundle\"), name)\n\t}\n\treturn obj.(*v1alpha1.Bundle), nil\n}", "func (s sMBNamespaceLister) Get(name string) (*v1.SMB, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"smb\"), name)\n\t}\n\treturn obj.(*v1.SMB), nil\n}", "func (s hookNamespaceLister) Get(name string) (*v1alpha1.Hook, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"hook\"), name)\n\t}\n\treturn obj.(*v1alpha1.Hook), nil\n}", "func (s logicalNetworkNamespaceLister) Get(name string) (*v1.LogicalNetwork, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(r.Resource(\"logicalnetwork\"), name)\n\t}\n\treturn obj.(*v1.LogicalNetwork), nil\n}", "func (nsi namespaceIndex) Get(name string) *namespaceData {\n\tdata := nsi[name]\n\tif data != nil {\n\t\treturn data\n\t}\n\tdata = &namespaceData{}\n\tnsi[name] = data\n\treturn data\n}", "func (api *APIClient) GetBlockByRepoName(repoPieces RepoPieces) (Block, error) {\n\tu, err := url.Parse(fmt.Sprintf(\"%s/api/v1/blocks\", api.baseURL))\n\tif err != nil {\n\t\treturn Block{}, errors.New(\"unable to parse Learn remote\")\n\t}\n\tv := url.Values{}\n\tv.Set(\"repo_name\", repoPieces.RepoName)\n\tv.Set(\"org\", repoPieces.Org)\n\tv.Set(\"origin\", repoPieces.Origin)\n\tu.RawQuery = v.Encode()\n\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Source\", \"gLearn_cli\")\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", api.Credentials.token))\n\n\tres, err := api.client.Do(req)\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != http.StatusOK {\n\t\treturn Block{}, fmt.Errorf(\"Error: response status: %d\", res.StatusCode)\n\t}\n\n\tvar blockResp blockResponse\n\terr = json.NewDecoder(res.Body).Decode(&blockResp)\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\n\tif len(blockResp.Blocks) == 1 {\n\t\treturn blockResp.Blocks[0], nil\n\t}\n\treturn Block{}, nil\n}", "func (s wafregionalRuleNamespaceLister) Get(name string) (*v1alpha1.WafregionalRule, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"wafregionalrule\"), name)\n\t}\n\treturn obj.(*v1alpha1.WafregionalRule), nil\n}", "func (s volumeCloneSourceNamespaceLister) Get(name string) (*v1beta1.VolumeCloneSource, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"volumeclonesource\"), name)\n\t}\n\treturn obj.(*v1beta1.VolumeCloneSource), nil\n}", "func (s rolloutBlockNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.RolloutBlock, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.RolloutBlock))\n\t})\n\treturn ret, err\n}", "func (s rabbitmqSourceNamespaceLister) Get(name string) (*v1alpha1.RabbitmqSource, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"rabbitmqsource\"), name)\n\t}\n\treturn obj.(*v1alpha1.RabbitmqSource), nil\n}", "func (s monitorMetricAlertruleNamespaceLister) Get(name string) (*v1alpha1.MonitorMetricAlertrule, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"monitormetricalertrule\"), name)\n\t}\n\treturn obj.(*v1alpha1.MonitorMetricAlertrule), nil\n}", "func (s *fsStore) Get(typ namespace.Type, name string) (*namespace.Namespace, error) {\n\tif !s.Exists(typ, name) {\n\t\treturn nil, store.ErrNotExists\n\t}\n\ttrgt := s.targetPath(name, typ)\n\treturn namespace.FromPath(trgt)\n}", "func (s genericNamespaceLister) Get(name string) (*v1alpha1.Generic, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"generic\"), name)\n\t}\n\treturn obj.(*v1alpha1.Generic), nil\n}", "func (s bindingTemplateNamespaceLister) Get(name string) (*experimental.BindingTemplate, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(experimental.Resource(\"bindingtemplate\"), name)\n\t}\n\treturn obj.(*experimental.BindingTemplate), nil\n}", "func (s kogitoSourceNamespaceLister) Get(name string) (*v1alpha1.KogitoSource, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"kogitosource\"), name)\n\t}\n\treturn obj.(*v1alpha1.KogitoSource), nil\n}", "func (c *MultiClusterController) Get(clusterName, namespace, name string) (interface{}, error) {\n\tcluster := c.GetCluster(clusterName)\n\tif cluster == nil {\n\t\treturn nil, errors.NewClusterNotFound(clusterName)\n\t}\n\tinstance := utilscheme.Scheme.NewObject(c.objectType)\n\tdelegatingClient, err := cluster.GetDelegatingClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = delegatingClient.Get(context.TODO(), client.ObjectKey{\n\t\tNamespace: namespace,\n\t\tName: name,\n\t}, instance)\n\treturn instance, err\n}", "func (s targetNamespaceLister) Get(name string) (*v1alpha1.Target, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"target\"), name)\n\t}\n\treturn obj.(*v1alpha1.Target), nil\n}", "func (client Client) Get(resourceGroupName string, name string) (result ResourceType, err error) {\n\treq, err := client.GetPreparer(resourceGroupName, name)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"redis.Client\", \"Get\", nil, \"Failure preparing request\")\n\t}\n\n\tresp, err := client.GetSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(err, \"redis.Client\", \"Get\", resp, \"Failure sending request\")\n\t}\n\n\tresult, err = client.GetResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"redis.Client\", \"Get\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (bp RPCBlockProvider) GetBlock(index int) SignedBlockData {\r\n\tvar block SignedBlockData\r\n\terr := bp.Client.Call(\"BlockPropagationHandler.GetBlock\", index, &block)\r\n\tif err != nil {\r\n\t\tlog.Print(err)\r\n\t}\r\n\treturn block\r\n}", "func (s kylinNodeNamespaceLister) Get(name string) (*v1.KylinNode, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"kylinnode\"), name)\n\t}\n\treturn obj.(*v1.KylinNode), nil\n}", "func (s sealedSecretNamespaceLister) Get(name string) (*v1alpha1.SealedSecret, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"sealedsecret\"), name)\n\t}\n\treturn obj.(*v1alpha1.SealedSecret), nil\n}", "func (s elasticDLJobNamespaceLister) Get(name string) (*v1alpha1.ElasticDLJob, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"elasticdljob\"), name)\n\t}\n\treturn obj.(*v1alpha1.ElasticDLJob), nil\n}", "func (s seaOtterNamespaceLister) Get(name string) (*v1alpha1.SeaOtter, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"seaotter\"), name)\n\t}\n\treturn obj.(*v1alpha1.SeaOtter), nil\n}", "func NewRolloutBlockLister(indexer cache.Indexer) RolloutBlockLister {\n\treturn &rolloutBlockLister{indexer: indexer}\n}", "func (s Store) GetBlock (hash string) (*types.FullSignedBlock, error) {\r\n\t// Open badger\r\n\tstor, err := badger.Open(badger.DefaultOptions(s.StorFileLocation))\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tdefer stor.Close()\r\n\r\n\tvar block types.FullSignedBlock\r\n\terr = stor.Update(func(txn *badger.Txn) error {\r\n\t\tbytes, err := readStringIndex (txn, hash, HashKeyPrefix)\r\n\t\tif err != nil{\r\n\t\t\treturn err\r\n\t\t}\r\n\t\terr = json.Unmarshal(bytes, &block)\r\n\r\n\t\treturn err\r\n\t})\r\n\r\n\treturn &block, err\r\n}", "func (s sensuAssetNamespaceLister) Get(name string) (*v1beta1.SensuAsset, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"sensuasset\"), name)\n\t}\n\treturn obj.(*v1beta1.SensuAsset), nil\n}", "func (s cloudformationNamespaceLister) Get(name string) (*v1alpha1.Cloudformation, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"cloudformation\"), name)\n\t}\n\treturn obj.(*v1alpha1.Cloudformation), nil\n}", "func (s knativeEventingNamespaceLister) Get(name string) (*v1beta1.KnativeEventing, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"knativeeventing\"), name)\n\t}\n\treturn obj.(*v1beta1.KnativeEventing), nil\n}", "func (s routeClaimNamespaceLister) Get(name string) (*v1alpha1.RouteClaim, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"routeclaim\"), name)\n\t}\n\treturn obj.(*v1alpha1.RouteClaim), nil\n}", "func (s vulnerabilityNamespaceLister) Get(name string) (*v1alpha1.Vulnerability, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"vulnerability\"), name)\n\t}\n\treturn obj.(*v1alpha1.Vulnerability), nil\n}", "func (s podUnavailableBudgetNamespaceLister) Get(name string) (*v1alpha1.PodUnavailableBudget, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"podunavailablebudget\"), name)\n\t}\n\treturn obj.(*v1alpha1.PodUnavailableBudget), nil\n}", "func (s elasticacheClusterNamespaceLister) Get(name string) (*v1alpha1.ElasticacheCluster, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"elasticachecluster\"), name)\n\t}\n\treturn obj.(*v1alpha1.ElasticacheCluster), nil\n}", "func (b *Bucket) Get(ctx context.Context, name string) (io.ReadCloser, error) {\n\treturn b.getRange(ctx, b.name, name, 0, -1)\n}", "func (s eCRRepositoryNamespaceLister) Get(name string) (*v1alpha1.ECRRepository, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"ecrrepository\"), name)\n\t}\n\treturn obj.(*v1alpha1.ECRRepository), nil\n}", "func (s testRunNamespaceLister) Get(name string) (*v1alpha1.TestRun, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"testrun\"), name)\n\t}\n\treturn obj.(*v1alpha1.TestRun), nil\n}", "func (s computeTargetSSLProxyNamespaceLister) Get(name string) (*v1alpha1.ComputeTargetSSLProxy, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"computetargetsslproxy\"), name)\n\t}\n\treturn obj.(*v1alpha1.ComputeTargetSSLProxy), nil\n}", "func (s *podDisruptionBudgetNamespaceLister) Get(name string) (*policyv1.PodDisruptionBudget, error) {\n\tkey := kcpcache.ToClusterAwareKey(s.clusterName.String(), s.namespace, name)\n\tobj, exists, err := s.indexer.GetByKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(policyv1.Resource(\"PodDisruptionBudget\"), name)\n\t}\n\treturn obj.(*policyv1.PodDisruptionBudget), nil\n}", "func (s gameliftFleetNamespaceLister) Get(name string) (*v1alpha1.GameliftFleet, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"gameliftfleet\"), name)\n\t}\n\treturn obj.(*v1alpha1.GameliftFleet), nil\n}", "func (e *offlineExchange) GetBlock(_ context.Context, k u.Key) (*blocks.Block, error) {\n\treturn e.bs.Get(k)\n}", "func (s democrdNamespaceLister) Get(name string) (*v1.Democrd, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"democrd\"), name)\n\t}\n\treturn obj.(*v1.Democrd), nil\n}", "func (s icecreamNamespaceLister) Get(name string) (*v1alpha1.Icecream, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"icecream\"), name)\n\t}\n\treturn obj.(*v1alpha1.Icecream), nil\n}", "func (s trainingNamespaceLister) Get(name string) (*v1.Training, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"training\"), name)\n\t}\n\treturn obj.(*v1.Training), nil\n}", "func (s keyVaultKeyNamespaceLister) Get(name string) (*v1alpha1.KeyVaultKey, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"keyvaultkey\"), name)\n\t}\n\treturn obj.(*v1alpha1.KeyVaultKey), nil\n}", "func (b *Block) Get(input *BlockInput) (*Block, error) {\n\tresp, err := b.c.Request(http.MethodGet, fmt.Sprintf(\"/blocks/%s\", input.ID), new(bytes.Buffer), nil)\n\tif err != nil {\n\t\treturn &Block{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar block *Block\n\terr = json.NewDecoder(resp.Body).Decode(&block)\n\tif err != nil {\n\t\treturn &Block{}, err\n\t}\n\treturn block, nil\n}", "func (itr *BlocksItr) Get() (ledger.QueryResult, error) {\n\tif itr.err != nil {\n\t\treturn nil, itr.err\n\t}\n\treturn &BlockHolder{itr.nextBlockBytes}, nil\n}", "func (s *NamespaceStorage) Get(ctx context.Context, name string) (*types.Namespace, error) {\n\n\tlog.V(logLevel).Debugf(\"storage:etcd:namespace:> get by name: %s\", name)\n\n\tconst filter = `\\b.+` + namespaceStorage + `\\/.+\\/(meta|spec)\\b`\n\n\tif len(name) == 0 {\n\t\terr := errors.New(\"name can not be empty\")\n\t\tlog.V(logLevel).Errorf(\"storage:etcd:namespace:> get by name err: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\n\tclient, destroy, err := getClient(ctx)\n\tif err != nil {\n\t\tlog.V(logLevel).Errorf(\"storage:etcd:namespace:> get by name err: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\tdefer destroy()\n\n\tnamespace := new(types.Namespace)\n\tkey := keyDirCreate(namespaceStorage, name)\n\n\tif err := client.Map(ctx, key, filter, namespace); err != nil {\n\t\tlog.V(logLevel).Errorf(\"storage:etcd:namespace:> get by name err: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\n\treturn namespace, nil\n}", "func (s crdExampleNamespaceLister) Get(name string) (*v1.CrdExample, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"crdexample\"), name)\n\t}\n\treturn obj.(*v1.CrdExample), nil\n}", "func (s awsIamPolicyAttachmentNamespaceLister) Get(name string) (*v1.AwsIamPolicyAttachment, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"awsiampolicyattachment\"), name)\n\t}\n\treturn obj.(*v1.AwsIamPolicyAttachment), nil\n}", "func (s scyllaDBMonitoringNamespaceLister) Get(name string) (*v1alpha1.ScyllaDBMonitoring, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"scylladbmonitoring\"), name)\n\t}\n\treturn obj.(*v1alpha1.ScyllaDBMonitoring), nil\n}", "func (s tagRouteNamespaceLister) Get(name string) (*v1alpha1.TagRoute, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"tagroute\"), name)\n\t}\n\treturn obj.(*v1alpha1.TagRoute), nil\n}", "func (sc *LoanDocContract) Get(ctx contractapi.TransactionContextInterface, key string) (*LoanDocObj, error) {\n\t\n existingObj, err := ctx.GetStub().GetState(key)\n if err != nil {\n return nil, err\n }\n\n if existingObj == nil {\n return nil, fmt.Errorf(\"Cannot read world state pair with key %s. Does not exist\", key)\n }\n\n\tloanDocObj := new(LoanDocObj)\n\tif err := json.Unmarshal(existingObj, loanDocObj); err != nil {\n\t\treturn nil, fmt.Errorf(\"Data retrieved from world state for key %s was not of type LoanDocObj\", key)\n\t}\n return loanDocObj, nil\n}", "func (s dataFactoryDatasetMysqlNamespaceLister) Get(name string) (*v1alpha1.DataFactoryDatasetMysql, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"datafactorydatasetmysql\"), name)\n\t}\n\treturn obj.(*v1alpha1.DataFactoryDatasetMysql), nil\n}", "func (s consumerNamespaceLister) Get(name string) (*arbv1.Consumer, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(arbv1.Resource(\"queue\"), name)\n\t}\n\treturn obj.(*arbv1.Consumer), nil\n}", "func (m *Manager) Get(base int64) *TimestampBuffering {\n\t// m.mutex.Lock()\n\t// defer m.mutex.Unlock()\n\n\t// get now\n\tindex := m.GetCurrentIndex(base)\n\tfmt.Printf(\"get current index :%d\\n\",index)\n\n\n\treturn m.targets[index]\n\n\t// return nil\n}", "func (s bucketRequestNamespaceLister) Get(name string) (*v1alpha1.BucketRequest, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"bucketrequest\"), name)\n\t}\n\treturn obj.(*v1alpha1.BucketRequest), nil\n}", "func (c *BlockCache) Get(height int) *walletrpc.CompactBlock {\n\tc.mutex.RLock()\n\tdefer c.mutex.RUnlock()\n\n\tif height < c.firstBlock || height >= c.nextBlock {\n\t\treturn nil\n\t}\n\tblock := c.readBlock(height)\n\tif block == nil {\n\t\tgo func() {\n\t\t\t// We hold only the read lock, need the exclusive lock.\n\t\t\tc.mutex.Lock()\n\t\t\tc.recoverFromCorruption(height - 10000)\n\t\t\tc.mutex.Unlock()\n\t\t}()\n\t\treturn nil\n\t}\n\treturn block\n}", "func (s hTTPCheckNamespaceLister) Get(name string) (*v1alpha1.HTTPCheck, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"httpcheck\"), name)\n\t}\n\treturn obj.(*v1alpha1.HTTPCheck), nil\n}", "func (s cognitoResourceServerNamespaceLister) Get(name string) (*v1alpha1.CognitoResourceServer, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"cognitoresourceserver\"), name)\n\t}\n\treturn obj.(*v1alpha1.CognitoResourceServer), nil\n}", "func (s tektonListenerNamespaceLister) Get(name string) (*v1alpha1.TektonListener, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"tektonlistener\"), name)\n\t}\n\treturn obj.(*v1alpha1.TektonListener), nil\n}", "func (s oAuthClientNamespaceLister) Get(name string) (*api.OAuthClient, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(api.Resource(\"oauthclient\"), name)\n\t}\n\treturn obj.(*api.OAuthClient), nil\n}", "func (s recoveryServicesProtectionContainerNamespaceLister) Get(name string) (*v1alpha1.RecoveryServicesProtectionContainer, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"recoveryservicesprotectioncontainer\"), name)\n\t}\n\treturn obj.(*v1alpha1.RecoveryServicesProtectionContainer), nil\n}", "func (s salesforceSourceNamespaceLister) Get(name string) (*v1alpha1.SalesforceSource, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"salesforcesource\"), name)\n\t}\n\treturn obj.(*v1alpha1.SalesforceSource), nil\n}", "func (s pipelineResourceNamespaceLister) Get(name string) (*v1alpha1.PipelineResource, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"pipelineresource\"), name)\n\t}\n\treturn obj.(*v1alpha1.PipelineResource), nil\n}", "func (s messagingInfrastructureNamespaceLister) Get(name string) (*v1.MessagingInfrastructure, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"messaginginfrastructure\"), name)\n\t}\n\treturn obj.(*v1.MessagingInfrastructure), nil\n}", "func (s trialNamespaceLister) Get(name string) (*v1beta1.Trial, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"trial\"), name)\n\t}\n\treturn obj.(*v1beta1.Trial), nil\n}", "func (s clientViewNamespaceLister) Get(name string) (*v1alpha.ClientView, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha.Resource(\"clientview\"), name)\n\t}\n\treturn obj.(*v1alpha.ClientView), nil\n}", "func (c *Cache) GetBlock(k Key) Block {\n\tidx := uint64(0)\n\tif len(c.shards) > 1 {\n\t\th := k.hashUint64()\n\t\tidx = h % uint64(len(c.shards))\n\t}\n\tshard := c.shards[idx]\n\treturn shard.GetBlock(k)\n}", "func (s storageBucketNamespaceLister) Get(name string) (*v1beta1.StorageBucket, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"storagebucket\"), name)\n\t}\n\treturn obj.(*v1beta1.StorageBucket), nil\n}", "func (s proxyRouteNamespaceLister) Get(name string) (*v1alpha1.ProxyRoute, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"proxyroute\"), name)\n\t}\n\treturn obj.(*v1alpha1.ProxyRoute), nil\n}", "func (sbc *SyncBlockChain) Get(Height int32) []Block {\n\tsbc.Mux.Lock()\n\tdefer sbc.Mux.Unlock()\n\tif val, ok := sbc.BC.Chain[Height]; ok {\n\t\treturn val\n\t}\n\treturn nil\n}", "func (s baremetalMachineProviderConfigNamespaceLister) Get(name string) (*v1alpha1.BaremetalMachineProviderConfig, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"baremetalmachineproviderconfig\"), name)\n\t}\n\treturn obj.(*v1alpha1.BaremetalMachineProviderConfig), nil\n}", "func (h *Handler) GetByName(name string) (*corev1.Namespace, error) {\n\treturn h.clientset.CoreV1().Namespaces().Get(h.ctx, name, h.Options.GetOptions)\n}", "func (s dynamoDBNamespaceLister) Get(name string) (*v1alpha1.DynamoDB, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"dynamodb\"), name)\n\t}\n\treturn obj.(*v1alpha1.DynamoDB), nil\n}", "func (s eventProviderNamespaceLister) Get(name string) (*v1alpha1.EventProvider, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"eventprovider\"), name)\n\t}\n\treturn obj.(*v1alpha1.EventProvider), nil\n}", "func (b *AbstractBaseEntity) GetBlock(parent string) (string, error) {\n\tparent = `(?m)^` + parent + `$`\n\treturn b.node.GetSection(parent, \"running-config\")\n}", "func (s computeSSLCertificateNamespaceLister) Get(name string) (*v1alpha1.ComputeSSLCertificate, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"computesslcertificate\"), name)\n\t}\n\treturn obj.(*v1alpha1.ComputeSSLCertificate), nil\n}", "func (s *customResourceDefinitionLister) Get(name string) (*v1.CustomResourceDefinition, error) {\n\tobj, exists, err := s.indexer.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"customresourcedefinition\"), name)\n\t}\n\treturn obj.(*v1.CustomResourceDefinition), nil\n}", "func (s iotPolicyNamespaceLister) Get(name string) (*v1alpha1.IotPolicy, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"iotpolicy\"), name)\n\t}\n\treturn obj.(*v1alpha1.IotPolicy), nil\n}", "func (b *Bucket) Get(ctx context.Context, name string) (io.ReadCloser, error) {\n\treturn b.bkt.Object(name).NewReader(ctx)\n}", "func (s elasticBeanstalkConfigurationTemplateNamespaceLister) Get(name string) (*v1alpha1.ElasticBeanstalkConfigurationTemplate, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"elasticbeanstalkconfigurationtemplate\"), name)\n\t}\n\treturn obj.(*v1alpha1.ElasticBeanstalkConfigurationTemplate), nil\n}", "func (s databaseClusterNamespaceLister) Get(name string) (*v1alpha1.DatabaseCluster, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"databasecluster\"), name)\n\t}\n\treturn obj.(*v1alpha1.DatabaseCluster), nil\n}", "func (s awsApiGatewayBasePathMappingNamespaceLister) Get(name string) (*v1.AwsApiGatewayBasePathMapping, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"awsapigatewaybasepathmapping\"), name)\n\t}\n\treturn obj.(*v1.AwsApiGatewayBasePathMapping), nil\n}", "func (c *Cache) getBlock(aoffset int64, locked bool) *cacheBlock {\n\tif !locked {\n\t\tc.mu.Lock()\n\t\tdefer c.mu.Unlock()\n\t}\n\n\tif blk, ok := c.blocks[aoffset]; ok {\n\t\tc.lru.MoveToFront(blk.lru)\n\t\treturn blk\n\t}\n\n\treturn nil\n}", "func (s previewNamespaceLister) Get(name string) (*v1alpha1.Preview, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"preview\"), name)\n\t}\n\treturn obj.(*v1alpha1.Preview), nil\n}", "func (s *Index) Get() IndexSnapshot {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\tii := IndexSnapshot{\n\t\tTipSetKey: s.index.TipSetKey,\n\t\tMiners: make(map[string]Slashes, len(s.index.Miners)),\n\t}\n\tfor addr, v := range s.index.Miners {\n\t\thistory := make([]uint64, len(v.Epochs))\n\t\tcopy(history, v.Epochs)\n\t\tii.Miners[addr] = Slashes{\n\t\t\tEpochs: history,\n\t\t}\n\t}\n\treturn ii\n}", "func (s ingressListenerNamespaceLister) Get(name string) (*v1alpha1.IngressListener, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"ingresslistener\"), name)\n\t}\n\treturn obj.(*v1alpha1.IngressListener), nil\n}", "func (s traitNamespaceLister) Get(name string) (*v1alpha1.Trait, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"trait\"), name)\n\t}\n\treturn obj.(*v1alpha1.Trait), nil\n}", "func (s redisTriggerNamespaceLister) Get(name string) (*v1beta1.RedisTrigger, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"redistrigger\"), name)\n\t}\n\treturn obj.(*v1beta1.RedisTrigger), nil\n}", "func (s horusecManagerNamespaceLister) Get(name string) (*v1alpha1.HorusecManager, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"horusecmanager\"), name)\n\t}\n\treturn obj.(*v1alpha1.HorusecManager), nil\n}", "func (s *BlocksService) Get(ctx context.Context, id string) (*GetBlock, *http.Response, error) {\n\tquery := &BlockIdQuery{Id: id}\n\n\tvar responseStruct *GetBlock\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"blocks/get\", query, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (s marketplaceAgreementNamespaceLister) Get(name string) (*v1alpha1.MarketplaceAgreement, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"marketplaceagreement\"), name)\n\t}\n\treturn obj.(*v1alpha1.MarketplaceAgreement), nil\n}", "func (s deepOneNamespaceLister) Get(name string) (*v1.DeepOne, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1.Resource(\"deepone\"), name)\n\t}\n\treturn obj.(*v1.DeepOne), nil\n}", "func (c *releaseClient) Get(name string) (*Release, error) {\n\tlist, err := c.config.Releases.List(func(r *release.Release) bool {\n\t\treturn r.Namespace == c.config.Namespace() && r.Name == name\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t} else if len(list) == 0 {\n\t\treturn nil, errors.New(\"release not found\")\n\t} else if len(list) > 1 {\n\t\treturn nil, errors.New(\"release is ambiguous\")\n\t}\n\treturn getRelease(c.config, list[0])\n}", "func (i IndexFile) Get(name, version string) (*bundle.Bundle, error) {\n\tvs, ok := i.Entries[name]\n\tif !ok {\n\t\treturn nil, ErrNoBundleName\n\t}\n\tif len(vs) == 0 {\n\t\treturn nil, ErrNoBundleVersion\n\t}\n\n\tvar constraint *semver.Constraints\n\tif len(version) == 0 {\n\t\tconstraint, _ = semver.NewConstraint(\"*\")\n\t} else {\n\t\tvar err error\n\t\tconstraint, err = semver.NewConstraint(version)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tfor _, ver := range vs {\n\t\ttest, err := semver.NewVersion(ver.Version)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif constraint.Check(test) {\n\t\t\treturn ver, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"No bundle version found for %s-%s\", name, version)\n}", "func (s *rolloutBlockLister) RolloutBlocks(namespace string) RolloutBlockNamespaceLister {\n\treturn rolloutBlockNamespaceLister{indexer: s.indexer, namespace: namespace}\n}", "func (s rBACDefinitionNamespaceLister) Get(name string) (*v1beta1.RBACDefinition, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"rbacdefinition\"), name)\n\t}\n\treturn obj.(*v1beta1.RBACDefinition), nil\n}", "func (r *Wrapper) Get(name string) any {\n\tval, ok := r.Lookup(name)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn val\n}", "func (t TokensWrapper) GetItem(itemName string) TokensItem {\n\t// find the item by name in content\n\tfor _, item := range t.Content {\n\t\tif item.Name == itemName {\n\t\t\treturn item\n\t\t}\n\t}\n\tpanic(\"No item found\")\n}", "func (s passwordNamespaceLister) Get(name string) (*v1alpha1.Password, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"password\"), name)\n\t}\n\treturn obj.(*v1alpha1.Password), nil\n}" ]
[ "0.6030591", "0.59331393", "0.5855316", "0.5818759", "0.5671234", "0.56690836", "0.5618589", "0.55901265", "0.5538037", "0.55035794", "0.548112", "0.54450256", "0.5436534", "0.54056436", "0.539699", "0.53958815", "0.53886515", "0.5377897", "0.5372501", "0.53640854", "0.5357762", "0.5344105", "0.53276235", "0.53193927", "0.53012586", "0.53006095", "0.5300465", "0.52989495", "0.5297278", "0.52763087", "0.5264586", "0.5255019", "0.525478", "0.5251468", "0.52328426", "0.5229231", "0.52226484", "0.5211426", "0.5205007", "0.51946324", "0.5174489", "0.51598877", "0.51497984", "0.51446956", "0.51446134", "0.5138133", "0.51276106", "0.51200664", "0.5098904", "0.50793546", "0.507923", "0.5072328", "0.50701433", "0.50588965", "0.50491536", "0.50416297", "0.503744", "0.50307083", "0.50288147", "0.5014426", "0.5013779", "0.5012299", "0.50084287", "0.50067544", "0.50029355", "0.4997747", "0.49892905", "0.4982563", "0.49793637", "0.49771762", "0.49555033", "0.49526963", "0.494825", "0.49412373", "0.4928392", "0.49261126", "0.49250874", "0.49233764", "0.49201262", "0.4916522", "0.49064025", "0.49057132", "0.48977345", "0.4882732", "0.48796386", "0.48794276", "0.4869863", "0.48592183", "0.48477304", "0.48390046", "0.48388767", "0.48290822", "0.48269212", "0.48169485", "0.48142573", "0.48138276", "0.48018044", "0.47983798", "0.4797203", "0.4783067" ]
0.80333996
0
AddCopy creates a new QuarksSecrets controller to watch for the user defined secrets.
func AddCopy(ctx context.Context, config *config.Config, mgr manager.Manager) error { ctx = ctxlog.NewContextWithRecorder(ctx, "copy-reconciler", mgr.GetEventRecorderFor("copy-recorder")) log := ctxlog.ExtractLogger(ctx) r := NewCopyReconciler(ctx, config, mgr, credsgen.NewInMemoryGenerator(log), controllerutil.SetControllerReference) c, err := controller.New("copy-controller", mgr, controller.Options{ Reconciler: r, MaxConcurrentReconciles: config.MaxQuarksSecretWorkers, }) if err != nil { return errors.Wrap(err, "Adding copy controller to manager failed.") } nsPred := newNSPredicate(ctx, mgr.GetClient(), config.MonitoredID) // Watch for changes to the copied status of QuarksSecrets p := predicate.Funcs{ CreateFunc: func(e event.CreateEvent) bool { return false }, DeleteFunc: func(e event.DeleteEvent) bool { return false }, GenericFunc: func(e event.GenericEvent) bool { return false }, UpdateFunc: func(e event.UpdateEvent) bool { n := e.ObjectNew.(*qsv1a1.QuarksSecret) if n.Status.Copied != nil { ctxlog.Debugf(ctx, "Skipping QuarksSecret '%s', if copy status '%v' is true", n.Name, *n.Status.Copied) return !(*n.Status.Copied) } return true }, } err = c.Watch(&source.Kind{Type: &qsv1a1.QuarksSecret{}}, &handler.EnqueueRequestForObject{}, nsPred, p) if err != nil { return errors.Wrapf(err, "Watching quarks secrets failed in copy controller.") } // Watch for changes to user created secrets p = predicate.Funcs{ CreateFunc: func(e event.CreateEvent) bool { return false }, DeleteFunc: func(e event.DeleteEvent) bool { return false }, GenericFunc: func(e event.GenericEvent) bool { return false }, UpdateFunc: func(e event.UpdateEvent) bool { n := e.ObjectNew.(*corev1.Secret) o := e.ObjectOld.(*corev1.Secret) shouldProcessReconcile := isUserCreatedSecret(n) if reflect.DeepEqual(n.Data, o.Data) && reflect.DeepEqual(n.Labels, o.Labels) && reflect.DeepEqual(n.Annotations, o.Annotations) { return false } return shouldProcessReconcile }, } err = c.Watch(&source.Kind{Type: &corev1.Secret{}}, handler.EnqueueRequestsFromMapFunc( func(a crc.Object) []reconcile.Request { secret := a.(*corev1.Secret) if skip.Reconciles(ctx, mgr.GetClient(), secret) { return []reconcile.Request{} } reconciles, err := listQuarksSecretsReconciles(ctx, mgr.GetClient(), secret, secret.Namespace) if err != nil { ctxlog.Errorf(ctx, "Failed to calculate reconciles for secret '%s/%s': %v", secret.Namespace, secret.Name, err) } if len(reconciles) > 0 { return reconciles } return reconciles }), nsPred, p) if err != nil { return errors.Wrapf(err, "Watching user defined secrets failed in copy controller.") } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\n \t// minimumRefreshRate = os.Getenv(\"MINIMUM_REFRESH_RATE\")\n\n\t// Create a new controller\n\tc, err := controller.New(\"vaultsecret-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource VaultSecret\n\terr = c.Watch(&source.Kind{Type: &crdv1alpha1.VaultSecret{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO(user): Modify this to be the types you create that are owned by the primary resource\n\t// Watch for changes to secondary resource Secrets and requeue the owner VaultSecret\n\terr = c.Watch(&source.Kind{Type: &corev1.Secret{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &crdv1alpha1.VaultSecret{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func copySecret(ctx context.Context, src, dst kubernetes.Interface, namespace, name string) error {\n\tsecret, err := src.CoreV1().Secrets(namespace).Get(ctx, name, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"failed retrieving secret: %s from source cluster: %w\", name, err)\n\t}\n\t_, err = dst.CoreV1().Secrets(namespace).Create(ctx, &corev1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: secret.Labels,\n\t\t},\n\t\tData: secret.Data,\n\t}, metav1.CreateOptions{})\n\tif !errors.IsAlreadyExists(err) && err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func CopySecret(corev1Input clientcorev1.CoreV1Interface, srcNS string, srcSecretName string, tgtNS string, svcAccount string) (*corev1.Secret, error) {\n\treturn CopySecretWithName(corev1Input,\n\t\tsrcNS,\n\t\tsrcSecretName,\n\t\ttgtNS,\n\t\tsrcSecretName, /* Use same target name as source by default */\n\t\tsvcAccount)\n}", "func (c *Client) Copy(pod *k8sv1.Pod, container, containerPath, localPath string, exclude []string) error {\n\treturn nil\n}", "func CopySecretWithName(corev1Input clientcorev1.CoreV1Interface, srcNS, srcSecretName, tgtNS, tgtSecretName, svcAccount string) (*corev1.Secret, error) {\n\ttgtNamespaceSvcAcct := corev1Input.ServiceAccounts(tgtNS)\n\tsrcSecrets := corev1Input.Secrets(srcNS)\n\ttgtNamespaceSecrets := corev1Input.Secrets(tgtNS)\n\n\t// First try to find the secret we're supposed to copy\n\tsrcSecret, err := srcSecrets.Get(context.Background(), srcSecretName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// check for nil source secret\n\tif srcSecret == nil {\n\t\treturn nil, errors.New(\"error copying secret; there is no error but secret is nil\")\n\t}\n\n\t// Found the secret, so now make a copy in our new namespace\n\tnewSecret, err := tgtNamespaceSecrets.Create(\n\t\tcontext.Background(),\n\t\t&corev1.Secret{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: tgtSecretName,\n\t\t\t},\n\t\t\tData: srcSecret.Data,\n\t\t\tType: srcSecret.Type,\n\t\t},\n\t\tmetav1.CreateOptions{})\n\n\t// If the secret already exists then that's ok - may have already been created\n\tif err != nil && !apierrs.IsAlreadyExists(err) {\n\t\treturn nil, fmt.Errorf(\"error copying the Secret: %s\", err)\n\t}\n\n\ttgtSvcAccount, err := tgtNamespaceSvcAcct.Get(context.Background(), svcAccount, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error getting service account %s: %w\", svcAccount, err)\n\t}\n\n\tfor _, secret := range tgtSvcAccount.ImagePullSecrets {\n\t\tif secret.Name == tgtSecretName {\n\t\t\treturn newSecret, nil\n\t\t}\n\t}\n\t// Prevent overwriting existing imagePullSecrets\n\tpatch := `[{\"op\":\"add\",\"path\":\"/imagePullSecrets/-\",\"value\":{\"name\":\"` + tgtSecretName + `\"}}]`\n\tif len(tgtSvcAccount.ImagePullSecrets) == 0 {\n\t\tpatch = `[{\"op\":\"add\",\"path\":\"/imagePullSecrets\",\"value\":[{\"name\":\"` + tgtSecretName + `\"}]}]`\n\t}\n\t_, err = tgtNamespaceSvcAcct.Patch(context.Background(), svcAccount, types.JSONPatchType,\n\t\t[]byte(patch), metav1.PatchOptions{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"patch failed on NS/SA (%s/%s): %w\",\n\t\t\ttgtNS, svcAccount, err)\n\t}\n\treturn newSecret, nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(ControllerName, mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource KeycloakClient\n\terr = c.Watch(&source.Kind{Type: &kc.KeycloakClient{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Make sure to watch the credential secrets\n\terr = c.Watch(&source.Kind{Type: &corev1.Secret{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &kc.KeycloakClient{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func newSecrets(c *APIV1Client) *secrets {\n\treturn &secrets{\n\t\tclient: c.RESTClient(),\n\t}\n}", "func (c *KubeTestPlatform) AddSecrets(secrets []kube.SecretDescription) error {\n\tif c.KubeClient == nil {\n\t\treturn fmt.Errorf(\"kubernetes cluster needs to be setup\")\n\t}\n\n\tfor _, secret := range secrets {\n\t\tc.Secrets.Add(kube.NewSecret(c.KubeClient, secret.Namespace, secret.Name, secret.Data))\n\t}\n\n\t// setup secret resources\n\tif err := c.Secrets.setup(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"copybird-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource Copybird\n\terr = c.Watch(&source.Kind{Type: &v1alpha1.Copybird{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO(user): Modify this to be the types you create that are owned by the primary resource\n\t// Watch for changes to secondary resource Pods and requeue the owner Copybird\n\terr = c.Watch(&source.Kind{Type: &v1beta1.CronJob{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &v1alpha1.Copybird{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *SecretsResource) Create(request *http.Request) (rest.Resource, error) {\n\tvar secretCurrent api.SecretCurrent\n\n\tdefer request.Body.Close()\n\tdecoder := json.NewDecoder(request.Body)\n\tif err := decoder.Decode(&secretCurrent); err != nil {\n\t\treturn nil, rest.HTTPBadRequest.WithDetails(err.Error())\n\t}\n\tif secretCurrent.Current == nil {\n\t\treturn nil, rest.HTTPBadRequest.WithDetails(\"No current secret\")\n\t}\n\n\tif err := r.secrets.Add(request.Context(), secretCurrent.ID, secretCurrent.Type, *secretCurrent.Current); err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewSecretResource(r.secrets, secretCurrent.ID, r.logger), nil\n}", "func (l CMD) AddSecret(secret string) Logger {\n\tl.secrets = append(l.secrets, secret)\n\treturn l\n}", "func AddClientSecret(ctx context.Context, objID string) (autorest.Response, error) {\n\tappClient := getApplicationsClient()\n\treturn appClient.UpdatePasswordCredentials(\n\t\tctx,\n\t\tobjID,\n\t\tgraphrbac.PasswordCredentialsUpdateParameters{\n\t\t\tValue: &[]graphrbac.PasswordCredential{\n\t\t\t\t{\n\t\t\t\t\tStartDate: &date.Time{time.Now()},\n\t\t\t\t\tEndDate: &date.Time{time.Date(2018, time.December, 20, 22, 0, 0, 0, time.UTC)},\n\t\t\t\t\tValue: to.StringPtr(\"052265a2-bdc8-49aa-81bd-ecf7e9fe0c42\"), // this will become the client secret! Record this value, there is no way to get it back\n\t\t\t\t\tKeyID: to.StringPtr(\"08023993-9209-4580-9d4a-e060b44a64b8\"),\n\t\t\t\t},\n\t\t\t},\n\t\t})\n}", "func NewSecretReplicator(client kubernetes.Interface, options ReplicatorOptions, resyncPeriod time.Duration) Replicator {\n\trepl := ObjectReplicator{\n\t\tReplicatorProps: NewReplicatorProps(client, \"secret\", options),\n\t\tReplicatorActions: _secretActions,\n\t}\n\tsecrets := client.CoreV1().Secrets(\"\")\n\tlistWatch := cache.ListWatch{\n\t\tListFunc: func(lo metav1.ListOptions) (runtime.Object, error) {\n\t\t\treturn secrets.List(lo)\n\t\t},\n\t\tWatchFunc: secrets.Watch,\n\t}\n\trepl.InitStores(&listWatch, &v1.Secret{}, resyncPeriod)\n\treturn &repl\n}", "func Create(ctx context.Context, dev *model.Dev, c *kubernetes.Clientset, s *syncthing.Syncthing) error {\n\tsecretName := GetSecretName(dev)\n\n\tsct, err := Get(ctx, secretName, dev.Namespace, c)\n\tif err != nil && !strings.Contains(err.Error(), \"not found\") {\n\t\treturn fmt.Errorf(\"error getting kubernetes secret: %s\", err)\n\t}\n\n\tconfig, err := getConfigXML(s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error generating syncthing configuration: %s\", err)\n\t}\n\tdata := &v1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: secretName,\n\t\t\tLabels: map[string]string{\n\t\t\t\tconstants.DevLabel: \"true\",\n\t\t\t},\n\t\t},\n\t\tType: v1.SecretTypeOpaque,\n\t\tData: map[string][]byte{\n\t\t\t\"config.xml\": config,\n\t\t\t\"cert.pem\": []byte(certPEM),\n\t\t\t\"key.pem\": []byte(keyPEM),\n\t\t},\n\t}\n\n\tidx := 0\n\tfor _, s := range dev.Secrets {\n\t\tcontent, err := os.ReadFile(s.LocalPath)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error reading secret '%s': %s\", s.LocalPath, err)\n\t\t}\n\t\tif strings.Contains(s.GetKeyName(), \"stignore\") {\n\t\t\tidx++\n\t\t\tdata.Data[fmt.Sprintf(\"%s-%d\", s.GetKeyName(), idx)] = content\n\t\t} else {\n\t\t\tdata.Data[s.GetKeyName()] = content\n\t\t}\n\n\t}\n\n\tif sct.Name == \"\" {\n\t\t_, err := c.CoreV1().Secrets(dev.Namespace).Create(ctx, data, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error creating kubernetes sync secret: %s\", err)\n\t\t}\n\n\t\toktetoLog.Infof(\"created okteto secret '%s'\", secretName)\n\t} else {\n\t\t_, err := c.CoreV1().Secrets(dev.Namespace).Update(ctx, data, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error updating kubernetes okteto secret: %s\", err)\n\t\t}\n\t\toktetoLog.Infof(\"updated okteto secret '%s'\", secretName)\n\t}\n\treturn nil\n}", "func NewSecretController(informerFactory informers.SharedInformerFactory, syncrule helpers.SyncRule, local bool) *SecretController {\n\tsecretInformer := informerFactory.Core().V1().Secrets()\n\n\tc := &SecretController{\n\t\tinformerFactory: informerFactory,\n\t\tsecretInformer: secretInformer,\n\t\tsyncrule: syncrule,\n\t}\n\tif local {\n\t\tsecretInformer.Informer().AddEventHandler(\n\t\t\t// Your custom resource event handlers.\n\t\t\tcache.ResourceEventHandlerFuncs{\n\t\t\t\t// Called on creation\n\t\t\t\tAddFunc: c.localSecretAdd,\n\t\t\t\t// Called on resource update and every resyncPeriod on existing resources.\n\t\t\t\tUpdateFunc: c.localSecretUpdate,\n\t\t\t\t// Called on resource deletion.\n\t\t\t\tDeleteFunc: c.localSecretDelete,\n\t\t\t},\n\t\t)\n\t\treturn c\n\t}\n\tsecretInformer.Informer().AddEventHandler(\n\t\t// Your custom resource event handlers.\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\t// Called on creation\n\t\t\tAddFunc: c.secretAdd,\n\t\t\t// Called on resource update and every resyncPeriod on existing resources.\n\t\t\tUpdateFunc: c.secretUpdate,\n\t\t\t// Called on resource deletion.\n\t\t\tDeleteFunc: c.secretDelete,\n\t\t},\n\t)\n\treturn c\n}", "func (in *Secret) DeepCopy() *Secret {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Secret)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (api *APIClient) AddSecrets(vaultName string, secrets []Secret) error {\n\taddVaultSecretsRequest := graphql.NewRequest(addVaultSecretsRequestString)\n\taddVaultSecretsInput := AddVaultSecretsInput{\n\t\tAffiliationName: api.Affiliation,\n\t\tSecrets: secrets,\n\t\tVaultName: vaultName,\n\t}\n\taddVaultSecretsRequest.Var(\"addVaultSecretsInput\", addVaultSecretsInput)\n\n\tvar addVaultSecretsResponse AddVaultSecretsResponse\n\tif err := api.RunGraphQlMutation(addVaultSecretsRequest, &addVaultSecretsResponse); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewSecretWatcher(kubeClient *unversioned.Client, configmap string, cmdRunner CmdRunner, done <-chan bool) Watcher {\n\tnamespace, name := parseNamespaceName(configmap)\n\tcmw := SecretWatcher{\n\t\tname: name,\n\t\tnamespace: namespace,\n\t\tkubeClient: kubeClient,\n\t\tcmdRunner: cmdRunner,\n\t\tdone: done,\n\t}\n\n\tcmw.watch()\n\treturn cmw\n}", "func addSecretsVolume(pod corev1.Pod) (patch []patchOperation) {\n\n\tvolume := corev1.Volume{\n\t\tName: \"secrets\",\n\t\tVolumeSource: corev1.VolumeSource{\n\t\t\tEmptyDir: &corev1.EmptyDirVolumeSource{Medium: corev1.StorageMediumMemory},\n\t\t},\n\t}\n\n\tpath := \"/spec/volumes\"\n\tvar value interface{}\n\n\tif len(pod.Spec.Volumes) != 0 {\n\t\tpath = path + \"/-\"\n\t\tvalue = volume\n\t} else {\n\t\tvalue = []corev1.Volume{volume}\n\t}\n\n\tpatch = append(patch, patchOperation{\n\t\tOp: \"add\",\n\t\tPath: path,\n\t\tValue: value,\n\t})\n\n\treturn\n}", "func (c Clipboard) Add(s string) {\n\tc.Storage.Save(s)\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(controllerName, mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to Instance\n\terr = c.Watch(&source.Kind{Type: &bucketv1alpha1.Bucket{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Copy(data string) {\n\tif err := clipboard.WriteAll(data); err != nil {\n\t\tfmt.Println(\"There was a problem copying to the computers local clipboard\")\n\t}\n\n\tdefer GenerateNewTokenOnError(func() {\n\t\tCopy(data)\n\t})\n\ttoken := RetrieveToken()\n\tfireboardtools.SetClipboard(token, data)\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(controllerName, mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to UnitedDeployment\n\terr = c.Watch(&source.Kind{Type: &appsv1alpha1.UnitedDeployment{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.Watch(&source.Kind{Type: &appsv1.StatefulSet{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &appsv1alpha1.UnitedDeployment{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *Registry) Copy() *Registry {\n\tplugins := make(map[string]interface{})\n\tfor k, v := range r.plugins {\n\t\tplugins[k] = v\n\t}\n\n\tproviders := make(map[string]interface{})\n\tfor k, v := range r.providers {\n\t\tproviders[k] = v\n\t}\n\n\treturn &Registry{\n\t\tplugins: plugins,\n\t\tproviders: providers,\n\t}\n}", "func (op *Operator) initSecretWatcher() cache.Controller {\n\tlw := &cache.ListWatch{\n\t\tListFunc: func(opts metav1.ListOptions) (runtime.Object, error) {\n\t\t\treturn op.KubeClient.CoreV1().Secrets(op.Opt.WatchNamespace()).List(metav1.ListOptions{})\n\t\t},\n\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\treturn op.KubeClient.CoreV1().Secrets(op.Opt.WatchNamespace()).Watch(metav1.ListOptions{})\n\t\t},\n\t}\n\t_, informer := cache.NewIndexerInformer(lw,\n\t\t&core.Secret{},\n\t\top.Opt.ResyncPeriod,\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\t\tif oldSecret, ok := old.(*core.Secret); ok {\n\t\t\t\t\tif newSecret, ok := new.(*core.Secret); ok {\n\t\t\t\t\t\tif reflect.DeepEqual(oldSecret.Data, newSecret.Data) {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tctx := etx.Background()\n\t\t\t\t\t\tlogger := log.New(ctx)\n\t\t\t\t\t\t// Secret DataChanged. We need to list all Ingress and check which of\n\t\t\t\t\t\t// those ingress uses this secret as basic auth secret.\n\t\t\t\t\t\titems, err := op.listIngresses()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Errorln(err)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor i := range items {\n\t\t\t\t\t\t\tengress := &items[i]\n\t\t\t\t\t\t\tif engress.ShouldHandleIngress(op.Opt.IngressClass) || op.IngressServiceUsesAuthSecret(engress, newSecret) {\n\t\t\t\t\t\t\t\tif engress.UsesAuthSecret(newSecret.Namespace, newSecret.Name) {\n\t\t\t\t\t\t\t\t\tctrl := ingress.NewController(ctx, op.KubeClient, op.CRDClient, op.VoyagerClient, op.PromClient, op.ServiceLister, op.EndpointsLister, op.Opt, engress)\n\t\t\t\t\t\t\t\t\tif ctrl.IsExists() {\n\t\t\t\t\t\t\t\t\t\tcfgErr := ctrl.Update(0, nil)\n\t\t\t\t\t\t\t\t\t\tif cfgErr != nil {\n\t\t\t\t\t\t\t\t\t\t\tlogger.Infof(\"Failed to update offshoots of %s Ingress %s/%s. Reason: %s\", engress.APISchema(), engress.Namespace, engress.Name, cfgErr)\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tctrl.Create()\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tcache.Indexers{},\n\t)\n\treturn informer\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(controllerName, mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource Policy\n\terr = c.Watch(&source.Kind{Type: &policiesv1.Policy{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Create(c *client.Client, i *Instance) error {\n\tsecretType, err := detectSecretType(i.Type)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsecret := v1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: i.Name,\n\t\t\tNamespace: i.Namespace,\n\t\t},\n\t\tData: map[string][]byte{\n\t\t\ti.Key: []byte(i.Value),\n\t\t},\n\t\tType: secretType,\n\t}\n\t_, err = c.Clientset.CoreV1().Secrets(i.Namespace).Create(\n\t\tcontext.TODO(),\n\t\t&secret,\n\t\tmetav1.CreateOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func ApplySecrets(rclient client.Client, secret *corev1.Secret) (string, error) {\n\tvar operation string\n\t// apply\n\tfound := &corev1.Secret{}\n\tif err := rclient.Get(context.TODO(), types.NamespacedName{Name: secret.Name, Namespace: secret.Namespace}, found); err != nil {\n\t\tif k8sErrors.IsNotFound(err) {\n\t\t\t// create\n\t\t\tif err := rclient.Create(context.TODO(), secret); err != nil {\n\t\t\t\treturn \"\", errors.WithStack(err)\n\t\t\t}\n\t\t\toperation = \"Created\"\n\t\t} else {\n\t\t\treturn \"\", errors.WithStack(err)\n\t\t}\n\n\t} else {\n\t\t//secret found, check if we need to update\n\t\tif !reflect.DeepEqual(secret.Data, found.Data) {\n\t\t\tif err := rclient.Update(context.TODO(), secret); err != nil {\n\t\t\t\treturn \"\", errors.WithStack(err)\n\t\t\t}\n\t\t\toperation = \"Updated\"\n\t\t} else {\n\t\t\t//Nothing happened\n\t\t\treturn \"\", nil\n\t\t}\n\n\t}\n\n\treturn operation, nil\n}", "func RegisterSecretsHandlerClient(ctx context.Context, mux *runtime.ServeMux, client SecretsClient) error {\n\n\tmux.Handle(\"POST\", pattern_Secrets_Create_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_Secrets_Create_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_Secrets_Create_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"GET\", pattern_Secrets_Read_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_Secrets_Read_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_Secrets_Read_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"PUT\", pattern_Secrets_Update_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_Secrets_Update_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_Secrets_Update_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"PATCH\", pattern_Secrets_Update_1, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_Secrets_Update_1(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_Secrets_Update_1(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"DELETE\", pattern_Secrets_Delete_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_Secrets_Delete_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_Secrets_Delete_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"GET\", pattern_Secrets_List_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := request_Secrets_List_0(rctx, inboundMarshaler, client, req, pathParams)\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_Secrets_List_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\treturn nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"sawtooth-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource Sawtooth\n\terr = c.Watch(&source.Kind{Type: &sawtoothv1alpha1.Sawtooth{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource Pods and requeue the owner Sawtooth\n\tsrc := &source.Kind{Type: &corev1.Pod{}}\n\tpred := predicate.Funcs{\n\t\tUpdateFunc: func(e event.UpdateEvent) bool {\n\t\t\treturn false\n\t\t},\n\t\tDeleteFunc: func(e event.DeleteEvent) bool {\n\t\t\treturn false\n\t\t},\n\t}\n\terr = c.Watch(src, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &sawtoothv1alpha1.Sawtooth{},\n\t}, pred)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func newSecretForCR(cr *crdv1alpha1.VaultSecret) *corev1.Secret {\n\n\tsecret := vault.GetSecret(cr.Spec.Path)\n\n\tcr.Status.RequestId = secret.RequestID\n\n\tvar secretMap map[string][]byte\n\tsecretMap = make(map[string][]byte)\n\tfor key, secret := range secret.Data {\n\t\tsecretMap[key] = []byte(secret.(string))\n\t}\n\n\tlabels := map[string]string{\n\t\t\"app\": cr.Name,\n\t}\n\treturn &corev1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tType: \"Opaque\",\n\t\tData: secretMap,\n\t}\n}", "func NewSecretController(ca ca.CertificateAuthority, certTTL time.Duration, identityDomain string,\n\tgracePeriodRatio float32, minGracePeriod time.Duration, dualUse bool,\n\tcore corev1.CoreV1Interface, forCA bool, namespace string, dnsNames map[string]DNSNameEntry) (*SecretController, error) {\n\n\tif gracePeriodRatio < 0 || gracePeriodRatio > 1 {\n\t\treturn nil, fmt.Errorf(\"grace period ratio %f should be within [0, 1]\", gracePeriodRatio)\n\t}\n\tif gracePeriodRatio < recommendedMinGracePeriodRatio || gracePeriodRatio > recommendedMaxGracePeriodRatio {\n\t\tlog.Warnf(\"grace period ratio %f is out of the recommended window [%.2f, %.2f]\",\n\t\t\tgracePeriodRatio, recommendedMinGracePeriodRatio, recommendedMaxGracePeriodRatio)\n\t}\n\n\tif identityDomain == \"\" {\n\t\tidentityDomain = DefaultIdentityDomain\n\t}\n\n\tc := &SecretController{\n\t\tca: ca,\n\t\tcertTTL: certTTL,\n\t\tidentityDomain: identityDomain,\n\t\tgracePeriodRatio: gracePeriodRatio,\n\t\tminGracePeriod: minGracePeriod,\n\t\tdualUse: dualUse,\n\t\tcore: core,\n\t\tforCA: forCA,\n\t\tdnsNames: dnsNames,\n\t\tmonitoring: newMonitoringMetrics(),\n\t}\n\n\tsaLW := &cache.ListWatch{\n\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\treturn core.ServiceAccounts(namespace).List(options)\n\t\t},\n\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\treturn core.ServiceAccounts(namespace).Watch(options)\n\t\t},\n\t}\n\trehf := cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.saAdded,\n\t\tDeleteFunc: c.saDeleted,\n\t\tUpdateFunc: c.saUpdated,\n\t}\n\tc.saStore, c.saController = cache.NewInformer(saLW, &v1.ServiceAccount{}, time.Minute, rehf)\n\n\tistioSecretSelector := fields.SelectorFromSet(map[string]string{\"type\": IstioSecretType}).String()\n\tscrtLW := &cache.ListWatch{\n\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\toptions.FieldSelector = istioSecretSelector\n\t\t\treturn core.Secrets(namespace).List(options)\n\t\t},\n\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\toptions.FieldSelector = istioSecretSelector\n\t\t\treturn core.Secrets(namespace).Watch(options)\n\t\t},\n\t}\n\tc.scrtStore, c.scrtController =\n\t\tcache.NewInformer(scrtLW, &v1.Secret{}, secretResyncPeriod, cache.ResourceEventHandlerFuncs{\n\t\t\tDeleteFunc: c.scrtDeleted,\n\t\t\tUpdateFunc: c.scrtUpdated,\n\t\t})\n\n\treturn c, nil\n}", "func NewReplicator(client kubernetes.Interface, resyncPeriod time.Duration, allowAll bool) common.Replicator {\n\trepl := Replicator{\n\t\tGenericReplicator: common.NewGenericReplicator(common.ReplicatorConfig{\n\t\t\tKind: \"Secret\",\n\t\t\tObjType: &v1.Secret{},\n\t\t\tAllowAll: allowAll,\n\t\t\tResyncPeriod: resyncPeriod,\n\t\t\tClient: client,\n\t\t\tListFunc: func(lo metav1.ListOptions) (runtime.Object, error) {\n\t\t\t\treturn client.CoreV1().Secrets(\"\").List(context.TODO(), lo)\n\t\t\t},\n\t\t\tWatchFunc: func(lo metav1.ListOptions) (watch.Interface, error) {\n\t\t\t\treturn client.CoreV1().Secrets(\"\").Watch(context.TODO(), lo)\n\t\t\t},\n\t\t}),\n\t}\n\trepl.UpdateFuncs = common.UpdateFuncs{\n\t\tReplicateDataFrom: repl.ReplicateDataFrom,\n\t\tReplicateObjectTo: repl.ReplicateObjectTo,\n\t\tPatchDeleteDependent: repl.PatchDeleteDependent,\n\t\tDeleteReplicatedResource: repl.DeleteReplicatedResource,\n\t}\n\n\treturn &repl\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(controllerName, mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tisAnnotatedSecret := predicate.Funcs{\n\t\tUpdateFunc: func(e event.UpdateEvent) bool {\n\t\t\toldSecret, ok := e.ObjectOld.(*corev1.Secret)\n\t\t\tif !ok {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tnewSecret, ok := e.ObjectNew.(*corev1.Secret)\n\t\t\tif !ok {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif newSecret.Type != util.TLSSecret {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\toldValue, _ := e.MetaOld.GetAnnotations()[certExpiryAlertAnnotation]\n\t\t\tnewValue, _ := e.MetaNew.GetAnnotations()[certExpiryAlertAnnotation]\n\t\t\told := oldValue == \"true\"\n\t\t\tnew := newValue == \"true\"\n\t\t\t// if the content has changed we trigger is the annotation is there\n\t\t\tif !reflect.DeepEqual(newSecret.Data[util.Cert], oldSecret.Data[util.Cert]) {\n\t\t\t\treturn new\n\t\t\t}\n\t\t\t// otherwise we trigger if the annotation has changed\n\t\t\treturn old != new\n\t\t},\n\t\tCreateFunc: func(e event.CreateEvent) bool {\n\t\t\tsecret, ok := e.Object.(*corev1.Secret)\n\t\t\tif !ok {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif secret.Type != util.TLSSecret {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tvalue, _ := e.Meta.GetAnnotations()[certExpiryAlertAnnotation]\n\t\t\treturn value == \"true\"\n\t\t},\n\t}\n\n\t// Watch for changes to primary resource CertExpiryAlert\n\terr = c.Watch(&source.Kind{Type: &corev1.Secret{\n\t\tTypeMeta: v1.TypeMeta{\n\t\t\tKind: \"Secret\",\n\t\t},\n\t}}, &handler.EnqueueRequestForObject{}, isAnnotatedSecret)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"deployment-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource Deployment\n\terr = c.Watch(&source.Kind{Type: &ketiv1.Deployment{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO(user): Modify this to be the types you create that are owned by the primary resource\n\t// Watch for changes to secondary resource Pods and requeue the owner Deployment\n\terr = c.Watch(&source.Kind{Type: &corev1.Pod{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &ketiv1.Deployment{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *secrets) Create(ctx context.Context, secret *v1.Secret,\n\topts metav1.CreateOptions) (result *v1.Secret, err error) {\n\tresult = &v1.Secret{}\n\terr = c.client.Post().\n\t\tResource(\"secrets\").\n\t\tVersionedParams(opts).\n\t\tBody(secret).\n\t\tDo(ctx).\n\t\tInto(result)\n\n\treturn\n}", "func (r *Helm) Copy() *Helm {\n\treturn &Helm{\n\t\tID: r.ID,\n\t\t//ProjectName: r.ProjectName,\n\t\tType: r.Type,\n\t\tName: r.Name,\n\t\tAddress: r.Address,\n\t\tUsername: r.Username,\n\t\tPrefix: r.Prefix,\n\t}\n}", "func SaveVarsInSecret(client kubectl.Client, vars map[string]string, secretName string) error {\n\tif vars == nil {\n\t\tvars = map[string]string{}\n\t}\n\n\t// marshal vars\n\tbytes, err := json.Marshal(vars)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsecret, err := client.KubeClient().CoreV1().Secrets(client.Namespace()).Get(context.TODO(), secretName, metav1.GetOptions{})\n\tif err != nil {\n\t\tif kerrors.IsNotFound(err) == false {\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = client.KubeClient().CoreV1().Secrets(client.Namespace()).Create(context.TODO(), &corev1.Secret{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: secretName,\n\t\t\t},\n\t\t\tData: map[string][]byte{\n\t\t\t\tSecretVarsKey: bytes,\n\t\t\t},\n\t\t}, metav1.CreateOptions{})\n\t\treturn err\n\t}\n\n\tif secret.Data == nil {\n\t\tsecret.Data = map[string][]byte{}\n\t}\n\n\tsecret.Data[SecretVarsKey] = bytes\n\t_, err = client.KubeClient().CoreV1().Secrets(client.Namespace()).Update(context.TODO(), secret, metav1.UpdateOptions{})\n\treturn err\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"volumebackup-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource VolumeBackup\n\terr = c.Watch(&source.Kind{Type: &backupsv1alpha1.VolumeBackup{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO(user): Modify this to be the types you create that are owned by the primary resource\n\t// Watch for changes to secondary resource Pods and requeue the owner VolumeBackup\n\terr = c.Watch(&source.Kind{Type: &v1alpha1.VolumeSnapshot{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &backupsv1alpha1.VolumeBackup{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func createSecrets(ctx context.Context, srcInfo *scanner.SourceInfo, appName string) error {\n\tif srcInfo == nil || len(srcInfo.Secrets) == 0 {\n\t\treturn nil\n\t}\n\n\tvar err error\n\tio := iostreams.FromContext(ctx)\n\tsecrets := map[string]string{}\n\n\tfor _, secret := range srcInfo.Secrets {\n\t\tval := \"\"\n\t\t// If a secret should be a random default, just generate it without displaying\n\t\t// Otherwise, prompt to type it in\n\t\tif secret.Generate != nil {\n\t\t\tif val, err = secret.Generate(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not generate random string: %w\", err)\n\t\t\t}\n\t\t} else if secret.Value != \"\" {\n\t\t\tval = secret.Value\n\t\t} else {\n\t\t\tprompt := fmt.Sprintf(\"Set secret %s:\", secret.Key)\n\t\t\tsurveyInput := &survey.Input{Message: prompt, Help: secret.Help}\n\t\t\tsurvey.AskOne(surveyInput, &val)\n\t\t}\n\n\t\tif val != \"\" {\n\t\t\tsecrets[secret.Key] = val\n\t\t}\n\t}\n\n\tif len(secrets) > 0 {\n\t\tapiClient := client.FromContext(ctx).API()\n\t\t_, err := apiClient.SetSecrets(ctx, appName, secrets)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Fprintf(io.Out, \"Set secrets on %s: %s\\n\", appName, strings.Join(lo.Keys(secrets), \", \"))\n\t}\n\treturn nil\n}", "func NewSecretsAddCommandFactory(ui cli.Ui) cli.CommandFactory {\n\treturn func() (cli.Command, error) {\n\t\tworkingDirectory, err := os.Getwd()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &SecretsAddCommand{\n\t\t\tSecretsBaseCommand: NewSecretsBaseCommand(\"add\", workingDirectory, ui),\n\t\t}, nil\n\t}\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"parameterstore-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource ParameterStore\n\terr = c.Watch(&source.Kind{Type: &ssmv1alpha1.ParameterStore{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.Watch(&source.Kind{Type: &corev1.Secret{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &ssmv1alpha1.ParameterStore{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"minecraft-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource Minecraft\n\terr = c.Watch(&source.Kind{Type: &interviewv1alpha1.Minecraft{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO(user): Modify this to be the types you create that are owned by the primary resource\n\t// Watch for changes to secondary resource Pods and requeue the owner Minecraft\n\terr = c.Watch(&source.Kind{Type: &corev1.Pod{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &interviewv1alpha1.Minecraft{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler, mapFn handler.ToRequestsFunc) error {\n\t// Create a new controller\n\tc, err := controller.New(\"certmerge-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource CertMerge\n\tif err := c.Watch(&source.Kind{Type: &certmergev1alpha1.CertMerge{}}, &handler.EnqueueRequestForObject{}); err != nil {\n\t\treturn err\n\t}\n\n\t// This will trigger the Reconcile if the Merged Secret is modified\n\tif err := c.Watch(&source.Kind{Type: &corev1.Secret{}}, &handler.EnqueueRequestForOwner{IsController: true, OwnerType: &certmergev1alpha1.CertMerge{}}); err != nil {\n\t\treturn err\n\t}\n\n\t// This predicate deduplicate the watch trigger if no data is modified inside the secret\n\t// if the Secret is Deleted, don't send the delete event as we can trigger it from the update\n\n\tupdateFunc := func(e event.UpdateEvent) bool {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"event\": e,\n\t\t}).Debugf(\"Update Predicate event\")\n\t\t// This update is in fact a Delete event, process it\n\t\tif e.MetaNew.GetDeletionGracePeriodSeconds() != nil {\n\t\t\treturn true\n\t\t}\n\n\t\t// if old and new data is the same, don't reconcile\n\t\tnewObj := e.ObjectNew.DeepCopyObject().(*corev1.Secret)\n\t\toldObj := e.ObjectOld.DeepCopyObject().(*corev1.Secret)\n\t\tif cmp.Equal(newObj.Data, oldObj.Data) {\n\t\t\treturn false\n\t\t}\n\n\t\treturn true\n\t}\n\tdeleteFunc := func(e event.DeleteEvent) bool {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"event\": e,\n\t\t}).Debugf(\"Delete Predicate event\")\n\t\treturn false\n\t}\n\n\t// Watch for Secret change and process them through the SecretTriggerCertMerge function\n\t// This watch enables us to reconcile a CertMerge when a concerned Secret is changed (create/update/delete)\n\tp := predicate.Funcs{\n\t\tUpdateFunc: updateFunc,\n\t\t// don't process any Delete event as we catch them in Update\n\t\tDeleteFunc: deleteFunc,\n\t}\n\ts := &source.Kind{\n\t\tType: &corev1.Secret{},\n\t}\n\th := &handler.EnqueueRequestsFromMapFunc{\n\t\tToRequests: mapFn,\n\t}\n\tif err := c.Watch(s, h, p); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewController(handler *Handler, secretInformer coreinformers.SecretInformer, azureKeyVaultSecretsInformer informers.AzureKeyVaultSecretInformer, azureFrequency AzurePollFrequency) *Controller {\n\t// Create event broadcaster\n\t// Add azure-keyvault-controller types to the default Kubernetes Scheme so Events can be\n\t// logged for azure-keyvault-controller types.\n\tutilruntime.Must(keyvaultScheme.AddToScheme(scheme.Scheme))\n\n\tcontroller := &Controller{\n\t\thandler: handler,\n\t\tsecretsSynced: secretInformer.Informer().HasSynced,\n\t\tazureKeyVaultSecretsSynced: azureKeyVaultSecretsInformer.Informer().HasSynced,\n\t\tworkqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"AzureKeyVaultSecrets\"),\n\t\tworkqueueAzure: workqueue.NewNamedRateLimitingQueue(workqueue.NewItemFastSlowRateLimiter(azureFrequency.Normal, azureFrequency.Slow, azureFrequency.MaxFailuresBeforeSlowingDown), \"AzureKeyVault\"),\n\t}\n\n\tlog.Info(\"Setting up event handlers\")\n\t// Set up an event handler for when AzureKeyVaultSecret resources change\n\tazureKeyVaultSecretsInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tsecret := obj.(*akv.AzureKeyVaultSecret)\n\t\t\tif secret.Spec.Output.Secret.Name == \"\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Debugf(\"AzureKeyVaultSecret '%s' added. Adding to queue.\", secret.Name)\n\t\t\tcontroller.enqueueAzureKeyVaultSecret(obj)\n\t\t\tcontroller.enqueueAzurePoll(obj)\n\t\t},\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\tnewSecret := new.(*akv.AzureKeyVaultSecret)\n\t\t\toldSecret := old.(*akv.AzureKeyVaultSecret)\n\t\t\tif oldSecret.Spec.Output.Secret.Name == \"\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif newSecret.ResourceVersion == oldSecret.ResourceVersion {\n\t\t\t\tlog.Debugf(\"AzureKeyVaultSecret '%s' added to Azure queue to check if changed in Azure.\", newSecret.Name)\n\t\t\t\t// Check if secret has changed in Azure\n\t\t\t\tcontroller.enqueueAzurePoll(new)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlog.Debugf(\"AzureKeyVaultSecret '%s' changed. Adding to queue.\", newSecret.Name)\n\t\t\tcontroller.enqueueAzureKeyVaultSecret(new)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tsecret := obj.(*akv.AzureKeyVaultSecret)\n\t\t\tif secret.Spec.Output.Secret.Name == \"\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Debugf(\"AzureKeyVaultSecret '%s' deleted. Adding to delete queue.\", secret.Name)\n\t\t\tcontroller.enqueueDeleteAzureKeyVaultSecret(obj)\n\t\t},\n\t})\n\n\t// Set up an event handler for when Secret resources change. This\n\t// handler will lookup the owner of the given Secret, and if it is\n\t// owned by a AzureKeyVaultSecret resource will enqueue that Secret resource for\n\t// processing. This way, we don't need to implement custom logic for\n\t// handling AzureKeyVaultSecret resources. More info on this pattern:\n\t// https://github.com/kubernetes/community/blob/8cafef897a22026d42f5e5bb3f104febe7e29830/contributors/devel/controllers.md\n\tsecretInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\tsecret := obj.(*corev1.Secret)\n\t\t\tlog.Debugf(\"Secret '%s' added. Handling.\", secret.Name)\n\t\t\tcontroller.enqueueObject(obj)\n\t\t},\n\t\tUpdateFunc: func(old, new interface{}) {\n\t\t\tnewSecret := new.(*corev1.Secret)\n\t\t\toldSecret := old.(*corev1.Secret)\n\n\t\t\tif newSecret.ResourceVersion == oldSecret.ResourceVersion {\n\t\t\t\t// Periodic resync will send update events for all known Secrets.\n\t\t\t\t// Two different versions of the same Secret will always have different RVs.\n\t\t\t\treturn\n\t\t\t}\n\t\t\tsecret := new.(*corev1.Secret)\n\t\t\tlog.Debugf(\"Secret '%s' controlled by AzureKeyVaultSecret changed. Handling.\", secret.Name)\n\t\t\tcontroller.enqueueObject(new)\n\t\t},\n\t\tDeleteFunc: func(obj interface{}) {\n\t\t\tsecret := obj.(*corev1.Secret)\n\t\t\tlog.Debugf(\"Secret '%s' deleted. Handling.\", secret.Name)\n\t\t\tcontroller.enqueueObject(obj)\n\t\t},\n\t})\n\n\treturn controller\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"minecraft-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource Minecraft\n\terr = c.Watch(&source.Kind{Type: &operatorv1alpha1.Minecraft{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO(user): Modify this to be the types you create that are owned by the primary resource\n\t// Watch for changes to secondary resource Pods and requeue the owner Minecraft\n\terr = c.Watch(&source.Kind{Type: &corev1.Pod{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &operatorv1alpha1.Minecraft{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func updateSecret(kubeClient *kubernetes.Clientset, secretName string, succChan chan<- string, errChan chan<- error) {\n\tb := bytes.NewBuffer(nil)\n\t// Secrets\n\tsecret, err := kubeClient.Secrets(\"deis\").Get(secretName)\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tsuccChan <- fmt.Sprintf(\"secret %s not found\", secretName)\n\t\t\treturn\n\t\t}\n\t\terrChan <- err\n\t\treturn\n\t}\n\tsecretNameDet := strings.SplitN(secret.ObjectMeta.Name, \"-\", 2)\n\tpath := \"workflow/charts/\" + secretNameDet[1] + \"templates/\" + secretNameDet[1] + \"-secret.yaml\"\n\tb.WriteString(\"\\n---\\n# Source: \" + path + \"\\n\")\n\tsecret.Kind = \"Secret\"\n\tsecret.APIVersion = \"v1\"\n\tsecret.ResourceVersion = \"\"\n\ty, err := yaml.Marshal(secret)\n\tif err != nil {\n\t\tfmt.Printf(\"err: %v\\n\", err)\n\t\terrChan <- err\n\t\treturn\n\t}\n\tb.WriteString(string(y))\n\n\tfactory := cmdutil.NewFactory(nil)\n\tcurrent := factory.NewBuilder().ContinueOnError().NamespaceParam(\"deis\").DefaultNamespace().Stream(b, \"\").Flatten().Do()\n\terr = current.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tobj, err := cmdutil.MaybeConvertObject(info.Object, info.Mapping.GroupVersionKind.GroupVersion(), info.Mapping)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tname, namespace := info.Name, info.Namespace\n\t\toldData, err := json.Marshal(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := updateAnnotations(obj); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnewData, err := json.Marshal(obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpatchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, obj)\n\t\tcreatedPatch := err == nil\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"couldn't compute patch: %v\", err)\n\t\t}\n\n\t\tmapping := info.ResourceMapping()\n\t\tclient, err := factory.ClientForMapping(mapping)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thelper := resource.NewHelper(client, mapping)\n\n\t\tif createdPatch {\n\t\t\t_, err = helper.Patch(namespace, name, api.StrategicMergePatchType, patchBytes)\n\t\t} else {\n\t\t\t_, err = helper.Replace(namespace, name, false, obj)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\treturn\n\t}\n\tsuccChan <- fmt.Sprintf(\"secret %s annotated successfuly\", secretName)\n}", "func (r *Reconciler) copyConfigurationResources(ctx context.Context, cluster,\n\tsourceCluster *v1beta1.PostgresCluster) error {\n\n\tfor i := range sourceCluster.Spec.Backups.PGBackRest.Configuration {\n\t\t// While all volume projections from .Configuration will be carried over to\n\t\t// the pgBackRest restore Job, we only explicitly copy the relevant ConfigMaps\n\t\t// and Secrets. Any DownwardAPI or ServiceAccountToken projections will need\n\t\t// to be handled manually.\n\t\t// - https://kubernetes.io/docs/concepts/storage/projected-volumes/\n\t\tif sourceCluster.Spec.Backups.PGBackRest.Configuration[i].Secret != nil {\n\t\t\tsecretProjection := sourceCluster.Spec.Backups.PGBackRest.Configuration[i].Secret\n\t\t\tsecretCopy := &corev1.Secret{}\n\t\t\tsecretName := types.NamespacedName{\n\t\t\t\tName: secretProjection.Name,\n\t\t\t\tNamespace: sourceCluster.Namespace,\n\t\t\t}\n\t\t\t// Get the existing Secret for the copy, if it exists. It **must**\n\t\t\t// exist if not configured as optional.\n\t\t\tif secretProjection.Optional != nil && *secretProjection.Optional {\n\t\t\t\tif err := errors.WithStack(r.Client.Get(ctx, secretName,\n\t\t\t\t\tsecretCopy)); apierrors.IsNotFound(err) {\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := errors.WithStack(\n\t\t\t\t\tr.Client.Get(ctx, secretName, secretCopy)); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Set a unique name for the Secret copy using the original Secret\n\t\t\t// name and the Secret projection index number.\n\t\t\tsecretCopyName := fmt.Sprintf(naming.RestoreConfigCopySuffix, secretProjection.Name, i)\n\n\t\t\t// set the new name and namespace\n\t\t\tsecretCopy.ObjectMeta = metav1.ObjectMeta{\n\t\t\t\tName: secretCopyName,\n\t\t\t\tNamespace: cluster.Namespace,\n\t\t\t}\n\t\t\tsecretCopy.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind(\"Secret\"))\n\t\t\tsecretCopy.Annotations = naming.Merge(\n\t\t\t\tcluster.Spec.Metadata.GetAnnotationsOrNil(),\n\t\t\t\tcluster.Spec.Backups.PGBackRest.Metadata.GetAnnotationsOrNil(),\n\t\t\t)\n\t\t\tsecretCopy.Labels = naming.Merge(\n\t\t\t\tcluster.Spec.Metadata.GetLabelsOrNil(),\n\t\t\t\tcluster.Spec.Backups.PGBackRest.Metadata.GetLabelsOrNil(),\n\t\t\t\t// this label allows for cleanup when the restore completes\n\t\t\t\tnaming.PGBackRestRestoreJobLabels(cluster.Name),\n\t\t\t)\n\t\t\tif err := r.setControllerReference(cluster, secretCopy); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := errors.WithStack(r.apply(ctx, secretCopy)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// update the copy of the source PostgresCluster to add the new Secret\n\t\t\t// projection(s) to the restore Job\n\t\t\tsourceCluster.Spec.Backups.PGBackRest.Configuration[i].Secret.Name = secretCopyName\n\t\t}\n\n\t\tif sourceCluster.Spec.Backups.PGBackRest.Configuration[i].ConfigMap != nil {\n\t\t\tconfigMapProjection := sourceCluster.Spec.Backups.PGBackRest.Configuration[i].ConfigMap\n\t\t\tconfigMapCopy := &corev1.ConfigMap{}\n\t\t\tconfigMapName := types.NamespacedName{\n\t\t\t\tName: configMapProjection.Name,\n\t\t\t\tNamespace: sourceCluster.Namespace,\n\t\t\t}\n\t\t\t// Get the existing ConfigMap for the copy, if it exists. It **must**\n\t\t\t// exist if not configured as optional.\n\t\t\tif configMapProjection.Optional != nil && *configMapProjection.Optional {\n\t\t\t\tif err := errors.WithStack(r.Client.Get(ctx, configMapName,\n\t\t\t\t\tconfigMapCopy)); apierrors.IsNotFound(err) {\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := errors.WithStack(\n\t\t\t\t\tr.Client.Get(ctx, configMapName, configMapCopy)); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Set a unique name for the ConfigMap copy using the original ConfigMap\n\t\t\t// name and the ConfigMap projection index number.\n\t\t\tconfigMapCopyName := fmt.Sprintf(naming.RestoreConfigCopySuffix, configMapProjection.Name, i)\n\n\t\t\t// set the new name and namespace\n\t\t\tconfigMapCopy.ObjectMeta = metav1.ObjectMeta{\n\t\t\t\tName: configMapCopyName,\n\t\t\t\tNamespace: cluster.Namespace,\n\t\t\t}\n\t\t\tconfigMapCopy.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind(\"ConfigMap\"))\n\t\t\tconfigMapCopy.Annotations = naming.Merge(\n\t\t\t\tcluster.Spec.Metadata.GetAnnotationsOrNil(),\n\t\t\t\tcluster.Spec.Backups.PGBackRest.Metadata.GetAnnotationsOrNil(),\n\t\t\t)\n\t\t\tconfigMapCopy.Labels = naming.Merge(\n\t\t\t\tcluster.Spec.Metadata.GetLabelsOrNil(),\n\t\t\t\tcluster.Spec.Backups.PGBackRest.Metadata.GetLabelsOrNil(),\n\t\t\t\t// this label allows for cleanup when the restore completes\n\t\t\t\tnaming.PGBackRestRestoreJobLabels(cluster.Name),\n\t\t\t)\n\t\t\tif err := r.setControllerReference(cluster, configMapCopy); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := errors.WithStack(r.apply(ctx, configMapCopy)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// update the copy of the source PostgresCluster to add the new ConfigMap\n\t\t\t// projection(s) to the restore Job\n\t\t\tsourceCluster.Spec.Backups.PGBackRest.Configuration[i].ConfigMap.Name = configMapCopyName\n\t\t}\n\t}\n\treturn nil\n}", "func (in *StringSecret) DeepCopy() *StringSecret {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(StringSecret)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func add(mgr manager.Manager, r reconcile.Reconciler, client dynamic.Interface) error {\n\topts := controller.Options{Reconciler: r}\n\tc, err := NewSBRController(mgr, opts, client)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.Watch()\n}", "func PutSecrets(ctx context.Context, cfg Config, secrets map[string]interface{}) error {\n\tcheckDefaults(&cfg)\n\tvClient, err := login(ctx, cfg)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to login to vault\")\n\t}\n\t_, err = vClient.Logical().Write(cfg.SecretPath, secrets)\n\treturn errors.Wrap(err, \"unable to make vault request\")\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"mutatingwebhook-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch secret\n\terr = c.Watch(&source.Kind{Type: &corev1.Secret{}}, &handler.EnqueueRequestsFromMapFunc{\n\t\tToRequests: handler.ToRequestsFunc(func(obj handler.MapObject) []reconcile.Request {\n\t\t\trequests := []reconcile.Request{}\n\t\t\trequests = append(requests, reconcile.Request{\n\t\t\t\tNamespacedName: types.NamespacedName{\n\t\t\t\t\tName: webhookConfigNamePrefix + obj.Meta.GetNamespace(),\n\t\t\t\t\tNamespace: \"\",\n\t\t\t\t},\n\t\t\t})\n\t\t\treturn requests\n\t\t})}, predicate.Funcs{\n\t\tCreateFunc: func(event event.CreateEvent) bool {\n\t\t\treturn event.Meta.GetName() == serviceAccountSecretName\n\t\t},\n\t\tUpdateFunc: func(event event.UpdateEvent) bool {\n\t\t\treturn event.MetaNew.GetName() == serviceAccountSecretName\n\t\t},\n\t\t// deletion and generic events don't interest us\n\t\tDeleteFunc: func(event event.DeleteEvent) bool {\n\t\t\treturn false\n\t\t},\n\t\tGenericFunc: func(event event.GenericEvent) bool {\n\t\t\treturn false\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch MutatingWebhookConfigurations\n\terr = c.Watch(&source.Kind{Type: &v1beta1.MutatingWebhookConfiguration{}}, &handler.EnqueueRequestForObject{}, predicate.Funcs{\n\t\tCreateFunc: func(event event.CreateEvent) bool {\n\t\t\treturn strings.HasPrefix(event.Meta.GetName(), webhookConfigNamePrefix)\n\t\t},\n\t\tUpdateFunc: func(event event.UpdateEvent) bool {\n\t\t\treturn strings.HasPrefix(event.MetaNew.GetName(), webhookConfigNamePrefix)\n\t\t},\n\t\t// deletion and generic events don't interest us\n\t\tDeleteFunc: func(event event.DeleteEvent) bool {\n\t\t\treturn false\n\t\t},\n\t\tGenericFunc: func(event event.GenericEvent) bool {\n\t\t\treturn false\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewSecrets(k8sClient kubernetes.Interface) *Secrets {\n\treturn &Secrets{\n\t\tk8sClient: k8sClient,\n\t}\n}", "func UpdateSecrets(request types.FunctionDeployment, deployment *appsv1.Deployment, existingSecrets map[string]*apiv1.Secret) error {\n\t// Add / reference pre-existing secrets within Kubernetes\n\tsecretVolumeProjections := []apiv1.VolumeProjection{}\n\n\tfor _, secretName := range request.Secrets {\n\t\tdeployedSecret, ok := existingSecrets[secretName]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Required secret '%s' was not found in the cluster\", secretName)\n\t\t}\n\n\t\tswitch deployedSecret.Type {\n\n\t\tcase apiv1.SecretTypeDockercfg,\n\t\t\tapiv1.SecretTypeDockerConfigJson:\n\n\t\t\tdeployment.Spec.Template.Spec.ImagePullSecrets = append(\n\t\t\t\tdeployment.Spec.Template.Spec.ImagePullSecrets,\n\t\t\t\tapiv1.LocalObjectReference{\n\t\t\t\t\tName: secretName,\n\t\t\t\t},\n\t\t\t)\n\n\t\t\tbreak\n\n\t\tdefault:\n\n\t\t\tprojectedPaths := []apiv1.KeyToPath{}\n\t\t\tfor secretKey := range deployedSecret.Data {\n\t\t\t\tprojectedPaths = append(projectedPaths, apiv1.KeyToPath{Key: secretKey, Path: secretKey})\n\t\t\t}\n\n\t\t\tprojection := &apiv1.SecretProjection{Items: projectedPaths}\n\t\t\tprojection.Name = secretName\n\t\t\tsecretProjection := apiv1.VolumeProjection{\n\t\t\t\tSecret: projection,\n\t\t\t}\n\t\t\tsecretVolumeProjections = append(secretVolumeProjections, secretProjection)\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\tvolumeName := fmt.Sprintf(\"%s-projected-secrets\", request.Service)\n\tprojectedSecrets := apiv1.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: apiv1.VolumeSource{\n\t\t\tProjected: &apiv1.ProjectedVolumeSource{\n\t\t\t\tSources: secretVolumeProjections,\n\t\t\t},\n\t\t},\n\t}\n\n\t// remove the existing secrets volume, if we can find it. The update volume will be\n\t// added below\n\texistingVolumes := removeVolume(volumeName, deployment.Spec.Template.Spec.Volumes)\n\tdeployment.Spec.Template.Spec.Volumes = existingVolumes\n\tif len(secretVolumeProjections) > 0 {\n\t\tdeployment.Spec.Template.Spec.Volumes = append(existingVolumes, projectedSecrets)\n\t}\n\n\t// add mount secret as a file\n\tupdatedContainers := []apiv1.Container{}\n\tfor _, container := range deployment.Spec.Template.Spec.Containers {\n\t\tmount := apiv1.VolumeMount{\n\t\t\tName: volumeName,\n\t\t\tReadOnly: true,\n\t\t\tMountPath: secretsMountPath,\n\t\t}\n\n\t\t// remove the existing secrets volume mount, if we can find it. We update it later.\n\t\tcontainer.VolumeMounts = removeVolumeMount(volumeName, container.VolumeMounts)\n\t\tif len(secretVolumeProjections) > 0 {\n\t\t\tcontainer.VolumeMounts = append(container.VolumeMounts, mount)\n\t\t}\n\n\t\tupdatedContainers = append(updatedContainers, container)\n\t}\n\n\tdeployment.Spec.Template.Spec.Containers = updatedContainers\n\n\treturn nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"deploymentconfig-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to DeploymentConfig\n\terr = c.Watch(&source.Kind{Type: &appsapi_v1.DeploymentConfig{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\tscope.Error(err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"webapp-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource WebApp\n\terr = c.Watch(&source.Kind{Type: &appv1alpha1.WebApp{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO(user): Modify this to be the types you create that are owned by the primary resource\n\t// Watch for changes to secondary resource Pods and requeue the owner WebApp\n\terr = c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &appv1alpha1.WebApp{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o OAUTHKeysList) Copy() elemental.Identifiables {\n\n\tcopy := append(OAUTHKeysList{}, o...)\n\treturn &copy\n}", "func (c *SecretConverter) newSecret() *corev1.Secret {\n\tsecret := &corev1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: c.keyvaultSecret.Name,\n\t\t\tNamespace: c.keyvaultSecret.Namespace,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t*metav1.NewControllerRef(c.keyvaultSecret, schema.GroupVersionKind{\n\t\t\t\t\tGroup: keyvaultsecretv1alpha1.SchemeGroupVersion.Group,\n\t\t\t\t\tVersion: keyvaultsecretv1alpha1.SchemeGroupVersion.Version,\n\t\t\t\t\tKind: \"KeyvaultSecret\",\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t}\n\treturn secret\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"perconaxtradbclusterbackup-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource PerconaXtraDBClusterBackup\n\terr = c.Watch(&source.Kind{Type: &api.PerconaXtraDBClusterBackup{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func newGCPSecretCR(namespace, creds string) *corev1.Secret {\n\treturn &corev1.Secret{\n\t\tType: \"Opaque\",\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Secret\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: gcpSecretName,\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tData: map[string][]byte{\n\t\t\t\"osServiceAccount.json\": []byte(creds),\n\t\t},\n\t}\n}", "func (k *K8s) Write(b []byte) (int, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), DefaultTimeout)\n\tdefer cancel()\n\n\tsecret, err := k.client.CoreV1().Secrets(k.ns).Get(ctx, k.secret, metav1.GetOptions{})\n\n\tif errors.IsNotFound(err) {\n\t\ts := &corev1.Secret{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: k.secret,\n\t\t\t},\n\t\t\tType: corev1.SecretTypeOpaque,\n\t\t\tData: map[string][]byte{\n\t\t\t\tk.key: b,\n\t\t\t},\n\t\t}\n\n\t\tif _, err := k.client.CoreV1().Secrets(k.ns).Create(ctx, s, metav1.CreateOptions{}); err != nil {\n\t\t\treturn 0, fmt.Errorf(\"failed to create secret %s in namespace %s: %v\", k.secret, k.ns, err)\n\t\t}\n\n\t\treturn len(b), nil\n\t}\n\n\t// compare the bytes and only update existing secrets if the bytes are not the same\n\tif !bytes.Equal(secret.Data[k.key], b) {\n\t\tsecret.Data[k.key] = b\n\n\t\tif _, err := k.client.CoreV1().Secrets(k.ns).Update(ctx, secret, metav1.UpdateOptions{}); err != nil {\n\t\t\treturn 0, fmt.Errorf(\"failed to update secret %s in namespace %s: %v\", k.secret, k.ns, err)\n\t\t}\n\t}\n\n\treturn len(b), nil\n}", "func (hc *Hailconfig) Copy(oldAlias, newAlias string) error {\n\tif !hc.IsPresent(oldAlias) {\n\t\treturn errors.New(\"old alias is not present\")\n\t}\n\tif hc.IsPresent(newAlias) {\n\t\treturn errors.New(\"new alias is already present\")\n\t}\n\thc.Add(newAlias, hc.Scripts[oldAlias].Command, hc.Scripts[oldAlias].Description)\n\treturn nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"kogitoapp-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource KogitoApp\n\terr = c.Watch(&source.Kind{Type: &v1alpha1.KogitoApp{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twatchOwnedObjects := []runtime.Object{\n\t\t&oappsv1.DeploymentConfig{},\n\t\t&corev1.Service{},\n\t\t&routev1.Route{},\n\t\t&obuildv1.BuildConfig{},\n\t\t&oimagev1.ImageStream{},\n\t}\n\townerHandler := &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &v1alpha1.KogitoApp{},\n\t}\n\tfor _, watchObject := range watchOwnedObjects {\n\t\terr = c.Watch(&source.Kind{Type: watchObject}, ownerHandler)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (bs *Bindings) Copy() (*Bindings, error) {\r\n\tbytes, err := json.Marshal(bs)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tret := NewBindings()\r\n\terr = json.Unmarshal(bytes, &ret)\r\n\r\n\treturn &ret, nil\r\n}", "func (c *configuration) Secret(clientSet ClientSet) *Secret {\n\tif clientSet != nil {\n\t\treturn NewSecret(clientSet)\n\t}\n\treturn nil\n\n}", "func AddSecretEventClient(contextName string, namespace string, client chan SecretEvent) error {\n\n\t// Get the receiver or create it\n\tctxReceiver, ok := contextReceivers[contextName]\n\tif !ok {\n\n\t\tclientset, err := context.GetClientset(contextName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmetrics, err := context.GetMetrics(contextName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tctxReceiver = &contextReceiver{\n\t\t\tclientset: clientset,\n\t\t\tmetrics: metrics,\n\t\t}\n\n\t\tcontextReceivers[contextName] = ctxReceiver\n\t}\n\n\tnsReceiver, ok := ctxReceiver.namespaceReceivers[namespace]\n\tif !ok {\n\t\tnsReceiver = &namespaceReceiver{}\n\t\tctxReceiver.namespaceReceivers[namespace] = nsReceiver\n\t}\n\n\t// If the event are not received, create a new event receiver\n\treceiver := nsReceiver.secretEventReceiver\n\tif receiver == nil {\n\n\t\treceiver = newSecretEventReceiver(ctxReceiver.clientset, namespace)\n\n\t\tnsReceiver.secretEventReceiver = receiver\n\t}\n\n\t// Add the client\n\treceiver.addClient(client)\n\n\treturn nil\n}", "func (s *SecretService) PutSecrets(ctx context.Context, orgID influxdb.ID, m map[string]string) error {\n\t// PutSecrets operates on intersection between m and keys beloging to orgID.\n\t// We need to have read access to those secrets since it deletes the secrets (within the intersection) that have not be overridden.\n\tif err := authorizeReadSecret(ctx, orgID); err != nil {\n\t\treturn err\n\t}\n\n\tif err := authorizeWriteSecret(ctx, orgID); err != nil {\n\t\treturn err\n\t}\n\n\terr := s.s.PutSecrets(ctx, orgID, m)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Client) AddSecret(variableID string, secretValue string) error {\n\treq, err := c.AddSecretRequest(variableID, secretValue)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp, err := c.SubmitRequest(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn response.EmptyResponse(resp)\n}", "func (r *PassLessReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\tl := log.FromContext(ctx)\n\n\t// Fetch the PassLess instance\n\tpsls := &v1alpha1.PassLess{}\n\terr := r.Client.Get(ctx, req.NamespacedName, psls)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// Request object not found, could have been deleted after reconcile request.\n\t\t\t// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.\n\t\t\t// Return and don't requeue\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\t\t// Error reading the object - requeue the request.\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Define a new Secret object\n\tsecret := psls.CreateSecret(r.generator(ctx))\n\thashcode := secrets.Hashcode(secret)\n\n\t// Set PassLess instance as the owner and controller\n\tif err := controllerutil.SetControllerReference(psls, secret, r.Scheme); err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Check if this Secret already exists\n\tfound := &corev1.Secret{}\n\terr = r.Client.Get(ctx, types.NamespacedName{\n\t\tName: secret.Name,\n\t\tNamespace: secret.Namespace,\n\t}, found)\n\tif err != nil && errors.IsNotFound(err) {\n\t\tl.Info(\"Creating a new secret\",\n\t\t\t\"Hash\", hashcode,\n\t\t)\n\t\terr = r.Client.Create(ctx, secret)\n\t\tif err != nil {\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\n\t\t// Secret created successfully - don't requeue\n\t\treturn ctrl.Result{}, nil\n\t} else if err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Secret already exists, check if need update\n\tif needsUpdate(secret, found) {\n\t\tl.Info(\"Updating a secret\",\n\t\t\t\"Hash\", hashcode,\n\t\t)\n\t\terr = r.Client.Update(ctx, secret)\n\t\tif err != nil {\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t}\n\treturn ctrl.Result{}, nil\n}", "func New(out io.Writer, in io.Reader, hasInput bool, snptStore *snippet.Store) *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse: \"copy [snippet ID | snippet name]\",\n\t\tAliases: []string{\"cp\"},\n\t\tShort: \"Copy a snippet to the clipboard\",\n\t\tLong: `\nCopy a snippet to the clipboard.\n\nIf you do not provide a snippet ID or snippet name then a prompt will be shown and you can select the snippet you want to copy to the clipboard.\n\nSnpt will read from stdin if provided and attempt to extract a snippet ID from it. The stdin should be formatted like:\n\n\tSome random string [snippet ID]\n\nSnpt will parse anything in the square brackets that appears at the end of the string. This is useful for piping into Snpt:\n\n\techo 'foo - bar baz [aff9aa71ead70963p3bfa4e49b18d27539f9d9d8]' | snpt cp`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tsnpt, err := cliHelper.ResolveSnippet(args, hasInput, in, snptStore)\n\n\t\t\tif err != nil || snpt.GetId() == \"\" {\n\t\t\t\treturn errors.New(\"Failed to retrieve snippet from database\")\n\t\t\t}\n\n\t\t\tif err := clipboard.WriteAll(snpt.Content); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed to copy %s to the clipboard\", snpt.GetFilename())\n\t\t\t}\n\n\t\t\tcliHelper.PrintSuccess(out, \"%s copied to the clipboard\", snpt.GetFilename())\n\n\t\t\treturn nil\n\t\t},\n\t}\n}", "func newSecretForCR(cr *ricobergerdev1alpha1.VaultSecret, data map[string][]byte) (*corev1.Secret, error) {\n\tlabels := map[string]string{}\n\tfor k, v := range cr.ObjectMeta.Labels {\n\t\tlabels[k] = v\n\t}\n\n\tannotations := map[string]string{}\n\tfor k, v := range cr.ObjectMeta.Annotations {\n\t\tannotations[k] = v\n\t}\n\n\tif cr.Spec.Templates != nil {\n\t\tnewdata := make(map[string][]byte)\n\t\tfor k, v := range cr.Spec.Templates {\n\t\t\ttemplated, err := runTemplate(cr, v, data)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Template ERROR: %w\", err)\n\t\t\t}\n\t\t\tnewdata[k] = templated\n\t\t}\n\t\tdata = newdata\n\t}\n\n\treturn &corev1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name,\n\t\t\tNamespace: cr.Namespace,\n\t\t\tLabels: labels,\n\t\t\tAnnotations: annotations,\n\t\t},\n\t\tData: data,\n\t\tType: cr.Spec.Type,\n\t}, nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler, logger logr.Logger) error {\n\t// Create a new controller\n\tc, err := controller.New(controllerName, mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to Deployable\n\terr = c.Watch(&source.Kind{Type: &dplv1.Deployable{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// watch for changes to channel too\n\treturn c.Watch(&source.Kind{\n\t\tType: &chv1.Channel{}},\n\t\t&handler.EnqueueRequestsFromMapFunc{ToRequests: &channelMapper{Client: mgr.GetClient(), logger: logger}})\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(controllerName, mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to Template\n\terr = c.Watch(&source.Kind{Type: &elasticsearchdbv1beta1.Template{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (g *Guard) Secret(v []byte) (*Secret, error) {\n\tg.lock.Lock()\n\tdefer g.lock.Unlock()\n\n\tb, err := memguard.NewMutableFromBytes(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := Secret{\n\t\tbuffer: b,\n\t\tguard: g,\n\t}\n\n\tg.secrets = append(g.secrets, &s)\n\treturn &s, nil\n}", "func newSecretClient(subID string, authorizer auth.Authorizer) (*client, error) {\n\tc, err := wssdcloudclient.GetSecretClient(&subID, authorizer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &client{c}, nil\n}", "func backupSecrets(env *localenv.LocalEnvironment, path string) error {\n\tsuffix, err := users.CryptoRandomToken(6)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tbackupPath := fmt.Sprintf(\"%v-%v\", path, suffix)\n\terr = utils.CopyDirContents(path, backupPath)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tenv.Printf(\"Backed up %v to %v\\n\", path, backupPath)\n\treturn nil\n}", "func UpdateSecrets(request requests.CreateFunctionRequest, deployment *v1beta1.Deployment, existingSecrets map[string]*apiv1.Secret) error {\n\t// Add / reference pre-existing secrets within Kubernetes\n\tsecretVolumeProjections := []apiv1.VolumeProjection{}\n\n\tfor _, secretName := range request.Secrets {\n\t\tdeployedSecret, ok := existingSecrets[secretName]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Required secret '%s' was not found in the cluster\", secretName)\n\t\t}\n\n\t\tswitch deployedSecret.Type {\n\n\t\tcase apiv1.SecretTypeDockercfg,\n\t\t\tapiv1.SecretTypeDockerConfigJson:\n\n\t\t\tdeployment.Spec.Template.Spec.ImagePullSecrets = append(\n\t\t\t\tdeployment.Spec.Template.Spec.ImagePullSecrets,\n\t\t\t\tapiv1.LocalObjectReference{\n\t\t\t\t\tName: secretName,\n\t\t\t\t},\n\t\t\t)\n\n\t\t\tbreak\n\n\t\tdefault:\n\n\t\t\tprojectedPaths := []apiv1.KeyToPath{}\n\t\t\tfor secretKey := range deployedSecret.Data {\n\t\t\t\tprojectedPaths = append(projectedPaths, apiv1.KeyToPath{Key: secretKey, Path: secretKey})\n\t\t\t}\n\n\t\t\tprojection := &apiv1.SecretProjection{Items: projectedPaths}\n\t\t\tprojection.Name = secretName\n\t\t\tsecretProjection := apiv1.VolumeProjection{\n\t\t\t\tSecret: projection,\n\t\t\t}\n\t\t\tsecretVolumeProjections = append(secretVolumeProjections, secretProjection)\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\tvolumeName := fmt.Sprintf(\"%s-projected-secrets\", request.Service)\n\tprojectedSecrets := apiv1.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: apiv1.VolumeSource{\n\t\t\tProjected: &apiv1.ProjectedVolumeSource{\n\t\t\t\tSources: secretVolumeProjections,\n\t\t\t},\n\t\t},\n\t}\n\n\t// remove the existing secrets volume, if we can find it. The update volume will be\n\t// added below\n\texistingVolumes := removeVolume(volumeName, deployment.Spec.Template.Spec.Volumes)\n\tdeployment.Spec.Template.Spec.Volumes = existingVolumes\n\tif len(secretVolumeProjections) > 0 {\n\t\tdeployment.Spec.Template.Spec.Volumes = append(existingVolumes, projectedSecrets)\n\t}\n\n\t// add mount secret as a file\n\tupdatedContainers := []apiv1.Container{}\n\tfor _, container := range deployment.Spec.Template.Spec.Containers {\n\t\tmount := apiv1.VolumeMount{\n\t\t\tName: volumeName,\n\t\t\tReadOnly: true,\n\t\t\tMountPath: \"/run/secrets\",\n\t\t}\n\n\t\t// remove the existing secrets volume mount, if we can find it. We update it later.\n\t\tcontainer.VolumeMounts = removeVolumeMount(volumeName, container.VolumeMounts)\n\t\tif len(secretVolumeProjections) > 0 {\n\t\t\tcontainer.VolumeMounts = append(container.VolumeMounts, mount)\n\t\t}\n\n\t\tupdatedContainers = append(updatedContainers, container)\n\t}\n\n\tdeployment.Spec.Template.Spec.Containers = updatedContainers\n\n\treturn nil\n}", "func Add(mgr manager.Manager) error {\n\tr := &Reconciler{\n\t\tconnecter: &providerConnecter{kube: mgr.GetClient(), newClient: resourcegroup.NewClient},\n\t\tkube: mgr.GetClient(),\n\t}\n\tc, err := controller.New(controllerName, mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"cannot create Kubernetes controller\")\n\t}\n\n\treturn c.Watch(&source.Kind{Type: &v1alpha1.ResourceGroup{}}, &handler.EnqueueRequestForObject{})\n}", "func Secret(s *dag.Secret) *envoy_api_v2_auth.Secret {\n\treturn &envoy_api_v2_auth.Secret{\n\t\tName: Secretname(s),\n\t\tType: &envoy_api_v2_auth.Secret_TlsCertificate{\n\t\t\tTlsCertificate: &envoy_api_v2_auth.TlsCertificate{\n\t\t\t\tPrivateKey: &envoy_api_v2_core.DataSource{\n\t\t\t\t\tSpecifier: &envoy_api_v2_core.DataSource_InlineBytes{\n\t\t\t\t\t\tInlineBytes: s.PrivateKey(),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tCertificateChain: &envoy_api_v2_core.DataSource{\n\t\t\t\t\tSpecifier: &envoy_api_v2_core.DataSource_InlineBytes{\n\t\t\t\t\t\tInlineBytes: s.Cert(),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"appservice-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource AppService\n\terr = c.Watch(&source.Kind{Type: &csye7374v1alpha1.AppService{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO(user): Modify this to be the types you create that are owned by the primary resource\n\t// Watch for changes to secondary resource Pods and requeue the owner AppService\n\terr = c.Watch(&source.Kind{Type: &corev1.Secret{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &csye7374v1alpha1.AppService{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"tektoninstallation-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource TektonInstallation\n\tif err := c.Watch(&source.Kind{Type: &v1alpha1.TektonInstallation{}}, &handler.EnqueueRequestForObject{}, predicate.GenerationChangedPredicate{}); err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource\n\tenqueueRequestForOwner := &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &toolchainv1alpha1.TektonInstallation{},\n\t}\n\n\treturn c.Watch(&source.Kind{Type: &olmv1alpha1.Subscription{}}, enqueueRequestForOwner)\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(config.ControllerNameEnvVar.Value, mgr, controller.Options{Reconciler: r, MaxConcurrentReconciles: 1})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource CustomResource\n\terr = c.Watch(&source.Kind{Type: &polkadotv1alpha1.Polkadot{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource StatefulSet and requeue the owner CustomResource\n\terr = c.Watch(&source.Kind{Type: &appsv1.StatefulSet{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &polkadotv1alpha1.Polkadot{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource Service and requeue the owner CustomResource\n\terr = c.Watch(&source.Kind{Type: &corev1.Service{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &polkadotv1alpha1.Polkadot{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//TODO add watch for NetworkPolicy\n\n\treturn nil\n}", "func Secret(s *dag.Secret) *envoy_tls_v3.Secret {\n\treturn &envoy_tls_v3.Secret{\n\t\tName: envoy.Secretname(s),\n\t\tType: &envoy_tls_v3.Secret_TlsCertificate{\n\t\t\tTlsCertificate: &envoy_tls_v3.TlsCertificate{\n\t\t\t\tPrivateKey: &envoy_core_v3.DataSource{\n\t\t\t\t\tSpecifier: &envoy_core_v3.DataSource_InlineBytes{\n\t\t\t\t\t\tInlineBytes: s.PrivateKey(),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tCertificateChain: &envoy_core_v3.DataSource{\n\t\t\t\t\tSpecifier: &envoy_core_v3.DataSource_InlineBytes{\n\t\t\t\t\t\tInlineBytes: s.Cert(),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func New(mgr manager.Manager, operatorNamespace, operandNamespace string) (runtimecontroller.Controller, error) {\n\toperatorCache := mgr.GetCache()\n\treconciler := &reconciler{\n\t\tclient: mgr.GetClient(),\n\t\tcache: operatorCache,\n\t\trecorder: mgr.GetEventRecorderFor(controllerName),\n\t\toperatorNamespace: operatorNamespace,\n\t\toperandNamespace: operandNamespace,\n\t}\n\tc, err := runtimecontroller.New(controllerName, mgr, runtimecontroller.Options{Reconciler: reconciler})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Index ingresscontrollers over the default certificate name so that\n\t// secretToIngressController can look up ingresscontrollers that\n\t// reference the secret.\n\tif err := operatorCache.IndexField(context.Background(), &operatorv1.IngressController{}, \"defaultCertificateName\", client.IndexerFunc(func(o client.Object) []string {\n\t\tsecret := controller.RouterEffectiveDefaultCertificateSecretName(o.(*operatorv1.IngressController), operandNamespace)\n\t\treturn []string{secret.Name}\n\t})); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create index for ingresscontroller: %v\", err)\n\t}\n\n\tsecretsInformer, err := operatorCache.GetInformer(context.Background(), &corev1.Secret{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create informer for secrets: %v\", err)\n\t}\n\tif err := c.Watch(&source.Informer{Informer: secretsInformer}, handler.EnqueueRequestsFromMapFunc(reconciler.secretToIngressController)); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := c.Watch(source.Kind(operatorCache, &operatorv1.IngressController{}), &handler.EnqueueRequestForObject{}, predicate.Funcs{\n\t\tCreateFunc: func(e event.CreateEvent) bool { return reconciler.hasSecret(e.Object, e.Object) },\n\t\tDeleteFunc: func(e event.DeleteEvent) bool { return reconciler.hasSecret(e.Object, e.Object) },\n\t\tUpdateFunc: func(e event.UpdateEvent) bool { return reconciler.secretChanged(e.ObjectOld, e.ObjectNew) },\n\t\tGenericFunc: func(e event.GenericEvent) bool { return reconciler.hasSecret(e.Object, e.Object) },\n\t}, predicate.NewPredicateFuncs(func(o client.Object) bool {\n\t\treturn reconciler.hasClusterIngressDomain(o) || isDefaultIngressController(o)\n\t})); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller. All injections (e.g. InjectClient) are performed after this call to controller.New()\n\tc, err := controller.New(\"kedacontroller-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource KedaController\n\terr = c.Watch(&source.Kind{Type: &kedav1alpha1.KedaController{}}, &handler.EnqueueRequestForObject{}, predicate.GenerationChangedPredicate{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource Deployment and requeue the owner KedaController\n\terr = c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &kedav1alpha1.KedaController{},\n\t}, predicate.GenerationChangedPredicate{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (_m *requestHeaderMapUpdatable) AddCopy(name string, value string) {\n\t_m.Called(name, value)\n}", "func (b *Bucket) Copy() *Bucket {\n\tmd := make(map[string]Metadata)\n\tfor k, v := range b.Metadata {\n\t\tmd[k] = v\n\t}\n\treturn &Bucket{\n\t\tKey: b.Key,\n\t\tOwner: b.Owner,\n\t\tName: b.Name,\n\t\tVersion: b.Version,\n\t\tLinkKey: b.LinkKey,\n\t\tPath: b.Path,\n\t\tMetadata: md,\n\t\tCreatedAt: b.CreatedAt,\n\t\tUpdatedAt: b.UpdatedAt,\n\t}\n}", "func ApplySecretHash(c client.Client, pod *corev1.PodTemplateSpec, annotationName string, namespace string, secretName string, keys ...string) error {\n\n\tsecret := &corev1.Secret{}\n\n\t// fetch secret\n\n\tif err := c.Get(context.Background(), client.ObjectKey{Namespace: namespace, Name: secretName}, secret); err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\t// we could pause reconciling until the secret is provided\n\t\t\treturn util.NewConfigurationError(\"Secret '\" + secretName + \"' missing for deployment\")\n\t\t}\n\t\treturn err\n\t}\n\n\t// create hash\n\n\trec := cchange.NewRecorder()\n\tif len(keys) == 0 {\n\t\trec.AddBytesFromMap(secret.Data)\n\t} else {\n\t\tfor _, k := range keys {\n\t\t\tif v, ok := secret.Data[k]; ok {\n\t\t\t\trec.AddBytes(v)\n\t\t\t} else {\n\t\t\t\treturn util.NewConfigurationError(\"Missing key '%s' in data section of Secret %s/%s\", k, namespace, secretName)\n\t\t\t}\n\t\t}\n\t}\n\n\t// store hash\n\n\tsetHashInformation(pod, annotationName, rec)\n\n\t// done\n\n\treturn nil\n\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(controllerName, mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to Provider\n\terr = c.Watch(&source.Kind{Type: &gcpv1alpha1.Provider{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Container) Copy() Scheduable {\n\tnewEl := NewContainer(c.id, c.start, c.end)\n\tsliceCopy := make([]Task, len(c.GetTasks()))\n\tcopy(sliceCopy, c.GetTasks())\n\tnewEl.SetTasks(sliceCopy)\n\treturn newEl\n}", "func generateSplunkSecret() []byte {\n\treturn resources.GenerateSecret(secretBytes, 24)\n}", "func PostSecret(c *gin.Context) {\n\trepo := session.Repo(c)\n\n\tin := new(model.Secret)\n\tif err := c.Bind(in); err != nil {\n\t\tc.String(http.StatusBadRequest, \"Error parsing secret. %s\", err)\n\t\treturn\n\t}\n\tsecret := &model.Secret{\n\t\tRepoID: repo.ID,\n\t\tName: in.Name,\n\t\tValue: in.Value,\n\t\tEvents: in.Events,\n\t\tImages: in.Images,\n\t}\n\tif err := secret.Validate(); err != nil {\n\t\tc.String(400, \"Error inserting secret. %s\", err)\n\t\treturn\n\t}\n\tif err := Config.Services.Secrets.SecretCreate(repo, secret); err != nil {\n\t\tc.String(500, \"Error inserting secret %q. %s\", in.Name, err)\n\t\treturn\n\t}\n\tc.JSON(200, secret.Copy())\n}", "func (b *Executor) Copy(excludes []string, copies ...imagebuilder.Copy) error {\n\tfor _, copy := range copies {\n\t\tlogrus.Debugf(\"COPY %#v, %#v\", excludes, copy)\n\t\tif err := b.volumeCacheInvalidate(copy.Dest); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsources := []string{}\n\t\tfor _, src := range copy.Src {\n\t\t\tif strings.HasPrefix(src, \"http://\") || strings.HasPrefix(src, \"https://\") {\n\t\t\t\tsources = append(sources, src)\n\t\t\t} else if len(copy.From) > 0 {\n\t\t\t\tif other, ok := b.named[copy.From]; ok && other.index < b.index {\n\t\t\t\t\tsources = append(sources, filepath.Join(other.mountPoint, src))\n\t\t\t\t} else {\n\t\t\t\t\treturn errors.Errorf(\"the stage %q has not been built\", copy.From)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsources = append(sources, filepath.Join(b.contextDir, src))\n\t\t\t}\n\t\t}\n\n\t\toptions := buildah.AddAndCopyOptions{\n\t\t\tChown: copy.Chown,\n\t\t}\n\n\t\tif err := b.builder.Add(copy.Dest, copy.Download, options, sources...); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Config) AddSecretVolumesToIntendedSTS(sts *appsv1.StatefulSet, volumeConfigMapMap map[string]string) {\n\tAddSecretVolumesToIntendedSTS(sts, volumeConfigMapMap)\n}", "func (sr *StoredRecording) Copy(key *ari.Key, dest string) (*ari.StoredRecordingHandle, error) {\n\th, err := sr.StageCopy(key, dest)\n\tif err != nil {\n\t\t// NOTE: return the handle even on failure so that it can be used to\n\t\t// delete the existing stored recording, should the Copy fail.\n\t\t// ARI provides no facility to force-copy a recording.\n\t\treturn h, err\n\t}\n\n\treturn h, h.Exec()\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"podreplica-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource PodReplica\n\terr = c.Watch(&source.Kind{Type: &appv1alpha1.PodReplica{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to secondary resource Pods and requeue the owner PodReplica\n\terr = c.Watch(&source.Kind{Type: &corev1.Pod{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &appv1alpha1.PodReplica{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (config *Config) AddSecret(tenants string, pw []byte) ([]byte, error) {\n\tvar err error\n\n\tsecret, err := config.GetSecretMap()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"AddSecret(GetSecretMap)\")\n\t}\n\n\t// create secret key once if it doesn't exist\n\tif _, ok := secret.Name[\"secretkey\"]; !ok {\n\n\t\tsecret.Name = make(map[string][]byte)\n\t\tsecret.Name[\"secretkey\"], err = GetSecretKey()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"AddSecret(GetSecretKey)\")\n\t\t}\n\t}\n\n\t// encrypt password\n\tencPw, err := PwEncrypt(pw, secret.Name[\"secretkey\"])\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"AddSecret(PwEncrypt)\")\n\t}\n\n\tfor _, tenant := range strings.Split(tenants, \",\") {\n\n\t\t// check, if cmd line tenant exists in configfile\n\t\ttInfo := config.FindTenant(low(tenant))\n\t\tif \"\" == tInfo.Name {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"tenant\": low(tenant),\n\t\t\t}).Error(\"missing tenant\")\n\t\t\treturn nil, errors.New(\"Did not find tenant in configfile tenants slice.\")\n\t\t}\n\n\t\t// add password to secret map\n\t\tsecret.Name[low(tenant)] = encPw\n\t}\n\n\t// write pw information back to the config file\n\tnewSecret, err := proto.Marshal(&secret)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"AddSecret(Marshal)\")\n\t}\n\n\treturn newSecret, nil\n}", "func (in *PlatformSecrets) DeepCopy() *PlatformSecrets {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PlatformSecrets)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"dataset-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource Dataset\n\terr = c.Watch(&source.Kind{Type: &comv1alpha1.Dataset{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Controller) Secrets() typedv1.SecretInterface {\n\treturn c.client.Secrets(c.namespace.Name)\n}" ]
[ "0.61047924", "0.58078575", "0.55848235", "0.5407227", "0.5254048", "0.5200474", "0.51375145", "0.49901083", "0.49053696", "0.48901126", "0.4862202", "0.4833981", "0.48101637", "0.48065236", "0.47915724", "0.47563052", "0.47331327", "0.47252765", "0.47191927", "0.46923995", "0.46914914", "0.46902007", "0.46865007", "0.46711046", "0.46570998", "0.4650207", "0.46490082", "0.46382594", "0.46232036", "0.4599958", "0.45986438", "0.4596334", "0.4593119", "0.45889023", "0.45665815", "0.45661953", "0.4566038", "0.45653766", "0.45627588", "0.45614845", "0.45536909", "0.45528078", "0.45497867", "0.4540884", "0.45382547", "0.45379573", "0.4531662", "0.45311275", "0.4502233", "0.45020038", "0.4491847", "0.44830003", "0.4473667", "0.44679958", "0.44658107", "0.4458257", "0.44511703", "0.44473505", "0.4445275", "0.44396394", "0.44379643", "0.44253808", "0.44222635", "0.44151437", "0.44099846", "0.44096527", "0.44045958", "0.43938085", "0.43860948", "0.43849128", "0.43721133", "0.43594605", "0.4357975", "0.43526936", "0.4344357", "0.4340745", "0.4338392", "0.43382633", "0.43373346", "0.43364128", "0.4333047", "0.4317101", "0.43116635", "0.43021196", "0.42978936", "0.42968196", "0.429542", "0.42912114", "0.42884743", "0.42862293", "0.4281692", "0.4280333", "0.42769882", "0.4275873", "0.42651674", "0.4261313", "0.4260805", "0.42597207", "0.4257963", "0.42568064" ]
0.8458819
0
listQuarksSecretsReconciles lists all Quarks Secrets associated with the a particular secret.
func listQuarksSecretsReconciles(ctx context.Context, client crc.Client, secret *corev1.Secret, namespace string) ([]reconcile.Request, error) { quarksSecretList := &qsv1a1.QuarksSecretList{} err := client.List(ctx, quarksSecretList, crc.InNamespace(namespace)) if err != nil { return nil, errors.Wrap(err, "failed to list QuarksSecrets") } result := []reconcile.Request{} for _, quarksSecret := range quarksSecretList.Items { if quarksSecret.Spec.SecretName == secret.Name { request := reconcile.Request{ NamespacedName: types.NamespacedName{ Name: quarksSecret.Name, Namespace: quarksSecret.Namespace, }} result = append(result, request) ctxlog.NewMappingEvent(secret).Debug(ctx, request, "QuarksSecret", secret.Name, qsv1a1.KubeSecretReference) } } return result, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s Secrets) List(ctx context.Context, maxResults int32) ([]string, error) {\n\tvers, err := s.Ops.Secrets().List(ctx, maxResults)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout := make([]string, 0, len(vers))\n\tfor _, ver := range vers {\n\t\tout = append(out, ver.ID)\n\t}\n\treturn out, nil\n}", "func (c *Client) ListScramSecrets(ctx context.Context, params *ListScramSecretsInput, optFns ...func(*Options)) (*ListScramSecretsOutput, error) {\n\tif params == nil {\n\t\tparams = &ListScramSecretsInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"ListScramSecrets\", params, optFns, addOperationListScramSecretsMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*ListScramSecretsOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (c *ClientSetClient) ListSecrets(namespace string, opts metav1.ListOptions) (*v1.SecretList, error) {\n\tctx := context.TODO()\n\treturn c.clientset.CoreV1().Secrets(namespace).List(ctx, opts)\n}", "func (api *API) ListWorkersSecrets(ctx context.Context, rc *ResourceContainer, params ListWorkersSecretsParams) (WorkersListSecretsResponse, error) {\n\tif rc.Level != AccountRouteLevel {\n\t\treturn WorkersListSecretsResponse{}, ErrRequiredAccountLevelResourceContainer\n\t}\n\n\tif rc.Identifier == \"\" {\n\t\treturn WorkersListSecretsResponse{}, ErrMissingAccountID\n\t}\n\n\turi := fmt.Sprintf(\"/accounts/%s/workers/scripts/%s/secrets\", rc.Identifier, params.ScriptName)\n\tres, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)\n\tif err != nil {\n\t\treturn WorkersListSecretsResponse{}, err\n\t}\n\n\tresult := WorkersListSecretsResponse{}\n\tif err := json.Unmarshal(res, &result); err != nil {\n\t\treturn result, fmt.Errorf(\"%s: %w\", errUnmarshalError, err)\n\t}\n\n\treturn result, err\n}", "func (dir EnvDir) Secrets() []string {\n\treturn []string{}\n}", "func (v *Vault) ListSecrets() {\n\tlog.Debugf(\"Listing secrets in Vault KV Path: %v\", s.VaultKVPath())\n\td, err := v.Client.Logical().List(s.VaultKVPath())\n\tif err != nil {\n\t\tlog.Fatalf(\"Vault error: %v\", err)\n\t}\n\n\ttable := tablewriter.NewWriter(os.Stdout)\n\ttable.SetHeader([]string{\"Key\"})\n\tfor _, l := range d.Data[\"keys\"].([]interface{}) {\n\t\ttable.Append([]string{l.(string)})\n\t}\n\ttable.Render()\n}", "func GetSecretList(c *gin.Context) {\n\trepo := session.Repo(c)\n\tlist, err := Config.Services.Secrets.SecretList(repo)\n\tif err != nil {\n\t\tc.String(500, \"Error getting secret list. %s\", err)\n\t\treturn\n\t}\n\t// copy the secret detail to remove the sensitive\n\t// password and token fields.\n\tfor i, secret := range list {\n\t\tlist[i] = secret.Copy()\n\t}\n\tc.JSON(200, list)\n}", "func (ef EnvFlags) Secrets() []string {\n\tresult := make([]string, len(ef))\n\ti := 0\n\tfor _, v := range ef {\n\t\tresult[i] = v\n\t\ti++\n\t}\n\treturn result\n}", "func (s S) Secrets() []v1.Secret {\n\treturn s.secrets\n}", "func getSecrets(p *Plugin) ([]Secret, error) {\n\ttype (\n\t\t// PasswordState JSON response for the passwords\n\t\tPasswordList struct {\n\t\t\tPasswordID int `json:\"PasswordID\"`\n\t\t\tTitle string `json:\"Title\"`\n\t\t\tUserName string `json:\"UserName\"`\n\t\t\tDescription string `json:\"Description\"`\n\t\t\tGenericField1 string `json:\"GenericField1\"`\n\t\t\tGenericField2 string `json:\"GenericField2\"`\n\t\t\tGenericField3 string `json:\"GenericField3\"`\n\t\t\tGenericField4 string `json:\"GenericField4\"`\n\t\t\tGenericField5 string `json:\"GenericField5\"`\n\t\t\tGenericField6 string `json:\"GenericField6\"`\n\t\t\tGenericField7 string `json:\"GenericField7\"`\n\t\t\tGenericField8 string `json:\"GenericField8\"`\n\t\t\tGenericField9 string `json:\"GenericField9\"`\n\t\t\tGenericField10 string `json:\"GenericField10\"`\n\t\t\tAccountTypeID int `json:\"AccountTypeID\"`\n\t\t\tNotes string `json:\"Notes\"`\n\t\t\tURL string `json:\"URL\"`\n\t\t\tPassword string `json:\"Password\"`\n\t\t\tExpiryDate string `json:\"ExpiryDate\"`\n\t\t\tAllowExport bool `json:\"AllowExport\"`\n\t\t\tAccountType string `json:\"AccountType\"`\n\t\t}\n\t)\n\n\tvar (\n\t\turl strings.Builder\n\t\tsecrets []Secret\n\t)\n\n\turl.WriteString(strings.TrimRight(p.Config.ApiEndpoint, \"/\"))\n\turl.WriteString(\"/passwords/{PasswordListID}\")\n\n\t// Configure the API client:\n\tclient := resty.New()\n\tclient.\n\t\tSetRetryCount(p.Config.ConnectionRetries).\n\t\tSetTimeout(time.Duration(p.Config.ConnectionTimeout) * time.Second)\n\tif p.Config.Debug {\n\t\tclient.SetDebug(true)\n\t}\n\tif p.Config.SkipTlsVerify {\n\t\tclient.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: p.Config.SkipTlsVerify})\n\t}\n\tclient.\n\t\tSetQueryParams(map[string]string{\n\t\t\t\"QueryAll\": \"true\",\n\t\t\t\"PreventAuditing\": \"false\",\n\t\t}).\n\t\tSetPathParams(map[string]string{\n\t\t\t\"PasswordListID\": strconv.Itoa(p.Config.PasswordListId),\n\t\t}).\n\t\tSetHeaders(map[string]string{\n\t\t\t\"APIKey\": p.Config.ApiKey,\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t})\n\n\t// Send the request:\n\tlogrus.WithField(\"endpoint\", p.Config.ApiEndpoint).WithField(\"list_id\", p.Config.PasswordListId).Infoln(\"Querying PasswordState API.\")\n\tresponse, err := client.R().\n\t\tSetResult([]PasswordList{}).\n\t\tGet(url.String())\n\n\tif err != nil {\n\t\tlogrus.WithError(err).Errorln(\"Failed to retrieved data from PasswordState.\")\n\t\treturn nil, err\n\t}\n\n\tpasswords := *response.Result().(*[]PasswordList)\n\tlogrus.WithField(\"count\", len(passwords)).Infoln(\"Passwords retrieved from PasswordState.\")\n\tlogrus.WithField(\"key_field\", p.Config.KeyField).WithField(\"value_field\", p.Config.ValueField).Infoln(\"Converting retrieved passwords to secrets.\")\n\tfor _, password := range passwords {\n\t\tkey := reflect.Indirect(reflect.ValueOf(password)).FieldByName(p.Config.KeyField).String()\n\t\tif key == \"\" || key == \"<invalid Value>\" {\n\t\t\tlogrus.WithField(\"password_id\", password.PasswordID).WithField(\"field\", p.Config.KeyField).Warnln(\"Key is empty. Skipping the secret.\")\n\t\t\tcontinue\n\t\t}\n\t\tvalue := reflect.Indirect(reflect.ValueOf(password)).FieldByName(p.Config.ValueField).String()\n\t\tif value == \"\" || value == \"<invalid Value>\" {\n\t\t\tlogrus.WithField(\"password_id\", password.PasswordID).WithField(\"field\", p.Config.ValueField).Warnln(\"Value is empty. Skipping the secret.\")\n\t\t\tcontinue\n\t\t}\n\t\tsecret := Secret{\n\t\t\tKey: key,\n\t\t\tValue: value,\n\t\t}\n\t\tsecrets = append(secrets, secret)\n\t}\n\n\tlogrus.WithField(\"count\", len(secrets)).Infoln(\"Finished processing the secrets.\")\n\treturn secrets, nil\n}", "func (s *ActionsService) ListEnvSecrets(ctx context.Context, repoID int, env string, opts *ListOptions) (*Secrets, *Response, error) {\n\turl := fmt.Sprintf(\"repositories/%v/environments/%v/secrets\", repoID, env)\n\treturn s.listSecrets(ctx, url, opts)\n}", "func (l *Libvirt) ListAllSecrets() ([]*Secret, error) {\n\treq := libvirt.RemoteConnectListAllSecretsReq{\n\t\tNeedResults: 1,\n\t\tFlags: 0}\n\tres := libvirt.RemoteConnectListAllSecretsRes{}\n\n\tbuf, err := encode(&req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := l.send(libvirt.RemoteProcConnectListAllSecrets, 0, libvirt.MessageTypeCall, libvirt.RemoteProgram, libvirt.MessageStatusOK, &buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr := <-resp\n\tif r.Header.Status != libvirt.MessageStatusOK {\n\t\treturn nil, decodeError(r.Payload)\n\t}\n\n\tdec := xdr.NewDecoder(bytes.NewReader(r.Payload))\n\t_, err = dec.Decode(&res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar secrets []*Secret\n\tfor _, secret := range res.Secrets {\n\t\tsecrets = append(secrets, &Secret{l: l, RemoteSecret: secret})\n\t}\n\treturn secrets, nil\n}", "func (r *SecretsResource) List(request *http.Request) (interface{}, error) {\n\treturn r.secrets.List(request.Context(), api.SecretListFilter{\n\t\tURL: request.FormValue(\"url\"),\n\t\tTag: request.FormValue(\"tag\"),\n\t\tType: api.SecretType(request.FormValue(\"type\")),\n\t\tName: request.FormValue(\"name\"),\n\t\tDeleted: request.FormValue(\"deleted\") == \"true\",\n\t})\n}", "func (l *Libvirt) Secrets() ([]Secret, error) {\n\tsecrets, _, err := l.ConnectListAllSecrets(1, 0)\n\treturn secrets, err\n}", "func (t envTemplate) Secrets() []string {\n\treturn []string{}\n}", "func ReconcileSecrets(ctx context.Context, namedGetters []NamedSecretCreatorGetter, namespace string, client ctrlruntimeclient.Client, objectModifiers ...ObjectModifier) error {\n\tfor _, get := range namedGetters {\n\t\tname, create := get()\n\t\tcreateObject := SecretObjectWrapper(create)\n\t\tcreateObject = createWithNamespace(createObject, namespace)\n\t\tcreateObject = createWithName(createObject, name)\n\n\t\tfor _, objectModifier := range objectModifiers {\n\t\t\tcreateObject = objectModifier(createObject)\n\t\t}\n\n\t\tif err := EnsureNamedObject(ctx, types.NamespacedName{Namespace: namespace, Name: name}, createObject, client, &corev1.Secret{}, false); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to ensure Secret %s/%s: %v\", namespace, name, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *secrets) List(ctx context.Context, opts metav1.ListOptions) (result *v1.SecretList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\n\tresult = &v1.SecretList{}\n\terr = c.client.Get().\n\t\tResource(\"secrets\").\n\t\tVersionedParams(opts).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\n\treturn\n}", "func (m *Synchronization) GetSecrets()([]SynchronizationSecretKeyStringValuePairable) {\n val, err := m.GetBackingStore().Get(\"secrets\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]SynchronizationSecretKeyStringValuePairable)\n }\n return nil\n}", "func (s *Secrets) List(ctx context.Context, ns, labelSelector string) ([]v1.Secret, error) {\n\tsList, err := s.k8sClient.CoreV1().Secrets(ns).List(ctx, metav1.ListOptions{LabelSelector: labelSelector})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn sList.Items, nil\n}", "func (c *GoClient) GetSecretList(namespace string) (*corev1.SecretList, error) {\n\tresources, err := c.client.CoreV1().Secrets(namespace).List(context.TODO(), metav1.ListOptions{})\n\treturn resources, errors.WithStack(err)\n}", "func (e EnvFile) Secrets() []string {\n\treturn e.env.Secrets()\n}", "func (o EnvironmentDaprComponentOutput) Secrets() EnvironmentDaprComponentSecretArrayOutput {\n\treturn o.ApplyT(func(v *EnvironmentDaprComponent) EnvironmentDaprComponentSecretArrayOutput { return v.Secrets }).(EnvironmentDaprComponentSecretArrayOutput)\n}", "func (secretsManager *SecretsManagerV2) ListSecrets(listSecretsOptions *ListSecretsOptions) (result *SecretMetadataPaginatedCollection, response *core.DetailedResponse, err error) {\n\treturn secretsManager.ListSecretsWithContext(context.Background(), listSecretsOptions)\n}", "func (a *EnvironmentSecretApiService) ListEnvironmentSecrets(ctx _context.Context, environmentId string) ApiListEnvironmentSecretsRequest {\n\treturn ApiListEnvironmentSecretsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tenvironmentId: environmentId,\n\t}\n}", "func (r *syncCommand) applySecrets(secrets []*api.Secret) error {\n\tlog.Infof(\"%s\", color.GreenString(\"-> synchronizing the secrets with vault, secrets: %d\", len(secrets)))\n\n\tfor _, s := range secrets {\n\t\t// step: validate the secret\n\t\tif err := s.IsValid(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Infof(\"[secret: %s] adding the secret\", s.Path)\n\n\t\t// step: apply the secret\n\t\tif err := r.client.AddSecret(s); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r *ReconcileVaultSecret) Reconcile(request reconcile.Request) (reconcile.Result, error) {\n\tlog.Printf(\"Reconciling VaultSecret %s/%s\\n\", request.Namespace, request.Name)\n\n\t// Fetch the VaultSecret instance\n\tinstance := &crdv1alpha1.VaultSecret{}\n\terr := r.client.Get(context.TODO(), request.NamespacedName, instance)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// Request object not found, could have been deleted after reconcile request.\n\t\t\t// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.\n\t\t\t// Return and don't requeue\n\t\t\treturn reconcile.Result{}, nil\n\t\t}\n\t\t// Error reading the object - requeue the request.\n\t\treturn reconcile.Result{}, err\n\t}\n\n\t// Define a new Secret object\n\tsecret := newSecretForCR(instance)\n\n\t// Set VaultSecret instance as the owner and controller\n\tif err := controllerutil.SetControllerReference(instance, secret, r.scheme); err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\n\trefreshRate := time.Duration(30)\n\n\t// Check if this Secret already exists\n\tfound := &corev1.Secret{}\n\terr = r.client.Get(context.TODO(), types.NamespacedName{Name: secret.Name, Namespace: secret.Namespace}, found)\n\tif err != nil && errors.IsNotFound(err) {\n\t\tlog.Printf(\"Creating a new Secret %s/%s\\n\", secret.Namespace, secret.Name)\n\t\terr = r.client.Create(context.TODO(), secret)\n\t\tif err != nil {\n\t\t\treturn reconcile.Result{}, err\n\t\t}\n\n\t\t// Secret created successfully - requeue after x seconds\n\t\treturn reconcile.Result{Requeue: true, RequeueAfter: time.Second*refreshRate}, nil\n\t} else if err != nil {\n\t\treturn reconcile.Result{Requeue: true, RequeueAfter: time.Second*refreshRate}, err\n\t}\n\n\t// Secret already exists - update and requeue\n\tlog.Printf(\"Secret %s/%s already exists, updating...\", found.Namespace, found.Name)\n\terr = r.client.Update(context.TODO(), secret)\n\tif err != nil {\n\t\treturn reconcile.Result{}, err\n\t}\n\treturn reconcile.Result{Requeue: true, RequeueAfter: time.Second*refreshRate}, nil\n}", "func (o TriggerBuildOutput) Secrets() TriggerBuildSecretArrayOutput {\n\treturn o.ApplyT(func(v TriggerBuild) []TriggerBuildSecret { return v.Secrets }).(TriggerBuildSecretArrayOutput)\n}", "func (c *Client) ListSecrets(ctx context.Context, params *ListSecretsInput, optFns ...func(*Options)) (*ListSecretsOutput, error) {\n\tif params == nil {\n\t\tparams = &ListSecretsInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"ListSecrets\", params, optFns, addOperationListSecretsMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*ListSecretsOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (s *k8sStore) syncSecrets(ing *networkingv1.Ingress) {\n\tkey := ik8s.MetaNamespaceKey(ing)\n\tfor _, secrKey := range s.secretIngressMap.getSecretKeys(key) {\n\t\ts.syncSecret(secrKey)\n\t}\n}", "func (c *Client) ListSecrets(ctx context.Context, params *ListSecretsInput, optFns ...func(*Options)) (*ListSecretsOutput, error) {\n\tif params == nil {\n\t\tparams = &ListSecretsInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"ListSecrets\", params, optFns, c.addOperationListSecretsMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*ListSecretsOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (c *Client) ListSecretVersions(secretBlindName string, withData bool) ([]*api.EncryptedSecretVersion, error) {\n\tout := []*api.EncryptedSecretVersion{}\n\trawURL := fmt.Sprintf(pathSecretVersions+\"?encrypted_blob=%t\", c.base.String(), secretBlindName, withData)\n\terr := c.get(rawURL, true, &out)\n\treturn out, errio.Error(err)\n}", "func (r *VaultSecretReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\tlog := logr.FromContext(ctx)\n\n\t// Set reconciliation if the vault-secret does not specify a version.\n\treconcileResult := ctrl.Result{}\n\tif vault.ReconciliationTime > 0 {\n\t\treconcileResult = ctrl.Result{\n\t\t\tRequeueAfter: time.Second * time.Duration(vault.ReconciliationTime),\n\t\t}\n\t}\n\n\t// Fetch the VaultSecret instance\n\tinstance := &ricobergerdev1alpha1.VaultSecret{}\n\n\terr := r.Get(ctx, req.NamespacedName, instance)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// Request object not found, could have been deleted after reconcile request.\n\t\t\t// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.\n\t\t\t// Return and don't requeue\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\t\t// Error reading the object - requeue the request.\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Check if the VaultSecret instance is marked to be deleted, which is\n // indicated by the deletion timestamp being set. The object will be deleted.\n isVaultSecretMarkedToBeDeleted := instance.GetDeletionTimestamp() != nil\n if isVaultSecretMarkedToBeDeleted {\n return ctrl.Result{}, nil\n }\n\n\t// Get secret from Vault.\n\t// If the VaultSecret contains the vaulRole property we are creating a new client with the specified Vault Role to\n\t// get the secret.\n\t// When the property isn't set we are using the shared client. It is also possible that the shared client is nil, so\n\t// that we have to check for this first. This could happen since we do not return an error when we initializing the\n\t// client during start up, to not require a default Vault Role.\n\tvar data map[string][]byte\n\n\tvar vaultClient *vault.Client\n\n\tif instance.Spec.VaultRole != \"\" {\n\t\tlog.WithValues(\"vaultRole\", instance.Spec.VaultRole).Info(\"Create client to get secret from Vault\")\n\t\tvaultClient, err = vault.CreateClient(instance.Spec.VaultRole)\n\t\tif err != nil {\n\t\t\t// Error creating the Vault client - requeue the request.\n\t\t\tr.updateConditions(ctx, instance, conditionReasonFetchFailed, err.Error(), metav1.ConditionFalse)\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t} else {\n\t\tlog.Info(\"Use shared client to get secret from Vault\")\n\t\tif vault.SharedClient == nil {\n\t\t\terr = fmt.Errorf(\"shared client not initialized and vaultRole property missing\")\n\t\t\tlog.Error(err, \"Could not get secret from Vault\")\n\t\t\tr.updateConditions(ctx, instance, conditionReasonFetchFailed, err.Error(), metav1.ConditionFalse)\n\t\t\treturn ctrl.Result{}, err\n\t\t} else {\n\t\t\tvaultClient = vault.SharedClient\n\t\t}\n\t}\n\n\tif instance.Spec.SecretEngine == \"\" || instance.Spec.SecretEngine == kvEngine {\n\t\tdata, err = vaultClient.GetSecret(instance.Spec.SecretEngine, instance.Spec.Path, instance.Spec.Keys, instance.Spec.Version, instance.Spec.IsBinary, instance.Spec.VaultNamespace)\n\t\tif err != nil {\n\t\t\t// Error while getting the secret from Vault - requeue the request.\n\t\t\tlog.Error(err, \"Could not get secret from vault\")\n\t\t\tr.updateConditions(ctx, instance, conditionReasonFetchFailed, err.Error(), metav1.ConditionFalse)\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t} else if instance.Spec.SecretEngine == pkiEngine {\n\t\tif err := ValidatePKI(instance); err != nil {\n\t\t\tlog.Error(err, \"Resource validation failed\")\n\t\t\tr.updateConditions(ctx, instance, conditionReasonInvalidResource, err.Error(), metav1.ConditionFalse)\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\n\t\tvar expiration *time.Time\n\t\tdata, expiration, err = vaultClient.GetCertificate(instance.Spec.Path, instance.Spec.Role, instance.Spec.EngineOptions)\n\t\tif err != nil {\n\t\t\tlog.Error(err, \"Could not get certificate from vault\")\n\t\t\tr.updateConditions(ctx, instance, conditionReasonFetchFailed, err.Error(), metav1.ConditionFalse)\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\n\t\t// Requeue before expiration\n\t\tlog.Info(fmt.Sprintf(\"Certificate will expire on %s\", expiration.String()))\n\t\tra := expiration.Sub(time.Now()) - vaultClient.GetPKIRenew()\n\t\tif ra <= 0 {\n\t\t\treconcileResult.Requeue = true\n\t\t} else {\n\t\t\treconcileResult.RequeueAfter = ra\n\t\t\tlog.Info(fmt.Sprintf(\"Certificate will be renewed on %s\", time.Now().Add(ra).String()))\n\t\t}\n\t}\n\n\t// Define a new Secret object\n\tsecret, err := newSecretForCR(instance, data)\n\tif err != nil {\n\t\t// Error while creating the Kubernetes secret - requeue the request.\n\t\tlog.Error(err, \"Could not create Kubernetes secret\")\n\t\tr.updateConditions(ctx, instance, conditionReasonCreateFailed, err.Error(), metav1.ConditionFalse)\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Set VaultSecret instance as the owner and controller\n\terr = ctrl.SetControllerReference(instance, secret, r.Scheme)\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Check if this Secret already exists\n\tfound := &corev1.Secret{}\n\terr = r.Get(ctx, types.NamespacedName{Name: secret.Name, Namespace: secret.Namespace}, found)\n\tif err != nil && errors.IsNotFound(err) {\n\t\tlog.Info(\"Creating a new Secret\", \"Secret.Namespace\", secret.Namespace, \"Secret.Name\", secret.Name)\n\t\terr = r.Create(ctx, secret)\n\t\tif err != nil {\n\t\t\tlog.Error(err, \"Could not create secret\")\n\t\t\tr.updateConditions(ctx, instance, conditionReasonCreateFailed, err.Error(), metav1.ConditionFalse)\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\n\t\t// Secret created successfully - requeue only if no version is specified\n\t\tr.updateConditions(ctx, instance, conditionReasonCreated, \"Secret was created\", metav1.ConditionTrue)\n\t\treturn reconcileResult, nil\n\t} else if err != nil {\n\t\tlog.Error(err, \"Could not create secret\")\n\t\tr.updateConditions(ctx, instance, conditionReasonCreateFailed, err.Error(), metav1.ConditionFalse)\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Secret already exists, update the secret\n\t// Merge -> Checks the existing data keys and merge them into the updated secret\n\t// Replace -> Do not check the data keys and replace the secret\n\tif instance.Spec.ReconcileStrategy == \"Merge\" {\n\t\tsecret = mergeSecretData(secret, found)\n\n\t\tlog.Info(\"Updating a Secret\", \"Secret.Namespace\", secret.Namespace, \"Secret.Name\", secret.Name)\n\t\terr = r.Update(ctx, secret)\n\t\tif err != nil {\n\t\t\tlog.Error(err, \"Could not update secret\")\n\t\t\tr.updateConditions(ctx, instance, conditionReasonMergeFailed, err.Error(), metav1.ConditionFalse)\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\tr.updateConditions(ctx, instance, conditionReasonUpdated, \"Secret was updated\", metav1.ConditionTrue)\n\t} else {\n\t\tlog.Info(\"Updating a Secret\", \"Secret.Namespace\", secret.Namespace, \"Secret.Name\", secret.Name)\n\t\terr = r.Update(ctx, secret)\n\t\tif err != nil {\n\t\t\tlog.Error(err, \"Could not update secret\")\n\t\t\tr.updateConditions(ctx, instance, conditionReasonUpdateFailed, err.Error(), metav1.ConditionFalse)\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\tr.updateConditions(ctx, instance, conditionReasonUpdated, \"Secret was updated\", metav1.ConditionTrue)\n\t}\n\n\t// Secret updated successfully - requeue only if no version is specified\n\treturn reconcileResult, nil\n}", "func (l *Libvirt) ConnectListSecrets(Maxuuids int32) (rUuids []string, err error) {\n\tvar buf []byte\n\n\targs := ConnectListSecretsArgs {\n\t\tMaxuuids: Maxuuids,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar r response\n\tr, err = l.requestStream(140, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Uuids: []string\n\t_, err = dec.Decode(&rUuids)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func configEditorCredentialsSecretFrom(objs []client.Object) string {\n\tfor _, obj := range objs {\n\t\tif !strings.Contains(obj.GetName(), \"quay-config-editor-credentials\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tgvk := obj.GetObjectKind().GroupVersionKind()\n\t\tif gvk.Version != \"v1\" {\n\t\t\tcontinue\n\t\t}\n\t\tif gvk.Kind != \"Secret\" {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn obj.GetName()\n\t}\n\treturn \"\"\n}", "func (c *Client) ListSecretKeys(secretBlindName string) ([]*api.EncryptedSecretKey, error) {\n\tout := []*api.EncryptedSecretKey{}\n\trawURL := fmt.Sprintf(pathSecretKeys, c.base.String(), secretBlindName)\n\terr := c.get(rawURL, true, &out)\n\treturn out, errio.Error(err)\n}", "func (s Secrets) ListDeleted(ctx context.Context, maxResults int32) ([]Deleted, error) {\n\treturn s.Ops.Secrets().ListDeleted(ctx, maxResults)\n}", "func (m *ApplicationResource) ListClientSecretsForApplication(ctx context.Context, appId string) ([]*ClientSecret, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/apps/%v/credentials/secrets\", appId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar clientSecret []*ClientSecret\n\n\tresp, err := rq.Do(ctx, req, &clientSecret)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn clientSecret, resp, nil\n}", "func (s *secretRenewer) Secrets() secrets {\n\ts.m.RLock()\n\tdefer s.m.RUnlock()\n\treturn secrets{\n\t\tRoots: s.roots,\n\t\tCertificates: s.certificates,\n\t}\n}", "func secretsByteList(secrets []string) [][][]byte {\n\tvar s [][][]byte\n\tfor _, secret := range secrets {\n\t\tlines, lastLine := splitAfterNewline([]byte(secret))\n\t\tif lines == nil && lastLine == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar secretLines [][]byte\n\t\tif lines != nil {\n\t\t\tsecretLines = append(secretLines, lines...)\n\t\t}\n\t\tif lastLine != nil {\n\t\t\tsecretLines = append(secretLines, lastLine)\n\t\t}\n\t\ts = append(s, secretLines)\n\t}\n\treturn s\n}", "func (o *InlineResponse2002) SetSecrets(v []Secret) {\n\to.Secrets = &v\n}", "func (a *apiServer) ListSecret(ctx context.Context, in *emptypb.Empty) (response *pps.SecretInfos, retErr error) {\n\tmetricsFn := metrics.ReportUserAction(ctx, a.reporter, \"ListSecret\")\n\tdefer func(start time.Time) { metricsFn(start, retErr) }(time.Now())\n\n\tsecrets, err := a.env.KubeClient.CoreV1().Secrets(a.namespace).List(ctx, metav1.ListOptions{\n\t\tLabelSelector: \"secret-source=pachyderm-user\",\n\t})\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to list secrets\")\n\t}\n\tsecretInfos := []*pps.SecretInfo{}\n\tfor _, s := range secrets.Items {\n\t\tsecretInfos = append(secretInfos, &pps.SecretInfo{\n\t\t\tSecret: &pps.Secret{\n\t\t\t\tName: s.Name,\n\t\t\t},\n\t\t\tType: string(s.Type),\n\t\t\tCreationTimestamp: timestamppb.New(s.GetCreationTimestamp().Time),\n\t\t})\n\t}\n\n\treturn &pps.SecretInfos{\n\t\tSecretInfo: secretInfos,\n\t}, nil\n}", "func (o ContainerV1Output) SecretRefs() ContainerV1SecretRefArrayOutput {\n\treturn o.ApplyT(func(v *ContainerV1) ContainerV1SecretRefArrayOutput { return v.SecretRefs }).(ContainerV1SecretRefArrayOutput)\n}", "func ListArtifactCredentials(c *gin.Context) {\n\tresponse := ArtifactsCredentials{\n\t\tArtifactsCredential{\n\t\t\tName: \"helm-stable\",\n\t\t\tTypes: []string{\n\t\t\t\t\"helm/chart\",\n\t\t\t},\n\t\t},\n\t\tArtifactsCredential{\n\t\t\tName: \"embedded-artifact\",\n\t\t\tTypes: []string{\n\t\t\t\t\"embedded/base64\",\n\t\t\t},\n\t\t},\n\t}\n\tc.JSON(http.StatusOK, response)\n}", "func UpdateSecrets(kubeClient *kubernetes.Clientset, secrets []string) error {\n\tsuccChan, errChan := make(chan string), make(chan error)\n\n\tfor _, secret := range secrets {\n\t\tgo updateSecret(kubeClient, secret, succChan, errChan)\n\t}\n\tfor i := 0; i < len(secrets); i++ {\n\t\tselect {\n\t\tcase successMsg := <-succChan:\n\t\t\tfmt.Println(successMsg)\n\t\tcase err := <-errChan:\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n\treturn nil\n}", "func ResolveSecrets(ctx context.Context, client client.Client, secretRefs []v1alpha1.ObjectReference) ([]corev1.Secret, error) {\n\tsecrets := make([]corev1.Secret, len(secretRefs))\n\tfor i, secretRef := range secretRefs {\n\t\tsecret := corev1.Secret{}\n\t\t// todo: check for cache\n\t\tif err := client.Get(ctx, secretRef.NamespacedName(), &secret); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsecrets[i] = secret\n\t}\n\treturn secrets, nil\n}", "func (cc *CredsConfig) GetSecretsCreds(id string) map[string]string {\n\treturn cc.Secrets[id]\n}", "func (r *Reconciler) ReconcileSecretAdmin() error {\n\n\tlog := r.Logger.WithField(\"func\", \"ReconcileSecretAdmin\")\n\n\tutil.KubeCheck(r.SecretAdmin)\n\tutil.SecretResetStringDataFromData(r.SecretAdmin)\n\n\tns := r.Request.Namespace\n\tname := r.Request.Name\n\tsecretAdminName := name + \"-admin\"\n\n\tr.SecretAdmin = &corev1.Secret{}\n\terr := r.GetObject(secretAdminName, r.SecretAdmin)\n\tif err == nil {\n\t\treturn nil\n\t}\n\tif !errors.IsNotFound(err) {\n\t\tlog.Errorf(\"Failed getting admin secret: %v\", err)\n\t\treturn err\n\t}\n\n\tr.SecretAdmin = &corev1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: ns,\n\t\t\tName: secretAdminName,\n\t\t\tLabels: map[string]string{\"app\": \"noobaa\"},\n\t\t},\n\t\tType: corev1.SecretTypeOpaque,\n\t\tStringData: map[string]string{\n\t\t\t\"system\": name,\n\t\t\t\"email\": options.AdminAccountEmail,\n\t\t\t\"password\": string(r.SecretOp.Data[\"password\"]),\n\t\t},\n\t}\n\n\tlog.Infof(\"listing accounts\")\n\tres, err := r.NBClient.ListAccountsAPI()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, account := range res.Accounts {\n\t\tif account.Email == options.AdminAccountEmail {\n\t\t\tif len(account.AccessKeys) > 0 {\n\t\t\t\tr.SecretAdmin.StringData[\"AWS_ACCESS_KEY_ID\"] = account.AccessKeys[0].AccessKey\n\t\t\t\tr.SecretAdmin.StringData[\"AWS_SECRET_ACCESS_KEY\"] = account.AccessKeys[0].SecretKey\n\t\t\t}\n\t\t}\n\t}\n\n\tr.Own(r.SecretAdmin)\n\treturn r.Client.Create(r.Ctx, r.SecretAdmin)\n}", "func (o TriggerBuildStepOutput) SecretEnvs() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v TriggerBuildStep) []string { return v.SecretEnvs }).(pulumi.StringArrayOutput)\n}", "func (secretsManager *SecretsManagerV2) ListSecretsWithContext(ctx context.Context, listSecretsOptions *ListSecretsOptions) (result *SecretMetadataPaginatedCollection, response *core.DetailedResponse, err error) {\n\terr = core.ValidateStruct(listSecretsOptions, \"listSecretsOptions\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbuilder := core.NewRequestBuilder(core.GET)\n\tbuilder = builder.WithContext(ctx)\n\tbuilder.EnableGzipCompression = secretsManager.GetEnableGzipCompression()\n\t_, err = builder.ResolveRequestURL(secretsManager.Service.Options.URL, `/api/v2/secrets`, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor headerName, headerValue := range listSecretsOptions.Headers {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\n\tsdkHeaders := common.GetSdkHeaders(\"secrets_manager\", \"V2\", \"ListSecrets\")\n\tfor headerName, headerValue := range sdkHeaders {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\tbuilder.AddHeader(\"Accept\", \"application/json\")\n\n\tif listSecretsOptions.Offset != nil {\n\t\tbuilder.AddQuery(\"offset\", fmt.Sprint(*listSecretsOptions.Offset))\n\t}\n\tif listSecretsOptions.Limit != nil {\n\t\tbuilder.AddQuery(\"limit\", fmt.Sprint(*listSecretsOptions.Limit))\n\t}\n\tif listSecretsOptions.Sort != nil {\n\t\tbuilder.AddQuery(\"sort\", fmt.Sprint(*listSecretsOptions.Sort))\n\t}\n\tif listSecretsOptions.Search != nil {\n\t\tbuilder.AddQuery(\"search\", fmt.Sprint(*listSecretsOptions.Search))\n\t}\n\tif listSecretsOptions.Groups != nil {\n\t\tbuilder.AddQuery(\"groups\", strings.Join(listSecretsOptions.Groups, \",\"))\n\t}\n\n\trequest, err := builder.Build()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar rawResponse map[string]json.RawMessage\n\tresponse, err = secretsManager.Service.Request(request, &rawResponse)\n\tif err != nil {\n\t\treturn\n\t}\n\tif rawResponse != nil {\n\t\terr = core.UnmarshalModel(rawResponse, \"\", &result, UnmarshalSecretMetadataPaginatedCollection)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tresponse.Result = result\n\t}\n\n\treturn\n}", "func (o TriggerBuildOptionsOutput) SecretEnvs() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v TriggerBuildOptions) []string { return v.SecretEnvs }).(pulumi.StringArrayOutput)\n}", "func (k *FileKeystore) List() ([]string, error) {\n\tk.RLock()\n\tdefer k.RUnlock()\n\n\tkeys := make([]string, 0, len(k.secrets))\n\tfor key := range k.secrets {\n\t\tkeys = append(keys, key)\n\t}\n\n\treturn keys, nil\n}", "func (o *InlineResponse2002) GetSecrets() []Secret {\n\tif o == nil || o.Secrets == nil {\n\t\tvar ret []Secret\n\t\treturn ret\n\t}\n\treturn *o.Secrets\n}", "func (o GithubEnterpriseConfigOutput) Secrets() GitHubEnterpriseSecretsResponseOutput {\n\treturn o.ApplyT(func(v *GithubEnterpriseConfig) GitHubEnterpriseSecretsResponseOutput { return v.Secrets }).(GitHubEnterpriseSecretsResponseOutput)\n}", "func (c *Channel) GetNeedRegisterSecrets(blockNumber int64) (secrets []common.Hash) {\n\tfor _, l := range c.PartnerState.Lock2UnclaimedLocks {\n\t\tif l.Lock.Expiration > blockNumber-int64(c.RevealTimeout) && l.Lock.Expiration < blockNumber {\n\t\t\t//底层负责处理重复的问题\n\t\t\tsecrets = append(secrets, l.Secret)\n\t\t}\n\t}\n\treturn\n}", "func DeleteSecrets(t *testing.T, ctx framework.TestContext, credNames []string) { // nolint:interfacer\n\tistioCfg := istio.DefaultConfigOrFail(t, ctx)\n\tsystemNS := namespace.ClaimOrFail(t, ctx, istioCfg.SystemNamespace)\n\tkubeAccessor := ctx.Environment().(*kube.Environment).Accessor\n\tfor _, cn := range credNames {\n\t\terr := kubeAccessor.DeleteSecret(systemNS.Name(), cn)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to delete secret (error: %s)\", err)\n\t\t}\n\t}\n\t// Check if Kubernetes secret is deleted\n\tmaxRetryNumber := 5\n\tcheckRetryInterval := time.Second * 1\n\tfor _, cn := range credNames {\n\t\tt.Logf(\"Check ingress Kubernetes secret %s:%s...\", systemNS.Name(), cn)\n\t\tfor i := 0; i < maxRetryNumber; i++ {\n\t\t\t_, err := kubeAccessor.GetSecret(systemNS.Name()).Get(cn, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\tt.Logf(\"Secret %s:%s is deleted\", systemNS.Name(), cn)\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tt.Logf(\"Secret %s:%s still exists.\", systemNS.Name(), cn)\n\t\t\t\ttime.Sleep(checkRetryInterval)\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *FakeAzureKeyVaultEnvSecrets) List(opts v1.ListOptions) (result *v1alpha1.AzureKeyVaultEnvSecretList, err error) {\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewListAction(azurekeyvaultenvsecretsResource, azurekeyvaultenvsecretsKind, c.ns, opts), &v1alpha1.AzureKeyVaultEnvSecretList{})\n\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\tlabel, _, _ := testing.ExtractFromListOptions(opts)\n\tif label == nil {\n\t\tlabel = labels.Everything()\n\t}\n\tlist := &v1alpha1.AzureKeyVaultEnvSecretList{ListMeta: obj.(*v1alpha1.AzureKeyVaultEnvSecretList).ListMeta}\n\tfor _, item := range obj.(*v1alpha1.AzureKeyVaultEnvSecretList).Items {\n\t\tif label.Matches(labels.Set(item.Labels)) {\n\t\t\tlist.Items = append(list.Items, item)\n\t\t}\n\t}\n\treturn list, err\n}", "func (r *Reconciler) ReconcileSecretServer() error {\n\tutil.KubeCheck(r.SecretServer)\n\tutil.SecretResetStringDataFromData(r.SecretServer)\n\n\tif r.SecretServer.StringData[\"jwt\"] == \"\" {\n\t\tr.SecretServer.StringData[\"jwt\"] = util.RandomBase64(16)\n\t}\n\tif r.SecretServer.StringData[\"server_secret\"] == \"\" {\n\t\tr.SecretServer.StringData[\"server_secret\"] = util.RandomHex(4)\n\t}\n\tr.Own(r.SecretServer)\n\tutil.KubeCreateSkipExisting(r.SecretServer)\n\treturn nil\n}", "func (o TriggerBuildOptionsPtrOutput) SecretEnvs() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *TriggerBuildOptions) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.SecretEnvs\n\t}).(pulumi.StringArrayOutput)\n}", "func (c *Controller) Secrets() typedv1.SecretInterface {\n\treturn c.client.Secrets(c.namespace.Name)\n}", "func (c *Controller) secretsUsedByPeers(meta metav1.ObjectMeta) (sets.String, error) {\n\tsecretUsed := sets.NewString()\n\n\tdbList, err := c.pgLister.Postgreses(meta.Namespace).List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, es := range dbList {\n\t\tif es.Name != meta.Name {\n\t\t\tsecretUsed.Insert(es.Spec.GetSecrets()...)\n\t\t}\n\t}\n\n\tlabelMap := map[string]string{\n\t\tapi.LabelDatabaseKind: api.ResourceKindPostgres,\n\t}\n\tdrmnList, err := c.ExtClient.KubedbV1alpha1().DormantDatabases(meta.Namespace).List(\n\t\tmetav1.ListOptions{\n\t\t\tLabelSelector: labels.SelectorFromSet(labelMap).String(),\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, ddb := range drmnList.Items {\n\t\tif ddb.Name != meta.Name {\n\t\t\tsecretUsed.Insert(ddb.GetDatabaseSecrets()...)\n\t\t}\n\t}\n\n\treturn secretUsed, nil\n}", "func GetSecretNames(host string, verifyTLS bool, apiKey string, project string, config string, includeDynamicSecrets bool) ([]string, Error) {\n\tvar params []queryParam\n\tparams = append(params, queryParam{Key: \"project\", Value: project})\n\tparams = append(params, queryParam{Key: \"config\", Value: config})\n\tparams = append(params, queryParam{Key: \"include_dynamic_secrets\", Value: strconv.FormatBool(includeDynamicSecrets)})\n\n\turl, err := generateURL(host, \"/v3/configs/config/secrets/names\", params)\n\tif err != nil {\n\t\treturn nil, Error{Err: err, Message: \"Unable to generate url\"}\n\t}\n\n\tstatusCode, _, response, err := GetRequest(url, verifyTLS, apiKeyHeader(apiKey))\n\tif err != nil {\n\t\treturn nil, Error{Err: err, Message: \"Unable to fetch secret names\", Code: statusCode}\n\t}\n\n\tvar result struct {\n\t\tNames []string `json:\"names\"`\n\t}\n\terr = json.Unmarshal(response, &result)\n\tif err != nil {\n\t\treturn nil, Error{Err: err, Message: \"Unable to parse API response\", Code: statusCode}\n\t}\n\n\treturn result.Names, Error{}\n}", "func (s *STFConfig) PullSecrets() []corev1.LocalObjectReference {\n\tsecrets := make([]corev1.LocalObjectReference, 0)\n\tif s.STFImage != nil {\n\t\tif s.STFImage.ImagePullSecrets != nil {\n\t\t\tsecrets = append(secrets, s.STFImage.ImagePullSecrets...)\n\t\t}\n\t}\n\tif s.ADB != nil {\n\t\tif s.ADB.ImagePullSecrets != nil {\n\t\t\tsecrets = append(secrets, s.ADB.ImagePullSecrets...)\n\t\t}\n\t}\n\treturn secrets\n}", "func getSecretsToRotate(client *k8s.Client, namespace string) (error, *corev1.SecretList) {\n\n\tl := new(k8s.LabelSelector)\n\tl.Eq(rotateKeyLabel, \"true\")\n\n\tvar secrets corev1.SecretList\n\tif err := client.List(context.TODO(), namespace, &secrets, l.Selector()); err != nil {\n\t\treturn err, nil\n\t}\n\treturn nil, &secrets\n}", "func (s SecretWatchableSet) Get() ([]WatchableResource, string, error) {\n\t// Query the initial list of Namespaces\n\t// TODO: Limit namespaces to only namespaces with label\n\tk8sSecrets, err := s.KubeClient.Core().Secrets(api.NamespaceAll).List(api.ListOptions{})\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\t// Filter out the secrets that are not router API Key secrets or that do not have the proper secret key\n\tsecrets := []WatchableResource{}\n\n\t// Filter secrets that have the APIKeySecret name\n\tfor _, secret := range k8sSecrets.Items {\n\t\tif secret.Name == s.Config.APIKeySecret {\n\t\t\tsecrets = append(secrets, s.ConvertToModel(&secret))\n\t\t}\n\t}\n\n\treturn secrets, k8sSecrets.ListMeta.ResourceVersion, nil\n}", "func (c *Cluster) GetSecrets(options apitypes.SecretListOptions) ([]types.Secret, error) {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\n\tstate := c.currentNodeState()\n\tif !state.IsActiveManager() {\n\t\treturn nil, c.errNoManager(state)\n\t}\n\n\tfilters, err := newListSecretsFilters(options.Filters)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tctx, cancel := c.getRequestContext()\n\tdefer cancel()\n\n\tr, err := state.controlClient.ListSecrets(ctx,\n\t\t&swarmapi.ListSecretsRequest{Filters: filters})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsecrets := []types.Secret{}\n\n\tfor _, secret := range r.Secrets {\n\t\tsecrets = append(secrets, convert.SecretFromGRPC(secret))\n\t}\n\n\treturn secrets, nil\n}", "func makeSecrets(secretNames []string) *v1.SecretList {\n\tvar secrets []v1.Secret\n\tfor _, secretName := range secretNames {\n\t\tobjMeta := metav1.ObjectMeta{Name: secretName}\n\t\tsecrets = append(secrets, v1.Secret{ObjectMeta: objMeta})\n\t}\n\treturn &v1.SecretList{Items: secrets}\n}", "func maskSecrets(values, secrets []string) []string {\n\tout := make([]string, len(values))\n\tfor vIndex, value := range values {\n\t\tout[vIndex] = value\n\t}\n\tfor _, secret := range secrets {\n\t\tfor vIndex, value := range out {\n\t\t\tout[vIndex] = strings.Replace(value, secret, \"###\", -1)\n\t\t}\n\t}\n\treturn out\n}", "func ExampleAuthorizationServerClient_ListSecrets() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armapimanagement.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewAuthorizationServerClient().ListSecrets(ctx, \"rg1\", \"apimService1\", \"newauthServer2\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.AuthorizationServerSecretsContract = armapimanagement.AuthorizationServerSecretsContract{\n\t// \tClientSecret: to.Ptr(\"2\"),\n\t// \tResourceOwnerPassword: to.Ptr(\"pwd\"),\n\t// \tResourceOwnerUsername: to.Ptr(\"un\"),\n\t// }\n}", "func computeSecretNames(secretList []corev1.Secret) sets.String {\n\tnames := sets.NewString()\n\n\tfor _, secret := range secretList {\n\t\tif secret.Type != corev1.SecretTypeOpaque {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, ownerRef := range secret.OwnerReferences {\n\t\t\tif ownerRef.APIVersion == gardencorev1beta1.SchemeGroupVersion.String() && ownerRef.Kind == \"Shoot\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tnames.Insert(secret.Name)\n\t}\n\n\treturn names\n}", "func (o TriggerBuildPtrOutput) Secrets() TriggerBuildSecretArrayOutput {\n\treturn o.ApplyT(func(v *TriggerBuild) []TriggerBuildSecret {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Secrets\n\t}).(TriggerBuildSecretArrayOutput)\n}", "func (tc *Configs) ListRemotes() error {\n\tfor _, tf := range tc.Files {\n\t\ttc.StdOut.Write([]byte(color.Green(fmt.Sprintf(\"(%s) %s\\n\", tf.Basename(), tf.Filepath))))\n\t\tif err := tf.Remotes.List(tc.StdOut); err != nil {\n\t\t\ttc.StdErr.Write([]byte(color.Red(err.Error())))\n\t\t}\n\t\ttc.StdOut.Write([]byte(color.Green(\"---\\n\\n\")))\n\t}\n\treturn nil\n}", "func (input *CreateTaskDefinitionInput) Secrets() []*awsecs.Secret {\n\treturn convertSecretVars(input.SecretVars)\n}", "func (j *JobSecrets) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", j, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"dcAccessSecurityCode\":\n\t\t\terr = unpopulate(val, \"DcAccessSecurityCode\", &j.DcAccessSecurityCode)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"error\":\n\t\t\terr = unpopulate(val, \"Error\", &j.Error)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"jobSecretsType\":\n\t\t\terr = unpopulate(val, \"JobSecretsType\", &j.JobSecretsType)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"podSecrets\":\n\t\t\terr = unpopulate(val, \"PodSecrets\", &j.PodSecrets)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", j, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (s *ActionsService) ListRepoSecrets(ctx context.Context, owner, repo string, opts *ListOptions) (*Secrets, *Response, error) {\n\turl := fmt.Sprintf(\"repos/%v/%v/actions/secrets\", owner, repo)\n\treturn s.listSecrets(ctx, url, opts)\n}", "func GetAllSecret() map[string]interface{} {\n\tpath := PROJECT + \"/metadata/\" + ENV\n\treturn GetAllSecretFromPath(path)\n}", "func (nsar *NamespacedServiceAccountReflector) List() ([]interface{}, error) {\n\treturn virtualkubelet.List[virtualkubelet.Lister[*corev1.Secret], *corev1.Secret](\n\t\tnsar.remoteSecrets,\n\t)\n}", "func ExampleConnectedEnvironmentsDaprComponentsClient_ListSecrets() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armappcontainers.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewConnectedEnvironmentsDaprComponentsClient().ListSecrets(ctx, \"examplerg\", \"myenvironment\", \"reddog\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.DaprSecretsCollection = armappcontainers.DaprSecretsCollection{\n\t// \tValue: []*armappcontainers.DaprSecret{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"secret1\"),\n\t// \t\t\tValue: to.Ptr(\"value1\"),\n\t// \t\t},\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"secret2\"),\n\t// \t\t\tValue: to.Ptr(\"value2\"),\n\t// \t}},\n\t// }\n}", "func (m *Synchronization) SetSecrets(value []SynchronizationSecretKeyStringValuePairable)() {\n err := m.GetBackingStore().Set(\"secrets\", value)\n if err != nil {\n panic(err)\n }\n}", "func (s *SecretService) PatchSecrets(ctx context.Context, orgID influxdb.ID, m map[string]string) error {\n\tif err := authorizeWriteSecret(ctx, orgID); err != nil {\n\t\treturn err\n\t}\n\n\terr := s.s.PatchSecrets(ctx, orgID, m)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (d *Database) ListPasswords() ([]storage.Password, error) {\n\tpasswords, err := d.client.Password.Query().All(context.TODO())\n\tif err != nil {\n\t\treturn nil, convertDBError(\"list passwords: %w\", err)\n\t}\n\n\tstoragePasswords := make([]storage.Password, 0, len(passwords))\n\tfor _, p := range passwords {\n\t\tstoragePasswords = append(storagePasswords, toStoragePassword(p))\n\t}\n\treturn storagePasswords, nil\n}", "func QuoteList(unquoted []string) string {\n\tvar quoted = make([]string, len(unquoted))\n\tfor i, u := range unquoted {\n\t\tquoted[i] = Quote(u)\n\t}\n\n\treturn strings.Join(quoted, \" \")\n}", "func (d *driver) SyncSecrets(sec *coreapi.Secret) (map[string]string, error) {\n\tcfg, err := clusterconfig.GetAWSConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Get the existing SecretKey and AccessKey\n\tvar existingAccessKey, existingSecretKey []byte\n\tif v, ok := sec.Data[\"REGISTRY_STORAGE_S3_ACCESSKEY\"]; ok {\n\t\texistingAccessKey = v\n\t}\n\tif v, ok := sec.Data[\"REGISTRY_STORAGE_S3_SECRETKEY\"]; ok {\n\t\texistingSecretKey = v\n\t}\n\n\t// Check if the existing SecretKey and AccessKey match what we got from the cluster or user configuration\n\tif !bytes.Equal([]byte(cfg.Storage.S3.AccessKey), existingAccessKey) || !bytes.Equal([]byte(cfg.Storage.S3.SecretKey), existingSecretKey) {\n\n\t\tdata := map[string]string{\n\t\t\t\"REGISTRY_STORAGE_S3_ACCESSKEY\": cfg.Storage.S3.AccessKey,\n\t\t\t\"REGISTRY_STORAGE_S3_SECRETKEY\": cfg.Storage.S3.SecretKey,\n\t\t}\n\t\treturn data, nil\n\n\t}\n\treturn nil, nil\n}", "func (s *ContainerDefinition) SetSecrets(v []*Secret) *ContainerDefinition {\n\ts.Secrets = v\n\treturn s\n}", "func GetSecretsFromCR(r ReconcilerCommon, obj runtime.Object, namespace string, spec interface{}, envVars *map[string]util.EnvSetter) ([]cinderv1beta1.Hash, error) {\n\thashes := []cinderv1beta1.Hash{}\n\tspecParameters := make(map[string]interface{})\n\tinrec, _ := json.Marshal(spec)\n\tjson.Unmarshal(inrec, &specParameters)\n\n\tfor param, value := range specParameters {\n\t\tif strings.HasSuffix(param, \"Secret\") {\n\t\t\t_, hash, err := GetSecret(r.GetClient(), fmt.Sprintf(\"%v\", value), namespace)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t// add hash to envVars\n\t\t\t(*envVars)[param] = util.EnvValue(hash)\n\t\t\thashes = append(hashes, cinderv1beta1.Hash{Name: param, Hash: hash})\n\t\t}\n\t}\n\n\treturn hashes, nil\n}", "func (secretsManager *SecretsManagerV2) ListSecretVersionsWithContext(ctx context.Context, listSecretVersionsOptions *ListSecretVersionsOptions) (result *SecretVersionMetadataCollection, response *core.DetailedResponse, err error) {\n\terr = core.ValidateNotNil(listSecretVersionsOptions, \"listSecretVersionsOptions cannot be nil\")\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.ValidateStruct(listSecretVersionsOptions, \"listSecretVersionsOptions\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpathParamsMap := map[string]string{\n\t\t\"secret_id\": *listSecretVersionsOptions.SecretID,\n\t}\n\n\tbuilder := core.NewRequestBuilder(core.GET)\n\tbuilder = builder.WithContext(ctx)\n\tbuilder.EnableGzipCompression = secretsManager.GetEnableGzipCompression()\n\t_, err = builder.ResolveRequestURL(secretsManager.Service.Options.URL, `/api/v2/secrets/{secret_id}/versions`, pathParamsMap)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor headerName, headerValue := range listSecretVersionsOptions.Headers {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\n\tsdkHeaders := common.GetSdkHeaders(\"secrets_manager\", \"V2\", \"ListSecretVersions\")\n\tfor headerName, headerValue := range sdkHeaders {\n\t\tbuilder.AddHeader(headerName, headerValue)\n\t}\n\tbuilder.AddHeader(\"Accept\", \"application/json\")\n\n\trequest, err := builder.Build()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar rawResponse map[string]json.RawMessage\n\tresponse, err = secretsManager.Service.Request(request, &rawResponse)\n\tif err != nil {\n\t\treturn\n\t}\n\tif rawResponse != nil {\n\t\terr = core.UnmarshalModel(rawResponse, \"\", &result, UnmarshalSecretVersionMetadataCollection)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tresponse.Result = result\n\t}\n\n\treturn\n}", "func (pager *SecretsPager) GetAll() (allItems []SecretMetadataIntf, err error) {\n\treturn pager.GetAllWithContext(context.Background())\n}", "func (expDetails *ExperimentDetails) ValidateSecrets(clients ClientSets) error {\n\n\tfor _, v := range expDetails.Secrets {\n\t\tif v.Name == \"\" || v.MountPath == \"\" {\n\t\t\treturn errors.New(\"Incomplete Information in Secret, will skip execution\")\n\t\t}\n\t\terr := clients.ValidateSecrets(v.Name, expDetails)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"Unable to get Secret with Name: %v, in namespace: %v\", v.Name, expDetails.Namespace)\n\t\t}\n\t\tklog.V(0).Infof(\"Succesfully Validated Secret: %v\", v.Name)\n\t}\n\treturn nil\n}", "func (nsq *NamespaceSecretQuery) All(ctx context.Context) ([]*NamespaceSecret, error) {\n\tif err := nsq.prepareQuery(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn nsq.sqlAll(ctx)\n}", "func GetSecrets(host string, verifyTLS bool, apiKey string, project string, config string, secrets []string, includeDynamicSecrets bool, dynamicSecretsTTL time.Duration) ([]byte, Error) {\n\tvar params []queryParam\n\tparams = append(params, queryParam{Key: \"project\", Value: project})\n\tparams = append(params, queryParam{Key: \"config\", Value: config})\n\tparams = append(params, queryParam{Key: \"include_dynamic_secrets\", Value: strconv.FormatBool(includeDynamicSecrets)})\n\n\tif secrets != nil {\n\t\tparams = append(params, queryParam{Key: \"secrets\", Value: strings.Join(secrets, \",\")})\n\t}\n\n\tif dynamicSecretsTTL > 0 {\n\t\tttlSeconds := int(dynamicSecretsTTL.Seconds())\n\t\tparams = append(params, queryParam{Key: \"dynamic_secrets_ttl_sec\", Value: strconv.Itoa(ttlSeconds)})\n\t}\n\n\turl, err := generateURL(host, \"/v3/configs/config/secrets\", params)\n\tif err != nil {\n\t\treturn nil, Error{Err: err, Message: \"Unable to generate url\"}\n\t}\n\n\theaders := apiKeyHeader(apiKey)\n\theaders[\"Accept\"] = \"application/json\"\n\tstatusCode, _, response, err := GetRequest(url, verifyTLS, headers)\n\tif err != nil {\n\t\treturn nil, Error{Err: err, Message: \"Unable to fetch secrets\", Code: statusCode}\n\t}\n\n\treturn response, Error{}\n}", "func GetSecrets() Secrets {\n\treturn Secrets{\n\t\tClientID: ClientID,\n\t\tClientSecret: ClientSecret,\n\t}\n}", "func (d *Driver) List() ([]string, error) {\n\td.lockfile.Lock()\n\tdefer d.lockfile.Unlock()\n\tsecretData, err := d.getAllData()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tallID := make([]string, 0, len(secretData))\n\tfor k := range secretData {\n\t\tallID = append(allID, k)\n\t}\n\tsort.Strings(allID)\n\treturn allID, err\n}", "func (secretsManager *SecretsManagerV2) ListConfigurations(listConfigurationsOptions *ListConfigurationsOptions) (result *ConfigurationMetadataPaginatedCollection, response *core.DetailedResponse, err error) {\n\treturn secretsManager.ListConfigurationsWithContext(context.Background(), listConfigurationsOptions)\n}", "func (e *ChefEnvironment) RecipeList() []string {\n\trecipeList := make(map[string]string)\n\tcbList := e.cookbookList()\n\tfor _, cb := range cbList {\n\t\tif cb == nil {\n\t\t\tcontinue\n\t\t}\n\t\tcbv := cb.LatestConstrained(e.CookbookVersions[cb.Name])\n\t\tif cbv == nil {\n\t\t\tcontinue\n\t\t}\n\t\trlist, _ := cbv.RecipeList()\n\n\t\tfor _, recipe := range rlist {\n\t\t\trecipeList[recipe] = recipe\n\t\t}\n\t}\n\tsortedRecipes := make([]string, len(recipeList))\n\ti := 0\n\tfor k := range recipeList {\n\t\tsortedRecipes[i] = k\n\t\ti++\n\t}\n\tsort.Strings(sortedRecipes)\n\treturn sortedRecipes\n}", "func setupConfigMapReconciler(mgr manager.Manager, log logr.Logger) error {\n\n\tlog = log.WithName(\"secret-reconciler\")\n\n\terr := ctrl.NewControllerManagedBy(mgr).\n\t\tFor(&corev1.Secret{}, builder.OnlyMetadata).\n\t\tComplete(reconcile.Func(func(_ context.Context, r reconcile.Request) (reconcile.Result, error) {\n\t\t\tlog := log\n\t\t\tlog = log.WithValues(\"secret\", r.NamespacedName)\n\t\t\tlog.Info(\"start\")\n\t\t\tdefer log.Info(\"end\")\n\n\t\t\tsecret := &corev1.Secret{}\n\t\t\terr := mgr.GetClient().Get(context.Background(), r.NamespacedName, secret)\n\t\t\tswitch {\n\t\t\t// If the secret doesn't exist, the reconciliation is done.\n\t\t\tcase apierrors.IsNotFound(err):\n\t\t\t\tlog.Info(\"secret not found\")\n\t\t\t\treturn reconcile.Result{}, nil\n\t\t\tcase err != nil:\n\t\t\t\treturn reconcile.Result{}, fmt.Errorf(\"looking for Secret %s: %w\", r.NamespacedName, err)\n\t\t\t}\n\n\t\t\tif secret.Annotations != nil && secret.Annotations[\"secret-found\"] == \"yes\" {\n\t\t\t\treturn reconcile.Result{}, nil\n\t\t\t}\n\n\t\t\tif secret.Annotations == nil {\n\t\t\t\tsecret.Annotations = make(map[string]string)\n\t\t\t}\n\t\t\tsecret.Annotations[\"secret-found\"] = \"yes\"\n\t\t\terr = mgr.GetClient().Update(context.Background(), secret)\n\t\t\tif err != nil {\n\t\t\t\treturn reconcile.Result{}, err\n\t\t\t}\n\n\t\t\treturn reconcile.Result{}, nil\n\t\t}))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"while completing new controller: %w\", err)\n\t}\n\n\treturn nil\n}", "func (s *sealedSecretLister) List(selector labels.Selector) (ret []*v1alpha1.SealedSecret, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.SealedSecret))\n\t})\n\treturn ret, err\n}", "func (r *ReconcileRethinkDBCluster) reconcileAdminSecret(cr *rethinkdbv1alpha1.RethinkDBCluster) error {\n\tname := fmt.Sprintf(\"%s-%s\", cr.ObjectMeta.Name, RethinkDBAdminKey)\n\tfound := &corev1.Secret{}\n\terr := r.client.Get(context.TODO(), types.NamespacedName{Name: name, Namespace: cr.Namespace}, found)\n\tif err != nil && errors.IsNotFound(err) {\n\t\tlog.Info(\"creating new secret\", \"secret\", name)\n\t\tsecret, err := newUserSecret(cr, RethinkDBAdminKey)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Set RethinkDBCluster instance as the owner and controller\n\t\tif err = controllerutil.SetControllerReference(cr, secret, r.scheme); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Create the Secret and return\n\t\treturn r.client.Create(context.TODO(), secret)\n\t} else if err != nil {\n\t\treturn err\n\t}\n\tlog.Info(\"secret exists\", \"secret\", found.Name)\n\treturn nil\n}", "func getSecrets(targetSecret, targetType string, secrets *v1.SecretList) (foundSecrets []*v1.Secret) {\n\tvar maxVersionned int\n\tsecretReleases := make(map[string]int)\n\tsecretFamilies := make(map[string]*v1.Secret)\n\n\tfor _, secret := range secrets.Items {\n\t\tif (targetType == \"\" || string(secret.Type) == targetType) && strings.Contains(secret.Name, targetSecret) {\n\t\t\tif matchVersioned, _ := regexp.MatchString(\"^\"+targetSecret+\"-[0-9]*$\", secret.Name); matchVersioned {\n\t\t\t\tif release := getRelease(secret.Name); release >= maxVersionned {\n\t\t\t\t\tmaxVersionned = release\n\t\t\t\t\tfoundSecrets = []*v1.Secret{secret.DeepCopy()}\n\t\t\t\t}\n\t\t\t} else if len(foundSecrets) == 0 {\n\t\t\t\trelease := getRelease(secret.Name)\n\t\t\t\tfamily := strings.TrimSuffix(secret.Name, strconv.Itoa(release))\n\t\t\t\tif release >= secretReleases[family] {\n\t\t\t\t\tsecretReleases[family] = release\n\t\t\t\t\tsecretFamilies[family] = secret.DeepCopy()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Flatten families if we haven't found any perfectly matching secret\n\tif len(foundSecrets) == 0 {\n\t\tfor _, secret := range secretFamilies {\n\t\t\tfoundSecrets = append(foundSecrets, secret.DeepCopy())\n\t\t}\n\t}\n\treturn\n}", "func ListQuotas(query ...*models.QuotaQuery) ([]*Quota, error) {\n\tcondition, params := quotaQueryConditions(query...)\n\n\tsql := fmt.Sprintf(`\nSELECT\n a.id,\n a.reference,\n a.reference_id,\n a.hard,\n b.used,\n b.creation_time,\n b.update_time\nFROM\n quota AS a\n JOIN quota_usage AS b ON a.id = b.id %s`, condition)\n\n\torderBy := quotaOrderBy(query...)\n\tif orderBy != \"\" {\n\t\tsql += ` order by ` + orderBy\n\t}\n\n\tif len(query) > 0 && query[0] != nil {\n\t\tpage, size := query[0].Page, query[0].Size\n\t\tif size > 0 {\n\t\t\tsql += ` limit ?`\n\t\t\tparams = append(params, size)\n\t\t\tif page > 0 {\n\t\t\t\tsql += ` offset ?`\n\t\t\t\tparams = append(params, size*(page-1))\n\t\t\t}\n\t\t}\n\t}\n\n\tvar quotas []*Quota\n\tif _, err := GetOrmer().Raw(sql, params).QueryRows(&quotas); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, quota := range quotas {\n\t\td, ok := driver.Get(quota.Reference)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tref, err := d.Load(quota.ReferenceID)\n\t\tif err != nil {\n\t\t\tlog.Warning(fmt.Sprintf(\"Load quota reference object (%s, %s) failed: %v\", quota.Reference, quota.ReferenceID, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tquota.Ref = ref\n\t}\n\n\treturn quotas, nil\n}", "func (r *TenantReconciler) syncResourceQuotas(tenant *capsulev1alpha1.Tenant) error {\n\t// getting requested ResourceQuota keys\n\tkeys := make([]string, 0, len(tenant.Spec.ResourceQuota))\n\tfor i := range tenant.Spec.ResourceQuota {\n\t\tkeys = append(keys, strconv.Itoa(i))\n\t}\n\n\t// getting ResourceQuota labels for the mutateFn\n\ttenantLabel, err := capsulev1alpha1.GetTypeLabel(&capsulev1alpha1.Tenant{})\n\tif err != nil {\n\t\treturn err\n\t}\n\ttypeLabel, err := capsulev1alpha1.GetTypeLabel(&corev1.ResourceQuota{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, ns := range tenant.Status.Namespaces {\n\t\tif err := r.pruningResources(ns, keys, &corev1.ResourceQuota{}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i, q := range tenant.Spec.ResourceQuota {\n\t\t\ttarget := &corev1.ResourceQuota{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: fmt.Sprintf(\"capsule-%s-%d\", tenant.Name, i),\n\t\t\t\t\tNamespace: ns,\n\t\t\t\t\tAnnotations: make(map[string]string),\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\ttenantLabel: tenant.Name,\n\t\t\t\t\t\ttypeLabel: strconv.Itoa(i),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t\tres, err := controllerutil.CreateOrUpdate(context.TODO(), r.Client, target, func() (err error) {\n\t\t\t\t// Requirement to list ResourceQuota of the current Tenant\n\t\t\t\ttr, err := labels.NewRequirement(tenantLabel, selection.Equals, []string{tenant.Name})\n\t\t\t\tif err != nil {\n\t\t\t\t\tr.Log.Error(err, \"Cannot build ResourceQuota Tenant requirement\")\n\t\t\t\t}\n\t\t\t\t// Requirement to list ResourceQuota for the current index\n\t\t\t\tir, err := labels.NewRequirement(typeLabel, selection.Equals, []string{strconv.Itoa(i)})\n\t\t\t\tif err != nil {\n\t\t\t\t\tr.Log.Error(err, \"Cannot build ResourceQuota index requirement\")\n\t\t\t\t}\n\n\t\t\t\t// Listing all the ResourceQuota according to the said requirements.\n\t\t\t\t// These are required since Capsule is going to sum all the used quota to\n\t\t\t\t// sum them and get the Tenant one.\n\t\t\t\trql := &corev1.ResourceQuotaList{}\n\t\t\t\terr = r.List(context.TODO(), rql, &client.ListOptions{\n\t\t\t\t\tLabelSelector: labels.NewSelector().Add(*tr).Add(*ir),\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tr.Log.Error(err, \"Cannot list ResourceQuota\", \"tenantFilter\", tr.String(), \"indexFilter\", ir.String())\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\t// Iterating over all the options declared for the ResourceQuota,\n\t\t\t\t// summing all the used quota across different Namespaces to determinate\n\t\t\t\t// if we're hitting a Hard quota at Tenant level.\n\t\t\t\t// For this case, we're going to block the Quota setting the Hard as the\n\t\t\t\t// used one.\n\t\t\t\tfor rn, rq := range q.Hard {\n\t\t\t\t\tr.Log.Info(\"Desired hard \" + rn.String() + \" quota is \" + rq.String())\n\n\t\t\t\t\t// Getting the whole usage across all the Tenant Namespaces\n\t\t\t\t\tvar qt resource.Quantity\n\t\t\t\t\tfor _, rq := range rql.Items {\n\t\t\t\t\t\tqt.Add(rq.Status.Used[rn])\n\t\t\t\t\t}\n\t\t\t\t\tr.Log.Info(\"Computed \" + rn.String() + \" quota for the whole Tenant is \" + qt.String())\n\n\t\t\t\t\tswitch qt.Cmp(q.Hard[rn]) {\n\t\t\t\t\tcase 0:\n\t\t\t\t\t\t// The Tenant is matching exactly the Quota:\n\t\t\t\t\t\t// falling through next case since we have to block further\n\t\t\t\t\t\t// resource allocations.\n\t\t\t\t\t\tfallthrough\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\t// The Tenant is OverQuota:\n\t\t\t\t\t\t// updating all the related ResourceQuota with the current\n\t\t\t\t\t\t// used Quota to block further creations.\n\t\t\t\t\t\tfor i := range rql.Items {\n\t\t\t\t\t\t\tif _, ok := rql.Items[i].Status.Used[rn]; ok {\n\t\t\t\t\t\t\t\trql.Items[i].Spec.Hard[rn] = rql.Items[i].Status.Used[rn]\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tum := make(map[corev1.ResourceName]resource.Quantity)\n\t\t\t\t\t\t\t\tum[rn] = resource.Quantity{}\n\t\t\t\t\t\t\t\trql.Items[i].Spec.Hard = um\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t// The Tenant is respecting the Hard quota:\n\t\t\t\t\t\t// restoring the default one for all the elements,\n\t\t\t\t\t\t// also for the reconciliated one.\n\t\t\t\t\t\tfor i := range rql.Items {\n\t\t\t\t\t\t\trql.Items[i].Spec.Hard[rn] = q.Hard[rn]\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttarget.Spec = q\n\t\t\t\t\t}\n\t\t\t\t\tif err := r.resourceQuotasUpdate(rn, qt, rql.Items...); err != nil {\n\t\t\t\t\t\tr.Log.Error(err, \"cannot proceed with outer ResourceQuota\")\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn controllerutil.SetControllerReference(tenant, target, r.Scheme)\n\t\t\t})\n\t\t\tr.Log.Info(\"Resource Quota sync result: \"+string(res), \"name\", target.Name, \"namespace\", target.Namespace)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (_SecretRegistry *SecretRegistryFilterer) FilterSecretRevealed(opts *bind.FilterOpts, secret [][32]byte) (*SecretRegistrySecretRevealedIterator, error) {\n\n\tvar secretRule []interface{}\n\tfor _, secretItem := range secret {\n\t\tsecretRule = append(secretRule, secretItem)\n\t}\n\n\tlogs, sub, err := _SecretRegistry.contract.FilterLogs(opts, \"SecretRevealed\", secretRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &SecretRegistrySecretRevealedIterator{contract: _SecretRegistry.contract, event: \"SecretRevealed\", logs: logs, sub: sub}, nil\n}" ]
[ "0.57259434", "0.5530794", "0.5380004", "0.53071386", "0.5273651", "0.5255789", "0.52251434", "0.52205926", "0.5210257", "0.51597595", "0.51561975", "0.5152343", "0.51374936", "0.51229763", "0.5094752", "0.50841784", "0.50665426", "0.50590277", "0.4997374", "0.4994975", "0.49898404", "0.49666545", "0.49582323", "0.4902275", "0.48804143", "0.48764372", "0.4870767", "0.48363695", "0.48257938", "0.48228982", "0.48217928", "0.4816341", "0.47949284", "0.47887215", "0.47737128", "0.47486764", "0.47395253", "0.4719133", "0.47088355", "0.46940726", "0.4685228", "0.46791238", "0.46607658", "0.4652358", "0.46431896", "0.46385083", "0.4638246", "0.46196413", "0.46095887", "0.45934063", "0.45678544", "0.4559498", "0.4555953", "0.45416754", "0.45386076", "0.45251524", "0.45120144", "0.45112836", "0.45085225", "0.44907853", "0.448551", "0.44838235", "0.44827318", "0.4481105", "0.44731006", "0.44706622", "0.44672617", "0.4464964", "0.4463902", "0.44551912", "0.44523993", "0.44338405", "0.4433673", "0.4422235", "0.44220558", "0.44216207", "0.4418273", "0.4376854", "0.4371942", "0.4362906", "0.43594304", "0.43495166", "0.43369624", "0.43351397", "0.4330278", "0.43292725", "0.4323123", "0.43226314", "0.43189907", "0.43175444", "0.43169552", "0.43142772", "0.43106794", "0.43073753", "0.43073592", "0.43068594", "0.4305521", "0.4301968", "0.42931703", "0.4291662" ]
0.833262
0
CreateOrder cria um novo contato
func Create(responseWriter http.ResponseWriter, request *http.Request) { fmt.Println("[ CreateOrder ]") body, _ := json.Marshal(request.Body) fmt.Println("[ CreateOrder ] Body=" + string(body)) //params := mux.Vars(request) var orderEntity OrderEntity _ = json.NewDecoder(request.Body).Decode(&orderEntity) var result OrderEntity = Insert(orderEntity) WriteMessages(result, Topic.TOPIC_SUCCESS) json.NewEncoder(responseWriter).Encode(result) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (company *Company) CreateOrder(id, color, quantity, dueDate, fulfilledQuantity int) *Order {\n\torder := &Order{\n\t\tkey: keyConfiguration.NewKey(),\n\t\tid: id,\n\t\tcolor: color,\n\t\tquantity: quantity,\n\t\tdueDate: dueDate,\n\t\tfulfilledQuantity: fulfilledQuantity,\n\t\tcompany: company,\n\t\tknifeSetting: nil,\n\t}\n\n\t// Add it to company unsorted\n\tcompany.orders = append(company.orders, order)\n\n\t// Create operations for order\n\torder.createOperations()\n\n\treturn order\n}", "func CreateOrder(ctx echo.Context) error {\n\tmetrics.CaptureDelay(\"CreateOrderHandler\")()\n\tvar req CreateOrderRequest\n\tif err := ctx.Bind(&req); err != nil {\n\t\tlog.Println(\"Error binding request\", err)\n\t\treturn ctx.JSON(ErrBadRequestInvalidBody())\n\t}\n\t//validate request\n\tif httpCode, err := req.Validate(); err != nil {\n\t\treturn ctx.JSON(httpCode, err)\n\t}\n\n\t// execute\n\tord, err := order.Create(ctx.Request().Context(), req.Origin, req.Destination)\n\tif err != nil {\n\t\tlog.Println(\"Error creating order \", err)\n\t\t// check for error and return appropriately\n\t\treturn ctx.JSON(ErrInternalServerError(err.Error()))\n\t}\n\treturn ctx.JSON(http.StatusOK, ord)\n}", "func CreateOrder(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\"message\": \"NOT IMPLEMENTED\"})\n}", "func (c *Client) Create(ctx context.Context, params *razorpay.OrderParams) (*razorpay.Order, error) {\n\torder := &razorpay.Order{}\n\terr := c.Call(ctx, http.MethodPost, \"/orders\", params, order)\n\treturn order, err\n}", "func (s *service) Create(ctx context.Context, order ordersvc.Order) (string, error) {\n\tlogger := log.With(s.logger, \"method\", \"Create\")\n\tuuid, _ := uuid.NewV4()\n\tid := uuid.String()\n\torder.ID = id\n\torder.Status = \"Pending\"\n\torder.CreatedOn = time.Now().Unix()\n\n\tif err := s.repository.CreateOrder(ctx, order); err != nil {\n\t\tlevel.Error(logger).Log(\"err\", err)\n\t\treturn \"\", ordersvc.ErrCmdRepository\n\t}\n\treturn id, nil\n}", "func (s *Server) CreateOrder(ctx context.Context, in *orderPb.CreateOrderRequest) (*orderPb.CreateOrderResponse, error) {\n\tt := time.Now()\n\trpcRequestCount.With(prometheus.Labels{\"method\": \"CreateOrderTotal\"}).Inc()\n\n\t// Check input params.\n\taddress := in.GetAddress()\n\trequestId := in.GetRequestId()\n\tfileName := in.GetFileName()\n\tfileSize := in.GetFileSize()\n\tif address == \"\" || requestId == \"\" || fileName == \"\" || fileSize <= 0 {\n\t\trpcRequestCount.With(prometheus.Labels{\"method\": \"CreateOrderFailed\"}).Inc()\n\t\treturn nil, errorm.RequestParamEmpty\n\t}\n\n\tdefer func(t time.Time) {\n\t\tdefer rpcRequestDuration.With(prometheus.Labels{\"method\": \"CreateOrder\"}).Observe(float64(time.Since(t).Microseconds()) / 1000)\n\t}(t)\n\n\t// Create order by address, requestId, fileName and fileSize.\n\tid, err := s.CreateOrderController(address, requestId, fileName, fileSize)\n\tif err != nil {\n\t\trpcRequestCount.With(prometheus.Labels{\"method\": \"CreateOrderError\"}).Inc()\n\t\treturn nil, err\n\t}\n\n\trpcRequestCount.With(prometheus.Labels{\"method\": \"CreateOrderSuccess\"}).Inc()\n\treturn &orderPb.CreateOrderResponse{OrderId: *id, SaveDays: int64(s.Time)}, nil\n}", "func Create() *Order {\n\torder := Order{}\n\torder.TrackChange(&order, &Created{})\n\treturn &order\n}", "func Create(id, pid, name, foreman, email string) *Order {\n\treturn &Order{\n\t\tID: id,\n\t\tProject: Project{\n\t\t\tID: pid,\n\t\t\tName: name,\n\t\t\tForeman: foreman,\n\t\t\tForemanEmail: email,\n\t\t},\n\t\tItems: []Item{},\n\t\tSentDate: time.Now().Unix(),\n\t\tStatus: Draft,\n\t}\n}", "func (c *OrderClient) Create() *OrderCreate {\n\tmutation := newOrderMutation(c.config, OpCreate)\n\treturn &OrderCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (a *App) CreateOrder(o *model.Order, shipAddr *model.Address, billAddr *model.Address) (*model.Order, *model.AppErr) {\n\to.PreSave()\n\treturn a.Srv().Store.Order().Save(o, shipAddr, billAddr)\n}", "func (me *OrderService) CreateOrder(ctx context.Context, request *OrderCreateRequest) (*Order, error) {\n\tnewOrder := &Order{\n\t\tOrderNumber: &request.OrderNumber,\n\t\tOrderDate: request.OrderDate,\n\t\tTotal: request.Total,\n\t\tCreatedAt: time.Now(),\n\t}\n\treturn me.orderRepository.Add(ctx, newOrder)\n}", "func (s *Store) CreateOrder(o *models.Order) (po *models.Order, err error) {\n\tc := s.orders // Basic Validation\n\n\to.Time = primitive.NewDateTimeFromTime(time.Now())\n\n\tif err = o.Validate(); err != nil {\n\t\treturn po, err\n\t}\n\n\tif err = s.processOrder(o); err != nil {\n\t\treturn po, err\n\t}\n\n\tif id, err := s.w.Add(c, o); err != nil {\n\t\treturn nil, err\n\t} else if o.ID, err = primitive.ObjectIDFromHex(id); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn o, err\n}", "func (repo *repository) CreateOrder(ctx context.Context, order order.Order) error {\n\n\t// Run a transaction to sync the query model.\n\terr := crdb.ExecuteTx(ctx, repo.db, nil, func(tx *sql.Tx) error {\n\t\treturn createOrder(tx, order)\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Client) CreateOrder() (*Order, error) {\n\turl := c.option.buildURL(\"orders\")\n\n\tresp, body, errs := c.request.Clone().\n\t\tPost(url).\n\t\tSet(\"Content-Type\", \"application/json\").\n\t\tSetBasicAuth(c.option.Key, c.option.Secret).\n\t\tEndBytes()\n\tif len(errs) > 0 {\n\t\treturn nil, errs[0]\n\t}\n\n\tif resp.StatusCode >= 400 {\n\t\tvar apiErr ApiError\n\t\terr := json.Unmarshal(body, &apiErr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, &apiErr\n\t}\n\n\tvar order Order\n\terr := json.Unmarshal(body, &order)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &order, nil\n\n}", "func createOrder(db *gorm.DB, user User, amount int, desc string) {\n\terr := db.Create(&Order{\n\t\tUserID: user.ID,\n\t\tAmount: amount,\n\t\tDescription: desc,\n\t}).Error\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (client *Client) OrderCreate(ctx context.Context, draft *OrderFromCartDraft, opts ...RequestOption) (result *Order, err error) {\n\tparams := url.Values{}\n\tfor _, opt := range opts {\n\t\topt(&params)\n\t}\n\n\tendpoint := \"orders\"\n\terr = client.create(ctx, endpoint, params, draft, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}", "func (c *Client) CreateOrder(o Order) (*PostOrderResponse, error) {\n\t// Perform request to API\n\tres, err := c.Post(\"/orders\", o)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Close()\n\n\t// Decode JSON\n\tdata := &PostOrderResponse{}\n\tif err := json.NewDecoder(res).Decode(data); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}", "func CreateOrder(db *sqlx.DB) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar ord Order\n\n\t\terr := c.Bind(&ord)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tc.AbortWithError(503, errors.NewAPIError(503, \"failed to create new order\", \"internal server error\", c))\n\t\t\treturn\n\t\t}\n\n\t\tif ok := auth.MustUser(c, ord.UserName); !ok {\n\t\t\tc.AbortWithError(401, errors.NewAPIError(401, \"failed to create new order\", \"internal server error\", c))\n\t\t\treturn\n\t\t}\n\n\t\tord.StatusDate = time.Now()\n\t\tord.Status = \"saved\"\n\n\t\tvar returnID int\n\t\tdbErr := db.Get(&returnID, `INSERT INTO gaea.order\n\t\t(order_id, sale_id, status, status_date, user_name, sale_type) VALUES\n\t\t(DEFAULT, $1, $2, $3, $4, $5) RETURNING order_id`,\n\t\t\tord.SaleId,\n\t\t\tord.Status,\n\t\t\tord.StatusDate,\n\t\t\tord.UserName,\n\t\t\tord.SaleType)\n\n\t\tif dbErr != nil {\n\t\t\tfmt.Println(dbErr)\n\t\t\tc.AbortWithError(503, errors.NewAPIError(503, \"failed to bind new order\", \"internal server error\", c))\n\t\t\treturn\n\t\t}\n\t\tord.OrderId = returnID\n\n\t\tc.JSON(200, ord)\n\t}\n}", "func (h Handler) create(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\tvar co CreateOrder\n\n\tdefer r.Body.Close()\n\tif err := json.NewDecoder(r.Body).Decode(&co); err != nil {\n\t\tdhttputil.ErrorHandler(err, w, r)\n\t\treturn\n\t}\n\n\tif err := h.service.CreateOrder(ctx, co); err != nil {\n\t\tdhttputil.ErrorHandler(err, w, r)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n}", "func Create(ctx context.Context, params *razorpay.OrderParams) (*razorpay.Order, error) {\n\treturn getDefaultClient().Create(ctx, params)\n}", "func (m *Marketplace) CreateOrder(ctx context.Context, req *pb.Order) (*pb.Order, error) {\n\tif err := CheckPermissions(ctx, req); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := m.validate(req); err != nil {\n\t\treturn nil, err\n\t}\n\n\torder := *req\n\t// generate a unique ID if it's empty\n\tif order.Id == \"\" {\n\t\torder.Id = IDGenerator()\n\t}\n\n\tlogger := ctx_zap.Extract(ctx)\n\tlogger.Info(\"Creating order\", zap.Any(\"order\", order))\n\n\tif err := m.createOrder(order); err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"cannot create order: %v\", err)\n\t}\n\n\tlogger.Info(\"Order created\", zap.String(\"id\", order.Id))\n\treturn m.GetOrderByID(ctx, &pb.ID{Id: order.Id})\n}", "func (m *MutationResolver) CreateOrder(\n\tctx context.Context,\n\tinput *models.CreateOrderInput,\n) (*pb.Order, error) {\n\tattr := &pb.NewOrderAttributes{}\n\tif input.Comments != nil {\n\t\tattr.Comments = *input.Comments\n\t}\n\tattr.Consumer = input.Consumer\n\tattr.Courier = input.Courier\n\tattr.CourierAccount = input.CourierAccount\n\tattr.Items = input.Items\n\tattr.Payer = input.Payer\n\tattr.Payment = input.Payment\n\tattr.PurchaseOrderNum = *input.PurchaseOrderNum\n\tattr.Purchaser = input.Purchaser\n\tattr.Status = statusConverter(input.Status)\n\to, err := m.GetOrderClient(registry.ORDER).CreateOrder(ctx, &pb.NewOrder{\n\t\tData: &pb.NewOrder_Data{\n\t\t\tType: \"order\",\n\t\t\tAttributes: attr,\n\t\t},\n\t})\n\tif err != nil {\n\t\terrorutils.AddGQLError(ctx, err)\n\t\tm.Logger.Error(err)\n\t\treturn nil, err\n\t}\n\tm.Logger.Debugf(\"successfully created new order with ID %s\", o.Data.Id)\n\treturn o, nil\n}", "func CreateOrder(productID, customerID, shipmentID string) (Order, Quote, Transaction, Invoice, error) {\n\treturn Order{}, Quote{}, Transaction{}, Invoice{}, nil\n}", "func (r *mutationResolver) CreateOrder(ctx context.Context, input *models.CreateOrderInput) (*order.Order, error) {\n\tpanic(\"not implemented\")\n}", "func (tx TxRepo) CreateOrder(order checkout.Order) error {\n\t_, err := tx.NamedExec(checkout.StmtCreateOrder, order)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (client *Client) CreateCdpOrder(request *CreateCdpOrderRequest) (response *CreateCdpOrderResponse, err error) {\n\tresponse = CreateCreateCdpOrderResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func createOrder(writer http.ResponseWriter, request *http.Request) {\n\ttransactionId := request.Header.Get(\"transactionId\")\n\torder := <-orderService.GetOrder(transactionId)\n\tif order.Id.Value == \"\" {\n\t\tlog.Printf(\"Creating order for transactionId :%s......\", transactionId)\n\t\torderHandler.CreateOrder(transactionId, command.CreateOrderCommand{Id: transactionId})\n\t}\n\trenderResponse(writer, []byte(transactionId))\n}", "func (tsl *TrailingStopLoss) CreateOrder() {\n\ttsl.Order = cbp.Order{\n\t\tPrice: fmt.Sprintf(\"%.2f\", tsl.SellPrice),\n\t\tSize: tsl.Account.Balance,\n\t\tSide: \"sell\",\n\t\tStop: \"loss\",\n\t\tStopPrice: fmt.Sprintf(\"%.2f\", tsl.SellPrice),\n\t\tTimeInForce: \"GTC\",\n\t\tProductID: fmt.Sprintf(\"%s-USD\", tsl.Account.Currency),\n\t}\n\tsavedOrder, err := tsl.Client.CreateOrder(&tsl.Order)\n\tif err != nil {\n\t\tlog.Fatalln(err.Error())\n\t}\n\ttsl.Order = savedOrder\n\tlog.Printf(\"[order] placed for: %f\\n\", tsl.SellPrice)\n\tfmt.Printf(\"[order] placed for: %f\\n\", tsl.SellPrice)\n\ttsl.UpdateTime()\n}", "func (svc *svc) CreateOrder(ctx context.Context, order *model.Order) error {\n\tvar err error\n\n\tswitch config.Config().Trader.Strategy {\n\tcase config.TraderStrategyDatabaseRowLock:\n\t\terr = svc.createOrderByDatabaseRowLock(ctx, order)\n\n\tcase config.TraderStrategyRedisLock:\n\t\terr = svc.createOrderByRedisLock(ctx, order)\n\n\tcase config.TraderStrategyAsyncInMemoryMatching:\n\t\terr = svc.createOrderByAsyncMemoryMatch(ctx, order)\n\n\tdefault: // default use DatabaseRowLock\n\t\terr = svc.createOrderByDatabaseRowLock(ctx, order)\n\t}\n\n\treturn err\n}", "func (n *Nicehash) CreateNewOrder(location, algo int64, amount, price, limit float64, pool_host, pool_port, pool_user, pool_pass string, code int64) (order OrderCallBack, err error) {\n\n\treqUrl := fmt.Sprintf(\"?method=orders.create&location=%d&algo=%d&amount=%f&price=%f&limit=%f&pool_host=%s&pool_port=%s&pool_user=%s&pool_pass=%s\", location, algo, amount, price, limit, pool_host, pool_port, pool_user, pool_pass)\n\tif code != 0 {\n\t\treqUrl += fmt.Sprintf(\"code=%d\", code)\n\t}\n\t_, err = n.client.do(\"POST\", reqUrl, \"private\", &order)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (s *orderRepo) CreateOrder(order entity.Order) (int64, *resterrors.RestErr) {\n\n\tquery := `\n\t\tINSERT INTO tab_order (\n\t\t\tuser_id,company_id,accept_tip\n\t\t) VALUES (?,?,?);\n\t\t`\n\n\tstmt, err := s.db.Prepare(query)\n\tif err != nil {\n\t\terrorCode := \"Error 0006: \"\n\t\tlog.Println(fmt.Sprintf(\"%sError when trying to prepare the query statement in the Create a order\", errorCode), err)\n\t\treturn 0, resterrors.NewInternalServerError(fmt.Sprintf(\"%sDatabase error\", errorCode))\n\t}\n\tdefer stmt.Close()\n\n\tinsertResult, err := stmt.Exec(\n\t\torder.UserID,\n\t\torder.CompanyID,\n\t\torder.AcceptTip)\n\tif err != nil {\n\t\terrorCode := \"Error 0007: \"\n\t\tlog.Println(fmt.Sprintf(\"%sError when trying to execute Query in the Create order\", errorCode), err)\n\t\treturn 0, mysqlutils.HandleMySQLError(errorCode, err)\n\t}\n\n\torderID, err := insertResult.LastInsertId()\n\tif err != nil {\n\t\terrorCode := \"Error 0008: \"\n\t\tlog.Println(fmt.Sprintf(\"%sError when trying to get LastInsertId in the Create order\", errorCode), err)\n\t\treturn 0, mysqlutils.HandleMySQLError(errorCode, err)\n\t}\n\n\treturn orderID, nil\n}", "func CreateOrder(src []string, des []string) (*Order, error) {\n\tcalc := distance.GetCalculator()\n\n\t// calculate the distance\n\td, err := calc.Calculate(src, des)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create the order in the db\n\to := Order{Distance: d, Status: StatusUnassigned}\n\tif err := db.Create(&o).Error; err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &o, nil\n}", "func (trading *TradingProvider) Create(order schemas.Order) (result schemas.Order, err error) {\n\tvar b []byte\n\tvar command string\n\tvar resp OrderCreate\n\n\tif strings.ToUpper(order.Type) == typeBuy {\n\t\tcommand = commandBuy\n\t}\n\tif strings.ToUpper(order.Type) == typeSell {\n\t\tcommand = commandSell\n\t}\n\n\tsymbol := unparseSymbol(order.Symbol)\n\tnonce := time.Now().UnixNano()\n\n\tpayload := httpclient.Params()\n\tpayload.Set(\"command\", command)\n\tpayload.Set(\"nonce\", strconv.FormatInt(nonce, 10))\n\tpayload.Set(\"currencyPair\", symbol)\n\tpayload.Set(\"rate\", strconv.FormatFloat(order.Price, 'f', -1, 64))\n\tpayload.Set(\"amount\", strconv.FormatFloat(order.Amount, 'f', -1, 64))\n\n\tb, err = trading.httpClient.Post(tradingAPI, httpclient.Params(), payload, true)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"[POLONIEX] Error creating order: %v\", string(b))\n\t\treturn\n\t}\n\tif err = json.Unmarshal(b, &resp); err != nil {\n\t\treturn\n\t}\n\tif len(resp.Error) > 0 {\n\t\terr = fmt.Errorf(\"[POLONIEX] Error creating order: %v\", resp.Error)\n\t\treturn\n\t}\n\n\tresult = order\n\tresult.ID = resp.OrderNumber\n\treturn\n}", "func (a *Client) CreateOrder(params *CreateOrderParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateOrderOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewCreateOrderParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"CreateOrder\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/v2/orders\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &CreateOrderReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*CreateOrderOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for CreateOrder: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (d *Db) CreateOrder(orderDate string, details string, idRestaurant int) Order {\n\tvar query = \"INSERT INTO orders (orderDate, details, idRestaurant) VALUES (?, ?, ?)\"\n\tstmt, err := d.Prepare(query)\n\tif err != nil {\n\t\tfmt.Println(\"CreateOrder Preperation Err: \", err)\n\t}\n\t// Executes te insert\n\t_, error := stmt.Exec(orderDate, details, idRestaurant)\n\tif error != nil {\n\t\tfmt.Println(\"CreateOrder Query Err: \", err)\n\t}\n\n\tvar order Order\n\n\treturn order\n}", "func (a *App) createOrder(w http.ResponseWriter, r *http.Request) {\n\tdecoder := json.NewDecoder(r.Body)\n\tvar trequest map[string][]string\n\terr := decoder.Decode(&trequest)\n\tif err != nil {\n\t\thelpers.RespondWithError(w, http.StatusBadRequest, \"INVALID_BODY\")\n\t\treturn\n\t}\n\torigin := trequest[\"origin\"]\n\tif len(origin) == 0 {\n\t\thelpers.RespondWithError(w, http.StatusBadRequest, \"INVALID_ORIGIN\")\n\t\treturn\n\t}\n\n\tdestination := trequest[\"destination\"]\n\tif len(destination) == 0 {\n\t\thelpers.RespondWithError(w, http.StatusBadRequest, \"INVALID_DESTINATION\")\n\t\treturn\n\t}\n\tdist := helpers.Distance{\n\t\tSrc: strings.Join(origin, \",\"),\n\t\tDst: strings.Join(destination, \",\"),\n\t}\n\tdistance, err := dist.CalcDistance()\n\tif err != nil {\n\t\thelpers.RespondWithError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tif distance == 0 {\n\t\thelpers.RespondWithError(w, http.StatusBadRequest, \"PROVIDED_POINT_NOT_CORRECT\")\n\t\treturn\n\t}\n\tp := models.Order{\n\t\tDistance: distance,\n\t\tStatus: \"UNASSIGN\",\n\t}\n\n\torderid, err := p.CreateOrder(a.DB)\n\n\tif err != nil {\n\t\thelpers.RespondWithError(w, http.StatusInternalServerError, \"DB_CONNECTION_ERR\")\n\t\treturn\n\t}\n\tp.ID = orderid\n\thelpers.RespondWithJSON(w, http.StatusOK, p)\n}", "func (dao *OrderDao) Create(order Order) (*Order, error) {\n\tquery := `\n\t\tINSERT INTO orders (status, customerid, productid, author)\n\t\tVALUES ($1, $2, $3, $4)\n\t\tRETURNING id\n\t`\n\torder.Status = OrderProccessing\n\terr := dao.DB.QueryRow(query, order.Status, order.CustomerID, order.ProductID, order.Author).Scan(&order.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &order, nil\n}", "func (c *Client) CreateOrder(orderItems []OrderItem) (*Order, error) {\n\trb, err := json.Marshal(orderItems)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", fmt.Sprintf(\"%s/orders\", c.HostURL), strings.NewReader(string(rb)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := c.doRequest(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\torder := Order{}\n\terr = json.Unmarshal(body, &order)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &order, nil\n}", "func CreateOrder(c *soso.Context) {\n\tif c.Token == nil {\n\t\tc.ErrorResponse(403, soso.LevelError, errors.New(\"User not authorized\"))\n\t\treturn\n\t}\n\treq := c.RequestMap\n\n\tredirectKey, _ := req[\"redirect\"].(string)\n\tredirect, ok := conf.GetSettings().PaymentsRedirects[redirectKey]\n\tif !ok {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"unknown redirect key\"))\n\t\treturn\n\t}\n\n\tamount, _ := req[\"amount\"].(float64)\n\tleadID, _ := req[\"lead_id\"].(float64)\n\n\tcurrency, _ := req[\"currency\"].(float64)\n\tcurrencyName, currencyOK := payment.Currency_name[int32(currency)]\n\n\t// retrieve card number from payments service\n\tshopCardID, _ := req[\"card\"].(float64)\n\tshopCardNumber, err := getCardNumber(c.Token.UID, uint64(shopCardID))\n\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusInternalServerError, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tif amount <= 0 || leadID <= 0 || !currencyOK || shopCardNumber == \"\" {\n\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"Incorrect parameter\"))\n\t\treturn\n\t}\n\n\tleadInfo, err := getLeadInfo(c.Token.UID, uint64(leadID))\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusInternalServerError, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tdirection, err := paymentDirection(leadInfo.UserRole, true)\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusInternalServerError, soso.LevelError, err)\n\t\treturn\n\t}\n\n\tif direction != payment.Direction_CLIENT_RECV && leadInfo.Shop.Suspended {\n\t\tc.ErrorResponse(http.StatusForbidden, soso.LevelError, errors.New(\"shop is suspended\"))\n\t\treturn\n\t}\n\n\tdata, err := json.Marshal(&payment.UsualData{\n\t\tDirection: direction,\n\t\tConversationId: leadInfo.ConversationId,\n\t})\n\tif err != nil {\n\t\tc.ErrorResponse(http.StatusInternalServerError, soso.LevelError, err)\n\t\treturn\n\t}\n\n\trequest := &payment.CreateOrderRequest{\n\t\tData: &payment.OrderData{\n\t\t\tAmount: uint64(amount),\n\t\t\tCurrency: payment.Currency(currency),\n\n\t\t\tLeadId: uint64(leadID),\n\t\t\tShopCardNumber: shopCardNumber,\n\n\t\t\tGateway: \"payture\",\n\t\t\tServiceName: \"api\",\n\t\t\tServiceData: string(data),\n\t\t\tRedirect: redirect,\n\t\t},\n\t\tInfo: &payment.UserInfo{\n\t\t\tUserId: c.Token.UID,\n\t\t},\n\t}\n\n\tif direction == payment.Direction_CLIENT_PAYS {\n\t\tplan, err := getMonetizationPlan(leadInfo.Shop.PlanId)\n\t\tif err != nil {\n\t\t\tc.ErrorResponse(http.StatusInternalServerError, soso.LevelError, err)\n\t\t\treturn\n\t\t}\n\t\tif plan.TransactionCommission != 0 && plan.CoinsExchangeRate != 0 {\n\t\t\tif plan.PrimaryCurrency != currencyName {\n\t\t\t\tc.ErrorResponse(http.StatusBadRequest, soso.LevelError, errors.New(\"Unexpected currency\"))\n\t\t\t}\n\t\t\trequest.Data.CommissionSource = uint64(leadInfo.Shop.SupplierId)\n\t\t\tfee := uint64(amount*plan.TransactionCommission*plan.CoinsExchangeRate + 0.5)\n\t\t\tif fee == 0 {\n\t\t\t\tfee = 1\n\t\t\t}\n\t\t\trequest.Data.CommissionFee = fee\n\t\t}\n\t}\n\n\t// now -- create the order\n\tctx, cancel := rpc.DefaultContext()\n\tdefer cancel()\n\n\tresp, err := paymentServiceClient.CreateOrder(ctx, request)\n\n\tif err != nil { // RPC errors\n\t\tc.ErrorResponse(http.StatusInternalServerError, soso.LevelError, err)\n\t\treturn\n\t}\n\tif resp.Error > 0 { // service errors\n\t\tc.Response.ResponseMap = map[string]interface{}{\n\t\t\t\"ErrorCode\": resp.Error,\n\t\t\t\"ErrorMessage\": resp.ErrorMessage,\n\t\t}\n\t\tc.ErrorResponse(http.StatusInternalServerError, soso.LevelError, errors.New(resp.ErrorMessage))\n\t\treturn\n\t}\n\n\tc.SuccessResponse(map[string]interface{}{\n\t\t\"id\": resp.Id,\n\t})\n}", "func CreateOrderHandler(w http.ResponseWriter, r *http.Request) {\n\tbody, err := ioutil.ReadAll(r.Body)\n\n\tif err != nil {\n\t\thelpers.RespondWithError(w, r, 400, err)\n\t\treturn\n\t}\n\n\to := models.Order{}\n\tjson.Unmarshal(body, &o)\n\n\torder, err := repository.CreateOrder(o)\n\n\thelpers.RespondWithJSON(w, r, order, err)\n}", "func (repo *OrderRepository) Create(order *models.Order) (id int64, err error) {\n\tstatement := \"insert into `order` (vendorId, customerId, orderDetails, status) values (?, ?, ?, ?)\"\n\tstmt, err := Db.Prepare(statement)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer stmt.Close()\n\tresult, err := stmt.Exec(order.VendorId, order.CustomerId, order.OrderDetails, order.Status)\n\tif err != nil {\n\t\tcommon.Error.Println(\"Order could not be created \", err)\n\t\treturn\n\t}\n\treturn result.LastInsertId()\n\n}", "func (gc grpcClient) createOrder(order order.Order) error {\n\tconn, err := grpc.Dial(grpcUri, grpc.WithInsecure())\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to connect: %v\", err)\n\t}\n\tdefer conn.Close()\n\tclient := eventstore.NewEventStoreClient(conn)\n\torderJSON, _ := json.Marshal(order)\n\n\teventid, _ := uuid.NewUUID()\n\tevent := &eventstore.Event{\n\t\tEventId: eventid.String(),\n\t\tEventType: event,\n\t\tAggregateId: order.ID,\n\t\tAggregateType: aggregate,\n\t\tEventData: string(orderJSON),\n\t\tStream: \"ORDERS\",\n\t}\n\n\tcreateEventRequest := &eventstore.CreateEventRequest{Event: event}\n\tresp, err := client.CreateEvent(context.Background(), createEventRequest)\n\tif err != nil {\n\t\tif st, ok := status.FromError(err); ok {\n\t\t\treturn fmt.Errorf(\"error from RPC server with: status code:%s message:%s\", st.Code().String(), st.Message())\n\t\t}\n\t\treturn fmt.Errorf(\"error from RPC server: %w\", err)\n\t}\n\tif resp.IsSuccess {\n\t\treturn nil\n\t}\n\treturn errors.New(\"error from RPC server\")\n}", "func (w *ServerInterfaceWrapper) CreateOrder(ctx echo.Context) error {\n\tvar err error\n\n\tctx.Set(ApiKeyAuthScopes, []string{\"\"})\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.CreateOrder(ctx)\n\treturn err\n}", "func (s *service) Create(ctx context.Context, newOrder Order) (string, error) {\n\tuuid, _ := uuid.NewUUID()\n\ttimestamp := time.Now().Unix()\n\tid := strconv.FormatInt(timestamp, 10)\n\tnewOrder.ID = id\n\tnewOrder.UUID = uuid.String()\n\tnewOrder.Timestamp = timestamp\n\tside := newOrder.Side\n\tnewOrder.Status = \"Active\"\n\tif !Orders.IsEmpty() {\n\t\tif strings.ToUpper(side) == \"ASK\" {\n\t\t\t// Matching\n\t\t\tif spread.BidMaxPrice >= newOrder.Price {\n\t\t\t\tmatch(newOrder.Quantity, newOrder.Price, side)\n\t\t\t\tnewOrder.Status = \"Completed\"\n\t\t\t}\n\t\t} else {\n\t\t\t// Matching\n\t\t\tif spread.AskMinPrice <= newOrder.Price {\n\t\t\t\tmatch(newOrder.Quantity, newOrder.Price, side)\n\t\t\t\tnewOrder.Status = \"Completed\"\n\t\t\t}\n\t\t}\n\n\t}\n\n\tOrders.Set(id, newOrder)\n\tspread.setPrices()\n\treturn id, nil\n}", "func (s *OrderItemService) Create(ctx context.Context, no entity.NewOrderItem) (entity.OrderItem, error) {\n\treturn s.repo.Create(ctx, no)\n}", "func (s *Store) CreateOrder(order *objects.Order, authzURL string, challengeURL string, finalizeURL string) (error, error, error) {\n\trejected, unsupported := order.CheckOrder()\n\tif rejected != nil || unsupported != nil {\n\t\treturn rejected, unsupported, nil\n\t}\n\torder.Status = \"pending\"\n\torder.Finalize = fmt.Sprintf(\"%s/%s\", finalizeURL, order.ID)\n\terr := s.createAuthorizations(order, authzURL, challengeURL)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\t_, err = s.engine.Insert(order)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"cannot insert order: %s\", err)\n\t}\n\t// link orders to identities\n\tfor _, id := range order.Identitifers {\n\t\tif id.ID == 0 {\n\t\t\t// unknonw identifer id\n\t\t\tvar identifier objects.Identifier\n\t\t\tok, err := s.engine.Where(\"type = ? and value = ?\", id.Type, id.Value).Get(&identifier)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"cannot get identifier %s: %s\", id.String(), err)\n\t\t\t}\n\t\t\tif !ok {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"cannot get identifier %s\", id.String())\n\t\t\t}\n\t\t\tid.ID = identifier.ID\n\t\t}\n\t\tlog.Infof(\"linking order %s to identifier %d\", order.ID, id.ID)\n\t\t_, err := s.engine.Insert(&OrdersToIdentifiers{OrderID: order.ID, IdentifierID: id.ID})\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"cannot link order %s to identifier %d: %s\", order.ID, id.ID, err)\n\t\t}\n\t}\n\treturn nil, nil, nil\n}", "func createOrderHandle(response http.ResponseWriter, request *http.Request) {\n\tlog.Println(\"Create new Order in System\")\n\tcreateOrderCommand := commands.CreateOrder{}\n\torderId := <-orderHandler.CreateOrder(createOrderCommand)\n\twriteResponse(response, orderId)\n}", "func CreateCreateCdpOrderRequest() (request *CreateCdpOrderRequest) {\n\trequest = &CreateCdpOrderRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Dycdpapi\", \"2018-06-10\", \"createCdpOrder\", \"\", \"\")\n\trequest.Domain = \"dycdpapi.aliyuncs.com\"\n\treturn\n}", "func (s *PurchaseOrdersEndpoint) Create(ctx context.Context, division int, entity *PurchaseOrders) (*PurchaseOrders, error) {\n\tu, _ := s.client.ResolvePathWithDivision(\"/api/v1/{division}/purchaseorder/PurchaseOrders\", division) // #nosec\n\te := &PurchaseOrders{}\n\t_, _, err := s.client.NewRequestAndDo(ctx, \"POST\", u.String(), entity, e)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn e, nil\n}", "func Order(w http.ResponseWriter, r *http.Request, session *gocql.Session) {\n //Número da Order. Geralmente esse número representa o ID da Order em um sistema externo através da integração com parceiros.\n number := r.FormValue(\"number\")\n //Referência da Order. Usada para facilitar o acesso ou localização da mesma.\n reference := r.FormValue(\"reference\")\n //Status da Order. DRAFT | ENTERED | CANCELED | PAID | APPROVED | REJECTED | RE-ENTERED | CLOSED\n status := r.FormValue(\"status\")\n // Um texto livre usado pelo Merchant para comunicação.\n notes := r.FormValue(\"notes\")\n fmt.Printf(\"Chegou uma requisicoes de order: number %s, reference %s, status %s, notes %s \\n\", number, reference, status, notes)\n\n uuid := gocql.TimeUUID()\n statusInt := translateStatus(status)\n if statusInt == 99 {\n http.Error(w, \"Parametro status invalido\", http.StatusPreconditionFailed)\n return\n }\n\n // Gravar no banco e retornar o UUID gerado\n if err := session.Query(\"INSERT INTO neurorder (order_id, number, reference, status, notes) VALUES (?,?,?,?,?)\", uuid, number, reference, statusInt, notes).Exec(); err != nil {\n fmt.Println(err)\n http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n } else {\n // Retornar um JSON com o UUID (id da Order)\n w.WriteHeader(http.StatusCreated)\n orderResponse := OrderResponse { Uuid: uuid.String() }\n json.NewEncoder(w).Encode(orderResponse)\n }\n}", "func CreateNewOrderService(db *sql.DB) NewOrderService {\n\treturn &NewOrderServiceImpl{\n\t\tdb: db,\n\t\td: dao.CreateDistrictDao(db),\n\t\tc: dao.CreateCustomerDao(db),\n\t\ts: dao.CreateStockDao(db),\n\t\to: dao.CreateOrderDao(db),\n\t\tol: dao.CreateOrderLineDao(db),\n\t\tcip: dao.CreateCustomerItemsPairDao(db),\n\t}\n}", "func CreateNewOrder(res http.ResponseWriter, req *http.Request) {\n\tdefer func() { //to handle potential panic situation\n\t\tif err := recover(); err != nil {\n\t\t\tlog.Panic(\"Panic occured at create order:\", err)\n\t\t}\n\t}()\n\tmyUser := ses.GetUser(res, req)\n\tif !ses.AlreadyLoggedIn(req) {\n\t\thttp.Redirect(res, req, \"/\", http.StatusSeeOther)\n\t\treturn\n\t}\n\t//fmt.Println(Items)\n\tsortItems(ds.Items)\n\n\tvar newShoppingCart = []ds.Order{}\n\n\tif req.Method == http.MethodPost {\n\t\tnameRegExp := regexp.MustCompile(`^[\\w'\\-,.][^0-9_!¡?÷?¿/\\\\+=@#$%ˆ&*(){}|~<>;:[\\]]{2,30}$`) //name regexp to check for name pattern match\n\t\tname := strings.TrimSpace(req.FormValue(\"name\"))\n\t\tif !nameRegExp.MatchString(name) {\n\t\t\thttp.Error(res, \"You have entered an invalid name field.\", http.StatusBadRequest)\n\t\t\tlog.Warning(\"Invalid user input for name field\")\n\t\t\treturn\n\t\t}\n\t\tname = pol.Sanitize(name) //pol.Sanitize is used to sanitize inputs\n\n\t\taddRegExp := regexp.MustCompile(`^[\\w'\\-,.][^_!¡?÷?¿/\\\\+=$%ˆ&*(){}|~<>;:[\\]]{2,100}$`) ////address regexp to check for address pattern match\n\t\tadd := strings.TrimSpace(req.FormValue(\"address\"))\n\t\tif !addRegExp.MatchString(add) {\n\t\t\thttp.Error(res, \"You have entered an invalid address.\", http.StatusBadRequest)\n\t\t\tlog.Warning(\"Invalid user input for address field\")\n\t\t\treturn\n\t\t}\n\t\tadd = pol.Sanitize(add) //pol.Sanitize is used to sanitize inputs\n\n\t\tsday := req.FormValue(\"dday\") //sday is string day\n\t\tdayRegExp := regexp.MustCompile(`^[1-7]$`)\n\t\tif !dayRegExp.MatchString(sday) {\n\t\t\thttp.Error(res, \"You have entered an invalid delivery day.\", http.StatusBadRequest)\n\t\t\tlog.Warning(\"Invalid user input for delivery day\")\n\t\t\treturn\n\t\t}\n\n\t\tdday, _ := strconv.Atoi(sday)\n\n\t\tavailableDay := ds.IsDayAvailable(dday)\n\t\tif availableDay == false { //this checks if the order was placed on an unavailable day\n\t\t\terrorString := \"Sorry! There are no more available delivery slots for \" + ds.IntToDay(dday)\n\t\t\thttp.Error(res, errorString, http.StatusBadRequest)\n\t\t\tlog.Warning(\"There are no more available delivery slots for \" + ds.IntToDay(dday))\n\t\t\treturn\n\t\t}\n\n\t\torderQtyRegExp := regexp.MustCompile(`^[0-9]{1,2}$`) //order quantity reg exp to check for quantity pattern match\n\n\t\tfor i := 0; i < len(ds.Items); i++ {\n\t\t\tif !orderQtyRegExp.MatchString(req.FormValue(ds.Items[i].Name)) {\n\t\t\t\terrorString := \"You have entered an invalid order quantity for \" + ds.Items[i].Name + \".\"\n\t\t\t\thttp.Error(res, errorString, http.StatusBadRequest)\n\t\t\t\tlog.Warning(\"Invalid user input for order quantity\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tquantity, _ := strconv.Atoi(req.FormValue(ds.Items[i].Name)) //label for the form input is the item name, but returns a quantity of that item\n\t\t\tquantity64 := float64(quantity)\n\n\t\t\tif quantity64 > 0 {\n\t\t\t\titemAvailable := availableItem(ds.Items[i].Name)\n\t\t\t\tif itemAvailable == false { // this checks if the current item is in stock\n\t\t\t\t\terrorString := \"Oops, \" + ds.Items[i].Name + \" is no longer available for ordering.\"\n\t\t\t\t\thttp.Error(res, errorString, http.StatusBadRequest)\n\t\t\t\t\tlog.Warning(\"User overordered on item:\", ds.Items[i].Name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tavailableBalance := isBalanceEnough(ds.Items[i].Name, quantity64)\n\t\t\t\tif availableBalance == false { //this checks if the user over ordered on the item\n\t\t\t\t\terrorString := \"Oops, there is no sufficient balance of\" + ds.Items[i].Name + \" for ordering..\"\n\t\t\t\t\thttp.Error(res, errorString, http.StatusBadRequest)\n\t\t\t\t\tlog.Warning(\"User overordered on item:\", ds.Items[i].Name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tsingleCart := ds.Order{\n\t\t\t\t\tOrderItem: ds.Items[i].Name,\n\t\t\t\t\tQty: quantity64,\n\t\t\t\t}\n\t\t\t\tnewShoppingCart = append(newShoppingCart, singleCart)\n\t\t\t}\n\t\t}\n\n\t\tif len(newShoppingCart) == 0 {\n\t\t\thttp.Error(res, \"Error: You cannot submit an empty shopping cart.\", http.StatusBadRequest)\n\t\t\tlog.Warning(\"User entered empty shopping cart.\")\n\t\t\treturn\n\t\t}\n\n\t\ton := atomic.AddInt64(&OrderNumber, 1) // use of atomic function to prevent multiple clients from possibly creating identical order number\n\t\tamt := ds.CalculateAmount(newShoppingCart)\n\t\tnewOrder := ds.OrderInfo{\n\t\t\tUsername: myUser.Username,\n\t\t\tName: name,\n\t\t\tAddress: add,\n\t\t\tDeliveryDay: dday,\n\t\t\tOrderNum: on,\n\t\t\tShoppingCart: newShoppingCart,\n\t\t\tAmount: amt,\n\t\t}\n\n\t\tds.OrderList.AddOrder(newOrder)\n\t\terr := UpdateWeeklySchedule(ds.OrderList)\n\t\tif err != nil {\n\t\t\thttp.Error(res, err.Error(), http.StatusBadRequest)\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\n\t\terr = UpdateWeeklyOrder(ds.OrderList)\n\t\tif err != nil {\n\t\t\thttp.Error(res, err.Error(), http.StatusBadRequest)\n\t\t\tlog.Error(err)\n\t\t\treturn\n\t\t}\n\n\t\t//fmt.Println(weeklySchedule)\n\t\t//fmt.Println(items)\n\t\t//orderList.printAllOrderNodes()\n\n\t\thttp.Redirect(res, req, \"/menu\", http.StatusSeeOther)\n\t\treturn\n\t}\n\n\ttype balanceStruct struct {\n\t\tItem string\n\t\tQuantity float64\n\t}\n\n\tvar itemData []balanceStruct\n\n\tfor i := 0; i < len(ds.Items); i++ {\n\t\tremainingQuantity := ds.Items[i].WeeklyCapacity - ds.Items[i].WeeklyOrder\n\t\td := balanceStruct{\n\t\t\tItem: ds.Items[i].Name,\n\t\t\tQuantity: remainingQuantity}\n\t\titemData = append(itemData, d)\n\t}\n\n\terr := tpl.ExecuteTemplate(res, \"createOrder.gohtml\", itemData)\n\tif err != nil {\n\t\thttp.Error(res, err.Error(), http.StatusBadRequest)\n\t\tlog.Fatalln(err)\n\t}\n\n\tViewAvailableDays(res, req)\n\tshowRemainingBalance(res, req)\n}", "func (v OrdersResource) Create(c buffalo.Context) error {\n // Allocate an empty Order\n order := &models.Order{}\n\n // Bind order to the html form elements\n if err := c.Bind(order); err != nil {\n return err\n }\n\n // Get the DB connection from the context\n tx, ok := c.Value(\"tx\").(*pop.Connection)\n if !ok {\n return fmt.Errorf(\"no transaction found\")\n }\n\n // Validate the data from the html form\n verrs, err := tx.ValidateAndCreate(order)\n if err != nil {\n return err\n }\n\n if verrs.HasAny() {\n return responder.Wants(\"html\", func (c buffalo.Context) error {\n // Make the errors available inside the html template\n c.Set(\"errors\", verrs)\n\n // Render again the new.html template that the user can\n // correct the input.\n c.Set(\"order\", order)\n\n return c.Render(http.StatusUnprocessableEntity, r.HTML(\"/orders/new.plush.html\"))\n }).Wants(\"json\", func (c buffalo.Context) error {\n return c.Render(http.StatusUnprocessableEntity, r.JSON(verrs))\n }).Wants(\"xml\", func (c buffalo.Context) error {\n return c.Render(http.StatusUnprocessableEntity, r.XML(verrs))\n }).Respond(c)\n }\n\n return responder.Wants(\"html\", func (c buffalo.Context) error {\n // If there are no errors set a success message\n c.Flash().Add(\"success\", T.Translate(c, \"order.created.success\"))\n\n // and redirect to the show page\n return c.Redirect(http.StatusSeeOther, \"/orders/%v\", order.ID)\n }).Wants(\"json\", func (c buffalo.Context) error {\n return c.Render(http.StatusCreated, r.JSON(order))\n }).Wants(\"xml\", func (c buffalo.Context) error {\n return c.Render(http.StatusCreated, r.XML(order))\n }).Respond(c)\n}", "func (s *Service) CreateOrder2(c context.Context, a *model.ArgCreateOrder2) (r *model.CreateOrderRet, o *model.PayOrder, err error) {\n\tvar (\n\t\tp *model.VipPirce\n\t\ttx *xsql.Tx\n\t\tplat = orderPlat(a.Platform, a.Device, a.MobiApp, a.Build)\n\t\tpargs map[string]interface{}\n\t\tdprice, oprice, couponMoney float64\n\t\tid int64\n\t)\n\tr = new(model.CreateOrderRet)\n\tif a.Bmid > 0 {\n\t\t// give friend can not use coupon.\n\t\ta.CouponToken = \"\"\n\t\ta.PanelType = model.PanelTypeFriend\n\t}\n\tif a.CouponToken != \"\" {\n\t\t//FIXME 代金券限制平台上线后可以删除\n\t\tif a.PanelType == \"ele\" {\n\t\t\tlog.Warn(\"illegal create order arg:%+v\", a)\n\t\t\terr = ecode.CouPonPlatformNotSupportErr\n\t\t\treturn\n\t\t}\n\t\t//FIXME 代金券限制平台上线后可以删除 end\n\t\tif err = s.CancelUseCoupon(c, a.Mid, a.CouponToken, IPStr(a.IP)); err != nil {\n\t\t\tif err == ecode.CouPonStateCanNotCancelErr {\n\t\t\t\terr = nil\n\t\t\t} else {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\tif p, err = s.VipPriceV2(c, &model.ArgPriceV2{\n\t\tMid: a.Mid,\n\t\tMonth: int16(a.Month),\n\t\tSubType: a.OrderType,\n\t\tToken: a.CouponToken,\n\t\tPlatform: a.Platform,\n\t\tPanelType: a.PanelType,\n\t\tMobiApp: a.MobiApp,\n\t\tDevice: a.Device,\n\t\tBuild: a.Build,\n\t}); err != nil {\n\t\terr = errors.WithStack(err)\n\t\treturn\n\t}\n\tif p == nil || p.Panel == nil {\n\t\terr = ecode.VipOrderPirceErr\n\t\treturn\n\t}\n\t// 商品限制\n\tif err = s.ProductLimit(c, &model.ArgProductLimit{\n\t\tMid: a.Mid,\n\t\tPanelType: a.PanelType,\n\t\tMonths: a.Month,\n\t}); err != nil {\n\t\treturn\n\t}\n\tdprice = p.Panel.DPrice\n\toprice = p.Panel.OPrice\n\tif p.Coupon != nil && p.Coupon.Amount >= 0 {\n\t\tcouponMoney = p.Coupon.Amount\n\t\tdprice = s.floatRound(dprice-couponMoney, _defround)\n\t}\n\tif dprice <= 0 {\n\t\terr = ecode.VipOrderPirceErr\n\t\treturn\n\t}\n\tif tx, err = s.dao.StartTx(c); err != nil {\n\t\terr = errors.WithStack(err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err == nil {\n\t\t\tif err = tx.Commit(); err != nil {\n\t\t\t\ttx.Rollback()\n\t\t\t}\n\t\t} else {\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\to = s.convertOrder(a, plat, dprice, couponMoney, a.Bmid)\n\to.PID = p.Panel.Id\n\tif id, err = s.dao.TxAddOrder(tx, o); err != nil {\n\t\terr = errors.WithStack(err)\n\t\treturn\n\t}\n\tif id > 1 {\n\t\tif err = s.dao.TxAddOrderLog(tx, &model.VipPayOrderLog{Mid: a.Mid, OrderNo: o.OrderNo, Status: o.Status}); err != nil {\n\t\t\terr = errors.WithStack(err)\n\t\t\treturn\n\t\t}\n\t}\n\tif pargs, err = s.createPayParams(c, o, p.Panel, a, plat); err != nil {\n\t\terr = errors.WithStack(err)\n\t\treturn\n\t}\n\tif a.CouponToken != \"\" {\n\t\tif err = s.couRPC.UseAllowance(c, &col.ArgUseAllowance{\n\t\t\tMid: o.Mid,\n\t\t\tCouponToken: a.CouponToken,\n\t\t\tRemark: model.CouponUseRemark,\n\t\t\tOrderNO: o.OrderNo,\n\t\t\tPrice: p.Panel.DPrice,\n\t\t\tPlatform: a.Platform,\n\t\t\tPanelType: a.PanelType,\n\t\t\tMobiApp: a.MobiApp,\n\t\t\tDevice: a.Device,\n\t\t\tBuild: a.Build,\n\t\t\tProdLimMonth: int8(a.Month),\n\t\t\tProdLimRenewal: model.MapProdLlimRenewal[a.OrderType],\n\t\t}); err != nil {\n\t\t\terr = errors.WithStack(err)\n\t\t\treturn\n\t\t}\n\t}\n\tr.Dprice = dprice\n\tr.Oprice = oprice\n\tr.PayParam = pargs\n\tr.CouponMoney = couponMoney\n\tr.UserIP = IPStr(a.IP)\n\tr.PID = o.PID\n\treturn\n}", "func (g Generator) NewOrder(o *pathway.Order, eventTime time.Time) *ir.Order {\n\torderStatus := o.OrderStatus\n\tif orderStatus == \"\" {\n\t\torderStatus = g.MessageConfig.OrderStatus.InProcess\n\t}\n\treturn &ir.Order{\n\t\tOrderProfile: g.OrderProfiles.Generate(o.OrderProfile),\n\t\tPlacer: g.PlacerGenerator.NewID(),\n\t\tOrderDateTime: ir.NewValidTime(eventTime),\n\t\tOrderControl: g.MessageConfig.OrderControl.New,\n\t\tOrderStatus: orderStatus,\n\t}\n}", "func (rpc *RPC) NewOrder(args *api.TransportOrderArgs, reply *api.TransportOrderReply) error {\n var (\n\t\terr error\n\t\tcost float64\n msg string\n\t)\n \n\tcost, msg, err = rpc.server.NewOrder(args.OrderNumber, args.Destination, args.Date, args.Tons, args.Quorum)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*reply = api.TransportOrderReply{cost, msg}\n\treturn nil\n}", "func CreateGetTaobaoOrderRequest() (request *GetTaobaoOrderRequest) {\n\trequest = &GetTaobaoOrderRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"CloudCallCenter\", \"2017-07-05\", \"GetTaobaoOrder\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func handleNewOrder(ctx http.TdkContext) error {\n\torder := new(usecase.Order)\n\terr := json.Unmarshal(ctx.Body(), order)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tinvoice, err := orderUsecase.PutNewOrder(*order)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\n\ttxt := fmt.Sprintf(\"invoice created: %s\", invoice)\n\tctx.Write([]byte(txt))\n\treturn nil\n}", "func (o *OrderRepository) NewOrder(order models.Order) error {\n\torder.Time = time.Now()\n\torder.ID = utils.GetObjectID()\n\t_, err := o.db.InsertOne(context.TODO(), order)\n\n\treturn err\n}", "func (s *OrderService) NewOrder(o *types.Order) error {\n\tif err := o.Validate(); err != nil {\n\t\tlogger.Error(err)\n\t\treturn err\n\t}\n\n\tok, err := o.VerifySignature()\n\tif err != nil {\n\t\tlogger.Error(err)\n\t}\n\n\tif !ok {\n\t\treturn errors.New(\"Invalid Signature\")\n\t}\n\n\tp, err := s.pairDao.GetByTokenAddress(o.BaseToken, o.QuoteToken)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn err\n\t}\n\n\tif p == nil {\n\t\treturn errors.New(\"Pair not found\")\n\t}\n\n\t/*\n\t\tif math.IsStrictlySmallerThan(o.QuoteAmount(p), p.MinQuoteAmount()) {\n\t\t\treturn errors.New(\"Order amount too low\")\n\t\t}\n\t*/\n\n\t// Fill token and pair data\n\terr = o.Process(p)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn err\n\t}\n\tif o.Type == types.TypeLimitOrder {\n\t\terr = s.validator.ValidateAvailablExchangeBalance(o)\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = s.broker.PublishNewOrderMessage(o)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewOrder(order map[string]interface{}) (err error) {\r\n\tmaster := \"\"\r\n\tdetail := \"\"\r\n\tpayment := \"\"\r\n\tinventory := \"\"\r\n\r\n\t// Get a new reference to the ordered items and remove it from the map.\r\n\tpayments := order[\"payments\"]\r\n\titemsOrdered := order[\"items\"]\r\n\tdelete(order, \"items\")\r\n\tdelete(order, \"payments\")\r\n\r\n\t// Get the master insert query\r\n\tif master, err = MaptoInsert(order, \"orders\"); err != nil {\r\n\t\tCheckError(\"Error Mapping the Order to SQL.\", err, false)\r\n\t\treturn err\r\n\t}\r\n\r\n\tmaster += \"SET @last_id := (SELECT LAST_INSERT_ID());\"\r\n\r\n\t// Get the details insert query\r\n\tfor _, _value := range itemsOrdered.([]interface{}) {\r\n\t\tif detail, err = MaptoInsert(_value.(map[string]interface{}), \"ordereditems\"); err != nil {\r\n\t\t\tCheckError(\"Error Mapping the Ordered Items to SQL.\", err, false)\r\n\t\t\treturn err\r\n\t\t}\r\n\r\n\t\t// Build out the needed queries\r\n\t\tinventory += fmt.Sprintf(`UPDATE products SET onhand = onhand - %v, serialnumbers = replace(serialnumbers, '%s', '') WHERE itemcode = \"%s\";`, _value.(map[string]interface{})[\"quantity\"], _value.(map[string]interface{})[\"serialnumber\"], _value.(map[string]interface{})[\"itemcode\"])\r\n\t\tmaster += strings.Replace(fmt.Sprintf(\"%v\", detail), `\"\"`, \"@last_id\", -1)\r\n\t\tmaster = strings.Replace(master, `\"null\"`, `\"\"`, -1)\r\n\t}\r\n\r\n\t// Get the payments insert query\r\n\tfor _, _value := range payments.([]interface{}) {\r\n\t\tif detail, err = MaptoInsert(_value.(map[string]interface{}), \"payments\"); err != nil {\r\n\t\t\tCheckError(\"Error Mapping the Payments to SQL.\", err, false)\r\n\t\t\treturn err\r\n\t\t}\r\n\r\n\t\t// Build out the needed queries\r\n\t\tpayment += strings.Replace(fmt.Sprintf(\"%v\", detail), `\"\"`, \"@last_id\", -1)\r\n\t}\r\n\r\n\t// Save the Order and Reduce inventory\r\n\tif err = Modify(master + payment + inventory); err != nil {\r\n\t\tCheckError(\"Error creating the Order.\", err, false)\r\n\t\treturn err\r\n\t}\r\n\r\n\treturn\r\n}", "func (or *OrderRow) Create() error {\n\treturn DB.Create(or).Error\n}", "func CreatePayment(c *soso.Context) {\n\tif c.Token == nil {\n\t\tc.ErrorResponse(403, soso.LevelError, errors.New(\"User not authorized\"))\n\t\treturn\n\t}\n\treq := c.RequestMap\n\n\tpayID, _ := req[\"id\"].(float64)\n\tleadID, _ := req[\"lead_id\"].(float64)\n\n\tif leadID < 0 || payID <= 0 {\n\t\tc.ErrorResponse(http.StatusInternalServerError, soso.LevelError, errors.New(\"Incorrect parameter\"))\n\t\treturn\n\t}\n\n\tif leadID != 0 {\n\t\t_, role, err := getConversationID(c.Token.UID, uint64(leadID))\n\t\tif err != nil {\n\t\t\tc.ErrorResponse(http.StatusInternalServerError, soso.LevelError, err)\n\t\t\treturn\n\t\t}\n\n\t\torderData, paymentData, err := retrieveOrder(uint64(payID))\n\t\tif err != nil {\n\t\t\tc.ErrorResponse(http.StatusInternalServerError, soso.LevelError, err)\n\t\t\treturn\n\t\t}\n\n\t\tif !canBuy(paymentData.Direction, role) {\n\t\t\tc.ErrorResponse(http.StatusInternalServerError, soso.LevelError, fmt.Errorf(\"This side of order can not pay it\"))\n\t\t\treturn\n\t\t}\n\t\tif orderData.LeadId != uint64(leadID) {\n\t\t\tc.ErrorResponse(http.StatusInternalServerError, soso.LevelError, fmt.Errorf(\"Parameters mangled\"))\n\t\t\treturn\n\t\t}\n\n\t}\n\n\t// now -- create the order\n\tctx, cancel := rpc.DefaultContext()\n\tdefer cancel()\n\tresp, err := paymentServiceClient.BuyOrder(ctx, &payment.BuyOrderRequest{\n\t\tPayId: uint64(payID),\n\t\tUser: &payment.UserInfo{\n\t\t\tIp: c.RemoteIP,\n\t\t\tUserId: c.Token.UID,\n\t\t\t// phone not needed here\n\t\t},\n\t})\n\n\tif err != nil { // RPC errors\n\t\tc.ErrorResponse(http.StatusInternalServerError, soso.LevelError, err)\n\t\treturn\n\t}\n\tif resp.Error > 0 { // service errors\n\t\tc.Response.ResponseMap = map[string]interface{}{\n\t\t\t\"ErrorCode\": resp.Error,\n\t\t\t\"ErrorMessage\": resp.ErrorMessage,\n\t\t}\n\t\tc.ErrorResponse(http.StatusInternalServerError, soso.LevelError, errors.New(resp.ErrorMessage))\n\t\treturn\n\t}\n\n\tc.SuccessResponse(map[string]interface{}{\n\t\t\"redirect_url\": resp.RedirectUrl,\n\t})\n\n}", "func (c *PartorderClient) Create() *PartorderCreate {\n\tmutation := newPartorderMutation(c.config, OpCreate)\n\treturn &PartorderCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func Create(reqDto *ReqCreateDto, custDto *ReqCustomerDto) (statusCode int, code string, respDto *RespBase, err error) {\r\n\treqDto.ServiceType = \"TMS_CREATE_ORDER\"\r\n\tbizData, err := xml.Marshal(reqDto.BizData)\r\n\tif err != nil {\r\n\t\tcode = E02\r\n\t\treturn\r\n\t}\r\n\tsignParam := string(bizData) + reqDto.PartnerKey\r\n\treqDto.Sign, err = sign.GetMD5Hash(signParam, true)\r\n\tif err != nil {\r\n\t\tcode = E02\r\n\t\treturn\r\n\t}\r\n\treqMap := make(map[string]string, 0)\r\n\treqMap[\"serviceType\"] = reqDto.ServiceType\r\n\treqMap[\"partnerID\"] = reqDto.PartnerID\r\n\treqMap[\"bizData\"] = string(bizData)\r\n\treqMap[\"sign\"] = reqDto.Sign\r\n\r\n\tdata := base.JoinMapString(reqMap)\r\n\r\n\treq := httpreq.New(http.MethodPost, custDto.Url, data, func(httpReq *httpreq.HttpReq) error {\r\n\t\thttpReq.ReqDataType = httpreq.FormType\r\n\t\thttpReq.RespDataType = httpreq.XmlType\r\n\t\treturn nil\r\n\t})\r\n\tstatusCode, err = req.Call(&respDto)\r\n\tif err != nil {\r\n\t\tcode = E01\r\n\t\treturn\r\n\t}\r\n\tif statusCode != http.StatusOK {\r\n\t\tcode = E01\r\n\t\terr = fmt.Errorf(\"http status exp:200,act:%v\", statusCode)\r\n\t\treturn\r\n\t}\r\n\tif respDto.Result != true {\r\n\t\tcode = E03\r\n\t\terr = fmt.Errorf(\"%v-%v\", respDto.ErrorCode, respDto.ErrorDescription)\r\n\t\treturn\r\n\t}\r\n\tcode = SUC\r\n\treturn\r\n}", "func createOrderId(writer http.ResponseWriter, _ *http.Request) {\n\torderId := []byte(uuid.New().String())\n\trenderResponse(writer, orderId)\n}", "func (main *Main) Create(e echo.Context) (err error) {\n\n\t// get request and validate\n\treq := new(request.Create)\n\te.Bind(req)\n\tif err = e.Validate(req); err != nil {\n\t\treturn rest.ConstructErrorResponse(e, exception.NewInputValidationFailed(err.Error()))\n\t}\n\t// map req to input data\n\treqData := input.NewNewTransactionCreate(\n\t\tmap[string]interface{}{\n\t\t\t\"Name\": req.Name,\n\t\t\t\"Qty\": req.Qty,\n\t\t\t\"Price\": req.Price,\n\t\t\t\"Weight\": req.Weight,\n\t\t\t\"Images\": req.Images,\n\t\t\t\"Description\": req.Description,\n\t\t},\n\t)\n\t//insert data to db\n\ttransaction, exc := TransactionModel.Create(reqData)\n\tif exc != nil {\n\t\treturn rest.ConstructErrorResponse(e, exc)\n\t}\n\tdata := map[string]contract.Model{\n\t\t\"created_transaction\": transaction,\n\t}\n\treturn rest.ConstructSuccessResponse(e, data)\n}", "func NewOrder(ctx *plan.Context, p *plan.Order) *Order {\n\to := &Order{\n\t\tTaskBase: NewTaskBase(ctx),\n\t\tp: p,\n\t\tcomplete: make(chan bool),\n\t}\n\treturn o\n}", "func NewCreateOrderRequest(server string, body CreateOrderJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateOrderRequestWithBody(server, \"application/json\", bodyReader)\n}", "func (c *Contract) AddOrder(tx pgx.Tx, ctx context.Context, o OrderEnt) (OrderEnt, error) {\n\tvar lastInsID int32\n\ttimeStamp := time.Now().In(time.UTC)\n\n\tsql := `INSERT INTO orders(title, paid_by, order_code, order_status, total_price, tc_id, order_type, created_date, details, chat_id, description, total_price_ppn) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11,$12) RETURNING id`\n\n\terr := tx.QueryRow(ctx, sql, o.Title, o.PaidBy, o.OrderCode, o.OrderStatus, o.TotalPrice, o.TcID, o.OrderType, timeStamp, o.Details, o.ChatID, o.Description, o.TotalPricePpn).Scan(&lastInsID)\n\n\to.ID = lastInsID\n\to.CreatedDate = timeStamp\n\n\treturn o, err\n}", "func (d *Distributor) CreatePO(ctx contractapi.TransactionContextInterface, poInfo []byte) (string, error) {\n\ttype POData struct {\n\t\tOrg\t\t\t\tstring `json:\"org\"`\t\n\t\tBuyerCRN\t\tstring `json:\"buyerCRN\"`\t\n\t\tSellerCRN\t\tstring `json:\"sellerCRN\"`\n\t\tDrugName\t\tstring `json:\"drugName\"`\n\t\tQuantity\t\tint `json:\"quantity\"`\n\t}\n\t\n\tvar poData POData\n\t\n\terr := json.Unmarshal(poInfo, &poData)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to unmarshal JSON: %v\", err)\n\t}\n\n\tpoCompositeKey, err := ctx.GetStub().CreateCompositeKey(\"po.pharma-net.com\", []string{poData.BuyerCRN, poData.DrugName})\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to create composite key: %v\", err)\n\t}\n\n\t\n\tbuyer, _ := getCompanyByPartialCompositeKey(ctx, poData.BuyerCRN, \"company.pharma-net.com\")\n\n\tseller, _ := getCompanyByPartialCompositeKey(ctx, poData.SellerCRN, \"company.pharma-net.com\")\n\t\n\tif buyer.HierarchyKey - seller.HierarchyKey != 1 {\n\t\treturn \"\", fmt.Errorf(\"%v not allowed to buy from %v\", buyer.Name, seller.Name)\n\t}\n\t//buyerCompositeKey, err := ctx.GetStub().CreateCompositeKey(\"company.pharma-net.com\", []string{buyer[0].Name, poData.BuyerCRN})\n\t//sellerCompositeKey, err := ctx.GetStub().CreateCompositeKey(\"company.pharma-net.com\", []string{seller[0].Name, poData.SellerCRN})\n\n\tnewPO := PurchaseOrder {\n\t\tOrg:\t\t\t\tpoData.Org,\t\n\t\tPOID:\t\t\t\tpoCompositeKey,\n\t\tDrugName:\t\t\tpoData.DrugName,\n\t\tQuantity:\t\t\tpoData.Quantity,\n\t\tBuyer:\t\t\t\tbuyer.CompanyID,\n\t\tSeller:\t\t\t\tseller.CompanyID,\n\n\t}\n\n\tmarshaledPO, err := json.Marshal(newPO)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to marshal PO into JSON: %v\", err)\n\t}\n\terr = ctx.GetStub().PutState(poCompositeKey, marshaledPO)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to put PO: %v\", err)\n\t}\n\t\n\treturn string(marshaledPO), nil\n\t\n}", "func NewOrdersCreateCmd(parentCmd *cobra.Command, cfg *config.Config) *OrdersCreateCmd {\n\tordersCreateCmd := &OrdersCreateCmd{\n\t\topCmd: NewOperationCmd(parentCmd, \"create\", \"/v1/orders\", http.MethodPost, map[string]string{\n\t\t\t\"currency\": \"string\",\n\t\t\t\"line_items[][product]\": \"string\",\n\t\t\t\"line_items[][quantity]\": \"integer\",\n\t\t\t\"automatic_tax[enabled]\": \"boolean\",\n\t\t}, cfg),\n\t}\n\n\tordersCreateCmd.opCmd.Cmd.RunE = ordersCreateCmd.runOrdersCreateCmd\n\n\treturn ordersCreateCmd\n}", "func (t *Procure2Pay) CreatePurchaseOrder(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\n var objpurchaseOrder purchaseOrder\n\tvar objitem item\n\tvar err error\n\t\n\tfmt.Println(\"Entering CreatePurchaseOrder\")\n\n\tif len(args) < 1 {\n\t\tfmt.Println(\"Invalid number of args\")\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tfmt.Println(\"Args [0] is : %v\\n\", args[0])\n\n\t//unmarshal customerInfo data from UI to \"customerInfo\" struct\n\terr = json.Unmarshal([]byte(args[0]), &objpurchaseOrder)\n\tif err != nil {\n\t\tfmt.Printf(\"Unable to unmarshal CreatePurchaseOrder input purchaseOrder: %s\\n\", err)\n\t\treturn shim.Error(err.Error())\n\t\t}\n\n\tfmt.Println(\"purchase order object PO ID variable value is : %s\\n\", objpurchaseOrder.POID)\n\tfmt.Println(\"purchase order object PO ID variable value is : %s\\n\", objpurchaseOrder.Quantity)\n\n\t// Data insertion for Couch DB starts here \n\ttransJSONasBytes, err := json.Marshal(objpurchaseOrder)\n\terr = stub.PutState(objpurchaseOrder.POID, transJSONasBytes)\n\t// Data insertion for Couch DB ends here\n\n\t//unmarshal LoanTransactions data from UI to \"LoanTransactions\" struct\n\terr = json.Unmarshal([]byte(args[0]), &objitem)\n\tif err != nil {\n\t\tfmt.Printf(\"Unable to unmarshal CreatePurchaseOrder input purchaseOrder: %s\\n\", err)\n\t\treturn shim.Error(err.Error())\n\t\t}\n\n\tfmt.Println(\"item object Item ID variable value is : %s\\n\", objitem.ItemID)\n\n\t// Data insertion for Couch DB starts here \n\ttransJSONasBytesLoan, err := json.Marshal(objitem)\n\terr = stub.PutState(objitem.ItemID, transJSONasBytesLoan)\n\t// Data insertion for Couch DB ends here\n\n\tfmt.Println(\"Create Purchase Order Successfully Done\")\n\n\tif err != nil {\n\t\tfmt.Printf(\"\\nUnable to make transevent inputs : %v \", err)\n\t\treturn shim.Error(err.Error())\n\t\t//return nil,nil\n\t}\n\treturn shim.Success(nil)\n}", "func (c *TradeClient) CreateConditionOrder(contractCode string, side int, _type string, trigPrice decimal.Decimal, expectedQuantity int, expectedPrice decimal.NullDecimal) error {\n\tif len(contractCode) == 0 {\n\t\treturn errors.New(\"contractCode must not empty\")\n\t}\n\n\tparam := &coremodel.ApiRequestModel{\n\t\tParam: &struct {\n\t\t\tContractCode string `json:\"contractCode\"`\n\t\t\tSide int `json:\"side\"`\n\t\t\tType string `json:\"type\"`\n\t\t\tTrigPrice decimal.Decimal `json:\"trigPrice\"`\n\t\t\tExpectedQuantity int `json:\"expectedQuantity\"`\n\t\t\tExpectedPrice decimal.NullDecimal `json:\"expectedPrice\"`\n\t\t}{contractCode, side, _type, trigPrice, expectedQuantity, expectedPrice},\n\t}\n\tbody, err := json.Marshal(param)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.requester.Post(\"/api/v1/condition_order\", body, nil, true, coremodel.NewBoolResponse())\n}", "func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToOrderCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\tresp, err := client.Post(createURL(client), &b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{202},\n\t})\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func CreateCreateCdpOrderResponse() (response *CreateCdpOrderResponse) {\n\tresponse = &CreateCdpOrderResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (sC StoreController) PlaceOrder(context *gin.Context) {\n\tvar order models.Order\n\tif err := context.ShouldBindJSON(&order); err != nil {\n\t\tcontext.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\torder, err := sC.StoreService.Create(order)\n\tif err != nil {\n\t\tcontext.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\tcontext.JSON(http.StatusCreated, gin.H{\"data\": order})\n}", "func (order *Order) New(priority int, quantity int, product string, customerName string) {\n\torder.priority = priority\n\torder.quantity = quantity\n\torder.product = product\n\torder.customerName = customerName\n}", "func (postgres *Postgres) CreateOne(order *proto.Order) (*proto.Order, error) {\n\tquery := fmt.Sprintf(\"INSERT INTO orders (product_id, user_id, status)\"+\n\t\t\" VALUES (%d, %d, 'waiting for payment')\", order.ProductId, order.UserId)\n\t_, err := postgres.DB.Exec(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn order, err\n}", "func InitOrder(userId int, buy bool, marketOrder bool, companyTicker string,\n numberOfShares int,\n limitPrice LimitPrice, eventTime time.Time) *Order {\n order := Order{\n IdNumber: currentId,\n UserId: userId,\n Buy: buy,\n MarketOrder: marketOrder,\n CompanyTicker: companyTicker,\n NumberOfShares: numberOfShares,\n LimitPrice: limitPrice,\n EventTime: eventTime}\n currentId += 1\n return &order\n}", "func NewOrder(u *User, p *Product) *Order {\n\treturn &Order{\n\t\tOrderID: uuid.New(),\n\t\tUserID: u.ID,\n\t\tProductID: p.ID,\n\t\tProduct: p,\n\t}\n}", "func CreateOrderTable(db *sql.DB, tableName string) error {\n\tsql := fmt.Sprintf(orderSQLString[orderTable], tableName)\n\n\t_, err := db.Exec(sql)\n\treturn err\n}", "func (s *PurchaseOrderLinesEndpoint) Create(ctx context.Context, division int, entity *PurchaseOrderLines) (*PurchaseOrderLines, error) {\n\tu, _ := s.client.ResolvePathWithDivision(\"/api/v1/{division}/purchaseorder/PurchaseOrderLines\", division) // #nosec\n\te := &PurchaseOrderLines{}\n\t_, _, err := s.client.NewRequestAndDo(ctx, \"POST\", u.String(), entity, e)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn e, nil\n}", "func (client *Client) OrderEditCreate(ctx context.Context, draft *OrderEditDraft, opts ...RequestOption) (result *OrderEdit, err error) {\n\tparams := url.Values{}\n\tfor _, opt := range opts {\n\t\topt(&params)\n\t}\n\n\tendpoint := \"orders/edits\"\n\terr = client.create(ctx, endpoint, params, draft, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}", "func AddOrder(ctx *fasthttp.RequestCtx) {\n\tord, err := acmeserverless.UnmarshalOrder(string(ctx.Request.Body()))\n\tif err != nil {\n\t\tErrorHandler(ctx, \"AddOrder\", \"UnmarshalOrder\", err)\n\t\treturn\n\t}\n\tord.OrderID = uuid.Must(uuid.NewV4()).String()\n\n\tord, err = db.AddOrder(ord)\n\tif err != nil {\n\t\tErrorHandler(ctx, \"AddOrder\", \"AddOrder\", err)\n\t\treturn\n\t}\n\n\tprEvent := acmeserverless.PaymentRequestedEvent{\n\t\tMetadata: acmeserverless.Metadata{\n\t\t\tDomain: acmeserverless.OrderDomain,\n\t\t\tSource: \"AddOrder\",\n\t\t\tType: acmeserverless.PaymentRequestedEventName,\n\t\t\tStatus: acmeserverless.DefaultSuccessStatus,\n\t\t},\n\t\tData: acmeserverless.PaymentRequestDetails{\n\t\t\tOrderID: ord.OrderID,\n\t\t\tCard: ord.Card,\n\t\t\tTotal: ord.Total,\n\t\t},\n\t}\n\n\t// Send a breadcrumb to Sentry with the payment request\n\tsentry.AddBreadcrumb(&sentry.Breadcrumb{\n\t\tCategory: acmeserverless.PaymentRequestedEventName,\n\t\tTimestamp: time.Now(),\n\t\tLevel: sentry.LevelInfo,\n\t\tData: acmeserverless.ToSentryMap(prEvent.Data),\n\t})\n\n\t// Create payment payload\n\tpayload, err := prEvent.Marshal()\n\tif err != nil {\n\t\tErrorHandler(ctx, \"AddOrder\", \"Marshal\", err)\n\t\treturn\n\t}\n\n\t// Send to Payment\n\treq, err := http.NewRequest(\"POST\", os.Getenv(\"PAYMENT_URL\"), bytes.NewReader(payload))\n\tif err != nil {\n\t\tErrorHandler(ctx, \"AddOrder\", \"NewRequest\", err)\n\t\treturn\n\t}\n\n\treq.Header.Add(\"content-type\", \"application/json\")\n\treq.Header.Add(\"host\", os.Getenv(\"PAYMENT_HOST\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tErrorHandler(ctx, \"AddOrder\", \"DefaultClient.Do\", err)\n\t\treturn\n\t}\n\n\tdefer res.Body.Close()\n\tbody, _ := ioutil.ReadAll(res.Body)\n\n\tif res.StatusCode != 200 {\n\t\tErrorHandler(ctx, \"AddOrder\", \"Payment\", fmt.Errorf(string(body)))\n\t\treturn\n\t}\n\n\tstatus := acmeserverless.OrderStatus{\n\t\tOrderID: ord.OrderID,\n\t\tUserID: ord.UserID,\n\t\tPayment: acmeserverless.CreditCardValidationDetails{\n\t\t\tMessage: \"pending payment\",\n\t\t\tSuccess: false,\n\t\t},\n\t}\n\n\t// Send a breadcrumb to Sentry with the shipment request\n\tsentry.AddBreadcrumb(&sentry.Breadcrumb{\n\t\tCategory: acmeserverless.PaymentRequestedEventName,\n\t\tTimestamp: time.Now(),\n\t\tLevel: sentry.LevelInfo,\n\t\tData: acmeserverless.ToSentryMap(status.Payment),\n\t})\n\n\tpayload, err = status.Marshal()\n\tif err != nil {\n\t\tErrorHandler(ctx, \"AddOrder\", \"Marshal\", err)\n\t\treturn\n\t}\n\n\treq, err = http.NewRequest(\"POST\", os.Getenv(\"SHIPMENT_URL\"), bytes.NewReader(payload))\n\tif err != nil {\n\t\tErrorHandler(ctx, \"AddOrder\", \"NewRequest\", err)\n\t\treturn\n\t}\n\n\treq.Header.Add(\"content-type\", \"application/json\")\n\treq.Header.Add(\"host\", os.Getenv(\"SHIPMENT_HOST\"))\n\n\t_, err = http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tErrorHandler(ctx, \"AddOrder\", \"DefaultClient.Do\", err)\n\t\treturn\n\t}\n\n\tctx.SetStatusCode(http.StatusOK)\n\tctx.Write(payload)\n}", "func NewOrder(ctx *pulumi.Context,\n\tname string, args *OrderArgs, opts ...pulumi.ResourceOption) (*Order, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.PackageVersion == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'PackageVersion'\")\n\t}\n\tif args.PricingCycle == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'PricingCycle'\")\n\t}\n\tif args.ProductCode == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ProductCode'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Order\n\terr := ctx.RegisterResource(\"alicloud:marketplace/order:Order\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (s *Service) CreateAssociateOrder(c context.Context, req *model.ArgCreateAssociateOrder) (res map[string]interface{}, err error) {\n\tvar p *v1.CreateAssociateOrderReply\n\tif p, err = s.vipgRPC.CreateAssociateOrder(c, &v1.CreateAssociateOrderReq{\n\t\tMid: req.Mid,\n\t\tMonth: req.Month,\n\t\tPlatform: req.Platform,\n\t\tMobiApp: req.MobiApp,\n\t\tDevice: req.Device,\n\t\tAppId: req.AppID,\n\t\tAppSubId: req.AppSubID,\n\t\tOrderType: int32(req.OrderType),\n\t\tDtype: int32(req.Dtype),\n\t\tReturnUrl: req.ReturnURL,\n\t\tCouponToken: req.CouponToken,\n\t\tBmid: req.Bmid,\n\t\tPanelType: req.PanelType,\n\t\tBuild: req.Build,\n\t\tIP: req.IP,\n\t}); err != nil {\n\t\treturn\n\t}\n\tjson.Unmarshal([]byte(p.PayParam), &res)\n\treturn\n}", "func (s *Service) PlaceOrder(w http.ResponseWriter, r *http.Request) {\n\tvar entry order.Order\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&entry); err != nil {\n\t\tlog.Errorf(\"PlaceOrder: %v\", err)\n\t\tutils.ResponseWithError(w, http.StatusBadRequest, \"Invalid request payload JSON format\")\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\t// Create the order in the storage\n\tvar err error\n\tentry.ID, err = usecases.PlaceOrder(s.storage, &entry)\n\tif err != nil {\n\t\tlog.Errorf(\"PlaceOrder usecase: %v\", err)\n\t\tutils.ResponseWithError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tutils.ResponseWithJSON(w, http.StatusCreated, entry)\n}", "func (r *Repository) InsertOrder(data *Order) (err error) {\n\n\terr = r.db.Create(data).Error\n\n\treturn\n}", "func NewOrder(orderType OrderType, amount, value uint64, user *uuid.UUID) (*Order, error) {\n\tif orderType != Buy && orderType != Sell {\n\t\terrorMsg := fmt.Sprintf(\"Invalid OrderType. Valid values are [%v, %v]\", Buy, Sell)\n\t\treturn nil, errors.New(errorMsg)\n\t}\n\treturn &Order{orderType, amount, value, user}, nil\n}", "func (e *Endpoints) CreateDeploymentOrder(ctx context.Context, r *http.Request, vars map[string]string) (httpserver.Responser, error) {\n\tvar req apistructs.DeploymentOrderCreateRequest\n\n\tif err := json.NewDecoder(r.Body).Decode(&req); err != nil {\n\t\t// param problem\n\t\tlogrus.Errorf(\"failed to parse request body: %v\", err)\n\t\treturn apierrors.ErrCreateDeploymentOrder.InvalidParameter(\"req body\").ToResp(), nil\n\t}\n\n\tuserID, err := user.GetUserID(r)\n\tif err != nil {\n\t\treturn apierrors.ErrCreateDeploymentOrder.NotLogin().ToResp(), nil\n\t}\n\n\torgID, err := getOrgID(r)\n\tif err != nil {\n\t\treturn apierrors.ErrCreateDeploymentOrder.InvalidParameter(\"org-id\").ToResp(), nil\n\t}\n\n\treq.Operator = userID.String()\n\n\tdata, err := e.deploymentOrder.Create(ctx, &req)\n\tif err != nil {\n\t\tlogrus.Errorf(\"failed to create deployment order: %v\", err)\n\t\terrCtx := map[string]interface{}{}\n\t\tif data != nil {\n\t\t\terrCtx[\"deploymentOrderID\"] = data.Id\n\t\t}\n\t\treturn errorresp.New().InternalError(err).SetCtx(errCtx).ToResp(), nil\n\t}\n\n\tif req.Source != apistructs.SourceDeployPipeline {\n\t\te.auditDeploymentOrder(req.Operator, data.ProjectName, data.Name, orgID, data.ProjectId,\n\t\t\tapistructs.CreateDeploymentOrderTemplate, r)\n\t}\n\n\treturn httpserver.OkResp(data)\n}", "func makeCreateOrderHandler(m *mux.Router, endpoints endpoint.Endpoints, options []kithttp.ServerOption) {\n\tm.Methods(\"POST\").Path(\"/orders\").Handler(\n\t\tkithttp.NewServer(\n\t\t\tendpoints.CreateOrderEndpoint,\n\t\t\tdecodeCreateOrderRequest,\n\t\t\tencodeHTTPGenericResponse,\n\t\t\toptions...,\n\t\t))\n}", "func (a *App) CreateOrderDetails(items []*model.OrderDetail) *model.AppErr {\n\treturn a.Srv().Store.OrderDetail().BulkInsert(items)\n}", "func (mr *MockExchangeMockRecorder) CreateOrder(arg0, arg1, arg2, arg3 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateOrder\", reflect.TypeOf((*MockExchange)(nil).CreateOrder), arg0, arg1, arg2, arg3)\n}", "func (g Generator) NewOrder(o *pathway.Order, eventTime time.Time) *ir.Order {\n\treturn g.orderGenerator.NewOrder(o, eventTime)\n}", "func NewCreateOrderRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) {\n\tvar err error\n\n\tserverURL, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toperationPath := fmt.Sprintf(\"/orders\")\n\tif operationPath[0] == '/' {\n\t\toperationPath = operationPath[1:]\n\t}\n\toperationURL := url.URL{\n\t\tPath: operationPath,\n\t}\n\n\tqueryURL := serverURL.ResolveReference(&operationURL)\n\n\treq, err := http.NewRequest(\"POST\", queryURL.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"Content-Type\", contentType)\n\n\treturn req, nil\n}", "func (s *Service) CreateQrCodeOrder(c context.Context, a *model.ArgCreateOrder2) (res *model.PayQrCodeRet, err error) {\n\tvar (\n\t\tqr *model.PayQrCode\n\t\tr *model.CreateOrderRet\n\t\torderNo string\n\t)\n\tdefer func() {\n\t\tif err != nil && a.CouponToken != \"\" {\n\t\t\ts.CancelUseCoupon(c, a.Mid, a.CouponToken, IPStr(a.IP))\n\t\t}\n\t}()\n\tres = new(model.PayQrCodeRet)\n\tif r, _, err = s.CreateOrder2(c, a); err != nil {\n\t\terr = errors.WithStack(err)\n\t\treturn\n\t}\n\torderNo = r.PayParam[\"orderId\"].(string)\n\tif qr, err = s.dao.PayQrCode(c, a.Mid, orderNo, r.PayParam); err != nil {\n\t\terr = errors.WithStack(err)\n\t\treturn\n\t}\n\tdata := &model.PayQrCodeResp{\n\t\tCodeURL: qr.CodeURL,\n\t\tExpiredTime: qr.ExpiredTime,\n\t\tAmount: r.Dprice,\n\t\tSaveAmount: s.floatRound(r.Oprice-r.Dprice, _defround),\n\t\tOrderNo: orderNo,\n\t}\n\tif a.OrderType == model.AutoRenewPayType {\n\t\tdata.Tip = model.QrAutoRenewTip\n\t} else {\n\t\tdata.Tip = model.QrTip\n\t}\n\tres.PayQrCodeResp = data\n\tres.Dprice = r.Dprice\n\tres.CouponMoney = r.CouponMoney\n\tres.UserIP = r.UserIP\n\tres.PID = r.PID\n\treturn\n}", "func NewOrder(id, price, amount uint64, side MarketSide, category OrderType, eventType CommandType) Order {\n\treturn Order{ID: id, Price: price, Amount: amount, Side: side, Type: category, EventType: eventType}\n}", "func (t *Trade) Create(c echo.Context, req gorsk.Trade) (*gorsk.Trade, error) {\n\treturn t.tdb.Create(t.db, req)\n}", "func CreateSalesOrder(order *createRequest) (sales *model.SalesOrder, err error) {\n\tsales = order.Transform()\n\t\n\t// Masukkan data ke dalam database sesuai dengan list inputan\n\tif err = sales.Save(); err != nil {\n\t\treturn nil, err\n\t}\n\t// wofulfillmentitem\n\tvar wofulfillmentitems []model.WorkorderFulfillmentItem\n\t// Simpan Sales Order Items\n\tfor _, row := range sales.SalesOrderItems {\n\t\trow.SalesOrder = &model.SalesOrder{ID: sales.ID}\n\t\tif err = row.Save(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trow.ItemVariant.Read()\n\t\t// Update avalibale stock dengan available stock lama dikurang dengan quantity input.\n\t\t// dan update commited stock dengan commited stock lama ditambah dengan quantity input\n\t\t// pada item variant yang dipilih\n\t\t_, err = stock.CalculateAvailableStockItemVariant(row.ItemVariant)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// Update total debt dengan total debt lama ditambah dengan total charge SO pada partner ship SO tersebut\n\t\tif err = partnership.CalculationTotalDebt(sales.Customer.ID); err == nil {\n\t\t\tif err = partnership.CalculationTotalSpend(sales.Customer.ID); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t\twofulfillmentitem := model.WorkorderFulfillmentItem{\n\t\t\tSalesOrderItem: row,\n\t\t\tQuantity: row.Quantity,\n\t\t}\n\t\twofulfillmentitems = append(wofulfillmentitems, wofulfillmentitem)\n\t}\n\n\tvar partner *model.Partnership\n\tpartner, err = partnership.GetPartnershipByField(\"id\", sales.Customer.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif sales.AutoInvoice == 1 || partner.IsDefault == 1 || sales.AutoPaid == 1 {\n\t\t// Masukkan data sales invoice dengan referensi sales order id dan semua sales order item id dengan quantity yang sama\n\t\t// (untuk data yang diinput dapat melihat list inputan)\n\t\tcode, err := util.CodeGen(\"code_sales_invoice\", \"sales_invoice\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsales.Customer.Read()\n\t\tsales.Read()\n\t\tsinvoice := model.SalesInvoice{\n\t\t\tSalesOrder: sales,\n\t\t\tCode: code,\n\t\t\tBillingAddress: sales.Customer.Address,\n\t\t\tRecognitionDate: sales.RecognitionDate,\n\t\t\tTotalAmount: sales.TotalCharge,\n\t\t\tDocumentStatus: \"new\",\n\t\t\tCreatedAt: sales.CreatedAt,\n\t\t\tCreatedBy: order.Session.User,\n\t\t}\n\t\tif err = sinvoice.Save(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// cek apakah yang membuat sales order walk-in customer\n\t\tif partner.IsDefault == int8(1) || sales.AutoPaid == int8(1) {\n\t\t\t// buat kan finance revenue untuk sales invoice yang tealah dibuat pada auto-invoice\n\t\t\tif err = createSOWalkInCustomerAutoInvoice(sales, &sinvoice); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t}\n\tif sales.AutoFulfillment == 1 || partner.IsDefault == 1 {\n\t\t// Masukkan data fullfillment dengan referensi sales order id dan semua sales order item id dengan quantity yang sama\n\t\t// (untuk data yang diinput dapat melihat list inputan)\n\t\tcode, err := util.CodeGen(\"code_fullfilment\", \"workorder_fulfillment\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsales.Customer.Read()\n\t\t// Update fullfilment status menjadi finished\n\t\twofulfillment := model.WorkorderFulfillment{\n\t\t\tSalesOrder: sales,\n\t\t\tCode: code,\n\t\t\tShippingAddress: sales.ShipmentAddress,\n\t\t\tDocumentStatus: \"new\",\n\t\t\tCreatedAt: sales.CreatedAt,\n\t\t\tCreatedBy: order.Session.User,\n\t\t\tPriority: \"routine\",\n\t\t}\n\n\t\tif err = wofulfillment.Save(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, row := range wofulfillmentitems {\n\t\t\trow.WorkorderFulfillment = &wofulfillment\n\t\t\tif err = row.Save(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\twofulfillmentID := wofulfillment.ID\n\t\tdatawofulfillment, _ := getWorkorderFulfillmentByID(wofulfillmentID)\n\t\tapproveFulfillment(datawofulfillment)\n\t}\n\t// update document status pada sales order menjadi active\n\tif sales.AutoInvoice == int8(0) && sales.AutoFulfillment == int8(0) && partner.IsDefault == int8(0) && sales.AutoPaid == int8(0) {\n\t\tsales.DocumentStatus = \"new\"\n\t}\n\n\tif err = sales.Save(\"DocumentStatus\"); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn\n}" ]
[ "0.7995825", "0.7714538", "0.76843715", "0.7665126", "0.7629189", "0.7612207", "0.75953907", "0.7582923", "0.7548065", "0.7545327", "0.75202197", "0.7519648", "0.75073755", "0.74967855", "0.749028", "0.7485679", "0.746166", "0.7416033", "0.74129796", "0.73773503", "0.73278636", "0.728847", "0.72289926", "0.72127026", "0.72071964", "0.716513", "0.7145563", "0.71257275", "0.71119666", "0.70831925", "0.70619076", "0.7051495", "0.7015567", "0.6996116", "0.6985657", "0.6980089", "0.6972551", "0.6967706", "0.69615537", "0.6935075", "0.692376", "0.6876871", "0.6826824", "0.6814547", "0.67805046", "0.67262113", "0.67146933", "0.66969186", "0.65690875", "0.65681654", "0.6560566", "0.6548797", "0.6538329", "0.64626944", "0.64540493", "0.6378795", "0.63731253", "0.63661176", "0.63445556", "0.6330636", "0.6313366", "0.62972534", "0.6289471", "0.62877315", "0.628679", "0.62805593", "0.6276538", "0.6257785", "0.6236887", "0.6227377", "0.6225421", "0.6213021", "0.6211416", "0.6197462", "0.618395", "0.6180366", "0.6159696", "0.6128902", "0.61001074", "0.60930157", "0.6085118", "0.6083612", "0.6070909", "0.60504705", "0.6049812", "0.6016189", "0.5964673", "0.596467", "0.5955932", "0.5954458", "0.5910991", "0.5897169", "0.5894949", "0.58888644", "0.5875729", "0.58751386", "0.5869132", "0.58663", "0.5861724", "0.58617115" ]
0.7286142
22
Closures Creamos una funcion tabla que recibe un entero y a su vez retorna una funcion que retorna un entero
func Tabla(valor int) func() int { numero := valor secuencia := 0 return func() int { secuencia++ return numero * secuencia } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Tabla(valor int) func() int {\n\tnumero := valor //la primera ejecucion va a ejecutar linea57 y 58\n\tsecuencia := 0\n\treturn func() int { //cuando se llama y se asigna a una variable, la variable solo toma la parte que se retorna.\n\t\tsecuencia++\n\t\treturn numero * secuencia\n\t}\n\n}", "func Tabla(valor int) func() int {\n\t// datos fuera de la funcion\n\tnumero := valor\n\tsecuencia := 0\n\treturn func() int {\n\t\tsecuencia++\n\t\treturn numero * secuencia\n\t}\n}", "func func_return() (func()){\n\n\treturn func() {\n\tfmt.Println(\"This is inside the function\")\n\t}\n\n}", "func (t *LineTable) funcTab() funcTab {\n\treturn funcTab{LineTable: t, sz: t.functabFieldSize()}\n}", "func Calculo(funccao func(int, int)int, numeroA int, numeroB int) int {\n\n\treturn funccao(numeroA, numeroB)\n}", "func operacionesMidd( f func(int, int) int ) func(int, int) int {\n\t//el middleware funciona como un pasamano,\n\t//le paso la referencia a mi funcion la recibe,\n\t//la procesa y devuelve la misma funcion para \n\t//q luego de eso ejecute lo q esta en la funcion\n\treturn func (a, b int) int {\n\t\tfmt.Println(\"Inicio de operacion\")\n\t\t/*aqui se hacen los llamados a operaciones de \n\t\tencriptacion seguridad etc antes del return*/\n\t\treturn f(a,b)\t\n\t}\n}", "func fibonacci(n int) func(int) int {\r\n\t\t//Initierar en variabel till en funtion av int\r\n\t\tx := func(n int) int{\r\n\t\t\t//returnar fib talen till x\r\n\t\t\treturn fib(n)\r\n\t\t}\r\n\treturn x\r\n}", "func returnFunc() func() int {\n\treturn func() int {\n\t\treturn 451\n\t}\n\n}", "func (s *BasejossListener) EnterFuncSin(ctx *FuncSinContext) {}", "func functionClosures() {\n\tfmt.Println(\"\\nfunctionClosures():\")\n\tpos, neg := adder(), adder()\n\tfor i := 0; i < 10; i++ {\n\t\tfmt.Println(\n\t\t\tpos(i),\n\t\t\tneg(-2*i),\n\t\t)\n\t}\n}", "func giveFunc(x int) func() int {\n\t// giveFunc returns function which returns int [func() int]\n\treturn func() int {\n\t\treturn x\n\t}\n}", "func squares() func () int {\n var x int\n // this is an anonymous function\n // importantly, even after it is returned, it as acess\n // to the variables of the enclosing function\n // the lifetime of var x is not define by it's scope\n // x is hidden in the returning function\n return func() int {\n x++\n return x*x\n }\n}", "func Operator2( csv_records type5.Csv_Records ,function string ,w http.ResponseWriter, r *http.Request ) ( csv_inf []type5.Csv_Inf ) {\n\n// IN  csv_records : some csv records\n// IN function :  \n//           and , or\n// IN w   : response-writer\n// IN r   : request-parameter\n\n// OUT csv_inf : csv inf. which is after extracting\n\n// fmt.Fprintf( w, \"operator start \\n\" )\n\n///\n/// jump some action in function\n\n\tswitch function {\n\n case \"or\" :\n\n csv_inf = Operator_or ( w , r ,csv_records )\n\n break;\n\n case \"and\" :\n\n csv_inf = Operator_and ( w , r ,csv_records )\n\n break;\n\n }\n\n\treturn csv_inf\n\n}", "func operacionesMidd(f func(int, int) int) func(int, int) int {\n\n\treturn func(a, b int) int {\n\t\t//Hago lo que necesito hacer\n\t\tfmt.Println(\"Soy el mensaje del Middleware\")\n\t\t//Devuelvo la funcion para que haga su trabajo :)\n\t\treturn f(a, b)\n\t}\n}", "func fibonacci() func() int {\n\tfib := 0\n\t//Defining func that returns an int\n\tclosure_func := func () int {\n\t\tfmt.Println(\"Closure of fibbonaci of \", fib)\n\t\tif fib <= 0{\n\t\t\tfmt.Println(\"fibbonaci of: \", fib, \"is : \", 0)\n\t\t\t// Increase for next iteration\n\t\t\tfib++\n\t\t\treturn 0\n\t\t}\n\t\tif fib == 1{\n\t\t\tfmt.Println(\"fibbonaci of: \", fib, \"is : \", 1)\n\t\t\t// Increase for next iteration\n\t\t\tfib++\n\t\t\treturn 1\n\t\t}\n\t\t// Increase for next iteration\n\t\tfib++\n\t\tvar a = 0\n\t\tb := 1\n\t\tc := 0\n\t\tfor i:= 1; i<fib; i++ {\n\t\t\tprint(i)\n\t\t\tc = a + b\n\t\t\ta = b\n\t\t\tb = c\n\t\t}\n\t\tfmt.Println(\"fibbonaci of: \", fib, \"is : \", c)\n\t\t// Return fibonacci\n\t\treturn c\n\t}//end closure\n\treturn closure_func\n}", "func getfunc() func() int {\n\treturn func() int {\n\t\treturn 158\n\t}\n}", "func (p *parser) function() Node {\n\tident := p.expect(TokenIdent)\n\tp.expect(TokenLParen)\n\targs := p.parameters()\n\tp.expect(TokenRParen)\n\n\tn := newFunc(ident.pos, ident.val, args)\n\treturn n\n}", "func (t *LineTable) funcData(i uint32) funcData {\n\tdata := t.funcdata[t.funcTab().funcOff(int(i)):]\n\treturn funcData{t: t, data: data}\n}", "func newLabo(s *goquery.Selection, l *Labo) *Labo {\n\tfor _, fn := range laboFn {\n\t\tfn(s, l)\n\t}\n\treturn l\n}", "func (t *LineTable) go12Funcs() []Func {\n\t// Assume it is malformed and return nil on error.\n\tif !disableRecover {\n\t\tdefer func() {\n\t\t\trecover()\n\t\t}()\n\t}\n\n\tft := t.funcTab()\n\tfuncs := make([]Func, ft.Count())\n\tsyms := make([]Sym, len(funcs))\n\tfor i := range funcs {\n\t\tf := &funcs[i]\n\t\tf.Entry = ft.pc(i)\n\t\tf.End = ft.pc(i + 1)\n\t\tinfo := t.funcData(uint32(i))\n\t\tf.LineTable = t\n\t\tf.FrameSize = int(info.deferreturn())\n\t\tsyms[i] = Sym{\n\t\t\tValue: f.Entry,\n\t\t\tType: 'T',\n\t\t\tName: t.funcName(info.nameoff()),\n\t\t\tGoType: 0,\n\t\t\tFunc: f,\n\t\t}\n\t\tf.Sym = &syms[i]\n\t}\n\treturn funcs\n}", "func example() error {\n\ta := func() {\n\t\tfmt.Println(\"zeynep\")\n\t}\n\n\ta()\n\n\treturn nil\n}", "func fibaonacci() func() int {\n\tindex := 0\n\tfn0 := 0\n\tfn1 := 0\n\tfn2 := 0\n\t\n\treturn func() int {\n\t\tif index == 0 {\n\t\t\tfn0 = 0;\n\t\t} else if index == 1 {\n\t\t\tfn0 = 1;\n\t\t} else if index > 1 {\n\t\t\tfn2 = fn1;\n\t\t\tfn1 = fn0;\n\t\t\tfn0 = fn1 + fn2\n\t\t}\n\t\t//fmt.Println(\"Index=\", index, \"fn1=\", fn1, \"fn2=\", fn2)\n\t\tindex += 1\n\t\treturn fn0\n\t}\n}", "func tableWith(l *lua.State, fs ...fm) int {\n\tl.CreateTable(0, len(fs))\n\tidx := l.Top()\n\tfor _, x := range fs {\n\t\tfor k := range x {\n\t\t\tl.PushGoFunction(x[k])\n\t\t\tl.SetField(idx, k)\n\t\t}\n\t}\n\treturn 1\n}", "func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\n\tif function == \"createTableTenancyContract\" {\n\n\t\ttable1Args := []string{\"Tenancy_Contract\"}\n\t\treturn t.createTable(stub, table1Args)\n\n\t} else if function == \"createTableInsuranceContract\" {\n\n\t\ttable2Args := []string{\"Insurance_Contract\"}\n\t\treturn t.createTable(stub, table2Args)\n\n\t} else if function == \"createTableRequest\" {\n\n\t\ttable3Args := []string{\"Request\"}\n\t\treturn t.createTable(stub, table3Args)\n\n\t} else if function == \"deleteTable\" {\n\t\treturn t.deleteTable(stub, args)\n\n\t} else if function == \"insertRowTenancyContract\" {\n\t\treturn t.insertRowTenancyContract(stub, args)\n\n\t} else if function == \"insertRowInsuranceContract\" {\n\t\treturn t.insertRowInsuranceContract(stub, args)\n\n\t} else if function == \"insertRowRequest\" {\n\t\treturn t.insertRowRequest(stub, args)\n\n\t} else if function == \"deleteRowTenancyContract\" {\n\t\treturn t.deleteRowTenancyContract(stub, args)\n\n\t} else if function == \"deleteRowInsuranceContract\" {\n\t\treturn t.deleteRowInsuranceContract(stub, args)\n\n\t} else if function == \"deleteRowRequest\" {\n\t\treturn t.deleteRowRequest(stub, args)\n\n\t} else if function == \"updateRowRequest\" {\n\t\treturn t.updateRowRequest(stub, args)\n\t}\n\n\treturn nil, errors.New(\"Unsupported Invoke Functions [\" + function + \"]\")\n}", "func squares() func() int {\n\tvar x int\n\treturn func() int {\n\t\tx++\n\t\treturn x * x\n\t}\n}", "func ParseSymTblFunc(ld *LineDesc) {\n var pd ParamDesc;\n var func_t *libgogo.TypeDesc = nil;\n var some_t *libgogo.TypeDesc = nil;\n var fwdStr string;\n var fwdNum uint64;\n var pkgFunc string;\n var funcName string;\n var pkgName string;\n var ind uint64;\n var paramType string;\n var tmpParam *libgogo.ObjectDesc;\n\n InitParamDesc(&pd);\n\n fwdStr = GetNextSymToken(ld);\n fwdNum = libgogo.StringToInt(fwdStr);\n pkgFunc = GetNextSymToken(ld);\n ind = libgogo.StringCompare(pkgFunc, \"main·init\");\n if ind != 0 {\n pkgName = GetPackageName(pkgFunc);\n funcName = GetFuncName(pkgFunc);\n func_t = NewFunction(funcName, pkgName, fwdNum);\n paramType = GetNextSymToken(ld);\n ind = libgogo.StringLength(paramType);\n for ; ind != 0 ; {\n ParseSymbolParam(&pd, paramType);\n tmpParam = libgogo.NewObject(pd.Name, \"\", libgogo.CLASS_PARAMETER);\n some_t = libgogo.GetType(pd.TypeName, pd.TypePackage, GlobalTypes, 1);\n if some_t != nil {\n tmpParam.ObjType = some_t;\n tmpParam.PtrType = pd.Ptr;\n libgogo.AddParameters(tmpParam, func_t);\n } else {\n LinkError(\"unable to find type '\",pd.TypePackage,\"·\",pd.TypeName,\"'.\");\n }\n paramType = GetNextSymToken(ld);\n ind = libgogo.StringLength(paramType);\n }\n }\n\n}", "func (s *BaseTdatListener) EnterEnumerableFunc(ctx *EnumerableFuncContext) {}", "func intSeq() func() int {\n i := 0\n return func() int {\n i += 1\n return i\n }\n}", "func fibonacci() func() int64 {\n\t/*\n\t\t関数の中で宣言された変数はローカル変数といい、呼び出しを終了する際に破棄される\n\t\tしかし、クロージャから呼び出されている変数はローカル変数であっても、破棄されずに保持される\n\t\t関数の中で呼び出されるローカル変数がすべて捕捉されるわけではなく、クロージャの中で参照されている変数のみが捕捉される\n\t\tgoにはジェネレータ(自身の内部の状態を保持し、呼び出されるたびに現在の状態から導き出される処理結果を返す)の機能はないが、クロージャを用いることでジェネレータの役割を実現できる\n\t\t※クロージャを別に新しく生成した際は、現在の内部の状態は共有されずに新しく生成される\n\t*/\n\tvar s int64\n\tvar next int64\n\t//var b bool\n\tvar work int64\n\t//var work2 int64\n\treturn func() int64 {\n\t\t/*\n\t\t\tif (s + next) == 0 {\n\t\t\t\tnext = 1\n\t\t\t} else if (s + next) == 1 {\n\t\t\t\ts = next\n\t\t\t} else {\n\t\t\t\tif b == true {\n\t\t\t\t\tif work == 0 {\n\t\t\t\t\t\tnext = next + s\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnext = work\n\t\t\t\t\t}\n\t\t\t\t\twork = next + s\n\t\t\t\t\ts = next\n\t\t\t\t} else {\n\t\t\t\t\tb = true\n\t\t\t\t}\n\t\t\t}\n\t\t*/\n\t\twork = s //ワークスペースに現在のフィボナッチ数の値を退避\n\t\ts = s + next //現在のフィボナッチ数にn-1番目の数値を足す\n\t\tnext = work //n-1番目のフィボナッチ数を次に足す値として代入\n\t\tif s == 0 {\n\t\t\tnext += 1\n\t\t\treturn s\n\t\t} else if s == 1 {\n\t\t\treturn s\n\t\t} else {\n\t\t\ts -= 1\n\t\t\tfibonacci()\n\t\t\ts -= 1\n\t\t\tfibonacci()\n\t\t\ts += 2\n\t\t}\n\t\treturn s\n\t}\n}", "func (s *BasejossListener) EnterFuncExp(ctx *FuncExpContext) {}", "func (s *BasejossListener) EnterFuncCos(ctx *FuncCosContext) {}", "func dosomething(random int, a func(), b func()) {\n\t fmt.Println(\"Details passed to dosomething function :\")\n\t fmt.Printf(\"\\t\\t\\t\\t%v\\t%v\\t%v\\n\",random,a,b)\n if random % 2 == 0{\n \ta()\n\t\t}else{\n b()\n\t\t}\n}", "func fibonacci() func() int {\n fib0 := 0\n fib1 := 1\n return func() int {\n result := fib0\n next := fib0 + fib1\n fib0 = fib1\n fib1 = next\n return result\n }\n}", "func (fsm *Fsm_s)init_fsm_table(){\n\tfsm.table = [][]func(){\n/*STATES:\t \\\tEVENTS:\t//NewOrder\t\t\t//FloorReached \t//Exec \t\t\t\t//TimerOut\t\t//Obst\t\t\t\t//EmgPressed\n/*IDLE */ []func(){fsm.action_start,\taction_dummy,\t\t\tfsm.action_exec_same,\taction_dummy,\tfsm.action_pause,\tfsm.action_stop},\n/*DOORS_OPEN */ []func(){action_dummy,\t\taction_dummy,\t\t\taction_dummy,\t\t\tfsm.action_done,fsm.action_pause,\tfsm.action_stop}, \n/*MOVING_UP */ []func(){action_dummy,\t\tfsm.action_check_order,\tfsm.action_exec,\t\taction_dummy,\tfsm.action_pause,\tfsm.action_stop},\n/*MOVING_DOWN*/ []func(){action_dummy,\t\tfsm.action_check_order,\tfsm.action_exec,\t\taction_dummy,\tfsm.action_pause,\tfsm.action_stop},\n/*EMG_STOP */ []func(){action_dummy,\t\taction_dummy,\t\t\taction_dummy,\t\t\taction_dummy,\tfsm.action_pause,\tfsm.action_stop}, \n/*OBST */ []func(){action_dummy,\t\taction_dummy,\t\t\taction_dummy,\t\t\taction_dummy,\taction_dummy,\t\tfsm.action_stop}, \n/*OBST+EMG\t */\t []func(){action_dummy,\t\taction_dummy,\t\t\taction_dummy,\t\t\taction_dummy,\taction_dummy,\t\tfsm.action_stop}, \n\t}\n}", "func (dt *StdTask) Func() func(id int64) {\n return dt.F\n}", "func diHola() {\n\t//el contenido de la funcion esta aqui\n\tfmt.Println(\"Funcion Hola\")\n}", "func fibonacci() func() int {\n\tterm_1, term_2 := 0, 1\n\treturn func () int {\n\t\tto_return := term_1\n\t\t\n\t\tterm_1 = term_2\n\t\tterm_2 = term_2 + to_return\n\t\n\t\treturn to_return\n\t}\n}", "func CrearTablaRecurso() {\n\tEjecutarExec(queryRecurso)\n}", "func bar() func() int {\n return func() int {\n return 451\n }\n}", "func (s *BasemumpsListener) EnterFunction_(ctx *Function_Context) {}", "func (gb *Gameboy) mainInstructions() [0x100]func() {\n\t// TODO: possibly faster if we derefernce\n\t// each register and gb methods in this scope\n\n\t// ret gets returned\n\tret := [0x100]func(){\n\t\t0x06: func() {\n\t\t\t// LD B, n\n\t\t\tgb.CPU.BC.SetHi(gb.popPC())\n\t\t},\n\t\t0x0E: func() {\n\t\t\t// LD C, n\n\t\t\tgb.CPU.BC.SetLo(gb.popPC())\n\t\t},\n\t\t0x16: func() {\n\t\t\t// LD D, n\n\t\t\tgb.CPU.DE.SetHi(gb.popPC())\n\t\t},\n\t\t0x1E: func() {\n\t\t\t// LD E, n\n\t\t\tgb.CPU.DE.SetLo(gb.popPC())\n\t\t},\n\t\t0x26: func() {\n\t\t\t// LD H, n\n\t\t\tgb.CPU.HL.SetHi(gb.popPC())\n\t\t},\n\t\t0x2E: func() {\n\t\t\t// LD L, n\n\t\t\tgb.CPU.HL.SetLo(gb.popPC())\n\t\t},\n\t\t0x7F: func() {\n\t\t\t// LD A,A\n\t\t\tgb.CPU.AF.SetHi(gb.CPU.AF.Hi())\n\t\t},\n\t\t0x78: func() {\n\t\t\t// LD A,B\n\t\t\tgb.CPU.AF.SetHi(gb.CPU.BC.Hi())\n\t\t},\n\t\t0x79: func() {\n\t\t\t// LD A,C\n\t\t\tgb.CPU.AF.SetHi(gb.CPU.BC.Lo())\n\t\t},\n\t\t0x7A: func() {\n\t\t\t// LD A,D\n\t\t\tgb.CPU.AF.SetHi(gb.CPU.DE.Hi())\n\t\t},\n\t\t0x7B: func() {\n\t\t\t// LD A,E\n\t\t\tgb.CPU.AF.SetHi(gb.CPU.DE.Lo())\n\t\t},\n\t\t0x7C: func() {\n\t\t\t// LD A,H\n\t\t\tgb.CPU.AF.SetHi(gb.CPU.HL.Hi())\n\t\t},\n\t\t0x7D: func() {\n\t\t\t// LD A,L\n\t\t\tgb.CPU.AF.SetHi(gb.CPU.HL.Lo())\n\t\t},\n\t\t0x0A: func() {\n\t\t\t// LD A,(BC)\n\t\t\tval := gb.Memory.Read(gb.CPU.BC.HiLo())\n\t\t\tgb.CPU.AF.SetHi(val)\n\t\t},\n\t\t0x1A: func() {\n\t\t\t// LD A,(DE)\n\t\t\tval := gb.Memory.Read(gb.CPU.DE.HiLo())\n\t\t\tgb.CPU.AF.SetHi(val)\n\t\t},\n\t\t0x7E: func() {\n\t\t\t// LD A,(HL)\n\t\t\tval := gb.Memory.Read(gb.CPU.HL.HiLo())\n\t\t\tgb.CPU.AF.SetHi(val)\n\t\t},\n\t\t0xFA: func() {\n\t\t\t// LD A,(nn)\n\t\t\tval := gb.Memory.Read(gb.popPC16())\n\t\t\tgb.CPU.AF.SetHi(val)\n\t\t},\n\t\t0x3E: func() {\n\t\t\t// LD A,(nn)\n\t\t\tval := gb.popPC()\n\t\t\tgb.CPU.AF.SetHi(val)\n\t\t},\n\t\t0x47: func() {\n\t\t\t// LD B,A\n\t\t\tgb.CPU.BC.SetHi(gb.CPU.AF.Hi())\n\t\t},\n\t\t0x40: func() {\n\t\t\t// LD B,B\n\t\t\tgb.CPU.BC.SetHi(gb.CPU.BC.Hi())\n\t\t},\n\t\t0x41: func() {\n\t\t\t// LD B,C\n\t\t\tgb.CPU.BC.SetHi(gb.CPU.BC.Lo())\n\t\t},\n\t\t0x42: func() {\n\t\t\t// LD B,D\n\t\t\tgb.CPU.BC.SetHi(gb.CPU.DE.Hi())\n\t\t},\n\t\t0x43: func() {\n\t\t\t// LD B,E\n\t\t\tgb.CPU.BC.SetHi(gb.CPU.DE.Lo())\n\t\t},\n\t\t0x44: func() {\n\t\t\t// LD B,H\n\t\t\tgb.CPU.BC.SetHi(gb.CPU.HL.Hi())\n\t\t},\n\t\t0x45: func() {\n\t\t\t// LD B,L\n\t\t\tgb.CPU.BC.SetHi(gb.CPU.HL.Lo())\n\t\t},\n\t\t0x46: func() {\n\t\t\t// LD B,(HL)\n\t\t\tval := gb.Memory.Read(gb.CPU.HL.HiLo())\n\t\t\tgb.CPU.BC.SetHi(val)\n\t\t},\n\t\t0x4F: func() {\n\t\t\t// LD C,A\n\t\t\tgb.CPU.BC.SetLo(gb.CPU.AF.Hi())\n\t\t},\n\t\t0x48: func() {\n\t\t\t// LD C,B\n\t\t\tgb.CPU.BC.SetLo(gb.CPU.BC.Hi())\n\t\t},\n\t\t0x49: func() {\n\t\t\t// LD C,C\n\t\t\tgb.CPU.BC.SetLo(gb.CPU.BC.Lo())\n\t\t},\n\t\t0x4A: func() {\n\t\t\t// LD C,D\n\t\t\tgb.CPU.BC.SetLo(gb.CPU.DE.Hi())\n\t\t},\n\t\t0x4B: func() {\n\t\t\t// LD C,E\n\t\t\tgb.CPU.BC.SetLo(gb.CPU.DE.Lo())\n\t\t},\n\t\t0x4C: func() {\n\t\t\t// LD C,H\n\t\t\tgb.CPU.BC.SetLo(gb.CPU.HL.Hi())\n\t\t},\n\t\t0x4D: func() {\n\t\t\t// LD C,L\n\t\t\tgb.CPU.BC.SetLo(gb.CPU.HL.Lo())\n\t\t},\n\t\t0x4E: func() {\n\t\t\t// LD C,(HL)\n\t\t\tval := gb.Memory.Read(gb.CPU.HL.HiLo())\n\t\t\tgb.CPU.BC.SetLo(val)\n\t\t},\n\t\t0x57: func() {\n\t\t\t// LD D,A\n\t\t\tgb.CPU.DE.SetHi(gb.CPU.AF.Hi())\n\t\t},\n\t\t0x50: func() {\n\t\t\t// LD D,B\n\t\t\tgb.CPU.DE.SetHi(gb.CPU.BC.Hi())\n\t\t},\n\t\t0x51: func() {\n\t\t\t// LD D,C\n\t\t\tgb.CPU.DE.SetHi(gb.CPU.BC.Lo())\n\t\t},\n\t\t0x52: func() {\n\t\t\t// LD D,D\n\t\t\tgb.CPU.DE.SetHi(gb.CPU.DE.Hi())\n\t\t},\n\t\t0x53: func() {\n\t\t\t// LD D,E\n\t\t\tgb.CPU.DE.SetHi(gb.CPU.DE.Lo())\n\t\t},\n\t\t0x54: func() {\n\t\t\t// LD D,H\n\t\t\tgb.CPU.DE.SetHi(gb.CPU.HL.Hi())\n\t\t},\n\t\t0x55: func() {\n\t\t\t// LD D,L\n\t\t\tgb.CPU.DE.SetHi(gb.CPU.HL.Lo())\n\t\t},\n\t\t0x56: func() {\n\t\t\t// LD D,(HL)\n\t\t\tval := gb.Memory.Read(gb.CPU.HL.HiLo())\n\t\t\tgb.CPU.DE.SetHi(val)\n\t\t},\n\t\t0x5F: func() {\n\t\t\t// LD E,A\n\t\t\tgb.CPU.DE.SetLo(gb.CPU.AF.Hi())\n\t\t},\n\t\t0x58: func() {\n\t\t\t// LD E,B\n\t\t\tgb.CPU.DE.SetLo(gb.CPU.BC.Hi())\n\t\t},\n\t\t0x59: func() {\n\t\t\t// LD E,C\n\t\t\tgb.CPU.DE.SetLo(gb.CPU.BC.Lo())\n\t\t},\n\t\t0x5A: func() {\n\t\t\t// LD E,D\n\t\t\tgb.CPU.DE.SetLo(gb.CPU.DE.Hi())\n\t\t},\n\t\t0x5B: func() {\n\t\t\t// LD E,E\n\t\t\tgb.CPU.DE.SetLo(gb.CPU.DE.Lo())\n\t\t},\n\t\t0x5C: func() {\n\t\t\t// LD E,H\n\t\t\tgb.CPU.DE.SetLo(gb.CPU.HL.Hi())\n\t\t},\n\t\t0x5D: func() {\n\t\t\t// LD E,L\n\t\t\tgb.CPU.DE.SetLo(gb.CPU.HL.Lo())\n\t\t},\n\t\t0x5E: func() {\n\t\t\t// LD E,(HL)\n\t\t\tval := gb.Memory.Read(gb.CPU.HL.HiLo())\n\t\t\tgb.CPU.DE.SetLo(val)\n\t\t},\n\t\t0x67: func() {\n\t\t\t// LD H,A\n\t\t\tgb.CPU.HL.SetHi(gb.CPU.AF.Hi())\n\t\t},\n\t\t0x60: func() {\n\t\t\t// LD H,B\n\t\t\tgb.CPU.HL.SetHi(gb.CPU.BC.Hi())\n\t\t},\n\t\t0x61: func() {\n\t\t\t// LD H,C\n\t\t\tgb.CPU.HL.SetHi(gb.CPU.BC.Lo())\n\t\t},\n\t\t0x62: func() {\n\t\t\t// LD H,D\n\t\t\tgb.CPU.HL.SetHi(gb.CPU.DE.Hi())\n\t\t},\n\t\t0x63: func() {\n\t\t\t// LD H,E\n\t\t\tgb.CPU.HL.SetHi(gb.CPU.DE.Lo())\n\t\t},\n\t\t0x64: func() {\n\t\t\t// LD H,H\n\t\t\tgb.CPU.HL.SetHi(gb.CPU.HL.Hi())\n\t\t},\n\t\t0x65: func() {\n\t\t\t// LD H,L\n\t\t\tgb.CPU.HL.SetHi(gb.CPU.HL.Lo())\n\t\t},\n\t\t0x66: func() {\n\t\t\t// LD H,(HL)\n\t\t\tval := gb.Memory.Read(gb.CPU.HL.HiLo())\n\t\t\tgb.CPU.HL.SetHi(val)\n\t\t},\n\t\t0x6F: func() {\n\t\t\t// LD L,A\n\t\t\tgb.CPU.HL.SetLo(gb.CPU.AF.Hi())\n\t\t},\n\t\t0x68: func() {\n\t\t\t// LD L,B\n\t\t\tgb.CPU.HL.SetLo(gb.CPU.BC.Hi())\n\t\t},\n\t\t0x69: func() {\n\t\t\t// LD L,C\n\t\t\tgb.CPU.HL.SetLo(gb.CPU.BC.Lo())\n\t\t},\n\t\t0x6A: func() {\n\t\t\t// LD L,D\n\t\t\tgb.CPU.HL.SetLo(gb.CPU.DE.Hi())\n\t\t},\n\t\t0x6B: func() {\n\t\t\t// LD L,E\n\t\t\tgb.CPU.HL.SetLo(gb.CPU.DE.Lo())\n\t\t},\n\t\t0x6C: func() {\n\t\t\t// LD L,H\n\t\t\tgb.CPU.HL.SetLo(gb.CPU.HL.Hi())\n\t\t},\n\t\t0x6D: func() {\n\t\t\t// LD L,L\n\t\t\tgb.CPU.HL.SetLo(gb.CPU.HL.Lo())\n\t\t},\n\t\t0x6E: func() {\n\t\t\t// LD L,(HL)\n\t\t\tval := gb.Memory.Read(gb.CPU.HL.HiLo())\n\t\t\tgb.CPU.HL.SetLo(val)\n\t\t},\n\t\t0x77: func() {\n\t\t\t// LD (HL),A\n\t\t\tval := gb.CPU.AF.Hi()\n\t\t\tgb.Memory.Write(gb.CPU.HL.HiLo(), val)\n\t\t},\n\t\t0x70: func() {\n\t\t\t// LD (HL),B\n\t\t\tval := gb.CPU.BC.Hi()\n\t\t\tgb.Memory.Write(gb.CPU.HL.HiLo(), val)\n\t\t},\n\t\t0x71: func() {\n\t\t\t// LD (HL),C\n\t\t\tval := gb.CPU.BC.Lo()\n\t\t\tgb.Memory.Write(gb.CPU.HL.HiLo(), val)\n\t\t},\n\t\t0x72: func() {\n\t\t\t// LD (HL),D\n\t\t\tval := gb.CPU.DE.Hi()\n\t\t\tgb.Memory.Write(gb.CPU.HL.HiLo(), val)\n\t\t},\n\t\t0x73: func() {\n\t\t\t// LD (HL),E\n\t\t\tval := gb.CPU.DE.Lo()\n\t\t\tgb.Memory.Write(gb.CPU.HL.HiLo(), val)\n\t\t},\n\t\t0x74: func() {\n\t\t\t// LD (HL),H\n\t\t\tval := gb.CPU.HL.Hi()\n\t\t\tgb.Memory.Write(gb.CPU.HL.HiLo(), val)\n\t\t},\n\t\t0x75: func() {\n\t\t\t// LD (HL),L\n\t\t\tval := gb.CPU.HL.Lo()\n\t\t\tgb.Memory.Write(gb.CPU.HL.HiLo(), val)\n\t\t},\n\t\t0x36: func() {\n\t\t\t// LD (HL),n 36\n\t\t\tval := gb.popPC()\n\t\t\tgb.Memory.Write(gb.CPU.HL.HiLo(), val)\n\t\t},\n\t\t0x02: func() {\n\t\t\t// LD (BC),A\n\t\t\tval := gb.CPU.AF.Hi()\n\t\t\tgb.Memory.Write(gb.CPU.BC.HiLo(), val)\n\t\t},\n\t\t0x12: func() {\n\t\t\t// LD (DE),A\n\t\t\tval := gb.CPU.AF.Hi()\n\t\t\tgb.Memory.Write(gb.CPU.DE.HiLo(), val)\n\t\t},\n\t\t0xEA: func() {\n\t\t\t// LD (nn),A\n\t\t\tval := gb.CPU.AF.Hi()\n\t\t\tgb.Memory.Write(gb.popPC16(), val)\n\t\t},\n\t\t0xF2: func() {\n\t\t\t// LD A,(C)\n\t\t\tval := 0xFF00 + uint16(gb.CPU.BC.Lo())\n\t\t\tgb.CPU.AF.SetHi(gb.Memory.Read(val))\n\t\t},\n\t\t0xE2: func() {\n\t\t\t// LD (C),A\n\t\t\tval := gb.CPU.AF.Hi()\n\t\t\tmem := 0xFF00 + uint16(gb.CPU.BC.Lo())\n\t\t\tgb.Memory.Write(mem, val)\n\t\t},\n\t\t0x3A: func() {\n\t\t\t// LDD A,(HL)\n\t\t\tval := gb.Memory.Read(gb.CPU.HL.HiLo())\n\t\t\tgb.CPU.AF.SetHi(val)\n\t\t\tgb.CPU.HL.Set(gb.CPU.HL.HiLo() - 1)\n\t\t},\n\t\t0x32: func() {\n\t\t\t// LDD (HL),A\n\t\t\tval := gb.CPU.HL.HiLo()\n\t\t\tgb.Memory.Write(val, gb.CPU.AF.Hi())\n\t\t\tgb.CPU.HL.Set(gb.CPU.HL.HiLo() - 1)\n\t\t},\n\t\t0x2A: func() {\n\t\t\t// LDI A,(HL)\n\t\t\tval := gb.Memory.Read(gb.CPU.HL.HiLo())\n\t\t\tgb.CPU.AF.SetHi(val)\n\t\t\tgb.CPU.HL.Set(gb.CPU.HL.HiLo() + 1)\n\t\t},\n\t\t0x22: func() {\n\t\t\t// LDI (HL),A\n\t\t\tval := gb.CPU.HL.HiLo()\n\t\t\tgb.Memory.Write(val, gb.CPU.AF.Hi())\n\t\t\tgb.CPU.HL.Set(gb.CPU.HL.HiLo() + 1)\n\t\t},\n\t\t0xE0: func() {\n\t\t\t// LD (0xFF00+n),A\n\t\t\tval := 0xFF00 + uint16(gb.popPC())\n\t\t\tgb.Memory.Write(val, gb.CPU.AF.Hi())\n\t\t},\n\t\t0xF0: func() {\n\t\t\t// LD A,(0xFF00+n)\n\t\t\tval := gb.Memory.ReadHighRam(0xFF00 + uint16(gb.popPC()))\n\t\t\tgb.CPU.AF.SetHi(val)\n\t\t},\n\t\t// ========== 16-Bit Loads ===========\n\t\t0x01: func() {\n\t\t\t// LD BC,nn\n\t\t\tval := gb.popPC16()\n\t\t\tgb.CPU.BC.Set(val)\n\t\t},\n\t\t0x11: func() {\n\t\t\t// LD DE,nn\n\t\t\tval := gb.popPC16()\n\t\t\tgb.CPU.DE.Set(val)\n\t\t},\n\t\t0x21: func() {\n\t\t\t// LD HL,nn\n\t\t\tval := gb.popPC16()\n\t\t\tgb.CPU.HL.Set(val)\n\t\t},\n\t\t0x31: func() {\n\t\t\t// LD SP,nn\n\t\t\tval := gb.popPC16()\n\t\t\tgb.CPU.SP.Set(val)\n\t\t},\n\t\t0xF9: func() {\n\t\t\t// LD SP,HL\n\t\t\tval := gb.CPU.HL\n\t\t\tgb.CPU.SP = val\n\t\t},\n\t\t0xF8: func() {\n\t\t\t// LD HL,SP+n\n\t\t\tval1 := int32(gb.CPU.SP.HiLo())\n\t\t\tval2 := int32(int8(gb.popPC()))\n\t\t\tresult := val1 + val2\n\t\t\tgb.CPU.HL.Set(uint16(result))\n\t\t\ttempVal := val1 ^ val2 ^ result\n\t\t\tgb.CPU.SetZ(false)\n\t\t\tgb.CPU.SetN(false)\n\t\t\t// TODO: Probably check these\n\t\t\tgb.CPU.SetH((tempVal & 0x10) == 0x10)\n\t\t\tgb.CPU.SetC((tempVal & 0x100) == 0x100)\n\t\t},\n\t\t0x08: func() {\n\t\t\t// LD (nn),SP\n\t\t\taddress := gb.popPC16()\n\t\t\tgb.Memory.Write(address, gb.CPU.SP.Lo())\n\t\t\tgb.Memory.Write(address+1, gb.CPU.SP.Hi())\n\t\t},\n\t\t0xF5: func() {\n\t\t\t// PUSH AF\n\t\t\tgb.pushStack(gb.CPU.AF.HiLo())\n\t\t},\n\t\t0xC5: func() {\n\t\t\t// PUSH BC\n\t\t\tgb.pushStack(gb.CPU.BC.HiLo())\n\t\t},\n\t\t0xD5: func() {\n\t\t\t// PUSH DE\n\t\t\tgb.pushStack(gb.CPU.DE.HiLo())\n\t\t},\n\t\t0xE5: func() {\n\t\t\t// PUSH HL\n\t\t\tgb.pushStack(gb.CPU.HL.HiLo())\n\t\t},\n\t\t0xF1: func() {\n\t\t\t// POP AF\n\t\t\tgb.CPU.AF.Set(gb.popStack())\n\t\t},\n\t\t0xC1: func() {\n\t\t\t// POP BC\n\t\t\tgb.CPU.BC.Set(gb.popStack())\n\t\t},\n\t\t0xD1: func() {\n\t\t\t// POP DE\n\t\t\tgb.CPU.DE.Set(gb.popStack())\n\t\t},\n\t\t0xE1: func() {\n\t\t\t// POP HL\n\t\t\tgb.CPU.HL.Set(gb.popStack())\n\t\t},\n\t\t// ========== 8-Bit ALU ===========\n\t\t0x87: func() {\n\t\t\t// ADD A,A\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.AF.Hi(), false)\n\t\t},\n\t\t0x80: func() {\n\t\t\t// ADD A,B\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.CPU.BC.Hi(), gb.CPU.AF.Hi(), false)\n\t\t},\n\t\t0x81: func() {\n\t\t\t// ADD A,C\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.CPU.BC.Lo(), gb.CPU.AF.Hi(), false)\n\t\t},\n\t\t0x82: func() {\n\t\t\t// ADD A,D\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.CPU.DE.Hi(), gb.CPU.AF.Hi(), false)\n\t\t},\n\t\t0x83: func() {\n\t\t\t// ADD A,E\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.CPU.DE.Lo(), gb.CPU.AF.Hi(), false)\n\t\t},\n\t\t0x84: func() {\n\t\t\t// ADD A,H\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.CPU.HL.Hi(), gb.CPU.AF.Hi(), false)\n\t\t},\n\t\t0x85: func() {\n\t\t\t// ADD A,L\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.CPU.HL.Lo(), gb.CPU.AF.Hi(), false)\n\t\t},\n\t\t0x86: func() {\n\t\t\t// ADD A,(HL)\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.Memory.Read(gb.CPU.HL.HiLo()), gb.CPU.AF.Hi(), false)\n\t\t},\n\t\t0xC6: func() {\n\t\t\t// ADD A,#\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.popPC(), gb.CPU.AF.Hi(), false)\n\t\t},\n\t\t0x8F: func() {\n\t\t\t// ADC A,A\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.AF.Hi(), true)\n\t\t},\n\t\t0x88: func() {\n\t\t\t// ADC A,B\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.CPU.BC.Hi(), gb.CPU.AF.Hi(), true)\n\t\t},\n\t\t0x89: func() {\n\t\t\t// ADC A,C\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.CPU.BC.Lo(), gb.CPU.AF.Hi(), true)\n\t\t},\n\t\t0x8A: func() {\n\t\t\t// ADC A,D\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.CPU.DE.Hi(), gb.CPU.AF.Hi(), true)\n\t\t},\n\t\t0x8B: func() {\n\t\t\t// ADC A,E\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.CPU.DE.Lo(), gb.CPU.AF.Hi(), true)\n\t\t},\n\t\t0x8C: func() {\n\t\t\t// ADC A,H\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.CPU.HL.Hi(), gb.CPU.AF.Hi(), true)\n\t\t},\n\t\t0x8D: func() {\n\t\t\t// ADC A,L\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.CPU.HL.Lo(), gb.CPU.AF.Hi(), true)\n\t\t},\n\t\t0x8E: func() {\n\t\t\t// ADC A,(HL)\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.Memory.Read(gb.CPU.HL.HiLo()), gb.CPU.AF.Hi(), true)\n\t\t},\n\t\t0xCE: func() {\n\t\t\t// ADC A,#\n\t\t\tgb.instAdd(gb.CPU.AF.SetHi, gb.popPC(), gb.CPU.AF.Hi(), true)\n\t\t},\n\t\t0x97: func() {\n\t\t\t// SUB A,A\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.AF.Hi(), false)\n\t\t},\n\t\t0x90: func() {\n\t\t\t// SUB A,B\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.BC.Hi(), false)\n\t\t},\n\t\t0x91: func() {\n\t\t\t// SUB A,C\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.BC.Lo(), false)\n\t\t},\n\t\t0x92: func() {\n\t\t\t// SUB A,D\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.DE.Hi(), false)\n\t\t},\n\t\t0x93: func() {\n\t\t\t// SUB A,E\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.DE.Lo(), false)\n\t\t},\n\t\t0x94: func() {\n\t\t\t// SUB A,H\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.HL.Hi(), false)\n\t\t},\n\t\t0x95: func() {\n\t\t\t// SUB A,L\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.HL.Lo(), false)\n\t\t},\n\t\t0x96: func() {\n\t\t\t// SUB A,(HL)\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.Memory.Read(gb.CPU.HL.HiLo()), false)\n\t\t},\n\t\t0xD6: func() {\n\t\t\t// SUB A,#\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.popPC(), false)\n\t\t},\n\t\t0x9F: func() {\n\t\t\t// SBC A,A\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.AF.Hi(), true)\n\t\t},\n\t\t0x98: func() {\n\t\t\t// SBC A,B\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.BC.Hi(), true)\n\t\t},\n\t\t0x99: func() {\n\t\t\t// SBC A,C\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.BC.Lo(), true)\n\t\t},\n\t\t0x9A: func() {\n\t\t\t// SBC A,D\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.DE.Hi(), true)\n\t\t},\n\t\t0x9B: func() {\n\t\t\t// SBC A,E\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.DE.Lo(), true)\n\t\t},\n\t\t0x9C: func() {\n\t\t\t// SBC A,H\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.HL.Hi(), true)\n\t\t},\n\t\t0x9D: func() {\n\t\t\t// SBC A,L\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.HL.Lo(), true)\n\t\t},\n\t\t0x9E: func() {\n\t\t\t// SBC A,(HL)\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.Memory.Read(gb.CPU.HL.HiLo()), true)\n\t\t},\n\t\t0xDE: func() {\n\t\t\t// SBC A,#\n\t\t\tgb.instSub(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.popPC(), true)\n\t\t},\n\t\t0xA7: func() {\n\t\t\t// AND A,A\n\t\t\tgb.instAnd(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xA0: func() {\n\t\t\t// AND A,B\n\t\t\tgb.instAnd(gb.CPU.AF.SetHi, gb.CPU.BC.Hi(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xA1: func() {\n\t\t\t// AND A,C\n\t\t\tgb.instAnd(gb.CPU.AF.SetHi, gb.CPU.BC.Lo(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xA2: func() {\n\t\t\t// AND A,D\n\t\t\tgb.instAnd(gb.CPU.AF.SetHi, gb.CPU.DE.Hi(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xA3: func() {\n\t\t\t// AND A,E\n\t\t\tgb.instAnd(gb.CPU.AF.SetHi, gb.CPU.DE.Lo(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xA4: func() {\n\t\t\t// AND A,H\n\t\t\tgb.instAnd(gb.CPU.AF.SetHi, gb.CPU.HL.Hi(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xA5: func() {\n\t\t\t// AND A,L\n\t\t\tgb.instAnd(gb.CPU.AF.SetHi, gb.CPU.HL.Lo(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xA6: func() {\n\t\t\t// AND A,(HL)\n\t\t\tgb.instAnd(gb.CPU.AF.SetHi, gb.Memory.Read(gb.CPU.HL.HiLo()), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xE6: func() {\n\t\t\t// AND A,#\n\t\t\tgb.instAnd(gb.CPU.AF.SetHi, gb.popPC(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xB7: func() {\n\t\t\t// OR A,A\n\t\t\tgb.instOr(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xB0: func() {\n\t\t\t// OR A,B\n\t\t\tgb.instOr(gb.CPU.AF.SetHi, gb.CPU.BC.Hi(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xB1: func() {\n\t\t\t// OR A,C\n\t\t\tgb.instOr(gb.CPU.AF.SetHi, gb.CPU.BC.Lo(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xB2: func() {\n\t\t\t// OR A,D\n\t\t\tgb.instOr(gb.CPU.AF.SetHi, gb.CPU.DE.Hi(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xB3: func() {\n\t\t\t// OR A,E\n\t\t\tgb.instOr(gb.CPU.AF.SetHi, gb.CPU.DE.Lo(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xB4: func() {\n\t\t\t// OR A,H\n\t\t\tgb.instOr(gb.CPU.AF.SetHi, gb.CPU.HL.Hi(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xB5: func() {\n\t\t\t// OR A,L\n\t\t\tgb.instOr(gb.CPU.AF.SetHi, gb.CPU.HL.Lo(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xB6: func() {\n\t\t\t// OR A,(HL)\n\t\t\tgb.instOr(gb.CPU.AF.SetHi, gb.Memory.Read(gb.CPU.HL.HiLo()), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xF6: func() {\n\t\t\t// OR A,#\n\t\t\tgb.instOr(gb.CPU.AF.SetHi, gb.popPC(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xAF: func() {\n\t\t\t// XOR A,A\n\t\t\tgb.instXor(gb.CPU.AF.SetHi, gb.CPU.AF.Hi(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xA8: func() {\n\t\t\t// XOR A,B\n\t\t\tgb.instXor(gb.CPU.AF.SetHi, gb.CPU.BC.Hi(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xA9: func() {\n\t\t\t// XOR A,C\n\t\t\tgb.instXor(gb.CPU.AF.SetHi, gb.CPU.BC.Lo(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xAA: func() {\n\t\t\t// XOR A,D\n\t\t\tgb.instXor(gb.CPU.AF.SetHi, gb.CPU.DE.Hi(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xAB: func() {\n\t\t\t// XOR A,E\n\t\t\tgb.instXor(gb.CPU.AF.SetHi, gb.CPU.DE.Lo(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xAC: func() {\n\t\t\t// XOR A,H\n\t\t\tgb.instXor(gb.CPU.AF.SetHi, gb.CPU.HL.Hi(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xAD: func() {\n\t\t\t// XOR A,L\n\t\t\tgb.instXor(gb.CPU.AF.SetHi, gb.CPU.HL.Lo(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xAE: func() {\n\t\t\t// XOR A,(HL)\n\t\t\tgb.instXor(gb.CPU.AF.SetHi, gb.Memory.Read(gb.CPU.HL.HiLo()), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xEE: func() {\n\t\t\t// XOR A,#\n\t\t\tgb.instXor(gb.CPU.AF.SetHi, gb.popPC(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xBF: func() {\n\t\t\t// CP A,A\n\t\t\tgb.instCp(gb.CPU.AF.Hi(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xB8: func() {\n\t\t\t// CP A,B\n\t\t\tgb.instCp(gb.CPU.BC.Hi(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xB9: func() {\n\t\t\t// CP A,C\n\t\t\tgb.instCp(gb.CPU.BC.Lo(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xBA: func() {\n\t\t\t// CP A,D\n\t\t\tgb.instCp(gb.CPU.DE.Hi(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xBB: func() {\n\t\t\t// CP A,E\n\t\t\tgb.instCp(gb.CPU.DE.Lo(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xBC: func() {\n\t\t\t// CP A,H\n\t\t\tgb.instCp(gb.CPU.HL.Hi(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xBD: func() {\n\t\t\t// CP A,L\n\t\t\tgb.instCp(gb.CPU.HL.Lo(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xBE: func() {\n\t\t\t// CP A,(HL)\n\t\t\tgb.instCp(gb.Memory.Read(gb.CPU.HL.HiLo()), gb.CPU.AF.Hi())\n\t\t},\n\t\t0xFE: func() {\n\t\t\t// CP A,#\n\t\t\tgb.instCp(gb.popPC(), gb.CPU.AF.Hi())\n\t\t},\n\t\t0x3C: func() {\n\t\t\t// INC A\n\t\t\tgb.instInc(gb.CPU.AF.SetHi, gb.CPU.AF.Hi())\n\t\t},\n\t\t0x04: func() {\n\t\t\t// INC B\n\t\t\tgb.instInc(gb.CPU.BC.SetHi, gb.CPU.BC.Hi())\n\t\t},\n\t\t0x0C: func() {\n\t\t\t// INC C\n\t\t\tgb.instInc(gb.CPU.BC.SetLo, gb.CPU.BC.Lo())\n\t\t},\n\t\t0x14: func() {\n\t\t\t// INC D\n\t\t\tgb.instInc(gb.CPU.DE.SetHi, gb.CPU.DE.Hi())\n\t\t},\n\t\t0x1C: func() {\n\t\t\t// INC E\n\t\t\tgb.instInc(gb.CPU.DE.SetLo, gb.CPU.DE.Lo())\n\t\t},\n\t\t0x24: func() {\n\t\t\t// INC H\n\t\t\tgb.instInc(gb.CPU.HL.SetHi, gb.CPU.HL.Hi())\n\t\t},\n\t\t0x2C: func() {\n\t\t\t// INC L\n\t\t\tgb.instInc(gb.CPU.HL.SetLo, gb.CPU.HL.Lo())\n\t\t},\n\t\t0x34: func() {\n\t\t\t// INC (HL)\n\t\t\taddr := gb.CPU.HL.HiLo()\n\t\t\tgb.instInc(func(val byte) { gb.Memory.Write(addr, val) }, gb.Memory.Read(addr))\n\t\t},\n\t\t0x3D: func() {\n\t\t\t// DEC A\n\t\t\tgb.instDec(gb.CPU.AF.SetHi, gb.CPU.AF.Hi())\n\t\t},\n\t\t0x05: func() {\n\t\t\t// DEC B\n\t\t\tgb.instDec(gb.CPU.BC.SetHi, gb.CPU.BC.Hi())\n\t\t},\n\t\t0x0D: func() {\n\t\t\t// DEC C\n\t\t\tgb.instDec(gb.CPU.BC.SetLo, gb.CPU.BC.Lo())\n\t\t},\n\t\t0x15: func() {\n\t\t\t// DEC D\n\t\t\tgb.instDec(gb.CPU.DE.SetHi, gb.CPU.DE.Hi())\n\t\t},\n\t\t0x1D: func() {\n\t\t\t// DEC E\n\t\t\tgb.instDec(gb.CPU.DE.SetLo, gb.CPU.DE.Lo())\n\t\t},\n\t\t0x25: func() {\n\t\t\t// DEC H\n\t\t\tgb.instDec(gb.CPU.HL.SetHi, gb.CPU.HL.Hi())\n\t\t},\n\t\t0x2D: func() {\n\t\t\t// DEC L\n\t\t\tgb.instDec(gb.CPU.HL.SetLo, gb.CPU.HL.Lo())\n\t\t},\n\t\t0x35: func() {\n\t\t\t// DEC (HL)\n\t\t\taddr := gb.CPU.HL.HiLo()\n\t\t\tgb.instDec(func(val byte) { gb.Memory.Write(addr, val) }, gb.Memory.Read(addr))\n\t\t},\n\t\t// ========== 16-Bit ALU ===========\n\t\t0x09: func() {\n\t\t\t// ADD HL,BC\n\t\t\tgb.instAdd16(gb.CPU.HL.Set, gb.CPU.HL.HiLo(), gb.CPU.BC.HiLo())\n\t\t},\n\t\t0x19: func() {\n\t\t\t// ADD HL,DE\n\t\t\tgb.instAdd16(gb.CPU.HL.Set, gb.CPU.HL.HiLo(), gb.CPU.DE.HiLo())\n\t\t},\n\t\t0x29: func() {\n\t\t\t// ADD HL,HL\n\t\t\tgb.instAdd16(gb.CPU.HL.Set, gb.CPU.HL.HiLo(), gb.CPU.HL.HiLo())\n\t\t},\n\t\t0x39: func() {\n\t\t\t// ADD HL,SP\n\t\t\tgb.instAdd16(gb.CPU.HL.Set, gb.CPU.HL.HiLo(), gb.CPU.SP.HiLo())\n\t\t},\n\t\t0xE8: func() {\n\t\t\t// ADD SP,n\n\t\t\tgb.instAdd16Signed(gb.CPU.SP.Set, gb.CPU.SP.HiLo(), int8(gb.popPC()))\n\t\t\tgb.CPU.SetZ(false)\n\t\t},\n\t\t0x03: func() {\n\t\t\t// INC BC\n\t\t\tgb.instInc16(gb.CPU.BC.Set, gb.CPU.BC.HiLo())\n\t\t},\n\t\t0x13: func() {\n\t\t\t// INC DE\n\t\t\tgb.instInc16(gb.CPU.DE.Set, gb.CPU.DE.HiLo())\n\t\t},\n\t\t0x23: func() {\n\t\t\t// INC HL\n\t\t\tgb.instInc16(gb.CPU.HL.Set, gb.CPU.HL.HiLo())\n\t\t},\n\t\t0x33: func() {\n\t\t\t// INC SP\n\t\t\tgb.instInc16(gb.CPU.SP.Set, gb.CPU.SP.HiLo())\n\t\t},\n\t\t0x0B: func() {\n\t\t\t// DEC BC\n\t\t\tgb.instDec16(gb.CPU.BC.Set, gb.CPU.BC.HiLo())\n\t\t},\n\t\t0x1B: func() {\n\t\t\t// DEC DE\n\t\t\tgb.instDec16(gb.CPU.DE.Set, gb.CPU.DE.HiLo())\n\t\t},\n\t\t0x2B: func() {\n\t\t\t// DEC HL\n\t\t\tgb.instDec16(gb.CPU.HL.Set, gb.CPU.HL.HiLo())\n\t\t},\n\t\t0x3B: func() {\n\t\t\t// DEC SP\n\t\t\tgb.instDec16(gb.CPU.SP.Set, gb.CPU.SP.HiLo())\n\t\t},\n\t\t0x27: func() {\n\t\t\t// DAA\n\t\t\t// When this instruction is executed, the A register is BCD\n\t\t\t// corrected using the contents of the flags. The exact process\n\t\t\t// is the following: if the least significant four bits of A\n\t\t\t// contain a non-BCD digit (i. e. it is greater than 9) or the\n\t\t\t// H flag is set, then $06 is added to the register. Then the\n\t\t\t// four most significant bits are checked. If this more significant\n\t\t\t// digit also happens to be greater than 9 or the C flag is set,\n\t\t\t// then $60 is added.\n\t\t\tif !gb.CPU.N() {\n\t\t\t\t// TODO: This could be more efficient?\n\t\t\t\tif gb.CPU.C() || gb.CPU.AF.Hi() > 0x99 {\n\t\t\t\t\tgb.CPU.AF.SetHi(gb.CPU.AF.Hi() + 0x60)\n\t\t\t\t\tgb.CPU.SetC(true)\n\t\t\t\t}\n\t\t\t\tif gb.CPU.H() || gb.CPU.AF.Hi()&0xF > 0x9 {\n\t\t\t\t\tgb.CPU.AF.SetHi(gb.CPU.AF.Hi() + 0x06)\n\t\t\t\t\tgb.CPU.SetH(false)\n\t\t\t\t}\n\t\t\t} else if gb.CPU.C() && gb.CPU.H() {\n\t\t\t\tgb.CPU.AF.SetHi(gb.CPU.AF.Hi() + 0x9A)\n\t\t\t\tgb.CPU.SetH(false)\n\t\t\t} else if gb.CPU.C() {\n\t\t\t\tgb.CPU.AF.SetHi(gb.CPU.AF.Hi() + 0xA0)\n\t\t\t} else if gb.CPU.H() {\n\t\t\t\tgb.CPU.AF.SetHi(gb.CPU.AF.Hi() + 0xFA)\n\t\t\t\tgb.CPU.SetH(false)\n\t\t\t}\n\t\t\tgb.CPU.SetZ(gb.CPU.AF.Hi() == 0)\n\t\t},\n\t\t0x2F: func() {\n\t\t\t// CPL\n\t\t\tgb.CPU.AF.SetHi(0xFF ^ gb.CPU.AF.Hi())\n\t\t\tgb.CPU.SetN(true)\n\t\t\tgb.CPU.SetH(true)\n\t\t},\n\t\t0x3F: func() {\n\t\t\t// CCF\n\t\t\tgb.CPU.SetN(false)\n\t\t\tgb.CPU.SetH(false)\n\t\t\tgb.CPU.SetC(!gb.CPU.C())\n\t\t},\n\t\t0x37: func() {\n\t\t\t// SCF\n\t\t\tgb.CPU.SetN(false)\n\t\t\tgb.CPU.SetH(false)\n\t\t\tgb.CPU.SetC(true)\n\t\t},\n\t\t0x00: func() {\n\t\t\t// NOP\n\t\t},\n\t\t0x76: func() {\n\t\t\t// HALT\n\t\t\tgb.halted = true\n\t\t},\n\t\t0x10: func() {\n\t\t\t// STOP\n\t\t\t//gb.halted = true\n\t\t\tlog.Print(\"0x10 (STOP) unimplemented (is 0x00 follows)\")\n\t\t},\n\t\t0xF3: func() {\n\t\t\t// DI\n\t\t\tgb.interruptsOn = false\n\t\t},\n\t\t0xFB: func() {\n\t\t\t// EI\n\t\t\tgb.interruptsEnabling = true\n\t\t},\n\t\t0x07: func() {\n\t\t\t// RLCA\n\t\t\tvalue := gb.CPU.AF.Hi()\n\t\t\tresult := byte(value<<1) | (value >> 7)\n\t\t\tgb.CPU.AF.SetHi(result)\n\t\t\tgb.CPU.SetZ(false)\n\t\t\tgb.CPU.SetN(false)\n\t\t\tgb.CPU.SetH(false)\n\t\t\tgb.CPU.SetC(value > 0x7F)\n\t\t},\n\t\t0x17: func() {\n\t\t\t// RLA\n\t\t\tvalue := gb.CPU.AF.Hi()\n\t\t\tvar carry byte\n\t\t\tif gb.CPU.C() {\n\t\t\t\tcarry = 1\n\t\t\t}\n\t\t\tresult := byte(value<<1) + carry\n\t\t\tgb.CPU.AF.SetHi(result)\n\t\t\tgb.CPU.SetZ(false)\n\t\t\tgb.CPU.SetN(false)\n\t\t\tgb.CPU.SetH(false)\n\t\t\tgb.CPU.SetC(value > 0x7F)\n\t\t},\n\t\t0x0F: func() {\n\t\t\t// RRCA\n\t\t\tvalue := gb.CPU.AF.Hi()\n\t\t\tresult := byte(value>>1) | byte((value&1)<<7)\n\t\t\tgb.CPU.AF.SetHi(result)\n\t\t\tgb.CPU.SetZ(false)\n\t\t\tgb.CPU.SetN(false)\n\t\t\tgb.CPU.SetH(false)\n\t\t\tgb.CPU.SetC(result > 0x7F)\n\t\t},\n\t\t0x1F: func() {\n\t\t\t// RRA\n\t\t\tvalue := gb.CPU.AF.Hi()\n\t\t\tvar carry byte\n\t\t\tif gb.CPU.C() {\n\t\t\t\tcarry = 0x80\n\t\t\t}\n\t\t\tresult := byte(value>>1) | carry\n\t\t\tgb.CPU.AF.SetHi(result)\n\t\t\tgb.CPU.SetZ(false)\n\t\t\tgb.CPU.SetN(false)\n\t\t\tgb.CPU.SetH(false)\n\t\t\tgb.CPU.SetC((1 & value) == 1)\n\t\t},\n\t\t0xC3: func() {\n\t\t\t// JP nn\n\t\t\tgb.instJump(gb.popPC16())\n\t\t},\n\t\t0xC2: func() {\n\t\t\t// JP NZ,nn\n\t\t\tnext := gb.popPC16()\n\t\t\tif !gb.CPU.Z() {\n\t\t\t\tgb.instJump(next)\n\t\t\t\tgb.thisCpuTicks += 4\n\t\t\t}\n\t\t},\n\t\t0xCA: func() {\n\t\t\t// JP Z,nn\n\t\t\tnext := gb.popPC16()\n\t\t\tif gb.CPU.Z() {\n\t\t\t\tgb.instJump(next)\n\t\t\t\tgb.thisCpuTicks += 4\n\t\t\t}\n\t\t},\n\t\t0xD2: func() {\n\t\t\t// JP NC,nn\n\t\t\tnext := gb.popPC16()\n\t\t\tif !gb.CPU.C() {\n\t\t\t\tgb.instJump(next)\n\t\t\t\tgb.thisCpuTicks += 4\n\t\t\t}\n\t\t},\n\t\t0xDA: func() {\n\t\t\t// JP C,nn\n\t\t\tnext := gb.popPC16()\n\t\t\tif gb.CPU.C() {\n\t\t\t\tgb.instJump(next)\n\t\t\t\tgb.thisCpuTicks += 4\n\t\t\t}\n\t\t},\n\t\t0xE9: func() {\n\t\t\t// JP HL\n\t\t\tgb.instJump(gb.CPU.HL.HiLo())\n\t\t},\n\t\t0x18: func() {\n\t\t\t// JR n\n\t\t\taddr := int32(gb.CPU.PC) + int32(int8(gb.popPC()))\n\t\t\tgb.instJump(uint16(addr))\n\t\t},\n\t\t0x20: func() {\n\t\t\t// JR NZ,n\n\t\t\tnext := int8(gb.popPC())\n\t\t\tif !gb.CPU.Z() {\n\t\t\t\taddr := int32(gb.CPU.PC) + int32(next)\n\t\t\t\tgb.instJump(uint16(addr))\n\t\t\t\tgb.thisCpuTicks += 4\n\t\t\t}\n\t\t},\n\t\t0x28: func() {\n\t\t\t// JR Z,n\n\t\t\tnext := int8(gb.popPC())\n\t\t\tif gb.CPU.Z() {\n\t\t\t\taddr := int32(gb.CPU.PC) + int32(next)\n\t\t\t\tgb.instJump(uint16(addr))\n\t\t\t\tgb.thisCpuTicks += 4\n\t\t\t}\n\t\t},\n\t\t0x30: func() {\n\t\t\t// JR NC,n\n\t\t\tnext := int8(gb.popPC())\n\t\t\tif !gb.CPU.C() {\n\t\t\t\taddr := int32(gb.CPU.PC) + int32(next)\n\t\t\t\tgb.instJump(uint16(addr))\n\t\t\t\tgb.thisCpuTicks += 4\n\t\t\t}\n\t\t},\n\t\t0x38: func() {\n\t\t\t// JR C,n\n\t\t\tnext := int8(gb.popPC())\n\t\t\tif gb.CPU.C() {\n\t\t\t\taddr := int32(gb.CPU.PC) + int32(next)\n\t\t\t\tgb.instJump(uint16(addr))\n\t\t\t\tgb.thisCpuTicks += 4\n\t\t\t}\n\t\t},\n\t\t0xCD: func() {\n\t\t\t// CALL nn\n\t\t\tgb.instCall(gb.popPC16())\n\t\t},\n\t\t0xC4: func() {\n\t\t\t// CALL NZ,nn\n\t\t\tnext := gb.popPC16()\n\t\t\tif !gb.CPU.Z() {\n\t\t\t\tgb.instCall(next)\n\t\t\t\tgb.thisCpuTicks += 12\n\t\t\t}\n\t\t},\n\t\t0xCC: func() {\n\t\t\t// CALL Z,nn\n\t\t\tnext := gb.popPC16()\n\t\t\tif gb.CPU.Z() {\n\t\t\t\tgb.instCall(next)\n\t\t\t\tgb.thisCpuTicks += 12\n\t\t\t}\n\t\t},\n\t\t0xD4: func() {\n\t\t\t// CALL NC,nn\n\t\t\tnext := gb.popPC16()\n\t\t\tif !gb.CPU.C() {\n\t\t\t\tgb.instCall(next)\n\t\t\t\tgb.thisCpuTicks += 12\n\t\t\t}\n\t\t},\n\t\t0xDC: func() {\n\t\t\t// CALL C,nn\n\t\t\tnext := gb.popPC16()\n\t\t\tif gb.CPU.C() {\n\t\t\t\tgb.instCall(next)\n\t\t\t\tgb.thisCpuTicks += 12\n\t\t\t}\n\t\t},\n\t\t0xC7: func() {\n\t\t\t// RST 0x00\n\t\t\tgb.instCall(0x0000)\n\t\t},\n\t\t0xCF: func() {\n\t\t\t// RST 0x08\n\t\t\tgb.instCall(0x0008)\n\t\t},\n\t\t0xD7: func() {\n\t\t\t// RST 0x10\n\t\t\tgb.instCall(0x0010)\n\t\t},\n\t\t0xDF: func() {\n\t\t\t// RST 0x18\n\t\t\tgb.instCall(0x0018)\n\t\t},\n\t\t0xE7: func() {\n\t\t\t// RST 0x20\n\t\t\tgb.instCall(0x0020)\n\t\t},\n\t\t0xEF: func() {\n\t\t\t// RST 0x28\n\t\t\tgb.instCall(0x0028)\n\t\t},\n\t\t0xF7: func() {\n\t\t\t// RST 0x30\n\t\t\tgb.instCall(0x0030)\n\t\t},\n\t\t0xFF: func() {\n\t\t\t// RST 0x38\n\t\t\tgb.instCall(0x0038)\n\t\t},\n\t\t0xC9: func() {\n\t\t\t// RET\n\t\t\tgb.instRet()\n\t\t},\n\t\t0xC0: func() {\n\t\t\t// RET NZ\n\t\t\tif !gb.CPU.Z() {\n\t\t\t\tgb.instRet()\n\t\t\t\tgb.thisCpuTicks += 12\n\t\t\t}\n\t\t},\n\t\t0xC8: func() {\n\t\t\t// RET Z\n\t\t\tif gb.CPU.Z() {\n\t\t\t\tgb.instRet()\n\t\t\t\tgb.thisCpuTicks += 12\n\t\t\t}\n\t\t},\n\t\t0xD0: func() {\n\t\t\t// RET NC\n\t\t\tif !gb.CPU.C() {\n\t\t\t\tgb.instRet()\n\t\t\t\tgb.thisCpuTicks += 12\n\t\t\t}\n\t\t},\n\t\t0xD8: func() {\n\t\t\t// RET C\n\t\t\tif gb.CPU.C() {\n\t\t\t\tgb.instRet()\n\t\t\t\tgb.thisCpuTicks += 12\n\t\t\t}\n\t\t},\n\t\t0xD9: func() {\n\t\t\t// RETI\n\t\t\tgb.instRet()\n\t\t\tgb.interruptsEnabling = true\n\t\t},\n\t\t0xCB: func() {\n\t\t\t// CB\n\t\t\tnextInst := gb.popPC()\n\t\t\tgb.thisCpuTicks += CBOpcodeCycles[nextInst] * 4\n\t\t\tgb.cbInst[nextInst]()\n\t\t},\n\t}\n\t// fill the empty elements of the array\n\t// with a noop function to eliminate null checks\n\tfor k, v := range ret {\n\t\tif v == nil {\n\t\t\topcode := k\n\t\t\tret[k] = func() {\n\t\t\t\tlog.Printf(\"Unimplemented opcode: %#2x\", opcode)\n\t\t\t\tWaitForInput()\n\t\t\t}\n\t\t}\n\t}\n\treturn ret\n}", "func (urli *URLInsane) FuncChain(funcs []Extra, in <-chan TypoResult) <-chan TypoResult {\n\tvar xfunc Extra\n\tout := make(chan TypoResult)\n\txfunc, funcs = funcs[len(funcs)-1], funcs[:len(funcs)-1]\n\tgo func() {\n\t\tfor i := range in {\n\t\t\tfor _, result := range xfunc.Exec(i) {\n\t\t\t\tout <- result\n\t\t\t}\n\t\t}\n\t\tclose(out)\n\t}()\n\n\tif len(funcs) > 0 {\n\t\treturn urli.FuncChain(funcs, out)\n\t} else {\n\t\treturn out\n\t}\n}", "func makeGreeter() func() string {\n\treturn func() string {\n\t\treturn \"Hello World\"\n\n\t}\n}", "func fibonacci() func() int {\n a := 0\n b := 1\n c := 0\n return func() int {\n c, a, b = a, b, a+b\n return c\n }\n}", "func fibonacci() func() int {\n\tn := -1 \t\n\treturn func () int {\n\t\tn++\t\n\t\tif n == 0{\n\t\t\treturn 0\n\t\t}else if n == 1 {\n\t\t\treturn 1\n\t\t}else{\n\t\t\ta := make([]int, n+1)\n\t\t \ta[0] = 0\n\t\t\ta[1] = 1\n\t\t\tfor i:=2; i<=n; i++ {\n\t\t\t\ta[i] = a[i-1] + a[i-2]\n\t\t\t}\n\t\t\treturn a[n]\n\t\t}\n\t}\n}", "func Function9x4[I0, I1, I2, I3, I4, I5, I6, I7, I8, R0, R1, R2, R3 any](doFn func(I0, I1, I2, I3, I4, I5, I6, I7, I8) (R0, R1, R2, R3)) {\n\truntime.RegisterFunction(doFn)\n\tregisterMethodTypes(reflect.TypeOf(doFn))\n\tcaller := func(fn any) reflectx.Func {\n\t\tf := fn.(func(I0, I1, I2, I3, I4, I5, I6, I7, I8) (R0, R1, R2, R3))\n\t\treturn &caller9x4[I0, I1, I2, I3, I4, I5, I6, I7, I8, R0, R1, R2, R3]{fn: f}\n\t}\n\treflectx.RegisterFunc(reflect.TypeOf((*func(I0, I1, I2, I3, I4, I5, I6, I7, I8) (R0, R1, R2, R3))(nil)).Elem(), caller)\n}", "func Function9x2[I0, I1, I2, I3, I4, I5, I6, I7, I8, R0, R1 any](doFn func(I0, I1, I2, I3, I4, I5, I6, I7, I8) (R0, R1)) {\n\truntime.RegisterFunction(doFn)\n\tregisterMethodTypes(reflect.TypeOf(doFn))\n\tcaller := func(fn any) reflectx.Func {\n\t\tf := fn.(func(I0, I1, I2, I3, I4, I5, I6, I7, I8) (R0, R1))\n\t\treturn &caller9x2[I0, I1, I2, I3, I4, I5, I6, I7, I8, R0, R1]{fn: f}\n\t}\n\treflectx.RegisterFunc(reflect.TypeOf((*func(I0, I1, I2, I3, I4, I5, I6, I7, I8) (R0, R1))(nil)).Elem(), caller)\n}", "func Operator( csv_inf []type5.Csv_Inf ,function string ,match_word string ,column_no int ,w http.ResponseWriter, r *http.Request ) ( csv_inf2 []type5.Csv_Inf ) {\n\n// IN  csv_inf :\n// IN function :  \n//           eq ne ge gt le lt\n// IN match_word :  \n// IN column_no  : the column no which is maked matching\n// IN w   : response-writer\n// IN r   : request-parameter\n\n\n// OUT csv_inf2 : csv inf. which is after matching\n\n// fmt.Fprintf( w, \"operator start \\n\" )\n// fmt.Fprintf( w, \"operator function %v\\n\" ,function )\n // fmt.Fprintf( w, \"operator match_word %v\\n\" ,match_word )\n\n///\n/// get matching key\n///\n\n match_key := trans3.Csv_inf_column ( w ,r ,column_no )\n\n///\n/// jump some action in function\n\n\tswitch function {\n\n case \"eq\" :\n\n csv_inf2 = Operator_eq ( w , r ,csv_inf ,match_word ,match_key )\n\n break;\n\n case \"ne\" :\n\n csv_inf2 = Operator_ne ( w , r ,csv_inf ,match_word ,match_key )\n\n break;\n\n case \"gt\" :\n\n csv_inf2 = Operator_gt ( w , r ,csv_inf ,match_word ,match_key )\n\n break;\n\n case \"ge\" :\n\n csv_inf2 = Operator_ge ( w , r ,csv_inf ,match_word ,match_key )\n\n break;\n\n case \"lt\" :\n\n csv_inf2 = Operator_lt ( w , r ,csv_inf ,match_word ,match_key )\n\n break;\n\n case \"le\" :\n\n csv_inf2 = Operator_le ( w , r ,csv_inf ,match_word ,match_key )\n\n break;\n\n }\n\n\treturn csv_inf2\n\n}", "func Function() {\n\n\t// a simple function\n\tfunctionName1()\n\n\t// function with parameters (again, types go after identifiers)\n\tfunctionName2(\"Salehin Rafi\", 26)\n\n\t// multiple parameters of the same type\n\tfunctionName3(1, 2)\n\n\t// return type declaration\n\tvar i = functionName4()\n\tfmt.Println(i)\n\n\t// return multiple values at once\n\tvar a, b = returnMulti()\n\tfmt.Println(a, b)\n\n\t// return multiple named results simply by return\n\tvar c, d = returnMulti2()\n\tfmt.Println(c, d)\n\n\t// assign a function to a name as a value\n\tadd := func(a, b int) int {\n\t\treturn a + b\n\t}\n\t// use the name to call the function\n\tfmt.Println(add(3, 4))\n\n}", "func incrementor() func() int {\n\tvar x int\n\treturn func() int {\n\t\tx++\n\t\treturn x\n\t}\n}", "func wrapper() func() int {\n x := 0\n\n return func() int {\n x++\n return x\n }\n}", "func Funcs(init Handler, fns []ContractFunctionInterface) map[coretypes.Hname]ContractFunctionInterface {\n\tret := map[coretypes.Hname]ContractFunctionInterface{\n\t\tcoretypes.EntryPointInit: Func(\"init\", init),\n\t}\n\tfor _, f := range fns {\n\t\thname := f.Hname()\n\t\tif _, ok := ret[hname]; ok {\n\t\t\tpanic(fmt.Sprintf(\"Duplicate function: %s\", f.Name))\n\t\t}\n\n\t\thandlers := 0\n\t\tif f.Handler != nil {\n\t\t\thandlers += 1\n\t\t}\n\t\tif f.ViewHandler != nil {\n\t\t\thandlers += 1\n\t\t}\n\t\tif handlers != 1 {\n\t\t\tpanic(\"Exactly one of Handler, ViewHandler must be set\")\n\t\t}\n\n\t\tret[hname] = f\n\t}\n\treturn ret\n}", "func Run() {\n\tmu.Lock()\n\tfns := funcs\n\tfuncs = nil\n\tmu.Unlock()\n\tfor i := len(fns) - 1; i >= 0; i-- {\n\t\tfns[i]()\n\t}\n}", "func fibonacchi() func() int {\n\tfirst := 0\n\tsecond := 1\n\treturn func() int {\n\t\tres := first\n\t\tfirst, second = second, first+second\n\t\treturn res\n\t}\n}", "func main() {\n\n\tmultiplicationTables()\n}", "func (s *BasejossListener) EnterFunction_(ctx *Function_Context) {}", "func funcLn(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\treturn simpleFunc(vals, enh, math.Log)\n}", "func fibonacci() func() int {\n x, y := 0, 1\n i := 0\n return func() int{\n if i!=0{\n x, y = y, x+y\n }\n i++\n return x\n }\n}", "func (s *BaselimboListener) EnterFunction_arg_ret(ctx *Function_arg_retContext) {}", "func fibonacci() func() int {\n\tvar first, second, x int\n\n\treturn func() int {\n\t\tvar temp int\n\t\tvar fib_series int\n\t\tx += 1\n\t\tif x == 1 {\n\t\t\tfib_series = 0\n\t\t\tfirst = fib_series\n\t\t} else if x == 2 {\n\t\t\tfib_series = 1\n\n\t\t} else {\n\t\t\tfib_series = first + second\n\n\t\t}\n\t\ttemp = first\n\t\tfirst = fib_series\n\t\tsecond = temp\n\n\t\treturn fib_series\n\t}\n\n}", "func fibonacci() func() int {\n\titeracao := 0\n\tprox := 0\n\tprimeiro := 0\n\tsegundo := 1\n\n\treturn func() int {\n\t\tif iteracao <= 1 {\n\t\t\tprox = iteracao\n\t\t\titeracao += 1\n\t\t} else {\n\t\t\tprox = primeiro + segundo\n\t\t\tprimeiro = segundo\n\t\t\tsegundo = prox\n\t\t}\n\t\treturn prox\n\t}\n}", "func wrapper() func() int {\n\tx := 0\n\treturn func() int {\n\t\tx++\n\t\treturn x\n\t}\n}", "func wrapper() func() int {\n\tx := 0\n\treturn func() int {\n\t\tx++\n\t\treturn x\n\t}\n}", "func transpileFunctionDecl(n *ast.FunctionDecl, p *program.Program) (\n\tdecls []goast.Decl, err error) {\n\tdefer func() {\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"cannot transpileFunctionDecl. %v\", err)\n\t\t}\n\t}()\n\n\t// This is set at the start of the function declaration so when the\n\t// ReturnStmt comes alone it will know what the current function is, and\n\t// therefore be able to lookup what the real return type should be. I'm sure\n\t// there is a much better way of doing this.\n\tp.Function = n\n\tdefer func() {\n\t\t// Reset the function name when we go out of scope.\n\t\tp.Function = nil\n\t}()\n\n\tn.Name = util.ConvertFunctionNameFromCtoGo(n.Name)\n\n\t// Always register the new function. Only from this point onwards will\n\t// we be allowed to refer to the function.\n\tdefine := func() (err error) {\n\t\tvar pr string\n\t\tvar f, r []string\n\t\tpr, _, f, r, err = util.ParseFunction(n.Type)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"cannot get function definition : %v\", err)\n\t\t\treturn\n\t\t}\n\t\tif len(pr) != 0 {\n\t\t\tp.AddMessage(p.GenerateWarningMessage(\n\t\t\t\tfmt.Errorf(\"prefix of type '%s' is not empty\", n.Type), n))\n\t\t}\n\n\t\tp.AddFunctionDefinition(program.DefinitionFunction{\n\t\t\tName: n.Name,\n\t\t\tReturnType: r[0],\n\t\t\tArgumentTypes: f,\n\t\t\tSubstitution: \"\",\n\t\t\tIncludeFile: n.Pos.File,\n\t\t})\n\n\t\treturn\n\t}\n\n\tif p.GetFunctionDefinition(n.Name) == nil {\n\t\tif err = define(); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif p.Binding {\n\t\t// probably a few function in result with same names\n\t\tdecls, err = bindingFunctionDecl(n, p)\n\t\treturn\n\t}\n\n\tif n.IsExtern {\n\t\treturn\n\t}\n\n\t// Test if the function has a body. This is identified by a child node that\n\t// is a CompoundStmt (since it is not valid to have a function body without\n\t// curly brackets).\n\tfunctionBody := getFunctionBody(n)\n\tif functionBody == nil {\n\t\treturn\n\t}\n\n\tif err = define(); err != nil {\n\t\treturn\n\t}\n\n\t// If the function has a direct substitute in Go we do not want to\n\t// output the C definition of it.\n\tf := p.GetFunctionDefinition(n.Name)\n\n\tp.SetHaveBody(n.Name)\n\tbody, pre, post, err := transpileToBlockStmt(functionBody, p)\n\tif err != nil || len(pre) > 0 || len(post) > 0 {\n\t\tp.AddMessage(p.GenerateWarningMessage(\n\t\t\tfmt.Errorf(\"not correct result in function %s body: err = %v\",\n\t\t\t\tn.Name, err), n))\n\t\terr = nil // Error is ignored\n\t}\n\n\tif p.IncludeHeaderIsExists(\"stdlib.h\") && n.Name == \"main\" {\n\t\tbody.List = append([]goast.Stmt{&goast.DeferStmt{\n\t\t\tCall: util.NewCallExpr(\"noarch.AtexitRun\"),\n\t\t}}, body.List...)\n\t\tp.AddImport(\"github.com/Konstantin8105/c4go/noarch\")\n\t}\n\n\t// if functionBody != nil {\n\n\t// If verbose mode is on we print the name of the function as a comment\n\t// immediately to stdout. This will appear at the top of the program but\n\t// make it much easier to diagnose when the transpiler errors.\n\tif p.Verbose {\n\t\tfmt.Fprintf(os.Stdout, \"// Function: %s(%s)\\n\", f.Name,\n\t\t\tstrings.Join(f.ArgumentTypes, \", \"))\n\t}\n\n\tvar fieldList = &goast.FieldList{}\n\tfieldList, err = getFieldList(p, n, f.ArgumentTypes)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// return type\n\n\tt, err := types.ResolveType(p, f.ReturnType)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"ReturnType: %s. %v\", f.ReturnType, err)\n\t\tp.AddMessage(p.GenerateWarningMessage(err, n))\n\t\terr = nil\n\t}\n\n\tif p.Function != nil && p.Function.Name == \"main\" {\n\t\t// main() function does not have a return type.\n\t\tt = \"\"\n\n\t\t// This collects statements that will be placed at the top of\n\t\t// (before any other code) in main().\n\t\tprependStmtsInMain := []goast.Stmt{}\n\n\t\t// In Go, the main() function does not take the system arguments.\n\t\t// Instead they are accessed through the os package. We create new\n\t\t// variables in the main() function (if needed), immediately after\n\t\t// the __init() for these variables.\n\t\tif len(fieldList.List) > 0 {\n\t\t\tp.AddImport(\"os\")\n\n\t\t\tprependStmtsInMain = append(\n\t\t\t\tprependStmtsInMain,\n\t\t\t\t&goast.AssignStmt{\n\t\t\t\t\tLhs: []goast.Expr{fieldList.List[0].Names[0]},\n\t\t\t\t\tTok: token.DEFINE,\n\t\t\t\t\tRhs: []goast.Expr{\n\t\t\t\t\t\t&goast.CallExpr{\n\t\t\t\t\t\t\tFun: goast.NewIdent(\"int32\"),\n\t\t\t\t\t\t\tArgs: []goast.Expr{\n\t\t\t\t\t\t\t\tutil.NewCallExpr(\"len\", goast.NewIdent(\"os.Args\")),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\n\t\tif len(fieldList.List) > 1 {\n\t\t\tprependStmtsInMain = append(\n\t\t\t\tprependStmtsInMain,\n\t\t\t\t&goast.AssignStmt{\n\t\t\t\t\tLhs: []goast.Expr{fieldList.List[1].Names[0]},\n\t\t\t\t\tTok: token.DEFINE,\n\t\t\t\t\tRhs: []goast.Expr{&goast.CompositeLit{Type: util.NewTypeIdent(\"[][]byte\")}},\n\t\t\t\t},\n\t\t\t\t&goast.RangeStmt{\n\t\t\t\t\tKey: goast.NewIdent(\"_\"),\n\t\t\t\t\tValue: util.NewIdent(\"argvSingle\"),\n\t\t\t\t\tTok: token.DEFINE,\n\t\t\t\t\tX: goast.NewIdent(\"os.Args\"),\n\t\t\t\t\tBody: &goast.BlockStmt{\n\t\t\t\t\t\tList: []goast.Stmt{\n\t\t\t\t\t\t\t&goast.AssignStmt{\n\t\t\t\t\t\t\t\tLhs: []goast.Expr{fieldList.List[1].Names[0]},\n\t\t\t\t\t\t\t\tTok: token.ASSIGN,\n\t\t\t\t\t\t\t\tRhs: []goast.Expr{util.NewCallExpr(\n\t\t\t\t\t\t\t\t\t\"append\",\n\t\t\t\t\t\t\t\t\tfieldList.List[1].Names[0],\n\t\t\t\t\t\t\t\t\tutil.NewCallExpr(\"[]byte\", util.NewIdent(\"argvSingle\")),\n\t\t\t\t\t\t\t\t)},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t}\n\n\t\t// Prepend statements for main().\n\t\tbody.List = append(prependStmtsInMain, body.List...)\n\n\t\t// The main() function does not have arguments or a return value.\n\t\tfieldList = &goast.FieldList{}\n\t}\n\n\t// Each function MUST have \"ReturnStmt\",\n\t// except function without return type\n\tvar addReturnName bool\n\tif len(body.List) > 0 {\n\t\tlast := body.List[len(body.List)-1]\n\t\tif _, ok := last.(*goast.ReturnStmt); !ok && t != \"\" {\n\t\t\tbody.List = append(body.List, &goast.ReturnStmt{})\n\t\t\taddReturnName = true\n\t\t}\n\t}\n\n\t// For functions without return type - no need add return at\n\t// the end of body\n\tif p.GetFunctionDefinition(n.Name).ReturnType == \"void\" {\n\t\tif len(body.List) > 0 {\n\t\t\tif _, ok := (body.List[len(body.List)-1]).(*goast.ReturnStmt); ok {\n\t\t\t\tbody.List = body.List[:len(body.List)-1]\n\t\t\t}\n\t\t}\n\t}\n\n\tdecls = append(decls, &goast.FuncDecl{\n\t\tName: util.NewIdent(n.Name),\n\t\tType: util.NewFuncType(fieldList, t, addReturnName),\n\t\tBody: body,\n\t})\n\t//}\n\n\terr = nil\n\treturn\n}", "func addTwo() func() int {\n\tsum := 0\n\treturn func() int {\n\t\tsum += 2\n\t\treturn sum\n\t}\n}", "func printTime(fn func(int) ([]int)) (func(int) ([]int)) {\n return func(arg int) ([]int){\n start := time.Now()\n res := fn(arg)\n end := time.Now()\n elapsed := end.Sub(start)\n fmt.Println(\"elapsed time = \", elapsed)\n return res\n }\n}", "func Function10x4[I0, I1, I2, I3, I4, I5, I6, I7, I8, I9, R0, R1, R2, R3 any](doFn func(I0, I1, I2, I3, I4, I5, I6, I7, I8, I9) (R0, R1, R2, R3)) {\n\truntime.RegisterFunction(doFn)\n\tregisterMethodTypes(reflect.TypeOf(doFn))\n\tcaller := func(fn any) reflectx.Func {\n\t\tf := fn.(func(I0, I1, I2, I3, I4, I5, I6, I7, I8, I9) (R0, R1, R2, R3))\n\t\treturn &caller10x4[I0, I1, I2, I3, I4, I5, I6, I7, I8, I9, R0, R1, R2, R3]{fn: f}\n\t}\n\treflectx.RegisterFunc(reflect.TypeOf((*func(I0, I1, I2, I3, I4, I5, I6, I7, I8, I9) (R0, R1, R2, R3))(nil)).Elem(), caller)\n}", "func GenDisplaceFn(a, vo, so float64) func(float64) float64 {\n fn := func(time float64) float64 {\n calc := 0.5 * a * math.Pow(time, 2) + vo*time + so\n return calc\n }\n return fn\n}", "func fibonacci() func() int {\n\ta:= 0\n\tb:= 1\n\treturn func() int {\n\t\tx := a+b\n\t\ta = b\n\t\tb = x\n\t\treturn x\n\t}\n}", "func fibonacci() func() int {\n\tx := 0\n\ty := 1\n\treturn func() int {\n\t\tx,y = y,x+y\n\t\treturn x\n\t}\n}", "func Function8x4[I0, I1, I2, I3, I4, I5, I6, I7, R0, R1, R2, R3 any](doFn func(I0, I1, I2, I3, I4, I5, I6, I7) (R0, R1, R2, R3)) {\n\truntime.RegisterFunction(doFn)\n\tregisterMethodTypes(reflect.TypeOf(doFn))\n\tcaller := func(fn any) reflectx.Func {\n\t\tf := fn.(func(I0, I1, I2, I3, I4, I5, I6, I7) (R0, R1, R2, R3))\n\t\treturn &caller8x4[I0, I1, I2, I3, I4, I5, I6, I7, R0, R1, R2, R3]{fn: f}\n\t}\n\treflectx.RegisterFunc(reflect.TypeOf((*func(I0, I1, I2, I3, I4, I5, I6, I7) (R0, R1, R2, R3))(nil)).Elem(), caller)\n}", "func greeting() func() string {\n\t// return value of type function of type string\n\treturn func() string {\n\t\treturn \"Greetings Hooman!!!!\"\n\t}\n}", "func (s *BasevhdlListener) EnterReturn_statement(ctx *Return_statementContext) {}", "func fibonacci() func() int {\n\tp1, p2, p3 := 0, 1, 1\n\tcount := 0\n\treturn func() int {\n\t\tcount++\n\t\tif count == 1 {\n\t\t\treturn p1\n\t\t} else if count == 2 {\n\t\t\treturn p2\n\t\t} else {\n\t\t\tp3 = p1 + p2\n\t\t\tp1, p2 = p2, p3\n\t\t\treturn p3\n\t\t}\n\t}\n}", "func CrearTablaZonaVerde() {\n\tEjecutarExec(queryZonaVerde)\n}", "func bar() func() int {\n\treturn func() int {\n\t\treturn 51\n\t}\n}", "func funky() func() int {\n\treturn func() int {\n\t\treturn 42\n\t}\n}", "func fibonacci() func() int {\r\n\ta := make([]int, 0)\r\n\ti := -1\r\n\treturn func() int {\r\n\t\ti++\r\n\t\tif i == 0 {\r\n\t\t\ta = append(a, 0)\r\n\t\t} else if i == 1 {\r\n\t\t\ta = append(a, 1)\r\n\t\t} else {\r\n\t\t\ta = append(a, a[i-2]+a[i-1])\r\n\t\t}\r\n\t\treturn a[i]\r\n\t}\r\n}", "func Function9x1[I0, I1, I2, I3, I4, I5, I6, I7, I8, R0 any](doFn func(I0, I1, I2, I3, I4, I5, I6, I7, I8) R0) {\n\truntime.RegisterFunction(doFn)\n\tregisterMethodTypes(reflect.TypeOf(doFn))\n\tcaller := func(fn any) reflectx.Func {\n\t\tf := fn.(func(I0, I1, I2, I3, I4, I5, I6, I7, I8) R0)\n\t\treturn &caller9x1[I0, I1, I2, I3, I4, I5, I6, I7, I8, R0]{fn: f}\n\t}\n\treflectx.RegisterFunc(reflect.TypeOf((*func(I0, I1, I2, I3, I4, I5, I6, I7, I8) R0)(nil)).Elem(), caller)\n}", "func (s *BasePlSqlParserListener) EnterFunction_body(ctx *Function_bodyContext) {}", "func fibonacci() func() int {\n\tx := 0\n\ty := 1\n\treturn func() int {\n\t\tx,y = y, x+y\n\t\treturn x\n\t}\n}", "func (t *LineTable) findFunc(pc uint64) funcData {\n\tft := t.funcTab()\n\tif pc < ft.pc(0) || pc >= ft.pc(ft.Count()) {\n\t\treturn funcData{}\n\t}\n\tidx := sort.Search(int(t.nfunctab), func(i int) bool {\n\t\treturn ft.pc(i) > pc\n\t})\n\tidx--\n\treturn t.funcData(uint32(idx))\n}", "func Function8x2[I0, I1, I2, I3, I4, I5, I6, I7, R0, R1 any](doFn func(I0, I1, I2, I3, I4, I5, I6, I7) (R0, R1)) {\n\truntime.RegisterFunction(doFn)\n\tregisterMethodTypes(reflect.TypeOf(doFn))\n\tcaller := func(fn any) reflectx.Func {\n\t\tf := fn.(func(I0, I1, I2, I3, I4, I5, I6, I7) (R0, R1))\n\t\treturn &caller8x2[I0, I1, I2, I3, I4, I5, I6, I7, R0, R1]{fn: f}\n\t}\n\treflectx.RegisterFunc(reflect.TypeOf((*func(I0, I1, I2, I3, I4, I5, I6, I7) (R0, R1))(nil)).Elem(), caller)\n}", "func MdlAnulaTransaccionesRet(idOperacion int, idUsuario int, motivo string, storeProduce string) []StructDB.RespuestaInsertInGeneral {\n\t//SETEANDO LA DATA EN EL STRUCT\n\trespuesta := []StructDB.RespuestaInsertInGeneral{}\n\t//instanciando la conexión\n\tConecta.ConectionSQL()\n\t//cerrar la conexión al final de script\n\tdefer Conecta.ConectionSQL().Close()\n\t//Tomando la hora y fecha actual para la fecha de registro\n\t//instanciando el objeto\n\tvar resp StructDB.RespuestaInsertInGeneral\n\tdt := time.Now()\n\tfmt.Println(dt)\n\t//\tfmt.Println(dt)\n\trows, err := Conecta.ConectionSQL().Query(\"EXEC \"+storeProduce+\" ?, ?, ?, ?\", idOperacion, idUsuario, motivo, dt)\n\tif err != nil {\n\t\tlog.Fatal(\"Error al guardar el ingreso general\")\n\t}\n\t//Destruir los rows que se almacenan en memoria dinamica al final del script\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\t//Leyendo cada una de las rows\n\t\terr := rows.Scan(&resp.RespSQL)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Error al gardar el producto\")\n\t\t}\n\t\trespuesta = append(respuesta, resp)\n\t\t//\tnames = append(names, id)\n\t}\n\tfmt.Println(rows)\n\treturn respuesta\n\n}", "func addTwoDynamic() func() int {\n\treturn func() int {\n\t\tsum += 2\n\t\treturn sum\n\t}\n}", "func Function10x2[I0, I1, I2, I3, I4, I5, I6, I7, I8, I9, R0, R1 any](doFn func(I0, I1, I2, I3, I4, I5, I6, I7, I8, I9) (R0, R1)) {\n\truntime.RegisterFunction(doFn)\n\tregisterMethodTypes(reflect.TypeOf(doFn))\n\tcaller := func(fn any) reflectx.Func {\n\t\tf := fn.(func(I0, I1, I2, I3, I4, I5, I6, I7, I8, I9) (R0, R1))\n\t\treturn &caller10x2[I0, I1, I2, I3, I4, I5, I6, I7, I8, I9, R0, R1]{fn: f}\n\t}\n\treflectx.RegisterFunc(reflect.TypeOf((*func(I0, I1, I2, I3, I4, I5, I6, I7, I8, I9) (R0, R1))(nil)).Elem(), caller)\n}", "func MakeFunc(regVars []args.Var, inputs ...interface{}) (*Function, error) {\n\tfunction := new(Function)\n\n\tfunction.regVars = regVars\n\tvar varNum = make(map[args.Var]int)\n\tvar numVars int\n\tvar tempOpsStack []string\n\tvar postfixStack []interface{}\n\tfor i, v := range regVars {\n\t\tif _, ok := varNum[v]; !ok {\n\t\t\tvarNum[v] = numVars\n\t\t\tnumVars++\n\t\t\tcontinue\n\t\t}\n\t\treturn nil, fmt.Errorf(\"Error registering variables. Variable at index %d, is a duplicate\", i)\n\n\t}\n\tvar inputType = make(map[int]args.Type)\n\tfor i, n := range inputs {\n\t\ttopIndexInPostfixStack := len(postfixStack) - 1\n\t\tswitch n.(type) {\n\t\tcase string:\n\t\t\toperation := n.(string)\n\t\t\tvar finishComparing bool\n\t\t\ttopIndexInTempOpsStack := len(tempOpsStack) - 1\n\t\t\tif len(tempOpsStack) == 0 ||\n\t\t\t\t(tempOpsStack[topIndexInTempOpsStack] == leftParen && operation != rightParen) {\n\t\t\t\ttempOpsStack = append(tempOpsStack, operation)\n\t\t\t} else if operation == leftParen {\n\t\t\t\ttempOpsStack = append(tempOpsStack, operation)\n\t\t\t} else if operation == rightParen {\n\t\t\t\tfor !finishComparing {\n\t\t\t\t\tif len(tempOpsStack) == 0 {\n\t\t\t\t\t\treturn nil, errors.New(\"Mismatch of Parentheses found\")\n\t\t\t\t\t}\n\t\t\t\t\ttopOperationInTempOpsStack := tempOpsStack[topIndexInTempOpsStack]\n\t\t\t\t\tif topOperationInTempOpsStack == leftParen {\n\t\t\t\t\t\ttempOpsStack = tempOpsStack[:topIndexInTempOpsStack]\n\t\t\t\t\t\tfinishComparing = true\n\t\t\t\t\t} else {\n\t\t\t\t\t\tinputType[topIndexInPostfixStack+1] = args.Operation\n\t\t\t\t\t\tpostfixStack, tempOpsStack = append(postfixStack, topOperationInTempOpsStack), tempOpsStack[:topIndexInTempOpsStack]\n\t\t\t\t\t}\n\t\t\t\t\ttopIndexInTempOpsStack = len(tempOpsStack) - 1\n\t\t\t\t\ttopIndexInPostfixStack = len(postfixStack) - 1\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttopOperationInTempOpsStack := tempOpsStack[topIndexInTempOpsStack]\n\t\t\t\tvar isPreviousUnary bool\n\t\t\t\tvar isUnary bool\n\t\t\t\tif _, ok := unaryFuncs[topOperationInTempOpsStack]; ok {\n\t\t\t\t\tisPreviousUnary = true\n\t\t\t\t}\n\t\t\t\tif _, ok := unaryFuncs[operation]; ok {\n\t\t\t\t\tisUnary = true\n\t\t\t\t}\n\t\t\t\tif isPreviousUnary || orderOfOperations[operation] < orderOfOperations[topOperationInTempOpsStack] {\n\t\t\t\t\tfor !finishComparing {\n\t\t\t\t\t\tif isUnary && isPreviousUnary {\n\t\t\t\t\t\t\ttempOpsStack = append(tempOpsStack, operation)\n\t\t\t\t\t\t\tfinishComparing = true\n\t\t\t\t\t\t} else if (topOperationInTempOpsStack == leftParen ||\n\t\t\t\t\t\t\torderOfOperations[operation] > orderOfOperations[topOperationInTempOpsStack] ||\n\t\t\t\t\t\t\tisUnary) &&\n\t\t\t\t\t\t\t!isPreviousUnary {\n\t\t\t\t\t\t\ttempOpsStack = append(tempOpsStack, operation)\n\t\t\t\t\t\t\tfinishComparing = true\n\t\t\t\t\t\t} else if orderOfOperations[operation] == orderOfOperations[topOperationInTempOpsStack] {\n\t\t\t\t\t\t\tif operation == pow {\n\t\t\t\t\t\t\t\ttempOpsStack = append(tempOpsStack, operation)\n\t\t\t\t\t\t\t\tfinishComparing = true\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tinputType[topIndexInPostfixStack+1] = args.Operation\n\t\t\t\t\t\t\t\tpostfixStack, tempOpsStack = append(postfixStack, topOperationInTempOpsStack), tempOpsStack[:topIndexInTempOpsStack]\n\t\t\t\t\t\t\t\ttopIndexInTempOpsStack = len(tempOpsStack) - 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if orderOfOperations[operation] < orderOfOperations[topOperationInTempOpsStack] || isPreviousUnary {\n\t\t\t\t\t\t\tinputType[topIndexInPostfixStack+1] = args.Operation\n\t\t\t\t\t\t\tpostfixStack, tempOpsStack = append(postfixStack, topOperationInTempOpsStack), tempOpsStack[:topIndexInTempOpsStack]\n\t\t\t\t\t\t\ttopIndexInTempOpsStack = len(tempOpsStack) - 1\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif len(tempOpsStack) == 0 {\n\t\t\t\t\t\t\ttempOpsStack = append(tempOpsStack, operation)\n\t\t\t\t\t\t\tfinishComparing = true\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttopOperationInTempOpsStack = tempOpsStack[topIndexInTempOpsStack]\n\t\t\t\t\t\t\ttopIndexInPostfixStack = len(postfixStack) - 1\n\t\t\t\t\t\t\tif _, ok := unaryFuncs[topOperationInTempOpsStack]; !ok {\n\t\t\t\t\t\t\t\tisPreviousUnary = false\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if orderOfOperations[operation] > orderOfOperations[topOperationInTempOpsStack] {\n\t\t\t\t\ttempOpsStack = append(tempOpsStack, operation)\n\t\t\t\t} else if orderOfOperations[operation] == orderOfOperations[topOperationInTempOpsStack] {\n\t\t\t\t\tif operation == pow {\n\t\t\t\t\t\ttempOpsStack = append(tempOpsStack, operation)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tinputType[topIndexInPostfixStack+1] = args.Operation\n\t\t\t\t\t\tpostfixStack, tempOpsStack = append(postfixStack, topOperationInTempOpsStack), tempOpsStack[:topIndexInTempOpsStack]\n\t\t\t\t\t\ttempOpsStack = append(tempOpsStack, operation)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase int, int32, int64, float32, float64, complex64, complex128, gcv.Value, v.Vector, m.Matrix:\n\t\t\tpostfixStack = append(postfixStack, args.MakeConst(inputs[i]))\n\t\t\tinputType[topIndexInPostfixStack+1] = args.Constant\n\t\tcase args.Const:\n\t\t\tpostfixStack = append(postfixStack, n)\n\t\t\tinputType[topIndexInPostfixStack+1] = args.Constant\n\t\tcase args.Var:\n\t\t\tif _, ok := varNum[n.(args.Var)]; !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"Variable at index %d, was not registered\", i)\n\n\t\t\t}\n\t\t\tpostfixStack = append(postfixStack, n)\n\t\t\tinputType[topIndexInPostfixStack+1] = args.Variable\n\t\tdefault:\n\t\t\treturn nil, errors.New(\"Input type not supported\")\n\t\t}\n\t}\n\n\tfor len(tempOpsStack) > 0 {\n\t\ttopIndexInTempOpsStack := len(tempOpsStack) - 1\n\t\ttopIndexInPostfixStack := len(postfixStack) - 1\n\t\tvar operation string\n\t\toperation, tempOpsStack = tempOpsStack[topIndexInTempOpsStack], tempOpsStack[:topIndexInTempOpsStack]\n\t\tif operation == \"(\" {\n\t\t\treturn nil, errors.New(\"Mismatch of Parentheses found\")\n\t\t}\n\t\tinputType[topIndexInPostfixStack+1] = args.Operation\n\t\tpostfixStack = append(postfixStack, operation)\n\t}\n\n\tfunction.inputTypes = inputType\n\tfunction.numVars = numVars\n\tfunction.varNum = varNum\n\tfunction.Args = postfixStack\n\treturn function, nil\n}", "func (gui *Gui) inputQuery() func(g *gocui.Gui, v *gocui.View) error {\n\treturn func(g *gocui.Gui, v *gocui.View) error {\n\t\tv.Rewind()\n\n\t\tov, err := gui.g.View(\"rows\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Cleans up the rows view.\n\t\tov.Clear()\n\n\t\tif err := gui.c.ResetPagination(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := gui.showIndex(\"index\", 1, 1); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tquery := v.Buffer()\n\n\t\tresultSet, columnNames, err := gui.c.Query(query)\n\t\tif err != nil {\n\t\t\t// Prints the error in red on the rows view.\n\t\t\tred := color.New(color.FgRed)\n\t\t\tboldRed := red.Add(color.Bold)\n\t\t\tboldRed.Fprintf(ov, \"%s\\n\", err)\n\t\t} else {\n\t\t\trenderTable(ov, columnNames, resultSet)\n\t\t}\n\n\t\tswitch {\n\t\tcase strings.Contains(strings.ToLower(query), \"alter table\"):\n\t\t\tfallthrough\n\t\tcase strings.Contains(strings.ToLower(query), \"drop table\"):\n\t\t\tfallthrough\n\t\tcase strings.Contains(strings.ToLower(query), \"create table\"):\n\t\t\tif err := gui.showTables(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif _, err := gui.g.SetViewOnTop(\"rows\"); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func fibonacci() func() int {\n\tvar fib func (n int) int\n n := 0\n fib = func(n int) int {\n if n == 0 {\n return 0\n } else if n == 1 {\n return 1\n } else {\n return fib(n-1) + fib(n-2)\n }\n }\n return func() int {\n acc := fib(n)\n\t\tn++\n\t\treturn acc \n }\n}", "func (s *BasevhdlListener) EnterFunction_call_or_indexed_name_part(ctx *Function_call_or_indexed_name_partContext) {\n}", "func fibonacci() func() int {\n\n\treturn func() int {\n\t\tif x == -1 {\n\t\t\tx = 0\n\t\t\treturn x\n\t\t}\n\t\tif y == -1 {\n\t\t\ty = 1\n\t\t\treturn y\n\t\t}\n\n\t\tvar cur int = x + y\n\t\tx = y\n\t\ty = cur\n\t\treturn cur\n\t}\n\n}", "func (NilTimer) Time(func()) {}", "func (w *Wrapper) Func(query string, data ...interface{}) function {\n\treturn function{\n\t\tquery: query,\n\t\tvalues: data,\n\t}\n}", "func fibonacci() func() int {\n prev1 := 0\n prev2 := 0\n next := 0\n return func() int {\n next = prev1 + prev2\n if prev1 == 0 {\n prev1++\n } else {\n prev1 = prev2\n }\n prev2 = next\n return next\n }\n}", "func Func() {}", "func f(a int, b int, c string, d int) {\n x = 5\n func k(a int, b string) {\n\n }\n return\n}", "func fibonacci() func(int) int {\n\tsum :=0\n\treturn func(i int) int {\n\t\tif i < 0 {\n\t\t\treturn 0\n\t\t}\n\t\tswitch i {\n\t\t\tcase 0:{\n\t\t\t\treturn 0\n\t\t\t}\n\t\t\tcase 1: {\n\t\t\t\treturn 1\n\t\t\t} \n\t\t\tdefault:{\n\t\t\t\tf :=fibonacci()\n\t\t\t\tsum = f(i-1) + f(i-2)\n\t\t\t\treturn sum\n\t\t\t}\n\t\t}\n\t}\n}", "func fibonacci() func() int {\n arr := make([]int, 0)\n var i int\n\n return func() int {\n switch i {\n case 0:\n arr = append(arr, 1)\n case 1:\n arr = append(arr, 1)\n default:\n arr = append(arr, arr[i-1] + arr[i-2])\n }\n i++\n return arr[len(arr) - 1]\n }\n}", "func Function9x0[I0, I1, I2, I3, I4, I5, I6, I7, I8 any](doFn func(I0, I1, I2, I3, I4, I5, I6, I7, I8)) {\n\truntime.RegisterFunction(doFn)\n\tregisterMethodTypes(reflect.TypeOf(doFn))\n\tcaller := func(fn any) reflectx.Func {\n\t\tf := fn.(func(I0, I1, I2, I3, I4, I5, I6, I7, I8))\n\t\treturn &caller9x0[I0, I1, I2, I3, I4, I5, I6, I7, I8]{fn: f}\n\t}\n\treflectx.RegisterFunc(reflect.TypeOf((*func(I0, I1, I2, I3, I4, I5, I6, I7, I8))(nil)).Elem(), caller)\n}", "func Function6x4[I0, I1, I2, I3, I4, I5, R0, R1, R2, R3 any](doFn func(I0, I1, I2, I3, I4, I5) (R0, R1, R2, R3)) {\n\truntime.RegisterFunction(doFn)\n\tregisterMethodTypes(reflect.TypeOf(doFn))\n\tcaller := func(fn any) reflectx.Func {\n\t\tf := fn.(func(I0, I1, I2, I3, I4, I5) (R0, R1, R2, R3))\n\t\treturn &caller6x4[I0, I1, I2, I3, I4, I5, R0, R1, R2, R3]{fn: f}\n\t}\n\treflectx.RegisterFunc(reflect.TypeOf((*func(I0, I1, I2, I3, I4, I5) (R0, R1, R2, R3))(nil)).Elem(), caller)\n}" ]
[ "0.61445713", "0.59035116", "0.54191124", "0.5237038", "0.52154064", "0.5208149", "0.5103757", "0.5103272", "0.5053731", "0.50382227", "0.5018528", "0.50136447", "0.5009777", "0.5006587", "0.5002946", "0.49952084", "0.49399126", "0.49373722", "0.48772338", "0.48347634", "0.4820328", "0.47796848", "0.47697133", "0.47606596", "0.47579488", "0.47572377", "0.47563645", "0.47500032", "0.47325164", "0.47077316", "0.469618", "0.46859574", "0.46766642", "0.46684033", "0.4666817", "0.4666702", "0.46375", "0.46248838", "0.46219096", "0.46027333", "0.4599457", "0.45976335", "0.45947102", "0.4586068", "0.45732006", "0.45707405", "0.45665562", "0.45629743", "0.45576423", "0.45490924", "0.453806", "0.45342422", "0.4530484", "0.45251825", "0.45137513", "0.45108107", "0.45052764", "0.45051014", "0.44996008", "0.44987315", "0.44948688", "0.44927162", "0.44927162", "0.4488533", "0.4468636", "0.44669116", "0.4465031", "0.44649956", "0.44614652", "0.44598976", "0.4451917", "0.44489747", "0.4448595", "0.44467583", "0.44323865", "0.443028", "0.4430056", "0.44280654", "0.44270003", "0.44247997", "0.4423444", "0.44219106", "0.44162056", "0.44156006", "0.44128454", "0.44038314", "0.43950242", "0.4393459", "0.43905622", "0.43893212", "0.4385746", "0.43834338", "0.43831414", "0.4382895", "0.43790153", "0.43789196", "0.43739992", "0.4373979", "0.43732792", "0.43717438" ]
0.5859927
2
RecoverPanics wraps http.Handler to recover and log panics.
func RecoverPanics(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { defer func() { if x := recover(); x != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, "apis panic. Look in log for details.") glog.Infof("APIServer panic'd on %v %v: %#v\n%s\n", req.Method, req.RequestURI, x, debug.Stack()) } }() defer httplog.NewLogged(req, &w).StacktraceWhen( httplog.StatusIsNot( http.StatusOK, http.StatusAccepted, http.StatusMovedPermanently, http.StatusTemporaryRedirect, http.StatusConflict, http.StatusNotFound, StatusUnprocessableEntity, ), ).Log() // Dispatch to the internal handler handler.ServeHTTP(w, req) }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RecoverPanics(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tdefer func() {\n\t\t\tif x := recover(); x != nil {\n\t\t\t\thttp.Error(w, \"apis panic. Look in log for details.\", http.StatusInternalServerError)\n\t\t\t\tglog.Errorf(\"APIServer panic'd on %v %v: %v\\n%s\\n\", req.Method, req.RequestURI, x, debug.Stack())\n\t\t\t}\n\t\t}()\n\t\tdefer httplog.NewLogged(req, &w).StacktraceWhen(\n\t\t\thttplog.StatusIsNot(\n\t\t\t\thttp.StatusOK,\n\t\t\t\thttp.StatusCreated,\n\t\t\t\thttp.StatusAccepted,\n\t\t\t\thttp.StatusBadRequest,\n\t\t\t\thttp.StatusMovedPermanently,\n\t\t\t\thttp.StatusTemporaryRedirect,\n\t\t\t\thttp.StatusConflict,\n\t\t\t\thttp.StatusNotFound,\n\t\t\t\thttp.StatusUnauthorized,\n\t\t\t\thttp.StatusForbidden,\n\t\t\t\terrors.StatusUnprocessableEntity,\n\t\t\t\thttp.StatusSwitchingProtocols,\n\t\t\t),\n\t\t).Log()\n\n\t\t// Dispatch to the internal handler\n\t\thandler.ServeHTTP(w, req)\n\t})\n}", "func panicRecover(handler func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer gulu.Panic.Recover(nil)\n\n\t\thandler(w, r)\n\t}\n}", "func recovery(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tpanicked := true\n\t\tdefer func() {\n\t\t\tif panicked {\n\t\t\t\tconst code = http.StatusInternalServerError\n\t\t\t\tswitch err := recover(); err := err.(type) {\n\t\t\t\tdefault:\n\t\t\t\t\tapp.Metric.PanicsTotal.Inc()\n\t\t\t\t\tlog := structlog.FromContext(r.Context(), nil)\n\t\t\t\t\tlog.PrintErr(\"panic\", def.LogHTTPStatus, code, \"err\", err, structlog.KeyStack, structlog.Auto)\n\t\t\t\t\tmiddlewareError(w, code, \"internal error\")\n\t\t\t\tcase net.Error:\n\t\t\t\t\tlog := structlog.FromContext(r.Context(), nil)\n\t\t\t\t\tlog.PrintErr(\"recovered\", def.LogHTTPStatus, code, \"err\", err)\n\t\t\t\t\tmiddlewareError(w, code, \"internal error\")\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\tnext.ServeHTTP(w, r)\n\t\tpanicked = false\n\t})\n}", "func PanicRecover(h juggler.Handler, vars *expvar.Map) juggler.Handler {\n\treturn juggler.HandlerFunc(func(ctx context.Context, c *juggler.Conn, m message.Msg) {\n\t\tdefer func() {\n\t\t\tif e := recover(); e != nil {\n\t\t\t\tif vars != nil {\n\t\t\t\t\tvars.Add(\"RecoveredPanics\", 1)\n\t\t\t\t}\n\n\t\t\t\tvar err error\n\t\t\t\tswitch e := e.(type) {\n\t\t\t\tcase error:\n\t\t\t\t\terr = e\n\t\t\t\tdefault:\n\t\t\t\t\terr = fmt.Errorf(\"%v\", e)\n\t\t\t\t}\n\t\t\t\tc.Close(err)\n\t\t\t}\n\t\t}()\n\t\th.Handle(ctx, c, m)\n\t})\n}", "func Recovery() func(h http.Handler) http.Handler {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tdefer errors.Recover(log.Fatal)\n\t\t\th.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func Recoverer(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\tdefer func() {\n\t\t\tif rec := recover(); rec != nil {\n\t\t\t\tvar err error\n\n\t\t\t\tswitch t := rec.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\terr = Error(t)\n\t\t\t\tcase error:\n\t\t\t\t\terr = t\n\t\t\t\tdefault:\n\t\t\t\t\terr = ErrUnknownError\n\t\t\t\t}\n\t\t\t\tif errors.Is(err, http.ErrAbortHandler) {\n\t\t\t\t\t// ErrAbortHandler is called when the client closes the connection or the connection is closed\n\t\t\t\t\t// so we don't need to lose our poop, just clean it up and move on\n\t\t\t\t\tErrorOut.Printf(\"%s\\n\", ErrRequestError{r, ErrAborted.Error()})\n\t\t\t\t\tDebugOut.Printf(\"ErrAbortHandler: %s\\n\", ErrRequestError{r, fmt.Sprintf(\"Panic occurred: %s\", gerrors.Wrap(err, 2).ErrorStack())})\n\t\t\t\t\thttp.Error(w, ErrRequestError{r, StatusClientClosedRequestText}.Error(), StatusClientClosedRequest) // Machine-readable\n\t\t\t\t\treturn\n\t\t\t\t} else if Conf.GetBool(ConfigRecovererLogStackTraces) {\n\t\t\t\t\tErrorOut.Printf(\"%s\\n\", ErrRequestError{r, fmt.Sprintf(\"Panic occurred: %s\", gerrors.Wrap(err, 2).ErrorStack())})\n\t\t\t\t} else {\n\t\t\t\t\tErrorOut.Printf(\"%s\\n\", ErrRequestError{r, fmt.Sprintf(\"Panic occurred: %s\", err)})\n\t\t\t\t}\n\t\t\t\t//http.Error(w, ErrRequestError{r, \"an internal error occurred\"}.Error(), http.StatusInternalServerError)\n\t\t\t\tRequestErrorResponse(r, w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t}()\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func Recover(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif rvr := recover(); rvr != nil {\n\n\t\t\t\tlogEntry := middleware.GetLogEntry(r)\n\t\t\t\tif logEntry != nil {\n\t\t\t\t\tlogEntry.Panic(rvr, debug.Stack())\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintf(os.Stderr, \"Panic: %+v\\n\", rvr)\n\t\t\t\t\tdebug.PrintStack()\n\t\t\t\t}\n\n\t\t\t\trender.Render(w, r, common.ErrorRender(errors.New(\"Internal server error\"), http.StatusInternalServerError))\n\t\t\t}\n\t\t}()\n\n\t\tnext.ServeHTTP(w, r)\n\t}\n\n\treturn http.HandlerFunc(fn)\n}", "func Recover(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tvar msg string\n\t\t\t\tswitch x := r.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\tmsg = fmt.Sprintf(\"panic: %s\", x)\n\t\t\t\tcase error:\n\t\t\t\t\tmsg = fmt.Sprintf(\"panic: %s\", x)\n\t\t\t\tdefault:\n\t\t\t\t\tmsg = \"unknown panic\"\n\t\t\t\t}\n\t\t\t\tconst size = 64 << 10 // 64KB\n\t\t\t\tbuf := make([]byte, size)\n\t\t\t\tbuf = buf[:runtime.Stack(buf, false)]\n\t\t\t\tlines := strings.Split(string(buf), \"\\n\")\n\t\t\t\tlog.Printf(\"%s\\n%s\", msg, strings.Join(lines, \"\\n\"))\n\n\t\t\t\trenderer.Error(w, msg, http.StatusInternalServerError)\n\t\t\t}\n\t\t}()\n\t\th.ServeHTTP(w, req)\n\t})\n}", "func recoverHandler(c *web.C, h http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\treqID := middleware.GetReqID(*c)\n\n\t\tdefer func() {\n\t\t\tif e := recover(); e != nil {\n\t\t\t\tmsg := fmt.Sprintf(\"Panic detected on request %s:\\n%+v\\nIP: %v, URL: %s\\n\",\n\t\t\t\t\treqID, e, r.RemoteAddr, r.URL.Path)\n\t\t\t\tdvid.ReportPanic(msg, WebServer())\n\t\t\t\thttp.Error(w, msg, 500)\n\t\t\t}\n\t\t}()\n\n\t\th.ServeHTTP(w, r)\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func recoverHandler(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tlog.Printf(\"panic: %+v\", err)\n\t\t\t\tlog.Print(string(debug.Stack()))\n\t\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\t}\n\t\t}()\n\n\t\tnext.ServeHTTP(w, r)\n\t}\n\n\treturn http.HandlerFunc(fn)\n}", "func recoverer(logger Logger) func(next http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\t\t// Capture our own copy of the logger so change in this closure\n\t\t\t// won't affect the object passed-in.\n\n\t\t\tlogger := logger\n\n\t\t\t// Defer a function to catch any panic and log a stack trace.\n\n\t\t\tdefer func() {\n\t\t\t\tif rcv := recover(); rcv != nil {\n\t\t\t\t\tif reqID := middleware.GetReqID(r.Context()); reqID != \"\" {\n\t\t\t\t\t\tlogger = logger.With(\"HTTP Request ID\", reqID)\n\t\t\t\t\t}\n\n\t\t\t\t\tscheme := \"http\"\n\t\t\t\t\tif r.TLS != nil {\n\t\t\t\t\t\tscheme = \"https\"\n\t\t\t\t\t}\n\n\t\t\t\t\tlogger.Errorw(\n\t\t\t\t\t\tlogMsgPanicRecovery,\n\t\t\t\t\t\t\"Method\", r.Method,\n\t\t\t\t\t\t\"URI\", fmt.Sprintf(\"%s://%s%s\", scheme, r.Host, r.RequestURI),\n\t\t\t\t\t\t\"Protocol\", r.Proto,\n\t\t\t\t\t\t\"Remote Address\", r.RemoteAddr,\n\t\t\t\t\t\t\"Panic Value\", rcv,\n\t\t\t\t\t\t\"Stack Trace\", string(debug.Stack()),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func Recovery() func(next http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\t\tdefer func() {\n\t\t\t\tif err := recover(); err != nil {\n\t\t\t\t\tcombinedErr := fmt.Sprintf(\"PANIC: %v\\n%s\", err, string(log.Stack(2)))\n\t\t\t\t\thttp.Error(w, combinedErr, 500)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tnext.ServeHTTP(w, req)\n\t\t})\n\t}\n}", "func (app *application) recoverPanic(next http.Handler) http.Handler {\r\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\r\n\t\tdefer func() {\r\n\t\t\tif err := recover(); err != nil {\r\n\t\t\t\tw.Header().Set(\"Connection\", \"close\")\r\n\t\t\t\tapp.serverError(w, fmt.Errorf(\"%s\", err))\r\n\t\t\t}\r\n\t\t}()\r\n\t\tnext.ServeHTTP(w, r)\r\n\t})\r\n}", "func PanicRecoverHandler(err error) {\n\tif r := recover(); r != nil {\n\t\tswitch x := r.(type) {\n\t\tcase string:\n\t\t\terr = errors.New(x)\n\t\tcase error:\n\t\t\terr = x\n\t\tdefault:\n\t\t\terr = errors.New(\"Unknown panic\")\n\t\t}\n\t}\n}", "func recoverInternal(w http.ResponseWriter) {\n\tvar err error\n\tr := recover()\n\tstatusCode := http.StatusInternalServerError\n\tif r != nil {\n\t\tlog.Println(\"Recovering from Panic:\", r)\n\t\tswitch t := r.(type) {\n\t\tcase string:\n\t\t\terr = errors.New(t)\n\t\tcase model.CustomError:\n\t\t\terr = t\n\t\t\tswitch t.ErrorType() {\n\t\t\tcase model.ErrorUnprocessableJSON:\n\t\t\t\tstatusCode = http.StatusUnprocessableEntity\n\t\t\tcase model.ErrorNotFound:\n\t\t\t\tstatusCode = http.StatusNotFound\n\t\t\tcase model.ErrorBadRequest:\n\t\t\t\tstatusCode = http.StatusBadRequest\n\t\t\tcase model.ErrorDefault:\n\t\t\t\tstatusCode = http.StatusInternalServerError\n\t\t\t}\n\t\tcase error:\n\t\t\terr = t\n\t\tdefault:\n\t\t\terr = errors.New(unknownErrorStr)\n\t\t}\n\t\tlog.Printf(\"Successfuly recovered from panic: %s\\n\", err.Error())\n\t\thttp.Error(w, err.Error(), statusCode)\n\t}\n}", "func (app *application) recoverPanic(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t// Create a deferred function (which will always be run in the event of a panic\n\t\t// as Go unwinds the stack).\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\t// If there was a panic, set a \"Connection: close\" header on the\n\t\t\t\t// response. This acts as a trigger to make Go's HTTP server\n\t\t\t\t// automatically close the current connection after a response has been\n\t\t\t\t// sent.\n\t\t\t\tw.Header().Set(\"Connection\", \"close\")\n\t\t\t\tapp.serverErrorResponse(w, r, fmt.Errorf(\"%s\", err))\n\t\t\t}\n\t\t}()\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func recoveryHandle(app http.Handler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tstack := debug.Stack()\n\t\t\t\tlog.Println(string(stack))\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tfmt.Fprintf(w, \"<h1>panic: %v</h1><pre>%s</pre>\", err, linkForm(string(stack)))\n\t\t\t}\n\t\t}()\n\t\tapp.ServeHTTP(w, r)\n\t}\n}", "func Recover() func(next http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t\tdefer func() {\n\t\t\t\tif err := recover(); err != nil {\n\t\t\t\t\thttp.Error(w, fmt.Sprintf(\"[PANIC RECOVERED] %v\", err), http.StatusInternalServerError)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tnext.ServeHTTP(w, r)\n\t\t}\n\t\treturn http.HandlerFunc(fn)\n\t}\n}", "func RecoverPanic(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\t// Check if there has been a panic\n\t\t\tif err := recover(); err != nil {\n\t\t\t\t// return a 500 Internal Server response\n\t\t\t\thelpers.ServerError(w, r, fmt.Errorf(\"%s\", err))\n\t\t\t}\n\t\t}()\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func Recover(next http.Handler) http.Handler {\n\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tlog.Printf(\"panic : %+v\", err)\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tw.Header().Set(\"Content-Type\", \"json/application\")\n\t\t\t\tpanicError := &responses.Error{\n\t\t\t\t\tCode: http.StatusInternalServerError,\n\t\t\t\t\tMessage: \"panic internal server error\",\n\t\t\t\t}\n\n\t\t\t\tencodeError := json.NewEncoder(w).Encode(panicError)\n\t\t\t\tif encodeError != nil {\n\t\t\t\t\t// A recover error can be critical, though it is better to avoid shutting down a running server.\n\t\t\t\t\tlog.Printf(\"\\n\\nfailed to recover: %s\", encodeError.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t}\n\t\t}()\n\t\tnext.ServeHTTP(w, r)\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func (h Handlers) RecoverHandler(next http.Handler) http.Handler {\r\n\tfn := func(w http.ResponseWriter, r *http.Request) {\r\n\t\tdefer func() {\r\n\t\t\tif err := recover(); err != nil {\r\n\t\t\t\tif h.debugmode {\r\n\t\t\t\t\tlog.Printf(\"panic: %+v\", err)\r\n\t\t\t\t\tlog.Printf(CallerInfo(1))\r\n\t\t\t\t\tlog.Printf(CallerInfo(2))\r\n\t\t\t\t\tlog.Printf(CallerInfo(3))\r\n\t\t\t\t\tlog.Printf(CallerInfo(4))\r\n\t\t\t\t\tlog.Printf(CallerInfo(5))\r\n\t\t\t\t\tlog.Printf(CallerInfo(6))\r\n\t\t\t\t\tlog.Printf(CallerInfo(7))\r\n\t\t\t\t\tlog.Printf(CallerInfo(8))\r\n\t\t\t\t\tlog.Printf(CallerInfo(9))\r\n\t\t\t\t}\r\n\t\t\t\thttp.Error(w, \"Internal Server Error\", http.StatusInternalServerError)\r\n\t\t\t}\r\n\t\t}()\r\n\t\tnext.ServeHTTP(w, r)\r\n\t}\r\n\treturn http.HandlerFunc(fn)\r\n}", "func logStackOnRecover(s runtime.NegotiatedSerializer, panicReason interface{}, w http.ResponseWriter) {\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(fmt.Sprintf(\"recover from panic situation: - %v\\r\\n\", panicReason))\n\tfor i := 2; ; i++ {\n\t\t_, file, line, ok := rt.Caller(i)\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tbuffer.WriteString(fmt.Sprintf(\" %s:%d\\r\\n\", file, line))\n\t}\n\tklog.Errorln(buffer.String())\n\n\theaders := http.Header{}\n\tif ct := w.Header().Get(\"Content-Type\"); len(ct) > 0 {\n\t\theaders.Set(\"Accept\", ct)\n\t}\n\tresponsewriters.ErrorNegotiated(apierrors.NewGenericServerResponse(http.StatusInternalServerError, \"\", schema.GroupResource{}, \"\", \"\", 0, false), s, schema.GroupVersion{}, w, &http.Request{Header: headers})\n}", "func Recovery(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tvar logMsg string\n\t\t\t\tif se, ok := err.(srverror.Error); ok {\n\t\t\t\t\tse.ServeHTTP(w, r)\n\t\t\t\t\tutil.VerboseRequest(r, se.Error())\n\t\t\t\t\tif se.Status() == 500 {\n\t\t\t\t\t\tlogMsg = srverror.LogString(se, r, w)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tutil.Verbose(\"Non-standard panic\")\n\t\t\t\t\tw.WriteHeader(500)\n\t\t\t\t\tw.Write([]byte(\"{\\\"message\\\": \\\"Server Error\\\"}\"))\n\t\t\t\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\t\t\tswitch v := err.(type) {\n\t\t\t\t\tcase string:\n\t\t\t\t\t\tutil.VerboseRequest(r, \"Panic: %s\", v)\n\t\t\t\t\t\tlogMsg = srverror.LogString(errors.New(v), r, w)\n\t\t\t\t\tcase error:\n\t\t\t\t\t\tutil.VerboseRequest(r, \"Panic: %s\", v.Error())\n\t\t\t\t\t\tlogMsg = srverror.LogString(v, r, w)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tutil.VerboseRequest(r, \"Panic: %v\", v)\n\t\t\t\t\t\tlogMsg = srverror.LogString(fmt.Errorf(\"%v\", v), r, w)\n\t\t\t\t\t}\n\t\t\t\t\tif *debugflag {\n\t\t\t\t\t\tdbug.PrintStack()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif len(logMsg) > 0 {\n\t\t\t\t\tlogErr := srverror.WriteToFile(logMsg)\n\t\t\t\t\tif logErr != nil {\n\t\t\t\t\t\tutil.Verbose(\"Failed to write log to file: %s\", logErr.Error())\n\t\t\t\t\t}\n\t\t\t\t\tlogErr = email.SendErrorEmail(logMsg)\n\t\t\t\t\tif logErr != nil {\n\t\t\t\t\t\tutil.Verbose(\"Failed to send log email: %s\", logErr.Error())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tutil.Verbose(\"An email has been sent to %s describing this issue\", config.V.ErrorEmail)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func recoverHandler(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\t//log.Printf(\"panic: %+v\", err)\n\t\t\t\t// notice that we're using 1, so it will actually log the where\n\t\t\t\t// the error happened, 0 = this function, we don't want that.\n\t\t\t\tpc, fn, line, _ := runtime.Caller(2)\n\t\t\t\tlog.Printf(\"[panic] in %s[%s:%d] %v\", runtime.FuncForPC(pc).Name(), fn, line, err)\n\t\t\t\t//log.Println(\"stacktrace from panic: \\n\" + string(debug.Stack()))\n\t\t\t\t//debug.PrintStack()\n\t\t\t\t// postgresql error check\n\t\t\t\t// pqErr, ok := err.(*pq.Error)\n\t\t\t\t// if ok {\n\t\t\t\t// \tlog.Printf(\"%+v\\n\", pqErr)\n\t\t\t\t// }\n\t\t\t\tWriteJSONError(w, ErrInternalServer)\n\t\t\t}\n\t\t}()\n\n\t\tnext.ServeHTTP(w, r)\n\t}\n\n\treturn http.HandlerFunc(fn)\n}", "func recoverHandler(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tlog.Printf(\"error: %+v\", err)\n\t\t\t\thttp.Error(w, http.StatusText(500), 500)\n\t\t\t}\n\t\t}()\n\t\tnext.ServeHTTP(w, r)\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func NewRecoverHandler() Middleware {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tdefer func() {\n\t\t\t\tif err := recover(); err != nil {\n\t\t\t\t\thandler.WriteError(w, r, fmt.Errorf(\"PANIC: %+v\", err), http.StatusInternalServerError)\n\t\t\t\t}\n\t\t\t}()\n\t\t\th.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func Recover() echo.MiddlewareFunc {\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) (err error) {\n\t\t\tdefer func() {\n\t\t\t\tif p := recover(); p != nil {\n\t\t\t\t\tfmt.Fprintln(os.Stderr, p)\n\t\t\t\t\tos.Stderr.Write(debug.Stack())\n\t\t\t\t\tif pErr, ok := p.(error); ok {\n\t\t\t\t\t\terr = ErrHTTPRecovered.WithCause(pErr)\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = ErrHTTPRecovered.WithAttributes(\"panic\", p)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\t\treturn next(c)\n\t\t}\n\t}\n}", "func PanicHandler() http.Handler { return panicHandler{} }", "func Recovery(inner http.Handler) http.Handler {\n\trecovery := &SimpleRecovery{}\n\treturn http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {\n\t\trecovery.ServeHTTP(rw, r, inner)\n\t})\n}", "func GinRecovery(logger log.Logger) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\t// Check for a broken connection, as it is not really a\n\t\t\t\t// condition that warrants a panic stack trace.\n\t\t\t\tvar brokenPipe bool\n\t\t\t\tif ne, ok := err.(*net.OpError); ok {\n\t\t\t\t\tif se, ok := ne.Err.(*os.SyscallError); ok {\n\t\t\t\t\t\tif strings.Contains(strings.ToLower(se.Error()), \"broken pipe\") ||\n\t\t\t\t\t\t\tstrings.Contains(strings.ToLower(se.Error()), \"connection reset by peer\") {\n\t\t\t\t\t\t\tbrokenPipe = true\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif logger != nil {\n\t\t\t\t\thttpRequest, _ := httputil.DumpRequest(c.Request, false)\n\t\t\t\t\theaders := strings.Split(string(httpRequest), \"\\r\\n\")\n\t\t\t\t\tfor idx, header := range headers {\n\t\t\t\t\t\tcurrent := strings.Split(header, \":\")\n\t\t\t\t\t\tif current[0] == \"Authorization\" {\n\t\t\t\t\t\t\theaders[idx] = current[0] + \": *\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tlogger.Errorc(c.Request.Context(), \"[Recovery] panic recovered:\\n%s\\n [%s]\",\n\t\t\t\t\t\tstrings.Join(headers, \"\\r\\n\"), err)\n\t\t\t\t}\n\n\t\t\t\tif brokenPipe {\n\t\t\t\t\t// If the connection is dead, we can't write a status to it.\n\t\t\t\t\tc.Error(err.(error)) // nolint: errcheck\n\t\t\t\t\tc.Abort()\n\t\t\t\t} else {\n\t\t\t\t\tc.AbortWithStatus(http.StatusInternalServerError)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\tc.Next()\n\t}\n}", "func CreateRecoverMiddleware(logger log.Interface) Middleware {\n\treturn func(next http.Handler) http.Handler {\n\t\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t\tdefer func() {\n\t\t\t\tif err := recover(); err != nil && err != http.ErrAbortHandler {\n\t\t\t\t\tstack := make([]byte, stackSize)\n\t\t\t\t\tstack = stack[:runtime.Stack(stack, false)]\n\n\t\t\t\t\tlogger.\n\t\t\t\t\t\tWithField(\"request_id\", context_utils.GetRequestID(r.Context())).\n\t\t\t\t\t\tWithField(\"error_type\", \"panic\").\n\t\t\t\t\t\tWithField(\"stack\", fmt.Sprintf(\"%s\", stack)).\n\t\t\t\t\t\tErrorf(\"%v\", err)\n\n\t\t\t\t\tresponse.InternalServerError(w)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tnext.ServeHTTP(w, r)\n\t\t}\n\n\t\treturn http.HandlerFunc(fn)\n\t}\n}", "func Recover(logger *log.Logger) mware.Middleware {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tdefer func(l *log.Logger) {\n\t\t\t\tif err := recover(); err != nil {\n\t\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\t\tl.Println(err)\n\t\t\t\t}\n\t\t\t}(logger)\n\n\t\t\th.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func PanicCatcher(w http.ResponseWriter, r *http.Request) {\n\tctx := httpway.GetContext(r)\n\n\tdefer func() {\n\n\t\tif rec := recover(); rec != nil {\n\t\t\tif ctx.StatusCode() == 0 {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tfmt.Fprintf(w, \"Internal Server error\")\n\n\t\t\t\tif _, ok := w.(http.Flusher); ok {\n\t\t\t\t\tprintln(\"HAHAHAHAHA FLUSHER\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !ctx.HasLog() {\n\t\t\t\tpanic(rec)\n\t\t\t}\n\n\t\t\tfile, line := getFileLine()\n\t\t\tctx.Log().Error(\"Panic catched on %s:%d - %s\", file, line, rec)\n\n\t\t}\n\t}()\n\n\tctx.Next(w, r)\n}", "func Recovery(n janice.HandlerFunc) janice.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) error {\n\t\tdefer func() {\n\t\t\tif rec := recover(); rec != nil {\n\t\t\t\tle := Logger.WithField(\"type\", \"recovery\")\n\n\t\t\t\tif rid, ok := GetRequestID(r); ok {\n\t\t\t\t\tle = le.WithField(\"request\", rid)\n\t\t\t\t}\n\n\t\t\t\tle.Error(rec)\n\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t}\n\t\t}()\n\n\t\treturn n(w, r)\n\t}\n}", "func Recovery(handlers ...func(c *Context, err interface{})) Middleware {\n\treturn func(c *Context) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tif handlers != nil {\n\t\t\t\t\tfor i := range handlers {\n\t\t\t\t\t\thandlers[i](c, err)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tc.Render(http.StatusInternalServerError, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\tc.Next()\n\t}\n}", "func NewRecover() Middleware {\n\treturn func(next http.Handler) http.Handler {\n\t\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t\t// defer the recovery\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tlog.Printf(\"There was a panic with this message: %v\\n\", r)\n\t\t\t\t\tswitch x := r.(type) {\n\t\t\t\t\tcase string:\n\t\t\t\t\t\thttp.Error(w, r.(string), http.StatusInternalServerError)\n\t\t\t\t\tcase error:\n\t\t\t\t\t\terr := x\n\t\t\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\thttp.Error(w, \"unknown panic\", http.StatusInternalServerError)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\t// call the actual api handler\n\t\t\tnext.ServeHTTP(w, r)\n\t\t}\n\n\t\treturn http.HandlerFunc(fn)\n\t}\n}", "func recoveryMw(app http.Handler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tstack := debug.Stack()\n\t\t\t\tlog.Println(string(stack))\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tfmt.Fprintf(w, \"<h1>panic: %v</h1><pre>%s</pre>\", err, makeLinks(string(stack)))\n\t\t\t}\n\t\t}()\n\t\tapp.ServeHTTP(w, r)\n\t}\n}", "func PanicRecoverMiddlewareBuilder(log *logrus.Entry) Middleware {\n\treturn func(h http.HandlerFunc) http.HandlerFunc {\n\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\tdefer func() {\n\t\t\t\tif rec := recover(); rec != nil {\n\t\t\t\t\t// Send useful debuggin information to the console.\n\t\t\t\t\tlog.WithContext(r.Context()).WithFields(logrus.Fields{\n\t\t\t\t\t\tlogfmt.StackKey: debug.Stack(),\n\t\t\t\t\t\t\"cause\": rec,\n\t\t\t\t\t}).Errorln(\"Request handler panicked! Recovering.\")\n\n\t\t\t\t\t// Clear the ResponseWriter and send internal error code.\n\t\t\t\t\tif wf, ok := w.(http.Flusher); ok {\n\t\t\t\t\t\twf.Flush()\n\t\t\t\t\t}\n\t\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\th(w, r)\n\t\t}\n\t}\n}", "func logStackOnRecover(panicReason interface{}, httpWriter http.ResponseWriter) {\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(fmt.Sprintf(\"recover from panic situation: - %v\\r\\n\", panicReason))\n\tfor i := 2; ; i += 1 {\n\t\t_, file, line, ok := runtime.Caller(i)\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tbuffer.WriteString(fmt.Sprintf(\" %s:%d\\r\\n\", file, line))\n\t}\n\t//\tlog.Print(buffer.String())\n\tlogger := log.New(os.Stderr, \"[server2 logStackOnRecover] \", log.LstdFlags|log.Lshortfile)\n\tlogger.Print(buffer.String())\n\thttpWriter.WriteHeader(http.StatusInternalServerError)\n\thttpWriter.Write(buffer.Bytes())\n}", "func PanicHandler() func(http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\t\tdefer PanicRecovery(nil, true, logging.TransactionFromContext(req.Context()))()\n\n\t\t\tnext.ServeHTTP(w, req)\n\t\t})\n\t}\n}", "func (m Middleware) RecoverHandler(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\t//FIXME: broken\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tlog.Printf(\"Recover from panic: %+v\", err)\n\t\t\thttp.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t}\n\t}()\n\tnext.ServeHTTP(rw, r)\n}", "func (h *TaskHandler) panicHandler(w http.ResponseWriter, r *http.Request, rcv interface{}) {\n\tctx := r.Context()\n\tpe := &errors2.Error{\n\t\tCode: errors2.EInternal,\n\t\tMsg: \"a panic has occurred\",\n\t\tErr: fmt.Errorf(\"%s: %v\", r.URL.String(), rcv),\n\t}\n\n\tif entry := h.log.Check(zapcore.ErrorLevel, pe.Msg); entry != nil {\n\t\tentry.Stack = string(debug.Stack())\n\t\tentry.Write(zap.Error(pe.Err))\n\t}\n\n\th.HandleHTTPError(ctx, pe, w)\n}", "func Recoverer(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\t// stack := stack(3)\n\t\t\t\tL(r.Context()).Error(\"panic\", zap.Error(err.(error)), zap.Stack(\"stack\"))\n\t\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\t}\n\t\t}()\n\n\t\tnext.ServeHTTP(w, r)\n\t}\n\n\treturn http.HandlerFunc(fn)\n}", "func PanicRecoveryMiddleware(h http.HandlerFunc, logger *zap.Logger) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif rec := recover(); rec != nil {\n\t\t\t\t// log the error\n\t\t\t\tlogger.Error(fmt.Sprint(rec))\n\n\t\t\t\t// write the error response\n\t\t\t\thelpers.JSONResponse(w, 500, map[string]interface{}{\n\t\t\t\t\t\"error\": \"Internal Error\",\n\t\t\t\t})\n\t\t\t}\n\t\t}()\n\n\t\th(w, r)\n\t}\n}", "func GlobalRecover(devConf *configs.DevelopConfig) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tdefer func(c *gin.Context) {\n\t\t\tif hh.IsStaticFile(c) {\n\t\t\t\tc.Next()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlg.Info(\"[GlobalRecover] defer func()\")\n\n\t\t\t//when crossing request, context data can't be left.\n\t\t\t//c.Set(\"skipMiddleWare\", \"1\")\n\n\t\t\tif c.IsAborted() {\n\t\t\t\tlg.Debug(\"[GlobalRecover] c.IsAborted() is true\")\n\n\t\t\t\t// response\n\t\t\t\tsetResponse(c, getErrMsg(c), c.Writer.Status())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif devConf.RecoverEnable {\n\t\t\t\tif rec := recover(); rec != nil {\n\t\t\t\t\tlg.Debugf(\"[GlobalRecover] recover() is not nil:\\n %v\", rec)\n\t\t\t\t\t//TODO:How should response data be decided whether html or json?\n\t\t\t\t\t//TODO:Ajax or not doesn't matter to response. HTTP header of Accept may be better.\n\t\t\t\t\t//TODO:How precise should I follow specifications of HTTP header.\n\n\t\t\t\t\tsetResponse(c, u.Itos(rec), 500)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}(c)\n\n\t\tc.Next()\n\t\t//Next is [Main gin Recovery]\n\t}\n}", "func RecoveryMid(app http.Handler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tstack := debug.Stack()\n\t\t\t\tlog.Println(string(stack))\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tfmt.Fprintf(w, \"<h1>panic: %v</h1><pre>%s</pre>\", err, errLinks(string(stack)))\n\t\t\t}\n\t\t}()\n\t\tapp.ServeHTTP(w, r)\n\t}\n}", "func recoverPanic(w http.ResponseWriter, panicSrc string) {\n\tif r := recover(); r != nil {\n\t\tgenericMsg := fmt.Sprintf(panicMessageTmpl, panicSrc)\n\t\tfmt.Fprintf(os.Stderr, fmt.Sprintf(\"%s\\npanic message: %v\\nstack trace: %s\", genericMsg, r, debug.Stack()))\n\t\tif w != nil {\n\t\t\twriteHTTPErrorResponse(w, http.StatusInternalServerError, crashStatus, genericMsg)\n\t\t}\n\t}\n}", "func Recoverer() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tlogger := GetLogger(c)\n\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tif logger != nil {\n\t\t\t\t\tlogger.Errorf(\"recv stack: %s\\n%s\", err, string(debug.Stack()))\n\t\t\t\t}\n\n\t\t\t\twriteInternalServerError(c)\n\t\t\t\t//c.Abort()\n\t\t\t\t//c.String(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))\n\t\t\t}\n\t\t}()\n\t\tc.Next()\n\t}\n}", "func panicHandler() mux.MiddlewareFunc {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t// http.Server hides panics from handlers, we want to record them and fix the cause\n\t\t\tdefer func() {\n\t\t\t\terr := recover()\n\t\t\t\tif err != nil {\n\t\t\t\t\tbuf := make([]byte, 1<<20)\n\t\t\t\t\tn := runtime.Stack(buf, true)\n\t\t\t\t\tlogrus.Warnf(\"Recovering from API service endpoint handler panic: %v, %s\", err, buf[:n])\n\t\t\t\t\t// Try to inform client things went south... won't work if handler already started writing response body\n\t\t\t\t\tutils.InternalServerError(w, fmt.Errorf(\"%v\", err))\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\th.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func Recovery() HandlerFunc {\n\treturn func(ctx *Context) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\t// Inform server of error\n\t\t\t\tlog.Printf(\"%s\\n\\n\", trace(err))\n\t\t\t\t// Inform client of error\n\t\t\t\tctx.Fail(http.StatusInternalServerError, \"Internal Server Error\")\n\t\t\t}\n\t\t}()\n\n\t\tctx.Next()\n\t}\n}", "func RecoverHandler(next http.Handler) http.Handler {\n\t// Define a function that defers a function to recover from a panic\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tlog.Printf(\"panic: %+v\", err)\n\t\t\t\thttp.Error(w, http.StatusText(500), 500)\n\t\t\t}\n\t\t}()\n\n\t\tnext.ServeHTTP(w, r)\n\t}\n\n\treturn http.HandlerFunc(fn)\n}", "func panicHandler(w http.ResponseWriter, r *http.Request) {\n\tfuncPanic()\n}", "func PanicRecoveryLogging(logFunc amqprpc.LogFunc) amqprpc.ServerMiddlewareFunc {\n\treturn PanicRecovery(func(r interface{}, _ context.Context, _ *amqprpc.ResponseWriter, d amqp.Delivery) {\n\t\tlogFunc(\"recovered (%s): %v\", d.CorrelationId, r)\n\t})\n}", "func PanicHandler(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tdefer func() {\n\t\terr := recover()\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"%s: %s\", err, debug.Stack())\n\t\t\thttp.Error(w, \"Internal Server Error\", http.StatusInternalServerError)\n\t\t}\n\t}()\n\n\tnext(w, r)\n}", "func NewRecoverMiddleware(logger *zap.Logger) Middleware {\n\treturn func(h fasthttp.RequestHandler) fasthttp.RequestHandler {\n\t\treturn func(ctx *fasthttp.RequestCtx) {\n\t\t\tdefer func() {\n\t\t\t\tif rec := recover(); rec != nil {\n\t\t\t\t\tlogger.DPanic(\"recover\")\n\t\t\t\t\tctx.Response.SetStatusCode(fasthttp.StatusInternalServerError)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}()\n\t\t\th(ctx)\n\t\t}\n\t}\n}", "func panicRecover(input *models.RunningInput) {\n\tif err := recover(); err != nil {\n\t\ttrace := make([]byte, 2048)\n\t\truntime.Stack(trace, true)\n\t\tlog.Printf(\"E! FATAL: [%s] panicked: %s, Stack:\\n%s\",\n\t\t\tinput.LogName(), err, trace)\n\t\tlog.Println(\"E! PLEASE REPORT THIS PANIC ON GITHUB with \" +\n\t\t\t\"stack trace, configuration, and OS information: \" +\n\t\t\t\"https://github.com/influxdata/telegraf/issues/new/choose\")\n\t}\n}", "func RecoverWithConfig(config RecoverConfig) echo.MiddlewareFunc {\n\t// Defaults\n\tif config.Skipper == nil {\n\t\tconfig.Skipper = DefaultRecoverConfig.Skipper\n\t}\n\tif config.StackSize == 0 {\n\t\tconfig.StackSize = DefaultRecoverConfig.StackSize\n\t}\n\n\treturn func(next echo.Handler) echo.Handler {\n\t\treturn echo.HandlerFunc(func(c echo.Context) error {\n\t\t\tif config.Skipper(c) {\n\t\t\t\treturn next.Handle(c)\n\t\t\t}\n\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tpanicErr := echo.NewPanicError(r, nil)\n\t\t\t\t\tpanicErr.SetDebug(c.Echo().Debug())\n\t\t\t\t\tvar err error\n\t\t\t\t\tswitch r := r.(type) {\n\t\t\t\t\tcase error:\n\t\t\t\t\t\terr = r\n\t\t\t\t\tdefault:\n\t\t\t\t\t\terr = fmt.Errorf(\"%v\", r)\n\t\t\t\t\t}\n\t\t\t\t\tif config.DisableStackAll {\n\t\t\t\t\t\tc.Error(panicErr.SetError(err))\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tcontent := \"[PANIC RECOVER] \" + err.Error()\n\t\t\t\t\tfor i := 1; len(content) < config.StackSize; i++ {\n\t\t\t\t\t\tpc, file, line, ok := runtime.Caller(i)\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tt := &echo.Trace{\n\t\t\t\t\t\t\tFile: file,\n\t\t\t\t\t\t\tLine: line,\n\t\t\t\t\t\t\tFunc: runtime.FuncForPC(pc).Name(),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpanicErr.AddTrace(t)\n\t\t\t\t\t\tcontent += \"\\n\" + fmt.Sprintf(`%v:%v`, file, line)\n\t\t\t\t\t}\n\t\t\t\t\tpanicErr.SetErrorString(content)\n\t\t\t\t\tc.Logger().Error(panicErr)\n\t\t\t\t\tc.Error(panicErr)\n\t\t\t\t}\n\t\t\t}()\n\t\t\treturn next.Handle(c)\n\t\t})\n\t}\n}", "func Recover(pf ...func(c *gin.Context, stack string)) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\ts := stack()\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"app\": c.GetString(gin_handler.KEY_APPNAME),\n\t\t\t\t\t\"stack\": s,\n\t\t\t\t}).Error(err)\n\n\t\t\t\tfor _, f := range pf {\n\t\t\t\t\tf(c, s)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\tc.Next()\n\t}\n}", "func PanicLogging(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tgoErr := errors.Wrap(err, 3)\n\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\"err\": goErr.Err,\n\t\t\t\t\t\"stackTrace\": string(goErr.Stack()),\n\t\t\t\t}).Errorf(\"Panic recovery -> %s\\n\", goErr.Err)\n\t\t\t}\n\t\t}()\n\t\th.ServeHTTP(w, r)\n\t})\n}", "func recoverFunc(w http.ResponseWriter, r *http.Request) {\n\trecoverError := recover()\n\tif recoverError != nil {\n\t\thttp.Error(w, fmt.Sprint(\"Error: \", recoverError), http.StatusInternalServerError)\n\t}\n}", "func withRecover(ctx context.Context, fn func()) {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tlogger.Error(ctx, \"dispatcher-panic error: %v\", err)\n\t\t\tsentry.Panic(err, \"request_id\", middleware.GetRequestId(ctx))\n\t\t}\n\t}()\n\n\tfn()\n}", "func RecoverMiddleware(next HandlerFunc) HandlerFunc {\n\tfn := func(ctx *Context) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\te := NewError(err)\n\t\t\t\thttpRequest, _ := httputil.DumpRequest(ctx.Request, true)\n\t\t\t\tlog.Printf(\"[Recovery] panic recovered:\\n%s\\n%s\\n%s\", string(httpRequest), err, e.StackTraceString())\n\t\t\t\tctx.statusCode = 500\n\t\t\t\tctx.Abort(500, map[string]interface{}{\n\t\t\t\t\t\"Code\": ctx.statusCode,\n\t\t\t\t\t\"Title\": \"Internal Server Error\",\n\t\t\t\t\t\"HTTPRequest\": string(httpRequest),\n\t\t\t\t\t\"Message\": e.Error(),\n\t\t\t\t\t\"StackTrace\": e.Stack,\n\t\t\t\t})\n\t\t\t}\n\t\t}()\n\t\tnext(ctx)\n\t}\n\treturn fn\n}", "func handlePanic(resp http.ResponseWriter, status int) {\n\tif p := recover(); p != nil {\n\n\t\tmessageFmt := \"Unhandled panic: %s\"\n\t\tvar err error\n\n\t\tswitch p.(type) {\n\t\tcase nil:\n\t\t\t// normal case, just ignore.\n\t\tcase string:\n\t\t\tmessageFmt = p.(string)\n\t\t\terr = errors.New(messageFmt)\n\t\tcase error:\n\t\t\terr = p.(error)\n\t\tdefault:\n\t\t\terr = errors.New(fmt.Sprint(p))\n\t\t}\n\n\t\tif err != nil {\n\t\t\treportError(err, messageFmt, resp, status)\n\t\t}\n\t}\n}", "func Recovery() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tyiigo.Logger.Error(fmt.Sprintf(\"yiigo demo panic: %v\", err), zap.ByteString(\"stack\", debug.Stack()))\n\n\t\t\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\t\t\"success\": false,\n\t\t\t\t\t\"code\": 5000,\n\t\t\t\t\t\"msg\": \"服务器错误,请稍后重试\",\n\t\t\t\t})\n\n\t\t\t\treturn\n\t\t\t}\n\t\t}()\n\n\t\tc.Next()\n\t}\n}", "func RecoverAndLog() {\n\tif r := recover(); r != nil {\n\t\tfmt.Println(\"Panic digested from \", r)\n\n\t\tlog.Printf(\"Internal error: %v\", r)\n\t\tbuf := make([]byte, 1<<16)\n\t\tstackSize := runtime.Stack(buf, true)\n\t\t//log.Printf(\"%s\\n\", string(buf[0:stackSize]))\n\n\t\tvar dir = platform.GetSurgeDir()\n\t\tvar logPathOS = dir + string(os.PathSeparator) + \"paniclog.txt\"\n\t\tf, _ := os.OpenFile(logPathOS, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)\n\t\tw := bufio.NewWriter(f)\n\t\tw.WriteString(string(buf[0:stackSize]))\n\t\tw.Flush()\n\n\t\tpushError(\"Panic\", \"Please check your log file and paniclog for more info\")\n\n\t\tpanic(\"Panic dumped but not digested, please check your log\")\n\t}\n}", "func (req *Request) handlePanic() {\n\tif rec := recover(); rec != nil {\n\t\treq.Response.WriteHeader(http.StatusInternalServerError)\n\t\treq.Response.Write([]byte(`{\"error\":\"Something went wrong\"}`))\n\n\t\t// The recovered panic may not be an error\n\t\tvar err error\n\t\tswitch val := rec.(type) {\n\t\tcase error:\n\t\t\terr = val\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"%v\", val)\n\t\t}\n\t\terr = fmt.Errorf(\"panic: %v\", err)\n\n\t\tlogger.Errorf(`message: \"%s\", %s`, err.Error(), req)\n\t\tlogger.Errorf(string(debug.Stack()))\n\n\t\t// Send an email async\n\t\tif mailer.Emailer != nil {\n\t\t\tsendEmail := func(stacktrace []byte) {\n\t\t\t\terr := mailer.Emailer.SendStackTrace(stacktrace, req.Endpoint(), err.Error(), req.ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(err.Error())\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgo sendEmail(debug.Stack())\n\t\t}\n\t}\n}", "func WithPanicRecovery(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tdefer runtime.HandleCrash(func(err interface{}) {\n\t\t\thttp.Error(w, \"This request caused apisever to panic. Look in log for details.\", http.StatusInternalServerError)\n\t\t\tglog.Errorf(\"APIServer panic'd on %v %v: %v\\n%s\\n\", req.Method, req.RequestURI, err, debug.Stack())\n\t\t})\n\n\t\tlogger := httplog.NewLogged(req, &w)\n\t\tdefer logger.Log()\n\n\t\t// Dispatch to the internal handler\n\t\thandler.ServeHTTP(w, req)\n\t})\n}", "func LoggingAndRecovery(c lars.Context) {\n\n\tt1 := time.Now()\n\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\ttrace := make([]byte, 1<<16)\n\t\t\tn := runtime.Stack(trace, true)\n\t\t\tlog.Printf(\" %srecovering from panic: %+v\\nStack Trace:\\n %s%s\", ansi.Red, err, trace[:n], ansi.Reset)\n\t\t\tHandlePanic(c, trace[:n])\n\t\t\treturn\n\t\t}\n\t\tcolor := status\n\t res := c.Response()\n\t req := c.Request()\n\t code := res.Status()\n\n\t switch {\n\t case code >= http.StatusInternalServerError:\n\t\t color = status500\n\t case code >= http.StatusBadRequest:\n\t\t color = status400\n\t case code >= http.StatusMultipleChoices:\n\t\t color = status300\n\t }\n\n\t t2 := time.Now()\n\n\t log.Printf(\"%s %d %s[%s%s%s] %q %v %d\\n\", color, code, ansi.Reset, color, req.Method, ansi.Reset, req.URL, t2.Sub(t1), res.Size())\n\t}()\n\n\tc.Next()\t\n}", "func Panic(panicHandler http.Handler) Middleware {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tdefer func() {\n\t\t\t\tif e := recover(); e != nil {\n\t\t\t\t\tlog.Errorf(r.Context(), \"middleware.Panic: %v\", e)\n\t\t\t\t\tpanicHandler.ServeHTTP(w, r)\n\t\t\t\t}\n\t\t\t}()\n\t\t\th.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func (h *Panic) ServeHTTP(r http.ResponseWriter, req *http.Request) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\th.loggerFunc(\"begin: recovered from panic\")\n\t\t\th.loggerFunc(fmt.Sprintf(\"unkown value of recover (%v)\", r))\n\t\t\th.loggerFunc(fmt.Sprintf(\"url %v\", req.URL.String()))\n\t\t\th.loggerFunc(fmt.Sprintf(\"method %v\", req.Method))\n\t\t\th.loggerFunc(fmt.Sprintf(\"remote address %v\", req.RemoteAddr))\n\t\t\th.loggerFunc(fmt.Sprintf(\"stack strace of cause \\n %v\", string(debug.Stack())))\n\t\t\th.loggerFunc(\"end: recovered from panic\")\n\t\t}\n\t}()\n\th.Next.ServeHTTP(r, req)\n}", "func Recovery(next http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tvar failed bool\n\t\tsafe.Routine(\n\t\t\tfunc() {\n\t\t\t\tnext(w, r)\n\t\t\t},\n\t\t\tfunc() {\n\t\t\t\tfailed = true\n\t\t\t},\n\t\t\tr,\n\t\t)\n\t\tif failed {\n\t\t\tframework.JSON(\n\t\t\t\tw,\n\t\t\t\thttp.StatusInternalServerError,\n\t\t\t\tstruct {\n\t\t\t\t\tError string `json:\"error\"`\n\t\t\t\t}{\n\t\t\t\t\tError: http.StatusText(http.StatusInternalServerError),\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t}\n}", "func Recover(next noodle.Handler) noodle.Handler {\n\treturn func(c context.Context, w http.ResponseWriter, r *http.Request) (err error) {\n\t\tdefer func() {\n\t\t\tif e := recover(); e != nil {\n\t\t\t\terr = RecoverError{e, debug.Stack()}\n\t\t\t}\n\t\t}()\n\t\terr = next(c, w, r)\n\t\treturn\n\t}\n}", "func (o *Obs) PanicRecover() {\n\tif r := recover(); r != nil {\n\t\t// According to Russ Cox (leader of the Go team) capturing the stack trace here works:\n\t\t// https://groups.google.com/d/msg/golang-nuts/MB8GyW5j2UY/m_YYy7mGYbIJ .\n\t\to.Logger.WithField(\"stack\", string(debug.Stack())).Error(fmt.Sprintf(\"%v\", r))\n\t}\n}", "func PanicHandler() func(http.ResponseWriter, *http.Request, interface{}) {\n\treturn func(w http.ResponseWriter, r *http.Request, rcv interface{}) {\n\t\tresponse := ResultInternalServerErr\n\t\tif env := viper.GetString(`env`); env == \"development\" {\n\t\t\tif rcv != nil {\n\t\t\t\tresponse.SetMessage(rcv)\n\t\t\t}\n\t\t}\n\n\t\tlog.Printf(\"%s %s\", r.Method, r.URL.Path)\n\t\tlog.Printf(\"Panic Error: %+v\", rcv)\n\n\t\tJSONResult(w, &response)\n\t}\n}", "func TestRecovererPanicWithStack(t *testing.T) {\n\treq, err := http.NewRequest(\"GET\", \"/\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tConvey(\"When a request is made, and panics, it is recovered\", t, func() {\n\t\ttestHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tpanic(\"OH MY GOSH!\")\n\t\t})\n\n\t\tConf.Set(ConfigRecovererLogStackTraces, true)\n\n\t\trr := httptest.NewRecorder()\n\n\t\thandler := Recoverer(testHandler)\n\n\t\t// Set up a dummy requestID\n\t\tctx := WithRqID(req.Context(), \"abc123\")\n\t\treq = req.WithContext(ctx)\n\n\t\thandler.ServeHTTP(rr, req)\n\n\t\tSo(rr.Code, ShouldEqual, http.StatusInternalServerError)\n\t\tSo(rr.Body.String(), ShouldContainSubstring, http.StatusText(http.StatusInternalServerError))\n\t})\n}", "func RecoverMiddleware(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer recoverInternal(w)\n\t\th.ServeHTTP(w, r)\n\t})\n}", "func panicHandler(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tlogrus.Panic(fmt.Sprintf(\"%v\", err))\n\t\t\t}\n\t\t}()\n\t\thandler.ServeHTTP(w, r)\n\t})\n}", "func (m *Monitor) Recovery(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {\n\t// recovery func\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\t// log stack\n\t\t\tstack := make([]byte, MAXSTACKSIZE)\n\t\t\tstack = stack[:runtime.Stack(stack, false)]\n\t\t\terrStack := string(stack)\n\t\t\tlog.Errorf(\"panic grpc invoke: %s, err=%v, stack:\\n%s\", info.FullMethod, r, errStack)\n\n\t\t\tfunc() {\n\t\t\t\tdefer func() {\n\t\t\t\t\tif r := recover(); err != nil {\n\t\t\t\t\t\tlog.Errorf(\"report sentry failed: %s, trace:\\n%s\", r, debug.Stack())\n\t\t\t\t\t\terr = grpc.Errorf(codes.Internal, \"panic error: %v\", r)\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t\tswitch rval := r.(type) {\n\t\t\t\tcase error:\n\t\t\t\t\tm.ObserveError(info.FullMethod, rval)\n\t\t\t\tdefault:\n\t\t\t\t\tm.ObserveError(info.FullMethod, errors.New(fmt.Sprint(rval)))\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\t// if panic, set custom error to 'err', in order that client and sense it.\n\t\t\terr = grpc.Errorf(codes.Internal, \"panic error: %v\", r)\n\t\t}\n\t}()\n\n\treturn handler(ctx, req)\n}", "func TestMiddlewares_OnPanic(t *testing.T) {\n\tassert := assertlib.New(t)\n\thook, restoreFct := logging.MockSharedLoggerHook()\n\tdefer restoreFct()\n\tapp, _ := New()\n\trouter := app.HTTPHandler\n\trouter.Get(\"/dummy\", func(http.ResponseWriter, *http.Request) {\n\t\tpanic(\"error in service\")\n\t})\n\tsrv := httptest.NewServer(router)\n\tdefer srv.Close()\n\n\tnbLogsBeforeRequest := len(hook.AllEntries())\n\trequest, _ := http.NewRequest(\"GET\", srv.URL+\"/dummy\", http.NoBody)\n\trequest.Header.Set(\"X-Forwarded-For\", \"1.1.1.1\")\n\tresponse, err := http.DefaultClient.Do(request)\n\tassert.NoError(err)\n\tif err != nil {\n\t\treturn\n\t}\n\trespBody, _ := ioutil.ReadAll(response.Body)\n\t_ = response.Body.Close()\n\n\t// check that the error has been handled by the recover\n\tassert.Equal(http.StatusInternalServerError, response.StatusCode)\n\tassert.Equal(\"Internal Server Error\\n\", string(respBody))\n\tassert.Equal(\"text/plain; charset=utf-8\", response.Header.Get(\"Content-type\"))\n\tallLogs := hook.AllEntries()\n\tassert.Equal(2, len(allLogs)-nbLogsBeforeRequest)\n\t// check that the req id is correct\n\tassert.Equal(allLogs[len(allLogs)-1].Data[\"req_id\"], allLogs[len(allLogs)-2].Data[\"req_id\"])\n\t// check that the recovere put the error info in the logs\n\tassert.Equal(\"error in service\", hook.LastEntry().Data[\"panic\"])\n\tassert.NotNil(hook.LastEntry().Data[\"stack\"])\n\t// check that the real IP is used in the logs\n\tassert.Equal(\"1.1.1.1\", allLogs[len(allLogs)-1].Data[\"remote_addr\"])\n\tassert.Equal(\"1.1.1.1\", allLogs[len(allLogs)-2].Data[\"remote_addr\"])\n}", "func PanicRecovery(onRecovery func(interface{}, context.Context, *amqprpc.ResponseWriter, amqp.Delivery)) amqprpc.ServerMiddlewareFunc {\n\treturn func(next amqprpc.HandlerFunc) amqprpc.HandlerFunc {\n\t\treturn func(ctx context.Context, rw *amqprpc.ResponseWriter, d amqp.Delivery) {\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tonRecovery(r, ctx, rw, d)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tnext(ctx, rw, d)\n\t\t}\n\t}\n}", "func panicRecover() {\n\tif rec := recover(); rec != nil {\n\t\tlog.Printf(\"Panic: %v\", rec)\n\t}\n}", "func Recoverer(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif rvr := recover(); rvr != nil {\n\n\t\t\t\tvar err error\n\t\t\t\tswitch x := rvr.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\terr = errors.New(x)\n\t\t\t\tcase error:\n\t\t\t\t\terr = x\n\t\t\t\tdefault:\n\t\t\t\t\terr = errors.New(\"unknown error\")\n\t\t\t\t}\n\n\t\t\t\tlog.Error().Stack().Err(errors.Wrap(err, \"unexpected error\")).Msg(\"unexpected error\")\n\t\t\t\tdebug.PrintStack()\n\t\t\t\trenderServerError(err, w, r)\n\t\t\t}\n\t\t}()\n\n\t\tnext.ServeHTTP(w, r)\n\t}\n\n\treturn http.HandlerFunc(fn)\n}", "func (rec *Recoverer) Wrap(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tw.Header().Set(\"Connection\", \"close\")\n\t\t\t\trestErr := &rest.Error{\n\t\t\t\t\tErr: fmt.Errorf(\"there was a panic: %s\", err),\n\t\t\t\t\tStatus: http.StatusInternalServerError,\n\t\t\t\t\tMessage: \"Internal Server Error\",\n\t\t\t\t\tIsSilent: false,\n\t\t\t\t\tInternalLogs: []zapcore.Field{\n\t\t\t\t\t\tzap.Stack(\"stack\"),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\trest.SendRESTError(w, r, rec.Logger, restErr)\n\t\t\t}\n\t\t}()\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func PanicRecovery(err *error, logErrors bool, txnID string) func() {\n\treturn func() {\n\n\t\t// If err is nil, we don't want to cause a panic. However, we can't actually set it\n\t\t// and have it persist beyond this function. Therefore, we force logging on so it\n\t\t// isn't just ignored completely if we receive a nil pointer.\n\t\tif err == nil {\n\t\t\tlogErrors = true\n\t\t\terr = new(error)\n\t\t}\n\n\t\tif r := recover(); r != nil && err != nil {\n\t\t\ts, i, _ := identifyPanic()\n\n\t\t\tswitch r := r.(type) {\n\t\t\tcase error:\n\t\t\t\tif logErrors {\n\t\t\t\t\tlog.WithFields(log.Fields{\"panic\": \"error\", \"file\": s, \"line_num\": i, \"txnID\": txnID}).Error(r)\n\t\t\t\t}\n\n\t\t\t\t// Create a new error and assign it to our pointer.\n\t\t\t\t*err = r.(error)\n\t\t\tcase string:\n\t\t\t\tif logErrors {\n\t\t\t\t\tlog.WithFields(log.Fields{\"panic\": \"string\", \"file\": s, \"line_num\": i, \"txnID\": txnID}).Error(r)\n\t\t\t\t}\n\n\t\t\t\t// Create a new error and assign it to our pointer.\n\t\t\t\t*err = errors.New(r)\n\t\t\tdefault:\n\t\t\t\tmsg := fmt.Sprintf(\"%+v\", r)\n\n\t\t\t\tif logErrors {\n\t\t\t\t\tlog.WithFields(log.Fields{\"panic\": \"default\", \"file\": s, \"line_num\": i, \"txnID\": txnID}).Error(msg)\n\t\t\t\t}\n\n\t\t\t\t// Create a new error and assign it to our pointer.\n\t\t\t\t*err = errors.New(\"Panic: \" + msg)\n\t\t\t}\n\t\t}\n\t}\n}", "func handlePanic() {\n\tif r := recover(); r != nil {\n\t\tlog.Printf(\"panic recovered: %s \\n %s\", r, debug.Stack())\n\t}\n}", "func panicHandler(w http.ResponseWriter, r *http.Request) {\n\tfuncThatPanic()\n}", "func Recovery(ctx *gin.Context) {\n\tdefer func(ctx *gin.Context) {\n\t\tif rec := recover(); rec != nil {\n\t\t\t//err := utils.GetError(rec)\n\n\t\t\t//errorCode := rzperrors.ErrorInternalServerError\n\t\t\t//payloadCreationError := rzperrors.NewRzpError(ctx, errorCode, err)\n\t\t\t//logger.RzpError(ctx, payloadCreationError)\n\n\t\t\tresponse := dtos.Base{}\n\t\t\tresponse.Success = false\n\t\t\t//response.Error = payloadCreationError.ErrorCode()\n\t\t\tresponse.Error = errors.New(\"error\")\n\t\t\tctx.JSON(http.StatusInternalServerError, response)\n\t\t}\n\t}(ctx)\n\n\tctx.Next()\n}", "func (this *BaseController) Panic() revel.Result {\n\tdefer func() {\n\t\tmongo.CloseSession(this.UserId, this.MongoSession)\n\t\tthis.MongoSession = nil\n\t}()\n\n\ttracelog.TRACE(this.UserId, \"Panic\", this.Request.URL.Path)\n\treturn nil\n}", "func PanicCatcher(logger *Xlogger) {\n\tif err := recover(); err != nil {\n\t\tlogger.Print(err)\n\t\tlogger.Print(string(debug.Stack()[:]))\n\t}\n}", "func RecoveryHandler(c *gin.Context, err interface{}) {\r\n\tc.JSON(http.StatusInternalServerError, gin.H{\r\n\t\t\"code\": http.StatusInternalServerError,\r\n\t\t\"err\": err,\r\n\t})\r\n}", "func TestPanicInHandler(t *testing.T) {\n\tbuffer := new(strings.Builder)\n\trouter := New()\n\trouter.Use(RecoveryWithWriter(buffer))\n\trouter.GET(\"/recovery\", func(_ *Context) {\n\t\tpanic(\"Oupps, Houston, we have a problem\")\n\t})\n\t// RUN\n\tw := PerformRequest(router, \"GET\", \"/recovery\")\n\t// TEST\n\tassert.Equal(t, http.StatusInternalServerError, w.Code)\n\tassert.Contains(t, buffer.String(), \"panic recovered\")\n\tassert.Contains(t, buffer.String(), \"Oupps, Houston, we have a problem\")\n\tassert.Contains(t, buffer.String(), t.Name())\n\tassert.NotContains(t, buffer.String(), \"GET /recovery\")\n\n\t// Debug mode prints the request\n\tSetMode(DebugMode)\n\t// RUN\n\tw = PerformRequest(router, \"GET\", \"/recovery\")\n\t// TEST\n\tassert.Equal(t, http.StatusInternalServerError, w.Code)\n\tassert.Contains(t, buffer.String(), \"GET /recovery\")\n\n\tSetMode(TestMode)\n}", "func (e *recoverableError) recover() {\n}", "func ensurePanicResponses(ctx context.Context, resp http.ResponseWriter, hooks *twirp.ServerHooks) {\n\tif r := recover(); r != nil {\n\t\t// Wrap the panic as an error so it can be passed to error hooks.\n\t\t// The original error is accessible from error hooks, but not visible in the response.\n\t\terr := errFromPanic(r)\n\t\ttwerr := &internalWithCause{msg: \"Internal service panic\", cause: err}\n\t\t// Actually write the error\n\t\twriteError(ctx, resp, twerr, hooks)\n\t\t// If possible, flush the error to the wire.\n\t\tf, ok := resp.(http.Flusher)\n\t\tif ok {\n\t\t\tf.Flush()\n\t\t}\n\n\t\tpanic(r)\n\t}\n}", "func ensurePanicResponses(ctx context.Context, resp http.ResponseWriter, hooks *twirp.ServerHooks) {\n\tif r := recover(); r != nil {\n\t\t// Wrap the panic as an error so it can be passed to error hooks.\n\t\t// The original error is accessible from error hooks, but not visible in the response.\n\t\terr := errFromPanic(r)\n\t\ttwerr := &internalWithCause{msg: \"Internal service panic\", cause: err}\n\t\t// Actually write the error\n\t\twriteError(ctx, resp, twerr, hooks)\n\t\t// If possible, flush the error to the wire.\n\t\tf, ok := resp.(http.Flusher)\n\t\tif ok {\n\t\t\tf.Flush()\n\t\t}\n\n\t\tpanic(r)\n\t}\n}", "func TestRecovererPanic(t *testing.T) {\n\treq, err := http.NewRequest(\"GET\", \"/\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tConvey(\"When a request is made, and panics, it is recovered\", t, func() {\n\t\ttestHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tpanic(\"OH MY GOSH!\")\n\t\t})\n\n\t\trr := httptest.NewRecorder()\n\n\t\thandler := Recoverer(testHandler)\n\n\t\t// Set up a dummy requestID\n\t\tctx := WithRqID(req.Context(), \"abc123\")\n\t\treq = req.WithContext(ctx)\n\n\t\thandler.ServeHTTP(rr, req)\n\n\t\tSo(rr.Code, ShouldEqual, http.StatusInternalServerError)\n\t\tSo(rr.Body.String(), ShouldContainSubstring, http.StatusText(http.StatusInternalServerError))\n\t})\n}", "func WithRecover(next http.Handler) http.Handler {\n\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tvar err error\n\t\tdefer func() {\n\t\t\tr := recover()\n\t\t\tif r != nil {\n\t\t\t\tswitch t := r.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\terr = errors.New(t)\n\t\t\t\tcase error:\n\t\t\t\t\terr = t\n\t\t\t\tdefault:\n\t\t\t\t\terr = errors.New(\"Unknown error\")\n\t\t\t\t}\n\t\t\t\tJSONErrorResponse(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t}()\n\t\tnext.ServeHTTP(w, r)\n\t})\n\treturn handler\n}", "func Recovery(f func(c *gin.Context, err interface{})) gin.HandlerFunc {\r\n\treturn RecoveryWithoutWriter(f)\r\n}", "func panicHandler(r interface{}) error {\n\tfmt.Println(\"600 Error\")\n\treturn ErrPanic(r)\n}", "func (e *Handler) Panic(err error) {\n\thas := e.hasErrPrint(err)\n\tif !has {\n\t\treturn\n\t}\n\tpanic(err)\n}", "func (r NopReporter) Recover(ctx context.Context) { _ = recover() }" ]
[ "0.73594993", "0.7038121", "0.7008406", "0.6885905", "0.6658655", "0.6547491", "0.64594406", "0.64355105", "0.6379547", "0.63791853", "0.63632184", "0.63296616", "0.631733", "0.630849", "0.6275611", "0.6274496", "0.6261786", "0.62580246", "0.6256298", "0.6241197", "0.6223762", "0.6192447", "0.61773324", "0.61270356", "0.61258286", "0.609522", "0.60912746", "0.6077271", "0.60605067", "0.60467154", "0.6045846", "0.6035639", "0.60198396", "0.5901158", "0.58971477", "0.58632076", "0.5855417", "0.58506507", "0.5845874", "0.58378506", "0.58223313", "0.57750255", "0.57744026", "0.5773004", "0.5765472", "0.5742097", "0.5722865", "0.5701837", "0.56872296", "0.5670874", "0.5665572", "0.56514734", "0.56417614", "0.5641385", "0.56173354", "0.56125844", "0.56072664", "0.55658734", "0.5565333", "0.5562891", "0.5558917", "0.5544191", "0.55410916", "0.5512701", "0.550641", "0.55061996", "0.5491171", "0.5484914", "0.5476612", "0.54745084", "0.5470959", "0.5467471", "0.54307073", "0.54284394", "0.54189104", "0.54107344", "0.54085386", "0.5391545", "0.53864807", "0.53848326", "0.5359253", "0.5348781", "0.5340913", "0.5332834", "0.52714217", "0.52656513", "0.5265248", "0.52549696", "0.5253379", "0.52384603", "0.52274966", "0.52261835", "0.5211609", "0.5211609", "0.5209815", "0.51948416", "0.51859206", "0.5177097", "0.5163856", "0.51318914" ]
0.74536425
0
Simple CORS implementation that wraps an http Handler For a more detailed implementation use or implement CORS at your proxy layer Pass nil for allowedMethods and allowedHeaders to use the defaults
func CORS(handler http.Handler, alloweedOriginPatterns []*regexp.Regexp, allowedMethods, allowedHeaders []string, allowCredentials string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { origin := req.Header.Get("Origin") if origin != "" { allowed := false for _, pattern := range alloweedOriginPatterns { if allowed = pattern.MatchString(origin); allowed { break } } if allowed { w.Header().Set("Access-Control-Allow-Origin", origin) // Set defaults for methods and headers if nothing was passed if allowedMethods == nil { allowedMethods = []string{"POST", "GET", "OPTIONS", "PUT", "DELETE"} } if allowedHeaders == nil { allowedHeaders = []string{"Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", "X-Requested-With", "If-Modified-Since"} } w.Header().Set("Access-Control-Allow-Methods", strings.Join(allowedMethods, ", ")) w.Header().Set("Access-Control-Allow-Headers", strings.Join(allowedHeaders, ", ")) w.Header().Set("Access-Control-Allow-Credentials", allowCredentials) // Stop here if its a preflight OPTIONS request if req.Method == "OPTIONS" { w.WriteHeader(http.StatusNoContent) return } } } // Dispatch to the next handler handler.ServeHTTP(w, req) }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func AllowCORS(h http.Handler) http.Handler {\n return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n if origin := r.Header.Get(\"Origin\"); origin != \"\" {\n w.Header().Set(\"Access-Control-Allow-Origin\", origin)\n if r.Method == \"OPTIONS\" && r.Header.Get(\"Access-Control-Request-Method\") != \"\" {\n preflightHandler(w, r)\n return\n }\n }\n h.ServeHTTP(w, r)\n })\n}", "func CorsHandler(options Options) func(http.Handler) http.Handler {\n\n\treturn func(next http.Handler) http.Handler {\n\t\t// Setting the default origins in case not specified\n\t\tif options.AllowOrigins == nil {\n\t\t\toptions.AllowOrigins = defaultAllowOrigins\n\t\t}\n\t\t// Setting the default headers in case not specified\n\t\tif options.AllowHeaders == nil {\n\t\t\toptions.AllowHeaders = defaultAllowHeaders\n\t\t}\n\t\t// Setting the default methods in case not specified\n\t\tif options.AllowMethods == nil {\n\t\t\toptions.AllowMethods = defaultAllowMethods\n\t\t}\n\t\t// Request managing func\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tif len(options.AllowOrigins) > 0 {\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", strings.Join(options.AllowOrigins, \" \"))\n\t\t\t} else {\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\t\t}\n\n\t\t\tif len(options.AllowHeaders) > 0 {\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Headers\", strings.Join(options.AllowHeaders, \",\"))\n\t\t\t} else {\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Headers\", strings.Join(defaultAllowHeaders, \",\"))\n\t\t\t}\n\n\t\t\tif len(options.AllowMethods) > 0 {\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Methods\", strings.Join(options.AllowMethods, \",\"))\n\t\t\t} else {\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Methods\", strings.Join(defaultAllowMethods, \",\"))\n\t\t\t}\n\n\t\t\tif options.AllowCredentials {\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Credentials\", strconv.FormatBool(defaultAllowCredentials))\n\t\t\t}\n\n\t\t\t/** OPTIONS Method returns no content status, this is important for example\n\t\t\twhen requesting server when AngularJS Resources in order to avoid OPTIONS Request error\n\t\t\t*/\n\t\t\tif r.Method == OptionsMethod {\n\t\t\t\tw.WriteHeader(http.StatusNoContent)\n\t\t\t}\n\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func (handler Handler) CORSWrapper(hf func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", handler.ContentType)\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type, Authorization, Cache-Control\")\n\t\tw.Header().Set(\"Access-Control-Expose-Headers\", \"*\")\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, DELETE, OPTIONS\")\n\t\tif r.Method == \"OPTIONS\" {\n\t\t\tlog.Printf(\"incoming CORS request\")\n\t\t} else {\n\t\t\tlog.Printf(\"incoming request\")\n\t\t\tw.Header().Set(\"Content-Type\", handler.ContentType)\n\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Authorization\")\n\t\t\thf(w, r)\n\t\t}\n\t}\n\n}", "func Cors(inner http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"*\")\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Accept, Content-Type, Content-Length, Accept-Encoding, Authorization\")\n\n\t\tif r.Method != \"OPTIONS\" {\n\t\t\tinner.ServeHTTP(w, r)\n\t\t}\n\t})\n}", "func CORS() func(next http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\t\tw.Header().Set(\"Access-Control-Allow-Methods\", strings.Join([]string{\n\t\t\t\thttp.MethodHead,\n\t\t\t\thttp.MethodOptions,\n\t\t\t\thttp.MethodGet,\n\t\t\t}, \", \"))\n\t\t\tnext.ServeHTTP(w, r)\n\t\t}\n\t\treturn http.HandlerFunc(fn)\n\t}\n}", "func CORS() func(next http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\t\tw.Header().Set(\"Access-Control-Allow-Methods\", strings.Join([]string{\n\t\t\t\thttp.MethodHead,\n\t\t\t\thttp.MethodOptions,\n\t\t\t\thttp.MethodGet,\n\t\t\t\thttp.MethodPost,\n\t\t\t\thttp.MethodPut,\n\t\t\t\thttp.MethodPatch,\n\t\t\t\thttp.MethodDelete,\n\t\t\t}, \", \"))\n\t\t\tnext.ServeHTTP(w, r)\n\t\t}\n\t\treturn http.HandlerFunc(fn)\n\t}\n}", "func CORS(handler http.Handler, allowedOriginPatterns []*regexp.Regexp, allowedMethods []string, allowedHeaders []string, allowCredentials string) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\torigin := req.Header.Get(\"Origin\")\n\t\tif origin != \"\" {\n\t\t\tallowed := false\n\t\t\tfor _, pattern := range allowedOriginPatterns {\n\t\t\t\tif allowed = pattern.MatchString(origin); allowed {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif allowed {\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\t\t// Set defaults for methods and headers if nothing was passed\n\t\t\t\tif allowedMethods == nil {\n\t\t\t\t\tallowedMethods = []string{\"POST\", \"GET\", \"OPTIONS\", \"PUT\", \"DELETE\"}\n\t\t\t\t}\n\t\t\t\tif allowedHeaders == nil {\n\t\t\t\t\tallowedHeaders = []string{\"Content-Type\", \"Content-Length\", \"Accept-Encoding\", \"X-CSRF-Token\", \"Authorization\", \"X-Requested-With\", \"If-Modified-Since\"}\n\t\t\t\t}\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Methods\", strings.Join(allowedMethods, \", \"))\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Headers\", strings.Join(allowedHeaders, \", \"))\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Credentials\", allowCredentials)\n\n\t\t\t\t// Stop here if its a preflight OPTIONS request\n\t\t\t\tif req.Method == \"OPTIONS\" {\n\t\t\t\t\tw.WriteHeader(http.StatusNoContent)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Dispatch to the next handler\n\t\thandler.ServeHTTP(w, req)\n\t})\n}", "func Cors(f HandlerFunc) HandlerFunc {\n\treturn func(ctx context.Context, r events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\t\tlogger := api.StandardLambdaLogger(ctx, pkg.EnvLogLevel)\n\t\torigin := \"\"\n\t\tif val, ok := r.Headers[\"Origin\"]; ok {\n\t\t\torigin = val\n\t\t} else if val2, ok2 := r.Headers[\"origin\"]; ok2 {\n\t\t\torigin = val2\n\t\t}\n\t\tlogger.Debugw(\"Found origin value...\", log.Fields{\n\t\t\t\"origin\": origin,\n\t\t})\n\t\tresponse, err := f(ctx, r)\n\t\tif err != nil {\n\t\t\t// don't set cors headers on a response that errored out\n\t\t\treturn response, err\n\t\t}\n\n\t\tif origin == \"\" {\n\t\t\tlogger.Debug(\"Empty 'Origin' header passed in, no cors available\")\n\t\t\treturn response, err\n\t\t}\n\t\tnormalizedOrigin := normalizeOrigin(origin)\n\t\tallowedOrigins := getAllowedOrigins(pkg.EnvCorsAllowedOrigins)\n\t\tallowedOrigin := \"\"\n\t\tfor _, curOrigin := range allowedOrigins {\n\t\t\tif curOrigin == normalizedOrigin {\n\t\t\t\tallowedOrigin = origin\n\t\t\t}\n\t\t}\n\t\tif allowedOrigin == \"\" {\n\t\t\t// don't set cors headers if the origin was not an allowed one\n\t\t\tlogger.Warnw(\"Unidentified origin attempting to call the api\", log.Fields{\n\t\t\t\t\"origin\": origin,\n\t\t\t})\n\t\t\treturn response, err\n\t\t}\n\t\tif _, ok := response.Headers[AllowCredentials]; !ok {\n\t\t\tresponse.Headers[AllowCredentials] = \"true\"\n\t\t}\n\t\tfinalAllowedHeaders := getAllowedHeadersStr(allowedHeaders)\n\t\tif _, ok := response.Headers[AllowHeaders]; !ok {\n\t\t\tresponse.Headers[AllowHeaders] = finalAllowedHeaders\n\t\t\tlogger.Debugw(\"Recording allowed headers...\", log.Fields{\n\t\t\t\t\"allowedHeaders\": finalAllowedHeaders,\n\t\t\t})\n\t\t}\n\t\tif _, ok := response.Headers[AllowMethods]; !ok {\n\t\t\tresponse.Headers[AllowMethods] = strings.Join(allowedMethods, \",\")\n\t\t}\n\t\tif _, ok := response.Headers[AllowOrigin]; !ok {\n\t\t\tresponse.Headers[AllowOrigin] = allowedOrigin\n\t\t}\n\t\tif _, ok := response.Headers[ExposeHeaders]; !ok {\n\t\t\tresponse.Headers[ExposeHeaders] = finalAllowedHeaders\n\t\t}\n\n\t\treturn response, err\n\t}\n}", "func CORS(fn http.Handler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif origin := r.Header.Get(\"Origin\"); origin != \"\" {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS, PUT, DELETE\")\n\t\t\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\t\tw.Header().Set(\"Access-Control-Allow-Headers\",\n\t\t\t\t\"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization\")\n\t\t\tw.Header().Set(\"Access-Control-Expose-Headers\", \"Status, Content-Type, Content-Length\")\n\t\t}\n\t\t// Stop here if its Preflighted OPTIONS request\n\t\tif r.Method == \"OPTIONS\" {\n\t\t\treturn\n\t\t}\n\n\t\tfn.ServeHTTP(w, r)\n\t}\n}", "func CORS(h http.Handler) http.Handler {\n\tallowHeaders := strings.Join([]string{\n\t\t\"Access-Control-Allow-Origin\",\n\t\t\"Access-Control-Allow-Headers\",\n\t\t\"Access-Control-Allow-Methods\",\n\t\t\"Content-Type\",\n\t\t\"Set-Cookie\",\n\t\t\"Cookie\",\n\t\t\"X-Login-With\",\n\t\t\"X-Requested-With\",\n\t}, \",\")\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Add(\"Access-Control-Allow-Origin\", r.Header.Get(\"Origin\"))\n\t\tw.Header().Add(\"Access-Control-Allow-Headers\", allowHeaders)\n\t\tw.Header().Add(\"Access-Control-Expose-Headers\", allowHeaders)\n\t\tw.Header().Add(\"Access-Control-Allow-Credentials\", \"true\")\n\t\tw.Header().Add(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, DELETE, OPTIONS\")\n\t\tif r.Method == \"OPTIONS\" {\n\t\t\treturn\n\t\t}\n\t\th.ServeHTTP(w, r)\n\t})\n}", "func cors(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\torigin := r.Header.Get(\"Origin\")\n\t\tif r.Method == \"OPTIONS\" {\n\t\t\tif origin == \"\" {\n\t\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\t\tlog.Error(\"Origin needed for preflight\")\n\t\t\t}\n\t\t\theaders := w.Header()\n\t\t\theaders.Add(\"Access-Control-Allow-Origin\", origin)\n\t\t\theaders.Add(\"Vary\", \"Origin\")\n\t\t\theaders.Add(\"Vary\", \"Access-Control-Request-Method\")\n\t\t\theaders.Add(\"Vary\", \"Access-Control-Request-Headers\")\n\t\t\theaders.Set(\"Access-Control-Allow-Methods\", allowMethods)\n\t\t\theaders.Set(\"Access-Control-Allow-Headers\", strings.Join(allowedHeaders, \", \"))\n\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t} else {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\tw.Header().Set(\"Cache-Control\", \"no-store, no-cache, must-revalidate, post-check=0, pre-check=0\")\n\t\t\tw.Header().Set(\"Access-Control-Expose-Headers\", strings.Join(allowedHeaders, \", \"))\n\t\t\tnext.ServeHTTP(w, r)\n\t\t}\n\t})\n}", "func corsHandler(resWriter http.ResponseWriter, req *http.Request) {\n\tresWriter.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tresWriter.Header().Set(\"Access-Control-Allow-Headers\", \"content-type,authorization\")\n\tresWriter.Header().Set(\"Access-Control-Allow-Methods\", \"OPTIONS,POST\")\n}", "func handleCorsMiddleWare(h http.HandlerFunc) http.HandlerFunc {\n\treturn func(res http.ResponseWriter, req *http.Request) {\n\t\tif origin := req.Header.Get(\"Origin\"); origin != \"\" {\n\t\t\tres.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\tres.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\t\tres.Header().Set(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS, PUT, DELETE\")\n\t\t\tres.Header().Set(\"Access-Control-Allow-Headers\", \"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization\")\n\t\t}\n\n\t\tif strings.ToLower(req.Method) == \"options\" {\n\t\t\tfmt.Println(\"CORS Preflight successful\")\n\t\t\tres.WriteHeader(http.StatusOK)\n\t\t\treturn\n\t\t}\n\t\t// Check if request has basic auth . If not, deny request further access\n\t\tuserid, password, ok := req.BasicAuth()\n\t\tif !ok || userid == \"\" || password == \"\" {\n\t\t\thttp.Error(res, \"401 - unauthorized\", http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\n\t\th.ServeHTTP(res, req)\n\t}\n}", "func CORS(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", corsOrigin)\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS, PUT, DELETE\")\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"X-Requested-With, Content-Type\")\n\t\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\tif r.Method == \"OPTIONS\" {\n\t\t\treturn\n\t\t}\n\t\th.ServeHTTP(w, r)\n\t})\n}", "func HandleCors(h http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tsetHeaders(&w)\n\n\t\tif r.Method == http.MethodOptions {\n\t\t\treturn\n\t\t}\n\n\t\th.ServeHTTP(w, r)\n\t}\n}", "func CORSMiddleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\n\t\tif r.Method == \"OPTIONS\" {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Authorization\")\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func corsPreflight(gcors *CorsAccessControl, lcors *CorsAccessControl, allowedMethods string, w http.ResponseWriter, r *http.Request) error {\n\n\tcors := gcors.Merge(lcors)\n\n\tif origin := r.Header.Get(\"Origin\"); cors != nil && origin != \"\" {\n\t\t// validate origin is in list of acceptable allow-origins\n\t\tallowedOrigin := false\n\t\tallowedOriginExact := false\n\t\tfor _, v := range cors.GetAllowOrigin() {\n\t\t\tif v == origin {\n\t\t\t\tw.Header().Add(\"Access-Control-Allow-Origin\", origin)\n\t\t\t\tallowedOriginExact = true\n\t\t\t\tallowedOrigin = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !allowedOrigin {\n\t\t\tfor _, v := range cors.GetAllowOrigin() {\n\t\t\t\tif v == \"*\" {\n\t\t\t\t\tw.Header().Add(\"Access-Control-Allow-Origin\", v)\n\t\t\t\t\tallowedOrigin = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif !allowedOrigin {\n\t\t\t// other option headers needed\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\tw.Write([]byte(\"\"))\n\t\t\treturn errors.New(\"quick cors end\")\n\n\t\t}\n\n\t\t// if the request includes access-control-request-method\n\t\tif method := r.Header.Get(\"Access-Control-Request-Method\"); method != \"\" {\n\t\t\t// if there are no cors settings for this resource, use the allowedMethods,\n\t\t\t// if there are settings for cors, use those\n\t\t\tresponseMethods := []string{}\n\t\t\tif methods := cors.GetAllowMethods(); len(methods) != 0 {\n\t\t\t\tfor _, x := range methods {\n\t\t\t\t\tif x == method {\n\t\t\t\t\t\tresponseMethods = append(responseMethods, x)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor _, x := range strings.Split(allowedMethods, \", \") {\n\t\t\t\t\tif x == method {\n\t\t\t\t\t\tresponseMethods = append(responseMethods, x)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(responseMethods) > 0 {\n\t\t\t\tw.Header().Add(\"Access-Control-Allow-Methods\", strings.Join(responseMethods, \", \"))\n\t\t\t} else {\n\t\t\t\t// other option headers needed\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t\tw.Write([]byte(\"\"))\n\t\t\t\treturn errors.New(\"quick cors end\")\n\t\t\t}\n\t\t}\n\n\t\t// if allow credentials is allowed on this resource respond with true\n\t\tif allowCredentials := cors.GetAllowCredentials(); allowedOriginExact && allowCredentials {\n\t\t\tw.Header().Add(\"Access-Control-Allow-Credentials\", \"true\")\n\t\t}\n\n\t\tif exposeHeaders := cors.GetExposeHeaders(); len(exposeHeaders) != 0 {\n\t\t\t// if we have expose headers, send them\n\t\t\tw.Header().Add(\"Access-Control-Expose-Headers\", strings.Join(exposeHeaders, \", \"))\n\t\t}\n\t\tif maxAge := cors.GetMaxAge(); maxAge.Seconds() != 0 {\n\t\t\t// optional, if we have a max age, send it\n\t\t\tsec := fmt.Sprint(int64(maxAge.Seconds()))\n\t\t\tw.Header().Add(\"Access-Control-Max-Age\", sec)\n\t\t}\n\n\t\tif header := r.Header.Get(\"Access-Control-Request-Headers\"); header != \"\" {\n\t\t\theader = strings.Replace(header, \" \", \"\", -1)\n\t\t\trequestHeaders := strings.Split(header, \",\")\n\n\t\t\tallowHeaders := cors.GetAllowHeaders()\n\n\t\t\tgoodHeaders := []string{}\n\n\t\t\tfor _, x := range requestHeaders {\n\t\t\t\tfor _, y := range allowHeaders {\n\t\t\t\t\tif strings.ToLower(x) == strings.ToLower(y) {\n\t\t\t\t\t\tgoodHeaders = append(goodHeaders, x)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(goodHeaders) > 0 {\n\t\t\t\tw.Header().Add(\"Access-Control-Allow-Headers\", strings.Join(goodHeaders, \", \"))\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func Cors(h http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"*\")\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With\")\n\t\th(w, r)\n\t}\n}", "func CORS() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Origin\", c.Request.Header.Get(\"Origin\"))\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Headers\", \"Origin, X-Requested-With, Content-Type, Accept, Authorization\")\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Methods\", \"GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH\")\n\n\t\tif c.Request.Method == \"OPTIONS\" {\n\t\t\tc.AbortWithStatus(204)\n\t\t\treturn\n\t\t}\n\t\tc.Next()\n\t}\n}", "func (s *Server) WithCors(next http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t// set CORS-Header to response writer as defined by the api\n\t\tw.Header().Set(accessControlAllowOrigin, strings.Join(s.allowedOrigins, \",\"))\n\t\tw.Header().Set(accessControlAllowMethods, strings.Join(s.allowedMethods, \",\"))\n\t\tw.Header().Set(accessControlAllowHeader, strings.Join(s.allowedHeaders, \",\"))\n\n\t\tif r.Method == \"OPTIONS\" {\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\treturn\n\t\t}\n\t\t// serve next handler\n\t\tnext(w, r)\n\t}\n}", "func CORS(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tnext(w, r)\n}", "func withCORS(fn http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tfn(w, r)\n\t}\n}", "func Cors() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tc.Writer.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\t\tc.Writer.Header().Add(\"Access-Control-Allow-Methods\", \"POST,PUT,DELETE,OPTIONS\")\n\t\tc.Writer.Header().Add(\"Access-Control-Allow-Headers\", \"Content-Type,Authorization\")\n\t\tif strings.ToLower(c.Request.Method) == \"options\" {\n\t\t\t// lib.Log.Notice(\"OPTIONS Request\")\n\t\t\t// ctx.ResponseWriter.WriteHeader(200)\n\t\t\tc.Writer.WriteHeader(200)\n\t\t\tc.Abort()\n\t\t\treturn\n\t\t}\n\t\tc.Next()\n\t}\n}", "func accessControl(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST, OPTIONS, PUT, DELETE, UPDATE, PATCH\")\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Origin, Content-Type, Authorization\")\n\n\t\tif r.Method == \"OPTIONS\" {\n\t\t\treturn\n\t\t}\n\n\t\th.ServeHTTP(w, r)\n\t})\n}", "func Cors(next http.HandlerFunc) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Accept, Content-Type\")\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS, PUT, DELETE, PATCH\")\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func CORS() gin.HandlerFunc {\n\treturn func(context *gin.Context) {\n\t\tcontext.Writer.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\t\tcontext.Writer.Header().Set(\"Access-Control-Max-Age\", \"86400\")\n\t\tcontext.Writer.Header().Set(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS, PUT, DELETE, UPDATE\")\n\t\tcontext.Writer.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With\")\n\t\tcontext.Writer.Header().Set(\"Access-Control-Expose-Headers\", \"Content-Length\")\n\t\tcontext.Writer.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\n\t\tif context.Request.Method == \"OPTIONS\" {\n\t\t\tcontext.AbortWithStatus(200)\n\t\t} else {\n\t\t\tcontext.Next()\n\t\t}\n\t}\n}", "func AllowCORS(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST, GET, PUT, DELETE\")\n\t\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Origin, X-Requested-With, Content-Type, Accept, df-token\")\n\t\thandler.ServeHTTP(w, r)\n\t})\n}", "func (cors *Cors) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, PUT, POST, PATCH, DELETE\")\n\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type, Authorization\")\n\tw.Header().Set(\"Access-Control-Expose-Headers\", \"Authorization\")\n\tw.Header().Set(\"Access-Control-Max-Age\", \"600\")\n\tif r.Method == http.MethodOptions {\n\t\tw.WriteHeader(http.StatusOK)\n\t}\n\tcors.handler.ServeHTTP(w, r)\n}", "func (s defaultServer) enableCors(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"http://localhost:8085\")\n\t\t\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type, X-Csrf-Token\")\n\t\t\th.ServeHTTP(w, r)\n\t\t})\n}", "func (m *GoMiddleware) CORS(next echo.HandlerFunc) echo.HandlerFunc {\n\treturn func(c echo.Context) error {\n\t\tc.Response().Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tc.Response().Header().Set(\"Access-Control-Allow-Methods\", \"DELETE, POST, GET, OPTIONS, PUT\")\n\t\tc.Response().Header().Set(\"Access-Control-Allow-Headers\", \"Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Custom-Header, Upgrade-Insecure-Requests\")\n\t\tc.Response().Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\t// Access-Control-Allow-Credentials\n\t\tif c.Request().Method == \"OPTIONS\" {\n\t\t\treturn c.JSON(http.StatusOK, \"ok\")\n\t\t}\n\n\t\treturn next(c)\n\t}\n}", "func CORSEnabledFunction(w http.ResponseWriter, r *http.Request) {\n\t// Set CORS headers for the preflight request\n\tif r.Method == http.MethodOptions {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST\")\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\t\tw.Header().Set(\"Access-Control-Max-Age\", \"3600\")\n\t\tw.WriteHeader(http.StatusNoContent)\n\t\treturn\n\t}\n\t// Set CORS headers for the main request.\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tfmt.Fprint(w, \"Hello, World!\")\n}", "func CORSMiddleware(origin string, methods ...string) Middleware {\n\treturn func(next http.Handler) http.Handler {\n\t\tfn := func(w http.ResponseWriter, r *http.Request) {\n\n\t\t\tif !stringInSlice(r.Method, methods) {\n\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\thttpp.AddCORSHeaders(w, origin, methods...)\n\t\t\tnext.ServeHTTP(w, r)\n\t\t}\n\n\t\treturn http.HandlerFunc(fn)\n\t}\n}", "func PreflightForCORS(w http.ResponseWriter, r *http.Request, allowHeaders, allowMethods *[]string, allowOrigin string) bool {\n\tif r.Method != http.MethodOptions {\n\t\treturn false\n\t}\n\n\t// When nil specified for allowHeaders, PreflightForCORS sets them as same as client request.\n\theaders := r.Header.Get(\"Access-Control-Request-Headers\")\n\tif allowHeaders != nil {\n\t\theaders = strings.Join(*allowHeaders, \", \")\n\t}\n\n\t// Also when nil specified for allowMethods, PreflightForCORS sets them as same as client request.\n\tmethods := r.Header.Get(\"Access-Control-Request-Method\")\n\tif allowMethods != nil {\n\t\tmethods = strings.Join(*allowMethods, \", \")\n\t}\n\n\tw.Header().Set(\"Access-Control-Allow-Origin\", allowOrigin)\n\tw.Header().Set(\"Access-Control-Allow-Headers\", headers)\n\tw.Header().Set(\"Access-Control-Allow-Methods\", methods)\n\tResponseOK(w)\n\treturn true\n}", "func handleSwaggerOrigin(h goa.Handler) goa.Handler {\n\tspec1 := regexp.MustCompile(\"(localhost|cryptopages.club)\")\n\n\treturn func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {\n\t\torigin := req.Header.Get(\"Origin\")\n\t\tif origin == \"\" {\n\t\t\t// Not a CORS request\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t\tif cors.MatchOrigin(origin, \"*\") {\n\t\t\tctx = goa.WithLogContext(ctx, \"origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"false\")\n\t\t\tif acrm := req.Header.Get(\"Access-Control-Request-Method\"); acrm != \"\" {\n\t\t\t\t// We are handling a preflight request\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, OPTIONS\")\n\t\t\t}\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t\tif cors.MatchOriginRegexp(origin, spec1) {\n\t\t\tctx = goa.WithLogContext(ctx, \"origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\trw.Header().Set(\"Vary\", \"Origin\")\n\t\t\trw.Header().Set(\"Access-Control-Expose-Headers\", \"Authorization\")\n\t\t\trw.Header().Set(\"Access-Control-Max-Age\", \"600\")\n\t\t\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\t\tif acrm := req.Header.Get(\"Access-Control-Request-Method\"); acrm != \"\" {\n\t\t\t\t// We are handling a preflight request\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, PATCH, DELETE\")\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Headers\", \"Authorization, Content-Type\")\n\t\t\t}\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\n\t\treturn h(ctx, rw, req)\n\t}\n}", "func CORSMiddleware(devMode bool, allowedOrigins []string) gin.HandlerFunc {\n\tcorsConfig := cors.DefaultConfig()\n\tif devMode {\n\t\tcorsConfig.AllowAllOrigins = true\n\t\tcorsConfig.AllowCredentials = false\n\t} else if !devMode && len(allowedOrigins) == 0 {\n\t\t// not dev mode, and no specified origins\n\t\t// so we should allow all\n\t\tcorsConfig.AllowAllOrigins = true\n\t\tcorsConfig.AllowOrigins = nil\n\t} else {\n\t\t// configure allowed origins\n\t\tcorsConfig.AllowOrigins = allowedOrigins\n\t}\n\t// allow the DELETE method, allowed methods are now\n\t// DELETE GET POST PUT HEAD\n\tcorsConfig.AddAllowMethods(\"DELETE\")\n\tcorsConfig.AddAllowHeaders(\"cache-control\", \"Authorization\", \"Content-Type\", \"X-Request-ID\")\n\treturn cors.New(corsConfig)\n}", "func preflightHandler(w http.ResponseWriter, r *http.Request, additionalAllowedHeaders ...string) {\n\theaders := []string{\"Content-Type\", \"Accept\", \"Authorization\"}\n\tw.Header().Set(\"Access-Control-Allow-Headers\", strings.Join(append(headers, additionalAllowedHeaders...), \",\"))\n\n\tmethods := []string{\"GET\", \"HEAD\", \"POST\", \"PUT\", \"DELETE\"}\n\n\tw.Header().Set(\"Access-Control-Allow-Methods\", strings.Join(methods, \",\"))\n\tglog.Infof(\"preflight request for %s\", r.URL.Path)\n}", "func handleUserOrigin(h goa.Handler) goa.Handler {\n\treturn func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {\n\t\torigin := req.Header.Get(\"Origin\")\n\t\tif origin == \"\" {\n\t\t\t// Not a CORS request\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t\tif cors.MatchOrigin(origin, \"*\") {\n\t\t\tctx = goa.WithLogContext(ctx, \"origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\t\trw.Header().Set(\"Access-Control-Expose-Headers\", \"Age, Cache-Control, Content-Length, Content-Type, Date, Expires, Host, Keep-Alive, Last-Modified, Location, Server, Status, Strict-Transport-Security\")\n\t\t\trw.Header().Set(\"Access-Control-Max-Age\", \"600\")\n\t\t\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\t\tif acrm := req.Header.Get(\"Access-Control-Request-Method\"); acrm != \"\" {\n\t\t\t\t// We are handling a preflight request\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, PATCH, DELETE\")\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Headers\", \"Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With\")\n\t\t\t}\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\n\t\treturn h(ctx, rw, req)\n\t}\n}", "func Cors(h httprouter.Handle) httprouter.Handle {\n\treturn func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Accept, Content-Type, Authorization\")\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT\")\n\n\t\th(w, r, ps)\n\t}\n}", "func PreflightHandler(w http.ResponseWriter, r *http.Request) {\n headers := []string{\"Content-Type\", \"Accept\", \"Authorization\"}\n w.Header().Set(\"Access-Control-Allow-Headers\", strings.Join(headers, \",\"))\n methods := []string{\"GET\", \"HEAD\", \"POST\", \"PUT\", \"DELETE\"}\n w.Header().Set(\"Access-Control-Allow-Methods\", strings.Join(methods, \",\"))\n glog.Infof(\"preflight request for %s\", r.URL.Path)\n}", "func CorsHandler(w http.ResponseWriter) {\r\n\t// Handle CORS, RMB wildcard needs to change in production\r\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\r\n\tw.Header().Set(\"Access-Control-Allow-Headers\", \"access-control-allow-origin\")\r\n}", "func corsMiddleware(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"GET\")\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Origin, Content-Type\")\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func optionsHandler(ctx apiContext, w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", originAddress)\n\tw.Header().Set(\"Access-Control-Allow-Headers\", supportedHeaders)\n\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", methodsToString(ctx.supportedMethods))\n\tw.WriteHeader(http.StatusOK)\n}", "func handleJsOrigin(h goa.Handler) goa.Handler {\n\n\treturn func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {\n\t\torigin := req.Header.Get(\"Origin\")\n\t\tif origin == \"\" {\n\t\t\t// Not a CORS request\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t\tif cors.MatchOrigin(origin, \"*\") {\n\t\t\tctx = goa.WithLogContext(ctx, \"origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"false\")\n\t\t\tif acrm := req.Header.Get(\"Access-Control-Request-Method\"); acrm != \"\" {\n\t\t\t\t// We are handling a preflight request\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, OPTIONS\")\n\t\t\t}\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t\tif cors.MatchOrigin(origin, \"http://swagger.goa.design\") {\n\t\t\tctx = goa.WithLogContext(ctx, \"origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\trw.Header().Set(\"Vary\", \"Origin\")\n\t\t\trw.Header().Set(\"Access-Control-Max-Age\", \"600\")\n\t\t\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\t\tif acrm := req.Header.Get(\"Access-Control-Request-Method\"); acrm != \"\" {\n\t\t\t\t// We are handling a preflight request\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, PATCH, DELETE\")\n\t\t\t}\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\n\t\treturn h(ctx, rw, req)\n\t}\n}", "func enableCors(w *http.ResponseWriter) {\n\t(*w).Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t(*w).Header().Set(\"Access-Control-Allow-Methods\", \"GET\")\n\t(*w).Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n}", "func (cors *Cors) Filter(c siesta.Context, w http.ResponseWriter, r *http.Request, quit func()) {\n\n\t// Allways add \"Vary:Origin\" header\n\tw.Header().Add(\"Vary\", OriginHeader)\n\n\torigin := r.Header.Get(OriginHeader)\n\n\t// is not cors request, same origin request\n\tif origin == \"\" {\n\t\tc.Set(\"cors\", false)\n\t\treturn\n\t}\n\n\tif !cors.isMethodAllowed(r.Method) {\n\t\tcors.logWrap(\"Filter: Request method %s not allowed\", r.Method)\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\tquit()\n\t\treturn\n\t}\n\n\tif !cors.isOriginAllowed(origin) {\n\t\tcors.logWrap(\"Filter: Origin %s not allowed\", origin)\n\t\tw.WriteHeader(http.StatusForbidden)\n\t\tquit()\n\t\treturn\n\t}\n\n\t// Ok, origin and method are allowed\n\tc.Set(\"cors\", true)\n\tw.Header().Set(AccessControlAllowOrigin, origin)\n\n\t// handle a preflight request\n\tif r.Method == http.MethodOptions {\n\t\tc.Set(\"preflight\", true)\n\t\tcors.preFlightRequest(c, w, r, quit)\n\t\treturn\n\t}\n\n\tif cors.exposeHeader {\n\t\tw.Header().Set(AccessControlExposeHeaders, cors.exposedHeaders)\n\t}\n\n\tif cors.allowCredentials {\n\t\tw.Header().Set(AccessControlAllowCredentials, \"true\")\n\t}\n}", "func EnableCors(w *http.ResponseWriter, r *http.Request) {\n\t(*w).Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n (*w).Header().Set(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS, PUT, DELETE\")\n (*w).Header().Set(\"Access-Control-Allow-Headers\", \"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization\")\n}", "func Cors(f http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"accept, content-type\")\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST\")\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tf(w, r)\n\t}\n}", "func addCORSHeaders(w http.ResponseWriter, r *http.Request) {\n\t// origin := r.Header.Get(\"Origin\")\n\t// for _, o := range cfg.AllowedOrigins {\n\t// \tif origin == o {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", r.Header.Get(\"Origin\"))\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, PUT, POST, DELETE, OPTIONS\")\n\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type,Authorization\")\n\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t// return\n\t// \t}\n\t// }\n}", "func WithCORS(cfg CORSConfig) Middleware {\n\treturn func(next Handler) Handler {\n\t\treturn func(ctx context.Context, req Request) (interface{}, error) {\n\t\t\tallowMethods := strings.Join(cfg.AllowMethods, \",\")\n\t\t\tallowHeaders := strings.Join(cfg.AllowHeaders, \",\")\n\n\t\t\thttpReq := req.HTTPRequest()\n\t\t\torigin := httpReq.Header.Get(HeaderOrigin)\n\t\t\tallowOrigin := getAllowOrigin(origin, cfg)\n\t\t\theader := ResponseHeaderFromCtx(ctx)\n\n\t\t\t// non-OPTIONS requests\n\t\t\tif httpReq.Method != http.MethodOptions {\n\t\t\t\theader.Add(HeaderVary, HeaderOrigin)\n\t\t\t\theader.Set(HeaderAccessControlAllowOrigin, allowOrigin)\n\t\t\t\tif cfg.AllowCredentials {\n\t\t\t\t\theader.Set(HeaderAccessControlAllowCredentials, \"true\")\n\t\t\t\t}\n\t\t\t\treturn next(ctx, req)\n\t\t\t}\n\n\t\t\t// Preflight requests\n\t\t\theader.Add(HeaderVary, HeaderOrigin)\n\t\t\theader.Add(HeaderVary, HeaderAccessControlRequestMethod)\n\t\t\theader.Add(HeaderVary, HeaderAccessControlRequestHeaders)\n\t\t\theader.Set(HeaderAccessControlAllowOrigin, allowOrigin)\n\t\t\theader.Set(HeaderAccessControlAllowMethods, allowMethods)\n\t\t\tif cfg.AllowCredentials {\n\t\t\t\theader.Set(HeaderAccessControlAllowCredentials, \"true\")\n\t\t\t}\n\t\t\tif allowHeaders != \"\" {\n\t\t\t\theader.Set(HeaderAccessControlAllowHeaders, allowHeaders)\n\t\t\t} else {\n\t\t\t\th := httpReq.Header.Get(HeaderAccessControlRequestHeaders)\n\t\t\t\tif h != \"\" {\n\t\t\t\t\theader.Set(HeaderAccessControlAllowHeaders, h)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif cfg.MaxAge > 0 {\n\t\t\t\theader.Set(HeaderAccessControlMaxAge, strconv.Itoa(cfg.MaxAge))\n\t\t\t}\n\n\t\t\treturn nil, nil\n\t\t}\n\t}\n}", "func enableCors(w *http.ResponseWriter) {\n\t// cross origin resource sharing\n\t(*w).Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t//(*w).Header().Set(\"Access-Control-Allow-Origin\", \"http://localhost:8070/products\")\n\t//w.Header().Set(\"Access-Control-Allow-Methods\", \"POST, GET\")\n}", "func handleJsOrigin(h goa.Handler) goa.Handler {\n\tspec1 := regexp.MustCompile(\"(localhost|cryptopages.club)\")\n\n\treturn func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {\n\t\torigin := req.Header.Get(\"Origin\")\n\t\tif origin == \"\" {\n\t\t\t// Not a CORS request\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t\tif cors.MatchOrigin(origin, \"*\") {\n\t\t\tctx = goa.WithLogContext(ctx, \"origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"false\")\n\t\t\tif acrm := req.Header.Get(\"Access-Control-Request-Method\"); acrm != \"\" {\n\t\t\t\t// We are handling a preflight request\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, OPTIONS\")\n\t\t\t}\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t\tif cors.MatchOriginRegexp(origin, spec1) {\n\t\t\tctx = goa.WithLogContext(ctx, \"origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\trw.Header().Set(\"Vary\", \"Origin\")\n\t\t\trw.Header().Set(\"Access-Control-Expose-Headers\", \"Authorization\")\n\t\t\trw.Header().Set(\"Access-Control-Max-Age\", \"600\")\n\t\t\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\t\tif acrm := req.Header.Get(\"Access-Control-Request-Method\"); acrm != \"\" {\n\t\t\t\t// We are handling a preflight request\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, PATCH, DELETE\")\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Headers\", \"Authorization, Content-Type\")\n\t\t\t}\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\n\t\treturn h(ctx, rw, req)\n\t}\n}", "func withCors() adapter {\n\treturn func(h http.Handler) http.Handler {\n\t\tc := cors.New(cors.Options{\n\t\t\tAllowedOrigins: []string{\"http://localhost\"},\n\t\t\tAllowedHeaders: []string{\"\"},\n\t\t\tAllowedMethods: []string{\"GET\", \"POST\", \"PUT\", \"DELETE\"},\n\t\t\tAllowCredentials: true,\n\t\t})\n\t\tc = cors.AllowAll()\n\t\treturn c.Handler(h)\n\t}\n}", "func CORS_Middleware() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tc.Writer.Header().Set(\"Access-Control-Max-Age\", \"86400\")\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS, PUT, DELETE, UPDATE\")\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Headers\", \"X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding, x-access-token\")\n\t\tc.Writer.Header().Set(\"Access-Control-Expose-Headers\", \"Content-Length\")\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t}\n}", "func New(allowOrigins, allowMethods, allowHeaders string, maxAge int, exposedHeaders string, allowCredentials bool, logger *log.Logger) *Cors {\n\tcors := defaultNew()\n\tcors.logger = logger\n\n\t// default all origins\n\tif len(allowOrigins) > 0 && allowOrigins != \"*\" {\n\t\torigins := strings.Split(strings.ToLower(allowOrigins), \",\")\n\n\t\t// now pre-copile pattern for regular expression match\n\t\tfor _, o := range origins {\n\t\t\tp := regexp.QuoteMeta(strings.TrimSpace(o))\n\t\t\tp = strings.Replace(p, \"\\\\*\", \".*\", -1)\n\t\t\tp = strings.Replace(p, \"\\\\?\", \".\", -1)\n\t\t\tr := regexp.MustCompile(p) // compile pattern\n\t\t\tcors.allowedOrigins = append(cors.allowedOrigins, r)\n\t\t}\n\n\t\tcors.allowAllOrigins = false // default is all origins\n\t}\n\n\tif len(allowMethods) > 0 {\n\t\t// TODO: remove duplicated allowed method\n\t\tcors.allowedMethods = strings.Split(strings.ToUpper(allowMethods), \",\")\n\t\tcors.allowedMethodsString = allowMethods\n\t}\n\n\tif len(allowHeaders) > 0 {\n\t\t// TODO: remove duplicated allowed headers\n\t\tcors.allowedHeaders = strings.Split(strings.ToLower(allowHeaders), \",\")\n\t\tcors.allowHeadersString = allowHeaders\n\t}\n\n\tcors.maxAge = strconv.Itoa(maxAge)\n\n\tif len(exposedHeaders) > 0 {\n\t\tcors.exposedHeaders = exposedHeaders\n\t\tcors.exposeHeader = true\n\t}\n\n\tcors.allowCredentials = allowCredentials\n\n\tcors.logWrap(\"cors filter configuration [%s]\", cors)\n\treturn cors\n}", "func (rout *RoutServeMux) CORS(next http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tsetupResponseCORS(&w, r)\n\t\tif (*r).Method == \"OPTIONS\" {\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t}\n}", "func CORSWrap(handler http.Handler) http.Handler {\n\tc := cors.New(cors.Options{\n\t\tAllowedOrigins: []string{\"*\"},\n\t\tAllowedMethods: []string{\"PUT\", \"POST\", \"GET\", \"DELETE\", \"OPTIONS\"},\n\t\tAllowedHeaders: []string{\"*\"},\n\t\tMaxAge: 3200,\n\t\tAllowCredentials: true,\n\t})\n\treturn c.Handler(handler)\n}", "func cors(h httprouter.Handle) httprouter.Handle {\n\treturn func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"accept, content-type\")\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST\")\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\th(w, r, p)\n\t}\n}", "func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif origin := r.Header.Get(\"Origin\"); origin != \"\" {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS, PUT, DELETE\")\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Accept, Accept-Language, Content-Type, YourOwnHeader\")\n\t\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t}\n\t// Stop here if its Preflighted OPTIONS request\n\tif r.Method == \"OPTIONS\" {\n\t\treturn\n\t}\n\tsrv.mux.ServeHTTP(w, r)\n}", "func WideOpenCORS() Adapter {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tif origin := r.Header.Get(\"Origin\"); origin != \"\" {\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS, PUT, DELETE\")\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Headers\",\n\t\t\t\t\t\"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization\")\n\t\t\t}\n\t\t\t// Stop here if its Preflighted OPTIONS request\n\t\t\tif r.Method == \"OPTIONS\" {\n\t\t\t\ttoolsLogger.Print(\"CORS preflight request!\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\th.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func handleSwaggerOrigin(h goa.Handler) goa.Handler {\n\n\treturn func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {\n\t\torigin := req.Header.Get(\"Origin\")\n\t\tif origin == \"\" {\n\t\t\t// Not a CORS request\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t\tif cors.MatchOrigin(origin, \"*\") {\n\t\t\tctx = goa.WithLogContext(ctx, \"origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"false\")\n\t\t\tif acrm := req.Header.Get(\"Access-Control-Request-Method\"); acrm != \"\" {\n\t\t\t\t// We are handling a preflight request\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, OPTIONS\")\n\t\t\t}\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t\tif cors.MatchOrigin(origin, \"http://swagger.goa.design\") {\n\t\t\tctx = goa.WithLogContext(ctx, \"origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\trw.Header().Set(\"Vary\", \"Origin\")\n\t\t\trw.Header().Set(\"Access-Control-Max-Age\", \"600\")\n\t\t\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\t\tif acrm := req.Header.Get(\"Access-Control-Request-Method\"); acrm != \"\" {\n\t\t\t\t// We are handling a preflight request\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, PATCH, DELETE\")\n\t\t\t}\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\n\t\treturn h(ctx, rw, req)\n\t}\n}", "func handlePublicOrigin(h goa.Handler) goa.Handler {\n\n\treturn func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {\n\t\torigin := req.Header.Get(\"Origin\")\n\t\tif origin == \"\" {\n\t\t\t// Not a CORS request\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t\tif cors.MatchOrigin(origin, \"*\") {\n\t\t\tctx = goa.WithLogContext(ctx, \"origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"false\")\n\t\t\tif acrm := req.Header.Get(\"Access-Control-Request-Method\"); acrm != \"\" {\n\t\t\t\t// We are handling a preflight request\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, OPTIONS\")\n\t\t\t}\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t\tif cors.MatchOrigin(origin, \"http://swagger.goa.design\") {\n\t\t\tctx = goa.WithLogContext(ctx, \"origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\trw.Header().Set(\"Vary\", \"Origin\")\n\t\t\trw.Header().Set(\"Access-Control-Max-Age\", \"600\")\n\t\t\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\t\tif acrm := req.Header.Get(\"Access-Control-Request-Method\"); acrm != \"\" {\n\t\t\t\t// We are handling a preflight request\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, PATCH, DELETE\")\n\t\t\t}\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\n\t\treturn h(ctx, rw, req)\n\t}\n}", "func handleCorsPreflight(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\n\tlog.Infof(\"Received [OPTIONS] request to CorsPreFlight: %+v\", r)\n\n\tc := cors.New(REST_CORS_PREFIX, log)\n\tc.HandlePreflight(w, r)\n}", "func Cors() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Headers\", \"Origin, Accept, Content-Type, X-ProxiedEntitiesChain\")\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Methods\", \"POST, OPTIONS, GET, PUT\")\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\n\t\tif c.Request.Method == \"OPTIONS\" {\n\t\t\tc.AbortWithStatus(204)\n\t\t\treturn\n\t\t}\n\n\t\tc.Next()\n\t}\n}", "func Handler(ac *AccessControl) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\taccess := mergeDefaults(ac)\n\t\tif access.AllowCredentials {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\t}\n\t\tif len(access.AllowHeaders) > 0 {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Headers\", strings.Join(access.AllowHeaders, \", \"))\n\t\t}\n\t\tif len(access.AllowMethods) > 0 {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Methods\", strings.Join(access.AllowMethods, \", \"))\n\t\t}\n\t\tif len(access.AllowOrigin) > 0 {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", strings.Join(access.AllowOrigin, \", \"))\n\t\t}\n\t\tif len(access.ExposeHeaders) > 0 {\n\t\t\tw.Header().Set(\"Access-Control-Expose-Headers\", strings.Join(access.ExposeHeaders, \", \"))\n\t\t}\n\t\tif access.MaxAge > 0 {\n\t\t\tw.Header().Set(\"Access-Control-Max-Age\", fmt.Sprintf(\"%v\", access.MaxAge))\n\t\t}\n\t\tfmt.Fprint(w, \"\")\n\t})\n}", "func AllowCORSFrom(h http.Handler, allowedOrigins []string) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif origin := r.Header.Get(\"Origin\"); origin != \"\" {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\tif r.Method == \"OPTIONS\" && r.Header.Get(\"Access-Control-Request-Method\") != \"\" {\n\t\t\t\tfor _, allowedOrigin := range allowedOrigins {\n\t\t\t\t\tif origin == allowedOrigin {\n\t\t\t\t\t\tpreflightHandler(w, r)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\th.ServeHTTP(w, r)\n\t})\n}", "func handleSwaggerOrigin(h goa.Handler) goa.Handler {\n\n\treturn func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {\n\t\torigin := req.Header.Get(\"Origin\")\n\t\tif origin == \"\" {\n\t\t\t// Not a CORS request\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t\tif cors.MatchOrigin(origin, \"*\") {\n\t\t\tctx = goa.WithLogContext(ctx, \"origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"false\")\n\t\t\tif acrm := req.Header.Get(\"Access-Control-Request-Method\"); acrm != \"\" {\n\t\t\t\t// We are handling a preflight request\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Methods\", \"GET\")\n\t\t\t}\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\n\t\treturn h(ctx, rw, req)\n\t}\n}", "func CorsSetup(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer recoverFunc(w, r)\n\t\tif origin := r.Header.Get(\"Origin\"); origin != \"\" {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST, DELETE, OPTIONS\")\n\t\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Accept, Accept-Encoding, Authorization, Content-Length, Content-Type\")\n\t\t\tif r.Method == \"OPTIONS\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t\treturn\n\t})\n}", "func WrapHandlerInCORS(h http.Handler) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, DELETE, OPTIONS\")\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Origin, X-Requested-With, Content-Type, Accept, Authorization\")\n\n\t\tif r.Method == http.MethodOptions && r.Header.Get(\"Access-Control-Request-Method\") != \"\" {\n\t\t\t// Its easiest just to always return a 200 OK for everything. Whether\n\t\t\t// this is technically correct or not is a question, but in the end this\n\t\t\t// is what a lot of other people do (including synapse) and the clients\n\t\t\t// are perfectly happy with it.\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t} else {\n\t\t\th.ServeHTTP(w, r)\n\t\t}\n\t})\n}", "func (s *SidecarApi) optionsHandler(response http.ResponseWriter, req *http.Request) {\n\tresponse.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tresponse.Header().Set(\"Access-Control-Allow-Methods\", \"GET\")\n}", "func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Add(\"Access-Control-Max-Age\", \"2592000\")\n\tw.Header().Add(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, DELETE\")\n\tw.Header().Add(\"Access-Control-Allow-Headers\", \"Origin, X-Requested-With, Content-Type, Accept\")\n\tw.Header().Add(\"X-Influxdb-Version\", h.Version)\n\n\t// If this is a CORS OPTIONS request then send back okie-dokie.\n\tif r.Method == \"OPTIONS\" {\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn\n\t}\n\n\t// Otherwise handle it via pat.\n\th.mux.ServeHTTP(w, r)\n}", "func Cors() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tc.Writer.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\t\tc.Next()\n\t}\n}", "func handleSwaggerOrigin(h goa.Handler) goa.Handler {\n\n\treturn func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {\n\t\torigin := req.Header.Get(\"Origin\")\n\t\tif origin == \"\" {\n\t\t\t// Not a CORS request\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t\tif cors.MatchOrigin(origin, \"*\") {\n\t\t\tctx = goa.WithLogContext(ctx, \"origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"false\")\n\t\t\tif acrm := req.Header.Get(\"Access-Control-Request-Method\"); acrm != \"\" {\n\t\t\t\t// We are handling a preflight request\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, OPTIONS\")\n\t\t\t}\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\n\t\treturn h(ctx, rw, req)\n\t}\n}", "func handleSwaggerOrigin(h goa.Handler) goa.Handler {\n\n\treturn func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {\n\t\torigin := req.Header.Get(\"Origin\")\n\t\tif origin == \"\" {\n\t\t\t// Not a CORS request\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t\tif cors.MatchOrigin(origin, \"*\") {\n\t\t\tctx = goa.WithLogContext(ctx, \"origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"false\")\n\t\t\tif acrm := req.Header.Get(\"Access-Control-Request-Method\"); acrm != \"\" {\n\t\t\t\t// We are handling a preflight request\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST, DELETE, PUT\")\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Headers\", \"x-auth\")\n\t\t\t}\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\n\t\treturn h(ctx, rw, req)\n\t}\n}", "func LoadCORS(r *mux.Router) http.Handler {\n var corsOpts *cors.Cors\n var origins []string\n var headers []string\n var methods []string\n\n origins = []string{\"*\"}\n headers = []string{\"*\"}\n methods = []string{http.MethodGet,\n http.MethodPost,\n http.MethodPut,\n http.MethodPatch,\n http.MethodDelete,\n http.MethodOptions,\n }\n\n corsOpts = cors.New(cors.Options{\n AllowedOrigins: origins,\n AllowedHeaders: headers,\n AllowedMethods: methods,\n })\n\n return corsOpts.Handler(r)\n}", "func handlePublicOrigin(h goa.Handler) goa.Handler {\n\tspec1 := regexp.MustCompile(\"(localhost|cryptopages.club)\")\n\n\treturn func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {\n\t\torigin := req.Header.Get(\"Origin\")\n\t\tif origin == \"\" {\n\t\t\t// Not a CORS request\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t\tif cors.MatchOrigin(origin, \"*\") {\n\t\t\tctx = goa.WithLogContext(ctx, \"origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"false\")\n\t\t\tif acrm := req.Header.Get(\"Access-Control-Request-Method\"); acrm != \"\" {\n\t\t\t\t// We are handling a preflight request\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, OPTIONS\")\n\t\t\t}\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t\tif cors.MatchOriginRegexp(origin, spec1) {\n\t\t\tctx = goa.WithLogContext(ctx, \"origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\trw.Header().Set(\"Vary\", \"Origin\")\n\t\t\trw.Header().Set(\"Access-Control-Expose-Headers\", \"Authorization\")\n\t\t\trw.Header().Set(\"Access-Control-Max-Age\", \"600\")\n\t\t\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\t\tif acrm := req.Header.Get(\"Access-Control-Request-Method\"); acrm != \"\" {\n\t\t\t\t// We are handling a preflight request\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, PATCH, DELETE\")\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Headers\", \"Authorization, Content-Type\")\n\t\t\t}\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\n\t\treturn h(ctx, rw, req)\n\t}\n}", "func OptionsHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST, PUT\")\n\tw.Header().Set(\"Access-Control-Max-Age\", \"120\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Headers\", \"content-type\")\n\tw.WriteHeader(200)\n}", "func enableCors(w *http.ResponseWriter) {\n\t(*w).Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n}", "func enableCors(w *http.ResponseWriter) {\n\t(*w).Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n}", "func (m *GoMiddleware) CORS(ctx iris.Context) {\n\tctx.Header(\"Access-Control-Allow-Origin\", \"*\")\n\tctx.Next()\n}", "func EnableCORSDecorator() Decorator {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS\")\n\t\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Origin,Accept,Content-Type,Authorization\")\n\n\t\t\t// Stop here if its Preflighted OPTIONS request\n\t\t\tif r.Method == \"OPTIONS\" {\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\th.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func CORSMiddleware() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With\")\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Methods\", \"DELETE, GET, OPTIONS, POST, PUT\")\n\n\t\tif c.Request.Method == \"OPTIONS\" {\n\t\t\tc.AbortWithStatus(204)\n\t\t\treturn\n\t\t}\n\n\t\tc.Next()\n\t}\n}", "func handleCouncillorsOrigin(h goa.Handler) goa.Handler {\n\n\treturn func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {\n\t\torigin := req.Header.Get(\"Origin\")\n\t\tif origin == \"\" {\n\t\t\t// Not a CORS request\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\t\tif cors.MatchOrigin(origin, \"*\") {\n\t\t\tctx = goa.WithLogContext(ctx, \"origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\trw.Header().Set(\"Access-Control-Allow-Credentials\", \"false\")\n\t\t\tif acrm := req.Header.Get(\"Access-Control-Request-Method\"); acrm != \"\" {\n\t\t\t\t// We are handling a preflight request\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST, DELETE, PUT\")\n\t\t\t\trw.Header().Set(\"Access-Control-Allow-Headers\", \"x-auth\")\n\t\t\t}\n\t\t\treturn h(ctx, rw, req)\n\t\t}\n\n\t\treturn h(ctx, rw, req)\n\t}\n}", "func (m *Middleware) CORS(next echo.HandlerFunc) echo.HandlerFunc {\n\treturn func(c echo.Context) error {\n\t\tc.Response().Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\treturn next(c)\n\t}\n}", "func AddCORSHandler(r *mux.Router) {\n\tr.Methods(\"OPTIONS\").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\torigin := r.Header.Get(\"Origin\")\n\t\tif origin == \"\" {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tSetAccessControlAllowHeaders(w, r.Header.Get(\"Origin\"))\n\t\tw.WriteHeader(http.StatusOK)\n\t})\n}", "func OptionsHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Add(\"Allow\", http.MethodGet)\n\tw.Header().Add(\"Allow\", http.MethodHead)\n\tw.Header().Add(\"Allow\", http.MethodPost)\n\tw.Header().Add(\"Allow\", http.MethodPut)\n\tw.Header().Add(\"Allow\", http.MethodDelete)\n\tw.Header().Add(\"Allow\", http.MethodOptions)\n\tw.Header().Set(\"Transfer-Encoding\", \"chunked\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.WriteHeader(http.StatusNoContent)\n}", "func CORSMiddleware(h http.Handler) http.Handler {\n\t// List of allowed domains.\n\tallowedOrigins := []string{\n\t\t\"https://rest-ui-dev01.digiapi.pizzahut.com\",\n\t\t\"https://rest-ui-stg01.digiapi.pizzahut.com\",\n\t\t\"https://rest-ui-prod.digiapi.pizzahut.com\",\n\t}\n\n\t// If the env is set to dev allow localhost.\n\t// if os.Getenv(\"ENV\") == \"dev\" {\n\tallowedOrigins = append(allowedOrigins, \"http://localhost:*\")\n\t// }\n\n\t// Configure the cors settings for requests.\n\tc := cors.New(cors.Options{\n\t\tAllowedOrigins: allowedOrigins,\n\t\tAllowCredentials: true,\n\t\tAllowedHeaders: []string{\"*\"},\n\t\tDebug: false,\n\t\tAllowedMethods: []string{\"GET\", \"PUT\", \"POST\", \"DELETE\"},\n\t})\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t// Continue with the middleware chain.\n\t\tc.ServeHTTP(w, r, h.ServeHTTP)\n\t})\n}", "func corsHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tsetCors(w)\n}", "func SetCors(s string) { corsAllow = s }", "func (m *GoMiddleware) CORS() fiber.Handler {\n\treturn cors.New(cors.Config{\n\t\tAllowOrigins: \"*\",\n\t\t//AllowOrigins: \"https://gofiber.io, https://gofiber.net\",\n\t\tAllowHeaders: \"Origin, Content-Type, Accept, Authorization\",\n\t\tAllowMethods: \"GET, HEAD, PUT, PATCH, POST, DELETE\",\n\t})\n}", "func CorsHandler(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tnext.ServeHTTP(w, r)\n\t}\n\n\treturn http.HandlerFunc(fn)\n\n}", "func CORSMiddleware() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With\")\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Methods\", \"POST, OPTIONS, GET, PUT, PATCH, DELETE\")\n\n\t\tif c.Request.Method == \"OPTIONS\" {\n\t\t\tc.AbortWithStatus(204)\n\t\t\treturn\n\t\t}\n\n\t\tc.Next()\n\t}\n}", "func ConfigureCors(res *http.ResponseWriter) {\n\n\t(*res).Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t(*res).Header().Set(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS, PUT, DELETE\")\n\t(*res).Header().Set(\"Access-Control-Allow-Headers\", \"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, username-from-header\")\n}", "func CorsMiddleware(h http.Handler, origins []string, methods []string, headers []string) http.Handler {\n\toriginsOk := handlers.AllowedOrigins(origins)\n\tmethodsOk := handlers.AllowedMethods(methods)\n\theadersOk := handlers.AllowedHeaders(headers)\n\n\treturn handlers.CORS(originsOk, methodsOk, headersOk)(h)\n}", "func CORSMiddleware() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With\")\n\t\tc.Writer.Header().Set(\"Access-Control-Allow-Methods\", \"POST, OPTIONS, GET, PUT, DELETE\")\n\n\t\tif c.Request.Method == \"OPTIONS\" {\n\t\t\tc.AbortWithStatus(204)\n\t\t\treturn\n\t\t}\n\n\t\tc.Next()\n\t}\n}", "func CORSMethodMiddleware(r *Router) MiddlewareFunc {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\t\tallMethods, err := getAllMethodsForRoute(r, req)\n\t\t\tif err == nil {\n\t\t\t\tfor _, v := range allMethods {\n\t\t\t\t\tif v == http.MethodOptions {\n\t\t\t\t\t\tw.Header().Set(\"Access-Control-Allow-Methods\", strings.Join(allMethods, \",\"))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnext.ServeHTTP(w, req)\n\t\t})\n\t}\n}", "func AllowAllCORSFromEverywhere(h http.Handler, additionalAllowedHeaders ...string) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif origin := r.Header.Get(\"Origin\"); origin != \"\" {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\t\tif r.Method == \"OPTIONS\" && r.Header.Get(\"Access-Control-Request-Method\") != \"\" {\n\t\t\t\tpreflightHandler(w, r, additionalAllowedHeaders...)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\th.ServeHTTP(w, r)\n\t})\n}", "func addHeaders(h http.Handler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"Allow-Control-Allow-Origin\", \"*\")\n\t\th.ServeHTTP(w, r)\n\t}\n}", "func ReboundCorsHandler(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", r.Header.Get(\"Origin\"))\n\t\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\tnext.ServeHTTP(w, r)\n\t}\n\n\treturn http.HandlerFunc(fn)\n}", "func Preflight(w http.ResponseWriter, r *http.Request) bool {\n\tif origin := r.Header.Get(\"Origin\"); origin != \"\" {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST, OPTIONS\")\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\",\n\t\t\t\"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization\")\n\t}\n\n\treturn (r.Method == \"OPTIONS\")\n}", "func Handler(origins string) func(http.Handler) http.Handler {\n\tors := strings.Split(origins, \",\")\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tfor _, k := range ors {\n\t\t\t\ts := struct{ domain string }{k} // copy for capturing by the goroutine\n\t\t\t\tif s.domain == r.Header.Get(\"Origin\") || s.domain == \"*\" {\n\t\t\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", s.domain)\n\t\t\t\t\th.ServeHTTP(w, r)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tw.Write([]byte(\"host not allowed\"))\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t})\n\t}\n}" ]
[ "0.76304674", "0.73658764", "0.73056734", "0.7282161", "0.71808046", "0.714095", "0.71343446", "0.7124745", "0.7118615", "0.71138436", "0.7107819", "0.70997053", "0.70225453", "0.700575", "0.70035934", "0.6915656", "0.69056773", "0.6897148", "0.6897042", "0.68887126", "0.6873086", "0.6857339", "0.6844684", "0.683477", "0.68168384", "0.6806353", "0.6790685", "0.6773395", "0.67677873", "0.67456204", "0.6733316", "0.6722641", "0.6721193", "0.6719864", "0.66894597", "0.6679858", "0.66686463", "0.666444", "0.66634154", "0.6660556", "0.66515046", "0.6632685", "0.6626769", "0.6619728", "0.6613577", "0.66051155", "0.66011876", "0.6599344", "0.65932745", "0.6582419", "0.656753", "0.6565347", "0.65600324", "0.65587485", "0.655794", "0.6549039", "0.6548678", "0.6545191", "0.6542044", "0.65370125", "0.65339226", "0.65335804", "0.6532304", "0.6525477", "0.65121657", "0.6510816", "0.6507786", "0.65075725", "0.65073496", "0.6484022", "0.6477632", "0.6470754", "0.64704216", "0.6464671", "0.6464388", "0.646379", "0.645042", "0.645042", "0.6445459", "0.64443827", "0.64018893", "0.63917327", "0.6390506", "0.6371854", "0.6364235", "0.6358171", "0.63579947", "0.63429207", "0.63418347", "0.63338387", "0.6331514", "0.6329103", "0.63262385", "0.63226235", "0.63223743", "0.63202524", "0.631472", "0.63005203", "0.62966156", "0.62895423" ]
0.71452546
5
Opts returns a redisconn.Opts object with the configured options applied.
func (cfg ClientConfig) Opts() redisconn.Opts { opts := redisconn.Opts{} cfg.Options.ApplyOpts(&opts) return opts }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetRedisOpts(driver *dipper.Driver) *Options {\n\tif conn, ok := dipper.GetMapData(driver.Options, \"data.connection\"); ok {\n\t\tdefer delete(conn.(map[string]interface{}), \"Password\")\n\t}\n\tif tls, ok := dipper.GetMapData(driver.Options, \"data.connection.TLS\"); ok {\n\t\tdefer delete(tls.(map[string]interface{}), \"CACerts\")\n\t}\n\n\tif localRedis, ok := os.LookupEnv(\"LOCALREDIS\"); ok && localRedis != \"\" {\n\t\tif opts, e := redis.ParseURL(localRedis); e == nil {\n\t\t\treturn &Options{\n\t\t\t\tOptions: opts,\n\t\t\t}\n\t\t}\n\n\t\treturn &Options{\n\t\t\tOptions: &redis.Options{\n\t\t\t\tAddr: \"127.0.0.1:6379\",\n\t\t\t\tDB: 0,\n\t\t\t},\n\t\t}\n\t}\n\n\topts := &redis.Options{}\n\tif value, ok := driver.GetOptionStr(\"data.connection.Addr\"); ok {\n\t\topts.Addr = value\n\t}\n\tif value, ok := driver.GetOptionStr(\"data.connection.Username\"); ok {\n\t\topts.Username = value\n\t}\n\tif value, ok := driver.GetOptionStr(\"data.connection.Password\"); ok {\n\t\topts.Password = value\n\t}\n\tif DB, ok := driver.GetOptionStr(\"data.connection.DB\"); ok {\n\t\topts.DB = dipper.Must(strconv.Atoi(DB)).(int)\n\t}\n\tif driver.CheckOption(\"data.connection.TLS.Enabled\") {\n\t\topts.TLSConfig = setupTLSConfig(driver)\n\t}\n\n\treturn &Options{\n\t\tOptions: opts,\n\t}\n}", "func (o Opts) ApplyOpts(opts *redisconn.Opts) {\n\n\tif o.DB != nil {\n\t\topts.DB = *o.DB\n\t}\n\tif o.WritePause > 0 {\n\t\topts.WritePause = o.WritePause\n\t}\n\tif o.ReconnectPause > 0 {\n\t\topts.ReconnectPause = o.ReconnectPause\n\t}\n\tif o.TCPKeepAlive > 0 {\n\t\topts.TCPKeepAlive = o.TCPKeepAlive\n\t}\n\to.Timeouts.ApplyOpts(opts)\n}", "func (cfg ClusterConfig) Opts() rediscluster.Opts {\n\topts := rediscluster.Opts{}\n\tcfg.Options.ApplyOpts(&opts.HostOpts)\n\tcfg.Cluster.ApplyOpts(&opts)\n\treturn opts\n}", "func NewOpts() Opts {\n\treturn Opts{\n\t\tBroker: getenv(\"MQTT_TEST_CLIENT_HOST\", \"ssl://mqtt:8883\"),\n\t\tID: getenv(\"MQTT_TEST_CLIENT_ID\", \"test-client\"),\n\t\tSerial: \"1001\",\n\t\tMode: ModeAuto,\n\t\tQoS: 2,\n\t\tRetained: true,\n\t\tSetWill: false,\n\t\tTLS: false,\n\t}\n}", "func (c *conn) Options() *ConnOptions {\n\treturn c.options\n}", "func customizedOption(viper *viper.Viper, rwType RWType) *Options {\n\n\tvar opt = Options{}\n\tletOldEnvSupportViper(viper, rwType)\n\thosts := addrStructure(viper.GetStringSlice(rwType.FmtSuffix(\"REDIS_PORT\")),\n\t\tviper.GetStringSlice(rwType.FmtSuffix(\"REDIS_HOST\")))\n\topt.Type = ClientType(viper.GetString(rwType.FmtSuffix(\"REDIS_TYPE\")))\n\topt.Hosts = hosts\n\topt.ReadOnly = rwType.IsReadOnly()\n\topt.Database = viper.GetInt(rwType.FmtSuffix(\"REDIS_DB_NAME\"))\n\topt.Password = viper.GetString(rwType.FmtSuffix(\"REDIS_DB_PASSWORD\"))\n\topt.KeyPrefix = viper.GetString(rwType.FmtSuffix(\"REDIS_KEY_PREFIX\"))\n\t// various timeout setting\n\topt.DialTimeout = viper.GetDuration(rwType.FmtSuffix(\"REDIS_TIMEOUT\")) * time.Second\n\topt.ReadTimeout = viper.GetDuration(rwType.FmtSuffix(\"REDIS_TIMEOUT\")) * time.Second\n\topt.WriteTimeout = viper.GetDuration(rwType.FmtSuffix(\"REDIS_TIMEOUT\")) * time.Second\n\t// REDIS_MAX_CONNECTIONS\n\topt.PoolSize = viper.GetInt(rwType.FmtSuffix(\"REDIS_MAX_CONNECTIONS\"))\n\topt.PoolTimeout = viper.GetDuration(rwType.FmtSuffix(\"REDIS_TIMEOUT\")) * time.Second\n\topt.IdleTimeout = viper.GetDuration(rwType.FmtSuffix(\"REDIS_TIMEOUT\")) * time.Second\n\topt.IdleCheckFrequency = viper.GetDuration(rwType.FmtSuffix(\"REDIS_TIMEOUT\")) * time.Second\n\topt.TLSConfig = nil\n\treturn &opt\n}", "func (p *P) Options() []gnomock.Option {\n\tp.setDefaults()\n\n\topts := []gnomock.Option{\n\t\tgnomock.WithHealthCheck(p.healthcheck),\n\t\tgnomock.WithEnv(\"DOCKER_INFLUXDB_INIT_MODE=setup\"),\n\t\tgnomock.WithEnv(\"DOCKER_INFLUXDB_INIT_USERNAME=\" + p.Username),\n\t\tgnomock.WithEnv(\"DOCKER_INFLUXDB_INIT_PASSWORD=\" + p.Password),\n\t\tgnomock.WithEnv(\"DOCKER_INFLUXDB_INIT_ORG=\" + p.Org),\n\t\tgnomock.WithEnv(\"DOCKER_INFLUXDB_INIT_BUCKET=\" + p.Bucket),\n\t\tgnomock.WithEnv(\"DOCKER_INFLUXDB_INIT_ADMIN_TOKEN=\" + p.AuthToken),\n\t}\n\n\treturn opts\n}", "func (r Redis) RedisOptions() *redis.Options {\n\treturn &redis.Options{\n\t\tNetwork: \"tcp\",\n\t\tAddr: r.Address,\n\t\tDB: r.DB,\n\t\tUsername: r.Username,\n\t\tPassword: r.Password,\n\t}\n}", "func (t Timeouts) ApplyOpts(opts *redisconn.Opts) {\n\tif t.Dial > 0 {\n\t\topts.DialTimeout = t.Dial\n\t}\n\tif t.IO > 0 {\n\t\topts.IOTimeout = t.IO\n\t}\n}", "func WithRedisOptions(opts *redis.Options) ClientOption {\n\treturn func(cfg *clientConfig) {\n\t\thost, port, err := net.SplitHostPort(opts.Addr)\n\t\tif err != nil {\n\t\t\thost = defaultHost\n\t\t\tport = defaultPort\n\t\t}\n\t\tcfg.host = host\n\t\tcfg.port = port\n\t\tcfg.db = strconv.Itoa(opts.DB)\n\t}\n}", "func NewOpts() TransactionOptions {\n\treturn TransactionOptions{\n\t\tDescription: \"\",\n\t\tCurrency: \"EUR\",\n\t}\n}", "func ClientOpts(clt *resty.Client) BuildOptions {\n\treturn func(client *PluginClient) {\n\t\tclient.client = clt\n\t}\n}", "func (ep *Endpoint) ClientOpts() ([]client.Opt, error) {\n\tvar result []client.Opt\n\tif ep.Host != \"\" {\n\t\thelper, err := connhelper.GetConnectionHelper(ep.Host)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif helper == nil {\n\t\t\ttlsConfig, err := ep.tlsConfig()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresult = append(result,\n\t\t\t\twithHTTPClient(tlsConfig),\n\t\t\t\tclient.WithHost(ep.Host),\n\t\t\t)\n\n\t\t} else {\n\t\t\tresult = append(result,\n\t\t\t\tclient.WithHTTPClient(&http.Client{\n\t\t\t\t\t// No TLS, and no proxy.\n\t\t\t\t\tTransport: &http.Transport{\n\t\t\t\t\t\tDialContext: helper.Dialer,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t\tclient.WithHost(helper.Host),\n\t\t\t\tclient.WithDialContext(helper.Dialer),\n\t\t\t)\n\t\t}\n\t}\n\n\tresult = append(result, client.WithVersionFromEnv(), client.WithAPIVersionNegotiation())\n\treturn result, nil\n}", "func NewWithOpts(options ...Option) *Config {\n\topts := &Options{}\n\n\tfor _, opt := range options {\n\t\topt(opts)\n\t}\n\n\tv := viper.New()\n\tv.AutomaticEnv()\n\tv.SetEnvKeyReplacer(strings.NewReplacer(\"-\", \"_\", \".\", \"_\"))\n\n\tflagSet := new(pflag.FlagSet)\n\n\tc := &Config{\n\t\tKstream: KstreamConfig{},\n\t\tFilament: FilamentConfig{},\n\t\tAPI: APIConfig{},\n\t\tPE: pe.Config{},\n\t\tLog: log.Config{},\n\t\tAggregator: aggregator.Config{},\n\t\tFilters: &Filters{},\n\t\tviper: v,\n\t\tflags: flagSet,\n\t\topts: opts,\n\t}\n\n\tif opts.run || opts.replay {\n\t\taggregator.AddFlags(flagSet)\n\t\tconsole.AddFlags(flagSet)\n\t\tamqp.AddFlags(flagSet)\n\t\telasticsearch.AddFlags(flagSet)\n\t\thttp.AddFlags(flagSet)\n\t\teventlog.AddFlags(flagSet)\n\t\tremovet.AddFlags(flagSet)\n\t\treplacet.AddFlags(flagSet)\n\t\trenamet.AddFlags(flagSet)\n\t\ttrimt.AddFlags(flagSet)\n\t\ttagst.AddFlags(flagSet)\n\t\tmailsender.AddFlags(flagSet)\n\t\tslacksender.AddFlags(flagSet)\n\t\tyara.AddFlags(flagSet)\n\t}\n\n\tif opts.run || opts.capture {\n\t\tpe.AddFlags(flagSet)\n\t}\n\n\tc.addFlags()\n\n\treturn c\n}", "func (w *Websocket) Options() *transport.Options {\n\treturn w.topts\n}", "func TestRedisOptions() *redis.Options {\n\tmr, err := miniredis.Run()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &redis.Options{Addr: mr.Addr()}\n}", "func DialOpts(dialOpts ...grpc.DialOption) ConnectOption {\n\treturn dialOptsOption(dialOpts)\n}", "func (r *root) opts() kivik.Options {\n\treturn r.options\n}", "func (n *natsBroker) Options() broker.Options {\n\treturn n.options\n}", "func (c *Caches) Option() Options {\n\treturn c.options\n}", "func (d *SQLike) Options() *destination.Options {\n\treturn d.options\n}", "func (c *Client) Options() ClientOptions {\n\treturn c.options\n}", "func (c *Container) Options() (*dockertest.RunOptions, error) {\n\n\tstrPort := strconv.Itoa(c.getBrokerPort())\n\tpb := map[docker.Port][]docker.PortBinding{}\n\tpb[docker.Port(fmt.Sprintf(\"%d/tcp\", brokerPort))] = []docker.PortBinding{{\n\t\tHostIP: \"0.0.0.0\",\n\t\tHostPort: strPort,\n\t}}\n\n\tstrPort = strconv.Itoa(c.getClientPort())\n\tpb[docker.Port(fmt.Sprintf(\"%d/tcp\", clientPort))] = []docker.PortBinding{{\n\t\tHostIP: \"0.0.0.0\",\n\t\tHostPort: strPort,\n\t}}\n\n\trepo, tag := c.params.GetRepoTag(\"confluentinc/cp-kafka\", \"5.3.0\")\n\tenv := c.params.MergeEnv([]string{\n\t\t\"KAFKA_BROKER_ID=1\",\n\t\tfmt.Sprintf(\"KAFKA_LISTENERS=\\\"PLAINTEXT://0.0.0.0:%d,BROKER://0.0.0.0:%d\", c.getClientPort(), c.getBrokerPort()),\n\t\t\"KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=\\\"BROKER:PLAINTEXT,PLAINTEXT:PLAINTEXT\\\"\",\n\t\t\"KAFKA_INTER_BROKER_LISTENER_NAME=BROKER\",\n\t\t\"KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1\",\n\t})\n\n\treturn &dockertest.RunOptions{\n\t\tRepository: repo,\n\t\tTag: tag,\n\t\tEnv: env,\n\t\tPortBindings: pb,\n\t}, nil\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"mount_path\":\n\t\t\t\topts.withMountPath = v\n\t\t\tcase \"key_name\":\n\t\t\t\topts.withKeyName = v\n\t\t\tcase \"disable_renewal\":\n\t\t\t\topts.withDisableRenewal = v\n\t\t\tcase \"namespace\":\n\t\t\t\topts.withNamespace = v\n\t\t\tcase \"address\":\n\t\t\t\topts.withAddress = v\n\t\t\tcase \"tls_ca_cert\":\n\t\t\t\topts.withTlsCaCert = v\n\t\t\tcase \"tls_ca_path\":\n\t\t\t\topts.withTlsCaPath = v\n\t\t\tcase \"tls_client_cert\":\n\t\t\t\topts.withTlsClientCert = v\n\t\t\tcase \"tls_client_key\":\n\t\t\t\topts.withTlsClientKey = v\n\t\t\tcase \"tls_server_name\":\n\t\t\t\topts.withTlsServerName = v\n\t\t\tcase \"tls_skip_verify\":\n\t\t\t\tvar err error\n\t\t\t\topts.withTlsSkipVerify, err = strconv.ParseBool(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\tcase \"token\":\n\t\t\t\topts.withToken = v\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func (gs *GenServer) Options() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"chan-size\": 100, // size of channel for regular messages\n\t}\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"key_not_required\":\n\t\t\t\tkeyNotRequired, err := strconv.ParseBool(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\topts.withKeyNotRequired = keyNotRequired\n\t\t\tcase \"user_agent\":\n\t\t\t\topts.withUserAgent = v\n\t\t\tcase \"credentials\":\n\t\t\t\topts.withCredentials = v\n\t\t\tcase \"project\":\n\t\t\t\topts.withProject = v\n\t\t\tcase \"region\":\n\t\t\t\topts.withRegion = v\n\t\t\tcase \"key_ring\":\n\t\t\t\topts.withKeyRing = v\n\t\t\tcase \"crypto_key\":\n\t\t\t\topts.withCryptoKey = v\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func (c *Config) GenerateOpts() (*client.Opts, error) {\n\tif c.A10.Username == \"\" {\n\t\treturn nil, validFail(\"username\", c.A10.Username)\n\t}\n\tif c.A10.Password == \"\" {\n\t\treturn nil, validFail(\"password\", c.A10.Password)\n\t}\n\treturn &c.A10, nil\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tvar err error\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"aead_type\":\n\t\t\t\topts.WithAeadType = wrapping.AeadTypeMap(v)\n\t\t\tcase \"hash_type\":\n\t\t\t\topts.WithHashType = wrapping.HashTypeMap(v)\n\t\t\tcase \"key\":\n\t\t\t\topts.WithKey, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding key value: %w\", err)\n\t\t\t\t}\n\t\t\tcase \"salt\":\n\t\t\t\topts.WithSalt, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding salt value: %w\", err)\n\t\t\t\t}\n\t\t\tcase \"info\":\n\t\t\t\topts.WithInfo, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding info value: %w\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func fromOptions(options []Option) *baseSettings {\n\t// Start from the default options:\n\topts := &baseSettings{\n\t\tconsumerOptions: []consumer.Option{consumer.WithCapabilities(consumer.Capabilities{MutatesData: true})},\n\t}\n\n\tfor _, op := range options {\n\t\top(opts)\n\t}\n\n\treturn opts\n}", "func ReqOpts(hdr http.Header) *toclient.RequestOptions {\n\topts := toclient.NewRequestOptions()\n\topts.Header = hdr\n\treturn &opts\n}", "func WithDBOpts(v struct {\n\tUseTracedDriver bool\n\tTraceOrphans bool\n\tOmitArgs bool\n\tForcedDriverName string\n}) DBOption {\n\treturn DBOptionFunc(func(o *DB) {\n\t\to.opts = v\n\t})\n}", "func (c *Client) GetCfgOpts() (api.Config, error) {\n\tcfg := api.ConfigMap{}\n\n\tcfg.Set(\"DNSList\", c.Cfg.DNSList)\n\tcfg.Set(\"S3Protocol\", c.Cfg.S3Protocol)\n\tcfg.Set(\"AutoHostNetworkInterfaces\", c.Cfg.AutoHostNetworkInterfaces)\n\tcfg.Set(\"UseLayer3Networking\", c.Cfg.UseLayer3Networking)\n\n\treturn cfg, nil\n}", "func GOpts() *GOptions {\n\treturn gOpts\n}", "func WithPoolSize(size int) OptsFunc {\n\treturn func(o *redis.Options) {\n\t\to.PoolSize = size\n\t}\n}", "func (v *Volume) Options() map[string]string {\n\toptions := make(map[string]string)\n\tfor key, value := range v.config.Options {\n\t\toptions[key] = value\n\t}\n\n\treturn options\n}", "func (f *HTTPFrontend) GetOpts() (opts HTTPFrontendOptions) {\n\topts.CopyFrom(&f.opts)\n\treturn\n}", "func DriverOptions() Options {\n\treturn Options{}\n}", "func SetupConnOptions(opts []nats.Option) []nats.Option {\n\ttotalWait := 10 * time.Minute\n\treconnectDelay := time.Second\n\n\topts = append(opts, nats.ReconnectWait(reconnectDelay))\n\topts = append(opts, nats.MaxReconnects(int(totalWait/reconnectDelay)))\n\topts = append(opts, nats.DisconnectHandler(func(nc *nats.Conn) {\n\t\tlogs.LogConf.Debug(\"Disconnected: will attempt reconnects for\", totalWait.Minutes())\n\t}))\n\topts = append(opts, nats.ReconnectHandler(func(nc *nats.Conn) {\n\t\tlogs.LogConf.Info(\"Reconnected [\", nc.ConnectedUrl(), \"]\")\n\t}))\n\topts = append(opts, nats.ClosedHandler(func(nc *nats.Conn) {\n\t\tlogs.LogConf.Exception(\"Exiting, no servers available\")\n\t}))\n\treturn opts\n}", "func WithDialOpts(d ...grpc.DialOption) Option {\n\treturn func(opts *backendOptions) {\n\t\topts.dialOpts = append(opts.dialOpts, d...)\n\t}\n}", "func WithPoolTimeout(timeout time.Duration) OptsFunc {\n\treturn func(o *redis.Options) {\n\t\to.PoolTimeout = timeout\n\t}\n}", "func DefaultOpts() Options {\n\treturn Options{\n\t\tCacheSize: 1024,\n\t\tTTLInterval: time.Second,\n\t\tWriteRetries: 5,\n\t}\n}", "func (o Options) GetNormalConfig() *redis.Options {\n\topts := &redis.Options{\n\t\tAddr: o.Hosts[0],\n\t\tPassword: o.Password,\n\t\tDB: o.Database,\n\t\tMaxRetries: o.MaxRedirects,\n\t\tDialTimeout: o.DialTimeout,\n\t\tReadTimeout: o.ReadTimeout,\n\t\tWriteTimeout: o.WriteTimeout,\n\t\tPoolSize: o.PoolSize,\n\t\tPoolTimeout: o.PoolTimeout,\n\t\tIdleTimeout: o.IdleTimeout,\n\t\tIdleCheckFrequency: o.IdleCheckFrequency,\n\t\tTLSConfig: o.TLSConfig,\n\t}\n\treturn opts\n}", "func (o *CreateOptions) GetDriverOpts() map[string]string {\n\tif o.DriverOpts == nil {\n\t\tvar z map[string]string\n\t\treturn z\n\t}\n\treturn o.DriverOpts\n}", "func (spec Spec) Options() ([]grpc.DialOption, error) {\n\tvar opts []grpc.DialOption\n\n\tif spec.Token == \"\" {\n\t\topts = append(opts, grpc.WithInsecure())\n\t} else {\n\t\ttc, err := transportCredentials()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Annotate(err, \"cannot create transport credentials\")\n\t\t}\n\t\topts = append(opts, grpc.WithTransportCredentials(tc))\n\n\t\trc := rpcCredentials{spec.Token}\n\t\topts = append(opts, grpc.WithPerRPCCredentials(rc))\n\t}\n\n\tif spec.Huge {\n\t\tconst HugeMessageSize = 1 << 32\n\t\topts = append(opts, grpc.WithDefaultCallOptions(\n\t\t\tgrpc.MaxCallRecvMsgSize(HugeMessageSize),\n\t\t\tgrpc.MaxCallSendMsgSize(HugeMessageSize),\n\t\t))\n\t}\n\n\treturn opts, nil\n}", "func (oc *OpusDecoder) Options() Options {\n\treturn oc.options\n}", "func (c *FakeClient) Option(opts ...Option) Interface {\n\tfor _, opt := range opts {\n\t\topt(&c.Opts)\n\t}\n\treturn c\n}", "func RealConnectOptions(connectOpts string) (string, error) {\n\t// list of lowercased versions of all go-sql-driver/mysql special params\n\tignored := map[string]bool{\n\t\t\"allowallfiles\": true, // banned in Dir.InstanceDefaultParams, listed here for sake of completeness\n\t\t\"allowcleartextpasswords\": true,\n\t\t\"allownativepasswords\": true,\n\t\t\"allowoldpasswords\": true,\n\t\t\"charset\": true,\n\t\t\"checkconnliveness\": true, // banned in Dir.InstanceDefaultParams, listed here for sake of completeness\n\t\t\"clientfoundrows\": true, // banned in Dir.InstanceDefaultParams, listed here for sake of completeness\n\t\t\"collation\": true,\n\t\t\"columnswithalias\": true, // banned in Dir.InstanceDefaultParams, listed here for sake of completeness\n\t\t\"interpolateparams\": true, // banned in Dir.InstanceDefaultParams, listed here for sake of completeness\n\t\t\"loc\": true, // banned in Dir.InstanceDefaultParams, listed here for sake of completeness\n\t\t\"maxallowedpacket\": true,\n\t\t\"multistatements\": true, // banned in Dir.InstanceDefaultParams, listed here for sake of completeness\n\t\t\"parsetime\": true, // banned in Dir.InstanceDefaultParams, listed here for sake of completeness\n\t\t\"readtimeout\": true,\n\t\t\"rejectreadonly\": true,\n\t\t\"serverpubkey\": true, // banned in Dir.InstanceDefaultParams, listed here for sake of completeness\n\t\t\"timeout\": true,\n\t\t\"tls\": true,\n\t\t\"writetimeout\": true,\n\t}\n\n\toptions, err := SplitConnectOptions(connectOpts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Iterate through the returned map, and remove any driver-specific options.\n\t// This is done via regular expressions substitution in order to keep the\n\t// string in its original order.\n\tfor name, value := range options {\n\t\tif ignored[strings.ToLower(name)] {\n\t\t\tre, err := regexp.Compile(fmt.Sprintf(`%s=%s(,|$)`, regexp.QuoteMeta(name), regexp.QuoteMeta(value)))\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tconnectOpts = re.ReplaceAllString(connectOpts, \"\")\n\t\t}\n\t}\n\tif len(connectOpts) > 0 && connectOpts[len(connectOpts)-1] == ',' {\n\t\tconnectOpts = connectOpts[0 : len(connectOpts)-1]\n\t}\n\treturn connectOpts, nil\n}", "func (sb ServiceBase) Options() Options {\n\treturn sb.options\n}", "func (o TransitGatewayConnectOutput) Options() TransitGatewayConnectOptionsOutput {\n\treturn o.ApplyT(func(v *TransitGatewayConnect) TransitGatewayConnectOptionsOutput { return v.Options }).(TransitGatewayConnectOptionsOutput)\n}", "func (n *noop) Options() Options {\n\treturn n.opts\n}", "func (c Config) GetGoRedisOptions() *redis.Options {\n\treturn &redis.Options{\n\t\tNetwork: c.Network,\n\t\tAddr: c.Addr,\n\t\tPassword: c.Password,\n\t\tDB: c.DB,\n\t\tMaxRetries: c.MaxRetries,\n\t\tMinRetryBackoff: c.MinRetryBackoff,\n\t\tMaxRetryBackoff: c.MaxRetryBackoff,\n\t\tDialTimeout: c.DialTimeout,\n\t\tReadTimeout: c.ReadTimeout,\n\t\tWriteTimeout: c.WriteTimeout,\n\t\tPoolSize: c.PoolSize,\n\t\tMinIdleConns: c.MinIdleConns,\n\t\tMaxConnAge: c.MaxConnAge,\n\t\tPoolTimeout: c.PoolTimeout,\n\t\tIdleTimeout: c.IdleTimeout,\n\t\tIdleCheckFrequency: c.IdleCheckFrequency,\n\t}\n}", "func WithReadTimeout(timeout time.Duration) OptsFunc {\n\treturn func(o *redis.Options) {\n\t\to.ReadTimeout = timeout\n\t}\n}", "func (cc *Cerberus) Opts() *bridges.Opts {\n\treturn &bridges.Opts{\n\t\tName: \"Cerberus\",\n\t\tLambda: true,\n\t}\n}", "func WithTLS(config *tls.Config) Option {\n\treturn func(r *Redis) {\n\t\tr.server.tlsCfg = config\n\t}\n}", "func (mgr *Manager) Options() map[string]string {\n\treturn mgr.GetOptions()\n}", "func NewOpts(exhaustCount int64) *opts {\n\treturn &opts{exhaustionCount: exhaustCount}\n}", "func newOptions() *Options {\n\topts := &Options{}\n\n\toptions := []Option{\n\t\tWithConcurrency(defaultConcurrency),\n\t\tWithMaxRetries(defaultMaxRetries),\n\t\tWithTTL(defaultTTL),\n\t\tWithTimeout(defaultTimeout),\n\t\tWithRetryIntervals(defaultRetryIntervals),\n\t\tWithInitialize(true),\n\t}\n\n\tfor i := range options {\n\t\toptions[i](opts)\n\t}\n\n\treturn opts\n}", "func Options(url string, opts ...RequestOption) (*Response, error) {\n\treturn DefaultSession.Options(url, opts...)\n}", "func (b *base) Options() []func(Call) error {\n\treturn b.options\n}", "func InitWithOptions(conf interface{}, opts Options) error {\n\tcinfo, err := ParseWithOptions(conf, opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn cinfo.Read()\n}", "func toOptions(in *structs.ActiveData) *Options {\n\tif in == nil {\n\t\treturn nil\n\t}\n\n\topts := &Options{}\n\tfor _, m := range in.Moves {\n\t\tmov := toMove(m)\n\t\tif mov != nil {\n\t\t\topts.Moves = append(opts.Moves, mov)\n\t\t}\n\t}\n\topts.CanMegaEvolve = in.CanMegaEvolve\n\n\tfor _, m := range in.ZMoves {\n\t\tif m == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tmov := toMove(m)\n\t\tif mov != nil {\n\t\t\topts.ZMoves = append(opts.ZMoves, mov)\n\t\t}\n\t}\n\topts.CanZMove = len(opts.ZMoves) > 0\n\n\tfor _, m := range in.Dynamax.Moves {\n\t\tmov := toMove(m)\n\t\tif mov != nil {\n\t\t\topts.DMoves = append(opts.DMoves, mov)\n\t\t}\n\t}\n\topts.CanDynamax = in.CanDynamax\n\n\treturn opts\n}", "func (adpt *DockerRunAdapter) Option() *docker.RunOption {\n\tspec := (*yaml.Option)(adpt)\n\n\topt := docker.RunOption{}\n\topt.AddHost = ExpandColonDelimitedStringListWithEnv(spec.AddHost)\n\topt.Attach = spec.Attach\n\topt.BlkioWeight = spec.BlkioWeight\n\topt.BlkioWeightDevice = ExpandColonDelimitedStringListWithEnv(spec.BlkioWeightDevice)\n\topt.CIDFile = spec.CIDFile\n\topt.CPUPeriod = spec.CPUPeriod\n\topt.CPUQuota = spec.CPUQuota\n\topt.CPURtPeriod = spec.CPURtPeriod\n\topt.CPURtRuntime = spec.CPURtRuntime\n\topt.CPUShares = spec.CPUShares\n\topt.CPUs = spec.CPUs\n\topt.CPUsetCPUs = spec.CPUsetCPUs\n\topt.CPUsetMems = spec.CPUsetMems\n\topt.CapAdd = spec.CapAdd\n\topt.CapDrop = spec.CapDrop\n\topt.CgroupParent = spec.CgroupParent\n\topt.DNS = spec.DNS\n\topt.DNSOption = spec.DNSOption\n\topt.DNSSearch = spec.DNSSearch\n\topt.Detach = spec.Detach\n\topt.DetachKeys = spec.DetachKeys\n\topt.Device = ExpandColonDelimitedStringListWithEnv(spec.Device)\n\topt.DeviceCgroupRule = spec.DeviceCgroupRule\n\topt.DeviceReadBPS = ExpandColonDelimitedStringListWithEnv(spec.DeviceReadBPS)\n\topt.DeviceReadIOPS = ExpandColonDelimitedStringListWithEnv(spec.DeviceReadIOPS)\n\topt.DeviceWriteBPS = ExpandColonDelimitedStringListWithEnv(spec.DeviceWriteBPS)\n\topt.DeviceWriteIOPS = ExpandColonDelimitedStringListWithEnv(spec.DeviceWriteIOPS)\n\topt.DisableContentTrust = spec.DisableContentTrust\n\topt.Domainname = spec.Domainname\n\tif spec.Command != nil {\n\t\topt.Entrypoint = spec.Command\n\t} else {\n\t\topt.Entrypoint = spec.Entrypoint\n\t}\n\topt.Env = ExpandStringKeyMapWithEnv(spec.Env)\n\topt.EnvFile = spec.EnvFile\n\topt.Expose = spec.Expose\n\topt.GroupAdd = spec.GroupAdd\n\topt.HealthCmd = spec.HealthCmd\n\topt.HealthInterval = spec.HealthInterval\n\topt.HealthRetries = spec.HealthRetries\n\topt.HealthStartPeriod = spec.HealthStartPeriod\n\topt.HealthTimeout = spec.HealthTimeout\n\topt.Hostname = spec.Hostname\n\topt.IP = spec.IP\n\topt.IP6 = spec.IP6\n\topt.IPC = spec.IPC\n\topt.Init = spec.Init\n\topt.Interactive = spec.Interactive\n\topt.Isolation = spec.Isolation\n\topt.KernelMemory = spec.KernelMemory\n\topt.Label = ExpandStringKeyMapWithEnv(spec.Label)\n\topt.LabelFile = spec.LabelFile\n\topt.Link = ExpandColonDelimitedStringListWithEnv(spec.Link)\n\topt.LinkLocalIP = spec.LinkLocalIP\n\topt.LogDriver = spec.LogDriver\n\topt.LogOpt = ExpandStringKeyMapWithEnv(spec.LogOpt)\n\topt.MacAddress = spec.MacAddress\n\topt.Memory = spec.Memory\n\topt.MemoryReservation = spec.MemoryReservation\n\topt.MemorySwap = spec.MemorySwap\n\topt.MemorySwappiness = spec.MemorySwappiness\n\topt.Mount = ExpandStringKeyMapWithEnv(spec.Mount)\n\topt.Name = spec.Name\n\topt.Network = spec.Network\n\topt.NetworkAlias = spec.NetworkAlias\n\topt.NoHealthcheck = spec.NoHealthcheck\n\topt.OOMKillDisable = spec.OOMKillDisable\n\topt.OOMScoreAdj = spec.OOMScoreAdj\n\topt.PID = spec.PID\n\topt.PidsLimit = spec.PidsLimit\n\topt.Platform = spec.Platform\n\topt.Privileged = spec.Privileged\n\topt.Publish = spec.Publish\n\topt.PublishAll = spec.PublishAll\n\topt.ReadOnly = spec.ReadOnly\n\topt.Restart = spec.Restart\n\topt.Rm = spec.Rm\n\topt.Runtime = spec.Runtime\n\topt.SecurityOpt = ExpandStringKeyMapWithEnv(spec.SecurityOpt)\n\topt.ShmSize = spec.ShmSize\n\topt.SigProxy = spec.SigProxy\n\topt.StopSignal = spec.StopSignal\n\topt.StopTimeout = spec.StopTimeout\n\topt.StorageOpt = ExpandStringKeyMapWithEnv(spec.StorageOpt)\n\topt.Sysctl = ExpandStringKeyMapWithEnv(spec.Sysctl)\n\topt.TTY = spec.TTY\n\topt.Tmpfs = spec.Tmpfs\n\topt.UTS = spec.UTS\n\topt.Ulimit = ExpandStringKeyMapWithEnv(spec.Ulimit)\n\tif spec.User != nil {\n\t\tuser := ExpandColonDelimitedStringWithEnv(*spec.User)\n\t\topt.User = &user\n\t}\n\topt.Userns = spec.Userns\n\topt.Volume = ExpandColonDelimitedStringListWithEnv(spec.Volume)\n\topt.VolumeDriver = spec.VolumeDriver\n\topt.VolumesFrom = spec.VolumesFrom\n\topt.Workdir = spec.Workdir\n\n\treturn &opt\n}", "func (q *query) Options() QueryOptions {\n\treturn q.opts\n}", "func (req *SelectRequest) Opts(opts SelectOpts) *SelectRequest {\n\treq.opts = opts\n\treturn req\n}", "func (factory DriverFactory) GetOptions() interface{} {\n\treturn factory.Ops\n}", "func (s *svc) Options() router.Options {\n\ts.Lock()\n\topts := s.opts\n\ts.Unlock()\n\n\treturn opts\n}", "func (client *Client) Option(opts ...Option) *Client {\n\tfor _, opt := range opts {\n\t\topt(&client.opts)\n\t}\n\treturn client\n}", "func (a *Autocompleter) SuggestOpts(prefix string, opts SuggestOptions) (ret []Suggestion, err error) {\n\tconn := a.pool.Get()\n\tdefer conn.Close()\n\n\targs, inc := a.Serialize(prefix, opts)\n\tvals, err := redis.Strings(conn.Do(\"FT.SUGGET\", args...))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret = ProcessSugGetVals(vals, inc, opts.WithScores, opts.WithPayloads)\n\n\treturn\n}", "func (h handlerResult) asMetricOpts(repository string) *metricsOpts {\n\treturn &metricsOpts{\n\t\tstatus: h.asStatusOpts(),\n\t\ttimeToDeploy: h.timeToDeploy,\n\t\trepository: repository,\n\t}\n}", "func flagOptions() *options {\n\to := &options{}\n\tflag.IntVar(&o.port, \"port\", 8888, \"Port to listen on.\")\n\tflag.StringVar(&o.gitBinary, \"git-binary\", \"/usr/bin/git\", \"Path to the `git` binary.\")\n\tflag.StringVar(&o.gitReposParentDir, \"git-repos-parent-dir\", \"/git-repo\", \"Path to the parent folder containing all Git repos to serve over HTTP.\")\n\treturn o\n}", "func Options(section string) []string {\n\treturn cfg.Options(section)\n}", "func New(rs *RuleSet) *Opts {\n\topts := Opts{\n\t\trs: rs,\n\t\toptions: make(map[string]bool),\n\t}\n\topts.updateOptions()\n\treturn &opts\n}", "func (j *JSON) Options(o map[string]string) Codec {\n\tjc := j\n\tjc.options = o\n\treturn jc\n}", "func Options(opts ...Option) Option {\n\treturn func(s *Settings) error {\n\t\tfor _, opt := range opts {\n\t\t\tif err := opt(s); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n}", "func Options() *DBOptions {\n\treturn &DBOptions{}\n}", "func (c *Client) GetAuthOpts() (authOpts dockerclient.AuthConfigurations) {\n\tauthOpt := dockerclient.AuthConfiguration{\n\t\tUsername: c.AuthConfig.Username,\n\t\tPassword: c.AuthConfig.Password,\n\t}\n\n\tauthOpts = dockerclient.AuthConfigurations{\n\t\tConfigs: make(map[string]dockerclient.AuthConfiguration),\n\t}\n\tauthOpts.Configs[c.Registry] = authOpt\n\n\treturn authOpts\n}", "func (opts DeleteOptions) toConfig() deleteConfig {\n\tcfg := deleteConfig{}\n\n\tfor _, v := range opts {\n\t\tv(&cfg)\n\t}\n\n\treturn cfg\n}", "func (t *Task) Options() task.Options {\n\treturn *t.opts\n}", "func WithConnOptions(opts ...nats.Option) Option {\n\treturn func(t *Transport) error {\n\t\tfor _, o := range opts {\n\t\t\tt.ConnOptions = append(t.ConnOptions, o)\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func DialOptions(v []grpc.DialOption) Configer {\n\treturn func(c *clientv3.Config) {\n\t\tc.DialOptions = v\n\t}\n}", "func New(opts ...ClientOpt) (*client, error) {\n\t// create new Redis client\n\tc := new(client)\n\n\t// create new fields\n\tc.config = new(config)\n\tc.Redis = new(redis.Client)\n\tc.Options = new(redis.Options)\n\n\t// create new logger for the client\n\t//\n\t// https://pkg.go.dev/github.com/sirupsen/logrus?tab=doc#StandardLogger\n\tlogger := logrus.StandardLogger()\n\n\t// create new logger for the client\n\t//\n\t// https://pkg.go.dev/github.com/sirupsen/logrus?tab=doc#NewEntry\n\tc.Logger = logrus.NewEntry(logger).WithField(\"queue\", c.Driver())\n\n\t// apply all provided configuration options\n\tfor _, opt := range opts {\n\t\terr := opt(c)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// parse the url provided\n\toptions, err := redis.ParseURL(c.config.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create the Redis options from the parsed url\n\tc.Options = options\n\n\t// check if clustering mode is enabled\n\tif c.config.Cluster {\n\t\t// create the Redis cluster client from the options\n\t\tc.Redis = redis.NewFailoverClient(failoverFromOptions(c.Options))\n\t} else {\n\t\t// create the Redis client from the parsed url\n\t\tc.Redis = redis.NewClient(c.Options)\n\t}\n\n\t// ping the queue\n\terr = pingQueue(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}", "func toPgOptions(config DbConfig) *pg.Options {\r\n\treturn &pg.Options{\r\n\t\tAddr: fmt.Sprintf(\"%s:%s\", config.Host, config.Port),\r\n\t\tUser: config.UserName,\r\n\t\tPassword: config.UserPassword,\r\n\t\tDatabase: config.DbName,\r\n\t\tApplicationName: AppName,\r\n\t\tReadTimeout: ReadTimeout,\r\n\t\tWriteTimeout: WriteTimeout,\r\n\t\tPoolSize: PoolSize,\r\n\t\tMinIdleConns: MinIdleConns,\r\n\t}\r\n}", "func (m *MonitorSubscriber) Options() *access.NotificationSubscriptionOptions {\n\treturn m.subscriberOptions\n}", "func (c *Context) Options(key string) map[string]interface{} {\n\ti := c.Config.get(name(c.T), key)\n\to, _ := i.(map[string]interface{})\n\treturn o\n}", "func (o ClusterOpts) ApplyOpts(opts *rediscluster.Opts) {\n\tif o.Name != \"\" {\n\t\topts.Name = o.Name\n\t}\n}", "func (o CrostiniOptions) ChromeOpts() []chrome.Option {\n\treturn []chrome.Option{chrome.ExtraArgs(\"--vmodule=crostini*=1\")}\n}", "func DiscoveryOptions(opt map[string]string) DiscoverOption {\n\treturn func(o *dOpts) {\n\t\to.do = opt\n\t}\n}", "func WithClusterOptions(clusterOptions *ClusterOpts) func(*redisDAL) {\n\treturn func(r *redisDAL) {\n\t\tr.clusterOpts = clusterOptions\n\t}\n}", "func (c *Client) getChunkerOptions(ctx context.Context) (*fastcdc.Options, error) {\n\tparams, err := c.iclient.GetChunkerParams(ctx, &pb.Empty{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &fastcdc.Options{\n\t\tMinSize: int(params.MinChunkSize),\n\t\tAverageSize: int(params.AvgChunkSize),\n\t\tMaxSize: int(params.MaxChunkSize),\n\t\tNormalization: int(params.Normalization),\n\t}, nil\n}", "func NewOptions(opts ...Option) Options {\n\toptions := Options{\n\t\tContext: context.Background(),\n\t\tContentType: DefaultContentType,\n\t\tCodecs: make(map[string]codec.Codec),\n\t\tCallOptions: CallOptions{\n\t\t\tContext: context.Background(),\n\t\t\tBackoff: DefaultBackoff,\n\t\t\tRetry: DefaultRetry,\n\t\t\tRetries: DefaultRetries,\n\t\t\tRequestTimeout: DefaultRequestTimeout,\n\t\t\tDialTimeout: transport.DefaultDialTimeout,\n\t\t},\n\t\tLookup: LookupRoute,\n\t\tPoolSize: DefaultPoolSize,\n\t\tPoolTTL: DefaultPoolTTL,\n\t\tSelector: random.NewSelector(),\n\t\tLogger: logger.DefaultLogger,\n\t\tBroker: broker.DefaultBroker,\n\t\tMeter: meter.DefaultMeter,\n\t\tTracer: tracer.DefaultTracer,\n\t}\n\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\treturn options\n}", "func WithPassword(password string) RedisClientOption {\n\treturn func(rs *RedisStorage) {\n\t\trs.password = password\n\t}\n}", "func NewOptions(iOpts instrument.Options) Options {\n\treturn &options{\n\t\tiOpts: iOpts,\n\t\trwOpts: xio.NewOptions(),\n\t}\n}", "func NewClientWithOpts(ops ...Opt) (*Client, error) {\n\tc := &Client{\n\t\thost: DefaultAgentHost,\n\t\tversion: api.DefaultVersion,\n\t\thttpClient: defaultHTTPClient(),\n\t\tproto: \"tcp\",\n\t\tscheme: \"http\",\n\t}\n\tfor _, op := range ops {\n\t\tif err := op(c); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn c, nil\n}", "func (c *ClientConn) Options(u *base.URL) (*base.Response, error) {\n\terr := c.checkState(map[clientConnState]struct{}{\n\t\tclientConnStateInitial: {},\n\t\tclientConnStatePrePlay: {},\n\t\tclientConnStatePreRecord: {},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := c.Do(&base.Request{\n\t\tMethod: base.Options,\n\t\tURL: u,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif res.StatusCode != base.StatusOK {\n\t\t// since this method is not implemented by every RTSP server,\n\t\t// return only if status code is not 404\n\t\tif res.StatusCode == base.StatusNotFound {\n\t\t\treturn res, nil\n\t\t}\n\t\treturn res, liberrors.ErrClientWrongStatusCode{Code: res.StatusCode, Message: res.StatusMessage}\n\t}\n\n\tc.getParameterSupported = func() bool {\n\t\tpub, ok := res.Header[\"Public\"]\n\t\tif !ok || len(pub) != 1 {\n\t\t\treturn false\n\t\t}\n\n\t\tfor _, m := range strings.Split(pub[0], \",\") {\n\t\t\tif base.Method(m) == base.GetParameter {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}()\n\n\treturn res, nil\n}", "func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*ConnConfig, error) {\n\tconfig, err := pgconn.ParseConfigWithOptions(connString, options.ParseConfigOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstatementCacheCapacity := 512\n\tif s, ok := config.RuntimeParams[\"statement_cache_capacity\"]; ok {\n\t\tdelete(config.RuntimeParams, \"statement_cache_capacity\")\n\t\tn, err := strconv.ParseInt(s, 10, 32)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot parse statement_cache_capacity: %w\", err)\n\t\t}\n\t\tstatementCacheCapacity = int(n)\n\t}\n\n\tdescriptionCacheCapacity := 512\n\tif s, ok := config.RuntimeParams[\"description_cache_capacity\"]; ok {\n\t\tdelete(config.RuntimeParams, \"description_cache_capacity\")\n\t\tn, err := strconv.ParseInt(s, 10, 32)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot parse description_cache_capacity: %w\", err)\n\t\t}\n\t\tdescriptionCacheCapacity = int(n)\n\t}\n\n\tdefaultQueryExecMode := QueryExecModeCacheStatement\n\tif s, ok := config.RuntimeParams[\"default_query_exec_mode\"]; ok {\n\t\tdelete(config.RuntimeParams, \"default_query_exec_mode\")\n\t\tswitch s {\n\t\tcase \"cache_statement\":\n\t\t\tdefaultQueryExecMode = QueryExecModeCacheStatement\n\t\tcase \"cache_describe\":\n\t\t\tdefaultQueryExecMode = QueryExecModeCacheDescribe\n\t\tcase \"describe_exec\":\n\t\t\tdefaultQueryExecMode = QueryExecModeDescribeExec\n\t\tcase \"exec\":\n\t\t\tdefaultQueryExecMode = QueryExecModeExec\n\t\tcase \"simple_protocol\":\n\t\t\tdefaultQueryExecMode = QueryExecModeSimpleProtocol\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"invalid default_query_exec_mode: %s\", s)\n\t\t}\n\t}\n\n\tconnConfig := &ConnConfig{\n\t\tConfig: *config,\n\t\tcreatedByParseConfig: true,\n\t\tStatementCacheCapacity: statementCacheCapacity,\n\t\tDescriptionCacheCapacity: descriptionCacheCapacity,\n\t\tDefaultQueryExecMode: defaultQueryExecMode,\n\t\tconnString: connString,\n\t}\n\n\treturn connConfig, nil\n}", "func WithDB(DB int) RedisClientOption {\n\treturn func(rs *RedisStorage) {\n\t\trs.db = DB\n\t}\n}", "func (b NDPRouterAdvert) Options() NDPOptions {\n\treturn NDPOptions(b[ndpRAOptionsOffset:])\n}", "func (c *Command) Options() map[string]string {\n\toptions := make(map[string]string)\n\tc.Flag.VisitAll(func(f *flag.Flag) {\n\t\tdefaultVal := f.DefValue\n\t\tif len(defaultVal) > 0 {\n\t\t\toptions[f.Name+\"=\"+defaultVal] = f.Usage\n\t\t} else {\n\t\t\toptions[f.Name] = f.Usage\n\t\t}\n\t})\n\treturn options\n}", "func newOptions() *options {\n\treturn &options{\n\t\tlogger: log.NewNopLogger(),\n\t\tclock: clock.New(),\n\t\tcertificateCacheDuration: time.Hour * 24,\n\t}\n}", "func (f destroyFlags) toOptions() *DestroyOptions {\n\treturn &DestroyOptions{\n\t\tName: f.name,\n\t\tNamespace: f.namespace,\n\t\tWait: f.wait,\n\t\tTimeout: f.timeout,\n\t\tDestroyVolumes: f.destroyVolumes,\n\t}\n}" ]
[ "0.69560456", "0.65203357", "0.6464695", "0.60208565", "0.6006148", "0.5755672", "0.5684365", "0.56654674", "0.5618213", "0.55474895", "0.54999447", "0.5461396", "0.5443127", "0.54348564", "0.5417129", "0.5403839", "0.5378627", "0.5340202", "0.53303003", "0.53119975", "0.52790064", "0.526166", "0.5252834", "0.5199802", "0.5180668", "0.5158324", "0.5148363", "0.509073", "0.50532526", "0.5045075", "0.5032252", "0.50231385", "0.50183576", "0.50156385", "0.50026715", "0.49972972", "0.4994592", "0.49903774", "0.49803856", "0.4980093", "0.4970088", "0.4957994", "0.49527076", "0.49504077", "0.49154413", "0.49094644", "0.49004126", "0.48880467", "0.4880945", "0.48726034", "0.48701638", "0.48656613", "0.4860269", "0.48426592", "0.48260927", "0.48253018", "0.482451", "0.4823687", "0.48213887", "0.48065934", "0.4800286", "0.48000553", "0.47915795", "0.4782501", "0.47783083", "0.47670895", "0.476502", "0.47522587", "0.4749502", "0.4748212", "0.47478557", "0.4734543", "0.47322667", "0.4731789", "0.4730132", "0.47177717", "0.47082287", "0.47082043", "0.47055203", "0.47019443", "0.4690764", "0.46720687", "0.46717855", "0.46696323", "0.4669074", "0.4659689", "0.46530065", "0.4629905", "0.46296042", "0.4625627", "0.46206802", "0.46176848", "0.46160537", "0.46127662", "0.46105185", "0.46076348", "0.46022826", "0.45994946", "0.45954064", "0.45876807" ]
0.7253291
0
Opts returns a rediscluster.Opts object with the configured options applied.
func (cfg ClusterConfig) Opts() rediscluster.Opts { opts := rediscluster.Opts{} cfg.Options.ApplyOpts(&opts.HostOpts) cfg.Cluster.ApplyOpts(&opts) return opts }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cfg ClientConfig) Opts() redisconn.Opts {\n\topts := redisconn.Opts{}\n\tcfg.Options.ApplyOpts(&opts)\n\treturn opts\n}", "func GetRedisOpts(driver *dipper.Driver) *Options {\n\tif conn, ok := dipper.GetMapData(driver.Options, \"data.connection\"); ok {\n\t\tdefer delete(conn.(map[string]interface{}), \"Password\")\n\t}\n\tif tls, ok := dipper.GetMapData(driver.Options, \"data.connection.TLS\"); ok {\n\t\tdefer delete(tls.(map[string]interface{}), \"CACerts\")\n\t}\n\n\tif localRedis, ok := os.LookupEnv(\"LOCALREDIS\"); ok && localRedis != \"\" {\n\t\tif opts, e := redis.ParseURL(localRedis); e == nil {\n\t\t\treturn &Options{\n\t\t\t\tOptions: opts,\n\t\t\t}\n\t\t}\n\n\t\treturn &Options{\n\t\t\tOptions: &redis.Options{\n\t\t\t\tAddr: \"127.0.0.1:6379\",\n\t\t\t\tDB: 0,\n\t\t\t},\n\t\t}\n\t}\n\n\topts := &redis.Options{}\n\tif value, ok := driver.GetOptionStr(\"data.connection.Addr\"); ok {\n\t\topts.Addr = value\n\t}\n\tif value, ok := driver.GetOptionStr(\"data.connection.Username\"); ok {\n\t\topts.Username = value\n\t}\n\tif value, ok := driver.GetOptionStr(\"data.connection.Password\"); ok {\n\t\topts.Password = value\n\t}\n\tif DB, ok := driver.GetOptionStr(\"data.connection.DB\"); ok {\n\t\topts.DB = dipper.Must(strconv.Atoi(DB)).(int)\n\t}\n\tif driver.CheckOption(\"data.connection.TLS.Enabled\") {\n\t\topts.TLSConfig = setupTLSConfig(driver)\n\t}\n\n\treturn &Options{\n\t\tOptions: opts,\n\t}\n}", "func NewOpts() Opts {\n\treturn Opts{\n\t\tBroker: getenv(\"MQTT_TEST_CLIENT_HOST\", \"ssl://mqtt:8883\"),\n\t\tID: getenv(\"MQTT_TEST_CLIENT_ID\", \"test-client\"),\n\t\tSerial: \"1001\",\n\t\tMode: ModeAuto,\n\t\tQoS: 2,\n\t\tRetained: true,\n\t\tSetWill: false,\n\t\tTLS: false,\n\t}\n}", "func (d *portworx) GetClusterOpts(n node.Node, options []string) (map[string]string, error) {\n\topts := node.ConnectionOpts{\n\t\tIgnoreError: false,\n\t\tTimeBeforeRetry: defaultRetryInterval,\n\t\tTimeout: defaultTimeout,\n\t}\n\tcmd := fmt.Sprintf(\"%s cluster options list -j json\", d.getPxctlPath(n))\n\tout, err := d.nodeDriver.RunCommand(n, cmd, opts)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get pxctl cluster options on node [%s], Err: %v\", n.Name, err)\n\t}\n\tvar data = map[string]interface{}{}\n\terr = json.Unmarshal([]byte(out), &data)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal pxctl cluster option on node [%s], Err: %v\", n.Name, err)\n\t}\n\tsort.Strings(options)\n\tvar options_map = make(map[string]string)\n\t//Values can be string, array or map\n\tfor key, val := range data {\n\t\tindex := sort.SearchStrings(options, key)\n\t\tif index < len(options) && options[index] == key {\n\t\t\toptions_map[key] = fmt.Sprint(val)\n\t\t}\n\t}\n\t//Make sure required options are available\n\tfor _, option := range options {\n\t\tif _, ok := options_map[option]; !ok {\n\t\t\treturn nil, fmt.Errorf(\"Failed to find option: %v\", option)\n\t\t}\n\t}\n\treturn options_map, nil\n}", "func (r *root) opts() kivik.Options {\n\treturn r.options\n}", "func (o Opts) ApplyOpts(opts *redisconn.Opts) {\n\n\tif o.DB != nil {\n\t\topts.DB = *o.DB\n\t}\n\tif o.WritePause > 0 {\n\t\topts.WritePause = o.WritePause\n\t}\n\tif o.ReconnectPause > 0 {\n\t\topts.ReconnectPause = o.ReconnectPause\n\t}\n\tif o.TCPKeepAlive > 0 {\n\t\topts.TCPKeepAlive = o.TCPKeepAlive\n\t}\n\to.Timeouts.ApplyOpts(opts)\n}", "func (p *P) Options() []gnomock.Option {\n\tp.setDefaults()\n\n\topts := []gnomock.Option{\n\t\tgnomock.WithHealthCheck(p.healthcheck),\n\t\tgnomock.WithEnv(\"DOCKER_INFLUXDB_INIT_MODE=setup\"),\n\t\tgnomock.WithEnv(\"DOCKER_INFLUXDB_INIT_USERNAME=\" + p.Username),\n\t\tgnomock.WithEnv(\"DOCKER_INFLUXDB_INIT_PASSWORD=\" + p.Password),\n\t\tgnomock.WithEnv(\"DOCKER_INFLUXDB_INIT_ORG=\" + p.Org),\n\t\tgnomock.WithEnv(\"DOCKER_INFLUXDB_INIT_BUCKET=\" + p.Bucket),\n\t\tgnomock.WithEnv(\"DOCKER_INFLUXDB_INIT_ADMIN_TOKEN=\" + p.AuthToken),\n\t}\n\n\treturn opts\n}", "func (o ClusterOpts) ApplyOpts(opts *rediscluster.Opts) {\n\tif o.Name != \"\" {\n\t\topts.Name = o.Name\n\t}\n}", "func (c *Caches) Option() Options {\n\treturn c.options\n}", "func customizedOption(viper *viper.Viper, rwType RWType) *Options {\n\n\tvar opt = Options{}\n\tletOldEnvSupportViper(viper, rwType)\n\thosts := addrStructure(viper.GetStringSlice(rwType.FmtSuffix(\"REDIS_PORT\")),\n\t\tviper.GetStringSlice(rwType.FmtSuffix(\"REDIS_HOST\")))\n\topt.Type = ClientType(viper.GetString(rwType.FmtSuffix(\"REDIS_TYPE\")))\n\topt.Hosts = hosts\n\topt.ReadOnly = rwType.IsReadOnly()\n\topt.Database = viper.GetInt(rwType.FmtSuffix(\"REDIS_DB_NAME\"))\n\topt.Password = viper.GetString(rwType.FmtSuffix(\"REDIS_DB_PASSWORD\"))\n\topt.KeyPrefix = viper.GetString(rwType.FmtSuffix(\"REDIS_KEY_PREFIX\"))\n\t// various timeout setting\n\topt.DialTimeout = viper.GetDuration(rwType.FmtSuffix(\"REDIS_TIMEOUT\")) * time.Second\n\topt.ReadTimeout = viper.GetDuration(rwType.FmtSuffix(\"REDIS_TIMEOUT\")) * time.Second\n\topt.WriteTimeout = viper.GetDuration(rwType.FmtSuffix(\"REDIS_TIMEOUT\")) * time.Second\n\t// REDIS_MAX_CONNECTIONS\n\topt.PoolSize = viper.GetInt(rwType.FmtSuffix(\"REDIS_MAX_CONNECTIONS\"))\n\topt.PoolTimeout = viper.GetDuration(rwType.FmtSuffix(\"REDIS_TIMEOUT\")) * time.Second\n\topt.IdleTimeout = viper.GetDuration(rwType.FmtSuffix(\"REDIS_TIMEOUT\")) * time.Second\n\topt.IdleCheckFrequency = viper.GetDuration(rwType.FmtSuffix(\"REDIS_TIMEOUT\")) * time.Second\n\topt.TLSConfig = nil\n\treturn &opt\n}", "func (c *Container) Options() (*dockertest.RunOptions, error) {\n\n\tstrPort := strconv.Itoa(c.getBrokerPort())\n\tpb := map[docker.Port][]docker.PortBinding{}\n\tpb[docker.Port(fmt.Sprintf(\"%d/tcp\", brokerPort))] = []docker.PortBinding{{\n\t\tHostIP: \"0.0.0.0\",\n\t\tHostPort: strPort,\n\t}}\n\n\tstrPort = strconv.Itoa(c.getClientPort())\n\tpb[docker.Port(fmt.Sprintf(\"%d/tcp\", clientPort))] = []docker.PortBinding{{\n\t\tHostIP: \"0.0.0.0\",\n\t\tHostPort: strPort,\n\t}}\n\n\trepo, tag := c.params.GetRepoTag(\"confluentinc/cp-kafka\", \"5.3.0\")\n\tenv := c.params.MergeEnv([]string{\n\t\t\"KAFKA_BROKER_ID=1\",\n\t\tfmt.Sprintf(\"KAFKA_LISTENERS=\\\"PLAINTEXT://0.0.0.0:%d,BROKER://0.0.0.0:%d\", c.getClientPort(), c.getBrokerPort()),\n\t\t\"KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=\\\"BROKER:PLAINTEXT,PLAINTEXT:PLAINTEXT\\\"\",\n\t\t\"KAFKA_INTER_BROKER_LISTENER_NAME=BROKER\",\n\t\t\"KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR=1\",\n\t})\n\n\treturn &dockertest.RunOptions{\n\t\tRepository: repo,\n\t\tTag: tag,\n\t\tEnv: env,\n\t\tPortBindings: pb,\n\t}, nil\n}", "func New(modifyOptions ModifyOptions) Options {\n\toption := Options{\n\t\tSkippedPropagatingAPIs: \"cluster.karmada.io;policy.karmada.io;work.karmada.io\",\n\t\tSecurePort: 8090,\n\t\tClusterStatusUpdateFrequency: metav1.Duration{Duration: 10 * time.Second},\n\t\tClusterLeaseDuration: metav1.Duration{Duration: 10 * time.Second},\n\t\tClusterMonitorPeriod: metav1.Duration{Duration: 10 * time.Second},\n\t\tClusterMonitorGracePeriod: metav1.Duration{Duration: 10 * time.Second},\n\t\tClusterStartupGracePeriod: metav1.Duration{Duration: 10 * time.Second},\n\t}\n\n\tif modifyOptions != nil {\n\t\tmodifyOptions(&option)\n\t}\n\treturn option\n}", "func NewWithOpts(options ...Option) *Config {\n\topts := &Options{}\n\n\tfor _, opt := range options {\n\t\topt(opts)\n\t}\n\n\tv := viper.New()\n\tv.AutomaticEnv()\n\tv.SetEnvKeyReplacer(strings.NewReplacer(\"-\", \"_\", \".\", \"_\"))\n\n\tflagSet := new(pflag.FlagSet)\n\n\tc := &Config{\n\t\tKstream: KstreamConfig{},\n\t\tFilament: FilamentConfig{},\n\t\tAPI: APIConfig{},\n\t\tPE: pe.Config{},\n\t\tLog: log.Config{},\n\t\tAggregator: aggregator.Config{},\n\t\tFilters: &Filters{},\n\t\tviper: v,\n\t\tflags: flagSet,\n\t\topts: opts,\n\t}\n\n\tif opts.run || opts.replay {\n\t\taggregator.AddFlags(flagSet)\n\t\tconsole.AddFlags(flagSet)\n\t\tamqp.AddFlags(flagSet)\n\t\telasticsearch.AddFlags(flagSet)\n\t\thttp.AddFlags(flagSet)\n\t\teventlog.AddFlags(flagSet)\n\t\tremovet.AddFlags(flagSet)\n\t\treplacet.AddFlags(flagSet)\n\t\trenamet.AddFlags(flagSet)\n\t\ttrimt.AddFlags(flagSet)\n\t\ttagst.AddFlags(flagSet)\n\t\tmailsender.AddFlags(flagSet)\n\t\tslacksender.AddFlags(flagSet)\n\t\tyara.AddFlags(flagSet)\n\t}\n\n\tif opts.run || opts.capture {\n\t\tpe.AddFlags(flagSet)\n\t}\n\n\tc.addFlags()\n\n\treturn c\n}", "func NewOpts() TransactionOptions {\n\treturn TransactionOptions{\n\t\tDescription: \"\",\n\t\tCurrency: \"EUR\",\n\t}\n}", "func (n *natsBroker) Options() broker.Options {\n\treturn n.options\n}", "func ClientOpts(clt *resty.Client) BuildOptions {\n\treturn func(client *PluginClient) {\n\t\tclient.client = clt\n\t}\n}", "func (d *DefaultDriver) SetClusterOpts(n node.Node, rtOpts map[string]string) error {\n\treturn &errors.ErrNotSupported{\n\t\tType: \"Function\",\n\t\tOperation: \"SetClusterOpts()\",\n\t}\n}", "func NewOpts(exhaustCount int64) *opts {\n\treturn &opts{exhaustionCount: exhaustCount}\n}", "func (ep *Endpoint) ClientOpts() ([]client.Opt, error) {\n\tvar result []client.Opt\n\tif ep.Host != \"\" {\n\t\thelper, err := connhelper.GetConnectionHelper(ep.Host)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif helper == nil {\n\t\t\ttlsConfig, err := ep.tlsConfig()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresult = append(result,\n\t\t\t\twithHTTPClient(tlsConfig),\n\t\t\t\tclient.WithHost(ep.Host),\n\t\t\t)\n\n\t\t} else {\n\t\t\tresult = append(result,\n\t\t\t\tclient.WithHTTPClient(&http.Client{\n\t\t\t\t\t// No TLS, and no proxy.\n\t\t\t\t\tTransport: &http.Transport{\n\t\t\t\t\t\tDialContext: helper.Dialer,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t\tclient.WithHost(helper.Host),\n\t\t\t\tclient.WithDialContext(helper.Dialer),\n\t\t\t)\n\t\t}\n\t}\n\n\tresult = append(result, client.WithVersionFromEnv(), client.WithAPIVersionNegotiation())\n\treturn result, nil\n}", "func (cc *Cerberus) Opts() *bridges.Opts {\n\treturn &bridges.Opts{\n\t\tName: \"Cerberus\",\n\t\tLambda: true,\n\t}\n}", "func (gs *GenServer) Options() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"chan-size\": 100, // size of channel for regular messages\n\t}\n}", "func (r Redis) RedisOptions() *redis.Options {\n\treturn &redis.Options{\n\t\tNetwork: \"tcp\",\n\t\tAddr: r.Address,\n\t\tDB: r.DB,\n\t\tUsername: r.Username,\n\t\tPassword: r.Password,\n\t}\n}", "func TestRedisOptions() *redis.Options {\n\tmr, err := miniredis.Run()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &redis.Options{Addr: mr.Addr()}\n}", "func WithClusterOptions(clusterOptions *ClusterOpts) func(*redisDAL) {\n\treturn func(r *redisDAL) {\n\t\tr.clusterOpts = clusterOptions\n\t}\n}", "func CfgAuthOpts(cfg *viper.Viper) *shttp.AuthenticationOpts {\n\tusername := cfg.GetString(\"analyzer.auth.cluster.username\")\n\tpassword := cfg.GetString(\"analyzer.auth.cluster.password\")\n\treturn &shttp.AuthenticationOpts{\n\t\tUsername: username,\n\t\tPassword: password,\n\t}\n}", "func (c *Client) GetCfgOpts() (api.Config, error) {\n\tcfg := api.ConfigMap{}\n\n\tcfg.Set(\"DNSList\", c.Cfg.DNSList)\n\tcfg.Set(\"S3Protocol\", c.Cfg.S3Protocol)\n\tcfg.Set(\"AutoHostNetworkInterfaces\", c.Cfg.AutoHostNetworkInterfaces)\n\tcfg.Set(\"UseLayer3Networking\", c.Cfg.UseLayer3Networking)\n\n\treturn cfg, nil\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"mount_path\":\n\t\t\t\topts.withMountPath = v\n\t\t\tcase \"key_name\":\n\t\t\t\topts.withKeyName = v\n\t\t\tcase \"disable_renewal\":\n\t\t\t\topts.withDisableRenewal = v\n\t\t\tcase \"namespace\":\n\t\t\t\topts.withNamespace = v\n\t\t\tcase \"address\":\n\t\t\t\topts.withAddress = v\n\t\t\tcase \"tls_ca_cert\":\n\t\t\t\topts.withTlsCaCert = v\n\t\t\tcase \"tls_ca_path\":\n\t\t\t\topts.withTlsCaPath = v\n\t\t\tcase \"tls_client_cert\":\n\t\t\t\topts.withTlsClientCert = v\n\t\t\tcase \"tls_client_key\":\n\t\t\t\topts.withTlsClientKey = v\n\t\t\tcase \"tls_server_name\":\n\t\t\t\topts.withTlsServerName = v\n\t\t\tcase \"tls_skip_verify\":\n\t\t\t\tvar err error\n\t\t\t\topts.withTlsSkipVerify, err = strconv.ParseBool(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\tcase \"token\":\n\t\t\t\topts.withToken = v\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func (ctrler CtrlDefReactor) GetClusterWatchOptions() *api.ListWatchOptions {\n\tlog.Info(\"GetClusterWatchOptions is not implemented\")\n\topts := &api.ListWatchOptions{}\n\treturn opts\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"key_not_required\":\n\t\t\t\tkeyNotRequired, err := strconv.ParseBool(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\topts.withKeyNotRequired = keyNotRequired\n\t\t\tcase \"user_agent\":\n\t\t\t\topts.withUserAgent = v\n\t\t\tcase \"credentials\":\n\t\t\t\topts.withCredentials = v\n\t\t\tcase \"project\":\n\t\t\t\topts.withProject = v\n\t\t\tcase \"region\":\n\t\t\t\topts.withRegion = v\n\t\t\tcase \"key_ring\":\n\t\t\t\topts.withKeyRing = v\n\t\t\tcase \"crypto_key\":\n\t\t\t\topts.withCryptoKey = v\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func (v *Volume) Options() map[string]string {\n\toptions := make(map[string]string)\n\tfor key, value := range v.config.Options {\n\t\toptions[key] = value\n\t}\n\n\treturn options\n}", "func newOptions() *Options {\n\topts := &Options{}\n\n\toptions := []Option{\n\t\tWithConcurrency(defaultConcurrency),\n\t\tWithMaxRetries(defaultMaxRetries),\n\t\tWithTTL(defaultTTL),\n\t\tWithTimeout(defaultTimeout),\n\t\tWithRetryIntervals(defaultRetryIntervals),\n\t\tWithInitialize(true),\n\t}\n\n\tfor i := range options {\n\t\toptions[i](opts)\n\t}\n\n\treturn opts\n}", "func (c *Config) GenerateOpts() (*client.Opts, error) {\n\tif c.A10.Username == \"\" {\n\t\treturn nil, validFail(\"username\", c.A10.Username)\n\t}\n\tif c.A10.Password == \"\" {\n\t\treturn nil, validFail(\"password\", c.A10.Password)\n\t}\n\treturn &c.A10, nil\n}", "func Options(section string) []string {\n\treturn cfg.Options(section)\n}", "func WithRedisOptions(opts *redis.Options) ClientOption {\n\treturn func(cfg *clientConfig) {\n\t\thost, port, err := net.SplitHostPort(opts.Addr)\n\t\tif err != nil {\n\t\t\thost = defaultHost\n\t\t\tport = defaultPort\n\t\t}\n\t\tcfg.host = host\n\t\tcfg.port = port\n\t\tcfg.db = strconv.Itoa(opts.DB)\n\t}\n}", "func (c *Client) Options() ClientOptions {\n\treturn c.options\n}", "func (factory *Factory) GetClusterOptions(options ...ClusterOption) []ClusterOption {\n\toptions = append(options, WithTLSEnabled)\n\n\tif factory.options.featureOperatorUnifiedImage {\n\t\toptions = append(options, WithUnifiedImage)\n\t}\n\n\tif factory.options.featureOperatorLocalities {\n\t\toptions = append(options, WithLocalitiesForExclusion)\n\t}\n\n\tif factory.options.featureOperatorDNS {\n\t\toptions = append(options, WithDNSEnabled)\n\t}\n\n\treturn options\n}", "func (mgr *Manager) Options() map[string]string {\n\treturn mgr.GetOptions()\n}", "func fromOptions(options []Option) *baseSettings {\n\t// Start from the default options:\n\topts := &baseSettings{\n\t\tconsumerOptions: []consumer.Option{consumer.WithCapabilities(consumer.Capabilities{MutatesData: true})},\n\t}\n\n\tfor _, op := range options {\n\t\top(opts)\n\t}\n\n\treturn opts\n}", "func (n *noop) Options() Options {\n\treturn n.opts\n}", "func getOpts() []htindex.Option {\n\tvar opts []htindex.Option\n\tcfg := &config{}\n\terr := viper.Unmarshal(cfg)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif cfg.Root != \"\" {\n\t\topts = append(opts, htindex.OptRoot(cfg.Root))\n\t}\n\tif cfg.Input != \"\" {\n\t\topts = append(opts, htindex.OptInput(cfg.Input))\n\t}\n\tif cfg.Output != \"\" {\n\t\topts = append(opts, htindex.OptOutput(cfg.Output))\n\t}\n\tif cfg.Jobs > 0 {\n\t\topts = append(opts, htindex.OptJobs(cfg.Jobs))\n\t}\n\tif cfg.WordsAround > 0 {\n\t\topts = append(opts, htindex.OptWordsAround(cfg.WordsAround))\n\t}\n\tif cfg.ProgressNum > 0 {\n\t\topts = append(opts, htindex.OptProgressNum(cfg.ProgressNum))\n\t}\n\treturn opts\n}", "func DiscoveryOptions(opt map[string]string) DiscoverOption {\n\treturn func(o *dOpts) {\n\t\to.do = opt\n\t}\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tvar err error\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"aead_type\":\n\t\t\t\topts.WithAeadType = wrapping.AeadTypeMap(v)\n\t\t\tcase \"hash_type\":\n\t\t\t\topts.WithHashType = wrapping.HashTypeMap(v)\n\t\t\tcase \"key\":\n\t\t\t\topts.WithKey, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding key value: %w\", err)\n\t\t\t\t}\n\t\t\tcase \"salt\":\n\t\t\t\topts.WithSalt, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding salt value: %w\", err)\n\t\t\t\t}\n\t\t\tcase \"info\":\n\t\t\t\topts.WithInfo, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding info value: %w\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func (f destroyFlags) toOptions() *DestroyOptions {\n\treturn &DestroyOptions{\n\t\tName: f.name,\n\t\tNamespace: f.namespace,\n\t\tWait: f.wait,\n\t\tTimeout: f.timeout,\n\t\tDestroyVolumes: f.destroyVolumes,\n\t}\n}", "func DefaultOpts() Options {\n\treturn Options{\n\t\tCacheSize: 1024,\n\t\tTTLInterval: time.Second,\n\t\tWriteRetries: 5,\n\t}\n}", "func (c *conn) Options() *ConnOptions {\n\treturn c.options\n}", "func (f *HTTPFrontend) GetOpts() (opts HTTPFrontendOptions) {\n\topts.CopyFrom(&f.opts)\n\treturn\n}", "func DialOpts(dialOpts ...grpc.DialOption) ConnectOption {\n\treturn dialOptsOption(dialOpts)\n}", "func (w *Websocket) Options() *transport.Options {\n\treturn w.topts\n}", "func NewOptions(chanOpts *tchannel.ChannelOptions) Options {\n\treturn &options{\n\t\tchannelOptions: chanOpts,\n\t\ttchanChannelFn: defaultTChanChannelFn,\n\t\ttchanNodeServerFn: defaultTChanNodeServerFn,\n\t}\n}", "func GOpts() *GOptions {\n\treturn gOpts\n}", "func (s *StanServer) configureClusterOpts() error {\n\topts := s.natsOpts\n\t// If we don't have cluster defined in the configuration\n\t// file and no cluster listen string override, but we do\n\t// have a routes override, we need to report misconfiguration.\n\tif opts.Cluster.ListenStr == \"\" && opts.Cluster.Host == \"\" &&\n\t\topts.Cluster.Port == 0 {\n\t\tif opts.RoutesStr != \"\" {\n\t\t\terr := fmt.Errorf(\"solicited routes require cluster capabilities, e.g. --cluster\")\n\t\t\ts.log.Fatalf(err.Error())\n\t\t\t// Also return error in case server is started from application\n\t\t\t// and no logger has been set.\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\t// If cluster flag override, process it\n\tif opts.Cluster.ListenStr != \"\" {\n\t\tclusterURL, err := url.Parse(opts.Cluster.ListenStr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\th, p, err := net.SplitHostPort(clusterURL.Host)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\topts.Cluster.Host = h\n\t\t_, err = fmt.Sscan(p, &opts.Cluster.Port)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif clusterURL.User != nil {\n\t\t\tpass, hasPassword := clusterURL.User.Password()\n\t\t\tif !hasPassword {\n\t\t\t\treturn fmt.Errorf(\"expected cluster password to be set\")\n\t\t\t}\n\t\t\topts.Cluster.Password = pass\n\n\t\t\tuser := clusterURL.User.Username()\n\t\t\topts.Cluster.Username = user\n\t\t} else {\n\t\t\t// Since we override from flag and there is no user/pwd, make\n\t\t\t// sure we clear what we may have gotten from config file.\n\t\t\topts.Cluster.Username = \"\"\n\t\t\topts.Cluster.Password = \"\"\n\t\t}\n\t}\n\n\t// If we have routes but no config file, fill in here.\n\tif opts.RoutesStr != \"\" && opts.Routes == nil {\n\t\topts.Routes = server.RoutesFromStr(opts.RoutesStr)\n\t}\n\n\treturn nil\n}", "func InitGetOpts(cmd *cobra.Command, args []string) (opts *InitOpts, warns []string, err error) {\n\twarns = make([]string, 0)\n\n\t// Validate cluster name\n\tclusterName, err := GetOneClusterName(cmd, args, true)\n\tif err != nil {\n\t\tif clusterName == \"\" {\n\t\t\treturn nil, warns, err\n\t\t}\n\t\twarns = append(warns, fmt.Sprintf(\"%s. They were replaced and the new cluster name is: %q\", err, clusterName))\n\t}\n\n\t// The `--update` flag will be deprecated and replaced by the `update` command\n\tupdate := false\n\tupdateFlag := cmd.Flags().Lookup(\"update\")\n\tif updateFlag != nil {\n\t\tupdate = updateFlag.Value.String() == \"true\"\n\t}\n\n\t// Validate platform (required unless it's an update)\n\tplatform := cmd.Flags().Lookup(\"platform\").Value.String()\n\tif len(platform) == 0 && !update {\n\t\treturn nil, warns, UserErrorf(\"platform is required\")\n\t}\n\tplatform = strings.ToLower(platform)\n\n\t// The `--path` and `--format` flags are only part of the `kubekit` binary\n\tvar path string\n\tif pathFlag := cmd.Flags().Lookup(\"path\"); pathFlag != nil {\n\t\tpath = pathFlag.Value.String()\n\t}\n\tvar format string\n\tif formatFlag := cmd.Flags().Lookup(\"format\"); formatFlag != nil {\n\t\tformat = formatFlag.Value.String()\n\t}\n\t// TODO: templateName will be used later to create a cluster from a template\n\tvar templateName string\n\tif templateNameFlag := cmd.Flags().Lookup(\"template\"); templateNameFlag != nil {\n\t\ttemplateName = templateNameFlag.Value.String()\n\t}\n\n\t// Variables:\n\tvarsStr := cmd.Flags().Lookup(\"var\").Value.String()\n\tvariables, warnV, errV := GetVariables(varsStr)\n\tif errV != nil {\n\t\treturn nil, warns, err\n\t}\n\tif len(warnV) != 0 {\n\t\twarns = append(warns, warnV...)\n\t}\n\n\t// Credentials:\n\tcreds := GetCredentials(platform, cmd)\n\n\treturn &InitOpts{\n\t\tClusterName: clusterName,\n\t\tPlatform: platform,\n\t\tPath: path,\n\t\tFormat: format,\n\t\tVariables: variables,\n\t\tCredentials: creds,\n\t\tTemplateName: templateName,\n\t\tUpdate: update,\n\t}, warns, nil\n}", "func New(rs *RuleSet) *Opts {\n\topts := Opts{\n\t\trs: rs,\n\t\toptions: make(map[string]bool),\n\t}\n\topts.updateOptions()\n\treturn &opts\n}", "func (spec Spec) Options() ([]grpc.DialOption, error) {\n\tvar opts []grpc.DialOption\n\n\tif spec.Token == \"\" {\n\t\topts = append(opts, grpc.WithInsecure())\n\t} else {\n\t\ttc, err := transportCredentials()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Annotate(err, \"cannot create transport credentials\")\n\t\t}\n\t\topts = append(opts, grpc.WithTransportCredentials(tc))\n\n\t\trc := rpcCredentials{spec.Token}\n\t\topts = append(opts, grpc.WithPerRPCCredentials(rc))\n\t}\n\n\tif spec.Huge {\n\t\tconst HugeMessageSize = 1 << 32\n\t\topts = append(opts, grpc.WithDefaultCallOptions(\n\t\t\tgrpc.MaxCallRecvMsgSize(HugeMessageSize),\n\t\t\tgrpc.MaxCallSendMsgSize(HugeMessageSize),\n\t\t))\n\t}\n\n\treturn opts, nil\n}", "func (c *Component) getTailerOptions(args Arguments) (*kubetail.Options, error) {\n\tif reflect.DeepEqual(c.args.Client, args.Client) && c.lastOptions != nil {\n\t\treturn c.lastOptions, nil\n\t}\n\n\tcfg, err := args.Client.BuildRESTConfig(c.log)\n\tif err != nil {\n\t\treturn c.lastOptions, fmt.Errorf(\"building Kubernetes config: %w\", err)\n\t}\n\tclientSet, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn c.lastOptions, fmt.Errorf(\"building Kubernetes client: %w\", err)\n\t}\n\n\treturn &kubetail.Options{\n\t\tClient: clientSet,\n\t\tHandler: loki.NewEntryHandler(c.handler.Chan(), func() {}),\n\t\tPositions: c.positions,\n\t}, nil\n}", "func (o Options) GetNormalConfig() *redis.Options {\n\topts := &redis.Options{\n\t\tAddr: o.Hosts[0],\n\t\tPassword: o.Password,\n\t\tDB: o.Database,\n\t\tMaxRetries: o.MaxRedirects,\n\t\tDialTimeout: o.DialTimeout,\n\t\tReadTimeout: o.ReadTimeout,\n\t\tWriteTimeout: o.WriteTimeout,\n\t\tPoolSize: o.PoolSize,\n\t\tPoolTimeout: o.PoolTimeout,\n\t\tIdleTimeout: o.IdleTimeout,\n\t\tIdleCheckFrequency: o.IdleCheckFrequency,\n\t\tTLSConfig: o.TLSConfig,\n\t}\n\treturn opts\n}", "func (t Timeouts) ApplyOpts(opts *redisconn.Opts) {\n\tif t.Dial > 0 {\n\t\topts.DialTimeout = t.Dial\n\t}\n\tif t.IO > 0 {\n\t\topts.IOTimeout = t.IO\n\t}\n}", "func (s *svc) Options() router.Options {\n\ts.Lock()\n\topts := s.opts\n\ts.Unlock()\n\n\treturn opts\n}", "func newOptions() *options {\n\treturn &options{\n\t\tlogger: log.NewNopLogger(),\n\t\tclock: clock.New(),\n\t\tcertificateCacheDuration: time.Hour * 24,\n\t}\n}", "func (c *Command) Options() map[string]string {\n\toptions := make(map[string]string)\n\tc.Flag.VisitAll(func(f *flag.Flag) {\n\t\tdefaultVal := f.DefValue\n\t\tif len(defaultVal) > 0 {\n\t\t\toptions[f.Name+\"=\"+defaultVal] = f.Usage\n\t\t} else {\n\t\t\toptions[f.Name] = f.Usage\n\t\t}\n\t})\n\treturn options\n}", "func WithZookeepers(zookeepers []string) SessionOpt {\n\treturn func(so SessionOpts) SessionOpts {\n\t\tso.servers = zookeepers\n\t\treturn so\n\t}\n}", "func (c *FakeClient) Option(opts ...Option) Interface {\n\tfor _, opt := range opts {\n\t\topt(&c.Opts)\n\t}\n\treturn c\n}", "func DeleteGetOpts(cmd *cobra.Command, args []string) (opts *DeleteOpts, warns []string, err error) {\n\twarns = make([]string, 0)\n\n\t// cluster_name\n\tclusterName, err := GetOneClusterName(cmd, args, false)\n\tif err != nil {\n\t\treturn nil, warns, err\n\t}\n\n\t// Get the flags `--all` and `--force`\n\tdestroyAll := false\n\tdestroyAllFlag := cmd.Flags().Lookup(\"all\")\n\tif destroyAllFlag != nil {\n\t\tdestroyAll = destroyAllFlag.Value.String() == \"true\"\n\t}\n\tforce := false\n\tforceFlag := cmd.Flags().Lookup(\"force\")\n\tif forceFlag != nil {\n\t\tforce = forceFlag.Value.String() == \"true\"\n\t}\n\n\topts = &DeleteOpts{\n\t\tClusterName: clusterName,\n\t\tDestroyAll: destroyAll,\n\t\tForce: force,\n\t}\n\n\treturn opts, warns, nil\n}", "func (t *Task) Options() task.Options {\n\treturn *t.opts\n}", "func defaultOptions() interface{} {\n\treturn &options{\n\t\tconfFile: \"\",\n\t\tconfDir: \"/etc/cmk\",\n\t\tcreateNodeLabel: defaultConfig().(*conf).LabelNode,\n\t\tcreateNodeTaint: defaultConfig().(*conf).TaintNode,\n\t}\n}", "func WithPoolSize(size int) OptsFunc {\n\treturn func(o *redis.Options) {\n\t\to.PoolSize = size\n\t}\n}", "func Options(opts ...Option) Option {\n\treturn func(s *Settings) error {\n\t\tfor _, opt := range opts {\n\t\t\tif err := opt(s); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n}", "func (h handlerResult) asMetricOpts(repository string) *metricsOpts {\n\treturn &metricsOpts{\n\t\tstatus: h.asStatusOpts(),\n\t\ttimeToDeploy: h.timeToDeploy,\n\t\trepository: repository,\n\t}\n}", "func NewOptions(opts ...Option) *Options {\n\topt := &Options{\n\t\tHandlerConcurrency: defaultHandlerConcurrency,\n\t\tMaxConcurrencyPerEvent: defaultMaxConcurrencyPerEvent,\n\t\tTimeoutPerEvent: defaultTimeout,\n\t\tPubsubReceiveSettings: pubsub.DefaultReceiveSettings,\n\t}\n\tfor _, o := range opts {\n\t\to(opt)\n\t}\n\tif opt.EventRequester == nil {\n\t\topt.EventRequester = defaultCeClient\n\t}\n\treturn opt\n}", "func (opts DeleteOptions) toConfig() deleteConfig {\n\tcfg := deleteConfig{}\n\n\tfor _, v := range opts {\n\t\tv(&cfg)\n\t}\n\n\treturn cfg\n}", "func ReqOpts(hdr http.Header) *toclient.RequestOptions {\n\topts := toclient.NewRequestOptions()\n\topts.Header = hdr\n\treturn &opts\n}", "func (adpt *DockerRunAdapter) Option() *docker.RunOption {\n\tspec := (*yaml.Option)(adpt)\n\n\topt := docker.RunOption{}\n\topt.AddHost = ExpandColonDelimitedStringListWithEnv(spec.AddHost)\n\topt.Attach = spec.Attach\n\topt.BlkioWeight = spec.BlkioWeight\n\topt.BlkioWeightDevice = ExpandColonDelimitedStringListWithEnv(spec.BlkioWeightDevice)\n\topt.CIDFile = spec.CIDFile\n\topt.CPUPeriod = spec.CPUPeriod\n\topt.CPUQuota = spec.CPUQuota\n\topt.CPURtPeriod = spec.CPURtPeriod\n\topt.CPURtRuntime = spec.CPURtRuntime\n\topt.CPUShares = spec.CPUShares\n\topt.CPUs = spec.CPUs\n\topt.CPUsetCPUs = spec.CPUsetCPUs\n\topt.CPUsetMems = spec.CPUsetMems\n\topt.CapAdd = spec.CapAdd\n\topt.CapDrop = spec.CapDrop\n\topt.CgroupParent = spec.CgroupParent\n\topt.DNS = spec.DNS\n\topt.DNSOption = spec.DNSOption\n\topt.DNSSearch = spec.DNSSearch\n\topt.Detach = spec.Detach\n\topt.DetachKeys = spec.DetachKeys\n\topt.Device = ExpandColonDelimitedStringListWithEnv(spec.Device)\n\topt.DeviceCgroupRule = spec.DeviceCgroupRule\n\topt.DeviceReadBPS = ExpandColonDelimitedStringListWithEnv(spec.DeviceReadBPS)\n\topt.DeviceReadIOPS = ExpandColonDelimitedStringListWithEnv(spec.DeviceReadIOPS)\n\topt.DeviceWriteBPS = ExpandColonDelimitedStringListWithEnv(spec.DeviceWriteBPS)\n\topt.DeviceWriteIOPS = ExpandColonDelimitedStringListWithEnv(spec.DeviceWriteIOPS)\n\topt.DisableContentTrust = spec.DisableContentTrust\n\topt.Domainname = spec.Domainname\n\tif spec.Command != nil {\n\t\topt.Entrypoint = spec.Command\n\t} else {\n\t\topt.Entrypoint = spec.Entrypoint\n\t}\n\topt.Env = ExpandStringKeyMapWithEnv(spec.Env)\n\topt.EnvFile = spec.EnvFile\n\topt.Expose = spec.Expose\n\topt.GroupAdd = spec.GroupAdd\n\topt.HealthCmd = spec.HealthCmd\n\topt.HealthInterval = spec.HealthInterval\n\topt.HealthRetries = spec.HealthRetries\n\topt.HealthStartPeriod = spec.HealthStartPeriod\n\topt.HealthTimeout = spec.HealthTimeout\n\topt.Hostname = spec.Hostname\n\topt.IP = spec.IP\n\topt.IP6 = spec.IP6\n\topt.IPC = spec.IPC\n\topt.Init = spec.Init\n\topt.Interactive = spec.Interactive\n\topt.Isolation = spec.Isolation\n\topt.KernelMemory = spec.KernelMemory\n\topt.Label = ExpandStringKeyMapWithEnv(spec.Label)\n\topt.LabelFile = spec.LabelFile\n\topt.Link = ExpandColonDelimitedStringListWithEnv(spec.Link)\n\topt.LinkLocalIP = spec.LinkLocalIP\n\topt.LogDriver = spec.LogDriver\n\topt.LogOpt = ExpandStringKeyMapWithEnv(spec.LogOpt)\n\topt.MacAddress = spec.MacAddress\n\topt.Memory = spec.Memory\n\topt.MemoryReservation = spec.MemoryReservation\n\topt.MemorySwap = spec.MemorySwap\n\topt.MemorySwappiness = spec.MemorySwappiness\n\topt.Mount = ExpandStringKeyMapWithEnv(spec.Mount)\n\topt.Name = spec.Name\n\topt.Network = spec.Network\n\topt.NetworkAlias = spec.NetworkAlias\n\topt.NoHealthcheck = spec.NoHealthcheck\n\topt.OOMKillDisable = spec.OOMKillDisable\n\topt.OOMScoreAdj = spec.OOMScoreAdj\n\topt.PID = spec.PID\n\topt.PidsLimit = spec.PidsLimit\n\topt.Platform = spec.Platform\n\topt.Privileged = spec.Privileged\n\topt.Publish = spec.Publish\n\topt.PublishAll = spec.PublishAll\n\topt.ReadOnly = spec.ReadOnly\n\topt.Restart = spec.Restart\n\topt.Rm = spec.Rm\n\topt.Runtime = spec.Runtime\n\topt.SecurityOpt = ExpandStringKeyMapWithEnv(spec.SecurityOpt)\n\topt.ShmSize = spec.ShmSize\n\topt.SigProxy = spec.SigProxy\n\topt.StopSignal = spec.StopSignal\n\topt.StopTimeout = spec.StopTimeout\n\topt.StorageOpt = ExpandStringKeyMapWithEnv(spec.StorageOpt)\n\topt.Sysctl = ExpandStringKeyMapWithEnv(spec.Sysctl)\n\topt.TTY = spec.TTY\n\topt.Tmpfs = spec.Tmpfs\n\topt.UTS = spec.UTS\n\topt.Ulimit = ExpandStringKeyMapWithEnv(spec.Ulimit)\n\tif spec.User != nil {\n\t\tuser := ExpandColonDelimitedStringWithEnv(*spec.User)\n\t\topt.User = &user\n\t}\n\topt.Userns = spec.Userns\n\topt.Volume = ExpandColonDelimitedStringListWithEnv(spec.Volume)\n\topt.VolumeDriver = spec.VolumeDriver\n\topt.VolumesFrom = spec.VolumesFrom\n\topt.Workdir = spec.Workdir\n\n\treturn &opt\n}", "func (p *Tmpfs) Options() map[string]types.Option {\n\treturn map[string]types.Option{\n\t\t\"ids\": {Value: \"\", Desc: \"tmpfs volume user's ids\"},\n\t\t\"reqID\": {Value: \"\", Desc: \"create tmpfs volume request id\"},\n\t\t\"freeTime\": {Value: \"\", Desc: \"tmpfs volume free time\"},\n\t}\n}", "func WithPoolTimeout(timeout time.Duration) OptsFunc {\n\treturn func(o *redis.Options) {\n\t\to.PoolTimeout = timeout\n\t}\n}", "func NewClusterOptions() *ClusterOpts {\n\treturn &ClusterOpts{\n\t\tMinIdleConnections: defaultMinIdleConnections,\n\t\tConnectionIdleTimeout: defaultIdleTimeout,\n\t\tMaxActiveConnections: defaultMaxActiveConnections,\n\t}\n}", "func DefaultOpts() Opts {\n\treturn Opts{\n\t\tMinRunInterval: MinRunInterval,\n\t\tMaxTimeout: MaxTimeout,\n\n\t\tDefaultRunInterval: DefaultRunInterval,\n\t\tDefaultTimeout: DefaultTimeout,\n\n\t\tMaxCheckParallelism: MaxCheckParallelism,\n\t}\n}", "func (o CrostiniOptions) ChromeOpts() []chrome.Option {\n\treturn []chrome.Option{chrome.ExtraArgs(\"--vmodule=crostini*=1\")}\n}", "func (c *Client) getChunkerOptions(ctx context.Context) (*fastcdc.Options, error) {\n\tparams, err := c.iclient.GetChunkerParams(ctx, &pb.Empty{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &fastcdc.Options{\n\t\tMinSize: int(params.MinChunkSize),\n\t\tAverageSize: int(params.AvgChunkSize),\n\t\tMaxSize: int(params.MaxChunkSize),\n\t\tNormalization: int(params.Normalization),\n\t}, nil\n}", "func (sb ServiceBase) Options() Options {\n\treturn sb.options\n}", "func (o StorageClusterSpecCloudStorageCapacitySpecsOutput) Options() pulumi.MapOutput {\n\treturn o.ApplyT(func(v StorageClusterSpecCloudStorageCapacitySpecs) map[string]interface{} { return v.Options }).(pulumi.MapOutput)\n}", "func NewOptions(opts ...Option) Options {\n\toptions := Options{\n\t\tContext: context.Background(),\n\t\tContentType: DefaultContentType,\n\t\tCodecs: make(map[string]codec.Codec),\n\t\tCallOptions: CallOptions{\n\t\t\tContext: context.Background(),\n\t\t\tBackoff: DefaultBackoff,\n\t\t\tRetry: DefaultRetry,\n\t\t\tRetries: DefaultRetries,\n\t\t\tRequestTimeout: DefaultRequestTimeout,\n\t\t\tDialTimeout: transport.DefaultDialTimeout,\n\t\t},\n\t\tLookup: LookupRoute,\n\t\tPoolSize: DefaultPoolSize,\n\t\tPoolTTL: DefaultPoolTTL,\n\t\tSelector: random.NewSelector(),\n\t\tLogger: logger.DefaultLogger,\n\t\tBroker: broker.DefaultBroker,\n\t\tMeter: meter.DefaultMeter,\n\t\tTracer: tracer.DefaultTracer,\n\t}\n\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\treturn options\n}", "func loadConfigOpts(cliOpts *cliOptions, host string) (\n\tconfig configuration, err error) {\n\n\tconfig = newConfiguration()\n\n\tif err := config.setPath(cliOpts.ConfigPath); err != nil {\n\t\treturn config, errors.WithMessage(err, \"set path\")\n\t}\n\n\tif err := config.loadConfig(); err != nil {\n\t\treturn config, errors.WithMessagef(err, \"loading %s\", config.Path)\n\t}\n\tlog.Debugf(\"DAOS config read from %s\", config.Path)\n\n\t// Override certificate support if specified in cliOpts\n\tif cliOpts.Insecure {\n\t\tconfig.TransportConfig.AllowInsecure = true\n\t}\n\n\t// get unique identifier to activate SPDK multiprocess mode\n\tconfig.NvmeShmID = hash(host + strconv.Itoa(os.Getpid()))\n\n\tif err = config.getIOParams(cliOpts); err != nil {\n\t\treturn config, errors.Wrap(\n\t\t\terr, \"failed to retrieve I/O service params\")\n\t}\n\n\tif len(config.Servers) == 0 {\n\t\treturn config, errors.New(\"missing I/O service params\")\n\t}\n\n\tfor idx := range config.Servers {\n\t\tconfig.Servers[idx].Hostname = host\n\t}\n\n\treturn config, nil\n}", "func toOptions(in *structs.ActiveData) *Options {\n\tif in == nil {\n\t\treturn nil\n\t}\n\n\topts := &Options{}\n\tfor _, m := range in.Moves {\n\t\tmov := toMove(m)\n\t\tif mov != nil {\n\t\t\topts.Moves = append(opts.Moves, mov)\n\t\t}\n\t}\n\topts.CanMegaEvolve = in.CanMegaEvolve\n\n\tfor _, m := range in.ZMoves {\n\t\tif m == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tmov := toMove(m)\n\t\tif mov != nil {\n\t\t\topts.ZMoves = append(opts.ZMoves, mov)\n\t\t}\n\t}\n\topts.CanZMove = len(opts.ZMoves) > 0\n\n\tfor _, m := range in.Dynamax.Moves {\n\t\tmov := toMove(m)\n\t\tif mov != nil {\n\t\t\topts.DMoves = append(opts.DMoves, mov)\n\t\t}\n\t}\n\topts.CanDynamax = in.CanDynamax\n\n\treturn opts\n}", "func (client *Client) Option(opts ...Option) *Client {\n\tfor _, opt := range opts {\n\t\topt(&client.opts)\n\t}\n\treturn client\n}", "func (k *kubernetes) Init(opts ...runtime.Option) error {\n\tk.Lock()\n\tdefer k.Unlock()\n\n\tfor _, o := range opts {\n\t\to(&k.options)\n\t}\n\n\treturn nil\n}", "func (d *SQLike) Options() *destination.Options {\n\treturn d.options\n}", "func (opts CreateOptions) toConfig() createConfig {\n\tcfg := createConfig{}\n\n\tfor _, v := range opts {\n\t\tv(&cfg)\n\t}\n\n\treturn cfg\n}", "func (opts CreateOptions) toConfig() createConfig {\n\tcfg := createConfig{}\n\n\tfor _, v := range opts {\n\t\tv(&cfg)\n\t}\n\n\treturn cfg\n}", "func NewOptions(instrumentOpts instrument.Options) Options {\n\treturn Options{\n\t\tHasExpensiveAggregations: defaultHasExpensiveAggregations,\n\t\tMetrics: NewMetrics(instrumentOpts.MetricsScope()),\n\t}\n}", "func (oc *OpusDecoder) Options() Options {\n\treturn oc.options\n}", "func NewOptions() Options {\n\tvar opts Options\n\tkingpin.Flag(\"verbose\", \"enable additional logging (env - VERBOSE)\").Envar(\"VERBOSE\").Short('v').BoolVar(&opts.Debug)\n\tkingpin.Flag(\"listen-addr\", \"address:port to listen for requests on (env - LISTEN_ADDR)\").Default(\":8099\").Envar(\"LISTEN_ADDR\").StringVar(&opts.ListenAddr)\n\tkingpin.Flag(\"metrics-listen-addr\", \"address:port to listen for Prometheus metrics on, empty to disable (env - METRICS_LISTEN_ADDR)\").Default(\"\").Envar(\"METRICS_LISTEN_ADDR\").StringVar(&opts.MetricsListenAddr)\n\tkingpin.Flag(\"pprof-listen-addr\", \"address:port to listen for pprof on, empty to disable (env - PPROF_LISTEN_ADDR)\").Default(\"\").Envar(\"PPROF_LISTEN_ADDR\").StringVar(&opts.PprofListenAddr)\n\tkingpin.Flag(\"allowed-endpoint\", \"allowed endpoint (Host header) to accept for incoming requests (env - ALLOWED_ENDPOINT)\").Envar(\"ALLOWED_ENDPOINT\").Required().PlaceHolder(\"my.host.example.com:8099\").StringVar(&opts.AllowedSourceEndpoint)\n\tkingpin.Flag(\"allowed-source-subnet\", \"allowed source IP addresses with netmask (env - ALLOWED_SOURCE_SUBNET)\").Default(\"127.0.0.1/32\").Envar(\"ALLOWED_SOURCE_SUBNET\").StringsVar(&opts.AllowedSourceSubnet)\n\tkingpin.Flag(\"aws-credentials\", \"set of AWS credentials (env - AWS_CREDENTIALS)\").PlaceHolder(\"\\\"AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY\\\"\").Envar(\"AWS_CREDENTIALS\").StringsVar(&opts.AwsCredentials)\n\tkingpin.Flag(\"aws-region\", \"send requests to this AWS S3 region (env - AWS_REGION)\").Envar(\"AWS_REGION\").Default(\"eu-central-1\").StringVar(&opts.Region)\n\tkingpin.Flag(\"upstream-insecure\", \"use insecure HTTP for upstream connections (env - UPSTREAM_INSECURE)\").Envar(\"UPSTREAM_INSECURE\").BoolVar(&opts.UpstreamInsecure)\n\tkingpin.Flag(\"upstream-endpoint\", \"use this S3 endpoint for upstream connections, instead of public AWS S3 (env - UPSTREAM_ENDPOINT)\").Envar(\"UPSTREAM_ENDPOINT\").StringVar(&opts.UpstreamEndpoint)\n\tkingpin.Flag(\"cert-file\", \"path to the certificate file (env - CERT_FILE)\").Envar(\"CERT_FILE\").Default(\"\").StringVar(&opts.CertFile)\n\tkingpin.Flag(\"key-file\", \"path to the private key file (env - KEY_FILE)\").Envar(\"KEY_FILE\").Default(\"\").StringVar(&opts.KeyFile)\n\tkingpin.Parse()\n\treturn opts\n}", "func ConstructorOpts(extra ...node.Option) NodeOpt {\n\treturn func(opts *nodeOpts) error {\n\t\topts.extraNodeOpts = append(opts.extraNodeOpts, extra...)\n\t\treturn nil\n\t}\n}", "func (o StorageNodeSpecCloudStorageDriveConfigsOutput) Options() pulumi.MapOutput {\n\treturn o.ApplyT(func(v StorageNodeSpecCloudStorageDriveConfigs) map[string]interface{} { return v.Options }).(pulumi.MapOutput)\n}", "func CollectOptions(opts ...Option) Options {\n\tvar suiteOpts Options\n\tfor _, o := range opts {\n\t\to(&suiteOpts)\n\t}\n\treturn suiteOpts\n}", "func (b *base) Options() []func(Call) error {\n\treturn b.options\n}", "func (req *SelectRequest) Opts(opts SelectOpts) *SelectRequest {\n\treq.opts = opts\n\treturn req\n}", "func SeriesCellOpts(co ...cell.Option) SeriesOption {\n\treturn seriesOption(func(opts *seriesValues) {\n\t\topts.seriesCellOpts = co\n\t})\n}", "func (b *ExperimentBuilder) Options() (map[string]OptionInfo, error) {\n\tresult := make(map[string]OptionInfo)\n\tptrinfo := reflect.ValueOf(b.config)\n\tif ptrinfo.Kind() != reflect.Ptr {\n\t\treturn nil, errors.New(\"config is not a pointer\")\n\t}\n\tstructinfo := ptrinfo.Elem().Type()\n\tif structinfo.Kind() != reflect.Struct {\n\t\treturn nil, errors.New(\"config is not a struct\")\n\t}\n\tfor i := 0; i < structinfo.NumField(); i++ {\n\t\tfield := structinfo.Field(i)\n\t\tresult[field.Name] = OptionInfo{\n\t\t\tDoc: field.Tag.Get(\"ooni\"),\n\t\t\tType: field.Type.String(),\n\t\t}\n\t}\n\treturn result, nil\n}", "func (ng *NodeGroup) GetOptions(defaults config.NodeGroupAutoscalingOptions) (*config.NodeGroupAutoscalingOptions, error) {\n\t// If node group autoscaling options nil, return defaults\n\tif ng.Autoscaling == nil {\n\t\treturn nil, nil\n\t}\n\n\t// Forge autoscaling configuration from node pool\n\tcfg := &config.NodeGroupAutoscalingOptions{\n\t\tScaleDownUnneededTime: time.Duration(ng.Autoscaling.ScaleDownUnneededTimeSeconds) * time.Second,\n\t\tScaleDownUnreadyTime: time.Duration(ng.Autoscaling.ScaleDownUnreadyTimeSeconds) * time.Second,\n\t}\n\n\t// Switch utilization threshold from defaults given flavor type\n\tif ng.isGpu() {\n\t\tcfg.ScaleDownUtilizationThreshold = defaults.ScaleDownUtilizationThreshold\n\t\tcfg.ScaleDownGpuUtilizationThreshold = float64(ng.Autoscaling.ScaleDownUtilizationThreshold) // Use this one\n\t} else {\n\t\tcfg.ScaleDownUtilizationThreshold = float64(ng.Autoscaling.ScaleDownUtilizationThreshold) // Use this one\n\t\tcfg.ScaleDownGpuUtilizationThreshold = defaults.ScaleDownGpuUtilizationThreshold\n\t}\n\n\treturn cfg, nil\n}", "func (c *Client) GetAuthOpts() (authOpts dockerclient.AuthConfigurations) {\n\tauthOpt := dockerclient.AuthConfiguration{\n\t\tUsername: c.AuthConfig.Username,\n\t\tPassword: c.AuthConfig.Password,\n\t}\n\n\tauthOpts = dockerclient.AuthConfigurations{\n\t\tConfigs: make(map[string]dockerclient.AuthConfiguration),\n\t}\n\tauthOpts.Configs[c.Registry] = authOpt\n\n\treturn authOpts\n}" ]
[ "0.6970594", "0.6281927", "0.59078234", "0.5868081", "0.5761447", "0.56771445", "0.56171125", "0.55353045", "0.5506973", "0.5471589", "0.54695356", "0.54681355", "0.54206634", "0.5406276", "0.5379113", "0.53657633", "0.5356025", "0.5337401", "0.52826387", "0.52810746", "0.5236273", "0.5228371", "0.51983553", "0.51926357", "0.5178007", "0.51692617", "0.51685077", "0.51150644", "0.5107587", "0.509537", "0.5091516", "0.5084232", "0.5067439", "0.50446784", "0.5034239", "0.50328165", "0.50073296", "0.5006212", "0.5004552", "0.5003781", "0.49991316", "0.49750435", "0.49733064", "0.49698144", "0.49545056", "0.49192026", "0.49119982", "0.49042183", "0.49005517", "0.48988387", "0.48947263", "0.4886981", "0.48724514", "0.48624003", "0.48541293", "0.48534524", "0.4829306", "0.48255104", "0.48241454", "0.48240703", "0.4820023", "0.48159155", "0.48143739", "0.48110065", "0.4806841", "0.48058537", "0.47905722", "0.4790194", "0.4789657", "0.47796994", "0.47759378", "0.47727197", "0.47667062", "0.4757676", "0.4756577", "0.47538516", "0.47472742", "0.47454834", "0.47412437", "0.47411454", "0.47149995", "0.47127968", "0.4703587", "0.46948785", "0.46890256", "0.4688184", "0.46690702", "0.46690702", "0.46645752", "0.46609813", "0.46605188", "0.46577546", "0.46539006", "0.46476388", "0.46430048", "0.4636706", "0.4633019", "0.46299204", "0.46298066", "0.46259743" ]
0.73391664
0
ApplyOpts applies any values set in o to opts, if a value is not set on o, then we don't update opts and allow redispipe to use its defaults.
func (o Opts) ApplyOpts(opts *redisconn.Opts) { if o.DB != nil { opts.DB = *o.DB } if o.WritePause > 0 { opts.WritePause = o.WritePause } if o.ReconnectPause > 0 { opts.ReconnectPause = o.ReconnectPause } if o.TCPKeepAlive > 0 { opts.TCPKeepAlive = o.TCPKeepAlive } o.Timeouts.ApplyOpts(opts) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *Options) Apply(opts ...Option) error {\n\tfor i, opt := range opts {\n\t\tif err := opt(o); err != nil {\n\t\t\treturn fmt.Errorf(\"option %d failed: %s\", i, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Options) Apply() {\n\tif o == nil {\n\t\treturn\n\t}\n\tif len(o.ShowHiddenMetricsForVersion) > 0 {\n\t\tSetShowHidden()\n\t}\n\t// set disabled metrics\n\tfor _, metricName := range o.DisabledMetrics {\n\t\tSetDisabledMetric(metricName)\n\t}\n\tif o.AllowListMapping != nil {\n\t\tSetLabelAllowListFromCLI(o.AllowListMapping)\n\t}\n}", "func (o *PatchOptions) ApplyOptions(opts []PatchOption) {\n\tfor _, opt := range opts {\n\t\topt.ApplyToHelper(o)\n\t}\n}", "func applyOptions(c *Container, opts ...Option) error {\n\tfor _, opt := range opts {\n\t\tif err := opt.set(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Options) Apply(opts ...Option) error {\n\tfor i, opt := range opts {\n\t\tif err := opt(o); err != nil {\n\t\t\treturn fmt.Errorf(\"dht option %d failed: %s\", i, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o Options) Apply(i *Important) {\n\tfor _, opt := range o {\n\t\topt(i)\n\t}\n}", "func (o optionFunc) ApplyOption(opts *Options) {\n\to(opts)\n}", "func (opts *Options) Apply(options ...Option) error {\n\tfor _, o := range options {\n\t\tif err := o(opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (o *MatchOptions) ApplyOptions(opts []MatchOption) *MatchOptions {\n\tfor _, opt := range opts {\n\t\topt.ApplyToMatcher(o)\n\t}\n\treturn o\n}", "func ApplyGaugeOptions(opts *Options, gos ...GaugeOptionApplier) {\n\tfor _, o := range gos {\n\t\to.ApplyGaugeOption(opts)\n\t}\n}", "func (ro *RequesterOptions) apply(opts ...RequesterOption) {\n\tfor _, opt := range opts {\n\t\topt(ro)\n\t}\n}", "func (cfg *Config) Apply(opts ...Option) error {\n\tfor _, opt := range opts {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err := opt(cfg); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (opt option) apply(o interface{}) error {\n\tswitch v := o.(type) {\n\tcase *TableEncoder:\n\t\tif opt.table != nil {\n\t\t\treturn opt.table(v)\n\t\t}\n\t\treturn nil\n\tcase *ExpandedEncoder:\n\t\tif opt.expanded != nil {\n\t\t\treturn opt.expanded(v)\n\t\t}\n\t\treturn nil\n\tcase *JSONEncoder:\n\t\tif opt.json != nil {\n\t\t\treturn opt.json(v)\n\t\t}\n\t\treturn nil\n\tcase *UnalignedEncoder:\n\t\tif opt.unaligned != nil {\n\t\t\treturn opt.unaligned(v)\n\t\t}\n\t\treturn nil\n\tcase *TemplateEncoder:\n\t\tif opt.template != nil {\n\t\t\treturn opt.template(v)\n\t\t}\n\t\treturn nil\n\tcase *CrosstabView:\n\t\tif opt.crosstab != nil {\n\t\t\treturn opt.crosstab(v)\n\t\t}\n\t\treturn nil\n\tcase *errEncoder:\n\t\tif opt.err != nil {\n\t\t\treturn opt.err(v)\n\t\t}\n\t\treturn nil\n\t}\n\tpanic(fmt.Sprintf(\"option cannot be applied to %T\", o))\n}", "func (d *OverloadServiceDesc) Apply(oo ...transport.DescOption) {\n\tfor _, o := range oo {\n\t\to.Apply(&d.opts)\n\t}\n}", "func (o Option) apply(r *Dol) { o(r) }", "func (o *Number[T]) ApplyOptions(options ...NumberOption[T]) *Number[T] {\n\tfor _, opt := range options {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\topt.apply(o)\n\t}\n\treturn o\n}", "func (o *JSONPb) ApplyOptions(options ...JSONPbOption) *JSONPb {\n\tfor _, opt := range options {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\topt.apply(o)\n\t}\n\treturn o\n}", "func (po *SubResourcePatchOptions) ApplyOptions(opts []SubResourcePatchOption) *SubResourcePatchOptions {\n\tfor _, o := range opts {\n\t\to.ApplyToSubResourcePatch(po)\n\t}\n\n\treturn po\n}", "func ApplyOptions(f *pflag.Flag, opts ...FlagOption) {\n\tfor _, opt := range opts {\n\t\topt(f)\n\t}\n}", "func (c *Default) Update(opts ...DefaultOption) {\n\tfor _, opt := range opts {\n\t\topt.ApplyDefault(c)\n\t}\n}", "func (t Timeouts) ApplyOpts(opts *redisconn.Opts) {\n\tif t.Dial > 0 {\n\t\topts.DialTimeout = t.Dial\n\t}\n\tif t.IO > 0 {\n\t\topts.IOTimeout = t.IO\n\t}\n}", "func (uo *SubResourceUpdateOptions) ApplyOptions(opts []SubResourceUpdateOption) *SubResourceUpdateOptions {\n\tfor _, o := range opts {\n\t\to.ApplyToSubResourceUpdate(uo)\n\t}\n\n\treturn uo\n}", "func (r RequestCryptoSignerOpts) ApplyCryptoSignerOpts(opts *crypto.SignerOpts) {\n\t*opts = r.opts\n}", "func (c *AppConfig) Apply(opts []AppOption) error {\r\n\tfor _, o := range opts {\r\n\t\tif err := o(c); err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t}\r\n\treturn nil\r\n}", "func ApplyOptions(opt ...Option) Options {\n\topts := Options{\n\t\tMaxTraversalLinks: math.MaxInt64, //default: traverse all\n\t\tMaxAllowedHeaderSize: carv1.DefaultMaxAllowedHeaderSize,\n\t\tMaxAllowedSectionSize: carv1.DefaultMaxAllowedSectionSize,\n\t}\n\tfor _, o := range opt {\n\t\to(&opts)\n\t}\n\t// Set defaults for zero valued fields.\n\tif opts.IndexCodec == 0 {\n\t\topts.IndexCodec = multicodec.CarMultihashIndexSorted\n\t}\n\tif opts.MaxIndexCidSize == 0 {\n\t\topts.MaxIndexCidSize = DefaultMaxIndexCidSize\n\t}\n\treturn opts\n}", "func MergeOpenDriveOptions(opts ...*OpenDriveOptions) *OpenDriveOptions {\n\to := OpenDrive()\n\n\tfor _, opt := range opts {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif opt.Directory != nil {\n\t\t\to.Directory = opt.Directory\n\t\t}\n\t\tif opt.Logger != nil {\n\t\t\to.Logger = opt.Logger\n\t\t}\n\t\tif opt.AccessController != nil {\n\t\t\to.AccessController = opt.AccessController\n\t\t}\n\t\tif opt.Create != nil {\n\t\t\to.Create = opt.Create\n\t\t}\n\t}\n\n\treturn o\n}", "func (op *ReadOptions) Apply(opts ...ReadOption) {\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n}", "func (opts RequestOpts) Apply(req *http.Request) {\n\t// apply per-request options\n\tfor _, o := range opts {\n\t\tif o != nil {\n\t\t\to(req)\n\t\t}\n\t}\n}", "func (o *ListImplementationRevisionsOptions) Apply(opts ...GetImplementationOption) {\n\tfor _, opt := range opts {\n\t\topt(o)\n\t}\n}", "func (o *DB) ApplyOptions(options ...DBOption) *DB {\n\tfor _, opt := range options {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\topt.apply(o)\n\t}\n\treturn o\n}", "func (o ClientOptions) ApplyDefaults(ctx context.Context, defaultDesc string) ClientOptions {\n\tif o.Hostname == \"\" {\n\t\to.Hostname = GetDefaultHostName(ctx)\n\t}\n\n\tif o.Username == \"\" {\n\t\to.Username = GetDefaultUserName(ctx)\n\t}\n\n\tif o.Description == \"\" {\n\t\to.Description = defaultDesc\n\t}\n\n\tif o.FormatBlobCacheDuration == 0 {\n\t\to.FormatBlobCacheDuration = format.DefaultRepositoryBlobCacheDuration\n\t}\n\n\treturn o\n}", "func (r *Repo) Apply(opts ...func(*Repo)) {\n\tif r == nil {\n\t\treturn\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(r)\n\t}\n}", "func ApplyGatewayDefaultOptions(opts *Options) error {\n\tif opts.Stack.Tenants == nil {\n\t\treturn nil\n\t}\n\n\tif !opts.Gates.OpenShift.Enabled {\n\t\treturn nil\n\t}\n\n\to := openshift.NewOptions(\n\t\topts.Name,\n\t\topts.Namespace,\n\t\tGatewayName(opts.Name),\n\t\tserviceNameGatewayHTTP(opts.Name),\n\t\tgatewayHTTPPortName,\n\t\topts.Timeouts.Gateway.WriteTimeout,\n\t\tComponentLabels(LabelGatewayComponent, opts.Name),\n\t\tRulerName(opts.Name),\n\t)\n\n\tswitch opts.Stack.Tenants.Mode {\n\tcase lokiv1.Static, lokiv1.Dynamic:\n\t\t// Do nothing as per tenants provided by LokiStack CR\n\tcase lokiv1.OpenshiftLogging, lokiv1.OpenshiftNetwork:\n\t\ttenantData := make(map[string]openshift.TenantData)\n\t\tfor name, tenant := range opts.Tenants.Configs {\n\t\t\ttenantData[name] = openshift.TenantData{\n\t\t\t\tCookieSecret: tenant.OpenShift.CookieSecret,\n\t\t\t}\n\t\t}\n\n\t\to.WithTenantsForMode(opts.Stack.Tenants.Mode, opts.GatewayBaseDomain, tenantData)\n\t}\n\n\tif err := mergo.Merge(&opts.OpenShiftOptions, o, mergo.WithOverride); err != nil {\n\t\treturn kverrors.Wrap(err, \"failed to merge defaults for mode openshift\")\n\t}\n\n\treturn nil\n}", "func ApplyLoggerOpts(opts ...Option) LoggerOpts {\n\t// set some defaults\n\tl := LoggerOpts{\n\t\tAdditionalLocationOffset: 1,\n\t\tIncludeLocation: true,\n\t\tIncludeTime: true,\n\t\tOutput: os.Stderr,\n\t}\n\tfor _, opt := range opts {\n\t\tl = opt(l)\n\t}\n\treturn l\n}", "func (getOpt *SubResourceGetOptions) ApplyOptions(opts []SubResourceGetOption) *SubResourceGetOptions {\n\tfor _, o := range opts {\n\t\to.ApplyToSubResourceGet(getOpt)\n\t}\n\n\treturn getOpt\n}", "func (a *APIPatchingApplicator) Apply(ctx context.Context, o client.Object, ao ...ApplyOption) error {\n\tif o.GetNamespace() == \"\" {\n\t\to.SetNamespace(\"default\")\n\t}\n\n\tm, ok := o.(metav1.Object)\n\tif !ok {\n\t\treturn errors.New(\"cannot access object metadata\")\n\t}\n\n\tif m.GetName() == \"\" && m.GetGenerateName() != \"\" {\n\t\treturn errors.Wrap(a.client.Create(ctx, o), \"cannot create object\")\n\t}\n\n\tdesired := o.DeepCopyObject()\n\n\terr := a.client.Get(ctx, types.NamespacedName{Name: m.GetName(), Namespace: m.GetNamespace()}, o)\n\tif kerrors.IsNotFound(err) {\n\t\t// TODO: Apply ApplyOptions here too?\n\t\treturn errors.Wrap(a.client.Create(ctx, o), \"cannot create object\")\n\t}\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"cannot get object\")\n\t}\n\n\tfor _, fn := range ao {\n\t\tif err := fn(ctx, o, desired); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// TODO: Allow callers to override the kind of patch used.\n\treturn errors.Wrap(a.client.Patch(ctx, o, &patch{desired.(client.Object)}), \"cannot patch object\")\n}", "func (lOpts *logOptions) apply(options ...Option) {\n\tfor _, opt := range options {\n\t\topt(lOpts)\n\t}\n}", "func (opts *lateInitOptions) apply(opt ...LateInitOption) {\n\tfor _, o := range opt {\n\t\to.apply(opts)\n\t}\n}", "func (o ClusterOpts) ApplyOpts(opts *rediscluster.Opts) {\n\tif o.Name != \"\" {\n\t\topts.Name = o.Name\n\t}\n}", "func (req *SelectRequest) Opts(opts SelectOpts) *SelectRequest {\n\treq.opts = opts\n\treturn req\n}", "func ApplyMeasureOptions(opts *Options, mos ...MeasureOptionApplier) {\n\tfor _, o := range mos {\n\t\to.ApplyMeasureOption(opts)\n\t}\n}", "func (o *DeleteOptions) ApplyOptions(opts []DeleteOption) {\n\tfor _, opt := range opts {\n\t\topt.ApplyToDeleteOptions(o)\n\t}\n}", "func (a *APIUpdatingApplicator) Apply(ctx context.Context, o client.Object, ao ...ApplyOption) error {\n\tm, ok := o.(Object)\n\tif !ok {\n\t\treturn errors.New(\"cannot access object metadata\")\n\t}\n\n\tif m.GetName() == \"\" && m.GetGenerateName() != \"\" {\n\t\treturn errors.Wrap(a.client.Create(ctx, o), \"cannot create object\")\n\t}\n\n\tcurrent := o.DeepCopyObject().(client.Object)\n\n\terr := a.client.Get(ctx, types.NamespacedName{Name: m.GetName(), Namespace: m.GetNamespace()}, current)\n\tif kerrors.IsNotFound(err) {\n\t\t// TODO: Apply ApplyOptions here too?\n\t\treturn errors.Wrap(a.client.Create(ctx, m), \"cannot create object\")\n\t}\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"cannot get object\")\n\t}\n\n\tfor _, fn := range ao {\n\t\tif err := fn(ctx, current, m); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// NOTE: we must set the resource version of the desired object\n\t// to that of the current or the update will always fail.\n\tm.SetResourceVersion(current.(metav1.Object).GetResourceVersion())\n\treturn errors.Wrap(a.client.Update(ctx, m), \"cannot update object\")\n}", "func (o *Options) applyDefaults(in *componentconfig.CoordinatorConfiguration) (*componentconfig.CoordinatorConfiguration, error) {\n\tcomponentconfig.SetDefaultsCoordinatorConfiguration(in)\n\treturn in, nil\n}", "func (bo *BoolOptions) Apply(n models.ConfigurationMap, changed ChangedFunc, data interface{}) int {\n\tchanges := []changedOptions{}\n\n\tbo.optsMU.Lock()\n\tfor k, v := range n {\n\t\tval, ok := bo.Opts[k]\n\n\t\tif boolVal, _ := NormalizeBool(v); boolVal {\n\t\t\t/* Only enable if not enabled already */\n\t\t\tif !ok || !val {\n\t\t\t\tbo.enable(k)\n\t\t\t\tchanges = append(changes, changedOptions{key: k, value: true})\n\t\t\t}\n\t\t} else {\n\t\t\t/* Only disable if enabled already */\n\t\t\tif ok && val {\n\t\t\t\tbo.disable(k)\n\t\t\t\tchanges = append(changes, changedOptions{key: k, value: false})\n\t\t\t}\n\t\t}\n\t}\n\tbo.optsMU.Unlock()\n\n\tfor _, change := range changes {\n\t\tchanged(change.key, change.value, data)\n\t}\n\n\treturn len(changes)\n}", "func (eeo EncodingErrorOption) argApply(o *argOptions) {\n\to.opts = append(o.opts, eeo)\n}", "func ApplyCounterOptions(opts *Options, cos ...CounterOptionApplier) {\n\tfor _, o := range cos {\n\t\to.ApplyCounterOption(opts)\n\t}\n}", "func (s *LCOWOption) Apply(interface{}) error {\n\treturn nil\n}", "func ApplyDefaults(obj interface{}, s *spec.Schema) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tres := false\n\n\t// Support utils.Values\n\tswitch vals := obj.(type) {\n\tcase utils.Values:\n\t\tobj = map[string]interface{}(vals)\n\tcase *utils.Values:\n\t\t// rare case\n\t\tobj = map[string]interface{}(*vals)\n\t}\n\n\tswitch obj := obj.(type) {\n\tcase map[string]interface{}:\n\t\t// Apply defaults to properties\n\t\tfor k, prop := range s.Properties {\n\t\t\tif prop.Default == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, found := obj[k]; !found {\n\t\t\t\tobj[k] = runtime.DeepCopyJSONValue(prop.Default)\n\t\t\t\tres = true\n\t\t\t}\n\t\t}\n\t\t// Apply to deeper levels.\n\t\tfor k, v := range obj {\n\t\t\tif prop, found := s.Properties[k]; found {\n\t\t\t\tdeepRes := ApplyDefaults(v, &prop)\n\t\t\t\tres = res || deepRes\n\t\t\t}\n\t\t}\n\tcase []interface{}:\n\t\t// Only List validation is supported.\n\t\t// See https://json-schema.org/understanding-json-schema/reference/array.html#list-validation\n\t\tfor _, v := range obj {\n\t\t\tdeepRes := ApplyDefaults(v, s.Items.Schema)\n\t\t\tres = res || deepRes\n\t\t}\n\tdefault:\n\t\t// scalars, no action\n\t}\n\n\treturn res\n}", "func (c *MockClient) ApplyOption(opt MockClientOption) {\n\topt(c)\n}", "func (req *UpsertObjectRequest) Opts(opts UpsertObjectOpts) *UpsertObjectRequest {\n\treq.opts = opts\n\treturn req\n}", "func Apply(rw ReadWriter, options ...Option) ReadWriter {\n\tfor _, option := range options {\n\t\toption(rw)\n\t}\n\treturn applyOptionsForState(rw)\n}", "func ApplyAll(rw ReadWriter, optionSets ...[]Option) ReadWriter {\n\toptions := []Option{}\n\tfor _, optionSet := range optionSets {\n\t\toptions = append(options, optionSet...)\n\t}\n\treturn Apply(rw, options...)\n}", "func (pool *ComplexPool) Option(opts ...Option) (err error) {\n\tfor _, opt := range opts {\n\t\terr = opt(pool)\n\t}\n\n\treturn err\n}", "func (options Options) merge(defaults Options) {\n for k, v := range defaults {\n if _, present := options[k]; !present {\n options[k] = v\n }\n }\n}", "func (sso *StartSpanOptions) Apply(opt opentracing.StartSpanOption) {\n\topt.Apply(&sso.OpenTracingOptions)\n\tif o, ok := opt.(StartSpanOption); ok {\n\t\to.ApplyBP(sso)\n\t}\n}", "func (opts *Opts) updateOptions() {\n\tfor option := range opts.rs.edges {\n\t\tif _, ok := opts.options[option]; !ok {\n\t\t\t// by default the option state is false\n\t\t\topts.options[option] = false\n\t\t\t// if a parent exist the new option takes its state\n\t\t\tif len(opts.rs.edges[option]) > 0 {\n\t\t\t\tparent := opts.rs.edges[option][0] // TODO: what if there are multiple parents?\n\t\t\t\topts.options[option] = opts.options[parent]\n\t\t\t}\n\t\t}\n\t}\n\n\tfor option := range opts.rs.conflicts {\n\t\tif _, ok := opts.options[option]; !ok {\n\t\t\topts.options[option] = false\n\t\t}\n\t}\n}", "func (f OptionFunc) Apply(ratelimiter Ratelimiter) error {\n\treturn f(ratelimiter)\n}", "func (p *Porter) applyActionOptionsToInstallation(ctx context.Context, ba BundleAction, inst *storage.Installation) error {\n\tctx, span := tracing.StartSpan(ctx)\n\tdefer span.EndSpan()\n\n\to := ba.GetOptions()\n\n\tbundleRef, err := o.GetBundleReference(ctx, p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbun := bundleRef.Definition\n\n\t// Update the installation with metadata from the options\n\tinst.TrackBundle(bundleRef.Reference)\n\tinst.Status.Modified = time.Now()\n\n\t//\n\t// 1. Record the parameter and credential sets used on the installation\n\t// if none were specified, reuse the previous sets from the installation\n\t//\n\tspan.SetAttributes(\n\t\ttracing.ObjectAttribute(\"override-parameter-sets\", o.ParameterSets),\n\t\ttracing.ObjectAttribute(\"override-credential-sets\", o.CredentialIdentifiers))\n\tif len(o.ParameterSets) > 0 {\n\t\tinst.ParameterSets = o.ParameterSets\n\t}\n\tif len(o.CredentialIdentifiers) > 0 {\n\t\tinst.CredentialSets = o.CredentialIdentifiers\n\t}\n\n\t//\n\t// 2. Parse parameter flags from the command line and apply to the installation as overrides\n\t//\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"override-parameters\", o.Params))\n\tparsedOverrides, err := storage.ParseVariableAssignments(o.Params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Default the porter-debug param to --debug\n\tif o.DebugMode {\n\t\tparsedOverrides[\"porter-debug\"] = \"true\"\n\t}\n\n\t// Apply overrides on to of any pre-existing parameters that were specified previously\n\tif len(parsedOverrides) > 0 {\n\t\tfor name, value := range parsedOverrides {\n\t\t\t// Do not resolve parameters from dependencies\n\t\t\tif strings.Contains(name, \"#\") {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Replace previous value if present\n\t\t\treplaced := false\n\t\t\tparamStrategy := storage.ValueStrategy(name, value)\n\t\t\tfor i, existingParam := range inst.Parameters.Parameters {\n\t\t\t\tif existingParam.Name == name {\n\t\t\t\t\tinst.Parameters.Parameters[i] = paramStrategy\n\t\t\t\t\treplaced = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !replaced {\n\t\t\t\tinst.Parameters.Parameters = append(inst.Parameters.Parameters, paramStrategy)\n\t\t\t}\n\t\t}\n\n\t\t// Keep the parameter overrides sorted, so that comparisons and general troubleshooting is easier\n\t\tsort.Sort(inst.Parameters.Parameters)\n\t}\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"merged-installation-parameters\", inst.Parameters.Parameters))\n\n\t//\n\t// 3. Resolve named parameter sets\n\t//\n\tresolvedParams, err := p.loadParameterSets(ctx, bun, o.Namespace, inst.ParameterSets)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to process provided parameter sets: %w\", err)\n\t}\n\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"resolved-parameter-sets-keys\", resolvedParams))\n\n\t//\n\t// 4. Resolve the installation's internal parameter set\n\tresolvedOverrides, err := p.Parameters.ResolveAll(ctx, inst.Parameters)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"resolved-installation-parameters\", inst.Parameters.Parameters))\n\n\t//\n\t// 5. Apply the overrides on top of the parameter sets\n\t//\n\tfor k, v := range resolvedOverrides {\n\t\tresolvedParams[k] = v\n\t}\n\n\t//\n\t// 6. Separate out params for the root bundle from the ones intended for dependencies\n\t// This only applies to the dep v1 implementation, in dep v2 you can't specify rando params for deps\n\t//\n\to.depParams = make(map[string]string)\n\tfor k, v := range resolvedParams {\n\t\tif strings.Contains(k, \"#\") {\n\t\t\to.depParams[k] = v\n\t\t\tdelete(resolvedParams, k)\n\t\t}\n\t}\n\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"user-specified-parameters\", resolvedParams))\n\n\t//\n\t// 7. When a parameter is not specified, fallback to a parameter source or default\n\t//\n\tfinalParams, err := p.finalizeParameters(ctx, *inst, bun, ba.GetAction(), resolvedParams)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"final-parameters\", finalParams))\n\n\t// Remember the final set of parameters so we don't have to resolve them more than once\n\to.finalParams = finalParams\n\n\t// Ensure we aren't storing any secrets on the installation resource\n\tif err = p.sanitizeInstallation(ctx, inst, bundleRef.Definition); err != nil {\n\t\treturn err\n\t}\n\n\t// re-validate the installation since we modified it here\n\treturn inst.Validate(ctx, p.GetSchemaCheckStrategy(ctx))\n}", "func (o *EphemeralVolumeControllerOptions) ApplyTo(cfg *ephemeralvolumeconfig.EphemeralVolumeControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentEphemeralVolumeSyncs = o.ConcurrentEphemeralVolumeSyncs\n\n\treturn nil\n}", "func (opts *Options) SetDefaults() {\n for name, _ := range opts.opt_map {\n //fmt.Printf(\"%s\\n\",name);\n opts.opt_map[name].SetDefault()\n }\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"key_not_required\":\n\t\t\t\tkeyNotRequired, err := strconv.ParseBool(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\topts.withKeyNotRequired = keyNotRequired\n\t\t\tcase \"user_agent\":\n\t\t\t\topts.withUserAgent = v\n\t\t\tcase \"credentials\":\n\t\t\t\topts.withCredentials = v\n\t\t\tcase \"project\":\n\t\t\t\topts.withProject = v\n\t\t\tcase \"region\":\n\t\t\t\topts.withRegion = v\n\t\t\tcase \"key_ring\":\n\t\t\t\topts.withKeyRing = v\n\t\t\tcase \"crypto_key\":\n\t\t\t\topts.withCryptoKey = v\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func (req MinRequest) Opts(opts MinOpts) MinRequest {\n\treq.opts = opts\n\treturn req\n}", "func (c *Currency) Option(opts ...OptionFunc) (previous OptionFunc) {\n\tfor _, o := range opts {\n\t\tif o != nil {\n\t\t\tprevious = o(c)\n\t\t}\n\t}\n\treturn previous\n}", "func transformOptions(options ...interface{}) map[string]interface{} {\n\tvar base map[string]interface{}\n\tvar option interface{}\n\t// Case 1: No options are given\n\tif len(options) == 0 {\n\t\treturn make(map[string]interface{})\n\t}\n\tif len(options) == 1 {\n\t\t// Case 2: a single value (either struct or map) is given.\n\t\tbase = make(map[string]interface{})\n\t\toption = options[0]\n\t} else if len(options) == 2 {\n\t\t// Case 3: two values are given. The first one needs to be a map and the\n\t\t// second one can be a struct or map. It will be then get merged into the first\n\t\t// base map.\n\t\tbase = transformStructIntoMapIfNeeded(options[0])\n\t\toption = options[1]\n\t}\n\tv := reflect.ValueOf(option)\n\tif v.Kind() == reflect.Slice {\n\t\tif v.Len() == 0 {\n\t\t\treturn base\n\t\t}\n\t\toption = v.Index(0).Interface()\n\t}\n\n\tif option == nil {\n\t\treturn base\n\t}\n\tv = reflect.ValueOf(option)\n\n\tif v.Kind() == reflect.Ptr {\n\t\tv = v.Elem()\n\t}\n\n\toptionMap := transformStructIntoMapIfNeeded(v.Interface())\n\tfor key, value := range optionMap {\n\t\tbase[key] = value\n\t}\n\treturn base\n}", "func fromOptions(options []Option) *baseSettings {\n\t// Start from the default options:\n\topts := &baseSettings{\n\t\tconsumerOptions: []consumer.Option{consumer.WithCapabilities(consumer.Capabilities{MutatesData: true})},\n\t}\n\n\tfor _, op := range options {\n\t\top(opts)\n\t}\n\n\treturn opts\n}", "func aggregateOptionsFromCommerceOptions(payload *app.CommerceOptionsPayload) (model.AggregateOptions, error) {\n\tvar o model.AggregateOptions\n\n\tfor _, val := range payload.FilterBy {\n\t\tfb := &model.FilterBy{\n\t\t\tTag: val.Tag,\n\t\t\tValues: val.Values,\n\t\t\tInverse: false,\n\t\t}\n\t\tif val.Inverse != nil {\n\t\t\tfb.Inverse = *val.Inverse\n\t\t}\n\t\to.FilterBy = append(o.FilterBy, fb)\n\t}\n\n\to.GroupBy = payload.GroupBy\n\tif payload.TimeAfter != nil {\n\t\to.TimeAfter = *payload.TimeAfter\n\t}\n\tif payload.TimeBefore != nil {\n\t\to.TimeBefore = *payload.TimeBefore\n\t}\n\n\tif payload.Step != nil {\n\t\to.Step = *payload.Step\n\t}\n\n\tif payload.TimeHistogram != nil {\n\t\to.TimeHistogram = &model.TimeHistogram{\n\t\t\tInterval: payload.TimeHistogram.Interval,\n\t\t}\n\n\t\tif payload.TimeHistogram.TimeZone != nil {\n\t\t\tlocation, err := time.LoadLocation(*payload.TimeHistogram.TimeZone)\n\t\t\tif err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t\to.TimeHistogram.TimeZone = location\n\t\t}\n\t}\n\n\treturn o, nil\n}", "func CommonOptions(ctx context.Context, scope kouch.TargetScope, flags *pflag.FlagSet) (*kouch.Options, error) {\n\to := kouch.NewOptions()\n\tvar err error\n\to.Target, err = kouch.NewTarget(ctx, scope, flags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif e := o.SetParam(flags, kouch.FlagRev); e != nil {\n\t\treturn nil, e\n\t}\n\tif e := setAutoRev(ctx, o, flags); e != nil {\n\t\treturn nil, e\n\t}\n\n\treturn o, nil\n}", "func (o *OptionsProvider) Options(opts ...Option) *OptionsProvider {\n\tfor _, opt := range opts {\n\t\toptType := reflect.TypeOf(opt)\n\t\tif _, ok := optType.FieldByName(\"Value\"); !ok {\n\t\t\tpanic(fmt.Sprintf(\"Option %v doesn't have a Value field.\", optType.Name()))\n\t\t}\n\t\tfieldName := o.m[optType.Name()]\n\t\tfield := reflect.ValueOf(o.spec).Elem().FieldByName(fieldName)\n\t\tif !field.CanSet() || !field.IsValid() {\n\t\t\tpanic(fmt.Sprintf(\"There is no option %v.\", optType.Name()))\n\t\t}\n\t\tfield.Set(reflect.ValueOf(opt))\n\t\to.set[fieldName] = true\n\t}\n\treturn o\n}", "func (o *Options) setDefaults() {\n\tif o.Timeout <= 0 {\n\t\to.Timeout = DefaultTimeout\n\t}\n\tif o.Count < 0 {\n\t\to.Count = 0\n\t}\n\tif o.PacketSize <= 0 {\n\t\to.PacketSize = DefaultPacketSize\n\t}\n}", "func (co *SubResourceCreateOptions) ApplyOptions(opts []SubResourceCreateOption) *SubResourceCreateOptions {\n\tfor _, o := range opts {\n\t\to.ApplyToSubResourceCreate(co)\n\t}\n\n\treturn co\n}", "func MergeAggregateOptions(opts ...*AggregateOptions) *AggregateOptions {\n\taggOpts := Aggregate()\n\tfor _, ao := range opts {\n\t\tif ao == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif ao.AllowDiskUse != nil {\n\t\t\taggOpts.AllowDiskUse = ao.AllowDiskUse\n\t\t}\n\t\tif ao.BatchSize != nil {\n\t\t\taggOpts.BatchSize = ao.BatchSize\n\t\t}\n\t\tif ao.BypassDocumentValidation != nil {\n\t\t\taggOpts.BypassDocumentValidation = ao.BypassDocumentValidation\n\t\t}\n\t\tif ao.Collation != nil {\n\t\t\taggOpts.Collation = ao.Collation\n\t\t}\n\t\tif ao.MaxTime != nil {\n\t\t\taggOpts.MaxTime = ao.MaxTime\n\t\t}\n\t\tif ao.MaxAwaitTime != nil {\n\t\t\taggOpts.MaxAwaitTime = ao.MaxAwaitTime\n\t\t}\n\t\tif ao.Comment != nil {\n\t\t\taggOpts.Comment = ao.Comment\n\t\t}\n\t\tif ao.Hint != nil {\n\t\t\taggOpts.Hint = ao.Hint\n\t\t}\n\t\tif ao.Let != nil {\n\t\t\taggOpts.Let = ao.Let\n\t\t}\n\t\tif ao.Custom != nil {\n\t\t\taggOpts.Custom = ao.Custom\n\t\t}\n\t}\n\n\treturn aggOpts\n}", "func (req *MinRequest) Opts(opts MinOpts) *MinRequest {\n\treq.opts = opts\n\treturn req\n}", "func (s *snapshot) ApplyOptions() Actionable {\n\ts.options = s.context.Options().(*options.SnapshotOptions)\n\n\tif len(s.options.Name) == 0 {\n\t\ts.options.Name = \"github.com/alejandro-carstens/scrubber-\" + time.Now().Format(\"1992-06-02\")\n\t}\n\n\tif !s.options.Exists(\"wait_for_completion\") {\n\t\ts.options.WaitForCompletion = DEFAULT_WAIT_FOR_COMPLETION\n\t}\n\n\tif !s.options.WaitForCompletion {\n\t\tif !s.options.Exists(\"max_wait\") {\n\t\t\ts.options.MaxWait = DEFAULT_MAX_WAIT\n\t\t}\n\n\t\tif !s.options.Exists(\"wait_interval\") {\n\t\t\ts.options.WaitInterval = DEFAULT_WAIT_INTERVAL\n\t\t}\n\t}\n\n\ts.indexer.SetOptions(&golastic.IndexOptions{\n\t\tTimeout: s.options.TimeoutInSeconds(),\n\t\tWaitForCompletion: s.options.WaitForCompletion,\n\t\tPartial: s.options.Partial,\n\t\tIncludeGlobalState: s.options.IncludeGlobalState,\n\t\tIgnoreUnavailable: s.options.IgnoreUnavailable,\n\t})\n\n\treturn s\n}", "func mergeOptions(pas []v1.Patch) []resource.ApplyOption {\n\topts := make([]resource.ApplyOption, 0, len(pas))\n\tfor _, p := range pas {\n\t\tif p.Policy == nil || p.ToFieldPath == nil {\n\t\t\tcontinue\n\t\t}\n\t\topts = append(opts, withMergeOptions(*p.ToFieldPath, p.Policy.MergeOptions))\n\t}\n\treturn opts\n}", "func _DoWithBackoffOptionWithDefault() DoWithBackoffOption {\n\treturn DoWithBackoffOptionFunc(func(*doWithBackoff) {\n\t\t// nothing to change\n\t})\n}", "func (e *ExternalService) Apply(opts ...func(*ExternalService)) {\n\tif e == nil {\n\t\treturn\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(e)\n\t}\n}", "func parseOptions(o Options) (Options, error) {\n\tif o.Capacity <= 0 {\n\t\to.Capacity = DefaultCapacity\n\t}\n\tif o.TimeProvider == nil {\n\t\to.TimeProvider = &timetools.RealTime{}\n\t}\n\treturn o, nil\n}", "func (o *SetoptionFlag) Execute(opts *Options) error {\n\tfor _, e := range *o {\n\t\tif err := e.Execute(opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Merge(target, source interface{}, opt *Options) error {\n\tvT := reflect.ValueOf(target)\n\tvS := reflect.ValueOf(source)\n\n\tif target != nil && vT.Type() == valType {\n\t\tvT = vT.Interface().(reflect.Value)\n\t}\n\tif source != nil && vS.Type() == valType {\n\t\tvS = vS.Interface().(reflect.Value)\n\t}\n\n\tif vT.Kind() != reflect.Ptr {\n\t\treturn errors.New(\"target must be a pointer\")\n\t}\n\n\tif !reflect.Indirect(vT).IsValid() {\n\t\treturn errors.New(\"target can not be zero value\")\n\t}\n\n\t// use defaults if none are provided\n\tif opt == nil {\n\t\topt = NewOptions()\n\t}\n\n\tif opt.mergeFuncs == nil {\n\t\treturn errors.New(\"invalid options, use NewOptions() to generate and then modify as needed\")\n\t}\n\n\t//make a copy here so if there is an error mid way, the target stays in tact\n\tcp := vT.Elem()\n\n\tmerged, err := merge(cp, reflect.Indirect(vS), opt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !isSettable(vT.Elem(), merged) {\n\t\treturn fmt.Errorf(\"Merge failed: expected merged result to be %v but got %v\",\n\t\t\tvT.Elem().Type(), merged.Type())\n\t}\n\n\tvT.Elem().Set(merged)\n\treturn nil\n}", "func (o *RemoveDropRequestParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func flattenOptions(dst, src Options) Options {\n\tfor _, opt := range src {\n\t\tswitch opt := opt.(type) {\n\t\tcase nil:\n\t\t\tcontinue\n\t\tcase Options:\n\t\t\tdst = flattenOptions(dst, opt)\n\t\tcase coreOption:\n\t\t\tdst = append(dst, opt)\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"invalid option type: %T\", opt))\n\t\t}\n\t}\n\treturn dst\n}", "func MergeReplaceOptions(opts ...*ReplaceOptions) *ReplaceOptions {\n\trOpts := Replace()\n\tfor _, ro := range opts {\n\t\tif ro == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif ro.BypassDocumentValidation != nil {\n\t\t\trOpts.BypassDocumentValidation = ro.BypassDocumentValidation\n\t\t}\n\t\tif ro.Collation != nil {\n\t\t\trOpts.Collation = ro.Collation\n\t\t}\n\t\tif ro.Upsert != nil {\n\t\t\trOpts.Upsert = ro.Upsert\n\t\t}\n\t}\n\n\treturn rOpts\n}", "func (c *operatorConfig) apply(options []OperatorOption) {\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tvar err error\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"aead_type\":\n\t\t\t\topts.WithAeadType = wrapping.AeadTypeMap(v)\n\t\t\tcase \"hash_type\":\n\t\t\t\topts.WithHashType = wrapping.HashTypeMap(v)\n\t\t\tcase \"key\":\n\t\t\t\topts.WithKey, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding key value: %w\", err)\n\t\t\t\t}\n\t\t\tcase \"salt\":\n\t\t\t\topts.WithSalt, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding salt value: %w\", err)\n\t\t\t\t}\n\t\t\tcase \"info\":\n\t\t\t\topts.WithInfo, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding info value: %w\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func MergeUpdateOptions(opts ...*UpdateOptions) *UpdateOptions {\n\tuOpts := Update()\n\tfor _, uo := range opts {\n\t\tif uo == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif uo.ArrayFilters != nil {\n\t\t\tuOpts.ArrayFilters = uo.ArrayFilters\n\t\t}\n\t\tif uo.BypassDocumentValidation != nil {\n\t\t\tuOpts.BypassDocumentValidation = uo.BypassDocumentValidation\n\t\t}\n\t\tif uo.Upsert != nil {\n\t\t\tuOpts.Upsert = uo.Upsert\n\t\t}\n\t}\n\n\treturn uOpts\n}", "func (set *Set) RefreshWithBuiltinOptions(entries [][]string) error {\n\tvar err error\n\n\t// The set-name must be < 32 characters!\n\ttempName := set.Name + \"-\"\n\n\tnewSet := &Set{\n\t\tParent: set.Parent,\n\t\tName: tempName,\n\t\tOptions: set.Options,\n\t}\n\n\terr = set.Parent.Add(newSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = newSet.BatchAdd(entries)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = set.Swap(newSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = set.Parent.Destroy(tempName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (req *UpsertRequest) Opts(opts UpsertOpts) *UpsertRequest {\n\treq.opts = opts\n\treturn req\n}", "func (pc ParseContext) Merge(o ParseContext) {\n\tfor k, vs := range o.Args {\n\t\tpc.Args[k] = append(pc.Args[k], vs...)\n\t}\n\n\tfor k, vs := range o.Opts {\n\t\tpc.Opts[k] = append(pc.Opts[k], vs...)\n\t}\n}", "func (f *Foo) Option(opts ...option) (previous option) {\n\tfor _, opt := range opts {\n\t\tprevious = opt(f)\n\t}\n\treturn previous\n}", "func InitWith(appName string, opts ...Opt) error {\n\n\t// Add baseInitOpt.\n\topts = append(opts, &baseInitOpt{})\n\n\t// Sort by order().\n\tsort.Sort(optSlice(opts))\n\n\t// Check for duplicate Opts.\n\tfor i := 0; i < len(opts)-1; i++ {\n\t\tif opts[i].order() == opts[i+1].order() {\n\t\t\treturn fmt.Errorf(\"Only one of each type of Opt can be used.\")\n\t\t}\n\t}\n\n\t// Run all preinit's.\n\tfor _, o := range opts {\n\t\tif err := o.preinit(appName); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Run all init's.\n\tfor _, o := range opts {\n\t\tif err := o.init(appName); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tsklog.Flush()\n\treturn nil\n}", "func (o *opts) WithLogger(value ILogger) *opts {\n\tb := value\n\n\to.log = b\n\n\treturn o\n}", "func (opt ArgJoiner) argApply(o *argOptions) {\n\to.joiner = string(opt)\n}", "func (r *bitroute) UseOptionsReplies(enabled bool) {\n\tr.optionsRepliesEnabled = enabled\n}", "func (opts *clientOptions) ApplyToGithubClientOptions(target *clientOptions) error {\n\t// Apply common values, if any\n\tif err := opts.CommonClientOptions.ApplyToCommonClientOptions(&target.CommonClientOptions); err != nil {\n\t\treturn err\n\t}\n\n\tif opts.AuthTransport != nil {\n\t\t// Make sure the user didn't specify the AuthTransport twice\n\t\tif target.AuthTransport != nil {\n\t\t\treturn fmt.Errorf(\"option AuthTransport already configured: %w\", gitprovider.ErrInvalidClientOptions)\n\t\t}\n\t\ttarget.AuthTransport = opts.AuthTransport\n\t}\n\n\tif opts.EnableConditionalRequests != nil {\n\t\t// Make sure the user didn't specify the EnableConditionalRequests twice\n\t\tif target.EnableConditionalRequests != nil {\n\t\t\treturn fmt.Errorf(\"option EnableConditionalRequests already configured: %w\", gitprovider.ErrInvalidClientOptions)\n\t\t}\n\t\ttarget.EnableConditionalRequests = opts.EnableConditionalRequests\n\t}\n\treturn nil\n}", "func (o *ValidatingAdmissionPolicyStatusControllerOptions) ApplyTo(cfg *validatingadmissionpolicystatusconfig.ValidatingAdmissionPolicyStatusControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentPolicySyncs = o.ConcurrentPolicySyncs\n\n\treturn nil\n}", "func (o Option) apply(r *Upload) *Upload { return o(r).(*Upload) }", "func Options(opts ...Option) Option {\n\treturn optionFunc(func(app *App) {\n\t\tfor _, opt := range opts {\n\t\t\topt.apply(app)\n\t\t}\n\t})\n}", "func (o *arg) setDefault() error {\n\t// Only set default if it was not parsed, and default value was defined\n\tif !o.parsed && o.opts != nil && o.opts.Default != nil {\n\t\tswitch o.result.(type) {\n\t\tcase *bool, *int, *float64, *string, *[]bool, *[]int, *[]float64, *[]string:\n\t\t\tif reflect.TypeOf(o.result) != reflect.PtrTo(reflect.TypeOf(o.opts.Default)) {\n\t\t\t\treturn fmt.Errorf(\"cannot use default type [%T] as value of pointer with type [%T]\", o.opts.Default, o.result)\n\t\t\t}\n\t\t\tdefaultValue := o.opts.Default\n\t\t\tif o.argType == Flag && defaultValue == true {\n\t\t\t\tdefaultValue = false\n\t\t\t}\n\t\t\treflect.ValueOf(o.result).Elem().Set(reflect.ValueOf(defaultValue))\n\n\t\tcase *os.File:\n\t\t\tif err := o.setDefaultFile(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase *[]os.File:\n\t\t\tif err := o.setDefaultFiles(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func ApplyOptions() metav1.ApplyOptions {\n\treturn metav1.ApplyOptions{\n\t\tForce: true,\n\t\tFieldManager: ReflectionFieldManager,\n\t}\n}" ]
[ "0.6115144", "0.6088725", "0.59637165", "0.58984965", "0.5830588", "0.5801298", "0.57815975", "0.5702999", "0.565666", "0.56555563", "0.5646621", "0.56115735", "0.5607685", "0.55613136", "0.544665", "0.54299736", "0.53732026", "0.5360941", "0.53602225", "0.5359189", "0.53463626", "0.53185546", "0.5254478", "0.52499914", "0.52414244", "0.52220863", "0.52005345", "0.51565737", "0.51508826", "0.50602883", "0.50446", "0.50422925", "0.50222373", "0.50008684", "0.49593914", "0.49478236", "0.49314907", "0.49115062", "0.49010015", "0.4882883", "0.48686093", "0.48385283", "0.48344138", "0.48241627", "0.47785363", "0.4772915", "0.47682336", "0.47564518", "0.47112742", "0.46712282", "0.4660336", "0.46603277", "0.46388513", "0.461186", "0.45863086", "0.45847705", "0.45733255", "0.45632064", "0.45613116", "0.45607632", "0.45549357", "0.4549474", "0.45494205", "0.45265526", "0.44968274", "0.44871894", "0.4485298", "0.44743577", "0.44717738", "0.44705582", "0.44690394", "0.44659954", "0.44554213", "0.44248897", "0.4412186", "0.43919727", "0.43909", "0.43891436", "0.43887082", "0.4387569", "0.43822536", "0.4373321", "0.4369557", "0.43656987", "0.4361305", "0.43448114", "0.43345284", "0.43291524", "0.43077478", "0.43054658", "0.42665374", "0.42653757", "0.42541307", "0.4247906", "0.42280385", "0.4217686", "0.4212993", "0.42122132", "0.4210786", "0.42002934" ]
0.608243
2
ApplyOpts applies any values set in t to opts, if a value is not set on t, then we don't update opts and allow redispipe to use its defaults.
func (t Timeouts) ApplyOpts(opts *redisconn.Opts) { if t.Dial > 0 { opts.DialTimeout = t.Dial } if t.IO > 0 { opts.IOTimeout = t.IO } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o Opts) ApplyOpts(opts *redisconn.Opts) {\n\n\tif o.DB != nil {\n\t\topts.DB = *o.DB\n\t}\n\tif o.WritePause > 0 {\n\t\topts.WritePause = o.WritePause\n\t}\n\tif o.ReconnectPause > 0 {\n\t\topts.ReconnectPause = o.ReconnectPause\n\t}\n\tif o.TCPKeepAlive > 0 {\n\t\topts.TCPKeepAlive = o.TCPKeepAlive\n\t}\n\to.Timeouts.ApplyOpts(opts)\n}", "func (o *Options) Apply(opts ...Option) error {\n\tfor i, opt := range opts {\n\t\tif err := opt(o); err != nil {\n\t\t\treturn fmt.Errorf(\"dht option %d failed: %s\", i, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (cfg *Config) Apply(opts ...Option) error {\n\tfor _, opt := range opts {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err := opt(cfg); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func applyOptions(c *Container, opts ...Option) error {\n\tfor _, opt := range opts {\n\t\tif err := opt.set(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Options) Apply(opts ...Option) error {\n\tfor i, opt := range opts {\n\t\tif err := opt(o); err != nil {\n\t\t\treturn fmt.Errorf(\"option %d failed: %s\", i, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (ro *RequesterOptions) apply(opts ...RequesterOption) {\n\tfor _, opt := range opts {\n\t\topt(ro)\n\t}\n}", "func (o *PatchOptions) ApplyOptions(opts []PatchOption) {\n\tfor _, opt := range opts {\n\t\topt.ApplyToHelper(o)\n\t}\n}", "func (o *Options) Apply() {\n\tif o == nil {\n\t\treturn\n\t}\n\tif len(o.ShowHiddenMetricsForVersion) > 0 {\n\t\tSetShowHidden()\n\t}\n\t// set disabled metrics\n\tfor _, metricName := range o.DisabledMetrics {\n\t\tSetDisabledMetric(metricName)\n\t}\n\tif o.AllowListMapping != nil {\n\t\tSetLabelAllowListFromCLI(o.AllowListMapping)\n\t}\n}", "func (o *MatchOptions) ApplyOptions(opts []MatchOption) *MatchOptions {\n\tfor _, opt := range opts {\n\t\topt.ApplyToMatcher(o)\n\t}\n\treturn o\n}", "func (opts *Options) Apply(options ...Option) error {\n\tfor _, o := range options {\n\t\tif err := o(opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (o *ListImplementationRevisionsOptions) Apply(opts ...GetImplementationOption) {\n\tfor _, opt := range opts {\n\t\topt(o)\n\t}\n}", "func (c *Default) Update(opts ...DefaultOption) {\n\tfor _, opt := range opts {\n\t\topt.ApplyDefault(c)\n\t}\n}", "func apply(\n\ttest func(t *testing.T, conf interface{}, opts ...option),\n\tconf interface{}, opts ...option,\n) func(*testing.T) {\n\treturn func(t *testing.T) {\n\t\ttest(t, conf, opts...)\n\t}\n}", "func (o Options) Apply(i *Important) {\n\tfor _, opt := range o {\n\t\topt(i)\n\t}\n}", "func (c *AppConfig) Apply(opts []AppOption) error {\r\n\tfor _, o := range opts {\r\n\t\tif err := o(c); err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t}\r\n\treturn nil\r\n}", "func (po *SubResourcePatchOptions) ApplyOptions(opts []SubResourcePatchOption) *SubResourcePatchOptions {\n\tfor _, o := range opts {\n\t\to.ApplyToSubResourcePatch(po)\n\t}\n\n\treturn po\n}", "func (uo *SubResourceUpdateOptions) ApplyOptions(opts []SubResourceUpdateOption) *SubResourceUpdateOptions {\n\tfor _, o := range opts {\n\t\to.ApplyToSubResourceUpdate(uo)\n\t}\n\n\treturn uo\n}", "func (opts *lateInitOptions) apply(opt ...LateInitOption) {\n\tfor _, o := range opt {\n\t\to.apply(opts)\n\t}\n}", "func (f *FlagBase[T, C, V]) Apply(set *flag.FlagSet) error {\n\t// TODO move this phase into a separate flag initialization function\n\t// if flag has been applied previously then it would have already been set\n\t// from env or file. So no need to apply the env set again. However\n\t// lots of units tests prior to persistent flags assumed that the\n\t// flag can be applied to different flag sets multiple times while still\n\t// keeping the env set.\n\tif !f.applied || !f.Persistent {\n\t\tnewVal := f.Value\n\n\t\tif val, source, found := f.Sources.LookupWithSource(); found {\n\t\t\ttmpVal := f.creator.Create(f.Value, new(T), f.Config)\n\t\t\tif val != \"\" || reflect.TypeOf(f.Value).Kind() == reflect.String {\n\t\t\t\tif err := tmpVal.Set(val); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\t\"could not parse %[1]q as %[2]T value from %[3]s for flag %[4]s: %[5]s\",\n\t\t\t\t\t\tval, f.Value, source, f.Name, err,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t} else if val == \"\" && reflect.TypeOf(f.Value).Kind() == reflect.Bool {\n\t\t\t\tval = \"false\"\n\t\t\t\tif err := tmpVal.Set(val); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\t\"could not parse %[1]q as %[2]T value from %[3]s for flag %[4]s: %[5]s\",\n\t\t\t\t\t\tval, f.Value, source, f.Name, err,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnewVal = tmpVal.Get().(T)\n\t\t\tf.hasBeenSet = true\n\t\t}\n\n\t\tif f.Destination == nil {\n\t\t\tf.value = f.creator.Create(newVal, new(T), f.Config)\n\t\t} else {\n\t\t\tf.value = f.creator.Create(newVal, f.Destination, f.Config)\n\t\t}\n\n\t\t// Validate the given default or values set from external sources as well\n\t\tif f.Validator != nil {\n\t\t\tif v, ok := f.value.Get().(T); !ok {\n\t\t\t\treturn &typeError[T]{\n\t\t\t\t\tother: f.value.Get(),\n\t\t\t\t}\n\t\t\t} else if err := f.Validator(v); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tisBool := false\n\tif b, ok := f.value.(boolFlag); ok && b.IsBoolFlag() {\n\t\tisBool = true\n\t}\n\n\tfor _, name := range f.Names() {\n\t\tset.Var(&fnValue{\n\t\t\tfn: func(val string) error {\n\t\t\t\tif f.count == 1 && f.OnlyOnce {\n\t\t\t\t\treturn fmt.Errorf(\"cant duplicate this flag\")\n\t\t\t\t}\n\t\t\t\tf.count++\n\t\t\t\tif err := f.value.Set(val); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif f.Validator != nil {\n\t\t\t\t\tif v, ok := f.value.Get().(T); !ok {\n\t\t\t\t\t\treturn &typeError[T]{\n\t\t\t\t\t\t\tother: f.value.Get(),\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if err := f.Validator(v); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tisBool: isBool,\n\t\t\tv: f.value,\n\t\t}, name, f.Usage)\n\t}\n\n\tf.applied = true\n\treturn nil\n}", "func (o *Number[T]) ApplyOptions(options ...NumberOption[T]) *Number[T] {\n\tfor _, opt := range options {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\topt.apply(o)\n\t}\n\treturn o\n}", "func (opts RequestOpts) Apply(req *http.Request) {\n\t// apply per-request options\n\tfor _, o := range opts {\n\t\tif o != nil {\n\t\t\to(req)\n\t\t}\n\t}\n}", "func ApplyOptions(f *pflag.Flag, opts ...FlagOption) {\n\tfor _, opt := range opts {\n\t\topt(f)\n\t}\n}", "func (getOpt *SubResourceGetOptions) ApplyOptions(opts []SubResourceGetOption) *SubResourceGetOptions {\n\tfor _, o := range opts {\n\t\to.ApplyToSubResourceGet(getOpt)\n\t}\n\n\treturn getOpt\n}", "func (op *ReadOptions) Apply(opts ...ReadOption) {\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n}", "func (lOpts *logOptions) apply(options ...Option) {\n\tfor _, opt := range options {\n\t\topt(lOpts)\n\t}\n}", "func (d *OverloadServiceDesc) Apply(oo ...transport.DescOption) {\n\tfor _, o := range oo {\n\t\to.Apply(&d.opts)\n\t}\n}", "func (o optionFunc) ApplyOption(opts *Options) {\n\to(opts)\n}", "func (bo *BoolOptions) Apply(n models.ConfigurationMap, changed ChangedFunc, data interface{}) int {\n\tchanges := []changedOptions{}\n\n\tbo.optsMU.Lock()\n\tfor k, v := range n {\n\t\tval, ok := bo.Opts[k]\n\n\t\tif boolVal, _ := NormalizeBool(v); boolVal {\n\t\t\t/* Only enable if not enabled already */\n\t\t\tif !ok || !val {\n\t\t\t\tbo.enable(k)\n\t\t\t\tchanges = append(changes, changedOptions{key: k, value: true})\n\t\t\t}\n\t\t} else {\n\t\t\t/* Only disable if enabled already */\n\t\t\tif ok && val {\n\t\t\t\tbo.disable(k)\n\t\t\t\tchanges = append(changes, changedOptions{key: k, value: false})\n\t\t\t}\n\t\t}\n\t}\n\tbo.optsMU.Unlock()\n\n\tfor _, change := range changes {\n\t\tchanged(change.key, change.value, data)\n\t}\n\n\treturn len(changes)\n}", "func (r RequestCryptoSignerOpts) ApplyCryptoSignerOpts(opts *crypto.SignerOpts) {\n\t*opts = r.opts\n}", "func ApplyLoggerOpts(opts ...Option) LoggerOpts {\n\t// set some defaults\n\tl := LoggerOpts{\n\t\tAdditionalLocationOffset: 1,\n\t\tIncludeLocation: true,\n\t\tIncludeTime: true,\n\t\tOutput: os.Stderr,\n\t}\n\tfor _, opt := range opts {\n\t\tl = opt(l)\n\t}\n\treturn l\n}", "func (f OptionFunc) Apply(ratelimiter Ratelimiter) error {\n\treturn f(ratelimiter)\n}", "func ApplyGaugeOptions(opts *Options, gos ...GaugeOptionApplier) {\n\tfor _, o := range gos {\n\t\to.ApplyGaugeOption(opts)\n\t}\n}", "func ApplyOptions(opt ...Option) Options {\n\topts := Options{\n\t\tMaxTraversalLinks: math.MaxInt64, //default: traverse all\n\t\tMaxAllowedHeaderSize: carv1.DefaultMaxAllowedHeaderSize,\n\t\tMaxAllowedSectionSize: carv1.DefaultMaxAllowedSectionSize,\n\t}\n\tfor _, o := range opt {\n\t\to(&opts)\n\t}\n\t// Set defaults for zero valued fields.\n\tif opts.IndexCodec == 0 {\n\t\topts.IndexCodec = multicodec.CarMultihashIndexSorted\n\t}\n\tif opts.MaxIndexCidSize == 0 {\n\t\topts.MaxIndexCidSize = DefaultMaxIndexCidSize\n\t}\n\treturn opts\n}", "func (o *DeleteOptions) ApplyOptions(opts []DeleteOption) {\n\tfor _, opt := range opts {\n\t\topt.ApplyToDeleteOptions(o)\n\t}\n}", "func (o ClusterOpts) ApplyOpts(opts *rediscluster.Opts) {\n\tif o.Name != \"\" {\n\t\topts.Name = o.Name\n\t}\n}", "func (r *Repo) Apply(opts ...func(*Repo)) {\n\tif r == nil {\n\t\treturn\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(r)\n\t}\n}", "func ApplyAll(rw ReadWriter, optionSets ...[]Option) ReadWriter {\n\toptions := []Option{}\n\tfor _, optionSet := range optionSets {\n\t\toptions = append(options, optionSet...)\n\t}\n\treturn Apply(rw, options...)\n}", "func (set *Set) RefreshWithBuiltinOptions(entries [][]string) error {\n\tvar err error\n\n\t// The set-name must be < 32 characters!\n\ttempName := set.Name + \"-\"\n\n\tnewSet := &Set{\n\t\tParent: set.Parent,\n\t\tName: tempName,\n\t\tOptions: set.Options,\n\t}\n\n\terr = set.Parent.Add(newSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = newSet.BatchAdd(entries)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = set.Swap(newSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = set.Parent.Destroy(tempName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *queueInformerConfig) apply(options []Option) {\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n}", "func ApplyLayerWithOpts(ctx context.Context, layer Layer, chain []digest.Digest, sn snapshots.Snapshotter, a diff.Applier, opts []snapshots.Opt, applyOpts []diff.ApplyOpt) (bool, error) {\n\tvar (\n\t\tchainID = identity.ChainID(append(chain, layer.Diff.Digest)).String()\n\t\tapplied bool\n\t)\n\tif _, err := sn.Stat(ctx, chainID); err != nil {\n\t\tif !errdefs.IsNotFound(err) {\n\t\t\treturn false, fmt.Errorf(\"failed to stat snapshot %s: %w\", chainID, err)\n\t\t}\n\n\t\tif err := applyLayers(ctx, []Layer{layer}, append(chain, layer.Diff.Digest), sn, a, opts, applyOpts); err != nil {\n\t\t\tif !errdefs.IsAlreadyExists(err) {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t} else {\n\t\t\tapplied = true\n\t\t}\n\t}\n\treturn applied, nil\n\n}", "func (opt option) apply(o interface{}) error {\n\tswitch v := o.(type) {\n\tcase *TableEncoder:\n\t\tif opt.table != nil {\n\t\t\treturn opt.table(v)\n\t\t}\n\t\treturn nil\n\tcase *ExpandedEncoder:\n\t\tif opt.expanded != nil {\n\t\t\treturn opt.expanded(v)\n\t\t}\n\t\treturn nil\n\tcase *JSONEncoder:\n\t\tif opt.json != nil {\n\t\t\treturn opt.json(v)\n\t\t}\n\t\treturn nil\n\tcase *UnalignedEncoder:\n\t\tif opt.unaligned != nil {\n\t\t\treturn opt.unaligned(v)\n\t\t}\n\t\treturn nil\n\tcase *TemplateEncoder:\n\t\tif opt.template != nil {\n\t\t\treturn opt.template(v)\n\t\t}\n\t\treturn nil\n\tcase *CrosstabView:\n\t\tif opt.crosstab != nil {\n\t\t\treturn opt.crosstab(v)\n\t\t}\n\t\treturn nil\n\tcase *errEncoder:\n\t\tif opt.err != nil {\n\t\t\treturn opt.err(v)\n\t\t}\n\t\treturn nil\n\t}\n\tpanic(fmt.Sprintf(\"option cannot be applied to %T\", o))\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"key_not_required\":\n\t\t\t\tkeyNotRequired, err := strconv.ParseBool(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\topts.withKeyNotRequired = keyNotRequired\n\t\t\tcase \"user_agent\":\n\t\t\t\topts.withUserAgent = v\n\t\t\tcase \"credentials\":\n\t\t\t\topts.withCredentials = v\n\t\t\tcase \"project\":\n\t\t\t\topts.withProject = v\n\t\t\tcase \"region\":\n\t\t\t\topts.withRegion = v\n\t\t\tcase \"key_ring\":\n\t\t\t\topts.withKeyRing = v\n\t\t\tcase \"crypto_key\":\n\t\t\t\topts.withCryptoKey = v\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func (o *JSONPb) ApplyOptions(options ...JSONPbOption) *JSONPb {\n\tfor _, opt := range options {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\topt.apply(o)\n\t}\n\treturn o\n}", "func (c *operatorConfig) apply(options []OperatorOption) {\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n}", "func ApplyOptions(optsGetter Getter, store *genericetcd.Etcd, etcdPrefix string) error {\n\tif store.QualifiedResource.IsEmpty() {\n\t\treturn fmt.Errorf(\"store must have a non-empty qualified resource\")\n\t}\n\tif store.NewFunc == nil {\n\t\treturn fmt.Errorf(\"store for %s must have NewFunc set\", store.QualifiedResource.String())\n\t}\n\tif store.NewListFunc == nil {\n\t\treturn fmt.Errorf(\"store for %s must have NewListFunc set\", store.QualifiedResource.String())\n\t}\n\tif store.CreateStrategy == nil {\n\t\treturn fmt.Errorf(\"store for %s must have CreateStrategy set\", store.QualifiedResource.String())\n\t}\n\n\topts, err := optsGetter.GetRESTOptions(store.QualifiedResource)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error building RESTOptions for %s store: %v\", store.QualifiedResource.String(), err)\n\t}\n\n\tstore.DeleteCollectionWorkers = opts.DeleteCollectionWorkers\n\tstore.Storage = opts.Decorator(opts.Storage, UseConfiguredCacheSize, store.NewFunc(), etcdPrefix, store.CreateStrategy, store.NewListFunc)\n\treturn nil\n\n}", "func buildConfig(opts []Option) config {\n\tc := config{\n\t\tclock: clock.New(),\n\t\tslack: 10,\n\t\tper: time.Second,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt.apply(&c)\n\t}\n\treturn c\n}", "func Apply(rw ReadWriter, options ...Option) ReadWriter {\n\tfor _, option := range options {\n\t\toption(rw)\n\t}\n\treturn applyOptionsForState(rw)\n}", "func buildConfig(opts []Option) config {\r\n\tc := config{\r\n\t\tclock: clock.New(),\r\n\t\tmaxSlack: 10,\r\n\t\tper: time.Second,\r\n\t}\r\n\tfor _, opt := range opts {\r\n\t\topt.apply(&c)\r\n\t}\r\n\treturn c\r\n}", "func ApplyMeasureOptions(opts *Options, mos ...MeasureOptionApplier) {\n\tfor _, o := range mos {\n\t\to.ApplyMeasureOption(opts)\n\t}\n}", "func (o *Options) applyDefaults(in *componentconfig.CoordinatorConfiguration) (*componentconfig.CoordinatorConfiguration, error) {\n\tcomponentconfig.SetDefaultsCoordinatorConfiguration(in)\n\treturn in, nil\n}", "func (opts *clientOptions) ApplyToGithubClientOptions(target *clientOptions) error {\n\t// Apply common values, if any\n\tif err := opts.CommonClientOptions.ApplyToCommonClientOptions(&target.CommonClientOptions); err != nil {\n\t\treturn err\n\t}\n\n\tif opts.AuthTransport != nil {\n\t\t// Make sure the user didn't specify the AuthTransport twice\n\t\tif target.AuthTransport != nil {\n\t\t\treturn fmt.Errorf(\"option AuthTransport already configured: %w\", gitprovider.ErrInvalidClientOptions)\n\t\t}\n\t\ttarget.AuthTransport = opts.AuthTransport\n\t}\n\n\tif opts.EnableConditionalRequests != nil {\n\t\t// Make sure the user didn't specify the EnableConditionalRequests twice\n\t\tif target.EnableConditionalRequests != nil {\n\t\t\treturn fmt.Errorf(\"option EnableConditionalRequests already configured: %w\", gitprovider.ErrInvalidClientOptions)\n\t\t}\n\t\ttarget.EnableConditionalRequests = opts.EnableConditionalRequests\n\t}\n\treturn nil\n}", "func (o ClientOptions) ApplyDefaults(ctx context.Context, defaultDesc string) ClientOptions {\n\tif o.Hostname == \"\" {\n\t\to.Hostname = GetDefaultHostName(ctx)\n\t}\n\n\tif o.Username == \"\" {\n\t\to.Username = GetDefaultUserName(ctx)\n\t}\n\n\tif o.Description == \"\" {\n\t\to.Description = defaultDesc\n\t}\n\n\tif o.FormatBlobCacheDuration == 0 {\n\t\to.FormatBlobCacheDuration = format.DefaultRepositoryBlobCacheDuration\n\t}\n\n\treturn o\n}", "func (f FilterParams) ApplyToDeploySettings(d *bosun.DeploySettings) {\n\tif !f.IsEmpty() {\n\t\tchain := f.Chain()\n\t\td.Filter = &chain\n\t}\n}", "func (opts *Opts) updateOptions() {\n\tfor option := range opts.rs.edges {\n\t\tif _, ok := opts.options[option]; !ok {\n\t\t\t// by default the option state is false\n\t\t\topts.options[option] = false\n\t\t\t// if a parent exist the new option takes its state\n\t\t\tif len(opts.rs.edges[option]) > 0 {\n\t\t\t\tparent := opts.rs.edges[option][0] // TODO: what if there are multiple parents?\n\t\t\t\topts.options[option] = opts.options[parent]\n\t\t\t}\n\t\t}\n\t}\n\n\tfor option := range opts.rs.conflicts {\n\t\tif _, ok := opts.options[option]; !ok {\n\t\t\topts.options[option] = false\n\t\t}\n\t}\n}", "func (o *DB) ApplyOptions(options ...DBOption) *DB {\n\tfor _, opt := range options {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\topt.apply(o)\n\t}\n\treturn o\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"mount_path\":\n\t\t\t\topts.withMountPath = v\n\t\t\tcase \"key_name\":\n\t\t\t\topts.withKeyName = v\n\t\t\tcase \"disable_renewal\":\n\t\t\t\topts.withDisableRenewal = v\n\t\t\tcase \"namespace\":\n\t\t\t\topts.withNamespace = v\n\t\t\tcase \"address\":\n\t\t\t\topts.withAddress = v\n\t\t\tcase \"tls_ca_cert\":\n\t\t\t\topts.withTlsCaCert = v\n\t\t\tcase \"tls_ca_path\":\n\t\t\t\topts.withTlsCaPath = v\n\t\t\tcase \"tls_client_cert\":\n\t\t\t\topts.withTlsClientCert = v\n\t\t\tcase \"tls_client_key\":\n\t\t\t\topts.withTlsClientKey = v\n\t\t\tcase \"tls_server_name\":\n\t\t\t\topts.withTlsServerName = v\n\t\t\tcase \"tls_skip_verify\":\n\t\t\t\tvar err error\n\t\t\t\topts.withTlsSkipVerify, err = strconv.ParseBool(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\tcase \"token\":\n\t\t\t\topts.withToken = v\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func transformOptions(options ...interface{}) map[string]interface{} {\n\tvar base map[string]interface{}\n\tvar option interface{}\n\t// Case 1: No options are given\n\tif len(options) == 0 {\n\t\treturn make(map[string]interface{})\n\t}\n\tif len(options) == 1 {\n\t\t// Case 2: a single value (either struct or map) is given.\n\t\tbase = make(map[string]interface{})\n\t\toption = options[0]\n\t} else if len(options) == 2 {\n\t\t// Case 3: two values are given. The first one needs to be a map and the\n\t\t// second one can be a struct or map. It will be then get merged into the first\n\t\t// base map.\n\t\tbase = transformStructIntoMapIfNeeded(options[0])\n\t\toption = options[1]\n\t}\n\tv := reflect.ValueOf(option)\n\tif v.Kind() == reflect.Slice {\n\t\tif v.Len() == 0 {\n\t\t\treturn base\n\t\t}\n\t\toption = v.Index(0).Interface()\n\t}\n\n\tif option == nil {\n\t\treturn base\n\t}\n\tv = reflect.ValueOf(option)\n\n\tif v.Kind() == reflect.Ptr {\n\t\tv = v.Elem()\n\t}\n\n\toptionMap := transformStructIntoMapIfNeeded(v.Interface())\n\tfor key, value := range optionMap {\n\t\tbase[key] = value\n\t}\n\treturn base\n}", "func (c *Config) SetOpt(opts ...Option) Option {\n\t// apply all the options, and replace each with its inverse\n\tfor i, opt := range opts {\n\t\topts[i] = opt(c)\n\t}\n\n\tfor i, j := 0, len(opts)-1; i <= j; i, j = i+1, j-1 {\n\t\topts[i], opts[j] = opts[j], opts[i]\n\t}\n\n\treturn func(c *Config) Option {\n\t\treturn c.SetOpt(opts...)\n\t}\n}", "func (e *ExternalService) Apply(opts ...func(*ExternalService)) {\n\tif e == nil {\n\t\treturn\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(e)\n\t}\n}", "func flattenOptions(dst, src Options) Options {\n\tfor _, opt := range src {\n\t\tswitch opt := opt.(type) {\n\t\tcase nil:\n\t\t\tcontinue\n\t\tcase Options:\n\t\t\tdst = flattenOptions(dst, opt)\n\t\tcase coreOption:\n\t\t\tdst = append(dst, opt)\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"invalid option type: %T\", opt))\n\t\t}\n\t}\n\treturn dst\n}", "func (s *snapshot) ApplyOptions() Actionable {\n\ts.options = s.context.Options().(*options.SnapshotOptions)\n\n\tif len(s.options.Name) == 0 {\n\t\ts.options.Name = \"github.com/alejandro-carstens/scrubber-\" + time.Now().Format(\"1992-06-02\")\n\t}\n\n\tif !s.options.Exists(\"wait_for_completion\") {\n\t\ts.options.WaitForCompletion = DEFAULT_WAIT_FOR_COMPLETION\n\t}\n\n\tif !s.options.WaitForCompletion {\n\t\tif !s.options.Exists(\"max_wait\") {\n\t\t\ts.options.MaxWait = DEFAULT_MAX_WAIT\n\t\t}\n\n\t\tif !s.options.Exists(\"wait_interval\") {\n\t\t\ts.options.WaitInterval = DEFAULT_WAIT_INTERVAL\n\t\t}\n\t}\n\n\ts.indexer.SetOptions(&golastic.IndexOptions{\n\t\tTimeout: s.options.TimeoutInSeconds(),\n\t\tWaitForCompletion: s.options.WaitForCompletion,\n\t\tPartial: s.options.Partial,\n\t\tIncludeGlobalState: s.options.IncludeGlobalState,\n\t\tIgnoreUnavailable: s.options.IgnoreUnavailable,\n\t})\n\n\treturn s\n}", "func (req *SelectRequest) Opts(opts SelectOpts) *SelectRequest {\n\treq.opts = opts\n\treturn req\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tvar err error\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"aead_type\":\n\t\t\t\topts.WithAeadType = wrapping.AeadTypeMap(v)\n\t\t\tcase \"hash_type\":\n\t\t\t\topts.WithHashType = wrapping.HashTypeMap(v)\n\t\t\tcase \"key\":\n\t\t\t\topts.WithKey, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding key value: %w\", err)\n\t\t\t\t}\n\t\t\tcase \"salt\":\n\t\t\t\topts.WithSalt, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding salt value: %w\", err)\n\t\t\t\t}\n\t\t\tcase \"info\":\n\t\t\t\topts.WithInfo, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding info value: %w\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func (p *Porter) applyActionOptionsToInstallation(ctx context.Context, ba BundleAction, inst *storage.Installation) error {\n\tctx, span := tracing.StartSpan(ctx)\n\tdefer span.EndSpan()\n\n\to := ba.GetOptions()\n\n\tbundleRef, err := o.GetBundleReference(ctx, p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbun := bundleRef.Definition\n\n\t// Update the installation with metadata from the options\n\tinst.TrackBundle(bundleRef.Reference)\n\tinst.Status.Modified = time.Now()\n\n\t//\n\t// 1. Record the parameter and credential sets used on the installation\n\t// if none were specified, reuse the previous sets from the installation\n\t//\n\tspan.SetAttributes(\n\t\ttracing.ObjectAttribute(\"override-parameter-sets\", o.ParameterSets),\n\t\ttracing.ObjectAttribute(\"override-credential-sets\", o.CredentialIdentifiers))\n\tif len(o.ParameterSets) > 0 {\n\t\tinst.ParameterSets = o.ParameterSets\n\t}\n\tif len(o.CredentialIdentifiers) > 0 {\n\t\tinst.CredentialSets = o.CredentialIdentifiers\n\t}\n\n\t//\n\t// 2. Parse parameter flags from the command line and apply to the installation as overrides\n\t//\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"override-parameters\", o.Params))\n\tparsedOverrides, err := storage.ParseVariableAssignments(o.Params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Default the porter-debug param to --debug\n\tif o.DebugMode {\n\t\tparsedOverrides[\"porter-debug\"] = \"true\"\n\t}\n\n\t// Apply overrides on to of any pre-existing parameters that were specified previously\n\tif len(parsedOverrides) > 0 {\n\t\tfor name, value := range parsedOverrides {\n\t\t\t// Do not resolve parameters from dependencies\n\t\t\tif strings.Contains(name, \"#\") {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Replace previous value if present\n\t\t\treplaced := false\n\t\t\tparamStrategy := storage.ValueStrategy(name, value)\n\t\t\tfor i, existingParam := range inst.Parameters.Parameters {\n\t\t\t\tif existingParam.Name == name {\n\t\t\t\t\tinst.Parameters.Parameters[i] = paramStrategy\n\t\t\t\t\treplaced = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !replaced {\n\t\t\t\tinst.Parameters.Parameters = append(inst.Parameters.Parameters, paramStrategy)\n\t\t\t}\n\t\t}\n\n\t\t// Keep the parameter overrides sorted, so that comparisons and general troubleshooting is easier\n\t\tsort.Sort(inst.Parameters.Parameters)\n\t}\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"merged-installation-parameters\", inst.Parameters.Parameters))\n\n\t//\n\t// 3. Resolve named parameter sets\n\t//\n\tresolvedParams, err := p.loadParameterSets(ctx, bun, o.Namespace, inst.ParameterSets)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to process provided parameter sets: %w\", err)\n\t}\n\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"resolved-parameter-sets-keys\", resolvedParams))\n\n\t//\n\t// 4. Resolve the installation's internal parameter set\n\tresolvedOverrides, err := p.Parameters.ResolveAll(ctx, inst.Parameters)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"resolved-installation-parameters\", inst.Parameters.Parameters))\n\n\t//\n\t// 5. Apply the overrides on top of the parameter sets\n\t//\n\tfor k, v := range resolvedOverrides {\n\t\tresolvedParams[k] = v\n\t}\n\n\t//\n\t// 6. Separate out params for the root bundle from the ones intended for dependencies\n\t// This only applies to the dep v1 implementation, in dep v2 you can't specify rando params for deps\n\t//\n\to.depParams = make(map[string]string)\n\tfor k, v := range resolvedParams {\n\t\tif strings.Contains(k, \"#\") {\n\t\t\to.depParams[k] = v\n\t\t\tdelete(resolvedParams, k)\n\t\t}\n\t}\n\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"user-specified-parameters\", resolvedParams))\n\n\t//\n\t// 7. When a parameter is not specified, fallback to a parameter source or default\n\t//\n\tfinalParams, err := p.finalizeParameters(ctx, *inst, bun, ba.GetAction(), resolvedParams)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"final-parameters\", finalParams))\n\n\t// Remember the final set of parameters so we don't have to resolve them more than once\n\to.finalParams = finalParams\n\n\t// Ensure we aren't storing any secrets on the installation resource\n\tif err = p.sanitizeInstallation(ctx, inst, bundleRef.Definition); err != nil {\n\t\treturn err\n\t}\n\n\t// re-validate the installation since we modified it here\n\treturn inst.Validate(ctx, p.GetSchemaCheckStrategy(ctx))\n}", "func fromOptions(options []Option) *baseSettings {\n\t// Start from the default options:\n\topts := &baseSettings{\n\t\tconsumerOptions: []consumer.Option{consumer.WithCapabilities(consumer.Capabilities{MutatesData: true})},\n\t}\n\n\tfor _, op := range options {\n\t\top(opts)\n\t}\n\n\treturn opts\n}", "func InitWith(appName string, opts ...Opt) error {\n\n\t// Add baseInitOpt.\n\topts = append(opts, &baseInitOpt{})\n\n\t// Sort by order().\n\tsort.Sort(optSlice(opts))\n\n\t// Check for duplicate Opts.\n\tfor i := 0; i < len(opts)-1; i++ {\n\t\tif opts[i].order() == opts[i+1].order() {\n\t\t\treturn fmt.Errorf(\"Only one of each type of Opt can be used.\")\n\t\t}\n\t}\n\n\t// Run all preinit's.\n\tfor _, o := range opts {\n\t\tif err := o.preinit(appName); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Run all init's.\n\tfor _, o := range opts {\n\t\tif err := o.init(appName); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tsklog.Flush()\n\treturn nil\n}", "func SetDefaultOpts(c *Opts) error {\n\tif c.OperatingSystem == \"\" {\n\t\tc.OperatingSystem = DefaultOperatingSystem\n\t}\n\n\tif c.NodeName == \"\" {\n\t\tc.NodeName = getEnv(\"DEFAULT_NODE_NAME\", DefaultNodeName)\n\t}\n\n\tif c.InformerResyncPeriod == 0 {\n\t\tc.InformerResyncPeriod = DefaultInformerResyncPeriod\n\t}\n\n\tif c.MetricsAddr == \"\" {\n\t\tc.MetricsAddr = DefaultMetricsAddr\n\t}\n\n\tif c.PodSyncWorkers == 0 {\n\t\tc.PodSyncWorkers = DefaultPodSyncWorkers\n\t}\n\n\tif c.TraceConfig.ServiceName == \"\" {\n\t\tc.TraceConfig.ServiceName = DefaultNodeName\n\t}\n\n\tif c.ListenPort == 0 {\n\t\tif kp := os.Getenv(\"KUBELET_PORT\"); kp != \"\" {\n\t\t\tp, err := strconv.Atoi(kp)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"error parsing KUBELET_PORT environment variable\")\n\t\t\t}\n\t\t\tif p > maxInt32 {\n\t\t\t\treturn fmt.Errorf(\"KUBELET_PORT environment variable is too large\")\n\t\t\t}\n\t\t\t/* #nosec */\n\t\t\tc.ListenPort = int32(p)\n\t\t} else {\n\t\t\tc.ListenPort = DefaultListenPort\n\t\t}\n\t}\n\n\tif c.KubeNamespace == \"\" {\n\t\tc.KubeNamespace = DefaultKubeNamespace\n\t}\n\n\tif c.KubeClusterDomain == \"\" {\n\t\tc.KubeClusterDomain = DefaultKubeClusterDomain\n\t}\n\n\tif c.TaintKey == \"\" {\n\t\tc.TaintKey = DefaultTaintKey\n\t}\n\tif c.TaintEffect == \"\" {\n\t\tc.TaintEffect = DefaultTaintEffect\n\t}\n\n\tif c.KubeConfigPath == \"\" {\n\t\tc.KubeConfigPath = os.Getenv(\"KUBECONFIG\")\n\t\tif c.KubeConfigPath == \"\" {\n\t\t\thome, _ := homedir.Dir()\n\t\t\tif home != \"\" {\n\t\t\t\tc.KubeConfigPath = filepath.Join(home, \".kube\", \"config\")\n\t\t\t}\n\t\t}\n\t}\n\n\tif c.StreamIdleTimeout == 0 {\n\t\tc.StreamIdleTimeout = DefaultStreamIdleTimeout\n\t}\n\n\tif c.StreamCreationTimeout == 0 {\n\t\tc.StreamCreationTimeout = DefaultStreamCreationTimeout\n\t}\n\n\treturn nil\n}", "func (c *Canvas) SetCellOpts(p image.Point, opts ...cell.Option) error {\n\tcurCell, err := c.Cell(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(opts) == 0 {\n\t\t// Set the default options.\n\t\topts = []cell.Option{\n\t\t\tcell.FgColor(cell.ColorDefault),\n\t\t\tcell.BgColor(cell.ColorDefault),\n\t\t}\n\t}\n\tif _, err := c.SetCell(p, curCell.Rune, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (flag *SliceFlag[T]) Apply(set *libflag.FlagSet) error {\n\tif flag.Splitter == nil {\n\t\tflag.Splitter = FlagSplitter\n\t}\n\n\tif flag.EnvVarSep == \"\" {\n\t\tflag.EnvVarSep = SliceFlagEnvVarSep\n\t}\n\n\tvar err error\n\tvalType := FlagType[T](new(genericType[T]))\n\n\tif flag.FlagValue, err = newSliceValue(valType, flag.LookupEnv(flag.EnvVar), flag.EnvVarSep, flag.Splitter, flag.Destination); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, name := range flag.Names() {\n\t\tset.Var(flag.FlagValue, name, flag.Usage)\n\t}\n\treturn nil\n}", "func (f RatingOptFunc) Apply(r *Rating) {\n\tf(r)\n}", "func (config *Configuration) ApplyOverrides(overrides map[string]string) error {\n\tmatch := func(s1 string) func(string) bool {\n\t\treturn func(s2 string) bool {\n\t\t\treturn strings.ToLower(s2) == s1\n\t\t}\n\t}\n\telem := reflect.ValueOf(config).Elem()\n\tfor k, v := range overrides {\n\t\tsplit := strings.Split(strings.ToLower(k), \".\")\n\t\tif len(split) != 2 {\n\t\t\treturn fmt.Errorf(\"Bad option format: %s\", k)\n\t\t}\n\t\tfield := elem.FieldByNameFunc(match(split[0]))\n\t\tif !field.IsValid() {\n\t\t\treturn fmt.Errorf(\"Unknown config field: %s\", split[0])\n\t\t} else if field.Kind() != reflect.Struct {\n\t\t\treturn fmt.Errorf(\"Unsettable config field: %s\", split[0])\n\t\t}\n\t\tfield = field.FieldByNameFunc(match(split[1]))\n\t\tif !field.IsValid() {\n\t\t\treturn fmt.Errorf(\"Unknown config field: %s\", split[1])\n\t\t}\n\t\tswitch field.Kind() {\n\t\tcase reflect.String:\n\t\t\tfield.Set(reflect.ValueOf(v))\n\t\tcase reflect.Bool:\n\t\t\tv = strings.ToLower(v)\n\t\t\t// Mimics the set of truthy things gcfg accepts in our config file.\n\t\t\tfield.SetBool(v == \"true\" || v == \"yes\" || v == \"on\" || v == \"1\")\n\t\tcase reflect.Int:\n\t\t\ti, err := strconv.Atoi(v)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Invalid value for an integer field: %s\", v)\n\t\t\t}\n\t\t\tfield.Set(reflect.ValueOf(i))\n\t\tcase reflect.Int64:\n\t\t\tvar d cli.Duration\n\t\t\tif err := d.UnmarshalText([]byte(v)); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Invalid value for a duration field: %s\", v)\n\t\t\t}\n\t\t\tfield.Set(reflect.ValueOf(d))\n\t\tcase reflect.Slice:\n\t\t\t// We only have to worry about slices of strings. Comma-separated values are accepted.\n\t\t\tfield.Set(reflect.ValueOf(strings.Split(v, \",\")))\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"Can't override config field %s (is %s)\", k, field.Kind())\n\t\t}\n\t}\n\treturn nil\n}", "func (co *SubResourceCreateOptions) ApplyOptions(opts []SubResourceCreateOption) *SubResourceCreateOptions {\n\tfor _, o := range opts {\n\t\to.ApplyToSubResourceCreate(co)\n\t}\n\n\treturn co\n}", "func Cond(apply bool, options ...types.Option) types.Option {\n\tif apply {\n\t\treturn func(g *types.Cmd) {\n\t\t\tg.ApplyOptions(options...)\n\t\t}\n\t}\n\treturn NoOp\n}", "func ApplyLayersWithOpts(ctx context.Context, layers []Layer, sn snapshots.Snapshotter, a diff.Applier, applyOpts []diff.ApplyOpt) (digest.Digest, error) {\n\tchain := make([]digest.Digest, len(layers))\n\tfor i, layer := range layers {\n\t\tchain[i] = layer.Diff.Digest\n\t}\n\tchainID := identity.ChainID(chain)\n\n\t// Just stat top layer, remaining layers will have their existence checked\n\t// on prepare. Calling prepare on upper layers first guarantees that upper\n\t// layers are not removed while calling stat on lower layers\n\t_, err := sn.Stat(ctx, chainID.String())\n\tif err != nil {\n\t\tif !errdefs.IsNotFound(err) {\n\t\t\treturn \"\", fmt.Errorf(\"failed to stat snapshot %s: %w\", chainID, err)\n\t\t}\n\n\t\tif err := applyLayers(ctx, layers, chain, sn, a, nil, applyOpts); err != nil && !errdefs.IsAlreadyExists(err) {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn chainID, nil\n}", "func (lOpts *logOptions) applyDefault() {\n\tlOpts.skipFrameCount = 2\n\tlOpts.colors = true\n\tlOpts.logLevel = TRACE\n\tlOpts.filePath = false\n\tlOpts.funcPath = false\n\tlOpts.writer = os.Stdout\n\tlOpts.output = OutText\n}", "func (c *MockClient) ApplyOption(opt MockClientOption) {\n\topt(c)\n}", "func (r *bitroute) UseOptionsReplies(enabled bool) {\n\tr.optionsRepliesEnabled = enabled\n}", "func (b *CleanupPolicySpecApplyConfiguration) WithContext(values ...*v1.ContextEntryApplyConfiguration) *CleanupPolicySpecApplyConfiguration {\n\tfor i := range values {\n\t\tif values[i] == nil {\n\t\t\tpanic(\"nil value passed to WithContext\")\n\t\t}\n\t\tb.Context = append(b.Context, *values[i])\n\t}\n\treturn b\n}", "func Apply(c Config) {\n\t// Normalize values\n\tif c.StdErrThreshold == 0 {\n\t\tc.StdErrThreshold = DefaultConfig.StdErrThreshold\n\t}\n\n\tif c.Verbosity == 0 {\n\t\tc.Verbosity = DefaultConfig.Verbosity\n\t}\n\n\tif c.OutputDir == \"\" {\n\t\tc.OutputDir = DefaultConfig.OutputDir\n\t}\n\n\t// Mimic flag.Set\n\tlogging.toStderr = (c.Output == OutputStdErr)\n\tlogging.alsoToStderr = (c.Output == OutputBoth)\n\tlogging.stderrThreshold.Set(strconv.FormatInt(int64(c.StdErrThreshold), 10))\n\tlogging.verbosity.Set(strconv.FormatInt(int64(c.Verbosity), 10))\n\n\tvmodules := make([]string, len(c.VerbosityModules))\n\tfor i, vm := range c.VerbosityModules {\n\t\tvmodules[i] = fmt.Sprintf(\"%s=%s\", vm.Module, vm.Verbosity)\n\t}\n\tlogging.vmodule.Set(strings.Join(vmodules, \",\"))\n\n\t// See glog_file.go\n\tlogDirs = []string{c.OutputDir}\n}", "func (opts *Options) SetDefaults() {\n for name, _ := range opts.opt_map {\n //fmt.Printf(\"%s\\n\",name);\n opts.opt_map[name].SetDefault()\n }\n}", "func setConfigs(apiClient client.ConfigAPIClient, service *swarm.ServiceSpec, opts *serviceOptions) error {\n\tspecifiedConfigs := opts.configs.Value()\n\t// if the user has requested to use a Config, for the CredentialSpec add it\n\t// to the specifiedConfigs as a RuntimeTarget.\n\tif cs := opts.credentialSpec.Value(); cs != nil && cs.Config != \"\" {\n\t\tspecifiedConfigs = append(specifiedConfigs, &swarm.ConfigReference{\n\t\t\tConfigName: cs.Config,\n\t\t\tRuntime: &swarm.ConfigReferenceRuntimeTarget{},\n\t\t})\n\t}\n\tif len(specifiedConfigs) > 0 {\n\t\t// parse and validate configs\n\t\tconfigs, err := ParseConfigs(apiClient, specifiedConfigs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tservice.TaskTemplate.ContainerSpec.Configs = configs\n\t\t// if we have a CredentialSpec Config, find its ID and rewrite the\n\t\t// field on the spec\n\t\t//\n\t\t// we check the opts instead of the service directly because there are\n\t\t// a few layers of nullable objects in the service, which is a PITA\n\t\t// to traverse, but the existence of the option implies that those are\n\t\t// non-null.\n\t\tif cs := opts.credentialSpec.Value(); cs != nil && cs.Config != \"\" {\n\t\t\tfor _, config := range configs {\n\t\t\t\tif config.ConfigName == cs.Config {\n\t\t\t\t\tservice.TaskTemplate.ContainerSpec.Privileges.CredentialSpec.Config = config.ConfigID\n\t\t\t\t\t// we've found the right config, no need to keep iterating\n\t\t\t\t\t// through the rest of them.\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func mergeOptions(pas []v1.Patch) []resource.ApplyOption {\n\topts := make([]resource.ApplyOption, 0, len(pas))\n\tfor _, p := range pas {\n\t\tif p.Policy == nil || p.ToFieldPath == nil {\n\t\t\tcontinue\n\t\t}\n\t\topts = append(opts, withMergeOptions(*p.ToFieldPath, p.Policy.MergeOptions))\n\t}\n\treturn opts\n}", "func (o *Options) ValidateAndApply(featureGate featuregate.FeatureGate) error {\n\terrs := o.validate()\n\tif len(errs) > 0 {\n\t\treturn utilerrors.NewAggregate(errs)\n\t}\n\to.apply(featureGate)\n\treturn nil\n}", "func (t1 *Target) EqualWithOpts(t2 *Target, ignoreID,\n\tignoreTS, ignoreForeign bool) bool {\n\tt1Copy := t1.Target.DeepCopy()\n\tt2Copy := t2.Target.DeepCopy()\n\n\tif ignoreID {\n\t\tt1Copy.ID = nil\n\t\tt2Copy.ID = nil\n\t}\n\tif ignoreTS {\n\t\tt1Copy.CreatedAt = nil\n\t\tt2Copy.CreatedAt = nil\n\t}\n\tif ignoreForeign {\n\t\tt1Copy.Upstream = nil\n\t\tt2Copy.Upstream = nil\n\t}\n\treturn reflect.DeepEqual(t1Copy, t2Copy)\n}", "func (i AllowPaths) ApplyToMatcher(opts *MatchOptions) {\n\topts.allowPaths = append(opts.allowPaths, i...)\n}", "func (c *Currency) Option(opts ...OptionFunc) (previous OptionFunc) {\n\tfor _, o := range opts {\n\t\tif o != nil {\n\t\t\tprevious = o(c)\n\t\t}\n\t}\n\treturn previous\n}", "func(s *SetImp) Apply(t Target, a Action) os.Error {\n\tif err := t.ApplyPreq(a); err != nil { return err }\n\tif err := t.Apply(a); err != nil { return err }\n\treturn nil\n}", "func (sso *StartSpanOptions) Apply(opt opentracing.StartSpanOption) {\n\topt.Apply(&sso.OpenTracingOptions)\n\tif o, ok := opt.(StartSpanOption); ok {\n\t\to.ApplyBP(sso)\n\t}\n}", "func ApplyCounterOptions(opts *Options, cos ...CounterOptionApplier) {\n\tfor _, o := range cos {\n\t\to.ApplyCounterOption(opts)\n\t}\n}", "func (w *Workspace) optionSet(updates []interface{}) {\n\toptionName := updates[1]\n\twid := util.ReflectToInt(updates[4])\n\t// new, err := strconv.Atoi(updates[2].(string))\n\t// if err != nil {\n\t// \treturn\n\t// }\n\n\tw.optionsetMutex.Lock()\n\tswitch optionName {\n\tcase editor.config.Editor.OptionsToUseGuideWidth:\n\t\tw.setBuffTS(wid)\n\n\t}\n\tw.optionsetMutex.Unlock()\n}", "func (o *Options) apply(featureGate featuregate.FeatureGate) {\n\tcontextualLoggingEnabled := contextualLoggingDefault\n\tif featureGate != nil {\n\t\tcontextualLoggingEnabled = featureGate.Enabled(ContextualLogging)\n\t}\n\n\t// if log format not exists, use nil loggr\n\tfactory, _ := registry.LogRegistry.Get(o.Config.Format)\n\tif factory == nil {\n\t\tklog.ClearLogger()\n\t} else {\n\t\t// This logger will do its own verbosity checking, using the exact same\n\t\t// configuration as klog itself.\n\t\tlog, flush := factory.Create(o.Config)\n\t\t// Therefore it can get called directly. However, we only allow that\n\t\t// when the feature is enabled.\n\t\tklog.SetLoggerWithOptions(log, klog.ContextualLogger(contextualLoggingEnabled), klog.FlushLogger(flush))\n\t}\n\tif err := loggingFlags.Lookup(\"v\").Value.Set(o.Config.Verbosity.String()); err != nil {\n\t\tpanic(fmt.Errorf(\"internal error while setting klog verbosity: %v\", err))\n\t}\n\tif err := loggingFlags.Lookup(\"vmodule\").Value.Set(o.Config.VModule.String()); err != nil {\n\t\tpanic(fmt.Errorf(\"internal error while setting klog vmodule: %v\", err))\n\t}\n\tklog.StartFlushDaemon(o.Config.FlushFrequency)\n\tklog.EnableContextualLogging(contextualLoggingEnabled)\n}", "func MustSetCellOpts(bc *braille.Canvas, cellPoint image.Point, opts ...cell.Option) {\n\tif err := bc.SetCellOpts(cellPoint, opts...); err != nil {\n\t\tpanic(fmt.Sprintf(\"bc.SetCellOpts => unexpected error: %v\", err))\n\t}\n}", "func (o *OptionsProvider) Options(opts ...Option) *OptionsProvider {\n\tfor _, opt := range opts {\n\t\toptType := reflect.TypeOf(opt)\n\t\tif _, ok := optType.FieldByName(\"Value\"); !ok {\n\t\t\tpanic(fmt.Sprintf(\"Option %v doesn't have a Value field.\", optType.Name()))\n\t\t}\n\t\tfieldName := o.m[optType.Name()]\n\t\tfield := reflect.ValueOf(o.spec).Elem().FieldByName(fieldName)\n\t\tif !field.CanSet() || !field.IsValid() {\n\t\t\tpanic(fmt.Sprintf(\"There is no option %v.\", optType.Name()))\n\t\t}\n\t\tfield.Set(reflect.ValueOf(opt))\n\t\to.set[fieldName] = true\n\t}\n\treturn o\n}", "func (o *EphemeralVolumeControllerOptions) ApplyTo(cfg *ephemeralvolumeconfig.EphemeralVolumeControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentEphemeralVolumeSyncs = o.ConcurrentEphemeralVolumeSyncs\n\n\treturn nil\n}", "func ApplyOptions() metav1.ApplyOptions {\n\treturn metav1.ApplyOptions{\n\t\tForce: true,\n\t\tFieldManager: ReflectionFieldManager,\n\t}\n}", "func (req *UpsertRequest) Opts(opts UpsertOpts) *UpsertRequest {\n\treq.opts = opts\n\treturn req\n}", "func (c *Config) Apply(cfg *Config) {\n\tif cfg == nil {\n\t\treturn\n\t}\n\n\tc.JrnlCtrlConfig.Apply(&cfg.JrnlCtrlConfig)\n\tc.PipesConfig.Apply(&cfg.PipesConfig)\n\n\tif cfg.BaseDir != \"\" {\n\t\tc.BaseDir = cfg.BaseDir\n\t}\n\tif cfg.HostHostId > 0 {\n\t\tc.HostHostId = cfg.HostHostId\n\t}\n\tif !reflect.DeepEqual(c.PublicApiRpc, cfg.PublicApiRpc) {\n\t\tc.PublicApiRpc = cfg.PublicApiRpc\n\t}\n\tif !reflect.DeepEqual(c.PrivateApiRpc, cfg.PrivateApiRpc) {\n\t\tc.PrivateApiRpc = cfg.PrivateApiRpc\n\t}\n\tif cfg.HostLeaseTTLSec > 0 {\n\t\tc.HostLeaseTTLSec = cfg.HostLeaseTTLSec\n\t}\n\tif cfg.HostRegisterTimeoutSec > 0 {\n\t\tc.HostRegisterTimeoutSec = cfg.HostRegisterTimeoutSec\n\t}\n}", "func (throttler *Throttler) applyThrottlerConfig(ctx context.Context, throttlerConfig *topodatapb.ThrottlerConfig) {\n\tlog.Infof(\"Throttler: applying topo config: %+v\", throttlerConfig)\n\tif throttlerConfig.CustomQuery == \"\" {\n\t\tthrottler.metricsQuery.Store(sqlparser.BuildParsedQuery(defaultReplicationLagQuery, sidecar.GetIdentifier()).Query)\n\t} else {\n\t\tthrottler.metricsQuery.Store(throttlerConfig.CustomQuery)\n\t}\n\tthrottler.StoreMetricsThreshold(throttlerConfig.Threshold)\n\tthrottler.checkAsCheckSelf.Store(throttlerConfig.CheckAsCheckSelf)\n\tfor _, appRule := range throttlerConfig.ThrottledApps {\n\t\tthrottler.ThrottleApp(appRule.Name, protoutil.TimeFromProto(appRule.ExpiresAt).UTC(), appRule.Ratio, appRule.Exempt)\n\t}\n\tif throttlerConfig.Enabled {\n\t\tgo throttler.Enable(ctx)\n\t} else {\n\t\tgo throttler.Disable(ctx)\n\t}\n}", "func OptionsEqual(xopts, yopts map[string]interface{}) bool {\n\tif len(xopts) != len(yopts) {\n\t\treturn false\n\t}\n\n\tfor k, v := range yopts {\n\t\txv, ok := xopts[k]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\n\t\tif strings.HasSuffix(k, \"ttl\") || strings.HasSuffix(k, \"period\") {\n\t\t\tif !ttlEqual(fmt.Sprintf(\"%v\", v), fmt.Sprintf(\"%v\", xv)) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif fmt.Sprintf(\"%v\", v) != fmt.Sprintf(\"%v\", xv) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (options Options) merge(defaults Options) {\n for k, v := range defaults {\n if _, present := options[k]; !present {\n options[k] = v\n }\n }\n}" ]
[ "0.62161744", "0.60801", "0.5962653", "0.58972675", "0.5862883", "0.5759934", "0.5752782", "0.57467747", "0.547668", "0.5474911", "0.5289025", "0.5288125", "0.52854234", "0.52022785", "0.5182077", "0.5168935", "0.51122046", "0.5102658", "0.5087273", "0.50831145", "0.5053145", "0.5026035", "0.4995962", "0.4944004", "0.49076673", "0.48957872", "0.4892616", "0.48151058", "0.4804198", "0.4801982", "0.47593862", "0.4754235", "0.4733839", "0.47030446", "0.46956035", "0.46884036", "0.46719593", "0.4645645", "0.4625517", "0.46019506", "0.45930216", "0.45654598", "0.4558427", "0.4552927", "0.45452514", "0.45251164", "0.45158195", "0.4505097", "0.4496525", "0.44862917", "0.44364154", "0.44325456", "0.4419133", "0.44187006", "0.43683273", "0.43610716", "0.43598956", "0.43565318", "0.43431357", "0.43340343", "0.43260205", "0.43211636", "0.431319", "0.42878333", "0.4256639", "0.4251982", "0.42394146", "0.42389774", "0.42345262", "0.42272037", "0.42199394", "0.4183975", "0.4180195", "0.41798717", "0.41795167", "0.41786027", "0.41740003", "0.41733003", "0.4171965", "0.41655412", "0.41644827", "0.41618603", "0.41542488", "0.41518605", "0.4141576", "0.41373008", "0.41330698", "0.41327915", "0.4118659", "0.41051325", "0.4104497", "0.4103677", "0.41013992", "0.40856344", "0.40759817", "0.40717664", "0.40700036", "0.4069038", "0.40681258", "0.4066266" ]
0.62208015
0
ApplyOpts applies any values set in o to opts, if a value is not set on o, then we don't update opts and allow redispipe to use its defaults.
func (o ClusterOpts) ApplyOpts(opts *rediscluster.Opts) { if o.Name != "" { opts.Name = o.Name } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *Options) Apply(opts ...Option) error {\n\tfor i, opt := range opts {\n\t\tif err := opt(o); err != nil {\n\t\t\treturn fmt.Errorf(\"option %d failed: %s\", i, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Options) Apply() {\n\tif o == nil {\n\t\treturn\n\t}\n\tif len(o.ShowHiddenMetricsForVersion) > 0 {\n\t\tSetShowHidden()\n\t}\n\t// set disabled metrics\n\tfor _, metricName := range o.DisabledMetrics {\n\t\tSetDisabledMetric(metricName)\n\t}\n\tif o.AllowListMapping != nil {\n\t\tSetLabelAllowListFromCLI(o.AllowListMapping)\n\t}\n}", "func (o Opts) ApplyOpts(opts *redisconn.Opts) {\n\n\tif o.DB != nil {\n\t\topts.DB = *o.DB\n\t}\n\tif o.WritePause > 0 {\n\t\topts.WritePause = o.WritePause\n\t}\n\tif o.ReconnectPause > 0 {\n\t\topts.ReconnectPause = o.ReconnectPause\n\t}\n\tif o.TCPKeepAlive > 0 {\n\t\topts.TCPKeepAlive = o.TCPKeepAlive\n\t}\n\to.Timeouts.ApplyOpts(opts)\n}", "func (o *PatchOptions) ApplyOptions(opts []PatchOption) {\n\tfor _, opt := range opts {\n\t\topt.ApplyToHelper(o)\n\t}\n}", "func applyOptions(c *Container, opts ...Option) error {\n\tfor _, opt := range opts {\n\t\tif err := opt.set(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (o *Options) Apply(opts ...Option) error {\n\tfor i, opt := range opts {\n\t\tif err := opt(o); err != nil {\n\t\t\treturn fmt.Errorf(\"dht option %d failed: %s\", i, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (o Options) Apply(i *Important) {\n\tfor _, opt := range o {\n\t\topt(i)\n\t}\n}", "func (o optionFunc) ApplyOption(opts *Options) {\n\to(opts)\n}", "func (opts *Options) Apply(options ...Option) error {\n\tfor _, o := range options {\n\t\tif err := o(opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (o *MatchOptions) ApplyOptions(opts []MatchOption) *MatchOptions {\n\tfor _, opt := range opts {\n\t\topt.ApplyToMatcher(o)\n\t}\n\treturn o\n}", "func ApplyGaugeOptions(opts *Options, gos ...GaugeOptionApplier) {\n\tfor _, o := range gos {\n\t\to.ApplyGaugeOption(opts)\n\t}\n}", "func (ro *RequesterOptions) apply(opts ...RequesterOption) {\n\tfor _, opt := range opts {\n\t\topt(ro)\n\t}\n}", "func (cfg *Config) Apply(opts ...Option) error {\n\tfor _, opt := range opts {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err := opt(cfg); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (opt option) apply(o interface{}) error {\n\tswitch v := o.(type) {\n\tcase *TableEncoder:\n\t\tif opt.table != nil {\n\t\t\treturn opt.table(v)\n\t\t}\n\t\treturn nil\n\tcase *ExpandedEncoder:\n\t\tif opt.expanded != nil {\n\t\t\treturn opt.expanded(v)\n\t\t}\n\t\treturn nil\n\tcase *JSONEncoder:\n\t\tif opt.json != nil {\n\t\t\treturn opt.json(v)\n\t\t}\n\t\treturn nil\n\tcase *UnalignedEncoder:\n\t\tif opt.unaligned != nil {\n\t\t\treturn opt.unaligned(v)\n\t\t}\n\t\treturn nil\n\tcase *TemplateEncoder:\n\t\tif opt.template != nil {\n\t\t\treturn opt.template(v)\n\t\t}\n\t\treturn nil\n\tcase *CrosstabView:\n\t\tif opt.crosstab != nil {\n\t\t\treturn opt.crosstab(v)\n\t\t}\n\t\treturn nil\n\tcase *errEncoder:\n\t\tif opt.err != nil {\n\t\t\treturn opt.err(v)\n\t\t}\n\t\treturn nil\n\t}\n\tpanic(fmt.Sprintf(\"option cannot be applied to %T\", o))\n}", "func (d *OverloadServiceDesc) Apply(oo ...transport.DescOption) {\n\tfor _, o := range oo {\n\t\to.Apply(&d.opts)\n\t}\n}", "func (o Option) apply(r *Dol) { o(r) }", "func (o *Number[T]) ApplyOptions(options ...NumberOption[T]) *Number[T] {\n\tfor _, opt := range options {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\topt.apply(o)\n\t}\n\treturn o\n}", "func (o *JSONPb) ApplyOptions(options ...JSONPbOption) *JSONPb {\n\tfor _, opt := range options {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\topt.apply(o)\n\t}\n\treturn o\n}", "func (po *SubResourcePatchOptions) ApplyOptions(opts []SubResourcePatchOption) *SubResourcePatchOptions {\n\tfor _, o := range opts {\n\t\to.ApplyToSubResourcePatch(po)\n\t}\n\n\treturn po\n}", "func ApplyOptions(f *pflag.Flag, opts ...FlagOption) {\n\tfor _, opt := range opts {\n\t\topt(f)\n\t}\n}", "func (c *Default) Update(opts ...DefaultOption) {\n\tfor _, opt := range opts {\n\t\topt.ApplyDefault(c)\n\t}\n}", "func (t Timeouts) ApplyOpts(opts *redisconn.Opts) {\n\tif t.Dial > 0 {\n\t\topts.DialTimeout = t.Dial\n\t}\n\tif t.IO > 0 {\n\t\topts.IOTimeout = t.IO\n\t}\n}", "func (uo *SubResourceUpdateOptions) ApplyOptions(opts []SubResourceUpdateOption) *SubResourceUpdateOptions {\n\tfor _, o := range opts {\n\t\to.ApplyToSubResourceUpdate(uo)\n\t}\n\n\treturn uo\n}", "func (r RequestCryptoSignerOpts) ApplyCryptoSignerOpts(opts *crypto.SignerOpts) {\n\t*opts = r.opts\n}", "func (c *AppConfig) Apply(opts []AppOption) error {\r\n\tfor _, o := range opts {\r\n\t\tif err := o(c); err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t}\r\n\treturn nil\r\n}", "func ApplyOptions(opt ...Option) Options {\n\topts := Options{\n\t\tMaxTraversalLinks: math.MaxInt64, //default: traverse all\n\t\tMaxAllowedHeaderSize: carv1.DefaultMaxAllowedHeaderSize,\n\t\tMaxAllowedSectionSize: carv1.DefaultMaxAllowedSectionSize,\n\t}\n\tfor _, o := range opt {\n\t\to(&opts)\n\t}\n\t// Set defaults for zero valued fields.\n\tif opts.IndexCodec == 0 {\n\t\topts.IndexCodec = multicodec.CarMultihashIndexSorted\n\t}\n\tif opts.MaxIndexCidSize == 0 {\n\t\topts.MaxIndexCidSize = DefaultMaxIndexCidSize\n\t}\n\treturn opts\n}", "func MergeOpenDriveOptions(opts ...*OpenDriveOptions) *OpenDriveOptions {\n\to := OpenDrive()\n\n\tfor _, opt := range opts {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif opt.Directory != nil {\n\t\t\to.Directory = opt.Directory\n\t\t}\n\t\tif opt.Logger != nil {\n\t\t\to.Logger = opt.Logger\n\t\t}\n\t\tif opt.AccessController != nil {\n\t\t\to.AccessController = opt.AccessController\n\t\t}\n\t\tif opt.Create != nil {\n\t\t\to.Create = opt.Create\n\t\t}\n\t}\n\n\treturn o\n}", "func (op *ReadOptions) Apply(opts ...ReadOption) {\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n}", "func (opts RequestOpts) Apply(req *http.Request) {\n\t// apply per-request options\n\tfor _, o := range opts {\n\t\tif o != nil {\n\t\t\to(req)\n\t\t}\n\t}\n}", "func (o *ListImplementationRevisionsOptions) Apply(opts ...GetImplementationOption) {\n\tfor _, opt := range opts {\n\t\topt(o)\n\t}\n}", "func (o *DB) ApplyOptions(options ...DBOption) *DB {\n\tfor _, opt := range options {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\topt.apply(o)\n\t}\n\treturn o\n}", "func (o ClientOptions) ApplyDefaults(ctx context.Context, defaultDesc string) ClientOptions {\n\tif o.Hostname == \"\" {\n\t\to.Hostname = GetDefaultHostName(ctx)\n\t}\n\n\tif o.Username == \"\" {\n\t\to.Username = GetDefaultUserName(ctx)\n\t}\n\n\tif o.Description == \"\" {\n\t\to.Description = defaultDesc\n\t}\n\n\tif o.FormatBlobCacheDuration == 0 {\n\t\to.FormatBlobCacheDuration = format.DefaultRepositoryBlobCacheDuration\n\t}\n\n\treturn o\n}", "func (r *Repo) Apply(opts ...func(*Repo)) {\n\tif r == nil {\n\t\treturn\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(r)\n\t}\n}", "func ApplyGatewayDefaultOptions(opts *Options) error {\n\tif opts.Stack.Tenants == nil {\n\t\treturn nil\n\t}\n\n\tif !opts.Gates.OpenShift.Enabled {\n\t\treturn nil\n\t}\n\n\to := openshift.NewOptions(\n\t\topts.Name,\n\t\topts.Namespace,\n\t\tGatewayName(opts.Name),\n\t\tserviceNameGatewayHTTP(opts.Name),\n\t\tgatewayHTTPPortName,\n\t\topts.Timeouts.Gateway.WriteTimeout,\n\t\tComponentLabels(LabelGatewayComponent, opts.Name),\n\t\tRulerName(opts.Name),\n\t)\n\n\tswitch opts.Stack.Tenants.Mode {\n\tcase lokiv1.Static, lokiv1.Dynamic:\n\t\t// Do nothing as per tenants provided by LokiStack CR\n\tcase lokiv1.OpenshiftLogging, lokiv1.OpenshiftNetwork:\n\t\ttenantData := make(map[string]openshift.TenantData)\n\t\tfor name, tenant := range opts.Tenants.Configs {\n\t\t\ttenantData[name] = openshift.TenantData{\n\t\t\t\tCookieSecret: tenant.OpenShift.CookieSecret,\n\t\t\t}\n\t\t}\n\n\t\to.WithTenantsForMode(opts.Stack.Tenants.Mode, opts.GatewayBaseDomain, tenantData)\n\t}\n\n\tif err := mergo.Merge(&opts.OpenShiftOptions, o, mergo.WithOverride); err != nil {\n\t\treturn kverrors.Wrap(err, \"failed to merge defaults for mode openshift\")\n\t}\n\n\treturn nil\n}", "func ApplyLoggerOpts(opts ...Option) LoggerOpts {\n\t// set some defaults\n\tl := LoggerOpts{\n\t\tAdditionalLocationOffset: 1,\n\t\tIncludeLocation: true,\n\t\tIncludeTime: true,\n\t\tOutput: os.Stderr,\n\t}\n\tfor _, opt := range opts {\n\t\tl = opt(l)\n\t}\n\treturn l\n}", "func (getOpt *SubResourceGetOptions) ApplyOptions(opts []SubResourceGetOption) *SubResourceGetOptions {\n\tfor _, o := range opts {\n\t\to.ApplyToSubResourceGet(getOpt)\n\t}\n\n\treturn getOpt\n}", "func (a *APIPatchingApplicator) Apply(ctx context.Context, o client.Object, ao ...ApplyOption) error {\n\tif o.GetNamespace() == \"\" {\n\t\to.SetNamespace(\"default\")\n\t}\n\n\tm, ok := o.(metav1.Object)\n\tif !ok {\n\t\treturn errors.New(\"cannot access object metadata\")\n\t}\n\n\tif m.GetName() == \"\" && m.GetGenerateName() != \"\" {\n\t\treturn errors.Wrap(a.client.Create(ctx, o), \"cannot create object\")\n\t}\n\n\tdesired := o.DeepCopyObject()\n\n\terr := a.client.Get(ctx, types.NamespacedName{Name: m.GetName(), Namespace: m.GetNamespace()}, o)\n\tif kerrors.IsNotFound(err) {\n\t\t// TODO: Apply ApplyOptions here too?\n\t\treturn errors.Wrap(a.client.Create(ctx, o), \"cannot create object\")\n\t}\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"cannot get object\")\n\t}\n\n\tfor _, fn := range ao {\n\t\tif err := fn(ctx, o, desired); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// TODO: Allow callers to override the kind of patch used.\n\treturn errors.Wrap(a.client.Patch(ctx, o, &patch{desired.(client.Object)}), \"cannot patch object\")\n}", "func (lOpts *logOptions) apply(options ...Option) {\n\tfor _, opt := range options {\n\t\topt(lOpts)\n\t}\n}", "func (opts *lateInitOptions) apply(opt ...LateInitOption) {\n\tfor _, o := range opt {\n\t\to.apply(opts)\n\t}\n}", "func (req *SelectRequest) Opts(opts SelectOpts) *SelectRequest {\n\treq.opts = opts\n\treturn req\n}", "func ApplyMeasureOptions(opts *Options, mos ...MeasureOptionApplier) {\n\tfor _, o := range mos {\n\t\to.ApplyMeasureOption(opts)\n\t}\n}", "func (o *DeleteOptions) ApplyOptions(opts []DeleteOption) {\n\tfor _, opt := range opts {\n\t\topt.ApplyToDeleteOptions(o)\n\t}\n}", "func (a *APIUpdatingApplicator) Apply(ctx context.Context, o client.Object, ao ...ApplyOption) error {\n\tm, ok := o.(Object)\n\tif !ok {\n\t\treturn errors.New(\"cannot access object metadata\")\n\t}\n\n\tif m.GetName() == \"\" && m.GetGenerateName() != \"\" {\n\t\treturn errors.Wrap(a.client.Create(ctx, o), \"cannot create object\")\n\t}\n\n\tcurrent := o.DeepCopyObject().(client.Object)\n\n\terr := a.client.Get(ctx, types.NamespacedName{Name: m.GetName(), Namespace: m.GetNamespace()}, current)\n\tif kerrors.IsNotFound(err) {\n\t\t// TODO: Apply ApplyOptions here too?\n\t\treturn errors.Wrap(a.client.Create(ctx, m), \"cannot create object\")\n\t}\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"cannot get object\")\n\t}\n\n\tfor _, fn := range ao {\n\t\tif err := fn(ctx, current, m); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// NOTE: we must set the resource version of the desired object\n\t// to that of the current or the update will always fail.\n\tm.SetResourceVersion(current.(metav1.Object).GetResourceVersion())\n\treturn errors.Wrap(a.client.Update(ctx, m), \"cannot update object\")\n}", "func (o *Options) applyDefaults(in *componentconfig.CoordinatorConfiguration) (*componentconfig.CoordinatorConfiguration, error) {\n\tcomponentconfig.SetDefaultsCoordinatorConfiguration(in)\n\treturn in, nil\n}", "func (bo *BoolOptions) Apply(n models.ConfigurationMap, changed ChangedFunc, data interface{}) int {\n\tchanges := []changedOptions{}\n\n\tbo.optsMU.Lock()\n\tfor k, v := range n {\n\t\tval, ok := bo.Opts[k]\n\n\t\tif boolVal, _ := NormalizeBool(v); boolVal {\n\t\t\t/* Only enable if not enabled already */\n\t\t\tif !ok || !val {\n\t\t\t\tbo.enable(k)\n\t\t\t\tchanges = append(changes, changedOptions{key: k, value: true})\n\t\t\t}\n\t\t} else {\n\t\t\t/* Only disable if enabled already */\n\t\t\tif ok && val {\n\t\t\t\tbo.disable(k)\n\t\t\t\tchanges = append(changes, changedOptions{key: k, value: false})\n\t\t\t}\n\t\t}\n\t}\n\tbo.optsMU.Unlock()\n\n\tfor _, change := range changes {\n\t\tchanged(change.key, change.value, data)\n\t}\n\n\treturn len(changes)\n}", "func (eeo EncodingErrorOption) argApply(o *argOptions) {\n\to.opts = append(o.opts, eeo)\n}", "func ApplyCounterOptions(opts *Options, cos ...CounterOptionApplier) {\n\tfor _, o := range cos {\n\t\to.ApplyCounterOption(opts)\n\t}\n}", "func (s *LCOWOption) Apply(interface{}) error {\n\treturn nil\n}", "func ApplyDefaults(obj interface{}, s *spec.Schema) bool {\n\tif s == nil {\n\t\treturn false\n\t}\n\n\tres := false\n\n\t// Support utils.Values\n\tswitch vals := obj.(type) {\n\tcase utils.Values:\n\t\tobj = map[string]interface{}(vals)\n\tcase *utils.Values:\n\t\t// rare case\n\t\tobj = map[string]interface{}(*vals)\n\t}\n\n\tswitch obj := obj.(type) {\n\tcase map[string]interface{}:\n\t\t// Apply defaults to properties\n\t\tfor k, prop := range s.Properties {\n\t\t\tif prop.Default == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, found := obj[k]; !found {\n\t\t\t\tobj[k] = runtime.DeepCopyJSONValue(prop.Default)\n\t\t\t\tres = true\n\t\t\t}\n\t\t}\n\t\t// Apply to deeper levels.\n\t\tfor k, v := range obj {\n\t\t\tif prop, found := s.Properties[k]; found {\n\t\t\t\tdeepRes := ApplyDefaults(v, &prop)\n\t\t\t\tres = res || deepRes\n\t\t\t}\n\t\t}\n\tcase []interface{}:\n\t\t// Only List validation is supported.\n\t\t// See https://json-schema.org/understanding-json-schema/reference/array.html#list-validation\n\t\tfor _, v := range obj {\n\t\t\tdeepRes := ApplyDefaults(v, s.Items.Schema)\n\t\t\tres = res || deepRes\n\t\t}\n\tdefault:\n\t\t// scalars, no action\n\t}\n\n\treturn res\n}", "func (c *MockClient) ApplyOption(opt MockClientOption) {\n\topt(c)\n}", "func (req *UpsertObjectRequest) Opts(opts UpsertObjectOpts) *UpsertObjectRequest {\n\treq.opts = opts\n\treturn req\n}", "func Apply(rw ReadWriter, options ...Option) ReadWriter {\n\tfor _, option := range options {\n\t\toption(rw)\n\t}\n\treturn applyOptionsForState(rw)\n}", "func ApplyAll(rw ReadWriter, optionSets ...[]Option) ReadWriter {\n\toptions := []Option{}\n\tfor _, optionSet := range optionSets {\n\t\toptions = append(options, optionSet...)\n\t}\n\treturn Apply(rw, options...)\n}", "func (pool *ComplexPool) Option(opts ...Option) (err error) {\n\tfor _, opt := range opts {\n\t\terr = opt(pool)\n\t}\n\n\treturn err\n}", "func (options Options) merge(defaults Options) {\n for k, v := range defaults {\n if _, present := options[k]; !present {\n options[k] = v\n }\n }\n}", "func (sso *StartSpanOptions) Apply(opt opentracing.StartSpanOption) {\n\topt.Apply(&sso.OpenTracingOptions)\n\tif o, ok := opt.(StartSpanOption); ok {\n\t\to.ApplyBP(sso)\n\t}\n}", "func (opts *Opts) updateOptions() {\n\tfor option := range opts.rs.edges {\n\t\tif _, ok := opts.options[option]; !ok {\n\t\t\t// by default the option state is false\n\t\t\topts.options[option] = false\n\t\t\t// if a parent exist the new option takes its state\n\t\t\tif len(opts.rs.edges[option]) > 0 {\n\t\t\t\tparent := opts.rs.edges[option][0] // TODO: what if there are multiple parents?\n\t\t\t\topts.options[option] = opts.options[parent]\n\t\t\t}\n\t\t}\n\t}\n\n\tfor option := range opts.rs.conflicts {\n\t\tif _, ok := opts.options[option]; !ok {\n\t\t\topts.options[option] = false\n\t\t}\n\t}\n}", "func (f OptionFunc) Apply(ratelimiter Ratelimiter) error {\n\treturn f(ratelimiter)\n}", "func (o *EphemeralVolumeControllerOptions) ApplyTo(cfg *ephemeralvolumeconfig.EphemeralVolumeControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentEphemeralVolumeSyncs = o.ConcurrentEphemeralVolumeSyncs\n\n\treturn nil\n}", "func (p *Porter) applyActionOptionsToInstallation(ctx context.Context, ba BundleAction, inst *storage.Installation) error {\n\tctx, span := tracing.StartSpan(ctx)\n\tdefer span.EndSpan()\n\n\to := ba.GetOptions()\n\n\tbundleRef, err := o.GetBundleReference(ctx, p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbun := bundleRef.Definition\n\n\t// Update the installation with metadata from the options\n\tinst.TrackBundle(bundleRef.Reference)\n\tinst.Status.Modified = time.Now()\n\n\t//\n\t// 1. Record the parameter and credential sets used on the installation\n\t// if none were specified, reuse the previous sets from the installation\n\t//\n\tspan.SetAttributes(\n\t\ttracing.ObjectAttribute(\"override-parameter-sets\", o.ParameterSets),\n\t\ttracing.ObjectAttribute(\"override-credential-sets\", o.CredentialIdentifiers))\n\tif len(o.ParameterSets) > 0 {\n\t\tinst.ParameterSets = o.ParameterSets\n\t}\n\tif len(o.CredentialIdentifiers) > 0 {\n\t\tinst.CredentialSets = o.CredentialIdentifiers\n\t}\n\n\t//\n\t// 2. Parse parameter flags from the command line and apply to the installation as overrides\n\t//\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"override-parameters\", o.Params))\n\tparsedOverrides, err := storage.ParseVariableAssignments(o.Params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Default the porter-debug param to --debug\n\tif o.DebugMode {\n\t\tparsedOverrides[\"porter-debug\"] = \"true\"\n\t}\n\n\t// Apply overrides on to of any pre-existing parameters that were specified previously\n\tif len(parsedOverrides) > 0 {\n\t\tfor name, value := range parsedOverrides {\n\t\t\t// Do not resolve parameters from dependencies\n\t\t\tif strings.Contains(name, \"#\") {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Replace previous value if present\n\t\t\treplaced := false\n\t\t\tparamStrategy := storage.ValueStrategy(name, value)\n\t\t\tfor i, existingParam := range inst.Parameters.Parameters {\n\t\t\t\tif existingParam.Name == name {\n\t\t\t\t\tinst.Parameters.Parameters[i] = paramStrategy\n\t\t\t\t\treplaced = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !replaced {\n\t\t\t\tinst.Parameters.Parameters = append(inst.Parameters.Parameters, paramStrategy)\n\t\t\t}\n\t\t}\n\n\t\t// Keep the parameter overrides sorted, so that comparisons and general troubleshooting is easier\n\t\tsort.Sort(inst.Parameters.Parameters)\n\t}\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"merged-installation-parameters\", inst.Parameters.Parameters))\n\n\t//\n\t// 3. Resolve named parameter sets\n\t//\n\tresolvedParams, err := p.loadParameterSets(ctx, bun, o.Namespace, inst.ParameterSets)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to process provided parameter sets: %w\", err)\n\t}\n\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"resolved-parameter-sets-keys\", resolvedParams))\n\n\t//\n\t// 4. Resolve the installation's internal parameter set\n\tresolvedOverrides, err := p.Parameters.ResolveAll(ctx, inst.Parameters)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"resolved-installation-parameters\", inst.Parameters.Parameters))\n\n\t//\n\t// 5. Apply the overrides on top of the parameter sets\n\t//\n\tfor k, v := range resolvedOverrides {\n\t\tresolvedParams[k] = v\n\t}\n\n\t//\n\t// 6. Separate out params for the root bundle from the ones intended for dependencies\n\t// This only applies to the dep v1 implementation, in dep v2 you can't specify rando params for deps\n\t//\n\to.depParams = make(map[string]string)\n\tfor k, v := range resolvedParams {\n\t\tif strings.Contains(k, \"#\") {\n\t\t\to.depParams[k] = v\n\t\t\tdelete(resolvedParams, k)\n\t\t}\n\t}\n\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"user-specified-parameters\", resolvedParams))\n\n\t//\n\t// 7. When a parameter is not specified, fallback to a parameter source or default\n\t//\n\tfinalParams, err := p.finalizeParameters(ctx, *inst, bun, ba.GetAction(), resolvedParams)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// This contains resolved sensitive values, so only trace it in special dev builds (nothing is traced for release builds)\n\tspan.SetSensitiveAttributes(tracing.ObjectAttribute(\"final-parameters\", finalParams))\n\n\t// Remember the final set of parameters so we don't have to resolve them more than once\n\to.finalParams = finalParams\n\n\t// Ensure we aren't storing any secrets on the installation resource\n\tif err = p.sanitizeInstallation(ctx, inst, bundleRef.Definition); err != nil {\n\t\treturn err\n\t}\n\n\t// re-validate the installation since we modified it here\n\treturn inst.Validate(ctx, p.GetSchemaCheckStrategy(ctx))\n}", "func (opts *Options) SetDefaults() {\n for name, _ := range opts.opt_map {\n //fmt.Printf(\"%s\\n\",name);\n opts.opt_map[name].SetDefault()\n }\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"key_not_required\":\n\t\t\t\tkeyNotRequired, err := strconv.ParseBool(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\topts.withKeyNotRequired = keyNotRequired\n\t\t\tcase \"user_agent\":\n\t\t\t\topts.withUserAgent = v\n\t\t\tcase \"credentials\":\n\t\t\t\topts.withCredentials = v\n\t\t\tcase \"project\":\n\t\t\t\topts.withProject = v\n\t\t\tcase \"region\":\n\t\t\t\topts.withRegion = v\n\t\t\tcase \"key_ring\":\n\t\t\t\topts.withKeyRing = v\n\t\t\tcase \"crypto_key\":\n\t\t\t\topts.withCryptoKey = v\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func (req MinRequest) Opts(opts MinOpts) MinRequest {\n\treq.opts = opts\n\treturn req\n}", "func (c *Currency) Option(opts ...OptionFunc) (previous OptionFunc) {\n\tfor _, o := range opts {\n\t\tif o != nil {\n\t\t\tprevious = o(c)\n\t\t}\n\t}\n\treturn previous\n}", "func transformOptions(options ...interface{}) map[string]interface{} {\n\tvar base map[string]interface{}\n\tvar option interface{}\n\t// Case 1: No options are given\n\tif len(options) == 0 {\n\t\treturn make(map[string]interface{})\n\t}\n\tif len(options) == 1 {\n\t\t// Case 2: a single value (either struct or map) is given.\n\t\tbase = make(map[string]interface{})\n\t\toption = options[0]\n\t} else if len(options) == 2 {\n\t\t// Case 3: two values are given. The first one needs to be a map and the\n\t\t// second one can be a struct or map. It will be then get merged into the first\n\t\t// base map.\n\t\tbase = transformStructIntoMapIfNeeded(options[0])\n\t\toption = options[1]\n\t}\n\tv := reflect.ValueOf(option)\n\tif v.Kind() == reflect.Slice {\n\t\tif v.Len() == 0 {\n\t\t\treturn base\n\t\t}\n\t\toption = v.Index(0).Interface()\n\t}\n\n\tif option == nil {\n\t\treturn base\n\t}\n\tv = reflect.ValueOf(option)\n\n\tif v.Kind() == reflect.Ptr {\n\t\tv = v.Elem()\n\t}\n\n\toptionMap := transformStructIntoMapIfNeeded(v.Interface())\n\tfor key, value := range optionMap {\n\t\tbase[key] = value\n\t}\n\treturn base\n}", "func fromOptions(options []Option) *baseSettings {\n\t// Start from the default options:\n\topts := &baseSettings{\n\t\tconsumerOptions: []consumer.Option{consumer.WithCapabilities(consumer.Capabilities{MutatesData: true})},\n\t}\n\n\tfor _, op := range options {\n\t\top(opts)\n\t}\n\n\treturn opts\n}", "func aggregateOptionsFromCommerceOptions(payload *app.CommerceOptionsPayload) (model.AggregateOptions, error) {\n\tvar o model.AggregateOptions\n\n\tfor _, val := range payload.FilterBy {\n\t\tfb := &model.FilterBy{\n\t\t\tTag: val.Tag,\n\t\t\tValues: val.Values,\n\t\t\tInverse: false,\n\t\t}\n\t\tif val.Inverse != nil {\n\t\t\tfb.Inverse = *val.Inverse\n\t\t}\n\t\to.FilterBy = append(o.FilterBy, fb)\n\t}\n\n\to.GroupBy = payload.GroupBy\n\tif payload.TimeAfter != nil {\n\t\to.TimeAfter = *payload.TimeAfter\n\t}\n\tif payload.TimeBefore != nil {\n\t\to.TimeBefore = *payload.TimeBefore\n\t}\n\n\tif payload.Step != nil {\n\t\to.Step = *payload.Step\n\t}\n\n\tif payload.TimeHistogram != nil {\n\t\to.TimeHistogram = &model.TimeHistogram{\n\t\t\tInterval: payload.TimeHistogram.Interval,\n\t\t}\n\n\t\tif payload.TimeHistogram.TimeZone != nil {\n\t\t\tlocation, err := time.LoadLocation(*payload.TimeHistogram.TimeZone)\n\t\t\tif err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t\to.TimeHistogram.TimeZone = location\n\t\t}\n\t}\n\n\treturn o, nil\n}", "func CommonOptions(ctx context.Context, scope kouch.TargetScope, flags *pflag.FlagSet) (*kouch.Options, error) {\n\to := kouch.NewOptions()\n\tvar err error\n\to.Target, err = kouch.NewTarget(ctx, scope, flags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif e := o.SetParam(flags, kouch.FlagRev); e != nil {\n\t\treturn nil, e\n\t}\n\tif e := setAutoRev(ctx, o, flags); e != nil {\n\t\treturn nil, e\n\t}\n\n\treturn o, nil\n}", "func (o *OptionsProvider) Options(opts ...Option) *OptionsProvider {\n\tfor _, opt := range opts {\n\t\toptType := reflect.TypeOf(opt)\n\t\tif _, ok := optType.FieldByName(\"Value\"); !ok {\n\t\t\tpanic(fmt.Sprintf(\"Option %v doesn't have a Value field.\", optType.Name()))\n\t\t}\n\t\tfieldName := o.m[optType.Name()]\n\t\tfield := reflect.ValueOf(o.spec).Elem().FieldByName(fieldName)\n\t\tif !field.CanSet() || !field.IsValid() {\n\t\t\tpanic(fmt.Sprintf(\"There is no option %v.\", optType.Name()))\n\t\t}\n\t\tfield.Set(reflect.ValueOf(opt))\n\t\to.set[fieldName] = true\n\t}\n\treturn o\n}", "func (o *Options) setDefaults() {\n\tif o.Timeout <= 0 {\n\t\to.Timeout = DefaultTimeout\n\t}\n\tif o.Count < 0 {\n\t\to.Count = 0\n\t}\n\tif o.PacketSize <= 0 {\n\t\to.PacketSize = DefaultPacketSize\n\t}\n}", "func (co *SubResourceCreateOptions) ApplyOptions(opts []SubResourceCreateOption) *SubResourceCreateOptions {\n\tfor _, o := range opts {\n\t\to.ApplyToSubResourceCreate(co)\n\t}\n\n\treturn co\n}", "func MergeAggregateOptions(opts ...*AggregateOptions) *AggregateOptions {\n\taggOpts := Aggregate()\n\tfor _, ao := range opts {\n\t\tif ao == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif ao.AllowDiskUse != nil {\n\t\t\taggOpts.AllowDiskUse = ao.AllowDiskUse\n\t\t}\n\t\tif ao.BatchSize != nil {\n\t\t\taggOpts.BatchSize = ao.BatchSize\n\t\t}\n\t\tif ao.BypassDocumentValidation != nil {\n\t\t\taggOpts.BypassDocumentValidation = ao.BypassDocumentValidation\n\t\t}\n\t\tif ao.Collation != nil {\n\t\t\taggOpts.Collation = ao.Collation\n\t\t}\n\t\tif ao.MaxTime != nil {\n\t\t\taggOpts.MaxTime = ao.MaxTime\n\t\t}\n\t\tif ao.MaxAwaitTime != nil {\n\t\t\taggOpts.MaxAwaitTime = ao.MaxAwaitTime\n\t\t}\n\t\tif ao.Comment != nil {\n\t\t\taggOpts.Comment = ao.Comment\n\t\t}\n\t\tif ao.Hint != nil {\n\t\t\taggOpts.Hint = ao.Hint\n\t\t}\n\t\tif ao.Let != nil {\n\t\t\taggOpts.Let = ao.Let\n\t\t}\n\t\tif ao.Custom != nil {\n\t\t\taggOpts.Custom = ao.Custom\n\t\t}\n\t}\n\n\treturn aggOpts\n}", "func (req *MinRequest) Opts(opts MinOpts) *MinRequest {\n\treq.opts = opts\n\treturn req\n}", "func (s *snapshot) ApplyOptions() Actionable {\n\ts.options = s.context.Options().(*options.SnapshotOptions)\n\n\tif len(s.options.Name) == 0 {\n\t\ts.options.Name = \"github.com/alejandro-carstens/scrubber-\" + time.Now().Format(\"1992-06-02\")\n\t}\n\n\tif !s.options.Exists(\"wait_for_completion\") {\n\t\ts.options.WaitForCompletion = DEFAULT_WAIT_FOR_COMPLETION\n\t}\n\n\tif !s.options.WaitForCompletion {\n\t\tif !s.options.Exists(\"max_wait\") {\n\t\t\ts.options.MaxWait = DEFAULT_MAX_WAIT\n\t\t}\n\n\t\tif !s.options.Exists(\"wait_interval\") {\n\t\t\ts.options.WaitInterval = DEFAULT_WAIT_INTERVAL\n\t\t}\n\t}\n\n\ts.indexer.SetOptions(&golastic.IndexOptions{\n\t\tTimeout: s.options.TimeoutInSeconds(),\n\t\tWaitForCompletion: s.options.WaitForCompletion,\n\t\tPartial: s.options.Partial,\n\t\tIncludeGlobalState: s.options.IncludeGlobalState,\n\t\tIgnoreUnavailable: s.options.IgnoreUnavailable,\n\t})\n\n\treturn s\n}", "func mergeOptions(pas []v1.Patch) []resource.ApplyOption {\n\topts := make([]resource.ApplyOption, 0, len(pas))\n\tfor _, p := range pas {\n\t\tif p.Policy == nil || p.ToFieldPath == nil {\n\t\t\tcontinue\n\t\t}\n\t\topts = append(opts, withMergeOptions(*p.ToFieldPath, p.Policy.MergeOptions))\n\t}\n\treturn opts\n}", "func _DoWithBackoffOptionWithDefault() DoWithBackoffOption {\n\treturn DoWithBackoffOptionFunc(func(*doWithBackoff) {\n\t\t// nothing to change\n\t})\n}", "func (e *ExternalService) Apply(opts ...func(*ExternalService)) {\n\tif e == nil {\n\t\treturn\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(e)\n\t}\n}", "func parseOptions(o Options) (Options, error) {\n\tif o.Capacity <= 0 {\n\t\to.Capacity = DefaultCapacity\n\t}\n\tif o.TimeProvider == nil {\n\t\to.TimeProvider = &timetools.RealTime{}\n\t}\n\treturn o, nil\n}", "func (o *SetoptionFlag) Execute(opts *Options) error {\n\tfor _, e := range *o {\n\t\tif err := e.Execute(opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Merge(target, source interface{}, opt *Options) error {\n\tvT := reflect.ValueOf(target)\n\tvS := reflect.ValueOf(source)\n\n\tif target != nil && vT.Type() == valType {\n\t\tvT = vT.Interface().(reflect.Value)\n\t}\n\tif source != nil && vS.Type() == valType {\n\t\tvS = vS.Interface().(reflect.Value)\n\t}\n\n\tif vT.Kind() != reflect.Ptr {\n\t\treturn errors.New(\"target must be a pointer\")\n\t}\n\n\tif !reflect.Indirect(vT).IsValid() {\n\t\treturn errors.New(\"target can not be zero value\")\n\t}\n\n\t// use defaults if none are provided\n\tif opt == nil {\n\t\topt = NewOptions()\n\t}\n\n\tif opt.mergeFuncs == nil {\n\t\treturn errors.New(\"invalid options, use NewOptions() to generate and then modify as needed\")\n\t}\n\n\t//make a copy here so if there is an error mid way, the target stays in tact\n\tcp := vT.Elem()\n\n\tmerged, err := merge(cp, reflect.Indirect(vS), opt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !isSettable(vT.Elem(), merged) {\n\t\treturn fmt.Errorf(\"Merge failed: expected merged result to be %v but got %v\",\n\t\t\tvT.Elem().Type(), merged.Type())\n\t}\n\n\tvT.Elem().Set(merged)\n\treturn nil\n}", "func (o *RemoveDropRequestParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func flattenOptions(dst, src Options) Options {\n\tfor _, opt := range src {\n\t\tswitch opt := opt.(type) {\n\t\tcase nil:\n\t\t\tcontinue\n\t\tcase Options:\n\t\t\tdst = flattenOptions(dst, opt)\n\t\tcase coreOption:\n\t\t\tdst = append(dst, opt)\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"invalid option type: %T\", opt))\n\t\t}\n\t}\n\treturn dst\n}", "func MergeReplaceOptions(opts ...*ReplaceOptions) *ReplaceOptions {\n\trOpts := Replace()\n\tfor _, ro := range opts {\n\t\tif ro == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif ro.BypassDocumentValidation != nil {\n\t\t\trOpts.BypassDocumentValidation = ro.BypassDocumentValidation\n\t\t}\n\t\tif ro.Collation != nil {\n\t\t\trOpts.Collation = ro.Collation\n\t\t}\n\t\tif ro.Upsert != nil {\n\t\t\trOpts.Upsert = ro.Upsert\n\t\t}\n\t}\n\n\treturn rOpts\n}", "func (c *operatorConfig) apply(options []OperatorOption) {\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tvar err error\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"aead_type\":\n\t\t\t\topts.WithAeadType = wrapping.AeadTypeMap(v)\n\t\t\tcase \"hash_type\":\n\t\t\t\topts.WithHashType = wrapping.HashTypeMap(v)\n\t\t\tcase \"key\":\n\t\t\t\topts.WithKey, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding key value: %w\", err)\n\t\t\t\t}\n\t\t\tcase \"salt\":\n\t\t\t\topts.WithSalt, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding salt value: %w\", err)\n\t\t\t\t}\n\t\t\tcase \"info\":\n\t\t\t\topts.WithInfo, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding info value: %w\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func MergeUpdateOptions(opts ...*UpdateOptions) *UpdateOptions {\n\tuOpts := Update()\n\tfor _, uo := range opts {\n\t\tif uo == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif uo.ArrayFilters != nil {\n\t\t\tuOpts.ArrayFilters = uo.ArrayFilters\n\t\t}\n\t\tif uo.BypassDocumentValidation != nil {\n\t\t\tuOpts.BypassDocumentValidation = uo.BypassDocumentValidation\n\t\t}\n\t\tif uo.Upsert != nil {\n\t\t\tuOpts.Upsert = uo.Upsert\n\t\t}\n\t}\n\n\treturn uOpts\n}", "func (set *Set) RefreshWithBuiltinOptions(entries [][]string) error {\n\tvar err error\n\n\t// The set-name must be < 32 characters!\n\ttempName := set.Name + \"-\"\n\n\tnewSet := &Set{\n\t\tParent: set.Parent,\n\t\tName: tempName,\n\t\tOptions: set.Options,\n\t}\n\n\terr = set.Parent.Add(newSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = newSet.BatchAdd(entries)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = set.Swap(newSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = set.Parent.Destroy(tempName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (req *UpsertRequest) Opts(opts UpsertOpts) *UpsertRequest {\n\treq.opts = opts\n\treturn req\n}", "func (pc ParseContext) Merge(o ParseContext) {\n\tfor k, vs := range o.Args {\n\t\tpc.Args[k] = append(pc.Args[k], vs...)\n\t}\n\n\tfor k, vs := range o.Opts {\n\t\tpc.Opts[k] = append(pc.Opts[k], vs...)\n\t}\n}", "func (f *Foo) Option(opts ...option) (previous option) {\n\tfor _, opt := range opts {\n\t\tprevious = opt(f)\n\t}\n\treturn previous\n}", "func InitWith(appName string, opts ...Opt) error {\n\n\t// Add baseInitOpt.\n\topts = append(opts, &baseInitOpt{})\n\n\t// Sort by order().\n\tsort.Sort(optSlice(opts))\n\n\t// Check for duplicate Opts.\n\tfor i := 0; i < len(opts)-1; i++ {\n\t\tif opts[i].order() == opts[i+1].order() {\n\t\t\treturn fmt.Errorf(\"Only one of each type of Opt can be used.\")\n\t\t}\n\t}\n\n\t// Run all preinit's.\n\tfor _, o := range opts {\n\t\tif err := o.preinit(appName); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Run all init's.\n\tfor _, o := range opts {\n\t\tif err := o.init(appName); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tsklog.Flush()\n\treturn nil\n}", "func (o *opts) WithLogger(value ILogger) *opts {\n\tb := value\n\n\to.log = b\n\n\treturn o\n}", "func (opt ArgJoiner) argApply(o *argOptions) {\n\to.joiner = string(opt)\n}", "func (r *bitroute) UseOptionsReplies(enabled bool) {\n\tr.optionsRepliesEnabled = enabled\n}", "func (opts *clientOptions) ApplyToGithubClientOptions(target *clientOptions) error {\n\t// Apply common values, if any\n\tif err := opts.CommonClientOptions.ApplyToCommonClientOptions(&target.CommonClientOptions); err != nil {\n\t\treturn err\n\t}\n\n\tif opts.AuthTransport != nil {\n\t\t// Make sure the user didn't specify the AuthTransport twice\n\t\tif target.AuthTransport != nil {\n\t\t\treturn fmt.Errorf(\"option AuthTransport already configured: %w\", gitprovider.ErrInvalidClientOptions)\n\t\t}\n\t\ttarget.AuthTransport = opts.AuthTransport\n\t}\n\n\tif opts.EnableConditionalRequests != nil {\n\t\t// Make sure the user didn't specify the EnableConditionalRequests twice\n\t\tif target.EnableConditionalRequests != nil {\n\t\t\treturn fmt.Errorf(\"option EnableConditionalRequests already configured: %w\", gitprovider.ErrInvalidClientOptions)\n\t\t}\n\t\ttarget.EnableConditionalRequests = opts.EnableConditionalRequests\n\t}\n\treturn nil\n}", "func (o *ValidatingAdmissionPolicyStatusControllerOptions) ApplyTo(cfg *validatingadmissionpolicystatusconfig.ValidatingAdmissionPolicyStatusControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ConcurrentPolicySyncs = o.ConcurrentPolicySyncs\n\n\treturn nil\n}", "func (o Option) apply(r *Upload) *Upload { return o(r).(*Upload) }", "func Options(opts ...Option) Option {\n\treturn optionFunc(func(app *App) {\n\t\tfor _, opt := range opts {\n\t\t\topt.apply(app)\n\t\t}\n\t})\n}", "func (o *arg) setDefault() error {\n\t// Only set default if it was not parsed, and default value was defined\n\tif !o.parsed && o.opts != nil && o.opts.Default != nil {\n\t\tswitch o.result.(type) {\n\t\tcase *bool, *int, *float64, *string, *[]bool, *[]int, *[]float64, *[]string:\n\t\t\tif reflect.TypeOf(o.result) != reflect.PtrTo(reflect.TypeOf(o.opts.Default)) {\n\t\t\t\treturn fmt.Errorf(\"cannot use default type [%T] as value of pointer with type [%T]\", o.opts.Default, o.result)\n\t\t\t}\n\t\t\tdefaultValue := o.opts.Default\n\t\t\tif o.argType == Flag && defaultValue == true {\n\t\t\t\tdefaultValue = false\n\t\t\t}\n\t\t\treflect.ValueOf(o.result).Elem().Set(reflect.ValueOf(defaultValue))\n\n\t\tcase *os.File:\n\t\t\tif err := o.setDefaultFile(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase *[]os.File:\n\t\t\tif err := o.setDefaultFiles(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func ApplyOptions() metav1.ApplyOptions {\n\treturn metav1.ApplyOptions{\n\t\tForce: true,\n\t\tFieldManager: ReflectionFieldManager,\n\t}\n}" ]
[ "0.6115116", "0.60880756", "0.60818255", "0.5963018", "0.58978915", "0.5830136", "0.5801093", "0.5780717", "0.5702616", "0.5656612", "0.5655646", "0.564559", "0.56109065", "0.5607306", "0.5561439", "0.544544", "0.5429387", "0.5372531", "0.5360312", "0.53601557", "0.5357337", "0.53457063", "0.53180736", "0.5253595", "0.5249485", "0.5241074", "0.5223084", "0.51993185", "0.51557547", "0.515023", "0.50608253", "0.50446856", "0.50415564", "0.502253", "0.5000679", "0.49582678", "0.49464443", "0.49308616", "0.49114552", "0.48818496", "0.48684248", "0.4839006", "0.4833138", "0.4822891", "0.47779623", "0.47721133", "0.47689778", "0.47553855", "0.47101408", "0.46690345", "0.46590796", "0.46587205", "0.463781", "0.46109885", "0.45850447", "0.45838764", "0.4571388", "0.4562241", "0.45609662", "0.45597035", "0.45542943", "0.45481423", "0.45476133", "0.45251286", "0.44955528", "0.44859657", "0.44855452", "0.44748196", "0.44706663", "0.44696125", "0.44691014", "0.44661078", "0.44536725", "0.44235888", "0.44113353", "0.4391384", "0.43899417", "0.4388755", "0.43883482", "0.43872032", "0.43817094", "0.4373046", "0.43701014", "0.43650433", "0.4360034", "0.43442824", "0.43332192", "0.4327559", "0.43075728", "0.43034938", "0.4266665", "0.4264801", "0.42537868", "0.42456368", "0.4227048", "0.4217454", "0.42126524", "0.4211715", "0.42090455", "0.42002523" ]
0.49006703
39
VersionString returns a TLS version string.
func VersionString(value uint16) string { if str, found := tlsVersionString[value]; found { return str } return fmt.Sprintf("TLS_VERSION_UNKNOWN_%d", value) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func VersionString() string {\n\treturn C.GoString(C.LZ4_versionString())\n}", "func TLSVersion(ver uint16) string {\n\tswitch ver {\n\tcase tls.VersionTLS10:\n\t\treturn \"1.0\"\n\tcase tls.VersionTLS11:\n\t\treturn \"1.1\"\n\tcase tls.VersionTLS12:\n\t\treturn \"1.2\"\n\t}\n\treturn fmt.Sprintf(\"Unknown [%x]\", ver)\n}", "func (v *Version) VersionString() string {\n\treturn fmt.Sprintf(\"%s%d.%d.%d%s\", v.Prefix, v.Major, v.Minor, v.Maintenance, v.Suffix)\n}", "func VersionString() string {\n\tif VersionStability != \"stable\" {\n\t\treturn fmt.Sprintf(\"%s-%s\", Version, VersionStability)\n\t}\n\treturn Version\n}", "func GetFormattedVersionString() string {\n\tif versionString == \"\" {\n\t\tversionString = \"Unknown\"\n\t}\n\treturn versionString\n}", "func GetVersionString() string {\n\treturn fmt.Sprintf(\"Praefect, version %v\", version.GetVersion())\n}", "func versionString() string {\n\tvar version string\n\tif SHA != \"\" {\n\t\tversion = fmt.Sprintf(\"%s (%s)\", Version, SHA)\n\t} else {\n\t\tversion = fmt.Sprintf(\"%s-dev\", Version) // no SHA. '0.x.y-dev' indicates it is run from source without build script.\n\t}\n\tif BuildTime != \"\" {\n\t\ti, err := strconv.ParseInt(BuildTime, 10, 64)\n\t\tif err == nil {\n\t\t\ttm := time.Unix(i, 0)\n\t\t\tversion += fmt.Sprintf(\" built %s\", tm.Format(time.RFC822))\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"dnscontrol %s\", version)\n}", "func (pv ProtocolVersion) String() string {\n\tstr := fmt.Sprintf(\"%d.%d.%d\",\n\t\t(pv.Version>>24)&0xFF, // major\n\t\t(pv.Version>>16)&0xFF, // minor\n\t\t(pv.Version>>8)&0xFF, // patch\n\t)\n\n\t// optional build number, only printed when non-0\n\tif build := pv.Version & 0xFF; build != 0 {\n\t\tstr += fmt.Sprintf(\".%d\", build)\n\t}\n\n\t// optional prerelease\n\tif pv.Prerelease != nilPreRelease {\n\t\tindex := 0\n\t\tfor index < 8 && pv.Prerelease[index] != 0 {\n\t\t\tindex++\n\t\t}\n\t\tstr += \"-\" + string(pv.Prerelease[:index])\n\t}\n\n\treturn str\n}", "func TLSVersionName(version uint16) string {\n\tswitch version {\n\tcase tls.VersionSSL30:\n\t\treturn \"SSL 3.0\"\n\tcase tls.VersionTLS10:\n\t\treturn \"TLS 1.0\"\n\tcase tls.VersionTLS11:\n\t\treturn \"TLS 1.1\"\n\tcase tls.VersionTLS12:\n\t\treturn \"TLS 1.2\"\n\tcase tls.VersionTLS13:\n\t\treturn \"TLS 1.3\"\n\t}\n\n\treturn \"Unknown\"\n}", "func GetTLSVersion(tr *http.Transport) string {\n switch tr.TLSClientConfig.MinVersion {\n case tls.VersionTLS10:\n return \"TLS 1.0\"\n case tls.VersionTLS11:\n return \"TLS 1.1\"\n case tls.VersionTLS12:\n return \"TLS 1.2\"\n case tls.VersionTLS13:\n return \"TLS 1.3\"\n }\n\n return \"Unknown\"\n}", "func (v Version) String() string {\n\treturn fmt.Sprintf(\"%d.%d.%d\", v.Major, v.Minor, v.Patch)\n}", "func (v Version) String() string {\n\treturn fmt.Sprintf(\"%d.%d.%d\", v.Major, v.Minor, v.Patch)\n}", "func (v Version) String() string {\n\treturn fmt.Sprintf(\"%0d.%0d\", v.Major, v.Minor)\n}", "func (v DefaultVersion) VersionString() string {\n\treturn v.spec\n}", "func (v Version) String() string {\n\treturn fmt.Sprintf(\"v%d.%d.%d\", v.Major, v.Minor, v.Patches)\n}", "func (v Version) String() string {\n\tvs := fmt.Sprintf(\"%d.%d.%d\", v.major, v.minor, v.patch)\n\tif len(v.preRelease) > 0 {\n\t\tvs += \"-\" + v.PreRelease()\n\t}\n\tif len(v.metadata) > 0 {\n\t\tvs += Metadata + v.Metadata()\n\t}\n\treturn vs\n}", "func GetVersionString() string {\n\treturn \"simple-http-server 1.0\"\n}", "func versionString() string {\n\treturn fmt.Sprintf(\"%s-%s\\n\", caddy.AppName, caddy.AppVersion)\n}", "func String() string {\n\treturn Version\n}", "func Version() string {\n\tapi := C.Create()\n\tdefer C.Free(api)\n\tversion := C.Version(api)\n\treturn C.GoString(version)\n}", "func GetVersionString() string {\n\treturn fmt.Sprintf(\"%s version %s\", os.Args[0], config.Version)\n}", "func (v Version) String() string {\n\ts := strconv.Itoa(v.Major) + \".\" + strconv.Itoa(v.Minor)\n\tif v.Patch > 0 {\n\t\ts += \".\" + strconv.Itoa(v.Patch)\n\t}\n\tif v.PreRelease != \"\" {\n\t\ts += v.PreRelease\n\t}\n\n\treturn s\n}", "func Version(message string) string {\n\treturn Encode(VERSION, message)\n}", "func GetVersion() string {\n\tvar versionString bytes.Buffer\n\tfmt.Fprintf(&versionString, \"v%s\", versn)\n\tif env != \"\" {\n\t\tfmt.Fprintf(&versionString, \"-%s\", env)\n\t}\n\n\treturn versionString.String()\n}", "func (v IPVSVersion) String() string {\n\treturn fmt.Sprintf(\"%d.%d.%d\", v.Major, v.Minor, v.Patch)\n}", "func (v Version) String() (s string) {\n\tif v.epoch != 0 {\n\t\ts = strconv.Itoa(v.epoch) + \":\"\n\t}\n\ts += v.version\n\tif v.revision != \"\" {\n\t\ts += \"-\" + v.revision\n\t}\n\treturn\n}", "func (m *MongoCrypt) CryptSharedLibVersionString() string {\n\t// Pass in a pointer for \"len\", but ignore the value because C.GoString can determine the string\n\t// length without it.\n\tlen := C.uint(0)\n\tstr := C.GoString(C.mongocrypt_crypt_shared_lib_version_string(m.wrapped, &len))\n\treturn str\n}", "func (client *Client) Version() string {\n\tversion := C.Version(client.api)\n\treturn C.GoString(version)\n}", "func (ver Version) String() string {\n\tif ver.RawVersion != \"\" {\n\t\treturn ver.RawVersion\n\t}\n\tv := fmt.Sprintf(\"v%d.%d.%d\", ver.Major, ver.Minor, ver.Patch)\n\tif ver.PreRelease != \"\" {\n\t\tv += \"-\" + ver.PreRelease\n\t}\n\tif ver.GitHash != \"\" {\n\t\tv += \"(\" + ver.GitHash + \")\"\n\t}\n\t// TODO: Add metadata about the commit or build hash.\n\t// See https://golang.org/issue/29814\n\t// See https://golang.org/issue/33533\n\tvar metadata = strings.Join(ver.MetaData, \".\")\n\tif strings.Contains(ver.PreRelease, \"devel\") && metadata != \"\" {\n\t\tv += \"+\" + metadata\n\t}\n\treturn v\n}", "func (v Version) Version() VersionString {\n\treturn VersionString(v.String())\n}", "func Version() string {\n\tif len(version) == 0 {\n\t\treturn \"UNKNOWN_VERSION\"\n\t}\n\treturn version\n}", "func GetVersionString() string {\n\treturn C.GoString(C.glfwGetVersionString())\n}", "func GetVersionString() string {\n\treturn C.GoString(C.glfwGetVersionString())\n}", "func GetVersionString() string {\n\treturn C.GoString(C.glfwGetVersionString())\n}", "func (version Version) String() string {\n\treturn strconv.Itoa(int(version))\n}", "func (version Version) String() string {\n\treturn strconv.Itoa(int(version))\n}", "func Version() string {\r\n\tonce.Do(func() {\r\n\t\tsemver := fmt.Sprintf(\"%d.%d.%d\", major, minor, patch)\r\n\t\tverBuilder := bytes.NewBufferString(semver)\r\n\t\tif tag != \"\" && tag != \"-\" {\r\n\t\t\tupdated := strings.TrimPrefix(tag, \"-\")\r\n\t\t\t_, err := verBuilder.WriteString(\"-\" + updated)\r\n\t\t\tif err == nil {\r\n\t\t\t\tverBuilder = bytes.NewBufferString(semver)\r\n\t\t\t}\r\n\t\t}\r\n\t\tversion = verBuilder.String()\r\n\t})\r\n\treturn version\r\n}", "func Version() string {\n\treturn C.GoString(C.yices_version)\n}", "func Version() string {\n\tstr := C.GoString(C.mongocrypt_version(nil))\n\treturn str\n}", "func (p ProtocolVersion) String() string {\n\tswitch p {\n\tcase ProtocolVersionUnrecorded:\n\t\treturn \"Unrecorded\"\n\n\tcase ProtocolVersionLegacy:\n\t\treturn \"Legacy\"\n\n\tcase ProtocolVersionMultiLoopOut:\n\t\treturn \"Multi Loop Out\"\n\n\tcase ProtocolVersionSegwitLoopIn:\n\t\treturn \"Segwit Loop In\"\n\n\tcase ProtocolVersionPreimagePush:\n\t\treturn \"Preimage Push\"\n\n\tcase ProtocolVersionUserExpiryLoopOut:\n\t\treturn \"User Expiry Loop Out\"\n\n\tcase ProtocolVersionHtlcV2:\n\t\treturn \"HTLC V2\"\n\n\tcase ProtocolVersionLoopOutCancel:\n\t\treturn \"Loop Out Cancel\"\n\n\tcase ProtocolVersionProbe:\n\t\treturn \"Probe\"\n\n\tcase ProtocolVersionRoutingPlugin:\n\t\treturn \"Routing Plugin\"\n\n\tcase ProtocolVersionHtlcV3:\n\t\treturn \"HTLC V3\"\n\n\tcase ProtocolVersionMuSig2:\n\t\treturn \"MuSig2\"\n\n\tdefault:\n\t\treturn \"Unknown\"\n\t}\n}", "func GetVersion() string {\n\treturn VersionString\n}", "func (fmd *FakeMysqlDaemon) GetVersionString(ctx context.Context) (string, error) {\n\treturn fmd.Version, nil\n}", "func Version() string {\n\tvar hashStr string\n\tif CommitHash != \"\" {\n\t\thashStr = \"+\" + CommitHash\n\t}\n\n\tif currentVersion.label == \"\" {\n\t\treturn fmt.Sprintf(\"%d.%d.%d%s\", currentVersion.major, currentVersion.minor, currentVersion.patch, hashStr)\n\t}\n\n\treturn fmt.Sprintf(\"%d.%d.%d-%s%s\", currentVersion.major, currentVersion.minor, currentVersion.patch, currentVersion.label, hashStr)\n}", "func GetVersion() string {\n\tversion := fmt.Sprintf(`Version : %s\nTag : %s\nBuildTime : %s\nGitHash : %s\nRunMode : %s\nDistribution: %s\nServiceName : %s\n`, CCVersion, CCTag, CCBuildTime, CCGitHash, CCRunMode, CCDistro, ServiceName)\n\treturn version\n}", "func VersionText() string {\n\treturn C.GoString(C.Pa_GetVersionText())\n}", "func (v ComponentVersion) String() string {\n\treturn v.Version\n}", "func (o LayerVersionOutput) Version() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *LayerVersion) pulumi.StringOutput { return v.Version }).(pulumi.StringOutput)\n}", "func (v *Version) String() string {\n\treturn fmt.Sprintf(\"Version: %s%d.%d.%d%s\\nBuild Date: %s\\n Minimum Go Version: %s\",\n\t\tv.Prefix, v.Major, v.Minor, v.Maintenance, v.Suffix, v.BuildDate, v.MinGoVersion)\n}", "func (s SymanticVersion) String() string {\n\treturn fmt.Sprintf(\"%v.%v.%v.%v\", s.Major, s.Minor, s.Patch, s.Build)\n}", "func Version() string {\n\tversion := C.GoString(C.lxc_get_version())\n\n\t// New liblxc versions append \"-devel\" when LXC_DEVEL is set.\n\tif strings.HasSuffix(version, \"-devel\") {\n\t\treturn fmt.Sprintf(\"%s (devel)\", version[:(len(version)-len(\"-devel\"))])\n\t}\n\n\treturn version\n}", "func (u *Uname) Version() string {\n\treturn toString(u.Utsname.Version[:])\n}", "func BuildVersionString() string {\n\tprogram := \"k8s-device-plugin\"\n\n\tversion := \"v\" + CurrentVersion.String()\n\tif CommitHash != \"\" {\n\t\tversion += \"-\" + strings.ToUpper(CommitHash)\n\t}\n\n\tosArch := runtime.GOOS + \"/\" + runtime.GOARCH\n\n\tdate := BuildDate\n\tif date == \"\" {\n\t\tdate = \"unknown\"\n\t}\n\n\treturn fmt.Sprintf(\"%s %s %s BuildDate: %s\", program, version, osArch, date)\n\n}", "func (t OptTPacketVersion) String() string {\n\tswitch t {\n\tcase TPacketVersion1:\n\t\treturn \"V1\"\n\tcase TPacketVersion2:\n\t\treturn \"V2\"\n\tcase TPacketVersion3:\n\t\treturn \"V3\"\n\tcase TPacketVersionHighestAvailable:\n\t\treturn \"HighestAvailable\"\n\t}\n\treturn \"InvalidVersion\"\n}", "func Version() string {\n\treturn fmt.Sprintf(\"%v (%v %v)\", version, revisionDate, revision)\n}", "func Version() string {\n\treturn C.GoString(C.worker_version())\n}", "func (s InvalidPolicyVersionError) Version() string {\n\treturn string(s)\n}", "func Version() (string, error) {\n\treturn makeRequest(\"version\")\n}", "func Version() string {\n\treturn versionNumber\n}", "func (l *Libvirt) Version() (string, error) {\n\tver, err := l.ConnectGetLibVersion()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// The version is provided as an int following this formula:\n\t// version * 1,000,000 + minor * 1000 + micro\n\t// See src/libvirt-host.c # virConnectGetLibVersion\n\tmajor := ver / 1000000\n\tver %= 1000000\n\tminor := ver / 1000\n\tver %= 1000\n\tmicro := ver\n\n\tversionString := fmt.Sprintf(\"%d.%d.%d\", major, minor, micro)\n\treturn versionString, nil\n}", "func Version() string {\n\treturn version\n}", "func Version() string {\n\treturn version\n}", "func Version() string {\n\treturn version\n}", "func Version() string {\n\treturn version\n}", "func Version() string {\n\treturn version\n}", "func Version() string {\n\treturn version\n}", "func Version() string {\n\treturn version\n}", "func Version() string {\n\treturn version\n}", "func Version() string {\n\tp := C.unqlite_lib_version()\n\treturn C.GoString(p)\n}", "func (sem *SemVer) String() (version string) {\n\tbase := fmt.Sprintf(\"v%d.%d.%d\", sem.Major, sem.Minor, sem.Patch)\n\tif len(sem.Pre) > 0 {\n\t\tvar build string\n\t\tfor _, val := range sem.Pre {\n\t\t\tbuild = build + \"-\" + val.String()\n\t\t}\n\t\treturn fmt.Sprintf(\"%s%s\", base, build)\n\t}\n\treturn base\n}", "func Version() string {\n\treturn fmt.Sprintf(\"%s %s %s\", AppVendor, AppName, AppVersion)\n}", "func Version() string {\n\tp := C.sqlite3_libversion()\n\treturn C.GoString(p)\n}", "func String() string {\n\tvar version bytes.Buffer\n\tif AppName != \"\" {\n\t\tfmt.Fprintf(&version, \"%s \", AppName)\n\t}\n\tfmt.Fprintf(&version, \"v%s\", Version)\n\tif Prerelease != \"\" {\n\t\tfmt.Fprintf(&version, \"-%s\", Prerelease)\n\t}\n\n\treturn version.String()\n}", "func GetVersion() (string, error) {\n\tvar buffer [4096]C.char\n\tvar cversion *C.char\n\n\trc, err := C.llapi_get_version(&buffer[0], C.int(len(buffer)), &cversion)\n\tif err := isError(rc, err); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn C.GoString(cversion), nil\n}", "func SprintfVersion(v csi.Version) string {\n\treturn fmt.Sprintf(\"%d.%d.%d\", v.Major, v.Minor, v.Patch)\n}", "func (c *Client) Version() (string, error) {\n\tv, err := c.Clientset.ServerVersion()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn v.String(), nil\n}", "func (n Version) String() string {\n\tif s, ok := verStrings[n]; ok {\n\t\treturn s\n\t}\n\treturn \"unknown\"\n}", "func Version() (version string) {\n\treturn GetVersion()\n}", "func (d *Diag) Version() string {\n\treturn bufToString(d.SzVersionString[:])\n}", "func (g *goVersion) String() string {\n\treturn g.golangVersion()\n}", "func LongString() string {\n\tvar version bytes.Buffer\n\n\tfmt.Fprintf(&version, \"%s\", String())\n\n\tif Build != \"\" {\n\t\tfmt.Fprintf(&version, \"+build.%s\", Build)\n\t\tif GitCommit != \"\" {\n\t\t\tfmt.Fprintf(&version, \".%s\", GitCommit)\n\t\t}\n\t}\n\n\trelease, ok := manifest.KubeManifest.Releases[Version]\n\tif !ok {\n\t\treturn version.String()\n\t}\n\n\tif len(release.KubernetesVersion) != 0 {\n\t\tfmt.Fprintf(&version, \"\\nKubernetes version: %s\", release.KubernetesVersion)\n\t}\n\tif len(release.DockerVersion) != 0 {\n\t\tfmt.Fprintf(&version, \"\\nDocker version: %s\", release.DockerVersion)\n\t}\n\tif len(release.EtcdVersion) != 0 {\n\t\tfmt.Fprintf(&version, \"\\netcd version: %s\", release.EtcdVersion)\n\t}\n\n\treturn version.String()\n}", "func StringToTLSVersion(st string) TLSVersion {\n\tswitch TLSVersion(st) {\n\tcase TLSVersion1p0:\n\t\treturn TLSVersion1p0\n\tcase TLSVersion1p1:\n\t\treturn TLSVersion1p1\n\tcase TLSVersion1p2:\n\t\treturn TLSVersion1p2\n\tcase TLSVersion1p3:\n\t\treturn TLSVersion1p3\n\t}\n\treturn TLSVersionInvalid\n}", "func (e E_OpenconfigSystem_System_SshServer_Config_ProtocolVersion) String() string {\n\treturn ygot.EnumLogString(e, int64(e), \"E_OpenconfigSystem_System_SshServer_Config_ProtocolVersion\")\n}", "func (_TTFT20 *TTFT20Session) Version() (string, error) {\n\treturn _TTFT20.Contract.Version(&_TTFT20.CallOpts)\n}", "func Version() string {\n\treturn libs.Version()\n}", "func formatVersion(v string) string {\n\tconst maxLen = 25\n\tif len(v) <= maxLen {\n\t\treturn v\n\t}\n\tvType, err := version.ParseType(v)\n\tif err != nil {\n\t\tlog.Errorf(context.TODO(), \"formatVersion(%q): error parsing version: %v\", v, err)\n\t\treturn v\n\t}\n\tif vType != version.TypePseudo {\n\t\t// If the version is release or prerelease, return a version string of\n\t\t// maxLen by truncating the end of the string. maxLen is inclusive of\n\t\t// the \"...\" characters.\n\t\treturn v[:maxLen-3] + \"...\"\n\t}\n\n\t// The version string will have a max length of 25:\n\t// base: \"vX.Y.Z-prerelease.0\" = up to 15\n\t// ellipse: \"...\" = 3\n\t// commit: \"-abcdefa\" = 7\n\tcommit := shorten(pseudoVersionRev(v), 7)\n\tbase := shorten(pseudoVersionBase(v), 15)\n\treturn fmt.Sprintf(\"%s...-%s\", base, commit)\n}", "func LibraryVersion() string {\n\treturn C.GoString(C.rl_library_version)\n}", "func Version() string {\n\treturn fmt.Sprint(\"C v1.2\", \"->\", d.Version())\n}", "func GetVersion(self *C.PyObject, args *C.PyObject) *C.PyObject {\n\tav, _ := version.New(version.AgentVersion, version.Commit)\n\n\tcStr := C.CString(av.GetNumber())\n\tpyStr := C.PyString_FromString(cStr)\n\tC.free(unsafe.Pointer(cStr))\n\treturn pyStr\n}", "func (api *API) Version(ctx context.Context) (string, error) {\n\taddr := api.host + \":\" + api.port\n\treturn version(addr)\n}", "func (v *V0) Version() string {\n\tif v == nil {\n\t\treturn VersionUnknown.String()\n\t}\n\treturn v.version.String()\n}", "func Version() string {\n\tvv := version{\n\t\tGitCommit: GitCommit,\n\t\tReleaseVersion: ReleaseVersion,\n\t\tBuildTime: BuildTime,\n\t}\n\tb, err := json.Marshal(vv)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(b)\n}", "func (k *Keybase) version() string {\n\tcmdOut, err := k.Exec(\"version\", \"-S\", \"-f\", \"s\")\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\treturn string(cmdOut)\n}", "func String() string {\n\tv := fmt.Sprintf(\"v%d.%d.%d\", Major, Minor, Patch)\n\tif PreRelease != \"\" {\n\t\tv += \"-\" + PreRelease\n\t}\n\treturn v\n}", "func (o NetworkEndpointGroupAppEngineResponseOutput) Version() pulumi.StringOutput {\n\treturn o.ApplyT(func(v NetworkEndpointGroupAppEngineResponse) string { return v.Version }).(pulumi.StringOutput)\n}", "func (o ClientLibrarySettingsResponseOutput) Version() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ClientLibrarySettingsResponse) string { return v.Version }).(pulumi.StringOutput)\n}", "func (mc *Client) Version() string {\n\n\treturn mc.info.Version\n}", "func terraformVersionString(ctx context.Context, execPath string) (string, error) {\n\ttmpDir, err := os.MkdirTemp(\"\", \"tfversion\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer os.RemoveAll(tmpDir)\n\n\ttf, err := tfexec.NewTerraform(tmpDir, execPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tversion, _, err := tf.Version(context.Background(), true)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn version.String(), nil\n}", "func (o NetworkEndpointGroupAppEngineOutput) Version() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v NetworkEndpointGroupAppEngine) *string { return v.Version }).(pulumi.StringPtrOutput)\n}", "func (r *Rkt) Version() (string, error) {\n\tver, err := r.Runner.CombinedOutput(\"rkt version\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// rkt Version: 1.24.0\n\t// appc Version: 0.8.10\n\tline := strings.Split(ver, \"\\n\")[0]\n\treturn strings.Replace(line, \"rkt Version: \", \"\", 1), nil\n}", "func (c *Client) Version() string {\n\treturn c.conn.Version()\n}" ]
[ "0.74643797", "0.7188609", "0.70724016", "0.70276886", "0.6924166", "0.6852171", "0.68485165", "0.68244296", "0.6796393", "0.6793432", "0.67549765", "0.67549765", "0.6725175", "0.6683086", "0.6674843", "0.66420186", "0.6634001", "0.6576915", "0.65724236", "0.6564921", "0.6546409", "0.6538453", "0.64431465", "0.6390172", "0.63689137", "0.6339908", "0.6328728", "0.63096", "0.62843883", "0.62830275", "0.6282773", "0.62682104", "0.62682104", "0.62682104", "0.62500787", "0.62500787", "0.62116396", "0.61987174", "0.61933446", "0.6189796", "0.6184143", "0.6164559", "0.6119192", "0.6103943", "0.60848373", "0.60618293", "0.6055845", "0.60406756", "0.6023757", "0.60044163", "0.6004124", "0.6002915", "0.5989458", "0.59883183", "0.5970228", "0.5965497", "0.59615976", "0.5945609", "0.592246", "0.5890377", "0.5890377", "0.5890377", "0.5890377", "0.5890377", "0.5890377", "0.5890377", "0.5890377", "0.58800375", "0.58696806", "0.586699", "0.58557427", "0.5855509", "0.585215", "0.5850275", "0.5849104", "0.58449733", "0.58431494", "0.5840503", "0.5834918", "0.58325136", "0.5805777", "0.579793", "0.57960546", "0.5794661", "0.57915443", "0.57766557", "0.5766023", "0.57609695", "0.5752789", "0.5742628", "0.57380605", "0.5734378", "0.573253", "0.5731833", "0.5719116", "0.57168096", "0.5713161", "0.5703269", "0.570025", "0.56975526" ]
0.77363867
0
CipherSuiteString returns the TLS cipher suite as a string.
func CipherSuiteString(value uint16) string { if str, found := tlsCipherSuiteString[value]; found { return str } return fmt.Sprintf("TLS_CIPHER_SUITE_UNKNOWN_%d", value) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CipherSuiteName(suite uint16) string {\n\tswitch suite {\n\tcase tls.TLS_RSA_WITH_RC4_128_SHA:\n\t\treturn \"TLS_RSA_WITH_RC4_128_SHA\"\n\tcase tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA:\n\t\treturn \"TLS_RSA_WITH_3DES_EDE_CBC_SHA\"\n\tcase tls.TLS_RSA_WITH_AES_128_CBC_SHA:\n\t\treturn \"TLS_RSA_WITH_AES_128_CBC_SHA\"\n\tcase tls.TLS_RSA_WITH_AES_256_CBC_SHA:\n\t\treturn \"TLS_RSA_WITH_AES_256_CBC_SHA\"\n\tcase tls.TLS_RSA_WITH_AES_128_CBC_SHA256:\n\t\treturn \"TLS_RSA_WITH_AES_128_CBC_SHA256\"\n\tcase tls.TLS_RSA_WITH_AES_128_GCM_SHA256:\n\t\treturn \"TLS_RSA_WITH_AES_128_GCM_SHA256\"\n\tcase tls.TLS_RSA_WITH_AES_256_GCM_SHA384:\n\t\treturn \"TLS_RSA_WITH_AES_256_GCM_SHA384\"\n\tcase tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA\"\n\tcase tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA\"\n\tcase tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA\"\n\tcase tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA:\n\t\treturn \"TLS_ECDHE_RSA_WITH_RC4_128_SHA\"\n\tcase tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:\n\t\treturn \"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA\"\n\tcase tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA\"\n\tcase tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA\"\n\tcase tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256\"\n\tcase tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256\"\n\tcase tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\"\n\tcase tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\"\n\tcase tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\"\n\tcase tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\"\n\tcase tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:\n\t\treturn \"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256\"\n\tcase tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256\"\n\tcase tls.TLS_AES_128_GCM_SHA256:\n\t\treturn \"TLS_AES_128_GCM_SHA256\"\n\tcase tls.TLS_AES_256_GCM_SHA384:\n\t\treturn \"TLS_AES_256_GCM_SHA384\"\n\tcase tls.TLS_CHACHA20_POLY1305_SHA256:\n\t\treturn \"TLS_CHACHA20_POLY1305_SHA256\"\n\tcase tls.TLS_FALLBACK_SCSV:\n\t\treturn \"TLS_FALLBACK_SCSV\"\n\t}\n\n\treturn \"Unknown\"\n}", "func CipherSuiteName(id uint16) string", "func cipherSuiteName(id uint16) string {\n\tswitch id {\n\tcase 0x0005:\n\t\treturn \"TLS_RSA_WITH_RC4_128_SHA\"\n\tcase 0x000a:\n\t\treturn \"TLS_RSA_WITH_3DES_EDE_CBC_SHA\"\n\tcase 0x002f:\n\t\treturn \"TLS_RSA_WITH_AES_128_CBC_SHA\"\n\tcase 0x0035:\n\t\treturn \"TLS_RSA_WITH_AES_256_CBC_SHA\"\n\tcase 0x003c:\n\t\treturn \"TLS_RSA_WITH_AES_128_CBC_SHA256\"\n\tcase 0x009c:\n\t\treturn \"TLS_RSA_WITH_AES_128_GCM_SHA256\"\n\tcase 0x009d:\n\t\treturn \"TLS_RSA_WITH_AES_256_GCM_SHA384\"\n\tcase 0xc007:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA\"\n\tcase 0xc009:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA\"\n\tcase 0xc00a:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA\"\n\tcase 0xc011:\n\t\treturn \"TLS_ECDHE_RSA_WITH_RC4_128_SHA\"\n\tcase 0xc012:\n\t\treturn \"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA\"\n\tcase 0xc013:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA\"\n\tcase 0xc014:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA\"\n\tcase 0xc023:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256\"\n\tcase 0xc027:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256\"\n\tcase 0xc02f:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\"\n\tcase 0xc02b:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\"\n\tcase 0xc030:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\"\n\tcase 0xc02c:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\"\n\tcase 0xcca8:\n\t\treturn \"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256\"\n\tcase 0xcca9:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256\"\n\tcase 0x1301:\n\t\treturn \"TLS_AES_128_GCM_SHA256\"\n\tcase 0x1302:\n\t\treturn \"TLS_AES_256_GCM_SHA384\"\n\tcase 0x1303:\n\t\treturn \"TLS_CHACHA20_POLY1305_SHA256\"\n\tcase 0x5600:\n\t\treturn \"TLS_FALLBACK_SCSV\"\n\t}\n\treturn fmt.Sprintf(\"0x%04X\", id)\n}", "func getEncryptionAlg(ciphersuite string) string {\n\tswitch ciphersuite {\n\tcase \"XSTREAM_X25519_HKDF_SHA256_AES128_SIV\":\n\t\treturn \"AES-SIV\"\n\tcase \"XSTREAM_X25519_HKDF_SHA256_AES128_PMAC_SIV\":\n\t\treturn \"AES-PMAC-SIV\"\n\tdefault:\n\t\tpanic(\"XSTREAM: unknown ciphersuite\")\n\t}\n}", "func CipherSuites() []*tls.CipherSuite", "func cipherToString(cipher packet.CipherFunction) string {\n\tswitch cipher {\n\tcase 2:\n\t\treturn \"3DES\"\n\tcase 3:\n\t\treturn \"CAST5\"\n\tcase 7:\n\t\treturn \"AES128\"\n\tcase 8:\n\t\treturn \"AES192\"\n\tcase 9:\n\t\treturn \"AES256\"\n\tdefault:\n\t\treturn \"NotKnown\"\n\t}\n}", "func InsecureCipherSuites() []*tls.CipherSuite", "func (suite Suite) String() string {\n\tnames := []string{\"Spade\", \"Clubs\", \"Hearts\", \"Diamond\"}\n\treturn names[suite]\n}", "func (c Cipher) String() string {\n\tswitch c {\n\tcase AES128CCM:\n\t\treturn \"AES-128-CCM\"\n\tcase AES128GCM:\n\t\treturn \"AES-128-GCM\"\n\tdefault:\n\t\treturn \"Cipher-\" + strconv.Itoa(int(c))\n\t}\n}", "func (s ListenerTls) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (c *Provider) CryptoSuite() core.CryptoSuite {\n\treturn c.cryptoSuite\n}", "func (s SecurityMode) String() string {\n\tswitch s {\n\tcase UnsecureOnly:\n\t\treturn UnsecureOnlyStr\n\tcase SecureOnly:\n\t\treturn SecureOnlyStr\n\tcase SecureAndUnsecure:\n\t\treturn SecureAndUnsecureStr\n\tcase UpgradeSecurity:\n\t\treturn UpgradeSecurityStr\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"invalid security mode value %d\", int(s)))\n\t}\n}", "func GetTLSVersion(tr *http.Transport) string {\n switch tr.TLSClientConfig.MinVersion {\n case tls.VersionTLS10:\n return \"TLS 1.0\"\n case tls.VersionTLS11:\n return \"TLS 1.1\"\n case tls.VersionTLS12:\n return \"TLS 1.2\"\n case tls.VersionTLS13:\n return \"TLS 1.3\"\n }\n\n return \"Unknown\"\n}", "func (s SimulationSoftwareSuite) String() string {\n\treturn awsutil.Prettify(s)\n}", "func TLSCipher(cs uint16) string {\n\tswitch cs {\n\tcase 0x0005:\n\t\treturn \"TLS_RSA_WITH_RC4_128_SHA\"\n\tcase 0x000a:\n\t\treturn \"TLS_RSA_WITH_3DES_EDE_CBC_SHA\"\n\tcase 0x002f:\n\t\treturn \"TLS_RSA_WITH_AES_128_CBC_SHA\"\n\tcase 0x0035:\n\t\treturn \"TLS_RSA_WITH_AES_256_CBC_SHA\"\n\tcase 0xc007:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA\"\n\tcase 0xc009:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA\"\n\tcase 0xc00a:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA\"\n\tcase 0xc011:\n\t\treturn \"TLS_ECDHE_RSA_WITH_RC4_128_SHA\"\n\tcase 0xc012:\n\t\treturn \"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA\"\n\tcase 0xc013:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA\"\n\tcase 0xc014:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA\"\n\tcase 0xc02f:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\"\n\tcase 0xc02b:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\"\n\tcase 0xc030:\n\t\treturn \"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\"\n\tcase 0xc02c:\n\t\treturn \"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\"\n\t}\n\treturn fmt.Sprintf(\"Unknown [%x]\", cs)\n}", "func (s RobotSoftwareSuite) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ListenerTlsCertificate) String() string {\n\treturn awsutil.Prettify(s)\n}", "func defaultCipherSuite() []uint16 {\n\treturn []uint16{\n\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\ttls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,\n\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,\n\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n\t\ttls.TLS_RSA_WITH_AES_128_GCM_SHA256,\n\t\ttls.TLS_RSA_WITH_AES_256_GCM_SHA384,\n\t\ttls.TLS_RSA_WITH_AES_128_CBC_SHA,\n\t\ttls.TLS_RSA_WITH_AES_256_CBC_SHA,\n\t}\n}", "func weakCipherSuites(details scan.LabsEndpointDetails) string {\n\t//Will require update as more vulnerabilities discovered, display results for TLS v1.2\n\t//https://github.com/ssllabs/research/wiki/SSL-and-TLS-Deployment-Best-Practices#23-use-secure-cipher-suites\n\tvar vulnSuites string\n\tfor _, suite := range details.Suites {\n\t\tfor _, suiteList := range suite.List {\n\t\t\tif !strings.Contains(suiteList.Name, \"DHE_\") {\n\t\t\t\tif suite.Protocol == 771 {\n\t\t\t\t\tvulnSuites += suiteList.Name + \"\\n\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn (vulnSuites)\n}", "func (pc *MockProviderContext) CryptoSuite() apicryptosuite.CryptoSuite {\n\treturn pc.cryptoSuite\n}", "func getCipherSuiteNames(ids []uint16) []string {\n\tif len(ids) == 0 {\n\t\treturn nil\n\t}\n\tnames := make([]string, len(ids))\n\tfor i, id := range ids {\n\t\tnames[i] = tls.CipherSuiteName(id)\n\t}\n\treturn names\n}", "func (cl *CommandLineInterface) SuiteStringFlag(name string, shorthand *string, defaultValue *string, description string, validationFn validator) {\n\tcl.StringFlagOnFlagSet(cl.suiteFlags, name, shorthand, defaultValue, description, nil, validationFn)\n}", "func EncodeTLSInfoToText(tcs *tls.ConnectionState, cri *tls.CertificateRequestInfo) string {\n\tversion := lookup(tlsVersions, tcs.Version)\n\tcipher := lookup(cipherSuites, tcs.CipherSuite)\n\tdescription := TLSDescription{\n\t\tVersion: tlscolor(version),\n\t\tCipher: tlscolor(explainCipher(cipher)),\n\t}\n\ttlsInfoContext := tlsInfoContext{\n\t\tConn: &description,\n\t}\n\tif cri != nil {\n\t\tcriDesc, err := EncodeCRIToObject(cri)\n\t\tif err == nil {\n\t\t\ttlsInfoContext.CRI = criDesc.(*CertificateRequestInfo)\n\t\t}\n\t}\n\n\tfuncMap := sprig.TxtFuncMap()\n\textras := template.FuncMap{\n\t\t\"printCommonName\": PrintCommonName,\n\t\t\"printShortName\": PrintShortName,\n\t\t\"greenify\": greenify,\n\t}\n\tfor k, v := range extras {\n\t\tfuncMap[k] = v\n\t}\n\n\tt := template.New(\"TLS template\").Funcs(funcMap)\n\tt, err := t.Parse(tlsLayout)\n\tif err != nil {\n\t\t// Should never happen\n\t\tpanic(err)\n\t}\n\tvar buffer bytes.Buffer\n\tw := bufio.NewWriter(&buffer)\n\terr = t.Execute(w, tlsInfoContext)\n\tif err != nil {\n\t\t// Should never happen\n\t\tpanic(err)\n\t}\n\tw.Flush()\n\treturn string(buffer.Bytes())\n}", "func (s PolicyTls) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (p *Provider) String() string {\n\tcert, err := p.GetLeafCertificate()\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn cert.Subject.CommonName\n}", "func (cl *CommandLineInterface) SuiteStringOptionsFlag(name string, shorthand *string, defaultValue *string, description string, validOpts []string) {\n\tcl.StringOptionsFlagOnFlagSet(cl.suiteFlags, name, shorthand, defaultValue, description, validOpts)\n}", "func (s TlsContext) String() string {\n\treturn awsutil.Prettify(s)\n}", "func TLSVersionName(version uint16) string {\n\tswitch version {\n\tcase tls.VersionSSL30:\n\t\treturn \"SSL 3.0\"\n\tcase tls.VersionTLS10:\n\t\treturn \"TLS 1.0\"\n\tcase tls.VersionTLS11:\n\t\treturn \"TLS 1.1\"\n\tcase tls.VersionTLS12:\n\t\treturn \"TLS 1.2\"\n\tcase tls.VersionTLS13:\n\t\treturn \"TLS 1.3\"\n\t}\n\n\treturn \"Unknown\"\n}", "func GetSslmode(ctx *pulumi.Context) string {\n\tv, err := config.Try(ctx, \"postgresql:sslmode\")\n\tif err == nil {\n\t\treturn v\n\t}\n\tvar value string\n\tif d := internal.GetEnvOrDefault(nil, nil, \"PGSSLMODE\"); d != nil {\n\t\tvalue = d.(string)\n\t}\n\treturn value\n}", "func parseCipherSuite(ids []string) []uint16 {\n\tciphers := []uint16{}\n\n\tcorrespondenceMap := map[string]uint16{\n\t\t\"TLS_RSA_WITH_RC4_128_SHA\": tls.TLS_RSA_WITH_RC4_128_SHA,\n\t\t\"TLS_RSA_WITH_3DES_EDE_CBC_SHA\": tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,\n\t\t\"TLS_RSA_WITH_AES_128_CBC_SHA\": tls.TLS_RSA_WITH_AES_128_CBC_SHA,\n\t\t\"TLS_RSA_WITH_AES_256_CBC_SHA\": tls.TLS_RSA_WITH_AES_256_CBC_SHA,\n\t\t\"TLS_RSA_WITH_AES_128_CBC_SHA256\": tls.TLS_RSA_WITH_AES_128_CBC_SHA256,\n\t\t\"TLS_RSA_WITH_AES_128_GCM_SHA256\": tls.TLS_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\"TLS_RSA_WITH_AES_256_GCM_SHA384\": tls.TLS_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA\": tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,\n\t\t\"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA\": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,\n\t\t\"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA\": tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,\n\t\t\"TLS_ECDHE_RSA_WITH_RC4_128_SHA\": tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,\n\t\t\"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA\": tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,\n\t\t\"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA\": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,\n\t\t\"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA\": tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n\t\t\"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256\": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,\n\t\t\"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256\": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,\n\t\t\"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\": tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\": tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n\t\t\"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\": tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\": tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\t\"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305\": tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,\n\t\t\"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305\": tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,\n\t}\n\n\tfor _, id := range ids {\n\t\tid = strings.ToUpper(id)\n\t\tif cipher, ok := correspondenceMap[id]; ok {\n\t\t\tciphers = append(ciphers, cipher)\n\t\t} else {\n\t\t\tlogger.Fatalf(\"unknown '%s' cipher\", id)\n\t\t}\n\t}\n\n\treturn ciphers\n}", "func (p Postgres) SSLMode() string {\n\tif p.sslmode != \"\" {\n\t\treturn p.sslmode\n\t}\n\treturn getDefaultValue(p, \"sslmode\")\n}", "func GetTestSuite(bs *messages.BuildStep) string {\n\ttestSuite := bs.Step.Name\n\ts := strings.Split(bs.Step.Name, \" \")\n\n\tif bs.Master.Name() == \"chromium.perf\" {\n\t\tfound := false\n\t\t// If a step has a swarming.summary log, then we assume it's a test\n\t\tfor _, b := range bs.Step.Logs {\n\t\t\tif len(b) > 1 && b[0] == \"swarming.summary\" {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn \"\"\n\t\t}\n\t} else if !(strings.HasSuffix(s[0], \"tests\") || strings.HasSuffix(s[0], \"test_apk\")) {\n\t\t// Some test steps have names like \"webkit_tests iOS(dbug)\" so we look at the first\n\t\t// term before the space, if there is one.\n\t\treturn testSuite\n\t}\n\n\t// Recipes add a suffix to steps of the OS that it's run on, when the test\n\t// is swarmed. The step name is formatted like this: \"<task title> on <OS>\".\n\t// Added in this code:\n\t// https://chromium.googlesource.com/chromium/tools/build/+/9ef66559727c320b3263d7e82fb3fcd1b6a3bd55/scripts/slave/recipe_modules/swarming/api.py#846\n\tif len(s) > 2 && s[1] == \"on\" {\n\t\ttestSuite = s[0]\n\t}\n\n\treturn testSuite\n}", "func (env Environment) String() string {\n\tswitch env {\n\tcase Local:\n\t\treturn \"Local\"\n\tcase Development:\n\t\treturn \"Development\"\n\tcase PreProduction:\n\t\treturn \"Pre-Production\"\n\tcase Production:\n\t\treturn \"Production\"\n\tcase UnitTest:\n\t\treturn \"UnitTest\"\n\tcase SystemIntegrationTest:\n\t\treturn \"SystemIntegrationTest\"\n\tcase SystemTest:\n\t\treturn \"SystemTest\"\n\tcase UserAcceptanceTest:\n\t\treturn \"UserAcceptanceTest\"\n\tcase PerformanceEvaluationTest:\n\t\treturn \"PerformanceEvaluationTest\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"Env(%d)\", env)\n\t}\n}", "func (s ListenerTlsAcmCertificate) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s VirtualGatewayTlsValidationContext) String() string {\n\treturn awsutil.Prettify(s)\n}", "func VersionString(value uint16) string {\n\tif str, found := tlsVersionString[value]; found {\n\t\treturn str\n\t}\n\treturn fmt.Sprintf(\"TLS_VERSION_UNKNOWN_%d\", value)\n}", "func (encl StoreEncryptionSpecList) String() string {\n\tvar buffer bytes.Buffer\n\tfor _, ss := range encl.Specs {\n\t\tfmt.Fprintf(&buffer, \"--%s=%s \", cliflagsccl.EnterpriseEncryption.Name, ss)\n\t}\n\t// Trim the extra space from the end if it exists.\n\tif l := buffer.Len(); l > 0 {\n\t\tbuffer.Truncate(l - 1)\n\t}\n\treturn buffer.String()\n}", "func (s ListenerTlsFileCertificate) String() string {\n\treturn awsutil.Prettify(s)\n}", "func GetsockoptString(fd, level, opt int) (string, error) {\n\tbuf := make([]byte, 256)\n\tvallen := _Socklen(len(buf))\n\terr := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(buf[:vallen-1]), nil\n}", "func (d Database) String() string {\n\treturn fmt.Sprintf(\"sslmode=%s host=%s user=%s dbname=%s\", d.SSLmode, d.Host, d.User, d.DBname)\n}", "func (s ServerGroup) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ServerGroup) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (t *Token) SecureString() string {\n\tdot := bytes.LastIndexByte(t.raw, '.')\n\treturn string(t.raw[:dot]) + `.<signature>`\n}", "func (c *Client) GetSuite(ctx context.Context, params *GetSuiteInput, optFns ...func(*Options)) (*GetSuiteOutput, error) {\n\tif params == nil {\n\t\tparams = &GetSuiteInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"GetSuite\", params, optFns, addOperationGetSuiteMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*GetSuiteOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (d *Device) CgroupString() string {\n\t// Agreement with Product:\n\t// we do not care about sub logic block device, they will take care of it.\n\treturn fmt.Sprintf(\"%s %s:%s %s\", d.Type, deviceNumberString(d.Major), deviceNumberString(d.Minor), d.Permissions)\n}", "func StringToTLSVersion(st string) TLSVersion {\n\tswitch TLSVersion(st) {\n\tcase TLSVersion1p0:\n\t\treturn TLSVersion1p0\n\tcase TLSVersion1p1:\n\t\treturn TLSVersion1p1\n\tcase TLSVersion1p2:\n\t\treturn TLSVersion1p2\n\tcase TLSVersion1p3:\n\t\treturn TLSVersion1p3\n\t}\n\treturn TLSVersionInvalid\n}", "func (s TlsValidationContext) String() string {\n\treturn awsutil.Prettify(s)\n}", "func GetSslMode(ctx *pulumi.Context) string {\n\treturn config.Get(ctx, \"postgresql:sslMode\")\n}", "func (l CacheMode) String() string {\n\tif l >= CacheMode(len(cacheModeToString)) {\n\t\treturn fmt.Sprintf(\"CacheMode(%d)\", l)\n\t}\n\treturn cacheModeToString[l]\n}", "func (cm CryptMethod) String() string {\n\tif cm == 1 {\n\t\treturn \"AES\"\n\t}\n\treturn \"none\"\n}", "func (s AnalyticsSessionGroupByKey) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s FirewallRuleGroup) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (t AuthenticatorProtocol) String() string {\n\treturn string(t)\n}", "func (s AnalyticsSessionGroupBySpecification) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (a *L3n4Addr) StringWithProtocol() string {\n\tvar scope string\n\tif a.Scope == ScopeInternal {\n\t\tscope = \"/i\"\n\t}\n\tif a.IsIPv6() {\n\t\treturn \"[\" + a.AddrCluster.String() + \"]:\" + strconv.FormatUint(uint64(a.Port), 10) + \"/\" + a.Protocol + scope\n\t}\n\treturn a.AddrCluster.String() + \":\" + strconv.FormatUint(uint64(a.Port), 10) + \"/\" + a.Protocol + scope\n}", "func (s SecurityGroup) String() string {\n\treturn awsutil.Prettify(s)\n}", "func SecureRandomString(keyLength int) (string, error) {\n\tkey, err := randomKey(keyLength)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tid := fmt.Sprintf(\"%0x\", key[0:keyLength])\n\treturn id, nil\n}", "func (s Subject) String() string {\n\treturn fmt.Sprintf(\"%s, %s, %s\", s.AuthenticationInfo, s.AuthorizationInfo, s.Session)\n}", "func (s VirtualGatewayListenerTls) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s VirtualGatewayListenerTlsCertificate) String() string {\n\treturn awsutil.Prettify(s)\n}", "func VersionString() string {\n\treturn C.GoString(C.LZ4_versionString())\n}", "func GetProtocolString(proto string) string {\n\tlookupKey := fmt.Sprintf(\"%s\", proto)\n\n\tprotocolName, err := LookupTZName(lookupKey, \"tz.tezz.ie\")\n\n\tif err != nil {\n\t\tlog.Printf(\"No protocol found for %s, err: %s\", lookupKey, err)\n\t\tprotocolName = proto\n\t}\n\n\treturn fmt.Sprintf(\"Protocol %s is now live on mainnet!\", protocolName)\n}", "func getCipherSuites(names []string) ([]uint16, error) {\n\tif len(names) == 0 {\n\t\treturn defaultCipherSuites, nil\n\t}\n\tcipherSuiteConsts := make([]uint16, len(names))\n\tfor i, name := range names {\n\t\tcipherSuiteConst, ok := cipherSuites[name]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"unknown TLS cipher suite '%s' specified for http.tls.cipherSuites\", name)\n\t\t}\n\t\tcipherSuiteConsts[i] = cipherSuiteConst\n\t}\n\treturn cipherSuiteConsts, nil\n}", "func TraceString(ctx context.Context) string {\n\tif ctx == nil {\n\t\treturn \"ctx=null\"\n\t}\n\ts, err := Format(ctx)\n\tif nil != err || \"\" == s {\n\t\treturn \"ctx_format=unset\"\n\t}\n\treturn s\n}", "func TLSVersion(ver uint16) string {\n\tswitch ver {\n\tcase tls.VersionTLS10:\n\t\treturn \"1.0\"\n\tcase tls.VersionTLS11:\n\t\treturn \"1.1\"\n\tcase tls.VersionTLS12:\n\t\treturn \"1.2\"\n\t}\n\treturn fmt.Sprintf(\"Unknown [%x]\", ver)\n}", "func GetCipherPassword() string {\n\tcpass := C.rresGetCipherPassword()\n\treturn C.GoString(cpass)\n}", "func (s SessionContext) String() string {\n\treturn awsutil.Prettify(s)\n}", "func __decryptString(key []byte, enc string) string {\n\tdata, err := base64.StdEncoding.DecodeString(enc)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsaltHeader := data[:aes.BlockSize]\n\tif string(saltHeader[:7]) != openSSLSaltHeader {\n\t\tlog.Fatal(\"String doesn't appear to have been encrypted with OpenSSL\")\n\t}\n\tsalt := saltHeader[8:]\n\tcreds := __extractOpenSSLCreds(key, salt)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn string(__decrypt(creds.key, creds.iv, data))\n}", "func (k Key) GetPlatformString() string {\n\treturn k.platform\n}", "func (s NASSecurityGroup) String() string {\n\treturn awsutil.Prettify(s)\n}", "func FirewallMode() string {\n\ts, _ := firewallMode.Load().(string)\n\treturn s\n}", "func (s FeatureGroup) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s SessionSpecification) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s VirtualGatewayTlsValidationContextTrust) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (c ConversionMode) GetString() string {\n\tswitch c {\n\tcase NONE:\n\t\treturn \"NONE\"\n\tcase FLOAT:\n\t\treturn \"FLOAT\"\n\tcase INTEGER:\n\t\treturn \"INTEGER\"\n\tcase UNSIGNED:\n\t\treturn \"UNSIGNED INTEGER\"\n\tcase STRING:\n\t\treturn \"STRING\"\n\tcase BOOLEAN:\n\t\treturn \"BOOLEAN\"\n\tcase HWADDRESS:\n\t\treturn \"HARDWARE ADDRESS\"\n\tcase IPADDRESS:\n\t\treturn \"IP ADDRESS\"\n\t}\n\treturn \"\"\n}", "func (s DeclineHandshakeOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func GetTLSCommonName(ctx context.Context) string {\n\tissuer := ctx.Value(PouchTLSCommonName)\n\tif issuer == nil {\n\t\treturn \"\"\n\t}\n\treturn issuer.(string)\n}", "func (t ConsumerGroupState) String() string {\n\treturn C.GoString(C.rd_kafka_consumer_group_state_name(\n\t\tC.rd_kafka_consumer_group_state_t(t)))\n}", "func (s TlsValidationContextTrust) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (l Locale) String() string {\n\tconst sep = '-'\n\tvar buf [12]byte\n\n\tlang, script, region := l.Subtags()\n\tn := copy(buf[:], lang)\n\tif script != \"\" {\n\t\tbuf[n] = sep\n\t\tn++\n\t\tn += copy(buf[n:], script)\n\t}\n\tif region != \"\" {\n\t\tbuf[n] = sep\n\t\tn++\n\t\tn += copy(buf[n:], region)\n\t}\n\treturn string(buf[:n])\n}", "func CryptoString(n int) string {\n\ts, err := cryptoString(n)\n\tif err != nil {\n\t\treturn String(n)\n\t}\n\treturn s\n}", "func (s VirtualGatewayClientPolicyTls) String() string {\n\treturn awsutil.Prettify(s)\n}", "func protocolToString(proto Protocol) string {\n\tswitch proto {\n\tcase unix.IPPROTO_TCP:\n\t\treturn \"TCP\"\n\tcase unix.IPPROTO_UDP:\n\t\treturn \"UDP\"\n\tcase unix.IPPROTO_SCTP:\n\t\treturn \"SCTP\"\n\t}\n\treturn \"\"\n}", "func (s GetFirewallRuleGroupOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DescribeFeatureGroupOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ChannelSpecification) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s TlsConfig) String() string {\n\treturn awsutil.Prettify(s)\n}", "func ConnectionString() string {\n\tuser := config.DBUser()\n\thost := config.DBHost()\n\tdbname := config.DBName()\n\tpasswd := config.DBPasswd()\n\tconnectString := fmt.Sprintf(\"host=%s user=%s dbname=%s sslmode=disable password=%s\", host, user, dbname, passwd)\n\treturn connectString\n}", "func NewSuiteContext(suiteID string) *types.SuiteContext {\n\tvar suiteCtx types.SuiteContext = types.SuiteContext{}\n\tsuiteCtx.SuiteID = suiteID\n\n\tsuiteCtx.OnlyTestOperator = onlyTestOperator\n\tif suiteCtx.OnlyTestOperator {\n\t\tlog.Info(\"Only testing operator functionality\")\n\t}\n\n\tsuiteCtx.DisableClusteredTests = disableClusteredTests\n\tif suiteCtx.DisableClusteredTests {\n\t\tlog.Info(\"Clustered registry tests disabled\")\n\t}\n\n\tsuiteCtx.DisableConvertersTests = disableConvertersTests\n\tif suiteCtx.DisableConvertersTests {\n\t\tlog.Info(\"Converters tests disabled\")\n\t}\n\n\tsuiteCtx.DisableAuthTests = disableAuthTests\n\tif suiteCtx.DisableAuthTests {\n\t\tlog.Info(\"Keycloak Authentication tests disabled\")\n\t}\n\n\tsuiteCtx.OLMRunAdvancedTestcases = olmRunAdvancedTestcases\n\tif suiteCtx.OLMRunAdvancedTestcases {\n\t\tlog.Info(\"Running Advanced Testcases with OLM deployment\")\n\t}\n\n\tsuiteCtx.SetupSelenium = setupSelenium\n\n\treturn &suiteCtx\n}", "func (s DescribeNASSecurityGroupsOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s RuleGroup) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (t OptTPacketVersion) String() string {\n\tswitch t {\n\tcase TPacketVersion1:\n\t\treturn \"V1\"\n\tcase TPacketVersion2:\n\t\treturn \"V2\"\n\tcase TPacketVersion3:\n\t\treturn \"V3\"\n\tcase TPacketVersionHighestAvailable:\n\t\treturn \"HighestAvailable\"\n\t}\n\treturn \"InvalidVersion\"\n}", "func (s KmsEncryptionConfig) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (c *Client) GetLanguagePackString(ctx context.Context, request *GetLanguagePackStringRequest) (LanguagePackStringValueClass, error) {\n\tvar result LanguagePackStringValueBox\n\n\tif err := c.rpc.Invoke(ctx, request, &result); err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.LanguagePackStringValue, nil\n}", "func (s DescribeModelPackageGroupOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DescribeTargetGroupsOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func stringToSpec(ja3 string) (*tls.ClientHelloSpec, error) {\n\ttokens := strings.Split(ja3, \",\")\n\n\tversion := tokens[0]\n\tciphers := strings.Split(tokens[1], \"-\")\n\textensions := strings.Split(tokens[2], \"-\")\n\tcurves := strings.Split(tokens[3], \"-\")\n\tif len(curves) == 1 && curves[0] == \"\" {\n\t\tcurves = []string{}\n\t}\n\tpointFormats := strings.Split(tokens[4], \"-\")\n\tif len(pointFormats) == 1 && pointFormats[0] == \"\" {\n\t\tpointFormats = []string{}\n\t}\n\n\t// parse curves\n\tvar targetCurves []tls.CurveID\n\tfor _, c := range curves {\n\t\tcid, err := strconv.ParseUint(c, 10, 16)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttargetCurves = append(targetCurves, tls.CurveID(cid))\n\t}\n\textMap[\"10\"] = &tls.SupportedCurvesExtension{Curves: targetCurves}\n\n\t// parse point formats\n\tvar targetPointFormats []byte\n\tfor _, p := range pointFormats {\n\t\tpid, err := strconv.ParseUint(p, 10, 8)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttargetPointFormats = append(targetPointFormats, byte(pid))\n\t}\n\textMap[\"11\"] = &tls.SupportedPointsExtension{SupportedPoints: targetPointFormats}\n\n\t// build extenions list\n\tvar exts []tls.TLSExtension\n\tfor _, e := range extensions {\n\t\tte, ok := extMap[e]\n\t\tif !ok {\n\t\t\treturn nil, ErrExtensionNotExist(e)\n\t\t}\n\t\texts = append(exts, te)\n\t}\n\t// build SSLVersion\n\tvid64, err := strconv.ParseUint(version, 10, 16)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvid := uint16(vid64)\n\n\t// build CipherSuites\n\tvar suites []uint16\n\tfor _, c := range ciphers {\n\t\tcid, err := strconv.ParseUint(c, 10, 16)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsuites = append(suites, uint16(cid))\n\t}\n\n\treturn &tls.ClientHelloSpec{\n\t\tTLSVersMin: vid,\n\t\tTLSVersMax: vid,\n\t\tCipherSuites: suites,\n\t\tCompressionMethods: []byte{0},\n\t\tExtensions: exts,\n\t\tGetSessionID: sha256.Sum256,\n\t}, nil\n}", "func stringToSpec(ja3 string) (*tls.ClientHelloSpec, error) {\n\ttokens := strings.Split(ja3, \",\")\n\n\tversion := tokens[0]\n\tciphers := strings.Split(tokens[1], \"-\")\n\textensions := strings.Split(tokens[2], \"-\")\n\tcurves := strings.Split(tokens[3], \"-\")\n\tif len(curves) == 1 && curves[0] == \"\" {\n\t\tcurves = []string{}\n\t}\n\tpointFormats := strings.Split(tokens[4], \"-\")\n\tif len(pointFormats) == 1 && pointFormats[0] == \"\" {\n\t\tpointFormats = []string{}\n\t}\n\n\t// parse curves\n\tvar targetCurves []tls.CurveID\n\tfor _, c := range curves {\n\t\tcid, err := strconv.ParseUint(c, 10, 16)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttargetCurves = append(targetCurves, tls.CurveID(cid))\n\t}\n\textMap[\"10\"] = &tls.SupportedCurvesExtension{targetCurves}\n\n\t// parse point formats\n\tvar targetPointFormats []byte\n\tfor _, p := range pointFormats {\n\t\tpid, err := strconv.ParseUint(p, 10, 8)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttargetPointFormats = append(targetPointFormats, byte(pid))\n\t}\n\textMap[\"11\"] = &tls.SupportedPointsExtension{SupportedPoints: targetPointFormats}\n\n\t// build extenions list\n\tvar exts []tls.TLSExtension\n\tfor _, e := range extensions {\n\t\tte, ok := extMap[e]\n\t\tif !ok {\n\t\t\treturn nil, ErrExtensionNotExist(e)\n\t\t}\n\t\texts = append(exts, te)\n\t}\n\t// build SSLVersion\n\tvid64, err := strconv.ParseUint(version, 10, 16)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvid := uint16(vid64)\n\n\t// build CipherSuites\n\tvar suites []uint16\n\tfor _, c := range ciphers {\n\t\tcid, err := strconv.ParseUint(c, 10, 16)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsuites = append(suites, uint16(cid))\n\t}\n\n\treturn &tls.ClientHelloSpec{\n\t\tTLSVersMin: vid,\n\t\tTLSVersMax: vid,\n\t\tCipherSuites: suites,\n\t\tCompressionMethods: []byte{0},\n\t\tExtensions: exts,\n\t\tGetSessionID: sha256.Sum256,\n\t}, nil\n}", "func (cl *CommandLineInterface) SuiteStringSliceFlag(name string, shorthand *string, defaultValue []string, description string) {\n\tcl.StringSliceFlagOnFlagSet(cl.suiteFlags, name, shorthand, defaultValue, description)\n}", "func (s VirtualGatewayListenerTlsAcmCertificate) String() string {\n\treturn awsutil.Prettify(s)\n}" ]
[ "0.69200236", "0.6264078", "0.60463476", "0.553764", "0.552981", "0.55205077", "0.5297108", "0.52549493", "0.521741", "0.5183919", "0.51783603", "0.51552385", "0.5096407", "0.50740904", "0.5053442", "0.49669608", "0.49222544", "0.49079034", "0.4856489", "0.48283112", "0.4725081", "0.46970397", "0.465581", "0.4648689", "0.46257386", "0.46100813", "0.4596472", "0.45590538", "0.45541683", "0.45176986", "0.45173398", "0.4507374", "0.44861397", "0.4485729", "0.44779718", "0.44613433", "0.44572833", "0.44054815", "0.43943477", "0.43728155", "0.43684003", "0.43684003", "0.43590215", "0.43291125", "0.4311861", "0.43038526", "0.42955858", "0.42940152", "0.42821586", "0.42561096", "0.4248566", "0.42333156", "0.42205018", "0.4218728", "0.42178547", "0.42147586", "0.42114002", "0.4206197", "0.4204337", "0.41991788", "0.41960233", "0.41948593", "0.4190752", "0.41898793", "0.41701746", "0.41689342", "0.41607383", "0.41411617", "0.4136703", "0.41302443", "0.41300574", "0.4126731", "0.4124398", "0.41160923", "0.41112393", "0.40916666", "0.40767798", "0.4076571", "0.40729055", "0.40708682", "0.40672797", "0.40590572", "0.4056697", "0.40526065", "0.4051846", "0.40468758", "0.40399182", "0.40388468", "0.40380794", "0.40278676", "0.4027591", "0.4023482", "0.40160418", "0.401533", "0.4010591", "0.40099627", "0.40090314", "0.39999592", "0.39949524", "0.39920157" ]
0.77113676
0
New creates a new engine with given options. Options can change the timeout, register a signal, execute a prehook callback and many other behaviours.
func New(ctx context.Context, options ...Option) (*Engine, error) { e := &Engine{} e.parent = ctx e.init() for _, o := range options { if err := o.apply(e); err != nil { return nil, err } } return e, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New(opts ...Option) *Engine {\n\toptions := defaultEngineOptions()\n\n\tfor _, opt := range opts {\n\t\topt.apply(&options)\n\t}\n\n\te := &Engine{\n\t\tsimStepper: options.simStepper,\n\t}\n\n\te.World = NewWorld()\n\n\treturn e\n}", "func NewEngine(cfg *config.Config, options ...func(*Engine)) *Engine {\n\tengine := &Engine{\n\t\tconfig: cfg,\n\t\tstop: make(chan struct{}),\n\t}\n\n\tfor _, opt := range options {\n\t\topt(engine)\n\t}\n\n\tif engine.timeManager == nil {\n\t\tengine.timeManager = defaultTimeManager{}\n\t}\n\n\treturn engine\n}", "func New(app dogma.Application, options ...EngineOption) *Engine {\n\tif app != nil {\n\t\toptions = append(options, WithApplication(app))\n\t}\n\n\topts := resolveEngineOptions(options...)\n\n\treturn &Engine{\n\t\topts: opts,\n\t\tdataStores: &persistence.DataStoreSet{\n\t\t\tProvider: opts.PersistenceProvider,\n\t\t},\n\t\tsemaphore: semaphore.NewWeighted(int64(opts.ConcurrencyLimit)),\n\t\tlogger: loggingx.WithPrefix(\n\t\t\topts.Logger,\n\t\t\t\"engine \",\n\t\t),\n\t\tready: make(chan struct{}),\n\t}\n}", "func New(backend Backend, frameSize int, opts ...Option) (*Engine, error) {\n\te := &Engine{\n\t\tbackend: backend,\n\t\tmessages: newMessageChannel(),\n\t\tgraph: NewGraph(frameSize),\n\t\terrors: make(chan error),\n\t\tstop: make(chan error),\n\t\tchunks: int(backend.FrameSize() / frameSize),\n\t\tframeSize: frameSize,\n\t\tgain: 1,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(e)\n\t}\n\n\treturn e, e.graph.Reset(e.fadeIn, e.frameSize, backend.SampleRate())\n}", "func NewEngine(store storage.Storage, notifier notify.Notifier, opts ...Option) (Engine, error) {\n\teng := &engine{\n\t\topts: &options{},\n\t\tstore: store,\n\t\tnotifier: notifier,\n\t\teventC: store.WatchEvent(),\n\t\tretryNewInstanceC: make(chan *metapb.WorkflowInstance, 16),\n\t\tretryStoppingInstanceC: make(chan *metapb.WorkflowInstance, 16),\n\t\tretryCompleteInstanceC: make(chan uint64, 1024),\n\t\tstopInstanceC: make(chan uint64, 1024),\n\t\trunner: task.NewRunner(),\n\t\tcronRunner: cron.New(cron.WithSeconds()),\n\t\tservice: crm.NewService(store),\n\t\tloaders: make(map[metapb.BMLoader]crowd.Loader),\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(eng.opts)\n\t}\n\n\teng.opts.adjust()\n\treturn eng, nil\n}", "func New(options ...Option) *T {\n\tt := &T{\n\t\tinterfaces: make(map[string]interfaceDesc),\n\t\tfunctions: make(map[string]funcDesc),\n\t\tdirty: make(map[string]HitMask),\n\t\tcomments: make(map[string][]commentDesc),\n\t}\n\tt.loader = newLoader(t.trace)\n\tfor _, fn := range options {\n\t\tfn(&t.options)\n\t}\n\treturn t\n}", "func NewEngine(signalClient *signal.Client, mgmClient *mgm.Client, config *EngineConfig, cancel context.CancelFunc) *Engine {\n\treturn &Engine{\n\t\tsignal: signalClient,\n\t\tmgmClient: mgmClient,\n\t\tconns: map[string]*Connection{},\n\t\tpeerMux: &sync.Mutex{},\n\t\tsyncMsgMux: &sync.Mutex{},\n\t\tconfig: config,\n\t\tSTUNs: []*ice.URL{},\n\t\tTURNs: []*ice.URL{},\n\t\tcancel: cancel,\n\t}\n}", "func New() Engine {\n\treturn new(engine)\n}", "func NewEngine() error {\n\t\n\treturn nil\n}", "func CreateEngine(opts Options) (*Engine, error) {\n\t// set default interval\n\tif opts.ExpireInterval == 0 {\n\t\topts.ExpireInterval = 60 * time.Second\n\t}\n\n\t// set default min and max oplog size\n\tif opts.MinOplogSize == 0 {\n\t\topts.MinOplogSize = 100\n\t}\n\tif opts.MaxOplogSize == 0 {\n\t\topts.MaxOplogSize = 1000\n\t}\n\n\t// set default min and max oplog age\n\tif opts.MinOplogAge == 0 {\n\t\topts.MinOplogAge = 5 * time.Minute\n\t}\n\tif opts.MaxOplogAge == 0 {\n\t\topts.MaxOplogAge = time.Hour\n\t}\n\n\t// create engine\n\te := &Engine{\n\t\topts: opts,\n\t\tstore: opts.Store,\n\t\tstreams: map[*Stream]struct{}{},\n\t\ttoken: dbkit.NewSemaphore(1),\n\t}\n\n\t// load catalog\n\tdata, err := e.store.Load()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// set catalog\n\te.catalog = data\n\n\t// run expiry\n\tgo e.expire(opts.ExpireInterval, opts.ExpireErrors)\n\n\treturn e, nil\n}", "func New(consumer Consumer, handler Handler, publisher Publisher) *Engine {\n\treturn &Engine{\n\t\tconsumer: consumer,\n\t\thandler: handler,\n\t\tpublisher: publisher,\n\t}\n}", "func New() *Engine {\n\treturn &Engine{router: newRouter()}\n}", "func New(c *config.Config, cc *Clients, l hclog.Logger) *Engine {\n\tp := generateProviders(c, cc, l)\n\n\treturn &Engine{\n\t\tproviders: p,\n\t\tclients: cc,\n\t\tconfig: c,\n\t\tlog: l,\n\t}\n}", "func NewEngine(opts ...EngineOption) (*Engine, error) {\n\te := &Engine{\n\t\tevalOpts: []cel.ProgramOption{},\n\t\tselectors: []Selector{},\n\t\tlimits: limits.NewLimits(),\n\t\tenvs: map[string]*cel.Env{\n\t\t\t\"\": stdEnv,\n\t\t},\n\t\tschemas: map[string]*model.OpenAPISchema{\n\t\t\t\"#openAPISchema\": model.SchemaDef,\n\t\t\t\"#instanceSchema\": model.InstanceSchema,\n\t\t\t\"#templateSchema\": model.TemplateSchema,\n\t\t},\n\t\ttemplates: map[string]*model.Template{},\n\t\tinstances: map[string][]*model.Instance{},\n\t\truntimes: map[string]*runtime.Template{},\n\t\tactPool: newActivationPool(),\n\t}\n\tvar err error\n\tfor _, opt := range opts {\n\t\te, err = opt(e)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn e, nil\n}", "func New(opts ...optionFunc) *Emulator {\n\toptions := options{\n\t\tSpeed: 1,\n\t}\n\n\ttimer := newTimerController()\n\tvideo := newVideoController()\n\tinterrupt := newInterruptController()\n\tserial := newSerialController()\n\tjoypad := newJoypadController()\n\tmemory := newMemory(video, timer, interrupt, serial, joypad)\n\tregisters := newRegisters()\n\tcpu := newCPU(memory, registers, options)\n\n\tinterrupt.registerSource(0, video.InterruptVBlank)\n\tinterrupt.registerSource(1, video.InterruptLCDCStatus)\n\tinterrupt.registerSource(2, timer.Interrupt)\n\tinterrupt.registerSource(3, serial.Interrupt)\n\tinterrupt.registerSource(4, joypad.Interrupt)\n\n\te := &Emulator{\n\t\tCPU: cpu,\n\t\tMemory: memory,\n\t\tVideo: video,\n\t\tTimer: timer,\n\t\tSerial: serial,\n\t\tInterrupt: interrupt,\n\t\tFrameChan: make(chan Frame),\n\t\toptions: options,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(e)\n\t}\n\n\treturn e\n}", "func New() (*Engine, error) {\n\n\tvar (\n\t\terr error\n\t\tdefaultOutputDeviceInfo *portaudio.DeviceInfo\n\t\tstreamParameters portaudio.StreamParameters\n\t)\n\n\t// initialize portaudio (this must be done to use *any* of portaudio's API)\n\tif err = portaudio.Initialize(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// get device info of the default output device\n\tif defaultOutputDeviceInfo, err = portaudio.DefaultOutputDevice(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// get stream parameters for the default devices\n\t// we're requesting low latency parameters (gotta go fast)\n\tstreamParameters = portaudio.LowLatencyParameters(nil, defaultOutputDeviceInfo)\n\n\t// stereo output is required for anything to work. If it doesn't\n\t// support stereo... well you'll find out when Start() is called.\n\tstreamParameters.Output.Channels = 2\n\n\treturn &Engine{\n\t\tstreamParameters: streamParameters, // <--- default configuration\n\t\tstream: nil,\n\t\ttables: map[int]*table{},\n\t\tactivePlaybackEvents: map[*playbackEvent]bool{},\n\t\tnewPlaybackEvents: make(chan *playbackEvent, 128), // <--- magic number\n\t\tinitialized: true,\n\t\tstarted: false,\n\t\tinputAmplitude: float32(1.0), // 0db gain for audio input\n\t}, nil\n}", "func New(c config.Template) *Engine {\n\ts := &Engine{Config: &c, templateCache: make(map[string]*raymond.Template, 0)}\n\treturn s\n}", "func New() (*Engine, error) {\n\tdownloader, err := cache.NewDownloader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcmdExec := exec.NewExec()\n\tloopbackRouting, err := sysctl.NewIpv4RouteLocalNet(cmdExec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tipv6RouterAdvertisements, err := sysctl.NewIpv6RouterAdvertisements(cmdExec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcredentialsProxyRoute, err := iptables.NewNetfilterRoute(cmdExec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Engine{\n\t\tdownloader: downloader,\n\t\tloopbackRouting: loopbackRouting,\n\t\tcredentialsProxyRoute: credentialsProxyRoute,\n\t\tipv6RouterAdvertisements: ipv6RouterAdvertisements,\n\t\tnvidiaGPUManager: gpu.NewNvidiaGPUManager(),\n\t}, nil\n}", "func New() DefaultEngine {\n\treturn DefaultEngine{}\n}", "func New(port string) *Engine {\n\tg := gin.New()\n\tg.Use(gin.Recovery())\n\tg.GET(\"/ping\", func(c *gin.Context) {\n\t\tc.String(200, \"pong\")\n\t})\n\treturn &Engine{g, port}\n}", "func NewOptions() *options {\n\td := time.Minute\n\treturn &options{\n\t\ttestrunnerConfig: testrunner.Config{},\n\t\twatchOptions: watch.Options{\n\t\t\tPollInterval: &d,\n\t\t},\n\t}\n}", "func New() *Engine {\n\tengine := &Engine{}\n\n\tLog = NewLogger(os.Stdout)\n\n\tengine.pool = NewContextPool()\n\tengine.Router = NewRouter()\n\n\tengine.sharedData = make(map[string]string)\n\n\t// Try to determine engine path\n\twd, _ := osext.ExecutableFolder()\n\tengine.Path = filepath.Clean(wd) + \"/\"\n\n\tif strings.Contains(filepath.Dir(engine.Path), \"go-build\") {\n\t\twd, _ = os.Getwd()\n\t\tengine.Path = filepath.Clean(wd) + \"/\"\n\t}\n\n\tif filepath.Base(engine.Path) == \"tests\" {\n\t\tengine.Path = engine.Path + \"../\"\n\t}\n\n\tif flag.Lookup(\"test.v\") != nil {\n\t\tSetMode(\"test\")\n\t\tengine.Path = engine.Path + \"../example\"\n\t}\n\n\t// Load configuration file.\n\tConfig = LoadConfig(engine.Path + \"config/app.json\")\n\n\treturn engine\n}", "func NewEngine(conf Config) *Engine {\n\tcpuNum := runtime.NumCPU()\n\tif conf.Name == \"\" {\n\t\tconf.Name = \"NB\"\n\t}\n\tif conf.NPoller <= 0 {\n\t\tconf.NPoller = cpuNum\n\t}\n\tif conf.ReadBufferSize <= 0 {\n\t\tconf.ReadBufferSize = DefaultReadBufferSize\n\t}\n\tif conf.Listen == nil {\n\t\tconf.Listen = net.Listen\n\t}\n\tif conf.ListenUDP == nil {\n\t\tconf.ListenUDP = net.ListenUDP\n\t}\n\n\tg := &Engine{\n\t\tTimer: timer.New(conf.Name, conf.TimerExecute),\n\t\tName: conf.Name,\n\t\tnetwork: conf.Network,\n\t\taddrs: conf.Addrs,\n\t\tlisten: conf.Listen,\n\t\tlistenUDP: conf.ListenUDP,\n\t\tpollerNum: conf.NPoller,\n\t\treadBufferSize: conf.ReadBufferSize,\n\t\tmaxWriteBufferSize: conf.MaxWriteBufferSize,\n\t\tudpReadTimeout: conf.UDPReadTimeout,\n\t\tlockListener: conf.LockListener,\n\t\tlockPoller: conf.LockPoller,\n\t\tlisteners: make([]*poller, len(conf.Addrs))[0:0],\n\t\tpollers: make([]*poller, conf.NPoller),\n\t\tconnsStd: map[*Conn]struct{}{},\n\t}\n\n\tg.initHandlers()\n\n\tg.OnReadBufferAlloc(func(c *Conn) []byte {\n\t\tif c.ReadBuffer == nil {\n\t\t\tc.ReadBuffer = make([]byte, g.readBufferSize)\n\t\t}\n\t\treturn c.ReadBuffer\n\t})\n\n\treturn g\n}", "func New(s interface{}, options ...Option) *Agent {\n\tvar opts agentOptions\n\tfor _, option := range options {\n\t\toption(&opts)\n\t}\n\n\tvar atomOptions []atom.Option\n\tif opts.equalityFn != nil {\n\t\tatomOptions = append(atomOptions,\n\t\t\tatom.EqualityFunc(opts.equalityFn))\n\t}\n\n\treturn &Agent{\n\t\tstate: atom.New(s, atomOptions...),\n\t\tqueue: jobq.New(runAction),\n\t\topts: opts,\n\t}\n}", "func New() *Options {\n\treturn &Options{}\n}", "func New(options ...Option) Application {\n\topts := &Options{}\n\tfor _, opt := range options {\n\t\topt(opts)\n\t}\n\n\tif opts.StartupTimeout == 0 {\n\t\topts.StartupTimeout = 1000\n\t}\n\tif opts.ShutdownTimeout == 0 {\n\t\topts.ShutdownTimeout = 5000\n\t}\n\n\tif opts.AutoMaxProcs == nil || *opts.AutoMaxProcs {\n\t\tprocsutil.EnableAutoMaxProcs()\n\t}\n\n\tconfig.AppendServiceTag(opts.Tags...)\n\n\tapp := &application{\n\t\tquit: make(chan os.Signal),\n\t\tstartupTimeout: opts.StartupTimeout,\n\t\tshutdownTimeout: opts.ShutdownTimeout,\n\t\tboxes: append(opts.Boxes, &boxMetric{}),\n\t}\n\n\tsignal.Notify(app.quit, syscall.SIGINT, syscall.SIGTERM)\n\n\treturn app\n}", "func New(o Options) *Pool {\n\tif o.New == nil {\n\t\tpanic(\"pool: new func must not be nil\")\n\t}\n\n\tif o.Size <= 0 {\n\t\to.Size = 1\n\t}\n\n\tif o.Timeout <= 0 {\n\t\to.Timeout = 30 * time.Second\n\t}\n\n\treturn &Pool{\n\t\titems: make(chan interface{}, o.Size),\n\t\tmaxSize: o.Size,\n\t\ttimeout: o.Timeout,\n\t\tnewFn: o.New,\n\t\tmu: new(sync.Mutex),\n\t}\n}", "func NewEngine(l log.Logger) *Engine {\n\tle := &Engine{\n\t\tcaravan: collections.CreateCaravan(),\n\t\tcloser: make(chan bool),\n\t\tLog: l,\n\t\tpackages: map[string]*Package{},\n\t\tstateChange: make(chan *stateChangeEvent),\n\t}\n\n\tgo func() {\n\t\tstop := false\n\t\tfor !stop {\n\t\t\tselect {\n\t\t\tcase <-le.closer:\n\t\t\t\tstop = true\n\t\t\tcase e := <-le.stateChange:\n\t\t\t\tgo le.processStateChange(e)\n\t\t\t}\n\t\t}\n\n\t\tle.Log.Debugf(\"Start: ending anon go func\\n\")\n\t}()\n\n\treturn le\n}", "func NewEngine(cfg *Config) (*Engine, error) {\n\te := &Engine{\n\t\tcfg: *cfg,\n\t}\n\n\terr := e.SetMethods(e.cfg.AvailableMethods)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn e, nil\n}", "func New(options Options) *Timer {\n\treturn &Timer{\n\t\toptions: options,\n\t}\n}", "func NewEngine(conf Config) Engine {\n\treturn &engineImpl{\n\t\tConfig: conf,\n\t\tdoneFlags: make(map[string]bool),\n\t}\n}", "func New(options Options) *Store {\n\tif options.Codec == nil {\n\t\toptions.Codec = DefaultOptions.Codec\n\t}\n\n\tif options.Interval == 0 {\n\t\toptions.Interval = DefaultOptions.Interval\n\t}\n\n\tif options.TableName == \"\" {\n\t\toptions.TableName = DefaultOptions.TableName\n\t}\n\n\tsql := newSqlSvr(options.User, options.Pwd, options.Host, options.Db, options.TableName, options.Split)\n\tif sql == nil {\n\t\treturn nil\n\t}\n\n\ts := &Store{\n\t\tSql: sql,\n\t\tCodec: options.Codec,\n\t}\n\n\t//go s.autoGC(options.Interval)\n\n\treturn s\n}", "func NewEngineBTC() *Engine { return newEngine(NewGeneratorBTC()) }", "func New(cfg *Config) *Engine {\n\tif cfg.OpenCacheSize == 0 {\n\t\tcfg.OpenCacheSize = DefaultOpenCacheSize\n\t}\n\n\tif cfg.BatchSize == 0 {\n\t\tcfg.BatchSize = DefaultBatchSize\n\t}\n\n\tif cfg.KVStore == \"\" {\n\t\tcfg.KVStore = DefaultKVStore\n\t}\n\n\tif cfg.KVConfig == nil {\n\t\tcfg.KVConfig = store.KVConfig{}\n\t}\n\n\tng := &Engine{\n\t\tconfig: cfg,\n\t\tstores: cache.NewLRUCache(cfg.OpenCacheSize),\n\t}\n\n\tif debug, ok := cfg.KVConfig[\"debug\"].(bool); ok {\n\t\tng.debug = debug\n\t}\n\n\tng.stores.OnRemove(func(key string, value interface{}) {\n\t\tstorekv, ok := value.(store.KVStore)\n\n\t\tif !ok {\n\t\t\tpanic(\"Unexpected value in cache\")\n\t\t}\n\n\t\tif storekv.IsOpen() {\n\t\t\tstorekv.Close()\n\t\t}\n\t})\n\n\treturn ng\n}", "func New(token string, words []string) (*Engine, error) {\n\tbot, err := tgbotapi.NewBotAPI(token)\n\tif err != nil {\n\t\treturn &Engine{}, err\n\t}\n\n\treturn &Engine{\n\t\tBot: bot,\n\t\tRoomList: make(map[int64]*room.Room),\n\t\tSendChan: make(chan message.Request),\n\n\t\tWords: words,\n\t}, nil\n}", "func NewEngine() *Engine {\n\treturn &Engine{\n\t\tech: echo.New(),\n\t}\n}", "func New(options ...func(pushers.Channel) error) (pushers.Channel, error) {\n\tc := Backend{\n\t\tch: make(chan map[string]interface{}, 100),\n\t}\n\n\tfor _, optionFn := range options {\n\t\toptionFn(&c)\n\t}\n\n\tif c.WebhookURL == \"\" {\n\t\treturn nil, errors.New(\"Invalid Config: WebhookURL can not be empty\")\n\t}\n\n\tgo c.run()\n\n\treturn &c, nil\n}", "func New(opt *common.Options) error {\n\tif opt.Address != \"\" {\n\t\tif opt.Daemon {\n\t\t\treturn daemon.New(opt)\n\t\t}\n\n\t\tserver.Run(opt)\n\t} else if opt.Check {\n\t\tif isConnected() {\n\t\t\tchecker.Do(opt)\n\n\t\t\tif opt.Output != \"\" {\n\t\t\t\tdefer opt.Result.Close()\n\t\t\t}\n\t\t} else {\n\t\t\treturn errors.New(\"no internet connection\")\n\t\t}\n\t} else {\n\t\treturn errors.New(\"no action needed\")\n\t}\n\n\treturn nil\n}", "func NewEngine(addr, port string) *Engine {\n\tserveraddr := fmt.Sprintf(\"%s:%s\", addr, port)\n\treturn &Engine{Stat: &stat{}, HandleTimeOut: handleTimeOut, ConnLog: NewConnLog(serveraddr), Addr: addr, Port: port}\n}", "func New(api restapi.Connector) *Engine {\n\treturn &Engine{api: api}\n}", "func NewEngine(config config.Config, consensus consensus.Consensus) (*Engine, error) {\n\n\tlogger := config.Logger()\n\n\tsubmitCh := make(chan []byte)\n\n\tstate, err := state.NewState(\n\t\tconfig.DbFile,\n\t\tconfig.Cache,\n\t\tconfig.Genesis,\n\t\tlogger.WithField(\"component\", \"state\"))\n\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"engine.go:NewEngine() state.NewState\")\n\t\treturn nil, err\n\t}\n\n\tminGasPrice, ok := math.ParseBig256(currency.ExpandCurrencyString(config.MinGasPrice))\n\tif !ok {\n\t\tlogger.WithField(\"min-gas-price\", config.MinGasPrice).Debug(\"Could not parse min-gas-price\")\n\t\tminGasPrice = big.NewInt(0)\n\t}\n\n\tservice := service.NewService(\n\t\tconfig.EthAPIAddr,\n\t\tstate,\n\t\tsubmitCh,\n\t\tminGasPrice,\n\t\tlogger.WithField(\"component\", \"service\"))\n\n\tif err := consensus.Init(state, service); err != nil {\n\t\tlogger.WithError(err).Error(\"engine.go:NewEngine() Consensus.Init\")\n\t\treturn nil, err\n\t}\n\n\tservice.SetInfoCallback(consensus.Info)\n\n\tengine := &Engine{\n\t\tstate: state,\n\t\tservice: service,\n\t\tconsensus: consensus,\n\t}\n\n\treturn engine, nil\n}", "func New(opts ...ProtocolOption) *Protocol {\n\tp := &Protocol{\n\t\tpingTimeout: 3 * time.Second,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(p)\n\t}\n\n\treturn p\n}", "func New(s *Setup) (Engine, error) {\n\t// validate the setup being provided\n\t//\n\t// https://pkg.go.dev/github.com/go-vela/pkg-executor/executor?tab=doc#Setup.Validate\n\terr := s.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogrus.Debug(\"creating executor engine from setup\")\n\t// process the executor driver being provided\n\tswitch s.Driver {\n\tcase constants.DriverDarwin:\n\t\t// handle the Darwin executor driver being provided\n\t\t//\n\t\t// https://pkg.go.dev/github.com/go-vela/pkg-executor/executor?tab=doc#Setup.Darwin\n\t\treturn s.Darwin()\n\tcase constants.DriverLinux:\n\t\t// handle the Linux executor driver being provided\n\t\t//\n\t\t// https://pkg.go.dev/github.com/go-vela/pkg-executor/executor?tab=doc#Setup.Linux\n\t\treturn s.Linux()\n\tcase constants.DriverLocal:\n\t\t// handle the Local executor driver being provided\n\t\t//\n\t\t// https://pkg.go.dev/github.com/go-vela/pkg-executor/executor?tab=doc#Setup.Local\n\t\treturn s.Local()\n\tcase constants.DriverWindows:\n\t\t// handle the Windows executor driver being provided\n\t\t//\n\t\t// https://pkg.go.dev/github.com/go-vela/pkg-executor/executor?tab=doc#Setup.Windows\n\t\treturn s.Windows()\n\tdefault:\n\t\t// handle an invalid executor driver being provided\n\t\treturn nil, fmt.Errorf(\"invalid executor driver provided: %s\", s.Driver)\n\t}\n}", "func NewEngine() *Engine {\n\treturn &Engine{}\n}", "func New(options ...Option) *Connection {\n\tc := Connection{\n\t\tdebug: false,\n\t\tusetor: true,\n\t\ttimeout: 180 * time.Second,\n\t\tname: \"\", // TOOD: use UUID?\n\t\theaders: make(map[string]string),\n\t}\n\tfor _, o := range options {\n\t\to(&c)\n\t}\n\n\treturn &c\n}", "func New(options *Config) (*KeKahu, error) {\n\t// Create default configuration\n\tconfig := new(Config)\n\tif err := config.Load(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Update the configuration from the options\n\tif err := config.Update(options); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Set the logging level\n\tSetLogLevel(uint8(config.Verbosity))\n\n\t// Create the HTTP client\n\ttimeout, _ := config.GetAPITimeout()\n\tclient := &http.Client{Timeout: timeout}\n\n\t// Create the Echo server\n\tserver := new(Server)\n\tserver.Init(\"\", \"\")\n\n\t// Create the ping latencies map\n\tnetwork := new(Network)\n\tnetwork.Init()\n\n\tkekahu := &KeKahu{config: config, client: client, server: server, network: network}\n\treturn kekahu, nil\n}", "func newEngine(cfg config.TSDB) (*engine, error) {\n\t// create time series storage path\n\tif err := mkDirIfNotExist(cfg.Dir); err != nil {\n\t\treturn nil, fmt.Errorf(\"create time sereis storage path[%s] erorr: %s\", cfg.Dir, err)\n\t}\n\te := &engine{\n\t\tcfg: cfg,\n\t}\n\te.ctx, e.cancel = context.WithCancel(context.Background())\n\te.dataFlushChecker = newDataFlushChecker(e.ctx)\n\te.dataFlushChecker.Start()\n\n\tif err := e.load(); err != nil {\n\t\tengineLogger.Error(\"load engine data error when create a new engine\", logger.Error(err))\n\t\t// close opened engine\n\t\te.Close()\n\t\treturn nil, err\n\t}\n\treturn e, nil\n}", "func New(options ...Option) *Server {\n\tcfg := &Config{\n\t\tLogger: log.New(os.Stdout, \"\", log.Ldate|log.Ltime),\n\t}\n\tfor _, option := range options {\n\t\toption(cfg)\n\t}\n\treturn &Server{cfg: cfg}\n}", "func New() *Engine {\n\tf := sprig.TxtFuncMap()\n\n\t// Prevent environment access inside the running KUDO Controller\n\tfuncs := []string{\"env\", \"expandenv\", \"base\", \"dir\", \"clean\", \"ext\", \"isAbs\"}\n\n\tfor _, fun := range funcs {\n\t\tdelete(f, fun)\n\t}\n\n\treturn &Engine{\n\t\tFuncMap: f,\n\t}\n}", "func NewOptions(io instrument.Options) Options {\n\treturn &opts{\n\t\tiopts: io,\n\t\tinitFn: defaultNoErrorFn,\n\t\treleaseFn: defaultNoErrorFn,\n\t\theartbeatTimeout: defaultHeartbeatTimeout,\n\t\tnowFn: time.Now,\n\t\tnewFileMode: defaultNewFileMode,\n\t\tnewDirectoryMode: defaultNewDirectoryMode,\n\t}\n}", "func New(app *app.Config) (Engine, error) {\n\t// App is required\n\tif app == nil {\n\t\treturn nil, errors.New(\"Error: No App configuration provided\")\n\t}\n\t// Name is required\n\tif len(app.Name) == 0 {\n\t\treturn nil, errors.New(\"Error: No App name provided\")\n\t}\n\t// Version is required\n\tif len(app.Version) == 0 {\n\t\treturn nil, errors.New(\"Error: No App version provided\")\n\t}\n\n\tlogLevel := config.GetLogLevel()\n\n\treturn &EngineConfig{App: app, serviceManager: util.GetDefaultServiceManager(), LogLevel:logLevel}, nil\n}", "func New(options ...Option) (*Webhook, error) {\n\thook := new(Webhook)\n\tfor _, opt := range options {\n\t\tif err := opt(hook); err != nil {\n\t\t\treturn nil, errors.New(\"Error applying Option\")\n\t\t}\n\t}\n\treturn hook, nil\n}", "func NewEngine() *Engine {\n\treturn &Engine{\n\t\tCmds: DefaultCmds(),\n\t\tConds: DefaultConds(),\n\t}\n}", "func New(port int, options ...Option) *API {\n\tapi := API{\n\t\tRouter: httprouter.New(),\n\t\tport: port,\n\t\tstopChan: make(chan struct{}, 1),\n\t}\n\n\t// apply the options\n\tfor _, opt := range options {\n\t\topt(&api)\n\t}\n\treturn &api\n}", "func New(uri string, timeout time.Duration) EventStore {\n\treturn &client{\n\t\turi: uri,\n\t\ttimeout: timeout,\n\t}\n}", "func New() *Engine {\n\tv := &Engine{Layer: layer.New()}\n\t// Use the default proxyer as final middleware handler\n\tv.UseFinalHandler(DefaultFinalHandler)\n\treturn v\n}", "func New() *JavaScriptEngine {\n\treturn &JavaScriptEngine{}\n}", "func NewEngine(code string) *Engine {\n\treturn &Engine{\n\t\tOrderbook: &OrderBook{\n\t\t\tCode: code,\n\t\t\tBids: OrderList{},\n\t\t\tAsks: OrderList{}},\n\t\tinEvents: make(chan *InEvent),\n\t\toutEvents: make(chan *OutEvent),\n\t\teventMapper: map[string]bool{},\n\t\teventQue: []string{},\n\t}\n}", "func New(options ...Option) (result translator.Proxy, err error) {\n\tresult = &proxy{\n\t\tlogger: zap.NewNop(),\n\t}\n\n\t// Apply options.\n\tfor _, opt := range options {\n\t\topt(result.(*proxy))\n\t}\n\n\treturn\n}", "func New(conf *viper.Viper) plugins.Plugin {\n\tconf = setDefaults(conf)\n\ttask := func() string {\n\t\tformat := conf.GetString(\"timeFormat\")\n\t\treturn time.Now().Format(format)\n\t}\n\treturn core.NewTimerFunc(conf, task)\n}", "func NewEngine(cfg config.TSDB) (Engine, error) {\n\tengine, err := newEngine(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn engine, nil\n}", "func NewEngine(queryable Queryable, o *EngineOptions) *Engine {\n\tif o == nil {\n\t\to = DefaultEngineOptions\n\t}\n\tmaxConcurrentQueries.Set(float64(o.MaxConcurrentQueries))\n\treturn &Engine{\n\t\tqueryable: queryable,\n\t\tgate: newQueryGate(o.MaxConcurrentQueries),\n\t\toptions: o,\n\t}\n}", "func New() *Engine {\n\tengine := &Engine{router: newRouter()}\n\tengine.RouterGroup = &RouterGroup{engine: engine}\n\tengine.groups = []*RouterGroup{engine.RouterGroup}\n\treturn engine\n}", "func NewEngine(config *rest.Config) *Engine {\n\treturn &Engine{\n\t\ttemplate: template.New(\"gotpl\"),\n\t\tconfig: config,\n\t}\n}", "func newOptions() *options {\n\treturn &options{\n\t\tlogger: log.NewNopLogger(),\n\t\tclock: clock.New(),\n\t\tcertificateCacheDuration: time.Hour * 24,\n\t}\n}", "func New(eventType Type, srv server.Server, bootType, script string, params map[string]interface{}) Event {\n\tvar event Event\n\n\tevent.Type = eventType\n\tevent.Date = time.Now()\n\tevent.Server = srv\n\tevent.BootType = bootType\n\tevent.Script = script\n\tevent.Params = params\n\n\tevent.setMessage()\n\n\treturn event\n}", "func New(ctx context.Context, opts ...Option) (StopFunc, error) {\n\tsettings := Settings{\n\t\tModules: map[interface{}]fx.Option{},\n\t\tInvokes: map[Invoke]InvokeOption{},\n\t}\n\n\t// apply module options in the right order\n\tif err := Options(opts...)(&settings); err != nil {\n\t\treturn nil, xerrors.Errorf(\"applying node options failed: %w\", err)\n\t}\n\n\t// gather constructors for fx.Options\n\tctors := make([]fx.Option, 0, len(settings.Modules))\n\tfor _, opt := range settings.Modules {\n\t\tctors = append(ctors, opt)\n\t}\n\n\t// fill holes in invokes for use in fx.Options\n\tinvokeOpts := []InvokeOption{}\n\tfor _, opt := range settings.Invokes {\n\t\tinvokeOpts = append(invokeOpts, opt)\n\t}\n\n\tsort.Slice(invokeOpts, func(i, j int) bool {\n\t\treturn invokeOpts[i].Priority < invokeOpts[j].Priority\n\t})\n\n\tinvokes := []fx.Option{}\n\tfor _, opt := range invokeOpts {\n\t\tinvokes = append(invokes, opt.Option)\n\t}\n\n\tapp := fx.New(\n\t\tfx.Options(ctors...),\n\t\tfx.Options(invokes...),\n\n\t\tfx.Logger(&debugPrinter{}),\n\t)\n\n\t// TODO: we probably should have a 'firewall' for Closing signal\n\t// on this context, and implement closing logic through lifecycles\n\t// correctly\n\tif err := app.Start(ctx); err != nil {\n\t\t// comment fx.NopLogger few lines above for easier debugging\n\t\treturn nil, xerrors.Errorf(\"starting node: %w\", err)\n\t}\n\n\treturn app.Stop, nil\n}", "func NewEngine(opt tsdb.EngineOptions) *Engine {\n\t// Generate temporary file.\n\tf, _ := ioutil.TempFile(\"\", \"bz1-\")\n\tf.Close()\n\tos.Remove(f.Name())\n\twalPath := filepath.Join(f.Name(), \"wal\")\n\n\t// Create test wrapper and attach mocks.\n\te := &Engine{\n\t\tEngine: bz1.NewEngine(f.Name(), walPath, opt).(*bz1.Engine),\n\t}\n\te.Engine.WAL = &e.PointsWriter\n\treturn e\n}", "func New(opts *Options) Manager {\n\treturn &tmux{options: opts}\n}", "func NewEngine() Engine {\n\tb := Engine{logger: helpers.Logger()}\n\tb.run()\n\treturn b\n}", "func NewEngine() *Engine {\n\te := &Engine{}\n\treturn e\n}", "func (d *Driver) New(config transaction.Config) (tx transaction.Transaction, err error) {\n\ttxn := &Transaction{}\n\n\tif config.Timeout != \"\" {\n\t\ttxn.timeout, err = time.ParseDuration(config.Timeout)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"driver/go: error parsing timeout: %w\", err)\n\t\t}\n\t}\n\n\ti := interp.New(interp.Options{})\n\ti.Use(stdlib.Symbols)\n\n\t_, err = i.Eval(config.Script)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"driver/go: error initializing transaction script: %w\", err)\n\t}\n\n\tv, err := i.Eval(\"transaction.Run\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"driver/go: error loading transaction program code: %w\", err)\n\t}\n\n\tvar ok bool\n\ttxn.transaction, ok = v.Interface().(func(context.Context) (message, data string, err error))\n\tif !ok || txn.transaction == nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t`driver/go: transaction.Run doesn't implement \"func(context.Context) (message, data string, err error)\" signature`)\n\t}\n\n\tif config.CallBack != nil {\n\t\ti := interp.New(interp.Options{})\n\t\ti.Use(stdlib.Symbols)\n\n\t\t_, err = i.Eval(config.CallBack.Script)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"driver/go: error initializing callback script: %w\", err)\n\t\t}\n\n\t\tvar ok bool\n\t\tv, err := i.Eval(\"callback.Handle\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"driver/go: error loading callback program code: %w\", err)\n\t\t}\n\n\t\ttxn.callbackHandler, ok = v.Interface().(func(context.Context, []byte) (message, data string, err error))\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t`driver/go: callback.Handle doesn't implement \"func(context.Context, []byte) (message, data string, err error)\" signature`)\n\t\t}\n\t}\n\n\ttxn.config = config\n\treturn txn, nil\n}", "func New(options *pg.Options) *pg.DB {\n\n db := pg.Connect(options)\n db.AddQueryHook(dbLogger{})\n return db\n}", "func newOptions() *options {\n\treturn &options{\n\t\tos: sys.DefaultOS(),\n\t}\n}", "func New(o *Options, logger *zap.Logger) *Server {\n\thttpClient := &http.Client{\n\t\tTimeout: o.HTTPClientTimeout,\n\t}\n\n\treturn &Server{\n\t\toptions: o,\n\t\thttpClient: httpClient,\n\t\trouter: mux.NewRouter(),\n\t\tlogger: logger,\n\t}\n}", "func New(opt StoreOptions) *Store {\n\tstore := &Store{}\n\n\tfmt.Println(opt.toString())\n\tsession, err := mgo.Dial(opt.toString())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tstore.cli = session\n\tstore.database = opt.Database\n\treturn store\n}", "func New(opts ...Option) *Vox {\n\tv := &Vox{\n\t\tcb: nil,\n\t\tholdTime: time.Millisecond * 500,\n\t\tthreshold: 0.1,\n\t\tlastActivation: time.Time{},\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(v)\n\t}\n\n\treturn v\n}", "func New(options ...OptionsFunc) (*Server, error) {\n\ts := &Server{\n\t\tauxAddr: \":9090\",\n\t\tstopChan: make(chan struct{}, 1),\n\t}\n\n\tfor _, f := range options {\n\t\tif err := f(s); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"options func failed\")\n\t\t}\n\t}\n\n\treturn s, nil\n}", "func New(v interface{}, config Config) (*twerk, error) {\n\n\tcallableFunc, err := callable.New(v)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = isValid(config)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttwrkr := &twerk{\n\t\tcallable: callableFunc,\n\n\t\tconfig: config,\n\n\t\tjobListener: make(chan jobInstruction, config.Max),\n\n\t\tliveWorkersNum: newAtomicNumber(0),\n\t\tcurrentlyWorkingNum: newAtomicNumber(0),\n\n\t\tbroadcastDie: make(chan bool),\n\n\t\torchestrator: &defaultOrchestrator{config: &config},\n\n\t\tstopTheWorldLock: &sync.RWMutex{},\n\t}\n\n\ttwrkr.startInBackground()\n\n\treturn twrkr, nil\n}", "func New(s *service.Canal) (engine *bm.Engine, err error) {\n\tcs = s\n\tengine = bm.DefaultServer(conf.Conf.BM)\n\n\tinitRouter(engine)\n\terr = engine.Start()\n\treturn\n}", "func New(name string) *Engine {\n\tengine := &Engine{Name: name}\n\tengine.RouterGroup = &RouterGroup{prefix: \"/\", engine: engine}\n\tengine.router = httprouter.New()\n\tengine.router.NotFound = engine.handle404\n\tengine.cache.New = func() interface{} {\n\t\tc := &Context{Engine: engine}\n\t\tc.Writer = &c.writermem\n\t\treturn c\n\t}\n\treturn engine\n}", "func New(handler func(*API), config *Config) *Transport {\n\tif config == nil {\n\t\tconfig = &Config{\n\t\t\tMaxThreads: 1,\n\t\t\tAcceptTimeout: 100,\n\t\t\tReadTimeout: 100,\n\t\t\tLogger: nil}\n\t}\n\treturn &Transport{\n\t\tConfig: config,\n\t\thandler: handler,\n\t\tactive: false,\n\t\tlock: &sync.Mutex{}}\n}", "func New(args framework.Arguments) framework.Plugin {\n\trevocableZone := make(map[string]string)\n\tevictPeriod := time.Minute\n\tmaxEvictStep := intstr.FromString(\"5%\")\n\n\tfor k, v := range args {\n\t\tif strings.Contains(k, revocableZoneLabelPrefix) {\n\t\t\trevocableZone[strings.Replace(k, revocableZoneLabelPrefix, \"\", 1)] = v\n\t\t}\n\t}\n\n\tif period, ok := args[evictPeriodLabel]; ok {\n\t\tif d, err := time.ParseDuration(period); err == nil {\n\t\t\tevictPeriod = d\n\t\t}\n\t}\n\n\tif maxStep, ok := args[evictMaxStepLabel]; ok {\n\t\tmaxEvictStep = intstr.Parse(maxStep)\n\t}\n\n\treturn &tdmPlugin{revocableZone, evictPeriod, maxEvictStep}\n}", "func New(port *Port, timeout time.Duration, options ...Option) (*PLM, error) {\n\tplm := &PLM{\n\t\ttimeout: timeout,\n\t\twriteDelay: 500 * time.Millisecond,\n\t\tport: port,\n\t\tconnections: make(map[insteon.Address]insteon.Connection),\n\n\t\tinsteonTxCh: make(chan *insteon.Message),\n\t\tinsteonRxCh: make(chan *insteon.Message),\n\t\tplmCh: make(chan *Packet),\n\t}\n\tplm.linkdb.plm = plm\n\tplm.linkdb.timeout = timeout\n\n\tfor _, o := range options {\n\t\terr := o(plm)\n\t\tif err != nil {\n\t\t\tinsteon.Log.Infof(\"error setting plm option: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tgo plm.readLoop()\n\tgo plm.writeLoop()\n\treturn plm, nil\n}", "func NewEngine(param *EngineParameter) (*Engine, error) {\n\n\te := &Engine{\n\t\tquery: \"\",\n\t\tqueryResult: []string{\"\", \"\"},\n\t\tdrawer: NewDrawer(Prompt),\n\t\ttable: NewTableManager(param.rows),\n\t\tcursorX: 0,\n\t}\n\treturn e, nil\n}", "func newOptions() *Options {\n\topts := &Options{}\n\n\toptions := []Option{\n\t\tWithConcurrency(defaultConcurrency),\n\t\tWithMaxRetries(defaultMaxRetries),\n\t\tWithTTL(defaultTTL),\n\t\tWithTimeout(defaultTimeout),\n\t\tWithRetryIntervals(defaultRetryIntervals),\n\t\tWithInitialize(true),\n\t}\n\n\tfor i := range options {\n\t\toptions[i](opts)\n\t}\n\n\treturn opts\n}", "func New(opts ...AgentOption) *Agent {\n\ta := spawn()\n\tfor _, o := range opts {\n\t\to.apply(a)\n\t}\n\ta.start()\n\treturn a\n}", "func New(q *ast.Questionaire, toFrontend, fromFrontend chan *fe.Event) {\n\tv := &vm{\n\t\tquestionaire: q,\n\t\tsend: toFrontend,\n\t\treceive: fromFrontend,\n\t}\n\tv.loop()\n}", "func NewOptions(opts ...Option) Options {\n\toptions := Options{\n\t\tContext: context.Background(),\n\t\tContentType: DefaultContentType,\n\t\tCodecs: make(map[string]codec.Codec),\n\t\tCallOptions: CallOptions{\n\t\t\tContext: context.Background(),\n\t\t\tBackoff: DefaultBackoff,\n\t\t\tRetry: DefaultRetry,\n\t\t\tRetries: DefaultRetries,\n\t\t\tRequestTimeout: DefaultRequestTimeout,\n\t\t\tDialTimeout: transport.DefaultDialTimeout,\n\t\t},\n\t\tLookup: LookupRoute,\n\t\tPoolSize: DefaultPoolSize,\n\t\tPoolTTL: DefaultPoolTTL,\n\t\tSelector: random.NewSelector(),\n\t\tLogger: logger.DefaultLogger,\n\t\tBroker: broker.DefaultBroker,\n\t\tMeter: meter.DefaultMeter,\n\t\tTracer: tracer.DefaultTracer,\n\t}\n\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\treturn options\n}", "func New(timeout time.Duration, someActionTitle string) *Worker {\n\treturn &Worker{\n\t\ttimeout: timeout,\n\t\taction: someActionTitle,\n\t}\n}", "func New(s *service.Service) (engine *bm.Engine, err error) {\n\tvar (\n\t\tcfg struct {\n\t\t\tbm.ServerConfig\n\t\t\tCrossDomains []string\n\t\t}\n\t\tct paladin.TOML\n\t)\n\tif err = paladin.Get(\"http.toml\").Unmarshal(&ct); err != nil {\n\t\treturn\n\t}\n\tif err = ct.Get(\"Server\").UnmarshalTOML(&cfg); err != nil {\n\t\treturn\n\t}\n\tengine = bm.DefaultServer(&cfg.ServerConfig)\n\tengine.Use(s.As.CORS(cfg.CrossDomains))\n\tengine.Use(gzip.Gzip(gzip.DefaultCompression))\n\tinitRouter(engine, s)\n\terr = engine.Start()\n\treturn\n}", "func NewOptions() *Options {\n\topts := Options{}\n\tvar version bool\n\tflag.BoolVar(&version, \"version\", false, \"displays version information\")\n\tflag.DurationVar(&opts.Polling, \"poll\", defPolling, \"defines polling interval\")\n\tflag.BoolVar(&opts.RestartOnEnd, \"restart\", false, \"restart process if terminated\")\n\tflag.DurationVar(&opts.Waiting, \"wait\", defWaiting, \"time to wait before polling again after a restart\")\n\tflag.Usage = func() {\n\t\tPrintInfo()\n\t\tfmt.Println(\"usage:\")\n\t\tflag.PrintDefaults()\n\t}\n\tflag.Parse()\n\tif version {\n\t\treturn nil\n\t}\n\treturn &opts\n}", "func NewEngine() *Engine {\n\treturn newEngine(C.wasm_engine_new())\n}", "func NewOptions(opts ...Option) *Options {\n\topt := &Options{\n\t\tHandlerConcurrency: defaultHandlerConcurrency,\n\t\tMaxConcurrencyPerEvent: defaultMaxConcurrencyPerEvent,\n\t\tTimeoutPerEvent: defaultTimeout,\n\t\tPubsubReceiveSettings: pubsub.DefaultReceiveSettings,\n\t}\n\tfor _, o := range opts {\n\t\to(opt)\n\t}\n\tif opt.EventRequester == nil {\n\t\topt.EventRequester = defaultCeClient\n\t}\n\treturn opt\n}", "func New(options Options, optFns ...func(*Options)) *Client {\n\toptions = options.Copy()\n\n\tresolveRetryer(&options)\n\n\tresolveHTTPClient(&options)\n\n\tresolveHTTPSignerV4(&options)\n\n\tresolveDefaultEndpointConfiguration(&options)\n\n\tresolveIdempotencyTokenProvider(&options)\n\n\tfor _, fn := range optFns {\n\t\tfn(&options)\n\t}\n\n\tclient := &Client{\n\t\toptions: options,\n\t}\n\n\treturn client\n}", "func New(opt *Options) *Application {\n\tr := mux.NewRouter()\n\treturn &Application{\n\t\tr: r,\n\t\tserv: &http.Server{\n\t\t\tAddr: \":8120\",\n\t\t\tReadTimeout: time.Duration(opt.Serv.ReadTimeout),\n\t\t\tIdleTimeout: time.Duration(opt.Serv.IdleTimeout),\n\t\t\tWriteTimeout: time.Duration(opt.Serv.WriteTimeout),\n\t\t\tHandler: r,\n\t\t},\n\t\thashSum: opt.HashSum,\n\t\tsvc: opt.Svc,\n\t\tpr: opt.Pr,\n\t\tlogger: opt.Logger,\n\t}\n}", "func newOptions() *options {\n\treturn &options{}\n}", "func New() (*Relay, error) {\n\treturn &Relay{\n\t\tvm: newRuntime(),\n\t}, nil\n}", "func NewWithTimeout(log zerolog.Logger, timeout time.Duration) EventBus {\n\te := &defaultEventBus{\n\t\tclosing: make(chan chan struct{}),\n\t\tchannel: make(chan Event, 100),\n\t\tlog: log,\n\t\tlock: new(deadlock.RWMutex),\n\t\terrorHandler: func(err error) { log.Debug().Msg(err.Error()) },\n\t}\n\tgo e.dispatcherLoop(timeout)\n\treturn e\n}", "func NewConstructor(o Options) func(http.Handler) http.Handler {\n\tif o.Timeout <= 0 {\n\t\treturn xhttp.NilConstructor\n\t}\n\n\t// nolint: typecheck\n\tif o.TimedOut == nil {\n\t\to.TimedOut = defaultTimedOut\n\t}\n\n\treturn func(next http.Handler) http.Handler {\n\t\treturn &timeoutHandler{\n\t\t\ttimeout: o.Timeout,\n\t\t\ttimedOut: o.TimedOut,\n\t\t\tnext: next,\n\t\t}\n\t}\n}" ]
[ "0.67921555", "0.669759", "0.6473409", "0.6158667", "0.6096818", "0.5842643", "0.58255535", "0.57950187", "0.57940483", "0.57030845", "0.5669355", "0.56626093", "0.5661552", "0.5651985", "0.5622525", "0.559433", "0.5591475", "0.55850506", "0.55799", "0.55681443", "0.5546847", "0.55374277", "0.5502195", "0.5478673", "0.5477477", "0.5467816", "0.5463776", "0.5460344", "0.5453038", "0.54280573", "0.5425746", "0.5417095", "0.5416791", "0.54066867", "0.539751", "0.5362977", "0.53579646", "0.5355569", "0.5345155", "0.5343038", "0.5305613", "0.5291087", "0.5285286", "0.5285114", "0.5269527", "0.5267333", "0.52657235", "0.525688", "0.52490145", "0.5239438", "0.5220337", "0.51989686", "0.5196936", "0.51730543", "0.5172674", "0.5164645", "0.5160174", "0.5153536", "0.5150208", "0.5147265", "0.51460075", "0.5145138", "0.51335067", "0.5133452", "0.51331055", "0.512375", "0.5120443", "0.5113726", "0.50946146", "0.5085451", "0.5082667", "0.5074243", "0.5073943", "0.50670314", "0.5060395", "0.5058007", "0.5040058", "0.5033574", "0.50333047", "0.502715", "0.50060153", "0.4999702", "0.49943957", "0.4986742", "0.498614", "0.49757367", "0.49746516", "0.4974607", "0.49743417", "0.49686384", "0.49683186", "0.49601123", "0.495885", "0.49409747", "0.49360877", "0.4930861", "0.49293923", "0.4928529", "0.4927847", "0.4924948" ]
0.6813927
0
launch will start given hook.
func (e *Engine) launch(h Hook) { e.wait.Add(1) go func() { defer e.wait.Done() runtime := &HookRuntime{} // Wait for an event to notify this goroutine that a shutdown is required. // It could either be from engine's context or during Hook startup if an error has occurred. // NOTE: If HookRuntime returns an error, we have to shutdown every Hook... err := runtime.WaitForEvent(e.ctx, h) if err != nil { e.mutex.Lock() e.log(err) e.cancel() e.cause = err e.mutex.Unlock() } // Wait for hook to gracefully shutdown, or kill it after timeout. // This is handled by HookRuntime. for _, err := range runtime.Shutdown(e.timeout) { e.mutex.Lock() e.log(err) e.mutex.Unlock() } }() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Launch(actions []actloop.Action, logger *log.Logger) (stop func()) {\n\tloop := actloop.NewActLoop(actions, logger)\n\tgo loop.Run(time.Second*2, time.Minute*5, notifyReady)\n\treturn loop.Cancel\n}", "func Launch(addr, localDir, filename string,\n\targs []string, logDir string, retry int) error {\n\n\tfields := strings.Split(addr, \":\")\n\tif len(fields) != 2 || len(fields[0]) <= 0 || len(fields[1]) <= 0 {\n\t\treturn fmt.Errorf(\"Launch addr %s not in form of host:port\")\n\t}\n\n\tc, e := connect(fields[0])\n\tif e != nil {\n\t\treturn e\n\t}\n\tdefer c.Close()\n\n\te = c.Call(\"Prism.Launch\",\n\t\t&Cmd{addr, localDir, filename, args, logDir, retry}, nil)\n\tif e != nil {\n\t\treturn fmt.Errorf(\"Prism.Launch failed: %v\", e)\n\t}\n\treturn nil\n}", "func executeLaunch() {\n\tfmt.Println(\"Launching ...\")\n}", "func (vr *VoiceRecorder) Launch(ctx context.Context) error {\n\t// vr.app.Install() will install the app only if the app doesn't exist.\n\tif err := vr.app.Install(ctx); err != nil {\n\t\treturn err\n\t}\n\n\tif err := vr.grantPermissions(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to grant permission\")\n\t}\n\n\tif _, err := vr.app.Launch(ctx); err != nil {\n\t\treturn err\n\t}\n\n\tstartOrStopRecordBtn := vr.app.Device.Object(ui.ID(startOrStopRecordBtnID))\n\tif err := apputil.WaitForExists(startOrStopRecordBtn, defaultUITimeout)(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"voice recorder is not ready\")\n\t}\n\n\treturn nil\n}", "func (tr *TaskRunner) prestart() error {\n\t// Determine if the allocation is terminal and we should avoid running\n\t// prestart hooks.\n\tif tr.shouldShutdown() {\n\t\ttr.logger.Trace(\"skipping prestart hooks since allocation is terminal\")\n\t\treturn nil\n\t}\n\n\tif tr.logger.IsTrace() {\n\t\tstart := time.Now()\n\t\ttr.logger.Trace(\"running prestart hooks\", \"start\", start)\n\t\tdefer func() {\n\t\t\tend := time.Now()\n\t\t\ttr.logger.Trace(\"finished prestart hooks\", \"end\", end, \"duration\", end.Sub(start))\n\t\t}()\n\t}\n\n\t// use a join context to allow any blocking pre-start hooks\n\t// to be canceled by either killCtx or shutdownCtx\n\tjoinedCtx, joinedCancel := joincontext.Join(tr.killCtx, tr.shutdownCtx)\n\tdefer joinedCancel()\n\n\tfor _, hook := range tr.runnerHooks {\n\t\tpre, ok := hook.(interfaces.TaskPrestartHook)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tname := pre.Name()\n\n\t\t// Build the request\n\t\treq := interfaces.TaskPrestartRequest{\n\t\t\tTask: tr.Task(),\n\t\t\tTaskDir: tr.taskDir,\n\t\t\tTaskEnv: tr.envBuilder.Build(),\n\t\t\tTaskResources: tr.taskResources,\n\t\t}\n\n\t\torigHookState := tr.hookState(name)\n\t\tif origHookState != nil {\n\t\t\tif origHookState.PrestartDone {\n\t\t\t\ttr.logger.Trace(\"skipping done prestart hook\", \"name\", pre.Name())\n\n\t\t\t\t// Always set env vars from hooks\n\t\t\t\tif name == HookNameDevices {\n\t\t\t\t\ttr.envBuilder.SetDeviceHookEnv(name, origHookState.Env)\n\t\t\t\t} else {\n\t\t\t\t\ttr.envBuilder.SetHookEnv(name, origHookState.Env)\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Give the hook it's old data\n\t\t\treq.PreviousState = origHookState.Data\n\t\t}\n\n\t\treq.VaultToken = tr.getVaultToken()\n\t\treq.NomadToken = tr.getNomadToken()\n\n\t\t// Time the prestart hook\n\t\tvar start time.Time\n\t\tif tr.logger.IsTrace() {\n\t\t\tstart = time.Now()\n\t\t\ttr.logger.Trace(\"running prestart hook\", \"name\", name, \"start\", start)\n\t\t}\n\n\t\t// Run the prestart hook\n\t\tvar resp interfaces.TaskPrestartResponse\n\t\tif err := pre.Prestart(joinedCtx, &req, &resp); err != nil {\n\t\t\ttr.emitHookError(err, name)\n\t\t\treturn structs.WrapRecoverable(fmt.Sprintf(\"prestart hook %q failed: %v\", name, err), err)\n\t\t}\n\n\t\t// Store the hook state\n\t\t{\n\t\t\thookState := &state.HookState{\n\t\t\t\tData: resp.State,\n\t\t\t\tPrestartDone: resp.Done,\n\t\t\t\tEnv: resp.Env,\n\t\t\t}\n\n\t\t\t// Store and persist local state if the hook state has changed\n\t\t\tif !hookState.Equal(origHookState) {\n\t\t\t\ttr.stateLock.Lock()\n\t\t\t\ttr.localState.Hooks[name] = hookState\n\t\t\t\ttr.stateLock.Unlock()\n\n\t\t\t\tif err := tr.persistLocalState(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Store the environment variables returned by the hook\n\t\tif name == HookNameDevices {\n\t\t\ttr.envBuilder.SetDeviceHookEnv(name, resp.Env)\n\t\t} else {\n\t\t\ttr.envBuilder.SetHookEnv(name, resp.Env)\n\t\t}\n\n\t\t// Store the resources\n\t\tif len(resp.Devices) != 0 {\n\t\t\ttr.hookResources.setDevices(resp.Devices)\n\t\t}\n\t\tif len(resp.Mounts) != 0 {\n\t\t\ttr.hookResources.setMounts(resp.Mounts)\n\t\t}\n\n\t\tif tr.logger.IsTrace() {\n\t\t\tend := time.Now()\n\t\t\ttr.logger.Trace(\"finished prestart hook\", \"name\", name, \"end\", end, \"duration\", end.Sub(start))\n\t\t}\n\t}\n\n\treturn nil\n}", "func (l *Launcher) Launch(self string, cmd []string) error {\n\tprocess, err := l.ProcessFor(cmd)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"determine start command\")\n\t}\n\treturn l.LaunchProcess(self, process)\n}", "func HookOnJobStart(hooks []string, j common.Job) {\n\tlog.WithField(\"id\", j.UUID).Debug(\"Executing hooks against job start.\")\n\n\tdata := copyJobToHookJob(j)\n\n\thooksRun(hooks, data)\n\n}", "func (la Launch) execute(l *Lobby) {\n\tl.started = true\n\tla.Event = \"launch\"\n\tl.send <- la\n}", "func (l *Launcher) Start(sourceProvider launchers.SourceProvider, pipelineProvider pipeline.Provider, registry auditor.Registry, tracker *tailers.TailerTracker) {\n\tl.sources = sourceProvider.GetAddedForType(config.JournaldType)\n\tl.pipelineProvider = pipelineProvider\n\tl.registry = registry\n\tgo l.run()\n}", "func (h *Handler) OnLaunch(ctx context.Context, request *alexa.Request, session *alexa.Session, ctxPtr *alexa.Context, response *alexa.Response) error {\n\tlog.Printf(\"OnLaunch requestId=%s, sessionId=%s\", request.RequestID, session.SessionID)\n\treturn nil\n}", "func (m *TestMod) Hook() error {\n\tm.RegisterCommand(NewTestCommand(m))\n\t//m.RegisterCommand(NewMonkeyCommand(m))\n\n\treturn nil\n}", "func (gitHubHook *GitHubHook) StartGitHubHook() {\n\trouter := httprouter.New()\n\trouter.POST(gitHubHook.GitHubHookEndPoint, gitHubHook.receiveGiHubDelivery)\n\tlog.Fatal(http.ListenAndServe(\":\"+gitHubHook.GitHubHookPort, router))\n}", "func Launch(eventBroker wire.EventBroker, committee Reducers, keys user.Keys,\n\ttimeout time.Duration, rpcBus *wire.RPCBus) {\n\tif committee == nil {\n\t\tcommittee = newReductionCommittee(eventBroker, nil)\n\t}\n\n\thandler := newReductionHandler(committee, keys)\n\tbroker := newBroker(eventBroker, handler, timeout, rpcBus)\n\tgo broker.Listen()\n}", "func Launch(start func() error, shutdown func() error, timeout time.Duration) {\n\tdone := make(chan int)\n\tgo func() {\n\t\tif err := start(); err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tdone <- 1\n\t\t}\n\t\tdone <- 0\n\t}()\n\tch := make(chan os.Signal, 2)\n\tsignal.Notify(ch, []os.Signal{syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT}...)\n\n\tselect {\n\tcase exitCode := <-done:\n\t\tif shutdown != nil {\n\t\t\tif err := shutdownWithTimeout(shutdown, timeout); err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t}\n\t\tos.Exit(exitCode)\n\tcase s := <-ch:\n\t\tfmt.Printf(\"received signal %s: terminating\\n\", s)\n\t\tif shutdown != nil {\n\t\t\tif err := shutdownWithTimeout(shutdown, timeout); err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t}\n\t\tos.Exit(0)\n\t}\n}", "func Launch(th ThreadWithRole) error {\n\tif e := AllocThread(th); e != nil {\n\t\treturn e\n\t}\n\tth.Launch()\n\treturn nil\n}", "func Launch(ctx context.Context, tconn *chrome.TestConn, appID string) error {\n\tif err := testing.Poll(ctx, func(ctx context.Context) error {\n\t\tcapps, err := ash.ChromeApps(ctx, tconn)\n\t\tif err != nil {\n\t\t\ttesting.PollBreak(err)\n\t\t}\n\t\tfor _, capp := range capps {\n\t\t\tif capp.AppID == appID {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn errors.New(\"App not yet found in available Chrome apps\")\n\t}, nil); err != nil {\n\t\treturn err\n\t}\n\treturn tconn.Call(ctx, nil, `tast.promisify(chrome.autotestPrivate.launchApp)`, appID)\n}", "func (s *BaseGShellListener) EnterStart(ctx *StartContext) {}", "func Launch(addr string) {\n\tlog.Fatal(http.ListenAndServe(addr, nil))\n}", "func (p PRPlugin) entrypoint(env *ActionsEnv) (err error) {\n\tswitch env.Event.GetAction() {\n\tcase actionOpen:\n\t\terr = p.onOpen(env)\n\tcase actionReopen:\n\t\terr = p.onReopen(env)\n\tcase actionEdit:\n\t\terr = p.onEdit(env)\n\tcase actionSync:\n\t\terr = p.onSync(env)\n\tdefault:\n\t\tp.Warningf(\"action %q received with no defined procedure, skipping\", env.Event.GetAction())\n\t}\n\n\treturn\n}", "func (fn *RuntimeMonitor) StartBundle(ctx context.Context, emit func([]byte, []byte)) {\n\truntime.Update(ctx, time.Now().UnixNano())\n}", "func (l *Launcher) Main(args []string) (int, error) {\n\tvar ret int\n\tif args == nil || len(args) < 2 {\n\t\t// todo print help about all registered jobs\n\t\tfmt.Println(\"Requires \\\"launch\\\" or job name as parameter\")\n\t\tkeys := l.ListFunctions()\n\t\tif len(keys) > 0 {\n\t\t\tfmt.Println(\"Following job names available:\")\n\t\t\tfor _, name := range keys {\n\t\t\t\tfmt.Println(name)\n\t\t\t}\n\t\t}\n\t\treturn 0, UnknownFunctionError\n\t}\n\tfname := args[1]\n\tif fname == \"launch\" {\n\t\tif fn, found := l.fs[\"workflow\"]; found == false {\n\t\t\tfmt.Println(\"No workflow function registered\")\n\t\t\tos.Exit(1)\n\t\t} else {\n\t\t\tfn.F(args[2:])\n\t\t}\n\t}\n\tfn, found := l.fs[fname]\n\tif !found {\n\t\treturn 0, UnknownFunctionError\n\t}\n\t// execute function\n\tret = fn.F(args[2:])\n\treturn ret, nil\n}", "func RunFromHook(db gorp.SqlExecutor, w *sdk.Workflow, e *sdk.WorkflowNodeRunHookEvent) (*sdk.WorkflowRun, error) {\n\treturn nil, nil\n}", "func start() {\n\tfmt.Printf(\"Starting %s...\", AppName)\n\tif err := Start(1); err != nil {\n\t\tfailed(err)\n\t} else {\n\t\tfmt.Println(\"OK\")\n\t}\n}", "func (app *App) Launch() (string, error) {\n\treturn app.tv.LaunchApp(app.ID)\n}", "func Launch() {\n\thttp.HandleFunc(\"/\", indexHandler)\n\thttp.ListenAndServe(\":1234\", nil)\n}", "func (s *kataBuiltInShim) start(sandbox *Sandbox, params ShimParams) (int, error) {\n\treturn -1, nil\n}", "func OnStart() {\n}", "func Main(args []string) {\n\twebhook.Launch(\n\t\tnil,\n\t\t9997,\n\t\tvalidator.AdmitSP,\n\t\t\"linkerd-sp-validator\",\n\t\t\"sp-validator\",\n\t\targs,\n\t)\n}", "func onLaunch() {\n\tmenu := &Menu{}\n\n\tapp.MenuBar().Mount(menu)\n\tapp.Dock().Mount(menu)\n\n\tmainWindow = newWelcomeWindow()\n}", "func (l *Logger) Hook(e zapcore.Entry) error {\n\tif l.IsHook {\n\t\terr := log.Emit(&log.Content{\n\t\t\tLevel: e.Level.CapitalString(),\n\t\t\tMessage: e.Message,\n\t\t\tDate: e.Time,\n\t\t\tCaller: e.Caller.TrimmedPath(),\n\t\t\tStack: e.Stack,\n\t\t})\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *Basegff3Listener) EnterStart(ctx *StartContext) {}", "func main() {\n\tvar err error\n\n\t// Get the location of the config file (relative to the binary)\n\tconfigLocation := flag.String(\n\t\t\"config\",\n\t\tDEFAULT_CONFIG_LOCATION,\n\t\t\"location of toml config file\")\n\tflag.Parse()\n\n\t// Load the config file (config needs to be toml)\n\tconfig, err = toml.LoadFile(*configLocation)\n\n\tif err != nil {\n\t\tpanic(\"No config file... cannot continue\")\n\t}\n\n\t// Get the port to listen on\n\tportStr := config.Get(\"server.port\").(string)\n\tport, _ := strconv.ParseInt(portStr, 10, 64)\n\n\tif port == 0 || port < 0 {\n\t\tport = DEFAULT_PORT\n\t}\n\n\tfmt.Printf(\"-------------- starting to listen on port %d\", port)\n\thttp.Handle(\"/hook\", http.HandlerFunc(getHook))\n\terr = http.ListenAndServe(fmt.Sprintf(\":%d\", port), nil)\n\n\tif err != nil {\n\t\tpanic(\"Can't listen or serve!!\" + err.Error())\n\t}\n}", "func (ssc *defaultGameStatefulSetControl) newHookRunFromGameStatefulSet(canaryCtx *canaryContext, hookStep *hookv1alpha1.HookStep,\n\targs []hookv1alpha1.Argument, revision string, stepIdx *int32, labels map[string]string) (*hookv1alpha1.HookRun, error) {\n\tset := canaryCtx.set\n\ttemplate, err := ssc.hookTemplateLister.HookTemplates(set.Namespace).Get(hookStep.TemplateName)\n\tif err != nil {\n\t\tif k8serrors.IsNotFound(err) {\n\t\t\tklog.Warningf(\"HookTemplate '%s' not found for GameStatefulSet %s/%s\", hookStep.TemplateName, set.Namespace, set.Name)\n\t\t}\n\t\treturn nil, err\n\t}\n\tnameParts := []string{\"canary\", revision}\n\tif stepIdx != nil {\n\t\tnameParts = append(nameParts, \"step\"+strconv.Itoa(int(*stepIdx)))\n\t}\n\tnameParts = append(nameParts, hookStep.TemplateName)\n\tname := strings.Join(nameParts, \"-\")\n\n\trun, err := commonhookutil.NewHookRunFromTemplate(template, args, name, \"\", set.Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trun.Labels = labels\n\trun.OwnerReferences = []metav1.OwnerReference{*metav1.NewControllerRef(set, util.ControllerKind)}\n\treturn run, nil\n}", "func (c *DockerContainer) startingHook(ctx context.Context) error {\n\tfor _, lifecycleHooks := range c.lifecycleHooks {\n\t\terr := containerHookFn(ctx, lifecycleHooks.PreStarts)(c)\n\t\tif err != nil {\n\t\t\tc.printLogs(ctx)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (w *DefaultPreWorkflowHooksCommandRunner) RunPreHooks(\n\tbaseRepo models.Repo,\n\theadRepo models.Repo,\n\tpull models.PullRequest,\n\tuser models.User,\n) {\n\tif opStarted := w.Drainer.StartOp(); !opStarted {\n\t\tif commentErr := w.VCSClient.CreateComment(baseRepo, pull.Num, ShutdownComment, \"pre_workflow_hooks\"); commentErr != nil {\n\t\t\tw.Logger.Log(logging.Error, \"unable to comment that Atlantis is shutting down: %s\", commentErr)\n\t\t}\n\t\treturn\n\t}\n\tdefer w.Drainer.OpDone()\n\n\tlog := w.buildLogger(baseRepo.FullName, pull.Num)\n\tdefer w.logPanics(baseRepo, pull.Num, log)\n\n\tlog.Info(\"running pre hooks\")\n\n\tunlockFn, err := w.WorkingDirLocker.TryLock(baseRepo.FullName, pull.Num, DefaultWorkspace)\n\tif err != nil {\n\t\tlog.Warn(\"workspace is locked\")\n\t\treturn\n\t}\n\tlog.Debug(\"got workspace lock\")\n\tdefer unlockFn()\n\n\trepoDir, _, err := w.WorkingDir.Clone(log, headRepo, pull, DefaultWorkspace)\n\tif err != nil {\n\t\tlog.Err(\"unable to run pre workflow hooks: %s\", err)\n\t\treturn\n\t}\n\n\tpreWorkflowHooks := make([]*valid.PreWorkflowHook, 0)\n\tfor _, repo := range w.GlobalCfg.Repos {\n\t\tif repo.IDMatches(baseRepo.ID()) && len(repo.PreWorkflowHooks) > 0 {\n\t\t\tpreWorkflowHooks = append(preWorkflowHooks, repo.PreWorkflowHooks...)\n\t\t}\n\t}\n\n\tctx := models.PreWorkflowHookCommandContext{\n\t\tBaseRepo: baseRepo,\n\t\tHeadRepo: headRepo,\n\t\tLog: log,\n\t\tPull: pull,\n\t\tUser: user,\n\t\tVerbose: false,\n\t}\n\n\terr = w.runHooks(ctx, preWorkflowHooks, repoDir)\n\n\tif err != nil {\n\t\tlog.Err(\"pre workflow hook run error results: %s\", err)\n\t}\n}", "func Launch() {\n\trouter := gin.Default()\n\n\t// GET-Route parametrized by 'root' param that hols root domain name,\n\t// usage: 'http://localhost:8080/domain/status/dropbox.com'.\n\trouter.GET(\"domain/status/:root\", getSubdomainStatus)\n\n\t// Run server and check errors\n\tif err := router.Run(addr); err != nil {\n\t\tlog.Fatalf(\"error running web server %v\", err)\n\t}\n}", "func (f *JobRunFunc) PushHook(hook func(context.Context, database.DB, streaming.Sender) (*search.Alert, error)) {\n\tf.mutex.Lock()\n\tf.hooks = append(f.hooks, hook)\n\tf.mutex.Unlock()\n}", "func (sry *Sryun) Hook(req *http.Request) (*model.Repo, *model.Build, error) {\n\treturn nil, nil, nil\n}", "func (l *Logger) Hook(h func(Entry)) *Logger {\n\tl.hook = h\n\treturn l\n}", "func main () {\n\n\tstartGame() // start the game\n\n}", "func main() {\n\tapp.StartApp()\n}", "func startLuna(this js.Value, args []js.Value) interface{} {\n\tinput := args[0].String()\n\treturn js.ValueOf(map[string]interface{}{\n\t\t\"module\": compile(input),\n\t})\n}", "func OnAppStart(f func()) {\n\tstartupHooks = append(startupHooks, f)\n}", "func (g Git) RunHook() error {\n\thook, stdin, args := os.Getenv(\"HOOK\"), os.Getenv(\"STDIN\"), strings.Fields(os.Getenv(\"ARGS\"))\n\tswitch hook {\n\tcase \"pre-commit\":\n\t\treturn g.preCommit()\n\tcase \"commit-msg\":\n\t\tvar messageFile string\n\t\tif len(args) > 0 {\n\t\t\tmessageFile = args[0]\n\t\t}\n\t\treturn g.commitMsg(messageFile)\n\tcase \"pre-push\":\n\t\tif mg.Verbose() {\n\t\t\tfmt.Println(\"Running pre-push hook with\", args)\n\t\t}\n\t\treturn g.prePush(stdin, args...)\n\tdefault:\n\t\treturn fmt.Errorf(\"Unknown hook %s\", hook)\n\t}\n}", "func start(){\n\t\t\t\t\n\t\t\t\tdebug.Send(\"exec-run\")\t\t\t\t\n\t\t\t\tdebug.Send(\"interpreter-exec\",\"console\",\"record\")\n\t\t\t\t\n\t\t\t\t\n\n\t}", "func (l *Lifecycle) Start(ctx context.Context) error {\n\tl.mu.Lock()\n\tl.startRecords = make(HookRecords, 0, len(l.hooks))\n\tl.mu.Unlock()\n\n\tfor _, hook := range l.hooks {\n\t\tif hook.OnStart != nil {\n\t\t\tl.mu.Lock()\n\t\t\tl.runningHook = hook\n\t\t\tl.mu.Unlock()\n\n\t\t\truntime, err := l.runStartHook(ctx, hook)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tl.mu.Lock()\n\t\t\tl.startRecords = append(l.startRecords, HookRecord{\n\t\t\t\tCallerFrame: hook.callerFrame,\n\t\t\t\tFunc: hook.OnStart,\n\t\t\t\tRuntime: runtime,\n\t\t\t})\n\t\t\tl.mu.Unlock()\n\t\t}\n\t\tl.numStarted++\n\t}\n\n\treturn nil\n}", "func withHook(preHook *Hook, action func() error, postHook *Hook) error {\n\tif preHook != nil {\n\t\tif err := (*preHook)(); err != nil {\n\t\t\treturn fmt.Errorf(\"running pre-hook: %w\", err)\n\t\t}\n\t}\n\n\tif err := action(); err != nil {\n\t\treturn fmt.Errorf(\"running action: %w\", err)\n\t}\n\n\tif postHook == nil {\n\t\treturn nil\n\t}\n\n\treturn (*postHook)()\n}", "func Run(appStart func() error) {\n\tlchr.run(appStart)\n}", "func main() {\n\tcore.Start()\n}", "func (y *YogClient) launchDroplet(droplet *Droplet) error {\n\terr := droplet.build(y)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdroplets.AddDroplet(droplet.Request.Name, droplet.Droplet.ID)\n\treturn nil\n}", "func (my *Driver) UseLaunchExecutable(l launchFn) {\n\tmy.launchExe = l\n}", "func (o *ComputerLaunchOption) Launch(name string) (err error) {\n\terr = o.ComputerClient.Launch(name)\n\treturn\n}", "func main() {\n\tparts := strings.Split(os.Args[0], \"/\")\n\ttrigger := parts[len(parts)-1]\n\tflag.Parse()\n\n\tswitch trigger {\n\tcase \"install\":\n\t\tbuildpacks.TriggerInstall()\n\tcase \"post-delete\":\n\t\tappName := flag.Arg(0)\n\t\tbuildpacks.TriggerPostDelete(appName)\n\tcase \"post-extract\":\n\t\tappName := flag.Arg(0)\n\t\tsourceWorkDir := flag.Arg(1)\n\t\tbuildpacks.TriggerPostExtract(appName, sourceWorkDir)\n\tcase \"report\":\n\t\tappName := flag.Arg(0)\n\t\tbuildpacks.ReportSingleApp(appName, \"\")\n\tdefault:\n\t\tcommon.LogFail(fmt.Sprintf(\"Invalid plugin trigger call: %s\", trigger))\n\t}\n}", "func insertHook(db gorp.SqlExecutor, node *sdk.WorkflowNode, hook *sdk.WorkflowNodeHook) error {\n\thook.WorkflowNodeID = node.ID\n\tif hook.WorkflowHookModelID == 0 {\n\t\thook.WorkflowHookModelID = hook.WorkflowHookModel.ID\n\t}\n\n\tvar icon string\n\tif hook.WorkflowHookModelID != 0 {\n\t\ticon = hook.WorkflowHookModel.Icon\n\t\tmodel, errm := LoadHookModelByID(db, hook.WorkflowHookModelID)\n\t\tif errm != nil {\n\t\t\treturn sdk.WrapError(errm, \"insertHook> Unable to load model %d\", hook.WorkflowHookModelID)\n\t\t}\n\t\thook.WorkflowHookModel = *model\n\t} else {\n\t\tmodel, errm := LoadHookModelByName(db, hook.WorkflowHookModel.Name)\n\t\tif errm != nil {\n\t\t\treturn sdk.WrapError(errm, \"insertHook> Unable to load model %s\", hook.WorkflowHookModel.Name)\n\t\t}\n\t\thook.WorkflowHookModel = *model\n\t}\n\thook.WorkflowHookModelID = hook.WorkflowHookModel.ID\n\n\t//TODO: to delete when all previous scheduler are updated\n\tif _, ok := hook.Config[\"payload\"]; hook.WorkflowHookModel.Name == sdk.SchedulerModelName && !ok {\n\t\thook.Config[\"payload\"] = sdk.SchedulerModel.DefaultConfig[\"payload\"]\n\t}\n\n\terrmu := sdk.MultiError{}\n\t// Check configuration of the hook vs the model\n\tfor k := range hook.WorkflowHookModel.DefaultConfig {\n\t\tif _, ok := hook.Config[k]; !ok {\n\t\t\terrmu = append(errmu, fmt.Errorf(\"Missing configuration key: %s\", k))\n\t\t}\n\t}\n\tif len(errmu) > 0 {\n\t\treturn sdk.WrapError(&errmu, \"insertHook> Invalid hook configuration\")\n\t}\n\n\t// if it's a new hook\n\tif hook.UUID == \"\" {\n\t\tuuid, erruuid := sessionstore.NewSessionKey()\n\t\tif erruuid != nil {\n\t\t\treturn sdk.WrapError(erruuid, \"insertHook> Unable to load model %d\", hook.WorkflowHookModelID)\n\t\t}\n\t\thook.UUID = string(uuid)\n\n\t\thook.Config[\"hookIcon\"] = sdk.WorkflowNodeHookConfigValue{\n\t\t\tValue: icon,\n\t\t\tConfigurable: false,\n\t\t}\n\t}\n\n\tdbhook := NodeHook(*hook)\n\tif err := db.Insert(&dbhook); err != nil {\n\t\treturn sdk.WrapError(err, \"insertHook> Unable to insert hook\")\n\t}\n\t*hook = sdk.WorkflowNodeHook(dbhook)\n\treturn nil\n}", "func (s *Splasher) splash(cmd *exec.Cmd) (sp *Splash, err error) {\n\t// Exec\n\tsp = &Splash{cmd: cmd}\n\tastilog.Debugf(\"Executing %s\", strings.Join(cmd.Args, \" \"))\n\tif err = sp.cmd.Start(); err != nil {\n\t\terr = errors.Wrapf(err, \"starting %s failed\", s.binaryPath)\n\t}\n\n\t// Wait\n\tgo cmd.Wait()\n\treturn\n}", "func main() {\n\tslackIt()\n}", "func (tr *TaskRunner) initHooks() {\n\thookLogger := tr.logger.Named(\"task_hook\")\n\ttask := tr.Task()\n\n\ttr.logmonHookConfig = newLogMonHookConfig(task.Name, tr.taskDir.LogDir)\n\n\t// Add the hook resources\n\ttr.hookResources = &hookResources{}\n\n\t// Create the task directory hook. This is run first to ensure the\n\t// directory path exists for other hooks.\n\talloc := tr.Alloc()\n\ttr.runnerHooks = []interfaces.TaskHook{\n\t\tnewValidateHook(tr.clientConfig, hookLogger),\n\t\tnewTaskDirHook(tr, hookLogger),\n\t\tnewIdentityHook(tr, hookLogger),\n\t\tnewLogMonHook(tr, hookLogger),\n\t\tnewDispatchHook(alloc, hookLogger),\n\t\tnewVolumeHook(tr, hookLogger),\n\t\tnewArtifactHook(tr, tr.getter, hookLogger),\n\t\tnewStatsHook(tr, tr.clientConfig.StatsCollectionInterval, hookLogger),\n\t\tnewDeviceHook(tr.devicemanager, hookLogger),\n\t}\n\n\t// If the task has a CSI stanza, add the hook.\n\tif task.CSIPluginConfig != nil {\n\t\ttr.runnerHooks = append(tr.runnerHooks, newCSIPluginSupervisorHook(\n\t\t\t&csiPluginSupervisorHookConfig{\n\t\t\t\tclientStateDirPath: tr.clientConfig.StateDir,\n\t\t\t\tevents: tr,\n\t\t\t\trunner: tr,\n\t\t\t\tlifecycle: tr,\n\t\t\t\tcapabilities: tr.driverCapabilities,\n\t\t\t\tlogger: hookLogger,\n\t\t\t}))\n\t}\n\n\t// If Vault is enabled, add the hook\n\tif task.Vault != nil {\n\t\ttr.runnerHooks = append(tr.runnerHooks, newVaultHook(&vaultHookConfig{\n\t\t\tvaultStanza: task.Vault,\n\t\t\tclient: tr.vaultClient,\n\t\t\tevents: tr,\n\t\t\tlifecycle: tr,\n\t\t\tupdater: tr,\n\t\t\tlogger: hookLogger,\n\t\t\talloc: tr.Alloc(),\n\t\t\ttask: tr.taskName,\n\t\t}))\n\t}\n\n\t// Get the consul namespace for the TG of the allocation.\n\tconsulNamespace := tr.alloc.ConsulNamespace()\n\n\t// Identify the service registration provider, which can differ from the\n\t// Consul namespace depending on which provider is used.\n\tserviceProviderNamespace := tr.alloc.ServiceProviderNamespace()\n\n\t// If there are templates is enabled, add the hook\n\tif len(task.Templates) != 0 {\n\t\ttr.runnerHooks = append(tr.runnerHooks, newTemplateHook(&templateHookConfig{\n\t\t\tlogger: hookLogger,\n\t\t\tlifecycle: tr,\n\t\t\tevents: tr,\n\t\t\ttemplates: task.Templates,\n\t\t\tclientConfig: tr.clientConfig,\n\t\t\tenvBuilder: tr.envBuilder,\n\t\t\tconsulNamespace: consulNamespace,\n\t\t\tnomadNamespace: tr.alloc.Job.Namespace,\n\t\t}))\n\t}\n\n\t// Always add the service hook. A task with no services on initial registration\n\t// may be updated to include services, which must be handled with this hook.\n\ttr.runnerHooks = append(tr.runnerHooks, newServiceHook(serviceHookConfig{\n\t\talloc: tr.Alloc(),\n\t\ttask: tr.Task(),\n\t\tnamespace: serviceProviderNamespace,\n\t\tserviceRegWrapper: tr.serviceRegWrapper,\n\t\trestarter: tr,\n\t\tlogger: hookLogger,\n\t}))\n\n\t// If this is a Connect sidecar proxy (or a Connect Native) service,\n\t// add the sidsHook for requesting a Service Identity token (if ACLs).\n\tif task.UsesConnect() {\n\t\t// Enable the Service Identity hook only if the Nomad client is configured\n\t\t// with a consul token, indicating that Consul ACLs are enabled\n\t\tif tr.clientConfig.ConsulConfig.Token != \"\" {\n\t\t\ttr.runnerHooks = append(tr.runnerHooks, newSIDSHook(sidsHookConfig{\n\t\t\t\talloc: tr.Alloc(),\n\t\t\t\ttask: tr.Task(),\n\t\t\t\tsidsClient: tr.siClient,\n\t\t\t\tlifecycle: tr,\n\t\t\t\tlogger: hookLogger,\n\t\t\t}))\n\t\t}\n\n\t\tif task.UsesConnectSidecar() {\n\t\t\ttr.runnerHooks = append(tr.runnerHooks,\n\t\t\t\tnewEnvoyVersionHook(newEnvoyVersionHookConfig(alloc, tr.consulProxiesClient, hookLogger)),\n\t\t\t\tnewEnvoyBootstrapHook(newEnvoyBootstrapHookConfig(alloc, tr.clientConfig.ConsulConfig, consulNamespace, hookLogger)),\n\t\t\t)\n\t\t} else if task.Kind.IsConnectNative() {\n\t\t\ttr.runnerHooks = append(tr.runnerHooks, newConnectNativeHook(\n\t\t\t\tnewConnectNativeHookConfig(alloc, tr.clientConfig.ConsulConfig, hookLogger),\n\t\t\t))\n\t\t}\n\t}\n\n\t// Always add the script checks hook. A task with no script check hook on\n\t// initial registration may be updated to include script checks, which must\n\t// be handled with this hook.\n\ttr.runnerHooks = append(tr.runnerHooks, newScriptCheckHook(scriptCheckHookConfig{\n\t\talloc: tr.Alloc(),\n\t\ttask: tr.Task(),\n\t\tconsul: tr.consulServiceClient,\n\t\tlogger: hookLogger,\n\t}))\n\n\t// If this task driver has remote capabilities, add the remote task\n\t// hook.\n\tif tr.driverCapabilities.RemoteTasks {\n\t\ttr.runnerHooks = append(tr.runnerHooks, newRemoteTaskHook(tr, hookLogger))\n\t}\n}", "func (c *client) Hook(r *http.Request) (*model.Repo, *model.Build, error) {\n\treturn parseHook(r)\n}", "func (consumer *Consumer) Launch() {\n\tconsumer.rxC.runNum++\n\tconsumer.txC.runNum = consumer.rxC.runNum\n\tconsumer.Rx.Launch()\n\tconsumer.Tx.Launch()\n}", "func (listener *WebhookListener) Start(l <-chan struct{}) error {\n\tif klog.V(utils.QuiteLogLel) {\n\t\tfnName := utils.GetFnName()\n\t\tklog.Infof(\"Entering: %v()\", fnName)\n\n\t\tdefer klog.Infof(\"Exiting: %v()\", fnName)\n\t}\n\n\thttp.HandleFunc(\"/webhook\", listener.HandleWebhook)\n\n\tif listener.TLSKeyFile != \"\" && listener.TLSCrtFile != \"\" {\n\t\tklog.Info(\"Starting the WebHook listener on port 8443 with TLS key and cert files: \" + listener.TLSKeyFile + \" \" + listener.TLSCrtFile)\n\t\tklog.Fatal(http.ListenAndServeTLS(\":8443\", listener.TLSCrtFile, listener.TLSKeyFile, nil))\n\t} else {\n\t\tklog.Info(\"Starting the WebHook listener on port 8443 with no TLS.\")\n\t\tklog.Fatal(http.ListenAndServe(\":8443\", nil))\n\t}\n\n\tklog.Info(\"the WebHook listener started on port 8443.\")\n\n\t<-l\n\n\treturn nil\n}", "func (g *Generator) AddPreStartHook(path string, args []string) {\n\tg.initSpec()\n\thook := rspec.Hook{Path: path, Args: args}\n\tg.spec.Hooks.Prestart = append(g.spec.Hooks.Prestart, hook)\n}", "func start(state GameState) {\n\tlog.Printf(\"%s START\\n\", state.Game.ID)\n}", "func start(state GameState) {\n\tlog.Printf(\"%s START\\n\", state.Game.ID)\n}", "func (u *Update) LaunchAppBinary() error {\n\tcmd := exec.Command(*u.oldMollyBinaryPath)\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to execute run command for Molly Wallet: %v\", err)\n\t}\n\treturn nil\n}", "func (tr *TaskRunner) poststart() error {\n\tif tr.logger.IsTrace() {\n\t\tstart := time.Now()\n\t\ttr.logger.Trace(\"running poststart hooks\", \"start\", start)\n\t\tdefer func() {\n\t\t\tend := time.Now()\n\t\t\ttr.logger.Trace(\"finished poststart hooks\", \"end\", end, \"duration\", end.Sub(start))\n\t\t}()\n\t}\n\n\thandle := tr.getDriverHandle()\n\tnet := handle.Network()\n\n\t// Pass the lazy handle to the hooks so even if the driver exits and we\n\t// launch a new one (external plugin), the handle will refresh.\n\tlazyHandle := NewLazyHandle(tr.shutdownCtx, tr.getDriverHandle, tr.logger)\n\n\tvar merr multierror.Error\n\tfor _, hook := range tr.runnerHooks {\n\t\tpost, ok := hook.(interfaces.TaskPoststartHook)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tname := post.Name()\n\t\tvar start time.Time\n\t\tif tr.logger.IsTrace() {\n\t\t\tstart = time.Now()\n\t\t\ttr.logger.Trace(\"running poststart hook\", \"name\", name, \"start\", start)\n\t\t}\n\n\t\treq := interfaces.TaskPoststartRequest{\n\t\t\tDriverExec: lazyHandle,\n\t\t\tDriverNetwork: net,\n\t\t\tDriverStats: lazyHandle,\n\t\t\tTaskEnv: tr.envBuilder.Build(),\n\t\t}\n\t\tvar resp interfaces.TaskPoststartResponse\n\t\tif err := post.Poststart(tr.killCtx, &req, &resp); err != nil {\n\t\t\ttr.emitHookError(err, name)\n\t\t\tmerr.Errors = append(merr.Errors, fmt.Errorf(\"poststart hook %q failed: %v\", name, err))\n\t\t}\n\n\t\t// No need to persist as PoststartResponse is currently empty\n\n\t\tif tr.logger.IsTrace() {\n\t\t\tend := time.Now()\n\t\t\ttr.logger.Trace(\"finished poststart hooks\", \"name\", name, \"end\", end, \"duration\", end.Sub(start))\n\t\t}\n\t}\n\n\treturn merr.ErrorOrNil()\n}", "func LaunchGame(gameVersion game.Interface) error {\n\tlogger := logrus.WithFields(logrus.Fields{\n\t\t\"executable\": gameVersion.Executable(),\n\t})\n\n\tcmd := exec.Command(gameVersion.Executable())\n\tcmd.Dir = gameVersion.WorkingDir()\n\treturn cmd.Run()\n}", "func (c *config) Hook(req *http.Request) (*model.Repo, *model.Build, error) {\n\treturn parseHook(req)\n}", "func Start(wl ...debugLevel) {\n\tif isStarted {\n\t\tcolorLog(\"[ERRO] Fail to start Bee Watch[ %s ]\",\n\t\t\t\"cannot start Bee Watch twice\")\n\t\treturn\n\t}\n\n\tisStarted = true\n\tcolorLog(\"[INIT] BW: Bee Watch v%s.\\n\", APP_VER)\n\n\twatchLevel = LevelTrace\n\tif len(wl) > 0 {\n\t\twatchLevel = wl[0]\n\t}\n\n\tApp.Name = \"Bee Watch\"\n\tApp.HttpPort = 23456\n\tApp.WatchEnabled = true\n\tApp.PrintStack = true\n\tApp.PrintSource = true\n\n\tloadJSON()\n\n\tif App.WatchEnabled {\n\t\tif App.CmdMode {\n\n\t\t} else {\n\t\t\tinitHTTP()\n\t\t}\n\t}\n}", "func invokeHook(fn func() error) error {\n\tif fn != nil {\n\t\treturn fn()\n\t}\n\n\treturn nil\n}", "func (l *LaunchControl) Run(ctx context.Context) error {\n\tctx, cancel := context.WithCancel(ctx)\n\n\tdefer cancel()\n\tch := make(chan Event, ReadBufferDepth)\n\twg := sync.WaitGroup{}\n\n\tfor i := 0; i < NumChannels; i++ {\n\t\tif err := l.Reset(i); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// The first swap enables double buffering.\n\t\tif err := l.SwapBuffers(i); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := l.SetTemplate(0); err != nil {\n\t\treturn err\n\t}\n\n\tlcfg := drivers.ListenConfig{\n\t\tTimeCode: false,\n\t\tActiveSense: false,\n\t\tSysEx: true,\n\t\tOnErr: func(err error) {\n\t\t\t_ = l.handleError(err)\n\t\t},\n\t}\n\n\tvar err error\n\tl.stopFn, err = l.inputDriver.Listen(func(msg []byte, milliseconds int32) {\n\t\tif len(msg) == 3 {\n\t\t\tch <- Event{\n\t\t\t\tTimestamp: milliseconds,\n\t\t\t\tStatus: msg[0],\n\t\t\t\tData1: msg[1],\n\t\t\t\tData2: msg[2],\n\t\t\t}\n\t\t} else {\n\t\t\tl.sysexEvent(msg)\n\t\t}\n\t}, lcfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase evt := <-ch:\n\t\t\t\tl.event(evt)\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\n\t\tticker := time.NewTicker(FlashPeriod)\n\t\tdefer ticker.Stop()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase <-ticker.C:\n\t\t\t\tl.lock.Lock()\n\t\t\t\tl.flashes++\n\t\t\t\tch := l.currentChannel\n\t\t\t\tl.lock.Unlock()\n\n\t\t\t\t_ = l.SwapBuffers(ch)\n\t\t\t}\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase err := <-l.errorChan:\n\t\treturn err\n\t}\n}", "func (s *BaseAspidaListener) EnterMain(ctx *MainContext) {}", "func hookTerminator(e *evtx.GoEvtxMap) {\n\tif e.EventID() == 1 {\n\t\tif commandLine, err := e.GetString(&sysmonCommandLine); err == nil {\n\t\t\tif pid, err := e.GetInt(&sysmonProcessId); err == nil {\n\t\t\t\tif blacklistedImages.Contains(commandLine) {\n\t\t\t\t\tlog.Warnf(\"Terminating blacklisted process PID=%d CommandLine=\\\"%s\\\"\", pid, commandLine)\n\t\t\t\t\tif err := terminator(int(pid)); err != nil {\n\t\t\t\t\t\tlog.Errorf(\"Failed to terminate process PID=%d: %s\", pid, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *DockerContainer) startedHook(ctx context.Context) error {\n\tfor _, lifecycleHooks := range c.lifecycleHooks {\n\t\terr := containerHookFn(ctx, lifecycleHooks.PostStarts)(c)\n\t\tif err != nil {\n\t\t\tc.printLogs(ctx)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (el *Launcher) Start() error {\n\tlogrus.Debugf(\"engine launcher %v: prepare to start engine %v at %v\",\n\t\tel.LauncherName, el.currentEngine.EngineName, el.currentEngine.GetListen())\n\n\tif err := el.currentEngine.Start(); err != nil {\n\t\treturn err\n\t}\n\n\tel.updateCh <- el\n\n\tlogrus.Debugf(\"engine launcher %v: succeed to start engine %v at %v\",\n\t\tel.LauncherName, el.currentEngine.EngineName, el.currentEngine.GetListen())\n\n\treturn nil\n}", "func NewLaunch(cfg datastore.Config, next http.HandlerFunc) *launch.Launch {\n\treturn launch.New(cfg, next)\n}", "func (p *procBase) start(args ...string) error {\n\tif p.Running() {\n\t\treturn fmt.Errorf(\"Process %s is running\", p.Name())\n\t}\n\n\t// Always log to stderr, we'll capture and process logs.\n\targs = append(args, \"-logtostderr\", \"-v=1\")\n\n\tp.cmd = exec.Command(p.bin, args...)\n\tp.cmd.Stdout = NewLogDemuxer(p.name, p.loggers)\n\tp.cmd.Stderr = p.cmd.Stdout\n\treturn p.cmd.Start()\n}", "func (s *BaseGShellListener) EnterCommandLine(ctx *CommandLineContext) {}", "func (u *UnityServer) startUnityApp() {\n\tu.Logger.Debugf(\"Path: %v\", pathToUnity)\n\tif pathToUnity != \"\" {\n\t\tu.unityApp = exec.Command(pathToUnity)\n\t\tu.unityApp.Run()\n\t} else {\n\t\tu.Logger.Warn(\"Path to unity not set\")\n\t}\n}", "func (g *Generator) AddPostStartHook(path string, args []string) {\n\tg.initSpec()\n\thook := rspec.Hook{Path: path, Args: args}\n\tg.spec.Hooks.Poststart = append(g.spec.Hooks.Poststart, hook)\n}", "func (p *usermdPlugin) Hook(h plugins.HookT, payload string) error {\n\tlog.Tracef(\"usermd Hook: %v\", plugins.Hooks[h])\n\n\tswitch h {\n\tcase plugins.HookTypeNewRecordPre:\n\t\treturn p.hookNewRecordPre(payload)\n\tcase plugins.HookTypeNewRecordPost:\n\t\treturn p.hookNewRecordPost(payload)\n\tcase plugins.HookTypeEditRecordPre:\n\t\treturn p.hookEditRecordPre(payload)\n\tcase plugins.HookTypeEditMetadataPre:\n\t\treturn p.hookEditMetadataPre(payload)\n\tcase plugins.HookTypeSetRecordStatusPre:\n\t\treturn p.hookSetRecordStatusPre(payload)\n\tcase plugins.HookTypeSetRecordStatusPost:\n\t\treturn p.hookSetRecordStatusPost(payload)\n\t}\n\n\treturn nil\n}", "func Run(ctx context.Context, initial Func, hooks ...Hook) (err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\tpe, ok := e.(error)\n\t\t\tif !ok {\n\t\t\t\tpe = fmt.Errorf(\"%+v\", e)\n\t\t\t}\n\t\t\tmsg := fmt.Sprintf(\"panic in %s\", Name(ctx))\n\t\t\tif err != nil {\n\t\t\t\tmsg += fmt.Sprintf(\"\\noriginal error: %+v\", err)\n\t\t\t}\n\t\t\terr = errors.Wrap(pe, msg)\n\t\t}\n\t}()\n\n\tctx = context.WithValue(ctx, stateKey, &initial)\n\tfor initial != nil {\n\t\tfor i, h := range hooks {\n\t\t\terr = h(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"applying state hook %d\", i)\n\t\t\t}\n\t\t}\n\t\tinitial = initial(ctx)\n\t}\n\treturn\n}", "func (*trackerServer) WorkflowLaunched(c context.Context, req *admin.WorkflowLaunchedRequest) (*admin.WorkflowLaunchedResponse, error) {\n\tif req.RunId == 0 {\n\t\treturn nil, grpc.Errorf(codes.InvalidArgument, \"missing run ID\")\n\t}\n\tif err := workflowLaunched(c, req, config.WorkflowCache); err != nil {\n\t\treturn nil, grpc.Errorf(codes.Internal, \"failed to track workflow launched: %v\", err)\n\t}\n\treturn &admin.WorkflowLaunchedResponse{}, nil\n}", "func (l Launcher) Launch(cmd string) (piper.Executor, error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\treturn exe{exec.CommandContext(ctx, \"sh\", \"-c\", cmd), cancel, cmd}, nil\n}", "func main() {\n\tdebugln(\"main!\")\n}", "func (h *Hook) Fire(entry *log.Entry) error {\n\n\tstart := time.Now()\n\tpc := make([]uintptr, 3, 3)\n\tcnt := runtime.Callers(6, pc)\n\n\tlo := &LogEntry{\n\t\tMessage: entry.Message,\n\t\tLevel: strings.ToUpper(entry.Level.String()),\n\t\tStartTime: start.Format(h.dateFormat),\n\t\tData: entry.Data,\n\t}\n\n\tfor i := 0; i < cnt; i++ {\n\t\tfu := runtime.FuncForPC(pc[i] - 1)\n\t\tname := fu.Name()\n\t\tif !strings.Contains(name, \"github.com/sirupsen/logrus\") {\n\t\t\tfile, line := fu.FileLine(pc[i] - 1)\n\t\t\tlo.File = path.Base(file)\n\t\t\tlo.Function = path.Base(name)\n\t\t\tlo.Line = strconv.Itoa(line)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tbuff := &bytes.Buffer{}\n\n\tif h.FormatType == constants.LogFormatJSON {\n\t\tjson.NewEncoder(buff).Encode(lo)\n\t} else {\n\t\th.template.Execute(buff, lo)\n\t}\n\n\tif h.logType == constants.LogTypePrint {\n\t\tfmt.Print(string(buff.String()))\n\t}\n\n\tif h.logType == constants.LogTypeFile {\n\t\tgo func() {\n\t\t\th.mutex.Lock()\n\t\t\tlogPath := config.GetString(\"log.path\")\n\n\t\t\trotate := logPath + \"/app-\" + start.Format(\"2006-01-02\")\n\n\t\t\tif h.rotateType == \"static\" {\n\t\t\t\trotate = logPath + \"/app\"\n\t\t\t}\n\n\t\t\tdir, base := filepath.Split(filepath.Clean(rotate))\n\n\t\t\tfileName := dir + base + \".log\"\n\n\t\t\tif helpers.PathExist(logPath) {\n\t\t\t\th.openNew(fileName)\n\t\t\t\tif h.file != nil {\n\t\t\t\t\th.lWriter.SetOutput(h.file)\n\t\t\t\t\th.lWriter.Print(string(buff.String()))\n\t\t\t\t}\n\t\t\t}\n\t\t\th.mutex.Unlock()\n\t\t}()\n\t}\n\treturn nil\n}", "func (tr *TaskRunner) preKill() {\n\tif tr.logger.IsTrace() {\n\t\tstart := time.Now()\n\t\ttr.logger.Trace(\"running pre kill hooks\", \"start\", start)\n\t\tdefer func() {\n\t\t\tend := time.Now()\n\t\t\ttr.logger.Trace(\"finished pre kill hooks\", \"end\", end, \"duration\", end.Sub(start))\n\t\t}()\n\t}\n\n\tfor _, hook := range tr.runnerHooks {\n\t\tkillHook, ok := hook.(interfaces.TaskPreKillHook)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tname := killHook.Name()\n\n\t\t// Time the pre kill hook\n\t\tvar start time.Time\n\t\tif tr.logger.IsTrace() {\n\t\t\tstart = time.Now()\n\t\t\ttr.logger.Trace(\"running prekill hook\", \"name\", name, \"start\", start)\n\t\t}\n\n\t\t// Run the pre kill hook\n\t\treq := interfaces.TaskPreKillRequest{}\n\t\tvar resp interfaces.TaskPreKillResponse\n\t\tif err := killHook.PreKilling(context.Background(), &req, &resp); err != nil {\n\t\t\ttr.emitHookError(err, name)\n\t\t\ttr.logger.Error(\"prekill hook failed\", \"name\", name, \"error\", err)\n\t\t}\n\n\t\t// No need to persist as TaskKillResponse is currently empty\n\n\t\tif tr.logger.IsTrace() {\n\t\t\tend := time.Now()\n\t\t\ttr.logger.Trace(\"finished prekill hook\", \"name\", name, \"end\", end, \"duration\", end.Sub(start))\n\t\t}\n\t}\n}", "func (master *ProcMaster) start(proc ProcContainer) error {\n\tif !proc.IsAlive() {\n\t\terr := proc.Start()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmaster.Watcher.AddProcWatcher(proc, false)\n\t\tproc.SetStatus(\"running\")\n\t}\n\treturn nil\n}", "func (g *GitLab) Hook(ctx context.Context, req *http.Request) (*model.Repo, *model.Pipeline, error) {\n\tdefer req.Body.Close()\n\tpayload, err := io.ReadAll(req.Body)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\teventType := gitlab.WebhookEventType(req)\n\tparsed, err := gitlab.ParseWebhook(eventType, payload)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tswitch event := parsed.(type) {\n\tcase *gitlab.MergeEvent:\n\t\tmergeIID, repo, pipeline, err := convertMergeRequestHook(event, req)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tif pipeline, err = g.loadChangedFilesFromMergeRequest(ctx, repo, pipeline, mergeIID); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\treturn repo, pipeline, nil\n\tcase *gitlab.PushEvent:\n\t\treturn convertPushHook(event)\n\tcase *gitlab.TagEvent:\n\t\treturn convertTagHook(event)\n\tdefault:\n\t\treturn nil, nil, &types.ErrIgnoreEvent{Event: string(eventType)}\n\t}\n}", "func (d *Demo) Play() {\n\t//Steam isn't in PATH on windows systems, have to specify steam path\n\tcmd := exec.Command(\"steam\", \"-applaunch\", \"440\", \"+playdemo\", d.PathInTFFolder())\n\tif runtime.GOOS == \"windows\" {\n\t\tcmd = exec.Command(\"cmd\", \"/c\", \"start\", \"\", `C:\\Program Files (x86)\\Steam\\Steam.exe`,\n\t\t\t\"-applaunch\", \"440\", \"+playdemo\", d.PathInTFFolder())\n\t}\n\tcmd.Start()\n}", "func (p PRPlugin) onOpen(env *ActionsEnv) error {\n\tp.Debugf(\"%q handler\", actionOpen)\n\t// Create the check run\n\tcheckRun, err := p.createCheckRun(env.Client, env.Owner, env.Repo, env.Event.GetPullRequest().GetHead().GetSHA())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Process the PR and submit the results\n\t_, err = p.processAndSubmit(env, checkRun)\n\treturn err\n}", "func (p Plane) Launch(logCh chan map[string]interface{}) ([]sleepwalker.Result, error) {\n\tdesc := \"airstrike.Plane.Launch\"\n\tvar results []sleepwalker.Result\n\n\tlogCh <- map[string]interface{}{\n\t\t\"source\": desc,\n\t\t\"plane\": p,\n\t}\n\n\tfor _, weapon := range p.Arsenal {\n\t\tresult, err := p.fireWeapon(weapon, logCh)\n\t\tif err != nil {\n\t\t\tlogCh <- map[string]interface{}{\n\t\t\t\t\"source\": desc,\n\t\t\t\t\"error\": err,\n\t\t\t\t\"plane\": p,\n\t\t\t\t\"weapon\": weapon,\n\t\t\t\t\"severity\": \"ERROR\",\n\t\t\t}\n\t\t}\n\t\tresults = append(results, result)\n\t}\n\treturn results, nil\n}", "func main() {\n\tdefer interrupts.WaitForGracefulShutdown()\n\n\to := gatherOptions(flag.NewFlagSet(os.Args[0], flag.ExitOnError), os.Args[1:]...)\n\tif err := o.Validate(); err != nil {\n\t\tlogrus.WithError(err).Fatal(\"Invalid options\")\n\t}\n\n\tif o.jsonLog {\n\t\tlogrus.SetFormatter(logrusutil.CreateDefaultFormatter())\n\t}\n\n\tcontroller, err := webhook.NewWebhooksController(o.path, o.namespace, o.botName, o.pluginFilename, o.configFilename)\n\tif err != nil {\n\t\tlogrus.WithError(err).Fatal(\"failed to set up controller\")\n\t}\n\tdefer func() {\n\t\tcontroller.CleanupGitClientDir()\n\t\tcontroller.ConfigMapWatcher.Stop()\n\t}()\n\n\tmux := http.NewServeMux()\n\tmux.Handle(HealthPath, http.HandlerFunc(controller.Health))\n\tmux.Handle(ReadyPath, http.HandlerFunc(controller.Ready))\n\n\tmux.Handle(\"/\", http.HandlerFunc(controller.DefaultHandler))\n\tmux.Handle(o.path, http.HandlerFunc(controller.HandleWebhookRequests))\n\tmux.Handle(o.pollPath, http.HandlerFunc(controller.HandlePollingRequests))\n\n\t// lets serve metrics\n\tmetricsHandler := http.HandlerFunc(controller.Metrics)\n\tgo serveMetrics(metricsHandler)\n\n\tlogrus.Infof(\"Lighthouse is now listening on path %s and port %d for WebHooks\", o.path, o.port)\n\terr = http.ListenAndServe(\":\"+strconv.Itoa(o.port), mux)\n\tlogrus.WithError(err).Errorf(\"failed to serve HTTP\")\n}", "func (s *BaseBundListener) EnterCall_term(ctx *Call_termContext) {}", "func (c *ComputerClient) Launch(name string) (err error) {\n\tapi := fmt.Sprintf(\"/computer/%s/launchSlaveAgent\", name)\n\t_, err = c.RequestWithoutData(\"POST\", api, nil, nil, 200)\n\treturn\n}", "func (plugin OpenPlugin) Run(cliConnection plugin.CliConnection, args []string) {\n\terr := checkArgs(cliConnection, args)\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\tif args[0] == \"open\" {\n\t\tplugin.runAppOpen(cliConnection, args)\n\t} else if args[0] == \"service-open\" {\n\t\tplugin.runServiceOpen(cliConnection, args)\n\t}\n}", "func (s *BasemumpsListener) EnterBreak_(ctx *Break_Context) {}", "func (e *engine) Start(context.Context, *Spec, *Step) error {\n\treturn nil // no-op for bash implementation\n}", "func (p *literalProcessor) start() { go p.run() }", "func main() {\n\tadapter.RunStage(split, chunk, join)\n}", "func (h LogHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {\n\t// Send log type metric\n\th.metric.RecordByLogTypes(level.String())\n\t// Send version in each log entry\n\te.Str(\"version\", Version)\n}" ]
[ "0.5877089", "0.5779476", "0.5759628", "0.57347715", "0.56235826", "0.5620141", "0.56181556", "0.5604568", "0.5598416", "0.5588178", "0.5450167", "0.5426442", "0.54139924", "0.53387564", "0.5329647", "0.5309052", "0.52930015", "0.52812076", "0.5246368", "0.52041054", "0.51378936", "0.51193875", "0.51181525", "0.511654", "0.5091731", "0.5067031", "0.50654596", "0.50652343", "0.5058392", "0.5057855", "0.5033662", "0.5029743", "0.5022925", "0.5021045", "0.4994063", "0.49930233", "0.49903986", "0.4989758", "0.4989042", "0.49866468", "0.49852404", "0.49833524", "0.49793667", "0.49669063", "0.4964295", "0.4947954", "0.49441075", "0.49359623", "0.49284264", "0.49278766", "0.49038512", "0.48831564", "0.48782852", "0.48750383", "0.48687696", "0.4864929", "0.48611107", "0.48521858", "0.48482928", "0.48341486", "0.48310143", "0.4801253", "0.4801253", "0.48000664", "0.47931254", "0.4791028", "0.4776433", "0.4776221", "0.47736102", "0.47567716", "0.47504866", "0.47501722", "0.47355798", "0.47206202", "0.47128433", "0.4712504", "0.4708922", "0.47059795", "0.4696992", "0.46889102", "0.46872878", "0.4672089", "0.46617058", "0.46612144", "0.46514574", "0.465103", "0.46335864", "0.4632002", "0.4631934", "0.46315327", "0.46176216", "0.46134526", "0.46060774", "0.46047756", "0.45957404", "0.45932105", "0.4592357", "0.4586601", "0.45829564", "0.45825824" ]
0.73184854
0
init configures default parameters for engine.
func (e *Engine) init() { e.mutex.Lock() defer e.mutex.Unlock() if e.ctx == nil || e.cancel == nil { e.ctx, e.cancel = context.WithCancel(e.parent) } if e.timeout == 0 { e.timeout = DefaultTimeout } if len(e.signals) == 0 && !e.noSignal { e.signals = Signals } if e.interrupt == nil { e.interrupt = make(chan os.Signal, 1) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (eng *Engine) Init(cfg string) error {\n\treturn nil\n}", "func Init(eng *en.RealEngine) {\n\tengine = *eng\n}", "func (engine *Engine) Init(options types.EngineOpts) {\n\t// 将线程数设置为CPU数\n\t// runtime.GOMAXPROCS(runtime.NumCPU())\n\t// runtime.GOMAXPROCS(128)\n\n\t// 初始化初始参数\n\tif engine.initialized {\n\t\tlog.Fatal(\"Do not re-initialize the engine.\")\n\t}\n\n\tif options.GseDict == \"\" && !options.NotUseGse && !engine.loaded {\n\t\tlog.Printf(\"Dictionary file path is empty, load the default dictionary file.\")\n\t\toptions.GseDict = \"zh\"\n\t}\n\n\tif options.UseStore == true && options.StoreFolder == \"\" {\n\t\tlog.Printf(\"Store file path is empty, use default folder path.\")\n\t\toptions.StoreFolder = DefaultPath\n\t\t// os.MkdirAll(DefaultPath, 0777)\n\t}\n\n\toptions.Init()\n\tengine.initOptions = options\n\tengine.initialized = true\n\n\tif !options.NotUseGse {\n\t\tif !engine.loaded {\n\t\t\t// 载入分词器词典\n\t\t\tengine.segmenter.LoadDict(options.GseDict)\n\t\t\tengine.loaded = true\n\t\t}\n\n\t\t// 初始化停用词\n\t\tengine.stopTokens.Init(options.StopTokenFile)\n\t}\n\n\t// 初始化索引器和排序器\n\tfor shard := 0; shard < options.NumShards; shard++ {\n\t\tengine.indexers = append(engine.indexers, core.Indexer{})\n\t\tengine.indexers[shard].Init(*options.IndexerOpts)\n\n\t\tengine.rankers = append(engine.rankers, core.Ranker{})\n\t\tengine.rankers[shard].Init(options.IDOnly)\n\t}\n\n\t// 初始化分词器通道\n\tengine.segmenterChan = make(\n\t\tchan segmenterReq, options.NumGseThreads)\n\n\t// 初始化索引器通道\n\tengine.Indexer(options)\n\n\t// 初始化排序器通道\n\tengine.Ranker(options)\n\n\t// engine.CheckMem(engine.initOptions.UseStore)\n\tengine.CheckMem()\n\n\t// 初始化持久化存储通道\n\tif engine.initOptions.UseStore {\n\t\tengine.InitStore()\n\t}\n\n\t// 启动分词器\n\tfor iThread := 0; iThread < options.NumGseThreads; iThread++ {\n\t\tgo engine.segmenterWorker()\n\t}\n\n\t// 启动索引器和排序器\n\tfor shard := 0; shard < options.NumShards; shard++ {\n\t\tgo engine.indexerAddDocWorker(shard)\n\t\tgo engine.indexerRemoveDocWorker(shard)\n\t\tgo engine.rankerAddDocWorker(shard)\n\t\tgo engine.rankerRemoveDocWorker(shard)\n\n\t\tfor i := 0; i < options.NumIndexerThreadsPerShard; i++ {\n\t\t\tgo engine.indexerLookupWorker(shard)\n\t\t}\n\t\tfor i := 0; i < options.NumRankerThreadsPerShard; i++ {\n\t\t\tgo engine.rankerRankWorker(shard)\n\t\t}\n\t}\n\n\t// 启动持久化存储工作协程\n\tif engine.initOptions.UseStore {\n\t\tengine.Store()\n\t}\n\n\tatomic.AddUint64(&engine.numDocsStored, engine.numIndexingReqs)\n}", "func Init() {\n\tEngine = gin.Default()\n}", "func init() {\n\tconfig.Read()\n\n\tdao.Server = config.Server\n\tdao.Database = config.Database\n\tdao.Connect()\n}", "func init() {\n\tconfig.Read()\n\n\tdao.Server = config.Server\n\tdao.Database = config.Database\n\tdao.Connect()\n}", "func (cfg *Config) init() {\n\tcfg.Version = viper.GetString(\"version\")\n\tcfg.setLogLevel(viper.GetString(\"log_level\"))\n\tcfg.AppName = viper.GetString(\"app_name\")\n\tcfg.AppShortName = viper.GetString(\"app_short_name\")\n\n\tcfg.API.UsingHttps = viper.GetBool(\"api.usingHttps\")\n\tcfg.API.Port = viper.GetInt(\"api.port\")\n\tcfg.API.AllowedMethods = viper.GetStringSlice(\"api.allowed_methods\")\n\tcfg.API.AllowedHeaders = viper.GetStringSlice(\"api.allowed_headers\")\n\tcfg.API.AllowedOrigins = viper.GetStringSlice(\"api.allowed_origins\")\n\n\tcfg.Database.Host = viper.GetString(\"database.host\")\n\tcfg.Database.Port = viper.GetInt(\"database.port\")\n\tcfg.Database.Db = viper.GetString(\"database.database\")\n\tcfg.Database.User = viper.GetString(\"database.user\")\n\tcfg.Database.Password = viper.GetString(\"database.password\")\n\tcfg.Database.SSLMode = viper.GetString(\"database.sslmode\")\n\n\tcfg.Keys.CSRFKey = viper.GetString(\"secrets.csrf\")\n\tcfg.Keys.JWTSecret = viper.GetString(\"secrets.jwtsecret\")\n\tcfg.Keys.ApiLogin = viper.GetString(\"secrets.api_login\")\n}", "func init() {\n\t// set reasonable defaults\n\tsetDefaults()\n\n\t// override defaults with configuration read from configuration file\n\tviper.AddConfigPath(\"$GOPATH/src/github.com/xlab-si/emmy/config\")\n\terr := loadConfig(\"defaults\", \"yml\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func init() {\n\tinitconf(configLocation)\n}", "func Init(path, defaultLocale string, trimOptional ...bool) error {\n\ttrim := false\n\tif len(trimOptional) > 0 {\n\t\ttrim = true\n\t}\n\n\tengine, err := NewEngine(path, defaultLocale, trim)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tDefaultEngine = engine\n\treturn nil\n}", "func (m Model) Init() tea.Cmd {\n\t//s := engineManager.StartMainEngine()\n\treturn tea.Batch(StartMainEngine, spinner.Tick)\n}", "func init() {\n\tflag.Parse()\n\t// Init the models and backend redis store.\n\trs := libstore.NewStore(*redisServer)\n\tuser.Setup(rs)\n\tfeed.Setup(rs)\n\t// Init feeder.\n\tfd = feeder.NewFeeder(\"http://localhost:\" + *keywordServerEndPoint)\n}", "func init() {\n\tprepareOptionsFromCommandline(&configFromInit)\n\tparseConfigFromEnvironment(&configFromInit)\n}", "func (d *Default) Init(params map[interface{}]interface{}) error {\n\treturn nil\n}", "func (e *AlertEngine) Init() error {\n\te.ticker = NewTicker(time.Now(), time.Second*0, clock.New())\n\te.execQueue = make(chan *Job, 1000)\n\te.scheduler = newScheduler()\n\te.evalHandler = NewEvalHandler()\n\te.ruleReader = newRuleReader()\n\te.log = log.New(\"alerting.engine\")\n\te.resultHandler = newResultHandler(e.RenderService)\n\treturn nil\n}", "func init() {\n\tv := initViper()\n\tconf = Config{\n\t\tApp: appConfig(v),\n\t\tMysql: mysqlConfig(v),\n\t\tRedis: redisConfig(v),\n\t\tLog: logConfig(v),\n\t\tElasticAPM: elasticApmConfig(v),\n\t\tSentry: sentryConfig(v),\n\t}\n}", "func init() {\n\t// Initialization goes here\n}", "func (templateEngine *TemplateEngine) Init(env interface{}) {\n\ttemplateEngine.Init1(env, nil, false)\n}", "func init() {\n\tconf = &Config{}\n\t// This prefix means our variables will be in the form of GDEMO_MODE (for example)\n\terr := envconfig.Process(\"GDEMO\", conf)\n\tif err != nil {\n\t\tfmt.Println(\"Fatal error processing configuration\")\n\t\tpanic(err)\n\t}\n\tl := conf.GetLogger()\n\n\t// Sanity check\n\tif !conf.IsDebugMode() && !conf.IsProductionMode() {\n\t\tl.Fatal(\"Invalid GDEMO_MODE variable, it must be either `debug` or `production`\")\n\t}\n}", "func init() {\n\tvar err error\n\tvar dataSource = os.Getenv(\"MYSQL_CONNECTION\")\n\tengine, err = xorm.NewEngine(\"mysql\", dataSource)\n\tif(err != nil){\n\t\tpanic(err)\n\t}\n\n\t//engine.ShowSQL(true)\n}", "func (c *Config) init() {\n\n\tc.logger = logrus.New()\n\n\t// Connect slots\n\tc.ConnectStringSet(func(key string, val string) {\n\t\tc.SetString(key, val)\n\t})\n\tc.ConnectBoolSet(func(key string, val bool) {\n\t\tc.SetBool(key, val)\n\t})\n\tc.ConnectStringValue(func(key string) string {\n\t\treturn c.GetString(key)\n\t})\n\tc.ConnectBoolValue(func(key string) bool {\n\t\treturn c.GetBool(key)\n\t})\n\tc.ConnectSave(func() {\n\t\tc.save()\n\t})\n\tc.ConnectDefaults(func() {\n\t\tc.SetDefaults()\n\t})\n}", "func init() {\n\t// TODO: set logger\n\t// TODO: register storage plugin to plugin manager\n}", "func (c *AuthConfig) init() {\n\tif c.Provisioners == nil {\n\t\tc.Provisioners = provisioner.List{}\n\t}\n\tif c.Template == nil {\n\t\tc.Template = &ASN1DN{}\n\t}\n\tif c.Backdate == nil {\n\t\tc.Backdate = &provisioner.Duration{\n\t\t\tDuration: DefaultBackdate,\n\t\t}\n\t}\n}", "func init() {\n\t// common\n\tviper.SetDefault(\"log.level\", \"info\")\n\n\t// ethereum\n\tviper.SetDefault(\"ethereum.addr\", \"https://cloudflare-eth.com\")\n\tviper.SetDefault(\"ethereum.wss\", false)\n\n\t// grpc admin\n\tviper.SetDefault(\"grpc.host\", \"0.0.0.0\")\n\tviper.SetDefault(\"grpc.port\", 9090)\n\tviper.SetDefault(\"grpc.timeout\", \"120s\")\n\n\t// cache\n\tviper.SetDefault(\"cachesize\", 100)\n}", "func (node *Node) init() {\n\n\t//step0. parse config\n\n\tif err := node.parseConfig(node.configFile); err != nil {\n\t\t//temp code\n\t\tlog.Panicf(\"Parse Config Error: %s\", err.Error())\n\t\treturn\n\t}\n\n\t//step1. init process runtime and update node state to NodeStateInit\n\n\t//step2. try to connecting other nodes and store the connection to internalConns\n\n\t//init finnal. update node state to NodeStateNormal\n\n}", "func init() {\n\t//todo...\n}", "func init() {\n\tdbconn, err := database.NewPostgreDB(dbType, connStr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsesconn, err := database.NewRedisCache(addr, pass)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tconfig.dbconn = dbconn\n\tconfig.sessionconn = sesconn\n}", "func init() {\n\tinitCfgDir()\n\tinitCreds()\n}", "func init() {\n\tviper.SetDefault(\"attestation-type\", constants.DefaultAttestationType)\n\tviper.SetDefault(\"poll-interval-minutes\", constants.PollingIntervalMinutes)\n\n\t//Set default values for TLS\n\tviper.SetDefault(\"tls-cert-file\", constants.DefaultTLSCertFile)\n\tviper.SetDefault(\"tls-key-file\", constants.DefaultTLSKeyFile)\n\tviper.SetDefault(\"tls-common-name\", constants.DefaultIHUBTlsCn)\n\tviper.SetDefault(\"tls-san-list\", constants.DefaultTLSSan)\n\n\t//Set default values for log\n\tviper.SetDefault(\"log-max-length\", constants.DefaultLogEntryMaxlength)\n\tviper.SetDefault(\"log-enable-stdout\", true)\n\tviper.SetDefault(\"log-level\", \"info\")\n}", "func init() {\n\tfor group, values := range defaultConfigs {\n\t\tcore.RegisterConfig(group, values)\n\t}\n\tcore.RegisterService(\"indicator\", indicator.Configs, &indicator.IndicatorServiceFactory{})\n\tcore.RegisterService(\"executor\", executor.Configs, &executor.ExecutorServiceFactory{})\n}", "func initConfig() {\n\tif RootConfig.clusterID == \"\" {\n\t\tlog.Fatal(\"A cluster id must be provided.\")\n\t}\n\tif RootConfig.internal {\n\t\tRootConfig.config = insideCluster()\n\t} else {\n\t\tRootConfig.config = outsideCluster()\n\t}\n}", "func (e *EventSourcedEntity) init() error {\n\te.SnapshotEvery = snapshotEveryDefault\n\treturn nil\n}", "func init() {\n\tc.getConf()\n\trotateLogger()\n}", "func initConfig() {\n}", "func initConfig() {\n}", "func initConfig() {\n}", "func initConfig() {\n}", "func initConfig() {\n}", "func initConfig() {\n}", "func (c *configData) init() {\n\tconst filename = \".workflow.yml\"\n\n\tc.Global = viper.New()\n\tc.Local = viper.New()\n\n\t// c.Local.SetConfigFile(\n\t// \tpath.Join(git.RootDir(), filename),\n\t// )\n\n\tc.Global.SetConfigFile(\n\t\tpath.Join(currentUser.HomeDir, filename),\n\t)\n\n\t// TODO: configs := []*viper.Viper{c.Local, c.Global}\n\tconfigs := []*viper.Viper{c.Global}\n\tfor _, v := range configs {\n\t\t_, _ = file.Touch(v.ConfigFileUsed())\n\t\tfailIfError(v.ReadInConfig())\n\t}\n\n\tfailIfError(c.validate())\n\tfailIfError(c.update())\n\tc.initJira()\n}", "func init() {\n\tconfig.Read()\n\tdao.DialInfo = &mgo.DialInfo{\n\t\tAddrs: []string{config.Server},\n\t\tDatabase: config.Database,\n\t\tUsername: config.Username,\n\t\tPassword: config.Password,\n\t}\n\n\tdao.Server = config.Server\n\tdao.Database = config.Database\n\tdao.Connect()\n\n}", "func init() {\n\tSetup()\n}", "func Init() error {\n\t// Logger = elog.DefaultLogger\n\tC.Github = &C.GithubOauth{}\n\tC.Facebook = &C.FacebookOauth{}\n\tC.Minio = &C.MinioConfig{}\n\tC.Seq = &C.Sequence{}\n\tC.JWT = &C.JWTConfig{}\n\n\terr := econf.UnmarshalKey(\"ceres.oauth.github\", C.Github)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = econf.UnmarshalKey(\"ceres.oauth.facebook\", C.Facebook)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = econf.UnmarshalKey(\"ceres.minio\", C.Minio)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = econf.UnmarshalKey(\"ceres.sequence\", C.Seq)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = econf.UnmarshalKey(\"ceres.jwt\", C.JWT)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func init() {\n\tInitSystemVariables()\n}", "func (e *Engine) Init() {\n\tif err := sdl.Init(sdl.INIT_EVERYTHING); err != nil {\n\t\tcheckErr(err)\n\t}\n\n\tif err := ttf.Init(); err != nil {\n\t\tcheckErr(err)\n\t}\n}", "func init() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\tappAddr = os.Getenv(\"APP_ADDR\") // e.g. \"0.0.0.0:8080\" or \"\"\n\n\tconf = new(app.ConfigConode)\n\tif err := app.ReadTomlConfig(conf, defaultConfigFile); err != nil {\n\t\tfmt.Printf(\"Couldn't read configuration file: %v\", err)\n\t\tos.Exit(1)\n\t}\n\n\tsuite = app.GetSuite(conf.Suite)\n\tpub, _ := base64.StdEncoding.DecodeString(conf.AggPubKey)\n\tsuite.Read(bytes.NewReader(pub), &public_X0)\n}", "func setupMainEngine() *gin.Engine {\n\tr := gin.Default()\n\n\t// healthz\n\thealthz := &healthz{}\n\tr.GET(\"/healthz\", healthz.getHealthz)\n\n\tsources := defaultSources\n\tsourcesFromEnv := strings.Split(os.Getenv(\"NEWS_SOURCES\"), \",\")\n\tif len(sourcesFromEnv) != 0 {\n\t\tsources = sourcesFromEnv\n\t}\n\tnews := &news{\n\t\tapiKey: os.Getenv(\"NEWS_API_KEY\"),\n\t\turl: \"https://newsapi.org/v2\",\n\t\tsources: sources,\n\t}\n\tr.GET(\"/\", news.articleURL)\n\tr.GET(\"/slack\", news.articleForSlack)\n\n\treturn r\n}", "func init() {\n\tviper.AddConfigPath(\".\")\n\tviper.AddConfigPath(\"/config\")\n\tviper.SetConfigName(\"postgres\")\n\tlog.Info(\"Initializing postgresql config\")\n\t// TODO: set defaults\n\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tlog.Error(err, \"Failed to read config\")\n\t\tos.Exit(1)\n\t}\n\n\tconnStr := fmt.Sprintf(\"dbname=%s user=%s password=%s host=%s sslmode=disable\",\n\t\tviper.GetString(\"dbDatabase\"),\n\t\tviper.GetString(\"dbUser\"),\n\t\tviper.GetString(\"dbPassword\"),\n\t\tviper.GetString(\"dbHost\"))\n\n\tdbCon, err = sql.Open(\"postgres\", connStr)\n\tif err != nil {\n\t\tlog.Error(err, \"Unable to connect to the database\")\n\t}\n\n\tif err = dbCon.Ping(); err != nil {\n\t\tlog.Error(err, \"Unable to access database\")\n\t}\n}", "func Init(config *Config) {\n\tif config != nil {\n\t\tdefaultConfig = config\n\t}\n}", "func init() {\n\tsetUpConfig()\n\tsetUpUsingEnv()\n}", "func init() {\n\tloadTheEnv()\n\tcreateDBInstance()\n\tloadRepDB()\n\tstartKafka()\n}", "func init() {\n\tcfg = pkg.InitializeConfig()\n\t_, err := pkg.InitializeDb()\n\tif err != nil {\n\t\tpanic(\"failed to initialize db connection : \" + err.Error())\n\t}\n}", "func (eng *Engine) Start(b []byte) error {\n\t// read configuration\n\tconfig := Config{}\n\terr := json.Unmarshal(b, &config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfigdata := ConfigData{}\n\terr = json.Unmarshal(b, &configdata)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// get plugins from configuration\n\tauth, err := createAuthentication(config.Authentication.Plugin, configdata.Authentication)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbytestore, err := createByteStore(config.ByteStore.Plugin, configdata.ByteStore)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfilesystem, err := createFileSystem(&bytestore, config.FileSystem.Plugin, configdata.FileSystem)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstatestore, err := createStateStore(config.StateStore.Plugin, configdata.StateStore)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparser, err := createParser(config.Parser.Plugin, configdata.Parser)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// setup engine\n\teng.Authentication = auth\n\teng.ByteStore = bytestore\n\teng.FileSystem = filesystem\n\teng.StateStore = statestore\n\teng.Parser = parser\n\n\treturn nil\n}", "func init() {\n\t// initialize config through viper\n\tcobra.OnInitialize(initConfig)\n\t// Define the flags to be supported.\n\tRootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"config file (default is $HOME/.go-webserver.yaml)\")\n}", "func (m *Manager) init(ledgerIndex iotago.MilestoneIndex) error {\n\tm.currentLock.Lock()\n\tdefer m.currentLock.Unlock()\n\n\tcurrentProtoParams, err := m.storage.ProtocolParameters(ledgerIndex)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm.current = currentProtoParams\n\tm.loadPending(ledgerIndex)\n\n\treturn nil\n}", "func init() {\n\t// bootstrap cosmos-sdk config for kava chain\n\tkavaConfig := sdk.GetConfig()\n\tapp.SetBech32AddressPrefixes(kavaConfig)\n\tapp.SetBip44CoinType(kavaConfig)\n\tkavaConfig.Seal()\n}", "func init() {\n\tcobra.OnInitialize(initConfig)\n\n\t// load the defaults from the default map here, add new defaults on the map\n\tfor key, val := range defaults {\n\t\tviper.SetDefault(key, val)\n\t}\n\n\trootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"config file (default is $HOME/.xendit-account-service.yaml)\")\n}", "func init() {\n\tconfig.URL = os.Getenv(\"RT_URL\")\n\tconfig.Username = os.Getenv(\"RT_USERNAME\")\n\tconfig.Password = os.Getenv(\"RT_PASSWORD\")\n\tconfig.Queue = os.Getenv(\"RT_QUEUE\")\n}", "func init() {\n\tcli.InitConfig(configName)\n}", "func init() {\n\tcli.InitConfig(configName)\n}", "func Init(c *conf.Config, s *service.Service) {\n\trelationSvc = s\n\tverify = v.New(c.Verify)\n\tanti = antispam.New(c.Antispam)\n\taddFollowingRate = rate.New(c.AddFollowingRate)\n\t// init inner router\n\tengine := bm.DefaultServer(c.BM)\n\tsetupInnerEngine(engine)\n\tif err := engine.Start(); err != nil {\n\t\tlog.Error(\"engine.Start() error(%v)\", err)\n\t\tpanic(err)\n\t}\n}", "func init() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\":: \")\n\n\tif XDG_CONFIG_HOME == \"\" {\n\t\tXDG_CONFIG_HOME = filepath.Join(os.Getenv(\"HOME\"), \".config\")\n\t}\n\n\tif XDG_DATA_DIRS == \"\" {\n\t\tXDG_DATA_DIRS = \"/usr/local/share/:/usr/share\"\n\t}\n\n\tcache.actions = make(map[string]string)\n\tcache.actionFiles = make(map[string]string)\n\tcache.scriptFiles = make(map[string]string)\n\n\tconfig = os.Getenv(\"DEMLORC\")\n\tif config == \"\" {\n\t\tconfig = filepath.Join(XDG_CONFIG_HOME, application, application+\"rc\")\n\t}\n}", "func init() {\n\tdebug = config.Bool(\"debug\")\n\tenable = config.Bool(\"redis.enable\")\n\tif !enable {\n\t\tclog.Debugf(\"redis is disabled, skip init redis connection\")\n\t\treturn\n\t}\n\n\tconf := config.StringMap(\"redis\")\n\n\t// 从配置文件获取redis的ip以及db\n\tredisUrl := conf[\"server\"]\n\tpassword := conf[\"auth\"]\n\tredisDb, _ := strconv.Atoi(conf[\"db\"])\n\n\tclog.Printf(\"redis - server=%s db=%d auth=%s\\n\", redisUrl, redisDb, password)\n\n\t// 建立连接池\n\tpool = helper.NewRedisPool(redisUrl, password, redisDb)\n}", "func init() {\n\tInitialize(Config{\n\t\tUseKms: true,\n\t\tSource: Auto,\n\t})\n}", "func init() {\n\tflag.StringVar(&configfile, \"configfile\", \"/data/config/go/best-practices/config.yml\", \"config file full path\")\n\tflag.StringVar(&loggerfile, \"loggerfile\", \"\", \"seelog config file\")\n\tflag.BoolVar(&help, \"h\", false, \"show help\")\n\tflag.IntVar(&port, \"port\", 0, \"service port to listen\")\n\tflag.Parse()\n\n\tif help {\n\t\tflag.Usage()\n\t}\n\t// init logger firstly!!!\n\tmylogger.Init(loggerfile)\n\n\tappConfig.GetConfig(configfile)\n\n\tlogger.Infof(\"Init with config:%+v\", appConfig)\n}", "func (meta *Meta) init() {\n\tmeta.client = utils.CreateMongoDB(dbConfig.Str(\"address\"), log)\n\tmeta.database = meta.client.Database(dbConfig.Str(\"db\"))\n\tmeta.collection = meta.database.Collection(metaCollection)\n}", "func init() {\n\tlog.Info(\"Initializing database\")\n\tpsqlInfo := fmt.Sprintf(\"host=%s port=%s user=%s \"+\n\t\t\"password=%s dbname=%s sslmode=disable\",\n\t\tconfig.Config().GetString(\"database.host\"),\n\t\tconfig.Config().GetString(\"database.port\"),\n\t\tconfig.Config().GetString(\"database.user\"),\n\t\tconfig.Config().GetString(\"database.password\"),\n\t\tconfig.Config().GetString(\"database.name\"))\n\tdb, err := sql.Open(\"postgres\", psqlInfo)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tlog.Info(\"Successfully connected to database!\")\n}", "func (c *Configurations) Init() error {\n\tc.Version = Version\n\tc.Location = \"Local\"\n\tc.Debug = Debug\n\n\t// server\n\tc.Server = &Server{}\n\tc.Server.Init()\n\n\t// redis init\n\tc.RedisConf = &RedisConf{}\n\tc.RedisConf.Init()\n\n\treturn nil\n}", "func init() {\n\tRegisterEngine(EngineTypeHTML, &htmlEngine{})\n}", "func init() {\n\tvar err error\n\n\tnodeUrl, found := os.LookupEnv(EnvNameSerNetworkFullNodes)\n\tif found {\n\t\tblockChainMonitorUrl = strings.Split(nodeUrl, \",\")\n\t}\n\n\tif v, found := os.LookupEnv(EnvNameWorkerNumExecuteTask); found {\n\t\tworkerNumExecuteTask, err = strconv.Atoi(v)\n\t\tif err != nil {\n\t\t\tlogger.Fatal(\"Can't convert str to int\", logger.String(EnvNameWorkerNumExecuteTask, v))\n\t\t}\n\t}\n\n\tif v, found := os.LookupEnv(EnvNameWorkerMaxSleepTime); found {\n\t\tworkerMaxSleepTime, err = strconv.Atoi(v)\n\t\tif err != nil {\n\t\t\tlogger.Fatal(\"Can't convert str to int\", logger.String(EnvNameWorkerMaxSleepTime, v))\n\t\t}\n\t}\n\tif v, ok := os.LookupEnv(EnvNameBech32ChainPrefix); ok {\n\t\tbech32ChainPrefix = v\n\t}\n\tif v, found := os.LookupEnv(EnvNameBlockNumPerWorkerHandle); found {\n\t\tblockNumPerWorkerHandle, err = strconv.Atoi(v)\n\t\tif err != nil {\n\t\t\tlogger.Fatal(\"Can't convert str to int\", logger.String(EnvNameBlockNumPerWorkerHandle, v))\n\t\t}\n\t}\n\tif v, ok := os.LookupEnv(EnvNameBehindBlockNum); ok {\n\t\tif n, err := strconv.Atoi(v); err != nil {\n\t\t\tlogger.Fatal(\"convert str to int fail\", logger.String(EnvNameBehindBlockNum, v))\n\t\t} else {\n\t\t\tbehindBlockNum = n\n\t\t}\n\t}\n\tif v, ok := os.LookupEnv(EnvNamePromethousPort); ok {\n\t\tif n, err := strconv.Atoi(v); err != nil {\n\t\t\tlogger.Fatal(\"convert str to int fail\", logger.String(EnvNamePromethousPort, v))\n\t\t} else {\n\t\t\tpromethousPort = n\n\t\t}\n\t}\n\tSvrConf = &ServerConf{\n\t\tNodeUrls: blockChainMonitorUrl,\n\t\tWorkerNumCreateTask: workerNumCreateTask,\n\t\tWorkerNumExecuteTask: workerNumExecuteTask,\n\t\tWorkerMaxSleepTime: workerMaxSleepTime,\n\t\tBlockNumPerWorkerHandle: blockNumPerWorkerHandle,\n\n\t\tMaxConnectionNum: maxConnectionNum,\n\t\tInitConnectionNum: initConnectionNum,\n\t\tBehindBlockNum: behindBlockNum,\n\t\tBech32ChainPrefix: bech32ChainPrefix,\n\t\tPromethousPort: promethousPort,\n\t}\n\tlogger.Debug(\"print server config\", logger.String(\"serverConf\", utils.MarshalJsonIgnoreErr(SvrConf)))\n}", "func (d *deviceCommon) init(instance InstanceIdentifier, state *state.State, name string, conf config.Device, volatileGet VolatileGetter, volatileSet VolatileSetter) {\n\td.instance = instance\n\td.name = name\n\td.config = conf\n\td.state = state\n\td.volatileGet = volatileGet\n\td.volatileSet = volatileSet\n}", "func init() {\n\tcobra.OnInitialize(mainconfig.ConfigInit)\n\n\trootCmd.PersistentFlags().BoolP(\"debug\", \"d\", false, \"Debug output\")\n\t_ = viper.BindPFlag(\"debug\", rootCmd.PersistentFlags().Lookup(\"debug\"))\n\t_ = viper.BindEnv(\"debug\", \"DEBUG\")\n\n\trootCmd.PersistentFlags().StringP(\"token\", \"t\", \"\", \"Connect Token\")\n\trootCmd.PersistentFlags().String(\"host\", \"\", \"Connect Host\")\n\n\t_ = viper.BindPFlag(\"test.token\", rootCmd.PersistentFlags().Lookup(\"token\"))\n\t_ = viper.BindPFlag(\"test.host\", rootCmd.PersistentFlags().Lookup(\"host\"))\n\t_ = viper.BindEnv(\"test.token\", \"OP_TOKEN\")\n\t_ = viper.BindEnv(\"test.host\", \"OP_HOST\")\n}", "func Initialize(cfg Config) {\n\tvar err error\n\tif cfg.UseKms {\n\t\t// FIXME(xnum): set at cmd.\n\t\tif utils.FullnodeCluster != utils.Environment() {\n\t\t\tif err = initKmsClient(); err != nil {\n\t\t\t\tpanic(err.Error())\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch cfg.Source {\n\tcase None:\n\t\tgetters = []Getter{noneGetter}\n\tcase K8S:\n\t\tgetters = []Getter{k8sGetter}\n\tcase File:\n\t\tgetters = []Getter{staticGetter}\n\t\tif err = initDataFromFile(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t// FIXME(xnum): not encourge to use. It depends on env.\n\tcase Auto:\n\t\tif utils.Environment() == utils.LocalDevelopment ||\n\t\t\tutils.Environment() == utils.CI {\n\t\t\tgetters = []Getter{staticGetter}\n\t\t\terr := initDataFromFile()\n\t\t\tif err != nil {\n\t\t\t\tlog.Panicln(err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tgetters = []Getter{k8sGetter}\n\t}\n}", "func (e *SqliteEndorsementStore) Init(args common.EndorsementStoreParams) error {\n\tdbPath := retrieveDbPath(args)\n\tif dbPath == \"\" {\n\t\treturn fmt.Errorf(\"dbPath not specified inside FetcherParams\")\n\t}\n\tdbConfig := fmt.Sprintf(\"file:%s?cache=shared\", dbPath)\n\tdb, err := sql.Open(\"sqlite3\", dbConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te.db = db\n\te.path = dbPath\n\n\te.Queries = map[string]common.Query{\n\t\t\"hardware_id\": e.GetHardwareID,\n\t\t\"software_components\": e.GetSoftwareComponents,\n\t}\n\n\te.Adders = map[string]common.QueryAdder{\n\t\t\"hardware_id\": e.AddHardwareID,\n\t\t\"software_components\": e.AddSoftwareComponents,\n\t}\n\n\treturn nil\n}", "func init() {\n\tgoPaths := strings.Split(filepath.Join(os.Getenv(\"GOPATH\"), \"src/github.com/databrary/databrary-backend-go/\"), \":\")\n\t// if there's a vendor directory then there will be two gopaths (that's how vendoring works). we want the second one\n\t// which is the actual gopath\n\tif len(goPaths) == 2 {\n\t\tprojRoot = goPaths[1]\n\t} else if len(goPaths) == 1 {\n\t\tprojRoot = goPaths[0]\n\t} else {\n\t\tpanic(fmt.Sprintf(\"unexpected gopath %#v\", goPaths))\n\t}\n\n\tconfigPath = kingpin.Flag(\"config\", \"Path to config file\").\n\t\tDefault(filepath.Join(projRoot, \"config/databrary_dev.toml\")).\n\t\tShort('c').\n\t\tString()\n\n\t// parse command line flags\n\tkingpin.Version(\"0.0.0\")\n\tkingpin.Parse()\n\n\tif configPath, err := filepath.Abs(*configPath); err != nil {\n\t\tpanic(\"command line config file path error\")\n\t} else {\n\t\tlog.InitLgr(config.InitConf(configPath))\n\t}\n\n\t// initialize db connection\n\terr := db.InitDB(config.GetConf())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\t// initialize redis connection\n\tredis.InitRedisStore(config.GetConf())\n\n\tif config.GetConf().GetString(\"log.level\") == \"DEBUG\" {\n\t\t// print to stdout the sql generated by sqlboiler\n\t\tboil.DebugMode = true\n\t}\n}", "func init() {\n\tinitTokens()\n\tvar err error\n\tLexer, err = initLexer()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func Init(cfg Configuration, db Database) {\n\tconfig = cfg\n\tdatabase = db\n\truns.Load(database)\n}", "func (hem *GW) Init(rootURL string, username string, password string) {\n\them.rootURL = rootURL\n\them.username = username\n\them.password = password\n\them.loadSmartMeterAttribute()\n}", "func Init(c common.AresServerConfig, l common.Logger, ql common.Logger, s tally.Scope) {\n\tconfig = c\n\tlogger = l\n\tqueryLogger = ql\n\treporterFactory = NewReporterFactory(s)\n}", "func (g *Generator) init() {\n\tg.filedInit = []string{}\n\tg.imports = map[string]bool{}\n\tg.pooledObjects = map[string]string{}\n\tg.structTypes = map[string]string{}\n\tg.sliceTypes = map[string]string{}\n\tg.poolInit = map[string]string{}\n\tg.addImport(gojayPackage)\n\t// if we want pools, add the sync package right away\n\tif g.options.PoolObjects {\n\t\tg.addImport(\"sync\")\n\t}\n}", "func (s *Service) init() {\n\tif s.hasInit {\n\t\treturn\n\t}\n\ts.hasInit = true\n\ts.usageErrors = make(map[string][]string)\n\tif s.fs == nil {\n\t\ts.fs = flag.CommandLine\n\t}\n\ts.es = fenv.NewEnvSet(s.fs, fenv.Prefix(\"plugin_\"))\n\tif s.envFunc == nil {\n\t\ts.envFunc = fenv.OSEnv\n\t}\n\tif s.log == nil {\n\t\ts.log = &Logger{}\n\t}\n\ts.log.s = s\n\n}", "func init() {\n\n\tcobra.OnInitialize(func() {\n\t\tconfig.Initialize(rootCmd)\n\t})\n\n\tconfig.InitializeFlags(rootCmd)\n}", "func Init(c *conf.Config) {\n\tinitService(c)\n\t// init inner router\n\tengine := bm.DefaultServer(c.HTTPServer)\n\tinnerRouter(engine)\n\t// init inner server\n\tif err := engine.Start(); err != nil {\n\t\tlog.Error(\"engine.Start error(%v)\", err)\n\t\tpanic(err)\n\t}\n}", "func (s *Server) init(renew bool) (err error) {\n\ts.Config.Operations.Metrics = s.Config.Metrics\n\ts.Operations = operations.NewSystem(s.Config.Operations)\n\ts.initMetrics()\n\n\tserverVersion := metadata.GetVersion()\n\terr = calog.SetLogLevel(s.Config.LogLevel, s.Config.Debug)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Infof(\"Server Version: %s\", serverVersion)\n\ts.levels, err = metadata.GetLevels(serverVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Infof(\"Server Levels: %+v\", s.levels)\n\n\ts.mux = gmux.NewRouter()\n\t// Initialize the config\n\terr = s.initConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Initialize the default CA last\n\terr = s.initDefaultCA(renew)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Successful initialization\n\treturn nil\n}", "func init() {\n\tflag.StringVar(&cfg.tzlib, \"tzlib\", \"./tzlib.json\", \"Use database file <tzlib>\")\n\tflag.StringVar(&cfg.from, \"from\", \"\", \"Import HTML from <from> and write database to <zlib>\")\n\tflag.StringVar(&cfg.webroot, \"webroot\", \"\", \"Serve the <webroot> directory at '/'\")\n\tflag.StringVar(&cfg.endpoint, \"endpoint\", \"/dann\", \"Serve the API at <endpoint>\")\n\tflag.StringVar(&cfg.bind, \"bind\", \"localhost:1620\", \"Listen on <bind> for connections. \")\n\n\tflag.Parse()\n}", "func init() {\n\tenv = flag.String(\"env\", \"development\", \"current environment\")\n\tport = flag.Int(\"port\", 3000, \"port number\")\n}", "func init() {\n\t// Here you will define your flags and configuration settings.\n\t// Cobra supports persistent flags, which, if defined here,\n\t// will be global for your application.\n\trootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"config file (default is hub3.toml)\")\n}", "func Init(opts storage.Options) (storage.Engine, error) {\n\te := Engine{\n\t\tparts: make(map[string]map[string][]byte),\n\t}\n\n\treturn &e, nil\n}", "func init() {\n\tlogger = config.Initlog()\n}", "func Init(config *config.Registry) {\n\tcfg = config\n}", "func (s *GCPCKMSSeal) Init(_ context.Context) error {\n\treturn nil\n}", "func (agent *Agent) init(state_size int, action_size int, dqn bool) Agent {\n\tagent.learning_rate = 0.95\n\tagent.action_size = action_size\n\tagent.state_size = state_size\n\tagent.epsilon = 1.0\n\tagent.epsilon_min = 0.01\n\tagent.epsilon_decay = 0.995\n\tagent.gamma = 0.95\n\tagent.HISTORY_LENGTH = 2000\n\tagent.memory = make([]history, agent.HISTORY_LENGTH)\n\tagent.model = *neural.NewNetwork(state_size, []int{state_size, state_size, action_size})\n\tagent.model.RandomizeSynapses()\n\tagent.target_model = *neural.NewNetwork(state_size, []int{state_size, state_size, action_size})\n\tagent.target_model.RandomizeSynapses()\n\tagent.DQN = dqn\n\n\treturn *agent\n}", "func init() {\n\tlog = config.Logger()\n}", "func init() {\n\tlog = config.Logger()\n}", "func (p *AbstractRunProvider) Init() error {\n\treturn nil\n}", "func init() {\n\tResetDefaults()\n}", "func (b *base) init(services []Service) (err error) {\n\tif err = b.initConfig(); err != nil {\n\t\treturn\n\t}\n\tif err = b.initNewrelic(); err != nil {\n\t\treturn\n\t}\n\tif err = b.initSentry(); err != nil {\n\t\treturn\n\t}\n\tb.initLogger()\n\tb.initDriver()\n\tb.initRouter(services)\n\treturn\n}", "func init() {\n\tdefaultClient = New(\"\")\n}", "func init() {\r\n// get the arguments to run the server\r\n\tflag.StringVar(&Host,\"httpserver\",DEFAULT_HOST,\"name of HTTP server\")\r\n\tflag.IntVar(&Port,\"port\",DEFAULT_PORT,\"port number\")\r\n\tflag.StringVar(&UrlPath,\"urlpath\",DEFAULT_URLPATH,\"relative url path\")\r\n\tflag.StringVar(&SecretKey,\"key\",DEFAULT_KEY,\"secret key to terminate program via TCP/UDP port\")\r\n\tflag.BoolVar(&isVerbose,\"verbose\",false,\"enable verbose logging output\")\r\n\tflag.Parse()\r\n\tlogger.Print(\"Starting servers on Port:\"+strconv.Itoa(Port)+\" HTTP-server:\"+Host+\" urlpath:\"+UrlPath+\" Key:\"+SecretKey)\r\n\tinitConf()\r\n}", "func (rnr *Runner) Init(c configurer.Configurer, l logger.Logger, s storer.Storer) error {\n\n\trnr.Log = l\n\tif rnr.Log == nil {\n\t\tmsg := \"Logger undefined, cannot init runner\"\n\t\treturn fmt.Errorf(msg)\n\t}\n\n\trnr.Log.Debug(\"** Initialise **\")\n\n\trnr.Config = c\n\tif rnr.Config == nil {\n\t\tmsg := \"Configurer undefined, cannot init runner\"\n\t\trnr.Log.Warn(msg)\n\t\treturn fmt.Errorf(msg)\n\t}\n\n\trnr.Store = s\n\tif rnr.Store == nil {\n\t\tmsg := \"Storer undefined, cannot init runner\"\n\t\trnr.Log.Warn(msg)\n\t\treturn fmt.Errorf(msg)\n\t}\n\n\t// Initialise storer\n\terr := rnr.Store.Init()\n\tif err != nil {\n\t\trnr.Log.Warn(\"Failed store init >%v<\", err)\n\t\treturn err\n\t}\n\n\t// Preparer\n\tif rnr.PreparerFunc == nil {\n\t\trnr.PreparerFunc = rnr.Preparer\n\t}\n\n\tp, err := rnr.PreparerFunc(l)\n\tif err != nil {\n\t\trnr.Log.Warn(\"Failed preparer func >%v<\", err)\n\t\treturn err\n\t}\n\n\trnr.Prepare = p\n\tif rnr.Prepare == nil {\n\t\trnr.Log.Warn(\"Preparer is nil, cannot continue\")\n\t\treturn err\n\t}\n\n\t// run server\n\tif rnr.RunHTTPFunc == nil {\n\t\trnr.RunHTTPFunc = rnr.RunHTTP\n\t}\n\n\t// run daemon\n\tif rnr.RunDaemonFunc == nil {\n\t\trnr.RunDaemonFunc = rnr.RunDaemon\n\t}\n\n\t// prepare\n\tif rnr.PreparerFunc == nil {\n\t\trnr.PreparerFunc = rnr.Preparer\n\t}\n\n\t// model\n\tif rnr.ModellerFunc == nil {\n\t\trnr.ModellerFunc = rnr.Modeller\n\t}\n\n\t// http server - router\n\tif rnr.RouterFunc == nil {\n\t\trnr.RouterFunc = rnr.Router\n\t}\n\n\t// http server - middleware\n\tif rnr.MiddlewareFunc == nil {\n\t\trnr.MiddlewareFunc = rnr.Middleware\n\t}\n\n\t// http server - handler\n\tif rnr.HandlerFunc == nil {\n\t\trnr.HandlerFunc = rnr.Handler\n\t}\n\n\treturn nil\n}" ]
[ "0.7221774", "0.66383153", "0.6604026", "0.6536726", "0.6430138", "0.6430138", "0.62999934", "0.62854785", "0.62300193", "0.62171", "0.62102425", "0.61965305", "0.6160467", "0.6122625", "0.61147517", "0.6108825", "0.6103406", "0.6101473", "0.60721517", "0.6070308", "0.60612386", "0.6033422", "0.602671", "0.6023647", "0.60021776", "0.5993558", "0.59549737", "0.59492123", "0.5920719", "0.5881989", "0.58709985", "0.58698356", "0.5862", "0.586145", "0.586145", "0.586145", "0.586145", "0.586145", "0.586145", "0.5840091", "0.58306235", "0.5827836", "0.5825415", "0.5818685", "0.58105254", "0.5798347", "0.5788284", "0.57678235", "0.5758466", "0.5756885", "0.57488364", "0.5747973", "0.57439023", "0.5743151", "0.57286745", "0.5726511", "0.5726158", "0.5725266", "0.5725216", "0.5725216", "0.57219833", "0.5719066", "0.5716187", "0.5713959", "0.5711027", "0.57054985", "0.5703351", "0.5702802", "0.57009596", "0.57008547", "0.56957525", "0.56948954", "0.5689112", "0.56855315", "0.5679077", "0.5678711", "0.5674177", "0.56722784", "0.56693876", "0.5668495", "0.56660503", "0.56626403", "0.5660051", "0.564823", "0.56325275", "0.5614489", "0.5611318", "0.5607788", "0.5604217", "0.5601108", "0.5598088", "0.55977476", "0.5588937", "0.5588937", "0.5583721", "0.55736244", "0.5568726", "0.55685985", "0.5562128", "0.55617654" ]
0.6992129
1
Start will launch the engine and start registered hooks. It will block until every hooks has shutdown, gracefully or with force...
func (e *Engine) Start() error { e.init() go e.waitShutdownNotification() for _, h := range e.hooks { e.launch(h) } e.wait.Wait() if e.afterShutdown != nil { e.afterShutdown() } e.mutex.Lock() defer e.mutex.Unlock() return e.cause }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (e *EngineConfig) Start() error {\n\tlogger.Info(\"Engine: Starting...\")\n\n\t// Todo document RunnerType for engine configuration\n\trunnerType := config.GetRunnerType()\n\te.Init(runnerType == \"DIRECT\")\n\n\tactionRunner := e.actionRunner.(interface{})\n\n\tif managedRunner, ok := actionRunner.(util.Managed); ok {\n\t\tutil.StartManaged(\"ActionRunner Service\", managedRunner)\n\t}\n\n\tlogger.Info(\"Engine: Starting Services...\")\n\n\terr := e.serviceManager.Start()\n\n\tif err != nil {\n\t\tlogger.Error(\"Engine: Error Starting Services - \" + err.Error())\n\t} else {\n\t\tlogger.Info(\"Engine: Started Services\")\n\t}\n\n\t// Start the triggers\n\tfor key, value := range e.triggers {\n\t\terr := util.StartManaged(fmt.Sprintf(\"Trigger [ '%s' ]\", key), value.Interf)\n\t\tif err != nil {\n\t\t\tlogger.Infof(\"Trigger [%s] failed to start due to error [%s]\", key, err.Error())\n\t\t\tvalue.Status = trigger.Failed\n\t\t\tvalue.Error = err\n\t\t\tlogger.Debugf(\"StackTrace: %s\", debug.Stack())\n\t\t\tif config.StopEngineOnError() {\n\t\t\t\tlogger.Debugf(\"{%s=true}. Stopping engine\", config.STOP_ENGINE_ON_ERROR_KEY)\n\t\t\t\tlogger.Info(\"Engine: Stopped\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.Infof(\"Trigger [%s] started\", key)\n\t\t\tvalue.Status = trigger.Started\n\t\t}\n\t}\n\n\tlogger.Info(\"Engine: Started\")\n\treturn nil\n}", "func (e *Engine) Start() error {\n\tpref, err := prefs.NewPreferences()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot load preferences\")\n\t}\n\n\tif pref.Core.EnableCheckUpdates {\n\t\tgo e.start()\n\t}\n\n\treturn nil\n}", "func (e *Engine) Start(ctx context.Context) {\n\terr := e.processBets(ctx)\n\tif err != nil {\n\t\tlog.Println(\"Engine failed to process bets received:\", err)\n\t\treturn\n\t}\n\n\terr = e.processEventsSettled(ctx)\n\tif err != nil {\n\t\tlog.Println(\"Engine failed to process bets calculated:\", err)\n\t\treturn\n\t}\n\n\t<-ctx.Done()\n}", "func (l *Lifecycle) Start(ctx context.Context) error {\n\tl.mu.Lock()\n\tl.startRecords = make(HookRecords, 0, len(l.hooks))\n\tl.mu.Unlock()\n\n\tfor _, hook := range l.hooks {\n\t\tif hook.OnStart != nil {\n\t\t\tl.mu.Lock()\n\t\t\tl.runningHook = hook\n\t\t\tl.mu.Unlock()\n\n\t\t\truntime, err := l.runStartHook(ctx, hook)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tl.mu.Lock()\n\t\t\tl.startRecords = append(l.startRecords, HookRecord{\n\t\t\t\tCallerFrame: hook.callerFrame,\n\t\t\t\tFunc: hook.OnStart,\n\t\t\t\tRuntime: runtime,\n\t\t\t})\n\t\t\tl.mu.Unlock()\n\t\t}\n\t\tl.numStarted++\n\t}\n\n\treturn nil\n}", "func (el *Launcher) Start() error {\n\tlogrus.Debugf(\"engine launcher %v: prepare to start engine %v at %v\",\n\t\tel.LauncherName, el.currentEngine.EngineName, el.currentEngine.GetListen())\n\n\tif err := el.currentEngine.Start(); err != nil {\n\t\treturn err\n\t}\n\n\tel.updateCh <- el\n\n\tlogrus.Debugf(\"engine launcher %v: succeed to start engine %v at %v\",\n\t\tel.LauncherName, el.currentEngine.EngineName, el.currentEngine.GetListen())\n\n\treturn nil\n}", "func (m *Manager) Start(ctx context.Context) error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\terr := storage.Txn(ctx, m.Store, storage.TransactionParams{}, func(txn storage.Transaction) error {\n\t\tcompiler, err := loadCompilerFromStore(ctx, m.Store, txn)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tm.setCompiler(compiler)\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := func() error {\n\t\tm.mtx.Lock()\n\t\tdefer m.mtx.Unlock()\n\n\t\tfor _, p := range m.plugins {\n\t\t\tif err := p.plugin.Start(ctx); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}(); err != nil {\n\t\treturn err\n\t}\n\n\tconfig := storage.TriggerConfig{OnCommit: m.onCommit}\n\n\treturn storage.Txn(ctx, m.Store, storage.WriteParams, func(txn storage.Transaction) error {\n\t\t_, err := m.Store.Register(ctx, txn, config)\n\t\treturn err\n\t})\n}", "func (a *Application) Start(ctx context.Context) (<-chan interface{}, error) {\n\tif timeout, ok := ctx.Deadline(); ok {\n\t\tlevel.Debug(a.logger).Log(\n\t\t\t\"msg\", \"starting up with timeout\",\n\t\t\t\"timeout\", math.Floor(timeout.Sub(time.Now()).Seconds()),\n\t\t)\n\t}\n\n\tdone := make(chan interface{}, len(a.lifecycle.hooks))\n\n\tfor _, hook := range a.lifecycle.hooks {\n\t\terr := invokeHook(hook.PreStart)\n\t\tif err != nil {\n\t\t\treturn done, err\n\t\t}\n\t}\n\n\tfor _, hook := range a.lifecycle.hooks {\n\t\tif hook.OnStart != nil {\n\t\t\terr := hook.OnStart(ctx, done)\n\t\t\tif err != nil {\n\t\t\t\treturn done, err\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, hook := range a.lifecycle.hooks {\n\t\terr := invokeHook(hook.PostStart)\n\t\tif err != nil {\n\t\t\treturn done, err\n\t\t}\n\t}\n\n\treturn done, nil\n}", "func (e *engine) Start(context.Context, *Spec, *Step) error {\n\treturn nil // no-op for bash implementation\n}", "func Start(c context.Context) (*Dispatcher) {\n\t// create the dispatcher\n\tdispatcher := Dispatcher{\n\t\tChannel: GetEventChannel(),\n\t}\n\n\t// preload the controllers\n\tcontroller.GetController(\"default\")\n\n\t// start the dispatcher\n\tgo dispatcher.Run(c)\n\n\tutil.LogInfo(\"main\", \"ENG\", \"engine active\")\n\n\treturn &dispatcher\n}", "func (o *FakeObjectTrackers) Start() {\n\tgo func() {\n\t\terr := o.ControlMachine.Start()\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"failed to start machine object tracker, Err: %v\", err)\n\t\t}\n\t}()\n\n\tgo func() {\n\t\terr := o.TargetCore.Start()\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"failed to start target core object tracker, Err: %v\", err)\n\t\t}\n\t}()\n}", "func (e *Engine) Start() error {\n\n\twgIface := e.config.WgIface\n\twgAddr := e.config.WgAddr\n\tmyPrivateKey := e.config.WgPrivateKey\n\n\terr := iface.Create(wgIface, wgAddr)\n\tif err != nil {\n\t\tlog.Errorf(\"failed creating interface %s: [%s]\", wgIface, err.Error())\n\t\treturn err\n\t}\n\n\terr = iface.Configure(wgIface, myPrivateKey.String())\n\tif err != nil {\n\t\tlog.Errorf(\"failed configuring Wireguard interface [%s]: %s\", wgIface, err.Error())\n\t\treturn err\n\t}\n\n\tport, err := iface.GetListenPort(wgIface)\n\tif err != nil {\n\t\tlog.Errorf(\"failed getting Wireguard listen port [%s]: %s\", wgIface, err.Error())\n\t\treturn err\n\t}\n\te.wgPort = *port\n\n\te.receiveSignalEvents()\n\te.receiveManagementEvents()\n\n\treturn nil\n}", "func (core *coreService) Start(_ context.Context) error {\n\tif err := core.chainListener.Start(); err != nil {\n\t\treturn errors.Wrap(err, \"failed to start blockchain listener\")\n\t}\n\tif core.messageBatcher != nil {\n\t\tif err := core.messageBatcher.Start(); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to start message batcher\")\n\t\t}\n\t}\n\treturn nil\n}", "func (e *Engine) launch(h Hook) {\n\n\te.wait.Add(1)\n\n\tgo func() {\n\n\t\tdefer e.wait.Done()\n\n\t\truntime := &HookRuntime{}\n\n\t\t// Wait for an event to notify this goroutine that a shutdown is required.\n\t\t// It could either be from engine's context or during Hook startup if an error has occurred.\n\t\t// NOTE: If HookRuntime returns an error, we have to shutdown every Hook...\n\t\terr := runtime.WaitForEvent(e.ctx, h)\n\t\tif err != nil {\n\t\t\te.mutex.Lock()\n\t\t\te.log(err)\n\t\t\te.cancel()\n\t\t\te.cause = err\n\t\t\te.mutex.Unlock()\n\t\t}\n\n\t\t// Wait for hook to gracefully shutdown, or kill it after timeout.\n\t\t// This is handled by HookRuntime.\n\t\tfor _, err := range runtime.Shutdown(e.timeout) {\n\t\t\te.mutex.Lock()\n\t\t\te.log(err)\n\t\t\te.mutex.Unlock()\n\t\t}\n\n\t}()\n}", "func Start(context.Context, *Config) ([]*logical.Loop, func(), error) {\n\tpanic(wire.Build(\n\t\twire.Bind(new(logical.Config), new(*Config)),\n\t\tProvideFirestoreClient,\n\t\tProvideLoops,\n\t\tProvideTombstones,\n\t\tlogical.Set,\n\t\tscript.Set,\n\t\tstaging.Set,\n\t\ttarget.Set,\n\t))\n}", "func (s *Server) Start(ctx context.Context) {\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tlogger := log.FromContext(ctx)\n\t\tlogger.Info(\"I have to go...\")\n\t\tlogger.Info(\"Stopping server gracefully\")\n\t\ts.Stop()\n\t}()\n\n\ts.tcpEntryPoints.Start()\n\ts.udpEntryPoints.Start()\n\ts.watcher.Start()\n\n\ts.routinesPool.GoCtx(s.listenSignals)\n}", "func (mgr *Manager) Start(register string) error {\n\terr := mgr.Register(register)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif mgr.tagsMap == nil || mgr.tagsMap[\"pindex\"] {\n\t\tmldd := mgr.options[\"managerLoadDataDir\"]\n\t\tif mldd == \"sync\" || mldd == \"async\" || mldd == \"\" {\n\t\t\terr := mgr.LoadDataDir()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif mgr.tagsMap == nil || mgr.tagsMap[\"planner\"] {\n\t\tgo mgr.PlannerLoop()\n\t\tgo mgr.PlannerKick(\"start\")\n\t}\n\n\tif mgr.tagsMap == nil ||\n\t\t(mgr.tagsMap[\"pindex\"] && mgr.tagsMap[\"janitor\"]) {\n\t\tgo mgr.JanitorLoop()\n\t\tgo mgr.JanitorKick(\"start\")\n\t}\n\n\treturn mgr.StartCfg()\n}", "func (op *AddonOperator) Start() error {\n\tif err := op.bootstrap(); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Info(\"Start first converge for modules\")\n\t// Loading the onStartup hooks into the queue and running all modules.\n\t// Turning tracking changes on only after startup ends.\n\n\t// Bootstrap main queue with tasks to run Startup process.\n\top.BootstrapMainQueue(op.TaskQueues)\n\t// Start main task queue handler\n\top.TaskQueues.StartMain()\n\n\t// Global hooks are registered, initialize their queues.\n\top.CreateAndStartQueuesForGlobalHooks()\n\n\t// ManagerEventsHandler handle events for kubernetes and schedule bindings.\n\t// Start it before start all informers to catch all kubernetes events (#42)\n\top.ManagerEventsHandler.Start()\n\n\t// Enable events from schedule manager.\n\top.ScheduleManager.Start()\n\n\top.KubeConfigManager.Start()\n\top.ModuleManager.Start()\n\top.StartModuleManagerEventHandler()\n\n\treturn nil\n}", "func (lr *LogicRunner) Start(ctx context.Context) error {\n\tlr.ArtifactManager = lr.Ledger.GetArtifactManager()\n\n\tif lr.Cfg.BuiltIn != nil {\n\t\tbi := builtin.NewBuiltIn(lr.MessageBus, lr.ArtifactManager)\n\t\tif err := lr.RegisterExecutor(core.MachineTypeBuiltin, bi); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlr.machinePrefs = append(lr.machinePrefs, core.MachineTypeBuiltin)\n\t}\n\n\tif lr.Cfg.GoPlugin != nil {\n\t\tif lr.Cfg.RPCListen != \"\" {\n\t\t\tStartRPC(ctx, lr)\n\t\t}\n\n\t\tgp, err := goplugin.NewGoPlugin(lr.Cfg, lr.MessageBus, lr.ArtifactManager)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := lr.RegisterExecutor(core.MachineTypeGoPlugin, gp); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlr.machinePrefs = append(lr.machinePrefs, core.MachineTypeGoPlugin)\n\t}\n\n\t// TODO: use separate handlers\n\tif err := lr.MessageBus.Register(core.TypeCallMethod, lr.Execute); err != nil {\n\t\treturn err\n\t}\n\tif err := lr.MessageBus.Register(core.TypeCallConstructor, lr.Execute); err != nil {\n\t\treturn err\n\t}\n\n\tif err := lr.MessageBus.Register(core.TypeExecutorResults, lr.ExecutorResults); err != nil {\n\t\treturn err\n\t}\n\tif err := lr.MessageBus.Register(core.TypeValidateCaseBind, lr.ValidateCaseBind); err != nil {\n\t\treturn err\n\t}\n\tif err := lr.MessageBus.Register(core.TypeValidationResults, lr.ProcessValidationResults); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (_m *MockHistoryEngine) Start() {\n\t_m.Called()\n}", "func (s *Service) Start(sc service.Context) error {\n\ts.sc = sc\n\n\ts.routines.Add(1)\n\tgo s.executionManagerLoop()\n\n\treturn nil\n}", "func Start(ctx context.Context, config *Config) error {\n\tlog.Debug(\"start application\")\n\n\tserviceRepo := service.NewRepository()\n\n\tserviceConfig := service.Config{\n\t\tNoTrackMode: config.NoTrackMode,\n\t\tConnDefaults: config.Defaults,\n\t\tConnsSettings: config.ServicesConnsSettings,\n\t\tDatabasesRE: config.DatabasesRE,\n\t\tDisabledCollectors: config.DisableCollectors,\n\t\tCollectorsSettings: config.CollectorsSettings,\n\t}\n\n\tvar wg sync.WaitGroup\n\tctx, cancel := context.WithCancel(ctx)\n\n\tif config.ServicesConnsSettings == nil || len(config.ServicesConnsSettings) == 0 {\n\t\t// run background discovery, the service repo will be fulfilled at first iteration\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tserviceRepo.StartBackgroundDiscovery(ctx, serviceConfig)\n\t\t\twg.Done()\n\t\t}()\n\t} else {\n\t\t// fulfill service repo using passed services\n\t\tserviceRepo.AddServicesFromConfig(serviceConfig)\n\n\t\t// setup exporters for all services\n\t\terr := serviceRepo.SetupServices(serviceConfig)\n\t\tif err != nil {\n\t\t\tcancel()\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Start auto-update loop if it is enabled.\n\tif config.AutoUpdate != \"off\" {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tac := &autoupdate.Config{\n\t\t\t\tBinaryPath: config.BinaryPath,\n\t\t\t\tBinaryVersion: config.BinaryVersion,\n\t\t\t\tUpdatePolicy: config.AutoUpdate,\n\t\t\t}\n\t\t\tautoupdate.StartAutoupdateLoop(ctx, ac)\n\t\t\twg.Done()\n\t\t}()\n\t}\n\n\terrCh := make(chan error)\n\tdefer close(errCh)\n\n\t// Start HTTP metrics listener.\n\twg.Add(1)\n\tgo func() {\n\t\tif err := runMetricsListener(ctx, config); err != nil {\n\t\t\terrCh <- err\n\t\t}\n\t\twg.Done()\n\t}()\n\n\t// Start metrics sender if necessary.\n\tif config.SendMetricsURL != \"\" {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tif err := runSendMetricsLoop(ctx, config, serviceRepo); err != nil {\n\t\t\t\terrCh <- err\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t}\n\n\t// Waiting for errors or context cancelling.\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tlog.Info(\"exit signaled, stop application\")\n\t\t\tcancel()\n\t\t\twg.Wait()\n\t\t\treturn nil\n\t\tcase err := <-errCh:\n\t\t\tcancel()\n\t\t\twg.Wait()\n\t\t\treturn err\n\t\t}\n\t}\n}", "func Start(ctx context.Context, config *Config) error {\n\tlog.Debug(\"start application\")\n\n\tserviceRepo := service.NewRepository()\n\n\tserviceConfig := service.Config{\n\t\tNoTrackMode: config.NoTrackMode,\n\t\tConnDefaults: config.Defaults,\n\t\tConnsSettings: config.ServicesConnsSettings,\n\t\tDatabasesRE: config.DatabasesRE,\n\t\tDisabledCollectors: config.DisableCollectors,\n\t\tCollectorsSettings: config.CollectorsSettings,\n\t}\n\n\tvar wg sync.WaitGroup\n\tctx, cancel := context.WithCancel(ctx)\n\n\tif config.ServicesConnsSettings == nil {\n\t\t// run background discovery, the service repo will be fulfilled at first iteration\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tserviceRepo.StartBackgroundDiscovery(ctx, serviceConfig)\n\t\t\twg.Done()\n\t\t}()\n\t} else {\n\t\t// fulfill service repo using passed services\n\t\tserviceRepo.AddServicesFromConfig(serviceConfig)\n\n\t\t// setup exporters for all services\n\t\terr := serviceRepo.SetupServices(serviceConfig)\n\t\tif err != nil {\n\t\t\tcancel()\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Start auto-update loop if it is enabled.\n\tif config.AutoUpdate != \"off\" {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tac := &autoupdate.Config{\n\t\t\t\tBinaryPath: config.BinaryPath,\n\t\t\t\tBinaryVersion: config.BinaryVersion,\n\t\t\t\tUpdatePolicy: config.AutoUpdate,\n\t\t\t}\n\t\t\tautoupdate.StartAutoupdateLoop(ctx, ac)\n\t\t\twg.Done()\n\t\t}()\n\t}\n\n\terrCh := make(chan error)\n\tdefer close(errCh)\n\n\t// Start HTTP metrics listener.\n\twg.Add(1)\n\tgo func() {\n\t\tif err := runMetricsListener(ctx, config); err != nil {\n\t\t\terrCh <- err\n\t\t}\n\t\twg.Done()\n\t}()\n\n\t// Start metrics sender if necessary.\n\tif config.SendMetricsURL != \"\" {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tif err := runSendMetricsLoop(ctx, config, serviceRepo); err != nil {\n\t\t\t\terrCh <- err\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t}\n\n\t// Waiting for errors or context cancelling.\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tlog.Info(\"exit signaled, stop application\")\n\t\t\tcancel()\n\t\t\twg.Wait()\n\t\t\treturn nil\n\t\tcase err := <-errCh:\n\t\t\tcancel()\n\t\t\twg.Wait()\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (e *Engine) Start(ctx context.Context) {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := <-e.inEvents:\n\t\t\t\tif ok {\n\t\t\t\t\te.processEvent(event)\n\t\t\t\t}\n\t\t\tcase <-ctx.Done():\n\t\t\t\tlog.Infoln(\"received done, exiting\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}", "func (s *LocalService) Start() error {\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, route := range s.routes {\n\t\tpath := filepath.Join(s.chroot, route.Username)\n\t\tif err := watcher.Add(path); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ts.watcher = watcher\n\n\tgo s.watch()\n\n\treturn nil\n}", "func (bot *Bot) Start() (err error) {\n\tif bot.opts.Webhook != nil {\n\t\treturn bot.startWebhook()\n\t}\n\treturn nil\n}", "func (p *Init) Start(ctx context.Context) error {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\treturn p.initState.Start(ctx)\n}", "func (a App) Start() error {\n\tgo a.checkerLoop()\n\treturn nil\n}", "func (c *Concentrator) Start() {\n\tc.exitWG.Add(1)\n\tgo func() {\n\t\tdefer watchdog.LogOnPanic()\n\t\tdefer c.exitWG.Done()\n\t\tc.Run()\n\t}()\n}", "func (s *Server) Start() {\n\tlog.Print(\"starting Mock Webhook server\")\n\ts.server.Start()\n}", "func Start(config *Config, placesStore places.PlacesStoreClient, templatesStorage *templates.Storage) error {\n\tif config == nil {\n\t\treturn fmt.Errorf(\"bot config is nil\")\n\t}\n\n\tdialogs, err := vkdialogs.LoadFromFile(config.DialogsPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not load vk dialogs: %v\", err)\n\t}\n\n\tbot := newWebhookBot(\n\t\tconfig.GroupID,\n\t\tconfig.Confirmation,\n\t\tvkapi.NewClient(config.Token),\n\t\tplacesStore,\n\t\tdialogs,\n\t\ttemplatesStorage,\n\t)\n\n\treturn http.ListenAndServe(config.Host, bot)\n}", "func (srv *Server) Start() {\n\tvar config *rest.Config\n\tvar err error\n\n\tif strings.ToUpper(srv.RunMode) == \"KUBE\" {\n\t\t// Create the Kubernetes in-cluster config\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t} else {\n\t\t// use the current context in kubeconfig\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", filepath.Join(util.HomeDir(), \".kube\", \"config\"))\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t}\n\n\t// Create the clientset\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\t// Create a watcher\n\twatcher, err := clientset.CoreV1().Services(\"\").Watch(metav1.ListOptions{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\t// Create a channel for the events to come in from the watcher\n\teventChannel := watcher.ResultChan()\n\n\t// Start an indefinite loop\n\tfor {\n\t\tevt := <-eventChannel\n\t\tsrv.handleEvent(evt)\n\t}\n}", "func Start(ctx context.Context, configFile string) (done chan struct{}) {\n\tdone = make(chan struct{})\n\n\tgo func() {\n\t\tdefer close(done)\n\n\t\tl := zerolog.New(os.Stdout)\n\n\t\terr := runApp(ctx, l, configFile)\n\t\tif err != nil {\n\t\t\tl.Fatal().Err(err).Msg(\"running app\")\n\t\t}\n\t}()\n\n\treturn done\n}", "func Start() {\n\tconfig, err := parseConfig()\n\tif err != nil {\n\t\t_, _ = fmt.Fprintln(os.Stderr, err)\n\n\t\tflag.PrintDefaults()\n\t\tos.Exit(1)\n\t}\n\n\tvos.LoadUserEnv()\n\n\t// stop exist servers first\n\tStopLogtail()\n\n\tgo StartLogtail(config)\n\n\tgo func() {\n\t\tif err := http.ListenAndServe(fmt.Sprintf(\":%d\", config.Port), &httpHandler{}); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\thandleSignal()\n}", "func (s *Server) OnStart(ctx context.Context) error { s.run(ctx); return nil }", "func (service *Service) Start(ctx context.Context, initFn func() error) {\n\thandleErr(service.openSQLDBConnections(ctx))\n\thandleErr(service.openRedisConnections(ctx))\n\thandleErr(service.openExternalConnections(ctx))\n\thandleErr(service.initGRPC(ctx))\n\thandleErr(initFn())\n\thandleErr(service.run(ctx))\n}", "func (eng *Engine) Start(b []byte) error {\n\t// read configuration\n\tconfig := Config{}\n\terr := json.Unmarshal(b, &config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfigdata := ConfigData{}\n\terr = json.Unmarshal(b, &configdata)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// get plugins from configuration\n\tauth, err := createAuthentication(config.Authentication.Plugin, configdata.Authentication)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbytestore, err := createByteStore(config.ByteStore.Plugin, configdata.ByteStore)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfilesystem, err := createFileSystem(&bytestore, config.FileSystem.Plugin, configdata.FileSystem)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstatestore, err := createStateStore(config.StateStore.Plugin, configdata.StateStore)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparser, err := createParser(config.Parser.Plugin, configdata.Parser)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// setup engine\n\teng.Authentication = auth\n\teng.ByteStore = bytestore\n\teng.FileSystem = filesystem\n\teng.StateStore = statestore\n\teng.Parser = parser\n\n\treturn nil\n}", "func Start() {\n\t// initialize the global DB connection\n\tinitPwmDb()\n\n\tfmt.Println(\"Starting pwm local API\")\n\tpwmapi.Start()\n}", "func (s *Session) Start(ctx context.Context) {\n\ts.done = make(chan interface{})\n\n\twgBackend := sync.WaitGroup{}\n\t// Start database\n\tgo func() {\n\t\twgBackend.Add(1)\n\t\terr := s.db.start(ctx)\n\t\tif err != nil {\n\t\t\ts.db.logger.Errorf(err.Error())\n\t\t}\n\t\twgBackend.Done()\n\t}()\n\n\t// Start plugins\n\twgPlugin := sync.WaitGroup{}\n\tstartPlugin := func(f func()) {\n\t\twgPlugin.Add(1)\n\t\tf()\n\t\twgPlugin.Done()\n\t}\n\tfor _, plugin := range s.plugins {\n\t\tgo startPlugin(plugin.Start)\n\t}\n\n\t// Start router\n\tgo func() {\n\t\twgBackend.Add(1)\n\t\ts.router.start(ctx, 5*time.Second, 5*time.Second)\n\t\twgBackend.Done()\n\t}()\n\n\t// Start Webhook handling server\n\ts.logger.Info(\"starting web server\")\n\ts.webServer.finalize()\n\tgo s.webServer.ListenAndServe()\n\n\t// Wait here until we received termination signal\n\t<-s.done\n\ts.logger.Info(\"terminating\")\n\n\t// Termination process\n\t// Shutdown Http server\n\ttimeout, stop := context.WithTimeout(context.Background(), 5*time.Second)\n\terr := s.webServer.Shutdown(timeout)\n\tstop()\n\tif err != nil {\n\t\ts.logger.Errorf(\"failed to shutdown httpserver: %s\", err.Error())\n\t\treturn\n\t}\n\ts.logger.Info(\"httpserver shutdown\")\n\n\t// Terminate plugins\n\tfor _, plugin := range s.plugins {\n\t\tplugin.Stop()\n\t}\n\twgPlugin.Wait()\n\ts.logger.Info(\"all plugins terminated\")\n\n\t// Wait for backend service\n\twgBackend.Wait()\n\ts.logger.Info(\"all backend services terminated\")\n\n\ts.logger.Info(\"session closed\")\n}", "func (m *Mod) Start() {\n\tm.app.WG.Add(1)\n\tgo m.start()\n\t// wait for all modules to start\n\tm.app.WG.Wait()\n}", "func (om *OpenMock) Start() {\n\tom.SetupLogrus()\n\tom.SetupRepo()\n\tom.SetRedis()\n\n\terr := om.Load()\n\tif err != nil {\n\t\tlogrus.Fatalf(\"%s: %s\", \"failed to load yaml templates for mocks\", err)\n\t}\n\n\tif om.HTTPEnabled {\n\t\tgo om.startHTTP()\n\t}\n\tif om.KafkaEnabled {\n\t\tgo om.startKafka()\n\t}\n\tif om.AMQPEnabled {\n\t\tgo om.startAMQP()\n\t}\n\tif om.GRPCEnabled {\n\t\tgo om.startGRPC()\n\t}\n\n\tif om.TemplatesDirHotReload {\n\t\tgo func() {\n\t\t\terr := reload.Do(logrus.Infof, reload.Dir(om.TemplatesDir, reload.Exec))\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Fatal(err)\n\t\t\t}\n\t\t}()\n\t}\n}", "func (s *Service) Start(store Store, options *Options) error {\n\ts.Options = options\n\tif store == nil {\n\t\tdb, err := ConnectBoltStore(options.DbPath)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ts.store = *db\n\t} else {\n\t\ts.store = store\n\t}\n\ts.channel = make(chan int)\n\ts.timers = make(map[int]*Timer)\n\n\tif err := s.restoreTimers(); err != nil {\n\t\tlog.Printf(\"Countdown package failed to restore timers: %s\", err.Error())\n\t}\n\n\tgo s.manageTimers()\n\n\treturn nil\n}", "func (m *Machine) Start(ctx context.Context) error {\n\tm.logger.Debug(\"Called Machine.Start()\")\n\talreadyStarted := true\n\tm.startOnce.Do(func() {\n\t\tm.logger.Debug(\"Marking Machine as Started\")\n\t\talreadyStarted = false\n\t})\n\tif alreadyStarted {\n\t\treturn ErrAlreadyStarted\n\t}\n\n\tvar err error\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif cleanupErr := m.doCleanup(); cleanupErr != nil {\n\t\t\t\tm.Logger().Errorf(\n\t\t\t\t\t\"failed to cleanup VM after previous start failure: %v\", cleanupErr)\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = m.Handlers.Run(ctx, m)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = m.startInstance(ctx)\n\treturn err\n}", "func (e *Engine) Start(listenAddr string, addons []string, folder string) {\n\n\t// Listen for signals\n\tgo e.ListenForSignal()\n\n\t// Initialize and start the networking engine\n\te.Log.Debug(\"Initializing networking engine\")\n\tnet := netengine.NewEngine()\n\tgo net.ListenChannels()\n\te.NetEngine = net\n\n\te.AddNetHandlers()\n\n\tlistener := netengine.WebsocketListener{\n\t\tnet,\n\t\tlistenAddr,\n\t}\n\tgo net.AddListener(&listener)\n\n\te.Log.Debug(\"Running player id generation goroutine\")\n\n\t// The player id channel\n\tplyIdChan := make(chan int)\n\tidGen(plyIdChan)\n\te.plyIdChan = plyIdChan\n\n\t// Worker id channel\n\tworkerIdChan := make(chan int)\n\tidGen(workerIdChan)\n\te.workerIdChan = workerIdChan\n\n\te.Log.Debug(\"Adding javascript extensions\")\n\t// Adds the javascript extensions, sets e.JsContext\n\te.AddJsExtensions()\n\n\te.Log.Debug(\"Loading, compiling and running addons\")\n\t// Load all the addons, compile the scripts etc..\n\terr := e.LoadAddons(addons, folder)\n\tif err != nil {\n\t\te.Log.Error(\"Error loading addons: \", err)\n\t\treturn\n\t}\n\tgo e.ListenForClosedConnection()\n\n\t// Emit server loaded event\n\tevt := NewGeneralEvent(\"loaded\")\n\te.EmitEvent(evt)\n}", "func Start() {\n\tconfig, configErr := config.ParseArgsReturnConfig(os.Args[1:])\n\tif configErr != nil {\n\t\tfor _, err := range configErr {\n\t\t\tlog.Error(err)\n\t\t}\n\t\tos.Exit(1)\n\t}\n\tswitch {\n\tcase config.FlagVersion:\n\t\tfmt.Printf(\"DCOS Signal Service\\n Version: %s\\n Revision: %s\\n DC/OS Variant: %s\\n\", VERSION, REVISION, config.DCOSVariant)\n\t\tos.Exit(0)\n\tdefault:\n\t\tif config.Enabled == \"false\" {\n\t\t\tos.Exit(0)\n\t\t}\n\t\tif config.FlagVerbose {\n\t\t\tlog.SetLevel(log.DebugLevel)\n\t\t}\n\t\tif config.FlagTest {\n\t\t\tlog.SetLevel(log.ErrorLevel)\n\t\t}\n\t}\n\tif err := executeRunner(config); err != nil {\n\t\tlog.Error(err)\n\t\tos.Exit(1)\n\t}\n\tos.Exit(0)\n}", "func Start() {\n\tdefaultDaemon.Start()\n}", "func (self *app) Start() {\n\t// ctrl-c: listen removes binary package when application stopped.\n\tchannel := make(chan os.Signal, 2)\n\tsignal.Notify(channel, os.Interrupt, syscall.SIGTERM)\n\tgo func() {\n\t\t<-channel\n\t\t// remove the binary package on stop.\n\t\tos.Remove(self.binary)\n\t\tos.Exit(1)\n\t}()\n\n\t// start waiting the signal to start running.\n\tvar gorun = self.run()\n\tself.build()\n\tgorun <- true\n\n\twatcher := fs.NewWatcher(self.dir)\n\tlog.Infof(\"Start watching: %s\", self.dir)\n\twatcher.Add(watchList, func(filename string) {\n\t\trelpath, _ := filepath.Rel(self.dir, filename)\n\t\tlog.Infof(\"Changes on %s detected\", relpath)\n\t\tself.rerun(gorun)\n\t})\n\twatcher.Start()\n}", "func (um *Manager) Start(ctx context.Context) error {\n\tlog.Info(\"Starting Upgrade Manager\")\n\tdefer log.Info(\"Stopping upgrade manager workers\")\n\terrCh := make(chan error)\n\tgo func() { errCh <- um.upgrade(ctx) }()\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil\n\tcase err := <-errCh:\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// We must block indefinitely or manager will exit\n\t<-ctx.Done()\n\treturn nil\n}", "func (p *Plugin) Start() {\n\tp.running = true\n\tgo p.run()\n}", "func (g *Glutton) Start() (err error) {\n\n\tquit := make(chan struct{}) // stop monitor on shutdown\n\tdefer func() {\n\t\tquit <- struct{}{}\n\t\tg.Shutdown()\n\t}()\n\n\tg.startMonitor(quit)\n\terr = g.processor.Start()\n\treturn\n}", "func (e *Emulator) Start() {\n\tfor {\n\t\te.cpu.Exec()\n\t}\n}", "func (b *Bot) Start(stop <-chan struct{}) error {\n\tlog.Info(\"start the bot ...\")\n\n\t// Now start all of the components.\n\tif err := b.server.Start(stop); err != nil {\n\t\treturn err\n\t}\n\n\tb.waitForShutdown(stop)\n\n\tlog.Info(\"bot started\")\n\treturn nil\n}", "func (d *loadReporterDaemonImpl) Start() {\n\tif !atomic.CompareAndSwapInt32(&d.started, 0, 1) {\n\t\treturn\n\t}\n\n\td.shutdownWG.Add(1)\n\tgo d.reporterPump()\n\n\td.logger.Info(\"Load reporter started.\")\n}", "func Start() {\n\troot := NewRootCmd()\n\tif err := root.Execute(); err != nil {\n\t\tlogger.WithError(err).Fatal(\"error executing driverkit\")\n\t}\n}", "func (w *ServiceWriter) Start() {\n\tgo func() {\n\t\tdefer watchdog.LogOnPanic()\n\t\tw.Run()\n\t}()\n}", "func Start(args ...string) {\n runInstances(\"Start\", func(i int, id string) error {\n return runDaemon(\"run\", settingsToParams(i, true)...)\n })\n\n if cfg.UseNginx {\n UpdateNginxConf()\n }\n}", "func (cracker *Firecracker) Start() error {\n\treturn cracker.action(\"InstanceStart\", \"\")\n}", "func Start(context unsafe.Pointer, engine string, config string, callback KVStartFailureCallback) *KVEngineSys {\n\tccontext, _ := context, cgoAllocsUnknown\n\tcengine, _ := unpackPCharString(engine)\n\tcconfig, _ := unpackPCharString(config)\n\tccallback, _ := callback.PassRef()\n\t__ret := C.kvengine_start(ccontext, cengine, cconfig, ccallback)\n\t__v := *(**KVEngineSys)(unsafe.Pointer(&__ret))\n\treturn __v\n}", "func (mng *Manager) Start() {\n\tgo func() {\n\t\tif err := mng.srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\t\tmng.lgr.Fatal(\"Error starting HTTP service: \" + err.Error())\n\t\t}\n\t}()\n}", "func (e *Engine) Start() {\n e.cmdStack = &Queue{onReceiveEmptyChan: make(chan bool)}\n e.onFinishChan = make(chan bool)\n go func() {\n for {\n cmd := e.cmdStack.Pull(&e.stopRequest)\n if cmd == nil {\n break\n }\n cmd.Execute(e)\n }\n e.onFinishChan <- true\n }()\n}", "func (c *ConfigManager) Start() {\n\tc.saveLoop()\n}", "func (p *Program) Start() error {\n\tvar err error\n\t// 连接数据库\n\terr = database.OpenMysql(global.ProjectConfig.MysqlCfgs...)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\terr = wallet.WalletService().LoadWallets()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\t// 启动http服务\n\terr = p.htpServe.Start(global.ProjectConfig.Servers.Debug, global.ProjectConfig.Servers.Server)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (k *kubernetes) Start() error {\n\tk.Lock()\n\tdefer k.Unlock()\n\n\t// already running\n\tif k.running {\n\t\treturn nil\n\t}\n\n\t// set running\n\tk.running = true\n\tk.closed = make(chan bool)\n\n\tvar events <-chan runtime.Event\n\tif k.options.Notifier != nil {\n\t\tvar err error\n\t\tevents, err = k.options.Notifier.Notify()\n\t\tif err != nil {\n\t\t\t// TODO: should we bail here?\n\t\t\tlog.Debugf(\"Runtime failed to start update notifier\")\n\t\t}\n\t}\n\n\tgo k.run(events)\n\n\treturn nil\n}", "func Start() {\n\tLoadConf()\n\tDeviceProcessStart()\n}", "func (a *appImpl) Start() {\n\tfor _, operation := range a.operations {\n\t\ta.vehiclePark.ExecuteCmd(operation)\n\t}\n}", "func (s *Server) Start() error {\n\tlevel, ok := levelMap[s.opts.LogLevel]\n\tif !ok {\n\t\tallLevels := make([]string, 0, len(levelMap))\n\t\tfor level := range levelMap {\n\t\t\tallLevels = append(allLevels, level)\n\t\t}\n\t\treturn fmt.Errorf(\"%v is not a valid level. Valid levels are %v\", s.opts.LogLevel, strings.Join(allLevels, \", \"))\n\t}\n\n\tlog.SetLevel(level)\n\tif s.opts.LogFile != \"\" {\n\t\tlogFH, err := os.Create(s.opts.LogFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.SetOutput(logFH)\n\t\ts.logFH = logFH\n\t}\n\n\tregistry := plugin.NewRegistry()\n\tloadInternalPlugins(registry)\n\tif len(s.opts.ExternalPlugins) > 0 {\n\t\tloadExternalPlugins(registry, s.opts.ExternalPlugins)\n\t}\n\tif len(registry.Plugins()) == 0 {\n\t\treturn fmt.Errorf(\"No plugins loaded\")\n\t}\n\n\tplugin.InitCache()\n\n\tapiServerStopCh, apiServerStoppedCh, err := api.StartAPI(registry, s.mountpoint, s.socket)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.api = controlChannels{stopCh: apiServerStopCh, stoppedCh: apiServerStoppedCh}\n\n\tfuseServerStopCh, fuseServerStoppedCh, err := fuse.ServeFuseFS(registry, s.mountpoint)\n\tif err != nil {\n\t\ts.stopAPIServer()\n\t\treturn err\n\t}\n\ts.fuse = controlChannels{stopCh: fuseServerStopCh, stoppedCh: fuseServerStoppedCh}\n\n\tif s.opts.CPUProfilePath != \"\" {\n\t\tf, err := os.Create(s.opts.CPUProfilePath)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\terrz.Fatal(pprof.StartCPUProfile(f))\n\t}\n\treturn nil\n}", "func Start() {\n\tgo BlobServerStart()\n\tgo CollectionServerStart()\n\tgo UploadServerStart()\n}", "func (m *hostConfiguredContainer) Start() error {\n\treturn withHook(nil, func() error {\n\t\treturn m.withForwardedRuntime(m.container.Start)\n\t}, m.hooks.PostStart)\n}", "func (m *master) Start() {\n\tm.init()\n\tm.setupEtcd()\n\tm.startServer()\n\tgo m.startEventHandling()\n\tm.runUserTask()\n\tm.stop()\n}", "func Start() {\n\tdriver.Main(func(app oswin.App) {\n\t\tatomic.AddInt32(&started, 1)\n\t\t<-quit\n\t})\n}", "func (e *Engine) Run(ctx context.Context) error {\n\t// load container\n\tif err := e.load(); err != nil {\n\t\treturn err\n\t}\n\t// start status watcher\n\teventChan, errChan := e.initMonitor()\n\tgo e.monitor(eventChan)\n\n\t// start health check\n\tgo e.healthCheck(ctx)\n\n\t// start node heartbeat\n\tgo e.heartbeat(ctx)\n\n\tlog.Info(\"[Engine] Node activated\")\n\n\t// wait for signal\n\tselect {\n\tcase <-ctx.Done():\n\t\tlog.Info(\"[Engine] Agent caught system signal, exiting\")\n\t\treturn nil\n\tcase err := <-errChan:\n\t\tif err := e.crash(); err != nil {\n\t\t\tlog.Infof(\"[Engine] Mark node crash failed %v\", err)\n\t\t}\n\t\treturn err\n\t}\n}", "func (TelegramBotApp *TelegramBotApp) Start() {\n\tupdates, err := TelegramBotApp.getUpdates()\n\tif err != nil {\n\t\tlog.Fatal(\"[!] Error: Can't get updates\")\n\t}\n\tfmt.Println(\"[+] Initializating telegram bot\")\n\n\t// Start the cronjob\n\tgo TelegramBotApp.startCron()\n\n\t// Handle telegram api updates\n\tfor update := range updates {\n\t\tif update.Message != nil && update.Message.IsCommand() {\n\t\t\tgo func() {\n\t\t\t\tTelegramBotApp.handleCommand(&update)\n\t\t\t}()\n\t\t}\n\n\t}\n}", "func (svc *Service) Start(ctx context.Context, svcErrors chan error) {\n\n\t// Start kafka logging\n\tsvc.dataBakerProducer.Channels().LogErrors(ctx, \"error received from kafka data baker producer, topic: \"+svc.cfg.DatabakerImportTopic)\n\tsvc.inputFileAvailableProducer.Channels().LogErrors(ctx, \"error received from kafka input file available producer, topic: \"+svc.cfg.InputFileAvailableTopic)\n\n\t// Start healthcheck\n\tsvc.healthCheck.Start(ctx)\n\n\t// Run the http server in a new go-routine\n\tgo func() {\n\t\tlog.Event(ctx, \"Starting api...\", log.INFO)\n\t\tif err := svc.server.ListenAndServe(); err != nil {\n\t\t\tsvcErrors <- errors.Wrap(err, \"failure in http listen and serve\")\n\t\t}\n\t}()\n}", "func (p *GenericPlugin) Start(Args ...interface{}) error {\n\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\tswitch p.state {\n\tcase stateNotLoaded:\n\t\tif err := p.Load(); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase stateLoaded:\n\tcase stateActive:\n\t\tp.agent.Logger().Printf(\"Cannot Start() module [ %s ], already running\", p.Name())\n\t\treturn nil\n\t}\n\n\tif err := p.ReadStatus(); err != nil {\n\t\treturn err\n\t}\n\n\tp.state = stateActive\n\tp.started = time.Now()\n\n\tswitch {\n\tcase p.init != nil:\n\t\t{\n\t\t\tArgs = append(p.args, Args...)\n\t\t\tif err := p.init(Args...); err != nil {\n\t\t\t\tp.stop()\n\t\t\t\tp.state = stateLoaded\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"plugin error: No Init() function loaded for module [ %s ]\", p.Name())\n\t}\n\n\tp.agent.Logger().Printf(\"Started module [ %s ]\", p.Name())\n\n\treturn nil\n}", "func (b *Bot) Start() {\n\trtm := b.client.NewRTM()\n\tb.rtm = rtm\n\n\tgo rtm.ManageConnection()\n\n\tfor {\n\t\tselect {\n\t\tcase msg := <-rtm.IncomingEvents:\n\t\t\tswitch ev := msg.Data.(type) {\n\t\t\tcase *slack.HelloEvent:\n\t\t\t\tb.log(\"Hello\")\n\t\t\t\tb.handleHello()\n\t\t\tcase *slack.ConnectedEvent:\n\t\t\t\tb.info = ev.Info\n\t\t\t\tb.logf(\"Info : %v\\n\", ev.Info)\n\t\t\t\tb.logf(\"Connections : %v\\n\", ev.ConnectionCount)\n\t\t\tcase *slack.DisconnectedEvent:\n\t\t\t\tb.log(\"Disconnected\")\n\t\t\t\tif ev.Intentional {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase *slack.MessageEvent:\n\t\t\t\tb.handleMessage(ev)\n\t\t\t}\n\t\t}\n\t}\n}", "func Start(cmd *cobra.Command, args []string) error {\n\tvar err error\n\tcfg, err = config.BindWithCobra(cmd)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstartServices()\n\treturn nil\n}", "func Start(wl ...debugLevel) {\n\tif isStarted {\n\t\tcolorLog(\"[ERRO] Fail to start Bee Watch[ %s ]\",\n\t\t\t\"cannot start Bee Watch twice\")\n\t\treturn\n\t}\n\n\tisStarted = true\n\tcolorLog(\"[INIT] BW: Bee Watch v%s.\\n\", APP_VER)\n\n\twatchLevel = LevelTrace\n\tif len(wl) > 0 {\n\t\twatchLevel = wl[0]\n\t}\n\n\tApp.Name = \"Bee Watch\"\n\tApp.HttpPort = 23456\n\tApp.WatchEnabled = true\n\tApp.PrintStack = true\n\tApp.PrintSource = true\n\n\tloadJSON()\n\n\tif App.WatchEnabled {\n\t\tif App.CmdMode {\n\n\t\t} else {\n\t\t\tinitHTTP()\n\t\t}\n\t}\n}", "func (d *DockerWebHook) Start(ctx context.Context) error {\n\tserver := &http.Server{\n\t\tAddr: d.bind,\n\t\tHandler: d,\n\t}\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\t\tdefer cancel()\n\t\tif err := server.Shutdown(ctx); err != nil {\n\t\t\tklog.Errorf(\"error shutting down https server: %s\", err)\n\t\t}\n\t}()\n\n\tif err := server.ListenAndServe(); err != nil {\n\t\tif err == http.ErrServerClosed {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *SafeTestingTBOnStart) Start(t testing.TB) error {\n\ts.SetTestingTB(t)\n\treturn nil\n}", "func Start(opts ...StartOption) {\n\tif internal.Testing {\n\t\treturn // mock tracer active\n\t}\n\tt := newTracer(opts...)\n\tif !t.config.enabled {\n\t\treturn\n\t}\n\tinternal.SetGlobalTracer(t)\n\tif t.config.logStartup {\n\t\tlogStartup(t)\n\t}\n}", "func (m *Mainloop) Start() {\n\tsigs := make([]os.Signal, len(m.Bindings))\n\tfor s, _ := range m.Bindings {\n\t\tsigs = append(sigs, s)\n\t}\n\tsignal.Notify(m.sigchan, sigs...)\n\tfor {\n\t\tselect {\n\t\tcase sig := <-m.sigchan:\n\t\t\tm.Bindings[sig]()\n\t\tcase _ = <-m.termchan:\n\t\t\tbreak\n\t\t}\n\t}\n\treturn\n}", "func (e *Executor) Start() { go e.loop() }", "func (p *Prober) Start() {\n\t// Get static copy of the config object\n\tcfg := p.config.Copy()\n\n\tfor _, svc := range cfg.Monitor.Services {\n\t\t// Create new Probe Bot and start it\n\t\tif svc.Interval == 0 {\n\t\t\tsvc.Interval = cfg.Monitor.Interval\n\t\t}\n\n\t\tgo NewProbeBot(\n\t\t\tp.eb,\n\t\t\tsvc,\n\t\t\tp.status.Update,\n\t\t).Start()\n\t}\n}", "func (pr *PolicyReflector) Start() {\n\tpr.wg.Add(1)\n\tgo pr.run()\n}", "func Start() {\n\n\tlog.SetFormatter(&log.TextFormatter{\n\t\tDisableColors: true,\n\t\tFullTimestamp: true,\n\t})\n\n\tcfg := config{}\n\tif err := env.Parse(&cfg); err != nil {\n\t\tlog.Fatalf(\"Error parsing environment variables %+v\\n\", err)\n\n\t}\n\n\tfinish := make(chan bool)\n\n\tgo func() {\n\t\thttp.Handle(\"/metrics\", promhttp.Handler())\n\t\tlistenAddress := fmt.Sprintf(\"0.0.0.0:%d\", cfg.Port)\n\t\terr := http.ListenAndServe(listenAddress, nil)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error starting metrics server %+v\\n\", err)\n\t\t}\n\t}()\n\n\tgo func() {\n\t\texecuteCronJob(cfg)\n\t}()\n\n\t<-finish\n}", "func (s *Server) Start() {\n\tgo func() {\n\t\tlevel.Info(s.logger).Log(\"msg\", \"starting server\", \"addr\", s.server.Addr)\n\t\t// returns ErrServerClosed on graceful close\n\t\tif err := s.server.ListenAndServe(); err != http.ErrServerClosed {\n\t\t\t// NOTE: there is a chance that next line won't have time to run,\n\t\t\t// as main() doesn't wait for this goroutine to stop. don't use\n\t\t\t// code with race conditions like these for production. see post\n\t\t\t// comments below on more discussion on how to handle this.\n\t\t\t// TODO remove this log and return error instead.\n\t\t\tlevel.Error(s.logger).Log(\"msg\", \"ListenAndServe()\", \"err\", err)\n\t\t}\n\t}()\n}", "func (pier *Pier) Start() error {\n\tif pier.config.Mode.Type == repo.UnionMode {\n\t\tif err := pier.lite.Start(); err != nil {\n\t\t\tpier.logger.Errorf(\"lite start: %w\", err)\n\t\t\treturn err\n\t\t}\n\t\tif err := pier.exchanger.Start(); err != nil {\n\t\t\tpier.logger.Errorf(\"exchanger start: %w\", err)\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\tif err := pier.pierHA.Start(); err != nil {\n\t\treturn fmt.Errorf(\"pier ha start fail\")\n\t}\n\tgo pier.startPierHA()\n\treturn nil\n}", "func (m *mockService) Start() {\n\tif err := m.server.Bootstrap(); err != nil {\n\t\tpanic(err)\n\t}\n\tm.started = true\n}", "func (w *GitWatcher) Start() error {\n\tzap.L().Debug(\"git watcher initialising, waiting for first state to be set\")\n\n\t// wait for the first config event to set the initial state\n\tw.__waitpoint__start_wait_init()\n\n\tzap.L().Debug(\"git watcher initialised\", zap.Any(\"initial_state\", w.state))\n\n\tfor {\n\t\terr := w.__waitpoint__start_select_states()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}", "func Start(\n\tctx context.Context,\n\tconfig Config,\n\tdbConfig fw.DBConfig,\n\tdbConnector fw.DBConnector,\n\tdbMigrationTool fw.DBMigrationTool,\n\tsecurityPolicy fw.SecurityPolicy,\n\teventDispatcher fw.Dispatcher,\n) {\n\tdb, err := dbConnector.Connect(dbConfig)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = dbMigrationTool.MigrateUp(db, config.MigrationRoot)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tgRpcService, err := dep.InitGRpcService(\n\t\tconfig.ServiceName,\n\t\tconfig.LogLevel,\n\t\tprovider.ServiceEmailAddress(config.ServiceEmailAddress),\n\t\tdb,\n\t\tsecurityPolicy,\n\t\tprovider.SendGridAPIKey(config.SendGridAPIKey),\n\t\tprovider.TemplateRootDir(config.TemplateRootDir),\n\t\tprovider.CacheSize(config.CacheSize),\n\t\teventDispatcher,\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tgRpcService.Stop()\n\t}()\n\n\tgRpcService.Start(config.GRpcAPIPort)\n}", "func Start(ctx context.Context) {\n\tlog.Infow(\"startup\", \"message\", \"running initial background tasks\")\n\tmodel.LocationClean()\n\n\thourly := time.NewTicker(time.Hour)\n\tdefer hourly.Stop()\n\n\tweekly := time.NewTicker(time.Hour * 24 * 7)\n\tdefer weekly.Stop()\n\n\tif config.IsFirebaseRunning() {\n\t\twfb.Resubscribe() // prevent a crash if background starts before firebase\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tlog.Infow(\"shutdown\", \"message\", \"background tasks shutting down\")\n\t\t\treturn\n\t\tcase <-hourly.C:\n\t\t\tmodel.LocationClean()\n\t\t\twfb.ResetDefaultRateLimits()\n\t\tcase <-weekly.C:\n\t\t\twfb.Resubscribe()\n\t\t}\n\t}\n}", "func (s *Server) Start(ctx context.Context) {\n\tnewctx, cancel := contextWithSignal(ctx, os.Interrupt, syscall.SIGTERM)\n\ts.startGears(newctx, cancel)\n}", "func (c *CamSodaChecker) Start() { c.startFullCheckerDaemon(c) }", "func (self *manager) Start() error {\n\t// Register Docker container factory.\n\terr := docker.Register(self, self.fsInfo)\n\tif err != nil {\n\t\tlog.Printf(\"{Error] Docker container factory registration failed: %v.\", err)\n\t\treturn err\n\t}\n\n\t// Register the raw driver.\n\terr = raw.Register(self, self.fsInfo)\n\tif err != nil {\n\t\tlog.Printf(\"[Error] Registration of the raw container factory failed: %v\", err)\n\t\treturn err\n\t}\n\n\tself.DockerInfo()\n\tself.DockerImages()\n\n\tif enableLoadReader {\n\t\t// Create cpu load reader.\n\t\tcpuLoadReader, err := cpuload.New()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[Error] Could not initialize cpu load reader: %s\", err)\n\t\t} else {\n\t\t\terr = cpuLoadReader.Start()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"[Error] Could not start cpu load stat collector: %s\", err)\n\t\t\t} else {\n\t\t\t\tself.loadReader = cpuLoadReader\n\t\t\t}\n\t\t}\n\t}\n\n\t// Watch for OOMs.\n\terr = self.watchForNewOoms()\n\tif err != nil {\n\t\tlog.Printf(\"[Error] Could not configure a source for OOM detection, disabling OOM events: %v\", err)\n\t}\n\n\t// If there are no factories, don't start any housekeeping and serve the information we do have.\n\tif !container.HasFactories() {\n\t\treturn nil\n\t}\n\n\t// Create root and then recover all containers.\n\terr = self.createContainer(\"/\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t//log.Printf(\"[Info] Starting recovery of all containers\")\n\n\terr = self.detectSubcontainers(\"/\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t//log.Printf(\"[Info] Recovery completed\")\n\n\t// Watch for new container.\n\tquitWatcher := make(chan error)\n\terr = self.watchForNewContainers(quitWatcher)\n\tif err != nil {\n\t\treturn err\n\t}\n\tself.quitChannels = append(self.quitChannels, quitWatcher)\n\n\t// Look for new containers in the main housekeeping thread.\n\tquitGlobalHousekeeping := make(chan error)\n\tself.quitChannels = append(self.quitChannels, quitGlobalHousekeeping)\n\tgo self.globalHousekeeping(quitGlobalHousekeeping)\n\n\treturn nil\n}", "func Start(config *model.Config) {\n\tlogger := config.Logger\n\ttgbotapi.SetLogger(logger)\n\n\tstore := memorystore.New()\n\tvar client *http.Client\n\tif config.Proxy != \"\" {\n\t\tproxy, err := url.Parse(config.Proxy)\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tclient = &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxy)}}\n\t} else {\n\t\tclient = &http.Client{}\n\t}\n\n\tbot, err := tgbotapi.NewBotAPIWithClient(config.TelegramToken, client)\n\t// bot.Debug = true\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\tos.Exit(1)\n\t}\n\tsrv := newServer(store, *bot, config)\n\n\tsrv.Run()\n}", "func (sv *Unit) Start() (err error) {\n\te := log.WithField(\"ExecStart\", sv.Definition.Service.ExecStart)\n\n\te.Debug(\"sv.Start\")\n\n\tswitch sv.Definition.Service.Type {\n\tcase \"simple\":\n\t\tif err = sv.Cmd.Start(); err == nil {\n\t\t\tgo sv.Cmd.Wait()\n\t\t}\n\tcase \"oneshot\":\n\t\terr = sv.Cmd.Run()\n\tdefault:\n\t\tpanic(\"Unknown service type\")\n\t}\n\n\te.WithField(\"err\", err).Debug(\"started\")\n\treturn\n}", "func (m *mockAPI) Start() {\n\tif m.isServing() {\n\t\treturn\n\t}\n\n\tm.Server.Start()\n\tm.Lock()\n\tdefer m.Unlock()\n\tm.serving = true\n}", "func Start(debugMode bool) error {\n\tvar err error\n\n\t// since init has been done in cmd init\n\tconfigN := config.Get()\n\tlog := logger.Get()\n\n\t// fetch globalDir\n\tvar globalDir string\n\tif globalDir, err = configN.FindString(\"global.dir\"); err != nil {\n\t\treturn addTag(\"cfg\", err)\n\t}\n\n\t// make directory\n\tif err = os.MkdirAll(globalDir, os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\n\t// init logFile & pidFile\n\tvar pidFile, logFile string\n\tif pidFile, err = configN.FindString(\"global.pidFile\"); err != nil {\n\t\treturn addTag(\"cfg\", err)\n\t}\n\tif logFile, err = configN.FindString(\"global.logFile\"); err != nil {\n\t\treturn addTag(\"cfg\", err)\n\t}\n\n\t// init context\n\tcntxt := &daemon.Context{\n\t\tPidFileName: pidFile,\n\t\tPidFilePerm: 0644,\n\t\tLogFileName: logFile,\n\t\tLogFilePerm: 0640,\n\t\tWorkDir: \"./\",\n\t\tUmask: 027,\n\t\tArgs: []string{},\n\t}\n\n\tvar p *os.Process\n\tp, err = cntxt.Reborn()\n\tif err != nil {\n\t\tlog.Debugf(\"[apm] daemon has started\")\n\t\treturn nil\n\t}\n\t// if fork process succeed, let the parent process\n\t// go and run the folllowing logic in the child process\n\tif p != nil {\n\t\treturn nil\n\t}\n\tdefer cntxt.Release()\n\n\t// CHILD PROCESS\n\treturn daemonHandler(debugMode)\n}", "func (h *HookbotTrigger) Start() error {\n\tfinishCh := make(chan struct{})\n\tmsgCh, errCh := listen.RetryingWatch(h.Endpoint, http.Header{}, finishCh)\n\tgo h.errorHandler(errCh)\n\tgo h.msgHandler(msgCh)\n\treturn nil\n}", "func (c *Component) Start() {\n\tc.Log.Info(\"Starting VolumeSeriesHandler\")\n\tc.oCrud = crud.NewClient(c.App.ClientAPI, c.Log)\n\tc.runCount = 0\n\tc.Animator.Start(c.oCrud, c.App.CrudeOps)\n}", "func (s *Server) Start() error {\n\tidleConnsClosed := make(chan struct{})\n\n\tgo func() {\n\t\tsigint := make(chan os.Signal, 1)\n\t\tsignal.Notify(sigint, syscall.SIGINT, syscall.SIGTERM)\n\t\t<-sigint\n\n\t\ts.logger.Info(\"Shutting down HTTP server\")\n\n\t\terr := s.httpServer.Shutdown()\n\t\tfailpoint.Inject(\"shutdownErr\", func() {\n\t\t\terr = errors.New(\"mock shutdown error\")\n\t\t})\n\t\tif err != nil {\n\t\t\ts.logger.Error(\"srv.Shutdown: %v\", zap.Error(err))\n\t\t}\n\t\ts.logger.Info(\"HTTP server is stopped\")\n\n\t\tclose(idleConnsClosed)\n\t}()\n\n\ts.logger.Info(\"Starting HTTP server\", zap.String(\"address\", s.addr))\n\terr := s.httpServer.ListenAndServe(s.addr)\n\tfailpoint.Inject(\"listenAndServeErr\", func() {\n\t\terr = errors.New(\"mock listen and serve error\")\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"ListenAndServe error: %w\", err)\n\t}\n\n\t<-idleConnsClosed\n\n\tif err := s.afterShutdown(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}" ]
[ "0.70842016", "0.70279807", "0.6923318", "0.6841361", "0.6739894", "0.6596409", "0.6575987", "0.6469447", "0.64490694", "0.6430585", "0.64055973", "0.6379535", "0.6339723", "0.6337157", "0.6315934", "0.6285416", "0.62843764", "0.6270798", "0.62603813", "0.62498593", "0.6222911", "0.6200143", "0.6167275", "0.615359", "0.6140899", "0.61243474", "0.61211944", "0.61185414", "0.6115358", "0.6104151", "0.6101459", "0.60985905", "0.60935307", "0.6087295", "0.6087025", "0.6080841", "0.60606337", "0.6046862", "0.6039034", "0.6034408", "0.6031499", "0.60208845", "0.6018018", "0.60051614", "0.59946185", "0.5984861", "0.5983111", "0.5978189", "0.5974504", "0.59723604", "0.59669924", "0.5965412", "0.59640676", "0.5956073", "0.59493583", "0.5944476", "0.5940607", "0.59367293", "0.59344465", "0.5934103", "0.59305394", "0.59254605", "0.59159726", "0.59154004", "0.5907318", "0.59040314", "0.59038585", "0.59012514", "0.5897683", "0.58933395", "0.5881346", "0.5871922", "0.586916", "0.5864401", "0.586099", "0.5840079", "0.5835499", "0.583433", "0.5827639", "0.5826334", "0.58253545", "0.58200455", "0.5816487", "0.5812042", "0.5811024", "0.5807751", "0.5803552", "0.5802581", "0.5799637", "0.57929516", "0.5792205", "0.5791257", "0.57910687", "0.578722", "0.5783094", "0.57807225", "0.5773333", "0.57664675", "0.5765629", "0.57604545" ]
0.78836673
0
Stop will shutdown engine.
func (e *Engine) Stop() error { e.mutex.Lock() defer e.mutex.Unlock() if e.interrupt != nil { select { case e.interrupt <- os.Interrupt: default: } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (e *Engine) Stop() error {\n\tclose(e.stop)\n\treturn nil\n}", "func (e *Engine) Stop() {\n\te.running = false\n}", "func (e *Engine) Stop() {\n\tif atomic.CompareAndSwapInt32(&e.stopping, 0, 1) {\n\t\te.wg.Wait()\n\t\te.running = 0\n\t\te.stopping = 0\n\t}\n}", "func (e *Engine) Stop() error {\n\te.stop <- nil\n\terr := <-e.stop\n\tclose(e.errors)\n\tclose(e.stop)\n\treturn err\n}", "func (e *Engine) stop() error {\n\te.booted = false\n\n\t// instruct engine to shutdown\n\tshutdown := \"shutdown\"\n\tcommunication.Publish(\n\t\tnaming.Topic(e.Index, naming.Command),\n\t\tnaming.Publisher(e.Index, naming.Command),\n\t\tshutdown)\n\n\t// stop subscribing to engine's commands and events\n\te.Communication.Teardown()\n\n\t// TODO create graphic for MQTT hierarchy, whos's publishing what to whom and why\n\t// TODO explain MQTT hierarchy\n\treturn nil\n}", "func Stop() {\n\tinstance.stop()\n}", "func (el *Launcher) Stop() error {\n\tlogrus.Debugf(\"engine launcher %v: prepare to stop engine %v\",\n\t\tel.LauncherName, el.currentEngine.EngineName)\n\n\tif _, err := el.currentEngine.Stop(); err != nil {\n\t\treturn err\n\t}\n\tel.lock.Lock()\n\tif !el.isStopping {\n\t\tclose(el.doneCh)\n\t}\n\tel.isStopping = true\n\tel.lock.Unlock()\n\n\tel.updateCh <- el\n\n\tlogrus.Debugf(\"engine launcher %v: succeed to stop engine %v at %v\",\n\t\tel.LauncherName, el.currentEngine.EngineName, el.currentEngine.GetListen())\n\treturn nil\n\n}", "func (r *runtime) Stop() {\n\tr.logger.Info(\"stopping broker server...\")\n\tdefer r.cancel()\n\n\tr.Shutdown()\n\n\tif r.httpServer != nil {\n\t\tr.logger.Info(\"stopping http server...\")\n\t\tif err := r.httpServer.Close(r.ctx); err != nil {\n\t\t\tr.logger.Error(\"shutdown http server error\", logger.Error(err))\n\t\t} else {\n\t\t\tr.logger.Info(\"stopped http server successfully\")\n\t\t}\n\t}\n\n\t// close registry, deregister broker node from active list\n\tif r.registry != nil {\n\t\tr.logger.Info(\"closing discovery-registry...\")\n\t\tif err := r.registry.Deregister(r.node); err != nil {\n\t\t\tr.logger.Error(\"unregister broker node error\", logger.Error(err))\n\t\t}\n\t\tif err := r.registry.Close(); err != nil {\n\t\t\tr.logger.Error(\"unregister broker node error\", logger.Error(err))\n\t\t} else {\n\t\t\tr.logger.Info(\"closed discovery-registry successfully\")\n\t\t}\n\t}\n\n\tif r.master != nil {\n\t\tr.logger.Info(\"stopping master...\")\n\t\tr.master.Stop()\n\t}\n\n\tif r.stateMachineFactory != nil {\n\t\tr.stateMachineFactory.Stop()\n\t}\n\n\tif r.repo != nil {\n\t\tr.logger.Info(\"closing state repo...\")\n\t\tif err := r.repo.Close(); err != nil {\n\t\t\tr.logger.Error(\"close state repo error, when broker stop\", logger.Error(err))\n\t\t} else {\n\t\t\tr.logger.Info(\"closed state repo successfully\")\n\t\t}\n\t}\n\tif r.stateMgr != nil {\n\t\tr.stateMgr.Close()\n\t}\n\tif r.srv.channelManager != nil {\n\t\tr.logger.Info(\"closing write channel manager...\")\n\t\tr.srv.channelManager.Close()\n\t\tr.logger.Info(\"closed write channel successfully\")\n\t}\n\n\tif r.factory.connectionMgr != nil {\n\t\tif err := r.factory.connectionMgr.Close(); err != nil {\n\t\t\tr.logger.Error(\"close connection manager error, when broker stop\", logger.Error(err))\n\t\t} else {\n\t\t\tr.logger.Info(\"closed connection manager successfully\")\n\t\t}\n\t}\n\tr.logger.Info(\"close connections successfully\")\n\n\t// finally, shutdown rpc server\n\tif r.grpcServer != nil {\n\t\tr.logger.Info(\"stopping grpc server...\")\n\t\tr.grpcServer.Stop()\n\t\tr.logger.Info(\"stopped grpc server successfully\")\n\t}\n\n\tr.state = server.Terminated\n\tr.logger.Info(\"stopped broker server successfully\")\n}", "func Stop(kv *KVEngineSys) {\n\tckv, _ := (*C.KVEngine)(unsafe.Pointer(kv)), cgoAllocsUnknown\n\tC.kvengine_stop(ckv)\n}", "func (s *orm) Stop(ctx context.Context) {\n\ts.shutdown()\n}", "func (a API) Stop(ctx context.Context) error {\n\treturn a.srv.Shutdown(ctx)\n}", "func (d *Driver) Stop() error {\n\tif err := d.verifyRootPermissions(); err != nil {\n\t\treturn err\n\t}\n\n\ts, err := d.GetState()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif s != state.Stopped {\n\t\terr := d.sendSignal(syscall.SIGTERM)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"hyperkit sigterm failed\")\n\t\t}\n\t\t// wait 120s for graceful shutdown\n\t\tfor i := 0; i < 60; i++ {\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t\ts, _ := d.GetState()\n\t\t\tlog.Debugf(\"VM state: %s\", s)\n\t\t\tif s == state.Stopped {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn errors.New(\"VM Failed to gracefully shutdown, try the kill command\")\n\t}\n\treturn nil\n}", "func (p *Program) Stop() error {\n\tdbsrv.DBServer().Stop()\n\tqserv.QueryServer().Stop()\n\tparseserv.ParseServer().Stop()\n\tqtasks.ContentRetrievalServer().Stop()\n\tglobal.StopChromeServer()\n\tlog.Error(\"KeywordCollection·服务退出\")\n\treturn nil\n}", "func (f *RemoteRuntime) Stop() {\n\tf.server.Stop()\n}", "func (api *API) Stop() error {\n\n\t// context: wait for 3 seconds\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\terr := api.srv.Shutdown(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Stop() {\n\ts.Stop()\n}", "func Stop() {\n\t// /bin/dbus-send --system --dest=org.ganesha.nfsd --type=method_call /org/ganesha/nfsd/admin org.ganesha.nfsd.admin.shutdown\n}", "func (e *Engine) Stop() error {\n\te.Lock()\n\tdefer e.Unlock()\n\n\t// check that we aren't already stopped\n\tif !e.started {\n\t\treturn errorEngineNotStarted\n\t}\n\n\t// try to stop the stream\n\tif err := e.stream.Stop(); err != nil {\n\t\t// if it failed, return the error\n\t\treturn err\n\t}\n\t// the stream stopped successfully\n\t// flag that we aren't started anymore\n\te.started = false\n\n\t// try to close the stream\n\tif err := e.stream.Close(); err != nil {\n\t\t// if it failed, return the error\n\t\treturn err\n\t}\n\t// return without error\n\treturn nil\n}", "func (r *Reloader) Stop() error {\n\tlog.Println(\"Shutting down...\")\n\tr.quit()\n\treturn nil\n}", "func Stop() {\n\tclose(shutdownChannel)\n\tshutdownWaitGroup.Wait()\n\tlog4go.Info(\"Console shutdown complete\")\n}", "func Stop(r *registry.Registry) error {\n\treturn r.Server.Shutdown(context.Background())\n}", "func (bt *BackTest) Stop() {\n\tclose(bt.shutdown)\n}", "func (r *Redeemer) Stop() {\n\tclose(r.quit)\n\tr.server.Stop()\n}", "func (p *Program) Stop() error {\n\tvar err error\n\n\tp.htpServe.Stop()\n\n\t// 存储钱包\n\tif err = wallet.WalletService().StoreWallets(); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\t// 关闭数据库连接\n\tdatabase.CloseMysql()\n\n\tlog.Error(\"WALLET·服务退出\")\n\treturn nil\n}", "func (e *Engine) Shutdown() {\n\te.shutdown <- true\n}", "func (s *Service) Stop() {\n\ts.s.Shutdown()\n}", "func (w *Web) Stop() error {\n\tw.L(\"Stopping web server on %s:%s\", w.Address, w.Port)\n\tctx, cancel := context.WithTimeout(context.Background(), nonZeroDuration(w.Timeouts.Shutdown, time.Second*30))\n\tdefer cancel()\n\terr := w.Shutdown(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tw.running = false\n\treturn nil\n}", "func (s *Envoy) Stop() error {\n\tlog.Printf(\"Kill Envoy ...\\n\")\n\terr := s.cmd.Process.Kill()\n\tlog.Printf(\"Kill Envoy ... Done\\n\")\n\treturn err\n}", "func Stop(args ...string) {\n switch {\n case cfg.Kill:\n Kill(args...)\n default:\n runInstances(\"Stopping\", func(i int, id string) error {\n defer os.Remove(pidFileName(i))\n return run(\"stop\", id)\n })\n }\n}", "func (e *Engine) Shutdown() error {\n\treturn e.server.Shutdown(context.TODO())\n}", "func (r *Randomizer) Stop() {\n\tif !r.running {\n\t\treturn\n\t}\n\n\tclose(r.quit)\n}", "func (se *StateEngine) Stop() {\n\tse.mgrLock.Lock()\n\tdefer se.mgrLock.Unlock()\n\tif se.stopped {\n\t\treturn\n\t}\n\tfor _, m := range se.managers {\n\t\tif stopper, ok := m.(StateStopper); ok {\n\t\t\tstopper.Stop()\n\t\t}\n\t}\n\tse.stopped = true\n}", "func Stop() {\n\tdefaultManager.Stop()\n}", "func (d *Driver) Stop() error {\n\treturn nil\n}", "func (d *Dameon) Stop(closeProcs bool) {\n\td.lockfile.Unlock()\n\td.listener.Close()\n\td.pm.Shutdown(closeProcs)\n}", "func (s *Server) Stop() error {\n\ts.logger.Log(\"msg\", \"stopping\")\n\tctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancelFn()\n\n\terr := s.encoder.(system.Stoppable).Stop()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = s.mqtt.(system.Stoppable).Stop()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = s.db.Stop()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.srv.Shutdown(ctx)\n}", "func (lt *Logtailer) Stop() {\n\tclose(lt.shutdown)\n}", "func (s *Server) Stop() {\n\tclose(s.channelQuit)\n}", "func (d *Driver) Stop() error {\n\tclient, err := d.getClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn client.ShutdownVirtualMachine(d.vmName(), true)\n}", "func (b *Bootstrapper) Stop() error {\n\treturn nil\n}", "func (b *Bootstrapper) Stop() error {\n\treturn nil\n}", "func (a *Agent) Stop() {\n\tlog.Debug().\n\t\tInt(\"pid\", os.Getpid()).\n\t\tStr(\"name\", release.NAME).\n\t\tStr(\"ver\", release.VERSION).Msg(\"Stopping\")\n\n\ta.stopSignalHandler()\n\ta.groupCancel()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n\tdefer cancel()\n\terr := a.svrHTTP.Shutdown(ctx)\n\tif err != nil {\n\t\tlog.Warn().Err(err).Msg(\"closing HTTP server\")\n\t}\n}", "func (cp *ControlPlane) Stop() {\n\tcp.Repo.Close()\n\tcp.Echo.Close()\n}", "func Stop() error {\n\terr := applicationServer.Stop()\n\treturn err\n}", "func (management *Management) Stop() {\n\tlog.Info(management.logPrefix, \"Shutdown\")\n\tmanagement.closesOnce.Do(func() {\n\t\tclose(management.shutdownStarted)\n\t})\n\n\tmanagement.shutdownWaiter.Wait()\n\n\tlog.Info(management.logPrefix, \"Shutdown finished\")\n}", "func (s *svc) Stop() error {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tselect {\n\tcase <-s.exit:\n\t\treturn nil\n\tdefault:\n\t\tclose(s.exit)\n\t}\n\n\treturn nil\n}", "func (c *ClusterEtcdint) Stop() error {\n\tc.etcdsrv.Server.Stop()\n\treturn nil\n}", "func (hSvr *HTTPServer) Stop(ctx context.Context) error {\n\treturn hSvr.svr.Shutdown(ctx)\n}", "func Stop() {\n\tstopRunning <- true\n\n}", "func (c *Finalizer) Stop() {\n\tc.log.Info(\"stopping...\")\n\tc.queue.ShutDown()\n}", "func (app *App) Stop() {}", "func (p *PrivNegAPI) Stop() {\n\tif err := p.server.Shutdown(nil); err != nil {\n\t\tpanic(err)\n\t}\n}", "func Stop() {\n\tExitChannel <- true\n}", "func (ms *MarvinServer) Stop() {\n\n}", "func (srv *Server) Stop() error {\n\tif err := srv.app.Shutdown(); err != nil {\n\t\treturn err\n\t}\n\tif err := srv.config.StorageDriver.Disconnect(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *Service) Stop() {\n\tclose(s.stopChan)\n}", "func (w *Worker) Stop() {\n\tw.quit <- true\n}", "func (r *RuntimeImpl) Shutdown() {\n\tr.logger.Info(\"\\n\\n * Starting graceful shutdown\")\n\tr.logger.Info(\" * Waiting goroutines stop\")\n\tif r.slackWriter != nil {\n\t\tmessage, attachments := buildSlackShutdownMessage(r.dashboardTitle, false)\n\t\tr.slackWriter.PostNow(message, attachments)\n\t}\n\tr.syncManager.Stop()\n\tif r.impListener != nil {\n\t\tr.impListener.Stop(true)\n\t}\n\tr.appMonitor.Stop()\n\tr.servicesMonitor.Stop()\n\n\tr.logger.Info(\" * Shutdown complete - see you soon!\")\n\tr.blocker <- struct{}{}\n}", "func (c *Controller) Stop() {\n\tglog.Info(\"shutdown http service\")\n}", "func (s *Server) Stop(ctx context.Context) {\n\ts.shutdownFuncsM.Lock()\n\tdefer s.shutdownFuncsM.Unlock()\n\ts.shutdownOnce.Do(func() {\n\t\tclose(s.shuttingDown)\n\t\t// Shut down the HTTP server in parallel to calling any custom shutdown functions\n\t\twg := sync.WaitGroup{}\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tif err := s.srv.Shutdown(ctx); err != nil {\n\t\t\t\tslog.Debug(ctx, \"Graceful shutdown failed; forcibly closing connections 👢\")\n\t\t\t\tif err := s.srv.Close(); err != nil {\n\t\t\t\t\tslog.Critical(ctx, \"Forceful shutdown failed, exiting 😱: %v\", err)\n\t\t\t\t\tpanic(err) // Something is super hosed here\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\tfor _, f := range s.shutdownFuncs {\n\t\t\tf := f // capture range variable\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tf(ctx)\n\t\t\t}()\n\t\t}\n\t\twg.Wait()\n\t})\n}", "func (u *utxoNursery) Stop() error {\n\tif !atomic.CompareAndSwapUint32(&u.stopped, 0, 1) {\n\t\treturn nil\n\t}\n\n\tutxnLog.Infof(\"UTXO nursery shutting down\")\n\n\tclose(u.quit)\n\tu.wg.Wait()\n\n\treturn nil\n}", "func (oc *OSRMConnector) Stop() {\n\t// todo\n}", "func Stop() {\n\tdriver.Stop()\n}", "func (ms *MesosCluster) Stop() {\n\n\tblog.Info(\"mesos cluster stop ...\")\n\tblog.Info(\"MesosCluster stop app watcher...\")\n\tms.app.stop()\n\tblog.Info(\"MesosCluster stop taskgroup watcher...\")\n\tms.taskGroup.stop()\n\tblog.Info(\"MesosCluster stop exportsvr watcher...\")\n\tms.exportSvr.stop()\n\n\tif ms.cancel != nil {\n\t\tms.cancel()\n\t}\n\tclose(ms.stopCh)\n\ttime.Sleep(2 * time.Second)\n\n\tif ms.client != nil {\n\t\tms.client.Close()\n\t\tms.client = nil\n\t}\n}", "func (s *MockMetricsServer) Stop() {\n\t_ = s.e.Close()\n}", "func (m *modules) Stop() {\n\tm.keyboard.Stop()\n\tm.dspEngine.Stop()\n}", "func (w *Whisper) Stop() error {\n\tclose(w.quit)\n\tlog.Info(\"whisper stopped\")\n\treturn nil\n}", "func (r *EtcdResolver) Stop() {\n\tr.Close()\n}", "func (b *Backend) Stop() error {\n\tb.eventSock.Close()\n\tb.commandSock.Close()\n\n\tb.eventSockCancel()\n\tb.commandSockCancel()\n\n\treturn nil\n}", "func Stop() error {\r\n\tlog.Logf(\"Stopping server\")\r\n\treturn DefaultServer.Stop()\r\n}", "func (m *Manager) Stop() error {\n\tselect {\n\tcase <-m.quit:\n\t\treturn errors.New(\"already stopped\")\n\tdefault:\n\t\tclose(m.quit)\n\t}\n\n\t// stop running sessions\n\tm.sessions.Range(func(k, v interface{}) bool {\n\t\twrap := v.(*container)\n\t\twrap.rmLock.Lock()\n\t\tses := wrap.ses\n\t\twrap.rmLock.Unlock()\n\n\t\tif ses != nil {\n\t\t\tses.stop(mqttp.CodeServerShuttingDown)\n\t\t} else {\n\t\t\tm.sessionsCount.Done()\n\t\t}\n\n\t\texp := wrap.expiry.Load()\n\t\tif exp != nil {\n\t\t\te := exp.(*expiry)\n\t\t\tif !e.cancel() {\n\t\t\t\t_ = m.persistence.ExpiryStore([]byte(k.(string)), e.persistedState())\n\t\t\t} else {\n\t\t\t\tm.expiryCount.Done()\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t})\n\n\tm.sessionsCount.Wait()\n\tm.expiryCount.Wait()\n\n\treturn nil\n}", "func (m *Manager) Stop() {\n\tdefer close(m.done)\n\n\tif m.shutdownFunc == nil {\n\t\treturn\n\t}\n\n\tif err := m.shutdownFunc(); err != nil {\n\t\tlevel.Error(m.logger).Log(\"msg\", \"failed to shut down the tracer provider\", \"err\", err)\n\t}\n\n\tlevel.Info(m.logger).Log(\"msg\", \"Tracing manager stopped\")\n}", "func (s *Server) Stop() {\n\ts.cmd.Process.Kill()\n\tos.RemoveAll(s.DataDir)\n}", "func (t *target) Stop(err error) {\n\tif !daemon.stopping.Load() {\n\t\t// vs metasync\n\t\tt.regstate.mu.Lock()\n\t\tdaemon.stopping.Store(true)\n\t\tt.regstate.mu.Unlock()\n\t}\n\tif err == nil {\n\t\tnlog.Infoln(\"Stopping \" + t.String())\n\t} else {\n\t\tnlog.Warningf(\"Stopping %s: %v\", t, err)\n\t}\n\txreg.AbortAll(err)\n\tt.htrun.stop(t.netServ.pub.s != nil && !isErrNoUnregister(err) /*rm from Smap*/)\n}", "func (a *Agent) Stop() {\n\tclose(a.stopping)\n\ta.wg.Wait()\n}", "func (sv *Unit) Stop() (err error) {\n\tif cmd := strings.Fields(sv.Definition.Service.ExecStop); len(cmd) > 0 {\n\t\treturn exec.Command(cmd[0], cmd[1:]...).Run()\n\t}\n\tif sv.Cmd.Process != nil {\n\t\treturn sv.Cmd.Process.Kill()\n\t}\n\treturn nil\n}", "func (self *Swarm) Stop() error {\n\tself.dpa.Stop()\n\terr := self.hive.Stop()\n\tif ch := self.config.Swap.Chequebook(); ch != nil {\n\t\tch.Stop()\n\t\tch.Save()\n\t}\n\n\tif self.lstore != nil {\n\t\tself.lstore.DbStore.Close()\n\t}\n\tself.sfs.Stop()\n\tstopCounter.Inc(1)\n\treturn err\n}", "func (b *Bot) Stop() {\n\tb.rtm.Disconnect()\n}", "func (rm *RouteMachine) Stop() error {\n\treturn rm.server.Shutdown(context.Background())\n}", "func (s *LesServer) Stop() {\n\ts.fcManager.Stop()\n\ts.chtIndexer.Close()\n\t// bloom trie indexer is closed by parent bloombits indexer\n\tgo func() {\n\t\t<-s.protocolManager.noMorePeers\n\t}()\n\ts.freeClientPool.stop()\n\ts.costTracker.stop()\n\ts.protocolManager.Stop()\n\ts.csvLogger.Stop()\n}", "func (s *ServerFx) Stop() error {\n\treturn s.app.Stop(context.Background())\n}", "func (s *Server) Stop() error {\n\treturn nil\n}", "func (tr *TestRunner) Stop() {\n\tlog.Println(\"Initiating Stop in TestRunner\")\n\tclose(tr.stop)\n\t// Release the portgroup\n\ttr.pg = nil\n}", "func (s SouinApp) Stop() error {\n\treturn nil\n}", "func (s *Plugin) Stop() error {\n\treturn nil\n}", "func (c *Concentrator) Stop() {\n\tclose(c.exit)\n\tc.exitWG.Wait()\n}", "func (zc *Coordinator) Stop() error {\n\tzc.Log.Info(\"stopping\")\n\n\t// This will close the event channel, closing the mainLoop\n\tzc.App.Zookeeper.Close()\n\tzc.running.Wait()\n\n\treturn nil\n}", "func (c *Controller) Stop(ctx hive.HookContext) error {\n\tdoneChan := make(chan struct{})\n\tgo func() {\n\t\tc.workerpool.Close()\n\t\tclose(doneChan)\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase <-doneChan:\n\t}\n\n\treturn nil\n}", "func (c *Controller) Stop(ctx hive.HookContext) error {\n\tdoneChan := make(chan struct{})\n\tgo func() {\n\t\tc.workerpool.Close()\n\t\tclose(doneChan)\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase <-doneChan:\n\t}\n\n\treturn nil\n}", "func (w *Webserver) Stop() error {\n\tw.logger.Infof(\"gracefully shutting down http server at %d...\", w.config.Port)\n\n\terr := w.Server.Shutdown(context.Background())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclose(w.jobs)\n\treturn nil\n}", "func (s *Server) Stop() {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n\tdefer cancel()\n\n\ts.logger.Info(\"Shutting down\")\n\tif err := s.server.Shutdown(ctx); err != nil {\n\t\ts.logger.Errorw(\"HTTP server shutdown\",\n\t\t\t\"error\", err,\n\t\t)\n\t}\n}", "func (ts *Server) Stop() error {\n\tif ts.Server == nil {\n\t\treturn nil\n\t}\n\tif err := ts.Server.Shutdown(context.Background()); err != nil {\n\t\treturn err\n\t}\n\tts.Server = nil\n\treturn nil\n}", "func Stop() {\n\tgo mainCron.Stop()\n}", "func (m *etcdMinion) Stop() error {\n\tlog.Println(\"Minion is shutting down\")\n\n\tclose(m.taskQueue)\n\tclose(m.done)\n\n\treturn nil\n}", "func (s *Bgmchain) Stop() error {\n\tif s.stopDbUpgrade != nil {\n\t\ts.stopDbUpgrade()\n\t}\n\ts.bloomIndexer.Close()\n\ts.blockchain.Stop()\n\ts.protocolManager.Stop()\n\tif s.lesServer != nil {\n\t\ts.lesServer.Stop()\n\t}\n\ts.txPool.Stop()\n\ts.miner.Stop()\n\ts.eventMux.Stop()\n\n\ts.chainDbPtr.Close()\n\tclose(s.shutdownChan)\n\n\treturn nil\n}", "func (m *Machine) Stop() error {\n\tm.State = driver.Poweroff\n\tfmt.Printf(\"Stop %s: %s\\n\", m.Name, m.State)\n\treturn nil\n}", "func (rcsw *RemoteClusterServiceWatcher) Stop(cleanupState bool) {\n\trcsw.probeEventsSink.send(&ClusterNotRegistered{\n\t\tclusterName: rcsw.clusterName,\n\t})\n\tclose(rcsw.stopper)\n\tif cleanupState {\n\t\trcsw.eventsQueue.Add(&ClusterUnregistered{})\n\t}\n\trcsw.eventsQueue.ShutDown()\n}", "func (w *Worker) Stop() {\n\tgo func() {\n\t\tw.quit <- true\n\t}()\n}", "func (s *Server) Stop() error {\n\tif err := s.ctx.Gateway.Close(); err != nil {\n\t\treturn fmt.Errorf(\"close gateway backend error: %s\", err)\n\t}\n\tif err := s.ctx.Application.Close(); err != nil {\n\t\treturn fmt.Errorf(\"close application backend error: %s\", err)\n\t}\n\tif err := s.ctx.Controller.Close(); err != nil {\n\t\treturn fmt.Errorf(\"close network-controller backend error: %s\", err)\n\t}\n\n\tlog.Info(\"waiting for pending actions to complete\")\n\ts.wg.Wait()\n\treturn nil\n}", "func (g *GApp) Stop(ctx context.Context) {\r\n\tg.App.Shutdown(ctx)\r\n}" ]
[ "0.8119374", "0.8024512", "0.7673363", "0.7569195", "0.7498961", "0.74496645", "0.729721", "0.7241718", "0.72293586", "0.71640617", "0.7073136", "0.70670533", "0.7035117", "0.70122164", "0.6990118", "0.69852245", "0.6978263", "0.6965461", "0.6890941", "0.6878703", "0.6846897", "0.6838789", "0.6823636", "0.6802751", "0.6783017", "0.6781692", "0.67451185", "0.6739672", "0.67343366", "0.67305684", "0.672447", "0.6722379", "0.67189693", "0.6711266", "0.67087793", "0.6700544", "0.669039", "0.6686495", "0.66839415", "0.66784376", "0.66784376", "0.66745955", "0.66476303", "0.6645824", "0.6641677", "0.663753", "0.6626228", "0.6621034", "0.66181403", "0.66112083", "0.6610633", "0.66043985", "0.6600263", "0.6591511", "0.65786844", "0.65756416", "0.65733856", "0.6571516", "0.65696174", "0.65685153", "0.6568218", "0.6566027", "0.6562878", "0.65624875", "0.6559031", "0.6558999", "0.6553386", "0.6550542", "0.6546529", "0.6542282", "0.6541435", "0.65385395", "0.65377855", "0.6537565", "0.65350103", "0.6530881", "0.6526858", "0.6525428", "0.6520748", "0.6520301", "0.6514642", "0.6510277", "0.6509472", "0.64964086", "0.64963925", "0.6491909", "0.6491205", "0.6486174", "0.6486174", "0.64729637", "0.64729226", "0.64718825", "0.6469806", "0.64693874", "0.64623666", "0.64562696", "0.6452479", "0.6452111", "0.64499474", "0.6449608" ]
0.74494004
6
NEW: This method is only available in solanacore v1.7 or newer. Please use getConfirmedBlocks for solanacore v1.6 GetBlocks returns a list of confirmed blocks between two slots Max range allowed is 500,000 slot
func (c *RpcClient) GetBlocks(ctx context.Context, startSlot uint64, endSlot uint64) (GetBlocksResponse, error) { return c.processGetBlocks(c.Call(ctx, "getBlocks", startSlot, endSlot)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *RpcClient) GetConfirmedBlocks(ctx context.Context, startSlot uint64, endSlot uint64) ([]uint64, error) {\n\tres := struct {\n\t\tGeneralResponse\n\t\tResult []uint64 `json:\"result\"`\n\t}{}\n\terr := s.request(ctx, \"getConfirmedBlocks\", []interface{}{startSlot, endSlot}, &res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res.Result, nil\n}", "func (lp *logPoller) GetBlocksRange(ctx context.Context, numbers []uint64, qopts ...pg.QOpt) ([]LogPollerBlock, error) {\n\tvar blocks []LogPollerBlock\n\n\t// Do nothing if no blocks are requested.\n\tif len(numbers) == 0 {\n\t\treturn blocks, nil\n\t}\n\n\t// Assign the requested blocks to a mapping.\n\tblocksRequested := make(map[uint64]struct{})\n\tfor _, b := range numbers {\n\t\tblocksRequested[b] = struct{}{}\n\t}\n\n\t// Retrieve all blocks within this range from the log poller.\n\tblocksFound := make(map[uint64]LogPollerBlock)\n\tqopts = append(qopts, pg.WithParentCtx(ctx))\n\tminRequestedBlock := mathutil.Min(numbers[0], numbers[1:]...)\n\tmaxRequestedBlock := mathutil.Max(numbers[0], numbers[1:]...)\n\tlpBlocks, err := lp.orm.GetBlocksRange(minRequestedBlock, maxRequestedBlock, qopts...)\n\tif err != nil {\n\t\tlp.lggr.Warnw(\"Error while retrieving blocks from log pollers blocks table. Falling back to RPC...\", \"requestedBlocks\", numbers, \"err\", err)\n\t} else {\n\t\tfor _, b := range lpBlocks {\n\t\t\tif _, ok := blocksRequested[uint64(b.BlockNumber)]; ok {\n\t\t\t\t// Only fill requested blocks.\n\t\t\t\tblocksFound[uint64(b.BlockNumber)] = b\n\t\t\t}\n\t\t}\n\t\tlp.lggr.Debugw(\"Got blocks from log poller\", \"blockNumbers\", maps.Keys(blocksFound))\n\t}\n\n\t// Fill any remaining blocks from the client.\n\tblocksFoundFromRPC, err := lp.fillRemainingBlocksFromRPC(ctx, numbers, blocksFound)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor num, b := range blocksFoundFromRPC {\n\t\tblocksFound[num] = b\n\t}\n\n\tvar blocksNotFound []uint64\n\tfor _, num := range numbers {\n\t\tb, ok := blocksFound[num]\n\t\tif !ok {\n\t\t\tblocksNotFound = append(blocksNotFound, num)\n\t\t}\n\t\tblocks = append(blocks, b)\n\t}\n\n\tif len(blocksNotFound) > 0 {\n\t\treturn nil, errors.Errorf(\"blocks were not found in db or RPC call: %v\", blocksNotFound)\n\t}\n\n\treturn blocks, nil\n}", "func (nc *NSBClient) GetBlocks(rangeL, rangeR int64) (*BlocksInfo, error) {\n\tb, err := nc.handler.Group(\"/blockchain\").GetWithParams(request.Param{\n\t\t\"minHeight\": rangeL,\n\t\t\"maxHeight\": rangeR,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar bb []byte\n\tbb, err = nc.preloadJSONResponse(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar a BlocksInfo\n\terr = json.Unmarshal(bb, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &a, nil\n}", "func (core *coreService) RawBlocks(startHeight uint64, count uint64, withReceipts bool, withTransactionLogs bool) ([]*iotexapi.BlockInfo, error) {\n\tif count == 0 || count > core.cfg.RangeQueryLimit {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"range exceeds the limit\")\n\t}\n\n\ttipHeight := core.bc.TipHeight()\n\tif startHeight > tipHeight {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"start height should not exceed tip height\")\n\t}\n\tendHeight := startHeight + count - 1\n\tif endHeight > tipHeight {\n\t\tendHeight = tipHeight\n\t}\n\tvar res []*iotexapi.BlockInfo\n\tfor height := startHeight; height <= endHeight; height++ {\n\t\tblk, err := core.dao.GetBlockByHeight(height)\n\t\tif err != nil {\n\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t}\n\t\tvar receiptsPb []*iotextypes.Receipt\n\t\tif withReceipts && height > 0 {\n\t\t\treceipts, err := core.dao.GetReceipts(height)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t\t}\n\t\t\tfor _, receipt := range receipts {\n\t\t\t\treceiptsPb = append(receiptsPb, receipt.ConvertToReceiptPb())\n\t\t\t}\n\t\t}\n\t\tvar transactionLogs *iotextypes.TransactionLogs\n\t\tif withTransactionLogs {\n\t\t\tif transactionLogs, err = core.dao.TransactionLogs(height); err != nil {\n\t\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t\t}\n\t\t}\n\t\tres = append(res, &iotexapi.BlockInfo{\n\t\t\tBlock: blk.ConvertToBlockPb(),\n\t\t\tReceipts: receiptsPb,\n\t\t\tTransactionLogs: transactionLogs,\n\t\t})\n\t}\n\treturn res, nil\n}", "func (synckerManager *SynckerManager) GetS2BBlocksForBeaconValidator(bestViewShardHash map[byte]common.Hash, list map[byte][]common.Hash) (map[byte][]interface{}, error) {\n\ts2bPoolLists := synckerManager.GetS2BBlocksForBeaconProducer(bestViewShardHash, list)\n\n\tmissingBlocks := compareLists(s2bPoolLists, list)\n\t// synckerManager.config.Server.\n\tif len(missingBlocks) > 0 {\n\t\tctx, _ := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tsynckerManager.StreamMissingShardToBeaconBlock(ctx, missingBlocks)\n\t\t//fmt.Println(\"debug finish stream missing s2b block\")\n\n\t\ts2bPoolLists = synckerManager.GetS2BBlocksForBeaconProducer(bestViewShardHash, list)\n\t\tmissingBlocks = compareLists(s2bPoolLists, list)\n\t\tif len(missingBlocks) > 0 {\n\t\t\treturn nil, errors.New(\"Unable to sync required block in time\")\n\t\t}\n\t}\n\n\tfor sid, heights := range list {\n\t\tif len(s2bPoolLists[sid]) != len(heights) {\n\t\t\treturn nil, fmt.Errorf(\"S2BPoolLists not match sid:%v pool:%v producer:%v\", sid, len(s2bPoolLists[sid]), len(heights))\n\t\t}\n\t}\n\n\treturn s2bPoolLists, nil\n}", "func (gw *Gateway) GetBlocksInRange(start, end uint64) ([]coin.SignedBlock, error) {\n\tvar blocks []coin.SignedBlock\n\tvar err error\n\tgw.strand(\"GetBlocksInRange\", func() {\n\t\tblocks, err = gw.v.GetBlocksInRange(start, end)\n\t})\n\treturn blocks, err\n}", "func consensusBlocksGetFromBlock(b types.Block, h types.BlockHeight) ConsensusBlocksGet {\n\ttxns := make([]ConsensusBlocksGetTxn, 0, len(b.Transactions))\n\tfor _, t := range b.Transactions {\n\t\t// Get the transaction's SiacoinOutputs.\n\t\tscos := make([]ConsensusBlocksGetSiacoinOutput, 0, len(t.SiacoinOutputs))\n\t\tfor i, sco := range t.SiacoinOutputs {\n\t\t\tscos = append(scos, ConsensusBlocksGetSiacoinOutput{\n\t\t\t\tID: t.SiacoinOutputID(uint64(i)),\n\t\t\t\tValue: sco.Value,\n\t\t\t\tUnlockHash: sco.UnlockHash,\n\t\t\t})\n\t\t}\n\t\t// Get the transaction's SiafundOutputs.\n\t\tsfos := make([]ConsensusBlocksGetSiafundOutput, 0, len(t.SiafundOutputs))\n\t\tfor i, sfo := range t.SiafundOutputs {\n\t\t\tsfos = append(sfos, ConsensusBlocksGetSiafundOutput{\n\t\t\t\tID: t.SiafundOutputID(uint64(i)),\n\t\t\t\tValue: sfo.Value,\n\t\t\t\tUnlockHash: sfo.UnlockHash,\n\t\t\t})\n\t\t}\n\t\t// Get the transaction's FileContracts.\n\t\tfcos := make([]ConsensusBlocksGetFileContract, 0, len(t.FileContracts))\n\t\tfor i, fc := range t.FileContracts {\n\t\t\t// Get the FileContract's valid proof outputs.\n\t\t\tfcid := t.FileContractID(uint64(i))\n\t\t\tvpos := make([]ConsensusBlocksGetSiacoinOutput, 0, len(fc.ValidProofOutputs))\n\t\t\tfor j, vpo := range fc.ValidProofOutputs {\n\t\t\t\tvpos = append(vpos, ConsensusBlocksGetSiacoinOutput{\n\t\t\t\t\tID: fcid.StorageProofOutputID(types.ProofValid, uint64(j)),\n\t\t\t\t\tValue: vpo.Value,\n\t\t\t\t\tUnlockHash: vpo.UnlockHash,\n\t\t\t\t})\n\t\t\t}\n\t\t\t// Get the FileContract's missed proof outputs.\n\t\t\tmpos := make([]ConsensusBlocksGetSiacoinOutput, 0, len(fc.MissedProofOutputs))\n\t\t\tfor j, mpo := range fc.MissedProofOutputs {\n\t\t\t\tmpos = append(mpos, ConsensusBlocksGetSiacoinOutput{\n\t\t\t\t\tID: fcid.StorageProofOutputID(types.ProofMissed, uint64(j)),\n\t\t\t\t\tValue: mpo.Value,\n\t\t\t\t\tUnlockHash: mpo.UnlockHash,\n\t\t\t\t})\n\t\t\t}\n\t\t\tfcos = append(fcos, ConsensusBlocksGetFileContract{\n\t\t\t\tID: fcid,\n\t\t\t\tFileSize: fc.FileSize,\n\t\t\t\tFileMerkleRoot: fc.FileMerkleRoot,\n\t\t\t\tWindowStart: fc.WindowStart,\n\t\t\t\tWindowEnd: fc.WindowEnd,\n\t\t\t\tPayout: fc.Payout,\n\t\t\t\tValidProofOutputs: vpos,\n\t\t\t\tMissedProofOutputs: mpos,\n\t\t\t\tUnlockHash: fc.UnlockHash,\n\t\t\t\tRevisionNumber: fc.RevisionNumber,\n\t\t\t})\n\t\t}\n\t\ttxns = append(txns, ConsensusBlocksGetTxn{\n\t\t\tID: t.ID(),\n\t\t\tSiacoinInputs: t.SiacoinInputs,\n\t\t\tSiacoinOutputs: scos,\n\t\t\tFileContracts: fcos,\n\t\t\tFileContractRevisions: t.FileContractRevisions,\n\t\t\tStorageProofs: t.StorageProofs,\n\t\t\tSiafundInputs: t.SiafundInputs,\n\t\t\tSiafundOutputs: sfos,\n\t\t\tMinerFees: t.MinerFees,\n\t\t\tArbitraryData: t.ArbitraryData,\n\t\t\tTransactionSignatures: t.TransactionSignatures,\n\t\t})\n\t}\n\treturn ConsensusBlocksGet{\n\t\tID: b.ID(),\n\t\tHeight: h,\n\t\tParentID: b.ParentID,\n\t\tNonce: b.Nonce,\n\t\tTimestamp: b.Timestamp,\n\t\tMinerPayouts: b.MinerPayouts,\n\t\tTransactions: txns,\n\t}\n}", "func GetBlockConfirmations() uint64 {\n\n\tconfirmationCount := Get(\"BlockConfirmations\")\n\tif confirmationCount == \"\" {\n\t\treturn 0\n\t}\n\n\tparsedConfirmationCount, err := strconv.ParseUint(confirmationCount, 10, 64)\n\tif err != nil {\n\t\tlog.Printf(\"[!] Failed to parse block confirmations : %s\\n\", err.Error())\n\t\treturn 0\n\t}\n\n\treturn parsedConfirmationCount\n\n}", "func (db *Database) QueryBlocks(before int, after int, limit int) ([]schema.Block, error) {\n\tblocks := make([]schema.Block, 0)\n\n\tvar err error\n\n\tswitch {\n\tcase before > 0:\n\t\terr = db.Model(&blocks).\n\t\t\tWhere(\"height < ?\", before).\n\t\t\tLimit(limit).\n\t\t\tOrder(\"id DESC\").\n\t\t\tSelect()\n\tcase after >= 0:\n\t\terr = db.Model(&blocks).\n\t\t\tWhere(\"height > ?\", after).\n\t\t\tLimit(limit).\n\t\t\tOrder(\"id ASC\").\n\t\t\tSelect()\n\tdefault:\n\t\terr = db.Model(&blocks).\n\t\t\tLimit(limit).\n\t\t\tOrder(\"id DESC\").\n\t\t\tSelect()\n\t}\n\n\tif err == pg.ErrNoRows {\n\t\treturn blocks, fmt.Errorf(\"no rows in block table: %s\", err)\n\t}\n\n\tif err != nil {\n\t\treturn blocks, fmt.Errorf(\"unexpected database error: %s\", err)\n\t}\n\n\treturn blocks, nil\n}", "func (b *logEventBuffer) getBlocksInRange(start, end int) []fetchedBlock {\n\tvar blocksInRange []fetchedBlock\n\tstart, end = b.normalRange(start, end)\n\tif start == -1 || end == -1 {\n\t\t// invalid range\n\t\treturn blocksInRange\n\t}\n\tif start < end {\n\t\treturn b.blocks[start:end]\n\t}\n\t// in case we get circular range such as [0, 1, end, ... , start, ..., size-1]\n\t// we need to return the blocks in two ranges: [start, size-1] and [0, end]\n\tblocksInRange = append(blocksInRange, b.blocks[start:]...)\n\tblocksInRange = append(blocksInRange, b.blocks[:end]...)\n\n\treturn blocksInRange\n}", "func (c *RPCClient) FilterBlocks(\n\treq *FilterBlocksRequest) (*FilterBlocksResponse, er.R) {\n\n\tblockFilterer := NewBlockFilterer(c.chainParams, req)\n\n\t// Construct the watchlist using the addresses and outpoints contained\n\t// in the filter blocks request.\n\twatchList, err := buildFilterBlocksWatchList(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Iterate over the requested blocks, fetching the compact filter for\n\t// each one, and matching it against the watchlist generated above. If\n\t// the filter returns a positive match, the full block is then requested\n\t// and scanned for addresses using the block filterer.\n\tfor i, blk := range req.Blocks {\n\t\trawFilter, err := c.GetCFilter(&blk.Hash, wire.GCSFilterRegular)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Ensure the filter is large enough to be deserialized.\n\t\tif len(rawFilter.Data) < 4 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfilter, err := gcs.FromNBytes(\n\t\t\tbuilder.DefaultP, builder.DefaultM, rawFilter.Data,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Skip any empty filters.\n\t\tif filter.N() == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tkey := builder.DeriveKey(&blk.Hash)\n\t\tmatched, err := filter.MatchAny(key, watchList)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t} else if !matched {\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Infof(\"Fetching block height=%d hash=%v\",\n\t\t\tblk.Height, blk.Hash)\n\n\t\trawBlock, err := c.GetBlock(&blk.Hash)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !blockFilterer.FilterBlock(rawBlock) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// If any external or internal addresses were detected in this\n\t\t// block, we return them to the caller so that the rescan\n\t\t// windows can widened with subsequent addresses. The\n\t\t// `BatchIndex` is returned so that the caller can compute the\n\t\t// *next* block from which to begin again.\n\t\tresp := &FilterBlocksResponse{\n\t\t\tBatchIndex: uint32(i),\n\t\t\tBlockMeta: blk,\n\t\t\tFoundExternalAddrs: blockFilterer.FoundExternal,\n\t\t\tFoundInternalAddrs: blockFilterer.FoundInternal,\n\t\t\tFoundOutPoints: blockFilterer.FoundOutPoints,\n\t\t\tRelevantTxns: blockFilterer.RelevantTxns,\n\t\t}\n\n\t\treturn resp, nil\n\t}\n\n\t// No addresses were found for this range.\n\treturn nil, nil\n}", "func (m *GetBlocksMessage) GetBlockLocator() []*bc.Hash {\n\tblockLocator := []*bc.Hash{}\n\tfor _, rawHash := range m.RawBlockLocator {\n\t\thash := bc.NewHash(rawHash)\n\t\tblockLocator = append(blockLocator, &hash)\n\t}\n\treturn blockLocator\n}", "func (dcr *ExchangeWallet) checkForNewBlocks() {\n\tctx, cancel := context.WithTimeout(dcr.ctx, 2*time.Second)\n\tdefer cancel()\n\tnewTip, err := dcr.getBestBlock(ctx)\n\tif err != nil {\n\t\tdcr.tipChange(fmt.Errorf(\"failed to get best block: %w\", err))\n\t\treturn\n\t}\n\n\t// This method is called frequently. Don't hold write lock\n\t// unless tip has changed.\n\tdcr.tipMtx.RLock()\n\tsameTip := dcr.currentTip.hash.IsEqual(newTip.hash)\n\tdcr.tipMtx.RUnlock()\n\tif sameTip {\n\t\treturn\n\t}\n\n\tdcr.tipMtx.Lock()\n\tdefer dcr.tipMtx.Unlock()\n\n\tprevTip := dcr.currentTip\n\tdcr.currentTip = newTip\n\tdcr.log.Debugf(\"tip change: %d (%s) => %d (%s)\", prevTip.height, prevTip.hash, newTip.height, newTip.hash)\n\tdcr.tipChange(nil)\n\n\t// Search for contract redemption in new blocks if there\n\t// are contracts pending redemption.\n\tdcr.findRedemptionMtx.RLock()\n\tpendingContractsCount := len(dcr.findRedemptionQueue)\n\tcontractOutpoints := make([]outPoint, 0, pendingContractsCount)\n\tfor contractOutpoint := range dcr.findRedemptionQueue {\n\t\tcontractOutpoints = append(contractOutpoints, contractOutpoint)\n\t}\n\tdcr.findRedemptionMtx.RUnlock()\n\tif pendingContractsCount == 0 {\n\t\treturn\n\t}\n\n\t// Use the previous tip hash to determine the starting point for\n\t// the redemption search. If there was a re-org, the starting point\n\t// would be the common ancestor of the previous tip and the new tip.\n\t// Otherwise, the starting point would be the block at previous tip\n\t// height + 1.\n\tvar startPoint *block\n\tvar startPointErr error\n\tprevTipBlock, err := dcr.node.GetBlockVerbose(dcr.ctx, prevTip.hash, false)\n\tswitch {\n\tcase err != nil:\n\t\tstartPointErr = fmt.Errorf(\"getBlockHeader error for prev tip hash %s: %w\", prevTip.hash, translateRPCCancelErr(err))\n\tcase prevTipBlock.Confirmations < 0:\n\t\t// There's been a re-org, common ancestor will be height\n\t\t// plus negative confirmation e.g. 155 + (-3) = 152.\n\t\treorgHeight := prevTipBlock.Height + prevTipBlock.Confirmations\n\t\tdcr.log.Debugf(\"reorg detected from height %d to %d\", reorgHeight, newTip.height)\n\t\treorgHash, err := dcr.node.GetBlockHash(dcr.ctx, reorgHeight)\n\t\tif err != nil {\n\t\t\tstartPointErr = fmt.Errorf(\"getBlockHash error for reorg height %d: %w\", reorgHeight, translateRPCCancelErr(err))\n\t\t} else {\n\t\t\tstartPoint = &block{hash: reorgHash, height: reorgHeight}\n\t\t}\n\tcase newTip.height-prevTipBlock.Height > 1:\n\t\t// 2 or more blocks mined since last tip, start at prevTip height + 1.\n\t\tafterPrivTip := prevTipBlock.Height + 1\n\t\thashAfterPrevTip, err := dcr.node.GetBlockHash(dcr.ctx, afterPrivTip)\n\t\tif err != nil {\n\t\t\tstartPointErr = fmt.Errorf(\"getBlockHash error for height %d: %w\", afterPrivTip, translateRPCCancelErr(err))\n\t\t} else {\n\t\t\tstartPoint = &block{hash: hashAfterPrevTip, height: afterPrivTip}\n\t\t}\n\tdefault:\n\t\t// Just 1 new block since last tip report, search the lone block.\n\t\tstartPoint = newTip\n\t}\n\n\t// Redemption search would be compromised if the starting point cannot\n\t// be determined, as searching just the new tip might result in blocks\n\t// being omitted from the search operation. If that happens, cancel all\n\t// find redemption requests in queue.\n\tif startPointErr != nil {\n\t\tdcr.fatalFindRedemptionsError(fmt.Errorf(\"new blocks handler error: %w\", startPointErr), contractOutpoints)\n\t} else {\n\t\tgo dcr.findRedemptionsInBlockRange(startPoint, newTip, contractOutpoints)\n\t}\n}", "func (m *BlocksMessage) GetBlocks() ([]*types.Block, error) {\n\tblocks := []*types.Block{}\n\tfor _, data := range m.RawBlocks {\n\t\tblock := &types.Block{}\n\t\tif err := json.Unmarshal(data, block); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tblocks = append(blocks, block)\n\t}\n\treturn blocks, nil\n}", "func (c *RpcClient) GetBlocksWithConfig(ctx context.Context, startSlot uint64, endSlot uint64, cfg GetBlocksConfig) (GetBlocksResponse, error) {\n\treturn c.processGetBlocks(c.Call(ctx, \"getBlocks\", startSlot, endSlot, cfg))\n}", "func (s *Service) GetExplorerBlocks(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfrom := r.FormValue(\"from\")\n\tto := r.FormValue(\"to\")\n\tpageParam := r.FormValue(\"page\")\n\toffsetParam := r.FormValue(\"offset\")\n\torder := r.FormValue(\"order\")\n\tdata := &Data{\n\t\tBlocks: []*Block{},\n\t}\n\tdefer func() {\n\t\tif err := json.NewEncoder(w).Encode(data.Blocks); err != nil {\n\t\t\tutils.Logger().Warn().Err(err).Msg(\"cannot JSON-encode blocks\")\n\t\t}\n\t}()\n\n\tif from == \"\" {\n\t\tutils.Logger().Warn().Msg(\"Missing from parameter\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tdb := s.Storage.GetDB()\n\tfromInt, err := strconv.Atoi(from)\n\tif err != nil {\n\t\tutils.Logger().Warn().Err(err).Msg(\"invalid from parameter\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tvar toInt int\n\tif to == \"\" {\n\t\ttoInt, err = func() (int, error) {\n\t\t\tbytes, err := db.Get([]byte(BlockHeightKey))\n\t\t\tif err == nil {\n\t\t\t\treturn strconv.Atoi(string(bytes))\n\t\t\t}\n\t\t\treturn toInt, err\n\t\t}()\n\t} else {\n\t\ttoInt, err = strconv.Atoi(to)\n\t}\n\tif err != nil {\n\t\tutils.Logger().Warn().Err(err).Msg(\"invalid to parameter\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tvar offset int\n\tif offsetParam != \"\" {\n\t\toffset, err = strconv.Atoi(offsetParam)\n\t\tif err != nil || offset < 1 {\n\t\t\tutils.Logger().Warn().Msg(\"invalid offset parameter\")\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\toffset = paginationOffset\n\t}\n\tvar page int\n\tif pageParam != \"\" {\n\t\tpage, err = strconv.Atoi(pageParam)\n\t\tif err != nil {\n\t\t\tutils.Logger().Warn().Err(err).Msg(\"invalid page parameter\")\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tpage = 0\n\t}\n\n\taccountBlocks := s.ReadBlocksFromDB(fromInt, toInt)\n\tfor id, accountBlock := range accountBlocks {\n\t\tif id == 0 || id == len(accountBlocks)-1 || accountBlock == nil {\n\t\t\tcontinue\n\t\t}\n\t\tblock := NewBlock(accountBlock, id+fromInt-1)\n\t\t// Populate transactions\n\t\tfor _, tx := range accountBlock.Transactions() {\n\t\t\ttransaction := GetTransaction(tx, accountBlock)\n\t\t\tif transaction != nil {\n\t\t\t\tblock.TXs = append(block.TXs, transaction)\n\t\t\t}\n\t\t}\n\t\tif accountBlocks[id-1] == nil {\n\t\t\tblock.BlockTime = int64(0)\n\t\t\tblock.PrevBlock = RefBlock{\n\t\t\t\tID: \"\",\n\t\t\t\tHeight: \"\",\n\t\t\t}\n\t\t} else {\n\t\t\tblock.BlockTime = accountBlock.Time().Int64() - accountBlocks[id-1].Time().Int64()\n\t\t\tblock.PrevBlock = RefBlock{\n\t\t\t\tID: accountBlocks[id-1].Hash().Hex(),\n\t\t\t\tHeight: strconv.Itoa(id + fromInt - 2),\n\t\t\t}\n\t\t}\n\t\tif accountBlocks[id+1] == nil {\n\t\t\tblock.NextBlock = RefBlock{\n\t\t\t\tID: \"\",\n\t\t\t\tHeight: \"\",\n\t\t\t}\n\t\t} else {\n\t\t\tblock.NextBlock = RefBlock{\n\t\t\t\tID: accountBlocks[id+1].Hash().Hex(),\n\t\t\t\tHeight: strconv.Itoa(id + fromInt),\n\t\t\t}\n\t\t}\n\t\tdata.Blocks = append(data.Blocks, block)\n\t}\n\tif offset*page >= len(data.Blocks) {\n\t\tdata.Blocks = []*Block{}\n\t} else if offset*page+offset > len(data.Blocks) {\n\t\tdata.Blocks = data.Blocks[offset*page:]\n\t} else {\n\t\tdata.Blocks = data.Blocks[offset*page : offset*page+offset]\n\t}\n\tif order == \"DESC\" {\n\t\tsort.Slice(data.Blocks[:], func(i, j int) bool {\n\t\t\treturn data.Blocks[i].Timestamp > data.Blocks[j].Timestamp\n\t\t})\n\t} else {\n\t\tsort.Slice(data.Blocks[:], func(i, j int) bool {\n\t\t\treturn data.Blocks[i].Timestamp < data.Blocks[j].Timestamp\n\t\t})\n\t}\n}", "func (core *coreService) BlockByHeightRange(start uint64, count uint64) ([]*apitypes.BlockWithReceipts, error) {\n\tif count == 0 {\n\t\treturn nil, errors.Wrap(errInvalidFormat, \"count must be greater than zero\")\n\t}\n\tif count > core.cfg.RangeQueryLimit {\n\t\treturn nil, errors.Wrap(errInvalidFormat, \"range exceeds the limit\")\n\t}\n\n\tvar (\n\t\ttipHeight = core.bc.TipHeight()\n\t\tres = make([]*apitypes.BlockWithReceipts, 0)\n\t)\n\tif start > tipHeight {\n\t\treturn nil, errors.Wrap(errInvalidFormat, \"start height should not exceed tip height\")\n\t}\n\tfor height := start; height <= tipHeight && count > 0; height++ {\n\t\tblkStore, err := core.getBlockByHeight(height)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tres = append(res, blkStore)\n\t\tcount--\n\t}\n\treturn res, nil\n}", "func (c *Client) GetBlocks(ctx context.Context, pg *Pagination) ([]*Account, error) {\n\tvar accounts []*Account\n\terr := c.doAPI(ctx, http.MethodGet, \"/api/v1/blocks\", nil, &accounts, pg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn accounts, nil\n}", "func (p *pool) SyncBlocks(ctx context.Context) error {\n\tap := &coilv2.AddressPool{}\n\terr := p.client.Get(ctx, client.ObjectKey{Name: p.name}, ap)\n\tif err != nil {\n\t\tp.log.Error(err, \"failed to get AddressPool\")\n\t\treturn err\n\t}\n\n\tvar maxBlocks int\n\tfor _, sub := range ap.Spec.Subnets {\n\t\tvar n *net.IPNet\n\t\tif sub.IPv4 != nil {\n\t\t\t_, n, _ = net.ParseCIDR(*sub.IPv4)\n\t\t} else {\n\t\t\t_, n, _ = net.ParseCIDR(*sub.IPv6)\n\t\t}\n\t\tones, bits := n.Mask.Size()\n\t\tmaxBlocks += 1 << (bits - ones - int(ap.Spec.BlockSizeBits))\n\t}\n\tp.maxBlocks.Set(float64(maxBlocks))\n\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\tp.allocated.ClearAll()\n\tblocks := &coilv2.AddressBlockList{}\n\terr = p.reader.List(ctx, blocks, client.MatchingLabels{\n\t\tconstants.LabelPool: p.name,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar allocatedBlocks int\n\tfor _, b := range blocks.Items {\n\t\tp.allocated.Set(uint(b.Index))\n\t\tallocatedBlocks += 1\n\t}\n\tp.allocatedBlocks.Set(float64(allocatedBlocks))\n\n\tp.log.Info(\"resynced block usage\", \"blocks\", len(blocks.Items))\n\treturn nil\n}", "func (dcr *ExchangeWallet) monitorBlocks(ctx context.Context) {\n\tticker := time.NewTicker(blockTicker)\n\tdefer ticker.Stop()\n\n\tvar walletBlock <-chan *block\n\tif notifier, isNotifier := dcr.wallet.(tipNotifier); isNotifier {\n\t\twalletBlock = notifier.tipFeed()\n\t}\n\n\t// A polledBlock is a block found during polling, but whose broadcast has\n\t// been queued in anticipation of a wallet notification.\n\ttype polledBlock struct {\n\t\t*block\n\t\tqueue *time.Timer\n\t}\n\n\t// queuedBlock is the currently queued, polling-discovered block that will\n\t// be broadcast after a timeout if the wallet doesn't send the matching\n\t// notification.\n\tvar queuedBlock *polledBlock\n\n\t// checkTip captures queuedBlock and walletBlock.\n\tcheckTip := func() {\n\t\tctx, cancel := context.WithTimeout(dcr.ctx, 4*time.Second)\n\t\tdefer cancel()\n\n\t\tnewTip, err := dcr.getBestBlock(ctx)\n\t\tif err != nil {\n\t\t\tdcr.handleTipChange(nil, 0, fmt.Errorf(\"failed to get best block: %w\", err))\n\t\t\treturn\n\t\t}\n\n\t\tdcr.tipMtx.RLock()\n\t\tsameTip := dcr.currentTip.hash.IsEqual(newTip.hash)\n\t\tdcr.tipMtx.RUnlock()\n\n\t\tif sameTip {\n\t\t\treturn\n\t\t}\n\n\t\tif walletBlock == nil {\n\t\t\tdcr.handleTipChange(newTip.hash, newTip.height, nil)\n\t\t\treturn\n\t\t}\n\n\t\t// Queue it for reporting, but don't send it right away. Give the wallet\n\t\t// a chance to provide their block update. SPV wallet may need more time\n\t\t// after storing the block header to fetch and scan filters and issue\n\t\t// the FilteredBlockConnected report.\n\t\tif queuedBlock != nil {\n\t\t\tqueuedBlock.queue.Stop()\n\t\t}\n\t\tblockAllowance := walletBlockAllowance\n\t\tctx, cancel = context.WithTimeout(dcr.ctx, 4*time.Second)\n\t\tsynced, _, err := dcr.wallet.SyncStatus(ctx)\n\t\tcancel()\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"Error retrieving sync status before queuing polled block: %v\", err)\n\t\t} else if !synced {\n\t\t\tblockAllowance *= 10\n\t\t}\n\t\tqueuedBlock = &polledBlock{\n\t\t\tblock: newTip,\n\t\t\tqueue: time.AfterFunc(blockAllowance, func() {\n\t\t\t\tdcr.log.Warnf(\"Reporting a block found in polling that the wallet apparently \"+\n\t\t\t\t\t\"never reported: %s (%d). If you see this message repeatedly, it may indicate \"+\n\t\t\t\t\t\"an issue with the wallet.\", newTip.hash, newTip.height)\n\t\t\t\tdcr.handleTipChange(newTip.hash, newTip.height, nil)\n\t\t\t}),\n\t\t}\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tcheckTip()\n\n\t\tcase walletTip := <-walletBlock:\n\t\t\tif queuedBlock != nil && walletTip.height >= queuedBlock.height {\n\t\t\t\tif !queuedBlock.queue.Stop() && walletTip.hash == queuedBlock.hash {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tqueuedBlock = nil\n\t\t\t}\n\t\t\tdcr.handleTipChange(walletTip.hash, walletTip.height, nil)\n\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c *Client) GetBlocksByRange(before, after uint64, noempty bool) (blocks *rpctypes.ResultBlockchainInfo, err error) {\n\tblocks = new(rpctypes.ResultBlockchainInfo)\n\tp := params{}\n\tif noempty {\n\t\tp[\"noempty\"] = \"true\"\n\t}\n\terr = c.get(blocks, c.URLP(\n\t\tp,\n\t\t\"block/range/%d/%d\", after, before,\n\t))\n\terr = errors.Wrap(err, \"getting blocks by height range\")\n\treturn\n}", "func GetBlocks(hostURL string, hostPort int, height int) *bytes.Buffer {\n\tparams := make(map[string]interface{})\n\tparams[\"height\"] = height\n\treturn makePostRequest(hostURL, hostPort, \"f_blocks_list_json\", params)\n}", "func CheckSizeBlocks(start, end uint64) error {\n\ttxn := globalOpt.Txn(true)\n\tdefer txn.Commit()\n\n\tlist := make([]interface{}, 0, 64)\n\n\tit, err := txn.Get(TableBlockKey, HeightBlockKey)\n\tif err != nil {\n\t\ttxn.Abort()\n\t\treturn err\n\t}\n\tfor obj := it.Next(); obj != nil; obj = it.Next() {\n\t\tv, ok := obj.(*fabclient.MiddleCommonBlock)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif v.Number < start || v.Number > end {\n\t\t\tlist = append(list, obj)\n\t\t}\n\t}\n\n\tfor _, one := range list {\n\t\terr = txn.Delete(TableBlockKey, one)\n\t\tif err != nil {\n\t\t\ttxn.Abort()\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func BorMissedBlocks(ops types.HTTPOptions, cfg *config.Config, c client.Client) {\n\tbp, err := db.CreateBatchPoints(cfg.InfluxDB.Database)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tborHeight := GetBorCurrentBlokHeightInHex(cfg, c)\n\tif borHeight == \"\" {\n\t\tlog.Println(\"Got empty block height of bor from db\")\n\t\treturn\n\t}\n\n\tops.Body.Params = append(ops.Body.Params, borHeight)\n\n\tsigners, err := scraper.BorSignersRes(ops)\n\tif err != nil {\n\t\tlog.Printf(\"Error in BorMissedBlocks: %v\", err)\n\t\treturn\n\t}\n\n\theight, err := utils.HexToIntConversion(borHeight)\n\tif err != nil {\n\t\tlog.Printf(\"Error while converting bor height from hex to int : %v\", err)\n\t\treturn\n\t}\n\n\tcbh := strconv.Itoa(height)\n\n\tif signers.Result != nil {\n\t\tisSigned := false\n\n\t\tfor _, addr := range signers.Result {\n\t\t\tif strings.EqualFold(addr, cfg.ValDetails.SignerAddress) {\n\t\t\t\tisSigned = true\n\t\t\t}\n\t\t}\n\n\t\tlog.Printf(\"block signed status : %v, and height : %s \", isSigned, cbh)\n\n\t\tif !isSigned {\n\t\t\tblocks := GetBorContinuousMissedBlock(cfg, c)\n\t\t\tcurrentHeightFromDb := GetBorlatestCurrentHeightFromDB(cfg, c)\n\t\t\tblocksArray := strings.Split(blocks, \",\")\n\t\t\t// calling function to store single blocks\n\t\t\terr = SendBorSingleMissedBlockAlert(ops, cfg, c, cbh)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error while sending missed block alert: %v\", err)\n\n\t\t\t}\n\t\t\tif cfg.AlertingThresholds.MissedBlocksThreshold > 1 && strings.ToUpper(cfg.AlerterPreferences.MissedBlockAlerts) == \"YES\" {\n\t\t\t\tif int64(len(blocksArray))-1 >= cfg.AlertingThresholds.MissedBlocksThreshold {\n\t\t\t\t\tmissedBlocks := strings.Split(blocks, \",\")\n\t\t\t\t\t_ = alerter.SendTelegramAlert(fmt.Sprintf(\"⚠️ Bor Missed Blocks Alert: %s validator on bor node missed blocks from height %s to %s\", cfg.ValDetails.ValidatorName, missedBlocks[0], missedBlocks[len(missedBlocks)-2]), cfg)\n\t\t\t\t\t_ = alerter.SendEmailAlert(fmt.Sprintf(\"⚠️ Bor Missed Blocks Alert: %s validator on bor node missed blocks from height %s to %s\", cfg.ValDetails.ValidatorName, missedBlocks[0], missedBlocks[len(missedBlocks)-2]), cfg)\n\t\t\t\t\t_ = db.WriteToInfluxDb(c, bp, \"bor_continuous_missed_blocks\", map[string]string{}, map[string]interface{}{\"missed_blocks\": blocks, \"range\": missedBlocks[0] + \" - \" + missedBlocks[len(missedBlocks)-2]})\n\t\t\t\t\t_ = db.WriteToInfluxDb(c, bp, \"matic_bor_missed_blocks\", map[string]string{}, map[string]interface{}{\"block_height\": \"\", \"current_height\": cbh})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif len(blocksArray) == 1 {\n\t\t\t\t\tblocks = cbh + \",\"\n\t\t\t\t} else {\n\t\t\t\t\trpcBlockHeight, _ := strconv.Atoi(cbh)\n\t\t\t\t\tdbBlockHeight, _ := strconv.Atoi(currentHeightFromDb)\n\t\t\t\t\tdiff := rpcBlockHeight - dbBlockHeight\n\t\t\t\t\tif diff == 1 {\n\t\t\t\t\t\tblocks = blocks + cbh + \",\"\n\t\t\t\t\t} else if diff > 1 {\n\t\t\t\t\t\tblocks = \"\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\terr = db.WriteToInfluxDb(c, bp, \"matic_bor_missed_blocks\", map[string]string{}, map[string]interface{}{\"block_height\": blocks, \"current_height\": cbh})\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error while storing missed blocks : %v \", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\terr = db.WriteToInfluxDb(c, bp, \"bor_val_signed_blocks\", map[string]string{}, map[string]interface{}{\"signed_block_height\": cbh})\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error while storing validator signed blocks : %v \", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else {\n\t\tlog.Println(\"Got an empty response from bor rpc !\")\n\t\treturn\n\t}\n}", "func GetBlockRange(cache *BlockCache, blockOut chan<- *walletrpc.CompactBlock, errOut chan<- error, start, end int) {\n\t// Go over [start, end] inclusive\n\tfor i := start; i <= end; i++ {\n\t\tblock, err := GetBlock(cache, i)\n\t\tif err != nil {\n\t\t\terrOut <- err\n\t\t\treturn\n\t\t}\n\t\tblockOut <- block\n\t}\n\terrOut <- nil\n}", "func (m *GetHeadersMessage) GetBlockLocator() []*bc.Hash {\n\tblockLocator := []*bc.Hash{}\n\tfor _, rawHash := range m.RawBlockLocator {\n\t\thash := bc.NewHash(rawHash)\n\t\tblockLocator = append(blockLocator, &hash)\n\t}\n\treturn blockLocator\n}", "func (c *Client) GetBlocksByDaterange(first, last time.Time, noempty bool, after time.Time, limit int) (blocks *rpctypes.ResultBlockchainInfo, err error) {\n\tblocks = new(rpctypes.ResultBlockchainInfo)\n\tp := params{}\n\tif after != (time.Time{}) {\n\t\tp[\"after\"] = after.Format(time.RFC3339)\n\t}\n\tif limit != 0 {\n\t\tp[\"limit\"] = limit\n\t}\n\terr = c.get(\n\t\tblocks,\n\t\tc.URLP(\n\t\t\tp,\n\t\t\t\"block/daterange/%s/%s\", first.Format(time.RFC3339), last.Format(time.RFC3339),\n\t\t),\n\t)\n\terr = errors.Wrap(err, \"getting blocks by date range\")\n\treturn\n}", "func GetBlocks(w http.ResponseWriter, r *http.Request) {\n\t// Send a copy of this node's blockchain\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(b.blockchain)\n}", "func (dcr *ExchangeWallet) findRedemptionsInBlockRange(startBlockHeight, endBlockHeight int64, contractOutpoints []outPoint) {\n\ttotalContracts := len(contractOutpoints)\n\tdcr.log.Debugf(\"finding redemptions for %d contracts in blocks %d - %d\",\n\t\ttotalContracts, startBlockHeight, endBlockHeight)\n\n\tvar lastScannedBlockHeight int64\n\tvar totalFound, totalCanceled int\n\nrangeBlocks:\n\tfor blockHeight := startBlockHeight; blockHeight <= endBlockHeight; blockHeight++ {\n\t\t// Get the hash for this block.\n\t\tblockHash, err := dcr.wallet.GetBlockHash(dcr.ctx, blockHeight)\n\t\tif err != nil { // unable to get block hash is a fatal error\n\t\t\terr = fmt.Errorf(\"unable to get hash for block %d: %w\", blockHeight, err)\n\t\t\tdcr.fatalFindRedemptionsError(err, contractOutpoints)\n\t\t\treturn\n\t\t}\n\n\t\t// Combine the p2sh scripts for all contracts (excluding contracts whose redemption\n\t\t// have been found) to check against this block's cfilters.\n\t\tdcr.findRedemptionMtx.RLock()\n\t\tcontractP2SHScripts := make([][]byte, 0)\n\t\tfor _, contractOutpoint := range contractOutpoints {\n\t\t\tif req, stillInQueue := dcr.findRedemptionQueue[contractOutpoint]; stillInQueue {\n\t\t\t\tcontractP2SHScripts = append(contractP2SHScripts, req.contractP2SHScript)\n\t\t\t}\n\t\t}\n\t\tdcr.findRedemptionMtx.RUnlock()\n\n\t\tbingo, err := dcr.wallet.MatchAnyScript(dcr.ctx, blockHash, contractP2SHScripts)\n\t\tif err != nil { // error retrieving a block's cfilters is a fatal error\n\t\t\terr = fmt.Errorf(\"MatchAnyScript error for block %d (%s): %w\", blockHeight, blockHash, err)\n\t\t\tdcr.fatalFindRedemptionsError(err, contractOutpoints)\n\t\t\treturn\n\t\t}\n\n\t\tif !bingo {\n\t\t\tlastScannedBlockHeight = blockHeight\n\t\t\tcontinue // block does not reference any of these contracts, continue to next block\n\t\t}\n\n\t\t// Pull the block info to confirm if any of its inputs spends a contract of interest.\n\t\tblk, err := dcr.wallet.GetBlock(dcr.ctx, blockHash)\n\t\tif err != nil { // error pulling a matching block's transactions is a fatal error\n\t\t\terr = fmt.Errorf(\"error retrieving transactions for block %d (%s): %w\",\n\t\t\t\tblockHeight, blockHash, err)\n\t\t\tdcr.fatalFindRedemptionsError(err, contractOutpoints)\n\t\t\treturn\n\t\t}\n\n\t\tlastScannedBlockHeight = blockHeight\n\t\tscanPoint := fmt.Sprintf(\"block %d\", blockHeight)\n\t\tfor _, tx := range append(blk.Transactions, blk.STransactions...) {\n\t\t\tfound, canceled := dcr.findRedemptionsInTx(scanPoint, tx, contractOutpoints)\n\t\t\ttotalFound += found\n\t\t\ttotalCanceled += canceled\n\t\t\tif totalFound+totalCanceled == totalContracts {\n\t\t\t\tbreak rangeBlocks\n\t\t\t}\n\t\t}\n\t}\n\n\tdcr.log.Debugf(\"%d redemptions found, %d canceled out of %d contracts in blocks %d to %d\",\n\t\ttotalFound, totalCanceled, totalContracts, startBlockHeight, lastScannedBlockHeight)\n\n\t// Search for redemptions in mempool if there are yet unredeemed\n\t// contracts after searching this block range.\n\tpendingContractsCount := totalContracts - totalFound - totalCanceled\n\tif pendingContractsCount > 0 {\n\t\tdcr.findRedemptionMtx.RLock()\n\t\tpendingContracts := make([]outPoint, 0, pendingContractsCount)\n\t\tfor _, contractOutpoint := range contractOutpoints {\n\t\t\tif _, pending := dcr.findRedemptionQueue[contractOutpoint]; pending {\n\t\t\t\tpendingContracts = append(pendingContracts, contractOutpoint)\n\t\t\t}\n\t\t}\n\t\tdcr.findRedemptionMtx.RUnlock()\n\t\tdcr.findRedemptionsInMempool(pendingContracts)\n\t}\n}", "func (client *Client) QueryBlocks(query *Query) (*Response, error) {\n\tpath := \"/block\"\n\turi := fmt.Sprintf(\"%s%s\", client.apiBaseURL, path)\n\n\treq, err := http.NewRequest(\"GET\", uri, bytes.NewBuffer([]byte(\"\")))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuildQuery(req, query)\n\tresp, err := client.performRequest(req, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar results map[string][]Block\n\terr = json.Unmarshal(resp.Response.([]byte), &results)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Response = results\n\treturn resp, err\n}", "func (c *Client) GetBlocks(height string) (resp *Blocks, e error) {\n\tif height == \"\" {\n\t\treturn nil, c.err(ErrBEW)\n\t}\n\n\tresp = &Blocks{}\n\treturn resp, c.Do(\"/blocks/\"+height, resp, nil)\n}", "func (synckerManager *SynckerManager) GetS2BBlocksForBeaconProducer(bestViewShardHash map[byte]common.Hash, limit map[byte][]common.Hash) map[byte][]interface{} {\n\tres := make(map[byte][]interface{})\n\n\tfor i := 0; i < synckerManager.config.Node.GetChainParam().ActiveShards; i++ {\n\t\tv := bestViewShardHash[byte(i)]\n\t\t//beacon beststate dont have shard hash => create one\n\t\tif (&v).IsEqual(&common.Hash{}) {\n\t\t\tblk := *synckerManager.config.Node.GetChainParam().GenesisShardBlock\n\t\t\tblk.Header.ShardID = byte(i)\n\t\t\tv = *blk.Hash()\n\t\t}\n\n\t\tfor _, v := range synckerManager.s2bPool.GetFinalBlockFromBlockHash(v.String()) {\n\t\t\t//if limit has 0 length, we should break now\n\t\t\tif limit != nil && len(res[byte(i)]) >= len(limit[byte(i)]) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tres[byte(i)] = append(res[byte(i)], v)\n\t\t\tif len(res[byte(i)]) >= MAX_S2B_BLOCK {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}", "func (l *Ledger) ConfirmBlock(block *pb.InternalBlock, isRoot bool) ConfirmStatus {\n\tl.mutex.Lock()\n\tdefer l.mutex.Unlock()\n\tblkTimer := timer.NewXTimer()\n\tl.xlog.Info(\"start to confirm block\", \"blockid\", utils.F(block.Blockid), \"txCount\", len(block.Transactions))\n\tvar confirmStatus ConfirmStatus\n\tdummyTransactions := []*pb.Transaction{}\n\trealTransactions := block.Transactions // 真正的交易转存到局部变量\n\tblock.Transactions = dummyTransactions // block表不保存transaction详情\n\n\tbatchWrite := l.ConfirmBatch\n\tbatchWrite.Reset()\n\tnewMeta := proto.Clone(l.meta).(*pb.LedgerMeta)\n\tsplitHeight := newMeta.TrunkHeight\n\tif isRoot { //确认创世块\n\t\tif block.PreHash != nil && len(block.PreHash) > 0 {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tl.xlog.Warn(\"genesis block shoud has no prehash\")\n\t\t\treturn confirmStatus\n\t\t}\n\t\tif len(l.meta.RootBlockid) > 0 {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tconfirmStatus.Error = ErrRootBlockAlreadyExist\n\t\t\tl.xlog.Warn(\"already hash genesis block\")\n\t\t\treturn confirmStatus\n\t\t}\n\t\tnewMeta.RootBlockid = block.Blockid\n\t\tnewMeta.TrunkHeight = 0 //代表主干上块的最大高度\n\t\tnewMeta.TipBlockid = block.Blockid\n\t\tblock.InTrunk = true\n\t\tblock.Height = 0 // 创世纪块是第0块\n\t} else { //非创世块,需要判断是在主干还是分支\n\t\tpreHash := block.PreHash\n\t\tpreBlock, findErr := l.fetchBlock(preHash)\n\t\tif findErr != nil {\n\t\t\tl.xlog.Warn(\"find pre block fail\", \"findErr\", findErr)\n\t\t\tconfirmStatus.Succ = false\n\t\t\treturn confirmStatus\n\t\t}\n\t\tblock.Height = preBlock.Height + 1 //不管是主干还是分支,height都是++\n\t\tif bytes.Equal(preBlock.Blockid, newMeta.TipBlockid) {\n\t\t\t//在主干上添加\n\t\t\tblock.InTrunk = true\n\t\t\tpreBlock.NextHash = block.Blockid\n\t\t\tnewMeta.TipBlockid = block.Blockid\n\t\t\tnewMeta.TrunkHeight++\n\t\t\t//因为改了pre_block的next_hash值,所以也要写回存储\n\t\t\tif !DisableTxDedup {\n\t\t\t\tsaveErr := l.saveBlock(preBlock, batchWrite)\n\t\t\t\tl.blockCache.Del(string(preBlock.Blockid))\n\t\t\t\tif saveErr != nil {\n\t\t\t\t\tl.xlog.Warn(\"save block fail\", \"saveErr\", saveErr)\n\t\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\t\treturn confirmStatus\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t//在分支上\n\t\t\tif preBlock.Height+1 > newMeta.TrunkHeight {\n\t\t\t\t//分支要变成主干了\n\t\t\t\toldTip := append([]byte{}, newMeta.TipBlockid...)\n\t\t\t\tnewMeta.TrunkHeight = preBlock.Height + 1\n\t\t\t\tnewMeta.TipBlockid = block.Blockid\n\t\t\t\tblock.InTrunk = true\n\t\t\t\tsplitBlock, splitErr := l.handleFork(oldTip, preBlock.Blockid, block.Blockid, batchWrite) //处理分叉\n\t\t\t\tif splitErr != nil {\n\t\t\t\t\tl.xlog.Warn(\"handle split failed\", \"splitErr\", splitErr)\n\t\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\t\treturn confirmStatus\n\t\t\t\t}\n\t\t\t\tsplitHeight = splitBlock.Height\n\t\t\t\tconfirmStatus.Split = true\n\t\t\t\tconfirmStatus.TrunkSwitch = true\n\t\t\t\tl.xlog.Info(\"handle split successfully\", \"splitBlock\", utils.F(splitBlock.Blockid))\n\t\t\t} else {\n\t\t\t\t// 添加在分支上, 对preblock没有影响\n\t\t\t\tblock.InTrunk = false\n\t\t\t\tconfirmStatus.Split = true\n\t\t\t\tconfirmStatus.TrunkSwitch = false\n\t\t\t\tconfirmStatus.Orphan = true\n\t\t\t}\n\t\t}\n\t}\n\tsaveErr := l.saveBlock(block, batchWrite)\n\tblkTimer.Mark(\"saveHeader\")\n\tif saveErr != nil {\n\t\tconfirmStatus.Succ = false\n\t\tl.xlog.Warn(\"save current block fail\", \"saveErr\", saveErr)\n\t\treturn confirmStatus\n\t}\n\t// update branch head\n\tupdateBranchErr := l.updateBranchInfo(block.Blockid, block.PreHash, block.Height, batchWrite)\n\tif updateBranchErr != nil {\n\t\tconfirmStatus.Succ = false\n\t\tl.xlog.Warn(\"update branch info fail\", \"updateBranchErr\", updateBranchErr)\n\t\treturn confirmStatus\n\t}\n\ttxExist, txData := l.parallelCheckTx(realTransactions, block)\n\tcbNum := 0\n\toldBlockCache := map[string]*pb.InternalBlock{}\n\tfor _, tx := range realTransactions {\n\t\t//在这儿解析交易存表,调用新版的接口TxOutputs不会超过4\n\t\t//理论上这儿坐过校验判断后,不会报错,目前还是写好报错码,以便调试\n\t\tif len(tx.TxInputs) >0 &&len(tx.TxOutputs) < 4 && len(tx.ContractRequests) > 0 {\n\t\t\treq := tx.ContractRequests[0]\n\t\t\ttmpReq := &InvokeRequest{\n\t\t\t\tModuleName: req.ModuleName,\n\t\t\t\tContractName: req.ContractName,\n\t\t\t\tMethodName: req.MethodName,\n\t\t\t\tArgs: map[string]string{},\n\t\t\t}\n\t\t\tfor argKey, argV := range req.Args {\n\t\t\t\ttmpReq.Args[argKey] = string(argV)\n\t\t\t}\n\t\t\tif tmpReq.ModuleName == \"xkernel\" && tmpReq.ContractName == \"$govern_token\"{\n\t\t\t\t//这里有buy和sell\n\t\t\t\tswitch tmpReq.MethodName {\n\t\t\t\tcase \"Buy\":\n\t\t\t\t\tl.WriteFreezeTable(batchWrite,tmpReq.Args[\"amount\"],string(tx.TxInputs[0].FromAddr),tx.Txid)\n\t\t\t\tcase \"Sell\":\n\t\t\t\t\tl.WriteThawTable(batchWrite,string(tx.TxInputs[0].FromAddr),tx.Desc)\n\t\t\t\tdefault:\n\t\t\t\t\tl.xlog.Warn(\"D__解析交易存表时方法异常,异常方法名:\",\"tmpReq.MethodName\",tmpReq.MethodName)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif tmpReq.ModuleName == \"xkernel\" && (tmpReq.ContractName == \"$tdpos\" || tmpReq.ContractName ==\"$xpos\" ) {\n\t\t\t\tswitch tmpReq.MethodName {\n\t\t\t\tcase \"nominateCandidate\":\n\t\t\t\t\tl.WriteCandidateTable(batchWrite,string(tx.TxInputs[0].FromAddr),tmpReq.Args)\n\t\t\t\tcase \"revokeNominate\":\n\t\t\t\t\tl.WriteReCandidateTable(batchWrite,string(tx.TxInputs[0].FromAddr),tmpReq.Args)\n\t\t\t\tcase \"voteCandidate\":\n\t\t\t\t\tl.VoteCandidateTable(batchWrite,string(tx.TxInputs[0].FromAddr),tmpReq.Args)\n\t\t\t\tcase \"revokeVote\":\n\t\t\t\t\tl.RevokeVote(batchWrite,string(tx.TxInputs[0].FromAddr),tmpReq.Args)\n\t\t\t\tdefault:\n\t\t\t\t\tl.xlog.Warn(\"D__解析tdpos交易存表时方法异常,异常方法名:\",\"tmpReq.MethodName\",tmpReq.MethodName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t\tif tx.Coinbase {\n\t\t\tcbNum = cbNum + 1\n\t\t}\n\t\tif cbNum > 1 {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tl.xlog.Warn(\"The num of Coinbase tx should not exceed one when confirm block\",\n\t\t\t\t\"BlockID\", utils.F(tx.Blockid), \"Miner\", string(block.Proposer))\n\t\t\treturn confirmStatus\n\t\t}\n\n\t\tpbTxBuf := txData[string(tx.Txid)]\n\t\tif pbTxBuf == nil {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tl.xlog.Warn(\"marshal trasaction failed when confirm block\")\n\t\t\treturn confirmStatus\n\t\t}\n\t\thasTx := txExist[string(tx.Txid)]\n\t\tif !hasTx {\n\t\t\tbatchWrite.Put(append([]byte(pb.ConfirmedTablePrefix), tx.Txid...), pbTxBuf)\n\t\t} else {\n\t\t\t//confirm表已经存在这个交易了,需要检查一下是否存在多个主干block包含同样trasnaction的情况\n\t\t\toldPbTxBuf, _ := l.ConfirmedTable.Get(tx.Txid)\n\t\t\toldTx := &pb.Transaction{}\n\t\t\tparserErr := proto.Unmarshal(oldPbTxBuf, oldTx)\n\t\t\tif parserErr != nil {\n\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\tconfirmStatus.Error = parserErr\n\t\t\t\treturn confirmStatus\n\t\t\t}\n\t\t\toldBlock := &pb.InternalBlock{}\n\t\t\tif cachedBlk, cacheHit := oldBlockCache[string(oldTx.Blockid)]; cacheHit {\n\t\t\t\toldBlock = cachedBlk\n\t\t\t} else {\n\t\t\t\toldPbBlockBuf, blockErr := l.blocksTable.Get(oldTx.Blockid)\n\t\t\t\tif blockErr != nil {\n\t\t\t\t\tif def.NormalizedKVError(blockErr) == def.ErrKVNotFound {\n\t\t\t\t\t\tl.xlog.Warn(\"old block that contains the tx has been truncated\", \"txid\", utils.F(tx.Txid), \"blockid\", utils.F(oldTx.Blockid))\n\t\t\t\t\t\tbatchWrite.Put(append([]byte(pb.ConfirmedTablePrefix), tx.Txid...), pbTxBuf) //overwrite with newtx\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\t\tconfirmStatus.Error = blockErr\n\t\t\t\t\treturn confirmStatus\n\t\t\t\t}\n\t\t\t\tparserErr = proto.Unmarshal(oldPbBlockBuf, oldBlock)\n\t\t\t\tif parserErr != nil {\n\t\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\t\tconfirmStatus.Error = parserErr\n\t\t\t\t\treturn confirmStatus\n\t\t\t\t}\n\t\t\t\toldBlockCache[string(oldBlock.Blockid)] = oldBlock\n\t\t\t}\n\t\t\tif oldBlock.InTrunk && block.InTrunk && oldBlock.Height <= splitHeight {\n\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\tconfirmStatus.Error = ErrTxDuplicated\n\t\t\t\tl.xlog.Warn(\"transaction duplicated in previous trunk block\",\n\t\t\t\t\t\"txid\", utils.F(tx.Txid),\n\t\t\t\t\t\"blockid\", utils.F(oldBlock.Blockid))\n\t\t\t\treturn confirmStatus\n\t\t\t} else if block.InTrunk {\n\t\t\t\tl.xlog.Info(\"change blockid of tx\", \"txid\", utils.F(tx.Txid), \"blockid\", utils.F(block.Blockid))\n\t\t\t\tbatchWrite.Put(append([]byte(pb.ConfirmedTablePrefix), tx.Txid...), pbTxBuf)\n\t\t\t}\n\t\t}\n\t}\n\tblkTimer.Mark(\"saveAllTxs\")\n\t//删除pendingBlock中对应的数据\n\tbatchWrite.Delete(append([]byte(pb.PendingBlocksTablePrefix), block.Blockid...))\n\t//改meta\n\tmetaBuf, pbErr := proto.Marshal(newMeta)\n\tif pbErr != nil {\n\t\tl.xlog.Warn(\"marshal meta fail\", \"pbErr\", pbErr)\n\t\tconfirmStatus.Succ = false\n\t\treturn confirmStatus\n\t}\n\tbatchWrite.Put([]byte(pb.MetaTablePrefix), metaBuf)\n\tl.xlog.Debug(\"print block size when confirm block\", \"blockSize\", batchWrite.ValueSize(), \"blockid\", utils.F(block.Blockid))\n\tkvErr := batchWrite.Write() // blocks, confirmed_transaction两张表原子写入\n\tblkTimer.Mark(\"saveToDisk\")\n\tif kvErr != nil {\n\t\tconfirmStatus.Succ = false\n\t\tconfirmStatus.Error = kvErr\n\t\tl.xlog.Warn(\"batch write failed when confirm block\", \"kvErr\", kvErr)\n\t} else {\n\t\tconfirmStatus.Succ = true\n\t\tl.meta = newMeta\n\t}\n\tblock.Transactions = realTransactions\n\tif isRoot {\n\t\t//首次confirm 创始块的时候\n\t\tlErr := l.loadGenesisBlock(false, nil)\n\t\tif lErr != nil {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tconfirmStatus.Error = lErr\n\t\t}\n\t}\n\tl.blockCache.Add(string(block.Blockid), block)\n\tl.xlog.Debug(\"confirm block cost\", \"blkTimer\", blkTimer.Print())\n\treturn confirmStatus\n}", "func GetBlock(x uint64) block.Block{\r\n\t\tvar block1 block.MinBlock\r\n\t\tvar block2 block.Block\r\n\t\tblock1.BlockNumber = x\r\n\t\tblock1.ChainYear = ChainYear\r\n\t\tfmt.Println(\"ChainYear\", block1.ChainYear)\r\n\t\tdata, err:= json.Marshal(block1)\r\n\t\tif err !=nil{\r\n\t\t\tfmt.Println(\"Error Reading Block\", err)\r\n\t\t}\r\n\t\tfmt.Println(\"Block as Json\", data)\r\n\t\ttheNodes := GetNodes(block1.BlockHash())\r\n\t\t\r\n\t\tcall := \"getBlock\"\r\n\t\t\r\n\t\tfor x:=0; x < len(theNodes); x +=1{\r\n\t\t\t\t\r\n\t\t\turl1 := \"http://\"+ MyNode.Ip+ MyNode.Port+\"/\"+ call\r\n\t\t\tfmt.Println(\"url:\", url1)\r\n\t\t\t resp, err := http.Post(url1, \"application/json\", bytes.NewBuffer(data))\r\n\r\n\t\t\tif err != nil {\r\n\t\t\t\tfmt.Println(\"Error connectig to node trying next node \", err)\r\n\t\t\t}else{\r\n\t\t\t\tfmt.Println(\"Block as Json\", data)\r\n\t\t\t\tjson.NewDecoder(resp.Body).Decode(&block2)\r\n\t\t\t\treturn block2\r\n\t\t\t}\r\n\t\t}\r\nreturn block2\r\n\t\t\r\n\t\t\r\n}", "func (dag *BlockDAG) BlockForMining(transactions []*util.Tx) (*domainmessage.MsgBlock, error) {\n\tblockTimestamp := dag.NextBlockTime()\n\trequiredDifficulty := dag.NextRequiredDifficulty(blockTimestamp)\n\n\t// Calculate the next expected block version based on the state of the\n\t// rule change deployments.\n\tnextBlockVersion, err := dag.CalcNextBlockVersion()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a new block ready to be solved.\n\thashMerkleTree := BuildHashMerkleTreeStore(transactions)\n\tacceptedIDMerkleRoot, err := dag.NextAcceptedIDMerkleRootNoLock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar msgBlock domainmessage.MsgBlock\n\tfor _, tx := range transactions {\n\t\tmsgBlock.AddTransaction(tx.MsgTx())\n\t}\n\n\tmultiset, err := dag.NextBlockMultiset()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmsgBlock.Header = domainmessage.BlockHeader{\n\t\tVersion: nextBlockVersion,\n\t\tParentHashes: dag.TipHashes(),\n\t\tHashMerkleRoot: hashMerkleTree.Root(),\n\t\tAcceptedIDMerkleRoot: acceptedIDMerkleRoot,\n\t\tUTXOCommitment: (*daghash.Hash)(multiset.Finalize()),\n\t\tTimestamp: blockTimestamp,\n\t\tBits: requiredDifficulty,\n\t}\n\n\treturn &msgBlock, nil\n}", "func (dcr *ExchangeWallet) findRedemptionsInBlockRange(startBlock, endBlock *block, contractOutpoints []outPoint) {\n\tcontractsCount := len(contractOutpoints)\n\tdcr.log.Debugf(\"finding redemptions for %d contracts in blocks %d - %d\",\n\t\tcontractsCount, startBlock.height, endBlock.height)\n\n\tnextBlockHash := startBlock.hash\n\tvar lastScannedBlockHeight int64\n\tvar redemptionsFound int\n\nrangeBlocks:\n\tfor nextBlockHash != nil && lastScannedBlockHeight < endBlock.height {\n\t\tblk, err := dcr.node.GetBlockVerbose(dcr.ctx, nextBlockHash, true)\n\t\tif err != nil {\n\t\t\t// Redemption search for this set of contracts is compromised. Notify\n\t\t\t// the redemption finder(s) of this fatal error and cancel redemption\n\t\t\t// search for these contracts. The redemption finder(s) may re-call\n\t\t\t// dcr.FindRedemption to restart find redemption attempts for any of\n\t\t\t// these contracts.\n\t\t\terr = fmt.Errorf(\"error fetching verbose block %s: %w\", nextBlockHash, translateRPCCancelErr(err))\n\t\t\tdcr.fatalFindRedemptionsError(err, contractOutpoints)\n\t\t\treturn\n\t\t}\n\t\tscanPoint := fmt.Sprintf(\"block %d\", blk.Height)\n\t\tlastScannedBlockHeight = blk.Height\n\t\tblkTxs := append(blk.RawTx, blk.RawSTx...)\n\t\tfor t := range blkTxs {\n\t\t\ttx := &blkTxs[t]\n\t\t\tredemptionsFound += dcr.findRedemptionsInTx(scanPoint, tx, contractOutpoints)\n\t\t\tif redemptionsFound == contractsCount {\n\t\t\t\tbreak rangeBlocks\n\t\t\t}\n\t\t}\n\t\tif blk.NextHash == \"\" {\n\t\t\tnextBlockHash = nil\n\t\t} else {\n\t\t\tnextBlockHash, err = chainhash.NewHashFromStr(blk.NextHash)\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"hash decode error %s: %w\", blk.NextHash, err)\n\t\t\t\tdcr.fatalFindRedemptionsError(err, contractOutpoints)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdcr.log.Debugf(\"%d redemptions out of %d contracts found in blocks %d - %d\",\n\t\tredemptionsFound, contractsCount, startBlock.height, lastScannedBlockHeight)\n\n\t// Search for redemptions in mempool if there are yet unredeemed\n\t// contracts after searching this block range.\n\tpendingContractsCount := contractsCount - redemptionsFound\n\tif pendingContractsCount > 0 {\n\t\tdcr.findRedemptionMtx.RLock()\n\t\tpendingContracts := make([]outPoint, 0, pendingContractsCount)\n\t\tfor _, contractOutpoint := range contractOutpoints {\n\t\t\tif _, pending := dcr.findRedemptionQueue[contractOutpoint]; pending {\n\t\t\t\tpendingContracts = append(pendingContracts, contractOutpoint)\n\t\t\t}\n\t\t}\n\t\tdcr.findRedemptionMtx.RUnlock()\n\t\tdcr.findRedemptionsInMempool(pendingContracts)\n\t}\n}", "func (bd *BlockDAG) locateBlocks(gs *GraphState, maxHashes uint) []*hash.Hash {\n\tif gs.IsExcellent(bd.getGraphState()) {\n\t\treturn nil\n\t}\n\tqueue := []IBlock{}\n\tfs := NewHashSet()\n\ttips := bd.getValidTips(false)\n\tfor _, v := range tips {\n\t\tib := bd.getBlock(v)\n\t\tqueue = append(queue, ib)\n\t}\n\tfor len(queue) > 0 {\n\t\tcur := queue[0]\n\t\tqueue = queue[1:]\n\n\t\tif fs.Has(cur.GetHash()) {\n\t\t\tcontinue\n\t\t}\n\t\tif gs.GetTips().Has(cur.GetHash()) || cur.GetHash().IsEqual(&bd.genesis) {\n\t\t\tcontinue\n\t\t}\n\t\tneedRec := true\n\t\tif cur.HasChildren() {\n\t\t\tfor _, v := range cur.GetChildren().GetMap() {\n\t\t\t\tib := v.(IBlock)\n\t\t\t\tif gs.GetTips().Has(ib.GetHash()) || !fs.Has(ib.GetHash()) && ib.IsOrdered() {\n\t\t\t\t\tneedRec = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif needRec {\n\t\t\tfs.AddPair(cur.GetHash(), cur)\n\t\t\tif cur.HasParents() {\n\t\t\t\tfor _, v := range cur.GetParents().GetMap() {\n\t\t\t\t\tvalue := v.(IBlock)\n\t\t\t\t\tib := value\n\t\t\t\t\tif fs.Has(ib.GetHash()) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tqueue = append(queue, ib)\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfsSlice := BlockSlice{}\n\tfor _, v := range fs.GetMap() {\n\t\tvalue := v.(IBlock)\n\t\tib := value\n\t\tif gs.GetTips().Has(ib.GetHash()) {\n\t\t\tcontinue\n\t\t}\n\t\tif ib.HasChildren() {\n\t\t\tneed := true\n\t\t\tfor _, v := range ib.GetChildren().GetMap() {\n\t\t\t\tib := v.(IBlock)\n\t\t\t\tif gs.GetTips().Has(ib.GetHash()) {\n\t\t\t\t\tneed = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !need {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tfsSlice = append(fsSlice, ib)\n\t}\n\n\tresult := []*hash.Hash{}\n\tif len(fsSlice) >= 2 {\n\t\tsort.Sort(fsSlice)\n\t}\n\tfor i := 0; i < len(fsSlice); i++ {\n\t\tif maxHashes > 0 && i >= int(maxHashes) {\n\t\t\tbreak\n\t\t}\n\t\tresult = append(result, fsSlice[i].GetHash())\n\t}\n\treturn result\n}", "func (gw *Gateway) GetBlocks(seqs []uint64) ([]coin.SignedBlock, error) {\n\tvar blocks []coin.SignedBlock\n\tvar err error\n\tgw.strand(\"GetBlocks\", func() {\n\t\tblocks, err = gw.v.GetBlocks(seqs)\n\t})\n\treturn blocks, err\n}", "func findBlocks(dasquery dasql.DASQuery) []string {\n\tspec := dasquery.Spec\n\tinst := dasquery.Instance\n\tvar out []string\n\tblk := spec[\"block\"]\n\tif blk != nil {\n\t\tout = append(out, blk.(string))\n\t\treturn out\n\t}\n\tdataset := spec[\"dataset\"].(string)\n\tapi := \"blocks\"\n\tfurl := fmt.Sprintf(\"%s/%s?dataset=%s\", DBSUrl(inst), api, dataset)\n\tclient := utils.HttpClient()\n\tresp := utils.FetchResponse(client, furl, \"\") // \"\" specify optional args\n\trecords := DBSUnmarshal(api, resp.Data)\n\tfor _, rec := range records {\n\t\tv := rec[\"block_name\"]\n\t\tif v != nil {\n\t\t\tout = append(out, v.(string))\n\t\t}\n\t}\n\treturn out\n}", "func (c *Client) GetBlocksByHeight(before, after uint64, noempty bool) (blocks *rpctypes.ResultBlockchainInfo, err error) {\n\tblocks = new(rpctypes.ResultBlockchainInfo)\n\tp := params{}\n\tif after > 0 {\n\t\tp[\"after\"] = after\n\t}\n\tif noempty {\n\t\tp[\"filter\"] = \"noempty\"\n\t}\n\terr = c.get(blocks, c.URLP(\n\t\tp,\n\t\t\"block/before/%d\", before,\n\t))\n\terr = errors.Wrap(err, \"getting blocks by height\")\n\treturn\n}", "func (f *fragment) Blocks() []FragmentBlock {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\tvar a []FragmentBlock\n\n\t// Initialize the iterator.\n\titr := f.storage.Iterator()\n\titr.Seek(0)\n\n\t// Initialize block hasher.\n\th := newBlockHasher()\n\n\t// Iterate over each value in the fragment.\n\tv, eof := itr.Next()\n\tif eof {\n\t\treturn nil\n\t}\n\tblockID := int(v / (HashBlockSize * ShardWidth))\n\tfor {\n\t\t// Check for multiple block checksums in a row.\n\t\tif n := f.readContiguousChecksums(&a, blockID); n > 0 {\n\t\t\titr.Seek(uint64(blockID+n) * HashBlockSize * ShardWidth)\n\t\t\tv, eof = itr.Next()\n\t\t\tif eof {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tblockID = int(v / (HashBlockSize * ShardWidth))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Reset hasher.\n\t\th.blockID = blockID\n\t\th.Reset()\n\n\t\t// Read all values for the block.\n\t\tfor ; ; v, eof = itr.Next() {\n\t\t\t// Once we hit the next block, save the value for the next iteration.\n\t\t\tblockID = int(v / (HashBlockSize * ShardWidth))\n\t\t\tif blockID != h.blockID || eof {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\th.WriteValue(v)\n\t\t}\n\n\t\t// Cache checksum.\n\t\tchksum := h.Sum()\n\t\tf.checksums[h.blockID] = chksum\n\n\t\t// Append block.\n\t\ta = append(a, FragmentBlock{\n\t\t\tID: h.blockID,\n\t\t\tChecksum: chksum,\n\t\t})\n\n\t\t// Exit if we're at the end.\n\t\tif eof {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn a\n}", "func Blocks(offset, count uint) ([]BlockItem, error) {\n\tjsonBlocks := []struct {\n\t\tNumber uint `json:\"number\"`\n\t\tHash string `json:\"hash\"`\n\t\tDate Time `json:\"date\"`\n\t\tDifficulty uint64 `json:\"difficulty\"`\n\t\tMiner string `json:\"miner\"`\n\t}{}\n\tif err := fetch(&jsonBlocks, blockEndpoint, offset, count); err != nil {\n\t\treturn nil, err\n\t}\n\tblocks := make([]BlockItem, len(jsonBlocks))\n\tfor i, b := range jsonBlocks {\n\t\tblocks[i] = BlockItem(b)\n\t}\n\treturn blocks, nil\n}", "func (bfx *bloomfilterIndexer) RangeBloomFilterBlocks() uint64 {\n\tbfx.mutex.RLock()\n\tdefer bfx.mutex.RUnlock()\n\treturn bfx.rangeSize\n}", "func netBlockReceived(conn *OneConnection, b []byte) {\r\n\tif len(b) < 100 {\r\n\t\tconn.DoS(\"ShortBlock\")\r\n\t\treturn\r\n\t}\r\n\r\n\thash := btc.NewSha2Hash(b[:80])\r\n\tidx := hash.BIdx()\r\n\t//println(\"got block data\", hash.String())\r\n\r\n\tMutexRcv.Lock()\r\n\r\n\t// the blocks seems to be fine\r\n\tif rb, got := ReceivedBlocks[idx]; got {\r\n\t\trb.Cnt++\r\n\t\tcommon.CountSafe(\"BlockSameRcvd\")\r\n\t\tconn.Mutex.Lock()\r\n\t\tdelete(conn.GetBlockInProgress, idx)\r\n\t\tconn.Mutex.Unlock()\r\n\t\tMutexRcv.Unlock()\r\n\t\treturn\r\n\t}\r\n\r\n\t// remove from BlocksToGet:\r\n\tb2g := BlocksToGet[idx]\r\n\tif b2g == nil {\r\n\t\t//println(\"Block\", hash.String(), \" from\", conn.PeerAddr.Ip(), conn.Node.Agent, \" was not expected\")\r\n\r\n\t\tvar hdr [81]byte\r\n\t\tvar sta int\r\n\t\tcopy(hdr[:80], b[:80])\r\n\t\tsta, b2g = conn.ProcessNewHeader(hdr[:])\r\n\t\tif b2g == nil {\r\n\t\t\tif sta == PH_STATUS_FATAL {\r\n\t\t\t\tprintln(\"Unrequested Block: FAIL - Ban\", conn.PeerAddr.Ip(), conn.Node.Agent)\r\n\t\t\t\tconn.DoS(\"BadUnreqBlock\")\r\n\t\t\t} else {\r\n\t\t\t\tcommon.CountSafe(\"ErrUnreqBlock\")\r\n\t\t\t}\r\n\t\t\t//conn.Disconnect()\r\n\t\t\tMutexRcv.Unlock()\r\n\t\t\treturn\r\n\t\t}\r\n\t\tif sta == PH_STATUS_NEW {\r\n\t\t\tb2g.SendInvs = true\r\n\t\t}\r\n\t\t//println(c.ConnID, \" - taking this new block\")\r\n\t\tcommon.CountSafe(\"UnxpectedBlockNEW\")\r\n\t}\r\n\r\n\t//println(\"block\", b2g.BlockTreeNode.Height,\" len\", len(b), \" got from\", conn.PeerAddr.Ip(), b2g.InProgress)\r\n\tb2g.Block.Raw = b\r\n\tif conn.X.Authorized {\r\n\t\tb2g.Block.Trusted = true\r\n\t}\r\n\r\n\ter := common.BlockChain.PostCheckBlock(b2g.Block)\r\n\tif er != nil {\r\n\t\tb2g.InProgress--\r\n\t\tprintln(\"Corrupt block received from\", conn.PeerAddr.Ip(), er.Error())\r\n\t\t//ioutil.WriteFile(hash.String() + \".bin\", b, 0700)\r\n\t\tconn.DoS(\"BadBlock\")\r\n\r\n\t\t// we don't need to remove from conn.GetBlockInProgress as we're disconnecting\r\n\r\n\t\tif b2g.Block.MerkleRootMatch() {\r\n\t\t\tprintln(\"It was a wrongly mined one - clean it up\")\r\n\t\t\tDelB2G(idx) //remove it from BlocksToGet\r\n\t\t\tif b2g.BlockTreeNode == LastCommitedHeader {\r\n\t\t\t\tLastCommitedHeader = LastCommitedHeader.Parent\r\n\t\t\t}\r\n\t\t\tcommon.BlockChain.DeleteBranch(b2g.BlockTreeNode, delB2G_callback)\r\n\t\t}\r\n\r\n\t\tMutexRcv.Unlock()\r\n\t\treturn\r\n\t}\r\n\r\n\torb := &OneReceivedBlock{TmStart: b2g.Started, TmPreproc: b2g.TmPreproc,\r\n\t\tTmDownload: conn.LastMsgTime, FromConID: conn.ConnID, DoInvs: b2g.SendInvs}\r\n\r\n\tconn.Mutex.Lock()\r\n\tbip := conn.GetBlockInProgress[idx]\r\n\tif bip == nil {\r\n\t\t//println(conn.ConnID, \"received unrequested block\", hash.String())\r\n\t\tcommon.CountSafe(\"UnreqBlockRcvd\")\r\n\t\tconn.counters[\"NewBlock!\"]++\r\n\t\torb.TxMissing = -2\r\n\t} else {\r\n\t\tdelete(conn.GetBlockInProgress, idx)\r\n\t\tconn.counters[\"NewBlock\"]++\r\n\t\torb.TxMissing = -1\r\n\t}\r\n\tconn.blocksreceived = append(conn.blocksreceived, time.Now())\r\n\tconn.Mutex.Unlock()\r\n\r\n\tReceivedBlocks[idx] = orb\r\n\tDelB2G(idx) //remove it from BlocksToGet if no more pending downloads\r\n\r\n\tstore_on_disk := len(BlocksToGet) > 10 && common.GetBool(&common.CFG.Memory.CacheOnDisk) && len(b2g.Block.Raw) > 16*1024\r\n\tMutexRcv.Unlock()\r\n\r\n\tvar bei *btc.BlockExtraInfo\r\n\r\n\tif store_on_disk {\r\n\t\tif e := ioutil.WriteFile(common.TempBlocksDir()+hash.String(), b2g.Block.Raw, 0600); e == nil {\r\n\t\t\tbei = new(btc.BlockExtraInfo)\r\n\t\t\t*bei = b2g.Block.BlockExtraInfo\r\n\t\t\tb2g.Block = nil\r\n\t\t} else {\r\n\t\t\tprintln(\"write tmp block:\", e.Error())\r\n\t\t}\r\n\t}\r\n\r\n\tNetBlocks <- &BlockRcvd{Conn: conn, Block: b2g.Block, BlockTreeNode: b2g.BlockTreeNode, OneReceivedBlock: orb, BlockExtraInfo: bei}\r\n}", "func (w *Wallet) ListSinceBlock(start, end, syncHeight int32) ([]btcjson.ListTransactionsResult, er.R) {\n\ttxList := []btcjson.ListTransactionsResult{}\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\ttxmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)\n\n\t\trangeFn := func(details []wtxmgr.TxDetails) (bool, er.R) {\n\t\t\tfor _, detail := range details {\n\t\t\t\tjsonResults := listTransactions(tx, &detail,\n\t\t\t\t\tw.Manager, syncHeight, w.chainParams)\n\t\t\t\ttxList = append(txList, jsonResults...)\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn w.TxStore.RangeTransactions(txmgrNs, start, end, rangeFn)\n\t})\n\treturn txList, err\n}", "func Blocks(mods ...qm.QueryMod) blockQuery {\n\tmods = append(mods, qm.From(\"\\\"block\\\"\"))\n\treturn blockQuery{NewQuery(mods...)}\n}", "func (cs *ConsensusSet) managedAcceptBlocks(blocks []types.Block) (blockchainExtended bool, err error) {\n\t// Grab a lock on the consensus set.\n\tcs.mu.Lock()\n\tdefer cs.mu.Unlock()\n\n\t// Make sure that blocks are consecutive. Though this isn't a strict\n\t// requirement, if blocks are not consecutive then it becomes a lot harder\n\t// to maintain correctness when adding multiple blocks in a single tx.\n\t//\n\t// This is the first time that IDs on the blocks have been computed.\n\tblockIDs := make([]types.BlockID, 0, len(blocks))\n\tfor i := 0; i < len(blocks); i++ {\n\t\tblockIDs = append(blockIDs, blocks[i].ID())\n\t\tif i > 0 && blocks[i].ParentID != blockIDs[i-1] {\n\t\t\treturn false, errNonLinearChain\n\t\t}\n\t}\n\n\t// Verify the headers for every block, throw out known blocks, and the\n\t// invalid blocks (which includes the children of invalid blocks).\n\tchainExtended := false\n\tchanges := make([]changeEntry, 0, len(blocks))\n\tsetErr := cs.db.Update(func(tx *bolt.Tx) error {\n\t\tfor i := 0; i < len(blocks); i++ {\n\t\t\t// Start by checking the header of the block.\n\t\t\tparent, err := cs.validateHeaderAndBlock(boltTxWrapper{tx}, blocks[i], blockIDs[i])\n\t\t\tif err == modules.ErrBlockKnown {\n\t\t\t\t// Skip over known blocks.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err == errFutureTimestamp {\n\t\t\t\t// Queue the block to be tried again if it is a future block.\n\t\t\t\tgo cs.threadedSleepOnFutureBlock(blocks[i])\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// log.Printf(\"\\n\\nmanagedAcceptBlocks: %d %s\", parent.Height+1, blocks[i].ID())\n\n\t\t\t// Try adding the block to consensus.\n\t\t\tchangeEntry, err := cs.addBlockToTree(tx, blocks[i], parent)\n\t\t\tif err == nil {\n\t\t\t\tchanges = append(changes, changeEntry)\n\t\t\t\tchainExtended = true\n\t\t\t\tvar applied, reverted []string\n\t\t\t\tfor _, b := range changeEntry.AppliedBlocks {\n\t\t\t\t\tapplied = append(applied, b.String()[:6])\n\t\t\t\t}\n\t\t\t\tfor _, b := range changeEntry.RevertedBlocks {\n\t\t\t\t\treverted = append(reverted, b.String()[:6])\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err == modules.ErrNonExtendingBlock {\n\t\t\t\terr = nil\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// Sanity check - we should never apply fewer blocks than we revert.\n\t\t\tif len(changeEntry.AppliedBlocks) < len(changeEntry.RevertedBlocks) {\n\t\t\t\terr := errors.New(\"after adding a change entry, there are more reverted blocks than applied ones\")\n\t\t\t\tcs.log.Severe(err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif _, ok := setErr.(bolt.MmapError); ok {\n\t\tcs.log.Println(\"ERROR: Bolt mmap failed:\", setErr)\n\t\tfmt.Println(\"Blockchain database has run out of disk space!\")\n\t\tos.Exit(1)\n\t}\n\tif setErr != nil {\n\t\tif len(changes) == 0 {\n\t\t\tcs.log.Println(\"Consensus received an invalid block:\", setErr)\n\t\t} else {\n\t\t\tfmt.Println(\"Received a partially valid block set.\")\n\t\t\tcs.log.Println(\"Consensus received a chain of blocks, where one was valid, but others were not:\", setErr)\n\t\t}\n\t\treturn false, setErr\n\t}\n\t// Stop here if the blocks did not extend the longest blockchain.\n\tif !chainExtended {\n\t\treturn false, modules.ErrNonExtendingBlock\n\t}\n\t// Send any changes to subscribers.\n\tfor i := 0; i < len(changes); i++ {\n\t\tcs.updateSubscribers(changes[i])\n\t}\n\treturn chainExtended, nil\n}", "func (bc *Blockchain) GetBlocks(offset uint32, limit uint32) ([]*block.Block, error) {\n\tblks, err := bc.r.Block.GetByRange(offset, limit)\n\tif err != nil {\n\t\tif err == repository.ErrNotFound {\n\t\t\treturn make([]*block.Block, 0), err\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn blks, nil\n}", "func (b *blocksProviderImpl) DeliverBlocks() {\n\terrorStatusCounter := 0\n\tvar statusCounter uint64 = 0\n\tvar verErrCounter uint64 = 0\n\tvar delay time.Duration\n\n\tdefer b.client.CloseSend()\n\tfor !b.isDone() {\n\t\tmsg, err := b.client.Recv()\n\t\tif err != nil {\n\t\t\tlogger.Warningf(\"[%s] Receive error: %s\", b.chainID, err.Error())\n\t\t\treturn\n\t\t}\n\t\tswitch t := msg.Type.(type) {\n\t\tcase *orderer.DeliverResponse_Status:\n\t\t\tverErrCounter = 0\n\n\t\t\tif t.Status == common.Status_SUCCESS {\n\t\t\t\tlogger.Warningf(\"[%s] ERROR! Received success for a seek that should never complete\", b.chainID)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif t.Status == common.Status_BAD_REQUEST || t.Status == common.Status_FORBIDDEN {\n\t\t\t\tlogger.Errorf(\"[%s] Got error %v\", b.chainID, t)\n\t\t\t\terrorStatusCounter++\n\t\t\t\tif errorStatusCounter > b.wrongStatusThreshold {\n\t\t\t\t\tlogger.Criticalf(\"[%s] Wrong statuses threshold passed, stopping block provider\", b.chainID)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terrorStatusCounter = 0\n\t\t\t\tlogger.Warningf(\"[%s] Got error %v\", b.chainID, t)\n\t\t\t}\n\n\t\t\tdelay, statusCounter = computeBackOffDelay(statusCounter)\n\t\t\ttime.Sleep(delay)\n\t\t\tb.client.Disconnect()\n\t\t\tcontinue\n\t\tcase *orderer.DeliverResponse_Block:\n\t\t\terrorStatusCounter = 0\n\t\t\tstatusCounter = 0\n\t\t\tblockNum := t.Block.Header.Number\n\n\t\t\tmarshaledBlock, err := proto.Marshal(t.Block)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(\"[%s] Error serializing block with sequence number %d, due to %s; Disconnecting client from orderer.\", b.chainID, blockNum, err)\n\t\t\t\tdelay, verErrCounter = computeBackOffDelay(verErrCounter)\n\t\t\t\ttime.Sleep(delay)\n\t\t\t\tb.client.Disconnect()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err := b.mcs.VerifyBlock(gossipcommon.ChannelID(b.chainID), blockNum, t.Block); err != nil {\n\t\t\t\tlogger.Errorf(\"[%s] Error verifying block with sequence number %d, due to %s; Disconnecting client from orderer.\", b.chainID, blockNum, err)\n\t\t\t\tdelay, verErrCounter = computeBackOffDelay(verErrCounter)\n\t\t\t\ttime.Sleep(delay)\n\t\t\t\tb.client.Disconnect()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tverErrCounter = 0 // On a good block\n\n\t\t\tnumberOfPeers := len(b.gossip.PeersOfChannel(gossipcommon.ChannelID(b.chainID)))\n\t\t\t// Create payload with a block received\n\t\t\tpayload := createPayload(blockNum, marshaledBlock)\n\t\t\t// Use payload to create gossip message\n\t\t\tgossipMsg := createGossipMsg(b.chainID, payload)\n\n\t\t\tlogger.Debugf(\"[%s] Adding payload to local buffer, blockNum = [%d]\", b.chainID, blockNum)\n\t\t\t// Add payload to local state payloads buffer\n\t\t\tif err := b.gossip.AddPayload(b.chainID, payload); err != nil {\n\t\t\t\tlogger.Warningf(\"Block [%d] received from ordering service wasn't added to payload buffer: %v\", blockNum, err)\n\t\t\t}\n\n\t\t\t// Gossip messages with other nodes\n\t\t\tlogger.Debugf(\"[%s] Gossiping block [%d], peers number [%d]\", b.chainID, blockNum, numberOfPeers)\n\t\t\tif !b.isDone() {\n\t\t\t\tb.gossip.Gossip(gossipMsg)\n\t\t\t}\n\n\t\t\tb.client.UpdateReceived(blockNum)\n\n\t\tdefault:\n\t\t\tlogger.Warningf(\"[%s] Received unknown: %v\", b.chainID, t)\n\t\t\treturn\n\t\t}\n\t}\n}", "func findMissingBlocks(nodeNum int, aNode *rpctest.Harness, expectedBlocks map[string]int) (map[string]int, error) {\n\tmissing := make(map[string]int)\n\n\ttips, err := aNode.Node.GetDAGTips()\n\tif err != nil {\n\t\treturn missing, err\n\t}\n\n\tfoundBlocks := make(map[string]int)\n\tfor height := int32(0); height <= tips.MaxHeight; height++ {\n\t\thashes, err := aNode.Node.GetBlockHash(int64(height))\n\t\tif err != nil {\n\t\t\treturn missing, err\n\t\t}\n\t\tvar hashStrings []string\n\t\tfor _, h := range hashes {\n\t\t\thashStrings = append(hashStrings, (*h).String())\n\t\t}\n\n\t\tfor _, hash := range hashes {\n\t\t\tfoundBlocks[hash.String()] = 0\n\t\t}\n\t}\n\n\tfor hash, _ := range expectedBlocks {\n\t\t_, ok := foundBlocks[hash]\n\t\tif !ok {\n\t\t\tmissing[hash] = 0\n\t\t}\n\t}\n\n\treturn missing, nil\n}", "func getblockchain() []Block {\n\tIntblock = *new(IntBlock)\n\tallchains(Mainblockchain.Root, 0)\n\tvar bestsofar = 0\n\tvar lastindex = 0\n\tvar node []Block\n\tfor index, c := range Intblock.clist {\n\t\tif bestsofar <= c {\n\t\t\tbestsofar = c\n\t\t\tlastindex = index\n\t\t}\n\t}\n\tfor i := 0; i <= bestsofar; i++ {\n\t\tnode = append([]Block{Intblock.blist[lastindex+i]}, node...)\n\t}\n\treturn node\n}", "func (s *service) MineNewBlock(lastBlock *Block, data []Transaction) (*Block, error) {\n\t// validations\n\tif lastBlock == nil {\n\t\treturn nil, ErrMissingLastBlock\n\t}\n\n\tdifficulty := lastBlock.Difficulty\n\tvar nonce uint32\n\tvar timestamp int64\n\tvar hash string\n\tfor {\n\t\tnonce++\n\t\ttimestamp = time.Now().UnixNano()\n\t\tdifficulty = adjustBlockDifficulty(*lastBlock, timestamp, s.MineRate)\n\t\thash = hashing.SHA256Hash(timestamp, *lastBlock.Hash, data, nonce, difficulty)\n\t\tif hexStringToBinary(hash)[:difficulty] == strings.Repeat(\"0\", int(difficulty)) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn yieldBlock(timestamp, lastBlock.Hash, &hash, data, nonce, difficulty), nil\n}", "func Block(b models.Block) *genModels.BlocksRow {\n\tts := b.Timestamp.Unix()\n\n\tgenBlock := genModels.BlocksRow{\n\t\tLevel: b.Level.Ptr(),\n\t\tProto: b.Proto.Ptr(),\n\t\tBlockTime: b.BlockTime,\n\t\tPredecessor: b.Predecessor.Ptr(),\n\t\tTimestamp: &ts,\n\t\tValidationPass: b.ValidationPass.Ptr(),\n\t\tFitness: b.Fitness.Ptr(),\n\t\tContext: b.Context,\n\t\tSignature: b.Signature,\n\t\tProtocol: b.Protocol.Ptr(),\n\t\tPriority: b.Priority.Ptr(),\n\t\tChainID: b.ChainID,\n\t\tHash: b.Hash.Ptr(),\n\t\tReward: &b.Reward,\n\t\tDeposit: b.Deposit,\n\t\tOperationsHash: b.OperationsHash,\n\t\tPeriodKind: b.PeriodKind,\n\t\tCurrentExpectedQuorum: b.CurrentExpectedQuorum,\n\t\tActiveProposal: b.ActiveProposal,\n\t\tBaker: b.Baker,\n\t\tBakerName: b.BakerName,\n\t\tNonceHash: b.NonceHash,\n\t\tConsumedGas: b.ConsumedGas,\n\t\tMetaLevel: b.MetaLevel,\n\t\tMetaLevelPosition: b.MetaLevelPosition,\n\t\tMetaCycle: b.MetaCycle,\n\t\tMetaCyclePosition: b.MetaCyclePosition,\n\t\tMetaVotingPeriod: b.MetaVotingPeriod,\n\t\tMetaVotingPeriodPosition: b.MetaVotingPeriodPosition,\n\t\tExpectedCommitment: b.ExpectedCommitment,\n\t}\n\n\tif b.BlockAggregation != nil {\n\t\tgenBlock.Volume = b.BlockAggregation.Volume\n\t\tgenBlock.Fees = b.BlockAggregation.Fees\n\t\tgenBlock.Endorsements = b.BlockAggregation.Endorsements\n\t\tgenBlock.Proposals = b.BlockAggregation.Proposals\n\t\tgenBlock.SeedNonceRevelations = b.BlockAggregation.SeedNonceRevelations\n\t\tgenBlock.Delegations = b.BlockAggregation.Delegations\n\t\tgenBlock.Transactions = b.BlockAggregation.Transactions\n\t\tgenBlock.ActivateAccounts = b.BlockAggregation.ActivateAccounts\n\t\tgenBlock.Ballots = b.BlockAggregation.Ballots\n\t\tgenBlock.Originations = b.BlockAggregation.Originations\n\t\tgenBlock.Reveals = b.BlockAggregation.Reveals\n\t\tgenBlock.DoubleBakingEvidence = b.BlockAggregation.DoubleBakingEvidences\n\t\tgenBlock.DoubleEndorsementEvidence = b.BlockAggregation.DoubleEndorsementEvidences\n\t\tgenBlock.NumberOfOperations = b.BlockAggregation.NumberOfOperations\n\t}\n\n\treturn &genBlock\n}", "func (synckerManager *SynckerManager) GetCrossShardBlocksForShardProducer(toShard byte, limit map[byte][]uint64) map[byte][]interface{} {\n\t//get last confirm crossshard -> process request until retrieve info\n\tres := make(map[byte][]interface{})\n\tbeaconDB := synckerManager.config.Node.GetBeaconChainDatabase()\n\tlastRequestCrossShard := synckerManager.ShardSyncProcess[int(toShard)].Chain.GetCrossShardState()\n\tbc := synckerManager.config.Blockchain\n\tfor i := 0; i < synckerManager.config.Node.GetChainParam().ActiveShards; i++ {\n\t\tfor {\n\t\t\tif i == int(toShard) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t//if limit has 0 length, we should break now\n\t\t\tif limit != nil && len(res[byte(i)]) >= len(limit[byte(i)]) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\trequestHeight := lastRequestCrossShard[byte(i)]\n\t\t\tnextCrossShardInfo := synckerManager.config.Node.FetchNextCrossShard(i, int(toShard), requestHeight)\n\t\t\tif nextCrossShardInfo == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif requestHeight == nextCrossShardInfo.NextCrossShardHeight {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tLogger.Info(\"nextCrossShardInfo.NextCrossShardHeight\", i, toShard, requestHeight, nextCrossShardInfo)\n\n\t\t\tbeaconHash, _ := common.Hash{}.NewHashFromStr(nextCrossShardInfo.ConfirmBeaconHash)\n\t\t\tbeaconBlockBytes, err := rawdbv2.GetBeaconBlockByHash(beaconDB, *beaconHash)\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tbeaconBlock := new(blockchain.BeaconBlock)\n\t\t\tjson.Unmarshal(beaconBlockBytes, beaconBlock)\n\n\t\t\tfor _, shardState := range beaconBlock.Body.ShardState[byte(i)] {\n\t\t\t\tif shardState.Height == nextCrossShardInfo.NextCrossShardHeight {\n\t\t\t\t\tif synckerManager.crossShardPool[int(toShard)].HasHash(shardState.Hash) {\n\t\t\t\t\t\t//validate crossShardBlock before add to result\n\t\t\t\t\t\tblkXShard := synckerManager.crossShardPool[int(toShard)].GetBlock(shardState.Hash)\n\t\t\t\t\t\tbeaconConsensusRootHash, err := bc.GetBeaconConsensusRootHash(bc.GetBeaconBestState(), beaconBlock.GetHeight()-1)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tLogger.Error(\"Cannot get beacon consensus root hash from block \", beaconBlock.GetHeight()-1)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbeaconConsensusStateDB, err := statedb.NewWithPrefixTrie(beaconConsensusRootHash, statedb.NewDatabaseAccessWarper(bc.GetBeaconChainDatabase()))\n\t\t\t\t\t\tcommittee := statedb.GetOneShardCommittee(beaconConsensusStateDB, byte(i))\n\t\t\t\t\t\terr = bc.ShardChain[byte(i)].ValidateBlockSignatures(blkXShard.(common.BlockInterface), committee)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tLogger.Error(\"Validate crossshard block fail\", blkXShard.GetHeight(), blkXShard.Hash())\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//add to result list\n\t\t\t\t\t\tres[byte(i)] = append(res[byte(i)], blkXShard)\n\t\t\t\t\t\t//has block in pool, update request pointer\n\t\t\t\t\t\tlastRequestCrossShard[byte(i)] = nextCrossShardInfo.NextCrossShardHeight\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//cannot append crossshard for a shard (no block in pool, validate error) => break process for this shard\n\t\t\tif requestHeight == lastRequestCrossShard[byte(i)] {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif len(res[byte(i)]) >= MAX_CROSSX_BLOCK {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}", "func TestBlock(t *testing.T) {\n\tb := btcutil.NewBlock(&Block100000)\n\n\t// Ensure we get the same data back out.\n\tif msgBlock := b.MsgBlock(); !reflect.DeepEqual(msgBlock, &Block100000) {\n\t\tt.Errorf(\"MsgBlock: mismatched MsgBlock - got %v, want %v\",\n\t\t\tspew.Sdump(msgBlock), spew.Sdump(&Block100000))\n\t}\n\n\t// Ensure block height set and get work properly.\n\twantHeight := int32(100000)\n\tb.SetHeight(wantHeight)\n\tif gotHeight := b.Height(); gotHeight != wantHeight {\n\t\tt.Errorf(\"Height: mismatched height - got %v, want %v\",\n\t\t\tgotHeight, wantHeight)\n\t}\n\n\t// Hash for block 100,000.\n\twantHashStr := \"3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506\"\n\twantHash, err := chainhash.NewHashFromStr(wantHashStr)\n\tif err != nil {\n\t\tt.Errorf(\"NewHashFromStr: %v\", err)\n\t}\n\n\t// Request the hash multiple times to test generation and caching.\n\tfor i := 0; i < 2; i++ {\n\t\thash := b.Hash()\n\t\tif !hash.IsEqual(wantHash) {\n\t\t\tt.Errorf(\"Hash #%d mismatched hash - got %v, want %v\",\n\t\t\t\ti, hash, wantHash)\n\t\t}\n\t}\n\n\t// Hashes for the transactions in Block100000.\n\twantTxHashes := []string{\n\t\t\"8c14f0db3df150123e6f3dbbf30f8b955a8249b62ac1d1ff16284aefa3d06d87\",\n\t\t\"fff2525b8931402dd09222c50775608f75787bd2b87e56995a7bdd30f79702c4\",\n\t\t\"6359f0868171b1d194cbee1af2f16ea598ae8fad666d9b012c8ed2b79a236ec4\",\n\t\t\"e9a66845e05d5abc0ad04ec80f774a7e585c6e8db975962d069a522137b80c1d\",\n\t}\n\n\t// Create a new block to nuke all cached data.\n\tb = btcutil.NewBlock(&Block100000)\n\n\t// Request hash for all transactions one at a time via Tx.\n\tfor i, txHash := range wantTxHashes {\n\t\twantHash, err := chainhash.NewHashFromStr(txHash)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"NewHashFromStr: %v\", err)\n\t\t}\n\n\t\t// Request the hash multiple times to test generation and\n\t\t// caching.\n\t\tfor j := 0; j < 2; j++ {\n\t\t\ttx, err := b.Tx(i)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Tx #%d: %v\", i, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\thash := tx.Hash()\n\t\t\tif !hash.IsEqual(wantHash) {\n\t\t\t\tt.Errorf(\"Hash #%d mismatched hash - got %v, \"+\n\t\t\t\t\t\"want %v\", j, hash, wantHash)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create a new block to nuke all cached data.\n\tb = btcutil.NewBlock(&Block100000)\n\n\t// Request slice of all transactions multiple times to test generation\n\t// and caching.\n\tfor i := 0; i < 2; i++ {\n\t\ttransactions := b.Transactions()\n\n\t\t// Ensure we get the expected number of transactions.\n\t\tif len(transactions) != len(wantTxHashes) {\n\t\t\tt.Errorf(\"Transactions #%d mismatched number of \"+\n\t\t\t\t\"transactions - got %d, want %d\", i,\n\t\t\t\tlen(transactions), len(wantTxHashes))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ensure all of the hashes match.\n\t\tfor j, tx := range transactions {\n\t\t\twantHash, err := chainhash.NewHashFromStr(wantTxHashes[j])\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"NewHashFromStr: %v\", err)\n\t\t\t}\n\n\t\t\thash := tx.Hash()\n\t\t\tif !hash.IsEqual(wantHash) {\n\t\t\t\tt.Errorf(\"Transactions #%d mismatched hashes \"+\n\t\t\t\t\t\"- got %v, want %v\", j, hash, wantHash)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\n\t// Serialize the test block.\n\tvar block100000Buf bytes.Buffer\n\terr = Block100000.Serialize(&block100000Buf)\n\tif err != nil {\n\t\tt.Errorf(\"Serialize: %v\", err)\n\t}\n\tblock100000Bytes := block100000Buf.Bytes()\n\n\t// Request serialized bytes multiple times to test generation and\n\t// caching.\n\tfor i := 0; i < 2; i++ {\n\t\tserializedBytes, err := b.Bytes()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Bytes: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tif !bytes.Equal(serializedBytes, block100000Bytes) {\n\t\t\tt.Errorf(\"Bytes #%d wrong bytes - got %v, want %v\", i,\n\t\t\t\tspew.Sdump(serializedBytes),\n\t\t\t\tspew.Sdump(block100000Bytes))\n\t\t\tcontinue\n\t\t}\n\t}\n\n\t// Transaction offsets and length for the transaction in Block100000.\n\twantTxLocs := []wire.TxLoc{\n\t\t{TxStart: 81, TxLen: 144},\n\t\t{TxStart: 225, TxLen: 259},\n\t\t{TxStart: 484, TxLen: 257},\n\t\t{TxStart: 741, TxLen: 225},\n\t}\n\n\t// Ensure the transaction location information is accurate.\n\ttxLocs, err := b.TxLoc()\n\tif err != nil {\n\t\tt.Errorf(\"TxLoc: %v\", err)\n\t\treturn\n\t}\n\tif !reflect.DeepEqual(txLocs, wantTxLocs) {\n\t\tt.Errorf(\"TxLoc: mismatched transaction location information \"+\n\t\t\t\"- got %v, want %v\", spew.Sdump(txLocs),\n\t\t\tspew.Sdump(wantTxLocs))\n\t}\n}", "func (f *Builder) GetBlocks(ctx context.Context, cids []cid.Cid) ([]*types.Block, error) {\n\tvar ret []*types.Block\n\tfor _, c := range cids {\n\t\tif block, ok := f.blocks[c]; ok {\n\t\t\tret = append(ret, block)\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"no block %s\", c)\n\t\t}\n\t}\n\treturn ret, nil\n}", "func loadBlocks(t *testing.T, dataFile string, network wire.BitcoinNet) (\n\t[]*btcutil.Block, error) {\n\t// Open the file that contains the blocks for reading.\n\tfi, err := os.Open(dataFile)\n\tif err != nil {\n\t\tt.Errorf(\"failed to open file %v, err %v\", dataFile, err)\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif err := fi.Close(); err != nil {\n\t\t\tt.Errorf(\"failed to close file %v %v\", dataFile,\n\t\t\t\terr)\n\t\t}\n\t}()\n\tdr := bzip2.NewReader(fi)\n\n\t// Set the first block as the genesis block.\n\tblocks := make([]*btcutil.Block, 0, 256)\n\tgenesis := btcutil.NewBlock(chaincfg.MainNetParams.GenesisBlock)\n\tblocks = append(blocks, genesis)\n\n\t// Load the remaining blocks.\n\tfor height := 1; ; height++ {\n\t\tvar net uint32\n\t\terr := binary.Read(dr, binary.LittleEndian, &net)\n\t\tif err == io.EOF {\n\t\t\t// Hit end of file at the expected offset. No error.\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to load network type for block %d: %v\",\n\t\t\t\theight, err)\n\t\t\treturn nil, err\n\t\t}\n\t\tif net != uint32(network) {\n\t\t\tt.Errorf(\"Block doesn't match network: %v expects %v\",\n\t\t\t\tnet, network)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar blockLen uint32\n\t\terr = binary.Read(dr, binary.LittleEndian, &blockLen)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to load block size for block %d: %v\",\n\t\t\t\theight, err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Read the block.\n\t\tblockBytes := make([]byte, blockLen)\n\t\t_, err = io.ReadFull(dr, blockBytes)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to load block %d: %v\", height, err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Deserialize and store the block.\n\t\tblock, err := btcutil.NewBlockFromBytes(blockBytes)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to parse block %v: %v\", height, err)\n\t\t\treturn nil, err\n\t\t}\n\t\tblocks = append(blocks, block)\n\t}\n\n\treturn blocks, nil\n}", "func (s *Store) rangeBlockTransactions(ns walletdb.ReadBucket, begin, end int32,\n\tf func([]TxDetails) (bool, error)) (bool, error) {\n\n\t// Mempool height is considered a high bound.\n\tif begin < 0 {\n\t\tbegin = int32(^uint32(0) >> 1)\n\t}\n\tif end < 0 {\n\t\tend = int32(^uint32(0) >> 1)\n\t}\n\n\tvar blockIter blockIterator\n\tvar advance func(*blockIterator) bool\n\tif begin < end {\n\t\t// Iterate in forwards order\n\t\tblockIter = makeReadBlockIterator(ns, begin)\n\t\tadvance = func(it *blockIterator) bool {\n\t\t\tif !it.next() {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn it.elem.Height <= end\n\t\t}\n\t} else {\n\t\t// Iterate in backwards order, from begin -> end.\n\t\tblockIter = makeReadBlockIterator(ns, begin)\n\t\tadvance = func(it *blockIterator) bool {\n\t\t\tif !it.prev() {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn end <= it.elem.Height\n\t\t}\n\t}\n\n\tvar details []TxDetails\n\tfor advance(&blockIter) {\n\t\tblock := &blockIter.elem\n\n\t\tif cap(details) < len(block.transactions) {\n\t\t\tdetails = make([]TxDetails, 0, len(block.transactions))\n\t\t} else {\n\t\t\tdetails = details[:0]\n\t\t}\n\n\t\tfor _, txHash := range block.transactions {\n\t\t\tk := keyTxRecord(&txHash, &block.Block)\n\t\t\tv := existsRawTxRecord(ns, k)\n\t\t\tif v == nil {\n\t\t\t\tstr := fmt.Sprintf(\"missing transaction %v for \"+\n\t\t\t\t\t\"block %v\", txHash, block.Height)\n\t\t\t\treturn false, storeError(ErrData, str, nil)\n\t\t\t}\n\n\t\t\tdetail, err := s.minedTxDetails(ns, &txHash, k, v)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\tdetails = append(details, *detail)\n\t\t}\n\n\t\t// Every block record must have at least one transaction, so it\n\t\t// is safe to call f.\n\t\tbrk, err := f(details)\n\t\tif err != nil || brk {\n\t\t\treturn brk, err\n\t\t}\n\t}\n\treturn false, blockIter.err\n}", "func NewBlock(chain uint64, producer Address) *StBlock {\n\tvar hashPowerLimit uint64\n\tvar blockInterval uint64\n\tvar pStat BaseInfo\n\tout := new(StBlock)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatHashPower}, &hashPowerLimit)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBlockInterval}, &blockInterval)\n\n\tif pStat.ID == 0 {\n\t\tlog.Println(\"fail to get the last block. chain:\", chain)\n\t\treturn nil\n\t}\n\n\thashPowerLimit = hashPowerLimit / 1000\n\tif hashPowerLimit < minHPLimit {\n\t\thashPowerLimit = minHPLimit\n\t}\n\n\tout.HashpowerLimit = hashPowerLimit\n\n\tif pStat.ID == 1 && chain > 1 {\n\t\tpStat.Time = pStat.Time + blockSyncMax + blockSyncMin + TimeSecond\n\t} else {\n\t\tpStat.Time += blockInterval\n\t}\n\n\tout.Previous = pStat.Key\n\tout.Producer = producer\n\tout.Time = pStat.Time\n\n\tout.Chain = chain\n\tout.Index = pStat.ID + 1\n\n\tif pStat.Chain > 1 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID+1), &key)\n\t\tgetDataFormLog(chain/2, logBlockInfo{}, key[:], &tmp)\n\t\tif out.Index != 2 && !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID+2), &key2)\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.Parent = key2\n\t\t\t} else {\n\t\t\t\tout.Parent = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else {\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID), &key)\n\t\t\tout.Parent = key\n\t\t}\n\t}\n\tif pStat.LeftChildID > 0 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID+1), &key)\n\t\tgetDataFormLog(2*chain, logBlockInfo{}, key[:], &tmp)\n\t\tif !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID+2), &key2)\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.LeftChild = key2\n\t\t\t} else {\n\t\t\t\tout.LeftChild = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else if pStat.LeftChildID == 1 {\n\t\t\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID), &key)\n\t\t\tout.LeftChild = key\n\t\t} else {\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID), &key)\n\t\t\tout.LeftChild = key\n\t\t}\n\t}\n\tif pStat.RightChildID > 0 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID+1), &key)\n\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, key[:], &tmp)\n\t\tif !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID+2), &key2)\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.RightChild = key2\n\t\t\t} else {\n\t\t\t\tout.RightChild = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else if pStat.RightChildID == 1 {\n\t\t\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(pStat.RightChildID), &key)\n\t\t\tout.RightChild = key\n\t\t} else {\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID), &key)\n\t\t\tout.RightChild = key\n\t\t}\n\t}\n\n\treturn out\n}", "func (s *stateMemory) GetMemoryBlocks(podUID string, containerName string) []Block {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tif res, ok := s.assignments[podUID][containerName]; ok {\n\t\treturn append([]Block{}, res...)\n\t}\n\treturn nil\n}", "func (b *Bitcoin) ConfirmationBlock() uint64 {\n\treturn b.confirmationBlock\n}", "func (am *AccountManager) ListSinceBlock(since, curBlockHeight int32,\n\tminconf int) ([]btcjson.ListTransactionsResult, error) {\n\n\t// Create and fill a map of account names and their balances.\n\tvar txList []btcjson.ListTransactionsResult\n\tfor _, a := range am.AllAccounts() {\n\t\ttxTmp, err := a.ListSinceBlock(since, curBlockHeight, minconf)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttxList = append(txList, txTmp...)\n\t}\n\treturn txList, nil\n}", "func (ts *Tipset) Block(miner Miner, winCount int64, msgs ...*ApplicableMessage) {\n\tblock := Block{\n\t\tMinerAddr: miner.MinerActorAddr.ID,\n\t\tWinCount: winCount,\n\t}\n\tfor _, am := range msgs {\n\t\tblock.Messages = append(block.Messages, MustSerialize(am.Message))\n\n\t\t// if we see this message for the first time, add it to the `msgIdx` map and to the `orderMsgs` slice.\n\t\tif _, ok := ts.tss.msgIdx[am.Message.Cid()]; !ok {\n\t\t\tts.tss.msgIdx[am.Message.Cid()] = am\n\t\t\tts.tss.orderedMsgs = append(ts.tss.orderedMsgs, am)\n\t\t}\n\t}\n\n\tts.Blocks = append(ts.Blocks, block)\n}", "func (blockchain *Blockchain) MineNewBlock(originalTxs []*Transaction) *Block {\n\t// Reward of mining a block\n\tcoinBaseTransaction := NewRewardTransacion()\n\ttxs := []*Transaction{coinBaseTransaction}\n\ttxs = append(txs, originalTxs...)\n\t// Verify transactions\n\tfor _, tx := range txs {\n\t\tif !tx.IsCoinBaseTransaction() {\n\t\t\tif blockchain.VerifityTransaction(tx, txs) == false {\n\t\t\t\tlog.Panic(\"Verify transaction failed...\")\n\t\t\t}\n\t\t}\n\t}\n\n\tDBName := fmt.Sprintf(DBName, os.Getenv(\"NODE_ID\"))\n\tdb, err := bolt.Open(DBName, 0600, nil)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tdefer db.Close()\n\t// Get the latest block\n\tvar block Block\n\terr = db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(BlockBucketName))\n\t\tif b != nil {\n\t\t\thash := b.Get([]byte(\"l\"))\n\t\t\tblockBytes := b.Get(hash)\n\t\t\tgobDecode(blockBytes, &block)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\t// Mine a new block\n\tnewBlock := NewBlock(txs, block.Height+1, block.BlockHash)\n\n\treturn newBlock\n}", "func (gw *Gateway) GetBlocksInRangeVerbose(start, end uint64) ([]coin.SignedBlock, [][][]visor.TransactionInput, error) {\n\tvar blocks []coin.SignedBlock\n\tvar inputs [][][]visor.TransactionInput\n\tvar err error\n\tgw.strand(\"GetBlocksInRangeVerbose\", func() {\n\t\tblocks, inputs, err = gw.v.GetBlocksInRangeVerbose(start, end)\n\t})\n\treturn blocks, inputs, err\n}", "func (a *IqnpoolApiService) GetIqnpoolBlockList(ctx context.Context) ApiGetIqnpoolBlockListRequest {\n\treturn ApiGetIqnpoolBlockListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (ns *EsIndexer) IndexBlocksInRange(fromBlockHeight uint64, toBlockHeight uint64) {\n\tctx := context.Background()\n\tchannel := make(chan EsType, 1000)\n\tdone := make(chan struct{})\n\ttxChannel := make(chan EsType, 20000)\n\tnameChannel := make(chan EsType, 5000)\n\tgenerator := func() error {\n\t\tdefer close(channel)\n\t\tdefer close(done)\n\t\tns.log.Info().Msg(fmt.Sprintf(\"Indexing %d missing blocks [%d..%d]\", (1 + toBlockHeight - fromBlockHeight), fromBlockHeight, toBlockHeight))\n\t\tfor blockHeight := fromBlockHeight; blockHeight <= toBlockHeight; blockHeight++ {\n\t\t\tblockQuery := make([]byte, 8)\n\t\t\tbinary.LittleEndian.PutUint64(blockQuery, uint64(blockHeight))\n\t\t\tblock, err := ns.grpcClient.GetBlock(context.Background(), &types.SingleBytes{Value: blockQuery})\n\t\t\tif err != nil {\n\t\t\t\tns.log.Warn().Uint64(\"blockHeight\", blockHeight).Err(err).Msg(\"Failed to get block\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(block.Body.Txs) > 0 {\n\t\t\t\tns.IndexTxs(block, block.Body.Txs, txChannel, nameChannel)\n\t\t\t}\n\t\t\td := ConvBlock(block)\n\t\t\tselect {\n\t\t\tcase channel <- d:\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\twaitForTx := func() error {\n\t\tdefer close(txChannel)\n\t\t<-done\n\t\treturn nil\n\t}\n\tgo BulkIndexer(ctx, ns.log, ns.client, txChannel, waitForTx, ns.indexNamePrefix+\"tx\", \"tx\", 10000, false)\n\n\twaitForNames := func() error {\n\t\tdefer close(nameChannel)\n\t\t<-done\n\t\treturn nil\n\t}\n\tgo BulkIndexer(ctx, ns.log, ns.client, nameChannel, waitForNames, ns.indexNamePrefix+\"name\", \"name\", 2500, true)\n\n\tBulkIndexer(ctx, ns.log, ns.client, channel, generator, ns.indexNamePrefix+\"block\", \"block\", 500, false)\n\n\tns.OnSyncComplete()\n}", "func (lc *LedgerCommitter) GetBlocks(blockSeqs []uint64) []*common.Block {\n\tvar blocks []*common.Block\n\n\tfor _, seqNum := range blockSeqs {\n\t\tif blck, err := lc.GetBlockByNumber(seqNum); err != nil {\n\t\t\tlogger.Errorf(\"Not able to acquire block num %d, from the ledger skipping...\", seqNum)\n\t\t\tcontinue\n\t\t} else {\n\t\t\tlogger.Debug(\"Appending next block with seqNum = \", seqNum, \" to the resulting set\")\n\t\t\tblocks = append(blocks, blck)\n\t\t}\n\t}\n\n\treturn blocks\n}", "func (env *Env) CheckBlock(pdu *libcoap.Pdu) (bool, *string, *libcoap.Block) {\n blockValue, err := pdu.GetOptionIntegerValue(libcoap.OptionBlock2)\n if err != nil {\n log.WithError(err).Warn(\"Get block2 option value failed.\")\n return false, nil, nil\n\t}\n block := libcoap.IntToBlock(int(blockValue))\n\n size2Value, err := pdu.GetOptionIntegerValue(libcoap.OptionSize2)\n\tif err != nil {\n\t\tlog.WithError(err).Warn(\"Get size 2 option value failed.\")\n return false, nil, nil\n }\n\n eTag := pdu.GetOptionOpaqueValue(libcoap.OptionEtag)\n\n if block != nil {\n isMoreBlock := true\n blockKey := eTag + string(pdu.Token)\n // If block.M = 1, block is more block. If block.M = 0, block is last block\n if block.M == libcoap.MORE_BLOCK {\n log.Debugf(\"Response block is comming (eTag=%+v, block=%+v, size2=%+v) for request (token=%+v), waiting for the next block.\", eTag, block.ToString(), size2Value, pdu.Token)\n if block.NUM == 0 {\n env.responseBlocks[blockKey] = pdu\n initialBlockSize := env.InitialRequestBlockSize()\n secondBlockSize := env.SecondRequestBlockSize()\n // Check what block_size is used for block2 option\n // If the initialBlockSize is set: client will always request with block2 option\n // If the initialBlockSize is not set and the secondBlockSize is set: if the secondBlockSize is greater than the\n // recommended block size -> use the recommended block size, reversely, use the configured block size\n // If both initialBlockSize and secondBlockSize are not set -> use the recommended block size\n if initialBlockSize == nil && secondBlockSize != nil {\n if *secondBlockSize > block.SZX {\n log.Warn(\"Second block size must not greater thans block size received from server\")\n block.NUM += 1\n } else {\n block.NUM = 1 << uint(block.SZX - *secondBlockSize)\n block.SZX = *secondBlockSize\n }\n } else {\n block.NUM += 1\n }\n } else {\n if data, ok := env.responseBlocks[blockKey]; ok {\n env.responseBlocks[blockKey].Data = append(data.Data, pdu.Data...)\n block.NUM += 1\n } else {\n log.Warnf(\"The block version is not unknown. Re-request from the first block\")\n delete(env.responseBlocks, blockKey)\n block.NUM = 0\n }\n }\n block.M = 0\n return isMoreBlock, &eTag, block\n } else if block.M == libcoap.LAST_BLOCK {\n log.Debugf(\"Response block is comming (eTag=%+v, block=%+v, size2=%+v), this is the last block.\", eTag, block.ToString(), size2Value)\n isMoreBlock = false\n if data, ok := env.responseBlocks[blockKey]; ok {\n env.responseBlocks[blockKey].Data = append(data.Data, pdu.Data...)\n } else if block.NUM > 0 {\n log.Warnf(\"The block version is not unknown. Re-request from the first block\")\n delete(env.responseBlocks, blockKey)\n block.NUM = 0\n isMoreBlock = true\n }\n return isMoreBlock, &eTag, block\n }\n }\n return false, nil, nil\n}", "func AskForBlock(height int32, hash string) {\n\t//TODO -> TEST: Update this function to recursively ask\n\t// for all the missing predesessor blocks instead of only the parent block.\n\tPeers.Rebalance()\n\n\tfor key, _ := range Peers.Copy() {\n\t\tresp, err := http.Get(key + \"/block/\" + string(height) + \"/\" + hash)\n\t\tif err != nil {\n\t\t\tprintln(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif resp.StatusCode == 200 {\n\t\t\trespData, erro := ioutil.ReadAll(resp.Body)\n\t\t\tif erro != nil {\n\t\t\t\tprintln(err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\trespBlc := p2.Block{}\n\t\t\trespBlc.DecodeFromJson(string(respData))\n\t\t\tif !SBC.CheckParentHash(respBlc) {\n\t\t\t\tAskForBlock(respBlc.GetHeight()-1, respBlc.GetParentHash())\n\t\t\t}\n\t\t\tSBC.Insert(respBlc)\n\t\t\tbreak\n\t\t}\n\t}\n\n}", "func (_Rootchain *RootchainSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _Rootchain.Contract.Blocks(&_Rootchain.CallOpts, arg0)\n}", "func getBlock(res rpc.GetBlockResponse) (GetBlockResponse, error) {\n\ttxs := make([]GetBlockTransaction, 0, len(res.Result.Transactions))\n\tfor _, rTx := range res.Result.Transactions {\n\t\tdata, ok := rTx.Transaction.([]interface{})\n\t\tif !ok {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to cast raw response to []interface{}\")\n\t\t}\n\t\tif data[1] != string(rpc.GetTransactionConfigEncodingBase64) {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"encoding mistmatch\")\n\t\t}\n\t\trawTx, err := base64.StdEncoding.DecodeString(data[0].(string))\n\t\tif err != nil {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to base64 decode data, err: %v\", err)\n\t\t}\n\t\ttx, err := types.TransactionDeserialize(rawTx)\n\t\tif err != nil {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to deserialize transaction, err: %v\", err)\n\t\t}\n\n\t\tvar transactionMeta *TransactionMeta\n\t\tif rTx.Meta != nil {\n\t\t\tinnerInstructions := make([]TransactionMetaInnerInstruction, 0, len(rTx.Meta.InnerInstructions))\n\t\t\tfor _, metaInnerInstruction := range rTx.Meta.InnerInstructions {\n\t\t\t\tcompiledInstructions := make([]types.CompiledInstruction, 0, len(metaInnerInstruction.Instructions))\n\t\t\t\tfor _, innerInstruction := range metaInnerInstruction.Instructions {\n\t\t\t\t\tdata, err := base58.Decode(innerInstruction.Data)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to base58 decode data, data: %v, err: %v\", innerInstruction.Data, err)\n\t\t\t\t\t}\n\t\t\t\t\tcompiledInstructions = append(compiledInstructions, types.CompiledInstruction{\n\t\t\t\t\t\tProgramIDIndex: innerInstruction.ProgramIDIndex,\n\t\t\t\t\t\tAccounts: innerInstruction.Accounts,\n\t\t\t\t\t\tData: data,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tinnerInstructions = append(innerInstructions, TransactionMetaInnerInstruction{\n\t\t\t\t\tIndex: metaInnerInstruction.Index,\n\t\t\t\t\tInstructions: compiledInstructions,\n\t\t\t\t})\n\t\t\t}\n\t\t\ttransactionMeta = &TransactionMeta{\n\t\t\t\tErr: rTx.Meta.Err,\n\t\t\t\tFee: rTx.Meta.Fee,\n\t\t\t\tPreBalances: rTx.Meta.PreBalances,\n\t\t\t\tPostBalances: rTx.Meta.PostBalances,\n\t\t\t\tPreTokenBalances: rTx.Meta.PreTokenBalances,\n\t\t\t\tPostTokenBalances: rTx.Meta.PostTokenBalances,\n\t\t\t\tLogMessages: rTx.Meta.LogMessages,\n\t\t\t\tInnerInstructions: innerInstructions,\n\t\t\t}\n\t\t}\n\n\t\ttxs = append(txs,\n\t\t\tGetBlockTransaction{\n\t\t\t\tMeta: transactionMeta,\n\t\t\t\tTransaction: tx,\n\t\t\t},\n\t\t)\n\t}\n\treturn GetBlockResponse{\n\t\tBlockhash: res.Result.Blockhash,\n\t\tBlockTime: res.Result.BlockTime,\n\t\tBlockHeight: res.Result.BlockHeight,\n\t\tPreviousBlockhash: res.Result.PreviousBlockhash,\n\t\tParentSLot: res.Result.ParentSLot,\n\t\tRewards: res.Result.Rewards,\n\t\tTransactions: txs,\n\t}, nil\n}", "func MockBlock(txs []*types.Tx) *types.Block {\n\treturn &types.Block{\n\t\tBlockHeader: types.BlockHeader{Timestamp: uint64(time.Now().Nanosecond())},\n\t\tTransactions: txs,\n\t}\n}", "func Test_ValidateBlockTransactions_IsValid(t *testing.T) {\n\tvar blockTransactionValidator = &BlockTransactionValidator{}\n\t// create inputs transaction\n\tvar blockIndex = 12\n\tvar transactions = []*Transaction{\n\t\t// coinbase transaction\n\t\t{\n\t\t\tID: \"ebafa7518cac709e160f201a888bdf3c969c36993eefbf852cc30c9eb1a553b8\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"\",\n\t\t\t\t\tSignature: \"\",\n\t\t\t\t\tOutputIndex: blockIndex,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: \"coinbase-address\",\n\t\t\t\t\tAmount: CoinbaseAmount,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"3e5d88c061d2b79dd2ac79daf877232203089307d4576b2c1b3851b4920eb952\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"1\",\n\t\t\t\t\tSignature: \"567af38a37a36b25e45a63f477c2b66a8e221a27831dc87624c6ebbe92ff16c5936eb0100490cbbc0b1658a2db4a0190b55c19b6756a9907ec9bddb8dfe0c141a7208fc1be073350e17a0d65aa9511d19e6713b28e37f3c732373d77aeac8e8a3e998721a64e235a7e84e0f16d61a6e556d329988f03f546e9906f7731f1aa78955666a65fa3739ef4198d7af2babe00c0fc268078c3992d1f1d6bed6be34ed3d475bb18437dc2aac31dbd90f891d6a0c9dbeefab6d40dd7b69c1b426eaa482841a637445988518fea20969bfa99312b16a95ba2d155e44d898ca8b8f189941ced763aa111826a45b669ff0f904419e475fce41829f9f2f26b11e9a9fb4f38a10bd12bf5a629c97dda67a61431bd3839a8a28e55646bf864286bc805002164a562b4ccc874dce4b9b9f08b33df5e5063af91d58fa4edd6d5f85d6d8a28c99534881ffaebac09e5990642fa4b14d349c1c4e23d3bd4d600f2e521b803c57c0b3fb820f81d8ba915cea300dc722f4ee1a5d2a339d5a85633151e17cb129ed6b750e69eb9e2f4aa43cefa94adf99675a2b01e0e837a80538e774839f4f27fc30034ae0a2d179da3eb34c1d46ba863f67c2efe4ff2405d89ad4f98acc57e411a3e85e3ba82dbe0e3e3c9a09dd99cfede261271a7cd442db4a34cbdd7fe11f1e3a8564e6e340a0c175e2ee5e950c2503a05caedabcb8c563c1157ed99eb0f2f8b7844\",\n\t\t\t\t\tOutputIndex: 10,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"7ef0ab206de97f0906adbaccb68bdd7039b86893cbeede8ef9311858b8187fdb\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"2\",\n\t\t\t\t\tSignature: \"45b364938dcde0267e019ad19518abd5174659e45341b624174cc6c941a98fd40cb9b230a2dce924f17982403b88d20afd8d7a11e046c6dfa8d2cd2b713232016d95a4c30990fb02f2b6b611311a02c490bb0f0a7e941a26ddc0b41ebb2356c2a250ab1ae34190463a1e63f896eb7a2f20edaffbd5fd715a819b3ba9c36ce3fe4006fc476add623e874cdb880ca9e2962ec369e6b097930652948c4a175231716e24cefec3b90908139dfe1ae29ca469d00bfaa127838c73e135ad5a66a34242d2518fd66a35857d0d1f897b7035862642c0d07c45b9094039dc278572c06045c09acd568dc0adda60e022b591f76061ede28010cbba7f2758e1a1dbc1e374a8266421ad9fb79e2d4532f1466b687ded5c02aeed4020ea23b4c184181453ea111b3b6db6c8e381f1467e56aecc02475463d713fb1300c5c38379763b26c6b87cb0f27b7d3603e83416dae8f2cd06e2c48090c3b08b5cd6525c669f5a730eec9062c6cffb916db2ce90d41b1734b16eb7be54be19910e9f2669e254c880346aec5756ee8e0520e076838414fafb8348ee350258fd18910f4cca3d8630aa621642fc2b437c6d74a151383beb95aacfe3c7fdf31e372c1d9330abb9ba0be27af1ed745735bd8c09bab1fbc3e7f4f1baf070a260bdbe439b119ae09d87a09989f0cdfdc4f99a109b62a2db862d5ded19daf20d28aafb098efdeefedd935053bd0796\",\n\t\t\t\t\tOutputIndex: 20,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 200,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar unspentTransactionOutputs = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"1\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 100,\n\t\t},\n\t\t{\n\t\t\tOutputID: \"2\",\n\t\t\tOutputIndex: 20,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 200,\n\t\t},\n\t}\n\n\t// create coinbase transaction\n\tresult, _ := blockTransactionValidator.ValidateBlockTransactions(transactions, unspentTransactionOutputs, blockIndex)\n\n\t// validate expected\n\tif !result {\n\t\tt.Errorf(\"block transactions are valid so the result should be true\")\n\t}\n}", "func (ns *EsIndexer) DeleteBlocksInRange(fromBlockHeight uint64, toBlockHeight uint64) {\n\tctx := context.Background()\n\tns.log.Info().Msg(fmt.Sprintf(\"Rolling back %d blocks [%d..%d]\", (1 + toBlockHeight - fromBlockHeight), fromBlockHeight, toBlockHeight))\n\t// Delete blocks\n\tquery := elastic.NewRangeQuery(\"no\").From(fromBlockHeight).To(toBlockHeight)\n\tres, err := ns.client.DeleteByQuery().Index(ns.indexNamePrefix + \"block\").Query(query).Do(ctx)\n\tif err != nil {\n\t\tns.log.Warn().Err(err).Msg(\"Failed to delete blocks\")\n\t} else {\n\t\tns.log.Info().Int64(\"deleted\", res.Deleted).Msg(\"Deleted blocks\")\n\t}\n\t// Delete tx of blocks\n\tquery = elastic.NewRangeQuery(\"blockno\").From(fromBlockHeight).To(toBlockHeight)\n\tres, err = ns.client.DeleteByQuery().Index(ns.indexNamePrefix + \"tx\").Query(query).Do(ctx)\n\tif err != nil {\n\t\tns.log.Warn().Err(err).Msg(\"Failed to delete tx\")\n\t} else {\n\t\tns.log.Info().Int64(\"deleted\", res.Deleted).Msg(\"Deleted tx\")\n\t}\n\t// Delete invalidated name entries\n\tquery = elastic.NewRangeQuery(\"blockno\").From(fromBlockHeight).To(toBlockHeight)\n\tres, err = ns.client.DeleteByQuery().Index(ns.indexNamePrefix + \"name\").Query(query).Do(ctx)\n\tif err != nil {\n\t\tns.log.Warn().Err(err).Msg(\"Failed to delete names\")\n\t} else {\n\t\tns.log.Info().Int64(\"deleted\", res.Deleted).Msg(\"Deleted names\")\n\t}\n}", "func (f *Fetcher) GetBlocks(ctx context.Context, cids []cid.Cid) ([]*types.Block, error) {\n\tvar unsanitized []blocks.Block\n\tfor b := range f.session.GetBlocks(ctx, cids) {\n\t\tunsanitized = append(unsanitized, b)\n\t}\n\n\tif len(unsanitized) < len(cids) {\n\t\tvar err error\n\t\tif ctxErr := ctx.Err(); ctxErr != nil {\n\t\t\terr = errors.Wrap(ctxErr, \"failed to fetch all requested blocks\")\n\t\t} else {\n\t\t\terr = errors.New(\"failed to fetch all requested blocks\")\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tvar blocks []*types.Block\n\tfor _, u := range unsanitized {\n\t\tblock, err := types.DecodeBlock(u.RawData())\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\"fetched data (cid %s) was not a block\", u.Cid().String()))\n\t\t}\n\n\t\t// reject blocks that are syntactically invalid.\n\t\tif err := f.validator.ValidateSyntax(ctx, block); err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tblocks = append(blocks, block)\n\t}\n\treturn blocks, nil\n}", "func GetBlockBytes(block *model.Block) ([]byte, error) {\n\tvar rawBlock []byte\n\n\t// convert nounce to bytes\n\tnounceBytes := Int64ToBytes(block.Nounce)\n\trawBlock = append(rawBlock, nounceBytes...)\n\n\t// convert preHash to bytes\n\tpreHashBytes, err := HexToBytes(block.PrevHash)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trawBlock = append(rawBlock, preHashBytes...)\n\n\t// convert transactions to bytes\n\tfor i := 0; i < len(block.Txs); i++ {\n\t\ttx := block.Txs[i]\n\t\ttxBytes, err := GetTransactionBytes(tx, true /*withHash*/)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trawBlock = append(rawBlock, txBytes...)\n\t}\n\n\t// covert coinbase to bytes\n\tcoinbaseBytes, err := GetTransactionBytes(block.Coinbase, true /*withHash*/)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trawBlock = append(rawBlock, coinbaseBytes...)\n\n\treturn rawBlock, nil\n}", "func (syncer *Syncer) ValidateBlock(ctx context.Context, b *types.FullBlock) (err error) {\n\tdefer func() {\n\t\t// b.Cid() could panic for empty blocks that are used in tests.\n\t\tif rerr := recover(); rerr != nil {\n\t\t\terr = xerrors.Errorf(\"validate block panic: %w\", rerr)\n\t\t\treturn\n\t\t}\n\t}()\n\n\tisValidated, err := syncer.store.IsBlockValidated(ctx, b.Cid())\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"check block validation cache %s: %w\", b.Cid(), err)\n\t}\n\n\tif isValidated {\n\t\treturn nil\n\t}\n\n\tvalidationStart := build.Clock.Now()\n\tdefer func() {\n\t\tstats.Record(ctx, metrics.BlockValidationDurationMilliseconds.M(metrics.SinceInMilliseconds(validationStart)))\n\t\tlog.Infow(\"block validation\", \"took\", time.Since(validationStart), \"height\", b.Header.Height, \"age\", time.Since(time.Unix(int64(b.Header.Timestamp), 0)))\n\t}()\n\n\tctx, span := trace.StartSpan(ctx, \"validateBlock\")\n\tdefer span.End()\n\n\tif err := blockSanityChecks(b.Header); err != nil {\n\t\treturn xerrors.Errorf(\"incoming header failed basic sanity checks: %w\", err)\n\t}\n\n\th := b.Header\n\n\tbaseTs, err := syncer.store.LoadTipSet(types.NewTipSetKey(h.Parents...))\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"load parent tipset failed (%s): %w\", h.Parents, err)\n\t}\n\n\tlbts, err := stmgr.GetLookbackTipSetForRound(ctx, syncer.sm, baseTs, h.Height)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"failed to get lookback tipset for block: %w\", err)\n\t}\n\n\tlbst, _, err := syncer.sm.TipSetState(ctx, lbts)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"failed to compute lookback tipset state: %w\", err)\n\t}\n\n\tprevBeacon, err := syncer.store.GetLatestBeaconEntry(baseTs)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"failed to get latest beacon entry: %w\", err)\n\t}\n\n\t// fast checks first\n\tnulls := h.Height - (baseTs.Height() + 1)\n\tif tgtTs := baseTs.MinTimestamp() + build.BlockDelaySecs*uint64(nulls+1); h.Timestamp != tgtTs {\n\t\treturn xerrors.Errorf(\"block has wrong timestamp: %d != %d\", h.Timestamp, tgtTs)\n\t}\n\n\tnow := uint64(build.Clock.Now().Unix())\n\tif h.Timestamp > now+build.AllowableClockDriftSecs {\n\t\treturn xerrors.Errorf(\"block was from the future (now=%d, blk=%d): %w\", now, h.Timestamp, ErrTemporal)\n\t}\n\tif h.Timestamp > now {\n\t\tlog.Warn(\"Got block from the future, but within threshold\", h.Timestamp, build.Clock.Now().Unix())\n\t}\n\n\tmsgsCheck := async.Err(func() error {\n\t\tif err := syncer.checkBlockMessages(ctx, b, baseTs); err != nil {\n\t\t\treturn xerrors.Errorf(\"block had invalid messages: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\tminerCheck := async.Err(func() error {\n\t\tif err := syncer.minerIsValid(ctx, h.Miner, baseTs); err != nil {\n\t\t\treturn xerrors.Errorf(\"minerIsValid failed: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\tbaseFeeCheck := async.Err(func() error {\n\t\tbaseFee, err := syncer.store.ComputeBaseFee(ctx, baseTs)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"computing base fee: %w\", err)\n\t\t}\n\t\tif types.BigCmp(baseFee, b.Header.ParentBaseFee) != 0 {\n\t\t\treturn xerrors.Errorf(\"base fee doesn't match: %s (header) != %s (computed)\",\n\t\t\t\tb.Header.ParentBaseFee, baseFee)\n\t\t}\n\t\treturn nil\n\t})\n\tpweight, err := syncer.store.Weight(ctx, baseTs)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"getting parent weight: %w\", err)\n\t}\n\n\tif types.BigCmp(pweight, b.Header.ParentWeight) != 0 {\n\t\treturn xerrors.Errorf(\"parrent weight different: %s (header) != %s (computed)\",\n\t\t\tb.Header.ParentWeight, pweight)\n\t}\n\n\t// Stuff that needs stateroot / worker address\n\tstateroot, precp, err := syncer.sm.TipSetState(ctx, baseTs)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"get tipsetstate(%d, %s) failed: %w\", h.Height, h.Parents, err)\n\t}\n\n\tif stateroot != h.ParentStateRoot {\n\t\tmsgs, err := syncer.store.MessagesForTipset(baseTs)\n\t\tif err != nil {\n\t\t\tlog.Error(\"failed to load messages for tipset during tipset state mismatch error: \", err)\n\t\t} else {\n\t\t\tlog.Warn(\"Messages for tipset with mismatching state:\")\n\t\t\tfor i, m := range msgs {\n\t\t\t\tmm := m.VMMessage()\n\t\t\t\tlog.Warnf(\"Message[%d]: from=%s to=%s method=%d params=%x\", i, mm.From, mm.To, mm.Method, mm.Params)\n\t\t\t}\n\t\t}\n\n\t\treturn xerrors.Errorf(\"parent state root did not match computed state (%s != %s)\", stateroot, h.ParentStateRoot)\n\t}\n\n\tif precp != h.ParentMessageReceipts {\n\t\treturn xerrors.Errorf(\"parent receipts root did not match computed value (%s != %s)\", precp, h.ParentMessageReceipts)\n\t}\n\n\twaddr, err := stmgr.GetMinerWorkerRaw(ctx, syncer.sm, lbst, h.Miner)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"GetMinerWorkerRaw failed: %w\", err)\n\t}\n\n\twinnerCheck := async.Err(func() error {\n\t\tif h.ElectionProof.WinCount < 1 {\n\t\t\treturn xerrors.Errorf(\"block is not claiming to be a winner\")\n\t\t}\n\n\t\thp, err := stmgr.MinerHasMinPower(ctx, syncer.sm, h.Miner, lbts)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"determining if miner has min power failed: %w\", err)\n\t\t}\n\n\t\tif !hp {\n\t\t\treturn xerrors.New(\"block's miner does not meet minimum power threshold\")\n\t\t}\n\n\t\trBeacon := *prevBeacon\n\t\tif len(h.BeaconEntries) != 0 {\n\t\t\trBeacon = h.BeaconEntries[len(h.BeaconEntries)-1]\n\t\t}\n\t\tbuf := new(bytes.Buffer)\n\t\tif err := h.Miner.MarshalCBOR(buf); err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to marshal miner address to cbor: %w\", err)\n\t\t}\n\n\t\tvrfBase, err := store.DrawRandomness(rBeacon.Data, crypto.DomainSeparationTag_ElectionProofProduction, h.Height, buf.Bytes())\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"could not draw randomness: %w\", err)\n\t\t}\n\n\t\tif err := VerifyElectionPoStVRF(ctx, waddr, vrfBase, h.ElectionProof.VRFProof); err != nil {\n\t\t\treturn xerrors.Errorf(\"validating block election proof failed: %w\", err)\n\t\t}\n\n\t\tslashed, err := stmgr.GetMinerSlashed(ctx, syncer.sm, baseTs, h.Miner)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to check if block miner was slashed: %w\", err)\n\t\t}\n\n\t\tif slashed {\n\t\t\treturn xerrors.Errorf(\"received block was from slashed or invalid miner\")\n\t\t}\n\n\t\tmpow, tpow, _, err := stmgr.GetPowerRaw(ctx, syncer.sm, lbst, h.Miner)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"failed getting power: %w\", err)\n\t\t}\n\n\t\tj := h.ElectionProof.ComputeWinCount(mpow.QualityAdjPower, tpow.QualityAdjPower)\n\t\tif h.ElectionProof.WinCount != j {\n\t\t\treturn xerrors.Errorf(\"miner claims wrong number of wins: miner: %d, computed: %d\", h.ElectionProof.WinCount, j)\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tblockSigCheck := async.Err(func() error {\n\t\tif err := sigs.CheckBlockSignature(ctx, h, waddr); err != nil {\n\t\t\treturn xerrors.Errorf(\"check block signature failed: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\tbeaconValuesCheck := async.Err(func() error {\n\t\tif os.Getenv(\"LOTUS_IGNORE_DRAND\") == \"_yes_\" {\n\t\t\treturn nil\n\t\t}\n\n\t\tif err := beacon.ValidateBlockValues(syncer.beacon, h, baseTs.Height(), *prevBeacon); err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to validate blocks random beacon values: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\ttktsCheck := async.Err(func() error {\n\t\tbuf := new(bytes.Buffer)\n\t\tif err := h.Miner.MarshalCBOR(buf); err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to marshal miner address to cbor: %w\", err)\n\t\t}\n\n\t\tif h.Height > build.UpgradeSmokeHeight {\n\t\t\tbuf.Write(baseTs.MinTicket().VRFProof)\n\t\t}\n\n\t\tbeaconBase := *prevBeacon\n\t\tif len(h.BeaconEntries) != 0 {\n\t\t\tbeaconBase = h.BeaconEntries[len(h.BeaconEntries)-1]\n\t\t}\n\n\t\tvrfBase, err := store.DrawRandomness(beaconBase.Data, crypto.DomainSeparationTag_TicketProduction, h.Height-build.TicketRandomnessLookback, buf.Bytes())\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to compute vrf base for ticket: %w\", err)\n\t\t}\n\n\t\terr = VerifyElectionPoStVRF(ctx, waddr, vrfBase, h.Ticket.VRFProof)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"validating block tickets failed: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\twproofCheck := async.Err(func() error {\n\t\tif err := syncer.VerifyWinningPoStProof(ctx, h, *prevBeacon, lbst, waddr); err != nil {\n\t\t\treturn xerrors.Errorf(\"invalid election post: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\tawait := []async.ErrorFuture{\n\t\tminerCheck,\n\t\ttktsCheck,\n\t\tblockSigCheck,\n\t\tbeaconValuesCheck,\n\t\twproofCheck,\n\t\twinnerCheck,\n\t\tmsgsCheck,\n\t\tbaseFeeCheck,\n\t}\n\n\tvar merr error\n\tfor _, fut := range await {\n\t\tif err := fut.AwaitContext(ctx); err != nil {\n\t\t\tmerr = multierror.Append(merr, err)\n\t\t}\n\t}\n\tif merr != nil {\n\t\tmulErr := merr.(*multierror.Error)\n\t\tmulErr.ErrorFormat = func(es []error) string {\n\t\t\tif len(es) == 1 {\n\t\t\t\treturn fmt.Sprintf(\"1 error occurred:\\n\\t* %+v\\n\\n\", es[0])\n\t\t\t}\n\n\t\t\tpoints := make([]string, len(es))\n\t\t\tfor i, err := range es {\n\t\t\t\tpoints[i] = fmt.Sprintf(\"* %+v\", err)\n\t\t\t}\n\n\t\t\treturn fmt.Sprintf(\n\t\t\t\t\"%d errors occurred:\\n\\t%s\\n\\n\",\n\t\t\t\tlen(es), strings.Join(points, \"\\n\\t\"))\n\t\t}\n\t\treturn mulErr\n\t}\n\n\tif err := syncer.store.MarkBlockAsValidated(ctx, b.Cid()); err != nil {\n\t\treturn xerrors.Errorf(\"caching block validation %s: %w\", b.Cid(), err)\n\t}\n\n\treturn nil\n}", "func (dcr *ExchangeWallet) monitorBlocks(ctx context.Context) {\n\tticker := time.NewTicker(blockTicker)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tdcr.checkForNewBlocks()\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (manager *SyncManager) SyncBlocks(latestHeight int64) error {\n\tmaybeLastIndexedHeight, err := manager.eventHandler.GetLastHandledEventHeight()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error running GetLastIndexedBlockHeight %v\", err)\n\t}\n\n\t// if none of the block has been indexed before, start with 0\n\tcurrentIndexingHeight := int64(0)\n\tif maybeLastIndexedHeight != nil {\n\t\tcurrentIndexingHeight = *maybeLastIndexedHeight + 1\n\t}\n\n\tmanager.logger.Infof(\"going to synchronized blocks from %d to %d\", currentIndexingHeight, latestHeight)\n\tfor currentIndexingHeight < latestHeight {\n\t\tblocksCommands, syncedHeight, err := manager.windowSyncStrategy.Sync(\n\t\t\tcurrentIndexingHeight, latestHeight, manager.syncBlockWorker,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error when synchronizing block with window strategy: %v\", err)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error beginning transaction: %v\", err)\n\t\t}\n\t\tfor i, commands := range blocksCommands {\n\t\t\tblockHeight := currentIndexingHeight + int64(i)\n\n\t\t\tevents := make([]event.Event, 0, len(commands))\n\t\t\tfor _, command := range commands {\n\t\t\t\tevent, err := command.Exec()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error generating event: %v\", err)\n\t\t\t\t}\n\t\t\t\tevents = append(events, event)\n\t\t\t}\n\n\t\t\terr := manager.eventHandler.HandleEvents(blockHeight, events)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error handling events: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\t// If there is any error before, short-circuit return in the error handling\n\t\t// while the local currentIndexingHeight won't be incremented and will be retried later\n\t\tmanager.logger.Infof(\"successfully synced to block height %d\", syncedHeight)\n\t\tcurrentIndexingHeight = syncedHeight + 1\n\t}\n\treturn nil\n}", "func NewBlock(previousBlock Block, data string) (Block, error) {\n\tvar newBlock Block\n\n\tnewBlock.Index = previousBlock.Index + 1\n\tnewBlock.Timestamp = time.Now().String()\n\tnewBlock.Data = data\n\tnewBlock.PrevHash = previousBlock.Hash\n\tnewBlock.Difficulty = GetDifficulty()\n\n\tif !isCandidateBlockValid(newBlock, previousBlock) {\n\t\treturn newBlock, errors.New(\"Candidate block is not valid\")\n\t}\n\n\tmineBlock(&newBlock)\n\n\treturn newBlock, nil\n}", "func (l *Ledger) FindUndoAndTodoBlocks(curBlockid []byte, destBlockid []byte) ([]*pb.InternalBlock, []*pb.InternalBlock, error) {\n\tl.mutex.RLock()\n\tdefer l.mutex.RUnlock()\n\tundoBlocks := []*pb.InternalBlock{}\n\ttodoBlocks := []*pb.InternalBlock{}\n\tif bytes.Equal(destBlockid, curBlockid) { //原地踏步的情况...\n\t\treturn undoBlocks, todoBlocks, nil\n\t}\n\trootBlockid := l.meta.RootBlockid\n\toldTip, oErr := l.queryBlock(curBlockid, true)\n\tif oErr != nil {\n\t\tl.xlog.Warn(\"block not found\", \"blockid\", utils.F(curBlockid))\n\t\treturn nil, nil, oErr\n\t}\n\tnewTip, nErr := l.queryBlock(destBlockid, true)\n\tif nErr != nil {\n\t\tl.xlog.Warn(\"block not found\", \"blockid\", utils.F(destBlockid))\n\t\treturn nil, nil, nErr\n\t}\n\tvisited := map[string]bool{}\n\tundoBlocks = append(undoBlocks, oldTip)\n\ttodoBlocks = append(todoBlocks, newTip)\n\tvisited[string(oldTip.Blockid)] = true\n\tvisited[string(newTip.Blockid)] = true\n\tvar splitBlockID []byte //最近的分叉点\n\tfor {\n\t\toldPreHash := oldTip.PreHash\n\t\tif len(oldPreHash) > 0 && oldTip.Height >= newTip.Height {\n\t\t\toldTip, oErr = l.queryBlock(oldPreHash, true)\n\t\t\tif oErr != nil {\n\t\t\t\treturn nil, nil, oErr\n\t\t\t}\n\t\t\tif _, exist := visited[string(oldTip.Blockid)]; exist {\n\t\t\t\tsplitBlockID = oldTip.Blockid //从老tip开始回溯到了分叉点\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tvisited[string(oldTip.Blockid)] = true\n\t\t\t\tundoBlocks = append(undoBlocks, oldTip)\n\t\t\t}\n\t\t}\n\t\tnewPreHash := newTip.PreHash\n\t\tif len(newPreHash) > 0 && newTip.Height >= oldTip.Height {\n\t\t\tnewTip, nErr = l.queryBlock(newPreHash, true)\n\t\t\tif nErr != nil {\n\t\t\t\treturn nil, nil, nErr\n\t\t\t}\n\t\t\tif _, exist := visited[string(newTip.Blockid)]; exist {\n\t\t\t\tsplitBlockID = newTip.Blockid //从新tip开始回溯到了分叉点\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tvisited[string(newTip.Blockid)] = true\n\t\t\t\ttodoBlocks = append(todoBlocks, newTip)\n\t\t\t}\n\t\t}\n\t\tif len(oldPreHash) == 0 && len(newPreHash) == 0 {\n\t\t\tsplitBlockID = rootBlockid // 这种情况只能从roott算了\n\t\t\tbreak\n\t\t}\n\t}\n\t//收尾工作,todo_blocks, undo_blocks 如果最后一个元素是分叉点,需要去掉\n\tif bytes.Equal(undoBlocks[len(undoBlocks)-1].Blockid, splitBlockID) {\n\t\tundoBlocks = undoBlocks[:len(undoBlocks)-1]\n\t}\n\tif bytes.Equal(todoBlocks[len(todoBlocks)-1].Blockid, splitBlockID) {\n\t\ttodoBlocks = todoBlocks[:len(todoBlocks)-1]\n\t}\n\treturn undoBlocks, todoBlocks, nil\n}", "func (b *Block) List(input *BlockCursorInput) (*Blocks, error) {\n\tparams := make(map[string]string)\n\tparams[\"cursor\"] = input.Cursor\n\tresp, err := b.c.Request(http.MethodGet, \"/blocks\", new(bytes.Buffer), params)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar blocks *Blocks\n\terr = json.NewDecoder(resp.Body).Decode(&blocks)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\treturn blocks, nil\n}", "func Test_MineBlock_MineBlock(t *testing.T) {\n\tvar block = &Block{\n\t\tIndex: 0,\n\t\tHash: \"\",\n\t\tTransactions: []*transactions.Transaction{\n\t\t\t{\n\t\t\t\tID: \"transactionID\",\n\t\t\t\tInputs: []*transactions.TransactionInput{\n\t\t\t\t\t{\n\t\t\t\t\t\tOutputID: \"output-ID\",\n\t\t\t\t\t\tOutputIndex: 1,\n\t\t\t\t\t\tSignature: \"signature\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tOutputs: []*transactions.TransactionOutput{\n\t\t\t\t\t{\n\t\t\t\t\t\tAddress: \"address\",\n\t\t\t\t\t\tAmount: 25,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tMessage: \"my genesis block!!\",\n\t\tPreviousHash: \"\",\n\t\tTimestamp: time.Unix(1465154705, 0),\n\t\tDifficulty: 5,\n\t\tNonce: 0,\n\t}\n\n\t// hash block\n\tblock.MineBlock()\n\n\t// result should be correct hash\n\texpectedHash := \"01cae462faef5b5132df4a29cba801c620813bc7033ad8ae7d4ad8a8806bb7ca\"\n\tif block.Hash != expectedHash {\n\t\tt.Errorf(\"mining result is incorrect, Actual: %s Expected: %s\", block.Hash, expectedHash)\n\t}\n\texpectedNonce := 4\n\tif block.Nonce != expectedNonce {\n\t\tt.Errorf(\"mining result is incorrect, Actual: %d Expected: %d\", block.Nonce, expectedNonce)\n\t}\n}", "func NewBlock(transactions []*Transaction, preBlockHash []byte) *Block {\n\tb := &Block{time.Now().Unix(), transactions, preBlockHash, []byte{}, 252, 0}\n\n\tpow := NewProofOfWork(b)\n\tnonce, hash := pow.Run()\n\n\tb.Nonce = nonce\n\tb.Hash = hash[:]\n\n\treturn b\n}", "func (_Rootchain *RootchainCallerSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _Rootchain.Contract.Blocks(&_Rootchain.CallOpts, arg0)\n}", "func TestFullBlocks(t *testing.T) {\n\tt.Parallel()\n\n\ttests, err := fullblocktests.Generate(false)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to generate tests: %v\", err)\n\t}\n\n\t// Create a new database and chain instance to run tests against.\n\tchain, err := chainSetup(t, chaincfg.RegNetParams())\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to setup chain instance: %v\", err)\n\t}\n\n\t// testAcceptedBlock attempts to process the block in the provided test\n\t// instance and ensures that it was accepted according to the flags\n\t// specified in the test.\n\ttestAcceptedBlock := func(item fullblocktests.AcceptedBlock) {\n\t\tblockHeight := item.Block.Header.Height\n\t\tblock := dcrutil.NewBlock(item.Block)\n\t\tt.Logf(\"Testing block %s (hash %s, height %d)\",\n\t\t\titem.Name, block.Hash(), blockHeight)\n\n\t\tvar isOrphan bool\n\t\tforkLen, err := chain.ProcessBlock(block)\n\t\tif errors.Is(err, ErrMissingParent) {\n\t\t\tisOrphan = true\n\t\t\terr = nil\n\t\t}\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) should have \"+\n\t\t\t\t\"been accepted: %v\", item.Name, block.Hash(),\n\t\t\t\tblockHeight, err)\n\t\t}\n\n\t\t// Ensure the main chain and orphan flags match the values\n\t\t// specified in the test.\n\t\tisMainChain := !isOrphan && forkLen == 0\n\t\tif isMainChain != item.IsMainChain {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) unexpected main \"+\n\t\t\t\t\"chain flag -- got %v, want %v\", item.Name,\n\t\t\t\tblock.Hash(), blockHeight, isMainChain,\n\t\t\t\titem.IsMainChain)\n\t\t}\n\t\tif isOrphan != item.IsOrphan {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) unexpected \"+\n\t\t\t\t\"orphan flag -- got %v, want %v\", item.Name,\n\t\t\t\tblock.Hash(), blockHeight, isOrphan,\n\t\t\t\titem.IsOrphan)\n\t\t}\n\t}\n\n\t// testRejectedBlock attempts to process the block in the provided test\n\t// instance and ensures that it was rejected with the reject code\n\t// specified in the test.\n\ttestRejectedBlock := func(item fullblocktests.RejectedBlock) {\n\t\tblockHeight := item.Block.Header.Height\n\t\tblock := dcrutil.NewBlock(item.Block)\n\t\tt.Logf(\"Testing block %s (hash %s, height %d)\",\n\t\t\titem.Name, block.Hash(), blockHeight)\n\n\t\t_, err := chain.ProcessBlock(block)\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) should not \"+\n\t\t\t\t\"have been accepted\", item.Name, block.Hash(),\n\t\t\t\tblockHeight)\n\t\t}\n\n\t\t// Convert the full block test error kind to the associated local\n\t\t// blockchain error kind.\n\t\twantRejectKind := fullBlockTestErrToLocalErr(t, item.RejectKind)\n\n\t\t// Ensure the error reject kind matches the value specified in the test\n\t\t// instance.\n\t\tif !errors.Is(err, wantRejectKind) {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) does not have \"+\n\t\t\t\t\"expected reject code -- got %v, want %v\",\n\t\t\t\titem.Name, block.Hash(), blockHeight, err, wantRejectKind)\n\t\t}\n\t}\n\n\t// testRejectedNonCanonicalBlock attempts to decode the block in the\n\t// provided test instance and ensures that it failed to decode with a\n\t// message error.\n\ttestRejectedNonCanonicalBlock := func(item fullblocktests.RejectedNonCanonicalBlock) {\n\t\theaderLen := wire.MaxBlockHeaderPayload\n\t\tif headerLen > len(item.RawBlock) {\n\t\t\theaderLen = len(item.RawBlock)\n\t\t}\n\t\tblockHeader := item.RawBlock[0:headerLen]\n\t\tblockHash := chainhash.HashH(chainhash.HashB(blockHeader))\n\t\tblockHeight := item.Height\n\t\tt.Logf(\"Testing block %s (hash %s, height %d)\", item.Name,\n\t\t\tblockHash, blockHeight)\n\n\t\t// Ensure there is an error due to deserializing the block.\n\t\tvar msgBlock wire.MsgBlock\n\t\terr := msgBlock.BtcDecode(bytes.NewReader(item.RawBlock), 0)\n\t\tvar werr *wire.MessageError\n\t\tif !errors.As(err, &werr) {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) should have \"+\n\t\t\t\t\"failed to decode\", item.Name, blockHash,\n\t\t\t\tblockHeight)\n\t\t}\n\t}\n\n\t// testOrphanOrRejectedBlock attempts to process the block in the\n\t// provided test instance and ensures that it was either accepted as an\n\t// orphan or rejected with a rule violation.\n\ttestOrphanOrRejectedBlock := func(item fullblocktests.OrphanOrRejectedBlock) {\n\t\tblockHeight := item.Block.Header.Height\n\t\tblock := dcrutil.NewBlock(item.Block)\n\t\tt.Logf(\"Testing block %s (hash %s, height %d)\",\n\t\t\titem.Name, block.Hash(), blockHeight)\n\n\t\t_, err := chain.ProcessBlock(block)\n\t\tif err != nil {\n\t\t\t// Ensure the error is of the expected type. Note that orphans are\n\t\t\t// rejected with ErrMissingParent, so this check covers both\n\t\t\t// conditions.\n\t\t\tvar rerr RuleError\n\t\t\tif !errors.As(err, &rerr) {\n\t\t\t\tt.Fatalf(\"block %q (hash %s, height %d) \"+\n\t\t\t\t\t\"returned unexpected error type -- \"+\n\t\t\t\t\t\"got %T, want blockchain.RuleError\",\n\t\t\t\t\titem.Name, block.Hash(), blockHeight,\n\t\t\t\t\terr)\n\t\t\t}\n\t\t}\n\t}\n\n\t// testExpectedTip ensures the current tip of the blockchain is the\n\t// block specified in the provided test instance.\n\ttestExpectedTip := func(item fullblocktests.ExpectedTip) {\n\t\tblockHeight := item.Block.Header.Height\n\t\tblock := dcrutil.NewBlock(item.Block)\n\t\tt.Logf(\"Testing tip for block %s (hash %s, height %d)\",\n\t\t\titem.Name, block.Hash(), blockHeight)\n\n\t\t// Ensure hash and height match.\n\t\tbest := chain.BestSnapshot()\n\t\tif best.Hash != item.Block.BlockHash() ||\n\t\t\tbest.Height != int64(blockHeight) {\n\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) should be \"+\n\t\t\t\t\"the current tip -- got (hash %s, height %d)\",\n\t\t\t\titem.Name, block.Hash(), blockHeight, best.Hash,\n\t\t\t\tbest.Height)\n\t\t}\n\t}\n\n\tfor testNum, test := range tests {\n\t\tfor itemNum, item := range test {\n\t\t\tswitch item := item.(type) {\n\t\t\tcase fullblocktests.AcceptedBlock:\n\t\t\t\ttestAcceptedBlock(item)\n\t\t\tcase fullblocktests.RejectedBlock:\n\t\t\t\ttestRejectedBlock(item)\n\t\t\tcase fullblocktests.RejectedNonCanonicalBlock:\n\t\t\t\ttestRejectedNonCanonicalBlock(item)\n\t\t\tcase fullblocktests.OrphanOrRejectedBlock:\n\t\t\t\ttestOrphanOrRejectedBlock(item)\n\t\t\tcase fullblocktests.ExpectedTip:\n\t\t\t\ttestExpectedTip(item)\n\t\t\tdefault:\n\t\t\t\tt.Fatalf(\"test #%d, item #%d is not one of \"+\n\t\t\t\t\t\"the supported test instance types -- \"+\n\t\t\t\t\t\"got type: %T\", testNum, itemNum, item)\n\t\t\t}\n\t\t}\n\t}\n}", "func NewBlock(transactions []*Transaction, prevBlockHash []byte, height int) *Block {\n\tblock := &Block{time.Now().Unix(), transactions, prevBlockHash, []byte{}, 0, height}\n\tblock.POW()\n\treturn block\n}", "func (sm *SyncManager) handleBlockMsg(bmsg *blockMsg) {\n\tpeer := bmsg.peer\n\tstate, exists := sm.peerStates[peer]\n\tif !exists {\n\t\tlog.Warnf(\"Received block message from unknown peer %s\", peer)\n\t\treturn\n\t}\n\n\t// If we didn't ask for this block then the peer is misbehaving.\n\tblockHash := bmsg.block.Block.Hash()\n\n\t// Remove block from request maps. Either chain will know about it and\n\t// so we shouldn't have any more instances of trying to fetch it, or we\n\t// will fail the insert and thus we'll retry next time we get an inv.\n\tif bmsg.block.Block.Height < sm.chainParams.CRCOnlyDPOSHeight {\n\t\t_, confirmedBlockExist := state.requestedConfirmedBlocks[blockHash]\n\t\tif confirmedBlockExist {\n\t\t\tdelete(state.requestedConfirmedBlocks, blockHash)\n\t\t\tdelete(sm.requestedConfirmedBlocks, blockHash)\n\t\t}\n\n\t\t_, blockExist := state.requestedBlocks[blockHash]\n\t\tif blockExist {\n\t\t\tdelete(state.requestedBlocks, blockHash)\n\t\t\tdelete(sm.requestedBlocks, blockHash)\n\t\t}\n\n\t\tif !confirmedBlockExist && !blockExist {\n\t\t\tlog.Warnf(\"Got unrequested confirmed block %v from %s -- \"+\n\t\t\t\t\"disconnecting\", blockHash, peer)\n\t\t\tpeer.Disconnect()\n\t\t\treturn\n\t\t}\n\t} else if bmsg.block.HaveConfirm {\n\t\tif _, exists = state.requestedConfirmedBlocks[blockHash]; !exists {\n\t\t\tlog.Warnf(\"Got unrequested confirmed block %v from %s -- \"+\n\t\t\t\t\"disconnecting\", blockHash, peer)\n\t\t\tpeer.Disconnect()\n\t\t\treturn\n\t\t}\n\t\tdelete(state.requestedConfirmedBlocks, blockHash)\n\t\tdelete(sm.requestedConfirmedBlocks, blockHash)\n\t} else {\n\t\tif _, exists = state.requestedBlocks[blockHash]; !exists {\n\t\t\tlog.Warnf(\"Got unrequested block %v from %s -- \"+\n\t\t\t\t\"disconnecting\", blockHash, peer)\n\t\t\tpeer.Disconnect()\n\t\t\treturn\n\t\t}\n\t\tdelete(state.requestedBlocks, blockHash)\n\t\tdelete(sm.requestedBlocks, blockHash)\n\t}\n\n\t// Process the block to include validation, best chain selection, orphan\n\t// handling, etc.\n\tlog.Debugf(\"Receive block %s at height %d\", blockHash,\n\t\tbmsg.block.Block.Height)\n\t_, isOrphan, err := sm.blockMemPool.AddDposBlock(bmsg.block)\n\tif err != nil {\n\t\tlog.Warn(\"add block error:\", err)\n\t\telaErr := errors.SimpleWithMessage(errors.ErrP2pReject, err,\n\t\t\tfmt.Sprintf(\"Rejected block %v from %s\", blockHash, peer))\n\n\t\tpeer.PushRejectMsg(p2p.CmdBlock, elaErr, &blockHash, false)\n\t\treturn\n\t}\n\n\tif peer == sm.syncPeer {\n\t\tsm.syncStartTime = time.Now()\n\t}\n\n\tif sm.syncPeer != nil && sm.chain.BestChain.Height >= sm.syncHeight {\n\t\tsm.syncPeer = nil\n\t}\n\n\t// Request the parents for the orphan block from the peer that sent it.\n\tif isOrphan {\n\t\torphanRoot := sm.chain.GetOrphanRoot(&blockHash)\n\t\tlocator, err := sm.chain.LatestBlockLocator()\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"Failed to get block locator for the \"+\n\t\t\t\t\"latest block: %v\", err)\n\t\t} else {\n\t\t\tif sm.syncPeer == nil {\n\t\t\t\tsm.syncPeer = peer\n\t\t\t\tsm.syncHeight = bmsg.block.Block.Height\n\t\t\t\tsm.syncStartTime = time.Now()\n\t\t\t}\n\t\t\tif sm.syncPeer == peer {\n\t\t\t\tpeer.PushGetBlocksMsg(locator, orphanRoot)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Clear the rejected transactions.\n\t\tsm.rejectedTxns = make(map[common.Uint256]struct{})\n\t}\n}", "func (synckerManager *SynckerManager) GetCrossShardBlocksForShardValidator(toShard byte, list map[byte][]uint64) (map[byte][]interface{}, error) {\n\tcrossShardPoolLists := synckerManager.GetCrossShardBlocksForShardProducer(toShard, list)\n\n\tmissingBlocks := compareListsByHeight(crossShardPoolLists, list)\n\t// synckerManager.config.Server.\n\tif len(missingBlocks) > 0 {\n\t\tctx, _ := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tsynckerManager.StreamMissingCrossShardBlock(ctx, toShard, missingBlocks)\n\t\t//Logger.Info(\"debug finish stream missing crossX block\")\n\n\t\tcrossShardPoolLists = synckerManager.GetCrossShardBlocksForShardProducer(toShard, list)\n\t\t//Logger.Info(\"get crosshshard block for shard producer\", crossShardPoolLists)\n\t\tmissingBlocks = compareListsByHeight(crossShardPoolLists, list)\n\n\t\tif len(missingBlocks) > 0 {\n\t\t\treturn nil, errors.New(\"Unable to sync required block in time\")\n\t\t}\n\t}\n\n\tfor sid, heights := range list {\n\t\tif len(crossShardPoolLists[sid]) != len(heights) {\n\t\t\treturn nil, fmt.Errorf(\"CrossShard list not match sid:%v pool:%v producer:%v\", sid, len(crossShardPoolLists[sid]), len(heights))\n\t\t}\n\t}\n\n\treturn crossShardPoolLists, nil\n}", "func GetNewBlock(blocks [][][]int)([][]int,[]int){\n\tLocationOfBlock := []int{0,3}\n\tNumberBlock := rand.Intn(7)\n block := blocks[NumberBlock]\n\tnum := rand.Intn(7)+1\n\tfor row := 0; row<len(block);row++{\n\t\tfor colum :=0; colum<len(block[row]); colum++{\n\t\t\tif block[row][colum] != 0{\n\t\t\t\tblock[row][colum] = num\n\t\t\t}\n\t\t}\n }\n\treturn block, LocationOfBlock\n}", "func (m *Mutate) DeserializeCellBlocks(pm proto.Message, b []byte) (uint32, error) {\n\tresp := pm.(*pb.MutateResponse)\n\tif resp.Result == nil {\n\t\t// TODO: is this possible?\n\t\treturn 0, nil\n\t}\n\tcells, read, err := deserializeCellBlocks(b, uint32(resp.Result.GetAssociatedCellCount()))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tresp.Result.Cell = append(resp.Result.Cell, cells...)\n\treturn read, nil\n}", "func (o SecurityGroupRuleOutput) CidrBlocks() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *SecurityGroupRule) pulumi.StringArrayOutput { return v.CidrBlocks }).(pulumi.StringArrayOutput)\n}", "func (a *Account) ListSinceBlock(since, curBlockHeight int32, minconf int) ([]map[string]interface{}, error) {\n\tvar txInfoList []map[string]interface{}\n\tfor _, txRecord := range a.TxStore.SortedRecords() {\n\t\t// check block number.\n\t\tif since != -1 && txRecord.Height() <= since {\n\t\t\tcontinue\n\t\t}\n\n\t\ttxInfoList = append(txInfoList,\n\t\t\ttxRecord.TxInfo(a.name, curBlockHeight, a.Net())...)\n\t}\n\n\treturn txInfoList, nil\n}", "func scanBlockChunks(wsc *wsClient, cmd *btcjson.RescanCmd, lookups *rescanKeys, minBlock,\n\tmaxBlock int32, chain *blockchain.BlockChain) (\n\t*btcutil.Block, *chainhash.Hash, error) {\n\n\t// lastBlock and lastBlockHash track the previously-rescanned block.\n\t// They equal nil when no previous blocks have been rescanned.\n\tvar (\n\t\tlastBlock *btcutil.Block\n\t\tlastBlockHash *chainhash.Hash\n\t)\n\n\t// A ticker is created to wait at least 10 seconds before notifying the\n\t// websocket client of the current progress completed by the rescan.\n\tticker := time.NewTicker(10 * time.Second)\n\tdefer ticker.Stop()\n\n\t// Instead of fetching all block shas at once, fetch in smaller chunks\n\t// to ensure large rescans consume a limited amount of memory.\nfetchRange:\n\tfor minBlock < maxBlock {\n\t\t// Limit the max number of hashes to fetch at once to the\n\t\t// maximum number of items allowed in a single inventory.\n\t\t// This value could be higher since it's not creating inventory\n\t\t// messages, but this mirrors the limiting logic used in the\n\t\t// peer-to-peer protocol.\n\t\tmaxLoopBlock := maxBlock\n\t\tif maxLoopBlock-minBlock > wire.MaxInvPerMsg {\n\t\t\tmaxLoopBlock = minBlock + wire.MaxInvPerMsg\n\t\t}\n\t\thashList, err := chain.HeightRange(minBlock, maxLoopBlock)\n\t\tif err != nil {\n\t\t\trpcsLog.Errorf(\"Error looking up block range: %v\", err)\n\t\t\treturn nil, nil, &btcjson.RPCError{\n\t\t\t\tCode: btcjson.ErrRPCDatabase,\n\t\t\t\tMessage: \"Database error: \" + err.Error(),\n\t\t\t}\n\t\t}\n\t\tif len(hashList) == 0 {\n\t\t\t// The rescan is finished if no blocks hashes for this\n\t\t\t// range were successfully fetched and a stop block\n\t\t\t// was provided.\n\t\t\tif maxBlock != math.MaxInt32 {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// If the rescan is through the current block, set up\n\t\t\t// the client to continue to receive notifications\n\t\t\t// regarding all rescanned addresses and the current set\n\t\t\t// of unspent outputs.\n\t\t\t//\n\t\t\t// This is done safely by temporarily grabbing exclusive\n\t\t\t// access of the block manager. If no more blocks have\n\t\t\t// been attached between this pause and the fetch above,\n\t\t\t// then it is safe to register the websocket client for\n\t\t\t// continuous notifications if necessary. Otherwise,\n\t\t\t// continue the fetch loop again to rescan the new\n\t\t\t// blocks (or error due to an irrecoverable reorganize).\n\t\t\tpauseGuard := wsc.server.cfg.SyncMgr.Pause()\n\t\t\tbest := wsc.server.cfg.Chain.BestSnapshot()\n\t\t\tcurHash := &best.Hash\n\t\t\tagain := true\n\t\t\tif lastBlockHash == nil || *lastBlockHash == *curHash {\n\t\t\t\tagain = false\n\t\t\t\tn := wsc.server.ntfnMgr\n\t\t\t\tn.RegisterSpentRequests(wsc, lookups.unspentSlice())\n\t\t\t\tn.RegisterTxOutAddressRequests(wsc, cmd.Addresses)\n\t\t\t}\n\t\t\tclose(pauseGuard)\n\t\t\tif err != nil {\n\t\t\t\trpcsLog.Errorf(\"Error fetching best block \"+\n\t\t\t\t\t\"hash: %v\", err)\n\t\t\t\treturn nil, nil, &btcjson.RPCError{\n\t\t\t\t\tCode: btcjson.ErrRPCDatabase,\n\t\t\t\t\tMessage: \"Database error: \" +\n\t\t\t\t\t\terr.Error(),\n\t\t\t\t}\n\t\t\t}\n\t\t\tif again {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\tloopHashList:\n\t\tfor i := range hashList {\n\t\t\tblk, err := chain.BlockByHash(&hashList[i])\n\t\t\tif err != nil {\n\t\t\t\t// Only handle reorgs if a block could not be\n\t\t\t\t// found for the hash.\n\t\t\t\tif dbErr, ok := err.(database.Error); !ok ||\n\t\t\t\t\tdbErr.ErrorCode != database.ErrBlockNotFound {\n\n\t\t\t\t\trpcsLog.Errorf(\"Error looking up \"+\n\t\t\t\t\t\t\"block: %v\", err)\n\t\t\t\t\treturn nil, nil, &btcjson.RPCError{\n\t\t\t\t\t\tCode: btcjson.ErrRPCDatabase,\n\t\t\t\t\t\tMessage: \"Database error: \" +\n\t\t\t\t\t\t\terr.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// If an absolute max block was specified, don't\n\t\t\t\t// attempt to handle the reorg.\n\t\t\t\tif maxBlock != math.MaxInt32 {\n\t\t\t\t\trpcsLog.Errorf(\"Stopping rescan for \"+\n\t\t\t\t\t\t\"reorged block %v\",\n\t\t\t\t\t\tcmd.EndBlock)\n\t\t\t\t\treturn nil, nil, &ErrRescanReorg\n\t\t\t\t}\n\n\t\t\t\t// If the lookup for the previously valid block\n\t\t\t\t// hash failed, there may have been a reorg.\n\t\t\t\t// Fetch a new range of block hashes and verify\n\t\t\t\t// that the previously processed block (if there\n\t\t\t\t// was any) still exists in the database. If it\n\t\t\t\t// doesn't, we error.\n\t\t\t\t//\n\t\t\t\t// A goto is used to branch executation back to\n\t\t\t\t// before the range was evaluated, as it must be\n\t\t\t\t// reevaluated for the new hashList.\n\t\t\t\tminBlock += int32(i)\n\t\t\t\thashList, err = recoverFromReorg(\n\t\t\t\t\tchain, minBlock, maxBlock, lastBlockHash,\n\t\t\t\t)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\t\t\t\tif len(hashList) == 0 {\n\t\t\t\t\tbreak fetchRange\n\t\t\t\t}\n\t\t\t\tgoto loopHashList\n\t\t\t}\n\t\t\tif i == 0 && lastBlockHash != nil {\n\t\t\t\t// Ensure the new hashList is on the same fork\n\t\t\t\t// as the last block from the old hashList.\n\t\t\t\tjsonErr := descendantBlock(lastBlockHash, blk)\n\t\t\t\tif jsonErr != nil {\n\t\t\t\t\treturn nil, nil, jsonErr\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// A select statement is used to stop rescans if the\n\t\t\t// client requesting the rescan has disconnected.\n\t\t\tselect {\n\t\t\tcase <-wsc.quit:\n\t\t\t\trpcsLog.Debugf(\"Stopped rescan at height %v \"+\n\t\t\t\t\t\"for disconnected client\", blk.Height())\n\t\t\t\treturn nil, nil, nil\n\t\t\tdefault:\n\t\t\t\trescanBlock(wsc, lookups, blk)\n\t\t\t\tlastBlock = blk\n\t\t\t\tlastBlockHash = blk.Hash()\n\t\t\t}\n\n\t\t\t// Periodically notify the client of the progress\n\t\t\t// completed. Continue with next block if no progress\n\t\t\t// notification is needed yet.\n\t\t\tselect {\n\t\t\tcase <-ticker.C: // fallthrough\n\t\t\tdefault:\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tn := btcjson.NewRescanProgressNtfn(\n\t\t\t\thashList[i].String(), blk.Height(),\n\t\t\t\tblk.MsgBlock().Header.Timestamp.Unix(),\n\t\t\t)\n\t\t\tmn, err := btcjson.MarshalCmd(btcjson.RpcVersion1, nil, n)\n\t\t\tif err != nil {\n\t\t\t\trpcsLog.Errorf(\"Failed to marshal rescan \"+\n\t\t\t\t\t\"progress notification: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err = wsc.QueueNotification(mn); err == ErrClientQuit {\n\t\t\t\t// Finished if the client disconnected.\n\t\t\t\trpcsLog.Debugf(\"Stopped rescan at height %v \"+\n\t\t\t\t\t\"for disconnected client\", blk.Height())\n\t\t\t\treturn nil, nil, nil\n\t\t\t}\n\t\t}\n\n\t\tminBlock += int32(len(hashList))\n\t}\n\n\treturn lastBlock, lastBlockHash, nil\n}", "func (dbv DiskBlockDevice) Blocks() uint16 {\n\treturn dbv.blocks\n}", "func (fc *FakeChains) GetNewBlock(shardIndex shard.Index, txps ...*wire.MsgTxWithProofs) *wire.MsgBlock {\n\treturn fc.Chains[shardIndex].GetNewBlock(txps...)\n}", "func (blockchain *BlockChain) GetBlocks() []*Block {\n\treturn blockchain.blocks\n}", "func (api *GoShimmerAPI) GetBlock(base58EncodedID string) (*jsonmodels.Block, error) {\n\tres := &jsonmodels.Block{}\n\n\tif err := api.do(\n\t\thttp.MethodGet,\n\t\trouteBlock+base58EncodedID,\n\t\tnil,\n\t\tres,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}", "func DeserializeBlock(d []byte) *Block {\n\n\tblock := &Block{}\n\n\terr := proto.Unmarshal(d, block)\n\tif err != nil {\n\t\tlog.Println(\"block-deserialize: protobuf decoding error: \", err)\n\t}\n\n\treturn block\n\n}" ]
[ "0.78249013", "0.6385375", "0.62107474", "0.6095312", "0.60634947", "0.6063101", "0.59976745", "0.5974859", "0.59326327", "0.58996063", "0.5883632", "0.5878408", "0.58193696", "0.5773688", "0.57701415", "0.57556033", "0.572684", "0.5716062", "0.5714754", "0.57055044", "0.5696699", "0.56868786", "0.5647177", "0.5623538", "0.5599805", "0.559624", "0.5583605", "0.5571844", "0.556818", "0.5555473", "0.55518645", "0.552984", "0.5519644", "0.5481176", "0.5471548", "0.54686975", "0.5451879", "0.5451074", "0.54304546", "0.54192734", "0.5417137", "0.54070723", "0.5404698", "0.5403558", "0.53592926", "0.5358738", "0.53467715", "0.53420734", "0.5320311", "0.5315774", "0.53147733", "0.5312037", "0.52944666", "0.52943915", "0.5289555", "0.5274044", "0.5273549", "0.52681726", "0.5263616", "0.5251771", "0.5247786", "0.52436596", "0.52315474", "0.52302307", "0.5229675", "0.5191558", "0.51878494", "0.5179558", "0.51790214", "0.5174664", "0.5170629", "0.5165465", "0.5164656", "0.5161439", "0.515846", "0.51583445", "0.515147", "0.5149599", "0.5148627", "0.514765", "0.5145306", "0.5135676", "0.513547", "0.51348925", "0.5132103", "0.512807", "0.5123568", "0.5122475", "0.5122319", "0.5120661", "0.51195544", "0.5115611", "0.5105115", "0.5104069", "0.5094911", "0.50945085", "0.50936687", "0.5093436", "0.5090473", "0.5081703" ]
0.6407925
1
NEW: This method is only available in solanacore v1.7 or newer. Please use getConfirmedBlocks for solanacore v1.6 GetBlocks returns a list of confirmed blocks between two slots Max range allowed is 500,000 slot
func (c *RpcClient) GetBlocksWithConfig(ctx context.Context, startSlot uint64, endSlot uint64, cfg GetBlocksConfig) (GetBlocksResponse, error) { return c.processGetBlocks(c.Call(ctx, "getBlocks", startSlot, endSlot, cfg)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *RpcClient) GetConfirmedBlocks(ctx context.Context, startSlot uint64, endSlot uint64) ([]uint64, error) {\n\tres := struct {\n\t\tGeneralResponse\n\t\tResult []uint64 `json:\"result\"`\n\t}{}\n\terr := s.request(ctx, \"getConfirmedBlocks\", []interface{}{startSlot, endSlot}, &res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res.Result, nil\n}", "func (c *RpcClient) GetBlocks(ctx context.Context, startSlot uint64, endSlot uint64) (GetBlocksResponse, error) {\n\treturn c.processGetBlocks(c.Call(ctx, \"getBlocks\", startSlot, endSlot))\n}", "func (lp *logPoller) GetBlocksRange(ctx context.Context, numbers []uint64, qopts ...pg.QOpt) ([]LogPollerBlock, error) {\n\tvar blocks []LogPollerBlock\n\n\t// Do nothing if no blocks are requested.\n\tif len(numbers) == 0 {\n\t\treturn blocks, nil\n\t}\n\n\t// Assign the requested blocks to a mapping.\n\tblocksRequested := make(map[uint64]struct{})\n\tfor _, b := range numbers {\n\t\tblocksRequested[b] = struct{}{}\n\t}\n\n\t// Retrieve all blocks within this range from the log poller.\n\tblocksFound := make(map[uint64]LogPollerBlock)\n\tqopts = append(qopts, pg.WithParentCtx(ctx))\n\tminRequestedBlock := mathutil.Min(numbers[0], numbers[1:]...)\n\tmaxRequestedBlock := mathutil.Max(numbers[0], numbers[1:]...)\n\tlpBlocks, err := lp.orm.GetBlocksRange(minRequestedBlock, maxRequestedBlock, qopts...)\n\tif err != nil {\n\t\tlp.lggr.Warnw(\"Error while retrieving blocks from log pollers blocks table. Falling back to RPC...\", \"requestedBlocks\", numbers, \"err\", err)\n\t} else {\n\t\tfor _, b := range lpBlocks {\n\t\t\tif _, ok := blocksRequested[uint64(b.BlockNumber)]; ok {\n\t\t\t\t// Only fill requested blocks.\n\t\t\t\tblocksFound[uint64(b.BlockNumber)] = b\n\t\t\t}\n\t\t}\n\t\tlp.lggr.Debugw(\"Got blocks from log poller\", \"blockNumbers\", maps.Keys(blocksFound))\n\t}\n\n\t// Fill any remaining blocks from the client.\n\tblocksFoundFromRPC, err := lp.fillRemainingBlocksFromRPC(ctx, numbers, blocksFound)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor num, b := range blocksFoundFromRPC {\n\t\tblocksFound[num] = b\n\t}\n\n\tvar blocksNotFound []uint64\n\tfor _, num := range numbers {\n\t\tb, ok := blocksFound[num]\n\t\tif !ok {\n\t\t\tblocksNotFound = append(blocksNotFound, num)\n\t\t}\n\t\tblocks = append(blocks, b)\n\t}\n\n\tif len(blocksNotFound) > 0 {\n\t\treturn nil, errors.Errorf(\"blocks were not found in db or RPC call: %v\", blocksNotFound)\n\t}\n\n\treturn blocks, nil\n}", "func (nc *NSBClient) GetBlocks(rangeL, rangeR int64) (*BlocksInfo, error) {\n\tb, err := nc.handler.Group(\"/blockchain\").GetWithParams(request.Param{\n\t\t\"minHeight\": rangeL,\n\t\t\"maxHeight\": rangeR,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar bb []byte\n\tbb, err = nc.preloadJSONResponse(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar a BlocksInfo\n\terr = json.Unmarshal(bb, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &a, nil\n}", "func (core *coreService) RawBlocks(startHeight uint64, count uint64, withReceipts bool, withTransactionLogs bool) ([]*iotexapi.BlockInfo, error) {\n\tif count == 0 || count > core.cfg.RangeQueryLimit {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"range exceeds the limit\")\n\t}\n\n\ttipHeight := core.bc.TipHeight()\n\tif startHeight > tipHeight {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"start height should not exceed tip height\")\n\t}\n\tendHeight := startHeight + count - 1\n\tif endHeight > tipHeight {\n\t\tendHeight = tipHeight\n\t}\n\tvar res []*iotexapi.BlockInfo\n\tfor height := startHeight; height <= endHeight; height++ {\n\t\tblk, err := core.dao.GetBlockByHeight(height)\n\t\tif err != nil {\n\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t}\n\t\tvar receiptsPb []*iotextypes.Receipt\n\t\tif withReceipts && height > 0 {\n\t\t\treceipts, err := core.dao.GetReceipts(height)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t\t}\n\t\t\tfor _, receipt := range receipts {\n\t\t\t\treceiptsPb = append(receiptsPb, receipt.ConvertToReceiptPb())\n\t\t\t}\n\t\t}\n\t\tvar transactionLogs *iotextypes.TransactionLogs\n\t\tif withTransactionLogs {\n\t\t\tif transactionLogs, err = core.dao.TransactionLogs(height); err != nil {\n\t\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\t\t}\n\t\t}\n\t\tres = append(res, &iotexapi.BlockInfo{\n\t\t\tBlock: blk.ConvertToBlockPb(),\n\t\t\tReceipts: receiptsPb,\n\t\t\tTransactionLogs: transactionLogs,\n\t\t})\n\t}\n\treturn res, nil\n}", "func (gw *Gateway) GetBlocksInRange(start, end uint64) ([]coin.SignedBlock, error) {\n\tvar blocks []coin.SignedBlock\n\tvar err error\n\tgw.strand(\"GetBlocksInRange\", func() {\n\t\tblocks, err = gw.v.GetBlocksInRange(start, end)\n\t})\n\treturn blocks, err\n}", "func (synckerManager *SynckerManager) GetS2BBlocksForBeaconValidator(bestViewShardHash map[byte]common.Hash, list map[byte][]common.Hash) (map[byte][]interface{}, error) {\n\ts2bPoolLists := synckerManager.GetS2BBlocksForBeaconProducer(bestViewShardHash, list)\n\n\tmissingBlocks := compareLists(s2bPoolLists, list)\n\t// synckerManager.config.Server.\n\tif len(missingBlocks) > 0 {\n\t\tctx, _ := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tsynckerManager.StreamMissingShardToBeaconBlock(ctx, missingBlocks)\n\t\t//fmt.Println(\"debug finish stream missing s2b block\")\n\n\t\ts2bPoolLists = synckerManager.GetS2BBlocksForBeaconProducer(bestViewShardHash, list)\n\t\tmissingBlocks = compareLists(s2bPoolLists, list)\n\t\tif len(missingBlocks) > 0 {\n\t\t\treturn nil, errors.New(\"Unable to sync required block in time\")\n\t\t}\n\t}\n\n\tfor sid, heights := range list {\n\t\tif len(s2bPoolLists[sid]) != len(heights) {\n\t\t\treturn nil, fmt.Errorf(\"S2BPoolLists not match sid:%v pool:%v producer:%v\", sid, len(s2bPoolLists[sid]), len(heights))\n\t\t}\n\t}\n\n\treturn s2bPoolLists, nil\n}", "func consensusBlocksGetFromBlock(b types.Block, h types.BlockHeight) ConsensusBlocksGet {\n\ttxns := make([]ConsensusBlocksGetTxn, 0, len(b.Transactions))\n\tfor _, t := range b.Transactions {\n\t\t// Get the transaction's SiacoinOutputs.\n\t\tscos := make([]ConsensusBlocksGetSiacoinOutput, 0, len(t.SiacoinOutputs))\n\t\tfor i, sco := range t.SiacoinOutputs {\n\t\t\tscos = append(scos, ConsensusBlocksGetSiacoinOutput{\n\t\t\t\tID: t.SiacoinOutputID(uint64(i)),\n\t\t\t\tValue: sco.Value,\n\t\t\t\tUnlockHash: sco.UnlockHash,\n\t\t\t})\n\t\t}\n\t\t// Get the transaction's SiafundOutputs.\n\t\tsfos := make([]ConsensusBlocksGetSiafundOutput, 0, len(t.SiafundOutputs))\n\t\tfor i, sfo := range t.SiafundOutputs {\n\t\t\tsfos = append(sfos, ConsensusBlocksGetSiafundOutput{\n\t\t\t\tID: t.SiafundOutputID(uint64(i)),\n\t\t\t\tValue: sfo.Value,\n\t\t\t\tUnlockHash: sfo.UnlockHash,\n\t\t\t})\n\t\t}\n\t\t// Get the transaction's FileContracts.\n\t\tfcos := make([]ConsensusBlocksGetFileContract, 0, len(t.FileContracts))\n\t\tfor i, fc := range t.FileContracts {\n\t\t\t// Get the FileContract's valid proof outputs.\n\t\t\tfcid := t.FileContractID(uint64(i))\n\t\t\tvpos := make([]ConsensusBlocksGetSiacoinOutput, 0, len(fc.ValidProofOutputs))\n\t\t\tfor j, vpo := range fc.ValidProofOutputs {\n\t\t\t\tvpos = append(vpos, ConsensusBlocksGetSiacoinOutput{\n\t\t\t\t\tID: fcid.StorageProofOutputID(types.ProofValid, uint64(j)),\n\t\t\t\t\tValue: vpo.Value,\n\t\t\t\t\tUnlockHash: vpo.UnlockHash,\n\t\t\t\t})\n\t\t\t}\n\t\t\t// Get the FileContract's missed proof outputs.\n\t\t\tmpos := make([]ConsensusBlocksGetSiacoinOutput, 0, len(fc.MissedProofOutputs))\n\t\t\tfor j, mpo := range fc.MissedProofOutputs {\n\t\t\t\tmpos = append(mpos, ConsensusBlocksGetSiacoinOutput{\n\t\t\t\t\tID: fcid.StorageProofOutputID(types.ProofMissed, uint64(j)),\n\t\t\t\t\tValue: mpo.Value,\n\t\t\t\t\tUnlockHash: mpo.UnlockHash,\n\t\t\t\t})\n\t\t\t}\n\t\t\tfcos = append(fcos, ConsensusBlocksGetFileContract{\n\t\t\t\tID: fcid,\n\t\t\t\tFileSize: fc.FileSize,\n\t\t\t\tFileMerkleRoot: fc.FileMerkleRoot,\n\t\t\t\tWindowStart: fc.WindowStart,\n\t\t\t\tWindowEnd: fc.WindowEnd,\n\t\t\t\tPayout: fc.Payout,\n\t\t\t\tValidProofOutputs: vpos,\n\t\t\t\tMissedProofOutputs: mpos,\n\t\t\t\tUnlockHash: fc.UnlockHash,\n\t\t\t\tRevisionNumber: fc.RevisionNumber,\n\t\t\t})\n\t\t}\n\t\ttxns = append(txns, ConsensusBlocksGetTxn{\n\t\t\tID: t.ID(),\n\t\t\tSiacoinInputs: t.SiacoinInputs,\n\t\t\tSiacoinOutputs: scos,\n\t\t\tFileContracts: fcos,\n\t\t\tFileContractRevisions: t.FileContractRevisions,\n\t\t\tStorageProofs: t.StorageProofs,\n\t\t\tSiafundInputs: t.SiafundInputs,\n\t\t\tSiafundOutputs: sfos,\n\t\t\tMinerFees: t.MinerFees,\n\t\t\tArbitraryData: t.ArbitraryData,\n\t\t\tTransactionSignatures: t.TransactionSignatures,\n\t\t})\n\t}\n\treturn ConsensusBlocksGet{\n\t\tID: b.ID(),\n\t\tHeight: h,\n\t\tParentID: b.ParentID,\n\t\tNonce: b.Nonce,\n\t\tTimestamp: b.Timestamp,\n\t\tMinerPayouts: b.MinerPayouts,\n\t\tTransactions: txns,\n\t}\n}", "func GetBlockConfirmations() uint64 {\n\n\tconfirmationCount := Get(\"BlockConfirmations\")\n\tif confirmationCount == \"\" {\n\t\treturn 0\n\t}\n\n\tparsedConfirmationCount, err := strconv.ParseUint(confirmationCount, 10, 64)\n\tif err != nil {\n\t\tlog.Printf(\"[!] Failed to parse block confirmations : %s\\n\", err.Error())\n\t\treturn 0\n\t}\n\n\treturn parsedConfirmationCount\n\n}", "func (db *Database) QueryBlocks(before int, after int, limit int) ([]schema.Block, error) {\n\tblocks := make([]schema.Block, 0)\n\n\tvar err error\n\n\tswitch {\n\tcase before > 0:\n\t\terr = db.Model(&blocks).\n\t\t\tWhere(\"height < ?\", before).\n\t\t\tLimit(limit).\n\t\t\tOrder(\"id DESC\").\n\t\t\tSelect()\n\tcase after >= 0:\n\t\terr = db.Model(&blocks).\n\t\t\tWhere(\"height > ?\", after).\n\t\t\tLimit(limit).\n\t\t\tOrder(\"id ASC\").\n\t\t\tSelect()\n\tdefault:\n\t\terr = db.Model(&blocks).\n\t\t\tLimit(limit).\n\t\t\tOrder(\"id DESC\").\n\t\t\tSelect()\n\t}\n\n\tif err == pg.ErrNoRows {\n\t\treturn blocks, fmt.Errorf(\"no rows in block table: %s\", err)\n\t}\n\n\tif err != nil {\n\t\treturn blocks, fmt.Errorf(\"unexpected database error: %s\", err)\n\t}\n\n\treturn blocks, nil\n}", "func (b *logEventBuffer) getBlocksInRange(start, end int) []fetchedBlock {\n\tvar blocksInRange []fetchedBlock\n\tstart, end = b.normalRange(start, end)\n\tif start == -1 || end == -1 {\n\t\t// invalid range\n\t\treturn blocksInRange\n\t}\n\tif start < end {\n\t\treturn b.blocks[start:end]\n\t}\n\t// in case we get circular range such as [0, 1, end, ... , start, ..., size-1]\n\t// we need to return the blocks in two ranges: [start, size-1] and [0, end]\n\tblocksInRange = append(blocksInRange, b.blocks[start:]...)\n\tblocksInRange = append(blocksInRange, b.blocks[:end]...)\n\n\treturn blocksInRange\n}", "func (c *RPCClient) FilterBlocks(\n\treq *FilterBlocksRequest) (*FilterBlocksResponse, er.R) {\n\n\tblockFilterer := NewBlockFilterer(c.chainParams, req)\n\n\t// Construct the watchlist using the addresses and outpoints contained\n\t// in the filter blocks request.\n\twatchList, err := buildFilterBlocksWatchList(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Iterate over the requested blocks, fetching the compact filter for\n\t// each one, and matching it against the watchlist generated above. If\n\t// the filter returns a positive match, the full block is then requested\n\t// and scanned for addresses using the block filterer.\n\tfor i, blk := range req.Blocks {\n\t\trawFilter, err := c.GetCFilter(&blk.Hash, wire.GCSFilterRegular)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Ensure the filter is large enough to be deserialized.\n\t\tif len(rawFilter.Data) < 4 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfilter, err := gcs.FromNBytes(\n\t\t\tbuilder.DefaultP, builder.DefaultM, rawFilter.Data,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Skip any empty filters.\n\t\tif filter.N() == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tkey := builder.DeriveKey(&blk.Hash)\n\t\tmatched, err := filter.MatchAny(key, watchList)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t} else if !matched {\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Infof(\"Fetching block height=%d hash=%v\",\n\t\t\tblk.Height, blk.Hash)\n\n\t\trawBlock, err := c.GetBlock(&blk.Hash)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !blockFilterer.FilterBlock(rawBlock) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// If any external or internal addresses were detected in this\n\t\t// block, we return them to the caller so that the rescan\n\t\t// windows can widened with subsequent addresses. The\n\t\t// `BatchIndex` is returned so that the caller can compute the\n\t\t// *next* block from which to begin again.\n\t\tresp := &FilterBlocksResponse{\n\t\t\tBatchIndex: uint32(i),\n\t\t\tBlockMeta: blk,\n\t\t\tFoundExternalAddrs: blockFilterer.FoundExternal,\n\t\t\tFoundInternalAddrs: blockFilterer.FoundInternal,\n\t\t\tFoundOutPoints: blockFilterer.FoundOutPoints,\n\t\t\tRelevantTxns: blockFilterer.RelevantTxns,\n\t\t}\n\n\t\treturn resp, nil\n\t}\n\n\t// No addresses were found for this range.\n\treturn nil, nil\n}", "func (m *GetBlocksMessage) GetBlockLocator() []*bc.Hash {\n\tblockLocator := []*bc.Hash{}\n\tfor _, rawHash := range m.RawBlockLocator {\n\t\thash := bc.NewHash(rawHash)\n\t\tblockLocator = append(blockLocator, &hash)\n\t}\n\treturn blockLocator\n}", "func (dcr *ExchangeWallet) checkForNewBlocks() {\n\tctx, cancel := context.WithTimeout(dcr.ctx, 2*time.Second)\n\tdefer cancel()\n\tnewTip, err := dcr.getBestBlock(ctx)\n\tif err != nil {\n\t\tdcr.tipChange(fmt.Errorf(\"failed to get best block: %w\", err))\n\t\treturn\n\t}\n\n\t// This method is called frequently. Don't hold write lock\n\t// unless tip has changed.\n\tdcr.tipMtx.RLock()\n\tsameTip := dcr.currentTip.hash.IsEqual(newTip.hash)\n\tdcr.tipMtx.RUnlock()\n\tif sameTip {\n\t\treturn\n\t}\n\n\tdcr.tipMtx.Lock()\n\tdefer dcr.tipMtx.Unlock()\n\n\tprevTip := dcr.currentTip\n\tdcr.currentTip = newTip\n\tdcr.log.Debugf(\"tip change: %d (%s) => %d (%s)\", prevTip.height, prevTip.hash, newTip.height, newTip.hash)\n\tdcr.tipChange(nil)\n\n\t// Search for contract redemption in new blocks if there\n\t// are contracts pending redemption.\n\tdcr.findRedemptionMtx.RLock()\n\tpendingContractsCount := len(dcr.findRedemptionQueue)\n\tcontractOutpoints := make([]outPoint, 0, pendingContractsCount)\n\tfor contractOutpoint := range dcr.findRedemptionQueue {\n\t\tcontractOutpoints = append(contractOutpoints, contractOutpoint)\n\t}\n\tdcr.findRedemptionMtx.RUnlock()\n\tif pendingContractsCount == 0 {\n\t\treturn\n\t}\n\n\t// Use the previous tip hash to determine the starting point for\n\t// the redemption search. If there was a re-org, the starting point\n\t// would be the common ancestor of the previous tip and the new tip.\n\t// Otherwise, the starting point would be the block at previous tip\n\t// height + 1.\n\tvar startPoint *block\n\tvar startPointErr error\n\tprevTipBlock, err := dcr.node.GetBlockVerbose(dcr.ctx, prevTip.hash, false)\n\tswitch {\n\tcase err != nil:\n\t\tstartPointErr = fmt.Errorf(\"getBlockHeader error for prev tip hash %s: %w\", prevTip.hash, translateRPCCancelErr(err))\n\tcase prevTipBlock.Confirmations < 0:\n\t\t// There's been a re-org, common ancestor will be height\n\t\t// plus negative confirmation e.g. 155 + (-3) = 152.\n\t\treorgHeight := prevTipBlock.Height + prevTipBlock.Confirmations\n\t\tdcr.log.Debugf(\"reorg detected from height %d to %d\", reorgHeight, newTip.height)\n\t\treorgHash, err := dcr.node.GetBlockHash(dcr.ctx, reorgHeight)\n\t\tif err != nil {\n\t\t\tstartPointErr = fmt.Errorf(\"getBlockHash error for reorg height %d: %w\", reorgHeight, translateRPCCancelErr(err))\n\t\t} else {\n\t\t\tstartPoint = &block{hash: reorgHash, height: reorgHeight}\n\t\t}\n\tcase newTip.height-prevTipBlock.Height > 1:\n\t\t// 2 or more blocks mined since last tip, start at prevTip height + 1.\n\t\tafterPrivTip := prevTipBlock.Height + 1\n\t\thashAfterPrevTip, err := dcr.node.GetBlockHash(dcr.ctx, afterPrivTip)\n\t\tif err != nil {\n\t\t\tstartPointErr = fmt.Errorf(\"getBlockHash error for height %d: %w\", afterPrivTip, translateRPCCancelErr(err))\n\t\t} else {\n\t\t\tstartPoint = &block{hash: hashAfterPrevTip, height: afterPrivTip}\n\t\t}\n\tdefault:\n\t\t// Just 1 new block since last tip report, search the lone block.\n\t\tstartPoint = newTip\n\t}\n\n\t// Redemption search would be compromised if the starting point cannot\n\t// be determined, as searching just the new tip might result in blocks\n\t// being omitted from the search operation. If that happens, cancel all\n\t// find redemption requests in queue.\n\tif startPointErr != nil {\n\t\tdcr.fatalFindRedemptionsError(fmt.Errorf(\"new blocks handler error: %w\", startPointErr), contractOutpoints)\n\t} else {\n\t\tgo dcr.findRedemptionsInBlockRange(startPoint, newTip, contractOutpoints)\n\t}\n}", "func (m *BlocksMessage) GetBlocks() ([]*types.Block, error) {\n\tblocks := []*types.Block{}\n\tfor _, data := range m.RawBlocks {\n\t\tblock := &types.Block{}\n\t\tif err := json.Unmarshal(data, block); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tblocks = append(blocks, block)\n\t}\n\treturn blocks, nil\n}", "func (s *Service) GetExplorerBlocks(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tfrom := r.FormValue(\"from\")\n\tto := r.FormValue(\"to\")\n\tpageParam := r.FormValue(\"page\")\n\toffsetParam := r.FormValue(\"offset\")\n\torder := r.FormValue(\"order\")\n\tdata := &Data{\n\t\tBlocks: []*Block{},\n\t}\n\tdefer func() {\n\t\tif err := json.NewEncoder(w).Encode(data.Blocks); err != nil {\n\t\t\tutils.Logger().Warn().Err(err).Msg(\"cannot JSON-encode blocks\")\n\t\t}\n\t}()\n\n\tif from == \"\" {\n\t\tutils.Logger().Warn().Msg(\"Missing from parameter\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tdb := s.Storage.GetDB()\n\tfromInt, err := strconv.Atoi(from)\n\tif err != nil {\n\t\tutils.Logger().Warn().Err(err).Msg(\"invalid from parameter\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tvar toInt int\n\tif to == \"\" {\n\t\ttoInt, err = func() (int, error) {\n\t\t\tbytes, err := db.Get([]byte(BlockHeightKey))\n\t\t\tif err == nil {\n\t\t\t\treturn strconv.Atoi(string(bytes))\n\t\t\t}\n\t\t\treturn toInt, err\n\t\t}()\n\t} else {\n\t\ttoInt, err = strconv.Atoi(to)\n\t}\n\tif err != nil {\n\t\tutils.Logger().Warn().Err(err).Msg(\"invalid to parameter\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tvar offset int\n\tif offsetParam != \"\" {\n\t\toffset, err = strconv.Atoi(offsetParam)\n\t\tif err != nil || offset < 1 {\n\t\t\tutils.Logger().Warn().Msg(\"invalid offset parameter\")\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\toffset = paginationOffset\n\t}\n\tvar page int\n\tif pageParam != \"\" {\n\t\tpage, err = strconv.Atoi(pageParam)\n\t\tif err != nil {\n\t\t\tutils.Logger().Warn().Err(err).Msg(\"invalid page parameter\")\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tpage = 0\n\t}\n\n\taccountBlocks := s.ReadBlocksFromDB(fromInt, toInt)\n\tfor id, accountBlock := range accountBlocks {\n\t\tif id == 0 || id == len(accountBlocks)-1 || accountBlock == nil {\n\t\t\tcontinue\n\t\t}\n\t\tblock := NewBlock(accountBlock, id+fromInt-1)\n\t\t// Populate transactions\n\t\tfor _, tx := range accountBlock.Transactions() {\n\t\t\ttransaction := GetTransaction(tx, accountBlock)\n\t\t\tif transaction != nil {\n\t\t\t\tblock.TXs = append(block.TXs, transaction)\n\t\t\t}\n\t\t}\n\t\tif accountBlocks[id-1] == nil {\n\t\t\tblock.BlockTime = int64(0)\n\t\t\tblock.PrevBlock = RefBlock{\n\t\t\t\tID: \"\",\n\t\t\t\tHeight: \"\",\n\t\t\t}\n\t\t} else {\n\t\t\tblock.BlockTime = accountBlock.Time().Int64() - accountBlocks[id-1].Time().Int64()\n\t\t\tblock.PrevBlock = RefBlock{\n\t\t\t\tID: accountBlocks[id-1].Hash().Hex(),\n\t\t\t\tHeight: strconv.Itoa(id + fromInt - 2),\n\t\t\t}\n\t\t}\n\t\tif accountBlocks[id+1] == nil {\n\t\t\tblock.NextBlock = RefBlock{\n\t\t\t\tID: \"\",\n\t\t\t\tHeight: \"\",\n\t\t\t}\n\t\t} else {\n\t\t\tblock.NextBlock = RefBlock{\n\t\t\t\tID: accountBlocks[id+1].Hash().Hex(),\n\t\t\t\tHeight: strconv.Itoa(id + fromInt),\n\t\t\t}\n\t\t}\n\t\tdata.Blocks = append(data.Blocks, block)\n\t}\n\tif offset*page >= len(data.Blocks) {\n\t\tdata.Blocks = []*Block{}\n\t} else if offset*page+offset > len(data.Blocks) {\n\t\tdata.Blocks = data.Blocks[offset*page:]\n\t} else {\n\t\tdata.Blocks = data.Blocks[offset*page : offset*page+offset]\n\t}\n\tif order == \"DESC\" {\n\t\tsort.Slice(data.Blocks[:], func(i, j int) bool {\n\t\t\treturn data.Blocks[i].Timestamp > data.Blocks[j].Timestamp\n\t\t})\n\t} else {\n\t\tsort.Slice(data.Blocks[:], func(i, j int) bool {\n\t\t\treturn data.Blocks[i].Timestamp < data.Blocks[j].Timestamp\n\t\t})\n\t}\n}", "func (core *coreService) BlockByHeightRange(start uint64, count uint64) ([]*apitypes.BlockWithReceipts, error) {\n\tif count == 0 {\n\t\treturn nil, errors.Wrap(errInvalidFormat, \"count must be greater than zero\")\n\t}\n\tif count > core.cfg.RangeQueryLimit {\n\t\treturn nil, errors.Wrap(errInvalidFormat, \"range exceeds the limit\")\n\t}\n\n\tvar (\n\t\ttipHeight = core.bc.TipHeight()\n\t\tres = make([]*apitypes.BlockWithReceipts, 0)\n\t)\n\tif start > tipHeight {\n\t\treturn nil, errors.Wrap(errInvalidFormat, \"start height should not exceed tip height\")\n\t}\n\tfor height := start; height <= tipHeight && count > 0; height++ {\n\t\tblkStore, err := core.getBlockByHeight(height)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tres = append(res, blkStore)\n\t\tcount--\n\t}\n\treturn res, nil\n}", "func (c *Client) GetBlocks(ctx context.Context, pg *Pagination) ([]*Account, error) {\n\tvar accounts []*Account\n\terr := c.doAPI(ctx, http.MethodGet, \"/api/v1/blocks\", nil, &accounts, pg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn accounts, nil\n}", "func (p *pool) SyncBlocks(ctx context.Context) error {\n\tap := &coilv2.AddressPool{}\n\terr := p.client.Get(ctx, client.ObjectKey{Name: p.name}, ap)\n\tif err != nil {\n\t\tp.log.Error(err, \"failed to get AddressPool\")\n\t\treturn err\n\t}\n\n\tvar maxBlocks int\n\tfor _, sub := range ap.Spec.Subnets {\n\t\tvar n *net.IPNet\n\t\tif sub.IPv4 != nil {\n\t\t\t_, n, _ = net.ParseCIDR(*sub.IPv4)\n\t\t} else {\n\t\t\t_, n, _ = net.ParseCIDR(*sub.IPv6)\n\t\t}\n\t\tones, bits := n.Mask.Size()\n\t\tmaxBlocks += 1 << (bits - ones - int(ap.Spec.BlockSizeBits))\n\t}\n\tp.maxBlocks.Set(float64(maxBlocks))\n\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\tp.allocated.ClearAll()\n\tblocks := &coilv2.AddressBlockList{}\n\terr = p.reader.List(ctx, blocks, client.MatchingLabels{\n\t\tconstants.LabelPool: p.name,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar allocatedBlocks int\n\tfor _, b := range blocks.Items {\n\t\tp.allocated.Set(uint(b.Index))\n\t\tallocatedBlocks += 1\n\t}\n\tp.allocatedBlocks.Set(float64(allocatedBlocks))\n\n\tp.log.Info(\"resynced block usage\", \"blocks\", len(blocks.Items))\n\treturn nil\n}", "func (dcr *ExchangeWallet) monitorBlocks(ctx context.Context) {\n\tticker := time.NewTicker(blockTicker)\n\tdefer ticker.Stop()\n\n\tvar walletBlock <-chan *block\n\tif notifier, isNotifier := dcr.wallet.(tipNotifier); isNotifier {\n\t\twalletBlock = notifier.tipFeed()\n\t}\n\n\t// A polledBlock is a block found during polling, but whose broadcast has\n\t// been queued in anticipation of a wallet notification.\n\ttype polledBlock struct {\n\t\t*block\n\t\tqueue *time.Timer\n\t}\n\n\t// queuedBlock is the currently queued, polling-discovered block that will\n\t// be broadcast after a timeout if the wallet doesn't send the matching\n\t// notification.\n\tvar queuedBlock *polledBlock\n\n\t// checkTip captures queuedBlock and walletBlock.\n\tcheckTip := func() {\n\t\tctx, cancel := context.WithTimeout(dcr.ctx, 4*time.Second)\n\t\tdefer cancel()\n\n\t\tnewTip, err := dcr.getBestBlock(ctx)\n\t\tif err != nil {\n\t\t\tdcr.handleTipChange(nil, 0, fmt.Errorf(\"failed to get best block: %w\", err))\n\t\t\treturn\n\t\t}\n\n\t\tdcr.tipMtx.RLock()\n\t\tsameTip := dcr.currentTip.hash.IsEqual(newTip.hash)\n\t\tdcr.tipMtx.RUnlock()\n\n\t\tif sameTip {\n\t\t\treturn\n\t\t}\n\n\t\tif walletBlock == nil {\n\t\t\tdcr.handleTipChange(newTip.hash, newTip.height, nil)\n\t\t\treturn\n\t\t}\n\n\t\t// Queue it for reporting, but don't send it right away. Give the wallet\n\t\t// a chance to provide their block update. SPV wallet may need more time\n\t\t// after storing the block header to fetch and scan filters and issue\n\t\t// the FilteredBlockConnected report.\n\t\tif queuedBlock != nil {\n\t\t\tqueuedBlock.queue.Stop()\n\t\t}\n\t\tblockAllowance := walletBlockAllowance\n\t\tctx, cancel = context.WithTimeout(dcr.ctx, 4*time.Second)\n\t\tsynced, _, err := dcr.wallet.SyncStatus(ctx)\n\t\tcancel()\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"Error retrieving sync status before queuing polled block: %v\", err)\n\t\t} else if !synced {\n\t\t\tblockAllowance *= 10\n\t\t}\n\t\tqueuedBlock = &polledBlock{\n\t\t\tblock: newTip,\n\t\t\tqueue: time.AfterFunc(blockAllowance, func() {\n\t\t\t\tdcr.log.Warnf(\"Reporting a block found in polling that the wallet apparently \"+\n\t\t\t\t\t\"never reported: %s (%d). If you see this message repeatedly, it may indicate \"+\n\t\t\t\t\t\"an issue with the wallet.\", newTip.hash, newTip.height)\n\t\t\t\tdcr.handleTipChange(newTip.hash, newTip.height, nil)\n\t\t\t}),\n\t\t}\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tcheckTip()\n\n\t\tcase walletTip := <-walletBlock:\n\t\t\tif queuedBlock != nil && walletTip.height >= queuedBlock.height {\n\t\t\t\tif !queuedBlock.queue.Stop() && walletTip.hash == queuedBlock.hash {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tqueuedBlock = nil\n\t\t\t}\n\t\t\tdcr.handleTipChange(walletTip.hash, walletTip.height, nil)\n\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c *Client) GetBlocksByRange(before, after uint64, noempty bool) (blocks *rpctypes.ResultBlockchainInfo, err error) {\n\tblocks = new(rpctypes.ResultBlockchainInfo)\n\tp := params{}\n\tif noempty {\n\t\tp[\"noempty\"] = \"true\"\n\t}\n\terr = c.get(blocks, c.URLP(\n\t\tp,\n\t\t\"block/range/%d/%d\", after, before,\n\t))\n\terr = errors.Wrap(err, \"getting blocks by height range\")\n\treturn\n}", "func GetBlocks(hostURL string, hostPort int, height int) *bytes.Buffer {\n\tparams := make(map[string]interface{})\n\tparams[\"height\"] = height\n\treturn makePostRequest(hostURL, hostPort, \"f_blocks_list_json\", params)\n}", "func CheckSizeBlocks(start, end uint64) error {\n\ttxn := globalOpt.Txn(true)\n\tdefer txn.Commit()\n\n\tlist := make([]interface{}, 0, 64)\n\n\tit, err := txn.Get(TableBlockKey, HeightBlockKey)\n\tif err != nil {\n\t\ttxn.Abort()\n\t\treturn err\n\t}\n\tfor obj := it.Next(); obj != nil; obj = it.Next() {\n\t\tv, ok := obj.(*fabclient.MiddleCommonBlock)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif v.Number < start || v.Number > end {\n\t\t\tlist = append(list, obj)\n\t\t}\n\t}\n\n\tfor _, one := range list {\n\t\terr = txn.Delete(TableBlockKey, one)\n\t\tif err != nil {\n\t\t\ttxn.Abort()\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func BorMissedBlocks(ops types.HTTPOptions, cfg *config.Config, c client.Client) {\n\tbp, err := db.CreateBatchPoints(cfg.InfluxDB.Database)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tborHeight := GetBorCurrentBlokHeightInHex(cfg, c)\n\tif borHeight == \"\" {\n\t\tlog.Println(\"Got empty block height of bor from db\")\n\t\treturn\n\t}\n\n\tops.Body.Params = append(ops.Body.Params, borHeight)\n\n\tsigners, err := scraper.BorSignersRes(ops)\n\tif err != nil {\n\t\tlog.Printf(\"Error in BorMissedBlocks: %v\", err)\n\t\treturn\n\t}\n\n\theight, err := utils.HexToIntConversion(borHeight)\n\tif err != nil {\n\t\tlog.Printf(\"Error while converting bor height from hex to int : %v\", err)\n\t\treturn\n\t}\n\n\tcbh := strconv.Itoa(height)\n\n\tif signers.Result != nil {\n\t\tisSigned := false\n\n\t\tfor _, addr := range signers.Result {\n\t\t\tif strings.EqualFold(addr, cfg.ValDetails.SignerAddress) {\n\t\t\t\tisSigned = true\n\t\t\t}\n\t\t}\n\n\t\tlog.Printf(\"block signed status : %v, and height : %s \", isSigned, cbh)\n\n\t\tif !isSigned {\n\t\t\tblocks := GetBorContinuousMissedBlock(cfg, c)\n\t\t\tcurrentHeightFromDb := GetBorlatestCurrentHeightFromDB(cfg, c)\n\t\t\tblocksArray := strings.Split(blocks, \",\")\n\t\t\t// calling function to store single blocks\n\t\t\terr = SendBorSingleMissedBlockAlert(ops, cfg, c, cbh)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error while sending missed block alert: %v\", err)\n\n\t\t\t}\n\t\t\tif cfg.AlertingThresholds.MissedBlocksThreshold > 1 && strings.ToUpper(cfg.AlerterPreferences.MissedBlockAlerts) == \"YES\" {\n\t\t\t\tif int64(len(blocksArray))-1 >= cfg.AlertingThresholds.MissedBlocksThreshold {\n\t\t\t\t\tmissedBlocks := strings.Split(blocks, \",\")\n\t\t\t\t\t_ = alerter.SendTelegramAlert(fmt.Sprintf(\"⚠️ Bor Missed Blocks Alert: %s validator on bor node missed blocks from height %s to %s\", cfg.ValDetails.ValidatorName, missedBlocks[0], missedBlocks[len(missedBlocks)-2]), cfg)\n\t\t\t\t\t_ = alerter.SendEmailAlert(fmt.Sprintf(\"⚠️ Bor Missed Blocks Alert: %s validator on bor node missed blocks from height %s to %s\", cfg.ValDetails.ValidatorName, missedBlocks[0], missedBlocks[len(missedBlocks)-2]), cfg)\n\t\t\t\t\t_ = db.WriteToInfluxDb(c, bp, \"bor_continuous_missed_blocks\", map[string]string{}, map[string]interface{}{\"missed_blocks\": blocks, \"range\": missedBlocks[0] + \" - \" + missedBlocks[len(missedBlocks)-2]})\n\t\t\t\t\t_ = db.WriteToInfluxDb(c, bp, \"matic_bor_missed_blocks\", map[string]string{}, map[string]interface{}{\"block_height\": \"\", \"current_height\": cbh})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif len(blocksArray) == 1 {\n\t\t\t\t\tblocks = cbh + \",\"\n\t\t\t\t} else {\n\t\t\t\t\trpcBlockHeight, _ := strconv.Atoi(cbh)\n\t\t\t\t\tdbBlockHeight, _ := strconv.Atoi(currentHeightFromDb)\n\t\t\t\t\tdiff := rpcBlockHeight - dbBlockHeight\n\t\t\t\t\tif diff == 1 {\n\t\t\t\t\t\tblocks = blocks + cbh + \",\"\n\t\t\t\t\t} else if diff > 1 {\n\t\t\t\t\t\tblocks = \"\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\terr = db.WriteToInfluxDb(c, bp, \"matic_bor_missed_blocks\", map[string]string{}, map[string]interface{}{\"block_height\": blocks, \"current_height\": cbh})\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error while storing missed blocks : %v \", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\terr = db.WriteToInfluxDb(c, bp, \"bor_val_signed_blocks\", map[string]string{}, map[string]interface{}{\"signed_block_height\": cbh})\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error while storing validator signed blocks : %v \", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else {\n\t\tlog.Println(\"Got an empty response from bor rpc !\")\n\t\treturn\n\t}\n}", "func GetBlockRange(cache *BlockCache, blockOut chan<- *walletrpc.CompactBlock, errOut chan<- error, start, end int) {\n\t// Go over [start, end] inclusive\n\tfor i := start; i <= end; i++ {\n\t\tblock, err := GetBlock(cache, i)\n\t\tif err != nil {\n\t\t\terrOut <- err\n\t\t\treturn\n\t\t}\n\t\tblockOut <- block\n\t}\n\terrOut <- nil\n}", "func (m *GetHeadersMessage) GetBlockLocator() []*bc.Hash {\n\tblockLocator := []*bc.Hash{}\n\tfor _, rawHash := range m.RawBlockLocator {\n\t\thash := bc.NewHash(rawHash)\n\t\tblockLocator = append(blockLocator, &hash)\n\t}\n\treturn blockLocator\n}", "func (c *Client) GetBlocksByDaterange(first, last time.Time, noempty bool, after time.Time, limit int) (blocks *rpctypes.ResultBlockchainInfo, err error) {\n\tblocks = new(rpctypes.ResultBlockchainInfo)\n\tp := params{}\n\tif after != (time.Time{}) {\n\t\tp[\"after\"] = after.Format(time.RFC3339)\n\t}\n\tif limit != 0 {\n\t\tp[\"limit\"] = limit\n\t}\n\terr = c.get(\n\t\tblocks,\n\t\tc.URLP(\n\t\t\tp,\n\t\t\t\"block/daterange/%s/%s\", first.Format(time.RFC3339), last.Format(time.RFC3339),\n\t\t),\n\t)\n\terr = errors.Wrap(err, \"getting blocks by date range\")\n\treturn\n}", "func GetBlocks(w http.ResponseWriter, r *http.Request) {\n\t// Send a copy of this node's blockchain\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(b.blockchain)\n}", "func (dcr *ExchangeWallet) findRedemptionsInBlockRange(startBlockHeight, endBlockHeight int64, contractOutpoints []outPoint) {\n\ttotalContracts := len(contractOutpoints)\n\tdcr.log.Debugf(\"finding redemptions for %d contracts in blocks %d - %d\",\n\t\ttotalContracts, startBlockHeight, endBlockHeight)\n\n\tvar lastScannedBlockHeight int64\n\tvar totalFound, totalCanceled int\n\nrangeBlocks:\n\tfor blockHeight := startBlockHeight; blockHeight <= endBlockHeight; blockHeight++ {\n\t\t// Get the hash for this block.\n\t\tblockHash, err := dcr.wallet.GetBlockHash(dcr.ctx, blockHeight)\n\t\tif err != nil { // unable to get block hash is a fatal error\n\t\t\terr = fmt.Errorf(\"unable to get hash for block %d: %w\", blockHeight, err)\n\t\t\tdcr.fatalFindRedemptionsError(err, contractOutpoints)\n\t\t\treturn\n\t\t}\n\n\t\t// Combine the p2sh scripts for all contracts (excluding contracts whose redemption\n\t\t// have been found) to check against this block's cfilters.\n\t\tdcr.findRedemptionMtx.RLock()\n\t\tcontractP2SHScripts := make([][]byte, 0)\n\t\tfor _, contractOutpoint := range contractOutpoints {\n\t\t\tif req, stillInQueue := dcr.findRedemptionQueue[contractOutpoint]; stillInQueue {\n\t\t\t\tcontractP2SHScripts = append(contractP2SHScripts, req.contractP2SHScript)\n\t\t\t}\n\t\t}\n\t\tdcr.findRedemptionMtx.RUnlock()\n\n\t\tbingo, err := dcr.wallet.MatchAnyScript(dcr.ctx, blockHash, contractP2SHScripts)\n\t\tif err != nil { // error retrieving a block's cfilters is a fatal error\n\t\t\terr = fmt.Errorf(\"MatchAnyScript error for block %d (%s): %w\", blockHeight, blockHash, err)\n\t\t\tdcr.fatalFindRedemptionsError(err, contractOutpoints)\n\t\t\treturn\n\t\t}\n\n\t\tif !bingo {\n\t\t\tlastScannedBlockHeight = blockHeight\n\t\t\tcontinue // block does not reference any of these contracts, continue to next block\n\t\t}\n\n\t\t// Pull the block info to confirm if any of its inputs spends a contract of interest.\n\t\tblk, err := dcr.wallet.GetBlock(dcr.ctx, blockHash)\n\t\tif err != nil { // error pulling a matching block's transactions is a fatal error\n\t\t\terr = fmt.Errorf(\"error retrieving transactions for block %d (%s): %w\",\n\t\t\t\tblockHeight, blockHash, err)\n\t\t\tdcr.fatalFindRedemptionsError(err, contractOutpoints)\n\t\t\treturn\n\t\t}\n\n\t\tlastScannedBlockHeight = blockHeight\n\t\tscanPoint := fmt.Sprintf(\"block %d\", blockHeight)\n\t\tfor _, tx := range append(blk.Transactions, blk.STransactions...) {\n\t\t\tfound, canceled := dcr.findRedemptionsInTx(scanPoint, tx, contractOutpoints)\n\t\t\ttotalFound += found\n\t\t\ttotalCanceled += canceled\n\t\t\tif totalFound+totalCanceled == totalContracts {\n\t\t\t\tbreak rangeBlocks\n\t\t\t}\n\t\t}\n\t}\n\n\tdcr.log.Debugf(\"%d redemptions found, %d canceled out of %d contracts in blocks %d to %d\",\n\t\ttotalFound, totalCanceled, totalContracts, startBlockHeight, lastScannedBlockHeight)\n\n\t// Search for redemptions in mempool if there are yet unredeemed\n\t// contracts after searching this block range.\n\tpendingContractsCount := totalContracts - totalFound - totalCanceled\n\tif pendingContractsCount > 0 {\n\t\tdcr.findRedemptionMtx.RLock()\n\t\tpendingContracts := make([]outPoint, 0, pendingContractsCount)\n\t\tfor _, contractOutpoint := range contractOutpoints {\n\t\t\tif _, pending := dcr.findRedemptionQueue[contractOutpoint]; pending {\n\t\t\t\tpendingContracts = append(pendingContracts, contractOutpoint)\n\t\t\t}\n\t\t}\n\t\tdcr.findRedemptionMtx.RUnlock()\n\t\tdcr.findRedemptionsInMempool(pendingContracts)\n\t}\n}", "func (client *Client) QueryBlocks(query *Query) (*Response, error) {\n\tpath := \"/block\"\n\turi := fmt.Sprintf(\"%s%s\", client.apiBaseURL, path)\n\n\treq, err := http.NewRequest(\"GET\", uri, bytes.NewBuffer([]byte(\"\")))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuildQuery(req, query)\n\tresp, err := client.performRequest(req, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar results map[string][]Block\n\terr = json.Unmarshal(resp.Response.([]byte), &results)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Response = results\n\treturn resp, err\n}", "func (c *Client) GetBlocks(height string) (resp *Blocks, e error) {\n\tif height == \"\" {\n\t\treturn nil, c.err(ErrBEW)\n\t}\n\n\tresp = &Blocks{}\n\treturn resp, c.Do(\"/blocks/\"+height, resp, nil)\n}", "func (synckerManager *SynckerManager) GetS2BBlocksForBeaconProducer(bestViewShardHash map[byte]common.Hash, limit map[byte][]common.Hash) map[byte][]interface{} {\n\tres := make(map[byte][]interface{})\n\n\tfor i := 0; i < synckerManager.config.Node.GetChainParam().ActiveShards; i++ {\n\t\tv := bestViewShardHash[byte(i)]\n\t\t//beacon beststate dont have shard hash => create one\n\t\tif (&v).IsEqual(&common.Hash{}) {\n\t\t\tblk := *synckerManager.config.Node.GetChainParam().GenesisShardBlock\n\t\t\tblk.Header.ShardID = byte(i)\n\t\t\tv = *blk.Hash()\n\t\t}\n\n\t\tfor _, v := range synckerManager.s2bPool.GetFinalBlockFromBlockHash(v.String()) {\n\t\t\t//if limit has 0 length, we should break now\n\t\t\tif limit != nil && len(res[byte(i)]) >= len(limit[byte(i)]) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tres[byte(i)] = append(res[byte(i)], v)\n\t\t\tif len(res[byte(i)]) >= MAX_S2B_BLOCK {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}", "func (l *Ledger) ConfirmBlock(block *pb.InternalBlock, isRoot bool) ConfirmStatus {\n\tl.mutex.Lock()\n\tdefer l.mutex.Unlock()\n\tblkTimer := timer.NewXTimer()\n\tl.xlog.Info(\"start to confirm block\", \"blockid\", utils.F(block.Blockid), \"txCount\", len(block.Transactions))\n\tvar confirmStatus ConfirmStatus\n\tdummyTransactions := []*pb.Transaction{}\n\trealTransactions := block.Transactions // 真正的交易转存到局部变量\n\tblock.Transactions = dummyTransactions // block表不保存transaction详情\n\n\tbatchWrite := l.ConfirmBatch\n\tbatchWrite.Reset()\n\tnewMeta := proto.Clone(l.meta).(*pb.LedgerMeta)\n\tsplitHeight := newMeta.TrunkHeight\n\tif isRoot { //确认创世块\n\t\tif block.PreHash != nil && len(block.PreHash) > 0 {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tl.xlog.Warn(\"genesis block shoud has no prehash\")\n\t\t\treturn confirmStatus\n\t\t}\n\t\tif len(l.meta.RootBlockid) > 0 {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tconfirmStatus.Error = ErrRootBlockAlreadyExist\n\t\t\tl.xlog.Warn(\"already hash genesis block\")\n\t\t\treturn confirmStatus\n\t\t}\n\t\tnewMeta.RootBlockid = block.Blockid\n\t\tnewMeta.TrunkHeight = 0 //代表主干上块的最大高度\n\t\tnewMeta.TipBlockid = block.Blockid\n\t\tblock.InTrunk = true\n\t\tblock.Height = 0 // 创世纪块是第0块\n\t} else { //非创世块,需要判断是在主干还是分支\n\t\tpreHash := block.PreHash\n\t\tpreBlock, findErr := l.fetchBlock(preHash)\n\t\tif findErr != nil {\n\t\t\tl.xlog.Warn(\"find pre block fail\", \"findErr\", findErr)\n\t\t\tconfirmStatus.Succ = false\n\t\t\treturn confirmStatus\n\t\t}\n\t\tblock.Height = preBlock.Height + 1 //不管是主干还是分支,height都是++\n\t\tif bytes.Equal(preBlock.Blockid, newMeta.TipBlockid) {\n\t\t\t//在主干上添加\n\t\t\tblock.InTrunk = true\n\t\t\tpreBlock.NextHash = block.Blockid\n\t\t\tnewMeta.TipBlockid = block.Blockid\n\t\t\tnewMeta.TrunkHeight++\n\t\t\t//因为改了pre_block的next_hash值,所以也要写回存储\n\t\t\tif !DisableTxDedup {\n\t\t\t\tsaveErr := l.saveBlock(preBlock, batchWrite)\n\t\t\t\tl.blockCache.Del(string(preBlock.Blockid))\n\t\t\t\tif saveErr != nil {\n\t\t\t\t\tl.xlog.Warn(\"save block fail\", \"saveErr\", saveErr)\n\t\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\t\treturn confirmStatus\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t//在分支上\n\t\t\tif preBlock.Height+1 > newMeta.TrunkHeight {\n\t\t\t\t//分支要变成主干了\n\t\t\t\toldTip := append([]byte{}, newMeta.TipBlockid...)\n\t\t\t\tnewMeta.TrunkHeight = preBlock.Height + 1\n\t\t\t\tnewMeta.TipBlockid = block.Blockid\n\t\t\t\tblock.InTrunk = true\n\t\t\t\tsplitBlock, splitErr := l.handleFork(oldTip, preBlock.Blockid, block.Blockid, batchWrite) //处理分叉\n\t\t\t\tif splitErr != nil {\n\t\t\t\t\tl.xlog.Warn(\"handle split failed\", \"splitErr\", splitErr)\n\t\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\t\treturn confirmStatus\n\t\t\t\t}\n\t\t\t\tsplitHeight = splitBlock.Height\n\t\t\t\tconfirmStatus.Split = true\n\t\t\t\tconfirmStatus.TrunkSwitch = true\n\t\t\t\tl.xlog.Info(\"handle split successfully\", \"splitBlock\", utils.F(splitBlock.Blockid))\n\t\t\t} else {\n\t\t\t\t// 添加在分支上, 对preblock没有影响\n\t\t\t\tblock.InTrunk = false\n\t\t\t\tconfirmStatus.Split = true\n\t\t\t\tconfirmStatus.TrunkSwitch = false\n\t\t\t\tconfirmStatus.Orphan = true\n\t\t\t}\n\t\t}\n\t}\n\tsaveErr := l.saveBlock(block, batchWrite)\n\tblkTimer.Mark(\"saveHeader\")\n\tif saveErr != nil {\n\t\tconfirmStatus.Succ = false\n\t\tl.xlog.Warn(\"save current block fail\", \"saveErr\", saveErr)\n\t\treturn confirmStatus\n\t}\n\t// update branch head\n\tupdateBranchErr := l.updateBranchInfo(block.Blockid, block.PreHash, block.Height, batchWrite)\n\tif updateBranchErr != nil {\n\t\tconfirmStatus.Succ = false\n\t\tl.xlog.Warn(\"update branch info fail\", \"updateBranchErr\", updateBranchErr)\n\t\treturn confirmStatus\n\t}\n\ttxExist, txData := l.parallelCheckTx(realTransactions, block)\n\tcbNum := 0\n\toldBlockCache := map[string]*pb.InternalBlock{}\n\tfor _, tx := range realTransactions {\n\t\t//在这儿解析交易存表,调用新版的接口TxOutputs不会超过4\n\t\t//理论上这儿坐过校验判断后,不会报错,目前还是写好报错码,以便调试\n\t\tif len(tx.TxInputs) >0 &&len(tx.TxOutputs) < 4 && len(tx.ContractRequests) > 0 {\n\t\t\treq := tx.ContractRequests[0]\n\t\t\ttmpReq := &InvokeRequest{\n\t\t\t\tModuleName: req.ModuleName,\n\t\t\t\tContractName: req.ContractName,\n\t\t\t\tMethodName: req.MethodName,\n\t\t\t\tArgs: map[string]string{},\n\t\t\t}\n\t\t\tfor argKey, argV := range req.Args {\n\t\t\t\ttmpReq.Args[argKey] = string(argV)\n\t\t\t}\n\t\t\tif tmpReq.ModuleName == \"xkernel\" && tmpReq.ContractName == \"$govern_token\"{\n\t\t\t\t//这里有buy和sell\n\t\t\t\tswitch tmpReq.MethodName {\n\t\t\t\tcase \"Buy\":\n\t\t\t\t\tl.WriteFreezeTable(batchWrite,tmpReq.Args[\"amount\"],string(tx.TxInputs[0].FromAddr),tx.Txid)\n\t\t\t\tcase \"Sell\":\n\t\t\t\t\tl.WriteThawTable(batchWrite,string(tx.TxInputs[0].FromAddr),tx.Desc)\n\t\t\t\tdefault:\n\t\t\t\t\tl.xlog.Warn(\"D__解析交易存表时方法异常,异常方法名:\",\"tmpReq.MethodName\",tmpReq.MethodName)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif tmpReq.ModuleName == \"xkernel\" && (tmpReq.ContractName == \"$tdpos\" || tmpReq.ContractName ==\"$xpos\" ) {\n\t\t\t\tswitch tmpReq.MethodName {\n\t\t\t\tcase \"nominateCandidate\":\n\t\t\t\t\tl.WriteCandidateTable(batchWrite,string(tx.TxInputs[0].FromAddr),tmpReq.Args)\n\t\t\t\tcase \"revokeNominate\":\n\t\t\t\t\tl.WriteReCandidateTable(batchWrite,string(tx.TxInputs[0].FromAddr),tmpReq.Args)\n\t\t\t\tcase \"voteCandidate\":\n\t\t\t\t\tl.VoteCandidateTable(batchWrite,string(tx.TxInputs[0].FromAddr),tmpReq.Args)\n\t\t\t\tcase \"revokeVote\":\n\t\t\t\t\tl.RevokeVote(batchWrite,string(tx.TxInputs[0].FromAddr),tmpReq.Args)\n\t\t\t\tdefault:\n\t\t\t\t\tl.xlog.Warn(\"D__解析tdpos交易存表时方法异常,异常方法名:\",\"tmpReq.MethodName\",tmpReq.MethodName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t\tif tx.Coinbase {\n\t\t\tcbNum = cbNum + 1\n\t\t}\n\t\tif cbNum > 1 {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tl.xlog.Warn(\"The num of Coinbase tx should not exceed one when confirm block\",\n\t\t\t\t\"BlockID\", utils.F(tx.Blockid), \"Miner\", string(block.Proposer))\n\t\t\treturn confirmStatus\n\t\t}\n\n\t\tpbTxBuf := txData[string(tx.Txid)]\n\t\tif pbTxBuf == nil {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tl.xlog.Warn(\"marshal trasaction failed when confirm block\")\n\t\t\treturn confirmStatus\n\t\t}\n\t\thasTx := txExist[string(tx.Txid)]\n\t\tif !hasTx {\n\t\t\tbatchWrite.Put(append([]byte(pb.ConfirmedTablePrefix), tx.Txid...), pbTxBuf)\n\t\t} else {\n\t\t\t//confirm表已经存在这个交易了,需要检查一下是否存在多个主干block包含同样trasnaction的情况\n\t\t\toldPbTxBuf, _ := l.ConfirmedTable.Get(tx.Txid)\n\t\t\toldTx := &pb.Transaction{}\n\t\t\tparserErr := proto.Unmarshal(oldPbTxBuf, oldTx)\n\t\t\tif parserErr != nil {\n\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\tconfirmStatus.Error = parserErr\n\t\t\t\treturn confirmStatus\n\t\t\t}\n\t\t\toldBlock := &pb.InternalBlock{}\n\t\t\tif cachedBlk, cacheHit := oldBlockCache[string(oldTx.Blockid)]; cacheHit {\n\t\t\t\toldBlock = cachedBlk\n\t\t\t} else {\n\t\t\t\toldPbBlockBuf, blockErr := l.blocksTable.Get(oldTx.Blockid)\n\t\t\t\tif blockErr != nil {\n\t\t\t\t\tif def.NormalizedKVError(blockErr) == def.ErrKVNotFound {\n\t\t\t\t\t\tl.xlog.Warn(\"old block that contains the tx has been truncated\", \"txid\", utils.F(tx.Txid), \"blockid\", utils.F(oldTx.Blockid))\n\t\t\t\t\t\tbatchWrite.Put(append([]byte(pb.ConfirmedTablePrefix), tx.Txid...), pbTxBuf) //overwrite with newtx\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\t\tconfirmStatus.Error = blockErr\n\t\t\t\t\treturn confirmStatus\n\t\t\t\t}\n\t\t\t\tparserErr = proto.Unmarshal(oldPbBlockBuf, oldBlock)\n\t\t\t\tif parserErr != nil {\n\t\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\t\tconfirmStatus.Error = parserErr\n\t\t\t\t\treturn confirmStatus\n\t\t\t\t}\n\t\t\t\toldBlockCache[string(oldBlock.Blockid)] = oldBlock\n\t\t\t}\n\t\t\tif oldBlock.InTrunk && block.InTrunk && oldBlock.Height <= splitHeight {\n\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\tconfirmStatus.Error = ErrTxDuplicated\n\t\t\t\tl.xlog.Warn(\"transaction duplicated in previous trunk block\",\n\t\t\t\t\t\"txid\", utils.F(tx.Txid),\n\t\t\t\t\t\"blockid\", utils.F(oldBlock.Blockid))\n\t\t\t\treturn confirmStatus\n\t\t\t} else if block.InTrunk {\n\t\t\t\tl.xlog.Info(\"change blockid of tx\", \"txid\", utils.F(tx.Txid), \"blockid\", utils.F(block.Blockid))\n\t\t\t\tbatchWrite.Put(append([]byte(pb.ConfirmedTablePrefix), tx.Txid...), pbTxBuf)\n\t\t\t}\n\t\t}\n\t}\n\tblkTimer.Mark(\"saveAllTxs\")\n\t//删除pendingBlock中对应的数据\n\tbatchWrite.Delete(append([]byte(pb.PendingBlocksTablePrefix), block.Blockid...))\n\t//改meta\n\tmetaBuf, pbErr := proto.Marshal(newMeta)\n\tif pbErr != nil {\n\t\tl.xlog.Warn(\"marshal meta fail\", \"pbErr\", pbErr)\n\t\tconfirmStatus.Succ = false\n\t\treturn confirmStatus\n\t}\n\tbatchWrite.Put([]byte(pb.MetaTablePrefix), metaBuf)\n\tl.xlog.Debug(\"print block size when confirm block\", \"blockSize\", batchWrite.ValueSize(), \"blockid\", utils.F(block.Blockid))\n\tkvErr := batchWrite.Write() // blocks, confirmed_transaction两张表原子写入\n\tblkTimer.Mark(\"saveToDisk\")\n\tif kvErr != nil {\n\t\tconfirmStatus.Succ = false\n\t\tconfirmStatus.Error = kvErr\n\t\tl.xlog.Warn(\"batch write failed when confirm block\", \"kvErr\", kvErr)\n\t} else {\n\t\tconfirmStatus.Succ = true\n\t\tl.meta = newMeta\n\t}\n\tblock.Transactions = realTransactions\n\tif isRoot {\n\t\t//首次confirm 创始块的时候\n\t\tlErr := l.loadGenesisBlock(false, nil)\n\t\tif lErr != nil {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tconfirmStatus.Error = lErr\n\t\t}\n\t}\n\tl.blockCache.Add(string(block.Blockid), block)\n\tl.xlog.Debug(\"confirm block cost\", \"blkTimer\", blkTimer.Print())\n\treturn confirmStatus\n}", "func GetBlock(x uint64) block.Block{\r\n\t\tvar block1 block.MinBlock\r\n\t\tvar block2 block.Block\r\n\t\tblock1.BlockNumber = x\r\n\t\tblock1.ChainYear = ChainYear\r\n\t\tfmt.Println(\"ChainYear\", block1.ChainYear)\r\n\t\tdata, err:= json.Marshal(block1)\r\n\t\tif err !=nil{\r\n\t\t\tfmt.Println(\"Error Reading Block\", err)\r\n\t\t}\r\n\t\tfmt.Println(\"Block as Json\", data)\r\n\t\ttheNodes := GetNodes(block1.BlockHash())\r\n\t\t\r\n\t\tcall := \"getBlock\"\r\n\t\t\r\n\t\tfor x:=0; x < len(theNodes); x +=1{\r\n\t\t\t\t\r\n\t\t\turl1 := \"http://\"+ MyNode.Ip+ MyNode.Port+\"/\"+ call\r\n\t\t\tfmt.Println(\"url:\", url1)\r\n\t\t\t resp, err := http.Post(url1, \"application/json\", bytes.NewBuffer(data))\r\n\r\n\t\t\tif err != nil {\r\n\t\t\t\tfmt.Println(\"Error connectig to node trying next node \", err)\r\n\t\t\t}else{\r\n\t\t\t\tfmt.Println(\"Block as Json\", data)\r\n\t\t\t\tjson.NewDecoder(resp.Body).Decode(&block2)\r\n\t\t\t\treturn block2\r\n\t\t\t}\r\n\t\t}\r\nreturn block2\r\n\t\t\r\n\t\t\r\n}", "func (dag *BlockDAG) BlockForMining(transactions []*util.Tx) (*domainmessage.MsgBlock, error) {\n\tblockTimestamp := dag.NextBlockTime()\n\trequiredDifficulty := dag.NextRequiredDifficulty(blockTimestamp)\n\n\t// Calculate the next expected block version based on the state of the\n\t// rule change deployments.\n\tnextBlockVersion, err := dag.CalcNextBlockVersion()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a new block ready to be solved.\n\thashMerkleTree := BuildHashMerkleTreeStore(transactions)\n\tacceptedIDMerkleRoot, err := dag.NextAcceptedIDMerkleRootNoLock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar msgBlock domainmessage.MsgBlock\n\tfor _, tx := range transactions {\n\t\tmsgBlock.AddTransaction(tx.MsgTx())\n\t}\n\n\tmultiset, err := dag.NextBlockMultiset()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmsgBlock.Header = domainmessage.BlockHeader{\n\t\tVersion: nextBlockVersion,\n\t\tParentHashes: dag.TipHashes(),\n\t\tHashMerkleRoot: hashMerkleTree.Root(),\n\t\tAcceptedIDMerkleRoot: acceptedIDMerkleRoot,\n\t\tUTXOCommitment: (*daghash.Hash)(multiset.Finalize()),\n\t\tTimestamp: blockTimestamp,\n\t\tBits: requiredDifficulty,\n\t}\n\n\treturn &msgBlock, nil\n}", "func (dcr *ExchangeWallet) findRedemptionsInBlockRange(startBlock, endBlock *block, contractOutpoints []outPoint) {\n\tcontractsCount := len(contractOutpoints)\n\tdcr.log.Debugf(\"finding redemptions for %d contracts in blocks %d - %d\",\n\t\tcontractsCount, startBlock.height, endBlock.height)\n\n\tnextBlockHash := startBlock.hash\n\tvar lastScannedBlockHeight int64\n\tvar redemptionsFound int\n\nrangeBlocks:\n\tfor nextBlockHash != nil && lastScannedBlockHeight < endBlock.height {\n\t\tblk, err := dcr.node.GetBlockVerbose(dcr.ctx, nextBlockHash, true)\n\t\tif err != nil {\n\t\t\t// Redemption search for this set of contracts is compromised. Notify\n\t\t\t// the redemption finder(s) of this fatal error and cancel redemption\n\t\t\t// search for these contracts. The redemption finder(s) may re-call\n\t\t\t// dcr.FindRedemption to restart find redemption attempts for any of\n\t\t\t// these contracts.\n\t\t\terr = fmt.Errorf(\"error fetching verbose block %s: %w\", nextBlockHash, translateRPCCancelErr(err))\n\t\t\tdcr.fatalFindRedemptionsError(err, contractOutpoints)\n\t\t\treturn\n\t\t}\n\t\tscanPoint := fmt.Sprintf(\"block %d\", blk.Height)\n\t\tlastScannedBlockHeight = blk.Height\n\t\tblkTxs := append(blk.RawTx, blk.RawSTx...)\n\t\tfor t := range blkTxs {\n\t\t\ttx := &blkTxs[t]\n\t\t\tredemptionsFound += dcr.findRedemptionsInTx(scanPoint, tx, contractOutpoints)\n\t\t\tif redemptionsFound == contractsCount {\n\t\t\t\tbreak rangeBlocks\n\t\t\t}\n\t\t}\n\t\tif blk.NextHash == \"\" {\n\t\t\tnextBlockHash = nil\n\t\t} else {\n\t\t\tnextBlockHash, err = chainhash.NewHashFromStr(blk.NextHash)\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"hash decode error %s: %w\", blk.NextHash, err)\n\t\t\t\tdcr.fatalFindRedemptionsError(err, contractOutpoints)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdcr.log.Debugf(\"%d redemptions out of %d contracts found in blocks %d - %d\",\n\t\tredemptionsFound, contractsCount, startBlock.height, lastScannedBlockHeight)\n\n\t// Search for redemptions in mempool if there are yet unredeemed\n\t// contracts after searching this block range.\n\tpendingContractsCount := contractsCount - redemptionsFound\n\tif pendingContractsCount > 0 {\n\t\tdcr.findRedemptionMtx.RLock()\n\t\tpendingContracts := make([]outPoint, 0, pendingContractsCount)\n\t\tfor _, contractOutpoint := range contractOutpoints {\n\t\t\tif _, pending := dcr.findRedemptionQueue[contractOutpoint]; pending {\n\t\t\t\tpendingContracts = append(pendingContracts, contractOutpoint)\n\t\t\t}\n\t\t}\n\t\tdcr.findRedemptionMtx.RUnlock()\n\t\tdcr.findRedemptionsInMempool(pendingContracts)\n\t}\n}", "func (gw *Gateway) GetBlocks(seqs []uint64) ([]coin.SignedBlock, error) {\n\tvar blocks []coin.SignedBlock\n\tvar err error\n\tgw.strand(\"GetBlocks\", func() {\n\t\tblocks, err = gw.v.GetBlocks(seqs)\n\t})\n\treturn blocks, err\n}", "func (bd *BlockDAG) locateBlocks(gs *GraphState, maxHashes uint) []*hash.Hash {\n\tif gs.IsExcellent(bd.getGraphState()) {\n\t\treturn nil\n\t}\n\tqueue := []IBlock{}\n\tfs := NewHashSet()\n\ttips := bd.getValidTips(false)\n\tfor _, v := range tips {\n\t\tib := bd.getBlock(v)\n\t\tqueue = append(queue, ib)\n\t}\n\tfor len(queue) > 0 {\n\t\tcur := queue[0]\n\t\tqueue = queue[1:]\n\n\t\tif fs.Has(cur.GetHash()) {\n\t\t\tcontinue\n\t\t}\n\t\tif gs.GetTips().Has(cur.GetHash()) || cur.GetHash().IsEqual(&bd.genesis) {\n\t\t\tcontinue\n\t\t}\n\t\tneedRec := true\n\t\tif cur.HasChildren() {\n\t\t\tfor _, v := range cur.GetChildren().GetMap() {\n\t\t\t\tib := v.(IBlock)\n\t\t\t\tif gs.GetTips().Has(ib.GetHash()) || !fs.Has(ib.GetHash()) && ib.IsOrdered() {\n\t\t\t\t\tneedRec = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif needRec {\n\t\t\tfs.AddPair(cur.GetHash(), cur)\n\t\t\tif cur.HasParents() {\n\t\t\t\tfor _, v := range cur.GetParents().GetMap() {\n\t\t\t\t\tvalue := v.(IBlock)\n\t\t\t\t\tib := value\n\t\t\t\t\tif fs.Has(ib.GetHash()) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tqueue = append(queue, ib)\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfsSlice := BlockSlice{}\n\tfor _, v := range fs.GetMap() {\n\t\tvalue := v.(IBlock)\n\t\tib := value\n\t\tif gs.GetTips().Has(ib.GetHash()) {\n\t\t\tcontinue\n\t\t}\n\t\tif ib.HasChildren() {\n\t\t\tneed := true\n\t\t\tfor _, v := range ib.GetChildren().GetMap() {\n\t\t\t\tib := v.(IBlock)\n\t\t\t\tif gs.GetTips().Has(ib.GetHash()) {\n\t\t\t\t\tneed = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !need {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tfsSlice = append(fsSlice, ib)\n\t}\n\n\tresult := []*hash.Hash{}\n\tif len(fsSlice) >= 2 {\n\t\tsort.Sort(fsSlice)\n\t}\n\tfor i := 0; i < len(fsSlice); i++ {\n\t\tif maxHashes > 0 && i >= int(maxHashes) {\n\t\t\tbreak\n\t\t}\n\t\tresult = append(result, fsSlice[i].GetHash())\n\t}\n\treturn result\n}", "func findBlocks(dasquery dasql.DASQuery) []string {\n\tspec := dasquery.Spec\n\tinst := dasquery.Instance\n\tvar out []string\n\tblk := spec[\"block\"]\n\tif blk != nil {\n\t\tout = append(out, blk.(string))\n\t\treturn out\n\t}\n\tdataset := spec[\"dataset\"].(string)\n\tapi := \"blocks\"\n\tfurl := fmt.Sprintf(\"%s/%s?dataset=%s\", DBSUrl(inst), api, dataset)\n\tclient := utils.HttpClient()\n\tresp := utils.FetchResponse(client, furl, \"\") // \"\" specify optional args\n\trecords := DBSUnmarshal(api, resp.Data)\n\tfor _, rec := range records {\n\t\tv := rec[\"block_name\"]\n\t\tif v != nil {\n\t\t\tout = append(out, v.(string))\n\t\t}\n\t}\n\treturn out\n}", "func (c *Client) GetBlocksByHeight(before, after uint64, noempty bool) (blocks *rpctypes.ResultBlockchainInfo, err error) {\n\tblocks = new(rpctypes.ResultBlockchainInfo)\n\tp := params{}\n\tif after > 0 {\n\t\tp[\"after\"] = after\n\t}\n\tif noempty {\n\t\tp[\"filter\"] = \"noempty\"\n\t}\n\terr = c.get(blocks, c.URLP(\n\t\tp,\n\t\t\"block/before/%d\", before,\n\t))\n\terr = errors.Wrap(err, \"getting blocks by height\")\n\treturn\n}", "func (f *fragment) Blocks() []FragmentBlock {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\tvar a []FragmentBlock\n\n\t// Initialize the iterator.\n\titr := f.storage.Iterator()\n\titr.Seek(0)\n\n\t// Initialize block hasher.\n\th := newBlockHasher()\n\n\t// Iterate over each value in the fragment.\n\tv, eof := itr.Next()\n\tif eof {\n\t\treturn nil\n\t}\n\tblockID := int(v / (HashBlockSize * ShardWidth))\n\tfor {\n\t\t// Check for multiple block checksums in a row.\n\t\tif n := f.readContiguousChecksums(&a, blockID); n > 0 {\n\t\t\titr.Seek(uint64(blockID+n) * HashBlockSize * ShardWidth)\n\t\t\tv, eof = itr.Next()\n\t\t\tif eof {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tblockID = int(v / (HashBlockSize * ShardWidth))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Reset hasher.\n\t\th.blockID = blockID\n\t\th.Reset()\n\n\t\t// Read all values for the block.\n\t\tfor ; ; v, eof = itr.Next() {\n\t\t\t// Once we hit the next block, save the value for the next iteration.\n\t\t\tblockID = int(v / (HashBlockSize * ShardWidth))\n\t\t\tif blockID != h.blockID || eof {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\th.WriteValue(v)\n\t\t}\n\n\t\t// Cache checksum.\n\t\tchksum := h.Sum()\n\t\tf.checksums[h.blockID] = chksum\n\n\t\t// Append block.\n\t\ta = append(a, FragmentBlock{\n\t\t\tID: h.blockID,\n\t\t\tChecksum: chksum,\n\t\t})\n\n\t\t// Exit if we're at the end.\n\t\tif eof {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn a\n}", "func Blocks(offset, count uint) ([]BlockItem, error) {\n\tjsonBlocks := []struct {\n\t\tNumber uint `json:\"number\"`\n\t\tHash string `json:\"hash\"`\n\t\tDate Time `json:\"date\"`\n\t\tDifficulty uint64 `json:\"difficulty\"`\n\t\tMiner string `json:\"miner\"`\n\t}{}\n\tif err := fetch(&jsonBlocks, blockEndpoint, offset, count); err != nil {\n\t\treturn nil, err\n\t}\n\tblocks := make([]BlockItem, len(jsonBlocks))\n\tfor i, b := range jsonBlocks {\n\t\tblocks[i] = BlockItem(b)\n\t}\n\treturn blocks, nil\n}", "func (bfx *bloomfilterIndexer) RangeBloomFilterBlocks() uint64 {\n\tbfx.mutex.RLock()\n\tdefer bfx.mutex.RUnlock()\n\treturn bfx.rangeSize\n}", "func netBlockReceived(conn *OneConnection, b []byte) {\r\n\tif len(b) < 100 {\r\n\t\tconn.DoS(\"ShortBlock\")\r\n\t\treturn\r\n\t}\r\n\r\n\thash := btc.NewSha2Hash(b[:80])\r\n\tidx := hash.BIdx()\r\n\t//println(\"got block data\", hash.String())\r\n\r\n\tMutexRcv.Lock()\r\n\r\n\t// the blocks seems to be fine\r\n\tif rb, got := ReceivedBlocks[idx]; got {\r\n\t\trb.Cnt++\r\n\t\tcommon.CountSafe(\"BlockSameRcvd\")\r\n\t\tconn.Mutex.Lock()\r\n\t\tdelete(conn.GetBlockInProgress, idx)\r\n\t\tconn.Mutex.Unlock()\r\n\t\tMutexRcv.Unlock()\r\n\t\treturn\r\n\t}\r\n\r\n\t// remove from BlocksToGet:\r\n\tb2g := BlocksToGet[idx]\r\n\tif b2g == nil {\r\n\t\t//println(\"Block\", hash.String(), \" from\", conn.PeerAddr.Ip(), conn.Node.Agent, \" was not expected\")\r\n\r\n\t\tvar hdr [81]byte\r\n\t\tvar sta int\r\n\t\tcopy(hdr[:80], b[:80])\r\n\t\tsta, b2g = conn.ProcessNewHeader(hdr[:])\r\n\t\tif b2g == nil {\r\n\t\t\tif sta == PH_STATUS_FATAL {\r\n\t\t\t\tprintln(\"Unrequested Block: FAIL - Ban\", conn.PeerAddr.Ip(), conn.Node.Agent)\r\n\t\t\t\tconn.DoS(\"BadUnreqBlock\")\r\n\t\t\t} else {\r\n\t\t\t\tcommon.CountSafe(\"ErrUnreqBlock\")\r\n\t\t\t}\r\n\t\t\t//conn.Disconnect()\r\n\t\t\tMutexRcv.Unlock()\r\n\t\t\treturn\r\n\t\t}\r\n\t\tif sta == PH_STATUS_NEW {\r\n\t\t\tb2g.SendInvs = true\r\n\t\t}\r\n\t\t//println(c.ConnID, \" - taking this new block\")\r\n\t\tcommon.CountSafe(\"UnxpectedBlockNEW\")\r\n\t}\r\n\r\n\t//println(\"block\", b2g.BlockTreeNode.Height,\" len\", len(b), \" got from\", conn.PeerAddr.Ip(), b2g.InProgress)\r\n\tb2g.Block.Raw = b\r\n\tif conn.X.Authorized {\r\n\t\tb2g.Block.Trusted = true\r\n\t}\r\n\r\n\ter := common.BlockChain.PostCheckBlock(b2g.Block)\r\n\tif er != nil {\r\n\t\tb2g.InProgress--\r\n\t\tprintln(\"Corrupt block received from\", conn.PeerAddr.Ip(), er.Error())\r\n\t\t//ioutil.WriteFile(hash.String() + \".bin\", b, 0700)\r\n\t\tconn.DoS(\"BadBlock\")\r\n\r\n\t\t// we don't need to remove from conn.GetBlockInProgress as we're disconnecting\r\n\r\n\t\tif b2g.Block.MerkleRootMatch() {\r\n\t\t\tprintln(\"It was a wrongly mined one - clean it up\")\r\n\t\t\tDelB2G(idx) //remove it from BlocksToGet\r\n\t\t\tif b2g.BlockTreeNode == LastCommitedHeader {\r\n\t\t\t\tLastCommitedHeader = LastCommitedHeader.Parent\r\n\t\t\t}\r\n\t\t\tcommon.BlockChain.DeleteBranch(b2g.BlockTreeNode, delB2G_callback)\r\n\t\t}\r\n\r\n\t\tMutexRcv.Unlock()\r\n\t\treturn\r\n\t}\r\n\r\n\torb := &OneReceivedBlock{TmStart: b2g.Started, TmPreproc: b2g.TmPreproc,\r\n\t\tTmDownload: conn.LastMsgTime, FromConID: conn.ConnID, DoInvs: b2g.SendInvs}\r\n\r\n\tconn.Mutex.Lock()\r\n\tbip := conn.GetBlockInProgress[idx]\r\n\tif bip == nil {\r\n\t\t//println(conn.ConnID, \"received unrequested block\", hash.String())\r\n\t\tcommon.CountSafe(\"UnreqBlockRcvd\")\r\n\t\tconn.counters[\"NewBlock!\"]++\r\n\t\torb.TxMissing = -2\r\n\t} else {\r\n\t\tdelete(conn.GetBlockInProgress, idx)\r\n\t\tconn.counters[\"NewBlock\"]++\r\n\t\torb.TxMissing = -1\r\n\t}\r\n\tconn.blocksreceived = append(conn.blocksreceived, time.Now())\r\n\tconn.Mutex.Unlock()\r\n\r\n\tReceivedBlocks[idx] = orb\r\n\tDelB2G(idx) //remove it from BlocksToGet if no more pending downloads\r\n\r\n\tstore_on_disk := len(BlocksToGet) > 10 && common.GetBool(&common.CFG.Memory.CacheOnDisk) && len(b2g.Block.Raw) > 16*1024\r\n\tMutexRcv.Unlock()\r\n\r\n\tvar bei *btc.BlockExtraInfo\r\n\r\n\tif store_on_disk {\r\n\t\tif e := ioutil.WriteFile(common.TempBlocksDir()+hash.String(), b2g.Block.Raw, 0600); e == nil {\r\n\t\t\tbei = new(btc.BlockExtraInfo)\r\n\t\t\t*bei = b2g.Block.BlockExtraInfo\r\n\t\t\tb2g.Block = nil\r\n\t\t} else {\r\n\t\t\tprintln(\"write tmp block:\", e.Error())\r\n\t\t}\r\n\t}\r\n\r\n\tNetBlocks <- &BlockRcvd{Conn: conn, Block: b2g.Block, BlockTreeNode: b2g.BlockTreeNode, OneReceivedBlock: orb, BlockExtraInfo: bei}\r\n}", "func Blocks(mods ...qm.QueryMod) blockQuery {\n\tmods = append(mods, qm.From(\"\\\"block\\\"\"))\n\treturn blockQuery{NewQuery(mods...)}\n}", "func (w *Wallet) ListSinceBlock(start, end, syncHeight int32) ([]btcjson.ListTransactionsResult, er.R) {\n\ttxList := []btcjson.ListTransactionsResult{}\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\ttxmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)\n\n\t\trangeFn := func(details []wtxmgr.TxDetails) (bool, er.R) {\n\t\t\tfor _, detail := range details {\n\t\t\t\tjsonResults := listTransactions(tx, &detail,\n\t\t\t\t\tw.Manager, syncHeight, w.chainParams)\n\t\t\t\ttxList = append(txList, jsonResults...)\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn w.TxStore.RangeTransactions(txmgrNs, start, end, rangeFn)\n\t})\n\treturn txList, err\n}", "func (cs *ConsensusSet) managedAcceptBlocks(blocks []types.Block) (blockchainExtended bool, err error) {\n\t// Grab a lock on the consensus set.\n\tcs.mu.Lock()\n\tdefer cs.mu.Unlock()\n\n\t// Make sure that blocks are consecutive. Though this isn't a strict\n\t// requirement, if blocks are not consecutive then it becomes a lot harder\n\t// to maintain correctness when adding multiple blocks in a single tx.\n\t//\n\t// This is the first time that IDs on the blocks have been computed.\n\tblockIDs := make([]types.BlockID, 0, len(blocks))\n\tfor i := 0; i < len(blocks); i++ {\n\t\tblockIDs = append(blockIDs, blocks[i].ID())\n\t\tif i > 0 && blocks[i].ParentID != blockIDs[i-1] {\n\t\t\treturn false, errNonLinearChain\n\t\t}\n\t}\n\n\t// Verify the headers for every block, throw out known blocks, and the\n\t// invalid blocks (which includes the children of invalid blocks).\n\tchainExtended := false\n\tchanges := make([]changeEntry, 0, len(blocks))\n\tsetErr := cs.db.Update(func(tx *bolt.Tx) error {\n\t\tfor i := 0; i < len(blocks); i++ {\n\t\t\t// Start by checking the header of the block.\n\t\t\tparent, err := cs.validateHeaderAndBlock(boltTxWrapper{tx}, blocks[i], blockIDs[i])\n\t\t\tif err == modules.ErrBlockKnown {\n\t\t\t\t// Skip over known blocks.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err == errFutureTimestamp {\n\t\t\t\t// Queue the block to be tried again if it is a future block.\n\t\t\t\tgo cs.threadedSleepOnFutureBlock(blocks[i])\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// log.Printf(\"\\n\\nmanagedAcceptBlocks: %d %s\", parent.Height+1, blocks[i].ID())\n\n\t\t\t// Try adding the block to consensus.\n\t\t\tchangeEntry, err := cs.addBlockToTree(tx, blocks[i], parent)\n\t\t\tif err == nil {\n\t\t\t\tchanges = append(changes, changeEntry)\n\t\t\t\tchainExtended = true\n\t\t\t\tvar applied, reverted []string\n\t\t\t\tfor _, b := range changeEntry.AppliedBlocks {\n\t\t\t\t\tapplied = append(applied, b.String()[:6])\n\t\t\t\t}\n\t\t\t\tfor _, b := range changeEntry.RevertedBlocks {\n\t\t\t\t\treverted = append(reverted, b.String()[:6])\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err == modules.ErrNonExtendingBlock {\n\t\t\t\terr = nil\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// Sanity check - we should never apply fewer blocks than we revert.\n\t\t\tif len(changeEntry.AppliedBlocks) < len(changeEntry.RevertedBlocks) {\n\t\t\t\terr := errors.New(\"after adding a change entry, there are more reverted blocks than applied ones\")\n\t\t\t\tcs.log.Severe(err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif _, ok := setErr.(bolt.MmapError); ok {\n\t\tcs.log.Println(\"ERROR: Bolt mmap failed:\", setErr)\n\t\tfmt.Println(\"Blockchain database has run out of disk space!\")\n\t\tos.Exit(1)\n\t}\n\tif setErr != nil {\n\t\tif len(changes) == 0 {\n\t\t\tcs.log.Println(\"Consensus received an invalid block:\", setErr)\n\t\t} else {\n\t\t\tfmt.Println(\"Received a partially valid block set.\")\n\t\t\tcs.log.Println(\"Consensus received a chain of blocks, where one was valid, but others were not:\", setErr)\n\t\t}\n\t\treturn false, setErr\n\t}\n\t// Stop here if the blocks did not extend the longest blockchain.\n\tif !chainExtended {\n\t\treturn false, modules.ErrNonExtendingBlock\n\t}\n\t// Send any changes to subscribers.\n\tfor i := 0; i < len(changes); i++ {\n\t\tcs.updateSubscribers(changes[i])\n\t}\n\treturn chainExtended, nil\n}", "func (bc *Blockchain) GetBlocks(offset uint32, limit uint32) ([]*block.Block, error) {\n\tblks, err := bc.r.Block.GetByRange(offset, limit)\n\tif err != nil {\n\t\tif err == repository.ErrNotFound {\n\t\t\treturn make([]*block.Block, 0), err\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn blks, nil\n}", "func (b *blocksProviderImpl) DeliverBlocks() {\n\terrorStatusCounter := 0\n\tvar statusCounter uint64 = 0\n\tvar verErrCounter uint64 = 0\n\tvar delay time.Duration\n\n\tdefer b.client.CloseSend()\n\tfor !b.isDone() {\n\t\tmsg, err := b.client.Recv()\n\t\tif err != nil {\n\t\t\tlogger.Warningf(\"[%s] Receive error: %s\", b.chainID, err.Error())\n\t\t\treturn\n\t\t}\n\t\tswitch t := msg.Type.(type) {\n\t\tcase *orderer.DeliverResponse_Status:\n\t\t\tverErrCounter = 0\n\n\t\t\tif t.Status == common.Status_SUCCESS {\n\t\t\t\tlogger.Warningf(\"[%s] ERROR! Received success for a seek that should never complete\", b.chainID)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif t.Status == common.Status_BAD_REQUEST || t.Status == common.Status_FORBIDDEN {\n\t\t\t\tlogger.Errorf(\"[%s] Got error %v\", b.chainID, t)\n\t\t\t\terrorStatusCounter++\n\t\t\t\tif errorStatusCounter > b.wrongStatusThreshold {\n\t\t\t\t\tlogger.Criticalf(\"[%s] Wrong statuses threshold passed, stopping block provider\", b.chainID)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terrorStatusCounter = 0\n\t\t\t\tlogger.Warningf(\"[%s] Got error %v\", b.chainID, t)\n\t\t\t}\n\n\t\t\tdelay, statusCounter = computeBackOffDelay(statusCounter)\n\t\t\ttime.Sleep(delay)\n\t\t\tb.client.Disconnect()\n\t\t\tcontinue\n\t\tcase *orderer.DeliverResponse_Block:\n\t\t\terrorStatusCounter = 0\n\t\t\tstatusCounter = 0\n\t\t\tblockNum := t.Block.Header.Number\n\n\t\t\tmarshaledBlock, err := proto.Marshal(t.Block)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(\"[%s] Error serializing block with sequence number %d, due to %s; Disconnecting client from orderer.\", b.chainID, blockNum, err)\n\t\t\t\tdelay, verErrCounter = computeBackOffDelay(verErrCounter)\n\t\t\t\ttime.Sleep(delay)\n\t\t\t\tb.client.Disconnect()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err := b.mcs.VerifyBlock(gossipcommon.ChannelID(b.chainID), blockNum, t.Block); err != nil {\n\t\t\t\tlogger.Errorf(\"[%s] Error verifying block with sequence number %d, due to %s; Disconnecting client from orderer.\", b.chainID, blockNum, err)\n\t\t\t\tdelay, verErrCounter = computeBackOffDelay(verErrCounter)\n\t\t\t\ttime.Sleep(delay)\n\t\t\t\tb.client.Disconnect()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tverErrCounter = 0 // On a good block\n\n\t\t\tnumberOfPeers := len(b.gossip.PeersOfChannel(gossipcommon.ChannelID(b.chainID)))\n\t\t\t// Create payload with a block received\n\t\t\tpayload := createPayload(blockNum, marshaledBlock)\n\t\t\t// Use payload to create gossip message\n\t\t\tgossipMsg := createGossipMsg(b.chainID, payload)\n\n\t\t\tlogger.Debugf(\"[%s] Adding payload to local buffer, blockNum = [%d]\", b.chainID, blockNum)\n\t\t\t// Add payload to local state payloads buffer\n\t\t\tif err := b.gossip.AddPayload(b.chainID, payload); err != nil {\n\t\t\t\tlogger.Warningf(\"Block [%d] received from ordering service wasn't added to payload buffer: %v\", blockNum, err)\n\t\t\t}\n\n\t\t\t// Gossip messages with other nodes\n\t\t\tlogger.Debugf(\"[%s] Gossiping block [%d], peers number [%d]\", b.chainID, blockNum, numberOfPeers)\n\t\t\tif !b.isDone() {\n\t\t\t\tb.gossip.Gossip(gossipMsg)\n\t\t\t}\n\n\t\t\tb.client.UpdateReceived(blockNum)\n\n\t\tdefault:\n\t\t\tlogger.Warningf(\"[%s] Received unknown: %v\", b.chainID, t)\n\t\t\treturn\n\t\t}\n\t}\n}", "func findMissingBlocks(nodeNum int, aNode *rpctest.Harness, expectedBlocks map[string]int) (map[string]int, error) {\n\tmissing := make(map[string]int)\n\n\ttips, err := aNode.Node.GetDAGTips()\n\tif err != nil {\n\t\treturn missing, err\n\t}\n\n\tfoundBlocks := make(map[string]int)\n\tfor height := int32(0); height <= tips.MaxHeight; height++ {\n\t\thashes, err := aNode.Node.GetBlockHash(int64(height))\n\t\tif err != nil {\n\t\t\treturn missing, err\n\t\t}\n\t\tvar hashStrings []string\n\t\tfor _, h := range hashes {\n\t\t\thashStrings = append(hashStrings, (*h).String())\n\t\t}\n\n\t\tfor _, hash := range hashes {\n\t\t\tfoundBlocks[hash.String()] = 0\n\t\t}\n\t}\n\n\tfor hash, _ := range expectedBlocks {\n\t\t_, ok := foundBlocks[hash]\n\t\tif !ok {\n\t\t\tmissing[hash] = 0\n\t\t}\n\t}\n\n\treturn missing, nil\n}", "func getblockchain() []Block {\n\tIntblock = *new(IntBlock)\n\tallchains(Mainblockchain.Root, 0)\n\tvar bestsofar = 0\n\tvar lastindex = 0\n\tvar node []Block\n\tfor index, c := range Intblock.clist {\n\t\tif bestsofar <= c {\n\t\t\tbestsofar = c\n\t\t\tlastindex = index\n\t\t}\n\t}\n\tfor i := 0; i <= bestsofar; i++ {\n\t\tnode = append([]Block{Intblock.blist[lastindex+i]}, node...)\n\t}\n\treturn node\n}", "func (s *service) MineNewBlock(lastBlock *Block, data []Transaction) (*Block, error) {\n\t// validations\n\tif lastBlock == nil {\n\t\treturn nil, ErrMissingLastBlock\n\t}\n\n\tdifficulty := lastBlock.Difficulty\n\tvar nonce uint32\n\tvar timestamp int64\n\tvar hash string\n\tfor {\n\t\tnonce++\n\t\ttimestamp = time.Now().UnixNano()\n\t\tdifficulty = adjustBlockDifficulty(*lastBlock, timestamp, s.MineRate)\n\t\thash = hashing.SHA256Hash(timestamp, *lastBlock.Hash, data, nonce, difficulty)\n\t\tif hexStringToBinary(hash)[:difficulty] == strings.Repeat(\"0\", int(difficulty)) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn yieldBlock(timestamp, lastBlock.Hash, &hash, data, nonce, difficulty), nil\n}", "func (synckerManager *SynckerManager) GetCrossShardBlocksForShardProducer(toShard byte, limit map[byte][]uint64) map[byte][]interface{} {\n\t//get last confirm crossshard -> process request until retrieve info\n\tres := make(map[byte][]interface{})\n\tbeaconDB := synckerManager.config.Node.GetBeaconChainDatabase()\n\tlastRequestCrossShard := synckerManager.ShardSyncProcess[int(toShard)].Chain.GetCrossShardState()\n\tbc := synckerManager.config.Blockchain\n\tfor i := 0; i < synckerManager.config.Node.GetChainParam().ActiveShards; i++ {\n\t\tfor {\n\t\t\tif i == int(toShard) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t//if limit has 0 length, we should break now\n\t\t\tif limit != nil && len(res[byte(i)]) >= len(limit[byte(i)]) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\trequestHeight := lastRequestCrossShard[byte(i)]\n\t\t\tnextCrossShardInfo := synckerManager.config.Node.FetchNextCrossShard(i, int(toShard), requestHeight)\n\t\t\tif nextCrossShardInfo == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif requestHeight == nextCrossShardInfo.NextCrossShardHeight {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tLogger.Info(\"nextCrossShardInfo.NextCrossShardHeight\", i, toShard, requestHeight, nextCrossShardInfo)\n\n\t\t\tbeaconHash, _ := common.Hash{}.NewHashFromStr(nextCrossShardInfo.ConfirmBeaconHash)\n\t\t\tbeaconBlockBytes, err := rawdbv2.GetBeaconBlockByHash(beaconDB, *beaconHash)\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tbeaconBlock := new(blockchain.BeaconBlock)\n\t\t\tjson.Unmarshal(beaconBlockBytes, beaconBlock)\n\n\t\t\tfor _, shardState := range beaconBlock.Body.ShardState[byte(i)] {\n\t\t\t\tif shardState.Height == nextCrossShardInfo.NextCrossShardHeight {\n\t\t\t\t\tif synckerManager.crossShardPool[int(toShard)].HasHash(shardState.Hash) {\n\t\t\t\t\t\t//validate crossShardBlock before add to result\n\t\t\t\t\t\tblkXShard := synckerManager.crossShardPool[int(toShard)].GetBlock(shardState.Hash)\n\t\t\t\t\t\tbeaconConsensusRootHash, err := bc.GetBeaconConsensusRootHash(bc.GetBeaconBestState(), beaconBlock.GetHeight()-1)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tLogger.Error(\"Cannot get beacon consensus root hash from block \", beaconBlock.GetHeight()-1)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbeaconConsensusStateDB, err := statedb.NewWithPrefixTrie(beaconConsensusRootHash, statedb.NewDatabaseAccessWarper(bc.GetBeaconChainDatabase()))\n\t\t\t\t\t\tcommittee := statedb.GetOneShardCommittee(beaconConsensusStateDB, byte(i))\n\t\t\t\t\t\terr = bc.ShardChain[byte(i)].ValidateBlockSignatures(blkXShard.(common.BlockInterface), committee)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tLogger.Error(\"Validate crossshard block fail\", blkXShard.GetHeight(), blkXShard.Hash())\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//add to result list\n\t\t\t\t\t\tres[byte(i)] = append(res[byte(i)], blkXShard)\n\t\t\t\t\t\t//has block in pool, update request pointer\n\t\t\t\t\t\tlastRequestCrossShard[byte(i)] = nextCrossShardInfo.NextCrossShardHeight\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//cannot append crossshard for a shard (no block in pool, validate error) => break process for this shard\n\t\t\tif requestHeight == lastRequestCrossShard[byte(i)] {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif len(res[byte(i)]) >= MAX_CROSSX_BLOCK {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}", "func Block(b models.Block) *genModels.BlocksRow {\n\tts := b.Timestamp.Unix()\n\n\tgenBlock := genModels.BlocksRow{\n\t\tLevel: b.Level.Ptr(),\n\t\tProto: b.Proto.Ptr(),\n\t\tBlockTime: b.BlockTime,\n\t\tPredecessor: b.Predecessor.Ptr(),\n\t\tTimestamp: &ts,\n\t\tValidationPass: b.ValidationPass.Ptr(),\n\t\tFitness: b.Fitness.Ptr(),\n\t\tContext: b.Context,\n\t\tSignature: b.Signature,\n\t\tProtocol: b.Protocol.Ptr(),\n\t\tPriority: b.Priority.Ptr(),\n\t\tChainID: b.ChainID,\n\t\tHash: b.Hash.Ptr(),\n\t\tReward: &b.Reward,\n\t\tDeposit: b.Deposit,\n\t\tOperationsHash: b.OperationsHash,\n\t\tPeriodKind: b.PeriodKind,\n\t\tCurrentExpectedQuorum: b.CurrentExpectedQuorum,\n\t\tActiveProposal: b.ActiveProposal,\n\t\tBaker: b.Baker,\n\t\tBakerName: b.BakerName,\n\t\tNonceHash: b.NonceHash,\n\t\tConsumedGas: b.ConsumedGas,\n\t\tMetaLevel: b.MetaLevel,\n\t\tMetaLevelPosition: b.MetaLevelPosition,\n\t\tMetaCycle: b.MetaCycle,\n\t\tMetaCyclePosition: b.MetaCyclePosition,\n\t\tMetaVotingPeriod: b.MetaVotingPeriod,\n\t\tMetaVotingPeriodPosition: b.MetaVotingPeriodPosition,\n\t\tExpectedCommitment: b.ExpectedCommitment,\n\t}\n\n\tif b.BlockAggregation != nil {\n\t\tgenBlock.Volume = b.BlockAggregation.Volume\n\t\tgenBlock.Fees = b.BlockAggregation.Fees\n\t\tgenBlock.Endorsements = b.BlockAggregation.Endorsements\n\t\tgenBlock.Proposals = b.BlockAggregation.Proposals\n\t\tgenBlock.SeedNonceRevelations = b.BlockAggregation.SeedNonceRevelations\n\t\tgenBlock.Delegations = b.BlockAggregation.Delegations\n\t\tgenBlock.Transactions = b.BlockAggregation.Transactions\n\t\tgenBlock.ActivateAccounts = b.BlockAggregation.ActivateAccounts\n\t\tgenBlock.Ballots = b.BlockAggregation.Ballots\n\t\tgenBlock.Originations = b.BlockAggregation.Originations\n\t\tgenBlock.Reveals = b.BlockAggregation.Reveals\n\t\tgenBlock.DoubleBakingEvidence = b.BlockAggregation.DoubleBakingEvidences\n\t\tgenBlock.DoubleEndorsementEvidence = b.BlockAggregation.DoubleEndorsementEvidences\n\t\tgenBlock.NumberOfOperations = b.BlockAggregation.NumberOfOperations\n\t}\n\n\treturn &genBlock\n}", "func TestBlock(t *testing.T) {\n\tb := btcutil.NewBlock(&Block100000)\n\n\t// Ensure we get the same data back out.\n\tif msgBlock := b.MsgBlock(); !reflect.DeepEqual(msgBlock, &Block100000) {\n\t\tt.Errorf(\"MsgBlock: mismatched MsgBlock - got %v, want %v\",\n\t\t\tspew.Sdump(msgBlock), spew.Sdump(&Block100000))\n\t}\n\n\t// Ensure block height set and get work properly.\n\twantHeight := int32(100000)\n\tb.SetHeight(wantHeight)\n\tif gotHeight := b.Height(); gotHeight != wantHeight {\n\t\tt.Errorf(\"Height: mismatched height - got %v, want %v\",\n\t\t\tgotHeight, wantHeight)\n\t}\n\n\t// Hash for block 100,000.\n\twantHashStr := \"3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506\"\n\twantHash, err := chainhash.NewHashFromStr(wantHashStr)\n\tif err != nil {\n\t\tt.Errorf(\"NewHashFromStr: %v\", err)\n\t}\n\n\t// Request the hash multiple times to test generation and caching.\n\tfor i := 0; i < 2; i++ {\n\t\thash := b.Hash()\n\t\tif !hash.IsEqual(wantHash) {\n\t\t\tt.Errorf(\"Hash #%d mismatched hash - got %v, want %v\",\n\t\t\t\ti, hash, wantHash)\n\t\t}\n\t}\n\n\t// Hashes for the transactions in Block100000.\n\twantTxHashes := []string{\n\t\t\"8c14f0db3df150123e6f3dbbf30f8b955a8249b62ac1d1ff16284aefa3d06d87\",\n\t\t\"fff2525b8931402dd09222c50775608f75787bd2b87e56995a7bdd30f79702c4\",\n\t\t\"6359f0868171b1d194cbee1af2f16ea598ae8fad666d9b012c8ed2b79a236ec4\",\n\t\t\"e9a66845e05d5abc0ad04ec80f774a7e585c6e8db975962d069a522137b80c1d\",\n\t}\n\n\t// Create a new block to nuke all cached data.\n\tb = btcutil.NewBlock(&Block100000)\n\n\t// Request hash for all transactions one at a time via Tx.\n\tfor i, txHash := range wantTxHashes {\n\t\twantHash, err := chainhash.NewHashFromStr(txHash)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"NewHashFromStr: %v\", err)\n\t\t}\n\n\t\t// Request the hash multiple times to test generation and\n\t\t// caching.\n\t\tfor j := 0; j < 2; j++ {\n\t\t\ttx, err := b.Tx(i)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Tx #%d: %v\", i, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\thash := tx.Hash()\n\t\t\tif !hash.IsEqual(wantHash) {\n\t\t\t\tt.Errorf(\"Hash #%d mismatched hash - got %v, \"+\n\t\t\t\t\t\"want %v\", j, hash, wantHash)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create a new block to nuke all cached data.\n\tb = btcutil.NewBlock(&Block100000)\n\n\t// Request slice of all transactions multiple times to test generation\n\t// and caching.\n\tfor i := 0; i < 2; i++ {\n\t\ttransactions := b.Transactions()\n\n\t\t// Ensure we get the expected number of transactions.\n\t\tif len(transactions) != len(wantTxHashes) {\n\t\t\tt.Errorf(\"Transactions #%d mismatched number of \"+\n\t\t\t\t\"transactions - got %d, want %d\", i,\n\t\t\t\tlen(transactions), len(wantTxHashes))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ensure all of the hashes match.\n\t\tfor j, tx := range transactions {\n\t\t\twantHash, err := chainhash.NewHashFromStr(wantTxHashes[j])\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"NewHashFromStr: %v\", err)\n\t\t\t}\n\n\t\t\thash := tx.Hash()\n\t\t\tif !hash.IsEqual(wantHash) {\n\t\t\t\tt.Errorf(\"Transactions #%d mismatched hashes \"+\n\t\t\t\t\t\"- got %v, want %v\", j, hash, wantHash)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\n\t// Serialize the test block.\n\tvar block100000Buf bytes.Buffer\n\terr = Block100000.Serialize(&block100000Buf)\n\tif err != nil {\n\t\tt.Errorf(\"Serialize: %v\", err)\n\t}\n\tblock100000Bytes := block100000Buf.Bytes()\n\n\t// Request serialized bytes multiple times to test generation and\n\t// caching.\n\tfor i := 0; i < 2; i++ {\n\t\tserializedBytes, err := b.Bytes()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Bytes: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tif !bytes.Equal(serializedBytes, block100000Bytes) {\n\t\t\tt.Errorf(\"Bytes #%d wrong bytes - got %v, want %v\", i,\n\t\t\t\tspew.Sdump(serializedBytes),\n\t\t\t\tspew.Sdump(block100000Bytes))\n\t\t\tcontinue\n\t\t}\n\t}\n\n\t// Transaction offsets and length for the transaction in Block100000.\n\twantTxLocs := []wire.TxLoc{\n\t\t{TxStart: 81, TxLen: 144},\n\t\t{TxStart: 225, TxLen: 259},\n\t\t{TxStart: 484, TxLen: 257},\n\t\t{TxStart: 741, TxLen: 225},\n\t}\n\n\t// Ensure the transaction location information is accurate.\n\ttxLocs, err := b.TxLoc()\n\tif err != nil {\n\t\tt.Errorf(\"TxLoc: %v\", err)\n\t\treturn\n\t}\n\tif !reflect.DeepEqual(txLocs, wantTxLocs) {\n\t\tt.Errorf(\"TxLoc: mismatched transaction location information \"+\n\t\t\t\"- got %v, want %v\", spew.Sdump(txLocs),\n\t\t\tspew.Sdump(wantTxLocs))\n\t}\n}", "func loadBlocks(t *testing.T, dataFile string, network wire.BitcoinNet) (\n\t[]*btcutil.Block, error) {\n\t// Open the file that contains the blocks for reading.\n\tfi, err := os.Open(dataFile)\n\tif err != nil {\n\t\tt.Errorf(\"failed to open file %v, err %v\", dataFile, err)\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif err := fi.Close(); err != nil {\n\t\t\tt.Errorf(\"failed to close file %v %v\", dataFile,\n\t\t\t\terr)\n\t\t}\n\t}()\n\tdr := bzip2.NewReader(fi)\n\n\t// Set the first block as the genesis block.\n\tblocks := make([]*btcutil.Block, 0, 256)\n\tgenesis := btcutil.NewBlock(chaincfg.MainNetParams.GenesisBlock)\n\tblocks = append(blocks, genesis)\n\n\t// Load the remaining blocks.\n\tfor height := 1; ; height++ {\n\t\tvar net uint32\n\t\terr := binary.Read(dr, binary.LittleEndian, &net)\n\t\tif err == io.EOF {\n\t\t\t// Hit end of file at the expected offset. No error.\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to load network type for block %d: %v\",\n\t\t\t\theight, err)\n\t\t\treturn nil, err\n\t\t}\n\t\tif net != uint32(network) {\n\t\t\tt.Errorf(\"Block doesn't match network: %v expects %v\",\n\t\t\t\tnet, network)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar blockLen uint32\n\t\terr = binary.Read(dr, binary.LittleEndian, &blockLen)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to load block size for block %d: %v\",\n\t\t\t\theight, err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Read the block.\n\t\tblockBytes := make([]byte, blockLen)\n\t\t_, err = io.ReadFull(dr, blockBytes)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to load block %d: %v\", height, err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Deserialize and store the block.\n\t\tblock, err := btcutil.NewBlockFromBytes(blockBytes)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to parse block %v: %v\", height, err)\n\t\t\treturn nil, err\n\t\t}\n\t\tblocks = append(blocks, block)\n\t}\n\n\treturn blocks, nil\n}", "func (f *Builder) GetBlocks(ctx context.Context, cids []cid.Cid) ([]*types.Block, error) {\n\tvar ret []*types.Block\n\tfor _, c := range cids {\n\t\tif block, ok := f.blocks[c]; ok {\n\t\t\tret = append(ret, block)\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"no block %s\", c)\n\t\t}\n\t}\n\treturn ret, nil\n}", "func (s *Store) rangeBlockTransactions(ns walletdb.ReadBucket, begin, end int32,\n\tf func([]TxDetails) (bool, error)) (bool, error) {\n\n\t// Mempool height is considered a high bound.\n\tif begin < 0 {\n\t\tbegin = int32(^uint32(0) >> 1)\n\t}\n\tif end < 0 {\n\t\tend = int32(^uint32(0) >> 1)\n\t}\n\n\tvar blockIter blockIterator\n\tvar advance func(*blockIterator) bool\n\tif begin < end {\n\t\t// Iterate in forwards order\n\t\tblockIter = makeReadBlockIterator(ns, begin)\n\t\tadvance = func(it *blockIterator) bool {\n\t\t\tif !it.next() {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn it.elem.Height <= end\n\t\t}\n\t} else {\n\t\t// Iterate in backwards order, from begin -> end.\n\t\tblockIter = makeReadBlockIterator(ns, begin)\n\t\tadvance = func(it *blockIterator) bool {\n\t\t\tif !it.prev() {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn end <= it.elem.Height\n\t\t}\n\t}\n\n\tvar details []TxDetails\n\tfor advance(&blockIter) {\n\t\tblock := &blockIter.elem\n\n\t\tif cap(details) < len(block.transactions) {\n\t\t\tdetails = make([]TxDetails, 0, len(block.transactions))\n\t\t} else {\n\t\t\tdetails = details[:0]\n\t\t}\n\n\t\tfor _, txHash := range block.transactions {\n\t\t\tk := keyTxRecord(&txHash, &block.Block)\n\t\t\tv := existsRawTxRecord(ns, k)\n\t\t\tif v == nil {\n\t\t\t\tstr := fmt.Sprintf(\"missing transaction %v for \"+\n\t\t\t\t\t\"block %v\", txHash, block.Height)\n\t\t\t\treturn false, storeError(ErrData, str, nil)\n\t\t\t}\n\n\t\t\tdetail, err := s.minedTxDetails(ns, &txHash, k, v)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\tdetails = append(details, *detail)\n\t\t}\n\n\t\t// Every block record must have at least one transaction, so it\n\t\t// is safe to call f.\n\t\tbrk, err := f(details)\n\t\tif err != nil || brk {\n\t\t\treturn brk, err\n\t\t}\n\t}\n\treturn false, blockIter.err\n}", "func NewBlock(chain uint64, producer Address) *StBlock {\n\tvar hashPowerLimit uint64\n\tvar blockInterval uint64\n\tvar pStat BaseInfo\n\tout := new(StBlock)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatHashPower}, &hashPowerLimit)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBlockInterval}, &blockInterval)\n\n\tif pStat.ID == 0 {\n\t\tlog.Println(\"fail to get the last block. chain:\", chain)\n\t\treturn nil\n\t}\n\n\thashPowerLimit = hashPowerLimit / 1000\n\tif hashPowerLimit < minHPLimit {\n\t\thashPowerLimit = minHPLimit\n\t}\n\n\tout.HashpowerLimit = hashPowerLimit\n\n\tif pStat.ID == 1 && chain > 1 {\n\t\tpStat.Time = pStat.Time + blockSyncMax + blockSyncMin + TimeSecond\n\t} else {\n\t\tpStat.Time += blockInterval\n\t}\n\n\tout.Previous = pStat.Key\n\tout.Producer = producer\n\tout.Time = pStat.Time\n\n\tout.Chain = chain\n\tout.Index = pStat.ID + 1\n\n\tif pStat.Chain > 1 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID+1), &key)\n\t\tgetDataFormLog(chain/2, logBlockInfo{}, key[:], &tmp)\n\t\tif out.Index != 2 && !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID+2), &key2)\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.Parent = key2\n\t\t\t} else {\n\t\t\t\tout.Parent = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else {\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID), &key)\n\t\t\tout.Parent = key\n\t\t}\n\t}\n\tif pStat.LeftChildID > 0 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID+1), &key)\n\t\tgetDataFormLog(2*chain, logBlockInfo{}, key[:], &tmp)\n\t\tif !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID+2), &key2)\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.LeftChild = key2\n\t\t\t} else {\n\t\t\t\tout.LeftChild = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else if pStat.LeftChildID == 1 {\n\t\t\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID), &key)\n\t\t\tout.LeftChild = key\n\t\t} else {\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID), &key)\n\t\t\tout.LeftChild = key\n\t\t}\n\t}\n\tif pStat.RightChildID > 0 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID+1), &key)\n\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, key[:], &tmp)\n\t\tif !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID+2), &key2)\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.RightChild = key2\n\t\t\t} else {\n\t\t\t\tout.RightChild = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else if pStat.RightChildID == 1 {\n\t\t\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(pStat.RightChildID), &key)\n\t\t\tout.RightChild = key\n\t\t} else {\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID), &key)\n\t\t\tout.RightChild = key\n\t\t}\n\t}\n\n\treturn out\n}", "func (s *stateMemory) GetMemoryBlocks(podUID string, containerName string) []Block {\n\ts.RLock()\n\tdefer s.RUnlock()\n\n\tif res, ok := s.assignments[podUID][containerName]; ok {\n\t\treturn append([]Block{}, res...)\n\t}\n\treturn nil\n}", "func (b *Bitcoin) ConfirmationBlock() uint64 {\n\treturn b.confirmationBlock\n}", "func (am *AccountManager) ListSinceBlock(since, curBlockHeight int32,\n\tminconf int) ([]btcjson.ListTransactionsResult, error) {\n\n\t// Create and fill a map of account names and their balances.\n\tvar txList []btcjson.ListTransactionsResult\n\tfor _, a := range am.AllAccounts() {\n\t\ttxTmp, err := a.ListSinceBlock(since, curBlockHeight, minconf)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttxList = append(txList, txTmp...)\n\t}\n\treturn txList, nil\n}", "func (ts *Tipset) Block(miner Miner, winCount int64, msgs ...*ApplicableMessage) {\n\tblock := Block{\n\t\tMinerAddr: miner.MinerActorAddr.ID,\n\t\tWinCount: winCount,\n\t}\n\tfor _, am := range msgs {\n\t\tblock.Messages = append(block.Messages, MustSerialize(am.Message))\n\n\t\t// if we see this message for the first time, add it to the `msgIdx` map and to the `orderMsgs` slice.\n\t\tif _, ok := ts.tss.msgIdx[am.Message.Cid()]; !ok {\n\t\t\tts.tss.msgIdx[am.Message.Cid()] = am\n\t\t\tts.tss.orderedMsgs = append(ts.tss.orderedMsgs, am)\n\t\t}\n\t}\n\n\tts.Blocks = append(ts.Blocks, block)\n}", "func (gw *Gateway) GetBlocksInRangeVerbose(start, end uint64) ([]coin.SignedBlock, [][][]visor.TransactionInput, error) {\n\tvar blocks []coin.SignedBlock\n\tvar inputs [][][]visor.TransactionInput\n\tvar err error\n\tgw.strand(\"GetBlocksInRangeVerbose\", func() {\n\t\tblocks, inputs, err = gw.v.GetBlocksInRangeVerbose(start, end)\n\t})\n\treturn blocks, inputs, err\n}", "func (blockchain *Blockchain) MineNewBlock(originalTxs []*Transaction) *Block {\n\t// Reward of mining a block\n\tcoinBaseTransaction := NewRewardTransacion()\n\ttxs := []*Transaction{coinBaseTransaction}\n\ttxs = append(txs, originalTxs...)\n\t// Verify transactions\n\tfor _, tx := range txs {\n\t\tif !tx.IsCoinBaseTransaction() {\n\t\t\tif blockchain.VerifityTransaction(tx, txs) == false {\n\t\t\t\tlog.Panic(\"Verify transaction failed...\")\n\t\t\t}\n\t\t}\n\t}\n\n\tDBName := fmt.Sprintf(DBName, os.Getenv(\"NODE_ID\"))\n\tdb, err := bolt.Open(DBName, 0600, nil)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tdefer db.Close()\n\t// Get the latest block\n\tvar block Block\n\terr = db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(BlockBucketName))\n\t\tif b != nil {\n\t\t\thash := b.Get([]byte(\"l\"))\n\t\t\tblockBytes := b.Get(hash)\n\t\t\tgobDecode(blockBytes, &block)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\t// Mine a new block\n\tnewBlock := NewBlock(txs, block.Height+1, block.BlockHash)\n\n\treturn newBlock\n}", "func (a *IqnpoolApiService) GetIqnpoolBlockList(ctx context.Context) ApiGetIqnpoolBlockListRequest {\n\treturn ApiGetIqnpoolBlockListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (ns *EsIndexer) IndexBlocksInRange(fromBlockHeight uint64, toBlockHeight uint64) {\n\tctx := context.Background()\n\tchannel := make(chan EsType, 1000)\n\tdone := make(chan struct{})\n\ttxChannel := make(chan EsType, 20000)\n\tnameChannel := make(chan EsType, 5000)\n\tgenerator := func() error {\n\t\tdefer close(channel)\n\t\tdefer close(done)\n\t\tns.log.Info().Msg(fmt.Sprintf(\"Indexing %d missing blocks [%d..%d]\", (1 + toBlockHeight - fromBlockHeight), fromBlockHeight, toBlockHeight))\n\t\tfor blockHeight := fromBlockHeight; blockHeight <= toBlockHeight; blockHeight++ {\n\t\t\tblockQuery := make([]byte, 8)\n\t\t\tbinary.LittleEndian.PutUint64(blockQuery, uint64(blockHeight))\n\t\t\tblock, err := ns.grpcClient.GetBlock(context.Background(), &types.SingleBytes{Value: blockQuery})\n\t\t\tif err != nil {\n\t\t\t\tns.log.Warn().Uint64(\"blockHeight\", blockHeight).Err(err).Msg(\"Failed to get block\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(block.Body.Txs) > 0 {\n\t\t\t\tns.IndexTxs(block, block.Body.Txs, txChannel, nameChannel)\n\t\t\t}\n\t\t\td := ConvBlock(block)\n\t\t\tselect {\n\t\t\tcase channel <- d:\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\twaitForTx := func() error {\n\t\tdefer close(txChannel)\n\t\t<-done\n\t\treturn nil\n\t}\n\tgo BulkIndexer(ctx, ns.log, ns.client, txChannel, waitForTx, ns.indexNamePrefix+\"tx\", \"tx\", 10000, false)\n\n\twaitForNames := func() error {\n\t\tdefer close(nameChannel)\n\t\t<-done\n\t\treturn nil\n\t}\n\tgo BulkIndexer(ctx, ns.log, ns.client, nameChannel, waitForNames, ns.indexNamePrefix+\"name\", \"name\", 2500, true)\n\n\tBulkIndexer(ctx, ns.log, ns.client, channel, generator, ns.indexNamePrefix+\"block\", \"block\", 500, false)\n\n\tns.OnSyncComplete()\n}", "func (lc *LedgerCommitter) GetBlocks(blockSeqs []uint64) []*common.Block {\n\tvar blocks []*common.Block\n\n\tfor _, seqNum := range blockSeqs {\n\t\tif blck, err := lc.GetBlockByNumber(seqNum); err != nil {\n\t\t\tlogger.Errorf(\"Not able to acquire block num %d, from the ledger skipping...\", seqNum)\n\t\t\tcontinue\n\t\t} else {\n\t\t\tlogger.Debug(\"Appending next block with seqNum = \", seqNum, \" to the resulting set\")\n\t\t\tblocks = append(blocks, blck)\n\t\t}\n\t}\n\n\treturn blocks\n}", "func (env *Env) CheckBlock(pdu *libcoap.Pdu) (bool, *string, *libcoap.Block) {\n blockValue, err := pdu.GetOptionIntegerValue(libcoap.OptionBlock2)\n if err != nil {\n log.WithError(err).Warn(\"Get block2 option value failed.\")\n return false, nil, nil\n\t}\n block := libcoap.IntToBlock(int(blockValue))\n\n size2Value, err := pdu.GetOptionIntegerValue(libcoap.OptionSize2)\n\tif err != nil {\n\t\tlog.WithError(err).Warn(\"Get size 2 option value failed.\")\n return false, nil, nil\n }\n\n eTag := pdu.GetOptionOpaqueValue(libcoap.OptionEtag)\n\n if block != nil {\n isMoreBlock := true\n blockKey := eTag + string(pdu.Token)\n // If block.M = 1, block is more block. If block.M = 0, block is last block\n if block.M == libcoap.MORE_BLOCK {\n log.Debugf(\"Response block is comming (eTag=%+v, block=%+v, size2=%+v) for request (token=%+v), waiting for the next block.\", eTag, block.ToString(), size2Value, pdu.Token)\n if block.NUM == 0 {\n env.responseBlocks[blockKey] = pdu\n initialBlockSize := env.InitialRequestBlockSize()\n secondBlockSize := env.SecondRequestBlockSize()\n // Check what block_size is used for block2 option\n // If the initialBlockSize is set: client will always request with block2 option\n // If the initialBlockSize is not set and the secondBlockSize is set: if the secondBlockSize is greater than the\n // recommended block size -> use the recommended block size, reversely, use the configured block size\n // If both initialBlockSize and secondBlockSize are not set -> use the recommended block size\n if initialBlockSize == nil && secondBlockSize != nil {\n if *secondBlockSize > block.SZX {\n log.Warn(\"Second block size must not greater thans block size received from server\")\n block.NUM += 1\n } else {\n block.NUM = 1 << uint(block.SZX - *secondBlockSize)\n block.SZX = *secondBlockSize\n }\n } else {\n block.NUM += 1\n }\n } else {\n if data, ok := env.responseBlocks[blockKey]; ok {\n env.responseBlocks[blockKey].Data = append(data.Data, pdu.Data...)\n block.NUM += 1\n } else {\n log.Warnf(\"The block version is not unknown. Re-request from the first block\")\n delete(env.responseBlocks, blockKey)\n block.NUM = 0\n }\n }\n block.M = 0\n return isMoreBlock, &eTag, block\n } else if block.M == libcoap.LAST_BLOCK {\n log.Debugf(\"Response block is comming (eTag=%+v, block=%+v, size2=%+v), this is the last block.\", eTag, block.ToString(), size2Value)\n isMoreBlock = false\n if data, ok := env.responseBlocks[blockKey]; ok {\n env.responseBlocks[blockKey].Data = append(data.Data, pdu.Data...)\n } else if block.NUM > 0 {\n log.Warnf(\"The block version is not unknown. Re-request from the first block\")\n delete(env.responseBlocks, blockKey)\n block.NUM = 0\n isMoreBlock = true\n }\n return isMoreBlock, &eTag, block\n }\n }\n return false, nil, nil\n}", "func AskForBlock(height int32, hash string) {\n\t//TODO -> TEST: Update this function to recursively ask\n\t// for all the missing predesessor blocks instead of only the parent block.\n\tPeers.Rebalance()\n\n\tfor key, _ := range Peers.Copy() {\n\t\tresp, err := http.Get(key + \"/block/\" + string(height) + \"/\" + hash)\n\t\tif err != nil {\n\t\t\tprintln(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif resp.StatusCode == 200 {\n\t\t\trespData, erro := ioutil.ReadAll(resp.Body)\n\t\t\tif erro != nil {\n\t\t\t\tprintln(err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\trespBlc := p2.Block{}\n\t\t\trespBlc.DecodeFromJson(string(respData))\n\t\t\tif !SBC.CheckParentHash(respBlc) {\n\t\t\t\tAskForBlock(respBlc.GetHeight()-1, respBlc.GetParentHash())\n\t\t\t}\n\t\t\tSBC.Insert(respBlc)\n\t\t\tbreak\n\t\t}\n\t}\n\n}", "func (_Rootchain *RootchainSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _Rootchain.Contract.Blocks(&_Rootchain.CallOpts, arg0)\n}", "func MockBlock(txs []*types.Tx) *types.Block {\n\treturn &types.Block{\n\t\tBlockHeader: types.BlockHeader{Timestamp: uint64(time.Now().Nanosecond())},\n\t\tTransactions: txs,\n\t}\n}", "func getBlock(res rpc.GetBlockResponse) (GetBlockResponse, error) {\n\ttxs := make([]GetBlockTransaction, 0, len(res.Result.Transactions))\n\tfor _, rTx := range res.Result.Transactions {\n\t\tdata, ok := rTx.Transaction.([]interface{})\n\t\tif !ok {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to cast raw response to []interface{}\")\n\t\t}\n\t\tif data[1] != string(rpc.GetTransactionConfigEncodingBase64) {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"encoding mistmatch\")\n\t\t}\n\t\trawTx, err := base64.StdEncoding.DecodeString(data[0].(string))\n\t\tif err != nil {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to base64 decode data, err: %v\", err)\n\t\t}\n\t\ttx, err := types.TransactionDeserialize(rawTx)\n\t\tif err != nil {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to deserialize transaction, err: %v\", err)\n\t\t}\n\n\t\tvar transactionMeta *TransactionMeta\n\t\tif rTx.Meta != nil {\n\t\t\tinnerInstructions := make([]TransactionMetaInnerInstruction, 0, len(rTx.Meta.InnerInstructions))\n\t\t\tfor _, metaInnerInstruction := range rTx.Meta.InnerInstructions {\n\t\t\t\tcompiledInstructions := make([]types.CompiledInstruction, 0, len(metaInnerInstruction.Instructions))\n\t\t\t\tfor _, innerInstruction := range metaInnerInstruction.Instructions {\n\t\t\t\t\tdata, err := base58.Decode(innerInstruction.Data)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to base58 decode data, data: %v, err: %v\", innerInstruction.Data, err)\n\t\t\t\t\t}\n\t\t\t\t\tcompiledInstructions = append(compiledInstructions, types.CompiledInstruction{\n\t\t\t\t\t\tProgramIDIndex: innerInstruction.ProgramIDIndex,\n\t\t\t\t\t\tAccounts: innerInstruction.Accounts,\n\t\t\t\t\t\tData: data,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tinnerInstructions = append(innerInstructions, TransactionMetaInnerInstruction{\n\t\t\t\t\tIndex: metaInnerInstruction.Index,\n\t\t\t\t\tInstructions: compiledInstructions,\n\t\t\t\t})\n\t\t\t}\n\t\t\ttransactionMeta = &TransactionMeta{\n\t\t\t\tErr: rTx.Meta.Err,\n\t\t\t\tFee: rTx.Meta.Fee,\n\t\t\t\tPreBalances: rTx.Meta.PreBalances,\n\t\t\t\tPostBalances: rTx.Meta.PostBalances,\n\t\t\t\tPreTokenBalances: rTx.Meta.PreTokenBalances,\n\t\t\t\tPostTokenBalances: rTx.Meta.PostTokenBalances,\n\t\t\t\tLogMessages: rTx.Meta.LogMessages,\n\t\t\t\tInnerInstructions: innerInstructions,\n\t\t\t}\n\t\t}\n\n\t\ttxs = append(txs,\n\t\t\tGetBlockTransaction{\n\t\t\t\tMeta: transactionMeta,\n\t\t\t\tTransaction: tx,\n\t\t\t},\n\t\t)\n\t}\n\treturn GetBlockResponse{\n\t\tBlockhash: res.Result.Blockhash,\n\t\tBlockTime: res.Result.BlockTime,\n\t\tBlockHeight: res.Result.BlockHeight,\n\t\tPreviousBlockhash: res.Result.PreviousBlockhash,\n\t\tParentSLot: res.Result.ParentSLot,\n\t\tRewards: res.Result.Rewards,\n\t\tTransactions: txs,\n\t}, nil\n}", "func Test_ValidateBlockTransactions_IsValid(t *testing.T) {\n\tvar blockTransactionValidator = &BlockTransactionValidator{}\n\t// create inputs transaction\n\tvar blockIndex = 12\n\tvar transactions = []*Transaction{\n\t\t// coinbase transaction\n\t\t{\n\t\t\tID: \"ebafa7518cac709e160f201a888bdf3c969c36993eefbf852cc30c9eb1a553b8\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"\",\n\t\t\t\t\tSignature: \"\",\n\t\t\t\t\tOutputIndex: blockIndex,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: \"coinbase-address\",\n\t\t\t\t\tAmount: CoinbaseAmount,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"3e5d88c061d2b79dd2ac79daf877232203089307d4576b2c1b3851b4920eb952\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"1\",\n\t\t\t\t\tSignature: \"567af38a37a36b25e45a63f477c2b66a8e221a27831dc87624c6ebbe92ff16c5936eb0100490cbbc0b1658a2db4a0190b55c19b6756a9907ec9bddb8dfe0c141a7208fc1be073350e17a0d65aa9511d19e6713b28e37f3c732373d77aeac8e8a3e998721a64e235a7e84e0f16d61a6e556d329988f03f546e9906f7731f1aa78955666a65fa3739ef4198d7af2babe00c0fc268078c3992d1f1d6bed6be34ed3d475bb18437dc2aac31dbd90f891d6a0c9dbeefab6d40dd7b69c1b426eaa482841a637445988518fea20969bfa99312b16a95ba2d155e44d898ca8b8f189941ced763aa111826a45b669ff0f904419e475fce41829f9f2f26b11e9a9fb4f38a10bd12bf5a629c97dda67a61431bd3839a8a28e55646bf864286bc805002164a562b4ccc874dce4b9b9f08b33df5e5063af91d58fa4edd6d5f85d6d8a28c99534881ffaebac09e5990642fa4b14d349c1c4e23d3bd4d600f2e521b803c57c0b3fb820f81d8ba915cea300dc722f4ee1a5d2a339d5a85633151e17cb129ed6b750e69eb9e2f4aa43cefa94adf99675a2b01e0e837a80538e774839f4f27fc30034ae0a2d179da3eb34c1d46ba863f67c2efe4ff2405d89ad4f98acc57e411a3e85e3ba82dbe0e3e3c9a09dd99cfede261271a7cd442db4a34cbdd7fe11f1e3a8564e6e340a0c175e2ee5e950c2503a05caedabcb8c563c1157ed99eb0f2f8b7844\",\n\t\t\t\t\tOutputIndex: 10,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"7ef0ab206de97f0906adbaccb68bdd7039b86893cbeede8ef9311858b8187fdb\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"2\",\n\t\t\t\t\tSignature: \"45b364938dcde0267e019ad19518abd5174659e45341b624174cc6c941a98fd40cb9b230a2dce924f17982403b88d20afd8d7a11e046c6dfa8d2cd2b713232016d95a4c30990fb02f2b6b611311a02c490bb0f0a7e941a26ddc0b41ebb2356c2a250ab1ae34190463a1e63f896eb7a2f20edaffbd5fd715a819b3ba9c36ce3fe4006fc476add623e874cdb880ca9e2962ec369e6b097930652948c4a175231716e24cefec3b90908139dfe1ae29ca469d00bfaa127838c73e135ad5a66a34242d2518fd66a35857d0d1f897b7035862642c0d07c45b9094039dc278572c06045c09acd568dc0adda60e022b591f76061ede28010cbba7f2758e1a1dbc1e374a8266421ad9fb79e2d4532f1466b687ded5c02aeed4020ea23b4c184181453ea111b3b6db6c8e381f1467e56aecc02475463d713fb1300c5c38379763b26c6b87cb0f27b7d3603e83416dae8f2cd06e2c48090c3b08b5cd6525c669f5a730eec9062c6cffb916db2ce90d41b1734b16eb7be54be19910e9f2669e254c880346aec5756ee8e0520e076838414fafb8348ee350258fd18910f4cca3d8630aa621642fc2b437c6d74a151383beb95aacfe3c7fdf31e372c1d9330abb9ba0be27af1ed745735bd8c09bab1fbc3e7f4f1baf070a260bdbe439b119ae09d87a09989f0cdfdc4f99a109b62a2db862d5ded19daf20d28aafb098efdeefedd935053bd0796\",\n\t\t\t\t\tOutputIndex: 20,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 200,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar unspentTransactionOutputs = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"1\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 100,\n\t\t},\n\t\t{\n\t\t\tOutputID: \"2\",\n\t\t\tOutputIndex: 20,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 200,\n\t\t},\n\t}\n\n\t// create coinbase transaction\n\tresult, _ := blockTransactionValidator.ValidateBlockTransactions(transactions, unspentTransactionOutputs, blockIndex)\n\n\t// validate expected\n\tif !result {\n\t\tt.Errorf(\"block transactions are valid so the result should be true\")\n\t}\n}", "func (f *Fetcher) GetBlocks(ctx context.Context, cids []cid.Cid) ([]*types.Block, error) {\n\tvar unsanitized []blocks.Block\n\tfor b := range f.session.GetBlocks(ctx, cids) {\n\t\tunsanitized = append(unsanitized, b)\n\t}\n\n\tif len(unsanitized) < len(cids) {\n\t\tvar err error\n\t\tif ctxErr := ctx.Err(); ctxErr != nil {\n\t\t\terr = errors.Wrap(ctxErr, \"failed to fetch all requested blocks\")\n\t\t} else {\n\t\t\terr = errors.New(\"failed to fetch all requested blocks\")\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tvar blocks []*types.Block\n\tfor _, u := range unsanitized {\n\t\tblock, err := types.DecodeBlock(u.RawData())\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\"fetched data (cid %s) was not a block\", u.Cid().String()))\n\t\t}\n\n\t\t// reject blocks that are syntactically invalid.\n\t\tif err := f.validator.ValidateSyntax(ctx, block); err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tblocks = append(blocks, block)\n\t}\n\treturn blocks, nil\n}", "func (ns *EsIndexer) DeleteBlocksInRange(fromBlockHeight uint64, toBlockHeight uint64) {\n\tctx := context.Background()\n\tns.log.Info().Msg(fmt.Sprintf(\"Rolling back %d blocks [%d..%d]\", (1 + toBlockHeight - fromBlockHeight), fromBlockHeight, toBlockHeight))\n\t// Delete blocks\n\tquery := elastic.NewRangeQuery(\"no\").From(fromBlockHeight).To(toBlockHeight)\n\tres, err := ns.client.DeleteByQuery().Index(ns.indexNamePrefix + \"block\").Query(query).Do(ctx)\n\tif err != nil {\n\t\tns.log.Warn().Err(err).Msg(\"Failed to delete blocks\")\n\t} else {\n\t\tns.log.Info().Int64(\"deleted\", res.Deleted).Msg(\"Deleted blocks\")\n\t}\n\t// Delete tx of blocks\n\tquery = elastic.NewRangeQuery(\"blockno\").From(fromBlockHeight).To(toBlockHeight)\n\tres, err = ns.client.DeleteByQuery().Index(ns.indexNamePrefix + \"tx\").Query(query).Do(ctx)\n\tif err != nil {\n\t\tns.log.Warn().Err(err).Msg(\"Failed to delete tx\")\n\t} else {\n\t\tns.log.Info().Int64(\"deleted\", res.Deleted).Msg(\"Deleted tx\")\n\t}\n\t// Delete invalidated name entries\n\tquery = elastic.NewRangeQuery(\"blockno\").From(fromBlockHeight).To(toBlockHeight)\n\tres, err = ns.client.DeleteByQuery().Index(ns.indexNamePrefix + \"name\").Query(query).Do(ctx)\n\tif err != nil {\n\t\tns.log.Warn().Err(err).Msg(\"Failed to delete names\")\n\t} else {\n\t\tns.log.Info().Int64(\"deleted\", res.Deleted).Msg(\"Deleted names\")\n\t}\n}", "func GetBlockBytes(block *model.Block) ([]byte, error) {\n\tvar rawBlock []byte\n\n\t// convert nounce to bytes\n\tnounceBytes := Int64ToBytes(block.Nounce)\n\trawBlock = append(rawBlock, nounceBytes...)\n\n\t// convert preHash to bytes\n\tpreHashBytes, err := HexToBytes(block.PrevHash)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trawBlock = append(rawBlock, preHashBytes...)\n\n\t// convert transactions to bytes\n\tfor i := 0; i < len(block.Txs); i++ {\n\t\ttx := block.Txs[i]\n\t\ttxBytes, err := GetTransactionBytes(tx, true /*withHash*/)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trawBlock = append(rawBlock, txBytes...)\n\t}\n\n\t// covert coinbase to bytes\n\tcoinbaseBytes, err := GetTransactionBytes(block.Coinbase, true /*withHash*/)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trawBlock = append(rawBlock, coinbaseBytes...)\n\n\treturn rawBlock, nil\n}", "func (syncer *Syncer) ValidateBlock(ctx context.Context, b *types.FullBlock) (err error) {\n\tdefer func() {\n\t\t// b.Cid() could panic for empty blocks that are used in tests.\n\t\tif rerr := recover(); rerr != nil {\n\t\t\terr = xerrors.Errorf(\"validate block panic: %w\", rerr)\n\t\t\treturn\n\t\t}\n\t}()\n\n\tisValidated, err := syncer.store.IsBlockValidated(ctx, b.Cid())\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"check block validation cache %s: %w\", b.Cid(), err)\n\t}\n\n\tif isValidated {\n\t\treturn nil\n\t}\n\n\tvalidationStart := build.Clock.Now()\n\tdefer func() {\n\t\tstats.Record(ctx, metrics.BlockValidationDurationMilliseconds.M(metrics.SinceInMilliseconds(validationStart)))\n\t\tlog.Infow(\"block validation\", \"took\", time.Since(validationStart), \"height\", b.Header.Height, \"age\", time.Since(time.Unix(int64(b.Header.Timestamp), 0)))\n\t}()\n\n\tctx, span := trace.StartSpan(ctx, \"validateBlock\")\n\tdefer span.End()\n\n\tif err := blockSanityChecks(b.Header); err != nil {\n\t\treturn xerrors.Errorf(\"incoming header failed basic sanity checks: %w\", err)\n\t}\n\n\th := b.Header\n\n\tbaseTs, err := syncer.store.LoadTipSet(types.NewTipSetKey(h.Parents...))\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"load parent tipset failed (%s): %w\", h.Parents, err)\n\t}\n\n\tlbts, err := stmgr.GetLookbackTipSetForRound(ctx, syncer.sm, baseTs, h.Height)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"failed to get lookback tipset for block: %w\", err)\n\t}\n\n\tlbst, _, err := syncer.sm.TipSetState(ctx, lbts)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"failed to compute lookback tipset state: %w\", err)\n\t}\n\n\tprevBeacon, err := syncer.store.GetLatestBeaconEntry(baseTs)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"failed to get latest beacon entry: %w\", err)\n\t}\n\n\t// fast checks first\n\tnulls := h.Height - (baseTs.Height() + 1)\n\tif tgtTs := baseTs.MinTimestamp() + build.BlockDelaySecs*uint64(nulls+1); h.Timestamp != tgtTs {\n\t\treturn xerrors.Errorf(\"block has wrong timestamp: %d != %d\", h.Timestamp, tgtTs)\n\t}\n\n\tnow := uint64(build.Clock.Now().Unix())\n\tif h.Timestamp > now+build.AllowableClockDriftSecs {\n\t\treturn xerrors.Errorf(\"block was from the future (now=%d, blk=%d): %w\", now, h.Timestamp, ErrTemporal)\n\t}\n\tif h.Timestamp > now {\n\t\tlog.Warn(\"Got block from the future, but within threshold\", h.Timestamp, build.Clock.Now().Unix())\n\t}\n\n\tmsgsCheck := async.Err(func() error {\n\t\tif err := syncer.checkBlockMessages(ctx, b, baseTs); err != nil {\n\t\t\treturn xerrors.Errorf(\"block had invalid messages: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\tminerCheck := async.Err(func() error {\n\t\tif err := syncer.minerIsValid(ctx, h.Miner, baseTs); err != nil {\n\t\t\treturn xerrors.Errorf(\"minerIsValid failed: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\tbaseFeeCheck := async.Err(func() error {\n\t\tbaseFee, err := syncer.store.ComputeBaseFee(ctx, baseTs)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"computing base fee: %w\", err)\n\t\t}\n\t\tif types.BigCmp(baseFee, b.Header.ParentBaseFee) != 0 {\n\t\t\treturn xerrors.Errorf(\"base fee doesn't match: %s (header) != %s (computed)\",\n\t\t\t\tb.Header.ParentBaseFee, baseFee)\n\t\t}\n\t\treturn nil\n\t})\n\tpweight, err := syncer.store.Weight(ctx, baseTs)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"getting parent weight: %w\", err)\n\t}\n\n\tif types.BigCmp(pweight, b.Header.ParentWeight) != 0 {\n\t\treturn xerrors.Errorf(\"parrent weight different: %s (header) != %s (computed)\",\n\t\t\tb.Header.ParentWeight, pweight)\n\t}\n\n\t// Stuff that needs stateroot / worker address\n\tstateroot, precp, err := syncer.sm.TipSetState(ctx, baseTs)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"get tipsetstate(%d, %s) failed: %w\", h.Height, h.Parents, err)\n\t}\n\n\tif stateroot != h.ParentStateRoot {\n\t\tmsgs, err := syncer.store.MessagesForTipset(baseTs)\n\t\tif err != nil {\n\t\t\tlog.Error(\"failed to load messages for tipset during tipset state mismatch error: \", err)\n\t\t} else {\n\t\t\tlog.Warn(\"Messages for tipset with mismatching state:\")\n\t\t\tfor i, m := range msgs {\n\t\t\t\tmm := m.VMMessage()\n\t\t\t\tlog.Warnf(\"Message[%d]: from=%s to=%s method=%d params=%x\", i, mm.From, mm.To, mm.Method, mm.Params)\n\t\t\t}\n\t\t}\n\n\t\treturn xerrors.Errorf(\"parent state root did not match computed state (%s != %s)\", stateroot, h.ParentStateRoot)\n\t}\n\n\tif precp != h.ParentMessageReceipts {\n\t\treturn xerrors.Errorf(\"parent receipts root did not match computed value (%s != %s)\", precp, h.ParentMessageReceipts)\n\t}\n\n\twaddr, err := stmgr.GetMinerWorkerRaw(ctx, syncer.sm, lbst, h.Miner)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"GetMinerWorkerRaw failed: %w\", err)\n\t}\n\n\twinnerCheck := async.Err(func() error {\n\t\tif h.ElectionProof.WinCount < 1 {\n\t\t\treturn xerrors.Errorf(\"block is not claiming to be a winner\")\n\t\t}\n\n\t\thp, err := stmgr.MinerHasMinPower(ctx, syncer.sm, h.Miner, lbts)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"determining if miner has min power failed: %w\", err)\n\t\t}\n\n\t\tif !hp {\n\t\t\treturn xerrors.New(\"block's miner does not meet minimum power threshold\")\n\t\t}\n\n\t\trBeacon := *prevBeacon\n\t\tif len(h.BeaconEntries) != 0 {\n\t\t\trBeacon = h.BeaconEntries[len(h.BeaconEntries)-1]\n\t\t}\n\t\tbuf := new(bytes.Buffer)\n\t\tif err := h.Miner.MarshalCBOR(buf); err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to marshal miner address to cbor: %w\", err)\n\t\t}\n\n\t\tvrfBase, err := store.DrawRandomness(rBeacon.Data, crypto.DomainSeparationTag_ElectionProofProduction, h.Height, buf.Bytes())\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"could not draw randomness: %w\", err)\n\t\t}\n\n\t\tif err := VerifyElectionPoStVRF(ctx, waddr, vrfBase, h.ElectionProof.VRFProof); err != nil {\n\t\t\treturn xerrors.Errorf(\"validating block election proof failed: %w\", err)\n\t\t}\n\n\t\tslashed, err := stmgr.GetMinerSlashed(ctx, syncer.sm, baseTs, h.Miner)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to check if block miner was slashed: %w\", err)\n\t\t}\n\n\t\tif slashed {\n\t\t\treturn xerrors.Errorf(\"received block was from slashed or invalid miner\")\n\t\t}\n\n\t\tmpow, tpow, _, err := stmgr.GetPowerRaw(ctx, syncer.sm, lbst, h.Miner)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"failed getting power: %w\", err)\n\t\t}\n\n\t\tj := h.ElectionProof.ComputeWinCount(mpow.QualityAdjPower, tpow.QualityAdjPower)\n\t\tif h.ElectionProof.WinCount != j {\n\t\t\treturn xerrors.Errorf(\"miner claims wrong number of wins: miner: %d, computed: %d\", h.ElectionProof.WinCount, j)\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tblockSigCheck := async.Err(func() error {\n\t\tif err := sigs.CheckBlockSignature(ctx, h, waddr); err != nil {\n\t\t\treturn xerrors.Errorf(\"check block signature failed: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\tbeaconValuesCheck := async.Err(func() error {\n\t\tif os.Getenv(\"LOTUS_IGNORE_DRAND\") == \"_yes_\" {\n\t\t\treturn nil\n\t\t}\n\n\t\tif err := beacon.ValidateBlockValues(syncer.beacon, h, baseTs.Height(), *prevBeacon); err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to validate blocks random beacon values: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\ttktsCheck := async.Err(func() error {\n\t\tbuf := new(bytes.Buffer)\n\t\tif err := h.Miner.MarshalCBOR(buf); err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to marshal miner address to cbor: %w\", err)\n\t\t}\n\n\t\tif h.Height > build.UpgradeSmokeHeight {\n\t\t\tbuf.Write(baseTs.MinTicket().VRFProof)\n\t\t}\n\n\t\tbeaconBase := *prevBeacon\n\t\tif len(h.BeaconEntries) != 0 {\n\t\t\tbeaconBase = h.BeaconEntries[len(h.BeaconEntries)-1]\n\t\t}\n\n\t\tvrfBase, err := store.DrawRandomness(beaconBase.Data, crypto.DomainSeparationTag_TicketProduction, h.Height-build.TicketRandomnessLookback, buf.Bytes())\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to compute vrf base for ticket: %w\", err)\n\t\t}\n\n\t\terr = VerifyElectionPoStVRF(ctx, waddr, vrfBase, h.Ticket.VRFProof)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"validating block tickets failed: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\twproofCheck := async.Err(func() error {\n\t\tif err := syncer.VerifyWinningPoStProof(ctx, h, *prevBeacon, lbst, waddr); err != nil {\n\t\t\treturn xerrors.Errorf(\"invalid election post: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\tawait := []async.ErrorFuture{\n\t\tminerCheck,\n\t\ttktsCheck,\n\t\tblockSigCheck,\n\t\tbeaconValuesCheck,\n\t\twproofCheck,\n\t\twinnerCheck,\n\t\tmsgsCheck,\n\t\tbaseFeeCheck,\n\t}\n\n\tvar merr error\n\tfor _, fut := range await {\n\t\tif err := fut.AwaitContext(ctx); err != nil {\n\t\t\tmerr = multierror.Append(merr, err)\n\t\t}\n\t}\n\tif merr != nil {\n\t\tmulErr := merr.(*multierror.Error)\n\t\tmulErr.ErrorFormat = func(es []error) string {\n\t\t\tif len(es) == 1 {\n\t\t\t\treturn fmt.Sprintf(\"1 error occurred:\\n\\t* %+v\\n\\n\", es[0])\n\t\t\t}\n\n\t\t\tpoints := make([]string, len(es))\n\t\t\tfor i, err := range es {\n\t\t\t\tpoints[i] = fmt.Sprintf(\"* %+v\", err)\n\t\t\t}\n\n\t\t\treturn fmt.Sprintf(\n\t\t\t\t\"%d errors occurred:\\n\\t%s\\n\\n\",\n\t\t\t\tlen(es), strings.Join(points, \"\\n\\t\"))\n\t\t}\n\t\treturn mulErr\n\t}\n\n\tif err := syncer.store.MarkBlockAsValidated(ctx, b.Cid()); err != nil {\n\t\treturn xerrors.Errorf(\"caching block validation %s: %w\", b.Cid(), err)\n\t}\n\n\treturn nil\n}", "func (dcr *ExchangeWallet) monitorBlocks(ctx context.Context) {\n\tticker := time.NewTicker(blockTicker)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tdcr.checkForNewBlocks()\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (manager *SyncManager) SyncBlocks(latestHeight int64) error {\n\tmaybeLastIndexedHeight, err := manager.eventHandler.GetLastHandledEventHeight()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error running GetLastIndexedBlockHeight %v\", err)\n\t}\n\n\t// if none of the block has been indexed before, start with 0\n\tcurrentIndexingHeight := int64(0)\n\tif maybeLastIndexedHeight != nil {\n\t\tcurrentIndexingHeight = *maybeLastIndexedHeight + 1\n\t}\n\n\tmanager.logger.Infof(\"going to synchronized blocks from %d to %d\", currentIndexingHeight, latestHeight)\n\tfor currentIndexingHeight < latestHeight {\n\t\tblocksCommands, syncedHeight, err := manager.windowSyncStrategy.Sync(\n\t\t\tcurrentIndexingHeight, latestHeight, manager.syncBlockWorker,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error when synchronizing block with window strategy: %v\", err)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error beginning transaction: %v\", err)\n\t\t}\n\t\tfor i, commands := range blocksCommands {\n\t\t\tblockHeight := currentIndexingHeight + int64(i)\n\n\t\t\tevents := make([]event.Event, 0, len(commands))\n\t\t\tfor _, command := range commands {\n\t\t\t\tevent, err := command.Exec()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"error generating event: %v\", err)\n\t\t\t\t}\n\t\t\t\tevents = append(events, event)\n\t\t\t}\n\n\t\t\terr := manager.eventHandler.HandleEvents(blockHeight, events)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error handling events: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\t// If there is any error before, short-circuit return in the error handling\n\t\t// while the local currentIndexingHeight won't be incremented and will be retried later\n\t\tmanager.logger.Infof(\"successfully synced to block height %d\", syncedHeight)\n\t\tcurrentIndexingHeight = syncedHeight + 1\n\t}\n\treturn nil\n}", "func NewBlock(previousBlock Block, data string) (Block, error) {\n\tvar newBlock Block\n\n\tnewBlock.Index = previousBlock.Index + 1\n\tnewBlock.Timestamp = time.Now().String()\n\tnewBlock.Data = data\n\tnewBlock.PrevHash = previousBlock.Hash\n\tnewBlock.Difficulty = GetDifficulty()\n\n\tif !isCandidateBlockValid(newBlock, previousBlock) {\n\t\treturn newBlock, errors.New(\"Candidate block is not valid\")\n\t}\n\n\tmineBlock(&newBlock)\n\n\treturn newBlock, nil\n}", "func (l *Ledger) FindUndoAndTodoBlocks(curBlockid []byte, destBlockid []byte) ([]*pb.InternalBlock, []*pb.InternalBlock, error) {\n\tl.mutex.RLock()\n\tdefer l.mutex.RUnlock()\n\tundoBlocks := []*pb.InternalBlock{}\n\ttodoBlocks := []*pb.InternalBlock{}\n\tif bytes.Equal(destBlockid, curBlockid) { //原地踏步的情况...\n\t\treturn undoBlocks, todoBlocks, nil\n\t}\n\trootBlockid := l.meta.RootBlockid\n\toldTip, oErr := l.queryBlock(curBlockid, true)\n\tif oErr != nil {\n\t\tl.xlog.Warn(\"block not found\", \"blockid\", utils.F(curBlockid))\n\t\treturn nil, nil, oErr\n\t}\n\tnewTip, nErr := l.queryBlock(destBlockid, true)\n\tif nErr != nil {\n\t\tl.xlog.Warn(\"block not found\", \"blockid\", utils.F(destBlockid))\n\t\treturn nil, nil, nErr\n\t}\n\tvisited := map[string]bool{}\n\tundoBlocks = append(undoBlocks, oldTip)\n\ttodoBlocks = append(todoBlocks, newTip)\n\tvisited[string(oldTip.Blockid)] = true\n\tvisited[string(newTip.Blockid)] = true\n\tvar splitBlockID []byte //最近的分叉点\n\tfor {\n\t\toldPreHash := oldTip.PreHash\n\t\tif len(oldPreHash) > 0 && oldTip.Height >= newTip.Height {\n\t\t\toldTip, oErr = l.queryBlock(oldPreHash, true)\n\t\t\tif oErr != nil {\n\t\t\t\treturn nil, nil, oErr\n\t\t\t}\n\t\t\tif _, exist := visited[string(oldTip.Blockid)]; exist {\n\t\t\t\tsplitBlockID = oldTip.Blockid //从老tip开始回溯到了分叉点\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tvisited[string(oldTip.Blockid)] = true\n\t\t\t\tundoBlocks = append(undoBlocks, oldTip)\n\t\t\t}\n\t\t}\n\t\tnewPreHash := newTip.PreHash\n\t\tif len(newPreHash) > 0 && newTip.Height >= oldTip.Height {\n\t\t\tnewTip, nErr = l.queryBlock(newPreHash, true)\n\t\t\tif nErr != nil {\n\t\t\t\treturn nil, nil, nErr\n\t\t\t}\n\t\t\tif _, exist := visited[string(newTip.Blockid)]; exist {\n\t\t\t\tsplitBlockID = newTip.Blockid //从新tip开始回溯到了分叉点\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tvisited[string(newTip.Blockid)] = true\n\t\t\t\ttodoBlocks = append(todoBlocks, newTip)\n\t\t\t}\n\t\t}\n\t\tif len(oldPreHash) == 0 && len(newPreHash) == 0 {\n\t\t\tsplitBlockID = rootBlockid // 这种情况只能从roott算了\n\t\t\tbreak\n\t\t}\n\t}\n\t//收尾工作,todo_blocks, undo_blocks 如果最后一个元素是分叉点,需要去掉\n\tif bytes.Equal(undoBlocks[len(undoBlocks)-1].Blockid, splitBlockID) {\n\t\tundoBlocks = undoBlocks[:len(undoBlocks)-1]\n\t}\n\tif bytes.Equal(todoBlocks[len(todoBlocks)-1].Blockid, splitBlockID) {\n\t\ttodoBlocks = todoBlocks[:len(todoBlocks)-1]\n\t}\n\treturn undoBlocks, todoBlocks, nil\n}", "func (b *Block) List(input *BlockCursorInput) (*Blocks, error) {\n\tparams := make(map[string]string)\n\tparams[\"cursor\"] = input.Cursor\n\tresp, err := b.c.Request(http.MethodGet, \"/blocks\", new(bytes.Buffer), params)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar blocks *Blocks\n\terr = json.NewDecoder(resp.Body).Decode(&blocks)\n\tif err != nil {\n\t\treturn &Blocks{}, err\n\t}\n\treturn blocks, nil\n}", "func Test_MineBlock_MineBlock(t *testing.T) {\n\tvar block = &Block{\n\t\tIndex: 0,\n\t\tHash: \"\",\n\t\tTransactions: []*transactions.Transaction{\n\t\t\t{\n\t\t\t\tID: \"transactionID\",\n\t\t\t\tInputs: []*transactions.TransactionInput{\n\t\t\t\t\t{\n\t\t\t\t\t\tOutputID: \"output-ID\",\n\t\t\t\t\t\tOutputIndex: 1,\n\t\t\t\t\t\tSignature: \"signature\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tOutputs: []*transactions.TransactionOutput{\n\t\t\t\t\t{\n\t\t\t\t\t\tAddress: \"address\",\n\t\t\t\t\t\tAmount: 25,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tMessage: \"my genesis block!!\",\n\t\tPreviousHash: \"\",\n\t\tTimestamp: time.Unix(1465154705, 0),\n\t\tDifficulty: 5,\n\t\tNonce: 0,\n\t}\n\n\t// hash block\n\tblock.MineBlock()\n\n\t// result should be correct hash\n\texpectedHash := \"01cae462faef5b5132df4a29cba801c620813bc7033ad8ae7d4ad8a8806bb7ca\"\n\tif block.Hash != expectedHash {\n\t\tt.Errorf(\"mining result is incorrect, Actual: %s Expected: %s\", block.Hash, expectedHash)\n\t}\n\texpectedNonce := 4\n\tif block.Nonce != expectedNonce {\n\t\tt.Errorf(\"mining result is incorrect, Actual: %d Expected: %d\", block.Nonce, expectedNonce)\n\t}\n}", "func NewBlock(transactions []*Transaction, preBlockHash []byte) *Block {\n\tb := &Block{time.Now().Unix(), transactions, preBlockHash, []byte{}, 252, 0}\n\n\tpow := NewProofOfWork(b)\n\tnonce, hash := pow.Run()\n\n\tb.Nonce = nonce\n\tb.Hash = hash[:]\n\n\treturn b\n}", "func (_Rootchain *RootchainCallerSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _Rootchain.Contract.Blocks(&_Rootchain.CallOpts, arg0)\n}", "func NewBlock(transactions []*Transaction, prevBlockHash []byte, height int) *Block {\n\tblock := &Block{time.Now().Unix(), transactions, prevBlockHash, []byte{}, 0, height}\n\tblock.POW()\n\treturn block\n}", "func TestFullBlocks(t *testing.T) {\n\tt.Parallel()\n\n\ttests, err := fullblocktests.Generate(false)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to generate tests: %v\", err)\n\t}\n\n\t// Create a new database and chain instance to run tests against.\n\tchain, err := chainSetup(t, chaincfg.RegNetParams())\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to setup chain instance: %v\", err)\n\t}\n\n\t// testAcceptedBlock attempts to process the block in the provided test\n\t// instance and ensures that it was accepted according to the flags\n\t// specified in the test.\n\ttestAcceptedBlock := func(item fullblocktests.AcceptedBlock) {\n\t\tblockHeight := item.Block.Header.Height\n\t\tblock := dcrutil.NewBlock(item.Block)\n\t\tt.Logf(\"Testing block %s (hash %s, height %d)\",\n\t\t\titem.Name, block.Hash(), blockHeight)\n\n\t\tvar isOrphan bool\n\t\tforkLen, err := chain.ProcessBlock(block)\n\t\tif errors.Is(err, ErrMissingParent) {\n\t\t\tisOrphan = true\n\t\t\terr = nil\n\t\t}\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) should have \"+\n\t\t\t\t\"been accepted: %v\", item.Name, block.Hash(),\n\t\t\t\tblockHeight, err)\n\t\t}\n\n\t\t// Ensure the main chain and orphan flags match the values\n\t\t// specified in the test.\n\t\tisMainChain := !isOrphan && forkLen == 0\n\t\tif isMainChain != item.IsMainChain {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) unexpected main \"+\n\t\t\t\t\"chain flag -- got %v, want %v\", item.Name,\n\t\t\t\tblock.Hash(), blockHeight, isMainChain,\n\t\t\t\titem.IsMainChain)\n\t\t}\n\t\tif isOrphan != item.IsOrphan {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) unexpected \"+\n\t\t\t\t\"orphan flag -- got %v, want %v\", item.Name,\n\t\t\t\tblock.Hash(), blockHeight, isOrphan,\n\t\t\t\titem.IsOrphan)\n\t\t}\n\t}\n\n\t// testRejectedBlock attempts to process the block in the provided test\n\t// instance and ensures that it was rejected with the reject code\n\t// specified in the test.\n\ttestRejectedBlock := func(item fullblocktests.RejectedBlock) {\n\t\tblockHeight := item.Block.Header.Height\n\t\tblock := dcrutil.NewBlock(item.Block)\n\t\tt.Logf(\"Testing block %s (hash %s, height %d)\",\n\t\t\titem.Name, block.Hash(), blockHeight)\n\n\t\t_, err := chain.ProcessBlock(block)\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) should not \"+\n\t\t\t\t\"have been accepted\", item.Name, block.Hash(),\n\t\t\t\tblockHeight)\n\t\t}\n\n\t\t// Convert the full block test error kind to the associated local\n\t\t// blockchain error kind.\n\t\twantRejectKind := fullBlockTestErrToLocalErr(t, item.RejectKind)\n\n\t\t// Ensure the error reject kind matches the value specified in the test\n\t\t// instance.\n\t\tif !errors.Is(err, wantRejectKind) {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) does not have \"+\n\t\t\t\t\"expected reject code -- got %v, want %v\",\n\t\t\t\titem.Name, block.Hash(), blockHeight, err, wantRejectKind)\n\t\t}\n\t}\n\n\t// testRejectedNonCanonicalBlock attempts to decode the block in the\n\t// provided test instance and ensures that it failed to decode with a\n\t// message error.\n\ttestRejectedNonCanonicalBlock := func(item fullblocktests.RejectedNonCanonicalBlock) {\n\t\theaderLen := wire.MaxBlockHeaderPayload\n\t\tif headerLen > len(item.RawBlock) {\n\t\t\theaderLen = len(item.RawBlock)\n\t\t}\n\t\tblockHeader := item.RawBlock[0:headerLen]\n\t\tblockHash := chainhash.HashH(chainhash.HashB(blockHeader))\n\t\tblockHeight := item.Height\n\t\tt.Logf(\"Testing block %s (hash %s, height %d)\", item.Name,\n\t\t\tblockHash, blockHeight)\n\n\t\t// Ensure there is an error due to deserializing the block.\n\t\tvar msgBlock wire.MsgBlock\n\t\terr := msgBlock.BtcDecode(bytes.NewReader(item.RawBlock), 0)\n\t\tvar werr *wire.MessageError\n\t\tif !errors.As(err, &werr) {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) should have \"+\n\t\t\t\t\"failed to decode\", item.Name, blockHash,\n\t\t\t\tblockHeight)\n\t\t}\n\t}\n\n\t// testOrphanOrRejectedBlock attempts to process the block in the\n\t// provided test instance and ensures that it was either accepted as an\n\t// orphan or rejected with a rule violation.\n\ttestOrphanOrRejectedBlock := func(item fullblocktests.OrphanOrRejectedBlock) {\n\t\tblockHeight := item.Block.Header.Height\n\t\tblock := dcrutil.NewBlock(item.Block)\n\t\tt.Logf(\"Testing block %s (hash %s, height %d)\",\n\t\t\titem.Name, block.Hash(), blockHeight)\n\n\t\t_, err := chain.ProcessBlock(block)\n\t\tif err != nil {\n\t\t\t// Ensure the error is of the expected type. Note that orphans are\n\t\t\t// rejected with ErrMissingParent, so this check covers both\n\t\t\t// conditions.\n\t\t\tvar rerr RuleError\n\t\t\tif !errors.As(err, &rerr) {\n\t\t\t\tt.Fatalf(\"block %q (hash %s, height %d) \"+\n\t\t\t\t\t\"returned unexpected error type -- \"+\n\t\t\t\t\t\"got %T, want blockchain.RuleError\",\n\t\t\t\t\titem.Name, block.Hash(), blockHeight,\n\t\t\t\t\terr)\n\t\t\t}\n\t\t}\n\t}\n\n\t// testExpectedTip ensures the current tip of the blockchain is the\n\t// block specified in the provided test instance.\n\ttestExpectedTip := func(item fullblocktests.ExpectedTip) {\n\t\tblockHeight := item.Block.Header.Height\n\t\tblock := dcrutil.NewBlock(item.Block)\n\t\tt.Logf(\"Testing tip for block %s (hash %s, height %d)\",\n\t\t\titem.Name, block.Hash(), blockHeight)\n\n\t\t// Ensure hash and height match.\n\t\tbest := chain.BestSnapshot()\n\t\tif best.Hash != item.Block.BlockHash() ||\n\t\t\tbest.Height != int64(blockHeight) {\n\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) should be \"+\n\t\t\t\t\"the current tip -- got (hash %s, height %d)\",\n\t\t\t\titem.Name, block.Hash(), blockHeight, best.Hash,\n\t\t\t\tbest.Height)\n\t\t}\n\t}\n\n\tfor testNum, test := range tests {\n\t\tfor itemNum, item := range test {\n\t\t\tswitch item := item.(type) {\n\t\t\tcase fullblocktests.AcceptedBlock:\n\t\t\t\ttestAcceptedBlock(item)\n\t\t\tcase fullblocktests.RejectedBlock:\n\t\t\t\ttestRejectedBlock(item)\n\t\t\tcase fullblocktests.RejectedNonCanonicalBlock:\n\t\t\t\ttestRejectedNonCanonicalBlock(item)\n\t\t\tcase fullblocktests.OrphanOrRejectedBlock:\n\t\t\t\ttestOrphanOrRejectedBlock(item)\n\t\t\tcase fullblocktests.ExpectedTip:\n\t\t\t\ttestExpectedTip(item)\n\t\t\tdefault:\n\t\t\t\tt.Fatalf(\"test #%d, item #%d is not one of \"+\n\t\t\t\t\t\"the supported test instance types -- \"+\n\t\t\t\t\t\"got type: %T\", testNum, itemNum, item)\n\t\t\t}\n\t\t}\n\t}\n}", "func (synckerManager *SynckerManager) GetCrossShardBlocksForShardValidator(toShard byte, list map[byte][]uint64) (map[byte][]interface{}, error) {\n\tcrossShardPoolLists := synckerManager.GetCrossShardBlocksForShardProducer(toShard, list)\n\n\tmissingBlocks := compareListsByHeight(crossShardPoolLists, list)\n\t// synckerManager.config.Server.\n\tif len(missingBlocks) > 0 {\n\t\tctx, _ := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tsynckerManager.StreamMissingCrossShardBlock(ctx, toShard, missingBlocks)\n\t\t//Logger.Info(\"debug finish stream missing crossX block\")\n\n\t\tcrossShardPoolLists = synckerManager.GetCrossShardBlocksForShardProducer(toShard, list)\n\t\t//Logger.Info(\"get crosshshard block for shard producer\", crossShardPoolLists)\n\t\tmissingBlocks = compareListsByHeight(crossShardPoolLists, list)\n\n\t\tif len(missingBlocks) > 0 {\n\t\t\treturn nil, errors.New(\"Unable to sync required block in time\")\n\t\t}\n\t}\n\n\tfor sid, heights := range list {\n\t\tif len(crossShardPoolLists[sid]) != len(heights) {\n\t\t\treturn nil, fmt.Errorf(\"CrossShard list not match sid:%v pool:%v producer:%v\", sid, len(crossShardPoolLists[sid]), len(heights))\n\t\t}\n\t}\n\n\treturn crossShardPoolLists, nil\n}", "func (sm *SyncManager) handleBlockMsg(bmsg *blockMsg) {\n\tpeer := bmsg.peer\n\tstate, exists := sm.peerStates[peer]\n\tif !exists {\n\t\tlog.Warnf(\"Received block message from unknown peer %s\", peer)\n\t\treturn\n\t}\n\n\t// If we didn't ask for this block then the peer is misbehaving.\n\tblockHash := bmsg.block.Block.Hash()\n\n\t// Remove block from request maps. Either chain will know about it and\n\t// so we shouldn't have any more instances of trying to fetch it, or we\n\t// will fail the insert and thus we'll retry next time we get an inv.\n\tif bmsg.block.Block.Height < sm.chainParams.CRCOnlyDPOSHeight {\n\t\t_, confirmedBlockExist := state.requestedConfirmedBlocks[blockHash]\n\t\tif confirmedBlockExist {\n\t\t\tdelete(state.requestedConfirmedBlocks, blockHash)\n\t\t\tdelete(sm.requestedConfirmedBlocks, blockHash)\n\t\t}\n\n\t\t_, blockExist := state.requestedBlocks[blockHash]\n\t\tif blockExist {\n\t\t\tdelete(state.requestedBlocks, blockHash)\n\t\t\tdelete(sm.requestedBlocks, blockHash)\n\t\t}\n\n\t\tif !confirmedBlockExist && !blockExist {\n\t\t\tlog.Warnf(\"Got unrequested confirmed block %v from %s -- \"+\n\t\t\t\t\"disconnecting\", blockHash, peer)\n\t\t\tpeer.Disconnect()\n\t\t\treturn\n\t\t}\n\t} else if bmsg.block.HaveConfirm {\n\t\tif _, exists = state.requestedConfirmedBlocks[blockHash]; !exists {\n\t\t\tlog.Warnf(\"Got unrequested confirmed block %v from %s -- \"+\n\t\t\t\t\"disconnecting\", blockHash, peer)\n\t\t\tpeer.Disconnect()\n\t\t\treturn\n\t\t}\n\t\tdelete(state.requestedConfirmedBlocks, blockHash)\n\t\tdelete(sm.requestedConfirmedBlocks, blockHash)\n\t} else {\n\t\tif _, exists = state.requestedBlocks[blockHash]; !exists {\n\t\t\tlog.Warnf(\"Got unrequested block %v from %s -- \"+\n\t\t\t\t\"disconnecting\", blockHash, peer)\n\t\t\tpeer.Disconnect()\n\t\t\treturn\n\t\t}\n\t\tdelete(state.requestedBlocks, blockHash)\n\t\tdelete(sm.requestedBlocks, blockHash)\n\t}\n\n\t// Process the block to include validation, best chain selection, orphan\n\t// handling, etc.\n\tlog.Debugf(\"Receive block %s at height %d\", blockHash,\n\t\tbmsg.block.Block.Height)\n\t_, isOrphan, err := sm.blockMemPool.AddDposBlock(bmsg.block)\n\tif err != nil {\n\t\tlog.Warn(\"add block error:\", err)\n\t\telaErr := errors.SimpleWithMessage(errors.ErrP2pReject, err,\n\t\t\tfmt.Sprintf(\"Rejected block %v from %s\", blockHash, peer))\n\n\t\tpeer.PushRejectMsg(p2p.CmdBlock, elaErr, &blockHash, false)\n\t\treturn\n\t}\n\n\tif peer == sm.syncPeer {\n\t\tsm.syncStartTime = time.Now()\n\t}\n\n\tif sm.syncPeer != nil && sm.chain.BestChain.Height >= sm.syncHeight {\n\t\tsm.syncPeer = nil\n\t}\n\n\t// Request the parents for the orphan block from the peer that sent it.\n\tif isOrphan {\n\t\torphanRoot := sm.chain.GetOrphanRoot(&blockHash)\n\t\tlocator, err := sm.chain.LatestBlockLocator()\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"Failed to get block locator for the \"+\n\t\t\t\t\"latest block: %v\", err)\n\t\t} else {\n\t\t\tif sm.syncPeer == nil {\n\t\t\t\tsm.syncPeer = peer\n\t\t\t\tsm.syncHeight = bmsg.block.Block.Height\n\t\t\t\tsm.syncStartTime = time.Now()\n\t\t\t}\n\t\t\tif sm.syncPeer == peer {\n\t\t\t\tpeer.PushGetBlocksMsg(locator, orphanRoot)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Clear the rejected transactions.\n\t\tsm.rejectedTxns = make(map[common.Uint256]struct{})\n\t}\n}", "func GetNewBlock(blocks [][][]int)([][]int,[]int){\n\tLocationOfBlock := []int{0,3}\n\tNumberBlock := rand.Intn(7)\n block := blocks[NumberBlock]\n\tnum := rand.Intn(7)+1\n\tfor row := 0; row<len(block);row++{\n\t\tfor colum :=0; colum<len(block[row]); colum++{\n\t\t\tif block[row][colum] != 0{\n\t\t\t\tblock[row][colum] = num\n\t\t\t}\n\t\t}\n }\n\treturn block, LocationOfBlock\n}", "func (m *Mutate) DeserializeCellBlocks(pm proto.Message, b []byte) (uint32, error) {\n\tresp := pm.(*pb.MutateResponse)\n\tif resp.Result == nil {\n\t\t// TODO: is this possible?\n\t\treturn 0, nil\n\t}\n\tcells, read, err := deserializeCellBlocks(b, uint32(resp.Result.GetAssociatedCellCount()))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tresp.Result.Cell = append(resp.Result.Cell, cells...)\n\treturn read, nil\n}", "func (o SecurityGroupRuleOutput) CidrBlocks() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *SecurityGroupRule) pulumi.StringArrayOutput { return v.CidrBlocks }).(pulumi.StringArrayOutput)\n}", "func (a *Account) ListSinceBlock(since, curBlockHeight int32, minconf int) ([]map[string]interface{}, error) {\n\tvar txInfoList []map[string]interface{}\n\tfor _, txRecord := range a.TxStore.SortedRecords() {\n\t\t// check block number.\n\t\tif since != -1 && txRecord.Height() <= since {\n\t\t\tcontinue\n\t\t}\n\n\t\ttxInfoList = append(txInfoList,\n\t\t\ttxRecord.TxInfo(a.name, curBlockHeight, a.Net())...)\n\t}\n\n\treturn txInfoList, nil\n}", "func (blockchain *BlockChain) GetBlocks() []*Block {\n\treturn blockchain.blocks\n}", "func (dbv DiskBlockDevice) Blocks() uint16 {\n\treturn dbv.blocks\n}", "func scanBlockChunks(wsc *wsClient, cmd *btcjson.RescanCmd, lookups *rescanKeys, minBlock,\n\tmaxBlock int32, chain *blockchain.BlockChain) (\n\t*btcutil.Block, *chainhash.Hash, error) {\n\n\t// lastBlock and lastBlockHash track the previously-rescanned block.\n\t// They equal nil when no previous blocks have been rescanned.\n\tvar (\n\t\tlastBlock *btcutil.Block\n\t\tlastBlockHash *chainhash.Hash\n\t)\n\n\t// A ticker is created to wait at least 10 seconds before notifying the\n\t// websocket client of the current progress completed by the rescan.\n\tticker := time.NewTicker(10 * time.Second)\n\tdefer ticker.Stop()\n\n\t// Instead of fetching all block shas at once, fetch in smaller chunks\n\t// to ensure large rescans consume a limited amount of memory.\nfetchRange:\n\tfor minBlock < maxBlock {\n\t\t// Limit the max number of hashes to fetch at once to the\n\t\t// maximum number of items allowed in a single inventory.\n\t\t// This value could be higher since it's not creating inventory\n\t\t// messages, but this mirrors the limiting logic used in the\n\t\t// peer-to-peer protocol.\n\t\tmaxLoopBlock := maxBlock\n\t\tif maxLoopBlock-minBlock > wire.MaxInvPerMsg {\n\t\t\tmaxLoopBlock = minBlock + wire.MaxInvPerMsg\n\t\t}\n\t\thashList, err := chain.HeightRange(minBlock, maxLoopBlock)\n\t\tif err != nil {\n\t\t\trpcsLog.Errorf(\"Error looking up block range: %v\", err)\n\t\t\treturn nil, nil, &btcjson.RPCError{\n\t\t\t\tCode: btcjson.ErrRPCDatabase,\n\t\t\t\tMessage: \"Database error: \" + err.Error(),\n\t\t\t}\n\t\t}\n\t\tif len(hashList) == 0 {\n\t\t\t// The rescan is finished if no blocks hashes for this\n\t\t\t// range were successfully fetched and a stop block\n\t\t\t// was provided.\n\t\t\tif maxBlock != math.MaxInt32 {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// If the rescan is through the current block, set up\n\t\t\t// the client to continue to receive notifications\n\t\t\t// regarding all rescanned addresses and the current set\n\t\t\t// of unspent outputs.\n\t\t\t//\n\t\t\t// This is done safely by temporarily grabbing exclusive\n\t\t\t// access of the block manager. If no more blocks have\n\t\t\t// been attached between this pause and the fetch above,\n\t\t\t// then it is safe to register the websocket client for\n\t\t\t// continuous notifications if necessary. Otherwise,\n\t\t\t// continue the fetch loop again to rescan the new\n\t\t\t// blocks (or error due to an irrecoverable reorganize).\n\t\t\tpauseGuard := wsc.server.cfg.SyncMgr.Pause()\n\t\t\tbest := wsc.server.cfg.Chain.BestSnapshot()\n\t\t\tcurHash := &best.Hash\n\t\t\tagain := true\n\t\t\tif lastBlockHash == nil || *lastBlockHash == *curHash {\n\t\t\t\tagain = false\n\t\t\t\tn := wsc.server.ntfnMgr\n\t\t\t\tn.RegisterSpentRequests(wsc, lookups.unspentSlice())\n\t\t\t\tn.RegisterTxOutAddressRequests(wsc, cmd.Addresses)\n\t\t\t}\n\t\t\tclose(pauseGuard)\n\t\t\tif err != nil {\n\t\t\t\trpcsLog.Errorf(\"Error fetching best block \"+\n\t\t\t\t\t\"hash: %v\", err)\n\t\t\t\treturn nil, nil, &btcjson.RPCError{\n\t\t\t\t\tCode: btcjson.ErrRPCDatabase,\n\t\t\t\t\tMessage: \"Database error: \" +\n\t\t\t\t\t\terr.Error(),\n\t\t\t\t}\n\t\t\t}\n\t\t\tif again {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\tloopHashList:\n\t\tfor i := range hashList {\n\t\t\tblk, err := chain.BlockByHash(&hashList[i])\n\t\t\tif err != nil {\n\t\t\t\t// Only handle reorgs if a block could not be\n\t\t\t\t// found for the hash.\n\t\t\t\tif dbErr, ok := err.(database.Error); !ok ||\n\t\t\t\t\tdbErr.ErrorCode != database.ErrBlockNotFound {\n\n\t\t\t\t\trpcsLog.Errorf(\"Error looking up \"+\n\t\t\t\t\t\t\"block: %v\", err)\n\t\t\t\t\treturn nil, nil, &btcjson.RPCError{\n\t\t\t\t\t\tCode: btcjson.ErrRPCDatabase,\n\t\t\t\t\t\tMessage: \"Database error: \" +\n\t\t\t\t\t\t\terr.Error(),\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// If an absolute max block was specified, don't\n\t\t\t\t// attempt to handle the reorg.\n\t\t\t\tif maxBlock != math.MaxInt32 {\n\t\t\t\t\trpcsLog.Errorf(\"Stopping rescan for \"+\n\t\t\t\t\t\t\"reorged block %v\",\n\t\t\t\t\t\tcmd.EndBlock)\n\t\t\t\t\treturn nil, nil, &ErrRescanReorg\n\t\t\t\t}\n\n\t\t\t\t// If the lookup for the previously valid block\n\t\t\t\t// hash failed, there may have been a reorg.\n\t\t\t\t// Fetch a new range of block hashes and verify\n\t\t\t\t// that the previously processed block (if there\n\t\t\t\t// was any) still exists in the database. If it\n\t\t\t\t// doesn't, we error.\n\t\t\t\t//\n\t\t\t\t// A goto is used to branch executation back to\n\t\t\t\t// before the range was evaluated, as it must be\n\t\t\t\t// reevaluated for the new hashList.\n\t\t\t\tminBlock += int32(i)\n\t\t\t\thashList, err = recoverFromReorg(\n\t\t\t\t\tchain, minBlock, maxBlock, lastBlockHash,\n\t\t\t\t)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\t\t\t\tif len(hashList) == 0 {\n\t\t\t\t\tbreak fetchRange\n\t\t\t\t}\n\t\t\t\tgoto loopHashList\n\t\t\t}\n\t\t\tif i == 0 && lastBlockHash != nil {\n\t\t\t\t// Ensure the new hashList is on the same fork\n\t\t\t\t// as the last block from the old hashList.\n\t\t\t\tjsonErr := descendantBlock(lastBlockHash, blk)\n\t\t\t\tif jsonErr != nil {\n\t\t\t\t\treturn nil, nil, jsonErr\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// A select statement is used to stop rescans if the\n\t\t\t// client requesting the rescan has disconnected.\n\t\t\tselect {\n\t\t\tcase <-wsc.quit:\n\t\t\t\trpcsLog.Debugf(\"Stopped rescan at height %v \"+\n\t\t\t\t\t\"for disconnected client\", blk.Height())\n\t\t\t\treturn nil, nil, nil\n\t\t\tdefault:\n\t\t\t\trescanBlock(wsc, lookups, blk)\n\t\t\t\tlastBlock = blk\n\t\t\t\tlastBlockHash = blk.Hash()\n\t\t\t}\n\n\t\t\t// Periodically notify the client of the progress\n\t\t\t// completed. Continue with next block if no progress\n\t\t\t// notification is needed yet.\n\t\t\tselect {\n\t\t\tcase <-ticker.C: // fallthrough\n\t\t\tdefault:\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tn := btcjson.NewRescanProgressNtfn(\n\t\t\t\thashList[i].String(), blk.Height(),\n\t\t\t\tblk.MsgBlock().Header.Timestamp.Unix(),\n\t\t\t)\n\t\t\tmn, err := btcjson.MarshalCmd(btcjson.RpcVersion1, nil, n)\n\t\t\tif err != nil {\n\t\t\t\trpcsLog.Errorf(\"Failed to marshal rescan \"+\n\t\t\t\t\t\"progress notification: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err = wsc.QueueNotification(mn); err == ErrClientQuit {\n\t\t\t\t// Finished if the client disconnected.\n\t\t\t\trpcsLog.Debugf(\"Stopped rescan at height %v \"+\n\t\t\t\t\t\"for disconnected client\", blk.Height())\n\t\t\t\treturn nil, nil, nil\n\t\t\t}\n\t\t}\n\n\t\tminBlock += int32(len(hashList))\n\t}\n\n\treturn lastBlock, lastBlockHash, nil\n}", "func (fc *FakeChains) GetNewBlock(shardIndex shard.Index, txps ...*wire.MsgTxWithProofs) *wire.MsgBlock {\n\treturn fc.Chains[shardIndex].GetNewBlock(txps...)\n}", "func (api *GoShimmerAPI) GetBlock(base58EncodedID string) (*jsonmodels.Block, error) {\n\tres := &jsonmodels.Block{}\n\n\tif err := api.do(\n\t\thttp.MethodGet,\n\t\trouteBlock+base58EncodedID,\n\t\tnil,\n\t\tres,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}", "func DeserializeBlock(d []byte) *Block {\n\n\tblock := &Block{}\n\n\terr := proto.Unmarshal(d, block)\n\tif err != nil {\n\t\tlog.Println(\"block-deserialize: protobuf decoding error: \", err)\n\t}\n\n\treturn block\n\n}" ]
[ "0.7826052", "0.6409298", "0.63869226", "0.62129146", "0.6096529", "0.6065399", "0.6064389", "0.59982294", "0.59739965", "0.5933728", "0.590104", "0.58848983", "0.58794004", "0.5818846", "0.57752573", "0.5755512", "0.57286024", "0.571757", "0.5715281", "0.5704689", "0.56978774", "0.56874955", "0.564803", "0.5622621", "0.5600832", "0.5596709", "0.55837834", "0.55719274", "0.5568211", "0.5555939", "0.5552887", "0.5529993", "0.5519471", "0.54812074", "0.54721", "0.54687035", "0.5451903", "0.5451888", "0.5430688", "0.54195946", "0.5418311", "0.5407347", "0.54063284", "0.5403472", "0.5359877", "0.53593546", "0.5347091", "0.53446716", "0.5319881", "0.5315443", "0.5314963", "0.5312209", "0.5294381", "0.52938825", "0.5288889", "0.52758247", "0.5275422", "0.52696717", "0.52642524", "0.5253324", "0.52479595", "0.5243225", "0.52309155", "0.5230901", "0.5229772", "0.51900285", "0.518744", "0.51813096", "0.5179172", "0.5173682", "0.51713246", "0.5164899", "0.51648647", "0.5161676", "0.5159665", "0.5158548", "0.5152386", "0.5149282", "0.51485634", "0.5147858", "0.51464546", "0.51362187", "0.51361054", "0.5134267", "0.5133992", "0.512865", "0.51241195", "0.512306", "0.51213044", "0.512086", "0.51193297", "0.5116823", "0.51066995", "0.51035136", "0.509544", "0.50950223", "0.50940573", "0.5092885", "0.5090278", "0.50826174" ]
0.57698154
15
initDNSServer creates an instance of the dnsforward.Server Please note that we must do it even if we don't start it so that we had access to the query log and the stats
func initDNSServer(baseDir string) { err := os.MkdirAll(baseDir, 0755) if err != nil { log.Fatalf("Cannot create DNS data dir at %s: %s", baseDir, err) } dnsServer = dnsforward.NewServer(baseDir) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func runDNSServer() {\n\n\t// load the blocked domains\n\tblacklist := LoadBlacklistOrFail(blacklistPath)\n\tfmt.Printf(\"Loading list of %d blocked domains...\\n\", blacklist.Size())\n\n\t// make the custom handler function to reply to DNS queries\n\tupstream := getEnvOrDefault(\"UPSTREAM_DNS\", \"1.1.1.1:53\")\n\tlogging := getEnvOrDefault(\"DEBUG\", \"\") == \"true\"\n\thandler := makeDNSHandler(blacklist, upstream, logging)\n\n\t// start the server\n\tport := getEnvOrDefault(\"DNS_PORT\", \"53\")\n\tfmt.Printf(\"Starting DNS server on UDP port %s (logging = %t)...\\n\", port, logging)\n\tserver := &dns.Server{Addr: \":\" + port, Net: \"udp\"}\n\tdns.HandleFunc(\".\", handler)\n\terr := server.ListenAndServe()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func NewDNSServerDefault() (srv *dns.Server) {\n\tsrv = &dns.Server{Addr: \":\" + strconv.Itoa(53), Net: \"udp\"}\n\tconfig, _ := dns.ClientConfigFromFile(resolvFile)\n\n\tsrv.Handler = &server{config}\n\n\tlog.Info().Msgf(\"Successful load local \" + resolvFile)\n\tfor _, server := range config.Servers {\n\t\tlog.Info().Msgf(\"Success load nameserver %s\\n\", server)\n\t}\n\tfor _, domain := range config.Search {\n\t\tlog.Info().Msgf(\"Success load search %s\\n\", domain)\n\t}\n\treturn\n}", "func InitServer() Server {\n\tserver := Server{&goserver.GoServer{}, ssdp.MakeManager()}\n\tserver.Register = server\n\n\treturn server\n}", "func init() {\n\tos.RemoveAll(DataPath)\n\n\tdc := DatabaseConfig{\n\t\tDataPath: DataPath,\n\t\tIndexDepth: 4,\n\t\tPayloadSize: 16,\n\t\tBucketDuration: 3600000000000,\n\t\tResolution: 60000000000,\n\t\tSegmentSize: 100000,\n\t}\n\n\tcfg := &ServerConfig{\n\t\tVerboseLogs: true,\n\t\tRemoteDebug: true,\n\t\tListenAddress: Address,\n\t\tDatabases: map[string]DatabaseConfig{\n\t\t\tDatabase: dc,\n\t\t},\n\t}\n\n\tdbs := map[string]kdb.Database{}\n\tdb, err := dbase.New(dbase.Options{\n\t\tDatabaseName: Database,\n\t\tDataPath: dc.DataPath,\n\t\tIndexDepth: dc.IndexDepth,\n\t\tPayloadSize: dc.PayloadSize,\n\t\tBucketDuration: dc.BucketDuration,\n\t\tResolution: dc.Resolution,\n\t\tSegmentSize: dc.SegmentSize,\n\t})\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdbs[\"test\"] = db\n\td = db\n\to = dc\n\n\ts = NewServer(dbs, cfg)\n\tgo s.Listen()\n\n\t// wait for the server to start\n\ttime.Sleep(time.Second * 2)\n\n\tc = NewClient(Address)\n\tif err := c.Connect(); err != nil {\n\t\tpanic(err)\n\t}\n}", "func InitHttpSrv(addr string) {\n go func() {\n err := http.ListenAndServe(addr, nil)\n if err != nil {\n log.Error(err.Error())\n }\n }()\n}", "func (s *Server) init(renew bool) (err error) {\n\ts.Config.Operations.Metrics = s.Config.Metrics\n\ts.Operations = operations.NewSystem(s.Config.Operations)\n\ts.initMetrics()\n\n\tserverVersion := metadata.GetVersion()\n\terr = calog.SetLogLevel(s.Config.LogLevel, s.Config.Debug)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Infof(\"Server Version: %s\", serverVersion)\n\ts.levels, err = metadata.GetLevels(serverVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Infof(\"Server Levels: %+v\", s.levels)\n\n\ts.mux = gmux.NewRouter()\n\t// Initialize the config\n\terr = s.initConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Initialize the default CA last\n\terr = s.initDefaultCA(renew)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Successful initialization\n\treturn nil\n}", "func InitServer() *Server {\n\ts := &Server{\n\t\t&goserver.GoServer{},\n\t\t\"logs\",\n\t\tmake(map[string]*logHolder),\n\t\t&sync.Mutex{},\n\t\ttime.Now(),\n\t\t&sync.Mutex{},\n\t\t0,\n\t\t0,\n\t\tmake(map[string]int),\n\t\t&sync.Mutex{},\n\t\t&pb.Config{},\n\t}\n\ts.Register = s\n\treturn s\n}", "func InitServer(addr string) *http.Server {\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"/pokemon/{name}\", endpoints.PokemonHandler)\n\trouter.HandleFunc(\"/health\", endpoints.HealthHandler)\n\n\trouter.Use(middleware.LoggingMiddleware)\n\n\tsrv := &http.Server{\n\t\tHandler: router,\n\t\tAddr: \"0.0.0.0:8080\",\n\t\tWriteTimeout: 15 * time.Second,\n\t\tReadTimeout: 15 * time.Second,\n\t}\n\n\treturn srv\n}", "func StartDNSDaemon() (err error) {\n\tsrv := &dns.Server{Addr: \":\" + strconv.Itoa(53), Net: \"udp\"}\n\tsrv.Handler = &dnsHandler{}\n\n\tconfig, _ := dns.ClientConfigFromFile(\"/etc/resolv.conf\")\n\n\tlog.Info().Msgf(\"Successful load local /etc/resolv.conf\")\n\tfor _, server := range config.Servers {\n\t\tlog.Info().Msgf(\"Success load nameserver %s\\n\", server)\n\t}\n\n\tfmt.Printf(\"DNS Server Start At 53...\\n\")\n\terr = srv.ListenAndServe()\n\tif err != nil {\n\t\tlog.Error().Msgf(\"Failed to set udp listener %s\\n\", err.Error())\n\t}\n\treturn\n}", "func (s *StanServer) startNATSServer() error {\n\tif err := s.configureClusterOpts(); err != nil {\n\t\treturn err\n\t}\n\tif err := s.configureNATSServerTLS(); err != nil {\n\t\treturn err\n\t}\n\topts := s.natsOpts\n\ts.natsServer = server.New(opts)\n\tif s.natsServer == nil {\n\t\treturn fmt.Errorf(\"no NATS Server object returned\")\n\t}\n\ts.log.SetNATSServer(s.natsServer)\n\t// Run server in Go routine.\n\tgo s.natsServer.Start()\n\t// Wait for accept loop(s) to be started\n\tif !s.natsServer.ReadyForConnections(10 * time.Second) {\n\t\treturn fmt.Errorf(\"unable to start a NATS Server on %s:%d\", opts.Host, opts.Port)\n\t}\n\treturn nil\n}", "func (ds *DNSSuite) Init(flagSet *flag.FlagSet, args []string) error {\n\tvar typeStr string\n\n\tflagSet.StringVar(&ds.Protocol, \"protocol\", \"udp\", \"DNS server protocol, udp|tcp|tcp-tls\")\n\tflagSet.StringVar(&ds.Host, \"host\", \"127.0.0.1:53\", \"DNS server host, IP and port\")\n\tflagSet.StringVar(&typeStr, \"type\", \"A\", \"DNS Type, like A|AAAA|CNAME\")\n\tflagSet.Var(&ds.Records, \"record\", \"DNS record to test\")\n\n\tflagSet.Parse(args)\n\n\tif ds.Protocol != \"udp\" && ds.Protocol != \"tcp\" && ds.Protocol != \"tcp-tls\" {\n\t\treturn errors.New(\"protocol should be one of udp|tcp|tcp-tls\")\n\t}\n\tif !strings.ContainsRune(ds.Host, ':') {\n\t\tds.Host += \":53\"\n\t}\n\tif typeStr != \"A\" && typeStr != \"AAAA\" && typeStr != \"CNAME\" {\n\t\treturn errors.New(\"type should be one of udp|tcp|tcp-tls\")\n\t}\n\tif len(ds.Records) == 0 {\n\t\treturn errors.New(\"specify at least one record\")\n\t}\n\n\tfor idx, record := range ds.Records {\n\t\tif record[len(record)-1] != '.' {\n\t\t\tds.Records[idx] = record + \".\"\n\t\t}\n\t}\n\n\tswitch typeStr {\n\tcase \"A\":\n\t\tds.Type = dns.TypeA\n\tcase \"AAAA\":\n\t\tds.Type = dns.TypeAAAA\n\tcase \"CNAME\":\n\t\tds.Type = dns.TypeCNAME\n\t}\n\n\tclient.DNSClient.Net = ds.Protocol\n\n\treturn nil\n}", "func newDNSTestServer(server *dns.Server) *dnsTestServer {\n\treturn &dnsTestServer{Server: server, DNSDatabase: make(dnsDatabase), DNSDatabaseRetry: make(dnsDatabase)}\n}", "func NewServer(\n\taddr string,\n\tcontrollerNS string,\n\tidentityTrustDomain string,\n\tenableH2Upgrade bool,\n\tk8sAPI *k8s.API,\n\tshutdown <-chan struct{},\n) *grpc.Server {\n\tlog := logging.WithFields(logging.Fields{\n\t\t\"addr\": addr,\n\t\t\"component\": \"server\",\n\t})\n\tendpoints := watcher.NewEndpointsWatcher(k8sAPI, log)\n\tprofiles := watcher.NewProfileWatcher(k8sAPI, log)\n\ttrafficSplits := watcher.NewTrafficSplitWatcher(k8sAPI, log)\n\n\tsrv := server{\n\t\tendpoints,\n\t\tprofiles,\n\t\ttrafficSplits,\n\t\tenableH2Upgrade,\n\t\tcontrollerNS,\n\t\tidentityTrustDomain,\n\t\tlog,\n\t\tshutdown,\n\t}\n\n\ts := prometheus.NewGrpcServer()\n\t// linkerd2-proxy-api/destination.Destination (proxy-facing)\n\tpb.RegisterDestinationServer(s, &srv)\n\t// controller/discovery.Discovery (controller-facing)\n\tdiscoveryPb.RegisterDiscoveryServer(s, &srv)\n\treturn s\n}", "func NewServer(c *Config) (*Server, error) {\n\ts := &Server{}\n\n\tif c.Timeout != \"\" {\n\t\ttimeout, err := time.ParseDuration(c.Timeout)\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"parse timeout: \" + err.Error())\n\t\t}\n\t\ts.dialer = &net.Dialer{Timeout: timeout}\n\t} else {\n\t\ts.dialer = &net.Dialer{Timeout: 20 * time.Second}\n\t}\n\n\tif c.Retries != nil {\n\t\ts.retries = *c.Retries\n\t} else {\n\t\ts.retries = 3\n\t}\n\n\ts.requireAuth = len(c.Accounts) > 0\n\tif s.requireAuth {\n\t\ts.account = make([]*internalAccount, len(c.Accounts))\n\t\tfor i, v := range c.Accounts {\n\t\t\ts.account[i] = &internalAccount{\n\t\t\t\tusername: []byte(v.Username),\n\t\t\t\tpassword: []byte(v.Password),\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(c.Upstreams) == 0 {\n\t\treturn nil, errors.New(\"no upstreams\")\n\t}\n\n\tupstreams := make([]*internalUpstream, len(c.Upstreams))\n\tfor i, v := range c.Upstreams {\n\t\taddr := v.Address\n\t\thost, port, err := net.SplitHostPort(addr)\n\t\tif err != nil {\n\t\t\taddr += \":80\"\n\t\t\thost, port, err = net.SplitHostPort(addr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(\"invalid address \" + v.Address)\n\t\t\t}\n\t\t}\n\t\taddr = net.JoinHostPort(host, port)\n\n\t\ttlsConfig := (*tls.Config)(nil)\n\t\tif t := v.TLSConfig; t != nil {\n\t\t\ttlsConfig = &tls.Config{\n\t\t\t\tNextProtos: []string{\"http/1.1\"},\n\t\t\t}\n\n\t\t\tif t.ServerName != \"\" {\n\t\t\t\ttlsConfig.ServerName = t.ServerName\n\t\t\t} else {\n\t\t\t\tu, err := url.Parse(v.Address)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.New(\"tls: parse server name: \" + err.Error())\n\t\t\t\t}\n\t\t\t\ttlsConfig.ServerName = u.Hostname()\n\t\t\t}\n\n\t\t\ttlsConfig.InsecureSkipVerify = t.InsecureSkipVerify\n\t\t\tif t.SHA256Fingerprint != \"\" {\n\t\t\t\tfin, err := hex.DecodeString(t.SHA256Fingerprint)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.New(\"tls: failed to parse fingerprint\")\n\t\t\t\t}\n\t\t\t\tif len(fin) != 32 {\n\t\t\t\t\treturn nil, errors.New(\"tls: fingerprint: wrong length, not like a sha256 digest\")\n\t\t\t\t}\n\n\t\t\t\ttlsConfig.VerifyPeerCertificate = func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {\n\t\t\t\t\tif len(rawCerts) < 1 {\n\t\t\t\t\t\treturn errors.New(\"server provides no cert\")\n\t\t\t\t\t}\n\n\t\t\t\t\tsum := sha256.Sum256(rawCerts[0])\n\t\t\t\t\tif !hmac.Equal(sum[:], fin) {\n\t\t\t\t\t\treturn errors.New(\"wrong fingerprint\")\n\t\t\t\t\t}\n\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif t.RootCA != \"\" {\n\t\t\t\tcertPool := x509.NewCertPool()\n\t\t\t\tpem, err := ioutil.ReadFile(t.RootCA)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.New(\"tls: read rootCAs: \" + err.Error())\n\t\t\t\t}\n\t\t\t\tif !certPool.AppendCertsFromPEM(pem) {\n\t\t\t\t\treturn nil, errors.New(\"tls: failed to load rootCAs\")\n\t\t\t\t}\n\t\t\t\ttlsConfig.RootCAs = certPool\n\t\t\t}\n\n\t\t\tif t.CertFile != \"\" && t.KeyFile != \"\" {\n\t\t\t\tcert, err := tls.LoadX509KeyPair(t.CertFile, t.KeyFile)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.New(\"tls: load key pair: \" + err.Error())\n\t\t\t\t}\n\t\t\t\ttlsConfig.Certificates = []tls.Certificate{cert}\n\t\t\t}\n\t\t}\n\n\t\tupstreams[i] = &internalUpstream{\n\t\t\taddress: addr,\n\t\t\theader: basicauth(v.Username, v.Password),\n\t\t\ttlsConfig: tlsConfig,\n\t\t}\n\t}\n\n\ts.next = make(chan *internalUpstream)\n\ts.stop = make(chan struct{})\n\tgo func() {\n\t\t// simple round-robin\n\t\tfor {\n\t\t\tfor _, v := range upstreams {\n\t\t\t\tselect {\n\t\t\t\tcase s.next <- v:\n\t\t\t\tcase <-s.stop:\n\t\t\t\t\tclose(s.next)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn s, nil\n}", "func runTestDNSServer(t *testing.T, port string) *dnsTestServer {\n\tlistener, err := net.ListenPacket(\"udp\", \"127.0.0.1:\"+port)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tmux := dns.NewServeMux()\n\tserver := &dns.Server{PacketConn: listener, Net: \"udp\", Handler: mux}\n\n\tgo func() {\n\t\tif err := server.ActivateAndServe(); err != nil {\n\t\t\tlog.Printf(\"Error in local DNS server: %s\", err)\n\t\t}\n\t}()\n\n\treturn newDNSTestServer(server)\n}", "func InitServer(dataDirectory string, showDash bool, logger *log.Logger) *MetaServer {\n\trouter := mux.NewRouter()\n\n\tdb, err := newMongoDB()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tserver := &MetaServer{\n\t\tdataDir: dataDirectory,\n\t\tdb: db,\n\t\trouter: router,\n\t\tlogger: logger,\n\t\tauthorizer: authorization.NewAuthorizer(logger),\n\t\tsigningKey: []byte(\"secret\"),\n\t}\n\n\tauthMiddleware := authorization.GetAuthMiddleware(server.signingKey)\n\n\trouter.Handle(\"/auth/provider\", server.authorizer.GetAuthChallengeHandler(\"providerID\")).Methods(\"GET\")\n\trouter.Handle(\"/auth/provider\", server.authorizer.GetRespondAuthChallengeHandler(\n\t\t\"providerID\", server.signingKey, server.getProviderPublicKey)).Methods(\"POST\")\n\n\trouter.Handle(\"/auth/renter\", server.authorizer.GetAuthChallengeHandler(\"renterID\")).Methods(\"GET\")\n\trouter.Handle(\"/auth/renter\", server.authorizer.GetRespondAuthChallengeHandler(\n\t\t\"renterID\", server.signingKey, server.getRenterPublicKey)).Methods(\"POST\")\n\n\trouter.Handle(\"/providers\", server.getProvidersHandler()).Methods(\"GET\")\n\trouter.Handle(\"/providers\", server.postProviderHandler()).Methods(\"POST\")\n\trouter.Handle(\"/providers/{id}\", server.getProviderHandler()).Methods(\"GET\")\n\trouter.Handle(\"/providers/{id}\", authMiddleware.Handler(server.putProviderHandler())).Methods(\"PUT\")\n\trouter.Handle(\"/providers/{id}\", authMiddleware.Handler(server.deleteProviderHandler())).Methods(\"DELETE\")\n\n\trouter.Handle(\"/providers/{providerID}/transactions\", authMiddleware.Handler(server.getProviderTransactionsHandler())).Methods(\"GET\")\n\n\trouter.Handle(\"/renters\", server.postRenterHandler()).Methods(\"POST\")\n\trouter.Handle(\"/renters\", server.getRenterByAliasHandler()).Queries(\"alias\", \"{alias}\").Methods(\"GET\")\n\trouter.Handle(\"/renters/{id}\", authMiddleware.Handler(server.getRenterHandler())).Methods(\"GET\")\n\trouter.Handle(\"/renters/{id}\", authMiddleware.Handler(server.putRenterHandler())).Methods(\"PUT\")\n\trouter.Handle(\"/renters/{id}\", authMiddleware.Handler(server.deleteRenterHandler())).Methods(\"DELETE\")\n\n\trouter.Handle(\"/renters/{renterID}/transactions\", authMiddleware.Handler(server.getRenterTransactionsHandler())).Methods(\"GET\")\n\n\trouter.Handle(\"/renters/{renterID}/contracts\", authMiddleware.Handler(server.getContractsHandler())).Methods(\"GET\")\n\trouter.Handle(\"/renters/{renterID}/contracts\", authMiddleware.Handler(server.postContractHandler())).Methods(\"POST\")\n\trouter.Handle(\"/renters/{renterID}/contracts/{contractID}\", authMiddleware.Handler(server.getContractHandler())).Methods(\"GET\")\n\trouter.Handle(\"/renters/{renterID}/contracts/{contractID}\", authMiddleware.Handler(server.putContractHandler())).Methods(\"PUT\")\n\trouter.Handle(\"/renters/{renterID}/contracts/{contractID}\", authMiddleware.Handler(server.deleteContractHandler())).Methods(\"DELETE\")\n\trouter.Handle(\"/renters/{renterID}/contracts/{contractID}/payment\", authMiddleware.Handler(server.getContractPaymentHandler())).Methods(\"GET\")\n\trouter.Handle(\"/renters/{renterID}/contracts/{contractID}/payment\", authMiddleware.Handler(server.putContractPaymentHandler())).Methods(\"PUT\")\n\n\trouter.Handle(\"/renters/{renterID}/files\", authMiddleware.Handler(server.getFilesHandler())).Methods(\"GET\")\n\trouter.Handle(\"/renters/{renterID}/files\", authMiddleware.Handler(server.postFileHandler())).Methods(\"POST\")\n\trouter.Handle(\"/renters/{renterID}/files/{fileID}\", authMiddleware.Handler(server.getFileHandler())).Methods(\"GET\")\n\trouter.Handle(\"/renters/{renterID}/files/{fileID}\", authMiddleware.Handler(server.putFileHandler())).Methods(\"PUT\")\n\trouter.Handle(\"/renters/{renterID}/files/{fileID}\", authMiddleware.Handler(server.deleteFileHandler())).Methods(\"DELETE\")\n\trouter.Handle(\"/renters/{renterID}/files/{fileID}/versions\", authMiddleware.Handler(server.getFileVersionsHandler())).Methods(\"GET\")\n\trouter.Handle(\"/renters/{renterID}/files/{fileID}/versions\", authMiddleware.Handler(server.postFileVersionHandler())).Methods(\"POST\")\n\trouter.Handle(\"/renters/{renterID}/files/{fileID}/versions/{version}\", authMiddleware.Handler(server.getFileVersionHandler())).Methods(\"GET\")\n\trouter.Handle(\"/renters/{renterID}/files/{fileID}/versions/{version}\", authMiddleware.Handler(server.putFileVersionHandler())).Methods(\"PUT\")\n\trouter.Handle(\"/renters/{renterID}/files/{fileID}/versions/{version}\", authMiddleware.Handler(server.deleteFileVersionHandler())).Methods(\"DELETE\")\n\trouter.Handle(\"/renters/{renterID}/files/{fileID}/permissions\", authMiddleware.Handler(server.getFilePermissionsHandler())).Methods(\"GET\")\n\trouter.Handle(\"/renters/{renterID}/files/{fileID}/permissions\", authMiddleware.Handler(server.postFilePermissionHandler())).Methods(\"POST\")\n\trouter.Handle(\"/renters/{renterID}/files/{fileID}/permissions/{sharedID}\", authMiddleware.Handler(server.getFilePermissionHandler())).Methods(\"GET\")\n\trouter.Handle(\"/renters/{renterID}/files/{fileID}/permissions/{sharedID}\", authMiddleware.Handler(server.putFilePermissionHandler())).Methods(\"PUT\")\n\trouter.Handle(\"/renters/{renterID}/files/{fileID}/permissions/{sharedID}\", authMiddleware.Handler(server.deleteFilePermissionHandler())).Methods(\"DELETE\")\n\n\trouter.Handle(\"/renters/{renterID}/shared\", authMiddleware.Handler(server.getSharedFilesHandler())).Methods(\"GET\")\n\trouter.Handle(\"/renters/{renterID}/shared/{fileID}\", authMiddleware.Handler(server.getFileHandler())).Methods(\"GET\")\n\trouter.Handle(\"/renters/{renterID}/shared/{fileID}\", authMiddleware.Handler(server.deleteSharedFileHandler())).Methods(\"DELETE\")\n\trouter.Handle(\"/renters/{renterID}/shared/{fileID}/versions\", authMiddleware.Handler(server.getFileVersionsHandler())).Methods(\"GET\")\n\trouter.Handle(\"/renters/{renterID}/shared/{fileID}/versions/{version}\", authMiddleware.Handler(server.getFileVersionHandler())).Methods(\"GET\")\n\n\trouter.Handle(\"/paypal/create\", authMiddleware.Handler(server.getCreatePaypalPaymentHandler())).Methods(\"POST\")\n\trouter.Handle(\"/paypal/execute\", authMiddleware.Handler(server.getExecutePaypalPaymentHandler())).Methods(\"POST\")\n\trouter.Handle(\"/paypal/renter-withdraw\", authMiddleware.Handler(server.getRenterPaypalWithdrawHandler())).Methods(\"POST\")\n\trouter.Handle(\"/paypal/provider-withdraw\", authMiddleware.Handler(server.getProviderPaypalWithdrawHandler())).Methods(\"POST\")\n\n\tif showDash {\n\t\trouter.Handle(\"/dashboard.json\", server.getDashboardDataHandler()).Methods(\"GET\")\n\t\trouter.Handle(\"/dashboard/audit/{fileID}/{blockID}\", server.getDashboardAuditHandler()).Methods(\"POST\")\n\n\t\tstaticPath, err := getStaticPath()\n\t\tif err != nil {\n\t\t\tserver.logger.Fatal(err)\n\t\t}\n\t\trouter.Handle(\"/{someFile}\", http.FileServer(http.Dir(staticPath)))\n\t}\n\n\tserver.startPaymentRunner()\n\n\treturn server\n}", "func (d *Daemon) Init() error {\n\tlistenerMap := make(map[string]net.Listener)\n\n\tif listener, err := getListener(d.normalSocketPath, listenerMap); err == nil {\n\t\td.generalListener = &ucrednetListener{Listener: listener}\n\t} else {\n\t\treturn fmt.Errorf(\"when trying to listen on %s: %v\", d.normalSocketPath, err)\n\t}\n\n\tif listener, err := getListener(d.untrustedSocketPath, listenerMap); err == nil {\n\t\t// This listener may also be nil if that socket wasn't among\n\t\t// the listeners, so check it before using it.\n\t\td.untrustedListener = &ucrednetListener{Listener: listener}\n\t} else {\n\t\tlogger.Debugf(\"cannot get listener for %q: %v\", d.untrustedSocketPath, err)\n\t}\n\n\td.addRoutes()\n\n\tlogger.Noticef(\"Started daemon.\")\n\treturn nil\n}", "func InitServer(ip string) Server {\n\tserver := Server{IP: ip, Port: 8090}\n\treturn server\n}", "func (s *UDPServer) Init(settings *ServerSettings) error {\n\turl := settings.URL\n\tport := settings.Port\n\tif port == \"\" {\n\t\treturn errors.New(\"udp_server_init: port required\")\n\t}\n\n\taddress := url + \":\" + port\n\n\tudpAddr, err := net.ResolveUDPAddr(\"udp4\", address)\n\tif err != nil {\n\t\treturn errors.New(\"udp_server_init: could not resolve address. err: \" + err.Error())\n\t}\n\n\ts.Conn, err = net.ListenUDP(\"udp\", udpAddr)\n\tif err != nil {\n\t\treturn errors.New(\"udp_server_init: could not start connection. err: \" + err.Error())\n\t}\n\n\treturn nil\n}", "func setupTestDNSServers(t *testing.T) (s1, s2 *dnsTestServer) {\n\ts1 = runTestDNSServer(t, \"0\")\n\ts2 = runTestDNSServer(t, \"0\")\n\n\tq := DNSQuery{\"NS\", testDomain}\n\ta := DNSAnswers{{\"NS\", s1.Address() + \".\"}, {\"NS\", s2.Address() + \".\"}}\n\ts1.AddEntryToDNSDatabase(q, a)\n\ts2.AddEntryToDNSDatabase(q, a)\n\n\ts1.Server.Handler.(*dns.ServeMux).HandleFunc(testDomain+\".\", func(w dns.ResponseWriter, r *dns.Msg) {\n\t\tstdDNSHandler(t, w, r, s1, false)\n\t})\n\ts2.Server.Handler.(*dns.ServeMux).HandleFunc(testDomain+\".\", func(w dns.ResponseWriter, r *dns.Msg) {\n\t\tstdDNSHandler(t, w, r, s2, true)\n\t})\n\n\treturn s1, s2\n}", "func NewServer(env dnsmgrenv.DNSMgrEnv, dnsService DNSService, db *sqlx.DB) *Server {\n\treturn &Server{env: env, dnsService: dnsService, db: db}\n}", "func initServer(ctx context.Context, n *Node) error {\n\n\tif n.index < int32(len(n.config.Nodes)) {\n\n\t\tle := n.config.Nodes[n.index]\n\t\tvar listener net.Listener\n\n\t\terr := backoff.Retry(\n\t\t\tfunc() error {\n\t\t\t\tvar err error\n\t\t\t\tlistener, err = net.Listen(\"tcp\", le)\n\t\t\t\treturn err\n\t\t\t},\n\t\t\tbackoff.WithMaxRetries(backoff.NewExponentialBackOff(), 3),\n\t\t)\n\n\t\t// listener, err := net.Listen(\"tcp\", le)\n\t\tif err != nil {\n\t\t\terr = raftErrorf(err, \"failed to acquire local TCP socket for gRPC\")\n\t\t\tn.logger.Errorw(\"initServer failed (some other application or previous instance still using socket?)\",\n\t\t\t\traftErrKeyword, err)\n\t\t\treturn err\n\t\t}\n\n\t\ts := &raftServer{\n\t\t\tnode: n,\n\t\t\tlocalListener: listener,\n\t\t\tlocalAddr: le,\n\t\t}\n\n\t\tn.messaging.server = s\n\t\tn.logger.Debugw(\"listener acquired local node address\", s.logKV()...)\n\n\t} else {\n\n\t\terr := raftErrorf(\n\t\t\tRaftErrorServerNotSetup, \"LocalNodeIndex in out of bounds of cluster Nodes configuration\")\n\t\tn.logger.Errorw(\"initServer failed\", raftErrKeyword, err)\n\t\treturn err\n\n\t}\n\n\treturn nil\n}", "func (s *Server) Init(addr string, db Store) error {\n\tvar err error\n\n\ts.l, err = net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error start server: %v\\n\", err)\n\t}\n\tlog.Println(\"Server start \", addr)\n\n\tif db == nil {\n\t\treturn fmt.Errorf(\"Store not initializate\\n\")\n\t}\n\ts.db = db\n\n\treturn err\n}", "func Init(c *conf.Config) {\n\tinitService(c)\n\tengine := bm.DefaultServer(c.HTTPServer)\n\tinnerRouter(engine)\n\t// init internal server\n\tif err := engine.Start(); err != nil {\n\t\tlog.Error(\"httpx.Serve error(%v)\", err)\n\t\tpanic(err)\n\t}\n}", "func (svr *Server) Init(maxConns int) (err error) {\n\tsvr.LineMgr, err = NewMLLineMgr(maxConns)\n\tif err != nil {\n\t\tutils.Logger.Error(\"New Magline Connection Pool Error!\")\n\t\treturn\n\t}\n\treturn\n}", "func NewServer(proxy *dns.Proxy, config Config) (*Server, error) {\n\tserver := &Server{\n\t\tConfig: config,\n\t\tdone: make(chan bool, 1),\n\t\tproxy: proxy,\n\t\thttpClient: &http.Client{Timeout: 10 * time.Second},\n\t}\n\tproxy.Handler = server.hijack\n\n\t// Periodically refresh hosts\n\tif interval := config.DNS.refreshInterval; interval > 0 {\n\t\tgo server.reloadHosts(interval)\n\t}\n\n\t// Load initial hosts\n\tgo server.loadHosts()\n\treturn server, nil\n}", "func init() {\r\n\tmux := http.NewServeMux()\r\n\trpcserver.RegisterRPCFuncs(mux, Routes)\r\n\twm := rpcserver.NewWebsocketManager(Routes, nil)\r\n\tmux.HandleFunc(websocketEndpoint, wm.WebsocketHandler)\r\n\tgo func() {\r\n\t\t_, err := rpcserver.StartHTTPServer(tcpAddr, mux)\r\n\t\tif err != nil {\r\n\t\t\tpanic(err)\r\n\t\t}\r\n\t}()\r\n\r\n\tmux2 := http.NewServeMux()\r\n\trpcserver.RegisterRPCFuncs(mux2, Routes)\r\n\twm = rpcserver.NewWebsocketManager(Routes, nil)\r\n\tmux2.HandleFunc(websocketEndpoint, wm.WebsocketHandler)\r\n\tgo func() {\r\n\t\t_, err := rpcserver.StartHTTPServer(unixAddr, mux2)\r\n\t\tif err != nil {\r\n\t\t\tpanic(err)\r\n\t\t}\r\n\t}()\r\n\r\n\t// wait for servers to start\r\n\ttime.Sleep(time.Second * 2)\r\n\r\n}", "func initMDNS(ctx context.Context, peerhost host.Host, rendezvous string) chan peer.AddrInfo {\n\t// An hour might be a long long period in practical applications. But this is fine for us\n\tser, err := discovery.NewMdnsService(ctx, peerhost, time.Hour, rendezvous)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t//register with service so that we get notified about peer discovery\n\tn := &discoveryNotifee{}\n\tn.PeerChan = make(chan peer.AddrInfo)\n\n\tser.RegisterNotifee(n)\n\treturn n.PeerChan\n}", "func NewServer(addr string, group []*Config) (*Server, error) {\n\ts := &Server{\n\t\tAddr: addr,\n\t\tzones: make(map[string][]*Config),\n\t\tgraceTimeout: 5 * time.Second,\n\t\tidleTimeout: 10 * time.Second,\n\t\treadTimeout: 3 * time.Second,\n\t\twriteTimeout: 5 * time.Second,\n\t\ttsigSecret: make(map[string]string),\n\t}\n\n\t// We have to bound our wg with one increment\n\t// to prevent a \"race condition\" that is hard-coded\n\t// into sync.WaitGroup.Wait() - basically, an add\n\t// with a positive delta must be guaranteed to\n\t// occur before Wait() is called on the wg.\n\t// In a way, this kind of acts as a safety barrier.\n\ts.dnsWg.Add(1)\n\n\tfor _, site := range group {\n\t\tif site.Debug {\n\t\t\ts.debug = true\n\t\t\tlog.D.Set()\n\t\t}\n\t\ts.stacktrace = site.Stacktrace\n\n\t\t// append the config to the zone's configs\n\t\ts.zones[site.Zone] = append(s.zones[site.Zone], site)\n\n\t\t// set timeouts\n\t\tif site.ReadTimeout != 0 {\n\t\t\ts.readTimeout = site.ReadTimeout\n\t\t}\n\t\tif site.WriteTimeout != 0 {\n\t\t\ts.writeTimeout = site.WriteTimeout\n\t\t}\n\t\tif site.IdleTimeout != 0 {\n\t\t\ts.idleTimeout = site.IdleTimeout\n\t\t}\n\n\t\t// copy tsig secrets\n\t\tfor key, secret := range site.TsigSecret {\n\t\t\ts.tsigSecret[key] = secret\n\t\t}\n\n\t\t// compile custom plugin for everything\n\t\tvar stack plugin.Handler\n\t\tfor i := len(site.Plugin) - 1; i >= 0; i-- {\n\t\t\tstack = site.Plugin[i](stack)\n\n\t\t\t// register the *handler* also\n\t\t\tsite.registerHandler(stack)\n\n\t\t\t// If the current plugin is a MetadataCollector, bookmark it for later use. This loop traverses the plugin\n\t\t\t// list backwards, so the first MetadataCollector plugin wins.\n\t\t\tif mdc, ok := stack.(MetadataCollector); ok {\n\t\t\t\tsite.metaCollector = mdc\n\t\t\t}\n\n\t\t\tif s.trace == nil && stack.Name() == \"trace\" {\n\t\t\t\t// we have to stash away the plugin, not the\n\t\t\t\t// Tracer object, because the Tracer won't be initialized yet\n\t\t\t\tif t, ok := stack.(trace.Trace); ok {\n\t\t\t\t\ts.trace = t\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Unblock CH class queries when any of these plugins are loaded.\n\t\t\tif _, ok := EnableChaos[stack.Name()]; ok {\n\t\t\t\ts.classChaos = true\n\t\t\t}\n\t\t}\n\t\tsite.pluginChain = stack\n\t}\n\n\tif !s.debug {\n\t\t// When reloading we need to explicitly disable debug logging if it is now disabled.\n\t\tlog.D.Clear()\n\t}\n\n\treturn s, nil\n}", "func startHttpServer(conn connectors.Clients) *http.Server {\n\n\t// set the server props\n\tsrv := &http.Server{Addr: \":\" + os.Getenv(\"SERVER_PORT\")}\n\n\t// set the router and endpoints\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"/api/v1/streamdata\", func(w http.ResponseWriter, req *http.Request) {\n\t\thandlers.StreamHandler(w, req, conn)\n\t}).Methods(\"POST\", \"OPTIONS\")\n\n\tr.HandleFunc(\"/api/v2/sys/info/isalive\", handlers.IsAlive).Methods(\"GET\", \"OPTIONS\")\n\n\thttp.Handle(\"/\", r)\n\n\t// start our server (concurrent)\n\tif err := srv.ListenAndServe(); err != nil {\n\t\tconn.Error(\"Httpserver: ListenAndServe() error: %v\", err)\n\t\tos.Exit(0)\n\t}\n\n\t// return our srv object\n\treturn srv\n}", "func NewServer(\n\taddr string,\n\tcontrollerNS string,\n\tidentityTrustDomain string,\n\tenableH2Upgrade bool,\n\tenableEndpointSlices bool,\n\tk8sAPI *k8s.API,\n\tmetadataAPI *k8s.MetadataAPI,\n\tclusterStore *watcher.ClusterStore,\n\tclusterDomain string,\n\tdefaultOpaquePorts map[uint32]struct{},\n\tshutdown <-chan struct{},\n) (*grpc.Server, error) {\n\tlog := logging.WithFields(logging.Fields{\n\t\t\"addr\": addr,\n\t\t\"component\": \"server\",\n\t})\n\n\t// Initialize indexers that are used across watchers\n\terr := watcher.InitializeIndexers(k8sAPI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tendpoints, err := watcher.NewEndpointsWatcher(k8sAPI, metadataAPI, log, enableEndpointSlices, \"local\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\topaquePorts, err := watcher.NewOpaquePortsWatcher(k8sAPI, log, defaultOpaquePorts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprofiles, err := watcher.NewProfileWatcher(k8sAPI, log)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tservers, err := watcher.NewServerWatcher(k8sAPI, log)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsrv := server{\n\t\tpb.UnimplementedDestinationServer{},\n\t\tendpoints,\n\t\topaquePorts,\n\t\tprofiles,\n\t\tservers,\n\t\tclusterStore,\n\t\tenableH2Upgrade,\n\t\tcontrollerNS,\n\t\tidentityTrustDomain,\n\t\tclusterDomain,\n\t\tdefaultOpaquePorts,\n\t\tk8sAPI,\n\t\tmetadataAPI,\n\t\tlog,\n\t\tshutdown,\n\t}\n\n\ts := prometheus.NewGrpcServer()\n\t// linkerd2-proxy-api/destination.Destination (proxy-facing)\n\tpb.RegisterDestinationServer(s, &srv)\n\treturn s, nil\n}", "func DTLSServer(conn net.Conn, config *Config) *Conn {\n\tc := &Conn{config: config, isDTLS: true, conn: conn}\n\tc.init()\n\treturn c\n}", "func StartServer(ctx context.Context, t SimpleTB, debugMode bool) (client.Client, *net.UDPAddr) {\n\tmetrics := landns.NewMetrics(\"landns\")\n\tdyn, err := landns.NewSqliteResolver(\":memory:\", metrics)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to make sqlite resolver: %s\", err)\n\t}\n\n\ts := &landns.Server{\n\t\tMetrics: metrics,\n\t\tDynamicResolver: dyn,\n\t\tResolvers: dyn,\n\t\tDebugMode: debugMode,\n\t}\n\n\tapiAddr := &net.TCPAddr{IP: net.ParseIP(\"127.0.0.1\"), Port: FindEmptyPort()}\n\tdnsAddr := &net.UDPAddr{IP: net.ParseIP(\"127.0.0.1\"), Port: 3553}\n\tgo func() {\n\t\tif err := s.ListenAndServe(ctx, apiAddr, dnsAddr, \"udp\"); err != nil {\n\t\t\tt.Fatalf(\"failed to start server: %s\", err)\n\t\t}\n\t}()\n\n\tu, err := url.Parse(fmt.Sprintf(\"http://%s/api/v1/\", apiAddr))\n\tif err != nil {\n\t\tt.Fatalf(\"failed to parse URL: %s\", err)\n\t}\n\n\ttime.Sleep(10 * time.Millisecond) // wait for start server\n\n\treturn client.New(u), dnsAddr\n}", "func init() {\r\n// get the arguments to run the server\r\n\tflag.StringVar(&Host,\"httpserver\",DEFAULT_HOST,\"name of HTTP server\")\r\n\tflag.IntVar(&Port,\"port\",DEFAULT_PORT,\"port number\")\r\n\tflag.StringVar(&UrlPath,\"urlpath\",DEFAULT_URLPATH,\"relative url path\")\r\n\tflag.StringVar(&SecretKey,\"key\",DEFAULT_KEY,\"secret key to terminate program via TCP/UDP port\")\r\n\tflag.BoolVar(&isVerbose,\"verbose\",false,\"enable verbose logging output\")\r\n\tflag.Parse()\r\n\tlogger.Print(\"Starting servers on Port:\"+strconv.Itoa(Port)+\" HTTP-server:\"+Host+\" urlpath:\"+UrlPath+\" Key:\"+SecretKey)\r\n\tinitConf()\r\n}", "func Init() {\n\tlog.Debug().Caller().Msg(\"initialize server\")\n\tr := router()\n\tr.Run()\n}", "func Init(c *conf.Config, s *service.Service) {\n\tsrv = s\n\t// init inner router\n\teng := bm.DefaultServer(c.BM)\n\tinitRouter(eng)\n\t// init inner server\n\tif err := eng.Start(); err != nil {\n\t\tlog.Error(\"bm.DefaultServer error(%v)\", err)\n\t\tpanic(err)\n\t}\n}", "func (s *Server) Init(c Configuration) (o *Server, err error) {\n\to = s\n\n\t// Init UDP server\n\tif err = o.serverUDP.Init(c); err != nil {\n\t\treturn\n\t}\n\n\t// Init HTTP server\n\tif err = o.serverHTTP.Init(c); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func (client *LANHostConfigManagement1) SetDNSServer(NewDNSServers string) (err error) {\n\treturn client.SetDNSServerCtx(context.Background(),\n\t\tNewDNSServers,\n\t)\n}", "func StartServer(listener net.Listener, dsServer *DSServer) *grpc.Server {\n\tserver := grpc.NewServer()\n\tds_grpc.RegisterDSServiceServer(server, dsServer)\n\n\tgo func() {\n\t\tdsServer.isStarted = true\n\t\tif err := server.Serve(listener); err != nil {\n\t\t\tpanic(err) // should not happen during running application, after start\n\t\t}\n\t}()\n\n\treturn server\n}", "func initServer() {\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"/consumables\", consumablesListHandler).Methods(\"GET\")\n\trouter.HandleFunc(\"/consumables\", optionsHandler).Methods(\"OPTIONS\")\n\trouter.HandleFunc(\"/consumables\", consumablesCreateHandler).Methods(\"POST\")\n\trouter.HandleFunc(\"/ingest\", optionsHandler).Methods(\"OPTIONS\")\n\trouter.HandleFunc(\"/ingest\", ingestHandler).Methods(\"POST\")\n\trouter.HandleFunc(\"/status/now\", statusHandler).Methods(\"GET\")\n\trouter.HandleFunc(\"/status/time\", statusTimeHandler).Methods(\"GET\")\n\thttp.Handle(\"/\", router)\n\thttp.ListenAndServe(fmt.Sprintf(\":%s\", os.Getenv(\"CAFFEINE_PORT\")), nil)\n}", "func (s *DnsServer) Run() error {\n\tmux := dns.NewServeMux()\n\tfor _, domain := range s.Domains {\n\t\tmux.HandleFunc(dns.Fqdn(domain), s.HandleIncoming)\n\t}\n\ts.dnsServer = &dns.Server{Handler: mux}\n\ts.dnsServer.Net = \"udp\"\n\tif s.Flags.Listener != nil {\n\t\ts.dnsServer.Listener = s.Flags.Listener\n\t\ts.dnsServer.Addr = s.Flags.Listener.Addr().String()\n\t} else {\n\t\tl, err := net.Listen(net.JoinHostPort(s.host, strconv.Itoa(s.Port)), \"tcp\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ts.dnsServer.Listener = l\n\t}\n\tif s.Port != 0 {\n\t\ts.dnsServer.Addr = net.JoinHostPort(s.host, strconv.Itoa(s.Port))\n\t}\n\tgo s.HandleControllers()\n\ts.Logger.Infof(\"Serving Dns on %s for domains %v\", s.dnsServer.Addr, s.Domains )\n\treturn s.dnsServer.ListenAndServe()\n}", "func (s *Server) initListener() error {\n\tlistener, err := net.Listen(\"tcp\", s.cfg.ProxyServer.Addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.listener = listener\n\treturn nil\n}", "func dInit() error {\n\tvar err error\n\tdial, err = grpc.Dial(address, grpc.WithInsecure(), grpc.WithTimeout(10*time.Second))\n\tif err != nil {\n\t\tgrpclog.Printf(\"Fail to dial: %v\", err)\n\t\treturn err\n\t}\n\n\tdemoClient = NewDemonstratorClient(dial)\n\treturn nil\n}", "func Init(c *conf.Config) {\n\tinitService(c)\n\t// init inner router\n\tengine := bm.DefaultServer(c.HTTPServer)\n\tinnerRouter(engine)\n\t// init inner server\n\tif err := engine.Start(); err != nil {\n\t\tlog.Error(\"engine.Start error(%v)\", err)\n\t\tpanic(err)\n\t}\n}", "func InitializeServer(host string) (server *network.WebServer) {\n\trand.Seed(time.Now().UTC().UnixNano())\n\t// Make sure folders exist that we want:\n\tif err := ensureBindDirs(); err != nil {\n\t\tLog.Error(\"Failed to have home working dir to put the files into at ~/Desktop/bind, err: \", err)\n\t} else {\n\t\tLog.Info(\"bind dirs ensured!\")\n\t}\n\tif os.Args[0] != \"d\" { //development mode\n\t\tgin.SetMode(gin.ReleaseMode)\n\t}\n\tr := gin.New()\n\tr.LoadHTMLGlob(\"public/tmpl/*.html\")\n\tr.StaticFS(\"/videos\", http.Dir(basePath+\"/videos\"))\n\tr.StaticFS(\"/frames\", http.Dir(basePath+\"/frames\"))\n\tr.Static(\"/public\", \"./public\")\n\tr.GET(\"/\", getIndex)\n\tr.POST(\"/g\", postIndex)\n\tr.GET(\"/g\", getIndex)\n\tr.GET(\"/about\", getAbout)\n\tr.GET(\"/jobs\", getJobs)\n\tr.GET(\"/code\", getCode)\n\tmel = melody.New() // melody middleware\n\n\t// websocket route\n\tr.GET(\"/ws\",func(ctx *gin.Context){\n\t\t// handle request with Melody\n\t\tmel.HandleRequest(ctx.Writer,ctx.Request)\n\t})\n\n\t// Melody message handler\n\tmel.HandleMessage(func(ses *melody.Session,msg []byte){\n\t\t// broadcast message to connected sockets\n\t\tmel.Broadcast(msg)\n\t})\n\n\n\tr.GET(\"/openframes\", func(c *gin.Context) {\n\t\topen.Run(basePath + \"/frames\")\n\t})\n\tr.GET(\"/openvideos\", func(c *gin.Context) {\n\t\topen.Run(basePath + \"/videos\")\n\t})\n\tr.GET(\"/openlogs\", func(c *gin.Context) {\n\t\topen.Run(basePath + \"/logs\")\n\t})\n\tr.GET(\"/toggleClipYt\", func(c *gin.Context) {\n\t\topen.Run(basePath + \"/logs\")\n\t})\n\t// go requests(mel)\n\t// go jobUpdates(mel)\n\n\treturn network.InitializeWebServer(r, host)\n}", "func (ks *KerbServer) Init(srv string) error {\n\tservice := C.CString(srv)\n\tdefer C.free(unsafe.Pointer(service))\n\n\tresult := 0\n\n\tks.state = C.new_gss_server_state()\n\tif ks.state == nil {\n\t\treturn errors.New(\"Failed to allocate memory for gss_server_state\")\n\t}\n\n\tresult = int(C.authenticate_gss_server_init(service, ks.state))\n\n\tif result == C.AUTH_GSS_ERROR {\n\t\treturn ks.GssError()\n\t}\n\n\treturn nil\n}", "func Init(d *db.Database, c config.Config) *Server {\n\tr := mux.NewRouter()\n\th := &http.Server{\n\t\tHandler: r,\n\t\tAddr: c.Web.Addr,\n\t\tWriteTimeout: 15 * time.Second,\n\t\tReadTimeout: 15 * time.Second,\n\t}\n\tsrv := &Server{\n\t\tDB: d,\n\t\trouter: r,\n\t\tHS: h,\n\t\tConfig: c,\n\t}\n\treturn srv\n}", "func init() {\r\n\r\n\tLog.LogShort(senderName, LM.CategorySYSTEM, LM.LevelINFO, LM.MessageNameSTARTUP, `Init the web server now.`)\r\n\tdefer Log.LogShort(senderName, LM.CategorySYSTEM, LM.LevelINFO, LM.MessageNameSTARTUP, `Done init the web server.`)\r\n\r\n\t// Public web server: use the servers public facing IP address and the configured port:\r\n\tserverPublicAddressPort = Tools.LocalIPAddressAndPort()\r\n\r\n\t// Private web server: use the configured end point:\r\n\tserverAdminAddressPort = ConfigurationDB.Read(`AdminWebServerBinding`)\r\n\r\n\t// Setup the public web server:\r\n\tserverPublic = &http.Server{}\r\n\tserverPublic.Addr = serverPublicAddressPort\r\n\tserverPublic.Handler = Handlers.GetPublicMux()\r\n\tserverPublic.SetKeepAlivesEnabled(true)\r\n\r\n\t// Public Web Server: Read Timeout\r\n\tif readTimeoutSeconds, errTimeout := strconv.Atoi(ConfigurationDB.Read(`PublicWebServerReadTimeoutSeconds`)); errTimeout != nil {\r\n\r\n\t\t// Case: Error! Use a default timeout:\r\n\t\tLog.LogFull(senderName, LM.CategorySYSTEM, LM.LevelWARN, LM.SeverityLow, LM.ImpactLow, LM.MessageNameCONFIGURATION, `Was not able to read the public server's read timeout value. Use the default of 10 seconds instead.`, errTimeout.Error())\r\n\t\tserverPublic.ReadTimeout = 10 * time.Second\r\n\t} else {\r\n\t\tLog.LogShort(senderName, LM.CategorySYSTEM, LM.LevelINFO, LM.MessageNameCONFIGURATION, fmt.Sprintf(\"The public web server's read timeout was set to %d seconds.\", readTimeoutSeconds))\r\n\t\tserverPublic.ReadTimeout = time.Duration(readTimeoutSeconds) * time.Second\r\n\t}\r\n\r\n\t// Public Web Server: Write Timeout\r\n\tif writeTimeoutSeconds, errTimeout := strconv.Atoi(ConfigurationDB.Read(`PublicWebServerWriteTimeoutSeconds`)); errTimeout != nil {\r\n\r\n\t\t// Case: Error! Use a default timeout:\r\n\t\tLog.LogFull(senderName, LM.CategorySYSTEM, LM.LevelWARN, LM.SeverityLow, LM.ImpactLow, LM.MessageNameCONFIGURATION, `Was not able to read the public server's write timeout value. Use the default of 10 seconds instead.`, errTimeout.Error())\r\n\t\tserverPublic.WriteTimeout = 10 * time.Second\r\n\t} else {\r\n\t\tLog.LogShort(senderName, LM.CategorySYSTEM, LM.LevelINFO, LM.MessageNameCONFIGURATION, fmt.Sprintf(\"The public web server's write timeout was set to %d seconds.\", writeTimeoutSeconds))\r\n\t\tserverPublic.WriteTimeout = time.Duration(writeTimeoutSeconds) * time.Second\r\n\t}\r\n\r\n\t// Public Web Server: Max. Header Size\r\n\tif maxHeaderBytes, errHeaderBytes := strconv.Atoi(ConfigurationDB.Read(`PublicWebServerMaxHeaderLenBytes`)); errHeaderBytes != nil {\r\n\r\n\t\t// Case: Error! Use a default threshold for the header size:\r\n\t\tLog.LogFull(senderName, LM.CategorySYSTEM, LM.LevelWARN, LM.SeverityLow, LM.ImpactLow, LM.MessageNameCONFIGURATION, `Was not able to read the public server's max. header size. Use the default of 1048576 bytes instead.`, errHeaderBytes.Error())\r\n\t\tserverPublic.MaxHeaderBytes = 1048576\r\n\t} else {\r\n\t\tLog.LogShort(senderName, LM.CategorySYSTEM, LM.LevelINFO, LM.MessageNameCONFIGURATION, fmt.Sprintf(\"The public web server's max. header size was set to %d bytes.\", maxHeaderBytes))\r\n\t\tserverPublic.MaxHeaderBytes = maxHeaderBytes\r\n\t}\r\n\r\n\t// Is TLS configured?\r\n\tif publicTLSEnabled := ConfigurationDB.Read(`PublicWebServerUseTLS`); strings.ToLower(publicTLSEnabled) == `true` {\r\n\r\n\t\t// TLS is enabled. Copy the certificate and private key to the source directory.\r\n\t\tpublicTLSCertificate := StaticFiles.FindAndReadFileINTERNAL(ConfigurationDB.Read(`PublicWebServerTLSCertificateName`))\r\n\t\tpublicTLSPrivateKey := StaticFiles.FindAndReadFileINTERNAL(ConfigurationDB.Read(`PublicWebServerTLSPrivateKey`))\r\n\r\n\t\t// Access to the working directory?\r\n\t\tcurrentDir, dirError := os.Getwd()\r\n\t\tif dirError != nil {\r\n\t\t\tLog.LogShort(senderName, LM.CategorySYSTEM, LM.LevelERROR, LM.MessageNameCONFIGURATION, `Was not able to read the working directory. Thus, cannot store the TLS certificates!`, dirError.Error())\r\n\t\t} else {\r\n\t\t\t// Build the filenames:\r\n\t\t\tpathCertificate := filepath.Join(currentDir, ConfigurationDB.Read(`PublicWebServerTLSCertificateName`))\r\n\t\t\tpathPrivateKey := filepath.Join(currentDir, ConfigurationDB.Read(`PublicWebServerTLSPrivateKey`))\r\n\r\n\t\t\t// Write the files:\r\n\t\t\tif writeError := ioutil.WriteFile(pathCertificate, publicTLSCertificate, 0660); writeError != nil {\r\n\t\t\t\tLog.LogShort(senderName, LM.CategorySYSTEM, LM.LevelERROR, LM.MessageNameCONFIGURATION, `Was not able to write the TLS certificate to the working directory.`, writeError.Error())\r\n\t\t\t}\r\n\t\t\tif writeError := ioutil.WriteFile(pathPrivateKey, publicTLSPrivateKey, 0660); writeError != nil {\r\n\t\t\t\tLog.LogShort(senderName, LM.CategorySYSTEM, LM.LevelERROR, LM.MessageNameCONFIGURATION, `Was not able to write the TLS private key to the working directory.`, writeError.Error())\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// Is the private web server (i.e. administration server) enabled?\r\n\tif strings.ToLower(ConfigurationDB.Read(`AdminWebServerEnabled`)) == `true` {\r\n\r\n\t\t// Setup the private web server:\r\n\t\tserverAdmin = &http.Server{}\r\n\t\tserverAdmin.Addr = serverAdminAddressPort\r\n\t\tserverAdmin.Handler = Handlers.GetAdminMux()\r\n\t\tserverAdmin.SetKeepAlivesEnabled(true)\r\n\r\n\t\t// Admin Web Server: Read Timeout\r\n\t\tif readTimeoutSeconds, errTimeout := strconv.Atoi(ConfigurationDB.Read(`AdminWebServerReadTimeoutSeconds`)); errTimeout != nil {\r\n\r\n\t\t\t// Case: Error! Use a default timeout:\r\n\t\t\tLog.LogFull(senderName, LM.CategorySYSTEM, LM.LevelWARN, LM.SeverityLow, LM.ImpactLow, LM.MessageNameCONFIGURATION, `Was not able to read the admin server's read timeout value. Use the default of 10 seconds instead.`, errTimeout.Error())\r\n\t\t\tserverAdmin.ReadTimeout = 10 * time.Second\r\n\t\t} else {\r\n\t\t\tLog.LogShort(senderName, LM.CategorySYSTEM, LM.LevelINFO, LM.MessageNameCONFIGURATION, fmt.Sprintf(\"The admin web server's read timeout was set to %d seconds.\", readTimeoutSeconds))\r\n\t\t\tserverAdmin.ReadTimeout = time.Duration(readTimeoutSeconds) * time.Second\r\n\t\t}\r\n\r\n\t\t// Admin Web Server: Write Timeout\r\n\t\tif writeTimeoutSeconds, errTimeout := strconv.Atoi(ConfigurationDB.Read(`AdminWebServerWriteTimeoutSeconds`)); errTimeout != nil {\r\n\r\n\t\t\t// Case: Error! Use a default timeout:\r\n\t\t\tLog.LogFull(senderName, LM.CategorySYSTEM, LM.LevelWARN, LM.SeverityLow, LM.ImpactLow, LM.MessageNameCONFIGURATION, `Was not able to read the admin server's write timeout value. Use the default of 10 seconds instead.`, errTimeout.Error())\r\n\t\t\tserverAdmin.WriteTimeout = 10 * time.Second\r\n\t\t} else {\r\n\t\t\tLog.LogShort(senderName, LM.CategorySYSTEM, LM.LevelINFO, LM.MessageNameCONFIGURATION, fmt.Sprintf(\"The admin web server's write timeout was set to %d seconds.\", writeTimeoutSeconds))\r\n\t\t\tserverAdmin.WriteTimeout = time.Duration(writeTimeoutSeconds) * time.Second\r\n\t\t}\r\n\r\n\t\t// Admin Web Server: Max. Header Size\r\n\t\tif maxHeaderBytes, errHeaderBytes := strconv.Atoi(ConfigurationDB.Read(`AdminWebServerMaxHeaderLenBytes`)); errHeaderBytes != nil {\r\n\r\n\t\t\t// Case: Error! Use a default threshold for the header size:\r\n\t\t\tLog.LogFull(senderName, LM.CategorySYSTEM, LM.LevelWARN, LM.SeverityLow, LM.ImpactLow, LM.MessageNameCONFIGURATION, `Was not able to read the admin server's max. header size. Use the default of 1048576 bytes instead.`, errHeaderBytes.Error())\r\n\t\t\tserverAdmin.MaxHeaderBytes = 1048576\r\n\t\t} else {\r\n\t\t\tLog.LogShort(senderName, LM.CategorySYSTEM, LM.LevelINFO, LM.MessageNameCONFIGURATION, fmt.Sprintf(\"The admin web server's max. header size was set to %d bytes.\", maxHeaderBytes))\r\n\t\t\tserverAdmin.MaxHeaderBytes = maxHeaderBytes\r\n\t\t}\r\n\r\n\t\t// Is TLS configured?\r\n\t\tif adminTLSEnabled := ConfigurationDB.Read(`AdminWebServerUseTLS`); strings.ToLower(adminTLSEnabled) == `true` {\r\n\r\n\t\t\t// TLS is enabled. Copy the certificate and private key to the source directory.\r\n\t\t\tadminTLSCertificate := StaticFiles.FindAndReadFileINTERNAL(ConfigurationDB.Read(`AdminWebServerTLSCertificateName`))\r\n\t\t\tadminTLSPrivateKey := StaticFiles.FindAndReadFileINTERNAL(ConfigurationDB.Read(`AdminWebServerTLSPrivateKey`))\r\n\r\n\t\t\t// Access to the working directory?\r\n\t\t\tcurrentDir, dirError := os.Getwd()\r\n\t\t\tif dirError != nil {\r\n\t\t\t\tLog.LogShort(senderName, LM.CategorySYSTEM, LM.LevelERROR, LM.MessageNameCONFIGURATION, `Was not able to read the working directory. Thus, cannot store the TLS certificates!`, dirError.Error())\r\n\t\t\t} else {\r\n\t\t\t\t// Build the filenames:\r\n\t\t\t\tpathCertificate := filepath.Join(currentDir, ConfigurationDB.Read(`AdminWebServerTLSCertificateName`))\r\n\t\t\t\tpathPrivateKey := filepath.Join(currentDir, ConfigurationDB.Read(`AdminWebServerTLSPrivateKey`))\r\n\r\n\t\t\t\t// Write the files:\r\n\t\t\t\tif writeError := ioutil.WriteFile(pathCertificate, adminTLSCertificate, 0660); writeError != nil {\r\n\t\t\t\t\tLog.LogShort(senderName, LM.CategorySYSTEM, LM.LevelERROR, LM.MessageNameCONFIGURATION, `Was not able to write the TLS certificate to the working directory.`, writeError.Error())\r\n\t\t\t\t}\r\n\t\t\t\tif writeError := ioutil.WriteFile(pathPrivateKey, adminTLSPrivateKey, 0660); writeError != nil {\r\n\t\t\t\t\tLog.LogShort(senderName, LM.CategorySYSTEM, LM.LevelERROR, LM.MessageNameCONFIGURATION, `Was not able to write the TLS private key to the working directory.`, writeError.Error())\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t} else {\r\n\t\t// Private web server is disabled:\r\n\t\tLog.LogShort(senderName, LM.CategorySYSTEM, LM.LevelINFO, LM.MessageNameSTARTUP, `The admin web server is disabled.`)\r\n\t}\r\n}", "func New(backend Backend,domains[]string ,addr,ipMonitorPath string,forwardNameServers []string, subDomainServers map[string][]string,cacheSize int ,random,hold bool) *server {\n\ts := new (server)\n\ts. backend = backend\n\ttimeOut := 30 * time.Second\n\ts.dnsUDPclient= &dns.Client{Net: \"udp\", ReadTimeout: timeOut, WriteTimeout: timeOut, SingleInflight: true}\n\ts.dnsTCPclient= &dns.Client{Net: \"tcp\", ReadTimeout: timeOut, WriteTimeout: timeOut, SingleInflight: true}\n\ts.dnsDomains = domains[:]\n\ts.dnsAddr = addr\n\ts.ipMonitorPath= ipMonitorPath\n\ts.msgPool = queue.QueueNew()\n\ts.msgPool.Reset = cacheMsgRest\n\ts.syncPeriod = 10 * time.Minute\n\ts.minTtl = 60\n\ts.rcache = NewMsgCache(cacheSize,random, hold,s.minTtl)\n\ts.forwardNameServers = forwardNameServers[:]\n\ts.subDomainServers = subDomainServers\n\treturn s\n}", "func (s *Server) init() (err error) {\n\tif err = s.Close(); err != nil {\n\t\treturn\n\t}\n\n\tif s.Hostname == \"\" {\n\t\tif s.Hostname, err = os.Hostname(); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}", "func New(ctx context.Context, opts ...Option) *Server {\n\tctx, span := trace.StartSpan(ctx, \"server_init\")\n\tdefer span.End()\n\n\tlog := common.Logger(ctx)\n\tengine := gin.New()\n\ts := &Server{\n\t\tRouter: engine,\n\t\tAdminRouter: engine,\n\t\tsvcConfigs: map[string]*http.Server{\n\t\t\tWebServer: &http.Server{\n\t\t\t\tMaxHeaderBytes: getEnvInt(EnvMaxHeaderSize, http.DefaultMaxHeaderBytes),\n\t\t\t\tReadHeaderTimeout: getEnvDuration(EnvReadHeaderTimeout, 0),\n\t\t\t\tReadTimeout: getEnvDuration(EnvReadTimeout, 0),\n\t\t\t\tWriteTimeout: getEnvDuration(EnvWriteTimeout, 0),\n\t\t\t\tIdleTimeout: getEnvDuration(EnvHTTPIdleTimeout, 0),\n\t\t\t},\n\t\t\tAdminServer: &http.Server{},\n\t\t\tGRPCServer: &http.Server{},\n\t\t},\n\t\t// MUST initialize these before opts\n\t\tappListeners: new(appListeners),\n\t\tfnListeners: new(fnListeners),\n\t\ttriggerListeners: new(triggerListeners),\n\n\t\t// Almost everything else is configured through opts (see NewFromEnv for ex.) or below\n\t}\n\n\tfor _, opt := range opts {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\terr := opt(ctx, s)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Fatal(\"Error during server opt initialization.\")\n\t\t}\n\t}\n\n\tif s.svcConfigs[WebServer].Addr == \"\" {\n\t\ts.svcConfigs[WebServer].Addr = fmt.Sprintf(\":%d\", DefaultPort)\n\t}\n\tif s.svcConfigs[AdminServer].Addr == \"\" {\n\t\ts.svcConfigs[AdminServer].Addr = fmt.Sprintf(\":%d\", DefaultPort)\n\t}\n\tif s.svcConfigs[GRPCServer].Addr == \"\" {\n\t\ts.svcConfigs[GRPCServer].Addr = fmt.Sprintf(\":%d\", DefaultGRPCPort)\n\t}\n\n\trequireConfigSet := func(id string, val interface{}) {\n\t\tif val == nil {\n\t\t\tlog.Fatalf(\"Invalid configuration for server type %s, %s must be configured during startup\", s.nodeType, id)\n\t\t}\n\t}\n\trequireConfigNotSet := func(id string, val interface{}) {\n\t\tif val != nil {\n\t\t\tlog.Fatalf(\"Invalid configuration for server type %s, %s must not be configured during startup\", s.nodeType, id)\n\t\t}\n\t}\n\n\t// Check that WithAgent options have been processed correctly.\n\t// Yuck the yuck - server should really be split into several interfaces (LB, Runner, API) and each should be instantiated separately\n\tswitch s.nodeType {\n\tcase ServerTypeAPI:\n\t\trequireConfigNotSet(\"agent\", s.agent)\n\t\trequireConfigSet(\"datastore\", s.datastore)\n\t\trequireConfigSet(\"triggerAnnotator\", s.triggerAnnotator)\n\tcase ServerTypeFull:\n\t\trequireConfigSet(\"agent\", s.agent)\n\t\trequireConfigSet(\"lbReadAccess\", s.lbReadAccess)\n\t\trequireConfigSet(\"datastore\", s.datastore)\n\t\trequireConfigSet(\"triggerAnnotator\", s.triggerAnnotator)\n\n\tcase ServerTypeLB:\n\t\trequireConfigSet(\"lbReadAccess\", s.lbReadAccess)\n\t\trequireConfigSet(\"agent\", s.agent)\n\n\tcase ServerTypePureRunner:\n\t\trequireConfigSet(\"agent\", s.agent)\n\n\tdefault:\n\n\t\tlog.Fatal(\"unknown server type %d\", s.nodeType)\n\n\t}\n\n\ts.Router.Use(loggerWrap, traceWrap) // TODO should be opts\n\toptionalCorsWrap(s.Router) // TODO should be an opt\n\tapiMetricsWrap(s)\n\t// panicWrap is last, specifically so that logging, tracing, cors, metrics, etc wrappers run\n\ts.Router.Use(panicWrap)\n\ts.AdminRouter.Use(panicWrap)\n\ts.bindHandlers(ctx)\n\n\treturn s\n}", "func setupServer() (*http.Server, error) {\n\t// get parameters and initialize the server\n\thost := os.Getenv(\"MESSAGES_SERVER_HOST\")\n\tport := os.Getenv(\"MESSAGES_SERVER_PORT\")\n\tif host == \"\" || port == \"\" {\n\t\treturn nil, errors.New(\"main: host or port not set\")\n\t}\n\t// make sure port is a number\n\tintPort, err := strconv.ParseInt(port, 10, 64)\n\tif err != nil {\n\t\treturn nil, errors.New(\"port must be a number\")\n\t}\n\n\tserver := &http.Server{\n\t\tAddr: fmt.Sprintf(\"%s:%d\", host, intPort),\n\t\tHandler: api.Container,\n\t}\n\treturn server, nil\n}", "func InitLDAP(config map[string]string) {\n\tldapServer = config[\"url\"]\n\tbaseDN = config[\"baseDN\"]\n\tlog.Debugf(\"Initialized Ldap server: %s with baseDN: %s\", ldapServer, baseDN)\n}", "func NewServer(logger zerolog.Logger, l listing.Service, s storemanagement.Service,\n\tauth authetication.Service, addr string) Server {\n\tif l == nil || s == nil || auth == nil || addr == \"\" {\n\t\tlog.Println(\"Unable to start server because services were not configured\")\n\t\tos.Exit(1)\n\t}\n\n\trouter := chi.NewRouter()\n\tserver := Server{\n\t\tlisting: l,\n\t\tsManager: s,\n\t\trouter: router,\n\t\tauth: auth,\n\t\tServer: &http.Server{\n\t\t\tAddr: addr,\n\t\t\tHandler: router,\n\t\t},\n\t}\n\trouter.Use(httplog.RequestLogger(logger))\n\tserver.Routes()\n\treturn server\n}", "func NewServer(addr net.Addr, opts ...DebugOption) serverz.Server {\n\to := newOptions(opts...)\n\n\tif o.debug {\n\t\t// This is probably okay, as this service should not be exposed to public in the first place.\n\t\ttrace.SetAuth(trace.NoAuth)\n\n\t\texpvar.RegisterRoutes(o.handler)\n\t\tpprof.RegisterRoutes(o.handler)\n\t\ttrace.RegisterRoutes(o.handler)\n\t}\n\n\treturn &serverz.AppServer{\n\t\tServer: &http.Server{\n\t\t\tHandler: o.handler,\n\t\t\tErrorLog: stdlog.New(log.NewStdlibAdapter(level.Error(log.With(o.logger, \"server\", \"debug\"))), \"\", 0),\n\t\t},\n\t\tName: \"debug\",\n\t\tAddr: addr,\n\t\tLogger: o.logger,\n\t}\n}", "func initialiseServer() {\n\tport := \":8090\"\n\tlog.Printf(\"Starting HTTP server at http://localhost:%s\", port)\n\n\t// Attach request handlers\n\thttp.HandleFunc(\"/api/v1/vehicles\", liveDataRequestHandler)\n\thttp.HandleFunc(\"/health\", healthEndpoint)\n\thttp.HandleFunc(\"/\", healthEndpoint)\n\n\t// Start HTTP server\n\tlog.Fatal(http.ListenAndServe(port, nil))\n}", "func InitServer(store *store.Store) *Handler {\n\th := &Handler{Store: store}\n\th.Router = echo.New()\n\n\treturn h\n}", "func InitClient() (*Client, error) {\n\tconn, err := net.Dial(\"udp\", *dnsServerAddrFlagVal)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Client{\n\t\tconn: conn,\n\t\trespBuf: make([]byte, maxUDPMsgSize),\n\t}, nil\n}", "func InitServer(svc *service.Service) *echo.Echo {\n\tmapper := mapper.New()\n\tsvm := service.NewServiceManager()\n\tsrv := echo.New()\n\n\tuserService := svm.UserService(svc)\n\thealthCheckService := svm.HealthCheckService(svc)\n\tcloudVisionService := svm.CloudVisionService(svc)\n\tuploadService := svm.UploadService(svc, cloudVisionService)\n\n\t//CORS\n\tsrv.Use(middleware.CORSWithConfig(middleware.CORSConfig{\n\t\tAllowOrigins: []string{\"*\"},\n\t\tAllowMethods: []string{echo.GET, echo.HEAD, echo.PUT, echo.PATCH, echo.POST, echo.DELETE},\n\t}))\n\n\treturn setupRoutes(srv, &controller{\n\t\tpingController: pingroute.NewController(),\n\t\tuserController: userroute.NewController(userService, mapper),\n\t\tuploadController: uploadroute.NewController(uploadService),\n\t\thealthcheckController: healthcheckroute.NewController(healthCheckService, mapper),\n\t})\n}", "func init() {\n\tprometheus.MustRegister(uptime, reqCount, reqCountPerEndpoint, userCPU, systemCPU, memUsage, diskUsage)\n\tinitStat, err := stat.GetServerStat()\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\tgo recordServerMetrics(initStat)\n}", "func startServer() error {\n\n\tc, err := config()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// checking if a router is defined\n\tif cfgRouter == nil {\n\t\treturn ErrNoRouterConfig\n\t}\n\n\t// HTTPS Server\n\tcfgServer := http.Server{}\n\tcfgServer.Addr = fmt.Sprint(\":\", c.Server.HTTPPort)\n\n\t//TODO write own cors middleware\n\tcorsManager := cors.New(cors.Options{\n\t\tAllowCredentials: true,\n\t\tAllowedOrigins: []string{\"http://localhost:8080\"},\n\t\tAllowedMethods: []string{\"GET\", \"POST\", \"PUT\", \"DELETE\"},\n\t\tAllowedHeaders: []string{\"Authorization\", \"Origin\", \"Cache-Control\", \"Accept\", \"Content-Type\", \"X-Requested-With\"},\n\t\tDebug: true,\n\t})\n\n\t//\tcfgRouter.Handler()\n\tcfgServer.Handler = corsManager.Handler(cfgRouter.Handler())\n\t//cfgServer.Handler = cfgRouter.Handler()\n\n\terr = cfgServer.ListenAndServe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer cfgServer.Close()\n\n\treturn nil\n}", "func newServer(ctx context.Context, dexDir string, port int32, environment string, ldap *ldaptest.TestLDAP) (*TestDex, error) {\n\tcertFile, keyFile := ssltest.CreateCertificates(\"localhost\", dexDir)\n\treturn newServerWithTLS(ctx, certFile, keyFile, port, environment, ldap)\n}", "func NewServer(options *Options) (s Server, err error) {\n\tdefer Logger.Time(time.Now(), time.Second, \"NewServer\")\n\tdbs := make(map[string]kadiyadb.Database)\n\tsrv := &server{\n\t\toptions: options,\n\t\tdatabases: dbs,\n\t}\n\n\terr = os.MkdirAll(options.Path, DataPerm)\n\tif err != nil {\n\t\treturn nil, goerr.Wrap(err, 0)\n\t}\n\n\tfiles, err := ioutil.ReadDir(options.Path)\n\tif err != nil {\n\t\treturn nil, goerr.Wrap(err, 0)\n\t}\n\n\tnow := time.Now().UnixNano()\n\tfields := []string{`¯\\_(ツ)_/¯`}\n\n\tfor _, finfo := range files {\n\t\tfname := finfo.Name()\n\t\tdbPath := path.Join(options.Path, fname)\n\n\t\tif fname == InitFile {\n\t\t\tcontinue\n\t\t}\n\n\t\tdb, err := kadiyadb.Open(dbPath, options.Recovery)\n\t\tif err != nil {\n\t\t\tLogger.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tinfo, err := db.Info()\n\t\tif err != nil {\n\t\t\tLogger.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar i uint32\n\t\tfor i = 0; i < info.MaxRWEpochs; i++ {\n\t\t\tii64 := int64(i)\n\t\t\tstart := now - ii64*info.Duration\n\t\t\tend := start + info.Resolution\n\n\t\t\t// this will trigger a epoch load\n\t\t\t// also acts as a db health check\n\t\t\t_, err = db.One(start, end, fields)\n\t\t\tif err != nil {\n\n\t\t\t\tif err := db.Close(); err != nil {\n\t\t\t\t\tLogger.Error(err)\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tdbs[fname] = db\n\t}\n\n\treturn srv, nil\n}", "func InitServer(srv *server.Server, opt Options) {\n\tpb.RegisterRecorderServer(srv.PRPC, &pb.DecoratedRecorder{\n\t\tService: &recorderServer{Options: &opt},\n\t\tPrelude: internal.CommonPrelude,\n\t\tPostlude: internal.CommonPostlude,\n\t})\n}", "func (g *GateKeeper) initSSHServer() error {\n\tif g.srv != nil {\n\t\treturn errors.New(\"SSH server already initialized\")\n\t}\n\taddr := fmt.Sprintf(\"%s:%d\", g.Meta.SSHAddr, g.Meta.SSHPort)\n\tserver := ssh.Server{\n\t\tAddr: addr,\n\t\tHandler: ssh.Handler(g.proxyCommandHandler()),\n\t\tReversePortForwardingCallback: ssh.ReversePortForwardingCallback(g.reversePortForwardHandler()),\n\t}\n\tg.srv = &server\n\tlog.Info().\n\t\tStr(\"addr\", g.Meta.SSHAddr).\n\t\tUint16(\"port\", g.Meta.SSHPort).\n\t\tMsg(\"starting SSH server\")\n\treturn server.ListenAndServe()\n}", "func NewServer(routinesPool *safe.Pool, entryPoints TCPEntryPoints, entryPointsUDP UDPEntryPoints, watcher *ConfigurationWatcher,\n\tchainBuilder *middleware.ChainBuilder, accessLoggerMiddleware *accesslog.Handler,\n) *Server {\n\tsrv := &Server{\n\t\twatcher: watcher,\n\t\ttcpEntryPoints: entryPoints,\n\t\tchainBuilder: chainBuilder,\n\t\taccessLoggerMiddleware: accessLoggerMiddleware,\n\t\tsignals: make(chan os.Signal, 1),\n\t\tstopChan: make(chan bool, 1),\n\t\troutinesPool: routinesPool,\n\t\tudpEntryPoints: entryPointsUDP,\n\t}\n\n\tsrv.configureSignals()\n\n\treturn srv\n}", "func (g *Server) Start() error {\n\tif len(g.registrars) == 0 {\n\t\treturn errors.New(\"No registration method added. impossible to boot\")\n\t}\n\tlisten, err := net.Listen(\"tcp\", \":\"+g.config.Port)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// The code below is to bootstrap a multiplexed server\n\t// this is necessary to create healthcheck endpoint from regular LoadBalancers\n\t// as they generate only use HTTP or TCP\n\n\t// creating multiplexed server\n\tmux := cmux.New(listen)\n\n\t// Matching connections by priority order\n\tgrpcListener := mux.Match(cmux.HTTP2HeaderField(\"content-type\", \"application/grpc\"))\n\t// used for health checks\n\thttpListener := mux.Match(cmux.Any())\n\n\t// initiating grpc server\n\tgrpcServer := grpc.NewServer()\n\t// registering handlers\n\tfor _, r := range g.registrars {\n\t\tr(grpcServer)\n\t}\n\treflection.Register(grpcServer)\n\n\t// creating http server\n\thttpServer := http.NewServeMux()\n\thttpServer.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintf(w, \"OK\")\n\t})\n\n\thttpS := &http.Server{\n\t\tHandler: httpServer,\n\t}\n\n\t// starting it all\n\tgo grpcServer.Serve(grpcListener)\n\tgo httpS.Serve(httpListener)\n\t// will periodically free memory if set\n\tif g.config.PeriodicMemory > 0 {\n\t\tgo g.PeriodicFree(g.config.PeriodicMemory)\n\t}\n\n\t// Start serving...\n\treturn mux.Serve()\n}", "func Init(c *conf.Config, s *service.Service) {\n\trelationSvc = s\n\tverify = v.New(c.Verify)\n\tanti = antispam.New(c.Antispam)\n\taddFollowingRate = rate.New(c.AddFollowingRate)\n\t// init inner router\n\tengine := bm.DefaultServer(c.BM)\n\tsetupInnerEngine(engine)\n\tif err := engine.Start(); err != nil {\n\t\tlog.Error(\"engine.Start() error(%v)\", err)\n\t\tpanic(err)\n\t}\n}", "func NewServer(setupSocket string) (*Server, error) {\n p := path.Join(os.TempDir(), setupSocket)\n conn, err := net.ListenUnixgram(udsType, &net.UnixAddr{p, udsType})\n if err != nil {\n return nil, fmt.Errorf(\"could not listen on domain socket %q: %s\", setupSocket, err)\n }\n\n s := &Server{setupConn: conn, registry: make(map[string]*register, 1)}\n\n return s, nil\n}", "func NewServer(config domain.ServerConfig) *Server {\n\tdebugger := logger.New(log.New(ioutil.Discard, \"\", 0))\n\tif config.Debug {\n\t\tdebugger = logger.New(log.New(os.Stderr, \"[debug] \", log.Flags()|log.Lshortfile))\n\t}\n\n\tdb, err := bolt.Open(config.BoltPath, 0644, nil)\n\tif err != nil {\n\t\tlog.Fatal(\"failed to start bolt db\")\n\t}\n\tdefer db.Close()\n\n\ts := &Server{\n\t\tConfig: config,\n\t\ti: uc.NewInteractor(\n\t\t\tconfig,\n\t\t\tcookies.New(config.CookieAge),\n\t\t\tdebugger,\n\t\t\tresources.New(encoder.New()),\n\t\t\thttpCaller.New(),\n\t\t\tmail.New(domain.EmailConfig{}),\n\t\t\tpathInfo.New(config),\n\t\t\tencoder.New(),\n\t\t\tsparql.New(),\n\t\t\tpages.New(config.DataRoot),\n\t\t\ttokenStorer.New(db),\n\t\t\tdomain.URIHandler{},\n\t\t\tuuid.New(),\n\t\t\tauthentication.New(httpCaller.New()),\n\t\t\tspkac.New(),\n\t\t),\n\t\tlogger: debugger,\n\t\tcookieManager: cookies.New(config.CookieAge),\n\t\tpathInformer: pathInfo.New(config),\n\t\turiManipulator: domain.URIHandler{},\n\t}\n\n\tmime.AddRDFExtension(s.Config.ACLSuffix)\n\tmime.AddRDFExtension(s.Config.MetaSuffix)\n\n\ts.logger.Debug(\"---- starting server ----\")\n\ts.logger.Debug(\"config: %#v\\n\", s.Config)\n\treturn s\n}", "func (as *ArgocdServer) Init() error {\n\tfor _, f := range []func() error{\n\t\tas.initClientSet,\n\t\tas.initTLSConfig,\n\t\tas.initRegistry,\n\t\tas.initDiscovery,\n\t\tas.initMicro,\n\t\tas.initHTTPService,\n\t\tas.initProxyAgent,\n\t\t//as.initMetric,\n\t} {\n\t\tif err := f(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *WServer) Start() error {\n\tl, err := net.Listen(\"tcp\", fmt.Sprintf(\":%v\", s.srv.Port))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuseTLS := func() bool {\n\t\tif len(s.certFile) > 0 && len(s.keyFile) > 0 {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}()\n\tsvcInfo := &wconsul.SvcInfo{\n\t\tID: s.srv.UniqID,\n\t\tName: s.srv.Name,\n\t\tHost: s.srv.Host,\n\t\tPort: s.srv.Port,\n\t\tTags: append([]string{}, s.srv.Tags...),\n\t\tChecker: wconsul.NewGrpcSvcCheck(s.srv.Host, s.srv.Port, \"5s\", \"3s\", useTLS),\n\t}\n\tif err := wconsul.SvcRegistration(svcInfo); err != nil {\n\t\t// s.Server.Stop()\n\t\txlog.Warn(\"===> WServer.Start.SvcRegistration uniqID=%v err=%v\", s.srv.UniqID, err)\n\t}\n\tdefer func() {\n\t\txlog.Info(\"===> WServer.Start.SvcDeregistration uniqID=%v ready\", svcInfo.ID)\n\t\twconsul.SvcDeregistration(svcInfo.ID)\n\t}()\n\n\tregistHealthSvc(s.Server)\n\treflection.Register(s.Server)\n\n\treturn s.Serve(l)\n}", "func InitializeHTTPServer(cfg *HTTPServerConfig) (*http.Server, error) {\n\t// create http server\n\tsrv := &http.Server{\n\t\tAddr: string(cfg.HTTPServerAddr),\n\t\tHandler: cfg.Router,\n\t}\n\n\treturn srv, nil\n}", "func SetupServer(opts Options) (\n\twwrSrv *Server,\n\thttpServer *http.Server,\n\taddr string,\n\trunFunc func() error,\n\terr error,\n) {\n\twwrSrv = NewServer(opts)\n\n\t// Initialize HTTP server\n\thttpServer = &http.Server{\n\t\tAddr: opts.Addr,\n\t\tHandler: wwrSrv,\n\t}\n\n\t// Determine final address\n\taddr = httpServer.Addr\n\tif addr == \"\" {\n\t\taddr = \":http\"\n\t}\n\n\t// Initialize TCP/IP listener\n\tlistener, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn nil, nil, \"\", nil, fmt.Errorf(\"Failed setting up TCP/IP listener: %s\", err)\n\t}\n\n\trunFunc = func() (err error) {\n\t\t// Launch server\n\t\terr = httpServer.Serve(\n\t\t\ttcpKeepAliveListener{listener.(*net.TCPListener)},\n\t\t)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"HTTP Server failure: %s\", err)\n\t\t}\n\t\treturn nil\n\t}\n\n\taddr = listener.Addr().String()\n\n\treturn wwrSrv, httpServer, addr, runFunc, nil\n}", "func NewServer(dev Device, loc *url.URL) (*Server, error) {\n\taddr, err := net.ResolveUDPAddr(\"udp\", MulticastIPv4Addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Server{dev: dev, loc: loc, addr: addr}, nil\n}", "func (g *authzProxyDaemon) Init(ctx context.Context) error {\n\treturn g.athenz.Init(ctx)\n}", "func NewSdns(cfg SdnsConfig) (s Sdns, err error) {\n\tif cfg.Port == 0 {\n\t\terr = errors.Errorf(\"a port must be specified\")\n\t\treturn\n\t}\n\n\tif cfg.Debug {\n\t\ts.logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr})\n\t} else {\n\t\ts.logger = zerolog.New(os.Stderr)\n\t}\n\n\terr = s.Load(cfg)\n\tif err != nil {\n\t\terr = errors.Wrapf(err,\n\t\t\t\"couldn't load internal configurations using config supplied.\")\n\t\treturn\n\t}\n\n\ts.client = &dns.Client{SingleInflight: true}\n\ts.recursors = cfg.Recursors\n\ts.address = fmt.Sprintf(\"%s:%d\", cfg.Address, cfg.Port)\n\n\treturn\n}", "func (s *Server) InitRouters(d *config.Daemon) {\n\ts.addRouter(host.NewRouter(d))\n\t//s.addRouter(xxx.NewRouter(d))\n}", "func (s *Server) Init() {\n\tif s.isInitialized {\n\t\tpanic(ErrAlreadyInitialized)\n\t}\n\n\t// If the repos are still missing, use the default implementation: AWS\n\tif s.options.documentRepo == nil || s.options.projectRepo == nil {\n\t\ts.With(AWS(\"eu-west-1\"))\n\t}\n\n\ts.projectHandler = project.Handler{\n\t\tProjectRepository: s.options.projectRepo,\n\t\tDocumentRepository: s.options.documentRepo,\n\t}\n\n\ts.documentHandler = document.Handler{\n\t\tDocumentRepository: s.options.documentRepo,\n\t}\n\n\t// Create router.\n\ts.router = chi.NewRouter()\n\n\t// Add middlewares.\n\ts.router.Use(cors.Handler(cors.Options{\n\t\tAllowedOrigins: []string{\"*\"},\n\t\tAllowedMethods: []string{\"GET\", \"POST\", \"PUT\", \"DELETE\", \"OPTIONS\"},\n\t\tAllowedHeaders: []string{\"*\"},\n\t\tExposedHeaders: []string{\"Link\"},\n\t\tAllowCredentials: false,\n\t\tMaxAge: 300, // Maximum value not ignored by any of major browsers\n\t}))\n\ts.router.Use(middleware.Logger)\n\n\t// Add routes.\n\ts.setupRoutes()\n\ts.isInitialized = true\n}", "func newServer(listenAddrs []string) (*server, error) {\n\tlogin := cfg.Username + \":\" + cfg.Password\n\tauth := \"Basic \" + base64.StdEncoding.EncodeToString([]byte(login))\n\ts := server{\n\t\tauthsha: sha256.Sum256([]byte(auth)),\n\t}\n\n\t// Check for existence of cert file and key file\n\tif !fileExists(cfg.RPCKey) && !fileExists(cfg.RPCCert) {\n\t\t// if both files do not exist, we generate them.\n\t\terr := genCertPair(cfg.RPCCert, cfg.RPCKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tkeypair, err := tls.LoadX509KeyPair(cfg.RPCCert, cfg.RPCKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttlsConfig := tls.Config{\n\t\tCertificates: []tls.Certificate{keypair},\n\t}\n\n\tipv4ListenAddrs, ipv6ListenAddrs, err := parseListeners(listenAddrs)\n\tlisteners := make([]net.Listener, 0,\n\t\tlen(ipv6ListenAddrs)+len(ipv4ListenAddrs))\n\tfor _, addr := range ipv4ListenAddrs {\n\t\tlistener, err := tls.Listen(\"tcp4\", addr, &tlsConfig)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"RPCS: Can't listen on %s: %v\", addr,\n\t\t\t\terr)\n\t\t\tcontinue\n\t\t}\n\t\tlisteners = append(listeners, listener)\n\t}\n\n\tfor _, addr := range ipv6ListenAddrs {\n\t\tlistener, err := tls.Listen(\"tcp6\", addr, &tlsConfig)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"RPCS: Can't listen on %s: %v\", addr,\n\t\t\t\terr)\n\t\t\tcontinue\n\t\t}\n\t\tlisteners = append(listeners, listener)\n\t}\n\tif len(listeners) == 0 {\n\t\treturn nil, errors.New(\"no valid listen address\")\n\t}\n\n\ts.listeners = listeners\n\n\treturn &s, nil\n}", "func StartServer(lis net.Listener) (*Server, func(), error) {\n\tif lis == nil {\n\t\tvar err error\n\t\tlis, err = net.Listen(\"tcp\", \"localhost:0\")\n\t\tif err != nil {\n\t\t\treturn nil, func() {}, fmt.Errorf(\"net.Listen() failed: %v\", err)\n\t\t}\n\t}\n\n\ts := NewServer(lis.Addr().String())\n\twp := &wrappedListener{\n\t\tListener: lis,\n\t\tserver: s,\n\t}\n\n\tserver := grpc.NewServer()\n\tv3lrsgrpc.RegisterLoadReportingServiceServer(server, s)\n\tv3discoverygrpc.RegisterAggregatedDiscoveryServiceServer(server, s)\n\tgo server.Serve(wp)\n\n\treturn s, func() { server.Stop() }, nil\n}", "func Init() error {\n\tconfigServerURL, err := GetConfigServerEndpoint()\n\tif err != nil {\n\t\topenlog.Warn(\"can not get config server endpoint: \" + err.Error())\n\t\treturn err\n\t}\n\n\tvar enableSSL bool\n\ttlsConfig, tlsError := getTLSForClient(configServerURL)\n\tif tlsError != nil {\n\t\topenlog.Error(fmt.Sprintf(\"Get %s.%s TLS config failed, err:[%s]\",\n\t\t\tconfigServerName, common.Consumer, tlsError.Error()))\n\t\treturn tlsError\n\t}\n\n\t/*This condition added because member discovery can have multiple ip's with IsHTTPS\n\thaving both true and false value.*/\n\tif tlsConfig != nil {\n\t\tenableSSL = true\n\t}\n\n\tinterval := config.GetConfigServerConf().RefreshInterval\n\tif interval == 0 {\n\t\tinterval = 30\n\t}\n\n\terr = initConfigServer(configServerURL, enableSSL, tlsConfig, interval)\n\tif err != nil {\n\t\topenlog.Error(\"failed to init config server: \" + err.Error())\n\t\treturn err\n\t}\n\n\topenlog.Warn(\"config server init success\")\n\treturn nil\n}", "func init() {\n\tif e, ok := os.LookupEnv(EnvConsul); ok && e != \"\" {\n\t\tconsulAddr = e\n\t}\n\tif consulAddr == \"--\" {\n\t\treturn\n\t}\n\tif consulAddr == \"-\" || (env.InTest() && consulAddr == localConsulAdr) {\n\t\tnoConsulTestMode()\n\t\treturn\n\t}\n\tif _, _, err := net.SplitHostPort(consulAddr); err != nil {\n\t\tconsulAddr = consulAddr + \":8500\"\n\t}\n\tif e, ok := os.LookupEnv(EnvFederatedDcs); ok {\n\t\tfederatedDcs = strings.Fields(e)\n\t}\n\trand.Seed(time.Now().UTC().UnixNano())\n\n\tmustConnect()\n\tupdateEnv()\n}", "func startHttpServer(s *Server, cfg *HttpConfig) (hs *http.Server, err error) {\n\n\tlogger := s.log // promlog.New(&cfg.promlogConfig)\n\n\thttpServer := &http.Server{\n\t\tAddr: cfg.Listen,\n\t\tHandler: nil,\n\t\tReadTimeout: 5 * time.Second,\n\t\tWriteTimeout: 5 * time.Second,\n\t\tMaxHeaderBytes: 1 << 13,\n\t}\n\thttpServer.RegisterOnShutdown(func() {\n\t\tlogger.Debugf(\"Http Server shutdown at %v\\n\", time.Now())\n\t})\n\n\tgo func() {\n\t\terr := httpServer.ListenAndServe()\n\t\tif err != http.ErrServerClosed {\n\t\t\tlogger.Printf(\"Http Server fatal error: %v\\n\", err)\n\t\t\ts.Shutdown()\n\t\t}\n\t}()\n\treturn httpServer, nil\n}", "func NewDSServer(keeper *Keeper) *DSServer {\n\treturn &DSServer{\n\t\tkeeper: keeper,\n\t}\n}", "func InitWebServer() {\n\thttp.ListenAndServe(\":8080\", initRouter())\n}", "func (g *Gateway) init(bootstrap bool) error {\n\tlogger.Debugf(\"Initializing database gateway\")\n\tg.stopCh = make(chan struct{})\n\n\tinfo, err := loadInfo(g.db, g.networkCert)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to create raft factory: %w\", err)\n\t}\n\n\tdir := filepath.Join(g.db.Dir(), \"global\")\n\tif shared.PathExists(filepath.Join(dir, \"logs.db\")) {\n\t\treturn fmt.Errorf(\"Unsupported upgrade path, please first upgrade to LXD 4.0\")\n\t}\n\n\t// If the resulting raft instance is not nil, it means that this node\n\t// should serve as database node, so create a dqlite driver possibly\n\t// exposing it over the network.\n\tif info != nil {\n\t\t// Use the autobind feature of abstract unix sockets to get a\n\t\t// random unused address.\n\t\tlistener, err := net.Listen(\"unix\", \"\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to autobind unix socket: %w\", err)\n\t\t}\n\n\t\tg.bindAddress = listener.Addr().String()\n\t\t_ = listener.Close()\n\n\t\toptions := []dqlite.Option{\n\t\t\tdqlite.WithBindAddress(g.bindAddress),\n\t\t}\n\n\t\tif info.Address == \"1\" {\n\t\t\tif info.ID != 1 {\n\t\t\t\tpanic(\"unexpected server ID\")\n\t\t\t}\n\n\t\t\tg.memoryDial = dqliteMemoryDial(g.bindAddress)\n\t\t\tg.store.inMemory = client.NewInmemNodeStore()\n\t\t\terr = g.store.Set(context.Background(), []client.NodeInfo{info.NodeInfo})\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed setting node info in store: %w\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tgo runDqliteProxy(g.stopCh, g.bindAddress, g.acceptCh)\n\t\t\tg.store.inMemory = nil\n\t\t\toptions = append(options, dqlite.WithDialFunc(g.raftDial()))\n\t\t}\n\n\t\tserver, err := dqlite.New(\n\t\t\tinfo.ID,\n\t\t\tinfo.Address,\n\t\t\tdir,\n\t\t\toptions...,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to create dqlite server: %w\", err)\n\t\t}\n\n\t\t// Force the correct configuration into the bootstrap node, this is needed\n\t\t// when the raft node already has log entries, in which case a regular\n\t\t// bootstrap fails, resulting in the node containing outdated configuration.\n\t\tif bootstrap {\n\t\t\tlogger.Debugf(\"Bootstrap database gateway ID:%v Address:%v\",\n\t\t\t\tinfo.ID, info.Address)\n\t\t\tcluster := []dqlite.NodeInfo{\n\t\t\t\t{ID: uint64(info.ID), Address: info.Address},\n\t\t\t}\n\n\t\t\terr = server.Recover(cluster)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed to recover database state: %w\", err)\n\t\t\t}\n\t\t}\n\n\t\terr = server.Start()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to start dqlite server: %w\", err)\n\t\t}\n\n\t\tg.lock.Lock()\n\t\tg.server = server\n\t\tg.info = info\n\t\tg.lock.Unlock()\n\t} else {\n\t\tg.lock.Lock()\n\t\tg.server = nil\n\t\tg.info = nil\n\t\tg.store.inMemory = nil\n\t\tg.lock.Unlock()\n\t}\n\n\tg.lock.Lock()\n\tg.store.onDisk = client.NewNodeStore(\n\t\tg.db.DB(), \"main\", \"raft_nodes\", \"address\")\n\tg.lock.Unlock()\n\n\treturn nil\n}", "func (s *Server) Initialize(log logging.Logger, factory logging.Factory, host string, port uint16) {\n\ts.log = log\n\ts.factory = factory\n\ts.listenAddress = fmt.Sprintf(\"%s:%d\", host, port)\n\ts.router = newRouter()\n}", "func InitializeServer(wg *sync.WaitGroup) {\n\n\tServerLoggerInitialize(\"seelog.xml\")\n\n\tConfigInitialize(\"config.ini\")\n\n\tHandlerInitialize()\n\n\tWorkerInitialize()\n\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\t//초기화 완료 처리\n\twg.Done()\n}", "func init() {\n\tlis = bufconn.Listen(bufSize)\n\tlog.Println(\"server is started\")\n\tserver := grpc.NewServer()\n\tapi.RegisterUserServiceServer(server, &GRPCServer{})\n\n\tdbConnection := postgres.OpenDataBaseConnection()\n\tpostgres.StorageInstance = postgres.NewStorage(dbConnection)\n\tgo func() {\n\t\tif err := server.Serve(lis); err != nil {\n\t\t\tlog.Fatalf(\"Server exited with error: %v\", err)\n\t\t}\n\t}()\n}", "func (instance *DBSyncSlave) init() {\n\tif nil != instance {\n\t\tif len(instance.Config.Uuid) > 0 {\n\t\t\tinstance.UID = instance.Config.Uuid\n\t\t} else {\n\t\t\tinstance.UID, _ = lygo_sys.ID()\n\t\t}\n\t\tif nil == instance.client {\n\t\t\tinstance.client = lygo_nio.NewNioClient(instance.Config.Host(), instance.Config.Port())\n\t\t\tinstance.client.OnConnect(instance.doConnect)\n\t\t\tinstance.client.OnDisconnect(instance.doDisconnect)\n\t\t}\n\t}\n}", "func (srv *Server) initAPI(addr string) {\n\tmux := http.NewServeMux()\n\n\t// 404 Calls\n\thandleHTTPRequest(mux, \"/\", srv.unrecognizedCallHandler)\n\n\t// Consensus API Calls\n\thandleHTTPRequest(mux, \"/consensus/status\", srv.consensusStatusHandler)\n\thandleHTTPRequest(mux, \"/consensus/synchronize\", srv.consensusSynchronizeHandler)\n\n\t// Daemon API Calls\n\thandleHTTPRequest(mux, \"/daemon/stop\", srv.daemonStopHandler)\n\thandleHTTPRequest(mux, \"/daemon/updates/apply\", srv.daemonUpdatesApplyHandler)\n\thandleHTTPRequest(mux, \"/daemon/updates/check\", srv.daemonUpdatesCheckHandler)\n\n\t// Debugging API Calls\n\thandleHTTPRequest(mux, \"/debug/constants\", srv.debugConstantsHandler)\n\thandleHTTPRequest(mux, \"/debug/mutextest\", srv.mutexTestHandler)\n\n\t// Gateway API Calls\n\thandleHTTPRequest(mux, \"/gateway/status\", srv.gatewayStatusHandler)\n\thandleHTTPRequest(mux, \"/gateway/peers/add\", srv.gatewayPeersAddHandler)\n\thandleHTTPRequest(mux, \"/gateway/peers/remove\", srv.gatewayPeersRemoveHandler)\n\n\t// Host API Calls\n\thandleHTTPRequest(mux, \"/host/announce\", srv.hostAnnounceHandler)\n\thandleHTTPRequest(mux, \"/host/configure\", srv.hostConfigureHandler)\n\thandleHTTPRequest(mux, \"/host/status\", srv.hostStatusHandler)\n\n\t// HostDB API Calls\n\thandleHTTPRequest(mux, \"/hostdb/hosts/active\", srv.hostdbHostsActiveHandler)\n\thandleHTTPRequest(mux, \"/hostdb/hosts/all\", srv.hostdbHostsAllHandler)\n\n\t// Miner API Calls\n\thandleHTTPRequest(mux, \"/miner/start\", srv.minerStartHandler)\n\thandleHTTPRequest(mux, \"/miner/status\", srv.minerStatusHandler)\n\thandleHTTPRequest(mux, \"/miner/stop\", srv.minerStopHandler)\n\thandleHTTPRequest(mux, \"/miner/blockforwork\", srv.minerBlockforworkHandler) // Deprecated\n\thandleHTTPRequest(mux, \"/miner/submitblock\", srv.minerSubmitblockHandler) // Deprecated\n\thandleHTTPRequest(mux, \"/miner/headerforwork\", srv.minerHeaderforworkHandler)\n\thandleHTTPRequest(mux, \"/miner/submitheader\", srv.minerSubmitheaderHandler)\n\n\t// Renter API Calls\n\thandleHTTPRequest(mux, \"/renter/downloadqueue\", srv.renterDownloadqueueHandler)\n\thandleHTTPRequest(mux, \"/renter/files/delete\", srv.renterFilesDeleteHandler)\n\thandleHTTPRequest(mux, \"/renter/files/download\", srv.renterFilesDownloadHandler)\n\thandleHTTPRequest(mux, \"/renter/files/list\", srv.renterFilesListHandler)\n\thandleHTTPRequest(mux, \"/renter/files/load\", srv.renterFilesLoadHandler)\n\thandleHTTPRequest(mux, \"/renter/files/loadascii\", srv.renterFilesLoadAsciiHandler)\n\thandleHTTPRequest(mux, \"/renter/files/rename\", srv.renterFilesRenameHandler)\n\thandleHTTPRequest(mux, \"/renter/files/share\", srv.renterFilesShareHandler)\n\thandleHTTPRequest(mux, \"/renter/files/shareascii\", srv.renterFilesShareAsciiHandler)\n\thandleHTTPRequest(mux, \"/renter/files/upload\", srv.renterFilesUploadHandler)\n\thandleHTTPRequest(mux, \"/renter/status\", srv.renterStatusHandler) // TODO: alter\n\n\t// TransactionPool API Calls\n\thandleHTTPRequest(mux, \"/transactionpool/transactions\", srv.transactionpoolTransactionsHandler)\n\n\t// Wallet API Calls\n\thandleHTTPRequest(mux, \"/wallet/address\", srv.walletAddressHandler)\n\thandleHTTPRequest(mux, \"/wallet/send\", srv.walletSendHandler)\n\thandleHTTPRequest(mux, \"/wallet/status\", srv.walletStatusHandler)\n\n\t// create graceful HTTP server\n\tsrv.apiServer = &graceful.Server{\n\t\tTimeout: apiTimeout,\n\t\tServer: &http.Server{Addr: addr, Handler: mux},\n\t}\n}", "func (m *Manager) startNorthboundServer() error {\n\ts := northbound.NewServer(northbound.NewServerCfg(\n\t\tm.Config.CAPath,\n\t\tm.Config.KeyPath,\n\t\tm.Config.CertPath,\n\t\tint16(m.Config.GRPCPort),\n\t\ttrue,\n\t\tnorthbound.SecurityConfig{}))\n\n\tif m.Config.AtomixClient == nil {\n\t\tm.Config.AtomixClient = client.NewClient()\n\t}\n\n\ttopoStore, err := store.NewAtomixStore(m.Config.AtomixClient)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.AddService(logging.Service{})\n\ts.AddService(service.NewService(topoStore))\n\n\tdoneCh := make(chan error)\n\tgo func() {\n\t\terr := s.Serve(func(started string) {\n\t\t\tlog.Info(\"Started NBI on \", started)\n\t\t\tclose(doneCh)\n\t\t})\n\t\tif err != nil {\n\t\t\tdoneCh <- err\n\t\t}\n\t}()\n\treturn <-doneCh\n}", "func NewServer(diagSet *Set) *Server {\n\tif diagSet == nil {\n\t\tdiagSet = DefaultDiagSet\n\t}\n\treturn &Server{ds: diagSet}\n}", "func InitServer(svc *service.Service) *gin.Engine {\n\tmapper := mapper.New()\n\tsvm := service.NewServiceManager()\n\tsrv := gin.Default()\n\n\tqrcodeService := svm.QRCodeService(svc)\n\tuserService := svm.UserService(svc)\n\tsafraService := svm.SafraService(svc)\n\n\tsrv.Use(cors.Default())\n\n\treturn setupRoutes(srv, &controller{\n\t\tpingController: pingroute.NewController(),\n\t\tqrcodeController: qrcoderoute.NewController(qrcodeService, mapper),\n\t\tuserController: userroute.NewController(userService, mapper),\n\t\tsafraController: safraroute.NewController(safraService),\n\t})\n}", "func StartServer() {\n\tif server == nil {\n\t\tGetInstance()\n\t}\n\n\tlog.Println(\"starting server on http://localhost\" + defaultPort)\n\tserver.Run(defaultPort)\n}", "func InitClient(host string, port string, prefix string, globalTags []string) error {\n\tvar err error\n\t// WithMaxBytesPerPayload optimal value is 1432, stacktrace is bigger than that, so remove it for keeping safe\n\tc, err = statsd.New(host+\":\"+port, statsd.WithMaxBytesPerPayload(maxBytesPerPayload))\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.Tags = append(c.Tags, globalTags...)\n\tc.Namespace = prefix + \".\"\n\tc.Incr(\"server_start\", []string(nil), 1)\n\treturn nil\n}", "func NewServer(aggregator *aggregator.BufferedAggregator) (*Server, error) {\n\tvar stats *util.Stats\n\tif config.Datadog.GetBool(\"dogstatsd_stats_enable\") == true {\n\t\tbuff := config.Datadog.GetInt(\"dogstatsd_stats_buffer\")\n\t\ts, err := util.NewStats(uint32(buff))\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Dogstatsd: unable to start statistics facilities\")\n\t\t}\n\t\tstats = s\n\t\tdogstatsdExpvars.Set(\"PacketsLastSecond\", &dogstatsdPacketsLastSec)\n\t}\n\n\tvar metricsStatsEnabled uint64 // we're using an uint64 for its atomic capacity\n\tif config.Datadog.GetBool(\"dogstatsd_metrics_stats_enable\") == true {\n\t\tlog.Info(\"Dogstatsd: metrics statistics will be stored.\")\n\t\tmetricsStatsEnabled = 1\n\t}\n\n\tpacketsChannel := make(chan listeners.Packets, config.Datadog.GetInt(\"dogstatsd_queue_size\"))\n\ttmpListeners := make([]listeners.StatsdListener, 0, 2)\n\n\t// sharedPacketPool is used by the packet assembler to retrieve already allocated\n\t// buffer in order to avoid allocation. The packets are pushed back by the server.\n\tsharedPacketPool := listeners.NewPacketPool(config.Datadog.GetInt(\"dogstatsd_buffer_size\"))\n\n\tsocketPath := config.Datadog.GetString(\"dogstatsd_socket\")\n\tif len(socketPath) > 0 {\n\t\tunixListener, err := listeners.NewUDSListener(packetsChannel, sharedPacketPool)\n\t\tif err != nil {\n\t\t\tlog.Errorf(err.Error())\n\t\t} else {\n\t\t\ttmpListeners = append(tmpListeners, unixListener)\n\t\t}\n\t}\n\tif config.Datadog.GetInt(\"dogstatsd_port\") > 0 {\n\t\tudpListener, err := listeners.NewUDPListener(packetsChannel, sharedPacketPool)\n\t\tif err != nil {\n\t\t\tlog.Errorf(err.Error())\n\t\t} else {\n\t\t\ttmpListeners = append(tmpListeners, udpListener)\n\t\t}\n\t}\n\n\tpipeName := config.Datadog.GetString(\"dogstatsd_windows_pipe_name\")\n\tif len(pipeName) > 0 {\n\t\tnamedPipeListener, err := listeners.NewNamedPipeListener(pipeName, packetsChannel, sharedPacketPool)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"named pipe error: %v\", err.Error())\n\t\t} else {\n\t\t\ttmpListeners = append(tmpListeners, namedPipeListener)\n\t\t}\n\t}\n\n\tif len(tmpListeners) == 0 {\n\t\treturn nil, fmt.Errorf(\"listening on neither udp nor socket, please check your configuration\")\n\t}\n\n\t// check configuration for custom namespace\n\tmetricPrefix := config.Datadog.GetString(\"statsd_metric_namespace\")\n\tif metricPrefix != \"\" && !strings.HasSuffix(metricPrefix, \".\") {\n\t\tmetricPrefix = metricPrefix + \".\"\n\t}\n\tmetricPrefixBlacklist := config.Datadog.GetStringSlice(\"statsd_metric_namespace_blacklist\")\n\n\tdefaultHostname, err := util.GetHostname()\n\tif err != nil {\n\t\tlog.Errorf(\"Dogstatsd: unable to determine default hostname: %s\", err.Error())\n\t}\n\n\thistToDist := config.Datadog.GetBool(\"histogram_copy_to_distribution\")\n\thistToDistPrefix := config.Datadog.GetString(\"histogram_copy_to_distribution_prefix\")\n\n\textraTags := config.Datadog.GetStringSlice(\"dogstatsd_tags\")\n\n\tentityIDPrecedenceEnabled := config.Datadog.GetBool(\"dogstatsd_entity_id_precedence\")\n\n\ts := &Server{\n\t\tStarted: true,\n\t\tStatistics: stats,\n\t\tpacketsIn: packetsChannel,\n\t\tsharedPacketPool: sharedPacketPool,\n\t\taggregator: aggregator,\n\t\tlisteners: tmpListeners,\n\t\tstopChan: make(chan bool),\n\t\thealth: health.RegisterLiveness(\"dogstatsd-main\"),\n\t\tmetricPrefix: metricPrefix,\n\t\tmetricPrefixBlacklist: metricPrefixBlacklist,\n\t\tdefaultHostname: defaultHostname,\n\t\thistToDist: histToDist,\n\t\thistToDistPrefix: histToDistPrefix,\n\t\textraTags: extraTags,\n\t\ttelemetryEnabled: telemetry_utils.IsEnabled(),\n\t\tentityIDPrecedenceEnabled: entityIDPrecedenceEnabled,\n\t\tdisableVerboseLogs: config.Datadog.GetBool(\"dogstatsd_disable_verbose_logs\"),\n\t\tDebug: &dsdServerDebug{\n\t\t\tStats: make(map[ckey.ContextKey]metricStat),\n\t\t\tmetricsCounts: metricsCountBuckets{\n\t\t\t\tcounts: [5]uint64{0, 0, 0, 0, 0},\n\t\t\t\tmetricChan: make(chan struct{}),\n\t\t\t\tcloseChan: make(chan struct{}),\n\t\t\t},\n\t\t\tkeyGen: ckey.NewKeyGenerator(),\n\t\t},\n\t}\n\n\t// packets forwarding\n\t// ----------------------\n\n\tforwardHost := config.Datadog.GetString(\"statsd_forward_host\")\n\tforwardPort := config.Datadog.GetInt(\"statsd_forward_port\")\n\tif forwardHost != \"\" && forwardPort != 0 {\n\t\tforwardAddress := fmt.Sprintf(\"%s:%d\", forwardHost, forwardPort)\n\t\tcon, err := net.Dial(\"udp\", forwardAddress)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"Could not connect to statsd forward host : %s\", err)\n\t\t} else {\n\t\t\ts.packetsIn = make(chan listeners.Packets, config.Datadog.GetInt(\"dogstatsd_queue_size\"))\n\t\t\tgo s.forwarder(con, packetsChannel)\n\t\t}\n\t}\n\n\t// start the workers processing the packets read on the socket\n\t// ----------------------\n\n\ts.handleMessages()\n\n\t// start the debug loop\n\t// ----------------------\n\n\tif metricsStatsEnabled == 1 {\n\t\ts.EnableMetricsStats()\n\t}\n\n\t// map some metric name\n\t// ----------------------\n\n\tcacheSize := config.Datadog.GetInt(\"dogstatsd_mapper_cache_size\")\n\n\tmappings, err := config.GetDogstatsdMappingProfiles()\n\tif err != nil {\n\t\tlog.Warnf(\"Could not parse mapping profiles: %v\", err)\n\t} else if len(mappings) != 0 {\n\t\tmapperInstance, err := mapper.NewMetricMapper(mappings, cacheSize)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"Could not create metric mapper: %v\", err)\n\t\t} else {\n\t\t\ts.mapper = mapperInstance\n\t\t}\n\t}\n\treturn s, nil\n}", "func Init() *Server {\n\ts := &Server{\n\t\t&goserver.GoServer{},\n\t\t0,\n\t}\n\treturn s\n}", "func StartHTTPServer(healthz http.HandlerFunc, port int, mux *http.ServeMux) error {\n\thttpSrv, err := buildServer(healthz, port, mux)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to prepare server prior to serving: %s\", err.Error())\n\t}\n\tlis, err := buildListener(port)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to prepare net.listener prior to serving: %s\", err.Error())\n\t}\n\treturn httpSrv.Serve(*lis)\n}" ]
[ "0.6577117", "0.61836004", "0.58856076", "0.5873448", "0.58571017", "0.5849781", "0.58205044", "0.5788006", "0.5765969", "0.5757338", "0.57560205", "0.57468", "0.5746392", "0.57075214", "0.5705852", "0.56903404", "0.5686891", "0.56743336", "0.5671335", "0.5657342", "0.56538653", "0.5646904", "0.56295526", "0.5591786", "0.55871993", "0.5569353", "0.55399513", "0.5537839", "0.55328166", "0.5530941", "0.5524769", "0.5492583", "0.54920727", "0.5488693", "0.5473374", "0.54700714", "0.5453051", "0.54346335", "0.5428007", "0.540884", "0.54080945", "0.5406098", "0.53952324", "0.5387264", "0.5384138", "0.5382628", "0.5375872", "0.5374102", "0.5360617", "0.5357242", "0.53429866", "0.5334781", "0.5327673", "0.53239185", "0.5322616", "0.53173476", "0.5303496", "0.52995014", "0.52955544", "0.5294501", "0.52897274", "0.52889633", "0.52863264", "0.5284668", "0.5275343", "0.52620727", "0.5257614", "0.5255664", "0.52541274", "0.5251027", "0.523429", "0.5231276", "0.5228843", "0.52268225", "0.52118057", "0.5204468", "0.51942104", "0.5190443", "0.51863986", "0.5182038", "0.5180406", "0.51796335", "0.51734513", "0.51727754", "0.5169849", "0.516597", "0.5165743", "0.5164224", "0.5163836", "0.515523", "0.51490307", "0.5142616", "0.51400465", "0.5138427", "0.5132764", "0.51209575", "0.5116223", "0.5114109", "0.5114099", "0.5112505" ]
0.7915286
0
checkIfBackupInNewOrProgress check whether there are backups created by this schedule still in New or InProgress state
func (c *scheduleReconciler) checkIfBackupInNewOrProgress(schedule *velerov1.Schedule) bool { log := c.logger.WithField("schedule", kube.NamespaceAndName(schedule)) backupList := &velerov1.BackupList{} options := &client.ListOptions{ Namespace: schedule.Namespace, LabelSelector: labels.Set(map[string]string{ velerov1.ScheduleNameLabel: schedule.Name, }).AsSelector(), } err := c.List(context.Background(), backupList, options) if err != nil { log.Errorf("fail to list backup for schedule %s/%s: %s", schedule.Namespace, schedule.Name, err.Error()) return true } for _, backup := range backupList.Items { if backup.Status.Phase == velerov1.BackupPhaseNew || backup.Status.Phase == velerov1.BackupPhaseInProgress { log.Debugf("%s/%s still has backups that are in InProgress or New...", schedule.Namespace, schedule.Name) return true } } return false }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t *Task) hasBackupCompleted(backup *velero.Backup) (bool, []string) {\n\tcompleted := false\n\treasons := []string{}\n\tprogress := []string{}\n\n\tpvbs := t.getPodVolumeBackupsForBackup(backup)\n\n\tswitch backup.Status.Phase {\n\tcase velero.BackupPhaseNew:\n\t\tprogress = append(\n\t\t\tprogress,\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"Backup %s/%s: Not started\",\n\t\t\t\tbackup.Namespace,\n\t\t\t\tbackup.Name))\n\tcase velero.BackupPhaseInProgress:\n\t\titemsBackedUp, totalItems := getBackupStats(backup)\n\t\tprogress = append(\n\t\t\tprogress,\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"Backup %s/%s: %d out of estimated total of %d objects backed up%s\",\n\t\t\t\tbackup.Namespace,\n\t\t\t\tbackup.Name,\n\t\t\t\titemsBackedUp,\n\t\t\t\ttotalItems,\n\t\t\t\tgetBackupDuration(backup)))\n\t\tprogress = append(\n\t\t\tprogress,\n\t\t\tgetPodVolumeBackupsProgress(pvbs)...)\n\tcase velero.BackupPhaseCompleted:\n\t\tcompleted = true\n\t\titemsBackedUp, totalItems := getBackupStats(backup)\n\t\tprogress = append(\n\t\t\tprogress,\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"Backup %s/%s: %d out of estimated total of %d objects backed up%s\",\n\t\t\t\tbackup.Namespace,\n\t\t\t\tbackup.Name,\n\t\t\t\titemsBackedUp,\n\t\t\t\ttotalItems,\n\t\t\t\tgetBackupDuration(backup)))\n\t\tprogress = append(\n\t\t\tprogress,\n\t\t\tgetPodVolumeBackupsProgress(pvbs)...)\n\tcase velero.BackupPhaseFailed:\n\t\tcompleted = true\n\t\tmessage := fmt.Sprintf(\n\t\t\t\"Backup %s/%s: failed.\",\n\t\t\tbackup.Namespace,\n\t\t\tbackup.Name)\n\t\treasons = append(reasons, message)\n\t\titemsBackedUp, totalItems := getBackupStats(backup)\n\t\tmessage = fmt.Sprintf(\n\t\t\t\"%s %d out of estimated total of %d objects backed up%s\",\n\t\t\tmessage,\n\t\t\titemsBackedUp,\n\t\t\ttotalItems,\n\t\t\tgetBackupDuration(backup))\n\t\tprogress = append(progress, message)\n\t\tprogress = append(\n\t\t\tprogress,\n\t\t\tgetPodVolumeBackupsProgress(pvbs)...)\n\tcase velero.BackupPhasePartiallyFailed:\n\t\tcompleted = true\n\t\titemsBackedUp, totalItems := getBackupStats(backup)\n\t\tmessage := fmt.Sprintf(\n\t\t\t\"Backup %s/%s: partially failed. %d out of estimated total of %d objects backed up%s\",\n\t\t\tbackup.Namespace,\n\t\t\tbackup.Name,\n\t\t\titemsBackedUp,\n\t\t\ttotalItems,\n\t\t\tgetBackupDuration(backup))\n\t\tprogress = append(progress, message)\n\t\tprogress = append(\n\t\t\tprogress,\n\t\t\tgetPodVolumeBackupsProgress(pvbs)...)\n\tcase velero.BackupPhaseFailedValidation:\n\t\treasons = backup.Status.ValidationErrors\n\t\treasons = append(\n\t\t\treasons,\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"Backup %s/%s: validation failed.\",\n\t\t\t\tbackup.Namespace,\n\t\t\t\tbackup.Name))\n\t\tcompleted = true\n\t}\n\tt.Log.Info(\"Velero Backup progress report\",\n\t\t\"backup\", path.Join(backup.Namespace, backup.Name),\n\t\t\"backupProgress\", progress)\n\n\tt.setProgress(progress)\n\treturn completed, reasons\n}", "func backupScheduleFound(repo v1beta1.PGBackRestRepo, backupType string) bool {\n\tif repo.BackupSchedules != nil {\n\t\tswitch backupType {\n\t\tcase full:\n\t\t\treturn repo.BackupSchedules.Full != nil\n\t\tcase differential:\n\t\t\treturn repo.BackupSchedules.Differential != nil\n\t\tcase incremental:\n\t\t\treturn repo.BackupSchedules.Incremental != nil\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func (c *Context) IsBackup() bool {\n\treturn c.MyIndex >= 0 && !c.IsPrimary()\n}", "func (t *Task) isBackupReplicated(backup *velero.Backup) (bool, error) {\n\tclient, err := t.getDestinationClient()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treplicated := velero.Backup{}\n\tt.Log.Info(\"Checking if Velero Backup has been replicated to destination cluster\",\n\t\t\"backup\", path.Join(backup.Namespace, backup.Name))\n\terr = client.Get(\n\t\tcontext.TODO(),\n\t\ttypes.NamespacedName{\n\t\t\tNamespace: backup.Namespace,\n\t\t\tName: backup.Name,\n\t\t},\n\t\t&replicated)\n\tif err == nil {\n\t\tt.Log.Info(\"FOUND Velero Backup has been replicated to destination cluster\",\n\t\t\t\"backup\", path.Join(replicated.Namespace, replicated.Name))\n\t\treturn true, nil\n\t}\n\tif k8serrors.IsNotFound(err) {\n\t\terr = nil\n\t}\n\treturn false, err\n}", "func IsInProgressStatus(bkp *apis.CStorBackup) bool {\n\tif string(bkp.Status) == string(apis.BKPCStorStatusInProgress) {\n\t\treturn true\n\t}\n\treturn false\n}", "func (backupWrapper *v1BackupWrapper) isBackupCompleted() bool {\n\tif backupWrapper.backup.IsFailed() ||\n\t\tbackupWrapper.backup.IsSucceeded() {\n\t\treturn true\n\t}\n\treturn false\n}", "func (c *CleanupStatusTracker) InProgress(bdName string) bool {\n\treturn c.JobController.IsCleaningJobRunning(bdName)\n}", "func (r *ReconcileBackup) isAllCreated(bkp *v1alpha1.Backup) error {\n\n\t// Check if was possible found the DB Pod\n\tif !r.isDbPodFound() {\n\t\terr := fmt.Errorf(\"Error: Database Pod is missing\")\n\t\treturn err\n\t}\n\n\t// Check if was possible found the DB Service\n\tif !r.isDbServiceFound() {\n\t\terr := fmt.Errorf(\"Error: Database Service is missing\")\n\t\treturn err\n\t}\n\n\t// Check if DB secret was created\n\tdbSecretName := utils.DbSecretPrefix + bkp.Name\n\t_, err := service.FetchSecret(bkp.Namespace, dbSecretName, r.client)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error: DB Secret is missing. (%v)\", dbSecretName)\n\t\treturn err\n\t}\n\n\t// Check if AWS secret was created\n\tawsSecretName := utils.GetAWSSecretName(bkp)\n\tawsSecretNamespace := utils.GetAwsSecretNamespace(bkp)\n\t_, err = service.FetchSecret(awsSecretNamespace, awsSecretName, r.client)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"Error: AWS Secret is missing. (name:%v,namespace:%v)\", awsSecretName, awsSecretNamespace)\n\t\treturn err\n\t}\n\n\t// Check if Enc secret was created (if was configured to be used)\n\tif utils.IsEncryptionKeyOptionConfig(bkp) {\n\t\tencSecretName := utils.GetEncSecretName(bkp)\n\t\tencSecretNamespace := utils.GetEncSecretNamespace(bkp)\n\t\t_, err := service.FetchSecret(encSecretNamespace, encSecretName, r.client)\n\t\tif err != nil {\n\t\t\terr := fmt.Errorf(\"Error: Encript Key Secret is missing. (name:%v,namespace:%v)\", encSecretName, encSecretNamespace)\n\t\t\treturn err\n\t\t}\n\t}\n\n\t//check if the cronJob was created\n\t_, err = service.FetchCronJob(bkp.Name, bkp.Namespace, r.client)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"Error: CronJob is missing\")\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func IsBackup(options []*commonpb.KeyValuePair) bool {\n\tisBackup, err := funcutil.GetAttrByKeyFromRepeatedKV(BackupFlag, options)\n\tif err != nil || strings.ToLower(isBackup) != \"true\" {\n\t\treturn false\n\t}\n\treturn true\n}", "func (s StackStatus) InProgress() bool {\n\treturn strings.HasSuffix(string(s), \"IN_PROGRESS\")\n}", "func isNewWorker(worker *workerv1.Worker, currentDeployment *appsv1.Deployment) bool {\n\treturn currentDeployment == nil && worker.DeletionTimestamp == nil\n}", "func (w *CrawlerWorker) HasPendingJobs() bool { return len(w.pending) > 0 }", "func (a *actionRebuildOutSyncedShards) CheckProgress(ctx context.Context) (bool, bool, error) {\n\tif !features.RebuildOutSyncedShards().Enabled() {\n\t\t// RebuildOutSyncedShards feature is not enabled\n\t\treturn true, false, nil\n\t}\n\n\tclientSync, err := a.actionCtx.GetMembersState().GetMemberClient(a.action.MemberID)\n\tif err != nil {\n\t\treturn false, false, errors.Wrapf(err, \"Unable to create client (SyncMode)\")\n\t}\n\n\tclientAsync, err := a.actionCtx.GetServerAsyncClient(a.action.MemberID)\n\tif err != nil {\n\t\treturn false, false, errors.Wrapf(err, \"Unable to create client (AsyncMode)\")\n\t}\n\n\tjobID, ok := a.actionCtx.Get(a.action, actionRebuildOutSyncedShardsLocalJobID)\n\tif !ok {\n\t\treturn false, true, errors.Newf(\"Local Key is missing in action: %s\", actionRebuildOutSyncedShardsLocalJobID)\n\t}\n\n\tbatchID, ok := a.actionCtx.Get(a.action, actionRebuildOutSyncedShardsBatchID)\n\tif !ok {\n\t\treturn false, true, errors.Newf(\"Local Key is missing in action: %s\", actionRebuildOutSyncedShardsBatchID)\n\t}\n\n\tdatabase, ok := a.actionCtx.Get(a.action, actionRebuildOutSyncedShardsLocalDatabase)\n\tif !ok {\n\t\treturn false, true, errors.Newf(\"Local Key is missing in action: %s\", actionRebuildOutSyncedShardsLocalDatabase)\n\t}\n\n\tshardID, ok := a.actionCtx.Get(a.action, actionRebuildOutSyncedShardsLocalShard)\n\tif !ok {\n\t\treturn false, true, errors.Newf(\"Local Key is missing in action: %s\", actionRebuildOutSyncedShardsLocalShard)\n\t}\n\n\t// check first if there is rebuild job running\n\trebuildInProgress, err := a.checkRebuildShardProgress(ctx, clientAsync, clientSync, shardID, database, jobID, batchID)\n\tif err != nil {\n\t\tif rebuildInProgress {\n\t\t\ta.log.Err(err).Error(\"Rebuild job failed but we will retry\", shardID, database, a.action.MemberID)\n\t\t\treturn false, false, err\n\t\t} else {\n\t\t\ta.log.Err(err).Error(\"Rebuild job failed\", shardID, database, a.action.MemberID)\n\t\t\treturn false, true, err\n\t\t}\n\n\t}\n\tif rebuildInProgress {\n\t\ta.log.Debug(\"Rebuild job is still in progress\", shardID, database, a.action.MemberID)\n\t\treturn false, false, nil\n\t}\n\n\t// rebuild job is done\n\ta.log.Info(\"Rebuild Shard Tree is done\", shardID, database, a.action.MemberID)\n\treturn true, false, nil\n}", "func (t *Task) hasAllProgressReportingCompleted() (bool, error) {\n\tt.Owner.Status.RunningPods = []*migapi.PodProgress{}\n\tt.Owner.Status.FailedPods = []*migapi.PodProgress{}\n\tt.Owner.Status.SuccessfulPods = []*migapi.PodProgress{}\n\tt.Owner.Status.PendingPods = []*migapi.PodProgress{}\n\tunknownPods := []*migapi.PodProgress{}\n\tvar pendingSinceTimeLimitPods []string\n\tpvcMap := t.getPVCNamespaceMap()\n\tfor bothNs, vols := range pvcMap {\n\t\tns := getSourceNs(bothNs)\n\t\tfor _, vol := range vols {\n\t\t\toperation := t.Owner.Status.GetRsyncOperationStatusForPVC(&corev1.ObjectReference{\n\t\t\t\tNamespace: ns,\n\t\t\t\tName: vol.Name,\n\t\t\t})\n\t\t\tdvmp := migapi.DirectVolumeMigrationProgress{}\n\t\t\terr := t.Client.Get(context.TODO(), types.NamespacedName{\n\t\t\t\tName: getMD5Hash(t.Owner.Name + vol.Name + ns),\n\t\t\t\tNamespace: migapi.OpenshiftMigrationNamespace,\n\t\t\t}, &dvmp)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tpodProgress := &migapi.PodProgress{\n\t\t\t\tObjectReference: &corev1.ObjectReference{\n\t\t\t\t\tNamespace: ns,\n\t\t\t\t\tName: dvmp.Status.PodName,\n\t\t\t\t},\n\t\t\t\tPVCReference: &corev1.ObjectReference{\n\t\t\t\t\tNamespace: ns,\n\t\t\t\t\tName: vol.Name,\n\t\t\t\t},\n\t\t\t\tLastObservedProgressPercent: dvmp.Status.TotalProgressPercentage,\n\t\t\t\tLastObservedTransferRate: dvmp.Status.LastObservedTransferRate,\n\t\t\t\tTotalElapsedTime: dvmp.Status.RsyncElapsedTime,\n\t\t\t}\n\t\t\tswitch {\n\t\t\tcase dvmp.Status.PodPhase == corev1.PodRunning:\n\t\t\t\tt.Owner.Status.RunningPods = append(t.Owner.Status.RunningPods, podProgress)\n\t\t\tcase operation.Failed:\n\t\t\t\tt.Owner.Status.FailedPods = append(t.Owner.Status.FailedPods, podProgress)\n\t\t\tcase dvmp.Status.PodPhase == corev1.PodSucceeded:\n\t\t\t\tt.Owner.Status.SuccessfulPods = append(t.Owner.Status.SuccessfulPods, podProgress)\n\t\t\tcase dvmp.Status.PodPhase == corev1.PodPending:\n\t\t\t\tt.Owner.Status.PendingPods = append(t.Owner.Status.PendingPods, podProgress)\n\t\t\t\tif dvmp.Status.CreationTimestamp != nil {\n\t\t\t\t\tif time.Now().UTC().Sub(dvmp.Status.CreationTimestamp.Time.UTC()) > PendingPodWarningTimeLimit {\n\t\t\t\t\t\tpendingSinceTimeLimitPods = append(pendingSinceTimeLimitPods, fmt.Sprintf(\"%s/%s\", podProgress.Namespace, podProgress.Name))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase dvmp.Status.PodPhase == \"\":\n\t\t\t\tunknownPods = append(unknownPods, podProgress)\n\t\t\tcase !operation.Failed:\n\t\t\t\tt.Owner.Status.RunningPods = append(t.Owner.Status.RunningPods, podProgress)\n\t\t\t}\n\t\t}\n\t}\n\n\tisCompleted := len(t.Owner.Status.SuccessfulPods)+len(t.Owner.Status.FailedPods) == len(t.Owner.Spec.PersistentVolumeClaims)\n\tisAnyPending := len(t.Owner.Status.PendingPods) > 0\n\tisAnyRunning := len(t.Owner.Status.RunningPods) > 0\n\tisAnyUnknown := len(unknownPods) > 0\n\tif len(pendingSinceTimeLimitPods) > 0 {\n\t\tpendingMessage := fmt.Sprintf(\"Rsync Client Pods [%s] are stuck in Pending state for more than 10 mins\", strings.Join(pendingSinceTimeLimitPods[:], \", \"))\n\t\tt.Log.Info(pendingMessage)\n\t\tt.Owner.Status.SetCondition(migapi.Condition{\n\t\t\tType: RsyncClientPodsPending,\n\t\t\tStatus: migapi.True,\n\t\t\tReason: \"PodStuckInContainerCreating\",\n\t\t\tCategory: migapi.Warn,\n\t\t\tMessage: pendingMessage,\n\t\t})\n\t}\n\treturn !isAnyRunning && !isAnyPending && !isAnyUnknown && isCompleted, nil\n}", "func WaitForScheduledBackup(backupScheduleName string, retryInterval time.Duration, timeout time.Duration) (*api.BackupObject, error) {\n\tbeginTime := time.Now()\n\tbeginTimeSec := beginTime.Unix()\n\n\tt := func() (interface{}, bool, error) {\n\t\tlogrus.Infof(\"Enumerating backups\")\n\t\tbkpEnumerateReq := &api.BackupEnumerateRequest{\n\t\t\tOrgId: OrgID}\n\t\t//ctx, err := backup.GetPxCentralAdminCtx()\n\t\tctx, err := backup.GetAdminCtxFromSecret()\n\t\tif err != nil {\n\t\t\treturn nil, true, err\n\t\t}\n\t\tcurBackups, err := Inst().Backup.EnumerateBackup(ctx, bkpEnumerateReq)\n\t\tif err != nil {\n\t\t\treturn nil, true, err\n\t\t}\n\t\tfor _, bkp := range curBackups.GetBackups() {\n\t\t\tcreateTime := bkp.GetCreateTime()\n\t\t\tif beginTimeSec > createTime.GetSeconds() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif (bkp.GetStatus().GetStatus() == api.BackupInfo_StatusInfo_Success ||\n\t\t\t\tbkp.GetStatus().GetStatus() == api.BackupInfo_StatusInfo_PartialSuccess) &&\n\t\t\t\tbkp.GetBackupSchedule().GetName() == backupScheduleName {\n\t\t\t\treturn bkp, false, nil\n\t\t\t}\n\t\t}\n\t\terr = fmt.Errorf(\"unable to find backup from backup schedule with name %s after time %v\",\n\t\t\tbackupScheduleName, beginTime)\n\t\treturn nil, true, err\n\t}\n\n\tbkpInterface, err := task.DoRetryWithTimeout(t, timeout, retryInterval)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbkp := bkpInterface.(*api.BackupObject)\n\treturn bkp, nil\n\n}", "func (o *HyperflexVmSnapshotInfoAllOf) HasVmBackupInfo() bool {\n\tif o != nil && o.VmBackupInfo != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func CheckFsCreationInProgress(device model.Device) (inProgress bool, err error) {\n\treturn false, fmt.Errorf(\"FS progress check is not implemented for Mac\")\n}", "func checkState() {\n\tlist := listContainers()\n\tallup := true\n\tfor _, cfgCon := range clusterConfig {\n\t\tfound := false\n\t\tfor _, con := range list {\n\t\t\tif con.Name == cfgCon.Name {\n\t\t\t\tif !con.State.Running {\n\t\t\t\t\tallup = false\n\t\t\t\t}\n\t\t\t\tcheckContainerState(con, cfgCon)\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tlog.Println(\"No container found for\", cfgCon.Name)\n\t\t\tcreateContainer(cfgCon)\n\t\t\tupdateConfig()\n\t\t}\n\t}\n\tif allup {\n\t\tlog.Println(\"All containers are up\")\n\t}\n}", "func (pr *Progress) maybeSnapshotAbort() bool {\n\treturn pr.State == ProgressStateSnapshot && pr.Match >= pr.PendingSnapshot\n}", "func IsPendingStatus(bkp *apis.CStorBackup) bool {\n\tif string(bkp.Status) == string(apis.BKPCStorStatusPending) {\n\t\treturn true\n\t}\n\treturn false\n}", "func (queryRunner *GpQueryRunner) IsInBackup() (isInBackupByContentID map[int]bool, err error) {\n\tconn := queryRunner.pgQueryRunner.Connection\n\n\trows, err := conn.Query(queryRunner.buildIsInBackup())\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"QueryRunner IsInBackup: query failed\")\n\t}\n\n\tdefer rows.Close()\n\tresults := make(map[int]bool)\n\tfor rows.Next() {\n\t\tvar contentID int\n\t\tvar isInBackup bool\n\t\tif err := rows.Scan(&isInBackup, &contentID); err != nil {\n\t\t\ttracelog.WarningLogger.Printf(\"QueryRunner IsInBackup: %v\\n\", err.Error())\n\t\t}\n\t\tresults[contentID] = isInBackup\n\t}\n\n\tif rows.Err() != nil {\n\t\treturn nil, rows.Err()\n\t}\n\n\treturn results, nil\n}", "func (b *Bar) InProgress() bool {\n\treturn !isClosed(b.done)\n}", "func (c *ClusterStateImpl) instanceUpdateInProgress(asgName, instanceId string) bool {\n\treturn c.getInstanceState(asgName, instanceId) == updateInProgress\n}", "func (ti TaskInstance) IsScheduled() bool {\n\tvar disabledCount int\n\n\tfor _, status := range ti.Statuses {\n\t\tif status == statuses.TaskInstanceDisabled {\n\t\t\tdisabledCount++\n\t\t\tcontinue\n\t\t}\n\n\t\tif status == statuses.TaskInstanceScheduled {\n\t\t\t// FIX: RMM-36676\n\t\t\treturn true\n\t\t}\n\t\tbreak\n\t}\n\treturn len(ti.Statuses) == disabledCount\n}", "func (o *RequestsDeploymentScheduledBackup) HasBackupTargetId() bool {\n\tif o != nil && o.BackupTargetId != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func IsOnlyStatusChange(oldbkp, newbkp *apis.CStorBackup) bool {\n\tif reflect.DeepEqual(oldbkp.Spec, newbkp.Spec) &&\n\t\t!reflect.DeepEqual(oldbkp.Status, newbkp.Status) {\n\t\treturn true\n\t}\n\treturn false\n}", "func (r *Reconciler) reconcileScheduledBackups(\n\tctx context.Context, cluster *v1beta1.PostgresCluster, sa *corev1.ServiceAccount,\n\tcronjobs []*batchv1.CronJob,\n) bool {\n\tlog := logging.FromContext(ctx).WithValues(\"reconcileResource\", \"repoCronJob\")\n\t// requeue if there is an error during creation\n\tvar requeue bool\n\n\tfor _, repo := range cluster.Spec.Backups.PGBackRest.Repos {\n\t\t// if the repo level backup schedules block has not been created,\n\t\t// there are no schedules defined\n\t\tif repo.BackupSchedules != nil {\n\t\t\t// next if the repo level schedule is not nil, create the CronJob.\n\t\t\tif repo.BackupSchedules.Full != nil {\n\t\t\t\tif err := r.reconcilePGBackRestCronJob(ctx, cluster, repo,\n\t\t\t\t\tfull, repo.BackupSchedules.Full, sa, cronjobs); err != nil {\n\t\t\t\t\tlog.Error(err, \"unable to reconcile Full backup for \"+repo.Name)\n\t\t\t\t\trequeue = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif repo.BackupSchedules.Differential != nil {\n\t\t\t\tif err := r.reconcilePGBackRestCronJob(ctx, cluster, repo,\n\t\t\t\t\tdifferential, repo.BackupSchedules.Differential, sa, cronjobs); err != nil {\n\t\t\t\t\tlog.Error(err, \"unable to reconcile Differential backup for \"+repo.Name)\n\t\t\t\t\trequeue = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif repo.BackupSchedules.Incremental != nil {\n\t\t\t\tif err := r.reconcilePGBackRestCronJob(ctx, cluster, repo,\n\t\t\t\t\tincremental, repo.BackupSchedules.Incremental, sa, cronjobs); err != nil {\n\t\t\t\t\tlog.Error(err, \"unable to reconcile Incremental backup for \"+repo.Name)\n\t\t\t\t\trequeue = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn requeue\n}", "func TestBackupBefore(t *testing.T) {\n\tb := backup{t: time.Unix(2, 0)}\n\tif b.before(time.Unix(1, 0)) {\n\t\tt.Errorf(\"b.before(time.Unix(1, 0)) returns false\")\n\t}\n\n\tif b.before(time.Unix(2, 0)) {\n\t\tt.Errorf(\"b.before(time.Unix(2, 0)) returns false\")\n\t}\n}", "func (t *Task) ensureInitialBackup() (*velero.Backup, error) {\n\tbackup, err := t.getInitialBackup()\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tif backup != nil {\n\t\treturn backup, nil\n\t}\n\n\tclient, err := t.getSourceClient()\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tnewBackup, err := t.buildBackup(client, \"initial\")\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tuserIncludedResources, _, err := t.PlanResources.MigPlan.GetIncludedResourcesList(client)\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\n\tnewBackup.Labels[migapi.InitialBackupLabel] = t.UID()\n\tnewBackup.Labels[migapi.MigMigrationDebugLabel] = t.Owner.Name\n\tnewBackup.Labels[migapi.MigPlanDebugLabel] = t.Owner.Spec.MigPlanRef.Name\n\tnewBackup.Labels[migapi.MigMigrationLabel] = string(t.Owner.UID)\n\tnewBackup.Labels[migapi.MigPlanLabel] = string(t.PlanResources.MigPlan.UID)\n\tnewBackup.Spec.IncludedResources = toStringSlice(settings.IncludedInitialResources.Difference(toSet(t.PlanResources.MigPlan.Status.ExcludedResources)))\n\tnewBackup.Spec.IncludedResources = append(newBackup.Spec.IncludedResources, userIncludedResources...)\n\tnewBackup.Spec.ExcludedResources = toStringSlice(settings.ExcludedInitialResources.Union(toSet(t.PlanResources.MigPlan.Status.ExcludedResources)))\n\tnewBackup.Spec.LabelSelector = t.PlanResources.MigPlan.Spec.LabelSelector\n\tdelete(newBackup.Annotations, migapi.QuiesceAnnotation)\n\n\tif Settings.DisImgCopy {\n\t\tif newBackup.Annotations == nil {\n\t\t\tnewBackup.Annotations = map[string]string{}\n\t\t}\n\t\tnewBackup.Annotations[migapi.DisableImageCopy] = strconv.FormatBool(Settings.DisImgCopy)\n\t}\n\n\terr = client.Create(context.TODO(), newBackup)\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\treturn newBackup, nil\n}", "func (t *Task) ensureStageBackup() (*velero.Backup, error) {\n\tbackup, err := t.getStageBackup()\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tif backup != nil {\n\t\treturn backup, nil\n\t}\n\n\tclient, err := t.getSourceClient()\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tt.Log.Info(\"Building Stage Velero Backup resource definition\")\n\tnewBackup, err := t.buildBackup(client, \"stage\")\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tlabelSelector := metav1.LabelSelector{\n\t\tMatchLabels: map[string]string{\n\t\t\tmigapi.IncludedInStageBackupLabel: t.UID(),\n\t\t},\n\t}\n\tnewBackup.Labels[migapi.StageBackupLabel] = t.UID()\n\tnewBackup.Labels[migapi.MigMigrationDebugLabel] = t.Owner.Name\n\tnewBackup.Labels[migapi.MigPlanDebugLabel] = t.Owner.Spec.MigPlanRef.Name\n\tnewBackup.Labels[migapi.MigMigrationLabel] = string(t.Owner.UID)\n\tnewBackup.Labels[migapi.MigPlanLabel] = string(t.PlanResources.MigPlan.UID)\n\tvar includedResources mapset.Set\n\n\tif (t.indirectImageMigration() || Settings.DisImgCopy) && !t.migrateState() {\n\t\tincludedResources = settings.IncludedStageResources\n\t} else {\n\t\tincludedResources = settings.IncludedStageResources.Difference(mapset.NewSetFromSlice([]interface{}{settings.ISResource}))\n\t}\n\tnewBackup.Spec.IncludedResources = toStringSlice(includedResources.Difference(toSet(t.PlanResources.MigPlan.Status.ExcludedResources)))\n\tnewBackup.Spec.ExcludedResources = toStringSlice(settings.ExcludedStageResources.Union(toSet(t.PlanResources.MigPlan.Status.ExcludedResources)))\n\tnewBackup.Spec.LabelSelector = &labelSelector\n\tif Settings.DisImgCopy {\n\t\tif newBackup.Annotations == nil {\n\t\t\tnewBackup.Annotations = map[string]string{}\n\t\t}\n\t\tnewBackup.Annotations[migapi.DisableImageCopy] = strconv.FormatBool(Settings.DisImgCopy)\n\t}\n\tt.Log.Info(\"Creating Stage Velero Backup on source cluster.\",\n\t\t\"backup\", path.Join(newBackup.Namespace, newBackup.Name))\n\terr = client.Create(context.TODO(), newBackup)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newBackup, nil\n}", "func (o *NetworkElementSummaryAllOf) HasConfModTsBackup() bool {\n\tif o != nil && o.ConfModTsBackup != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (es *EventuallyFileOnlySnapshot) hasTransitioned() bool {\n\tes.mu.Lock()\n\tdefer es.mu.Unlock()\n\treturn es.mu.vers != nil\n}", "func (r *BackupReconciler) instReady(ctx context.Context, ns, instName string, inst *v1alpha1.Instance) error {\n\tif err := r.Get(ctx, types.NamespacedName{Namespace: ns, Name: instName}, inst); err != nil {\n\t\tr.Log.Error(err, \"error finding instance for backup validation\")\n\t\treturn fmt.Errorf(\"error finding instance - %v\", err)\n\t}\n\tif !k8s.ConditionStatusEquals(k8s.FindCondition(inst.Status.Conditions, k8s.Ready), v1.ConditionTrue) {\n\t\tr.Log.Error(fmt.Errorf(\"instance not in ready state\"), \"Instance not in ready state for backup\", \"inst.Status.Conditions\", inst.Status.Conditions)\n\t\treturn errors.New(\"instance is not in a ready state\")\n\t}\n\treturn nil\n}", "func checkJobStatus(jobQueue *jobqueue.Client, t *jobqueue.Task) (bool, error) {\n\tif t.Job.Status != jobqueue.JobStatusNew {\n\t\treturn true, fmt.Errorf(\"bad job status: %s\", t.Job.Status)\n\t}\n\tif t.Job.Action != \"select-hypervisor\" {\n\t\treturn true, fmt.Errorf(\"bad action: %s\", t.Job.Action)\n\t}\n\treturn false, nil\n}", "func (h *Handler) reconcileBackupStatus(vmBackup *harvesterv1.VirtualMachineBackup) error {\n\tvar deletedSnapshots, skippedSnapshots []string\n\n\tvar backupReady = isBackupReady(vmBackup)\n\tvar backupError = isBackupError(vmBackup)\n\n\t// create CSI volume snapshots\n\tfor i, volumeBackup := range vmBackup.Status.VolumeBackups {\n\t\tif volumeBackup.Name == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar vsName = *volumeBackup.Name\n\n\t\tvolumeSnapshot, err := h.getVolumeSnapshot(vmBackup.Namespace, vsName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif volumeSnapshot == nil {\n\t\t\t// check if snapshot was deleted\n\t\t\tif backupReady {\n\t\t\t\tlogrus.Warningf(\"VolumeSnapshot %s no longer exists\", vsName)\n\t\t\t\th.recorder.Eventf(\n\t\t\t\t\tvmBackup,\n\t\t\t\t\tcorev1.EventTypeWarning,\n\t\t\t\t\tvolumeSnapshotMissingEvent,\n\t\t\t\t\t\"VolumeSnapshot %s no longer exists\",\n\t\t\t\t\tvsName,\n\t\t\t\t)\n\t\t\t\tdeletedSnapshots = append(deletedSnapshots, vsName)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif backupError {\n\t\t\t\tlogrus.Infof(\"Not creating snapshot %s because content in error state\", vsName)\n\t\t\t\tskippedSnapshots = append(skippedSnapshots, vsName)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvolumeSnapshot, err = h.createVolumeSnapshot(vmBackup, volumeBackup)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif volumeSnapshot.Status != nil {\n\t\t\tvmBackup.Status.VolumeBackups[i].ReadyToUse = volumeSnapshot.Status.ReadyToUse\n\t\t\tvmBackup.Status.VolumeBackups[i].CreationTime = volumeSnapshot.Status.CreationTime\n\t\t\tvmBackup.Status.VolumeBackups[i].Error = translateError(volumeSnapshot.Status.Error)\n\t\t}\n\n\t}\n\n\tvar ready = true\n\tvar errorMessage = \"\"\n\tbackupCpy := vmBackup.DeepCopy()\n\tif len(deletedSnapshots) > 0 {\n\t\tready = false\n\t\terrorMessage = fmt.Sprintf(\"volumeSnapshots (%s) missing\", strings.Join(deletedSnapshots, \",\"))\n\t} else if len(skippedSnapshots) > 0 {\n\t\tready = false\n\t\terrorMessage = fmt.Sprintf(\"volumeSnapshots (%s) skipped because in error state\", strings.Join(skippedSnapshots, \",\"))\n\t} else {\n\t\tfor _, vb := range vmBackup.Status.VolumeBackups {\n\t\t\tif vb.ReadyToUse == nil || !*vb.ReadyToUse {\n\t\t\t\tready = false\n\t\t\t}\n\n\t\t\tif vb.Error != nil {\n\t\t\t\terrorMessage = \"VolumeSnapshot in error state\"\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif ready && (backupCpy.Status.ReadyToUse == nil || !*backupCpy.Status.ReadyToUse) {\n\t\tbackupCpy.Status.CreationTime = currentTime()\n\t\tupdateBackupCondition(backupCpy, newProgressingCondition(corev1.ConditionFalse, \"Operation complete\"))\n\t\tupdateBackupCondition(backupCpy, newReadyCondition(corev1.ConditionTrue, \"Operation complete\"))\n\t}\n\n\t// check if the status need to update the error status\n\tif errorMessage != \"\" && (backupCpy.Status.Error == nil || backupCpy.Status.Error.Message == nil || *backupCpy.Status.Error.Message != errorMessage) {\n\t\tbackupCpy.Status.Error = &harvesterv1.Error{\n\t\t\tTime: currentTime(),\n\t\t\tMessage: &errorMessage,\n\t\t}\n\t}\n\n\tbackupCpy.Status.ReadyToUse = &ready\n\n\tif !reflect.DeepEqual(vmBackup.Status, backupCpy.Status) {\n\t\tif _, err := h.vmBackups.Update(backupCpy); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func isScheduleStillInUse(s models.Schedule) (bool, error) {\n\tvar scheduleEvents []models.ScheduleEvent\n\tif err := dbClient.GetScheduleEventsByScheduleName(&scheduleEvents, s.Name); err != nil {\n\t\treturn false, err\n\t}\n\tif len(scheduleEvents) > 0 {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}", "func (solver *MapSolver)HasScheduled(arc *data.Arc) bool{\n\tfor _, cap := range arc.Capacity {\n\t\tif cap > 0 { // if dstNode is not machineNode, we can assume that if capacity > 0, then this task still not scheduled\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func HasPendingRestoreRequest(statusRecords []*ProcessStatus) (bool) {\n\tfor _, record := range statusRecords {\n\t\tif record.Action == ActionRestore &&\n\t\t\t(record.Status == StatusStarted || record.Status == StatusPending) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func isNewSnapshotRequest(id string, status *types.AppInstanceStatus) bool {\n\t// Check if the snapshot is already present in the list of the snapshots to be taken.\n\tfor _, snapRequest := range status.SnapStatus.RequestedSnapshots {\n\t\tif snapRequest.Snapshot.SnapshotID == id {\n\t\t\treturn false\n\t\t}\n\t}\n\t// Check if the snapshot is already present in the list of the available snapshots.\n\tfor _, snapAvailable := range status.SnapStatus.AvailableSnapshots {\n\t\tif snapAvailable.Snapshot.SnapshotID == id {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func backup(\n\tctx context.Context,\n\tdb *client.DB,\n\tgossip *gossip.Gossip,\n\tsettings *cluster.Settings,\n\texportStore storageccl.ExportStorage,\n\tjob *jobs.Job,\n\tbackupDesc *BackupDescriptor,\n\tcheckpointDesc *BackupDescriptor,\n\tresultsCh chan<- tree.Datums,\n) (roachpb.BulkOpSummary, error) {\n\t// TODO(dan): Figure out how permissions should work. #6713 is tracking this\n\t// for grpc.\n\n\tmu := struct {\n\t\tsyncutil.Mutex\n\t\tfiles []BackupDescriptor_File\n\t\texported roachpb.BulkOpSummary\n\t\tlastCheckpoint time.Time\n\t}{}\n\n\tvar checkpointMu syncutil.Mutex\n\n\tvar ranges []roachpb.RangeDescriptor\n\tif err := db.Txn(ctx, func(ctx context.Context, txn *client.Txn) error {\n\t\tvar err error\n\t\t// TODO(benesch): limit the range descriptors we fetch to the ranges that\n\t\t// are actually relevant in the backup to speed up small backups on large\n\t\t// clusters.\n\t\tranges, err = allRangeDescriptors(ctx, txn)\n\t\treturn err\n\t}); err != nil {\n\t\treturn mu.exported, errors.Wrap(err, \"fetching range descriptors\")\n\t}\n\n\tvar completedSpans, completedIntroducedSpans []roachpb.Span\n\tif checkpointDesc != nil {\n\t\t// TODO(benesch): verify these files, rather than accepting them as truth\n\t\t// blindly.\n\t\t// No concurrency yet, so these assignments are safe.\n\t\tmu.files = checkpointDesc.Files\n\t\tmu.exported = checkpointDesc.EntryCounts\n\t\tfor _, file := range checkpointDesc.Files {\n\t\t\tif file.StartTime.IsEmpty() && !file.EndTime.IsEmpty() {\n\t\t\t\tcompletedIntroducedSpans = append(completedIntroducedSpans, file.Span)\n\t\t\t} else {\n\t\t\t\tcompletedSpans = append(completedSpans, file.Span)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Subtract out any completed spans and split the remaining spans into\n\t// range-sized pieces so that we can use the number of completed requests as a\n\t// rough measure of progress.\n\tspans := splitAndFilterSpans(backupDesc.Spans, completedSpans, ranges)\n\tintroducedSpans := splitAndFilterSpans(backupDesc.IntroducedSpans, completedIntroducedSpans, ranges)\n\n\tallSpans := make([]spanAndTime, 0, len(spans)+len(introducedSpans))\n\tfor _, s := range introducedSpans {\n\t\tallSpans = append(allSpans, spanAndTime{span: s, start: hlc.Timestamp{}, end: backupDesc.StartTime})\n\t}\n\tfor _, s := range spans {\n\t\tallSpans = append(allSpans, spanAndTime{span: s, start: backupDesc.StartTime, end: backupDesc.EndTime})\n\t}\n\n\tprogressLogger := jobs.ProgressLogger{\n\t\tJob: job,\n\t\tTotalChunks: len(spans),\n\t\tStartFraction: job.Payload().FractionCompleted,\n\t}\n\n\t// We're already limiting these on the server-side, but sending all the\n\t// Export requests at once would fill up distsender/grpc/something and cause\n\t// all sorts of badness (node liveness timeouts leading to mass leaseholder\n\t// transfers, poor performance on SQL workloads, etc) as well as log spam\n\t// about slow distsender requests. Rate limit them here, too.\n\t//\n\t// Each node limits the number of running Export & Import requests it serves\n\t// to avoid overloading the network, so multiply that by the number of nodes\n\t// in the cluster and use that as the number of outstanding Export requests\n\t// for the rate limiting. This attempts to strike a balance between\n\t// simplicity, not getting slow distsender log spam, and keeping the server\n\t// side limiter full.\n\t//\n\t// TODO(dan): Make this limiting per node.\n\t//\n\t// TODO(dan): See if there's some better solution than rate-limiting #14798.\n\tmaxConcurrentExports := clusterNodeCount(gossip) * int(storage.ExportRequestsLimit.Get(&settings.SV))\n\texportsSem := make(chan struct{}, maxConcurrentExports)\n\n\tg, gCtx := errgroup.WithContext(ctx)\n\n\trequestFinishedCh := make(chan struct{}, len(spans)) // enough buffer to never block\n\n\t// Only start the progress logger if there are spans, otherwise this will\n\t// block forever. This is needed for TestBackupRestoreResume which doesn't\n\t// have any spans. Users should never hit this.\n\tif len(spans) > 0 {\n\t\tg.Go(func() error {\n\t\t\treturn progressLogger.Loop(gCtx, requestFinishedCh)\n\t\t})\n\t}\n\n\tfor i := range allSpans {\n\t\tselect {\n\t\tcase exportsSem <- struct{}{}:\n\t\tcase <-ctx.Done():\n\t\t\treturn mu.exported, ctx.Err()\n\t\t}\n\n\t\tspan := allSpans[i]\n\t\tg.Go(func() error {\n\t\t\tdefer func() { <-exportsSem }()\n\t\t\theader := roachpb.Header{Timestamp: span.end}\n\t\t\treq := &roachpb.ExportRequest{\n\t\t\t\tSpan: span.span,\n\t\t\t\tStorage: exportStore.Conf(),\n\t\t\t\tStartTime: span.start,\n\t\t\t\tMVCCFilter: roachpb.MVCCFilter(backupDesc.MVCCFilter),\n\t\t\t}\n\t\t\trawRes, pErr := client.SendWrappedWith(gCtx, db.GetSender(), header, req)\n\t\t\tif pErr != nil {\n\t\t\t\treturn pErr.GoError()\n\t\t\t}\n\t\t\tres := rawRes.(*roachpb.ExportResponse)\n\n\t\t\tmu.Lock()\n\t\t\tif backupDesc.RevisionStartTime.Less(res.StartTime) {\n\t\t\t\tbackupDesc.RevisionStartTime = res.StartTime\n\t\t\t}\n\t\t\tfor _, file := range res.Files {\n\t\t\t\tf := BackupDescriptor_File{\n\t\t\t\t\tSpan: file.Span,\n\t\t\t\t\tPath: file.Path,\n\t\t\t\t\tSha512: file.Sha512,\n\t\t\t\t\tEntryCounts: file.Exported,\n\t\t\t\t}\n\t\t\t\tif span.start != backupDesc.StartTime {\n\t\t\t\t\tf.StartTime = span.start\n\t\t\t\t\tf.EndTime = span.end\n\t\t\t\t}\n\t\t\t\tmu.files = append(mu.files, f)\n\t\t\t\tmu.exported.Add(file.Exported)\n\t\t\t}\n\t\t\tvar checkpointFiles BackupFileDescriptors\n\t\t\tif timeutil.Since(mu.lastCheckpoint) > BackupCheckpointInterval {\n\t\t\t\t// We optimistically assume the checkpoint will succeed to prevent\n\t\t\t\t// multiple threads from attempting to checkpoint.\n\t\t\t\tmu.lastCheckpoint = timeutil.Now()\n\t\t\t\tcheckpointFiles = append(checkpointFiles, mu.files...)\n\t\t\t}\n\t\t\tmu.Unlock()\n\n\t\t\trequestFinishedCh <- struct{}{}\n\n\t\t\tif checkpointFiles != nil {\n\t\t\t\tcheckpointMu.Lock()\n\t\t\t\tbackupDesc.Files = checkpointFiles\n\t\t\t\terr := writeBackupDescriptor(\n\t\t\t\t\tctx, exportStore, BackupDescriptorCheckpointName, backupDesc,\n\t\t\t\t)\n\t\t\t\tcheckpointMu.Unlock()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(ctx, \"unable to checkpoint backup descriptor: %+v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\n\tif err := g.Wait(); err != nil {\n\t\treturn mu.exported, errors.Wrapf(err, \"exporting %d ranges\", len(spans))\n\t}\n\n\t// No more concurrency, so no need to acquire locks below.\n\n\tbackupDesc.Files = mu.files\n\tbackupDesc.EntryCounts = mu.exported\n\n\tif err := writeBackupDescriptor(ctx, exportStore, BackupDescriptorName, backupDesc); err != nil {\n\t\treturn mu.exported, err\n\t}\n\n\treturn mu.exported, nil\n}", "func (b *Backup) Status() BackupStatus {\n\treturn BackupStatus{int(C.sqlite3_backup_remaining(b.sb)), int(C.sqlite3_backup_pagecount(b.sb))}\n}", "func isWorkerUpdated(worker *workerv1.Worker, currentDeployment *appsv1.Deployment) bool {\n\tdeployment := generateDeploymentFromWorker(worker)\n\tres := !isSameDeploymentSpecs(deployment, currentDeployment)\n\treturn res\n}", "func Test_getLastSuccessBySchedule(t *testing.T) {\n\tbuildBackup := func(phase velerov1api.BackupPhase, completion time.Time, schedule string) velerov1api.Backup {\n\t\tb := builder.ForBackup(\"\", \"\").\n\t\t\tObjectMeta(builder.WithLabels(velerov1api.ScheduleNameLabel, schedule)).\n\t\t\tPhase(phase)\n\n\t\tif !completion.IsZero() {\n\t\t\tb.CompletionTimestamp(completion)\n\t\t}\n\n\t\treturn *b.Result()\n\t}\n\n\t// create a static \"base time\" that can be used to easily construct completion timestamps\n\t// by using the .Add(...) method.\n\tbaseTime, err := time.Parse(time.RFC1123, time.RFC1123)\n\trequire.NoError(t, err)\n\n\ttests := []struct {\n\t\tname string\n\t\tbackups []velerov1api.Backup\n\t\twant map[string]time.Time\n\t}{\n\t\t{\n\t\t\tname: \"when backups is nil, an empty map is returned\",\n\t\t\tbackups: nil,\n\t\t\twant: map[string]time.Time{},\n\t\t},\n\t\t{\n\t\t\tname: \"when backups is empty, an empty map is returned\",\n\t\t\tbackups: []velerov1api.Backup{},\n\t\t\twant: map[string]time.Time{},\n\t\t},\n\t\t{\n\t\t\tname: \"when multiple completed backups for a schedule exist, the latest one is returned\",\n\t\t\tbackups: []velerov1api.Backup{\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime, \"schedule-1\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(time.Second), \"schedule-1\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(-time.Second), \"schedule-1\"),\n\t\t\t},\n\t\t\twant: map[string]time.Time{\n\t\t\t\t\"schedule-1\": baseTime.Add(time.Second),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"when the most recent backup for a schedule is Failed, the timestamp of the most recent Completed one is returned\",\n\t\t\tbackups: []velerov1api.Backup{\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime, \"schedule-1\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseFailed, baseTime.Add(time.Second), \"schedule-1\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(-time.Second), \"schedule-1\"),\n\t\t\t},\n\t\t\twant: map[string]time.Time{\n\t\t\t\t\"schedule-1\": baseTime,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"when there are no Completed backups for a schedule, it's not returned\",\n\t\t\tbackups: []velerov1api.Backup{\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseInProgress, baseTime, \"schedule-1\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseFailed, baseTime.Add(time.Second), \"schedule-1\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhasePartiallyFailed, baseTime.Add(-time.Second), \"schedule-1\"),\n\t\t\t},\n\t\t\twant: map[string]time.Time{},\n\t\t},\n\t\t{\n\t\t\tname: \"when backups exist without a schedule, the most recent Completed one is returned\",\n\t\t\tbackups: []velerov1api.Backup{\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime, \"\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseFailed, baseTime.Add(time.Second), \"\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(-time.Second), \"\"),\n\t\t\t},\n\t\t\twant: map[string]time.Time{\n\t\t\t\t\"\": baseTime,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"when backups exist for multiple schedules, the most recent Completed timestamp for each schedule is returned\",\n\t\t\tbackups: []velerov1api.Backup{\n\t\t\t\t// ad-hoc backups (no schedule)\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(30*time.Minute), \"\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseFailed, baseTime.Add(time.Hour), \"\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(-time.Second), \"\"),\n\n\t\t\t\t// schedule-1\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime, \"schedule-1\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseFailed, baseTime.Add(time.Second), \"schedule-1\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(-time.Second), \"schedule-1\"),\n\n\t\t\t\t// schedule-2\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(24*time.Hour), \"schedule-2\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(48*time.Hour), \"schedule-2\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(72*time.Hour), \"schedule-2\"),\n\n\t\t\t\t// schedule-3\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseNew, baseTime, \"schedule-3\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseInProgress, baseTime.Add(time.Minute), \"schedule-3\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhasePartiallyFailed, baseTime.Add(2*time.Minute), \"schedule-3\"),\n\t\t\t},\n\t\t\twant: map[string]time.Time{\n\t\t\t\t\"\": baseTime.Add(30 * time.Minute),\n\t\t\t\t\"schedule-1\": baseTime,\n\t\t\t\t\"schedule-2\": baseTime.Add(72 * time.Hour),\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tassert.Equal(t, tc.want, getLastSuccessBySchedule(tc.backups))\n\t\t})\n\t}\n}", "func checkNotActive() error {\n\toperationDetails := activeOperation\n\tif operationDetails != nil {\n\t\tselect {\n\t\tcase <-operationDetails.exportDone:\n\t\t\t// nil-out any stale operation\n\t\t\tactiveOperation = nil\n\t\tdefault:\n\t\t\tif operationDetails.isRestore {\n\t\t\t\treturn fmt.Errorf(\"restore operation already in progress for height %d\", operationDetails.blockHeight)\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"export operation already in progress for height %d\", operationDetails.blockHeight)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Controller) validateBackupAnnotations(key string, volumeMissing prometheus.GaugeVec, excludeAnnotation string, backupAnnotation string) error {\n\n\tobj, exists, err := c.indexer.GetByKey(key)\n\tif err != nil {\n\t\tklog.Errorf(\"fetching object with key %s from store failed with %v\", key, err)\n\t\treturn err\n\t}\n\tif !exists {\n\t\tklog.Infof(\"pod %s does not exist anymore\", key)\n\t\tif obj, exists, err = c.deletedIndexer.GetByKey(key); err == nil && exists {\n\n\t\t\tpod := obj.(*v1.Pod)\n\t\t\townerInfo := getPodOwnerInfo(pod)\n\t\t\tklog.Infof(\"disabling metric %s\", ownerInfo.name)\n\t\t\tc.disableMetric(ownerInfo)\n\t\t\t_ = c.deletedIndexer.Delete(key)\n\t\t}\n\n\t} else {\n\t\tpod := obj.(*v1.Pod)\n\t\townerInfo := getPodOwnerInfo(pod)\n\n\t\tif _, ok := c.podCache[ownerInfo.name]; !ok {\n\t\t\tc.podCache[ownerInfo.name] = map[VolumeName]bool{}\n\t\t}\n\t\tklog.Infof(\"controlling backup config for %s\", pod.GetName())\n\t\tmissings := c.getMissingBackups(pod)\n\t\tif len(missings) > 0 {\n\t\t\tklog.Infof(\"backup missing enable metric for %s\", ownerInfo.name)\n\t\t\tc.enableMetric(ownerInfo, missings)\n\t\t}\n\t}\n\n\treturn nil\n}", "func IsCatchingUp(b bazooka.Bazooka, db db.DB) (bool, error) {\n\ttotalBatches, err := b.TotalBatches()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\ttotalBatchedStored, err := db.GetBatchCount()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t// if total batchse are greater than what we recorded we are still catching up\n\tif totalBatches > uint64(totalBatchedStored) {\n\t\treturn true, err\n\t}\n\n\treturn false, nil\n}", "func (alloc *Alloc) CheckTaskStates(state string) bool {\n\tfor k := range alloc.Tasks {\n\t\ttask := alloc.Tasks[k]\n\t\tif task.State != state {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func checkExistingState() error {\n\n\t// In case any previous volumes are present\n\t// clean up is needed\n\n\tvols, err := client.ListVolumes()\n\tif err != nil {\n\t\trwolog.Error(\"Error while listing volumes \", err)\n\t\treturn err\n\t}\n\n\tpeers, err := client.PeerStatus()\n\tif err != nil {\n\t\trwolog.Error(\"Error while checking gluster Pool list\", err.Error())\n\t\treturn err\n\t}\n\n\tif len(vols) >= 1 || len(peers) >= 1 {\n\t\t// check if the current member has any previous volumes/peers associated with it.\n\t\t// if yes, then check if the member is joining previous cluster,\n\t\t// else remove the volumes and join the cluster\n\t\terr = checkOldStateOfGluster()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func (queryRunner *GpQueryRunner) buildIsInBackup() string {\n\treturn `\nSELECT pg_is_in_backup(), gp_segment_id FROM gp_dist_random('gp_id')\nUNION ALL\nSELECT pg_is_in_backup(), -1;\n`\n}", "func (o *ModelsBackupSchedule) HasSchedule() bool {\n\tif o != nil && o.Schedule != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (nd *Node) MigrationInProgress() (bool, error) {\n\tvalues, err := RequestNodeStats(nd)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t// if the migration_progress_send exists and is not `0`, then migration is in progress\n\tif migration, exists := values[\"migrate_progress_send\"]; exists && migration != \"0\" {\n\t\treturn true, nil\n\t}\n\n\t// migration not in progress\n\treturn false, nil\n}", "func (a *actionRebuildOutSyncedShards) checkRebuildShardProgress(ctx context.Context, clientAsync, clientSync driver.Client, shardID, database, jobID, batchID string) (bool, error) {\n\treq, err := a.createShardRebuildRequest(clientAsync, shardID, database, batchID)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tresp, err := clientAsync.Connection().Do(conn.WithAsyncID(ctx, jobID), req)\n\tif err != nil {\n\t\tif _, ok := conn.IsAsyncJobInProgress(err); ok {\n\t\t\treturn true, nil\n\t\t}\n\n\t\t// Add wait grace period\n\t\tif ok := conn.IsAsyncErrorNotFound(err); ok {\n\t\t\tif s := a.action.StartTime; s != nil && !s.Time.IsZero() {\n\t\t\t\tif time.Since(s.Time) < 10*time.Second {\n\t\t\t\t\t// Retry\n\t\t\t\t\treturn true, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn false, errors.Wrapf(err, \"check rebuild progress error\")\n\t}\n\n\t// cleanup batch\n\t_ = a.deleteBatch(ctx, clientSync, batchID)\n\n\tif resp.StatusCode() == http.StatusNoContent {\n\t\treturn false, nil\n\t} else {\n\t\treturn false, errors.Wrapf(err, \"rebuild progress failed with status code %d\", resp.StatusCode())\n\t}\n}", "func (t *Task) deleteStaleBackupsOnCluster(cluster *migapi.MigCluster) (int, int, error) {\n\tt.Log.Info(\"Checking for stale Velero Backups on MigCluster\",\n\t\t\"migCluster\", path.Join(cluster.Namespace, cluster.Name))\n\tnDeleted := 0\n\tnInProgressDeleted := 0\n\n\tclusterClient, err := cluster.GetClient(t.Client)\n\tif err != nil {\n\t\treturn 0, 0, liberr.Wrap(err)\n\t}\n\n\tlist := velero.BackupList{}\n\terr = clusterClient.List(\n\t\tcontext.TODO(),\n\t\t&list,\n\t\tk8sclient.InNamespace(migapi.VeleroNamespace))\n\tif err != nil {\n\t\treturn 0, 0, liberr.Wrap(err)\n\t}\n\tfor _, backup := range list.Items {\n\t\t// Skip delete unless phase is \"\", \"New\" or \"InProgress\"\n\t\tif backup.Status.Phase != velero.BackupPhaseNew &&\n\t\t\tbackup.Status.Phase != velero.BackupPhaseInProgress &&\n\t\t\tbackup.Status.Phase != \"\" {\n\t\t\tt.Log.V(4).Info(\"Backup phase is not 'New' or 'InProgress'. Skipping deletion.\",\n\t\t\t\t\"backup\", path.Join(backup.Namespace, backup.Name),\n\t\t\t\t\"backupPhase\", backup.Status.Phase)\n\t\t\tcontinue\n\t\t}\n\t\t// Skip if missing a migmigration correlation label (only delete our own CRs)\n\t\tmigMigrationUID, ok := backup.ObjectMeta.Labels[migapi.MigMigrationLabel]\n\t\tif !ok {\n\t\t\tt.Log.V(4).Info(\"Backup does not have an attached label \"+\n\t\t\t\t\"associating it with a MigMigration. Skipping deletion.\",\n\t\t\t\t\"backup\", path.Join(backup.Namespace, backup.Name),\n\t\t\t\t\"backupPhase\", backup.Status.Phase,\n\t\t\t\t\"associationLabel\", migapi.MigMigrationLabel)\n\t\t\tcontinue\n\t\t}\n\t\t// Skip if correlation label points to an existing, running migration\n\t\tisRunning, err := t.migrationUIDisRunning(migMigrationUID)\n\t\tif err != nil {\n\t\t\treturn nDeleted, nInProgressDeleted, liberr.Wrap(err)\n\t\t}\n\t\tif isRunning {\n\t\t\tt.Log.Info(\"Backup is running. Skipping deletion.\",\n\t\t\t\t\"backup\", path.Join(backup.Namespace, backup.Name),\n\t\t\t\t\"backupPhase\", backup.Status.Phase)\n\t\t\tcontinue\n\t\t}\n\t\t// Submit a request to remove backup assets from storage\n\t\t// Note, this will probably be a no-op. See velero backup_deletion_controller.go\n\t\tdeleteBackupRequest := &velero.DeleteBackupRequest{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: migapi.VeleroNamespace,\n\t\t\t\tGenerateName: backup.Name + \"-\",\n\t\t\t},\n\t\t\tSpec: velero.DeleteBackupRequestSpec{\n\t\t\t\tBackupName: backup.Name,\n\t\t\t},\n\t\t}\n\t\tt.Log.Info(\"CREATING Velero DeleteBackupRequest for Backup on MigCluster\",\n\t\t\t\"backup\", path.Join(backup.Namespace, backup.Name),\n\t\t\t\"backupPhase\", backup.Status.Phase,\n\t\t\t\"migCluster\", path.Join(cluster.Namespace, cluster.Name))\n\t\terr = clusterClient.Create(context.TODO(), deleteBackupRequest)\n\t\tif err != nil {\n\t\t\treturn nDeleted, nInProgressDeleted, liberr.Wrap(err)\n\t\t}\n\t\t// Also delete the backup CR directly\n\t\t// This should work since backup is still in-progress.\n\t\tt.Log.Info(\"DELETING stale Velero Backup from MigCluster\",\n\t\t\t\"backup\", path.Join(backup.Namespace, backup.Name),\n\t\t\t\"backupPhase\", backup.Status.Phase,\n\t\t\t\"migCluster\", path.Join(cluster.Namespace, cluster.Name))\n\t\terr = clusterClient.Delete(context.TODO(), &backup)\n\t\tif err != nil && !k8serrors.IsNotFound(err) {\n\t\t\treturn nDeleted, nInProgressDeleted, liberr.Wrap(err)\n\t\t}\n\t\tnDeleted++\n\t\t// Separate count for InProgress, used to determine if restart needed\n\t\tif backup.Status.Phase == velero.BackupPhaseInProgress {\n\t\t\tnInProgressDeleted++\n\t\t}\n\t}\n\n\treturn nDeleted, nInProgressDeleted, err\n}", "func (s *Scheduler) CheckJobsToExecute(now time.Time) {\n\tif rdb.Available() {\n\t\t// TODO: Pensar em um jeito de impedir threads diferentes pegarem a mesma instância de job\n\t\tjobInstances := []JobInstance{}\n\t\tjobInstanceTable := constants.TableCoreJobInstances\n\n\t\terr := db.SelectStruct(jobInstanceTable, &jobInstances, &db.Options{\n\t\t\tConditions: builder.Equal(\"status\", constants.JobStatusCreated),\n\t\t})\n\t\tif err != nil {\n\t\t\t// TODO: Pensar em como tratar esse erro\n\t\t\tfmt.Println(err.Error())\n\t\t\ts.WG.Done()\n\t\t\treturn\n\t\t}\n\n\t\tjobInstanceIDColumn := fmt.Sprintf(\"%s.id\", jobInstanceTable)\n\n\t\tfor _, jobInstance := range jobInstances {\n\t\t\tjobInstance.Status = constants.JobStatusInQueue\n\t\t\tjobInstance.UpdatedAt = time.Now()\n\n\t\t\terr := rdb.LPush(\"queue:jobs\", jobInstance.ID)\n\n\t\t\tif err != nil {\n\t\t\t\tjobInstance.Status = constants.JobStatusCreated\n\t\t\t\tfmt.Printf(\"JOB Instance ID: %s | Error trying to send to queue: %s\\n\", jobInstance.ID, err.Error())\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"JOB Instance ID: %s | Sent to queue successfully\\n\", jobInstance.ID)\n\t\t\t}\n\n\t\t\t// TODO: change to transaction\n\t\t\terr = db.UpdateStruct(jobInstanceTable, &jobInstance, &db.Options{\n\t\t\t\tConditions: builder.Equal(jobInstanceIDColumn, jobInstance.ID),\n\t\t\t}, \"status\", \"updated_at\")\n\t\t\tif err != nil {\n\t\t\t\t// TODO: Pensar em como tratar esse erro\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t}\n\t\t}\n\t}\n\ts.WG.Done()\n}", "func (c *Checkpoint) IsNew() bool {\n\treturn c.State == ActiveState && c.ID == 0 && c.EndTime == nil &&\n\t\tc.UUID == nil && len(c.Resources) == 0 && len(c.Metadata) == 0\n}", "func (r *Reservation) IsSuccessfullyDeployed() bool {\n\tsucceeded := false\n\tif len(r.Results) >= len(r.Workloads(\"\")) {\n\t\tsucceeded = true\n\t\tfor _, result := range r.Results {\n\t\t\tif result.State != generated.ResultStateOK {\n\t\t\t\tsucceeded = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn succeeded\n}", "func (b *gsDBBackup) getBackupMetrics(now time.Time) (time.Time, int64, error) {\n\tlastTime := time.Time{}\n\tvar count int64 = 0\n\tcountAfter := now.Add(-24 * time.Hour)\n\terr := gs.AllFilesInDir(b.gsClient, b.gsBucket, DB_BACKUP_DIR, func(item *storage.ObjectAttrs) {\n\t\tif item.Updated.After(lastTime) {\n\t\t\tlastTime = item.Updated\n\t\t}\n\t\tif item.Updated.After(countAfter) {\n\t\t\tcount++\n\t\t}\n\t})\n\treturn lastTime, count, err\n}", "func (b *gsDBBackup) maybeBackupDB(now time.Time) {\n\tb.maybeBackupDBLiveness.Reset()\n\t// Look for a trigger file written by task-scheduler-db-backup.service\n\t// or a previous automatic backup attempt.\n\tbasename, attemptCount, err := b.findAndParseTriggerFile()\n\tif err != nil {\n\t\tglog.Error(err)\n\t}\n\tif basename == \"\" {\n\t\treturn\n\t}\n\tattemptCount++\n\tif attemptCount == 1 {\n\t\tglog.Infof(\"Beginning automatic DB backup.\")\n\t} else {\n\t\tglog.Infof(\"Retrying automatic DB backup -- attempt %d.\", attemptCount)\n\t}\n\tif err := b.backupDB(now, basename); err != nil {\n\t\tglog.Errorf(\"Automatic DB backup failed: %s\", err)\n\t\tif attemptCount >= RETRY_COUNT {\n\t\t\tglog.Errorf(\"Automatic DB backup failed after %d attempts. Retries exhausted.\", attemptCount)\n\t\t\tif err := b.deleteTriggerFile(basename); err != nil {\n\t\t\t\tglog.Error(err)\n\t\t\t}\n\t\t} else {\n\t\t\tif err := b.writeTriggerFile(basename, attemptCount); err != nil {\n\t\t\t\tglog.Error(err)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tglog.Infof(\"Completed automatic DB backup.\")\n\t\tif err := b.deleteTriggerFile(basename); err != nil {\n\t\t\tglog.Error(err)\n\t\t}\n\t}\n}", "func (r *BackupReconciler) reconcileVerifyExists(ctx context.Context, backup *v1alpha1.Backup) (ctrl.Result, error) {\n\tvar errMsgs []string\n\tif backup.Spec.Type != commonv1alpha1.BackupTypePhysical {\n\t\terrMsgs = append(errMsgs, fmt.Sprintf(\"%v backup does not support VerifyExists mode\", backup.Spec.Type))\n\t}\n\n\tif backup.Spec.GcsPath == \"\" {\n\t\terrMsgs = append(errMsgs, fmt.Sprintf(\".spec.gcsPath must be specified, VerifyExists mode only support GCS based physical backup\"))\n\t}\n\n\tif len(errMsgs) > 0 {\n\t\tbackup.Status.Phase = commonv1alpha1.BackupFailed\n\t\tmsg := strings.Join(errMsgs, \"; \")\n\t\tr.Recorder.Event(backup, corev1.EventTypeWarning, k8s.NotSupported, msg)\n\t\tbackup.Status.Conditions = k8s.Upsert(backup.Status.Conditions, k8s.Ready, v1.ConditionFalse, k8s.NotSupported, msg)\n\t\treturn ctrl.Result{}, r.Status().Update(ctx, backup)\n\t}\n\n\t// controller can run in different namespaces, hence different k8s service account.\n\t// it is better to verify physical backup in data plane.\n\t// In the future, we may consider deploying an independent pod to help verify a backup,\n\t// so that verification does not depend on the instance pod.\n\tinst := &v1alpha1.Instance{}\n\t// ensure data plane is ready\n\tif err := r.instReady(ctx, backup.Namespace, backup.Spec.Instance, inst); err != nil {\n\t\tr.Log.Error(err, \"instance not ready\")\n\t\treturn ctrl.Result{RequeueAfter: time.Second}, nil\n\t}\n\tr.Log.Info(\"Verifying the existence of a backup\")\n\n\tcaClient, closeConn, err := r.ClientFactory.New(ctx, r, backup.Namespace, inst.Name)\n\tif err != nil {\n\t\treturn ctrl.Result{}, fmt.Errorf(\"failed to create config agent client: %w\", err)\n\t}\n\tdefer closeConn()\n\tresp, err := caClient.VerifyPhysicalBackup(ctx, &capb.VerifyPhysicalBackupRequest{\n\t\tGcsPath: backup.Spec.GcsPath,\n\t})\n\tif err != nil {\n\t\tr.Log.Error(err, \"failed to verify a physical backup\")\n\t\t// retry\n\t\treturn ctrl.Result{Requeue: true}, nil\n\t}\n\tif len(resp.ErrMsgs) == 0 {\n\t\tbackup.Status.Phase = commonv1alpha1.BackupSucceeded\n\t\tmsg := \"verified the existence of a physical backup\"\n\t\tr.Recorder.Event(backup, corev1.EventTypeNormal, \"BackupVerified\", msg)\n\t\tbackup.Status.Conditions = k8s.Upsert(backup.Status.Conditions, k8s.Ready, v1.ConditionTrue, k8s.BackupReady, msg)\n\t} else {\n\t\tbackup.Status.Phase = commonv1alpha1.BackupFailed\n\t\tmsg := fmt.Sprintf(\"Failed to verify the existence of a physical backup: %s\", strings.Join(resp.GetErrMsgs(), \"; \"))\n\t\tr.Recorder.Event(backup, corev1.EventTypeWarning, \"BackupVerifyFailed\", msg)\n\t\tbackup.Status.Conditions = k8s.Upsert(backup.Status.Conditions, k8s.Ready, v1.ConditionFalse, k8s.BackupFailed, msg)\n\t}\n\treturn ctrl.Result{RequeueAfter: verifyExistsInterval}, r.Status().Update(ctx, backup)\n}", "func isDuplicateStateUpdate(\n\ttaskInfo *pb_task.TaskInfo,\n\tupdateEvent *statusupdate.Event,\n) bool {\n\tif updateEvent.State() != taskInfo.GetRuntime().GetState() {\n\t\treturn false\n\t}\n\n\tmesosTaskStatus := updateEvent.MesosTaskStatus()\n\tpodEvent := updateEvent.PodEvent()\n\n\tif updateEvent.State() != pb_task.TaskState_RUNNING {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"db_task_runtime\": taskInfo.GetRuntime(),\n\t\t\t\"task_status_event\": mesosTaskStatus,\n\t\t\t\"pod_event\": podEvent,\n\t\t}).Debug(\"skip same status update if state is not RUNNING\")\n\t\treturn true\n\t}\n\n\tif taskInfo.GetConfig().GetHealthCheck() == nil ||\n\t\t!taskInfo.GetConfig().GetHealthCheck().GetEnabled() {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"db_task_runtime\": taskInfo.GetRuntime(),\n\t\t\t\"task_status_event\": mesosTaskStatus,\n\t\t\t\"pod_event\": podEvent,\n\t\t}).Debug(\"skip same status update if health check is not configured or \" +\n\t\t\t\"disabled\")\n\t\treturn true\n\t}\n\n\tnewStateReason := updateEvent.Reason()\n\t// TODO p2k: not sure which kubelet reason matches this.\n\t// Should we skip some status updates from kubelets?\n\tif newStateReason != mesos.TaskStatus_REASON_TASK_HEALTH_CHECK_STATUS_UPDATED.String() {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"db_task_runtime\": taskInfo.GetRuntime(),\n\t\t\t\"task_status_event\": mesosTaskStatus,\n\t\t\t\"pod_event\": podEvent,\n\t\t}).Debug(\"skip same status update if status update reason is not from health check\")\n\t\treturn true\n\t}\n\n\t// Current behavior will log consecutive negative health check results\n\t// ToDo (varung): Evaluate if consecutive negative results should be logged or not\n\tisPreviousStateHealthy := taskInfo.GetRuntime().GetHealthy() == pb_task.HealthState_HEALTHY\n\tif !isPreviousStateHealthy {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"db_task_runtime\": taskInfo.GetRuntime(),\n\t\t\t\"task_status_event\": mesosTaskStatus,\n\t\t\t\"pod_event\": podEvent,\n\t\t}).Debug(\"log each negative health check result\")\n\t\treturn false\n\t}\n\n\tif updateEvent.Healthy() == isPreviousStateHealthy {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"db_task_runtime\": taskInfo.GetRuntime(),\n\t\t\t\"task_status_event\": mesosTaskStatus,\n\t\t\t\"pod_event\": podEvent,\n\t\t}).Debug(\"skip same status update if health check result is positive consecutively\")\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (b *Backtest) IsRunning() (ret bool) {\n\treturn b.running\n}", "func isStepRunning(index int, stageSteps []v1.CoreActivityStep) bool {\n\tif len(stageSteps) > 0 {\n\t\tpreviousStep := stageSteps[index-1]\n\t\treturn previousStep.CompletedTimestamp != nil\n\t}\n\treturn true\n}", "func CheckFsCreationInProgress(device model.Device) (inProgress bool, err error) {\n\treturn linux.CheckFsCreationInProgress(device)\n}", "func (sp SnapshotPolicy) IsAllNew() bool { return sp == SnapshotPolicyAllNew || sp == \"\" }", "func (o *UcsdBackupInfoAllOf) HasBackupSize() bool {\n\tif o != nil && o.BackupSize != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func notRunning(statuses []v1.ContainerStatus) bool {\n\tfor _, status := range statuses {\n\t\tif status.State.Terminated == nil && status.State.Waiting == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func statefulSetProgressing(ss *appsv1.StatefulSet) bool {\n\tstatus := ss.Status\n\n\t// Copy-pasted from status_manager: Determine if a DaemonSet is progressing\n\tprogressing := (status.ReadyReplicas < status.Replicas ||\n\t\tstatus.AvailableReplicas == 0 ||\n\t\tss.Generation > status.ObservedGeneration)\n\n\ts := \"progressing\"\n\tif !progressing {\n\t\ts = \"complete\"\n\t}\n\tklog.V(2).Infof(\"statefulset %s/%s rollout %s; %d/%d scheduled; %d available; generation %d -> %d\",\n\t\tss.Namespace, ss.Name, s, status.ReadyReplicas, status.Replicas,\n\t\tstatus.AvailableReplicas, ss.Generation, status.ObservedGeneration)\n\n\tif !progressing {\n\t\tklog.V(2).Infof(\"statefulset %s/%s rollout complete\", ss.Namespace, ss.Name)\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (tp *Tableprov) checkForChanges(file string) (usesBackup, bool, error) {\n\tf, err := os.Stat(file)\n\t_, bErr := os.Stat(bak(file))\n\ttf, tErr := os.Stat(tmp(file))\n\n\t// Does the file even exist?\n\tif err != nil { // No\n\t\t// Check for a backup file\n\t\tif bErr != nil {\n\t\t\treturn false, false, err\n\t\t}\n\t\treturn true, false, nil\n\t}\n\n\t// Does a tmpfile exist?\n\tif tErr == nil { // Yes, we probably crashed while reading this file.\n\t\t// Has a new file arrived?\n\t\tif f.ModTime().After(tf.ModTime()) {\n\t\t\t// Yes\n\t\t\treturn false, true, nil\n\t\t}\n\t\t// No, check for a backup file\n\t\tif bErr != nil {\n\t\t\treturn false, false, bErr\n\t\t}\n\t\treturn true, false, nil\n\t}\n\n\t// Does the backup file exist?\n\tif bErr != nil { // No\n\t\treturn false, true, nil\n\t}\n\n\t// Check if the table file has been modified\n\tif f.ModTime() == tp.Tables[file].timestamp {\n\t\t// No, use the backup file\n\t\treturn true, false, nil\n\t}\n\treturn false, true, nil\n}", "func (o *ModelsBackupSchedule) HasRetentionCount() bool {\n\tif o != nil && o.RetentionCount != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (b *BackuPOT) needBackup(remotePath remotePath, newFileInfo *RemoteFileInfo) (bool, error) {\n // get remote file info\n fileInfo, err := b.getRemoteFileInfo(remotePath, -1)\n if err != nil {\n // check err kind.\n if !strings.HasPrefix(err.Error(), \"The key doesn't exist.\") {\n return false, backupotDebug.Error(err)\n } else {\n return true, nil\n }\n }\n if fileInfo.EncodedHash != newFileInfo.EncodedHash {\n return true, nil\n }\n return false, nil\n}", "func getBackupStats(backup *velero.Backup) (itemsBackedUp int, totalItems int) {\n\tif backup == nil || backup.Status.Progress == nil {\n\t\treturn\n\t}\n\ttotalItems = backup.Status.Progress.TotalItems\n\titemsBackedUp = backup.Status.Progress.ItemsBackedUp\n\treturn\n}", "func (j *ScheduledJob) IsPaused() bool {\n\treturn j.rec.NextRun == time.Time{}\n}", "func (p PodStatusInformation) IsNew(lastSeen PodStatusInformation, timeSince int) bool {\n\n\t// assume not a failure\n\tif p.Image == \"\" || p.ContainerName == \"\" || p.FinishedAt.IsZero() {\n\t\treturn false\n\t}\n\n\t// Check to see if its been over 'x' minutes, if so its new yet again.\n\tif ok := p.timeCheck(lastSeen, timeSince); ok {\n\t\treturn true\n\t}\n\n\t// Identical\n\tif reflect.DeepEqual(p, lastSeen) {\n\n\t\treturn false\n\t}\n\n\tif p.PodName == lastSeen.PodName && p.ContainerName == lastSeen.PodName {\n\n\t\treturn false\n\t}\n\n\t// Same pod, same start time\n\tif p.PodName == lastSeen.PodName && p.StartedAt == lastSeen.StartedAt {\n\n\t\treturn false\n\t}\n\n\t// same container, same exit code\n\tif p.ContainerName == lastSeen.ContainerName && p.ExitCode == lastSeen.ExitCode {\n\n\t\treturn false\n\t}\n\n\t// same container, same exit code\n\tif p.PodName == lastSeen.PodName && p.ExitCode == lastSeen.ExitCode {\n\n\t\treturn false\n\t}\n\n\treturn true\n}", "func ArchInBackup(arch Archive, backup *Backup) bool {\n\tbackupStart := backup.MongoMeta.Before.LastMajTS\n\tbackupEnd := backup.MongoMeta.After.LastMajTS\n\treturn TimestampInInterval(arch.Start, backupStart, backupEnd) ||\n\t\tTimestampInInterval(arch.End, backupStart, backupEnd) ||\n\t\tTimestampInInterval(backupStart, arch.Start, arch.End) ||\n\t\tTimestampInInterval(backupEnd, arch.Start, arch.End)\n}", "func (s *Step) IsNew() bool {\n\treturn s.State == ActiveState && s.EndTime == nil && len(s.Metrics) == 0\n}", "func (f *fwUpdater) isChecking(imsi int64) bool {\n\tf.mutex.Lock()\n\tdefer f.mutex.Unlock()\n\tcheck, ret := f.inProgress[imsi]\n\tif check && ret {\n\t\treturn true\n\t}\n\treturn false\n}", "func (t *Task) deleteStalePVBsOnCluster(cluster *migapi.MigCluster) (int, error) {\n\tt.Log.Info(\"Checking for stale PodVolumeBackups on MigCluster\",\n\t\t\"migCluster\", path.Join(cluster.Namespace, cluster.Name))\n\tnDeleted := 0\n\tclusterClient, err := cluster.GetClient(t.Client)\n\tif err != nil {\n\t\treturn 0, liberr.Wrap(err)\n\t}\n\n\tlist := velero.PodVolumeBackupList{}\n\terr = clusterClient.List(\n\t\tcontext.TODO(),\n\t\t&list,\n\t\tk8sclient.InNamespace(migapi.VeleroNamespace))\n\tif err != nil {\n\t\treturn 0, liberr.Wrap(err)\n\t}\n\tfor _, pvb := range list.Items {\n\t\t// Skip delete unless phase is \"\", \"New\" or \"InProgress\"\n\t\tif pvb.Status.Phase != velero.PodVolumeBackupPhaseNew &&\n\t\t\tpvb.Status.Phase != velero.PodVolumeBackupPhaseInProgress &&\n\t\t\tpvb.Status.Phase != \"\" {\n\t\t\tt.Log.V(4).Info(\"PodVolumeBackup with is not 'New' or 'InProgress'. Skipping deletion.\",\n\t\t\t\t\"podVolumeBackup\", path.Join(pvb.Namespace, pvb.Name),\n\t\t\t\t\"podVolumeBackupPhase\", pvb.Status.Phase)\n\t\t\tcontinue\n\t\t}\n\t\t// Skip delete if PVB is associated with running migration\n\t\tpvbHasRunningMigration := false\n\t\tfor _, ownerRef := range pvb.OwnerReferences {\n\t\t\tif ownerRef.Kind != \"Backup\" {\n\t\t\t\tt.Log.V(4).Info(\"PodVolumeBackup does not have an OwnerRef associated \"+\n\t\t\t\t\t\"with a Velero Backup. Skipping deletion.\",\n\t\t\t\t\t\"podVolumeBackup\", path.Join(pvb.Namespace, pvb.Name),\n\t\t\t\t\t\"podVolumeBackupPhase\", pvb.Status.Phase)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbackup := velero.Backup{}\n\t\t\terr := clusterClient.Get(\n\t\t\t\tcontext.TODO(),\n\t\t\t\ttypes.NamespacedName{\n\t\t\t\t\tNamespace: migapi.VeleroNamespace,\n\t\t\t\t\tName: ownerRef.Name,\n\t\t\t\t},\n\t\t\t\t&backup,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn nDeleted, liberr.Wrap(err)\n\t\t\t}\n\t\t\t// Skip delete if missing a migmigration correlation label (only delete our own CRs)\n\t\t\tmigMigrationUID, ok := backup.ObjectMeta.Labels[migapi.MigMigrationLabel]\n\t\t\tif !ok {\n\t\t\t\tt.Log.V(4).Info(\"PodVolumeBackup does not have an attached label \"+\n\t\t\t\t\t\"associating it with a MigMigration. Skipping deletion.\",\n\t\t\t\t\t\"podVolumeBackup\", path.Join(pvb.Namespace, pvb.Name),\n\t\t\t\t\t\"podVolumeBackupPhase\", pvb.Status.Phase,\n\t\t\t\t\t\"associationLabel\", migapi.MigMigrationLabel)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tisRunning, err := t.migrationUIDisRunning(migMigrationUID)\n\t\t\tif err != nil {\n\t\t\t\treturn nDeleted, liberr.Wrap(err)\n\t\t\t}\n\t\t\tif isRunning {\n\t\t\t\tpvbHasRunningMigration = true\n\t\t\t}\n\t\t}\n\t\tif pvbHasRunningMigration == true {\n\t\t\tt.Log.Info(\"PodVolumeBackup with is associated with a running migration. Skipping deletion.\",\n\t\t\t\t\"podVolumeBackup\", path.Join(pvb.Namespace, pvb.Name),\n\t\t\t\t\"podVolumeBackupPhase\", pvb.Status.Phase)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Delete the PVB\n\t\tt.Log.Info(\"DELETING stale Velero PodVolumeBackup from MigCluster\",\n\t\t\t\"podVolumeBackup\", path.Join(pvb.Namespace, pvb.Name),\n\t\t\t\"podVolumeBackupPhase\", pvb.Status.Phase,\n\t\t\t\"migCluster\", path.Join(cluster.Namespace, cluster.Name))\n\t\terr = clusterClient.Delete(context.TODO(), &pvb)\n\t\tif err != nil && !k8serrors.IsNotFound(err) {\n\t\t\treturn nDeleted, liberr.Wrap(err)\n\t\t}\n\t\tnDeleted++\n\t}\n\n\treturn nDeleted, nil\n}", "func (tk *timekeeper) checkPendingTS(streamId common.StreamId, bucket string) {\n\n\t//if there is a flush already in progress for this stream and bucket\n\t//or flush is disabled, nothing to be done\n\tbucketFlushInProgressMap := tk.streamBucketFlushInProgressMap[streamId]\n\tbucketFlushEnabledMap := tk.streamBucketFlushEnabledMap[streamId]\n\n\tif (*bucketFlushInProgressMap)[bucket] == true ||\n\t\t(*bucketFlushEnabledMap)[bucket] == false {\n\t\treturn\n\t}\n\n\t//if there are pending TS for this bucket, send New TS\n\tbucketTsListMap := tk.streamBucketTsListMap[streamId]\n\ttsList := (*bucketTsListMap)[bucket]\n\tif tsList.Len() > 0 {\n\t\te := tsList.Front()\n\t\tts := e.Value.(Timestamp)\n\t\ttsList.Remove(e)\n\t\tcommon.Debugf(\"Timekeeper::checkPendingTS \\n\\tFound Pending Stability TS Bucket: %v \"+\n\t\t\t\"Stream: %v TS: %v\", bucket, streamId, ts)\n\t\tgo tk.sendNewStabilityTS(ts, bucket, streamId)\n\t}\n}", "func TestBackup(t *testing.T) {\n\tt.Run(\"with failing operations\", func(t *testing.T) {\n\t\texec, bctx, _ := testBackupExecutor(t, testFailSyncSpec)\n\n\t\terr := exec.Backup(bctx)\n\n\t\trequire.Error(t, err, \"returns an error of a sync operation fails\")\n\t\tassert.Contains(t, \"test operation failed\", err.Error())\n\t})\n\n\tt.Run(\"with successful operations\", func(t *testing.T) {\n\t\texec, bctx, _ := testBackupExecutor(t, testSuccessSpec)\n\n\t\trequire.NoError(t, exec.Backup(bctx))\n\t})\n\n\tt.Run(\"timeout doesn't hang\", func(t *testing.T) {\n\t\texec, bctx, _ := testBackupExecutorWithTimeout(t, testSuccessSpec, 0)\n\n\t\terr := exec.Backup(bctx)\n\t\trequire.Error(t, err, \"a timeout has happened\")\n\t\tassert.Contains(t, err.Error(), \"context deadline exceeded\")\n\t})\n}", "func (cs *CrawlerSupervisor) HasPending() bool {\n\treturn len(cs.pending) > 0\n}", "func (w *WaitTask) skipped(taskContext *TaskContext, id object.ObjMetadata) bool {\n\tim := taskContext.InventoryManager()\n\tif w.Condition == AllCurrent &&\n\t\tim.IsFailedApply(id) || im.IsSkippedApply(id) {\n\t\treturn true\n\t}\n\tif w.Condition == AllNotFound &&\n\t\tim.IsFailedDelete(id) || im.IsSkippedDelete(id) {\n\t\treturn true\n\t}\n\treturn false\n}", "func findWinChkBackUpToggled() {\n\topt.MakeBackup = obj.findWinChkBackUp.GetActive()\n}", "func (s *trialWorkloadSequencer) UpToDate() bool {\n\t// If all operations for the last asked-for step are done, then the trial has no more workloads\n\t// to run at the moment. We check len(s.ops) <= s.CurOpIdx for the case when in restart\n\t// the trial has been recreated from a snapshot but not received its current operations.\n\treturn len(s.ops) <= s.CurOpIdx && !s.hasSearcherValidation() ||\n\t\ts.ExitingEarly && !s.postGracefulStopCheckpointNeeded()\n}", "func (s *SegmentUpdateWorker) IsRunning() bool {\n\treturn s.lifecycle.IsRunning()\n}", "func (q *ExecutionBroker) notConfirmedPending() bool {\n\treturn q.pending == insolar.InPending && !q.PendingConfirmed\n}", "func (o *RequestsDeploymentScheduledBackup) HasBackupPolicyId() bool {\n\tif o != nil && o.BackupPolicyId != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *Operator) onStartBackup(stop <-chan struct{}) {\n\tfor {\n\t\tif err := o.waitForCRD(false, false, false, true); err == nil {\n\t\t\tbreak\n\t\t} else {\n\t\t\tlog.Error().Err(err).Msg(\"Resource initialization failed\")\n\t\t\tlog.Info().Msgf(\"Retrying in %s...\", initRetryWaitTime)\n\t\t\ttime.Sleep(initRetryWaitTime)\n\t\t}\n\t}\n\toperatorName := \"arangodb-backup-operator\"\n\toperator := backupOper.NewOperator(operatorName, o.Namespace)\n\n\trand.Seed(time.Now().Unix())\n\n\tzerolog.SetGlobalLevel(zerolog.DebugLevel)\n\n\trestClient, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tarangoClientSet, err := arangoClientSet.NewForConfig(restClient)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tkubeClientSet, err := kubernetes.NewForConfig(restClient)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\teventRecorder := event.NewEventRecorder(operatorName, kubeClientSet)\n\n\tarangoInformer := arangoInformer.NewSharedInformerFactoryWithOptions(arangoClientSet, 10*time.Second, arangoInformer.WithNamespace(o.Namespace))\n\n\tif err = backup.RegisterInformer(operator, eventRecorder, arangoClientSet, kubeClientSet, arangoInformer); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err = policy.RegisterInformer(operator, eventRecorder, arangoClientSet, kubeClientSet, arangoInformer); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err = operator.RegisterStarter(arangoInformer); err != nil {\n\t\tpanic(err)\n\t}\n\n\tprometheus.MustRegister(operator)\n\n\toperator.Start(8, stop)\n\to.Dependencies.BackupProbe.SetReady()\n\n\t<-stop\n}", "func (r *OpenedxReconciler) isMysqlUp(instance *cachev1.Openedx) bool {\n\tdeployment := &appsv1.Deployment{}\n\n\terr := r.Client.Get(context.TODO(), types.NamespacedName{\n\t\tName: mysqlDeploymentName(instance),\n\t\tNamespace: instance.Namespace,\n\t}, deployment)\n\n\tif err != nil {\n\t\tlog.Error(err, \"Deployment mysql not found\")\n\t\treturn false\n\t}\n\n\tif deployment.Status.ReadyReplicas == 1 {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func TearDownBackupRestoreAll() {\n\tlogrus.Infof(\"Enumerating scheduled backups\")\n\tbkpScheduleEnumerateReq := &api.BackupScheduleEnumerateRequest{\n\t\tOrgId: OrgID,\n\t\tLabels: make(map[string]string),\n\t\tBackupLocationRef: &api.ObjectRef{\n\t\t\tName: backupLocationName,\n\t\t\tUid: BackupLocationUID,\n\t\t},\n\t}\n\tctx, err := backup.GetPxCentralAdminCtx()\n\texpect(err).NotTo(haveOccurred())\n\tenumBkpScheduleResponse, _ := Inst().Backup.EnumerateBackupSchedule(ctx, bkpScheduleEnumerateReq)\n\tbkpSchedules := enumBkpScheduleResponse.GetBackupSchedules()\n\tfor _, bkpSched := range bkpSchedules {\n\t\tschedPol := bkpSched.GetSchedulePolicyRef()\n\t\tDeleteScheduledBackup(bkpSched.GetName(), bkpSched.GetUid(), schedPol.GetName(), schedPol.GetUid())\n\t}\n\n\tlogrus.Infof(\"Enumerating backups\")\n\tbkpEnumerateReq := &api.BackupEnumerateRequest{\n\t\tOrgId: OrgID,\n\t}\n\tctx, err = backup.GetPxCentralAdminCtx()\n\texpect(err).NotTo(haveOccurred())\n\tenumBkpResponse, _ := Inst().Backup.EnumerateBackup(ctx, bkpEnumerateReq)\n\tbackups := enumBkpResponse.GetBackups()\n\tfor _, bkp := range backups {\n\t\tDeleteBackup(bkp.GetName(), OrgID)\n\t}\n\n\tlogrus.Infof(\"Enumerating restores\")\n\trestoreEnumerateReq := &api.RestoreEnumerateRequest{\n\t\tOrgId: OrgID}\n\tctx, err = backup.GetPxCentralAdminCtx()\n\texpect(err).NotTo(haveOccurred())\n\tenumRestoreResponse, _ := Inst().Backup.EnumerateRestore(ctx, restoreEnumerateReq)\n\trestores := enumRestoreResponse.GetRestores()\n\tfor _, restore := range restores {\n\t\tDeleteRestore(restore.GetName(), OrgID)\n\t}\n\n\tfor _, bkp := range backups {\n\t\tInst().Backup.WaitForBackupDeletion(ctx, bkp.GetName(), OrgID,\n\t\t\tBackupRestoreCompletionTimeoutMin*time.Minute,\n\t\t\tRetrySeconds*time.Second)\n\t}\n\tfor _, restore := range restores {\n\t\tInst().Backup.WaitForRestoreDeletion(ctx, restore.GetName(), OrgID,\n\t\t\tBackupRestoreCompletionTimeoutMin*time.Minute,\n\t\t\tRetrySeconds*time.Second)\n\t}\n\tprovider := GetProvider()\n\tDeleteCluster(destinationClusterName, OrgID)\n\tDeleteCluster(sourceClusterName, OrgID)\n\tDeleteBackupLocation(backupLocationName, OrgID)\n\tDeleteCloudCredential(CredName, OrgID, CloudCredUID)\n\tDeleteBucket(provider, BucketName)\n}", "func (r *BackupItem) IsArchived() bool {\n\treturn r.Status&StatusArchived == StatusArchived\n}", "func (r *BackupItem) IsArchived() bool {\n\treturn r.Status&StatusArchived == StatusArchived\n}", "func (dn *DNode) HasPendingSync() bool {\n\tvar retVal bool\n\tdn.tshards.Range(func(key interface{}, value interface{}) bool {\n\t\tshard := value.(*TshardState)\n\t\tshard.syncLock.Lock()\n\t\tdefer shard.syncLock.Unlock()\n\t\tif shard.syncPending {\n\t\t\tdn.logger.Infof(\"Datanode %s tstore shard %d replica %d has sync pending\", dn.nodeUUID, shard.shardID, shard.replicaID)\n\t\t\tretVal = true\n\t\t}\n\t\treturn true\n\t})\n\treturn retVal\n}", "func (e *etcdCacheEntry) IsWatching() bool {\n e.RLock()\n defer e.RUnlock()\n return e.watching\n}", "func (r *BackupReconciler) updateBackupStatus(ctx context.Context, backup *v1alpha1.Backup, inst *v1alpha1.Instance) error {\n\treadyCond := k8s.FindCondition(backup.Status.Conditions, k8s.Ready)\n\tif k8s.ConditionReasonEquals(readyCond, k8s.BackupInProgress) {\n\t\tbackup.Status.Phase = commonv1alpha1.BackupInProgress\n\t} else if k8s.ConditionReasonEquals(readyCond, k8s.BackupFailed) {\n\t\tbackup.Status.Phase = commonv1alpha1.BackupFailed\n\t} else if k8s.ConditionReasonEquals(readyCond, k8s.BackupReady) {\n\t\tbackup.Status.Phase = commonv1alpha1.BackupSucceeded\n\t\tif err := r.Status().Update(ctx, backup); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tinst.Status.BackupID = backup.Status.BackupID\n\t\treturn r.Status().Update(ctx, inst)\n\t} else {\n\t\t// No handlers found for current set of conditions\n\t\tbackup.Status.Phase = \"\"\n\t}\n\n\treturn r.Status().Update(ctx, backup)\n}", "func (o *UcsdBackupInfoAllOf) HasStatus() bool {\n\tif o != nil && o.Status != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func IsFileReadyToUpload(regex, fname string, now time.Time) (ok bool, err error) {\n\tr := regexp.MustCompile(regex)\n\tsubS := r.FindStringSubmatch(fname)\n\n\tif len(subS) < 2 {\n\t\treturn false, nil\n\t}\n\n\tlastFinishedBackupFileBeforeHours := 35.0 // 24 + 11,last flush occurred at 10:00 CST\n\tt, err := time.Parse(\"20060102-0700\", subS[1]+\"+0800\")\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"parse file time error\")\n\t}\n\n\tif now.Sub(t).Hours() <= lastFinishedBackupFileBeforeHours {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}", "func (o *InstanceStatusKubernetes) HasBackoffSeconds() bool {\n\tif o != nil && o.BackoffSeconds != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *Job) GetProgressValid(ctx context.Context) (progressValid bool, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceJob, \"ProgressValid\").Store(&progressValid)\n\treturn\n}", "func (v Repository) IsRebaseInProgress() bool {\n\tgitDir := v.RepoDir()\n\treturn path.Exist(filepath.Join(gitDir, \"rebase-apply\")) ||\n\t\tpath.Exist(filepath.Join(gitDir, \"rebase-merge\")) ||\n\t\tpath.Exist(filepath.Join(gitDir, \".dotest\"))\n}", "func (container *container) HasPendingUpdates() (bool, error) {\r\n\treturn false, nil\r\n}" ]
[ "0.65107685", "0.60924333", "0.6047755", "0.59358364", "0.5879894", "0.58064044", "0.579322", "0.5754999", "0.546307", "0.54417455", "0.54404837", "0.54389805", "0.5420077", "0.54141295", "0.53390694", "0.5332677", "0.5270624", "0.52638215", "0.5197946", "0.51915765", "0.5188692", "0.518613", "0.51734096", "0.51526904", "0.51204026", "0.5119891", "0.51149327", "0.5106044", "0.50971216", "0.50916773", "0.5086276", "0.5050972", "0.5048553", "0.5035914", "0.50099075", "0.50032455", "0.50003695", "0.4999434", "0.49806356", "0.49684638", "0.4967716", "0.49625465", "0.4953621", "0.49534264", "0.4943557", "0.49427876", "0.493359", "0.49321347", "0.49201253", "0.4917584", "0.48944977", "0.4886191", "0.48658758", "0.48606896", "0.48600587", "0.48474264", "0.4831539", "0.4821781", "0.48055243", "0.48051438", "0.48013893", "0.47989595", "0.47914934", "0.4780901", "0.4769014", "0.47627932", "0.47615236", "0.47590736", "0.47547832", "0.4749101", "0.4746854", "0.47459584", "0.47450823", "0.47401175", "0.47356316", "0.4728575", "0.47149613", "0.46990344", "0.46956274", "0.46857315", "0.46716258", "0.4663764", "0.46586007", "0.4656676", "0.46536118", "0.46445355", "0.4643809", "0.4641672", "0.46354857", "0.46341377", "0.46341377", "0.46334267", "0.4632463", "0.46300542", "0.4627788", "0.46260625", "0.46117908", "0.46082082", "0.46078554", "0.4606219" ]
0.8554207
0
ifDue check whether schedule is due to create a new backup.
func (c *scheduleReconciler) ifDue(schedule *velerov1.Schedule, cronSchedule cron.Schedule) bool { isDue, nextRunTime := getNextRunTime(schedule, cronSchedule, c.clock.Now()) log := c.logger.WithField("schedule", kube.NamespaceAndName(schedule)) if !isDue { log.WithField("nextRunTime", nextRunTime).Debug("Schedule is not due, skipping") return false } return true }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *scheduleReconciler) checkIfBackupInNewOrProgress(schedule *velerov1.Schedule) bool {\n\tlog := c.logger.WithField(\"schedule\", kube.NamespaceAndName(schedule))\n\tbackupList := &velerov1.BackupList{}\n\toptions := &client.ListOptions{\n\t\tNamespace: schedule.Namespace,\n\t\tLabelSelector: labels.Set(map[string]string{\n\t\t\tvelerov1.ScheduleNameLabel: schedule.Name,\n\t\t}).AsSelector(),\n\t}\n\n\terr := c.List(context.Background(), backupList, options)\n\tif err != nil {\n\t\tlog.Errorf(\"fail to list backup for schedule %s/%s: %s\", schedule.Namespace, schedule.Name, err.Error())\n\t\treturn true\n\t}\n\n\tfor _, backup := range backupList.Items {\n\t\tif backup.Status.Phase == velerov1.BackupPhaseNew || backup.Status.Phase == velerov1.BackupPhaseInProgress {\n\t\t\tlog.Debugf(\"%s/%s still has backups that are in InProgress or New...\", schedule.Namespace, schedule.Name)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func backupScheduleFound(repo v1beta1.PGBackRestRepo, backupType string) bool {\n\tif repo.BackupSchedules != nil {\n\t\tswitch backupType {\n\t\tcase full:\n\t\t\treturn repo.BackupSchedules.Full != nil\n\t\tcase differential:\n\t\t\treturn repo.BackupSchedules.Differential != nil\n\t\tcase incremental:\n\t\t\treturn repo.BackupSchedules.Incremental != nil\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func DueDate(project_name, project_owner, task_name, dueDate string, db *sql.DB) bool {\n\tsqlStatement1 := `SELECT id FROM projects WHERE owner = $1 AND name = $2;`\n\n\tvar parentID string\n\terr = db.QueryRow(sqlStatement1, project_owner, project_name).Scan(&parentID)\n\n\tif err == sql.ErrNoRows {\n\t\treturn false\n\t} else if err != nil {\n\t\treturn false\n\t}\n\n\tsqlStatement := `UPDATE tasks\n \tSET due_date = $1\n \tWHERE project = $2 AND name = $3;`\n\n\t_, err = db.Exec(sqlStatement, dueDate, parentID, task_name)\n\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (solver *MapSolver)HasScheduled(arc *data.Arc) bool{\n\tfor _, cap := range arc.Capacity {\n\t\tif cap > 0 { // if dstNode is not machineNode, we can assume that if capacity > 0, then this task still not scheduled\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (o *TransactionSplit) HasDueDate() bool {\n\tif o != nil && o.DueDate.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (c *Job) canDo() {\n\tdiff := int64(time.Now().Sub(c.nextTime) / time.Millisecond /*1000000*/)\n\tif diff >= 0 {\n\t\tif c.unit == delay || c.timingMode == beforeExecuteTask {\n\t\t\tc.fiber.EnqueueWithTask(c.task)\n\t\t} else {\n\t\t\td := c.task.Run()\n\t\t\tc.nextTime = c.nextTime.Add(d)\n\t\t}\n\t\tswitch c.unit {\n\t\tcase delay:\n\t\t\treturn\n\t\tcase weeks:\n\t\t\tc.nextTime = c.nextTime.AddDate(0, 0, 7)\n\t\tcase days:\n\t\t\tc.nextTime = c.nextTime.AddDate(0, 0, int(c.interval))\n\t\tcase hours:\n\t\t\tc.nextTime = c.nextTime.Add(time.Duration(c.interval) * time.Hour)\n\t\tcase minutes:\n\t\t\tc.nextTime = c.nextTime.Add(time.Duration(c.interval) * time.Minute)\n\t\tcase seconds:\n\t\t\tc.nextTime = c.nextTime.Add(time.Duration(c.interval) * time.Second)\n\t\tcase milliseconds:\n\t\t\tc.nextTime = c.nextTime.Add(time.Duration(c.interval) * time.Millisecond)\n\t\t}\n\t}\n\n\tc.taskDisposer.Dispose()\n\tadjustTime := int64(c.nextTime.Sub(time.Now()) / time.Millisecond /*1000000*/)\n\tc.taskDisposer = c.fiber.Schedule(adjustTime, c.canDo)\n}", "func (c *Circuit) allowNewRun(now time.Time) bool {\n\tif !c.IsOpen() {\n\t\treturn true\n\t}\n\tif c.OpenToClose.Allow(now) {\n\t\treturn true\n\t}\n\treturn false\n}", "func (e *ExternalServiceStore) SyncDue(ctx context.Context, intIDs []int64, d time.Duration) (bool, error) {\n\tif len(intIDs) == 0 {\n\t\treturn false, nil\n\t}\n\tids := make([]*sqlf.Query, 0, len(intIDs))\n\tfor _, id := range intIDs {\n\t\tids = append(ids, sqlf.Sprintf(\"%s\", id))\n\t}\n\tidFilter := sqlf.Sprintf(\"IN (%s)\", sqlf.Join(ids, \",\"))\n\tdeadline := time.Now().Add(d)\n\n\tq := sqlf.Sprintf(`\nSELECT TRUE\nWHERE EXISTS(\n SELECT\n FROM external_services\n WHERE id %s\n AND (\n next_sync_at IS NULL\n OR next_sync_at <= %s)\n )\n OR EXISTS(\n SELECT\n FROM external_service_sync_jobs\n WHERE external_service_id %s\n AND state IN ('queued', 'processing')\n );\n`, idFilter, deadline, idFilter)\n\n\tv, exists, err := basestore.ScanFirstBool(e.Query(ctx, q))\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn v && exists, nil\n}", "func (c *scheduleReconciler) submitBackup(ctx context.Context, schedule *velerov1.Schedule) error {\n\tc.logger.WithField(\"schedule\", schedule.Namespace+\"/\"+schedule.Name).Info(\"Schedule is due, going to submit backup.\")\n\n\tnow := c.clock.Now()\n\t// Don't attempt to \"catch up\" if there are any missed or failed runs - simply\n\t// trigger a Backup if it's time.\n\tbackup := getBackup(schedule, now)\n\tif err := c.Create(ctx, backup); err != nil {\n\t\treturn errors.Wrap(err, \"error creating Backup\")\n\t}\n\n\toriginal := schedule.DeepCopy()\n\tschedule.Status.LastBackup = &metav1.Time{Time: now}\n\n\tif err := c.Patch(ctx, schedule, client.MergeFrom(original)); err != nil {\n\t\treturn errors.Wrapf(err, \"error updating Schedule's LastBackup time to %v\", schedule.Status.LastBackup)\n\t}\n\n\treturn nil\n}", "func (o *InlineResponse20051TodoItems) HasDueDateBase() bool {\n\tif o != nil && o.DueDateBase != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (b *gsDBBackup) maybeBackupDB(now time.Time) {\n\tb.maybeBackupDBLiveness.Reset()\n\t// Look for a trigger file written by task-scheduler-db-backup.service\n\t// or a previous automatic backup attempt.\n\tbasename, attemptCount, err := b.findAndParseTriggerFile()\n\tif err != nil {\n\t\tglog.Error(err)\n\t}\n\tif basename == \"\" {\n\t\treturn\n\t}\n\tattemptCount++\n\tif attemptCount == 1 {\n\t\tglog.Infof(\"Beginning automatic DB backup.\")\n\t} else {\n\t\tglog.Infof(\"Retrying automatic DB backup -- attempt %d.\", attemptCount)\n\t}\n\tif err := b.backupDB(now, basename); err != nil {\n\t\tglog.Errorf(\"Automatic DB backup failed: %s\", err)\n\t\tif attemptCount >= RETRY_COUNT {\n\t\t\tglog.Errorf(\"Automatic DB backup failed after %d attempts. Retries exhausted.\", attemptCount)\n\t\t\tif err := b.deleteTriggerFile(basename); err != nil {\n\t\t\t\tglog.Error(err)\n\t\t\t}\n\t\t} else {\n\t\t\tif err := b.writeTriggerFile(basename, attemptCount); err != nil {\n\t\t\t\tglog.Error(err)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tglog.Infof(\"Completed automatic DB backup.\")\n\t\tif err := b.deleteTriggerFile(basename); err != nil {\n\t\t\tglog.Error(err)\n\t\t}\n\t}\n}", "func (o *InlineResponse20051TodoItems) HasDueDate() bool {\n\tif o != nil && o.DueDate != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (id Job) Due() Time {\n\treturn ksuid.KSUID(id).Time()\n}", "func (o *ModelsBackupSchedule) HasSchedule() bool {\n\tif o != nil && o.Schedule != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *TransactionSplit) GetDueDateOk() (*time.Time, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.DueDate.Get(), o.DueDate.IsSet()\n}", "func (_BREMICO *BREMICOCaller) IsOverdue(opts *bind.CallOpts) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _BREMICO.contract.Call(opts, out, \"isOverdue\")\n\treturn *ret0, err\n}", "func (tbbsd TimeBasedBackupScheduleDescription) AsBackupScheduleDescription() (*BackupScheduleDescription, bool) {\n\treturn nil, false\n}", "func AssertRetentionSchedule(ctx context.Context, db *sql.DB, queueName string, taskType queue.TaskType, status queue.TaskStatus, age time.Duration) (err error) {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"AssertRetentionSchedule\")\n\tspan.SetTag(\"pkg.name\", \"postgres\")\n\n\tspec := createRetentionSpec(queueName, taskType, status, age)\n\tspecBytes, err := json.Marshal(spec)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can not build retention task spec: %w\", err)\n\t}\n\t// randomly distribute the retention tasks throughout the hour\n\twhen := rand.Intn(60)\n\tretentionSchedule := queue.TaskScheduleRequest{\n\t\tTaskBase: queue.TaskBase{\n\t\t\tQueue: MaintenanceTaskQueue,\n\t\t\tType: RetentionTask,\n\t\t\tSpec: specBytes,\n\t\t},\n\t\tCronSchedule: fmt.Sprintf(\"%d * * * *\", when), // every hour at minute \"when\"\n\t}\n\ttx, err := db.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can not start transaction for scheduling: %w\", err)\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t_ = tx.Rollback()\n\t\t\treturn\n\t\t}\n\t\terr = tx.Commit()\n\t}()\n\n\t_, err = tx.ExecContext(ctx, `LOCK TABLE schedules IN ACCESS EXCLUSIVE MODE;`)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to lock `schedules`: %w\", err)\n\t}\n\n\tbuilder := squirrel.StatementBuilder.\n\t\tPlaceholderFormat(squirrel.Dollar).\n\t\tRunWith(cdb.WrapWithTracing(tx))\n\n\tvar exists int\n\t// use a unique error name here otherwise the sql.ErrNoRows might shadow\n\t// us and things will break. This is also handled by the named error return\n\t// variable, but this makes the code easier to copy and paste\n\texistsErr := builder.Select(\"1\").\n\t\tFrom(\"schedules\").\n\t\tWhere(squirrel.Eq{\n\t\t\t\"task_queue\": MaintenanceTaskQueue,\n\t\t\t\"task_type\": RetentionTask,\n\t\t\t\"task_spec->>'queueName'\": queueName,\n\t\t\t\"task_spec->>'taskType'\": taskType,\n\t\t\t\"task_spec->>'status'\": status,\n\t\t}).ScanContext(ctx, &exists)\n\tif existsErr != nil && existsErr != sql.ErrNoRows {\n\t\treturn fmt.Errorf(\"can not verify existing schedule: %w\", existsErr)\n\t}\n\n\t// will only non-zero if err is nil and task is not found\n\tif exists == 0 {\n\t\tspan.SetTag(\"created\", true)\n\t\t// pass nil db because it doesn't need the raw db\n\t\treturn NewScheduler(nil).Schedule(ctx, builder, retentionSchedule)\n\t}\n\n\tspan.SetTag(\"updated\", true)\n\tres, err := builder.Update(\"schedules\").\n\t\tWhere(squirrel.Eq{\n\t\t\t\"task_queue\": MaintenanceTaskQueue,\n\t\t\t\"task_type\": RetentionTask,\n\t\t\t\"task_spec->>'queueName'\": queueName,\n\t\t\t\"task_spec->>'taskType'\": taskType,\n\t\t\t\"task_spec->>'status'\": status,\n\t\t}).\n\t\tSet(\"updated_at\", time.Now()).\n\t\tSet(\"task_spec\", retentionSchedule.Spec).\n\t\tSet(\"cron_schedule\", retentionSchedule.CronSchedule).\n\t\tSet(\"next_execution_time\", time.Now()).\n\t\tExecContext(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can not update existing schdule: %w\", err)\n\t}\n\n\tupdated, err := res.RowsAffected()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can not determine the number of rows affected: %w\", err)\n\t}\n\n\tspan.SetTag(\"affected\", updated)\n\n\treturn nil\n}", "func assert_schedule_improved(w map[int]float64, final, init vrp.Allocation) bool {\n\treturn weighted_reward(w, final) >= weighted_reward(w, init)\n}", "func (w *Week) shouldStartNewWeek(time string) bool {\n\treturn w.canAddNewDay(time) && len(w.days) == 7\n}", "func (f *FakeInstance) GetBackupSchedule(_ context.Context, _ string) (*govultr.BackupSchedule, *http.Response, error) {\n\tpanic(\"implement me\")\n}", "func WaitForScheduledBackup(backupScheduleName string, retryInterval time.Duration, timeout time.Duration) (*api.BackupObject, error) {\n\tbeginTime := time.Now()\n\tbeginTimeSec := beginTime.Unix()\n\n\tt := func() (interface{}, bool, error) {\n\t\tlogrus.Infof(\"Enumerating backups\")\n\t\tbkpEnumerateReq := &api.BackupEnumerateRequest{\n\t\t\tOrgId: OrgID}\n\t\t//ctx, err := backup.GetPxCentralAdminCtx()\n\t\tctx, err := backup.GetAdminCtxFromSecret()\n\t\tif err != nil {\n\t\t\treturn nil, true, err\n\t\t}\n\t\tcurBackups, err := Inst().Backup.EnumerateBackup(ctx, bkpEnumerateReq)\n\t\tif err != nil {\n\t\t\treturn nil, true, err\n\t\t}\n\t\tfor _, bkp := range curBackups.GetBackups() {\n\t\t\tcreateTime := bkp.GetCreateTime()\n\t\t\tif beginTimeSec > createTime.GetSeconds() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif (bkp.GetStatus().GetStatus() == api.BackupInfo_StatusInfo_Success ||\n\t\t\t\tbkp.GetStatus().GetStatus() == api.BackupInfo_StatusInfo_PartialSuccess) &&\n\t\t\t\tbkp.GetBackupSchedule().GetName() == backupScheduleName {\n\t\t\t\treturn bkp, false, nil\n\t\t\t}\n\t\t}\n\t\terr = fmt.Errorf(\"unable to find backup from backup schedule with name %s after time %v\",\n\t\t\tbackupScheduleName, beginTime)\n\t\treturn nil, true, err\n\t}\n\n\tbkpInterface, err := task.DoRetryWithTimeout(t, timeout, retryInterval)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbkp := bkpInterface.(*api.BackupObject)\n\treturn bkp, nil\n\n}", "func (task *Task) IsScheduled() bool {\n\tif task.State != statuses.TaskStateActive {\n\t\treturn false\n\t}\n\treturn task.IsRecurringlyScheduled() || task.Schedule.Regularity == apiModels.OneTime\n}", "func isOldEnough(pr *github.PullRequest) bool {\n\treturn time.Now().Unix()-pr.CreatedAt.Unix() > config.TimeForCreatingJIRATicket\n}", "func (t *Task) ensureInitialBackup() (*velero.Backup, error) {\n\tbackup, err := t.getInitialBackup()\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tif backup != nil {\n\t\treturn backup, nil\n\t}\n\n\tclient, err := t.getSourceClient()\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tnewBackup, err := t.buildBackup(client, \"initial\")\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tuserIncludedResources, _, err := t.PlanResources.MigPlan.GetIncludedResourcesList(client)\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\n\tnewBackup.Labels[migapi.InitialBackupLabel] = t.UID()\n\tnewBackup.Labels[migapi.MigMigrationDebugLabel] = t.Owner.Name\n\tnewBackup.Labels[migapi.MigPlanDebugLabel] = t.Owner.Spec.MigPlanRef.Name\n\tnewBackup.Labels[migapi.MigMigrationLabel] = string(t.Owner.UID)\n\tnewBackup.Labels[migapi.MigPlanLabel] = string(t.PlanResources.MigPlan.UID)\n\tnewBackup.Spec.IncludedResources = toStringSlice(settings.IncludedInitialResources.Difference(toSet(t.PlanResources.MigPlan.Status.ExcludedResources)))\n\tnewBackup.Spec.IncludedResources = append(newBackup.Spec.IncludedResources, userIncludedResources...)\n\tnewBackup.Spec.ExcludedResources = toStringSlice(settings.ExcludedInitialResources.Union(toSet(t.PlanResources.MigPlan.Status.ExcludedResources)))\n\tnewBackup.Spec.LabelSelector = t.PlanResources.MigPlan.Spec.LabelSelector\n\tdelete(newBackup.Annotations, migapi.QuiesceAnnotation)\n\n\tif Settings.DisImgCopy {\n\t\tif newBackup.Annotations == nil {\n\t\t\tnewBackup.Annotations = map[string]string{}\n\t\t}\n\t\tnewBackup.Annotations[migapi.DisableImageCopy] = strconv.FormatBool(Settings.DisImgCopy)\n\t}\n\n\terr = client.Create(context.TODO(), newBackup)\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\treturn newBackup, nil\n}", "func (r *Release) isConsideredToRun() bool {\n\tif r == nil {\n\t\treturn false\n\t}\n\treturn !r.disabled\n}", "func (me TEventType) IsAssignmentAbandoned() bool { return me.String() == \"AssignmentAbandoned\" }", "func canModify(now int64, clientID int32, task *Task) bool {\n\treturn task.AT <= now || clientID == task.OwnerID\n}", "func (f *FakeInstance) SetBackupSchedule(_ context.Context, _ string, _ *govultr.BackupScheduleReq) (*http.Response, error) {\n\tpanic(\"implement me\")\n}", "func (o *ModelsBackupSchedule) GetScheduleOk() (*string, bool) {\n\tif o == nil || o.Schedule == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Schedule, true\n}", "func (s *Scheduler) DeploymentCheck(ns string, name string, recover bool) {\n\n\tblog.Info(\"deployment(%s.%s) check begin\", ns, name)\n\tif recover == true {\n\t\tif s.Role != SchedulerRoleMaster {\n\t\t\tblog.Warn(\"deployment(%s.%s) check exit, because scheduler is not master now\", ns, name)\n\t\t\treturn\n\t\t}\n\t\tfinish := s.deploymentCheckTick(ns, name, true)\n\t\tif finish == true {\n\t\t\tblog.Info(\"deployment(%s.%s) check finish\", ns, name)\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\n\tfor {\n\t\tif s.Role != SchedulerRoleMaster {\n\t\t\tblog.Warn(\"deployment(%s.%s) check exit, because scheduler is not master now\", ns, name)\n\t\t\treturn\n\t\t}\n\t\tfinish := s.deploymentCheckTick(ns, name, false)\n\t\tif finish == true {\n\t\t\tblog.Info(\"deployment(%s.%s) check finish\", ns, name)\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}", "func isScheduleStillInUse(s models.Schedule) (bool, error) {\n\tvar scheduleEvents []models.ScheduleEvent\n\tif err := dbClient.GetScheduleEventsByScheduleName(&scheduleEvents, s.Name); err != nil {\n\t\treturn false, err\n\t}\n\tif len(scheduleEvents) > 0 {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}", "func (d *dmaasBackup) cleanupOldSchedule(dbkp *v1alpha1.DMaaSBackup) error {\n\t// TODO\n\treturn nil\n}", "func (t *Task) hasBackupCompleted(backup *velero.Backup) (bool, []string) {\n\tcompleted := false\n\treasons := []string{}\n\tprogress := []string{}\n\n\tpvbs := t.getPodVolumeBackupsForBackup(backup)\n\n\tswitch backup.Status.Phase {\n\tcase velero.BackupPhaseNew:\n\t\tprogress = append(\n\t\t\tprogress,\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"Backup %s/%s: Not started\",\n\t\t\t\tbackup.Namespace,\n\t\t\t\tbackup.Name))\n\tcase velero.BackupPhaseInProgress:\n\t\titemsBackedUp, totalItems := getBackupStats(backup)\n\t\tprogress = append(\n\t\t\tprogress,\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"Backup %s/%s: %d out of estimated total of %d objects backed up%s\",\n\t\t\t\tbackup.Namespace,\n\t\t\t\tbackup.Name,\n\t\t\t\titemsBackedUp,\n\t\t\t\ttotalItems,\n\t\t\t\tgetBackupDuration(backup)))\n\t\tprogress = append(\n\t\t\tprogress,\n\t\t\tgetPodVolumeBackupsProgress(pvbs)...)\n\tcase velero.BackupPhaseCompleted:\n\t\tcompleted = true\n\t\titemsBackedUp, totalItems := getBackupStats(backup)\n\t\tprogress = append(\n\t\t\tprogress,\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"Backup %s/%s: %d out of estimated total of %d objects backed up%s\",\n\t\t\t\tbackup.Namespace,\n\t\t\t\tbackup.Name,\n\t\t\t\titemsBackedUp,\n\t\t\t\ttotalItems,\n\t\t\t\tgetBackupDuration(backup)))\n\t\tprogress = append(\n\t\t\tprogress,\n\t\t\tgetPodVolumeBackupsProgress(pvbs)...)\n\tcase velero.BackupPhaseFailed:\n\t\tcompleted = true\n\t\tmessage := fmt.Sprintf(\n\t\t\t\"Backup %s/%s: failed.\",\n\t\t\tbackup.Namespace,\n\t\t\tbackup.Name)\n\t\treasons = append(reasons, message)\n\t\titemsBackedUp, totalItems := getBackupStats(backup)\n\t\tmessage = fmt.Sprintf(\n\t\t\t\"%s %d out of estimated total of %d objects backed up%s\",\n\t\t\tmessage,\n\t\t\titemsBackedUp,\n\t\t\ttotalItems,\n\t\t\tgetBackupDuration(backup))\n\t\tprogress = append(progress, message)\n\t\tprogress = append(\n\t\t\tprogress,\n\t\t\tgetPodVolumeBackupsProgress(pvbs)...)\n\tcase velero.BackupPhasePartiallyFailed:\n\t\tcompleted = true\n\t\titemsBackedUp, totalItems := getBackupStats(backup)\n\t\tmessage := fmt.Sprintf(\n\t\t\t\"Backup %s/%s: partially failed. %d out of estimated total of %d objects backed up%s\",\n\t\t\tbackup.Namespace,\n\t\t\tbackup.Name,\n\t\t\titemsBackedUp,\n\t\t\ttotalItems,\n\t\t\tgetBackupDuration(backup))\n\t\tprogress = append(progress, message)\n\t\tprogress = append(\n\t\t\tprogress,\n\t\t\tgetPodVolumeBackupsProgress(pvbs)...)\n\tcase velero.BackupPhaseFailedValidation:\n\t\treasons = backup.Status.ValidationErrors\n\t\treasons = append(\n\t\t\treasons,\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"Backup %s/%s: validation failed.\",\n\t\t\t\tbackup.Namespace,\n\t\t\t\tbackup.Name))\n\t\tcompleted = true\n\t}\n\tt.Log.Info(\"Velero Backup progress report\",\n\t\t\"backup\", path.Join(backup.Namespace, backup.Name),\n\t\t\"backupProgress\", progress)\n\n\tt.setProgress(progress)\n\treturn completed, reasons\n}", "func (t *Task) MarkDoneForToday() {\n t.SnoozedUntil = floorDate(time.Now().Add(time.Hour * 24))\n}", "func (backupWrapper *v1BackupWrapper) isBackupCompleted() bool {\n\tif backupWrapper.backup.IsFailed() ||\n\t\tbackupWrapper.backup.IsSucceeded() {\n\t\treturn true\n\t}\n\treturn false\n}", "func (task *Task) IsTrigger() bool {\n\tswitch task.Schedule.Regularity {\n\tcase apiModels.Trigger:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (n *NodeBlockMaker) checkGoodTimeToMakeBlock() bool {\n\treturn true\n}", "func (o *ViewMilestone) HasOriginalDueDate() bool {\n\tif o != nil && o.OriginalDueDate != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (r *ReconcileBackup) isAllCreated(bkp *v1alpha1.Backup) error {\n\n\t// Check if was possible found the DB Pod\n\tif !r.isDbPodFound() {\n\t\terr := fmt.Errorf(\"Error: Database Pod is missing\")\n\t\treturn err\n\t}\n\n\t// Check if was possible found the DB Service\n\tif !r.isDbServiceFound() {\n\t\terr := fmt.Errorf(\"Error: Database Service is missing\")\n\t\treturn err\n\t}\n\n\t// Check if DB secret was created\n\tdbSecretName := utils.DbSecretPrefix + bkp.Name\n\t_, err := service.FetchSecret(bkp.Namespace, dbSecretName, r.client)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error: DB Secret is missing. (%v)\", dbSecretName)\n\t\treturn err\n\t}\n\n\t// Check if AWS secret was created\n\tawsSecretName := utils.GetAWSSecretName(bkp)\n\tawsSecretNamespace := utils.GetAwsSecretNamespace(bkp)\n\t_, err = service.FetchSecret(awsSecretNamespace, awsSecretName, r.client)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"Error: AWS Secret is missing. (name:%v,namespace:%v)\", awsSecretName, awsSecretNamespace)\n\t\treturn err\n\t}\n\n\t// Check if Enc secret was created (if was configured to be used)\n\tif utils.IsEncryptionKeyOptionConfig(bkp) {\n\t\tencSecretName := utils.GetEncSecretName(bkp)\n\t\tencSecretNamespace := utils.GetEncSecretNamespace(bkp)\n\t\t_, err := service.FetchSecret(encSecretNamespace, encSecretName, r.client)\n\t\tif err != nil {\n\t\t\terr := fmt.Errorf(\"Error: Encript Key Secret is missing. (name:%v,namespace:%v)\", encSecretName, encSecretNamespace)\n\t\t\treturn err\n\t\t}\n\t}\n\n\t//check if the cronJob was created\n\t_, err = service.FetchCronJob(bkp.Name, bkp.Namespace, r.client)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"Error: CronJob is missing\")\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (_BREMICO *BREMICOCallerSession) IsOverdue() (bool, error) {\n\treturn _BREMICO.Contract.IsOverdue(&_BREMICO.CallOpts)\n}", "func (bsd BackupScheduleDescription) AsBackupScheduleDescription() (*BackupScheduleDescription, bool) {\n\treturn &bsd, true\n}", "func (t Task) IsDoneNow() bool {\n return t.Complete || time.Now().Before(t.SnoozedUntil)\n}", "func (e *CronJob) effectiveSchedule() string {\n\tif e.Paused {\n\t\treturn \"manual\"\n\t}\n\treturn e.Schedule\n}", "func (t *Task) ensureStageBackup() (*velero.Backup, error) {\n\tbackup, err := t.getStageBackup()\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tif backup != nil {\n\t\treturn backup, nil\n\t}\n\n\tclient, err := t.getSourceClient()\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tt.Log.Info(\"Building Stage Velero Backup resource definition\")\n\tnewBackup, err := t.buildBackup(client, \"stage\")\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tlabelSelector := metav1.LabelSelector{\n\t\tMatchLabels: map[string]string{\n\t\t\tmigapi.IncludedInStageBackupLabel: t.UID(),\n\t\t},\n\t}\n\tnewBackup.Labels[migapi.StageBackupLabel] = t.UID()\n\tnewBackup.Labels[migapi.MigMigrationDebugLabel] = t.Owner.Name\n\tnewBackup.Labels[migapi.MigPlanDebugLabel] = t.Owner.Spec.MigPlanRef.Name\n\tnewBackup.Labels[migapi.MigMigrationLabel] = string(t.Owner.UID)\n\tnewBackup.Labels[migapi.MigPlanLabel] = string(t.PlanResources.MigPlan.UID)\n\tvar includedResources mapset.Set\n\n\tif (t.indirectImageMigration() || Settings.DisImgCopy) && !t.migrateState() {\n\t\tincludedResources = settings.IncludedStageResources\n\t} else {\n\t\tincludedResources = settings.IncludedStageResources.Difference(mapset.NewSetFromSlice([]interface{}{settings.ISResource}))\n\t}\n\tnewBackup.Spec.IncludedResources = toStringSlice(includedResources.Difference(toSet(t.PlanResources.MigPlan.Status.ExcludedResources)))\n\tnewBackup.Spec.ExcludedResources = toStringSlice(settings.ExcludedStageResources.Union(toSet(t.PlanResources.MigPlan.Status.ExcludedResources)))\n\tnewBackup.Spec.LabelSelector = &labelSelector\n\tif Settings.DisImgCopy {\n\t\tif newBackup.Annotations == nil {\n\t\t\tnewBackup.Annotations = map[string]string{}\n\t\t}\n\t\tnewBackup.Annotations[migapi.DisableImageCopy] = strconv.FormatBool(Settings.DisImgCopy)\n\t}\n\tt.Log.Info(\"Creating Stage Velero Backup on source cluster.\",\n\t\t\"backup\", path.Join(newBackup.Namespace, newBackup.Name))\n\terr = client.Create(context.TODO(), newBackup)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newBackup, nil\n}", "func TestInitialDateTimeChecks4(t *testing.T) {\n\n\texpected := true\n\n\tcurrDate := time.Now().Add(24 * time.Hour).Format(\"2006-01-02\")\n\tactual, _ := restaurantBooking.InitialDateTimeChecks(currDate, \"15:00\")\n\n\tif actual != expected {\n\t\tt.Fail()\n\t}\n\n}", "func isPlanUpdate(old *PhoneNumberInfo, new *PhoneNumberInfo) bool {\n\tnewActivationDate := *(new.getActivationDate())\n\toldActivationDate := *(old.getActivationDate())\n\n\tif newActivationDate.After(oldActivationDate) && old.DeactivationDate == new.ActivationDate {\n\t\treturn true\n\t}\n\treturn false\n}", "func (a *Scheduler) processDueJobs(ctx context.Context, nowTime time.Time) {\n\tdueJobs, err := a.scanner.GetDueJobs(nowTime)\n\tif err != nil {\n\t\tlogrus.Errorf(\"unable to retrieve due jobs: %s\", err.Error())\n\t\treturn\n\t}\n\tif len(dueJobs) > 0 {\n\t\tlogrus.Debugf(\"processDueJobs, %d recurring jobs are due for running...\", len(dueJobs))\n\t}\n\tfor _, job := range dueJobs {\n\t\terr := a.pushWorkflow(job, false)\n\t\tif err != nil {\n\t\t\tif err == cereal.ErrWorkflowInstanceExists {\n\t\t\t\tlogrus.Infof(\"Job %q is still/already running\", job.Id)\n\t\t\t} else {\n\t\t\t\tlogrus.Errorf(\"Error handling job %q: %v\", job.Id, err)\n\t\t\t}\n\t\t}\n\t}\n}", "func shouldDeploy(currentEnvironment, newEnvironment *bitesize.Environment, serviceName string) bool {\n\tcurrentService := currentEnvironment.Services.FindByName(serviceName)\n\tupdatedService := newEnvironment.Services.FindByName(serviceName)\n\n\tif (currentService != nil && currentService.Status.DeployedAt != \"\") || (updatedService != nil && updatedService.Version != \"\") {\n\t\tif diff.ServiceChanged(serviceName) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func newCron(schedule string) (chan bool, *cron.Cron) {\n\tchannel := make(chan bool)\n\tcj := cron.New()\n\tcj.AddFunc(schedule, func() { cronTriggered(channel) })\n\tglog.Info(\"db backup schedule: \" + schedule)\n\treturn channel, cj\n}", "func (o *Run) GetScheduledForOk() (*time.Time, bool) {\n\tif o == nil || o.ScheduledFor == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ScheduledFor, true\n}", "func (w *Week) canAddNewDay(time string) bool {\n\tfor _, v := range w.days {\n\t\tif v == time {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (r *RenewalInfoResponse) ShouldRenewAt(now time.Time, willingToSleep time.Duration) *time.Time {\n\t// Explicitly convert all times to UTC.\n\tnow = now.UTC()\n\tstart := r.SuggestedWindow.Start.UTC()\n\tend := r.SuggestedWindow.End.UTC()\n\n\t// Select a uniform random time within the suggested window.\n\twindow := end.Sub(start)\n\trandomDuration := time.Duration(rand.Int63n(int64(window)))\n\trt := start.Add(randomDuration)\n\n\t// If the selected time is in the past, attempt renewal immediately.\n\tif rt.Before(now) {\n\t\treturn &now\n\t}\n\n\t// Otherwise, if the client can schedule itself to attempt renewal at exactly the selected time, do so.\n\twillingToSleepUntil := now.Add(willingToSleep)\n\tif willingToSleepUntil.After(rt) || willingToSleepUntil.Equal(rt) {\n\t\treturn &rt\n\t}\n\n\t// TODO: Otherwise, if the selected time is before the next time that the client would wake up normally, attempt renewal immediately.\n\n\t// Otherwise, sleep until the next normal wake time, re-check ARI, and return to Step 1.\n\treturn nil\n}", "func (e ScheduledDateValidationError) Reason() string { return e.reason }", "func (_BREMICO *BREMICOSession) IsOverdue() (bool, error) {\n\treturn _BREMICO.Contract.IsOverdue(&_BREMICO.CallOpts)\n}", "func (fbbsd FrequencyBasedBackupScheduleDescription) AsBackupScheduleDescription() (*BackupScheduleDescription, bool) {\n\treturn nil, false\n}", "func (tbbsd TimeBasedBackupScheduleDescription) AsBasicBackupScheduleDescription() (BasicBackupScheduleDescription, bool) {\n\treturn &tbbsd, true\n}", "func isUndoneTaskOFDeployByRelease(piplineDetail *pipelinepb.PipelineDetailDTO) bool {\n\tif len(piplineDetail.PipelineStages) == 0 || len(piplineDetail.PipelineStages[0].PipelineTasks) == 0 {\n\t\treturn false\n\t}\n\n\ttask := piplineDetail.PipelineStages[0].PipelineTasks[0]\n\treturn task.Type == \"dice-deploy-release\" && !apistructs.PipelineStatus(task.Status).IsEndStatus()\n}", "func TestBackupBefore(t *testing.T) {\n\tb := backup{t: time.Unix(2, 0)}\n\tif b.before(time.Unix(1, 0)) {\n\t\tt.Errorf(\"b.before(time.Unix(1, 0)) returns false\")\n\t}\n\n\tif b.before(time.Unix(2, 0)) {\n\t\tt.Errorf(\"b.before(time.Unix(2, 0)) returns false\")\n\t}\n}", "func (task *Task) IsExpired() bool {\n\tswitch task.Schedule.Regularity {\n\tcase apiModels.OneTime, apiModels.Trigger:\n\t\treturn common.ValidTime(time.Now().UTC(), task.RunTimeUTC)\n\tcase apiModels.Recurrent:\n\t\treturn !common.ValidTime(task.Schedule.EndRunTime.UTC(), task.RunTimeUTC)\n\t}\n\treturn true\n}", "func (task *Task) IsRecurringlyScheduled() bool {\n\treturn task.Schedule.Regularity == apiModels.Recurrent && common.ValidTime(task.Schedule.EndRunTime.UTC(), task.RunTimeUTC)\n}", "func (m *MigrateManager) mayRecover() error {\n\t// It may be not need to do anything now.\n\treturn nil\n}", "func (c *VolumeController) shouldRestoreRecurringJobs(v *longhorn.Volume) bool {\n\tif v.Spec.FromBackup == \"\" || v.Spec.Standby || v.Status.RestoreInitiated {\n\t\treturn false\n\t}\n\n\tif v.Spec.RestoreVolumeRecurringJob == longhorn.RestoreVolumeRecurringJobEnabled {\n\t\treturn true\n\t}\n\n\tif v.Spec.RestoreVolumeRecurringJob == longhorn.RestoreVolumeRecurringJobDisabled {\n\t\treturn false\n\t}\n\n\t// Avoid recurring job restoration overrides the new recurring jobs added by users.\n\texistingJobs := datastore.MarshalLabelToVolumeRecurringJob(v.Labels)\n\tfor jobName, job := range existingJobs {\n\t\tif !job.IsGroup || jobName != longhorn.RecurringJobGroupDefault {\n\t\t\tc.logger.Warn(\"User already specified recurring jobs for this volume, cannot continue restoring recurring jobs from the backup volume labels\")\n\t\t\treturn false\n\t\t}\n\t}\n\n\trestoringRecurringJobs, err := c.ds.GetSettingAsBool(types.SettingNameRestoreVolumeRecurringJobs)\n\tif err != nil {\n\t\tc.logger.WithError(err).Warnf(\"Failed to get %v setting\", types.SettingNameRestoreVolumeRecurringJobs)\n\t}\n\n\treturn restoringRecurringJobs\n}", "func immediateBackupBasename(now time.Time) string {\n\treturn \"task-scheduler-\" + now.UTC().Format(\"15:04:05\")\n}", "func (me TEventType) IsAssignmentRejected() bool { return me.String() == \"AssignmentRejected\" }", "func (c *Controller) shouldSkipProcessingChange(change client.ChangeInfo, lastProjectSyncTime time.Time) bool {\n\trevision := change.Revisions[change.CurrentRevision]\n\tif revision.Created.After(lastProjectSyncTime) {\n\t\treturn false\n\t}\n\n\tfor _, message := range currentMessages(change, lastProjectSyncTime) {\n\t\tif c.messageContainsJobTriggeringCommand(message) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (d *dmaasBackup) updateScheduleInfo(dbkp *v1alpha1.DMaaSBackup) error {\n\t// TODO\n\treturn nil\n}", "func (o *PaymentInitiationPayment) HasSchedule() bool {\n\tif o != nil && o.Schedule.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (r *BackupReconciler) instReady(ctx context.Context, ns, instName string, inst *v1alpha1.Instance) error {\n\tif err := r.Get(ctx, types.NamespacedName{Namespace: ns, Name: instName}, inst); err != nil {\n\t\tr.Log.Error(err, \"error finding instance for backup validation\")\n\t\treturn fmt.Errorf(\"error finding instance - %v\", err)\n\t}\n\tif !k8s.ConditionStatusEquals(k8s.FindCondition(inst.Status.Conditions, k8s.Ready), v1.ConditionTrue) {\n\t\tr.Log.Error(fmt.Errorf(\"instance not in ready state\"), \"Instance not in ready state for backup\", \"inst.Status.Conditions\", inst.Status.Conditions)\n\t\treturn errors.New(\"instance is not in a ready state\")\n\t}\n\treturn nil\n}", "func (q *UniqueQueue) trySchedule() {\n\tselect {\n\tcase q.readyChan <- struct{}{}:\n\tdefault:\n\t\tscope.Warnf(\"queue could not be scheduled (head=%v tail=%v depth=%v)\",\n\t\t\tq.head, q.tail, q.maxDepth)\n\t}\n}", "func checkExisting(ctx context.Context, rc *runcreator.Creator, combo combo, useTrigger func(*run.Triggers) *run.Trigger) (bool, time.Time, error) {\n\t// Check if Run about to be created already exists in order to detect avoid\n\t// infinite retries if CL triggers are somehow re-used.\n\texisting := run.Run{ID: rc.ExpectedRunID()}\n\tswitch err := datastore.Get(ctx, &existing); {\n\tcase err == datastore.ErrNoSuchEntity:\n\t\t// This is the expected case.\n\t\t// NOTE: actual creation may still fail due to a race, and that's fine.\n\t\treturn false, time.Time{}, nil\n\tcase err != nil:\n\t\treturn false, time.Time{}, errors.Annotate(err, \"failed to check for existing Run %q\", existing.ID).Tag(transient.Tag).Err()\n\tcase !run.IsEnded(existing.Status):\n\t\t// The Run already exists. Most likely another triager called from another\n\t\t// TQ was first. Check again in a few seconds, at which point PM should\n\t\t// incorporate existing Run into its state.\n\t\tlogging.Warningf(ctx, \"Run %q already exists. If this warning persists, there is a bug in PM which appears to not see this Run\", existing.ID)\n\t\treturn true, clock.Now(ctx).Add(5 * time.Second), nil\n\tdefault:\n\t\tsince := clock.Since(ctx, existing.EndTime)\n\t\tif since < time.Minute {\n\t\t\tlogging.Warningf(ctx, \"Recently finalized Run %q already exists, will check later\", existing.ID)\n\t\t\treturn true, existing.EndTime.Add(time.Minute), nil\n\t\t}\n\t\tlogging.Warningf(ctx, \"Run %q already exists, finalized %s ago; will purge CLs with reused triggers\", existing.ID, since)\n\t\tfor _, info := range combo.all {\n\t\t\tinfo.addPurgeReason(useTrigger(info.pcl.Triggers), &changelist.CLError{\n\t\t\t\tKind: &changelist.CLError_ReusedTrigger_{\n\t\t\t\t\tReusedTrigger: &changelist.CLError_ReusedTrigger{\n\t\t\t\t\t\tRun: string(existing.ID),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\treturn true, time.Time{}, nil\n\t}\n}", "func (me TEventType) IsAssignmentApproved() bool { return me.String() == \"AssignmentApproved\" }", "func CreateScheduledBackup(backupScheduleName, backupScheduleUID, schedulePolicyName, schedulePolicyUID string,\n\tinterval time.Duration, namespaces []string) (err error) {\n\tvar ctx context1.Context\n\tlabelSelectors := make(map[string]string)\n\tStep(fmt.Sprintf(\"Create scheduled backup %s of namespaces %v on cluster %s in organization %s\",\n\t\tbackupScheduleNamePrefix+backupScheduleName, namespaces, sourceClusterName, OrgID), func() {\n\t\tbackupDriver := Inst().Backup\n\n\t\t// Create a schedule policy\n\t\tschedulePolicyCreateRequest := &api.SchedulePolicyCreateRequest{\n\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\tName: schedulePolicyName,\n\t\t\t\tUid: schedulePolicyUID,\n\t\t\t\tOrgId: OrgID,\n\t\t\t},\n\n\t\t\tSchedulePolicy: &api.SchedulePolicyInfo{\n\t\t\t\tInterval: &api.SchedulePolicyInfo_IntervalPolicy{\n\t\t\t\t\t// Retain 5 backups at a time for ease of inspection\n\t\t\t\t\tRetain: 5,\n\t\t\t\t\tMinutes: int64(interval / time.Minute),\n\t\t\t\t\tIncrementalCount: &api.SchedulePolicyInfo_IncrementalCount{\n\t\t\t\t\t\tCount: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\t//ctx, err = backup.GetPxCentralAdminCtx()\n\t\tctx, err = backup.GetAdminCtxFromSecret()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t_, err = backupDriver.CreateSchedulePolicy(ctx, schedulePolicyCreateRequest)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// Create a backup schedule\n\t\tbkpScheduleCreateRequest := &api.BackupScheduleCreateRequest{\n\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\tName: backupScheduleNamePrefix + backupScheduleName,\n\t\t\t\tUid: backupScheduleUID,\n\t\t\t\tOrgId: OrgID,\n\t\t\t},\n\n\t\t\tNamespaces: namespaces,\n\n\t\t\tReclaimPolicy: api.BackupScheduleInfo_Delete,\n\t\t\t// Name of Cluster\n\t\t\tCluster: sourceClusterName,\n\t\t\t// Label selectors to choose resources\n\t\t\tLabelSelectors: labelSelectors,\n\n\t\t\tSchedulePolicyRef: &api.ObjectRef{\n\t\t\t\tName: schedulePolicyName,\n\t\t\t\tUid: schedulePolicyUID,\n\t\t\t},\n\t\t\tBackupLocationRef: &api.ObjectRef{\n\t\t\t\tName: backupLocationName,\n\t\t\t\tUid: BackupLocationUID,\n\t\t\t},\n\t\t}\n\t\t//ctx, err = backup.GetPxCentralAdminCtx()\n\t\tctx, err = backup.GetAdminCtxFromSecret()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t_, err = backupDriver.CreateBackupSchedule(ctx, bkpScheduleCreateRequest)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t})\n\treturn err\n}", "func (m *EducationAssignment) GetDueDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n return m.dueDateTime\n}", "func (scw *JobFuncWrapper) ensureNooneElseRunning(job *que.Job, tx *pgx.Tx, key string) (bool, error) {\n\tvar lastCompleted time.Time\n\tvar nextScheduled time.Time\n\terr := tx.QueryRow(\"SELECT last_completed, next_scheduled FROM cron_metadata WHERE id = $1 FOR UPDATE\", key).Scan(&lastCompleted, &nextScheduled)\n\tif err != nil {\n\t\tif err == pgx.ErrNoRows {\n\t\t\t_, err = tx.Exec(\"INSERT INTO cron_metadata (id) VALUES ($1)\", key)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\treturn false, ErrImmediateReschedule\n\t\t}\n\t\treturn false, err\n\t}\n\n\tif time.Now().Before(nextScheduled) {\n\t\tvar futureJobs int\n\t\t// make sure we don't regard ourself as a future job. Sometimes clock skew makes us think we can't run yet.\n\t\terr = tx.QueryRow(\"SELECT count(*) FROM que_jobs WHERE job_class = $1 AND args::jsonb = $2::jsonb AND run_at >= $3 AND job_id != $4\", job.Type, job.Args, nextScheduled, job.ID).Scan(&futureJobs)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tif futureJobs > 0 {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn false, scw.QC.EnqueueInTx(&que.Job{\n\t\t\tType: job.Type,\n\t\t\tArgs: job.Args,\n\t\t\tRunAt: nextScheduled,\n\t\t}, tx)\n\t}\n\n\t// Continue\n\treturn true, nil\n}", "func (b bot) scheduleNotify(id int64) {\n\tif b.notifyTimers == nil {\n\t\treturn\n\t}\n\n\tisSubscribed, err := b.store.IsSubscribed(id)\n\tif err != nil {\n\t\tb.err.Println(err)\n\t\treturn\n\t}\n\tif !isSubscribed {\n\t\treturn\n\t}\n\n\tif timer := b.notifyTimers[id]; timer != nil {\n\t\t// Don't care if timer is active or not\n\t\t_ = timer.Stop()\n\t}\n\tu := b.getUser(id)\n\td, count, err := b.store.GetNotifyTime(id, u.Timezone())\n\tif err != nil {\n\t\tb.err.Println(err)\n\t\treturn\n\t}\n\tif count <= 1 {\n\t\treturn\n\t}\n\n\tb.info.Printf(\"Notify %d in %s with %d due studies\", id, d.String(), count)\n\tb.notifyTimers[id] = time.AfterFunc(d, func() {\n\t\tb.notify(id, count)\n\t})\n}", "func (o *PaymentInitiationPayment) GetScheduleOk() (*ExternalPaymentScheduleGet, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Schedule.Get(), o.Schedule.IsSet()\n}", "func (o *Run) HasScheduledFor() bool {\n\tif o != nil && o.ScheduledFor != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func wasRunAfter(p1 PlanStatus, p2 PlanStatus) bool {\n\tif p1.Status == ExecutionNeverRun || p2.Status == ExecutionNeverRun || p1.LastUpdatedTimestamp == nil || p2.LastUpdatedTimestamp == nil {\n\t\treturn false\n\t}\n\treturn p1.LastUpdatedTimestamp.Time.After(p2.LastUpdatedTimestamp.Time)\n}", "func (m *EducationAssignment) SetDueDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() {\n m.dueDateTime = value\n}", "func (b *BackuPOT) needBackup(remotePath remotePath, newFileInfo *RemoteFileInfo) (bool, error) {\n // get remote file info\n fileInfo, err := b.getRemoteFileInfo(remotePath, -1)\n if err != nil {\n // check err kind.\n if !strings.HasPrefix(err.Error(), \"The key doesn't exist.\") {\n return false, backupotDebug.Error(err)\n } else {\n return true, nil\n }\n }\n if fileInfo.EncodedHash != newFileInfo.EncodedHash {\n return true, nil\n }\n return false, nil\n}", "func (action *scheduleRoutineAction) CanHandle(build *v1.Build) bool {\n\treturn build.Status.Phase == v1.BuildPhaseScheduling\n}", "func isNewWorker(worker *workerv1.Worker, currentDeployment *appsv1.Deployment) bool {\n\treturn currentDeployment == nil && worker.DeletionTimestamp == nil\n}", "func (o *InlineResponse20051TodoItems) SetDueDateBase(v string) {\n\to.DueDateBase = &v\n}", "func (tbbsd TimeBasedBackupScheduleDescription) AsFrequencyBasedBackupScheduleDescription() (*FrequencyBasedBackupScheduleDescription, bool) {\n\treturn nil, false\n}", "func (me TAssignmentStatus) IsRejected() bool { return me.String() == \"Rejected\" }", "func TestInitialDateTimeChecks3(t *testing.T) {\n\n\texpected := false\n\n\tcurrDate := time.Now().Format(\"2006-01-02\")\n\tbeforeRestaurantOpenCheck, _ := restaurantBooking.InitialDateTimeChecks(currDate, \"12:00\")\n\tafterRestaurantOpenCheck, _ := restaurantBooking.InitialDateTimeChecks(currDate, \"22:00\")\n\n\tif (beforeRestaurantOpenCheck && afterRestaurantOpenCheck) != expected {\n\t\tt.Fail()\n\t}\n}", "func (a *account) managedNeedsToRefill(target types.Currency) bool {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\treturn a.availableBalance().Cmp(target) < 0\n}", "func (d *Deleter) ShouldSkipThis(workItem *registry.WorkItem) bool {\n\n\t// It's possible that another worker recently marked this as\n\t// \"do not retry.\" If that's the case, skip it.\n\tif !d.ShouldRetry(workItem) {\n\t\treturn true\n\t}\n\n\t// Definitely don't delete this if it's not a deletion request.\n\tif HasWrongAction(d.Context, workItem, constants.ActionDelete) {\n\t\treturn true\n\t}\n\n\t// Do not proceed without the approval of institutional admin.\n\tif d.MissingRequiredApproval(workItem) {\n\t\treturn true\n\t}\n\n\t// Occasionally, NSQ will think an item has timed out because\n\t// it took a long time to record. NSQ sends it to a new worker\n\t// after the original worker has completed it.\n\tif workItem.ProcessingHasCompleted() {\n\t\tmessage := fmt.Sprintf(\"Rejecting WorkItem %d because status is %s\", workItem.ID, workItem.Status)\n\t\td.Context.Logger.Info(message)\n\t\treturn true\n\t}\n\n\t// Note that returning nil tells NSQ that a worker is\n\t// working on this item, even if it's not us. We don't\n\t// want to requeue duplicates, and we don't want to return\n\t// an error, because that's equivalent to FIN/failed.\n\tif d.OtherWorkerIsHandlingThis(workItem) {\n\t\treturn true\n\t}\n\n\t// See if this worker is already processing this item.\n\t// This happens sometimes when NSQ thinks the item has\n\t// timed out while a worker is validating or storing\n\t// an object.\n\tif d.ImAlreadyProcessingThis(workItem) {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (obj *expense) HasRemaining() bool {\n\treturn obj.remaining != nil\n}", "func waitForDeployToProcess(currentVersion time.Time, name, ip string) bool {\n\tebo := backoff.NewExponentialBackOff()\n\tebo.MaxElapsedTime = 10 * time.Second\n\tdeployError := backoff.Retry(safe.OperationWithRecover(func() error {\n\t\t// Configuration should have deployed successfully, confirm version match.\n\t\tnewVersion, exists, newErr := getDeployedVersion(ip)\n\t\tif newErr != nil {\n\t\t\treturn fmt.Errorf(\"could not get newly deployed configuration version: %v\", newErr)\n\t\t}\n\t\tif exists {\n\t\t\tif currentVersion.Equal(newVersion) {\n\t\t\t\t// The version we are trying to deploy is confirmed.\n\t\t\t\t// Return nil, to break out of the ebo.\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"deployment was not successful\")\n\t}), ebo)\n\n\tif deployError == nil {\n\t\t// The version we are trying to deploy is confirmed.\n\t\t// Return true, so that it will be removed from the deploy queue.\n\t\tlog.Debugf(\"Successfully deployed version for pod %s: %s\", name, currentVersion)\n\t\treturn true\n\t}\n\treturn false\n}", "func (m *AgedAccountsPayable) SetBalanceDue(value *float64)() {\n err := m.GetBackingStore().Set(\"balanceDue\", value)\n if err != nil {\n panic(err)\n }\n}", "func (bsd BackupScheduleDescription) AsBasicBackupScheduleDescription() (BasicBackupScheduleDescription, bool) {\n\treturn &bsd, true\n}", "func (dt DefaultTrigger) IsTriggered(times interface{}, user interface{}) bool {\n\treturn true\n}", "func (dispatcher *Dispatcher) shouldPublish(update StatusUpdate) bool {\n\tpingerName := update.Name\n\t// state transistions are always to be published\n\tif statusChanged(update.Status) {\n\t\tlog.Debugf(\"state transition on [%s]\", pingerName)\n\t\treturn true\n\t}\n\n\t// if not a state transition, we only alert of error states in\n\t// case the reminder delay has passed since the last alert.\n\tif update.Status.LatestResult.Status == ping.StatusNOK {\n\t\tif lastAlert, ok := dispatcher.alertHistory[pingerName]; ok {\n\t\t\ttimeUntilReminder := dispatcher.reminderDelay - time.Since(lastAlert)\n\t\t\tlog.Debugf(\"time until reminder for [%s]: %s\", pingerName, timeUntilReminder.String())\n\t\t\treturn timeUntilReminder <= 0\n\t\t}\n\t}\n\n\treturn false\n}", "func IsFileReadyToUpload(regex, fname string, now time.Time) (ok bool, err error) {\n\tr := regexp.MustCompile(regex)\n\tsubS := r.FindStringSubmatch(fname)\n\n\tif len(subS) < 2 {\n\t\treturn false, nil\n\t}\n\n\tlastFinishedBackupFileBeforeHours := 35.0 // 24 + 11,last flush occurred at 10:00 CST\n\tt, err := time.Parse(\"20060102-0700\", subS[1]+\"+0800\")\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"parse file time error\")\n\t}\n\n\tif now.Sub(t).Hours() <= lastFinishedBackupFileBeforeHours {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}", "func (m *Manager) currentShouldChange(milestonePayload *iotago.Milestone) bool {\n\tm.pendingLock.RLock()\n\tdefer m.pendingLock.RUnlock()\n\n\tif len(m.pending) == 0 {\n\t\treturn false\n\t}\n\n\tnext := m.pending[0]\n\n\tswitch {\n\tcase next.TargetMilestoneIndex == milestonePayload.Index+1:\n\t\tif !m.SupportedVersions().Supports(next.ProtocolVersion) {\n\t\t\tm.Events.NextMilestoneUnsupported.Trigger(next)\n\t\t}\n\n\t\treturn false\n\tcase next.TargetMilestoneIndex > milestonePayload.Index:\n\t\treturn false\n\tdefault:\n\t\treturn true\n\t}\n}", "func (cl *Client) prepareToday() error {\n\tboard, err := BoardFor(cl.Member, \"Kanban daily/weekly\")\n\tif err != nil {\n\t\t// handle error\n\t\treturn err\n\t}\n\tfmt.Println(\"Kanban board is \", board.ID)\n\tfor _, boardlist := range []string{\"Today\"} {\n\t\tfmt.Printf(\"move items from %s to backlog based on label color\\n\", boardlist)\n\n\t\tlist, err := ListFor(cl, \"Kanban daily/weekly\", boardlist)\n\t\tif err != nil {\n\t\t\t// handle error\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"kanban/%s is %v\", boardlist, list)\n\t\tcards, err := list.GetCards(trello.Defaults())\n\t\tif err != nil {\n\t\t\t// handle error\n\t\t\treturn err\n\t\t}\n\t\tfor _, card := range cards {\n\t\t\tfmt.Println(card.Name, card.Labels)\n\t\t\tmoveBackCard(cl, card)\n\t\t}\n\t}\n\treturn nil\n}", "func (ti TaskInstance) IsScheduled() bool {\n\tvar disabledCount int\n\n\tfor _, status := range ti.Statuses {\n\t\tif status == statuses.TaskInstanceDisabled {\n\t\t\tdisabledCount++\n\t\t\tcontinue\n\t\t}\n\n\t\tif status == statuses.TaskInstanceScheduled {\n\t\t\t// FIX: RMM-36676\n\t\t\treturn true\n\t\t}\n\t\tbreak\n\t}\n\treturn len(ti.Statuses) == disabledCount\n}", "func wasShootRescheduledToNewSeed(shoot *gardencorev1beta1.Shoot) bool {\n\treturn shoot.Status.LastOperation != nil &&\n\t\tshoot.Status.LastOperation.Type != gardencorev1beta1.LastOperationTypeMigrate &&\n\t\tshoot.Spec.SeedName != nil &&\n\t\tshoot.Status.SeedName != nil &&\n\t\t*shoot.Spec.SeedName != *shoot.Status.SeedName\n}" ]
[ "0.5760196", "0.5610772", "0.52594167", "0.5190598", "0.51561713", "0.5043613", "0.4985795", "0.4985035", "0.49514583", "0.4903711", "0.49007374", "0.4899634", "0.48967138", "0.48667654", "0.485368", "0.4840095", "0.48217595", "0.4819338", "0.4814378", "0.48026362", "0.4792456", "0.47820652", "0.47527525", "0.47492683", "0.47130176", "0.47026676", "0.46930146", "0.46923906", "0.46807578", "0.46673527", "0.4664804", "0.46602824", "0.46538973", "0.4647935", "0.46400768", "0.4635183", "0.46338716", "0.46294338", "0.46153674", "0.4613282", "0.46092772", "0.46034703", "0.46007493", "0.45896587", "0.4581455", "0.45787677", "0.45760038", "0.4571078", "0.45403713", "0.4530912", "0.4529411", "0.4527197", "0.45231557", "0.45179525", "0.4512306", "0.45114574", "0.44921428", "0.44918483", "0.44900033", "0.44836354", "0.44797194", "0.44788036", "0.4459191", "0.44477752", "0.44425923", "0.44338495", "0.44337702", "0.44268695", "0.44227886", "0.44213346", "0.44201908", "0.4419723", "0.44168484", "0.44162926", "0.44124776", "0.44090563", "0.4407962", "0.43979472", "0.4397493", "0.43956506", "0.43932888", "0.4391585", "0.43850753", "0.43828523", "0.43727493", "0.4370326", "0.43623298", "0.43578392", "0.4354537", "0.43525562", "0.43515486", "0.43446803", "0.43428105", "0.43420082", "0.4340055", "0.43398383", "0.43324184", "0.43319032", "0.43279403", "0.4323148" ]
0.7543842
0
submitBackup create a backup from schedule.
func (c *scheduleReconciler) submitBackup(ctx context.Context, schedule *velerov1.Schedule) error { c.logger.WithField("schedule", schedule.Namespace+"/"+schedule.Name).Info("Schedule is due, going to submit backup.") now := c.clock.Now() // Don't attempt to "catch up" if there are any missed or failed runs - simply // trigger a Backup if it's time. backup := getBackup(schedule, now) if err := c.Create(ctx, backup); err != nil { return errors.Wrap(err, "error creating Backup") } original := schedule.DeepCopy() schedule.Status.LastBackup = &metav1.Time{Time: now} if err := c.Patch(ctx, schedule, client.MergeFrom(original)); err != nil { return errors.Wrapf(err, "error updating Schedule's LastBackup time to %v", schedule.Status.LastBackup) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func createBackup(w http.ResponseWriter, r *http.Request) {\n\tlogrus.Infof(\">>>>CreateBackup r=%s\", r)\n\n\tif RunningBackupAPIID != \"\" {\n\t\tlogrus.Infof(\"Another backup id %s is already running. Aborting.\", RunningBackupAPIID)\n\t\thttp.Error(w, fmt.Sprintf(\"Another backup id %s is already running. Aborting.\", RunningBackupAPIID), http.StatusConflict)\n\t\treturn\n\t}\n\n\tRunningBackupAPIID = createAPIID()\n\tCurrentBackupStartTime = time.Now()\n\n\t//run backup assyncronouslly\n\tgo runBackup(RunningBackupAPIID)\n\n\tsendSchellyResponse(RunningBackupAPIID, \"\", \"running\", \"backup triggered\", -1, http.StatusAccepted, w)\n}", "func CreateScheduledBackup(backupScheduleName, backupScheduleUID, schedulePolicyName, schedulePolicyUID string,\n\tinterval time.Duration, namespaces []string) (err error) {\n\tvar ctx context1.Context\n\tlabelSelectors := make(map[string]string)\n\tStep(fmt.Sprintf(\"Create scheduled backup %s of namespaces %v on cluster %s in organization %s\",\n\t\tbackupScheduleNamePrefix+backupScheduleName, namespaces, sourceClusterName, OrgID), func() {\n\t\tbackupDriver := Inst().Backup\n\n\t\t// Create a schedule policy\n\t\tschedulePolicyCreateRequest := &api.SchedulePolicyCreateRequest{\n\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\tName: schedulePolicyName,\n\t\t\t\tUid: schedulePolicyUID,\n\t\t\t\tOrgId: OrgID,\n\t\t\t},\n\n\t\t\tSchedulePolicy: &api.SchedulePolicyInfo{\n\t\t\t\tInterval: &api.SchedulePolicyInfo_IntervalPolicy{\n\t\t\t\t\t// Retain 5 backups at a time for ease of inspection\n\t\t\t\t\tRetain: 5,\n\t\t\t\t\tMinutes: int64(interval / time.Minute),\n\t\t\t\t\tIncrementalCount: &api.SchedulePolicyInfo_IncrementalCount{\n\t\t\t\t\t\tCount: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\t//ctx, err = backup.GetPxCentralAdminCtx()\n\t\tctx, err = backup.GetAdminCtxFromSecret()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t_, err = backupDriver.CreateSchedulePolicy(ctx, schedulePolicyCreateRequest)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// Create a backup schedule\n\t\tbkpScheduleCreateRequest := &api.BackupScheduleCreateRequest{\n\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\tName: backupScheduleNamePrefix + backupScheduleName,\n\t\t\t\tUid: backupScheduleUID,\n\t\t\t\tOrgId: OrgID,\n\t\t\t},\n\n\t\t\tNamespaces: namespaces,\n\n\t\t\tReclaimPolicy: api.BackupScheduleInfo_Delete,\n\t\t\t// Name of Cluster\n\t\t\tCluster: sourceClusterName,\n\t\t\t// Label selectors to choose resources\n\t\t\tLabelSelectors: labelSelectors,\n\n\t\t\tSchedulePolicyRef: &api.ObjectRef{\n\t\t\t\tName: schedulePolicyName,\n\t\t\t\tUid: schedulePolicyUID,\n\t\t\t},\n\t\t\tBackupLocationRef: &api.ObjectRef{\n\t\t\t\tName: backupLocationName,\n\t\t\t\tUid: BackupLocationUID,\n\t\t\t},\n\t\t}\n\t\t//ctx, err = backup.GetPxCentralAdminCtx()\n\t\tctx, err = backup.GetAdminCtxFromSecret()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t_, err = backupDriver.CreateBackupSchedule(ctx, bkpScheduleCreateRequest)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t})\n\treturn err\n}", "func (p *AuroraAdminClient) PerformBackup(ctx context.Context) (r *Response, err error) {\n var _args321 AuroraAdminPerformBackupArgs\n var _result322 AuroraAdminPerformBackupResult\n if err = p.Client_().Call(ctx, \"performBackup\", &_args321, &_result322); err != nil {\n return\n }\n return _result322.GetSuccess(), nil\n}", "func (p *AuroraAdminClient) PerformBackup(ctx context.Context) (r *Response, err error) {\n var _args371 AuroraAdminPerformBackupArgs\n var _result372 AuroraAdminPerformBackupResult\n var meta thrift.ResponseMeta\n meta, err = p.Client_().Call(ctx, \"performBackup\", &_args371, &_result372)\n p.SetLastResponseMeta_(meta)\n if err != nil {\n return\n }\n return _result372.GetSuccess(), nil\n}", "func (f *FakeInstance) SetBackupSchedule(_ context.Context, _ string, _ *govultr.BackupScheduleReq) (*http.Response, error) {\n\tpanic(\"implement me\")\n}", "func CreateBackup(serviceID string, settings *models.Settings) *models.Task {\n\tbackup := map[string]string{\n\t\t\"archiveType\": \"cf\",\n\t\t\"encryptionType\": \"aes\",\n\t}\n\tb, err := json.Marshal(backup)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(1)\n\t}\n\tresp := httpclient.Post(b, fmt.Sprintf(\"%s/v1/environments/%s/services/%s/backup\", settings.PaasHost, settings.EnvironmentID, serviceID), true, settings)\n\tvar m map[string]string\n\tjson.Unmarshal(resp, &m)\n\treturn &models.Task{\n\t\tID: m[\"taskId\"],\n\t}\n}", "func (i *InstanceServiceHandler) SetBackupSchedule(ctx context.Context, instanceID string, backup *BackupScheduleReq) error {\n\turi := fmt.Sprintf(\"%s/%s/backup-schedule\", instancePath, instanceID)\n\treq, err := i.client.NewRequest(ctx, http.MethodPost, uri, backup)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn i.client.DoWithContext(ctx, req, nil)\n}", "func CreateBackup(service *pgCommon.PostgresServiceInformations) error {\n\tresp, err := service.PgoApi.CreateBackup(&msgs.CreateBackrestBackupRequest{\n\t\tNamespace: service.ClusterInstance.Namespace,\n\t\tSelector: \"name=\" + service.ClusterInstance.Name,\n\t})\n\n\tif err != nil {\n\t\tlogger.RError(err, \"Unable to progress create backup action for database \"+service.ClusterInstance.Name)\n\t}\n\n\t_ = resp\n\treturn err\n}", "func (ctl Controller) Backup() *pitr.Error {\n\tstdout, stderr, err := ctl.runner.Run(\"sudo --login --user postgres wal-g backup-push %s\", ctl.cluster.DataDirectory())\n\n\tif err != nil {\n\t\treturn &pitr.Error{\n\t\t\tMessage: err.Error(),\n\t\t\tStdout: stdout,\n\t\t\tStderr: stderr,\n\t\t}\n\t}\n\n\treturn nil\n}", "func CreateBackupAction(service *pgCommon.PostgresServiceInformations) action.IAction {\n\treturn action.FormAction{\n\t\tName: \"Backup\",\n\t\tUniqueCommand: \"cmd_pg_create_backup\",\n\t\tPlaceholder: nil,\n\t\tActionExecuteCallback: func(placeholder interface{}) (interface{}, error) {\n\t\t\treturn nil, CreateBackup(service)\n\t\t},\n\t}\n}", "func (client CloudEndpointsClient) PostBackupSender(req *http.Request) (future CloudEndpointsPostBackupFuture, err error) {\n\tvar resp *http.Response\n\tfuture.FutureAPI = &azure.Future{}\n\tresp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))\n\tif err != nil {\n\t\treturn\n\t}\n\tvar azf azure.Future\n\tazf, err = azure.NewFutureFromResponse(resp)\n\tfuture.FutureAPI = &azf\n\tfuture.Result = future.result\n\treturn\n}", "func (t *Task) buildBackup(client k8sclient.Client, backupTypePrefix string) (*velero.Backup, error) {\n\tvar includeClusterResources *bool = nil\n\tannotations, err := t.getAnnotations(client)\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tbackupLocation, err := t.getBSL()\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tsnapshotLocation, err := t.getVSL()\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\n\t// Construct a restore name like \"$migrationname-54823-initial\" or \"$migrationname-54823-stage\".\n\t// This will produce a 57 character string max. Note that generateName gracefully handles strings >63 char.\n\tfmtString := fmt.Sprintf(\"%%.%ds\", 55-len(backupTypePrefix))\n\tmigrationNameTruncated := fmt.Sprintf(fmtString, t.Owner.GetName())\n\ttruncatedGenerateName := fmt.Sprintf(\"%s-%s-\", migrationNameTruncated, backupTypePrefix)\n\n\tbackup := &velero.Backup{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tLabels: t.Owner.GetCorrelationLabels(),\n\t\t\tGenerateName: truncatedGenerateName,\n\t\t\tNamespace: migapi.VeleroNamespace,\n\t\t\tAnnotations: annotations,\n\t\t},\n\t\tSpec: velero.BackupSpec{\n\t\t\tIncludeClusterResources: includeClusterResources,\n\t\t\tStorageLocation: backupLocation.Name,\n\t\t\tVolumeSnapshotLocations: []string{snapshotLocation.Name},\n\t\t\tTTL: metav1.Duration{Duration: 720 * time.Hour},\n\t\t\tIncludedNamespaces: t.sourceNamespaces(),\n\t\t\tHooks: velero.BackupHooks{\n\t\t\t\tResources: []velero.BackupResourceHookSpec{},\n\t\t\t},\n\t\t},\n\t}\n\treturn backup, nil\n}", "func (f *FakeInstance) GetBackupSchedule(_ context.Context, _ string) (*govultr.BackupSchedule, *http.Response, error) {\n\tpanic(\"implement me\")\n}", "func (client CloudEndpointsClient) PostBackup(ctx context.Context, resourceGroupName string, storageSyncServiceName string, syncGroupName string, cloudEndpointName string, parameters BackupRequest) (result CloudEndpointsPostBackupFuture, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/CloudEndpointsClient.PostBackup\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.FutureAPI != nil && result.FutureAPI.Response() != nil {\n\t\t\t\tsc = result.FutureAPI.Response().StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: client.SubscriptionID,\n\t\t\tConstraints: []validation.Constraint{{Target: \"client.SubscriptionID\", Name: validation.MinLength, Rule: 1, Chain: nil}}},\n\t\t{TargetValue: resourceGroupName,\n\t\t\tConstraints: []validation.Constraint{{Target: \"resourceGroupName\", Name: validation.MaxLength, Rule: 90, Chain: nil},\n\t\t\t\t{Target: \"resourceGroupName\", Name: validation.MinLength, Rule: 1, Chain: nil},\n\t\t\t\t{Target: \"resourceGroupName\", Name: validation.Pattern, Rule: `^[-\\w\\._\\(\\)]+$`, Chain: nil}}}}); err != nil {\n\t\treturn result, validation.NewError(\"storagesync.CloudEndpointsClient\", \"PostBackup\", err.Error())\n\t}\n\n\treq, err := client.PostBackupPreparer(ctx, resourceGroupName, storageSyncServiceName, syncGroupName, cloudEndpointName, parameters)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"storagesync.CloudEndpointsClient\", \"PostBackup\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresult, err = client.PostBackupSender(req)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"storagesync.CloudEndpointsClient\", \"PostBackup\", result.Response(), \"Failure sending request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func CreateBackup(conTimeout, reqTimeout time.Duration, _ cli.FormatWriter) (*api.CreateBackupResponse, error) {\n\tcon, ctx, cancel, err := newCon(conTimeout, reqTimeout)\n\tdefer cancel()\n\n\tif err != nil {\n\t\treturn &api.CreateBackupResponse{}, status.Wrap(\n\t\t\terr,\n\t\t\tstatus.DeploymentServiceUnreachableError,\n\t\t\t\"Connection to deployment-service failed\",\n\t\t)\n\t}\n\n\tres, err := con.CreateBackup(ctx, &api.CreateBackupRequest{})\n\tif err != nil {\n\t\terr = status.Wrap(\n\t\t\terr,\n\t\t\tstatus.DeploymentServiceCallError,\n\t\t\t\"Request to create a backup failed\",\n\t\t)\n\t}\n\n\treturn res, err\n}", "func SetupBackup(testName string) {\n\tlogrus.Infof(\"Backup driver: %v\", Inst().Backup)\n\tprovider := GetProvider()\n\tlogrus.Infof(\"Run Setup backup with object store provider: %s\", provider)\n\tOrgID = \"default\"\n\tBucketName = fmt.Sprintf(\"%s-%s\", BucketNamePrefix, Inst().InstanceID)\n\tCloudCredUID = uuid.New()\n\t//cloudCredUID = \"5a48be84-4f63-40ae-b7f1-4e4039ab7477\"\n\tBackupLocationUID = uuid.New()\n\t//backupLocationUID = \"64d908e7-40cf-4c9e-a5cf-672e955fd0ca\"\n\n\tCreateBucket(provider, BucketName)\n\tCreateOrganization(OrgID)\n\tCreateCloudCredential(provider, CredName, CloudCredUID, OrgID)\n\tCreateBackupLocation(provider, backupLocationName, BackupLocationUID, CredName, CloudCredUID, BucketName, OrgID)\n\tCreateSourceAndDestClusters(CredName, OrgID)\n}", "func (b *gsDBBackup) backupDB(now time.Time, basename string) (err error) {\n\t// We expect TMPDIR to be set to a location that can store a large file at\n\t// high throughput.\n\ttempdir, err := ioutil.TempDir(\"\", \"dbbackup\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer util.RemoveAll(tempdir)\n\ttempfilename := path.Join(tempdir, fmt.Sprintf(\"%s.%s\", basename, DB_FILE_NAME_EXTENSION))\n\n\tmodTime, err := b.db.GetIncrementalBackupTime()\n\tif err != nil {\n\t\tglog.Warningf(\"Error getting DB incremental backup time; using current time instead. %s\", err)\n\t\tmodTime = now\n\t}\n\tif err := b.writeDBBackupToFile(tempfilename); err != nil {\n\t\treturn err\n\t}\n\tbucket := b.gsClient.Bucket(b.gsBucket)\n\tobjectname := fmt.Sprintf(\"%s/%s/%s.%s\", DB_BACKUP_DIR, now.UTC().Format(\"2006/01/02\"), basename, DB_FILE_NAME_EXTENSION)\n\tif err := uploadFile(b.ctx, tempfilename, bucket, objectname, modTime); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func performBackup() (int, error) {\n\ttime.Sleep(1 * time.Second)\n\treturn 42, nil\n}", "func (t *Task) ensureStageBackup() (*velero.Backup, error) {\n\tbackup, err := t.getStageBackup()\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tif backup != nil {\n\t\treturn backup, nil\n\t}\n\n\tclient, err := t.getSourceClient()\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tt.Log.Info(\"Building Stage Velero Backup resource definition\")\n\tnewBackup, err := t.buildBackup(client, \"stage\")\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tlabelSelector := metav1.LabelSelector{\n\t\tMatchLabels: map[string]string{\n\t\t\tmigapi.IncludedInStageBackupLabel: t.UID(),\n\t\t},\n\t}\n\tnewBackup.Labels[migapi.StageBackupLabel] = t.UID()\n\tnewBackup.Labels[migapi.MigMigrationDebugLabel] = t.Owner.Name\n\tnewBackup.Labels[migapi.MigPlanDebugLabel] = t.Owner.Spec.MigPlanRef.Name\n\tnewBackup.Labels[migapi.MigMigrationLabel] = string(t.Owner.UID)\n\tnewBackup.Labels[migapi.MigPlanLabel] = string(t.PlanResources.MigPlan.UID)\n\tvar includedResources mapset.Set\n\n\tif (t.indirectImageMigration() || Settings.DisImgCopy) && !t.migrateState() {\n\t\tincludedResources = settings.IncludedStageResources\n\t} else {\n\t\tincludedResources = settings.IncludedStageResources.Difference(mapset.NewSetFromSlice([]interface{}{settings.ISResource}))\n\t}\n\tnewBackup.Spec.IncludedResources = toStringSlice(includedResources.Difference(toSet(t.PlanResources.MigPlan.Status.ExcludedResources)))\n\tnewBackup.Spec.ExcludedResources = toStringSlice(settings.ExcludedStageResources.Union(toSet(t.PlanResources.MigPlan.Status.ExcludedResources)))\n\tnewBackup.Spec.LabelSelector = &labelSelector\n\tif Settings.DisImgCopy {\n\t\tif newBackup.Annotations == nil {\n\t\t\tnewBackup.Annotations = map[string]string{}\n\t\t}\n\t\tnewBackup.Annotations[migapi.DisableImageCopy] = strconv.FormatBool(Settings.DisImgCopy)\n\t}\n\tt.Log.Info(\"Creating Stage Velero Backup on source cluster.\",\n\t\t\"backup\", path.Join(newBackup.Namespace, newBackup.Name))\n\terr = client.Create(context.TODO(), newBackup)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newBackup, nil\n}", "func WaitForScheduledBackup(backupScheduleName string, retryInterval time.Duration, timeout time.Duration) (*api.BackupObject, error) {\n\tbeginTime := time.Now()\n\tbeginTimeSec := beginTime.Unix()\n\n\tt := func() (interface{}, bool, error) {\n\t\tlogrus.Infof(\"Enumerating backups\")\n\t\tbkpEnumerateReq := &api.BackupEnumerateRequest{\n\t\t\tOrgId: OrgID}\n\t\t//ctx, err := backup.GetPxCentralAdminCtx()\n\t\tctx, err := backup.GetAdminCtxFromSecret()\n\t\tif err != nil {\n\t\t\treturn nil, true, err\n\t\t}\n\t\tcurBackups, err := Inst().Backup.EnumerateBackup(ctx, bkpEnumerateReq)\n\t\tif err != nil {\n\t\t\treturn nil, true, err\n\t\t}\n\t\tfor _, bkp := range curBackups.GetBackups() {\n\t\t\tcreateTime := bkp.GetCreateTime()\n\t\t\tif beginTimeSec > createTime.GetSeconds() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif (bkp.GetStatus().GetStatus() == api.BackupInfo_StatusInfo_Success ||\n\t\t\t\tbkp.GetStatus().GetStatus() == api.BackupInfo_StatusInfo_PartialSuccess) &&\n\t\t\t\tbkp.GetBackupSchedule().GetName() == backupScheduleName {\n\t\t\t\treturn bkp, false, nil\n\t\t\t}\n\t\t}\n\t\terr = fmt.Errorf(\"unable to find backup from backup schedule with name %s after time %v\",\n\t\t\tbackupScheduleName, beginTime)\n\t\treturn nil, true, err\n\t}\n\n\tbkpInterface, err := task.DoRetryWithTimeout(t, timeout, retryInterval)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbkp := bkpInterface.(*api.BackupObject)\n\treturn bkp, nil\n\n}", "func TestBackup(t *testing.T) {\n\tt.Run(\"with failing operations\", func(t *testing.T) {\n\t\texec, bctx, _ := testBackupExecutor(t, testFailSyncSpec)\n\n\t\terr := exec.Backup(bctx)\n\n\t\trequire.Error(t, err, \"returns an error of a sync operation fails\")\n\t\tassert.Contains(t, \"test operation failed\", err.Error())\n\t})\n\n\tt.Run(\"with successful operations\", func(t *testing.T) {\n\t\texec, bctx, _ := testBackupExecutor(t, testSuccessSpec)\n\n\t\trequire.NoError(t, exec.Backup(bctx))\n\t})\n\n\tt.Run(\"timeout doesn't hang\", func(t *testing.T) {\n\t\texec, bctx, _ := testBackupExecutorWithTimeout(t, testSuccessSpec, 0)\n\n\t\terr := exec.Backup(bctx)\n\t\trequire.Error(t, err, \"a timeout has happened\")\n\t\tassert.Contains(t, err.Error(), \"context deadline exceeded\")\n\t})\n}", "func (b *BackupJob) Run() {\n\tb.Log.Info(fmt.Sprintf(\"Kick off backup job for %s/%s...\", b.Instance.Namespace, b.Instance.Name))\n\tctx := context.Background()\n\tinstance := mysqlv1alpha1.Instance{}\n\tif err := b.Client.Get(ctx, b.Instance, &instance); err != nil {\n\t\tb.Log.Info(fmt.Sprintf(\"job for %s/%s failed. Could not access instance...\", b.Instance.Namespace, b.Instance.Name))\n\t\treturn\n\t}\n\tb.Log.Info(fmt.Sprintf(\"job for %s/%s succeeded...\", b.Instance.Namespace, b.Instance.Name))\n\tbackupName := fmt.Sprintf(\"%s-backup-%s\", instance.Name, time.Now().Format(\"20060102-150405\"))\n\tbackup := &mysqlv1alpha1.Backup{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: backupName,\n\t\t\tNamespace: instance.Namespace,\n\t\t},\n\t\tSpec: mysqlv1alpha1.BackupSpec{\n\t\t\tStore: instance.Spec.BackupSchedule.Store,\n\t\t\tInstance: instance.Name,\n\t\t},\n\t}\n\tif err := controllerutil.SetControllerReference(&instance, backup, b.Scheme); err != nil {\n\t\tb.Log.Info(fmt.Sprintf(\"Error registering backup %s/%s with instance %s\", instance.Namespace, backupName, instance.Name))\n\t\treturn\n\t}\n\tif err := b.Client.Create(ctx, backup); err != nil {\n\t\tb.Log.Info(fmt.Sprintf(\"Error creating backup %s/%s for instance %s\", instance.Namespace, backupName, instance.Name))\n\t\treturn\n\t}\n\tb.Log.Info(fmt.Sprintf(\"Backup %s/%s for instance %s successfully created\", instance.Namespace, backupName, instance.Name))\n}", "func generateBackupJobSpecIntent(postgresCluster *v1beta1.PostgresCluster,\n\trepo v1beta1.PGBackRestRepo, serviceAccountName string,\n\tlabels, annotations map[string]string, opts ...string) (*batchv1.JobSpec, error) {\n\n\tselector, containerName, err := getPGBackRestExecSelector(postgresCluster, repo)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\n\trepoIndex := regexRepoIndex.FindString(repo.Name)\n\tcmdOpts := []string{\n\t\t\"--stanza=\" + pgbackrest.DefaultStanzaName,\n\t\t\"--repo=\" + repoIndex,\n\t}\n\tcmdOpts = append(cmdOpts, opts...)\n\n\tcontainer := corev1.Container{\n\t\tCommand: []string{\"/opt/crunchy/bin/pgbackrest\"},\n\t\tEnv: []corev1.EnvVar{\n\t\t\t{Name: \"COMMAND\", Value: \"backup\"},\n\t\t\t{Name: \"COMMAND_OPTS\", Value: strings.Join(cmdOpts, \" \")},\n\t\t\t{Name: \"COMPARE_HASH\", Value: \"true\"},\n\t\t\t{Name: \"CONTAINER\", Value: containerName},\n\t\t\t{Name: \"NAMESPACE\", Value: postgresCluster.GetNamespace()},\n\t\t\t{Name: \"SELECTOR\", Value: selector.String()},\n\t\t},\n\t\tImage: config.PGBackRestContainerImage(postgresCluster),\n\t\tImagePullPolicy: postgresCluster.Spec.ImagePullPolicy,\n\t\tName: naming.PGBackRestRepoContainerName,\n\t\tSecurityContext: initialize.RestrictedSecurityContext(),\n\t}\n\n\tif postgresCluster.Spec.Backups.PGBackRest.Jobs != nil {\n\t\tcontainer.Resources = postgresCluster.Spec.Backups.PGBackRest.Jobs.Resources\n\t}\n\n\tjobSpec := &batchv1.JobSpec{\n\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\tObjectMeta: metav1.ObjectMeta{Labels: labels, Annotations: annotations},\n\t\t\tSpec: corev1.PodSpec{\n\t\t\t\tContainers: []corev1.Container{container},\n\n\t\t\t\t// Disable environment variables for services other than the Kubernetes API.\n\t\t\t\t// - https://docs.k8s.io/concepts/services-networking/connect-applications-service/#accessing-the-service\n\t\t\t\t// - https://releases.k8s.io/v1.23.0/pkg/kubelet/kubelet_pods.go#L553-L563\n\t\t\t\tEnableServiceLinks: initialize.Bool(false),\n\n\t\t\t\t// Set RestartPolicy to \"Never\" since we want a new Pod to be created by the Job\n\t\t\t\t// controller when there is a failure (instead of the container simply restarting).\n\t\t\t\t// This will ensure the Job always has the latest configs mounted following a\n\t\t\t\t// failure as needed to successfully verify config hashes and run the Job.\n\t\t\t\tRestartPolicy: corev1.RestartPolicyNever,\n\t\t\t\tSecurityContext: initialize.PodSecurityContext(),\n\t\t\t\tServiceAccountName: serviceAccountName,\n\t\t\t},\n\t\t},\n\t}\n\n\tif jobs := postgresCluster.Spec.Backups.PGBackRest.Jobs; jobs != nil {\n\t\tjobSpec.TTLSecondsAfterFinished = jobs.TTLSecondsAfterFinished\n\t}\n\n\t// set the priority class name, tolerations, and affinity, if they exist\n\tif postgresCluster.Spec.Backups.PGBackRest.Jobs != nil {\n\t\tif postgresCluster.Spec.Backups.PGBackRest.Jobs.PriorityClassName != nil {\n\t\t\tjobSpec.Template.Spec.PriorityClassName =\n\t\t\t\t*postgresCluster.Spec.Backups.PGBackRest.Jobs.PriorityClassName\n\t\t}\n\t\tjobSpec.Template.Spec.Tolerations = postgresCluster.Spec.Backups.PGBackRest.Jobs.Tolerations\n\t\tjobSpec.Template.Spec.Affinity = postgresCluster.Spec.Backups.PGBackRest.Jobs.Affinity\n\t}\n\n\t// Set the image pull secrets, if any exist.\n\t// This is set here rather than using the service account due to the lack\n\t// of propagation to existing pods when the CRD is updated:\n\t// https://github.com/kubernetes/kubernetes/issues/88456\n\tjobSpec.Template.Spec.ImagePullSecrets = postgresCluster.Spec.ImagePullSecrets\n\n\t// add pgBackRest configs to template\n\tif containerName == naming.PGBackRestRepoContainerName {\n\t\tpgbackrest.AddConfigToRepoPod(postgresCluster, &jobSpec.Template.Spec)\n\t} else {\n\t\tpgbackrest.AddConfigToInstancePod(postgresCluster, &jobSpec.Template.Spec)\n\t}\n\n\treturn jobSpec, nil\n}", "func (client *WebAppsClient) backupCreateRequest(ctx context.Context, resourceGroupName string, name string, request BackupRequest, options *WebAppsBackupOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/backup\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, runtime.MarshalAsJSON(req, request)\n}", "func NewModelsBackupSchedule() *ModelsBackupSchedule {\n\tthis := ModelsBackupSchedule{}\n\treturn &this\n}", "func (o *Operator) onStartBackup(stop <-chan struct{}) {\n\tfor {\n\t\tif err := o.waitForCRD(false, false, false, true); err == nil {\n\t\t\tbreak\n\t\t} else {\n\t\t\tlog.Error().Err(err).Msg(\"Resource initialization failed\")\n\t\t\tlog.Info().Msgf(\"Retrying in %s...\", initRetryWaitTime)\n\t\t\ttime.Sleep(initRetryWaitTime)\n\t\t}\n\t}\n\toperatorName := \"arangodb-backup-operator\"\n\toperator := backupOper.NewOperator(operatorName, o.Namespace)\n\n\trand.Seed(time.Now().Unix())\n\n\tzerolog.SetGlobalLevel(zerolog.DebugLevel)\n\n\trestClient, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tarangoClientSet, err := arangoClientSet.NewForConfig(restClient)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tkubeClientSet, err := kubernetes.NewForConfig(restClient)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\teventRecorder := event.NewEventRecorder(operatorName, kubeClientSet)\n\n\tarangoInformer := arangoInformer.NewSharedInformerFactoryWithOptions(arangoClientSet, 10*time.Second, arangoInformer.WithNamespace(o.Namespace))\n\n\tif err = backup.RegisterInformer(operator, eventRecorder, arangoClientSet, kubeClientSet, arangoInformer); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err = policy.RegisterInformer(operator, eventRecorder, arangoClientSet, kubeClientSet, arangoInformer); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err = operator.RegisterStarter(arangoInformer); err != nil {\n\t\tpanic(err)\n\t}\n\n\tprometheus.MustRegister(operator)\n\n\toperator.Start(8, stop)\n\to.Dependencies.BackupProbe.SetReady()\n\n\t<-stop\n}", "func deleteBackup(w http.ResponseWriter, r *http.Request) {\n\tlogrus.Debugf(\"DeleteBackup r=%s\", r)\n\tparams := mux.Vars(r)\n\n\tapiID := params[\"id\"]\n\n\tif RunningBackupAPIID == apiID {\n\t\tif currentBackupContext.CmdRef != nil {\n\t\t\tlogrus.Debugf(\"Canceling currently running backup %s\", RunningBackupAPIID)\n\t\t\terr := (*currentBackupContext.CmdRef).Stop()\n\t\t\tif err != nil {\n\t\t\t\tsendSchellyResponse(apiID, \"\", \"running\", \"Couldn't cancel current running backup task. err=\"+err.Error(), -1, http.StatusInternalServerError, w)\n\t\t\t} else {\n\t\t\t\tsendSchellyResponse(apiID, \"\", \"deleted\", \"Running backup task was cancelled successfuly\", -1, http.StatusOK, w)\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\tbk, err := currentBackuper.GetBackup(apiID)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Error calling deleteBackup() with id %s\", apiID)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t} else if bk == nil {\n\t\tlogrus.Warnf(\"Backup %s not found\", apiID)\n\t\thttp.Error(w, fmt.Sprintf(\"Backup %s not found\", apiID), http.StatusNotFound)\n\t\treturn\n\t}\n\n\terr = currentBackuper.DeleteBackup(apiID)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Error calling deleteBackup() with id %s\", apiID)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tlogrus.Debugf(\"Backup %s deleted\", apiID)\n\n\tsendSchellyResponse(apiID, bk.DataID, \"deleted\", \"backup deleted successfuly\", -1, http.StatusOK, w)\n}", "func NewBackupJob(client client.Client, instance types.NamespacedName, log logr.Logger, scheme *runtime.Scheme) *BackupJob {\n\treturn &BackupJob{\n\t\tClient: client,\n\t\tInstance: instance,\n\t\tLog: log,\n\t\tScheme: scheme,\n\t}\n}", "func backupExecutor(args prompter.CmdArgs) error {\n\tfmt.Println(\"inside backupExecutor\")\n\tfmt.Printf(\"args: %v\\n\", args)\n\tif args.Contains(\"-file\") {\n\t\tfilename, err := args.GetFirstValue(\"-file\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn config.Backup(filename)\n\t}\n\treturn config.Backup(\"\")\n}", "func newCron(schedule string) (chan bool, *cron.Cron) {\n\tchannel := make(chan bool)\n\tcj := cron.New()\n\tcj.AddFunc(schedule, func() { cronTriggered(channel) })\n\tglog.Info(\"db backup schedule: \" + schedule)\n\treturn channel, cj\n}", "func makeBackUp(params [2]string, ip string, port int, login string, pass string, bkp bool) {\n\t//Снятие бэкапов с перечисленных роутеров\n\n\t//dbconfig := params[0]\n\t//savepath := params[1]\n\n\t//sftpRouter(sshRouter(login, pass, ip, port), bkp, params[1])\n}", "func (device *Device) CreateBackup() error {\n\tif err := device.Device.CreateBackup(); err != nil {\n\t\treturn err\n\t}\n\tdevice.Notify(observable.Event{\n\t\tSubject: fmt.Sprintf(\"devices/bitbox02/%s/backups/list\", device.deviceID),\n\t\tAction: action.Reload,\n\t})\n\treturn nil\n}", "func (t *Task) ensureInitialBackup() (*velero.Backup, error) {\n\tbackup, err := t.getInitialBackup()\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tif backup != nil {\n\t\treturn backup, nil\n\t}\n\n\tclient, err := t.getSourceClient()\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tnewBackup, err := t.buildBackup(client, \"initial\")\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\tuserIncludedResources, _, err := t.PlanResources.MigPlan.GetIncludedResourcesList(client)\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\n\tnewBackup.Labels[migapi.InitialBackupLabel] = t.UID()\n\tnewBackup.Labels[migapi.MigMigrationDebugLabel] = t.Owner.Name\n\tnewBackup.Labels[migapi.MigPlanDebugLabel] = t.Owner.Spec.MigPlanRef.Name\n\tnewBackup.Labels[migapi.MigMigrationLabel] = string(t.Owner.UID)\n\tnewBackup.Labels[migapi.MigPlanLabel] = string(t.PlanResources.MigPlan.UID)\n\tnewBackup.Spec.IncludedResources = toStringSlice(settings.IncludedInitialResources.Difference(toSet(t.PlanResources.MigPlan.Status.ExcludedResources)))\n\tnewBackup.Spec.IncludedResources = append(newBackup.Spec.IncludedResources, userIncludedResources...)\n\tnewBackup.Spec.ExcludedResources = toStringSlice(settings.ExcludedInitialResources.Union(toSet(t.PlanResources.MigPlan.Status.ExcludedResources)))\n\tnewBackup.Spec.LabelSelector = t.PlanResources.MigPlan.Spec.LabelSelector\n\tdelete(newBackup.Annotations, migapi.QuiesceAnnotation)\n\n\tif Settings.DisImgCopy {\n\t\tif newBackup.Annotations == nil {\n\t\t\tnewBackup.Annotations = map[string]string{}\n\t\t}\n\t\tnewBackup.Annotations[migapi.DisableImageCopy] = strconv.FormatBool(Settings.DisImgCopy)\n\t}\n\n\terr = client.Create(context.TODO(), newBackup)\n\tif err != nil {\n\t\treturn nil, liberr.Wrap(err)\n\t}\n\treturn newBackup, nil\n}", "func (scheduler *BackupJobScheduler) Schedule(namespace string, pvcName string) {\n\tscheduler.inputChannel <- &BackupJobInput{\n\t\tNamespace: namespace,\n\t\tPVCName: pvcName,\n\t}\n}", "func (tbbsd TimeBasedBackupScheduleDescription) AsBackupScheduleDescription() (*BackupScheduleDescription, bool) {\n\treturn nil, false\n}", "func NewBackup() *Backup {\n\treturn &Backup{\n\t\tExec: \"mysqldump\",\n\t}\n}", "func Test_getLastSuccessBySchedule(t *testing.T) {\n\tbuildBackup := func(phase velerov1api.BackupPhase, completion time.Time, schedule string) velerov1api.Backup {\n\t\tb := builder.ForBackup(\"\", \"\").\n\t\t\tObjectMeta(builder.WithLabels(velerov1api.ScheduleNameLabel, schedule)).\n\t\t\tPhase(phase)\n\n\t\tif !completion.IsZero() {\n\t\t\tb.CompletionTimestamp(completion)\n\t\t}\n\n\t\treturn *b.Result()\n\t}\n\n\t// create a static \"base time\" that can be used to easily construct completion timestamps\n\t// by using the .Add(...) method.\n\tbaseTime, err := time.Parse(time.RFC1123, time.RFC1123)\n\trequire.NoError(t, err)\n\n\ttests := []struct {\n\t\tname string\n\t\tbackups []velerov1api.Backup\n\t\twant map[string]time.Time\n\t}{\n\t\t{\n\t\t\tname: \"when backups is nil, an empty map is returned\",\n\t\t\tbackups: nil,\n\t\t\twant: map[string]time.Time{},\n\t\t},\n\t\t{\n\t\t\tname: \"when backups is empty, an empty map is returned\",\n\t\t\tbackups: []velerov1api.Backup{},\n\t\t\twant: map[string]time.Time{},\n\t\t},\n\t\t{\n\t\t\tname: \"when multiple completed backups for a schedule exist, the latest one is returned\",\n\t\t\tbackups: []velerov1api.Backup{\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime, \"schedule-1\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(time.Second), \"schedule-1\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(-time.Second), \"schedule-1\"),\n\t\t\t},\n\t\t\twant: map[string]time.Time{\n\t\t\t\t\"schedule-1\": baseTime.Add(time.Second),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"when the most recent backup for a schedule is Failed, the timestamp of the most recent Completed one is returned\",\n\t\t\tbackups: []velerov1api.Backup{\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime, \"schedule-1\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseFailed, baseTime.Add(time.Second), \"schedule-1\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(-time.Second), \"schedule-1\"),\n\t\t\t},\n\t\t\twant: map[string]time.Time{\n\t\t\t\t\"schedule-1\": baseTime,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"when there are no Completed backups for a schedule, it's not returned\",\n\t\t\tbackups: []velerov1api.Backup{\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseInProgress, baseTime, \"schedule-1\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseFailed, baseTime.Add(time.Second), \"schedule-1\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhasePartiallyFailed, baseTime.Add(-time.Second), \"schedule-1\"),\n\t\t\t},\n\t\t\twant: map[string]time.Time{},\n\t\t},\n\t\t{\n\t\t\tname: \"when backups exist without a schedule, the most recent Completed one is returned\",\n\t\t\tbackups: []velerov1api.Backup{\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime, \"\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseFailed, baseTime.Add(time.Second), \"\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(-time.Second), \"\"),\n\t\t\t},\n\t\t\twant: map[string]time.Time{\n\t\t\t\t\"\": baseTime,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"when backups exist for multiple schedules, the most recent Completed timestamp for each schedule is returned\",\n\t\t\tbackups: []velerov1api.Backup{\n\t\t\t\t// ad-hoc backups (no schedule)\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(30*time.Minute), \"\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseFailed, baseTime.Add(time.Hour), \"\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(-time.Second), \"\"),\n\n\t\t\t\t// schedule-1\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime, \"schedule-1\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseFailed, baseTime.Add(time.Second), \"schedule-1\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(-time.Second), \"schedule-1\"),\n\n\t\t\t\t// schedule-2\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(24*time.Hour), \"schedule-2\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(48*time.Hour), \"schedule-2\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseCompleted, baseTime.Add(72*time.Hour), \"schedule-2\"),\n\n\t\t\t\t// schedule-3\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseNew, baseTime, \"schedule-3\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhaseInProgress, baseTime.Add(time.Minute), \"schedule-3\"),\n\t\t\t\tbuildBackup(velerov1api.BackupPhasePartiallyFailed, baseTime.Add(2*time.Minute), \"schedule-3\"),\n\t\t\t},\n\t\t\twant: map[string]time.Time{\n\t\t\t\t\"\": baseTime.Add(30 * time.Minute),\n\t\t\t\t\"schedule-1\": baseTime,\n\t\t\t\t\"schedule-2\": baseTime.Add(72 * time.Hour),\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tassert.Equal(t, tc.want, getLastSuccessBySchedule(tc.backups))\n\t\t})\n\t}\n}", "func (a *Client) BackupDatabase(params *BackupDatabaseParams) (*BackupDatabaseOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewBackupDatabaseParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"backupDatabase\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/sdx/{name}/backupDatabase\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &BackupDatabaseReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*BackupDatabaseOK), nil\n\n}", "func (client *Client) CreateBackup(request *CreateBackupRequest) (_result *CreateBackupResponse, _err error) {\n\truntime := &util.RuntimeOptions{}\n\t_result = &CreateBackupResponse{}\n\t_body, _err := client.CreateBackupWithOptions(request, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_result = _body\n\treturn _result, _err\n}", "func (client *Client) CreateBackupWithOptions(request *CreateBackupRequest, runtime *util.RuntimeOptions) (_result *CreateBackupResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tquery := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.InstanceId)) {\n\t\tquery[\"InstanceId\"] = request.InstanceId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerAccount)) {\n\t\tquery[\"OwnerAccount\"] = request.OwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerId)) {\n\t\tquery[\"OwnerId\"] = request.OwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerAccount)) {\n\t\tquery[\"ResourceOwnerAccount\"] = request.ResourceOwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerId)) {\n\t\tquery[\"ResourceOwnerId\"] = request.ResourceOwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.SecurityToken)) {\n\t\tquery[\"SecurityToken\"] = request.SecurityToken\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tQuery: openapiutil.Query(query),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"CreateBackup\"),\n\t\tVersion: tea.String(\"2015-01-01\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &CreateBackupResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func BackupAPI(rotation int, folder string, db *models.DB) {\n\n\tapi := NewAPI(db)\n\tid := time.Now().Format(\"2006-01-02_150405\")\n\n\tfmt.Println(\"backuped tables:\")\n\ttableNames := []string{\"rates\", \"projects\", \"reported_records\", \"consultants\", \"holidays\"}\n\tfor _, baseFileName := range tableNames {\n\t\terr := rotateBackupFile(rotation, folder, baseFileName)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"not able to rotate %s backup files, backups stopped, handle the error: %s\\n\", baseFileName, err)\n\t\t}\n\n\t\tfileName := baseFileName + \"_\" + id + \".csv\"\n\t\tfilePath := filepath.Join(folder, fileName)\n\t\tn := 0\n\t\tswitch baseFileName {\n\t\tcase \"projects\": n, err = api.projects.ProjectBackup(filePath)\n\t\tcase \"rates\": n, err = api.rates.RateBackup(filePath)\n\t\tcase \"consultants\": n, err = api.consultants.ConsultantBackup(filePath)\n\t\tcase \"holidays\": n, err = api.holidays.HolidayBackup(filePath)\n\t\tcase \"reported_records\": n, err = api.reportedRecords.ReportedRecordBackup(filePath)\n\t\t}\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"error during %s backup: %s\\n\", baseFileName, err)\n\t\t} else {\n\t\t\tfmt.Printf(\"- %s, %d records\\n\", baseFileName, n)\n\t\t}\n\t}\n}", "func NewBackupJobScheduler(\n\tjob BackupJobRunner,\n\tclientSet *kubernetes.Clientset,\n\tcsiClient *csiV1.Clientset,\n\tstorageClassName string,\n\ts3Url string,\n\ts3Bucket string,\n\ts3AccessKey string,\n\ts3SecretKey string) *BackupJobScheduler {\n\n\tscheduler := BackupJobScheduler{\n\t\tjobFunc: \t\tjob,\n\t\twaitGroup: \t\tsync.WaitGroup{},\n\t\tinputChannel: \t\tmake(chan *BackupJobInput),\n\t\toutputChannel: \t\tmake(chan error),\n\t\tstorageClassName: \tstorageClassName,\n\t\tclientSet: \t\t\tclientSet,\n\t\tcsiClient: \t\t\tcsiClient,\n\t\ts3Url:\t\t\t\ts3Url,\n\t\ts3Bucket: \t\t\ts3Bucket,\n\t\ts3AccessKey: \t\ts3AccessKey,\n\t\ts3SecretKey:\t\ts3SecretKey,\n\t}\n\tgo scheduler.Run()\n\treturn &scheduler\n}", "func BackupInitInstance() {\n\tvar err error\n\tvar token string\n\tvar commitID string\n\tlog.Infof(\"Inside BackupInitInstance\")\n\terr = Inst().S.Init(scheduler.InitOptions{\n\t\tSpecDir: Inst().SpecDir,\n\t\tVolDriverName: Inst().V.String(),\n\t\tStorageProvisioner: Inst().Provisioner,\n\t\tNodeDriverName: Inst().N.String(),\n\t})\n\tlog.FailOnError(err, \"Error occurred while Scheduler Driver Initialization\")\n\terr = Inst().N.Init(node.InitOptions{\n\t\tSpecDir: Inst().SpecDir,\n\t})\n\tlog.FailOnError(err, \"Error occurred while Node Driver Initialization\")\n\terr = Inst().V.Init(Inst().S.String(), Inst().N.String(), token, Inst().Provisioner, Inst().CsiGenericDriverConfigMap)\n\tlog.FailOnError(err, \"Error occurred while Volume Driver Initialization\")\n\tif Inst().Backup != nil {\n\t\terr = Inst().Backup.Init(Inst().S.String(), Inst().N.String(), Inst().V.String(), token)\n\t\tlog.FailOnError(err, \"Error occurred while Backup Driver Initialization\")\n\t}\n\tSetupTestRail()\n\n\t// Getting Px version info\n\tpxVersion, err := Inst().V.GetDriverVersion()\n\tlog.FailOnError(err, \"Error occurred while getting PX version\")\n\tif len(strings.Split(pxVersion, \"-\")) > 1 {\n\t\tcommitID = strings.Split(pxVersion, \"-\")[1]\n\t} else {\n\t\tcommitID = \"NA\"\n\t}\n\tt := Inst().Dash.TestSet\n\tt.CommitID = commitID\n\tif pxVersion != \"\" {\n\t\tt.Tags[\"px-version\"] = pxVersion\n\t}\n\n\t// Getting Px-Backup server version info and setting Aetos Dashboard tags\n\tPxBackupVersion, err = GetPxBackupVersionString()\n\tlog.FailOnError(err, \"Error getting Px Backup version\")\n\tPxBackupBuildDate, err := GetPxBackupBuildDate()\n\tlog.FailOnError(err, \"Error getting Px Backup build date\")\n\tt.Tags[\"px-backup-version\"] = PxBackupVersion\n\tt.Tags[\"px-backup-build-date\"] = PxBackupBuildDate\n\tt.Tags[\"storageProvisioner\"] = Inst().Provisioner\n\tt.Tags[\"pureVolume\"] = fmt.Sprintf(\"%t\", Inst().PureVolumes)\n\tt.Tags[\"pureSANType\"] = Inst().PureSANType\n\n\tInst().Dash.TestSetUpdate(t)\n\t// Setting the common password\n\tcommonPassword = backup.PxCentralAdminPwd + RandomString(4)\n\t// Dumping source and destination kubeconfig to file system path\n\tlog.Infof(\"Dumping source and destination kubeconfig to file system path\")\n\tkubeconfigs := os.Getenv(\"KUBECONFIGS\")\n\tdash.VerifyFatal(kubeconfigs != \"\", true, \"Getting KUBECONFIGS Environment variable\")\n\tkubeconfigList := strings.Split(kubeconfigs, \",\")\n\tdash.VerifyFatal(len(kubeconfigList) < 2, false, \"minimum 2 kubeconfigs are required for source and destination cluster\")\n\tDumpKubeconfigs(kubeconfigList)\n\tif os.Getenv(\"CLUSTER_PROVIDER\") == drivers.ProviderRke {\n\t\t// Switch context to destination cluster to update RancherMap with destination cluster details\n\t\terr = SetDestinationKubeConfig()\n\t\tlog.FailOnError(err, \"Switching context to destination cluster failed\")\n\t\t// Switch context to destination cluster to update RancherMap with source cluster details\n\t\terr = SetSourceKubeConfig()\n\t\tlog.FailOnError(err, \"Switching context to source cluster failed\")\n\t}\n}", "func NewBackup() *Backup {\n\treturn &Backup{}\n}", "func (r *Repo) RunBackup(source string, tags []string) error {\n\tcmd := exec.Command(resticCmd, \"-r\", r.Path, \"-p\", r.Passwordfile,\n\t\t\"backup\", \"--exclude-caches\")\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\tfor _, t := range tags {\n\t\tcmd.Args = append(cmd.Args, \"--tag\", t)\n\t}\n\tcmd.Args = append(cmd.Args, source)\n\n\treturn cmd.Run()\n}", "func NewBackup(ctx *pulumi.Context,\n\tname string, args *BackupArgs, opts ...pulumi.ResourceOption) (*Backup, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.BackupId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'BackupId'\")\n\t}\n\tif args.EncryptionConfigEncryptionType == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'EncryptionConfigEncryptionType'\")\n\t}\n\tif args.InstanceId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'InstanceId'\")\n\t}\n\treplaceOnChanges := pulumi.ReplaceOnChanges([]string{\n\t\t\"backupId\",\n\t\t\"encryptionConfigEncryptionType\",\n\t\t\"instanceId\",\n\t\t\"project\",\n\t})\n\topts = append(opts, replaceOnChanges)\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Backup\n\terr := ctx.RegisterResource(\"google-native:spanner/v1:Backup\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func LogBackupSchedule(schedule *crv1.MySQLBackupSchedule) *logrus.Entry {\n\treturn logrus.WithFields(logrus.Fields{\n\t\t\"backupSchedule\": schedule.Name,\n\t})\n}", "func (s *API) CreateDatabaseBackup(req *CreateDatabaseBackupRequest, opts ...scw.RequestOption) (*DatabaseBackup, error) {\n\tvar err error\n\n\tif req.Region == \"\" {\n\t\tdefaultRegion, _ := s.client.GetDefaultRegion()\n\t\treq.Region = defaultRegion\n\t}\n\n\tif req.Name == \"\" {\n\t\treq.Name = namegenerator.GetRandomName(\"bkp\")\n\t}\n\n\tif fmt.Sprint(req.Region) == \"\" {\n\t\treturn nil, errors.New(\"field Region cannot be empty in request\")\n\t}\n\n\tscwReq := &scw.ScalewayRequest{\n\t\tMethod: \"POST\",\n\t\tPath: \"/rdb/v1/regions/\" + fmt.Sprint(req.Region) + \"/backups\",\n\t\tHeaders: http.Header{},\n\t}\n\n\terr = scwReq.SetBody(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar resp DatabaseBackup\n\n\terr = s.client.Do(scwReq, &resp, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func getBackup(w http.ResponseWriter, r *http.Request) {\n\tlogrus.Debugf(\"GetBackup r=%s\", r)\n\tparams := mux.Vars(r)\n\n\tapiID := params[\"id\"]\n\n\tif RunningBackupAPIID == apiID {\n\t\tsendSchellyResponse(apiID, \"\", \"running\", \"backup is running\", -1, http.StatusOK, w)\n\t\treturn\n\t}\n\n\tresp, err := currentBackuper.GetBackup(apiID)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Error calling getBackup() for id %s. err=%s\", apiID, err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t} else if resp == nil {\n\t\tlogrus.Debugf(\"Backup %s not found\", apiID)\n\t\thttp.Error(w, fmt.Sprintf(\"Backup %s not found\", apiID), http.StatusNotFound)\n\t\treturn\n\t}\n\n\tsendSchellyResponse(apiID, resp.DataID, resp.Status, resp.Message, resp.SizeMB, http.StatusOK, w)\n}", "func Backup(action *recipe.Action, tmpDir string) error {\n\tpath, err := action.GetS(0)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tisSafePath, err := checkPathSafety(action.Command.Recipe, path)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch {\n\tcase !isSafePath:\n\t\treturn fmt.Errorf(\"Path is unsafe (%s)\", path)\n\tcase !fsutil.IsExist(path):\n\t\treturn fmt.Errorf(\"File %s does not exist\", path)\n\tcase !fsutil.IsRegular(path):\n\t\treturn fmt.Errorf(\"Object %s is not a file\", path)\n\t}\n\n\tpathCRC32 := calcCRC32Q(path)\n\n\terr = fsutil.CopyFile(path, tmpDir+\"/\"+pathCRC32)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Can't backup file: %v\", err)\n\t}\n\n\terr = fsutil.CopyAttr(path, tmpDir+\"/\"+pathCRC32)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Can't copy attributes: %v\", err)\n\t}\n\n\treturn nil\n}", "func backupEtcd(mgr *manager.Manager, node *kubekeyapiv1alpha1.HostCfg) error {\n\t_, err := mgr.Runner.ExecuteCmd(fmt.Sprintf(\"sudo -E /bin/sh -c \\\"mkdir -p %s\\\"\", mgr.Cluster.Kubernetes.EtcdBackupScriptDir), 0, false)\n\tif err != nil {\n\t\treturn errors.Wrap(errors.WithStack(err), \"Failed to create etcd backup\")\n\t}\n\ttmpDir := \"/tmp/kubekey\"\n\tetcdBackupScript, _ := tmpl.EtcdBackupScript(mgr, node)\n\tetcdBackupScriptBase64 := base64.StdEncoding.EncodeToString([]byte(etcdBackupScript))\n\t_, err2 := mgr.Runner.ExecuteCmd(fmt.Sprintf(\"sudo -E /bin/sh -c \\\"echo %s | base64 -d > %s/etcd-backup.sh && chmod +x %s/etcd-backup.sh\\\"\", etcdBackupScriptBase64, tmpDir, tmpDir), 1, false)\n\tif err2 != nil {\n\t\treturn errors.Wrap(errors.WithStack(err2), \"Failed to generate etcd backup\")\n\t}\n\t_, err3 := mgr.Runner.ExecuteCmd(fmt.Sprintf(\"sudo cp %s/etcd-backup.sh %s &&sudo %s/etcd-backup.sh\", tmpDir, mgr.Cluster.Kubernetes.EtcdBackupScriptDir, mgr.Cluster.Kubernetes.EtcdBackupScriptDir), 1, false)\n\tif err3 != nil {\n\t\treturn errors.Wrap(errors.WithStack(err3), \"Failed to run the etcd-backup.sh\")\n\t}\n\treturn nil\n}", "func (c *calcium) Backup(id, srcPath string) (*types.BackupMessage, error) {\n\tif c.config.BackupDir == \"\" {\n\t\tlog.Infof(\"[Backup] This core has no BackupDir set in config, skip backup for container %s\", id)\n\t\treturn nil, errors.New(\"BackupDir not set\")\n\t}\n\tlog.Debugf(\"[Backup] Backup %s for container %s\", srcPath, id)\n\tcontainer, err := c.GetContainer(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnode, err := c.GetNode(container.Podname, container.Nodename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tctx := utils.ToDockerContext(node.Engine)\n\n\tresp, stat, err := node.Engine.CopyFromContainer(ctx, container.ID, srcPath)\n\tdefer resp.Close()\n\tlog.Debugf(\"[Backup] Docker cp stat: %v\", stat)\n\tif err != nil {\n\t\tlog.Errorf(\"[Backup] Error during CopyFromContainer: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tappname, entrypoint, ident, err := utils.ParseContainerName(container.Name)\n\tif err != nil {\n\t\tlog.Errorf(\"[Backup] Error during ParseContainerName: %v\", err)\n\t\treturn nil, err\n\t}\n\tnow := time.Now().Format(\"2006.01.02.15.04.05\")\n\tbaseDir := filepath.Join(c.config.BackupDir, appname, entrypoint)\n\terr = os.MkdirAll(baseDir, os.FileMode(0700)) // drwx------\n\tif err != nil {\n\t\tlog.Errorf(\"[Backup] Error during mkdir %s, %v\", baseDir, err)\n\t\treturn nil, err\n\t}\n\n\tfilename := fmt.Sprintf(\"%s-%s-%s-%s.tar.gz\", stat.Name, container.ShortID(), ident, now)\n\tbackupFile := filepath.Join(baseDir, filename)\n\tlog.Debugf(\"[Backup] Creating %s\", backupFile)\n\tfile, err := os.Create(backupFile)\n\tif err != nil {\n\t\tlog.Errorf(\"[Backup] Error during create backup file %s: %v\", backupFile, err)\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\tgw := gzip.NewWriter(file)\n\tdefer gw.Close()\n\n\t_, err = io.Copy(gw, resp)\n\tif err != nil {\n\t\tlog.Errorf(\"[Backup] Error during copy resp: %v\", err)\n\t\treturn nil, err\n\t}\n\n\treturn &types.BackupMessage{\n\t\tStatus: \"ok\",\n\t\tSize: stat.Size,\n\t\tPath: backupFile,\n\t}, nil\n}", "func RegisterBackup(ctx context.Context, management *config.Management, opts config.Options) error {\n\tvmBackups := management.HarvesterFactory.Harvesterhci().V1beta1().VirtualMachineBackup()\n\tpvc := management.CoreFactory.Core().V1().PersistentVolumeClaim()\n\tvms := management.VirtFactory.Kubevirt().V1().VirtualMachine()\n\tvolumes := management.LonghornFactory.Longhorn().V1beta1().Volume()\n\tsnapshots := management.SnapshotFactory.Snapshot().V1beta1().VolumeSnapshot()\n\tsnapshotClass := management.SnapshotFactory.Snapshot().V1beta1().VolumeSnapshotClass()\n\n\tvmBackupController := &Handler{\n\t\tvmBackups: vmBackups,\n\t\tvmBackupController: vmBackups,\n\t\tvmBackupCache: vmBackups.Cache(),\n\t\tpvcCache: pvc.Cache(),\n\t\tvms: vms,\n\t\tvmsCache: vms.Cache(),\n\t\tvolumeCache: volumes.Cache(),\n\t\tvolumes: volumes,\n\t\tsnapshots: snapshots,\n\t\tsnapshotCache: snapshots.Cache(),\n\t\tsnapshotClassCache: snapshotClass.Cache(),\n\t\trecorder: management.NewRecorder(backupControllerName, \"\", \"\"),\n\t}\n\n\tvmBackups.OnChange(ctx, backupControllerName, vmBackupController.OnBackupChange)\n\tsnapshots.OnChange(ctx, backupControllerName, vmBackupController.updateVolumeSnapshotChanged)\n\treturn nil\n}", "func (t Task) getBackup(labels map[string]string) (*velero.Backup, error) {\n\tclient, err := t.getSourceClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlist := velero.BackupList{}\n\terr = client.List(\n\t\tcontext.TODO(),\n\t\t&list,\n\t\tk8sclient.MatchingLabels(labels))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(list.Items) > 0 {\n\t\treturn &list.Items[0], nil\n\t}\n\n\treturn nil, nil\n}", "func (s *BackupServer) applyBackup(ctx context.Context, c *beta.Client, request *betapb.ApplyFilestoreBetaBackupRequest) (*betapb.FilestoreBetaBackup, error) {\n\tp := ProtoToBackup(request.GetResource())\n\tres, err := c.ApplyBackup(ctx, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := BackupToProto(res)\n\treturn r, nil\n}", "func Backup(ctx context.Context, res http.ResponseWriter) error {\n\tts := time.Now().Unix()\n\tfilename := fmt.Sprintf(\"search-%d.bak.tar.gz\", ts)\n\ttmp := os.TempDir()\n\tbk := filepath.Join(tmp, filename)\n\n\t// create search-{stamp}.bak.tar.gz\n\tf, err := os.Create(bk)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = backup.ArchiveFS(ctx, cfg.SearchDir(), f)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = f.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// write data to response\n\tdata, err := os.Open(bk)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer data.Close()\n\tdefer os.Remove(bk)\n\n\tdisposition := `attachment; filename=%s`\n\tinfo, err := data.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres.Header().Set(\"Content-Type\", \"application/octet-stream\")\n\tres.Header().Set(\"Content-Disposition\", fmt.Sprintf(disposition, ts))\n\tres.Header().Set(\"Content-Length\", fmt.Sprintf(\"%d\", info.Size()))\n\n\t_, err = io.Copy(res, data)\n\n\treturn err\n}", "func (s *Service) ScheduleTransfer(params *ScheduleParams, tx *gorm.DB) error {\n\tvar err error\n\tif tx == nil {\n\t\ttx = s.db.Begin()\n\t\tdefer func() {\n\t\t\tif err != nil {\n\t\t\t\ttx.Rollback()\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttx.Commit()\n\t\t}()\n\t}\n\n\terr = s.validate(params, tx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger := s.logger.New(\"method\", \"ScheduleTransfer\")\n\ttxRepo := s.scheduledTransactionRepository.WrapContext(tx)\n\tlogRepo := s.scheduledTransactionLogRepository.WrapContext(tx)\n\n\ttransaction, err := s.findOrCreateScheduledTransaction(params, tx)\n\tif err != nil {\n\t\tlogger.Error(\"failed to find or create scheduled transaction\", \"error\", err, \"params\", s.paramsToString(params))\n\t\treturn err\n\t}\n\n\tnewAmount := transaction.Amount.Add(params.Amount)\n\terr = txRepo.Updates(&ScheduledTransaction{\n\t\tId: transaction.Id,\n\t\tAmount: newAmount,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = logRepo.Create(&ScheduledTransactionLog{\n\t\tScheduledTransactionId: transaction.Id,\n\t\tAmount: params.Amount,\n\t\tCreatedAt: &params.Now,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (api *APIServer) integrationPost(w http.ResponseWriter, r *http.Request) {\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tlines := strings.Split(string(body), \"\\n\")\n\tif len(lines) < 2 {\n\t\thttp.Error(w, \"use TSVWithNames format\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tcolumns := strings.Split(lines[1], \"\\t\")\n\tcommands := strings.Split(columns[0], \" \")\n\tlog.Println(commands)\n\n\tswitch commands[0] {\n\tcase \"create\", \"upload\", \"download\":\n\t\tif locked := api.lock.TryAcquire(1); !locked {\n\t\t\tlog.Println(ErrAPILocked)\n\t\t\thttp.Error(w, ErrAPILocked.Error(), http.StatusLocked)\n\t\t\treturn\n\t\t}\n\t\tdefer api.lock.Release(1)\n\t\tstart := time.Now()\n\t\tapi.metrics.LastBackupStart.Set(float64(start.Unix()))\n\t\tdefer api.metrics.LastBackupDuration.Set(float64(time.Since(start).Nanoseconds()))\n\t\tdefer api.metrics.LastBackupEnd.Set(float64(time.Now().Unix()))\n\n\t\tgo func() {\n\t\t\tapi.status.start(columns[0])\n\t\t\terr := api.c.Run(append([]string{\"clickhouse-backup\"}, commands...))\n\t\t\tdefer api.status.stop(err)\n\t\t\tif err != nil {\n\t\t\t\tapi.metrics.FailedBackups.Inc()\n\t\t\t\tapi.metrics.LastBackupSuccess.Set(0)\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}()\n\t\tapi.metrics.SuccessfulBackups.Inc()\n\t\tapi.metrics.LastBackupSuccess.Set(1)\n\t\tfmt.Fprintln(w, \"acknowledged\")\n\t\treturn\n\tcase \"delete\", \"freeze\", \"clean\":\n\t\tif locked := api.lock.TryAcquire(1); !locked {\n\t\t\tlog.Println(ErrAPILocked)\n\t\t\thttp.Error(w, ErrAPILocked.Error(), http.StatusLocked)\n\t\t\treturn\n\t\t}\n\t\tdefer api.lock.Release(1)\n\t\tstart := time.Now()\n\t\tapi.metrics.LastBackupStart.Set(float64(start.Unix()))\n\t\tdefer api.metrics.LastBackupDuration.Set(float64(time.Since(start).Nanoseconds()))\n\t\tdefer api.metrics.LastBackupEnd.Set(float64(time.Now().Unix()))\n\n\t\tapi.status.start(columns[0])\n\t\terr := api.c.Run(append([]string{\"clickhouse-backup\"}, commands...))\n\t\tdefer api.status.stop(err)\n\t\tif err != nil {\n\t\t\tapi.metrics.FailedBackups.Inc()\n\t\t\tapi.metrics.LastBackupSuccess.Set(0)\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t\tapi.metrics.SuccessfulBackups.Inc()\n\t\tapi.metrics.LastBackupSuccess.Set(1)\n\t\tfmt.Fprintln(w, \"OK\")\n\t\tlog.Println(\"OK\")\n\t\treturn\n\tdefault:\n\t\thttp.Error(w, fmt.Sprintf(\"bad operation '%s'\", columns[0]), http.StatusBadRequest)\n\t}\n}", "func NewBackupBackend(b *APIBackend) *BackupBackend {\n\treturn &BackupBackend{\n\t\tLogger: b.Logger.With(zap.String(\"handler\", \"backup\")),\n\n\t\tHTTPErrorHandler: b.HTTPErrorHandler,\n\t\tBackupService: b.BackupService,\n\t\tSqlBackupRestoreService: b.SqlBackupRestoreService,\n\t\tBucketManifestWriter: b.BucketManifestWriter,\n\t}\n}", "func Backup(ns string, pod string, s string) (err error) {\n\tcmdName := \"unwritten\"\n\tcmdArgs := []string{\"backup\"}\n\tcmdTimeout := time.Duration(maxApplyTimeout) * time.Second\n\terr = RunCommand(cmdName, cmdArgs, cmdTimeout)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (client *KeyVaultClient) backupSecretCreateRequest(ctx context.Context, vaultBaseURL string, secretName string, options *KeyVaultClientBackupSecretOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/secrets/{secret-name}/backup\"\n\tif secretName == \"\" {\n\t\treturn nil, errors.New(\"parameter secretName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{secret-name}\", url.PathEscape(secretName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"7.2\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (c *Client) scheduleSubmit(r *Request) {\n\tc.requests = append(c.requests, r)\n}", "func SaveBackup(rootname string) (string, error) {\n\tt0 := time.Now()\n\tfname := rootname\n\tif util.Blank(fname) {\n\t\tfname = \"Backup_\" + t0.Format(\"2006-01-02-15-04-05\")\n\t}\n\tfn := backupfolder + fname + \".dat\"\n\tdblock.Lock()\n\tdefer dblock.Unlock()\n\terr := write_file(db, fn)\n\ttelp := time.Now().Sub(t0).Seconds() * 1000.0\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to write backup file. Err=%v\", err)\n\t\tlog.Errorf(\"Name of backup file: %s\", fn)\n\t\treturn fname, fmt.Errorf(\"Unalble to write backup file. Err=%v\", err)\n\t} else {\n\t\tlog.Infof(\"Backup file (%s) written to disk. (%8.2f ms)\", fn, telp)\n\t}\n\treturn fname, nil\n}", "func (client CloudEndpointsClient) PostBackupPreparer(ctx context.Context, resourceGroupName string, storageSyncServiceName string, syncGroupName string, cloudEndpointName string, parameters BackupRequest) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"cloudEndpointName\": autorest.Encode(\"path\", cloudEndpointName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"storageSyncServiceName\": autorest.Encode(\"path\", storageSyncServiceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t\t\"syncGroupName\": autorest.Encode(\"path\", syncGroupName),\n\t}\n\n\tconst APIVersion = \"2020-03-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/syncGroups/{syncGroupName}/cloudEndpoints/{cloudEndpointName}/postbackup\", pathParameters),\n\t\tautorest.WithJSON(parameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (database *Database) Backup(reason string) error {\n\n\terr := os.MkdirAll(backupsDir, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tname := \"testing\"\n\tfilename := fmt.Sprintf(\"%s/%s_%s_%s.db\",\n\t\tbackupsDir, strings.Replace(name, \" \", \"_\", -1),\n\t\ttime.Now().Format(\"20060102150405\"), reason)\n\n\tsrc, err := os.Open(database.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer src.Close()\n\n\tdest, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer dest.Close()\n\n\tif _, err := io.Copy(dest, src); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *mutationResolver) BackupDatabase(ctx context.Context, input models.BackupDatabaseInput) (*models.BackupDatabasePayload, error) {\n\tret := new(models.BackupDatabasePayload)\n\tret.ClientMutationID = input.ClientMutationID\n\terr := verifyAdminToken(input.AdminToken)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tvar compress bool\n\tif input.Compress != nil && *input.Compress {\n\t\tcompress = true\n\t}\n\n\tvar fullPath = path.Join(DataPath, \"backup\", time.Now().Format(\"csheet-20060102-150405.bak\"))\n\tif compress {\n\t\tfullPath += \".gz\"\n\t}\n\terr = os.MkdirAll(path.Dir(fullPath), 0700)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tf, err := os.Create(fullPath)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tdefer f.Close()\n\n\tvar w io.Writer = f\n\tif compress {\n\t\tvar zw = gzip.NewWriter(w)\n\t\tdefer zw.Close()\n\t\tw = zw\n\t}\n\t_, err = db.Backup(w, 0)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tret.Created = new(deprecated.DiskFile)\n\tret.Created.Path = fullPath\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tret.Created.ModTime = fi.ModTime()\n\tret.Created.Size = fi.Size()\n\treturn ret, err\n}", "func (self *Tree) BackupToDisk(t time.Time) (error, *BackupQuery) {\n\n\tfmt.Println(\"STARTING FILE DUMP\", t)\n\t_, _, _, _, _, qhour, _, _, _ := self.When(t)\n\tq := &BackupQuery{\n\t\ttree: self,\n\t\tencname: fmt.Sprintf(\n\t\t\t\"%d_%02d_%02d_%02d_\",\n\t\t\tt.Year(),\n\t\t\tint(t.Month()),\n\t\t\tt.Day(),\n\t\t\tt.Hour(),\n\t\t),\n\t}\n\treturn q.Do(qhour, nil), q\n}", "func StartBackup() {\n\tfor {\n\t\tRunOnce()\n\t\t// sleep to tomorrow night\n\t\tsleep()\n\t}\n}", "func CreateBackupFromRequest(backupName string, orgID string, request *api.BackupCreateRequest) (err error) {\n\t//ctx, err := backup.GetPxCentralAdminCtx()\n\tctx, err := backup.GetAdminCtxFromSecret()\n\texpect(err).NotTo(haveOccurred(),\n\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\", err))\n\tbackupDriver := Inst().Backup\n\t_, err = backupDriver.CreateBackup(ctx, request)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Failed to create backup [%s] in org [%s]. Error: [%v]\",\n\t\t\tbackupName, orgID, err)\n\t}\n\treturn err\n}", "func (c *ClientSet) CreateSchedule(ns, period string, count int) (string, v1.BackupPhase, error) {\n\tvar status v1.BackupPhase\n\tsnapVolume := true\n\n\tsname, err := c.generateScheduleName()\n\tif err != nil {\n\t\treturn \"\", status, err\n\t}\n\n\tsched := &v1.Schedule{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: sname,\n\t\t\tNamespace: VeleroNamespace,\n\t\t},\n\t\tSpec: v1.ScheduleSpec{\n\t\t\tTemplate: v1.BackupSpec{\n\t\t\t\tIncludedNamespaces: []string{ns},\n\t\t\t\tSnapshotVolumes: &snapVolume,\n\t\t\t\tStorageLocation: BackupLocation,\n\t\t\t\tVolumeSnapshotLocations: []string{SnapshotLocation},\n\t\t\t},\n\t\t\tSchedule: period,\n\t\t},\n\t}\n\to, err := c.VeleroV1().\n\t\tSchedules(VeleroNamespace).\n\t\tCreate(context.TODO(), sched, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn \"\", status, err\n\t}\n\n\tif count < 0 {\n\t\treturn o.Name, status, nil\n\t}\n\tif status, err = c.waitForScheduleCompletion(o.Name, count); err == nil {\n\t\treturn o.Name, status, nil\n\t}\n\treturn o.Name, status, err\n}", "func CreateBackupGetErr(backupName string, clusterName string, bLocation string, bLocationUID string,\n\tnamespaces []string, labelSelectors map[string]string, orgID string) (err error) {\n\n\tStep(fmt.Sprintf(\"Create backup [%s] in org [%s] from cluster [%s]\",\n\t\tbackupName, orgID, clusterName), func() {\n\n\t\tbackupDriver := Inst().Backup\n\t\tbkpCreateRequest := &api.BackupCreateRequest{\n\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\tName: backupName,\n\t\t\t\tOrgId: orgID,\n\t\t\t},\n\t\t\tBackupLocationRef: &api.ObjectRef{\n\t\t\t\tName: bLocation,\n\t\t\t\tUid: bLocationUID,\n\t\t\t},\n\t\t\tCluster: sourceClusterName,\n\t\t\tNamespaces: namespaces,\n\t\t\tLabelSelectors: labelSelectors,\n\t\t}\n\t\t//ctx, err := backup.GetPxCentralAdminCtx()\n\t\tctx, err := backup.GetAdminCtxFromSecret()\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\terr))\n\t\t_, err = backupDriver.CreateBackup(ctx, bkpCreateRequest)\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Failed to create backup [%s] in org [%s]. Error: [%v]\",\n\t\t\t\tbackupName, orgID, err)\n\t\t}\n\t})\n\n\treturn err\n}", "func (t BackupJob) Run() {\n\n\tparms, err := GetBackupJobParms(t.Logger)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tparms.CCP_IMAGE_TAG = t.CCP_IMAGE_TAG\n\n\tvar s = getBackupJobTemplate(t.Logger)\n\tvar pv = getBackupJobPVTemplate(t.Logger)\n\tvar pvc = getBackupJobPVCTemplate(t.Logger)\n\n\ttmpl, err := template.New(\"jobtemplate\").Parse(s)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttmplpv, err := template.New(\"pvtemplate\").Parse(pv)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttmplpvc, err := template.New(\"pvctemplate\").Parse(pvc)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar tmpfile, tmpfilePV, tmpfilePVC *os.File\n\ttmpfile, err = ioutil.TempFile(\"/tmp\", \"backupjob\")\n\tif err != nil {\n\t\tt.Logger.Println(err.Error())\n\t\tpanic(err)\n\t}\n\ttmpfilePV, err = ioutil.TempFile(\"/tmp\", \"backupjobpv\")\n\tif err != nil {\n\t\tt.Logger.Println(err.Error())\n\t\tpanic(err)\n\t}\n\ttmpfilePVC, err = ioutil.TempFile(\"/tmp\", \"backupjobpvc\")\n\tif err != nil {\n\t\tt.Logger.Println(err.Error())\n\t\tpanic(err)\n\t}\n\n\terr = tmpl.Execute(tmpfile, parms)\n\n\tif err := tmpfile.Close(); err != nil {\n\t\tt.Logger.Println(err.Error())\n\t\tpanic(err)\n\t}\n\tt.Logger.Println(\"tmpfile is \" + tmpfile.Name())\n\n\terr = tmplpv.Execute(tmpfilePV, parms)\n\tif err := tmpfilePV.Close(); err != nil {\n\t\tt.Logger.Println(err.Error())\n\t\tpanic(err)\n\t}\n\tt.Logger.Println(\"tmpfilePV is \" + tmpfilePV.Name())\n\n\terr = tmplpvc.Execute(tmpfilePVC, parms)\n\tif err := tmpfilePVC.Close(); err != nil {\n\t\tt.Logger.Println(err.Error())\n\t\tpanic(err)\n\t}\n\tt.Logger.Println(\"tmpfilePVC is \" + tmpfilePVC.Name())\n\n\tvar stdout, stderr string\n\tstdout, stderr, err = createBackupJob(parms, tmpfile.Name(), tmpfilePV.Name(), tmpfilePVC.Name(), t.Cmd)\n\tif err != nil {\n\t\tt.Logger.Println(err.Error())\n\t}\n\tt.Logger.Println(stdout)\n\tt.Logger.Println(stderr)\n\n\t//defer os.Remove(tmpfile.Name()) //clean up\n\t//defer os.Remove(tmpfilePV.Name()) //clean up\n\t//defer os.Remove(tmpfilePVC.Name()) //clean up\n}", "func (r *Reconciler) reconcileScheduledBackups(\n\tctx context.Context, cluster *v1beta1.PostgresCluster, sa *corev1.ServiceAccount,\n\tcronjobs []*batchv1.CronJob,\n) bool {\n\tlog := logging.FromContext(ctx).WithValues(\"reconcileResource\", \"repoCronJob\")\n\t// requeue if there is an error during creation\n\tvar requeue bool\n\n\tfor _, repo := range cluster.Spec.Backups.PGBackRest.Repos {\n\t\t// if the repo level backup schedules block has not been created,\n\t\t// there are no schedules defined\n\t\tif repo.BackupSchedules != nil {\n\t\t\t// next if the repo level schedule is not nil, create the CronJob.\n\t\t\tif repo.BackupSchedules.Full != nil {\n\t\t\t\tif err := r.reconcilePGBackRestCronJob(ctx, cluster, repo,\n\t\t\t\t\tfull, repo.BackupSchedules.Full, sa, cronjobs); err != nil {\n\t\t\t\t\tlog.Error(err, \"unable to reconcile Full backup for \"+repo.Name)\n\t\t\t\t\trequeue = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif repo.BackupSchedules.Differential != nil {\n\t\t\t\tif err := r.reconcilePGBackRestCronJob(ctx, cluster, repo,\n\t\t\t\t\tdifferential, repo.BackupSchedules.Differential, sa, cronjobs); err != nil {\n\t\t\t\t\tlog.Error(err, \"unable to reconcile Differential backup for \"+repo.Name)\n\t\t\t\t\trequeue = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif repo.BackupSchedules.Incremental != nil {\n\t\t\t\tif err := r.reconcilePGBackRestCronJob(ctx, cluster, repo,\n\t\t\t\t\tincremental, repo.BackupSchedules.Incremental, sa, cronjobs); err != nil {\n\t\t\t\t\tlog.Error(err, \"unable to reconcile Incremental backup for \"+repo.Name)\n\t\t\t\t\trequeue = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn requeue\n}", "func (s *CreateFileSystemInput) SetBackup(v bool) *CreateFileSystemInput {\n\ts.Backup = &v\n\treturn s\n}", "func RestoreBackup(serviceID string, backupID string, settings *models.Settings) *models.Task {\n\tbackup := map[string]string{\n\t\t\"archiveType\": \"cf\",\n\t\t\"encryptionType\": \"aes\",\n\t}\n\tb, err := json.Marshal(backup)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(1)\n\t}\n\tresp := httpclient.Post(b, fmt.Sprintf(\"%s/v1/environments/%s/services/%s/restore/%s\", settings.PaasHost, settings.EnvironmentID, serviceID, backupID), true, settings)\n\tvar m map[string]string\n\tjson.Unmarshal(resp, &m)\n\treturn &models.Task{\n\t\tID: m[\"taskId\"],\n\t}\n}", "func (scheduleAPI *scheduleAPIServer) saveScheduleWorker() {\n\tfor {\n\t\tselect {\n\t\tcase <-scheduleAPI.ctx.Done():\n\t\t\treturn\n\t\tcase <-time.After(time.Duration(5 * time.Minute)):\n\t\t\tfunc() {\n\t\t\t\tf, err := os.OpenFile(\"snapshot\", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 066)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Log.Warn(\"error while saving file\", zap.Error(err))\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Lock the mutex\n\t\t\t\tscheduleAPI.muSchedule.Lock()\n\n\t\t\t\tbs, err := proto.Marshal(&scheduleAPI.weeklySchedule)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Log.Error(\"error while marshaling file\", zap.Error(err))\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Unlock the mutex\n\t\t\t\tscheduleAPI.muSchedule.Unlock()\n\n\t\t\t\t_, err = f.Write(bs)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogger.Log.Error(\"error while writing to file\", zap.Error(err))\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}()\n\t\t}\n\t}\n}", "func (client *WebAppsClient) backupSlotCreateRequest(ctx context.Context, resourceGroupName string, name string, slot string, request BackupRequest, options *WebAppsBackupSlotOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/slots/{slot}/backup\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif slot == \"\" {\n\t\treturn nil, errors.New(\"parameter slot cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{slot}\", url.PathEscape(slot))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, runtime.MarshalAsJSON(req, request)\n}", "func Start() {\n\tfor {\n\t\tlog.Println(\"Starting backup.\")\n\n\t\t// read the config file\n\t\tconfig, err := readConfigFile()\n\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\ttime.Sleep(retryPeriod)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar databases []*database.Database\n\n\t\t// add all databases to the databases slice\n\t\tfor _, name := range config.Databases {\n\t\t\tdatabases = append(databases, database.New(name))\n\t\t}\n\n\t\t// create a new temporary zip file\n\t\tfile, err := zipper.New()\n\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\ttime.Sleep(retryPeriod)\n\t\t\tcontinue\n\t\t}\n\n\t\t// go through the databases slice and dump the databases\n\t\tfor _, db := range databases {\n\t\t\terr = db.Dump()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// add the databases to the zip file\n\t\tif errs := file.Zip(databases); errs != nil {\n\t\t\tlog.Printf(\"Failed to zip the files. Error:%s\", err.Error())\n\t\t\ttime.Sleep(retryPeriod)\n\t\t\tcontinue\n\t\t}\n\n\t\t// close (save) the zip file\n\t\tif err = file.ZipFile.Close(); err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\ttime.Sleep(retryPeriod)\n\t\t\tcontinue\n\t\t}\n\n\t\t// upload the zip file\n\t\tif err = file.Upload(); err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\ttime.Sleep(retryPeriod)\n\t\t\tcontinue\n\t\t}\n\n\t\tstats := Stats{\n\t\t\tBackupTime: time.Now().UTC().Format(timeFormat),\n\t\t\tNextBackupTime: time.Now().UTC().Add(sleepPeriod).Format(timeFormat),\n\t\t\tSuccess: true,\n\t\t}\n\n\t\tif err = stats.store(); err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t}\n\n\t\tlog.Println(\"Backed up!\")\n\n\t\t// sleep for 24 hours\n\t\ttime.Sleep(sleepPeriod)\n\t}\n}", "func sqlBackup() {\n\tgodrv.Register(\"SET NAMES utf8\")\n\tdb, err := sql.Open(\"mysql\", fmt.Sprintf(\"%s:%s@tcp(%s:%s)/%s\", username, password, hostname, port, dbname))\n\tif err != nil {\n\t\tfmt.Println(\"Error opening database: \", err)\n\t\treturn\n\t}\n\n\tdefer db.Close()\n\n\trows, err := db.Query(\"Show databases;\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar name string\n\t\terr := rows.Scan(&name)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tif !contains(ingoreSqlTableList, name) {\n\t\t\tlog.Println(\"*******************\")\n\t\t\tlog.Println(name + \" is backuping\")\n\t\t\tdumpFilenameFormat := fmt.Sprintf(\"%s-20060102150405\", name)\n\t\t\tdumper, err := mysqldump.Register(db, backupSqlDir, dumpFilenameFormat)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error registering databse:\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tresultFilename, err := dumper.Dump()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error dumping:\", err)\n\t\t\t}\n\t\t\tlog.Println(name + \" is backuped\")\n\t\t\tlog.Printf(\"File is saved to %s \\n\", resultFilename)\n\t\t\tlog.Println(\"*******************\")\n\n\t\t\tdumper.Close()\n\t\t}\n\n\t}\n}", "func (b *BackuPOT) backup(localPath localPath, remotePath remotePath) error {\n if err := log.ValidateKey(log.Key(remotePath)); err != nil {\n return backupotDebug.Error(err)\n }\n // get file info\n dir, name := splitPath(localPath)\n //localPath = dir + \"/\" + name\n // compress and read the file\n buf, fileInfo, err := b.prepareFile(dir, name)\n if err != nil {\n return backupotDebug.Error(err)\n }\n if need, err := b.needBackup(remotePath, fileInfo); err != nil {\n return backupotDebug.Error(err)\n } else if !need {\n return backupotDebug.Error(errors.New(\"No need to backup. No change since last backup.\"))\n }\n // Put the file to teapot\n if err := b.putRemoteFile(remotePath, buf); err != nil {\n return backupotDebug.Error(err)\n }\n // Put fileInfo\n if err := b.putRemoteFileInfo(remotePath, fileInfo); err != nil {\n return backupotDebug.Error(err)\n }\n return nil\n}", "func (backupWrapper *v1BackupWrapper) setBackup(\n\tbackup *cstorapis.CStorBackup) *v1BackupWrapper {\n\tbackupWrapper.backup = backup\n\treturn backupWrapper\n}", "func (b BackupSchedule) Validate() error {\n\treturn validateBackupSchedule(&b).ToAggregate()\n}", "func NewAutoBackup(ctx *pulumi.Context,\n\tname string, args *AutoBackupArgs, opts ...pulumi.ResourceOption) (*AutoBackup, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.DiskId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'DiskId'\")\n\t}\n\tif args.Weekdays == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Weekdays'\")\n\t}\n\tvar resource AutoBackup\n\terr := ctx.RegisterResource(\"sakuracloud:index/autoBackup:AutoBackup\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (client *KeyVaultClient) fullBackupCreateRequest(ctx context.Context, vaultBaseURL string, options *KeyVaultClientBeginFullBackupOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/backup\"\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"7.2\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\tif options != nil && options.AzureStorageBlobContainerURI != nil {\n\t\treturn req, runtime.MarshalAsJSON(req, *options.AzureStorageBlobContainerURI)\n\t}\n\treturn req, nil\n}", "func (game *Game) Backup(turnNumber int, force bool) error {\n\tcurrent2hPath := game.TwohFile.Fullpath\n\n\ttarget2hPath, err := game.TwohFile.BackupFilepath(turnNumber)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcurrentTrnPath := game.TrnFile.Fullpath\n\n\ttargetTrnPath, err := game.TrnFile.BackupFilepath(turnNumber)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !force && (utility.FileExists(target2hPath) || utility.FileExists(targetTrnPath)) {\n\t\treturn errors.New(fmt.Sprintf(\"Backup for turn %v already exists in %v, not forcing\", turnNumber, game.Directory))\n\t}\n\n\terr = utility.Cp(current2hPath, target2hPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = utility.Cp(currentTrnPath, targetTrnPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func GetBackupCreateRequest(backupName string, clusterName string, bLocation string, bLocationUID string,\n\tnamespaces []string, labelSelectors map[string]string, orgID string) *api.BackupCreateRequest {\n\treturn &api.BackupCreateRequest{\n\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\tName: backupName,\n\t\t\tOrgId: orgID,\n\t\t},\n\t\tBackupLocationRef: &api.ObjectRef{\n\t\t\tName: bLocation,\n\t\t\tUid: bLocationUID,\n\t\t},\n\t\tCluster: clusterName,\n\t\tNamespaces: namespaces,\n\t\tLabelSelectors: labelSelectors,\n\t}\n}", "func handleABS(kubecli kubernetes.Interface, s *api.ABSBackupSource, sch api.BackupSchedule, endpoints []string, clientTLSSecret, namespace string) (*api.BackupStatus, error) {\n\tcli, err := absfactory.NewClientFromSecret(kubecli, namespace, s.ABSSecret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar tlsConfig *tls.Config\n\tif len(clientTLSSecret) != 0 {\n\t\td, err := k8sutil.GetTLSDataFromSecret(kubecli, namespace, clientTLSSecret)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get TLS data from secret (%v): %v\", clientTLSSecret, err)\n\t\t}\n\t\ttlsConfig, err = etcdutil.NewTLSConfig(d.CertData, d.KeyData, d.CAData)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to constructs tls config: %v\", err)\n\t\t}\n\t}\n\n\tbm := backup.NewBackupManagerFromWriter(kubecli, writer.NewABSWriter(cli.ABS), tlsConfig, endpoints, namespace)\n\tappendRev := false\n\tif sch.BackupIntervalInSecond > 0 {\n\t\tappendRev = true\n\t}\n\trev, etcdVersion, err := bm.SaveSnap(s.Path, appendRev)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to save snapshot (%v)\", err)\n\t}\n\n\terr = bm.PurgeBackup(s.Path, sch.MaxBackups)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to purge backups (%v)\", err)\n\t}\n\treturn &api.BackupStatus{EtcdVersion: etcdVersion, EtcdRevision: rev}, nil\n}", "func UpdateScheduledBackup(schedulePolicyName, schedulePolicyUID string, ScheduledBackupInterval time.Duration) (err error) {\n\tvar ctx context1.Context\n\n\tStep(fmt.Sprintf(\"Update schedule policy %s\", schedulePolicyName), func() {\n\t\tbackupDriver := Inst().Backup\n\n\t\t// Create a backup schedule\n\t\tschedulePolicyUpdateRequest := &api.SchedulePolicyUpdateRequest{\n\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\tName: schedulePolicyName,\n\t\t\t\tUid: schedulePolicyUID,\n\t\t\t\tOrgId: OrgID,\n\t\t\t},\n\n\t\t\tSchedulePolicy: &api.SchedulePolicyInfo{\n\t\t\t\tInterval: &api.SchedulePolicyInfo_IntervalPolicy{\n\t\t\t\t\t// Retain 5 backups at a time for ease of inspection\n\t\t\t\t\tRetain: 5,\n\t\t\t\t\tMinutes: int64(ScheduledBackupInterval / time.Minute),\n\t\t\t\t\tIncrementalCount: &api.SchedulePolicyInfo_IncrementalCount{\n\t\t\t\t\t\tCount: 0,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\t//ctx, err = backup.GetPxCentralAdminCtx()\n\t\tctx, err = backup.GetAdminCtxFromSecret()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t_, err = backupDriver.UpdateSchedulePolicy(ctx, schedulePolicyUpdateRequest)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t})\n\treturn err\n}", "func NewBackupScheduleReconciler(mgr manager.Manager) *BackupScheduleReconciler {\n\treturn &BackupScheduleReconciler{\n\t\tClient: mgr.GetClient(),\n\t\tLog: ctrl.Log.WithName(\"controllers\").WithName(\"BackupSchedule\"),\n\t\tscheme: mgr.GetScheme(),\n\t\tbackupScheduleCtrl: &realBackupScheduleControl{client: mgr.GetClient()},\n\t\tcronAnythingCtrl: &realCronAnythingControl{client: mgr.GetClient()},\n\t\tbackupCtrl: &realBackupControl{client: mgr.GetClient()},\n\t}\n}", "func (fbbsd FrequencyBasedBackupScheduleDescription) AsBackupScheduleDescription() (*BackupScheduleDescription, bool) {\n\treturn nil, false\n}", "func backupScheduleFound(repo v1beta1.PGBackRestRepo, backupType string) bool {\n\tif repo.BackupSchedules != nil {\n\t\tswitch backupType {\n\t\tcase full:\n\t\t\treturn repo.BackupSchedules.Full != nil\n\t\tcase differential:\n\t\t\treturn repo.BackupSchedules.Differential != nil\n\t\tcase incremental:\n\t\t\treturn repo.BackupSchedules.Incremental != nil\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\treturn false\n}", "func (client *CassandraClustersClient) getBackupCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, backupID string, options *CassandraClustersClientGetBackupOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/cassandraClusters/{clusterName}/backups/{backupId}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif clusterName == \"\" {\n\t\treturn nil, errors.New(\"parameter clusterName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{clusterName}\", url.PathEscape(clusterName))\n\tif backupID == \"\" {\n\t\treturn nil, errors.New(\"parameter backupID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{backupId}\", url.PathEscape(backupID))\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-03-15-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (w *Worker) doBackups(r *http.Request) *http.Response {\n\thosts := w.getAliveHosts(w.backup)\n\tif len(hosts) == 0 {\n\t\treturn nil\n\t}\n\n\tfor id, host := range hosts {\n\t\tvar req *http.Request\n\n\t\tif req = w.requestSetHost(host, r); req != nil {\n\t\t\tres, err := w.makeRequest(req)\n\n\t\t\tif err != nil && err != http_err {\n\t\t\t\tw.markHostBroken(TYPE_BACKUP, id)\n\t\t\t}\n\n\t\t\treturn res\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Client) Backup(fullName string) (string, error) {\n\tnewName := c.newFullName(fullName)\n\tif err := c.copyImage(fullName, newName); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn newName, nil\n}", "func (r *ReconcileVolumeBackup) requestCreate(snapshot *v1alpha1.VolumeSnapshot, instance *backupsv1alpha1.VolumeBackup) error {\n\tif err := controllerutil.SetControllerReference(instance, snapshot, r.scheme); err != nil {\n\t\tlog.Error(err, \"Unable to set owner reference of %v\", snapshot.Name)\n\t\treturn err\n\t}\n\n\t_, err := r.snapClientset.SnapshotV1alpha1().VolumeSnapshots(instance.Namespace).Create(snapshot)\n\tif err != nil {\n\t\tlog.Error(err, \"Error creating VolumeSnapshot\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func (tbbsd TimeBasedBackupScheduleDescription) AsBasicBackupScheduleDescription() (BasicBackupScheduleDescription, bool) {\n\treturn &tbbsd, true\n}", "func (client *BackupAndExportClient) validateBackupCreateRequest(ctx context.Context, resourceGroupName string, serverName string, options *BackupAndExportClientValidateBackupOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/flexibleServers/{serverName}/validateBackup\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif serverName == \"\" {\n\t\treturn nil, errors.New(\"parameter serverName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serverName}\", url.PathEscape(serverName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-09-30-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func NewCreateBackupPlanRequestWithoutParam() *CreateBackupPlanRequest {\n\n return &CreateBackupPlanRequest{\n JDCloudRequest: core.JDCloudRequest{\n URL: \"/regions/{regionId}/backupPlans\",\n Method: \"POST\",\n Header: nil,\n Version: \"v2\",\n },\n }\n}", "func (a *Client) CreateVolumeBackup(params *CreateVolumeBackupParams) (*CreateVolumeBackupOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewCreateVolumeBackupParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"CreateVolumeBackup\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/volumeBackups\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &CreateVolumeBackupReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*CreateVolumeBackupOK), nil\n\n}", "func RestoreBackup(dto *action_dtos.RestoreBackupDto, service *pgCommon.PostgresServiceInformations) error {\n\t_, err := service.PgoApi.RestoreBackup(&msgs.RestoreRequest{\n\t\tBackrestStorageType: \"s3\",\n\t\tNamespace: service.ClusterInstance.Namespace,\n\t\tFromCluster: dto.OldClusterName,\n\t})\n\n\tif err != nil {\n\t\tlogger.RError(err, \"Unable to progress restore backup action for \"+service.ClusterInstance.Name)\n\t}\n\n\treturn err\n}" ]
[ "0.68177533", "0.6513657", "0.6345432", "0.61539024", "0.6150429", "0.59448236", "0.59301215", "0.57305014", "0.567647", "0.56463933", "0.56347996", "0.55442417", "0.5516464", "0.5512978", "0.54288435", "0.54252183", "0.5423092", "0.53933567", "0.53620535", "0.5304515", "0.53024966", "0.5287012", "0.5274553", "0.5240257", "0.52125907", "0.5201263", "0.5197901", "0.5193865", "0.5190788", "0.51752067", "0.51659596", "0.5156838", "0.51544", "0.51497257", "0.5144454", "0.5130758", "0.5118629", "0.51069325", "0.51032394", "0.509765", "0.5095664", "0.5089121", "0.5045759", "0.5038492", "0.5031684", "0.50157404", "0.49964774", "0.49929613", "0.49886978", "0.4984478", "0.49727508", "0.49612388", "0.49432582", "0.49203804", "0.49145597", "0.48910302", "0.48842147", "0.48794314", "0.4859297", "0.4853696", "0.48391458", "0.48350975", "0.48336023", "0.48207933", "0.47995034", "0.47800428", "0.47796935", "0.47609758", "0.47550917", "0.4750218", "0.47475082", "0.474426", "0.47394803", "0.47359347", "0.47356698", "0.47129026", "0.47111207", "0.47100815", "0.46899512", "0.46878478", "0.46866283", "0.46765006", "0.4673488", "0.46702135", "0.46696153", "0.4666109", "0.46660882", "0.46615413", "0.46611732", "0.4658255", "0.4650289", "0.46458763", "0.46453506", "0.46369666", "0.4622272", "0.46214142", "0.46200666", "0.46130967", "0.4613006", "0.46083748" ]
0.78230155
0
GetUserList get user list from paas
func (m *publicUser) GetUserList(c *gin.Context) (int, interface{}) { user := plugins.CurrentPlugin(c, m.config.LoginVersion) userList, err := user.GetUserList(c, m.config.ConfigMap) rspBody := metadata.LonginSystemUserListResult{} if nil != err { rspBody.Code = common.CCErrCommHTTPDoRequestFailed rspBody.ErrMsg = err.Error() rspBody.Result = false } rspBody.Result = true rspBody.Data = userList return 200, rspBody }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetListUser(c *gin.Context) {\r\n\tvar usr []model.UserTemporary\r\n\tres := model.GetLUser(usr)\r\n\r\n\tutils.WrapAPIData(c, map[string]interface{}{\r\n\t\t\"Data\": res,\r\n\t}, http.StatusOK, \"success\")\r\n}", "func getUserList() string {\n\tvar userlist string\n\tfmt.Println(len(Users))\n\tfor key, value := range Users {\n\t\tfmt.Println(\"key\", key, \"value\", value)\n\t\tuserlist = userlist + key + \"|\"\n\n\t}\n\treturn strings.TrimRight(userlist, \"|\")\n}", "func (up *userProvider) List(ctx context.Context) ([]models.User, error) {\n\tusers, err := up.userStore.List(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn users, nil\n}", "func (s *initServer) GetUserList(ctx context.Context, in *pb.UserListRequest) (*pb.UserListResponse, error) {\t\n\treturn userListTempl(ctx, in, \"userList:user\", false)\n}", "func (s *Service) List(c context.Context, req *user.ListReq) (*user.ListResp, error) {\n\tif err := req.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tu := s.auth.GetUser(c)\n\n\tlimit, offset := query.Paginate(req.Limit, req.Page)\n\n\tusers, err := s.udb.List(\n\t\ts.dbcl.WithContext(c),\n\t\tquery.ForTenant(u, req.TenantId),\n\t\tlimit,\n\t\toffset,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pu []*user.Resp\n\tfor _, v := range users {\n\t\tpu = append(pu, v.Proto())\n\t}\n\n\treturn &user.ListResp{Users: pu}, nil\n}", "func (retUser) List(ctx context.Context, db *sqlx.DB) ([]User, error) {\n\tctx, span := global.Tracer(\"service\").Start(ctx, \"internal.data.retrieve.user.list\")\n\tdefer span.End()\n\n\tusers := []User{}\n\tconst q = `SELECT * FROM users`\n\n\tif err := db.SelectContext(ctx, &users, q); err != nil {\n\t\treturn nil, errors.Wrap(err, \"selecting users\")\n\t}\n\n\treturn users, nil\n}", "func (m *userManager) UserList() []string {\n\tuserList := make([]string, 0)\n\tm.db.View(func(tx *bolt.Tx) error {\n\t\tusers := tx.Bucket(m.usersBucket)\n\t\treturn users.ForEach(func(username, v []byte) error {\n\t\t\tuserList = append(userList, string(username))\n\t\t\treturn nil\n\t\t})\n\t})\n\treturn userList\n}", "func userList(w http.ResponseWriter, r *http.Request) {}", "func GetUserList(w http.ResponseWriter, r *http.Request) {\n\n\tusers, err := user.GetUserList(r)\n\n\tif err != nil {\n\t\thttpext.AbortAPI(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thttpext.SuccessDataAPI(w, \"Ok\", users)\n}", "func (UserService) List(ctx context.Context, gdto dto.GeneralListDto) ([]model.User, int64) {\n\tcols := \"*\"\n\tgdto.Q, cols = dataPermService.DataPermFilter(ctx, \"users\", gdto)\n\treturn userDao.List(gdto, cols)\n}", "func (u *User) List() ([]*UserListRes, error) {\n\tvar users []db.Users\n\tif err := u.Sess.Asc(\"id\").Find(&users); err != nil {\n\t\treturn nil, err\n\t}\n\tres := make([]*UserListRes, len(users))\n\tfor i := 0; i < len(users); i++ {\n\t\tuser := users[i]\n\t\tres[i] = &UserListRes{ID: user.Id, Name: user.Name}\n\t}\n\treturn res, nil\n}", "func (m *Mgr) list(ctx context.Context) (users []*User, err error) {\n\trows, err := m.db.QueryContext(ctx, `SELECT username, password FROM users`)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar u User\n\t\tif err = rows.Scan(&u.Username, &u.Password); err != nil {\n\t\t\treturn\n\t\t}\n\t\tusers = append(users, &u)\n\t}\n\treturn users, rows.Err()\n}", "func (us *UserService) List(p *Pagination) ([]User, error) {\n\treturn us.Datasource.List(p)\n}", "func (us UserService) List(dto dto.GeneralListDto) ([]model.User, int64) {\n\treturn userDao.List(dto)\n}", "func (m *Mgr) List(ctx context.Context) ([]*User, error) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\tusers, err := m.list(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// hide passwords\n\tfor _, u := range users {\n\t\tu.Password = \"\"\n\t}\n\treturn users, nil\n}", "func (r *UserRead) list(q *msg.Request, mr *msg.Result) {\n\tvar (\n\t\tuserID, userName string\n\t\trows *sql.Rows\n\t\terr error\n\t)\n\n\tif rows, err = r.stmtList.Query(); err != nil {\n\t\tmr.ServerError(err, q.Section)\n\t\treturn\n\t}\n\n\tfor rows.Next() {\n\t\tif err = rows.Scan(\n\t\t\t&userID,\n\t\t\t&userName,\n\t\t); err != nil {\n\t\t\trows.Close()\n\t\t\tmr.ServerError(err, q.Section)\n\t\t\treturn\n\t\t}\n\t\tmr.User = append(mr.User, proto.User{\n\t\t\tID: userID,\n\t\t\tUserName: userName,\n\t\t})\n\t}\n\tif err = rows.Err(); err != nil {\n\t\tmr.ServerError(err, q.Section)\n\t\treturn\n\t}\n\tmr.OK()\n}", "func (u *UserServiceHandler) List(ctx context.Context) ([]User, error) {\n\n\turi := \"/v1/user/list\"\n\n\treq, err := u.client.NewRequest(ctx, http.MethodGet, uri, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar users []User\n\terr = u.client.DoWithContext(ctx, req, &users)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn users, nil\n}", "func (h *User) List(w http.ResponseWriter, r *http.Request) {\n\tlimit, offset := utils.GetPaginationParams(r.URL.Query())\n\tresp, err := h.Storage.GetUserList(limit, offset)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tR.JSON500(w)\n\t\treturn\n\t}\n\n\tif len(resp) < 1 {\n\t\tR.JSON404(w)\n\t\treturn\n\t}\n\n\tR.JSON200(w, resp)\n}", "func (h *ServiceUsersHandler) List(ctx context.Context, project, serviceName string) ([]*ServiceUser, error) {\n\t// Aiven API does not provide list operation for service users, need to get them via service info instead\n\tservice, err := h.client.Services.Get(ctx, project, serviceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn service.Users, nil\n}", "func (c *UsersClient) List(ctx context.Context, filter string) (*[]models.User, int, error) {\n\tparams := url.Values{}\n\tif filter != \"\" {\n\t\tparams.Add(\"$filter\", filter)\n\t}\n\tresp, status, _, err := c.BaseClient.Get(ctx, base.GetHttpRequestInput{\n\t\tValidStatusCodes: []int{http.StatusOK},\n\t\tUri: base.Uri{\n\t\t\tEntity: \"/users\",\n\t\t\tParams: params,\n\t\t\tHasTenantId: true,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, status, err\n\t}\n\tdefer resp.Body.Close()\n\trespBody, _ := ioutil.ReadAll(resp.Body)\n\tvar data struct {\n\t\tUsers []models.User `json:\"value\"`\n\t}\n\tif err := json.Unmarshal(respBody, &data); err != nil {\n\t\treturn nil, status, err\n\t}\n\treturn &data.Users, status, nil\n}", "func (u *UserService) List(ctx context.Context) ([]*User, *http.Response, error) {\n\treq, err := u.client.newRequest(\"GET\", \"user.list\", nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar users []*User\n\tresp, err := u.client.do(ctx, req, &users)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn users, resp, nil\n}", "func (remoteAccessVpnUserApi *RemoteAccessVpnUserApi) List() ([]RemoteAccessVpnUser, error) {\n\tdata, err := remoteAccessVpnUserApi.entityService.List(map[string]string{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn parseRemoteAccessVpnUserList(data), nil\n}", "func (service Service) GetList(pagination entity.Pagination) (ug []entity.UserGroup, count int, err error) {\n\tusers, count, err := service.repository.GetList(pagination)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tug, err = service.mapUsersToUserGroups(users)\n\treturn\n}", "func List(ctx echo.Context) error {\n\tvar res []*userResponse\n\terr := db.Model(&User{}).Where(\"type = ?\", ctx.QueryParams().Get(\"type\")).Scan(&res).Error\n\tif err != nil {\n\t\treturn ctx.JSON(http.StatusBadRequest, &response{Code: 1})\n\t}\n\treturn ctx.JSON(http.StatusOK, &response{\n\t\tCode: 0,\n\t\tData: res,\n\t})\n}", "func (s *UserServer) List(ctx context.Context, in *pb.UserQuery) (*pb.UsersInfo, error) {\n\tvar err error\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tutils.GetLog().Error(\"rpc.user.List error: %+v\", err)\n\t\t}\n\t}()\n\n\tconfig := &users.Config{\n\t\tPageNum: int(in.Num),\n\t\tPageSize: int(in.Size),\n\t\tSearch: in.Search,\n\t\tIDs: in.IDs,\n\t}\n\n\tusers := users.NewUsers(config)\n\tif err = users.Do(); err != nil {\n\t\treturn nil, errors.New(users.ErrorCode().String())\n\t}\n\n\tsrvUsers := users.Users()\n\tcount := users.Count()\n\n\tvar pbUsers []*pb.UserInfo\n\tfor _, srvUser := range srvUsers {\n\t\tpbUser := srvUserToPbUser(srvUser)\n\t\tpbUsers = append(pbUsers, pbUser)\n\t}\n\n\treturn &pb.UsersInfo{Users: pbUsers, TotalNum: count}, nil\n}", "func (m *manager) List(ctx context.Context, query *q.Query) (models.Users, error) {\n\tquery = q.MustClone(query)\n\tif query.Sorting == \"\" {\n\t\tquery.Sorting = \"username\"\n\t}\n\n\texcludeAdmin := true\n\tfor key := range query.Keywords {\n\t\tstr := strings.ToLower(key)\n\t\tif str == \"user_id__in\" {\n\t\t\texcludeAdmin = false\n\t\t\tbreak\n\t\t} else if str == \"user_id\" {\n\t\t\texcludeAdmin = false\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif excludeAdmin {\n\t\t// Exclude admin account when not filter by UserIDs, see https://github.com/goharbor/harbor/issues/2527\n\t\tquery.Keywords[\"user_id__gt\"] = 1\n\t}\n\n\treturn m.dao.List(ctx, query)\n}", "func (us *UserService) List(ctx context.Context) ([]*resources.User, error) {\n\tdoc, err := us.list(ctx, \"one.userpool.info\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\telements := doc.FindElements(\"USER_POOL/USER\")\n\n\tusers := make([]*resources.User, len(elements))\n\tfor i, e := range elements {\n\t\tusers[i] = resources.CreateUserFromXML(e)\n\t}\n\n\treturn users, nil\n}", "func listUser(ctx sdk.Context, k Keeper) ([]byte, error) {\n\tvar userList []types.User\n\tstore := ctx.KVStore(k.storeKey)\n\titerator := sdk.KVStorePrefixIterator(store, []byte(types.UserPrefix))\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tvar user types.User\n\t\tk.cdc.MustUnmarshalBinaryLengthPrefixed(store.Get(iterator.Key()), &user)\n\t\tuserList = append(userList, user)\n\t}\n\tres := codec.MustMarshalJSONIndent(k.cdc, userList)\n\treturn res, nil\n}", "func GetUsers(req *http.Request, render render.Render, account services.Account) {\n qs := req.URL.Query()\n userIDs := qs[\"userId\"]\n var users []models.User\n for _, userID := range userIDs {\n if user, err := account.GetUser(userID); err != nil {\n render.JSON(err.HttpCode, err)\n return\n } else {\n users = append(users, *user)\n }\n }\n render.JSON(http.StatusOK, users)\n}", "func ListUser(email, password string) []User {\n\tvar u []User\n\tDb.Find(&u)\n\treturn u\n}", "func (db *MySQLDB) ListUser(ctx context.Context, request *helper.PageRequest) ([]*User, *helper.Page, error) {\n\tfLog := mysqlLog.WithField(\"func\", \"ListUser\").WithField(\"RequestID\", ctx.Value(constants.RequestID))\n\tcount, err := db.Count(ctx)\n\tif err != nil {\n\t\tfLog.Errorf(\"db.Count got %s\", err.Error())\n\t\treturn nil, nil, err\n\t}\n\tpage := helper.NewPage(request, uint(count))\n\tuserList := make([]*User, 0)\n\n\tvar OrderBy string\n\tswitch strings.ToUpper(request.OrderBy) {\n\tcase \"EMAIL\":\n\t\tOrderBy = \"EMAIL\"\n\tcase \"ENABLED\":\n\t\tOrderBy = \"ENABLED\"\n\tcase \"SUSPENDED\":\n\t\tOrderBy = \"SUSPENDED\"\n\tcase \"LAST_SEEN\":\n\t\tOrderBy = \"LAST_SEEN\"\n\tcase \"LAST_LOGIN\":\n\t\tOrderBy = \"LAST_LOGIN\"\n\tdefault:\n\t\tOrderBy = \"EMAIL\"\n\t}\n\n\tq := fmt.Sprintf(\"SELECT REC_ID, EMAIL,HASHED_PASSPHRASE,ENABLED, SUSPENDED,LAST_SEEN,LAST_LOGIN,FAIL_COUNT,ACTIVATION_CODE,ACTIVATION_DATE,TOTP_KEY,ENABLE_2FE,TOKEN_2FE,RECOVERY_CODE FROM HANSIP_USER ORDER BY %s %s LIMIT %d, %d\", OrderBy, request.Sort, page.OffsetStart, page.OffsetEnd-page.OffsetStart)\n\trows, err := db.instance.QueryContext(ctx, q)\n\tif err != nil {\n\t\tfLog.Errorf(\"db.instance.QueryContext got %s. SQL = %s\", err.Error(), q)\n\t\treturn nil, nil, &ErrDBQueryError{\n\t\t\tWrapped: err,\n\t\t\tMessage: \"Error ListUser\",\n\t\t\tSQL: q,\n\t\t}\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tuser := &User{}\n\t\tvar enabled, suspended, enable2fa int\n\t\terr := rows.Scan(&user.RecID, &user.Email, &user.HashedPassphrase, &enabled, &suspended, &user.LastSeen, &user.LastLogin, &user.FailCount, &user.ActivationCode,\n\t\t\t&user.ActivationDate, &user.UserTotpSecretKey, &enable2fa, &user.Token2FA, &user.RecoveryCode)\n\t\tif err != nil {\n\t\t\tfLog.Warnf(\"rows.Scan got %s\", err.Error())\n\t\t\treturn nil, nil, &ErrDBScanError{\n\t\t\t\tWrapped: err,\n\t\t\t\tMessage: \"Error ListUser\",\n\t\t\t\tSQL: q,\n\t\t\t}\n\t\t} else {\n\t\t\tif enabled == 1 {\n\t\t\t\tuser.Enabled = true\n\t\t\t}\n\t\t\tif suspended == 1 {\n\t\t\t\tuser.Suspended = true\n\t\t\t}\n\t\t\tif enable2fa == 1 {\n\t\t\t\tuser.Enable2FactorAuth = true\n\t\t\t}\n\t\t\tuserList = append(userList, user)\n\t\t}\n\t}\n\treturn userList, page, nil\n}", "func (r repository) List(ctx context.Context, list *ListUsersRequest) ([]model.User, error) {\n\tusers := make([]model.User, 0)\n\toffset := (list.Page - 1) * list.Limit\n\terr := r.db.Select(&users, ListUsersSQL, offset, list.Limit)\n\tif err != nil {\n\t\tr.logger.Errorf(\"Failed to select users %s\", err)\n\t\treturn nil, err\n\t}\n\treturn users, nil\n}", "func UserListAll(w http.ResponseWriter, r *http.Request) {\n\n\tvar err error\n\tvar pageSize int\n\tvar paginatedUsers auth.PaginatedUsers\n\n\t// Init output\n\toutput := []byte(\"\")\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\trefRoles := gorillaContext.Get(r, \"auth_roles\").([]string)\n\n\t// Grab url path variables\n\turlValues := r.URL.Query()\n\tpageToken := urlValues.Get(\"pageToken\")\n\tstrPageSize := urlValues.Get(\"pageSize\")\n\tprojectName := urlValues.Get(\"project\")\n\tprojectUUID := \"\"\n\n\tif projectName != \"\" {\n\t\tprojectUUID = projects.GetUUIDByName(projectName, refStr)\n\t\tif projectUUID == \"\" {\n\t\t\terr := APIErrorNotFound(\"ProjectUUID\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif strPageSize != \"\" {\n\t\tif pageSize, err = strconv.Atoi(strPageSize); err != nil {\n\t\t\tlog.Errorf(\"Pagesize %v produced an error while being converted to int: %v\", strPageSize, err.Error())\n\t\t\terr := APIErrorInvalidData(\"Invalid page size\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// check that user is indeed a service admin in order to be priviledged to see full user info\n\tpriviledged := auth.IsServiceAdmin(refRoles)\n\n\t// Get Results Object - call is always priviledged because this handler is only accessible by service admins\n\tif paginatedUsers, err = auth.PaginatedFindUsers(pageToken, int32(pageSize), projectUUID, priviledged, refStr); err != nil {\n\t\terr := APIErrorInvalidData(\"Invalid page token\")\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := paginatedUsers.ExportJSON()\n\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\toutput = []byte(resJSON)\n\trespondOK(w, output)\n\n}", "func ListUser(url, token string) {\n\tres, err := handleReadRequest(url, http.MethodGet, token)\n\tif err != nil {\n\t\tfmt.Println(\"Error\\n\")\n\t}\n\n\tvar apiResponse ListUsers\n\terr = json.Unmarshal(res, &apiResponse)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Print(\"List of users:\\n\")\n\tfor i:=0; i < len(apiResponse.Users); i++ {\n\t\tfmt.Print(apiResponse.Users[i],\"\\n\")\n\t}\n}", "func (s *initServer) GetUserListFilter(ctx context.Context, in *pb.UserListRequest) (*pb.UserListResponse, error) {\t\n\treturn userListTempl(ctx, in, \"userListFilter:user\", true)\n}", "func (s *UserServiceImpl) ListUser(c *gin.Context) ([]*models.User, error) {\n\tdb := c.MustGet(\"db\").(*gorm.DB)\n\tusers := []*models.User{}\n\terr := db.Find(&users).Error\n\treturn users, err\n}", "func (u *User) List(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\tctx, span := trace.StartSpan(ctx, \"handlers.User.List\")\n\tdefer span.End()\n\n\tusers, err := user.List(ctx, u.db)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn web.Respond(ctx, w, users, http.StatusOK)\n}", "func (r mysqlRepo) GetUserList(ctx context.Context, page, perpage int) (data []User, total int, err error) {\n\tusers := make([]User, 0)\n\toffset := (page - 1) * perpage\n\tquery := \"SELECT id, username, email, created_at, updated_at FROM users limit ?,?\"\n\n\terr = r.db.Select(&users, query, offset, perpage)\n\tif err != nil {\n\t\tr.logger.Errorf(\"failed to get list of users %s\", err)\n\t\treturn\n\t}\n\n\treturn users, len(users), nil\n}", "func getUser(c *fiber.Ctx) error {\n\tUserscollection := mg.Db.Collection(\"users\")\n\tListscollection := mg.Db.Collection(\"lists\")\n\tusername := c.Params(\"name\")\n\tuserQuery := bson.D{{Key: \"username\", Value: username}}\n\n\tuserRecord := Userscollection.FindOne(c.Context(), &userQuery)\n\tuser := &User{}\n\tuserRecord.Decode(&user)\n\tif len(user.ID) < 1 {\n\t\treturn c.Status(404).SendString(\"cant find user\")\n\t}\n\tlistQuery := bson.D{{Key: \"userid\", Value: user.Username}}\n\tcursor, err := Listscollection.Find(c.Context(), &listQuery)\n\tif err != nil {\n\t\treturn c.Status(500).SendString(err.Error())\n\t}\n\tvar lists []List = make([]List, 0)\n\tif err := cursor.All(c.Context(), &lists); err != nil {\n\t\treturn c.Status(500).SendString(\"internal err\")\n\t}\n\tuser.Password = \"\"\n\tuser.TaskCode = \"\"\n\treturn c.Status(200).JSON(&fiber.Map{\n\t\t\"user\": user,\n\t\t\"lists\": lists,\n\t})\n}", "func userListTempl(ctx context.Context, in *pb.UserListRequest, id string, f bool) (*pb.UserListResponse, error) {\n\tresp := getUserListResp(ctx)\n\n\tc := newConn(id)\n\tu := pbUser.NewUserServiceClient(c)\n\tdefer c.Close()\n\n\tcode, err := handleAuthCheck(ctx, u); \n\tif err != nil {\n\t\treturn resp(nil, err.Error(), code)\n\t}\n\n\tres, err := u.UserList(ctx, &pbUser.UserListRequest{\n\t\tList: in.GetList(),\n\t\tOffset: in.GetOffset(),\n\t\tFilter: f,\n\t\tValue: in.GetValue(),\n\t})\n\n\tif err != nil {\n\t\treturn resp(nil, err.Error(), \"400\")\n\t}\n\n\tvar users []*pb.Users\n\tvar wg sync.WaitGroup\n\n\tfor _, el := range res.GetUsers() {\n\t\twg.Add(1)\n\t\tgo func(item *pbUser.Users) {\n\t\t\tusers = append(users, &pb.Users{\n\t\t\t\tName: item.GetName(),\n\t\t\t\tEmail: item.GetEmail(),\n\t\t\t\tUuid: item.GetUuid(),\n\t\t\t\tId: item.GetId(),\n\t\t\t})\n\t\t\twg.Done()\n\t\t}(el)\n\t}\n\twg.Wait()\n\t\n\treturn resp(users, res.Message, res.Code)\n}", "func (c client) UserList() ([]*User, error) {\n\tdata := url.Values{}\n\tdata.Set(\"token\", c.conf.Token)\n\tres, err := http.PostForm(\"https://slack.com/api/users.list\", data)\n\tif err != nil {\n\t\treturn []*User{}, err\n\t}\n\tdefer res.Body.Close()\n\n\tvar list userlist\n\tif err = json.NewDecoder(res.Body).Decode(&list); err != nil {\n\t\treturn []*User{}, err\n\t}\n\treturn list.Members, nil\n}", "func listUsersPartial(client *Client) ([]interface{}, error) {\n\treturn client.GetItemListInterfaceArray(\"/access/users\")\n}", "func (pool *Pool) GetUserList() []string {\n\tpool.mu.Lock()\n\tusernames := make([]string, 0)\n\n\tfor client := range pool.Clients {\n\t\tusernames = append(usernames, client.Account.Username)\n\t}\n\n\tpool.mu.Unlock()\n\treturn usernames\n}", "func (rep *UserRepo) List(ctx context.Context) ([]*User, error) {\n\tu := []*User{}\n\terr := rep.db.Query(\n\t\tctx,\n\t\trep.db.Select(\"*\").From(rep.table()),\n\t).Decode(&u)\n\treturn u, err\n}", "func (s repoUserService) List(path string) ([]*api.User, error) {\n\trepoPath, err := api.NewRepoPath(path)\n\tif err != nil {\n\t\treturn nil, errio.Error(err)\n\t}\n\n\tusers, err := s.client.httpClient.ListRepoUsers(repoPath.GetNamespaceAndRepoName())\n\tif err != nil {\n\t\treturn nil, errio.Error(err)\n\t}\n\n\treturn users, nil\n}", "func (c *DefaultIdentityProvider) ListUsers(ctx context.Context, options *metainternal.ListOptions) (*auth.UserList, error) {\n\tkeyword := \"\"\n\tlimit := 50\n\tif options.FieldSelector != nil {\n\t\tkeyword, _ = options.FieldSelector.RequiresExactMatch(auth.KeywordQueryTag)\n\t\tlimitStr, _ := options.FieldSelector.RequiresExactMatch(auth.QueryLimitTag)\n\t\tif li, err := strconv.Atoi(limitStr); err == nil && li > 0 {\n\t\t\tlimit = li\n\t\t}\n\t}\n\n\t_, tenantID := authentication.GetUsernameAndTenantID(ctx)\n\tif tenantID != \"\" && tenantID != c.tenantID {\n\t\treturn nil, apierrors.NewBadRequest(\"must in the same tenant\")\n\t}\n\n\tallList, err := c.localIdentityLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar localIdentityList []*authv1.LocalIdentity\n\tfor i, item := range allList {\n\t\tif item.Spec.TenantID == c.tenantID {\n\t\t\tlocalIdentityList = append(localIdentityList, allList[i])\n\t\t}\n\t}\n\n\tif keyword != \"\" {\n\t\tvar newList []*authv1.LocalIdentity\n\t\tfor i, val := range localIdentityList {\n\t\t\tif strings.Contains(val.Name, keyword) || strings.Contains(val.Spec.Username, keyword) || strings.Contains(val.Spec.DisplayName, keyword) {\n\t\t\t\tnewList = append(newList, localIdentityList[i])\n\t\t\t}\n\t\t}\n\t\tlocalIdentityList = newList\n\t}\n\n\titems := localIdentityList[0:min(len(localIdentityList), limit)]\n\n\tuserList := auth.UserList{}\n\tfor _, item := range items {\n\t\tuser := convertToUser(item)\n\t\tuserList.Items = append(userList.Items, user)\n\t}\n\n\treturn &userList, nil\n}", "func (cs *UserService) List() ([]UsersResponse, error) {\n\n\treq, err := cs.client.NewRequest(\"GET\", \"/users\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := cs.client.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif err := validateResponse(resp); err != nil {\n\t\treturn nil, err\n\t}\n\n\tbodyBytes, _ := ioutil.ReadAll(resp.Body)\n\tbodyString := string(bodyBytes)\n\n\tu := &listUsersJSONResponse{}\n\terr = json.Unmarshal([]byte(bodyString), &u)\n\n\treturn u.Users, err\n}", "func (h UserHTTP) List(w http.ResponseWriter, r *http.Request) {\n\tlistRequest := listRequestDecoder(r)\n\tusers, err := h.svc.ListUsers(r.Context(), listRequest)\n\tif err != nil {\n\t\th.logger.With(r.Context()).Errorf(\"list users error : %s\", err)\n\t\trender.Render(w, r, e.BadRequest(err, \"bad request\"))\n\t\treturn\n\t}\n\trender.Respond(w, r, users)\n}", "func (cli *OpsGenieUserV2Client) List(req userv2.ListUsersRequest) (*userv2.ListUsersResponse, error) {\n\tvar response userv2.ListUsersResponse\n\terr := cli.sendGetRequest(&req, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &response, nil\n}", "func (s *Database) ListUser() ([]*UserPartner, error) {\n\tvar users []*UserPartner\n\terr := s.Engine.Desc(\"id\").Find(&users)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(users) == 0 {\n\t\treturn nil, errors.New(\"Database rong\")\n\t}\n\treturn users, nil\n}", "func listUsers(client *chef.Client, filters ...string) map[string]string {\n\tvar filter string\n\tif len(filters) > 0 {\n\t\tfilter = filters[0]\n\t}\n\tuserList, err := client.Users.List(filter)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"Issue listing users:\", err)\n\t}\n\treturn userList\n}", "func List(w http.ResponseWriter, r *http.Request) {\n\tauthUser, err := auth.GetUserFromJWT(w, r)\n\tif err != nil {\n\t\tresponse.FormatStandardResponse(false, \"error-auth\", \"\", err.Error(), w)\n\t\treturn\n\t}\n\n\tlistHandler(w, authUser, false)\n}", "func List(ctx context.Context, dbConn *db.DB) ([]User, error) {\n\tu := []User{}\n\n\tf := func(collection *mgo.Collection) error {\n\t\treturn collection.Find(nil).All(&u)\n\t}\n\tif err := dbConn.MGOExecute(ctx, usersCollection, f); err != nil {\n\t\treturn nil, errors.Wrap(err, \"db.users.find()\")\n\t}\n\n\treturn u, nil\n}", "func ListUser(ctx context.Context, tx *sql.Tx, request *models.ListUserRequest) (response *models.ListUserResponse, err error) {\n\tvar rows *sql.Rows\n\tqb := &common.ListQueryBuilder{}\n\tqb.Auth = common.GetAuthCTX(ctx)\n\tspec := request.Spec\n\tqb.Spec = spec\n\tqb.Table = \"user\"\n\tqb.Fields = UserFields\n\tqb.RefFields = UserRefFields\n\tqb.BackRefFields = UserBackRefFields\n\tresult := []*models.User{}\n\n\tif spec.ParentFQName != nil {\n\t\tparentMetaData, err := common.GetMetaData(tx, \"\", spec.ParentFQName)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"can't find parents\")\n\t\t}\n\t\tspec.Filters = common.AppendFilter(spec.Filters, \"parent_uuid\", parentMetaData.UUID)\n\t}\n\n\tquery := qb.BuildQuery()\n\tcolumns := qb.Columns\n\tvalues := qb.Values\n\tlog.WithFields(log.Fields{\n\t\t\"listSpec\": spec,\n\t\t\"query\": query,\n\t}).Debug(\"select query\")\n\trows, err = tx.QueryContext(ctx, query, values...)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"select query failed\")\n\t}\n\tdefer rows.Close()\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"row error\")\n\t}\n\n\tfor rows.Next() {\n\t\tvaluesMap := map[string]interface{}{}\n\t\tvalues := make([]interface{}, len(columns))\n\t\tvaluesPointers := make([]interface{}, len(columns))\n\t\tfor _, index := range columns {\n\t\t\tvaluesPointers[index] = &values[index]\n\t\t}\n\t\tif err := rows.Scan(valuesPointers...); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"scan failed\")\n\t\t}\n\t\tfor column, index := range columns {\n\t\t\tval := valuesPointers[index].(*interface{})\n\t\t\tvaluesMap[column] = *val\n\t\t}\n\t\tm, err := scanUser(valuesMap)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"scan row failed\")\n\t\t}\n\t\tresult = append(result, m)\n\t}\n\tresponse = &models.ListUserResponse{\n\t\tUsers: result,\n\t}\n\treturn response, nil\n}", "func (s *UsersService) List(opt *UsersOptions) ([]User, *http.Response, error) {\n\turi, err := addOptions(\"users\", opt)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tusers := new(Users)\n\tres, err := s.client.Get(uri, users)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\n\treturn users.Users, res, err\n}", "func (a *API) listUsers(w http.ResponseWriter, req *http.Request) {\n\tvar (\n\t\tpath string\n\t\tusers cmap.ConcurrentMap\n\t\twg sync.WaitGroup\n\t)\n\t// Force reload policy to get the newest\n\t_ = a.policyEngine.LoadPolicy()\n\tif username := req.FormValue(\"name\"); username != \"\" {\n\t\tpath = common.Path(model.DefaultUsersPrefix, common.Hash(username, crypto.MD5))\n\t} else {\n\t\tpath = common.Path(model.DefaultUsersPrefix)\n\t}\n\tresp, err := a.etcdcli.DoGet(path, etcdv3.WithPrefix(),\n\t\tetcdv3.WithSort(etcdv3.SortByKey, etcdv3.SortAscend))\n\tif err != nil {\n\t\ta.respondError(w, apiError{\n\t\t\tcode: http.StatusInternalServerError,\n\t\t\terr: err,\n\t\t})\n\t\treturn\n\t}\n\tusers = cmap.New()\n\tfor _, ev := range resp.Kvs {\n\t\twg.Add(1)\n\t\tgo func(evv []byte) {\n\t\t\tdefer wg.Done()\n\t\t\tvar (\n\t\t\t\tu model.User\n\t\t\t\tp [][]string\n\t\t\t)\n\t\t\t_ = json.Unmarshal(evv, &u)\n\t\t\tp = a.policyEngine.GetFilteredPolicy(0, u.Username)\n\t\t\tfor i, v := range p {\n\t\t\t\t// The first element is username, so just remove it.\n\t\t\t\tp[i] = v[1:]\n\t\t\t}\n\t\t\tusers.Set(u.Username, p)\n\t\t}(ev.Value)\n\t}\n\twg.Wait()\n\ta.respondSuccess(w, http.StatusOK, users)\n}", "func ListAllUsers(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, \"Mohomaaf ...dsb\", nil, nil)\n\t\t}\n\t}()\n\n\tfLog := userMgmtLogger.WithField(\"func\", \"ListAllUsers\").WithField(\"RequestID\", r.Context().Value(constants.RequestID)).WithField(\"path\", r.URL.Path).WithField(\"method\", r.Method)\n\n\tiauthctx := r.Context().Value(constants.HansipAuthentication)\n\tif iauthctx == nil {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusUnauthorized, \"You are not authorized to access this resource\", nil, nil)\n\t\treturn\n\t}\n\n\tfLog.Trace(\"Listing Users\")\n\tpageRequest, err := helper.NewPageRequestFromRequest(r)\n\tif err != nil {\n\t\tfLog.Errorf(\"helper.NewPageRequestFromRequest got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tusers, page, err := UserRepo.ListUser(r.Context(), pageRequest)\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.ListUser got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tsusers := make([]*SimpleUser, len(users))\n\tfor i, v := range users {\n\t\tsusers[i] = &SimpleUser{\n\t\t\tRecID: v.RecID,\n\t\t\tEmail: v.Email,\n\t\t\tEnabled: v.Enabled,\n\t\t\tSuspended: v.Suspended,\n\t\t}\n\t}\n\tret := make(map[string]interface{})\n\tret[\"users\"] = susers\n\tret[\"page\"] = page\n\thelper.WriteHTTPResponse(r.Context(), w, http.StatusOK, \"List of all user paginated\", nil, ret)\n}", "func GetPropiedadesByUser(c *gin.Context) {\n\tvar prop []Models.Propiedad\n\tparams, ok := c.Request.URL.Query()[\"userId\"]\n\n\tif(!ok){\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"error\" : gin.H { \n\t\t\t\"status\": http.StatusBadRequest,\n\t\t\t\"message\": \"Invalid param\",\n\t\t}})\n\t\tc.AbortWithStatus(http.StatusBadRequest)\n\t}\n\terr := Models.GetAllPropiedadesByUser(&prop, string(params[0]))\n\tif (err != nil || !ok ) {\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\" : gin.H { \n\t\t\t\"status\": http.StatusNotFound,\n\t\t\t\"message\": err.Error(),\n\t\t}})\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tfmt.Println(c.Request.URL.Query())\n\t\t page, _ := strconv.Atoi(c.DefaultQuery(\"page\", \"1\"))\n\t\t limit, _ := strconv.Atoi(c.DefaultQuery(\"limit\", \"15\"))\n\t\n\t\t paginator := pagination.Paging(&pagination.Param{\n\t\t\tDB: Config.DB.Model(&prop).Preload(\"SharedAreas\").Select(\"*\").Joins(\"inner join PropiedadUsuario on PropiedadUsuario.propiedad_id = Propiedades.id\").Where(\"PropiedadUsuario.user_id = ?\", params).Find(&prop),\n\t\t\tPage: page,\n\t\t\tLimit: limit,\n\t\t\tOrderBy: []string{\"id\"},\n\t\t\tShowSQL: true,\n\t\t}, &prop)\n\t\tc.JSON(http.StatusOK, paginator)\n\t}\n}", "func (c *Client) ListUser(ctx context.Context, path string) (*http.Response, error) {\n\tvar body io.Reader\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"https\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"GET\", u.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\theader := req.Header\n\theader.Set(\"Content-Type\", \"application/json\")\n\tc.SignerJWT.Sign(ctx, req)\n\treturn c.Client.Do(ctx, req)\n}", "func (srv *UsersService) ListHandler(ctx *gin.Context) {\n\tlogger := srv.logger.New(\"action\", \"ListHandler\")\n\n\tcurrentUser := GetCurrentUser(ctx)\n\n\tlimitQuery := ctx.DefaultQuery(\"limit\", \"10\")\n\tpageQuery := ctx.DefaultQuery(\"page\", \"1\")\n\tparams := ctx.Request.URL.Query()\n\n\tvar adminsRoleIncluded = false\n\n\troles := params[\"filter[role_name]\"]\n\tif len(roles) > 0 {\n\t\tfor key, role := range roles {\n\t\t\t// remove root from role names if user is not root\n\t\t\t// only root can see root users\n\t\t\tif role == models.RoleRoot && currentUser.RoleName != models.RoleRoot {\n\t\t\t\tcopy(roles[key:], roles[key+1:])\n\t\t\t\troles[len(roles)-1] = \"\"\n\t\t\t\troles = roles[:len(roles)-1]\n\t\t\t}\n\t\t\tif role == models.RoleRoot || role == models.RoleAdmin {\n\t\t\t\tadminsRoleIncluded = true\n\t\t\t}\n\t\t}\n\t} else {\n\t\tadminsRoleIncluded = true\n\t}\n\n\tvar hasPerm bool\n\tif adminsRoleIncluded {\n\t\thasPerm = srv.PermissionsService.CanViewAdminProfile(currentUser.UID)\n\t} else {\n\t\thasPerm = srv.PermissionsService.CanViewUserProfile(currentUser.UID)\n\t}\n\n\tif !hasPerm {\n\t\tsrv.ResponseService.Forbidden(ctx)\n\t\treturn\n\t}\n\n\tquery := srv.Repository.GetUsersRepository().Filter(params)\n\n\tpagination, err := srv.Repository.GetUsersRepository().Paginate(query, pageQuery, limitQuery, serializers.NewUsers())\n\tif err != nil {\n\t\tlogger.Error(\"сan't load list of user\", \"error\", err)\n\t\t// Returns a \"400 StatusBadRequest\" response\n\t\tsrv.ResponseService.Error(ctx, responses.CannotRetrieveCollection, \"Can't load list of users\")\n\t\treturn\n\t}\n\n\t// Returns a \"200 OK\" response\n\tsrv.ResponseService.OkResponse(ctx, pagination)\n}", "func (t *CassandraUpgradeTest) listUsers() ([]string, error) {\n\tr, err := http.Get(fmt.Sprintf(\"http://%s/list\", net.JoinHostPort(t.ip, \"8080\")))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Body.Close()\n\tif r.StatusCode != http.StatusOK {\n\t\tb, err := io.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, fmt.Errorf(string(b))\n\t}\n\tvar names []string\n\tif err := json.NewDecoder(r.Body).Decode(&names); err != nil {\n\t\treturn nil, err\n\t}\n\treturn names, nil\n}", "func (e Endpoints) ListUsers(ctx context.Context, token string, args map[string]string) (users []registry.User, err error) {\n\trequest := ListUsersRequest{\n\t\tArgs: args,\n\t\tToken: token,\n\t}\n\tresponse, err := e.ListUsersEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn response.(ListUsersResponse).Users, response.(ListUsersResponse).Err\n}", "func (s *Service) List() *ListOp {\n\treturn &ListOp{\n\t\tCredential: s.credential,\n\t\tMethod: \"GET\",\n\t\tPath: \"users\",\n\t\tAccept: \"application/json\",\n\t\tQueryOpts: make(url.Values),\n\t\tVersion: esign.APIv21,\n\t}\n}", "func (c *Client) ListUsers() ([]User, error) {\n\tusers := []User{}\n\t_, err := c.sling.Get(\"users\").ReceiveSuccess(&users)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn users, nil\n}", "func (m *TestTooDB) ListUser(ctx context.Context) []*app.User {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"user\", \"listuser\"}, time.Now())\n\n\tvar native []*TestToo\n\tvar objs []*app.User\n\terr := m.Db.Scopes().Table(m.TableName()).Find(&native).Error\n\n\tif err != nil {\n\t\tgoa.LogError(ctx, \"error listing TestToo\", \"error\", err.Error())\n\t\treturn objs\n\t}\n\n\tfor _, t := range native {\n\t\tobjs = append(objs, t.TestTooToUser())\n\t}\n\n\treturn objs\n}", "func getUsers(types int) {\n\treq, _ := http.NewRequest(\"GET\", cfg.Main.Server+\"users\", nil)\n\treq.Header.Set(\"Content-Type\", \"application/xml\")\n\treq.Header.Set(\"Authorization\", cfg.Main.Key)\n\tclient := &http.Client{}\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\tp(\"Couldn't connect to Openfire server: %s\", err.Error())\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != 200 {\n\t\tp(\"Error requesting userlist from the server.\")\n\t\treturn\n\t}\n\tbody, _ := ioutil.ReadAll(res.Body)\n\tvar users XMLUsers\n\txml.Unmarshal(body, &users)\n\tfor _, e := range users.User {\n\t\tn := e.Username + \",\"\n\t\tif e.Name != \"\" {\n\t\t\tn = e.Username + \",\" + e.Name\n\t\t}\n\t\tswitch types {\n\t\tcase 0:\n\t\t\tm := \"<missing e-mail>\"\n\t\t\tif e.Email != \"\" {\n\t\t\t\tm = e.Email\n\t\t\t}\n\t\t\tp(\"%s,%s\", n, m)\n\t\tcase 1:\n\t\t\tif e.Email != \"\" {\n\t\t\t\tp(\"%s,%s\", n, e.Email)\n\t\t\t}\n\t\tcase 2:\n\t\t\tif e.Email == \"\" {\n\t\t\t\tp(\"%s\", n)\n\t\t\t}\n\t\t}\n\t}\n}", "func (db *Database) GetUsersList() ([]*User, error) {\n\trows, err := db.db.Query(`\n\t\tSELECT id, username, owner FROM melodious.accounts WHERE banned=false;\n\t`)\n\tif err != nil {\n\t\treturn []*User{}, err\n\t}\n\tusers := []*User{}\n\tfor rows.Next() {\n\t\tuser := &User{}\n\t\terr := rows.Scan(&(user.ID), &(user.Username), &(user.Owner))\n\t\tif err != nil {\n\t\t\treturn []*User{}, err\n\t\t}\n\t\tusers = append(users, user)\n\t}\n\treturn users, nil\n}", "func (store *Storage) ListUsers() ([]string, error) {\n\treturn store.Back.ListUsers()\n}", "func (a *Server) ListUsers(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"lists all users\")\n}", "func (c *UsersController) List(ctx *app.ListUsersContext) error {\n\t// UsersController_List: start_implement\n\n\t// Put your logic here\n\tusers, err := models.UserList(c.db, ctx.Offset, ctx.Limit)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn ctx.InternalServerError(goa.ErrInternal(ErrInternalServerError))\n\t}\n\n\tres := app.UserCollection{}\n\n\tfor _, user := range users {\n\t\tuserMedia := &app.User{\n\t\t\tID: user.ID,\n\t\t\tScreenName: user.ScreenName,\n\t\t\tCreatedAt: user.CreatedAt.Unix(),\n\t\t\tUpdatedAt: user.UpdatedAt.Unix(),\n\t\t}\n\t\tres = append(res, userMedia)\n\t}\n\n\treturn ctx.OK(res)\n\t// UsersController_List: end_implement\n}", "func GetUsers(c *gin.Context) {\n\tdb := dbConn()\n\tselDB, err := db.Query(\"CALL read_users()\")\n\tif err != nil {\n\t\tpanic(err.Error)\n\t}\n\n\tuser := User{}\n\tusers := []User{}\n\tfor selDB.Next() {\n\t\tvar id, username, useremail, fname, lname, password, passwordchange, passwordexpired, lastlogon, accountlocked string\n\t\terr = selDB.Scan(&id, &username, &useremail, &fname, &lname, &password, &passwordchange, &passwordexpired, &lastlogon, &accountlocked)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tc.JSON(500, gin.H{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t}\n\t\tuser.ID = id\n\t\tuser.UserName = username\n\t\tuser.UserEmail = useremail\n\t\tuser.FName = fname\n\t\tuser.LName = lname\n\t\tuser.Password = password\n\t\tuser.PasswordChange = passwordchange\n\t\tuser.PasswordExpired = passwordexpired\n\t\tuser.LastLogon = lastlogon\n\t\tuser.AccountLocked = accountlocked\n\t\tiid, err := strconv.Atoi(id)\n\t\tif err != nil {\n\t\t\tpanic(err.Error)\n\t\t}\n\t\tselDB02, err := db.Query(\"CALL read_access_userid(?)\", iid)\n\t\tif err != nil {\n\t\t\tpanic(err.Error)\n\t\t}\n\t\taccess := Access{}\n\t\taccessList := []Access{}\n\t\tfor selDB02.Next() {\n\t\t\tvar accessid, userid, courtid, caseaccess, personaccess, accountingaccess, juryaccess, attorneyaccess, configaccess, securitylevel, sealedcase string\n\t\t\terr := selDB02.Scan(&accessid, &userid, &courtid, &caseaccess, &personaccess, &accountingaccess, &juryaccess, &attorneyaccess, &configaccess, &securitylevel, &sealedcase)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tc.JSON(500, gin.H{\n\t\t\t\t\t\"error\": err.Error(),\n\t\t\t\t})\n\t\t\t}\n\t\t\taccess.AccessID = accessid\n\t\t\taccess.IDUser = userid\n\t\t\taccess.IDCourt = courtid\n\t\t\taccess.CaseAccess = caseaccess\n\t\t\taccess.PersonAccess = personaccess\n\t\t\taccess.AccountingAccess = accountingaccess\n\t\t\taccess.JuryAccess = juryaccess\n\t\t\taccess.AttorneyAccess = attorneyaccess\n\t\t\taccess.ConfigAccess = configaccess\n\t\t\taccess.SecurityLevel = securitylevel\n\t\t\taccess.SealedCase = sealedcase\n\t\t\taccessList = append(accessList, access)\n\t\t}\n\t\tuser.AccessList = accessList\n\t\tusers = append(users, user)\n\t}\n\n\tc.JSON(200, gin.H{\n\t\t\"result\": users,\n\t})\n\n\tdefer db.Close()\n}", "func (u *UserModel) List(limit int, offset int, order string) ([]*models.User, error) {\n\torderOpts := map[string]string{\n\t\t\"firstName\": \"first_name\",\n\t\t\"lastName\": \"last_name\",\n\t\t\"email\": \"email\",\n\t\t\"created\": \"created\",\n\t\t\"status\": \"s.name\",\n\t}\n\n\tif val, ok := orderOpts[order]; ok {\n\t\torder = val\n\t} else {\n\t\torder = \"created\"\n\t}\n\n\tstmt := fmt.Sprintf(`SELECT u.id, u.uuid, first_name, last_name, email, phone, s.slug, u.created\n\t\t\t FROM user AS u\n\t\t LEFT JOIN ref_user_status AS s ON u.status_id = s.id\n\t\t ORDER BY %s\n\t\t\t LIMIT ?,?`, order)\n\n\tif limit < 1 {\n\t\tlimit = DEFAULT_LIMIT\n\t}\n\n\trows, err := u.DB.Query(stmt, offset, limit)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tusers := []*models.User{}\n\n\tfor rows.Next() {\n\t\tu := &models.User{}\n\t\terr = rows.Scan(&u.ID, &u.UUID, &u.FirstName, &u.LastName, &u.Email, &u.Phone, &u.Status, &u.Created)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tusers = append(users, u)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn users, nil\n}", "func GetList(tx *sql.Tx) (list []Info, err error) {\n\tmapper := rlt.NewAccountMapper(tx)\n\trows, err := mapper.FindAccountAll()\n\tfor _, row := range rows {\n\t\tinfo := Info{}\n\t\tinfo.ID = row.ID\n\t\tinfo.Domain = row.Domain.String\n\t\tinfo.UserName = row.UserName\n\t\tinfo.DisplayName = row.DisplayName\n\t\tinfo.Email = row.Email\n\t\tlist = append(list, info) //数据写入\n\t}\n\treturn list, err\n}", "func getUser(client *chef.Client, name string) chef.User {\n\tuserList, err := client.Users.Get(name)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"Issue listing user\", err)\n\t}\n\treturn userList\n}", "func (objectSet *UserObjectSet) GetObjectListFromParams(params *param.GetParams) ([]*nimbleos.User, error) {\n\tuserObjectSetResp, err := objectSet.Client.ListFromParams(userPath, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buildUserObjectSet(userObjectSetResp), err\n}", "func UserListByToken(w http.ResponseWriter, r *http.Request) {\n\n\t// Init output\n\toutput := []byte(\"\")\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab url path variables\n\turlVars := mux.Vars(r)\n\turlToken := urlVars[\"token\"]\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\n\t// Get Results Object\n\tresult, err := auth.GetUserByToken(urlToken, refStr)\n\n\tif err != nil {\n\t\tif err.Error() == \"not found\" {\n\t\t\terr := APIErrorNotFound(\"User\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t\terr := APIErrQueryDatastore()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := result.ExportJSON()\n\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\toutput = []byte(resJSON)\n\trespondOK(w, output)\n\n}", "func (v UsersResource) List(c buffalo.Context) error {\n\t// Get the DB connection from the context\n\ttx, ok := c.Value(\"tx\").(*pop.Connection)\n\tif !ok {\n\t\treturn errors.WithStack(errors.New(\"no transaction found\"))\n\t}\n\n\tusers := &models.Users{}\n\n\t// Paginate results. Params \"page\" and \"per_page\" control pagination.\n\t// Default values are \"page=1\" and \"per_page=20\".\n\tq := tx.PaginateFromParams(c.Params())\n\n\t// Retrieve all Users from the DB\n\tif err := q.All(users); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\treturn c.Render(200, r.JSON(users))\n}", "func ShowCurrentUserList() {\n\tul := &define.UserList\n\tShowUserList(ul)\n}", "func (r *V1Alpha1PermissionManagerUser) List() ([]User, error) {\n\t//noinspection GoPreferNilSlice\n\tusers := []User{}\n\n\trawResponse, err := r.kubeclient.Discovery().RESTClient().Get().AbsPath(v1alpha1.ResourceURL).DoRaw(r.context)\n\n\tif err != nil {\n\t\tlog.Print(\"Failed to get users from k8s CRUD api\", err)\n\t\treturn []User{}, err\n\t}\n\n\t// generated from the api-server JSON response, most of the fields are not used but useful as documentation\n\tvar getAllUserResponse v1alpha1.PermissionManagerUserList\n\terr = json.Unmarshal(rawResponse, &getAllUserResponse)\n\n\tif err != nil {\n\t\tlog.Print(\"Failed to decode users from k8s CRUD api\", err)\n\t\treturn []User{}, err\n\t}\n\n\tfor _, v := range getAllUserResponse.Items {\n\t\tusers = append(users, User{Name: v.Spec.Name})\n\t}\n\n\treturn users, nil\n}", "func DefaultListUserInfo(ctx context.Context, db *gorm.DB) ([]*UserInfo, error) {\n\tin := UserInfo{}\n\tormObj, err := in.ToORM(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif hook, ok := interface{}(&ormObj).(UserInfoORMWithBeforeListApplyQuery); ok {\n\t\tif db, err = hook.BeforeListApplyQuery(ctx, db); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tdb, err = gorm1.ApplyCollectionOperators(ctx, db, &UserInfoORM{}, &UserInfo{}, nil, nil, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif hook, ok := interface{}(&ormObj).(UserInfoORMWithBeforeListFind); ok {\n\t\tif db, err = hook.BeforeListFind(ctx, db); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tdb = db.Where(&ormObj)\n\tdb = db.Order(\"id\")\n\tormResponse := []UserInfoORM{}\n\tif err := db.Find(&ormResponse).Error; err != nil {\n\t\treturn nil, err\n\t}\n\tif hook, ok := interface{}(&ormObj).(UserInfoORMWithAfterListFind); ok {\n\t\tif err = hook.AfterListFind(ctx, db, &ormResponse); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tpbResponse := []*UserInfo{}\n\tfor _, responseEntry := range ormResponse {\n\t\ttemp, err := responseEntry.ToPB(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpbResponse = append(pbResponse, &temp)\n\t}\n\treturn pbResponse, nil\n}", "func (v UsersResource) List(c buffalo.Context) error {\n\t// Get the DB connection from the context\n\ttx, ok := c.Value(\"tx\").(*pop.Connection)\n\tif !ok {\n\t\treturn fmt.Errorf(\"no transaction found\")\n\t}\n\n\tusers := &models.Users{}\n\n\t// Paginate results. Params \"page\" and \"per_page\" control pagination.\n\t// Default values are \"page=1\" and \"per_page=20\".\n\tq := tx.PaginateFromParams(c.Params())\n\n\t// Retrieve all Users from the DB\n\tif err := q.All(users); err != nil {\n\t\treturn err\n\t}\n\n\t// Add the paginator to the context so it can be used in the template.\n\tc.Set(\"pagination\", q.Paginator)\n\n\treturn c.Render(http.StatusOK, r.Auto(c, users))\n}", "func (s *UsersService) ListWithFilter(opt *UserListFilterOptions) ([]User, *Response, error) {\n\tvar u string\n\tvar err error\n\n\tpagesRetreived := 0\n\n\tif opt.NextURL != nil {\n\t\tu = opt.NextURL.String()\n\t} else {\n\t\tif opt.EmailEqualTo != \"\" {\n\t\t\topt.FilterString = appendToFilterString(opt.FilterString, profileEmailFilter, FilterEqualOperator, opt.EmailEqualTo)\n\t\t}\n\t\tif opt.LoginEqualTo != \"\" {\n\t\t\topt.FilterString = appendToFilterString(opt.FilterString, profileLoginFilter, FilterEqualOperator, opt.LoginEqualTo)\n\t\t}\n\n\t\tif opt.StatusEqualTo != \"\" {\n\t\t\topt.FilterString = appendToFilterString(opt.FilterString, profileStatusFilter, FilterEqualOperator, opt.StatusEqualTo)\n\t\t}\n\n\t\tif opt.IDEqualTo != \"\" {\n\t\t\topt.FilterString = appendToFilterString(opt.FilterString, profileIDFilter, FilterEqualOperator, opt.IDEqualTo)\n\t\t}\n\n\t\tif opt.FirstNameEqualTo != \"\" {\n\t\t\topt.FilterString = appendToFilterString(opt.FilterString, profileFirstNameFilter, FilterEqualOperator, opt.FirstNameEqualTo)\n\t\t}\n\n\t\tif opt.LastNameEqualTo != \"\" {\n\t\t\topt.FilterString = appendToFilterString(opt.FilterString, profileLastNameFilter, FilterEqualOperator, opt.LastNameEqualTo)\n\t\t}\n\n\t\t// API documenation says you can search with \"starts with\" but these don't work\n\t\t// if opt.FirstNameStartsWith != \"\" {\n\t\t// \topt.FilterString = appendToFilterString(opt.FilterString, profileFirstNameFilter, filterStartsWithOperator, opt.FirstNameStartsWith)\n\t\t// }\n\n\t\t// if opt.LastNameStartsWith != \"\" {\n\t\t// \topt.FilterString = appendToFilterString(opt.FilterString, profileLastNameFilter, filterStartsWithOperator, opt.LastNameStartsWith)\n\t\t// }\n\n\t\tif !opt.LastUpdated.Value.IsZero() {\n\t\t\topt.FilterString = appendToFilterString(opt.FilterString, profileLastUpdatedFilter, opt.LastUpdated.Operator, opt.LastUpdated.Value.UTC().Format(oktaFilterTimeFormat))\n\t\t}\n\n\t\tif opt.Limit == 0 {\n\t\t\topt.Limit = defaultLimit\n\t\t}\n\n\t\tu, err = addOptions(\"users\", opt)\n\n\t}\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tusers := make([]User, 1)\n\tresp, err := s.client.Do(req, &users)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\tpagesRetreived++\n\n\tif (opt.NumberOfPages > 0 && pagesRetreived < opt.NumberOfPages) || opt.GetAllPages {\n\n\t\tfor {\n\n\t\t\tif pagesRetreived == opt.NumberOfPages {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif resp.NextURL != nil {\n\t\t\t\tvar userPage []User\n\t\t\t\tpageOption := new(UserListFilterOptions)\n\t\t\t\tpageOption.NextURL = resp.NextURL\n\t\t\t\tpageOption.NumberOfPages = 1\n\t\t\t\tpageOption.Limit = opt.Limit\n\n\t\t\t\tuserPage, resp, err = s.ListWithFilter(pageOption)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn users, resp, err\n\t\t\t\t}\n\t\t\t\tusers = append(users, userPage...)\n\t\t\t\tpagesRetreived++\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn users, resp, err\n}", "func GetUsers(c *gin.Context) {\n\tvar user []Models.User\n\tvar u Models.User\n\terr := Models.GetAllUsers(&user)\n\tif err != nil {\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"error\" : gin.H { \n\t\t\t\"status\": http.StatusNotFound,\n\t\t\t\"message\": err.Error(),\n\t\t}})\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tlog.Println(\"====== Bind By Query String ======\")\n\t\tlog.Println(u.Nombre)\n\t\t//var rubro []Models.RubroUsuario\n\t \n\t\tfmt.Println(c.Request.URL.Query())\n\t\t page, _ := strconv.Atoi(c.DefaultQuery(\"page\", \"1\"))\n\t\t limit, _ := strconv.Atoi(c.DefaultQuery(\"limit\", \"50\"))\n\t\n\t\t paginator := pagination.Paging(&pagination.Param{\n\t\t\tDB: Config.DB.Preload(\"Rubros\").Preload(\"Unidades\"),\n\t\t\tPage: page,\n\t\t\tLimit: limit,\n\t\t\tOrderBy: []string{\"id\"},\n\t\t\tShowSQL: true,\n\t\t}, &user)\n \n\t\tc.JSON(200, paginator)\n\n\t}\n}", "func (u *UsersController) List(ctx *gin.Context) {\n\tcriteria := u.buildCriteria(ctx)\n\n\tvar listAsAdmin bool\n\tif isTatAdmin(ctx) {\n\t\tlistAsAdmin = true\n\t} else {\n\t\tuser, e := PreCheckUser(ctx)\n\t\tif e != nil {\n\t\t\tctx.AbortWithError(http.StatusInternalServerError, e)\n\t\t\treturn\n\t\t}\n\t\tlistAsAdmin = user.CanListUsersAsAdmin\n\t}\n\tcount, users, err := userDB.ListUsers(criteria, listAsAdmin)\n\tif err != nil {\n\t\tctx.AbortWithError(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tout := &tat.UsersJSON{\n\t\tCount: count,\n\t\tUsers: users,\n\t}\n\tctx.JSON(http.StatusOK, out)\n}", "func (s *userService) List() *userListDoer {\n\treturn &userListDoer{client: s.client}\n}", "func ListAll() []ModelUser {\n\tcommon.Logger(\"info\", \"Initialize Get Database in PostgreSQL\", \"Modul User : ListAll\")\n\tdb := common.GetPostgreSQLDB()\n\n\ttx := db.Begin()\n\n\tcommon.Logger(\"info\", \"Prepare Query Select Table in Database PostgreSQL\", \"Modul User : ListAll\")\n\tvar models []ModelUser\n\n\tcommon.Logger(\"info\", \"Prepare Read Data from PostgreSQL\", \"Modul User : ListAll\")\n\ttx.Find(&models)\n\n\ttx.Commit()\n\tcommon.Logger(\"info\", \"Finnished Read Data from PostgreSQL\", \"Modul User : ListAll\")\n\n\treturn models\n}", "func ListAllUsers(w http.ResponseWriter, r *http.Request){\n\n\trows, err:= db.Query(\"SELECT * FROM users LIMIT 20\")\n\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tpanic(\"failed to connect database\")\n\t}\n\n\tlistUsers := Users{}\n\tfor rows.Next() {\n\t\tp := User{}\n\t\tif err := rows.Scan(&p.ID, &p.Name, &p.Score); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tlistUsers = append(listUsers, p)\n\n\t}\n\tdefer rows.Close()\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n\tjson.NewEncoder(w).Encode(listUsers)\n}", "func GetUsersByName(name string)(users Users,err error){\n\trows,err := db.Query(\"select user_id,email,password,date from users where user_name = ?\",name)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor rows.Next() {\n\t\tu := &User{}\n\t\trows.Scan(&u.Id,&u.Email,&u.password,&u.Date)\n\t\tu.Name = name\n\t\tusers = append(users,u)\n\t}\n\t//for _,v := range users{\n\t//\tfmt.Println(v)\n\t//}\n\treturn\n}", "func (e *EndpointUsers) listUsers(writer http.ResponseWriter, request *http.Request) {\n\t_, usr := validate(e.sessions, e.users, e.permissions, writer, request, user.LIST_USERS)\n\tif usr == nil {\n\t\treturn\n\t}\n\n\tusers, err := e.users.List()\n\tif err != nil {\n\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tres := &userListDTO{}\n\tfor _, u := range users {\n\t\tres.List = append(res.List, newUserDTO(u))\n\t}\n\tWriteJSONBody(writer, res)\n}", "func (s *HookStorage) ListByUser(id string) (*model.HookList, error) {\n\n\tvar (\n\t\terr error\n\t\thooks = new(model.HookList)\n\t\tuser_filter = r.Row.Field(\"user\").Eq(id)\n\t)\n\n\tres, err := r.Table(HookTable).Filter(user_filter).Run(s.Session)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Close()\n\n\tif res.IsNil() {\n\t\treturn nil, nil\n\t}\n\n\terr = res.All(hooks)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn hooks, nil\n}", "func listUsersFull(client *Client) ([]interface{}, error) {\n\treturn client.GetItemListInterfaceArray(\"/access/users?full=1\")\n}", "func (client IdentityClient) listUsers(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/users\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListUsersResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func users(ds *datastore.Client) ([]User, error) {\n\tdst := make([]User, 0)\n\t_, err := ds.GetAll(context.Background(), datastore.NewQuery(userKind).Limit(limit).Project(usernameField, userIDField).Order(usernameField), &dst)\n\treturn dst, err\n}", "func (sys *IAMSys) ListUsers() (map[string]madmin.UserInfo, error) {\n\tobjectAPI := newObjectLayerFn()\n\tif objectAPI == nil {\n\t\treturn nil, errServerNotInitialized\n\t}\n\n\tvar users = make(map[string]madmin.UserInfo)\n\n\tsys.RLock()\n\tdefer sys.RUnlock()\n\n\tfor k, v := range sys.iamUsersMap {\n\t\tusers[k] = madmin.UserInfo{\n\t\t\tPolicyName: sys.iamUserPolicyMap[k].Policy,\n\t\t\tStatus: madmin.AccountStatus(v.Status),\n\t\t}\n\t}\n\n\treturn users, nil\n}", "func GetListUserRej(c *gin.Context) {\r\n\tvar usr []model.UserReject\r\n\tres := model.GetLUserRE(usr)\r\n\r\n\tutils.WrapAPIData(c, map[string]interface{}{\r\n\t\t\"Data\": res,\r\n\t}, http.StatusOK, \"success\")\r\n}", "func (s *Shell) ListUsers(_ *cli.Context) (err error) {\n\tresp, err := s.HTTP.Get(\"/v2/users/\", nil)\n\tif err != nil {\n\t\treturn s.errorOut(err)\n\t}\n\tdefer func() {\n\t\tif cerr := resp.Body.Close(); cerr != nil {\n\t\t\terr = multierr.Append(err, cerr)\n\t\t}\n\t}()\n\n\treturn s.renderAPIResponse(resp, &AdminUsersPresenters{})\n}", "func GetUserAnimelist(username string) (*UserAnimelist, error) {\n\tres := &UserAnimelist{}\n\terr := urlToStruct(fmt.Sprintf(\"/users/%s/animelist\",\n\t\turl.QueryEscape(username)), res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}", "func ListUsers(db *pg.DB) ([]*models.User, error) {\n\tvar users []*models.User\n\n\t_, err := db.Query(&users, `SELECT * FROM Users`)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Print names and PK\n\tfor i, n := range users {\n\t\tfmt.Println(i, n.UserName, n.Password, n.Email)\n\t}\n\treturn users, nil\n}", "func (objectSet *UserObjectSet) GetObjectList() ([]*nimbleos.User, error) {\n\tresp, err := objectSet.Client.List(userPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buildUserObjectSet(resp), err\n}", "func ListUsers(w http.ResponseWriter, r *http.Request) {\n\tusers, err := dal.GetUsers(\"\")\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tcommon.WriteResponse(w, users)\n}" ]
[ "0.7359356", "0.72904336", "0.7077272", "0.7028727", "0.7027776", "0.702073", "0.70161134", "0.6993351", "0.6991551", "0.6870929", "0.6868621", "0.68681204", "0.68483824", "0.6812991", "0.67967814", "0.6774643", "0.6770087", "0.6731464", "0.67262626", "0.6713845", "0.6699844", "0.669929", "0.6655612", "0.6642702", "0.66425526", "0.66208535", "0.66092664", "0.6592394", "0.65824366", "0.6565941", "0.6565435", "0.65618855", "0.6551717", "0.65379125", "0.652043", "0.64877695", "0.6467049", "0.64624953", "0.6460552", "0.6437262", "0.6417338", "0.6416917", "0.64069706", "0.63966924", "0.63772124", "0.635496", "0.63445115", "0.63397175", "0.63367265", "0.6330442", "0.6330112", "0.63160896", "0.6307465", "0.6302185", "0.63019973", "0.6290428", "0.62751806", "0.6273702", "0.62730396", "0.6243787", "0.62279373", "0.6223127", "0.62165004", "0.6207883", "0.62019795", "0.61897224", "0.61881655", "0.61817247", "0.6138993", "0.613614", "0.61356974", "0.61355895", "0.6134378", "0.61292255", "0.6124605", "0.6120286", "0.61117357", "0.6110998", "0.61083", "0.6101624", "0.60785526", "0.6058127", "0.60500795", "0.6046629", "0.604288", "0.6033443", "0.6027155", "0.60182554", "0.6013303", "0.6011811", "0.6010597", "0.60038596", "0.59978145", "0.5975926", "0.5972293", "0.59710544", "0.59707624", "0.59706646", "0.59648466", "0.5962433" ]
0.7338346
1
CgoEform Earth reference ellipsoids. E f o r m This function is part of the International Astronomical Union's SOFA (Standards of Fundamental Astronomy) software collection. Status: canonical. Given: n int ellipsoid identifier (Note 1) Returned: a double equatorial radius (meters, Note 2) f double flattening (Note 2) Returned (function value): err error nil = OK errEformE1 = illegal identifier (Note 3) Notes: 1) The identifier n is a number that specifies the choice of reference ellipsoid. The following are supported: n ellipsoid 1 WGS84 2 GRS80 3 WGS72 The n value has no significance outside the SOFA software. For convenience, symbols WGS84 etc. are defined in sofam.h. 2) The ellipsoid parameters are returned in the form of equatorial radius in meters (a) and flattening (f). The latter is a number around 0.00335, i.e. around 1/298. 3) For the case where an unsupported n value is supplied, zero a and f are returned, as well as error status. References: Department of Defense World Geodetic System 1984, National Imagery and Mapping Agency Technical Report 8350.2, Third Edition, p32. Moritz, H., Bull. Geodesique 662, 187 (1992). The Department of Defense World Geodetic System 1972, World Geodetic System Committee, May 1974. Explanatory Supplement to the Astronomical Almanac, P. Kenneth Seidelmann (ed), University Science Books (1992), p220. This revision: 2013 June 18 SOFA release 20200721 Copyright (C) 2020 IAU SOFA Board. See notes at end. CgoEform Earth reference ellipsoids.
func CgoEform(n int) (a, f float64, err en.ErrNum) { var cA, cF C.double var cStatus C.int cStatus = C.iauEform(C.int(n), &cA, &cF) switch int(cStatus) { case 0: case -1: err = errEform.Set(-1) default: err = errEform.Set(0) } return float64(cA), float64(cF), err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GoEform(n int) (a, f float64, err en.ErrNum) {\n\n\t// Look up a and f for the specified reference ellipsoid.\n\tswitch n {\n\tcase WGS84:\n\t\ta = 6378137.0\n\t\tf = 1.0 / 298.257223563\n\tcase GRS80:\n\t\ta = 6378137.0\n\t\tf = 1.0 / 298.257222101\n\tcase WGS72:\n\t\ta = 6378135.0\n\t\tf = 1.0 / 298.26\n\tdefault:\n\t\t// Invalid identifier.\n\t\ta = 0.0\n\t\tf = 0.0\n\t\terr = errEform.Set(-1)\n\t}\n\treturn\n}", "func NewEllipsoid(radius, flattening float64) *Ellipsoid {\n\te := new(Ellipsoid)\n\tC.geod_init(&e.g, C.double(radius), C.double(flattening))\n\treturn e\n}", "func GetEquationOfCenter(anomaly float64) float64 {\n\t// The numbers being multiplied below are coefficients for the Equation of Center for Earth\n\tvar anomalyInRad float64\n\tanomalyInRad = anomaly * (math.Pi/180)\n\treturn 1.9148 * (math.Sin(anomalyInRad)) + 0.0200 * math.Sin(2 * anomalyInRad) + 0.0003 * math.Sin(3 * anomalyInRad)\n}", "func earthRadius(x float64) float64 {\n\tmasm := 6378137.0 // Major semiaxis [m]\n\tmism := 6356752.3 // Minor semiaxis [m]\n\n\tan := masm * masm * math.Cos(x)\n\tbn := mism * mism * math.Sin(x)\n\tad := masm * math.Cos(x)\n\tbd := mism * math.Sin(x)\n\treturn math.Sqrt((an*an + bn*bn) / (ad*ad + bd*bd))\n}", "func calcEccentEarthOrbit(julianCentury []float64) (eccentEarthOrbit []float64) {\n\tfor index := 0; index < len(julianCentury); index++ {\n\t\ttemp := 0.016708634 - julianCentury[index]*(0.000042037+0.0000001267*julianCentury[index])\n\t\teccentEarthOrbit = append(eccentEarthOrbit, temp)\n\t}\n\treturn\n}", "func TestEllipticE(t *testing.T) {\n\tt.Parallel()\n\tconst tol = 1.0e-14\n\trnd := rand.New(rand.NewSource(1))\n\n\t// The following EllipticE(pi/3,m), m=0.1(0.1)0.9 was computed in Maxima 5.38.0 using Bigfloat arithmetic.\n\tvE := [...]float64{\n\t\t1.0316510822817691068014397636905610074934300946730,\n\t\t1.0156973658341766636288643556414001451527597364432,\n\t\t9.9929636467826398814855428365155224243586391115108e-1,\n\t\t9.8240033979859736941287149003648737502960015189033e-1,\n\t\t9.6495145764299257550956863602992167490195750321518e-1,\n\t\t9.4687829659158090935158610908054896203271861698355e-1,\n\t\t9.2809053417715769009517654522979827392794124845027e-1,\n\t\t9.0847044378047233264777277954768245721857017157916e-1,\n\t\t8.8785835036531301307661603341327881634688308777383e-1,\n\t}\n\tphi := math.Pi / 3\n\tfor m := 1; m <= 9; m++ {\n\t\tmf := float64(m) / 10\n\t\tdelta := math.Abs(EllipticE(phi, mf) - vE[m-1])\n\t\tif delta > tol {\n\t\t\tt.Fatalf(\"EllipticE(pi/3,m) test fail for m=%v\", mf)\n\t\t}\n\t}\n\n\tfor test := 0; test < 100; test++ {\n\t\talpha := rnd.Float64() * math.Pi / 4\n\t\tbeta := rnd.Float64() * math.Pi / 4\n\t\tfor mi := 0; mi < 9999; mi++ {\n\t\t\tm := float64(mi) / 10000\n\t\t\tEa := EllipticE(alpha, m)\n\t\t\tEb := EllipticE(beta, m)\n\t\t\tsina, cosa := math.Sincos(alpha)\n\t\t\tsinb, cosb := math.Sincos(beta)\n\t\t\ttan := (sina*math.Sqrt(1-m*sinb*sinb) + sinb*math.Sqrt(1-m*sina*sina)) / (cosa + cosb)\n\t\t\tgamma := 2 * math.Atan(tan)\n\t\t\tEg := EllipticE(gamma, m)\n\t\t\tdelta := math.Abs(Ea + Eb - Eg - m*sina*sinb*math.Sin(gamma))\n\t\t\tif delta > tol {\n\t\t\t\tt.Fatalf(\"EllipticE test fail for m=%v, alpha=%v, beta=%v\", m, alpha, beta)\n\t\t\t}\n\t\t}\n\t}\n}", "func East(value float64) *SimpleElement { return newSEFloat(\"east\", value) }", "func NewOrbitFromOE(a, e, i, Ω, ω, ν float64, c CelestialObject) *Orbit {\n\t// Convert angles to radians\n\ti = i * deg2rad\n\tΩ = Ω * deg2rad\n\tω = ω * deg2rad\n\tν = ν * deg2rad\n\n\t// Algorithm from Vallado, 4th edition, page 118 (COE2RV).\n\tif e < eccentricityε {\n\t\t// Circular...\n\t\tif i < angleε {\n\t\t\t// ... equatorial\n\t\t\tΩ = 0\n\t\t\tω = 0\n\t\t\tν = math.Mod(ω+Ω+ν, 2*math.Pi)\n\t\t} else {\n\t\t\t// ... inclined\n\t\t\tω = 0\n\t\t\tν = math.Mod(ν+ω, 2*math.Pi)\n\t\t}\n\t} else if i < angleε && !(c.Equals(Sun) && config.meeus) {\n\t\t// Meeus breaks if doing this correction by Vallado\n\t\t// Elliptical equatorial\n\t\tΩ = 0\n\t\tω = math.Mod(ω+Ω, 2*math.Pi)\n\t}\n\tp := a * (1 - e*e)\n\tif floats.EqualWithinAbs(e, 1, eccentricityε) || e > 1 {\n\t\tpanic(\"[ERROR] should initialize parabolic or hyperbolic orbits with R, V\")\n\t}\n\tμOp := math.Sqrt(c.μ / p)\n\tsinν, cosν := math.Sincos(ν)\n\trPQW := []float64{p * cosν / (1 + e*cosν), p * sinν / (1 + e*cosν), 0}\n\tvPQW := []float64{-μOp * sinν, μOp * (e + cosν), 0}\n\trIJK := Rot313Vec(-ω, -i, -Ω, rPQW)\n\tvIJK := Rot313Vec(-ω, -i, -Ω, vPQW)\n\torbit := Orbit{rIJK, vIJK, c, a, e, i, Ω, ω, ν, 0, 0, 0, 0.0}\n\torbit.Elements()\n\treturn &orbit\n}", "func (o Orbit) SinCosE() (sinE, cosE float64) {\n\t_, e, _, _, _, ν, _, _, _ := o.Elements()\n\tsinν, cosν := math.Sincos(ν)\n\tdenom := 1 + e*cosν\n\tif e > 1 {\n\t\t// Hyperbolic orbit\n\t\tsinE = math.Sqrt(e*e-1) * sinν / denom\n\t} else {\n\t\tsinE = math.Sqrt(1-e*e) * sinν / denom\n\t}\n\tcosE = (e + cosν) / denom\n\treturn\n}", "func fnETransform(ctx Context, doc *JDoc, params []string) interface{} {\n\tstats := ctx.Value(EelTotalStats).(*ServiceStats)\n\tif params == nil || len(params) == 0 || len(params) > 1 {\n\t\tctx.Log().Error(\"error_type\", \"func_etransform\", \"op\", \"etransform\", \"cause\", \"wrong_number_of_parameters\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"wrong number of parameters in call to etransform function\"), \"etransform\", params})\n\t\treturn nil\n\t}\n\t// prepare event\n\tevent, err := NewJDocFromString(extractStringParam(params[0]))\n\tif err != nil {\n\t\tctx.Log().Error(\"error_type\", \"func_etransform\", \"op\", \"etransform\", \"cause\", \"invalid_json\", \"params\", params, \"error\", err.Error())\n\t\tstats.IncErrors()\n\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"non json parameters in call to etransform function\"), \"etransform\", params})\n\t\treturn nil\n\t}\n\t// pick handler\n\thandlers := GetHandlerFactory(ctx).GetHandlersForEvent(ctx, event)\n\tif len(handlers) == 0 {\n\t\tctx.Log().Error(\"error_type\", \"func_etransform\", \"op\", \"etransform\", \"cause\", \"no_matching_handler\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"no matching handler found in call to etransform function\"), \"etransform\", params})\n\t\treturn nil\n\t}\n\tif len(handlers) > 1 {\n\t\tctx.Log().Error(\"error_type\", \"func_etransform\", \"op\", \"etransform\", \"cause\", \"too_many_matching_handlers\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"too many matching handlers found in call to etransform function\"), \"etransform\", params})\n\t\treturn nil\n\t}\n\t// apply debug logs\n\tlogParams := GetConfig(ctx).LogParams\n\tif logParams != nil {\n\t\tfor k, v := range logParams {\n\t\t\tev := event.ParseExpression(ctx, v)\n\t\t\tctx.AddLogValue(k, ev)\n\t\t}\n\t}\n\t// apply handler / transformation\n\teps, err := handlers[0].ProcessEvent(Gctx.SubContext(), event)\n\tif err != nil {\n\t\tctx.Log().Error(\"error_type\", \"func_etransform\", \"op\", \"etransform\", \"cause\", \"bad_transformation\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"failed to process external transformation in call to etransform function\"), \"etransform\", params})\n\t\treturn nil\n\t}\n\tif len(eps) == 0 {\n\t\tctx.Log().Error(\"error_type\", \"func_etransform\", \"op\", \"etransform\", \"cause\", \"no_results\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"no results found in call to etransform function\"), \"etransform\", params})\n\t\treturn nil\n\t}\n\t// if this check is present some unit tests will fail\n\t/*if len(eps) > 1 {\n\t\tctx.Log().Error(\"error_type\", \"func_etransform\", \"op\", \"etransform\", \"cause\", \"too_many_results\", \"params\", params, \"count\", len(eps))\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"too many results found in call to etransform function\"), \"etransform\", params})\n\t\treturn nil\n\t}*/\n\tresult := eps[0].GetPayloadParsed().GetOriginalObject()\n\treturn result\n}", "func molodensky(ilat, ilon float64, from, to eDatum) (float64, float64) {\n\t// from->WGS84 - to->WGS84 = from->WGS84 + WGS84->to = from->to\n\tdX := Datum[from].dX - Datum[to].dX\n\tdY := Datum[from].dY - Datum[to].dY\n\tdZ := Datum[from].dZ - Datum[to].dZ\n\tslat := math.Sin(ilat)\n\tclat := math.Cos(ilat)\n\tslon := math.Sin(ilon)\n\tclon := math.Cos(ilon)\n\tssqlat := slat * slat\n\n\t//dlat = ((-dx * slat * clon - dy * slat * slon + dz * clat)\n\t// + (da * rn * fromEsq * slat * clat / fromA)\n\t// + (df * (rm * adb + rn / adb )* slat * clat))\n\t// / (rm + from.h);\n\n\tfromF := Datum[from].f\n\tdf := Datum[to].f - fromF\n\tfromA := Datum[from].a\n\tda := Datum[to].a - fromA\n\tfromEsq := Datum[from].esq\n\tadb := 1.0 / (1.0 - fromF)\n\trn := fromA / math.Sqrt(1-fromEsq*ssqlat)\n\trm := fromA * (1 - fromEsq) / math.Pow((1-fromEsq*ssqlat), 1.5)\n\tfromH := 0.0 // we're flat!\n\tdlat := (-dX*slat*clon - dY*slat*slon + dZ*clat + da*rn*fromEsq*slat*clat/fromA +\n\t\t+df*(rm*adb+rn/adb)*slat*clat) /\n\t\t(rm + fromH)\n\n\t// result lat (radians)\n\tolat := ilat + dlat\n\n\t// dlon = (-dx * slon + dy * clon) / ((rn + from.h) * clat);\n\tdlon := (-dX*slon + dY*clon) / ((rn + fromH) * clat)\n\t// result lon (radians)\n\tolon := ilon + dlon\n\treturn olat, olon\n}", "func NewEllipsoid(sys *System) (*Ellipsoid, error) {\n\tellipsoid := &Ellipsoid{}\n\n\terr := ellipsoid.initialize(sys)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ellipsoid, nil\n}", "func get_arc_center(x1, y1, x2, y2, fa, fs, rx, ry, sin_phi, cos_phi float64) []float64 {\n\t// Step 1.\n\t//\n\t// Moving an ellipse so origin will be the middlepoint between our two\n\t// points. After that, rotate it to line up ellipse axes with coordinate\n\t// axes.\n\t//\n\tx1p := cos_phi*(x1-x2)/2 + sin_phi*(y1-y2)/2\n\ty1p := -sin_phi*(x1-x2)/2 + cos_phi*(y1-y2)/2\n\n\trx_sq := rx * rx\n\try_sq := ry * ry\n\tx1p_sq := x1p * x1p\n\ty1p_sq := y1p * y1p\n\n\t// Step 2.\n\t//\n\t// Compute coordinates of the centre of this ellipse (cx', cy')\n\t// in the new coordinate system.\n\t//\n\tradicant := (rx_sq * ry_sq) - (rx_sq * y1p_sq) - (ry_sq * x1p_sq)\n\n\tif radicant < 0 {\n\t\t// due to rounding errors it might be e.g. -1.3877787807814457e-17\n\t\tradicant = 0\n\t}\n\n\tradicant /= (rx_sq * y1p_sq) + (ry_sq * x1p_sq)\n\tsign := 1.0\n\tif fa == fs {\n\t\tsign = -1.0\n\t}\n\tradicant = math.Sqrt(radicant) * sign\n\n\tcxp := radicant * rx / ry * y1p\n\tcyp := radicant * -ry / rx * x1p\n\n\t// Step 3.\n\t//\n\t// Transform back to get centre coordinates (cx, cy) in the original\n\t// coordinate system.\n\t//\n\tcx := cos_phi*cxp - sin_phi*cyp + (x1+x2)/2\n\tcy := sin_phi*cxp + cos_phi*cyp + (y1+y2)/2\n\n\t// Step 4.\n\t//\n\t// Compute angles (theta1, delta_theta).\n\t//\n\tv1x := (x1p - cxp) / rx\n\tv1y := (y1p - cyp) / ry\n\tv2x := (-x1p - cxp) / rx\n\tv2y := (-y1p - cyp) / ry\n\n\ttheta1 := unit_vector_angle(1, 0, v1x, v1y)\n\tdelta_theta := unit_vector_angle(v1x, v1y, v2x, v2y)\n\n\tif fs == 0 && delta_theta > 0 {\n\t\tdelta_theta -= TAU\n\t}\n\tif fs == 1 && delta_theta < 0 {\n\t\tdelta_theta += TAU\n\t}\n\n\treturn []float64{cx, cy, theta1, delta_theta}\n}", "func Erf(value gcv.Value) (gcv.Value, error) {\n\tif value.Type() == gcv.Complex {\n\t\treturn nil, errors.New(\"Erf is not supported for Complex numbers\")\n\t}\n\treturn gcv.MakeValue(math.Erf(value.Real())), nil\n}", "func eastDelta(e, w float64) float64 {\n\te = normEasting(e)\n\tw = normEasting(w)\n\tif e < w {\n\t\treturn 360 + e - w\n\t}\n\treturn e - w\n}", "func TestEllipticF(t *testing.T) {\n\tt.Parallel()\n\tconst tol = 1.0e-14\n\trnd := rand.New(rand.NewSource(1))\n\n\t// The following EllipticF(pi/3,m), m=0.1(0.1)0.9 was computed in Maxima 5.38.0 using Bigfloat arithmetic.\n\tvF := [...]float64{\n\t\t1.0631390181954904767742338285104637431858016483079,\n\t\t1.0803778062523490005579242592072579594037132891908,\n\t\t1.0991352230920430074586978843452269008747645822123,\n\t\t1.1196949183404746257742176145632376703505764745654,\n\t\t1.1424290580457772555013955266260457822322036529624,\n\t\t1.1678400583161860445148860686430780757517286094732,\n\t\t1.1966306515644649360767197589467723191317720122309,\n\t\t1.2298294422249382706933871574135731278765534034979,\n\t\t1.2690359140762658660446752406901433173504503955036,\n\t}\n\tphi := math.Pi / 3\n\tfor m := 1; m <= 9; m++ {\n\t\tmf := float64(m) / 10\n\t\tdelta := math.Abs(EllipticF(phi, mf) - vF[m-1])\n\t\tif delta > tol {\n\t\t\tt.Fatalf(\"EllipticF(pi/3,m) test fail for m=%v\", mf)\n\t\t}\n\t}\n\n\tfor test := 0; test < 100; test++ {\n\t\talpha := rnd.Float64() * math.Pi / 4\n\t\tbeta := rnd.Float64() * math.Pi / 4\n\t\tfor mi := 0; mi < 9999; mi++ {\n\t\t\tm := float64(mi) / 10000\n\t\t\tFa := EllipticF(alpha, m)\n\t\t\tFb := EllipticF(beta, m)\n\t\t\tsina, cosa := math.Sincos(alpha)\n\t\t\tsinb, cosb := math.Sincos(beta)\n\t\t\ttan := (sina*math.Sqrt(1-m*sinb*sinb) + sinb*math.Sqrt(1-m*sina*sina)) / (cosa + cosb)\n\t\t\tgamma := 2 * math.Atan(tan)\n\t\t\tFg := EllipticF(gamma, m)\n\t\t\tdelta := math.Abs(Fa + Fb - Fg)\n\t\t\tif delta > tol {\n\t\t\t\tt.Fatalf(\"EllipticF test fail for m=%v, alpha=%v, beta=%v\", m, alpha, beta)\n\t\t\t}\n\t\t}\n\t}\n}", "func (o *Orbit) Elements() (a, e, i, Ω, ω, ν, λ, tildeω, u float64) {\n\tif o.hashValid() {\n\t\treturn o.ccha, o.cche, o.cchi, o.cchΩ, o.cchω, o.cchν, o.cchλ, o.cchtildeω, o.cchu\n\t}\n\t// Algorithm from Vallado, 4th edition, page 113 (RV2COE).\n\thVec := Cross(o.rVec, o.vVec)\n\tn := Cross([]float64{0, 0, 1}, hVec)\n\tv := Norm(o.vVec)\n\tr := Norm(o.rVec)\n\tξ := (v*v)/2 - o.Origin.μ/r\n\ta = -o.Origin.μ / (2 * ξ)\n\teVec := make([]float64, 3, 3)\n\tfor i := 0; i < 3; i++ {\n\t\teVec[i] = ((v*v-o.Origin.μ/r)*o.rVec[i] - Dot(o.rVec, o.vVec)*o.vVec[i]) / o.Origin.μ\n\t}\n\te = Norm(eVec)\n\t// Prevent nil values for e\n\tif e < eccentricityε {\n\t\te = eccentricityε\n\t}\n\ti = math.Acos(hVec[2] / Norm(hVec))\n\tif i < angleε {\n\t\ti = angleε\n\t}\n\tω = math.Acos(Dot(n, eVec) / (Norm(n) * e))\n\tif math.IsNaN(ω) {\n\t\tω = 0\n\t}\n\tif eVec[2] < 0 {\n\t\tω = 2*math.Pi - ω\n\t}\n\tΩ = math.Acos(n[0] / Norm(n))\n\tif math.IsNaN(Ω) {\n\t\tΩ = angleε\n\t}\n\tif n[1] < 0 {\n\t\tΩ = 2*math.Pi - Ω\n\t}\n\tcosν := Dot(eVec, o.rVec) / (e * r)\n\tif abscosν := math.Abs(cosν); abscosν > 1 && floats.EqualWithinAbs(abscosν, 1, 1e-12) {\n\t\t// Welcome to the edge case which took about 1.5 hours of my time.\n\t\tcosν = Sign(cosν) // GTFO NaN!\n\t}\n\tν = math.Acos(cosν)\n\tif math.IsNaN(ν) {\n\t\tν = 0\n\t}\n\tif Dot(o.rVec, o.vVec) < 0 {\n\t\tν = 2*math.Pi - ν\n\t}\n\t// Fix rounding errors.\n\ti = math.Mod(i, 2*math.Pi)\n\tΩ = math.Mod(Ω, 2*math.Pi)\n\tω = math.Mod(ω, 2*math.Pi)\n\tν = math.Mod(ν, 2*math.Pi)\n\tλ = math.Mod(ω+Ω+ν, 2*math.Pi)\n\ttildeω = math.Mod(ω+Ω, 2*math.Pi)\n\tif e < eccentricityε {\n\t\t// Circular\n\t\tu = math.Acos(Dot(n, o.rVec) / (Norm(n) * r))\n\t} else {\n\t\tu = math.Mod(ν+ω, 2*math.Pi)\n\t}\n\t// Cache values\n\to.ccha = a\n\to.cche = e\n\to.cchi = i\n\to.cchΩ = Ω\n\to.cchω = ω\n\to.cchν = ν\n\to.cchλ = λ\n\to.cchtildeω = tildeω\n\to.cchu = u\n\to.computeHash()\n\treturn\n}", "func Float64E(name string, value float64, usage string) *float64 {\n\treturn Global.Float64E(name, value, usage)\n}", "func EarthDistance(firstVector, secondVector []float64) (float64, error) {\n\tvar R float64 = 6378137 // radius of the earth in meter\n\ttoRadians := func(d float64) float64 {\n\t\treturn d * math.Pi / 180.0\n\t}\n\n\tlat1 := toRadians(firstVector[1])\n\tlat2 := toRadians(secondVector[1])\n\tdLat := lat2 - lat1\n\tdLng := toRadians(secondVector[0] - firstVector[0])\n\tc := 2.0 * math.Asin(math.Sqrt(math.Pow(math.Sin(dLat/2.0), 2)+\n\t\tmath.Cos(lat1)*math.Cos(lat2)*math.Pow(math.Sin(dLng/2.0), 2)))\n\n\treturn c * R, nil\n}", "func floatMandE(f float64, tmp []byte) (int, []byte) {\n\tif f < 0 {\n\t\tf = -f\n\t}\n\n\t// Use strconv.FormatFloat to handle the intricacies of determining how much\n\t// precision is necessary to precisely represent f. The 'e' format is\n\t// d.dddde±dd.\n\ttmp = strconv.AppendFloat(tmp, f, 'e', -1, 64)\n\tif len(tmp) < 4 {\n\t\t// The formatted float must be at least 4 bytes (\"1e+0\") or something\n\t\t// unexpected has occurred.\n\t\tpanic(fmt.Sprintf(\"malformed float: %v -> %s\", f, tmp))\n\t}\n\n\t// Parse the exponent.\n\te := bytes.IndexByte(tmp, 'e')\n\te10 := 0\n\tfor i := e + 2; i < len(tmp); i++ {\n\t\te10 = e10*10 + int(tmp[i]-'0')\n\t}\n\tswitch tmp[e+1] {\n\tcase '-':\n\t\te10 = -e10\n\tcase '+':\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"malformed float: %v -> %s\", f, tmp))\n\t}\n\n\t// Strip off the exponent.\n\ttmp = tmp[:e]\n\n\t// Move all of the digits after the decimal and prepend a leading 0.\n\tif len(tmp) > 1 {\n\t\t// \"d.dddd\" -> \"dddddd\"\n\t\ttmp[1] = tmp[0]\n\t} else {\n\t\t// \"d\" -> \"dd\"\n\t\ttmp = append(tmp, tmp[0])\n\t}\n\ttmp[0] = '0' // \"0ddddd\"\n\te10++\n\n\t// Convert the power-10 exponent to a power of 100 exponent.\n\tvar e100 int\n\tif e10 >= 0 {\n\t\te100 = (e10 + 1) / 2\n\t} else {\n\t\te100 = e10 / 2\n\t}\n\t// Strip the leading 0 if the conversion to e100 did not add a multiple of\n\t// 10.\n\tif e100*2 == e10 {\n\t\ttmp = tmp[1:]\n\t}\n\n\t// Ensure that the number of digits is even.\n\tif len(tmp)%2 != 0 {\n\t\ttmp = append(tmp, '0')\n\t}\n\n\t// Convert the base-10 'b' slice to a base-100 'm' slice. We do this\n\t// conversion in place to avoid an allocation.\n\tm := tmp[:len(tmp)/2]\n\tfor i := 0; i < len(tmp); i += 2 {\n\t\taccum := 10*int(tmp[i]-'0') + int(tmp[i+1]-'0')\n\t\t// The bytes are encoded as 2n+1.\n\t\tm[i/2] = byte(2*accum + 1)\n\t}\n\t// The last byte is encoded as 2n+0.\n\tm[len(m)-1]--\n\n\treturn e100, m\n}", "func (c *Configurator) Float64E(name string, value float64, usage string) *float64 {\n\tp := new(float64)\n\n\tc.Float64VarE(p, name, value, usage)\n\n\treturn p\n}", "func InitAndApplyE(options *Options) (string, error) {\n\tif _, err := InitE(options); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif _, err := GetE(options); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn ApplyE(options)\n}", "func Project(zone int, south bool, latitude, longitude float64) (float64, float64) {\n\n\t// False northing\n\tfn := 0.\n\tif south {\n\t\tfn = utmSouthernHemisphereFalseNorthing\n\t}\n\n\th1 := n/2 - n2*2/3 + n3*5/16 + n4*41/180\n\th2 := n2*13/48 - n3*3/5 + n4*557/1440\n\th3 := n3*61/240 - n4*103/140\n\th4 := n4 * 49561 / 161280\n\n\tq := math.Asinh(math.Tan(latitude)) - e*math.Atanh(e*math.Sin(latitude))\n\tβ := math.Atan(math.Sinh(q))\n\n\tη0 := math.Atanh(math.Cos(β) * math.Sin(longitude-λO(zone)))\n\tξ0 := math.Asin(math.Sin(β) * math.Cosh(η0))\n\n\tη1 := h1 * math.Cos(2*ξ0) * math.Sinh(2*η0)\n\tη2 := h2 * math.Cos(4*ξ0) * math.Sinh(4*η0)\n\tη3 := h3 * math.Cos(6*ξ0) * math.Sinh(6*η0)\n\tη4 := h4 * math.Cos(8*ξ0) * math.Sinh(8*η0)\n\n\tξ1 := h1 * math.Sin(2*ξ0) * math.Cosh(2*η0)\n\tξ2 := h2 * math.Sin(4*ξ0) * math.Cosh(4*η0)\n\tξ3 := h3 * math.Sin(6*ξ0) * math.Cosh(6*η0)\n\tξ4 := h4 * math.Sin(8*ξ0) * math.Cosh(8*η0)\n\n\tξ := ξ0 + ξ1 + ξ2 + ξ3 + ξ4\n\tη := η0 + η1 + η2 + η3 + η4\n\n\te := fe + kO*b*η\n\tn := fn + kO*b*ξ\n\treturn e, n\n}", "func tElliptic(s float64) float64 {\n\tm := (2 * math.Sqrt(s*s-s+1) / s) + (2 / s) - 1\n\tx := m\n\ty := m + 3 - 2*math.Sqrt(3)\n\tz := m + 3 + 2*math.Sqrt(3)\n\treturn 4 * mathext.EllipticRF(x, y, z)\n}", "func (e *Ellipsoid) Inverse(\n\tlat1, lon1, lat2, lon2 float64,\n\ts12, azi1, azi2 *float64,\n) {\n\tC.geod_inverse(&e.g,\n\t\tC.double(lat1), C.double(lon1), C.double(lat2), C.double(lon2),\n\t\t(*C.double)(s12), (*C.double)(azi1), (*C.double)(azi2))\n}", "func Root4(in *big.Float) *big.Float {\n\treturn Root(in, 4)\n}", "func Zgeequ(m, n int, a *mat.CMatrix, r, c *mat.Vector) (rowcnd, colcnd, amax float64, info int, err error) {\n\tvar bignum, one, rcmax, rcmin, smlnum, zero float64\n\tvar i, j int\n\n\tone = 1.0\n\tzero = 0.0\n\n\t// Test the input parameters.\n\tif m < 0 {\n\t\terr = fmt.Errorf(\"m < 0: m=%v\", m)\n\t} else if n < 0 {\n\t\terr = fmt.Errorf(\"n < 0: n=%v\", n)\n\t} else if a.Rows < max(1, m) {\n\t\terr = fmt.Errorf(\"a.Rows < max(1, m): a.Rows=%v, m=%v\", a.Rows, m)\n\t}\n\tif err != nil {\n\t\tgltest.Xerbla2(\"Zgeequ\", err)\n\t\treturn\n\t}\n\n\t// Quick return if possible\n\tif m == 0 || n == 0 {\n\t\trowcnd = one\n\t\tcolcnd = one\n\t\tamax = zero\n\t\treturn\n\t}\n\n\t// Get machine constants.\n\tsmlnum = Dlamch(SafeMinimum)\n\tbignum = one / smlnum\n\n\t// Compute row scale factors.\n\tfor i = 1; i <= m; i++ {\n\t\tr.Set(i-1, zero)\n\t}\n\n\t// Find the maximum element in each row.\n\tfor j = 1; j <= n; j++ {\n\t\tfor i = 1; i <= m; i++ {\n\t\t\tr.Set(i-1, math.Max(r.Get(i-1), cabs1(a.Get(i-1, j-1))))\n\t\t}\n\t}\n\n\t// Find the maximum and minimum scale factors.\n\trcmin = bignum\n\trcmax = zero\n\tfor i = 1; i <= m; i++ {\n\t\trcmax = math.Max(rcmax, r.Get(i-1))\n\t\trcmin = math.Min(rcmin, r.Get(i-1))\n\t}\n\tamax = rcmax\n\n\tif rcmin == zero {\n\t\t// Find the first zero scale factor and return an error code.\n\t\tfor i = 1; i <= m; i++ {\n\t\t\tif r.Get(i-1) == zero {\n\t\t\t\tinfo = i\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Invert the scale factors.\n\t\tfor i = 1; i <= m; i++ {\n\t\t\tr.Set(i-1, one/math.Min(math.Max(r.Get(i-1), smlnum), bignum))\n\t\t}\n\n\t\t// Compute ROWCND = min(R(I)) / max(R(I))\n\t\trowcnd = math.Max(rcmin, smlnum) / math.Min(rcmax, bignum)\n\t}\n\n\t// Compute column scale factors\n\tfor j = 1; j <= n; j++ {\n\t\tc.Set(j-1, zero)\n\t}\n\n\t// Find the maximum element in each column,\n\t// assuming the row scaling computed above.\n\tfor j = 1; j <= n; j++ {\n\t\tfor i = 1; i <= m; i++ {\n\t\t\tc.Set(j-1, math.Max(c.Get(j-1), cabs1(a.Get(i-1, j-1))*r.Get(i-1)))\n\t\t}\n\t}\n\n\t// Find the maximum and minimum scale factors.\n\trcmin = bignum\n\trcmax = zero\n\tfor j = 1; j <= n; j++ {\n\t\trcmin = math.Min(rcmin, c.Get(j-1))\n\t\trcmax = math.Max(rcmax, c.Get(j-1))\n\t}\n\n\tif rcmin == zero {\n\t\t// Find the first zero scale factor and return an error code.\n\t\tfor j = 1; j <= n; j++ {\n\t\t\tif c.Get(j-1) == zero {\n\t\t\t\tinfo = m + j\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Invert the scale factors.\n\t\tfor j = 1; j <= n; j++ {\n\t\t\tc.Set(j-1, one/math.Min(math.Max(c.Get(j-1), smlnum), bignum))\n\t\t}\n\n\t\t// Compute COLCND = min(C(J)) / max(C(J))\n\t\tcolcnd = math.Max(rcmin, smlnum) / math.Min(rcmax, bignum)\n\t}\n\n\treturn\n}", "func (crs TransverseMercator) FromLonLat(lon, lat float64, gs GeodeticSpheroid) (east, north float64) {\n\ts := spheroid(gs, crs.GeodeticDatum)\n\tφ := radian(lat)\n\tA := (radian(lon) - radian(crs.Lonf)) * math.Cos(φ)\n\teast = crs.Scale*crs._N(φ, s)*(A+(1-crs._T(φ)+crs._C(φ, s))*\n\t\tmath.Pow(A, 3)/6+(5-18*crs._T(φ)+crs._T(φ)*crs._T(φ)+72*crs._C(φ, s)-58*s.Ei2())*\n\t\tmath.Pow(A, 5)/120) + crs.Eastf\n\tnorth = crs.Scale*(crs._M(φ, s)-crs._M(radian(crs.Latf), s)+crs._N(φ, s)*math.Tan(φ)*\n\t\t(A*A/2+(5-crs._T(φ)+9*crs._C(φ, s)+4*crs._C(φ, s)*crs._C(φ, s))*\n\t\t\tmath.Pow(A, 4)/24+(61-58*crs._T(φ)+crs._T(φ)*crs._T(φ)+600*\n\t\t\tcrs._C(φ, s)-330*s.Ei2())*math.Pow(A, 6)/720)) + crs.Northf\n\treturn east, north\n}", "func (crs TransverseMercator) ToLonLat(east, north float64, gs GeodeticSpheroid) (lon, lat float64) {\n\ts := spheroid(gs, crs.GeodeticDatum)\n\teast -= crs.Eastf\n\tnorth -= crs.Northf\n\tMi := crs._M(radian(crs.Latf), s) + north/crs.Scale\n\tμ := Mi / (s.MajorAxis() * (1 - s.E2()/4 - 3*s.E4()/64 - 5*s.E6()/256))\n\tφ1 := μ + (3*s.Ei()/2-27*s.Ei3()/32)*math.Sin(2*μ) +\n\t\t(21*s.Ei2()/16-55*s.Ei4()/32)*math.Sin(4*μ) +\n\t\t(151*s.Ei3()/96)*math.Sin(6*μ) +\n\t\t(1097*s.Ei4()/512)*math.Sin(8*μ)\n\tR1 := s.MajorAxis() * (1 - s.E2()) / math.Pow(1-s.E2()*sin2(φ1), 3/2)\n\tD := east / (crs._N(φ1, s) * crs.Scale)\n\tφ := φ1 - (crs._N(φ1, s)*math.Tan(φ1)/R1)*(D*D/2-(5+3*crs._T(φ1)+10*\n\t\tcrs._C(φ1, s)-4*crs._C(φ1, s)*crs._C(φ1, s)-9*s.Ei2())*\n\t\tmath.Pow(D, 4)/24+(61+90*crs._T(φ1)+298*crs._C(φ1, s)+45*crs._T(φ1)*\n\t\tcrs._T(φ1)-252*s.Ei2()-3*crs._C(φ1, s)*crs._C(φ1, s))*\n\t\tmath.Pow(D, 6)/720)\n\tλ := radian(crs.Lonf) + (D-(1+2*crs._T(φ1)+crs._C(φ1, s))*D*D*D/6+(5-2*crs._C(φ1, s)+\n\t\t28*crs._T(φ1)-3*crs._C(φ1, s)*crs._C(φ1, s)+8*s.Ei2()+24*crs._T(φ1)*crs._T(φ1))*\n\t\tmath.Pow(D, 5)/120)/math.Cos(φ1)\n\treturn degree(λ), degree(φ)\n}", "func moonCoords(d float64) moonCoordinates { // geocentric ecliptic coordinates of the moon\n\tL := rad * (218.316 + 13.176396*d) // ecliptic longitude\n\tM := rad * (134.963 + 13.064993*d) // mean anomaly\n\tF := rad * (93.272 + 13.229350*d) // mean distance\n\n\tl := L + rad*6.289*math.Sin(M) // longitude\n\tb := rad * 5.128 * math.Sin(F) // latitude\n\tdt := 385001 - 20905*math.Cos(M) // distance to the moon in km\n\n\treturn moonCoordinates{\n\t\trightAscension(l, b),\n\t\tdeclination(l, b),\n\t\tdt,\n\t}\n}", "func (d Degrees) E5() int32 { return round(float64(d * 1e5)) }", "func (dw *DrawingWand) Ellipse(ox, oy, rx, ry, start, end float64) {\n\tC.MagickDrawEllipse(dw.dw, C.double(ox), C.double(oy), C.double(rx), C.double(ry), C.double(start), C.double(end))\n}", "func (d Degrees) E7() int32 { return round(float64(d * 1e7)) }", "func Erfc(scope *Scope, x tf.Output) (y tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"Erfc\",\n\t\tInput: []tf.Input{\n\t\t\tx,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func Grid2LatLon(N, E float64, from gGrid, to eDatum) (float64, float64) {\n\t//================\n\t// GRID -> Lat/Lon\n\t//================\n\ty := N + grid[from].falseN\n\tx := E - grid[from].falseE\n\tM := y / grid[from].k0\n\ta := Datum[to].a\n\tb := Datum[to].b\n\te := Datum[to].e\n\tesq := Datum[to].esq\n\tmu := M / (a * (1 - e*e/4 - 3*math.Pow(e, 4)/64 - 5*math.Pow(e, 6)/256))\n\n\tee := math.Sqrt(1 - esq)\n\te1 := (1 - ee) / (1 + ee)\n\tj1 := 3*e1/2 - 27*e1*e1*e1/32\n\tj2 := 21*e1*e1/16 - 55*e1*e1*e1*e1/32\n\tj3 := 151 * e1 * e1 * e1 / 96\n\tj4 := 1097 * e1 * e1 * e1 * e1 / 512\n\t// Footprint Latitude\n\tfp := mu + j1*math.Sin(2*mu) + j2*math.Sin(4*mu) + j3*math.Sin(6*mu) + j4*math.Sin(8*mu)\n\n\tsinfp := math.Sin(fp)\n\tcosfp := math.Cos(fp)\n\ttanfp := sinfp / cosfp\n\teg := (e * a / b)\n\teg2 := eg * eg\n\tC1 := eg2 * cosfp * cosfp\n\tT1 := tanfp * tanfp\n\tR1 := a * (1 - e*e) / math.Pow(1-(e*sinfp)*(e*sinfp), 1.5)\n\tN1 := a / math.Sqrt(1-(e*sinfp)*(e*sinfp))\n\tD := x / (N1 * grid[from].k0)\n\n\tQ1 := N1 * tanfp / R1\n\tQ2 := D * D / 2\n\tQ3 := (5 + 3*T1 + 10*C1 - 4*C1*C1 - 9*eg2*eg2) * (D * D * D * D) / 24\n\tQ4 := (61 + 90*T1 + 298*C1 + 45*T1*T1 - 3*C1*C1 - 252*eg2*eg2) * (D * D * D * D * D * D) / 720\n\t// result lat\n\tlat := fp - Q1*(Q2-Q3+Q4)\n\n\tQ5 := D\n\tQ6 := (1 + 2*T1 + C1) * (D * D * D) / 6\n\tQ7 := (5 - 2*C1 + 28*T1 - 3*C1*C1 + 8*eg2*eg2 + 24*T1*T1) * (D * D * D * D * D) / 120\n\t// result lon\n\tlon := grid[from].lon0 + (Q5-Q6+Q7)/cosfp\n\treturn lat, lon\n}", "func (c1 CIELab) DeltaE(c2 CIELab) float64 {\n\treturn math.Sqrt(math.Pow(c1.L*1-c2.L*2, 2) +\n\t\tmath.Pow(c1.A*1-c2.A*2, 2) + math.Pow(c1.B*1-c2.B*2, 2),\n\t)\n}", "func calcEquationOfTime(multiFactor []float64, geomMeanLongSun []float64, eccentEarthOrbit []float64, geomMeanAnomSun []float64) (equationOfTime []float64) {\n\n\tif len(multiFactor) != len(geomMeanLongSun) ||\n\t\tlen(multiFactor) != len(eccentEarthOrbit) ||\n\t\tlen(multiFactor) != len(geomMeanAnomSun) {\n\t\treturn\n\t}\n\n\tfor index := 0; index < len(multiFactor); index++ {\n\t\ta := multiFactor[index] * math.Sin(2.0*deg2rad(geomMeanLongSun[index]))\n\t\tb := 2.0 * eccentEarthOrbit[index] * math.Sin(deg2rad(geomMeanAnomSun[index]))\n\t\tc := 4.0 * eccentEarthOrbit[index] * multiFactor[index] * math.Sin(deg2rad(geomMeanAnomSun[index]))\n\t\td := math.Cos(2.0 * deg2rad(geomMeanLongSun[index]))\n\t\te := 0.5 * multiFactor[index] * multiFactor[index] * math.Sin(4.0*deg2rad(geomMeanLongSun[index]))\n\t\tf := 1.25 * eccentEarthOrbit[index] * eccentEarthOrbit[index] * math.Sin(2.0*deg2rad(geomMeanAnomSun[index]))\n\t\ttemp := 4.0 * rad2deg(a-b+c*d-e-f)\n\t\tequationOfTime = append(equationOfTime, temp)\n\t}\n\treturn\n}", "func (a *EditionApiService) V1EditionsEditionIdGet(ctx _context.Context, editionId int32) (EditionGroupDto, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue EditionGroupDto\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/v1/editions/{editionId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"editionId\"+\"}\", _neturl.QueryEscape(parameterToString(editionId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func GetEFS(e *efs.EFS, s string, n string) (string, error) {\n\t// Check if the EFS Filesystem already exists.\n\tfs, err := DescribeFilesystem(e, n)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(fs.FileSystems) > 0 {\n\t\tmnt, err := DescribeMountTarget(e, *fs.FileSystems[0].FileSystemId)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\t// This means we do have a mount target and we don't need to worry about\n\t\t// creating one.\n\t\tif len(mnt.MountTargets) > 0 {\n\t\t\treturn *mnt.MountTargets[0].IpAddress, nil\n\t\t}\n\n\t\t// In the off chance that we find outselves in a position where we don't have\n\t\t// a mount target for this EFS Filesystem we create one.\n\t\tnewMnt, err := CreateMountTarget(e, *fs.FileSystems[0].FileSystemId, s)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tlog.Printf(\"Using existing EFS Mount point: %s\", *newMnt.IpAddress)\n\t\treturn *newMnt.IpAddress, nil\n\t}\n\n\t// We now have the go ahead to create one instead.\n\tnewFs, err := CreateFilesystem(e, n)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tnewMnt, err := CreateMountTarget(e, *newFs.FileSystemId, s)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tlog.Printf(\"Created new EFS Filesytem with mount point: %s\", *newMnt.IpAddress)\n\treturn *newMnt.IpAddress, nil\n}", "func (g *EWgraph) E() int {\n\treturn g.e\n}", "func (c *Client) D3Era(ctx context.Context, eraID int) (*d3gd.Era, *Header, error) {\n\tdat, header, err := c.getStructDataNoNamespace(ctx,\n\t\tfmt.Sprintf(\"/data/d3/era/%d\", eraID),\n\t\t&d3gd.Era{},\n\t)\n\treturn dat.(*d3gd.Era), header, err\n}", "func simpleEC(this js.Value, inputs []js.Value) interface{} {\n\tvar suite = suites.MustFind(\"Ed25519\")\n\tvar args map[string]interface{}\n\tjson.Unmarshal([]byte(inputs[0].String()), &args)\n\tscalar := suite.Scalar()\n\tscalarB, _ := base64.StdEncoding.DecodeString(args[\"scalar\"].(string))\n\tscalar.UnmarshalBinary(scalarB)\n\tvar resultB []byte\n\tfor i := 0; i < 1; i++ {\n\t\tresultB, _ = suite.Point().Mul(scalar, nil).MarshalBinary()\n\t}\n\targs[\"result\"] = base64.StdEncoding.EncodeToString(resultB)\n\t//args[\"resultTest\"] = result.String()\n\targs[\"Accepted\"] = \"true\"\n\treturn args\n}", "func Erf(x float64) float64 {\n\t// Constants\n\ta1 := 0.254829592\n\ta2 := -0.284496736\n\ta3 := 1.421413741\n\ta4 := -1.453152027\n\ta5 := 1.061405429\n\tp := 0.3275911\n\n\t// Save the sign of x\n\tvar sign float64\n\tif x < 0.0 {\n\t\tsign = -1.0\n\t} else {\n\t\tsign = 1.0\n\t}\n\tx = math.Abs(x)\n\n\t// Formula 7.1.26 given in Abramowitz and Stegun\n\tt := 1.0 / (1.0 + p*x)\n\ty := 1.0 - ((((a5*t+a4)*t+a3)*t+a2)*t+a1)*t*math.Pow(math.E, -x*x)\n\treturn sign * y\n}", "func NewEasee(user, password, charger string, timeout time.Duration) (*Easee, error) {\n\tlog := util.NewLogger(\"easee\").Redact(user, password)\n\n\tif !sponsor.IsAuthorized() {\n\t\treturn nil, api.ErrSponsorRequired\n\t}\n\n\tc := &Easee{\n\t\tHelper: request.NewHelper(log),\n\t\tcharger: charger,\n\t\tlog: log,\n\t\tcurrent: 6, // default current\n\t\tdone: make(chan struct{}),\n\t\tcmdC: make(chan easee.SignalRCommandResponse),\n\t\tobsC: make(chan easee.Observation),\n\t\tobsTime: make(map[easee.ObservationID]time.Time),\n\t}\n\n\tc.Client.Timeout = timeout\n\n\tts, err := easee.TokenSource(log, user, password)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\n\t// replace client transport with authenticated transport\n\tc.Client.Transport = &oauth2.Transport{\n\t\tSource: ts,\n\t\tBase: c.Client.Transport,\n\t}\n\n\t// find charger\n\tif charger == \"\" {\n\t\tchargers, err := c.chargers()\n\t\tif err != nil {\n\t\t\treturn c, err\n\t\t}\n\n\t\tif len(chargers) != 1 {\n\t\t\treturn c, fmt.Errorf(\"cannot determine charger id, found: %v\", lo.Map(chargers, func(c easee.Charger, _ int) string { return c.ID }))\n\t\t}\n\n\t\tc.charger = chargers[0].ID\n\t}\n\n\t// find site\n\tsite, err := c.chargerSite(c.charger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// find single charger per circuit\n\tfor _, circuit := range site.Circuits {\n\t\tif len(circuit.Chargers) > 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, charger := range circuit.Chargers {\n\t\t\tif charger.ID == c.charger {\n\t\t\t\tc.site = site.ID\n\t\t\t\tc.circuit = circuit.ID\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tclient, err := signalr.NewClient(context.Background(),\n\t\tsignalr.WithConnector(c.connect(ts)),\n\t\tsignalr.WithReceiver(c),\n\t\tsignalr.Logger(easee.SignalrLogger(c.log.TRACE), false),\n\t)\n\n\tif err == nil {\n\t\tc.subscribe(client)\n\n\t\tclient.Start()\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), request.Timeout)\n\t\tdefer cancel()\n\t\terr = <-client.WaitForState(ctx, signalr.ClientConnected)\n\t}\n\n\t// wait for first update\n\tselect {\n\tcase <-c.done:\n\tcase <-time.After(request.Timeout):\n\t\terr = os.ErrDeadlineExceeded\n\t}\n\n\tif err == nil {\n\t\tgo c.refresh()\n\t}\n\n\treturn c, err\n}", "func (s String) FloatE() (float64, error) {\n\tf, err := cast.ToFloat64E(string(s))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn f, nil\n}", "func Read(r io.Reader) (geom.T, error) {\n\tewkbByteOrder, err := wkbcommon.ReadByte(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar byteOrder binary.ByteOrder\n\tswitch ewkbByteOrder {\n\tcase wkbcommon.XDRID:\n\t\tbyteOrder = XDR\n\tcase wkbcommon.NDRID:\n\t\tbyteOrder = NDR\n\tdefault:\n\t\treturn nil, wkbcommon.ErrUnknownByteOrder(ewkbByteOrder)\n\t}\n\n\tewkbGeometryType, err := wkbcommon.ReadUInt32(r, byteOrder)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := wkbcommon.Type(ewkbGeometryType)\n\n\tvar layout geom.Layout\n\tswitch t & (ewkbZ | ewkbM) {\n\tcase 0:\n\t\tlayout = geom.XY\n\tcase ewkbZ:\n\t\tlayout = geom.XYZ\n\tcase ewkbM:\n\t\tlayout = geom.XYM\n\tcase ewkbZ | ewkbM:\n\t\tlayout = geom.XYZM\n\tdefault:\n\t\treturn nil, wkbcommon.ErrUnknownType(t)\n\t}\n\n\tvar srid uint32\n\tif ewkbGeometryType&ewkbSRID != 0 {\n\t\tsrid, err = wkbcommon.ReadUInt32(r, byteOrder)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tswitch t &^ (ewkbZ | ewkbM | ewkbSRID) {\n\tcase wkbcommon.PointID:\n\t\tflatCoords, err := wkbcommon.ReadFlatCoords0(r, byteOrder, layout.Stride())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn geom.NewPointFlatMaybeEmpty(layout, flatCoords).SetSRID(int(srid)), nil\n\tcase wkbcommon.LineStringID:\n\t\tflatCoords, err := wkbcommon.ReadFlatCoords1(r, byteOrder, layout.Stride())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn geom.NewLineStringFlat(layout, flatCoords).SetSRID(int(srid)), nil\n\tcase wkbcommon.PolygonID:\n\t\tflatCoords, ends, err := wkbcommon.ReadFlatCoords2(r, byteOrder, layout.Stride())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn geom.NewPolygonFlat(layout, flatCoords, ends).SetSRID(int(srid)), nil\n\tcase wkbcommon.MultiPointID:\n\t\tn, err := wkbcommon.ReadUInt32(r, byteOrder)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif limit := wkbcommon.MaxGeometryElements[1]; limit >= 0 && int(n) > limit {\n\t\t\treturn nil, wkbcommon.ErrGeometryTooLarge{Level: 1, N: int(n), Limit: limit}\n\t\t}\n\t\tmp := geom.NewMultiPoint(layout).SetSRID(int(srid))\n\t\tfor i := uint32(0); i < n; i++ {\n\t\t\tg, err := Read(r)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tp, ok := g.(*geom.Point)\n\t\t\tif !ok {\n\t\t\t\treturn nil, wkbcommon.ErrUnexpectedType{Got: g, Want: &geom.Point{}}\n\t\t\t}\n\t\t\tif err = mp.Push(p); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\treturn mp, nil\n\tcase wkbcommon.MultiLineStringID:\n\t\tn, err := wkbcommon.ReadUInt32(r, byteOrder)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif limit := wkbcommon.MaxGeometryElements[2]; limit >= 0 && int(n) > limit {\n\t\t\treturn nil, wkbcommon.ErrGeometryTooLarge{Level: 2, N: int(n), Limit: limit}\n\t\t}\n\t\tmls := geom.NewMultiLineString(layout).SetSRID(int(srid))\n\t\tfor i := uint32(0); i < n; i++ {\n\t\t\tg, err := Read(r)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tp, ok := g.(*geom.LineString)\n\t\t\tif !ok {\n\t\t\t\treturn nil, wkbcommon.ErrUnexpectedType{Got: g, Want: &geom.LineString{}}\n\t\t\t}\n\t\t\tif err = mls.Push(p); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\treturn mls, nil\n\tcase wkbcommon.MultiPolygonID:\n\t\tn, err := wkbcommon.ReadUInt32(r, byteOrder)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif limit := wkbcommon.MaxGeometryElements[3]; limit >= 0 && int(n) > limit {\n\t\t\treturn nil, wkbcommon.ErrGeometryTooLarge{Level: 3, N: int(n), Limit: limit}\n\t\t}\n\t\tmp := geom.NewMultiPolygon(layout).SetSRID(int(srid))\n\t\tfor i := uint32(0); i < n; i++ {\n\t\t\tg, err := Read(r)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tp, ok := g.(*geom.Polygon)\n\t\t\tif !ok {\n\t\t\t\treturn nil, wkbcommon.ErrUnexpectedType{Got: g, Want: &geom.Polygon{}}\n\t\t\t}\n\t\t\tif err = mp.Push(p); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\treturn mp, nil\n\tcase wkbcommon.GeometryCollectionID:\n\t\tn, err := wkbcommon.ReadUInt32(r, byteOrder)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif limit := wkbcommon.MaxGeometryElements[1]; limit >= 0 && int(n) > limit {\n\t\t\treturn nil, wkbcommon.ErrGeometryTooLarge{Level: 1, N: int(n), Limit: limit}\n\t\t}\n\t\tgc := geom.NewGeometryCollection().SetSRID(int(srid))\n\t\tfor i := uint32(0); i < n; i++ {\n\t\t\tg, err := Read(r)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif err = gc.Push(g); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\t// If EMPTY, mark the collection with a fixed layout to differentiate\n\t\t// GEOMETRYCOLLECTION EMPTY between 2D/Z/M/ZM.\n\t\tif gc.Empty() && gc.NumGeoms() == 0 {\n\t\t\tif err := gc.SetLayout(layout); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\treturn gc, nil\n\tdefault:\n\t\treturn nil, wkbcommon.ErrUnsupportedType(ewkbGeometryType)\n\t}\n}", "func NewComputeServiceE(t *testing.T) (*compute.Service, error) {\n\tctx := context.Background()\n\n\tclient, err := google.DefaultClient(ctx, compute.CloudPlatformScope)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to get default client: %v\", err)\n\t}\n\n\tservice, err := compute.New(client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn service, nil\n}", "func (a *AllApiService) EventGetEnterpriseEvents(ctx _context.Context, body EventGetEnterpriseEvents) (EventGetEnterpriseEventsResult, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue EventGetEnterpriseEventsResult\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/event/getEnterpriseEvents\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &body\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v EventGetEnterpriseEventsResult\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func TestWCDMELcdm(t *testing.T) {\n\tcos := WCDM{H0: 70, Om0: 0.27, Ol0: 0.73, W0: -1}\n\t// Check value of E(z=1.0)\n\t// OM, OL, OK, z = 0.27, 0.73, 0.0, 1.0\n\t// sqrt(OM*(1+z)**3 + OK * (1+z)**2 + OL)\n\t// sqrt(0.27*(1+1.0)**3 + 0.0 * (1+1.0)**2 + 0.73)\n\t// sqrt(0.27*8 + 0 + 0.73)\n\t// sqrt(2.89)\n\tz := 1.0\n\texp := 1.7\n\trunTest(cos.E, z, exp, eTol, t, 0)\n\n\texp = 1 / 1.7\n\trunTest(cos.Einv, z, exp, eTol, t, 0)\n}", "func NewECE(maxAge time.Duration, logFile string, maxLogSize int, maxLogBackups int, maxLogAge int, logCompress bool) *ECE {\n\tlogObj := log.New(os.Stdout, \"\", 0)\n\n\tlogObj.SetOutput(&lumberjack.Logger{\n\t\tFilename: logFile,\n\t\tMaxSize: maxLogSize,\n\t\tMaxBackups: maxLogBackups,\n\t\tMaxAge: maxLogAge,\n\t\tCompress: logCompress,\n\t})\n\n\ta := &ECE{\n\t\tTtl: maxAge,\n\t\tlogger: logObj,\n\t\tEvents: make(map[string]*Event),\n\t}\n\n\treturn a\n}", "func GetEarthquake(id string) *Earthquake {\n\tearthquakeDetails := earthquakeData()\n\n\tfor _, locFeature := range earthquakeDetails.Features {\n\t\tif locFeature.ID == id {\n\t\t\treturn featureToEarthquakeFormat(locFeature)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (e *Ellipsoid) Direct(\n\tlat1, lon1, azi1, s12 float64,\n\tlat2, lon2, azi2 *float64,\n) {\n\tC.geod_direct(&e.g,\n\t\tC.double(lat1), C.double(lon1), C.double(azi1), C.double(s12),\n\t\t(*C.double)(lat2), (*C.double)(lon2), (*C.double)(azi2))\n}", "func FindFermi(n int, num_electrons float64, Ecache EnergyCache, all_bands_at_once bool) (float64, error) {\n\tstatecount_error := func(E float64) float64 {\n\t\tcount := NumStates(E, n, Ecache, all_bands_at_once)\n\t\treturn count - num_electrons\n\t}\n\temin := Ecache.MinE()\n\temax := Ecache.MaxE()\n\ttoln := 1e-10\n\tmaxiter := 300\n\tE_Fermi, err := Bisect(statecount_error, emin, emax, toln, maxiter)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\treturn E_Fermi, nil\n}", "func (vca *VapmControlApi) GetEulasInfo(ctx context.Context, params PUpdates) (*PEulasInfo, error) {\n\tpostData, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequest, err := http.NewRequest(\"POST\", vca.client.Server+\"/api/v1.0/VapmControlApi.GetEulasInfo\", bytes.NewBuffer(postData))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpEulasInfo := new(PEulasInfo)\n\t_, err = vca.client.Do(ctx, request, &pEulasInfo)\n\treturn pEulasInfo, err\n}", "func EasyExponentiation(g *Cyclo6, f *Fp12) {\n\tvar t0, t1, p Fp12\n\tp.Frob(f) // p = f^(p)\n\tp.Frob(&p) // p = f^(p^2)\n\tt0.Mul(&p, f) // t0 = f^(p^2 + 1)\n\tt1.Frob(&t0) // t1 = f^(p^2 + 1)*(p)\n\tt1.Frob(&t1) // t1 = f^(p^2 + 1)*(p^2)\n\tt1.Frob(&t1) // t1 = f^(p^2 + 1)*(p^3)\n\tt1.Frob(&t1) // t1 = f^(p^2 + 1)*(p^4)\n\tt1.Frob(&t1) // t1 = f^(p^2 + 1)*(p^5)\n\tt1.Frob(&t1) // t1 = f^(p^2 + 1)*(p^6)\n\tt0.Inv(&t0) // t0 = f^-(p^2 + 1)\n\tt0.Mul(&t0, &t1) // t0 = f^(p^2 + 1)*(p^6 - 1)\n\n\t*g = (Cyclo6)(t0)\n}", "func testEquation(t *testing.T, eqn, expected string) {\n\tgin.SetMode(gin.TestMode)\n\ttestRouter := SetupRouter()\n\n\tresp := performSolveRequest(testRouter, eqn)\n\n\t// Check status code is what we expect\n\tif resp.Code != http.StatusOK {\n\t\tt.Errorf(\"Unexpected response code: got %v want %v\", resp.Code, http.StatusOK)\n\t}\n\n\t// Check response body is what we expect\n\texpectedMap := map[string]string{\"result\": expected}\n\texpectedJSON, _ := json.Marshal(expectedMap)\n\n\texpectedJSONString := string(expectedJSON)\n\tif resp.Body.String() != expectedJSONString {\n\t\tt.Errorf(\"handler returned unexpected body: got %v want %v\",\n\t\t\tresp.Body.String(), expectedJSONString)\n\t}\n}", "func Teo2eps() Mat3 {\n\t/*no:=complex(2.1895, 0)\n\tne:=complex(2.3309, 0)*/\n\n\treturn Uniaxial(5.1984, 6.0025)\n}", "func (s *Service) ENoteConfigurationsGet() *ENoteConfigurationsGetOp {\n\treturn &ENoteConfigurationsGetOp{\n\t\tCredential: s.credential,\n\t\tMethod: \"GET\",\n\t\tPath: \"settings/enote_configuration\",\n\t\tAccept: \"application/json\",\n\t\tQueryOpts: make(url.Values),\n\t\tVersion: esign.APIv2,\n\t}\n}", "func solveEqn(s string, n int)map[byte]float64{\n rhs := make([]float64, n)\n //res := make([]int, n)\n co_eff := make([][]float64, n)\n m := make(map[byte]int)\n var k, e bool\n var i, j, t, c int\n p := true\n co_eff[0] = make([]float64,n)\n for ;i < len(s); i++{\n if s[i] == 10{ //new line; new equation signal\n if c != 0{\n if p{\n rhs[j] += float64(c)\n }else{\n rhs[j] -= float64(c)\n }\n }\n e = false\n p = true\n c = 0\n j += 1\n if j < n{\n co_eff[j] = make([]float64, n)\n }\n }else if s[i] > 47 && s[i] < 58{ //number\n c = c*10 + int(s[i]-48)\n }else if s[i] == 43{ //\"+\"\n if (e && !p) || (!e && p){\n rhs[j] -= float64(c)\n }else{\n rhs[j] += float64(c)\n }\n p = true\n c = 0\n }else if s[i] == 45{ //\"-\"\n if (e && !p) || (!e && p){\n rhs[j] -= float64(c)\n }else{\n rhs[j] += float64(c)\n }\n p = false\n c = 0\n }else if s[i] == 61{ //\"=\"\n if (e && !p) || (!e && p){\n rhs[j] -= float64(c)\n }else{\n rhs[j] += float64(c)\n }\n e = true\n p = true\n c = 0\n }else{ //char_variable\n _, k = m[s[i]]\n if !k{\n m[s[i]] = len(m)\n }\n if c == 0{ //x + y = 1; coefficient of x == 1\n c = 1\n }\n //fmt.Println(j, s[i],m[s[i]])\n if (e && !p) || (!e && p){\n co_eff[j][m[s[i]]] += float64(c)\n }else{\n co_eff[j][m[s[i]]] -= float64(c)\n }\n c = 0\n }\n }\n// printmatrix(co_eff)\n// fmt.Println(rhs)\n /*\n Gauss elimination method, turn co_eff into an upper triangular matirx using\n row operations (also perform the same operations on rhs) and than solve for each\n variable starting from the end row(i == n-1)\n */\n\n for i = 0; i < n-1; i++{\n j = i+1\n c = i\n if co_eff[i][c] == 0{\n k = false\n //find row with non zero value at col == c if it doesnt exist than return\n for ;j < n; j++{\n if co_eff[j][c] != 0{\n k = true\n break\n }\n }\n if k{\n //swap i and j rows\n rhs[j], rhs[i] = rhs[i], rhs[j]\n for t = c; t < n; t++{ //row operation\n co_eff[i][t], co_eff[j][t] = co_eff[j][t], co_eff[i][t]\n }\n j = j+1\n }else{\n return map[byte]float64{} //infinite or no solution case\n }\n }\n\n for ;j < n; j++{\n if co_eff[j][c] == 0{\n continue\n }\n co_eff[j][c] /= co_eff[i][c]\n rhs[j] -= co_eff[j][c]*rhs[i]\n for t = n-1; t > c; t--{//row operation\n co_eff[j][t] -= co_eff[j][c]*co_eff[i][t]\n }\n co_eff[j][c] = 0\n }\n }\n fmt.Println(\"row echleon form\")\n printmatrix(co_eff)\n fmt.Println(\"rhs\", rhs)\n for i = n-1; i >= 0; i--{\n for j = i+1; j < n; j++{\n rhs[i] -= co_eff[i][j]*rhs[j]\n }\n rhs[i] /= co_eff[i][i]\n }\n res := make(map[byte]float64)\n for b, i := range m{\n res[b] = rhs[i]\n }\n return res\n}", "func (etf *Etf) RefineEtf(kernel int) {\n\twidth, height := etf.flowField.Cols(), etf.flowField.Rows()\n\tetf.wg.Add(width * height)\n\n\tfor y := 0; y < height; y++ {\n\t\tfor x := 0; x < width; x++ {\n\t\t\t// Spawn computation into separate goroutines\n\t\t\tgo func(y, x int) {\n\t\t\t\tetf.mu.Lock()\n\t\t\t\tetf.computeNewVector(x, y, kernel)\n\t\t\t\tetf.mu.Unlock()\n\n\t\t\t\tetf.wg.Done()\n\t\t\t}(y, x)\n\t\t}\n\t}\n\tetf.wg.Wait()\n\tetf.flowField = etf.refinedEtf.Clone()\n}", "func GetE2EConfig(mode ops.Mode, cmd *cobra.Command) (*ops.E2EConfig, error) {\n\tflags := cmd.PersistentFlags()\n\tcfg := mode.Get().E2EConfig\n\tif flags.Changed(e2eFocusFlag) {\n\t\tfocus, err := flags.GetString(e2eFocusFlag)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"couldn't retrieve focus flag\")\n\t\t}\n\t\tcfg.Focus = focus\n\t}\n\n\tif flags.Changed(e2eSkipFlag) {\n\t\tskip, err := flags.GetString(e2eSkipFlag)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"couldn't retrieve skip flag\")\n\t\t}\n\t\tcfg.Skip = skip\n\t}\n\treturn &cfg, nil\n}", "func (a *ImagedObjectApiService) V1EditionsEditionIdImagedObjectsGet(ctx _context.Context, editionId int32, localVarOptionals *V1EditionsEditionIdImagedObjectsGetOpts) (ImagedObjectListDto, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ImagedObjectListDto\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/v1/editions/{editionId}/imaged-objects\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"editionId\"+\"}\", _neturl.QueryEscape(parameterToString(editionId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif localVarOptionals != nil && localVarOptionals.Optional.IsSet() {\n\t\tt:=localVarOptionals.Optional.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"optional\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"optional\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func Encuentra_E() {\n\n\tfor i := 0; i < 15; i++ {\n\t\tfor j := 0; j < 15; j++ {\n\t\t\tif laberinto[i][j] == \"E\" {\n\t\t\t\tx = i\n\t\t\t\ty = j\n\t\t\t}\n\t\t}\n\t}\n}", "func (o Orbit) epsilons() (float64, float64, float64) {\n\tif o.Origin.Equals(Sun) {\n\t\treturn distanceLgε, eccentricityLgε, angleLgε\n\t}\n\treturn distanceε, eccentricityε, angleε\n}", "func (o LookupSharedImageResultOutput) Eula() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSharedImageResult) string { return v.Eula }).(pulumi.StringOutput)\n}", "func E(args ...interface{}) error {\n\te := &posError{}\n\tupdate(e, args)\n\treturn e\n}", "func (d Degrees) E6() int32 { return round(float64(d * 1e6)) }", "func ceClient(uri string, insecure bool, encoding string) (ceclient.Client, error) {\n\ttlsConfig := tls.Config{\n\t\tInsecureSkipVerify: insecure, //nolint:gosec\n\t}\n\thttpTransport := &http.Transport{TLSClientConfig: &tlsConfig}\n\n\t// Create protocol and client\n\ttransport, err := cloudevents.NewHTTP(cloudevents.WithTarget(uri), cloudevents.WithRoundTripper(httpTransport))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"create cloud events http transport\")\n\t}\n\n\tclientOpts := []ceclient.Option{ceclient.WithUUIDs()}\n\tswitch encoding {\n\tcase \"structured\":\n\t\tclientOpts = append(clientOpts, ceclient.WithForceStructured())\n\tcase \"binary\":\n\t\tclientOpts = append(clientOpts, ceclient.WithForceBinary())\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported encoding type specified: %q\", encoding)\n\t}\n\n\tclient, err := cloudevents.NewClient(transport, clientOpts...)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"create cloud events client\")\n\t}\n\n\treturn client, nil\n}", "func (b *BBox) NE() *LatLng {\n\treturn b[1]\n}", "func (c *ClientMgr) Ecs() *ecs.Client {\n\tc.Lock()\n\tdefer c.Unlock()\n\ttokenUpdated, err := c.refreshToken()\n\tlogrus.Debugf(\"Token update: %v, %v\", tokenUpdated, err)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Error refresh OpenAPI token: %v\", err)\n\t}\n\treturn c.ecs\n}", "func DetermineComplexArithmeticResult(function, nStr string, x float64, n int) float64 {\n\tswitch function {\n\tcase \"ln\":\n\t\treturn NaturalLog(x, n)\n\tcase \"log\":\n\t\treturn LogBaseTen(x, n)\n\tcase \"exponent\", \"e\":\n\t\treturn Exponent(x, n)\n\tdefault:\n\t\ta, _ := strconv.ParseFloat(nStr, 64)\n\t\treturn HeronsSquareRoot(x, a)\n\t}\n}", "func (c *CorporationResolver) CEOID() *int32 {\n\treturn &c.corp.CEOID\n}", "func calcEquation(equations [][]string, values []float64, queries [][]string) []float64 {\n tree := make(map[string]map[string]float64, 0)\n\tfor index, equation := range equations {\n\t\tif tree[equation[0]] == nil {\n\t\t\ttree[equation[0]] = make(map[string]float64, 0)\n\t\t}\n\t\ttree[equation[0]][equation[1]] = values[index]\n\t\tif tree[equation[1]] == nil {\n\t\t\ttree[equation[1]] = make(map[string]float64, 0)\n\t\t}\n\t\ttree[equation[1]][equation[0]] = 1/values[index]\n\t}\n\n\troad := make([]float64, 0)\n\thas := make(map[string]bool, 0)\n\tvar find func (tree map[string]map[string]float64, a, b string)(bool)\n\tfind = func (tree map[string]map[string]float64, a, b string)(bool){\n\t\tm, ok := tree[a]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\tif val, ok := m[b]; ok {\n\t\t\troad = append(road, val)\n\t\t\treturn true\n\t\t}\n\t\tfor mm, f := range m {\n\t\t\tif has[mm] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\troad = append(road, f)\n\t\t\thas[mm] = true\n\t\t\tb := find(tree, mm, b)\n\t\t\tif b {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\troad = road[0:len(road)-1]\n\t\t\thas[mm] = false\n\t\t}\n\t\treturn false\n\t}\n\n\tresult := make([]float64, 0, len(queries))\n\tfor _, query := range queries {\n\t\tbol := find(tree, query[0], query[1])\n\t\tif bol {\n\t\t\tval := 1.0\n\t\t\tfor _,v := range road {\n\t\t\t\tval *= v\n\t\t\t}\n\t\t\tresult = append(result, val)\n\t\t} else {\n\t\t\tresult = append(result, -1.0)\n\t\t}\n\t\troad = make([]float64, 0)\n\t\thas = make(map[string]bool, 0)\n\t}\n\treturn result\n}", "func (wf *wavefrontMaterial) GetExpression() string {\n\tif wf.MaterialExpression != \"\" {\n\t\treturn wf.MaterialExpression\n\t}\n\n\tisSpecularReflection := wf.Ks.MaxComponent() > 0.0 || wf.KsTex != \"\"\n\tisEmissive := wf.Ke.MaxComponent() > 0.0 || wf.KeTex != \"\"\n\n\tvar bxdf material.BxdfType\n\tvar exprArgs = make([]string, 0)\n\tswitch {\n\tcase isSpecularReflection && wf.Ni == 0.0:\n\t\tbxdf = material.BxdfConductor\n\n\t\tif wf.KsTex != \"\" {\n\t\t\texprArgs = append(exprArgs, fmt.Sprintf(\"%s: %q\", material.ParamSpecularity, wf.KsTex))\n\t\t} else if wf.Ks.MaxComponent() > 0.0 {\n\t\t\texprArgs = append(exprArgs, fmt.Sprintf(\"%s: %v\", material.ParamSpecularity, wf.Ks))\n\t\t}\n\tcase isSpecularReflection && wf.Ni != 0.0:\n\t\tbxdf = material.BxdfDielectric\n\n\t\tif wf.KsTex != \"\" {\n\t\t\texprArgs = append(exprArgs, fmt.Sprintf(\"%s: %q\", material.ParamSpecularity, wf.KsTex))\n\t\t} else if wf.Ks.MaxComponent() > 0.0 {\n\t\t\texprArgs = append(exprArgs, fmt.Sprintf(\"%s: %v\", material.ParamSpecularity, wf.Ks))\n\t\t}\n\n\t\tif wf.TfTex != \"\" {\n\t\t\texprArgs = append(exprArgs, fmt.Sprintf(\"%s: %q\", material.ParamTransmittance, wf.TfTex))\n\t\t} else if wf.Tf.MaxComponent() > 0.0 {\n\t\t\texprArgs = append(exprArgs, fmt.Sprintf(\"%s: %v\", material.ParamTransmittance, wf.Tf))\n\t\t}\n\n\t\texprArgs = append(exprArgs, fmt.Sprintf(\"%s: %v\", material.ParamIntIOR, wf.Ni))\n\tcase isEmissive:\n\t\tbxdf = material.BxdfEmissive\n\n\t\tif wf.KeTex != \"\" {\n\t\t\texprArgs = append(exprArgs, fmt.Sprintf(\"%s: %q\", material.ParamRadiance, wf.KeTex))\n\t\t} else if wf.Ke.MaxComponent() > 0.0 {\n\t\t\texprArgs = append(exprArgs, fmt.Sprintf(\"%s: %v\", material.ParamRadiance, wf.Ke))\n\t\t}\n\n\t\tif wf.KeScaler != 0 {\n\t\t\texprArgs = append(exprArgs, fmt.Sprintf(\"%s: %v\", material.ParamScale, wf.KeScaler))\n\t\t}\n\tdefault:\n\t\tbxdf = material.BxdfDiffuse\n\n\t\tif wf.KdTex != \"\" {\n\t\t\texprArgs = append(exprArgs, fmt.Sprintf(\"%s: %q\", material.ParamReflectance, wf.KdTex))\n\t\t} else if wf.Kd.MaxComponent() > 0.0 {\n\t\t\texprArgs = append(exprArgs, fmt.Sprintf(\"%s: %v\", material.ParamReflectance, wf.Kd))\n\t\t}\n\t}\n\n\tmaterialExpr := bxdf.String() + \"(\" + strings.Join(exprArgs, \", \") + \")\"\n\n\t// Apply bump map modifier (prefer normal maps to bump maps)\n\tif wf.NormalTex != \"\" {\n\t\tmaterialExpr = fmt.Sprintf(\"normalMap(%s, %q)\", materialExpr, wf.NormalTex)\n\t} else if wf.BumpTex != \"\" {\n\t\tmaterialExpr = fmt.Sprintf(\"bumpMap(%s, %q)\", materialExpr, wf.BumpTex)\n\t}\n\n\treturn materialExpr\n}", "func (me XsdGoPkgHasElem_East) EastDefault() Tangle180Type {\r\n\tvar x = new(Tangle180Type)\r\n\tx.Set(\"180.0\")\r\n\treturn *x\r\n}", "func (a *AllApiService) EdgeSetEdgeEnterpriseConfiguration(ctx _context.Context, body EdgeSetEdgeEnterpriseConfiguration) (EdgeSetEdgeEnterpriseConfigurationResult, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue EdgeSetEdgeEnterpriseConfigurationResult\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/edge/setEdgeEnterpriseConfiguration\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &body\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v EdgeSetEdgeEnterpriseConfigurationResult\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func makeFloatFromMandE(negative bool, e int, m []byte, tmp []byte) float64 {\n\t// ±.dddde±dd.\n\tb := tmp[:0]\n\tif n := len(m)*2 + 6; cap(b) < n {\n\t\tb = make([]byte, 0, n)\n\t}\n\tif negative {\n\t\tb = append(b, '-')\n\t}\n\tb = append(b, '.')\n\tfor i, v := range m {\n\t\tt := int(v)\n\t\tif i == len(m) {\n\t\t\tt--\n\t\t}\n\t\tt /= 2\n\t\tb = append(b, byte(t/10)+'0', byte(t%10)+'0')\n\t}\n\tb = append(b, 'e')\n\te = 2 * e\n\tif e < 0 {\n\t\tb = append(b, '-')\n\t\te = -e\n\t} else {\n\t\tb = append(b, '+')\n\t}\n\n\tvar buf [3]byte\n\ti := len(buf)\n\tfor e >= 10 {\n\t\ti--\n\t\tbuf[i] = byte(e%10 + '0')\n\t\te /= 10\n\t}\n\ti--\n\tbuf[i] = byte(e + '0')\n\n\tb = append(b, buf[i:]...)\n\n\t// We unsafely convert the []byte to a string to avoid the usual allocation\n\t// when converting to a string.\n\tf, err := strconv.ParseFloat(*(*string)(unsafe.Pointer(&b)), 64)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}", "func entrance1(size v3.Vec) (sdf.SDF3, error) {\n\n\tconst rows = 3\n\tconst cols = 16\n\tconst holeRadius = 3.2 * 0.5\n\n\thole, err := sdf.Circle2D(holeRadius)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsize.X -= 2 * holeRadius\n\tsize.Y -= 2 * holeRadius\n\tdx := size.X / (cols - 1)\n\tdy := size.Y / (rows - 1)\n\txOfs := -size.X / 2\n\tyOfs := size.Y / 2\n\n\tpositions := []v2.Vec{}\n\tx := xOfs\n\tfor i := 0; i < cols; i++ {\n\t\ty := yOfs\n\t\tfor j := 0; j < rows; j++ {\n\t\t\tpositions = append(positions, v2.Vec{x, y})\n\t\t\ty -= dy\n\t\t}\n\t\tx += dx\n\t}\n\ts := sdf.Multi2D(hole, positions)\n\n\treturn sdf.Extrude3D(s, size.Z), nil\n}", "func (c *container) Ellipse(cx, cy, rx, ry float64) *Ellipse {\n\te := &Ellipse{Cx: cx, Cy: cy, Rx: rx, Ry: ry}\n\tc.contents = append(c.contents, e)\n\n\treturn e\n}", "func (a *ImagedObjectApiService) V1EditionsEditionIdImagedObjectsImagedObjectIdGet(ctx _context.Context, editionId int32, imagedObjectId string, localVarOptionals *V1EditionsEditionIdImagedObjectsImagedObjectIdGetOpts) (ImagedObjectDto, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ImagedObjectDto\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/v1/editions/{editionId}/imaged-objects/{imagedObjectId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"editionId\"+\"}\", _neturl.QueryEscape(parameterToString(editionId, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"imagedObjectId\"+\"}\", _neturl.QueryEscape(parameterToString(imagedObjectId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif localVarOptionals != nil && localVarOptionals.Optional.IsSet() {\n\t\tt:=localVarOptionals.Optional.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"optional\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"optional\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func eawk(fm *Frame, f Callable, inputs Inputs) error {\n\tbroken := false\n\tvar err error\n\tinputs(func(v interface{}) {\n\t\tif broken {\n\t\t\treturn\n\t\t}\n\t\tline, ok := v.(string)\n\t\tif !ok {\n\t\t\tbroken = true\n\t\t\terr = ErrInputOfEawkMustBeString\n\t\t\treturn\n\t\t}\n\t\targs := []interface{}{line}\n\t\tfor _, field := range eawkWordSep.Split(strings.Trim(line, \" \\t\"), -1) {\n\t\t\targs = append(args, field)\n\t\t}\n\n\t\tnewFm := fm.fork(\"fn of eawk\")\n\t\t// TODO: Close port 0 of newFm.\n\t\tex := f.Call(newFm, args, NoOpts)\n\t\tnewFm.Close()\n\n\t\tif ex != nil {\n\t\t\tswitch Cause(ex) {\n\t\t\tcase nil, Continue:\n\t\t\t\t// nop\n\t\t\tcase Break:\n\t\t\t\tbroken = true\n\t\t\tdefault:\n\t\t\t\tbroken = true\n\t\t\t\terr = ex\n\t\t\t}\n\t\t}\n\t})\n\treturn err\n}", "func latLon2Grid(lat, lon float64, from eDatum, to gGrid) (int, int) {\n\t// Datum data for Lat/Lon to TM conversion\n\ta := Datum[from].a\n\te := Datum[from].e // sqrt(esq);\n\tb := Datum[from].b\n\n\t//===============\n\t// Lat/Lon -> TM\n\t//===============\n\tslat1 := math.Sin(lat)\n\tclat1 := math.Cos(lat)\n\tclat1sq := clat1 * clat1\n\ttanlat1sq := slat1 * slat1 / clat1sq\n\te2 := e * e\n\te4 := e2 * e2\n\te6 := e4 * e2\n\teg := (e * a / b)\n\teg2 := eg\n\tl1 := 1 - e2/4 - 3*e4/64 - 5*e6/256\n\tl2 := 3*e2/8 + 3*e4/32 + 45*e6/1024\n\tl3 := 15*e4/256 + 45*e6/1024\n\tl4 := 35 * e6 / 3072\n\tM := a * (l1*lat - l2*math.Sin(2*lat) + l3*math.Sin(4*lat) - l4*math.Sin(6*lat))\n\t//double rho = a*(1-e2) / pow((1-(e*slat1)*(e*slat1)),1.5);\n\tnu := a / math.Sqrt(1-(e*slat1)*(e*slat1))\n\tp := lon - grid[to].lon0\n\tk0 := grid[to].k0\n\t// y = northing = K1 + K2p2 + K3p4, where\n\tK1 := M * k0\n\tK2 := k0 * nu * slat1 * clat1 / 2\n\tK3 := (k0 * nu * slat1 * clat1 * clat1sq / 24) * (5 - tanlat1sq + 9*eg2*clat1sq + 4*eg2*eg2*clat1sq*clat1sq)\n\t// ING north\n\tY := K1 + K2*p*p + K3*p*p*p*p - grid[to].falseN\n\n\t// x = easting = K4p + K5p3, where\n\tK4 := k0 * nu * clat1\n\tK5 := (k0 * nu * clat1 * clat1sq / 6) * (1 - tanlat1sq + eg2*clat1*clat1)\n\t// ING east\n\tX := K4*p + K5*p*p*p + grid[to].falseE\n\n\t// final rounded results\n\tE := int(X + 0.5)\n\tN := int(Y + 0.5)\n\treturn E, N\n}", "func BuildEpinio() {\n\ttargets := []string{\"embed_files\", \"build-linux-amd64\"}\n\tif runtime.GOOS != \"linux\" || runtime.GOARCH != \"amd64\" {\n\t\t// we need a different binary to run locally\n\t\ttargets = append(targets, fmt.Sprintf(\"build-%s-%s\", runtime.GOOS, runtime.GOARCH))\n\t}\n\n\toutput, err := proc.Run(Root(), false, \"make\", targets...)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Couldn't build Epinio: %s\\n %s\\n\"+err.Error(), output))\n\t}\n}", "func (me XsdGoPkgHasElems_East) EastDefault() Tangle180Type {\r\n\tvar x = new(Tangle180Type)\r\n\tx.Set(\"180.0\")\r\n\treturn *x\r\n}", "func equation2(output ChanBig, a ChanBig, b ChanBig, c ChanBig, d ChanBig, e ChanBig, count int) {\n\n\ttype EquationInput struct {\n\t\ta *big.Rat\n\t\tb *big.Rat\n\t\tc *big.Rat\n\t\td *big.Rat\n\t\te *big.Rat\n\t}\n\n\t// 1 Setup. Lately it seems like running a large farm is a\n\t// a bad idea that just wastes memory, as equations calculate more\n\t// than fast enough to keep the downstream adders busy.\n\tfarmSize:=1\n\tforkInput:=make(chan *EquationInput, 20)\n\tsignalBack:=make(chan bool, 20)\n\n\t// 2 Fork a series of helpers that run the equation:\n\tfor i:=0; i<farmSize; i++ {\n\t\tgo func() {\n\t\t\tfor values:=range forkInput {\n\t\t\t\toutput <- doEquation(values.a, values.b, values.c, values.d, values.e)\n\t\t\t\tsignalBack<-true\n\t\t\t\t//fmt.Print(\"e\")\n\t\t\t}\n\t\t}()\n\t}\n\n\t// 3 Fork a manager that pumps data to the helpers:\n\tgo func() {\n\t\tfor i:=0; i<count; i++ {\n\t\t\tforkInput <- &EquationInput{<-a, <-b, <-c, <-d, <-e}\n\t\t}\n\t\tclose(forkInput)\n\t}()\n\n\t// 4 Wait on the helpers to finish:\n\tfor i:=0; i<count; i++ {\n\t\t<- signalBack\n\t}\n\tfmt.Println(\"Equations complete \", count)\n\tclose(signalBack)\n\n\t// 5 We are done:\n\tclose(output)\n}", "func NewEaseeFromConfig(other map[string]interface{}) (api.Charger, error) {\n\tcc := struct {\n\t\tUser string\n\t\tPassword string\n\t\tCharger string\n\t\tTimeout time.Duration\n\t}{\n\t\tTimeout: request.Timeout,\n\t}\n\n\tif err := util.DecodeOther(other, &cc); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cc.User == \"\" || cc.Password == \"\" {\n\t\treturn nil, api.ErrMissingCredentials\n\t}\n\n\treturn NewEasee(cc.User, cc.Password, cc.Charger, cc.Timeout)\n}", "func IntsComplex64sE(s []int, f func(s int) (complex64, error)) (complex64s.Complex64s, error) {\n\tm := complex64s.Complex64s(make([]complex64, len(s)))\n\tvar err error\n\tfor i, v := range s {\n\t\tm[i], err = f(v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn m, nil\n}", "func normEasting(deg float64) float64 {\n\t// go's Mod fcn preserves sign on first param\n\tif deg < -180 {\n\t\treturn math.Mod(deg+180, 360) + 180\n\t}\n\tif deg > 180 {\n\t\treturn math.Mod(deg-180, 360) - 180\n\t}\n\treturn deg\n}", "func (e *Engine) ElEq(a tensor.Tensor, b tensor.Tensor, opts ...tensor.FuncOpt) (retVal tensor.Tensor, err error) {\n\tname := constructName2(a, b, \"eq\")\n\n\tif !e.HasFunc(name) {\n\t\treturn nil, errors.Errorf(\"Unable to perform ElEq(). The tensor engine does not have the function %q\", name)\n\t}\n\n\tif err = binaryCheck(a, b); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Basic checks failed for ElEq\")\n\t}\n\n\tvar reuse tensor.DenseTensor\n\tvar safe, toReuse bool\n\tif reuse, safe, toReuse, _, _, err = handleFuncOpts(a.Shape(), a.Dtype(), a.DataOrder(), true, opts...); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Unable to handle funcOpts\")\n\t}\n\n\tvar mem, memB cu.DevicePtr\n\tvar size int64\n\n\tswitch {\n\tcase toReuse:\n\t\tmem = cu.DevicePtr(reuse.Uintptr())\n\t\tmemA := cu.DevicePtr(a.Uintptr())\n\t\tmemSize := int64(a.MemSize())\n\t\te.memcpy(mem, memA, memSize)\n\n\t\tsize = int64(logicalSize(reuse.Shape()))\n\t\tretVal = reuse\n\tcase !safe:\n\t\tmem = cu.DevicePtr(a.Uintptr())\n\t\tretVal = a\n\t\tsize = int64(logicalSize(a.Shape()))\n\tdefault:\n\t\treturn nil, errors.New(\"Impossible state: A reuse tensor must be passed in, or the operation must be unsafe. Incr and safe operations are not supported\")\n\t}\n\n\tmemB = cu.DevicePtr(b.Uintptr())\n\tfn := e.f[name]\n\tgridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ := e.ElemGridSize(int(size))\n\targs := []unsafe.Pointer{\n\t\tunsafe.Pointer(&mem),\n\t\tunsafe.Pointer(&memB),\n\t\tunsafe.Pointer(&size),\n\t}\n\tlogf(\"gx %d, gy %d, gz %d | bx %d by %d, bz %d\", gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ)\n\tlogf(\"CUDADO %q, Mem: %v MemB: %v size %v, args %v\", name, mem, memB, size, args)\n\tlogf(\"LaunchKernel Params. mem: %v. Size %v\", mem, size)\n\te.c.LaunchAndSync(fn, gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ, 0, cu.NoStream, args)\n\treturn\n}", "func (b *Bound) East() float64 {\n\treturn b.ne[0]\n}", "func Radians(zone int, south bool, easting, northing float64) (float64, float64) {\n\n\t// False northing\n\tfn := 0.\n\tif south {\n\t\tfn = utmSouthernHemisphereFalseNorthing\n\t}\n\n\tξPrime := (northing - fn) / (b * kO)\n\tηPrime := (easting - fe) / (b * kO)\n\n\tξ1Prime := h1Prime * math.Sin(2*ξPrime) * math.Cosh(2*ηPrime)\n\tξ2Prime := h2Prime * math.Sin(4*ξPrime) * math.Cosh(4*ηPrime)\n\tξ3Prime := h3Prime * math.Sin(6*ξPrime) * math.Cosh(6*ηPrime)\n\tξ4Prime := h4Prime * math.Sin(8*ξPrime) * math.Cosh(8*ηPrime)\n\tξ0Prime := ξPrime - (ξ1Prime + ξ2Prime + ξ3Prime + ξ4Prime)\n\n\tη1Prime := h1Prime * math.Cos(2*ξPrime) * math.Sinh(2*ηPrime)\n\tη2Prime := h2Prime * math.Cos(4*ξPrime) * math.Sinh(4*ηPrime)\n\tη3Prime := h3Prime * math.Cos(6*ξPrime) * math.Sinh(6*ηPrime)\n\tη4Prime := h4Prime * math.Cos(8*ξPrime) * math.Sinh(8*ηPrime)\n\tη0Prime := ηPrime - (η1Prime + η2Prime + η3Prime + η4Prime)\n\n\tβPrime := math.Asin(math.Sin(ξ0Prime) / math.Cosh(η0Prime))\n\tqPrime := math.Asinh(math.Tan(βPrime))\n\n\tqDoublePrime := qPrime + e*math.Atanh(e*math.Tanh(qPrime))\n\n\t// Iterate until the difference is insignificant.\n\tfor {\n\t\tnextqDoublePrime := qPrime + e*math.Atanh(e*math.Tanh(qDoublePrime))\n\t\tif nextqDoublePrime == qDoublePrime {\n\t\t\tbreak\n\t\t}\n\n\t\tqDoublePrime = nextqDoublePrime\n\t}\n\n\tϕ := math.Atan(math.Sinh(qDoublePrime))\n\tλ := λO(zone) + math.Asin(math.Tanh(η0Prime)/math.Cos(βPrime))\n\treturn ϕ, λ\n}", "func (urlb *URLBuilder) GetEpisole(movieid, ep dna.Int) dna.String {\n\tstr := dna.Sprintf(\"movieid=%v&accesstokenkey=%v&ep=%v\", movieid, ACCESS_TOKEN_KEY, ep)\n\tdata := []byte(str.String())\n\tstrBase64 := base64.StdEncoding.EncodeToString(data)\n\tsign := getMD5(dna.String(strBase64) + SECRET_KEY)\n\treturn dna.Sprintf(\"%vmovieid=%v&accesstokenkey=%v&ep=%v&sign=%v\", BASE_URL, movieid, ACCESS_TOKEN_KEY, ep, sign)\n}", "func (n *ListCmd) RunE(cmd *cobra.Command, args []string) error {\n\tcfg, err := n.factory.Config()\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient, err := n.factory.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\tinputIterators, err := cmdutil.NewRequestInputIterators(cmd, cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// query parameters\n\tquery := flags.NewQueryTemplate()\n\terr = flags.WithQueryParameters(\n\t\tcmd,\n\t\tquery,\n\t\tinputIterators,\n\t\tflags.WithCustomStringSlice(func() ([]string, error) { return cfg.GetQueryParameters(), nil }, \"custom\"),\n\t\tflags.WithStringSliceCSV(\"ids\", \"ids\", \"\"),\n\t\tflags.WithStringValue(\"type\", \"type\"),\n\t\tflags.WithStringValue(\"fragmentType\", \"fragmentType\"),\n\t\tflags.WithStringValue(\"text\", \"text\"),\n\t\tflags.WithBoolValue(\"withParents\", \"withParents\", \"\"),\n\t\tflags.WithBoolValue(\"skipChildrenNames\", \"skipChildrenNames\", \"\"),\n\t)\n\tif err != nil {\n\t\treturn cmderrors.NewUserError(err)\n\t}\n\tcommonOptions, err := cfg.GetOutputCommonOptions(cmd)\n\tif err != nil {\n\t\treturn cmderrors.NewUserError(fmt.Sprintf(\"Failed to get common options. err=%s\", err))\n\t}\n\tcommonOptions.AddQueryParameters(query)\n\n\tqueryValue, err := query.GetQueryUnescape(true)\n\n\tif err != nil {\n\t\treturn cmderrors.NewSystemError(\"Invalid query parameter\")\n\t}\n\n\t// headers\n\theaders := http.Header{}\n\terr = flags.WithHeaders(\n\t\tcmd,\n\t\theaders,\n\t\tinputIterators,\n\t\tflags.WithCustomStringSlice(func() ([]string, error) { return cfg.GetHeader(), nil }, \"header\"),\n\t)\n\tif err != nil {\n\t\treturn cmderrors.NewUserError(err)\n\t}\n\n\t// form data\n\tformData := make(map[string]io.Reader)\n\terr = flags.WithFormDataOptions(\n\t\tcmd,\n\t\tformData,\n\t\tinputIterators,\n\t)\n\tif err != nil {\n\t\treturn cmderrors.NewUserError(err)\n\t}\n\n\t// body\n\tbody := mapbuilder.NewInitializedMapBuilder()\n\terr = flags.WithBody(\n\t\tcmd,\n\t\tbody,\n\t\tinputIterators,\n\t)\n\tif err != nil {\n\t\treturn cmderrors.NewUserError(err)\n\t}\n\n\t// path parameters\n\tpath := flags.NewStringTemplate(\"inventory/managedObjects\")\n\terr = flags.WithPathParameters(\n\t\tcmd,\n\t\tpath,\n\t\tinputIterators,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq := c8y.RequestOptions{\n\t\tMethod: \"GET\",\n\t\tPath: path.GetTemplate(),\n\t\tQuery: queryValue,\n\t\tBody: body,\n\t\tFormData: formData,\n\t\tHeader: headers,\n\t\tIgnoreAccept: cfg.IgnoreAcceptHeader(),\n\t\tDryRun: cfg.ShouldUseDryRun(cmd.CommandPath()),\n\t}\n\n\treturn n.factory.RunWithWorkers(client, cmd, &req, inputIterators)\n}", "func parseESCR(i []byte) *ClockReference {\n\tvar escr = uint64(i[0])>>3&0x7<<39 | uint64(i[0])&0x3<<37 | uint64(i[1])<<29 | uint64(i[2])>>3<<24 | uint64(i[2])&0x3<<22 | uint64(i[3])<<14 | uint64(i[4])>>3<<9 | uint64(i[4])&0x3<<7 | uint64(i[5])>>1\n\treturn newClockReference(int(escr>>9), int(escr&0x1ff))\n}", "func (c *RunCommand) RunE() error {\n\tcfg, err := c.Factory()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thelper, err := NewHelper(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient := NewClient(helper)\n\n\tphase, err := client.PhaseByID(c.Options.PhaseID)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn phase.Run(ifc.RunOptions{DryRun: c.Options.DryRun})\n}", "func (t *Three) OctahedronGeometry() *OctahedronGeometry {\n\tp := t.ctx.Get(\"OctahedronGeometry\")\n\treturn OctahedronGeometryFromJSObject(p)\n}", "func (c *Client) Epic(jql string) (*SearchResult, error) {\n\tres, err := c.Get(context.Background(), \"/search?jql=\"+url.QueryEscape(jql), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif res == nil {\n\t\treturn nil, ErrEmptyResponse\n\t}\n\tdefer func() { _ = res.Body.Close() }()\n\n\tif res.StatusCode != http.StatusOK {\n\t\treturn nil, ErrUnexpectedStatusCode\n\t}\n\n\tvar out SearchResult\n\n\terr = json.NewDecoder(res.Body).Decode(&out)\n\n\treturn &out, err\n}", "func TestCompleteKE(t *testing.T) {\n\tt.Parallel()\n\tconst tol = 1.0e-14\n\n\tfor m := 1; m <= 9999; m++ {\n\t\tmf := float64(m) / 10000\n\t\tmp := 1 - mf\n\t\tK, Kp := CompleteK(mf), CompleteK(mp)\n\t\tE, Ep := CompleteE(mf), CompleteE(mp)\n\t\tlegendre := math.Abs(E*Kp + Ep*K - K*Kp - math.Pi/2)\n\t\tif legendre > tol {\n\t\t\tt.Fatalf(\"legendre > tol: m=%v, legendre=%v, tol=%v\", mf, legendre, tol)\n\t\t}\n\t}\n}", "func (a *EditionApiService) V1EditionsEditionIdEditorsEditorEmailIdPut(ctx _context.Context, editionId int32, editorEmailId string, localVarOptionals *V1EditionsEditionIdEditorsEditorEmailIdPutOpts) (DetailedEditorRightsDto, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue DetailedEditorRightsDto\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/v1/editions/{editionId}/editors/{editorEmailId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"editionId\"+\"}\", _neturl.QueryEscape(parameterToString(editionId, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"editorEmailId\"+\"}\", _neturl.QueryEscape(parameterToString(editorEmailId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\", \"text/json\", \"application/_*+json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tif localVarOptionals != nil && localVarOptionals.UpdateEditorRightsDto.IsSet() {\n\t\tlocalVarOptionalUpdateEditorRightsDto, localVarOptionalUpdateEditorRightsDtook := localVarOptionals.UpdateEditorRightsDto.Value().(UpdateEditorRightsDto)\n\t\tif !localVarOptionalUpdateEditorRightsDtook {\n\t\t\treturn localVarReturnValue, nil, reportError(\"updateEditorRightsDto should be UpdateEditorRightsDto\")\n\t\t}\n\t\tlocalVarPostBody = &localVarOptionalUpdateEditorRightsDto\n\t}\n\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func VFMSUB132PD_RN_SAE(ops ...operand.Op) { ctx.VFMSUB132PD_RN_SAE(ops...) }" ]
[ "0.74699134", "0.53509736", "0.5212823", "0.5123355", "0.49350253", "0.49159133", "0.4744874", "0.46416277", "0.4524783", "0.4492814", "0.4436879", "0.44055137", "0.43862936", "0.43788657", "0.43419313", "0.43260568", "0.43255433", "0.43137696", "0.4303726", "0.42876762", "0.42613313", "0.4228972", "0.4210644", "0.4205833", "0.41979083", "0.41592512", "0.41459894", "0.41351244", "0.41297355", "0.40701944", "0.4051705", "0.4037875", "0.40340695", "0.4027277", "0.4010651", "0.39945364", "0.39863357", "0.3975982", "0.39747047", "0.39729068", "0.3953351", "0.39489985", "0.39465556", "0.393706", "0.39314377", "0.3919977", "0.39123806", "0.3910121", "0.39015055", "0.38903087", "0.38898408", "0.388706", "0.38784042", "0.38763803", "0.38624996", "0.38526314", "0.38470867", "0.38408273", "0.38336772", "0.38275167", "0.38181618", "0.38156334", "0.38025954", "0.3802032", "0.37986964", "0.3797831", "0.3790253", "0.37896627", "0.37889862", "0.37813222", "0.377997", "0.37781247", "0.37772742", "0.37743884", "0.37739187", "0.37654468", "0.37583363", "0.3753547", "0.37488437", "0.3746324", "0.37455392", "0.37400904", "0.37390244", "0.3722102", "0.37199926", "0.37159526", "0.37139624", "0.36978456", "0.36932677", "0.369172", "0.36898306", "0.36885542", "0.36882696", "0.36874986", "0.36867976", "0.36849275", "0.3673309", "0.3665806", "0.36586654", "0.36565432" ]
0.5603201
1
GoEform Earth reference ellipsoids.
func GoEform(n int) (a, f float64, err en.ErrNum) { // Look up a and f for the specified reference ellipsoid. switch n { case WGS84: a = 6378137.0 f = 1.0 / 298.257223563 case GRS80: a = 6378137.0 f = 1.0 / 298.257222101 case WGS72: a = 6378135.0 f = 1.0 / 298.26 default: // Invalid identifier. a = 0.0 f = 0.0 err = errEform.Set(-1) } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewEllipsoid(radius, flattening float64) *Ellipsoid {\n\te := new(Ellipsoid)\n\tC.geod_init(&e.g, C.double(radius), C.double(flattening))\n\treturn e\n}", "func (e *Ellipsoid) Inverse(\n\tlat1, lon1, lat2, lon2 float64,\n\ts12, azi1, azi2 *float64,\n) {\n\tC.geod_inverse(&e.g,\n\t\tC.double(lat1), C.double(lon1), C.double(lat2), C.double(lon2),\n\t\t(*C.double)(s12), (*C.double)(azi1), (*C.double)(azi2))\n}", "func calcEccentEarthOrbit(julianCentury []float64) (eccentEarthOrbit []float64) {\n\tfor index := 0; index < len(julianCentury); index++ {\n\t\ttemp := 0.016708634 - julianCentury[index]*(0.000042037+0.0000001267*julianCentury[index])\n\t\teccentEarthOrbit = append(eccentEarthOrbit, temp)\n\t}\n\treturn\n}", "func eastDelta(e, w float64) float64 {\n\te = normEasting(e)\n\tw = normEasting(w)\n\tif e < w {\n\t\treturn 360 + e - w\n\t}\n\treturn e - w\n}", "func NewEllipsoid(sys *System) (*Ellipsoid, error) {\n\tellipsoid := &Ellipsoid{}\n\n\terr := ellipsoid.initialize(sys)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ellipsoid, nil\n}", "func GetEquationOfCenter(anomaly float64) float64 {\n\t// The numbers being multiplied below are coefficients for the Equation of Center for Earth\n\tvar anomalyInRad float64\n\tanomalyInRad = anomaly * (math.Pi/180)\n\treturn 1.9148 * (math.Sin(anomalyInRad)) + 0.0200 * math.Sin(2 * anomalyInRad) + 0.0003 * math.Sin(3 * anomalyInRad)\n}", "func East(value float64) *SimpleElement { return newSEFloat(\"east\", value) }", "func Project(zone int, south bool, latitude, longitude float64) (float64, float64) {\n\n\t// False northing\n\tfn := 0.\n\tif south {\n\t\tfn = utmSouthernHemisphereFalseNorthing\n\t}\n\n\th1 := n/2 - n2*2/3 + n3*5/16 + n4*41/180\n\th2 := n2*13/48 - n3*3/5 + n4*557/1440\n\th3 := n3*61/240 - n4*103/140\n\th4 := n4 * 49561 / 161280\n\n\tq := math.Asinh(math.Tan(latitude)) - e*math.Atanh(e*math.Sin(latitude))\n\tβ := math.Atan(math.Sinh(q))\n\n\tη0 := math.Atanh(math.Cos(β) * math.Sin(longitude-λO(zone)))\n\tξ0 := math.Asin(math.Sin(β) * math.Cosh(η0))\n\n\tη1 := h1 * math.Cos(2*ξ0) * math.Sinh(2*η0)\n\tη2 := h2 * math.Cos(4*ξ0) * math.Sinh(4*η0)\n\tη3 := h3 * math.Cos(6*ξ0) * math.Sinh(6*η0)\n\tη4 := h4 * math.Cos(8*ξ0) * math.Sinh(8*η0)\n\n\tξ1 := h1 * math.Sin(2*ξ0) * math.Cosh(2*η0)\n\tξ2 := h2 * math.Sin(4*ξ0) * math.Cosh(4*η0)\n\tξ3 := h3 * math.Sin(6*ξ0) * math.Cosh(6*η0)\n\tξ4 := h4 * math.Sin(8*ξ0) * math.Cosh(8*η0)\n\n\tξ := ξ0 + ξ1 + ξ2 + ξ3 + ξ4\n\tη := η0 + η1 + η2 + η3 + η4\n\n\te := fe + kO*b*η\n\tn := fn + kO*b*ξ\n\treturn e, n\n}", "func earthRadius(x float64) float64 {\n\tmasm := 6378137.0 // Major semiaxis [m]\n\tmism := 6356752.3 // Minor semiaxis [m]\n\n\tan := masm * masm * math.Cos(x)\n\tbn := mism * mism * math.Sin(x)\n\tad := masm * math.Cos(x)\n\tbd := mism * math.Sin(x)\n\treturn math.Sqrt((an*an + bn*bn) / (ad*ad + bd*bd))\n}", "func (me XsdGoPkgHasElem_East) EastDefault() Tangle180Type {\r\n\tvar x = new(Tangle180Type)\r\n\tx.Set(\"180.0\")\r\n\treturn *x\r\n}", "func (b *Bound) East() float64 {\n\treturn b.ne[0]\n}", "func (me XsdGoPkgHasElems_East) EastDefault() Tangle180Type {\r\n\tvar x = new(Tangle180Type)\r\n\tx.Set(\"180.0\")\r\n\treturn *x\r\n}", "func (o *Orbit) Elements() (a, e, i, Ω, ω, ν, λ, tildeω, u float64) {\n\tif o.hashValid() {\n\t\treturn o.ccha, o.cche, o.cchi, o.cchΩ, o.cchω, o.cchν, o.cchλ, o.cchtildeω, o.cchu\n\t}\n\t// Algorithm from Vallado, 4th edition, page 113 (RV2COE).\n\thVec := Cross(o.rVec, o.vVec)\n\tn := Cross([]float64{0, 0, 1}, hVec)\n\tv := Norm(o.vVec)\n\tr := Norm(o.rVec)\n\tξ := (v*v)/2 - o.Origin.μ/r\n\ta = -o.Origin.μ / (2 * ξ)\n\teVec := make([]float64, 3, 3)\n\tfor i := 0; i < 3; i++ {\n\t\teVec[i] = ((v*v-o.Origin.μ/r)*o.rVec[i] - Dot(o.rVec, o.vVec)*o.vVec[i]) / o.Origin.μ\n\t}\n\te = Norm(eVec)\n\t// Prevent nil values for e\n\tif e < eccentricityε {\n\t\te = eccentricityε\n\t}\n\ti = math.Acos(hVec[2] / Norm(hVec))\n\tif i < angleε {\n\t\ti = angleε\n\t}\n\tω = math.Acos(Dot(n, eVec) / (Norm(n) * e))\n\tif math.IsNaN(ω) {\n\t\tω = 0\n\t}\n\tif eVec[2] < 0 {\n\t\tω = 2*math.Pi - ω\n\t}\n\tΩ = math.Acos(n[0] / Norm(n))\n\tif math.IsNaN(Ω) {\n\t\tΩ = angleε\n\t}\n\tif n[1] < 0 {\n\t\tΩ = 2*math.Pi - Ω\n\t}\n\tcosν := Dot(eVec, o.rVec) / (e * r)\n\tif abscosν := math.Abs(cosν); abscosν > 1 && floats.EqualWithinAbs(abscosν, 1, 1e-12) {\n\t\t// Welcome to the edge case which took about 1.5 hours of my time.\n\t\tcosν = Sign(cosν) // GTFO NaN!\n\t}\n\tν = math.Acos(cosν)\n\tif math.IsNaN(ν) {\n\t\tν = 0\n\t}\n\tif Dot(o.rVec, o.vVec) < 0 {\n\t\tν = 2*math.Pi - ν\n\t}\n\t// Fix rounding errors.\n\ti = math.Mod(i, 2*math.Pi)\n\tΩ = math.Mod(Ω, 2*math.Pi)\n\tω = math.Mod(ω, 2*math.Pi)\n\tν = math.Mod(ν, 2*math.Pi)\n\tλ = math.Mod(ω+Ω+ν, 2*math.Pi)\n\ttildeω = math.Mod(ω+Ω, 2*math.Pi)\n\tif e < eccentricityε {\n\t\t// Circular\n\t\tu = math.Acos(Dot(n, o.rVec) / (Norm(n) * r))\n\t} else {\n\t\tu = math.Mod(ν+ω, 2*math.Pi)\n\t}\n\t// Cache values\n\to.ccha = a\n\to.cche = e\n\to.cchi = i\n\to.cchΩ = Ω\n\to.cchω = ω\n\to.cchν = ν\n\to.cchλ = λ\n\to.cchtildeω = tildeω\n\to.cchu = u\n\to.computeHash()\n\treturn\n}", "func NewOrbitFromOE(a, e, i, Ω, ω, ν float64, c CelestialObject) *Orbit {\n\t// Convert angles to radians\n\ti = i * deg2rad\n\tΩ = Ω * deg2rad\n\tω = ω * deg2rad\n\tν = ν * deg2rad\n\n\t// Algorithm from Vallado, 4th edition, page 118 (COE2RV).\n\tif e < eccentricityε {\n\t\t// Circular...\n\t\tif i < angleε {\n\t\t\t// ... equatorial\n\t\t\tΩ = 0\n\t\t\tω = 0\n\t\t\tν = math.Mod(ω+Ω+ν, 2*math.Pi)\n\t\t} else {\n\t\t\t// ... inclined\n\t\t\tω = 0\n\t\t\tν = math.Mod(ν+ω, 2*math.Pi)\n\t\t}\n\t} else if i < angleε && !(c.Equals(Sun) && config.meeus) {\n\t\t// Meeus breaks if doing this correction by Vallado\n\t\t// Elliptical equatorial\n\t\tΩ = 0\n\t\tω = math.Mod(ω+Ω, 2*math.Pi)\n\t}\n\tp := a * (1 - e*e)\n\tif floats.EqualWithinAbs(e, 1, eccentricityε) || e > 1 {\n\t\tpanic(\"[ERROR] should initialize parabolic or hyperbolic orbits with R, V\")\n\t}\n\tμOp := math.Sqrt(c.μ / p)\n\tsinν, cosν := math.Sincos(ν)\n\trPQW := []float64{p * cosν / (1 + e*cosν), p * sinν / (1 + e*cosν), 0}\n\tvPQW := []float64{-μOp * sinν, μOp * (e + cosν), 0}\n\trIJK := Rot313Vec(-ω, -i, -Ω, rPQW)\n\tvIJK := Rot313Vec(-ω, -i, -Ω, vPQW)\n\torbit := Orbit{rIJK, vIJK, c, a, e, i, Ω, ω, ν, 0, 0, 0, 0.0}\n\torbit.Elements()\n\treturn &orbit\n}", "func TestEllipticE(t *testing.T) {\n\tt.Parallel()\n\tconst tol = 1.0e-14\n\trnd := rand.New(rand.NewSource(1))\n\n\t// The following EllipticE(pi/3,m), m=0.1(0.1)0.9 was computed in Maxima 5.38.0 using Bigfloat arithmetic.\n\tvE := [...]float64{\n\t\t1.0316510822817691068014397636905610074934300946730,\n\t\t1.0156973658341766636288643556414001451527597364432,\n\t\t9.9929636467826398814855428365155224243586391115108e-1,\n\t\t9.8240033979859736941287149003648737502960015189033e-1,\n\t\t9.6495145764299257550956863602992167490195750321518e-1,\n\t\t9.4687829659158090935158610908054896203271861698355e-1,\n\t\t9.2809053417715769009517654522979827392794124845027e-1,\n\t\t9.0847044378047233264777277954768245721857017157916e-1,\n\t\t8.8785835036531301307661603341327881634688308777383e-1,\n\t}\n\tphi := math.Pi / 3\n\tfor m := 1; m <= 9; m++ {\n\t\tmf := float64(m) / 10\n\t\tdelta := math.Abs(EllipticE(phi, mf) - vE[m-1])\n\t\tif delta > tol {\n\t\t\tt.Fatalf(\"EllipticE(pi/3,m) test fail for m=%v\", mf)\n\t\t}\n\t}\n\n\tfor test := 0; test < 100; test++ {\n\t\talpha := rnd.Float64() * math.Pi / 4\n\t\tbeta := rnd.Float64() * math.Pi / 4\n\t\tfor mi := 0; mi < 9999; mi++ {\n\t\t\tm := float64(mi) / 10000\n\t\t\tEa := EllipticE(alpha, m)\n\t\t\tEb := EllipticE(beta, m)\n\t\t\tsina, cosa := math.Sincos(alpha)\n\t\t\tsinb, cosb := math.Sincos(beta)\n\t\t\ttan := (sina*math.Sqrt(1-m*sinb*sinb) + sinb*math.Sqrt(1-m*sina*sina)) / (cosa + cosb)\n\t\t\tgamma := 2 * math.Atan(tan)\n\t\t\tEg := EllipticE(gamma, m)\n\t\t\tdelta := math.Abs(Ea + Eb - Eg - m*sina*sinb*math.Sin(gamma))\n\t\t\tif delta > tol {\n\t\t\t\tt.Fatalf(\"EllipticE test fail for m=%v, alpha=%v, beta=%v\", m, alpha, beta)\n\t\t\t}\n\t\t}\n\t}\n}", "func (crs TransverseMercator) ToLonLat(east, north float64, gs GeodeticSpheroid) (lon, lat float64) {\n\ts := spheroid(gs, crs.GeodeticDatum)\n\teast -= crs.Eastf\n\tnorth -= crs.Northf\n\tMi := crs._M(radian(crs.Latf), s) + north/crs.Scale\n\tμ := Mi / (s.MajorAxis() * (1 - s.E2()/4 - 3*s.E4()/64 - 5*s.E6()/256))\n\tφ1 := μ + (3*s.Ei()/2-27*s.Ei3()/32)*math.Sin(2*μ) +\n\t\t(21*s.Ei2()/16-55*s.Ei4()/32)*math.Sin(4*μ) +\n\t\t(151*s.Ei3()/96)*math.Sin(6*μ) +\n\t\t(1097*s.Ei4()/512)*math.Sin(8*μ)\n\tR1 := s.MajorAxis() * (1 - s.E2()) / math.Pow(1-s.E2()*sin2(φ1), 3/2)\n\tD := east / (crs._N(φ1, s) * crs.Scale)\n\tφ := φ1 - (crs._N(φ1, s)*math.Tan(φ1)/R1)*(D*D/2-(5+3*crs._T(φ1)+10*\n\t\tcrs._C(φ1, s)-4*crs._C(φ1, s)*crs._C(φ1, s)-9*s.Ei2())*\n\t\tmath.Pow(D, 4)/24+(61+90*crs._T(φ1)+298*crs._C(φ1, s)+45*crs._T(φ1)*\n\t\tcrs._T(φ1)-252*s.Ei2()-3*crs._C(φ1, s)*crs._C(φ1, s))*\n\t\tmath.Pow(D, 6)/720)\n\tλ := radian(crs.Lonf) + (D-(1+2*crs._T(φ1)+crs._C(φ1, s))*D*D*D/6+(5-2*crs._C(φ1, s)+\n\t\t28*crs._T(φ1)-3*crs._C(φ1, s)*crs._C(φ1, s)+8*s.Ei2()+24*crs._T(φ1)*crs._T(φ1))*\n\t\tmath.Pow(D, 5)/120)/math.Cos(φ1)\n\treturn degree(λ), degree(φ)\n}", "func (eClass *eClassImpl) GetEReferences() EList {\n\teClass.getInitializers().initEReferences()\n\treturn eClass.eReferences\n}", "func (eClass *eClassImpl) GetEAllReferences() EList {\n\teClass.getInitializers().initEAllReferences()\n\treturn eClass.eAllReferences\n}", "func normEasting(deg float64) float64 {\n\t// go's Mod fcn preserves sign on first param\n\tif deg < -180 {\n\t\treturn math.Mod(deg+180, 360) + 180\n\t}\n\tif deg > 180 {\n\t\treturn math.Mod(deg-180, 360) - 180\n\t}\n\treturn deg\n}", "func molodensky(ilat, ilon float64, from, to eDatum) (float64, float64) {\n\t// from->WGS84 - to->WGS84 = from->WGS84 + WGS84->to = from->to\n\tdX := Datum[from].dX - Datum[to].dX\n\tdY := Datum[from].dY - Datum[to].dY\n\tdZ := Datum[from].dZ - Datum[to].dZ\n\tslat := math.Sin(ilat)\n\tclat := math.Cos(ilat)\n\tslon := math.Sin(ilon)\n\tclon := math.Cos(ilon)\n\tssqlat := slat * slat\n\n\t//dlat = ((-dx * slat * clon - dy * slat * slon + dz * clat)\n\t// + (da * rn * fromEsq * slat * clat / fromA)\n\t// + (df * (rm * adb + rn / adb )* slat * clat))\n\t// / (rm + from.h);\n\n\tfromF := Datum[from].f\n\tdf := Datum[to].f - fromF\n\tfromA := Datum[from].a\n\tda := Datum[to].a - fromA\n\tfromEsq := Datum[from].esq\n\tadb := 1.0 / (1.0 - fromF)\n\trn := fromA / math.Sqrt(1-fromEsq*ssqlat)\n\trm := fromA * (1 - fromEsq) / math.Pow((1-fromEsq*ssqlat), 1.5)\n\tfromH := 0.0 // we're flat!\n\tdlat := (-dX*slat*clon - dY*slat*slon + dZ*clat + da*rn*fromEsq*slat*clat/fromA +\n\t\t+df*(rm*adb+rn/adb)*slat*clat) /\n\t\t(rm + fromH)\n\n\t// result lat (radians)\n\tolat := ilat + dlat\n\n\t// dlon = (-dx * slon + dy * clon) / ((rn + from.h) * clat);\n\tdlon := (-dX*slon + dY*clon) / ((rn + fromH) * clat)\n\t// result lon (radians)\n\tolon := ilon + dlon\n\treturn olat, olon\n}", "func (g *Galaxy) GenerateEarth() {\n\tss := g.GenerateRandomSubSector()\n\tss.starSystem = NewStarSystem(ss.GetCoords())\n\tss.starSystem.GenerateSolSystem()\n\tg.earth = ss.starSystem.Planets[2].GetCoords()\n}", "func EarthDistance(firstVector, secondVector []float64) (float64, error) {\n\tvar R float64 = 6378137 // radius of the earth in meter\n\ttoRadians := func(d float64) float64 {\n\t\treturn d * math.Pi / 180.0\n\t}\n\n\tlat1 := toRadians(firstVector[1])\n\tlat2 := toRadians(secondVector[1])\n\tdLat := lat2 - lat1\n\tdLng := toRadians(secondVector[0] - firstVector[0])\n\tc := 2.0 * math.Asin(math.Sqrt(math.Pow(math.Sin(dLat/2.0), 2)+\n\t\tmath.Cos(lat1)*math.Cos(lat2)*math.Pow(math.Sin(dLng/2.0), 2)))\n\n\treturn c * R, nil\n}", "func (b *BBox) NE() *LatLng {\n\treturn b[1]\n}", "func (crs TransverseMercator) FromLonLat(lon, lat float64, gs GeodeticSpheroid) (east, north float64) {\n\ts := spheroid(gs, crs.GeodeticDatum)\n\tφ := radian(lat)\n\tA := (radian(lon) - radian(crs.Lonf)) * math.Cos(φ)\n\teast = crs.Scale*crs._N(φ, s)*(A+(1-crs._T(φ)+crs._C(φ, s))*\n\t\tmath.Pow(A, 3)/6+(5-18*crs._T(φ)+crs._T(φ)*crs._T(φ)+72*crs._C(φ, s)-58*s.Ei2())*\n\t\tmath.Pow(A, 5)/120) + crs.Eastf\n\tnorth = crs.Scale*(crs._M(φ, s)-crs._M(radian(crs.Latf), s)+crs._N(φ, s)*math.Tan(φ)*\n\t\t(A*A/2+(5-crs._T(φ)+9*crs._C(φ, s)+4*crs._C(φ, s)*crs._C(φ, s))*\n\t\t\tmath.Pow(A, 4)/24+(61-58*crs._T(φ)+crs._T(φ)*crs._T(φ)+600*\n\t\t\tcrs._C(φ, s)-330*s.Ei2())*math.Pow(A, 6)/720)) + crs.Northf\n\treturn east, north\n}", "func (me *XsdGoPkgHasElem_East) Walk() (err error) {\r\n\tif fn := WalkHandlers.XsdGoPkgHasElem_East; me != nil {\r\n\t\tif fn != nil {\r\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\t}\r\n\t\tif fn != nil {\r\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn\r\n}", "func GE(x float64, y float64) bool {\n\treturn (x > y-e)\n}", "func CgoEform(n int) (a, f float64, err en.ErrNum) {\n\tvar cA, cF C.double\n\tvar cStatus C.int\n\tcStatus = C.iauEform(C.int(n), &cA, &cF)\n\tswitch int(cStatus) {\n\tcase 0:\n\tcase -1:\n\t\terr = errEform.Set(-1)\n\tdefault:\n\t\terr = errEform.Set(0)\n\t}\n\treturn float64(cA), float64(cF), err\n}", "func Merc(this *SR) (forward, inverse Transformer, err error) {\n\tif math.IsNaN(this.Long0) {\n\t\tthis.Long0 = 0\n\t}\n\tvar con = this.B / this.A\n\tthis.Es = 1 - con*con\n\tif math.IsNaN(this.X0) {\n\t\tthis.X0 = 0\n\t}\n\tif math.IsNaN(this.Y0) {\n\t\tthis.Y0 = 0\n\t}\n\tthis.E = math.Sqrt(this.Es)\n\tif !math.IsNaN(this.LatTS) {\n\t\tif this.sphere {\n\t\t\tthis.K0 = math.Cos(this.LatTS)\n\t\t} else {\n\t\t\tthis.K0 = msfnz(this.E, math.Sin(this.LatTS), math.Cos(this.LatTS))\n\t\t}\n\t} else {\n\t\tif math.IsNaN(this.K0) {\n\t\t\tif !math.IsNaN(this.K) {\n\t\t\t\tthis.K0 = this.K\n\t\t\t} else {\n\t\t\t\tthis.K0 = 1\n\t\t\t}\n\t\t}\n\t}\n\n\t// Mercator forward equations--mapping lat,long to x,y\n\tforward = func(lon, lat float64) (x, y float64, err error) {\n\t\t// convert to radians\n\t\tif math.IsNaN(lat) || math.IsNaN(lon) || lat*r2d > 90 || lat*r2d < -90 || lon*r2d > 180 || lon*r2d < -180 {\n\t\t\terr = fmt.Errorf(\"in proj.Merc forward: invalid longitude (%g) or latitude (%g)\", lon, lat)\n\t\t\treturn\n\t\t}\n\n\t\tif math.Abs(math.Abs(lat)-halfPi) <= epsln {\n\t\t\terr = fmt.Errorf(\"in proj.Merc forward, abs(lat)==pi/2\")\n\t\t\treturn\n\t\t}\n\t\tif this.sphere {\n\t\t\tx = this.X0 + this.A*this.K0*adjust_lon(lon-this.Long0)\n\t\t\ty = this.Y0 + this.A*this.K0*math.Log(math.Tan(fortPi+0.5*lat))\n\t\t} else {\n\t\t\tvar sinphi = math.Sin(lat)\n\t\t\tvar ts = tsfnz(this.E, lat, sinphi)\n\t\t\tx = this.X0 + this.A*this.K0*adjust_lon(lon-this.Long0)\n\t\t\ty = this.Y0 - this.A*this.K0*math.Log(ts)\n\t\t}\n\t\treturn\n\t}\n\n\t// Mercator inverse equations--mapping x,y to lat/long\n\tinverse = func(x, y float64) (lon, lat float64, err error) {\n\t\tx -= this.X0\n\t\ty -= this.Y0\n\n\t\tif this.sphere {\n\t\t\tlat = halfPi - 2*math.Atan(math.Exp(-y/(this.A*this.K0)))\n\t\t} else {\n\t\t\tvar ts = math.Exp(-y / (this.A * this.K0))\n\t\t\tlat, err = phi2z(this.E, ts)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tlon = adjust_lon(this.Long0 + x/(this.A*this.K0))\n\t\treturn\n\t}\n\treturn\n}", "func (c1 CIELab) DeltaE(c2 CIELab) float64 {\n\treturn math.Sqrt(math.Pow(c1.L*1-c2.L*2, 2) +\n\t\tmath.Pow(c1.A*1-c2.A*2, 2) + math.Pow(c1.B*1-c2.B*2, 2),\n\t)\n}", "func (b *Bound) NorthEast() *Point { return b.ne.Clone() }", "func (o Orbit) epsilons() (float64, float64, float64) {\n\tif o.Origin.Equals(Sun) {\n\t\treturn distanceLgε, eccentricityLgε, angleLgε\n\t}\n\treturn distanceε, eccentricityε, angleε\n}", "func Zgeequ(m, n int, a *mat.CMatrix, r, c *mat.Vector) (rowcnd, colcnd, amax float64, info int, err error) {\n\tvar bignum, one, rcmax, rcmin, smlnum, zero float64\n\tvar i, j int\n\n\tone = 1.0\n\tzero = 0.0\n\n\t// Test the input parameters.\n\tif m < 0 {\n\t\terr = fmt.Errorf(\"m < 0: m=%v\", m)\n\t} else if n < 0 {\n\t\terr = fmt.Errorf(\"n < 0: n=%v\", n)\n\t} else if a.Rows < max(1, m) {\n\t\terr = fmt.Errorf(\"a.Rows < max(1, m): a.Rows=%v, m=%v\", a.Rows, m)\n\t}\n\tif err != nil {\n\t\tgltest.Xerbla2(\"Zgeequ\", err)\n\t\treturn\n\t}\n\n\t// Quick return if possible\n\tif m == 0 || n == 0 {\n\t\trowcnd = one\n\t\tcolcnd = one\n\t\tamax = zero\n\t\treturn\n\t}\n\n\t// Get machine constants.\n\tsmlnum = Dlamch(SafeMinimum)\n\tbignum = one / smlnum\n\n\t// Compute row scale factors.\n\tfor i = 1; i <= m; i++ {\n\t\tr.Set(i-1, zero)\n\t}\n\n\t// Find the maximum element in each row.\n\tfor j = 1; j <= n; j++ {\n\t\tfor i = 1; i <= m; i++ {\n\t\t\tr.Set(i-1, math.Max(r.Get(i-1), cabs1(a.Get(i-1, j-1))))\n\t\t}\n\t}\n\n\t// Find the maximum and minimum scale factors.\n\trcmin = bignum\n\trcmax = zero\n\tfor i = 1; i <= m; i++ {\n\t\trcmax = math.Max(rcmax, r.Get(i-1))\n\t\trcmin = math.Min(rcmin, r.Get(i-1))\n\t}\n\tamax = rcmax\n\n\tif rcmin == zero {\n\t\t// Find the first zero scale factor and return an error code.\n\t\tfor i = 1; i <= m; i++ {\n\t\t\tif r.Get(i-1) == zero {\n\t\t\t\tinfo = i\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Invert the scale factors.\n\t\tfor i = 1; i <= m; i++ {\n\t\t\tr.Set(i-1, one/math.Min(math.Max(r.Get(i-1), smlnum), bignum))\n\t\t}\n\n\t\t// Compute ROWCND = min(R(I)) / max(R(I))\n\t\trowcnd = math.Max(rcmin, smlnum) / math.Min(rcmax, bignum)\n\t}\n\n\t// Compute column scale factors\n\tfor j = 1; j <= n; j++ {\n\t\tc.Set(j-1, zero)\n\t}\n\n\t// Find the maximum element in each column,\n\t// assuming the row scaling computed above.\n\tfor j = 1; j <= n; j++ {\n\t\tfor i = 1; i <= m; i++ {\n\t\t\tc.Set(j-1, math.Max(c.Get(j-1), cabs1(a.Get(i-1, j-1))*r.Get(i-1)))\n\t\t}\n\t}\n\n\t// Find the maximum and minimum scale factors.\n\trcmin = bignum\n\trcmax = zero\n\tfor j = 1; j <= n; j++ {\n\t\trcmin = math.Min(rcmin, c.Get(j-1))\n\t\trcmax = math.Max(rcmax, c.Get(j-1))\n\t}\n\n\tif rcmin == zero {\n\t\t// Find the first zero scale factor and return an error code.\n\t\tfor j = 1; j <= n; j++ {\n\t\t\tif c.Get(j-1) == zero {\n\t\t\t\tinfo = m + j\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Invert the scale factors.\n\t\tfor j = 1; j <= n; j++ {\n\t\t\tc.Set(j-1, one/math.Min(math.Max(c.Get(j-1), smlnum), bignum))\n\t\t}\n\n\t\t// Compute COLCND = min(C(J)) / max(C(J))\n\t\tcolcnd = math.Max(rcmin, smlnum) / math.Min(rcmax, bignum)\n\t}\n\n\treturn\n}", "func PeelCentralCurve() func(x float64) model3d.Coord3D {\n\tplaneCurve := PeelCurve()\n\tzCurve := PeelHeight()\n\treturn func(x float64) model3d.Coord3D {\n\t\treturn model3d.XYZ(x, model2d.CurveEvalX(planeCurve, x), model2d.CurveEvalX(zCurve, x))\n\t}\n}", "func Encuentra_E() {\n\n\tfor i := 0; i < 15; i++ {\n\t\tfor j := 0; j < 15; j++ {\n\t\t\tif laberinto[i][j] == \"E\" {\n\t\t\t\tx = i\n\t\t\t\ty = j\n\t\t\t}\n\t\t}\n\t}\n}", "func PeelMesh(stops int) *model3d.Mesh {\n\tcurve := PeelCentralCurve()\n\ttwist := PeelTwist()\n\tcentralDir := func(x float64) model3d.Coord3D {\n\t\tdelta := 0.001\n\t\tif x > 0 {\n\t\t\tx -= delta\n\t\t}\n\t\treturn curve(x + delta).Sub(curve(x)).Normalize()\n\t}\n\tcorners := func(t int) [4]model3d.Coord3D {\n\t\tx := float64(t)/float64(stops)*(1-PeelEdgeInset)*2 - (1 - PeelEdgeInset)\n\t\tc := curve(x)\n\t\tdir := centralDir(x)\n\n\t\ttheta := model2d.CurveEvalX(twist, x)\n\t\trotation := model3d.Rotation(dir, theta)\n\n\t\tlongDir := model3d.Z(1.0)\n\t\tshortDir := longDir.Cross(dir).Normalize()\n\t\tlongDir = rotation.Apply(longDir).Scale(PeelLongSide / 2.0)\n\t\tshortDir = rotation.Apply(shortDir).Scale(PeelSmallSide / 2.0)\n\n\t\tscales := [4][2]float64{{1, 1}, {1, -1}, {-1, -1}, {-1, 1}}\n\t\tres := [4]model3d.Coord3D{}\n\t\tfor i, scale := range scales {\n\t\t\tres[i] = c.Add(shortDir.Scale(scale[0])).Add(longDir.Scale(scale[1]))\n\t\t}\n\t\treturn res\n\t}\n\n\tres := model3d.NewMesh()\n\tfor t := 0; t < stops; t++ {\n\t\tcorners1 := corners(t)\n\t\tcorners2 := corners(t + 1)\n\t\tfor i := 0; i < 4; i++ {\n\t\t\tres.AddQuad(corners1[(i+1)%4], corners1[i], corners2[i], corners2[(i+1)%4])\n\t\t}\n\t}\n\tfor _, t := range [2]int{0, stops} {\n\t\tcorners := corners(t)\n\t\tif t == 0 {\n\t\t\tres.AddQuad(corners[0], corners[1], corners[2], corners[3])\n\t\t} else {\n\t\t\tres.AddQuad(corners[1], corners[0], corners[3], corners[2])\n\t\t}\n\t}\n\n\treturn res\n}", "func (eClass *eClassImpl) GetEAllContainments() EList {\n\teClass.getInitializers().initEAllContainments()\n\treturn eClass.eAllContainments\n}", "func (e *Ellipsoid) Direct(\n\tlat1, lon1, azi1, s12 float64,\n\tlat2, lon2, azi2 *float64,\n) {\n\tC.geod_direct(&e.g,\n\t\tC.double(lat1), C.double(lon1), C.double(azi1), C.double(s12),\n\t\t(*C.double)(lat2), (*C.double)(lon2), (*C.double)(azi2))\n}", "func Root4(in *big.Float) *big.Float {\n\treturn Root(in, 4)\n}", "func (me *XsdGoPkgHasElems_East) Walk() (err error) {\r\n\tif fn := WalkHandlers.XsdGoPkgHasElems_East; me != nil {\r\n\t\tif fn != nil {\r\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\t}\r\n\t\tif fn != nil {\r\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn\r\n}", "func Teo2eps() Mat3 {\n\t/*no:=complex(2.1895, 0)\n\tne:=complex(2.3309, 0)*/\n\n\treturn Uniaxial(5.1984, 6.0025)\n}", "func EPSG() *Repository {\n\tcodes := map[int]CoordinateReferenceSystem{\n\t\t4326: LonLat(),\n\t\t4978: XYZ(),\n\t\t3857: WebMercator(),\n\t\t900913: WebMercator(),\n\t\t4258: ETRS89().LonLat(),\n\t\t3416: ETRS89AustriaLambert(),\n\t\t3035: ETRS89LambertAzimuthalEqualArea(),\n\t\t31287: MGIAustriaLambert(),\n\t\t31284: MGIAustriaM28(),\n\t\t31285: MGIAustriaM31(),\n\t\t31286: MGIAustriaM34(),\n\t\t31257: MGIAustriaGKM28(),\n\t\t31258: MGIAustriaGKM31(),\n\t\t31259: MGIAustriaGKM34(),\n\t\t4314: DHDN2001().LonLat(),\n\t\t27700: OSGB36NationalGrid(),\n\t\t4277: OSGB36().LonLat(),\n\t\t4171: RGF93().LonLat(),\n\t\t2154: RGF93FranceLambert(),\n\t\t4269: NAD83().LonLat(),\n\t\t6355: NAD83AlabamaEast(),\n\t\t6356: NAD83AlabamaWest(),\n\t\t6414: NAD83CaliforniaAlbers(),\n\t}\n\n\tfor i := 1; i < 61; i++ {\n\t\tcodes[32600+i] = UTM(float64(i), true)\n\t\tcodes[32700+i] = UTM(float64(i), false)\n\t}\n\n\tfor i := 42; i < 51; i++ {\n\t\tcodes[3900+i] = RGF93CC(float64(i))\n\t}\n\n\tfor i := 2; i < 6; i++ {\n\t\tcodes[31464+i] = DHDN2001GK(float64(i))\n\t}\n\n\tfor i := 28; i < 39; i++ {\n\t\tcodes[25800+i] = ETRS89UTM(float64(i))\n\t}\n\n\treturn &Repository{\n\t\tcodes: codes,\n\t}\n}", "func get_arc_center(x1, y1, x2, y2, fa, fs, rx, ry, sin_phi, cos_phi float64) []float64 {\n\t// Step 1.\n\t//\n\t// Moving an ellipse so origin will be the middlepoint between our two\n\t// points. After that, rotate it to line up ellipse axes with coordinate\n\t// axes.\n\t//\n\tx1p := cos_phi*(x1-x2)/2 + sin_phi*(y1-y2)/2\n\ty1p := -sin_phi*(x1-x2)/2 + cos_phi*(y1-y2)/2\n\n\trx_sq := rx * rx\n\try_sq := ry * ry\n\tx1p_sq := x1p * x1p\n\ty1p_sq := y1p * y1p\n\n\t// Step 2.\n\t//\n\t// Compute coordinates of the centre of this ellipse (cx', cy')\n\t// in the new coordinate system.\n\t//\n\tradicant := (rx_sq * ry_sq) - (rx_sq * y1p_sq) - (ry_sq * x1p_sq)\n\n\tif radicant < 0 {\n\t\t// due to rounding errors it might be e.g. -1.3877787807814457e-17\n\t\tradicant = 0\n\t}\n\n\tradicant /= (rx_sq * y1p_sq) + (ry_sq * x1p_sq)\n\tsign := 1.0\n\tif fa == fs {\n\t\tsign = -1.0\n\t}\n\tradicant = math.Sqrt(radicant) * sign\n\n\tcxp := radicant * rx / ry * y1p\n\tcyp := radicant * -ry / rx * x1p\n\n\t// Step 3.\n\t//\n\t// Transform back to get centre coordinates (cx, cy) in the original\n\t// coordinate system.\n\t//\n\tcx := cos_phi*cxp - sin_phi*cyp + (x1+x2)/2\n\tcy := sin_phi*cxp + cos_phi*cyp + (y1+y2)/2\n\n\t// Step 4.\n\t//\n\t// Compute angles (theta1, delta_theta).\n\t//\n\tv1x := (x1p - cxp) / rx\n\tv1y := (y1p - cyp) / ry\n\tv2x := (-x1p - cxp) / rx\n\tv2y := (-y1p - cyp) / ry\n\n\ttheta1 := unit_vector_angle(1, 0, v1x, v1y)\n\tdelta_theta := unit_vector_angle(v1x, v1y, v2x, v2y)\n\n\tif fs == 0 && delta_theta > 0 {\n\t\tdelta_theta -= TAU\n\t}\n\tif fs == 1 && delta_theta < 0 {\n\t\tdelta_theta += TAU\n\t}\n\n\treturn []float64{cx, cy, theta1, delta_theta}\n}", "func (o *Shape) Extrapolator(E [][]float64, ips []Ipoint) (err error) {\n\tla.MatFill(E, 0)\n\tnip := len(ips)\n\tN := o.GetShapeMatAtIps(ips)\n\tif nip < o.Nverts {\n\t\tξ := o.GetNodesNatCoordsMat()\n\t\tξh := o.GetIpsNatCoordsMat(ips)\n\t\tξhi := la.MatAlloc(o.Gndim+1, nip)\n\t\tNi := la.MatAlloc(o.Nverts, nip)\n\t\terr = la.MatInvG(Ni, N, 1e-10)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\terr = la.MatInvG(ξhi, ξh, 1e-10)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tξhξhI := la.MatAlloc(nip, nip) // ξh * inv(ξh)\n\t\tfor k := 0; k < o.Gndim+1; k++ {\n\t\t\tfor j := 0; j < nip; j++ {\n\t\t\t\tfor i := 0; i < nip; i++ {\n\t\t\t\t\tξhξhI[i][j] += ξh[i][k] * ξhi[k][j]\n\t\t\t\t}\n\t\t\t\tfor i := 0; i < o.Nverts; i++ {\n\t\t\t\t\tE[i][j] += ξ[i][k] * ξhi[k][j] // ξ * inv(ξh)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor i := 0; i < o.Nverts; i++ {\n\t\t\tfor j := 0; j < nip; j++ {\n\t\t\t\tfor k := 0; k < nip; k++ {\n\t\t\t\t\tI_kj := 0.0\n\t\t\t\t\tif j == k {\n\t\t\t\t\t\tI_kj = 1.0\n\t\t\t\t\t}\n\t\t\t\t\tE[i][j] += Ni[i][k] * (I_kj - ξhξhI[k][j])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\terr = la.MatInvG(E, N, 1e-10)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func (dw *DrawingWand) Ellipse(ox, oy, rx, ry, start, end float64) {\n\tC.MagickDrawEllipse(dw.dw, C.double(ox), C.double(oy), C.double(rx), C.double(ry), C.double(start), C.double(end))\n}", "func setGeoDegs(p *GeoCoord, latDegs float64, lonDegs float64) {\n\t_setGeoRads(p, degsToRads(latDegs), degsToRads(lonDegs))\n}", "func (o Orbit) SinCosE() (sinE, cosE float64) {\n\t_, e, _, _, _, ν, _, _, _ := o.Elements()\n\tsinν, cosν := math.Sincos(ν)\n\tdenom := 1 + e*cosν\n\tif e > 1 {\n\t\t// Hyperbolic orbit\n\t\tsinE = math.Sqrt(e*e-1) * sinν / denom\n\t} else {\n\t\tsinE = math.Sqrt(1-e*e) * sinν / denom\n\t}\n\tcosE = (e + cosν) / denom\n\treturn\n}", "func (eClass *eClassImpl) GetEContainments() EList {\n\teClass.getInitializers().initEContainments()\n\treturn eClass.eContainments\n}", "func latLon2Grid(lat, lon float64, from eDatum, to gGrid) (int, int) {\n\t// Datum data for Lat/Lon to TM conversion\n\ta := Datum[from].a\n\te := Datum[from].e // sqrt(esq);\n\tb := Datum[from].b\n\n\t//===============\n\t// Lat/Lon -> TM\n\t//===============\n\tslat1 := math.Sin(lat)\n\tclat1 := math.Cos(lat)\n\tclat1sq := clat1 * clat1\n\ttanlat1sq := slat1 * slat1 / clat1sq\n\te2 := e * e\n\te4 := e2 * e2\n\te6 := e4 * e2\n\teg := (e * a / b)\n\teg2 := eg\n\tl1 := 1 - e2/4 - 3*e4/64 - 5*e6/256\n\tl2 := 3*e2/8 + 3*e4/32 + 45*e6/1024\n\tl3 := 15*e4/256 + 45*e6/1024\n\tl4 := 35 * e6 / 3072\n\tM := a * (l1*lat - l2*math.Sin(2*lat) + l3*math.Sin(4*lat) - l4*math.Sin(6*lat))\n\t//double rho = a*(1-e2) / pow((1-(e*slat1)*(e*slat1)),1.5);\n\tnu := a / math.Sqrt(1-(e*slat1)*(e*slat1))\n\tp := lon - grid[to].lon0\n\tk0 := grid[to].k0\n\t// y = northing = K1 + K2p2 + K3p4, where\n\tK1 := M * k0\n\tK2 := k0 * nu * slat1 * clat1 / 2\n\tK3 := (k0 * nu * slat1 * clat1 * clat1sq / 24) * (5 - tanlat1sq + 9*eg2*clat1sq + 4*eg2*eg2*clat1sq*clat1sq)\n\t// ING north\n\tY := K1 + K2*p*p + K3*p*p*p*p - grid[to].falseN\n\n\t// x = easting = K4p + K5p3, where\n\tK4 := k0 * nu * clat1\n\tK5 := (k0 * nu * clat1 * clat1sq / 6) * (1 - tanlat1sq + eg2*clat1*clat1)\n\t// ING east\n\tX := K4*p + K5*p*p*p + grid[to].falseE\n\n\t// final rounded results\n\tE := int(X + 0.5)\n\tN := int(Y + 0.5)\n\treturn E, N\n}", "func FSobel(in image.Image) image.Image {\n\tloadedImage := in\n\n\t//Creation of a new image with the same dimensions as the input one\n\tb := loadedImage.Bounds()\n\tminx, miny := b.Min.X, b.Min.Y\n\tmaxx, maxy := b.Max.X, b.Max.Y\n\tw, h := b.Dx(), b.Dy()\n\tmyImage := image.NewRGBA(loadedImage.Bounds())\n\n\t//convertion in greyscale with the BW algo\n\tgris := make([][]int16, h)\n\tfor i := range gris {\n\t\tgris[i] = make([]int16, w)\n\t}\n\tfor cpt := miny; cpt < maxy; cpt++ {\n\t\tfor cpt2 := minx; cpt2 < maxx; cpt2++ {\n\t\t\tred, gr, blue, _ := loadedImage.At(cpt2, cpt).RGBA()\n\t\t\tgris[cpt-miny][cpt2-minx] = int16(0.2125*float32(red*255/65535) + 0.7154*float32(gr*255/65535) + 0.0721*float32(blue*255/65535))\n\n\t\t}\n\t}\n\t//Edge-detection algorithm applied to each pixel\n\tvar maxG float64 = 0 //we save the highest value of gradient for mapping the values\n\tgradient := make([][]float64, h)\n\tfor i := range gradient {\n\t\tgradient[i] = make([]float64, w)\n\t}\n\tfor cpt := miny + 1; cpt < maxy-2; cpt++ {\n\t\tfor cpt2 := minx + 1; cpt2 < maxx-2; cpt2++ {\n\t\t\tvar gx float64\n\t\t\tgx = float64(-1*gris[cpt-1-miny][cpt2-1-minx] + 1*gris[cpt+1-miny][cpt2-1-minx] + -2*gris[cpt-1-miny][cpt2-minx] + 2*gris[cpt+1-miny][cpt2-minx] - 1*gris[cpt-1-miny][cpt2+1-minx] + 1*gris[cpt+1-miny][cpt2+1-minx])\n\t\t\tgy := float64(-1*gris[cpt-1-miny][cpt2-1-minx] - 2*gris[cpt-miny][cpt2-1-minx] - 1*gris[cpt+1-miny][cpt2-1-minx] + 1*gris[cpt-1-miny][cpt2+1-minx] + 2*gris[cpt-miny][cpt2+1-minx] + 1*gris[cpt+1-miny][cpt2+1-minx])\n\t\t\tgradient[cpt-miny][cpt2-minx] = math.Sqrt(gx*gx + gy*gy)\n\t\t\tif gradient[cpt-miny][cpt2-minx] > maxG {\n\t\t\t\tmaxG = gradient[cpt-miny][cpt2-minx]\n\t\t\t}\n\n\t\t}\n\t}\n\tfor cpt := miny + 1; cpt < maxy-2; cpt++ {\n\t\tfor cpt2 := minx + 1; cpt2 < maxx-2; cpt2++ {\n\t\t\tvar valsobel uint8\n\t\t\tif gradient[cpt-miny][cpt2-minx] > 255 {\n\t\t\t\tvalsobel = 255\n\t\t\t}\n\t\t\tvalsobel = uint8(gradient[cpt-miny][cpt2-minx] * 255 / maxG)\n\t\t\tmyImage.Set(cpt2, cpt, color.RGBA{valsobel, valsobel, valsobel, 255})\n\t\t}\n\t}\n\treturn myImage\n\n}", "func (eReference *eReferenceImpl) GetEKeys() EList {\n\tif eReference.eKeys == nil {\n\t\teReference.eKeys = eReference.asInitializers().initEKeys()\n\t}\n\treturn eReference.eKeys\n}", "func ELng(lng float64) float64 {\n\tfor 360 <= lng {\n\t\tlng -= 360\n\t}\n\tfor lng < 0 {\n\t\tlng += 360\n\t}\n\treturn lng\n}", "func (g *EWgraph) E() int {\n\treturn g.e\n}", "func (etf *Etf) RefineEtf(kernel int) {\n\twidth, height := etf.flowField.Cols(), etf.flowField.Rows()\n\tetf.wg.Add(width * height)\n\n\tfor y := 0; y < height; y++ {\n\t\tfor x := 0; x < width; x++ {\n\t\t\t// Spawn computation into separate goroutines\n\t\t\tgo func(y, x int) {\n\t\t\t\tetf.mu.Lock()\n\t\t\t\tetf.computeNewVector(x, y, kernel)\n\t\t\t\tetf.mu.Unlock()\n\n\t\t\t\tetf.wg.Done()\n\t\t\t}(y, x)\n\t\t}\n\t}\n\tetf.wg.Wait()\n\tetf.flowField = etf.refinedEtf.Clone()\n}", "func GetEarthquakes() []Earthquake {\n\tearthquakeDetails := earthquakeData()\n\tearthquakes := []Earthquake{}\n\n\tfor _, locFeature := range earthquakeDetails.Features {\n\t\tearthquake := featureToEarthquakeFormat(locFeature)\n\t\tearthquakes = append(earthquakes, *earthquake)\n\t}\n\n\treturn earthquakes\n}", "func StartGE() *GE {\n\tg := &GE{Engine: gin.New(), Dependency: NewDependency()}\n\tg.Use(ErrorHandler())\n\treturn g\n}", "func getcoordinates(quakes Quakes) [][]float64 {\n\tvar geomplaces [][]float64\n\tfor _, quake := range quakes.Features {\n\t\tpoint := []float64{quake.Geometry.Coordinates[1], quake.Geometry.Coordinates[0]}\n\t\tgeomplaces = append(geomplaces, point)\n\t}\n\treturn geomplaces\n}", "func (s *Surface) GetVehicleAngels(x, y, phi, a, b float64) (float64, float64) {\n\txbr := x + a*math.Cos(phi) + b*math.Sin(phi)\n\txtr := x + a*math.Cos(phi) - b*math.Sin(phi)\n\txtl := x - a*math.Cos(phi) - b*math.Sin(phi)\n\txbl := x - a*math.Cos(phi) + b*math.Sin(phi)\n\n\tybr := y + a*math.Sin(phi) - b*math.Cos(phi)\n\tytr := y + a*math.Sin(phi) + b*math.Cos(phi)\n\tytl := y - a*math.Sin(phi) + b*math.Cos(phi)\n\tybl := y - a*math.Sin(phi) - b*math.Cos(phi)\n\n\tztr := s.GetHeight(xtr, ytr)\n\tztl := s.GetHeight(xtl, ytl)\n\tzbl := s.GetHeight(xbl, ybl)\n\tzbr := s.GetHeight(xbr, ybr)\n\n\ttltr := r3.Vector{X: xtr - xtl, Y: ytr - ytl, Z: ztr - ztl}\n\ttrbr := r3.Vector{X: xbr - xtr, Y: ybr - ytr, Z: zbr - ztr}\n\tbrbl := r3.Vector{X: xbl - xbr, Y: ybl - ybr, Z: zbl - zbr}\n\tbltl := r3.Vector{X: xtl - xbl, Y: ytl - ybl, Z: ztl - zbl}\n\n\tntl := bltl.Cross(tltr).Normalize()\n\tntr := tltr.Cross(trbr).Normalize()\n\tnbr := trbr.Cross(brbl).Normalize()\n\tnbl := brbl.Cross(bltl).Normalize()\n\n\tn := ntl.Add(ntr).Add(nbr).Add(nbl).Mul(0.25)\n\n\treturn 90 - n.Angle(r3.Vector{X: -math.Sin(phi), Y: math.Cos(phi), Z: 0}).Degrees(), -90 + n.Angle(r3.Vector{X: math.Cos(phi), Y: math.Sin(phi), Z: 0}).Degrees()\n}", "func Grid2LatLon(N, E float64, from gGrid, to eDatum) (float64, float64) {\n\t//================\n\t// GRID -> Lat/Lon\n\t//================\n\ty := N + grid[from].falseN\n\tx := E - grid[from].falseE\n\tM := y / grid[from].k0\n\ta := Datum[to].a\n\tb := Datum[to].b\n\te := Datum[to].e\n\tesq := Datum[to].esq\n\tmu := M / (a * (1 - e*e/4 - 3*math.Pow(e, 4)/64 - 5*math.Pow(e, 6)/256))\n\n\tee := math.Sqrt(1 - esq)\n\te1 := (1 - ee) / (1 + ee)\n\tj1 := 3*e1/2 - 27*e1*e1*e1/32\n\tj2 := 21*e1*e1/16 - 55*e1*e1*e1*e1/32\n\tj3 := 151 * e1 * e1 * e1 / 96\n\tj4 := 1097 * e1 * e1 * e1 * e1 / 512\n\t// Footprint Latitude\n\tfp := mu + j1*math.Sin(2*mu) + j2*math.Sin(4*mu) + j3*math.Sin(6*mu) + j4*math.Sin(8*mu)\n\n\tsinfp := math.Sin(fp)\n\tcosfp := math.Cos(fp)\n\ttanfp := sinfp / cosfp\n\teg := (e * a / b)\n\teg2 := eg * eg\n\tC1 := eg2 * cosfp * cosfp\n\tT1 := tanfp * tanfp\n\tR1 := a * (1 - e*e) / math.Pow(1-(e*sinfp)*(e*sinfp), 1.5)\n\tN1 := a / math.Sqrt(1-(e*sinfp)*(e*sinfp))\n\tD := x / (N1 * grid[from].k0)\n\n\tQ1 := N1 * tanfp / R1\n\tQ2 := D * D / 2\n\tQ3 := (5 + 3*T1 + 10*C1 - 4*C1*C1 - 9*eg2*eg2) * (D * D * D * D) / 24\n\tQ4 := (61 + 90*T1 + 298*C1 + 45*T1*T1 - 3*C1*C1 - 252*eg2*eg2) * (D * D * D * D * D * D) / 720\n\t// result lat\n\tlat := fp - Q1*(Q2-Q3+Q4)\n\n\tQ5 := D\n\tQ6 := (1 + 2*T1 + C1) * (D * D * D) / 6\n\tQ7 := (5 - 2*C1 + 28*T1 - 3*C1*C1 + 8*eg2*eg2 + 24*T1*T1) * (D * D * D * D * D) / 120\n\t// result lon\n\tlon := grid[from].lon0 + (Q5-Q6+Q7)/cosfp\n\treturn lat, lon\n}", "func NewTePhotoelastic() Tensor4 {\n\treturn NewTrigonalPhotoelasticTensor(0.164, 0.138, 0.146, -0.086, 0.038, -0.04, 0.28, 0.14)\n}", "func (geom Geometry) Envelope() Envelope {\n\tvar env Envelope\n\tC.OGR_G_GetEnvelope(geom.cval, &env.cval)\n\treturn env\n}", "func (d Degrees) E7() int32 { return round(float64(d * 1e7)) }", "func tElliptic(s float64) float64 {\n\tm := (2 * math.Sqrt(s*s-s+1) / s) + (2 / s) - 1\n\tx := m\n\ty := m + 3 - 2*math.Sqrt(3)\n\tz := m + 3 + 2*math.Sqrt(3)\n\treturn 4 * mathext.EllipticRF(x, y, z)\n}", "func (e *E6) Inverse(cs *frontend.ConstraintSystem, e1 *E6, ext Extension) *E6 {\n\n\tvar t [7]E2\n\tvar c [3]E2\n\tvar buf E2\n\n\tt[0].Mul(cs, &e1.B0, &e1.B0, ext)\n\tt[1].Mul(cs, &e1.B1, &e1.B1, ext)\n\tt[2].Mul(cs, &e1.B2, &e1.B2, ext)\n\tt[3].Mul(cs, &e1.B0, &e1.B1, ext)\n\tt[4].Mul(cs, &e1.B0, &e1.B2, ext)\n\tt[5].Mul(cs, &e1.B1, &e1.B2, ext)\n\n\tc[0].MulByIm(cs, &t[5], ext)\n\n\tc[0].Neg(cs, &c[0]).Add(cs, &c[0], &t[0])\n\n\tc[1].MulByIm(cs, &t[2], ext)\n\n\tc[1].Sub(cs, &c[1], &t[3])\n\tc[2].Sub(cs, &t[1], &t[4])\n\tt[6].Mul(cs, &e1.B2, &c[1], ext)\n\tbuf.Mul(cs, &e1.B1, &c[2], ext)\n\tt[6].Add(cs, &t[6], &buf)\n\n\tt[6].MulByIm(cs, &t[6], ext)\n\n\tbuf.Mul(cs, &e1.B0, &c[0], ext)\n\tt[6].Add(cs, &t[6], &buf)\n\n\tt[6].Inverse(cs, &t[6], ext)\n\te.B0.Mul(cs, &c[0], &t[6], ext)\n\te.B1.Mul(cs, &c[1], &t[6], ext)\n\te.B2.Mul(cs, &c[2], &t[6], ext)\n\n\treturn e\n\n}", "func Inv(proj *Proj, x, y float64) (long, lat float64, err error) {\n\tif !proj.opened {\n\t\treturn math.NaN(), math.NaN(), errors.New(\"projection is closed\")\n\t}\n\tx2 := C.double(x)\n\ty2 := C.double(y)\n\te := C.inv(proj.pj, &x2, &y2)\n\tif e != nil {\n\t\treturn math.NaN(), math.NaN(), errors.New(C.GoString(e))\n\t}\n\treturn float64(x2), float64(y2), nil\n}", "func (r *Rover) fromEast(com string) {\n\toptions := map[string]string{\"L\": \"NORTH\", \"R\": \"SOUTH\"}\n\tr.Dir = options[com]\n}", "func (xyz XYZ) CIELab(ref XYZ) CIELab {\n\tX := xyz.X / ref.X\n\tY := xyz.Y / ref.Y\n\tZ := xyz.Z / ref.Z\n\n\tif X > 0.008856 {\n\t\tX = math.Pow(X, (1.0 / 3))\n\t} else {\n\t\tX = (7.787 * X) + (16.0 / 116)\n\t}\n\n\tif Y > 0.008856 {\n\t\tY = math.Pow(Y, (1.0 / 3))\n\t} else {\n\t\tY = (7.787 * Y) + (16.0 / 116)\n\t}\n\n\tif Z > 0.008856 {\n\t\tZ = math.Pow(Z, (1.0 / 3))\n\t} else {\n\t\tZ = (7.787 * Z) + (16.0 / 116)\n\t}\n\n\treturn CIELab{\n\t\tL: (116.0 * Y) - 16,\n\t\tA: 500.0 * (X - Y),\n\t\tB: 200.0 * (Y - Z),\n\t}\n}", "func XYZ(width, height int) (*ImageRef, error) {\n\tvipsImage, err := vipsXYZ(width, height)\n\treturn newImageRef(vipsImage, ImageTypeUnknown, ImageTypeUnknown, nil), err\n}", "func newEReferenceImpl() *eReferenceImpl {\n\teReference := new(eReferenceImpl)\n\teReference.SetInterfaces(eReference)\n\teReference.Initialize()\n\treturn eReference\n}", "func (e *Engine) ElEq(a tensor.Tensor, b tensor.Tensor, opts ...tensor.FuncOpt) (retVal tensor.Tensor, err error) {\n\tname := constructName2(a, b, \"eq\")\n\n\tif !e.HasFunc(name) {\n\t\treturn nil, errors.Errorf(\"Unable to perform ElEq(). The tensor engine does not have the function %q\", name)\n\t}\n\n\tif err = binaryCheck(a, b); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Basic checks failed for ElEq\")\n\t}\n\n\tvar reuse tensor.DenseTensor\n\tvar safe, toReuse bool\n\tif reuse, safe, toReuse, _, _, err = handleFuncOpts(a.Shape(), a.Dtype(), a.DataOrder(), true, opts...); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Unable to handle funcOpts\")\n\t}\n\n\tvar mem, memB cu.DevicePtr\n\tvar size int64\n\n\tswitch {\n\tcase toReuse:\n\t\tmem = cu.DevicePtr(reuse.Uintptr())\n\t\tmemA := cu.DevicePtr(a.Uintptr())\n\t\tmemSize := int64(a.MemSize())\n\t\te.memcpy(mem, memA, memSize)\n\n\t\tsize = int64(logicalSize(reuse.Shape()))\n\t\tretVal = reuse\n\tcase !safe:\n\t\tmem = cu.DevicePtr(a.Uintptr())\n\t\tretVal = a\n\t\tsize = int64(logicalSize(a.Shape()))\n\tdefault:\n\t\treturn nil, errors.New(\"Impossible state: A reuse tensor must be passed in, or the operation must be unsafe. Incr and safe operations are not supported\")\n\t}\n\n\tmemB = cu.DevicePtr(b.Uintptr())\n\tfn := e.f[name]\n\tgridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ := e.ElemGridSize(int(size))\n\targs := []unsafe.Pointer{\n\t\tunsafe.Pointer(&mem),\n\t\tunsafe.Pointer(&memB),\n\t\tunsafe.Pointer(&size),\n\t}\n\tlogf(\"gx %d, gy %d, gz %d | bx %d by %d, bz %d\", gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ)\n\tlogf(\"CUDADO %q, Mem: %v MemB: %v size %v, args %v\", name, mem, memB, size, args)\n\tlogf(\"LaunchKernel Params. mem: %v. Size %v\", mem, size)\n\te.c.LaunchAndSync(fn, gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ, 0, cu.NoStream, args)\n\treturn\n}", "func (Project) Edges() []ent.Edge {\n\treturn nil\n}", "func (crs TransverseMercator) FromWGS84(x0, y0, z0 float64) (x, y, z float64) {\n\treturn fromWGS84(crs.GeodeticDatum, x0, y0, z0)\n}", "func geoToMercator(longitude, latitude float64) (float64, float64) {\n\t// bound to world coordinates\n\tif latitude > 80 {\n\t\tlatitude = 80\n\t} else if latitude < -80 {\n\t\tlatitude = -80\n\t}\n\n\torigin := 6378137 * math.Pi // 6378137 is WGS84 semi-major axis\n\tx := longitude * origin / 180\n\ty := math.Log(math.Tan((90+latitude)*math.Pi/360)) / (math.Pi / 180) * (origin / 180)\n\n\treturn x, y\n}", "func (v *vertex) OutE(labels ...string) interfaces.Edge {\n\tquery := multiParamQuery(\".outE\", labels...)\n\tv.Add(query)\n\treturn NewEdgeV(v)\n}", "func (o *Orbit) ToXCentric(b CelestialObject, dt time.Time) {\n\tif o.Origin.Name == b.Name {\n\t\tpanic(fmt.Errorf(\"already in orbit around %s\", b.Name))\n\t}\n\n\t// Using SPICE for the conversion.\n\tstate := make([]float64, 6)\n\tfor i := 0; i < 3; i++ {\n\t\tstate[i] = o.rVec[i]\n\t\tstate[i+3] = o.vVec[i]\n\t}\n\ttoFrame := \"IAU_\" + b.Name\n\tif b.Equals(Sun) {\n\t\ttoFrame = \"ECLIPJ2000\"\n\t}\n\tfromFrame := \"IAU_\" + o.Origin.Name\n\tif o.Origin.Equals(Sun) {\n\t\tfromFrame = \"ECLIPJ2000\"\n\t}\n\tpstate := smdConfig().ChgFrame(toFrame, fromFrame, dt, state)\n\to.rVec = pstate.R\n\to.vVec = pstate.V\n\n\to.Origin = b // Don't forget to switch origin\n}", "func GetCurrentEngineAndExtras(v *longhorn.Volume, es map[string]*longhorn.Engine) (currentEngine *longhorn.Engine, extras []*longhorn.Engine, err error) {\n\tfor _, e := range es {\n\t\tif e.Spec.Active {\n\t\t\tif currentEngine != nil {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"BUG: found the second active engine %v besides %v\", e.Name, currentEngine.Name)\n\t\t\t}\n\t\t\tcurrentEngine = e\n\t\t} else {\n\t\t\textras = append(extras, e)\n\t\t}\n\t}\n\tif currentEngine == nil {\n\t\tlogrus.Warnf(\"failed to directly pick up the current one from multiple engines for volume %v, fall back to detect the new current engine, \"+\n\t\t\t\"current node %v, desire node %v\", v.Name, v.Status.CurrentNodeID, v.Spec.NodeID)\n\t\treturn GetNewCurrentEngineAndExtras(v, es)\n\t}\n\treturn\n}", "func GetNewCurrentEngineAndExtras(v *longhorn.Volume, es map[string]*longhorn.Engine) (currentEngine *longhorn.Engine, extras []*longhorn.Engine, err error) {\n\toldEngineName := \"\"\n\tfor name := range es {\n\t\te := es[name]\n\t\tif e.Spec.Active {\n\t\t\toldEngineName = e.Name\n\t\t}\n\t\tif (v.Spec.NodeID != \"\" && v.Spec.NodeID == e.Spec.NodeID) ||\n\t\t\t(v.Status.CurrentNodeID != \"\" && v.Status.CurrentNodeID == e.Spec.NodeID) ||\n\t\t\t(v.Status.PendingNodeID != \"\" && v.Status.PendingNodeID == e.Spec.NodeID) {\n\t\t\tif currentEngine != nil {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"BUG: found the second new active engine %v besides %v\", e.Name, currentEngine.Name)\n\t\t\t}\n\t\t\tcurrentEngine = e\n\t\t\tcurrentEngine.Spec.Active = true\n\t\t} else {\n\t\t\textras = append(extras, e)\n\t\t}\n\t}\n\n\tif currentEngine == nil {\n\t\treturn nil, nil, fmt.Errorf(\"cannot find the current engine for the switching after iterating and cleaning up all engines for volume %v, all engines may be detached or in a transient state\", v.Name)\n\t}\n\n\tif currentEngine.Name != oldEngineName {\n\t\tlogrus.Infof(\"Found the new current engine %v for volume %v, the old one is %v\", currentEngine.Name, v.Name, oldEngineName)\n\t} else {\n\t\tlogrus.Infof(\"The current engine for volume %v is still %v\", v.Name, currentEngine.Name)\n\t}\n\n\treturn\n}", "func NewTeEps() Mat3 {\n\treturn Uniaxial(4.8*4.8, 6.2*6.2)\n}", "func entrance0(size v3.Vec) (sdf.SDF3, error) {\n\tr := size.Y * 0.5\n\ts0 := sdf.Line2D(size.X-(2*r), r)\n\ts1 := sdf.Extrude3D(s0, size.Z)\n\treturn s1, nil\n}", "func (dw *DrawingWand) PathEllipticArcAbsolute(rx, ry, xAxisRotation float64, largeArcFlag, sweepFlag bool, x, y float64) {\n\tC.MagickDrawPathEllipticArcAbsolute(dw.dw, C.double(rx), C.double(ry), C.double(xAxisRotation), b2i(largeArcFlag), b2i(sweepFlag), C.double(x), C.double(y))\n}", "func (crs AlbersEqualAreaConic) ToLonLat(east, north float64, gs GeodeticSpheroid) (lon, lat float64) {\n\ts := spheroid(gs, crs.GeodeticDatum)\n\teast -= crs.Eastf\n\tnorth -= crs.Northf\n\tρi := math.Sqrt(east*east + math.Pow(crs._ρ(radian(crs.Latf), s)-north, 2))\n\tqi := (crs._C(s) - ρi*ρi*crs._n(s)*crs._n(s)/s.A2()) / crs._n(s)\n\tφ := math.Asin(qi / 2)\n\tfor i := 0; i < 5; i++ {\n\t\tφ += math.Pow(1-s.E2()*sin2(φ), 2) /\n\t\t\t(2 * math.Cos(φ)) * (qi/(1-s.E2()) -\n\t\t\tmath.Sin(φ)/(1-s.E2()*sin2(φ)) +\n\t\t\t1/(2*s.E())*math.Log((1-s.E()*math.Sin(φ))/(1+s.E()*math.Sin(φ))))\n\t}\n\tθ := math.Atan(east / (crs._ρ(radian(crs.Latf), s) - north))\n\treturn degree(radian(crs.Lonf) + θ/crs._n(s)), degree(φ)\n}", "func (d Degrees) E6() int32 { return round(float64(d * 1e6)) }", "func (gdt *Vector3) Outer(b Vector3) Basis {\n\targ0 := gdt.getBase()\n\targ1 := b.getBase()\n\n\tret := C.go_godot_vector3_outer(GDNative.api, arg0, arg1)\n\n\treturn Basis{base: &ret}\n\n}", "func (gps *GPS) Mercator_encrypt( wgsLat float64, wgsLon float64) map[string]float64 {\n x := wgsLon * 20037508.34 / 180.\n y := math.Log(math.Tan((90. + wgsLat) * PI / 360.)) / (PI / 180.)\n y = y * 20037508.34 / 180.\n return map[string]float64{\"lat\": y, \"lon\": x}\n\n}", "func RT90toWGS84(x float64, y float64) (float64, float64) {\n\tvar xi = (x - falseNorthing) / (scale * aRoof)\n\tvar eta = (y - falseEasting) / (scale * aRoof)\n\tvar xiPrim = xi -\n\t\tdelta1*math.Sin(2.0*xi)*math.Cosh(2.0*eta) -\n\t\tdelta2*math.Sin(4.0*xi)*math.Cosh(4.0*eta) -\n\t\tdelta3*math.Sin(6.0*xi)*math.Cosh(6.0*eta) -\n\t\tdelta4*math.Sin(8.0*xi)*math.Cosh(8.0*eta)\n\tvar etaPrim = eta -\n\t\tdelta1*math.Cos(2.0*xi)*math.Sinh(2.0*eta) -\n\t\tdelta2*math.Cos(4.0*xi)*math.Sinh(4.0*eta) -\n\t\tdelta3*math.Cos(6.0*xi)*math.Sinh(6.0*eta) -\n\t\tdelta4*math.Cos(8.0*xi)*math.Sinh(8.0*eta)\n\tvar phiStar = math.Asin(math.Sin(xiPrim) / math.Cosh(etaPrim))\n\tvar deltaLambda = math.Atan(math.Sinh(etaPrim) / math.Cos(xiPrim))\n\tvar lngRadian = lambdaZero + deltaLambda\n\tvar latRadian = phiStar + math.Sin(phiStar)*math.Cos(phiStar)*\n\t\t(aStar+\n\t\t\tbStar*(math.Pow(math.Sin(phiStar), 2))+\n\t\t\tcStar*(math.Pow(math.Sin(phiStar), 4))+\n\t\t\tdStar*(math.Pow(math.Sin(phiStar), 6)))\n\treturn latRadian * 180.0 / math.Pi, lngRadian * 180.0 / math.Pi\n}", "func Ics2wgs84(N, E float64) (float64, float64) {\n\t// 1. Local Grid (ICS) -> Clark_1880_modified\n\tlat80, lon80 := Grid2LatLon(N, E, gICS, eCLARK80M)\n\n\t// 2. molodensky Clark_1880_modified -> WGS84\n\tlat84, lon84 := molodensky(lat80, lon80, eCLARK80M, eWGS84)\n\n\t// final results\n\tlat := lat84 * 180 / pi\n\tlon := lon84 * 180 / pi\n\treturn lat, lon\n}", "func (c *container) Ellipse(cx, cy, rx, ry float64) *Ellipse {\n\te := &Ellipse{Cx: cx, Cy: cy, Rx: rx, Ry: ry}\n\tc.contents = append(c.contents, e)\n\n\treturn e\n}", "func (v *Vector3D) X() float64 {\n\treturn v.E1\n}", "func North(value float64) *SimpleElement { return newSEFloat(\"north\", value) }", "func simpleEC(this js.Value, inputs []js.Value) interface{} {\n\tvar suite = suites.MustFind(\"Ed25519\")\n\tvar args map[string]interface{}\n\tjson.Unmarshal([]byte(inputs[0].String()), &args)\n\tscalar := suite.Scalar()\n\tscalarB, _ := base64.StdEncoding.DecodeString(args[\"scalar\"].(string))\n\tscalar.UnmarshalBinary(scalarB)\n\tvar resultB []byte\n\tfor i := 0; i < 1; i++ {\n\t\tresultB, _ = suite.Point().Mul(scalar, nil).MarshalBinary()\n\t}\n\targs[\"result\"] = base64.StdEncoding.EncodeToString(resultB)\n\t//args[\"resultTest\"] = result.String()\n\targs[\"Accepted\"] = \"true\"\n\treturn args\n}", "func NewEngine(filename string) (e *Engine) {\n\traw, err := readLevelAsString(filename)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// remove the \"\\r\" from stupid windows files...\n\traw = strings.Replace(raw, \"\\r\", \"\", -1)\n\t// get single lines in an array\n\tlines := strings.Split(raw, \"\\n\")\n\n\te = new(Engine)\n\te.Surface = Surface{{}}\n\te.Targets = Points{}\n\te.History = []State{}\n\te.CurrentState = State{Points{}, Point{0, 0}}\n\ty := 0\n\tmaxlen := 0\n\tvar char uint8\n\n\tfor _, line := range lines {\n\t\tif len(line) > 0 && line[0] == '#' && len(line) > maxlen {\n\t\t\tmaxlen = len(line)\n\t\t}\n\t}\n\n\tfor _, line := range lines {\n\t\t// filter empty lines and lines that do not start with '#'\n\t\tif len(line) == 0 || line[0] != '#' {\n\t\t\tcontinue\n\t\t}\n\t\tfor x := 0; x < maxlen; x++ {\n\t\t\tchar = '#'\n\t\t\tif x < len(line) {\n\t\t\t\tchar = line[x]\n\t\t\t}\n\t\t\tswitch char {\n\t\t\tcase '#':\n\t\t\t\t// wall\n\t\t\t\te.Surface[y] = append(e.Surface[y], WALL)\n\t\t\tcase ' ':\n\t\t\t\t// empty\n\t\t\t\te.Surface[y] = append(e.Surface[y], EMPTY)\n\t\t\tcase '$':\n\t\t\t\t// box, empty\n\t\t\t\te.Surface[y] = append(e.Surface[y], EMPTY)\n\t\t\t\te.CurrentState.Boxes[NewPoint(x, y)] = true\n\t\t\tcase '@':\n\t\t\t\t// figure, empty\n\t\t\t\te.Surface[y] = append(e.Surface[y], EMPTY)\n\t\t\t\te.CurrentState.Figure = NewPoint(x, y)\n\t\t\tcase '.':\n\t\t\t\t// target\n\t\t\t\te.Surface[y] = append(e.Surface[y], EMPTY)\n\t\t\t\te.Targets[NewPoint(x, y)] = true\n\t\t\tcase '*':\n\t\t\t\t// target, box\n\t\t\t\te.Surface[y] = append(e.Surface[y], EMPTY)\n\t\t\t\te.CurrentState.Boxes[NewPoint(x, y)] = true\n\t\t\tcase '+':\n\t\t\t\t// target, figure\n\t\t\t\te.Surface[y] = append(e.Surface[y], EMPTY)\n\t\t\t\te.CurrentState.Figure = NewPoint(x, y)\n\t\t\tdefault:\n\t\t\t\tpanic(\"Unknown character in level file: \" + string(char))\n\t\t\t}\n\t\t}\n\t\ty++\n\t\te.Surface = append(e.Surface, []Field{})\n\t}\n\t// the last sub-array of Surface is always empty, so remove it...\n\tif len(e.Surface[len(e.Surface)-1]) == 0 {\n\t\te.Surface = e.Surface[:len(e.Surface)-1]\n\t}\n\treturn\n}", "func (o *HyperflexReplicationPlatDatastore) GetDatastoreEr() HyperflexEntityReference {\n\tif o == nil || o.DatastoreEr.Get() == nil {\n\t\tvar ret HyperflexEntityReference\n\t\treturn ret\n\t}\n\treturn *o.DatastoreEr.Get()\n}", "func ceClient(uri string, insecure bool, encoding string) (ceclient.Client, error) {\n\ttlsConfig := tls.Config{\n\t\tInsecureSkipVerify: insecure, //nolint:gosec\n\t}\n\thttpTransport := &http.Transport{TLSClientConfig: &tlsConfig}\n\n\t// Create protocol and client\n\ttransport, err := cloudevents.NewHTTP(cloudevents.WithTarget(uri), cloudevents.WithRoundTripper(httpTransport))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"create cloud events http transport\")\n\t}\n\n\tclientOpts := []ceclient.Option{ceclient.WithUUIDs()}\n\tswitch encoding {\n\tcase \"structured\":\n\t\tclientOpts = append(clientOpts, ceclient.WithForceStructured())\n\tcase \"binary\":\n\t\tclientOpts = append(clientOpts, ceclient.WithForceBinary())\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported encoding type specified: %q\", encoding)\n\t}\n\n\tclient, err := cloudevents.NewClient(transport, clientOpts...)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"create cloud events client\")\n\t}\n\n\treturn client, nil\n}", "func (crs TransverseMercator) ToWGS84(x, y, z float64) (x0, y0, z0 float64) {\n\treturn toWGS84(crs.GeodeticDatum, x, y, z)\n}", "func (crs WebMercator) ToXYZ(a, b, c float64, gs GeodeticSpheroid) (x, y, z float64) {\n\ts := spheroid(gs, crs.GeodeticDatum)\n\treturn Projection{\n\t\tGeodeticDatum: crs.GeodeticDatum,\n\t\tCoordinateProjection: crs,\n\t}.ToXYZ(a, b, c, s)\n}", "func GetRootEnforcer(e BasicEnforcer) *casbin.Enforcer {\n\tvar ce ChainedEnforcer\n\tvar ok bool\n\tfor {\n\t\tif ce, ok = e.(ChainedEnforcer); !ok {\n\t\t\treturn e.(*casbin.Enforcer)\n\t\t}\n\t\tif ne := ce.GetParentEnforcer(); ne != nil {\n\t\t\te = ne\n\t\t} else {\n\t\t\treturn ce.GetRootEnforcer()\n\t\t}\n\t}\n}", "func Inverse(lat1, lon1, lat2, lon2 float64) (s12, azi1, azi2 float64) {\n\tlon12 := angNormalize(lon2 - lon1)\n\tlon12 = angRound(lon12)\n\t// Make longitude difference positive.\n\tlonsign := sg(lon12 >= 0)\n\tlon12 *= lonsign\n\tif lon12 == math.Pi {\n\t\tlonsign = 1\n\t}\n\n\t// If really close to the equator, treat as on equator.\n\tlat1 = angRound(lat1)\n\tlat2 = angRound(lat2)\n\n\t// Swap points so that point with higher (abs) latitude is point 1\n\tswapp := sg(math.Abs(lat1) >= math.Abs(lat2))\n\tif swapp < 0 {\n\t\tlonsign *= -1\n\t\tlat1, lat2 = lat2, lat1\n\t}\n\n\t// Make lat1 <= 0\n\tlatsign := sg(lat1 < 0)\n\tlat1 *= latsign\n\tlat2 *= latsign\n\n\t// Now we have\n\t//\n\t// 0 <= lon12 <= 180\n\t// -90 <= lat1 <= 0\n\t// lat1 <= lat2 <= -lat1\n\t//\n\t// lonsign, swapp, latsign register the transformation to bring the\n\t// coordinates to this canonical form. In all cases, false means no change was\n\t// made. We make these transformations so that there are few cases to\n\t// check, e.g., on verifying quadrants in atan2. In addition, this\n\t// enforces some symmetries in the results returned.\n\n\tvar phi, sbet1, cbet1, sbet2, cbet2, s12x, m12x float64\n\n\tphi = lat1\n\t// Ensure cbet1 = +epsilon at poles\n\tsbet1, cbet1 = math.Sincos(phi)\n\tsbet1 *= _f1\n\tif cbet1 == 0. && lat1 < 0 {\n\t\tcbet1 = _tiny\n\t}\n\tsbet1, cbet1 = sinCosNorm(sbet1, cbet1)\n\n\tphi = lat2\n\t// Ensure cbet2 = +epsilon at poles\n\tsbet2, cbet2 = math.Sincos(phi)\n\tsbet2 *= _f1\n\tif cbet2 == 0. {\n\t\tcbet2 = _tiny\n\t}\n\tsbet2, cbet2 = sinCosNorm(sbet2, cbet2)\n\n\t// If cbet1 < -sbet1, then cbet2 - cbet1 is a sensitive measure of the\n\t// |bet1| - |bet2|. Alternatively (cbet1 >= -sbet1), abs(sbet2) + sbet1 is\n\t// a better measure. This logic is used in assigning calp2 in Lambda12.\n\t// Sometimes these quantities vanish and in that case we force bet2 = +/-\n\t// bet1 exactly. An example where is is necessary is the inverse problem\n\t// 48.522876735459 0 -48.52287673545898293 179.599720456223079643\n\t// which failed with Visual Studio 10 (Release and Debug)\n\tif cbet1 < -sbet1 {\n\t\tif cbet2 == cbet1 {\n\t\t\tif sbet2 < 0 {\n\t\t\t\tsbet2 = sbet1\n\t\t\t} else {\n\t\t\t\tsbet2 = -sbet1\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif math.Abs(sbet2) == -sbet1 {\n\t\t\tcbet2 = cbet1\n\t\t}\n\t}\n\n\tlam12 := lon12\n\tslam12, clam12 := math.Sincos(lam12) // lon12 == 90 isn't interesting\n\n\tvar sig12, calp1, salp1, calp2, salp2, omg12 float64\n\t// index zero elements of these arrays are unused\n\tvar (\n\t\tC1a [_nC1 + 1]float64\n\t\tC2a [_nC2 + 1]float64\n\t\tC3a [_nC3]float64\n\t)\n\n\tmeridian := lat1 == -math.Pi/2 || slam12 == 0.0\n\n\tif meridian {\n\n\t\t// Endpoints are on a single full meridian, so the geodesic might lie on\n\t\t// a meridian.\n\n\t\tcalp1, salp2 = clam12, slam12 // Head to the target longitude\n\t\tcalp2, salp2 = 1, 0 // At the target we're heading north\n\n\t\t// tan(bet) = tan(sig) * cos(alp)\n\t\tssig1, csig1 := sbet1, calp1*cbet1\n\t\tssig2, csig2 := sbet2, calp2*cbet2\n\n\t\t// sig12 = sig2 - sig1\n\t\tsig12 = math.Atan2(max(csig1*ssig2-ssig1*csig2, 0), csig1*csig2+ssig1*ssig2)\n\n\t\ts12x, m12x, _ = lengths(_n, sig12, ssig1, csig1, ssig2, csig2, cbet1, cbet2, C1a[:], C2a[:])\n\n\t\t// Add the check for sig12 since zero length geodesics might yield m12 < 0. Test case was\n\t\t//\n\t\t// echo 20.001 0 20.001 0 | Geod -i\n\t\t//\n\t\t// In fact, we will have sig12 > pi/2 for meridional geodesic which is\n\t\t// not a shortest path.\n\t\tif sig12 < 1 || m12x >= 0 {\n\t\t\tm12x *= _a\n\t\t\ts12x *= _b\n\t\t} else {\n\t\t\t// m12 < 0, i.e., prolate and too close to anti-podal\n\t\t\tmeridian = false\n\t\t}\n\n\t}\n\n\tif !meridian && sbet1 == 0 && (_f <= 0 || lam12 <= math.Pi-_f*math.Pi) {\n\n\t\t// Geodesic runs along equator\n\t\tcalp1, salp1, calp2, salp2 = 0, 1, 0, 1\n\t\ts12x = _a * lam12\n\t\tm12x = _b * math.Sin(lam12/_f1)\n\t\tomg12 = lam12 / _f1\n\t\tsig12 = omg12\n\n\t} else if !meridian {\n\n\t\t// Now point1 and point2 belong within a hemisphere bounded by a\n\t\t// meridian and geodesic is neither meridional or equatorial.\n\n\t\t// Figure a starting point for Newton's method\n\t\tsig12, salp1, calp1, salp2, calp2 = inverseStart(sbet1, cbet1, sbet2, cbet2, lam12, salp2, calp2, C1a[:], C2a[:])\n\n\t\tif sig12 >= 0 {\n\n\t\t\t// Short lines (InverseStart sets salp2, calp2)\n\t\t\tw1 := math.Sqrt(1 - _e2*cbet1*cbet1)\n\t\t\ts12x = sig12 * _a * w1\n\t\t\tm12x = w1 * w1 * _a / _f1 * math.Sin(sig12*_f1/w1)\n\t\t\tomg12 = lam12 / w1\n\n\t\t} else {\n\n\t\t\t// Newton's method\n\t\t\tvar ssig1, csig1, ssig2, csig2, eps, ov float64\n\t\t\tnumit := 0\n\t\t\tfor trip := 0; numit < _maxit; numit++ {\n\t\t\t\tvar v, dv float64\n\n\t\t\t\tv, salp2, calp2, sig12, ssig1, csig1, ssig2, csig2, eps, omg12, dv = \n\t\t\t\t\tlambda12(sbet1, cbet1, sbet2, cbet2, salp1, calp1, trip < 1, C1a[:], C2a[:], C3a[:])\n\t\t\t\tv -= lam12\n\n\t\t\t\tif !(math.Abs(v) > _tiny) || !(trip < 1) {\n\t\t\t\t\tif !(math.Abs(v) <= max(_tol1, ov)) {\n\t\t\t\t\t\tnumit = _maxit\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tdalp1 := -v / dv\n\n\t\t\t\tsdalp1, cdalp1 := math.Sincos(dalp1)\n\t\t\t\tnsalp1 := salp1*cdalp1 + calp1*sdalp1\n\t\t\t\tcalp1 = calp1*cdalp1 - salp1*sdalp1\n\t\t\t\tsalp1 = max(0, nsalp1)\n\t\t\t\tsalp1, calp1 = sinCosNorm(salp1, calp1)\n\n\t\t\t\tif !(math.Abs(v) >= _tol1 && v*v >= ov*_tol0) {\n\t\t\t\t\ttrip++\n\t\t\t\t}\n\t\t\t\tov = math.Abs(v)\n\t\t\t}\n\n\t\t\tif numit >= _maxit {\n\t\t\t\treturn math.NaN(), math.NaN(), math.NaN() // Signal failure.\n\t\t\t}\n\n\t\t\ts12x, m12x, _ = lengths(eps, sig12, ssig1, csig1, ssig2, csig2, cbet1, cbet2, C1a[:], C2a[:])\n\n\t\t\tm12x *= _a\n\t\t\ts12x *= _b\n\t\t\tomg12 = lam12 - omg12\n\t\t}\n\t}\n\n\ts12 = 0 + s12x // Convert -0 to 0\n\n\t// Convert calp, salp to azimuth accounting for lonsign, swapp, latsign.\n\tif swapp < 0 {\n\t\tsalp1, salp2 = salp2, salp1\n\t\tcalp1, calp2 = calp2, calp1\n\t}\n\n\tsalp1 *= swapp * lonsign; calp1 *= swapp * latsign;\n\tsalp2 *= swapp * lonsign; calp2 *= swapp * latsign;\n\n\t// minus signs give range [-180, 180). 0- converts -0 to +0.\n\tazi1 = 0 - math.Atan2(-salp1, calp1)\n\tazi2 = 0 - math.Atan2(salp2, -calp2) // make it point backwards\n\n\treturn\n}", "func (crs AlbersEqualAreaConic) FromLonLat(lon, lat float64, gs GeodeticSpheroid) (east, north float64) {\n\ts := spheroid(gs, crs.GeodeticDatum)\n\tθ := crs._n(s) * (radian(lon) - radian(crs.Lonf))\n\teast = crs.Eastf + crs._ρ(radian(lat), s)*math.Sin(θ)\n\tnorth = crs.Northf + crs._ρ(radian(crs.Latf), s) - crs._ρ(radian(lat), s)*math.Cos(θ)\n\treturn east, north\n}", "func (crs AlbersEqualAreaConic) FromWGS84(x0, y0, z0 float64) (x, y, z float64) {\n\treturn fromWGS84(crs.GeodeticDatum, x0, y0, z0)\n}", "func NewECE(maxAge time.Duration, logFile string, maxLogSize int, maxLogBackups int, maxLogAge int, logCompress bool) *ECE {\n\tlogObj := log.New(os.Stdout, \"\", 0)\n\n\tlogObj.SetOutput(&lumberjack.Logger{\n\t\tFilename: logFile,\n\t\tMaxSize: maxLogSize,\n\t\tMaxBackups: maxLogBackups,\n\t\tMaxAge: maxLogAge,\n\t\tCompress: logCompress,\n\t})\n\n\ta := &ECE{\n\t\tTtl: maxAge,\n\t\tlogger: logObj,\n\t\tEvents: make(map[string]*Event),\n\t}\n\n\treturn a\n}", "func TestEe00b(t *testing.T) {\n\tconst fname = \"Ee00b\"\n\tvar ee float64\n\n\ttests := []struct {\n\t\tref string\n\t\tfn func(a1,a2 float64) float64\t\n\t}{\n\t\t{\"cgo\", CgoEe00b},\n\t\t{\"go\", GoEe00b},\n\t}\n\n\tfor _, test := range tests {\n\t\ttname := fname + \" \" + test.ref\n\t\tee = test.fn(2400000.5, 53736.0)\n\n\t\tvvd(t, ee, -0.8835700060003032831e-5, 1e-18, tname, \"\")\n\t}\n}" ]
[ "0.57555723", "0.5633475", "0.56043756", "0.55265075", "0.54089504", "0.53410894", "0.52664757", "0.5026412", "0.49845457", "0.4889047", "0.48806256", "0.4879575", "0.48052537", "0.47927207", "0.47134507", "0.46969742", "0.46880403", "0.46797422", "0.46588522", "0.46408844", "0.46096024", "0.46036005", "0.45409828", "0.45247775", "0.45231947", "0.4498461", "0.44882587", "0.44329852", "0.44326106", "0.44240895", "0.44235975", "0.44124442", "0.44005495", "0.4392374", "0.43667844", "0.43457636", "0.43421298", "0.4331203", "0.43277866", "0.43264335", "0.4321219", "0.43197107", "0.4318676", "0.43100953", "0.43056253", "0.4302714", "0.42766058", "0.4249104", "0.42469084", "0.42462936", "0.4242854", "0.42399502", "0.42394316", "0.42296004", "0.4226755", "0.42209747", "0.42185256", "0.42175925", "0.4212267", "0.4197639", "0.41960734", "0.41824865", "0.41761485", "0.4170654", "0.4163623", "0.4147321", "0.41158152", "0.4114156", "0.4108701", "0.41078866", "0.41077226", "0.41043842", "0.4103364", "0.41025573", "0.40934548", "0.4086376", "0.40857705", "0.40779227", "0.40775147", "0.407507", "0.4063606", "0.40547597", "0.40487728", "0.40425587", "0.40405646", "0.4033478", "0.4028184", "0.40196764", "0.4015404", "0.4011137", "0.39939854", "0.39904675", "0.3988989", "0.3988606", "0.39850944", "0.39826727", "0.39812586", "0.3977366", "0.3963246", "0.39599258" ]
0.6615527
0
Register a new tunnel on this control connection
func (c *Control) registerTunnel(rawTunnelReq *msg.ReqTunnel) { for _, proto := range strings.Split(rawTunnelReq.Protocol, "+") { tunnelReq := *rawTunnelReq tunnelReq.Protocol = proto c.conn.Debug("Registering new tunnel") t, err := NewTunnel(&tunnelReq, c) if err != nil { ack := &msg.NewTunnel{Error: err.Error()} if len(c.tunnels) == 0 { // you can't fail your first tunnel registration // terminate the control connection c.stop <- ack } else { // inform client of failure c.out <- ack } // we're done return } // add it to the list of tunnels c.tunnels = append(c.tunnels, t) // acknowledge success c.out <- &msg.NewTunnel{ Url: t.url, Protocol: proto, ReqId: rawTunnelReq.ReqId, } rawTunnelReq.Hostname = strings.Replace(t.url, proto+"://", "", 1) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (na *Nagent) CreateTunnel(tun *netproto.Tunnel) error {\n\terr := na.validateMeta(tun.Kind, tun.ObjectMeta)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// check if tunnel already exists\n\toldTun, err := na.FindTunnel(tun.ObjectMeta)\n\tif err == nil {\n\t\t// check if tunnel contents are same\n\t\tif !proto.Equal(&oldTun.Spec, &tun.Spec) {\n\t\t\tlog.Errorf(\"Tunnel %+v already exists\", oldTun)\n\t\t\treturn errors.New(\"tunnel already exists\")\n\t\t}\n\n\t\tlog.Infof(\"Received duplicate tunnel create for {%+v}\", tun)\n\t\treturn nil\n\t}\n\t// find the corresponding namespace\n\tns, err := na.FindNamespace(tun.ObjectMeta)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// find the corresponding vrf for the route\n\tvrf, err := na.ValidateVrf(tun.Tenant, tun.Namespace, tun.Spec.VrfName)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to find the vrf %v\", tun.Spec.VrfName)\n\t\treturn err\n\t}\n\t// Allocate ID only on first object creates and use existing ones during config replay\n\tif tun.Status.TunnelID == 0 {\n\t\t// Tunnel IDs and Interface IDs must be unique in the datapath as tunnel is modeled as an interface in HAL.\n\t\ttunnelID, err := na.Store.GetNextID(types.InterfaceID, 0)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Could not allocate tunnel id. {%+v}\", err)\n\t\t\treturn err\n\t\t}\n\t\ttun.Status.TunnelID = tunnelID + types.UplinkOffset + types.TunnelOffset\n\t}\n\n\t// create it in datapath\n\terr = na.Datapath.CreateTunnel(tun, vrf)\n\tif err != nil {\n\t\tlog.Errorf(\"Error creating tunnel in datapath. Nw {%+v}. Err: %v\", tun, err)\n\t\treturn err\n\t}\n\n\t// Add the current tunnel as a dependency to the namespace.\n\terr = na.Solver.Add(ns, tun)\n\tif err != nil {\n\t\tlog.Errorf(\"Could not add dependency. Parent: %v. Child: %v\", ns, tun)\n\t\treturn err\n\t}\n\n\t// Add the current tunnel as a dependency to the vrf.\n\terr = na.Solver.Add(vrf, tun)\n\tif err != nil {\n\t\tlog.Errorf(\"Could not add dependency. Parent: %v. Child: %v\", vrf, tun)\n\t\treturn err\n\t}\n\n\t// save it in db\n\tkey := na.Solver.ObjectKey(tun.ObjectMeta, tun.TypeMeta)\n\tna.Lock()\n\tna.TunnelDB[key] = tun\n\tna.Unlock()\n\tdat, _ := tun.Marshal()\n\terr = na.Store.RawWrite(tun.GetKind(), tun.GetKey(), dat)\n\n\treturn err\n}", "func NewTunnel(m *msg.ReqTunnel, ctl *Control) (t *Tunnel, err error) {\n\tt = &Tunnel{\n\t\treq: m,\n\t\tstart: time.Now(),\n\t\tctl: ctl,\n\t\tLogger: log.NewPrefixLogger(),\n\t}\n\n\tproto := t.req.Protocol\n\tswitch proto {\n\tcase \"tcp\":\n\t\tbindTcp := func(port int) error {\n\t\t\tif t.listener, err = net.ListenTCP(\"tcp\", &net.TCPAddr{IP: net.ParseIP(\"0.0.0.0\"), Port: port}); err != nil {\n\t\t\t\terr = t.ctl.conn.Error(\"Error binding TCP listener: %v\", err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// create the url\n\t\t\taddr := t.listener.Addr().(*net.TCPAddr)\n\t\t\tt.url = fmt.Sprintf(\"tcp://%s:%d\", opts.domain, addr.Port)\n\n\t\t\t// register it\n\t\t\tif err = tunnelRegistry.RegisterAndCache(t.url, t); err != nil {\n\t\t\t\t// This should never be possible because the OS will\n\t\t\t\t// only assign available ports to us.\n\t\t\t\tt.listener.Close()\n\t\t\t\terr = fmt.Errorf(\"TCP listener bound, but failed to register %s\", t.url)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tgo t.listenTcp(t.listener)\n\t\t\treturn nil\n\t\t}\n\n\t\t// use the custom remote port you asked for\n\t\tif t.req.RemotePort != 0 {\n\t\t\tbindTcp(int(t.req.RemotePort))\n\t\t\treturn\n\t\t}\n\n\t\t// try to return to you the same port you had before\n\t\tcachedUrl := tunnelRegistry.GetCachedRegistration(t)\n\t\tif cachedUrl != \"\" {\n\t\t\tvar port int\n\t\t\tparts := strings.Split(cachedUrl, \":\")\n\t\t\tportPart := parts[len(parts)-1]\n\t\t\tport, err = strconv.Atoi(portPart)\n\t\t\tif err != nil {\n\t\t\t\tt.ctl.conn.Error(\"Failed to parse cached url port as integer: %s\", portPart)\n\t\t\t} else {\n\t\t\t\t// we have a valid, cached port, let's try to bind with it\n\t\t\t\tif bindTcp(port) != nil {\n\t\t\t\t\tt.ctl.conn.Warn(\"Failed to get custom port %d: %v, trying a random one\", port, err)\n\t\t\t\t} else {\n\t\t\t\t\t// success, we're done\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Bind for TCP connections\n\t\tbindTcp(0)\n\t\treturn\n\n\tcase \"http\", \"https\":\n\t\tl, ok := listeners[proto]\n\t\tif !ok {\n\t\t\terr = fmt.Errorf(\"Not listening for %s connections\", proto)\n\t\t\treturn\n\t\t}\n\n\t\tif err = registerVhost(t, proto, l.Addr.(*net.TCPAddr).Port); err != nil {\n\t\t\treturn\n\t\t}\n\n\tdefault:\n\t\terr = fmt.Errorf(\"Protocol %s is not supported\", proto)\n\t\treturn\n\t}\n\n\t// pre-encode the http basic auth for fast comparisons later\n\tif m.HttpAuth != \"\" {\n\t\tm.HttpAuth = \"Basic \" + base64.StdEncoding.EncodeToString([]byte(m.HttpAuth))\n\t}\n\n\tt.AddLogPrefix(t.Id())\n\tt.Info(\"Registered new tunnel on: %s\", t.ctl.conn.Id())\n\n\tmetrics.OpenTunnel(t)\n\treturn\n}", "func (db *DB) NewTunnel(tunnel *Tunnel) error {\n\tq := `\nINSERT INTO tunnel (port, forward_port, forward_address) VALUES(?, ?, ?);\n `\n\t_, err := db.Exec(q, tunnel.Port, tunnel.ForwardPort, tunnel.ForwardAddress)\n\treturn err\n}", "func newTunnel(nc *nats.Conn, subject string, readTimeout time.Duration, respHandler func(response *Response)) *Tunnel {\n\treturn &Tunnel{\n\t\tsubject: subject,\n\t\tnc: nc,\n\t\tdone: make(chan bool),\n\t\trespHandler: respHandler,\n\t\trandSuffix: &RandomSuffix{\n\t\t\trandomGenerator: rand.New(rand.NewSource(time.Now().UnixNano())), //nolint gosec\n\t\t},\n\t\tmon: tunnelMon{\n\t\t\treadTimeout: readTimeout,\n\t\t},\n\t}\n}", "func registerVhost(t *Tunnel, protocol string, servingPort int) (err error) {\n\tvhost := os.Getenv(\"VHOST\")\n\tif vhost == \"\" {\n\t\tvhost = fmt.Sprintf(\"%s:%d\", opts.domain, servingPort)\n\t}\n\n\t// Canonicalize virtual host by removing default port (e.g. :80 on HTTP)\n\tdefaultPort, ok := defaultPortMap[protocol]\n\tif !ok {\n\t\treturn fmt.Errorf(\"Couldn't find default port for protocol %s\", protocol)\n\t}\n\n\tif servingPort == defaultPort {\n\t\tvhost = opts.domain\n\t}\n\n\t// Register for specific hostname\n\thostname := strings.ToLower(strings.TrimSpace(t.req.Hostname))\n\tif hostname != \"\" {\n\t\tt.url = fmt.Sprintf(\"%s://%s\", protocol, hostname)\n\t\treturn tunnelRegistry.Register(t.url, t)\n\t}\n\n\t// Register for specific subdomain\n\tsubdomain := strings.ToLower(strings.TrimSpace(t.req.Subdomain))\n\tif subdomain != \"\" {\n\t\tt.url = fmt.Sprintf(\"%s://%s.%s\", protocol, subdomain, vhost)\n\t\treturn tunnelRegistry.Register(t.url, t)\n\t}\n\n\t// Register for random URL\n\tt.url, err = tunnelRegistry.RegisterRepeat(func() string {\n\t\treturn fmt.Sprintf(\"%s://%x.%s\", protocol, rand.Int31(), vhost)\n\t}, t)\n\n\treturn\n}", "func (c *service) OpenTunnel(localAddress, remoteAddress string) error {\n\tlocal, err := net.Listen(\"tcp\", localAddress)\n\tif err != nil {\n\t\treturn errors.Wrap(err, fmt.Sprintf(\"failed to listen on local: %v\", localAddress))\n\t}\n\tvar forwarding = NewForwarding(c.client, remoteAddress, local)\n\tif len(c.forwarding) == 0 {\n\t\tc.forwarding = make([]*Tunnel, 0)\n\t}\n\tc.forwarding = append(c.forwarding, forwarding)\n\tgo forwarding.Handle()\n\treturn nil\n}", "func NewTunnel(dst, src string) *Tunnel {\n\ttunnel := &Tunnel{Src: src, Dst: dst}\n\treturn tunnel\n}", "func (sc stakingClient) RegisterProxy(fromInfo keys.Info, passWd, memo string, accNum, seqNum uint64) (\n\tresp sdk.TxResponse, err error) {\n\tif err = params.CheckKeyParams(fromInfo, passWd); err != nil {\n\t\treturn\n\t}\n\n\tmsg := types.NewMsgRegProxy(fromInfo.GetAddress(), true)\n\n\treturn sc.BuildAndBroadcast(fromInfo.GetName(), passWd, memo, []sdk.Msg{msg}, accNum, seqNum)\n\n}", "func (ghost *Ghost) Register() error {\n\tfor _, addr := range ghost.addrs {\n\t\tvar (\n\t\t\tconn net.Conn\n\t\t\terr error\n\t\t)\n\n\t\tlog.Printf(\"Trying %s ...\\n\", addr)\n\t\tghost.Reset()\n\n\t\t// Check if server has TLS enabled.\n\t\t// Only control channel needs to determine if TLS is enabled. Other mode\n\t\t// should use the tlsSettings passed in when it was spawned.\n\t\tif ghost.mode == ModeControl {\n\t\t\tvar enabled bool\n\n\t\t\tswitch ghost.tlsMode {\n\t\t\tcase TLSDetect:\n\t\t\t\tenabled, err = ghost.tlsEnabled(addr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\tcase TLSForceEnable:\n\t\t\t\tenabled = true\n\t\t\tcase TLSForceDisable:\n\t\t\t\tenabled = false\n\t\t\t}\n\n\t\t\tghost.tls.SetEnabled(enabled)\n\t\t}\n\n\t\tconn, err = net.DialTimeout(\"tcp\", addr, connectTimeout)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Println(\"Connection established, registering...\")\n\t\tif ghost.tls.Enabled {\n\t\t\tcolonPos := strings.LastIndex(addr, \":\")\n\t\t\tconfig := ghost.tls.Config\n\t\t\tconfig.ServerName = addr[:colonPos]\n\t\t\tconn = tls.Client(conn, config)\n\t\t}\n\n\t\tghost.Conn = conn\n\t\treq := NewRequest(\"register\", map[string]interface{}{\n\t\t\t\"mid\": ghost.mid,\n\t\t\t\"sid\": ghost.sid,\n\t\t\t\"mode\": ghost.mode,\n\t\t\t\"properties\": ghost.properties,\n\t\t})\n\n\t\tregistered := func(res *Response) error {\n\t\t\tif res == nil {\n\t\t\t\tghost.reset = true\n\t\t\t\treturn errors.New(\"Register request timeout\")\n\t\t\t} else if res.Response != Success {\n\t\t\t\tlog.Println(\"Register:\", res.Response)\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Registered with Overlord at %s\", addr)\n\t\t\t\tghost.connectedAddr = addr\n\t\t\t\tif err := ghost.Upgrade(); err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t}\n\t\t\t\tghost.pauseLanDisc = true\n\t\t\t}\n\t\t\tghost.RegisterStatus = res.Response\n\t\t\treturn nil\n\t\t}\n\n\t\tvar handler ResponseHandler\n\t\tswitch ghost.mode {\n\t\tcase ModeControl:\n\t\t\thandler = registered\n\t\tcase ModeTerminal:\n\t\t\thandler = ghost.SpawnTTYServer\n\t\tcase ModeShell:\n\t\t\thandler = ghost.SpawnShellServer\n\t\tcase ModeFile:\n\t\t\thandler = ghost.InitiatefileOperation\n\t\tcase ModeForward:\n\t\t\thandler = ghost.SpawnPortModeForwardServer\n\t\t}\n\t\terr = ghost.SendRequest(req, handler)\n\t\treturn nil\n\t}\n\n\treturn errors.New(\"Cannot connect to any server\")\n}", "func (n networkRoute) Register(m *mux.Router, handler http.Handler) {\n}", "func (s *replayService) OpenTunnel(localAddress, remoteAddress string) error {\n\treturn nil\n}", "func (p *Pool) Tunnel(host string, local, remote string) (*Tunnel, error) {\n\n\tlistener, err := net.Listen(\"tcp\", local)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttunnel := &Tunnel{\n\t\tlistener: listener,\n\t\thost: host,\n\t\tremote: remote,\n\t\tpool: p,\n\t}\n\n\tgo tunnel.accept()\n\n\treturn tunnel, nil\n}", "func (o *Overlay) RegisterProtocolInstance(pi ProtocolInstance) error {\n\to.instancesLock.Lock()\n\tdefer o.instancesLock.Unlock()\n\tvar tni *TreeNodeInstance\n\tvar tok = pi.Token()\n\tvar ok bool\n\t// if the TreeNodeInstance doesn't exist\n\tif tni, ok = o.instances[tok.ID()]; !ok {\n\t\treturn ErrWrongTreeNodeInstance\n\t}\n\n\tif tni.isBound() {\n\t\treturn ErrProtocolRegistered\n\t}\n\n\ttni.bind(pi)\n\to.protocolInstances[tok.ID()] = pi\n\tlog.Lvlf4(\"%s registered ProtocolInstance %x\", o.server.Address(), tok.ID())\n\treturn nil\n}", "func (hub *WSHub) Register(conn *websocket.Conn) {\n\thub.mu.Lock()\n\thub.connections[conn] = true\n\thub.mu.Unlock()\n}", "func NewTunnel(fakedns string, dohdns doh.Transport, tunWriter io.WriteCloser, dialer *net.Dialer, config *net.ListenConfig, listener Listener) (Tunnel, error) {\n\tif tunWriter == nil {\n\t\treturn nil, errors.New(\"Must provide a valid TUN writer\")\n\t}\n\tcore.RegisterOutputFn(tunWriter.Write)\n\tt := &intratunnel{\n\t\tTunnel: tunnel.NewTunnel(tunWriter, core.NewLWIPStack()),\n\t}\n\tif err := t.registerConnectionHandlers(fakedns, dialer, config, listener); err != nil {\n\t\treturn nil, err\n\t}\n\tt.SetDNS(dohdns)\n\treturn t, nil\n}", "func New(clientset *kubernetes.Clientset, config *restclient.Config, namespace, deploymentName string, remotePort, localPort int) (*k8s.Tunnel, error) {\n\tpodName, err := getServerPodName(clientset, namespace, deploymentName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debugf(\"found pod: %s\", podName)\n\n\tt := k8s.NewTunnel(clientset.CoreV1().RESTClient(), config, namespace, podName, remotePort)\n\treturn t, t.ForwardPort(localPort)\n}", "func (opt *GuacamoleHTTPTunnelMap) Put(uuid string, tunnel gnet.GuacamoleTunnel) {\n\tone := NewGuacamoleHTTPTunnel(tunnel)\n\topt.tunnelMapLock.Lock()\n\topt.tunnelMap[uuid] = &one\n\topt.tunnelMapLock.Unlock()\n}", "func RegisterProtocol(name string, v interface{}) {\n\troot.Protocols[name] = v\n}", "func (pr *ProxyRegistry) RegisterProxy(proxy *models.Proxy) {\n\tpr.mu.Lock()\n\tdefer pr.mu.Unlock()\n\tpr.connectedProxies[proxy.GetConnectionID()] = proxy\n\tlog.Debug().Str(\"proxy\", proxy.String()).Msgf(\"Registered proxy %s from stream %d\", proxy.String(), proxy.GetConnectionID())\n}", "func sshTunnel(tunnel *config.Tunnel, address, port string) (*sshtun.SSHTun, error) {\n\tdebug := viper.GetBool(\"debug\")\n\n\tlp, err := strconv.Atoi(tunnel.LocalPort)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid local port '%s': %w\", tunnel.LocalPort, err)\n\t}\n\n\trp, err := strconv.Atoi(port)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid remote port '%s': %w\", port, err)\n\t}\n\n\t// Get the address of the intermediate host\n\tserver, _, err := configuration.HostSocket(tunnel.Host, true)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getting ssh tunnel server address: %s\", err)\n\t}\n\n\tsshTun := sshtun.New(lp, server, rp)\n\tsshTun.SetKeyFile(tunnel.Key)\n\tsshTun.SetUser(tunnel.User)\n\tsshTun.SetRemoteHost(address)\n\n\t// We enable debug messages to see what happens\n\tsshTun.SetDebug(debug) //DEBUG\n\n\tif debug {\n\t\t// Print the equivalent SSH command\n\t\tfmt.Printf(\"ssh -i %s -N -L %d:%s:%d %s@%s\\n\",\n\t\t\ttunnel.Key,\n\t\t\tlp,\n\t\t\taddress,\n\t\t\trp,\n\t\t\ttunnel.User,\n\t\t\tserver,\n\t\t)\n\n\t\t// Print tunnel status changes\n\t\tsshTun.SetConnState(func(tun *sshtun.SSHTun, state sshtun.ConnState) {\n\t\t\tswitch state {\n\t\t\tcase sshtun.StateStarting:\n\t\t\t\tlog.Printf(\"SSH tunnel starting\")\n\t\t\tcase sshtun.StateStarted:\n\t\t\t\tlog.Printf(\"SSH tunnel open\")\n\t\t\tcase sshtun.StateStopped:\n\t\t\t\tlog.Printf(\"SSH tunnel Stopped\")\n\t\t\t}\n\t\t})\n\t}\n\n\t// Start the tunnel\n\tgo func() {\n\t\tif err := sshTun.Start(); err != nil {\n\t\t\tlog.Printf(\"SSH tunnel stopped: %s\", err.Error())\n\t\t}\n\t}()\n\n\treturn sshTun, nil\n}", "func RegisterProxy(initialEntry *ServiceEntry, entries chan *ServiceEntry, iface *net.Interface) (*Server, error) {\n\ts, err := newServer(initialEntry, iface)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.waitGroup.Add(1)\n\tgo s.mainloop(entries)\n\n\treturn s, nil\n}", "func StartTunnel(host string, port int) (*Tunnel, error) {\n\n\tngrok, err := startTunnel(host, port)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo ngrok.tail()\n\tngrok.wait()\n\n\treturn ngrok, nil\n}", "func Register(b bot.Bot, hostPort, key string) {\n\tb.Commands().Add(\"tor\", bot.Command{\n\t\tHelp: \"get info on TOR node\",\n\t\tHandler: func(e *bot.Event) { torInfo(e, hostPort, key) },\n\t\tPub: true,\n\t\tPriv: false,\n\t\tHidden: false})\n}", "func NewTunnelIF(name string, counter *vswitch.Counter,\n\tparams CParams) (*TunnelIF, error) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tfor _, direction := range directions {\n\t\tif _, err := moduleNoLock(direction, params); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\ttif := &TunnelIF{\n\t\tname: name,\n\t\tcounter: (*C.struct_vsw_counter)(unsafe.Pointer(counter)),\n\t}\n\n\treturn tif, nil\n}", "func Register(kontrolURL, kiteHome, username, token string, debug bool) error {\n\tvar err error\n\n\t// Open up a prompt if the username is not passed via a flag and it's not a\n\t// token based authentication. If token is empty, it means the user can be\n\t// authenticated via password\n\tif token == \"\" && username == \"\" {\n\t\tusername, err = ask(\"Username:\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// User can just press enter to use the default on the prompt\n\t\tif username == \"\" {\n\t\t\treturn errors.New(\"Username can not be empty.\")\n\t\t}\n\t}\n\n\tk := kite.New(\"klient\", protocol.Version)\n\tk.Config.Environment = protocol.Environment\n\tk.Config.Region = protocol.Region\n\tk.Config.Username = username\n\n\tif debug {\n\t\tk.SetLogLevel(kite.DEBUG)\n\t}\n\n\t// Production Koding servers are only working over HTTP\n\tk.Config.Transport = config.XHRPolling\n\n\t// Give a warning if an existing kite.key exists\n\tkiteKeyPath := kiteHome + \"/kite.key\"\n\tif _, err := readKey(kiteKeyPath); err == nil {\n\t\tresult, err := ask(fmt.Sprintf(\"An existing %s detected. Type 'yes' to override and continue:\", kiteKeyPath))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif result != \"yes\" {\n\t\t\treturn errors.New(\"aborting registration\")\n\t\t}\n\t}\n\n\tkontrol := k.NewClient(kontrolURL)\n\tif err := kontrol.Dial(); err != nil {\n\t\treturn err\n\t}\n\tdefer kontrol.Close()\n\n\t// Register is always called with sudo, so Init should have enough\n\t// permissions.\n\tif err := tlsproxy.Init(); err != nil {\n\t\treturn err\n\t}\n\n\tauthType := \"password\"\n\tif token != \"\" {\n\t\tauthType = \"token\"\n\t}\n\n\tvar args = struct {\n\t\tUsername string\n\t\tToken string\n\t\tAuthType string\n\t}{\n\t\tUsername: username,\n\t\tToken: token,\n\t\tAuthType: authType,\n\t}\n\n\t// If authtType is password, this causes Kontrol to execute the\n\t// 'kite.getPass' method (builtin method in the Kite library) on our own\n\t// local kite (the one we declared above) method bidirectional. So once we\n\t// execute this, we immediately get a prompt asking for our password, which\n\t// is then transfered back to Kontrol. If we have a token, it will not ask\n\t// for a password and will create retunr the key immediately if the token\n\t// is valid for the given username (which is passed via the args).\n\tresult, err := kontrol.TellWithTimeout(\"registerMachine\", 5*time.Minute, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// If the token is correct a valid and signed `kite.key` is returned\n\t// back. We go and create/override the ~/.kite/kite.key with this content.\n\tif err := writeKey(result.MustString(), kiteKeyPath); err != nil {\n\t\treturn err\n\t}\n\n\t// Using authenticated here instead of registered, so it is a\n\t// middleground in UX for both raw `klient -register` usage, and also\n\t// `kd install` usage. `kd install` is very user facing, and\n\t// registration is potentially confusing to the end user (since\n\t// they are already registered to koding.com.. etc)\n\tfmt.Println(\"Authenticated successfully\")\n\treturn nil\n}", "func testFlowTunnel(t *testing.T, tunnelType string) {\n\tts := NewTestStorage()\n\n\taa := helper.NewAgentAnalyzerWithConfig(t, confAgentAnalyzer, ts)\n\taa.Start()\n\tdefer aa.Stop()\n\n\tclient, err := api.NewCrudClientFromConfig(&http.AuthenticationOpts{})\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\n\tcapture1 := api.NewCapture(\"G.V().Has('Name', 'tunnel-vm1').Out().Has('Name', 'tunnel')\", \"\")\n\tif err := client.Create(\"capture\", capture1); err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\n\tcapture2 := api.NewCapture(\"G.V().Has('Name', 'tunnel-vm2-eth0')\", \"\")\n\tif err := client.Create(\"capture\", capture2); err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\ttime.Sleep(1 * time.Second)\n\n\tsetupCmds := []helper.Cmd{\n\t\t{\"sudo ovs-vsctl add-br br-tunnel\", true},\n\n\t\t{\"sudo ip netns add tunnel-vm1\", true},\n\t\t{\"sudo ip link add tunnel-vm1-eth0 type veth peer name eth0 netns tunnel-vm1\", true},\n\t\t{\"sudo ip link set tunnel-vm1-eth0 up\", true},\n\n\t\t{\"sudo ip netns exec tunnel-vm1 ip link set eth0 up\", true},\n\t\t{\"sudo ip netns exec tunnel-vm1 ip address add 172.16.0.1/24 dev eth0\", true},\n\n\t\t{\"sudo ip netns add tunnel-vm2\", true},\n\t\t{\"sudo ip link add tunnel-vm2-eth0 type veth peer name eth0 netns tunnel-vm2\", true},\n\t\t{\"sudo ip link set tunnel-vm2-eth0 up\", true},\n\t\t{\"sudo ip netns exec tunnel-vm2 ip link set eth0 up\", true},\n\t\t{\"sudo ip netns exec tunnel-vm2 ip address add 172.16.0.2/24 dev eth0\", true},\n\n\t\t{\"sudo ovs-vsctl add-port br-tunnel tunnel-vm1-eth0\", true},\n\t\t{\"sudo ovs-vsctl add-port br-tunnel tunnel-vm2-eth0\", true}}\n\n\ttunnelAdd := \"\"\n\tif tunnelType == \"gre\" {\n\t\ttunnelAdd = \"sudo ip netns exec tunnel-vm1 ip tunnel add tunnel mode gre remote 172.16.0.2 local 172.16.0.1 ttl 255\"\n\t} else {\n\t\ttunnelAdd = \"sudo ip netns exec tunnel-vm1 ip link add tunnel type vxlan id 10 remote 172.16.0.2 local 172.16.0.1 ttl 255 dev eth0 dstport 4789\"\n\t}\n\tsetupCmds = append(setupCmds, []helper.Cmd{\n\t\t{tunnelAdd, true},\n\t\t{\"sudo ip netns exec tunnel-vm1 ip link set tunnel up\", true},\n\t\t{\"sudo ip netns exec tunnel-vm1 ip link add name dummy0 type dummy\", true},\n\t\t{\"sudo ip netns exec tunnel-vm1 ip link set dummy0 up\", true},\n\t\t{\"sudo ip netns exec tunnel-vm1 ip a add 192.168.0.1/32 dev dummy0\", true},\n\t\t{\"sudo ip netns exec tunnel-vm1 ip r add 192.168.0.0/24 dev tunnel\", true}}...)\n\n\tif tunnelType == \"gre\" {\n\t\ttunnelAdd = \"sudo ip netns exec tunnel-vm2 ip tunnel add tunnel mode gre remote 172.16.0.1 local 172.16.0.2 ttl 255\"\n\t} else {\n\t\ttunnelAdd = \"sudo ip netns exec tunnel-vm2 ip link add tunnel type vxlan id 10 remote 172.16.0.1 local 172.16.0.2 ttl 255 dev eth0 dstport 4789\"\n\t}\n\tsetupCmds = append(setupCmds, []helper.Cmd{\n\t\t{tunnelAdd, true},\n\t\t{\"sudo ip netns exec tunnel-vm2 ip link set tunnel up\", true},\n\t\t{\"sudo ip netns exec tunnel-vm2 ip link add name dummy0 type dummy\", true},\n\t\t{\"sudo ip netns exec tunnel-vm2 ip link set dummy0 up\", true},\n\t\t{\"sudo ip netns exec tunnel-vm2 ip a add 192.168.0.2/32 dev dummy0\", true},\n\t\t{\"sudo ip netns exec tunnel-vm2 ip r add 192.168.0.0/24 dev tunnel\", true},\n\t\t{\"sleep 10\", false},\n\t\t{\"sudo ip netns exec tunnel-vm1 ping -c 5 -I 192.168.0.1 192.168.0.2\", false}}...)\n\n\ttearDownCmds := []helper.Cmd{\n\t\t{\"ip netns del tunnel-vm1\", true},\n\t\t{\"ip netns del tunnel-vm2\", true},\n\t\t{\"ovs-vsctl del-br br-tunnel\", true},\n\t}\n\n\thelper.ExecCmds(t, setupCmds...)\n\tdefer helper.ExecCmds(t, tearDownCmds...)\n\n\tgh := helper.NewGremlinQueryHelper(&http.AuthenticationOpts{})\n\n\tflowsInnerTunnel := gh.GetFlowsFromGremlinReply(t, `G.V().Has('Name', 'tunnel-vm1').Out().Has('Name', 'tunnel').Flows()`)\n\tflowsBridge := gh.GetFlowsFromGremlinReply(t, `G.V().Has('Name', 'tunnel-vm2-eth0').Flows()`)\n\n\tvar TrackID string\n\tfor _, flow := range flowsInnerTunnel {\n\t\t// A vxlan innerpacket contains Ethernet while gre\n\t\t// innerpacket does not\n\t\tif strings.Contains(flow.LayersPath, \"IPv4/ICMPv4/Payload\") {\n\t\t\tif TrackID != \"\" {\n\t\t\t\tt.Errorf(\"We should only found one ICMPv4 flow in the tunnel %v\", flowsInnerTunnel)\n\t\t\t}\n\t\t\tTrackID = flow.TrackingID\n\t\t}\n\t}\n\n\tsuccess := false\n\tfor _, f := range flowsBridge {\n\t\tif TrackID == f.TrackingID && strings.Contains(f.LayersPath, \"ICMPv4/Payload\") && f.Network != nil && f.Network.Protocol == flow.FlowProtocol_IPV4 {\n\t\t\tsuccess = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !success {\n\t\tt.Errorf(\"TrackingID not found in %s tunnel: leaving the interface(%v) == seen in the tunnel(%v)\", tunnelType, flowsInnerTunnel, flowsBridge)\n\t}\n\n\tclient.Delete(\"capture\", capture1.ID())\n\tclient.Delete(\"capture\", capture2.ID())\n}", "func actHostRegister(data *interface{}, client *wserver.Client) {\n\thostLogin := (*data).(string)\n\tnew_host := NewHost(hostLogin, client)\n\tok := hostConnections.Add(new_host)\n\tif !ok {\n\t\tclient.SendJson(&Action{\"REGISTER_FAIL\", \"login exist\"})\n\t} else {\n\t\tclient.SendJson(&Action{\"REGISTER_SUCCESS\", \"\"})\n\t}\n}", "func Register(p Protocol, n NewFunc) {\n\treglock.Lock()\n\tdefer reglock.Unlock()\n\tregistry[p] = n\n}", "func NewTunnel(conn net.Conn) *Tunnel {\n\tnc := &netConn{Conn: conn}\n\n\t// The rURL value doesn't actually matter, as we are not actually dialing to anything\n\trURL, _ := url.Parse(\"http://\" + conn.RemoteAddr().String())\n\tproxy := httputil.NewSingleHostReverseProxy(rURL)\n\tproxy.Transport = &http2.Transport{\n\t\tDialTLS: func(netw, addr string, _ *tls.Config) (net.Conn, error) {\n\t\t\t// HTTP/2 protocol normally requires a TLS handshake. This works\n\t\t\t// around that by using an already established connection. This\n\t\t\t// also avoids the usual requirement of performing an h2c upgrade\n\t\t\t// when not using TLS.\n\t\t\treturn nc, nil\n\t\t},\n\t\t// Routed requests may use the http scheme if we specify this config.\n\t\tAllowHTTP: true,\n\t}\n\n\treturn &Tunnel{\n\t\tproxy: proxy,\n\t\tconn: nc,\n\t}\n}", "func (s *server) OpenTunnel(req *message.OpenTunnelRequest) (*message.OpenTunnelResponse, error) {\n\tver, err := semver.NewVersion(req.Version)\n\tif err != nil {\n\t\treturn nil, withcode(err, message.StatusCode_InvalidVersion)\n\t}\n\n\tif ver.Major < version.MajorVersion {\n\t\terr := errors.Errorf(\"client version %s doesn't match the server version %s\", req.Version, version.NewVersion().String())\n\t\treturn nil, withcode(err, message.StatusCode_VersionTooOld)\n\t}\n\n\t// TODO: check encryption\n\n\tsrc := s.Peer(req.Source)\n\tif src == nil {\n\t\treturn nil, errors.Errorf(\"source peer '%s' not found in cache\", req.Source)\n\t}\n\tdst := s.Peer(req.Destination)\n\tif dst == nil {\n\t\treturn nil, errors.Errorf(\"destination peer '%s' not found in cache\", req.Destination)\n\t}\n\ts.notifier.OpenTunnel(src, dst)\n\n\treturn &message.OpenTunnelResponse{}, nil\n}", "func (f *FakeTunnel) Start(serviceURL string) error {\n\tf.active = true\n\treturn nil\n}", "func (c *Client) CreateDirectConnectTunnel(request *CreateDirectConnectTunnelRequest) (response *CreateDirectConnectTunnelResponse, err error) {\n if request == nil {\n request = NewCreateDirectConnectTunnelRequest()\n }\n response = NewCreateDirectConnectTunnelResponse()\n err = c.Send(request, response)\n return\n}", "func PrepareTunnel(db *DB) error {\n\tq := `\nCREATE TABLE IF NOT EXISTS tunnel (port INTEGER PRIMARY KEY,\n forward_port INTEGER,\n forward_address VARCHAR)\n `\n\t_, err := db.Exec(q)\n\treturn err\n}", "func Accept(t *Tunnel, tunnelID string, relayURL string, auths ...config.Auth) error {\n\tvar cfg, err = config.Load()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdeviceKey := cfg.LoadAuth().GetDeviceKey()\n\tparams := map[string]string{\"key\": deviceKey, \"tunnel\": tunnelID}\n\n\t// get authentication\n\tauth, err := config.LoadAuth().GetDeviceAuth()\n\tif len(auths) > 0 {\n\t\tauth = auths[0]\n\t} else if err != nil {\n\t\treturn err\n\t}\n\n\t// set relayURL\n\tauth = auth.WithAPIServer(relayURL)\n\n\tt._initTunnel(DeviceSide)\n\tt.CloseListeners = append(t.CloseListeners, t._onClose)\n\tt.TimeoutListeners = append(t.TimeoutListeners, t._pingTimeout)\n\terr = OpenWebsocket(&t.Connection, \"/accept\", params, t.onMessage, auth)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// time out after 30 secs\n\tselect {\n\tcase err = <-t.connected:\n\t\tbreak\n\tcase <-time.After(time.Second * 30):\n\t\terr = fmt.Errorf(\"Timeout while accepting tunnel %s\", tunnelID)\n\t}\n\n\tclose(t.connected)\n\tt.connected = nil\n\n\t// init watchdog\n\tif err == nil {\n\t\tt.wdog = util.NewWatchdog(180*time.Second, t._onTimeout)\n\t}\n\n\treturn err\n}", "func createTunnel(cfg *SSHConfig) (*SSHTunnel, error) {\n\tf, err := CreateTempFileFromString(cfg.GatewayConfig.PrivateKey, 0400)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlocalPort := cfg.LocalPort\n\tif localPort == 0 {\n\t\tlocalPort, err = getFreePort()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\toptions := \"-q -oServerAliveInterval=60 -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oPubkeyAuthentication=yes -oPasswordAuthentication=no\"\n\tcmdString := fmt.Sprintf(\"ssh -i %s -NL %d:%s:%d %s@%s %s -p %d\",\n\t\tf.Name(),\n\t\tlocalPort,\n\t\tcfg.Host,\n\t\tcfg.Port,\n\t\tcfg.GatewayConfig.User,\n\t\tcfg.GatewayConfig.Host,\n\t\toptions,\n\t\tcfg.GatewayConfig.Port,\n\t)\n\tcmd := exec.Command(\"sh\", \"-c\", cmdString)\n\terr = cmd.Start()\n\t//\terr = cmd.Wait()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor nbiter := 0; !isTunnelReady(localPort) && nbiter < 100; nbiter++ {\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n\treturn &SSHTunnel{\n\t\tport: localPort,\n\t\tcmd: cmd,\n\t\tcmdString: cmdString,\n\t\tkeyFile: f,\n\t}, nil\n}", "func NewTunnel(\n\tgatewayAddr string,\n\tlayer knxnet.TunnelLayer,\n\tconfig TunnelConfig,\n) (tunnel *Tunnel, err error) {\n\tvar sock knxnet.Socket\n\n\t// Create socket which will be used for communication.\n\tif config.UseTCP {\n\t\tsock, err = knxnet.DialTunnelTCP(gatewayAddr)\n\t} else {\n\t\tsock, err = knxnet.DialTunnelUDP(gatewayAddr)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initialize the Client structure.\n\tclient := &Tunnel{\n\t\tsock: sock,\n\t\tconfig: checkTunnelConfig(config),\n\t\tlayer: layer,\n\t\tack: make(chan *knxnet.TunnelRes),\n\t\tinbound: make(chan cemi.Message),\n\t\tdone: make(chan struct{}),\n\t}\n\n\t// Connect to the gateway.\n\terr = client.requestConn()\n\tif err != nil {\n\t\tsock.Close()\n\t\treturn nil, err\n\t}\n\n\tclient.wait.Add(1)\n\tgo client.serve()\n\n\treturn client, nil\n}", "func (_PlasmaFramework *PlasmaFrameworkTransactorSession) RegisterVault(_vaultId *big.Int, _vaultAddress common.Address) (*types.Transaction, error) {\n\treturn _PlasmaFramework.Contract.RegisterVault(&_PlasmaFramework.TransactOpts, _vaultId, _vaultAddress)\n}", "func newCreateClientTunnelReply(cidr *net.IPNet, tid int64) (f linkFrame) {\n f.method = CLIENT_TUN_NEW\n f.param = map[string]interface{} { K_CIDR : cidr.String() }\n f.response = tid\n return\n}", "func (t *targetrunner) register() error {\n\tjsbytes, err := json.Marshal(t.si)\n\tif err != nil {\n\t\tglog.Errorf(\"Unexpected failure to json-marshal %+v, err: %v\", t.si, err)\n\t\treturn err\n\t}\n\turl := ctx.config.Proxy.URL + \"/\" + Rversion + \"/\" + Rcluster\n\t_, err = t.call(url, http.MethodPost, jsbytes)\n\treturn err\n}", "func (_PlasmaFramework *PlasmaFrameworkSession) RegisterVault(_vaultId *big.Int, _vaultAddress common.Address) (*types.Transaction, error) {\n\treturn _PlasmaFramework.Contract.RegisterVault(&_PlasmaFramework.TransactOpts, _vaultId, _vaultAddress)\n}", "func (c *Compute) Tunnel(ip string, port int) (Dialer, error) {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get current user: %v\", err)\n\t}\n\tif err := key.Read(); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read ssh private key: %v\", err)\n\t}\n\traddr := ip + \":22\"\n\tconn, err := ssh.Dial(\"tcp\", ip+\":22\", &ssh.ClientConfig{\n\t\tUser: usr.Username,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(key),\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to dial ssh conn to %q: %v\", raddr, err)\n\t}\n\treturn func(net, addr string) (net.Conn, error) {\n\t\tparts := strings.Split(addr, \":\")\n\t\tif len(parts) < 2 {\n\t\t\treturn nil, fmt.Errorf(\"no port to connect to %q: %v\", addr, parts)\n\t\t}\n\t\tport := parts[1]\n\t\tlog.Println(\"tunneling connection to port:\", port)\n\t\tladdr := fmt.Sprintf(\"127.0.0.1:%s\", parts[1])\n\t\treturn conn.Dial(\"tcp\", laddr)\n\t}, nil\n}", "func (g *Gossiper) Register(subscriber IEndPointStateChangeSubscriber) {\n\tg.subscribers = append(g.subscribers, subscriber)\n}", "func (m *Monocular) Register(echoContext echo.Context) error {\n\tlog.Debug(\"Helm Repository Register...\")\n\treturn m.portalProxy.RegisterEndpoint(echoContext, m.Info)\n}", "func (r *dbLocalProxyRequirement) addLocalProxyWithTunnel(reasons ...string) {\n\tr.addLocalProxy(reasons...)\n\tr.tunnel = true\n\tr.tunnelReasons = append(r.tunnelReasons, reasons...)\n}", "func openTunnel(a, b net.Conn, timeout time.Duration) error {\n\tfe := firstErr{}\n\tmuTimeout := atomic.Value{}\n\tmuTimeout.Store(timeout)\n\n\twg := sync.WaitGroup{}\n\twg.Add(1)\n\tgo func() {\n\t\topenOneWayTunnel(a, b, &muTimeout, &fe)\n\t\twg.Done()\n\t}()\n\topenOneWayTunnel(b, a, &muTimeout, &fe)\n\twg.Wait()\n\n\treturn fe.getErr()\n}", "func (p *Proxy) AddServerAccess(s *Server) (err error) {\n\n // We only want to connect internally to the VPN.\n // These should not be exposed.\n // serverAddress := s.PublicServerAddress()\n serverAddress := s.ServerAddress()\n\n f:= logrus.Fields{\n \"proxy\": p.Name, \"server\": s.Name, \"user\": s.User, \"serverAddress\": serverAddress,\n }\n log.Info(f, \"Adding server access to proxy.\")\n\n if s.ServerPort == 0 {\n return fmt.Errorf(\"Failed to add server: invalid server port = (%d)\", s.ServerPort)\n }\n\n rcon, err := p.GetRcon()\n if err != nil { return err }\n\n motd := fmt.Sprintf(\"%s hosted by %s in the %s neighborhood.\", s.Name, s.User, s.Name)\n command := fmt.Sprintf(\"bconf addServer(\\\"%s\\\", \\\"%s\\\", \\\"%s\\\", false)\",\n s.Name, motd, serverAddress)\n\n reply, err := rcon.Send(command)\n f[\"command\"] = command\n f[\"reply\"] = reply\n if err != nil { \n log.Error(f, \"Remore addServer failed.\", err)\n return err \n }\n // fmt.Printf(\"Received reply: %s\\n\", reply)\n log.Info(f, \"Remote addServer reply.\")\n\n return err\n}", "func RegisterGateway(tp Type, gw Gateway) {\n\tif _, ok := gateways[tp]; ok {\n\t\tpanic(fmt.Errorf(\"%s gateway already registered\", tp))\n\t}\n\tgateways[tp] = gw\n}", "func (s *MirrorConnections) Add(mirror uint32, ip string, port uint16) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tif m, ok := s.value[mirror]; ok {\n\t\tm[ip] = port\n\t\treturn\n\t}\n\n\tm := make(map[string]uint16)\n\tm[ip] = port\n\ts.value[mirror] = m\n}", "func (s *Server) Register(tm server.StateHandlerType, hmi interface{}) {\n\ts.pub.Register(tm, hmi)\n}", "func (c *connection) Register(state *utils.State) {\n\tvar connection = connect()\n\tlistener(connection, state)\n\n\tdefer connection.Close()\n}", "func (net *Network) Register(vm *intcode.VM) {\n\taddress := net.nextAddr\n\tnet.nextAddr++\n\tnet.vms[address] = vm\n\n\tmsgCh := make(chan int, 128)\n\tmsgCh <- address\n\tvm.SetInputFunc(func() int {\n\t\t// can't use SetInputChan because it will block if there is nothing available\n\t\t// in the channel.\n\t\tselect {\n\t\tcase val := <-msgCh:\n\t\t\treturn val\n\t\tdefault:\n\t\t\treturn -1\n\t\t}\n\t})\n\tnet.msgs[address] = msgCh\n}", "func (f *Forwarder) Add(id userid.ID, stream TransferAgent) {\n\tif _, loaded := f.transferAgents.LoadOrStore(id, stream); !loaded {\n\t\tf.connections += 1\n\t}\n}", "func (_DelegateProfile *DelegateProfileSession) Register() (common.Address, error) {\n\treturn _DelegateProfile.Contract.Register(&_DelegateProfile.CallOpts)\n}", "func (s *Service) AddRemote(conn net.Conn) {\r\n\ts.Mutex.Lock()\r\n\ts.Remotes = append(s.Remotes, CreateRemoteConnection(conn, s.Protocols, s, s.Engine))\r\n\ts.Mutex.Unlock()\r\n}", "func (b *Builder) RegisterProtocol(rp *rolldpos.Protocol) *Builder {\n\tb.rp = rp\n\treturn b\n}", "func Register(t *http.Transport) {\n\tcopy := t.Clone()\n\n\tcopy.Dial = nil // nolint <= deprecated function\n\tcopy.DialTLS = nil // nolint <= deprecated function\n\n\tswitch {\n\tcase copy.DialContext == nil && copy.DialTLSContext == nil:\n\t\tcopy.DialContext = dialContextAdapter(defaultDialContextFunc)\n\n\tcase copy.DialContext == nil && copy.DialTLSContext != nil:\n\t\tcopy.DialContext = dialContextAdapter(defaultDialContextFunc)\n\t\tcopy.DialTLSContext = dialContextAdapter(copy.DialTLSContext)\n\n\tcase copy.DialContext != nil && copy.DialTLSContext == nil:\n\t\tcopy.DialContext = dialContextAdapter(copy.DialContext)\n\n\tcase copy.DialContext != nil && copy.DialTLSContext != nil:\n\t\tcopy.DialContext = dialContextAdapter(copy.DialContext)\n\t\tcopy.DialTLSContext = dialContextAdapter(copy.DialTLSContext)\n\t}\n\n\ttt := roundTripAdapter(copy)\n\n\tt.RegisterProtocol(\"unix\", tt)\n}", "func NewRegister(router router.Router, proxy *Proxy) *Register {\n\treturn &Register{router: router, proxy: proxy}\n}", "func newProxyConn(client *ssh.Client, stderr io.Writer, free func()) (*proxyConn, error) {\n\t// Open new session to the agent\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Get a pipe to stdin so that we can send data down\n\tstdin, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Get a pipe to stdout so that we can get responses back\n\tstdout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Set stderr\n\tsession.Stderr = stderr\n\n\t// Start the shell on the other side\n\tif err := session.Shell(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &proxyConn{\n\t\tclient: client,\n\t\tsession: session,\n\t\tstdin: stdin,\n\t\tstdout: stdout,\n\t\tfree: free,\n\t}, nil\n}", "func (h *IPSecVppHandler) AddTunnelInterface(tunnel *ipsec.TunnelInterfaces_Tunnel) (uint32, error) {\n\treturn h.tunnelIfAddDel(tunnel, true)\n}", "func (g *Glutton) registerHandlers() {\n\n\tfor _, rule := range g.rules {\n\n\t\tif rule.Type == \"conn_handler\" && rule.Target != \"\" {\n\n\t\t\tvar handler string\n\n\t\t\tswitch rule.Name {\n\n\t\t\tcase \"proxy_tcp\":\n\t\t\t\thandler = rule.Name\n\t\t\t\tg.protocolHandlers[rule.Target] = g.protocolHandlers[handler]\n\t\t\t\tdelete(g.protocolHandlers, handler)\n\t\t\t\thandler = rule.Target\n\t\t\t\tbreak\n\n\t\t\tcase \"proxy_ssh\":\n\t\t\t\thandler = rule.Name\n\t\t\t\terr := g.NewSSHProxy(rule.Target)\n\t\t\t\tif err != nil {\n\t\t\t\t\tg.logger.Error(fmt.Sprintf(\"[ssh.prxy] failed to initialize SSH proxy\"))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trule.Target = handler\n\t\t\t\tbreak\n\t\t\tcase \"proxy_telnet\":\n\t\t\t\thandler = rule.Name\n\t\t\t\terr := g.NewTelnetProxy(rule.Target)\n\t\t\t\tif err != nil {\n\t\t\t\t\tg.logger.Error(fmt.Sprint(\"[telnet.prxy] failed to initialize TELNET proxy\"))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trule.Target = handler\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\thandler = rule.Target\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif g.protocolHandlers[handler] == nil {\n\t\t\t\tg.logger.Warn(fmt.Sprintf(\"[glutton ] no handler found for %v protocol\", handler))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tg.processor.RegisterConnHandler(handler, func(conn net.Conn, md *freki.Metadata) error {\n\t\t\t\thost, port, err := net.SplitHostPort(conn.RemoteAddr().String())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif md == nil {\n\t\t\t\t\tg.logger.Debug(fmt.Sprintf(\"[glutton ] connection not tracked: %s:%s\", host, port))\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tg.logger.Debug(\n\t\t\t\t\tfmt.Sprintf(\"[glutton ] new connection: %s:%s -> %d\", host, port, md.TargetPort),\n\t\t\t\t\tzap.String(\"host\", host),\n\t\t\t\t\tzap.String(\"sport\", port),\n\t\t\t\t\tzap.String(\"dport\", strconv.Itoa(int(md.TargetPort))),\n\t\t\t\t\tzap.String(\"handler\", handler),\n\t\t\t\t)\n\n\t\t\t\tif g.producer != nil {\n\t\t\t\t\terr = g.producer.LogHTTP(conn, md, nil, \"\")\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tg.logger.Error(fmt.Sprintf(\"[glutton ] error: %v\", err))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdone := make(chan struct{})\n\t\t\t\tgo g.closeOnShutdown(conn, done)\n\t\t\t\tconn.SetDeadline(time.Now().Add(45 * time.Second))\n\t\t\t\tctx := g.contextWithTimeout(72)\n\t\t\t\terr = g.protocolHandlers[handler](ctx, conn)\n\t\t\t\tdone <- struct{}{}\n\t\t\t\treturn err\n\t\t\t})\n\t\t}\n\t}\n}", "func Register(r shared.Responder) {\n\tserver.Register(r)\n}", "func (na *Nagent) UpdateTunnel(tun *netproto.Tunnel) error {\n\t// find the corresponding namespace\n\t_, err := na.FindNamespace(tun.ObjectMeta)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\texistingTunnel, err := na.FindTunnel(tun.ObjectMeta)\n\tif err != nil {\n\t\tlog.Errorf(\"Tunnel %v not found\", tun.ObjectMeta)\n\t\treturn err\n\t}\n\n\t// find the corresponding vrf for the route\n\tvrf, err := na.ValidateVrf(existingTunnel.Tenant, existingTunnel.Namespace, existingTunnel.Spec.VrfName)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to find the vrf %v\", existingTunnel.Spec.VrfName)\n\t\treturn err\n\t}\n\n\tif proto.Equal(tun, existingTunnel) {\n\t\tlog.Infof(\"Nothing to update.\")\n\t\treturn nil\n\t}\n\n\terr = na.Datapath.UpdateTunnel(existingTunnel, vrf)\n\tif err != nil {\n\t\tlog.Errorf(\"Error updating the tunnel {%+v} in datapath. Err: %v\", existingTunnel, err)\n\t\treturn err\n\t}\n\tkey := na.Solver.ObjectKey(tun.ObjectMeta, tun.TypeMeta)\n\tna.Lock()\n\tna.TunnelDB[key] = tun\n\tna.Unlock()\n\terr = na.Store.Write(tun)\n\treturn err\n}", "func (_KNS *KNSSession) Register(prime_owner common.Address, wallet common.Address, Jid string, tel string) (*types.Transaction, error) {\n\treturn _KNS.Contract.Register(&_KNS.TransactOpts, prime_owner, wallet, Jid, tel)\n}", "func Register() error {\n\tif os.Getenv(\"PREMKIT_ROUTER\") == \"\" {\n\t\tlog.Infof(\"PREMKIT_ROUTER not defined. Not going to register with an upstream.\")\n\t\treturn nil\n\t}\n\n\t// TODO once the code is in github, use a reference to the schema instead of hard coding this json object\n\tbody := fmt.Sprintf(`\n{\n\t\"service\": {\n\t\t\"name\": \"healthcheck\",\n\t\t\"path\": \"healthcheck\",\n\t\t\"upstreams\": [\n\t\t\t{\n\t\t\t\t\"url\": %q,\n\t\t\t\t\"include_service_path\": false,\n\t\t\t\t\"insecure_skip_verify\": false\n\t\t\t}\n\t\t]\n\t}\n}`, os.Getenv(\"ADVERTISE_ADDRESS\"))\n\n\turi := fmt.Sprintf(\"%s/premkit/v1/service\", os.Getenv(\"PREMKIT_ROUTER\"))\n\trequest := gorequest.New()\n\tresp, _, errs := request.Post(uri).\n\t\tSend(body).\n\t\tEnd()\n\n\tif len(errs) > 0 {\n\t\terr := fmt.Errorf(\"Error(s) registering with router: %#v\", errs)\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\n\tif resp.StatusCode != http.StatusCreated {\n\t\terr := fmt.Errorf(\"Unexpected response from router: %d\", resp.StatusCode)\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (m *RdmaDevPlugin) register() error {\n\tkubeletEndpoint := filepath.Join(deprecatedSockDir, kubeEndPoint)\n\tconn, err := dial(kubeletEndpoint, 5*time.Second)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tclient := pluginapi.NewRegistrationClient(conn)\n\treqt := &pluginapi.RegisterRequest{\n\t\tVersion: pluginapi.Version,\n\t\tEndpoint: m.socketName,\n\t\tResourceName: m.resourceName,\n\t}\n\n\t_, err = client.Register(context.Background(), reqt)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Register(t types.ImageTransport) {\n\tkt.Add(t)\n}", "func newTunnelDialer(ssh ssh.ClientConfig, keepAlivePeriod, dialTimeout time.Duration, opts ...DialProxyOption) ContextDialer {\n\tdialer := newDirectDialer(keepAlivePeriod, dialTimeout)\n\treturn ContextDialerFunc(func(ctx context.Context, network, addr string) (conn net.Conn, err error) {\n\t\tif proxyURL := utils.GetProxyURL(addr); proxyURL != nil {\n\t\t\tconn, err = DialProxyWithDialer(ctx, proxyURL, addr, dialer, opts...)\n\t\t} else {\n\t\t\tconn, err = dialer.DialContext(ctx, network, addr)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\n\t\tsconn, err := sshConnect(ctx, conn, ssh, dialTimeout, addr)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn sconn, nil\n\t})\n}", "func Run(p ProtocolHandler, tunnelID string, brokerURL string) {\n\tdata := p.self()\n\n\terr := tunnel.Accept(data.tunnel, tunnelID, brokerURL)\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"accepting tunnel failed: \")\n\t} else {\n\t\tp.receive()\n\t}\n}", "func (h *Hub) Add(conn *websocket.Conn) {\n\th.mux.Lock()\n\tdefer h.mux.Unlock()\n\n\th.conns[conn] = struct{}{}\n}", "func (server *Server) Register(action INetworkAction) {\n\n}", "func (follower *Follower) Register(leaderHost string) (err error) {\n\tlog.Printf(\"Registring with Leader...\\n\")\n\tconn, err := net.Dial(\"tcp\", leaderHost)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmessage := &Message{\n\t\tAction: Message_REGISTER.Enum(),\n\n\t\tId: follower.id[:],\n\t\tHost: proto.String(follower.host),\n\t}\n\n\tdata, err := proto.Marshal(message)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := conn.Write(data); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (h *BasicHost) RegisterProtocol(\n\tpid common.Pid,\n\thandler ProtocolHandler,\n\tadapters ...ProtocolAdapter,\n) {\n\th.host.SetStreamHandler(pid.ProtocolID(), func(stream net.Stream) {\n\t\tdefer stream.Reset()\n\t\tmsg, err := common.ReadMessage(stream)\n\t\tif err != nil {\n\t\t\tlog.Println(\"failed to read message from stream :\", err)\n\t\t\treturn\n\t\t}\n\t\tgo handler.Handle(adapters...)(msg)\n\t})\n}", "func Register(c *context.Context) {\n\tctx = c\n\tensureConnection()\n\tsetTargetChannel = startReleaseChannelUpdater(ctx)\n}", "func (c *Cluster) Set(host, forward string) {\n\tproxy := &httputil.ReverseProxy{\n\t\tDirector: func(r *http.Request) {\n\t\t\tr.URL.Scheme = \"http\"\n\t\t\tr.URL.Host = forward\n\t\t},\n\t\tErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {\n\t\t\tw.WriteHeader(http.StatusBadGateway)\n\t\t\t_, _ = w.Write([]byte(errors.Cause(err).Error()))\n\t\t},\n\t}\n\n\tc.proxiesLock.Lock()\n\tdefer c.proxiesLock.Unlock()\n\n\tc.proxies[host] = proxy\n}", "func (t *ZMQTransport) RegisterHook(h TransportHook) {\n\tt.hooks = append(t.hooks, h)\n}", "func RegisterStartForward(pubKey, upstream string) {\n\tpubKey = strings.TrimPrefix(pubKey, \"authorized_keys_\")\n\tconnectionsStarted.WithLabelValues(pubKey, upstream).Inc()\n\tconnectionsEnded.WithLabelValues(pubKey, upstream).Add(0)\n}", "func (_PlasmaFramework *PlasmaFrameworkTransactor) RegisterVault(opts *bind.TransactOpts, _vaultId *big.Int, _vaultAddress common.Address) (*types.Transaction, error) {\n\treturn _PlasmaFramework.contract.Transact(opts, \"registerVault\", _vaultId, _vaultAddress)\n}", "func (i *Interface) NewTunnel(index uint32, tunnel *Tunnel) (*VIF, error) {\n\tif tunnel == nil {\n\t\treturn nil, errors.New(\"Tunnel details is not given\")\n\t}\n\n\tvif, err := newVIF(i, fmt.Sprintf(\"%s-%d\", i.name, index))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvif.setTunnel(tunnel)\n\tif err := i.initVIF(vif); err != nil {\n\t\tvif.Free()\n\t\treturn nil, err\n\t}\n\n\treturn vif, nil\n}", "func (k *Keeper) RegisterRoute(moduleName, route string, invar sdk.Invariant) {\n\tinvarRoute := NewInvarRoute(moduleName, route, invar)\n\tk.routes = append(k.routes, invarRoute)\n}", "func (t *Tunnel) Connect(client *ssh.Client) {\n\t// Connect to the remote website we will forward. If we cannot connect, we\n\t// stop the forwarding.\n\ttarget, err := net.DialTimeout(\"tcp\", t.Src, 10*time.Second)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t\treturn\n\t}\n\n\t// Try to allocate the port in the remote client to listen to the content of\n\t// target. If it is not possible, we skip.\n\tlistener, err := client.Listen(\"tcp\", t.Dst)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\n\t// If everything goes well, we establish the connection and copy the content\n\t// of the target into the listener in the remote host.\n\tres, err := listener.Accept()\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\n\tgo util.Transfer(res, target)\n\tgo util.Transfer(target, res)\n}", "func (svr *Service) RegisterWorkConn(workConn net.Conn, newMsg *msg.NewWorkConn) error {\n\txl := utilnet.NewLogFromConn(workConn)\n\tctl, exist := svr.ctlManager.GetByID(newMsg.RunID)\n\tif !exist {\n\t\txl.Warn(\"No client control found for run id [%s]\", newMsg.RunID)\n\t\treturn fmt.Errorf(\"no client control found for run id [%s]\", newMsg.RunID)\n\t}\n\t// server plugin hook\n\tcontent := &plugin.NewWorkConnContent{\n\t\tUser: plugin.UserInfo{\n\t\t\tUser: ctl.loginMsg.User,\n\t\t\tMetas: ctl.loginMsg.Metas,\n\t\t\tRunID: ctl.loginMsg.RunID,\n\t\t},\n\t\tNewWorkConn: *newMsg,\n\t}\n\tretContent, err := svr.pluginManager.NewWorkConn(content)\n\tif err == nil {\n\t\tnewMsg = &retContent.NewWorkConn\n\t\t// Check auth.\n\t\terr = svr.authVerifier.VerifyNewWorkConn(newMsg)\n\t}\n\tif err != nil {\n\t\txl.Warn(\"invalid NewWorkConn with run id [%s]\", newMsg.RunID)\n\t\t_ = msg.WriteMsg(workConn, &msg.StartWorkConn{\n\t\t\tError: util.GenerateResponseErrorString(\"invalid NewWorkConn\", err, ctl.serverCfg.DetailedErrorsToClient),\n\t\t})\n\t\treturn fmt.Errorf(\"invalid NewWorkConn with run id [%s]\", newMsg.RunID)\n\t}\n\treturn ctl.RegisterWorkConn(workConn)\n}", "func cliRegister(name string, servport, myport int){\n\t//este serv va a enviarle un mensaje a un servidor\n\t//save a quien se va a conectar y le envia el nombre, su credencial\n\tresp := send(servport + 1, name, fmt.Sprintf(\"%d\", myport))\n\t//con la rspta necesitamos crear un mapa temporal de tipo entero\n\ttemp := make(map[int]string)\n\t_ = json.Unmarshal([]byte(resp),&temp)\n\tfor port, na := range temp {\n\t\tlib[port] = na\n\t}\n\tfmt.Println(lib)\n}", "func (tunnel *Tunnel) Start() error {\n\treturn <-tunnel.startAsync()\n}", "func (g *GrpcClient) Register(request *protofiles.RegisterRequest) (*protofiles.RegisterResponse, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), g.connectionTimeoutSecs)\n\tdefer cancel()\n\n\treturn g.client.Register(ctx, request)\n}", "func (m *WidgetDevicePlugin) Register(kubeletEndpoint, resourceName string) error {\n\tconn, err := dial(kubeletEndpoint, 5*time.Second)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tclient := pluginapi.NewRegistrationClient(conn)\n\treqt := &pluginapi.RegisterRequest{\n\t\tVersion: pluginapi.Version,\n\t\tEndpoint: path.Base(m.socket),\n\t\tResourceName: resourceName,\n\t}\n\n\t_, err = client.Register(context.Background(), reqt)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (client *GatewayClient) putConn(c *tls.Conn) {\n\tclient.idleConn <- c\n}", "func (c *ConsulClient) Register(ctx context.Context, name string, ttl time.Duration) (string, error) {\n\tregistryOperationCount.WithLabelValues(env, \"Register\").Inc()\n\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tregistryOperationTimeTaken.WithLabelValues(env, \"Register\").Observe(time.Now().Sub(startTime).Seconds())\n\t}()\n\n\tsessionID, _, err := c.client.Session().Create(&api.SessionEntry{\n\t\tName: name,\n\t\tTTL: ttl.String(),\n\t\tLockDelay: 2,\n\t\tBehavior: api.SessionBehaviorDelete,\n\t}, nil)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn sessionID, nil\n}", "func (s *Switch) RegisterDirectProtocol(protocol string) chan service.DirectMessage { // TODO: not used - remove\n\tif s.started == 1 {\n\t\tlog.Panic(\"attempt to register direct protocol after p2p has started\")\n\t}\n\tmchan := make(chan service.DirectMessage, s.config.BufferSize)\n\ts.directProtocolHandlers[protocol] = mchan\n\treturn mchan\n}", "func (n *Node) RegisterStrategy(topic string, strategy RoutingStrategy) {\n\tn.strategyMap[topic] = strategy\n}", "func (p *Protocol) Register(r *protocol.Registry) error {\n\treturn r.Register(protocolID, p)\n}", "func (p *Protocol) Register(r *protocol.Registry) error {\n\treturn r.Register(protocolID, p)\n}", "func (p *Protocol) Register(r *protocol.Registry) error {\n\treturn r.Register(protocolID, p)\n}", "func (c *Connector) Tunnel(host kubeoneapi.HostConfig) (Tunneler, error) {\n\tconn, err := c.Connect(host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttunn, ok := conn.(Tunneler)\n\tif !ok {\n\t\terr = errors.New(\"unable to assert Tunneler\")\n\t}\n\n\treturn tunn, err\n}", "func (w Ws) Register(r *gin.RouterGroup) {\n\tst := r.Group(\"\")\n\tst.GET(\"/ws/:id\", w.Server)\n\tst.DELETE(\"/ws/:id\", w.Offline)\n\tst.PUT(\"/ws/:id\", w.Dispatch)\n}", "func (router *Router) ListenAndAcceptTunnels(addr string) {\n\tladdr, err := net.ResolveTCPAddr(\"tcp\", addr)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tln, err := net.ListenTCP(\"tcp\", laddr)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tgo func() {\n\t\tdefer ln.Close()\n\t\tfor {\n\t\t\tconn, err := ln.AcceptTCP()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Error accepting tunnel conn:\", err)\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\trouter.mu.Lock()\n\t\t\trouter.pool = append(router.pool, NewTunnel(conn))\n\t\t\trouter.mu.Unlock()\n\n\t\t\tlog.Println(\"Tunnel added:\", conn.RemoteAddr().String())\n\t\t}\n\t}()\n}", "func Register(name string, h Holder) {\n\tmux.Lock()\n\tdefer mux.Unlock()\n\tif h == nil {\n\t\tpanic(\"Register Holder is nil\")\n\t}\n\tif _, dup := pool[name]; dup {\n\t\tpanic(\"Register called twice for Holder \" + name)\n\t}\n\tpool[name] = h\n}", "func (m *CambriconDevicePlugin) Register(kubeletEndpoint, resourceName string) error {\n\tconn, err := dial(kubeletEndpoint, 5*time.Second)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tclient := pluginapi.NewRegistrationClient(conn)\n\treqt := &pluginapi.RegisterRequest{\n\t\tVersion: pluginapi.Version,\n\t\tEndpoint: path.Base(m.socket),\n\t\tResourceName: resourceName,\n\t\tOptions: &pluginapi.DevicePluginOptions{\n\t\t\tGetPreferredAllocationAvailable: m.options.Mode == topologyAware,\n\t\t},\n\t}\n\n\t_, err = client.Register(context.Background(), reqt)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Tunnel() net.Conn {\n\tconn, err := net.Dial(tcpPort, address)\n\tif err != nil {\n\t\tlog.Println(\"[TUNNEL-ERROR] : Unable to connect to port.\")\n\t}\n\treturn conn\n}", "func (s *Server) Register(name string, h Handler) error {\n if _, ok := s.registry[name]; ok {\n return fmt.Errorf(\"cannot register name %q twice\", name)\n }\n s.registry[name] = &register{handler: h}\n return nil\n}", "func NextTunnel(inlet int) (int, error) {\n\tif inlet <= TunnelNotConnected || inlet > TunnelLeftTop {\n\t\treturn TunnelNotConnected, fmt.Errorf(\"inlet out of bounds %v\", inlet)\n\t}\n\t/*\n\t 6 5\n\t 1 2\n\t 3 8 3 8\n\t 4 7 4 7\n\t 6 5\n\t 1 2\n\t*/\n\tio := map[int]int{\n\t\t1: 6,\n\t\t2: 5,\n\t\t3: 8,\n\t\t4: 7,\n\t\t5: 2,\n\t\t6: 1,\n\t\t7: 4,\n\t\t8: 3,\n\t}\n\treturn io[inlet], nil\n}" ]
[ "0.6146846", "0.61225635", "0.5909397", "0.56072223", "0.5565189", "0.5540766", "0.5476352", "0.54763263", "0.54655796", "0.5418362", "0.53958005", "0.5362109", "0.5323186", "0.5291799", "0.52836424", "0.526554", "0.5163012", "0.5159695", "0.51567835", "0.51567405", "0.5155557", "0.5148601", "0.5127688", "0.5121817", "0.5112529", "0.51095676", "0.5072767", "0.506788", "0.50528103", "0.50481075", "0.50387627", "0.5023833", "0.50199693", "0.5004026", "0.49882382", "0.49841318", "0.498195", "0.4975741", "0.4974349", "0.4953912", "0.49515274", "0.49416265", "0.49184445", "0.4917442", "0.4897506", "0.48853973", "0.488468", "0.48774812", "0.4876174", "0.4867218", "0.48502234", "0.48491552", "0.48398325", "0.4834381", "0.48256502", "0.4806526", "0.47991687", "0.47952753", "0.47879094", "0.47842863", "0.47778383", "0.47715294", "0.4756461", "0.47534055", "0.4744438", "0.47377965", "0.47344035", "0.4733924", "0.47330102", "0.47327498", "0.47091317", "0.46959", "0.469049", "0.46896935", "0.46862856", "0.4684824", "0.4681123", "0.4671364", "0.4667592", "0.4657169", "0.46543753", "0.46539307", "0.46495807", "0.4639256", "0.46362063", "0.46359277", "0.4633345", "0.46304682", "0.4630449", "0.4622438", "0.4622438", "0.4622438", "0.46200383", "0.46128556", "0.46109164", "0.45999858", "0.4598325", "0.45936212", "0.45796767", "0.45785987" ]
0.73147064
0
Remove a proxy connection from the pool and return it If not proxy connections are in the pool, request one and wait until it is available Returns an error if we couldn't get a proxy because it took too long or the tunnel is closing
func (c *Control) GetProxy() (proxyConn conn.Conn, err error) { // initial timeout is zero to try to get a proxy connection without asking for one timeout := time.NewTimer(0) // get a proxy connection. if we timeout, request one over the control channel for proxyConn == nil { var ok bool select { case proxyConn, ok = <-c.proxies: if !ok { err = fmt.Errorf("No proxy connections available, control is closing") return } continue case <-timeout.C: c.conn.Debug("Requesting new proxy connection") // request a proxy connection c.out <- &msg.ReqProxy{} // timeout after 1 second if we don't get one timeout.Reset(1 * time.Second) } } // To try to reduce latency hanndling tunnel connections, we employ // the following curde heuristic: // If the proxy connection pool is empty, request a new one. // The idea is to always have at least one proxy connection available for immediate use. // There are two major issues with this strategy: it's not thread safe and it's not predictive. // It should be a good start though. if len(c.proxies) == 0 { c.out <- &msg.ReqProxy{} } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (router *Router) GetTunnel() *Tunnel {\n\trouter.mu.Lock()\n\tdefer router.mu.Unlock()\n\n\t// Keep trying to find a healthy tunnel until the pool exhausted and\n\t// actively remove unhealthy tunnels from the pool.\n\tfor {\n\t\tif len(router.pool) < 1 {\n\t\t\treturn nil\n\t\t}\n\t\ti := rand.Intn(len(router.pool))\n\t\ttunnel := router.pool[i]\n\t\tif err := tunnel.Err(); err != nil {\n\t\t\trouter.pool = append(router.pool[:i], router.pool[i+1:]...)\n\t\t\tlog.Println(\"Tunnel removed:\", tunnel.conn.RemoteAddr().String()+\":\", err)\n\t\t\tcontinue\n\t\t}\n\t\treturn tunnel\n\t}\n}", "func (nc *NodeController) getTunnel(reqBrokerMsg *ReqBroker) (tunConn net.Conn, err error) {\n\tvar ok bool\n\tfor {\n\t\tfor {\n\t\t\t// get a tunnel connection from the pool\n\t\t\tselect {\n\t\t\tcase tunConn, ok = <-nc.tunnels:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, errors.New(\"no tunnel connections available, control is closing\")\n\t\t\t\t}\n\t\t\t\tlog.Debug(\"NodeController::getTunnel get a tunnel connection from pool\")\n\t\t\t\tgoto end\n\t\t\tdefault:\n\t\t\t\t// no tunnel available in the pool, ask for one over the control channel\n\t\t\t\tlog.Debug(\"NodeController::getTunnel no tunnel in pool, send ReqTunnel message...\")\n\t\t\t\tif err = util.PanicToError(func() { nc.out <- new(ReqTunnel) }); err != nil {\n\t\t\t\t\t// c.out is closed, impossible to get a tunnel connection\n\t\t\t\t\tlog.Debug(\"NodeController::getTunnel send message to c.out error: %v\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tselect {\n\t\t\t\tcase <-time.After(dialTimeout):\n\t\t\t\t\t// try again, never stop believing\n\t\t\t\t\tcontinue\n\t\t\t\tcase tunConn, ok = <-nc.tunnels:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn nil, errors.New(\"no tunnel connections available, control is closing\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlog.Debug(\"NodeController::getTunnel get a tunnel connection after sending ReqTunnel\")\n\t\t\t\tgoto end\n\t\t\t}\n\t\t}\n\n\tend:\n\t\t{\n\t\t\t// try to send StartTunnel message\n\t\t\tif err := WriteMsg(tunConn, &StartTunnel{*reqBrokerMsg}); err != nil {\n\t\t\t\t// this tunnel connection is reached deadline\n\t\t\t\tlog.Debug(\"NodeController::getTunnel failed to send ping: %v\", err)\n\t\t\t\ttunConn.Close()\n\t\t\t\ttunConn = nil\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// receive response message\n\t\t\tresp := new(AccessResp)\n\t\t\ttunConn.SetReadDeadline(time.Now().Add(rwTimeout))\n\t\t\tif err := ReadMsgInto(tunConn, resp); err != nil {\n\t\t\t\tlog.Debug(\"NodeController::getTunnel failed to receive response message: %v\", err)\n\t\t\t\ttunConn.Close()\n\t\t\t\ttunConn = nil\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif resp.Error != \"\" {\n\t\t\t\tlog.Debug(\"NodeController::getTunnel failed with response: %s\", resp.Error)\n\t\t\t\ttunConn.Close()\n\t\t\t\treturn nil, errors.New(resp.Error)\n\t\t\t}\n\n\t\t\ttunConn.SetDeadline(time.Time{})\n\n\t\t\tutil.PanicToError(func() { nc.out <- new(ReqTunnel) })\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func (p *Pool) Get() (*redis.Client, error) {\n\tselect {\n\tcase conn := <- p.pool:\n\t\treturn conn, nil\n\n\tdefault:\n\t\tselect {\n\t\tcase conn := <- p.pool:\n\t\t\treturn conn, nil\n\n\t\tcase addr := <- p.spare:\n\t\t\tvar conn *redis.Client\n\t\t\tvar err error\n\n\t\t\tdefer func() {\n\t\t\t\tif err != nil {\n\t\t\t\t\tp.replenish(p.network, addr)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tconn, err = p.df(p.network, addr)\n\t\t\treturn conn, err\n\n\t\tcase <-time.After(time.Second * 5):\n\t\t\treturn nil, errors.New(\"pool exhausted\")\n\t\t}\n\t}\n}", "func (c *boundedPool) Get() (net.Conn, error) {\n\tconns := c.getConns()\n\tif conns == nil {\n\t\treturn nil, pool.ErrClosed\n\t}\n\n\t// Try and grab a connection from the pool\n\tselect {\n\tcase conn := <-conns:\n\t\tif conn == nil {\n\t\t\treturn nil, pool.ErrClosed\n\t\t}\n\t\treturn c.wrapConn(conn), nil\n\tdefault:\n\t\t// Could not get connection, can we create a new one?\n\t\tif atomic.LoadInt32(&c.total) < int32(cap(conns)) {\n\t\t\tconn, err := c.factory()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tatomic.AddInt32(&c.total, 1)\n\n\t\t\treturn c.wrapConn(conn), nil\n\t\t}\n\t}\n\n\t// The pool was empty and we couldn't create a new one to\n\t// retry until one is free or we timeout\n\tselect {\n\tcase conn := <-conns:\n\t\tif conn == nil {\n\t\t\treturn nil, pool.ErrClosed\n\t\t}\n\t\treturn c.wrapConn(conn), nil\n\tcase <-time.After(c.timeout):\n\t\treturn nil, fmt.Errorf(\"timed out waiting for free connection\")\n\t}\n\n}", "func (pool *Pool) Get() (*Conn, error) {\n\n\tfor {\n\t\tif n := atomic.LoadInt32(&pool.numIdle); n > 0 {\n\t\t\tif atomic.CompareAndSwapInt32(&pool.numIdle, n, n-1) {\n\t\t\t\tdeadline := pool.Deadline()\n\t\t\t\treturn pool.get(deadline.UnixNano())\n\t\t\t}\n\t\t} else if n < 0 {\n\t\t\treturn nil, errPoolClosed\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tmax := pool.maxConnections()\n\tfor {\n\t\tif n := atomic.LoadInt32(&pool.numOpen); 0 <= n && n < max {\n\t\t\tif atomic.CompareAndSwapInt32(&pool.numOpen, n, n+1) {\n\t\t\t\tconn, err := pool.dial()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\treturn conn, nil\n\t\t\t}\n\t\t} else if n < 0 {\n\t\t\treturn nil, errPoolClosed\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tdeadline := pool.Deadline()\n\treturn pool.get(deadline.UnixNano())\n}", "func (s *ProxyServer) Proxy(ctx context.Context, proxyCtx *common.ProxyContext, clientConn, serviceConn net.Conn) error {\n\t// Wrap a client connection into monitor that auto-terminates\n\t// idle connection and connection with expired cert.\n\ttc, err := monitorConn(ctx, monitorConnConfig{\n\t\tconn: clientConn,\n\t\tlockWatcher: s.cfg.LockWatcher,\n\t\tlockTargets: proxyCtx.AuthContext.LockTargets(),\n\t\tidentity: proxyCtx.AuthContext.Identity.GetIdentity(),\n\t\tchecker: proxyCtx.AuthContext.Checker,\n\t\tclock: s.cfg.Clock,\n\t\tserverID: s.cfg.ServerID,\n\t\tauthClient: s.cfg.AuthClient,\n\t\tteleportUser: proxyCtx.AuthContext.Identity.GetIdentity().Username,\n\t\temitter: s.cfg.Emitter,\n\t\tlog: s.log,\n\t\tctx: s.closeCtx,\n\t})\n\tif err != nil {\n\t\tclientConn.Close()\n\t\tserviceConn.Close()\n\t\treturn trace.Wrap(err)\n\t}\n\terrCh := make(chan error, 2)\n\tgo func() {\n\t\tdefer s.log.Debug(\"Stop proxying from client to service.\")\n\t\tdefer serviceConn.Close()\n\t\tdefer tc.Close()\n\t\t_, err := io.Copy(serviceConn, tc)\n\t\terrCh <- err\n\t}()\n\tgo func() {\n\t\tdefer s.log.Debug(\"Stop proxying from service to client.\")\n\t\tdefer serviceConn.Close()\n\t\tdefer tc.Close()\n\t\t_, err := io.Copy(tc, serviceConn)\n\t\terrCh <- err\n\t}()\n\tvar errs []error\n\tfor i := 0; i < 2; i++ {\n\t\tselect {\n\t\tcase err := <-errCh:\n\t\t\tif err != nil && !utils.IsOKNetworkError(err) {\n\t\t\t\ts.log.WithError(err).Warn(\"Connection problem.\")\n\t\t\t\terrs = append(errs, err)\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\treturn trace.ConnectionProblem(nil, \"context is closing\")\n\t\t}\n\t}\n\treturn trace.NewAggregate(errs...)\n}", "func (p *connPool) wait() *conn {\n\tdeadline := time.After(p.opt.getPoolTimeout())\n\tfor {\n\t\tselect {\n\t\tcase cn := <-p.freeConns:\n\t\t\tif p.isIdle(cn) {\n\t\t\t\tvar err error\n\t\t\t\tcn, err = p.replace(cn)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"redis: replace failed: %s\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn cn\n\t\tcase <-deadline:\n\t\t\treturn nil\n\t\t}\n\t}\n\tpanic(\"not reached\")\n}", "func (p *Pool) Get() (*PooledConnection, error) {\n\t// Lock the pool to keep the kids out.\n\tp.mu.Lock()\n\n\t// Clean this place up.\n\tp.purge()\n\n\t// Wait loop\n\tfor {\n\t\t// Try to grab first available idle connection\n\t\tif conn := p.first(); conn != nil {\n\n\t\t\t// Remove the connection from the idle slice\n\t\t\tp.idle = append(p.idle[:0], p.idle[1:]...)\n\t\t\tp.active++\n\t\t\tp.mu.Unlock()\n\t\t\tpc := &PooledConnection{Pool: p, Client: conn.pc.Client}\n\t\t\treturn pc, nil\n\n\t\t}\n\n\t\t// No idle connections, try dialing a new one\n\t\tif p.MaxActive == 0 || p.active < p.MaxActive {\n\t\t\tp.active++\n\t\t\tdial := p.Dial\n\n\t\t\t// Unlock here so that any other connections that need to be\n\t\t\t// dialed do not have to wait.\n\t\t\tp.mu.Unlock()\n\n\t\t\tdc, err := dial()\n\t\t\tif err != nil {\n\t\t\t\tp.mu.Lock()\n\t\t\t\tp.release()\n\t\t\t\tp.mu.Unlock()\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tpc := &PooledConnection{Pool: p, Client: dc}\n\t\t\treturn pc, nil\n\t\t}\n\n\t\t//No idle connections and max active connections, let's wait.\n\t\tif p.cond == nil {\n\t\t\tp.cond = sync.NewCond(&p.mu)\n\t\t}\n\n\t\tp.cond.Wait()\n\t}\n}", "func (p *pool) Fetch(w http.ResponseWriter, r *http.Request) {\n\tstart := time.Now()\n\tconn := <-p.connections\n\n\tctxAttempt := r.Context().Value(attemptsKey)\n\tvar attempt int\n\n\tif ctxAttempt != nil {\n\t\tattempt = ctxAttempt.(int) + 1\n\t}\n\n\tif attempt > p.maxRetries {\n\t\treturn\n\t}\n\n\tduration := time.Since(start).Seconds()\n\tstats.Durations.WithLabelValues(\"get_connection\").Observe(duration)\n\tstats.AvailableConnectionsGauge.WithLabelValues(\"in_use\").Add(1)\n\tdefer func() {\n\t\tstats.AvailableConnectionsGauge.WithLabelValues(\"in_use\").Sub(1)\n\t\tstats.Attempts.WithLabelValues().Observe(float64(attempt))\n\t\tduration = time.Since(start).Seconds()\n\t\tstats.Durations.WithLabelValues(\"return_connection\").Observe(duration)\n\n\t\tif !conn.Shut {\n\t\t\tp.connections <- conn\n\t\t}\n\t}()\n\n\tif p.cache != nil && r.Method == \"GET\" {\n\t\tvalue, found := p.cache.Get(r.URL.Path)\n\t\tif found {\n\t\t\tstats.CacheCounter.WithLabelValues(r.URL.Path, \"hit\").Add(1)\n\t\t\tres := value.(string)\n\t\t\t_, err := w.Write([]byte(res))\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error writing: %s\", err.Error())\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tstats.CacheCounter.WithLabelValues(r.URL.Path, \"miss\").Add(1)\n\t}\n\n\tusableProxy, err := conn.Get()\n\tctx := context.WithValue(r.Context(), attemptsKey, attempt)\n\n\tif err != nil {\n\t\tlog.Printf(\"retrying err with request: %s\", err.Error())\n\t\tp.Fetch(w, r.WithContext(ctx))\n\t} else {\n\t\tusableProxy.ServeHTTP(w, r)\n\t}\n}", "func proxy(ctx context.Context, logger hclog.Logger, destAddr string, l net.Listener) {\n\t// Wait for all connections to be done before exiting to prevent\n\t// goroutine leaks.\n\twg := sync.WaitGroup{}\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer func() {\n\t\t// Must cancel context and close listener before waiting\n\t\tcancel()\n\t\t_ = l.Close()\n\t\twg.Wait()\n\t}()\n\n\t// Close Accept() when context is cancelled\n\tgo func() {\n\t\t<-ctx.Done()\n\t\t_ = l.Close()\n\t}()\n\n\tfor ctx.Err() == nil {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\tif ctx.Err() != nil {\n\t\t\t\t// Accept errors during shutdown are to be expected\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlogger.Error(\"error in socket proxy; shutting down proxy\", \"error\", err, \"dest\", destAddr)\n\t\t\treturn\n\t\t}\n\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tproxyConn(ctx, logger, destAddr, conn)\n\t\t}()\n\t}\n}", "func (p *Pool) purge() {\n\tif timeout := p.IdleTimeout; timeout > 0 {\n\t\tvar valid []*idleConnection\n\t\tnow := time.Now()\n\t\tfor _, v := range p.idle {\n\t\t\t// If the client has an error then exclude it from the pool\n\t\t\tif v.pc.Client.Errored {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif v.t.Add(timeout).After(now) {\n\t\t\t\tvalid = append(valid, v)\n\t\t\t} else {\n\t\t\t\t// Force underlying connection closed\n\t\t\t\tv.pc.Client.Close()\n\t\t\t}\n\t\t}\n\t\tp.idle = valid\n\t}\n}", "func (c *ChannelPool) Get() (interface{}, error) {\n\tconns := c.getConns()\n\tif conns == nil {\n\t\treturn nil, ErrClosed\n\t}\n\tfor {\n\t\tselect {\n\t\tcase wrapConn := <-conns:\n\t\t\tif wrapConn == nil {\n\t\t\t\treturn c.factory(c.para)\n\t\t\t}\n\t\t\tif timeout := c.idleTimeout; timeout > 0 {\n\t\t\t\tif wrapConn.t.Add(timeout).Before(time.Now()) {\n\t\t\t\t\tc.Close(wrapConn.conn)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn wrapConn.conn, nil\n\t\tdefault:\n\t\t\tconn, err := c.factory(c.para)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\treturn conn, nil\n\t\t}\n\t}\n}", "func DialProxy() (net.Conn, error) {\n\tvar d Dialer\n\treturn d.DialProxy()\n}", "func (s *Pool) Get() (net.Conn, error) {\n\tif cn := s.pop(); cn != nil {\n\t\treturn cn, nil\n\t}\n\n\treturn s.factory()\n}", "func (h *http1) Dial(network, addr string) (net.Conn, error) {\n\tswitch network {\n\tcase \"tcp\", \"tcp6\", \"tcp4\":\n\tdefault:\n\t\treturn nil, errors.New(\"proxy: no support for HTTP proxy connections of type \" + network)\n\t}\n\n\tconn, err := h.forward.Dial(h.network, h.addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcloseConn := &conn\n\tdefer func() {\n\t\tif closeConn != nil {\n\t\t\t(*closeConn).Close()\n\t\t}\n\t}()\n\n\thost, portStr, err := net.SplitHostPort(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tport, err := strconv.Atoi(portStr)\n\tif err != nil {\n\t\treturn nil, errors.New(\"proxy: failed to parse port number: \" + portStr)\n\t}\n\tif port < 1 || port > 0xffff {\n\t\treturn nil, errors.New(\"proxy: port number out of range: \" + portStr)\n\t}\n\n\tif h.resolver != nil {\n\t\thosts, err := h.resolver.LookupHost(host)\n\t\tif err == nil && len(hosts) > 0 {\n\t\t\thost = hosts[0]\n\t\t}\n\t}\n\n\tb := bufPool.Get().(*bytes.Buffer)\n\tb.Reset()\n\n\tfmt.Fprintf(b, \"CONNECT %s:%s HTTP/1.1\\r\\nHost: %s:%s\\r\\n\", host, portStr, host, portStr)\n\tif h.user != \"\" {\n\t\tfmt.Fprintf(b, \"Proxy-Authorization: Basic %s\\r\\n\", base64.StdEncoding.EncodeToString([]byte(h.user+\":\"+h.password)))\n\t}\n\tio.WriteString(b, \"\\r\\n\")\n\n\tbb := b.Bytes()\n\tbufPool.Put(b)\n\n\tif _, err := conn.Write(bb); err != nil {\n\t\treturn nil, errors.New(\"proxy: failed to write greeting to HTTP proxy at \" + h.addr + \": \" + err.Error())\n\t}\n\n\tbuf := make([]byte, 2048)\n\tb0 := buf\n\ttotal := 0\n\n\tfor {\n\t\tn, err := conn.Read(buf)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttotal += n\n\t\tbuf = buf[n:]\n\n\t\tif i := bytes.Index(b0, CRLFCRLF); i > 0 {\n\t\t\tconn = &preReaderConn{conn, b0[i+4 : total]}\n\t\t\tb0 = b0[:i+4]\n\t\t\tbreak\n\t\t}\n\t}\n\n\tresp, err := http.ReadResponse(bufio.NewReader(bytes.NewReader(b0)), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, errors.New(\"proxy: failed to read greeting from HTTP proxy at \" + h.addr + \": \" + resp.Status)\n\t}\n\n\tcloseConn = nil\n\treturn conn, nil\n}", "func (p *Pool) Get(ctx context.Context) (*PoolConn, error) {\n\tselect {\n\tcase conn := <-p.ch:\n\t\tnow := p.nowfunc()\n\t\tif (p.maxIdleTime > 0 && now.Sub(conn.freedAt) > p.maxIdleTime) ||\n\t\t\t(p.maxConnTime > 0 && now.Sub(conn.CreatedAt()) > p.maxConnTime) {\n\t\t\tp.closeconn(conn)\n\t\t\treturn p.Get(ctx)\n\t\t}\n\t\tconn.p = p\n\t\treturn conn, nil\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\tdefault:\n\t}\n\tactive := atomic.AddInt64(&p.active, 1)\n\tif p.maxActive > 0 && active > p.maxActive {\n\t\tatomic.AddInt64(&p.active, -1)\n\t\treturn nil, ErrMaxActive\n\t}\n\tc, err := p.dial(ctx)\n\tif err != nil {\n\t\tatomic.AddInt64(&p.active, -1)\n\t\treturn nil, err\n\t}\n\treturn &PoolConn{Conn: c, p: p, createdAt: p.nowfunc()}, nil\n}", "func (p *Pool) Get(ctx context.Context) (*ClientConn, error) {\n\tif p == nil {\n\t\treturn nil, ErrClosed\n\t}\n\n\tclient := make(chan *ClientConn, 1)\n\tp.clientQueue(client)\n\n\tselect {\n\tcase conn := <-client:\n\t\tconn.use()\n\t\treturn conn, nil\n\tcase <-ctx.Done():\n\t\treturn nil, ErrTimeout\n\t}\n}", "func RemotePoolWithTimeout(remoteURL string) (couchbase.Pool, error) {\n\tpoolObj, err := simple_utils.ExecWithTimeout2(remotePool, remoteURL, base.DefaultHttpTimeout, logger_utils)\n\tif poolObj != nil {\n\t\treturn poolObj.(couchbase.Pool), err\n\t} else {\n\t\tvar pool couchbase.Pool\n\t\treturn pool, err\n\t}\n}", "func connectPool() *http.Client {\n\tif clientConnect == nil {\n\t\tclientConnect = new(httpClient)\n\t\thttptr := &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\n\t\t\tMaxIdleConns: 50,\n\t\t\tMaxIdleConnsPerHost: 50,\n\t\t}\n\t\tclientConnect.Client = &http.Client{\n\t\t\tTransport: httptr,\n\t\t}\n\t}\n\treturn clientConnect.Client\n}", "func establishConn(p *pool.Pool, dest pool.Destination) (net.Conn, error) {\n\tretry := 0\n\tretryMax := 3\n\n\tfor {\n\t\t// If it's not registered, abort.\n\t\tif _, destinationRegistered := p.Registered[dest.Name]; !destinationRegistered {\n\t\t\treturn nil, errors.New(\"Destination not registered\")\n\t\t}\n\n\t\t_, connectionIsInPool := p.Conns[dest.Name]\n\n\t\t// Are we retrying a previously established connection that failed?\n\t\tif retry >= retryMax && connectionIsInPool {\n\t\t\tlog.Printf(\"Exceeded retry count (%d) for destination %s\\n\", retryMax, dest.Name)\n\t\t\tp.RemoveConn(dest)\n\t\t}\n\n\t\t// Try a connection every 10s.\n\t\tconn, err := net.DialTimeout(\"tcp\", dest.Addr, time.Duration(3*time.Second))\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Destination error: %s, retrying in 10s\\n\", err)\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t\t// Increment failure count.\n\t\t\tretry++\n\t\t\tcontinue\n\t\t} else {\n\t\t\t// If this connection succeeds and is not in the pool\n\t\t\tif !connectionIsInPool {\n\t\t\t\tlog.Printf(\"Adding destination to connection pool: %s\\n\", dest.Name)\n\t\t\t\tp.AddConn(dest)\n\t\t\t} else {\n\t\t\t\t// If this connection is still in the pool, we're\n\t\t\t\t// likely here due to a temporary disconnect.\n\t\t\t\tlog.Printf(\"Reconnected to destination: %s\\n\", dest.Name)\n\t\t\t}\n\n\t\t\treturn conn, nil\n\t\t}\n\n\t}\n\n}", "func (p *Pool) Get() (net.Conn, error) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tif p.conns == nil {\n\t\treturn nil, ErrPoolClosed\n\t}\n\n\tvar err error\n\tselect {\n\tcase conn := <-p.conns:\n\t\tif err = p.heartbeat(conn); err != nil {\n\t\t\tfmt.Println(\"detected connection closed\")\n\t\t\tconn, err = p.factory()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tif conn == nil {\n\t\t\tconn, err = p.factory()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t}\n\n\t\treturn conn, nil\n\tdefault:\n\t\treturn p.factory()\n\t}\n}", "func (p *Pool) Get() (*redisClient, error) {\n\tselect {\n\tcase rc := <-p.pool:\n\t\tif p.clientTimeout > 0 && time.Now().Sub(rc.createdTime) > p.clientTimeout {\n\t\t\tif err := rc.Conn.Close(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn p.generate()\n\t\t}\n\t\treturn rc, nil\n\tdefault:\n\t\treturn p.generate()\n\t}\n}", "func (pool *ComplexPool) New() (Proxy, error) {\n\tlength := pool.SizeUnused()\n\n\tif length == 0 {\n\t\tif !pool.Config.ReloadWhenEmpty {\n\t\t\treturn Proxy{}, fmt.Errorf(\"prox (%p): cannot select proxy, no unused proxies left in pool\", pool)\n\t\t}\n\n\t\terr := pool.Load()\n\t\tif err != nil {\n\t\t\treturn Proxy{}, fmt.Errorf(\"prox (%p): cannot select unused proxy, error occurred while reloading pool: %v\", pool, err)\n\t\t}\n\n\t\tlength = pool.SizeUnused()\n\t\tif length == 0 {\n\t\t\treturn Proxy{}, fmt.Errorf(\"prox (%p): cannot select proxy, no unused proxies even after reload\", pool)\n\t\t}\n\t}\n\n\trawProxy := pool.Unused.Random()\n\tpool.Unused.Remove(rawProxy)\n\n\treturn *CastProxy(rawProxy), nil\n}", "func TestSourcePool_connsReturning(t *testing.T) {\n\tsrc := &testSource{}\n\texpires := time.Millisecond\n\tpool := store.Pool(src, 1, expires)\n\tpool.Open()\n\n\tgetConn := func() <-chan store.Conn {\n\t\tout := make(chan store.Conn)\n\t\tgo func() {\n\t\t\tconn, _ := pool.Open()\n\t\t\tout <- conn\n\t\t\tclose(out)\n\t\t}()\n\t\treturn out\n\t}\n\n\tselect {\n\tcase <-getConn():\n\t\t// skip\n\tcase <-time.After((expires * 15) / 10):\n\t\t// wait some more to see if get new connection\n\t\tt.Errorf(\"failed to get connection after conn expires\")\n\t}\n}", "func remotePool(remoteURLObj interface{}) (interface{}, error) {\n\tremoteURL := remoteURLObj.(string)\n\tclient, err := couchbase.Connect(remoteURL)\n\tif err != nil {\n\t\treturn couchbase.Pool{}, NewEnhancedError(fmt.Sprintf(\"Error connecting to couchbase. url=%v\", UrlForLog(remoteURL)), err)\n\t}\n\treturn client.GetPool(\"default\")\n}", "func (r *RoundRobin) Next() (*proxy.Proxy, error) {\n\tnext := atomic.AddInt32(&r.current, 1) % int32(len(r.proxies))\n\tatomic.StoreInt32(&r.current, next)\n\treturn getAvailableProxy(r.proxies, int(next))\n}", "func CheckProxySOCKS(proxyy string, c chan QR, wg *sync.WaitGroup) (err error) {\n\n\tdefer wg.Done()\n\n\td := net.Dialer{\n\t\tTimeout: timeout,\n\t\tKeepAlive: timeout,\n\t}\n\n\t//Sending request through proxy\n\tdialer, _ := proxy.SOCKS5(\"tcp\", proxyy, nil, &d)\n\n\thttpClient := &http.Client{\n\t\tTimeout: timeout,\n\t\tTransport: &http.Transport{\n\t\t\tDisableKeepAlives: true,\n\t\t\tDial: dialer.Dial,\n\t\t},\n\t}\n\tresponse, err := httpClient.Get(\"https://api.ipify.org?format=json\")\n\n\tif err != nil {\n\n\t\tc <- QR{Addr: proxyy, Res: false}\n\t\treturn\n\t}\n\n\tdefer response.Body.Close()\n\tio.Copy(ioutil.Discard, response.Body)\n\n\tc <- QR{Addr: proxyy, Res: true}\n\n\treturn nil\n\n}", "func getPool() *redis.Pool {\n\tif(pool == nil){\n pool = &redis.Pool{\n\t\t\tMaxIdle: 3,\n\t\t\tIdleTimeout: 240 * time.Second,\n\t\t\tDial: func () (redis.Conn, error) { return redis.Dial(\"tcp\", redisUrlServer) },\n\t\t }\n\t}\n\n\treturn pool\t\n}", "func (p *RedisConnectionPool) Pop() (*RedisConnection, error) {\n\t// Pop a connection from the pool\n\tc := p.myPool.GetConnection()\n\n\t// Return the connection\n\tif c != nil {\n\t\tp.Logger.Finest(\"Removed connection %v\", c)\n\t\treturn c.(*RedisConnection), nil\n\t}\n\n\t// Return an error when all connections are exhausted\n\tp.Logger.Critical(\"[RedisConnectionPool][Pop] No connections available pool=%v\", p.String())\n\treturn nil, ErrNoConnectionsAvailable\n}", "func (p *ConnProvider) Get(addr string) (net.Conn, error) {\n\tclosed := atomic.LoadInt32(&p.closed)\n\tif closed == 1 {\n\t\treturn nil, errors.New(\"pool is closed\")\n\t}\n\n\tp.mu.Lock()\n\tif _, ok := p.idleConnMap[addr]; !ok {\n\t\tp.mu.Unlock()\n\t\treturn nil, errors.New(\"no idle conn\")\n\t}\n\tp.mu.Unlock()\n\nRETRY:\n\tselect {\n\tcase conn := <-p.idleConnMap[addr]:\n\t\t// Getting a net.Conn requires verifying that the net.Conn is valid\n\t\t_, err := conn.Read([]byte{})\n\t\tif err != nil || err == io.EOF {\n\t\t\t// conn is close Or timeout\n\t\t\t_ = conn.Close()\n\t\t\tgoto RETRY\n\t\t}\n\t\treturn conn, nil\n\tdefault:\n\t\treturn nil, errors.New(\"no idle conn\")\n\t}\n}", "func proxyConnection(c net.Conn, upstreamAddr string) error {\n\tupC, err := net.Dial(\"tcp\", upstreamAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer upC.Close()\n\twg := sync.WaitGroup{}\n\twg.Add(2)\n\n\t// to upstream\n\tgo func() {\n\t\tio.Copy(upC, c)\n\t\twg.Done()\n\t}()\n\t// from upstream\n\tgo func() {\n\t\tio.Copy(c, upC)\n\t\twg.Done()\n\t}()\n\n\twg.Wait()\n\treturn nil\n}", "func proxyStress(t *testing.T) {\n\tvar (\n\t\twg sync.WaitGroup\n\t\terrChs = make([]chan error, workerCnt+1)\n\t\tstopChs = make([]chan struct{}, workerCnt+1)\n\t\tproxyURLChs = make([]chan string, workerCnt)\n\t\tbck = cmn.Bck{\n\t\t\tName: testBucketName,\n\t\t\tProvider: cmn.ProviderAIS,\n\t\t}\n\t\tproxyURL = tutils.RandomProxyURL(t)\n\t)\n\n\ttutils.CreateFreshBucket(t, proxyURL, bck, nil)\n\tdefer func() {\n\t\terr := tutils.WaitNodeReady(proxyURL)\n\t\ttassert.CheckFatal(t, err)\n\t}()\n\n\t// start all workers\n\tfor i := 0; i < workerCnt; i++ {\n\t\terrChs[i] = make(chan error, defaultChanSize)\n\t\tstopChs[i] = make(chan struct{}, defaultChanSize)\n\t\tproxyURLChs[i] = make(chan string, defaultChanSize)\n\n\t\twg.Add(1)\n\t\tgo putGetDelWorker(proxyURL, stopChs[i], proxyURLChs[i], errChs[i], &wg)\n\n\t\t// stagger the workers so they don't always do the same operation at the same time\n\t\tn := cos.NowRand().Intn(999)\n\t\ttime.Sleep(time.Duration(n+1) * time.Millisecond)\n\t}\n\n\terrChs[workerCnt] = make(chan error, defaultChanSize)\n\tstopChs[workerCnt] = make(chan struct{}, defaultChanSize)\n\twg.Add(1)\n\tgo primaryKiller(t, proxyURL, stopChs[workerCnt], proxyURLChs, errChs[workerCnt], &wg)\n\n\ttimer := time.After(multiProxyTestTimeout)\nloop:\n\tfor {\n\t\tfor _, ch := range errChs {\n\t\t\tselect {\n\t\t\tcase <-timer:\n\t\t\t\tbreak loop\n\t\t\tcase <-ch:\n\t\t\t\t// Read errors, throw away, this is needed to unblock the workers.\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\t}\n\n\t// stop all workers\n\tfor _, stopCh := range stopChs {\n\t\tstopCh <- struct{}{}\n\t\tclose(stopCh)\n\t}\n\n\twg.Wait()\n}", "func TestReverseProxyMaxConnLimit(t *testing.T) {\n\tlog.SetOutput(ioutil.Discard)\n\tdefer log.SetOutput(os.Stderr)\n\n\tconst MaxTestConns = 2\n\tconnReceived := make(chan bool, MaxTestConns)\n\tconnContinue := make(chan bool)\n\tbackend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tconnReceived <- true\n\t\t<-connContinue\n\t}))\n\tdefer backend.Close()\n\n\tsu, err := NewStaticUpstreams(caddyfile.NewDispenser(\"Testfile\", strings.NewReader(`\n\t\tproxy / `+backend.URL+` {\n\t\t\tmax_conns `+fmt.Sprint(MaxTestConns)+`\n\t\t}\n\t`)), \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// set up proxy\n\tp := &Proxy{\n\t\tNext: httpserver.EmptyNext, // prevents panic in some cases when test fails\n\t\tUpstreams: su,\n\t}\n\n\tvar jobs sync.WaitGroup\n\n\tfor i := 0; i < MaxTestConns; i++ {\n\t\tjobs.Add(1)\n\t\tgo func(i int) {\n\t\t\tdefer jobs.Done()\n\t\t\tw := httptest.NewRecorder()\n\t\t\tcode, err := p.ServeHTTP(w, httptest.NewRequest(\"GET\", \"/\", nil))\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Request %d failed: %v\", i, err)\n\t\t\t} else if code != 0 {\n\t\t\t\tt.Errorf(\"Bad return code for request %d: %d\", i, code)\n\t\t\t} else if w.Code != 200 {\n\t\t\t\tt.Errorf(\"Bad statuc code for request %d: %d\", i, w.Code)\n\t\t\t}\n\t\t}(i)\n\t}\n\t// Wait for all the requests to hit the backend.\n\tfor i := 0; i < MaxTestConns; i++ {\n\t\t<-connReceived\n\t}\n\n\t// Now we should have MaxTestConns requests connected and sitting on the backend\n\t// server. Verify that the next request is rejected.\n\tw := httptest.NewRecorder()\n\tcode, err := p.ServeHTTP(w, httptest.NewRequest(\"GET\", \"/\", nil))\n\tif code != http.StatusBadGateway {\n\t\tt.Errorf(\"Expected request to be rejected, but got: %d [%v]\\nStatus code: %d\",\n\t\t\tcode, err, w.Code)\n\t}\n\n\t// Now let all the requests complete and verify the status codes for those:\n\tclose(connContinue)\n\n\t// Wait for the initial requests to finish and check their results.\n\tjobs.Wait()\n}", "func (c *PoolClient) GetConn(fn func(conn *grpc.ClientConn) error) error {\n\tfor {\n\t\tconn, ok := c.getNextConn()\n\t\tif !ok {\n\t\t\treturn ErrNoConn\n\t\t}\n\n\t\tok = conn.acquire()\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\treturn doRequestConn(conn, fn)\n\t}\n}", "func (c *ChannelPool) Get() (net.Conn, error) {\n\tconns := c.getConns()\n\tif conns == nil {\n\t\treturn nil, ErrClosed\n\t}\n\n\tselect {\n\tcase conn := <-conns:\n\t\tif conn == nil {\n\t\t\treturn nil, ErrClosed\n\t\t}\n\t\treturn conn, nil\n\tdefault:\n\t\treturn c.factory()\n\t}\n}", "func dqliteProxy(name string, stopCh chan struct{}, remote net.Conn, local net.Conn) {\n\tl := logger.AddContext(logger.Ctx{\"name\": name, \"local\": remote.LocalAddr(), \"remote\": remote.RemoteAddr()})\n\tl.Info(\"Dqlite proxy started\")\n\tdefer l.Info(\"Dqlite proxy stopped\")\n\n\tremoteTCP, err := tcp.ExtractConn(remote)\n\tif err != nil {\n\t\tl.Warn(\"Failed extracting TCP connection from remote connection\", logger.Ctx{\"err\": err})\n\t} else {\n\t\terr := tcp.SetTimeouts(remoteTCP, time.Second*30)\n\t\tif err != nil {\n\t\t\tl.Warn(\"Failed setting TCP timeouts on remote connection\", logger.Ctx{\"err\": err})\n\t\t}\n\t}\n\n\tremoteToLocal := make(chan error)\n\tlocalToRemote := make(chan error)\n\n\t// Start copying data back and forth until either the client or the\n\t// server get closed or hit an error.\n\tgo func() {\n\t\t_, err := io.Copy(local, remote)\n\t\tremoteToLocal <- err\n\t}()\n\n\tgo func() {\n\t\t_, err := io.Copy(remote, local)\n\t\tlocalToRemote <- err\n\t}()\n\n\terrs := make([]error, 2)\n\n\tselect {\n\tcase <-stopCh:\n\t\t// Force closing, ignore errors.\n\t\t_ = remote.Close()\n\t\t_ = local.Close()\n\t\t<-remoteToLocal\n\t\t<-localToRemote\n\tcase err := <-remoteToLocal:\n\t\tif err != nil {\n\t\t\terrs[0] = fmt.Errorf(\"remote -> local: %w\", err)\n\t\t}\n\n\t\t_ = local.(*net.UnixConn).CloseRead()\n\t\terr = <-localToRemote\n\t\tif err != nil {\n\t\t\terrs[1] = fmt.Errorf(\"local -> remote: %w\", err)\n\t\t}\n\n\t\t_ = remote.Close()\n\t\t_ = local.Close()\n\tcase err := <-localToRemote:\n\t\tif err != nil {\n\t\t\terrs[0] = fmt.Errorf(\"local -> remote: %w\", err)\n\t\t}\n\n\t\t_ = remoteTCP.CloseRead()\n\t\terr = <-remoteToLocal\n\t\tif err != nil {\n\t\t\terrs[1] = fmt.Errorf(\"remote -> local: %w\", err)\n\t\t}\n\n\t\t_ = local.Close()\n\t\t_ = remote.Close()\n\t}\n\n\tif errs[0] != nil || errs[1] != nil {\n\t\terr := dqliteProxyError{first: errs[0], second: errs[1]}\n\t\tl.Warn(\"Dqlite proxy failed\", logger.Ctx{\"err\": err})\n\t}\n}", "func (c *channelPool) Get() (RpcAble, error) {\n\trconns := c.getRconns()\n\tif rconns == nil {\n\t\treturn nil, ErrClosed\n\t}\n\n\t// wrap our rconns with out custom RpcAble implementation (wrapRconn\n\t// method) that puts the RPC-able connection back to the pool if it's closed.\n\tselect {\n\tcase rconn := <-rconns:\n\t\tif rconn == nil {\n\t\t\treturn nil, ErrClosed\n\t\t}\n\n\t\treturn c.wrapRconn(rconn), nil\n\tdefault:\n\t\trconn, err := c.factory()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn c.wrapRconn(rconn), nil\n\t}\n}", "func (p *TCPProxy) Close() {\n\tvar err error\n\tlogger.Green.Printf(\"Closing proxy, type: [%s], addr: [%s].\\n\", p.listenerConfigs.Protocol, p.listenerAddr.String())\n\tp.closed.SetToIf(false, true)\n\tp.connMap.Range(func(k, conn interface{}) bool {\n\t\tif err = conn.(io.ReadWriteCloser).Close(); err == nil {\n\t\t\tlogger.Cyan.Printf(\"closing connection to remote: [%v] success.\\n\", k)\n\t\t} else {\n\t\t\tlogger.Red.Printf(\"closing connection to remote: [%v] with error: %v\\n\", k, err)\n\t\t}\n\t\treturn true\n\t})\n\tif p.listenerConn != nil {\n\t\tp.listenerConn.Close()\n\t}\n}", "func (p *connPool) Get() (cn *conn, isNew bool, err error) {\n\tif p.closed() {\n\t\terr = errClosed\n\t\treturn\n\t}\n\n\t// Fetch first non-idle connection, if available.\n\tif cn = p.First(); cn != nil {\n\t\treturn\n\t}\n\n\t// Try to create a new one.\n\tif p.conns.Reserve() {\n\t\tcn, err = p.new()\n\t\tif err != nil {\n\t\t\tp.conns.Remove(nil)\n\t\t\treturn\n\t\t}\n\t\tp.conns.Add(cn)\n\t\tisNew = true\n\t\treturn\n\t}\n\n\t// Otherwise, wait for the available connection.\n\tif cn = p.wait(); cn != nil {\n\t\treturn\n\t}\n\n\terr = errPoolTimeout\n\treturn\n}", "func (t *TCPPool)getConnection() *net.TCPConn{\n\tnum := len(t.pool)\n\tif num == 0{\n\t\treturn nil\n\t}\n\tconn := t.pool[num-1]\n\n\t//pop last item from the pool \n\tt.pool = t.pool[:num-1]\n\treturn conn\n}", "func (m *MultiConnPool) Get() *pgx.ConnPool {\n\tif len(m.Pools) == 1 {\n\t\treturn m.Pools[0]\n\t}\n\ti := atomic.AddUint32(&m.counter, 1) - 1\n\treturn m.Pools[i%uint32(len(m.Pools))]\n}", "func (p *ReverseProxy) ProxyHTTPS(rw http.ResponseWriter, req *http.Request) {\n\thij, ok := rw.(http.Hijacker)\n\tif !ok {\n\t\tp.logf(\"http server does not support hijacker\")\n\t\ttime.Sleep(500 * time.Millisecond)\n\t\treturn\n\t}\n\n\tclientConn, _, err := hij.Hijack()\n\tif err != nil {\n\t\tp.logf(\"http: proxy error: %v\", err)\n\t\tif clientConn != nil {\n\t\t\tclientConn.Close()\n\t\t}\n\t\treturn\n\t}\n\n\tproxyConn, err := net.Dial(\"tcp\", req.URL.Host)\n\tif err != nil {\n\t\tp.logf(\"http: proxy error: %v\", err)\n\t\tp.logf(\"dial stopped %v\", req.URL)\n\t\tp.logf(\"client connection stopped\")\n\t\tclientConn.Close()\n\t\tif proxyConn != nil {\n\t\t\tproxyConn.Close()\n\t\t}\n\t\treturn\n\t}\n\n\tdeadline := time.Now()\n\tif p.Timeout == 0 {\n\t\tdeadline = deadline.Add(defaultTimeout)\n\t} else {\n\t\tdeadline = deadline.Add(p.Timeout)\n\t}\n\n\terr = clientConn.SetDeadline(deadline)\n\tif err != nil {\n\t\tp.logf(\"http: proxy error: %v\", err)\n\t\tclientConn.Close()\n\t\tproxyConn.Close()\n\t\ttime.Sleep(500 * time.Millisecond)\n\t\treturn\n\t}\n\n\terr = proxyConn.SetDeadline(deadline)\n\tif err != nil {\n\t\tp.logf(\"http: proxy error: %v\", err)\n\t\tclientConn.Close()\n\t\tproxyConn.Close()\n\t\ttime.Sleep(500 * time.Millisecond)\n\t\treturn\n\t}\n\n\t_, err = clientConn.Write([]byte(\"HTTP/1.0 200 OK\\r\\n\\r\\n\"))\n\tif err != nil {\n\t\tclientConn.Close()\n\t\tproxyConn.Close()\n\t\treturn\n\t}\n\n\tstop := make(chan bool)\n\n\tgo transfer(clientConn, proxyConn, stop)\n\tgo transfer(proxyConn, clientConn, stop)\n\n\tselect {\n\tcase <-stop:\n\t\treturn\n\t}\n}", "func (d *Dialer) DialProxy() (net.Conn, error) {\n\treturn d.DialProxyContext(context.Background())\n}", "func (cop *ConnPool) getChannel() (*Channel, error) {\n\nGETFREECHANNEL:\n\tcop.l.Lock()\n\n\tif cop.closed {\n\t\tcop.l.Unlock()\n\t\treturn nil, ErrPoolClosed\n\t}\n\n\t// step1: reuse free channels\n\tif len(cop.idleChas) > 0 {\n\t\tvar cha *Channel\n\t\t// shift from free pool\n\t\tcha, cop.idleChas = cop.idleChas[0], cop.idleChas[1:]\n\t\tcop.incrChaBusyNum()\n\n\t\tcop.l.Unlock()\n\t\treturn cha, nil\n\t}\n\n\t// step2: get connection\n\tconn, err := cop.getConn()\n\tif err == ErrTooManyConn {\n\t\t// unlock\n\t\tcop.l.Unlock()\n\n\t\t// wait for available channel\n\t\t// if wait return and has a free channel, use it\n\t\tch := make(chan *Channel)\n\t\tcop.reqChaList.Put(ch)\n\t\tif cha := <-ch; cha != nil {\n\t\t\tcop.incrChaBusyNum()\n\t\t\treturn cha, nil\n\t\t}\n\n\t\t// retry\n\t\tgoto GETFREECHANNEL\n\t} else if err != nil {\n\t\tcop.close()\n\t\t// unlock\n\t\tcop.l.Unlock()\n\t\tutil.FailOnError(err, \"ConnPool.getChannel\")\n\t}\n\n\t// step3: open new channel\n\tcha, err := conn.openChannel()\n\n\tif err == amqp.ErrClosed || err == ErrBadConn {\n\t\tlog.Warnf(\"ConnPool.getChannel: %s\", ErrBadConn)\n\t\tcop.removeConn(conn)\n\t\t// unlock\n\t\tcop.l.Unlock()\n\t\tgoto GETFREECHANNEL\n\t} else if err == amqp.ErrChannelMax {\n\t\tlog.Warnf(\"ConnPool.getChannel: %s\", amqp.ErrChannelMax)\n\t\tcop.l.Unlock()\n\t\tgoto GETFREECHANNEL\n\t} else if err != nil {\n\t\tcop.close()\n\t\t// unlock\n\t\tcop.l.Unlock()\n\t\tutil.FailOnError(err, \"ConnPool.getChannel\")\n\t}\n\n\tcop.incrChaBusyNum()\n\n\tif cop.conf.Debug {\n\t\tlog.Debug(\"[channel] new channel opened\")\n\t}\n\n\t// unlock\n\tcop.l.Unlock()\n\treturn cha, nil\n}", "func ProxyRemoteRead(req *gomemcached.MCRequest) *gomemcached.MCResponse {\n\n\tkey := req.Key\n\tnodeList := getVbucketNode(int(findShard(string(key))))\n\tnodes := strings.Split(nodeList, \";\")\n\tvar res *gomemcached.MCResponse\n\n\tif len(nodes) < 1 {\n\t\tlog.Fatal(\"Nodelist is empty. Cannot proceed\")\n\t}\n\n\tpool, ok := connPool[nodes[0]]\n\tif ok == false {\n\t\tpool = newConnectionPool(nodes[0], 64, 128)\n\t\tconnPool[nodes[0]] = pool\n\t}\n\n\tcp, err := pool.Get()\n\tif err != nil {\n\t\tlog.Printf(\" Cannot get connection from pool %v\", err)\n\t\t// should retry or giveup TODO\n\t\tgoto done\n\t}\n\n\tres, err = cp.Get(0, string(req.Key))\n\tif err != nil || res.Status != gomemcached.SUCCESS {\n\t\tlog.Printf(\"Set failed. Error %v\", err)\n\t\tgoto done\n\t}\ndone:\n\tpool.Return(cp)\n\n\treturn res\n}", "func TestPoolDoDoesNotBlock(t *T) {\n\tsize := 10\n\trequestTimeout := 200 * time.Millisecond\n\tredialInterval := 100 * time.Millisecond\n\n\tconnFunc := PoolConnFunc(func(string, string) (Conn, error) {\n\t\treturn dial(DialTimeout(requestTimeout)), nil\n\t})\n\tpool := testPool(size,\n\t\tPoolOnEmptyCreateAfter(redialInterval),\n\t\tPoolPipelineWindow(0, 0),\n\t\tconnFunc,\n\t)\n\n\tassertPoolConns := func(exp int) {\n\t\tassert.Equal(t, exp, pool.NumAvailConns())\n\t}\n\tassertPoolConns(size)\n\n\tvar wg sync.WaitGroup\n\tvar timeExceeded uint32\n\n\t// here we try to imitate external requests which come one at a time\n\t// and exceed the number of connections in pool\n\tfor i := 0; i < 5*size; i++ {\n\t\twg.Add(1)\n\t\tgo func(i int) {\n\t\t\ttime.Sleep(time.Duration(i*10) * time.Millisecond)\n\n\t\t\ttimeStart := time.Now()\n\t\t\terr := pool.Do(WithConn(\"\", func(conn Conn) error {\n\t\t\t\ttime.Sleep(requestTimeout)\n\t\t\t\tconn.(*ioErrConn).lastIOErr = errors.New(\"i/o timeout\")\n\t\t\t\treturn nil\n\t\t\t}))\n\t\t\tassert.NoError(t, err)\n\n\t\t\tif time.Since(timeStart)-requestTimeout-redialInterval > 20*time.Millisecond {\n\t\t\t\tatomic.AddUint32(&timeExceeded, 1)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(i)\n\t}\n\n\twg.Wait()\n\tassert.True(t, timeExceeded == 0)\n}", "func (rc *RedisClient) GetConn() redis.Conn {\n\treturn rc.pool.Get()\n}", "func (h *Host) NextProxy() *httputil.ReverseProxy {\n\treturn <-h.proxyChannel\n}", "func RunProxy() {\n\tbuffer := make([]byte, 1500)\n\tfor {\n\t\tn, cliaddr, err := ProxyConn.ReadFromUDP(buffer[0:])\n\t\tif checkreport(1, err) {\n\t\t\tcontinue\n\t\t}\n\n\t\tr := bytes.NewReader(buffer)\n\t\tpublicHeader, err := quic.ParsePublicHeader(r)\n\n\t\t// drop every x-th packet\n\t\tdrop := 11\n\t\tif int(publicHeader.PacketNumber)%drop == 0 {\n\t\t\tVlogf(3, \"Dropping PacketNumber %d\\n\", publicHeader.PacketNumber)\n\t\t\tcontinue\n\t\t}\n\n\t\tVlogf(3, \"<- Connection 0x%x, PacketNumber %d\\n\", publicHeader.ConnectionID, publicHeader.PacketNumber)\n\n\t\tsaddr := cliaddr.String()\n\t\tdlock()\n\t\tconn, found := ClientDict[saddr]\n\t\tif !found {\n\t\t\tconn = NewConnection(ServerAddr, cliaddr)\n\t\t\tif conn == nil {\n\t\t\t\tdunlock()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tClientDict[saddr] = conn\n\t\t\tdunlock()\n\t\t\tVlogf(2, \"Created new connection for client %s\\n\", saddr)\n\t\t\t// Fire up routine to manage new connection\n\t\t\tgo RunConnection(conn)\n\t\t} else {\n\t\t\tVlogf(5, \"Found connection for client %s\\n\", saddr)\n\t\t\tdunlock()\n\t\t}\n\t\t// Relay to server\n\t\t_, err = conn.ServerConn.Write(buffer[0:n])\n\t\tif checkreport(1, err) {\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func proxyConn(ctx context.Context, logger hclog.Logger, destAddr string, conn net.Conn) {\n\t// Close the connection when we're done with it.\n\tdefer conn.Close()\n\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\t// Detect unix sockets\n\tnetwork := \"tcp\"\n\tconst unixPrefix = \"unix://\"\n\tif strings.HasPrefix(destAddr, unixPrefix) {\n\t\tnetwork = \"unix\"\n\t\tdestAddr = destAddr[len(unixPrefix):]\n\t}\n\n\tdialer := &net.Dialer{}\n\tdest, err := dialer.DialContext(ctx, network, destAddr)\n\tif err == context.Canceled || err == context.DeadlineExceeded {\n\t\tlogger.Trace(\"proxy exiting gracefully\", \"error\", err, \"dest\", destAddr,\n\t\t\t\"src_local\", conn.LocalAddr(), \"src_remote\", conn.RemoteAddr())\n\t\treturn\n\t}\n\tif err != nil {\n\t\tlogger.Error(\"error connecting to grpc\", \"error\", err, \"dest\", destAddr)\n\t\treturn\n\t}\n\n\t// Wait for goroutines to exit before exiting to prevent leaking.\n\twg := sync.WaitGroup{}\n\tdefer wg.Wait()\n\n\t// socket -> consul\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tdefer cancel()\n\t\tn, err := io.Copy(dest, conn)\n\t\tif ctx.Err() == nil && err != nil {\n\t\t\t// expect disconnects when proxying http\n\t\t\tlogger.Trace(\"error message received proxying to Consul\",\n\t\t\t\t\"msg\", err, \"dest\", destAddr, \"src_local\", conn.LocalAddr(),\n\t\t\t\t\"src_remote\", conn.RemoteAddr(), \"bytes\", n)\n\t\t\treturn\n\t\t}\n\t\tlogger.Trace(\"proxy to Consul complete\",\n\t\t\t\"src_local\", conn.LocalAddr(), \"src_remote\", conn.RemoteAddr(),\n\t\t\t\"bytes\", n,\n\t\t)\n\t}()\n\n\t// consul -> socket\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tdefer cancel()\n\t\tn, err := io.Copy(conn, dest)\n\t\tif ctx.Err() == nil && err != nil {\n\t\t\tlogger.Trace(\"error message received proxying from Consul\",\n\t\t\t\t\"msg\", err, \"dest\", destAddr, \"src_local\", conn.LocalAddr(),\n\t\t\t\t\"src_remote\", conn.RemoteAddr(), \"bytes\", n)\n\t\t\treturn\n\t\t}\n\t\tlogger.Trace(\"proxy from Consul complete\",\n\t\t\t\"src_local\", conn.LocalAddr(), \"src_remote\", conn.RemoteAddr(),\n\t\t\t\"bytes\", n,\n\t\t)\n\t}()\n\n\t// When cancelled close connections to break out of copies goroutines.\n\t<-ctx.Done()\n\t_ = conn.Close()\n\t_ = dest.Close()\n}", "func (p *connPool) Release(client *mcc.Client) {\n\t//reset connection deadlines\n\tconn := client.Hijack()\n\n\tconn.(net.Conn).SetReadDeadline(time.Date(1, time.January, 0, 0, 0, 0, 0, time.UTC))\n\tconn.(net.Conn).SetWriteDeadline(time.Date(1, time.January, 0, 0, 0, 0, 0, time.UTC))\n\n\tp.lock.RLock()\n\tdefer p.lock.RUnlock()\n\tif p.clients != nil {\n\t\tselect {\n\t\tcase p.clients <- client:\n\t\t\treturn\n\t\tdefault:\n\t\t\t//the pool reaches its capacity, drop the client on the floor\n\t\t\tclient.Close()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (p *Proxy) connectAndCopy(conn net.Conn, brw *bufio.ReadWriter, req *http.Request, reconnected bool) {\n\tlogger := req.Context().Value(LogEntryCtx).(*zap.Logger)\n\n\tretries := 0\nProxyDialRetry:\n\t// Open connection with downstream proxy\n\tpconn, err := net.DialTimeout(\"tcp\", p.config.DownstreamProxyURL.Host, p.config.Timeouts.DownstreamProxy.DialTimeout)\n\tif err != nil {\n\t\tif retries < p.config.DownstreamProxyDialRetries {\n\t\t\tlogger.Error(\"Connection to downstream proxy failed.\", zap.Error(err))\n\t\t\tretries++\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tlogger.Debug(\"Downstream proxy dial retry.\", zap.Int(\"retries\", retries))\n\n\t\t\tgoto ProxyDialRetry\n\t\t}\n\n\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"cannot connect to downstream proxy: %w\", err))\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err := pconn.Close(); err != nil {\n\t\t\tlogger.Error(\"Cannot close connection\", zap.Error(err))\n\t\t}\n\t}()\n\n\t// Set Keep-Alive\n\tif tconn, ok := pconn.(*net.TCPConn); ok {\n\t\tif err := tconn.SetKeepAlive(true); err != nil {\n\t\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"cannot turn on keep-alive: %w\", err))\n\t\t\treturn\n\t\t}\n\t\tif err := tconn.SetKeepAlivePeriod(p.config.Timeouts.DownstreamProxy.KeepAlivePeriod); err != nil {\n\t\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"cannot set keep-alive period: %w\", err))\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Set Downstream Proxy connection timeouts\n\tnow := time.Now()\n\tif p.config.Timeouts.DownstreamProxy.ReadTimeout.Nanoseconds() != 0 {\n\t\tif err := pconn.SetReadDeadline(now.Add(p.config.Timeouts.DownstreamProxy.ReadTimeout)); err != nil {\n\t\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"cannot set read timeout for connection with downstream proxy: %w\", err))\n\t\t\treturn\n\t\t}\n\t}\n\tif p.config.Timeouts.DownstreamProxy.WriteTimeout.Nanoseconds() != 0 {\n\t\tif err := pconn.SetWriteDeadline(now.Add(p.config.Timeouts.DownstreamProxy.WriteTimeout)); err != nil {\n\t\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"cannot set write timeout for connection with downstream proxy: %w\", err))\n\t\t\treturn\n\t\t}\n\t}\n\n\tpbw := bufio.NewWriter(pconn)\n\tpbr := bufio.NewReader(pconn)\n\n\t// Write client's request into proxy connection\n\tif err := req.Write(pbw); err != nil {\n\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"cannot write request into proxy connection: %w\", err))\n\t\treturn\n\t}\n\tif err := pbw.Flush(); err != nil {\n\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"cannot flush writer to commit request into proxy connection: %w\", err))\n\t\treturn\n\t}\n\n\t// Read response from body, usually it's just 407 Proxy Authentication Required\n\tresp, err := http.ReadResponse(pbr, req)\n\tif err != nil {\n\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"cannot read response from proxy connection: %w\", err))\n\t\treturn\n\t}\n\n\tswitch resp.StatusCode {\n\t// Proxy authentication required, we have to pass Proxy-Authorization header\n\tcase http.StatusProxyAuthRequired:\n\t\t// Close the body, no need to read it, there is only HTML template with Proxy warning\n\t\t//noinspection ALL\n\t\tresp.Body.Close()\n\n\t\t// Set Proxy-Authorization header\n\t\tif err := p.setProxyAuthorizationHeader(req); err != nil {\n\t\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"cannot set authrorization header: %w\", err))\n\t\t\treturn\n\t\t}\n\n\t\t// Write request into proxy connection again, now with proper auth\n\t\tif err := req.Write(pbw); err != nil {\n\t\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"cannot write request into proxy connection: %w\", err))\n\t\t\treturn\n\t\t}\n\t\tif err := pbw.Flush(); err != nil {\n\t\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"cannot flush writer to commit request into proxy connection: %w\", err))\n\t\t\treturn\n\t\t}\n\n\t\t// Read proxy response again, hope user credentials are valid and proxy returned 200\n\t\tresp, err = http.ReadResponse(pbr, req)\n\t\tif err != nil {\n\t\t\t// Some proxies drop connection after responding 407\n\t\t\tvar target *net.OpError\n\t\t\tif (errors.As(err, &target) || errors.Is(err, io.ErrUnexpectedEOF)) && !reconnected {\n\t\t\t\t// Reconnection could be tried only once to prevent infinity loop;\n\t\t\t\t// Proxy-Authorization header is already set, so we can try again;\n\t\t\t\tp.connectAndCopy(conn, brw, req, true)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"cannot read response from proxy connection: %w\", err))\n\t\t\treturn\n\t\t}\n\t\tif resp.StatusCode == http.StatusOK {\n\t\t\tresp.Body = nil\n\t\t} else {\n\t\t\tlogger.Warn(\"Proxy did NOT return 200 Connection established\", zap.Int(\"proxy_resp_code\", resp.StatusCode))\n\t\t}\n\n\t\t// Return this response to client\n\t\tif err := resp.Write(brw); err != nil {\n\t\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"cannot write response from proxy into client connection: %w\", err))\n\t\t\treturn\n\t\t}\n\t\tif err := brw.Flush(); err != nil {\n\t\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"cannot flush writer to commit response from proxy into client connection: %w\", err))\n\t\t\treturn\n\t\t}\n\t// 200 Connection established, we can immediately start data transfer\n\tcase http.StatusOK:\n\t\t// Set body to nil, otherwise we will get deadlock\n\t\tresp.Body = nil\n\n\t\t// Return this response to client\n\t\tif err := resp.Write(brw); err != nil {\n\t\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"cannot write response from proxy into client connection: %w\", err))\n\t\t\treturn\n\t\t}\n\t\tif err := brw.Flush(); err != nil {\n\t\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"cannot flush writer to commit response from proxy into client connection: %w\", err))\n\t\t\treturn\n\t\t}\n\tdefault:\n\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"unknown code recieved: %d\", resp.StatusCode))\n\t\treturn\n\t}\n\n\t// Start traffic copying inside newly created tunnel\n\terrc := make(chan error, 1)\n\tcc := connectCopier{\n\t\tlogger: logger,\n\t\tclient: conn,\n\t\tbackend: pconn,\n\t}\n\tgo cc.copyToBackend(errc)\n\tgo cc.copyFromBackend(errc)\n\n\tlogger.Debug(\"CONNECT tunnel opened\")\n\tdefer logger.Debug(\"CONNECT tunnel closed\")\n\n\terr = <-errc\n\tif err == nil {\n\t\terr = <-errc\n\t}\n\n\tif err != nil {\n\t\thttpsErrorHijackedHandler(brw, req, fmt.Errorf(\"traffic copying inside tunnel failed: %w\", err))\n\t\treturn\n\t}\n\n\tlogger.Debug(\"Traffic copied successfully\")\n}", "func getProxyURL() (bool, *url.URL) {\n\t// Grab the list of HTTP proxies from the configuration\n\tlog.Debug(\"Attempting to use one of the proxies defined in the configuration file\")\n\thttpProxyStringMap := viper.GetStringMap(\"HTTPProxies\")\n\n\t// This will be set to the URL to use or remain nil\n\tvar proxyURL *url.URL\n\n\t// Try each proxy and use it if it's available\n\tfor proxyAlias, httpProxy := range httpProxyStringMap {\n\t\tproxyURLString := httpProxy.(map[string]interface{})[\"proxyurl\"]\n\t\tif proxyURLString == nil {\n\t\t\tlog.Warnf(\"The proxy entry %s needs a ProxyURL in the configuration file: %s\", proxyAlias, httpProxy)\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Debugf(\"Checking access to proxy: %s\", proxyURLString)\n\n\t\tvar parseError error\n\t\tproxyURL, parseError = url.Parse(proxyURLString.(string))\n\t\tif parseError != nil {\n\t\t\tlog.Debugf(\"Skipping proxy URL that couldn't be parsed: %s\", parseError)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Get the proxy hostname\n\t\tproxyHost := proxyURL.Hostname()\n\n\t\t// Try looking up the hostname IP\n\t\tlog.Debugf(\"Looking up IP address for: %s\", proxyHost)\n\t\t_, lookupError := net.LookupHost(proxyHost)\n\t\tif lookupError != nil {\n\t\t\tlog.Debugf(\"Skipping proxy because the IP lookup failed: %s\", proxyHost)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Get the proxy hostname\n\t\tproxyPort := proxyURL.Port()\n\n\t\t// Try connecting to the proxy port\n\t\tlog.Debugf(\"Attempting to connect to %s on port %s\", proxyHost, proxyPort)\n\t\tconnection, dialError := net.Dial(\"tcp\", proxyHost+\":\"+proxyPort)\n\t\tif dialError != nil {\n\t\t\tlog.Debugf(\"Unable to connect to proxy %s on port %s\", proxyHost, proxyPort)\n\t\t\tcontinue\n\t\t}\n\t\terr := connection.Close()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Unable to close connection to proxy host: %s\", err)\n\t\t}\n\n\t\t// Set the no proxy based on this config... this may be futile, need more research\n\t\tnoProxy := httpProxy.(map[string]interface{})[\"noproxy\"]\n\t\tif noProxy != nil {\n\t\t\tlog.Debugf(\"Setting NO_PROXY to %s\", noProxy)\n\t\t\terr := os.Setenv(\"NO_PROXY\", noProxy.(string))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Unable to set NO_PROXY environment variable: %s\", err)\n\t\t\t}\n\t\t}\n\n\t\t// If we made it this far, the proxy is usable\n\t\tlog.Infof(\"Found a working proxy from the configuration file: %s on port %s\", proxyHost, proxyPort)\n\t\treturn true, proxyURL\n\t}\n\n\treturn false, proxyURL\n}", "func proxyOpen(item ProxyItem) bool {\n\tvar ipPort = fmt.Sprintf(\"%s:%d\", item.IP, item.Port)\n\t_, err := net.DialTimeout(\"tcp\", ipPort, time.Second)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func (r *RedisPool) GetConn() redis.Conn {\n\tif r.pool == nil {\n\t\tlog.Fatalln(errors.New(\"error get redis pool\"))\n\t}\n\treturn r.pool.Get()\n}", "func (pool *connectionPool) borrowConnection(addr string, timeout time.Duration) (*tlsConn, error) {\n\tpool.mtx.Lock()\n\tdefer pool.mtx.Unlock()\n\tif pool.cache == nil {\n\t\treturn nil, errors.New(\"connection pool closed\")\n\t}\n\tkey := fmt.Sprintf(\"%s/%d\", addr, int64(timeout))\n\tconn, exists := pool.cache.Get(key)\n\tif exists && conn.alive() {\n\t\treturn conn, nil\n\t}\n\tconn, err := dialTLSConn(addr, timeout, pool.tlsConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpool.cache.Add(key, conn)\n\treturn conn, nil\n}", "func (h *ProxyHandler) ReturnConn() {\n\th.connPoolCache.ReturnConn(h.currentDBName, h.remoteConn)\n}", "func GetConnection(requestPath string) (httpClient *http.Client, ok bool) {\n\trequestURL, err := url.Parse(requestPath)\n\tif err != nil {\n\t\treturn\n\t}\n\trequestHost := requestURL.Host\n\tconnectionPool.RLock()\n\texistingConn, ok := connectionPool.pool[requestHost]\n\tconnectionPool.RUnlock()\n\tif ok { //Get the existing connection in cache\n\t\treturn existingConn, true\n\t}\n\tok = false\n\treturn\n}", "func (clientSession *ClientCommandsSession) proxyConnections() {\n\treturn\n}", "func proxyTransport(p *transportParams) {\n\tdefer p.channel.Close()\n\n\t// Always push space into stderr to make sure the caller can always\n\t// safely call read (stderr) without blocking. This stderr is only used\n\t// to request proxying of TCP/IP via reverse tunnel.\n\tfmt.Fprint(p.channel.Stderr(), \" \")\n\n\t// Wait for a request to come in from the other side telling the server\n\t// where to dial to.\n\tvar req *ssh.Request\n\tselect {\n\tcase <-p.closeContext.Done():\n\t\treturn\n\tcase req = <-p.requestCh:\n\t\tif req == nil {\n\t\t\treturn\n\t\t}\n\tcase <-time.After(defaults.DefaultDialTimeout):\n\t\tp.log.Warnf(\"Transport request failed: timed out waiting for request.\")\n\t\treturn\n\t}\n\n\tserver := string(req.Payload)\n\tvar servers []string\n\n\t// Handle special non-resolvable addresses first.\n\tswitch server {\n\t// Connect to an Auth Server.\n\tcase RemoteAuthServer:\n\t\tauthServers, err := p.authClient.GetAuthServers()\n\t\tif err != nil {\n\t\t\tp.log.Errorf(\"Transport request failed: unable to get list of Auth Servers: %v.\", err)\n\t\t\treq.Reply(false, []byte(\"connection rejected: failed to connect to auth server\"))\n\t\t\treturn\n\t\t}\n\t\tif len(authServers) == 0 {\n\t\t\tp.log.Errorf(\"Transport request failed: no auth servers found.\")\n\t\t\treq.Reply(false, []byte(\"connection rejected: failed to connect to auth server\"))\n\t\t\treturn\n\t\t}\n\t\tfor _, as := range authServers {\n\t\t\tservers = append(servers, as.GetAddr())\n\t\t}\n\t// Connect to the Kubernetes proxy.\n\tcase RemoteKubeProxy:\n\t\tif p.component == teleport.ComponentReverseTunnelServer {\n\t\t\treq.Reply(false, []byte(\"connection rejected: no remote kubernetes proxy\"))\n\t\t\treturn\n\t\t}\n\n\t\t// If Kubernetes is not configured, reject the connection.\n\t\tif p.kubeDialAddr.IsEmpty() {\n\t\t\treq.Reply(false, []byte(\"connection rejected: configure kubernetes proxy for this cluster.\"))\n\t\t\treturn\n\t\t}\n\t\tservers = append(servers, p.kubeDialAddr.Addr)\n\t// LocalNode requests are for the single server running in the agent pool.\n\tcase LocalNode:\n\t\tif p.component == teleport.ComponentReverseTunnelServer {\n\t\t\treq.Reply(false, []byte(\"connection rejected: no local node\"))\n\t\t\treturn\n\t\t}\n\t\tif p.server == nil {\n\t\t\treq.Reply(false, []byte(\"connection rejected: server missing\"))\n\t\t\treturn\n\t\t}\n\t\tif p.sconn == nil {\n\t\t\treq.Reply(false, []byte(\"connection rejected: server connection missing\"))\n\t\t\treturn\n\t\t}\n\n\t\treq.Reply(true, []byte(\"Connected.\"))\n\n\t\t// Hand connection off to the SSH server.\n\t\tp.server.HandleConnection(utils.NewChConn(p.sconn, p.channel))\n\t\treturn\n\tdefault:\n\t\tservers = append(servers, server)\n\t}\n\n\tp.log.Debugf(\"Received out-of-band proxy transport request: %v\", servers)\n\n\t// Loop over all servers and try and connect to one of them.\n\tvar err error\n\tvar conn net.Conn\n\tfor _, s := range servers {\n\t\tconn, err = net.Dial(\"tcp\", s)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// Log the reason the connection failed.\n\t\tp.log.Debugf(trace.DebugReport(err))\n\t}\n\n\t// If all net.Dial attempts failed, write the last connection error to stderr\n\t// of the caller (via SSH channel) so the error will be propagated all the\n\t// way back to the client (tsh or ssh).\n\tif err != nil {\n\t\tfmt.Fprint(p.channel.Stderr(), err.Error())\n\t\treq.Reply(false, []byte(err.Error()))\n\t\treturn\n\t}\n\n\t// Dail was successful.\n\treq.Reply(true, []byte(\"Connected.\"))\n\tp.log.Debugf(\"Successfully dialed to %v, start proxying.\", server)\n\n\terrorCh := make(chan error, 2)\n\n\tgo func() {\n\t\t// Make sure that we close the client connection on a channel\n\t\t// close, otherwise the other goroutine would never know\n\t\t// as it will block on read from the connection.\n\t\tdefer conn.Close()\n\t\t_, err := io.Copy(conn, p.channel)\n\t\terrorCh <- err\n\t}()\n\n\tgo func() {\n\t\t_, err := io.Copy(p.channel, conn)\n\t\terrorCh <- err\n\t}()\n\n\tfor i := 0; i < 2; i++ {\n\t\tselect {\n\t\tcase err := <-errorCh:\n\t\t\tif err != nil && err != io.EOF {\n\t\t\t\tp.log.Warnf(\"Proxy transport failed: %v %T.\", trace.DebugReport(err), err)\n\t\t\t}\n\t\tcase <-p.closeContext.Done():\n\t\t\tp.log.Warnf(\"Proxy transport failed: closing context.\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func ConnectionPool(cfg *viper.Viper) *redis.Pool {\n\t// As per https://www.iana.org/assignments/uri-schemes/prov/redis\n\t// redis://user:secret@localhost:6379/0?foo=bar&qux=baz\n\n\t// Add redis user and password to connection url if they exist\n\tredisURL := \"redis://\"\n\tif cfg.IsSet(\"redis.user\") && cfg.GetString(\"redis.user\") != \"\" &&\n\t\tcfg.IsSet(\"redis.password\") && cfg.GetString(\"redis.password\") != \"\" {\n\t\tredisURL += cfg.GetString(\"redis.user\") + \":\" + cfg.GetString(\"redis.password\") + \"@\"\n\t}\n\tredisURL += cfg.GetString(\"redis.hostname\") + \":\" + cfg.GetString(\"redis.port\")\n\n\trhLog.WithFields(log.Fields{\"redisURL\": redisURL}).Debug(\"Attempting to connect to Redis\")\n\tpool := redis.Pool{\n\t\tMaxIdle: cfg.GetInt(\"redis.pool.maxIdle\"),\n\t\tMaxActive: cfg.GetInt(\"redis.pool.maxActive\"),\n\t\tIdleTimeout: cfg.GetDuration(\"redis.pool.idleTimeout\") * time.Second,\n\t\tDial: func() (redis.Conn, error) { return redis.DialURL(redisURL) },\n\t}\n\n\t// Sanity check that connection works before passing it back. Redigo\n\t// always returns a valid connection, and will just fail on the first\n\t// query: https://godoc.org/github.com/gomodule/redigo/redis#Pool.Get\n\tredisConn := pool.Get()\n\tdefer redisConn.Close()\n\t_, err := redisConn.Do(\"SELECT\", \"0\")\n\t// Encountered an issue getting a connection from the pool.\n\tif err != nil {\n\t\trhLog.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t\t\"query\": \"SELECT 0\"}).Error(\"state storage connection error\")\n\t\treturn nil\n\t}\n\n\trhLog.Info(\"Connected to Redis\")\n\treturn &pool\n}", "func GetPool() *radix.Pool {\n\tpool, err := radix.NewPool(\"tcp\", os.Getenv(\"ERU_SE_REDIS_IP\"), 10)\n\tif err != nil {\n\t\tprintln(err)\n\t\tpanic(err)\n\t} else {\n\t\treturn pool\n\t}\n}", "func Proxy(port string, dest *net.TCPAddr) *net.TCPAddr {\n\tlistener, addr := Listen(\"proxy for \"+dest.String(), port)\n\tif addr == nil {\n\t\treturn nil // error already logged\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tconn, err := listener.Accept()\n\t\t\tif err != nil {\n\t\t\t\tlog.Critf(\"Proxy: error accepting: %v\", err) // will this loop with error?\n\t\t\t} else {\n\t\t\t\ttcpConn := conn.(*net.TCPConn)\n\t\t\t\tlog.LogVf(\"Proxy: Accepted proxy connection from %v -> %v (for listener %v)\",\n\t\t\t\t\tconn.RemoteAddr(), conn.LocalAddr(), dest)\n\t\t\t\t// TODO limit number of go request, use worker pool, etc...\n\t\t\t\tgo handleProxyRequest(tcpConn, dest)\n\t\t\t}\n\t\t}\n\t}()\n\treturn addr\n}", "func (r *Random) Next() (*proxy.Proxy, error) {\n\tif r.proxies.Len() > 0 {\n\t\tn := rand.Intn(r.proxies.Len())\n\t\treturn getAvailableProxy(r.proxies, n)\n\t}\n\treturn nil, fmt.Errorf(\"no proxies set\")\n}", "func (p *TCPProxy) Close() error {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tp.closed = true\n\tp.listener.Close()\n\tfor _, c := range p.conns {\n\t\tc.Close()\n\t}\n\treturn nil\n}", "func (proxy *UnixProxy) Close() { proxy.listener.Close() }", "func (n *BufferedNetpool) Close(conn NetpoolConnInterface) error {\n\t//n.closeLock.Lock()\n\t//defer n.closeLock.Unlock()\n\tif atomic.LoadInt32(&n.didclose) == 0 {\n\t\treturn n.pool.Close(conn)\n\t}\n\treturn nil\n}", "func (p *connPool) First() *conn {\n\tfor {\n\t\tselect {\n\t\tcase cn := <-p.freeConns:\n\t\t\tif p.isIdle(cn) {\n\t\t\t\tvar err error\n\t\t\t\tcn, err = p.replace(cn)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"redis: replace failed: %s\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn cn\n\t\tdefault:\n\t\t\treturn nil\n\t\t}\n\t}\n\tpanic(\"not reached\")\n}", "func newPool(addr string) *redis.Pool {\n\tp := &redis.Pool{\n\t\tMaxIdle: 3,\n\t\tIdleTimeout: 240 * time.Second,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\t/*c, err := redis.Dial(\"tcp\", addr)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error in connecting to Redis: %v\", err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tlog.Printf(\"Connected!\")\n\t\t\treturn c, nil\n\t\t\t*/\n\t\t\treturn redis.Dial(\"tcp\", addr)\n\t\t},\n\t}\n\treturn p\n}", "func makeHTTPClient(proxyURL *url.URL, options *HTTPOptions) *retryablehttp.Client {\n\t// Multiple Host\n\tretryablehttpOptions := retryablehttp.DefaultOptionsSpraying\n\tdisableKeepAlives := true\n\tmaxIdleConns := 0\n\tmaxConnsPerHost := 0\n\tmaxIdleConnsPerHost := -1\n\n\tif options.BulkHTTPRequest.Threads > 0 {\n\t\t// Single host\n\t\tretryablehttpOptions = retryablehttp.DefaultOptionsSingle\n\t\tdisableKeepAlives = false\n\t\tmaxIdleConnsPerHost = 500\n\t\tmaxConnsPerHost = 500\n\t}\n\n\tretryablehttpOptions.RetryWaitMax = 10 * time.Second\n\tretryablehttpOptions.RetryMax = options.Retries\n\tfollowRedirects := options.BulkHTTPRequest.Redirects\n\tmaxRedirects := options.BulkHTTPRequest.MaxRedirects\n\n\ttransport := &http.Transport{\n\t\tDialContext: options.Dialer.Dial,\n\t\tMaxIdleConns: maxIdleConns,\n\t\tMaxIdleConnsPerHost: maxIdleConnsPerHost,\n\t\tMaxConnsPerHost: maxConnsPerHost,\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tRenegotiation: tls.RenegotiateOnceAsClient,\n\t\t\tInsecureSkipVerify: true,\n\t\t},\n\t\tDisableKeepAlives: disableKeepAlives,\n\t}\n\n\t// Attempts to overwrite the dial function with the socks proxied version\n\tif options.ProxySocksURL != \"\" {\n\t\tvar proxyAuth *proxy.Auth\n\n\t\tsocksURL, err := url.Parse(options.ProxySocksURL)\n\n\t\tif err == nil {\n\t\t\tproxyAuth = &proxy.Auth{}\n\t\t\tproxyAuth.User = socksURL.User.Username()\n\t\t\tproxyAuth.Password, _ = socksURL.User.Password()\n\t\t}\n\n\t\tdialer, err := proxy.SOCKS5(\"tcp\", fmt.Sprintf(\"%s:%s\", socksURL.Hostname(), socksURL.Port()), proxyAuth, proxy.Direct)\n\t\tdc := dialer.(interface {\n\t\t\tDialContext(ctx context.Context, network, addr string) (net.Conn, error)\n\t\t})\n\n\t\tif err == nil {\n\t\t\ttransport.DialContext = dc.DialContext\n\t\t}\n\t}\n\n\tif proxyURL != nil {\n\t\ttransport.Proxy = http.ProxyURL(proxyURL)\n\t}\n\n\treturn retryablehttp.NewWithHTTPClient(&http.Client{\n\t\tTransport: transport,\n\t\tTimeout: time.Duration(options.Timeout) * time.Second,\n\t\tCheckRedirect: makeCheckRedirectFunc(followRedirects, maxRedirects),\n\t}, retryablehttpOptions)\n}", "func (poolConn *PoolConn) Close() error {\n\tpoolConn.mu.RLock()\n\tdefer poolConn.mu.RUnlock()\n\n\treturn poolConn.pool.Return(poolConn.Conn)\n}", "func (p *Pool) Close() {\n\tp.stopOnce.Do(func() {\n\t\tclose(p.stopCh)\n\n\t\tvar conn *redis.Client\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase conn = <-p.pool:\n\t\t\t\tconn.Close()\n\t\t\tdefault:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t})\n}", "func GetRedisPool(cfg config.View) *redis.Pool {\n\tvar dialFunc func(context.Context) (redis.Conn, error)\n\tmaxIdle := cfg.GetInt(\"redis.pool.maxIdle\")\n\tmaxActive := cfg.GetInt(\"redis.pool.maxActive\")\n\tidleTimeout := cfg.GetDuration(\"redis.pool.idleTimeout\")\n\n\tif cfg.IsSet(\"redis.sentinelHostname\") {\n\t\tsentinelPool := getSentinelPool(cfg)\n\t\tdialFunc = func(ctx context.Context) (redis.Conn, error) {\n\t\t\tif ctx.Err() != nil {\n\t\t\t\treturn nil, ctx.Err()\n\t\t\t}\n\n\t\t\tsentinelConn, err := sentinelPool.GetContext(ctx)\n\t\t\tif err != nil {\n\t\t\t\tredisLogger.WithFields(logrus.Fields{\n\t\t\t\t\t\"error\": err.Error(),\n\t\t\t\t}).Error(\"failed to connect to redis sentinel\")\n\t\t\t\treturn nil, status.Errorf(codes.Unavailable, \"%v\", err)\n\t\t\t}\n\n\t\t\tmasterInfo, err := redis.Strings(sentinelConn.Do(\"SENTINEL\", \"GET-MASTER-ADDR-BY-NAME\", cfg.GetString(\"redis.sentinelMaster\")))\n\t\t\tif err != nil {\n\t\t\t\tredisLogger.WithFields(logrus.Fields{\n\t\t\t\t\t\"error\": err.Error(),\n\t\t\t\t}).Error(\"failed to get current master from redis sentinel\")\n\t\t\t\treturn nil, status.Errorf(codes.Unavailable, \"%v\", err)\n\t\t\t}\n\n\t\t\tmasterURL := redisURLFromAddr(fmt.Sprintf(\"%s:%s\", masterInfo[0], masterInfo[1]), cfg, cfg.GetBool(\"redis.usePassword\"))\n\t\t\treturn redis.DialURL(masterURL, redis.DialConnectTimeout(idleTimeout), redis.DialReadTimeout(idleTimeout))\n\t\t}\n\t} else {\n\t\tmasterAddr := getMasterAddr(cfg)\n\t\tmasterURL := redisURLFromAddr(masterAddr, cfg, cfg.GetBool(\"redis.usePassword\"))\n\t\tdialFunc = func(ctx context.Context) (redis.Conn, error) {\n\t\t\tif ctx.Err() != nil {\n\t\t\t\treturn nil, ctx.Err()\n\t\t\t}\n\t\t\treturn redis.DialURL(masterURL, redis.DialConnectTimeout(idleTimeout), redis.DialReadTimeout(idleTimeout))\n\t\t}\n\t}\n\n\treturn &redis.Pool{\n\t\tMaxIdle: maxIdle,\n\t\tMaxActive: maxActive,\n\t\tIdleTimeout: idleTimeout,\n\t\tWait: true,\n\t\tTestOnBorrow: testOnBorrow,\n\t\tDialContext: dialFunc,\n\t}\n}", "func putGetDelWorker(proxyURL string, stopCh <-chan struct{}, proxyURLCh <-chan string, errCh chan error,\n\twg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\tmissedDeleteCh := make(chan string, 100)\n\tbaseParams := tutils.BaseAPIParams(proxyURL)\n\n\tbck := cmn.Bck{\n\t\tName: testBucketName,\n\t\tProvider: cmn.ProviderAIS,\n\t}\n\tcksumType := cmn.DefaultBckProps(bck).Cksum.Type\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-stopCh:\n\t\t\tclose(errCh)\n\t\t\tbreak loop\n\n\t\tcase url := <-proxyURLCh:\n\t\t\t// send failed deletes to the new primary proxy\n\t\tdeleteLoop:\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase objName := <-missedDeleteCh:\n\t\t\t\t\terr := tutils.Del(url, bck, objName, nil, errCh, true)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tmissedDeleteCh <- objName\n\t\t\t\t\t}\n\n\t\t\t\tdefault:\n\t\t\t\t\tbreak deleteLoop\n\t\t\t\t}\n\t\t\t}\n\n\t\tdefault:\n\t\t}\n\n\t\treader, err := readers.NewRandReader(fileSize, cksumType)\n\t\tif err != nil {\n\t\t\terrCh <- err\n\t\t\tcontinue\n\t\t}\n\n\t\tfname := cos.RandString(20)\n\t\tobjName := fmt.Sprintf(\"%s/%s\", localBucketDir, fname)\n\t\tputArgs := api.PutObjectArgs{\n\t\t\tBaseParams: baseParams,\n\t\t\tBck: bck,\n\t\t\tObject: objName,\n\t\t\tCksum: reader.Cksum(),\n\t\t\tReader: reader,\n\t\t}\n\t\terr = api.PutObject(putArgs)\n\t\tif err != nil {\n\t\t\terrCh <- err\n\t\t\tcontinue\n\t\t}\n\t\t_, err = api.GetObject(baseParams, bck, objName)\n\t\tif err != nil {\n\t\t\terrCh <- err\n\t\t}\n\n\t\terr = tutils.Del(proxyURL, bck, objName, nil, errCh, true)\n\t\tif err != nil {\n\t\t\tmissedDeleteCh <- objName\n\t\t}\n\t}\n\n\t// process left over not deleted objects\n\tclose(missedDeleteCh)\n\tfor n := range missedDeleteCh {\n\t\ttutils.Del(proxyURL, bck, n, nil, nil, true)\n\t}\n}", "func (p *Proxy) Close() error {\n\terr := p.Proxy.Close()\n\n\tp.Proxy = nil\n\n\tp.CloseConnections()\n\n\treturn err\n}", "func (p *connPool) Purge() {\n\tdpiPool := p.dpiPool\n\tp.dpiPool = nil\n\tif dpiPool != nil {\n\t\tC.dpiPool_close(dpiPool, C.DPI_MODE_POOL_CLOSE_FORCE)\n\t}\n}", "func Proxy(req Request) error {\n\tlocal := fmt.Sprintf(\"localhost:%d\", req.LocalPort)\n\tremote := fmt.Sprintf(\"%s:%d\", req.RemoteIP, req.RemotePort)\n\n\tklog.Infof(\"start reverse-proxy %s->%s\", local, remote)\n\n\tlistener, err := net.Listen(\"tcp\", local)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdone := false\n\tgo func() {\n\t\t<-req.StopCh\n\t\tklog.Infof(\"stopped reverse-proxy %s->%s\", local, remote)\n\t\tdone = true\n\t\tlistener.Close()\n\t}()\n\n\tgo func() {\n\t\tfor {\n\t\t\tif done {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconn, err := listener.Accept()\n\t\t\tif err != nil {\n\t\t\t\tif !done {\n\t\t\t\t\tklog.Warningf(\"error accepting connection: %s\", err)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgo func() {\n\t\t\t\tconn2, err := net.DialTimeout(\"tcp\", remote, req.TimeOut)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Warningf(\"error dialing remote addr: %s\", err)\n\t\t\t\t\tconn.Close()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tgo io.Copy(conn2, conn)\n\t\t\t\tio.Copy(conn, conn2)\n\t\t\t\tconn2.Close()\n\t\t\t\tconn.Close()\n\t\t\t}()\n\t\t}\n\t}()\n\treturn nil\n}", "func (b *Botanist) WaitUntilTunnelConnectionExists(ctx context.Context) error {\n\treturn retry.UntilTimeout(ctx, 5*time.Second, 900*time.Second, func(ctx context.Context) (done bool, err error) {\n\t\ttunnelName := common.VPNTunnel\n\t\tif b.Shoot.KonnectivityTunnelEnabled {\n\t\t\ttunnelName = common.KonnectivityTunnel\n\t\t}\n\n\t\treturn b.CheckTunnelConnection(ctx, b.Logger, tunnelName)\n\t})\n}", "func (bcp *basicClientPool) Get(url, authType, accessCredential string, skipCertVerify bool) (Client, error) {\n\tk := fmt.Sprintf(\"%s:%s:%s:%v\", url, authType, accessCredential, skipCertVerify)\n\n\titem, ok := bcp.pool.Load(k)\n\tif !ok {\n\t\tnc, err := NewClient(url, authType, accessCredential, skipCertVerify)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"client pool: get\")\n\t\t}\n\n\t\t// Cache it\n\t\tnpi := &poolItem{\n\t\t\tc: nc,\n\t\t\ttimestamp: time.Now().UTC(),\n\t\t}\n\n\t\tbcp.pool.Store(k, npi)\n\t\titem = npi\n\n\t\t// dead check\n\t\tbcp.deadCheck(k, npi)\n\t}\n\n\treturn item.(*poolItem).c, nil\n}", "func WaitForProxyEndpoints(s rpc.Server, proxyName string) rpc.ServerStatus {\n\tfor {\n\t\tstatus := s.Status()\n\t\tif err, ok := status.ProxyErrors[proxyName]; ok && err == nil {\n\t\t\treturn status\n\t\t}\n\t\t<-status.Dirty\n\t}\n}", "func (p *connPool) get(params planetscalev2.VitessLockserverParams) *Conn {\n\tpool.mapMu.Lock()\n\tdefer pool.mapMu.Unlock()\n\n\tconn := p.conns[params]\n\tif conn != nil {\n\t\tif conn.failed() {\n\t\t\t// If the connect attempt failed, remove it and pretend it wasn't found.\n\t\t\tdelete(p.conns, params)\n\t\t\tconn = nil\n\t\t} else if conn.succeeded() {\n\t\t\tcacheHits.Inc()\n\t\t\t// Every time we fetch a cached conn, we also check if the connection is\n\t\t\t// still alive. We do this asynchronously because we need a long timeout to\n\t\t\t// avoid false negatives, but we don't want to hold up the caller.\n\t\t\tgo p.checkConn(params)\n\t\t}\n\t}\n\tif conn == nil {\n\t\tcacheMisses.Inc()\n\t\t// Start a new connection attempt.\n\t\tconn = newConn(params)\n\t\tp.conns[params] = conn\n\t}\n\treturn conn\n}", "func (c *Client) GetPool(name string) (p Pool, err error) {\n\tvar poolURI string\n\n\tfor _, p := range c.Info.Pools {\n\t\tif p.Name == name {\n\t\t\tpoolURI = p.URI\n\t\t\tbreak\n\t\t}\n\t}\n\tif poolURI == \"\" {\n\t\treturn p, errors.New(\"No pool named \" + name)\n\t}\n\n\terr = c.parseURLResponse(poolURI, &p)\n\n\tp.client = c\n\n\terr = p.refresh()\n\treturn\n}", "func proxyCrash(t *testing.T) {\n\tproxyURL := tutils.RandomProxyURL(t)\n\tsmap := tutils.GetClusterMap(t, proxyURL)\n\ttlog.Logf(\"targets: %d, proxies: %d\\n\", smap.CountActiveTargets(), smap.CountActiveProxies())\n\n\tprimaryURL, primaryID := smap.Primary.URL(cmn.NetworkPublic), smap.Primary.ID()\n\ttlog.Logf(\"Primary proxy: %s\\n\", primaryURL)\n\n\tvar (\n\t\tsecondURL string\n\t\tsecondID string\n\t\tsecondNode *cluster.Snode\n\t\torigProxyCount = smap.CountActiveProxies()\n\t)\n\n\t// Select a random non-primary proxy\n\tfor k, v := range smap.Pmap {\n\t\tif k != primaryID {\n\t\t\tsecondURL = v.URL(cmn.NetworkPublic)\n\t\t\tsecondID = v.ID()\n\t\t\tsecondNode = v\n\t\t\tbreak\n\t\t}\n\t}\n\n\ttlog.Logf(\"Killing non-primary proxy: %s - %s\\n\", secondURL, secondID)\n\tsecondCmd, err := tutils.KillNode(secondNode)\n\ttassert.CheckFatal(t, err)\n\n\tsmap, err = tutils.WaitForClusterState(primaryURL, \"propagate new Smap\",\n\t\tsmap.Version, origProxyCount-1, 0)\n\ttassert.CheckFatal(t, err)\n\n\terr = tutils.RestoreNode(secondCmd, false, \"proxy\")\n\ttassert.CheckFatal(t, err)\n\n\tsmap, err = tutils.WaitForClusterState(primaryURL, \"restore\", smap.Version, origProxyCount, 0)\n\ttassert.CheckFatal(t, err)\n\n\tif _, ok := smap.Pmap[secondID]; !ok {\n\t\tt.Fatalf(\"Non-primary proxy did not rejoin the cluster.\")\n\t}\n}", "func (conn *Tunnel) requestConn() (err error) {\n\n\thostInfo, err := conn.hostInfo()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconn.control = hostInfo\n\n\treq := &knxnet.ConnReq{\n\t\tLayer: conn.layer,\n\t\tControl: conn.control,\n\t\tTunnel: conn.control,\n\t}\n\n\t// Send the initial request.\n\terr = conn.sock.Send(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Create a resend timer.\n\tticker := time.NewTicker(conn.config.ResendInterval)\n\tdefer ticker.Stop()\n\n\t// Setup timeout.\n\ttimeout := time.After(conn.config.ResponseTimeout)\n\n\t// Cycle until a request gets a response.\n\tfor {\n\t\tselect {\n\t\t// Timeout reached.\n\t\tcase <-timeout:\n\t\t\treturn errResponseTimeout\n\n\t\t// Resend timer triggered.\n\t\tcase <-ticker.C:\n\t\t\terr = conn.sock.Send(req)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t// A message has been received or the channel has been closed.\n\t\tcase msg, open := <-conn.sock.Inbound():\n\t\t\tif !open {\n\t\t\t\treturn errors.New(\"socket's inbound channel has been closed\")\n\t\t\t}\n\n\t\t\t// We're only interested in connection responses.\n\t\t\tif res, ok := msg.(*knxnet.ConnRes); ok {\n\t\t\t\tswitch res.Status {\n\t\t\t\t// Conection has been established.\n\t\t\t\tcase knxnet.NoError:\n\t\t\t\t\tconn.channel = res.Channel\n\n\t\t\t\t\tconn.seqMu.Lock()\n\t\t\t\t\tconn.seqNumber = 0\n\t\t\t\t\tconn.seqMu.Unlock()\n\n\t\t\t\t\treturn nil\n\n\t\t\t\t// The gateway is busy, but we don't stop yet.\n\t\t\t\tcase knxnet.ErrNoMoreConnections, knxnet.ErrNoMoreUniqueConnections:\n\t\t\t\t\tcontinue\n\n\t\t\t\t// Connection request has been denied.\n\t\t\t\tdefault:\n\t\t\t\t\treturn res.Status\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (nc *NoiseClient) connClosed(id int) {\n\tnc.mu.Lock()\n\tdefer nc.mu.Unlock()\n\tconn := nc.connPool[id]\n\tif conn != nil {\n\t\tdelete(nc.connPool, id)\n\t\tif nc.last == conn {\n\t\t\tnc.last = nil\n\t\t}\n\t}\n}", "func (s *Set) Remove(proxy Proxy) {\n\ts.m.Lock()\n\n\tdelete(s.proxies, proxy)\n\ts.m.Unlock()\n}", "func (c *connPool) GetFromPool() interface{} {\n\tdefer c.nextMutex.Unlock()\n\tc.nextMutex.Lock()\n\tif c.total == 0 {\n\t\treturn nil\n\t}\n\tc.next = (c.next + 1) % c.total\n\treturn c.pool[c.next]\n}", "func (p PgxWrapper) GetConn(ctx context.Context) (*pgx.Conn, error) {\n\tconn, err := p.pool.Acquire(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not acquire connection: %w\", err)\n\t}\n\treturn conn.Conn(), nil\n}", "func (pool *Pool) Do(p *Pipeline, r *resp.Reply) error {\n\tconn, err := pool.Get()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = conn.Do(p, r)\n\tpool.Put(conn)\n\treturn err\n}", "func TestDialProxy(t *testing.T) {\n\tctx := context.Background()\n\tdest := \"remote-ip:3080\"\n\n\ttlsConfig, err := fixtures.LocalTLSConfig()\n\trequire.NoError(t, err)\n\n\tcases := []struct {\n\t\tproxy func(chan error, net.Listener, *tls.Config)\n\t\tscheme string\n\t\tassertDial require.ErrorAssertionFunc\n\t}{\n\t\t{\n\t\t\tproxy: serveSOCKSProxy,\n\t\t\tscheme: \"socks5\",\n\t\t\tassertDial: require.NoError,\n\t\t},\n\t\t{\n\t\t\tproxy: serveHTTPProxy,\n\t\t\tscheme: \"http\",\n\t\t\tassertDial: require.NoError,\n\t\t},\n\t\t{\n\t\t\tproxy: serveHTTPProxy,\n\t\t\tscheme: \"https\",\n\t\t\tassertDial: require.NoError,\n\t\t},\n\t\t{\n\t\t\tproxy: func(errChan chan error, l net.Listener, _ *tls.Config) { close(errChan) },\n\t\t\tscheme: \"unknown\",\n\t\t\tassertDial: require.Error,\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.scheme, func(t *testing.T) {\n\t\t\terrChan := make(chan error, 1)\n\t\t\tl, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\t\t\trequire.NoError(t, err)\n\n\t\t\tt.Cleanup(func() {\n\t\t\t\trequire.NoError(t, l.Close())\n\t\t\t\terr := <-errChan\n\t\t\t\trequire.NoError(t, err)\n\t\t\t})\n\n\t\t\tvar serverTLSConfig *tls.Config\n\t\t\tif tc.scheme == \"https\" {\n\t\t\t\tserverTLSConfig = tlsConfig.TLS\n\t\t\t}\n\t\t\tgo tc.proxy(errChan, l, serverTLSConfig)\n\n\t\t\tproxyURL, err := url.Parse(tc.scheme + \"://\" + l.Addr().String())\n\t\t\trequire.NoError(t, err)\n\n\t\t\tpool := x509.NewCertPool()\n\t\t\tpool.AddCert(tlsConfig.Certificate)\n\t\t\tclientTLSConfig := &tls.Config{\n\t\t\t\tRootCAs: pool,\n\t\t\t}\n\n\t\t\tconn, err := client.DialProxy(ctx, proxyURL, dest, client.WithTLSConfig(clientTLSConfig))\n\t\t\ttc.assertDial(t, err)\n\n\t\t\tif conn != nil {\n\t\t\t\tresult := make([]byte, len(dest))\n\t\t\t\t_, err = io.ReadFull(conn, result)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.Equal(t, string(result), dest)\n\t\t\t}\n\t\t})\n\t}\n}", "func newPool(addr string) (*pool, error) {\n\tp := pool{redis.Pool{\n\t\tMaxActive: 100,\n\t\tWait: true,\n\t\tMaxIdle: 10,\n\t\tIdleTimeout: 240 * time.Second,\n\t\tDial: func() (redis.Conn, error) { return redis.Dial(\"tcp\", addr) },\n\t}}\n\n\t// Test connection\n\tconn := p.Get()\n\tdefer conn.Close()\n\n\t_, err := conn.Do(\"PING\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &p, nil\n}", "func (p *dnsOverTLS) conn() (conn net.Conn, err error) {\n\t// Dial a new connection outside the lock, if needed.\n\tdefer func() {\n\t\tif conn == nil {\n\t\t\tconn, err = p.dial()\n\t\t}\n\t}()\n\n\tp.connsMu.Lock()\n\tdefer p.connsMu.Unlock()\n\n\tl := len(p.conns)\n\tif l == 0 {\n\t\treturn nil, nil\n\t}\n\n\tp.conns, conn = p.conns[:l-1], p.conns[l-1]\n\n\terr = conn.SetDeadline(time.Now().Add(dialTimeout))\n\tif err != nil {\n\t\tlog.Debug(\"dot upstream: setting deadline to conn from pool: %s\", err)\n\n\t\t// If deadLine can't be updated it means that connection was already\n\t\t// closed.\n\t\treturn nil, nil\n\t}\n\n\tlog.Debug(\"dot upstream: using existing conn %s\", conn.RemoteAddr())\n\n\treturn conn, nil\n}", "func Proxy(redirection string) error {\n\t// Connect to the sink\n\n\tif err := connectToSink(redirection); err != nil {\n\t\treturn err\n\t}\n\tlog.Lvl2(\"Proxy connected to sink\", redirection)\n\n\t// The proxy listens on the port one lower than itself\n\t_, port, err := net.SplitHostPort(redirection)\n\tif err != nil {\n\t\tlog.Fatal(\"Couldn't get port-numbre from\", redirection)\n\t}\n\tportNbr, err := strconv.Atoi(port)\n\tif err != nil {\n\t\tlog.Fatal(\"Couldn't convert\", port, \"to a number\")\n\t}\n\tsinkAddr := Sink + \":\" + strconv.Itoa(portNbr-1)\n\tln, err := net.Listen(\"tcp\", sinkAddr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error while binding proxy to addr %s: %v\", sinkAddr, err)\n\t}\n\tlog.Lvl2(\"Proxy listening on\", sinkAddr)\n\tnewConn := make(chan bool)\n\tcloseConn := make(chan bool)\n\tfinished := false\n\tproxyConns := make(map[string]*json.Encoder)\n\n\t// Listen for incoming connections\n\tgo func() {\n\t\tfor finished == false {\n\t\t\tconn, err := ln.Accept()\n\t\t\tif err != nil {\n\t\t\t\toperr, ok := err.(*net.OpError)\n\t\t\t\t// the listener is closed\n\t\t\t\tif ok && operr.Op == \"accept\" {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tlog.Lvl1(\"Error proxy accepting connection:\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.Lvl3(\"Proxy accepting incoming connection from:\", conn.RemoteAddr().String())\n\t\t\tnewConn <- true\n\t\t\tproxyConns[conn.RemoteAddr().String()] = json.NewEncoder(conn)\n\t\t\tgo proxyConnection(conn, closeConn)\n\t\t}\n\t}()\n\n\tgo func() {\n\t\t// notify every new connection and every end of connection. When all\n\t\t// connections are closed, send an \"end\" measure to the sink.\n\t\tvar nconn int\n\t\tfor finished == false {\n\t\t\tselect {\n\t\t\tcase <-newConn:\n\t\t\t\tnconn++\n\t\t\tcase <-closeConn:\n\t\t\t\tnconn--\n\t\t\t\tif nconn == 0 {\n\t\t\t\t\t// everything is finished\n\t\t\t\t\tif err := serverEnc.Encode(newSingleMeasure(\"end\", 0)); err != nil {\n\t\t\t\t\t\tlog.Error(\"Couldn't send 'end' message:\", err)\n\t\t\t\t\t}\n\t\t\t\t\tif err := serverConn.Close(); err != nil {\n\t\t\t\t\t\tlog.Error(\"Couldn't close server connection:\", err)\n\t\t\t\t\t}\n\t\t\t\t\tif err := ln.Close(); err != nil {\n\t\t\t\t\t\tlog.Error(\"Couldn't close listener:\", err)\n\t\t\t\t\t}\n\t\t\t\t\tfinished = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\treturn nil\n}", "func Proxy(options ...Option) http.RoundTripper {\n\tp := &proxy{\n\t\tnext: http.DefaultTransport,\n\t\tscheme: \"http\",\n\t\tresolver: resolve.ResolverFunc(resolve.DNSSRV),\n\t\tpoolReporter: nil,\n\t\tfactory: pool.RoundRobin,\n\t\tregistry: nil,\n\t}\n\tp.setOptions(options...)\n\tp.registry = newRegistry(p.resolver, p.poolReporter, p.factory)\n\treturn p\n}", "func (m *ClientPool) Get(addr string) rpcClient {\n\tfun := \"ClientPool.Get -->\"\n\n\tpo := m.getPool(addr)\n\tvar c rpcClient\n\tselect {\n\tcase c = <-po:\n\t\tslog.Tracef(\"%s get: %s len:%d\", fun, addr, len(po))\n\tdefault:\n\t\tc = m.Factory(addr)\n\t}\n\treturn c\n}", "func (p *grpcSocketProxy) stop() error {\n\tp.cancel()\n\n\t// If proxy was never run, don't wait for anything to shutdown.\n\tif !p.runOnce {\n\t\treturn nil\n\t}\n\n\tselect {\n\tcase <-p.doneCh:\n\t\treturn nil\n\tcase <-time.After(socketProxyStopWaitTime):\n\t\treturn errSocketProxyTimeout\n\t}\n}", "func (p *MultiProxy) Handle(c net.Conn) (net.Conn, error) {\n\treturn nil, proxy(c, p.proto, p.dest)\n}", "func (c *ChannelPool) Close(conn interface{}) error {\n\tif conn == nil {\n\t\treturn nil\n\t}\n\treturn c.close(conn)\n}", "func GetConnection() redis.Conn {\n\treturn pool.Get()\n}", "func GetConnection() redis.Conn {\n\treturn pool.Get()\n}" ]
[ "0.6022615", "0.60019463", "0.5842775", "0.58329505", "0.5832659", "0.5711125", "0.55737877", "0.55508256", "0.5519788", "0.55154026", "0.5507154", "0.5496575", "0.54928315", "0.5485385", "0.5482652", "0.54800826", "0.5476584", "0.54401356", "0.5434093", "0.54271895", "0.54167473", "0.5403836", "0.53870916", "0.53748804", "0.5363165", "0.53494644", "0.5317859", "0.53120947", "0.5270646", "0.5259981", "0.5228474", "0.52144986", "0.5210345", "0.5196924", "0.5189105", "0.5169076", "0.5168541", "0.5163318", "0.5161938", "0.5131019", "0.51277936", "0.51247567", "0.5100756", "0.50861436", "0.50790036", "0.5071976", "0.50558275", "0.5051051", "0.50374085", "0.502987", "0.5029115", "0.5028271", "0.5022137", "0.5008044", "0.5001138", "0.49967277", "0.49930283", "0.4992676", "0.49887833", "0.49747795", "0.49617386", "0.49598226", "0.49525085", "0.4943139", "0.4941091", "0.4940412", "0.49366292", "0.49345037", "0.4932076", "0.49289495", "0.4926736", "0.49233022", "0.4920163", "0.4904915", "0.4899617", "0.48919427", "0.4889682", "0.48880088", "0.48863092", "0.48841882", "0.4881583", "0.48769215", "0.4871033", "0.48632848", "0.48615226", "0.4843206", "0.48423335", "0.4838242", "0.48370588", "0.4835721", "0.48355892", "0.4831911", "0.48251194", "0.4824782", "0.48168385", "0.48147777", "0.48055828", "0.48050293", "0.48014203", "0.48014203" ]
0.67896104
0
Up20200929144301 adds Visual Studio Code as a workspace template.
func Up20200929144301(tx *sql.Tx) error { client, err := getClient() if err != nil { return err } defer client.DB.Close() migrationsRan, err := getRanSQLMigrations(client) if err != nil { return err } if _, ok := migrationsRan[20200929144301]; ok { return nil } namespaces, err := client.ListOnepanelEnabledNamespaces() if err != nil { return err } workspaceTemplate := &v1.WorkspaceTemplate{ Name: vscodeWorkspaceTemplateName, Manifest: vscodeWorkspaceTemplate, } // Adding description workspaceTemplate.Description = "Open source code editor" for _, namespace := range namespaces { if _, err := client.CreateWorkspaceTemplate(namespace.Name, workspaceTemplate); err != nil { return err } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func createWorkspace(client secrethub.ClientInterface, io ui.IO, org string, orgDescription string, progressPrinter progress.Printer) error {\n\tif org == \"\" {\n\t\tcreateWorkspace, err := ui.AskYesNo(io, \"Do you want to create a shared workspace for your team?\", ui.DefaultYes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Fprintln(io.Output())\n\t\tif !createWorkspace {\n\t\t\tfmt.Fprint(io.Output(), \"You can create a shared workspace later using `secrethub org init`.\\n\\n\")\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tvar err error\n\tif org == \"\" {\n\t\torg, err = ui.AskAndValidate(io, \"Workspace name (e.g. your company name): \", 2, api.ValidateOrgName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif orgDescription == \"\" {\n\t\torgDescription, err = ui.AskAndValidate(io, \"A description (max 144 chars) for your team workspace so others will recognize it:\\n\", 2, api.ValidateOrgDescription)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfmt.Fprint(io.Output(), \"Creating your shared workspace...\")\n\tprogressPrinter.Start()\n\n\t_, err = client.Orgs().Create(org, orgDescription)\n\tprogressPrinter.Stop()\n\tif err == api.ErrOrgAlreadyExists {\n\t\tfmt.Fprintf(io.Output(), \"The workspace %s already exists. If it is your organization, ask a colleague to invite you to the workspace. You can also create a new one using `secrethub org init`.\\n\", org)\n\t} else if err != nil {\n\t\treturn err\n\t} else {\n\t\tfmt.Fprint(io.Output(), \"Created your shared workspace.\\n\\n\")\n\t}\n\treturn nil\n}", "func (a *App) VSCode(ctx context.Context, browser browser, codespaceName string, useInsiders bool) error {\n\tif codespaceName == \"\" {\n\t\tcodespace, err := chooseCodespace(ctx, a.apiClient)\n\t\tif err != nil {\n\t\t\tif err == errNoCodespaces {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"error choosing codespace: %w\", err)\n\t\t}\n\t\tcodespaceName = codespace.Name\n\t}\n\n\turl := vscodeProtocolURL(codespaceName, useInsiders)\n\tif err := browser.Browse(url); err != nil {\n\t\treturn fmt.Errorf(\"error opening Visual Studio Code: %w\", err)\n\t}\n\n\treturn nil\n}", "func createNewTemplate(name string, namespace string, expose bool, clusterDomain string, kube kube.KymaKube) error {\n\tparams := TemplateParameters{\n\t\tName: name,\n\t\tExpose: expose,\n\t\tNamespace: namespace,\n\t\tClusterDomain: clusterDomain,\n\t}\n\n\tcurrentDir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// check if folder exists\n\toutputPath := filepath.Join(currentDir, name)\n\terr = dev.EnsureDir(outputPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// iterate through files of template and create files based on parameters\n\tvar files []string\n\terr = filepath.Walk(templateFolder, func(path string, info os.FileInfo, err error) error {\n\t\tfiles = append(files, path)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not generate lambda\")\n\t}\n\tfor _, file := range files {\n\t\tif file != templateFolder {\n\t\t\tdev.ProcessTemplateFile(outputPath, templateFolder, file, params)\n\t\t}\n\t}\n\treturn nil\n}", "func InitProject() {\n\tfmt.Println(\"\\nDownloading template...\")\n\tresp, err := http.Get(\"https://github.com/ryanlbrown/spapp/archive/master.zip\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor _, f := range r.File {\n\t\t// Ignore dot files.\n\t\tif path.Base(f.Name)[0] == '.' {\n\t\t\tcontinue\n\t\t}\n\t\tpathTokens := strings.Split(f.Name, \"/\")\n\t\tsubName := strings.Join(pathTokens[1:], \"/\")\n\t\tif subName == \"\" || subName == \"README.md\" {\n\t\t\tcontinue\n\t\t}\n\t\tif subName[len(subName)-1] == '/' {\n\t\t\tdirName := subName[:len(subName)-1]\n\t\t\tfmt.Println(\"Created:\", dirName)\n\t\t\terr = os.Mkdir(dirName, 0755)\n\t\t\tif err != nil && !os.IsExist(err) {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t} else {\n\t\t\tfa, err := f.Open()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdefer fa.Close()\n\t\t\tfb, err := os.OpenFile(subName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdefer fb.Close()\n\t\t\t_, err = io.Copy(fb, fa)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tfmt.Println(\"Created:\", subName)\n\t\t}\n\t}\n\tfmt.Println()\n}", "func GetNewGitIgnoreTemplate(cc CodeConfig) string {\n\treturn `\n# See http://help.github.com/ignore-files/ for more about ignoring files.\n#\n# If you find yourself ignoring temporary files generated by your text editor\n# or operating system, you probably want to add a global ignore instead:\n# git config --global core.excludesfile '~/.gitignore_global'\n\n# Ignore tags\n/tags\n\n# Ignore tmp\n/tmp\n\n# Ignore test coverage files\n*.coverprofile\n*coverage.out\n\n# Ignore swap files\n*.swp\n*.swo\n\n# Ignore config files\n# /config.json`\n}", "func ExampleWorkbookTemplatesClient_CreateOrUpdate() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient, err := armapplicationinsights.NewWorkbookTemplatesClient(\"subid\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := client.CreateOrUpdate(ctx,\n\t\t\"my-resource-group\",\n\t\t\"testtemplate2\",\n\t\tarmapplicationinsights.WorkbookTemplate{\n\t\t\tLocation: to.Ptr(\"west us\"),\n\t\t\tProperties: &armapplicationinsights.WorkbookTemplateProperties{\n\t\t\t\tAuthor: to.Ptr(\"Contoso\"),\n\t\t\t\tGalleries: []*armapplicationinsights.WorkbookTemplateGallery{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: to.Ptr(\"Simple Template\"),\n\t\t\t\t\t\tType: to.Ptr(\"tsg\"),\n\t\t\t\t\t\tCategory: to.Ptr(\"Failures\"),\n\t\t\t\t\t\tOrder: to.Ptr[int32](100),\n\t\t\t\t\t\tResourceType: to.Ptr(\"microsoft.insights/components\"),\n\t\t\t\t\t}},\n\t\t\t\tPriority: to.Ptr[int32](1),\n\t\t\t\tTemplateData: map[string]interface{}{\n\t\t\t\t\t\"$schema\": \"https://github.com/Microsoft/Application-Insights-Workbooks/blob/master/schema/workbook.json\",\n\t\t\t\t\t\"items\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"name\": \"text - 2\",\n\t\t\t\t\t\t\t\"type\": float64(1),\n\t\t\t\t\t\t\t\"content\": map[string]interface{}{\n\t\t\t\t\t\t\t\t\"json\": \"## New workbook\\n---\\n\\nWelcome to your new workbook. This area will display text formatted as markdown.\\n\\n\\nWe've included a basic analytics query to get you started. Use the `Edit` button below each section to configure it or add more sections.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"name\": \"query - 2\",\n\t\t\t\t\t\t\t\"type\": float64(3),\n\t\t\t\t\t\t\t\"content\": map[string]interface{}{\n\t\t\t\t\t\t\t\t\"exportToExcelOptions\": \"visible\",\n\t\t\t\t\t\t\t\t\"query\": \"union withsource=TableName *\\n| summarize Count=count() by TableName\\n| render barchart\",\n\t\t\t\t\t\t\t\t\"queryType\": float64(0),\n\t\t\t\t\t\t\t\t\"resourceType\": \"microsoft.operationalinsights/workspaces\",\n\t\t\t\t\t\t\t\t\"size\": float64(1),\n\t\t\t\t\t\t\t\t\"version\": \"KqlItem/1.0\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t\"styleSettings\": map[string]interface{}{},\n\t\t\t\t\t\"version\": \"Notebook/1.0\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// TODO: use response item\n\t_ = res\n}", "func createNewSolutionScriptEntry(solution string, flags *flag.FlagSet) (store.Script, error) {\n\ttimeNow := time.Now()\n\n\tcomment, err := flags.GetString(\"comment\")\n\tif err != nil {\n\t\treturn store.Script{}, fmt.Errorf(\"could not parse `comment` flag: %s\", err)\n\t}\n\tpath, err := flags.GetString(\"path\")\n\tif err != nil {\n\t\treturn store.Script{}, fmt.Errorf(\"could not parse `path` flag: %s\", err)\n\t}\n\n\tif path != \"\" {\n\t\tbytes, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn store.Script{}, fmt.Errorf(\"failed to read %s: %s\", path, err)\n\t\t}\n\t\tsolution = string(bytes)\n\t}\n\n\t//Generate script entry unique id\n\tid, err := store.GenereateIdempotentID(\"\", comment, \"\", solution)\n\tif err != nil {\n\t\treturn store.Script{}, fmt.Errorf(\"failed to generate idem potent id: %s\", err)\n\t}\n\n\treturn store.Script{\n\t\tID: id,\n\t\tComment: comment,\n\t\tCreationTime: timeNow,\n\t\tUpdateTime: timeNow,\n\t\tSolution: store.Solution{\n\t\t\tContent: solution,\n\t\t},\n\t}, nil\n}", "func Create(t *testing.T, knFunc *TestShellCmdRunner, project FunctionTestProject) {\n\tvar result TestShellCmdResult\n\tif project.RemoteRepository == \"\" {\n\t\tresult = knFunc.Exec(\"create\", project.ProjectPath, \"--language\", project.Runtime, \"--template\", project.Template)\n\t} else {\n\t\tresult = knFunc.Exec(\"create\", project.ProjectPath, \"--language\", project.Runtime, \"--template\", project.Template, \"--repository\", project.RemoteRepository)\n\t}\n\tif result.Error != nil {\n\t\tt.Fatal()\n\t}\n}", "func defaultTemplateDir() string {\n return filepath.Join(\"contrib\", \"templates\", \"default\")\n}", "func (m *MigrationService) CreateTemplate(args []string) error {\n\tif m.existMigration() {\n\t\tfileName := args[0]\n\t\ttypes := args[1]\n\t\tprojectID := args[2]\n\t\ttargetBranch := args[3]\n\t\tnameBranch := args[4]\n\t\tcommitMessage := args[5]\n\t\tfolderToCreate, _ := m.getCurrentFolder()\n\n\t\tm.file.CreateFile(folderToCreate, fileName, projectID, targetBranch, nameBranch, commitMessage)\n\t\tm.file.WriteToFile(folderToCreate, fileName, types)\n\t} else {\n\t\tfmt.Println(\"doesn't exist migration. please run [fastshop migrations new] \")\n\t}\n\n\treturn nil\n}", "func Init(projectPath string, commit git.CallbackAddAndCommit, step int) error {\n\tpattern := filepath.Join(\"./golangci/tmpl\", \"*.tmpl\")\n\ttmpl, err := template.ParseGlob(pattern)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to load templates: %s\", err)\n\t}\n\n\tfilename := filepath.Join(projectPath, \".golangci.json\")\n\tfile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create golangci config: %s\", err)\n\t}\n\tdefer func() {\n\t\t_ = file.Close()\n\t}()\n\n\tif err = tmpl.ExecuteTemplate(file, \"golangci\", nil); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse template: %s\", err)\n\t}\n\n\treturn commit([]string{filename}, \"added config for golangci\", step)\n}", "func handleNewCommand() {\n\tneoCliRoot := os.Getenv(\"GOPATH\") + \"/src/github.com/ivpusic/neo/cmd/neo\"\n\n\tif len(*templateName) == 0 {\n\t\tlogger.Info(\"Creating Neo project\")\n\t\trunCmd(neoCliRoot+\"/scripts/neo-template\", []string{*projectName})\n\n\t} else {\n\t\tswitch *templateName {\n\t\tcase \"angular\":\n\t\t\tlogger.Info(\"Creating Neo Angular project\")\n\t\t\trunCmd(neoCliRoot+\"/scripts/angular-template\", []string{*projectName})\n\t\tcase \"html\":\n\t\t\tlogger.Info(\"Creating Neo HTML project\")\n\t\t\trunCmd(neoCliRoot+\"/scripts/neo-html-template\", []string{*projectName})\n\t\tdefault:\n\t\t\tlogger.Errorf(\"Unkonown template %s!\", *projectName)\n\t\t}\n\t}\n}", "func InfraProjectName() []Prompt {\n\treturn []Prompt{\n\t\t{\n\t\t\tName: \"projectName\",\n\t\t\tQuestion: \"Enter the name of your project (will be prefixed to most resources):\",\n\t\t},\n\t}\n}", "func addSourceFile(t *Template, typ sourceType, file string) {}", "func newCreateProjectCmd() *cobra.Command {\n\tvar (\n\t\toptions core.CreateProjectOptions\n\t)\n\n\tcreateProjectCmd := cobra.Command{\n\t\tUse: \"project NAME\",\n\t\tShort: `Create a new verless project`,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tpath := args[0]\n\t\t\treturn core.CreateProject(path, options)\n\t\t},\n\t}\n\n\tcreateProjectCmd.Flags().BoolVar(&options.Overwrite, \"overwrite\",\n\t\tfalse, `overwrite the directory if it already exists`)\n\n\treturn &createProjectCmd\n}", "func AddSourceAttributesForTemplate(sourceID string, template *dw.DevWorkspaceTemplateSpec) {\n\tfor idx, component := range template.Components {\n\t\tif component.Attributes == nil {\n\t\t\ttemplate.Components[idx].Attributes = attributes.Attributes{}\n\t\t}\n\t\ttemplate.Components[idx].Attributes.PutString(constants.PluginSourceAttribute, sourceID)\n\t}\n\tfor idx, command := range template.Commands {\n\t\tif command.Attributes == nil {\n\t\t\ttemplate.Commands[idx].Attributes = attributes.Attributes{}\n\t\t}\n\t\ttemplate.Commands[idx].Attributes.PutString(constants.PluginSourceAttribute, sourceID)\n\t}\n\tfor idx, project := range template.Projects {\n\t\tif project.Attributes == nil {\n\t\t\ttemplate.Projects[idx].Attributes = attributes.Attributes{}\n\t\t}\n\t\ttemplate.Projects[idx].Attributes.PutString(constants.PluginSourceAttribute, sourceID)\n\t}\n\tfor idx, project := range template.StarterProjects {\n\t\tif project.Attributes == nil {\n\t\t\ttemplate.StarterProjects[idx].Attributes = attributes.Attributes{}\n\t\t}\n\t\ttemplate.StarterProjects[idx].Attributes.PutString(constants.PluginSourceAttribute, sourceID)\n\t}\n}", "func NewWorkspace(identifier string) Workspace {\n\treturn Workspace{\n\t\tIdentifier: identifier,\n\t\tCurrentVersion: \"4.0\",\n\t\tCreateVersion: \"4.0\",\n\t}\n}", "func ProjectSnippetCreate(pid interface{}, opts *gitlab.CreateProjectSnippetOptions) (*gitlab.Snippet, error) {\n\tsnip, _, err := lab.ProjectSnippets.CreateSnippet(pid, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn snip, nil\n}", "func (c *Controller) WorkspaceCreated(w *WorkspaceData) error {\n\n\tevent, err := c.prepareEvent(createWSEvent, w.AccountId)\n\tif err == ErrDisabled {\n\t\treturn nil\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tevent.Properties[\"groupName\"] = w.GroupName\n\tevent.Properties[\"message\"] = CreateWSBody\n\n\treturn c.exporter.Send(event)\n}", "func infrastructureMachineTemplateNamePrefix(clusterName, machineDeploymentTopologyName string) string {\n\treturn fmt.Sprintf(\"%s-%s-\", clusterName, machineDeploymentTopologyName)\n}", "func templateDeploy(cmd *cobra.Command, args []string) {\n\t//Check deploy template file.\n\tif len(args) <= 0 || utils.IsFileExist(args[0]) == false {\n\t\tfmt.Fprintf(os.Stderr, \"the deploy template file is required, %s\\n\", \"see https://github.com/Huawei/containerops/singular for more detail.\")\n\t\tos.Exit(1)\n\t}\n\n\ttemplate := args[0]\n\td := new(objects.Deployment)\n\n\t//Read template file and parse.\n\tif err := d.ParseFromFile(template, output); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"parse deploy template error: %s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t//Set private key file path.\n\tif privateKey != \"\" {\n\t\td.Tools.SSH.Private, d.Tools.SSH.Public = privateKey, publicKey\n\t}\n\n\t//The integrity checking of deploy template.\n\tif err := d.Check(); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"parse deploy template error: %s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t//Set log and error io.Writer\n\tvar logWriters io.Writer\n\n\t//Generate stdout/stderr io.Writer\n\tstdoutFile, _ := os.Create(path.Join(d.Config, \"deploy.log\"))\n\tdefer stdoutFile.Close()\n\n\t//Using MultiWriter log and error.\n\tif verbose == true {\n\t\tlogWriters = io.MultiWriter(stdoutFile, os.Stdout)\n\t} else {\n\t\tlogWriters = io.MultiWriter(stdoutFile)\n\t}\n\n\t//Deploy cloud native stack\n\tif err := module.DeployInfraStacks(d, db, logWriters, timestamp); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t//Delete droplets\n\tif del == true {\n\t\tif err := module.DeleteInfraStacks(d, logWriters, timestamp); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func Generate(c *goproject.Config, p *Project) error {\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to get current working directory: %v\", err)\n\t}\n\n\tfullPath := filepath.Join(cwd, p.Name)\n\n\terr = os.Mkdir(fullPath, 0750)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to create project directory: %v\", err)\n\t}\n\n\terr = copyFiles(p.Tpl.path, fullPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to copy template files: %v\", err)\n\t}\n\n\terr = applyProjectToTemplates(p, fullPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to execute templates: %v\", err)\n\t}\n\n\terr = fixCmdProjectFolderName(p, fullPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to rename cmd project folder: %v\", err)\n\t}\n\n\terr = gitCleanup(fullPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to initialize git: %v\", err)\n\t}\n\n\treturn nil\n}", "func CreateTemplate(oc *exutil.CLI, baseName string, ns string, configPath string, numObjects int, tuning *TuningSetType) {\n\t// Try to read the file\n\tcontent, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\tframework.Failf(\"Error reading file: %s\", err)\n\t}\n\n\t// ${IDENTIFER} is what we're replacing in the file\n\tregex, err := regexp.Compile(\"\\\\${IDENTIFIER}\")\n\tif err != nil {\n\t\tframework.Failf(\"Error compiling regex: %v\", err)\n\t}\n\n\tfor i := 0; i < numObjects; i++ {\n\t\tresult := regex.ReplaceAll(content, []byte(strconv.Itoa(i)))\n\n\t\ttmpfile, err := ioutil.TempFile(\"\", \"cl\")\n\t\tif err != nil {\n\t\t\te2e.Failf(\"Error creating new tempfile: %v\", err)\n\t\t}\n\t\tdefer os.Remove(tmpfile.Name())\n\n\t\tif _, err := tmpfile.Write(result); err != nil {\n\t\t\te2e.Failf(\"Error writing to tempfile: %v\", err)\n\t\t}\n\t\tif err := tmpfile.Close(); err != nil {\n\t\t\te2e.Failf(\"Error closing tempfile: %v\", err)\n\t\t}\n\n\t\terr = oc.Run(\"new-app\").Args(\"-f\", tmpfile.Name(), getNsCmdFlag(ns)).Execute()\n\t\te2e.Logf(\"%d/%d : Created template %s\", i+1, numObjects, baseName)\n\n\t\t// If there is a tuning set defined for this template\n\t\tif tuning != nil {\n\t\t\tif tuning.Templates.RateLimit.Delay != 0 {\n\t\t\t\te2e.Logf(\"Sleeping %d ms between template creation.\", tuning.Templates.RateLimit.Delay)\n\t\t\t\ttime.Sleep(time.Duration(tuning.Templates.RateLimit.Delay) * time.Millisecond)\n\t\t\t}\n\t\t\tif tuning.Templates.Stepping.StepSize != 0 && (i+1)%tuning.Templates.Stepping.StepSize == 0 {\n\t\t\t\te2e.Logf(\"We have created %d templates and are now sleeping for %d seconds\", i+1, tuning.Templates.Stepping.Pause)\n\t\t\t\ttime.Sleep(time.Duration(tuning.Templates.Stepping.Pause) * time.Second)\n\t\t\t}\n\t\t}\n\t}\n}", "func Down20200929144301(tx *sql.Tx) error {\n\tclient, err := getClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnamespaces, err := client.ListOnepanelEnabledNamespaces()\n\tif err != nil {\n\t\treturn err\n\t}\n\tuid, err := uid2.GenerateUID(vscodeWorkspaceTemplateName, 30)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, namespace := range namespaces {\n\t\tif _, err := client.ArchiveWorkspaceTemplate(namespace.Name, uid); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func generateTsxFromTemplate(path, name string) {\n\tfullpath := path + name + \"/\" + filepath.Base(name)\n\tgenerateDir(fullpath)\n\tdata := struct{ Name string }{Name: name}\n\tgenerateFromTemplate(fullpath+\".tsx\", \"componentTemplate\", componentTemplate, data)\n\tgenerateFromString(fullpath+\"Styles.tsx\", styleTemplate)\n}", "func addTemplateDataToSite(siteData *SiteData, templateId string, baseFolder string, templateFolder string) {\n\tfolder := filepath.Join(baseFolder, templateFolder)\n\tlogger.Info(\"Scanning for template in folder: \" + folder)\n\ttemplate, err := template.ScanTemplateInFolder(templateId, folder)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// store this template data in map\n\tsiteData.TemplateFolders.Add(templateFolder)\n\tsiteData.Templates[templateId] = template\n}", "func controlPlaneInfrastructureMachineTemplateNamePrefix(clusterName string) string {\n\treturn fmt.Sprintf(\"%s-\", clusterName)\n}", "func createSouceCodeZipFile(context *Context) error {\n\tzipFile, _ := filepath.Abs(context.sourceZipFileName)\n\n\t// create zip file\n\tnewZipFile, err := os.Create(zipFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// create zip writer\n\tzipWriter := zip.NewWriter(newZipFile)\n\n\t// Add everything in Data.Sources to zip file\n\tfor _, item := range context.sechubConfig.Data.Sources {\n\t\terr = appendToSourceCodeZipFile(zipFile, zipWriter, item, context.config.quiet, context.config.debug)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Also support legacy definition:\n\tif len(context.sechubConfig.CodeScan.FileSystem.Folders) > 0 {\n\t\tnamedCodeScanConfig := NamedCodeScanConfig{\n\t\t\tName: \"\",\n\t\t\tFileSystem: context.sechubConfig.CodeScan.FileSystem,\n\t\t\tExcludes: context.sechubConfig.CodeScan.Excludes,\n\t\t\tSourceCodePatterns: context.sechubConfig.CodeScan.SourceCodePatterns,\n\t\t}\n\t\terr = appendToSourceCodeZipFile(zipFile, zipWriter, namedCodeScanConfig, context.config.quiet, context.config.debug)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tzipWriter.Close()\n\tnewZipFile.Close()\n\n\t// Check if context.sourceZipFileName is an empty zip\n\t// For performance reasons we only look deeper into very small files\n\tif sechubUtil.GetFileSize(zipFile) < 300 {\n\t\tzipFileContent, _ := sechubUtil.ReadContentOfZipFile(zipFile)\n\t\tif len(zipFileContent) == 0 {\n\t\t\treturn errors.New(sechubUtil.ZipFileHasNoContent)\n\t\t}\n\t}\n\n\treturn nil\n}", "func main() {\n out, _ := os.Create(\"error-template.go\")\n out.Write([]byte(\"// generated by go run scripts/embed-template.go; DO NOT EDIT\\n\\n\"))\n out.Write([]byte(\"package main\\n\\nconst (\\n\"))\n out.Write([]byte(\"errorTemplate = `\"))\n f, _ := os.Open(\"error-template.html\")\n io.Copy(out, f)\n out.Write([]byte(\"`\\n\"))\n out.Write([]byte(\")\\n\"))\n}", "func K8sCodegen(projectDir string) {\n\tfmt.Fprintln(os.Stdout, \"Run code-generation for custom resources\")\n\tkcmd := exec.Command(k8sGenerated)\n\tkcmd.Dir = projectDir\n\to, err := kcmd.CombinedOutput()\n\tif err != nil {\n\t\tcmdError.ExitWithError(cmdError.ExitError, fmt.Errorf(\"failed to perform code-generation for CustomResources: (%v)\", string(o)))\n\t}\n\tfmt.Fprintln(os.Stdout, string(o))\n}", "func (c *Codegen) AddDefaultSnippets() {\n\t/* common props */\n\tc.AddSnippet(\"php\", \"<?php\")\n\tc.AddSnippet(\"path\", \"$_SERVER['DOCUMENT_ROOT'] = dirname(__FILE__);\")\n\tc.AddSnippet(\"bxheader\", \"require_once($_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/include/prolog_before.php');\")\n\n\t/* specially for iblock properties */\n\tc.AddSnippet(\"iblock\", \"\\\\Bitrix\\\\Main\\\\Loader::includeModule('iblock');\")\n\tc.AddSnippet(\"ibp_obj\", \"$ibp = new CIBlockProperty();\")\n\tc.AddSnippet(\"iblock_prop_st\", \"$prop = array(\")\n\tc.AddSnippet(\"iblock_prop_en\", \");\")\n\tc.AddSnippet(\"iblock_prop_run\", \"$r = $ibp->add($prop);\")\n\tc.AddSnippet(\"iblock_prop_check\", \"if ($r) { \"+c.LineBreak+c.Indent+\"echo 'Added prop with ID: ' . $r . PHP_EOL; \"+c.LineBreak+\"} else { \"+c.LineBreak+c.Indent+\"echo 'Error adding prop: ' . $ibp->LAST_ERROR . PHP_EOL; \"+c.LineBreak+\"}\")\n\n\t/* specially for user fields */\n\tc.AddSnippet(\"uf_obj\", \"$ufo = new CUserTypeEntity;\")\n\tc.AddSnippet(\"uf_data_st\", \"$uf = array(\")\n\tc.AddSnippet(\"uf_data_en\", \");\")\n\tc.AddSnippet(\"uf_data_run\", \"$r = $ufo->add($uf);\")\n\tc.AddSnippet(\"uf_data_check\", \"if ($r) { \"+c.LineBreak+c.Indent+\"echo 'Added UserField with ID: ' . $r . PHP_EOL; \"+c.LineBreak+\"} else { \"+c.LineBreak+c.Indent+\"echo 'Error adding UserField: ' . $ufo->LAST_ERROR . PHP_EOL; \"+c.LineBreak+\"}\")\n\t// TODO - no LAST_ERROR here, catch exception?\n\n\t/* specially for mail event/template */\n\tc.AddSnippet(\"mevent_obj\", \"$meo = new CEventType;\")\n\tc.AddSnippet(\"mevent_data_st\", \"$me = array(\")\n\tc.AddSnippet(\"mevent_data_en\", \");\")\n\tc.AddSnippet(\"mevent_run\", \"$r = $meo->add($me);\")\n\tc.AddSnippet(\"mevent_run_succ_wo_mm\", \"if ($r) { \"+c.LineBreak+c.Indent+\"echo 'Added MailEvent with ID: ' . $r . PHP_EOL; \"+c.LineBreak+\"} else { \"+c.LineBreak+c.Indent+\"echo 'Error adding MailEvent: ' . $meo->LAST_ERROR . PHP_EOL; \"+c.LineBreak+\"}\")\n\tc.AddSnippet(\"mevent_run_check\", \"if ($r) {\")\n\tc.AddSnippet(\"mevent_run_check_else\", \"} else {\"+c.LineBreak+c.Indent+\"echo 'Error adding MailEvent: ' . $meo->LAST_ERROR . PHP_EOL; \"+c.LineBreak+\"}\")\n\tc.AddSnippet(\"mevent_succ\", c.Indent+\"echo 'Added MailEvent with ID: ' . $r . PHP_EOL;\"+c.LineBreak)\n\n\tc.AddSnippet(\"mtpl_warn\", c.Indent+\"// TODO - set proper LID for template!\")\n\tc.AddSnippet(\"mtpl_obj\", \"$mmo = new CEventMessage;\")\n\tc.AddSnippet(\"mtpl_data_st\", \"$mm = array(\")\n\tc.AddSnippet(\"mtpl_data_en\", \");\")\n\tc.AddSnippet(\"mtpl_run\", \"$r = $mmo->add($mm);\")\n\tc.AddSnippet(\"mtpl_run_check\", c.Indent+\"if ($r) {\"+c.LineBreak+c.Indent+c.Indent+\"echo 'Added MailTemplate with ID: ' . $r . PHP_EOL;\"+c.LineBreak+c.Indent+\"} else {\"+c.LineBreak+c.Indent+c.Indent+\"echo 'Error adding MailTemplate: ' . $mmo->LAST_ERROR . PHP_EOL;\"+c.LineBreak+c.Indent+\"}\")\n\n\t/* common, group 2 */\n\tc.AddSnippet(\"done\", \"echo 'Done!' . PHP_EOL;\")\n}", "func newCreateThemeCmd() *cobra.Command {\n\tvar (\n\t\toptions core.CreateThemeOptions\n\t)\n\tcreateThemeCmd := cobra.Command{\n\t\tUse: \"theme THEME_NAME\",\n\t\tShort: `Create a new verless theme`,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tname := args[0]\n\n\t\t\treturn core.CreateTheme(options, name)\n\t\t},\n\t}\n\n\tcreateThemeCmd.Flags().StringVarP(&options.Project, \"project\", \"p\", \".\", `project path to create new theme in.`)\n\treturn &createThemeCmd\n}", "func NewWorkspace(name string, environment map[string]string, columns map[string]map[string][]string, inheritEnv bool) *Workspace {\n\tif environment == nil {\n\t\tenvironment = make(map[string]string)\n\t}\n\tws := &Workspace{\n\t\tName: name,\n\t\tEnvironment: environment,\n\t\tTasks: make(map[string]*Task),\n\t\tFunctions: make(map[string]*Function),\n\t\tColumns: columns,\n\t\tInheritEnvironment: inheritEnv,\n\t}\n\tif _, ok := ws.Environment[\"WORKSPACE\"]; !ok {\n\t\tws.Environment[\"WORKSPACE\"] = name\n\t}\n\treturn ws\n}", "func CodeGenCustomization() {\n\textract, err := bel.Extract(HelloWorld{})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tf, err := os.Create(\"helloworld.ts\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer f.Close()\n\n\t// wrap in a namespace, add to the preamble and write to file\n\terr = bel.Render(extract,\n\t\tbel.GenerateAdditionalPreamble(\"// Hello World\\n\"),\n\t\tbel.GenerateNamespace(\"helloworld\"),\n\t\tbel.GenerateOutputTo(f),\n\t)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func newTemplateHelper(cr *integreatlyv1alpha1.Gitea) *GiteaTemplateHelper {\n\tparam := GiteaParameters{\n\t\tGiteaConfigMapName: GiteaConfigMapName,\n\t\tGiteaDeploymentName: GiteaDeploymentName,\n\t\tGiteaIngressName: GiteaIngressName,\n\t\tGiteaPgDeploymentName: GiteaPgDeploymentName,\n\t\tGiteaPgPvcName: GiteaPgPvcName,\n\t\tGiteaPgServiceName: GiteaPgServiceName,\n\t\tGiteaReposPvcName: GiteaReposPvcName,\n\t\tGiteaServiceAccountName: GiteaServiceAccountName,\n\t\tGiteaServiceName: GiteaServiceName,\n\t\tProxyDeploymentName: ProxyDeploymentName,\n\t\tProxyRouteName: ProxyRouteName,\n\t\tProxyServiceName: ProxyServiceName,\n\t\tProxyServiceAccountName: ProxyServiceAccountName,\n\t\tApplicationNamespace: cr.Namespace,\n\t\tApplicationName: \"gitea\",\n\t\tHostname: cr.Spec.Hostname,\n\t\tDatabaseUser: \"gitea\",\n\t\tDatabasePassword: DatabasePassword,\n\t\tDatabaseAdminPassword: DatabaseAdminPassword,\n\t\tDatabaseName: \"gitea\",\n\t\tDatabaseMaxConnections: \"100\",\n\t\tDatabaseSharedBuffers: \"12MB\",\n\t\tInstallLock: true,\n\t\tGiteaInternalToken: generateToken(105),\n\t\tGiteaSecretKey: generateToken(10),\n\t\tGiteaImage: GiteaImage,\n\t\tGiteaVersion: GiteaVersion,\n\t\tGiteaVolumeCapacity: \"1Gi\",\n\t\tDbVolumeCapacity: \"1Gi\",\n\t}\n\n\ttemplatePath := os.Getenv(\"TEMPLATE_PATH\")\n\tif templatePath == \"\" {\n\t\ttemplatePath = \"./templates\"\n\t}\n\n\treturn &GiteaTemplateHelper{\n\t\tParameters: param,\n\t\tTemplatePath: templatePath,\n\t}\n}", "func showNewSiteHelp(projectPath string) {\n\thelpString := fragmentaDivider\n\thelpString += \"Congratulations, we've made a new website at \" + projectPathRelative(projectPath)\n\thelpString += \"\\n if you wish you can edit the database config at:\"\n\thelpString += \"\\n \" + projectPathRelative(configPath(projectPath))\n\thelpString += \"\\n and sql at:\"\n\thelpString += \"\\n \" + projectPathRelative(dbMigratePath(projectPath))\n\thelpString += \"\\n To get started, run the following commands:\"\n\thelpString += \"\\n cd \" + projectPath\n\thelpString += \"\\n fragmenta migrate\"\n\thelpString += \"\\n fragmenta\"\n\thelpString += fragmentaDivider + \"\\n\"\n\tfmt.Print(helpString) // fmt to avoid time output\n}", "func generateWorkFlow(ctx *Context) error {\n\trootCtx, err := getRootContext()\n\tif err != nil {\n\t\treturn err\n\t}\n\texamples, err := rootCtx.GetExamples()\n\tif err != nil {\n\t\treturn err\n\t}\n\tmodules, err := rootCtx.GetModules()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn workflow.Generate(ctx.GithubWorkflowsDir(), examples, modules)\n}", "func RevertTemplate(name string) error {\n\treturn pathx.CreateTemplate(category, name, deploymentTemplate)\n}", "func (e *explorer) parseGoTemplate() error {\n\ttmplName := \"go.tmpl\"\n\ttmplPath := filepath.Join(e.repoDir, \"cmd/explore\", tmplName)\n\tts, err := template.ParseFiles(tmplPath)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\te.goTmpl = ts.Lookup(tmplName)\n\treturn nil\n}", "func (s *projectService) createNewProject(projectName, owner string) (*schema.Project, error) {\n\tproject := schema.NewProject(projectName, owner)\n\treturn s.projects.Insert(&project)\n}", "func GetNewConfigJsonTemplate(cc CodeConfig) string {\n\treturn `{\n\t\"version\": \"0.1.0\",\n \"gson_api_url\": \"https://api.your-domain-goes-here.com/v1/\",\n\t\"port\": 4000,\n\t\"new_relic_key\": \"\",\n\t\"debug\": false,\n\t\"environment\": \"test\",\n\t\"test\": { {{if .IsMSSQL}}\n\t\t\"mssql\": {\n\t\t \"aws\": {\n\t\t\t\"server\": \"\",\n\t\t\t\"port\": 1433,\n\t\t\t\"dbname\": \"\",\n\t\t\t\"username\": \"\",\n\t\t\t\"password\": \"\",\n\t\t\t\"maxidleconnections\": 10,\n\t\t\t\"maxopenconnections\": 100,\n\t\t\t\"debug\": true\n\t\t }\n\t\t}\n {{else if .IsPostgresql}}\n \"postgresql\": {\n\t\t \"aws\": {\n\t\t\t\"server\": \"\",\n\t\t\t\"port\": 5432,\n\t\t\t\"dbname\": \"\",\n\t\t\t\"username\": \"\",\n\t\t\t\"password\": \"\",\n\t\t\t\"maxidleconnections\": 10,\n\t\t\t\"maxopenconnections\": 100,\n\t\t\t\"debug\": true\n\t\t }\n\t\t}\n {{else if .IsRethinkDB}}\n\t\t\"rethinkdb\": {\n\t\t \"aws\": {\n\t\t \"addresses\":\"\",\n\t\t \"dbname\": \"\",\n\t\t \"authkey\": \"\",\n\t\t \"discoverhosts\": false,\n\t\t \"maxidleconnections\": 10,\n\t\t \"maxopenconnections\": 100,\n\t\t \"debug\": true\n\t\t}\n\t}{{end}}\n }\n}`\n}", "func (c *PromptAddFolder) Run(w *lime.Window) error {\n\tdir := viewDirectory(w.ActiveView())\n\tfe := lime.GetEditor().Frontend()\n\tfolders := fe.Prompt(\"Open file\", dir, lime.PROMPT_ONLY_FOLDER|lime.PROMPT_SELECT_MULTIPLE)\n\tfor _, folder := range folders {\n\t\tw.Project().AddFolder(folder)\n\t}\n\treturn nil\n}", "func GenerateCode(config Config) error {\n\terr := copyTemplatesDir(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = executeTemplatesDir(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Client) UpdateWorkspaceTemplate(namespace string, workspaceTemplate *WorkspaceTemplate) (*WorkspaceTemplate, error) {\n\texistingWorkspaceTemplate, err := c.GetWorkspaceTemplate(namespace, workspaceTemplate.UID, workspaceTemplate.Version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif existingWorkspaceTemplate == nil {\n\t\treturn nil, util.NewUserError(codes.NotFound, \"Workspace template not found.\")\n\t}\n\tworkspaceTemplate.ID = existingWorkspaceTemplate.ID\n\tworkspaceTemplate.Name = existingWorkspaceTemplate.UID\n\tworkspaceTemplate.Namespace = existingWorkspaceTemplate.Namespace\n\n\tupdatedWorkflowTemplate, err := c.generateWorkspaceTemplateWorkflowTemplate(workspaceTemplate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tupdatedWorkflowTemplate.ID = existingWorkspaceTemplate.WorkflowTemplate.ID\n\tupdatedWorkflowTemplate.UID = existingWorkspaceTemplate.WorkflowTemplate.UID\n\n\tupdatedWorkflowTemplate.Labels = workspaceTemplate.Labels\n\tworkflowTemplateVersion, err := c.CreateWorkflowTemplateVersion(namespace, updatedWorkflowTemplate)\n\tif err != nil {\n\t\tvar statusError *util.UserError\n\t\tif goerrors.As(err, &statusError) && statusError.Code == codes.InvalidArgument {\n\t\t\treturn nil, util.NewUserError(statusError.Code, strings.Replace(statusError.Message, \"{{workflow.\", \"{{workspace.\", -1))\n\t\t}\n\t\treturn nil, err\n\t}\n\n\t// TODO - this might not be needed with recent changes made.\n\tworkspaceTemplate.Version = workflowTemplateVersion.Version\n\tworkspaceTemplate.IsLatest = true\n\n\ttx, err := c.DB.Begin()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer tx.Rollback()\n\n\tif err := createLatestWorkspaceTemplateVersionDB(tx, workspaceTemplate); err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = sb.Update(\"workspace_templates\").\n\t\tSetMap(sq.Eq{\n\t\t\t\"labels\": workspaceTemplate.Labels,\n\t\t\t\"description\": workspaceTemplate.Description,\n\t\t}).\n\t\tWhere(sq.Eq{\n\t\t\t\"uid\": workspaceTemplate.UID,\n\t\t\t\"namespace\": workspaceTemplate.Namespace,\n\t\t}).\n\t\tRunWith(tx).\n\t\tExec()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := tx.Commit(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn workspaceTemplate, nil\n}", "func (c *Client) CreateTranscodeTemplate(request *CreateTranscodeTemplateRequest) (response *CreateTranscodeTemplateResponse, err error) {\n if request == nil {\n request = NewCreateTranscodeTemplateRequest()\n }\n response = NewCreateTranscodeTemplateResponse()\n err = c.Send(request, response)\n return\n}", "func Up20201016170415(tx *sql.Tx) error {\n\t// This code is executed when the migration is applied.\n\treturn updateWorkspaceTemplateManifest(\n\t\tfilepath.Join(\"workspaces\", \"cvat\", \"20201016170415.yaml\"),\n\t\tcvatTemplateName)\n}", "func createWorkspaceTemplateVersionDB(tx sq.BaseRunner, template *WorkspaceTemplate) (err error) {\n\terr = sb.Insert(\"workspace_template_versions\").\n\t\tSetMap(sq.Eq{\n\t\t\t\"version\": template.Version,\n\t\t\t\"is_latest\": template.IsLatest,\n\t\t\t\"manifest\": template.Manifest,\n\t\t\t\"workspace_template_id\": template.ID,\n\t\t\t\"labels\": template.Labels,\n\t\t}).\n\t\tSuffix(\"RETURNING id\").\n\t\tRunWith(tx).\n\t\tQueryRow().\n\t\tScan(&template.ID)\n\n\treturn\n}", "func addDFCToPodTemplate(podTemplateSpec *corev1.PodTemplateSpec, cr *v1alpha1.SplunkEnterprise) error {\n\trequirements, err := spark.GetSparkRequirements(cr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// create an init container in the pod, which is just used to populate the jdk and spark mount directories\n\tcontainerSpec := corev1.Container{\n\t\tImage: spark.GetSparkImage(cr),\n\t\tImagePullPolicy: corev1.PullPolicy(cr.Spec.ImagePullPolicy),\n\t\tName: \"init\",\n\t\tResources: requirements,\n\t\tCommand: []string{\"bash\", \"-c\", \"cp -r /opt/jdk /mnt && cp -r /opt/spark /mnt\"},\n\t}\n\tcontainerSpec.VolumeMounts = append(containerSpec.VolumeMounts, corev1.VolumeMount{\n\t\tName: \"mnt-splunk-jdk\",\n\t\tMountPath: \"/mnt/jdk\",\n\t})\n\tcontainerSpec.VolumeMounts = append(containerSpec.VolumeMounts, corev1.VolumeMount{\n\t\tName: \"mnt-splunk-spark\",\n\t\tMountPath: \"/mnt/spark\",\n\t})\n\tpodTemplateSpec.Spec.InitContainers = append(podTemplateSpec.Spec.InitContainers, containerSpec)\n\n\t// add empty jdk and spark mount directories to all of the splunk containers\n\temptyVolumeSource := corev1.VolumeSource{\n\t\tEmptyDir: &corev1.EmptyDirVolumeSource{},\n\t}\n\taddSplunkVolumeToTemplate(podTemplateSpec, \"jdk\", emptyVolumeSource)\n\taddSplunkVolumeToTemplate(podTemplateSpec, \"spark\", emptyVolumeSource)\n\n\treturn nil\n}", "func NewTemplate() {\n\tfileName := \"\"\n\tsurvey.AskOne(&survey.Input{Message: \"Enter a name for this template\"}, &fileName)\n\tfilePath := filepath.Join(TemplatesDir(), fileName)\n\n\tif _, err := os.Stat(filePath); !os.IsNotExist(err) {\n\t\tshouldReplace := false\n\t\terr := survey.AskOne(\n\t\t\t&survey.Confirm{Message: \"A template with this name already exists, do you want to overwrite it?\"},\n\t\t\t&shouldReplace,\n\t\t\tsurvey.WithValidator(survey.Required),\n\t\t)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif shouldReplace {\n\t\t\terr = ioutil.WriteFile(filePath, []byte{}, os.FileMode(0644))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}\n\t} else if os.IsNotExist(err) {\n\t\terr = ioutil.WriteFile(filePath, []byte{}, os.FileMode(0644))\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\teditFile(filePath)\n}", "func NewCfnStudio_Override(c CfnStudio, scope awscdk.Construct, id *string, props *CfnStudioProps) {\n\t_init_.Initialize()\n\n\t_jsii_.Create(\n\t\t\"monocdk.aws_nimblestudio.CfnStudio\",\n\t\t[]interface{}{scope, id, props},\n\t\tc,\n\t)\n}", "func execmTemplateNew(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := args[0].(*template.Template).New(args[1].(string))\n\tp.Ret(2, ret)\n}", "func (m *Meta) selectWorkspace(b backend.Backend) error {\n\tworkspaces, err := b.Workspaces()\n\tif err == backend.ErrWorkspacesNotSupported {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to get existing workspaces: %s\", err)\n\t}\n\tif len(workspaces) == 0 {\n\t\tif c, ok := b.(*cloud.Cloud); ok && m.input {\n\t\t\t// len is always 1 if using Name; 0 means we're using Tags and there\n\t\t\t// aren't any matching workspaces. Which might be normal and fine, so\n\t\t\t// let's just ask:\n\t\t\tname, err := m.UIInput().Input(context.Background(), &terraform.InputOpts{\n\t\t\t\tId: \"create-workspace\",\n\t\t\t\tQuery: \"\\n[reset][bold][yellow]No workspaces found.[reset]\",\n\t\t\t\tDescription: fmt.Sprintf(inputCloudInitCreateWorkspace, strings.Join(c.WorkspaceMapping.Tags, \", \")),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Couldn't create initial workspace: %w\", err)\n\t\t\t}\n\t\t\tname = strings.TrimSpace(name)\n\t\t\tif name == \"\" {\n\t\t\t\treturn fmt.Errorf(\"Couldn't create initial workspace: no name provided\")\n\t\t\t}\n\t\t\tlog.Printf(\"[TRACE] Meta.selectWorkspace: selecting the new TFC workspace requested by the user (%s)\", name)\n\t\t\treturn m.SetWorkspace(name)\n\t\t} else {\n\t\t\treturn fmt.Errorf(strings.TrimSpace(errBackendNoExistingWorkspaces))\n\t\t}\n\t}\n\n\t// Get the currently selected workspace.\n\tworkspace, err := m.Workspace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Check if any of the existing workspaces matches the selected\n\t// workspace and create a numbered list of existing workspaces.\n\tvar list strings.Builder\n\tfor i, w := range workspaces {\n\t\tif w == workspace {\n\t\t\tlog.Printf(\"[TRACE] Meta.selectWorkspace: the currently selected workspace is present in the configured backend (%s)\", workspace)\n\t\t\treturn nil\n\t\t}\n\t\tfmt.Fprintf(&list, \"%d. %s\\n\", i+1, w)\n\t}\n\n\t// If the backend only has a single workspace, select that as the current workspace\n\tif len(workspaces) == 1 {\n\t\tlog.Printf(\"[TRACE] Meta.selectWorkspace: automatically selecting the single workspace provided by the backend (%s)\", workspaces[0])\n\t\treturn m.SetWorkspace(workspaces[0])\n\t}\n\n\tif !m.input {\n\t\treturn fmt.Errorf(\"Currently selected workspace %q does not exist\", workspace)\n\t}\n\n\t// Otherwise, ask the user to select a workspace from the list of existing workspaces.\n\tv, err := m.UIInput().Input(context.Background(), &terraform.InputOpts{\n\t\tId: \"select-workspace\",\n\t\tQuery: fmt.Sprintf(\n\t\t\t\"\\n[reset][bold][yellow]The currently selected workspace (%s) does not exist.[reset]\",\n\t\t\tworkspace),\n\t\tDescription: fmt.Sprintf(\n\t\t\tstrings.TrimSpace(inputBackendSelectWorkspace), list.String()),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to select workspace: %s\", err)\n\t}\n\n\tidx, err := strconv.Atoi(v)\n\tif err != nil || (idx < 1 || idx > len(workspaces)) {\n\t\treturn fmt.Errorf(\"Failed to select workspace: input not a valid number\")\n\t}\n\n\tworkspace = workspaces[idx-1]\n\tlog.Printf(\"[TRACE] Meta.selectWorkspace: setting the current workpace according to user selection (%s)\", workspace)\n\treturn m.SetWorkspace(workspace)\n}", "func (c *Client) CreateWorkspace(label, description string) (*Workspace, error) {\n\trequest := fmt.Sprintf(workspaceCreateRequest, label, description)\n\n\tresponse, err := c.QueryHouston(request)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"CreateWorkspace Failed\")\n\t}\n\n\treturn response.Data.CreateWorkspace, nil\n}", "func genSource(dir, filename, templateSource string, args map[string]interface{}) {\n\tsourceCode := revel.ExecuteTemplate(\n\t\ttemplate.Must(template.New(\"\").Parse(templateSource)),\n\t\targs)\n\n\t// Create a fresh dir.\n\ttmpPath := path.Join(revel.AppPath, dir)\n\terr := os.RemoveAll(tmpPath)\n\tif err != nil {\n\t\trevel.ERROR.Println(\"Failed to remove dir:\", err)\n\t}\n\terr = os.Mkdir(tmpPath, 0777)\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Failed to make tmp directory: %v\", err)\n\t}\n\n\t// Create the file\n\tfile, err := os.Create(path.Join(tmpPath, filename))\n\tdefer file.Close()\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Failed to create file: %v\", err)\n\t}\n\t_, err = file.WriteString(sourceCode)\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Failed to write to file: %v\", err)\n\t}\n}", "func AppHelpTemplate() string {\n\treturn `NAME:\n {{.Name}}{{if .Usage}} - {{.Usage}}{{end}}\n\nUSAGE:\n {{if .UsageText}}{{.UsageText | nindent 3 | trim}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Version}}{{if not .HideVersion}}\n\nVERSION:\n {{.Version}}{{end}}{{end}}{{if .Description}}\n\nDESCRIPTION:\n {{.Description | nindent 3 | trim}}{{end}}{{if len .Authors}}\n\nAUTHOR{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}:\n {{range $index, $author := .Authors}}{{if $index}}\n {{end}}{{$author}}{{end}}{{end}}{{if .VisibleCommands}}\n\nCOMMANDS:{{range .VisibleCategories}}{{if .Name}}\n {{.Name}}:{{range .VisibleCommands}}\n {{join .Names \", \"}}{{\"\\t\"}}{{.Usage}}{{end}}{{else}}{{range .VisibleCommands}}\n {{join .Names \", \"}}{{\"\\t\"}}{{.Usage}}{{end}}{{end}}{{end}}{{end}}{{if .VisibleFlags}}\n\nGLOBAL OPTIONS:\n {{range $index, $option := .VisibleFlags}}{{if $index}}\n {{end}}{{stripDefault $option}}{{end}}{{end}}{{if .Copyright}}\n\nCOPYRIGHT:\n {{.Copyright}}{{end}}\n`\n}", "func init() {\n\t_workspace = Absolute(lygo.DEF_WORKSPACE)\n}", "func genSource(dir, filename, templateSource string, args map[string]interface{}) {\n\tsourceCode := revel.ExecuteTemplate(\n\t\ttemplate.Must(template.New(\"\").Parse(templateSource)),\n\t\targs)\n\n\t// Create a fresh dir.\n\t// tmpPath := path.Join(revel.AppPath, dir)\n\n\t// Create the file\n\tfile, err := os.Create(path.Join(dir, filename))\n\tdefer file.Close()\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Failed to create file: %v\", err)\n\t}\n\t_, err = file.WriteString(sourceCode)\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Failed to write to file: %v\", err)\n\t}\n}", "func RunNew(args []string) {\n\n\t// Remove fragmenta backup from args list\n\targs = args[2:]\n\n\t// We expect two args left:\n\tif len(args) < 2 {\n\t\tlog.Printf(\"Both a project path and a project type or URL are required to create a new site\\n\")\n\t\treturn\n\t}\n\n\trepo := args[0]\n\tprojectPath, err := filepath.Abs(args[1])\n\tif err != nil {\n\t\tlog.Printf(\"Error expanding file path\\n\")\n\t\treturn\n\t}\n\n\tif !strings.HasPrefix(projectPath, filepath.Join(os.Getenv(\"GOPATH\"), \"src\")) {\n\t\tlog.Printf(\"WARNING: You should create your project in $GOPATH/src\\n\")\n\t}\n\n\tif fileExists(projectPath) {\n\t\tlog.Printf(\"A folder already exists at path %s\\n\", projectPath)\n\t\treturn\n\t}\n\n\tswitch repo {\n\tcase \"app\":\n\t\trepo = \"github.com/fragmenta/fragmenta-app\"\n\tcase \"cms\":\n\t\trepo = \"github.com/fragmenta/fragmenta-cms\"\n\t\t// TODO: Blog example does not exist yet\n\t\t//\tcase \"blog\":\n\t\t//\t\trepo = \"github.com/fragmenta/fragmenta-blog\"\n\tdefault:\n\t\t// TODO clean repo if it contains https or .git...\n\t}\n\n\t// Log fetching our files\n\tlog.Printf(\"Fetching from url: %s\\n\", repo)\n\n\t// Go get the project url, to make sure it is up to date, should use -u\n\t_, err = runCommand(\"go\", \"get\", repo)\n\tif err != nil {\n\t\tlog.Printf(\"Error calling go get %s\", err)\n\t\treturn\n\t}\n\n\t// Copy the pristine new site over\n\tgoProjectPath := filepath.Join(os.Getenv(\"GOPATH\"), \"src\", repo)\n\terr = copyNewSite(goProjectPath, projectPath)\n\tif err != nil {\n\t\tlog.Printf(\"Error copying project %s\", err)\n\t\treturn\n\t}\n\n\t// Generate config files\n\terr = generateConfig(projectPath)\n\tif err != nil {\n\t\tlog.Printf(\"Error generating config %s\", err)\n\t\treturn\n\t}\n\n\t// Generate a migration AND run it\n\terr = generateCreateSQL(projectPath)\n\tif err != nil {\n\t\tlog.Printf(\"Error generating migrations %s\", err)\n\t\treturn\n\t}\n\n\t// Output instructions to let them change setup first if they wish\n\tshowNewSiteHelp(projectPath)\n\n}", "func AddTemplateExt(ext string) {\n\tfor _, v := range beeTemplateExt {\n\t\tif v == ext {\n\t\t\treturn\n\t\t}\n\t}\n\tbeeTemplateExt = append(beeTemplateExt, ext)\n}", "func newWorkspace(session *session, root string) *Workspace {\n\treturn &Workspace{\n\t\tsession: session,\n\t\trootPath: root,\n\t}\n}", "func (g *Generator) AddTemplate(t string) {\n\t// read the prelude\n\tnewT, newData, err := utils.GetPrelude(t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tg.SetDataMap(newData)\n\n\tg.tpls = append(g.tpls, newT)\n}", "func NewPage(ctx *sweetygo.Context) error {\n\tctx.Set(\"title\", \"New\")\n\tctx.Set(\"editor\", true)\n\treturn ctx.Render(200, \"posts/new\")\n}", "func outputMustBeNewProject() {\n\tnewProjectName := outputOperatorType + \"-\" + projectName\n\tfp := filepath.Join(projutil.MustGetwd())\n\tstat, err := os.Stat(fp)\n\tif err != nil && os.IsNotExist(err) {\n\t\treturn\n\t}\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to determine if project (%v) exists\", newProjectName)\n\t}\n\tif stat.IsDir() {\n\t\tlog.Fatalf(\"Project (%v) in (%v) path already exists. Please use a different project name or delete the existing one\", newProjectName, fp)\n\t}\n}", "func Create (appName string) {\n\n checkGopath ()\n checkContainer (appName)\n\n app := Application { Name: appName }\n\n app.createContainer ()\n\n err := app.copyFileTree (\n GOPATH + slash + applicationTemplatesPath,\n GOPATH_SRC + app.Name,\n )\n\n if err != nil {\n log.Fatal (err)\n }\n}", "func createSnykProject(token, org, integrationID, owner, name, branch string) {\n\tclient, err := snyk.NewClient(snyk.WithToken(token))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tcb, err := client.OrganizationImportProject(context.TODO(), org, integrationID, snyk.GitHubImport(owner, name, branch, nil))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(cb)\n}", "func TestWorkspaceSymbol(t *testing.T) {\n\tt.Parallel()\n\n\ttree := writeTree(t, `\n-- go.mod --\nmodule example.com\ngo 1.18\n\n-- a.go --\npackage a\nfunc someFunctionName()\n`)\n\t// no files\n\t{\n\t\tres := gopls(t, tree, \"workspace_symbol\")\n\t\tres.checkExit(false)\n\t\tres.checkStderr(\"expects 1 argument\")\n\t}\n\t// success\n\t{\n\t\tres := gopls(t, tree, \"workspace_symbol\", \"meFun\")\n\t\tres.checkExit(true)\n\t\tres.checkStdout(\"a.go:2:6-22 someFunctionName Function\")\n\t}\n}", "func (g project) GetTemplates(serviceName string) {\n\tcontents := `#!/usr/bin/env bash\n\tservicename=$1;\n\tcd $servicename;\n\tgit init;\n\tgit remote add origin [email protected]:yowez/skeleton-service.git;\n\tgit remote -v;\n\tgit fetch;\t\n\tgit pull origin master;\n\trm -rf .git;\n\tcd ..;\n`\n\tbt := []byte(contents)\n\terr := ioutil.WriteFile(template, bt, 0644)\n\tif err != nil {\n\t\tg.rollbackWhenError(\"fail when create scaffold script\")\n\t}\n\tdefer func() {\n\t\t_ = os.Remove(template)\n\t}()\n\tcmd := exec.Command(bash, template, serviceName)\n\terr = g.runCmd(cmd)\n\tif err != nil {\n\t\tlog.Fatal(\"fail run scaffold script\")\n\t}\n\n}", "func (hub *Hub) ScaffoldProject(config models.Config) cli.Command {\n\treturn cli.Command{\n\t\tName: \"scaffold\",\n\t\tAliases: []string{\"s\"},\n\t\tUsage: \"Scaffold a new project with gitops structure\",\n\t\tAction: hub.initApp(hub.scaffold),\n\t\tFlags: []cli.Flag{\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"output, o\",\n\t\t\t\tUsage: \"Path to manifests output directory for `PROJECT`\",\n\t\t\t},\n\t\t},\n\t}\n}", "func (s *Static) GenerateStaticTemplates() (fNames []string, err error) {\n\n\t// begin of new part\n\ttmlFiles, err := glob(s.SrcDir, \"*\"+\".gotmpl\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// end of new part\n\n\tfor _, f := range tmlFiles {\n\n\t\t// start of new part\n\t\tfi, err := pkger.Stat(f)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Stat: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttf, err := pkger.Open(f)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Open: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer tf.Close()\n\n\t\t// read the template source from pkger\n\t\tbuf := make([]byte, fi.Size())\n\t\t_, err = tf.Read(buf)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Unable to read template: %s %v\\n\", f, err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tst := template.Must(template.New(\"Static template\").Parse(string(buf)))\n\t\tif st == nil {\n\t\t\tlog.Printf(\"Parse error: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\t// end of new part\n\n\t\t// create the file-path if required\n\t\t_, err = os.Stat(s.DstDir)\n\t\tif err != nil {\n\t\t\tos.Mkdir(s.DstDir, 0755)\n\t\t}\n\n\t\t// create the static source file\n\t\tfileName := filepath.Base(f)\n\t\tfileName = strings.TrimSuffix(fileName, \"tmpl\")\n\t\tf, err := os.Create(s.DstDir + \"/\" + fileName)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"generateStaticTemplates: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer f.Close()\n\n\t\t// set permissions\n\t\terr = f.Chmod(0755)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"generateStaticTemplates: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// execute the template using the new controller file as a target\n\t\terr = st.Execute(f, s)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"generateStaticTemplates: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tfName := s.DstDir + \"/\" + fileName\n\t\tfNames = append(fNames, fName)\n\t\tlog.Println(\"generated:\", fName)\n\t\tf.Close()\n\t}\n\treturn fNames, nil\n}", "func scaffold(name string, op string, args UserRepoArgs) error {\n\n\t// Fetch the scaffold files for the tutorial\n\tfiles := files(name)\n\t// Create the necessary folders for the files\n\terr := createUniqueFolders(files, op, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create the files and fill them with the applied templates\n\terr = applyTemplates(files, op, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func InitializeProject(templateName string, silent bool) {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tlogger.Fatalf(true, \"Failed to find working directory. %s\", err.Error())\n\t}\n\tconfig.ProjectRoot = wd\n\tif isGaugeProject() {\n\t\tlogger.Fatalf(true, \"This is already a Gauge Project. Please try to initialize a Gauge project in a different location.\")\n\t}\n\texists, _ := common.UrlExists(getTemplateURL(templateName))\n\tif exists {\n\t\terr = initializeTemplate(templateName)\n\t\tinstallRunner(templateName, silent)\n\t} else {\n\t\tinstallRunner(templateName, silent)\n\t\terr = createProjectTemplate(templateName)\n\t}\n\tif err != nil {\n\t\tlogger.Fatalf(true, \"Failed to initialize project. %s\", err.Error())\n\t}\n}", "func writeIstioTemplate(path string) error {\n\tif err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(path, []byte(istioBootStrapTemplate), 0644)\n}", "func (e *rhcosEditor) CreateMinimalISOTemplate(serviceBaseURL string) (string, error) {\n\tif err := e.isoHandler.Extract(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err := os.Remove(e.isoHandler.ExtractedPath(\"images/pxeboot/rootfs.img\")); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err := e.embedInitrdPlaceholders(); err != nil {\n\t\te.log.WithError(err).Warnf(\"Failed to embed initrd placeholders\")\n\t\treturn \"\", err\n\t}\n\n\t// ToDo: store placeholders' offsets in system area\n\n\tif err := e.fixTemplateConfigs(serviceBaseURL); err != nil {\n\t\te.log.WithError(err).Warnf(\"Failed to edit template configs\")\n\t\treturn \"\", err\n\t}\n\n\te.log.Info(\"Creating minimal ISO template\")\n\treturn e.create()\n}", "func newTemplateHelper(cr *v1alpha1.Installation, extraParams map[string]string, config *config.Monitoring) *TemplateHelper {\n\tparam := Parameters{\n\t\tPlaceholder: Placeholder,\n\t\tNamespace: config.GetNamespace(),\n\t\tMonitoringKey: config.GetLabelSelector(),\n\t\tExtraParams: extraParams,\n\t}\n\n\ttemplatePath, exists := os.LookupEnv(\"TEMPLATE_PATH\")\n\tif !exists {\n\t\ttemplatePath = \"./templates/monitoring\"\n\t}\n\n\tmonitoringKey, exists := os.LookupEnv(\"MONITORING_KEY\")\n\tif exists {\n\t\tparam.MonitoringKey = monitoringKey\n\t}\n\n\treturn &TemplateHelper{\n\t\tParameters: param,\n\t\tTemplatePath: templatePath,\n\t}\n}", "func CreateCommand() *cobra.Command {\n\treturn base.CreateCommand(\"template\", \"Create vt template from xml\", New())\n}", "func cloneProject(projectPath string) {\n\tvar projectLocation = trimPathAfterLastSlash(projectPath) //get project location\n\tvar prevProjectPath = projectPath + \"_previous\"\n\tvar isFound, _ = searchForFilePath(projectLocation, trimPathBeforeLastSlash(prevProjectPath, false)) //look for a prevProject from project locaation where the project and prevProject should be store\n\tprint(\"\\n\")\n\tif isFound { //if clonedProject already exist, delete it and create a new clone\n\t\tcolor.Style{color.Red}.Print(\"Deleting \", trimPathBeforeLastSlash(prevProjectPath, false), \"... \")\n\t\tdeleteAllFiles(prevProjectPath)\n\t\tcolor.Style{color.Red, color.Bold}.Print(\"Deleted. \")\n\n\t}\n\tprint(\"Cloning \", trimPathBeforeLastSlash(projectPath, false), \".\\n\")\n\tcopy.CopyDir(projectPath, prevProjectPath) //clones project in the same place where the project exist\"\n\tcolor.Style{color.Green}.Print(trimPathBeforeLastSlash(prevProjectPath, false) + \" created at \" + projectLocation + \". \")\n\tcolor.Style{color.Bold}.Print(\"StringsUtility is now ready to make changes.\")\n\tfmt.Print(\"\\n\\n\"+kCONSTANTDASHES, \"\\n\")\n}", "func home(c *gin.Context) {\n\tc.HTML(200, \"home/home\", gin.H{\n\t\t\"Title\": config.Settings.ProjectName + \" welcomes you!\",\n\t})\n}", "func Codegen(dir string, b *bytes.Buffer, out string) {\n\ttd := CollectTemplateData(dir)\n\tWritePackage(\"00-main.go.tmpl\", \"templates/*\", b, td, map[string]interface{}{\n\t\t\"toReceiverCase\": toReceiverCase,\n\t\t\"lowerFirst\": lowerFirst,\n\t\t\"toLower\": strings.ToLower,\n\t\t\"TStringifyField\": TStringifyField,\n\t\t\"TParseField\": TParseField,\n\t})\n\tsrc, err := format.Source(b.Bytes())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tioutil.WriteFile(out, src, 0644)\n}", "func addSplunkVolumeToTemplate(podTemplateSpec *corev1.PodTemplateSpec, name string, volumeSource corev1.VolumeSource) {\n\tpodTemplateSpec.Spec.Volumes = append(podTemplateSpec.Spec.Volumes, corev1.Volume{\n\t\tName: \"mnt-splunk-\" + name,\n\t\tVolumeSource: volumeSource,\n\t})\n\n\tfor idx := range podTemplateSpec.Spec.Containers {\n\t\tcontainerSpec := &podTemplateSpec.Spec.Containers[idx]\n\t\tcontainerSpec.VolumeMounts = append(containerSpec.VolumeMounts, corev1.VolumeMount{\n\t\t\tName: \"mnt-splunk-\" + name,\n\t\t\tMountPath: \"/mnt/splunk-\" + name,\n\t\t})\n\t}\n}", "func ProjectCreate(p project.APIProject, c *cli.Context) error {\n\toptions := options.Create{\n\t\tNoRecreate: c.Bool(\"no-recreate\"),\n\t\tForceRecreate: c.Bool(\"force-recreate\"),\n\t\tNoBuild: c.Bool(\"no-build\"),\n\t}\n\terr := p.Create(context.Background(), options, c.Args()...)\n\tif err != nil {\n\t\treturn cli.NewExitError(err.Error(), 1)\n\t}\n\treturn nil\n}", "func (options *CreateWorkspaceOptions) SetTemplateData(templateData []TemplateSourceDataRequest) *CreateWorkspaceOptions {\n\toptions.TemplateData = templateData\n\treturn options\n}", "func (c *Client) GenerateWorkspaceTemplateWorkflowTemplate(workspaceTemplate *WorkspaceTemplate) (workflowTemplate *WorkflowTemplate, err error) {\n\tworkflowTemplate, err = c.generateWorkspaceTemplateWorkflowTemplate(workspaceTemplate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn workflowTemplate, nil\n}", "func InitStageTemplates(client clientset.Interface, systemNamespace, scene string) {\n\t// Load all stage templates. Template files path is given by environment variable\n\t// TEMPLATES_PATH, if not set, use default one \"/root/templates\"\n\tloader := &StageTemplatesLoader{TemplatesDir: os.Getenv(TemplatesPathEnvName)}\n\tstages, err := loader.LoadStageTemplates(scene)\n\tif err != nil {\n\t\tlog.Errorf(\"Load stage templates error: %v\", err)\n\t\treturn\n\t}\n\tlog.Infof(\"%d stage templates loaded.\", len(stages))\n\n\t// Create all stage templates\n\tfor _, stg := range stages {\n\t\t_, err := client.CycloneV1alpha1().Stages(systemNamespace).Create(context.TODO(), stg, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\tif errors.IsAlreadyExists(err) {\n\t\t\t\tlog.Infof(\"Stage template '%s' already exist, skip it.\", stg.Name)\n\t\t\t} else {\n\t\t\t\tlog.Errorf(\"Create stage template '%s' error: %v\", stg.Name, err)\n\t\t\t}\n\t\t}\n\t}\n}", "func (e *rhcosEditor) CreateMinimalISOTemplate(fullISOPath, rootFSURL, arch, minimalISOPath string) error {\n\textractDir, err := os.MkdirTemp(e.workDir, \"isoutil\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = Extract(fullISOPath, extractDir); err != nil {\n\t\treturn err\n\t}\n\n\tif err = os.Remove(filepath.Join(extractDir, \"images/pxeboot/rootfs.img\")); err != nil {\n\t\treturn err\n\t}\n\n\tif err = embedInitrdPlaceholders(extractDir); err != nil {\n\t\tlog.WithError(err).Warnf(\"Failed to embed initrd placeholders\")\n\t\treturn err\n\t}\n\n\tif err = fixGrubConfig(rootFSURL, extractDir); err != nil {\n\t\tlog.WithError(err).Warnf(\"Failed to edit grub config\")\n\t\treturn err\n\t}\n\t// ignore isolinux.cfg for ppc64le because it doesn't exist\n\tif arch != \"ppc64le\" {\n\t\tif err = fixIsolinuxConfig(rootFSURL, extractDir); err != nil {\n\t\t\tlog.WithError(err).Warnf(\"Failed to edit isolinux config\")\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvolumeID, err := VolumeIdentifier(fullISOPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = Create(minimalISOPath, extractDir, volumeID); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func generateReadmeAndChanges(path, importPath, apiName string) error {\n\treadmePath := filepath.Join(path, \"README.md\")\n\tlog.Printf(\"Creating %q\", readmePath)\n\treadmeFile, err := os.Create(readmePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer readmeFile.Close()\n\tt := template.Must(template.New(\"readme\").Parse(readmeTmpl))\n\treadmeData := struct {\n\t\tName string\n\t\tImportPath string\n\t}{\n\t\tName: apiName,\n\t\tImportPath: importPath,\n\t}\n\tif err := t.Execute(readmeFile, readmeData); err != nil {\n\t\treturn err\n\t}\n\n\tchangesPath := filepath.Join(path, \"CHANGES.md\")\n\tlog.Printf(\"Creating %q\", changesPath)\n\tchangesFile, err := os.Create(changesPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer changesFile.Close()\n\t_, err = changesFile.WriteString(\"# Changes\\n\")\n\treturn err\n}", "func newCreateFile() *cobra.Command {\n\tvar (\n\t\toptions core.CreateFileOptions\n\t)\n\tcreateFileCmd := cobra.Command{\n\t\tUse: \"file NAME\",\n\t\tShort: `Create a new content file`,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tpath := args[0]\n\t\t\treturn core.CreateFile(path, options)\n\t\t},\n\t}\n\n\tcreateFileCmd.Flags().StringVarP(&options.Project, \"project\", \"p\", \".\", `project path to create file in.`)\n\n\treturn &createFileCmd\n}", "func NewProject() *app.Command {\n\tdesc := \"Create a project.\"\n\tcmd := app.NewCommand(\"project\", desc, func(ctx *app.Context) error {\n\t\targs := &struct {\n\t\t\tGroup string `option:\"group\"`\n\t\t\tArtifact string `option:\"artifact\"`\n\t\t}{}\n\t\tif err := config.Unmarshal(args); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif args.Group == \"\" {\n\t\t\treturn errors.New(\"group is missing\")\n\t\t}\n\n\t\twd, err := os.Getwd()\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"acquire work directory failed\")\n\t\t}\n\n\t\tif len(ctx.Args()) == 0 {\n\t\t\treturn errors.New(\"project name is missing\")\n\t\t}\n\n\t\tname := ctx.Args()[0]\n\t\tif args.Artifact == \"\" {\n\t\t\targs.Artifact = name\n\t\t}\n\n\t\t// check dir exist\n\t\tdir := filepath.Join(wd, name)\n\t\tif file.Exist(dir) {\n\t\t\treturn errors.New(\"directory already exist: \" + dir)\n\t\t}\n\n\t\tdata := map[string]string{\n\t\t\t\"GroupID\": args.Group,\n\t\t\t\"ArtifactID\": args.Artifact,\n\t\t}\n\n\t\t// create files\n\t\tfiles := make(map[string]string)\n\t\tfiles[filepath.Join(dir, \"pom.xml\")] = \"project/pom.xml\"\n\t\tfiles[filepath.Join(dir, \"README.md\")] = \"project/README.md\"\n\t\tfiles[filepath.Join(dir, \".gitignore\")] = \"project/gitignore\"\n\t\tif err = tpl.Execute(files, data); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Println(\"finished.\")\n\t\treturn nil\n\t})\n\tcmd.Flags.Register(flag.Help)\n\tcmd.Flags.String(\"group\", \"g\", \"\", \"group id\")\n\tcmd.Flags.String(\"artifact\", \"a\", \"\", \"artifact id\")\n\treturn cmd\n}", "func templateFunctionSnippet(entry *registry.Entry) func(name string) (interface{}, error) {\n\treturn func(name string) (interface{}, error) {\n\t\tglog.V(log.LevelDebug).Infof(\"template: name '%s'\", name)\n\n\t\ttemplate, err := getTemplate(name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttemplate, err = renderTemplate(template, entry, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar value interface{}\n\n\t\tif err := json.Unmarshal(template.Template.Raw, &value); err != nil {\n\t\t\treturn nil, errors.NewConfigurationError(\"template not JSON formatted: %v\", err)\n\t\t}\n\n\t\tglog.V(log.LevelDebug).Infof(\"template: value '%v'\", value)\n\n\t\treturn value, nil\n\t}\n}", "func execNew(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := template.New(args[0].(string))\n\tp.Ret(1, ret)\n}", "func (o *CreateQuickstartOptions) Run() error {\n\tinstallOpts := InstallOptions{\n\t\tCommonOptions: CommonOptions{\n\t\t\tFactory: o.Factory,\n\t\t\tOut: o.Out,\n\t\t},\n\t}\n\tuserAuth, err := installOpts.getGitUser(\"git username to create the quickstart\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tauthConfigSvc, err := o.Factory.CreateGitAuthConfigService()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar server *auth.AuthServer\n\tconfig := authConfigSvc.Config()\n\tif o.GitHub {\n\t\tserver = config.GetOrCreateServer(gits.GitHubHost)\n\t} else {\n\t\tif o.GitHost != \"\" {\n\t\t\tserver = config.GetOrCreateServer(o.GitHost)\n\t\t} else {\n\t\t\tserver, err = config.PickServer(\"Pick the git server to search for repositories\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tif server == nil {\n\t\treturn fmt.Errorf(\"no git server provided\")\n\t}\n\n\to.GitProvider, err = gits.CreateProvider(server, userAuth)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmodel, err := o.LoadQuickstarts()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to load quickstarts: %s\", err)\n\t}\n\tq, err := model.CreateSurvey(&o.Filter)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif q == nil {\n\t\treturn fmt.Errorf(\"no quickstart chosen\")\n\t}\n\n\tdir := o.OutDir\n\tif dir == \"\" {\n\t\tdir, err = os.Getwd()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tgenDir, err := o.createQuickstart(q, dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Printf(\"Created project at %s\\n\\n\", util.ColorInfo(genDir))\n\n\to.CreateProjectOptions.ImportOptions.GitProvider = o.GitProvider\n\to.Organisation = userAuth.Username\n\treturn o.ImportCreatedProject(genDir)\n}", "func createFolderStructure(templatePath string) error {\n\tpath := filepath.Dir(templatePath)\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\terr := os.MkdirAll(path, 0755) //TODO: use dir mode if available\n\t\tif err != nil {\n\t\t\tfmt.Errorf(\"Could not create dir structure for template destPath %s, error: %v\", templatePath, err)\n\t\t}\n\t}\n\treturn nil\n}", "func create_site() {\n\n\tcreate_dirs()\n\tcreate_theme_files()\n}", "func GenerateTemplates() error {\n\n\t// ensure qtc is available\n\tif err := exsh.EnsureGoBin(\"qtc\", \"github.com/valyala/quicktemplate/qtc\"); err != nil {\n\t\treturn err\n\t}\n\n\t// run qtc command\n\tif err := sh.Run(\"qtc\", \"-dir=\"+templateDir, \"-skipLineComments\"); err != nil {\n\t\treturn err\n\t}\n\n\t// move templates from templateDir to the corresponding location in ./internal/pages\n\terr := filepath.Walk(\n\t\ttemplateDir,\n\t\tfunc(filename string, info os.FileInfo, err error) error {\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif strings.HasSuffix(filename, \".qtpl.go\") {\n\t\t\t\tnewFilename := strings.Replace(filename, templateDir, generatedTemplatesOutputDir, 1)\n\n\t\t\t\tif mg.Verbose() {\n\t\t\t\t\tfmt.Printf(\"Moving %s to %s\\n\", filename, newFilename)\n\t\t\t\t}\n\n\t\t\t\tif err := sh.Copy(newFilename, filename); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn sh.Rm(filename)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t)\n\n\treturn err\n}", "func Create(app string, flags string, extensions string, tpl string) Wrapper {\n\tw := Wrapper{\n\t\tNoHighlight: true,\n\t\tDoTOC: true,\n\t\tDoStandalone: false,\n\t\tDoNumericalHeadings: false,\n\t}\n\tw.create(app, flags, extensions, tpl)\n\treturn w\n}", "func (c *Client) GetWorkspaceTemplate(namespace, uid string, version int64) (workspaceTemplate *WorkspaceTemplate, err error) {\n\tsb := c.workspaceTemplateVersionsSelectBuilder(namespace, uid).\n\t\tLimit(1)\n\n\tsb = sb.Where(sq.Eq{\"wt.is_archived\": false})\n\n\tif version == 0 {\n\t\tsb = sb.Where(sq.Eq{\n\t\t\t\"wtv.is_latest\": true,\n\t\t\t\"wftv.is_latest\": true,\n\t\t})\n\t} else {\n\t\tsb = sb.Where(sq.Eq{\n\t\t\t\"wtv.version\": version,\n\t\t\t\"wftv.version\": version,\n\t\t})\n\t}\n\n\tworkspaceTemplate = &WorkspaceTemplate{}\n\tif err = c.DB.Getx(workspaceTemplate, sb); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\treturn\n\t}\n\n\tsysConfig, err := c.GetSystemConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := workspaceTemplate.InjectRuntimeParameters(sysConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn\n}", "func (csets *CloudSpecificExtensionTemplateService) CreateTemplate(\n\ttemplateParams *map[string]interface{},\n) (template *types.CloudSpecificExtensionTemplate, err error) {\n\tlog.Debug(\"CreateTemplate\")\n\n\tdata, status, err := csets.concertoService.Post(APIPathCseTemplates, templateParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = utils.CheckStandardStatus(status, data); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = json.Unmarshal(data, &template); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn template, nil\n}", "func newCloudFormationTemplates(c *ServiceoperatorV1alpha1Client, namespace string) *cloudFormationTemplates {\n\treturn &cloudFormationTemplates{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}", "func bootstrapTemplateNamePrefix(clusterName, machineDeploymentTopologyName string) string {\n\treturn fmt.Sprintf(\"%s-%s-\", clusterName, machineDeploymentTopologyName)\n}", "func (c *Config) tastWorkspace() string {\n\treturn filepath.Join(c.trunkDir, \"src/platform/tast\")\n}", "func promptToDeletePrevProject(prevProjPath string) {\n\t// var shouldUndo = askBooleanQuestion(false, \"QUESTION: Delete the cloned previous version of the project?\")\n\t// if shouldUndo {\n\t// \tdeleteAllFiles(prevProjPath)\n\t// \tcolor.Style{color.Green}.Print(\"\\nFinished deleting\\n\")\n\t// }\n\tvar projectLocation = trimPathAfterLastSlash(prevProjPath) //get project location\n\tvar isFound, _ = searchForFilePath(projectLocation, trimPathBeforeLastSlash(prevProjPath, false)) //look for a prevProject from project locaation where the project and prevProject should be store\n\t// print(\"\\n\")\n\tif isFound { //if clonedProject already exist, delete it and create a new clone\n\t\t// color.Style{color.Red}.Print(\"Deleting \", trimPathBeforeLastSlash(prevProjPath, false), \"... \")\n\t\tdeleteAllFiles(prevProjPath)\n\t\t// color.Style{color.Red, color.Bold}.Print(\"Deleted. \")\n\t}\n}" ]
[ "0.49752992", "0.49527052", "0.48761147", "0.48284465", "0.4793886", "0.45810252", "0.44825286", "0.4462606", "0.4437953", "0.43855366", "0.43842992", "0.438213", "0.43730313", "0.43259045", "0.43124765", "0.42978927", "0.42976612", "0.42841607", "0.42832598", "0.42819938", "0.42697626", "0.4265472", "0.42619863", "0.42280033", "0.41975427", "0.41719323", "0.41642302", "0.4147565", "0.41356117", "0.41350973", "0.41253096", "0.4122009", "0.41216722", "0.4100958", "0.4093073", "0.4070699", "0.4056486", "0.40552524", "0.40481246", "0.40447274", "0.40180364", "0.40066594", "0.39865154", "0.3978916", "0.39744636", "0.3967719", "0.39671952", "0.3966951", "0.39625654", "0.3951675", "0.3945946", "0.39448825", "0.3941078", "0.39386097", "0.39341608", "0.39329997", "0.39267695", "0.3919491", "0.39066067", "0.39009315", "0.38974681", "0.38958552", "0.38920444", "0.38911736", "0.3885259", "0.38777182", "0.3866568", "0.38650078", "0.38629594", "0.3861044", "0.38535237", "0.38521817", "0.38501436", "0.38483045", "0.38469225", "0.38408837", "0.38335258", "0.3832902", "0.3831991", "0.383033", "0.382379", "0.3823315", "0.3823112", "0.38129804", "0.3811662", "0.3807324", "0.38063154", "0.37970182", "0.3792269", "0.37849835", "0.37776443", "0.37772667", "0.37771854", "0.37723735", "0.3772163", "0.37681875", "0.37663388", "0.3765736", "0.37562838", "0.37542018" ]
0.5603818
0
Down20200929144301 removes Visual Studio Code from workspace templates.
func Down20200929144301(tx *sql.Tx) error { client, err := getClient() if err != nil { return err } namespaces, err := client.ListOnepanelEnabledNamespaces() if err != nil { return err } uid, err := uid2.GenerateUID(vscodeWorkspaceTemplateName, 30) if err != nil { return err } for _, namespace := range namespaces { if _, err := client.ArchiveWorkspaceTemplate(namespace.Name, uid); err != nil { return err } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Up20200929144301(tx *sql.Tx) error {\n\tclient, err := getClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer client.DB.Close()\n\n\tmigrationsRan, err := getRanSQLMigrations(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, ok := migrationsRan[20200929144301]; ok {\n\t\treturn nil\n\t}\n\n\tnamespaces, err := client.ListOnepanelEnabledNamespaces()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tworkspaceTemplate := &v1.WorkspaceTemplate{\n\t\tName: vscodeWorkspaceTemplateName,\n\t\tManifest: vscodeWorkspaceTemplate,\n\t}\n\n\t// Adding description\n\tworkspaceTemplate.Description = \"Open source code editor\"\n\n\tfor _, namespace := range namespaces {\n\t\tif _, err := client.CreateWorkspaceTemplate(namespace.Name, workspaceTemplate); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func FixWorkspace(f *rule.File) {\n\tremoveLegacyGoRepository(f)\n}", "func fixTemplateNames(templates []string) {\n\tfor i := range templates {\n\t\ttemplates[i] = \"templates/\" + templates[i]\n\t}\n}", "func RevertTemplate(name string) error {\n\treturn pathx.CreateTemplate(category, name, deploymentTemplate)\n}", "func projectCleanup(env environment.Environment, macro *model.Macro) error {\n\tpartialComparisonService := env.ServiceFactory().MustPartialComparisonService()\n\treturn partialComparisonService.DeleteFrom(macro)\n}", "func undoUtilityChanges(prevProjPath, projPath string) {\n\tfiles, err := ioutil.ReadDir(prevProjPath) //ReadDir returns a slice of FileInfo structs\n\tif isError(err) {\n\t\treturn\n\t}\n\tfor _, file := range files { //loop through each files and directories from previous project\n\t\tvar fileName = file.Name()\n\t\tif file.IsDir() { //if directory...\n\t\t\tif fileName == \"Pods\" || fileName == \".git\" { //ignore Pods and .git directories\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tprevProjPath = prevProjPath + \"/\" + fileName //update directory path by adding /fileName\n\t\t\tundoUtilityChanges(prevProjPath, projPath) //recursively call this function again\n\t\t\tprevProjPath = trimPathAfterLastSlash(prevProjPath) //reset path by removing the / + fileName\n\t\t} else { //for each .swift and .strings file in previous project\n\t\t\tvar fileExtension = filepath.Ext(strings.TrimSpace(fileName)) //gets the file extension from file name\n\t\t\tif fileExtension == \".swift\" || fileExtension == \".strings\" { //only undo .swift and .strings files\n\t\t\t\tvar prevProjPathToSearch = trimPathBeforeLastSlash(prevProjPath, false) + \"/\" + fileName //get the path of a language file e.g. \"en.lproj/Localize.strings\"\n\t\t\t\tprevProjPath = prevProjPath + \"/\" + fileName //update the prevProjPath like always\n\t\t\t\tvar isFound, filePath = searchForFilePath(projPath, prevProjPathToSearch) //search project for file with the same name as .swift file from previour version\n\t\t\t\tif isFound { //if found... read both file's content\n\t\t\t\t\tvar prevProjContents = readFile(prevProjPath)\n\t\t\t\t\tvar currentProjContents = readFile(filePath)\n\t\t\t\t\tif prevProjContents != currentProjContents { //if contents are not the same, replace project's file contents with the previous project's contents\n\t\t\t\t\t\t// fmt.Println(\"\\nCopying contents of \" + prevProjPath + \" to \" + filePath)\n\t\t\t\t\t\treplaceFile(filePath, prevProjContents)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Print(\"Error: Failed to find \", fileName, \" during undo. Please remove all changes using version control instead.\\n\")\n\t\t\t\t}\n\t\t\t\tprevProjPath = trimPathAfterLastSlash(prevProjPath) //reset path by removing the / + fileName\n\t\t\t}\n\t\t}\n\t}\n}", "func cleanOldNodes(assets assets, target string) {\n\td, err := os.ReadDir(target)\n\tif err != nil {\n\t\treturn\n\t}\n\t// Find deleted nodes by selecting one generated\n\t// file from standard templates (<T>_query.go).\n\tvar deleted []*Type\n\tfor _, f := range d {\n\t\tif !strings.HasSuffix(f.Name(), \"_query.go\") {\n\t\t\tcontinue\n\t\t}\n\t\ttyp := &Type{Name: strings.TrimSuffix(f.Name(), \"_query.go\")}\n\t\tpath := filepath.Join(target, typ.PackageDir())\n\t\tif _, ok := assets.dirs[path]; ok {\n\t\t\tcontinue\n\t\t}\n\t\t// If it is a node, it must have a model file and a dir (e.g. ent/t.go, ent/t).\n\t\t_, err1 := os.Stat(path + \".go\")\n\t\tf2, err2 := os.Stat(path)\n\t\tif err1 == nil && err2 == nil && f2.IsDir() {\n\t\t\tdeleted = append(deleted, typ)\n\t\t}\n\t}\n\tfor _, typ := range deleted {\n\t\tfor _, t := range Templates {\n\t\t\terr := os.Remove(filepath.Join(target, t.Format(typ)))\n\t\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\t\tlog.Printf(\"remove old file %s: %s\\n\", filepath.Join(target, t.Format(typ)), err)\n\t\t\t}\n\t\t}\n\t\terr := os.Remove(filepath.Join(target, typ.PackageDir()))\n\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\tlog.Printf(\"remove old dir %s: %s\\n\", filepath.Join(target, typ.PackageDir()), err)\n\t\t}\n\t}\n}", "func cleanUpAfterProjects(projects []string) {\n\tfor _, p := range projects {\n\t\todoDeleteProject(p)\n\t}\n}", "func RemoveView(name string) {\n\tfmt.Println()\n\tRemoveFile(ViewFilename(name))\n\tRemoveFile(SassFilename(name))\n\tRemoveFile(TemplateFilename(name))\n\tRemoveFile(CssFilename(name))\n\tRemoveLinkTag(name)\n\tfmt.Println()\n}", "func deleteClonedProject(path string) {\n\tos.RemoveAll(path)\n}", "func (ct *ContentTypes) RemoveContent(fileName string) {\n\tfor i, part := range ct.ml.Overrides {\n\t\tif part.PartName == fileName {\n\t\t\tct.ml.Overrides = append(ct.ml.Overrides[:i], ct.ml.Overrides[i+1:]...)\n\t\t\tct.file.MarkAsUpdated()\n\t\t\treturn\n\t\t}\n\t}\n}", "func CleanUp(ctx context.Context, cfg *config.Config, pipeline *pipelines.Pipeline, name names.Name) error {\n\tkubectlPath, err := cfg.Tools[config.Kubectl].Resolve()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd := proc.GracefulCommandContext(ctx, kubectlPath, \"delete\",\n\t\t\"all\",\n\t\t\"-l\", k8s.StackLabel+\"=\"+name.DNSName(),\n\t)\n\tif err := cmd.Run(); err != nil {\n\t\treturn fmt.Errorf(\"could not delete k8s resources: %v\", err)\n\t}\n\treturn nil\n}", "func removeText(fileName string) {\n\t//Skip main.go file\n\tif fileName != \"main.go\" {\n\t\t//Read file bytes from filename param, a success call return err==null, not err==EOF\n\t\tinput, err := ioutil.ReadFile(fileName)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\n\t\t//Convert content to string\n\t\ttext := string(input)\n\n\t\t//Replace keyword 'TODO' by regex\n\t\tre := regexp.MustCompile(\".*TODO.*\\r?\\n\")\n\t\tlines := re.ReplaceAllString(text, \"\")\n\n\t\t//Write string into a file\n\t\terr = WriteToFile(fileName, lines)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}", "func (c *Lang) cleanLang(code string) error {\n\ts := c.langFileName(\"tmp_dir\", code)\n\terr := ioutil.WriteFile(s, []byte(\"[]\"), 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.Remove(s)\n\treturn i18n.LoadTranslationFile(s)\n}", "func removeTestFiles(defDir string) {\n\t// svcout dir\n\tos.RemoveAll(filepath.Join(defDir, \"metaverse\"))\n\t// service dir\n\tos.RemoveAll(filepath.Join(defDir, \"test-service\"))\n\t// where the binaries are compiled to\n\tos.RemoveAll(filepath.Join(defDir, \"bin\"))\n\t// Remove all the .pb.go files which may remain\n\tdirs, _ := ioutil.ReadDir(defDir)\n\tfor _, d := range dirs {\n\t\tif strings.HasSuffix(d.Name(), \".pb.go\") {\n\t\t\tos.RemoveAll(filepath.Join(defDir, d.Name()))\n\t\t}\n\t}\n}", "func Delete(c *cli.Context) {\n\tprinter.Progress(\"Kombusting\")\n\n\tfileName := c.Args().Get(0)\n\tif fileName == \"\" {\n\t\tprinter.Fatal(\n\t\t\tfmt.Errorf(\"Can't upsert file, no source template provided\"),\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"Add the path to the source template file you want to generate like: `kombustion upsert template.yaml`.\",\n\t\t\t),\n\t\t\t\"https://www.kombustion.io/api/manifest/\",\n\t\t)\n\t}\n\n\tmanifestFile := manifest.FindAndLoadManifest()\n\n\tenvironment := c.String(\"environment\")\n\n\tstackName := cloudformation.GetStackName(manifestFile, fileName, environment, c.String(\"stack-name\"))\n\n\tregion := c.String(\"region\")\n\tif region == \"\" {\n\t\t// If no region was provided by the cli flag, check for the default in the manifest\n\t\tif manifestFile.Region != \"\" {\n\t\t\tregion = manifestFile.Region\n\t\t}\n\t}\n\n\ttasks.DeleteStack(\n\t\tstackName,\n\t\tc.GlobalString(\"profile\"),\n\t\tregion,\n\t)\n}", "func removeNoImportAndDeployToSystem(config *gctsDeployOptions, httpClient piperhttp.Sender) error {\n\tlog.Entry().Infof(\"Removing VCS_NO_IMPORT configuration\")\n\tconfigToDelete := \"VCS_NO_IMPORT\"\n\tdeleteConfigKeyErr := deleteConfigKey(config, httpClient, configToDelete)\n\tif deleteConfigKeyErr != nil {\n\t\tlog.Entry().WithError(deleteConfigKeyErr).Error(\"step execution failed at Set Config key for VCS_NO_IMPORT\")\n\t\treturn deleteConfigKeyErr\n\t}\n\t// Get deploy scope and gctsDeploy\n\tlog.Entry().Infof(\"gCTS Deploy: Deploying Commit to ABAP System for Repository %v with scope %v\", config.Repository, config.Scope)\n\tdeployErr := deployCommitToAbapSystem(config, httpClient)\n\tif deployErr != nil {\n\t\tlog.Entry().WithError(deployErr).Error(\"step execution failed at Deploying Commit to ABAP system.\")\n\t\treturn deployErr\n\t}\n\treturn nil\n}", "func Clean (current string) string {\n\n // Remove unicode characters.\n formatted := html2text.HTML2Text(current)\n // Remove specific characters.\n formatted = strings.Replace(formatted, \"\\n\", \" \", -1)\n formatted = strings.Replace(formatted, \"\\r\", \" \", -1)\n\n // Final unicode removal (specific to code sections).\n return html2text.HTML2Text(formatted)\n}", "func removeWebConsoleCustomization(k *kabanerov1alpha1.Kabanero) error {\n\t// Create a clientset to drive API operations on resources.\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get a copy of the web-console ConfigMap.\n\tcm, err := getWebConsoleConfigMap(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get the embedded yaml entry in the web console ConfigMap yaml.\n\twccyaml := cm.Data[\"webconsole-config.yaml\"]\n\tm := make(map[string]interface{})\n\terr = yaml.Unmarshal([]byte(wccyaml), &m)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Update the extensions section of the embedded webconsole-config.yaml entry\n\tlandingURL, err := getLandingURL(k, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tscripts, ssheets := getCustomizationURLs(landingURL)\n\n\tfor k, v := range m {\n\t\tif k == \"extensions\" {\n\t\t\textmap := v.(map[interface{}]interface{})\n\t\t\tfor kk, vv := range extmap {\n\t\t\t\tif kk == \"scriptURLs\" {\n\t\t\t\t\tif vv != nil {\n\t\t\t\t\t\tsu := vv.([]interface{})\n\t\t\t\t\t\tvar esu []interface{}\n\t\t\t\t\t\tfor _, s := range su {\n\t\t\t\t\t\t\tif isInStringList(scripts, s.(string)) {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tesu = append(esu, s)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\textmap[kk] = esu\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif kk == \"stylesheetURLs\" {\n\t\t\t\t\tif vv != nil {\n\t\t\t\t\t\tssu := vv.([]interface{})\n\t\t\t\t\t\tvar essu []interface{}\n\n\t\t\t\t\t\tfor _, ss := range ssu {\n\t\t\t\t\t\t\tif isInStringList(ssheets, ss.(string)) {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tessu = append(essu, ss)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\textmap[kk] = essu\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tm[k] = extmap\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Update our copy of the web console yaml and update it.\n\tupatedCMBytes, err := yaml.Marshal(m)\n\tcm.Data[\"webconsole-config.yaml\"] = string(upatedCMBytes)\n\t_, err = yaml.Marshal(cm)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkllog.Info(fmt.Sprintf(\"removeWebConsoleCustomization: ConfigMap for update: %v\", cm))\n\n\t_, err = clientset.CoreV1().ConfigMaps(\"openshift-web-console\").Update(cm)\n\n\treturn err\n}", "func removePython2(pyPackages []*cipd.Package) []*cipd.Package {\n\tvar python3Pkgs []*cipd.Package\n\tfor _, p := range pyPackages {\n\t\tif strings.HasPrefix(p.Version, \"version:[email protected]\") {\n\t\t\tcontinue\n\t\t}\n\t\tpython3Pkgs = append(python3Pkgs, p)\n\t}\n\treturn python3Pkgs\n}", "func Down_20130702202327(txn *sql.Tx) {\n\t_, err := txn.Exec(\"DROP TABLE IF EXISTS projects, components, repositories, types, jobs, owners, authentication;\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = txn.Commit()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func cleanProjectName(projectName string) string {\n\treturn projectNameCleanRegexp.ReplaceAllString(projectName, \"-\")\n}", "func ProjectDown(p project.APIProject, c *cli.Context) error {\n\toptions := options.Down{\n\t\tRemoveVolume: c.Bool(\"volumes\"),\n\t\tRemoveImages: options.ImageType(c.String(\"rmi\")),\n\t\tRemoveOrphans: c.Bool(\"remove-orphans\"),\n\t}\n\terr := p.Down(context.Background(), options, c.Args()...)\n\tif err != nil {\n\t\treturn cli.NewExitError(err.Error(), 1)\n\t}\n\treturn nil\n}", "func StopUp(_ *context.ExecuteContext, t *Task) error {\n\tt.logger().Info(\"project stop\")\n\treturn t.execCompose(\"stop\", \"-t\", t.config.StopGraceString())\n}", "func teardownFirecracker(ctx context.Context, runner commandRunner, logger *Logger, name string, options Options, operations *Operations) error {\n\tremoveCommand := command{\n\t\tKey: \"teardown.firecracker.remove\",\n\t\tCommand: flatten(\"ignite\", \"rm\", \"-f\", name),\n\t\tOperation: operations.TeardownFirecrackerRemove,\n\t}\n\tif err := runner.RunCommand(ctx, removeCommand, logger); err != nil {\n\t\tlog15.Error(\"Failed to remove firecracker vm\", \"name\", name, \"err\", err)\n\t}\n\n\treturn nil\n}", "func removeTempRepos() {\n\tos.RemoveAll(\"/tmp/github.com\")\n}", "func Remove(base string) (err error) {\n\thooksFolder := filepath.Join(base, hooksPath())\n\n\t// The hooks folder must exist.\n\texists, err := helper.DoesPathExistErr(hooksFolder)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif !exists {\n\t\treturn fmt.Errorf(\"the hooks folder does not exist\")\n\t}\n\n\tif err = EnsureRemoveComment(preCommitFilepath(base), defaultBashComment); err != nil {\n\t\treturn\n\t}\n\n\tif err = EnsureRemoveComment(postCommitFilepath(base), defaultBashComment); err != nil {\n\t\treturn\n\t}\n\n\tklog.InfoS(\"Removed gogit replace lines\",\n\t\t\"from-pre-commit\", preCommitFilepath(base),\n\t\t\"from-post-commit\", postCommitFilepath(base),\n\t)\n\n\treturn nil\n}", "func Down20201209124226(tx *sql.Tx) error {\n\t// This code is executed when the migration is rolled back.\n\treturn updateWorkflowTemplateManifest(\n\t\tfilepath.Join(\"workflows\", \"tensorflow-mnist-training\", \"20200605090535.yaml\"),\n\t\ttensorflowWorkflowTemplateName,\n\t\tmap[string]string{\n\t\t\t\"framework\": \"tensorflow\",\n\t\t},\n\t)\n}", "func Up20201016170415(tx *sql.Tx) error {\n\t// This code is executed when the migration is applied.\n\treturn updateWorkspaceTemplateManifest(\n\t\tfilepath.Join(\"workspaces\", \"cvat\", \"20201016170415.yaml\"),\n\t\tcvatTemplateName)\n}", "func (r *LocalRegistry) removeFiles(pack *Package, artHome string) error {\n\t// remove the zip file\n\terr := os.Remove(fmt.Sprintf(\"%s/%s.zip\", core.RegistryPath(artHome), pack.FileRef))\n\tif err != nil {\n\t\treturn err\n\t}\n\t// remove the json file\n\treturn os.Remove(fmt.Sprintf(\"%s/%s.json\", core.RegistryPath(artHome), pack.FileRef))\n}", "func Clean(category string) error {\n\tdir, err := GetTemplateDir(category)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn os.RemoveAll(dir)\n}", "func FixupSDKMismatch(template map[string]interface{}) error {\n\tfor _, resource := range jsonpath.MustCompile(\"$.resources.*\").Get(template) {\n\t\ttyp := jsonpath.MustCompile(\"$.type\").MustGetString(resource)\n\t\tname := jsonpath.MustCompile(\"$.name\").MustGetString(resource)\n\t\t// inject management vnet conigurations into the VNET config\n\t\tif typ == \"Microsoft.Network/virtualNetworks\" && name == armconst.VnetName {\n\t\t\tjsonpath.MustCompile(\"$.apiVersion\").Set(resource, \"2019-04-01\")\n\t\t\tfor _, subnet := range jsonpath.MustCompile(\"$.properties.subnets.*\").Get(resource) {\n\t\t\t\tname := jsonpath.MustCompile(\"$.name\").MustGetString(subnet)\n\t\t\t\tif name == armconst.VnetManagementSubnetName {\n\t\t\t\t\tjsonpath.MustCompile(\"$.properties.privateEndpointNetworkPolicies\").Set(subnet, \"Disabled\")\n\t\t\t\t\tjsonpath.MustCompile(\"$.properties.privateLinkServiceNetworkPolicies\").Set(subnet, \"Disabled\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\treturn nil\n}", "func main() {\n\t// go through each directory in go using os package\n\thtmlFiles := []string{}\n\toutputFolder := \"gh-pages\"\n\treg := []string{\"rm\", \"-rf\", outputFolder}\n\tcmd := strings.Join(reg[:], \" \")\n\n\ttmpl := `\n\t<html>\n\t\t<head>\n\t\t\t<title>List of Matlab Reports and Files</title>\n\t\t</head>\n\t\t<body>\n\t\t\t<h1>List of Files</h1>\n\t\t\t<ul>\n\t\t\t{{ range . }}\n\t\t\t\t<li><a href={{.}}>{{ . }}</a></li>\n\t\t\t{{ end }}\n\t\t\t</ul>\n\t\t</body>\n\t</html>\n\t`\n\tscript.IfExists(outputFolder).Exec(cmd).Stdout()\n\tscript.FindFiles(\".\").FilterScan(func(line string, w io.Writer) {\n\t\t// if line contains html print it\n\t\tif strings.Contains(line, \".html\") || strings.Contains(line, \".pdf\") {\n\t\t\tfmt.Fprintf(w, \"scanned line: %q\\n\", line)\n\t\t\thtmlFiles = append(htmlFiles, line)\n\t\t}\n\t}).Stdout()\n\n\tfmt.Println(htmlFiles)\n\t// create html directory\n\tscript.Exec(\"mkdir \" + outputFolder).Stdout()\n\n\t// for each html file\n\tfor _, file := range htmlFiles {\n\t\treg = []string{\"cp\", file, outputFolder}\n\t\tcmd = strings.Join(reg[:], \" \")\n\t\t// copy file to html directory\n\t\tscript.Exec(cmd).Stdout()\n\t}\n\n\t// move ads.txt to html directory\n\tscript.Exec(\"mv ads.txt \" + outputFolder).Stdout()\n\n\tt, err := template.New(\"files\").Parse(tmpl)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfile, err := os.Create(outputFolder + \"/index.html\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tdefer file.Close()\n\t// remove outputFolder from htmlFiles\n\tfor i, file := range htmlFiles {\n\t\t// get basename of file\n\t\tbaseName := filepath.Base(file)\n\t\thtmlFiles[i] = baseName\n\t}\n\terr = t.Execute(file, htmlFiles)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n}", "func TearDown() {\n\n\tcmd := exec.Command(\"/bin/sh\", \"-c\", \"sudo terraform destroy -auto-approve\")\n\tcmd.Dir = \"/home/ubuntu/terradir\"\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tcmd.Run()\n}", "func removeOnedrive() {\n\tensureRunning()\n\trunScript(onedriveScript)\n}", "func (m *Client_20200525_121200) Down() {\n\t// use m.SQL(\"DROP TABLE ...\") to reverse schema update\n\tm.SQL(\"DROP TABLE client\")\n\tm.SQL(\"DELETE FROM migrations WHERE name = 'Client_20200525_121200'\")\n}", "func ProjectSnippetDelete(pid interface{}, id int) error {\n\t_, err := lab.ProjectSnippets.DeleteSnippet(pid, id)\n\treturn err\n}", "func (self *WorkingTreeCommands) UnStageFile(fileNames []string, reset bool) error {\n\tfor _, name := range fileNames {\n\t\tvar cmdArgs []string\n\t\tif reset {\n\t\t\tcmdArgs = NewGitCmd(\"reset\").Arg(\"HEAD\", \"--\", name).ToArgv()\n\t\t} else {\n\t\t\tcmdArgs = NewGitCmd(\"rm\").Arg(\"--cached\", \"--force\", \"--\", name).ToArgv()\n\t\t}\n\n\t\terr := self.cmd.New(cmdArgs).Run()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func ClearCode(str string) string {\n\treturn codeRegex.ReplaceAllString(str, \"\")\n}", "func (self *WorkingTreeCommands) RemoveUntrackedFiles() error {\n\tcmdArgs := NewGitCmd(\"clean\").Arg(\"-fd\").ToArgv()\n\n\treturn self.cmd.New(cmdArgs).Run()\n}", "func (a *Artifact) Destroy() error {\n\tlog.Printf(\"Destroying template: %s\", a.templatePath)\n\ta.vim.DeleteVm(a.templatePath)\n\treturn nil\n}", "func cleanupChange(p4 p4lib.P4, change int) error {\n\tif _, err := p4.ExecCmd(\"revert\", \"-c\", strconv.Itoa(change), \"//...\"); err != nil {\n\t\treturn fmt.Errorf(\"could not revert change %d: %v\", change, err)\n\t}\n\tif _, err := p4.ExecCmd(\"change\", \"-d\", strconv.Itoa(change)); err != nil {\n\t\treturn fmt.Errorf(\"could not delete change %d: %v\", change, err)\n\t}\n\treturn nil\n}", "func destroyKnative() {\n\n\t//Make command options for Knative Setup\n\tco := utils.NewCommandOptions()\n\n\t//Install Openshift Serveless and Knative Serving\n\tco.Commands = append(co.Commands, \"https://raw.githubusercontent.com/redhat-iot/iot-dev/master/yamls/knative/setup/knative-eventing.yaml\")\n\n\tco.Commands = append(co.Commands, \"https://raw.githubusercontent.com/redhat-iot/iot-dev/master/yamls/knative/setup/knative-serving.yaml\")\n\tIOStreams, _, out, _ := genericclioptions.NewTestIOStreams()\n\n\tco.SwitchContext(\"knative-eventing\")\n\n\tlog.Info(\"Remove Openshift Serverless Operator and Knative Serving\")\n\tfor commandNumber, command := range co.Commands {\n\t\tif commandNumber == 1 {\n\t\t\tco.SwitchContext(\"knative-serving\")\n\t\t}\n\t\tcmd := delete.NewCmdDelete(co.CurrentFactory, IOStreams)\n\t\tcmd.Flags().Set(\"filename\", command)\n\t\tcmd.Run(cmd, []string{})\n\t\tlog.Info(out.String())\n\t\tout.Reset()\n\t\t//Allow time for Operator to distribute to all namespaces\n\t}\n\n\t/*\n\n\t\tcurrentCSV, err := exec.Command(\"bash\", \"-c\", \"./oc get subscription serverless-operator -n openshift-operators -o jsonpath='{.status.currentCSV}'\").Output()\n\t\terr = exec.Command(\"./oc\", \"delete\", \"subscription\", \"serverless-operator\", \"-n\", \"openshift-operators\").Run()\n\t\tif err != nil {\n\t\t\t//Ignore Resource Not found error and continue, but still notify the user\n\t\t\tlog.Println(err)\n\t\t}\n\t\terr = exec.Command(\"./oc\", \"delete\", \"clusterserviceversion\", string(currentCSV), \"-n\", \"openshift-operators\").Run()\n\t\tif err != nil {\n\t\t\t//Igonore Resource Not found error and continue, but still notify the user\n\t\t\tlog.Println(err)\n\t\t}\n\t\tos.Remove(\"oc\")\n\t*/\n\n}", "func CleanupCli(input string) string {\n\treturn Replace(input, \" \", `(\\s{2,}|\\t{1,}|\\n{1,})+`)\n}", "func destroyDeployment(toRemove string) {\n\tlog.Debug(\"Destroying deployment %s\", toRemove)\n\toldPwd := sh.Pwd()\n\ttoRemoveRepo := path.Join(toRemove, sh.Basename(repoURL))\n\tsh.Cd(toRemoveRepo)\n\n\tlog.Debugf(\"Actually destroying resources now\")\n\tcloudRe := regexp.MustCompile(`(gce|aws|digitalocean|openstack|softlayer)`)\n\tif cloudRe.MatchString(toRemove) {\n\t\tlog.Debug(\"Destroying terraformed resources in %s\", toRemoveRepo)\n\t\tterraformDestroy(toRemoveRepo)\n\t} else {\n\t\tlog.Debug(\"Destroying vagrant box in %s\", toRemoveRepo)\n\t\tsh.SetE(exec.Command(\"vagrant\", \"destroy\", \"-f\"))\n\t}\n\n\tsh.Cd(oldPwd)\n\tlog.Debugf(\"Removing leftovers in %s\", toRemove)\n\tsh.RmR(toRemove)\n\tlog.Debug(\"Finished destruction process\")\n}", "func removeContent(dir string) error {\n\td, err := os.Open(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer d.Close()\n\tnames, err := d.Readdirnames(-1)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, name := range names {\n\t\terr = os.RemoveAll(filepath.Join(dir, name))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func TestDeleteRepoFileWithoutBranchNames(t *testing.T) {\n\tonGiteaRun(t, testDeleteRepoFileWithoutBranchNames)\n}", "func (r *repoManager) cleanChromium() error {\n\tif _, err := exec.RunCwd(r.chromiumDir, \"git\", \"clean\", \"-d\", \"-f\", \"-f\"); err != nil {\n\t\treturn err\n\t}\n\t_, _ = exec.RunCwd(r.chromiumDir, \"git\", \"rebase\", \"--abort\")\n\tif _, err := exec.RunCwd(r.chromiumDir, \"git\", \"checkout\", \"origin/master\", \"-f\"); err != nil {\n\t\treturn err\n\t}\n\t_, _ = exec.RunCwd(r.chromiumDir, \"git\", \"branch\", \"-D\", DEPS_ROLL_BRANCH)\n\tif _, err := exec.RunCommand(&exec.Command{\n\t\tDir: r.chromiumDir,\n\t\tEnv: getEnv(r.depot_tools),\n\t\tName: r.gclient,\n\t\tArgs: []string{\"revert\", \"--nohooks\"},\n\t}); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func RemoveCommand(cmd *cobra.Command, args []string) error {\n\tinitConfig()\n\n\tfor _, fileArg := range args {\n\t\tfn := fileutil.NormalizeToPlaintextFile(fileArg)\n\n\t\ti := fileutil.ListIndexOf(sopsConfig.EncryptedFiles, fn)\n\t\tif i < 0 {\n\t\t\treturn fmt.Errorf(\"File not found: %s\", fn)\n\t\t}\n\n\t\t//splice file out of list\n\t\tsopsConfig.EncryptedFiles = append(sopsConfig.EncryptedFiles[:i], sopsConfig.EncryptedFiles[i+1:]...)\n\n\t\tif deleteFiles {\n\t\t\terr := execwrap.RemoveFile(fn)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = execwrap.RemoveSopsFile(fn)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tfmt.Println(\"removed file from list:\", fn)\n\t}\n\n\terr := sopsyaml.WriteEncryptFilesToDisk(sopsConfig.Path, sopsConfig.Tree, sopsConfig.EncryptedFiles)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DeleteTemplate(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"URL PATH - %s!\", r.URL.Path[1:])\n}", "func GenerateUnstakeTokensScript(env Environment) []byte {\n\tcode := assets.MustAssetString(unstakeTokensFilename)\n\n\treturn []byte(replaceAddresses(code, env))\n}", "func (Dev) Reset(ctx context.Context) error {\n\targ := BuildDockerComposeArgs(ProjectName, ProjectType, \"test\", DockerComposeDevFile)\n\targ = append(arg, \"down\")\n\treturn Exec(ComposeBin, arg...)\n}", "func removeOldBinFiles(search string) {\n\tif cmdOptions.Product == \"gpdb\" {\n\t\tremoveFiles(Config.DOWNLOAD.DOWNLOADDIR, fmt.Sprintf(\"*%s*.bin*\", cmdOptions.Version))\n\t\tremoveFiles(Config.DOWNLOAD.DOWNLOADDIR, \"*README_INSTALL*\")\n\t} else if cmdOptions.Product == \"gpcc\" && !isThis4x() {\n\t\tremoveFiles(Config.DOWNLOAD.DOWNLOADDIR, fmt.Sprintf(\"*%s*.bin*\", cmdOptions.CCVersion))\n\t\tremoveFiles(Config.DOWNLOAD.DOWNLOADDIR, \"*README_INSTALL*\")\n\t} else { // GPCC 4.x has folder into folders\n\t\tallfiles, _ := FilterDirsGlob(Config.DOWNLOAD.DOWNLOADDIR, fmt.Sprintf(\"%s\", search))\n\t\tfor _, v := range allfiles {\n\t\t\tif !strings.HasSuffix(v, \".zip\") {\n\t\t\t\tdeleteFile(v)\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *PBFTServer) removeOldViewChange(seq int) {\n\tfor k := range s.vcs {\n\t\tif k < seq {\n\t\t\tdelete(s.vcs, k)\n\t\t}\n\t}\n}", "func reifyNewSite(goProjectPath, projectPath string) error {\n\tfiles, err := collectFiles(projectPath, []string{\".go\"})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// For each go file within project, make sure the refs are to the new site,\n\t// not to the template site\n\trelGoProjectPath := projectPathRelative(goProjectPath)\n\trelProjectPath := projectPathRelative(projectPath)\n\tfor _, f := range files {\n\t\t// Load the file, if it contains refs to goprojectpath, replace them with relative project path imports\n\t\tdata, err := ioutil.ReadFile(f)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Substitutions - consider reifying instead if it is any more complex\n\t\tfileString := string(data)\n\t\tif strings.Contains(fileString, relGoProjectPath) {\n\t\t\tfileString = strings.Replace(fileString, relGoProjectPath, relProjectPath, -1)\n\t\t}\n\n\t\terr = ioutil.WriteFile(f, []byte(fileString), permissions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func (c *CloseFolderList) Run(w *lime.Window) error {\n\tfor _, folder := range w.Project().Folders() {\n\t\tw.Project().RemoveFolder(folder)\n\t}\n\treturn nil\n}", "func Delete(c *cli.Context) {\n\tobjectStore := core.NewFilesystemStore(\".\")\n\n\tfileName := c.Args().Get(0)\n\tif fileName == \"\" {\n\t\tprinter.Fatal(\n\t\t\tfmt.Errorf(\"Can't upsert file, no source template provided\"),\n\t\t\t\"Add the path to the source template file you want to generate like: `kombustion upsert template.yaml`.\",\n\t\t\t\"https://www.kombustion.io/api/manifest/\",\n\t\t)\n\t}\n\n\tclient := &cloudformation.Wrapper{}\n\tprofile := c.GlobalString(\"profile\")\n\tregion := c.String(\"region\")\n\tenvName := c.String(\"environment\")\n\tstackName := c.String(\"stack-name\")\n\tmanifestFile := c.GlobalString(\"manifest-file\")\n\n\ttaskDelete(\n\t\tclient,\n\t\tobjectStore,\n\t\tfileName,\n\t\tprofile,\n\t\tstackName,\n\t\tregion,\n\t\tenvName,\n\t\tmanifestFile,\n\t)\n}", "func RemovePreUnifiedResources(kube kubernetes.Interface, oldName string) error {\n\tif err := kube.AppsV1().Deployments(system.Namespace()).Delete(oldName, &metav1.DeleteOptions{}); err != nil && !apierrs.IsNotFound(err) {\n\t\treturn fmt.Errorf(\"failed to remove old deployment %s: %w\", oldName, err)\n\t}\n\tif err := kube.CoreV1().ServiceAccounts(system.Namespace()).Delete(oldName, &metav1.DeleteOptions{}); err != nil && !apierrs.IsNotFound(err) {\n\t\treturn fmt.Errorf(\"failed to remove old serviceaccount %s: %w\", oldName, err)\n\t}\n\n\treturn nil\n}", "func (f *fixture) cleanUp(ctx context.Context, s *testing.FixtState) {\n\tif err := ash.CloseAllWindows(ctx, f.tconn); err != nil {\n\t\ts.Error(\"Failed trying to close all windows: \", err)\n\t}\n\n\tf.tconn = nil\n\n\tif len(f.drivefsOptions) > 0 && f.driveFs != nil {\n\t\tif err := f.driveFs.ClearCommandLineFlags(); err != nil {\n\t\t\ts.Fatal(\"Failed to remove command line args file: \", err)\n\t\t}\n\t}\n\tf.driveFs = nil\n\tf.mountPath = \"\"\n\n\t// Clean up files in this account that are older than 1 hour, files past this\n\t// date are assumed no longer required and were not successfully cleaned up.\n\t// Note this removal can take a while ~1s per file and may end up exceeding\n\t// the timeout, this is not a failure as the next run will try to remove the\n\t// files that weren't deleted in time.\n\tfileList, err := f.APIClient.ListAllFilesOlderThan(ctx, time.Hour)\n\tif err != nil {\n\t\ts.Error(\"Failed to list all my drive files: \", err)\n\t} else {\n\t\ts.Logf(\"Attempting to remove %d files older than 1 hour\", len(fileList.Files))\n\t\tfor _, i := range fileList.Files {\n\t\t\tif err := f.APIClient.RemoveFileByID(ctx, i.Id); err != nil {\n\t\t\t\ts.Logf(\"Failed to remove file %q (%s): %v\", i.Name, i.Id, err)\n\t\t\t} else {\n\t\t\t\ts.Logf(\"Successfully removed file %q (%s, %s)\", i.Name, i.Id, i.ModifiedTime)\n\t\t\t}\n\t\t}\n\t}\n\tf.APIClient = nil\n\tif f.cr != nil {\n\t\tif err := f.cr.Close(ctx); err != nil {\n\t\t\ts.Log(\"Failed closing chrome: \", err)\n\t\t}\n\t\tf.cr = nil\n\t}\n}", "func GetNewGitIgnoreTemplate(cc CodeConfig) string {\n\treturn `\n# See http://help.github.com/ignore-files/ for more about ignoring files.\n#\n# If you find yourself ignoring temporary files generated by your text editor\n# or operating system, you probably want to add a global ignore instead:\n# git config --global core.excludesfile '~/.gitignore_global'\n\n# Ignore tags\n/tags\n\n# Ignore tmp\n/tmp\n\n# Ignore test coverage files\n*.coverprofile\n*coverage.out\n\n# Ignore swap files\n*.swp\n*.swo\n\n# Ignore config files\n# /config.json`\n}", "func removeFromKustomization(providerDirectory string, release v1alpha1.Release) error {\n\tpath := filepath.Join(providerDirectory, \"kustomization.yaml\")\n\tvar providerKustomization kustomizationFile\n\tproviderKustomizationData, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\terr = yaml.UnmarshalStrict(providerKustomizationData, &providerKustomization)\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\tfor i, r := range providerKustomization.Resources {\n\t\tif r == releaseToDirectory(release) {\n\t\t\tproviderKustomization.Resources = append(providerKustomization.Resources[:i], providerKustomization.Resources[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n\tproviderKustomization.Resources, err = deduplicateAndSortVersions(providerKustomization.Resources)\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\tdata, err := yaml.Marshal(providerKustomization)\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\terr = ioutil.WriteFile(path, data, 0644) //nolint:gosec\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\treturn nil\n}", "func Down_20190715211631(txn *sql.Tx) {\n\t_, err := txn.Exec(`DROP TRIGGER IF EXISTS wep_update ON weapons;`)\n\tif err != nil {\n\t\tlog.Fatalf(\"fatal error while running weapons trigger migration %v\", err)\n\t}\n\n\t_, err2 := txn.Exec(`DROP FUNCTION IF EXISTS wep_update;`)\n\tif err2 != nil {\n\t\tlog.Fatalf(\"fatal error while running weapons trigger migration %v\", err2)\n\t}\n}", "func Down() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"down\",\n\t\tShort: \"Deactivate your cloud native development environment\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn executeDown(c.devPath)\n\t\t},\n\t}\n\n\treturn cmd\n}", "func GenerateTemplates() error {\n\n\t// ensure qtc is available\n\tif err := exsh.EnsureGoBin(\"qtc\", \"github.com/valyala/quicktemplate/qtc\"); err != nil {\n\t\treturn err\n\t}\n\n\t// run qtc command\n\tif err := sh.Run(\"qtc\", \"-dir=\"+templateDir, \"-skipLineComments\"); err != nil {\n\t\treturn err\n\t}\n\n\t// move templates from templateDir to the corresponding location in ./internal/pages\n\terr := filepath.Walk(\n\t\ttemplateDir,\n\t\tfunc(filename string, info os.FileInfo, err error) error {\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif strings.HasSuffix(filename, \".qtpl.go\") {\n\t\t\t\tnewFilename := strings.Replace(filename, templateDir, generatedTemplatesOutputDir, 1)\n\n\t\t\t\tif mg.Verbose() {\n\t\t\t\t\tfmt.Printf(\"Moving %s to %s\\n\", filename, newFilename)\n\t\t\t\t}\n\n\t\t\t\tif err := sh.Copy(newFilename, filename); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn sh.Rm(filename)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t)\n\n\treturn err\n}", "func (cp *OCIConveyorPacker) CleanUp() {\n\tos.RemoveAll(cp.b.Path)\n}", "func cleanup() {\n\tif integrationType == slackIntegrationType {\n\t\tif err := slack.DeleteState(); err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t} else {\n\t\tif err := github.DeleteState(); err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n}", "func (self *WorkingTreeCommands) RemoveTrackedFiles(name string) error {\n\tcmdArgs := NewGitCmd(\"rm\").Arg(\"-r\", \"--cached\", \"--\", name).\n\t\tToArgv()\n\n\treturn self.cmd.New(cmdArgs).Run()\n}", "func (h *Helpers) FixIndentedTemplate(s string) string {\n\ts = h.TemplateString(s)\n\ts = h.FixIndentation(s)\n\treturn s\n}", "func removePage(id string) {\n\terr := os.Remove(pagesDir + id + \".html\")\n\tif err != nil {\n\t\tlog.Printf(\"Error removing page: %s\\n\", err)\n\t}\n}", "func removeContents(dir string) error {\n\td, err := os.Open(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer d.Close()\n\n\tnames, err := d.Readdirnames(-1)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, name := range names {\n\t\terr = os.RemoveAll(path.Join(dir, name))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (f *tmplFuncs) cleanType(path string) string {\n\tsplit := strings.Split(path, \".\")\n\treturn split[len(split)-1]\n}", "func (s *SoftHSMSetup) RunSoftHSMTeardown(softhsmSetup string) {\n\tcmd := exec.Command(softhsmSetup, \"teardown\")\n\tcmd.Env = append(cmd.Env, \"SOFTHSM_SETUP_CONFIGDIR=\"+s.statedir)\n\t_ = cmd.Run()\n\n\tos.RemoveAll(s.statedir)\n}", "func revertCNIBackup() error {\n\treturn filepath.Walk(cniPath,\n\t\tfunc(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !info.Mode().IsRegular() {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif !strings.HasSuffix(path, \".cilium_bak\") {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\torigFileName := strings.TrimSuffix(path, \".cilium_bak\")\n\t\t\treturn os.Rename(path, origFileName)\n\t\t})\n}", "func removeNonIgnitionKeyPathFragments() error {\n\t// /home/core/.ssh/authorized_keys.d\n\tauthKeyFragmentDirPath := filepath.Dir(constants.RHCOS9SSHKeyPath)\n\t// ignition\n\tauthKeyFragmentBasename := filepath.Base(constants.RHCOS9SSHKeyPath)\n\n\tkeyFragmentsDir, err := ctrlcommon.ReadDir(authKeyFragmentDirPath)\n\tif err == nil {\n\t\tfor _, fragment := range keyFragmentsDir {\n\t\t\tif fragment.Name() != authKeyFragmentBasename {\n\t\t\t\tkeyPath := filepath.Join(authKeyFragmentDirPath, fragment.Name())\n\t\t\t\terr := os.RemoveAll(keyPath)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to remove path '%s': %w\", keyPath, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else if !errors.Is(err, fs.ErrNotExist) {\n\t\t// This shouldn't ever happen\n\t\treturn fmt.Errorf(\"unexpectedly failed to get info for path '%s': %w\", constants.RHCOS9SSHKeyPath, err)\n\t}\n\n\treturn nil\n}", "func main() {\n out, _ := os.Create(\"error-template.go\")\n out.Write([]byte(\"// generated by go run scripts/embed-template.go; DO NOT EDIT\\n\\n\"))\n out.Write([]byte(\"package main\\n\\nconst (\\n\"))\n out.Write([]byte(\"errorTemplate = `\"))\n f, _ := os.Open(\"error-template.html\")\n io.Copy(out, f)\n out.Write([]byte(\"`\\n\"))\n out.Write([]byte(\")\\n\"))\n}", "func SetupTemplates(cfg chef.ServerConfig) ([]string, error) {\n\tfiles := make([]string, 0)\n\tlog.Debug().Msg(\"setting up templates\")\n\n\tlog.Debug().Msg(\"cleaning output directory\")\n\t// clean static output dir\n\terr := os.RemoveAll(TemplateOutputDir)\n\tif err != nil {\n\t\treturn nil,\n\t\t\tfmt.Errorf(\"error cleaning ouput directory %v : %w\", TemplateOutputDir, err)\n\t}\n\n\tlog.Debug().Str(\"OutputDir\", TemplateOutputDir).Msg(\"creating new output directories\")\n\t// Create/ensure output directory\n\tif err = EnsureDir(TemplateOutputDir); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create subdirs\n\thtmlOutputDir := filepath.Join(TemplateOutputDir, \"html\")\n\tif err = EnsureDir(htmlOutputDir); err != nil {\n\t\treturn nil, err\n\t}\n\n\tjsOutputDir := filepath.Join(TemplateOutputDir, \"js\")\n\tif err = EnsureDir(jsOutputDir); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcssOutputDir := filepath.Join(TemplateOutputDir, \"css\")\n\tif err = EnsureDir(cssOutputDir); err != nil {\n\t\treturn nil, err\n\t}\n\n\ttsOutputDir := filepath.Join(TemplateOutputDir, \"src\")\n\tif err = EnsureDir(tsOutputDir); err != nil {\n\t\treturn nil, err\n\t}\n\n\timgOutputDir := filepath.Join(TemplateOutputDir, \"img\")\n\tif err = EnsureDir(imgOutputDir); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmiscFilesOutputDir := filepath.Join(TemplateOutputDir, \"files\")\n\tif err = EnsureDir(miscFilesOutputDir); err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Debug().Str(\"BaseDir\", TemplateBaseDir).Msg(\"ensuring template base directory exists\")\n\t// Ensure base template directory exists\n\tif !Exists(TemplateBaseDir) {\n\t\treturn nil,\n\t\t\tfmt.Errorf(\"base Dir %v does not exist\", TemplateBaseDir)\n\t}\n\n\t// walk through all files in the template resource dir\n\terr = filepath.Walk(TemplateBaseDir,\n\t\tfunc(path string, info os.FileInfo, err error) error {\n\t\t\t// skip certain directories\n\t\t\tif info.IsDir() && info.Name() == \"node_modules\" {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\n\t\t\thandleCopyFileErr := func(err error) {\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal().Err(err).Msg(\"error copying file\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\thandleExecuteTemlateErr := func(err error) {\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal().Err(err).Msg(\"error executing HTML template\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch filepath.Ext(path) {\n\t\t\tcase \".html\":\n\t\t\t\tnewPath := filepath.Join(htmlOutputDir, filepath.Base(path))\n\t\t\t\tlog.Debug().Str(\"fromPath\", path).Str(\"toPath\", newPath).Msg(\"moving static web resources\")\n\t\t\t\thandleExecuteTemlateErr(ExecuteTemplateHTML(cfg, path, newPath))\n\t\t\tcase \".js\", \".map\":\n\t\t\t\tnewPath := filepath.Join(jsOutputDir, filepath.Base(path))\n\t\t\t\tif filepath.Base(path) == \"serviceWorker.js\" || filepath.Base(path) == \"serviceWorker.js.map\" {\n\t\t\t\t\tnewPath = filepath.Join(\"./\", filepath.Base(path))\n\t\t\t\t}\n\t\t\t\tlog.Debug().Str(\"fromPath\", path).Str(\"toPath\", newPath).Msg(\"moving static web resources\")\n\t\t\t\thandleCopyFileErr(CopyFile(path, newPath))\n\t\t\tcase \".css\":\n\t\t\t\tnewPath := filepath.Join(cssOutputDir, filepath.Base(path))\n\t\t\t\tlog.Debug().Str(\"fromPath\", path).Str(\"toPath\", newPath).Msg(\"moving static web resources\")\n\t\t\t\thandleCopyFileErr(CopyFile(path, newPath))\n\t\t\tcase \".ts\":\n\t\t\t\tnewPath := filepath.Join(tsOutputDir, filepath.Base(path))\n\t\t\t\tlog.Debug().Str(\"fromPath\", path).Str(\"toPath\", newPath).Msg(\"moving static web resources\")\n\t\t\t\thandleCopyFileErr(CopyFile(path, newPath))\n\t\t\tcase \".ico\", \".png\", \".jpg\", \".svg\", \".gif\":\n\t\t\t\tnewPath := filepath.Join(imgOutputDir, filepath.Base(path))\n\t\t\t\tlog.Debug().Str(\"fromPath\", path).Str(\"toPath\", newPath).Msg(\"moving static web resources\")\n\t\t\t\thandleCopyFileErr(CopyFile(path, newPath))\n\t\t\tcase \".pdf\", \".doc\", \".docx\", \".xml\":\n\t\t\t\tnewPath := filepath.Join(miscFilesOutputDir, filepath.Base(path))\n\t\t\t\tlog.Debug().Str(\"fromPath\", path).Str(\"toPath\", newPath).Msg(\"moving static web resources\")\n\t\t\t\thandleCopyFileErr(CopyFile(path, newPath))\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\tif err != nil {\n\t\treturn nil,\n\t\t\tfmt.Errorf(\"error walking %v : %w\", TemplateBaseDir, err)\n\t}\n\n\tlog.Debug().Msg(\"template setup complete.\")\n\treturn files, nil\n}", "func (o *Content) UnsetPyVersion() {\n\to.PyVersion.Unset()\n}", "func cleanUmociMetadata(bundlePath string) error {\n\tents, err := ioutil.ReadDir(bundlePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, ent := range ents {\n\t\tif ent.Name() == \"rootfs\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tos.Remove(path.Join(bundlePath, ent.Name()))\n\t}\n\n\treturn nil\n}", "func Clean() error {\n\tfixtureDir := filepath.Join(\"integration\", \"testdata\", \"fixtures\")\n\tpaths := []string{\n\t\tfilepath.Join(fixtureDir, \"images\"),\n\t\tfilepath.Join(fixtureDir, \"vm-images\"),\n\t}\n\tfor _, p := range paths {\n\t\tif err := sh.Rm(p); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func GenerateRemoveNodeScript(env Environment) []byte {\n\tcode := assets.MustAssetString(removeNodeFilename)\n\n\treturn []byte(replaceAddresses(code, env))\n}", "func TestDeleteCmdWithProject(t *testing.T) {\n\tfuncYaml := `name: bar\nnamespace: \"\"\nruntime: go\nimage: \"\"\nimageDigest: \"\"\nbuilder: quay.io/boson/faas-go-builder\nbuilderMap:\n default: quay.io/boson/faas-go-builder\nenvs: []\nannotations: {}\n`\n\ttmpDir, err := ioutil.TempDir(\"\", \"bar\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(tmpDir)\n\n\tf, err := os.Create(filepath.Join(tmpDir, \"func.yaml\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer f.Close()\n\n\t_, err = f.WriteString(funcYaml)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tf.Close()\n\n\toldWD, err := os.Getwd()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer func() {\n\t\terr = os.Chdir(oldWD)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\terr = os.Chdir(tmpDir)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ttr := &testRemover{}\n\tcmd := NewDeleteCmd(func(ns string, verbose bool) (fn.Remover, error) {\n\t\treturn tr, nil\n\t})\n\n\tcmd.SetArgs([]string{\"-p\", \".\"})\n\terr = cmd.Execute()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif tr.invokedWith == nil {\n\t\tt.Fatal(\"fn.Remover has not been invoked\")\n\t}\n\n\tif *tr.invokedWith != \"bar\" {\n\t\tt.Fatalf(\"expected fn.Remover to be called with 'bar', but was called with '%s'\", *tr.invokedWith)\n\t}\n}", "func (s *Server) cleanTmpFiles(dir string) {\n\tnow := time.Now()\n\tpackdir := filepath.Join(dir, \".git\", \"objects\", \"pack\")\n\terr := filepath.Walk(packdir, func(path string, info os.FileInfo, err error) error {\n\t\tif path != packdir && info.IsDir() {\n\t\t\treturn filepath.SkipDir\n\t\t}\n\t\tfile := filepath.Base(path)\n\t\tif strings.HasPrefix(file, \"tmp_pack_\") {\n\t\t\tif now.Sub(info.ModTime()) > longGitCommandTimeout {\n\t\t\t\terr := os.Remove(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog15.Error(\"error removing tmp_pack_* files\", \"error\", err)\n\t}\n}", "func removePendingDeployment() error {\n\treturn runRpmOstree(\"cleanup\", \"-p\")\n}", "func (self *WorkingTreeCommands) ResetAndClean() error {\n\tsubmoduleConfigs, err := self.submodule.GetConfigs()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(submoduleConfigs) > 0 {\n\t\tif err := self.submodule.ResetSubmodules(submoduleConfigs); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := self.ResetHard(\"HEAD\"); err != nil {\n\t\treturn err\n\t}\n\n\treturn self.RemoveUntrackedFiles()\n}", "func TestDevRemove(t *testing.T) {\n\tassert := asrt.New(t)\n\n\t// Make sure we have running sites.\n\taddSites()\n\n\tfor _, site := range DevTestSites {\n\t\tcleanup := site.Chdir()\n\n\t\tout, err := exec.RunCommand(DdevBin, []string{\"remove\"})\n\t\tassert.NoError(err, \"ddev remove should succeed but failed, err: %v, output: %s\", err, out)\n\t\tassert.Contains(out, \"has been removed\")\n\n\t\t// Ensure the site that was just stopped does not appear in the list of sites\n\t\tapps := ddevapp.GetApps()\n\t\tfor _, app := range apps {\n\t\t\tassert.True(app.GetName() != site.Name)\n\t\t}\n\n\t\tcleanup()\n\t}\n\n\t// Re-create running sites.\n\taddSites()\n\n\t// Ensure a user can't accidentally wipe out everything.\n\tappsBefore := len(ddevapp.GetApps())\n\tout, err := exec.RunCommand(DdevBin, []string{\"remove\", \"--remove-data\", \"--all\"})\n\tassert.Error(err, \"ddev remove --all --remove-data should error, but succeeded\")\n\tassert.Contains(out, \"Illegal option\")\n\tassert.EqualValues(appsBefore, len(ddevapp.GetApps()), \"No apps should be removed or added after ddev remove --all --remove-data\")\n\n\t// Ensure the --all option can remove all active apps\n\tout, err = exec.RunCommand(DdevBin, []string{\"remove\", \"--all\"})\n\tassert.NoError(err, \"ddev remove --all should succeed but failed, err: %v, output: %s\", err, out)\n\tout, err = exec.RunCommand(DdevBin, []string{\"list\"})\n\tassert.NoError(err)\n\tassert.Contains(out, \"no running ddev projects\")\n\tassert.Equal(0, len(ddevapp.GetApps()), \"Not all apps were removed after ddev remove --all\")\n\n\t// Now put the sites back together so other tests can use them.\n\taddSites()\n}", "func InitProject() {\n\tfmt.Println(\"\\nDownloading template...\")\n\tresp, err := http.Get(\"https://github.com/ryanlbrown/spapp/archive/master.zip\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor _, f := range r.File {\n\t\t// Ignore dot files.\n\t\tif path.Base(f.Name)[0] == '.' {\n\t\t\tcontinue\n\t\t}\n\t\tpathTokens := strings.Split(f.Name, \"/\")\n\t\tsubName := strings.Join(pathTokens[1:], \"/\")\n\t\tif subName == \"\" || subName == \"README.md\" {\n\t\t\tcontinue\n\t\t}\n\t\tif subName[len(subName)-1] == '/' {\n\t\t\tdirName := subName[:len(subName)-1]\n\t\t\tfmt.Println(\"Created:\", dirName)\n\t\t\terr = os.Mkdir(dirName, 0755)\n\t\t\tif err != nil && !os.IsExist(err) {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t} else {\n\t\t\tfa, err := f.Open()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdefer fa.Close()\n\t\t\tfb, err := os.OpenFile(subName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdefer fb.Close()\n\t\t\t_, err = io.Copy(fb, fa)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tfmt.Println(\"Created:\", subName)\n\t\t}\n\t}\n\tfmt.Println()\n}", "func destructor(cmd *cobra.Command, args []string) {\n\tlog.Debug().Msgf(\"Running Destructor.\\n\")\n\tif debug {\n\t\t// Keep intermediary files, when on debug\n\t\tlog.Debug().Msgf(\"Skipping file clearance on Debug Mode.\\n\")\n\t\treturn\n\t}\n\tintermediaryFiles := []string{\"generate_pylist.py\", \"pylist.json\", \"dependencies.txt\", \"golist.json\", \"npmlist.json\"}\n\tfor _, file := range intermediaryFiles {\n\t\tfile = filepath.Join(os.TempDir(), file)\n\t\tif _, err := os.Stat(file); err != nil {\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\t// If file doesn't exists, continue\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\te := os.Remove(file)\n\t\tif e != nil {\n\t\t\tlog.Fatal().Msgf(\"Error clearing files %s\", file)\n\t\t}\n\t}\n}", "func promptToDeletePrevProject(prevProjPath string) {\n\t// var shouldUndo = askBooleanQuestion(false, \"QUESTION: Delete the cloned previous version of the project?\")\n\t// if shouldUndo {\n\t// \tdeleteAllFiles(prevProjPath)\n\t// \tcolor.Style{color.Green}.Print(\"\\nFinished deleting\\n\")\n\t// }\n\tvar projectLocation = trimPathAfterLastSlash(prevProjPath) //get project location\n\tvar isFound, _ = searchForFilePath(projectLocation, trimPathBeforeLastSlash(prevProjPath, false)) //look for a prevProject from project locaation where the project and prevProject should be store\n\t// print(\"\\n\")\n\tif isFound { //if clonedProject already exist, delete it and create a new clone\n\t\t// color.Style{color.Red}.Print(\"Deleting \", trimPathBeforeLastSlash(prevProjPath, false), \"... \")\n\t\tdeleteAllFiles(prevProjPath)\n\t\t// color.Style{color.Red, color.Bold}.Print(\"Deleted. \")\n\t}\n}", "func (me *TCmd) Cleanup() {\n\tos.Chdir(me.origin)\n\tos.RemoveAll(me.dir)\n}", "func removeNode(n *doc.Node) {\n\t// Check if this node exists.\n\tfor i, v := range localNodes {\n\t\tif n.ImportPath == v.ImportPath {\n\t\t\tlocalNodes = append(localNodes[:i], localNodes[i+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n}", "func CleanUntracked(ctx context.Context, roots doltdb.Roots, tables []string, dryrun bool, force bool) (doltdb.Roots, error) {\n\tuntrackedTables := make(map[string]struct{})\n\n\tvar err error\n\tif len(tables) == 0 {\n\t\ttables, err = roots.Working.GetTableNames(ctx)\n\t\tif err != nil {\n\t\t\treturn doltdb.Roots{}, nil\n\t\t}\n\t}\n\n\tfor i := range tables {\n\t\tname := tables[i]\n\t\t_, _, err = roots.Working.GetTable(ctx, name)\n\t\tif err != nil {\n\t\t\treturn doltdb.Roots{}, err\n\t\t}\n\t\tuntrackedTables[name] = struct{}{}\n\t}\n\n\t// untracked tables = working tables - staged tables\n\theadTblNames, err := roots.Staged.GetTableNames(ctx)\n\tif err != nil {\n\t\treturn doltdb.Roots{}, err\n\t}\n\n\tfor _, name := range headTblNames {\n\t\tdelete(untrackedTables, name)\n\t}\n\n\tnewRoot := roots.Working\n\tvar toDelete []string\n\tfor t := range untrackedTables {\n\t\ttoDelete = append(toDelete, t)\n\t}\n\n\tnewRoot, err = newRoot.RemoveTables(ctx, force, force, toDelete...)\n\tif err != nil {\n\t\treturn doltdb.Roots{}, fmt.Errorf(\"failed to remove tables; %w\", err)\n\t}\n\n\tif dryrun {\n\t\treturn roots, nil\n\t}\n\troots.Working = newRoot\n\n\treturn roots, nil\n}", "func (g *GitLocal) RemoveForce(dir, fileName string) error {\n\treturn g.GitCLI.RemoveForce(dir, fileName)\n}", "func cleanDocXml(content string) string {\n\tcleanContent := findPlaceholdersAndRemoveWordTags(content)\n\n\tfor _, find := range findContainingXmlBlockForMacro(cleanContent) {\n\t\treplace := splitTextIntoTexts(find)\n\t\tcleanContent = strings.ReplaceAll(cleanContent, find, replace)\n\t}\n\treturn cleanContent\n}", "func moveHTML(filePath string, version string, outputDir string) error {\n\tdirs := strings.Split(filePath, \"/\")\n\tvar i int\n\tfor i = 0; i < len(dirs); i++ {\n\t\tif dirs[i] == \"api-reference\" {\n\t\t\tbreak\n\t\t}\n\t}\n\tif i == len(dirs) {\n\t\treturn fmt.Errorf(\"failed to find fold \\\"api-reference\\\"\\n\")\n\t}\n\tfileName := strings.Join(dirs[i+1:], \"-\")\n\t// version is needed to eliminate conflicts among releases.\n\tif err := os.MkdirAll(outputDir+\"/../_includes/\"+version, 0766); err != nil {\n\t\treturn err\n\t}\n\treturn os.Rename(filePath, outputDir+\"/../_includes/\"+version+\"/\"+fileName)\n}", "func ExampleWorkbookTemplatesClient_Delete() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient, err := armapplicationinsights.NewWorkbookTemplatesClient(\"subid\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\t_, err = client.Delete(ctx,\n\t\t\"my-resource-group\",\n\t\t\"my-template-resource\",\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n}", "func (m *EmployeeWorkingHoursMutation) ResetCodeWork() {\n\tm._CodeWork = nil\n}", "func pkgPathStdStrip(path string) string {\n\treturn strings.TrimPrefix(path, \"std/\")\n}", "func RemoveContents(dir string) {\n\tfiles, err := filepath.Glob(dir)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tfor _, file := range files {\n\t\terr = os.RemoveAll(file)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n}", "func TestVoltBuildT3RemoveUserVimrcGvimrc(t *testing.T) {\n\t// =============== setup =============== //\n\n\ttestutil.SetUpEnv(t)\n\tdefer testutil.CleanUpEnv(t)\n\n\tinstallVimRC(t, \"vimrc-magic.vim\", pathutil.Vimrc)\n\tinstallVimRC(t, \"gvimrc-magic.vim\", pathutil.Gvimrc)\n\n\t// =============== run =============== //\n\n\tout, err := testutil.RunVolt(\"build\")\n\t// (A, B)\n\ttestutil.SuccessExit(t, out, err)\n\n\t// (!F, !H)\n\tcheckRCInstalled(t, 0, -1, 0, -1)\n}", "func cleanup() {\n\tos.Remove(dummyPath)\n}" ]
[ "0.5403419", "0.48610234", "0.48188964", "0.47880107", "0.46502808", "0.4624768", "0.4575532", "0.45335364", "0.44752434", "0.44420055", "0.44269013", "0.44095922", "0.44063526", "0.43804044", "0.4365622", "0.4359805", "0.4350803", "0.43353775", "0.4305398", "0.42996585", "0.4287423", "0.4277257", "0.42691112", "0.42627135", "0.42619637", "0.42593622", "0.4237609", "0.42360148", "0.4217561", "0.420206", "0.41967073", "0.4195524", "0.4170836", "0.41682935", "0.4160233", "0.4135284", "0.41319513", "0.4129988", "0.4114393", "0.4111249", "0.4106957", "0.40920356", "0.40893874", "0.40804604", "0.40759823", "0.40740624", "0.40686613", "0.40655977", "0.405909", "0.40587112", "0.40585804", "0.4040387", "0.40381417", "0.4037992", "0.40239254", "0.40222308", "0.40149236", "0.40139413", "0.4012466", "0.40095258", "0.39984542", "0.3991929", "0.39912072", "0.3986677", "0.39841124", "0.39741778", "0.39717874", "0.39654422", "0.39614952", "0.39547068", "0.39516118", "0.39490163", "0.39438653", "0.39367458", "0.3935231", "0.39339802", "0.39325395", "0.39310756", "0.39290112", "0.39235765", "0.39211565", "0.39162", "0.39148292", "0.39147007", "0.39119506", "0.3910553", "0.39100915", "0.3907832", "0.39077872", "0.39071813", "0.39071667", "0.39068854", "0.39018467", "0.38982624", "0.388904", "0.38820165", "0.38818434", "0.38800237", "0.38774812", "0.38771707" ]
0.5788403
0
WithLogger sets the logger to use. By default, it logs to the standard library logger.
func WithLogger(l goka.Logger) Option { return func(s *Server) { s.log = l } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func WithLogger(logger Logger) Option {\n\treturn loggerOption{Logger: logger}\n}", "func WithLogger(l Logger) OptionFn {\n\treturn func(app *Application) {\n\t\tif l != nil {\n\t\t\tapp.logger = l\n\t\t\tapp.MustRegister(\"logger\", l)\n\t\t}\n\t}\n}", "func WithLogger(l log.Logger) Option {\n\treturn func(o *options) {\n\t\to.log = l\n\t}\n}", "func WithLogger(l log.Logger) Option {\n\treturn func(o *options) {\n\t\to.logger = l\n\t}\n}", "func WithLogger(logger log.Logger) Option {\n\treturn func(options *options) {\n\t\toptions.logger = logger\n\t}\n}", "func WithLogger(logger log.Logger) Option {\n\treturn func(o *options) {\n\t\to.logger = logger\n\t}\n}", "func WithLogger(logger log.Logger) Option {\n\treturn func(o *options) {\n\t\to.logger = logger\n\t}\n}", "func WithLogger(log logr.Logger) Option {\n\treturn optionFunc(func(c *config) error {\n\t\tc.log = log\n\t\treturn nil\n\t})\n}", "func WithLogger(l ww.Logger) Option {\n\tif l == nil {\n\t\tl = log.New()\n\t}\n\n\treturn func(c *Config) (err error) {\n\t\tc.log = l\n\t\treturn\n\t}\n}", "func WithLogger(with hclog.Logger) wrapping.Option {\n\treturn func() interface{} {\n\t\treturn OptionFunc(func(o *options) error {\n\t\t\to.withLogger = with\n\t\t\treturn nil\n\t\t})\n\t}\n}", "func WithLogger(log logging.Logger) Option {\n\treturn func(o *Options) {\n\t\to.log = log\n\t}\n}", "func WithLogger(l logger.Logger) Option {\n\treturn func(o *Options) {\n\t\to.Logger = l\n\t}\n}", "func WithLogger(l logrus.FieldLogger) Option {\n\treturn func(o *options) error {\n\t\to.log = l\n\t\treturn nil\n\t}\n}", "func WithLogger(logger logging.Logger) Option {\n\treturn func(opts *Options) {\n\t\topts.Logger = logger\n\t}\n}", "func WithLogger(logger *log.Logger) Option {\n\treturn func(cfg *Config) {\n\t\tcfg.Logger = logger\n\t}\n}", "func (d *dispatcher) WithLogger(logger *log.Logger) {\n\td.mu.Lock()\n\tdefer d.mu.Unlock()\n\n\td.logger = logger\n}", "func WithLogger(logger logr.Logger) Option {\n\treturn func(args *Client) { args.Logger = logger }\n}", "func WithLogger(logger log.Log) Opt {\n\treturn func(t *Tortoise) {\n\t\tt.logger = logger.Zap()\n\t}\n}", "func WithLogger(l Logger) Option {\n\treturn func(c *Config) {\n\t\tif l != nil {\n\t\t\tc.logger = l\n\t\t}\n\t}\n}", "func WithLogger(l log.Logger) Option {\n\tif l == nil {\n\t\tl = log.New(log.OptLevel(log.FatalLevel))\n\t}\n\n\treturn func(c *Config) (err error) {\n\t\tc.log = l\n\t\treturn\n\t}\n}", "func WithLogger(logger zerolog.Logger) Option {\n\treturn func(api *API) {\n\t\tapi.logger = logger\n\t}\n}", "func WithLogger(logger *log.Logger) {\n\tdefaultDispatcher.WithLogger(logger)\n}", "func WithLogger(logger commonLogger.Logger) Option {\n\treturn func(o *options) {\n\t\to.logger = logger\n\t}\n}", "func WithLogger(logger Logger) Option {\n\treturn func(s *Service) {\n\t\ts.logger = logger\n\t}\n}", "func WithLogger(logger log.Logger) Option {\n\treturn func(o *builder) {\n\t\to.logger = logger\n\t}\n}", "func WithLogger(l logger.Logger) TransportOption {\n\treturn func(tr *Transport) {\n\t\ttr.logger = l\n\t}\n}", "func WithLogger(l log.Logger) Option {\n\treturn func(s *Server) {\n\t\ts.Logger = l\n\t}\n}", "func WithLogger(logger logger.Interface) Option {\n\treturn func(b *builder) {\n\t\tb.logger = logger\n\t}\n}", "func WithLogger(ctx *gin.Context, logger *logrus.Entry) {\n\tctx.Set(constants.LOGGER, logger)\n}", "func WithLogger(log *logger.UPPLogger) Option {\n\treturn func(d *ExtensibleTransport) {\n\t\ttr := d.delegate\n\t\td.delegate = &loggingTransport{\n\t\t\tlog: log,\n\t\t\ttransport: tr,\n\t\t}\n\t}\n}", "func WithLogger(logger Logger) TranslatorOption {\n\treturn fnTranslatorOption(func(t *Translator) {\n\t\tt.logger = logger\n\t})\n}", "func WithLogger(l *zap.Logger) Option {\n\treturn func(c *Client) { c.logger = l.Named(\"http\") }\n}", "func WithLogger(logger log.Logger) Option {\n\treturn func(c *dbConfig) {\n\t\tc.logger = logger\n\t}\n}", "func WithLogger(l *zap.Logger) Option {\n\treturn func(a *App) {\n\t\ta.logger = l\n\t}\n}", "func WithLogger(l *zap.Logger) Option {\n\treturn func(a *App) {\n\t\ta.logger = l\n\t}\n}", "func WithLogger(logger *log.Logger) RouterOption {\n\treturn func(router *Router) {\n\t\trouter.logger = logger\n\t}\n}", "func WithLogger(ctx context.Context, logger *log.Logger) context.Context {\n\treturn context.WithValue(ctx, ctxlog{}, logger)\n}", "func WithLogger(logger *zap.Logger) OptionFunc {\n\treturn func(opts *option) error {\n\t\topts.logger = logger\n\t\treturn nil\n\t}\n}", "func WithLogger(ctx Context, logger log.Logger) Context {\n\t// Logger can be overridden below... no problem\n\treturn context.WithValue(ctx, contextKeyLogger, logger)\n}", "func WithLogger(logger *log.Logger) Option {\n\treturn func(c *Consumer) error {\n\t\tc.logger = logger\n\t\treturn nil\n\t}\n}", "func WithLogger(logger Logger) TreeOption {\n\treturn oversight.WithLogger(logger)\n}", "func WithLogger(ctx context.Context, logger Logger) context.Context {\n\treturn context.WithValue(ctx, ctxlog{}, logger)\n}", "func WithLogger(logger *logrus.Logger) Option {\n\treturn func(service *service) error {\n\t\tif logger == nil {\n\t\t\treturn fmt.Errorf(\"logger option: nil\")\n\t\t}\n\t\tservice.logger = logger\n\n\t\treturn nil\n\t}\n}", "func WithLogger(logger *zap.Logger) Option {\n\treturn func(s *service) {\n\t\ts.logger = logger\n\t}\n}", "func WithLogger(logger *logrus.Logger) Opt {\n\treturn func(fwdr *TCPForwarder) {\n\t\tfwdr.logger = logger\n\t}\n}", "func WithLogger(l log.Logger) BotOption {\n\treturn func(b *Bot) {\n\t\tb.logger = l\n\t}\n}", "func WithLogger(logger Logger) KeptnOption {\n\treturn func(k *Keptn) {\n\t\tk.logger = logger\n\t}\n}", "func WithLogger(l Logger) Option {\n\treturn func(cb *CircuitBreaker) {\n\t\tcb.logger = l\n\t}\n}", "func WithLogger(l Logger) ConfigOption {\n\treturn func(c *Config) {\n\t\tc.logger = l\n\t}\n}", "func WithLogger(logger interface{}) VWOOption {\n\treturn func(vwo *VWOInstance) {\n\t\tvwo.Logger = logger\n\t}\n}", "func WithLogger(log logging.Logger) ReconcilerOption {\n\treturn func(r *Reconciler) {\n\t\tr.log = log\n\t}\n}", "func WithLogger(ctx context.Context, logger Logger) context.Context {\n\treturn context.WithValue(ctx, loggerKey{}, logger)\n}", "func WithLogger(logger *log.Logger) DMGOption {\n\treturn func(d *DMG) {\n\t\td.logger = logger\n\t}\n}", "func WithLogger(l *log.Logger) ClientOption {\n\treturn func(c *Client) error {\n\t\tc.logger = l\n\t\treturn nil\n\t}\n}", "func WithLogger(ctx context.Context, logger *logr.Logger) context.Context {\n\treturn context.WithValue(ctx, loggerKey{}, logger)\n}", "func WithLogger(l log.Logger) ClientOption {\n\treturn func(c *Client) {\n\t\tc.logger = l\n\t}\n}", "func WithLogger(l logging.Logger) ReconcilerOption {\n\treturn func(r *Reconciler) {\n\t\tr.log = l\n\t}\n}", "func WithLogger(l logging.Logger) ReconcilerOption {\n\treturn func(r *Reconciler) {\n\t\tr.log = l\n\t}\n}", "func WithLogger(logger logger.Interface) Option {\n\treturn func(l *nvcdilib) {\n\t\tl.logger = logger\n\t}\n}", "func WithLogger(l *logrus.Logger) Config {\n\treturn func(r *router) {\n\t\tr.logger = l\n\t}\n}", "func WithLogger(oldLogger Logger, newLogs ...Logger) Logger {\n\tif lc, ok := oldLogger.(LogContext); ok {\n\t\tls := make([]Logger, 0, len(lc.loggers)+len(newLogs))\n\t\tls = append(ls, lc.loggers...)\n\t\tls = append(ls, newLogs...)\n\t\treturn &LogContext{\n\t\t\tloggers: ls,\n\t\t\tprefix: lc.prefix,\n\t\t}\n\t}\n\t// init\n\tls := make([]Logger, 0, len(newLogs)+1)\n\tls = append(ls, oldLogger)\n\tls = append(ls, newLogs...)\n\treturn &LogContext{loggers: ls}\n}", "func WithLogger(logger Logger) Option {\n\treturn func(p *proxy) {\n\t\tp.logger = logger\n\t}\n}", "func NewLoggerWith(logger Logger, keyvals ...interface{}) Logger {\n\treturn Logger{\n\t\tlogger: log.With(logger.logger, keyvals...),\n\t}\n}", "func WithLogger(logger *zap.Logger) Option {\n\treturn optionFn(func(n *namespaceClient) error {\n\t\tn.logger = logger\n\t\treturn nil\n\t})\n}", "func WithLogger(logger *zap.Logger, atom zap.AtomicLevel) Option {\n\treturn func(s *SVC) error {\n\t\treturn assignLogger(s, logger, atom)\n\t}\n}", "func WithLogger(ctx context.Context, log logger.Interface) context.Context {\n\treturn context.WithValue(ctx, logKey, log)\n}", "func WithLogger(l account.Logger) ConfigOption {\n\treturn func(c *Config) {\n\t\tc.logger = l\n\t}\n}", "func WithLogger(logger *logrus.Logger) Option {\n\treturn func(config *queueInformerConfig) {\n\t\tconfig.logger = logger\n\t}\n}", "func WithLogger(ctx context.Context, logger *Logger) context.Context {\n\treturn context.WithValue(ctx, globalLoggerKeyType{}, logger)\n}", "func WithLogger(l logger) func(rpc *EthRPC) {\n\treturn func(rpc *EthRPC) {\n\t\trpc.log = l\n\t}\n}", "func WithLogger(ctx context.Context, logger *logrus.Entry) context.Context {\n\treturn context.WithValue(ctx, loggerKey, logger)\n}", "func WithLogger(logger log.Log) Opt {\n\treturn func(o *Organizer) {\n\t\to.logger = logger\n\t}\n}", "func NewWithLogger(w io.Writer) *Flame {\n\tf := &Flame{\n\t\tInjector: inject.New(),\n\t\tlogger: log.New(w, \"[Flamego] \", 0),\n\t\tstop: make(chan struct{}),\n\t}\n\tf.Router = newRouter(f.createContext)\n\tf.NotFound(http.NotFound)\n\n\tf.Map(f.logger)\n\tf.Map(defaultReturnHandler())\n\treturn f\n}", "func WithLogger(ctx context.Context, l Logger) context.Context {\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\n\treturn context.WithValue(ctx, ctxKey{}, l)\n}", "func WithLogger(logger *log.Logger) ManagerOption {\n\treturn func(o *managerOptions) {\n\t\to.logger = logger\n\t}\n}", "func WithLogger(logger log.Logger) ServiceOption {\n\treturn func(s *service) error {\n\t\ts.debugLogger = logger\n\t\treturn nil\n\t}\n}", "func WithLogger(ctx context.Context, logger *log.Entry) context.Context {\n\tl := logger.WithContext(ctx)\n\treturn context.WithValue(ctx, LoggerKey, l)\n}", "func WithLogger(logger stdLogger) SessionOpt {\n\treturn func(so SessionOpts) SessionOpts {\n\t\t// Maintain backwards compatibility\n\t\tif logger == nil {\n\t\t\tlogger = &nullLogger{}\n\t\t}\n\t\tso.logger = logger\n\t\treturn so\n\t}\n}", "func WithLogger(l Logger) serverOption {\n\treturn func(s *Server) error {\n\t\ts.logger = l\n\t\treturn nil\n\t}\n}", "func WithLogger(ctx context.Context, logger *zap.SugaredLogger) context.Context {\n\treturn context.WithValue(ctx, loggerKey, logger)\n}", "func WithLogger(l logrus.FieldLogger) ServerOption {\n\treturn func(s *Server) {\n\t\ts.logger = l\n\t}\n}", "func WithLogger(l log.FieldLogger) ClientOption {\n\treturn func(opt *ClientConfig) error {\n\t\topt.log = l\n\t\treturn nil\n\t}\n}", "func WithLogger(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tzap.L().Info(\n\t\t\t\"request\",\n\t\t\tzap.String(\"method\", r.Method),\n\t\t\tzap.String(\"path\", r.URL.Path),\n\t\t\tzap.Any(\"query\", r.URL.Query()),\n\t\t\tzap.Any(\"headers\", r.Header),\n\t\t\tzap.Int64(\"body\", r.ContentLength),\n\t\t)\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func WithLogger(ctx context.Context, logger *zap.Logger) context.Context {\n\treturn context.WithValue(ctx, loggerContextKey{}, logger)\n}", "func UseLogger(logger logging.Logger) {\n\tlog = logger\n}", "func (s *Server) WithLogger(l *log.Logger) http.Handler {\n\treturn &logger{\n\t\tlogger: l,\n\t\tserver: s,\n\t}\n}", "func WithLogger(ctx context.Context, logger Logger) context.Context {\n\treturn context.WithValue(ctx, contextKey, logger)\n}", "func WithLogger(ctx context.Context, logger Logger) context.Context {\n\treturn context.WithValue(ctx, contextKey, logger)\n}", "func withLogger(fn func() *logger.Logger) ServerOption {\n\treturn func(cfg *serverConfig) {\n\t\tcfg.logger = fn()\n\t}\n}", "func WithLogger(ctx context.Context, logger *zap.Logger) context.Context {\n\treturn context.WithValue(ctx, loggerKey{}, logger)\n}", "func WithLogger(parent context.Context, logCtx kitlog.Logger) context.Context {\n\treturn context.WithValue(parent, logCtxKey, logCtx)\n}", "func (o *opts) WithLogger(value ILogger) *opts {\n\tb := value\n\n\to.log = b\n\n\treturn o\n}", "func SetLogger(l Logger) {\n\t_, isDefault := l.(*logger)\n\tif isDefault && oakLogger != nil {\n\t\t// The user set the logger themselves,\n\t\t// don't reset to the default logger\n\t\treturn\n\t}\n\toakLogger = l\n\tError = l.Error\n\tWarn = l.Warn\n\tInfo = l.Info\n\tVerb = l.Verb\n\t// If this logger supports the additional functionality described\n\t// by the FullLogger interface, enable those functions. Otherwise\n\t// they are NOPs. (the default logger supports these functions.)\n\tif fl, ok := l.(FullLogger); ok {\n\t\tfullOakLogger = fl\n\t\tFileWrite = fl.FileWrite\n\t\tGetLogLevel = fl.GetLogLevel\n\t\tSetDebugFilter = fl.SetDebugFilter\n\t\tSetDebugLevel = fl.SetDebugLevel\n\t\tCreateLogFile = fl.CreateLogFile\n\t}\n}", "func With(logger Logger, keyvals ...interface{}) Logger {\n\tw, ok := logger.(*withLogger)\n\tif !ok {\n\t\tw = &withLogger{logger: logger}\n\t}\n\treturn w.with(keyvals...)\n}", "func WithLogger(w io.ReadWriteCloser) CallOpt {\n\treturn func(c *call) error {\n\t\tc.stderr = w\n\t\treturn nil\n\t}\n}", "func WithLogger(l log.Logger) APIOption {\n\treturn newAPIOption(func(o *Options) {\n\t\tif l == nil {\n\t\t\treturn\n\t\t}\n\t\to.Logger = l\n\t})\n}", "func WithLogger(logger Logger) ServerOption {\n\treturn func(s *Server) {\n\t\tif logger != nil {\n\t\t\ts.logger = logger\n\t\t}\n\t}\n}", "func (o *Options) WithLogger(value *zap.Logger) *Options {\n\to.logger = value.With(zap.String(\"module\", \"server\"))\n\treturn o\n}", "func With(logger Logger, keyvals ...interface{}) Logger {\n\treturn &ctLogger{\n\t\tlogger: kit_log.With(logger.ToGoKitLogger(), keyvals...),\n\t}\n}", "func (a *app) UseLogger(l Logger) App {\n\ta.logDebugInfo(\"UseLogger\")\n\ta.logger = l\n\ta.safeLogInfo(\"Added Logger\")\n\treturn a\n}" ]
[ "0.7840537", "0.7794925", "0.77942044", "0.77463925", "0.7745421", "0.7726518", "0.7726518", "0.7713602", "0.7698265", "0.76704085", "0.7669409", "0.7656201", "0.76350176", "0.76218003", "0.7616936", "0.76035553", "0.7575008", "0.75647897", "0.75019264", "0.7490467", "0.7482255", "0.7464135", "0.7451795", "0.74144125", "0.7403887", "0.7372219", "0.73602027", "0.7350481", "0.7328712", "0.7301633", "0.72613657", "0.7256566", "0.72032917", "0.71827084", "0.71827084", "0.71792793", "0.7167992", "0.7151313", "0.7136737", "0.71292126", "0.7126476", "0.710954", "0.7106203", "0.7068879", "0.70679677", "0.7067886", "0.70625144", "0.70473474", "0.7043765", "0.70233464", "0.70200944", "0.7019187", "0.7017133", "0.70075303", "0.70063025", "0.7001197", "0.6991253", "0.6991253", "0.6990297", "0.69616485", "0.6956225", "0.6953807", "0.6951171", "0.6909575", "0.6907682", "0.6896661", "0.6887867", "0.6886861", "0.6882246", "0.6861996", "0.68504786", "0.68486696", "0.6840583", "0.6831209", "0.6816739", "0.67953175", "0.67827296", "0.67808086", "0.67735565", "0.6767775", "0.67600965", "0.6754028", "0.67512983", "0.6749331", "0.6742206", "0.67340624", "0.6719596", "0.6719596", "0.67131853", "0.67130893", "0.6700698", "0.6691806", "0.669158", "0.66865206", "0.66847706", "0.6667802", "0.6646277", "0.6624807", "0.6618609", "0.66175693" ]
0.73261267
29
GenerateModels parses the magmagenmeta key of the given swagger YAML file, copies the files that the target file depends on into the current working directory, shells out to `swagger generate models`, then cleans up the dependency files.
func GenerateModels(targetFilepath string, configFilepath string, rootDir string, specs map[string]MagmaSwaggerSpec) error { absTargetFilepath, err := filepath.Abs(targetFilepath) if err != nil { return fmt.Errorf("target filepath %s is invalid: %w", targetFilepath, err) } tmpGenDir, err := ioutil.TempDir(".", "tmpgen") if err != nil { return fmt.Errorf("could not create temporary gen directory: %w", err) } defer os.RemoveAll(tmpGenDir) // For each dependency, strip the magma-gen-meta and write the result to // the filename specified by `dependent-filename` err = StripAndWriteSwaggerSpecs(specs, tmpGenDir) if err != nil { return err } // Shell out to go-swagger targetSpec := specs[absTargetFilepath] outputDir := filepath.Join(rootDir, targetSpec.MagmaGenMeta.OutputDir) absConfigFilepath, err := filepath.Abs(configFilepath) if err != nil { return err } cmd := exec.Command( "swagger", "generate", "model", "--spec", filepath.Join(tmpGenDir, targetSpec.MagmaGenMeta.TempGenFilename), "--target", outputDir, "--config-file", absConfigFilepath, ) stdoutBuf := &strings.Builder{} stderrBuf := &strings.Builder{} cmd.Stdout = stdoutBuf cmd.Stderr = stderrBuf err = cmd.Run() if err != nil { return fmt.Errorf("failed to generate models; stdout:\n%s\nstderr:\n%s: %w", stdoutBuf.String(), stderrBuf.String(), err) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (g *Generator) Generate(context *common.Context, schema *schema.Schema) ([]common.Output, error) {\n\tmoduleName := strings.ToLower(schema.Title)\n\tvar outputs []common.Output\n\n\tfor _, def := range schema.Definitions {\n\t\t// create models only for objects\n\t\tif def.Type != nil {\n\t\t\tif t, ok := def.Type.(string); ok {\n\t\t\t\tif t != \"object\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tf, err := generateMainFile(context, schema)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpath := fmt.Sprintf(\n\t\t\t\"%s%s/main.go\",\n\t\t\tcontext.Config.Target,\n\t\t\tmoduleName,\n\t\t)\n\n\t\toutputs = append(outputs, common.Output{\n\t\t\tContent: f,\n\t\t\tPath: path,\n\t\t})\n\n\t}\n\n\treturn outputs, nil\n\n}", "func GenerateModels(w *Writer, packagename string, spec *swagme.Spec) error {\n\tw.WriteSinglelineComment(\"Code generated by swagme\")\n\tw.WriteBlankLine()\n\n\tif info := spec.Info; info != nil {\n\t\tw.WriteSinglelineComment(fmt.Sprintf(\"package %s defines models for %s %s\", packagename, info.Title, info.Version))\n\t}\n\n\tw.WritePackage(packagename)\n\n\t// generate enums\n\tfor _, enum := range buildEnums(spec.Definitions) {\n\t\tw.WriteBlankLine()\n\t\tif err := generateEnum(w, &enum); err != nil {\n\t\t\tw.WriteMultilineCommentf(`ERROR with enum %q:\\n%v`, enum.Name, err)\n\t\t}\n\t}\n\n\t// generate structs\n\tfor name, definition := range spec.Definitions {\n\t\tw.WriteBlankLine()\n\t\tif err := generateDefinition(w, name, definition); err != nil {\n\t\t\tw.WriteMultilineCommentf(`ERROR with definition %q:\\n%v`, name, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func Generate(swaggerFile string, options Options) (err error) {\n\tpkgName := \"api\"\n\tif options.PackageName != \"\" {\n\t\tpkgName = options.PackageName\n\t}\n\n\t// Generate to stdout\n\tif options.TargetFile == \"\" {\n\t\treturn pkg.GenerateFromFile(swaggerFile, pkgName, os.Stdout)\n\t}\n\n\t// Generate to tmp file. If no errors presents then will move tmp file to `options.TargetFile`\n\tgenFile, err := ioutil.TempFile(\"\", \"*-gorest.go\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while tmp file creating: %v\", err)\n\t}\n\n\terr = pkg.GenerateFromFile(swaggerFile, pkgName, genFile)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"api generating error: %v\", err)\n\n\t\tif removeErr := removeFile(genFile); removeErr != nil {\n\t\t\treturn fmt.Errorf(\"%s, error while tmp file removing: %v\", err, removeErr)\n\t\t}\n\t\treturn err\n\t}\n\treturn os.Rename(genFile.Name(), options.TargetFile)\n}", "func (s *schg) Generate(schemaInBase, schemaOutBase string) (err error) {\n\ts.definitions = nil\n\ts.services = make(map[string]string, 0)\n\ts.pkg = filepath.Base(schemaOutBase)\n\tif schemaInBase, err = filepath.Abs(filepath.Clean(schemaInBase)); err != nil {\n\t\treturn\n\t}\n\tif schemaOutBase, err = filepath.Abs(filepath.Clean(schemaOutBase)); err != nil {\n\t\treturn\n\t}\n\ts.defFile = filepath.Join(schemaInBase, definitionsFile)\n\n\tif err = s.loadDefinitions(schemaInBase); err != nil {\n\t\tlog.Println(fmt.Sprintf(cannotReadFileErr, definitionsFile, err))\n\t}\n\tif err = filepath.Walk(schemaInBase, s.walkFunc()); err != nil {\n\t\treturn\n\t}\n\t// remove created temporary files/dirs at the end.\n\tdefer func() {\n\t\tif e := s.dropTmpDirs(); e != nil {\n\t\t\tlog.Println(fmt.Sprintf(cannotRemoveTempDirsErr, e))\n\t\t}\n\t}()\n\tif err = s.createPaths(schemaOutBase); err != nil {\n\t\treturn\n\t}\n\tif err = s.saveAsGoBinData(schemaOutBase); err != nil {\n\t\treturn\n\t}\n\tif err = s.createBindSchemaFiles(schemaOutBase); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func Generate(swagger *openapi3.Swagger, packageName string, opts Options) (string, error) {\n\timportMapping = constructImportMapping(opts.ImportMapping)\n\n\tfilterOperationsByTag(swagger, opts)\n\tif !opts.SkipPrune {\n\t\tpruneUnusedComponents(swagger)\n\t}\n\n\t// This creates the golang templates text package\n\tTemplateFunctions[\"opts\"] = func() Options { return opts }\n\tt := template.New(\"oapi-codegen\").Funcs(TemplateFunctions)\n\t// This parses all of our own template files into the template object\n\t// above\n\tt, err := templates.Parse(t)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error parsing oapi-codegen templates\")\n\t}\n\n\t// Override built-in templates with user-provided versions\n\tfor _, tpl := range t.Templates() {\n\t\tif _, ok := opts.UserTemplates[tpl.Name()]; ok {\n\t\t\tutpl := t.New(tpl.Name())\n\t\t\tif _, err := utpl.Parse(opts.UserTemplates[tpl.Name()]); err != nil {\n\t\t\t\treturn \"\", errors.Wrapf(err, \"error parsing user-provided template %q\", tpl.Name())\n\t\t\t}\n\t\t}\n\t}\n\n\tops, err := OperationDefinitions(swagger)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error creating operation definitions\")\n\t}\n\n\tvar typeDefinitions, constantDefinitions string\n\tif opts.GenerateTypes {\n\t\ttypeDefinitions, err = GenerateTypeDefinitions(t, swagger, ops, opts.ExcludeSchemas)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error generating type definitions\")\n\t\t}\n\n\t\tconstantDefinitions, err = GenerateConstants(t, ops)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error generating constants\")\n\t\t}\n\n\t}\n\n\tvar echoServerOut string\n\tif opts.GenerateEchoServer {\n\t\techoServerOut, err = GenerateEchoServer(t, ops)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error generating Go handlers for Paths\")\n\t\t}\n\t}\n\n\tvar chiServerOut string\n\tif opts.GenerateChiServer {\n\t\tchiServerOut, err = GenerateChiServer(t, ops)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error generating Go handlers for Paths\")\n\t\t}\n\t}\n\n\tvar clientOut string\n\tif opts.GenerateClient {\n\t\tclientOut, err = GenerateClient(t, ops)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error generating client\")\n\t\t}\n\t}\n\n\tvar clientWithResponsesOut string\n\tif opts.GenerateClient {\n\t\tclientWithResponsesOut, err = GenerateClientWithResponses(t, ops)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error generating client with responses\")\n\t\t}\n\t}\n\n\tvar inlinedSpec string\n\tif opts.EmbedSpec {\n\t\tinlinedSpec, err = GenerateInlinedSpec(t, swagger)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error generating Go handlers for Paths\")\n\t\t}\n\t}\n\n\tvar buf bytes.Buffer\n\tw := bufio.NewWriter(&buf)\n\n\texternalImports := importMapping.GoImports()\n\timportsOut, err := GenerateImports(t, externalImports, packageName)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error generating imports\")\n\t}\n\n\t_, err = w.WriteString(importsOut)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error writing imports\")\n\t}\n\n\t_, err = w.WriteString(constantDefinitions)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error writing constants\")\n\t}\n\n\t_, err = w.WriteString(typeDefinitions)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error writing type definitions\")\n\n\t}\n\n\tif opts.GenerateClient {\n\t\t_, err = w.WriteString(clientOut)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error writing client\")\n\t\t}\n\t\t_, err = w.WriteString(clientWithResponsesOut)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error writing client\")\n\t\t}\n\t}\n\n\tif opts.GenerateEchoServer {\n\t\t_, err = w.WriteString(echoServerOut)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error writing server path handlers\")\n\t\t}\n\t}\n\n\tif opts.GenerateChiServer {\n\t\t_, err = w.WriteString(chiServerOut)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error writing server path handlers\")\n\t\t}\n\t}\n\n\tif opts.EmbedSpec {\n\t\t_, err = w.WriteString(inlinedSpec)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error writing inlined spec\")\n\t\t}\n\t}\n\n\terr = w.Flush()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"error flushing output buffer\")\n\t}\n\n\t// remove any byte-order-marks which break Go-Code\n\tgoCode := SanitizeCode(buf.String())\n\n\t// The generation code produces unindented horrors. Use the Go Imports\n\t// to make it all pretty.\n\tif opts.SkipFmt {\n\t\treturn goCode, nil\n\t}\n\n\toutBytes, err := imports.Process(packageName+\".go\", []byte(goCode), nil)\n\tif err != nil {\n\t\tfmt.Println(goCode)\n\t\treturn \"\", errors.Wrap(err, \"error formatting Go code\")\n\t}\n\treturn string(outBytes), nil\n}", "func (m *MigrationParams) GenerateFiles() (err error) {\n\tvar forwardFile, reverseFile *os.File\n\n\tif forwardFile, err = newMigrationFile(m.Forward, m.Dirpath); err != nil {\n\t\treturn\n\t}\n\tfmt.Fprintln(os.Stderr, \"created forward file:\", forwardFile.Name())\n\tdefer func() { _ = forwardFile.Close() }()\n\n\tif !m.Reversible {\n\t\tfmt.Fprintln(os.Stderr, \"migration marked irreversible, did not create reverse file\")\n\t\treturn\n\t}\n\n\tif reverseFile, err = newMigrationFile(m.Reverse, m.Dirpath); err != nil {\n\t\treturn\n\t}\n\tfmt.Fprintln(os.Stderr, \"created reverse file:\", reverseFile.Name())\n\tdefer func() { _ = reverseFile.Close() }()\n\treturn\n}", "func (g *generator) Generate() error {\n\terr := g.Prepare()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// temporary template variable\n\tvar templ string\n\tswitch g.repositoryType {\n\tcase Mongo:\n\t\ttempl = repositorytmpl.MongoRepositoryTemplate\n\t}\n\n\t// compile mongo repository\n\trepoTmpl, err := template.New(\"repository\").Parse(templ)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, resource := range *g.Resources {\n\t\tif entity, ok := resource.(*model.Model); ok {\n\t\t\tgenlog.Info(\"Generating repository for model %s\", entity.Name)\n\t\t\tcontent := bytes.Buffer{}\n\t\t\terr = repoTmpl.Execute(&content,\n\t\t\t\tstruct {\n\t\t\t\t\tModel *model.Model\n\t\t\t\t\tPackageName string\n\t\t\t\t}{\n\t\t\t\t\tModel: entity,\n\t\t\t\t\tPackageName: g.PackageName(),\n\t\t\t\t},\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tg.SaveFile(entity.Name+\"Repository\", content)\n\t\t}\n\t}\n\n\treturn nil\n}", "func actionGenerate(ctx *cli.Context) (err error) {\n\tif err = autoUpdate(ctx); err != nil {\n\t\treturn\n\t}\n\terr = installDependencies()\n\tif err != nil {\n\t\treturn\n\t}\n\tf := ctx.Args().Get(0)\n\n\tgoPath := initGopath()\n\tif !fileExist(goPath) {\n\t\treturn cli.NewExitError(fmt.Sprintf(\"GOPATH not exist: \"+goPath), 1)\n\t}\n\n\tfilesToGenerate := []string{f}\n\tiPath := ctx.String(\"i\")\n\tif iPath != \"\" {\n\t\tiPath = goPath + \"/src/go-common/app/interface/\" + iPath\n\t\tif !fileExist(iPath) {\n\t\t\treturn cli.NewExitError(fmt.Sprintf(\"interface project not found: \"+iPath), 1)\n\t\t}\n\t\tpbs := filesWithSuffix(iPath+\"/api\", \".pb\", \".proto\")\n\t\tif len(pbs) == 0 {\n\t\t\treturn cli.NewExitError(fmt.Sprintf(\"no pbs found in path: \"+iPath+\"/api\"), 1)\n\t\t}\n\t\tfilesToGenerate = pbs\n\t\tfmt.Printf(\".pb files found %v\\n\", pbs)\n\t} else {\n\t\tif f == \"\" {\n\t\t\t// if is is empty, look up project that contains current dir\n\t\t\tabs, _ := filepath.Abs(\".\")\n\t\t\tproj := lookupProjPath(abs)\n\t\t\tif proj == \"\" {\n\t\t\t\treturn cli.NewExitError(\"current dir is not in any project : \"+abs, 1)\n\t\t\t}\n\t\t\tif proj != \"\" {\n\t\t\t\tpbs := filesWithSuffix(proj+\"/api\", \".pb\", \".proto\")\n\t\t\t\tif len(pbs) == 0 {\n\t\t\t\t\treturn cli.NewExitError(fmt.Sprintf(\"no pbs found in path: \"+proj+\"/api\"), 1)\n\t\t\t\t}\n\t\t\t\tfilesToGenerate = pbs\n\t\t\t\tfmt.Printf(\".pb files found %v\\n\", pbs)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, p := range filesToGenerate {\n\t\tif !fileExist(p) {\n\t\t\treturn cli.NewExitError(fmt.Sprintf(\"file not exist: \"+p), 1)\n\t\t}\n\t\tgenerateForFile(p, goPath)\n\t}\n\tif syncLiveDoc {\n\t\terr = actionSyncLiveDoc(ctx)\n\t}\n\treturn\n}", "func Generate() error {\n\tlogCategories, err := getDefinitions()\n\tif err != nil {\n\t\treturn err\n\t}\n\ttemp, err := getTemplates()\n\tif err != nil {\n\t\treturn err\n\t}\n\toutputPath := os.Getenv(\"GENERATOR_OUTPUT_PATH\")\n\tavailable := make([]string, 0)\n\tif len(outputPath) == 0 {\n\t\toutputPath = \"./templates\"\n\t}\n\tfor k, content := range logCategories {\n\t\tavailable = append(available, content.ResourceType)\n\t\tos.MkdirAll(fmt.Sprintf(\"%s/%s/\", outputPath, k), os.ModePerm)\n\t\tfr, err := os.Create(fmt.Sprintf(\"%s/%s/rule.json\", outputPath, k))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_ = temp.ExecuteTemplate(fr, ruleTemplate, content)\n\t\tfp, err := os.Create(fmt.Sprintf(\"%s/%s/parameters.json\", outputPath, k))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_ = temp.ExecuteTemplate(fp, paramTemplate, nil)\n\t}\n\tos.MkdirAll(outputPath, os.ModePerm)\n\tfa, err := os.Create(fmt.Sprintf(\"%s/available_resources.json\", outputPath))\n\tif err != nil {\n\t\treturn err\n\t}\n\t_ = temp.ExecuteTemplate(fa, generatedTemplate, available)\n\treturn nil\n}", "func (s *Schema) Generate(root string) error {\n\treturn inSubDirectory(root, s.Package, func(dir string) error {\n\t\tk, p, err := s.getFirstEndpoint()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(s.Endpoints) == 1 && isDefaultEndpoint(k) {\n\t\t\tif err = s.genSingleHandler(dir, p); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn fixImports(dir, handlerDst)\n\t\t}\n\n\t\tif err = s.genEndpointsInterface(dir); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err = s.genHandler(dir); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err = s.genDispatcher(dir); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err = s.genHandlers(dir); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn fixImports(dir, endpointsDst)\n\t})\n}", "func Generate(c *goproject.Config, p *Project) error {\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to get current working directory: %v\", err)\n\t}\n\n\tfullPath := filepath.Join(cwd, p.Name)\n\n\terr = os.Mkdir(fullPath, 0750)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to create project directory: %v\", err)\n\t}\n\n\terr = copyFiles(p.Tpl.path, fullPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to copy template files: %v\", err)\n\t}\n\n\terr = applyProjectToTemplates(p, fullPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to execute templates: %v\", err)\n\t}\n\n\terr = fixCmdProjectFolderName(p, fullPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to rename cmd project folder: %v\", err)\n\t}\n\n\terr = gitCleanup(fullPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to initialize git: %v\", err)\n\t}\n\n\treturn nil\n}", "func Generate(ctx *cli.Context) error { // nolint: gocyclo\n\tvar filterRe *regexp.Regexp\n\tvar excludeLabels []string\n\tvar err error\n\n\t// verify the given endpoint, it should be one of supported connectors\n\tif ctx.String(\"endpoint\") == \"\" {\n\t\treturn fmt.Errorf(\"endpoint type is missing\")\n\t}\n\tconnector := ctx.String(\"endpoint\")\n\tif !connectors.ConnectorRegistered(connector) {\n\t\treturn fmt.Errorf(\"given endpoint isn't supported: %v\", connector)\n\t}\n\n\tif !ctx.Bool(\"no-filter-tags\") { // if the flag is not there, lets apply the filter\n\t\tfilterReStr := ctx.String(\"filter-tags\")\n\t\tif filterReStr == \"\" {\n\t\t\treturn fmt.Errorf(\"regular expression for tag filtering should be defined\")\n\t\t}\n\t\tif filterRe, err = regexp.Compile(filterReStr); err != nil {\n\t\t\treturn fmt.Errorf(\"can't compile the regular expression: %v\", err)\n\t\t}\n\t}\n\n\tls := ctx.String(\"exclude-labels\")\n\tif ls != \"\" {\n\t\texcludeLabels = strings.Split(ls, \",\")\n\t\t//trim spaces from label names\n\t\tfor i := range excludeLabels {\n\t\t\texcludeLabels[i] = strings.Trim(excludeLabels[i], \" \")\n\t\t}\n\t}\n\n\tconn, err := connectors.NewConnector(connector, ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\texists, err := conn.RepositoryExists()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !exists {\n\t\t// TODO: this should provide detailed information about repository: owner, repo name\n\t\treturn fmt.Errorf(\"project not found\")\n\t}\n\n\ttags, issues, mrs, err := getConnectorData(\n\t\tconn,\n\t\tfilterRe,\n\t\texcludeLabels,\n\t\tctx.String(\"new-release\"),\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgen := generator.New(data.NewReleases(tags, issues, mrs))\n\n\t// use stdout if - is given, otherwise create a new file\n\tfilename := ctx.String(\"file\")\n\tvar wr io.Writer\n\tif filename != \"-\" {\n\t\tvar file *os.File\n\t\tif file, err = os.Create(filename); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif cerr := file.Close(); err == nil && cerr != nil {\n\t\t\t\terr = cerr\n\t\t\t}\n\t\t}()\n\n\t\twr = file\n\t} else {\n\t\twr = Stdout\n\t}\n\n\terr = gen.Render(wr)\n\n\treturn err\n}", "func (g Generator) Generate() error {\n\tdefaultSchema := \"public\"\n\tif g.DefaultSchema != \"\" {\n\t\tdefaultSchema = g.DefaultSchema\n\t}\n\n\ttableFiles, err := listYamlFiles(\"tables\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tviewFiles, err := listYamlFiles(\"views\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttableSpecs, err := createTableSpecs(tableFiles, defaultSchema)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tviewSpecs, err := createViewSpecs(viewFiles, defaultSchema)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trootDir := \".\"\n\tif g.RootDir != \"\" {\n\t\trootDir = g.RootDir\n\t}\n\n\ti, err := interpolation.NewInterpolator(g.BaseImportPath, rootDir, defaultSchema, tableSpecs, viewSpecs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = i.Interpolate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ti.DisplayTargets()\n\n\terr = g.generateCommons(i)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = g.generateTables(i.TablesData)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = g.generateViews(i.ViewsData)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Generate(env environ.Values, cfg *Config) error {\n\tinfo, err := cfg.Driver.Parse(env.Log, cfg.ConnStr, cfg.Schemas, makeFilter(cfg.IncludeTables, cfg.ExcludeTables))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdb, err := makeData(env.Log, info, cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(cfg.SchemaPaths) == 0 {\n\t\tenv.Log.Println(\"No SchemaPaths specified, skipping schemas.\")\n\t} else {\n\t\tif err := generateSchemas(env, cfg, db); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif len(cfg.EnumPaths) == 0 {\n\t\tenv.Log.Println(\"No EnumPath specified, skipping enums.\")\n\t} else {\n\t\tif err := generateEnums(env, cfg, db); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif len(cfg.TablePaths) == 0 {\n\t\tenv.Log.Println(\"No table path specified, skipping tables.\")\n\t} else {\n\t\tif err := generateTables(env, cfg, db); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn copyStaticFiles(env, cfg.StaticDir, cfg.OutputDir)\n}", "func generate(ctx *Context) (err error) {\n\tgt, err := parseDirRecursive(ctx)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Create dummies if no C & C++ files will be generated.\n\tif len(gt.Packages) == 0 {\n\t\treturn generateDummyFiles(ctx)\n\t}\n\n\terr = generateCMainHeader(gt, ctx.CGenIncludeDir)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, gp := range gt.Packages {\n\t\terr = generateGoFile(gp)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\terr = generateCHeaderFile(gp, ctx.CGenDir)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\terr = generateCPPHeaderFile(gp, ctx.CPPGenDir)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\terr = generateCPPSourceFile(gp, ctx.CPPGenDir)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func generate(copyrights string, collector *collector, templateBuilder templateBuilder) {\n\tfor _, pkg := range collector.Packages {\n\t\tfileTemplate := fileTpl{\n\t\t\tCopyright: copyrights,\n\n\t\t\tStandardImports: []string{\n\t\t\t\t\"fmt\",\n\t\t\t\t\"unicode\",\n\t\t\t\t\"unicode/utf8\",\n\t\t\t},\n\n\t\t\tCustomImports: []string{\n\t\t\t\t\"github.com/google/uuid\",\n\t\t\t},\n\t\t}\n\t\tfor _, f := range pkg.Files {\n\t\t\tfor _, d := range f.Decls {\n\t\t\t\tg, ok := d.(*ast.GenDecl)\n\t\t\t\tif !ok {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tstructs := structSearch(g)\n\t\t\t\tif len(structs) == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tfor _, s := range structs {\n\t\t\t\t\tatLeastOneField := false\n\n\t\t\t\t\tfor _, field := range s.Type.Fields.List {\n\n\t\t\t\t\t\tpos := collector.FileSet.Position(field.Type.Pos())\n\t\t\t\t\t\ttyp := collector.Info.TypeOf(field.Type)\n\n\t\t\t\t\t\tcomposedType := \"\"\n\t\t\t\t\t\tbaseName := getType(typ, &composedType)\n\t\t\t\t\t\tfmt.Println(\"Add validation: \", pos, \": \", baseName, \"/\", composedType)\n\n\t\t\t\t\t\tif err := templateBuilder.generateCheck(field, s.Name, baseName, composedType); err != nil {\n\t\t\t\t\t\t\tfmt.Printf(\"struct %s: %s\\n\", s.Name, err)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tatLeastOneField = true\n\t\t\t\t\t}\n\n\t\t\t\t\tif !atLeastOneField {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\terr := templateBuilder.generateMethod(s.Name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Printf(\"struct gen %s: %s\\n\", s.Name, err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfileTemplate.Package = pkg.Name\n\t\terr := templateBuilder.generateFile(pkg.Path, fileTemplate)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Generation error\", err)\n\t\t}\n\t}\n}", "func TestGenerator_Generate(t *testing.T) {\n\timportmap := map[string]string{\n\t\t\"policy/v1beta1/value_type.proto\": \"istio.io/api/policy/v1beta1\",\n\t\t\"mixer/adapter/model/v1beta1/extensions.proto\": \"istio.io/api/mixer/adapter/model/v1beta1\",\n\t\t\"gogoproto/gogo.proto\": \"github.com/gogo/protobuf/gogoproto\",\n\t\t\"google/protobuf/duration.proto\": \"github.com/gogo/protobuf/types\",\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\tfdsFiles map[string]string // FDS and their package import paths\n\t\twant string\n\t}{\n\t\t{\"AllTemplates\", map[string]string{\n\t\t\t\"testdata/check/template.descriptor\": \"istio.io/istio/mixer/template/list\",\n\t\t\t\"testdata/report2/template.descriptor\": \"istio.io/istio/mixer/template/metric\",\n\t\t\t\"testdata/quota/template.descriptor\": \"istio.io/istio/mixer/template/quota\",\n\t\t\t\"testdata/apa/template.descriptor\": \"istio.io/istio/mixer/template/apa\",\n\t\t\t\"testdata/report1/template.descriptor\": \"istio.io/istio/mixer/template/log\"},\n\t\t\t\"testdata/template.gen.go.golden\"},\n\t}\n\tfor _, v := range tests {\n\t\tt.Run(v.name, func(t *testing.T) {\n\t\t\ttestTmpDir := path.Join(os.TempDir(), \"bootstrapTemplateTest\")\n\t\t\t_ = os.MkdirAll(testTmpDir, os.ModeDir|os.ModePerm)\n\t\t\toutFile, err := os.Create(path.Join(testTmpDir, path.Base(v.want)))\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\tif !t.Failed() {\n\t\t\t\t\tif removeErr := os.RemoveAll(testTmpDir); removeErr != nil {\n\t\t\t\t\t\tt.Logf(\"Could not remove temporary folder %s: %v\", testTmpDir, removeErr)\n\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tt.Logf(\"Generated data is located at '%s'\", testTmpDir)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tg := Generator{OutFilePath: outFile.Name(), ImportMapping: importmap}\n\t\t\tif err := g.Generate(v.fdsFiles); err != nil {\n\t\t\t\tt.Fatalf(\"Generate(%s) produced an error: %v\", v.fdsFiles, err)\n\t\t\t}\n\n\t\t\tif same := fileCompare(outFile.Name(), v.want, t.Errorf); !same {\n\t\t\t\tt.Errorf(\"Files %v and %v were not the same.\", outFile.Name(), v.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func (l *library) generate() error {\n\t// write empty __init__.py in each dir\n\twalkFn := func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\treturn generateEmptyInitPy(path)\n\t}\n\n\tif err := filepath.Walk(l.baseDir, walkFn); err != nil {\n\t\treturn err\n\t}\n\n\t// json schema\n\tif err := generateJSONSchema(&raml.APIDefinition{\n\t\tTypes: l.Types,\n\t}, l.dir); err != nil {\n\t\tlog.Errorf(\"failed to generate jsonschema:%v\", err)\n\t\treturn err\n\t}\n\n\t// security schemes\n\tif err := generateServerSecurity(l.SecuritySchemes, templates(serverKindFlask), l.dir); err != nil {\n\t\treturn err\n\t}\n\n\t// included libraries\n\tfor _, ramlLib := range l.Libraries {\n\t\tchildLib := newLibrary(ramlLib, l.baseDir)\n\t\tif err := childLib.generate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func main() {\n\tif len(os.Args) < 4 {\n\t\tfmt.Fprintln(os.Stderr, \"not enough program arguments: [cmd] [package] [model] [mattermost-server dir]\")\n\t\tos.Exit(1)\n\t}\n\tpackageName := os.Args[1]\n\tmodelName := os.Args[2]\n\tvar goFiles []string\n\twalker := func(fullPath string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif (info.IsDir() && strings.HasPrefix(info.Name(), \".\")) || strings.Contains(fullPath, \"mattermost-server/vendor\") {\n\t\t\treturn nil\n\t\t}\n\t\tif path.Ext(info.Name()) == \".go\" && !strings.HasSuffix(info.Name(), \"_test\") {\n\t\t\tgoFiles = append(goFiles, fullPath)\n\t\t}\n\t\treturn nil\n\t}\n\tif err := filepath.Walk(os.Args[3], walker); err != nil {\n\t\tlog.Fatalf(\"could not scan folder: %v\", err)\n\t}\n\tfset := token.NewFileSet()\n\n\tfor _, fileName := range goFiles {\n\t\tfileNode, err := parser.ParseFile(fset, fileName, nil, parser.AllErrors|parser.ParseComments)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"could not parse %s: %v\", fileName, err)\n\t\t\tcontinue\n\t\t}\n\t\tw := &finder.Walker{\n\t\t\tName: modelName,\n\t\t\tPackage: packageName,\n\t\t}\n\t\tresult := w.Process(fileNode)\n\t\tbuf := new(bytes.Buffer)\n\t\tif err = format.Node(buf, fset, result); err != nil {\n\t\t\tlog.Printf(\"error: %v\\n\", err)\n\t\t} else if err := ioutil.WriteFile(fileName, buf.Bytes(), 0664); err != nil {\n\t\t\tlog.Printf(\"error: %v\\n\", err)\n\t\t}\n\t}\n}", "func (Docs) Generate() error {\n\treturn sh.RunWith(ENV, \"go\", \"run\", \"-tags=mage_docs\", \"./magefiles\")\n}", "func generateSchemaFile(o, wdPath string) error {\n\tsData, err := GenerateSchema()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// check if the provided output path is relative\n\tif !path.IsAbs(o) {\n\t\to = path.Join(wdPath, o)\n\t}\n\n\terr = os.WriteFile(path.Join(o, schemaFileName), sData, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tLog.Info(\"generated JSON schema for BlueprintMetadata\", \"path\", path.Join(o, schemaFileName))\n\treturn nil\n}", "func generatePbFiles() error {\n\tfullPath := filepath.Join(appPath)\n\n\t_, err := os.Stat(fullPath)\n\tif err != nil {\n\t\tos.MkdirAll(fullPath, os.ModePerm)\n\t}\n\n\t_, err = exec.LookPath(\"protoc\")\n\tif err != nil {\n\t\tlog.Fatal(\"protoc is not available\")\n\t\treturn err\n\t}\n\n\terr = Exec(\"protoc\", \"-I\", protoPath, protoPath+string(filepath.Separator)+protoFileName, \"--go_out=plugins=grpc:\"+fullPath)\n\tif err != nil {\n\t\t_, statErr := os.Stat(fullPath)\n\t\tif statErr == nil {\n\t\t\tos.RemoveAll(fullPath)\n\t\t}\n\t\tlog.Fatal(\"error occured\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func Generate(ctx context.Context, p StructProvider, filename string, pkg string, embedStructs bool) error {\n\tstructs, err := p.ProvideStructs(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !embedStructs {\n\t\tvar results []*structbuilder.Struct\n\t\tfor _, s := range structs {\n\t\t\tresults = append(results, s.UnembedStructs()...)\n\t\t}\n\n\t\tstructs = results\n\t}\n\n\timportPaths := uniqueImportPaths(structs)\n\n\tdata := struct {\n\t\tStructs []*structbuilder.Struct\n\t\tPackage string\n\t\tImportPaths []string\n\t}{\n\t\tstructs,\n\t\tpkg,\n\t\timportPaths,\n\t}\n\n\tvar buf bytes.Buffer\n\tif err := tmpl.Execute(&buf, &data); err != nil {\n\t\treturn err\n\t}\n\n\t//formatted := buf.Bytes()\n\tformatted, err := format.Source(buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif filename != \"\" {\n\t\treturn ioutil.WriteFile(filename, formatted, 0666)\n\t}\n\n\tfmt.Println(string(formatted))\n\treturn nil\n}", "func main() {\n\tgodotenv.Load(os.Getenv(\"PWD\") + \"/.env\")\n\tuser := os.Getenv(\"DB_USERNAME\")\n\tpass := os.Getenv(\"DB_PASSWORD\")\n\thost := os.Getenv(\"DB_HOSTNAME\")\n\tport := os.Getenv(\"DB_PORT\")\n\tdatabase := os.Getenv(\"DB_DATABASE\")\n\n\tmode := flag.String(\"mode\", \"code\", \"Generate Mode\")\n\ttemplatePath := flag.String(\"template\", os.Getenv(\"PWD\")+\"/template\", \"Template Path\")\n\toutputPath := flag.String(\"project\", os.Getenv(\"PWD\")+\"/src\", \"Project Path\")\n\trelationMode := flag.Bool(\"relation\", false, \"Relation Mode\")\n\tflag.Parse()\n\n\tfmt.Println(\"Generate Mode: \" + *mode)\n\tfmt.Println(\"Template Path: \" + *templatePath)\n\tfmt.Println(\"Project Path: \" + *outputPath)\n\n\tif *mode == \"json\" || *mode == \"all\" {\n\t\tfmt.Println(\"Generate:\", \"goapigen.json\")\n\t\tfmt.Println(\"hostdb:\", host)\n\t\tfmt.Println(\"Connecting to mysql server \" + host + \":\" + port)\n\t\tgenjson.GenJson(user, pass, host, port, database, *relationMode)\n\t}\n\n\tif *mode == \"code\" || *mode == \"all\" {\n\t\tgenstruct.GenStruct(*templatePath, *outputPath)\n\t}\n\n\treturn\n}", "func generateGoSchemaFile(schema map[string]interface{}, config Config) {\r\n var obj map[string]interface{}\r\n var schemas = make(map[string]interface{})\r\n var outString = \"package main\\n\\nvar schemas = `\\n\"\r\n\r\n var filename = config.Schemas.GoSchemaFilename\r\n var apiFunctions = config.Schemas.API\r\n var elementNames = config.Schemas.GoSchemaElements\r\n \r\n var functionKey = \"API\"\r\n var objectModelKey = \"objectModelSchemas\"\r\n \r\n schemas[functionKey] = interface{}(make(map[string]interface{}))\r\n schemas[objectModelKey] = interface{}(make(map[string]interface{}))\r\n\r\n fmt.Printf(\"Generate Go SCHEMA file %s for: \\n %s and: \\n %s\\n\", filename, apiFunctions, elementNames)\r\n\r\n // grab the event API functions for input\r\n for i := range apiFunctions {\r\n functionSchemaName := \"#/definitions/API/\" + apiFunctions[i]\r\n functionName := apiFunctions[i]\r\n obj = getObject(schema, functionSchemaName)\r\n if obj == nil {\r\n fmt.Printf(\"** WARN ** %s returned nil from getObject\\n\", functionSchemaName)\r\n return\r\n }\r\n schemas[functionKey].(map[string]interface{})[functionName] = obj \r\n } \r\n\r\n // grab the elements requested (these are useful separately even though\r\n // they obviously appear already as part of the event API functions)\r\n for i := range elementNames {\r\n elementName := elementNames[i]\r\n obj = getObject(schema, elementName)\r\n if obj == nil {\r\n fmt.Printf(\"** ERR ** %s returned nil from getObject\\n\", elementName)\r\n return\r\n }\r\n schemas[objectModelKey].(map[string]interface{})[elementName] = obj \r\n }\r\n \r\n // marshal for output to file \r\n schemaOut, err := json.MarshalIndent(&schemas, \"\", \" \")\r\n if err != nil {\r\n fmt.Printf(\"** ERR ** cannot marshal schema file output for writing\\n\")\r\n return\r\n }\r\n outString += string(schemaOut) + \"`\"\r\n ioutil.WriteFile(filename, []byte(outString), 0644)\r\n}", "func Generate() error {\n\tmg.Deps(Download)\n\tmg.Deps(appConf)\n\tmg.Deps(manifest)\n\tmg.Deps(versionInfo)\n\n\tfmt.Println(\"⚙️ Go generate...\")\n\tif err := sh.RunV(mg.GoCmd(), \"generate\", \"-v\"); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (g *Generator) Generate() error {\n\tsteps := []func() error{\n\t\tg.prepareData,\n\t\tg.genModels,\n\t\tg.genSchema,\n\t}\n\n\tfor _, s := range steps {\n\t\tif err := s(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (input Input) GenerateModel() error {\n\tfolderName := \"model\"\n\t// Create model folder if not exists\n\tif _, err := os.Stat(folderName); os.IsNotExist(err) {\n\t\terr = os.MkdirAll(folderName, 0755)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tcontent, err := input.generateHeaderContent()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif input.Settings.List {\n\t\tcontent += \"\\n\\n\" + input.getnerateGetFunction()\n\t}\n\tif input.Settings.Add {\n\t\tcontent += \"\\n\\n\" + input.generateCreateFunction()\n\t}\n\tif input.Settings.Details {\n\t\tcontent += \"\\n\\n\" + input.generateGetDetailsFunction()\n\t}\n\tif input.Settings.Update {\n\t\tcontent += \"\\n\\n\" + input.generateUpdateFunction()\n\t}\n\tif input.Settings.Delete {\n\t\tcontent += \"\\n\\n\" + input.generateDeleteFunction()\n\t}\n\tcontent += \"\\n\\n\" + input.generateExports()\n\n\tfilename := strings.ToLower(input.Name) + \".js\"\n\n\terr = ioutil.WriteFile(folderName+\"/\"+filename, []byte(content), 0644)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func RunGenerate(output, input, title, description string) error {\n\tvar err error\n\tvar t *template.Template\n\tvar fd *os.File\n\n\tpages := filepath.Join(output, \"post\")\n\tif err = createStructure(input, output); err != nil {\n\t\treturn errors.Wrap(err, \"create directory structure\")\n\t}\n\tif err = models.ParseDir(input); err != nil {\n\t\treturn errors.Wrap(err, \"parse input directory\")\n\t}\n\tif t, err = template.ParseGlob(\"templates/*.tmpl\"); err != nil {\n\t\treturn errors.Wrap(err, \"parse template glob\")\n\t}\n\tfor _, v := range models.MPages {\n\t\tv.Slug = v.Slug + \".html\"\n\t\tif fd, err = os.Create(filepath.Join(pages, v.Slug)); err != nil {\n\t\t\treturn errors.Wrap(err, \"create post file\")\n\t\t}\n\t\tif err = t.ExecuteTemplate(\n\t\t\tfd, \"post.tmpl\",\n\t\t\tgin.H{\"post\": v, \"gitalk\": gin.H{}, \"local\": true},\n\t\t); err != nil {\n\t\t\treturn errors.Wrap(err, \"execute template post\")\n\t\t}\n\t}\n\n\tif fd, err = os.Create(filepath.Join(output, \"index.html\")); err != nil {\n\t\treturn errors.Wrap(err, \"create index file\")\n\t}\n\tdata := gin.H{\n\t\t\"posts\": models.SPages,\n\t\t\"title\": title,\n\t\t\"description\": description,\n\t\t\"local\": true,\n\t\t\"author\": models.GetGlobalAuthor(),\n\t}\n\tif err = t.ExecuteTemplate(fd, \"index.tmpl\", data); err != nil {\n\t\treturn errors.Wrap(err, \"execute template index\")\n\t}\n\treturn nil\n}", "func Generate() ([]string, error) {\n\tvar (\n\t\tver string\n\t\toutDir string\n\t)\n\tset := flag.NewFlagSet(\"app\", flag.PanicOnError)\n\tset.String(\"design\", \"\", \"\") // Consume design argument so Parse doesn't complain\n\tset.StringVar(&ver, \"version\", \"\", \"\")\n\tset.StringVar(&outDir, \"out\", \"\", \"\")\n\tset.Parse(os.Args[2:])\n\t// First check compatibility\n\tif err := codegen.CheckVersion(ver); err != nil {\n\t\treturn nil, err\n\t}\n\treturn writeFunctions(design.Design, outDir)\n}", "func CollectModels(outModelDir string) (Models, error) {\n\tfiles, err := ioutil.ReadDir(outModelDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar models Models\n\tvar wg sync.WaitGroup\n\tvar mu sync.Mutex\n\terrCh := make(chan error, 1)\n\tdone := make(chan bool, 1)\n\n\tfor _, file := range files {\n\t\twg.Add(1)\n\t\tgo func(f os.FileInfo) {\n\t\t\tdefer wg.Done()\n\t\t\tif f.IsDir() {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !strings.HasSuffix(f.Name(), \".go\") {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tmodelPath := filepath.Join(outModelDir, f.Name())\n\t\t\tms, err := ParseModel(modelPath)\n\t\t\tif err != nil {\n\t\t\t\terrCh <- err\n\t\t\t}\n\n\t\t\tmu.Lock()\n\n\t\t\tfor _, m := range ms {\n\t\t\t\tmodels = append(models, m)\n\t\t\t}\n\n\t\t\tmu.Unlock()\n\t\t}(file)\n\t}\n\n\twg.Wait()\n\tclose(done)\n\n\tselect {\n\tcase <-done:\n\tcase err := <-errCh:\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn models, nil\n}", "func (a Generator) Run(root string, data makr.Data) error {\n\tg := makr.New()\n\n\tif a.AsAPI {\n\t\tdefer os.RemoveAll(filepath.Join(a.Root, \"templates\"))\n\t\tdefer os.RemoveAll(filepath.Join(a.Root, \"locales\"))\n\t\tdefer os.RemoveAll(filepath.Join(a.Root, \"public\"))\n\t}\n\tif a.Force {\n\t\tos.RemoveAll(a.Root)\n\t}\n\n\tg.Add(makr.NewCommand(makr.GoGet(\"golang.org/x/tools/cmd/goimports\", \"-u\")))\n\tif a.WithDep {\n\t\tg.Add(makr.NewCommand(makr.GoGet(\"github.com/golang/dep/cmd/dep\", \"-u\")))\n\t}\n\n\tfiles, err := generators.FindByBox(packr.NewBox(\"../newapp/templates\"))\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tfor _, f := range files {\n\t\tif !a.AsAPI {\n\t\t\tg.Add(makr.NewFile(f.WritePath, f.Body))\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.Contains(f.WritePath, \"locales\") || strings.Contains(f.WritePath, \"templates\") || strings.Contains(f.WritePath, \"public\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tg.Add(makr.NewFile(f.WritePath, f.Body))\n\t}\n\n\tdata[\"name\"] = a.Name\n\tif err := refresh.Run(root, data); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\ta.setupCI(g, data)\n\n\tif err := a.setupWebpack(root, data); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif err := a.setupPop(root, data); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif err := a.setupDocker(root, data); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tg.Add(makr.NewCommand(a.goGet()))\n\n\tg.Add(makr.Func{\n\t\tRunner: func(root string, data makr.Data) error {\n\t\t\tg.Fmt(root)\n\t\t\treturn nil\n\t\t},\n\t})\n\n\ta.setupVCS(g)\n\n\tdata[\"opts\"] = a\n\treturn g.Run(root, data)\n}", "func GenerateTestSupport(name string, modelNames, operationIDs []string, includeUI bool,includeTCK bool, opts GenOpts) error {\n\t\t// Load the spec\n\t_, specDoc, err := loadSpec(opts.Spec)\n\t\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\t\n\tmodels, mnc := make(map[string]spec.Schema), len(modelNames)\n\tfor k, v := range specDoc.Spec().Definitions {\n\t\tfor _, nm := range modelNames {\n\t\t\tif mnc == 0 || k == nm {\n\t\t\t\tmodels[k] = v\n\t\t\t}\n\t\t}\n\t}\n\n\toperations := make(map[string]spec.Operation)\n\tif len(modelNames) == 0 {\n\t\tfor _, k := range specDoc.OperationIDs() {\n\t\t\tif op, ok := specDoc.OperationForName(k); ok {\n\t\t\t\toperations[k] = *op\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor _, k := range specDoc.OperationIDs() {\n\t\t\tfor _, nm := range operationIDs {\n\t\t\t\tif k == nm {\n\t\t\t\t\tif op, ok := specDoc.OperationForName(k); ok {\n\t\t\t\t\t\toperations[k] = *op\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif name == \"\" {\n\t\tif specDoc.Spec().Info != nil && specDoc.Spec().Info.Title != \"\" {\n\t\t\tname = swag.ToGoName(specDoc.Spec().Info.Title)\n\t\t} else {\n\t\t\tname = \"swagger\"\n\t\t}\n\t}\n\n\tgenerator := testGenerator{\n\t\tName: name,\n\t\tSpecDoc: specDoc,\n\t\tModels: models,\n\t\tOperations: operations,\n\t\tTarget: opts.Target,\n\t\tDumpData: opts.DumpData,\n\t\tPackage: opts.APIPackage,\n\t\tAPIPackage: opts.APIPackage,\n\t\tModelsPackage: opts.ModelPackage,\n\t\tServerPackage: opts.ServerPackage,\n\t\tClientPackage: opts.ClientPackage,\n\t\tPrincipal: opts.Principal,\n\t\tIncludeUI: includeUI,\n\t\tIncludeTCK: includeTCK,\n\t}\n\n\treturn generator.GenerateTest()\n}", "func (c *Converter) GenerateJSONSchemas() ([]types.GeneratedJSONSchema, error) {\n\n\tc.logger.Debug(\"Converting API\")\n\n\t// Store the output in here:\n\tgeneratedJSONSchemas, err := c.mapOpenAPIDefinitionsToJSONSchema()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not map openapi definitions to jsonschema\")\n\t}\n\n\treturn generatedJSONSchemas, nil\n}", "func (g *RPCGenerator) Generate(src, target string, protoImportPath []string, goOptions ...string) error {\n\tabs, err := filepath.Abs(target)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = util.MkdirIfNotExist(abs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = g.g.Prepare()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprojectCtx, err := ctx.Prepare(abs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp := parser.NewDefaultProtoParser()\n\tproto, err := p.Parse(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdirCtx, err := mkdir(projectCtx, proto)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = g.g.GenEtc(dirCtx, proto, g.cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = g.g.GenPb(dirCtx, protoImportPath, proto, g.cfg, goOptions...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = g.g.GenConfig(dirCtx, proto, g.cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = g.g.GenSvc(dirCtx, proto, g.cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = g.g.GenLogic(dirCtx, proto, g.cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = g.g.GenServer(dirCtx, proto, g.cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = g.g.GenMain(dirCtx, proto, g.cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = g.g.GenCall(dirCtx, proto, g.cfg)\n\n\tconsole.NewColorConsole().MarkDone()\n\n\treturn err\n}", "func (a *App) Generator(data makr.Data) (*makr.Generator, error) {\n\tg := makr.New()\n\tg.Add(makr.NewCommand(makr.GoGet(\"golang.org/x/tools/cmd/goimports\", \"-u\")))\n\tg.Add(makr.NewCommand(makr.GoGet(\"github.com/golang/dep/cmd/dep\", \"-u\")))\n\tg.Add(makr.NewCommand(makr.GoGet(\"github.com/motemen/gore\", \"-u\")))\n\n\tfiles, err := generators.Find(filepath.Join(generators.TemplatesPath, \"newapp\"))\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\n\tfor _, f := range files {\n\t\tg.Add(makr.NewFile(f.WritePath, f.Body))\n\t}\n\trr, err := refresh.New()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tg.Add(rr)\n\n\tif data[\"ciProvider\"] == \"travis\" {\n\t\tg.Add(makr.NewFile(\".travis.yml\", nTravis))\n\t} else if data[\"ciProvider\"] == \"gitlab-ci\" {\n\t\tif _, ok := data[\"withPop\"]; ok {\n\t\t\tif data[\"dbType\"] == \"postgres\" {\n\t\t\t\tdata[\"testDbUrl\"] = \"postgres://postgres:postgres@postgres:5432/\" + data[\"name\"].(string) + \"_test?sslmode=disable\"\n\t\t\t} else if data[\"dbType\"] == \"mysql\" {\n\t\t\t\tdata[\"testDbUrl\"] = \"mysql://root:root@mysql:3306/\" + data[\"name\"].(string) + \"_test\"\n\t\t\t} else {\n\t\t\t\tdata[\"testDbUrl\"] = \"\"\n\t\t\t}\n\t\t\tg.Add(makr.NewFile(\".gitlab-ci.yml\", nGitlabCi))\n\t\t} else {\n\t\t\tg.Add(makr.NewFile(\".gitlab-ci.yml\", nGitlabCiNoPop))\n\t\t}\n\t}\n\n\tif !a.API {\n\t\tif a.SkipWebpack {\n\t\t\twg, err := standard.New(data)\n\t\t\tif err != nil {\n\t\t\t\treturn g, errors.WithStack(err)\n\t\t\t}\n\t\t\tg.Add(wg)\n\t\t} else if a.WithReact {\n\t\t\twg, err := react.New(data)\n\t\t\tif err != nil {\n\t\t\t\treturn g, err\n\t\t\t}\n\t\t\tg.Add(wg)\n\t\t} else {\n\t\t\twg, err := webpack.New(data)\n\t\t\tif err != nil {\n\t\t\t\treturn g, errors.WithStack(err)\n\t\t\t}\n\t\t\tg.Add(wg)\n\t\t}\n\t}\n\tif !a.SkipPop {\n\t\tg.Add(newSodaGenerator())\n\t}\n\tif a.API {\n\t\tg.Add(makr.Func{\n\t\t\tRunner: func(path string, data makr.Data) error {\n\t\t\t\treturn os.RemoveAll(filepath.Join(path, \"templates\"))\n\t\t\t},\n\t\t})\n\t\tg.Add(makr.Func{\n\t\t\tRunner: func(path string, data makr.Data) error {\n\t\t\t\treturn os.RemoveAll(filepath.Join(path, \"locales\"))\n\t\t\t},\n\t\t})\n\t}\n\tif a.Docker != \"none\" {\n\t\tdg, err := docker.New()\n\t\tif err != nil {\n\t\t\treturn g, errors.WithStack(err)\n\t\t}\n\t\tg.Add(dg)\n\t}\n\tg.Add(makr.NewCommand(a.goGet()))\n\n\tif _, err := exec.LookPath(\"git\"); err == nil {\n\t\tg.Add(makr.NewCommand(exec.Command(\"git\", \"init\")))\n\t\tg.Add(makr.NewCommand(exec.Command(\"git\", \"add\", \".\")))\n\t\tg.Add(makr.NewCommand(exec.Command(\"git\", \"commit\", \"-m\", \"Initial Commit\")))\n\t}\n\n\treturn g, nil\n}", "func Generate() error {\n\tmg.Deps(Download)\n\tmg.Deps(appConf)\n\tmg.Deps(versionInfo)\n\n\tfmt.Println(\"⚙️ Go generate...\")\n\tif err := sh.RunV(mg.GoCmd(), \"generate\", \"-v\"); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Generate(fileSet *token.FileSet, pkgs map[string]*ast.Package, pkgPath string, typeName string) *ast.File {\n\tpkg, spec, zeroValue, values, valueStrings, _ := findDefinitions(fileSet, pkgs, typeName)\n\treturn generateFile(pkg, spec, zeroValue, values, valueStrings)\n}", "func (g *Generator) GenerateMessages() error {\n\tfor _, message := range g.depfile.ProtoFile.CollectMessages() {\n\t\terr := g.generateMessage(message.(*fproto.MessageElement))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (s *Server) Generate() error {\n\tif err := s.generateSchemas(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := s.generateMain(); err != nil {\n\t\treturn err\n\t}\n\n\treturn s.generateResources()\n}", "func main() {\n\tgenerateSwaggerJSON()\n}", "func (s *Service) GenerateManifest(ctx context.Context, q *apiclient.ManifestRequest) (*apiclient.ManifestResponse, error) {\n\tconfig := s.initConstants.PluginConfig\n\n\tenv := append(os.Environ(), environ(q.Env)...)\n\tif len(config.Spec.Init.Command) > 0 {\n\t\t_, err := runCommand(config.Spec.Init, q.AppPath, env)\n\t\tif err != nil {\n\t\t\treturn &apiclient.ManifestResponse{}, err\n\t\t}\n\t}\n\n\tout, err := runCommand(config.Spec.Generate, q.AppPath, env)\n\tif err != nil {\n\t\treturn &apiclient.ManifestResponse{}, err\n\t}\n\n\tmanifests, err := kube.SplitYAMLToString([]byte(out))\n\tif err != nil {\n\t\treturn &apiclient.ManifestResponse{}, err\n\t}\n\n\treturn &apiclient.ManifestResponse{\n\t\tManifests: manifests,\n\t}, err\n}", "func (g *Generator) Generate(opts ...Option) error {\n\tfor _, opt := range opts {\n\t\tif err := opt(g); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif g.getWriter == nil {\n\t\treturn errNoGetWriter\n\t}\n\n\tpkg, err := g.generate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tw, err := g.getWriter()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn genutil.WriteYAML(w, pkg)\n}", "func (baseModel *BaseModel) Generate(specificModel AppliedAlgorithm) {\n specificModel.Clear()\n for {\n finished := baseModel.SingleIteration(specificModel)\n if finished {\n return\n }\n }\n}", "func (mfs *MemFS) GoGenerate(pkgName, out, contentEncoding string) (err error) {\n\tif len(pkgName) == 0 {\n\t\tpkgName = \"main\"\n\t}\n\tif len(out) == 0 {\n\t\tout = \"memfs_generate.go\"\n\t}\n\n\ttmpl, err := generateTemplate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(out)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"memfs: GoGenerate: %w\", err)\n\t}\n\n\tif len(contentEncoding) > 0 {\n\t\terr = mfs.ContentEncode(contentEncoding)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"GoGenerate: %w\", err)\n\t\t}\n\t}\n\n\tnames := mfs.ListNames()\n\n\terr = tmpl.ExecuteTemplate(f, templateNameHeader, pkgName)\n\tif err != nil {\n\t\tgoto fail\n\t}\n\n\tfor x := 0; x < len(names); x++ {\n\t\t// Ignore and delete the file from map if its the output\n\t\t// itself.\n\t\tif strings.HasSuffix(names[x], out) {\n\t\t\tdelete(mfs.pn.v, names[x])\n\t\t\tcontinue\n\t\t}\n\n\t\tnode := mfs.pn.v[names[x]]\n\t\terr = tmpl.ExecuteTemplate(f, templateNameGenerateNode, node)\n\t\tif err != nil {\n\t\t\tgoto fail\n\t\t}\n\t}\n\n\terr = tmpl.ExecuteTemplate(f, templateNamePathFuncs, mfs.pn.v)\n\tif err != nil {\n\t\tgoto fail\n\t}\n\n\terr = f.Sync()\n\tif err != nil {\n\t\tgoto fail\n\t}\n\n\terr = f.Close()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"memfs: GoGenerate: %w\", err)\n\t}\n\n\treturn nil\nfail:\n\t_ = f.Close()\n\treturn fmt.Errorf(\"memfs: GoGenerate: %w\", err)\n}", "func (g Generator) Generate(ctx *genall.GenerationContext) error {\n\tobjs := generateFeatures(ctx)\n\n\tif len(objs) == 0 {\n\t\treturn nil\n\t}\n\tfor _, obj := range objs {\n\t\tif err := ctx.WriteYAML(obj.(corev1alpha2.Feature).Name+\".yaml\", obj); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (g *GenprotoGenerator) Regen(ctx context.Context) error {\n\tlog.Println(\"regenerating genproto\")\n\t// Create space to put generated .pb.go's.\n\tc := execv.Command(\"mkdir\", \"-p\", \"generated\")\n\tc.Dir = g.genprotoDir\n\tif err := c.Run(); err != nil {\n\t\treturn err\n\t}\n\n\t// Get the last processed googleapis hash.\n\tlastHash, err := os.ReadFile(filepath.Join(g.genprotoDir, \"regen.txt\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO(noahdietz): In local mode, since it clones a shallow copy with 1 commit,\n\t// if the last regenerated hash is earlier than the top commit, the git diff-tree\n\t// command fails. This is is a bit of a rough edge. Using my local clone of\n\t// googleapis rectified the issue.\n\tpkgFiles, err := g.getUpdatedPackages(string(lastHash))\n\tif err != nil {\n\t\treturn err\n\t}\n\tpkgFiles, err = filterPackages(pkgFiles)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Println(\"generating from protos\")\n\tgrp, _ := errgroup.WithContext(ctx)\n\tfor pkg, fileNames := range pkgFiles {\n\t\tpk := pkg\n\t\tfn := fileNames\n\n\t\tgrp.Go(func() error {\n\t\t\tlog.Println(\"running protoc on\", pk)\n\t\t\treturn g.protoc(fn)\n\t\t})\n\t}\n\tif err := grp.Wait(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := g.moveAndCleanupGeneratedSrc(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := gocmd.Vet(g.genprotoDir); err != nil {\n\t\treturn err\n\t}\n\n\tif err := gocmd.Build(g.genprotoDir); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (g *Generator) Generate() error {\n\t// first we read the code from which we should find the types\n\tif err := g.readPackageCode(g.options.Source); err != nil {\n\t\treturn err\n\t}\n\n\t// then we generate code for the types given\n\tfor _, rootType := range g.options.Types {\n\t\tif err := g.generateStructCode(rootType); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t//\n\tg.Imports = strings.Join(toolbox.MapKeysToStringSlice(g.imports), \"\\n\")\n\treturn g.writeCode()\n}", "func generate(\n\tkustomization *types.Kustomization, overlay string, quayConfigFiles map[string][]byte,\n) ([]client.Object, error) {\n\tfSys := filesys.MakeEmptyDirInMemory()\n\tif err := filepath.Walk(\n\t\tkustomizeDir(),\n\t\tfunc(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif info.IsDir() {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tf, err := os.ReadFile(path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn fSys.WriteFile(path, f)\n\t\t},\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Write `kustomization.yaml` to filesystem\n\tkustomizationFile, err := yaml.Marshal(kustomization)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := fSys.WriteFile(\n\t\tfilepath.Join(appDir(), \"kustomization.yaml\"), kustomizationFile,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Add all Quay config files to directory to be included in the generated `Secret`\n\tfor fileName, file := range quayConfigFiles {\n\t\tif err := fSys.WriteFile(\n\t\t\tfilepath.Join(appDir(), \"bundle\", fileName), file,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\topts := &krusty.Options{\n\t\tPluginConfig: &types.PluginConfig{},\n\t}\n\tk := krusty.MakeKustomizer(opts)\n\tresMap, err := k.Run(fSys, overlay)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toutput := []client.Object{}\n\tfor _, resource := range resMap.Resources() {\n\t\tresourceJSON, err := resource.MarshalJSON()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tgvk := schema.GroupVersionKind{\n\t\t\tGroup: resource.GetGvk().Group,\n\t\t\tVersion: resource.GetGvk().Version,\n\t\t\tKind: resource.GetGvk().Kind,\n\t\t}\n\n\t\tobj := ModelFor(gvk)\n\t\tif obj == nil {\n\t\t\treturn nil, fmt.Errorf(\"kind not supported: %s\", gvk.Kind)\n\t\t}\n\n\t\tif err := json.Unmarshal(resourceJSON, obj); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\toutput = append(output, obj)\n\t}\n\n\treturn output, nil\n}", "func generate(g *Graph) error {\n\tvar (\n\t\tassets assets\n\t\texternal []GraphTemplate\n\t)\n\ttemplates, external = g.templates()\n\tfor _, n := range g.Nodes {\n\t\tassets.addDir(filepath.Join(g.Config.Target, n.PackageDir()))\n\t\tfor _, tmpl := range Templates {\n\t\t\tb := bytes.NewBuffer(nil)\n\t\t\tif err := templates.ExecuteTemplate(b, tmpl.Name, n); err != nil {\n\t\t\t\treturn fmt.Errorf(\"execute template %q: %w\", tmpl.Name, err)\n\t\t\t}\n\t\t\tassets.add(filepath.Join(g.Config.Target, tmpl.Format(n)), b.Bytes())\n\t\t}\n\t}\n\tfor _, tmpl := range append(GraphTemplates, external...) {\n\t\tif tmpl.Skip != nil && tmpl.Skip(g) {\n\t\t\tcontinue\n\t\t}\n\t\tif dir := filepath.Dir(tmpl.Format); dir != \".\" {\n\t\t\tassets.addDir(filepath.Join(g.Config.Target, dir))\n\t\t}\n\t\tb := bytes.NewBuffer(nil)\n\t\tif err := templates.ExecuteTemplate(b, tmpl.Name, g); err != nil {\n\t\t\treturn fmt.Errorf(\"execute template %q: %w\", tmpl.Name, err)\n\t\t}\n\t\tassets.add(filepath.Join(g.Config.Target, tmpl.Format), b.Bytes())\n\t}\n\tfor _, f := range AllFeatures {\n\t\tif f.cleanup == nil || g.featureEnabled(f) {\n\t\t\tcontinue\n\t\t}\n\t\tif err := f.cleanup(g.Config); err != nil {\n\t\t\treturn fmt.Errorf(\"cleanup %q feature assets: %w\", f.Name, err)\n\t\t}\n\t}\n\t// Write and format assets only if template execution\n\t// finished successfully.\n\tif err := assets.write(); err != nil {\n\t\treturn err\n\t}\n\t// cleanup assets that are not needed anymore.\n\tcleanOldNodes(assets, g.Config.Target)\n\t// We can't run \"imports\" on files when the state is not completed.\n\t// Because, \"goimports\" will drop undefined package. Therefore, it\n\t// is suspended to the end of the writing.\n\treturn assets.format()\n}", "func Generate(dirList ...string) {\n\tvar root = NewEmptyFileTree()\n\tfor _, dir := range dirList {\n\t\ttree := LoadFileTree(dir)\n\t\troot.Children = append(root.Children, tree)\n\t}\n\n\tvar RawFuncList []RawFunc\n\tWalkFileTree(root, &RawFuncList)\n\n\tvar handlers []HandlerFunc\n\tvar middlewares = make(map[string]*MiddlewareFunc)\n\tvar imports = make(map[string]bool)\n\tTraverseRawFuncList(&RawFuncList, &handlers, middlewares, imports)\n\n\tvar ctx GenContext\n\tctx.InitGroupTree(middlewares, &handlers)\n\n\ttplFile := GenTemplate()\n\tfor k, _ := range imports {\n\t\tAddImport(tplFile, k)\n\t}\n\n\tlist := ctx.Root.GenAST()\n\tfileExprListAppend(tplFile, &list)\n\n\texport(tplFile)\n}", "func Generate(destDir string, dbConn DBConnection) (err error) {\n\tdefer utils.ErrorCatch(&err)\n\n\tdb := openConnection(dbConn)\n\tdefer utils.DBClose(db)\n\n\tfmt.Println(\"Retrieving database information...\")\n\t// No schemas in MySQL\n\tdbInfo := metadata.GetSchemaMetaData(db, dbConn.DBName, &mySqlQuerySet{})\n\n\tgenPath := path.Join(destDir, dbConn.DBName)\n\n\ttemplate.GenerateFiles(genPath, dbInfo, mysql.Dialect)\n\n\treturn nil\n}", "func GenerateSupportFiles(packageName, path string) error {\n\n\tpath, _ = filepath.Abs(path)\n\t_, err := os.Stat(path)\n\tif err != nil {\n\t\tlog.Fatal(\"file path provided is invalid\")\n\t\treturn err\n\t}\n\n\tprotoPath = path[:strings.LastIndex(path, string(filepath.Separator))]\n\tprotoFileName = path[strings.LastIndex(path, string(filepath.Separator))+1:]\n\n\tlog.Println(\"protoPath:[\", protoPath, \"] protoFileName:[\", protoFileName, \"]\")\n\n\tprotoImpPath = strings.Split(protoFileName, \".\")[0]\n\n\tlog.Println(\"generating pb files\")\n\terr = generatePbFiles()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Println(\"getting proto data\")\n\tpdArr, err := getProtoData(packageName, path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// refactoring streaming methods and unary methods\n\tpdArr = arrangeProtoData(pdArr)\n\n\tlog.Println(\"creating trigger support files\")\n\terr = generateServiceImplFile(pdArr, \"server\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Println(\"creating service support files\")\n\terr = generateServiceImplFile(pdArr, \"client\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Println(\"support files created\")\n\treturn nil\n}", "func Generate(analysis *types.Analysis) {\n\tcreateFolders(analysis.Settings)\n\n\tcorrConditions := correlateConditions(analysis)\n\tcluster(corrConditions, analysis.Settings)\n\tcorrReadouts := correlateReadouts(analysis)\n\tcluster(corrReadouts, analysis.Settings)\n\n\tcreateCorrelationImages(corrConditions, corrReadouts, analysis.Settings)\n\tcreateCytoscapeFiles(corrConditions, corrReadouts, analysis.Settings)\n\twriteTrees(corrConditions, corrReadouts, analysis.Settings)\n\tcreateBaitPreyImages(analysis, corrConditions, corrReadouts)\n\n\tfs.Instance.RemoveAll(filepath.Join(\".\", \"minimap\"))\n}", "func (g *Generator) generate(file *FileDescriptor) {\n\tg.file = g.FileOf(file.FileDescriptorProto)\n\tg.usedPackages = make(map[string]bool)\n\n\tif g.file.index == 0 {\n\t\t// For one file in the package, assert version compatibility.\n\t\tg.P(\"// This is a compile-time assertion to ensure that this generated file\")\n\t\tg.P(\"// is compatible with the proto package it is being compiled against.\")\n\t\tg.P(\"// A compilation error at this line likely means your copy of the\")\n\t\tg.P(\"// proto package needs to be updated.\")\n\t\tg.P(\"const _ = \", g.Pkg[\"proto\"], \".ProtoPackageIsVersion\", generatedCodeVersion, \" // please upgrade the proto package\")\n\t\tg.P()\n\t}\n\n\tfor _, td := range g.file.imp {\n\t\tg.generateImported(td)\n\t}\n\tfor _, desc := range g.file.desc {\n\t\t// Don't generate virtual messages for maps.\n\t\tif desc.GetOptions().GetMapEntry() {\n\t\t\tcontinue\n\t\t}\n\t}\n\tg.generateInitFunction()\n\n\t// Run the plugins before the imports so we know which imports are necessary.\n\tg.runPlugins(file)\n\n\t// Generate header and imports last, though they appear first in the output.\n\trem := g.Buffer\n\tg.Buffer = new(bytes.Buffer)\n\tg.generateHeader()\n\tg.generateImports()\n\tif !g.writeOutput {\n\t\treturn\n\t}\n\tg.Write(rem.Bytes())\n\n\t// Reformat generated code.\n\tfset := token.NewFileSet()\n\traw := g.Bytes()\n\tast, err := parser.ParseFile(fset, \"\", g, parser.ParseComments)\n\tif err != nil {\n\t\t// Print out the bad code with line numbers.\n\t\t// This should never happen in practice, but it can while changing generated code,\n\t\t// so consider this a debugging aid.\n\t\tvar src bytes.Buffer\n\t\ts := bufio.NewScanner(bytes.NewReader(raw))\n\t\tfor line := 1; s.Scan(); line++ {\n\t\t\tfmt.Fprintf(&src, \"%5d\\t%s\\n\", line, s.Bytes())\n\t\t}\n\t\tg.Fail(\"bad Go source code was generated:\", err.Error(), \"\\n\"+src.String())\n\t}\n\tg.Reset()\n\terr = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(g, fset, ast)\n\tif err != nil {\n\t\tg.Fail(\"generated Go source code could not be reformatted:\", err.Error())\n\t}\n}", "func (gc Client) Generate() error {\n\t// helper package\n\tgh := goramlHelper{\n\t\tpackageName: \"goraml\",\n\t\tpackageDir: \"goraml\",\n\t}\n\tif err := gh.generate(gc.TargetDir); err != nil {\n\t\treturn err\n\t}\n\n\t// generate struct\n\tif err := generateAllStructs(gc.apiDef, gc.TargetDir, gc.PackageName); err != nil {\n\t\treturn err\n\t}\n\n\t// libraries\n\tif err := generateLibraries(gc.libraries, gc.TargetDir, gc.libsRootURLs); err != nil {\n\t\treturn err\n\t}\n\n\tif err := gc.generateHelperFile(gc.TargetDir); err != nil {\n\t\treturn err\n\t}\n\n\tif err := gc.generateSecurity(gc.TargetDir); err != nil {\n\t\treturn err\n\t}\n\n\tif err := gc.generateServices(gc.TargetDir); err != nil {\n\t\treturn err\n\t}\n\treturn gc.generateClientFile(gc.TargetDir)\n}", "func generate(c *cli.Context) error {\n\t// load variables from the config file\n\terr := action.Load(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// create the docs configuration\n\t//\n\t// https://pkg.go.dev/github.com/go-vela/cli/action/docs?tab=doc#Config\n\td := &docs.Config{\n\t\tAction: internal.ActionGenerate,\n\t\tMarkdown: c.Bool(\"markdown\"),\n\t\tMan: c.Bool(\"man\"),\n\t}\n\n\t// validate docs configuration\n\t//\n\t// https://pkg.go.dev/github.com/go-vela/cli/action/docs?tab=doc#Config.Validate\n\terr = d.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// execute the generate call for the docs configuration\n\t//\n\t// https://pkg.go.dev/github.com/go-vela/cli/action/docs?tab=doc#Config.Generate\n\treturn d.Generate(c.App)\n}", "func (g *GenData) GenFiles(fd *[]FileDefn) error {\n\tvar err error\n\tvar pathIn *util.Path\n\tvar work *util.WorkQueue\n\n\t// Setup the worker queue.\n\twork = util.NewWorkQueue(\n\t\tfunc(a interface{}, cmn interface{}) {\n\t\t\tvar data *TaskData\n\t\t\tvar ok bool\n\n\t\t\tdata, ok = a.(*TaskData)\n\t\t\tif ok {\n\t\t\t\tdata.genFile()\n\t\t\t} else {\n\t\t\t\tpanic(fmt.Sprintf(\"FATAL: Invalid TaskData Type of %T!\", a))\n\t\t\t}\n\t\t},\n\t\tnil,\n\t\t0)\n\n\t// Generate all the files for this phase.\n\tfor _, def := range *fd {\n\n\t\tif !sharedData.Quiet() {\n\t\t\tlog.Println(\"Setting up file:\", def.ModelName, \"generating:\", def.FileName, \"...\")\n\t\t}\n\n\t\t// Create the input model file path.\n\t\tif pathIn, err = g.CreateModelPath(def.ModelName); err != nil {\n\t\t\treturn fmt.Errorf(\"Error: %s: %s\\n\", pathIn.String(), err.Error())\n\t\t}\n\t\tif sharedData.Debug() {\n\t\t\tlog.Println(\"\\t\\tmodelPath=\", pathIn)\n\t\t}\n\n\t\t// Now setup to generate the file pushing the setup info\n\t\t// onto the work queue.\n\t\tif g.SetupFile != nil {\n\t\t\tg.SetupFile(g, def, work)\n\t\t} else {\n\t\t\tpanic(\"FATAL: Missing GenData::SetupFile!\\n\")\n\t\t}\n\t}\n\twork.CloseAndWaitForCompletion()\n\n\treturn err\n}", "func (d *Dir) Generate(cfg *Config) (Document, error) {\n\n\tif err := cfg.check(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"config is improperly formatted\")\n\t}\n\n\tff, err := d.Files(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfiles := Docs{}\n\tfor _, f := range ff {\n\t\tif d, err := f.Generate(cfg); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tfiles = append(files, d)\n\t\t}\n\t}\n\treturn files, nil\n}", "func Generate(meltAst comp.Module, ctx *comp.Context) (*token.FileSet, *ast.File, error) {\n\t// b()\n\tf := token.NewFileSet()\n\ta, err := GenerateModule(meltAst, ctx)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn f, a, nil\n}", "func GenORMSetup(db *gorm.DB) {\n\n\t// relative to the models package, swith to ../controlers package\n\tfilename := filepath.Join(OrmPkgGenPath, \"setup.go\")\n\n\t// we should use go generate\n\tlog.Println(\"generating orm setup file : \" + filename)\n\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\t// create the list of structs\n\tvar structs []models.Struct\n\tdb.Find(&structs)\n\n\tLISTOFSTRUCT := \"\\n\"\n\n\tdeleteCalls := \"\"\n\n\tfor idx, _struct := range structs {\n\t\tif idx != 0 {\n\t\t\tLISTOFSTRUCT += \",\\n\"\n\t\t}\n\t\tLISTOFSTRUCT += fmt.Sprintf(\"\\t\\t&%sDB{}\", _struct.Name)\n\n\t\tdeleteCalls += fmt.Sprintf(\"\\tdb.Delete(&%sDB{})\\n\", _struct.Name)\n\n\t\tfmt.Printf(\"\t\torm.LoadDB%s(%ss, db)\\n\", _struct.Name, _struct.Name)\n\t}\n\tres := strings.ReplaceAll(template, \"{{LISTOFSTRUCT}}\", LISTOFSTRUCT)\n\n\tres = strings.ReplaceAll(res, \"{{Deletes}}\", deleteCalls)\n\n\tfmt.Fprintf(f, \"%s\", res)\n\n\tdefer f.Close()\n}", "func GenerateMicroService(plugin *protogen.Plugin, file *protogen.File, svc *protogen.Service, opts *annotations.ServiceOptions) error {\n\tc := NewMicroService(plugin, file, svc, opts)\n\treturn c.render()\n}", "func genPackage(types map[string]pschema.ComplexTypeSpec, resourceTokens []string, includeObjectMetaType bool) (*pschema.Package, error) {\n\tif includeObjectMetaType {\n\t\ttypes[objectMetaToken] = pschema.ComplexTypeSpec{\n\t\t\tObjectTypeSpec: pschema.ObjectTypeSpec{\n\t\t\t\tType: \"object\",\n\t\t\t},\n\t\t}\n\t}\n\n\tresources := map[string]pschema.ResourceSpec{}\n\tfor _, baseRef := range resourceTokens {\n\t\tcomplexTypeSpec := types[baseRef]\n\t\tresources[baseRef] = pschema.ResourceSpec{\n\t\t\tObjectTypeSpec: complexTypeSpec.ObjectTypeSpec,\n\t\t\tInputProperties: complexTypeSpec.Properties,\n\t\t}\n\t}\n\n\tpkgSpec := pschema.PackageSpec{\n\t\tName: DefaultName,\n\t\tVersion: Version,\n\t\tTypes: types,\n\t\tResources: resources,\n\t}\n\n\tpkg, err := pschema.ImportSpec(pkgSpec, nil)\n\tif err != nil {\n\t\treturn &pschema.Package{}, errors.Wrapf(err, \"could not import spec\")\n\t}\n\n\tif includeObjectMetaType {\n\t\tdelete(types, objectMetaToken)\n\t}\n\n\treturn pkg, nil\n}", "func Generate(pkginfo *pkginfo.PkgInfo) {\n\tcmake := cmakefile.Open(pkginfo.Name)\n\tdefer cmake.Close()\n\tfor key, values := range pkginfo.Amalgamate {\n\t\tcmake.Amalgamate(key, values)\n\t}\n\tfor _, funcheck := range pkginfo.FunctionChecks {\n\t\tcmake.CheckFunctionExists(funcheck.Name, funcheck.Define)\n\t}\n\tfor _, symcheck := range pkginfo.SymbolChecks {\n\t\tcmake.CheckSymbolExists(symcheck.Name, symcheck.Header, symcheck.Define)\n\t}\n\tfor _, depname := range pkginfo.Dependencies {\n\t\thandler, ok := deps.All[depname]\n\t\tif !ok {\n\t\t\tlog.Fatalf(\"unknown dependency: %s\", depname)\n\t\t}\n\t\thandler(cmake)\n\t}\n\tcmake.FinalizeCompilerFlags()\n\tfor _, name := range sortedLibraryBuildInfo(pkginfo.Targets.Libraries) {\n\t\tbuildinfo := pkginfo.Targets.Libraries[name]\n\t\tcmake.AddLibrary(\n\t\t\tname, buildinfo.Compile, buildinfo.Link, buildinfo.Install,\n\t\t\tbuildinfo.Headers,\n\t\t)\n\t}\n\tfor _, name := range sortedBuildInfo(pkginfo.Targets.Executables) {\n\t\tbuildinfo := pkginfo.Targets.Executables[name]\n\t\tcmake.AddExecutable(\n\t\t\tname, buildinfo.Compile, buildinfo.Link, buildinfo.Install,\n\t\t)\n\t}\n\tfor _, name := range sortedScriptBuildInfo(pkginfo.Targets.Scripts) {\n\t\tbuildinfo := pkginfo.Targets.Scripts[name]\n\t\tcmake.AddScript(name, buildinfo.Install)\n\t}\n\tfor _, name := range sortedTestInfo(pkginfo.Tests) {\n\t\ttestinfo := pkginfo.Tests[name]\n\t\tcmake.AddTest(name, testinfo.Command)\n\t}\n}", "func main() {\n\tvar svcPath, svcImportPath string\n\tflag.StringVar(&svcPath, \"path\", \"service\",\n\t\t\"The `path` to generate service clients in to.\",\n\t)\n\tflag.StringVar(&svcImportPath, \"svc-import-path\",\n\t\tapi.SDKImportRoot+\"/service\",\n\t\t\"The Go `import path` to generate client to be under.\",\n\t)\n\tvar ignoreUnsupportedAPIs bool\n\tflag.BoolVar(&ignoreUnsupportedAPIs, \"ignore-unsupported-apis\",\n\t\ttrue,\n\t\t\"Ignores API models that use unsupported features\",\n\t)\n\n\tvar strictServiceId bool\n\tflag.BoolVar(&strictServiceId, \"use-service-id\", false, \"enforce strict usage of the serviceId from the model\")\n\n\tflag.Usage = usage\n\tflag.Parse()\n\n\tif len(os.Getenv(\"AWS_SDK_CODEGEN_DEBUG\")) != 0 {\n\t\tapi.LogDebug(os.Stdout)\n\t}\n\n\t// Make sure all paths are based on platform's pathing not Unix\n\tglobs := flag.Args()\n\tfor i, g := range globs {\n\t\tglobs[i] = filepath.FromSlash(g)\n\t}\n\tsvcPath = filepath.FromSlash(svcPath)\n\n\tmodelPaths, err := api.ExpandModelGlobPath(globs...)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"failed to glob file pattern\", err)\n\t\tos.Exit(1)\n\t}\n\tmodelPaths, _ = api.TrimModelServiceVersions(modelPaths)\n\n\tloader := api.Loader{\n\t\tBaseImport: svcImportPath,\n\t\tIgnoreUnsupportedAPIs: ignoreUnsupportedAPIs,\n\t\tStrictServiceId: strictServiceId,\n\t}\n\n\tapis, err := loader.Load(modelPaths)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"failed to load API models\", err)\n\t\tos.Exit(1)\n\t}\n\tif len(apis) == 0 {\n\t\tfmt.Fprintf(os.Stderr, \"expected to load models, but found none\")\n\t\tos.Exit(1)\n\t}\n\n\tif v := os.Getenv(\"SERVICES\"); len(v) != 0 {\n\t\tsvcs := strings.Split(v, \",\")\n\t\tfor pkgName, a := range apis {\n\t\t\tvar found bool\n\t\t\tfor _, include := range svcs {\n\t\t\t\tif a.PackageName() == include {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\tdelete(apis, pkgName)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar wg sync.WaitGroup\n\tservicePaths := map[string]struct{}{}\n\tfor _, a := range apis {\n\t\tif _, ok := excludeServices[a.PackageName()]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Create the output path for the model.\n\t\tpkgDir := filepath.Join(svcPath, a.PackageName())\n\t\tos.MkdirAll(filepath.Join(pkgDir, a.InterfacePackageName()), 0775)\n\n\t\tif _, ok := servicePaths[pkgDir]; ok {\n\t\t\tfmt.Fprintf(os.Stderr,\n\t\t\t\t\"attempted to generate a client into %s twice. Second model package, %v\\n\",\n\t\t\t\tpkgDir, a.PackageName())\n\t\t\tos.Exit(1)\n\t\t}\n\t\tservicePaths[pkgDir] = struct{}{}\n\n\t\tg := &generateInfo{\n\t\t\tAPI: a,\n\t\t\tPackageDir: pkgDir,\n\t\t}\n\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\twriteServiceFiles(g, pkgDir)\n\t\t}()\n\t}\n\n\twg.Wait()\n}", "func Generate(inst cue.InstanceOrValue, c *Config) (*ast.File, error) {\n\tall, err := schemas(c, inst)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttop, err := c.compose(inst, all)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ast.File{Decls: top.Elts}, nil\n}", "func Generate(packageName, srcDir string) error {\n\n\terrFmt := \"generate: %v\\n\"\n\n\tabsPath, err := filepath.Abs(srcDir)\n\tif err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\n\tfs := vfs.New()\n\n\terr = buildTree(absPath, fs.Children)\n\tif err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\n\terr = os.MkdirAll(packageName, os.FileMode(0755))\n\tif err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\n\tspec := vfsSpec{packageName, absPath, fs}\n\n\terr = writeFile(prodTmplStr, \"\", &spec)\n\tif err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\n\terr = writeFile(devTmplStr, \"dev\", &spec)\n\tif err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\n\treturn nil\n\n}", "func (meta *BundleMetaData) GenerateMetadata() error {\n\t// Create output directory\n\tif err := os.MkdirAll(meta.BundleDir, projutil.DirMode); err != nil {\n\t\treturn err\n\t}\n\n\t// Create annotation values for both bundle.Dockerfile and annotations.yaml, which should\n\t// hold the same set of values always.\n\tvalues := annotationsValues{\n\t\tBundleDir: meta.BundleDir,\n\t\tPackageName: meta.PackageName,\n\t\tChannels: meta.Channels,\n\t\tDefaultChannel: meta.DefaultChannel,\n\t\tIsScorecardConfigPresent: meta.IsScoreConfigPresent,\n\t}\n\n\tfor k, v := range meta.OtherLabels {\n\t\tvalues.OtherLabels = append(values.OtherLabels, fmt.Sprintf(\"%s=%s\", k, v))\n\t}\n\tsort.Strings(values.OtherLabels)\n\n\t// Write each file\n\tmetadataDir := filepath.Join(meta.BundleDir, defaultMetadataDir)\n\tif err := os.MkdirAll(metadataDir, projutil.DirMode); err != nil {\n\t\treturn err\n\t}\n\n\tdockerfilePath := defaultBundleDockerfilePath\n\t// If migrating from packagemanifests to bundle, bundle.Dockerfile is present\n\t// inside bundleDir, else it's in the project directory. Hence, dockerfile\n\t// should have the path specified with respect to output directory of resulting bundles.\n\t// Remove this, when pkgman-to-bundle migrate command is removed.\n\tif len(meta.PkgmanifestPath) != 0 {\n\t\tdockerfilePath = filepath.Join(filepath.Dir(meta.BundleDir), \"bundle.Dockerfile\")\n\t\tvalues.BundleDir = filepath.Base(meta.BundleDir)\n\t}\n\n\ttemplateMap := map[string]*template.Template{\n\t\tdockerfilePath: dockerfileTemplate,\n\t\tfilepath.Join(metadataDir, \"annotations.yaml\"): annotationsTemplate,\n\t}\n\n\tfor path, tmpl := range templateMap {\n\t\tlog.Info(fmt.Sprintf(\"Creating %s\", path))\n\t\tf, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif err := f.Close(); err != nil {\n\t\t\t\tlog.Error(err)\n\t\t\t}\n\t\t}()\n\t\tif err = tmpl.Execute(f, values); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tlog.Infof(\"Bundle metadata generated successfully\")\n\treturn nil\n}", "func (g *CodeGenerator) Generate() error {\n\tif len(g.opts.FilePath) == 0 {\n\t\treturn errors.New(\"invalid file path\")\n\t}\n\n\tif len(g.opts.PackageName) == 0 {\n\t\treturn errors.New(\"invalid package name\")\n\t}\n\n\t// generate package\n\tg.P(\"package \", g.opts.PackageName)\n\tg.P()\n\n\t// generate import path\n\tg.P(\"import (\")\n\tfor _, path := range g.opts.ImportPath {\n\t\tg.P(\"\\t\\\"\", path, \"\\\"\")\n\t}\n\tg.P(\")\")\n\tg.P()\n\n\t// generate variables\n\tfor _, v := range g.opts.Variables {\n\t\tvariableLine := fmt.Sprintf(\"var\\t%-15s\\t%-15s\\t//%-15s\", v.name, v.tp, v.comment)\n\t\tg.P(variableLine)\n\t\tg.P()\n\t}\n\n\t// generate structs\n\tfor _, s := range g.opts.Structs {\n\t\t// struct comment\n\t\tif len(s.comment) > 0 {\n\t\t\tg.P(\"// \", s.comment)\n\t\t}\n\n\t\t// struct begin\n\t\tg.P(\"type \", s.name, \" struct {\")\n\n\t\t// struct fields\n\t\tfieldLines := make([]string, s.fieldRaw.Size())\n\t\tit := s.fieldRaw.Iterator()\n\t\tfor it.Next() {\n\t\t\tfieldRaw := it.Value().(*ExcelFieldRaw)\n\n\t\t\t// don't need import\n\t\t\tif !fieldRaw.imp {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfieldLine := fmt.Sprintf(\"\\t%-15s\\t%-20s\\t%-20s\\t//%-10s\", it.Key(), fieldRaw.tp, fieldRaw.tag, fieldRaw.desc)\n\t\t\tfieldLines[fieldRaw.idx] = fieldLine\n\t\t}\n\n\t\t// print struct field in sort\n\t\tfor _, v := range fieldLines {\n\t\t\tif len(v) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tg.P(v)\n\t\t}\n\n\t\t// struct end\n\t\tg.P(\"}\")\n\t\tg.P()\n\t}\n\n\t// generate functions\n\tfor _, f := range g.opts.Functions {\n\t\t// function comment\n\t\tif len(f.comment) > 0 {\n\t\t\tg.P(\"// \", f.comment)\n\t\t}\n\n\t\t// function receiver\n\t\tvar receiver string\n\t\tif len(f.receiver) > 0 {\n\t\t\treceiver = fmt.Sprintf(\"(e *%s)\", f.receiver)\n\t\t}\n\n\t\t// function parameters\n\t\tparameters := strings.Join(f.parameters, \", \")\n\n\t\t// function begin\n\t\tg.P(\"func \", receiver, \" \", f.name, \"(\", parameters, \") \", f.retType, \" {\")\n\n\t\t// function body\n\t\tg.P(\"\\t\", f.body)\n\n\t\t// function end\n\t\tg.P(\"}\")\n\t\tg.P()\n\t}\n\n\treturn ioutil.WriteFile(g.opts.FilePath, g.buf.Bytes(), 0666)\n}", "func GenerateSubCommands() []*cobra.Command {\n\n\tvar generateService = &cobra.Command{\n\t\tUse: \"project\",\n\t\tRunE: actionGenerateProject,\n\t}\n\treturn []*cobra.Command{generateService}\n}", "func main() {\n\tvar err error\n\tvar buffer bytes.Buffer\n\n\t// Generate the User struct\n\tuserStruct, userImport, err := Generate(User{})\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\t// Generate the UserStatus struct\n\tuserStatus, statusImport, err := Generate(UserStatus{})\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\t// Write the package declaration\n\tbuffer.Write([]byte(\"package model\\n\"))\n\n\t// Write the imports\n\tbuffer.Write([]byte(\"import (\\n\"))\n\tfor _, i := range userImport {\n\t\tbuffer.Write([]byte(fmt.Sprintf(`\"%s\"`, i) + \"\\n\"))\n\t}\n\tfor _, i := range statusImport {\n\t\tbuffer.Write([]byte(fmt.Sprintf(`\"%s\"`, i) + \"\\n\"))\n\t}\n\tbuffer.Write([]byte(\")\\n\"))\n\n\t// Wrote the structs\n\tbuffer.Write(userStruct)\n\tbuffer.Write([]byte(\"\\n\\n\"))\n\tbuffer.Write(userStatus)\n\tbuffer.Write([]byte(\"\\n\\n\"))\n\n\t// Format the buffer using go fmt\n\tout, err := format.Source(buffer.Bytes())\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\t// Write the file\n\terr = ioutil.WriteFile(\"model.go\", out, 0644)\n\tif err != nil {\n\t\tlog.Println(\"File save error\")\n\t\treturn\n\t}\n}", "func Generate(g *grammar.Grammar, w Writer, opts Options) error {\n\tlang, ok := languages[g.TargetLang]\n\tif !ok {\n\t\treturn fmt.Errorf(\"unsupported language: %s\", g.TargetLang)\n\t}\n\n\ttemplates := lang.templates(g)\n\tfor _, f := range templates {\n\t\ttmpl := template.New(\"main\").Funcs(funcMap).Funcs(extraFuncs(f.name, g))\n\n\t\t// Load shared templates.\n\t\tvar err error\n\t\tif !opts.NoBuiltins {\n\t\t\ttmpl, err = tmpl.Parse(lang.SharedDefs)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error in built-in shared_defs: %v\", err)\n\t\t\t}\n\t\t}\n\t\ttmpl, err = loadOverlay(g.TargetLang+\"_shared\", tmpl, opts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Load templates for the current file.\n\t\tif !opts.NoBuiltins {\n\t\t\ttmpl, err = tmpl.Parse(f.template)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error in built-in %v: %v\", f.name, err)\n\t\t\t}\n\t\t}\n\t\ttmpl, err = loadOverlay(g.TargetLang+\"_\"+f.name, tmpl, opts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// TODO come up with a way to parse this once\n\t\t_, err = tmpl.Parse(g.CustomTemplates)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error in inline template: %v\", err)\n\t\t}\n\n\t\tvar buf strings.Builder\n\t\terr = tmpl.Execute(&buf, g)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error generating %v: %w\", f.name, err)\n\t\t}\n\t\toutName := g.Options.FilenamePrefix + f.name\n\t\tsrc := Format(outName, ExtractImports(buf.String()), opts.Compat)\n\t\tif err := w.Write(outName, src); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Generate(opts GenerateOptions, queryFiles []codegen.QueryFile) error {\n\tpkgName := opts.GoPkg\n\tif pkgName == \"\" {\n\t\tpkgName = filepath.Base(opts.OutputDir)\n\t}\n\tcaser := casing.NewCaser()\n\tcaser.AddAcronyms(opts.Acronyms)\n\ttemplater := NewTemplater(TemplaterOpts{\n\t\tCaser: caser,\n\t\tResolver: NewTypeResolver(caser, opts.TypeOverrides),\n\t\tPkg: pkgName,\n\t})\n\ttemplatedFiles, err := templater.TemplateAll(queryFiles)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"template all: %w\", err)\n\t}\n\n\t// Order for reproducible results.\n\tsort.Slice(templatedFiles, func(i, j int) bool {\n\t\treturn templatedFiles[i].SourcePath < templatedFiles[j].SourcePath\n\t})\n\n\t// Link each child to the package. Necessary so the leader can define all\n\t// Querier methods.\n\tpkg := TemplatedPackage{Files: templatedFiles}\n\tfor i := range templatedFiles {\n\t\ttemplatedFiles[i].Pkg = pkg\n\t}\n\n\ttmpl, err := parseQueryTemplate()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parse generated Go code template: %w\", err)\n\t}\n\temitter := NewEmitter(opts.OutputDir, tmpl)\n\tif err := emitter.EmitAllQueryFiles(templatedFiles); err != nil {\n\t\treturn fmt.Errorf(\"emit generated Go code: %w\", err)\n\t}\n\treturn nil\n}", "func (g *TmplGen) GenerateAllFiles() {\n\t// Initialize the plugins\n\tfor _, p := range plugins {\n\t\tp.Init(&g.Generator)\n\t}\n\t// Generate the output. The generator runs for every file, even the files\n\t// that we don't generate output for, so that we can collate the full list\n\t// of exported symbols to support public imports.\n\tgenFileMap := make(map[*FileDescriptor]bool, len(g.genFiles))\n\tfor _, file := range g.genFiles {\n\t\tgenFileMap[file] = true\n\t}\n\tfor _, file := range g.allFiles {\n\t\tg.Reset()\n\t\tg.annotations = nil\n\t\tg.writeOutput = genFileMap[file]\n\t\tg.generate(file)\n\t\tif !g.writeOutput {\n\t\t\tcontinue\n\t\t}\n\t\tfname := file.goPFileName(g.pathType, g.PName)\n\t\tlog.Println(fname)\n\t\tg.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{\n\t\t\tName: proto.String(fname),\n\t\t\tContent: proto.String(g.String()),\n\t\t})\n\t\tif g.annotateCode {\n\t\t\t// Store the generated code annotations in text, as the protoc plugin protocol requires that\n\t\t\t// strings contain valid UTF-8.\n\t\t\tg.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{\n\t\t\t\tName: proto.String(file.goFileName(g.pathType) + \".meta\"),\n\t\t\t\tContent: proto.String(proto.CompactTextString(&descriptor.GeneratedCodeInfo{Annotation: g.annotations})),\n\t\t\t})\n\t\t}\n\t}\n}", "func (plugs Plugins) Generate(ctx context.Context, args []string) error {\n\topts := struct {\n\t\thelp bool\n\t}{}\n\n\tflags := flag.NewFlagSet(\"bluffalo generate\", flag.ContinueOnError)\n\tflags.BoolVar(&opts.help, \"h\", false, \"print this help\")\n\n\tif err := flags.Parse(args); err != nil {\n\t\treturn err\n\t}\n\n\targs = flags.Args()\n\tif opts.help || len(args) == 0 {\n\t\tsort.Slice(plugs, func(i, j int) bool {\n\t\t\treturn plugs[i].Name() < plugs[j].Name()\n\t\t})\n\n\t\tstderr := cmdx.Stderr(ctx)\n\t\tfor _, p := range plugs {\n\t\t\tif _, ok := p.(Generator); ok {\n\t\t\t\tfmt.Fprintf(stderr, \"%s %s - [%s]\\n\", flags.Name(), p.Name(), p)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\targ := args[0]\n\tif len(args) > 0 {\n\t\targs = args[1:]\n\t}\n\n\tfor _, p := range plugs {\n\t\tf, ok := p.(Generator)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif p.Name() != arg {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn f.Generate(ctx, args)\n\t}\n\treturn fmt.Errorf(\"unknown generator %s\", arg)\n}", "func (d *docGenerator) generateDocs(api API) error {\n\tdir := api.Configuration().DocsDirectory\n\tif !strings.HasSuffix(dir, \"/\") {\n\t\tdir = dir + \"/\"\n\t}\n\n\tif err := d.mkdir(dir, os.FileMode(0777)); err != nil {\n\t\tapi.Configuration().Logger.Println(err)\n\t\treturn err\n\t}\n\n\thandlers := api.ResourceHandlers()\n\tdocs := map[string][]handlerDoc{}\n\tversions := versions(handlers)\n\n\tfor _, version := range versions {\n\t\tversionDocs := make([]handlerDoc, 0, len(handlers))\n\t\tfor _, handler := range handlers {\n\t\t\tdoc, err := d.generateHandlerDoc(handler, version, dir)\n\t\t\tif err != nil {\n\t\t\t\tapi.Configuration().Logger.Println(err)\n\t\t\t\treturn err\n\t\t\t} else if doc != nil {\n\t\t\t\tversionDocs = append(versionDocs, doc)\n\t\t\t}\n\t\t}\n\n\t\tdocs[version] = versionDocs\n\t}\n\n\tif err := d.generateIndexDocs(docs, versions, dir); err != nil {\n\t\tapi.Configuration().Logger.Println(err)\n\t\treturn err\n\t}\n\n\tapi.Configuration().Debugf(\"Documentation generated in %s\", dir)\n\treturn nil\n}", "func Generate(file File) ([]byte, error) {\n\tcode := jen.NewFilePathName(file.Package.Path, file.Package.Name)\n\n\tcode.HeaderComment(\"//go:build !ignore_autogenerated\\n// +build !ignore_autogenerated\\n\")\n\n\tif file.HeaderText != \"\" {\n\t\tcode.HeaderComment(file.HeaderText)\n\t}\n\n\tcode.HeaderComment(\"Code generated by mga tool. DO NOT EDIT.\")\n\n\tcode.ImportName(\"github.com/go-kit/kit/endpoint\", \"endpoint\")\n\tcode.ImportAlias(\"github.com/sagikazarmark/kitx/endpoint\", \"kitxendpoint\")\n\n\tcode.Comment(\"endpointError identifies an error that should be returned as an endpoint error.\")\n\tcode.Type().Id(\"endpointError\").Interface(\n\t\tjen.Id(\"EndpointError\").Params().Bool(),\n\t)\n\n\tcode.Comment(\"serviceError identifies an error that should be returned as a service error.\")\n\tcode.Type().Id(\"serviceError\").Interface(\n\t\tjen.Id(\"ServiceError\").Params().Bool(),\n\t)\n\n\tfor _, set := range file.EndpointSets {\n\t\tgenerateEndpointSet(code, set)\n\t}\n\n\tvar buf bytes.Buffer\n\n\terr := code.Render(&buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn format.Source(buf.Bytes())\n}", "func generate(proto string, localArgs []string) error {\n\targs := []string{\n\t\t\"--proto_path=.\",\n\t\t\"--proto_path=\" + filepath.Join(base.KratosMod(), \"api\"),\n\t\t\"--proto_path=\" + filepath.Join(base.KratosMod(), \"third_party\"),\n\t\t\"--proto_path=\" + filepath.Join(os.Getenv(\"GOPATH\"), \"src\"),\n\t\t\"--go_out=paths=source_relative:.\",\n\t\t\"--go-grpc_out=paths=source_relative:.\",\n\t\t\"--go-http_out=paths=source_relative:.\",\n\t\t\"--go-errors_out=paths=source_relative:.\",\n\t}\n\t// ts umi为可选项 只在安装 protoc-gen-ts-umi情况下生成\n\tfmt.Println(localArgs)\n\tfor _, v := range localArgs[1:] {\n\t\tif v == \"vendor\" {\n\t\t\targs = append(args, \"--proto_path=./vendor\")\n\t\t} else {\n\t\t\tif err := look(fmt.Sprintf(\"protoc-gen-%s\", v)); err == nil {\n\t\t\t\targs = append(args, fmt.Sprintf(\"--%s_out=paths=source_relative:.\", v))\n\t\t\t} else {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t}\n\t}\n\targs = append(args, proto)\n\tfd := exec.Command(\"protoc\", args...)\n\tfd.Stdout = os.Stdout\n\tfd.Stderr = os.Stderr\n\t//fd.Dir = path\n\tif err := fd.Run(); err != nil {\n\t\tfmt.Printf(\"comand: protoc %s \\n\", strings.Join(args, \" \"))\n\t\treturn err\n\t}\n\tfmt.Printf(\"proto: %s\\n\", proto)\n\tfmt.Printf(\"comand: protoc %s \\n\", strings.Join(args, \" \"))\n\treturn nil\n}", "func main() {\n\tflag.Parse()\n\tconfig := createConfig()\n\twebServices := rest.AggregatedAPIs()\n\tswagger, err := builder.BuildOpenAPISpec(webServices, config)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\tjsonBytes, err := json.MarshalIndent(swagger, \"\", \" \")\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\tif err := ioutil.WriteFile(*outputFile, jsonBytes, 0644); err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n}", "func generateMan(info os.FileInfo, name string) {\n\tcontents, err := ioutil.ReadFile(info.Name())\n\tif err != nil {\n\t\tfmt.Printf(\"Could not read file: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tout := md2man.Render(contents)\n\tif len(out) == 0 {\n\t\tfmt.Println(\"Failed to render\")\n\t\tos.Exit(1)\n\t}\n\tcomplete := filepath.Join(m1Dir, name)\n\tif err := ioutil.WriteFile(complete, out, info.Mode()); err != nil {\n\t\tfmt.Printf(\"Could not write file: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// Check duplicates (e.g. lu and list-updates)\n\tname = duplicateName(name)\n\tif name != \"\" {\n\t\tcomplete = filepath.Join(m1Dir, name)\n\t\tif err := ioutil.WriteFile(complete, out, info.Mode()); err != nil {\n\t\t\tfmt.Printf(\"Could not write file: %v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func Generate() {\n\treader := strings.NewReader(API)\n\tvar conf = config.Source(reader)\n\tyml, err := config.NewYAML(conf)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(yml.Name())\n}", "func (self *GoCodeGenerator) Generate(in io.Reader, out io.Writer) error {\n\tfuncMap := template.FuncMap{\n\t\t\"title\": strings.Title,\n\t\t\"fieldType\": self.fieldType,\n\t\t\"val\": self.val,\n\t}\n\tbuff, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\tt := template.Must(template.New(\"gen\").Funcs(funcMap).Parse(string(buff)))\n\treturn t.Execute(out, struct {\n\t\tAll []*objectRef\n\t}{\n\t\tAll: self.all,\n\t})\n}", "func (p *servicePlugin) Generate(file *generator.FileDescriptor) {\n\tif !p.getGenericServicesOptions(file) {\n\t\treturn\n\t}\n\tfor _, svc := range file.Service {\n\t\tp.genServiceInterface(file, svc)\n\t\tp.genServiceServer(file, svc)\n\t\tp.genServiceClient(file, svc)\n\t}\n}", "func GenerateCustomBuilders(opts Opts) error {\n\tconf := loader.Config{}\n\tif opts.IsTestFile {\n\t\tconf.ImportWithTests(opts.PkgPath)\n\t} else {\n\t\tconf.Import(opts.PkgPath)\n\t}\n\tprg, err := conf.Load()\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tvar tables types.Object\n\tvar tablesPkg *types.Package\n\n\tpkg := prg.Package(opts.PkgPath)\n\tif opts.IsTestFile {\n\t\ttestPkg := prg.Package(opts.PkgPath + \"_test\")\n\t\ttables, tablesPkg = findTablesDef(opts.TablesStructName, testPkg, pkg)\n\t} else {\n\t\ttables, tablesPkg = findTablesDef(opts.TablesStructName, pkg)\n\t}\n\n\tif tables == nil {\n\t\treturn fmt.Errorf(\"Table definition struct '%s' not found\", opts.TablesStructName)\n\t}\n\n\ttablesT, ok := tables.Type().Underlying().(*types.Struct)\n\tif !ok {\n\t\treturn errors.Wrapf(err, \"%s is not struct\", opts.TablesStructName)\n\t}\n\n\thelpers := make([]*helper, 0, tablesT.NumFields())\n\n\tfor i := 0; i < tablesT.NumFields(); i++ {\n\t\tfld := tablesT.Field(i)\n\n\t\ttableName := fld.Name()\n\n\t\tvar fldT *types.Struct\n\t\tfldVar, ok := fld.Type().(*types.Named)\n\t\tif ok {\n\t\t\tfldT, ok = fldVar.Underlying().(*types.Struct)\n\t\t}\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"%s contains non struct field %s\",\n\t\t\t\topts.TablesStructName,\n\t\t\t\ttableName,\n\t\t\t)\n\t\t}\n\n\t\tmodelPkgName := \"\"\n\t\tmodelPkg := fldVar.Obj().Pkg()\n\t\tif modelPkg.Name() != tablesPkg.Name() {\n\t\t\tmodelPkgName = modelPkg.Name()\n\t\t}\n\n\t\ttableTag, err := parseTableTag(getTag(tablesT.Tag(i), \"goq\"))\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to parse tag of Tables.%s\", tableName)\n\t\t}\n\n\t\thelperName := tableTag.HelperName\n\t\tif helperName == \"\" {\n\t\t\thelperName = util.ColToFld(tableName)\n\t\t}\n\n\t\tmodelName := fldVar.Obj().Name()\n\t\tfields, err := listColumnFields(modelName, fldT)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thelpers = append(helpers, &helper{\n\t\t\tName: helperName,\n\t\t\tTableName: tableName,\n\t\t\tModelPkgName: modelPkgName,\n\t\t\tModelName: modelName,\n\t\t\tFields: fields,\n\t\t})\n\n\t}\n\n\tsrc, err := execTemplate(tablesPkg.Name(), helpers, nil)\n\tif src != nil {\n\t\tfile, err := createOutFile(opts.OutFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tfile.Write(src)\n\t}\n\n\treturn err\n}", "func (g *Generator) GenerateServices() error {\n\tif g.ServiceGen == nil || len(g.depfile.ProtoFile.Services) == 0 {\n\t\treturn nil\n\t}\n\n\tfor _, svc := range g.depfile.ProtoFile.CollectServices() {\n\t\terr := g.ServiceGen.GenerateService(g, svc.(*fproto.ServiceElement))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Generate(conf config.Config, tableName string) (err error) {\n\n\terr = yaml.ReadTables(conf)\n\tif util.ErrorCheck(err) {\n\t\treturn fmt.Errorf(\"Generate failed. Unable to read YAML Tables\")\n\t}\n\n\t// Filter by tableName in the YAML Schema\n\tif tableName != \"*\" {\n\t\ttgtTbl := []table.Table{}\n\n\t\tfor _, tbl := range yaml.Schema {\n\t\t\tif tbl.Name == tableName {\n\t\t\t\ttgtTbl = append(tgtTbl, tbl)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// Reduce the YAML schema to the single target table\n\t\tyaml.Schema = tgtTbl\n\t}\n\n\tif len(yaml.Schema) == 0 {\n\t\treturn fmt.Errorf(\"Generate: YAML Table not found: %s\", tableName)\n\t}\n\n\treturn writeTables(conf, yaml.Schema)\n}", "func NewGenerateCommand() *cobra.Command {\n\tconst StdIn = \"-\"\n\n\tvar command = &cobra.Command{\n\t\tUse: \"generate --path=<path> --include-paths=<additional path>:<additional path>\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tvar manifests []unstructured.Unstructured\n\t\t\tvar err error\n\t\t\tvar errs []error\n\n\t\t\tconf := getConfig(cmd)\n\n\t\t\tif conf.path == StdIn {\n\t\t\t\tmanifests, err = readManifestData(cmd.InOrStdin())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfiles, err := listYamlFiles(conf.path)\n\t\t\t\tif len(files) < 1 {\n\t\t\t\t\treturn fmt.Errorf(\"no YAML files were found in %s\", conf.path)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tmanifests, errs = readFilesAsManifests(files)\n\t\t\t\tif len(errs) != 0 {\n\t\t\t\t\t// TODO: handle multiple errors nicely\n\t\t\t\t\treturn fmt.Errorf(\"could not read YAML files: %s\", errs)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(conf.includePaths) > 0 {\n\t\t\t\tvar addManifests []unstructured.Unstructured\n\n\t\t\t\tfor _, path := range conf.includePaths {\n\t\t\t\t\tfiles, err := listYamlFiles(path)\n\t\t\t\t\tif len(files) < 1 {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\taddManifests, errs = readFilesAsManifests(files)\n\t\t\t\t\tif len(errs) != 0 {\n\t\t\t\t\t\treturn fmt.Errorf(\"could not read YAML files: %s\", errs)\n\t\t\t\t\t}\n\t\t\t\t\tmanifests = append(manifests, addManifests...)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, manifest := range manifests {\n\n\t\t\t\tif len(manifest.Object) == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\toutput, err := yaml.Marshal(manifest.Object)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Errorf(\"could not export %s into YAML: %s\", err)\n\t\t\t\t}\n\n\t\t\t\tfmt.Fprintf(cmd.OutOrStdout(), \"%s---\\n\", string(output))\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn command\n}", "func GenerateSubCommands() []*cobra.Command {\n\n\tvar generaterule = &cobra.Command{\n\t\tUse: \"filestore-rules\",\n\t\tRunE: actionGenerateFilestoreRule,\n\t}\n\n\tvar generateconfig = &cobra.Command{\n\t\tUse: \"filestore-config\",\n\t\tRunE: actionGenerateFilestoreConfig,\n\t}\n\n\treturn []*cobra.Command{generaterule, generateconfig}\n}", "func (b *Bundler) Generate(p *ir.PatientInfo) (*r4pb.Bundle, error) {\n\tif p == nil {\n\t\treturn nil, errors.New(\"cannot generate resources from nil PatientInfo\")\n\t}\n\treturn b.createBundle(p), nil\n}", "func GeneratePlantUMLFiles(master *assembly.MasterTypeCollection, outputFolder string, verbose bool) {\r\n\tif verbose {\r\n\t\tfmt.Println(\"------------------------------------------------------------------------------------------------------------------------------------\")\r\n\t\tfmt.Println(\"------------------------------------------------------------------------------------------------------------------------------------\")\r\n\t}\r\n\r\n\tif verbose {\r\n\t\tfor _, k := range master.GetDataTypeKeys() {\r\n\t\t\tv, _ := master.GetDataType(k)\r\n\t\t\tfmt.Printf(\"%s\\n\", *v)\r\n\t\t}\r\n\r\n\t\tfor _, k := range master.GetScopeKeys() {\r\n\t\t\tv, _ := master.GetScope(k)\r\n\t\t\tfmt.Printf(\"%s\\n\", v)\r\n\t\t}\r\n\t}\r\n\r\n\tscopeUMLBuilderMap := make(map[string]*strings.Builder)\r\n\tscopeNotesBuilderMap := make(map[string]*strings.Builder)\r\n\r\n\t//\r\n\t// generate the scope classes\r\n\t//\r\n\tfor _, scopeName := range master.GetScopeKeys() {\r\n\t\tscope, _ := master.GetScope(scopeName)\r\n\r\n\t\tumlSb := &strings.Builder{}\r\n\t\tscopeUMLBuilderMap[scopeName] = umlSb\r\n\t\tnotesSb := &strings.Builder{}\r\n\t\tscopeNotesBuilderMap[scopeName] = notesSb\r\n\r\n\t\tumlSb.WriteString(\"@startuml\\n\")\r\n\t\tumlSb.WriteString(\"skinparam classAttributeIconSize 0\\n\")\r\n\r\n\t\tumlSb.WriteString(fmt.Sprintf(\"class %s {\\n\", scope.Name))\r\n\r\n\t\tfor _, scopeMethod := range scope.Methods {\r\n\t\t\twriteMethodToStringBuilder(umlSb, scopeMethod, scopeName, \"static\")\r\n\t\t}\r\n\r\n\t\tumlSb.WriteString(\"}\\n\")\r\n\t}\r\n\r\n\t//\r\n\t// generate the data types for each scope\r\n\t//\r\n\r\n\tfor _, k := range master.GetDataTypeKeys() {\r\n\t\tv, _ := master.GetDataType(k)\r\n\r\n\t\tswitch vActual := (*v).(type) {\r\n\t\tcase *types.InterfaceDescriptor:\r\n\t\t\tscopeName := vActual.Package\r\n\t\t\tumlSb, existing := scopeUMLBuilderMap[scopeName]\r\n\t\t\tif !existing {\r\n\t\t\t\tfmt.Printf(\"Skipping UML generation for interface, no scope tracked for '%s\\n\", vActual.GetCannonicalName())\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\r\n\t\t\tumlSb.WriteString(fmt.Sprintf(\"interface \\\"%s\\\" {\\n\", vActual.Name))\r\n\t\t\tfor _, method := range vActual.Methods {\r\n\t\t\t\twriteMethodToStringBuilder(umlSb, method, scopeName, \"abstract\")\r\n\t\t\t}\r\n\r\n\t\t\tumlSb.WriteString(\"}\\n\")\r\n\r\n\t\t\tfor _, promoted := range vActual.PromotedTypes {\r\n\t\t\t\tpromotedName := (*promoted).GetCannonicalName()\r\n\r\n\t\t\t\tif strings.HasPrefix(promotedName, scopeName) {\r\n\t\t\t\t\tpromotedName = (*promoted).GetSimpleName()\r\n\t\t\t\t}\r\n\r\n\t\t\t\tumlSb.WriteString(fmt.Sprintf(\"\\\"%s\\\" <|-- %s\\n\", promotedName, vActual.Name))\r\n\t\t\t}\r\n\t\tcase *types.StructDescriptor:\r\n\t\t\tscopeName := vActual.Package\r\n\r\n\t\t\tif vActual.IsBuiltin() {\r\n\t\t\t\tif verbose {\r\n\t\t\t\t\tfmt.Printf(\"Skipping UML generation for builtin type '%s'\\n\", vActual.Name)\r\n\t\t\t\t}\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\r\n\t\t\tumlSb, existing := scopeUMLBuilderMap[scopeName]\r\n\t\t\tif !existing {\r\n\t\t\t\tif verbose {\r\n\t\t\t\t\tfmt.Printf(\"Skipping UML generation for struct, no scope tracked for '%s'\\n\", vActual.GetCannonicalName())\r\n\t\t\t\t}\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\r\n\t\t\tumlSb.WriteString(fmt.Sprintf(\"class \\\"%s\\\" {\\n\", vActual.Name))\r\n\r\n\t\t\tfor _, attribute := range vActual.Attributes {\r\n\t\t\t\twriteAttributeToStringBuilder(umlSb, attribute, scopeName)\r\n\t\t\t}\r\n\r\n\t\t\tfor _, method := range vActual.Methods {\r\n\t\t\t\twriteMethodToStringBuilder(umlSb, method, scopeName, \"\")\r\n\t\t\t}\r\n\r\n\t\t\tumlSb.WriteString(\"}\\n\")\r\n\t\t\tfor _, promoted := range vActual.PromotedTypes {\r\n\t\t\t\tpromotedName := (*promoted).GetCannonicalName()\r\n\r\n\t\t\t\tif _, _, isLocal := types.IsNameLocalToScope(promotedName, scopeName); isLocal {\r\n\t\t\t\t\tpromotedName = (*promoted).GetSimpleName()\r\n\t\t\t\t}\r\n\r\n\t\t\t\tumlSb.WriteString(fmt.Sprintf(\"\\\"%s\\\" <|-- %s\\n\", promotedName, vActual.Name))\r\n\t\t\t}\r\n\r\n\t\t\tfor _, attribute := range vActual.Attributes {\r\n\t\t\t\tattributeTypeName := attribute.CannonicalTypeName\r\n\r\n\t\t\t\tif resolvedName, extractedPrefix, isLocal := types.IsNameLocalToScope(attributeTypeName, scopeName); isLocal {\r\n\t\t\t\t\tattributeTypeName = resolvedName\r\n\t\t\t\t\tif extractedPrefix == types.ArrayDescriptorMarker {\r\n\t\t\t\t\t\tumlSb.WriteString(fmt.Sprintf(\"\\\"%s\\\" --* %s\\n\", attributeTypeName, vActual.Name))\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tumlSb.WriteString(fmt.Sprintf(\"\\\"%s\\\" -- %s\\n\", attributeTypeName, vActual.Name))\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\tcase *types.PointerDescriptor:\r\n\t\t\tif verbose {\r\n\t\t\t\tfmt.Printf(\"Skipping UML generation for '%s'\\n\", vActual.GetCannonicalName())\r\n\t\t\t}\r\n\t\tcase *types.ArrayDescriptor:\r\n\t\t\tif verbose {\r\n\t\t\t\tfmt.Printf(\"Skipping UML generation for '%s'\\n\", vActual.GetCannonicalName())\r\n\t\t\t}\r\n\t\tcase *types.MapDescriptor:\r\n\t\t\tif verbose {\r\n\t\t\t\tfmt.Printf(\"Skipping UML generation for '%s'\\n\", vActual.GetCannonicalName())\r\n\t\t\t}\r\n\t\tcase *types.ChannelDescriptor:\r\n\t\t\tif verbose {\r\n\t\t\t\tfmt.Printf(\"Skipping UML generation for '%s'\\n\", vActual.GetCannonicalName())\r\n\t\t\t}\r\n\t\tcase *types.FunctionDescriptor:\r\n\t\t\tif verbose {\r\n\t\t\t\tfmt.Printf(\"Skipping UML generation for '%s'\\n\", vActual.GetCannonicalName())\r\n\t\t\t}\r\n\t\tcase *types.EllipsisDescriptor:\r\n\t\t\tif verbose {\r\n\t\t\t\tfmt.Printf(\"Skipping UML generation for '%s'\\n\", vActual.GetCannonicalName())\r\n\t\t\t}\r\n\t\tcase *types.AliasedTypeDescriptor:\r\n\t\t\tscopeName := vActual.Package\r\n\t\t\tnotesSb, existing := scopeNotesBuilderMap[scopeName]\r\n\t\t\tif !existing {\r\n\t\t\t\tif verbose {\r\n\t\t\t\t\tfmt.Printf(\"Skipping UML generation for alias, no scope tracked for '%s'\\n\", vActual.GetCannonicalName())\r\n\t\t\t\t}\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\r\n\t\t\tnotesSb.WriteString(vActual.String())\r\n\t\t\tnotesSb.WriteString(\"\\n\")\r\n\r\n\t\tdefault:\r\n\t\t\tif verbose {\r\n\t\t\t\tfmt.Printf(\"skipping UML generation for '%s'\\n\", *v)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t//\r\n\t// end the scopes and write the files\r\n\t//\r\n\tfor _, k := range master.GetScopeKeys() {\r\n\t\tumlSb := scopeUMLBuilderMap[k]\r\n\t\tnoteSb := scopeNotesBuilderMap[k]\r\n\r\n\t\tif noteSb.Len() > 0 {\r\n\t\t\tumlSb.WriteString(fmt.Sprintf(\"note as Note%s\\n\", k))\r\n\t\t\tumlSb.WriteString(noteSb.String())\r\n\t\t\tumlSb.WriteString(\"end note\\n\")\r\n\t\t\tumlSb.WriteString(fmt.Sprintf(\"%s .. Note%s\\n\", k, k))\r\n\t\t}\r\n\r\n\t\tumlSb.WriteString(\"@enduml\\n\")\r\n\r\n\t\tfileName := outputFolder + k + \".uml.txt\"\r\n\t\tuml := umlSb.String()\r\n\t\tumlBytes := []byte(uml)\r\n\t\terr := ioutil.WriteFile(fileName, umlBytes, 0644)\r\n\t\tif err != nil {\r\n\t\t\tfmt.Printf(\"ERROR: err while writing to %s\\n\", fileName)\r\n\t\t\tfmt.Println(err)\r\n\t\t} else {\r\n\t\t\tfmt.Printf(\"wrote out %s\\n\", fileName)\r\n\t\t}\r\n\t}\r\n\r\n}", "func Generate(req *plugin.CodeGeneratorRequest, p Plugin, filenameSuffix string) *plugin.CodeGeneratorResponse {\n\tg := New()\n\tg.Request = req\n\tif len(g.Request.FileToGenerate) == 0 {\n\t\tg.Fail(\"no files to generate\")\n\t}\n\n\tg.CommandLineParameters(g.Request.GetParameter())\n\n\tg.WrapTypes()\n\tg.SetPackageNames()\n\tg.BuildTypeNameMap()\n\tg.GeneratePlugin(p)\n\n\tfor i := 0; i < len(g.Response.File); i++ {\n\t\tg.Response.File[i].Name = proto.String(\n\t\t\tstrings.Replace(*g.Response.File[i].Name, \".pb.go\", filenameSuffix, -1),\n\t\t)\n\t}\n\tif err := FormatSource(g.Response); err != nil {\n\t\tg.Error(err)\n\t}\n\treturn g.Response\n}", "func Generate(conf config.Curve, baseDir string, bgen *bavard.BatchGenerator) error {\n\tif conf.Equal(config.BW6_761) || conf.Equal(config.BW6_633) || conf.Equal(config.BLS24_315) {\n\t\treturn nil\n\t}\n\n\tentries := []bavard.Entry{\n\t\t{File: filepath.Join(baseDir, \"e2.go\"), Templates: []string{\"fq2.go.tmpl\"}},\n\t\t{File: filepath.Join(baseDir, \"e6.go\"), Templates: []string{\"fq6.go.tmpl\"}},\n\t\t{File: filepath.Join(baseDir, \"e12.go\"), Templates: []string{\"fq12.go.tmpl\"}},\n\t\t{File: filepath.Join(baseDir, \"e2_amd64.go\"), Templates: []string{\"amd64.fq2.go.tmpl\"}},\n\t\t{File: filepath.Join(baseDir, \"e2_fallback.go\"), Templates: []string{\"fallback.fq2.go.tmpl\"}, BuildTag: \"!amd64\"},\n\t\t{File: filepath.Join(baseDir, \"e2_test.go\"), Templates: []string{\"tests/fq2.go.tmpl\"}},\n\t\t{File: filepath.Join(baseDir, \"e6_test.go\"), Templates: []string{\"tests/fq6.go.tmpl\"}},\n\t\t{File: filepath.Join(baseDir, \"e12_test.go\"), Templates: []string{\"tests/fq12.go.tmpl\"}},\n\t\t{File: filepath.Join(baseDir, \"asm.go\"), Templates: []string{\"asm.go.tmpl\"}, BuildTag: \"!noadx\"},\n\t\t{File: filepath.Join(baseDir, \"asm_noadx.go\"), Templates: []string{\"asm_noadx.go.tmpl\"}, BuildTag: \"noadx\"},\n\t}\n\n\tif err := bgen.Generate(conf, \"fptower\", \"./tower/template/fq12over6over2\", entries...); err != nil {\n\t\treturn err\n\t}\n\n\t{\n\t\t// fq2 assembly\n\t\tfName := filepath.Join(baseDir, \"e2_amd64.s\")\n\t\tf, err := os.Create(fName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif conf.Equal(config.BN254) || conf.Equal(config.BLS12_381) {\n\t\t\t_, _ = io.WriteString(f, \"// +build !amd64_adx\\n\")\n\t\t}\n\t\tFq2Amd64 := amd64.NewFq2Amd64(f, conf.Fp, conf)\n\t\tif err := Fq2Amd64.Generate(true); err != nil {\n\t\t\t_ = f.Close()\n\t\t\treturn err\n\t\t}\n\t\t_ = f.Close()\n\n\t}\n\n\tif conf.Equal(config.BN254) || conf.Equal(config.BLS12_381) {\n\t\t{\n\t\t\t// fq2 assembly\n\t\t\tfName := filepath.Join(baseDir, \"e2_adx_amd64.s\")\n\t\t\tf, err := os.Create(fName)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t_, _ = io.WriteString(f, \"// +build amd64_adx\\n\")\n\t\t\tFq2Amd64 := amd64.NewFq2Amd64(f, conf.Fp, conf)\n\t\t\tif err := Fq2Amd64.Generate(false); err != nil {\n\t\t\t\t_ = f.Close()\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_ = f.Close()\n\n\t\t}\n\t}\n\n\treturn nil\n\n}", "func (tg *Generate) CreateAll() (err error) {\n\tif tg == nil {\n\t\treturn ErrInvalidTemlateGenerator\n\t}\n\tif tg.Project == \"\" {\n\t\treturn ErrInvalidRoot\n\t}\n\t// Todo write more conditions here\n\n\tfor _, opsData := range tg.Mapping.OpsData {\n\t\t//fmt.Println(opsData)\n\t\tswitch opsData.OpType {\n\t\tcase \"directories\":\n\t\t\tpath := filepath.Join(tg.Project, opsData.Src)\n\t\t\ttg.Output <- \"generating the following directory :\" + path\n\t\t\terr = os.MkdirAll(path, os.ModePerm)\n\t\t\tif err != nil {\n\t\t\t\terrRm := tg.RmDir()\n\t\t\t\tif errRm != nil {\n\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ttg.Output <- \"the following directory has been generated :\" + path\n\t\tcase \"static-files\":\n\t\t\tdst := filepath.Join(tg.Project, opsData.Dst)\n\t\t\ttg.Output <- \"generating the following static file :\" + dst\n\t\t\tcontent, err := tg.Mapping.Reader.Read(opsData.Src)\n\t\t\tif err != nil {\n\t\t\t\terrRm := tg.RmDir()\n\t\t\t\tif errRm != nil {\n\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif content != \"\" {\n\t\t\t\tvar li int\n\n\t\t\t\tcos := runtime.GOOS\n\t\t\t\tswitch cos {\n\t\t\t\tcase \"windows\":\n\t\t\t\t\tli = strings.LastIndex(dst, \"\\\\\")\n\t\t\t\tdefault:\n\t\t\t\t\tli = strings.LastIndex(dst, \"/\")\n\t\t\t\t}\n\n\t\t\t\tdirs := dst[0:li]\n\t\t\t\terr = os.MkdirAll(dirs, 0755)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrRm := tg.RmDir()\n\t\t\t\t\tif errRm != nil {\n\t\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\terr = ioutil.WriteFile(dst, []byte(content), 0644)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrRm := tg.RmDir()\n\t\t\t\t\tif errRm != nil {\n\t\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ttg.Output <- \"The following static file has been generated :\" + dst\n\t\t\t}\n\t\tcase \"multiple-file-templates\":\n\t\t\tmhandler := make(map[string]interface{})\n\t\t\tmhandler[\"Project\"] = tg.Project\n\t\t\tmhandler[\"config\"] = tg\n\t\t\tif opsData.GenForType == \"both\" {\n\t\t\t\tfor _, v := range tg.Models {\n\t\t\t\t\tmhandler[\"Model\"] = v\n\t\t\t\t\tdst := filepath.Join(tg.Project, opsData.Dst)\n\t\t\t\t\ttg.Output <- \"generating template based file :\" + dst\n\t\t\t\t\terr = os.MkdirAll(dst, 0755)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\terrRm := tg.RmDir()\n\t\t\t\t\t\tif errRm != nil {\n\t\t\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\t// If there is any extension in the opsData that means file to be created with the given extension. Otherwise create a default one with .go\n\t\t\t\t\tif opsData.Ext == \"\" {\n\t\t\t\t\t\tdst = path.Join(tg.Project, opsData.Dst, strings.ToLower(v.Name)+\".go\")\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// If any extension starts with . add the extension as it is.Otherwise add . as a prefix to the opsData.Ext\n\t\t\t\t\t\tif string(strings.Trim(opsData.Ext, \" \")[0]) == \".\" {\n\t\t\t\t\t\t\tdst = path.Join(tg.Project, opsData.Dst, strings.ToLower(v.Name)+opsData.Ext)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdst = path.Join(tg.Project, opsData.Dst, strings.ToLower(v.Name)+\".\"+opsData.Ext)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcontent, err := tg.Mapping.Reader.Read(opsData.Src)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\terrRm := tg.RmDir()\n\t\t\t\t\t\tif errRm != nil {\n\t\t\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tif content != \"\" {\n\t\t\t\t\t\terr := tg.WriteTmplToFile(dst, content, mhandler)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\terrRm := tg.RmDir()\n\t\t\t\t\t\t\tif errRm != nil {\n\t\t\t\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttg.Output <- \"the following templated based file has been generated :\" + dst\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if opsData.GenForType == \"main\" {\n\t\t\t\tfor _, v := range tg.Models {\n\t\t\t\t\tif v.Type == \"main\" {\n\t\t\t\t\t\tmhandler[\"Model\"] = v\n\t\t\t\t\t\tdst := filepath.Join(tg.Project, opsData.Dst)\n\t\t\t\t\t\ttg.Output <- \"generating template based file :\" + dst\n\t\t\t\t\t\terr = os.MkdirAll(dst, 0755)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\terrRm := tg.RmDir()\n\t\t\t\t\t\t\tif errRm != nil {\n\t\t\t\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// If there is any extension in the opsData that means file to be created with the given extension. Otherwise create a default one with .go\n\t\t\t\t\t\tif opsData.Ext == \"\" {\n\t\t\t\t\t\t\tdst = path.Join(tg.Project, opsData.Dst, strings.ToLower(v.Name)+\".go\")\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// If any extension starts with . add the extension as it is.Otherwise add . as a prefix to the opsData.Ext\n\t\t\t\t\t\t\tif string(strings.Trim(opsData.Ext, \" \")[0]) == \".\" {\n\t\t\t\t\t\t\t\tdst = path.Join(tg.Project, opsData.Dst, strings.ToLower(v.Name)+opsData.Ext)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tdst = path.Join(tg.Project, opsData.Dst, strings.ToLower(v.Name)+\".\"+opsData.Ext)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontent, err := tg.Mapping.Reader.Read(opsData.Src)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\terrRm := tg.RmDir()\n\t\t\t\t\t\t\tif errRm != nil {\n\t\t\t\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif content != \"\" {\n\t\t\t\t\t\t\terr := tg.WriteTmplToFile(dst, content, mhandler)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\terrRm := tg.RmDir()\n\t\t\t\t\t\t\t\tif errRm != nil {\n\t\t\t\t\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttg.Output <- \"the following templated based file has been generated :\" + dst\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if opsData.GenForType == \"sub\" {\n\t\t\t\tfor _, v := range tg.Models {\n\t\t\t\t\tif v.Type == \"sub\" {\n\t\t\t\t\t\tmhandler[\"Model\"] = v\n\t\t\t\t\t\tdst := filepath.Join(tg.Project, opsData.Dst)\n\t\t\t\t\t\ttg.Output <- \"generating template based file :\" + dst\n\t\t\t\t\t\terr = os.MkdirAll(dst, 0755)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\terrRm := tg.RmDir()\n\t\t\t\t\t\t\tif errRm != nil {\n\t\t\t\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// If there is any extension in the opsData that means file to be created with the given extension. Otherwise create a default one with .go\n\t\t\t\t\t\tif opsData.Ext == \"\" {\n\t\t\t\t\t\t\tdst = path.Join(tg.Project, opsData.Dst, strings.ToLower(v.Name)+\".go\")\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// If any extension starts with . add the extension as it is.Otherwise add . as a prefix to the opsData.Ext\n\t\t\t\t\t\t\tif string(strings.Trim(opsData.Ext, \" \")[0]) == \".\" {\n\t\t\t\t\t\t\t\tdst = path.Join(tg.Project, opsData.Dst, strings.ToLower(v.Name)+opsData.Ext)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tdst = path.Join(tg.Project, opsData.Dst, strings.ToLower(v.Name)+\".\"+opsData.Ext)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontent, err := tg.Mapping.Reader.Read(opsData.Src)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\terrRm := tg.RmDir()\n\t\t\t\t\t\t\tif errRm != nil {\n\t\t\t\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif content != \"\" {\n\t\t\t\t\t\t\terr := tg.WriteTmplToFile(dst, content, mhandler)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\terrRm := tg.RmDir()\n\t\t\t\t\t\t\t\tif errRm != nil {\n\t\t\t\t\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttg.Output <- \"the following templated based file has been generated :\" + dst\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase \"single-file-templates\":\n\t\t\t// Todo for opsData.Ext if there is an extension\n\t\t\tmhandler := make(map[string]interface{})\n\t\t\tmhandler[\"config\"] = tg\n\t\t\tdst := path.Join(tg.Project, opsData.Dst)\n\t\t\ttg.Output <- \"generating template based contents to the file :\" + dst\n\t\t\tli := strings.LastIndex(dst, \"/\")\n\t\t\tdirs := dst[0:li]\n\t\t\terr = os.MkdirAll(dirs, 0755)\n\t\t\tif err != nil {\n\t\t\t\terrRm := tg.RmDir()\n\t\t\t\tif errRm != nil {\n\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontent, err := tg.Mapping.Reader.Read(opsData.Src)\n\t\t\tif err != nil {\n\t\t\t\terrRm := tg.RmDir()\n\t\t\t\tif errRm != nil {\n\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif content != \"\" {\n\t\t\t\terr := tg.WriteTmplToFile(dst, content, mhandler)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrRm := tg.RmDir()\n\t\t\t\t\tif errRm != nil {\n\t\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ttg.Output <- \"The following templated based file has been generated :\" + dst\n\t\t\t}\n\t\tcase \"exec\":\n\t\t\t// Todo for opsData.Ext if there is an extension\n\t\t\tmhandler := make(map[string]interface{})\n\t\t\tmhandler[\"config\"] = tg\n\t\t\tdst := path.Join(tg.Project, opsData.Dst)\n\t\t\ttg.Output <- \"generating shall based executable files :\" + dst\n\t\t\tli := strings.LastIndex(dst, \"/\")\n\t\t\tdirs := dst[0:li]\n\t\t\terr = os.MkdirAll(dirs, 0755)\n\t\t\tif err != nil {\n\t\t\t\terrRm := tg.RmDir()\n\t\t\t\tif errRm != nil {\n\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontent, err := tg.Mapping.Reader.Read(opsData.Src)\n\t\t\tif err != nil {\n\t\t\t\terrRm := tg.RmDir()\n\t\t\t\tif errRm != nil {\n\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif content != \"\" {\n\t\t\t\terr := tg.WriteTmplToFile(dst, content, mhandler)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrRm := tg.RmDir()\n\t\t\t\t\tif errRm != nil {\n\t\t\t\t\t\treturn errors.New(\"1.\" + err.Error() + \".2.\" + errRm.Error())\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ttg.Output <- \"The following shell file has been generated :\" + dst\n\n\t\t\t\terr = os.Chmod(dst, 0700)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ttg.Output <- \"giving read|writeexecute permissions to the file :\" + dst\n\n\t\t\t}\n\t\tdefault:\n\t\t\treturn errors.New(opsData.OpType + \":this type has no implementation\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func main() {\n\tflag.Var(&filenames, \"filename\", \"specified filename those you want to generate, if no filename be set, will parse all files under ($dir)\")\n\tflag.Parse()\n\n\texportDir, _ := filepath.Abs(*generateDir)\n\t*dir, _ = filepath.Abs(*dir)\n\tif *debug {\n\t\tlog.Println(\"fromDir:\", *dir)\n\t\tlog.Println(\"generateFilename:\", *generateFilename)\n\t\tlog.Println(\"exportDir:\", exportDir)\n\t}\n\n\t// set custom funcs\n\t// tools.SetCustomGenTagFunc(CustomGenerateTagFunc)\n\t// tools.SetCustomParseTagFunc(CustomParseTagFunc)\n\n\tif len(filenames) == 0 {\n\t\tfiles, _ := ioutil.ReadDir(*dir)\n\t\tfor _, file := range files {\n\t\t\tif file.IsDir() || !strings.HasSuffix(file.Name(), \".go\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfilenames = append(filenames, file.Name())\n\t\t}\n\t}\n\n\tcfg := &tools.UsageCfg{\n\t\tExportDir: exportDir,\n\t\tExportFilename: *generateFilename,\n\t\tExportPkgName: *generatePkgName,\n\t\tExportStructSuffix: *generateStructSuffix,\n\t\tModelImportPath: *modelImportPath,\n\t\tStructSuffix: *modelStructSuffix,\n\t\tDebug: *debug,\n\t\tFilenames: filenames,\n\t\tDir: *dir,\n\t}\n\n\tif *debug {\n\t\tlog.Println(\"following filenames will be parsed\", filenames)\n\t}\n\n\tif err := tools.ParseAndGenerate(cfg); err != nil {\n\t\tpanic(err)\n\t}\n\n\tprintln(\"done!\")\n}", "func (g *Generator) Fgenerate(w io.Writer) {\n\ttpkg := templateBuilder(\"package\", `package {{ .Package }}{{\"\\n\\n\"}}`)\n\n\ttimp := templateBuilder(\"imports\", `import {{ if eq (len .Imports) 1 }}\"{{ index .Imports 0 }}\"{{else}}(\n{{ range .Imports }}{{\"\\t\"}}\"{{ . }}\"\n{{ end }}){{ end }}{{\"\\n\\n\"}}`)\n\n\tttyp := templateBuilder(\"type\", `type {{ .Opts.Type }} struct{{\"{\"}}\n{{- if gt (len .Deps) 0 -}}{{ \"\\n\" }}\n {{- range .Deps -}}\n {{- \"\\t\" }}{{ .Name }} {{ .Type -}}{{ \"\\n\" }}\n {{- end -}}\n{{- end -}}\n}{{\"\\n\\n\"}}`)\n\n\ttdep := templateBuilder(\"deps\", `{{- $cname := .Opts.Name -}}\n{{- $ctype := .Opts.Type -}}\n{{- range .Deps -}}\nfunc ({{ $cname }} *{{ $ctype }}) New{{ .Name | ucfirst }}() {{ .Type }} {{ .Func }}{{ \"\\n\\n\" }}\nfunc ({{ $cname }} *{{ $ctype }}) {{ .Name | ucfirst }}() {{ .Type }} {\n{{ \"\\t\" }}if {{ $cname }}.{{ .Name | lcfirst }} == nil {\n{{ \"\\t\\t\" }}{{ $cname }}.{{ .Name | lcfirst }} = {{ $cname }}.New{{ .Name | ucfirst }}()\n{{ \"\\t\" }}}\n{{ \"\\t\" }}return {{ $cname }}.{{ .Name | lcfirst }}\n}{{ \"\\n\\n\" }}\n{{- end -}}`)\n\n\terr := tpkg.Execute(w, g.opts)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif len(g.opts.Imports) > 0 {\n\t\terr = timp.Execute(w, g.opts)\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tgWithPublicFields := struct {\n\t\tOpts opts\n\t\tDeps []dep\n\t}{\n\t\tg.opts,\n\t\tg.deps,\n\t}\n\n\terr = ttyp.Execute(w, gWithPublicFields)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif len(g.deps) > 0 {\n\t\terr = tdep.Execute(w, gWithPublicFields)\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func (s *Service) Generate(dir, filename string) error {\n\terr := makeDirIfNotExists(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(path.Join(dir, filename))\n\tdefer f.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.generator.Execute(f, s.tmpl)\n}", "func GenerateSubCommands() []*cobra.Command {\n\n\tvar generateUserManagement = &cobra.Command{\n\t\tUse: \"auth-provider [path to config file]\",\n\t\tRunE: actionGenerateUserManagement,\n\t\tAliases: []string{\"auth-providers\"},\n\t\tExample: \"space-cli generate auth-provider config.yaml --project myproject --log-level info\",\n\t}\n\n\treturn []*cobra.Command{generateUserManagement}\n}", "func (*okapiLang) GenerateRules(args language.GenerateArgs) language.GenerateResult {\n\tconfig, valid := args.Config.Exts[okapiName].(Config)\n\tif !valid {\n\t\tlog.Fatalf(\"invalid config: %#v\", args.Config.Exts[okapiName])\n\t}\n\tvar results []RuleResult\n\tif args.File != nil && args.File.Rules != nil && containsLibrary(args.File.Rules) {\n\t\t// results = AmendRules(args, args.File.Rules, Dependencies(args.Dir, args.RegularFiles), *config.library)\n\t} else {\n\t\tresults = generateIfOcaml(args, *config.library)\n\t}\n\t// Poorman's unzip\n\tvar rules []*rule.Rule\n\tvar imports []interface{}\n\tfor _, result := range results {\n\t\trules = append(rules, result.rule)\n\t\timports = append(imports, result.deps)\n\t}\n\treturn language.GenerateResult{\n\t\tGen: rules,\n\t\tEmpty: nil,\n\t\tImports: imports,\n\t}\n}", "func generateBodyStructs(apiDef *raml.APIDefinition, dir, packageName string) error {\n\t// generate\n\tfor _, v := range apiDef.Resources {\n\t\tif err := generateStructsFromResourceBody(\"\", dir, packageName, &v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func Generate(dir string, varConfName string) {\n\tt, dirPath := gatherVars(dir, varConfName)\n\toutput(t, dirPath)\n}" ]
[ "0.66913444", "0.64157486", "0.61856574", "0.61356175", "0.5997691", "0.589548", "0.57147914", "0.56822777", "0.56303346", "0.5599357", "0.5589933", "0.55740947", "0.5566793", "0.5553001", "0.55090463", "0.5508715", "0.5495265", "0.54901445", "0.5487085", "0.5477915", "0.54352814", "0.54107386", "0.53808415", "0.53748345", "0.533596", "0.53288394", "0.5309424", "0.53075117", "0.52891326", "0.52842444", "0.5276375", "0.52436453", "0.5241689", "0.5231385", "0.5228604", "0.52280027", "0.52167946", "0.5197135", "0.5195845", "0.515559", "0.5129238", "0.50912166", "0.5082226", "0.507459", "0.5067638", "0.50665027", "0.5058799", "0.5052758", "0.504078", "0.5035947", "0.5035558", "0.50193906", "0.5010657", "0.500742", "0.50033695", "0.49998856", "0.49992004", "0.4992752", "0.49893606", "0.49813357", "0.4980251", "0.49726284", "0.4970004", "0.496529", "0.49641046", "0.49622092", "0.49536887", "0.49487722", "0.4947907", "0.49445075", "0.4943662", "0.49388188", "0.49275476", "0.49256897", "0.4911477", "0.49097633", "0.4902586", "0.48996234", "0.48940456", "0.4893853", "0.48938176", "0.48935306", "0.48780435", "0.48721305", "0.4868479", "0.48673907", "0.48672086", "0.4863784", "0.48624963", "0.4860453", "0.4852028", "0.48428935", "0.4827657", "0.48274705", "0.48171806", "0.48122436", "0.48087403", "0.4782019", "0.47706237", "0.47699928" ]
0.8132264
0
ParseSwaggerDependencyTree parses the entire dependency tree of a magma swagger spec file specified by the rootFilepath parameter. The returned value maps between the absolute specified dependency filepath and the parsed struct for the dependency file.
func ParseSwaggerDependencyTree(rootFilepath string, rootDir string) (map[string]MagmaSwaggerSpec, error) { absRootFilepath, err := filepath.Abs(rootFilepath) if err != nil { return nil, fmt.Errorf("root filepath %s is invalid: %w", rootFilepath, err) } targetSpec, err := readSwaggerSpec(absRootFilepath) if err != nil { return nil, err } type mscAndPath struct { MagmaSwaggerSpec path string } // Do a BFS to parse the entire dependency tree of swagger spec files // into structs openedFiles := map[string]bool{absRootFilepath: true} allSpecs := map[string]MagmaSwaggerSpec{} specsToVisit := []mscAndPath{{MagmaSwaggerSpec: targetSpec, path: absRootFilepath}} for len(specsToVisit) > 0 { nextSpec := specsToVisit[0] specsToVisit = specsToVisit[1:] allSpecs[nextSpec.path] = nextSpec.MagmaSwaggerSpec for _, dependencyPath := range nextSpec.MagmaGenMeta.Dependencies { absDependencyPath, err := filepath.Abs(filepath.Join(rootDir, dependencyPath)) if err != nil { return nil, fmt.Errorf("dependency filepath %s is invalid: %w", dependencyPath, err) } if _, alreadyOpened := openedFiles[absDependencyPath]; alreadyOpened { continue } openedFiles[absDependencyPath] = true dependencySpec, err := readSwaggerSpec(absDependencyPath) if err != nil { return nil, fmt.Errorf("failed to read dependency tree of swagger specs: %w", err) } specsToVisit = append( specsToVisit, mscAndPath{ MagmaSwaggerSpec: dependencySpec, path: absDependencyPath, }, ) } } return allSpecs, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Matcher) GeneratorDependencyTree(manifestFilePath string) string {\n\tlog.Debug().Msgf(\"Executing: Generate dependencies.txt\")\n\tmaven, err := exec.LookPath(\"mvn\")\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msgf(\"Please make sure Maven is installed. Hint: Check same by executing: mvn --version \\n\")\n\t}\n\ttreePath, _ := filepath.Abs(filepath.Join(os.TempDir(), m.DepsTreeFileName()))\n\toutcmd := fmt.Sprintf(\"-DoutputFile=%s\", treePath)\n\tcleanRepo := exec.Command(maven, \"--quiet\", \"clean\", \"-f\", manifestFilePath)\n\tdependencyTree := exec.Command(maven, \"--quiet\", \"org.apache.maven.plugins:maven-dependency-plugin:3.0.2:tree\", \"-f\", manifestFilePath, outcmd, \"-DoutputType=dot\", \"-DappendOutput=true\")\n\tlog.Debug().Msgf(\"Clean Repo Command: %s\", cleanRepo)\n\tlog.Debug().Msgf(\"dependencyTree Command: %s\", dependencyTree)\n\tif err := cleanRepo.Run(); err != nil {\n\t\tlog.Fatal().Err(err).Msgf(err.Error())\n\t}\n\tif err := dependencyTree.Run(); err != nil {\n\t\tlog.Fatal().Err(err).Msgf(err.Error())\n\t}\n\tlog.Debug().Msgf(\"Success: buildDepsTree\")\n\treturn treePath\n}", "func ParseDepFile(content []byte) ([]string, []string) {\n\tcontent = bytes.Replace(content, []byte(\"\\\\\\n\"), nil, -1)\n\tcomponents := bytes.Split(content, []byte(\":\"))\n\tif len(components) != 2 {\n\t\treturn nil, nil\n\t}\n\n\ttargetStrs := bytes.Split(components[0], []byte(\" \"))\n\tdepStrs := bytes.Split(components[1], []byte(\" \"))\n\n\tvar targets, deps []string\n\tfor _, t := range targetStrs {\n\t\tif len(t) > 0 {\n\t\t\ttargets = append(targets, string(t))\n\t\t}\n\t}\n\tfor _, d := range depStrs {\n\t\tif len(d) > 0 {\n\t\t\tdeps = append(deps, string(d))\n\t\t}\n\t}\n\n\treturn targets, deps\n}", "func flattenDepsToRoot(manager gps.SourceManager, deps []Dependency) (map[string]string, error) {\n\tdepMap := make(map[string]string)\n\tfor _, d := range deps {\n\t\troot, err := manager.DeduceProjectRoot(d.ImportPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdepMap[string(root)] = d.Rev\n\t}\n\treturn depMap, nil\n}", "func loadTree(root string) (*importTree, error) {\n\tvar f fileLoaderFunc\n\tswitch ext(root) {\n\tcase \".tf\", \".tf.json\":\n\t\tf = loadFileHcl\n\tdefault:\n\t}\n\n\tif f == nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"%s: unknown configuration format. Use '.tf' or '.tf.json' extension\",\n\t\t\troot)\n\t}\n\n\tc, imps, err := f(root)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tchildren := make([]*importTree, len(imps))\n\tfor i, imp := range imps {\n\t\tt, err := loadTree(imp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tchildren[i] = t\n\t}\n\n\treturn &importTree{\n\t\tPath: root,\n\t\tRaw: c,\n\t\tChildren: children,\n\t}, nil\n}", "func dependencyCache(chartdir string) (map[string]*chart.Chartfile, error) {\n\tcache := map[string]*chart.Chartfile{}\n\tdir, err := os.Open(chartdir)\n\tif err != nil {\n\t\treturn cache, err\n\t}\n\tdefer dir.Close()\n\n\tfis, err := dir.Readdir(0)\n\tif err != nil {\n\t\treturn cache, err\n\t}\n\n\tfor _, fi := range fis {\n\t\tif !fi.IsDir() {\n\t\t\tcontinue\n\t\t}\n\t\tcf, err := chart.LoadChartfile(filepath.Join(chartdir, fi.Name(), \"Chart.yaml\"))\n\t\tif err != nil {\n\t\t\t// If the chartfile does not load, we ignore it.\n\t\t\tcontinue\n\t\t}\n\n\t\tcache[fi.Name()] = cf\n\t}\n\treturn cache, nil\n}", "func (w *RootWalker) DeserializeFromRef(ref skyobject.Reference, p interface{}) error {\n\tif w.r == nil {\n\t\treturn ErrRootNotFound\n\t}\n\tdata, got := w.r.Get(ref)\n\tif !got {\n\t\treturn ErrObjNotFound\n\t}\n\treturn encoder.DeserializeRaw(data, p)\n}", "func Parse(dir string) ([]*cfg.Dependency, error) {\n\tpath := filepath.Join(dir, \"Godeps/Godeps.json\")\n\tif _, err := os.Stat(path); err != nil {\n\t\treturn []*cfg.Dependency{}, nil\n\t}\n\tmsg.Info(\"Found Godeps.json file in %s\", gpath.StripBasepath(dir))\n\tmsg.Info(\"--> Parsing Godeps metadata...\")\n\n\tbuf := []*cfg.Dependency{}\n\n\tgodeps := &Godeps{}\n\n\t// Get a handle to the file.\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn buf, err\n\t}\n\tdefer file.Close()\n\n\tdec := json.NewDecoder(file)\n\tif err := dec.Decode(godeps); err != nil {\n\t\treturn buf, err\n\t}\n\n\tseen := map[string]bool{}\n\tfor _, d := range godeps.Deps {\n\t\tpkg, _ := util.NormalizeName(d.ImportPath)\n\t\tif !seen[pkg] {\n\t\t\tseen[pkg] = true\n\t\t\tdep := &cfg.Dependency{Name: pkg, Version: d.Rev}\n\t\t\tbuf = append(buf, dep)\n\t\t}\n\t}\n\n\treturn buf, nil\n}", "func parseGoListOutput(output, rootVersion string) (map[string]Module, error) {\n\tdependencies := map[string]Module{}\n\tdecoder := json.NewDecoder(strings.NewReader(output))\n\n\tfor {\n\t\tvar module jsonModule\n\t\tif err := decoder.Decode(&module); err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Stash original name before applying replacement\n\t\timportPath := module.Name\n\n\t\t// If there's a replace directive, use that module instead\n\t\tif module.Replace != nil {\n\t\t\tmodule = *module.Replace\n\t\t}\n\n\t\t// Local file paths and root modules\n\t\tif module.Version == \"\" {\n\t\t\tmodule.Version = rootVersion\n\t\t}\n\n\t\tdependencies[importPath] = Module{\n\t\t\tName: module.Name,\n\t\t\tVersion: cleanVersion(module.Version),\n\t\t}\n\t}\n\n\treturn dependencies, nil\n}", "func ParsePackageJSON(rawFile []byte) map[string]string {\n\tv, _ := jason.NewObjectFromBytes(rawFile)\n\n\tdevDependecies, _ := v.GetObject(\"devDependencies\")\n\tdeps, _ := v.GetObject(\"dependencies\")\n\n\tversions := map[string]string{}\n\tassignVersionsFromDeps(devDependecies, versions)\n\tassignVersionsFromDeps(deps, versions)\n\n\treturn versions\n}", "func Parse(r io.ReadSeeker, pkgpath string) (*Package, error)", "func Decompose(root string) ([]byte, error) {\n\tm := make(map[string]interface{})\n\n\t// TODO: actually support arbitrary depths :)\n\t// TODO: yaml support would be nice as well\n\n\terr := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbase, err := filepath.Rel(root, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !info.Mode().IsRegular() {\n\t\t\treturn nil\n\t\t}\n\n\t\tif !strings.HasSuffix(path, \".json\") {\n\t\t\treturn nil\n\t\t}\n\n\t\tf, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar v map[string]interface{}\n\t\tif err := json.NewDecoder(f).Decode(&v); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tname := strings.Replace(base, \".json\", \"\", -1)\n\n\t\tif \"index\" == name {\n\t\t\tfor k, v := range v {\n\t\t\t\tm[k] = v\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tm[name] = v\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn json.MarshalIndent(m, \"\", \" \")\n}", "func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {\n\tinfo, err := buildinfo.Read(r)\n\tif err != nil {\n\t\treturn nil, nil, convertError(err)\n\t}\n\n\tlibs := make([]types.Library, 0, len(info.Deps))\n\n\tfor _, dep := range info.Deps {\n\t\t// binaries with old go version may incorrectly add module in Deps\n\t\t// In this case Path == \"\", Version == \"Devel\"\n\t\t// we need to skip this\n\t\tif dep.Path == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tmod := dep\n\t\tif dep.Replace != nil {\n\t\t\tmod = dep.Replace\n\t\t}\n\n\t\tlibs = append(libs, types.Library{\n\t\t\tName: mod.Path,\n\t\t\tVersion: mod.Version,\n\t\t})\n\t}\n\n\treturn libs, nil, nil\n}", "func getDependenciesForModule(module *TerraformModule, moduleMap map[string]*TerraformModule, terragruntConfigPaths []string) ([]*TerraformModule, error) {\n\tdependencies := []*TerraformModule{}\n\n\tif module.Config.Dependencies == nil || len(module.Config.Dependencies.Paths) == 0 {\n\t\treturn dependencies, nil\n\t}\n\n\tfor _, dependencyPath := range module.Config.Dependencies.Paths {\n\t\tdependencyModulePath, err := util.CanonicalPath(dependencyPath, module.Path)\n\t\tif err != nil {\n\t\t\treturn dependencies, nil\n\t\t}\n\n\t\tdependencyModule, foundModule := moduleMap[dependencyModulePath]\n\t\tif !foundModule {\n\t\t\terr := UnrecognizedDependency{\n\t\t\t\tModulePath: module.Path,\n\t\t\t\tDependencyPath: dependencyPath,\n\t\t\t\tTerragruntConfigPaths: terragruntConfigPaths,\n\t\t\t}\n\t\t\treturn dependencies, errors.WithStackTrace(err)\n\t\t}\n\t\tdependencies = append(dependencies, dependencyModule)\n\t}\n\n\treturn dependencies, nil\n}", "func ParseFile(path string) ([]*StructData, error) {\n\tfset := token.NewFileSet()\n\tfileNode, err := parser.ParseFile(fset, path, nil, parser.ParseComments)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error parsing file %v: %v\", path, err)\n\t}\n\n\tvar res []*StructData\n\n\tfor _, decl := range fileNode.Decls {\n\t\tgd, ok := decl.(*ast.GenDecl)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, spec := range gd.Specs {\n\t\t\tts, ok := spec.(*ast.TypeSpec)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// magic comment may be attached to \"type Foo struct\" (TypeSpec)\n\t\t\t// or to \"type (\" (GenDecl)\n\t\t\tdoc := ts.Doc\n\t\t\tif doc == nil && len(gd.Specs) == 1 {\n\t\t\t\tdoc = gd.Doc\n\t\t\t}\n\t\t\tif doc == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\targs, ok := magicYagoCommentArgs(doc.Text())\n\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttablename := ToDBName(ts.Name.Name)\n\n\t\t\tif args.TableName != \"\" {\n\t\t\t\ttablename = args.TableName\n\t\t\t}\n\n\t\t\tstr, ok := ts.Type.(*ast.StructType)\n\t\t\tif !ok || str.Incomplete {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsd, err := parseStructTypeSpecs(ts, str, args.AutoAttrs)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tsd.NoTable = args.NoTable\n\t\t\tif !sd.NoTable {\n\t\t\t\tsd.TableName = tablename\n\t\t\t}\n\t\t\tres = append(res, sd)\n\t\t}\n\t}\n\n\treturn res, nil\n}", "func TestFindMapPaths(t *testing.T) {\n\tms := compileModules(t, map[string]string{\n\t\t\"a-module\": `\n\t\t\tmodule a-module {\n\t\t\t\tprefix \"m\";\n\t\t\t\tnamespace \"urn:m\";\n\n\t\t\t\tcontainer a-container {\n\t\t\t\t\tleaf field-a {\n\t\t\t\t\t\ttype string;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcontainer b-container {\n\t\t\t\t\tcontainer config {\n\t\t\t\t\t\tleaf field-b {\n\t\t\t\t\t\t\ttype string;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcontainer state {\n\t\t\t\t\t\tleaf field-b {\n\t\t\t\t\t\t\ttype string;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tcontainer c-container {\n\t\t\t\t\t\tleaf field-d {\n\t\t\t\t\t\t\ttype string;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t`,\n\t\t\"d-module\": `\n\t\t\tmodule d-module {\n\t\t\t\tprefix \"n\";\n\t\t\t\tnamespace \"urn:n\";\n\n\t\t\t\timport a-module { prefix \"a\"; }\n\n\t\t\t\taugment \"/a:b-container/config\" {\n\t\t\t\t\tleaf field-c { type string; }\n\t\t\t\t}\n\n\t\t\t\taugment \"/a:b-container/state\" {\n\t\t\t\t\tleaf field-c { type string; }\n\t\t\t\t}\n\n\t\t\t\tcontainer d-container {\n\t\t\t\t\tlist d-list {\n\t\t\t\t\t\tkey d-key;\n\n\t\t\t\t\t\tleaf d-key {\n\t\t\t\t\t\t\ttype leafref {\n\t\t\t\t\t\t\t\tpath \"../config/d-key\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcontainer config {\n\t\t\t\t\t\t\tleaf d-key {\n\t\t\t\t\t\t\t\ttype string;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcontainer state {\n\t\t\t\t\t\t\tleaf d-key {\n\t\t\t\t\t\t\t\ttype string;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t`,\n\t})\n\n\ttests := []struct {\n\t\tname string\n\t\tinStruct *Directory\n\t\tinField string\n\t\tinCompressPaths bool\n\t\tinShadowSchemaPaths bool\n\t\tinAbsolutePaths bool\n\t\twantPaths [][]string\n\t\twantModules [][]string\n\t\twantErr bool\n\t}{{\n\t\tname: \"first-level container with path compression off\",\n\t\tinStruct: &Directory{\n\t\t\tName: \"AContainer\",\n\t\t\tPath: []string{\"\", \"a-module\", \"a-container\"},\n\t\t\tFields: map[string]*yang.Entry{\n\t\t\t\t\"field-a\": findEntry(t, ms, \"a-module\", \"a-container/field-a\"),\n\t\t\t},\n\t\t},\n\t\tinField: \"field-a\",\n\t\twantPaths: [][]string{{\"field-a\"}},\n\t\twantModules: [][]string{{\"a-module\"}},\n\t}, {\n\t\tname: \"invalid parent path - shorter than directory path\",\n\t\tinStruct: &Directory{\n\t\t\tName: \"AContainer\",\n\t\t\tPath: []string{\"\", \"a-module\", \"a-container\"},\n\t\t\tFields: map[string]*yang.Entry{\n\t\t\t\t\"field-a\": findEntry(t, ms, \"a-module\", \"a-container\"),\n\t\t\t},\n\t\t},\n\t\tinField: \"field-a\",\n\t\twantErr: true,\n\t}, {\n\t\tname: \"first-level container with path compression on\",\n\t\tinStruct: &Directory{\n\t\t\tName: \"BContainer\",\n\t\t\tPath: []string{\"\", \"a-module\", \"b-container\"},\n\t\t\tFields: map[string]*yang.Entry{\n\t\t\t\t\"field-b\": findEntry(t, ms, \"a-module\", \"b-container/config/field-b\"),\n\t\t\t},\n\t\t\tShadowedFields: map[string]*yang.Entry{\n\t\t\t\t\"field-b\": findEntry(t, ms, \"a-module\", \"b-container/state/field-b\"),\n\t\t\t},\n\t\t},\n\t\tinField: \"field-b\",\n\t\tinCompressPaths: true,\n\t\twantPaths: [][]string{{\"config\", \"field-b\"}},\n\t\twantModules: [][]string{{\"a-module\", \"a-module\"}},\n\t}, {\n\t\tname: \"first-level container with path compression on and ignoreShadowSchemaPaths on\",\n\t\tinStruct: &Directory{\n\t\t\tName: \"BContainer\",\n\t\t\tPath: []string{\"\", \"a-module\", \"b-container\"},\n\t\t\tFields: map[string]*yang.Entry{\n\t\t\t\t\"field-b\": findEntry(t, ms, \"a-module\", \"b-container/config/field-b\"),\n\t\t\t},\n\t\t\tShadowedFields: map[string]*yang.Entry{\n\t\t\t\t\"field-b\": findEntry(t, ms, \"a-module\", \"b-container/state/field-b\"),\n\t\t\t},\n\t\t},\n\t\tinField: \"field-b\",\n\t\tinCompressPaths: true,\n\t\tinShadowSchemaPaths: true,\n\t\twantPaths: [][]string{{\"state\", \"field-b\"}},\n\t\twantModules: [][]string{{\"a-module\", \"a-module\"}},\n\t}, {\n\t\tname: \"augmented first-level container with path compression on\",\n\t\tinStruct: &Directory{\n\t\t\tName: \"BContainer\",\n\t\t\tPath: []string{\"\", \"a-module\", \"b-container\"},\n\t\t\tFields: map[string]*yang.Entry{\n\t\t\t\t\"field-c\": findEntry(t, ms, \"a-module\", \"b-container/config/field-c\"),\n\t\t\t},\n\t\t\tShadowedFields: map[string]*yang.Entry{\n\t\t\t\t\"field-c\": findEntry(t, ms, \"a-module\", \"b-container/state/field-c\"),\n\t\t\t},\n\t\t},\n\t\tinField: \"field-c\",\n\t\tinCompressPaths: true,\n\t\twantPaths: [][]string{{\"config\", \"field-c\"}},\n\t\twantModules: [][]string{{\"a-module\", \"d-module\"}},\n\t}, {\n\t\tname: \"augmented first-level container with inShadowSchemaPaths=true\",\n\t\tinStruct: &Directory{\n\t\t\tName: \"BContainer\",\n\t\t\tPath: []string{\"\", \"a-module\", \"b-container\"},\n\t\t\tFields: map[string]*yang.Entry{\n\t\t\t\t\"field-c\": findEntry(t, ms, \"a-module\", \"b-container/config/field-c\"),\n\t\t\t},\n\t\t\tShadowedFields: map[string]*yang.Entry{\n\t\t\t\t\"field-c\": findEntry(t, ms, \"a-module\", \"b-container/state/field-c\"),\n\t\t\t},\n\t\t},\n\t\tinField: \"field-c\",\n\t\tinCompressPaths: true,\n\t\tinShadowSchemaPaths: true,\n\t\twantPaths: [][]string{{\"state\", \"field-c\"}},\n\t\twantModules: [][]string{{\"a-module\", \"d-module\"}},\n\t}, {\n\t\tname: \"container with absolute paths on\",\n\t\tinStruct: &Directory{\n\t\t\tName: \"BContainer\",\n\t\t\tPath: []string{\"\", \"a-module\", \"b-container\", \"c-container\"},\n\t\t\tFields: map[string]*yang.Entry{\n\t\t\t\t\"field-d\": findEntry(t, ms, \"a-module\", \"b-container/c-container/field-d\"),\n\t\t\t},\n\t\t},\n\t\tinField: \"field-d\",\n\t\tinAbsolutePaths: true,\n\t\twantPaths: [][]string{{\"\", \"b-container\", \"c-container\", \"field-d\"}},\n\t\twantModules: [][]string{{\"\", \"a-module\", \"a-module\", \"a-module\"}},\n\t}, {\n\t\tname: \"top-level module\",\n\t\tinStruct: &Directory{\n\t\t\tName: \"CContainer\",\n\t\t\tPath: []string{\"\"},\n\t\t\tFields: map[string]*yang.Entry{\n\t\t\t\t\"top\": findEntry(t, ms, \"a-module\", \"\"),\n\t\t\t},\n\t\t},\n\t\tinField: \"top\",\n\t\twantPaths: [][]string{{\"a-module\"}},\n\t\twantModules: [][]string{{\"a-module\"}},\n\t}, {\n\t\tname: \"list with leafref key\",\n\t\tinStruct: &Directory{\n\t\t\tName: \"DList\",\n\t\t\tPath: []string{\"\", \"d-module\", \"d-container\", \"d-list\"},\n\t\t\tListAttr: &YangListAttr{\n\t\t\t\tKeyElems: []*yang.Entry{\n\t\t\t\t\tfindEntry(t, ms, \"d-module\", \"d-container/d-list/config/d-key\"),\n\t\t\t\t},\n\t\t\t},\n\t\t\tFields: map[string]*yang.Entry{\n\t\t\t\t\"d-key\": findEntry(t, ms, \"d-module\", \"d-container/d-list/config/d-key\"),\n\t\t\t},\n\t\t\tShadowedFields: map[string]*yang.Entry{\n\t\t\t\t\"d-key\": findEntry(t, ms, \"d-module\", \"d-container/d-list/state/d-key\"),\n\t\t\t},\n\t\t},\n\t\tinField: \"d-key\",\n\t\tinCompressPaths: true,\n\t\twantPaths: [][]string{\n\t\t\t{\"config\", \"d-key\"},\n\t\t\t{\"d-key\"},\n\t\t},\n\t\twantModules: [][]string{\n\t\t\t{\"d-module\", \"d-module\"},\n\t\t\t{\"d-module\"},\n\t\t},\n\t}, {\n\t\tname: \"list with leafref key with shadowSchemaPaths=true\",\n\t\tinStruct: &Directory{\n\t\t\tName: \"DList\",\n\t\t\tPath: []string{\"\", \"d-module\", \"d-container\", \"d-list\"},\n\t\t\tListAttr: &YangListAttr{\n\t\t\t\tKeyElems: []*yang.Entry{\n\t\t\t\t\tfindEntry(t, ms, \"d-module\", \"d-container/d-list/config/d-key\"),\n\t\t\t\t},\n\t\t\t},\n\t\t\tFields: map[string]*yang.Entry{\n\t\t\t\t\"d-key\": findEntry(t, ms, \"d-module\", \"d-container/d-list/config/d-key\"),\n\t\t\t},\n\t\t\tShadowedFields: map[string]*yang.Entry{\n\t\t\t\t\"d-key\": findEntry(t, ms, \"d-module\", \"d-container/d-list/state/d-key\"),\n\t\t\t},\n\t\t},\n\t\tinField: \"d-key\",\n\t\tinCompressPaths: true,\n\t\tinShadowSchemaPaths: true,\n\t\twantPaths: [][]string{\n\t\t\t{\"state\", \"d-key\"},\n\t\t\t{\"d-key\"},\n\t\t},\n\t\twantModules: [][]string{\n\t\t\t{\"d-module\", \"d-module\"},\n\t\t\t{\"d-module\"},\n\t\t},\n\t}}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgotPaths, gotModules, err := findMapPaths(tt.inStruct, tt.inField, tt.inCompressPaths, tt.inShadowSchemaPaths, tt.inAbsolutePaths)\n\t\t\tif (err != nil) != tt.wantErr {\n\t\t\t\tt.Errorf(\"%s: YANGCodeGenerator.findMapPaths(%v, %v): compress: %v, shadowSchemaPaths: %v, wantErr: %v, gotPaths error: %v\",\n\t\t\t\t\ttt.name, tt.inStruct, tt.inField, tt.inCompressPaths, tt.inShadowSchemaPaths, tt.wantErr, err)\n\t\t\t}\n\t\t\tif tt.wantErr {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif diff := cmp.Diff(tt.wantPaths, gotPaths); diff != \"\" {\n\t\t\t\tt.Errorf(\"%s: YANGCodeGenerator.findMapPaths(%v, %v): compress: %v, shadowSchemaPaths: %v, (-want, +gotPaths):\\n%s\", tt.name, tt.inStruct, tt.inField, tt.inCompressPaths, tt.inShadowSchemaPaths, diff)\n\t\t\t}\n\n\t\t\tif diff := cmp.Diff(tt.wantModules, gotModules); diff != \"\" {\n\t\t\t\tt.Errorf(\"%s: YANGCodeGenerator.findMapPaths(%v, %v): compress: %v, shadowSchemaPaths: %v, (-want, +gotModules):\\n%s\", tt.name, tt.inStruct, tt.inField, tt.inCompressPaths, tt.inShadowSchemaPaths, diff)\n\t\t\t}\n\t\t})\n\t}\n}", "func guessDeps(base string, skipImport bool) *cfg.Config {\n\tbuildContext, err := util.GetBuildContext()\n\tif err != nil {\n\t\tmsg.Die(\"Failed to build an import context: %s\", err)\n\t}\n\tname := buildContext.PackageName(base)\n\n\n\tmsg.Info(\"Generating a YAML configuration file and guessing the dependencies\")\n\n\tconfig := new(cfg.Config)\n\n\t// Get the name of the top level package\n\tconfig.Name = name\n\n\t// Import by looking at other package managers and looking over the\n\t// entire directory structure.\n\n\t// Attempt to import from other package managers.\n\tif !skipImport {\n\t\tguessImportDeps(base, config)\n\t}\n\n\timportLen := len(config.Imports)\n\tif importLen == 0 {\n\t\tmsg.Info(\"Scanning code to look for dependencies\")\n\t} else {\n\t\tmsg.Info(\"Scanning code to look for dependencies not found in import\")\n\t}\n\n\t// 返回依赖解析器\n\tr, err := dependency.NewResolver(base)\n\n\n\tif err != nil {\n\t\tmsg.Die(\"Error creating a dependency resolver: %s\", err)\n\t}\n\n\t// 初始化以测试模式\n\tr.ResolveTest = true\n\n\th := &dependency.DefaultMissingPackageHandler{Missing: []string{}, Gopath: []string{}}\n\tr.Handler = h\n\n\tsortable, testSortable, err := r.ResolveLocal(false)\n\tif err != nil {\n\t\tmsg.Die(\"分析本地依赖失败: %s\", err)\n\t}\n\n\tsort.Strings(sortable)\n\tsort.Strings(testSortable)\n\n\tvpath := r.VendorDir\n\tif !strings.HasSuffix(vpath, \"/\") {\n\t\tvpath = vpath + string(os.PathSeparator)\n\t}\n\n\tfor _, pa := range sortable {\n\t\tn := strings.TrimPrefix(pa, vpath)\n\t\troot, subpkg := util.NormalizeName(n)\n\n\t\tif !config.Imports.Has(root) && root != config.Name {\n\t\t\tmsg.Info(\"--> Found reference to %s\\n\", n)\n\t\t\td := &cfg.Dependency{\n\t\t\t\tName: root,\n\t\t\t}\n\t\t\tif len(subpkg) > 0 {\n\t\t\t\td.Subpackages = []string{subpkg}\n\t\t\t}\n\t\t\tconfig.Imports = append(config.Imports, d)\n\t\t} else if config.Imports.Has(root) {\n\t\t\tif len(subpkg) > 0 {\n\t\t\t\tsubpkg = strings.TrimPrefix(subpkg, \"/\")\n\t\t\t\td := config.Imports.Get(root)\n\t\t\t\tif !d.HasSubpackage(subpkg) {\n\t\t\t\t\tmsg.Info(\"--> Adding sub-package %s to %s\\n\", subpkg, root)\n\t\t\t\t\td.Subpackages = append(d.Subpackages, subpkg)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, pa := range testSortable {\n\t\tn := strings.TrimPrefix(pa, vpath)\n\t\troot, subpkg := util.NormalizeName(n)\n\n\t\tif config.Imports.Has(root) && root != config.Name {\n\t\t\tmsg.Debug(\"--> Found test reference to %s already listed as an import\", n)\n\t\t} else if !config.DevImports.Has(root) && root != config.Name {\n\t\t\tmsg.Info(\"--> Found test reference to %s\", n)\n\t\t\td := &cfg.Dependency{\n\t\t\t\tName: root,\n\t\t\t}\n\t\t\tif len(subpkg) > 0 {\n\t\t\t\td.Subpackages = []string{subpkg}\n\t\t\t}\n\t\t\tconfig.DevImports = append(config.DevImports, d)\n\t\t} else if config.DevImports.Has(root) {\n\t\t\tif len(subpkg) > 0 {\n\t\t\t\tsubpkg = strings.TrimPrefix(subpkg, \"/\")\n\t\t\t\td := config.DevImports.Get(root)\n\t\t\t\tif !d.HasSubpackage(subpkg) {\n\t\t\t\t\tmsg.Info(\"--> Adding test sub-package %s to %s\\n\", subpkg, root)\n\t\t\t\t\td.Subpackages = append(d.Subpackages, subpkg)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(config.Imports) == importLen && importLen != 0 {\n\t\tmsg.Info(\"--> Code scanning found no additional imports\")\n\t}\n\n\treturn config\n}", "func GuessDeps(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {\n\tbuildContext, err := util.GetBuildContext()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbase := p.Get(\"dirname\", \".\").(string)\n\tskipImport := p.Get(\"skipImport\", false).(bool)\n\tname := guessPackageName(buildContext, base)\n\n\tInfo(\"Generating a YAML configuration file and guessing the dependencies\")\n\n\tconfig := new(cfg.Config)\n\n\t// Get the name of the top level package\n\tconfig.Name = name\n\n\t// Import by looking at other package managers and looking over the\n\t// entire directory structure.\n\n\t// Attempt to import from other package managers.\n\tif !skipImport {\n\t\tInfo(\"Attempting to import from other package managers (use --skip-import to skip)\")\n\t\tdeps := []*cfg.Dependency{}\n\t\tabsBase, err := filepath.Abs(base)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif d, ok := guessImportGodep(absBase); ok {\n\t\t\tInfo(\"Importing Godep configuration\")\n\t\t\tWarn(\"Godep uses commit id versions. Consider using Semantic Versions with Glide\")\n\t\t\tdeps = d\n\t\t} else if d, ok := guessImportGPM(absBase); ok {\n\t\t\tInfo(\"Importing GPM configuration\")\n\t\t\tdeps = d\n\t\t} else if d, ok := guessImportGB(absBase); ok {\n\t\t\tInfo(\"Importing GB configuration\")\n\t\t\tdeps = d\n\t\t}\n\n\t\tfor _, i := range deps {\n\t\t\tInfo(\"Found imported reference to %s\\n\", i.Name)\n\t\t\tconfig.Imports = append(config.Imports, i)\n\t\t}\n\t}\n\n\t// Resolve dependencies by looking at the tree.\n\tr, err := dependency.NewResolver(base)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th := &dependency.DefaultMissingPackageHandler{Missing: []string{}, Gopath: []string{}}\n\tr.Handler = h\n\n\tsortable, err := r.ResolveLocal(false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsort.Strings(sortable)\n\n\tvpath := r.VendorDir\n\tif !strings.HasSuffix(vpath, \"/\") {\n\t\tvpath = vpath + string(os.PathSeparator)\n\t}\n\n\tfor _, pa := range sortable {\n\t\tn := strings.TrimPrefix(pa, vpath)\n\t\troot := util.GetRootFromPackage(n)\n\n\t\tif !config.HasDependency(root) {\n\t\t\tInfo(\"Found reference to %s\\n\", n)\n\t\t\td := &cfg.Dependency{\n\t\t\t\tName: root,\n\t\t\t}\n\t\t\tsubpkg := strings.TrimPrefix(n, root)\n\t\t\tif len(subpkg) > 0 && subpkg != \"/\" {\n\t\t\t\td.Subpackages = []string{subpkg}\n\t\t\t}\n\t\t\tconfig.Imports = append(config.Imports, d)\n\t\t} else {\n\t\t\tsubpkg := strings.TrimPrefix(n, root)\n\t\t\tif len(subpkg) > 0 && subpkg != \"/\" {\n\t\t\t\tsubpkg = strings.TrimPrefix(subpkg, \"/\")\n\t\t\t\td := config.Imports.Get(root)\n\t\t\t\tf := false\n\t\t\t\tfor _, v := range d.Subpackages {\n\t\t\t\t\tif v == subpkg {\n\t\t\t\t\t\tf = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !f {\n\t\t\t\t\tInfo(\"Adding sub-package %s to %s\\n\", subpkg, root)\n\t\t\t\t\td.Subpackages = append(d.Subpackages, subpkg)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn config, nil\n}", "func TreeToFiles(r *git.Repository, t *git.Tree,\n\trepoURL string, repoCache *RepoCache) (map[FileKey]BlobLocation, map[string]git.Oid, error) {\n\tref := newRepoWalker(r, repoURL, repoCache)\n\n\tif err := ref.parseModuleMap(t); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tt.Walk(ref.cbInt)\n\tif ref.err != nil {\n\t\treturn nil, nil, ref.err\n\t}\n\treturn ref.tree, ref.subRepoVersions, nil\n}", "func LoadSwaggerV2AsV3(specPath string) *openapi3.Swagger {\n\tswaggerSpec := openapi2.Swagger{}\n\tc, err := ioutil.ReadFile(specPath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = yaml.Unmarshal(c, &swaggerSpec)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\toa3, err := openapi2conv.ToV3Swagger(&swaggerSpec)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn oa3\n}", "func getDependencies(srcDir, importPath string, dependencies map[string]map[string]bool, maxDepth int) error {\n\tif callerFunctionName(maxDepth) == callerFunctionName(0) {\n\t\treturn nil\n\t}\n\tif dependencies[importPath] != nil {\n\t\treturn nil\n\t}\n\tdependencies[importPath] = make(map[string]bool)\n\n\t// Stop if the directory doesn't exist.\n\t// It could be because it's an built-in package or the package hasn't been downloaded.\n\tdirectory := filepath.Join(srcDir, importPath)\n\tif _, err := os.Stat(directory); os.IsNotExist(err) {\n\t\treturn nil\n\t} else if err != nil {\n\t\treturn err\n\t}\n\n\tfiles, err := ioutil.ReadDir(directory)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnext := make(map[string]bool)\n\tfor _, file := range files {\n\t\tif file.IsDir() || strings.HasPrefix(file.Name(), \".\") {\n\t\t\tcontinue\n\t\t}\n\t\tfilename := file.Name()\n\t\tif filepath.Ext(filename) == \".go\" {\n\t\t\tast, err := parser.ParseFile(token.NewFileSet(), filepath.Join(directory, filename), nil, parser.ImportsOnly)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, im := range ast.Imports {\n\t\t\t\tnextImportPath := im.Path.Value\n\t\t\t\tdependencies[importPath][nextImportPath] = true\n\n\t\t\t\tnextImportPathUnquoted, err := strconv.Unquote(nextImportPath)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Println(err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tnext[nextImportPathUnquoted] = true\n\t\t\t}\n\t\t}\n\t}\n\n\tfor n := range next {\n\t\tif err := getDependencies(srcDir, n, dependencies, maxDepth); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *Manager) ResolveTree(hash string) (*backend.ResolutionTree, error) {\n\t// resolve the tree\n\tlayers, err := m.processLayers(hash)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// convert the list of hashes into a list of directories and get the manifests\n\tpaths := make(map[string]string, len(layers))\n\tmanifests := make(map[string]*schema.ImageManifest, len(layers))\n\tm.imagesLock.RLock()\n\tdefer m.imagesLock.RUnlock()\n\tfor _, layer := range layers {\n\t\tpaths[layer] = filepath.Join(m.Options.Directory, layer, \"rootfs\")\n\t\tmanifests[layer] = m.images[layer]\n\t}\n\n\treturn &backend.ResolutionTree{Order: layers, Paths: paths, Manifests: manifests}, nil\n}", "func resolveRoot(ctx context.Context, src ReadOnlyTarget, srcRef string, proxy *cas.Proxy) (ocispec.Descriptor, error) {\n\trefFetcher, ok := src.(registry.ReferenceFetcher)\n\tif !ok {\n\t\treturn src.Resolve(ctx, srcRef)\n\t}\n\n\t// optimize performance for ReferenceFetcher targets\n\trefProxy := &registryutil.Proxy{\n\t\tReferenceFetcher: refFetcher,\n\t\tProxy: proxy,\n\t}\n\troot, rc, err := refProxy.FetchReference(ctx, srcRef)\n\tif err != nil {\n\t\treturn ocispec.Descriptor{}, err\n\t}\n\tdefer rc.Close()\n\t// cache root if it is a non-leaf node\n\tfetcher := content.FetcherFunc(func(ctx context.Context, target ocispec.Descriptor) (io.ReadCloser, error) {\n\t\tif content.Equal(target, root) {\n\t\t\treturn rc, nil\n\t\t}\n\t\treturn nil, errors.New(\"fetching only root node expected\")\n\t})\n\tif _, err = content.Successors(ctx, fetcher, root); err != nil {\n\t\treturn ocispec.Descriptor{}, err\n\t}\n\n\t// TODO: optimize special case where root is a leaf node (i.e. a blob)\n\t// and dst is a ReferencePusher.\n\treturn root, nil\n}", "func DirTree(root string) ([]*pkgs.Package, error) {\n\tparseCfg := &packages.Config{\n\t\tLogf: nil, // log.Printf (for debug), nil (for release)\n\t\tDir: root,\n\t\tTests: true,\n\t\tMode: packages.NeedName | packages.NeedImports | packages.NeedSyntax,\n\t}\n\n\tpacks, err := packages.Load(parseCfg, root+\"/...\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif packages.PrintErrors(packs) > 0 {\n\t\treturn nil, errors.New(\"unable to parse packages at root: \" + root)\n\t}\n\treturn packs, nil\n}", "func getSchemaAndDirs() (*yang.Entry, map[string]*ygen.Directory, map[string]map[string]*ygen.MappedType) {\n\tschema := &yang.Entry{\n\t\tName: \"root-module\",\n\t\tKind: yang.DirectoryEntry,\n\t\tDir: map[string]*yang.Entry{\n\t\t\t\"leaf\": {\n\t\t\t\tName: \"leaf\",\n\t\t\t\tKind: yang.LeafEntry,\n\t\t\t\t// Name is given here to test setting the YANGTypeName field.\n\t\t\t\tType: &yang.YangType{Name: \"ieeefloat32\", Kind: yang.Ybinary},\n\t\t\t},\n\t\t\t\"container\": {\n\t\t\t\tName: \"container\",\n\t\t\t\tKind: yang.DirectoryEntry,\n\t\t\t\tDir: map[string]*yang.Entry{\n\t\t\t\t\t\"leaf\": {\n\t\t\t\t\t\tName: \"leaf\",\n\t\t\t\t\t\tKind: yang.LeafEntry,\n\t\t\t\t\t\tType: &yang.YangType{Name: \"int32\", Kind: yang.Yint32},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"container-with-config\": {\n\t\t\t\tName: \"container-with-config\",\n\t\t\t\tKind: yang.DirectoryEntry,\n\t\t\t\tDir: map[string]*yang.Entry{\n\t\t\t\t\t\"config\": {\n\t\t\t\t\t\tName: \"config\",\n\t\t\t\t\t\tKind: yang.DirectoryEntry,\n\t\t\t\t\t\tDir: map[string]*yang.Entry{\n\t\t\t\t\t\t\t\"leaf\": {\n\t\t\t\t\t\t\t\tName: \"leaf\",\n\t\t\t\t\t\t\t\tKind: yang.LeafEntry,\n\t\t\t\t\t\t\t\tType: &yang.YangType{Kind: yang.Ybinary},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t\"state\": {\n\t\t\t\t\t\tName: \"state\",\n\t\t\t\t\t\tKind: yang.DirectoryEntry,\n\t\t\t\t\t\tConfig: yang.TSFalse,\n\t\t\t\t\t\tDir: map[string]*yang.Entry{\n\t\t\t\t\t\t\t\"leaf\": {\n\t\t\t\t\t\t\t\tName: \"leaf\",\n\t\t\t\t\t\t\t\tKind: yang.LeafEntry,\n\t\t\t\t\t\t\t\tType: &yang.YangType{Kind: yang.Ybinary},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\"leaflist\": {\n\t\t\t\t\t\t\t\tName: \"leaflist\",\n\t\t\t\t\t\t\t\tKind: yang.LeafEntry,\n\t\t\t\t\t\t\t\tListAttr: &yang.ListAttr{},\n\t\t\t\t\t\t\t\tType: &yang.YangType{Kind: yang.Yuint32},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\"leaflist2\": {\n\t\t\t\t\t\t\t\tName: \"leaflist2\",\n\t\t\t\t\t\t\t\tKind: yang.LeafEntry,\n\t\t\t\t\t\t\t\tListAttr: &yang.ListAttr{},\n\t\t\t\t\t\t\t\tType: &yang.YangType{Kind: yang.Ybinary},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"list-container\": {\n\t\t\t\tName: \"list-container\",\n\t\t\t\tKind: yang.DirectoryEntry,\n\t\t\t\tDir: map[string]*yang.Entry{\n\t\t\t\t\t\"list\": {\n\t\t\t\t\t\tName: \"list\",\n\t\t\t\t\t\tKind: yang.DirectoryEntry,\n\t\t\t\t\t\tListAttr: &yang.ListAttr{},\n\t\t\t\t\t\tDir: map[string]*yang.Entry{\n\t\t\t\t\t\t\t\"key1\": {\n\t\t\t\t\t\t\t\tName: \"key1\",\n\t\t\t\t\t\t\t\tKind: yang.LeafEntry,\n\t\t\t\t\t\t\t\tType: &yang.YangType{Kind: yang.Ystring},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\"key2\": {\n\t\t\t\t\t\t\t\tName: \"key2\",\n\t\t\t\t\t\t\t\tKind: yang.LeafEntry,\n\t\t\t\t\t\t\t\tType: &yang.YangType{Kind: yang.Ybinary},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\"union-key\": {\n\t\t\t\t\t\t\t\tName: \"union-key\",\n\t\t\t\t\t\t\t\tType: &yang.YangType{\n\t\t\t\t\t\t\t\t\tKind: yang.Yunion,\n\t\t\t\t\t\t\t\t\tType: []*yang.YangType{{\n\t\t\t\t\t\t\t\t\t\tName: \"enumeration\",\n\t\t\t\t\t\t\t\t\t\tKind: yang.Yenum,\n\t\t\t\t\t\t\t\t\t\tEnum: &yang.EnumType{},\n\t\t\t\t\t\t\t\t\t}, {\n\t\t\t\t\t\t\t\t\t\tKind: yang.Yuint32,\n\t\t\t\t\t\t\t\t\t}},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"list-container-with-state\": {\n\t\t\t\tName: \"list-container-with-state\",\n\t\t\t\tKind: yang.DirectoryEntry,\n\t\t\t\tDir: map[string]*yang.Entry{\n\t\t\t\t\t\"list-with-state\": {\n\t\t\t\t\t\tName: \"list-with-state\",\n\t\t\t\t\t\tKind: yang.DirectoryEntry,\n\t\t\t\t\t\tListAttr: &yang.ListAttr{},\n\t\t\t\t\t\tDir: map[string]*yang.Entry{\n\t\t\t\t\t\t\t\"key\": {\n\t\t\t\t\t\t\t\tName: \"key\",\n\t\t\t\t\t\t\t\tKind: yang.LeafEntry,\n\t\t\t\t\t\t\t\tType: &yang.YangType{\n\t\t\t\t\t\t\t\t\tKind: yang.Yleafref,\n\t\t\t\t\t\t\t\t\tPath: \"../state/key\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\"state\": {\n\t\t\t\t\t\t\t\tName: \"state\",\n\t\t\t\t\t\t\t\tKind: yang.DirectoryEntry,\n\t\t\t\t\t\t\t\tDir: map[string]*yang.Entry{\n\t\t\t\t\t\t\t\t\t\"key\": {\n\t\t\t\t\t\t\t\t\t\tName: \"key\",\n\t\t\t\t\t\t\t\t\t\tKind: yang.LeafEntry,\n\t\t\t\t\t\t\t\t\t\tType: &yang.YangType{Kind: yang.Ydecimal64},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tAnnotation: map[string]interface{}{\"isCompressedSchema\": true},\n\t}\n\taddParents(schema)\n\n\t// Build fake root.\n\tfakeRoot := ygen.MakeFakeRoot(\"root\")\n\tfor k, v := range schema.Dir {\n\t\tfakeRoot.Dir[k] = v\n\t}\n\n\tdirectories := map[string]*ygen.Directory{\n\t\t\"/root\": {\n\t\t\tName: \"Root\",\n\t\t\tFields: map[string]*yang.Entry{\n\t\t\t\t\"leaf\": schema.Dir[\"leaf\"],\n\t\t\t\t\"container\": schema.Dir[\"container\"],\n\t\t\t\t\"container-with-config\": schema.Dir[\"container-with-config\"],\n\t\t\t\t\"list\": schema.Dir[\"list-container\"].Dir[\"list\"],\n\t\t\t\t\"list-with-state\": schema.Dir[\"list-container-with-state\"].Dir[\"list-with-state\"],\n\t\t\t},\n\t\t\tPath: []string{\"\", \"root\"},\n\t\t\tEntry: fakeRoot,\n\t\t},\n\t\t\"/root-module/container\": {\n\t\t\tName: \"Container\",\n\t\t\tFields: map[string]*yang.Entry{\n\t\t\t\t\"leaf\": schema.Dir[\"container\"].Dir[\"leaf\"],\n\t\t\t},\n\t\t\tPath: []string{\"\", \"root-module\", \"container\"},\n\t\t\tEntry: schema.Dir[\"container\"],\n\t\t},\n\t\t\"/root-module/container-with-config\": {\n\t\t\tName: \"ContainerWithConfig\",\n\t\t\tFields: map[string]*yang.Entry{\n\t\t\t\t\"leaf\": schema.Dir[\"container-with-config\"].Dir[\"state\"].Dir[\"leaf\"],\n\t\t\t\t\"leaflist\": schema.Dir[\"container-with-config\"].Dir[\"state\"].Dir[\"leaflist\"],\n\t\t\t\t\"leaflist2\": schema.Dir[\"container-with-config\"].Dir[\"state\"].Dir[\"leaflist2\"],\n\t\t\t},\n\t\t\tPath: []string{\"\", \"root-module\", \"container-with-config\"},\n\t\t\tEntry: schema.Dir[\"container-with-config\"],\n\t\t},\n\t\t\"/root-module/list-container/list\": {\n\t\t\tName: \"List\",\n\t\t\tListAttr: &ygen.YangListAttr{\n\t\t\t\tKeys: map[string]*ygen.MappedType{\n\t\t\t\t\t\"key1\": {NativeType: \"string\"},\n\t\t\t\t\t\"key2\": {NativeType: \"Binary\"},\n\t\t\t\t\t\"union-key\": {NativeType: \"RootModule_List_UnionKey_Union\", UnionTypes: map[string]int{\"string\": 0, \"Binary\": 1}},\n\t\t\t\t},\n\t\t\t\tKeyElems: []*yang.Entry{{Name: \"key1\"}, {Name: \"key2\"}, {Name: \"union-key\"}},\n\t\t\t},\n\t\t\tFields: map[string]*yang.Entry{\n\t\t\t\t\"key1\": schema.Dir[\"list-container\"].Dir[\"list\"].Dir[\"key1\"],\n\t\t\t\t\"key2\": schema.Dir[\"list-container\"].Dir[\"list\"].Dir[\"key2\"],\n\t\t\t\t\"union-key\": schema.Dir[\"list-container\"].Dir[\"list\"].Dir[\"union-key\"],\n\t\t\t},\n\t\t\tPath: []string{\"\", \"root-module\", \"list-container\", \"list\"},\n\t\t\tEntry: schema.Dir[\"list-container\"],\n\t\t},\n\t\t\"/root-module/list-container-with-state/list-with-state\": {\n\t\t\tName: \"ListWithState\",\n\t\t\tListAttr: &ygen.YangListAttr{\n\t\t\t\tKeys: map[string]*ygen.MappedType{\n\t\t\t\t\t\"key\": {NativeType: \"float64\"},\n\t\t\t\t},\n\t\t\t\tKeyElems: []*yang.Entry{{Name: \"key\"}},\n\t\t\t},\n\t\t\tFields: map[string]*yang.Entry{\n\t\t\t\t\"key\": schema.Dir[\"list-container-with-state\"].Dir[\"list-with-state\"].Dir[\"key\"],\n\t\t\t},\n\t\t\tPath: []string{\"\", \"root-module\", \"list-container-with-state\", \"list-with-state\"},\n\t\t\tEntry: schema.Dir[\"list-container-with-state\"],\n\t\t},\n\t}\n\n\tleafTypeMap := map[string]map[string]*ygen.MappedType{\n\t\t\"/root\": {\n\t\t\t\"leaf\": {NativeType: \"Binary\"},\n\t\t\t\"container\": nil,\n\t\t\t\"container-with-config\": nil,\n\t\t\t\"list\": nil,\n\t\t\t\"list-with-state\": nil,\n\t\t},\n\t\t\"/root-module/container\": {\n\t\t\t\"leaf\": {NativeType: \"int32\"},\n\t\t},\n\t\t\"/root-module/container-with-config\": {\n\t\t\t\"leaf\": {NativeType: \"Binary\"},\n\t\t\t\"leaflist\": {NativeType: \"uint32\"},\n\t\t\t\"leaflist2\": {NativeType: \"Binary\"},\n\t\t},\n\t\t\"/root-module/list-container/list\": {\n\t\t\t\"key1\": {NativeType: \"string\"},\n\t\t\t\"key2\": {NativeType: \"Binary\"},\n\t\t\t\"union-key\": {NativeType: \"RootModule_List_UnionKey_Union\", UnionTypes: map[string]int{\"string\": 0, \"Binary\": 1}},\n\t\t},\n\t\t\"/root-module/list-container-with-state/list-with-state\": {\n\t\t\t\"key\": {NativeType: \"float64\"},\n\t\t},\n\t}\n\n\treturn schema, directories, leafTypeMap\n}", "func (resolver *NpmResolver) ParsePkgFile(pkgFile string) (*Package, error) {\n\tcontent, err := ioutil.ReadFile(pkgFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar packageInfo Package\n\tif err := json.Unmarshal(content, &packageInfo); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &packageInfo, nil\n}", "func (c APIClient) Walk(repoName string, commitID string, path string, walkFn WalkFn) error {\n\tfileInfo, err := c.InspectFile(repoName, commitID, path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := walkFn(fileInfo); err != nil {\n\t\treturn err\n\t}\n\tfor _, childPath := range fileInfo.Children {\n\t\tif err := c.Walk(repoName, commitID, filepath.Join(path, childPath), walkFn); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func DecodeRootMetadata(codec kbfscodec.Codec, tlfID tlf.ID,\n\tver, max MetadataVer, buf []byte) (MutableRootMetadata, error) {\n\trmd, err := makeMutableRootMetadataForDecode(codec, tlfID, ver, max, buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := codec.Decode(buf, rmd); err != nil {\n\t\treturn nil, err\n\t}\n\tif ver < ImplicitTeamsVer && tlfID.Type() != tlf.SingleTeam &&\n\t\trmd.TypeForKeying() == tlf.TeamKeying {\n\t\treturn nil, errors.Errorf(\n\t\t\t\"Can't make an implicit teams TLF with version %s\", ver)\n\t}\n\treturn rmd, nil\n}", "func GetRoot(authToken string) (*http.Response, *Root, error) {\n\n apiDef := &api{method: \"GET\", endpoint: \"/root\", authToken: authToken}\n resp, body, err := proxyRequest(apiDef)\n if err != nil {\n return nil, nil, err\n }\n\n r := new(Root)\n err = json.Unmarshal(body, &r)\n if err != nil {\n return nil, nil, err\n }\n\n return resp, r, nil\n}", "func Read(filename string) (deps DependencyMap, err error) {\n\tdeps.Map = make(map[string]*Dependency)\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(data, &deps.Map)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// traverse map and look for empty version fields - provide a default if such found\n\tfor key := range deps.Map {\n\t\tval := deps.Map[key]\n\t\tif val.Version == \"\" {\n\t\t\tswitch val.Type {\n\t\t\tcase TypeGit, TypeGitClone:\n\t\t\t\tval.Version = \"master\"\n\t\t\tcase TypeHg:\n\t\t\t\tval.Version = \"tip\"\n\t\t\tcase TypeBzr:\n\t\t\t\tval.Version = \"trunk\"\n\t\t\tdefault:\n\t\t\t\tval.Version = \"\"\n\t\t\t}\n\t\t\tdeps.Map[key] = val\n\t\t}\n\t}\n\n\tfor name, d := range deps.Map {\n\t\terr := d.SetupVCS(name)\n\t\tif err != nil {\n\t\t\tdelete(deps.Map, name)\n\t\t}\n\n\t}\n\n\tdeps.Path = filename\n\n\treturn\n}", "func ParseGomodFile(b []byte) ([]string, error) {\n\tvar requiredModules []string\n\n\tgoModFile, err := modfile.Parse(\"\", b, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, req := range goModFile.Require {\n\t\tif !strings.Contains(req.Syntax.Token[0], \"golang.org\") { //filtering golang x std packages\n\t\t\trequiredModules = append(requiredModules, req.Syntax.Token[0])\n\t\t}\n\t}\n\t// fmt.Println(goModFile.Require)\n\n\treturn requiredModules, nil\n}", "func (u *PathRoot) UnmarshalJSON(body []byte) error {\n\ttype wrap struct {\n\t\tdropbox.Tagged\n\t\t// Root : Paths are relative to the authenticating user's root namespace\n\t\t// (This results in `PathRootError.invalid_root` if the user's root\n\t\t// namespace has changed.).\n\t\tRoot string `json:\"root,omitempty\"`\n\t\t// NamespaceId : Paths are relative to given namespace id (This results\n\t\t// in `PathRootError.no_permission` if you don't have access to this\n\t\t// namespace.).\n\t\tNamespaceId string `json:\"namespace_id,omitempty\"`\n\t}\n\tvar w wrap\n\tvar err error\n\tif err = json.Unmarshal(body, &w); err != nil {\n\t\treturn err\n\t}\n\tu.Tag = w.Tag\n\tswitch u.Tag {\n\tcase \"root\":\n\t\tu.Root = w.Root\n\n\tcase \"namespace_id\":\n\t\tu.NamespaceId = w.NamespaceId\n\n\t}\n\treturn nil\n}", "func DepthFirstSearch(root string, currentBuildNode NodeState, nodeMap map[string]NodeState) ([]string, error) {\n\n\tcurrentNodeData := currentBuildNode.NodeData\n\t// set Processing equal to true until all it's dependencies are not executed\n\tcurrentBuildNode.Processing = true\n\tnodeMap[currentNodeData.Location + currentNodeData.RuleName] = currentBuildNode\n\n\tvar dependentFiles []string\n\tfor file := range currentNodeData.Files {\n\t\tdependentFiles = append(dependentFiles, currentNodeData.Location + file)\n\t}\n\n\tfor dependencyName := range currentNodeData.Dependency {\n\n\t\tdependencyNode, FoundDependency := nodeMap[currentNodeData.Location + dependencyName]\n\t\tif FoundDependency == true {\n\n\t\t\t// If dependency is already in a processing state then it's a circular dependency\n\t\t\tif dependencyNode.Processing == true {\n\t\t\t\terr := \"Error: Circular dependency detected between \" + currentNodeData.RuleName + \" and \" + dependencyName\n\t\t\t\treturn dependentFiles, errors.New(err)\n\t\t\t} else if dependencyNode.Executed == false {\n\t\t\t\tdelete(nodeMap, dependencyName)\n\t\t\t\tfiles, err := DepthFirstSearch(root, dependencyNode, nodeMap)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn dependentFiles, err\n\t\t\t\t}\n\n\t\t\t\tfor _, file := range files {\n\t\t\t\t\tdependentFiles = append(dependentFiles, file)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tcmd := exec.Command(\"bash\", \"-c\", currentBuildNode.NodeData.Command)\n\t// Executing command from this directory\n\tcmd.Dir = root + currentBuildNode.NodeData.Location\n\t_, err := cmd.Output()\n\tif err != nil {\n\t\treturn dependentFiles, err\n\t}\n\n\tdelete(nodeMap, currentNodeData.Location + currentNodeData.RuleName)\n\tcurrentBuildNode.Processing = false\n\tcurrentBuildNode.Executed = true\n\tnodeMap[currentNodeData.Location + currentNodeData.RuleName] = currentBuildNode\n\treturn dependentFiles, nil\n}", "func GenerateModels(targetFilepath string, configFilepath string, rootDir string, specs map[string]MagmaSwaggerSpec) error {\n\tabsTargetFilepath, err := filepath.Abs(targetFilepath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"target filepath %s is invalid: %w\", targetFilepath, err)\n\t}\n\n\ttmpGenDir, err := ioutil.TempDir(\".\", \"tmpgen\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not create temporary gen directory: %w\", err)\n\t}\n\tdefer os.RemoveAll(tmpGenDir)\n\n\t// For each dependency, strip the magma-gen-meta and write the result to\n\t// the filename specified by `dependent-filename`\n\terr = StripAndWriteSwaggerSpecs(specs, tmpGenDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Shell out to go-swagger\n\ttargetSpec := specs[absTargetFilepath]\n\toutputDir := filepath.Join(rootDir, targetSpec.MagmaGenMeta.OutputDir)\n\tabsConfigFilepath, err := filepath.Abs(configFilepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd := exec.Command(\n\t\t\"swagger\", \"generate\", \"model\",\n\t\t\"--spec\", filepath.Join(tmpGenDir, targetSpec.MagmaGenMeta.TempGenFilename),\n\t\t\"--target\", outputDir,\n\t\t\"--config-file\", absConfigFilepath,\n\t)\n\tstdoutBuf := &strings.Builder{}\n\tstderrBuf := &strings.Builder{}\n\tcmd.Stdout = stdoutBuf\n\tcmd.Stderr = stderrBuf\n\n\terr = cmd.Run()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to generate models; stdout:\\n%s\\nstderr:\\n%s: %w\", stdoutBuf.String(), stderrBuf.String(), err)\n\t}\n\n\treturn nil\n}", "func BuildTree(values []change.ConfigValue, pretty bool) ([]byte, error) {\n\tvar buf bytes.Buffer\n\n\troot := Node{Name: \"(root)\", Children: make([]*Node, 0), Leaves: make([]*Leaf, 0)}\n\n\tfor _, cv := range values {\n\t\taddPathToTree(cv.Path, cv.Value, &root)\n\t}\n\n\tjsonifyNodes(&root, &buf, pretty, 1)\n\treturn buf.Bytes(), nil\n}", "func (self *SassDependencyResolver) Resolve(path string) ([]string, error) {\n\tabs, err := filepath.Abs(path)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdeps, ok := self.deepDeps[abs]\n\n\tif ok {\n\t\treturn deps, nil\n\t}\n\n\tscanned := make(map[string]bool, 100)\n\tunscanned := make(map[string]bool, 100)\n\tunscanned[abs] = true\n\n\tfor len(unscanned) > 0 {\n\t\tfor subpath := range unscanned {\n\t\t\t// Move the file to scanned\n\t\t\tdelete(unscanned, subpath)\n\t\t\tscanned[subpath] = true\n\n\t\t\t// Get the dependencies or read them if needed\n\t\t\tdeps, err := self.shallowResolve(subpath)\n\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t// Add the dependency to unscanned if it hasn't been scanned\n\t\t\t// already\n\t\t\tfor _, dep := range deps {\n\t\t\t\t_, ok = scanned[dep]\n\n\t\t\t\tif !ok {\n\t\t\t\t\tunscanned[dep] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdeps = make([]string, 0, len(scanned))\n\n\tfor dep := range scanned {\n\t\tif dep != abs {\n\t\t\tdeps = append(deps, dep)\n\t\t}\n\t}\n\n\tself.deepDeps[abs] = deps\n\treturn deps, nil\n}", "func protoGoRuntimeLibraryToGoRuntimeDependency(config *registryv1alpha1.GoConfig_RuntimeLibrary) *bufpluginconfig.GoRegistryDependencyConfig {\n\treturn &bufpluginconfig.GoRegistryDependencyConfig{\n\t\tModule: config.Module,\n\t\tVersion: config.Version,\n\t}\n}", "func (d *Graph) buildTree() {\n\tconfig := build.Default\n\n\t// For each package, look for the dependencies and build out a tree\n\tfor p := range d.Pkgs {\n\t\tpkg, _ := config.Import(d.Pkgs[p], d.SrcDir, build.AllowBinary)\n\t\timports := pkg.Imports\n\n\t\t// Iterate through the imports and build our tree\n\t\tfor i := range imports {\n\t\t\t// The full path of our current import\n\t\t\tpath := imports[i]\n\n\t\t\t// When dealing with multiple packages, we can't assume that imports\n\t\t\t// are unique. Thus the nodes may already exist and we shouldn't do any work\n\t\t\tif d.Nodes[path] != nil {\n\t\t\t\td.Nodes[path].IsDuplicate = true\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Ignore the GO standard library imports\n\t\t\tif _, ok := stdlib[strings.Split(path, \"/\")[0]]; ok && !d.StdLib {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Keep track when traversing the path\n\t\t\tvar currentNode = &Node{\n\t\t\t\tPath: path,\n\t\t\t\tIsDep: true,\n\t\t\t\tIsCoreDep: strings.HasPrefix(path, strings.Split(d.Pkgs[p], \"/\")[0]),\n\t\t\t}\n\n\t\t\t// Keep track of the number of dependencies\n\t\t\td.TotalDeps++\n\n\t\t\t// Link our dependency node to its ancestors\n\t\t\tfor path != \"\" {\n\t\t\t\t// Constant time lookup to all of our nodes\n\t\t\t\t// based on their full path string\n\t\t\t\td.Nodes[path] = currentNode\n\n\t\t\t\t// Keep popping off the tip of the path\n\t\t\t\tpath, _ = filepath.Split(path)\n\n\t\t\t\tif len(path) > 0 {\n\t\t\t\t\t// Trailing slash in file path causes issues, remove it\n\t\t\t\t\tif strings.HasSuffix(path, \"/\") {\n\t\t\t\t\t\tpath = path[:len(path)-1]\n\t\t\t\t\t}\n\n\t\t\t\t\t// Create nodes for all directory paths if they don't exist\n\t\t\t\t\tif d.Nodes[path] == nil {\n\t\t\t\t\t\tcurrentNode.addParent(&Node{\n\t\t\t\t\t\t\tPath: path,\n\t\t\t\t\t\t})\n\n\t\t\t\t\t\t// Change the current node to the newly created item\n\t\t\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Otherwise, assume the common ancestor already has it's tree built\n\t\t\t\t\t\tcurrentNode.addParent(d.Nodes[path])\n\t\t\t\t\t\tcurrentNode = nil\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// currentNode will be nil if there was already a common ancestor --\n\t\t\t// which means the root node already exists for that import path\n\t\t\tif currentNode != nil {\n\t\t\t\td.RootNode.addChild(currentNode)\n\t\t\t}\n\t\t}\n\t}\n}", "func YAMLRemoteRefParser(path string, b []byte) (*RemoteRef, error) {\n\tvar maybeRef struct {\n\t\tRemote *string `yaml:\"remote\"`\n\t\tPath string `yaml:\"path\"`\n\t\tRef string `yaml:\"ref\"`\n\t}\n\n\tif err := yaml.UnmarshalStrict(b, &maybeRef); err != nil {\n\t\t// assume errors mean this isn't a remote config\n\t\treturn nil, nil\n\t}\n\tif maybeRef.Remote == nil {\n\t\treturn nil, nil\n\t}\n\n\tref := RemoteRef{\n\t\tRemote: *maybeRef.Remote,\n\t\tPath: maybeRef.Path,\n\t\tRef: maybeRef.Ref,\n\t}\n\tif ref.Remote == \"\" {\n\t\treturn nil, errors.New(\"invalid remote reference: empty \\\"remote\\\" field\")\n\t}\n\treturn &ref, nil\n}", "func dependencyBlocksToModuleDependencies(decodedDependencyBlocks []Dependency) *ModuleDependencies {\n\tif len(decodedDependencyBlocks) == 0 {\n\t\treturn nil\n\t}\n\n\tpaths := []string{}\n\tfor _, decodedDependencyBlock := range decodedDependencyBlocks {\n\t\tconfigPath := decodedDependencyBlock.ConfigPath\n\t\tif util.IsFile(configPath) && filepath.Base(configPath) == DefaultTerragruntConfigPath {\n\t\t\t// dependencies system expects the directory containing the terragrunt.hcl file\n\t\t\tconfigPath = filepath.Dir(configPath)\n\t\t}\n\t\tpaths = append(paths, configPath)\n\t}\n\treturn &ModuleDependencies{Paths: paths}\n}", "func ParseDockerRef(dockerRef string) (string, string) {\n\trepoName, tag := parsers.ParseRepositoryTag(dockerRef)\n\n\tif len(tag) == 0 {\n\t\ttag = \"latest\"\n\t}\n\n\treturn repoName, tag\n}", "func GetStructsInFile(filePath string) (*loader.PackageInfo, ParsedStructs, error) {\n\tabsFilePath, err := filepath.Abs(filePath)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"can't get abs path for %s\", filePath)\n\t}\n\n\tneededStructs, err := getStructNamesInFile(absFilePath)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"can't get struct names: %s\", err)\n\t}\n\n\tpackageFullName := fileNameToPkgName(filePath, absFilePath)\n\tlprog, err := loadProgramFromPackage(packageFullName)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpkgInfo := lprog.Package(packageFullName)\n\tif pkgInfo == nil {\n\t\treturn nil, nil, fmt.Errorf(\"can't load types for file %s in package %q\",\n\t\t\tfilePath, packageFullName)\n\t}\n\n\tret := ParsedStructs{}\n\n\tscope := pkgInfo.Pkg.Scope()\n\tfor _, name := range scope.Names() {\n\t\tobj := scope.Lookup(name)\n\n\t\tif neededStructs[name] == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tt := obj.Type().(*types.Named)\n\t\ts := t.Underlying().(*types.Struct)\n\n\t\tparsedStruct := parseStruct(s, neededStructs[name])\n\t\tif parsedStruct != nil {\n\t\t\tret[name] = *parsedStruct\n\t\t}\n\t}\n\n\treturn pkgInfo, ret, nil\n}", "func SchemaDescriptor() (interface{}, error) {\n\tzr, err := gzip.NewReader(bytes.NewReader(fileDescriptor))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar buf bytes.Buffer\n\t_, err = buf.ReadFrom(zr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar v interface{}\n\tif err := json.NewDecoder(bytes.NewReader(buf.Bytes())).Decode(&v); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn v, nil\n}", "func SchemaDescriptor() (interface{}, error) {\n\tzr, err := gzip.NewReader(bytes.NewReader(fileDescriptor))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar buf bytes.Buffer\n\t_, err = buf.ReadFrom(zr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar v interface{}\n\tif err := json.NewDecoder(bytes.NewReader(buf.Bytes())).Decode(&v); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn v, nil\n}", "func (d *galleryDocument) Dependencies() map[string]struct{} {\n\treturn map[string]struct{}{tmplPathToName(galTmplPath): {}}\n}", "func (tree *Tree) ConstructTree(details *pb.MetricDetailsResponse) error {\n\talreadyVisited := []*caching.Node{}\n\troot, err := tree.GetNode(tree.RootName)\n\tif err != nil {\n\t\treturn err\n\t}\n\t//cycles on all the metrics of the details response.\n\t//For each metric it splits the metric name into dot separated elements. Each\n\t//element will represent a node in the tree structure.\n\t//\n\t//All the nodes will have initial Size = 0\n\tfor metric, data := range details.Metrics {\n\t\tparts := strings.Split(metric, \".\")\n\t\tleafIndex := len(parts) - 1\n\n\t\talreadyVisited = []*caching.Node{root}\n\n\t\tfor currentIndex := 0; currentIndex <= leafIndex; currentIndex++ {\n\t\t\tcurrentName := strings.Join(parts[0:currentIndex+1], \".\")\n\t\t\tif val, _ := tree.GetNodeFromRoot(currentName); val != nil {\n\t\t\t\talreadyVisited = append(alreadyVisited, val)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif currentIndex == leafIndex {\n\t\t\t\tfor index, node := range alreadyVisited {\n\t\t\t\t\tif index != len(alreadyVisited)-1 {\n\t\t\t\t\t\tnode.Leaf = false\n\t\t\t\t\t}\n\t\t\t\t\tnode.Size += data.Size_\n\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcurrentNode := &caching.Node{\n\t\t\t\tName: tree.RootName + \".\" + currentName,\n\t\t\t\tChildren: []*caching.Node{},\n\t\t\t\tLeaf: true,\n\t\t\t\tSize: int64(0),\n\t\t\t}\n\n\t\t\ttree.AddNode(currentName, currentNode)\n\t\t\ttree.AddChild(alreadyVisited[len(alreadyVisited)-1], currentNode)\n\n\t\t\talreadyVisited = append(alreadyVisited, currentNode)\n\t\t}\n\t}\n\n\treturn nil\n}", "func FindAppDependencies(path string) (Dependencies, error) {\n\tapp, appOK, appErr := FindApp(path)\n\tif appErr != nil {\n\t\treturn Dependencies{}, appErr\n\t}\n\tif !appOK {\n\t\treturn Dependencies{}, nil\n\t}\n\n\trootDir := filepath.Join(app.RootDir, NameFunctions)\n\n\tarchives, archivesErr := filepath.Glob(filepath.Join(rootDir, nameNodeModules+\"*\"))\n\tif archivesErr != nil {\n\t\treturn Dependencies{}, archivesErr\n\t}\n\tif len(archives) == 0 {\n\t\treturn Dependencies{}, fmt.Errorf(\"node_modules archive not found at '%s'\", rootDir)\n\t}\n\n\tarchivePath, archivePathErr := filepath.Abs(archives[0])\n\tif archivePathErr != nil {\n\t\treturn Dependencies{}, archivePathErr\n\t}\n\n\treturn Dependencies{rootDir, archivePath}, nil\n}", "func FindAndParseTemplates(rootDir, ext string, funcMap template.FuncMap) (*template.Template, error) {\n\tcleanRoot := filepath.Clean(rootDir)\n\tpfx := len(cleanRoot) + 1\n\troot := template.New(\"\")\n\n\terr := filepath.Walk(cleanRoot, func(path string, info os.FileInfo, e1 error) error {\n\t\tif !info.IsDir() && strings.HasSuffix(path, ext) {\n\t\t\tif e1 != nil {\n\t\t\t\treturn e1\n\t\t\t}\n\n\t\t\tb, e2 := ioutil.ReadFile(path)\n\t\t\tif e2 != nil {\n\t\t\t\treturn e2\n\t\t\t}\n\n\t\t\tname := path[pfx:]\n\t\t\tt := root.New(name).Funcs(funcMap)\n\t\t\t_, e2 = t.Parse(string(b))\n\t\t\tif e2 != nil {\n\t\t\t\treturn e2\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn root, err\n}", "func Initialize(basePath string) error {\n log(dtalog.DBG, \"Initialize(%q) called\", basePath)\n dir, err := os.Open(basePath)\n if err != nil {\n log(dtalog.ERR, \"Initialize(%q): error opening directory for read: %s\",\n basePath, err)\n return err\n }\n \n filez, err := dir.Readdirnames(0)\n if err != nil {\n log(dtalog.ERR, \"Initialize(%q): error reading from directory: %s\",\n basePath, err)\n dir.Close()\n return err\n }\n dir.Close()\n \n Paths = make([]string, 0, len(filez))\n Limbo = make(map[string]*string)\n \n for _, fname := range filez {\n pth := filepath.Join(basePath, fname)\n f, err := os.Open(pth)\n if err != nil {\n log(dtalog.WRN, \"Initialize(): error opening file %q: %s\", pth, err)\n continue\n }\n defer f.Close()\n log(dtalog.DBG, \"Initialize(): reading file %q\", pth)\n \n Paths = append(Paths, pth)\n cur_ptr := &(Paths[len(Paths)-1])\n \n dcdr := json.NewDecoder(f)\n var raw interface{}\n var raw_slice []interface{}\n var i ref.Interface\n var idx string\n for dcdr.More() {\n err = dcdr.Decode(&raw)\n if err != nil {\n log(dtalog.WRN, \"Initialize(): error decoding from file %q: %s\",\n pth, err)\n continue\n }\n raw_slice = raw.([]interface{})\n if len(raw_slice) < 2 {\n log(dtalog.WRN, \"Initialize(): in file %q: slice too short: %q\",\n pth, raw_slice)\n continue\n }\n \n idx = raw_slice[0].(string)\n i = ref.Deref(idx)\n if i == nil {\n Limbo[idx] = cur_ptr\n } else {\n i.(Interface).SetDescPage(cur_ptr)\n }\n }\n }\n return nil\n}", "func Unmarshal(xmlPath string) (*MetaLib, error) {\n\tdata, err := ioutil.ReadFile(xmlPath)\n\tif err != nil {\n\t\tlogrus.WithError(err).Panic(\"tlogBaseService 加载 tlog.xml 失败\")\n\t\treturn nil, err\n\t}\n\tv := MetaLib{}\n\terr = xml.Unmarshal(data, &v)\n\tif err != nil {\n\t\tlogrus.WithError(err).Panic(\"tlogBaseService 解析 tlog.xml 失败\")\n\t\treturn nil, err\n\t}\n\n\tfor _, s := range v.Structs {\n\t\ts.init()\n\t}\n\n\treturn &v, nil\n}", "func parseRef(k8sRef string) (string, string, error) {\n\ts := strings.Split(strings.TrimPrefix(k8sRef, keyReference), \"/\")\n\tif len(s) != 2 {\n\t\treturn \"\", \"\", errors.New(\"kubernetes specification should be in the format k8s://<namespace>/<secret>\")\n\t}\n\treturn s[0], s[1], nil\n}", "func GetFileInfo(inputPath string) (string, []string, error) {\n\tfset := token.NewFileSet()\n\n\tf, err := parser.ParseFile(fset, inputPath, nil, 0)\n\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\tpackageName := f.Name.String()\n\tstructs := []string{}\n\n\tfor name, obj := range f.Scope.Objects {\n\t\tif obj.Kind == ast.Typ {\n\t\t\tts, ok := obj.Decl.(*ast.TypeSpec)\n\t\t\tif !ok {\n\t\t\t\treturn \"\", nil, fmt.Errorf(\"Unknown type without TypeSpec: %v\", obj)\n\t\t\t}\n\n\t\t\t_, ok = ts.Type.(*ast.StructType)\n\t\t\tif !ok {\n\t\t\t\t// Not a struct, so skip it\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tstructs = append(structs, name)\n\t\t}\n\t}\n\n\treturn packageName, structs, nil\n}", "func DependencySort(ks []HelmRelease) ([]HelmRelease, error) {\n\tn := make(graph)\n\tlookup := map[string]*HelmRelease{}\n\tfor i := 0; i < len(ks); i++ {\n\t\tn[ks[i].Name] = after(ks[i].Spec.DependsOn)\n\t\tlookup[ks[i].Name] = &ks[i]\n\t}\n\tsccs := tarjanSCC(n)\n\tvar sorted []HelmRelease\n\tvar unsortable CircularDependencyError\n\tfor i := 0; i < len(sccs); i++ {\n\t\ts := sccs[i]\n\t\tif len(s) != 1 {\n\t\t\tunsortable = append(unsortable, s)\n\t\t\tcontinue\n\t\t}\n\t\tif k, ok := lookup[s[0]]; ok {\n\t\t\tsorted = append(sorted, *k.DeepCopy())\n\t\t}\n\t}\n\tif unsortable != nil {\n\t\tfor i, j := 0, len(unsortable)-1; i < j; i, j = i+1, j-1 {\n\t\t\tunsortable[i], unsortable[j] = unsortable[j], unsortable[i]\n\t\t}\n\t\treturn nil, unsortable\n\t}\n\treturn sorted, nil\n}", "func parseFiles(files []string) (*parser.Namespace, [][]schema.QualifiedName, error) {\n\tvar fileDefinitions [][]schema.QualifiedName\n\tns := parser.NewNamespace(false)\n\tfor _, f := range files {\n\t\tdata, err := os.ReadFile(f)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tvar definitions []schema.QualifiedName\n\t\t// Make a new namespace just for this file only\n\t\t// so we can tell which names are defined in this\n\t\t// file alone.\n\t\tsingleNS := parser.NewNamespace(false)\n\t\tavroType, err := singleNS.TypeForSchema(data)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"invalid schema in %s: %v\", f, err)\n\t\t}\n\t\tif _, ok := avroType.(*schema.Reference); !ok {\n\t\t\t// The schema doesn't have a top-level name.\n\t\t\t// TODO how should we cope with a schema that's not\n\t\t\t// a definition? In that case we don't have\n\t\t\t// a name for the type, and we may not be able to define\n\t\t\t// methods on it because it might be a union type which\n\t\t\t// is represented by an interface type in Go.\n\t\t\t// See https://github.com/heetch/avro/issues/13\n\t\t\treturn nil, nil, fmt.Errorf(\"cannot generate code for schema %q which hasn't got a name (%T)\", f, avroType)\n\t\t}\n\t\tfor name, def := range singleNS.Definitions {\n\t\t\tif name != def.AvroName() {\n\t\t\t\t// It's an alias, so ignore it.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdefinitions = append(definitions, name)\n\t\t}\n\t\t// Sort the definitions so we get deterministic output.\n\t\t// TODO sort topologically so we get top level definitions\n\t\t// before lower level definitions.\n\t\tsort.Slice(definitions, func(i, j int) bool {\n\t\t\treturn definitions[i].String() < definitions[j].String()\n\t\t})\n\t\tfileDefinitions = append(fileDefinitions, definitions)\n\t\t// Parse the schema again but use the global namespace\n\t\t// this time so all the schemas can share the same definitions.\n\t\tif _, err := ns.TypeForSchema(data); err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"cannot parse schema in %s: %v\", f, err)\n\t\t}\n\t}\n\t// Now we've accumulated all the available types,\n\t// resolve the names with respect to the complete\n\t// namespace.\n\tfor name, def := range ns.Roots {\n\t\tif err := resolver.ResolveDefinition(def, ns.Definitions); err != nil {\n\t\t\t// TODO find out which file(s) the definition came from\n\t\t\t// and include that file name in the error.\n\t\t\treturn nil, nil, fmt.Errorf(\"cannot resolve reference %q: %v\", name, err)\n\t\t}\n\t}\n\treturn ns, fileDefinitions, nil\n}", "func (KubeAPIs KubernetesAPIs) PopulateKubeAPIMap(config *rest.Config, swaggerfile string) (err error) {\n\n\t// Open our jsonFile\n\tjsonFile, err := os.Open(swaggerfile)\n\t// if we os.Open returns an error then handle it\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// read our opened xmlFile as a byte array.\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\n\terr = jsonFile.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(byteValue, &definitionsMap)\n\tif err != nil {\n\t\tfmt.Println(\"Error parsing the JSON, file might me invalid\")\n\t\treturn err\n\t}\n\n\tdefinitions := definitionsMap[\"definitions\"].(map[string]interface{})\n\n\tfor _, value := range definitions {\n\t\tval := value.(map[string]interface{})\n\t\tif kubeapivalue, valid := getKubeAPIValues(val, config); valid {\n\t\t\tvar name string\n\t\t\tif kubeapivalue.group != \"\" {\n\t\t\t\tname = fmt.Sprintf(\"%s/%s/%s\", kubeapivalue.group, kubeapivalue.version, kubeapivalue.name)\n\t\t\t} else {\n\t\t\t\tname = fmt.Sprintf(\"%s/%s\", kubeapivalue.version, kubeapivalue.name)\n\t\t\t}\n\t\t\tKubeAPIs[name] = kubeapivalue\n\t\t}\n\t}\n\treturn nil\n}", "func (g *Generator) ParseFileMap(dir, data string) error {\n\t// Parse the template data.\n\tt, err := template.New(\"\").Funcs(Preload).Parse(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Execute the template.\n\tbuf := bytes.NewBuffer(nil)\n\terr = t.Execute(buf, g.request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Parse the filemap.\n\tg.FileMap.Dir = dir\n\terr = xml.Unmarshal(buf.Bytes(), &g.FileMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(g.FileMap.Generate) == 0 {\n\t\treturn errors.New(\"no generate elements found in file map\")\n\t}\n\treturn nil\n}", "func (o *OpenAPI3) ParseCallbacks(ctx context.Context, cbs map[string]*openapi3.CallbackRef, opts *OpenAPI3Options) (map[string][]*spec.Path, error) {\n\tspecCbs := make(map[string][]*spec.Path)\n\n\tfor cbEvent, cbRef := range cbs {\n\t\tif cbRef == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tcbPaths := make([]*spec.Path, 0, len(*cbRef.Value))\n\n\t\tfor cbURL, cb := range *cbRef.Value {\n\t\t\tspecCb, err := o.ParsePath(ctx, cb, opts)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tspecCb.PathString = cbURL\n\n\t\t\tvar ext OpenAPI3PathExtension\n\t\t\terr = o.GetExtension(opts.ExtensionName, cb.Extensions, &ext)\n\t\t\tif err != nil && err != ErrExtNotFound {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif ext.Name != nil && len(*ext.Name) != 0 {\n\t\t\t\tspecCb.Name = *ext.Name\n\t\t\t}\n\n\t\t\tcbPaths = append(cbPaths, specCb)\n\t\t}\n\n\t\tspecCbs[util.ToGoName(strings.Title(strcase.ToCamel(cbEvent)))] = cbPaths\n\t}\n\n\treturn specCbs, nil\n}", "func (m *defaultResourceManager) findMeshDependency(ctx context.Context, vr *appmesh.VirtualRouter) (*appmesh.Mesh, error) {\n\tif vr.Spec.MeshRef == nil {\n\t\treturn nil, errors.Errorf(\"meshRef shouldn't be nil, please check webhook setup\")\n\t}\n\tms, err := m.referencesResolver.ResolveMeshReference(ctx, *vr.Spec.MeshRef)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to resolve meshRef\")\n\t}\n\treturn ms, nil\n}", "func GetSwagger() (swagger *openapi3.T, err error) {\n\tvar resolvePath = PathToRawSpec(\"\")\n\n\tloader := openapi3.NewLoader()\n\tloader.IsExternalRefsAllowed = true\n\tloader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) {\n\t\tvar pathToFile = url.String()\n\t\tpathToFile = path.Clean(pathToFile)\n\t\tgetSpec, ok := resolvePath[pathToFile]\n\t\tif !ok {\n\t\t\terr1 := fmt.Errorf(\"path not found: %s\", pathToFile)\n\t\t\treturn nil, err1\n\t\t}\n\t\treturn getSpec()\n\t}\n\tvar specData []byte\n\tspecData, err = rawSpec()\n\tif err != nil {\n\t\treturn\n\t}\n\tswagger, err = loader.LoadFromData(specData)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func GetSwagger() (swagger *openapi3.T, err error) {\n\tvar resolvePath = PathToRawSpec(\"\")\n\n\tloader := openapi3.NewLoader()\n\tloader.IsExternalRefsAllowed = true\n\tloader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) {\n\t\tvar pathToFile = url.String()\n\t\tpathToFile = path.Clean(pathToFile)\n\t\tgetSpec, ok := resolvePath[pathToFile]\n\t\tif !ok {\n\t\t\terr1 := fmt.Errorf(\"path not found: %s\", pathToFile)\n\t\t\treturn nil, err1\n\t\t}\n\t\treturn getSpec()\n\t}\n\tvar specData []byte\n\tspecData, err = rawSpec()\n\tif err != nil {\n\t\treturn\n\t}\n\tswagger, err = loader.LoadFromData(specData)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func filesChangedTree(g model.TargetGraph, target model.TargetSpec, stateSet store.BuildStateSet) ([]string, error) {\n\tresult := []string{}\n\terr := g.VisitTree(target, func(current model.TargetSpec) error {\n\t\tstate := stateSet[current.ID()]\n\t\tresult = append(result, state.FilesChanged()...)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn sliceutils.DedupedAndSorted(result), nil\n}", "func (rmc *RMakeConf) MakeDepTree() (*rmake.DepTreeNode, error) {\n\tjobbyout := make(map[string]*rmake.Job)\n\tfor _,j := range rmc.Jobs {\n\t\tjobbyout[j.Output] = j\n\t}\n\n\tfinal,ok := jobbyout[rmc.Output]\n\tif !ok {\n\t\treturn nil,fmt.Errorf(\"Could not find job for final output.\")\n\t}\n\tdelete(jobbyout, rmc.Output)\n\n\tfi := make(map[string]bool)\n\tfor _,f := range rmc.Files {\n\t\tfi[f.Path] = true\n\t}\n\troot := new(rmake.DepTreeNode)\n\troot.Result = rmc.Output\n\troot.Type = rmake.TBuild\n\terr := root.Build(final.Deps, jobbyout, fi)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn root,nil\n}", "func LoadBTree(\n\tctx context.Context,\n\tobjStore *objstore.ObjectStore,\n\tencConf pbobject.EncryptionConfig,\n\trootRef *storageref.StorageRef,\n) (*BTree, error) {\n\tctx = objstore.WithObjStore(ctx, objStore)\n\trootNod := &Root{}\n\tif err := rootRef.FollowRef(ctx, nil, rootNod, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\tbt := &BTree{\n\t\tobjStore: objStore,\n\t\trootNod: rootNod,\n\t\trootNodRef: rootRef,\n\t\tencConf: encConf,\n\t\tfreeList: sync.Pool{New: func() interface{} { return &Node{} }},\n\t}\n\n\trootMemNode, err := bt.followNodeRef(rootNod.GetRootNodeRef())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbt.root = rootMemNode\n\n\treturn bt, nil\n}", "func (ld *loader) refine(response *driverResponse) ([]*Package, error) {\n\troots := response.Roots\n\trootMap := make(map[string]int, len(roots))\n\tfor i, root := range roots {\n\t\trootMap[root] = i\n\t}\n\tld.pkgs = make(map[string]*loaderPackage)\n\t// first pass, fixup and build the map and roots\n\tvar initial = make([]*loaderPackage, len(roots))\n\tfor _, pkg := range response.Packages {\n\t\trootIndex := -1\n\t\tif i, found := rootMap[pkg.ID]; found {\n\t\t\trootIndex = i\n\t\t}\n\n\t\t// Overlays can invalidate export data.\n\t\t// TODO(matloob): make this check fine-grained based on dependencies on overlaid files\n\t\texportDataInvalid := len(ld.Overlay) > 0 || pkg.ExportFile == \"\" && pkg.PkgPath != \"unsafe\"\n\t\t// This package needs type information if the caller requested types and the package is\n\t\t// either a root, or it's a non-root and the user requested dependencies ...\n\t\tneedtypes := (ld.Mode&NeedTypes|NeedTypesInfo != 0 && (rootIndex >= 0 || ld.Mode&NeedDeps != 0))\n\t\t// This package needs source if the call requested source (or types info, which implies source)\n\t\t// and the package is either a root, or itas a non- root and the user requested dependencies...\n\t\tneedsrc := ((ld.Mode&(NeedSyntax|NeedTypesInfo) != 0 && (rootIndex >= 0 || ld.Mode&NeedDeps != 0)) ||\n\t\t\t// ... or if we need types and the exportData is invalid. We fall back to (incompletely)\n\t\t\t// typechecking packages from source if they fail to compile.\n\t\t\t(ld.Mode&(NeedTypes|NeedTypesInfo) != 0 && exportDataInvalid)) && pkg.PkgPath != \"unsafe\"\n\t\tlpkg := &loaderPackage{\n\t\t\tPackage: pkg,\n\t\t\tneedtypes: needtypes,\n\t\t\tneedsrc: needsrc,\n\t\t\tgoVersion: response.GoVersion,\n\t\t}\n\t\tld.pkgs[lpkg.ID] = lpkg\n\t\tif rootIndex >= 0 {\n\t\t\tinitial[rootIndex] = lpkg\n\t\t\tlpkg.initial = true\n\t\t}\n\t}\n\tfor i, root := range roots {\n\t\tif initial[i] == nil {\n\t\t\treturn nil, fmt.Errorf(\"root package %v is missing\", root)\n\t\t}\n\t}\n\n\t// Materialize the import graph.\n\n\tconst (\n\t\twhite = 0 // new\n\t\tgrey = 1 // in progress\n\t\tblack = 2 // complete\n\t)\n\n\t// visit traverses the import graph, depth-first,\n\t// and materializes the graph as Packages.Imports.\n\t//\n\t// Valid imports are saved in the Packages.Import map.\n\t// Invalid imports (cycles and missing nodes) are saved in the importErrors map.\n\t// Thus, even in the presence of both kinds of errors, the Import graph remains a DAG.\n\t//\n\t// visit returns whether the package needs src or has a transitive\n\t// dependency on a package that does. These are the only packages\n\t// for which we load source code.\n\tvar stack []*loaderPackage\n\tvar visit func(lpkg *loaderPackage) bool\n\tvar srcPkgs []*loaderPackage\n\tvisit = func(lpkg *loaderPackage) bool {\n\t\tswitch lpkg.color {\n\t\tcase black:\n\t\t\treturn lpkg.needsrc\n\t\tcase grey:\n\t\t\tpanic(\"internal error: grey node\")\n\t\t}\n\t\tlpkg.color = grey\n\t\tstack = append(stack, lpkg) // push\n\t\tstubs := lpkg.Imports // the structure form has only stubs with the ID in the Imports\n\t\t// If NeedImports isn't set, the imports fields will all be zeroed out.\n\t\tif ld.Mode&NeedImports != 0 {\n\t\t\tlpkg.Imports = make(map[string]*Package, len(stubs))\n\t\t\tfor importPath, ipkg := range stubs {\n\t\t\t\tvar importErr error\n\t\t\t\timp := ld.pkgs[ipkg.ID]\n\t\t\t\tif imp == nil {\n\t\t\t\t\t// (includes package \"C\" when DisableCgo)\n\t\t\t\t\timportErr = fmt.Errorf(\"missing package: %q\", ipkg.ID)\n\t\t\t\t} else if imp.color == grey {\n\t\t\t\t\timportErr = fmt.Errorf(\"import cycle: %s\", stack)\n\t\t\t\t}\n\t\t\t\tif importErr != nil {\n\t\t\t\t\tif lpkg.importErrors == nil {\n\t\t\t\t\t\tlpkg.importErrors = make(map[string]error)\n\t\t\t\t\t}\n\t\t\t\t\tlpkg.importErrors[importPath] = importErr\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif visit(imp) {\n\t\t\t\t\tlpkg.needsrc = true\n\t\t\t\t}\n\t\t\t\tlpkg.Imports[importPath] = imp.Package\n\t\t\t}\n\t\t}\n\t\tif lpkg.needsrc {\n\t\t\tsrcPkgs = append(srcPkgs, lpkg)\n\t\t}\n\t\tif ld.Mode&NeedTypesSizes != 0 {\n\t\t\tlpkg.TypesSizes = ld.sizes\n\t\t}\n\t\tstack = stack[:len(stack)-1] // pop\n\t\tlpkg.color = black\n\n\t\treturn lpkg.needsrc\n\t}\n\n\tif ld.Mode&NeedImports == 0 {\n\t\t// We do this to drop the stub import packages that we are not even going to try to resolve.\n\t\tfor _, lpkg := range initial {\n\t\t\tlpkg.Imports = nil\n\t\t}\n\t} else {\n\t\t// For each initial package, create its import DAG.\n\t\tfor _, lpkg := range initial {\n\t\t\tvisit(lpkg)\n\t\t}\n\t}\n\tif ld.Mode&NeedImports != 0 && ld.Mode&NeedTypes != 0 {\n\t\tfor _, lpkg := range srcPkgs {\n\t\t\t// Complete type information is required for the\n\t\t\t// immediate dependencies of each source package.\n\t\t\tfor _, ipkg := range lpkg.Imports {\n\t\t\t\timp := ld.pkgs[ipkg.ID]\n\t\t\t\timp.needtypes = true\n\t\t\t}\n\t\t}\n\t}\n\t// Load type data and syntax if needed, starting at\n\t// the initial packages (roots of the import DAG).\n\tif ld.Mode&NeedTypes != 0 || ld.Mode&NeedSyntax != 0 {\n\t\tvar wg sync.WaitGroup\n\t\tfor _, lpkg := range initial {\n\t\t\twg.Add(1)\n\t\t\tgo func(lpkg *loaderPackage) {\n\t\t\t\tld.loadRecursive(lpkg)\n\t\t\t\twg.Done()\n\t\t\t}(lpkg)\n\t\t}\n\t\twg.Wait()\n\t}\n\n\tresult := make([]*Package, len(initial))\n\tfor i, lpkg := range initial {\n\t\tresult[i] = lpkg.Package\n\t}\n\tfor i := range ld.pkgs {\n\t\t// Clear all unrequested fields,\n\t\t// to catch programs that use more than they request.\n\t\tif ld.requestedMode&NeedName == 0 {\n\t\t\tld.pkgs[i].Name = \"\"\n\t\t\tld.pkgs[i].PkgPath = \"\"\n\t\t}\n\t\tif ld.requestedMode&NeedFiles == 0 {\n\t\t\tld.pkgs[i].GoFiles = nil\n\t\t\tld.pkgs[i].OtherFiles = nil\n\t\t\tld.pkgs[i].IgnoredFiles = nil\n\t\t}\n\t\tif ld.requestedMode&NeedEmbedFiles == 0 {\n\t\t\tld.pkgs[i].EmbedFiles = nil\n\t\t}\n\t\tif ld.requestedMode&NeedEmbedPatterns == 0 {\n\t\t\tld.pkgs[i].EmbedPatterns = nil\n\t\t}\n\t\tif ld.requestedMode&NeedCompiledGoFiles == 0 {\n\t\t\tld.pkgs[i].CompiledGoFiles = nil\n\t\t}\n\t\tif ld.requestedMode&NeedImports == 0 {\n\t\t\tld.pkgs[i].Imports = nil\n\t\t}\n\t\tif ld.requestedMode&NeedExportFile == 0 {\n\t\t\tld.pkgs[i].ExportFile = \"\"\n\t\t}\n\t\tif ld.requestedMode&NeedTypes == 0 {\n\t\t\tld.pkgs[i].Types = nil\n\t\t\tld.pkgs[i].Fset = nil\n\t\t\tld.pkgs[i].IllTyped = false\n\t\t}\n\t\tif ld.requestedMode&NeedSyntax == 0 {\n\t\t\tld.pkgs[i].Syntax = nil\n\t\t}\n\t\tif ld.requestedMode&NeedTypesInfo == 0 {\n\t\t\tld.pkgs[i].TypesInfo = nil\n\t\t}\n\t\tif ld.requestedMode&NeedTypesSizes == 0 {\n\t\t\tld.pkgs[i].TypesSizes = nil\n\t\t}\n\t\tif ld.requestedMode&NeedModule == 0 {\n\t\t\tld.pkgs[i].Module = nil\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func (info *Info) BuildFromFilePath(root string) (err error) {\n\tinfo.Name = filepath.Base(root)\n\tinfo.Files = nil\n\terr = filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif fi.IsDir() {\n\t\t\t// Directories are implicit in torrent files.\n\t\t\treturn nil\n\t\t} else if path == root {\n\t\t\t// The root is a file.\n\t\t\tinfo.Length = fi.Size()\n\t\t\treturn nil\n\t\t}\n\t\trelPath, err := filepath.Rel(root, path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error getting relative path: %s\", err)\n\t\t}\n\t\tinfo.Files = append(info.Files, FileInfo{\n\t\t\tPath: strings.Split(relPath, string(filepath.Separator)),\n\t\t\tLength: fi.Size(),\n\t\t})\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\tslices.Sort(info.Files, func(l, r FileInfo) bool {\n\t\treturn strings.Join(l.Path, \"/\") < strings.Join(r.Path, \"/\")\n\t})\n\terr = info.GeneratePieces(func(fi FileInfo) (io.ReadCloser, error) {\n\t\treturn os.Open(filepath.Join(root, strings.Join(fi.Path, string(filepath.Separator))))\n\t})\n\tif err != nil {\n\t\terr = fmt.Errorf(\"error generating pieces: %s\", err)\n\t}\n\treturn\n}", "func GetJarDeps(path string) (map[string]string, error) {\n\tlog.Debugf(\"GetJarDeps %s\", path)\n\tgathered := make(map[string]string)\n\n\tjar, err := jargo.GetJarInfo(path)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, j := range jar.Files {\n\t\tidx := strings.LastIndex(j, \"@\")\n\n\t\tif idx == -1 || idx+1 > len(j) {\n\t\t\tgathered[j] = \"\"\n\t\t} else {\n\t\t\tgathered[j[:idx]] = j[idx+1:]\n\t\t}\n\t}\n\treturn gathered, nil\n}", "func (i *Interface) parseDependencies() {\n\tvar dependencies []string\n\tfor _, function := range i.Functions {\n\n\t\t// \"expanded\" refers to creating a parsers.from a templated type, i.e \"QMap <int, QString>\" becomes [QMap int QString]\n\t\texpandedReturnType := strings.FieldsFunc(function.ReturnType, templatedTypeSeparators) \n\t\tfor _, dataType := range(expandedReturnType) {\n\t\t\tdependencies = append(dependencies, strings.TrimSpace(dataType))\n\t\t}\n\n\t\tfor _, parameter := range function.Parameters {\n\t\t\texpandedParameter := strings.FieldsFunc(parameter.Type, templatedTypeSeparators)\n\t\t\tfor _, innerParameter := range expandedParameter {\n\t\t\t\tdependencies = append(dependencies, strings.TrimSpace(innerParameter))\n\t\t\t} \n\t\t}\n\t}\n\ti.Dependencies = dependencies\n\ti.Dependencies = parsers.RemoveConstSpecifiers(i.Dependencies)\n\ti.Dependencies = parsers.RemovePointersAndReferences(i.Dependencies)\n\ti.Dependencies = parsers.RemoveStdDataTypes(i.Dependencies)\n\ti.Dependencies = parsers.MapDataTypesToLibraryDependencies(i.Dependencies)\n\ti.Dependencies = parsers.RemoveDuplicates(i.Dependencies)\n\tsort.Strings(i.Dependencies)\n}", "func loadV2JsonPb(data []byte) (*core.Config, error) {\n\tcoreconf := &core.Config{}\n\tjsonpbloader := &protojson.UnmarshalOptions{Resolver: anyresolverv2{serial.GetResolver()}, AllowPartial: true}\n\terr := jsonpbloader.Unmarshal(data, &V2JsonProtobufFollower{coreconf.ProtoReflect()})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn coreconf, nil\n}", "func Parse(repoRoot, path string) (_ *Deployment, err error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"open the deploy file: %w\", err)\n\t}\n\tdefer func() {\n\t\tcErr := f.Close()\n\t\tif err == nil {\n\t\t\terr = cErr\n\t\t}\n\t}()\n\n\tname := filepath.Dir(path)\n\n\tdc := Deployment{\n\t\tMain: name,\n\t}\n\terr = yaml.NewDecoder(f).Decode(&dc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parse the deploy file: %w\", err)\n\t}\n\n\treturn &dc, nil\n}", "func LoadWithKin(specPath string) *openapi3.Swagger {\n\tloader := openapi3.NewSwaggerLoader()\n\tloader.IsExternalRefsAllowed = true\n\toa3, err := loader.LoadSwaggerFromFile(specPath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn oa3\n}", "func decodeAndRetrieveOutputs(\n\tfile *hcl.File,\n\tfilename string,\n\tterragruntOptions *options.TerragruntOptions,\n\textensions EvalContextExtensions,\n) (*cty.Value, error) {\n\tdecodedDependency := terragruntDependency{}\n\terr := decodeHcl(file, filename, &decodedDependency, terragruntOptions, extensions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dependencyBlocksToCtyValue(decodedDependency.Dependencies, terragruntOptions)\n}", "func (m *Map) traversePath(path string, updateValue interface{}, createPaths bool) (interface{}, error) {\n\tpath = strings.TrimPrefix(path, \"/\")\n\tcomponents := strings.Split(path, \"/\")\n\n\tLog.Debug.Printf(\"Traversing path %v with value %v\", path, updateValue)\n\n\tif len(components) == 1 && components[0] == \"\" && updateValue != nil {\n\t\t// Complete replacement of root map, updateValue must be a generic map\n\t\t*m = Map(updateValue.(map[string]interface{}))\n\t\treturn m, nil\n\t}\n\n\tvar lastIndex = len(components) - 1\n\n\tref := *m\n\tvar child interface{} = nil\n\n\tfor i, component := range components {\n\t\tvar ok bool\n\n\t\tif component == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"Empty component encountered in path %v\", path)\n\t\t}\n\n\t\tisUpdate := updateValue != nil\n\n\t\tif i == lastIndex && isUpdate {\n\t\t\tLog.Debug.Printf(\"Updating component %v value %+v\", component, updateValue)\n\n\t\t\tvar jsonUpdateValue = updateValue\n\t\t\tif updateValue == Nil {\n\t\t\t\tjsonUpdateValue = nil\n\t\t\t} else if updateValue == Remove {\n\t\t\t\tdelete(ref, component)\n\t\t\t\treturn Remove, nil\n\t\t\t}\n\n\t\t\tref[component] = jsonUpdateValue\n\t\t\treturn ref[component], nil\n\t\t} else {\n\t\t\tchild, ok = ref[component]\n\t\t\t// Error if this child is not found\n\t\t\tif !ok {\n\t\t\t\tif createPaths && isUpdate {\n\t\t\t\t\tLog.Debug.Printf(\"Creating path for component %v\", component)\n\t\t\t\t\tnewPath := map[string]interface{}{}\n\t\t\t\t\tref[component] = newPath\n\t\t\t\t\tref = newPath\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Child component %v of path %v not found\", component, path)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif i == lastIndex && !isUpdate {\n\t\t\t\t// Return the queried value\n\t\t\t\tLog.Debug.Printf(\"Returning query value %+v\", child)\n\t\t\t\treturn child, nil\n\t\t\t}\n\n\t\t\t// Keep going - child must be a map to enable further traversal\n\t\t\tref, ok = child.(map[string]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"Child component %v of path %v is not a map\", component, path)\n\t\t\t}\n\t\t}\n\t}\n\n\t// XXX Shouldn't get here\n\treturn nil, fmt.Errorf(\"Unexpected return from TraversePath %v\", path)\n}", "func (self *SassDependencyResolver) shallowResolve(path string) ([]string, error) {\n\tdeps, ok := self.shallowDeps[path]\n\n\tif ok {\n\t\treturn deps, nil\n\t}\n\n\t// Get the file contents\n\tcontents, err := self.filecache.Get(path)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Build the matches\n\tmatches := importPattern.FindAllSubmatch(contents, -1)\n\tdeps = make([]string, len(matches))\n\n\tfor i, match := range matches {\n\t\tref := string(match[3])\n\t\trefPath, err := resolveRefPath(filepath.Dir(path), ref)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdeps[i] = refPath\n\t}\n\n\tself.shallowDeps[path] = deps\n\treturn deps, nil\n}", "func ParseBuildSpec(filePath string) (bs BuildSpec, err error) {\n\tcontents, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn bs, err\n\t}\n\n\terr = yaml.Unmarshal(contents, &bs)\n\tif err != nil {\n\t\treturn bs, err\n\t}\n\n\treturn bs, nil\n}", "func parseTopLevel(fset *token.FileSet, buf *Buffer) (*ast.File, error) {\n\tsrc := []byte(\"package p\\n\" + buf.String())\n\treturn parser.ParseFile(fset, \"<input>\", src, parser.DeclarationErrors|parser.ParseComments)\n}", "func ParsePods(jsonFile string) (configStruct kapiv1.Pod) {\n\tconfigFile, err := ioutil.ReadFile(jsonFile)\n\tif err != nil {\n\t\tframework.Failf(\"Cant read pod config file. Error: %v\", err)\n\t}\n\n\terr = json.Unmarshal(configFile, &configStruct)\n\tif err != nil {\n\t\te2e.Failf(\"Unable to unmarshal pod config. Error: %v\", err)\n\t}\n\n\te2e.Logf(\"The loaded config file is: %+v\", configStruct.Spec.Containers)\n\treturn\n}", "func ProtoMavenRuntimeLibraryToDependencyConfig(proto *registryv1alpha1.MavenConfig_RuntimeLibrary) bufpluginconfig.MavenDependencyConfig {\n\treturn bufpluginconfig.MavenDependencyConfig{\n\t\tGroupID: proto.GetGroupId(),\n\t\tArtifactID: proto.GetArtifactId(),\n\t\tVersion: proto.GetVersion(),\n\t\tClassifier: proto.GetClassifier(),\n\t\tExtension: proto.GetExtension(),\n\t}\n}", "func resolveExternalDependenciesForModule(module *TerraformModule, moduleMap map[string]*TerraformModule, terragruntOptions *options.TerragruntOptions, chilTerragruntConfig *config.TerragruntConfig) (map[string]*TerraformModule, error) {\n\tif module.Config.Dependencies == nil || len(module.Config.Dependencies.Paths) == 0 {\n\t\treturn map[string]*TerraformModule{}, nil\n\t}\n\n\texternalTerragruntConfigPaths := []string{}\n\tfor _, dependency := range module.Config.Dependencies.Paths {\n\t\tdependencyPath, err := util.CanonicalPath(dependency, module.Path)\n\t\tif err != nil {\n\t\t\treturn map[string]*TerraformModule{}, err\n\t\t}\n\n\t\tterragruntConfigPath := config.GetDefaultConfigPath(dependencyPath)\n\t\tif _, alreadyContainsModule := moduleMap[dependencyPath]; !alreadyContainsModule {\n\t\t\texternalTerragruntConfigPaths = append(externalTerragruntConfigPaths, terragruntConfigPath)\n\t\t}\n\t}\n\n\thowThesePathsWereFound := fmt.Sprintf(\"dependency of module at '%s'\", module.Path)\n\treturn resolveModules(externalTerragruntConfigPaths, terragruntOptions, chilTerragruntConfig, howThesePathsWereFound)\n}", "func (service *Service) GetServiceDef(path string) error {\n\tfilePath := service.ServiceFilePath(path)\n\traw, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjson.Unmarshal(raw, &service)\n\treturn nil\n}", "func UnmarshalChartfile(data []byte) (*chart.Metadata, error) {\n\ty := &chart.Metadata{}\n\terr := yaml.Unmarshal(data, y)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn y, nil\n}", "func InfoFromPath(configFilePath string) (*Info, error) {\n\tconfigSpecDir := filepath.Dir(configFilePath)\n\trepo := filepath.Base(configSpecDir)\n\tif repo == \".\" || repo == \"/\" {\n\t\treturn nil, fmt.Errorf(\"could not extract repo from '%s' (expected path like '.../ORG/REPO/ORGANIZATION-COMPONENT-BRANCH.yaml\", configFilePath)\n\t}\n\n\torg := filepath.Base(filepath.Dir(configSpecDir))\n\tif org == \".\" || org == \"/\" {\n\t\treturn nil, fmt.Errorf(\"could not extract org from '%s' (expected path like '.../ORG/REPO/ORGANIZATION-COMPONENT-BRANCH.yaml\", configFilePath)\n\t}\n\n\tfileName := filepath.Base(configFilePath)\n\ts := strings.TrimSuffix(fileName, filepath.Ext(configFilePath))\n\tbranch := strings.TrimPrefix(s, fmt.Sprintf(\"%s-%s-\", org, repo))\n\n\tvar variant string\n\tif i := strings.LastIndex(branch, \"__\"); i != -1 {\n\t\tvariant = branch[i+2:]\n\t\tbranch = branch[:i]\n\t}\n\n\treturn &Info{\n\t\tMetadata: cioperatorapi.Metadata{\n\t\t\tOrg: org,\n\t\t\tRepo: repo,\n\t\t\tBranch: branch,\n\t\t\tVariant: variant,\n\t\t},\n\t\tFilename: configFilePath,\n\t\tOrgPath: filepath.Dir(configSpecDir),\n\t\tRepoPath: configSpecDir,\n\t}, nil\n}", "func (t *importTree) ConfigTree() (*configTree, error) {\n\tconfig, err := t.Raw.Config()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"Error loading %s: %s\",\n\t\t\tt.Path,\n\t\t\terr)\n\t}\n\n\t// Build our result\n\tresult := &configTree{\n\t\tPath: t.Path,\n\t\tConfig: config,\n\t}\n\n\t// Build the config trees for the children\n\tresult.Children = make([]*configTree, len(t.Children))\n\tfor i, ct := range t.Children {\n\t\tt, err := ct.ConfigTree()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tresult.Children[i] = t\n\t}\n\n\treturn result, nil\n}", "func parsePath(path string, fset *token.FileSet) (map[string]*ast.Package, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinfo, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pkgs map[string]*ast.Package // Assigned in either of two branches below.\n\n\tif info.IsDir() {\n\t\tpkgs, err = parser.ParseDir(fset, path, nil, 0)\n\t\tif err != nil {\n\t\t\treturn nil, wrapErr(\"failed to parse directory\", err)\n\t\t}\n\t} else {\n\t\tfile, err := parser.ParseFile(fset, path, nil, 0)\n\t\tif err != nil {\n\t\t\treturn nil, wrapErr(\"failed to parse file\", err)\n\t\t}\n\t\tpkg := &ast.Package{\n\t\t\tName: file.Name.Name,\n\t\t\tFiles: map[string]*ast.File{\n\t\t\t\tfilepath.Base(path): file,\n\t\t\t},\n\t\t}\n\t\tpkgs = map[string]*ast.Package{pkg.Name: pkg}\n\t}\n\n\treturn pkgs, nil\n}", "func findFileInDeps(s MetadataSource, m *Metadata, uri span.URI) *Metadata {\n\tseen := make(map[PackageID]bool)\n\tvar search func(*Metadata) *Metadata\n\tsearch = func(m *Metadata) *Metadata {\n\t\tif seen[m.ID] {\n\t\t\treturn nil\n\t\t}\n\t\tseen[m.ID] = true\n\t\tfor _, cgf := range m.CompiledGoFiles {\n\t\t\tif cgf == uri {\n\t\t\t\treturn m\n\t\t\t}\n\t\t}\n\t\tfor _, dep := range m.DepsByPkgPath {\n\t\t\tm := s.Metadata(dep)\n\t\t\tif m == nil {\n\t\t\t\tbug.Reportf(\"nil metadata for %q\", dep)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif found := search(m); found != nil {\n\t\t\t\treturn found\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\treturn search(m)\n}", "func MergeSwaggerDoc(currentPaths []*Path, config *Config, doc *loads.Document, validateCapturedSegments bool, pathPrefix string) ([]*Path, error) {\n\tallPaths, err := GetPathsFromSwagger(doc, config, pathPrefix)\n\tif err != nil {\n\t\tempty := []*Path{}\n\t\treturn empty, err // TODO add context to errors!\n\t}\n\treturn MergeSwaggerPaths(currentPaths, config, allPaths, validateCapturedSegments, pathPrefix)\n}", "func ParseTfmConfigs(workdirDir string) (string, error) {\n\tvar versionString string\n\tconfigRootSchema := &hcl.BodySchema{\n\t\tBlocks: []hcl.BlockHeaderSchema{\n\t\t\t{\n\t\t\t\tType: \"terraform\",\n\t\t\t},\n\t\t},\n\t}\n\tconfigFileVersionSniffBlockSchema := &hcl.BodySchema{\n\t\tAttributes: []hcl.AttributeSchema{\n\t\t\t{\n\t\t\t\tName: \"required_version\",\n\t\t\t},\n\t\t},\n\t}\n\tmatches, _ := filepath.Glob(fmt.Sprintf(\"%s/*.tf\", workdirDir))\n\tfor _, path := range matches {\n\t\tif src, err := ioutil.ReadFile(path); err == nil {\n\t\t\tfile, _ := hclparse.NewParser().ParseHCL(src, path)\n\t\t\tif file == nil || file.Body == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trootContent, _, _ := file.Body.PartialContent(configRootSchema)\n\t\t\tfor _, block := range rootContent.Blocks {\n\t\t\t\tcontent, _, _ := block.Body.PartialContent(configFileVersionSniffBlockSchema)\n\t\t\t\tattr, exists := content.Attributes[\"required_version\"]\n\t\t\t\tif !exists || len(versionString) > 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tval, diags := attr.Expr.Value(nil)\n\t\t\t\tif diags.HasErrors() {\n\t\t\t\t\terr = fmt.Errorf(\"Error in attribute value\")\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\t\t\t\tversionString = val.AsString()\n\t\t\t}\n\t\t}\n\t}\n\tif versionString == \"\" {\n\t\tversionString = DefaultConstraint\n\t}\n\treturn versionString, nil\n}", "func pkgDeps(imports pkgMap, pkg *ast.Package) {\n\tfor _, file := range pkg.Files {\n\t\tfor _, imp := range file.Imports {\n\t\t\timportPath := importPath(imp)\n\t\t\tif _, ok := imports[importPath]; ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tpdir := importDir(importPath)\n\t\t\tif pdir != \"\" {\n\t\t\t\tfpkg, err := getFuelPkg(pdir)\n\t\t\t\tif err != nil {\n\t\t\t\t\tprintErr(efmt(\"%v: %v\", importPath, err))\n\t\t\t\t}\n\n\t\t\t\timports[importPath] = fpkg\n\t\t\t\tif fpkg != nil && err == nil {\n\t\t\t\t\tpkgDeps(imports, fpkg.pkg.Package)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\timports[importPath] = nil\n\t\t\t}\n\t\t}\n\t}\n}", "func (this *Codec) deserialize(data string) *TreeNode {\n\tif len(data) == 0 || data == \"[]\" {\n\t\treturn nil\n\t}\n\n\tarray := strings.Split(data, \",\")\n\tmaps := make(map[int64]int)\n\n\tfor _, v := range array {\n\t\tkeyValueArray := strings.Split(v, \":\")\n\t\tindex, _ := strconv.ParseInt(keyValueArray[0], 10, 64)\n\t\tvalue, _ := strconv.Atoi(keyValueArray[1])\n\t\tmaps[index] = value\n\t}\n\n\troot := TreeNode{\n\t\tVal: maps[1],\n\t\tRight: innerDeserialize(&maps, 3),\n\t\tLeft: innerDeserialize(&maps, 2),\n\t}\n\n\treturn &root\n}", "func CalTree(data [][]byte) {\r\n\tvar Root Node\r\n\tRoot.GenerateRoot(data, true)\r\n}", "func (v *Validator) getSchemaByRef(uri string) (json.Value, json.Value, error) {\n\tu, err := url.Parse(uri)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse %q: %s\", uri, err)\n\t}\n\ts, ref := v.schema, u.Fragment\n\n\tif !strings.HasPrefix(uri, \"#\") {\n\t\tu.Fragment = \"\"\n\t\turi := u.String()\n\t\ts, err = v.loader.Get(uri)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tr, err := resolveRef(s, ref)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to resolve ref %q: %s\", uri, err)\n\t}\n\treturn r, s, nil\n}", "func GetApplicationDefinition(filePath string) (*v2.ApplicationDefinition, []byte, error) {\n\tinfo, err := os.Stat(filePath)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar buffer []byte\n\tif info.IsDir() {\n\t\t_, content, err := resolveYamlOrJSON(path.Join(filePath, filepath.Base(filePath)))\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tbuffer = content\n\t} else {\n\t\treturn nil, nil, fmt.Errorf(\"looking for directory, found %s\", info.Name())\n\t}\n\tapi, err := extractAppDefinition(buffer)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn api, buffer, nil\n}", "func parseTerragruntConfigFile(configPath string) (*TerragruntConfig, error) {\n\tbytes, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\treturn nil, errors.WithStackTraceAndPrefix(err, \"Error reading Terragrunt config file %s\", configPath)\n\t}\n\n\tconfig, err := parseTerragruntConfig(string(bytes))\n\tif err != nil {\n\t\treturn nil, errors.WithStackTraceAndPrefix(err, \"Error parsing Terragrunt config file %s\", configPath)\n\t}\n\n\treturn config, nil\n}", "func (*GetSignedMapRootByRevisionRequest) Descriptor() ([]byte, []int) {\n\treturn file_trillian_map_api_proto_rawDescGZIP(), []int{15}\n}", "func OapiValidatorFromYamlFile(path string) (fiber.Handler, error) {\n\n\tdata, err := os.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading %s: %s\", path, err)\n\t}\n\n\tswagger, err := openapi3.NewLoader().LoadFromData(data)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing %s as Swagger YAML: %s\",\n\t\t\tpath, err)\n\t}\n\n\treturn OapiRequestValidator(swagger), nil\n}", "func (d DownloadCacheLayer) Metadata(root string) string {\n\treturn filepath.Join(root, \"dependency.toml\")\n}", "func ParseConfigFile(configPath string) (map[string][]dns.RR, error) {\n\tconf, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar dat map[string][]string\n\tif err := json.Unmarshal(conf, &dat); err == nil {\n\t\treturn ParseDNSRecordsMap(dat)\n\t} else {\n\t\treturn nil, err\n\t}\n}", "func ParseDockerRef(ref string) (Named, error) {\n\tnamed, err := ParseNormalizedNamed(ref)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif _, ok := named.(NamedTagged); ok {\n\t\tif canonical, ok := named.(Canonical); ok {\n\t\t\t// The reference is both tagged and digested, only\n\t\t\t// return digested.\n\t\t\tnewNamed, err := WithName(canonical.Name())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tnewCanonical, err := WithDigest(newNamed, canonical.Digest())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn newCanonical, nil\n\t\t}\n\t}\n\treturn TagNameOnly(named), nil\n}", "func (p *Parser) Parse(_ string, fileContent []byte) ([]model.Document, error) {\n\tvar documents []model.Document\n\tcom, err := dockerfile.ParseReader(bytes.NewReader(fileContent))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Failed to parse Dockerfile\")\n\t}\n\n\tdoc := &model.Document{}\n\n\tvar resource Resource\n\tresource.CommandList = com\n\n\tj, err := json.Marshal(resource)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Failed to Marshal Dockerfile\")\n\t}\n\n\tif err := json.Unmarshal(j, &doc); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Failed to Unmarshal Dockerfile\")\n\t}\n\n\tdocuments = append(documents, *doc)\n\n\treturn documents, nil\n}", "func (d *Dao) Tree(c context.Context, token string) (data interface{}, err error) {\n\tvar (\n\t\treq *http.Request\n\t\ttmp map[string]interface{}\n\t\tok bool\n\t)\n\tif req, err = http.NewRequest(\"GET\", dataURI, nil); err != nil {\n\t\tlog.Error(\"Status url(%s) error(%v)\", dataURI, err)\n\t\treturn\n\t}\n\treq.Header.Set(\"X-Authorization-Token\", token)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tvar res struct {\n\t\tCode int `json:\"code\"`\n\t\tData map[string]map[string]interface{} `json:\"data\"`\n\t\tMessage string `json:\"message\"`\n\t\tStatus int `json:\"status\"`\n\t}\n\tif err = d.client.Do(c, req, &res); err != nil {\n\t\tlog.Error(\"d.Status url(%s) res($s) err(%v)\", dataURI, res, err)\n\t\treturn\n\t}\n\tif res.Code != 90000 {\n\t\terr = fmt.Errorf(\"error code :%d\", res.Code)\n\t\tlog.Error(\"Status url(%s) res(%v)\", dataURI, res)\n\t\treturn\n\t}\n\tif tmp, ok = res.Data[\"bilibili\"]; ok {\n\t\tdata, ok = tmp[\"children\"]\n\t}\n\tif !ok {\n\t\terr = ecode.NothingFound\n\t}\n\treturn\n}", "func dependencyBlocksToCtyValue(dependencyConfigs []Dependency, terragruntOptions *options.TerragruntOptions) (*cty.Value, error) {\n\tpaths := []string{}\n\t// dependencyMap is the top level map that maps dependency block names to the encoded version, which includes\n\t// various attributes for accessing information about the target config (including the module outputs).\n\tdependencyMap := map[string]cty.Value{}\n\n\tfor _, dependencyConfig := range dependencyConfigs {\n\t\t// Loose struct to hold the attributes of the dependency. This includes:\n\t\t// - outputs: The module outputs of the target config\n\t\tdependencyEncodingMap := map[string]cty.Value{}\n\n\t\t// Encode the outputs and nest under `outputs` attribute\n\t\tpaths = append(paths, dependencyConfig.ConfigPath)\n\t\toutputVal, err := getTerragruntOutput(dependencyConfig, terragruntOptions)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdependencyEncodingMap[\"outputs\"] = *outputVal\n\n\t\t// Once the dependency is encoded into a map, we need to conver to a cty.Value again so that it can be fed to\n\t\t// the higher order dependency map.\n\t\tdependencyEncodingMapEncoded, err := gocty.ToCtyValue(dependencyEncodingMap, generateTypeFromValuesMap(dependencyEncodingMap))\n\t\tif err != nil {\n\t\t\terr = TerragruntOutputListEncodingError{Paths: paths, Err: err}\n\t\t}\n\n\t\t// Finally, feed the encoded dependency into the higher order map under the block name\n\t\tdependencyMap[dependencyConfig.Name] = dependencyEncodingMapEncoded\n\t}\n\n\t// We need to convert the value map to a single cty.Value at the end so that it can be used in the execution context\n\tconvertedOutput, err := gocty.ToCtyValue(dependencyMap, generateTypeFromValuesMap(dependencyMap))\n\tif err != nil {\n\t\terr = TerragruntOutputListEncodingError{Paths: paths, Err: err}\n\t}\n\treturn &convertedOutput, errors.WithStackTrace(err)\n}", "func (t *Tables) FileTree() filetree.FileTree { return t }" ]
[ "0.44742846", "0.4455825", "0.43550068", "0.43006805", "0.4232624", "0.41817617", "0.40636328", "0.40288898", "0.39767098", "0.39680606", "0.39440867", "0.3909975", "0.38882518", "0.38842115", "0.38663462", "0.3862431", "0.38287383", "0.38224056", "0.3783585", "0.37813827", "0.37639192", "0.37486592", "0.37433174", "0.37286022", "0.3721877", "0.37083578", "0.36979386", "0.36836642", "0.367974", "0.36631432", "0.3647026", "0.36445725", "0.36437666", "0.3635032", "0.3634338", "0.3632871", "0.3626514", "0.36227846", "0.36211073", "0.3613153", "0.36109856", "0.36097935", "0.36097935", "0.36082813", "0.36025965", "0.35987264", "0.35921654", "0.35903168", "0.35890982", "0.358801", "0.3573279", "0.35724053", "0.35707882", "0.35627824", "0.356094", "0.3560749", "0.35465425", "0.35431337", "0.35431337", "0.35403985", "0.352545", "0.3518159", "0.35102183", "0.35057622", "0.35049734", "0.3502346", "0.349671", "0.3492842", "0.3492825", "0.34811604", "0.34708306", "0.34683165", "0.3460186", "0.345218", "0.34519652", "0.34502313", "0.34495205", "0.34470445", "0.3446722", "0.34420782", "0.34382278", "0.34367344", "0.3434756", "0.34338874", "0.34322926", "0.3430879", "0.3426195", "0.34184948", "0.341566", "0.34151047", "0.34125984", "0.34099418", "0.34054303", "0.34028476", "0.3398432", "0.33951178", "0.33941945", "0.33895996", "0.33881992", "0.33871156" ]
0.8142745
0
MarshalToYAML marshals a MagmaSwaggerSpec to a YAMLformatted string.
func (m *MagmaSwaggerSpec) MarshalToYAML() (string, error) { d, err := yaml.Marshal(&m) if err != nil { return "", err } return string(d), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d LegacyDec) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (c *Components) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(c, c.low)\n\treturn nb.Render(), nil\n}", "func (f Fixed8) MarshalYAML() (interface{}, error) {\n\treturn f.String(), nil\n}", "func (p *Parameter) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(p, p.low)\n\treturn nb.Render(), nil\n}", "func (r ParseKind) MarshalYAML() ([]byte, error) {\n\tif s, ok := interface{}(r).(fmt.Stringer); ok {\n\t\treturn yaml.Marshal(s.String())\n\t}\n\ts, ok := _ParseKindValueToName[r]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid ParseKind: %d\", r)\n\t}\n\treturn yaml.Marshal(s)\n}", "func (s *Spec020) Marshal() ([]byte, error) {\n\treturn yaml.Marshal(s)\n}", "func (p Params) MarshalYAML() (interface{}, error) {\n\treturn p.String(), nil\n}", "func (r *Regexp) MarshalYAML() (interface{}, error) {\n\treturn r.String(), nil\n}", "func (ep Endpoint) MarshalYAML() (interface{}, error) {\n\ts, err := ep.toString()\n\treturn s, err\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (re Regexp) MarshalYAML() (interface{}, error) {\n\tif re.original != \"\" {\n\t\treturn re.original, nil\n\t}\n\treturn nil, nil\n}", "func (schema SchemaType) MarshalYAML() (interface{}, error) {\n\treturn schema.String(), nil\n}", "func (a ApprovalStrategy) MarshalYAML() (interface{}, error) {\n\treturn approvalStrategyToString[a], nil\n\t//buffer := bytes.NewBufferString(`\"`)\n\t//buffer.WriteString(approvalStrategyToString[*s])\n\t//buffer.WriteString(`\"`)\n\t//return buffer.Bytes(), nil\n}", "func (s GitEvent) MarshalYAML() (interface{}, error) {\n\treturn toString[s], nil\n}", "func (d Rate) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (i UOM) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (o *OAuthFlow) MarshalYAML() (interface{}, error) {\n\tnb := high.NewNodeBuilder(o, o.low)\n\treturn nb.Render(), nil\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.String(), nil\n}", "func (o Op) MarshalYAML() (interface{}, error) {\n\treturn map[string]interface{}{\n\t\to.Type(): o.OpApplier,\n\t}, nil\n}", "func (u *URL) MarshalYAML() (interface{}, error) {\n\treturn u.String(), nil\n}", "func (i ChannelName) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func specYAMLToJSON(specContent []byte) []byte {\n\tspecMap := make(map[string]interface{})\n\t// check if the content is already json\n\terr := json.Unmarshal(specContent, &specMap)\n\tif err == nil {\n\t\treturn specContent\n\t}\n\n\t// check if the content is already yaml\n\terr = yaml.Unmarshal(specContent, &specMap)\n\tif err != nil {\n\t\t// Not yaml, nothing more to be done\n\t\treturn specContent\n\t}\n\n\ttranscoded, err := yaml.YAMLToJSON(specContent)\n\tif err != nil {\n\t\t// Not json encodeable, nothing more to be done\n\t\treturn specContent\n\t}\n\treturn transcoded\n}", "func (s String) MarshalYAML() (interface{}, error) {\n\tif !s.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn s.value, nil\n}", "func (v Validator) MarshalYAML() (interface{}, error) {\n\tbs, err := yaml.Marshal(struct {\n\t\tStatus sdk.BondStatus\n\t\tJailed bool\n\t\tUnbondingHeight int64\n\t\tConsPubKey string\n\t\tOperatorAddress sdk.ValAddress\n\t\tTokens sdk.Int\n\t\tDelegatorShares sdk.Dec\n\t\tDescription Description\n\t\tUnbondingCompletionTime time.Time\n\t\tCommission Commission\n\t\tMinSelfDelegation sdk.Dec\n\t}{\n\t\tOperatorAddress: v.OperatorAddress,\n\t\tConsPubKey: MustBech32ifyConsPub(v.ConsPubKey),\n\t\tJailed: v.Jailed,\n\t\tStatus: v.Status,\n\t\tTokens: v.Tokens,\n\t\tDelegatorShares: v.DelegatorShares,\n\t\tDescription: v.Description,\n\t\tUnbondingHeight: v.UnbondingHeight,\n\t\tUnbondingCompletionTime: v.UnbondingCompletionTime,\n\t\tCommission: v.Commission,\n\t\tMinSelfDelegation: v.MinSelfDelegation,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bs), nil\n}", "func (f Flag) MarshalYAML() (interface{}, error) {\n\treturn f.Name, nil\n}", "func (key PrivateKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}", "func (m OrderedMap[K, V]) MarshalYAML() ([]byte, error) {\n\tvar s yaml.MapSlice\n\tfor _, item := range m.ToSlice() {\n\t\ts = append(s, yaml.MapItem{\n\t\t\tKey: item.Key,\n\t\t\tValue: item.Value,\n\t\t})\n\t}\n\treturn yaml.Marshal(s)\n}", "func (b *Backend) MarshalYAML() (interface{}, error) {\n\tb.mu.RLock()\n\tdefer b.mu.RUnlock()\n\n\tpayload := struct {\n\t\tAddress string\n\t\tDisabledUntil time.Time `yaml:\"disabledUntil\"`\n\t\tForcePromotionsAfter time.Duration `yaml:\"forcePromotionsAfter\"`\n\t\tLatency time.Duration `yaml:\"latency\"`\n\t\tMaxConnections int `yaml:\"maxConnections\"`\n\t\tTier int `yaml:\"tier\"`\n\t}{\n\t\tAddress: b.addr.String(),\n\t\tDisabledUntil: b.mu.disabledUntil,\n\t\tForcePromotionsAfter: b.mu.forcePromotionAfter,\n\t\tLatency: b.mu.lastLatency,\n\t\tMaxConnections: b.mu.maxConnections,\n\t\tTier: b.mu.tier,\n\t}\n\treturn payload, nil\n}", "func (m MixinDeclaration) MarshalYAML() (interface{}, error) {\n\tif m.Config == nil {\n\t\treturn m.Name, nil\n\t}\n\n\traw := map[string]interface{}{\n\t\tm.Name: m.Config,\n\t}\n\treturn raw, nil\n}", "func (m *BootstrapMode) MarshalYAML() (interface{}, error) {\n\treturn m.String(), nil\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (s Secret) MarshalYAML() (interface{}, error) {\n\tif s != \"\" {\n\t\treturn \"<secret>\", nil\n\t}\n\treturn nil, nil\n}", "func (d Duration) MarshalYAML() (interface{}, error) {\n\treturn d.Duration.String(), nil\n}", "func (d *DefaultOptions) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(d)\n}", "func ExportYAMLForSpec(ctx context.Context, client *gapic.RegistryClient, message *rpc.Spec) {\n\tprintDocAsYaml(docForMapping(exportSpec(ctx, client, message)))\n}", "func (z Z) MarshalYAML() (interface{}, error) {\n\ttype Z struct {\n\t\tS string `json:\"s\"`\n\t\tI int32 `json:\"iVal\"`\n\t\tHash string\n\t\tMultiplyIByTwo int64 `json:\"multipliedByTwo\"`\n\t}\n\tvar enc Z\n\tenc.S = z.S\n\tenc.I = z.I\n\tenc.Hash = z.Hash()\n\tenc.MultiplyIByTwo = int64(z.MultiplyIByTwo())\n\treturn &enc, nil\n}", "func MarshalMetricsYAML(metrics pmetric.Metrics) ([]byte, error) {\n\tunmarshaler := &pmetric.JSONMarshaler{}\n\tfileBytes, err := unmarshaler.MarshalMetrics(metrics)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar jsonVal map[string]interface{}\n\tif err = json.Unmarshal(fileBytes, &jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\tb := &bytes.Buffer{}\n\tenc := yaml.NewEncoder(b)\n\tenc.SetIndent(2)\n\tif err := enc.Encode(jsonVal); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.Bytes(), nil\n}", "func (v *VersionInfo) MarshalYAML() (interface{}, error) {\n\n\treturn &struct {\n\t\tSemVer string `yaml:\"semver\"`\n\t\tShaLong string `yaml:\"shaLong\"`\n\t\tBuildTimestamp int64 `yaml:\"buildTimestamp\"`\n\t\tBranch string `yaml:\"branch\"`\n\t\tArch string `yaml:\"arch\"`\n\t}{\n\t\tSemVer: v.SemVer,\n\t\tShaLong: v.ShaLong,\n\t\tBuildTimestamp: v.BuildTimestamp.Unix(),\n\t\tBranch: v.Branch,\n\t\tArch: v.Arch,\n\t}, nil\n}", "func (r OAuthFlow) MarshalYAML() (interface{}, error) {\n\tobj := make(map[string]interface{})\n\n\tobj[\"authorizationUrl\"] = r.AuthorizationURL\n\n\tobj[\"tokenUrl\"] = r.TokenURL\n\n\tif r.RefreshURL != \"\" {\n\t\tobj[\"refreshUrl\"] = r.RefreshURL\n\t}\n\n\tobj[\"scopes\"] = r.Scopes\n\n\tfor key, val := range r.Extensions {\n\t\tobj[key] = val\n\t}\n\n\treturn obj, nil\n}", "func (d *WebAuthnDevice) MarshalYAML() (any, error) {\n\treturn d.ToData(), nil\n}", "func (s String) MarshalYAML() (interface{}, error) {\n\tif len(string(s)) == 0 || string(s) == `\"\"` {\n\t\treturn nil, nil\n\t}\n\treturn string(s), nil\n}", "func (bc *ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(AtomicLoadByteCount(bc)), nil\n}", "func (u *URL) MarshalYAML() (interface{}, error) {\n\tif u.url == nil {\n\t\treturn nil, nil\n\t}\n\treturn u.url.String(), nil\n}", "func (i Instance) MarshalYAML() (interface{}, error) {\n\treturn i.Vars, nil\n}", "func (f BodyField) MarshalYAML() (interface{}, error) {\n\treturn toJSONDot(f), nil\n}", "func Marshal(v interface{}) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tenc := yaml.NewEncoder(&buf)\n\tenc.SetIndent(2)\n\terr := enc.Encode(v)\n\treturn buf.Bytes(), err\n}", "func (ss StdSignature) MarshalYAML() (interface{}, error) {\n\tpk := \"\"\n\tif ss.PubKey != nil {\n\t\tpk = ss.PubKey.String()\n\t}\n\n\tbz, err := yaml.Marshal(struct {\n\t\tPubKey string `json:\"pub_key\"`\n\t\tSignature string `json:\"signature\"`\n\t}{\n\t\tpk,\n\t\tfmt.Sprintf(\"%X\", ss.Signature),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn string(bz), err\n}", "func (v *Int8) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func (u URL) MarshalYAML() (interface{}, error) {\n\tif u.URL != nil {\n\t\treturn u.String(), nil\n\t}\n\treturn nil, nil\n}", "func (d Document) MarshalYAML() (interface{}, error) {\n\treturn d.raw, nil\n}", "func configSpecToYaml(configSpec opv1alpha1.NetworkAddonsConfigSpec) string {\n\tmanifest, err := yaml.Marshal(configSpec)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tmanifestLines := strings.Split(string(manifest), \"\\n\")\n\n\t// We don't want to show non-set (default) values, usually null. Try our best to filter those out.\n\tmanifestLinesWithoutEmptyValues := []string{}\n\tfor _, line := range manifestLines {\n\t\t// If root attribute (e.g. ImagePullPolicy) is set to default, drop it. If it\n\t\t// is a nested attribute (e.g. KubeMacPool's RangeEnd), keep it.\n\t\trootAttributeSetToDefault := !strings.Contains(line, \" \") && (strings.Contains(line, \": \\\"\\\"\") || strings.Contains(line, \": null\"))\n\t\tif line != \"\" && !rootAttributeSetToDefault {\n\t\t\tmanifestLinesWithoutEmptyValues = append(manifestLinesWithoutEmptyValues, line)\n\t\t}\n\t}\n\n\t// If any values has been set, return Spec in a nice YAML format\n\tif len(manifestLinesWithoutEmptyValues) > 0 {\n\t\tindentedManifest := strings.TrimSpace(strings.Join(manifestLinesWithoutEmptyValues, \"\\n\"))\n\t\treturn indentedManifest\n\t}\n\n\t// Note that it is empty otherwise\n\treturn \"Empty Spec\"\n}", "func (o *OpenAPI3SchemaExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (n Nil) MarshalYAML() (interface{}, error) {\n\treturn nil, nil\n}", "func (d DurationMillis) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Millisecond), nil\n}", "func (export WebAuthnDeviceExport) MarshalYAML() (any, error) {\n\treturn export.ToData(), nil\n}", "func (i Interface) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (op OpRemove) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}", "func (o *Output) MarshalYAML() (interface{}, error) {\n\tif o.ShowValue {\n\t\treturn withvalue(*o), nil\n\t}\n\to.Value = nil // explicitly make empty\n\to.Sensitive = false // explicitly make empty\n\treturn *o, nil\n}", "func (r RetryConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyRetryConfig{\n\t\tOutput: r.Output,\n\t\tConfig: r.Config,\n\t}\n\tif r.Output == nil {\n\t\tdummy.Output = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func (o *OpenAPI3Options) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (d DurationMinutes) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn int(d.value / time.Minute), nil\n}", "func (v *Uint16) MarshalYAML() (interface{}, error) {\n\tif v.IsAssigned {\n\t\treturn v.Val, nil\n\t}\n\treturn nil, nil\n}", "func (b ByteCount) MarshalYAML() (interface{}, error) {\n\treturn uint64(b), nil\n}", "func (date Date) MarshalYAML() (interface{}, error) {\n\tvar d = string(date)\n\tif err := checkDateFormat(d); err != nil {\n\t\treturn nil, err\n\t}\n\treturn d, nil\n}", "func (op OpFlatten) MarshalYAML() (interface{}, error) {\n\treturn op.Field.String(), nil\n}", "func (c CompressionType) MarshalYAML() (interface{}, error) {\n\treturn compressionTypeID[c], nil\n}", "func MarshalYAML(v interface{}, extensions map[string]interface{}) (interface{}, error) {\n\tif len(extensions) == 0 {\n\t\treturn v, nil\n\t}\n\tmarshaled, err := yaml.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar unmarshaled map[string]interface{}\n\tif err := yaml.Unmarshal(marshaled, &unmarshaled); err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range extensions {\n\t\tunmarshaled[k] = v\n\t}\n\treturn unmarshaled, nil\n}", "func (key PublicKey) MarshalYAML() (interface{}, error) {\n\treturn key.String(), nil\n}", "func (o *OpenAPI3PathExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (d *Discriminator) MarshalYAML() (interface{}, error) {\n\tnb := low2.NewNodeBuilder(d, d.low)\n\treturn nb.Render(), nil\n}", "func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {\n\tdummy := dummyReadUntilConfig{\n\t\tInput: r.Input,\n\t\tRestart: r.Restart,\n\t\tCheck: r.Check,\n\t}\n\tif r.Input == nil {\n\t\tdummy.Input = struct{}{}\n\t}\n\treturn dummy, nil\n}", "func (p *ServiceDefinition) Marshal() (string, error) {\n\toutput, err := yaml.Marshal(p)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(output), nil\n}", "func (f Float64) MarshalYAML() (interface{}, error) {\n\tif !f.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn f.value, nil\n}", "func ParseAppSpecToYaml(appSpec *godo.AppSpec) ([]byte, error) {\n\tnewYaml, err := yaml.Marshal(appSpec)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Error in building yaml\")\n\t}\n\treturn newYaml, nil\n}", "func (i UserGroupAccess) MarshalYAML() (interface{}, error) {\n\treturn i.String(), nil\n}", "func (ec EllipticCurve) MarshalYAML() (interface{}, error) {\n\treturn ec.String(), nil\n}", "func (op OpRetain) MarshalYAML() (interface{}, error) {\n\treturn op.Fields, nil\n}", "func SPrintYAML(a interface{}) (string, error) {\n\tb, err := MarshalJSON(a)\n\t// doing yaml this way because at times you have nested proto structs\n\t// that need to be cleaned.\n\tyam, err := yamlconv.JSONToYAML(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(yam), nil\n}", "func (s *spiff) Marshal(node Node) ([]byte, error) {\n\treturn yaml.Marshal(node)\n}", "func (o *OpenAPI3ResponseExtension) MarshalYAML() (interface{}, error) {\n\treturn util.MarshalYAMLWithDescriptions(o)\n}", "func (s SensitiveString) MarshalYAML() (interface{}, error) {\n\treturn s.String(), nil\n}", "func Marshal(o interface{}) ([]byte, error) {\n\tj, err := json.Marshal(o)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error marshaling into JSON: %v\", err)\n\t}\n\n\ty, err := JSONToYAML(j)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error converting JSON to YAML: %v\", err)\n\t}\n\n\treturn y, nil\n}", "func MarshalToYaml(obj runtime.Object, gv schema.GroupVersion) ([]byte, error) {\n\treturn MarshalToYamlForCodecs(obj, gv, clientsetscheme.Codecs)\n}", "func (i Int) MarshalYAML() (interface{}, error) {\n\tif !i.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn i.value, nil\n}", "func (b Bool) MarshalYAML() (interface{}, error) {\n\tif !b.IsPresent() {\n\t\treturn nil, nil\n\t}\n\treturn b.value, nil\n}", "func (vm ValidationMap) AsYAML() (string, error) {\n\tdata, err := yaml.Marshal(vm)\n\treturn string(data), err\n}", "func MarshalToYamlForCodecs(obj runtime.Object, gv schema.GroupVersion, codecs serializer.CodecFactory) ([]byte, error) {\n\tconst mediaType = runtime.ContentTypeYAML\n\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn []byte{}, errors.Errorf(\"unsupported media type %q\", mediaType)\n\t}\n\n\tencoder := codecs.EncoderForVersion(info.Serializer, gv)\n\treturn runtime.Encode(encoder, obj)\n}", "func ProtoToYAML(m protoreflect.ProtoMessage) ([]byte, error) {\n\tmarshalOptions := protojson.MarshalOptions{\n\t\tUseProtoNames: true,\n\t}\n\tconfigJSON, err := marshalOptions.Marshal(m)\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"Error marshaling proto to JSON\")\n\t\treturn nil, err\n\t}\n\n\tconfigYAML, err := yaml.JSONToYAML(configJSON)\n\tif err != nil {\n\t\tlog.Error().Err(err).Msgf(\"Error converting JSON to YAML\")\n\t\treturn nil, err\n\t}\n\treturn configYAML, err\n}", "func NewSpec(yamlConfig string) (*Spec, error) {\n\ts := &Spec{\n\t\tyamlConfig: yamlConfig,\n\t}\n\n\tmeta := &MetaSpec{}\n\terr := yaml.Unmarshal([]byte(yamlConfig), meta)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshal failed: %v\", err)\n\t}\n\tvr := v.Validate(meta, []byte(yamlConfig))\n\tif !vr.Valid() {\n\t\treturn nil, fmt.Errorf(\"validate metadata failed: \\n%s\", vr)\n\t}\n\n\trootObject, exists := objectRegistry[meta.Kind]\n\tif !exists {\n\t\treturn nil, fmt.Errorf(\"kind %s not found\", meta.Kind)\n\t}\n\n\ts.meta, s.objectSpec = meta, rootObject.DefaultSpec()\n\n\terr = yaml.Unmarshal([]byte(yamlConfig), s.objectSpec)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshal failed: %v\", err)\n\t}\n\tvr = v.Validate(s.objectSpec, []byte(yamlConfig))\n\tif !vr.Valid() {\n\t\treturn nil, fmt.Errorf(\"validate spec failed: \\n%s\", vr)\n\t}\n\n\treturn s, nil\n}", "func (d DurationSeconds) MarshalYAML() (interface{}, error) {\n\tif !d.IsPresent() {\n\t\treturn nil, nil\n\t}\n\n\treturn int(d.value / time.Second), nil\n}", "func Marshal(ds interface{}, spec *Spec) (buf *bytes.Buffer) {\n\tMap(buf, ds, spec)\n\treturn\n}", "func (i *Info) YAMLString() string {\n\treturn marshal.SafeYAML(i.ctx, netPrinter{i})\n}", "func (k *Kluster) YAML() ([]byte, error) {\n\treturn yaml.Marshal(k)\n}", "func MarshalYAMLWithDescriptions(val interface{}) (interface{}, error) {\n\ttp := reflect.TypeOf(val)\n\tif tp.Kind() == reflect.Ptr {\n\t\ttp = tp.Elem()\n\t}\n\n\tif tp.Kind() != reflect.Struct {\n\t\treturn nil, fmt.Errorf(\"only structs are supported\")\n\t}\n\n\tv := reflect.ValueOf(val)\n\tif v.Kind() == reflect.Ptr {\n\t\tv = v.Elem()\n\t}\n\n\tb, err := yaml.Marshal(v.Interface())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar node yaml.Node\n\terr = yaml.Unmarshal(b, &node)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !DisableYAMLMarshalComments {\n\t\tfor _, n := range node.Content[0].Content {\n\t\t\tfor i := 0; i < v.NumField(); i++ {\n\t\t\t\tfieldType := tp.Field(i)\n\t\t\t\tname := strings.Split(fieldType.Tag.Get(\"yaml\"), \",\")[0]\n\n\t\t\t\tif name == \"\" {\n\t\t\t\t\tname = fieldType.Name\n\t\t\t\t}\n\n\t\t\t\tif n.Value == name {\n\t\t\t\t\tdesc := fieldType.Tag.Get(\"description\")\n\t\t\t\t\tn.HeadComment = wordwrap.WrapString(desc, 80) + \".\"\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\tnode.Kind = yaml.MappingNode\n\tnode.Content = node.Content[0].Content\n\n\treturn &node, nil\n}", "func (s *Spec) YAMLConfig() string {\n\treturn s.yamlConfig\n}", "func Marshal(ctx context.Context, obj interface{}, paths ...string) (string, error) {\n\trequestYaml, err := yaml.MarshalContext(ctx, obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfile, err := parser.ParseBytes(requestYaml, 0)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// normalize the structure converting the byte slice fields to string\n\tfor _, path := range paths {\n\t\tpathString, err := yaml.PathString(path)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tvar byteSlice []byte\n\t\terr = pathString.Read(strings.NewReader(string(requestYaml)), &byteSlice)\n\t\tif err != nil && !errors.Is(err, yaml.ErrNotFoundNode) {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif err := pathString.ReplaceWithReader(file,\n\t\t\tstrings.NewReader(string(byteSlice)),\n\t\t); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn file.String(), nil\n}", "func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) {\n\taccAddr, err := sdk.AccAddressFromBech32(pva.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := vestingAccountYAML{\n\t\tAddress: accAddr,\n\t\tAccountNumber: pva.AccountNumber,\n\t\tPubKey: getPKString(pva),\n\t\tSequence: pva.Sequence,\n\t\tOriginalVesting: pva.OriginalVesting,\n\t\tDelegatedFree: pva.DelegatedFree,\n\t\tDelegatedVesting: pva.DelegatedVesting,\n\t\tEndTime: pva.EndTime,\n\t\tStartTime: pva.StartTime,\n\t\tVestingPeriods: pva.VestingPeriods,\n\t}\n\treturn marshalYaml(out)\n}", "func (cp *CertPool) MarshalYAML() (interface{}, error) {\n\treturn cp.Files, nil\n}", "func (c *Config) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}", "func (c Configuration) YAML() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}" ]
[ "0.6445463", "0.6326264", "0.63029575", "0.63027453", "0.6261498", "0.6249017", "0.6187328", "0.6172001", "0.61505026", "0.6124385", "0.6124385", "0.60929036", "0.6092049", "0.6075512", "0.6065055", "0.6051939", "0.60301274", "0.6030115", "0.59681195", "0.5957629", "0.5953704", "0.5945245", "0.59346616", "0.5909714", "0.5906009", "0.59037775", "0.5888819", "0.58877563", "0.58747125", "0.5853025", "0.5847595", "0.5847595", "0.5839862", "0.583814", "0.57943624", "0.57855004", "0.57724804", "0.5764962", "0.575372", "0.5744729", "0.5737275", "0.5733952", "0.5727749", "0.57028157", "0.5699345", "0.5690758", "0.56791556", "0.5663087", "0.5655797", "0.5628871", "0.5624484", "0.56092685", "0.55970806", "0.55577993", "0.5537346", "0.55356485", "0.55245644", "0.5509427", "0.55083025", "0.55067366", "0.55059403", "0.5491867", "0.5478284", "0.5471918", "0.5466596", "0.5452316", "0.54491645", "0.5448204", "0.5445538", "0.5419312", "0.54036134", "0.5380504", "0.53796977", "0.53733927", "0.53657824", "0.5339991", "0.5335069", "0.5323552", "0.5321177", "0.53053194", "0.529901", "0.5292113", "0.5282602", "0.52774143", "0.52687675", "0.52466124", "0.52345896", "0.52194", "0.5203625", "0.5148877", "0.5118096", "0.5096668", "0.50576216", "0.50437355", "0.5042614", "0.50336516", "0.5029468", "0.50288075", "0.5007143", "0.50058573" ]
0.77819127
0
OK, nothing special here
func Hash(data []byte) [blake2b.Size]byte { return blake2b.Sum512(data) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func curate(file *pe.File) []byte {\n\n\tm := make(map[string]interface{})\n\tfields := make([]string, 0)\n\n\tif file.HasDOSHdr {\n\t\tm[\"dos_header\"] = file.DOSHeader\n\t\tfields = append(fields, \"dos_header\")\n\t}\n\n\tif file.HasRichHdr {\n\t\tm[\"rich_header\"] = file.RichHeader\n\t\tfields = append(fields, \"rich_header\")\n\t}\n\n\tif file.HasCOFF {\n\t\tm[\"coff\"] = file.COFF\n\t\tfields = append(fields, \"coff\")\n\t}\n\n\tif file.HasNTHdr {\n\t\tm[\"nt_header\"] = file.NtHeader\n\t\tfields = append(fields, \"nt_header\")\n\t}\n\n\tif file.HasSections {\n\t\tm[\"sections\"] = file.Sections\n\t\tfields = append(fields, \"sections\")\n\t}\n\n\tif file.HasExport {\n\t\tm[\"export\"] = file.Export\n\t\tfields = append(fields, \"export\")\n\t}\n\n\tif file.HasImport {\n\t\tm[\"import\"] = file.Imports\n\t\tfields = append(fields, \"import\")\n\t}\n\n\tif file.HasResource {\n\t\tm[\"resource\"] = file.Resources\n\t\tfields = append(fields, \"resource\")\n\t}\n\n\tif file.HasException {\n\t\tm[\"exception\"] = file.Exceptions\n\t\tfields = append(fields, \"exception\")\n\t}\n\n\tif file.HasReloc {\n\t\tm[\"reloc\"] = file.Relocations\n\t\tfields = append(fields, \"reloc\")\n\t}\n\n\tif file.HasDebug {\n\t\tm[\"debug\"] = file.Debugs\n\t\tfields = append(fields, \"debug\")\n\t}\n\n\tif file.HasGlobalPtr {\n\t\tm[\"global_ptr\"] = file.GlobalPtr\n\t\tfields = append(fields, \"global_ptr\")\n\t}\n\n\tif file.HasTLS {\n\t\tm[\"tls\"] = file.TLS\n\t\tfields = append(fields, \"tls\")\n\t}\n\n\tif file.HasLoadCFG {\n\t\tm[\"load_config\"] = file.LoadConfig\n\t\tfields = append(fields, \"load_config\")\n\t}\n\n\tif file.HasBoundImp {\n\t\tm[\"bound_import\"] = file.BoundImports\n\t\tfields = append(fields, \"bound_import\")\n\t}\n\n\tif file.HasIAT {\n\t\tm[\"iat\"] = file.IAT\n\t\tfields = append(fields, \"iat\")\n\t}\n\n\tif file.HasDelayImp {\n\t\tm[\"delay_import\"] = file.DelayImports\n\t\tfields = append(fields, \"delay_import\")\n\t}\n\n\tif file.HasCLR {\n\t\tm[\"clr\"] = file.CLR\n\t\tfields = append(fields, \"clr\")\n\t}\n\n\tif file.HasSecurity {\n\t\tm[\"security\"] = file.Certificates\n\t\tif file.IsSigned {\n\t\t\tif file.Certificates.Verified {\n\t\t\t\tm[\"signature\"] = \"Signed file, valid signature\"\n\t\t\t} else {\n\t\t\t\tm[\"signature\"] = \"Signed file, invalid signature\"\n\t\t\t}\n\t\t}\n\t\tfields = append(fields, \"security\")\n\t} else {\n\t\tm[\"signature\"] = \"File is not signed\"\n\t}\n\n\tm[\"meta\"] = fields\n\treturn toJSON(m)\n}", "func _() {\n\tX(Interface[*F /* ERROR got 1 arguments but 2 type parameters */ [string]](Impl{}))\n}", "func init() {}", "func init() {}", "func init() {}", "func init() {}", "func (e rawEntry) value(buf []byte) rawValue { return buf[e.ptr():][:e.sz()] }", "func (mtr *Dppdpp0intreg1Metrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"ErrPhvSopNoEop\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrPhvSopNoEop.Size()\n\n\tif fldName == \"ErrPhvEopNoSop\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrPhvEopNoSop.Size()\n\n\tif fldName == \"ErrOhiSopNoEop\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrOhiSopNoEop.Size()\n\n\tif fldName == \"ErrOhiEopNoSop\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrOhiEopNoSop.Size()\n\n\tif fldName == \"ErrFramerCreditOverrun\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrFramerCreditOverrun.Size()\n\n\tif fldName == \"ErrPacketsInFlightCreditOverrun\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrPacketsInFlightCreditOverrun.Size()\n\n\tif fldName == \"ErrNullHdrVld\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrNullHdrVld.Size()\n\n\tif fldName == \"ErrNullHdrfldVld\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrNullHdrfldVld.Size()\n\n\tif fldName == \"ErrMaxPktSize\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrMaxPktSize.Size()\n\n\tif fldName == \"ErrMaxActiveHdrs\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrMaxActiveHdrs.Size()\n\n\tif fldName == \"ErrPhvNoDataReferenceOhi\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrPhvNoDataReferenceOhi.Size()\n\n\tif fldName == \"ErrCsumMultipleHdr\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumMultipleHdr.Size()\n\n\tif fldName == \"ErrCsumMultipleHdrCopy\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumMultipleHdrCopy.Size()\n\n\tif fldName == \"ErrCrcMultipleHdr\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCrcMultipleHdr.Size()\n\n\tif fldName == \"ErrPtrFifoCreditOverrun\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrPtrFifoCreditOverrun.Size()\n\n\tif fldName == \"ErrClipMaxPktSize\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrClipMaxPktSize.Size()\n\n\tif fldName == \"ErrMinPktSize\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrMinPktSize.Size()\n\n\treturn offset\n}", "func (mtr *Dppdpp1intreg1Metrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"ErrPhvSopNoEop\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrPhvSopNoEop.Size()\n\n\tif fldName == \"ErrPhvEopNoSop\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrPhvEopNoSop.Size()\n\n\tif fldName == \"ErrOhiSopNoEop\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrOhiSopNoEop.Size()\n\n\tif fldName == \"ErrOhiEopNoSop\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrOhiEopNoSop.Size()\n\n\tif fldName == \"ErrFramerCreditOverrun\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrFramerCreditOverrun.Size()\n\n\tif fldName == \"ErrPacketsInFlightCreditOverrun\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrPacketsInFlightCreditOverrun.Size()\n\n\tif fldName == \"ErrNullHdrVld\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrNullHdrVld.Size()\n\n\tif fldName == \"ErrNullHdrfldVld\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrNullHdrfldVld.Size()\n\n\tif fldName == \"ErrMaxPktSize\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrMaxPktSize.Size()\n\n\tif fldName == \"ErrMaxActiveHdrs\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrMaxActiveHdrs.Size()\n\n\tif fldName == \"ErrPhvNoDataReferenceOhi\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrPhvNoDataReferenceOhi.Size()\n\n\tif fldName == \"ErrCsumMultipleHdr\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumMultipleHdr.Size()\n\n\tif fldName == \"ErrCsumMultipleHdrCopy\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumMultipleHdrCopy.Size()\n\n\tif fldName == \"ErrCrcMultipleHdr\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCrcMultipleHdr.Size()\n\n\tif fldName == \"ErrPtrFifoCreditOverrun\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrPtrFifoCreditOverrun.Size()\n\n\tif fldName == \"ErrClipMaxPktSize\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrClipMaxPktSize.Size()\n\n\tif fldName == \"ErrMinPktSize\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrMinPktSize.Size()\n\n\treturn offset\n}", "func TestGetNone4A(t *testing.T) {\n}", "func TestEmptyPrewrite4A(t *testing.T) {\n}", "func(this*Window)Write(p[]byte)(int,error){\nf,err:=this.File(\"body\")\nif err!=nil{\nreturn 0,err\n}\n\n\n/*71:*/\n\n\n//line goacme.w:1016\n\nf= &wrapper{f:f}\n\n\n\n\n\n/*:71*/\n\n\n//line goacme.w:244\n\nreturn f.Write(p)\n}", "func (c *Create ) MagicNumberMap() {\n\n}", "func (e *elf) rep() {\n\n\tfmt.Println(\"Pass\")\n\n}", "func (r *importReader) pos() {\n\tif r.int64() != deltaNewFile {\n\t} else if l := r.int64(); l == -1 {\n\t} else {\n\t\tr.string()\n\t}\n}", "func (object MQObject) getInternal(gomd *MQMD,\n\tgogmo *MQGMO, buffer []byte, useCap bool) (int, error) {\n\n\tvar mqrc C.MQLONG\n\tvar mqcc C.MQLONG\n\tvar mqmd C.MQMD\n\tvar mqgmo C.MQGMO\n\tvar datalen C.MQLONG\n\tvar ptr C.PMQVOID\n\n\terr := checkMD(gomd, \"MQGET\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\terr = checkGMO(gogmo, \"MQGET\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tbufflen := 0\n\tif useCap {\n\t\tbufflen = cap(buffer)\n\t} else {\n\t\tbufflen = len(buffer)\n\t}\n\n\tcopyMDtoC(&mqmd, gomd)\n\tcopyGMOtoC(&mqgmo, gogmo)\n\n\tif bufflen > 0 {\n\t\t// There has to be something in the buffer for CGO to be able to\n\t\t// find its address. We know there's space backing the buffer so just\n\t\t// set the first byte to something.\n\t\tif useCap && len(buffer) == 0 {\n\t\t\tbuffer = append(buffer, 0)\n\t\t}\n\t\tptr = (C.PMQVOID)(unsafe.Pointer(&buffer[0]))\n\t} else {\n\t\tptr = nil\n\t}\n\n\tC.MQGET(object.qMgr.hConn, object.hObj, (C.PMQVOID)(unsafe.Pointer(&mqmd)),\n\t\t(C.PMQVOID)(unsafe.Pointer(&mqgmo)),\n\t\t(C.MQLONG)(bufflen),\n\t\tptr,\n\t\t&datalen,\n\t\t&mqcc, &mqrc)\n\n\tgodatalen := int(datalen)\n\tcopyMDfromC(&mqmd, gomd)\n\tcopyGMOfromC(&mqgmo, gogmo)\n\n\tmqreturn := MQReturn{MQCC: int32(mqcc),\n\t\tMQRC: int32(mqrc),\n\t\tverb: \"MQGET\",\n\t}\n\n\tif mqcc != C.MQCC_OK {\n\t\treturn godatalen, &mqreturn\n\t}\n\n\treturn godatalen, nil\n\n}", "func (ce *mySpiderError) genFullErrMsg() {\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"Spider Error:\")\n\tif ce.errType != \"\" {\n\t\tbuffer.WriteString(string(ce.errType))\n\t\tbuffer.WriteString(\": \")\n\t}\n\tbuffer.WriteString(ce.errMsg)\n\n\tce.fullErrMsg = fmt.Sprintf(\"%s\\n\", buffer.String())\n}", "func _(s struct{A0}) { s.A0 = x0 }", "func G() {}", "func CQO() { ctx.CQO() }", "func (self *Rectangle) GetPoint1O(position int) *Point{\n return &Point{self.Object.Call(\"getPoint\", position)}\n}", "func (q *dnsQuestion) getQuestion(req []byte, offset uint16, head *dnsHeader) {\n\tost := offset\n\ttmp := ost\n\tost = q.getQName(req, ost)\n\tq.qType = binary.BigEndian.Uint16(req[ost : ost+twoByteSize])\n\tost += twoByteSize\n\tq.qClass = binary.BigEndian.Uint16(req[ost : ost+twoByteSize])\n\tost += twoByteSize\n\tq.head = head\n\tq.queByte = req[tmp:ost]\n}", "func ret(v *vm.State, _ vm.Opcode) error {\n\tvar err error\n\tv.SP -= 2\n\tv.PC, err = v.PointerAt(v.SP)\n\treturn err\n}", "func pyrs(play *legends) { //\"u\" , pointer getinto that address and get the value of the address\n\tfmt.Println(play.dhoni)\n\tfmt.Println(play.virat)\n\tfmt.Println(play.rohit)\n\tfmt.Println(play.no1)\n\tfmt.Println(play.no2)\n\tfmt.Println(play.no3)\n}", "func (self *SinglePad) Index() int{\n return self.Object.Get(\"index\").Int()\n}", "func init() {\n\t//todo...\n}", "func TestSinglePrewrite4A(t *testing.T) {\n}", "func ByteOrder() binary.ByteOrder { return byteOrder }", "func init_node(node int32){\nname_dir[node].equiv= -1\n}", "func (p *literalProcessor) name() string { return \"\" }", "func (px *Paxos) status(Seq int) (Fate, interface{}) {\n\t// Your code here.\n\tpx.mu.Lock()\n\tdefer px.mu.Unlock()\n\tVal, ok := px.Stati[Seq]\n\n\tif !ok {\n\t\treturn Pending, nil\n\t}\n\n\tif Val == Decided {\n\t\t// return Decided, px.result[Seq]\n\t\treturn Decided, px.Val[Seq]\n\t}\n\treturn Val, nil\n}", "func _[A any](s S /* ERROR got 1 arguments but 2 type parameters */ [A]) {\n\t// we should see no follow-on errors below\n\ts.f = 1\n\ts.m()\n}", "func (InvertingInt32SliceIterator) Err() error { return nil }", "func (tw *Topwords) get_inserter() func(uint8) {\n\tcurrent := &tw.start\n\tinword := false\n\n\treturn func(b uint8) {\n\t\tb = filterToLower(b)\n\n\t\tif b == ' ' {\n\t\t\t//fmt.Printf(\"_\")\n\t\t\tif inword {\n\t\t\t\tif current.word_count == 0 {\n\t\t\t\t\ttw.uniquewordcount += 1\n\t\t\t\t}\n\t\t\t\tcurrent.word_count += 1\n\t\t\t\tcurrent = &tw.start // Start at the beginning again\n\t\t\t}\n\t\t\tinword = false\n\t\t\treturn\n\t\t}\n\t\t//fmt.Printf(\"%v\", string(b))\n\t\tinword = true\n\t\tchildren := &(current.children)\n\t\tfor e := range *children {\n\t\t\tif (*children)[e].char == b {\n\t\t\t\t//fmt.Printf(\"<\")\n\t\t\t\tcurrent = (*children)[e]\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\t//fmt.Printf(\"^\")\n\t\tnew_node := &Node{b, 0, nil}\n\t\tcurrent.children = append(current.children, new_node)\n\t\tcurrent = new_node\n\t\t// fmt.Printf(\"\\n+%v\\n\", current.children)\n\t\treturn\n\n\t}\n\n}", "func (e *binaryExprEvaluator) name() string { return \"\" }", "func getMarker(bloc,data []byte)Marker{\n\tmarker := hex.EncodeToString(bloc[0:2])\n\ttypeMarker := intReader.ReadInt16(bloc[2:4])\n\tlength := intReader.ReadInt32(bloc[4:8])\n\tvar formatData interface{}\n\tswitch typeMarker {\n\tcase 2 :\n\t\tif length > 4 {\n\t\t\t// Read data at offset\n\t\t\toffset := intReader.ReadInt32(bloc[8:])\n\t\t\tformatData = string(data[offset:offset+length])\n\t\t}else{\n\t\t\tformatData = string(bloc)\n\t\t}\n\tcase 3 : formatData = intReader.ReadInt16(bloc[8:])\n\tcase 4 : formatData = intReader.ReadInt32(bloc[8:])\n\t\tdefault:formatData = bloc[8:]\n\t}\n\n\treturn Marker{marker,typeMarker,length,formatData}\n}", "func TestPrewriteMultiple4A(t *testing.T) {\n}", "func getMetaTimeEvent(inputFile string, hdrData []string) MetaHDR {\n\tvar metaHdrTmEnvt MetaHDR\n\t// hdrData := GetHeader(inputFile)\n\tfor index, hdrName := range hdrData {\n\t\tmetaTmEvntStructVal := reflect.ValueOf(&metaHdrTmEnvt)\n\t\tstructField := metaTmEvntStructVal.Elem().FieldByName(strings.ToUpper(hdrName))\n\t\tif structField.IsValid() {\n\t\t\tstructField.SetInt(int64(index))\n\t\t}\n\t}\n\treturn metaHdrTmEnvt\n}", "func (Int32SliceIterator) Err() error { return nil }", "func (mtr *Dppdpp0intcreditMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"PtrCreditOvflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.PtrCreditOvflow.Size()\n\n\tif fldName == \"PtrCreditUndflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.PtrCreditUndflow.Size()\n\n\tif fldName == \"PktCreditOvflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.PktCreditOvflow.Size()\n\n\tif fldName == \"PktCreditUndflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.PktCreditUndflow.Size()\n\n\tif fldName == \"FramerCreditOvflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.FramerCreditOvflow.Size()\n\n\tif fldName == \"FramerCreditUndflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.FramerCreditUndflow.Size()\n\n\tif fldName == \"FramerHdrfldVldOvfl\" {\n\t\treturn offset\n\t}\n\toffset += mtr.FramerHdrfldVldOvfl.Size()\n\n\tif fldName == \"FramerHdrfldOffsetOvfl\" {\n\t\treturn offset\n\t}\n\toffset += mtr.FramerHdrfldOffsetOvfl.Size()\n\n\tif fldName == \"ErrFramerHdrsizeZeroOvfl\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrFramerHdrsizeZeroOvfl.Size()\n\n\treturn offset\n}", "func (self *Graphics) _generateCachedSprite() {\n self.Object.Call(\"_generateCachedSprite\")\n}", "func Dummy() {}", "func Dummy() {}", "func pudding_stir(prime *pudding) {\n\n}", "func fillInStackTrace(frame *rtdata.Frame) {\n\t// 获取局部变量表第0位,this引用\n\tthis := frame.LocalVars().GetThis()\n\t// 将this引用入栈\n\tframe.OperandStack().PushRef(this)\n\t// 创建完整的堆栈打印信息\n\tstes := createStackTraceElements(this, frame.Thread())\n\t// 将完整的堆栈信息赋值到异常类实例(this)的extra字段中,athrow指令中打印了extra信息\n\tthis.SetExtra(stes)\n}", "func (mtr *Mcmc1mchintmcMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"Ecc_1BitThreshPs1\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Ecc_1BitThreshPs1.Size()\n\n\tif fldName == \"Ecc_1BitThreshPs0\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Ecc_1BitThreshPs0.Size()\n\n\treturn offset\n}", "func(this*wrapper)Read(p[]byte)(int,error){\nreturn this.f.Read(p)\n}", "func printErr (err error){ // this function is used for printing error\r\n if err != nil{\r\n fmt.Println(err)\r\n }\r\n }", "func Umagic(m *Magic)", "func (mtr *Dprdpr1intreg1Metrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"ErrPhvSopNoEop\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrPhvSopNoEop.Size()\n\n\tif fldName == \"ErrPhvEopNoSop\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrPhvEopNoSop.Size()\n\n\tif fldName == \"ErrOhiSopNoEop\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrOhiSopNoEop.Size()\n\n\tif fldName == \"ErrOhiEopNoSop\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrOhiEopNoSop.Size()\n\n\tif fldName == \"ErrPktinSopNoEop\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrPktinSopNoEop.Size()\n\n\tif fldName == \"ErrPktinEopNoSop\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrPktinEopNoSop.Size()\n\n\tif fldName == \"ErrCsumOffsetGtPktSize_4\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumOffsetGtPktSize_4.Size()\n\n\tif fldName == \"ErrCsumOffsetGtPktSize_3\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumOffsetGtPktSize_3.Size()\n\n\tif fldName == \"ErrCsumOffsetGtPktSize_2\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumOffsetGtPktSize_2.Size()\n\n\tif fldName == \"ErrCsumOffsetGtPktSize_1\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumOffsetGtPktSize_1.Size()\n\n\tif fldName == \"ErrCsumOffsetGtPktSize_0\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumOffsetGtPktSize_0.Size()\n\n\tif fldName == \"ErrCsumPhdrOffsetGtPktSize_4\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumPhdrOffsetGtPktSize_4.Size()\n\n\tif fldName == \"ErrCsumPhdrOffsetGtPktSize_3\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumPhdrOffsetGtPktSize_3.Size()\n\n\tif fldName == \"ErrCsumPhdrOffsetGtPktSize_2\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumPhdrOffsetGtPktSize_2.Size()\n\n\tif fldName == \"ErrCsumPhdrOffsetGtPktSize_1\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumPhdrOffsetGtPktSize_1.Size()\n\n\tif fldName == \"ErrCsumPhdrOffsetGtPktSize_0\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumPhdrOffsetGtPktSize_0.Size()\n\n\tif fldName == \"ErrCsumLocGtPktSize_4\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumLocGtPktSize_4.Size()\n\n\tif fldName == \"ErrCsumLocGtPktSize_3\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumLocGtPktSize_3.Size()\n\n\tif fldName == \"ErrCsumLocGtPktSize_2\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumLocGtPktSize_2.Size()\n\n\tif fldName == \"ErrCsumLocGtPktSize_1\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumLocGtPktSize_1.Size()\n\n\tif fldName == \"ErrCsumLocGtPktSize_0\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumLocGtPktSize_0.Size()\n\n\tif fldName == \"ErrCrcOffsetGtPktSize\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCrcOffsetGtPktSize.Size()\n\n\tif fldName == \"ErrCrcLocGtPktSize\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCrcLocGtPktSize.Size()\n\n\tif fldName == \"ErrPtrFfOverflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrPtrFfOverflow.Size()\n\n\tif fldName == \"ErrCsumFfOverflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrCsumFfOverflow.Size()\n\n\tif fldName == \"ErrPktoutFfOverflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrPktoutFfOverflow.Size()\n\n\treturn offset\n}", "func (mtr *Mcmc0mchintmcMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"Ecc_1BitThreshPs1\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Ecc_1BitThreshPs1.Size()\n\n\tif fldName == \"Ecc_1BitThreshPs0\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Ecc_1BitThreshPs0.Size()\n\n\treturn offset\n}", "func (mtr *Dppdpp1intcreditMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"PtrCreditOvflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.PtrCreditOvflow.Size()\n\n\tif fldName == \"PtrCreditUndflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.PtrCreditUndflow.Size()\n\n\tif fldName == \"PktCreditOvflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.PktCreditOvflow.Size()\n\n\tif fldName == \"PktCreditUndflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.PktCreditUndflow.Size()\n\n\tif fldName == \"FramerCreditOvflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.FramerCreditOvflow.Size()\n\n\tif fldName == \"FramerCreditUndflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.FramerCreditUndflow.Size()\n\n\tif fldName == \"FramerHdrfldVldOvfl\" {\n\t\treturn offset\n\t}\n\toffset += mtr.FramerHdrfldVldOvfl.Size()\n\n\tif fldName == \"FramerHdrfldOffsetOvfl\" {\n\t\treturn offset\n\t}\n\toffset += mtr.FramerHdrfldOffsetOvfl.Size()\n\n\tif fldName == \"ErrFramerHdrsizeZeroOvfl\" {\n\t\treturn offset\n\t}\n\toffset += mtr.ErrFramerHdrsizeZeroOvfl.Size()\n\n\treturn offset\n}", "func setup(){}", "func(this*Window)File(file string)(io.ReadWriteSeeker,error){\nfid,ok:=this.files[file]\nif!ok{\nvar err error\nif fid,err= fsys.Open(fmt.Sprintf(\"%d/%s\",this.id,file),plan9.ORDWR);err!=nil{\nif fid,err= fsys.Open(fmt.Sprintf(\"%d/%s\",this.id,file),plan9.OREAD);err!=nil{\nif fid,err= fsys.Open(fmt.Sprintf(\"%d/%s\",this.id,file),plan9.OWRITE);err!=nil{\nreturn nil,err\n}\n}\n}\nthis.files[file]= fid\n}\nvar f io.ReadWriteSeeker= fid\n\n\n/*71:*/\n\n\n//line goacme.w:1016\n\nf= &wrapper{f:f}\n\n\n\n\n\n/*:71*/\n\n\n//line goacme.w:334\n\nreturn f,nil\n}", "func (ex extractors) execute(s *goquery.Selection) string {\n\tv := \"\"\n\tfor _, e := range ex {\n\t\tv, s = e(v, s)\n\t}\n\treturn v\n}", "func next(t traversal, e Elem) {\n\tswitch e := e.(type) {\n\tcase *Map:\n\t\tt.gMap(e)\n\tcase *Struct:\n\t\tt.gStruct(e)\n\tcase *Slice:\n\t\tt.gSlice(e)\n\tcase *Array:\n\t\tt.gArray(e)\n\tcase *Ptr:\n\t\tt.gPtr(e)\n\tcase *BaseElem:\n\t\tt.gBase(e)\n\tdefault:\n\t\tpanic(\"bad element type\")\n\t}\n}", "func (mtr *Mcmc2mchintmcMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"Ecc_1BitThreshPs1\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Ecc_1BitThreshPs1.Size()\n\n\tif fldName == \"Ecc_1BitThreshPs0\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Ecc_1BitThreshPs0.Size()\n\n\treturn offset\n}", "func (p *LapJoin) do_add(key string, d LapData, src string){\n //src:=d.From\n index:=-1\n for i,str:=range(p.sources){\n if str==src {index=i;break;}\n }\n\n if index==-1 {\n LapLog(\"JOIN ERROR: bad source: '%s' (%+v)\",src,d)\n return\n }\n n,ok:=d.GetNum(p.maps[src][0])\n if ok {\n dd:=p.elements[key].data\n dd.AddNumber(p.maps[src][1],n)\n p.elements[key].got[index]=true\n delete(p.elements[key].data.NumFields,p.maps[src][0])\n //LapLog(\"JOIN ADDED: '%s' %d from=%s %v (%s)\",key,index,src,p.elements[key].data,p.maps[src][0])\n }else{\n s,ok2:=d.GetStr(p.maps[src][0])\n if ok2 {\n dd:=p.elements[key].data\n dd.AddString(p.maps[src][1],s)\n p.elements[key].got[index]=true\n delete(p.elements[key].data.StrFields,p.maps[src][0])\n //LapLog(\"JOIN ADDED: '%s' %d from=%s %v (%s)\",key,index,src,p.elements[key].data,p.maps[src][0])\n }else{\n\n LapLog(\"JOIN ERROR: no requested field '%s' from source '%s' [%+v]\",p.maps[src][0], src,d)\n return\n }\n }\n}", "func getDummyHeader(i int) []byte {\n\thdr := []byte{1, 0, 0, 0, 0, 0, 0, 0}\n\thdr[i] = 10\n\treturn hdr\n}", "func (mp *mirmap) access0(k voidptr, v *voidptr) int {\n\tv1 := mp.access1(k)\n\t// when key not exist, v1 will nil\n\tif v1 != nil {\n\t\tmemcpy3(v, v1, mp.valsz)\n\t\treturn 0\n\t}\n\treturn -1\n}", "func XGETBV() { ctx.XGETBV() }", "func (mtr *Mcmc0intmcMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"MchInt\" {\n\t\treturn offset\n\t}\n\toffset += mtr.MchInt.Size()\n\n\treturn offset\n}", "func stsf() {\n\tswitch typ = implicitArrayDeref(x.typ.Underlying()); t := typ.(type) {\n\tcase *Basic:\n\t}\n}", "func bug(err error) error {\n\treturn fmt.Errorf(\"BUG(go-landlock): This should not have happened: %w\", err)\n}", "func Supported() bool { return true }", "func (mtr *Mcmc4mchintmcMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"Ecc_1BitThreshPs1\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Ecc_1BitThreshPs1.Size()\n\n\tif fldName == \"Ecc_1BitThreshPs0\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Ecc_1BitThreshPs0.Size()\n\n\treturn offset\n}", "func self(i Instruction, ls *LuaState) {\n\ta, b, c := i.ABC()\n\ta += 1\n\tb += 1\n\n\tluaCopy(ls, b, a+1)\n\tls.getRK(c)\n\tluaGetTable(ls, b)\n\tluaReplace(ls, a)\n}", "func (self *mergeState) getPoint(fields []string, p *protocol.Point) *protocol.Point {\n\tif !self.modifyValues {\n\t\treturn p\n\t}\n\n\tnewValues := make([]*protocol.FieldValue, len(self.fields))\n\toldValues := p.Values\n\tfor idx, f := range fields {\n\t\tnewIdx := self.fields[f]\n\t\tnewValues[newIdx] = oldValues[idx]\n\t}\n\tp.Values = newValues\n\treturn p\n}", "func escrever2() {\n\tfmt.Println(\"Auxiliar 2\")\n}", "func (mtr *Mcmc7mchintmcMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"Ecc_1BitThreshPs1\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Ecc_1BitThreshPs1.Size()\n\n\tif fldName == \"Ecc_1BitThreshPs0\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Ecc_1BitThreshPs0.Size()\n\n\treturn offset\n}", "func main() {\n\ta := Gps4dLoc{}\n\ta.Lati = 23.333\n\ta.Long = 123.3333\n\n\tugi := UserGpsInfo{}\n\tugi.CurrentLoc.Lati = 12.3\n\tugi.CurrentLoc.Long = 123.333\n\ttestloc := Gps2dLoc{12.3, 22.3}\n\n\tif ugi.CameraLoc.Loc == nil {\n\t\tfmt.Println(\"cameraloc is nil\")\n\t\tfmt.Println(ugi.CameraLoc)\n\t\tugi.CameraLoc.Loc = append(ugi.CameraLoc.Loc, testloc)\n\t\tfmt.Println(len(ugi.CameraLoc.Loc))\n\t\tfmt.Println(\"shoelati\", ugi.CameraLoc.Loc[0].Lati)\n\t} else {\n\t\tfmt.Println(\"shoelati\", ugi.CameraLoc.Loc[0].Lati)\n\t}\n\n\tif ugi.CreateLoc.Timestamp == 0 {\n\t\tfmt.Println(\"create loc is nil\")\n\t}\n\n}", "func (self *TileSprite) FrameName() string{\n return self.Object.Get(\"frameName\").String()\n}", "func readEvent(r io.Reader)(*Event,error){\no,t,b,e,f,s,err:=readFields(r)\nif err!=nil{\nreturn nil,err\n}\nvar ev Event\n\n\n/*43:*/\n\n\n//line goacme.w:522\n\nswitch o{\ncase'E':ev.Origin= Edit\ncase'F':ev.Origin= File\ncase'K':ev.Origin= Keyboard\ncase'M':ev.Origin= Mouse\ndefault:return nil,ErrInvalidOrigin\n}\n\n\n\n/*:43*/\n\n\n//line goacme.w:482\n\n\n\n/*48:*/\n\n\n//line goacme.w:560\n\nswitch t{\ncase'D':ev.Type= Delete\ncase'd':ev.Type= Delete|Tag\ncase'I':ev.Type= Insert\ncase'i':ev.Type= Insert|Tag\ncase'L':ev.Type= Look\ncase'l':ev.Type= Look|Tag\ncase'X':ev.Type= Execute\ncase'x':ev.Type= Execute|Tag\ndefault:return nil,ErrInvalidType\n}\n\n\n\n/*:48*/\n\n\n//line goacme.w:483\n\n\n\n/*50:*/\n\n\n//line goacme.w:586\n\nev.begin= b\nev.Begin= b\nev.end= e\nev.End= e\n\n\n\n/*:50*/\n\n\n//line goacme.w:484\n\n\n\n/*52:*/\n\n\n//line goacme.w:608\n\nev.flag= f\n\nif ev.Type&Execute==Execute{\nev.IsBuiltin= (ev.flag&1)==1\n}else if ev.Type&Look==Look{\nev.NoLoad= (ev.flag&1)==1\nev.IsFile= (ev.flag&4)==4\n}\n\nev.Text= s\n\n// if there is an expansion\nif(ev.flag&2)==2{\n_,_,ev.Begin,ev.End,_,ev.Text,err= readFields(r)\nif err!=nil{\nreturn nil,err\n}\n}\n// if there is a chording\nif(ev.flag&8)==8{\n_,_,_,_,_,ev.Arg,err= readFields(r)\nif err!=nil{\nreturn nil,err\n}\n_,_,_,_,_,_,err= readFields(r)\nif err!=nil{\nreturn nil,err\n}\n}\n\n\n/*54:*/\n\n\n//line goacme.w:645\n\nif len(ev.Text)> 0{\nf:=strings.Fields(ev.Text)\nif len(f)> 1{\nev.Text= f[0]\ns:=ev.Arg\nif len(s)> 0{\ns= \" \"+ev.Arg\n}\nev.Arg= strings.Join(f[1:],\" \")+s\n}\n}\n\n\n\n\n/*:54*/\n\n\n//line goacme.w:638\n\n\n\n\n/*:52*/\n\n\n//line goacme.w:485\n\nreturn&ev,nil\n}", "func cgounimpl() {\n\tthrow(\"cgo not implemented\")\n}", "func (mtr *Mxmx0intmacMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"Lane0Sbe\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Lane0Sbe.Size()\n\n\tif fldName == \"Lane0Dbe\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Lane0Dbe.Size()\n\n\tif fldName == \"Lane1Sbe\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Lane1Sbe.Size()\n\n\tif fldName == \"Lane1Dbe\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Lane1Dbe.Size()\n\n\tif fldName == \"Lane2Sbe\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Lane2Sbe.Size()\n\n\tif fldName == \"Lane2Dbe\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Lane2Dbe.Size()\n\n\tif fldName == \"Lane3Sbe\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Lane3Sbe.Size()\n\n\tif fldName == \"Lane3Dbe\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Lane3Dbe.Size()\n\n\tif fldName == \"M0PbPbusDrdy\" {\n\t\treturn offset\n\t}\n\toffset += mtr.M0PbPbusDrdy.Size()\n\n\tif fldName == \"M1PbPbusDrdy\" {\n\t\treturn offset\n\t}\n\toffset += mtr.M1PbPbusDrdy.Size()\n\n\tif fldName == \"M2PbPbusDrdy\" {\n\t\treturn offset\n\t}\n\toffset += mtr.M2PbPbusDrdy.Size()\n\n\tif fldName == \"M3PbPbusDrdy\" {\n\t\treturn offset\n\t}\n\toffset += mtr.M3PbPbusDrdy.Size()\n\n\treturn offset\n}", "func TestPrewriteWritten4A(t *testing.T) {\n}", "func (mtr *Mxmx1intmacMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"Lane0Sbe\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Lane0Sbe.Size()\n\n\tif fldName == \"Lane0Dbe\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Lane0Dbe.Size()\n\n\tif fldName == \"Lane1Sbe\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Lane1Sbe.Size()\n\n\tif fldName == \"Lane1Dbe\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Lane1Dbe.Size()\n\n\tif fldName == \"Lane2Sbe\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Lane2Sbe.Size()\n\n\tif fldName == \"Lane2Dbe\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Lane2Dbe.Size()\n\n\tif fldName == \"Lane3Sbe\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Lane3Sbe.Size()\n\n\tif fldName == \"Lane3Dbe\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Lane3Dbe.Size()\n\n\tif fldName == \"M0PbPbusDrdy\" {\n\t\treturn offset\n\t}\n\toffset += mtr.M0PbPbusDrdy.Size()\n\n\tif fldName == \"M1PbPbusDrdy\" {\n\t\treturn offset\n\t}\n\toffset += mtr.M1PbPbusDrdy.Size()\n\n\tif fldName == \"M2PbPbusDrdy\" {\n\t\treturn offset\n\t}\n\toffset += mtr.M2PbPbusDrdy.Size()\n\n\tif fldName == \"M3PbPbusDrdy\" {\n\t\treturn offset\n\t}\n\toffset += mtr.M3PbPbusDrdy.Size()\n\n\treturn offset\n}", "func (mtr *Mcmc6mchintmcMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"Ecc_1BitThreshPs1\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Ecc_1BitThreshPs1.Size()\n\n\tif fldName == \"Ecc_1BitThreshPs0\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Ecc_1BitThreshPs0.Size()\n\n\treturn offset\n}", "func (mtr *Mcmc1intmcMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"MchInt\" {\n\t\treturn offset\n\t}\n\toffset += mtr.MchInt.Size()\n\n\treturn offset\n}", "func (mtr *Mcmc3mchintmcMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"Ecc_1BitThreshPs1\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Ecc_1BitThreshPs1.Size()\n\n\tif fldName == \"Ecc_1BitThreshPs0\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Ecc_1BitThreshPs0.Size()\n\n\treturn offset\n}", "func buildAux(aa []sam.Aux, buf *[]byte) {\n\tfor _, a := range aa {\n\t\t// TODO: validate each 'a'\n\t\t*buf = append(*buf, []byte(a)...)\n\t\tswitch a.Type() {\n\t\tcase 'Z', 'H':\n\t\t\t*buf = append(*buf, 0)\n\t\t}\n\t}\n}", "func field6(x *X) { // ERROR \"leaking param content: x$\"\n\tsink = x.p2 // ERROR \"x\\.p2 escapes to heap\"\n}", "func (mtr *Mxmx0inteccMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"Uncorrectable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Uncorrectable.Size()\n\n\tif fldName == \"Correctable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Correctable.Size()\n\n\treturn offset\n}", "func (mtr *Mcmc5mchintmcMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"Ecc_1BitThreshPs1\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Ecc_1BitThreshPs1.Size()\n\n\tif fldName == \"Ecc_1BitThreshPs0\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Ecc_1BitThreshPs0.Size()\n\n\treturn offset\n}", "func checkErr(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n}", "func (mtr *Dppdpp0intfifoMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"PhvFfOverflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.PhvFfOverflow.Size()\n\n\tif fldName == \"OhiFfOverflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.OhiFfOverflow.Size()\n\n\tif fldName == \"PktSizeFfOvflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.PktSizeFfOvflow.Size()\n\n\tif fldName == \"PktSizeFfUndflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.PktSizeFfUndflow.Size()\n\n\tif fldName == \"CsumPhvFfOvflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.CsumPhvFfOvflow.Size()\n\n\tif fldName == \"CsumPhvFfUndflow\" {\n\t\treturn offset\n\t}\n\toffset += mtr.CsumPhvFfUndflow.Size()\n\n\treturn offset\n}", "func onebitwalktype1(t *Type, xoffset *int64, bv Bvec) {\n\tif t.Align > 0 && *xoffset&int64(t.Align-1) != 0 {\n\t\tFatal(\"onebitwalktype1: invalid initial alignment, %v\", t)\n\t}\n\n\tswitch t.Etype {\n\tcase TINT8,\n\t\tTUINT8,\n\t\tTINT16,\n\t\tTUINT16,\n\t\tTINT32,\n\t\tTUINT32,\n\t\tTINT64,\n\t\tTUINT64,\n\t\tTINT,\n\t\tTUINT,\n\t\tTUINTPTR,\n\t\tTBOOL,\n\t\tTFLOAT32,\n\t\tTFLOAT64,\n\t\tTCOMPLEX64,\n\t\tTCOMPLEX128:\n\t\t*xoffset += t.Width\n\n\tcase TPTR32,\n\t\tTPTR64,\n\t\tTUNSAFEPTR,\n\t\tTFUNC,\n\t\tTCHAN,\n\t\tTMAP:\n\t\tif *xoffset&int64(Widthptr-1) != 0 {\n\t\t\tFatal(\"onebitwalktype1: invalid alignment, %v\", t)\n\t\t}\n\t\tbvset(bv, int32(*xoffset/int64(Widthptr))) // pointer\n\t\t*xoffset += t.Width\n\n\tcase TSTRING:\n\t\t// struct { byte *str; intgo len; }\n\t\tif *xoffset&int64(Widthptr-1) != 0 {\n\t\t\tFatal(\"onebitwalktype1: invalid alignment, %v\", t)\n\t\t}\n\t\tbvset(bv, int32(*xoffset/int64(Widthptr))) //pointer in first slot\n\t\t*xoffset += t.Width\n\n\tcase TINTER:\n\t\t// struct { Itab *tab;\tunion { void *ptr, uintptr val } data; }\n\t\t// or, when isnilinter(t)==true:\n\t\t// struct { Type *type; union { void *ptr, uintptr val } data; }\n\t\tif *xoffset&int64(Widthptr-1) != 0 {\n\t\t\tFatal(\"onebitwalktype1: invalid alignment, %v\", t)\n\t\t}\n\t\tbvset(bv, int32(*xoffset/int64(Widthptr))) // pointer in first slot\n\t\tbvset(bv, int32(*xoffset/int64(Widthptr)+1)) // pointer in second slot\n\t\t*xoffset += t.Width\n\n\tcase TARRAY:\n\t\t// The value of t->bound is -1 for slices types and >0 for\n\t\t// for fixed array types. All other values are invalid.\n\t\tif t.Bound < -1 {\n\t\t\tFatal(\"onebitwalktype1: invalid bound, %v\", t)\n\t\t}\n\t\tif Isslice(t) {\n\t\t\t// struct { byte *array; uintgo len; uintgo cap; }\n\t\t\tif *xoffset&int64(Widthptr-1) != 0 {\n\t\t\t\tFatal(\"onebitwalktype1: invalid TARRAY alignment, %v\", t)\n\t\t\t}\n\t\t\tbvset(bv, int32(*xoffset/int64(Widthptr))) // pointer in first slot (BitsPointer)\n\t\t\t*xoffset += t.Width\n\t\t} else {\n\t\t\tfor i := int64(0); i < t.Bound; i++ {\n\t\t\t\tonebitwalktype1(t.Type, xoffset, bv)\n\t\t\t}\n\t\t}\n\n\tcase TSTRUCT:\n\t\to := int64(0)\n\t\tvar fieldoffset int64\n\t\tfor t1 := t.Type; t1 != nil; t1 = t1.Down {\n\t\t\tfieldoffset = t1.Width\n\t\t\t*xoffset += fieldoffset - o\n\t\t\tonebitwalktype1(t1.Type, xoffset, bv)\n\t\t\to = fieldoffset + t1.Type.Width\n\t\t}\n\n\t\t*xoffset += t.Width - o\n\n\tdefault:\n\t\tFatal(\"onebitwalktype1: unexpected type, %v\", t)\n\t}\n}", "func (node *selfNode) checkMetaHeader(elemType reflect.Type) error {\n\n\theader := node.head.String()\n\tkind := elemType.Kind()\n\n\tif kind == reflect.Slice || kind == reflect.Array {\n\t\t// Packing a slice of slices requires the [] (empty string) header.\n\t\tif len(header) != 0 {\n\t\t\treturn node.head.newPackError(\"slice head has value `\" + header + \"` instead of []\")\n\t\t}\n\n\t} else if kind == reflect.Struct || kind == reflect.Map {\n\t\t// Packing a slice of structs or maps. Requires the type name as header or a bullet point.\n\t\tif !isBulletPoint(header) && header != elemType.Name() {\n\t\t\treturn node.head.newPackError(\"struct head has value `\" + header + \"` instead of bullet or `\" + elemType.Name() + \"`\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func check_complete(){\nif len(change_buffer)> 0{/* changing is false */\nbuffer= change_buffer\nchange_buffer= nil\nchanging= true\nchange_depth= include_depth\nloc= 0\nerr_print(\"! Change file entry did not match\")\n\n}\n}", "func (r *Reader) nextUnit() {\n\tr.unit++\n\tu := &r.d.unit[r.unit]\n\tr.b = makeBuf(r.d, u, \"info\", u.off, u.data)\n\tr.cu = nil\n}", "func (px *Paxos) Status(seq int) (bool, interface{}) {\n // Your code here.\n DPrintf(\"Paxos %v is getting status ...\\n\", px.me)\n if seq < px.Min() {\n DPrintf(\"Required Status less than min available...\\n\")\n return false, nil\n }\n ins := px.getProp(seq)\n DPrintf(\"Return status '%v' with value %v...\\n\", ins.status, ins.v_a)\n return ins.status, ins.v_a\n}", "func Err2_1(){\n\t_, er := Err2(-1)\n\tif e1, ok := er.(*argError); ok {\n\t\tfmt.Println(e1.arg)\n\t\tfmt.Println(e1.prob)\n\t}\n}", "func (rpcServer * RPCServer)makeInsertsToSuccessor(){\n\t//open a read transaction\n\trpcServer.boltDB.View(func(tx *bolt.Tx) error {\n\t\tvar cursor *bolt.Cursor\n\t\tcursor = tx.Cursor()\n\t\t\n\t\tvar bucket *bolt.Bucket\n\t\t\n\n\t\t//traverse through all keys\n\t\tfor k, _ := cursor.First(); k != nil; k, _ = cursor.Next() {\n\t\t\tbucket = tx.Bucket(k)\n\t\t\t\n\t\t\t//traverse through all relation and value pairs\n\t\t\tbucket.ForEach(func(relation, value []byte) error {\n\t\t\t\t//create paramter - successor\n\t\t\t\n\t\t\t\t//add to array of interface\n\t\t\t\t\n\t\t\t\tparameterArray := make([]interface{},3)\n\t\t\t\tparameterArray[0] = string(k)\n\t\t\t\tparameterArray[1] = string(relation)\n\t\t\t\tparameterArray[2] = string(value)\n\t\t\t\t\n\n\t\t\t\t//create json message\n\t\t\t\tjsonMessage := rpcclient.RequestParameters{}\n\t\t\t\tjsonMessage.Method = \"Insert\";\n\t\t\t\tjsonMessage.Params = parameterArray\n\t\t\t\t\n\t\t\t\tjsonBytes,err :=json.Marshal(jsonMessage)\n\t\t\t\tif err!=nil{\n\t\t\t\t\trpcServer.logger.Println(err)\n\t\t\t\t\treturn err\n\t\t\t\t} \n \n\t\t\t\trpcServer.logger.Println(string(jsonBytes))\n\n\t\t\t\tclientServerInfo,err := rpcServer.chordNode.PrepareClientServerInfo(rpcServer.chordNode.FingerTable[1])\n\t\t\t\tif err!=nil{\n\t\t\t\t\t\n\t\t\t\t\trpcServer.logger.Println(err)\n\t\t\t\t\treturn nil\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tclient := &rpcclient.RPCClient{}\n\t\t\t\terr, _ = client.RpcCall(clientServerInfo, string(jsonBytes))\n\t\t\t\t\n\t\t\t\tif err != nil {\n\t\t\t\t\trpcServer.logger.Println(err)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\treturn nil\n\t\t\t})\n\t\t}\n\t\treturn nil\n\t})\n\n}", "func (self* bestFit) state() ([]float64,[]float64,error) {\n\tif len(self.ys) < 2 {\n\t\treturn nil,nil,ENOTENOUGHDATAPOINTS\n\t}\n\treturn self.ys,[]float64{self.c,self.m},nil\n}", "func (p *Parser) label() {\n\tlabel := p.previous.Literal\n\tif offset, ok := p.labels[label]; ok {\n\t\tp.emitByte(byte(offset))\n\t} else {\n\t\tdata := Label{offset: p.chunk.count, token: p.previous}\n\t\tp.backpatch[label] = append(p.backpatch[label], data)\n\t\tp.emitByte(0)\n\t}\n}", "func (d *decoder) object(childKey string, value reflect.Value) error {\n\treturn d.valueStruct(childKey, value.Addr().Interface())\n}", "func (l *Lfguild) Prepare() {\n}", "func (o *queuePtr) getRelativeOffset(p *queuePtr) uint16 {\n\tif o.index == p.index {\n\t\tif o.offset > p.offset {\n\t\t\tpanic(\" getRelativeOffset(p *queuePtr) \")\n\t\t}\n\t\treturn p.offset - o.offset\n\t}\n\treturn p.offset\n}", "func Auto(c *rux.Context, i interface{}) {\n\n}", "func (mtr *Mcmc2intmcMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"MchInt\" {\n\t\treturn offset\n\t}\n\toffset += mtr.MchInt.Size()\n\n\treturn offset\n}", "func (mtr *Dppdpp0intsramseccMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"DppPhvFifoUncorrectable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.DppPhvFifoUncorrectable.Size()\n\n\tif fldName == \"DppPhvFifoCorrectable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.DppPhvFifoCorrectable.Size()\n\n\tif fldName == \"DppOhiFifoUncorrectable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.DppOhiFifoUncorrectable.Size()\n\n\tif fldName == \"DppOhiFifoCorrectable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.DppOhiFifoCorrectable.Size()\n\n\treturn offset\n}" ]
[ "0.48523924", "0.47066402", "0.4516987", "0.4516987", "0.4516987", "0.4516987", "0.45057568", "0.4504245", "0.44656408", "0.44644177", "0.4460515", "0.44400802", "0.44385478", "0.44224203", "0.44211292", "0.44093663", "0.44025904", "0.4399125", "0.4385478", "0.4383673", "0.43809396", "0.43799177", "0.43713325", "0.43619195", "0.4360416", "0.43601644", "0.43600982", "0.43596315", "0.43570328", "0.43535405", "0.43527198", "0.4328916", "0.43273127", "0.43160495", "0.43100208", "0.4299101", "0.42961252", "0.42911774", "0.42830643", "0.42789203", "0.4275051", "0.42743468", "0.42743468", "0.42647645", "0.4261988", "0.42609003", "0.42570603", "0.42559233", "0.42536417", "0.42511934", "0.42480746", "0.4247153", "0.4246697", "0.42421135", "0.42418814", "0.4240998", "0.42407978", "0.42391813", "0.4239126", "0.42365083", "0.42329225", "0.42272905", "0.42224795", "0.4218825", "0.42164674", "0.42152157", "0.4214474", "0.42113563", "0.42045826", "0.4201066", "0.42010042", "0.4198634", "0.41979378", "0.41967267", "0.41965425", "0.41954938", "0.41931996", "0.41929442", "0.41911113", "0.41884154", "0.41873154", "0.4182076", "0.41771644", "0.41766652", "0.417607", "0.4175623", "0.41750664", "0.4173864", "0.41710934", "0.41690284", "0.41658795", "0.4165469", "0.4165452", "0.4164695", "0.41642824", "0.41625988", "0.41613883", "0.41594955", "0.41581258", "0.4157274", "0.41552007" ]
0.0
-1
Compute and check the hash
func CheckHash(data []byte, target [blake2b.Size]byte) bool { if Hash(data) == target { return true } else { return false } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func computeHash(w http.ResponseWriter, req *http.Request) {\n\tvalues := req.URL.Query()\n\tdata := values.Get(\"data\")\n\tif data == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"400 - data param not present\"))\n\t\treturn\n\t}\n\tsalt := values.Get(\"salt\")\n\tif salt == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"400 - salt param not present\"))\n\t\treturn\n\t}\n\th := sha256.Sum256([]byte(data+salt))\n\tencodedStr := hex.EncodeToString(h[:])\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(encodedStr))\n}", "func calcHash(data string) string {\n\th := sha256.New()\n\th.Write([]byte(data))\n\thash := fmt.Sprintf(\"%x\", h.Sum(nil))\n\treturn hash\n}", "func (authSvc *AuthService) computeHash(s string) hash.Hash {\n\t\n\tvar hash hash.Hash = sha256.New()\n\tvar bytes []byte = []byte(s)\n\thash.Write(authSvc.secretSalt)\n\thash.Write(bytes)\n\treturn hash\n}", "func TestHash(t *testing.T) {\n\tdata := \"bce-auth-v1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/2015-04-27T08:23:49Z/1800\"\n\tkey := \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n\tresult := \"1d5ce5f464064cbee060330d973218821825ac6952368a482a592e6615aef479\"\n\ttestResult := hash(data, key)\n\tif result == testResult {\n\t\tt.Log(\"hash test success\")\n\t} else {\n\t\tt.Error(\"hash test fail\")\n\t}\n}", "func hash(x []byte) uint32 {\n\treturn crc32.ChecksumIEEE(x)\n}", "func hash(value string) uint32 {\n\th := fnv.New32a()\n\th.Write([]byte(value))\n\n\treturn h.Sum32()\n}", "func hash(s string) uint32 {\n h := fnv.New32a()\n h.Write([]byte(s))\n return h.Sum32()\n}", "func Hashcalc(filename string) (Hashval, error) {\n\tr, err := GetHashForFile(filename)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn internHash(r), nil\n}", "func ComputeHash(body []byte) string {\n\th := md5.New()\n\th.Write(body)\n\th.Write(kSecret)\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}", "func Hash(length int, key string) int64 {\n\tif key == \"\" {\n\t\treturn 0\n\t}\n\thc := hashCode(key)\n\treturn (hc ^ (hc >> 16)) % int64(length)\n}", "func hash(s string) int {\n\th := fnv.New32a()\n\tif _, err := h.Write([]byte(s)); err != nil {\n\t\tpanic(err) // should never happen\n\t}\n\n\treturn int(h.Sum32() & 0x7FFFFFFF) // mask MSB of uint32 as this will be sign bit\n}", "func computeHash(nstObj megav1.NamespaceTemplate) uint64 {\n\thash, err := hashstructure.Hash(nstObj, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"computeHash: %d\\n\", hash)\n\treturn hash\n}", "func (n Node) CalSHA256Hash(input []byte) []byte {\r\n\th := sha256.New()\r\n\th.Write(input)\r\n\treturn h.Sum(nil)\r\n}", "func hash(data []byte) [32]byte {\n\tvar hash [32]byte\n\n\th := sha256.New()\n\t// The hash interface never returns an error, for that reason\n\t// we are not handling the error below. For reference, it is\n\t// stated here https://golang.org/pkg/hash/#Hash\n\t// #nosec G104\n\th.Write(data)\n\th.Sum(hash[:0])\n\n\treturn hash\n}", "func Hash(strings ...string) uint32 {\n\tdigester := fnv.New32()\n\tfor _, s := range strings {\n\t\t_, _ = io.WriteString(digester, s)\n\t}\n\treturn digester.Sum32()\n}", "func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func (r *RunCtx) Hash() (uint32, error) {\n\treturn 0, fmt.Errorf(\"not hashable\")\n}", "func (p Path) Hash() (uint32, error) {\n\treturn adler32.Checksum([]byte(p)), nil\n}", "func computeHash(rdr io.Reader) string {\n\tsha256 := sha256.New()\n\tio.Copy(sha256, rdr)\n\thash := sha256.Sum(make([]byte, 0))\n\treturn hex.EncodeToString(hash)\n}", "func Hash(mdfcge []byte) [32]byte {\n\treturn sha256.Sum256(mdfcge)\n}", "func getHash(s string) uint32 {\n\ttbl := crc32.MakeTable(crc32.IEEE)\n\treturn crc32.Checksum([]byte(s), tbl)\n}", "func CalcHash(data string) string {\r\n\thashed := sha256.Sum256([]byte(data))\r\n\treturn hex.EncodeToString(hashed[:])\r\n}", "func (in *Instance) hash(x, y, mu *big.Int, T uint64) *big.Int {\n\tb := sha512.New()\n\tb.Write(x.Bytes())\n\tb.Write(y.Bytes())\n\tb.Write(mu.Bytes())\n\tbits := make([]byte, 8)\n\tbinary.LittleEndian.PutUint64(bits, T)\n\tb.Write(bits)\n\tres := new(big.Int).SetBytes(b.Sum(nil))\n\tres.Mod(res, in.rsaModulus)\n\treturn res\n}", "func (h *Hash) Check(plainText string) error {\n\tb, err := hex.DecodeString(h.Salt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\th.HashFn.Reset() // allow reuse\n\th.HashFn.Write([]byte(plainText))\n\th.HashFn.Write(b)\n\tif result := hex.EncodeToString(h.HashFn.Sum(nil)); result != h.Hash {\n\t\treturn ErrIncorrect\n\t}\n\n\treturn nil\n}", "func hash(ba string) string {\n\th := sha256.New()\n\th.Write([]byte(ba))\n\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}", "func ComputeHash(p, s string) string {\n\th := sha1.New()\n\tio.WriteString(h, p+s)\n\treturn hex.EncodeToString(h.Sum(nil))\n}", "func Hash(b []byte, seed uint64) uint64", "func ExampleMustHashTrytes() {}", "func calculateHash (block Block) string{\n h := sha256.New()\n unique := block.Data + block.PrevHash + block.TimeStamp + strconv.Itoa(block.Nonce)\n h.Write([]byte(unique))\n \n return hex.EncodeToString(h.Sum(nil))\n}", "func memhash(p unsafe.Pointer, h, s uintptr) uintptr", "func memhash(p unsafe.Pointer, h, s uintptr) uintptr", "func (d *Data)ComputeHash(k int, s string) {\n\n time.Sleep(5 * time.Second)\n\n h := sha512.New()\n h.Write([]byte(s))\n val := base64.StdEncoding.EncodeToString(h.Sum(nil))\n\n mutex.Lock()\n d.hashMap[k] = val\n d.inProgressCount--\n mutex.Unlock()\n}", "func byteshash(p *[]byte, h uintptr) uintptr", "func Hash(data []byte) [blake2b.Size]byte {\n\treturn blake2b.Sum512(data)\n}", "func (t TestContent) CalculateHash() ([]byte, error) {\n\th := sha256.New()\n\tif _, err := h.Write([]byte(t.x)); err != nil {\n\t\treturn nil, err\n\t}\n\treturn h.Sum(nil), nil\n}", "func CalculateHash(args []string) string {\n\tvar str = \"\"\n\tfor _,v := range args {\n\t\tstr += v\n\t}\n\thasher := sha256.New()\n\thasher.Write([]byte(str))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}", "func (t *Table) hash(s string) int {\n\t// Good enough.\n\th := fnv.New32()\n\th.Write([]byte(s))\n\treturn int(h.Sum32()) % t.m\n}", "func hash(key string) int{\n\tvar num = 0\n\t// get the lenght of the key\n\tvar length = len(key)\n\n\t// add the ascii character value to creat a sum \n\tfor i := 0; i < length; i++{\n\n\t\tnum += int(key[i])\n\t}\n\t\n\t// square in the middle hash method\n\tvar avg = num * int((math.Pow(5.0, 0.5) - 1)) / 2\n\tvar numeric = avg - int(math.Floor(float64(avg)))\n\n\n\t// hash value to place into the table slice between -1 and CAPACITY - 1\n\treturn int(math.Floor(float64(numeric * CAPACITY)))\n}", "func hash(f []byte) (string, error) {\n\tsha := sha256.New()\n\t_, err := sha.Write(f)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%x\", sha.Sum(nil)), nil\n}", "func (pssOpts *PSSOptions) HashFunc() crypto.Hash", "func hash(key uint64) uint64 {\r\n\tkey ^= key >> 33\r\n\tkey *= 0xff51afd7ed558ccd\r\n\tkey ^= key >> 33\r\n\tkey *= 0xc4ceb9fe1a85ec53\r\n\tkey ^= key >> 33\r\n\treturn key\r\n}", "func (block *Block) calculateHash() {\n\tblock.hash = hash([]byte(string(block.id) +\n\t\tstring(block.previousBlockHash) +\n\t\tstring(block.Content)))\n}", "func (hasher *SHA256) HashLength() uint {\n\treturn 64\n}", "func (c *HashRing) generateHash(key string) uint32 {\n\treturn crc32.ChecksumIEEE([]byte(key))\n}", "func CheckHMACHash(data string, hash string, secret string) bool {\n\th := hmac.New(sha256.New, []byte(secret))\n\th.Write([]byte(data))\n\t// Get result and encode as hexadecimal string\n\tsha := hex.EncodeToString(h.Sum(nil))\n\treturn sha == hash\n}", "func TestHash(t *testing.T) {\n\t// Hash of block 234439.\n\tblockHashStr := \"14a0810ac680a3eb3f82edc878cea25ec41d6b790744e5daeef\"\n\tblockHash, err := NewHashFromStr(blockHashStr)\n\tassert.NoError(t, err)\n\n\t// Hash of block 234440 as byte slice.\n\tbuf := []byte{\n\t\t0x79, 0xa6, 0x1a, 0xdb, 0xc6, 0xe5, 0xa2, 0xe1,\n\t\t0x39, 0xd2, 0x71, 0x3a, 0x54, 0x6e, 0xc7, 0xc8,\n\t\t0x75, 0x63, 0x2e, 0x75, 0xf1, 0xdf, 0x9c, 0x3f,\n\t\t0xa6, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t}\n\n\thash, err := NewHash(buf)\n\tassert.NoError(t, err)\n\n\t// Ensure proper size.\n\tassert.Equal(t, HashSize, len(hash))\n\n\t// Ensure contents match.\n\tassert.Equal(t, buf[:], hash[:])\n\n\t// Ensure contents of hash of block 234440 don't match 234439.\n\tassert.False(t, hash.IsEqual(blockHash))\n\n\t// Set hash from byte slice and ensure contents match.\n\terr = hash.SetBytes(blockHash.CloneBytes())\n\tassert.NoError(t, err)\n\tassert.True(t, hash.IsEqual(blockHash))\n\n\t// Ensure nil hashes are handled properly.\n\tassert.True(t, (*Hash)(nil).IsEqual(nil))\n\n\tassert.False(t, hash.IsEqual(nil))\n\n\t// Invalid size for SetBytes.\n\terr = hash.SetBytes([]byte{0x00})\n\tassert.NotNil(t, err)\n\n\t// Invalid size for NewHash.\n\tinvalidHash := make([]byte, HashSize+1)\n\t_, err = NewHash(invalidHash)\n\tassert.NotNil(t, err)\n\n\tif err == nil {\n\t\tt.Errorf(\"NewHash: failed to received expected err - got: nil\")\n\t}\n}", "func compareHmac(value string, hash string, secret string) bool {\n return hash == Hash(value, secret)\n}", "func Hash(value int64) uint64 {\n\treturn FNVHash64(uint64(value))\n}", "func CalculateHash(key string, iteration int) string {\n\ty := fmt.Sprintf(\"%s%d\", key, iteration)\n\tx := fmt.Sprintf(\"%x\", md5.Sum([]byte(y)))\n\treturn x\n}", "func hash(s string) string {\n\th := fnv.New32a()\n\t_, err := h.Write([]byte(s))\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprint(h.Sum32())\n}", "func Hash(b []byte) uint32 {\n\tconst (\n\t\tseed = 0xbc9f1d34\n\t\tm = 0xc6a4a793\n\t)\n\th := uint32(seed) ^ uint32(len(b))*m\n\tfor ; len(b) >= 4; b = b[4:] {\n\t\th += uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24\n\t\th *= m\n\t\th ^= h >> 16\n\t}\n\tswitch len(b) {\n\tcase 3:\n\t\th += uint32(b[2]) << 16\n\t\tfallthrough\n\tcase 2:\n\t\th += uint32(b[1]) << 8\n\t\tfallthrough\n\tcase 1:\n\t\th += uint32(b[0])\n\t\th *= m\n\t\th ^= h >> 24\n\t}\n\treturn h\n}", "func TestDeriveSha(t *testing.T) {\n\tlist := testList{\n\t\t{1, 2, 3, 4, 5, 6},\n\t\t{6, 5, 4, 3, 2, 1},\n\t\t{1, 1, 1, 1, 1, 1},\n\t\t{3, 3, 3, 3, 3, 3},\n\t}\n\tres := DeriveSha(list)\n\texpected := []byte{\n\t\t0x52, 0x7a, 0x68, 0x9a, 0xa5, 0x1c, 0x42, 0x5d, 0x22, 0x9f, 0xeb, 0x46, 0xa1, 0xab, 0xc8,\n\t\t0x55, 0x72, 0x12, 0x08, 0xf4, 0x56, 0xa8, 0x1f, 0x5a, 0x63, 0x5d, 0x52, 0x3f, 0xf9, 0x3d,\n\t\t0xa2, 0x16,\n\t}\n\tif !bytes.Equal(res.Bytes(), expected) {\n\t\tt.Errorf(\"DeriveSha Got an unexpected root hash. Got %x Want %x.\", res, expected)\n\t}\n}", "func CalcHash(r io.Reader) (b []byte, err error) {\n\thash := sha512.New()\n\t_, err = io.Copy(hash, r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tsum := hash.Sum(b)\n\tb = make([]byte, hex.EncodedLen(len(sum)))\n\thex.Encode(b, sum)\n\n\treturn\n}", "func (i *Instance) Hash() (uint32, error) {\n\th := fnv.New32()\n\tfmt.Fprintf(h, \"%s%s\", i.Name, i.Version)\n\n\tfn, err := i.Fn.Hash()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn fn ^ h.Sum32(), nil\n}", "func Hash(data []byte) {\n\tfor i := 0; i < 50; i++ {\n\t\tsha256.Sum256(data)\n\t}\n}", "func Hash(p string) (string, string) {\n\ts := GenString(32)\n\treturn ComputeHash(p, s), s\n}", "func (blk Block) CalcHash() []byte {\n\t// TODO\n\n\tprevHashStr := hex.EncodeToString(blk.PrevHash)\n\tgen := blk.Generation\n\tdif := blk.Difficulty\n\tdata := blk.Data\n\tprf := blk.Proof\n\n\thashStr := fmt.Sprintf(\"%s:%d:%d:%s:%d\", prevHashStr, gen, dif, data, prf)\n\n\thash := sha256.New()\n\n\thash.Write([]byte(hashStr))\n\n\treturn hash.Sum(nil)\n}", "func (h *MemHash) Hash() uint32 {\n\tss := (*stringStruct)(unsafe.Pointer(&h.buf))\n\treturn uint32(memhash(ss.str, 0, uintptr(ss.len)))\n}", "func (mh *Median) computeHash(img *image.Gray, median uint) hashtype.Binary {\n\tsize := mh.width * mh.height / 8\n\thash := make(hashtype.Binary, size)\n\tbnds := img.Bounds()\n\tvar c uint\n\tfor i := bnds.Min.Y; i < bnds.Max.Y; i++ {\n\t\tfor j := bnds.Min.X; j < bnds.Max.X; j++ {\n\t\t\tpix := img.GrayAt(j, i).Y\n\t\t\tif uint(pix) > median {\n\t\t\t\thash.Set(c)\n\t\t\t}\n\t\t\tc++\n\t\t}\n\t}\n\treturn hash\n}", "func runtime_memhash(p unsafe.Pointer, seed, s uintptr) uintptr", "func sha3hash(t *testing.T, data ...[]byte) []byte {\n\tt.Helper()\n\th := sha3.NewLegacyKeccak256()\n\tr, err := doSum(h, nil, data...)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn r\n}", "func VerifySha256(password, hash string) bool {\n return Sha256Hash(password) == hash\n}", "func Hash(input []byte) string {\n\treturn fmt.Sprintf(\"%x\", sha256.Sum256(input))\n}", "func TestGenerateHash(t *testing.T) {\n\t// Define The TestCase Struct\n\ttype TestCase struct {\n\t\tName string\n\t\tLength int\n\t}\n\n\t// Create The TestCases\n\ttestCases := []TestCase{\n\t\t{Name: \"\", Length: 32},\n\t\t{Name: \"short string\", Length: 4},\n\t\t{Name: \"long string, 8-character hash\", Length: 8},\n\t\t{Name: \"odd hash length, 13-characters\", Length: 13},\n\t\t{Name: \"very long string with 16-character hash and more than 64 characters total\", Length: 16},\n\t}\n\n\t// Run The TestCases\n\tfor _, testCase := range testCases {\n\t\thash := GenerateHash(testCase.Name, testCase.Length)\n\t\texpected := fmt.Sprintf(\"%x\", md5.Sum([]byte(testCase.Name)))[0:testCase.Length]\n\t\tassert.Equal(t, expected, hash)\n\t}\n\n}", "func Hash(key string) uint32 {\n\treturn uint32(aeshashstr(noescape(unsafe.Pointer(&key)), 0))\n}", "func hashIt(s string, bit int) int {\n\th := sha1.New()\n\th.Write([]byte(s))\n\tbs := h.Sum(nil)\n\thashValue := math.Mod(float64(bs[len(bs)-1]), math.Exp2(float64(bit)))\n\treturn int(hashValue)\n}", "func hash_func(x, y, n HashValue) (HashValue) {\n return (x*1640531513 ^ y*2654435789) % n\n}", "func calculateHash(block Block) string {\n\trecord := strconv.Itoa(block.Index) + block.Timestamp + strconv.Itoa(block.Key) + block.PrevHash\n\th := sha256.New()\n\th.Write([]byte(record))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func (ph *PHash) computeHash(img [][]float32) hashtype.Binary {\n\t// TODO: Remove magic numbers\n\thash := make(hashtype.Binary, 8)\n\tvar c uint\n\tfor i := range img {\n\t\tfor j := range img[i] {\n\t\t\tif img[i][j] != 0 {\n\t\t\t\thash.Set(c)\n\t\t\t}\n\t\t\tc++\n\t\t}\n\t}\n\treturn hash\n}", "func IsHash(str string, algorithm string) bool {\n\tlen := \"0\"\n\talgo := strings.ToLower(algorithm)\n\n\tif algo == \"crc32\" || algo == \"crc32b\" {\n\t\tlen = \"8\"\n\t} else if algo == \"md5\" || algo == \"md4\" || algo == \"ripemd128\" || algo == \"tiger128\" {\n\t\tlen = \"32\"\n\t} else if algo == \"sha1\" || algo == \"ripemd160\" || algo == \"tiger160\" {\n\t\tlen = \"40\"\n\t} else if algo == \"tiger192\" {\n\t\tlen = \"48\"\n\t} else if algo == \"sha256\" {\n\t\tlen = \"64\"\n\t} else if algo == \"sha384\" {\n\t\tlen = \"96\"\n\t} else if algo == \"sha512\" {\n\t\tlen = \"128\"\n\t} else {\n\t\treturn false\n\t}\n\n\treturn Matches(str, \"^[a-f0-9]{\"+len+\"}$\")\n}", "func TestCompareHashPass(t *testing.T) {\n\tpass := \"hello\"\n\n\tresult, err := HashPass(pass)\n\n\tif err != nil {\n\t\tt.Errorf(\"%#v couldnt be hashed: %#v\", pass, err)\n\t\treturn\n\t}\n\n\tif ans := CompareHashPass(pass, result); ans {\n\t\tt.Logf(\"CompareHashPass returned the correct result: pass=%#v, hash=%#v\", pass, result)\n\t} else {\n\t\tt.Errorf(\"CompareHashPass didnt return the correct result: pass=%#v, hash=%#v\", pass, result)\n\t}\n}", "func calculateHash(block Block) string {\n\n\t// Time and vehicle identifier (v5c) are the key block items to generate the hash\n\trecord := string(string(block.Index) + block.Timestamp + block.Event.PerformedOnVehicle.V5c + block.PrevHash)\n\th := sha256.New()\n\th.Write([]byte(record))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func (t *openAddressing) hash(key string, round int) uint32 {\n\tnum := uint(stringToInt(key))\n\tmax := uint(len(t.values) - 1)\n\treturn uint32((hashDivision(num, max) + uint(round)*hashDivision2(num, max)) % max)\n}", "func Hashit(tox string) string {\n h:= sha256.New()\n h.Write([]byte(tox))\n bs := h.Sum([]byte{})\n str := base64.StdEncoding.EncodeToString(bs)\n return str\n}", "func (fw *LocalClient) hashsum(relpath string) string {\n\n\tabspath := filepath.Join(fw.rootDir, relpath)\n\tcheck, err := utils.CheckSum(abspath)\n\tcheckErr(err)\n\treturn check\n}", "func (h Hasher) Hash(data []byte) []byte {\n\thf := h.New()\n\tif hf == nil {\n\t\treturn nil\n\t}\n\thf.Write(data)\n\treturn hf.Sum(nil)\n}", "func (v MultiValidator) Hash() (*types.Bytes32, error) {\n\tb := make([]byte, 0)\n\tfor _, processValidators := range v.validators {\n\t\tfor _, validator := range processValidators {\n\t\t\tvalidatorHash, err := validator.Hash()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStack(err)\n\t\t\t}\n\t\t\tb = append(b, validatorHash[:]...)\n\t\t}\n\t}\n\tvalidationsHash := types.Bytes32(sha256.Sum256(b))\n\treturn &validationsHash, nil\n}", "func TestHash(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tdesc string\n\t\tin string\n\t\tcrc32c string\n\t\tmd5 string\n\t}{\n\t\t{\n\t\t\tdesc: \"empty\",\n\t\t\tin: \"\",\n\t\t\tcrc32c: \"AAAAAA==\",\n\t\t\tmd5: \"1B2M2Y8AsgTpgAmY7PhCfg==\",\n\t\t},\n\t\t{\n\t\t\tdesc: \"hello.c\",\n\t\t\tin: `#include <stdio.h>\n\nint i = 1;\n\nint main(int argc, char *argv[]) {\n\t printf(\"hello, world\\n\");\n\t return 0;\n}\n`,\n\t\t\tcrc32c: \"r+rffw==\",\n\t\t\tmd5: \"Q9yWleHH0r5N2AYXTIBHQw==\",\n\t\t},\n\t} {\n\t\tgot := crc32cStr(crc32.Checksum([]byte(tc.in), crc32cTable))\n\t\tif got != tc.crc32c {\n\t\t\tt.Errorf(\"%s: crc32c: %s; want %s\", tc.desc, tc.in, tc.crc32c)\n\t\t}\n\t\tmd5sum := md5.Sum([]byte(tc.in))\n\t\tgot = md5sumStr(md5sum[:])\n\t\tif got != tc.md5 {\n\t\t\tt.Errorf(\"%s: md5: %s; want %s\", tc.desc, tc.in, tc.md5)\n\t\t}\n\t}\n}", "func (h *hasht) hash(input string) uint64 {\n\tvar hash uint64 = FNVOffset\n\tfor _, char := range input {\n\t\thash ^= uint64(char)\n\t\thash *= FNVPrime\n\t}\n\treturn hash\n}", "func sumHash(c byte, h uint32) uint32 {\n\treturn (h * hashPrime) ^ uint32(c)\n}", "func hash(s string) string {\n\treturn fmt.Sprintf(\"%x\", md5.Sum([]byte(s)))\n}", "func (this *Ring) Hash(key string) uint32 {\n\treturn crc32.ChecksumIEEE([]byte(key))\n}", "func checkHashSize(hexStr string) int {\n\tmaxint64 := 9223372036854775807\n\tminint64 := -9223372036854775807\n\tint64val := hex2int(hexStr)\n\n\tfor len(hexStr) > 0 && int64val >= maxint64 || int64val <= minint64 {\n\t\thexStr = hexStr[:len(hexStr)-1]\n\t\tint64val = hex2int(hexStr)\n\t}\n\treturn int64val\n}", "func Hash(msg string, nonce uint64) uint64 {\r\n\thasher := sha256.New()\r\n\thasher.Write([]byte(fmt.Sprintf(\"%s %d\", msg, nonce)))\r\n\treturn binary.BigEndian.Uint64(hasher.Sum(nil))\r\n}", "func (s *grpcServer) validateHash(hash string, logPrefix string) error {\n\tif len(hash) != hashKeyLength {\n\t\tmsg := fmt.Sprintf(\"Hash length must be length %d\", hashKeyLength)\n\t\ts.accessLogger.Printf(\"%s %s: %s\", logPrefix, hash, msg)\n\t\treturn status.Error(codes.InvalidArgument, msg)\n\t}\n\n\tif !hashKeyRegex.MatchString(hash) {\n\t\tmsg := \"Malformed hash\"\n\t\ts.accessLogger.Printf(\"%s %s: %s\", logPrefix, hash, msg)\n\t\treturn status.Error(codes.InvalidArgument, msg)\n\t}\n\n\treturn nil\n}", "func TestHash32(t *testing.T) {\n\tstdHash := crc32.New(crc32.IEEETable)\n\tif _, err := stdHash.Write([]byte(\"test\")); err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// create a new hash with stdHash.Sum32() as initial crc\n\tcrcHash := New(stdHash.Sum32(), crc32.IEEETable)\n\n\tstdHashSize := stdHash.Size()\n\tcrcHashSize := crcHash.Size()\n\tif stdHashSize != crcHashSize {\n\t\tt.Fatalf(\"%d != %d\", stdHashSize, crcHashSize)\n\t}\n\n\tstdHashBlockSize := stdHash.BlockSize()\n\tcrcHashBlockSize := crcHash.BlockSize()\n\tif stdHashBlockSize != crcHashBlockSize {\n\t\tt.Fatalf(\"%d != %d\", stdHashBlockSize, crcHashBlockSize)\n\t}\n\n\tstdHashSum32 := stdHash.Sum32()\n\tcrcHashSum32 := crcHash.Sum32()\n\tif stdHashSum32 != crcHashSum32 {\n\t\tt.Fatalf(\"%d != %d\", stdHashSum32, crcHashSum32)\n\t}\n\n\tstdHashSum := stdHash.Sum(make([]byte, 32))\n\tcrcHashSum := crcHash.Sum(make([]byte, 32))\n\tif !reflect.DeepEqual(stdHashSum, crcHashSum) {\n\t\tt.Fatalf(\"sum = %v, want %v\", crcHashSum, stdHashSum)\n\t}\n\n\t// write something\n\tif _, err := stdHash.Write([]byte(\"hello\")); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif _, err := crcHash.Write([]byte(\"hello\")); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tstdHashSum32 = stdHash.Sum32()\n\tcrcHashSum32 = crcHash.Sum32()\n\tif stdHashSum32 != crcHashSum32 {\n\t\tt.Fatalf(\"%d != %d\", stdHashSum32, crcHashSum32)\n\t}\n\n\t// reset\n\tstdHash.Reset()\n\tcrcHash.Reset()\n\tstdHashSum32 = stdHash.Sum32()\n\tcrcHashSum32 = crcHash.Sum32()\n\tif stdHashSum32 != crcHashSum32 {\n\t\tt.Fatalf(\"%d != %d\", stdHashSum32, crcHashSum32)\n\t}\n}", "func hash(s string) string {\n\thash := fnv.New32a()\n\thash.Write([]byte(s))\n\tintHash := hash.Sum32()\n\tresult := fmt.Sprintf(\"%08x\", intHash)\n\treturn result\n}", "func strhash(p *string, h uintptr) uintptr", "func (t *Target) hash() uint64 {\n\th := fnv.New64a()\n\n\t//nolint: errcheck\n\th.Write([]byte(fmt.Sprintf(\"%016d\", t.labels.Hash())))\n\t//nolint: errcheck\n\th.Write([]byte(t.URL().String()))\n\n\treturn h.Sum64()\n}", "func getHash(data string, hashType Hash) (hash crypto.Hash, hashed []byte, err error) {\n\tnewHash := sha1.New()\n\tswitch hashType {\n\tcase SHA1:\n\t\tnewHash = sha1.New()\n\t\thash = crypto.SHA1\n\tcase SHA224:\n\t\tnewHash = sha256.New224()\n\t\thash = crypto.SHA224\n\tcase SHA256:\n\t\tnewHash = sha256.New()\n\t\thash = crypto.SHA256\n\tcase SHA384:\n\t\tnewHash = sha512.New384()\n\t\thash = crypto.SHA384\n\tcase SHA512:\n\t\tnewHash = sha512.New()\n\t\thash = crypto.SHA512\n\tcase SHA512_224:\n\t\tnewHash = sha512.New512_224()\n\t\thash = crypto.SHA512_224\n\tcase SHA512_256:\n\t\tnewHash = sha512.New512_256()\n\t\thash = crypto.SHA512_256\n\tcase MD5:\n\t\tnewHash = md5.New()\n\t\thash = crypto.MD5\n\tdefault:\n\t\treturn hash, hashed, fmt.Errorf(\"unsupport hashType\")\n\t}\n\t_, err = newHash.Write([]byte(data))\n\tif err != nil {\n\t\treturn hash, hashed, err\n\t}\n\t//newHash.Write([]byte(data))\n\thashed = newHash.Sum(nil)\n\treturn hash, hashed, nil\n}", "func hash(fn string) (res string) {\n\th := sha256.New()\n\n\tfi, err := os.Stat(fn)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer f.Close()\n\n\tif fi.IsDir() {\n\t\tns, err := f.Readdirnames(0)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tfor _, e := range ns {\n\t\t\th.Write([]byte(e))\n\t\t}\n\t} else {\n\t\tif _, err := io.Copy(h, f); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn string(h.Sum(nil))\n}", "func (r RawRecord) ComputeHash() fnv1a.Hash {\n\treturn fnv1a.ZeroHash()\n}", "func (c *CurrentBlock) SafeHash() [32]byte {\n\tc.mux.RLock()\n\tdefer c.mux.RUnlock()\n\n\treturn c.b.Hash()\n}", "func (bc *Blockchain) Hash() {\n\n}", "func strhash(a unsafe.Pointer, h uintptr) uintptr", "func op_BLOCKHASH(pc *uint64, in *interpreter, ctx *callCtx) uint64 {\n\tnum := ctx.stack.Peek()\n\tnum64, overflow := num.Uint64WithOverflow()\n\tif overflow {\n\t\tnum.Clear()\n\t}\n\tvar upper, lower uint64\n\tupper = in.evm.block.NumberU64()\n\tif upper < 257 {\n\t\tlower = 0\n\t} else {\n\t\tlower = upper - 256\n\t}\n\tif num64 >= lower && num64 < upper {\n\t\tnum.SetBytes(in.evm.block.Hash().Bytes())\n\t} else {\n\t\tnum.Clear()\n\t}\n\treturn 0\n}", "func badHash(data []byte) [32]byte {\n\th := fnv.New64a()\n\th.Write(data)\n\ts := h.Sum64()\n\ts1 := s ^ BAD_HASH_SEED_1\n\ts2 := s ^ BAD_HASH_SEED_2\n\ts3 := s ^ BAD_HASH_SEED_3\n\ts4 := s ^ BAD_HASH_SEED_4\n\treturn [32]byte{\n\t\tbyte(0xff & s1),\n\t\tbyte(0xff & (s1 >> 8)),\n\t\tbyte(0xff & (s1 >> 16)),\n\t\tbyte(0xff & (s1 >> 24)),\n\t\tbyte(0xff & (s1 >> 32)),\n\t\tbyte(0xff & (s1 >> 40)),\n\t\tbyte(0xff & (s1 >> 48)),\n\t\tbyte(0xff & (s1 >> 56)),\n\t\tbyte(0xff & s2),\n\t\tbyte(0xff & (s2 >> 8)),\n\t\tbyte(0xff & (s2 >> 16)),\n\t\tbyte(0xff & (s2 >> 24)),\n\t\tbyte(0xff & (s2 >> 32)),\n\t\tbyte(0xff & (s2 >> 40)),\n\t\tbyte(0xff & (s2 >> 48)),\n\t\tbyte(0xff & (s2 >> 56)),\n\t\tbyte(0xff & s3),\n\t\tbyte(0xff & (s3 >> 8)),\n\t\tbyte(0xff & (s3 >> 16)),\n\t\tbyte(0xff & (s3 >> 24)),\n\t\tbyte(0xff & (s3 >> 32)),\n\t\tbyte(0xff & (s3 >> 40)),\n\t\tbyte(0xff & (s3 >> 48)),\n\t\tbyte(0xff & (s3 >> 56)),\n\t\tbyte(0xff & s4),\n\t\tbyte(0xff & (s4 >> 8)),\n\t\tbyte(0xff & (s4 >> 16)),\n\t\tbyte(0xff & (s4 >> 24)),\n\t\tbyte(0xff & (s4 >> 32)),\n\t\tbyte(0xff & (s4 >> 40)),\n\t\tbyte(0xff & (s4 >> 48)),\n\t\tbyte(0xff & (s4 >> 56)),\n\t}\n}", "func newSHA256() hash.Hash { return sha256.New() }", "func blockHash(x uint64) uint32 {\n\tconst prime6bytes = 227718039650203\n\tx &= 1<<40 - 1\n\treturn uint32((x * prime6bytes) >> (64 - hashLog))\n}" ]
[ "0.69898987", "0.6741546", "0.67407966", "0.6724998", "0.6688802", "0.6658574", "0.66341126", "0.6630911", "0.66244596", "0.66141754", "0.66067123", "0.6591132", "0.65789235", "0.6557145", "0.65372247", "0.6517661", "0.6517661", "0.6517661", "0.64942336", "0.6490384", "0.6477171", "0.64450866", "0.6436836", "0.6429433", "0.6418533", "0.6418432", "0.64173424", "0.64143217", "0.63959384", "0.6379789", "0.63793844", "0.6371421", "0.6371421", "0.6331663", "0.6330768", "0.6324727", "0.63233453", "0.6322094", "0.6320029", "0.63156706", "0.6310407", "0.6306917", "0.6300627", "0.6294206", "0.62863165", "0.6283797", "0.6276375", "0.6272649", "0.62686944", "0.6265347", "0.6263359", "0.62549", "0.6250134", "0.6246514", "0.6229754", "0.6224478", "0.6216626", "0.62142015", "0.62097085", "0.6180649", "0.6176756", "0.6173584", "0.617198", "0.6167592", "0.6166958", "0.6162755", "0.61625695", "0.61512977", "0.61510766", "0.6149023", "0.61485004", "0.614685", "0.61464596", "0.6135154", "0.61342454", "0.61266047", "0.61261904", "0.61248213", "0.6115888", "0.61153686", "0.611221", "0.6107482", "0.6105927", "0.610344", "0.60976356", "0.60906005", "0.6089689", "0.60878944", "0.6079312", "0.6075255", "0.6073788", "0.60662794", "0.6063637", "0.605516", "0.604465", "0.6041852", "0.6040159", "0.60358137", "0.603247", "0.6031284", "0.60272604" ]
0.0
-1
/ Starting Point : 1 Starting Point 2 : 1
func ConvertXY(src int, dst int) int { que := new(Queue) visited := make(map[int]int) que.Add([]int{src, 0}) for que.Len() != 0 { node := que.Remove().([]int) visited[node[0]] = 1 value := node[0] steps := node[1] if value == dst { return steps } if _, ok := visited[value*2]; !ok && value < dst { que.Add([]int{value * 2, steps + 1}) } if _, ok := visited[value-1]; !ok && value > 0 { que.Add([]int{value - 1, steps + 1}) } } return -1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func firstStep(y int) {\n\tfmt.Println(\"1.1\", y)\n\ty = 52 // 1.4 assign y to 52\n\tfmt.Println(\"1.2\", y)\n}", "func stepfrom(dir rune, x, y int) (sx, sy int) {\n\tswitch dir {\n\tcase 'N':\n\t\treturn x, y + 1\n\tcase 'S':\n\t\treturn x, y - 1\n\tcase 'W':\n\t\treturn x + 1, y\n\tcase 'E':\n\t\treturn x - 1, y\n\t}\n\tpanic(\"invalid stepfrom direction\")\n}", "func (ds *DijkstraSolver) _initStartPoint(S []StartPoint, dp []Value, colors []int) *VertexPQ {\n\tpq := NewVertexPQ()\n\n\tfor _, sp := range S {\n\t\tpq.push(&Vertex{id: sp.id, v: sp.vzero})\n\t\tdp[sp.id] = sp.vzero\n\t\tcolors[sp.id] = GRAY\n\t}\n\n\treturn pq\n}", "func StartPosition() (p *Position) {\n\tbar0 := make([]int, WIDTH()+1)\n\tbar1 := make([]int, WIDTH()+1)\n\tfor i := range bar0 {\n\t\tbar0[i] = STONE()\n\t}\n\tbar0[0] = 0\n\tcopy(bar1, bar0)\n\n\tp = &Position{}\n\tp.Row[0] = Side{Items: bar0}\n\tp.Row[1] = Side{Items: bar1}\n\treturn\n}", "func (f *Feature) StartOne() uint64 {\n\treturn f.Pos\n}", "func createOpenings(x, y *int) {\n setInt(&begY, *x)\n setInt(&endY, *y)\n setMaze(getInt(&begX) - 1, getInt(&begY), path)\n setMaze(getInt(&endX) + 1, getInt(&endY), path)\n *x = getInt(&begX)\n *y = getInt(&begY)\n}", "func path(start Point) int {\n\tret := 0\n\tupret := 0\n\trightret := 0\n\tdownret := 0\n\tuppoint := start\n\tuppoint.Y = uppoint.Y + 1\n\tok := isPointOK(&uppoint)\n\tif ok {\n\t\tfmt.Printf(\"%+v\\n\", uppoint)\n\t\tsumpoint <- uppoint\n\t\tpathrecordpoint <- uppoint\n\t\tupret = path(uppoint)\n\n\t\tret = ret + 1\n\t}\n\trightpoint := start\n\trightpoint.X = rightpoint.X + 1\n\tok = isPointOK(&rightpoint)\n\tif ok {\n\t\tfmt.Printf(\"%+v\\n\", rightpoint)\n\t\tsumpoint <- rightpoint\n\t\tpathrecordpoint <- rightpoint\n\t\trightret = path(rightpoint)\n\t\tret = ret + 1\n\n\t}\n\n\treturn ret + upret + downret + rightret\n}", "func stepUR(position Point, slice [][]int32) Point {\n\tif position.x+1 < len(slice) &&\n\t\tposition.y-2 >= 0 &&\n\t\tslice[position.y-2][position.x+1] == 0 {\n\t\treturn Point{\n\t\t\tx: position.x + 1,\n\t\t\ty: position.y - 2,\n\t\t}\n\t}\n\treturn notPoint\n}", "func (r *baseNsRange) Start() int { return r.start }", "func secondStep(p *int) {\n\tfmt.Println(\"2.1\", p)\n\t*p = 52 // 2.4 assign p to 52\n\tfmt.Println(\"2.2\", *p)\n}", "func (f *Feature) StartZero() uint64 {\n\tif f.Pos == 0 {\n\t\treturn 0\n\t}\n\treturn f.Pos - 1\n}", "func (r *Automaton) GetStartPoints() []int {\n\tpointset := make(map[int]struct{})\n\tpointset[0] = struct{}{}\n\n\tfor s := 0; s < r.nextState; s += 2 {\n\t\ttrans := r.states[s]\n\t\tlimit := trans + 3*r.states[s+1]\n\t\t//System.out.println(\" state=\" + (s/2) + \" trans=\" + trans + \" limit=\" + limit);\n\t\tfor trans < limit {\n\t\t\tmin := r.transitions[trans+1]\n\t\t\tmax := r.transitions[trans+2]\n\t\t\t//System.out.println(\" min=\" + min);\n\t\t\tpointset[min] = struct{}{}\n\t\t\tif max < 0x10FFFF {\n\t\t\t\tpointset[max+1] = struct{}{}\n\t\t\t}\n\t\t\ttrans += 3\n\t\t}\n\t}\n\n\tpoints := make([]int, 0, len(pointset))\n\tfor k, _ := range pointset {\n\t\tpoints = append(points, k)\n\t}\n\tsort.Ints(points)\n\treturn points\n}", "func calcCoordinateStartingPoint(wm *WatermarkImage, oh OverheadImage, position int, offsetX int, offsetY int) image.Point {\n\n\treturn image.Point{0, 0}\n}", "func halfSolutionPath(links map[string]string, objective, start string) []string {\n if start == objective {\n return []string{}\n } else {\n next := links[start]\n return append(halfSolutionPath(links, objective, next), next)\n }\n}", "func stepLD(position Point, slice [][]int32) Point {\n\tif position.x-2 >= 0 &&\n\t\tposition.y+1 < len(slice[position.y]) &&\n\t\tslice[position.y+1][position.x-2] == 0 {\n\t\treturn Point{\n\t\t\tx: position.x - 2,\n\t\t\ty: position.y + 1,\n\t\t}\n\t}\n\treturn notPoint\n}", "func part1(numbers []int, target int) (error, int, int) {\n\tfor _, num1 := range numbers {\n\t\tfor _, num2 := range numbers {\n\t\t\tif num1+num2 == target {\n\t\t\t\treturn nil, num1, num2\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errors.New(\"Could not find pair\"), -1, -1\n}", "func (im *imageContrller) pointCalculator(index, width, height int) (start image.Point, end image.Point) {\n\t// variables\n\n\txpoint := 0\n\typoint := 0\n\n\t// point data\n\tif index < 6 {\n\t\t// 1st row\n\t\ti := index\n\t\txpoint = LeftMargin + i*width + i*Spacing\n\t\typoint = TopMargin\n\n\t} else if index > 5 && index < 12 {\n\t\t// 2nd row\n\t\ti := (index - 6)\n\t\txpoint = LeftMargin + i*width + i*Spacing\n\t\typoint = TopMargin + height + Spacing\n\n\t} else if index > 10 && index < 18 {\n\t\t// 3rd row\n\t\ti := (index - 12)\n\t\txpoint = LeftMargin + i*width + i*Spacing\n\t\typoint = TopMargin + 2*height + 2*Spacing\n\n\t} else {\n\t\t// 4th row\n\t\ti := (index - 18)\n\t\txpoint = LeftMargin + i*width + i*Spacing\n\t\typoint = TopMargin + 3*height + 3*Spacing\n\t}\n\n\tstartPoint := image.Pt(xpoint, ypoint)\n\tendPoint := image.Pt(xpoint+width, ypoint+width)\n\n\treturn startPoint, endPoint\n}", "func main() {\n\n\t//fmt.Println(jump([]int{2, 1}))\n\t//fmt.Println(jump([]int{1, 3, 2}))\n\t//fmt.Println(jump([]int{1, 2}))\n\t//fmt.Println(jump([]int{1, 1, 1, 1, 1}))\n\t//fmt.Println(jump([]int{1, 2, 1, 1, 1}))\n\t//fmt.Println(jump([]int{2, 3, 1, 1, 4}))\n\tfmt.Println(jump([]int{3, 2, 1, 0, 4}))\n}", "func calculateStartAndEndOfAPiece(index int, pieceLength int, fileTotalLength int) (begin int, end int) {\n\t// Why we need to calculate\n\tfmt.Println(\"calculateStartAndEndOfAPiece index \", index, \" pieceLength\", pieceLength)\n\tbegin = index * pieceLength\n\tend = begin + pieceLength\n\tif end > fileTotalLength {\n\t\tend = fileTotalLength\n\t}\n\treturn begin, end\n}", "func (self *Tween) Start1O(index int) *Tween{\n return &Tween{self.Object.Call(\"start\", index)}\n}", "func c1(n int) int { return n - WIDTH - 1 }", "func findMinimumSteps(distances []int) int {\n\tmin := distances[0]\n\tfor _, v := range distances {\n\t\tif v < min {\n\t\t\tmin = v\n\t\t}\n\t}\n\n\treturn min\n}", "func stepRD(position Point, slice [][]int32) Point {\n\tif position.x+2 < len(slice) &&\n\t\tposition.y+1 < len(slice[position.y]) &&\n\t\tslice[position.y+1][position.x+2] == 0 {\n\t\treturn Point{\n\t\t\tx: position.x + 2,\n\t\t\ty: position.y + 1,\n\t\t}\n\t}\n\treturn notPoint\n}", "func getFinalPosition2(commands []command) (int, int) {\n\thorizontal, depth, aim := 0, 0, 0\n\tfor _, cmd := range commands {\n\t\tswitch cmd.direction {\n\t\tcase \"forward\":\n\t\t\thorizontal += cmd.unit\n\t\t\tdepth += aim * cmd.unit\n\t\tcase \"down\":\n\t\t\taim += cmd.unit\n\t\tcase \"up\":\n\t\t\taim -= cmd.unit\n\t\t}\n\t}\n\treturn horizontal, depth\n}", "func firstdecision(gconfig Kiai.GameConfig) {\n\t\n\tif turn.X <= gconfig.Width / 2 && turn.Y < gconfig.Height / 2 { //Be careful, this method favours the top left corner due to int variables rounding the results of the division to lower limit.\n\t\tpath = 1 \n\t}\n\tif turn.X >= gconfig.Width / 2 && turn.Y < gconfig.Height / 2 {\n\t\tpath = 2 \n\t}\n\tif turn.X >= gconfig.Width / 2 && turn.Y > gconfig.Height / 2 {\n\t\tpath = 3 \n\t}\n\tif turn.X <= gconfig.Width / 2 && turn.Y > gconfig.Height / 2 {\n\t\tpath = 4 \n\t}\n\t\n\tstart = true\n}", "func (l *Lexer) updateStart() {\n\tif l.b {\n\t\tl.S = l.n - 1\n\t} else {\n\t\tl.S = l.n\n\t}\n}", "func findPathStart(x, y *int) bool {\n directions := make([]dirTable, 4, 4)\n xStart := rand.Intn(height)\n yStart := rand.Intn(width )\n length := -1\n for i := 0; i < height; i++ {\n for j := 0; j < width; j++ {\n *x = 2*((xStart + i) % height + 1)\n *y = 2*((yStart + j) % width + 1)\n if (getMaze(*x, *y) == path && !straightThru(*x, *y, path) && findDirections(*x, *y, &length, wall, directions) > 0) {\n return true\n }\n }\n }\n return false\n}", "func getStartIndex(st int32, a []int32) int {\n\tif st <= a[0] {\n\t\treturn 0 // st a[0]......a[len(a) - 1]\n\t}\n\tif st == a[len(a)-1] {\n\t\treturn len(a) - 1\n\t}\n\tif st > a[len(a)-1] {\n\t\treturn -1 // a[0]......a[len(a) - 1] st\n\t}\n\treturn sort.Search(len(a), func(i int) bool {\n\t\treturn a[i] >= st // a[0], a[1], st, a[2], a[3]....a[len(a) - 1]\n\t})\n}", "func (ed *Edges) zeroStart(start int) {\n\ted.grow(start)\n\toffset := start * 6\n\tfor i := range ed.slice[offset : offset+6] {\n\t\ted.slice[offset+i] = Edge{}\n\t}\n}", "func (root *mTreap) start(mask, match treapIterType) treapIter {\n\tf := treapFilter(mask, match)\n\treturn treapIter{f, root.treap.findMinimal(f)}\n}", "func (f *Feature) Start() float64 {\n\treturn f.location.PointCoord(0)\n}", "func getMiddle(x int, y int) int {\n\tif x > y {\n\t\treturn ((x - y) / 2) + y\n\t} else {\n\t\treturn ((y - x) / 2) + x\n\t}\n}", "func stepRU(position Point, slice [][]int32) Point {\n\tif position.x+2 < len(slice) &&\n\t\tposition.y-1 >= 0 &&\n\t\tslice[position.y-1][position.x+2] == 0 {\n\t\treturn Point{\n\t\t\tx: position.x + 2,\n\t\t\ty: position.y - 1,\n\t\t}\n\t}\n\treturn notPoint\n}", "func onesFromTo(startPos, endPos uint) uint64 {\n\t// if endPos < startPos {\n\t// \tpanic(\"assert\")\n\t// }\n\n\t// Generate two overlapping sequences of 1s, and keep the overlap.\n\thighOrderOnes := all1s << startPos\n\tlowOrderOnes := all1s >> (64 - endPos - 1)\n\tresult := highOrderOnes & lowOrderOnes\n\treturn result\n}", "func (px *Paxos) Start(seq int, v interface{}) {\n\t// Your code here.\n\t// TBD: check seq < px.Min() in px.Propose? Start should return immidiately\n\tgo px.Propose(seq, v)\n}", "func jump(nums []int) int {\n\n\tn := len(nums)\n\tif n <= 1 {\n\t\treturn 0\n\t}\n\t//当前位置可达最远距离\n\tfar := 0\n\t//上一跳最远距离,到达该位置时,进行下一跳,跳至下一个位置最远距离\n\tend := 0\n\tstep := 0\n\tfor i := 0; i < n-1; i++ {\n\t\tif i+nums[i] > far {\n\t\t\tfar = i + nums[i]\n\t\t}\n\t\tif i == end {\n\t\t\tend = far\n\t\t\tstep++\n\t\t}\n\t}\n\t//判断最远距离是否到达终点\n\tif far < n-1 {\n\t\treturn -1\n\t}\n\treturn step\n}", "func (s segment) responsibilityPosition(pos float64) (float64, float64) {\n\tif pos < 0.0 {\n\t\tpos = 0.0\n\t}\n\tif pos > float64(s.length()) {\n\t\tpos = float64(s.length())\n\t}\n\tx := float64(s.start.position.X) + float64(s.start.direction.X)*pos\n\ty := float64(s.start.position.Y) + float64(s.start.direction.Y)*pos\n\treturn x, y\n}", "func main() {\n\tbusTables := readBusTables()\n\n\tfmt.Println(busTables)\n\n\tstartPoint := 0\n\tfor bound := 2; bound <= len(busTables); bound++ {\n\t\thighestPos, highestBusID := findHighestBusID(busTables[:bound])\n\t\tif startPoint == 0 {\n\t\t\tstartPoint = highestBusID\n\t\t}\n\t\tcalculateDeltas(busTables[:bound], highestPos)\n\t\tfmt.Println(busTables)\n\t\tfmt.Println(startPoint)\n\t\tstartPoint = earlistCascade(busTables[:bound], startPoint) - highestBusID\n\t}\n\n\tfmt.Printf(\"earlist start point all busses depart one after another: %d\\n\", startPoint)\n}", "func shortestPath(youPath, sanPath []string) int {\n\tfor i := range youPath {\n\t\tfor j := range sanPath {\n\t\t\tif youPath[i] == sanPath[j] {\n\t\t\t\treturn i + j - 2 // don't count the two starting paths\n\t\t\t}\n\t\t}\n\t}\n\treturn -1\n}", "func (pm *IntegerParameterRange) Start() interface{} {\n\treturn pm.start\n}", "func minStartValue(nums []int) int {\n\tstartValue, sum := 1, 1\n\tfor _, num := range nums {\n\t\tsum = sum + num\n\t\tif sum <= 0 {\n\t\t\taddNum := 1 - sum\n\t\t\tsum, startValue = sum+addNum, startValue+addNum\n\t\t}\n\t}\n\treturn startValue\n}", "func paging(start, length, totalCount int) (int, int) {\n\tif length == 0 {\n\t\tlength = 20\n\t}\n\n\tstart = totalCount - start - length\n\tif start < 0 {\n\t\tlength += start\n\t\tstart = 0\n\t}\n\treturn start, length\n}", "func part2(mem []int64) int64 {\n\tg := readGrid(mem)\n\tvar r robot\n\tfor y, row := range g {\n\t\tfor x, c := range row {\n\t\t\tif strings.ContainsRune(\"^v<>\", c) {\n\t\t\t\tr = robot{point{x, y}, north}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tprev := r.pos.move(west)\n\tpath := []direction{east}\n\tfor {\n\t\tadj := adjacent(g, r.pos)\n\t\tif len(path) > 2 && len(adj) == 1 {\n\t\t\tbreak\n\t\t}\n\t\tif 0 < len(adj) && len(adj) <= 2 {\n\t\t\tnext := adj[0]\n\t\t\tif len(adj) == 2 && adj[0] == prev {\n\t\t\t\tnext = adj[1]\n\t\t\t}\n\t\t\tif r.pos.x < next.x {\n\t\t\t\tr.dir = east\n\t\t\t}\n\t\t\tif r.pos.x > next.x {\n\t\t\t\tr.dir = west\n\t\t\t}\n\t\t\tif r.pos.y < next.y {\n\t\t\t\tr.dir = south\n\t\t\t}\n\t\t\tif r.pos.y > next.y {\n\t\t\t\tr.dir = north\n\t\t\t}\n\t\t}\n\t\tpath = append(path, r.dir)\n\t\tprev = r.pos\n\t\tr.move()\n\t}\n\n\tqueue := []step{{0, right}}\n\tfor i, d := range path[1:] {\n\t\trot := path[i].rotation(d)\n\t\tif len(queue) > 0 && rot == none {\n\t\t\tqueue[len(queue)-1].n++\n\t\t\tcontinue\n\t\t}\n\t\tqueue = append(queue, step{1, rot})\n\t}\n\n\tvar out string\n\tfor _, v := range queue {\n\t\tout += v.String() + \",\"\n\t}\n\tfmt.Println(out)\n\n\tp := newProgram(mem)\n\tp.memory[0] = 2\n\t// I have to be honest. I used my editors \"highlight other occurrences\"\n\t// feature on the previous output.\n\tin := strings.Join([]string{\n\t\t\"A,B,A,C,A,B,C,C,A,B\",\n\t\t\"R,8,L,10,R,8\",\n\t\t\"R,12,R,8,L,8,L,12\",\n\t\t\"L,12,L,10,L,8\",\n\t\t\"n\",\n\t\t\"\",\n\t}, \"\\n\")\n\tfor _, c := range in {\n\t\tp.input = append(p.input, int64(c))\n\t}\n\tres, err := p.run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn res[len(res)-1]\n}", "func WindowStart(t, every, offset int64) int64 {\n\tmod := Modulo(t, every)\n\toff := Modulo(offset, every)\n\tbeg := t - mod + off\n\tif mod < off {\n\t\tbeg -= every\n\t}\n\treturn beg\n}", "func Point_one() (Point) { \n\ttoken := make([]byte,32)\n\ttoken[0]=1\n\treturn Point{*big.NewInt(0),*big.NewInt(0),token}\n}", "func stepUL(position Point, slice [][]int32) Point {\n\tif position.x-1 >= 0 &&\n\t\tposition.y-2 >= 0 &&\n\t\tslice[position.y-2][position.x-1] == 0 {\n\t\treturn Point{\n\t\t\tx: position.x - 1,\n\t\t\ty: position.y - 2,\n\t\t}\n\t}\n\treturn notPoint\n}", "func inverseStart(sbet1, cbet1, sbet2, cbet2, lam12, _salp2, _calp2 float64, C1a, C2a []float64) (sig12, salp1, calp1, salp2, calp2 float64) {\n\n\tsig12 = -1.\n\tsalp2, calp2 = _salp2, _calp2\n\t// bet12 = bet2 - bet1 in [0, pi); bet12a = bet2 + bet1 in (-pi, 0]\n\tsbet12 := sbet2*cbet1 - cbet2*sbet1\n\tcbet12 := cbet2*cbet1 + sbet2*sbet1\n\tsbet12a := sbet2*cbet1 + cbet2*sbet1\n\n\tshortline := cbet12 >= 0 && sbet12 < 0.5 && lam12 <= math.Pi/6\n\n\tomg12 := lam12\n\tif shortline {\n\t\tomg12 = lam12 / math.Sqrt(1-_e2*cbet1*cbet1)\n\t}\n\tsomg12, comg12 := math.Sincos(omg12)\n\n\tsalp1 = cbet2 * somg12\n\tif comg12 >= 0 {\n\t\tcalp1 = sbet12 + cbet2*sbet1*somg12*somg12/(1.+comg12)\n\t} else {\n\t\tcalp1 = sbet12a - cbet2*sbet1*somg12*somg12/(1.-comg12)\n\t}\n\n\tssig12 := math.Hypot(salp1, calp1)\n\tcsig12 := sbet1*sbet2 + cbet1*cbet2*comg12\n\n\tif shortline && ssig12 < _etol2 {\n\t\t// really short lines\n\t\tsalp2 = cbet1 * somg12\n\t\tcalp2 = sbet12 - cbet1*sbet2*somg12*somg12/(1+comg12)\n\t\tsalp2, calp2 = sinCosNorm(salp2, calp2)\n\t\t// Set return value\n\t\tsig12 = math.Atan2(ssig12, csig12)\n\t} else if csig12 >= 0 || ssig12 >= 3*math.Abs(_f)*math.Pi*cbet1*cbet1 {\n\t\t// Nothing to do, zeroth order spherical approximation is OK\n\t} else {\n\t\t// Scale lam12 and bet2 to x, y coordinate system where antipodal point\n\t\t// is at origin and singular point is at y = 0, x = -1.\n\t\tvar x, y, lamscale, betscale float64\n\t\tif _f >= 0 { // In fact f == 0 does not get here\n\t\t\t// x = dlong, y = dlat\n\t\t\tk2 := sbet1 * sbet1 * _ep2\n\t\t\teps := k2 / (2*(1+math.Sqrt(1+k2)) + k2)\n\t\t\tlamscale = _f * cbet1 * a3f(eps) * math.Pi\n\t\t\tbetscale = lamscale * cbet1\n\n\t\t\tx = (lam12 - math.Pi) / lamscale\n\t\t\ty = sbet12a / betscale\n\t\t} else { // _f < 0\n\t\t\t// x = dlat, y = dlong\n\t\t\tcbet12a := cbet2*cbet1 - sbet2*sbet1\n\t\t\tbet12a := math.Atan2(sbet12a, cbet12a)\n\n\t\t\t// In the case of lon12 = 180, this repeats a calculation made in\n\t\t\t// Inverse.\n\t\t\t_, m12a, m0 := lengths(_n, math.Pi+bet12a, sbet1, -cbet1, sbet2, cbet2, cbet1, cbet2, C1a, C2a)\n\n\t\t\tx = -1 + m12a/(_f1*cbet1*cbet2*m0*math.Pi)\n\t\t\tif x < -0.01 {\n\t\t\t\tbetscale = sbet12a / x\n\t\t\t} else {\n\t\t\t\tbetscale = -_f * cbet1 * cbet1 * math.Pi\n\t\t\t}\n\t\t\tlamscale = betscale / cbet1\n\t\t\ty = (lam12 - math.Pi) / lamscale\n\t\t}\n\n\t\tif y > -_tol1 && x > -1-_xthresh {\n\t\t\t// strip near cut\n\t\t\tif _f >= 0 {\n\t\t\t\tsalp1 = min(1, -x)\n\t\t\t\tcalp1 = -math.Sqrt(1 - salp1*salp1)\n\t\t\t} else {\n\t\t\t\tif x > -_tol1 {\n\t\t\t\t\tcalp1 = max(0, x)\n\t\t\t\t} else {\n\t\t\t\t\tcalp1 = max(-1, x)\n\t\t\t\t}\n\t\t\t\tsalp1 = math.Sqrt(1 - calp1*calp1)\n\t\t\t}\n\t\t} else {\n\t\t\tk := astroid(x, y)\n\n\t\t\tomg12a := lamscale\n\t\t\tif _f >= 0 {\n\t\t\t\tomg12a *= -x * k / (1 + k)\n\t\t\t} else {\n\t\t\t\tomg12a *= -y * (1 + k) / k\n\t\t\t}\n\n\t\t\tsomg12, comg12 := math.Sincos(omg12a)\n\t\t\tcomg12 = -comg12\n\n\t\t\t// Update spherical estimate of alp1 using omg12 instead of lam12\n\t\t\tsalp1 = cbet2 * somg12\n\t\t\tcalp1 = sbet12a - cbet2*sbet1*somg12*somg12/(1-comg12)\n\t\t}\n\t}\n\n\tsalp1, calp1 = sinCosNorm(salp1, calp1)\n\treturn\n}", "func crossoverOne(parent1 *Member, parent2 *Member, point int) (*Member, *Member) {\n\t//\tchoose a random point between the beginning and the end\n\tif point == -1 {\n\t\tminval := min(len(parent1.Track)-1, len(parent2.Track)-1)\n\t\tpoint = rand.Intn(minval)\n\t}\n\treturn crossoverAtPoint(parent1, parent2, point)\n}", "func lineStart(f *token.File, line int) token.Pos {\n\t// Use binary search to find the start offset of this line.\n\t//\n\t// TODO(rstambler): eventually replace this function with the\n\t// simpler and more efficient (*go/token.File).LineStart, added\n\t// in go1.12.\n\n\tmin := 0 // inclusive\n\tmax := f.Size() // exclusive\n\tfor {\n\t\toffset := (min + max) / 2\n\t\tpos := f.Pos(offset)\n\t\tposn := f.Position(pos)\n\t\tif posn.Line == line {\n\t\t\treturn pos - (token.Pos(posn.Column) - 1)\n\t\t}\n\n\t\tif min+1 >= max {\n\t\t\treturn token.NoPos\n\t\t}\n\n\t\tif posn.Line < line {\n\t\t\tmin = offset\n\t\t} else {\n\t\t\tmax = offset\n\t\t}\n\t}\n}", "func findNearNeighbor(x []float64, y []float64, points map[int]int, start int) int {\n neighbor := 0\n smDist := 10000000.0\n\n // Loop through all yet visited points to find out the cloesest point to current point.\n for i := 1; i < len(points); i++ {\n if (i != start) && (points[i] != 0) {\n sqSum := math.Pow(x[i] - x[start], 2) + math.Pow(y[i] - y[start], 2)\n dist := math.Sqrt(sqSum)\n if dist < smDist {\n neighbor = i\n smDist = dist\n }\n }\n }\n return neighbor\n}", "func (q *QQwry) getMiddleOffset(start uint32, end uint32) uint32 {\n\trecords := ((end - start) / INDEX_LEN) >> 1\n\treturn start + records*INDEX_LEN\n}", "func leadingDrawdownSequence(returns []Percent) ([]GrowthMultiplier, bool) {\n\tend := -1\n\tcumulativeReturns := cumulativeList(returns)[1:]\n\tfor i, value := range cumulativeReturns {\n\t\tif value >= 1 {\n\t\t\tend = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif end == -1 {\n\t\treturn cumulativeReturns, false\n\t}\n\treturn cumulativeReturns[0:end], true\n}", "func linePointsGen(p1, p2 Point, speed float64) (gen func() (x, y float64, e error)) {\n\t// Set up math\n\tslopeT, slope, _ := getLineParams(p1, p2)\n\n\tx := p1.X\n\txPrev := x\n\ty := p1.Y\n\tyPrev := y\n\te := fmt.Errorf(\"End of path reached\")\n\ttheta := math.Atan(slope)\n\n\t// Every slope type has a different iterator, since they change the\n\t// x and y values in different combinations, as well as do different\n\t// comparisons on the values.\n\tswitch slopeT {\n\tcase ZERORIGHT:\n\t\treturn func() (float64, float64, error) {\n\t\t\tif x > p2.X {\n\t\t\t\treturn 0, 0, e\n\t\t\t}\n\n\t\t\txPrev = x\n\t\t\tx += speed\n\n\t\t\treturn xPrev, y, nil\n\t\t}\n\tcase ZEROLEFT:\n\t\treturn func() (float64, float64, error) {\n\t\t\tif x < p2.X {\n\t\t\t\treturn 0, 0, e\n\t\t\t}\n\n\t\t\txPrev = x\n\t\t\tx -= speed\n\n\t\t\treturn xPrev, y, nil\n\t\t}\n\tcase POSRIGHT:\n\t\treturn func() (float64, float64, error) {\n\t\t\tif y > p2.Y || x > p2.X {\n\t\t\t\treturn 0, 0, e\n\t\t\t}\n\n\t\t\tyPrev = y\n\t\t\txPrev = x\n\n\t\t\ty += speed * math.Sin(theta)\n\t\t\tx += speed * math.Cos(theta)\n\n\t\t\treturn xPrev, yPrev, nil\n\t\t}\n\tcase NEGRIGHT:\n\t\treturn func() (float64, float64, error) {\n\t\t\tif y < p2.Y || x > p2.X {\n\t\t\t\treturn 0, 0, e\n\t\t\t}\n\n\t\t\tyPrev = y\n\t\t\txPrev = x\n\n\t\t\ty += speed * math.Sin(theta)\n\t\t\tx += speed * math.Cos(theta)\n\n\t\t\treturn xPrev, yPrev, nil\n\t\t}\n\tcase POSLEFT:\n\t\treturn func() (float64, float64, error) {\n\t\t\tif y < p2.Y || x < p2.X {\n\t\t\t\treturn 0, 0, e\n\t\t\t}\n\n\t\t\tyPrev = y\n\t\t\txPrev = x\n\n\t\t\ty -= speed * math.Sin(theta)\n\t\t\tx -= speed * math.Cos(theta)\n\n\t\t\treturn xPrev, yPrev, nil\n\t\t}\n\tcase NEGLEFT:\n\t\treturn func() (float64, float64, error) {\n\t\t\tif y > p2.Y || x < p2.X {\n\t\t\t\treturn 0, 0, e\n\t\t\t}\n\n\t\t\tyPrev = y\n\t\t\txPrev = x\n\n\t\t\ty -= speed * math.Sin(theta)\n\t\t\tx -= speed * math.Cos(theta)\n\n\t\t\treturn xPrev, yPrev, nil\n\t\t}\n\tcase INFUP:\n\t\treturn func() (float64, float64, error) {\n\t\t\tif y > p2.Y {\n\t\t\t\treturn 0, 0, e\n\t\t\t}\n\n\t\t\tyPrev := y\n\t\t\ty += speed\n\n\t\t\treturn x, yPrev, nil\n\t\t}\n\tcase INFDOWN:\n\t\treturn func() (float64, float64, error) {\n\t\t\tif y < p2.Y {\n\t\t\t\treturn 0, 0, e\n\t\t\t}\n\n\t\t\tyPrev := y\n\t\t\ty -= speed\n\n\t\t\treturn x, yPrev, nil\n\t\t}\n\t}\n\n\treturn nil\n}", "func find(gs []*Geodesic, v Vector, minDistSq float64, start int) int {\n\tgs0 := gs[0]\n\tnextStart := start\n\tneighbors := gs0.Faces[start].Neighbors\n\tfor _, n := range neighbors {\n\t\tiDistSq := DistSq(gs0.Centers[n], v)\n\t\tif iDistSq < minDistSq {\n\t\t\tminDistSq = iDistSq\n\t\t\tnextStart = n\n\t\t}\n\t}\n\n\tif len(gs) == 1 {\n\t\t// There's a bug related to correctly classifying the neighbor of a\n\t\t// pentagon face, so this corrects for that.\n\t\tif nextStart == start {\n\t\t\treturn nextStart\n\t\t}\n\t\treturn find(gs, v, minDistSq, nextStart)\n\t}\n\n\treturn find(gs[1:], v, minDistSq, nextStart)\n}", "func (self *BpNode) get_start(key types.Hashable) (i int, leaf *BpNode) {\n\tif self.Internal() {\n\t\treturn self.internal_get_start(key)\n\t} else {\n\t\treturn self.leaf_get_start(key)\n\t}\n}", "func (client *Client) nextAllocationStep(previous int64) int64 {\n\t// TODO: ensure that this is frame idependent\n\tnext := previous * 3 / 2\n\tif next > client.config.MaximumStep {\n\t\tnext = client.config.MaximumStep\n\t}\n\treturn next\n}", "func part1(arr []int) int {\n\tvar i, j int\n\tn := len(arr)\n\n\ti = 0\n\tj = n - 1\n\n\tfor i < n && j >= 0 {\n\t\tif arr[i]+arr[j] == target {\n\t\t\tbreak\n\t\t}\n\t\tif arr[i]+arr[j] < target {\n\t\t\ti++\n\t\t} else {\n\t\t\tj--\n\t\t}\n\t}\n\treturn arr[i] * arr[j]\n}", "func findMazeStartAndEnd(gridPtr *gameGrid) (startPtr, endPtr *gridSquare) {\n\tfor x := range *gridPtr {\n\t\tfor y := range (*gridPtr)[x] {\n\t\t\tsquarePtr := getSquarePtr(gridPtr, x, y)\n\n\t\t\tswitch (*squarePtr).marker {\n\t\t\tcase 'S':\n\t\t\t\tif startPtr != nil {\n\t\t\t\t\tpanic(\"Too many start positions ('S') marked!\")\n\t\t\t\t}\n\t\t\t\tstartPtr = squarePtr\n\t\t\t\tdrawText(fmt.Sprintf(\"Found start at %v,%v (dist:%v)\", (*squarePtr).posX, (*squarePtr).posY, (*squarePtr).distance))\n\n\t\t\tcase 'E':\n\t\t\t\tif endPtr != nil {\n\t\t\t\t\tpanic(\"Too many end positions ('E') marked!\")\n\t\t\t\t}\n\t\t\t\tendPtr = squarePtr\n\t\t\t\tdrawText(fmt.Sprintf(\"Found end at %v,%v\", (*squarePtr).posX, (*squarePtr).posY))\n\t\t\t}\n\t\t}\n\t}\n\tif startPtr == nil {\n\t\tpanic(\"Board is missing start position ('S')!\")\n\t}\n\tif endPtr == nil {\n\t\tpanic(\"Board is missing end position ('E')!\")\n\t}\n\tlogOnExit(fmt.Sprintf(\"start pos: %v,%v, end pos: %v,%v\",\n\t\t(*startPtr).posX, (*startPtr).posY, (*endPtr).posX, (*endPtr).posY))\n\treturn\n}", "func GetStartAndEndIndexForCurrentThread(tasksPerThread int, threadNumber int, totalTasks int) (int, int){\n\tstartIndex := threadNumber * tasksPerThread\n\tendIndex := min(startIndex + tasksPerThread, totalTasks)\n\treturn startIndex, endIndex\n}", "func stepDR(position Point, slice [][]int32) Point {\n\tif position.x+1 < len(slice) &&\n\t\tposition.y+2 < len(slice[position.y]) &&\n\t\tslice[position.y+2][position.x+1] == 0 {\n\t\treturn Point{\n\t\t\tx: position.x + 1,\n\t\t\ty: position.y + 2,\n\t\t}\n\t}\n\treturn notPoint\n}", "func (px *Paxos) Start(seq int, v interface{}) {\n\tif seq >= px.Min() {\n\t\tpx.mu.Lock()\n\t\tpx.mu.Unlock()\n\t\tpx.proposer(seq, v) // THIS IS OUR CODE - changed from go\n\t}\n\n}", "func moveCursorLeft(positionCursor *int, numberDigits int,listOfNumbers [6]int) {\n\n\tif *positionCursor == 0 { \t\t\t\t\t\t // Scenario 1: position of cursor at the beginning of list\n\n\t\t*positionCursor=numberDigits-1\t\t\t\t // set it to the end\n\n\t\tpositionCursor = &listOfNumbers[numberDigits-1] // sets address of position to be that of the correct element\n\n\t} else {\t\t\t\t\t\t\t\t\t\t // Scenario 2: position of cursor is not at the beginning of list\n\n\t\t*positionCursor--\t\t\t\t\t\t\t // decrease the value of position of the cursor\n\n\t\tvar temp = *positionCursor\t\t\t\t\t // temp variable for position of cursor\n\n\t\tpositionCursor = &listOfNumbers[temp] \t // sets address of position to be that of the correct element\n\t}\n}", "func (g *Graph) GetStartEndVerticies(mapInfo structs.MapSpec) (int, int) {\n\tvertNum := 0\n\tstartVertNum := 0\n\ttargetVertNum := 0\n\tfor i := 0; i < mapInfo.Height; i++ {\n\t\tfor j := 0; j < mapInfo.Width; j++ {\n\t\t\tif i == mapInfo.StartPosY && j == mapInfo.StartPosX {\n\t\t\t\tstartVertNum = vertNum\n\t\t\t}\n\t\t\tif i == mapInfo.GoalPosY && j == mapInfo.GoalPosX {\n\t\t\t\ttargetVertNum = vertNum\n\t\t\t}\n\t\t\tvertNum++\n\t\t}\n\t}\n\treturn startVertNum, targetVertNum\n}", "func main() {\n\tx := []int{42, 43, 44, 45, 46, 47, 48, 49, 50, 51}\n\n\tfirst_sl := x[0:5]\n\tsecond_sl := x[5:]\n\tthird_sl := x[2:7]\n\tfourth_sl := x[1:6]\n\n\tfmt.Println(first_sl)\n\tfmt.Println(second_sl)\n\tfmt.Println(third_sl)\n\tfmt.Println(fourth_sl)\n\n}", "func getPosLimit(pos Point, max *Point, rv int32) (start, end Point) {\n\tif (pos.X - rv) < 0 {\n\t\tstart.X = 0\n\t\tend.X = 2 * rv\n\t} else if (pos.X + rv) > max.X {\n\t\tend.X = max.X\n\t\tstart.X = max.X - 2*rv\n\t} else {\n\t\tstart.X = pos.X - rv\n\t\tend.X = pos.X + rv\n\t}\n\n\tif (pos.Y - rv) < 0 {\n\t\tstart.Y = 0\n\t\tend.Y = 2 * rv\n\t} else if (pos.Y + rv) > max.Y {\n\t\tend.Y = max.Y\n\t\tstart.Y = max.Y - 2*rv\n\t} else {\n\t\tstart.Y = pos.Y - rv\n\t\tend.Y = pos.Y + rv\n\t}\n\n\tif start.X < 0 {\n\t\tstart.X = 0\n\t}\n\n\tif end.X > max.X {\n\t\tend.X = max.X\n\t}\n\n\tif start.Y < 0 {\n\t\tstart.Y = 0\n\t}\n\n\tif end.Y > max.Y {\n\t\tend.Y = max.Y\n\t}\n\n\treturn\n}", "func stepDL(position Point, slice [][]int32) Point {\n\tif position.x-1 >= 0 &&\n\t\tposition.y+2 < len(slice[position.y]) &&\n\t\tslice[position.y+2][position.x-1] == 0 {\n\t\treturn Point{\n\t\t\tx: position.x - 1,\n\t\t\ty: position.y + 2,\n\t\t}\n\t}\n\treturn notPoint\n}", "func next2Values(number int)(int, int){\n\treturn number+1, number+2\n}", "func carvePaths(x, y int) {\n if x > 0 && y > 0 {\n carvePath(&x, &y)\n }\n for findPathStart(&x, &y) &&\n carvePath(&x, &y) {\n }\n}", "func findDelta(first, second float64) float64 {\n\tif first == 0 {\n\t\treturn 0\n\t}\n\treturn second / first\n}", "func step1(w string) string {\n\tvar suffixes []string = []string{\"erendes\", \"erende\", \"hedens\", \"erede\", \"ethed\", \"heden\", \"endes\", \"erets\", \"heder\", \"ernes\", \"erens\", \"ered\", \"ende\", \"erne\", \"eres\", \"eren\", \"eret\", \"erer\", \"enes\", \"heds\", \"ens\", \"ene\", \"ere\", \"ers\", \"ets\", \"hed\", \"es\", \"et\", \"er\", \"en\", \"e\"}\n\n\tfor _, suffix := range suffixes {\n\t\tif searchInR1(w, suffix) {\n i := str.LastIndex(w, suffix)\n w = w[:i]\n break\n\t\t}\n\t}\n\n\t// s\n\t// delete if preceded by a valid s-ending\n\tif searchInR1(w, \"s\") {\n\t\tif hasValidEnding(w) == true {\n\t\t\tw = str.TrimSuffix(w, \"s\")\n\t\t}\n\t}\n\n\treturn w\n}", "func (f *lazyCallReq) Arg2StartOffset() int {\n\treturn int(f.arg2StartOffset)\n}", "func (orderbook *Orderbook) backfillPoints(topbook []*Point, pointDistance uint64, leftMultiple uint64, rightMultiple uint64) []*Point {\n\tfor currentMultiple := leftMultiple; currentMultiple < rightMultiple; currentMultiple++ {\n\t\tpoint := CreatePoint(orderbook, (currentMultiple+1)*pointDistance)\n\t\ttopbook = append(topbook, &point)\n\t}\n\treturn topbook\n}", "func getParentIndex(pos int) int {\n\treturn (pos - 1) / 2\n}", "func findPaths2(m int, n int, maxMove int, startRow int, startColumn int) int {\n\t// 값이 클 수 있어 modulo 모듈 값을 리턴하라고 문제에 써있음\n\tmodulo := 1000000000 + 7\n\tif startRow < 0 || startRow == m ||\n\t\tstartColumn < 0 || startColumn == n {\n\t\treturn 1\n\t}\n\tif maxMove == 0 {\n\t\treturn 0\n\t}\n\t// 4방향 각각에 대해서 boundary 를 벗어나는지 경우들을 모두 더한다.\n\treturn findPaths(m, n, maxMove-1, startRow-1, startColumn)%modulo +\n\t\tfindPaths(m, n, maxMove-1, startRow, startColumn-1)%modulo +\n\t\tfindPaths(m, n, maxMove-1, startRow+1, startColumn)%modulo +\n\t\tfindPaths(m, n, maxMove-1, startRow, startColumn+1)%modulo\n}", "func (d *DStarLite) Step() bool {\n\t/*\n\t procedure Main()\n\t {32”} while (s_start != s_goal)\n\t {33”} // if (rhs(s_start) = ∞) then there is no known path\n\t {34”} s_start = argmin s'∈Succ(s_start)(c(s_start, s') + g(s'));\n\t*/\n\tif d.s.ID() == d.t.ID() {\n\t\treturn false\n\t}\n\tif math.IsInf(d.s.rhs, 1) {\n\t\treturn false\n\t}\n\n\t// We use rhs comparison to break ties\n\t// between coequally weighted nodes.\n\trhs := math.Inf(1)\n\tmin := math.Inf(1)\n\n\tvar next *dStarLiteNode\n\tdsid := d.s.ID()\n\tto := d.model.From(dsid)\n\tfor to.Next() {\n\t\ts := to.Node().(*dStarLiteNode)\n\t\tw := edgeWeight(d.model.Weight, dsid, s.ID()) + s.g\n\t\tif w < min || (w == min && s.rhs < rhs) {\n\t\t\tnext = s\n\t\t\tmin = w\n\t\t\trhs = s.rhs\n\t\t}\n\t}\n\td.s = next\n\n\t/*\n\t procedure Main()\n\t {35”} Move to s_start;\n\t*/\n\treturn true\n}", "func getCoordinatesForIndex(index int) (int, int) {\n\treturn index % 3, index / 3o hello world\n\n}", "func firstGE(nums []int, target int) int {\n\n\tif nums[0] >= target {\n\t\treturn 0\n\t}\n\tvar start = 0\n\tvar end = len(nums)\n\tfor start+1 < end {\n\t\tvar mid = start + (end-start)/2\n\t\tif nums[mid] >= target {\n\t\t\tend = mid\n\t\t} else {\n\t\t\tstart = mid\n\t\t}\n\t}\n\treturn end\n}", "func getMoveDirection(from, to *point) int {\n\tif from.x == to.x && from.y == to.y+1 {\n\t\treturn 1\n\t} else if from.x == to.x && from.y == to.y-1 {\n\t\treturn 2\n\t} else if from.x == to.x+1 && from.y == to.y {\n\t\treturn 3\n\t} else if from.x == to.x-1 && from.y == to.y {\n\t\treturn 4\n\t} else {\n\t\tlog.Fatalf(\"Points %v and %v are not adjacent\\n\", from, to)\n\t}\n\treturn 0\n}", "func PrevOne(bm []uint64, i, end int32) int32 {\n\n\tend--\n\twordIdx := end >> 6\n\tbitIdx := end & 63\n\tvar prv int32 = -1\n\n\tword := bm[wordIdx] & MaskUpto[bitIdx]\n\tif word != 0 {\n\t\tprv = wordIdx<<6 + 63 - int32(bits.LeadingZeros64(word))\n\t} else {\n\t\tend = (end & ^63) - 1\n\n\t\tfor ; end >= i; end -= 64 {\n\n\t\t\tword := bm[end>>6]\n\t\t\tif word != 0 {\n\t\t\t\tprv = end - int32(bits.LeadingZeros64(word))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif prv < i {\n\t\treturn -1\n\t}\n\n\treturn prv\n}", "func CheckStart(mess string, t *testing.T, g *Immutable, v int, visited []bool) {\n\tn := g.Order()\n\tcheck := make([]bool, len(visited)) // Check that we get the same neighbors.\n\tfor a := 0; a <= n+1; a++ {\n\t\tprev := -1\n\t\tfor v := a; v < n; v++ {\n\t\t\tcheck[v] = visited[v]\n\t\t}\n\t\tg.VisitFrom(v, a, func(w int, _ int64) (skip bool) {\n\t\t\tif w < 0 {\n\t\t\t\tt.Errorf(\"%s: visit(%d, %d): returned negative w=%d\", mess, v, a, w)\n\t\t\t}\n\t\t\tif w >= n {\n\t\t\t\tt.Errorf(\"%s: visit(%d, %d): returned w=%d bigger than n=%d\", mess, v, a, w, n)\n\t\t\t}\n\t\t\tif w < a {\n\t\t\t\tt.Errorf(\"%s: visit(%d, %d): returned small w=%d\", mess, v, a, w)\n\t\t\t} else if 0 <= w && w < n && !check[w] {\n\t\t\t\tt.Errorf(\"%s, visit(%d, %d) didn't return %d when a=0.\\n\", mess, v, a, w)\n\t\t\t}\n\t\t\tif prev > w {\n\t\t\t\tt.Errorf(\"%s, visit(%d, %d) returned %d before %d.\\n\", mess, v, a, prev, w)\n\t\t\t}\n\t\t\tcheck[w] = false\n\t\t\tprev = w\n\t\t\treturn\n\t\t})\n\t\tfor w := a; w < n; w++ {\n\t\t\tif check[w] {\n\t\t\t\tt.Errorf(\"%s, visit(%d, %d) did return %d when a=0.\\n\", mess, v, a, w)\n\t\t\t}\n\t\t}\n\t}\n}", "func getLayerFirstIx(layer float64) int32 {\r\n\treturn int32((math.Pow(4, layer) - 1) / 3)\r\n}", "func keypathpair(k0, k1 int) float64 {\n\tswitch p := math.Abs(float64(row(k0)-row(k1))) + math.Abs(float64(column(k0)-column(k1))); {\n\tcase finger(k0) == finger(k1):\n\t\treturn 2 * p\n\tcase (finger(k0) < finger(k1)) == (finger(k1) < 5):\n\t\treturn p - 0.5\n\tdefault:\n\t\treturn p\n\t}\n}", "func Part1(input Input) (result int) {\n\tspokenNumbers := make(map[int]int)\n\tfor turn, startingNumber := range input[:len(input)-1] {\n\t\tspokenNumbers[startingNumber] = turn + 1\n\t}\n\n\tlastNumber := input[len(input)-1]\n\tfor turn := len(input); turn < 2020; turn++ {\n\t\tlastSpoken, wasSpoken := spokenNumbers[lastNumber]\n\t\tspokenNumbers[lastNumber] = turn\n\t\tif !wasSpoken {\n\t\t\tlastNumber = 0\n\t\t} else {\n\t\t\tlastNumber = turn - lastSpoken\n\t\t}\n\t}\n\treturn lastNumber\n}", "func position(index int) (int, int) {\n\treturn index / 3, index % 3\n}", "func initialPosition(ctx, sub string, loc []int) (int, string) {\n\tidx := strings.Index(ctx, sub)\n\tif idx < 0 {\n\t\t// Fall back to the JaroWinkler distance. This should only happen if\n\t\t// we're in a scope that contains inline markup (e.g., a sentence with\n\t\t// code spans).\n\t\treturn JaroWinkler(ctx, sub)\n\t}\n\tpat := `(?:^|\\b|_)` + regexp.QuoteMeta(sub) + `(?:\\b|_|$)`\n\ttxt := strings.TrimSpace(ctx[Max(idx-1, 0):Min(idx+len(sub)+1, len(ctx))])\n\tif match, err := regexp.MatchString(pat, txt); err != nil || !match {\n\t\t// If there's more than one, we take the first bounded option.\n\t\t// For example, given that we're looking for \"very\", \"every\" => nested\n\t\t// and \" very \" => bounded.\n\t\tsloc := regexp.MustCompile(pat).FindStringIndex(ctx)\n\t\tif len(sloc) > 0 {\n\t\t\tidx = sloc[0]\n\t\t\tif strings.HasPrefix(ctx[idx:], \"_\") {\n\t\t\t\tidx++ // We don't want to include the underscore boundary.\n\t\t\t}\n\t\t}\n\t}\n\treturn utf8.RuneCountInString(ctx[:idx]) + 1, sub\n}", "func (stab *adaptiveStabilize) step() {\n\tstab.min += (stab.min / 2)\n\tstab.max += (stab.max / 2)\n}", "func minRefuelStops(target int, startFuel int, stations [][]int) int {\n \n}", "func (actor *Actor) start(idx, n int) {\n\tif idx == n {\n\t\treturn\n\t}\n\n\t// worker number starts from 1\n\tgo actor.work(idx + 1)\n\tactor.start(idx+1, n)\n}", "func StartCompute(start uint8) string {\n\tdate := time.Now().Format(\"2006-01-02\")\n\treturn fmt.Sprintf(\"%s %s:00\", date, strconv.Itoa(int(start)))\n}", "func (c *InstallerController) getRevisionToStart(currNodeState, prevNodeState *operatorv1.NodeStatus, operatorStatus *operatorv1.StaticPodOperatorStatus) int32 {\n\tif prevNodeState == nil {\n\t\tcurrentAtLatest := currNodeState.CurrentRevision == operatorStatus.LatestAvailableRevision\n\t\tif !currentAtLatest {\n\t\t\treturn operatorStatus.LatestAvailableRevision\n\t\t}\n\t\treturn 0\n\t}\n\n\tprevFinished := prevNodeState.TargetRevision == 0\n\tprevInTransition := prevNodeState.CurrentRevision != prevNodeState.TargetRevision\n\tif prevInTransition && !prevFinished {\n\t\treturn 0\n\t}\n\n\tprevAhead := prevNodeState.CurrentRevision > currNodeState.CurrentRevision\n\tfailedAtPrev := currNodeState.LastFailedRevision == prevNodeState.CurrentRevision\n\tif prevAhead && !failedAtPrev {\n\t\treturn prevNodeState.CurrentRevision\n\t}\n\n\treturn 0\n}", "func (px *Paxos) Start(seq int, v interface{}) {\n // Your code here.\n if seq < px.Min() {\n return\n }\n go func() {\n instance := px.getInstance(seq)\n instance.mu.Lock()\n defer instance.mu.Unlock()\n for !px.dead {\n if instance.decidedValue != nil {\n break\n }\n instance.proposer.highestSeenProposedNumber++\n instance.proposer.proposedNumber = instance.proposer.highestSeenProposedNumber\n ok, value := px.propose(instance, seq)\n if !ok {\n continue\n }\n if value != nil {\n v = value\n }\n if !px.requestAccept(instance, seq, v) {\n continue\n }\n px.decide(seq, v)\n break\n }\n }()\n}", "func getFinalPosition(commands []command) (int, int) {\n\thorizontal, depth := 0, 0\n\tfor _, cmd := range commands {\n\t\tswitch cmd.direction {\n\t\tcase \"forward\":\n\t\t\thorizontal += cmd.unit\n\t\tcase \"down\":\n\t\t\tdepth += cmd.unit\n\t\tcase \"up\":\n\t\t\tdepth -= cmd.unit\n\t\t}\n\t}\n\treturn horizontal, depth\n}", "func getR1R2End(s string) (string) {\n\t// Find initial vowels. Start as consonant; then find 1st vowel; then find 1st consonant after that.\n\tinitialVowel := false\n\tR1start := len(s) - 1 // default for specifying null region at the end\n\tLabel:\n\tfor i, c := range s {\n\t\tswitch initialVowel {\n\t\tcase false: // until 1st vowel\n\t\t\tif isVowel(c) {\n\t\t\t\tinitialVowel = true\n\t\t\t}\n\t\t\tcontinue\n\t\tcase true: // until 1st consonant after vowel\n\t\t\tif !isVowel(c) {\n\t\t\t\tR1start = i\n\t\t\t\tbreak Label // break defaults to breaking out of switch case\n\t\t\t}\n\t\t}\n\t}\n\treturn s[R1start+1:]\n}", "func fistStep(numbers []int) []int {\n\n\tdouble := make([]int, len(numbers))\n\n\tcopy(double, numbers)\n\n\tfor i := 0; i < len(double); i++ {\n\t\tif i%2 != 0 {\n\t\t\tdouble[i] = double[i] * 2\n\t\t\tif double[i] > 9 {\n\t\t\t\tdouble[i] = double[i] - 9\n\t\t\t}\n\t\t}\n\t}\n\n\treturn double\n}", "func nextLoc(q, r int, cmd string) (int, int) {\r\n\tswitch cmd {\r\n\tcase \"e\":\r\n\t\treturn q + 1, r\r\n\tcase \"w\":\r\n\t\treturn q - 1, r\r\n\tcase \"ne\":\r\n\t\tif r%2 == 0 {\r\n\t\t\treturn q, r - 1\r\n\t\t}\r\n\t\treturn q + 1, r - 1\r\n\tcase \"nw\":\r\n\t\tif r%2 == 0 {\r\n\t\t\treturn q - 1, r - 1\r\n\t\t}\r\n\t\treturn q, r - 1\r\n\tcase \"se\":\r\n\t\tif r%2 == 0 {\r\n\t\t\treturn q, r + 1\r\n\t\t}\r\n\t\treturn q + 1, r + 1\r\n\tcase \"sw\":\r\n\t\tif r%2 == 0 {\r\n\t\t\treturn q - 1, r + 1\r\n\t\t}\r\n\t\treturn q, r + 1\r\n\t}\r\n\tpanic(fmt.Sprintf(\"invalid command %s\", cmd))\r\n}", "func (ival *InputValue) Start() Pos {\n\tswitch {\n\tcase ival == nil:\n\t\treturn -1\n\tcase ival.Null != nil:\n\t\treturn ival.Null.Start\n\tcase ival.Scalar != nil:\n\t\treturn ival.Scalar.Start\n\tcase ival.VariableRef != nil:\n\t\treturn ival.VariableRef.Dollar\n\tcase ival.List != nil:\n\t\treturn ival.List.LBracket\n\tcase ival.InputObject != nil:\n\t\treturn ival.InputObject.LBrace\n\tdefault:\n\t\tpanic(\"unknown input value\")\n\t}\n}", "func (nn *NonNullType) Start() Pos {\n\tswitch {\n\tcase nn.Named != nil:\n\t\treturn nn.Named.Start\n\tcase nn.List != nil:\n\t\treturn nn.List.LBracket\n\tdefault:\n\t\tpanic(\"unknown non-null type\")\n\t}\n}", "func (p Partition) Start() VertexId {\n\treturn VertexId(p.StartIdx)\n}", "func pageRange(p *params, n int) (int, int) {\n\tif p.Count == 0 && p.Offset == 0 {\n\t\treturn 0, n\n\t}\n\tif p.Count < 0 {\n\t\t// Items from the back of the array, like Python arrays. Do a postive mod n.\n\t\treturn (((n + p.Count) % n) + n) % n, n\n\t}\n\tstart := p.Offset\n\tif start < 0 {\n\t\tstart = 0\n\t}\n\tif p.Count == 0 { // No count specified. Just take the offset parameter.\n\t\treturn start, n\n\t}\n\tend := start + p.Count\n\tif end > n {\n\t\tend = n\n\t}\n\treturn start, end\n}", "func next(start uintptr, size uintptr) uintptr {\n\tstart &= ^(size - 1)\n\tstart += size\n\treturn start\n}", "func Line(x0, y0, x1, y1 int) []image.Point {\n\tdx := int(math.Abs(float64(x1 - x0)))\n\tdy := int(math.Abs(float64(y1 - y0)))\n\tsx := 0\n\tsy := 0\n\tif x0 < x1 {\n\t\tsx = 1\n\t} else {\n\t\tsx = -1\n\t}\n\n\tif y0 < y1 {\n\t\tsy = 1\n\t} else {\n\t\tsy = -1\n\t}\n\n\terr := dx - dy\n\n\tps := make([]image.Point, 0)\n\tfor {\n\t\tps = append(ps, image.Pt(x0, y0))\n\t\tif x0 == x1 && y0 == y1 {\n\t\t\tbreak\n\t\t}\n\t\te2 := err * 2\n\t\tif e2 > -dy {\n\t\t\terr -= dy\n\t\t\tx0 += sx\n\t\t}\n\t\tif e2 < dx {\n\t\t\terr += dx\n\t\t\ty0 += sy\n\t\t}\n\t}\n\treturn ps\n}" ]
[ "0.5825244", "0.5791528", "0.558185", "0.55745775", "0.55386", "0.55188316", "0.54899657", "0.5474828", "0.54533607", "0.5444746", "0.54436755", "0.54403", "0.5420142", "0.5400024", "0.5377683", "0.5345384", "0.5345", "0.52899605", "0.5273703", "0.525066", "0.5220603", "0.5219867", "0.5217444", "0.5214905", "0.520959", "0.52090037", "0.5197125", "0.5185924", "0.5156647", "0.51480436", "0.51359993", "0.5132575", "0.51315045", "0.51315", "0.51213014", "0.51177585", "0.5112118", "0.5110181", "0.5098744", "0.5086364", "0.5079619", "0.5076255", "0.5076148", "0.50693697", "0.50621426", "0.50556165", "0.5053425", "0.5042808", "0.5036655", "0.5033806", "0.50255287", "0.5025429", "0.50245523", "0.5022115", "0.5020866", "0.5009143", "0.5002528", "0.49980697", "0.49928772", "0.49928132", "0.49900442", "0.49793494", "0.4977977", "0.4976695", "0.49739864", "0.49738604", "0.49719572", "0.4971236", "0.49710393", "0.49647167", "0.49647003", "0.49632075", "0.49615535", "0.49569875", "0.49565148", "0.4948287", "0.49440813", "0.49365863", "0.49329355", "0.4924943", "0.49241093", "0.49083483", "0.49081716", "0.49066007", "0.4904758", "0.49014923", "0.49011633", "0.48984134", "0.48931563", "0.48924136", "0.4889353", "0.48827842", "0.48807913", "0.4878049", "0.48647654", "0.486095", "0.48597482", "0.4848384", "0.48400572", "0.48376435", "0.48346484" ]
0.0
-1
/ Steps to convert 2 to 7: 3
func maxSlidingWindows(arr []int, k int) { size := len(arr) for i := 0; i < size-k+1; i++ { max := arr[i] for j := 1; j < k; j++ { if max < arr[i+j] { max = arr[i+j] } } fmt.Print(max, " ") } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func stepPerms(n int32) int32 {\n\tif n < 3 {\n\t\treturn n\n\t}\n\n\ta, b, c, current := 1, 2, 4, 0\n\n\tfor i := int32(3); i < n; i++ {\n\t\tcurrent = a + b + c\n\t\ta, b = b, c\n\t\tc = current\n\t}\n\n\treturn int32(c)\n}", "func solve2(input string) string {\n\tlist := parseInput(input)\n\ti := 0\n\tn := 0\n\tfor i >= 0 && i < len(list) {\n\t\tj := list[i]\n\t\tif j > 2 {\n\t\t\tlist[i]--\n\t\t} else {\n\t\t\tlist[i]++\n\t\t}\n\t\ti += j\n\t\tn++\n\t}\n\treturn fmt.Sprint(n)\n}", "func (stem *Stem) step3() {\r\n\tif stem.k == stem.k0 {\r\n\t\treturn /*ForBug1*/\r\n\t}\r\n\tswitch stem.b[stem.k-1] {\r\n\tcase 'a':\r\n\t\tif stem.ends(\"ational\") {\r\n\t\t\tstem.r(\"ate\")\r\n\t\t}\r\n\t\tif stem.ends(\"tional\") {\r\n\t\t\tstem.r(\"tion\")\r\n\t\t}\r\n\tcase 'c':\r\n\t\tif stem.ends(\"enci\") {\r\n\t\t\tstem.r(\"ence\")\r\n\t\t}\r\n\t\tif stem.ends(\"anci\") {\r\n\t\t\tstem.r(\"ance\")\r\n\t\t\tbreak\r\n\t\t}\r\n\tcase 'e':\r\n\t\tif stem.ends(\"izer\") {\r\n\t\t\tstem.r(\"ize\")\r\n\t\t}\r\n\tcase 'l':\r\n\t\tif stem.ends(\"bli\") {\r\n\t\t\tstem.r(\"ble\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"alli\") {\r\n\t\t\tstem.r(\"al\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"entli\") {\r\n\t\t\tstem.r(\"ent\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"eli\") {\r\n\t\t\tstem.r(\"e\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"ousli\") {\r\n\t\t\tstem.r(\"ous\")\r\n\t\t\tbreak\r\n\t\t}\r\n\tcase 'o':\r\n\t\tif stem.ends(\"ization\") {\r\n\t\t\tstem.r(\"ize\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"ation\") {\r\n\t\t\tstem.r(\"ate\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"ator\") {\r\n\t\t\tstem.r(\"ate\")\r\n\t\t\tbreak\r\n\t\t}\r\n\tcase 's':\r\n\t\tif stem.ends(\"alism\") {\r\n\t\t\tstem.r(\"al\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"iveness\") {\r\n\t\t\tstem.r(\"ive\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"fulness\") {\r\n\t\t\tstem.r(\"ful\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"ousness\") {\r\n\t\t\tstem.r(\"ous\")\r\n\t\t\tbreak\r\n\t\t}\r\n\tcase 't':\r\n\t\tif stem.ends(\"aliti\") {\r\n\t\t\tstem.r(\"al\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"iviti\") {\r\n\t\t\tstem.r(\"ive\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"biliti\") {\r\n\t\t\tstem.r(\"ble\")\r\n\t\t\tbreak\r\n\t\t}\r\n\tcase 'g':\r\n\t\tif stem.ends(\"logi\") {\r\n\t\t\tstem.r(\"log\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n}", "func part2(input []int) int {\n\tx := 0 // Last computed joltage (initialize on the 0j input)\n\tsum, prev1, prev2 := 1, 0, 0 // Number of arrangements for x, x-1, x-2 jolts\n\tfor _, n := range input {\n\t\tfor x < n-1 {\n\t\t\t// \"Slide the window\" until we have the number of arrangements for\n\t\t\t// n-1, n-2, n-3 jolts: fill missing values with 0.\n\t\t\tx++\n\t\t\tprev2, prev1, sum = prev1, sum, 0\n\t\t}\n\t\tx++\n\t\tprev2, prev1, sum = prev1, sum, sum+prev1+prev2\n\t}\n\treturn sum\n}", "func main() {\n var N int\n fmt.Scan(&N)\n\n tryPoint := 5\n transformPoint := 2\n penaDropPoint := 3\n\n var results []string\n\n possibleTryTimes := int(math.Floor(float64(N / tryPoint)))\n for tryTimes := possibleTryTimes; tryTimes >= 0; tryTimes-- {\n tryPoints := tryPoint * tryTimes\n\n possibleTransformationTimes := int(math.Min(float64((N - tryPoints) / transformPoint), float64(tryTimes)))\n for transformationTimes := possibleTransformationTimes; transformationTimes >= 0; transformationTimes-- {\n transformPoints := transformPoint * transformationTimes\n\n reminingPoints := N - tryPoints - transformPoints\n if reminingPoints % penaDropPoint == 0 {\n penaltieOrDropTimes := reminingPoints / penaDropPoint\n result := fmt.Sprintf(\"%d %d %d\", tryTimes, transformationTimes, penaltieOrDropTimes)\n\n results = append([]string{result}, results...)\n }\n }\n }\n\n // fmt.Fprintln(os.Stderr, \"Debug messages...\")\n // fmt.Println(\"tries transformations penalties\")// Write answer to stdout\n for _, v := range results {\n fmt.Println(v)\n }\n}", "func SolvePartTwo(str string, input int) []int {\n\tintcodes := parseIntCode(str)\n\tvar outputs []int\n\nLoop:\n\tfor i := 0; i < len(intcodes); {\n\t\tinstruction, modeParamNb1, modeParamNb2, modeParamNb3 := parseOpcode(intcodes[i])\n\n\t\tif instruction == 1 || instruction == 2 {\n\t\t\tvar leftOperand int\n\n\t\t\tif modeParamNb1 == 0 {\n\t\t\t\tleftOperandIndex := intcodes[i+1]\n\t\t\t\tleftOperand = intcodes[leftOperandIndex]\n\t\t\t} else {\n\t\t\t\tleftOperand = intcodes[i+1]\n\t\t\t}\n\n\t\t\tvar rightOperand int\n\n\t\t\tif modeParamNb2 == 0 {\n\t\t\t\trightOperandIndex := intcodes[i+2]\n\t\t\t\trightOperand = intcodes[rightOperandIndex]\n\t\t\t} else {\n\t\t\t\trightOperand = intcodes[i+2]\n\t\t\t}\n\n\t\t\tif modeParamNb3 == 0 {\n\t\t\t\tstoreIndex := intcodes[i+3]\n\n\t\t\t\tif instruction == 1 {\n\t\t\t\t\tintcodes[storeIndex] = leftOperand + rightOperand\n\t\t\t\t} else {\n\t\t\t\t\tintcodes[storeIndex] = leftOperand * rightOperand\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif instruction == 1 {\n\t\t\t\t\tintcodes[i+3] = leftOperand + rightOperand\n\t\t\t\t} else {\n\t\t\t\t\tintcodes[i+3] = leftOperand * rightOperand\n\t\t\t\t}\n\t\t\t}\n\t\t} else if instruction == 3 {\n\t\t\tif modeParamNb1 == 0 {\n\t\t\t\tparameterIndex := intcodes[i+1]\n\t\t\t\tintcodes[parameterIndex] = input\n\t\t\t} else {\n\t\t\t\tintcodes[i+1] = input\n\t\t\t}\n\t\t} else if instruction == 4 {\n\t\t\tif modeParamNb1 == 0 {\n\t\t\t\tparameterIndex := intcodes[i+1]\n\t\t\t\toutputs = append(outputs, intcodes[parameterIndex])\n\t\t\t} else {\n\t\t\t\toutputs = append(outputs, intcodes[i+1])\n\t\t\t}\n\t\t} else if instruction == 5 || instruction == 6 {\n\t\t\tvar leftOperand int\n\n\t\t\tif modeParamNb1 == 0 {\n\t\t\t\tleftOperandIndex := intcodes[i+1]\n\t\t\t\tleftOperand = intcodes[leftOperandIndex]\n\t\t\t} else {\n\t\t\t\tleftOperand = intcodes[i+1]\n\t\t\t}\n\n\t\t\tvar rightOperand int\n\n\t\t\tif modeParamNb2 == 0 {\n\t\t\t\trightOperandIndex := intcodes[i+2]\n\t\t\t\trightOperand = intcodes[rightOperandIndex]\n\t\t\t} else {\n\t\t\t\trightOperand = intcodes[i+2]\n\t\t\t}\n\n\t\t\tif leftOperand != 0 && instruction == 5 || leftOperand == 0 && instruction == 6 {\n\t\t\t\ti = rightOperand\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else if instruction == 7 || instruction == 8 {\n\t\t\tvar param1 int\n\n\t\t\tif modeParamNb1 == 0 {\n\t\t\t\tparam1Index := intcodes[i+1]\n\t\t\t\tparam1 = intcodes[param1Index]\n\t\t\t} else {\n\t\t\t\tparam1 = intcodes[i+1]\n\t\t\t}\n\n\t\t\tvar param2 int\n\n\t\t\tif modeParamNb2 == 0 {\n\t\t\t\tparam2Index := intcodes[i+2]\n\t\t\t\tparam2 = intcodes[param2Index]\n\t\t\t} else {\n\t\t\t\tparam2 = intcodes[i+2]\n\t\t\t}\n\n\t\t\tvar param3 int\n\n\t\t\tif modeParamNb3 == 0 {\n\t\t\t\t//param3Index := intcodes[i+3]\n\t\t\t\t//param3 = intcodes[param3Index]\n\t\t\t\tparam3 = intcodes[i+3]\n\t\t\t} else {\n\t\t\t\tparam3 = intcodes[i+3]\n\t\t\t}\n\n\t\t\tif param1 < param2 && instruction == 7 || param1 == param2 && instruction == 8 {\n\t\t\t\tintcodes[param3] = 1\n\t\t\t} else {\n\t\t\t\tintcodes[param3] = 0\n\t\t\t}\n\t\t} else if instruction == 99 {\n\t\t\tbreak Loop\n\t\t} else {\n\t\t\tpanic(\"Unknow instruction!\")\n\t\t}\n\n\t\ti = i + getIncrementForInstruction(instruction)\n\t}\n\n\treturn outputs\n}", "func Day16Part2(input []string) int {\n\tresult := 1\n\tvalidCond := make(map[int][]string)\n\t// validValue := []int{}\n\tmyTicket := []int{}\n\tvalidTickets := [][]int{}\n\tpossibleFields := [][]string{}\n\tcondRE := regexp.MustCompile(`\\d+-\\d+`)\n\tsteps := 1\n\tfor _, item := range input {\n\t\tcmd := strings.Split(item, \":\")\n\t\tswitch cmd[0] {\n\t\tcase \"departure location\", \"departure station\", \"departure platform\", \"departure track\", \"departure date\", \"departure time\", \"arrival location\", \"arrival station\", \"arrival platform\", \"arrival track\", \"class\", \"duration\", \"price\", \"route\", \"row\", \"seat\", \"train\", \"type\", \"wagon\", \"zone\":\n\t\t\tsteps = 1\n\t\tcase \"your ticket\":\n\t\t\tsteps = 2\n\t\tcase \"nearby tickets\":\n\t\t\tsteps = 3\n\t\tcase \"\":\n\t\t\tsteps = 0\n\t\t}\n\t\tswitch steps {\n\t\tcase 1:\n\t\t\tfor _, rangeStr := range condRE.FindAllStringSubmatch(item, -1) {\n\t\t\t\ts, _ := strconv.Atoi(strings.Split(rangeStr[0], \"-\")[0])\n\t\t\t\te, _ := strconv.Atoi(strings.Split(rangeStr[0], \"-\")[1])\n\t\t\t\tfor i := s; i < e+1; i++ {\n\t\t\t\t\tvalidCond[i] = append(validCond[i], cmd[0])\n\t\t\t\t}\n\t\t\t}\n\t\tcase 2:\n\t\t\tif item == \"your ticket:\" {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tfor _, value := range strings.Split(item, \",\") {\n\t\t\t\tv, _ := strconv.Atoi(value)\n\t\t\t\tmyTicket = append(myTicket, v)\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif item == \"nearby tickets:\" {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcheck := true\n\t\t\tticketValues := strings.Split(item, \",\")\n\t\t\t// maze := [][]string{}\n\t\t\tvalidTicket := []int{}\n\t\t\tfor _, value := range ticketValues {\n\t\t\t\tv, _ := strconv.Atoi(value)\n\t\t\t\tif _, ok := validCond[v]; !ok {\n\t\t\t\t\tcheck = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif check {\n\t\t\t\tfor _, value := range strings.Split(item, \",\") {\n\t\t\t\t\tv, _ := strconv.Atoi(value)\n\t\t\t\t\tvalidTicket = append(validTicket, v)\n\t\t\t\t}\n\t\t\t\tvalidTickets = append(validTickets, validTicket)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor j := 0; j < len(validTickets[0]); j++ {\n\t\tpossibleField := []string{}\n\t\tfor i := 0; i < len(validTickets); i++ {\n\t\t\tv := validTickets[i][j]\n\t\t\tf, _ := validCond[v]\n\t\t\tif len(possibleField) == 0 {\n\t\t\t\tpossibleField = append(possibleField, f...)\n\t\t\t} else {\n\t\t\t\tpossibleField = intersection(possibleField, f)\n\t\t\t}\n\t\t}\n\t\tpossibleFields = append(possibleFields, possibleField)\n\t}\n\n\tcount := 0\n\tfor count < len(possibleFields) {\n\t\t// fmt.Printf(\"%#v\\n\", possibleFields)\n\t\tcount = 0\n\t\tfor i := 0; i < len(possibleFields); i++ {\n\t\t\tif len(possibleFields[i]) == 1 {\n\t\t\t\tcount++\n\t\t\t\tfor j := 0; j < len(possibleFields); j++ {\n\t\t\t\t\tif i != j {\n\t\t\t\t\t\tidx := -1\n\t\t\t\t\t\tfor ii, v := range possibleFields[j] {\n\t\t\t\t\t\t\tif v == possibleFields[i][0] {\n\t\t\t\t\t\t\t\tidx = ii\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif idx == -1 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif idx+1 >= len(possibleFields[j]) {\n\t\t\t\t\t\t\tpossibleFields[j] = possibleFields[j][:idx]\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpossibleFields[j] = append(possibleFields[j][:idx], possibleFields[j][idx+1:]...)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// fmt.Printf(\"%#v\\n\", possibleFields)\n\tfor i, v := range possibleFields {\n\t\tif strings.Contains(v[0], \"departure\") {\n\t\t\tresult *= myTicket[i]\n\t\t}\n\t}\n\n\treturn result\n}", "func main() {\n\tinstructions := readLineByLine()\n\n\tvar accumulator int\n\tvar hasCycles bool\n\tinstructionsSwitched := make(map[int]instruction)\n\ti := 0\n\n\tfor i > -1 {\n\t\tfor k, v := range instructions {\n\t\t\tinstructionsSwitched[k] = v\n\t\t}\n\n\t\tif i > len(instructions) {\n\t\t\tbreak\n\t\t}\n\t\t// cycle through instructions and if found nop or jmp switch > create new instructions\n\t\t// calculate accumulator and if has cycles\n\t\taction := instructions[i].action\n\t\tif action == \"jmp\" || action == \"nop\" {\n\t\t\tif action == \"jmp\" {\n\t\t\t\tmove := instructions[i].move\n\t\t\t\tinstructionsSwitched[i] = instruction{\"nop\", move}\n\t\t\t\taccumulator, hasCycles = computeAcc(instructionsSwitched)\n\t\t\t}\n\t\t\tif action == \"nop\" {\n\t\t\t\tmove := instructions[i].move\n\t\t\t\tinstructionsSwitched[i] = instruction{\"jmp\", move}\n\t\t\t\taccumulator, hasCycles = computeAcc(instructionsSwitched)\n\t\t\t}\n\t\t\tif !hasCycles {\n\t\t\t\tfmt.Println(\"no cycle found\", i)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif hasCycles {\n\t\t\t\tfmt.Println(\"cycle found\", i)\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\t\tif action == \"acc\" {\n\t\t\ti++\n\t\t}\n\t}\n\n\tfmt.Println(accumulator)\n\t//fmt.Println(g, nodesMap)\n}", "func Day8Part2(filepath string) any {\n\tvar res int\n\n\t// parse out treeMap from file\n\t// open file\n\treadFile, _ := os.Open(filepath)\n\n\t// read line\n\tfileScanner := bufio.NewScanner(readFile)\n\tfileScanner.Split(bufio.ScanLines)\n\n\t// parse map in to [][]int\n\ttreeMap := parseMap(fileScanner)\n\n\t// iterate every tree\n\tfor i := range treeMap {\n\t\tfor j := range treeMap[0] {\n\t\t\t// for every tree, calculate scenicScore\n\t\t\ts := getScenicScore(treeMap, i, j)\n\t\t\t// update max scenic score\n\t\t\tif s > res {\n\t\t\t\tres = s\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}", "func Problem17() int {\n\tcnt := 0\n\n\tunits := []int{\n\t\tlen(\"one\"),\n\t\tlen(\"two\"),\n\t\tlen(\"three\"),\n\t\tlen(\"four\"),\n\t\tlen(\"five\"),\n\t\tlen(\"six\"),\n\t\tlen(\"seven\"),\n\t\tlen(\"eight\"),\n\t\tlen(\"nine\"),\n\t}\n\n\tteens := []int{\n\t\tlen(\"ten\"),\n\t\tlen(\"eleven\"),\n\t\tlen(\"twelve\"),\n\t\tlen(\"thirteen\"),\n\t\tlen(\"fourteen\"),\n\t\tlen(\"fifteen\"),\n\t\tlen(\"sixteen\"),\n\t\tlen(\"seventeen\"),\n\t\tlen(\"eighteen\"),\n\t\tlen(\"nineteen\"),\n\t}\n\n\ttens := []int{\n\t\tlen(\"twenty\"),\n\t\tlen(\"thirty\"),\n\t\tlen(\"forty\"),\n\t\tlen(\"fifty\"),\n\t\tlen(\"sixty\"),\n\t\tlen(\"seventy\"),\n\t\tlen(\"eighty\"),\n\t\tlen(\"ninety\"),\n\t}\n\n\t// Add 1-9.\n\tfor _, u := range units {\n\t\tcnt += u\n\t}\n\n\t// Add 10-19.\n\tfor _, t := range teens {\n\t\tcnt += t\n\t}\n\n\t// Add 20-99.\n\tfor _, t := range tens {\n\t\tcnt += t\n\t\tfor _, u := range units {\n\t\t\tcnt += t + u\n\t\t}\n\t}\n\n\t// Add 100-999.\n\tnn := cnt // Length of numbers 1-99.\n\th := len(\"hundred\")\n\tfor _, u := range units {\n\t\t// 99*(u+h+3) replace cycle for doing this 99 times on first 99 numbers.\n\t\t// E.g: \"one hundred and twenty-two\" (without spaces and hyphens).\n\t\tcnt += (u + h) + (99*(u+h+3) + nn)\n\t}\n\n\t// Add 1000.\n\tcnt += len(\"onethousand\")\n\n\treturn cnt\n}", "func steps(s []int) int {\n\tsteps := 0\n\n\tfor pos := 0; pos >= 0 && pos < len(s); steps += 1 {\n\t\tnewpos := pos + s[pos]\n\t\tif s[pos] >= 3 {\n\t\t\ts[pos] -= 1\n\t\t} else {\n\t\t\ts[pos] += 1\n\t\t}\n\t\tpos = newpos\n\t}\n\n\treturn steps\n}", "func cuttingRope2(n int) int {\n\tif n < 4 {\n\t\treturn n - 1\n\t}\n\tres := 1\n\tfor n > 4 {\n\t\tres = res * 3 % 1000000007\n\t\tn -= 3\n\t}\n\treturn res * n % 1000000007\n}", "func P011() int {\n\tvec := newVector()\n\tmax, sum := 0, 0\n\n\tfor j := 0; j < 20; j++ {\n\t\tfor i := 0; i < 20; i++ {\n\t\t\t//fmt.Println(vec[i][j])\n\t\t\tsum = 0\n\t\t\t/*\n\t\t\t * UP\n\t\t\t */\n\t\t\tif j > 2 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i][j-k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * Down\n\t\t\t */\n\t\t\tif j < 17 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i][j+k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * LEFT\n\t\t\t */\n\t\t\tif i > 2 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i-k][j]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * RIGHT\n\t\t\t */\n\t\t\tif i < 17 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i+k][j]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * UP LEFT\n\t\t\t */\n\t\t\tif j > 2 && i > 2 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i-k][j-k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * UP RIGHT\n\t\t\t */\n\t\t\tif j > 2 && i < 17 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i+k][j-k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * DOWN LEFT\n\t\t\t */\n\t\t\tif i > 2 && j < 17 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i-k][j+k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * DOWN RIGHT\n\t\t\t */\n\t\t\tif i < 17 && j < 17 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i+k][j+k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif sum > max {\n\t\t\t\tmax = sum\n\t\t\t}\n\t\t}\n\t}\n\treturn max\n}", "func main() {\n\tarr := []int{17, 18, 5, 4, 6, 1}\n\tresult := solution(arr)\n\tfmt.Println(result)\n}", "func solutionLvl2(puzzle string, parameters map[string]int) (answer int) {\n\tmem := map[string]string{}\n\tmask := \"\"\n\tfor _, line := range strings.Split(puzzle, \"\\n\") {\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tdata := strings.Split(line, \"=\")\n\t\tif strings.HasPrefix(data[0], \"ma\") {\n\t\t\tmask = data[1][1:]\n\t\t\tcontinue\n\t\t}\n\t\taddress := data[0][4 : len(data[0])-2]\n\t\tvalue := data[1][1:]\n\n\t\tmasked := applyAddressMask(to36Bin(address), mask)\n\t\tadresses := generateAdresses(masked)\n\t\tfor _, m := range adresses {\n\t\t\tmem[m] = value\n\t\t}\n\t}\n\tfor _, v := range mem {\n\t\tval, _ := strconv.Atoi(v)\n\t\tanswer += val\n\t}\n\n\treturn\n}", "func main() {\n\tN := scanInt()\n\tn, e, t := 1, 1, 1\n\tfor i := 0; i < N; i++ {\n\t\t// [+/*]you can divide by mod each add/time ops\n\t\te = (e * 8) % mod\n\t\tn = (n * 9) % mod\n\t\tt = (t * 10) % mod\n\t}\n\tans := t - n - n + e\n\t// [+]consider if above time calc result over mod\n\tans %= mod\n\t// [-]consider if above sub calc result goes negative number\n\tans = (ans + mod) % mod\n\tfmt.Println(ans)\n}", "func Preprocess() (*map[string] int, *[]string, *[] int, int){\n\tf, err := ioutil.ReadFile(\"project4input.txt\")\n\n\n\tinputMap := make(map[string] int)\n\tvar inputTransFormation []int \n\tvar inputKeys []string\n\tif err != nil{\n\t\tprintln(\"failed\")\n\t\treturn &inputMap, &inputKeys, &inputTransFormation, 0 \n\t}\n\n\ttemp := strings.Split(string(f), \"\\n\")\n\tnumberOfFlows , _ := strconv.Atoi(strings.Fields(temp[0])[0]);\n\t//println(numberOfFlows)\n\tfor i, tmp := range temp{\n\t\tif i == numberOfFlows{ break}\n\t\tif i == 0 { continue }\n\t\ttemp2 := strings.Fields(tmp)\n\t\t//println(tmp)\n\t\tinputMap[temp2[0]] = 0\n\t\tif len(temp2) == 2{\n\t\t\tinputMap[temp2[0]], _ = strconv.Atoi(temp2[1])\n\t\t}\n\t\t\n\t\tinputKeys = append(inputKeys, temp2[0])\n\t}\n\n\tfor range inputKeys{\n\t\tinputTransFormation = append(inputTransFormation, customrandom.GetRandomNumber(0,2147483647))\n\t}\t\n\n\treturn &inputMap , &inputKeys, &inputTransFormation ,numberOfFlows\n}", "func solveAllSegments(display sevenSegmentDisplay) (result int) {\n\tlookupTable := make(map[string]int)\n\tcountPositions := make(map[rune]int)\n\tfor _, displayPos := range display.segments {\n\t\tfor _, char := range displayPos {\n\t\t\tcountPositions[char]++\n\t\t}\n\t}\n\n\tpositionSheet := make(map[int][]rune)\n\tfor char, val := range countPositions {\n\t\tpositionSheet[val] = append(positionSheet[val], char)\n\t}\n\n\tfor _, displayPos := range display.segments {\n\t\tswitch len(displayPos) {\n\t\tcase 2:\n\t\t\tlookupTable[displayPos] = 1\n\t\tcase 3:\n\t\t\tlookupTable[displayPos] = 7\n\t\tcase 4:\n\t\t\tlookupTable[displayPos] = 4\n\t\tcase 7:\n\t\t\tlookupTable[displayPos] = 8\n\t\tcase 5: // 2, 3 or 5\n\t\t\t// Only 2 has an empty space bottom-right\n\t\t\tif !strings.ContainsRune(displayPos, positionSheet[9][0]) {\n\t\t\t\tlookupTable[displayPos] = 2\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// if they have top and top-right it's 3 else 5\n\t\t\tif strings.ContainsRune(displayPos, positionSheet[8][0]) && strings.ContainsRune(displayPos, positionSheet[8][1]) {\n\t\t\t\tlookupTable[displayPos] = 3\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlookupTable[displayPos] = 5\n\t\tcase 6: // 0, 6 or 9\n\t\t\t// if they have bottom left they can be - 0 6 -\n\t\t\tif strings.ContainsRune(displayPos, positionSheet[4][0]) {\n\t\t\t\t// if they have top and top-right it's 0 else 6\n\t\t\t\tif strings.ContainsRune(displayPos, positionSheet[8][0]) && strings.ContainsRune(displayPos, positionSheet[8][1]) {\n\t\t\t\t\tlookupTable[displayPos] = 0\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlookupTable[displayPos] = 6\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlookupTable[displayPos] = 9\n\t\t}\n\t}\n\n\tvar resultString = \"\"\n\tfor _, value := range display.values {\n\t\tresultString += strconv.FormatInt(int64(lookupTable[value]), 10)\n\t}\n\n\treturn pkg.MustAtoi(resultString)\n}", "func Part1(filename string) int {\n\tfmt.Println(\"Day 1 : Part 1\")\n\n\tinput := parser.ParseTextFileToInt(filename)\n\tswitch approach := 2; approach {\n\tcase 1:\n\t\tfmt.Println(\"Approach: \", approach)\n\n\t\t// Sort the input first - O(nlog(n))\n\t\tsort.Slice(input, func(i, j int) bool {\n\t\t\treturn input[i] < input[j]\n\t\t})\n\n\t\ti := 0\n\t\tj := len(input) - 1\n\t\tfor i < j {\n\t\t\tif input[i]+input[j] == 2020 {\n\t\t\t\treturn input[i] * input[j]\n\t\t\t} else if input[i]+input[j] < 2020 {\n\t\t\t\ti++\n\t\t\t} else {\n\t\t\t\tj--\n\t\t\t}\n\t\t}\n\tcase 2:\n\t\tfmt.Println(\"Approach: \", approach)\n\n\t\tinputByCount := make(map[int]int)\n\t\tfor _, val := range input {\n\t\t\tinputByCount[val]++\n\t\t}\n\n\t\tfor _, val := range input {\n\t\t\tif 2020-val == val && inputByCount[val] >= 2 {\n\t\t\t\treturn val * val\n\t\t\t} else if count, ok := inputByCount[2020-val]; ok && count >= 1 {\n\t\t\t\tfmt.Println(val)\n\t\t\t\treturn (2020 - val) * val\n\t\t\t}\n\t\t}\n\t\treturn -1\n\tcase 3:\n\t\tfmt.Println(\"Approach: \", approach)\n\t\t// TODO\n\tcase 4:\n\t\tfmt.Println(\"Approach: \", approach)\n\t\t// TODO\n\t}\n\n\treturn -1\n}", "func Day12_solve_part2(file string) int {\n\tparticles := day12_parse(file)\n\thistory := make_history(&particles)\n\tcount := 0\n\tfor {\n\t\tcount++\n\t\tstep(&particles)\n\t\thistory.check(&particles, count)\n\t\tif history.complete() {\n\t\t\tcycles := history.gather()\n\t\t\tlog.Printf(\"cycles: %v\", cycles)\n\t\t\treturn lcm(cycles)\n\t\t}\n\t}\n}", "func Solution002() string {\n\n\tfib_0 := 1\n\tfib_1 := 2\n\tanswer := 2\n\n\tfor fib_0 + fib_1 < 4000000 {\n\t\tfib_next := fib_0 + fib_1\n\t\tfib_0 = fib_1\n\t\tfib_1 = fib_next\n\n\t\tif (fib_next % 2 == 0) {\n\t\t\tanswer += fib_next\n\t\t}\n\t}\n\n\treturn fmt.Sprint(answer)\n}", "func convert() {\n\tf, err := os.Open(\"10-million-combos.txt\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer f.Close()\n\n\tpws, err := os.Create(\"10-mil-pws.txt\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer pws.Close()\n\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tparts := strings.Split(scanner.Text(), \"\\t\")\n\t\tpw := parts[len(parts)-1]\n\t\tif len(parts) != 2 {\n\t\t\tswitch pw {\n\t\t\tcase \"markcgilberteternity2969\":\n\t\t\t\tpw = \"eternity2969\"\n\t\t\tcase \"sailer1216soccer1216\":\n\t\t\t\tpw = \"soccer1216\"\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Couldn't read line: \", parts)\n\t\t\t}\n\t\t}\n\t\tfmt.Fprintln(pws, pw)\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tpanic(err)\n\t}\n}", "func Solve6() {\n\n\tzipRequest, err := http.Get(\"http://www.pythonchallenge.com/pc/def/channel.zip\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tzipBytes, err := io.ReadAll(zipRequest.Body)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tzipReader, err := zip.NewReader(bytes.NewReader(zipBytes), zipRequest.ContentLength)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tcomments := make([]string, 10)\n\n\tnavFunction := func(navigateId string) string {\n\t\tnextId, comment := zipNavigate(zipReader, navigateId)\n\n\t\tcomments = append(comments, comment)\n\t\treturn nextId\n\t}\n\n\tutility.ListWalker(navFunction, 90052)\n\n\tfor _, c := range comments {\n\t\tfmt.Print(c)\n\t}\n\n\tfmt.Println(\"Next: http://www.pythonchallenge.com/pc/def/☝️ .html\")\n}", "func Run() {\n\tinputInts := bp.Atoi(bp.GetN(\"day10/day10_input.txt\"))\n\tsort.Ints(inputInts)\n\n\toneJoltDiff, threeJoltDiff := 0, 0\n\tfor i := 0; i <= len(inputInts); i++ {\n\t\tcurr := 0\n\t\tif i == 0 {\n\t\t\tcurr = 0\n\t\t} else {\n\t\t\tcurr = inputInts[i-1]\n\t\t}\n\n\t\tnext := 0\n\t\tif len(inputInts) == i {\n\t\t\tnext = inputInts[i-1] + 3\n\t\t} else {\n\t\t\tnext = inputInts[i]\n\t\t}\n\n\t\tif next-curr == 1 {\n\t\t\toneJoltDiff++\n\t\t} else if next-curr == 3 {\n\t\t\tthreeJoltDiff++\n\t\t}\n\t}\n\n\tfmt.Println(\"\\tpart 1:\", oneJoltDiff*threeJoltDiff)\n\n\tinputInts = append([]int{0}, inputInts...)\n\tinputInts = append(inputInts, inputInts[len(inputInts)-1]+3)\n\n\tindices := make([]int, 1)\n\tfor i := 1; i < len(inputInts); i++ {\n\t\tif inputInts[i-1] == inputInts[i]-3 {\n\t\t\tindices = append(indices, i)\n\t\t}\n\t}\n\n\tres := 1\n\tfor i := 1; i < len(indices); i++ {\n\t\tpaths, prevIndex, currIndex := 0, indices[i-1], indices[i]\n\t\tnext(prevIndex, &inputInts, &paths, currIndex)\n\t\tres *= paths\n\t}\n\n\tfmt.Println(\"\\tpart 2:\", res)\n}", "func solutionLvl2(puzzle string, parameters map[string]int) (answer int) {\n\tfor _, line := range strings.Split(puzzle, \"\\n\") {\n\t\tif line != \"\" {\n\t\t\tanswer += evaluateExpr2(line)\n\t\t}\n\t}\n\treturn\n}", "func Day8Part1(filepath string) any {\n\tvar res int\n\n\t// open file\n\treadFile, _ := os.Open(filepath)\n\n\t// read line\n\tfileScanner := bufio.NewScanner(readFile)\n\tfileScanner.Split(bufio.ScanLines)\n\n\t// parse map in to [][]int\n\ttreeMap := parseMap(fileScanner)\n\t// fmt.Println(treeMap)\n\n\t// init visible trees 2D array\n\tvisible := make([][]bool, len(treeMap))\n\tfor i := range visible {\n\t\tvisible[i] = make([]bool, len(treeMap[0]))\n\t}\n\n\t// look from left to r\n\tfor i := range treeMap {\n\t\tmax := 0\n\t\tfor j := range treeMap[0] {\n\t\t\tif i == 0 || i == len(treeMap)-1 || j == 0 || j == len(treeMap[0])-1 || treeMap[i][j] > max {\n\t\t\t\tvisible[i][j] = true\n\t\t\t\tmax = treeMap[i][j]\n\t\t\t}\n\t\t}\n\t}\n\n\t// look from right to l\n\tfor i := range treeMap {\n\t\tmax := 0\n\t\tfor j := len(treeMap[0]) - 1; j >= 0; j-- {\n\t\t\tif i == 0 || i == len(treeMap)-1 || j == 0 || j == len(treeMap[0])-1 || treeMap[i][j] > max {\n\t\t\t\tvisible[i][j] = true\n\t\t\t\tmax = treeMap[i][j]\n\t\t\t}\n\t\t}\n\t}\n\n\t// look from up to down\n\tfor j := 0; j <= len(treeMap[0])-1; j++ {\n\t\tmax := 0\n\t\tfor i := 0; i <= len(treeMap)-1; i++ {\n\t\t\tif i == 0 || i == len(treeMap)-1 || j == 0 || j == len(treeMap[0])-1 || treeMap[i][j] > max {\n\t\t\t\tvisible[i][j] = true\n\t\t\t\tmax = treeMap[i][j]\n\t\t\t}\n\t\t}\n\t}\n\n\t// look from down to up\n\tfor j := 0; j <= len(treeMap[0])-1; j++ {\n\t\tmax := 0\n\t\tfor i := len(treeMap) - 1; i >= 0; i-- {\n\t\t\tif i == 0 || i == len(treeMap)-1 || j == 0 || j == len(treeMap[0])-1 || treeMap[i][j] > max {\n\t\t\t\tvisible[i][j] = true\n\t\t\t\tmax = treeMap[i][j]\n\t\t\t}\n\t\t}\n\t}\n\n\t// traverse visible trees 2D array and count visibles\n\tfor i := range visible {\n\t\tfor j := range visible[i] {\n\t\t\tif visible[i][j] {\n\t\t\t\tres++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res\n}", "func main() {\n\tnumbers1 := []int{6, 10, 2}\n\tfmt.Println(solution(numbers1))\n\tnumbers2 := []int{3, 30, 34, 5, 9}\n\tfmt.Println(solution(numbers2))\n\tnumbers3 := []int{0, 0, 0, 0}\n\tfmt.Println(solution(numbers3))\n\n}", "func main() {\n\tnums := []int{1, 0, -1, 0, -2, 2}\n\ttarget := 0\n\tsum := map[string]int{}\n\n\t//1st loop\n\tfor i, val1 := range nums {\n\t\t//2nd loop\n\t\tfor j, val2 := range nums {\n\t\t\tif i == j {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t//3rd loop\n\t\t\tfor k, val3 := range nums {\n\t\t\t\tif i == k || j == k {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfor l, val4 := range nums {\n\t\t\t\t\tif k == l || l == j || l == i {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tkeyArr := []int{val1, val2, val3, val4}\n\t\t\t\t\tsort.Ints(keyArr)\n\t\t\t\t\tkey := strconv.Itoa(keyArr[0]) + \".\" + strconv.Itoa(keyArr[1]) + \".\" + strconv.Itoa(keyArr[2]) + \".\" + strconv.Itoa(keyArr[3])\n\t\t\t\t\tsum[key] = val1 + val2 + val3 + val4\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tresult := [][]int{}\n\n\tfor k, val := range sum {\n\t\tif val == target {\n\t\t\tarr4 := strings.Split(k, \".\")\n\t\t\tsum4 := make([]int, 0, 4)\n\t\t\tfor _, v := range arr4 {\n\t\t\t\tval, _ := strconv.Atoi(v)\n\t\t\t\tsum4 = append(sum4, val)\n\t\t\t}\n\t\t\tresult = append(result, sum4)\n\t\t}\n\t}\n\n}", "func ProblemX2() {\n\n\tfmt.Println(stringShift(\"abc\", [][]int{{0, 1}, {1, 2}}))\n\n\tfmt.Println(stringShift(\"abcdefg\", [][]int{{1, 1}, {1, 1}, {0, 2}, {1, 3}}))\n\n}", "func SolvePartOne(str string, input int) []int {\n\tintcodes := parseIntCode(str)\n\tvar outputs []int\n\nLoop:\n\tfor i := 0; i < len(intcodes); {\n\t\tinstruction, modeParamNb1, modeParamNb2, modeParamNb3 := parseOpcode(intcodes[i])\n\n\t\tif instruction == 1 || instruction == 2 {\n\t\t\tvar leftOperand int\n\n\t\t\tif modeParamNb1 == 0 {\n\t\t\t\tleftOperandIndex := intcodes[i+1]\n\t\t\t\tleftOperand = intcodes[leftOperandIndex]\n\t\t\t} else {\n\t\t\t\tleftOperand = intcodes[i+1]\n\t\t\t}\n\n\t\t\tvar rightOperand int\n\n\t\t\tif modeParamNb2 == 0 {\n\t\t\t\trightOperandIndex := intcodes[i+2]\n\t\t\t\trightOperand = intcodes[rightOperandIndex]\n\t\t\t} else {\n\t\t\t\trightOperand = intcodes[i+2]\n\t\t\t}\n\n\t\t\tif modeParamNb3 == 0 {\n\t\t\t\tstoreIndex := intcodes[i+3]\n\n\t\t\t\tif instruction == 1 {\n\t\t\t\t\tintcodes[storeIndex] = leftOperand + rightOperand\n\t\t\t\t} else {\n\t\t\t\t\tintcodes[storeIndex] = leftOperand * rightOperand\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif instruction == 1 {\n\t\t\t\t\tintcodes[i+3] = leftOperand + rightOperand\n\t\t\t\t} else {\n\t\t\t\t\tintcodes[i+3] = leftOperand * rightOperand\n\t\t\t\t}\n\t\t\t}\n\t\t} else if instruction == 3 {\n\t\t\tif modeParamNb1 == 0 {\n\t\t\t\tparameterIndex := intcodes[i+1]\n\t\t\t\tintcodes[parameterIndex] = input\n\t\t\t} else {\n\t\t\t\tintcodes[i+1] = input\n\t\t\t}\n\t\t} else if instruction == 4 {\n\t\t\tif modeParamNb1 == 0 {\n\t\t\t\tparameterIndex := intcodes[i+1]\n\t\t\t\toutputs = append(outputs, intcodes[parameterIndex])\n\t\t\t} else {\n\t\t\t\toutputs = append(outputs, intcodes[i+1])\n\t\t\t}\n\t\t} else if instruction == 99 {\n\t\t\tbreak Loop\n\t\t} else {\n\t\t\tpanic(\"Unknow instruction!\")\n\t\t}\n\n\t\ti = i + getIncrementForInstruction(instruction)\n\t}\n\n\treturn outputs\n}", "func solutionLvl1(puzzle string, parameters map[string]int) (answer int) {\n\tmem := map[string]string{}\n\tmask := \"\"\n\tfor _, line := range strings.Split(puzzle, \"\\n\") {\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tdata := strings.Split(line, \"=\")\n\t\tif strings.HasPrefix(data[0], \"ma\") {\n\t\t\tmask = data[1][1:]\n\t\t\tcontinue\n\t\t}\n\t\taddress := data[0][4 : len(data[0])-2]\n\t\tvalue := data[1][1:]\n\n\t\tmasked := applyMask(to36Bin(value), mask)\n\t\tmem[address] = masked\n\t}\n\tfor _, v := range mem {\n\t\tval, err := strconv.ParseInt(v, 2, 64) // now we decimal again\n\t\tif err != nil {\n\t\t\tfmt.Println(\"HOLY SHIT\", err)\n\t\t}\n\t\tanswer += int(val)\n\t}\n\treturn\n}", "func main() {\n\ttotal := int64(0)\n\tvectors := ways(10, top, 3)\n\tfor _, vector := range vectors {\n\t\ttotal += distribute(vector)\n\t}\n\n\tfmt.Println(\"172/ How many 18-digit numbers n (without leading zeros) are there such that no digit occurs more than three times in n?\")\n\tfmt.Println(total)\n}", "func main() {\n\tvar a [101]int\n\t//j is the trip\n\tfor j := 1; j <= 100; j++ {\n\t\t//k is the switch\n\t\tfor k := 1; k <= 100; k++ {\n\t\t\tif k%j == 0 {\n\t\t\t\ta[k]++\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := 1; i <= 100; i++ {\n\t\tif a[i]%2 == 1 {\n\t\t\tfmt.Printf(\"switch %v = nyala, dipencet %v kali\\n\", i, a[i])\n\t\t}\n\t}\n\n}", "func solution(val string) string {\n\tretVal := val[0:2]\n\t//fmt.Println(retVal)\n\tfor x := 3; x < len(val); x = x + 2 {\n\t\tretVal += string(val[x])\n\t}\n\treturn retVal\n}", "func stepPerms(n int32) int32 {\n\tcollection := &StepsPremsCollection{memory: make(map[int32]int32)}\n\treturn collection.getPerms(n)\n}", "func Convert(input int) string {\n\tout := \"\"\n\n\t//check if this number is divisible by 3 (Pling)\n\tif input%3 == 0 {\n\t\tout = \"Pling\"\n\t}\n\n\t//check if the number is divisible by 5 (Plang)\n\tif input%5 == 0 {\n\t\tout = out + \"Plang\"\n\t}\n\n\t//check if the number is divisible by 7 (Plong)\n\tif input%7 == 0 {\n\t\tout = out + \"Plong\"\n\t}\n\n\t//if we go into this branch, we have no factors in {3,5,7}\n\tif len(out) == 0 {\n\t\treturn strconv.Itoa(input)\n\t}\n\n\treturn out\n}", "func main() {\n\n\tinput := []int{1, 1, 0, 1, 1, 1}\n\n\tresult := solution(input)\n\tfmt.Println(result)\n\n}", "func beautifulDays(i int32, j int32, k int32) int32 {\nvar num string\nvar rev string\nvar revnum int32\nvar res int32 = 0\n for p := i; p <= j; p++ {\n num = strconv.FormatInt(int64(p), 10)\n rev = \"\"\n for q := len(num) - 1; q >= 0; q-- {\n rev += string(num[q])\n }\n revnum64, err := strconv.ParseInt(rev, 10, 64)\n if err != nil {\n panic(err)\n }\n revnum = int32(revnum64)\n if abs(p - revnum) % k == 0 {\n res++\n } \n }\n return res\n}", "func convertToBase7(num int) string {\n\tif num == 0 {\n\t\treturn \"0\"\n\t}\n\tarr := []byte{}\n\tneg := false\n\tif num < 0 {\n\t\tneg = true\n\t\tnum *= -1\n\t}\n\tfor num != 0 {\n\t\tarr = append(arr, byte(num%7)+'0')\n\t\tnum /= 7\n\t}\n\tif neg {\n\t\tarr = append(arr, '-')\n\t}\n\tfor i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 {\n\t\tarr[i], arr[j] = arr[j], arr[i]\n\t}\n\treturn string(arr)\n}", "func h(n int) int {\n var a int = n % 2\n if a == 1 {\n return n * 3 + 1\n }\n return n / 2\n}", "func solve1(input string) string {\n\tlist := parseInput(input)\n\ti := 0\n\tn := 0\n\tfor i >= 0 && i < len(list) {\n\t\tj := list[i]\n\t\tlist[i]++\n\t\ti += j\n\t\tn++\n\t}\n\treturn fmt.Sprint(n)\n}", "func solveAlgo7(g Solver, l *Line) {\n\t//l.print(\"solveAlgo7\")\n\trsg := l.getUnsolvedRanges()\n\n\tfor _, r := range rsg {\n\t\tcs := l.getPotentialCluesForRange(r)\n\n\t\tshortest := l.length\n\t\tisFound, step := l.getStepToNextBlank(r, false)\n\t\tif isFound {\n\t\t\tisFound = false\n\t\t\tfor _, c := range cs {\n\t\t\t\tif c.length <= step+r.length() {\n\t\t\t\t\t//fmt.Printf(\"Canceling... Clue(n:%d,b:%d,e:%d,l:%d)\\n\", c.index+1, c.begin+1, c.end+1, c.length)\n\t\t\t\t\tisFound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tshortest = min(shortest, c.length-step-r.length())\n\t\t\t}\n\t\t\t//if we didn't find anyone, we can fill taking into account the shortest trail\n\t\t\tif !isFound {\n\t\t\t\tfor i := 0; i < shortest; i++ {\n\t\t\t\t\tg.SetValue(l.squares[r.min-i-1], 2)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tshortest = l.length\n\t\tisFound, step = l.getStepToNextBlank(r, true)\n\t\tif isFound {\n\t\t\tisFound = false\n\t\t\tfor _, c := range cs {\n\t\t\t\tif c.length <= step+r.length() {\n\t\t\t\t\t//fmt.Printf(\"Canceling... Clue(n:%d,b:%d,e:%d,l:%d)\\n\", c.index+1, c.begin+1, c.end+1, c.length)\n\t\t\t\t\tisFound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tshortest = min(shortest, c.length-step-r.length())\n\t\t\t}\n\t\t\t//if we didn't find anyone, we can fill taking into account the shortest trail\n\t\t\tif !isFound {\n\t\t\t\tfor i := 0; i < shortest; i++ {\n\t\t\t\t\tg.SetValue(l.squares[r.max+i+1], FILLED)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func part2(mem []int64) int64 {\n\tg := readGrid(mem)\n\tvar r robot\n\tfor y, row := range g {\n\t\tfor x, c := range row {\n\t\t\tif strings.ContainsRune(\"^v<>\", c) {\n\t\t\t\tr = robot{point{x, y}, north}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tprev := r.pos.move(west)\n\tpath := []direction{east}\n\tfor {\n\t\tadj := adjacent(g, r.pos)\n\t\tif len(path) > 2 && len(adj) == 1 {\n\t\t\tbreak\n\t\t}\n\t\tif 0 < len(adj) && len(adj) <= 2 {\n\t\t\tnext := adj[0]\n\t\t\tif len(adj) == 2 && adj[0] == prev {\n\t\t\t\tnext = adj[1]\n\t\t\t}\n\t\t\tif r.pos.x < next.x {\n\t\t\t\tr.dir = east\n\t\t\t}\n\t\t\tif r.pos.x > next.x {\n\t\t\t\tr.dir = west\n\t\t\t}\n\t\t\tif r.pos.y < next.y {\n\t\t\t\tr.dir = south\n\t\t\t}\n\t\t\tif r.pos.y > next.y {\n\t\t\t\tr.dir = north\n\t\t\t}\n\t\t}\n\t\tpath = append(path, r.dir)\n\t\tprev = r.pos\n\t\tr.move()\n\t}\n\n\tqueue := []step{{0, right}}\n\tfor i, d := range path[1:] {\n\t\trot := path[i].rotation(d)\n\t\tif len(queue) > 0 && rot == none {\n\t\t\tqueue[len(queue)-1].n++\n\t\t\tcontinue\n\t\t}\n\t\tqueue = append(queue, step{1, rot})\n\t}\n\n\tvar out string\n\tfor _, v := range queue {\n\t\tout += v.String() + \",\"\n\t}\n\tfmt.Println(out)\n\n\tp := newProgram(mem)\n\tp.memory[0] = 2\n\t// I have to be honest. I used my editors \"highlight other occurrences\"\n\t// feature on the previous output.\n\tin := strings.Join([]string{\n\t\t\"A,B,A,C,A,B,C,C,A,B\",\n\t\t\"R,8,L,10,R,8\",\n\t\t\"R,12,R,8,L,8,L,12\",\n\t\t\"L,12,L,10,L,8\",\n\t\t\"n\",\n\t\t\"\",\n\t}, \"\\n\")\n\tfor _, c := range in {\n\t\tp.input = append(p.input, int64(c))\n\t}\n\tres, err := p.run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn res[len(res)-1]\n}", "func Test_step2b(t *testing.T) {\n\ttestCases := []romance.StepTestCase{\n\t\t{\"posée\", 3, 5, 2, true, \"pos\", 3, 3, 2},\n\t\t{\"contentait\", 3, 6, 2, true, \"content\", 3, 6, 2},\n\t\t{\"évita\", 2, 4, 3, true, \"évit\", 2, 4, 3},\n\t\t{\"cantonnées\", 3, 6, 2, true, \"cantonn\", 3, 6, 2},\n\t\t{\"tender\", 3, 6, 2, true, \"tend\", 3, 4, 2},\n\t\t{\"survenait\", 3, 6, 2, true, \"surven\", 3, 6, 2},\n\t\t{\"plongeaIent\", 4, 8, 3, true, \"plong\", 4, 5, 3},\n\t\t{\"modéra\", 3, 5, 2, true, \"modér\", 3, 5, 2},\n\t\t{\"copier\", 3, 6, 2, true, \"copi\", 3, 4, 2},\n\t\t{\"bougez\", 4, 6, 2, true, \"boug\", 4, 4, 2},\n\t\t{\"déploYaIent\", 3, 6, 2, true, \"déploY\", 3, 6, 2},\n\t\t{\"entendra\", 2, 5, 4, true, \"entendr\", 2, 5, 4},\n\t\t{\"blâmer\", 4, 6, 3, true, \"blâm\", 4, 4, 3},\n\t\t{\"déshonorait\", 3, 6, 2, true, \"déshonor\", 3, 6, 2},\n\t\t{\"concentrés\", 3, 6, 2, true, \"concentr\", 3, 6, 2},\n\t\t{\"mangeant\", 3, 7, 2, true, \"mang\", 3, 4, 2},\n\t\t{\"écouteront\", 2, 5, 3, true, \"écout\", 2, 5, 3},\n\t\t{\"pressaIent\", 4, 7, 3, true, \"press\", 4, 5, 3},\n\t\t{\"ébréché\", 2, 5, 4, true, \"ébréch\", 2, 5, 4},\n\t\t{\"frapper\", 4, 7, 3, true, \"frapp\", 4, 5, 3},\n\t\t{\"côtoYé\", 3, 5, 2, true, \"côtoY\", 3, 5, 2},\n\t\t{\"réfugié\", 3, 5, 2, true, \"réfugi\", 3, 5, 2},\n\t\t{\"jeûnant\", 4, 6, 2, true, \"jeûn\", 4, 4, 2},\n\t\t{\"succombé\", 3, 6, 2, true, \"succomb\", 3, 6, 2},\n\t\t{\"irrité\", 2, 5, 4, true, \"irrit\", 2, 5, 4},\n\t\t{\"danger\", 3, 6, 2, true, \"dang\", 3, 4, 2},\n\t\t{\"sachant\", 3, 6, 2, true, \"sach\", 3, 4, 2},\n\t\t{\"reparaissaIent\", 3, 5, 2, true, \"reparaiss\", 3, 5, 2},\n\t\t{\"reconnaissant\", 3, 5, 2, true, \"reconnaiss\", 3, 5, 2},\n\t\t{\"faisant\", 4, 6, 2, true, \"fais\", 4, 4, 2},\n\t\t{\"arrangés\", 2, 5, 4, true, \"arrang\", 2, 5, 4},\n\t\t{\"emparés\", 2, 5, 4, true, \"empar\", 2, 5, 4},\n\t\t{\"choqUée\", 4, 7, 3, true, \"choqU\", 4, 5, 3},\n\t\t{\"gênait\", 3, 6, 2, true, \"gên\", 3, 3, 2},\n\t\t{\"croissante\", 5, 8, 3, true, \"croiss\", 5, 6, 3},\n\t\t{\"scié\", 4, 4, 3, true, \"sci\", 3, 3, 3},\n\t\t{\"reconnaissez\", 3, 5, 2, true, \"reconnaiss\", 3, 5, 2},\n\t\t{\"pliaIent\", 5, 7, 3, true, \"pli\", 3, 3, 3},\n\t\t{\"expédia\", 2, 5, 4, true, \"expédi\", 2, 5, 4},\n\t\t{\"déshabillaIent\", 3, 6, 2, true, \"déshabill\", 3, 6, 2},\n\t\t{\"appréciée\", 2, 6, 5, true, \"appréci\", 2, 6, 5},\n\t\t{\"amputés\", 2, 5, 4, true, \"amput\", 2, 5, 4},\n\t\t{\"dominait\", 3, 5, 2, true, \"domin\", 3, 5, 2},\n\t\t{\"vexantes\", 3, 5, 2, true, \"vex\", 3, 3, 2},\n\t\t{\"fabriqUées\", 3, 6, 2, true, \"fabriqU\", 3, 6, 2},\n\t\t{\"retomber\", 3, 5, 2, true, \"retomb\", 3, 5, 2},\n\t\t{\"exercer\", 2, 4, 3, true, \"exerc\", 2, 4, 3},\n\t\t{\"entourait\", 2, 6, 4, true, \"entour\", 2, 6, 4},\n\t\t{\"voYait\", 3, 6, 2, true, \"voY\", 3, 3, 2},\n\t\t{\"soupait\", 4, 7, 2, true, \"soup\", 4, 4, 2},\n\t\t{\"apportiez\", 2, 5, 4, true, \"apport\", 2, 5, 4},\n\t\t{\"tuée\", 4, 4, 2, true, \"tu\", 2, 2, 2},\n\t\t{\"proposait\", 4, 6, 3, true, \"propos\", 4, 6, 3},\n\t\t{\"citations\", 3, 5, 2, true, \"citat\", 3, 5, 2},\n\t\t{\"distinguée\", 3, 6, 2, true, \"distingu\", 3, 6, 2},\n\t\t{\"parlerez\", 3, 6, 3, true, \"parl\", 3, 4, 3},\n\t\t{\"stanislas\", 4, 6, 3, true, \"stanisl\", 4, 6, 3},\n\t\t{\"enlevée\", 2, 5, 4, true, \"enlev\", 2, 5, 4},\n\t\t{\"irriguaIent\", 2, 5, 4, true, \"irrigu\", 2, 5, 4},\n\t\t{\"contenant\", 3, 6, 2, true, \"conten\", 3, 6, 2},\n\t\t{\"empêchèrent\", 2, 5, 4, true, \"empêch\", 2, 5, 4},\n\t\t{\"inspirées\", 2, 6, 5, true, \"inspir\", 2, 6, 5},\n\t\t{\"basée\", 3, 5, 2, true, \"bas\", 3, 3, 2},\n\t\t{\"consultait\", 3, 6, 2, true, \"consult\", 3, 6, 2},\n\t\t{\"retardait\", 3, 5, 2, true, \"retard\", 3, 5, 2},\n\t\t{\"enlevât\", 2, 5, 4, true, \"enlev\", 2, 5, 4},\n\t\t{\"convenaIent\", 3, 6, 2, true, \"conven\", 3, 6, 2},\n\t\t{\"portât\", 3, 6, 2, true, \"port\", 3, 4, 2},\n\t\t{\"admirée\", 2, 5, 4, true, \"admir\", 2, 5, 4},\n\t\t{\"copiée\", 3, 6, 2, true, \"copi\", 3, 4, 2},\n\t\t{\"démenaIent\", 3, 5, 2, true, \"démen\", 3, 5, 2},\n\t\t{\"fortifiées\", 3, 6, 2, true, \"fortifi\", 3, 6, 2},\n\t\t{\"apercevrait\", 2, 4, 3, true, \"apercevr\", 2, 4, 3},\n\t\t{\"risqUer\", 3, 7, 2, true, \"risqU\", 3, 5, 2},\n\t\t{\"réclamer\", 3, 6, 2, true, \"réclam\", 3, 6, 2},\n\t\t{\"tremblaIent\", 4, 8, 3, true, \"trembl\", 4, 6, 3},\n\t\t{\"calomnier\", 3, 5, 2, true, \"calomni\", 3, 5, 2},\n\t\t{\"réclamée\", 3, 6, 2, true, \"réclam\", 3, 6, 2},\n\t\t{\"déposât\", 3, 5, 2, true, \"dépos\", 3, 5, 2},\n\t\t{\"filé\", 3, 4, 2, true, \"fil\", 3, 3, 2},\n\t\t{\"déchirée\", 3, 6, 2, true, \"déchir\", 3, 6, 2},\n\t\t{\"prononça\", 4, 6, 3, true, \"prononç\", 4, 6, 3},\n\t\t{\"précédé\", 4, 6, 3, true, \"précéd\", 4, 6, 3},\n\t\t{\"asseYait\", 2, 5, 4, true, \"asseY\", 2, 5, 4},\n\t\t{\"emploYés\", 2, 6, 5, true, \"emploY\", 2, 6, 5},\n\t\t{\"chagriner\", 4, 7, 3, true, \"chagrin\", 4, 7, 3},\n\t\t{\"dévorât\", 3, 5, 2, true, \"dévor\", 3, 5, 2},\n\t\t{\"remonté\", 3, 5, 2, true, \"remont\", 3, 5, 2},\n\t\t{\"emploYant\", 2, 6, 5, true, \"emploY\", 2, 6, 5},\n\t\t{\"redoublait\", 3, 6, 2, true, \"redoubl\", 3, 6, 2},\n\t\t{\"marchant\", 3, 7, 2, true, \"march\", 3, 5, 2},\n\t\t{\"pétrifiée\", 3, 6, 2, true, \"pétrifi\", 3, 6, 2},\n\t\t{\"enlevées\", 2, 5, 4, true, \"enlev\", 2, 5, 4},\n\t\t{\"donnassent\", 3, 6, 2, true, \"donn\", 3, 4, 2},\n\t\t{\"recomptait\", 3, 5, 2, true, \"recompt\", 3, 5, 2},\n\t\t{\"masqUait\", 3, 8, 2, true, \"masqU\", 3, 5, 2},\n\t\t{\"renouvelèrent\", 3, 6, 2, true, \"renouvel\", 3, 6, 2},\n\t\t{\"recoucher\", 3, 6, 2, true, \"recouch\", 3, 6, 2},\n\t\t{\"abrégea\", 2, 5, 4, true, \"abrég\", 2, 5, 4},\n\t\t{\"flattait\", 4, 8, 3, true, \"flatt\", 4, 5, 3},\n\t}\n\tromance.RunStepTest(t, step2b, testCases)\n}", "func partTwo(inp []int) int {\n\tfor _, num1 := range inp {\n\t\tfor _, num2 := range inp {\n\t\t\tfor _, num3 := range inp {\n\t\t\t\tsum := num1 + num2 + num3\n\n\t\t\t\tif sum == 2020 {\n\t\t\t\t\treturn num1 * num2 * num3\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 0\n}", "func main() {\n\n\tpuzzle := PUZZLE{\n\t\t{0, 3, 0, 4, 8, 0, 6, 0, 9},\n\t\t{0, 0, 0, 0, 2, 7, 0, 0, 0},\n\t\t{8, 0, 0, 3, 0, 0, 0, 0, 0},\n\t\t{0, 1, 9, 0, 0, 0, 0, 0, 0},\n\t\t{7, 8, 0, 0, 0, 2, 0, 9, 3},\n\t\t{0, 0, 0, 0, 0, 4, 8, 7, 0},\n\t\t{0, 0, 0, 0, 0, 5, 0, 0, 6},\n\t\t{0, 0, 0, 1, 3, 0, 0, 0, 0},\n\t\t{9, 0, 2, 0, 4, 8, 0, 1, 0},\n\t}\n\n\tprintln(\"Start of Puzzle\")\n\tprintPuzzle(&puzzle)\n\n\tprintln(\"Solving...\")\n\tsolved := solve(puzzle)\n\n\tprintln(\"Done.\")\n\tprintPuzzle(solved)\n}", "func solve2(input string) string {\n\tprev := []byte(Password2)\n\tnext := make([]byte, len(prev))\n\tcopy(next, prev)\n\tvar n1, n2 int\n\tvar c1, c2 byte\n\tvar err error\n\tp := func(s string) { panic(s) }\n\tlines := strings.Split(input, \"\\n\")\n\t// run backwards\n\tfor i := len(lines) - 1; i > -1; i-- {\n\t\tline := lines[i]\n\t\t// work out what to do.\n\t\tif len(line) < 8 {\n\t\t\t// not a real line\n\t\t\tcontinue\n\t\t}\n\t\t//\tfmt.Printf(\"# %s\\n\", line)\n\t\tswitch line[0] {\n\t\tcase 'm': //move position X to position Y\n\t\t\tif _, err = fmt.Sscanf(line, \"move position %d to position %d\", &n1, &n2); err != nil {\n\t\t\t\tp(line)\n\t\t\t}\n\t\t\tmovePosition(prev, next, n2, n1)\n\t\tcase 's':\n\t\t\tswitch line[5] {\n\t\t\tcase 'l': // swap letter\n\t\t\t\tif _, err = fmt.Sscanf(line, \"swap letter %c with letter %c\", &c1, &c2); err != nil {\n\t\t\t\t\tp(line)\n\t\t\t\t}\n\t\t\t\tswapLetter(prev, next, c2, c1)\n\t\t\tcase 'p': // swap position\n\t\t\t\tif _, err = fmt.Sscanf(line, \"swap position %d with position %d\", &n1, &n2); err != nil {\n\t\t\t\t\tp(line)\n\t\t\t\t}\n\t\t\t\tswapPosition(prev, next, n2, n1)\n\t\t\t}\n\t\tcase 'r':\n\t\t\tswitch line[7] {\n\t\t\tcase ' ': // reverse positions\n\t\t\t\tif _, err = fmt.Sscanf(line, \"reverse positions %d through %d\", &n1, &n2); err != nil {\n\t\t\t\t\tp(line)\n\t\t\t\t}\n\t\t\t\treversePositions(prev, next, n1, n2) // nb this is it's own reverse function\n\t\t\tcase 'b': // rotate based on position\n\t\t\t\tif _, err = fmt.Sscanf(line, \"rotate based on position of letter %c\", &c1); err != nil {\n\t\t\t\t\tp(line)\n\t\t\t\t}\n\t\t\t\t// how do we do this...\n\t\t\t\treverseRotateFromLetter(prev, next, c1)\n\t\t\tcase 'l': //rotate left\n\t\t\t\tif _, err = fmt.Sscanf(line, \"rotate left %d step\", &n1); err != nil {\n\t\t\t\t\tp(line)\n\t\t\t\t}\n\t\t\t\trotate(prev, next, n1) //reversed to positive\n\t\t\tcase 'r': //rotate right\n\t\t\t\tif _, err = fmt.Sscanf(line, \"rotate right %d step\", &n1); err != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\trotate(prev, next, n1*-1) //reverse to negative\n\t\t\tdefault:\n\t\t\t\tp(line)\n\t\t\t}\n\t\tdefault:\n\t\t\tp(line)\n\t\t}\n\t\t// make them the same with next as the template\n\t\t//fmt.Printf(\"%s => %s\\n\", prev, next)\n\t\t// quick sanity check.\n\t\t//\tsanityCheck(next)\n\t\tcopy(prev, next)\n\t}\n\treturn string(prev)\n}", "func Test_step2a(t *testing.T) {\n\ttestCases := []romance.StepTestCase{\n\t\t{\"épanoUit\", 2, 4, 3, true, \"épanoU\", 2, 4, 3},\n\t\t{\"faillirent\", 4, 7, 2, true, \"faill\", 4, 5, 2},\n\t\t{\"acabit\", 2, 4, 3, true, \"acab\", 2, 4, 3},\n\t\t{\"établissait\", 2, 4, 3, true, \"établ\", 2, 4, 3},\n\t\t{\"découvrir\", 3, 6, 2, true, \"découvr\", 3, 6, 2},\n\t\t{\"réjoUissait\", 3, 5, 2, true, \"réjoU\", 3, 5, 2},\n\t\t{\"trahiront\", 4, 6, 3, true, \"trah\", 4, 4, 3},\n\t\t{\"maintenir\", 4, 7, 2, true, \"mainten\", 4, 7, 2},\n\t\t{\"vendit\", 3, 6, 2, true, \"vend\", 3, 4, 2},\n\t\t{\"repartit\", 3, 5, 2, true, \"repart\", 3, 5, 2},\n\t\t{\"giletti\", 3, 5, 2, true, \"gilett\", 3, 5, 2},\n\t\t{\"rienzi\", 4, 6, 2, true, \"rienz\", 4, 5, 2},\n\t\t{\"punie\", 3, 5, 2, true, \"pun\", 3, 3, 2},\n\t\t{\"accueillir\", 2, 7, 4, true, \"accueill\", 2, 7, 4},\n\t\t{\"rétablit\", 3, 5, 2, true, \"rétabl\", 3, 5, 2},\n\t\t{\"ravis\", 3, 5, 2, true, \"rav\", 3, 3, 2},\n\t\t{\"xviIi\", 4, 5, 3, true, \"xviI\", 4, 4, 3},\n\t\t{\"blottie\", 4, 7, 3, true, \"blott\", 4, 5, 3},\n\t\t{\"approfondie\", 2, 6, 5, true, \"approfond\", 2, 6, 5},\n\t\t{\"infirmerie\", 2, 5, 4, true, \"infirmer\", 2, 5, 4},\n\t\t{\"scotti\", 4, 6, 3, true, \"scott\", 4, 5, 3},\n\t\t{\"adoucissait\", 2, 5, 3, true, \"adouc\", 2, 5, 3},\n\t\t{\"finissait\", 3, 5, 2, true, \"fin\", 3, 3, 2},\n\t\t{\"promit\", 4, 6, 3, true, \"prom\", 4, 4, 3},\n\t\t{\"franchies\", 4, 9, 3, true, \"franch\", 4, 6, 3},\n\t\t{\"franchissant\", 4, 8, 3, true, \"franch\", 4, 6, 3},\n\t\t{\"micheli\", 3, 6, 2, true, \"michel\", 3, 6, 2},\n\t\t{\"éteignit\", 2, 5, 3, true, \"éteign\", 2, 5, 3},\n\t\t{\"puni\", 3, 4, 2, true, \"pun\", 3, 3, 2},\n\t\t{\"apoplexie\", 2, 4, 3, true, \"apoplex\", 2, 4, 3},\n\t\t{\"désira\", 3, 5, 2, true, \"dés\", 3, 3, 2},\n\t\t{\"étourdi\", 2, 5, 3, true, \"étourd\", 2, 5, 3},\n\t\t{\"giovanni\", 4, 6, 2, true, \"giovann\", 4, 6, 2},\n\t\t{\"apprécie\", 2, 6, 5, true, \"appréc\", 2, 6, 5},\n\t\t{\"poésies\", 4, 7, 2, true, \"poés\", 4, 4, 2},\n\t\t{\"pairie\", 4, 6, 2, true, \"pair\", 4, 4, 2},\n\t\t{\"sortit\", 3, 6, 2, true, \"sort\", 3, 4, 2},\n\t\t{\"subi\", 3, 4, 2, true, \"sub\", 3, 3, 2},\n\t\t{\"aigrirait\", 3, 6, 3, true, \"aigr\", 3, 4, 3},\n\t\t{\"assailli\", 2, 6, 4, true, \"assaill\", 2, 6, 4},\n\t\t{\"bertolotti\", 3, 6, 2, true, \"bertolott\", 3, 6, 2},\n\t\t{\"recouvrir\", 3, 6, 2, true, \"recouvr\", 3, 6, 2},\n\t\t{\"visconti\", 3, 6, 2, true, \"viscont\", 3, 6, 2},\n\t\t{\"surgir\", 3, 6, 2, true, \"surg\", 3, 4, 2},\n\t\t{\"remercie\", 3, 5, 2, true, \"remerc\", 3, 5, 2},\n\t\t{\"joUissaIent\", 3, 5, 2, true, \"joU\", 3, 3, 2},\n\t\t{\"bondissant\", 3, 6, 2, true, \"bond\", 3, 4, 2},\n\t\t{\"saisi\", 4, 5, 2, true, \"sais\", 4, 4, 2},\n\t\t{\"missouri\", 3, 7, 2, true, \"missour\", 3, 7, 2},\n\t\t{\"remplirent\", 3, 7, 2, true, \"rempl\", 3, 5, 2},\n\t\t{\"envahi\", 2, 5, 4, true, \"envah\", 2, 5, 4},\n\t\t{\"tandis\", 3, 6, 2, true, \"tand\", 3, 4, 2},\n\t\t{\"trahit\", 4, 6, 3, true, \"trah\", 4, 4, 3},\n\t\t{\"trahissaIent\", 4, 6, 3, true, \"trah\", 4, 4, 3},\n\t\t{\"réunie\", 4, 6, 2, true, \"réun\", 4, 4, 2},\n\t\t{\"avarie\", 2, 4, 3, true, \"avar\", 2, 4, 3},\n\t\t{\"dilettanti\", 3, 5, 2, true, \"dilettant\", 3, 5, 2},\n\t\t{\"raidie\", 4, 6, 2, true, \"raid\", 4, 4, 2},\n\t\t{\"écuries\", 2, 4, 3, true, \"écur\", 2, 4, 3},\n\t\t{\"recouvrît\", 3, 6, 2, true, \"recouvr\", 3, 6, 2},\n\t\t{\"parsis\", 3, 6, 3, true, \"pars\", 3, 4, 3},\n\t\t{\"monti\", 3, 5, 2, true, \"mont\", 3, 4, 2},\n\t\t{\"reproduisit\", 3, 6, 2, true, \"reproduis\", 3, 6, 2},\n\t\t{\"étendit\", 2, 4, 3, true, \"étend\", 2, 4, 3},\n\t\t{\"suffi\", 3, 5, 2, true, \"suff\", 3, 4, 2},\n\t\t{\"pillaji\", 3, 6, 2, true, \"pillaj\", 3, 6, 2},\n\t\t{\"rougir\", 4, 6, 2, true, \"roug\", 4, 4, 2},\n\t\t{\"désirez\", 3, 5, 2, true, \"dés\", 3, 3, 2},\n\t\t{\"subit\", 3, 5, 2, true, \"sub\", 3, 3, 2},\n\t\t{\"fondirent\", 3, 6, 2, true, \"fond\", 3, 4, 2},\n\t\t{\"coqUineries\", 3, 6, 2, true, \"coqUiner\", 3, 6, 2},\n\t\t{\"venir\", 3, 5, 2, true, \"ven\", 3, 3, 2},\n\t\t{\"plaidoirie\", 5, 8, 3, true, \"plaidoir\", 5, 8, 3},\n\t\t{\"fournissant\", 4, 7, 2, true, \"fourn\", 4, 5, 2},\n\t\t{\"bonzeries\", 3, 6, 2, true, \"bonzer\", 3, 6, 2},\n\t\t{\"flétri\", 4, 6, 3, true, \"flétr\", 4, 5, 3},\n\t\t{\"faillit\", 4, 7, 2, true, \"faill\", 4, 5, 2},\n\t\t{\"hardie\", 3, 6, 2, true, \"hard\", 3, 4, 2},\n\t\t{\"compagnie\", 3, 6, 2, true, \"compagn\", 3, 6, 2},\n\t\t{\"vernis\", 3, 6, 2, true, \"vern\", 3, 4, 2},\n\t\t{\"attendit\", 2, 5, 4, true, \"attend\", 2, 5, 4},\n\t\t{\"blanchies\", 4, 9, 3, true, \"blanch\", 4, 6, 3},\n\t\t{\"choisie\", 5, 7, 3, true, \"chois\", 5, 5, 3},\n\t\t{\"rafraîchir\", 3, 7, 2, true, \"rafraîch\", 3, 7, 2},\n\t\t{\"choisir\", 5, 7, 3, true, \"chois\", 5, 5, 3},\n\t\t{\"nourrisse\", 4, 7, 2, true, \"nourr\", 4, 5, 2},\n\t\t{\"chancellerie\", 4, 7, 3, true, \"chanceller\", 4, 7, 3},\n\t\t{\"repartie\", 3, 5, 2, true, \"repart\", 3, 5, 2},\n\t\t{\"redira\", 3, 5, 2, true, \"red\", 3, 3, 2},\n\t\t{\"sentira\", 3, 6, 2, true, \"sent\", 3, 4, 2},\n\t\t{\"surgirait\", 3, 6, 2, true, \"surg\", 3, 4, 2},\n\t\t{\"cani\", 3, 4, 2, true, \"can\", 3, 3, 2},\n\t\t{\"gratis\", 4, 6, 3, true, \"grat\", 4, 4, 3},\n\t\t{\"médît\", 3, 5, 2, true, \"méd\", 3, 3, 2},\n\t\t{\"avertis\", 2, 4, 3, true, \"avert\", 2, 4, 3},\n\t\t{\"chirurgie\", 4, 6, 3, true, \"chirurg\", 4, 6, 3},\n\t\t{\"ironie\", 2, 4, 3, true, \"iron\", 2, 4, 3},\n\t\t{\"punîtes\", 3, 5, 2, true, \"pun\", 3, 3, 2},\n\t\t{\"compromis\", 3, 7, 2, true, \"comprom\", 3, 7, 2},\n\t\t{\"simonie\", 3, 5, 2, true, \"simon\", 3, 5, 2},\n\t}\n\tromance.RunStepTest(t, step2a, testCases)\n}", "func firstStep(y int) {\n\tfmt.Println(\"1.1\", y)\n\ty = 52 // 1.4 assign y to 52\n\tfmt.Println(\"1.2\", y)\n}", "func m7RewardsAndDatesPart2(db *IndexerDb, state *MigrationState) error {\n\tdb.log.Print(\"m7 account cumulative rewards migration starting\")\n\n\t// Skip the work if all accounts have previously been updated.\n\tif (state.PointerRound == nil) || (*state.PointerRound != 0) || (*state.PointerIntra != 0) {\n\t\tmaxRound := uint32(state.NextRound)\n\n\t\t// Get the number of accounts to potentially warn the user about high memory usage.\n\t\terr := warnUser(db, maxRound)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Get special accounts, so that we can ignore them throughout the migration. A later migration\n\t\t// handles them.\n\t\tspecialAccounts, err := db.GetSpecialAccounts()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"m7: unable to get special accounts: %v\", err)\n\t\t}\n\t\t// Get the transaction id that created each account. This function simple loops over all\n\t\t// transactions from rounds <= `maxRound` in arbitrary order.\n\t\taccountsFirstUsed, err := getAccountsFirstUsed(db, maxRound, specialAccounts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Get account data for accounts without transactions such as genesis accounts.\n\t\t// This function reads the `account` table but only considers accounts created before or at\n\t\t// `maxRound`.\n\t\treadyAccountData, err := getAccountsWithoutTxnData(\n\t\t\tdb, maxRound, specialAccounts, accountsFirstUsed)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Finally, read all transactions from most recent to oldest, update rewards and create/close dates,\n\t\t// and write this account data to the database. To save memory, this function removes account's\n\t\t// data as soon as we reach the transaction that created this account at which point older\n\t\t// transactions cannot update its state. It writes account data to the database in batches.\n\t\terr = updateAccounts(db, specialAccounts, accountsFirstUsed, readyAccountData, state)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Update migration state.\n\tstate.NextMigration++\n\tstate.NextRound = 0\n\tstate.PointerRound = nil\n\tstate.PointerIntra = nil\n\tmigrationStateJSON := encoding.EncodeJSON(state)\n\t_, err := db.db.Exec(setMetastateUpsert, migrationMetastateKey, migrationStateJSON)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"m7: failed to write final migration state: %v\", err)\n\t}\n\n\treturn nil\n}", "func Problem14() {\n\n\tvar maxChain int\n\tvar maxChainNum int\n\tvar n int\n\n\tfor i := 1; i < 1000000; i++ {\n\n\t\tn = i\n\t\tfor length := 1; n != 1; length++ {\n\t\t\tif n%2 == 0 {\n\t\t\t\tn /= 2\n\t\t\t} else {\n\t\t\t\tn = 3*n + 1\n\t\t\t}\n\t\t\tif length > maxChain {\n\t\t\t\tmaxChain = length\n\t\t\t\tmaxChainNum = i\n\t\t\t}\n\t\t}\n\n\t}\n\n\tfmt.Println(maxChainNum, maxChain)\n}", "func run(input string) (interface{}, interface{}) {\n\tlist := pkg.ParseIntList(puzzle, \"\\n\")\n\n\tpart1, part2 := 0, 0\npart1:\n\tfor i, number := range list {\n\t\tif i < 25 {\n\t\t\tcontinue\n\t\t}\n\t\tpreviousNumbers := []int(nil)\n\t\tfor j := i - 1; i-j <= 25; j-- {\n\t\t\tpreviousNumbers = append(previousNumbers, list[j])\n\t\t}\n\t\tfor k, n1 := range previousNumbers {\n\t\t\tfor j, n2 := range previousNumbers {\n\t\t\t\tif k == j {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif n1+n2 == number {\n\t\t\t\t\tcontinue part1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tpart1 = number\n\t\tbreak\n\t}\n\ndance:\n\tfor i := 0; i < len(list); i++ {\n\t\tcontiguous := []int(nil)\n\t\tsum := 0\n\t\tfor j := i; j < len(list); j++ {\n\t\t\tif sum == part1 {\n\t\t\t\tpart2 = pkg.Min(contiguous...) + pkg.Max(contiguous...)\n\t\t\t\tbreak dance\n\t\t\t}\n\t\t\tif sum > part1 {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tsum += list[j]\n\t\t\tcontiguous = append(contiguous, list[j])\n\t\t}\n\t}\n\n\treturn part1, part2\n}", "func integerBreak(n int) int {\n if n == 2 {\n return 1\n }\n if n == 3 {\n return 2\n }\n product := 1\n for ; n > 4; n -= 3 {\n product *= 3\n }\n return product * n\n}", "func fourSum(nums []int, target int) [][]int {\n\tif len(nums) < 4 {\n\t\treturn nil\n\t}\n\tif len(nums) == 4 {\n\t\tif sum(nums) == target {\n\t\t\treturn [][]int{nums}\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tsort(nums)\n\n\tvar (\n\t\ta, b int\n\t\tlength = len(nums)\n\t\tc, d = 2, length - 1\n\t\tdp = make([][]int, length)\n\t)\n\tfor i := range dp {\n\t\tdp[i] = make([]int, length)\n\t}\n\tfor ; c < d; c++ {\n\t\tfor ; d > c; d-- {\n\t\t\tdp[c][d] = nums[c] + nums[d]\n\t\t}\n\t\td = length - 1\n\t}\n\tfmt.Println(\"dp: \", dp)\n\n\tvar (\n\t\ttemp1, temp2 int\n\t\tresult = make([][]int, 0, 20)\n\t)\n\tfor ; a < length-3; a++ {\n\t\ttemp1 = target - nums[a]\n\t\tfor b = a + 1; b < length-2; b++ {\n\t\t\ttemp2 = temp1 - nums[b]\n\t\t\tfor c = b + 1; c < d; c++ {\n\t\t\t\tfor ; d > c; d-- {\n\t\t\t\t\tif dp[c][d] == temp2 {\n\t\t\t\t\t\tresult = append(result, []int{nums[a], nums[b], nums[c], nums[d]})\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\td = length - 1\n\t\t\t\tfor c < d && nums[c] == nums[c+1] {\n\t\t\t\t\tc++\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor b < length-2 && nums[b] == nums[b+1] {\n\t\t\t\tb++\n\t\t\t}\n\t\t}\n\t\tfor a < length-3 && nums[a] == nums[a+1] {\n\t\t\ta++\n\t\t}\n\t}\n\n\treturn result\n}", "func fistStep(numbers []int) []int {\n\n\tdouble := make([]int, len(numbers))\n\n\tcopy(double, numbers)\n\n\tfor i := 0; i < len(double); i++ {\n\t\tif i%2 != 0 {\n\t\t\tdouble[i] = double[i] * 2\n\t\t\tif double[i] > 9 {\n\t\t\t\tdouble[i] = double[i] - 9\n\t\t\t}\n\t\t}\n\t}\n\n\treturn double\n}", "func secondStep(p *int) {\n\tfmt.Println(\"2.1\", p)\n\t*p = 52 // 2.4 assign p to 52\n\tfmt.Println(\"2.2\", *p)\n}", "func main() {\n\tvar n, x, y int\n\tfmt.Scan(&n)\n\n\t/*\n\t x, y > n\n\t n < x <= 2*n\n\t y = (n*x) / x - n\n\n\t x = 2*n\n\t tant que x > n\n\t x--\n\t y = (n*x) / (x-n)\n\t if (n*x) % (x-n) == 0 and y > n alors\n\t found solution: y = (n*x) / (x-n)\n\t sinon KO\n\t*/\n\n\tfor x = n + 1; x <= 2*n; x++ {\n\t\tif (n*x)%(x-n) == 0 {\n\t\t\ty = int((n * x) / (x - n))\n\t\t\tfmt.Printf(\"1/%d = 1/%v + 1/%v\\n\", n, y, x)\n\t\t}\n\t}\n}", "func FourSum(seq []int, target int) [][]int {\n res := [][]int{}\n seqPairMap := map[int][]int{} // { sum1: [i1, j1, i2, j2, ...], sum2: [i3, j3, i4, j4, ...], ... }\n for i := 0; i < len(seq) - 1; i++ {\n for j := i + 1; j < len(seq); j++ {\n sum := seq[i] + seq[j]\n if _, ok := seqPairMap[sum]; !ok { seqPairMap[sum] = []int{}; }\n seqPairMap[sum] = append(seqPairMap[sum], i)\n seqPairMap[sum] = append(seqPairMap[sum], j)\n }\n }\n // example: target = 14, sums are 5 + 9, 3 + 11 (map on smaller of the two i.e. 5, 3; other is implicit)\n sumMap := map[int][][]int{} // { 5: [[i1, j1, ...],[i5, j5, ...]], ...} 5 <-- [i1, j1, ...], 9 <-- [i5, j5, ...]\n for k, _ := range seqPairMap {\n if _, ok := seqPairMap[target-k]; ok {\n if k < target - k {\n sumMap[k] = [][]int{[]int{}, []int{}}\n sumMap[k][0] = seqPairMap[k]; sumMap[k][1] = seqPairMap[target-k];\n } else {\n sumMap[target-k] = [][]int{[]int{}, []int{}}\n sumMap[target-k][0] = seqPairMap[target-k]; sumMap[target-k][1] = seqPairMap[k];\n }\n }\n }\n \n for _, indexArr := range sumMap {\n arr0 := indexArr[0]; arr1 := indexArr[1]\n for m := 0; m < len(arr0); m += 2 {\n for n := 0; n < len(arr1); n += 2 {\n // check for distinctness of arr0[m], arr0[m+1], arr1[n], arr1[n+1]\n if arr0[m] != arr1[n] && arr0[m] != arr1[n+1] &&\n arr0[m+1] != arr1[n] && arr0[m+1] != arr1[n+1] {\n // still allows some dups to go through e.g. indexes [2 5 7 10], [2 7 5 10]\n res = append(res, []int{arr0[m], arr0[m+1], arr1[n], arr1[n+1]})\n }\n }\n }\n }\n // returns arrays of indices, convert to actual values as seq[i] for each i \n return res\n}", "func TestPart2(t *testing.T) {\n //NB: test data needs a triplet of numbers that sum to the target value 2020\n // and we pick a result that has modulus 4*7*2009 = 56252\n testData := []int{1,2,3,4,5,7,2009,4367}\n var r []int\n r = Part2(testData)\n if(len(r) != 4 || r[0] != 4 || r[1] != 7 || r[2] != 2009 || r[3] != 56252) {\n t.Log(\"Part2 did not find factors correctly: \", r)\n t.Fail()\n }\n}", "func waysToChange(n int) int {\n\tdp := make([]int, n+1)\n\tdp[0] = 1\n\tcoins := []int{1, 5, 10, 25}\n\tfor _, coin := range coins {\n\t\tfor i := coin; i <= n; i++ {\n\t\t\tdp[i] = (dp[i] + dp[i-coin]) % 1000000007\n\t\t}\n\t}\n\treturn dp[n]\n}", "func day1B() {\n\t//Test comment\n\tvar nums = []int{+5, -11, +17, +9, -4, -2, +11, -10, -16, +18, +18, -2, -2, +17, +13, +14, -11, +19, -14, +8, +10, -3, -12, +13, -3, +18, -20, +8, +3, +8, +13, +9, +14, -11, -6, +16, -12, +14, -8, +3, -18, -11, +6, -2, -14, -2, +17, -2, +6, -1, -13, +20, +9, +14, -15, -16, +18, -4, -8, +5, +19, -1, +19, +11, -3, +16, -12, -6, +3, -7, -1, +4, -15, -5, +13, +9, +11, +2, +17, +12, -7, -16, +13, -11, -14, +22, +16, -8, +16, +8, -10, +8, -19, +17, -9, +8, -2, +18, +9, +1, +10, -14, +6, +2, +2, -15, -15, -6, +11, +16, -8, +14, -18, -12, +14, +7, -1, -13, -18, -13, +5, -3, -18, +7, -2, -2, +6, -12, +15, +1, +18, -8, +22, +6, -1, +9, +9, +17, +18, +9, +13, -8, -17, +16, +16, +12, -11, -6, -9, +13, +11, -8, -12, +8, -10, +17, -13, -17, +7, -10, -3, +4, +1, -11, +3, -6, +19, +4, +13, +1, +11, +6, -3, +16, +8, +1, +17, -10, +18, -3, -7, +20, +4, +1, -8, +1, -2, +12, -1, +8, +8, +18, -10, +6, -16, +1, -3, +10, -11, -1, -5, +15, -11, -10, +18, +4, +8, +14, +6, +16, +12, +2, -19, +18, -5, -16, -10, -7, -3, +13, +14, +16, +13, -12, +15, +8, +17, +10, +7, +6, +17, +19, +19, -16, +10, +4, -16, -14, +8, +7, -22, -8, -19, +13, +12, -18, -21, +10, -12, -2, -12, -11, -16, -20, +6, -3, +2, -16, +9, -13, +1, +2, -13, +15, +9, -7, +22, -2, +18, +5, +4, -20, +14, -17, -19, +16, -6, +19, +1, +5, +24, +11, -16, +15, +13, +15, -3, -5, -17, -1, +8, +5, -10, +9, -2, +7, -11, -17, -13, -1, -9, +4, -10, -26, -22, +16, +14, +21, -20, +43, +8, -12, +2, -7, +15, +12, +17, +12, -18, +16, -12, +13, +8, +14, -12, +26, -6, +18, -3, -7, +19, -5, +13, +12, -14, -7, -14, +13, +13, -18, -6, +3, -12, +5, -20, +19, -11, -7, -15, -11, +12, -14, +24, -1, +18, +24, -9, +11, +9, -3, +8, -21, +1, +17, +1, +4, +20, -12, -5, +23, -9, +6, -12, -36, +13, -3, +33, -2, +9, +11, +23, -18, +22, -11, +14, +9, +8, -12, +5, -3, -3, +8, +16, +6, -18, +10, -18, -6, -1, -2, +24, -17, +23, +16, -9, +10, +23, -10, +2, +2, -9, +13, +3, +18, +12, +15, +16, -3, -7, -7, -5, +9, +1, -3, -19, -7, +17, +3, +13, +25, -4, -1, -19, -7, +15, -21, +43, +17, +5, +19, +10, +14, -15, -12, +19, +19, -16, -7, -7, -15, +6, -8, +18, +12, -7, -18, +9, +18, +16, -23, -18, -3, +12, -15, +9, +3, -14, +16, +18, +13, +19, -1, +11, +14, -4, -16, +11, -12, +27, -1, -13, +9, +7, -9, -1, +14, -35, -28, +1, +4, +15, -18, +10, -6, +12, -2, -5, -23, +31, -23, -37, +6, -13, -3, +4, +38, -23, -28, -24, -15, +4, +3, -16, +32, +13, -24, -9, -41, -41, -13, -41, -17, +16, -3, -36, -136, -9, +7, -4, -54, +20, +3, +11, +13, +16, +6, +6, -29, -118, -68, -416, -393, -73804, +17, +8, -14, +12, -22, -19, -7, -3, -14, +8, -3, -3, +16, -14, +5, -19, +16, +15, +8, +11, -14, -13, +3, +14, -15, +19, +26, +8, -11, -12, +17, -12, -12, +20, +22, +13, +14, +13, -3, -2, -1, -4, -16, +7, +12, +18, -15, -11, +7, -15, +11, +16, +13, +16, -2, -9, -4, +6, -8, -27, +16, -7, +87, +17, +11, -12, -2, +11, -13, -9, -10, -21, +15, -23, -15, +13, +11, +37, +16, +22, +16, +12, +18, -9, -8, +19, -5, -4, +13, +8, +4, -9, +4, +9, +4, -19, -2, -11, -2, +16, +17, +6, -8, +19, -2, +6, +2, -10, +12, +6, -20, -6, +5, +14, +12, +20, -21, +22, -2, +9, -2, -14, -15, +14, +7, -2, +9, -19, -52, -20, +4, -1, -18, +9, +7, -17, -22, -20, -7, -2, -9, +8, -3, +11, +18, -7, +17, +22, -18, -15, -19, -8, +13, +3, -15, +17, -3, -43, -34, +9, -37, +41, +141, -16, +19, -10, +14, +4, -7, -17, +12, +23, +2, +16, +36, -61, -253, -41, -44, -17, +10, -9, -5, +15, +20, +16, -4, +3, -12, +21, -11, -9, +16, -24, -12, +5, -2, -6, -18, -15, +16, -10, -5, -4, +8, +6, -20, -3, -19, +7, +4, -3, -11, +20, +4, +17, -3, -5, -3, +6, -4, -16, -15, +3, +19, -18, +16, -9, +17, +15, -25, -12, -17, -17, -4, +13, -15, +4, +17, -7, +13, -18, +4, +3, +10, +5, -1, +12, +9, -19, +16, +2, -11, -14, -14, -14, -2, +6, -3, +1, -15, +3, +2, -11, -9, +4, -3, +13, -1, -20, -19, -13, -8, -1, +13, +8, +9, +2, +6, +8, -9, -20, -5, +11, +20, +2, +9, +15, +17, +3, +18, -20, -3, +7, +8, +15, -6, -10, -16, +19, +2, -32, -7, -11, +3, +11, -25, -11, +16, -3, +16, -35, +10, +16, +24, -3, +1, -15, -8, +20, +27, +23, +20, -1, -14, +34, +14, +3, -18, +6, +10, +9, -18, -27, -42, -41, -37, -12, -22, +15, +12, -19, -18, +17, -15, +18, -4, +20, -12, +17, -34, -23, -8, -27, -4, -8, +20, -10, -8, -19, +8, -4, +11, -1, -11, +9, +1, -4, +15, -6, +3, -10, -10, -4, +5, +28, -2, +15, -21, +19, -1, -6, -8, +13, -44, +3, -9, +3, -24, -19, +17, -3, +7, -16, +11, +17, -27, -15, -2, -11, -18, +9, -6, -17, +2, -16, +13, +16, -9, +1, -13, -5, -11, +4, -2, +8, +3, +25, +15, -20, +7, +2, +5, -3, -13, -17, -5, -6, +4, +20, +22, +8, +18, -7, +4, +13, -1, -6, -14, -4, -5, -25, +21, -5, -20, +15, +20, +1, +1, +3, +5, +3, +75248}\n\tsum := 0\n\tset := make(map[int]bool)\n\tset[0] = true\n\tm := false\n\tfor set[sum] {\n\t\tfor _, num := range nums {\n\t\t\t// map the freq and check if array has that value, if true print and break\n\t\t\tsum += num\n\t\t\tif set[sum] {\n\t\t\t\tfmt.Println(\"freq match\")\n\t\t\t\tm = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tset[sum] = true\n\t\t}\n\t\tif m {\n\t\t\tbreak\n\t\t}\n\t}\n\tfmt.Println(\"match:\", sum)\n}", "func problem2() int {\n\tvar fib func(int, int, int) int\n\tfib = func(prev, cur, sum int) int {\n\t\tif cur < 4000000 {\n\t\t\tif cur%2 == 0 {\n\t\t\t\tsum += cur\n\t\t\t}\n\t\t\treturn fib(cur, prev+cur, sum)\n\t\t}\n\t\treturn sum\n\t}\n\treturn fib(1, 2, 0)\n}", "func main() {\n\tpp.Println(\"=========================================\")\n\tpp.Println(change(5, []int{1, 2, 5}))\n\tpp.Println(4)\n\tpp.Println(\"=========================================\")\n\tpp.Println(change(3, []int{2}))\n\tpp.Println(0)\n\tpp.Println(\"=========================================\")\n\tpp.Println(change(10, []int{10}))\n\tpp.Println(1)\n\tpp.Println(\"=========================================\")\n\tpp.Println(change(500, []int{1, 2, 5}))\n\tpp.Println(12701)\n\tpp.Println(\"=========================================\")\n}", "func main() {\n\n\t//fmt.Println(jump([]int{2, 1}))\n\t//fmt.Println(jump([]int{1, 3, 2}))\n\t//fmt.Println(jump([]int{1, 2}))\n\t//fmt.Println(jump([]int{1, 1, 1, 1, 1}))\n\t//fmt.Println(jump([]int{1, 2, 1, 1, 1}))\n\t//fmt.Println(jump([]int{2, 3, 1, 1, 4}))\n\tfmt.Println(jump([]int{3, 2, 1, 0, 4}))\n}", "func main() {\n\tb, _ := ioutil.ReadAll(os.Stdin)\n\torig := strings.Split(string(b), \",\")\n\n\tfor i := 0; i < 100; i++ {\n\t\tfor j := 0; j < 100; j++ {\n\t\t\tprog := make([]string, len(orig))\n\t\t\tcopy(prog, orig)\n\t\t\tnoun := strconv.Itoa(i)\n\t\t\tverb := strconv.Itoa(j)\n\t\t\tprog[1] = noun\n\t\t\tprog[2] = verb\n\n\t\t\tcode := \"0\"\n\t\t\tpc := 0\n\t\tLoop:\n\t\t\tfor {\n\t\t\t\tcode = prog[pc]\n\t\t\t\tswitch code {\n\t\t\t\tcase \"1\":\n\t\t\t\t\tp1 := atoi(prog[pc+1])\n\t\t\t\t\top1 := atoi(prog[p1])\n\t\t\t\t\tp2 := atoi(prog[pc+2])\n\t\t\t\t\top2 := atoi(prog[p2])\n\t\t\t\t\tp3 := atoi(prog[pc+3])\n\n\t\t\t\t\tprog[p3] = strconv.Itoa(op1 + op2)\n\t\t\t\t\tpc = pc + 4\n\t\t\t\tcase \"2\":\n\t\t\t\t\tp1 := atoi(prog[pc+1])\n\t\t\t\t\top1 := atoi(prog[p1])\n\t\t\t\t\tp2 := atoi(prog[pc+2])\n\t\t\t\t\top2 := atoi(prog[p2])\n\t\t\t\t\tp3 := atoi(prog[pc+3])\n\n\t\t\t\t\tprog[p3] = strconv.Itoa(op1 * op2)\n\t\t\t\t\tpc = pc + 4\n\t\t\t\tcase \"99\":\n\t\t\t\t\tif prog[0] == \"19690720\" {\n\t\t\t\t\t\tfmt.Println(\"HALT!\")\n\t\t\t\t\t\tfmt.Printf(\"noun %v verb %v \\n\", noun, verb)\n\t\t\t\t\t\tfmt.Println(\"POS 0\", prog[0])\n\t\t\t\t\t}\n\t\t\t\t\tbreak Loop\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(\"oh dear\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func waysToClimbStaircase(numberOfStairs int, possibleSteps []int) int {\n\tif numberOfStairs <= 0 {\n\t\treturn 0\n\t}\n\n\tpossibleWays := 0\n\tfor _, step := range possibleSteps {\n\t\tif numberOfStairs-step == 0 {\n\t\t\tpossibleWays++\n\t\t}\n\t}\n\tfor _, step := range possibleSteps {\n\t\tpossibleWays += waysToClimbStaircase(numberOfStairs-step, possibleSteps)\n\t}\n\n\treturn possibleWays\n}", "func Day09(input string) (answer1, answer2 string, err error) {\n\n\tic, err := intcode.NewFromString(input)\n\tif err != nil {\n\t\treturn\n\t}\n\tmemory := ic.Snapshot()\n\tintcode.InstallAdderMultiplier(ic)\n\tintcode.InstallJumpers(ic)\n\tic.Install(intcode.Inputter)\n\tic.Install(intcode.Outputter)\n\tic.Install(intcode.ChangeRelativeBase)\n\t// now run it.\n\tic.PushToInput(1)\n\tif err = ic.Operate(); !intcode.IsHalt(err) {\n\t\t// there's a deeper reason here...\n\t\tif serr, isOpErr := err.(*intcode.OperationError); isOpErr {\n\t\t\tglog.Errorf(\"ERROR DETAILS\")\n\t\t\tglog.Errorf(\"Memory: %v\", serr.Memory)\n\t\t\tglog.Errorf(\"PC: %v (%v)\", serr.PC, serr.Opcode)\n\t\t\tglog.Errorf(\"Inputs: %v\", serr.Input)\n\t\t\tglog.Errorf(\"Outputs: %v\", serr.Output)\n\t\t\tglog.Errorf(\"Underlying cause: %+v\", serr.Child)\n\t\t}\n\t\treturn\n\t}\n\tout, err := ic.GetOutput()\n\tif err != nil {\n\t\treturn\n\t}\n\tanswer1 = strconv.FormatInt(out, 10)\n\n\t// now for part 2\n\tic.Format(memory)\n\tic.PushToInput(2)\n\tif err = ic.Operate(); !intcode.IsHalt(err) {\n\t\t// there's a deeper reason here...\n\t\tif serr, isOpErr := err.(*intcode.OperationError); isOpErr {\n\t\t\tglog.Errorf(\"ERROR DETAILS\")\n\t\t\tglog.Errorf(\"Memory: %v\", serr.Memory)\n\t\t\tglog.Errorf(\"PC: %v (%v)\", serr.PC, serr.Opcode)\n\t\t\tglog.Errorf(\"Inputs: %v\", serr.Input)\n\t\t\tglog.Errorf(\"Outputs: %v\", serr.Output)\n\t\t\tglog.Errorf(\"Underlying cause: %+v\", serr.Child)\n\t\t}\n\t\treturn\n\t}\n\tout, err = ic.GetOutput()\n\tif err != nil {\n\t\treturn\n\t}\n\tanswer2 = strconv.FormatInt(out, 10)\n\n\treturn\n}", "func solutionLvl1(puzzle string, parameters map[string]int) (answer int) {\n\tfor _, line := range strings.Split(puzzle, \"\\n\") {\n\t\tif line != \"\" {\n\t\t\tanswer += evaluateExpr(line)\n\t\t}\n\t}\n\treturn\n}", "func run(input string) (interface{}, interface{}) {\n\tvar displays []sevenSegmentDisplay\n\n\tfor _, line := range strings.Split(input, \"\\n\") {\n\t\tdigitsAndTarget := strings.Split(line, \" | \")\n\t\tsegments := strings.Split(digitsAndTarget[0], \" \")\n\t\tval := strings.Split(digitsAndTarget[1], \" \")\n\t\t// sort them to enable the lookup table in the future\n\t\tfor i, s := range segments {\n\t\t\tsegments[i] = helpers.SortString(s)\n\t\t}\n\t\tfor i, s := range val {\n\t\t\tval[i] = helpers.SortString(s)\n\t\t}\n\t\tdisplays = append(displays, sevenSegmentDisplay{\n\t\t\tsegments: segments,\n\t\t\tvalues: val,\n\t\t})\n\t}\n\n\ttotalA := 0\n\tfor _, segment := range displays {\n\t\ttotalA += solveBasicSegments(segment)\n\t}\n\n\ttotalB := 0\n\tfor _, segment := range displays {\n\t\ttotalB += solveAllSegments(segment)\n\t}\n\n\treturn totalA, totalB\n}", "func solve2(input string) string {\n\tstacks, instructions := parseStacks(input)\n\n\tfor _, ins := range instructions {\n\t\t//fmt.Println(ins)\n\t\tmove2(stacks, ins.N, ins.Src, ins.Dst)\n\t}\n\n\t// now read off the tops of all the stacks.\n\tsb := strings.Builder{}\n\tfor _, s := range stacks {\n\t\tif len(s) > 0 {\n\t\t\tsb.WriteByte(s[len(s)-1])\n\t\t}\n\t}\n\n\treturn sb.String()\n}", "func kerDIT8(a []fr.Element, twiddles [][]fr.Element, stage int) {\n\n\tfr.Butterfly(&a[0], &a[1])\n\tfr.Butterfly(&a[2], &a[3])\n\tfr.Butterfly(&a[4], &a[5])\n\tfr.Butterfly(&a[6], &a[7])\n\tfr.Butterfly(&a[0], &a[2])\n\ta[3].Mul(&a[3], &twiddles[stage+1][1])\n\tfr.Butterfly(&a[1], &a[3])\n\tfr.Butterfly(&a[4], &a[6])\n\ta[7].Mul(&a[7], &twiddles[stage+1][1])\n\tfr.Butterfly(&a[5], &a[7])\n\tfr.Butterfly(&a[0], &a[4])\n\ta[5].Mul(&a[5], &twiddles[stage+0][1])\n\tfr.Butterfly(&a[1], &a[5])\n\ta[6].Mul(&a[6], &twiddles[stage+0][2])\n\tfr.Butterfly(&a[2], &a[6])\n\ta[7].Mul(&a[7], &twiddles[stage+0][3])\n\tfr.Butterfly(&a[3], &a[7])\n}", "func Day07() *day.Day {\n\n\tbuild := func() *tower {\n\t\tf := input.Open(7)\n\n\t\tscanner := bufio.NewScanner(f)\n\n\t\ttower := &tower{\n\t\t\tmake(map[string]string),\n\t\t\tmake(map[string][]string),\n\t\t\tmake(map[string]int),\n\t\t\t\"\",\n\t\t}\n\n\t\tcandidates := make(map[string]bool)\n\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\n\t\t\tvar name string\n\t\t\tvar weight int\n\t\t\tfmt.Sscanf(line, \"%s (%d)\", &name, &weight)\n\n\t\t\tcandidates[name] = true\n\n\t\t\tvar above []string\n\t\t\tarrow := \" -> \"\n\t\t\ti := strings.Index(line, arrow)\n\t\t\tif i >= 0 {\n\t\t\t\tvalues := line[i+len(arrow):]\n\t\t\t\tabove = strings.Split(values, \", \")\n\t\t\t\tfor _, n := range above {\n\t\t\t\t\tdelete(candidates, n)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttower.add(name, weight, above)\n\t\t}\n\n\t\tfor k := range tower.below {\n\t\t\tdelete(candidates, k)\n\t\t}\n\n\t\tif len(candidates) != 1 {\n\t\t\tpanic(\"This is unexptected...\")\n\t\t}\n\n\t\tfor k := range candidates {\n\t\t\ttower.root = k\n\t\t}\n\n\t\treturn tower\n\t}\n\n\tsolve := func() (interface{}, interface{}) {\n\t\ttower := build()\n\t\tpart1 := tower.root\n\t\tpart2, _ := tower.find(tower.root)\n\t\treturn part1, part2\n\t}\n\n\treturn day.New(7, \"Recursive Circus\", solve)\n}", "func (s Solution) Problem7(n int) int {\n\treturn findNthPrime(n)\n}", "func collectLast7Moves() {\n\t// Collect the state of nodes on the board as the 'TRUE' state.\n\tfor _, node := range nodes {\n\t\t// Clear the list.\n\t\tgameHistory[node.Id] = make([]*Pos, 0)\n\n\t\t// Put in current location.\n\t\tgameHistory[node.Id] = append(gameHistory[node.Id], node.CurrLoc)\n\n\t\ti := 1\n\t\txPos := node.CurrLoc.X\n\t\tyPos := node.CurrLoc.Y\n\t\ttrail := \"t\" + string(node.Id[len(node.Id)-1])\n\t\tfor i < 7 {\n\t\t\tp := findTrail(xPos, yPos, trail, gameHistory[node.Id])\n\t\t\tif p != nil {\n\t\t\t\tgameHistory[node.Id] = append(gameHistory[node.Id], p)\n\t\t\t\txPos = p.X\n\t\t\t\tyPos = p.Y\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ti++\n\t\t}\n\n\t\tlocalLog(\"History of node \", node.Id, \"with len\", len(gameHistory[node.Id]))\n\t\tfor _, p := range gameHistory[node.Id] {\n\t\t\tlocalLog(*p)\n\t\t}\n\t}\n}", "func SatFromBytes(out1 *[3]uint64, arg1 *[17]uint8) {\n\tx1 := arg1[16]\n\tx2 := (uint64(arg1[15]) << 56)\n\tx3 := (uint64(arg1[14]) << 48)\n\tx4 := (uint64(arg1[13]) << 40)\n\tx5 := (uint64(arg1[12]) << 32)\n\tx6 := (uint64(arg1[11]) << 24)\n\tx7 := (uint64(arg1[10]) << 16)\n\tx8 := (uint64(arg1[9]) << 8)\n\tx9 := arg1[8]\n\tx10 := (uint64(arg1[7]) << 56)\n\tx11 := (uint64(arg1[6]) << 48)\n\tx12 := (uint64(arg1[5]) << 40)\n\tx13 := (uint64(arg1[4]) << 32)\n\tx14 := (uint64(arg1[3]) << 24)\n\tx15 := (uint64(arg1[2]) << 16)\n\tx16 := (uint64(arg1[1]) << 8)\n\tx17 := arg1[0]\n\tx18 := (x16 + uint64(x17))\n\tx19 := (x15 + x18)\n\tx20 := (x14 + x19)\n\tx21 := (x13 + x20)\n\tx22 := (x12 + x21)\n\tx23 := (x11 + x22)\n\tx24 := (x10 + x23)\n\tx25 := (x8 + uint64(x9))\n\tx26 := (x7 + x25)\n\tx27 := (x6 + x26)\n\tx28 := (x5 + x27)\n\tx29 := (x4 + x28)\n\tx30 := (x3 + x29)\n\tx31 := (x2 + x30)\n\tout1[0] = x24\n\tout1[1] = x31\n\tout1[2] = uint64(x1)\n}", "func translateToTaskGroups(stepId2StepGroup []*StepGroup) (ret []*TaskGroup) {\n\tfor _, stepGroup := range stepId2StepGroup {\n\t\tassertSameNumberOfTasks(stepGroup.Steps)\n\t\tcount := len(stepGroup.Steps[0].Tasks)\n\t\t// println(\"dealing with\", stepGroup.Steps[0].Name, \"tasks:\", len(stepGroup.Steps[0].Tasks))\n\t\tfor i := 0; i < count; i++ {\n\t\t\ttg := NewTaskGroup()\n\t\t\tfor _, step := range stepGroup.Steps {\n\t\t\t\ttg.AddTask(step.Tasks[i])\n\t\t\t}\n\t\t\t// depends on the previous step group\n\t\t\t// MAYBE IMPROVEMENT: depends on a subset of previus shards\n\t\t\ttg.ParentStepGroup = stepGroup\n\t\t\tstepGroup.TaskGroups = append(stepGroup.TaskGroups, tg)\n\t\t\ttg.Id = len(ret)\n\t\t\tret = append(ret, tg)\n\t\t}\n\t}\n\treturn\n}", "func solve2(input string) string {\n\treturn solveN(input, 14)\n}", "func Solve0002() {\n\tvar answer int = 2\n\tvar base1 int = 1\n\tvar base2 int = 2\n\tvar addition int\n\tvar limit int = 4000000\n\n\tfor base2 < limit {\n\t\taddition = base1 + base2\n\t\tif addition%2 == 0 {\n\t\t\tanswer = answer + addition\n\t\t}\n\n\t\tbase1 = base2\n\t\tbase2 = addition\n\t}\n\n\tfmt.Println(answer)\n}", "func play(ba int, step int) int {\n\tif step>=n {\n\t\treturn 0\n\t} else if mem[ba][step]>=0 {\n\t\treturn mem[ba][step]\n\t}\n\t// pass fishka\n\tretp := p[step] + (pSumLeft[step+1] - play(1-ba, step+1));\n\t// stay with fishka\n\trets := play(ba, step+1)\n\t// max result\n\tret := retp\n\tif ret < rets {\n\t\tret = rets\n\t}\n\t// fmt.Printf(\"play(%d, %d) returned %d\\n\", ba,step, ret)\n\tmem[ba][step] = ret;\n\treturn ret;\n}", "func TrezorP2WPKHAndP2SH() []int {\n\treturn []int{35, 36, 37, 38}\n}", "func main(){\n var i int;\n // if i == i+1 { i++; break; };\n /* i = 1;\n\n for i < 5 { i = i+4; break; i--;}; // go's while loop\n \n for { i = i+9; };\n*/\n var j, k, l int;\n\n for ; l < 12; l = l+1 {\n\n here:\n for k = 0; k < 10; k = k+1 {\n for i = 0; i < 10; i = i+1 { \n\n if ( i == k ){\n j = j+2;\n continue;\n } else if ( i < k ){\n j = j+3;\n } else if ( i > 2*k ) {\n j = j+4;\n continue here;\n } else{\n j = j+1;\n };\n j=j+3;\n \n };\n };\n };\n /* i=2;\n {\n {\n i=100;\n };\n };\n i=21;*/\n \n}", "func solveAlgo6(g Solver, l *Line) {\n\t//l.print(\"solveAlgo6\")\n\trsg := l.getUnsolvedRanges()\n\n\tfor _, r := range rsg {\n\t\tcs := l.getPotentialCluesForRange(r)\n\n\t\tlongest := 0\n\t\tisFound, step := l.getStepToNextBlank(r, false)\n\t\tif isFound {\n\t\t\tisFound = false\n\t\t\tfor _, c := range cs {\n\t\t\t\tif c.index < l.ce {\n\t\t\t\t\tnext := l.clues[c.index+1]\n\t\t\t\t\tif step <= c.length-r.length() || step > next.length {\n\t\t\t\t\t\tisFound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlongest = max(longest, c.length-r.length())\n\t\t\t}\n\t\t\t//if we didn't find anyone, we can blank taking into account the longest trail\n\t\t\tif len(cs) > 1 && !isFound {\n\t\t\t\tfor i := longest + 1; i <= step; i++ {\n\t\t\t\t\tg.SetValue(l.squares[r.max+i], BLANK)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlongest = 0\n\t\tisFound, step = l.getStepToNextBlank(r, true)\n\t\tif isFound {\n\t\t\tisFound = false\n\t\t\tfor _, c := range cs {\n\t\t\t\tif c.index > l.cb {\n\t\t\t\t\tprevious := l.clues[c.index-1]\n\t\t\t\t\tif step <= c.length-r.length() || step > previous.length {\n\t\t\t\t\t\tisFound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlongest = max(longest, c.length-r.length())\n\t\t\t}\n\t\t\t//if we didn't find anyone, we can blank taking into account the longest trail\n\t\t\tif len(cs) > 1 && !isFound {\n\t\t\t\tfor i := longest + 1; i <= step; i++ {\n\t\t\t\t\tg.SetValue(l.squares[r.min-i], BLANK)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func resOriginal(n int) int {\n\tif n <= 2 { //区别Fibonacci\n\t\treturn n\n\t}\n\treturn resOriginal(n-1) + resOriginal(n-2)\n}", "func SolvePart2(data []string) {\n\tr := new(permutation.Request)\n\tphases := r.GenerateFor(\"56789\")\n\tmaxSignal := 0\n\n\tlg.Print(LogTagInfo, \"Number of phases to try: %v\\n\", len(phases))\n\n\tfor _, phase := range phases {\n\t\toutput := tryPhase(data, phase, false)\n\t\tif output > maxSignal {\n\t\t\tmaxSignal = output\n\t\t}\n\t}\n\tfmt.Println(\"Part 2 - Highest signal output:\", maxSignal)\n}", "func Day8Part1(input []string) (string, error) {\n\n\timData := input[0]\n\timWidth, imHeight := 25, 6\n\n\tlayers := generateLayers(imData, imWidth, imHeight)\n\n\tvar layerWithFewestZeros [][]int\n\tfewestZeros := imWidth * imHeight\n\tfor _, layer := range layers {\n\n\t\tzeros := 0\n\t\tfor y := 0; y < len(layer); y++ {\n\t\t\tfor x := 0; x < len(layer[y]); x++ {\n\t\t\t\tif layer[y][x] == 0 {\n\t\t\t\t\tzeros++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif zeros < fewestZeros {\n\t\t\tfewestZeros = zeros\n\t\t\tlayerWithFewestZeros = layer\n\t\t}\n\t}\n\n\tones, twos := 0, 0\n\tfor y := 0; y < len(layerWithFewestZeros); y++ {\n\t\tfor x := 0; x < len(layerWithFewestZeros[y]); x++ {\n\t\t\tswitch layerWithFewestZeros[y][x] {\n\t\t\tcase 1:\n\t\t\t\tones++\n\t\t\tcase 2:\n\t\t\t\ttwos++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn fmt.Sprintf(\"%d\", ones*twos), nil\n}", "func solution(rows int, cols int) string {\n\tretVal := \"Vivek\"\n\t//fmt.Println(rows, cols)\n\tif rows > cols {\n\t\trows, cols = cols, rows\n\t}\n\n\tif rows%2 == 1 {\n\t\tretVal = \"Ashish\"\n\n\t}\n\treturn retVal\n}", "func part2() {\n\tscanner := getScanner()\n\tscanner.Scan()\n\tscanner.Scan()\n\tbuses := strings.Split(scanner.Text(), \",\")\n\tcrts := []*CRT{}\n\tfor i, bus := range buses {\n\t\tif bus != \"x\" {\n\t\t\tcrt := &CRT{}\n\t\t\tbusNum, _ := strconv.Atoi(bus)\n\t\t\tcrt.n = big.NewInt(int64(busNum))\n\t\t\tcrt.a = big.NewInt(int64(busNum - i))\n\t\t\tcrts = append(crts, crt)\n\t\t}\n\t}\n\n\tp := new(big.Int).Set(crts[0].n)\n\tfor _, crt := range crts[1:] {\n\t\tp.Mul(p, crt.n)\n\t}\n\n\tvar x, q, s, z big.Int\n\tfor _, crt := range crts {\n\t\tq.Div(p, crt.n)\n\t\tz.GCD(nil, &s, crt.n, &q)\n\t\tx.Add(&x, s.Mul(crt.a, s.Mul(&s, &q)))\n\t}\n\tfmt.Println(x.Mod(&x, p))\n}", "func Hamming7(file []byte) []byte {\n\t//Mask that shows first bits\n\tmask1 := 240\n\t//Mask that shows last bits\n\tmask2 := 15\n\tentryLength := len(file)\n\t//Number that I use so that the size of the array is a multiple of 8, thus making compression simpler\n\tmodule := 0\n\tif 2*entryLength%8 != 0 {\n\t\tmodule = 8 - 2*entryLength%8\n\t}\n\tauxLength := 2*entryLength + module\n\tfinalLength := int(math.Ceil(float64(entryLength) * 1.75))\n\tvar auxArray = make([]byte, auxLength)\n\t//Applies the PracticoDeMaquina encode to each byte of the file\n\tfor i := 0; i < entryLength; i++ {\n\t\tvar firstBits, lastBits byte\n\t\tfirstBits = (file[i] & uint8(mask1)) >> 4\n\t\tlastBits = file[i] & uint8(mask2)\n\t\tauxArray[2*i] = encode7(firstBits)\n\t\tauxArray[2*i+1] = encode7(lastBits)\n\t}\n\tj := 0\n\tret := make([]byte, auxLength)\n\t//Compress the array\n\tfor i := 0; i < auxLength; i += 8 {\n\t\tsevenBlock := compressBlock(auxArray[i : i+8])\n\t\tret[j] = sevenBlock[0]\n\t\tret[j+1] = sevenBlock[1]\n\t\tret[j+2] = sevenBlock[2]\n\t\tret[j+3] = sevenBlock[3]\n\t\tret[j+4] = sevenBlock[4]\n\t\tret[j+5] = sevenBlock[5]\n\t\tret[j+6] = sevenBlock[6]\n\t\tj += 7\n\t}\n\treturn ret[0:finalLength]\n}", "func main() {\n\tInt := func(r byte) int { return int(r - '0') }\n\tvar i, n, cnt, firstSum, secondSum, dayNumber, genderNumber, firstCheck, secondCheck int\n\tfirstMultipliers := []int{3, 7, 6, 1, 8, 9, 4, 5, 2, 0}\n\tsecondMultipliers := []int{5, 4, 3, 2, 7, 6, 5, 4, 3, 2}\n\tdat, _ := ioutil.ReadFile(\"./input-fnr.txt\")\n\tfor _, line := range strings.Split(string(dat), \"\\n\") {\n\t\tif len(line) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tdayNumber, _ = strconv.Atoi(line[0:2])\n\t\tgenderNumber, _ = strconv.Atoi(line[8:9])\n\t\tif line[2:4] != \"08\" || genderNumber%2 != 0 || dayNumber > 31 {\n\t\t\tcontinue\n\t\t}\n\t\tfor i, firstSum, secondSum = 0, 0, 0; i < 10; i++ {\n\t\t\tn = Int(line[i])\n\t\t\tfirstSum += firstMultipliers[i] * n\n\t\t\tsecondSum += secondMultipliers[i] * n\n\t\t}\n\t\tfirstCheck, secondCheck = Int(line[9]), Int(line[10])\n\t\tfirstSum, secondSum = (11-(firstSum%11))%11, (11-(secondSum%11))%11\n\t\tif firstCheck == firstSum && secondCheck == secondSum && firstSum != 10 && secondSum != 10 {\n\t\t\tcnt++\n\t\t}\n\t}\n\tfmt.Println(cnt)\n}", "func Part2(program []int) (int, error) {\n\tphaseInput := []int{5, 6, 7, 8, 9}\n\tmaxOutput := 0\n\n\tvar err error\n\n\tcommon.PermutationsInt(phaseInput, func(phases []int) {\n\t\tcomputers := make([]*intcode.Computer, numAmplifiers)\n\n\t\t// create computers\n\t\tfor i := range computers {\n\t\t\tcomputers[i] = intcode.NewComputer(program)\n\t\t}\n\n\t\t// hook up inputs to previous computer's output\n\t\tfor i, cmp := range computers {\n\t\t\tif i == 0 {\n\t\t\t\ti = len(computers)\n\t\t\t}\n\t\t\tcmp.InputChan = computers[i-1].OutputChan\n\t\t}\n\n\t\t// set the initial phase input\n\t\tfor i, p := range phases {\n\t\t\tcomputers[i].InputChan <- p\n\t\t}\n\n\t\t// first computer gets initial 0 input\n\t\tcomputers[0].InputChan <- 0\n\n\t\tvar wg sync.WaitGroup\n\n\t\tfor i, cmp := range computers {\n\t\t\twg.Add(1)\n\t\t\tgo func(i int, c *intcode.Computer) {\n\t\t\t\tc.Run()\n\t\t\t\twg.Done()\n\t\t\t}(i, cmp)\n\t\t}\n\n\t\twg.Wait()\n\n\t\tlastOutputs := computers[len(computers)-1].Outputs()\n\t\tif len(lastOutputs) != 1 {\n\t\t\terr = fmt.Errorf(\"unexpected number of outputs\")\n\t\t\treturn\n\t\t}\n\n\t\tif lastOutputs[0] > maxOutput {\n\t\t\tmaxOutput = lastOutputs[0]\n\t\t}\n\t})\n\n\treturn maxOutput, err\n}", "func Day13b(input []string) string {\n\tbuses := list.New()\n\tfor i, bus := range strings.Split(input[1], \",\") {\n\t\tbusNum, err := strconv.Atoi(bus)\n\t\tif err == nil {\n\t\t\tbuses.PushBack(Bus{i, busNum})\n\t\t}\n\t}\n\n\tstep := buses.Front().Value.(Bus).step\n\tt := step\n\tfor e := buses.Front().Next(); e != nil; e = e.Next() {\n\t\tfor bus := e.Value.(Bus); (t+bus.position)%bus.step != 0; t += step {\n\t\t}\n\t\tstep *= e.Value.(Bus).step\n\t}\n\treturn strconv.Itoa(t)\n}", "func ToSat(out1 *[3]uint64, arg1 *TightFieldElement) {\n\tvar x1 uint64\n\tvar x2 uint1\n\tsubborrowxU44(&x1, &x2, 0x0, arg1[0], 0xffffffffffb)\n\tvar x3 uint64\n\tvar x4 uint1\n\tsubborrowxU43(&x3, &x4, x2, arg1[1], 0x7ffffffffff)\n\tvar x5 uint64\n\tvar x6 uint1\n\tsubborrowxU43(&x5, &x6, x4, arg1[2], 0x7ffffffffff)\n\tvar x7 uint64\n\tcmovznzU64(&x7, x6, uint64(0x0), 0xffffffffffffffff)\n\tvar x8 uint64\n\tvar x9 uint1\n\taddcarryxU44(&x8, &x9, 0x0, x1, (x7 & 0xffffffffffb))\n\tvar x10 uint64\n\tvar x11 uint1\n\taddcarryxU43(&x10, &x11, x9, x3, (x7 & 0x7ffffffffff))\n\tvar x12 uint64\n\tvar x13 uint1\n\taddcarryxU43(&x12, &x13, x11, x5, (x7 & 0x7ffffffffff))\n\tx14 := (uint128(x12) << 23)\n\tx15 := (uint128(x10) << 44)\n\tx16 := (x15 + uint128(x8))\n\tx17 := (uint64(x16) & 0xffffffffffffffff)\n\tx18 := uint64((x16 >> 64))\n\tx19 := (x14 + uint128(x18))\n\tx20 := (uint64(x19) & 0xffffffffffffffff)\n\tx21 := uint8((x19 >> 64))\n\tout1[0] = x17\n\tout1[1] = x20\n\tout1[2] = uint64(x21)\n}", "func Problem1046() {\n\n\tfmt.Println(lastStoneWeight([]int{2, 7, 4, 1, 8, 1}))\n\n}", "func pivotForLab(n float64) float64 {\n\tif n > 0.008856 {\n\t\treturn math.Pow(n, (1.0 / 3.0))\n\t}\n\treturn ((903.3*n + 16) / 116)\n}", "func parent_step(x uint) uint {\n\t// xy01 -> x011\n\tk := level(x)\n\tone := uint(1)\n\treturn (x | (one << k)) & ^(one << (k + 1))\n}", "func findSteps(lines [][]Point) []int {\n\tline1 := lines[0]\n\tline2 := lines[1]\n\n\tline1Size := len(lines[0])\n\tline2Size := len(lines[1])\n\tvar steps []int\n\n\tif line1Size == line2Size {\n\t\tfor i := 0; i <= line1Size-2; i++ {\n\t\t\tfor j := 0; j <= line1Size-2; j++ {\n\t\t\t\tnumSteps := calculateSteps(line1, line2, i, j)\n\t\t\t\tif numSteps != 0 {\n\t\t\t\t\tsteps = append(steps, numSteps)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else if line1Size > line2Size {\n\t\tfor i := 0; i <= line1Size-2; i++ {\n\t\t\tfor j := 0; j <= line2Size-2; j++ {\n\t\t\t\tnumSteps := calculateSteps(line1, line2, i, j)\n\t\t\t\tif numSteps != 0 {\n\t\t\t\t\tsteps = append(steps, numSteps)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor i := 0; i < line2Size-2; i++ {\n\t\t\tfor j := 0; j < line1Size-2; j++ {\n\t\t\t\tnumSteps := calculateSteps(line1, line2, i, j)\n\t\t\t\tif numSteps != 0 {\n\t\t\t\t\tsteps = append(steps, numSteps)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn steps\n}", "func numWays(steps int, arrLen int) int {\n\tfor i := 2; i <= 500; i += 2 {\n\t\tresult := calcWays(0, i, i/2, i/2, arrLen-1)\n\t\tcache[i] = result\n\t\tpp.Println(i, result)\n\t}\n\n\treturn calcWays(0, steps, steps/2, steps/2, arrLen-1)\n\t// Since the answer may be too large, return it modulo 10^9 + 7.\n\t// return 0\n}", "func buildOracleMultiple (p []string) (orToReturn map[int]map[uint8]int, f map[int][]int) {\n orTrie, stateIsTerminal, f := constructTrie(p)\n s := make([]int, len(stateIsTerminal)) //supply function\n i := 0 //root of trie\n orToReturn = orTrie\n s[i] = -1\n if debugMode==true {\n fmt.Printf(\"\\n\\nOracle construction: \\n\")\n }\n for current := 1; current < len(stateIsTerminal); current++ {\n o, parent := getParent(current, orTrie)\n down := s[parent]\n for stateExists(down, orToReturn) && getTransition(down, o, orToReturn) == -1 {\n createTransition(down, o, current, orToReturn)\n down = s[down]\n }\n if stateExists(down, orToReturn) {\n s[current] = getTransition(down, o, orToReturn)\n } else {\n s[current] = i\n }\n }\n return orToReturn, f\n}", "func elfProg() int {\n\t// value one = 10,551,381\n\t// valueOne := 2\n\t// // 19 is current prog counter\n\t// valueOne = valueOne * valueOne * 19 * 11\n\t// // valueOne = valueOne * 19\n\t// // valueOne = valueOne * 11\n\t// // 836\n\n\t// // twenty two is current prog counter\n\t// valueTwo := 6*22 + 13\n\t// valueOne += valueTwo\n\t// // 981\n\n\t// // Here, an instruction is skipped??? Prog counter incremented by 1. I'll write the instruction down in code.\n\t// // seti 0 -> 3 // Initial value gets set to the program counter??? While loop?\n\n\t// // 27 is the current prog counter\n\t// valueTwo = 27\n\t// // 28 is the current prog counter\n\t// valueTwo = 28 * valueTwo\n\t// // 29 is the current prog counter\n\t// valueTwo = 29 + valueTwo\n\t// // 30 is the current prog counter\n\t// valueTwo = 30 * valueTwo\n\t// valueTwo = 14 * valueTwo\n\t// // 32 is the current prog counter\n\t// valueTwo = 32 * valueTwo\n\t// valueOne += valueTwo\n\n\tincrementor := 10551381\n\treturnValue := 0\n\n\t// Ok, it looks like this little snippet just adds all the factors of the \"incrementor\" to the return value.\n\t// Maybe I should look at all the values i needed to multiply to get this awful number LOL.\n\t// Nvm, i'm gonna cheat and use an online calculator\n\t// 1 + 3 + 71 + 213 + 49537 + 148611 + 3517127 + 10551381 = 14266944\n\tfor i := 1; i <= incrementor; i++ {\n\t\tfor j := 1; j < incrementor; j++ {\n\t\t\tintermediate := i * j\n\t\t\tif intermediate == incrementor {\n\t\t\t\t// addr 4 0 0 (increment the return value by variable 'i' which is register 4.)\n\t\t\t\treturnValue += i\n\t\t\t}\n\t\t}\n\t}\n\n\treturn returnValue\n\n\t// // Here, prog counter gets set back to 0, then incremented to 1\n\t// valueThree := 1\n\t// valueFour := 1\n\t// valueTwo := valueThree * valueFour\n\t// if incrementor == valueTwo {\n\t// \tvalueTwo = 1\n\t// } else {\n\t// \tvalueTwo = 0\n\t// }\n\n\t// IF VALUE 2 equals 1, WE ARE GOING TO SKIP THE NEXT INSTRUCTION.\n\t// addi 3 1 3 // UH WHAT, SKIP THE NEXT INSTRUCTION AGAIN???\n\n\t// // If value 2 equaled 0, this instruction gets skipped b/c the \"addi 3 1 3\" instruction was run\n\t// if valueTwo == 1 {\n\t// \t// Yay increment the initial value\n\t// \treturnValue += valueFour\n\t// }\n\n\t// valueFour++ // Fuck, this was actually addi, not addr. Just increment one always.\n\n\t// // value one is a really big number\n\t// if valueFour > incrementor {\n\t// \tvalueTwo = 1\n\t// } else {\n\t// \tvalueTwo = 0\n\t// }\n\n\t// IF VALUE 2 equals 1, WE ARE GOING TO SKIP THE NEXT INSTRUCTION.\n\t// seti 2 3 // UH WHAT, go back to instruction 2, then 3??? While loop????\n\t// Ok, here is the first while loop from instruction 3 -> instruction 11\n\n\t// valueThree++\n\t// // Lol, now value three has to be bigger than value one\n\t// if valueThree > incrementor {\n\t// \tvalueTwo = 1\n\t// } else {\n\t// \tvalueTwo = 0\n\t// }\n\n\t// IF VALUE 2 equals 1, WE ARE GOING TO SKIP THE NEXT INSTRUCTION.\n\t// seti 1 3, go back to instruction 1, then 2. Does this mean i have to fucking repeat the first while loop?\n\t// Is this a double for loop???\n\n\t// mulr 3 3 3\n\t// ^^^ I'm asuming this breaks the program. Back at instruction 16.\n\t// At the beginning, instruction 16 got incremented immediately. Now register 3 is about to get fucked up with a value of 256.\n}", "func strobogrammatic(numCount int) []string {\n\tsbgNumbers := []int{1, 6, 8, 9, 0}\n\tn := numCount % 2\n\n\tvar numList []string\n\tvar f func(str string)\n\tf = func(str string) {\n\t\tif len(str) == numCount {\n\t\t\tnumList = append(numList, str)\n\t\t\treturn\n\t\t}\n\t\tfor _, x := range sbgNumbers {\n\t\t\ty := strconv.Itoa(x)\n\t\t\tif str == \"\" && n > 0 {\n\t\t\t\tif x == 6 || x == 9 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tf(y)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(str) == numCount-2 && x == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tz := y\n\t\t\tif x == 6 {\n\t\t\t\tz = \"9\"\n\t\t\t}\n\t\t\tif x == 9 {\n\t\t\t\tz = \"6\"\n\t\t\t}\n\t\t\tf(y + str + z)\n\t\t}\n\t}\n\tf(\"\")\n\n\treturn numList\n}", "func Solution009() string {\n\n\tanswer := 0\n\n\tLoop:\n\t\tfor a := 1; a < 1000; a++ {\n\t\t\tfor b := a+1; b < 1000; b++ {\n\t\t\t\tfor c := b+1; c < 1000; c++ {\n\t\t\t\t\tif a + b + c == 1000 && a*a + b*b == c*c {\n\t\t\t\t\t\tanswer = a*b*c\n\t\t\t\t\t\tbreak Loop\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\treturn strconv.Itoa(answer)\n}" ]
[ "0.56478983", "0.54741895", "0.54507023", "0.543882", "0.5436077", "0.5412232", "0.5351659", "0.5347985", "0.53406036", "0.53287077", "0.5303835", "0.52942103", "0.5291034", "0.5268272", "0.5268217", "0.5260187", "0.52593374", "0.5203191", "0.51988673", "0.51940155", "0.5187907", "0.5178124", "0.51710546", "0.5169173", "0.51690286", "0.51640797", "0.5156692", "0.5147985", "0.51375854", "0.5127095", "0.5126091", "0.51255804", "0.51245916", "0.5084605", "0.50794107", "0.5069305", "0.5067029", "0.5063854", "0.5059891", "0.5055176", "0.5052129", "0.50514734", "0.5040763", "0.5020624", "0.50176495", "0.50011784", "0.5000144", "0.4999708", "0.49937403", "0.49792212", "0.4976592", "0.4972826", "0.49693778", "0.4962767", "0.49591842", "0.49567667", "0.4956157", "0.49530777", "0.49415496", "0.494071", "0.49396038", "0.49382138", "0.49378318", "0.49337497", "0.4932272", "0.49273556", "0.4925213", "0.49181774", "0.4913648", "0.49135917", "0.48994273", "0.48954427", "0.4891763", "0.48848695", "0.48840865", "0.48831582", "0.48826692", "0.48814446", "0.4868448", "0.48671836", "0.48603028", "0.48585495", "0.48423773", "0.48393008", "0.4834292", "0.48325208", "0.48322514", "0.48235345", "0.48232993", "0.4819426", "0.48176628", "0.48128474", "0.48089656", "0.4805539", "0.4805232", "0.4801763", "0.48013565", "0.48004147", "0.48000285", "0.47997278", "0.479785" ]
0.0
-1
/ 75 92 92 92 90 75 92 92 92 90
func minOfMaxSlidingWindows(arr []int, k int) { size := len(arr) que := new(Queue) minVal := math.MaxInt32 i := 0 for i < size { // Remove out of range elements if que.Len() > 0 && que.Front().(int) <= i-k { que.Remove() } // Remove smaller values at left. for que.Len() > 0 && arr[que.Back().(int)] <= arr[i] { que.RemoveBack() } que.Add(i) // window of size k if i >= (k-1) && minVal > arr[que.Front().(int)] { minVal = arr[que.Front().(int)] } i += 1 } fmt.Println("Min of max is:", minVal) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func main() {\n\tvalues := []string{\"ABC\", \"ACB\", \"BAC\", \"BCA\", \"CAB\", \"CBA\"}\n\t// values := []string{\"to\", \"to\", \"top\", \"ton\", \"tom\"}\n\tfactor := []int{100, 10, 1}\n\n\t// 65x100 + 66x10 + 67x1 = 7227\n\thashKey := 0\n\tfor v := range values {\n\t\tbytes := []byte(values[v])\n\t\tf := 0\n\t\thashKey = 0\n\t\tfor i := range bytes {\n\t\t\tfmt.Print(bytes[i], \" \")\n\t\t\thashKey += int(bytes[i]) * factor[f]\n\t\t\tf++\n\t\t}\n\t\tfmt.Printf(\" (hashKey: %d) \\n\", hashKey)\n\t}\n}", "func part2(mem []int64) int64 {\n\tg := readGrid(mem)\n\tvar r robot\n\tfor y, row := range g {\n\t\tfor x, c := range row {\n\t\t\tif strings.ContainsRune(\"^v<>\", c) {\n\t\t\t\tr = robot{point{x, y}, north}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tprev := r.pos.move(west)\n\tpath := []direction{east}\n\tfor {\n\t\tadj := adjacent(g, r.pos)\n\t\tif len(path) > 2 && len(adj) == 1 {\n\t\t\tbreak\n\t\t}\n\t\tif 0 < len(adj) && len(adj) <= 2 {\n\t\t\tnext := adj[0]\n\t\t\tif len(adj) == 2 && adj[0] == prev {\n\t\t\t\tnext = adj[1]\n\t\t\t}\n\t\t\tif r.pos.x < next.x {\n\t\t\t\tr.dir = east\n\t\t\t}\n\t\t\tif r.pos.x > next.x {\n\t\t\t\tr.dir = west\n\t\t\t}\n\t\t\tif r.pos.y < next.y {\n\t\t\t\tr.dir = south\n\t\t\t}\n\t\t\tif r.pos.y > next.y {\n\t\t\t\tr.dir = north\n\t\t\t}\n\t\t}\n\t\tpath = append(path, r.dir)\n\t\tprev = r.pos\n\t\tr.move()\n\t}\n\n\tqueue := []step{{0, right}}\n\tfor i, d := range path[1:] {\n\t\trot := path[i].rotation(d)\n\t\tif len(queue) > 0 && rot == none {\n\t\t\tqueue[len(queue)-1].n++\n\t\t\tcontinue\n\t\t}\n\t\tqueue = append(queue, step{1, rot})\n\t}\n\n\tvar out string\n\tfor _, v := range queue {\n\t\tout += v.String() + \",\"\n\t}\n\tfmt.Println(out)\n\n\tp := newProgram(mem)\n\tp.memory[0] = 2\n\t// I have to be honest. I used my editors \"highlight other occurrences\"\n\t// feature on the previous output.\n\tin := strings.Join([]string{\n\t\t\"A,B,A,C,A,B,C,C,A,B\",\n\t\t\"R,8,L,10,R,8\",\n\t\t\"R,12,R,8,L,8,L,12\",\n\t\t\"L,12,L,10,L,8\",\n\t\t\"n\",\n\t\t\"\",\n\t}, \"\\n\")\n\tfor _, c := range in {\n\t\tp.input = append(p.input, int64(c))\n\t}\n\tres, err := p.run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn res[len(res)-1]\n}", "func main() {\n scanner := bufio.NewScanner(os.Stdin)\n scanner.Buffer(make([]byte, 1000000), 1000000)\n\n var width, height int\n scanner.Scan()\n fmt.Sscan(scanner.Text(),&width, &height)\n\n var count int\n scanner.Scan()\n fmt.Sscan(scanner.Text(),&count)\n\n grid := [][]string{}\n for i := 0; i < height; i++ {\n scanner.Scan()\n raster := scanner.Text()\n // _ = raster // to avoid unused error\n\n grid = append(grid, strings.Split(raster, \"\"))\n }\n\n for i := 0; i < count; i++ {\n for _, row := range grid {\n sort.Strings(row)\n }\n grid = anticlockwiseTurn90Degree(grid)\n }\n\n // fmt.Fprintln(os.Stderr, \"Debug messages...\")\n // fmt.Println(\"...\")// Write answer to stdout\n // fmt.Println(\"write ###\")\n for _, row := range grid {\n fmt.Println(strings.Join(row, \"\"))\n }\n}", "func split(sum int) (x,y int) {\n\tx = sum * 4/9\n\ty = sum - x\n\treturn\n}", "func maximalRectangle85(matrix [][]byte) int {\n\tif len(matrix) == 0 {\n\t\treturn 0\n\t}\n\tres := 0\n\n\tn := len(matrix[0])\n\tdp := make([]int, n)\n\n\tfor i := range matrix {\n\t\tfor j := range matrix[i] {\n\t\t\t// if the above element is 1, then we sum it up with current element; otherwise make current element 0\n\t\t\tif i == 0 {\n\t\t\t\tif matrix[i][j] == 49 {\n\t\t\t\t\tdp[j] = 1\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif matrix[i][j] != 48 {\n\t\t\t\t\tdp[j] = 1 + dp[j]\n\t\t\t\t} else {\n\t\t\t\t\tdp[j] = 0\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tres = int(math.Max(float64(res), float64(helper85(dp))))\n\t}\n\n\treturn res\n}", "func constructRectangle(area int) []int {\n a := int(math.Sqrt(float64(area)))\n for area % a != 0 {\n a--\n }\n return []int{area/a,a}\n}", "func c1(n int) int { return n - WIDTH - 1 }", "func main() {\n\tmatrix := [][]int {\n\t\t[]int { 8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8 },\n\t\t[]int { 49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0 },\n\t\t[]int { 81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65 },\n\t\t[]int { 52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91 },\n\t\t[]int { 22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80 },\n\t\t[]int { 24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50 },\n\t\t[]int { 32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70 },\n\t\t[]int { 67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21 },\n\t\t[]int { 24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72 },\n\t\t[]int { 21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95 },\n\t\t[]int { 78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92 },\n\t\t[]int { 16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57 },\n\t\t[]int { 86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58 },\n\t\t[]int { 19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40 },\n\t\t[]int { 4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66 },\n\t\t[]int { 88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69 },\n\t\t[]int { 4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36 },\n\t\t[]int { 20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16 },\n\t\t[]int { 20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54 },\n\t\t[]int { 1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48 } }\n\n\tvar candidate int\n\tfor i := 0; i < 20; i++ {\n\t\tfor j := 0; j < 20; j++ {\n\t\t\t// Walk the matrix and becareful of the edges.\n\t\t\t// We have 8 directions to evaluate\n\t\t\tdirections := []int {1,1,1,1,0,1,1,1,1}\n\t\t\tif i < 3 {\n\t\t\t\t// dont do north, northwest, or northeast\n\t\t\t\tdirections[0] = 0\n\t\t\t\tdirections[1] = 0\n\t\t\t\tdirections[2] = 0\n\t\t\t}\n\t\t\tif i > 16 {\n\t\t\t\t// dont do south, southwest, or southeast\n\t\t\t\tdirections[6] = 0\n\t\t\t\tdirections[7] = 0\n\t\t\t\tdirections[8] = 0\n\t\t\t}\n\t\t\tif j < 3 {\n\t\t\t\t// dont do west, northwest, or southwest\n\t\t\t\tdirections[0] = 0\n\t\t\t\tdirections[3] = 0\n\t\t\t\tdirections[6] = 0\n\t\t\t}\n\t\t\tif j > 16 {\n\t\t\t\t// dont do east, northeast, or southeast\n\t\t\t\tdirections[2] = 0\n\t\t\t\tdirections[5] = 0\n\t\t\t\tdirections[8] = 0\n\t\t\t}\n\n\t\t\t// location, direction, values, product\n\n\t\t\tfor l,v := range directions {\n\t\t\t\tif v == 1 {\n\t\t\t\t\tswitch l {\n\t\t\t\t\tcase 0:\n\t\t\t\t\t\t// northwest\n\t\t\t\t\t\tif candidate < matrix[i][j] * matrix[i-1][j-1] * matrix[i-2][j-2] * matrix[i-3][j-3] {\n\t\t\t\t\t\t\tfmt.Printf(\"i: %d j: %d dir: %s %d %d %d %d product: %d\\n\", i, j, \"nw\",\n\t\t\t\t\t\t\t\tmatrix[i][j], matrix[i-1][j-1], matrix[i-2][j-2], matrix[i-3][j-3],\n\t\t\t\t\t\t\t\tmatrix[i][j] * matrix[i-1][j-1] * matrix[i-2][j-2] * matrix[i-3][j-3] )\n\t\t\t\t\t\t\tcandidate = matrix[i][j] * matrix[i-1][j-1] * matrix[i-2][j-2] * matrix[i-3][j-3]\n\t\t\t\t\t\t}\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\t// north\n\t\t\t\t\t\tif candidate < matrix[i][j] * matrix[i-1][j] * matrix[i-2][j] * matrix[i-3][j] {\n\t\t\t\t\t\t\tfmt.Printf(\"i: %d j: %d dir: %s %d %d %d %d product: %d\\n\", i, j, \"n\",\n\t\t\t\t\t\t\t\tmatrix[i][j], matrix[i-1][j], matrix[i-2][j], matrix[i-3][j],\n\t\t\t\t\t\t\t\tmatrix[i][j] * matrix[i-1][j] * matrix[i-2][j] * matrix[i-3][j] )\n\t\t\t\t\t\t\tcandidate = matrix[i][j] * matrix[i-1][j] * matrix[i-2][j] * matrix[i-3][j]\n\t\t\t\t\t\t}\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\t// northeast\n\t\t\t\t\t\tif candidate < matrix[i][j] * matrix[i-1][j+1] * matrix[i-2][j+2] * matrix[i-3][j+3] {\n\t\t\t\t\t\t\tfmt.Printf(\"i: %d j: %d dir: %s %d %d %d %d product: %d\\n\", i, j, \"ne\",\n\t\t\t\t\t\t\t\tmatrix[i][j], matrix[i-1][j+1], matrix[i-2][j+2], matrix[i-3][j+3],\n\t\t\t\t\t\t\t\tmatrix[i][j] * matrix[i-1][j+1] * matrix[i-2][j+2] * matrix[i-3][j+3] )\n\t\t\t\t\t\t\tcandidate = matrix[i][j] * matrix[i-1][j+1] * matrix[i-2][j+2] * matrix[i-3][j+3]\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 3:\n\t\t\t\t\t\t// west\n\t\t\t\t\t\tif candidate < matrix[i][j] * matrix[i][j-1] * matrix[i][j-2] * matrix[i][j-3] {\n\t\t\t\t\t\t\tfmt.Printf(\"i: %d j: %d dir: %s %d %d %d %d product: %d\\n\", i, j, \"w\",\n\t\t\t\t\t\t\t\tmatrix[i][j], matrix[i][j-1], matrix[i][j-2], matrix[i][j-3],\n\t\t\t\t\t\t\t\tmatrix[i][j] * matrix[i][j-1] * matrix[i][j-2] * matrix[i][j-3] )\n\t\t\t\t\t\t\tcandidate = matrix[i][j] * matrix[i][j-1] * matrix[i][j-2] * matrix[i][j-3]\n\t\t\t\t\t\t}\n\t\t\t\t\tcase 4:\n\t\t\t\t\t\t// middle\n\t\t\t\t\t\tfmt.Printf(\"wut?\")\n\t\t\t\t\tcase 5:\n\t\t\t\t\t\t// east\n\t\t\t\t\t\tif candidate < matrix[i][j] * matrix[i][j+1] * matrix[i][j+2] * matrix[i][j+3] {\n\t\t\t\t\t\t\tfmt.Printf(\"i: %d j: %d dir: %s %d %d %d %d product: %d\\n\", i, j, \"e\",\n\t\t\t\t\t\t\t\tmatrix[i][j], matrix[i][j+1], matrix[i][j+2], matrix[i][j+3],\n\t\t\t\t\t\t\t\tmatrix[i][j] * matrix[i][j+1] * matrix[i][j+2] * matrix[i][j+3] )\n\t\t\t\t\t\t\tcandidate = matrix[i][j] * matrix[i][j+1] * matrix[i][j+2] * matrix[i][j+3]\n\t\t\t\t\t\t}\n\t\t\t\t\tcase 6:\n\t\t\t\t\t\t// southwest\n\t\t\t\t\t\tif candidate < matrix[i][j] * matrix[i+1][j-1] * matrix[i+2][j-2] * matrix[i+3][j-3] {\n\t\t\t\t\t\t\tfmt.Printf(\"i: %d j: %d dir: %s %d %d %d %d product: %d\\n\", i, j, \"ne\",\n\t\t\t\t\t\t\t\tmatrix[i][j], matrix[i+1][j-1], matrix[i+2][j-2], matrix[i+3][j-3],\n\t\t\t\t\t\t\t\tmatrix[i][j] * matrix[i+1][j-1] * matrix[i+2][j-2] * matrix[i+3][j-3] )\n\t\t\t\t\t\t\tcandidate = matrix[i][j] * matrix[i+1][j-1] * matrix[i+2][j-2] * matrix[i+3][j-3]\n\t\t\t\t\t\t}\n\t\t\t\t\tcase 7:\n\t\t\t\t\t\t// south\n\t\t\t\t\t\tif candidate < matrix[i][j] * matrix[i+1][j] * matrix[i+2][j] * matrix[i+3][j] {\n\t\t\t\t\t\t\tfmt.Printf(\"i: %d j: %d dir: %s %d %d %d %d product: %d\\n\", i, j, \"n\",\n\t\t\t\t\t\t\t\tmatrix[i][j], matrix[i+1][j], matrix[i+2][j], matrix[i+3][j],\n\t\t\t\t\t\t\t\tmatrix[i][j] * matrix[i+1][j] * matrix[i+2][j] * matrix[i+3][j] )\n\t\t\t\t\t\t\tcandidate = matrix[i][j] * matrix[i+1][j] * matrix[i+2][j] * matrix[i+3][j]\n\t\t\t\t\t\t}\n\t\t\t\t\tcase 8:\n\t\t\t\t\t\t// southeast\n\t\t\t\t\t\tif candidate < matrix[i][j] * matrix[i+1][j+1] * matrix[i+2][j+2] * matrix[i+3][j+3] {\n\t\t\t\t\t\t\tfmt.Printf(\"i: %d j: %d dir: %s %d %d %d %d product: %d\\n\", i, j, \"ne\",\n\t\t\t\t\t\t\t\tmatrix[i][j], matrix[i+1][j+1], matrix[i+2][j+2], matrix[i+3][j+3],\n\t\t\t\t\t\t\t\tmatrix[i][j] * matrix[i+1][j+1] * matrix[i+2][j+2] * matrix[i+3][j+3] )\n\t\t\t\t\t\t\tcandidate = matrix[i][j] * matrix[i+1][j+1] * matrix[i+2][j+2] * matrix[i+3][j+3]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Printf(\"candidate %d wins.\\n\", candidate )\n}", "func main() {\n\n\thittable := make(map[int]bool)\n\tans := int64(0)\n\n\tfor i := 1; i*i <= top*9*9; i++ {\n\t\thittable[i*i] = true\n\t}\n\n\tfor i := range hittable {\n\t\tways, _ := enumerate(9, top, i)\n\t\tfor i := 0; i < len(ways); i++ {\n\t\t\tans += process(ways[i])\n\t\t\tans %= mod\n\t\t}\n\t}\n\n\tfmt.Println(\"171/ Find the last nine digits of the sum of all n, 0 < n < 10^20, such that f(n) is a perfect square\")\n\tfmt.Println(ans)\n}", "func computeNj(P string) []int {\n\tn := len(P)\n\tNj := make([]int, n)\n\t// [l, r] is the current Z box.\n\tl := n\n\tr := n - 1\n\tfor i := n - 2; i >= 0; i-- {\n\t\tif i < l {\n\t\t\tj := i\n\t\t\tfor j >= 0 && P[n-1-i+j] == P[j] {\n\t\t\t\tj--\n\t\t\t}\n\t\t\tif j < i {\n\t\t\t\tl = j + 1\n\t\t\t\tr = i\n\t\t\t\tNj[i] = i - j\n\t\t\t}\n\t\t} else {\n\t\t\tbelta := Nj[n-1-r+i]\n\t\t\tif belta <= i-l {\n\t\t\t\tNj[i] = belta\n\t\t\t} else {\n\t\t\t\tj := l - 1\n\t\t\t\tfor ; j >= 0 && P[n-belta-i+j] == P[j]; j-- {\n\t\t\t\t}\n\t\t\t\tl = j + 1\n\t\t\t\tr = i\n\t\t\t\tNj[i] = i - j\n\t\t\t}\n\t\t}\n\t}\n\treturn Nj\n}", "func oo135(ratings []int) int {\n\tsum := 0\n\tleft, mid, right := 0, 0, 0\n\tfor {\n\t\tfor mid = left; mid+1 < len(ratings) && ratings[mid+1] > ratings[mid]; mid += 1 {\n\t\t}\n\t\tfor right = mid; right+1 < len(ratings) && ratings[right] > ratings[right+1]; right += 1 {\n\t\t}\n\t\tll, rr := mid-left, right-mid\n\t\tsum += (ll) * (ll + 1) / 2\n\t\tsum += (rr) * (rr + 1) / 2\n\t\tif ll > rr {\n\t\t\tsum += ll\n\t\t} else {\n\t\t\tsum += rr\n\t\t}\n\t\tsum += 1\n\t\t// change left\n\t\tif right == len(ratings)-1 {\n\t\t\tbreak\n\t\t}\n\t\tif ratings[right] == ratings[right+1] {\n\t\t\tleft = right + 1\n\t\t} else {\n\t\t\tleft = right\n\t\t\tsum -= 1\n\t\t}\n\t}\n\treturn sum\n}", "func round(i int) []subround {\n\tp := &perm512[i%4]\n\tr := &rot512[i%8]\n\treturn []subround{\n\t\t{int(p[0]), int(p[1]), int(r[0])},\n\t\t{int(p[2]), int(p[3]), int(r[1])},\n\t\t{int(p[4]), int(p[5]), int(r[2])},\n\t\t{int(p[6]), int(p[7]), int(r[3])},\n\t}\n}", "func Day8Part1(filepath string) any {\n\tvar res int\n\n\t// open file\n\treadFile, _ := os.Open(filepath)\n\n\t// read line\n\tfileScanner := bufio.NewScanner(readFile)\n\tfileScanner.Split(bufio.ScanLines)\n\n\t// parse map in to [][]int\n\ttreeMap := parseMap(fileScanner)\n\t// fmt.Println(treeMap)\n\n\t// init visible trees 2D array\n\tvisible := make([][]bool, len(treeMap))\n\tfor i := range visible {\n\t\tvisible[i] = make([]bool, len(treeMap[0]))\n\t}\n\n\t// look from left to r\n\tfor i := range treeMap {\n\t\tmax := 0\n\t\tfor j := range treeMap[0] {\n\t\t\tif i == 0 || i == len(treeMap)-1 || j == 0 || j == len(treeMap[0])-1 || treeMap[i][j] > max {\n\t\t\t\tvisible[i][j] = true\n\t\t\t\tmax = treeMap[i][j]\n\t\t\t}\n\t\t}\n\t}\n\n\t// look from right to l\n\tfor i := range treeMap {\n\t\tmax := 0\n\t\tfor j := len(treeMap[0]) - 1; j >= 0; j-- {\n\t\t\tif i == 0 || i == len(treeMap)-1 || j == 0 || j == len(treeMap[0])-1 || treeMap[i][j] > max {\n\t\t\t\tvisible[i][j] = true\n\t\t\t\tmax = treeMap[i][j]\n\t\t\t}\n\t\t}\n\t}\n\n\t// look from up to down\n\tfor j := 0; j <= len(treeMap[0])-1; j++ {\n\t\tmax := 0\n\t\tfor i := 0; i <= len(treeMap)-1; i++ {\n\t\t\tif i == 0 || i == len(treeMap)-1 || j == 0 || j == len(treeMap[0])-1 || treeMap[i][j] > max {\n\t\t\t\tvisible[i][j] = true\n\t\t\t\tmax = treeMap[i][j]\n\t\t\t}\n\t\t}\n\t}\n\n\t// look from down to up\n\tfor j := 0; j <= len(treeMap[0])-1; j++ {\n\t\tmax := 0\n\t\tfor i := len(treeMap) - 1; i >= 0; i-- {\n\t\t\tif i == 0 || i == len(treeMap)-1 || j == 0 || j == len(treeMap[0])-1 || treeMap[i][j] > max {\n\t\t\t\tvisible[i][j] = true\n\t\t\t\tmax = treeMap[i][j]\n\t\t\t}\n\t\t}\n\t}\n\n\t// traverse visible trees 2D array and count visibles\n\tfor i := range visible {\n\t\tfor j := range visible[i] {\n\t\t\tif visible[i][j] {\n\t\t\t\tres++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res\n}", "func solveAllSegments(display sevenSegmentDisplay) (result int) {\n\tlookupTable := make(map[string]int)\n\tcountPositions := make(map[rune]int)\n\tfor _, displayPos := range display.segments {\n\t\tfor _, char := range displayPos {\n\t\t\tcountPositions[char]++\n\t\t}\n\t}\n\n\tpositionSheet := make(map[int][]rune)\n\tfor char, val := range countPositions {\n\t\tpositionSheet[val] = append(positionSheet[val], char)\n\t}\n\n\tfor _, displayPos := range display.segments {\n\t\tswitch len(displayPos) {\n\t\tcase 2:\n\t\t\tlookupTable[displayPos] = 1\n\t\tcase 3:\n\t\t\tlookupTable[displayPos] = 7\n\t\tcase 4:\n\t\t\tlookupTable[displayPos] = 4\n\t\tcase 7:\n\t\t\tlookupTable[displayPos] = 8\n\t\tcase 5: // 2, 3 or 5\n\t\t\t// Only 2 has an empty space bottom-right\n\t\t\tif !strings.ContainsRune(displayPos, positionSheet[9][0]) {\n\t\t\t\tlookupTable[displayPos] = 2\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// if they have top and top-right it's 3 else 5\n\t\t\tif strings.ContainsRune(displayPos, positionSheet[8][0]) && strings.ContainsRune(displayPos, positionSheet[8][1]) {\n\t\t\t\tlookupTable[displayPos] = 3\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlookupTable[displayPos] = 5\n\t\tcase 6: // 0, 6 or 9\n\t\t\t// if they have bottom left they can be - 0 6 -\n\t\t\tif strings.ContainsRune(displayPos, positionSheet[4][0]) {\n\t\t\t\t// if they have top and top-right it's 0 else 6\n\t\t\t\tif strings.ContainsRune(displayPos, positionSheet[8][0]) && strings.ContainsRune(displayPos, positionSheet[8][1]) {\n\t\t\t\t\tlookupTable[displayPos] = 0\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlookupTable[displayPos] = 6\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlookupTable[displayPos] = 9\n\t\t}\n\t}\n\n\tvar resultString = \"\"\n\tfor _, value := range display.values {\n\t\tresultString += strconv.FormatInt(int64(lookupTable[value]), 10)\n\t}\n\n\treturn pkg.MustAtoi(resultString)\n}", "func SplitBy46(sum float64) (x, y float64){\n\tx = sum * (4.0/10.0)\n\ty = sum - x\n\treturn\n}", "func split(sum int) (x, y int) {\n\tx = sum * 4 / 9\n\ty = sum - x\n\treturn\n}", "func split(sum int) (x, y int) {\n\tx = sum * 4 / 9\n\ty = sum - x\n\treturn\n}", "func split(sum int) (x, y int) {\n\tx = sum * 4 / 9\n\ty = sum - x\n\treturn\n}", "func split(sum int) (x, y int) {\n\tx = sum * 4 / 9\n\ty = sum - x\n\treturn\n}", "func split(sum int) (x, y int) {\n\tx = sum * 4 / 9\n\ty = sum - x\n\treturn\n}", "func split(sum int) (x, y int) {\n\tx = sum * 4 / 9\n\ty = sum - x\n\treturn\n}", "func split(sum int) (x, y int) {\n\tx = sum * 4 / 9\n\ty = sum - x\n\treturn\n}", "func split(sum int) (x, y int) {\n\tx = sum * 4 / 9\n\ty = sum - x\n\treturn\n}", "func MiniMap(mini []string){\n fmt.Printf(\"Mini Map: \\n\")\n fmt.Printf(\" 1 2 3 4 5 \\n\")\n for i := 0; i <= 4; i ++ {\n fmt.Printf(\"%d\",(i+1))\n for j := 0; j <= 4; j ++ {\n fmt.Printf(\" %s \", mini[i*5+j])\n }\n fmt.Printf(\"\\n\")\n }\n fmt.Printf(\"*****************************************************************************\\n\")\n}", "func split(sum int) (x, y int) {\n\tx = sum * 4 / 9\n\ty = sum - x\n\t//fmt.Println(x)\n\t//fmt.Println(y)\n\treturn\n}", "func lookup8(k []byte, level uint64) uint64 {\n\t// uint8_t *k; /* the key */\n\t// uint64_t length; /* the length of the key */\n\t// uint64_t level; /* the previous hash, or an arbitrary value */\n\tvar a, b, c uint64\n\tvar length int\n\n\t/* Set up the internal state */\n\tlength = len(k)\n\ta = level\n\tb = level /* the previous hash value */\n\tc = 0x9e3779b97f4a7c13 /* the golden ratio; an arbitrary value */\n\tp := 0\n\t/*---------------------------------------- handle most of the key */\n\tfor length >= 24 {\n\t\ta += uint64(k[p+0]) + (uint64(k[p+1]) << 8) + (uint64(k[p+2]) << 16) + (uint64(k[p+3]) << 24) + (uint64(k[p+4]) << 32) + (uint64(k[p+5]) << 40) + (uint64(k[p+6]) << 48) + (uint64(k[p+7]) << 56)\n\t\tb += uint64(k[p+8]) + (uint64(k[p+9]) << 8) + (uint64(k[p+10]) << 16) + (uint64(k[p+11]) << 24) + (uint64(k[p+12]) << 32) + (uint64(k[p+13]) << 40) + (uint64(k[p+14]) << 48) + (uint64(k[p+15]) << 56)\n\t\tc += uint64(k[p+16]) + (uint64(k[p+17]) << 8) + (uint64(k[p+18]) << 16) + (uint64(k[p+19]) << 24) + (uint64(k[p+20]) << 32) + (uint64(k[p+21]) << 40) + (uint64(k[p+22]) << 48) + (uint64(k[p+23]) << 56)\n\t\tmix64(&a, &b, &c)\n\t\tp += 24\n\t\tlength -= 24\n\t}\n\n\t/*------------------------------------- handle the last 23 bytes */\n\tc += uint64(len(k))\n\tswitch length { /* all the case statements fall through */\n\tcase 23:\n\t\tc += (uint64(k[p+22]) << 56)\n\t\tfallthrough\n\tcase 22:\n\t\tc += (uint64(k[p+21]) << 48)\n\t\tfallthrough\n\tcase 21:\n\t\tc += (uint64(k[p+20]) << 40)\n\t\tfallthrough\n\tcase 20:\n\t\tc += (uint64(k[p+19]) << 32)\n\t\tfallthrough\n\tcase 19:\n\t\tc += (uint64(k[p+18]) << 24)\n\t\tfallthrough\n\tcase 18:\n\t\tc += (uint64(k[p+17]) << 16)\n\t\tfallthrough\n\tcase 17:\n\t\tc += (uint64(k[p+16]) << 8)\n\t\tfallthrough\n\t/* the first byte of c is reserved for the length */\n\tcase 16:\n\t\tb += (uint64(k[p+15]) << 56)\n\t\tfallthrough\n\tcase 15:\n\t\tb += (uint64(k[p+14]) << 48)\n\t\tfallthrough\n\tcase 14:\n\t\tb += (uint64(k[p+13]) << 40)\n\t\tfallthrough\n\tcase 13:\n\t\tb += (uint64(k[p+12]) << 32)\n\t\tfallthrough\n\tcase 12:\n\t\tb += (uint64(k[p+11]) << 24)\n\t\tfallthrough\n\tcase 11:\n\t\tb += (uint64(k[p+10]) << 16)\n\t\tfallthrough\n\tcase 10:\n\t\tb += (uint64(k[p+9]) << 8)\n\t\tfallthrough\n\tcase 9:\n\t\tb += (uint64(k[p+8]))\n\t\tfallthrough\n\tcase 8:\n\t\ta += (uint64(k[p+7]) << 56)\n\t\tfallthrough\n\tcase 7:\n\t\ta += (uint64(k[p+6]) << 48)\n\t\tfallthrough\n\tcase 6:\n\t\ta += (uint64(k[p+5]) << 40)\n\t\tfallthrough\n\tcase 5:\n\t\ta += (uint64(k[p+4]) << 32)\n\t\tfallthrough\n\tcase 4:\n\t\ta += (uint64(k[p+3]) << 24)\n\t\tfallthrough\n\tcase 3:\n\t\ta += (uint64(k[p+2]) << 16)\n\t\tfallthrough\n\tcase 2:\n\t\ta += (uint64(k[p+1]) << 8)\n\t\tfallthrough\n\tcase 1:\n\t\ta += uint64(k[p+0])\n\t\t/* case 0: nothing left to add */\n\t}\n\tmix64(&a, &b, &c)\n\t/*-------------------------------------------- report the result */\n\treturn c\n}", "func encryption(s string) string {\n\troot := math.Sqrt(float64(len(s)))\n\n\tn := int32(math.Floor(root))\n\tm := int32(math.Ceil(root))\n\n\tif n*m < int32(len(s)) {\n\t\tn++\n\t}\n\n\tfmt.Println(n)\n\tfmt.Println(m)\n\n\tinput := \"\"\n\n\tfor i := int32(0); i < n; i++ {\n\t\tinput += s[i*m : int32(math.Min(float64(i*m+m), float64(len(s))))]\n\n\t\tfor int32(len(input)) < i+(i+1)*m {\n\t\t\tinput += \" \"\n\t\t}\n\n\t\tinput += \"\\n\"\n\t}\n\n\tfmt.Println(input)\n\n\toutput := \"\"\n\n\tfor i := int32(0); i < m; i++ {\n\t\tfor j := int32(0); j < n; j++ {\n\t\t\tk := i + (m+1)*j\n\t\t\tif input[k] != ' ' || (output[len(output)-1] == ' ') {\n\t\t\t\toutput += string(input[k])\n\t\t\t}\n\t\t}\n\t\toutput += \" \"\n\t}\n\n\treturn output\n}", "func main() {\n var N int\n fmt.Scan(&N)\n\n tryPoint := 5\n transformPoint := 2\n penaDropPoint := 3\n\n var results []string\n\n possibleTryTimes := int(math.Floor(float64(N / tryPoint)))\n for tryTimes := possibleTryTimes; tryTimes >= 0; tryTimes-- {\n tryPoints := tryPoint * tryTimes\n\n possibleTransformationTimes := int(math.Min(float64((N - tryPoints) / transformPoint), float64(tryTimes)))\n for transformationTimes := possibleTransformationTimes; transformationTimes >= 0; transformationTimes-- {\n transformPoints := transformPoint * transformationTimes\n\n reminingPoints := N - tryPoints - transformPoints\n if reminingPoints % penaDropPoint == 0 {\n penaltieOrDropTimes := reminingPoints / penaDropPoint\n result := fmt.Sprintf(\"%d %d %d\", tryTimes, transformationTimes, penaltieOrDropTimes)\n\n results = append([]string{result}, results...)\n }\n }\n }\n\n // fmt.Fprintln(os.Stderr, \"Debug messages...\")\n // fmt.Println(\"tries transformations penalties\")// Write answer to stdout\n for _, v := range results {\n fmt.Println(v)\n }\n}", "func part1() {\n\ts := \"abc\"\n\tcount := 0\n\ti := 0\n\th := md5.New()\n\tbuffer := bytes.NewBuffer(make([]byte, 64))\n\n\tfor count < 8 {\n\t\tbuffer.Reset()\n\t\tfmt.Fprintf(buffer, \"%s%d\", s, i)\n\n\t\th.Reset()\n\t\th.Write(buffer.Bytes())\n\t\tdigest := h.Sum(nil)\n\t\tif digest[0] == 0 && digest[1] == 0 && digest[2] < 16 {\n\t\t\tfmt.Printf(\"%x\", digest[2])\n\t\t\tcount++\n\t\t}\n\t\ti++\n\t}\n\tfmt.Println()\n}", "func minimumBribes(q []int32) {\n\tbribes := 0\n\tqbribes := make([]int, len(q))\n\treverse := false\n\tfor i, j := 0, len(q)-1; i < len(q); {\n\t\tif !reverse {\n\t\t\tfor x := 0; x < len(q)-i-1; x++ {\n\t\t\t\tif q[x]-1 == int32(x) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif q[x] > q[x+1] {\n\t\t\t\t\tqbribes[q[x]-1]++\n\t\t\t\t\tif qbribes[q[x]-1] > 2 {\n\t\t\t\t\t\tfmt.Printf(\"Too chaotic\\n\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tq[x], q[x+1] = q[x+1], q[x]\n\t\t\t\t\tbribes++\n\t\t\t\t}\n\t\t\t}\n\t\t\ti++\n\t\t} else {\n\t\t\tfor x := j; x > i; x-- {\n\t\t\t\tif q[x]-1 == int32(x) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif q[x-1] > q[x] {\n\t\t\t\t\tqbribes[q[x-1]-1]++\n\t\t\t\t\tif qbribes[q[x-1]-1] > 2 {\n\t\t\t\t\t\tfmt.Printf(\"Too chaotic\\n\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tq[x-1], q[x] = q[x], q[x-1]\n\t\t\t\t\tbribes++\n\t\t\t\t}\n\t\t\t}\n\t\t\tj--\n\t\t}\n\t\treverse = !reverse\n\t}\n\tfmt.Printf(\"%d\\n\", bribes)\n}", "func sherlockAndAnagrams(s string) int32 {\n\trs := []rune(s)\n\tans := make(map[string]int)\n\tsl := len(rs)\n\tret := 0\n\tfor l := 1; l <= sl; l++ {\n\t\tfor i := 0; i+l <= sl; i++ {\n\t\t\tsub := make([]rune, l)\n\t\t\tcopy(sub, rs[i:i+l])\n\t\t\tsort.Slice(sub, func(m, n int) bool {\n\t\t\t\treturn sub[m] < sub[n]\n\t\t\t})\n\t\t\tans[string(sub)]++\n\t\t}\n\t}\n\tfor _, v := range ans {\n\t\tret += v * (v - 1) / 2\n\t}\n\treturn int32(ret)\n}", "func pack60(src []uint64) uint64 {\n\t_ = src[59] // eliminate multiple bounds checks\n\treturn 2<<60 |\n\t\tsrc[0] |\n\t\tsrc[1]<<1 |\n\t\tsrc[2]<<2 |\n\t\tsrc[3]<<3 |\n\t\tsrc[4]<<4 |\n\t\tsrc[5]<<5 |\n\t\tsrc[6]<<6 |\n\t\tsrc[7]<<7 |\n\t\tsrc[8]<<8 |\n\t\tsrc[9]<<9 |\n\t\tsrc[10]<<10 |\n\t\tsrc[11]<<11 |\n\t\tsrc[12]<<12 |\n\t\tsrc[13]<<13 |\n\t\tsrc[14]<<14 |\n\t\tsrc[15]<<15 |\n\t\tsrc[16]<<16 |\n\t\tsrc[17]<<17 |\n\t\tsrc[18]<<18 |\n\t\tsrc[19]<<19 |\n\t\tsrc[20]<<20 |\n\t\tsrc[21]<<21 |\n\t\tsrc[22]<<22 |\n\t\tsrc[23]<<23 |\n\t\tsrc[24]<<24 |\n\t\tsrc[25]<<25 |\n\t\tsrc[26]<<26 |\n\t\tsrc[27]<<27 |\n\t\tsrc[28]<<28 |\n\t\tsrc[29]<<29 |\n\t\tsrc[30]<<30 |\n\t\tsrc[31]<<31 |\n\t\tsrc[32]<<32 |\n\t\tsrc[33]<<33 |\n\t\tsrc[34]<<34 |\n\t\tsrc[35]<<35 |\n\t\tsrc[36]<<36 |\n\t\tsrc[37]<<37 |\n\t\tsrc[38]<<38 |\n\t\tsrc[39]<<39 |\n\t\tsrc[40]<<40 |\n\t\tsrc[41]<<41 |\n\t\tsrc[42]<<42 |\n\t\tsrc[43]<<43 |\n\t\tsrc[44]<<44 |\n\t\tsrc[45]<<45 |\n\t\tsrc[46]<<46 |\n\t\tsrc[47]<<47 |\n\t\tsrc[48]<<48 |\n\t\tsrc[49]<<49 |\n\t\tsrc[50]<<50 |\n\t\tsrc[51]<<51 |\n\t\tsrc[52]<<52 |\n\t\tsrc[53]<<53 |\n\t\tsrc[54]<<54 |\n\t\tsrc[55]<<55 |\n\t\tsrc[56]<<56 |\n\t\tsrc[57]<<57 |\n\t\tsrc[58]<<58 |\n\t\tsrc[59]<<59\n\n}", "func answerQuery(l int32, r int32) int32 {\n // Return the answer for this query modulo 1000000007.\n letters := make([]int32, 26)\n unique := int32(0)\n for i := l - 1; i < r; i++ {\n if letters[S[i] - 97] == int32(0){\n unique++\n }\n letters[S[i] - 97]++\n }\n\n if unique == int32(1){\n return int32(1)\n }\n\n middles := int64(0)\n substringLength := int64(0)\n duplicates := int64(1)\n result := int64(1)\n for _, n := range letters {\n if n == 0 {\n continue\n }\n\n if n == 1 {\n middles++\n continue\n }\n\n if n % 2 == 1 {\n middles++\n }\n\n for i := int64(0); int32(i) < n / 2; i++ {\n substringLength++\n result *= substringLength\n result %= M\n duplicates *= i + 1\n duplicates %= M\n }\n }\n\n duplicates = expBySquaring(duplicates, M - 2)\n result *= duplicates\n result %= M\n\n if result == 0 {\n return int32(middles % M)\n }\n\n if middles > 0 {\n result *= middles\n result %= M\n }\n\n return int32(result)\n}", "func yeast(num int64) (encoded string) {\n\talphabet := \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_\"\n\tlength := int64(len(alphabet))\n\tfor num > 0 {\n\t\tencoded = string(alphabet[int(num%length)]) + encoded\n\t\tnum = int64(math.Floor(float64(num / length)))\n\t}\n\treturn\n}", "func findPaths2(m int, n int, maxMove int, startRow int, startColumn int) int {\n\tprevGrid := make([][]int, m)\n\tnextGrid := make([][]int, m)\n\tfor i := 0; i < m; i++ {\n\t\tprevGrid[i] = make([]int, n)\n\t\tnextGrid[i] = make([]int, n)\n\t}\n\n\tres := 0\n\tprevGrid[startRow][startColumn] = 1\n\n\tfor move := 0; move < maxMove; move++ {\n\t\tfor x := 0; x < m; x++ {\n\t\t\tfor y := 0; y < n; y++ {\n\t\t\t\tv := prevGrid[x][y] % modulo\n\t\t\t\tif v == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tprevGrid[x][y] = 0\n\n\t\t\t\tif x == 0 {\n\t\t\t\t\tres += v\n\t\t\t\t} else {\n\t\t\t\t\tnextGrid[x-1][y] += v\n\t\t\t\t}\n\n\t\t\t\tif x == m-1 {\n\t\t\t\t\tres += v\n\t\t\t\t} else {\n\t\t\t\t\tnextGrid[x+1][y] += v\n\t\t\t\t}\n\n\t\t\t\tif y == 0 {\n\t\t\t\t\tres += v\n\t\t\t\t} else {\n\t\t\t\t\tnextGrid[x][y-1] += v\n\t\t\t\t}\n\n\t\t\t\tif y == n-1 {\n\t\t\t\t\tres += v\n\t\t\t\t} else {\n\t\t\t\t\tnextGrid[x][y+1] += v\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprevGrid, nextGrid = nextGrid, prevGrid\n\t}\n\n\treturn res % modulo\n}", "func xx512x1(inner_512 []byte) [20]byte {\n\touter_512 := sha512.Sum512(inner_512)\n\treturn sha1.Sum(outer_512[:])\n}", "func row(k int) int { return k % 4 }", "func _rotate(matrix [][]int) {\n\tn := len(matrix)\n\tif n <= 1 {\n\t\treturn\n\t}\n\n\t// 从外到内遍历每一圈\n\tfor level := 1; level <= n/2; level++ {\n\t\trowMin := level - 1\n\t\trowMax := n - level\n\t\tcolMin := level - 1\n\t\tcolMax := n - level\n\t\t// 将每一圈分为四块相等的区域,每个区域的元素数目为 n-2*(level-1)-1\n\t\tbatchSize := n - 2*(level-1) - 1\n\t\tfor offset := 0; offset < batchSize; offset++ {\n\t\t\t// 在缓存区中放入上区块的元素\n\t\t\ttemp := matrix[rowMin][colMin+offset]\n\t\t\t// 在上区块放入左区块的元素\n\t\t\tmatrix[rowMin][colMin+offset] = matrix[rowMax-offset][colMin]\n\t\t\t// 在左区块放入下区块的元素\n\t\t\tmatrix[rowMax-offset][colMin] = matrix[rowMax][colMax-offset]\n\t\t\t// 在下区块放入右区块的元素\n\t\t\tmatrix[rowMax][colMax-offset] = matrix[rowMin+offset][colMax]\n\t\t\t// 在右区块放入缓存区的元素\n\t\t\tmatrix[rowMin+offset][colMax] = temp\n\t\t}\n\t}\n}", "func minimumBribes(q []int32) {\n\tvar ret, i int32\n\tvar length = int32(len(q))\n\tvar t1 = make([]int32, length+1)\n\tfor i = 0; i < length+1; i++ {\n\t\tt1[i] = i\n\t}\n\tvar t2 = make([]int32, length+1)\n\tcopy(t2[:], t1)\n\tfor i = 1; i <= length; i++ {\n\t\tv := q[i-1]\n\t\tif v > i+2 {\n\t\t\tret = -1\n\t\t\tbreak\n\t\t} else if t2[v] > i {\n\t\t\tfor j := t2[v] - 1; j >= i; j-- {\n\t\t\t\tt1[j+1] = t1[j]\n\t\t\t\tt2[t1[j]]++\n\t\t\t\tret++\n\t\t\t}\n\t\t\tt2[v] = i\n\t\t}\n\t}\n\tif ret == -1 {\n\t\tfmt.Println(\"Too chaotic\")\n\t} else {\n\t\tfmt.Println(ret)\n\t}\n\n}", "func zig(i uint32, j uint32) uint32 {\n\tif (i > 0x4000) || (j > 0x4000) {\n\t\tpanic(\"overflow\")\n\t}\n\tn := i + j\n\treturn ((n * (n + 1)) / 2) + j\n}", "func BP2FP(perm []uint8) [][4]uint8 {\n\tn := uint8(len(perm))\n\trects := make([][4]uint8, n+1)\n\trects[perm[0]] = [4]uint8{0, n, 0, n}\n\tbelow := make(map[uint8]uint8)\n\tleft := make(map[uint8]uint8)\n\tprevlabel := perm[0]\n\n\tfor k := uint8(1); k < n; k++ {\n\t\tp := perm[k]\n\t\tif p < prevlabel {\n\t\t\toldrect := rects[prevlabel]\n\t\t\t// middle := (oldrect[2] + oldrect[3]) / 2\n\n\t\t\t// Horizontal slice\n\t\t\trects[p] = oldrect\n\t\t\trects[p][2] = k\n\t\t\trects[prevlabel][3] = k\n\n\t\t\t// Store spatial relations\n\t\t\tbelow[p] = prevlabel\n\t\t\tlp, past := left[prevlabel]\n\t\t\tif past {\n\t\t\t\tleft[p] = lp\n\t\t\t}\n\n\t\t\t_, ok := left[p]\n\t\t\tfor ok && left[p] > p {\n\t\t\t\tl := left[p]\n\n\t\t\t\trects[p][0] = rects[l][0]\n\n\t\t\t\trects[l][3] = rects[p][2]\n\n\t\t\t\tll, okl := left[l]\n\t\t\t\tif okl {\n\t\t\t\t\tleft[p] = ll\n\t\t\t\t} else {\n\t\t\t\t\tdelete(left, p)\n\t\t\t\t}\n\n\t\t\t\tok = okl\n\t\t\t}\n\n\t\t\tprevlabel = p\n\n\t\t} else {\n\t\t\toldrect := rects[prevlabel]\n\t\t\t// middle := (oldrect[0] + oldrect[1]) / 2\n\n\t\t\t// Vertical slice\n\t\t\trects[p] = oldrect\n\t\t\trects[p][0] = k\n\t\t\trects[prevlabel][1] = k\n\n\t\t\t// Store spatial relations\n\t\t\tleft[p] = prevlabel\n\t\t\tbp, past := below[prevlabel]\n\t\t\tif past {\n\t\t\t\tbelow[p] = bp\n\t\t\t}\n\n\t\t\t_, ok := below[p]\n\t\t\tfor ok && below[p] < p {\n\t\t\t\tb := below[p]\n\n\t\t\t\trects[p][2] = rects[b][2]\n\n\t\t\t\trects[b][1] = rects[p][0]\n\n\t\t\t\tbb, okb := below[b]\n\t\t\t\tif okb {\n\t\t\t\t\tbelow[p] = bb\n\t\t\t\t} else {\n\t\t\t\t\tdelete(below, p)\n\t\t\t\t}\n\n\t\t\t\tok = okb\n\t\t\t}\n\n\t\t\tprevlabel = p\n\n\t\t}\n\t}\n\n\treturn rects[1:]\n}", "func main() {\n\tfor o := 65; o <= 90; o++ {\n\t\tfmt.Println(o)\n\t\tfor i := 0; i < 3; i++ {\n\t\t\tfmt.Printf(\"\\t%#U\\n\", o)\n\t\t}\n\t}\n}", "func findPaths(m int, n int, maxMove int, startRow int, startColumn int) int {\n\tgrid := make([][][]int, maxMove+1)\n\tfor k := 0; k <= maxMove; k++ {\n\t\tgrid[k] = make([][]int, m)\n\t\tfor i := 0; i < m; i++ {\n\t\t\tgrid[k][i] = make([]int, n)\n\t\t}\n\t}\n\n\tres := 0\n\tgrid[0][startRow][startColumn] = 1\n\n\tfor move := 0; move < maxMove; move++ {\n\t\tfor x := 0; x < m; x++ {\n\t\t\tfor y := 0; y < n; y++ {\n\t\t\t\tv := grid[move][x][y] % modulo\n\t\t\t\tif v == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif x == 0 {\n\t\t\t\t\tres += v\n\t\t\t\t} else {\n\t\t\t\t\tgrid[move+1][x-1][y] += v\n\t\t\t\t}\n\n\t\t\t\tif x == m-1 {\n\t\t\t\t\tres += v\n\t\t\t\t} else {\n\t\t\t\t\tgrid[move+1][x+1][y] += v\n\t\t\t\t}\n\n\t\t\t\tif y == 0 {\n\t\t\t\t\tres += v\n\t\t\t\t} else {\n\t\t\t\t\tgrid[move+1][x][y-1] += v\n\t\t\t\t}\n\n\t\t\t\tif y == n-1 {\n\t\t\t\t\tres += v\n\t\t\t\t} else {\n\t\t\t\t\tgrid[move+1][x][y+1] += v\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res % modulo\n}", "func space_hash(x, y, n uint64) (SpaceMapKey) {\n return SpaceMapKey((x*1640531513 ^ y*2654435789) % n)\n}", "func scReduce(dst, src []byte) {\n\t// Input:\n\t// s[0]+256*s[1]+...+256^63*s[63] = s\n\t//\n\t// Output:\n\t// s[0]+256*s[1]+...+256^31*s[31] = s mod l\n\t// where l = 2^252 + 27742317777372353535851937790883648493.\n\n\ts0 := int64(0x1fffff & load3(src[0:]))\n\ts1 := int64(0x1fffff & (load4(src[2:]) >> 5))\n\ts2 := int64(0x1fffff & (load3(src[5:]) >> 2))\n\ts3 := int64(0x1fffff & (load4(src[7:]) >> 7))\n\ts4 := int64(0x1fffff & (load4(src[10:]) >> 4))\n\ts5 := int64(0x1fffff & (load3(src[13:]) >> 1))\n\ts6 := int64(0x1fffff & (load4(src[15:]) >> 6))\n\ts7 := int64(0x1fffff & (load3(src[18:]) >> 3))\n\ts8 := int64(0x1fffff & load3(src[21:]))\n\ts9 := int64(0x1fffff & (load4(src[23:]) >> 5))\n\ts10 := int64(0x1fffff & (load3(src[26:]) >> 2))\n\ts11 := int64(0x1fffff & (load4(src[28:]) >> 7))\n\ts12 := int64(0x1fffff & (load4(src[31:]) >> 4))\n\ts13 := int64(0x1fffff & (load3(src[34:]) >> 1))\n\ts14 := int64(0x1fffff & (load4(src[36:]) >> 6))\n\ts15 := int64(0x1fffff & (load3(src[39:]) >> 3))\n\ts16 := int64(0x1fffff & load3(src[42:]))\n\ts17 := int64(0x1fffff & (load4(src[44:]) >> 5))\n\ts18 := int64(0x1fffff & (load3(src[47:]) >> 2))\n\ts19 := int64(0x1fffff & (load4(src[49:]) >> 7))\n\ts20 := int64(0x1fffff & (load4(src[52:]) >> 4))\n\ts21 := int64(0x1fffff & (load3(src[55:]) >> 1))\n\ts22 := int64(0x1fffff & (load4(src[57:]) >> 6))\n\ts23 := int64(load4(src[60:]) >> 3)\n\tvar (\n\t\tcarry0, carry1, carry2, carry3 int64\n\t\tcarry4, carry5, carry6, carry7 int64\n\t\tcarry8, carry9, carry10, carry11 int64\n\t\tcarry12, carry13, carry14, carry15 int64\n\t\tcarry16 int64\n\t)\n\n\ts11 += s23 * 666643\n\ts12 += s23 * 470296\n\ts13 += s23 * 654183\n\ts14 -= s23 * 997805\n\ts15 += s23 * 136657\n\ts16 -= s23 * 683901\n\n\ts10 += s22 * 666643\n\ts11 += s22 * 470296\n\ts12 += s22 * 654183\n\ts13 -= s22 * 997805\n\ts14 += s22 * 136657\n\ts15 -= s22 * 683901\n\n\ts9 += s21 * 666643\n\ts10 += s21 * 470296\n\ts11 += s21 * 654183\n\ts12 -= s21 * 997805\n\ts13 += s21 * 136657\n\ts14 -= s21 * 683901\n\n\ts8 += s20 * 666643\n\ts9 += s20 * 470296\n\ts10 += s20 * 654183\n\ts11 -= s20 * 997805\n\ts12 += s20 * 136657\n\ts13 -= s20 * 683901\n\n\ts7 += s19 * 666643\n\ts8 += s19 * 470296\n\ts9 += s19 * 654183\n\ts10 -= s19 * 997805\n\ts11 += s19 * 136657\n\ts12 -= s19 * 683901\n\n\ts6 += s18 * 666643\n\ts7 += s18 * 470296\n\ts8 += s18 * 654183\n\ts9 -= s18 * 997805\n\ts10 += s18 * 136657\n\ts11 -= s18 * 683901\n\n\tcarry6 = (s6 + (1 << 20)) >> 21\n\ts7 += carry6\n\ts6 -= carry6 << 21\n\tcarry8 = (s8 + (1 << 20)) >> 21\n\ts9 += carry8\n\ts8 -= carry8 << 21\n\tcarry10 = (s10 + (1 << 20)) >> 21\n\ts11 += carry10\n\ts10 -= carry10 << 21\n\tcarry12 = (s12 + (1 << 20)) >> 21\n\ts13 += carry12\n\ts12 -= carry12 << 21\n\tcarry14 = (s14 + (1 << 20)) >> 21\n\ts15 += carry14\n\ts14 -= carry14 << 21\n\tcarry16 = (s16 + (1 << 20)) >> 21\n\ts17 += carry16\n\ts16 -= carry16 << 21\n\n\tcarry7 = (s7 + (1 << 20)) >> 21\n\ts8 += carry7\n\ts7 -= carry7 << 21\n\tcarry9 = (s9 + (1 << 20)) >> 21\n\ts10 += carry9\n\ts9 -= carry9 << 21\n\tcarry11 = (s11 + (1 << 20)) >> 21\n\ts12 += carry11\n\ts11 -= carry11 << 21\n\tcarry13 = (s13 + (1 << 20)) >> 21\n\ts14 += carry13\n\ts13 -= carry13 << 21\n\tcarry15 = (s15 + (1 << 20)) >> 21\n\ts16 += carry15\n\ts15 -= carry15 << 21\n\n\ts5 += s17 * 666643\n\ts6 += s17 * 470296\n\ts7 += s17 * 654183\n\ts8 -= s17 * 997805\n\ts9 += s17 * 136657\n\ts10 -= s17 * 683901\n\n\ts4 += s16 * 666643\n\ts5 += s16 * 470296\n\ts6 += s16 * 654183\n\ts7 -= s16 * 997805\n\ts8 += s16 * 136657\n\ts9 -= s16 * 683901\n\n\ts3 += s15 * 666643\n\ts4 += s15 * 470296\n\ts5 += s15 * 654183\n\ts6 -= s15 * 997805\n\ts7 += s15 * 136657\n\ts8 -= s15 * 683901\n\n\ts2 += s14 * 666643\n\ts3 += s14 * 470296\n\ts4 += s14 * 654183\n\ts5 -= s14 * 997805\n\ts6 += s14 * 136657\n\ts7 -= s14 * 683901\n\n\ts1 += s13 * 666643\n\ts2 += s13 * 470296\n\ts3 += s13 * 654183\n\ts4 -= s13 * 997805\n\ts5 += s13 * 136657\n\ts6 -= s13 * 683901\n\n\ts0 += s12 * 666643\n\ts1 += s12 * 470296\n\ts2 += s12 * 654183\n\ts3 -= s12 * 997805\n\ts4 += s12 * 136657\n\ts5 -= s12 * 683901\n\ts12 = 0\n\n\tcarry0 = (s0 + (1 << 20)) >> 21\n\ts1 += carry0\n\ts0 -= carry0 << 21\n\tcarry2 = (s2 + (1 << 20)) >> 21\n\ts3 += carry2\n\ts2 -= carry2 << 21\n\tcarry4 = (s4 + (1 << 20)) >> 21\n\ts5 += carry4\n\ts4 -= carry4 << 21\n\tcarry6 = (s6 + (1 << 20)) >> 21\n\ts7 += carry6\n\ts6 -= carry6 << 21\n\tcarry8 = (s8 + (1 << 20)) >> 21\n\ts9 += carry8\n\ts8 -= carry8 << 21\n\tcarry10 = (s10 + (1 << 20)) >> 21\n\ts11 += carry10\n\ts10 -= carry10 << 21\n\n\tcarry1 = (s1 + (1 << 20)) >> 21\n\ts2 += carry1\n\ts1 -= carry1 << 21\n\tcarry3 = (s3 + (1 << 20)) >> 21\n\ts4 += carry3\n\ts3 -= carry3 << 21\n\tcarry5 = (s5 + (1 << 20)) >> 21\n\ts6 += carry5\n\ts5 -= carry5 << 21\n\tcarry7 = (s7 + (1 << 20)) >> 21\n\ts8 += carry7\n\ts7 -= carry7 << 21\n\tcarry9 = (s9 + (1 << 20)) >> 21\n\ts10 += carry9\n\ts9 -= carry9 << 21\n\tcarry11 = (s11 + (1 << 20)) >> 21\n\ts12 += carry11\n\ts11 -= carry11 << 21\n\n\ts0 += s12 * 666643\n\ts1 += s12 * 470296\n\ts2 += s12 * 654183\n\ts3 -= s12 * 997805\n\ts4 += s12 * 136657\n\ts5 -= s12 * 683901\n\ts12 = 0\n\n\tcarry0 = s0 >> 21\n\ts1 += carry0\n\ts0 -= carry0 << 21\n\tcarry1 = s1 >> 21\n\ts2 += carry1\n\ts1 -= carry1 << 21\n\tcarry2 = s2 >> 21\n\ts3 += carry2\n\ts2 -= carry2 << 21\n\tcarry3 = s3 >> 21\n\ts4 += carry3\n\ts3 -= carry3 << 21\n\tcarry4 = s4 >> 21\n\ts5 += carry4\n\ts4 -= carry4 << 21\n\tcarry5 = s5 >> 21\n\ts6 += carry5\n\ts5 -= carry5 << 21\n\tcarry6 = s6 >> 21\n\ts7 += carry6\n\ts6 -= carry6 << 21\n\tcarry7 = s7 >> 21\n\ts8 += carry7\n\ts7 -= carry7 << 21\n\tcarry8 = s8 >> 21\n\ts9 += carry8\n\ts8 -= carry8 << 21\n\tcarry9 = s9 >> 21\n\ts10 += carry9\n\ts9 -= carry9 << 21\n\tcarry10 = s10 >> 21\n\ts11 += carry10\n\ts10 -= carry10 << 21\n\tcarry11 = s11 >> 21\n\ts12 += carry11\n\ts11 -= carry11 << 21\n\n\ts0 += s12 * 666643\n\ts1 += s12 * 470296\n\ts2 += s12 * 654183\n\ts3 -= s12 * 997805\n\ts4 += s12 * 136657\n\ts5 -= s12 * 683901\n\n\tcarry0 = s0 >> 21\n\ts1 += carry0\n\ts0 -= carry0 << 21\n\tcarry1 = s1 >> 21\n\ts2 += carry1\n\ts1 -= carry1 << 21\n\tcarry2 = s2 >> 21\n\ts3 += carry2\n\ts2 -= carry2 << 21\n\tcarry3 = s3 >> 21\n\ts4 += carry3\n\ts3 -= carry3 << 21\n\tcarry4 = s4 >> 21\n\ts5 += carry4\n\ts4 -= carry4 << 21\n\tcarry5 = s5 >> 21\n\ts6 += carry5\n\ts5 -= carry5 << 21\n\tcarry6 = s6 >> 21\n\ts7 += carry6\n\ts6 -= carry6 << 21\n\tcarry7 = s7 >> 21\n\ts8 += carry7\n\ts7 -= carry7 << 21\n\tcarry8 = s8 >> 21\n\ts9 += carry8\n\ts8 -= carry8 << 21\n\tcarry9 = s9 >> 21\n\ts10 += carry9\n\ts9 -= carry9 << 21\n\tcarry10 = s10 >> 21\n\ts11 += carry10\n\ts10 -= carry10 << 21\n\n\tdst[0] = byte(s0 >> 0)\n\tdst[1] = byte(s0 >> 8)\n\tdst[2] = byte((s0 >> 16) | (s1 << 5))\n\tdst[3] = byte(s1 >> 3)\n\tdst[4] = byte(s1 >> 11)\n\tdst[5] = byte((s1 >> 19) | (s2 << 2))\n\tdst[6] = byte(s2 >> 6)\n\tdst[7] = byte((s2 >> 14) | (s3 << 7))\n\tdst[8] = byte(s3 >> 1)\n\tdst[9] = byte(s3 >> 9)\n\tdst[10] = byte((s3 >> 17) | (s4 << 4))\n\tdst[11] = byte(s4 >> 4)\n\tdst[12] = byte(s4 >> 12)\n\tdst[13] = byte((s4 >> 20) | (s5 << 1))\n\tdst[14] = byte(s5 >> 7)\n\tdst[15] = byte((s5 >> 15) | (s6 << 6))\n\tdst[16] = byte(s6 >> 2)\n\tdst[17] = byte(s6 >> 10)\n\tdst[18] = byte((s6 >> 18) | (s7 << 3))\n\tdst[19] = byte(s7 >> 5)\n\tdst[20] = byte(s7 >> 13)\n\tdst[21] = byte(s8 >> 0)\n\tdst[22] = byte(s8 >> 8)\n\tdst[23] = byte((s8 >> 16) | (s9 << 5))\n\tdst[24] = byte(s9 >> 3)\n\tdst[25] = byte(s9 >> 11)\n\tdst[26] = byte((s9 >> 19) | (s10 << 2))\n\tdst[27] = byte(s10 >> 6)\n\tdst[28] = byte((s10 >> 14) | (s11 << 7))\n\tdst[29] = byte(s11 >> 1)\n\tdst[30] = byte(s11 >> 9)\n\tdst[31] = byte(s11 >> 17)\n}", "func findPaths2(m int, n int, maxMove int, startRow int, startColumn int) int {\n\t// 값이 클 수 있어 modulo 모듈 값을 리턴하라고 문제에 써있음\n\tmodulo := 1000000000 + 7\n\tif startRow < 0 || startRow == m ||\n\t\tstartColumn < 0 || startColumn == n {\n\t\treturn 1\n\t}\n\tif maxMove == 0 {\n\t\treturn 0\n\t}\n\t// 4방향 각각에 대해서 boundary 를 벗어나는지 경우들을 모두 더한다.\n\treturn findPaths(m, n, maxMove-1, startRow-1, startColumn)%modulo +\n\t\tfindPaths(m, n, maxMove-1, startRow, startColumn-1)%modulo +\n\t\tfindPaths(m, n, maxMove-1, startRow+1, startColumn)%modulo +\n\t\tfindPaths(m, n, maxMove-1, startRow, startColumn+1)%modulo\n}", "func main() {\n\t// 2^qN is pi/2\n\tfor i := 0; i < 8; i++ {\n\t\tr := isin_S3(int32(i << (qN -1)))\n\t\tfmt.Printf(\"%d %x %f\\n\", 45 * i, r, float32(r) / float32(1 << qA))\n\t}\n}", "func hammingDistance(x int, y int) int {\n\n}", "func rowFromPosition(pos int) int {\n return pos / 8\n}", "func decodeExactCoverSolution(cs [][]int) string {\n\tb := make([]byte, len(cs))\n\tfor _, row := range cs {\n\t\tposition := row[0]\n\t\tvalue := row[1] % 9\n\t\tb[position] = byte(value) + '1'\n\t}\n\treturn string(b)\n}", "func p256OrdSqr(res, in []uint64, n int)", "func p256OrdSqr(res, in []uint64, n int)", "func shortestPathAllKeys(grid []string) int {\n \n}", "func expand(s string, i, j int) int {\n\n}", "func Changebytetoint(b []byte) (x int64) {\n\tfor i, val := range b {\n\t\tif i == 0 {\n\t\t\tx = x + int64(val)\n\t\t} else {\n\t\t\tx = x + int64(2<<7*int64(i)*int64(val))\n\t\t}\n\t}\n\treturn\n}", "func main() {\n\tt := time.Now()\n\ttetragrams := []string{\"𝌆\", \"𝌇\", \"𝌈\", \"𝌉\", \"𝌊\", \"𝌋\", \"𝌌\", \"𝌍\", \"𝌎\", \"𝌏\", \"𝌐\", \"𝌑\", \"𝌒\", \"𝌓\", \"𝌔\", \"𝌕\", \"𝌖\", \"𝌗\", \"𝌘\", \"𝌙\", \"𝌚\", \"𝌛\", \"𝌜\", \"𝌝\", \"𝌞\", \"𝌟\", \"𝌠\", \"𝌡\", \"𝌢\", \"𝌣\", \"𝌤\", \"𝌥\", \"𝌦\", \"𝌧\", \"𝌨\", \"𝌩\", \"𝌪\", \"𝌫\", \"𝌬\", \"𝌭\", \"𝌮\", \"𝌯\", \"𝌰\", \"𝌱\", \"𝌲\", \"𝌳\", \"𝌴\", \"𝌵\", \"𝌶\", \"𝌷\", \"𝌸\", \"𝌹\", \"𝌺\", \"𝌻\", \"𝌼\", \"𝌽\", \"𝌾\", \"𝌿\", \"𝍀\", \"𝍁\", \"𝍂\", \"𝍃\", \"𝍄\", \"𝍅\", \"𝍆\", \"𝍇\", \"𝍈\", \"𝍉\", \"𝍊\", \"𝍋\", \"𝍌\", \"𝍍\", \"𝍎\", \"𝍏\", \"𝍐\", \"𝍑\", \"𝍒\", \"𝍓\", \"𝍔\", \"𝍕\", \"𝍖\"}\n\n\t// choose random from [0,81)\n\trandInt, err := rand.Int(rand.Reader, big.NewInt(81))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// have to convert bigint back to int64 to use in index\n\ttetragram := tetragrams[randInt.Int64()]\n\ttetragram_int := randInt.Int64() + 1\n\t// now := t.Format(\"2006-01-02 15:04:05\")\n\tfmt.Printf(\"%d %s %s\\n\", tetragram_int, tetragram, t)\n}", "func pyramidScan(text string) (string) {\n\tvar result []byte\n var str = \"\";\n\tcount := 0;\n\tsize := 0;\n size = len(text)\n size = size - 1\n end := size + 1 \n\tfor i := 0; i <= size; i++ {\n\t// \tfor j := end; j >= 0; j-- {\n\t \tfor j := i; j <= end; j++ {\n // fmt.Println(x)\n \t// var bstr = \"testing\"\n \t// str = str[:len(str)-1]\n \t// bstr = str[1:3]\n \t// p(\"testing\", str, bstr)\n\t\t\tvar substring = text\n\t\t\ttotal := i + j\n \t\tif i != j {\n\t\t\tstr = substring[i:j]\n\t\t\tcount++\n\t\t\t// fmt.Println(\"Value of i,j is now:\", size, total, count, i, j, str)\n\t\t\tfmt.Println(\"Value of i,j is now:\", i, j, count, total, str)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn string(result) // f will be closed if we return here.\n}", "func main() {\n\tfor i := 1; i < 500; i++ {\n\n\t\tif i%7 == 0 && i%5 == 0 {\n\t\t\tfmt.Println(i)\n\n\t\t}\n\n\t}\n}", "func P011() int {\n\tvec := newVector()\n\tmax, sum := 0, 0\n\n\tfor j := 0; j < 20; j++ {\n\t\tfor i := 0; i < 20; i++ {\n\t\t\t//fmt.Println(vec[i][j])\n\t\t\tsum = 0\n\t\t\t/*\n\t\t\t * UP\n\t\t\t */\n\t\t\tif j > 2 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i][j-k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * Down\n\t\t\t */\n\t\t\tif j < 17 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i][j+k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * LEFT\n\t\t\t */\n\t\t\tif i > 2 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i-k][j]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * RIGHT\n\t\t\t */\n\t\t\tif i < 17 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i+k][j]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * UP LEFT\n\t\t\t */\n\t\t\tif j > 2 && i > 2 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i-k][j-k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * UP RIGHT\n\t\t\t */\n\t\t\tif j > 2 && i < 17 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i+k][j-k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * DOWN LEFT\n\t\t\t */\n\t\t\tif i > 2 && j < 17 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i-k][j+k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*\n\t\t\t * DOWN RIGHT\n\t\t\t */\n\t\t\tif i < 17 && j < 17 {\n\t\t\t\tpsum := 1\n\t\t\t\tfor k := 0; k < 4; k++ {\n\t\t\t\t\tpsum = psum * vec[i+k][j+k]\n\t\t\t\t}\n\t\t\t\tif psum > sum {\n\t\t\t\t\tsum = psum\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif sum > max {\n\t\t\t\tmax = sum\n\t\t\t}\n\t\t}\n\t}\n\treturn max\n}", "func formingMagicSquare(s [][]int32) int32 {\n\tsquares := genMagicSquares()\n\tminDist := int32(math.MaxInt32)\n\t// For each magic square\n\tfor _, square := range squares {\n\t\t// Try to adjust s so that it matches the magic square\n\t\td := editDistance(s, square, 0, 0)\n\t\tif d < minDist {\n\t\t\tminDist = d\n\t\t}\n\t}\n\n\treturn minDist\n}", "func (p *Poly) compress(d int) []byte {\n\tc := make([]byte, n*d/8)\n\tswitch d {\n\n\tcase 3:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<3)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 3) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<3) | byte(t[2]<<6)\n\t\t\tc[id+1] = byte(t[2]>>2) | byte(t[3]<<1) | byte(t[4]<<4) | byte(t[5]<<7)\n\t\t\tc[id+2] = byte(t[5]>>1) | byte(t[6]<<2) | byte(t[7]<<5)\n\t\t\tid += 3\n\t\t}\n\n\tcase 4:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<4)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 4) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<4)\n\t\t\tc[id+1] = byte(t[2]) | byte(t[3]<<4)\n\t\t\tc[id+2] = byte(t[4]) | byte(t[5]<<4)\n\t\t\tc[id+3] = byte(t[6]) | byte(t[7]<<4)\n\t\t\tid += 4\n\t\t}\n\n\tcase 5:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<5)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 5) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<5)\n\t\t\tc[id+1] = byte(t[1]>>3) | byte(t[2]<<2) | byte(t[3]<<7)\n\t\t\tc[id+2] = byte(t[3]>>1) | byte(t[4]<<4)\n\t\t\tc[id+3] = byte(t[4]>>4) | byte(t[5]<<1) | byte(t[6]<<6)\n\t\t\tc[id+4] = byte(t[6]>>2) | byte(t[7]<<3)\n\t\t\tid += 5\n\t\t}\n\n\tcase 6:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[4*i+j])<<6)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 6) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0]) | byte(t[1]<<6)\n\t\t\tc[id+1] = byte(t[1]>>2) | byte(t[2]<<4)\n\t\t\tc[id+2] = byte(t[2]>>2) | byte(t[3]<<2)\n\t\t\tid += 3\n\t\t}\n\n\tcase 10:\n\t\tvar t [4]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/4; i++ {\n\t\t\tfor j := 0; j < 4; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[4*i+j])<<10)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 10) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0])\n\t\t\tc[id+1] = byte(t[0]>>8) | byte(t[1]<<2)\n\t\t\tc[id+2] = byte(t[1]>>6) | byte(t[2]<<4)\n\t\t\tc[id+3] = byte(t[2]>>4) | byte(t[3]<<6)\n\t\t\tc[id+4] = byte(t[3] >> 2)\n\t\t\tid += 5\n\t\t}\n\tcase 11:\n\t\tvar t [8]uint16\n\t\tid := 0\n\t\tfor i := 0; i < n/8; i++ {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tt[j] = uint16(((uint32(p[8*i+j])<<11)+uint32(q)/2)/\n\t\t\t\t\tuint32(q)) & ((1 << 11) - 1)\n\t\t\t}\n\t\t\tc[id] = byte(t[0])\n\t\t\tc[id+1] = byte(t[0]>>8) | byte(t[1]<<3)\n\t\t\tc[id+2] = byte(t[1]>>5) | byte(t[2]<<6)\n\t\t\tc[id+3] = byte(t[2] >> 2)\n\t\t\tc[id+4] = byte(t[2]>>10) | byte(t[3]<<1)\n\t\t\tc[id+5] = byte(t[3]>>7) | byte(t[4]<<4)\n\t\t\tc[id+6] = byte(t[4]>>4) | byte(t[5]<<7)\n\t\t\tc[id+7] = byte(t[5] >> 1)\n\t\t\tc[id+8] = byte(t[5]>>9) | byte(t[6]<<2)\n\t\t\tc[id+9] = byte(t[6]>>6) | byte(t[7]<<5)\n\t\t\tc[id+10] = byte(t[7] >> 3)\n\t\t\tid += 11\n\t\t}\n\tdefault:\n\t\tpanic(\"bad d value\")\n\t}\n\treturn c[:]\n}", "func countingValleys(n int32, s string) int32 {\n\tstartAr := []int32{0}\n\tvar start int32\n\tvar valleyPoint int32 = 1\n\tfor _, elem := range s {\n\t\tchar := string(elem)\n\t\tcheckInt := true\n\t\tcheckInt = math.Signbit(float64(start))\n\t\tif char == \"D\" {\n\t\t\tstart = start - 1\n\t\t} else {\n\t\t\tstart = start + 1\n\t\t}\n\n\t\tif start == 0 {\n\t\t\tif checkInt == true {\n\t\t\t\tvalleyPoint = valleyPoint + 1\n\t\t\t}\n\t\t}\n\t\tstartAr = append(startAr, start)\n\t}\n\tfmt.Println(startAr)\n\tvalley := valleyPoint - 1\n\treturn valley\n}", "func threeWayZfunc(data LessSwap, lo, hi int) (midlo, midhi int) {\n\tm := int(uint(lo+hi) >> 1)\n\tif hi-lo > 40 {\n\t\ts := (hi - lo) / 8\n\t\tmedianOfThreeZfunc(data, lo, lo+s, lo+2*s)\n\t\tmedianOfThreeZfunc(data, m, m-s, m+s)\n\t\tmedianOfThreeZfunc(data, hi-1, hi-1-s, hi-1-2*s)\n\t}\n\tmedianOfThreeZfunc(data, lo, m, hi-1)\n\tpivot := lo\n\ta, c := lo+1, hi-1\n\tfor ; a < c && data.Less(a, pivot); a++ {\n\t}\n\tb := a\n\tfor {\n\t\tfor ; b < c && !data.Less(pivot, b); b++ {\n\t\t}\n\t\tfor ; b < c && data.Less(pivot, c-1); c-- {\n\t\t}\n\t\tif b >= c {\n\t\t\tbreak\n\t\t}\n\t\tdata.Swap(b, c-1)\n\t\tb++\n\t\tc--\n\t}\n\tprotect := hi-c < 5\n\tif !protect && hi-c < (hi-lo)/4 {\n\t\tdups := 0\n\t\tif !data.Less(pivot, hi-1) {\n\t\t\tdata.Swap(c, hi-1)\n\t\t\tc++\n\t\t\tdups++\n\t\t}\n\t\tif !data.Less(b-1, pivot) {\n\t\t\tb--\n\t\t\tdups++\n\t\t}\n\t\tif !data.Less(m, pivot) {\n\t\t\tdata.Swap(m, b-1)\n\t\t\tb--\n\t\t\tdups++\n\t\t}\n\t\tprotect = dups > 1\n\t}\n\tif protect {\n\t\tfor {\n\t\t\tfor ; a < b && !data.Less(b-1, pivot); b-- {\n\t\t\t}\n\t\t\tfor ; a < b && data.Less(a, pivot); a++ {\n\t\t\t}\n\t\t\tif a >= b {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdata.Swap(a, b-1)\n\t\t\ta++\n\t\t\tb--\n\t\t}\n\t}\n\tdata.Swap(pivot, b-1)\n\treturn b - 1, c\n}", "func minimumBribes(q []int32) {\n\tvar min int32\n\tminor := make([]int32, 0, len(q))\n\tfor i := 0; i < len(q); i++ {\n\t\toffset := q[i] - int32(i) - 1\n\t\tif offset > 2 {\n\t\t\tfmt.Println(\"Too chaotic\")\n\t\t\treturn\n\t\t} else if offset > 0 {\n\t\t\tmin += offset\n\t\t} else if offset <= 0 {\n\t\t\tminor = append(minor, q[i])\n\t\t\t/*\n\t\t\t\tfor j := i; j < len(q); j++ {\n\t\t\t\t\tif q[j] < q[i] {\n\t\t\t\t\t\tmin++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t*/\n\t\t}\n\t}\n\tvar curMax int32\n\tmax := make([]int32, len(minor))\n\tfor i := 0; i < len(minor); i++ {\n\t\tif minor[i] > curMax {\n\t\t\tmax[i] = minor[i]\n\t\t\tcurMax = minor[i]\n\t\t} else {\n\t\t\tmax[i] = curMax\n\n\t\t\tback := i - 1\n\t\t\tfor back >= 0 {\n\t\t\t\tif minor[i] < max[i] {\n\t\t\t\t\tif minor[i] < minor[back] {\n\t\t\t\t\t\tmin++\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tback--\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t\tfor i := len(q) - 1; i >= 0; i-- {\n\t\t\toffset := q[i] - int32(i) - 1\n\t\t\toffset1 := int32(i) + 1 - q[i]\n\t\t\tif offset > 2 {\n\t\t\t\tfmt.Println(\"Too chaotic\")\n\t\t\t\treturn\n\t\t\t} else if offset1 >= 0 {\n\t\t\t\tmin += offset1\n\t\t\t\tif offset1 == 0 {\n\t\t\t\t\tmin++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t*/\n\n\tfmt.Println(min)\n}", "func simplify(landmarks []image.Point) []image.Point {\n\tvar out []image.Point\n\n\tfor i := 0; i < 17; i++ {\n\t\tout = append(out, landmarks[i])\n\t}\n\n\tfor i := 26; i >= 17; i-- {\n\t\tout = append(out, moveUp(landmarks[8], landmarks[i]))\n\t}\n\n\treturn out\n}", "func GoldMinePath(arr [][]int) {\n\tdp := [][]int{}\n\tfor i := 0; i < len(arr); i++ {\n\t\ttemp := make([]int, len(arr[0]))\n\t\tdp = append(dp, temp)\n\t}\n\n\tfor col := len(dp[0]) - 1; col >= 0; col-- {\n\t\tfor row := 0; row < len(dp); row++ {\n\t\t\tif col == len(dp[0])-1 {\n\t\t\t\tdp[row][col] = arr[row][col]\n\t\t\t} else {\n\t\t\t\tcurrent := dp[row][col+1]\n\t\t\t\tif row-1 >= 0 && col+1 < len(dp[0]) {\n\t\t\t\t\tcurrent = maximum(current, dp[row-1][col+1])\n\t\t\t\t}\n\t\t\t\tif row+1 < len(dp) && col+1 < len(dp[0]) {\n\t\t\t\t\tcurrent = maximum(current, dp[row+1][col+1])\n\t\t\t\t}\n\t\t\t\tcurrent += arr[row][col]\n\t\t\t\tdp[row][col] = current\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Println(dp)\n\n}", "func main() {\n\ttotal := int64(0)\n\tvectors := ways(10, top, 3)\n\tfor _, vector := range vectors {\n\t\ttotal += distribute(vector)\n\t}\n\n\tfmt.Println(\"172/ How many 18-digit numbers n (without leading zeros) are there such that no digit occurs more than three times in n?\")\n\tfmt.Println(total)\n}", "func TopByGSM(F []int, c []int, n_gsm int) (float64){\n s, e := 0, 2*n_gsm\n \n sum_F := 0\n sum_c := 0\n for i := s; i<e; i++ {\n sum_F = sum_F + F[i]\n sum_c = sum_c + c[i]\n }\n\n //fmt.Println(\"Top GSM by Prop to Total Genome GSM: \", filename, n_gsm, s, e, sum_F, sum_c)\n \n r4 := float64(sum_c)/float64(sum_F)\n\n return r4\n}", "func icecreamParlor(m int32, arr []int32) []int32 {\n prev := map[int32]int{};\n for i, a := range arr {\n if prev[m-a] != 0 {\n return []int32{int32(prev[m-a]), int32(i+1)}\n }\n\n prev[a] = i+1\n }\n\n return []int32{}\n}", "func afficheDistancesHamming(distancesDeHamming DistancesHamming) {\n\tfmt.Print(\" | \")\n\n\tfor i := range distancesDeHamming {\n\t\tfmt.Printf(\"%d | \", i+1)\n\t}\n\n\tfmt.Println()\n\n\t// Matrice nbExemples x nbExemples contenatn les distances de hamming\n\t// Calcul et affichage de toutes les distances de Hamming\n\tfor i, row := range distancesDeHamming {\n\t\tfmt.Printf(\"%d |\", i+1)\n\n\t\tfor j, dist := range row {\n\t\t\tif i == j {\n\t\t\t\tfmt.Print(\" - |\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfmt.Printf(\" %d |\", dist-1)\n\t\t}\n\n\t\tfmt.Println()\n\t}\n\n\tfmt.Println()\n\tfmt.Println()\n}", "func sherlockAndAnagrams(s string) int32 {\n\t// Write your code here\n\tvar answer int32 = 0\n\n\t//increase of anagram elements size from 1 to exlusive len(s)\n\tfor anagramSize := 1; anagramSize < len(s); anagramSize++ {\n\n\t\t//Declare slice of maps of runes sets with counter of every rune inclusion\n\t\t//\n\t\t//Explanation: because we looks for unordered anagrams,\n\t\t//the best way to compare them is to count number of its runes.\n\t\t//\n\t\t//For ex.:\n\t\t// \"iffa\" = i:1,f:2,a:1\n\t\t// \"fifa\" =f:2,i:1,a:1 ==> map of iffa runes = map of fifa runes\n\t\t//\n\t\t//Because only same-sized anagrams can be matched, we should renew\n\t\t//slice on every step of anagram incrise\n\t\tanagram := []map[string]int{}\n\n\t\t//Iter over S with all-sized anagrams\n\n\t\tfor anagramPos := 0; anagramPos <= len(s)-anagramSize; anagramPos++ {\n\t\t\ttempMap := make(map[string]int)\n\n\t\t\t//Fill map with s[rune] = counter\n\t\t\tfor i := 0; i < anagramSize; i++ {\n\t\t\t\ttempMap[string(s[anagramPos+i])]++\n\n\t\t\t\t// fmt.Println(\"tempMap\", tempMap) //for debug\n\t\t\t}\n\n\t\t\t//Check is there equal maps in our slice\n\t\t\tfor _, m := range anagram {\n\n\t\t\t\tif reflect.DeepEqual(m, tempMap) {\n\t\t\t\t\tanswer++\n\n\t\t\t\t\t// fmt.Println(\"match found!\", answer) //for debug\n\t\t\t\t}\n\t\t\t}\n\t\t\tanagram = append(anagram, tempMap)\n\n\t\t\t// fmt.Println(\"map slice\", anagram) //for debug\n\t\t}\n\t}\n\n\treturn answer\n}", "func getSegmentNumber(i int) int {\n\tsegRow := int(i / 27)\n\tsegCol := int(i % 9 / 3)\n\treturn segRow * 3 + segCol\n}", "func spiralOrder(matrix [][]int) []int {\n\t//coord := [][]int{ {0, 1}, {1, 0}, {0, -1},{-1, 0}} // right down left up\n\tif len(matrix) == 0 {\n\t\treturn []int{}\n\t}\n\t//start:=[]int{0,0}\n\tres := []int{}\n\tresCount := 0\n\n\tn := len(matrix)\n\tm := len(matrix[0])\n\n\tuw := 0\n\trw := 0\n\tdw := 0\n\tlw := 0\n\n\tcurPosH := 0\n\tcurPosV := -1\n\n\tfor {\n\t\tfor i := 1; i <= m-rw-lw; i++ {\n\t\t\tcurPosV++\n\t\t\tmeta := matrix[curPosH][curPosV]\n\t\t\tres = append(res, meta)\n\t\t\tresCount++\n\t\t}\n\t\tuw += 1\n\t\tif resCount == m*n {\n\t\t\tbreak\n\t\t}\n\n\t\tfor i := 1; i <= n-uw-dw; i++ {\n\t\t\tcurPosH++\n\t\t\tmeta := matrix[curPosH][curPosV]\n\t\t\tres = append(res, meta)\n\t\t\tresCount++\n\t\t}\n\t\trw += 1\n\t\tif resCount == m*n {\n\t\t\tbreak\n\t\t}\n\n\t\tfor i := 1; i <= m-rw-lw; i++ {\n\t\t\tcurPosV--\n\t\t\tmeta := matrix[curPosH][curPosV]\n\t\t\tres = append(res, meta)\n\t\t\tresCount++\n\t\t}\n\t\tdw += 1\n\t\tif resCount == m*n {\n\t\t\tbreak\n\t\t}\n\n\t\tfor i := 1; i <= n-dw-uw; i++ {\n\t\t\tcurPosH--\n\t\t\tmeta := matrix[curPosH][curPosV]\n\t\t\tres = append(res, meta)\n\t\t\tresCount++\n\t\t}\n\t\tlw += 1\n\t\tif resCount == m*n {\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\treturn res\n}", "func splitmix64(key uint64) uint64 {\n\tkey = (key ^ (key >> 31) ^ (key >> 62)) * uint64(0x319642b2d24d8ec3)\n\tkey = (key ^ (key >> 27) ^ (key >> 54)) * uint64(0x96de1b173f119089)\n\tkey = key ^ (key >> 30) ^ (key >> 60)\n\treturn key\n}", "func main() {\n\tvar N int\n\tfmt.Scan(&N)\n\n\thorses := make([]int, N)\n\tfor i := 0; i < N; i++ {\n\t\tfmt.Scan(&(horses[i]))\n\t}\n\n\tsort.Ints(horses)\n\n\tminD := 10*1000*1000\n\tfor i := 0; i < N-1; i++ {\n\t\tif dist := horses[i+1]-horses[i]; dist < minD {\n\t\t\tminD = dist\n\t\t}\n\t}\n\t// fmt.Fprintln(os.Stderr, \"Debug messages...\")\n\tfmt.Println(minD)// Write answer to stdout\n}", "func expandRanges(rs []int32) []int32 {\n\tret := map[int32]bool{}\n\tfor i, s := range rs {\n\t\tif i%2 == 1 {\n\t\t\tcontinue\n\t\t}\n\t\tfor c := s; rs[i+1] >= c; c++ {\n\t\t\tret[c] = true\n\t\t}\n\t}\n\tout := make([]int32, 0, len(ret))\n\tfor c := range ret {\n\t\tout = append(out, c)\n\t}\n\tsort.Slice(out, func(i, j int) bool {\n\t\treturn out[i] < out[j]\n\t})\n\treturn out\n}", "func bgmlogsdist(a, b bgmcommon.Hash) int {\n\tlz := 0\n\tfor i := range a {\n\t\tx := a[i] ^ b[i]\n\t\tif x == 0 {\n\t\t\tlz += 8\n\t\t} else {\n\t\t\tlz += lzcount[x]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn len(a)*8 - lz\n}", "func main() {\n\ts := bufio.NewScanner(os.Stdin)\n\tn := 0\n\tm := 0\n\tfor s.Scan() {\n\t\tfields := strings.Fields(s.Text())\n\t\tbounds := strings.SplitN(fields[0], \"-\", 2)\n\t\tminCt, _ := strconv.Atoi(bounds[0])\n\t\tmaxCt, _ := strconv.Atoi(bounds[1])\n\t\tchr := strings.TrimSuffix(fields[1], \":\")\n\t\tpass := fields[2]\n\n\t\tct := strings.Count(pass, chr)\n\t\tif ct >= minCt && ct <= maxCt {\n\t\t\tfmt.Println(s.Text())\n\t\t\tn++\n\t\t}\n\n\t\t// fmt.Println(minCt, maxCt, chr)\n\t\t// fmt.Println(pass)\n\t\t// for i := 0; i < (minCt - 1); i++ {\n\t\t// \tfmt.Print(\" \")\n\t\t// }\n\t\t// fmt.Print(chr)\n\t\t// for i := 0; i < (maxCt - minCt); i++ {\n\t\t// \tfmt.Print(\" \")\n\t\t// }\n\t\t// fmt.Println(chr)\n\t\tmatches := 0\n\t\tif pass[minCt-1] == chr[0] {\n\t\t\tmatches++\n\t\t}\n\t\tif pass[maxCt-1] == chr[0] {\n\t\t\tmatches++\n\t\t}\n\t\tm += matches % 2\n\t}\n\tfmt.Println(n, m)\n}", "func split(sum int) (x, y int) {\n\tx = sum * 4 / 9\n\ty = sum - x\n\t//naked return statement\n\treturn\n}", "func findAnagrams(s string, p string) []int {\n\tls := len(s)\n\tlp := len(p)\n\tms := [26]int{}\n\tmp := [26]int{}\n\tres := []int{}\n\tfor _, v := range p {\n\t\tmp[v-'a'] += 1\n\t}\n\tfor i := 0; i < ls; i++ {\n\t\tif i >= lp {\n\t\t\tms[s[i-lp]-'a'] -= 1\n\t\t}\n\t\tms[s[i]-'a']+=1\n\t\tif ms == mp {\n\t\t\tres = append(res, i-lp+1)\n\t\t}\n\t}\n\treturn res\n}", "func main() {\n\tx := []int{42, 43, 44, 45, 46, 47, 48, 49, 50, 51}\n\n\tfirst_sl := x[0:5]\n\tsecond_sl := x[5:]\n\tthird_sl := x[2:7]\n\tfourth_sl := x[1:6]\n\n\tfmt.Println(first_sl)\n\tfmt.Println(second_sl)\n\tfmt.Println(third_sl)\n\tfmt.Println(fourth_sl)\n\n}", "func kerDIT8(a []fr.Element, twiddles [][]fr.Element, stage int) {\n\n\tfr.Butterfly(&a[0], &a[1])\n\tfr.Butterfly(&a[2], &a[3])\n\tfr.Butterfly(&a[4], &a[5])\n\tfr.Butterfly(&a[6], &a[7])\n\tfr.Butterfly(&a[0], &a[2])\n\ta[3].Mul(&a[3], &twiddles[stage+1][1])\n\tfr.Butterfly(&a[1], &a[3])\n\tfr.Butterfly(&a[4], &a[6])\n\ta[7].Mul(&a[7], &twiddles[stage+1][1])\n\tfr.Butterfly(&a[5], &a[7])\n\tfr.Butterfly(&a[0], &a[4])\n\ta[5].Mul(&a[5], &twiddles[stage+0][1])\n\tfr.Butterfly(&a[1], &a[5])\n\ta[6].Mul(&a[6], &twiddles[stage+0][2])\n\tfr.Butterfly(&a[2], &a[6])\n\ta[7].Mul(&a[7], &twiddles[stage+0][3])\n\tfr.Butterfly(&a[3], &a[7])\n}", "func encodeZigZag(i int64) uint32 {\n\treturn uint32((i << 1) ^ (i >> 31))\n}", "func solve(board [][]byte) {\n \n}", "func Encode(x, y int32) int64 {\n\tvar rx, ry int32\n\tvar d int64\n\tfor s := int32(n / 2); s > 0; s /= 2 {\n\t\trx = boolToInt(x&s > 0)\n\t\try = boolToInt(y&s > 0)\n\t\td += int64(int64(s) * int64(s) * int64(((3 * rx) ^ ry)))\n\t\trotate(s, rx, ry, &x, &y)\n\t}\n\n\treturn d\n}", "func run(input string) (interface{}, interface{}) {\n\thexaPositions := parse(input)\n\n\t// part 1\n\tm := twod.Map{}\n\tfor _, p := range hexaPositions {\n\t\tflip(m, p)\n\t}\n\tpart1 := len(m)\n\n\t// part 2\n\tfor i := 0; i < 100; i++ {\n\t\tblackCounts := make(twod.Map)\n\t\tfor pos := range m {\n\t\t\tfor _, dir := range hexaDirs {\n\t\t\t\t_, exist := blackCounts[pos+dir]\n\t\t\t\tif !exist {\n\t\t\t\t\tblackCounts[pos+dir] = 0\n\t\t\t\t}\n\t\t\t\tblackCounts[pos+dir] = blackCounts[pos+dir].(int) + 1\n\t\t\t}\n\t\t}\n\t\tnewM := make(twod.Map)\n\t\tfor pos := range m {\n\t\t\tcount, exist := blackCounts[pos]\n\t\t\tif !exist || count.(int) > 2 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnewM[pos] = '#'\n\t\t}\n\t\tfor pos, count := range blackCounts {\n\t\t\t_, exist := m[pos]\n\t\t\tif !exist && count == 2 {\n\t\t\t\tnewM[pos] = '#'\n\t\t\t}\n\t\t}\n\t\tm = newM\n\t}\n\tpart2 := len(m)\n\n\treturn part1, part2\n}", "func Sum(out *[16]byte, m []byte, key *[32]byte) {\n\tr := key\n\ts := key[16:]\n\tvar (\n\t\ty7 float64\n\t\ty6 float64\n\t\ty1 float64\n\t\ty0 float64\n\t\ty5 float64\n\t\ty4 float64\n\t\tx7 float64\n\t\tx6 float64\n\t\tx1 float64\n\t\tx0 float64\n\t\ty3 float64\n\t\ty2 float64\n\t\tx5 float64\n\t\tr3lowx0 float64\n\t\tx4 float64\n\t\tr0lowx6 float64\n\t\tx3 float64\n\t\tr3highx0 float64\n\t\tx2 float64\n\t\tr0highx6 float64\n\t\tr0lowx0 float64\n\t\tsr1lowx6 float64\n\t\tr0highx0 float64\n\t\tsr1highx6 float64\n\t\tsr3low float64\n\t\tr1lowx0 float64\n\t\tsr2lowx6 float64\n\t\tr1highx0 float64\n\t\tsr2highx6 float64\n\t\tr2lowx0 float64\n\t\tsr3lowx6 float64\n\t\tr2highx0 float64\n\t\tsr3highx6 float64\n\t\tr1highx4 float64\n\t\tr1lowx4 float64\n\t\tr0highx4 float64\n\t\tr0lowx4 float64\n\t\tsr3highx4 float64\n\t\tsr3lowx4 float64\n\t\tsr2highx4 float64\n\t\tsr2lowx4 float64\n\t\tr0lowx2 float64\n\t\tr0highx2 float64\n\t\tr1lowx2 float64\n\t\tr1highx2 float64\n\t\tr2lowx2 float64\n\t\tr2highx2 float64\n\t\tsr3lowx2 float64\n\t\tsr3highx2 float64\n\t\tz0 float64\n\t\tz1 float64\n\t\tz2 float64\n\t\tz3 float64\n\t\tm0 int64\n\t\tm1 int64\n\t\tm2 int64\n\t\tm3 int64\n\t\tm00 uint32\n\t\tm01 uint32\n\t\tm02 uint32\n\t\tm03 uint32\n\t\tm10 uint32\n\t\tm11 uint32\n\t\tm12 uint32\n\t\tm13 uint32\n\t\tm20 uint32\n\t\tm21 uint32\n\t\tm22 uint32\n\t\tm23 uint32\n\t\tm30 uint32\n\t\tm31 uint32\n\t\tm32 uint32\n\t\tm33 uint64\n\t\tlbelow2 int32\n\t\tlbelow3 int32\n\t\tlbelow4 int32\n\t\tlbelow5 int32\n\t\tlbelow6 int32\n\t\tlbelow7 int32\n\t\tlbelow8 int32\n\t\tlbelow9 int32\n\t\tlbelow10 int32\n\t\tlbelow11 int32\n\t\tlbelow12 int32\n\t\tlbelow13 int32\n\t\tlbelow14 int32\n\t\tlbelow15 int32\n\t\ts00 uint32\n\t\ts01 uint32\n\t\ts02 uint32\n\t\ts03 uint32\n\t\ts10 uint32\n\t\ts11 uint32\n\t\ts12 uint32\n\t\ts13 uint32\n\t\ts20 uint32\n\t\ts21 uint32\n\t\ts22 uint32\n\t\ts23 uint32\n\t\ts30 uint32\n\t\ts31 uint32\n\t\ts32 uint32\n\t\ts33 uint32\n\t\tbits32 uint64\n\t\tf uint64\n\t\tf0 uint64\n\t\tf1 uint64\n\t\tf2 uint64\n\t\tf3 uint64\n\t\tf4 uint64\n\t\tg uint64\n\t\tg0 uint64\n\t\tg1 uint64\n\t\tg2 uint64\n\t\tg3 uint64\n\t\tg4 uint64\n\t)\n\n\tvar p int32\n\n\tl := int32(len(m))\n\n\tr00 := uint32(r[0])\n\n\tr01 := uint32(r[1])\n\n\tr02 := uint32(r[2])\n\tr0 := int64(2151)\n\n\tr03 := uint32(r[3])\n\tr03 &= 15\n\tr0 <<= 51\n\n\tr10 := uint32(r[4])\n\tr10 &= 252\n\tr01 <<= 8\n\tr0 += int64(r00)\n\n\tr11 := uint32(r[5])\n\tr02 <<= 16\n\tr0 += int64(r01)\n\n\tr12 := uint32(r[6])\n\tr03 <<= 24\n\tr0 += int64(r02)\n\n\tr13 := uint32(r[7])\n\tr13 &= 15\n\tr1 := int64(2215)\n\tr0 += int64(r03)\n\n\td0 := r0\n\tr1 <<= 51\n\tr2 := int64(2279)\n\n\tr20 := uint32(r[8])\n\tr20 &= 252\n\tr11 <<= 8\n\tr1 += int64(r10)\n\n\tr21 := uint32(r[9])\n\tr12 <<= 16\n\tr1 += int64(r11)\n\n\tr22 := uint32(r[10])\n\tr13 <<= 24\n\tr1 += int64(r12)\n\n\tr23 := uint32(r[11])\n\tr23 &= 15\n\tr2 <<= 51\n\tr1 += int64(r13)\n\n\td1 := r1\n\tr21 <<= 8\n\tr2 += int64(r20)\n\n\tr30 := uint32(r[12])\n\tr30 &= 252\n\tr22 <<= 16\n\tr2 += int64(r21)\n\n\tr31 := uint32(r[13])\n\tr23 <<= 24\n\tr2 += int64(r22)\n\n\tr32 := uint32(r[14])\n\tr2 += int64(r23)\n\tr3 := int64(2343)\n\n\td2 := r2\n\tr3 <<= 51\n\n\tr33 := uint32(r[15])\n\tr33 &= 15\n\tr31 <<= 8\n\tr3 += int64(r30)\n\n\tr32 <<= 16\n\tr3 += int64(r31)\n\n\tr33 <<= 24\n\tr3 += int64(r32)\n\n\tr3 += int64(r33)\n\th0 := alpha32 - alpha32\n\n\td3 := r3\n\th1 := alpha32 - alpha32\n\n\th2 := alpha32 - alpha32\n\n\th3 := alpha32 - alpha32\n\n\th4 := alpha32 - alpha32\n\n\tr0low := math.Float64frombits(uint64(d0))\n\th5 := alpha32 - alpha32\n\n\tr1low := math.Float64frombits(uint64(d1))\n\th6 := alpha32 - alpha32\n\n\tr2low := math.Float64frombits(uint64(d2))\n\th7 := alpha32 - alpha32\n\n\tr0low -= alpha0\n\n\tr1low -= alpha32\n\n\tr2low -= alpha64\n\n\tr0high := r0low + alpha18\n\n\tr3low := math.Float64frombits(uint64(d3))\n\n\tr1high := r1low + alpha50\n\tsr1low := scale * r1low\n\n\tr2high := r2low + alpha82\n\tsr2low := scale * r2low\n\n\tr0high -= alpha18\n\tr0high_stack := r0high\n\n\tr3low -= alpha96\n\n\tr1high -= alpha50\n\tr1high_stack := r1high\n\n\tsr1high := sr1low + alpham80\n\n\tr0low -= r0high\n\n\tr2high -= alpha82\n\tsr3low = scale * r3low\n\n\tsr2high := sr2low + alpham48\n\n\tr1low -= r1high\n\tr1low_stack := r1low\n\n\tsr1high -= alpham80\n\tsr1high_stack := sr1high\n\n\tr2low -= r2high\n\tr2low_stack := r2low\n\n\tsr2high -= alpham48\n\tsr2high_stack := sr2high\n\n\tr3high := r3low + alpha112\n\tr0low_stack := r0low\n\n\tsr1low -= sr1high\n\tsr1low_stack := sr1low\n\n\tsr3high := sr3low + alpham16\n\tr2high_stack := r2high\n\n\tsr2low -= sr2high\n\tsr2low_stack := sr2low\n\n\tr3high -= alpha112\n\tr3high_stack := r3high\n\n\tsr3high -= alpham16\n\tsr3high_stack := sr3high\n\n\tr3low -= r3high\n\tr3low_stack := r3low\n\n\tsr3low -= sr3high\n\tsr3low_stack := sr3low\n\n\tif l < 16 {\n\t\tgoto addatmost15bytes\n\t}\n\n\tm00 = uint32(m[p+0])\n\tm0 = 2151\n\n\tm0 <<= 51\n\tm1 = 2215\n\tm01 = uint32(m[p+1])\n\n\tm1 <<= 51\n\tm2 = 2279\n\tm02 = uint32(m[p+2])\n\n\tm2 <<= 51\n\tm3 = 2343\n\tm03 = uint32(m[p+3])\n\n\tm10 = uint32(m[p+4])\n\tm01 <<= 8\n\tm0 += int64(m00)\n\n\tm11 = uint32(m[p+5])\n\tm02 <<= 16\n\tm0 += int64(m01)\n\n\tm12 = uint32(m[p+6])\n\tm03 <<= 24\n\tm0 += int64(m02)\n\n\tm13 = uint32(m[p+7])\n\tm3 <<= 51\n\tm0 += int64(m03)\n\n\tm20 = uint32(m[p+8])\n\tm11 <<= 8\n\tm1 += int64(m10)\n\n\tm21 = uint32(m[p+9])\n\tm12 <<= 16\n\tm1 += int64(m11)\n\n\tm22 = uint32(m[p+10])\n\tm13 <<= 24\n\tm1 += int64(m12)\n\n\tm23 = uint32(m[p+11])\n\tm1 += int64(m13)\n\n\tm30 = uint32(m[p+12])\n\tm21 <<= 8\n\tm2 += int64(m20)\n\n\tm31 = uint32(m[p+13])\n\tm22 <<= 16\n\tm2 += int64(m21)\n\n\tm32 = uint32(m[p+14])\n\tm23 <<= 24\n\tm2 += int64(m22)\n\n\tm33 = uint64(m[p+15])\n\tm2 += int64(m23)\n\n\td0 = m0\n\tm31 <<= 8\n\tm3 += int64(m30)\n\n\td1 = m1\n\tm32 <<= 16\n\tm3 += int64(m31)\n\n\td2 = m2\n\tm33 += 256\n\n\tm33 <<= 24\n\tm3 += int64(m32)\n\n\tm3 += int64(m33)\n\td3 = m3\n\n\tp += 16\n\tl -= 16\n\n\tz0 = math.Float64frombits(uint64(d0))\n\n\tz1 = math.Float64frombits(uint64(d1))\n\n\tz2 = math.Float64frombits(uint64(d2))\n\n\tz3 = math.Float64frombits(uint64(d3))\n\n\tz0 -= alpha0\n\n\tz1 -= alpha32\n\n\tz2 -= alpha64\n\n\tz3 -= alpha96\n\n\th0 += z0\n\n\th1 += z1\n\n\th3 += z2\n\n\th5 += z3\n\n\tif l < 16 {\n\t\tgoto multiplyaddatmost15bytes\n\t}\n\nmultiplyaddatleast16bytes:\n\n\tm2 = 2279\n\tm20 = uint32(m[p+8])\n\ty7 = h7 + alpha130\n\n\tm2 <<= 51\n\tm3 = 2343\n\tm21 = uint32(m[p+9])\n\ty6 = h6 + alpha130\n\n\tm3 <<= 51\n\tm0 = 2151\n\tm22 = uint32(m[p+10])\n\ty1 = h1 + alpha32\n\n\tm0 <<= 51\n\tm1 = 2215\n\tm23 = uint32(m[p+11])\n\ty0 = h0 + alpha32\n\n\tm1 <<= 51\n\tm30 = uint32(m[p+12])\n\ty7 -= alpha130\n\n\tm21 <<= 8\n\tm2 += int64(m20)\n\tm31 = uint32(m[p+13])\n\ty6 -= alpha130\n\n\tm22 <<= 16\n\tm2 += int64(m21)\n\tm32 = uint32(m[p+14])\n\ty1 -= alpha32\n\n\tm23 <<= 24\n\tm2 += int64(m22)\n\tm33 = uint64(m[p+15])\n\ty0 -= alpha32\n\n\tm2 += int64(m23)\n\tm00 = uint32(m[p+0])\n\ty5 = h5 + alpha96\n\n\tm31 <<= 8\n\tm3 += int64(m30)\n\tm01 = uint32(m[p+1])\n\ty4 = h4 + alpha96\n\n\tm32 <<= 16\n\tm02 = uint32(m[p+2])\n\tx7 = h7 - y7\n\ty7 *= scale\n\n\tm33 += 256\n\tm03 = uint32(m[p+3])\n\tx6 = h6 - y6\n\ty6 *= scale\n\n\tm33 <<= 24\n\tm3 += int64(m31)\n\tm10 = uint32(m[p+4])\n\tx1 = h1 - y1\n\n\tm01 <<= 8\n\tm3 += int64(m32)\n\tm11 = uint32(m[p+5])\n\tx0 = h0 - y0\n\n\tm3 += int64(m33)\n\tm0 += int64(m00)\n\tm12 = uint32(m[p+6])\n\ty5 -= alpha96\n\n\tm02 <<= 16\n\tm0 += int64(m01)\n\tm13 = uint32(m[p+7])\n\ty4 -= alpha96\n\n\tm03 <<= 24\n\tm0 += int64(m02)\n\td2 = m2\n\tx1 += y7\n\n\tm0 += int64(m03)\n\td3 = m3\n\tx0 += y6\n\n\tm11 <<= 8\n\tm1 += int64(m10)\n\td0 = m0\n\tx7 += y5\n\n\tm12 <<= 16\n\tm1 += int64(m11)\n\tx6 += y4\n\n\tm13 <<= 24\n\tm1 += int64(m12)\n\ty3 = h3 + alpha64\n\n\tm1 += int64(m13)\n\td1 = m1\n\ty2 = h2 + alpha64\n\n\tx0 += x1\n\n\tx6 += x7\n\n\ty3 -= alpha64\n\tr3low = r3low_stack\n\n\ty2 -= alpha64\n\tr0low = r0low_stack\n\n\tx5 = h5 - y5\n\tr3lowx0 = r3low * x0\n\tr3high = r3high_stack\n\n\tx4 = h4 - y4\n\tr0lowx6 = r0low * x6\n\tr0high = r0high_stack\n\n\tx3 = h3 - y3\n\tr3highx0 = r3high * x0\n\tsr1low = sr1low_stack\n\n\tx2 = h2 - y2\n\tr0highx6 = r0high * x6\n\tsr1high = sr1high_stack\n\n\tx5 += y3\n\tr0lowx0 = r0low * x0\n\tr1low = r1low_stack\n\n\th6 = r3lowx0 + r0lowx6\n\tsr1lowx6 = sr1low * x6\n\tr1high = r1high_stack\n\n\tx4 += y2\n\tr0highx0 = r0high * x0\n\tsr2low = sr2low_stack\n\n\th7 = r3highx0 + r0highx6\n\tsr1highx6 = sr1high * x6\n\tsr2high = sr2high_stack\n\n\tx3 += y1\n\tr1lowx0 = r1low * x0\n\tr2low = r2low_stack\n\n\th0 = r0lowx0 + sr1lowx6\n\tsr2lowx6 = sr2low * x6\n\tr2high = r2high_stack\n\n\tx2 += y0\n\tr1highx0 = r1high * x0\n\tsr3low = sr3low_stack\n\n\th1 = r0highx0 + sr1highx6\n\tsr2highx6 = sr2high * x6\n\tsr3high = sr3high_stack\n\n\tx4 += x5\n\tr2lowx0 = r2low * x0\n\tz2 = math.Float64frombits(uint64(d2))\n\n\th2 = r1lowx0 + sr2lowx6\n\tsr3lowx6 = sr3low * x6\n\n\tx2 += x3\n\tr2highx0 = r2high * x0\n\tz3 = math.Float64frombits(uint64(d3))\n\n\th3 = r1highx0 + sr2highx6\n\tsr3highx6 = sr3high * x6\n\n\tr1highx4 = r1high * x4\n\tz2 -= alpha64\n\n\th4 = r2lowx0 + sr3lowx6\n\tr1lowx4 = r1low * x4\n\n\tr0highx4 = r0high * x4\n\tz3 -= alpha96\n\n\th5 = r2highx0 + sr3highx6\n\tr0lowx4 = r0low * x4\n\n\th7 += r1highx4\n\tsr3highx4 = sr3high * x4\n\n\th6 += r1lowx4\n\tsr3lowx4 = sr3low * x4\n\n\th5 += r0highx4\n\tsr2highx4 = sr2high * x4\n\n\th4 += r0lowx4\n\tsr2lowx4 = sr2low * x4\n\n\th3 += sr3highx4\n\tr0lowx2 = r0low * x2\n\n\th2 += sr3lowx4\n\tr0highx2 = r0high * x2\n\n\th1 += sr2highx4\n\tr1lowx2 = r1low * x2\n\n\th0 += sr2lowx4\n\tr1highx2 = r1high * x2\n\n\th2 += r0lowx2\n\tr2lowx2 = r2low * x2\n\n\th3 += r0highx2\n\tr2highx2 = r2high * x2\n\n\th4 += r1lowx2\n\tsr3lowx2 = sr3low * x2\n\n\th5 += r1highx2\n\tsr3highx2 = sr3high * x2\n\n\tp += 16\n\tl -= 16\n\th6 += r2lowx2\n\n\th7 += r2highx2\n\n\tz1 = math.Float64frombits(uint64(d1))\n\th0 += sr3lowx2\n\n\tz0 = math.Float64frombits(uint64(d0))\n\th1 += sr3highx2\n\n\tz1 -= alpha32\n\n\tz0 -= alpha0\n\n\th5 += z3\n\n\th3 += z2\n\n\th1 += z1\n\n\th0 += z0\n\n\tif l >= 16 {\n\t\tgoto multiplyaddatleast16bytes\n\t}\n\nmultiplyaddatmost15bytes:\n\n\ty7 = h7 + alpha130\n\n\ty6 = h6 + alpha130\n\n\ty1 = h1 + alpha32\n\n\ty0 = h0 + alpha32\n\n\ty7 -= alpha130\n\n\ty6 -= alpha130\n\n\ty1 -= alpha32\n\n\ty0 -= alpha32\n\n\ty5 = h5 + alpha96\n\n\ty4 = h4 + alpha96\n\n\tx7 = h7 - y7\n\ty7 *= scale\n\n\tx6 = h6 - y6\n\ty6 *= scale\n\n\tx1 = h1 - y1\n\n\tx0 = h0 - y0\n\n\ty5 -= alpha96\n\n\ty4 -= alpha96\n\n\tx1 += y7\n\n\tx0 += y6\n\n\tx7 += y5\n\n\tx6 += y4\n\n\ty3 = h3 + alpha64\n\n\ty2 = h2 + alpha64\n\n\tx0 += x1\n\n\tx6 += x7\n\n\ty3 -= alpha64\n\tr3low = r3low_stack\n\n\ty2 -= alpha64\n\tr0low = r0low_stack\n\n\tx5 = h5 - y5\n\tr3lowx0 = r3low * x0\n\tr3high = r3high_stack\n\n\tx4 = h4 - y4\n\tr0lowx6 = r0low * x6\n\tr0high = r0high_stack\n\n\tx3 = h3 - y3\n\tr3highx0 = r3high * x0\n\tsr1low = sr1low_stack\n\n\tx2 = h2 - y2\n\tr0highx6 = r0high * x6\n\tsr1high = sr1high_stack\n\n\tx5 += y3\n\tr0lowx0 = r0low * x0\n\tr1low = r1low_stack\n\n\th6 = r3lowx0 + r0lowx6\n\tsr1lowx6 = sr1low * x6\n\tr1high = r1high_stack\n\n\tx4 += y2\n\tr0highx0 = r0high * x0\n\tsr2low = sr2low_stack\n\n\th7 = r3highx0 + r0highx6\n\tsr1highx6 = sr1high * x6\n\tsr2high = sr2high_stack\n\n\tx3 += y1\n\tr1lowx0 = r1low * x0\n\tr2low = r2low_stack\n\n\th0 = r0lowx0 + sr1lowx6\n\tsr2lowx6 = sr2low * x6\n\tr2high = r2high_stack\n\n\tx2 += y0\n\tr1highx0 = r1high * x0\n\tsr3low = sr3low_stack\n\n\th1 = r0highx0 + sr1highx6\n\tsr2highx6 = sr2high * x6\n\tsr3high = sr3high_stack\n\n\tx4 += x5\n\tr2lowx0 = r2low * x0\n\n\th2 = r1lowx0 + sr2lowx6\n\tsr3lowx6 = sr3low * x6\n\n\tx2 += x3\n\tr2highx0 = r2high * x0\n\n\th3 = r1highx0 + sr2highx6\n\tsr3highx6 = sr3high * x6\n\n\tr1highx4 = r1high * x4\n\n\th4 = r2lowx0 + sr3lowx6\n\tr1lowx4 = r1low * x4\n\n\tr0highx4 = r0high * x4\n\n\th5 = r2highx0 + sr3highx6\n\tr0lowx4 = r0low * x4\n\n\th7 += r1highx4\n\tsr3highx4 = sr3high * x4\n\n\th6 += r1lowx4\n\tsr3lowx4 = sr3low * x4\n\n\th5 += r0highx4\n\tsr2highx4 = sr2high * x4\n\n\th4 += r0lowx4\n\tsr2lowx4 = sr2low * x4\n\n\th3 += sr3highx4\n\tr0lowx2 = r0low * x2\n\n\th2 += sr3lowx4\n\tr0highx2 = r0high * x2\n\n\th1 += sr2highx4\n\tr1lowx2 = r1low * x2\n\n\th0 += sr2lowx4\n\tr1highx2 = r1high * x2\n\n\th2 += r0lowx2\n\tr2lowx2 = r2low * x2\n\n\th3 += r0highx2\n\tr2highx2 = r2high * x2\n\n\th4 += r1lowx2\n\tsr3lowx2 = sr3low * x2\n\n\th5 += r1highx2\n\tsr3highx2 = sr3high * x2\n\n\th6 += r2lowx2\n\n\th7 += r2highx2\n\n\th0 += sr3lowx2\n\n\th1 += sr3highx2\n\naddatmost15bytes:\n\n\tif l == 0 {\n\t\tgoto nomorebytes\n\t}\n\n\tlbelow2 = l - 2\n\n\tlbelow3 = l - 3\n\n\tlbelow2 >>= 31\n\tlbelow4 = l - 4\n\n\tm00 = uint32(m[p+0])\n\tlbelow3 >>= 31\n\tp += lbelow2\n\n\tm01 = uint32(m[p+1])\n\tlbelow4 >>= 31\n\tp += lbelow3\n\n\tm02 = uint32(m[p+2])\n\tp += lbelow4\n\tm0 = 2151\n\n\tm03 = uint32(m[p+3])\n\tm0 <<= 51\n\tm1 = 2215\n\n\tm0 += int64(m00)\n\tm01 &^= uint32(lbelow2)\n\n\tm02 &^= uint32(lbelow3)\n\tm01 -= uint32(lbelow2)\n\n\tm01 <<= 8\n\tm03 &^= uint32(lbelow4)\n\n\tm0 += int64(m01)\n\tlbelow2 -= lbelow3\n\n\tm02 += uint32(lbelow2)\n\tlbelow3 -= lbelow4\n\n\tm02 <<= 16\n\tm03 += uint32(lbelow3)\n\n\tm03 <<= 24\n\tm0 += int64(m02)\n\n\tm0 += int64(m03)\n\tlbelow5 = l - 5\n\n\tlbelow6 = l - 6\n\tlbelow7 = l - 7\n\n\tlbelow5 >>= 31\n\tlbelow8 = l - 8\n\n\tlbelow6 >>= 31\n\tp += lbelow5\n\n\tm10 = uint32(m[p+4])\n\tlbelow7 >>= 31\n\tp += lbelow6\n\n\tm11 = uint32(m[p+5])\n\tlbelow8 >>= 31\n\tp += lbelow7\n\n\tm12 = uint32(m[p+6])\n\tm1 <<= 51\n\tp += lbelow8\n\n\tm13 = uint32(m[p+7])\n\tm10 &^= uint32(lbelow5)\n\tlbelow4 -= lbelow5\n\n\tm10 += uint32(lbelow4)\n\tlbelow5 -= lbelow6\n\n\tm11 &^= uint32(lbelow6)\n\tm11 += uint32(lbelow5)\n\n\tm11 <<= 8\n\tm1 += int64(m10)\n\n\tm1 += int64(m11)\n\tm12 &^= uint32(lbelow7)\n\n\tlbelow6 -= lbelow7\n\tm13 &^= uint32(lbelow8)\n\n\tm12 += uint32(lbelow6)\n\tlbelow7 -= lbelow8\n\n\tm12 <<= 16\n\tm13 += uint32(lbelow7)\n\n\tm13 <<= 24\n\tm1 += int64(m12)\n\n\tm1 += int64(m13)\n\tm2 = 2279\n\n\tlbelow9 = l - 9\n\tm3 = 2343\n\n\tlbelow10 = l - 10\n\tlbelow11 = l - 11\n\n\tlbelow9 >>= 31\n\tlbelow12 = l - 12\n\n\tlbelow10 >>= 31\n\tp += lbelow9\n\n\tm20 = uint32(m[p+8])\n\tlbelow11 >>= 31\n\tp += lbelow10\n\n\tm21 = uint32(m[p+9])\n\tlbelow12 >>= 31\n\tp += lbelow11\n\n\tm22 = uint32(m[p+10])\n\tm2 <<= 51\n\tp += lbelow12\n\n\tm23 = uint32(m[p+11])\n\tm20 &^= uint32(lbelow9)\n\tlbelow8 -= lbelow9\n\n\tm20 += uint32(lbelow8)\n\tlbelow9 -= lbelow10\n\n\tm21 &^= uint32(lbelow10)\n\tm21 += uint32(lbelow9)\n\n\tm21 <<= 8\n\tm2 += int64(m20)\n\n\tm2 += int64(m21)\n\tm22 &^= uint32(lbelow11)\n\n\tlbelow10 -= lbelow11\n\tm23 &^= uint32(lbelow12)\n\n\tm22 += uint32(lbelow10)\n\tlbelow11 -= lbelow12\n\n\tm22 <<= 16\n\tm23 += uint32(lbelow11)\n\n\tm23 <<= 24\n\tm2 += int64(m22)\n\n\tm3 <<= 51\n\tlbelow13 = l - 13\n\n\tlbelow13 >>= 31\n\tlbelow14 = l - 14\n\n\tlbelow14 >>= 31\n\tp += lbelow13\n\tlbelow15 = l - 15\n\n\tm30 = uint32(m[p+12])\n\tlbelow15 >>= 31\n\tp += lbelow14\n\n\tm31 = uint32(m[p+13])\n\tp += lbelow15\n\tm2 += int64(m23)\n\n\tm32 = uint32(m[p+14])\n\tm30 &^= uint32(lbelow13)\n\tlbelow12 -= lbelow13\n\n\tm30 += uint32(lbelow12)\n\tlbelow13 -= lbelow14\n\n\tm3 += int64(m30)\n\tm31 &^= uint32(lbelow14)\n\n\tm31 += uint32(lbelow13)\n\tm32 &^= uint32(lbelow15)\n\n\tm31 <<= 8\n\tlbelow14 -= lbelow15\n\n\tm3 += int64(m31)\n\tm32 += uint32(lbelow14)\n\td0 = m0\n\n\tm32 <<= 16\n\tm33 = uint64(lbelow15 + 1)\n\td1 = m1\n\n\tm33 <<= 24\n\tm3 += int64(m32)\n\td2 = m2\n\n\tm3 += int64(m33)\n\td3 = m3\n\n\tz3 = math.Float64frombits(uint64(d3))\n\n\tz2 = math.Float64frombits(uint64(d2))\n\n\tz1 = math.Float64frombits(uint64(d1))\n\n\tz0 = math.Float64frombits(uint64(d0))\n\n\tz3 -= alpha96\n\n\tz2 -= alpha64\n\n\tz1 -= alpha32\n\n\tz0 -= alpha0\n\n\th5 += z3\n\n\th3 += z2\n\n\th1 += z1\n\n\th0 += z0\n\n\ty7 = h7 + alpha130\n\n\ty6 = h6 + alpha130\n\n\ty1 = h1 + alpha32\n\n\ty0 = h0 + alpha32\n\n\ty7 -= alpha130\n\n\ty6 -= alpha130\n\n\ty1 -= alpha32\n\n\ty0 -= alpha32\n\n\ty5 = h5 + alpha96\n\n\ty4 = h4 + alpha96\n\n\tx7 = h7 - y7\n\ty7 *= scale\n\n\tx6 = h6 - y6\n\ty6 *= scale\n\n\tx1 = h1 - y1\n\n\tx0 = h0 - y0\n\n\ty5 -= alpha96\n\n\ty4 -= alpha96\n\n\tx1 += y7\n\n\tx0 += y6\n\n\tx7 += y5\n\n\tx6 += y4\n\n\ty3 = h3 + alpha64\n\n\ty2 = h2 + alpha64\n\n\tx0 += x1\n\n\tx6 += x7\n\n\ty3 -= alpha64\n\tr3low = r3low_stack\n\n\ty2 -= alpha64\n\tr0low = r0low_stack\n\n\tx5 = h5 - y5\n\tr3lowx0 = r3low * x0\n\tr3high = r3high_stack\n\n\tx4 = h4 - y4\n\tr0lowx6 = r0low * x6\n\tr0high = r0high_stack\n\n\tx3 = h3 - y3\n\tr3highx0 = r3high * x0\n\tsr1low = sr1low_stack\n\n\tx2 = h2 - y2\n\tr0highx6 = r0high * x6\n\tsr1high = sr1high_stack\n\n\tx5 += y3\n\tr0lowx0 = r0low * x0\n\tr1low = r1low_stack\n\n\th6 = r3lowx0 + r0lowx6\n\tsr1lowx6 = sr1low * x6\n\tr1high = r1high_stack\n\n\tx4 += y2\n\tr0highx0 = r0high * x0\n\tsr2low = sr2low_stack\n\n\th7 = r3highx0 + r0highx6\n\tsr1highx6 = sr1high * x6\n\tsr2high = sr2high_stack\n\n\tx3 += y1\n\tr1lowx0 = r1low * x0\n\tr2low = r2low_stack\n\n\th0 = r0lowx0 + sr1lowx6\n\tsr2lowx6 = sr2low * x6\n\tr2high = r2high_stack\n\n\tx2 += y0\n\tr1highx0 = r1high * x0\n\tsr3low = sr3low_stack\n\n\th1 = r0highx0 + sr1highx6\n\tsr2highx6 = sr2high * x6\n\tsr3high = sr3high_stack\n\n\tx4 += x5\n\tr2lowx0 = r2low * x0\n\n\th2 = r1lowx0 + sr2lowx6\n\tsr3lowx6 = sr3low * x6\n\n\tx2 += x3\n\tr2highx0 = r2high * x0\n\n\th3 = r1highx0 + sr2highx6\n\tsr3highx6 = sr3high * x6\n\n\tr1highx4 = r1high * x4\n\n\th4 = r2lowx0 + sr3lowx6\n\tr1lowx4 = r1low * x4\n\n\tr0highx4 = r0high * x4\n\n\th5 = r2highx0 + sr3highx6\n\tr0lowx4 = r0low * x4\n\n\th7 += r1highx4\n\tsr3highx4 = sr3high * x4\n\n\th6 += r1lowx4\n\tsr3lowx4 = sr3low * x4\n\n\th5 += r0highx4\n\tsr2highx4 = sr2high * x4\n\n\th4 += r0lowx4\n\tsr2lowx4 = sr2low * x4\n\n\th3 += sr3highx4\n\tr0lowx2 = r0low * x2\n\n\th2 += sr3lowx4\n\tr0highx2 = r0high * x2\n\n\th1 += sr2highx4\n\tr1lowx2 = r1low * x2\n\n\th0 += sr2lowx4\n\tr1highx2 = r1high * x2\n\n\th2 += r0lowx2\n\tr2lowx2 = r2low * x2\n\n\th3 += r0highx2\n\tr2highx2 = r2high * x2\n\n\th4 += r1lowx2\n\tsr3lowx2 = sr3low * x2\n\n\th5 += r1highx2\n\tsr3highx2 = sr3high * x2\n\n\th6 += r2lowx2\n\n\th7 += r2highx2\n\n\th0 += sr3lowx2\n\n\th1 += sr3highx2\n\nnomorebytes:\n\n\ty7 = h7 + alpha130\n\n\ty0 = h0 + alpha32\n\n\ty1 = h1 + alpha32\n\n\ty2 = h2 + alpha64\n\n\ty7 -= alpha130\n\n\ty3 = h3 + alpha64\n\n\ty4 = h4 + alpha96\n\n\ty5 = h5 + alpha96\n\n\tx7 = h7 - y7\n\ty7 *= scale\n\n\ty0 -= alpha32\n\n\ty1 -= alpha32\n\n\ty2 -= alpha64\n\n\th6 += x7\n\n\ty3 -= alpha64\n\n\ty4 -= alpha96\n\n\ty5 -= alpha96\n\n\ty6 = h6 + alpha130\n\n\tx0 = h0 - y0\n\n\tx1 = h1 - y1\n\n\tx2 = h2 - y2\n\n\ty6 -= alpha130\n\n\tx0 += y7\n\n\tx3 = h3 - y3\n\n\tx4 = h4 - y4\n\n\tx5 = h5 - y5\n\n\tx6 = h6 - y6\n\n\ty6 *= scale\n\n\tx2 += y0\n\n\tx3 += y1\n\n\tx4 += y2\n\n\tx0 += y6\n\n\tx5 += y3\n\n\tx6 += y4\n\n\tx2 += x3\n\n\tx0 += x1\n\n\tx4 += x5\n\n\tx6 += y5\n\n\tx2 += offset1\n\td1 = int64(math.Float64bits(x2))\n\n\tx0 += offset0\n\td0 = int64(math.Float64bits(x0))\n\n\tx4 += offset2\n\td2 = int64(math.Float64bits(x4))\n\n\tx6 += offset3\n\td3 = int64(math.Float64bits(x6))\n\n\tf0 = uint64(d0)\n\n\tf1 = uint64(d1)\n\tbits32 = math.MaxUint64\n\n\tf2 = uint64(d2)\n\tbits32 >>= 32\n\n\tf3 = uint64(d3)\n\tf = f0 >> 32\n\n\tf0 &= bits32\n\tf &= 255\n\n\tf1 += f\n\tg0 = f0 + 5\n\n\tg = g0 >> 32\n\tg0 &= bits32\n\n\tf = f1 >> 32\n\tf1 &= bits32\n\n\tf &= 255\n\tg1 = f1 + g\n\n\tg = g1 >> 32\n\tf2 += f\n\n\tf = f2 >> 32\n\tg1 &= bits32\n\n\tf2 &= bits32\n\tf &= 255\n\n\tf3 += f\n\tg2 = f2 + g\n\n\tg = g2 >> 32\n\tg2 &= bits32\n\n\tf4 = f3 >> 32\n\tf3 &= bits32\n\n\tf4 &= 255\n\tg3 = f3 + g\n\n\tg = g3 >> 32\n\tg3 &= bits32\n\n\tg4 = f4 + g\n\n\tg4 = g4 - 4\n\ts00 = uint32(s[0])\n\n\tf = uint64(int64(g4) >> 63)\n\ts01 = uint32(s[1])\n\n\tf0 &= f\n\tg0 &^= f\n\ts02 = uint32(s[2])\n\n\tf1 &= f\n\tf0 |= g0\n\ts03 = uint32(s[3])\n\n\tg1 &^= f\n\tf2 &= f\n\ts10 = uint32(s[4])\n\n\tf3 &= f\n\tg2 &^= f\n\ts11 = uint32(s[5])\n\n\tg3 &^= f\n\tf1 |= g1\n\ts12 = uint32(s[6])\n\n\tf2 |= g2\n\tf3 |= g3\n\ts13 = uint32(s[7])\n\n\ts01 <<= 8\n\tf0 += uint64(s00)\n\ts20 = uint32(s[8])\n\n\ts02 <<= 16\n\tf0 += uint64(s01)\n\ts21 = uint32(s[9])\n\n\ts03 <<= 24\n\tf0 += uint64(s02)\n\ts22 = uint32(s[10])\n\n\ts11 <<= 8\n\tf1 += uint64(s10)\n\ts23 = uint32(s[11])\n\n\ts12 <<= 16\n\tf1 += uint64(s11)\n\ts30 = uint32(s[12])\n\n\ts13 <<= 24\n\tf1 += uint64(s12)\n\ts31 = uint32(s[13])\n\n\tf0 += uint64(s03)\n\tf1 += uint64(s13)\n\ts32 = uint32(s[14])\n\n\ts21 <<= 8\n\tf2 += uint64(s20)\n\ts33 = uint32(s[15])\n\n\ts22 <<= 16\n\tf2 += uint64(s21)\n\n\ts23 <<= 24\n\tf2 += uint64(s22)\n\n\ts31 <<= 8\n\tf3 += uint64(s30)\n\n\ts32 <<= 16\n\tf3 += uint64(s31)\n\n\ts33 <<= 24\n\tf3 += uint64(s32)\n\n\tf2 += uint64(s23)\n\tf3 += uint64(s33)\n\n\tout[0] = byte(f0)\n\tf0 >>= 8\n\tout[1] = byte(f0)\n\tf0 >>= 8\n\tout[2] = byte(f0)\n\tf0 >>= 8\n\tout[3] = byte(f0)\n\tf0 >>= 8\n\tf1 += f0\n\n\tout[4] = byte(f1)\n\tf1 >>= 8\n\tout[5] = byte(f1)\n\tf1 >>= 8\n\tout[6] = byte(f1)\n\tf1 >>= 8\n\tout[7] = byte(f1)\n\tf1 >>= 8\n\tf2 += f1\n\n\tout[8] = byte(f2)\n\tf2 >>= 8\n\tout[9] = byte(f2)\n\tf2 >>= 8\n\tout[10] = byte(f2)\n\tf2 >>= 8\n\tout[11] = byte(f2)\n\tf2 >>= 8\n\tf3 += f2\n\n\tout[12] = byte(f3)\n\tf3 >>= 8\n\tout[13] = byte(f3)\n\tf3 >>= 8\n\tout[14] = byte(f3)\n\tf3 >>= 8\n\tout[15] = byte(f3)\n}", "func anticlockwiseTurn90Degree(slice [][]string) [][]string {\n return reverse(transpose(slice))\n}", "func binary(x int64, arr []int64) {\n\t// fmt.Printf(\"Looking for %v in %v \\n\", x, arr)\n\tlbound := 0\n\trbound := len(arr)\n\ti, max := 0, 10\n\tmid := (rbound - lbound) / 2\n\tvar steps []string\n\tfor i < max {\n\t\t// fmt.Printf(\"mid: %v, lbound : %v, rbound : %v\\n\", mid, lbound, rbound)\n\t\tsteps = append(steps, strconv.Itoa(mid))\n\t\tif x == arr[mid] {\n\t\t\tbreak\n\t\t}\n\t\tif x > arr[mid] {\n\t\t\t// fmt.Printf(\"lbound %v=>%v\\n\", lbound, mid)\n\t\t\tlbound = mid\n\t\t\tmid = lbound + (rbound-lbound)/2\n\t\t} else {\n\t\t\t// fmt.Printf(\"rbound %v=>%v\\n\", rbound, mid)\n\t\t\trbound = mid\n\t\t\tmid = rbound - (rbound-lbound)/2\n\t\t}\n\t\ti++\n\t}\n\tfmt.Println(strings.Join(steps, \" \"))\n}", "func encryption(s string) string {\n length := float64(len(s))\n root := math.Sqrt(length)\n rows := math.Floor(root)\n columns := math.Ceil(root)\n if rows * columns < length {\n rows++\n }\n var stripped string\n stripped = strings.ReplaceAll(s, \" \", \"\")\n var encrypted string\n for y := float64(0); y < columns; y++ {\n for x := float64(0); x + y < length; x+=columns {\n encrypted = encrypted + string(stripped[int(x+y)])\n }\n encrypted = encrypted + \" \"\n }\n return encrypted\n}", "func removeDuplicates80(nums []int) int {\n\ti := 0\n\tfor _, n := range nums {\n\t\tif i < 2 || n != nums[i-2] {\n\t\t\tnums[i] = n\n\t\t\ti++\n\t\t}\n\t}\n\treturn i\n}", "func CuttingPaperSquares(n int32, m int32) int64 {\n return int64(n)*int64(m)-1\n}", "func MakeBoundary()(b string){\n b = strconv.FormatInt(time.Now().UnixNano(), 10)\n b += strconv.FormatInt(rand.New(rand.NewSource(time.Now().UnixNano())).Int63(), 10)\n b = MD5(b)\n return\n}", "func multiples(of []int, below int)[]int {\n\t// Using a hash as a poor man's set\n\tvalues := make(map[int]bool)\n\tfor _, num := range of {\n\t\tfor i := num; i < below; i += num {\n\t\t\tvalues[i] = true\n\t\t}\n\t}\n\tresults := make([]int, len(values))\n\tvar i int = 0\n\tfor n, _ := range values {\n\t\tresults[i] = n\n\t\ti++\n\t}\n\treturn results\n}", "func steps(s []int) int {\n\tsteps := 0\n\n\tfor pos := 0; pos >= 0 && pos < len(s); steps += 1 {\n\t\tnewpos := pos + s[pos]\n\t\tif s[pos] >= 3 {\n\t\t\ts[pos] -= 1\n\t\t} else {\n\t\t\ts[pos] += 1\n\t\t}\n\t\tpos = newpos\n\t}\n\n\treturn steps\n}", "func main() {\n\tvar buffer bytes.Buffer\n\tvar validHash = regexp.MustCompile(`^0{5}.*$`)\n\tcount := 0\n\tinput := \"ugkcyxxp\"\n\n\tfor len(buffer.String()) < 8 {\n\t\ttmp := md5.Sum([]byte(fmt.Sprintf(\"%s%d\", input, count)))\n\t\tif str := hex.EncodeToString(tmp[:]); validHash.MatchString(str) {\n\t\t\tbuffer.WriteByte(str[5])\n\t\t}\n\t\tcount++\n\t}\n\n\tfmt.Println(buffer.String())\n}", "func main() {\n scanner := bufio.NewScanner(os.Stdin)\n scanner.Buffer(make([]byte, 1000000), 1000000)\n\n scanner.Scan()\n equality := scanner.Text()\n // _ = equality // to avoid unused error\n\n elms := regexp.MustCompile(\"[+=]\").Split(equality, -1)\n x, y, z := elms[0], elms[1], elms[2]\n\n numerals := \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n maxNumeralIndex := -1\n for index, num := range numerals {\n if strings.Contains(equality, string(num)) {\n maxNumeralIndex = index\n }\n }\n maxNumeralIndex++\n\n result := -1\n for i := maxNumeralIndex; i <= len(numerals); i++ {\n numeralX := toDecimal(x, i)\n numeralY := toDecimal(y, i)\n numeralZ := toDecimal(z, i)\n\n if numeralX + numeralY == numeralZ {\n result = i\n break\n }\n }\n\n // fmt.Fprintln(os.Stderr, \"Debug messages...\")\n // fmt.Println(\"answer\")// Write answer to stdout\n fmt.Println(result)\n}", "func div(u uint8) (uint8, uint8) {\n\treturn u / 64, u % 64\n}", "func numIslands(grid [][]byte) int {\n\t//h := len(grid)\n\t//w := len(grid[0])\n\t//walkJudge := make([][]bool, h)\n\t//for i, _ := range walkJudge {\n\t//\twalkJudge[i] = make([]bool, w)\n\t//}\n\tcount := 0\n\n\tfor i, _ := range grid {\n\t\tfor j, _ := range grid[i] {\n\t\t\tif grid[i][j] == '1' {\n\t\t\t\tdfs(grid, i, j)\n\t\t\t\tcount += 1\n\t\t\t\t//fullPath(&walkJudge, grid,i, j)\n\t\t\t}\n\t\t}\n\t}\n\treturn count\n}", "func (s *CountMinSketch) locations(key []byte) (locs []uint) {\n\tlocs = make([]uint, s.d)\n\ta, b := s.baseHashes(key)\n\tua := uint(a)\n\tub := uint(b)\n\tfor r := uint(0); r < s.d; r++ {\n\t\tlocs[r] = (ua + ub*r) % s.w\n\t}\n\treturn\n}", "func fingerprint(str []byte) uint64 {\n\tvar hi = hash32(str, 0, len(str), 0)\n\tvar lo = hash32(str, 0, len(str), 102072)\n\tif (hi == 0) && (lo == 0 || lo == 1) {\n\t\t// Turn 0/1 into another fingerprint\n\t\thi ^= 0x130f9bef\n\t\tlo ^= 0x94a0a928\n\t}\n\treturn (uint64(hi) << 32) | uint64(lo&0xffffffff)\n}" ]
[ "0.58024555", "0.5661549", "0.5576845", "0.5349433", "0.5328527", "0.5309565", "0.53035676", "0.5302726", "0.52974", "0.5284454", "0.5270035", "0.5224862", "0.52078164", "0.5188299", "0.5173334", "0.5172408", "0.5172408", "0.5172408", "0.5172408", "0.5172408", "0.5172408", "0.5172408", "0.5172408", "0.51550025", "0.5153112", "0.514917", "0.51460683", "0.51421726", "0.5135196", "0.5135164", "0.5119654", "0.51193696", "0.51085204", "0.5107168", "0.50985456", "0.5061542", "0.5053697", "0.5047041", "0.5019534", "0.5011306", "0.49973723", "0.49964282", "0.49892554", "0.49814162", "0.49776298", "0.4974919", "0.49697962", "0.4966913", "0.495805", "0.4958024", "0.49552855", "0.49552855", "0.49506596", "0.49497923", "0.49472117", "0.49465036", "0.4943548", "0.49420732", "0.49404958", "0.49378067", "0.49342555", "0.493043", "0.49292123", "0.49263886", "0.49238405", "0.4922644", "0.49086556", "0.49084547", "0.48985362", "0.48982117", "0.48939914", "0.4889766", "0.48854727", "0.48838905", "0.4883343", "0.48778617", "0.48757645", "0.48652", "0.4859359", "0.4857869", "0.48576134", "0.4852902", "0.484651", "0.4845548", "0.4845374", "0.484301", "0.48406872", "0.48354128", "0.48313367", "0.48267984", "0.48260692", "0.48254535", "0.48149982", "0.4813896", "0.4812025", "0.4808479", "0.48022333", "0.4802225", "0.48002836", "0.4799712", "0.4798361" ]
0.0
-1
Min of max is: 75
func maxOfMinSlidingWindows(arr []int, k int) { size := len(arr) que := new(Queue) maxVal := math.MinInt32 i := 0 for i < size { // Remove out of range elements if que.Len() > 0 && que.Front().(int) <= i-k { que.Remove() } // Remove smaller values at left. for que.Len() > 0 && arr[que.Back().(int)] >= arr[i] { que.RemoveBack() } que.Add(i) // window of size k if i >= (k-1) && maxVal < arr[que.Front().(int)] { maxVal = arr[que.Front().(int)] } i += 1 } fmt.Println("Max of min is:", maxVal) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func MinMax(x, min, max int) int { return x }", "func (p parseSpec) minMax() (int, int) {\n\tmaxVal := -math.MaxInt64\n\tminVal := math.MaxInt64\n\tfor _, v := range p {\n\t\tif v > maxVal {\n\t\t\tmaxVal = v\n\t\t} else if v < minVal {\n\t\t\tminVal = v\n\t\t}\n\t}\n\treturn minVal, maxVal\n}", "func minmax(a, b, c float64) float64 {\n\ta = math.Max(a, b)\n\ta = math.Min(a, c)\n\treturn a\n}", "func getRange(min, max int) int {\n\treturn max * min\n}", "func MinMaxInt8(x, min, max int8) int8 { return x }", "func LabelMaxMin(c *Curve, rend gochart.Renderer, width, height int) {\n\n\tminlabel := \"-\"\n\tmaxlabel := \"-\"\n\n\tif c.MinIndex >= 0 {\n\t\tminlabel = strconv.FormatFloat(c.Value[c.MinIndex], 'f', 0, 64)\n\t}\n\n\tif c.MaxIndex >= 0 {\n\t\tmaxlabel = strconv.FormatFloat(c.Value[c.MaxIndex], 'f', 0, 64)\n\t}\n\n\trend.SetFontSize(9)\n\t//rend.SetFontColor(gochart.ColorRed) // Color{R: 0x00, G: 0x66, B: 0xff, A: 255})\n\trend.SetFontColor(drawing.Color{R: 255, G: 0, B: 0, A: 255})\n\trend.Text(minlabel, 4, 12)\n\n\trend.SetFontColor(drawing.Color{R: 0x23, G: 0xd1, B: 0x60, A: 255}) // (drawing.Color{R: 0x00, G: 0xFF, B: 0x00, A: 255})\n\trend.Text(maxlabel, width-2-rend.MeasureText(maxlabel).Right, height-2)\n}", "func maxYmin(numeros []int) (int, int) { //indicamos los tipos que va retornar (int, int)\n\tvar max, min int\n\n\tfor _, v := range numeros {\n\t\tif v > max {\n\t\t\tmax = v\n\t\t}\n\n\t\tif v < min {\n\t\t\tmin = v\n\t\t}\n\t}\n\n\treturn max, min //indicamos el orden en el que se debe retornar\n}", "func constrain(input, min, max float64) float32 {\n\tvar value float32\n\tvalue = float32(math.Min(max, math.Max(min, input)))\n\treturn value\n}", "func maxYmin2(numeros []int) (max int, min int) { //indicamos los tipos y nombre que va retornar (int, int)\n\tfor _, v := range numeros {\n\t\tif v > max {\n\t\t\tmax = v\n\t\t}\n\n\t\tif v < min {\n\t\t\tmin = v\n\t\t}\n\t}\n\n\treturn //ya no necesita return porque ya le indicamos como va retornar y que orden\n}", "func clamp(min, max, v int) int {\n\tif v < min {\n\t\tmin = v\n\t} else if v > max {\n\t\tmax = v\n\t}\n\n\treturn v\n}", "func max(x int) int {\n\treturn 40 + x\n}", "func MinMaxInt32(x, min, max int32) int32 { return x }", "func MinMaxDiff(vals []string) int {\n\tmin, _ := strconv.Atoi(vals[0])\n\tmax := min\n\tfor _, v := range vals {\n\t\td, err := strconv.Atoi(v)\n\t\tif err != nil {\n\t\t\tpanic(\"could not parse number!\")\n\t\t}\n\t\tif int(d) < min {\n\t\t\tmin = int(d)\n\t\t} else if int(d) > max {\n\t\t\tmax = int(d)\n\t\t}\n\t}\n\n\treturn max - min\n}", "func (s *Slider) Max(max float32) *Slider {\n\ts.max = max\n\treturn s\n}", "func (r *Retry) min(a, b uint64) uint64 {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}", "func MinMax(min, max int) int {\n\trand.Seed(time.Now().UTC().UnixNano())\n\tif min > max {\n\t\tbuf := min\n\t\tmin = max\n\t\tmax = buf\n\t}\n\treturn rand.Intn(max-min) + min\n}", "func Min(x, min int) int { return x }", "func MinMax(w http.ResponseWriter, req *http.Request) {\r\n\r\n minmax_templ.Execute(w, req.FormValue(\"s\"))\r\n if req.FormValue != nil {\r\n min, max, sum := minmax.FindMinmax(req.FormValue(\"s\"))\r\n if min != 0 && max != 0 && sum != 0 {\r\n fmt.Fprintf(w, \"%d %d %d\", min, max, sum)\r\n }\r\n }\r\n \r\n}", "func (px *Paxos) Max() int {\n\treturn px.Hi\n}", "func minmax() (min float64, max float64) {\n\tmin = math.NaN()\n\tmax = math.NaN()\n\tfor i := 0; i < cells; i++ {\n\t\tfor j := 0; j < cells; j++ {\n\t\t\tfor xoff := 0; xoff <= 1; xoff++ {\n\t\t\t\tfor yoff := 0; yoff <= 1; yoff++ {\n\t\t\t\t\tx := xyrange * (float64(i+xoff)/cells - 0.5)\n\t\t\t\t\ty := xyrange * (float64(j+yoff)/cells - 0.5)\n\t\t\t\t\tz := f(x, y)\n\t\t\t\t\tif math.IsNaN(min) || z < min {\n\t\t\t\t\t\tmin = z\n\t\t\t\t\t}\n\t\t\t\t\tif math.IsNaN(max) || z > max {\n\t\t\t\t\t\tmax = z\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func MinMaxInt64(x, min, max int64) int64 { return x }", "func clamp(v, min, max int) int {\n\tif v > max {\n\t\treturn max\n\t}\n\tif v < min {\n\t\treturn min\n\t}\n\treturn v\n}", "func MinMaxUint8(x, min, max uint8) uint8 { return x }", "func MinMaxUint64(x, min, max uint64) uint64 { return x }", "func (px *Paxos) Min() int {\n\treturn px.Lo\n}", "func (self *Limits) Maximum() uint32 {\n\treturn uint32(self.inner().max)\n}", "func clampRange(low, size, max int) (from, upto int) {\n\tfrom, upto = low, low+size\n\tif from > max {\n\t\tfrom = max\n\t}\n\tif upto > max {\n\t\tupto = max\n\t}\n\treturn\n}", "func (obj *interval) Max() int {\n\treturn obj.max\n}", "func Max(a, b float64) float64 {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Max(a, b float64) float64 {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Max(a, b float64) float64 {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}", "func constrain(min, n, max float64) float64 {\n\tn = math.Max(min, n)\n\tn = math.Min(n, max)\n\treturn n\n}", "func normalize(val, oldMax, newMax int) int {\n\treturn int(float64(newMax) / float64(oldMax) * float64(val))\n}", "func min(x, y int) int {\n\tif x > y {\n\t\treturn y\n\t}\n\treturn x\n}", "func min(x, y int64) int64 {\n\tif x > y {\n\t\treturn y\n\t}\n\treturn x\n}", "func scale(val float64, min float64, max float64, outMin float64, outMax float64) float64 {\r\n\tdenom := 1.0\r\n\ty := 0.0\r\n\tif outMin - min != 0 {\r\n\t\tdenom = outMin - min\r\n\t\ty = (outMax - max) / denom * val - min + outMin\r\n\t} else {\r\n\t\ty = outMax / max * val - min + outMin\r\n\t}\r\n\treturn y\r\n}", "func (m mathUtil) MinAndMax(values ...float64) (min float64, max float64) {\n\tif len(values) == 0 {\n\t\treturn\n\t}\n\tmin = values[0]\n\tmax = values[0]\n\tfor _, v := range values {\n\t\tif max < v {\n\t\t\tmax = v\n\t\t}\n\t\tif min > v {\n\t\t\tmin = v\n\t\t}\n\t}\n\treturn\n}", "func (px *Paxos) Max() int {\n\t// Your code here.\n\treturn px.max\n}", "func min(x, y int) int {\n\tif x > y {\n\t\treturn y\n\t}\n\n\treturn x\n}", "func clamp(n, min, max int16) int16 {\n\tif n < min {\n\t\treturn min\n\t} else if n > max {\n\t\treturn max\n\t}\n\n\treturn n\n}", "func main() {\n\tvar minMax = func(n []int) (int, int) {\n\t\tvar min, max int\n\n\t\tfor key, val := range n {\n\n\t\t\tif key == 0 {\n\t\t\t\tmin, max = val, val\n\t\t\t}\n\n\t\t\tif val < min {\n\t\t\t\tmin = val\n\t\t\t}\n\n\t\t\tif val > max {\n\t\t\t\tmax = val\n\t\t\t}\n\t\t}\n\n\t\treturn min, max\n\t}\n\n\tvar number = []int{10, 22, 3, 77, 1, 5}\n\n\tvar min, max = minMax(number)\n\n\tfmt.Printf(\"min : %d \", min)\n\tfmt.Printf(\"max : %d\", max)\n}", "func MinMaxInt16(x, min, max int16) int16 { return x }", "func InRange(val, min, max float64) float64 {\n\tif val < min {\n\t\treturn min\n\t} else if val > max {\n\t\treturn max\n\t}\n\treturn val\n}", "func (rn *RangedNumber) Min() int {\n\tif rn.min > rn.max {\n\t\trn.Set(rn.max, rn.min)\n\t}\n\n\treturn rn.min\n}", "func testMaxMin(f interface{}) (passed, failed int, err error) {\n\tintArr := &pr.ArrayMatcher{M: &pr.KindMatcher{Kind: reflect.Int}}\n\twantFn := &pr.FuncMatcher{\n\t\tIn: []pr.TypeMatcher{intArr},\n\t\tOut: []pr.TypeMatcher{\n\t\t\t&pr.KindMatcher{Kind: reflect.Int},\n\t\t\t&pr.KindMatcher{Kind: reflect.Int},\n\t\t},\n\t}\n\tif !wantFn.MatchType(reflect.TypeOf(f)) {\n\t\treturn 0, 0, errors.New(\"want func([N]int)(min, max int)\")\n\t}\n\n\tvalF := reflect.ValueOf(f)\n\tcallF := func(in reflect.Value) (max, min int) {\n\t\targs := []reflect.Value{in.Elem()}\n\t\tret := valF.Call(args)\n\t\treturn int(ret[0].Int()), int(ret[1].Int())\n\t}\n\n\tal := intArr.Len\n\tbuilder := func() *pr.IntArrayBuilder {\n\t\treturn &pr.IntArrayBuilder{Count: al}\n\t}\n\n\tfor _, test := range []struct {\n\t\tname string\n\t\tin *pr.IntArrayBuilder\n\t\twantMin, wantMax int\n\t}{\n\t\t{name: \"zero value\", wantMin: 0, wantMax: 0, in: builder()},\n\t\t{name: \"straight up\", wantMin: 1, wantMax: al, in: builder().FillRange(1, 1)},\n\t\t{name: \"straight down\", wantMin: -al, wantMax: -1, in: builder().FillRange(-1, -1)},\n\t\t{name: \"shuffle\", wantMin: -al / 2, wantMax: -al/2 + al - 1, in: builder().FillRange(-al/2, 1).Shuffle()},\n\t} {\n\t\tactualMax, actualMin := callF(test.in.Build())\n\t\tif actualMin == test.wantMin && actualMax == test.wantMax {\n\t\t\tlog.Println(\"PASS:\", test.name)\n\t\t\tpassed++\n\t\t} else {\n\t\t\tlog.Println(\"FAIL:\", test.name)\n\t\t\tfailed++\n\t\t}\n\t}\n\treturn\n}", "func MinMaxUint(x, min, max uint) uint { return x }", "func Max(val, max any) bool { return valueCompare(val, max, \"<=\") }", "func min(a, b float64) float64 {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Max(x, y int) int {\n\tif x < y {\n\t\treturn y\n\t}\n\treturn x\n}", "func MinMaxUint32(x, min, max uint32) uint32 { return x }", "func GetMinmax(target uint32, reset bool, format uint32, xtype uint32, values unsafe.Pointer) {\n C.glowGetMinmax(gpGetMinmax, (C.GLenum)(target), (C.GLboolean)(boolToInt(reset)), (C.GLenum)(format), (C.GLenum)(xtype), values)\n}", "func min(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}", "func (r SampleRateRange) Max() int {\n\treturn r.max\n}", "func min(a, b uint64) uint64 {\n\tif a <= b {\n\t\treturn a\n\t}\n\treturn b\n}", "func (rn *RangedNumber) Max() int {\n\tif rn.min > rn.max {\n\t\trn.Set(rn.max, rn.min)\n\t}\n\n\treturn rn.max\n}", "func GetRangeLimit() int {\n\treturn 25\n}", "func Min(a, b float64) float64 {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Min(a, b float64) float64 {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Min(a, b float64) float64 {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func max(a, b float64) float64 {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Clamp(value, min, max float32) float32 {\n\tvar res float32\n\tif value < min {\n\t\tres = min\n\t} else {\n\t\tres = value\n\t}\n\n\tif res > max {\n\t\treturn max\n\t}\n\n\treturn res\n}", "func getMinMaxScores(scores framework.NodeScoreList) (int64, int64) {\n\tvar max int64 = math.MinInt64 // Set to min value\n\tvar min int64 = math.MaxInt64 // Set to max value\n\n\tfor _, nodeScore := range scores {\n\t\tif nodeScore.Score > max {\n\t\t\tmax = nodeScore.Score\n\t\t}\n\t\tif nodeScore.Score < min {\n\t\t\tmin = nodeScore.Score\n\t\t}\n\t}\n\t// return min and max scores\n\treturn min, max\n}", "func minMax(values []float64) (x, y float64) {\n\tmin, max := numbers.MinMax(values)\n\tif math.IsNaN(min) {\n\t\tmin = 0\n\t}\n\tif math.IsNaN(max) {\n\t\tmax = 0\n\t}\n\treturn min, max\n}", "func min(a, b int32) int32 {\n\tif a <= b {\n\t\treturn a\n\t}\n\treturn b\n}", "func axisMax(val int) (int, int) {\n\tif val < 10 {\n\t\treturn 10, 1\n\t}\n\n\t// If val is less than 100, return val rounded up to the next 10\n\tif val < 100 {\n\t\tx := val % 10\n\t\treturn val + 10 - x, 10\n\t}\n\n\t// If val is less than 500, return val rounded up to the next 50\n\tif val < 500 {\n\t\tx := val % 50\n\t\treturn val + 50 - x, 50\n\t}\n\treturn 1000, 100\n}", "func Max(x, y int) int {\n\tif y > x {\n\t\treturn y\n\t}\n\treturn x\n}", "func (qs ControlQS) IntabsmaxLt(v float64) ControlQS {\n\treturn qs.filter(`\"intabsmax\" <`, v)\n}", "func (s *Slider) Min(min float32) *Slider {\n\ts.min = min\n\treturn s\n}", "func Max(a int, b int) int {\n\tif a >= b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Max(a uint64, b uint64) uint64 {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}", "func min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}", "func min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}", "func min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}", "func (self *ComponentScaleMinMax) SetScaleMinMax(minX interface{}, minY interface{}, maxX interface{}, maxY interface{}) {\n self.Object.Call(\"setScaleMinMax\", minX, minY, maxX, maxY)\n}", "func MaxFadeExtent(value int) *SimpleElement { return newSEInt(\"maxFadeExtent\", value) }", "func Min(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}", "func Min(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}", "func Min(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}", "func (r SampleRateRange) Min() int {\n\treturn r.min\n}", "func (m Metric) MinLevel(val float64) int {\n\tif val < 0 {\n\t\treturn maxLevel\n\t}\n\n\tlevel := -(math.Ilogb(val/m.Deriv) >> uint(m.Dim-1))\n\tif level > maxLevel {\n\t\tlevel = maxLevel\n\t}\n\tif level < 0 {\n\t\tlevel = 0\n\t}\n\treturn level\n}", "func (p *BW) MaxValue() uint16 {\n\treturn 1\n}", "func min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t} else {\n\t\treturn y\n\t}\n}", "func (p *analogPin) Range() (analog.Sample, analog.Sample) {\n\tmax := analog.Sample{Raw: math.MaxInt16, V: p.voltageMultiplier}\n\tmin := analog.Sample{Raw: -math.MaxInt16, V: -p.voltageMultiplier}\n\treturn min, max\n}", "func max(a, b int) int {\nif a < b {\nreturn b\n}\nreturn a\n}", "func max(x, y int) int {\n\tif x < y {\n\t\treturn y\n\t}\n\treturn x\n}", "func Max(x, y int64) int64 {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func Max(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func Max(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func Min(val, min any) bool { return valueCompare(val, min, \">=\") }", "func Max(a, b uint32) uint32 {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}", "func max(x, y int64) int64 {\n\tif x < y {\n\t\treturn y\n\t}\n\treturn x\n}", "func Constrain(n, low, high float64) float64 {\n\treturn math.Max(math.Min(n, high), low)\n}", "func MinFadeExtent(value int) *SimpleElement { return newSEInt(\"minFadeExtent\", value) }", "func Max(x, y int) int {\n if x < y {\n return y\n }\n return x\n}", "func Max(a, b int) int {\n\tif a < b {\n\t\treturn b\n\t}\n\treturn a\n}", "func Max(a, b int) int {\n\tif a < b {\n\t\treturn b\n\t}\n\treturn a\n}", "func MinMax(array []int64) (int64, int64) {\n\tvar max = array[0]\n\tvar min = array[0]\n\tfor _, value := range array {\n\t\tif max < value {\n\t\t\tmax = value\n\t\t}\n\t\tif min > value {\n\t\t\tmin = value\n\t\t}\n\t}\n\treturn min, max\n}", "func MinMax(array []int64) (int64, int64) {\n\tvar max = array[0]\n\tvar min = array[0]\n\tfor _, value := range array {\n\t\tif max < value {\n\t\t\tmax = value\n\t\t}\n\t\tif min > value {\n\t\t\tmin = value\n\t\t}\n\t}\n\treturn min, max\n}", "func (qs ControlQS) IntabsmaxGe(v float64) ControlQS {\n\treturn qs.filter(`\"intabsmax\" >=`, v)\n}", "func Min(a int, b int) int {\n\tif a <= b {\n\t\treturn a\n\t}\n\treturn b\n}", "func (r *SlidingWindow) Max() int {return r.base + len(r.values) - 1}" ]
[ "0.74028397", "0.6915779", "0.66241217", "0.6616075", "0.6559249", "0.64556175", "0.6428241", "0.6380175", "0.6302906", "0.62899035", "0.62846214", "0.626812", "0.6259294", "0.6231927", "0.62230694", "0.6221588", "0.62114716", "0.6209669", "0.62021357", "0.61924946", "0.6184377", "0.61504984", "0.6121321", "0.610572", "0.6097324", "0.6067848", "0.60534674", "0.6053458", "0.604908", "0.604908", "0.604908", "0.6045262", "0.60385233", "0.6034196", "0.60319525", "0.60312235", "0.60280377", "0.6017658", "0.6013951", "0.5997187", "0.59907633", "0.5989524", "0.5986447", "0.59608084", "0.59539", "0.59524137", "0.5938257", "0.59238064", "0.5915482", "0.5906259", "0.5905962", "0.5891361", "0.5877097", "0.5867715", "0.5862276", "0.58612895", "0.5851052", "0.5851052", "0.5851052", "0.5840789", "0.5840633", "0.5839013", "0.5836535", "0.5833627", "0.582472", "0.5821611", "0.5818792", "0.58139896", "0.58085006", "0.5801227", "0.58003294", "0.58003294", "0.58003294", "0.57992435", "0.57977587", "0.57963425", "0.57963425", "0.57963425", "0.5790176", "0.5788928", "0.57857597", "0.5781677", "0.57771695", "0.5776763", "0.5772524", "0.5771385", "0.5771291", "0.5771291", "0.57688314", "0.5767646", "0.5766692", "0.5759481", "0.575732", "0.57556516", "0.57515675", "0.57515675", "0.5746868", "0.5746868", "0.5744077", "0.57413155", "0.5736198" ]
0.0
-1
/ Max of min is: 59
func firstNegSlidingWindows(arr []int, k int) { size := len(arr) que := new(Queue) i := 0 for i < size { // Remove out of range elements if que.Len() > 0 && que.Front().(int) <= i-k { que.Remove() } if arr[i] < 0 { que.Add(i) } // window of size k if i >= (k - 1) { if que.Len() > 0 { fmt.Print(arr[que.Front().(int)], " ") } else { fmt.Print("NAN ") } } i += 1 } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func normalizeMinutes(min int) (int, int) {\n\tflag := false\n\taddHours := 0\n\tif min < 0 {\n\t\tflag = !flag\n\t\tmin = -1 * min\n\t}\n\n\tif min >= 60 {\n\t\taddHours = min / 60\n\t\tmin = min % 60\n\t}\n\n\tif flag {\n\t\tif min > 0 {\n\t\t\tmin = 60 - min\n\t\t\taddHours += 1\n\t\t}\n\t\taddHours = -1 * addHours\n\t}\n\n\treturn min, addHours\n}", "func (NilTimer) Min() int64 { return 0 }", "func (tod *ValidatedTimeOfDay) Min() int {\n\treturn tod.min\n}", "func getMinutes(time *int) int {\n\treturn getTimeScale(time, 60)\n}", "func (c Clock) max24Hour() Clock {\n\tc = c % minutesInDay\n\tif int(c) < 0 {\n\t\treturn c + minutesInDay\n\t}\n\treturn c\n}", "func (NilTimer) Max() int64 { return 0 }", "func getRangeTime(agencyID int64) int {\n\n\tswitch agencyID {\n\tcase 14:\n\t\treturn 30\n\tcase 23:\n\t\treturn 10\n\tdefault:\n\t\treturn 10\n\t}\n\treturn 10\n}", "func tzsetNum(s string, min, max int) (num int, rest string, ok bool) {\n\tif len(s) == 0 {\n\t\treturn 0, \"\", false\n\t}\n\tnum = 0\n\tfor i, r := range s {\n\t\tif r < '0' || r > '9' {\n\t\t\tif i == 0 || num < min {\n\t\t\t\treturn 0, \"\", false\n\t\t\t}\n\t\t\treturn num, s[i:], true\n\t\t}\n\t\tnum *= 10\n\t\tnum += int(r) - '0'\n\t\tif num > max {\n\t\t\treturn 0, \"\", false\n\t\t}\n\t}\n\tif num < min {\n\t\treturn 0, \"\", false\n\t}\n\treturn num, \"\", true\n}", "func (et ExfatTimestamp) Minute() int {\n\treturn int(et&2016) >> 5\n}", "func (o TransferJobScheduleStartTimeOfDayOutput) Minutes() pulumi.IntOutput {\n\treturn o.ApplyT(func(v TransferJobScheduleStartTimeOfDay) int { return v.Minutes }).(pulumi.IntOutput)\n}", "func (t Time) Minute() int {}", "func validateFieldDurationSchedule(fl validator.FieldLevel) bool {\n\tv := fl.Field().Int()\n\tif v < durationScheduleMinutesMin {\n\t\treturn false\n\t}\n\tif v > durationScheduleMinutesMax {\n\t\treturn false\n\t}\n\treturn true\n}", "func min(data []int64) string {\n value := data[0]\n for _, n := range data {\n if n < value {\n value = n\n }\n }\n duration, _ := time.ParseDuration(fmt.Sprintf(\"%dns\", value))\n return fmt.Sprintf(\"%.3f\", duration.Seconds())\n}", "func MinMax(x, min, max int) int { return x }", "func normalize(hour, minute int) (int, int) {\n\tif minute < 0 || minute >= 60 {\n\t\thour += minute / 60\n\t\tminute = minute % 60\n\t}\n\tif minute < 0 {\n\t\tminute += 60\n\t\thour--\n\t}\n\tif hour < 0 || hour >= 24 {\n\t\thour = hour % 24\n\t\tif hour < 0 {\n\t\t\thour += 24\n\t\t}\n\t}\n\treturn hour, minute\n}", "func (o BucketReplicationConfigRuleDestinationReplicationTimeTimeOutput) Minutes() pulumi.IntOutput {\n\treturn o.ApplyT(func(v BucketReplicationConfigRuleDestinationReplicationTimeTime) int { return v.Minutes }).(pulumi.IntOutput)\n}", "func (tb *TimeBucket) Min() int64 { return tb.min }", "func GetTimeRange() uint64 {\n\n\ttimeRange := Get(\"TimeRange\")\n\tif timeRange == \"\" {\n\t\treturn 3600\n\t}\n\n\tparsedTimeRange, err := strconv.ParseUint(timeRange, 10, 64)\n\tif err != nil {\n\t\tlog.Printf(\"[!] Failed to parse time range : %s\\n\", err.Error())\n\t\treturn 3600\n\t}\n\n\treturn parsedTimeRange\n\n}", "func hour(n int) float64 { return float64(n * 60 * 60) }", "func validateFieldDurationScheduleStr(fl validator.FieldLevel) bool {\n\tv, err := strconv.ParseInt(fl.Field().String(), 10, 32)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif v < durationScheduleMinutesMin {\n\t\treturn false\n\t}\n\tif v > durationScheduleMinutesMax {\n\t\treturn false\n\t}\n\treturn true\n}", "func (obj *interval) Max() int {\n\treturn obj.max\n}", "func (p parseSpec) minMax() (int, int) {\n\tmaxVal := -math.MaxInt64\n\tminVal := math.MaxInt64\n\tfor _, v := range p {\n\t\tif v > maxVal {\n\t\t\tmaxVal = v\n\t\t} else if v < minVal {\n\t\t\tminVal = v\n\t\t}\n\t}\n\treturn minVal, maxVal\n}", "func (o InstanceDenyMaintenancePeriodTimeOutput) Minutes() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v InstanceDenyMaintenancePeriodTime) *int { return v.Minutes }).(pulumi.IntPtrOutput)\n}", "func NsMinutes(count int64) int64 { return NsSeconds(count * 60) }", "func min(a time.Duration, b time.Duration) time.Duration {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}", "func (obj *interval) Min() int {\n\treturn obj.min\n}", "func ToSlabRange(res Resolution, sTime time.Time, eTime time.Time) []string {\n\toutStr := []string{}\n\tonT := sTime.UTC()\n\tuseEnd := eTime.UTC()\n\tswitch res {\n\tcase Resolution_MIN:\n\t\tuseEnd = useEnd.Add(time.Minute * 1) // need to include the end\n\t\tfor onT.Before(useEnd) {\n\t\t\toutStr = append(outStr, onT.Format(\"200601021504\"))\n\t\t\tonT = onT.Add(time.Minute * 1)\n\t\t}\n\t\treturn outStr\n\tcase Resolution_MIN5:\n\t\tuseEnd = useEnd.Add(time.Minute * 5) // need to include the end\n\t\tfor onT.Before(useEnd) {\n\t\t\tm := onT.Minute() / 5\n\t\t\toutStr = append(outStr, onT.Format(\"2006010215\")+\"I5\"+strconv.Itoa(m))\n\t\t\tonT = onT.Add(time.Minute * 5)\n\t\t}\n\t\treturn outStr\n\tcase Resolution_MIN10:\n\t\tuseEnd = useEnd.Add(time.Minute * 10) // need to include the end\n\t\tfor onT.Before(useEnd) {\n\t\t\tm := onT.Minute() / 10\n\t\t\toutStr = append(outStr, onT.Format(\"2006010215\")+\"I10\"+strconv.Itoa(m))\n\t\t\tonT = onT.Add(time.Minute * 10)\n\t\t}\n\t\treturn outStr\n\tcase Resolution_MIN15:\n\t\tuseEnd = useEnd.Add(time.Minute * 15) // need to include the end\n\t\tfor onT.Before(useEnd) {\n\t\t\tm := onT.Minute() / 15\n\t\t\toutStr = append(outStr, onT.Format(\"2006010215\")+\"I15\"+strconv.Itoa(m))\n\t\t\tonT = onT.Add(time.Minute * 15)\n\t\t}\n\t\treturn outStr\n\tcase Resolution_MIN20:\n\t\tuseEnd = useEnd.Add(time.Minute * 20) // need to include the end\n\t\tfor onT.Before(useEnd) {\n\t\t\tm := onT.Minute() / 20\n\t\t\toutStr = append(outStr, onT.Format(\"2006010215\")+\"I20\"+strconv.Itoa(m))\n\t\t\tonT = onT.Add(time.Minute * 20)\n\t\t}\n\t\treturn outStr\n\tcase Resolution_MIN30:\n\t\tuseEnd = useEnd.Add(time.Minute * 30) // need to include the end\n\t\tfor onT.Before(useEnd) {\n\t\t\tm := onT.Minute() / 30\n\t\t\toutStr = append(outStr, onT.Format(\"2006010215\")+\"I30\"+strconv.Itoa(m))\n\t\t\tonT = onT.Add(time.Minute * 30)\n\t\t}\n\t\treturn outStr\n\tcase Resolution_DAY:\n\t\tuseEnd = useEnd.AddDate(0, 0, 1) // need to include the end\n\t\tfor onT.Before(useEnd) {\n\t\t\toutStr = append(outStr, onT.Format(\"20060102\"))\n\t\t\tonT = onT.AddDate(0, 0, 1)\n\t\t}\n\t\treturn outStr\n\tcase Resolution_WEEK:\n\t\tuseEnd = useEnd.AddDate(0, 0, 7) // need to include the end\n\t\tfor onT.Before(useEnd) {\n\t\t\tynum, wnum := onT.ISOWeek()\n\t\t\toutStr = append(outStr, fmt.Sprintf(\"%04d%02d\", ynum, wnum))\n\t\t\tonT = onT.AddDate(0, 0, 7)\n\t\t}\n\t\treturn outStr\n\tcase Resolution_MONTH:\n\t\tuseEnd = useEnd.AddDate(0, 1, 0) // need to include the end\n\t\tfor onT.Before(useEnd) {\n\t\t\toutStr = append(outStr, onT.Format(\"200601\"))\n\t\t\tonT = onT.AddDate(0, 1, 0)\n\t\t}\n\t\treturn outStr\n\tcase Resolution_MONTH2:\n\t\tuseEnd = useEnd.AddDate(0, 2, 0) // need to include the end\n\t\tfor onT.Before(useEnd) {\n\t\t\tm := (int(onT.Month()) / 2)\n\t\t\toutStr = append(outStr, onT.Format(\"2006\")+\"M2\"+strconv.Itoa(m))\n\t\t\tonT = onT.AddDate(0, 2, 0)\n\t\t}\n\t\treturn outStr\n\tcase Resolution_MONTH3:\n\t\tuseEnd = useEnd.AddDate(0, 3, 0) // need to include the end\n\t\tfor onT.Before(eTime) {\n\t\t\tm := (int(onT.Month()) / 3)\n\t\t\toutStr = append(outStr, onT.Format(\"2006\")+\"M3\"+strconv.Itoa(m))\n\t\t\tonT = onT.AddDate(0, 3, 0)\n\t\t}\n\t\treturn outStr\n\tcase Resolution_MONTH6:\n\t\tuseEnd = useEnd.AddDate(0, 6, 0) // need to include the end\n\t\tfor onT.Before(useEnd) {\n\t\t\tm := (int(onT.Month()) / 6)\n\t\t\toutStr = append(outStr, onT.Format(\"2006\")+\"M6\"+strconv.Itoa(m))\n\t\t\tonT = onT.AddDate(0, 6, 0)\n\t\t}\n\t\treturn outStr\n\tcase Resolution_YEAR:\n\t\tuseEnd = useEnd.AddDate(1, 0, 0) // need to include the end\n\t\tfor onT.Before(useEnd) {\n\t\t\toutStr = append(outStr, onT.Format(\"2006\"))\n\t\t\tonT = onT.AddDate(1, 0, 0)\n\t\t}\n\t\treturn outStr\n\tcase Resolution_ALL:\n\t\treturn []string{\"ALL\"}\n\n\t//default is hourly\n\tdefault:\n\t\tuseEnd = useEnd.Add(time.Hour) // need to include the end\n\t\tfor onT.Before(eTime) {\n\t\t\toutStr = append(outStr, onT.Format(\"2006010215\"))\n\t\t\tonT = onT.Add(time.Hour)\n\t\t}\n\t\treturn outStr\n\t}\n}", "func validateRange(value, field string, max int) (int, error) {\n\tn, err := strconv.Atoi(value)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif (n < 1) || (n > max) {\n\t\treturn 0, fmt.Errorf(\"field %v=%v but available range [%v - %v]\", field, n, 1, max)\n\t}\n\treturn n, nil\n}", "func normalize(hour, minute int) (int, int) {\n\n\t// total minutes are remaining\n\tminutesNormalized := minute % 60\n\n\t// total hours are remaining; don't care about days\n\thoursNormalized := (hour + minute/60) % 24\n\n\t// if remaining hours are negative, add the negative hours to the total hours in day\n\tif hoursNormalized < 0 {\n\t\thoursNormalized = 24 + hoursNormalized\n\t}\n\n\t// if remaining minutes are negative, add the negaive minutes to the total minutes in one hour\n\tif minutesNormalized < 0 {\n\t\tminutesNormalized = 60 + minutesNormalized\n\t\t// when subtracting from minutes, the hour goes down by one\n\t\t// before lowering the hour make, sure the value is 24 and not 0\n\t\tif hoursNormalized == 0 {\n\t\t\thoursNormalized = 24\n\t\t}\n\t\t// lower hours by one\n\t\thoursNormalized--\n\t}\n\n\treturn hoursNormalized, minutesNormalized\n}", "func Past(h, m, s int) int {\n\tvar sum int\n\tif h >= 1 && m >= 1 && s >= 1 {\n\t\th = (h * 60 * 60 * 1000)\n\t\tm = (m * 60 * 1000)\n\t\ts = s * 1000\n\t\tsum += h + m + s\n\t} else if h <= 0 && m >= 1 && s >= 1 {\n\t\tm = (m * 60 * 1000)\n\t\ts = s * 1000\n\t\tsum += h + m + s\n\t} else if h >= 1 && m == 0 && s == 0 {\n\t\th = (h * 60 * 60 * 1000)\n\t\tm = (m * 0)\n\t\ts = (s * 0)\n\t\tsum += h + m + s\n\t} else if m <= 0 && h >= 1 && s >= 1 {\n\t\th = (h * 60 * 60 * 1000)\n\t\ts = s * 1000\n\t\tsum += h + m + s\n\t} else if s <= 0 && m >= 1 && h >= 1 {\n\t\th = (h * 60 * 60 * 1000)\n\t\tm = (m * 60 * 1000)\n\t\tsum += h + m + s\n\t} else if h == 0 && m == 0 && s == 0 {\n\t\th = (h * 0)\n\t\tm = (m * 0)\n\t\ts = (s * 0)\n\t\tsum += h + m + s\n\t}\n\n\treturn sum\n}", "func checkTimeRange(db *db.DB, mint, maxt int64) (int64, int64) {\n\n\tlogger := log.With(logger, \"stage\", \"checkTimeRange\")\n\n\tvar actualMint int64 = math.MaxInt64\n\tvar actualMaxt int64 = math.MinInt64\n\n\tif db.ReadOnly {\n\t\tblocks, _ := db.BlockReader()\n\t\t//Look time ranges for blocks\n\t\tfor _, block := range blocks {\n\t\t\tif actualMint > block.Meta().MinTime {\n\t\t\t\tactualMint = block.Meta().MinTime\n\t\t\t}\n\n\t\t\tif actualMaxt < block.Meta().MaxTime {\n\t\t\t\tactualMaxt = block.Meta().MaxTime\n\t\t\t}\n\t\t}\n\t} else {\n\t\tblocks := db.Blocks()\n\t\t//Look time ranges for blocks\n\t\tfor _, block := range blocks {\n\t\t\tif actualMint > block.Meta().MinTime {\n\t\t\t\tactualMint = block.Meta().MinTime\n\t\t\t}\n\n\t\t\tif actualMaxt < block.Meta().MaxTime {\n\t\t\t\tactualMaxt = block.Meta().MaxTime\n\t\t\t}\n\t\t}\n\t}\n\n\tlogger.Log(\"status\", fmt.Sprintf(\"According to Blocks Mint: %d, Maxt: %d\", actualMint, actualMaxt))\n\n\thead := db.Head() // If tsdb opened in write mode\n\tif head != nil {\n\t\t//Look the time range for head\n\t\tif head.MinTime() < actualMint {\n\t\t\tactualMint = head.MinTime()\n\t\t}\n\n\t\tif head.MaxTime() > actualMaxt {\n\t\t\tactualMaxt = head.MaxTime()\n\t\t}\n\n\t\tlogger.Log(\"status\", fmt.Sprintf(\"According to Head Mint: %d, Maxt: %d\", actualMint, actualMaxt))\n\t}\n\n\tif actualMint < mint {\n\t\tactualMint = mint\n\t} // else use calculated actualMint\n\n\tif actualMaxt > maxt {\n\t\tactualMaxt = maxt\n\t} // else use calculated actualMaxt\n\n\treturn actualMint, actualMaxt\n\n}", "func (tb *TimeBucket) Max() int64 { return tb.max }", "func toUnixMsec(t time.Time) int64 {\n\treturn t.UnixNano() / 1e6\n}", "func parseTimeWindowLimit(rawLimit uint64, timeMult float64) float64 {\n\n\t//This is taken from the Intel SDM, Vol 3B 14.9.3\n\t/*\n\t\tTime limit = 2^Y * (1.0 + Z/4.0) * Time_Unit\n\n\t\tHere “Y” is the unsigned integer value represented by bits 21:17,\n\t\t“Z” is an unsigned integer represented by bits 23:22.\n\t\t“Time_Unit” is specified by the “Time Units” field of MSR_RAPL_POWER_UNIT.\n\t*/\n\ty := float64(rawLimit & 0x1f)\n\tz := float64(rawLimit >> 5 & 0x3)\n\treturn math.Pow(2, y) * (1.0 + (z / 4.0)) * timeMult\n\n}", "func (r *Retry) min(a, b uint64) uint64 {\n\tif a > b {\n\t\treturn b\n\t}\n\treturn a\n}", "func validateFieldDurationService(fl validator.FieldLevel) bool {\n\tv, err := strconv.ParseInt(fl.Field().String(), 10, 32)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif v < durationServiceMinutesMin {\n\t\treturn false\n\t}\n\tif v > durationServiceMinutesMax {\n\t\treturn false\n\t}\n\treturn true\n}", "func getRange(min, max int) int {\n\treturn max * min\n}", "func parseIntegerParameterRange(input string) (*IntegerParameterRange, error) {\n\tvar start, end int\n\n\tvar err error\n\tif strings.Index(input, \"-\") >= 0 {\n\t\tarray := strings.Split(input, \"-\")\n\t\tif len(array) != 2 {\n\t\t\terr = errors.New(\"Failed to split the string type\")\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif start, err = strconv.Atoi(array[0]); err != nil {\n\t\t\t// negative values must be dropped here\n\t\t\treturn nil, err\n\t\t}\n\t\tif end, err = strconv.Atoi(array[1]); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tif start, err = strconv.Atoi(input); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tend = start\n\t}\n\n\tif start > end {\n\t\terr = errors.New(\"The 'max-config-values' attributes MUST be greater or equal to their counterpart in 'min-config-values' attributes.\")\n\t\treturn nil, err\n\t}\n\n\treturn &IntegerParameterRange{\n\t\tstart: start,\n\t\tend: end,\n\t}, nil\n}", "func Min(x, min int) int { return x }", "func MinMaxDiff(vals []string) int {\n\tmin, _ := strconv.Atoi(vals[0])\n\tmax := min\n\tfor _, v := range vals {\n\t\td, err := strconv.Atoi(v)\n\t\tif err != nil {\n\t\t\tpanic(\"could not parse number!\")\n\t\t}\n\t\tif int(d) < min {\n\t\t\tmin = int(d)\n\t\t} else if int(d) > max {\n\t\t\tmax = int(d)\n\t\t}\n\t}\n\n\treturn max - min\n}", "func minDuration(a, b time.Duration) time.Duration {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func (minutes Minutes) Validate() bool {\n\tret := true\n\tif !validation.ValidateInt(minutes.value) ||\n\t\t!validation.CheckRange(minutes.value, 0, 99) {\n\t\tret = false\n\t}\n\treturn ret\n}", "func ValidBetween(min, max int) ValidatorFunc {\n\tvar EInvalidInterval = errors.New(\n\t\tfmt.Sprintf(\"must be integer between %d and %d\", min, max))\n\treturn func(field FormField, ctx context.Context) error {\n\t\tvalue, err := field.GetInt()\n\t\tif err != nil {\n\t\t\treturn EInvalidInteger\n\t\t}\n\t\tif value < min || value > max {\n\t\t\treturn EInvalidInterval\n\t\t}\n\t\treturn nil\n\t}\n}", "func (f *Formatter) Minutes() string {\n\tvar format string\n\tif f.withoutUnit {\n\t\tformat = \"%d\\n\"\n\t} else {\n\t\tformat = \"%d minutes\\n\"\n\t}\n\treturn fmt.Sprintf(format, int(f.duration.Minutes()))\n}", "func (o BucketReplicationConfigurationRuleDestinationReplicationTimeOutput) Minutes() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v BucketReplicationConfigurationRuleDestinationReplicationTime) *int { return v.Minutes }).(pulumi.IntPtrOutput)\n}", "func secToMins(t ClockTime) (mins, secs uint) {\n\tmins = uint(t) / 60\n\tsecs = uint(t) % 60\n\n\treturn mins, secs\n}", "func Min(val, min any) bool { return valueCompare(val, min, \">=\") }", "func getMinTimeDuration(durationFirst, durationSecond time.Duration) time.Duration {\n\tif durationFirst <= durationSecond {\n\t\treturn durationFirst\n\t}\n\treturn durationSecond\n}", "func (o InstanceMaintenanceWindowStartTimeOutput) Minutes() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceWindowStartTime) *int { return v.Minutes }).(pulumi.IntPtrOutput)\n}", "func getDurationWithin(min, max int) time.Duration {\n\tjitter := max - min\n\tif jitter <= 0 {\n\t\tjitter = 1\n\t}\n\tduration := rand.Intn(jitter) + min\n\treturn time.Duration(duration) * time.Second\n}", "func NsHours(count int64) int64 { return NsMinutes(count * 60) }", "func (t *TimerSnapshot) Min() int64 { return t.histogram.Min() }", "func MinMax(w http.ResponseWriter, req *http.Request) {\r\n\r\n minmax_templ.Execute(w, req.FormValue(\"s\"))\r\n if req.FormValue != nil {\r\n min, max, sum := minmax.FindMinmax(req.FormValue(\"s\"))\r\n if min != 0 && max != 0 && sum != 0 {\r\n fmt.Fprintf(w, \"%d %d %d\", min, max, sum)\r\n }\r\n }\r\n \r\n}", "func (dv *DurationValue) Min(min time.Duration) *DurationValue {\n\tdv.v.add(func() error {\n\t\tif n := dv.get(); n < min {\n\t\t\treturn fmt.Errorf(\"less than %s: %s\", min, n)\n\t\t}\n\t\treturn nil\n\t})\n\treturn dv\n}", "func (xt XSDTime) Minute() int {\n\treturn xt.innerTime.Minute()\n}", "func (this *MillisToUTC) MinArgs() int { return 1 }", "func (c Clock) Minute() int {\n\tr := time.Duration(c) % time.Hour\n\treturn int(r / time.Minute)\n}", "func MinimumFinishTime(tires [][]int, changeTime int, numLaps int) int {\n\tvar l int = len(tires)\n\tvar dp []int = make([]int,numLaps + 1)//dp[i], 跑i圈的最短时间\n\tfor i := 0;i <= numLaps;i++{\n\t\tdp[i] = 2147483647\n\t}\n\t//var factor int = 0\n\tvar eachround_time int = 2147483647\n\tfor i := 0;i < l;i++{\n\t\tif tires[i][0] < eachround_time{\n\t\t\teachround_time = tires[i][0]\n\t\t\t//factor = tires[i][1]\n\t\t}\n\t}\n\t//var total int = eachround_time\n\tvar neg bool = false\n\tfor i := 1;i <= numLaps;i++{\n\t\tif !neg{\n\t\t\tfor k := 0;k < l;k++{\n\t\t\t\ta1 := tires[k][0]\n\t\t\t\tan := tires[k][0] * int(math.Pow(float64(tires[k][1]),float64(i - 1)))\n\t\t\t\tsn := (an * tires[k][1] - a1)/(tires[k][1] - 1)\n\t\t\t\tif sn > 0 && sn < 2147483647{\n\t\t\t\t\tdp[i] = min_int(dp[i],sn)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif dp[i] < 0{\n\t\t\tneg = true\n\t\t\tdp[i] = 2147483647\n\t\t}\n\n\t\t//change_perround := changeTime * (i - 1) + eachround_time * i\n\t\t//if change_perround > 0{\n\t\t//\tdp[i] = change_perround\n\t\t//}\n\t\t//if total > 0{\n\t\t//\tdp[i] = min_int(dp[i],total)\n\t\t//}\n\t\t//eachround_time *= factor\n\t\t//total += eachround_time\n\t\tfor j := 1;j < i;j++{\n\t\t\tdp[i] = min_int(dp[i],dp[j] + dp[i - j] + changeTime)\n\t\t}\n\t}\n\treturn dp[numLaps]\n}", "func LimitPerMinute(t time.Time) time.Time {\n\treturn time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), 0, 0, t.Location())\n}", "func MinMaxUint(x, min, max uint) uint { return x }", "func absClock(abs uint64) (hour, min, sec int) {\n\tsec = int(abs % secondsPerDay)\n\thour = sec / secondsPerHour\n\tsec -= hour * secondsPerHour\n\tmin = sec / secondsPerMinute\n\tsec -= min * secondsPerMinute\n\treturn\n}", "func (k *Key) RangeTime(defaultVal, min, max time.Time) time.Time {\n\treturn k.RangeTimeFormat(time.RFC3339, defaultVal, min, max)\n}", "func NewMinute(t time.Time, lsw, dut1 int) (Minute, error) {\n\tt = t.UTC() // Don't care about local times\n\tmin := Minute{\n\t\tTime: t,\n\t\tlsw: lsw == 1,\n\t\tdut1: dut1,\n\t}\n\tbits := min.bits[:]\n\n\tmarkers := []int{9, 19, 29, 39, 49, 59} // P1-P6\n\tbits[0] = bitNone // Minute mark\n\tfor _, v := range markers {\n\t\tbits[v] = bitMarker\n\t}\n\n\tmidnight := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.UTC)\n\tendOfDay := midnight.AddDate(0, 0, 1)\n\n\tdst1 := 0 // DST status at 00:00Z today\n\tif isDST(midnight) {\n\t\tdst1 = 1\n\t}\n\tdst2 := 0 // DST status at 24:00Z today\n\tif isDST(endOfDay) {\n\t\tdst2 = 1\n\t}\n\n\tyear1s := t.Year() % 10\n\tyear10s := t.Year()%100 - year1s\n\n\tminute1s := t.Minute() % 10\n\tminute10s := t.Minute()%100 - minute1s\n\n\thour1s := t.Hour() % 10\n\thour10s := t.Hour()%100 - hour1s\n\n\tdayOfYear1s := t.YearDay() % 10\n\tdayOfYear10s := t.YearDay()%100 - dayOfYear1s\n\tdayOfYear100s := t.YearDay()%1000 - dayOfYear1s - dayOfYear10s\n\n\tdut1Sign, dut1Magnitude := 1, dut1 // dut1Sign is positive\n\tif dut1 < 0 {\n\t\tdut1Sign = 0\n\t\tdut1Magnitude *= -1\n\t}\n\tif dut1Magnitude > 7 {\n\t\tdut1Magnitude = 7 // Only 3 bits for this value.\n\t}\n\n\terr := minuteEncoder.encode(bits, []int{\n\t\t0, 0, dst1, lsw, year1s, 0, 0,\n\t\tminute1s, minute10s, 0, 0,\n\t\thour1s, hour10s, 0, 0,\n\t\tdayOfYear1s, dayOfYear10s, 0,\n\t\tdayOfYear100s, 0, 0,\n\t\tdut1Sign, year10s, dst2, dut1Magnitude, 0,\n\t})\n\tif err != nil {\n\t\treturn min, errors.Wrapf(err, \"Cannot encode minute %s\", t.Format(\"15:04\"))\n\t}\n\n\tmin.lastSecond = lastSecond(t, min.lsw)\n\n\treturn min, nil\n}", "func mesIntFunc() int {\n\tenero := 31\n\tfebrero := 28\n\tmarzo := 31\n\tabril := 30\n\tmayo := 31\n\tjunio := 30\n\tjulio := 31\n\tagosto := 31\n\tseptiembre := 30\n\toctubre := 31\n\tnoviembre := 30\n\tdiciembre := 31\n\t_, mes, _ := time.Now().Date()\n\tswitch {\n\tcase mes == time.January:\n\t\treturn enero\n\tcase mes == time.February:\n\t\treturn enero + febrero\n\tcase mes == time.March:\n\t\treturn enero + febrero + marzo\n\tcase mes == time.April:\n\t\treturn enero + febrero + marzo + abril\n\tcase mes == time.May:\n\t\treturn enero + febrero + marzo + abril + mayo\n\tcase mes == time.June:\n\t\treturn enero + febrero + marzo + abril + mayo + junio\n\tcase mes == time.July:\n\t\treturn enero + febrero + marzo + abril + mayo + junio + julio\n\tcase mes == time.August:\n\t\treturn enero + febrero + marzo + abril + mayo + junio + julio + agosto\n\tcase mes == time.September:\n\t\treturn enero + febrero + marzo + abril + mayo + junio + julio + agosto + septiembre\n\tcase mes == time.October:\n\t\treturn enero + febrero + marzo + abril + mayo + junio + julio + agosto + septiembre + octubre\n\tcase mes == time.November:\n\t\treturn enero + febrero + marzo + abril + mayo + junio + julio + agosto + septiembre + octubre + noviembre\n\tcase mes == time.December:\n\t\treturn enero + febrero + marzo + abril + mayo + junio + julio + agosto + septiembre + octubre + noviembre + diciembre\n\t}\n\treturn 0\n}", "func (c *Job) Minutes() *Job {\n\tif c.delayUnit == delayNone {\n\t\tc.unit = minutes\n\t} else {\n\t\tc.delayUnit = delayMinutes\n\t}\n\treturn c\n}", "func (o BucketV2ReplicationConfigurationRuleDestinationReplicationTimeOutput) Minutes() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v BucketV2ReplicationConfigurationRuleDestinationReplicationTime) *int { return v.Minutes }).(pulumi.IntPtrOutput)\n}", "func (m *sdt) Minute() int32 {\n\treturn m.minuteField\n}", "func MinMaxInt64(x, min, max int64) int64 { return x }", "func GetMaxBlockGenerationTime() int64 {\r\n\treturn converter.StrToInt64(SysString(MaxBlockGenerationTime))\r\n}", "func Min(min time.Duration) exponentialOption {\n\treturn func(e *Exponential) {\n\t\te.min = min\n\t}\n}", "func normalizeHours(hrs int) int {\n\tflag := false\n\n\tif hrs < 0 {\n\t\tflag = !flag\n\t\thrs = -1 * hrs\n\t}\n\n\thrs = hrs % 24\n\n\tif flag && hrs > 0 {\n\t\thrs = 24 - hrs\n\t}\n\n\treturn hrs\n}", "func NewMaxOrMinDec(negative bool, prec, frac int) *MyDecimal {\n\tstr := make([]byte, prec+2)\n\tfor i := 0; i < len(str); i++ {\n\t\tstr[i] = '9'\n\t}\n\tif negative {\n\t\tstr[0] = '-'\n\t} else {\n\t\tstr[0] = '+'\n\t}\n\tstr[1+prec-frac] = '.'\n\tdec := new(MyDecimal)\n\terr := dec.FromString(str)\n\tterror.Log(errors.Trace(err))\n\treturn dec\n}", "func (k *Key) RangeTimeFormat(format string, defaultVal, min, max time.Time) time.Time {\n\tval := k.MustTimeFormat(format)\n\tif val.Unix() < min.Unix() || val.Unix() > max.Unix() {\n\t\treturn defaultVal\n\t}\n\treturn val\n}", "func Minute(minute int) string {\n\tt := parsedTime(minute)\n\treturn t.Format(\"04\")\n}", "func MinMaxInt8(x, min, max int8) int8 { return x }", "func main() {\n\tconst now = 1589570165\n\n\ttimeStamp := time.Unix(now, 0).UTC()\n\n\tscanner := bufio.NewScanner(os.Stdin)\n\tscanner.Scan()\n\ts := scanner.Text()\n\n\telapsedTime := strings.Replace(s, \"мин.\", \"m\", 1)\n\telapsedTime = strings.Replace(elapsedTime, \"сек.\", \"s\", 1)\n\telapsedTime = strings.Replace(elapsedTime, \" \", \"\", -1)\n\n\tdur, err := time.ParseDuration(elapsedTime)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t//dur.Round(time.Hour).Hours()\n\tunitedDate := timeStamp.Add(dur)\n\n\tfmt.Println(unitedDate.Format(time.UnixDate))\n\n}", "func (c *cursor) blockMinTime(pos uint32) int64 {\n\treturn int64(btou64(c.f.mmap[pos+12 : pos+20]))\n}", "func (j *Job) Minutes() (job *Job) {\n\tj.unit = JOB_UNIT_TYPE_MINUTE\n\treturn j\n}", "func (o SnapshotPolicyHourlyScheduleOutput) Minute() pulumi.IntOutput {\n\treturn o.ApplyT(func(v SnapshotPolicyHourlySchedule) int { return v.Minute }).(pulumi.IntOutput)\n}", "func parseClock(s string) (int, error) {\n\tclock := 0\n\n\tfor s != \"\" {\n\t\tcomponent, rest := splitOnce(s, \":\")\n\n\t\tn, err := strconv.Atoi(component)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tclock *= 60\n\t\tclock += int(n)\n\n\t\ts = rest\n\t}\n\n\treturn clock, nil\n}", "func validateFieldTimeUnix(fl validator.FieldLevel) bool {\n\tv := ParseTimeUnixUTC(fl.Field().String())\n\tif v.IsZero() {\n\t\treturn false\n\t}\n\treturn v.Unix() > unixTimeMin\n}", "func (s *Value) asRangeInt(min, max int64) (int64, error) {\n\tif s == nil {\n\t\treturn 0, fmt.Errorf(\"value is required in the range of [%d..%d]\", min, max)\n\t}\n\tn, err := ParseInt(s.Name)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ti, err := n.Int()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif i < min || i > max {\n\t\treturn 0, fmt.Errorf(\"value %s out of range [%d..%d]\", s.Name, min, max)\n\t}\n\treturn i, nil\n}", "func inMeshCap(slot time.Duration) float64 {\n\treturn float64((3600 * time.Second) / slot)\n}", "func dealDurationBounds(size abi.PaddedPieceSize) (min abi.ChainEpoch, max abi.ChainEpoch) {\n\treturn abi.ChainEpoch(180 * builtin.EpochsInDay), abi.ChainEpoch(540 * builtin.EpochsInDay) // PARAM_FINISH\n}", "func (o TransferJobScheduleStartTimeOfDayPtrOutput) Minutes() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *TransferJobScheduleStartTimeOfDay) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Minutes\n\t}).(pulumi.IntPtrOutput)\n}", "func (t *TimerSnapshot) Max() int64 { return t.histogram.Max() }", "func Int(i *int, title, id, class string, min, max, step float64, valid Validator) (jquery.JQuery, error) {\n\tj := jq(\"<input>\").AddClass(ClassPrefix + \"-int\").AddClass(class)\n\tj.SetAttr(\"title\", title).SetAttr(\"id\", id)\n\tj.SetAttr(\"type\", \"number\")\n\tif !math.IsNaN(min) {\n\t\tj.SetAttr(\"min\", int(min))\n\t}\n\tif !math.IsNaN(max) {\n\t\tj.SetAttr(\"max\", int(max))\n\t}\n\tif !math.IsNaN(step) {\n\t\tj.SetAttr(\"step\", int(step))\n\t}\n\tj.SetAttr(\"value\", *i)\n\tj.SetData(\"prev\", *i)\n\tj.Call(jquery.CHANGE, func(event jquery.Event) {\n\t\tval := event.Target.Get(\"value\").String()\n\t\tnewI, e := strconv.Atoi(val)\n\t\tif e != nil {\n\t\t\tf, e := strconv.ParseFloat(val, 64)\n\t\t\tif e != nil {\n\t\t\t\tpanic(fmt.Errorf(\"value '%s' has invalid type, expected a number\", val))\n\t\t\t}\n\t\t\t// Truncate to int\n\t\t\tnewI = int(f)\n\t\t\tj.SetVal(newI)\n\t\t}\n\t\t// Need to check for min and max ourselves because html min and max are easy to get around\n\t\tisValid := valid == nil || valid.Validate(newI)\n\t\tisToLow := !math.IsNaN(min) && newI < int(min)\n\t\tisToHigh := !math.IsNaN(max) && newI > int(max)\n\t\tif !isValid || isToLow || isToHigh {\n\t\t\tnewI = int(j.Data(\"prev\").(float64))\n\t\t\tj.SetVal(newI)\n\t\t}\n\t\t*i = newI\n\t\tj.SetData(\"prev\", newI)\n\t})\n\treturn j, nil\n}", "func max(data []int64) string {\n var value int64\n for _, n := range data {\n if n > value {\n value = n\n }\n }\n duration, _ := time.ParseDuration(fmt.Sprintf(\"%dns\", value))\n return fmt.Sprintf(\"%.3f\", duration.Seconds())\n}", "func max(x int) int {\n\treturn 40 + x\n}", "func (o SnapshotPolicyDailyScheduleOutput) Minute() pulumi.IntOutput {\n\treturn o.ApplyT(func(v SnapshotPolicyDailySchedule) int { return v.Minute }).(pulumi.IntOutput)\n}", "func getExponentialTime(min time.Duration, max time.Duration, attempts int) time.Duration {\n\tif min <= 0 {\n\t\tmin = 100 * time.Millisecond\n\t}\n\tif max <= 0 {\n\t\tmax = 10 * time.Second\n\t}\n\tminFloat := float64(min)\n\tnapDuration := minFloat * math.Pow(2, float64(attempts-1))\n\t// add some jitter\n\tnapDuration += rand.Float64()*minFloat - (minFloat / 2)\n\tif napDuration > float64(max) {\n\t\treturn time.Duration(max)\n\t}\n\treturn time.Duration(napDuration)\n}", "func (rn *RangedNumber) Min() int {\n\tif rn.min > rn.max {\n\t\trn.Set(rn.max, rn.min)\n\t}\n\n\treturn rn.min\n}", "func (m *Minute) Type() sql.Type { return sql.Int32 }", "func (o GetSnapshotPolicyHourlyScheduleOutput) Minute() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetSnapshotPolicyHourlySchedule) int { return v.Minute }).(pulumi.IntOutput)\n}", "func MinMaxInt32(x, min, max int32) int32 { return x }", "func Gt(val, min any) bool { return valueCompare(val, min, \">\") }", "func FromBPM(bpm int) time.Duration {\n\treturn time.Duration(60 * 1E9 / bpm)\n}", "func(md MonitorData) From() int64 {\n return md[0].Timestamp - int64(md[0].Per)\n}", "func (o GetSnapshotPolicyDailyScheduleOutput) Minute() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetSnapshotPolicyDailySchedule) int { return v.Minute }).(pulumi.IntOutput)\n}", "func (sc SfcConfig) MinLockupDuration() (hexutil.Big, error) {\n\tc, err := sc.getConfig()\n\tif err != nil {\n\t\treturn hexutil.Big{}, err\n\t}\n\treturn c.MinLockupDuration, nil\n}", "func MinMaxUint64(x, min, max uint64) uint64 { return x }" ]
[ "0.61662334", "0.57398677", "0.5701072", "0.5669399", "0.5604872", "0.5507069", "0.54734653", "0.5398669", "0.5395211", "0.5355866", "0.5341673", "0.52995133", "0.52645224", "0.5257398", "0.5246607", "0.523801", "0.5223781", "0.5210974", "0.5200304", "0.5191768", "0.51909083", "0.51883173", "0.5186917", "0.517812", "0.5164651", "0.5156479", "0.5145729", "0.51141036", "0.5109044", "0.5104516", "0.5085699", "0.50726604", "0.50694424", "0.50607616", "0.50599796", "0.50430304", "0.50232595", "0.50163937", "0.5000623", "0.49657694", "0.49447846", "0.49249637", "0.4917584", "0.49116153", "0.49074832", "0.4904692", "0.48914045", "0.48857418", "0.48823422", "0.48728168", "0.48703483", "0.48695803", "0.4843383", "0.48431987", "0.48412827", "0.4840073", "0.483512", "0.4832889", "0.48325524", "0.48300493", "0.48229316", "0.48160666", "0.48053122", "0.47983986", "0.4798183", "0.47940737", "0.47931316", "0.47823524", "0.47809273", "0.47802904", "0.47729066", "0.47679988", "0.47670296", "0.4758739", "0.47531176", "0.47518647", "0.47505924", "0.47453302", "0.47397906", "0.4738073", "0.47371843", "0.4736745", "0.47344196", "0.4732635", "0.4730816", "0.47258365", "0.47196433", "0.4711379", "0.47108844", "0.47089273", "0.47057587", "0.47055262", "0.47048762", "0.47000363", "0.46987173", "0.46960866", "0.46821612", "0.4680731", "0.46760982", "0.4673725", "0.46731678" ]
0.0
-1
/ 2 2 6 14 14 NAN
func RottenFruitUtil(arr [][]int, maxCol int, maxRow int, currCol int, currRow int, traversed [][]int, day int) { if currCol < 0 || currCol >= maxCol || currRow < 0 || currRow >= maxRow { return } // Traversable and rot if not already rotten. if traversed[currCol][currRow] <= day || arr[currCol][currRow] == 0 { return } dir := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} traversed[currCol][currRow] = day // Update rot time. for i := 0; i < 4; i++ { x := currCol + dir[i][0] y := currRow + dir[i][1] RottenFruitUtil(arr, maxCol, maxRow, x, y, traversed, day+1) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NaN() float32 { return Float32frombits(uvnan) }", "func fillNaNDense(m *mat.Dense) {\n\tr, c := m.Dims()\n\tfor i := 0; i < r; i++ {\n\t\tfor j := 0; j < c; j++ {\n\t\t\tm.Set(i, j, math.NaN())\n\t\t}\n\t}\n}", "func (a *Array64) NaNSum(axis ...int) *Array64 {\n\tif a.valAxis(&axis, \"NaNSum\") {\n\t\treturn a\n\t}\n\n\tns := func(d []float64) (r float64) {\n\t\tflag := false\n\t\tfor _, v := range d {\n\t\t\tif !math.IsNaN(v) {\n\t\t\t\tflag = true\n\t\t\t\tr += v\n\t\t\t}\n\t\t}\n\t\tif flag {\n\t\t\treturn r\n\t\t}\n\t\treturn math.NaN()\n\t}\n\n\treturn a.Fold(ns, axis...)\n\n}", "func (v Volume) Nanolitres() float64 {\n\treturn float64(v / Nanolitre)\n}", "func nanotime() int64", "func nanotime() int64", "func nanotime() int64", "func nanotime() int64", "func IsNan(arg float64) bool {\n\treturn math.IsNaN(arg)\n}", "func DivNoNan(scope *Scope, x tf.Output, y tf.Output) (z tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"DivNoNan\",\n\t\tInput: []tf.Input{\n\t\t\tx, y,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (result Result) NaN() Result {\r\n\tresult.AvgDelay = math.NaN()\r\n\tresult.MinDelay = math.NaN()\r\n\tresult.MaxDelay = math.NaN()\r\n\treturn result\r\n}", "func IsNan(f float64) bool {\n\n\treturn math.IsNaN(f)\n}", "func Nanotime() int64 {\n\treturn nanotime()\n}", "func Nanotime() int64 {\n\treturn nanotime()\n}", "func TestFetchNanNumberEndByNonEOF(t *testing.T) {\n\tinputs := [][]byte{[]byte(\"aN \"), []byte(\"aN{\"), []byte(\"aN}\"), []byte(\"aN[\"), []byte(\"aN]\"), []byte(\"aN:\"), []byte(\"aN,\")}\n\texpected := \"NaN\"\n\n\tfor _, input := range inputs {\n\t\tlex := NewLexer(bytes.NewReader(input))\n\t\terr := lex.fetchNanNumber()\n\t\tif err != nil {\n\t\t\tt.Error(err.Error())\n\t\t\treturn\n\t\t}\n\n\t\ttoken := lex.tokens[0]\n\t\tif token.String() != expected {\n\t\t\tt.Errorf(\"unexpected '%s', expecting '%s'\", token.String(), expected)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (sp positiveRealSpace) Inf() float64 {\n\treturn 0\n}", "func NaN32() float32 { return Float32frombits(uvnan32) }", "func (o InstanceDenyMaintenancePeriodTimeOutput) Nanos() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v InstanceDenyMaintenancePeriodTime) *int { return v.Nanos }).(pulumi.IntPtrOutput)\n}", "func isNaN(f float64) bool {\n\treturn f != f\n}", "func isNaN(f float64) bool {\n\treturn f != f\n}", "func naiveMean(i int, j int64, k *int, l *int64, meanValue *float64, w float64, intervallLength int)(){\n\t*meanValue = 6.3\n}", "func (o TransferJobScheduleStartTimeOfDayOutput) Nanos() pulumi.IntOutput {\n\treturn o.ApplyT(func(v TransferJobScheduleStartTimeOfDay) int { return v.Nanos }).(pulumi.IntOutput)\n}", "func Minf(a, b float32) float32", "func (a *Array64) NaNMean(axis ...int) *Array64 {\n\tswitch {\n\tcase a.valAxis(&axis, \"Sum\"):\n\t\treturn a\n\t}\n\treturn a.NaNSum(axis...).Div(a.NaNCount(axis...))\n}", "func isNaN(val string) bool {\n\tif val == nan {\n\t\treturn true\n\t}\n\n\t_, err := strconv.ParseFloat(val, 64)\n\n\treturn err != nil\n}", "func TestFetchNanNumber(t *testing.T) {\n\texpected := \"NaN\"\n\tinput := []byte(\"aN\")\n\tlex := NewLexer(bytes.NewReader(input))\n\terr := lex.fetchNanNumber()\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\n\ttoken := lex.tokens[0]\n\tif token.String() != expected {\n\t\tt.Errorf(\"unexpected '%s', expecting '%s'\", token.String(), expected)\n\t}\n}", "func ReplaceNaNs(data *FilteredData, replacementType NaNReplacement) *FilteredData {\n\t// go does not marshal NaN values properly so make them empty\n\tnumericColumns := make([]int, 0)\n\tfor _, c := range data.Columns {\n\t\tif model.IsNumerical(c.Type) {\n\t\t\tnumericColumns = append(numericColumns, c.Index)\n\t\t}\n\t}\n\n\tif len(numericColumns) > 0 {\n\t\tfor _, r := range data.Values {\n\t\t\tfor _, nc := range numericColumns {\n\t\t\t\tf, ok := r[nc].Value.(float64)\n\t\t\t\tif ok && math.IsNaN(f) {\n\t\t\t\t\tif replacementType == Null {\n\t\t\t\t\t\tr[nc].Value = nil\n\t\t\t\t\t} else if replacementType == EmptyString {\n\t\t\t\t\t\tr[nc].Value = \"\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn data\n}", "func nanChecker(want, got float64) bool {\n\ta, b, c := math.IsNaN(want), math.IsNaN(got), (want == got)\n\treturn (a && b) || (!a && !b && c)\n}", "func (o DurationOutput) Nanos() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v Duration) *int { return v.Nanos }).(pulumi.IntPtrOutput)\n}", "func Benchmark_FindNaNOrInf(b *testing.B) {\n\tfuncs := []taggedMultiBenchVarargsFunc{\n\t\t{\n\t\t\tf: findNaNOrInfSimdSubtask,\n\t\t\ttag: \"SIMD\",\n\t\t},\n\t\t{\n\t\t\tf: findNaNOrInfBitwiseSubtask,\n\t\t\ttag: \"Bitwise\",\n\t\t},\n\t\t{\n\t\t\tf: findNaNOrInfStandardSubtask,\n\t\t\ttag: \"Standard\",\n\t\t},\n\t}\n\trand.Seed(1)\n\tfor _, f := range funcs {\n\t\tmultiBenchmarkVarargs(f.f, f.tag+\"Long\", 100000, func() interface{} {\n\t\t\tmain := make([]float64, 30000)\n\t\t\t// Results were overly influenced by RNG if the number of NaNs/infs in\n\t\t\t// the slice was not controlled.\n\t\t\tfor i := 0; i < 30; i++ {\n\t\t\t\tfor {\n\t\t\t\t\tpos := rand.Intn(len(main))\n\t\t\t\t\tif main[pos] != math.Inf(0) {\n\t\t\t\t\t\tmain[pos] = math.Inf(0)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn float64Args{\n\t\t\t\tmain: main,\n\t\t\t}\n\t\t}, b)\n\t}\n}", "func r_mx(Hstar, fo float64) float64 {\n\treturn 1. / (Hstar/3000. + 100.*fo)\n}", "func (space RealIntervalSpace) Inf() float64 {\n\treturn space.Min\n}", "func Nper(rate decimal.Decimal, pmt decimal.Decimal, pv decimal.Decimal, fv decimal.Decimal, when paymentperiod.Type) (result decimal.Decimal, err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tresult = decimal.Zero\n\t\t\terr = fmt.Errorf(\"%w: %v\", ErrOutOfBounds, r)\n\t\t}\n\t}()\n\tone := decimal.NewFromInt(1)\n\tminusOne := decimal.NewFromInt(-1)\n\tdWhen := decimal.NewFromInt(when.Value())\n\tdRateWithWhen := rate.Mul(dWhen)\n\tz := pmt.Mul(one.Add(dRateWithWhen)).Div(rate)\n\tnumerator := minusOne.Mul(fv).Add(z).Div(pv.Add(z))\n\tdenominator := one.Add(rate)\n\tfloatNumerator, _ := numerator.BigFloat().Float64()\n\tfloatDenominator, _ := denominator.BigFloat().Float64()\n\tlogNumerator := math.Log(floatNumerator)\n\tlogDenominator := math.Log(floatDenominator)\n\tdlogDenominator := decimal.NewFromFloat(logDenominator)\n\tresult = decimal.NewFromFloat(logNumerator).Div(dlogDenominator)\n\treturn result, nil\n}", "func expAvg2N(d []float64, step float64) float64 {\n\ts := 0.\n\t//\tsz := float64(len(d))\n\tm := step\n\tl := len(d) - 1\n\tfor i := range d {\n\t\ts += m * d[l-i]\n\t\tm *= (1 - step)\n\t\t//\tfmt.Printf(\"S = %v M = %v\\n\", s, m)\n\t}\n\treturn s\n}", "func IsNan(scope *Scope, x tf.Output) (y tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"IsNan\",\n\t\tInput: []tf.Input{\n\t\t\tx,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func nd(n int) int {\n\tif n == 0 {\n\t\treturn 1\n\t}\n\treturn int(math.Log10(float64(n))) + 1\n}", "func (o InstanceDenyMaintenancePeriodTimePtrOutput) Nanos() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *InstanceDenyMaintenancePeriodTime) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Nanos\n\t}).(pulumi.IntPtrOutput)\n}", "func (o TransferJobScheduleStartTimeOfDayPtrOutput) Nanos() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *TransferJobScheduleStartTimeOfDay) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Nanos\n\t}).(pulumi.IntPtrOutput)\n}", "func (o InstanceMaintenanceWindowStartTimeOutput) Nanos() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenanceWindowStartTime) *int { return v.Nanos }).(pulumi.IntPtrOutput)\n}", "func (t Time) Nanosecond() int {}", "func Sum(values []float64) float64 {\n\tvar sum float64 = 0.0\n\tfor _, d := range values {\n\t\tif !math.IsNaN(d) {\n\t\t\tsum += d\n\t\t}\n\t}\n\treturn sum\n}", "func (o InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput) Nanos() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTime) *int { return v.Nanos }).(pulumi.IntPtrOutput)\n}", "func (o InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTimeOutput) Nanos() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenancePolicyWeeklyMaintenanceWindowStartTime) *int { return v.Nanos }).(pulumi.IntPtrOutput)\n}", "func SomenteNumeros(cnpj string) string {\n\tr := regexp.MustCompile(\"[0-9]+\")\n\treturn strings.Join(r.FindAllString(cnpj, -1), \"\")\n}", "func NaN32() float32 {\n\treturn float32(math.NaN())\n}", "func trailingZeroes(n int) int {\n\tif n < 5 {\n\t\treturn 0\n\t}\n\tfives := n / 5\n\n\treturn fives + trailingZeroes(n/5)\n}", "func (sp booleanSpace) Inf() float64 {\n\treturn 0\n}", "func TestNoPanic(t *testing.T) {\n\ts := NewGKArray(testEps)\n\tfor i := 0; i < 2*int(1/s.epsilon); i++ {\n\t\ts.Add(float64(i))\n\t\tassert.NotPanics(t, func() { s.Quantile(0.9) })\n\t}\n}", "func isNaN64(f float64) bool { return f != f }", "func HitungNA(clo1, clo2, clo3 float64) float64 {\r\n\r\n\tvar Total float64\r\n\tTotal = (clo1 * 20 / 100) + (clo2 * 35 / 100) + (clo3 * 45 / 100)\r\n\r\n\treturn Total\r\n\r\n}", "func (NilTimer) Mean() float64 { return 0.0 }", "func Infoln(v ...interface{}) {\n\tlog.Infoln(v...)\n}", "func (o DurationResponseOutput) Nanos() pulumi.IntOutput {\n\treturn o.ApplyT(func(v DurationResponse) int { return v.Nanos }).(pulumi.IntOutput)\n}", "func (o DurationPtrOutput) Nanos() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *Duration) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Nanos\n\t}).(pulumi.IntPtrOutput)\n}", "func parseTemp(t float64) float64 {\n\treturn (t * 1.8) + 32\n}", "func posInf() float64 {\n\treturn math.Inf(1) // argument specifies positive infinity\n}", "func dagiFNV(r, p *node)", "func (*BigInt) IsNaN() bool {\n\treturn false\n}", "func JN(T, fmin, fmax, R float64) float64 {\n\tconst k_b = 1.38064852e-23\n\treturn math.Sqrt(4 * k_b * (273.15 + T) * (fmax - fmin) * R)\n}", "func (Integer) IsNaN() bool {\n\treturn false\n}", "func JNO(r operand.Op) { ctx.JNO(r) }", "func formatNano(nanosec uint, n int, trim bool) []byte {\n\tu := nanosec\n\tvar buf [9]byte\n\tfor start := len(buf); start > 0; {\n\t\tstart--\n\t\tbuf[start] = byte(u%10 + '0')\n\t\tu /= 10\n\t}\n\n\tif n > 9 {\n\t\tn = 9\n\t}\n\tif trim {\n\t\tfor n > 0 && buf[n-1] == '0' {\n\t\t\tn--\n\t\t}\n\t\tif n == 0 {\n\t\t\treturn buf[:0]\n\t\t}\n\t}\n\treturn buf[:n]\n}", "func Mean(values []float64) float64 {\n\tvar sum float64 = 0.0\n\tcount := 0\n\tfor _, d := range values {\n\t\tif !math.IsNaN(d) {\n\t\t\tsum += d\n\t\t\tcount++\n\t\t}\n\t}\n\treturn sum / float64(count)\n}", "func (o InstanceMaintenanceWindowStartTimePtrOutput) Nanos() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *InstanceMaintenanceWindowStartTime) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Nanos\n\t}).(pulumi.IntPtrOutput)\n}", "func (dt DateTime) Nanosecond() int {\n\treturn dt.src.Nanosecond()\n}", "func DivZeroExp(exp string) bool {\n var index int = strings.Index(exp, \"/\")\n for index != -1 {\n var divisor string = exp[index+1:index+2]\n if divisor == \"(\" {\n divisor = exp[index+1:FindClosingParen(exp, index+1)+1]\n } else {\n var end int = index + 2\n for end < len(exp) && strings.Index(numbers, string(exp[end])) != -1 {\n end++\n }\n divisor = exp[index+1:end]\n }\n\n var result string = Pemdas(divisor)\n if result == \"Infinity\" || NotateToDouble(result) == 0 {\n return true\n }\n\n index = strings.Index(exp[index + 1:], \"/\")\n }\n\n return false\n}", "func JNZ(r operand.Op) { ctx.JNZ(r) }", "func (s Series) IsNaN() []bool {\n\tret := make([]bool, s.Len())\n\tfor i := 0; i < s.Len(); i++ {\n\t\tret[i] = s.elements.Elem(i).IsNaN()\n\t}\n\treturn ret\n}", "func (xt XSDTime) Nanosecond() int {\n\treturn xt.innerTime.Nanosecond()\n}", "func Nanosec() int64 {\n\treturn internal.Syscall0r64(NANOSEC)\n}", "func MulNoNan(scope *Scope, x tf.Output, y tf.Output) (z tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"MulNoNan\",\n\t\tInput: []tf.Input{\n\t\t\tx, y,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func Infinity() Point {\n\treturn Point{1, 0}\n}", "func calcSolarNoon(longitude float64, equationOfTime []float64, utcOffset float64) (solarNoon []float64) {\n\tfor index := 0; index < len(equationOfTime); index++ {\n\t\ttemp := (720.0 - 4.0*longitude - equationOfTime[index] + utcOffset*60.0) * 60.0\n\t\tsolarNoon = append(solarNoon, temp)\n\t}\n\treturn\n}", "func moment(data []float64, c float64, p float64, N int) float64 {\n\n\tsum := 0.0\n\tfor i := 0; i < N; i++ {\n\t\tsum += math.Pow(data[i]-c, p)\n\t}\n\n\treturn sum / float64(N)\n}", "func naiveDFT(x []complex128) (y []complex128) {\n\ty = make([]complex128, len(x))\n\tdt := -2 * math.Pi / float64(len(x))\n\tfor i := range x {\n\t\targ1 := float64(i) * dt\n\t\tfor k, xv := range x {\n\t\t\targ2 := float64(k) * arg1\n\t\t\ty[i] += complex(math.Cos(arg2), math.Sin(arg2)) * xv\n\t\t}\n\t}\n\treturn y\n}", "func NSEpow(o, s []float64, p float64) float64 {\n\tvar n, d float64\n\tom, _ := Meansd(o)\n\tif len(o) != len(s) {\n\t\tlog.Fatalf(\"NSEpow array lengths not matching %d %d\\n\", len(o), len(s))\n\t}\n\tfor i := range o {\n\t\tif !math.IsNaN(s[i]) && !math.IsNaN(o[i]) {\n\t\t\tn += math.Pow(s[i]-o[i], p)\n\t\t\td += math.Pow(o[i]-om, p)\n\t\t}\n\t}\n\treturn 1. - n/d\n}", "func parseNullableFloat64(content []byte, aggErr *AggregateError) *float64 {\n if len(content) == 0 {\n return nil\n }\n result := parseFloat64(content, aggErr)\n return &result\n}", "func recip(val float64) float64 {\n\treturn 1 / val\n}", "func nulls(i int) string {\n\ts := \"\"\n\tfor j := 0; j < i; j++ {\n\t\ts += zero\n\t}\n\treturn s\n}", "func Nanosec() int64 {\n\treturn syscall.Nanosec()\n}", "func _MeasurementNoOp() {\n\tvar x [1]struct{}\n\t_ = x[Frequency-(1)]\n\t_ = x[Current-(2)]\n\t_ = x[CurrentL1-(3)]\n\t_ = x[CurrentL2-(4)]\n\t_ = x[CurrentL3-(5)]\n\t_ = x[Voltage-(6)]\n\t_ = x[VoltageL1-(7)]\n\t_ = x[VoltageL2-(8)]\n\t_ = x[VoltageL3-(9)]\n\t_ = x[Power-(10)]\n\t_ = x[PowerL1-(11)]\n\t_ = x[PowerL2-(12)]\n\t_ = x[PowerL3-(13)]\n\t_ = x[ImportPower-(14)]\n\t_ = x[ImportPowerL1-(15)]\n\t_ = x[ImportPowerL2-(16)]\n\t_ = x[ImportPowerL3-(17)]\n\t_ = x[ExportPower-(18)]\n\t_ = x[ExportPowerL1-(19)]\n\t_ = x[ExportPowerL2-(20)]\n\t_ = x[ExportPowerL3-(21)]\n\t_ = x[ReactivePower-(22)]\n\t_ = x[ReactivePowerL1-(23)]\n\t_ = x[ReactivePowerL2-(24)]\n\t_ = x[ReactivePowerL3-(25)]\n\t_ = x[ApparentPower-(26)]\n\t_ = x[ApparentPowerL1-(27)]\n\t_ = x[ApparentPowerL2-(28)]\n\t_ = x[ApparentPowerL3-(29)]\n\t_ = x[Cosphi-(30)]\n\t_ = x[CosphiL1-(31)]\n\t_ = x[CosphiL2-(32)]\n\t_ = x[CosphiL3-(33)]\n\t_ = x[THD-(34)]\n\t_ = x[THDL1-(35)]\n\t_ = x[THDL2-(36)]\n\t_ = x[THDL3-(37)]\n\t_ = x[Sum-(38)]\n\t_ = x[SumT1-(39)]\n\t_ = x[SumT2-(40)]\n\t_ = x[SumL1-(41)]\n\t_ = x[SumL2-(42)]\n\t_ = x[SumL3-(43)]\n\t_ = x[Import-(44)]\n\t_ = x[ImportT1-(45)]\n\t_ = x[ImportT2-(46)]\n\t_ = x[ImportL1-(47)]\n\t_ = x[ImportL2-(48)]\n\t_ = x[ImportL3-(49)]\n\t_ = x[Export-(50)]\n\t_ = x[ExportT1-(51)]\n\t_ = x[ExportT2-(52)]\n\t_ = x[ExportL1-(53)]\n\t_ = x[ExportL2-(54)]\n\t_ = x[ExportL3-(55)]\n\t_ = x[ReactiveSum-(56)]\n\t_ = x[ReactiveSumT1-(57)]\n\t_ = x[ReactiveSumT2-(58)]\n\t_ = x[ReactiveSumL1-(59)]\n\t_ = x[ReactiveSumL2-(60)]\n\t_ = x[ReactiveSumL3-(61)]\n\t_ = x[ReactiveImport-(62)]\n\t_ = x[ReactiveImportT1-(63)]\n\t_ = x[ReactiveImportT2-(64)]\n\t_ = x[ReactiveImportL1-(65)]\n\t_ = x[ReactiveImportL2-(66)]\n\t_ = x[ReactiveImportL3-(67)]\n\t_ = x[ReactiveExport-(68)]\n\t_ = x[ReactiveExportT1-(69)]\n\t_ = x[ReactiveExportT2-(70)]\n\t_ = x[ReactiveExportL1-(71)]\n\t_ = x[ReactiveExportL2-(72)]\n\t_ = x[ReactiveExportL3-(73)]\n\t_ = x[DCCurrent-(74)]\n\t_ = x[DCVoltage-(75)]\n\t_ = x[DCPower-(76)]\n\t_ = x[HeatSinkTemp-(77)]\n\t_ = x[DCCurrentS1-(78)]\n\t_ = x[DCVoltageS1-(79)]\n\t_ = x[DCPowerS1-(80)]\n\t_ = x[DCEnergyS1-(81)]\n\t_ = x[DCCurrentS2-(82)]\n\t_ = x[DCVoltageS2-(83)]\n\t_ = x[DCPowerS2-(84)]\n\t_ = x[DCEnergyS2-(85)]\n\t_ = x[DCCurrentS3-(86)]\n\t_ = x[DCVoltageS3-(87)]\n\t_ = x[DCPowerS3-(88)]\n\t_ = x[DCEnergyS3-(89)]\n\t_ = x[DCCurrentS4-(90)]\n\t_ = x[DCVoltageS4-(91)]\n\t_ = x[DCPowerS4-(92)]\n\t_ = x[DCEnergyS4-(93)]\n\t_ = x[ChargeState-(94)]\n\t_ = x[BatteryVoltage-(95)]\n\t_ = x[PhaseAngle-(96)]\n}", "func Infoln(val ...interface{}) error {\n\tlog := logger.Get()\n\tlog.Infoln(val...)\n\treturn nil\n}", "func (z *Big) setNaN(c Condition, f form, p Payload) *Big {\n\tz.form = f\n\tz.compact = uint64(p)\n\tz.Context.Conditions |= c\n\tif z.Context.OperatingMode == Go {\n\t\tpanic(ErrNaN{Msg: z.Context.Conditions.String()})\n\t}\n\treturn z\n}", "func (x *Big) IsNaN(quiet int) bool {\n\treturn quiet >= 0 && x.form&qnan == qnan || quiet <= 0 && x.form&snan == snan\n}", "func RegulateTemp (value float64) float64{\n\n\tif value> 22 {\n\t\treturn (22 * 100)/ value\n\t}else if value < 22{\n return 100.0\n\t}\n\n\treturn 0.0\n}", "func NilFloat() Float {\n\treturn Float{0, false}\n}", "func (o DurationResponsePtrOutput) Nanos() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *DurationResponse) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Nanos\n\t}).(pulumi.IntPtrOutput)\n}", "func TestEvaluatorMissingValue(t *testing.T) {\n\tvar values = make(map[string]int)\n\texpression := \"value\"\n\n\t_, err := evaluator.Evaluate(expression, values)\n\n\tassert.Error(t, err, \"error is expected\")\n}", "func (s *Series) CountOfNA() int {\n\tcount := 0\n\tfor _, val := range s.Data {\n\t\tif val == nil {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}", "func naiveDFTreal(x []float64) (y []complex128) {\n\ty = make([]complex128, len(x))\n\tdt := -2 * math.Pi / float64(len(x))\n\tfor i := range x {\n\t\targ1 := float64(i) * dt\n\t\tfor k, xv := range x {\n\t\t\targ2 := float64(k) * arg1\n\t\t\ty[i] += complex(xv*math.Cos(arg2), xv*math.Sin(arg2))\n\t\t}\n\t}\n\treturn y[:len(x)/2+1]\n}", "func (dt *DateTime) Nanosecond() *Number {\n\topChain := dt.chain.enter(\"Nanosecond()\")\n\tdefer opChain.leave()\n\n\tif opChain.failed() {\n\t\treturn newNumber(opChain, float64(0))\n\t}\n\n\treturn newNumber(opChain, float64(dt.value.Nanosecond()))\n}", "func (x *Float) IsInf() bool {}", "func pi(n int) float64 {\n\tvar x float64\n\tvar a = 1\n\tvar b = 1\n\tfor i := 0; i < n; i++ {\n\t\tx += float64(a) / float64(b)\n\t\ta *= -1\n\t\tb += 2\n\t}\n\treturn x * 4.0\n}", "func main() {\n\tfmt.Println(missingNumber([]int{0}))\n\tfmt.Println(missingNumber([]int{0, 1}))\n}", "func (p *Parser) NullFloat64(i int, context string) Float64 {\n\ts := p.String(i, context)\n\tif p.err != nil {\n\t\treturn Float64{}\n\t}\n\tif s == \"\" {\n\t\treturn Float64{}\n\t}\n\tv, err := strconv.ParseFloat(s, 64)\n\tif err != nil {\n\t\tp.SetErr(context, s)\n\t\treturn Float64{}\n\t}\n\treturn Float64{Value: v, Valid: true}\n}", "func TestFloatNull(t *testing.T) {\n\tclient := newQueriesClient(t)\n\tresult, err := client.FloatNull(context.Background(), nil)\n\trequire.NoError(t, err)\n\trequire.Zero(t, result)\n}", "func (a *Array64) NaNCount(axis ...int) *Array64 {\n\tif a.valAxis(&axis, \"NaNCount\") {\n\t\treturn a\n\t}\n\n\tnc := func(d []float64) (r float64) {\n\t\tfor _, v := range d {\n\t\t\tif !math.IsNaN(v) {\n\t\t\t\tr++\n\t\t\t}\n\t\t}\n\t\treturn r\n\t}\n\n\treturn a.Fold(nc, axis...)\n}", "func encodeFloats(data map[string]any) {\n\tfor k, v := range data {\n\t\tswitch v := v.(type) {\n\t\tcase float64:\n\t\t\tif math.IsNaN(v) || math.IsInf(v, 0) {\n\t\t\t\tdata[k] = nil\n\t\t\t}\n\t\t}\n\t}\n}", "func (dt DateTime) Nanosecond() int {\n\treturn dt.Time().Nanosecond()\n}", "func Momentum(n int) func(s []float64) []float64 {\n\treturn func(s []float64) (res []float64) {\n\t\tf := Skip(n)(s)\n\t\tres = make([]float64, len(f))\n\t\tfor i := range res {\n\t\t\tres[i] = f[i]/s[i] - 1\n\t\t}\n\n\t\treturn\n\t}\n}", "func (a *Array64) Nonzero(axis ...int) *Array64 {\n\tif a.valAxis(&axis, \"Nonzero\") {\n\t\treturn a\n\t}\n\n\treturn a.Map(func(d float64) float64 {\n\t\tif d == 0 {\n\t\t\treturn 0\n\t\t}\n\t\treturn 1\n\t}).Sum(axis...)\n}" ]
[ "0.602442", "0.58442634", "0.5628861", "0.56243914", "0.55352783", "0.55352783", "0.55352783", "0.55352783", "0.5477595", "0.5387952", "0.5378903", "0.5312592", "0.52907044", "0.52907044", "0.52536094", "0.5228146", "0.5210892", "0.5192936", "0.5192836", "0.5192836", "0.5129684", "0.5119692", "0.50891507", "0.50829613", "0.50723016", "0.5070217", "0.5065093", "0.50431216", "0.5039759", "0.50165457", "0.50154424", "0.5009955", "0.4981591", "0.4958172", "0.4944439", "0.49395725", "0.49136388", "0.49020612", "0.489799", "0.48833823", "0.48821366", "0.48750034", "0.48750034", "0.48675478", "0.48619005", "0.48580202", "0.48555353", "0.484155", "0.48324353", "0.48305535", "0.48203075", "0.47866753", "0.47830993", "0.47702512", "0.4758619", "0.47579315", "0.47570753", "0.47569522", "0.47567484", "0.474523", "0.47390795", "0.4733964", "0.473174", "0.47308522", "0.47224903", "0.47120064", "0.46845117", "0.46314865", "0.46300358", "0.46221492", "0.46213147", "0.46144757", "0.46078715", "0.45990503", "0.45989445", "0.45967135", "0.45880625", "0.4583485", "0.4567007", "0.4564724", "0.45595378", "0.45517495", "0.45510498", "0.455059", "0.4548045", "0.4547688", "0.4547583", "0.4547473", "0.45471954", "0.4542184", "0.45359108", "0.45050377", "0.4500752", "0.44999436", "0.44916752", "0.44807282", "0.4476989", "0.44734642", "0.44727492", "0.4465442", "0.4459521" ]
0.0
-1
/ RottenFruit : 3 RottenFruit2 : 3
func StepsOfKnightUtil(size int, currCol int, currRow int, traversed [][]int, dist int) { // Range check if currCol < 0 || currCol >= size || currRow < 0 || currRow >= size { return } // Traverse if not already traversed. if traversed[currCol][currRow] <= dist { return } dir := [][]int{{-2, -1}, {-2, 1}, {2, -1}, {2, 1}, {-1, -2}, {1, -2}, {-1, 2}, {1, 2}} traversed[currCol][currRow] = dist for i := 0; i < 8; i++ { x := currCol + dir[i][0] y := currRow + dir[i][1] StepsOfKnightUtil(size, x, y, traversed, dist+1) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func printTally(wrapped, dropped int64) {\n\tfmt.Println(\"\\n--------------------------------------\")\n\tfmt.Printf(\"%-10s : %02d\\n\", \"Total\", chocolateCount)\n\tfmt.Printf(\"%-10s : %02d\\n\", \"Wrapped\", wrapped)\n\tfmt.Printf(\"%-10s : %02d\\n\", \"Dropped\", dropped)\n\tfmt.Println(\"--------------------------------------\")\n}", "func totalFruit(fruits []int) int {\n\tpairs := make([]pair, 0)\n\tif len(fruits) > 0 {\n\t\tcrtPair := newPair(0)\n\t\tcrtPair.fruits[fruits[0]] = 1\n\t\tfor i := 1; i < len(fruits); i++ {\n\t\t\tfruit := fruits[i]\n\t\t\tct, present := crtPair.fruits[fruit]\n\t\t\tif present {\n\t\t\t\tcrtPair.fruits[fruit] = ct + 1\n\t\t\t} else {\n\t\t\t\tif len(crtPair.fruits) == 1 {\n\t\t\t\t\tcrtPair.fruits[fruit] = 1\n\t\t\t\t} else {\n\t\t\t\t\t// we have encountered a new fruit, start the new pair\n\t\t\t\t\tj := i - 1\n\t\t\t\t\tpreviousFruit := fruits[j]\n\t\t\t\t\tpreviousFruitCount := 0\n\t\t\t\t\tfor j > -1 && fruits[j] == previousFruit {\n\t\t\t\t\t\tpreviousFruitCount++\n\t\t\t\t\t\tj--\n\t\t\t\t\t}\n\t\t\t\t\t// add the current pair\n\t\t\t\t\tpairs = append(pairs, *crtPair)\n\t\t\t\t\t// create a new pair\n\t\t\t\t\tcrtPair = newPair(i)\n\t\t\t\t\tcrtPair.fruits[previousFruit] = previousFruitCount\n\t\t\t\t\tcrtPair.fruits[fruit] = 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tpairs = append(pairs, *crtPair)\n\t}\n\treturn findMaxCount(pairs)\n}", "func fungsilen() {\n\n\tvar fruits = []string{\"apple\", \"grape\", \"banana\", \"melon\"}\n\tfmt.Println(\"index is: \", len(fruits))\n}", "func (self *Tween) Repeat2O(total int, repeat int, index int) *Tween{\n return &Tween{self.Object.Call(\"repeat\", total, repeat, index)}\n}", "func repeatWord(word string, repetitions int) string {\n\tvar response string\n\tvar i int\n\n\tif repetitions < 0 {\n\t\tlog.Fatal(\"Can not repeat a word a negative number of times\\n\")\n\t} else if repetitions == 0 {\n\t\treturn \"\"\n\t}\n\n\t// we are now dealing with the case that we must\n\t// repeat the word one, or more, times\n\tresponse = word\n\tfor i = 1; i < repetitions; i++ {\n\t\tresponse = fmt.Sprintf(\"%s %s\", response, word)\n\t}\n\n\treturn response\n}", "func Grapple(i *InputHandler, b *models.Box) {\n\ti.NewRope = true\n\ti.DestroyRope = false\n\tb.State = models.GRAPPLING\n}", "func (self *Tween) RepeatCounter() int{\n return self.Object.Get(\"repeatCounter\").Int()\n}", "func main() {\n\tfmt.Println(first, second)\n\n\t//fmt.Println(first, second, third) // in case example number 5 only\n\n\t//fmt.Println(first, second, third, fourth) // in case example number 6 (the last one) only\n}", "func PrintDiff(add, remove []domain.UserAudience) {\n\tfmt.Println(\"************* Count add *************\")\n\tfmt.Println(len(add))\n\tfmt.Println(\"************* Array add *************\")\n\tfmt.Println(add)\n\tfmt.Println(\"************ Count remove ***********\")\n\tfmt.Println(len(remove))\n\tfmt.Println(\"************ Array remove ***********\")\n\tfmt.Println(remove)\n}", "func RepeatMe(words ...string) {\n\tfmt.Println(words)\n}", "func totalFruit(tree []int) int {\n\tif len(tree) <= 2 {\n\t\treturn len(tree)\n\t}\n\tm := make(map[int]int)\n\tres := 0\n\t// 以下的code是典型的滑动窗口的写法\n\tstart := 0\n\tfor end := 0; end < len(tree); end++ {\n\t\tif _, ok := m[tree[end]]; ok {\n\t\t\tm[tree[end]] += 1\n\t\t} else {\n\t\t\tm[tree[end]] = 1\n\t\t}\n\t\tfor len(m) > 2 && start < end {\n\t\t\tm[tree[start]] -= 1\n\t\t\tif m[tree[start]] == 0 {\n\t\t\t\tdelete(m, tree[start])\n\t\t\t}\n\t\t\tstart++\n\t\t}\n\t\tif (end - start + 1) > res {\n\t\t\tres = end - start + 1\n\t\t}\n\t}\n\treturn res\n}", "func (self *Tween) Repeat1O(total int, repeat int) *Tween{\n return &Tween{self.Object.Call(\"repeat\", total, repeat)}\n}", "func infoPhotosQuantity() {\n\tfmt.Println(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n\tfmt.Printf(\"! SE ENCONTRARON %v FOTOS\\n\", len(store))\n\tfmt.Println(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n}", "func ExampleRepeat() {\n\tsum := Repeat(\"a\", 5)\n\tfmt.Println(sum)\n\t// Output: aaaaa\n}", "func Verse(v int) string {\n\t// if it's the final verse, return it alone\n\tif v == len(lyrics) {\n\t\treturn lyrics[v-1].item\n\t}\n\n\t// otherwise return the item plus the list plus the list of all previous stanzas\n\tr := lyrics[v-1].item\n\tfor i := v - 1; i >= 0; i-- {\n\t\tr += \"\\n\" + lyrics[i].list\n\t}\n\treturn r\n}", "func Teapot(w http.ResponseWriter, message ...interface{}) {\n\tboom(w, 418, message...)\n}", "func getIceCream(w http.ResponseWriter, r *http.Request) {\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\tparams := mux.Vars(r) // Gets params\r\n\tflavourid_int,_ := strconv.Atoi(params[\"flavourid\"])\r\n\t// Loop through flavours and find one with the flavourId from the params\r\n\tfor _, item := range flavours {\r\n\t\tif item.FlavourId == flavourid_int {\r\n\t\t\tjson.NewEncoder(w).Encode(item)\r\n\t\t\treturn\r\n\t\t}\r\n\t}\r\n\tjson.NewEncoder(w).Encode(&IceCream{})\r\n}", "func formatUserChoice(playlists []map[string]interface{}) (string, error) {\n\ti := 1\n\tres := \"\"\n\tfor _, v := range playlists {\n\t\tres += strconv.Itoa(i) + \")\" + v[\"name\"].(string) + \"\\n\"\n\t\ti++\n\t}\n\tif res == \"\" {\n\t\treturn res, errors.New(\"Can't format user choice\")\n\t}\n\treturn res, nil\n}", "func RottenFruitUtil(arr [][]int, maxCol int, maxRow int, currCol int, currRow int, traversed [][]int, day int) {\n\tif currCol < 0 || currCol >= maxCol || currRow < 0 || currRow >= maxRow {\n\t\treturn\n\t}\n\t// Traversable and rot if not already rotten.\n\tif traversed[currCol][currRow] <= day || arr[currCol][currRow] == 0 {\n\t\treturn\n\t}\n\n\tdir := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}\n\ttraversed[currCol][currRow] = day // Update rot time.\n\tfor i := 0; i < 4; i++ {\n\t\tx := currCol + dir[i][0]\n\t\ty := currRow + dir[i][1]\n\t\tRottenFruitUtil(arr, maxCol, maxRow, x, y, traversed, day+1)\n\t}\n}", "func Zap(f Food) {\n\tfmt.Printf(\"I hate %ss!\", f.Name)\n\n}", "func Teapot(message ...interface{}) Err {\n\treturn Boomify(http.StatusTeapot, message...)\n}", "func TestApploffer1(t *testing.T) {\n\tclearBasket()\n\n\tbasket.Basket.AddItem(\"AP1\")\n\tbasket.Basket.AddItem(\"AP1\")\n\n\tvar totalItem, appleCount int64\n\n\tCos.PrintBills()\n\n\tfor _, be := range Cos.bill {\n\t\ttotalItem++\n\n\t\tif be.prodCode == \"AP1\" {\n\t\t\tappleCount++\n\t\t}\n\t}\n\n\tif totalItem != appleCount {\n\t\tt.Errorf(\"ordered 2 apple. But found: %d\", appleCount)\n\t}\n}", "func printTopK(tags []string, data map[string]float64,topKWord int){\n // i :=1\n // for _,t := range tags{\n // fmt.Printf(\" %s :%v \\n\", t,data[t])\n // // i++\n // }\n\n fmt.Println(strings.Join(tags, \"/ \"))\n }", "func (s *Scanner) identRest() {\n\tswitch {\n\tcase s.acceptIf(text.IdentRest):\n\t\ts.identRest()\n\tcase s.accept('_'):\n\t\ts.identOrOperatorRest()\n\tcase s.acceptIf(text.IsIdentifierPart):\n\t\ts.identRest()\n\t}\n}", "func redact(match HTTPMatch, value interface{}, locationPrefix string) interface{} {\n\tif match.HasBodyWhitelistMatch(locationPrefix) {\n\t\treturn value\n\t}\n\n\tswitch typedValue := value.(type) {\n\tcase map[string]interface{}:\n\t\tm := make(map[string]interface{})\n\t\tfor k, v := range typedValue {\n\t\t\tm[k] = redact(match, v, locationPrefix+\".\"+k)\n\t\t}\n\t\treturn m\n\tcase []interface{}:\n\t\tm := make([]interface{}, len(typedValue))\n\t\tfor k, v := range typedValue {\n\t\t\tm[k] = redact(match, v, locationPrefix+\"[\"+strconv.Itoa(k)+\"]\")\n\t\t}\n\t\treturn m\n\tcase float64:\n\t\treturn RedactedNumber\n\tcase string:\n\t\treturn RedactedStr\n\tcase bool:\n\t\treturn RedactedBool\n\tcase nil:\n\t\treturn nil\n\tdefault:\n\t\treturn nil\n\t}\n}", "func deleteIceCream(w http.ResponseWriter, r *http.Request) {\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\tparams := mux.Vars(r)\r\n\tflavourid_int,_ := strconv.Atoi(params[\"flavourid\"])\r\n\tfor index, item := range flavours {\r\n\t\tif item.FlavourId == flavourid_int {\r\n\t\t\tflavours = append(flavours[:index], flavours[index+1:]...)\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n\tjson.NewEncoder(w).Encode(flavours)\r\n}", "func TugOfWars(arr []int) (ans1, ans2 []int) {\n\tfirst := []int{}\n\tsecond := []int{}\n\ttugHelper(arr, first, second, 0, 0, 0)\n\treturn ans1, ans2\n}", "func AutoG(w http.ResponseWriter, req *http.Request) {\n\tvar frase Frase\n\t_ = json.NewDecoder(req.Body).Decode(&frase)\n\tfraseNooized := \"\"\n\trand.Seed(time.Now().UnixNano())\n\tnum := rand.Intn(3)\n\tswitch num {\n\tcase 0:\n\t\tfraseNooized = NDecorator(frase.Testo)\n\tcase 1:\n\t\tfraseNooized = GDecorator(frase.Testo)\n\tdefault:\n\t\tfraseNooized = EDecorator(frase.Testo)\n\t}\n\tjson.NewEncoder(w).Encode(fraseNooized)\n}", "func slicecap() {\n\n\tvar fruits = []string{\"apple\", \"grape\", \"banana\", \"melon\"}\n\tfmt.Println(\"index len is: \", len(fruits))\n\tfmt.Println(\"index cap is: \", cap(fruits))\n\n\tvar aFruits = fruits[0:3]\n\tfmt.Println(\"index len is: \", len(aFruits))\n\tfmt.Println(\"index cap is: \", cap(aFruits))\n\n\tvar bFruits = fruits[1:4]\n\tfmt.Println(\"index len is: \", len(bFruits))\n\tfmt.Println(\"index cap is: \", cap(bFruits))\n}", "func createIceCream(w http.ResponseWriter, r *http.Request) {\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\tvar IceCream IceCream\r\n\t_ = json.NewDecoder(r.Body).Decode(&IceCream)\r\n\tIceCream.FlavourId = genNextId()\r\n\tflavours = append(flavours, IceCream)\r\n\tjson.NewEncoder(w).Encode(IceCream)\r\n}", "func RobotLingo() string {\n\n println(\"Affirmatives\")\n println(\"Affirmative\")\n println(\"affirmative\")\n println(\"affirmative\")\n\n println(\"lickMyBatteries\")\n println(\"LickMyBattery\")\n println(\"lickMyBattery\")\n println(\"lick_my_battery\")\n\n println(\"exterminate_the_humans\")\n println(\"Exterminatethehuman\")\n println(\"exterminatethehuman\")\n println(\"exterminate_the_human\")\n\n}", "func betterRestaurant() {\r\n\tvar wg sync.WaitGroup\r\n\r\n\twg.Add(1)\r\n\tgo func() {\r\n\t\tbetterChef(\"炒饭\")\r\n\t\twg.Done()\r\n\t}()\r\n\r\n\twg.Add(1)\r\n\tgo func() {\r\n\t\tbetterChef(\"炒时蔬\")\r\n\t\twg.Done()\r\n\t}()\r\n\r\n\twg.Add(1)\r\n\tgo func() {\r\n\t\tbetterChef(\"水煮肉片\")\r\n\t\twg.Done()\r\n\t}()\r\n\r\n\twg.Wait()\r\n}", "func (self *Tween) Repeat(total int) *Tween{\n return &Tween{self.Object.Call(\"repeat\", total)}\n}", "func Red(x ...interface{}) {\n\tred.Println(x...)\n}", "func amigos(res http.ResponseWriter, req *http.Request) {\n\trows, err := db.Query(`SELECT amigoName FROM amigos;`)\n\tcheck(err)\n\tdefer rows.Close()\n\n\t// data to be used in query\n\tvar s, name string\n\ts = \"RETRIEVED RECORDS:\\n\"\n\n\t// query\n\tfor rows.Next() {\n\t\terr = rows.Scan(&name)\n\t\tcheck(err)\n\t\ts += name + \"\\n\"\n\t}\n\tfmt.Fprintln(res, s)\n}", "func TestAddManyViewMany(t *testing.T) {\n\ttarget := teaser.New()\n\tm1id := target.Add(\"msg1\")\n\tm2id := target.Add(\"msg2\")\n\tm3id := target.Add(\"msg3\")\n\n\tm2Hash, m1vid := target.View()\n\tassertMessageId(m1id, m1vid, t)\n\tassertMessageHash(\"msg2\", m2Hash, t)\n\n\tm3Hash, m2vid := target.View()\n\tassertMessageId(m2id, m2vid, t)\n\tassertMessageHash(\"msg3\", m3Hash, t)\n\n\tnextHash, m3vid := target.View()\n\tassertMessageId(m3id, m3vid, t)\n\tassertMessageHash(\"\", nextHash, t)\n\n}", "func Repeat(word string, repeat int) string {\n\tvar result string\n\n\tif repeat == 0 {\n\t\trepeat = repeatCount\n\t}\n\n\tfor i := 0; i < repeat; i++ {\n\t\tresult += word\n\t}\n\treturn result\n}", "func addQuantity(ingredient Ingredient, quantity int) Ingredient {\n\tingredient.Quantity = ingredient.Quantity + quantity\n\treturn ingredient\n}", "func (a AnalysisServer) TopRestaurants(ctx stdctx.Context, quantity *pb.Quantity) (*pb.RestaurantList, error) {\n restaurantList, err := db.GetTopRestaurants(\"Restaurants\", quantity.Size)\n if err != nil {\n return &pb.RestaurantList{}, err\n }\n return restaurantListToPb(restaurantList), nil\n}", "func indexHandler1( w http.ResponseWriter, r *http.Request){\n\n\treg, err := regexp.Compile(\"[^a-zA-Z0-9]+\")\n\tfmt.Fprintf(w, \"word\"+\" \"+\"count\")\n\tfmt.Fprintf(w,\"\\n----------\\n\")\n\tfor key, val := range wordcountMap {\n\n\t\tfmt.Println(strings.TrimRight(key, \" \"), val)\n\t\tfmt.Fprintf(w, reg.ReplaceAllString(key, \"\")+\" \"+strconv.Itoa(val))\n\t\tfmt.Fprintf(w,\"\\n\")\n\n\t}\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}", "func key(keys ...string) string {\n\treturn fmt.Sprintf(\"%s:%s\", \"mailimage\", strings.Join(keys, \":\"))\n}", "func spacer(level int) string {\n\treturn strings.Repeat(\" \", level)\n}", "func printIDs(sectionName string, matches map[string]string) {\n\tfmt.Printf(\"%v:\\n\", sectionName)\n\tfor id, title := range matches {\n\t\tfmt.Printf(\"[%v] %v\\n\", id, title)\n\t}\n\tfmt.Printf(\"\\n\\n\")\n}", "func RETFW(i operand.Op) { ctx.RETFW(i) }", "func CountPrintln(f ...interface{}) {\n\tcount++\n\tfmt.Printf(\"%d - \", count)\n\tfmt.Println(f...)\n}", "func TestAddTwoDeleteFirst(t *testing.T) {\n\ttarget := teaser.New()\n\tm1id := target.Add(\"msg1\")\n\tm2id := target.Add(\"msg2\")\n\n\t{\n\t\tdeleted := target.Delete(m1id)\n\t\tassertDeleted(m1id, deleted, t)\n\t}\n\n\t{\n\t\tnextHash, m2vid := target.View()\n\t\tassertMessageId(m2id, m2vid, t)\n\t\tassertMessageHash(\"\", nextHash, t)\n\t}\n}", "func TestAddOnceViewMany(t *testing.T) {\n\ttarget := teaser.New()\n\tm1id := target.Add(\"msg1\")\n\n\t{\n\t\tnextHash, m1vid := target.View()\n\t\tassertMessageId(m1id, m1vid, t)\n\t\tassertMessageHash(\"\", nextHash, t)\n\t}\n\n\t{\n\t\tnextHash, nextvid := target.View()\n\t\tassertMessageId(\"\", nextvid, t)\n\t\tassertMessageHash(\"\", nextHash, t)\n\t}\n}", "func (a Snake) Eat() {\n\tfmt.Printf(\"%s \\n\", a.food)\n}", "func countApplesAndOranges(s int32, t int32, a int32, b int32, apples []int32, oranges []int32) {\n\tvar hitApples, hitOranges int32\n\tfor _, apple := range apples {\n\t\tplace := a + apple\n\t\tif s <= place && place <= t {\n\t\t\thitApples++\n\t\t}\n\t}\n\tfor _, orange := range oranges {\n\t\tplace := b + orange\n\t\tif s <= place && place <= t {\n\t\t\thitOranges++\n\t\t}\n\t}\n\tfmt.Println(hitApples)\n\tfmt.Println(hitOranges)\n}", "func wearArmor(dexterity int) (string, int) {\n\tlottery := random(1, 5)\n\tvar armorname string\n\tvar armorBonus, dexBonus int\n\tdexBonus = attrModifier(dexterity)\n\tswitch lottery {\n\tcase 1:\n\t\tarmorname = \"Leather Armor\"\n\t\tarmorBonus = 2\n\t\tif dexBonus > 8 { // Every armor has a limit of how many dexterity bonus points can be added.\n\t\t\tdexBonus = 8\n\t\t}\n\tcase 2:\n\t\tarmorname = \"Chain Shirt\"\n\t\tarmorBonus = 4\n\t\tif dexBonus > 4 {\n\t\t\tdexBonus = 4\n\t\t}\n\tcase 3:\n\t\tarmorname = \"Scale Mail\"\n\t\tarmorBonus = 4\n\t\tif dexBonus > 4 {\n\t\t\tdexBonus = 4\n\t\t}\n\tcase 4:\n\t\tarmorname = \"Breastplate\"\n\t\tarmorBonus = 5\n\t\tif dexBonus > 3 {\n\t\t\tdexBonus = 3\n\t\t}\n\tcase 5:\n\t\tarmorname = \"Full Plate Armor\"\n\t\tarmorBonus = 8\n\t\tif dexBonus > 1 {\n\t\t\tdexBonus = 1\n\t\t}\n\t}\n\treturn armorname, 10 + armorBonus + dexBonus\n}", "func (t *Translator) chooseUnit(unit string, count int64) (string, error) {\n\ts := strings.Split(t.resources[unit], \"|\")\n\tif count > 1 {\n\t\treturn strings.Replace(s[1], \":count\", strconv.FormatInt(int64(count), 10), 1), nil\n\t}\n\n\treturn s[0], nil\n}", "func ConcatVitals(x, y, rot float64, health uint64) string {\n\treturn fmt.Sprintf(\"%f|%f|%f|%d\", x, y, rot, health)\n}", "func (m *RoomdetailMutation) AddRoomprice(i int) {\n\tif m.addroomprice != nil {\n\t\t*m.addroomprice += i\n\t} else {\n\t\tm.addroomprice = &i\n\t}\n}", "func DeleteFruit(c *gin.Context, params *FruitIdentityParams) error {\n\tif params.APIKey == \"\" {\n\t\treturn errors.Forbiddenf(\"invalid api key\")\n\t}\n\tmarket.Lock()\n\tdefer market.Unlock()\n\n\tn := strings.ToLower(params.Name)\n\tif _, ok := market.fruits[n]; !ok {\n\t\treturn errors.NotFoundf(\"fruit\")\n\t}\n\tdelete(market.fruits, n)\n\n\treturn nil\n}", "func (self *Tween) RepeatAll1O(total int) *Tween{\n return &Tween{self.Object.Call(\"repeatAll\", total)}\n}", "func (r *Responder) Teapot() { r.write(http.StatusTeapot) }", "func (g *Game) Shot(shot int) {\n\n\tif g.isOver() {\n\t\tfmt.Println(\"Illegal extra shot\")\n\t\treturn\n\t}\n\tfmt.Printf(\"Shot: %d, Pinup: %d. Game frames: %v \\n\", shot, g.numPinUp, g.frames)\n\tg.accountBonus(shot)\n\tg.recordShot(shot)\n\tg.prepareNextShot()\n}", "func Repeat(count int, operand string) string { return strings.Repeat(operand, count) }", "func print_prefix_name(p int32)(str string){\nl:=name_dir[p].name[0]\nstr= fmt.Sprint(string(name_dir[p].name[1:]))\nif int(l)<len(name_dir[p].name){\nstr+= \"...\"\n}\nreturn\n}", "func Redact(s string) string {\n redaction := \"[REDACTED]\"\n str := strings.Fields(s)\n for idx, _ := range str {\n str[idx] = redaction\n }\n\n return strings.Join(str, \" \")\n}", "func (animal *Animal) Eat() {\n\tfmt.Println(string(colorRed), animal.food)\n}", "func redact(line []byte, ranges []matchRange) []byte {\n\tvar offset int // the offset of ranges generated by replacing x bytes by the RedactStr\n\tfor _, r := range ranges {\n\t\tlength := r.last - r.first\n\t\tfirst := r.first + offset\n\t\tlast := first + length\n\n\t\ttoRedact := line[first:last]\n\t\tredactStr := RedactStr\n\t\tif bytes.HasSuffix(toRedact, []byte(\"\\n\")) {\n\t\t\t// if string to redact ends with newline redact message should also\n\t\t\tredactStr += \"\\n\"\n\t\t}\n\n\t\tnewLine := append([]byte{}, line[:first]...)\n\t\tnewLine = append(newLine, redactStr...)\n\t\tnewLine = append(newLine, line[last:]...)\n\n\t\toffset += len(redactStr) - length\n\n\t\tline = newLine\n\t}\n\treturn line\n}", "func TestRecruitEditor_UpdateRecruit(t *testing.T) {\n\tassert := assert.New(t)\n\tcrud := moc.NewLoadedCRUD()\n\thandler := createGqlHandler(crud)\n\n\t// login as recruit user\n\ttoken, _ := login(crud, getRecruitUserAccount().ID, \"none\")\n\n\t// prep data\n\tphone := \"082 345 6789\"\n\temail := \"[email protected]\"\n\tprovince := \"LIMPOPO\"\n\tgender := \"FEMALE\"\n\tcity := \"Polokwane\"\n\tdisability := \"Blind\"\n\tvid1URL := \"http://google.com\"\n\tvid2URL := \"http://youtube.com\"\n\tbirthYear := 1987\n\n\t// prepare query\n\tquery := fmt.Sprintf(`\n\t\tmutation {\n\t\t\tedit(token: \"%s\"){\n\t\t\t\t... on RecruitEditor{\n\t\t\t\t\tupdateRecruit(info: {\n\t\t\t\t\t\tphone: \"%s\",\n\t\t\t\t\t\temail: \"%s\",\n\t\t\t\t\t\tprovince: %s,\n\t\t\t\t\t\tcity: \"%s\",\n\t\t\t\t\t\tgender: %s,\n\t\t\t\t\t\tdisability: \"%s\",\n\t\t\t\t\t\tvid1_url: \"%s\",\n\t\t\t\t\t\tvid2_url: \"%s\",\n\t\t\t\t\t\tbirth_year: %v,\n\t\t\t\t\t}){\n\t\t\t\t\t\tphone\n\t\t\t\t\t\temail\n\t\t\t\t\t\tprovince\n\t\t\t\t\t\tcity\n\t\t\t\t\t\tgender\n\t\t\t\t\t\tdisability\n\t\t\t\t\t\tvid1_url\n\t\t\t\t\t\tvid2_url\n\t\t\t\t\t\tage\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t`, token, phone, email, province, city, gender, disability,\n\t\tvid1URL, vid2URL, birthYear,\n\t)\n\n\tresponse, err := gqlRequestAndRespond(handler, query, nil)\n\tfailOnError(assert, err)\n\n\texpected := map[string]interface{}{\n\t\t\"data\": map[string]interface{}{\n\t\t\t\"edit\": map[string]interface{}{\n\t\t\t\t\"updateRecruit\": map[string]interface{}{\n\t\t\t\t\t\"phone\": phone,\n\t\t\t\t\t\"email\": email,\n\t\t\t\t\t\"province\": province,\n\t\t\t\t\t\"city\": city,\n\t\t\t\t\t\"gender\": gender,\n\t\t\t\t\t\"disability\": disability,\n\t\t\t\t\t\"vid1_url\": vid1URL,\n\t\t\t\t\t\"vid2_url\": vid2URL,\n\t\t\t\t\t\"age\": float64(time.Now().Year() - birthYear),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tassert.Equal(expected, response, msgInvalidResult)\n}", "func (t *Text) IdentTop(n int) *Text {\n\tif n < 0 {\n\t\treturn t\n\t}\n\tt.addMethod(func() {\n\t\tfor i := 0; i < n; i++ {\n\t\t\tt.buffer.WriteString(\"\\n\")\n\t\t}\n\t})\n\treturn t\n}", "func (self *Tween) SetRepeatCounterA(member int) {\n self.Object.Set(\"repeatCounter\", member)\n}", "func TestAddProductToCatalog2(t *testing.T) {\n\t\n\te := httpexpect.New(t, API_URL)\n\t\n\tprintComment(\"ADD0002\", \"Test add product 2 to catalog --> ult_medium Unlimited 2GB $29.90\")\n\tproduct := map[string]interface{}{\n\t\t\"code\": \"ult_medium\",\n\t\t\"name\": \"Unlimited 2GB\",\n\t\t\"price\": 29.90,\n\t}\n\n\te.POST(\"/products\").\n\t\tWithJSON(product).\n\t\tExpect().\n\t\tStatus(http.StatusOK)\n\n}", "func (level *Level) EatApple() {\n\t// log.Println(\"Apple was eaten\")\n\n\t// Increment the size of the snake\n\tlevel.snake.IncrementSize()\n\n\t// Increment the game score\n\tlevel.game.score++\n\n\t// Move the apple to a new location\n\tlevel.apple.position = level.GetRandomPosition()\n}", "func add_grocery(a ...string) {\n\tfor _, d := range a {\n\t\tg_groceries = append(g_groceries, d)\n\t}\n}", "func Repeat(v string, repeatNtimes int) string {\n\tvar repeated string\n\tfor i := 1; i <= repeatNtimes; i++ {\n\t\trepeated += v\n\t}\n\treturn repeated\n}", "func (b *Banana) PrintfFood() {\n\tfmt.Println(\"I am a fruit of banana\")\n}", "func updateIceCream(w http.ResponseWriter, r *http.Request) {\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\tparams := mux.Vars(r)\r\n\tflavourid_int,_ := strconv.Atoi(params[\"flavourid\"])\r\n\tfor index, item := range flavours {\r\n\t\tif item.FlavourId == flavourid_int {\r\n\t\t\tflavours = append(flavours[:index], flavours[index+1:]...)\r\n\t\t\tvar IceCream IceCream\r\n\t\t\t_ = json.NewDecoder(r.Body).Decode(&IceCream)\r\n\t\t\tIceCream.FlavourId = flavourid_int\r\n\t\t\tflavours = append(flavours, IceCream)\r\n\t\t\tjson.NewEncoder(w).Encode(IceCream)\r\n\t\t\treturn\r\n\t\t}\r\n\t}\r\n}", "func printRes() {\n\tfmt.Printf(\"%d %d\\n\", pAlice, pBob)\n}", "func viewLots(a [10]car) {\n\tfmt.Println(len(a))\n}", "func (arg1 *UConverter) GetStarters(arg2 *UErrorCode) []int", "func main() {\n\tvar name string\n\tfriends := make([]string, 3)\n\n\tfor i := 0; name != \"q\"; i++ {\n\t\tfmt.Print(\"Digite o nome de um amigo e digite 'q' para parar: \")\n\t\tfmt.Scanf(\"%s\", &name)\n\t\tif name != \"q\" {\n\t\t\tif i < 3 {\n\t\t\t\tfriends[i] = name\n\t\t\t} else {\n\t\t\t\t// friends = append(friends, name, \"João\", \"Maria\", \"Mario\")\n\t\t\t\tfriends = append(friends, name)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Printf(\"\\nVocê tem %v amigo(s) \\n\", len(friends))\n\tfor _, friend := range friends {\n\t\tfmt.Printf(\"— %s \\n\", friend)\n\t}\n\n\t// other_type_slice := friends[:3] // Quando nenhum valor é colocado antes do ':' quer dizer que é sempre 0\n\n\tother_type_slice := friends[1:3]\n\tfmt.Println(other_type_slice)\n}", "func take(theitem, arg int) int {\n\t/* cursors(); */\n\tlimit := 15 + (c[LEVEL] >> 1)\n\tif limit > 26 {\n\t\tlimit = 26\n\t}\n\tfor i := 0; i < limit; i++ {\n\t\tif iven[i] == 0 {\n\t\t\tiven[i] = theitem\n\t\t\tivenarg[i] = arg\n\t\t\tlimit = 0\n\t\t\tswitch theitem {\n\t\t\tcase OPROTRING, ODAMRING, OBELT:\n\t\t\t\tlimit = 1\n\t\t\tcase ODEXRING:\n\t\t\t\tc[DEXTERITY] += ivenarg[i] + 1\n\t\t\t\tlimit = 1\n\t\t\tcase OSTRRING:\n\t\t\t\tc[STREXTRA] += ivenarg[i] + 1\n\t\t\t\tlimit = 1\n\t\t\tcase OCLEVERRING:\n\t\t\t\tc[INTELLIGENCE] += ivenarg[i] + 1\n\t\t\t\tlimit = 1\n\t\t\tcase OHAMMER:\n\t\t\t\tc[DEXTERITY] += 10\n\t\t\t\tc[STREXTRA] += 10\n\t\t\t\tc[INTELLIGENCE] -= 10\n\t\t\t\tlimit = 1\n\n\t\t\tcase OORBOFDRAGON:\n\t\t\t\tc[SLAYING]++\n\t\t\tcase OSPIRITSCARAB:\n\t\t\t\tc[NEGATESPIRIT]++\n\t\t\tcase OCUBEofUNDEAD:\n\t\t\t\tc[CUBEofUNDEAD]++\n\t\t\tcase ONOTHEFT:\n\t\t\t\tc[NOTHEFT]++\n\t\t\tcase OSWORDofSLASHING:\n\t\t\t\tc[DEXTERITY] += 5\n\t\t\t\tlimit = 1\n\t\t\t}\n\t\t\tlprcat(\"\\nYou pick up:\")\n\t\t\tsrcount = 0\n\t\t\tshow3(i)\n\t\t\tif limit != 0 {\n\t\t\t\tbottomline()\n\t\t\t}\n\t\t\treturn 0\n\t\t}\n\t}\n\tlprcat(\"\\nYou can't carry anything else\")\n\treturn 1\n}", "func cleaner(listy ...int) {\n\tfor _, x := range listy {\n\t\tfmt.Println(\"Deleting\", x)\n\t\tdelete(myGreeting, x)\n\t}\n}", "func Racer(url1, url2 string) (winner string, err error) {\n\treturn ConfigurableRacer(url1, url2, tenSecondTimeout)\n}", "func newRelease(a Artist) int {\n a.Songs++\n return a.Songs\n}", "func (m *Match) printMatch() {\n\tfmt.Printf(\"%s%s%s%s:%s:%s%s%s%s%s%s\\n\",\n\t\tcolors.Purple,\n\t\tm.Path,\n\t\tcolors.Restore,\n\t\tcolors.Green,\n\t\tstrconv.Itoa(m.LineNumber),\n\t\tcolors.Restore,\n\t\tstring(m.Line[:m.Match[0]]),\n\t\tcolors.LightRed,\n\t\tstring(m.Line[m.Match[0]:m.Match[1]]),\n\t\tcolors.Restore,\n\t\tstring(m.Line[m.Match[1]:]),\n\t)\n}", "func MogTar() int {\r\n\treturn rand.Intn(3) + 1\r\n}", "func printColoredSecretJsonObject(secret SecretFound, isFirstSecret *bool) {\n\tIndent3 := Indent + Indent + Indent\n\n\tif *isFirstSecret {\n\t\tfmt.Printf(Indent + Indent + \"{\\n\")\n\t} else {\n\t\tfmt.Printf(\",\\n\" + Indent + Indent + \"{\\n\")\n\t}\n\n\tfmt.Printf(Indent3+\"\\\"Image Layer ID\\\": %s,\\n\", jsonMarshal(secret.LayerID))\n\tfmt.Printf(Indent3+\"\\\"Matched Rule ID\\\": %d,\\n\", secret.RuleID)\n\tfmt.Printf(Indent3+\"\\\"Matched Rule Name\\\": %s,\\n\", jsonMarshal(secret.RuleName))\n\tfmt.Printf(Indent3+\"\\\"Matched Part\\\": %s,\\n\", jsonMarshal(secret.PartToMatch))\n\tfmt.Printf(Indent3+\"\\\"String to Match\\\": %s,\\n\", jsonMarshal(secret.Match))\n\tfmt.Printf(Indent3+\"\\\"Signature to Match\\\": %s,\\n\", jsonMarshal(secret.Regex))\n\tfmt.Printf(Indent3+\"\\\"Severity\\\": %s,\\n\", jsonMarshal(secret.Severity))\n\tfmt.Printf(Indent3+\"\\\"Severity Score\\\": %.2f,\\n\", secret.SeverityScore)\n\tfmt.Printf(Indent3+\"\\\"Starting Index of Match in Original Content\\\": %d,\\n\", secret.PrintBufferStartIndex)\n\tfmt.Printf(Indent3+\"\\\"Relative Starting Index of Match in Displayed Substring\\\": %d,\\n\", secret.MatchFromByte)\n\tfmt.Printf(Indent3+\"\\\"Relative Ending Index of Match in Displayed Substring\\\": %d,\\n\", secret.MatchToByte)\n\tfmt.Printf(Indent3+\"\\\"Full File Name\\\": %s,\\n\", jsonMarshal(secret.CompleteFilename))\n\tmatch := secret.MatchedContents\n\tfrom := secret.MatchFromByte\n\tto := secret.MatchToByte\n\tprefix := removeFirstLastChar(jsonMarshal(match[0:from]))\n\tcoloredMatch := color.RedString(removeFirstLastChar(jsonMarshal(string(match[from:to]))))\n\tsuffix := removeFirstLastChar(jsonMarshal(match[to:]))\n\tfmt.Printf(Indent3+\"\\\"Matched Contents\\\": \\\"%s%s%s\\\"\\n\", prefix, coloredMatch, suffix)\n\n\tfmt.Printf(Indent + Indent + \"}\")\n}", "func getHashColorBullet(v string) string {\n\tif len(v) > 6 {\n\t\tv = strutil.Head(v, 6)\n\t}\n\n\treturn fmtc.Sprintf(\" {#\" + strutil.Head(v, 6) + \"}● {!}\")\n}", "func Verse(v int) string {\n\n\tdays := map[int]string{\n\t\t1: \"first\",\n\t\t2: \"second\",\n\t\t3: \"third\",\n\t\t4: \"fourth\",\n\t\t5: \"fifth\",\n\t\t6: \"sixth\",\n\t\t7: \"seventh\",\n\t\t8: \"eighth\",\n\t\t9: \"ninth\",\n\t\t10: \"tenth\",\n\t\t11: \"eleventh\",\n\t\t12: \"twelfth\",\n\t}\n\n\tgifts := map[int]string{\n\t\t1: \"a Partridge in a Pear Tree\",\n\t\t2: \"two Turtle Doves\",\n\t\t3: \"three French Hens\",\n\t\t4: \"four Calling Birds\",\n\t\t5: \"five Gold Rings\",\n\t\t6: \"six Geese-a-Laying\",\n\t\t7: \"seven Swans-a-Swimming\",\n\t\t8: \"eight Maids-a-Milking\",\n\t\t9: \"nine Ladies Dancing\",\n\t\t10: \"ten Lords-a-Leaping\",\n\t\t11: \"eleven Pipers Piping\",\n\t\t12: \"twelve Drummers Drumming\",\n\t}\n\n\tgift := \"\"\n\tfor d := v; d >= 1; d-- {\n\n\t\tif v != 1 && d == 1 {\n\t\t\tgift = fmt.Sprintf(\"%s, and %s\", gift, gifts[d])\n\t\t} else {\n\t\t\tgift = fmt.Sprintf(\"%s, %s\", gift, gifts[d])\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"On the %s day of Christmas my true love gave to me%s.\", days[v], gift)\n}", "func (p *Bare) sprintTrice() (n int, err error) {\n\tswitch p.trice.Type {\n\tcase \"TRICE0\":\n\t\treturn p.trice0()\n\tcase \"TRICE8_1\":\n\t\treturn p.trice81()\n\tcase \"TRICE8_2\":\n\t\treturn p.trice82()\n\tcase \"TRICE8_3\":\n\t\treturn p.trice83()\n\tcase \"TRICE8_4\":\n\t\treturn p.trice84()\n\tcase \"TRICE8_5\":\n\t\treturn p.trice85()\n\tcase \"TRICE8_6\":\n\t\treturn p.trice86()\n\tcase \"TRICE8_7\":\n\t\treturn p.trice87()\n\tcase \"TRICE8_8\":\n\t\treturn p.trice88()\n\tcase \"TRICE16_1\":\n\t\treturn p.trice161()\n\tcase \"TRICE16_2\":\n\t\treturn p.trice162()\n\tcase \"TRICE16_3\":\n\t\treturn p.trice163()\n\tcase \"TRICE16_4\":\n\t\treturn p.trice164()\n\tcase \"TRICE32_1\":\n\t\treturn p.trice321()\n\tcase \"TRICE32_2\":\n\t\treturn p.trice322()\n\tcase \"TRICE32_3\":\n\t\treturn p.trice323()\n\tcase \"TRICE32_4\":\n\t\treturn p.trice324()\n\tcase \"TRICE64_1\":\n\t\treturn p.trice641()\n\tcase \"TRICE64_2\":\n\t\treturn p.trice642()\n\t}\n\treturn p.outOfSync(fmt.Sprintf(\"Unexpected trice.Type %s\", p.trice.Type))\n}", "func generateItemNumbers() (int, int, int) {\n\tnumComments := (numDoc * 4) / 5\n\tnumUsers := (numDoc * 3) / 20\n\tnumAssets := numDoc / 20\n\treturn numComments, numUsers, numAssets\n}", "func (tk Tokens) CombineRepeats() bool {\n\tcat := tk.Cat()\n\treturn (cat == Literal || cat == Comment || cat == Text || cat == Name)\n}", "func main() {\n\ts1 := stringAppender(\"hoo\")\n\tfmt.Println(s1(\"woo\"))\n\n\ts2 := stringAppender(\"Orioles\")\n\tfmt.Println(s2(\"Baltimore \"))\n\n}", "func prt(args ...interface{}) {\n\tfmt.Println(append([]interface{}{\"-------------> DEMO\"}, args...)...)\n}", "func (r Roster) Inject(i int) {\n\tfor _, v := range r {\n\t\tv.rating = v.rating + i\n\t}\n}", "func AddPlanetEndpoint(w http.ResponseWriter, req *http.Request) {\n var planet Planet\n _ = json.NewDecoder(req.Body).Decode(&planet)\n auto_id_ = auto_id_ + 1\n planet.ID = strconv.FormatInt(int64(auto_id_), 10)\n planet.Films = GetNumElements(getapiinfo.GetApiInformation(planet.Name))\n planets_ = append(planets_, planet)\n json.NewEncoder(w).Encode(planets_)\n}", "func TestSizeRepeat(t *testing.T) {\n\t// init trie obj\n\ttrieObj := trie.NewTrie()\n\n\t// test size with 1st insert\n\ttrieObj.Insert(\"A\")\n\tassert.Equal(t, trieObj.Size, 1)\n\tassert.Equal(t, trieObj.IsEmpty(), false)\n\n\t// test size with repeated insert\n\ttrieObj.Insert(\"A\")\n\tassert.Equal(t, trieObj.Size, 1)\n\n\t// test size with 2nd insert\n\ttrieObj.Insert(\"ALO\")\n\tassert.Equal(t, trieObj.Size, 2)\n\tassert.Equal(t, trieObj.IsEmpty(), false)\n\n\t// test with repeated insert\n\ttrieObj.Insert(\"ALO\")\n\tassert.Equal(t, trieObj.Size, 2)\n\n\t// test with 3rd insert\n\ttrieObj.Insert(\"ALOHA\")\n\tassert.Equal(t, trieObj.Size, 3)\n\tassert.Equal(t, trieObj.IsEmpty(), false)\n\n\t// test with repeated insert\n\ttrieObj.Insert(\"ALOHA\")\n\tassert.Equal(t, trieObj.Size, 3)\n\n}", "func restNote(rest rune, dotted bool, tempo int) []int16 {\n\tvar samples int\n\tlength := wholeNote + (wholeNote / 100 * 4 * (4 - tempo)) // 4% per tempo unit\n\tswitch rest {\n\tcase 'W':\n\t\tsamples = length\n\tcase 'H':\n\t\tsamples = length / 2\n\tcase 'Q':\n\t\tsamples = length / 4\n\tcase 'E':\n\t\tsamples = length / 8\n\tcase 'S':\n\t\tsamples = length / 16\n\tcase 'T':\n\t\tsamples = length / 32\n\tcase 'I':\n\t\tsamples = length / 64\n\t}\n\n\tif dotted {\n\t\tsamples += samples / 2\n\t}\n\n\treturn make([]int16, samples)\n}", "func Eat(f Food) {\n\tfmt.Printf(\"I love %ss!\", f.Name)\n}", "func (Service) TooManyArguments(a, b string) {\n}", "func TestAddTwoDeleteScond(t *testing.T) {\n\ttarget := teaser.New()\n\tm1id := target.Add(\"msg1\")\n\tm2id := target.Add(\"msg2\")\n\n\t{\n\t\tdeleted := target.Delete(m2id)\n\t\tassertDeleted(m2id, deleted, t)\n\t}\n\n\t{\n\t\tnextHash, m1vid := target.View()\n\t\tassertMessageId(m1id, m1vid, t)\n\t\tassertMessageHash(\"\", nextHash, t)\n\t}\n}", "func plusUserID(step int64) int64 {\n\tuserid += step\n\treturn userid\n}", "func generateLogLine(id int) string {\n\tmethod := httpMethods[rand.Intn(len(httpMethods))]\n\tnamespace := namespaces[rand.Intn(len(namespaces))]\n\n\tpodName := rand.String(rand.IntnRange(3, 5))\n\turl := fmt.Sprintf(\"/api/v1/namespaces/%s/pods/%s\", namespace, podName)\n\tstatus := rand.IntnRange(200, 600)\n\n\treturn fmt.Sprintf(\"%d %s %s %d\", id, method, url, status)\n}", "func viewCar(a [10]car, printLots func(a [10]car)) {\n\tfor i := 0; i < lots; i++ {\n\t\tfmt.Println(a[i].color, a[i].cost)\n\t}\n\tprintLots(a)\n}", "func newRelease(a *Artist) int {\n a.Songs++\n return a.Songs\n}", "func (s *stepConstructor) RepeatStep() {\n\ts.CurrentStep--\n}" ]
[ "0.48526704", "0.45791003", "0.45148775", "0.45120233", "0.45096675", "0.4484106", "0.44114172", "0.44073385", "0.43790644", "0.4351559", "0.43006048", "0.42932254", "0.42848495", "0.4264322", "0.42597494", "0.42453548", "0.4244313", "0.42309946", "0.422844", "0.4227956", "0.4188795", "0.41744077", "0.417175", "0.41701224", "0.4147963", "0.4130036", "0.4118443", "0.41147417", "0.40997154", "0.4093644", "0.40845743", "0.4072336", "0.4060472", "0.40575415", "0.40428293", "0.40391344", "0.4033631", "0.4014582", "0.4012665", "0.40090466", "0.40036762", "0.39963773", "0.39931825", "0.3993081", "0.3992702", "0.39899758", "0.39865008", "0.3986126", "0.398449", "0.3978036", "0.3972328", "0.3972197", "0.3967863", "0.39673063", "0.3966417", "0.39633983", "0.39629227", "0.39622864", "0.3957854", "0.395638", "0.39556938", "0.39482585", "0.39375156", "0.39374155", "0.39374065", "0.39253992", "0.3921235", "0.39207423", "0.3919707", "0.39172396", "0.3916506", "0.39150208", "0.3914878", "0.3910657", "0.39066902", "0.39059678", "0.38900083", "0.38796255", "0.38784528", "0.38682276", "0.38643077", "0.38618827", "0.38614306", "0.38595238", "0.38584694", "0.38571963", "0.38511485", "0.3845322", "0.3838638", "0.38361806", "0.38358864", "0.38343126", "0.3834312", "0.38262457", "0.3826142", "0.38233343", "0.3821757", "0.3820973", "0.38199952", "0.3818266", "0.38171113" ]
0.0
-1
/ StepsOfKnight : 8 StepsOfKnight2 : 8
func DistNearestFillUtil(arr [][]int, maxCol int, maxRow int, currCol int, currRow int, traversed [][]int, dist int) { // Range check if currCol < 0 || currCol >= maxCol || currRow < 0 || currRow >= maxRow { return } // Traversable if there is a better distance. if traversed[currCol][currRow] <= dist { return } // Update distance. traversed[currCol][currRow] = dist dir := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} // Traverse in each direction. for i := 0; i < 4; i++ { x := currCol + dir[i][0] y := currRow + dir[i][1] DistNearestFillUtil(arr, maxCol, maxRow, x, y, traversed, dist+1) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func StepsOfKnightUtil(size int, currCol int, currRow int, traversed [][]int, dist int) {\n\t// Range check\n\tif currCol < 0 || currCol >= size || currRow < 0 || currRow >= size {\n\t\treturn\n\t}\n\n\t// Traverse if not already traversed.\n\tif traversed[currCol][currRow] <= dist {\n\t\treturn\n\t}\n\n\tdir := [][]int{{-2, -1}, {-2, 1}, {2, -1}, {2, 1}, {-1, -2}, {1, -2}, {-1, 2}, {1, 2}}\n\ttraversed[currCol][currRow] = dist\n\n\tfor i := 0; i < 8; i++ {\n\t\tx := currCol + dir[i][0]\n\t\ty := currRow + dir[i][1]\n\t\tStepsOfKnightUtil(size, x, y, traversed, dist+1)\n\t}\n}", "func minKnightMoves(ex int, ey int) int {\r\n\tif ex == 0 && ey == 0 {\r\n\t\treturn 0\r\n\t}\r\n\tq := [][]int{}\r\n\tq = append(q, []int{0, 0})\r\n\tdir := [][]int{{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, 2}, {-2, 1}, {-1, -2}, {-2, -1}}\r\n\tsteps := 0\r\n\tseen := map[int]map[int]bool{0: map[int]bool{0: true}}\r\n\t// BFS loop\r\n\tfor len(q) > 0 {\r\n\t\tsteps++\r\n\t\tn := len(q)\r\n\t\tfor i := 0; i < n; i++ {\r\n\t\t\tt := q[0]\r\n\t\t\tq = q[1:]\r\n\t\t\tfor _, d := range dir {\r\n\t\t\t\tnx := t[0] + d[0]\r\n\t\t\t\tny := t[1] + d[1]\r\n\t\t\t\tif nx == ex && ny == ey {\r\n\t\t\t\t\treturn steps\r\n\t\t\t\t}\r\n\t\t\t\tif _, exists := seen[nx]; !exists {\r\n\t\t\t\t\tseen[nx] = map[int]bool{}\r\n\t\t\t\t}\r\n\t\t\t\tif _, exists := seen[nx][ny]; !exists &&\r\n\t\t\t\t\t(nx*ex >= 0 && ny*ey >= 0 || steps < 3) {\r\n\t\t\t\t\tseen[nx][ny] = true\r\n\t\t\t\t\tq = append(q, []int{nx, ny})\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn -1\r\n}", "func findSteps(lines [][]Point) []int {\n\tline1 := lines[0]\n\tline2 := lines[1]\n\n\tline1Size := len(lines[0])\n\tline2Size := len(lines[1])\n\tvar steps []int\n\n\tif line1Size == line2Size {\n\t\tfor i := 0; i <= line1Size-2; i++ {\n\t\t\tfor j := 0; j <= line1Size-2; j++ {\n\t\t\t\tnumSteps := calculateSteps(line1, line2, i, j)\n\t\t\t\tif numSteps != 0 {\n\t\t\t\t\tsteps = append(steps, numSteps)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else if line1Size > line2Size {\n\t\tfor i := 0; i <= line1Size-2; i++ {\n\t\t\tfor j := 0; j <= line2Size-2; j++ {\n\t\t\t\tnumSteps := calculateSteps(line1, line2, i, j)\n\t\t\t\tif numSteps != 0 {\n\t\t\t\t\tsteps = append(steps, numSteps)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor i := 0; i < line2Size-2; i++ {\n\t\t\tfor j := 0; j < line1Size-2; j++ {\n\t\t\t\tnumSteps := calculateSteps(line1, line2, i, j)\n\t\t\t\tif numSteps != 0 {\n\t\t\t\t\tsteps = append(steps, numSteps)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn steps\n}", "func knightDialer(n int) int {\n\tif n == 1 {\n\t\t// the only case where 5 is a valid starting position\n\t\treturn 10\n\t}\n\n\tconst mod = 1e9 + 7\n\tr := [10]int{1, 1, 1, 1, 1, 0, 1, 1, 1, 1}\n\tfor n > 1 {\n\t\tnext := [10]int{\n\t\t\t(r[4] + r[6]) % mod, // 0\n\t\t\t(r[6] + r[8]) % mod, // 1\n\t\t\t(r[7] + r[9]) % mod, // 2\n\t\t\t(r[4] + r[8]) % mod, // 3\n\t\t\t(r[3] + r[9] + r[0]) % mod, // 4\n\t\t\t0,\n\t\t\t(r[1] + r[7] + r[0]) % mod, // 6\n\t\t\t(r[2] + r[6]) % mod, // 7\n\t\t\t(r[1] + r[3]) % mod, // 8\n\t\t\t(r[2] + r[4]) % mod, // 9\n\t\t}\n\t\tr = next\n\t\tn--\n\t}\n\n\ts := 0\n\tfor _, v := range r {\n\t\ts = (s + v) % mod\n\t}\n\treturn s\n}", "func KnightMoves(b Board, row, col int, recurse bool) (possible []ValidMove) {\n\tpossible = tryAndAppend(possible, b, row, col, -2, -1, recurse) // up-left\n\tpossible = tryAndAppend(possible, b, row, col, -2, 1, recurse) // up-right\n\tpossible = tryAndAppend(possible, b, row, col, 2, -1, recurse) // down-left\n\tpossible = tryAndAppend(possible, b, row, col, 2, 1, recurse) // down-right\n\n\tpossible = tryAndAppend(possible, b, row, col, -1, -2, recurse) // left-up\n\tpossible = tryAndAppend(possible, b, row, col, 1, -2, recurse) // left-down\n\tpossible = tryAndAppend(possible, b, row, col, -1, 2, recurse) // right-up\n\tpossible = tryAndAppend(possible, b, row, col, 1, 2, recurse) // right-down\n\n\treturn\n}", "func countDiag(mygame game.Game, playerNum int, streakLength int) int {\n\tcount := 0 //overall # of streaks of n length\n\tcurrCount := 0 //this needs to be exactly n so that we don't count streaks of 2 as streaks of 3\n\tsymbol := mygame.PlayerSymbols[playerNum]\n\t//downwards to the right first\n\t//increment over every square\n\tfor i := 0; i < game.BoardHeight; i++ { //rows\n\t\tfor j := 0; j < game.BoardWidth; j++ { //columns\n\t\t\tif mygame.GameBoard[i][j].Active {\n\t\t\t\t//check that the symbol matches\n\t\t\t\tif mygame.GameBoard[i][j].Symbol == symbol {\n\t\t\t\t\t//make sure piece up and left to it isn't the same symbol\n\t\t\t\t\t//so that we're not double counting\n\t\t\t\t\tif i == 0 || j == 0 || mygame.GameBoard[i-1][j-1].Symbol != symbol {\n\t\t\t\t\t\tcurrCount++\n\t\t\t\t\t\tfor k := 1; k < 4; k++ {\n\t\t\t\t\t\t\tif i+k < game.BoardHeight && j+k < game.BoardWidth { //make sure we don't go off board\n\t\t\t\t\t\t\t\tif mygame.GameBoard[i+k][j+k].Symbol == symbol {\n\t\t\t\t\t\t\t\t\tcurrCount++\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tbreak //break if different symbol\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//only increment count if currentcount matches n\n\t\t\t\t\t\tif currCount == streakLength {\n\t\t\t\t\t\t\tcount++\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrCount = 0 //reset currCount\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\t//now downwards to the left\n\tfor i := 0; i < game.BoardHeight; i++ { //rows\n\t\tfor j := 0; j < game.BoardWidth; j++ { //columns\n\t\t\tif mygame.GameBoard[i][j].Active {\n\t\t\t\t//check that the symbol matches\n\t\t\t\tif mygame.GameBoard[i][j].Symbol == symbol {\n\t\t\t\t\t//make sure piece up and left to it isn't the same symbol\n\t\t\t\t\t//so that we're not double counting\n\t\t\t\t\tif i == 0 || j == game.BoardWidth-1 || mygame.GameBoard[i-1][j+1].Symbol != symbol {\n\t\t\t\t\t\tcurrCount++\n\t\t\t\t\t\tfor k := 1; k < 4; k++ {\n\t\t\t\t\t\t\tif i+k < game.BoardHeight && j-k >= 0 { //make sure we don't go off board\n\t\t\t\t\t\t\t\tif mygame.GameBoard[i+k][j-k].Symbol == symbol {\n\t\t\t\t\t\t\t\t\tcurrCount++\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tbreak //break if different symbol\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//only increment count if currentcount matches n\n\t\t\t\t\t\tif currCount == streakLength {\n\t\t\t\t\t\t\tcount++\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrCount = 0 //reset currCount\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\treturn count\n}", "func Day16Part2(input []string) int {\n\tresult := 1\n\tvalidCond := make(map[int][]string)\n\t// validValue := []int{}\n\tmyTicket := []int{}\n\tvalidTickets := [][]int{}\n\tpossibleFields := [][]string{}\n\tcondRE := regexp.MustCompile(`\\d+-\\d+`)\n\tsteps := 1\n\tfor _, item := range input {\n\t\tcmd := strings.Split(item, \":\")\n\t\tswitch cmd[0] {\n\t\tcase \"departure location\", \"departure station\", \"departure platform\", \"departure track\", \"departure date\", \"departure time\", \"arrival location\", \"arrival station\", \"arrival platform\", \"arrival track\", \"class\", \"duration\", \"price\", \"route\", \"row\", \"seat\", \"train\", \"type\", \"wagon\", \"zone\":\n\t\t\tsteps = 1\n\t\tcase \"your ticket\":\n\t\t\tsteps = 2\n\t\tcase \"nearby tickets\":\n\t\t\tsteps = 3\n\t\tcase \"\":\n\t\t\tsteps = 0\n\t\t}\n\t\tswitch steps {\n\t\tcase 1:\n\t\t\tfor _, rangeStr := range condRE.FindAllStringSubmatch(item, -1) {\n\t\t\t\ts, _ := strconv.Atoi(strings.Split(rangeStr[0], \"-\")[0])\n\t\t\t\te, _ := strconv.Atoi(strings.Split(rangeStr[0], \"-\")[1])\n\t\t\t\tfor i := s; i < e+1; i++ {\n\t\t\t\t\tvalidCond[i] = append(validCond[i], cmd[0])\n\t\t\t\t}\n\t\t\t}\n\t\tcase 2:\n\t\t\tif item == \"your ticket:\" {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tfor _, value := range strings.Split(item, \",\") {\n\t\t\t\tv, _ := strconv.Atoi(value)\n\t\t\t\tmyTicket = append(myTicket, v)\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif item == \"nearby tickets:\" {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcheck := true\n\t\t\tticketValues := strings.Split(item, \",\")\n\t\t\t// maze := [][]string{}\n\t\t\tvalidTicket := []int{}\n\t\t\tfor _, value := range ticketValues {\n\t\t\t\tv, _ := strconv.Atoi(value)\n\t\t\t\tif _, ok := validCond[v]; !ok {\n\t\t\t\t\tcheck = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif check {\n\t\t\t\tfor _, value := range strings.Split(item, \",\") {\n\t\t\t\t\tv, _ := strconv.Atoi(value)\n\t\t\t\t\tvalidTicket = append(validTicket, v)\n\t\t\t\t}\n\t\t\t\tvalidTickets = append(validTickets, validTicket)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor j := 0; j < len(validTickets[0]); j++ {\n\t\tpossibleField := []string{}\n\t\tfor i := 0; i < len(validTickets); i++ {\n\t\t\tv := validTickets[i][j]\n\t\t\tf, _ := validCond[v]\n\t\t\tif len(possibleField) == 0 {\n\t\t\t\tpossibleField = append(possibleField, f...)\n\t\t\t} else {\n\t\t\t\tpossibleField = intersection(possibleField, f)\n\t\t\t}\n\t\t}\n\t\tpossibleFields = append(possibleFields, possibleField)\n\t}\n\n\tcount := 0\n\tfor count < len(possibleFields) {\n\t\t// fmt.Printf(\"%#v\\n\", possibleFields)\n\t\tcount = 0\n\t\tfor i := 0; i < len(possibleFields); i++ {\n\t\t\tif len(possibleFields[i]) == 1 {\n\t\t\t\tcount++\n\t\t\t\tfor j := 0; j < len(possibleFields); j++ {\n\t\t\t\t\tif i != j {\n\t\t\t\t\t\tidx := -1\n\t\t\t\t\t\tfor ii, v := range possibleFields[j] {\n\t\t\t\t\t\t\tif v == possibleFields[i][0] {\n\t\t\t\t\t\t\t\tidx = ii\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif idx == -1 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif idx+1 >= len(possibleFields[j]) {\n\t\t\t\t\t\t\tpossibleFields[j] = possibleFields[j][:idx]\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpossibleFields[j] = append(possibleFields[j][:idx], possibleFields[j][idx+1:]...)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// fmt.Printf(\"%#v\\n\", possibleFields)\n\tfor i, v := range possibleFields {\n\t\tif strings.Contains(v[0], \"departure\") {\n\t\t\tresult *= myTicket[i]\n\t\t}\n\t}\n\n\treturn result\n}", "func (s Solution) Steps() string {\n\treturn s.text\n}", "func waysToClimbStaircase(numberOfStairs int, possibleSteps []int) int {\n\tif numberOfStairs <= 0 {\n\t\treturn 0\n\t}\n\n\tpossibleWays := 0\n\tfor _, step := range possibleSteps {\n\t\tif numberOfStairs-step == 0 {\n\t\t\tpossibleWays++\n\t\t}\n\t}\n\tfor _, step := range possibleSteps {\n\t\tpossibleWays += waysToClimbStaircase(numberOfStairs-step, possibleSteps)\n\t}\n\n\treturn possibleWays\n}", "func Day8Part1(filepath string) any {\n\tvar res int\n\n\t// open file\n\treadFile, _ := os.Open(filepath)\n\n\t// read line\n\tfileScanner := bufio.NewScanner(readFile)\n\tfileScanner.Split(bufio.ScanLines)\n\n\t// parse map in to [][]int\n\ttreeMap := parseMap(fileScanner)\n\t// fmt.Println(treeMap)\n\n\t// init visible trees 2D array\n\tvisible := make([][]bool, len(treeMap))\n\tfor i := range visible {\n\t\tvisible[i] = make([]bool, len(treeMap[0]))\n\t}\n\n\t// look from left to r\n\tfor i := range treeMap {\n\t\tmax := 0\n\t\tfor j := range treeMap[0] {\n\t\t\tif i == 0 || i == len(treeMap)-1 || j == 0 || j == len(treeMap[0])-1 || treeMap[i][j] > max {\n\t\t\t\tvisible[i][j] = true\n\t\t\t\tmax = treeMap[i][j]\n\t\t\t}\n\t\t}\n\t}\n\n\t// look from right to l\n\tfor i := range treeMap {\n\t\tmax := 0\n\t\tfor j := len(treeMap[0]) - 1; j >= 0; j-- {\n\t\t\tif i == 0 || i == len(treeMap)-1 || j == 0 || j == len(treeMap[0])-1 || treeMap[i][j] > max {\n\t\t\t\tvisible[i][j] = true\n\t\t\t\tmax = treeMap[i][j]\n\t\t\t}\n\t\t}\n\t}\n\n\t// look from up to down\n\tfor j := 0; j <= len(treeMap[0])-1; j++ {\n\t\tmax := 0\n\t\tfor i := 0; i <= len(treeMap)-1; i++ {\n\t\t\tif i == 0 || i == len(treeMap)-1 || j == 0 || j == len(treeMap[0])-1 || treeMap[i][j] > max {\n\t\t\t\tvisible[i][j] = true\n\t\t\t\tmax = treeMap[i][j]\n\t\t\t}\n\t\t}\n\t}\n\n\t// look from down to up\n\tfor j := 0; j <= len(treeMap[0])-1; j++ {\n\t\tmax := 0\n\t\tfor i := len(treeMap) - 1; i >= 0; i-- {\n\t\t\tif i == 0 || i == len(treeMap)-1 || j == 0 || j == len(treeMap[0])-1 || treeMap[i][j] > max {\n\t\t\t\tvisible[i][j] = true\n\t\t\t\tmax = treeMap[i][j]\n\t\t\t}\n\t\t}\n\t}\n\n\t// traverse visible trees 2D array and count visibles\n\tfor i := range visible {\n\t\tfor j := range visible[i] {\n\t\t\tif visible[i][j] {\n\t\t\t\tres++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res\n}", "func testOneScenario(start, goal Node, algo func (start, goal Node) []Node, trials int) ([]Node, int, float64, float64, int) {\n\tvar path []Node\n\n\t// Get path and average runtime\n\ttotalRuntime := 0.0\n\tfor i := 0; i < trials; i++ {\n\t\tbefore := time.Now()\n\t\tpath = algo(start, goal)\n\t\tafter := time.Now()\n\t\telapsed := after.Sub(before)\n\t\ttotalRuntime += float64(elapsed.Milliseconds())\n\t}\n\tavgRuntime := int(math.Round(totalRuntime/float64(trials)))\n\n\t// Calculate path length\n\tpathLen := 0.0\n\tfor i := 0; i < len(path)-1; i++ {\n\t\tn1 := path[i]\n\t\tn2 := path[i+1]\n\t\tpathLen += StraightLineDist(n1, n2)\n\t}\n\n\t// Calculate turn count and average angle of turns\n\tturns := 0\n\tavgAngle := 0.0\n\tfor i := 0; i < len(path)-2; i++ {\n\t\tn1 := path[i]\n\t\tn2 := path[i+1]\n\t\tn3 := path[i+2]\n\t\t// There are two vectors (n1,n2) and (n2,n3)\n\t\tv1_x, v1_y := float64(n2.X - n1.X), float64(n2.Y - n1.Y)\n\t\tv2_x, v2_y := float64(n3.X - n2.X), float64(n3.Y - n2.Y)\n\t\tdot := v1_x * v2_x + v1_y * v2_y\n\t\tv1_len := math.Sqrt(v1_x * v1_x + v1_y * v1_y)\n\t\tv2_len := math.Sqrt(v2_x * v2_x + v2_y * v2_y)\n\t\ta := dot / (v1_len * v2_len)\n\t\ta = math.Max(-1, math.Min(1, a)) // Rounding errors may produce values outside [-1,1] so clamp it.\n\t\tangle := math.Acos(a)\n\t\tif angle >= 0.001 {\n\t\t\t// We are turning at node n1\n\t\t\tavgAngle += angle\n\t\t\tturns++\n\t\t}\n\t}\n\n\tif turns > 0 {\n\t\tavgAngle /= float64(turns)\n\t}\n\n\treturn path, turns, pathLen, avgAngle, avgRuntime\n}", "func KnightAttacks(square Square) Bitboard {\n\treturn knightTable[square]\n}", "func findPaths2(m int, n int, maxMove int, startRow int, startColumn int) int {\n\t// 값이 클 수 있어 modulo 모듈 값을 리턴하라고 문제에 써있음\n\tmodulo := 1000000000 + 7\n\tif startRow < 0 || startRow == m ||\n\t\tstartColumn < 0 || startColumn == n {\n\t\treturn 1\n\t}\n\tif maxMove == 0 {\n\t\treturn 0\n\t}\n\t// 4방향 각각에 대해서 boundary 를 벗어나는지 경우들을 모두 더한다.\n\treturn findPaths(m, n, maxMove-1, startRow-1, startColumn)%modulo +\n\t\tfindPaths(m, n, maxMove-1, startRow, startColumn-1)%modulo +\n\t\tfindPaths(m, n, maxMove-1, startRow+1, startColumn)%modulo +\n\t\tfindPaths(m, n, maxMove-1, startRow, startColumn+1)%modulo\n}", "func part2(mem []int64) int64 {\n\tg := readGrid(mem)\n\tvar r robot\n\tfor y, row := range g {\n\t\tfor x, c := range row {\n\t\t\tif strings.ContainsRune(\"^v<>\", c) {\n\t\t\t\tr = robot{point{x, y}, north}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tprev := r.pos.move(west)\n\tpath := []direction{east}\n\tfor {\n\t\tadj := adjacent(g, r.pos)\n\t\tif len(path) > 2 && len(adj) == 1 {\n\t\t\tbreak\n\t\t}\n\t\tif 0 < len(adj) && len(adj) <= 2 {\n\t\t\tnext := adj[0]\n\t\t\tif len(adj) == 2 && adj[0] == prev {\n\t\t\t\tnext = adj[1]\n\t\t\t}\n\t\t\tif r.pos.x < next.x {\n\t\t\t\tr.dir = east\n\t\t\t}\n\t\t\tif r.pos.x > next.x {\n\t\t\t\tr.dir = west\n\t\t\t}\n\t\t\tif r.pos.y < next.y {\n\t\t\t\tr.dir = south\n\t\t\t}\n\t\t\tif r.pos.y > next.y {\n\t\t\t\tr.dir = north\n\t\t\t}\n\t\t}\n\t\tpath = append(path, r.dir)\n\t\tprev = r.pos\n\t\tr.move()\n\t}\n\n\tqueue := []step{{0, right}}\n\tfor i, d := range path[1:] {\n\t\trot := path[i].rotation(d)\n\t\tif len(queue) > 0 && rot == none {\n\t\t\tqueue[len(queue)-1].n++\n\t\t\tcontinue\n\t\t}\n\t\tqueue = append(queue, step{1, rot})\n\t}\n\n\tvar out string\n\tfor _, v := range queue {\n\t\tout += v.String() + \",\"\n\t}\n\tfmt.Println(out)\n\n\tp := newProgram(mem)\n\tp.memory[0] = 2\n\t// I have to be honest. I used my editors \"highlight other occurrences\"\n\t// feature on the previous output.\n\tin := strings.Join([]string{\n\t\t\"A,B,A,C,A,B,C,C,A,B\",\n\t\t\"R,8,L,10,R,8\",\n\t\t\"R,12,R,8,L,8,L,12\",\n\t\t\"L,12,L,10,L,8\",\n\t\t\"n\",\n\t\t\"\",\n\t}, \"\\n\")\n\tfor _, c := range in {\n\t\tp.input = append(p.input, int64(c))\n\t}\n\tres, err := p.run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn res[len(res)-1]\n}", "func Steps(turns float64) int {\n\treturn int(MotorSteps * turns)\n}", "func (i *BaseInhabitant) NextStep(relWatcher cr.RelativeWatcher) (int, int) {\n\ti.days++\n\t// iterate over fields to find enemy\n\tfor rH := 2; rH >= -2; rH-- {\n\t\tfor rW := 2; rW >= -2; rW-- {\n\t\t\tif rH == 0 && rW == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif i.IsEnemy(relWatcher(rH, rW)) {\n\t\t\t\t// found enemy, trying to find safe field\n\t\t\t\tisHPositive := rH >= 0\n\t\t\t\tisWPositive := rW >= 0\n\t\t\t\tvar nextH, nextW int\n\n\t\t\t\tif isHPositive && rH != 0 {\n\t\t\t\t\tnextH = -1\n\t\t\t\t} else if !isHPositive && rH != 0 {\n\t\t\t\t\tnextH = 1\n\t\t\t\t}\n\n\t\t\t\tif isWPositive && rW != 0 {\n\t\t\t\t\tnextW = -1\n\t\t\t\t} else if !isWPositive && rW != 0 {\n\t\t\t\t\tnextW = 1\n\t\t\t\t}\n\n\t\t\t\tif i.IsSafeField(relWatcher, nextH, nextW) {\n\t\t\t\t\treturn nextH, nextW\n\t\t\t\t}\n\t\t\t\t// try find safe place\n\n\t\t\t\tif rH == 0 && i.IsSafeField(relWatcher, -1, nextW) {\n\t\t\t\t\treturn -1, nextW\n\t\t\t\t}\n\n\t\t\t\tif rH == 0 && i.IsSafeField(relWatcher, 1, nextW) {\n\t\t\t\t\treturn 1, nextW\n\t\t\t\t}\n\n\t\t\t\tif rW == 0 && i.IsSafeField(relWatcher, nextH, -1) {\n\t\t\t\t\treturn nextH, -1\n\t\t\t\t}\n\n\t\t\t\tif rW == 0 && i.IsSafeField(relWatcher, nextH, 1) {\n\t\t\t\t\treturn nextH, 1\n\t\t\t\t}\n\n\t\t\t\tif isHPositive && i.IsSafeField(relWatcher, nextH, nextW-1) {\n\t\t\t\t\treturn nextH, nextW - 1\n\t\t\t\t}\n\n\t\t\t\tif isHPositive && i.IsSafeField(relWatcher, nextH, nextW+1) {\n\t\t\t\t\treturn nextH, nextW + 1\n\t\t\t\t}\n\n\t\t\t\tif isWPositive && i.IsSafeField(relWatcher, nextH-1, nextW) {\n\t\t\t\t\treturn nextH - 1, nextW\n\t\t\t\t}\n\n\t\t\t\tif isHPositive && i.IsSafeField(relWatcher, nextH+1, nextW) {\n\t\t\t\t\treturn nextH + 1, nextW\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn rand.Intn(i.maxMove+i.maxMove+1) - i.maxMove, rand.Intn(i.maxMove+i.maxMove+1) - i.maxMove\n}", "func (g *Game) Step() {\n\n\trows, cols := int(g.rows), int(g.cols)\n\tvar neighbors int\n\n\t//Swapping the boards allows us to overwrite the state from two turns ago, while reading the state from last turn\n\tg.state, g.prevState = g.prevState, g.state\n\n\t//Iterate over every row, skipping the border rows\n\tfor y := 1; y <= rows; y++ {\n\t\t//Cell by cell, skipping borders\n\t\tfor x := 1; x <= cols; x++ {\n\n\t\t\t// Count the neighbors\n\t\t\tneighbors = 0\n\t\t\tfor i := 0; i < 8; i++ {\n\t\t\t\tif g.prevState[offset[i].y+y][offset[i].x+x].Alive {\n\t\t\t\t\tneighbors++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*Implement game of life ruleset:\n\t\t\t With exactly 2 neighbors: Alive cell stays alive and dead cell stays dead\n\t\t\t With exactly 3 neighbors: Alive cell stays alive and dead cell also lives\n\t\t\t Any other number of neighbors: Alive cell dies and dead cell stays dead\n\t\t\t*/\n\t\t\tif neighbors == 2 {\n\t\t\t\tg.state[y][x] = g.prevState[y][x]\n\t\t\t} else if neighbors == 3 {\n\t\t\t\tg.state[y][x].Alive = true\n\t\t\t} else {\n\t\t\t\tg.state[y][x].Alive = false\n\t\t\t}\n\n\t\t}\n\t}\n\n\t//Update the copy\n\tfor y := 0; y < int(g.rows); y++ {\n\t\tfor x := 0; x < int(g.cols); x++ {\n\t\t\t//+1 to avoid copying the border cells\n\t\t\tg.board[y][x] = g.state[y+1][x+1]\n\t\t}\n\t}\n\n\treturn\n\n}", "func findPaths2(m int, n int, maxMove int, startRow int, startColumn int) int {\n\tprevGrid := make([][]int, m)\n\tnextGrid := make([][]int, m)\n\tfor i := 0; i < m; i++ {\n\t\tprevGrid[i] = make([]int, n)\n\t\tnextGrid[i] = make([]int, n)\n\t}\n\n\tres := 0\n\tprevGrid[startRow][startColumn] = 1\n\n\tfor move := 0; move < maxMove; move++ {\n\t\tfor x := 0; x < m; x++ {\n\t\t\tfor y := 0; y < n; y++ {\n\t\t\t\tv := prevGrid[x][y] % modulo\n\t\t\t\tif v == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tprevGrid[x][y] = 0\n\n\t\t\t\tif x == 0 {\n\t\t\t\t\tres += v\n\t\t\t\t} else {\n\t\t\t\t\tnextGrid[x-1][y] += v\n\t\t\t\t}\n\n\t\t\t\tif x == m-1 {\n\t\t\t\t\tres += v\n\t\t\t\t} else {\n\t\t\t\t\tnextGrid[x+1][y] += v\n\t\t\t\t}\n\n\t\t\t\tif y == 0 {\n\t\t\t\t\tres += v\n\t\t\t\t} else {\n\t\t\t\t\tnextGrid[x][y-1] += v\n\t\t\t\t}\n\n\t\t\t\tif y == n-1 {\n\t\t\t\t\tres += v\n\t\t\t\t} else {\n\t\t\t\t\tnextGrid[x][y+1] += v\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprevGrid, nextGrid = nextGrid, prevGrid\n\t}\n\n\treturn res % modulo\n}", "func numWays(steps int, arrLen int) int {\n\tfor i := 2; i <= 500; i += 2 {\n\t\tresult := calcWays(0, i, i/2, i/2, arrLen-1)\n\t\tcache[i] = result\n\t\tpp.Println(i, result)\n\t}\n\n\treturn calcWays(0, steps, steps/2, steps/2, arrLen-1)\n\t// Since the answer may be too large, return it modulo 10^9 + 7.\n\t// return 0\n}", "func countHoriz(mygame game.Game, playerNum int, streakLength int) int {\n\tcount := 0 //overall # of streaks of n length\n\tcurrCount := 0 //this needs to be exactly n so that we don't count streaks of 2 as streaks of 3\n\tsymbol := mygame.PlayerSymbols[playerNum]\n\t//increment over every square\n\tfor i := 0; i < game.BoardHeight; i++ { //rows\n\t\tfor j := 0; j < game.BoardWidth; j++ { //columns\n\t\t\tif mygame.GameBoard[i][j].Active {\n\t\t\t\t//check that the symbol matches\n\t\t\t\tif mygame.GameBoard[i][j].Symbol == symbol {\n\t\t\t\t\t//make sure piece to left isn't the same symbol\n\t\t\t\t\t//so that we're not double counting\n\t\t\t\t\tif j == 0 || mygame.GameBoard[i][j-1].Symbol != symbol {\n\t\t\t\t\t\tcurrCount++\n\t\t\t\t\t\tfor k := 1; k < 4; k++ {\n\t\t\t\t\t\t\tif j+k < game.BoardWidth { //make sure we don't go off board\n\t\t\t\t\t\t\t\tif mygame.GameBoard[i][j+k].Symbol == symbol {\n\t\t\t\t\t\t\t\t\tcurrCount++\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tbreak //break if different symbol\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//only increment count if currentcount matches n\n\t\t\t\t\t\tif currCount == streakLength {\n\t\t\t\t\t\t\tcount++\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrCount = 0 //reset currCount\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\treturn count\n}", "func Part2(shipMap ShipMap) string {\n\tminutes := 0\n\toxygenatedPoints := []Point{shipMap.grid[shipMap.osY][shipMap.osX]}\n\n\tfor shipMap.Unoxygenated() > 0 {\n\t\tfor _, point := range oxygenatedPoints {\n\t\t\tneighbors := shipMap.Neighbors(point)\n\t\t\tfor idx := 0; idx < len(neighbors); idx++ {\n\t\t\t\tneighbor := neighbors[idx]\n\t\t\t\tshipMap.grid[neighbor.y][neighbor.x].oxygenated = true\n\t\t\t\tif !containsPoint(oxygenatedPoints, neighbor) {\n\t\t\t\t\toxygenatedPoints = append(oxygenatedPoints, neighbor)\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t\tminutes++\n\t}\n\n\treturn \"Answer: \" + strconv.Itoa(minutes)\n}", "func steps(s []int) int {\n\tsteps := 0\n\n\tfor pos := 0; pos >= 0 && pos < len(s); steps += 1 {\n\t\tnewpos := pos + s[pos]\n\t\tif s[pos] >= 3 {\n\t\t\ts[pos] -= 1\n\t\t} else {\n\t\t\ts[pos] += 1\n\t\t}\n\t\tpos = newpos\n\t}\n\n\treturn steps\n}", "func step2(w string) string {\n\tvar endings []string = []string{\"gd\", \"dt\", \"gt\", \"kt\"}\n\n\tfor _, e := range endings {\n\t\tif searchInR1(w, e) {\n\t\t\treturn w[0 : len(w)-1]\n\t\t}\n\t}\n\n\treturn w\n}", "func PathLength(board [][]bool, start, target Coord) (int, bool) {\n\tn := len(board)\n\t// Check if start is out of bounds\n\tif start.Row < 0 || start.Row >= n || start.Col < 0 || start.Col >= len(board[start.Row]) {\n\t\treturn 0, false\n\t}\n\n\t// Check that not a wall\n\tif board[start.Row][start.Col] {\n\t\treturn 0, false\n\t}\n\n\t// Are we done?!\n\tif start == target {\n\t\treturn 0, true\n\t}\n\n\t// Backtracking algorithm\n\n\t// Set board-value at the current position\n\tboard[start.Row][start.Col] = true\n\n\tnSteps := math.MaxInt64\n\n\tup, ok := PathLength(board, Coord{Row: start.Row - 1, Col: start.Col}, target)\n\tnSteps = minIfOkElseFirstArg(nSteps, up, ok)\n\n\tdown, ok := PathLength(board, Coord{Row: start.Row + 1, Col: start.Col}, target)\n\tnSteps = minIfOkElseFirstArg(nSteps, down, ok)\n\n\tleft, ok := PathLength(board, Coord{Row: start.Row, Col: start.Col - 1}, target)\n\tnSteps = minIfOkElseFirstArg(nSteps, left, ok)\n\n\tright, ok := PathLength(board, Coord{Row: start.Row, Col: start.Col + 1}, target)\n\tnSteps = minIfOkElseFirstArg(nSteps, right, ok)\n\n\t// Unset the board-value at the current position\n\tboard[start.Row][start.Col] = false\n\n\t// No direction is valid\n\tif nSteps == math.MaxInt64 {\n\t\treturn -1, false\n\t}\n\n\t// Return minimum number of steps to target\n\treturn 1 + nSteps, true\n}", "func findPaths(m int, n int, N int, i int, j int) int {\n \n}", "func prisonAfterNDays(cells []int, N int) []int {\n \n}", "func stepsToOxygen(d *droid) int {\n\n\t// Run search algorithm (assume no more than n steps are required)\n\tfor i := 0; i < 1000; i++ {\n\t\t// Try to take next step from all existing moves with distance i\n\t\ttryMoves := d.getAllMovesWithDistance(i)\n\t\tfor _, tryMove := range tryMoves {\n\t\t\t// First, navigate to the location of the move chosen\n\t\t\td.moveToPoint(tryMove.location)\n\t\t\t// Take a step in every direction (will populate map of movements)\n\t\t\td.moveEveryDirection()\n\t\t}\n\t\t// Check if target found flag is set, if yes, we're done\n\t\tif d.foundTarget {\n\t\t\treturn i + 1\n\t\t}\n\t}\n\n\tlog.Fatal(\"Could not find target...\")\n\treturn 0\n}", "func TimeToRun(marathonHours, marathonMinutes, miles float64) float64 {\n var speed float64 = 26.2 / (marathonHours * 60 + marathonMinutes)\n var days float64 = (miles / speed) / (24 * 60)\n fmt.Println(\"You could run %.4f in %.4f days.\", miles, days)\n return days\n}", "func TestStepCycle(t *testing.T) {\n\tvar pathways [alphabetSize]int\n\tfor i := 0; i < alphabetSize; i++ {\n\t\tpathways[i] = i\n\t}\n\n\tfor i, test := range []struct {\n\t\tstep int\n\t\tcycle int\n\t\tshouldErr bool\n\t}{\n\t\t{\n\t\t\tstep: 1,\n\t\t\tcycle: 1,\n\t\t\tshouldErr: false,\n\t\t},\n\t\t{\n\t\t\tstep: 1,\n\t\t\tcycle: 2,\n\t\t\tshouldErr: false,\n\t\t},\n\t\t{\n\t\t\tstep: 2,\n\t\t\tcycle: 1,\n\t\t\tshouldErr: false,\n\t\t},\n\t\t{\n\t\t\tstep: 1,\n\t\t\tcycle: 13,\n\t\t\tshouldErr: false,\n\t\t},\n\t\t{\n\t\t\tstep: 13,\n\t\t\tcycle: 1,\n\t\t\tshouldErr: false,\n\t\t},\n\t\t{\n\t\t\tstep: 1,\n\t\t\tcycle: 26,\n\t\t\tshouldErr: false,\n\t\t},\n\t\t{\n\t\t\tstep: 26,\n\t\t\tcycle: 1,\n\t\t\tshouldErr: false,\n\t\t},\n\t\t{\n\t\t\tstep: 2,\n\t\t\tcycle: 13,\n\t\t\tshouldErr: false,\n\t\t},\n\t\t{\n\t\t\tstep: 13,\n\t\t\tcycle: 2,\n\t\t\tshouldErr: false,\n\t\t},\n\t\t{\n\t\t\tstep: 23,\n\t\t\tcycle: 32,\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tstep: 1,\n\t\t\tcycle: -3,\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tstep: 0,\n\t\t\tcycle: 1,\n\t\t\tshouldErr: true,\n\t\t},\n\t} {\n\t\terr := verifyRotor(pathways, 0, test.step, test.cycle)\n\t\tif test.shouldErr && err == nil {\n\t\t\tt.Errorf(\"test %d: want error, got nil\", i)\n\t\t} else if !test.shouldErr && err != nil {\n\t\t\tt.Errorf(\"test %d: want nil, got %w\", i, err)\n\t\t}\n\t}\n}", "func (c Chessboard) validPieceKnight(square int) bool {\n return int(c.boardSquares[square] % 10) == 2\n}", "func (c Chessboard) candSquaresKnight(from int) []int {\n if !c.validPieceKnight(from) {\n return make([]int, 0, 1)\n }\n\n candSquares := make([]int, 0, 16)\n color := c.pieceColorOnPosition(from)\n\n directions := [][]int{{2,1},{-2,1},{2,-1},{-2,-1}, {1,2},{-1,2},{1,-2},{-1,-2}}\n\n for _,v := range(directions) {\n currRow := rowFromPosition(from) + v[0]\n currCol := colFromPosition(from) + v[1]\n\n currPos := posFromRowColumn(currRow, currCol)\n\n if currRow > -1 && currRow < 8 && currCol > -1 && currCol < 8 {\n if c.pieceColorOnPosition(currPos) != color {\n candSquares = append(candSquares, currPos)\n }\n }\n }\n\n return candSquares\n}", "func Day8Part2(filepath string) any {\n\tvar res int\n\n\t// parse out treeMap from file\n\t// open file\n\treadFile, _ := os.Open(filepath)\n\n\t// read line\n\tfileScanner := bufio.NewScanner(readFile)\n\tfileScanner.Split(bufio.ScanLines)\n\n\t// parse map in to [][]int\n\ttreeMap := parseMap(fileScanner)\n\n\t// iterate every tree\n\tfor i := range treeMap {\n\t\tfor j := range treeMap[0] {\n\t\t\t// for every tree, calculate scenicScore\n\t\t\ts := getScenicScore(treeMap, i, j)\n\t\t\t// update max scenic score\n\t\t\tif s > res {\n\t\t\t\tres = s\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}", "func findRescuePathLength(caveDepth, targetX, targetY int, cavePlan cavePlanType) (int, cavePlanType) {\n\tgraphMap := make(graphMapType)\n\tstartTorchKey := graphItemKeyType{0, 0, TORCH}\n\tstartTorch := graphItemType{&startTorchKey, 0, -1, nil, false}\n\tpq := make(priorityQueue, 1)\n\tpq[0] = &startTorch\n\tgraphMap[startTorchKey] = &startTorch\n\theap.Init(&pq)\n\n\tfor len(pq) > 0 {\n\t\thead := heap.Pop(&pq).(*graphItemType)\n\t\thead.processed = true\n\t\t// If target reached return distance\n\t\tif head.x == targetX && head.y == targetY && head.tool == TORCH {\n\t\t\treturn head.dist, cavePlan\n\t\t}\n\t\t// Left\n\t\tif head.x > 0 && cavePlan[head.y][head.x-1].erosion != head.tool {\n\t\t\tcreateGraphItem(head.x-1, head.y, head.tool, head.dist+1, &pq, &graphMap, head)\n\t\t}\n\t\t// Up\n\t\tif head.y > 0 && cavePlan[head.y-1][head.x].erosion != head.tool {\n\t\t\tcreateGraphItem(head.x, head.y-1, head.tool, head.dist+1, &pq, &graphMap, head)\n\t\t}\n\t\t// Generate additional cave plan if required\n\t\tif head.x == len(cavePlan[head.y])-1 {\n\t\t\tcavePlan = addColumn(caveDepth, targetX, targetY, cavePlan)\n\t\t}\n\t\tif head.y == len(cavePlan)-1 {\n\t\t\tcavePlan = addRow(caveDepth, targetX, targetY, cavePlan)\n\t\t}\n\t\t// Right\n\t\tif cavePlan[head.y][head.x+1].erosion != head.tool {\n\t\t\tcreateGraphItem(head.x+1, head.y, head.tool, head.dist+1, &pq, &graphMap, head)\n\t\t}\n\t\t// Down\n\t\tif cavePlan[head.y+1][head.x].erosion != head.tool {\n\t\t\tcreateGraphItem(head.x, head.y+1, head.tool, head.dist+1, &pq, &graphMap, head)\n\t\t}\n\t\t// Change the tool operation is also one of options\n\t\tnewTool := (head.tool + 1) % 3\n\t\tif newTool == cavePlan[head.y][head.x].erosion {\n\t\t\tnewTool = (newTool + 1) % 3\n\t\t}\n\t\tcreateGraphItem(head.x, head.y, newTool, head.dist+7, &pq, &graphMap, head)\n\t}\n\treturn -1, cavePlan\n}", "func (r *Register) totalSteps() string {\n\treturn fmt.Sprintf(\"%d\", len(r.steps)-1)\n}", "func (c Chessboard) validMoveKnight(from int, to int) bool {\n if !c.validPieceKnight(from) {\n return false\n }\n\n fromRow := rowFromPosition(from)\n fromCol := colFromPosition(from)\n toRow := rowFromPosition(to)\n toCol := colFromPosition(to)\n\n if ((toRow == (fromRow - 2) || toRow == (fromRow + 2)) &&\n (toCol == (fromCol - 1) || toCol == (fromCol + 1))) {\n\n return true\n\n }\n\n if ((toRow == (fromRow - 1) || toRow == (fromRow + 1)) &&\n (toCol == (fromCol - 2) || toCol == (fromCol + 2))) {\n\n return true\n\n }\n\n return false\n}", "func Test_step1(t *testing.T) {\n\ttestCases := []romance.StepTestCase{\n\t\t{\"rapidement\", 3, 5, 2, true, \"rapid\", 3, 5, 2},\n\t\t{\"paresseuse\", 3, 5, 3, true, \"paress\", 3, 5, 3},\n\t\t{\"prosaïqUement\", 4, 7, 3, true, \"prosaïqU\", 4, 7, 3},\n\t\t{\"nonchalance\", 3, 7, 2, true, \"nonchal\", 3, 7, 2},\n\t\t{\"apostoliqUes\", 2, 4, 3, true, \"apostol\", 2, 4, 3},\n\t\t{\"assiduités\", 2, 5, 4, true, \"assidu\", 2, 5, 4},\n\t\t{\"philosophiqUement\", 4, 6, 3, true, \"philosoph\", 4, 6, 3},\n\t\t{\"despotiqUement\", 3, 6, 2, true, \"despot\", 3, 6, 2},\n\t\t{\"incontestablement\", 2, 5, 4, true, \"incontest\", 2, 5, 4},\n\t\t{\"diminution\", 3, 5, 2, true, \"diminu\", 3, 5, 2},\n\t\t{\"séditieuse\", 3, 5, 2, true, \"séditi\", 3, 5, 2},\n\t\t{\"anonymement\", 2, 4, 3, true, \"anonym\", 2, 4, 3},\n\t\t{\"conservation\", 3, 6, 2, true, \"conserv\", 3, 6, 2},\n\t\t{\"fâcheuses\", 3, 7, 2, true, \"fâcheux\", 3, 7, 2},\n\t\t{\"houleuse\", 4, 7, 2, true, \"houleux\", 4, 7, 2},\n\t\t{\"historiqUes\", 3, 6, 2, true, \"histor\", 3, 6, 2},\n\t\t{\"impérieusement\", 2, 5, 4, true, \"impéri\", 2, 5, 4},\n\t\t{\"complaisances\", 3, 8, 2, true, \"complais\", 3, 8, 2},\n\t\t{\"confessionnaux\", 3, 6, 2, true, \"confessionnal\", 3, 6, 2},\n\t\t{\"grandement\", 4, 7, 3, true, \"grand\", 4, 5, 3},\n\t\t{\"passablement\", 3, 6, 2, true, \"passabl\", 3, 6, 2},\n\t\t{\"strictement\", 5, 8, 4, true, \"strict\", 5, 6, 4},\n\t\t{\"physiqUement\", 4, 6, 3, true, \"physiqU\", 4, 6, 3},\n\t\t{\"serieusement\", 3, 7, 2, true, \"serieux\", 3, 7, 2},\n\t\t{\"roulement\", 4, 6, 2, true, \"roul\", 4, 4, 2},\n\t\t{\"appartement\", 2, 5, 4, true, \"appart\", 2, 5, 4},\n\t\t{\"reconnaissance\", 3, 5, 2, true, \"reconnaiss\", 3, 5, 2},\n\t\t{\"aigrement\", 3, 6, 3, true, \"aigr\", 3, 4, 3},\n\t\t{\"impertinences\", 2, 5, 4, true, \"impertinent\", 2, 5, 4},\n\t\t{\"parlement\", 3, 6, 3, true, \"parl\", 3, 4, 3},\n\t\t{\"malicieux\", 3, 5, 2, true, \"malici\", 3, 5, 2},\n\t\t{\"suffisance\", 3, 6, 2, true, \"suffis\", 3, 6, 2},\n\t\t{\"prémédité\", 4, 6, 3, true, \"préméd\", 4, 6, 3},\n\t\t{\"métalliqUes\", 3, 5, 2, true, \"métall\", 3, 5, 2},\n\t\t{\"météorologiste\", 3, 6, 2, true, \"météorolog\", 3, 6, 2},\n\t\t{\"prononciation\", 4, 6, 3, true, \"prononci\", 4, 6, 3},\n\t\t{\"nombreuse\", 3, 8, 2, true, \"nombreux\", 3, 8, 2},\n\t\t{\"extatiqUe\", 2, 5, 4, true, \"extat\", 2, 5, 4},\n\t\t{\"magnifiqUement\", 3, 6, 2, true, \"magnif\", 3, 6, 2},\n\t\t{\"gymnastiqUe\", 3, 6, 2, true, \"gymnast\", 3, 6, 2},\n\t\t{\"dramatiqUe\", 4, 6, 3, true, \"dramat\", 4, 6, 3},\n\t\t{\"simplicité\", 3, 7, 2, true, \"simpliqU\", 3, 7, 2},\n\t\t{\"roYalistes\", 3, 5, 2, true, \"roYal\", 3, 5, 2},\n\t\t{\"fortifications\", 3, 6, 2, true, \"fortif\", 3, 6, 2},\n\t\t{\"attendrissement\", 2, 5, 4, true, \"attendr\", 2, 5, 4},\n\t\t{\"respectueusement\", 3, 6, 2, true, \"respectu\", 3, 6, 2},\n\t\t{\"patriotisme\", 3, 7, 2, true, \"patriot\", 3, 7, 2},\n\t\t{\"curieuse\", 3, 7, 2, true, \"curieux\", 3, 7, 2},\n\t\t{\"fascination\", 3, 6, 2, true, \"fascin\", 3, 6, 2},\n\t\t{\"effectivement\", 2, 5, 4, true, \"effect\", 2, 5, 4},\n\t\t{\"condoléance\", 3, 6, 2, true, \"condolé\", 3, 6, 2},\n\t\t{\"malignité\", 3, 5, 2, true, \"malign\", 3, 5, 2},\n\t\t{\"capricieuse\", 3, 6, 2, true, \"caprici\", 3, 6, 2},\n\t\t{\"applaudissements\", 2, 7, 5, true, \"applaud\", 2, 7, 5},\n\t\t{\"praticable\", 4, 6, 3, true, \"pratic\", 4, 6, 3},\n\t\t{\"rivaux\", 3, 6, 2, true, \"rival\", 3, 5, 2},\n\t\t{\"augmentation\", 3, 6, 3, true, \"augment\", 3, 6, 3},\n\t\t{\"ameublement\", 2, 5, 3, true, \"ameubl\", 2, 5, 3},\n\t\t{\"honorables\", 3, 5, 2, true, \"honor\", 3, 5, 2},\n\t\t{\"effervescence\", 2, 5, 4, true, \"effervescent\", 2, 5, 4},\n\t\t{\"excentricité\", 2, 5, 4, true, \"excentr\", 2, 5, 4},\n\t\t{\"misérable\", 3, 5, 2, true, \"misér\", 3, 5, 2},\n\t\t{\"capitulation\", 3, 5, 2, true, \"capitul\", 3, 5, 2},\n\t\t{\"enjoUement\", 2, 5, 4, true, \"enjoU\", 2, 5, 4},\n\t\t{\"sévérité\", 3, 5, 2, true, \"sévér\", 3, 5, 2},\n\t\t{\"perplexités\", 3, 7, 2, true, \"perplex\", 3, 7, 2},\n\t\t{\"consentement\", 3, 6, 2, true, \"consent\", 3, 6, 2},\n\t\t{\"convocation\", 3, 6, 2, true, \"convoc\", 3, 6, 2},\n\t\t{\"assurances\", 2, 5, 4, true, \"assur\", 2, 5, 4},\n\t\t{\"ébloUissement\", 2, 5, 4, true, \"ébloU\", 2, 5, 4},\n\t\t{\"méridionaux\", 3, 5, 2, true, \"méridional\", 3, 5, 2},\n\t\t{\"dérangements\", 3, 5, 2, true, \"dérang\", 3, 5, 2},\n\t\t{\"domination\", 3, 5, 2, true, \"domin\", 3, 5, 2},\n\t\t{\"incroYable\", 2, 6, 5, true, \"incroY\", 2, 6, 5},\n\t\t{\"réjoUissances\", 3, 5, 2, true, \"réjoUiss\", 3, 5, 2},\n\t\t{\"décadence\", 3, 5, 2, true, \"décadent\", 3, 5, 2},\n\t\t{\"bâillement\", 4, 7, 2, true, \"bâill\", 4, 5, 2},\n\t\t{\"habillement\", 3, 5, 2, true, \"habill\", 3, 5, 2},\n\t\t{\"irréparablement\", 2, 5, 4, true, \"irrépar\", 2, 5, 4},\n\t\t{\"diplomatiqUes\", 3, 6, 2, true, \"diplomat\", 3, 6, 2},\n\t\t{\"distribution\", 3, 7, 2, true, \"distribu\", 3, 7, 2},\n\t\t{\"pétulance\", 3, 5, 2, true, \"pétul\", 3, 5, 2},\n\t\t{\"considérable\", 3, 6, 2, true, \"considér\", 3, 6, 2},\n\t\t{\"éducation\", 2, 4, 3, true, \"éduc\", 2, 4, 3},\n\t\t{\"indications\", 2, 5, 4, true, \"indiqU\", 2, 5, 4},\n\t\t{\"cupidité\", 3, 5, 2, true, \"cupid\", 3, 5, 2},\n\t\t{\"traîtreusement\", 5, 9, 3, true, \"traîtreux\", 5, 9, 3},\n\t\t{\"silencieuse\", 3, 5, 2, true, \"silenci\", 3, 5, 2},\n\t\t{\"pessimisme\", 3, 6, 2, true, \"pessim\", 3, 6, 2},\n\t\t{\"préoccupation\", 5, 8, 3, true, \"préoccup\", 5, 8, 3},\n\t\t// Special cases that should return false despite\n\t\t// being changed. They \"don't count\".\n\t\t{\"compliment\", 3, 7, 2, false, \"compli\", 3, 6, 2},\n\t\t{\"vraiment\", 5, 7, 3, false, \"vrai\", 4, 4, 3},\n\t\t{\"remercîment\", 3, 5, 2, false, \"remercî\", 3, 5, 2},\n\t\t{\"puissamment\", 4, 7, 2, false, \"puissant\", 4, 7, 2},\n\t\t{\"absolument\", 2, 5, 4, false, \"absolu\", 2, 5, 4},\n\t\t{\"décidément\", 3, 5, 2, false, \"décidé\", 3, 5, 2},\n\t\t{\"condiments\", 3, 6, 2, false, \"condi\", 3, 5, 2},\n\t}\n\tromance.RunStepTest(t, step1, testCases)\n\n}", "func findPaths(m int, n int, maxMove int, startRow int, startColumn int) int {\n\tgrid := make([][][]int, maxMove+1)\n\tfor k := 0; k <= maxMove; k++ {\n\t\tgrid[k] = make([][]int, m)\n\t\tfor i := 0; i < m; i++ {\n\t\t\tgrid[k][i] = make([]int, n)\n\t\t}\n\t}\n\n\tres := 0\n\tgrid[0][startRow][startColumn] = 1\n\n\tfor move := 0; move < maxMove; move++ {\n\t\tfor x := 0; x < m; x++ {\n\t\t\tfor y := 0; y < n; y++ {\n\t\t\t\tv := grid[move][x][y] % modulo\n\t\t\t\tif v == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif x == 0 {\n\t\t\t\t\tres += v\n\t\t\t\t} else {\n\t\t\t\t\tgrid[move+1][x-1][y] += v\n\t\t\t\t}\n\n\t\t\t\tif x == m-1 {\n\t\t\t\t\tres += v\n\t\t\t\t} else {\n\t\t\t\t\tgrid[move+1][x+1][y] += v\n\t\t\t\t}\n\n\t\t\t\tif y == 0 {\n\t\t\t\t\tres += v\n\t\t\t\t} else {\n\t\t\t\t\tgrid[move+1][x][y-1] += v\n\t\t\t\t}\n\n\t\t\t\tif y == n-1 {\n\t\t\t\t\tres += v\n\t\t\t\t} else {\n\t\t\t\t\tgrid[move+1][x][y+1] += v\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res % modulo\n}", "func stepSeatMap(seatMap *SeatMap, count CountNeighbours, neighbourLimit int) (*SeatMap, bool) {\n\tnewMap := &SeatMap{\n\t\tseats: make([][]rune, len(seatMap.seats)),\n\t\toccupied: 0,\n\t}\n\tchanged := false\n\n\tfor i := 0; i < len(seatMap.seats); i++ {\n\t\tnewMap.seats[i] = make([]rune, len(seatMap.seats[i]))\n\t\tfor j := 0; j < len(seatMap.seats[i]); j++ {\n\t\t\tif seatMap.seats[i][j] == '.' {\n\t\t\t\tnewMap.seats[i][j] = '.'\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\toccupiedNeighbours := count(seatMap, i, j)\n\t\t\tif seatMap.seats[i][j] == 'L' {\n\t\t\t\tif occupiedNeighbours == 0 {\n\t\t\t\t\tnewMap.seats[i][j] = '#'\n\t\t\t\t\tchanged = true\n\t\t\t\t\tnewMap.occupied++\n\t\t\t\t} else {\n\t\t\t\t\tnewMap.seats[i][j] = 'L'\n\t\t\t\t}\n\t\t\t} else if seatMap.seats[i][j] == '#' {\n\t\t\t\tif occupiedNeighbours < neighbourLimit {\n\t\t\t\t\tnewMap.seats[i][j] = '#'\n\t\t\t\t\tnewMap.occupied++\n\t\t\t\t} else {\n\t\t\t\t\tnewMap.seats[i][j] = 'L'\n\t\t\t\t\tchanged = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn newMap, !changed\n}", "func kerDIT8(a []fr.Element, twiddles [][]fr.Element, stage int) {\n\n\tfr.Butterfly(&a[0], &a[1])\n\tfr.Butterfly(&a[2], &a[3])\n\tfr.Butterfly(&a[4], &a[5])\n\tfr.Butterfly(&a[6], &a[7])\n\tfr.Butterfly(&a[0], &a[2])\n\ta[3].Mul(&a[3], &twiddles[stage+1][1])\n\tfr.Butterfly(&a[1], &a[3])\n\tfr.Butterfly(&a[4], &a[6])\n\ta[7].Mul(&a[7], &twiddles[stage+1][1])\n\tfr.Butterfly(&a[5], &a[7])\n\tfr.Butterfly(&a[0], &a[4])\n\ta[5].Mul(&a[5], &twiddles[stage+0][1])\n\tfr.Butterfly(&a[1], &a[5])\n\ta[6].Mul(&a[6], &twiddles[stage+0][2])\n\tfr.Butterfly(&a[2], &a[6])\n\ta[7].Mul(&a[7], &twiddles[stage+0][3])\n\tfr.Butterfly(&a[3], &a[7])\n}", "func TestTakeSteps(t *testing.T) {\n\tfor i, test := range []struct {\n\t\trotors *Rotors\n\t\tsteps []int\n\t\texpected [][]int\n\t}{\n\t\t{\n\t\t\trotors: newTestRotors(\n\t\t\t\tt,\n\t\t\t\t[]int{0, 0, 0},\n\t\t\t\t[]int{1, 1, 1},\n\t\t\t\t[]int{26, 26, 26},\n\t\t\t),\n\t\t\tsteps: []int{10, 26 * 26 * 26},\n\t\t\texpected: [][]int{{10, 0, 0}, {10, 0, 0}},\n\t\t},\n\t\t{\n\t\t\trotors: newTestRotors(\n\t\t\t\tt,\n\t\t\t\t[]int{1, 0, 0},\n\t\t\t\t[]int{1, 1, 1},\n\t\t\t\t[]int{2, 2, 2},\n\t\t\t),\n\t\t\tsteps: []int{3, 20},\n\t\t\texpected: [][]int{{4, 2, 1}, {24, 12, 6}},\n\t\t},\n\t\t{\n\t\t\trotors: newTestRotors(\n\t\t\t\tt,\n\t\t\t\t[]int{0, 13, 0},\n\t\t\t\t[]int{13, 13, 13},\n\t\t\t\t[]int{2, 2, 2},\n\t\t\t),\n\t\t\tsteps: []int{2, 8},\n\t\t\texpected: [][]int{{0, 0, 13}, {0, 0, 13}},\n\t\t},\n\t\t{\n\t\t\trotors: newTestRotors(\n\t\t\t\tt,\n\t\t\t\t[]int{0, 0, 0},\n\t\t\t\t[]int{2, 2, 2},\n\t\t\t\t[]int{13, 13, 13},\n\t\t\t),\n\t\t\tsteps: []int{1, 14},\n\t\t\texpected: [][]int{{2, 0, 0}, {4, 2, 0}},\n\t\t},\n\t\t{\n\t\t\trotors: newTestRotors(\n\t\t\t\tt,\n\t\t\t\t[]int{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\t[]int{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},\n\t\t\t\t[]int{26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26},\n\t\t\t),\n\t\t\tsteps: []int{5, 26 * 26 * 26 * 26},\n\t\t\texpected: [][]int{\n\t\t\t\t{5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\t{5, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\trotors: newTestRotors(\n\t\t\t\tt,\n\t\t\t\t[]int{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\t[]int{13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13},\n\t\t\t\t[]int{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},\n\t\t\t),\n\t\t\tsteps: []int{15, 30},\n\t\t\texpected: [][]int{\n\t\t\t\t{13, 13, 13, 13, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\t{13, 0, 13, 13, 0, 13, 0, 0, 0, 0, 0, 0},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\trotors: newTestRotors(\n\t\t\t\tt,\n\t\t\t\t[]int{0, 0, 0},\n\t\t\t\t[]int{1, 2, 1},\n\t\t\t\t[]int{1, 13, 26},\n\t\t\t),\n\t\t\tsteps: []int{8, 2},\n\t\t\texpected: [][]int{{8, 16, 0}, {10, 20, 0}},\n\t\t},\n\t\t{\n\t\t\trotors: newTestRotors(\n\t\t\t\tt,\n\t\t\t\t[]int{\n\t\t\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t\t},\n\t\t\t\t[]int{\n\t\t\t\t\t13, 2, 13, 2, 13, 2, 13, 2, 13, 2,\n\t\t\t\t\t13, 2, 13, 2, 13, 2, 13, 2, 13, 2,\n\t\t\t\t\t13, 2, 13, 2, 13, 2, 13, 2, 13, 2,\n\t\t\t\t},\n\t\t\t\t[]int{\n\t\t\t\t\t2, 13, 2, 13, 2, 13, 2, 13, 2, 13,\n\t\t\t\t\t2, 13, 2, 13, 2, 13, 2, 13, 2, 13,\n\t\t\t\t\t2, 13, 2, 13, 2, 13, 2, 13, 2, 13,\n\t\t\t\t},\n\t\t\t),\n\t\t\tsteps: []int{30, 30},\n\t\t\texpected: [][]int{\n\t\t\t\t{\n\t\t\t\t\t0, 4, 13, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t0, 8, 0, 2, 0, 0, 0, 0, 0, 0,\n\t\t\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t} {\n\t\tfor j, step := range test.steps {\n\t\t\tfor k := 0; k < step; k++ {\n\t\t\t\ttest.rotors.takeStep()\n\t\t\t}\n\n\t\t\tif diff := cmp.Diff(test.expected[j], test.rotors.Setting()); diff != \"\" {\n\t\t\t\tt.Errorf(\"test %d: mismatch (-want +got):\\n%s\", i, diff)\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *statement) prevTurn() int {\n\treturn (s.Step+2)%4 + 1\n}", "func main() {\n\tg, nodesMap := graphLineByLine()\n\n\tstart := nodesMap[\"shiny gold\"]\n\tcount := 0\n\tgraph.BFS(g, start, func(v, w int, _ int64) {\n\t\t//fmt.Println(v, \"to\", w)\n\t\tcount++\n\n\t})\n\n\tfmt.Println(count)\n}", "func mapSteps(g *GraphFile, edgeIndices []int) int {\n\tsize := 0\n\tfor e := 0; e < g.EdgeCount(); e++ {\n\t\tif edgeIndices[e] == -1 {\n\t\t\tcontinue\n\t\t}\n\t\tsize += int(g.Steps[e+1] - g.Steps[e])\n\t}\n\treturn size\n}", "func stepPerms(n int32) int32 {\n\tcollection := &StepsPremsCollection{memory: make(map[int32]int32)}\n\treturn collection.getPerms(n)\n}", "func countVert(mygame game.Game, playerNum int, streakLength int) int {\n\n\tcount := 0 //overall # of streaks of n length\n\tcurrCount := 0 //this needs to be exactly n so that we don't count streaks of 2 as streaks of 3\n\tsymbol := mygame.PlayerSymbols[playerNum]\n\n\t//increment over every square\n\tfor i := 0; i < game.BoardHeight; i++ { //rows\n\t\tfor j := 0; j < game.BoardWidth; j++ { //columns\n\n\t\t\tif mygame.GameBoard[i][j].Active {\n\t\t\t\t//check that the symbol matches\n\t\t\t\tif mygame.GameBoard[i][j].Symbol == symbol {\n\t\t\t\t\t//make sure piece above isn't the same symbol\n\t\t\t\t\t//so that we're not double counting\n\t\t\t\t\tif i == 0 || mygame.GameBoard[i-1][j].Symbol != symbol {\n\t\t\t\t\t\tcurrCount++\n\t\t\t\t\t\tfor k := 1; k < 4; k++ {\n\t\t\t\t\t\t\tif i+k < game.BoardHeight { //make sure we don't go off board\n\t\t\t\t\t\t\t\tif mygame.GameBoard[i+k][j].Symbol == symbol {\n\t\t\t\t\t\t\t\t\tcurrCount++\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tbreak //break if different symbol\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//only increment count if currentcount matches n\n\n\t\t\t\t\t\tif currCount == streakLength {\n\t\t\t\t\t\t\tcount++\n\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrCount = 0 //reset currCount\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\treturn count\n}", "func Test_step2b(t *testing.T) {\n\ttestCases := []romance.StepTestCase{\n\t\t{\"posée\", 3, 5, 2, true, \"pos\", 3, 3, 2},\n\t\t{\"contentait\", 3, 6, 2, true, \"content\", 3, 6, 2},\n\t\t{\"évita\", 2, 4, 3, true, \"évit\", 2, 4, 3},\n\t\t{\"cantonnées\", 3, 6, 2, true, \"cantonn\", 3, 6, 2},\n\t\t{\"tender\", 3, 6, 2, true, \"tend\", 3, 4, 2},\n\t\t{\"survenait\", 3, 6, 2, true, \"surven\", 3, 6, 2},\n\t\t{\"plongeaIent\", 4, 8, 3, true, \"plong\", 4, 5, 3},\n\t\t{\"modéra\", 3, 5, 2, true, \"modér\", 3, 5, 2},\n\t\t{\"copier\", 3, 6, 2, true, \"copi\", 3, 4, 2},\n\t\t{\"bougez\", 4, 6, 2, true, \"boug\", 4, 4, 2},\n\t\t{\"déploYaIent\", 3, 6, 2, true, \"déploY\", 3, 6, 2},\n\t\t{\"entendra\", 2, 5, 4, true, \"entendr\", 2, 5, 4},\n\t\t{\"blâmer\", 4, 6, 3, true, \"blâm\", 4, 4, 3},\n\t\t{\"déshonorait\", 3, 6, 2, true, \"déshonor\", 3, 6, 2},\n\t\t{\"concentrés\", 3, 6, 2, true, \"concentr\", 3, 6, 2},\n\t\t{\"mangeant\", 3, 7, 2, true, \"mang\", 3, 4, 2},\n\t\t{\"écouteront\", 2, 5, 3, true, \"écout\", 2, 5, 3},\n\t\t{\"pressaIent\", 4, 7, 3, true, \"press\", 4, 5, 3},\n\t\t{\"ébréché\", 2, 5, 4, true, \"ébréch\", 2, 5, 4},\n\t\t{\"frapper\", 4, 7, 3, true, \"frapp\", 4, 5, 3},\n\t\t{\"côtoYé\", 3, 5, 2, true, \"côtoY\", 3, 5, 2},\n\t\t{\"réfugié\", 3, 5, 2, true, \"réfugi\", 3, 5, 2},\n\t\t{\"jeûnant\", 4, 6, 2, true, \"jeûn\", 4, 4, 2},\n\t\t{\"succombé\", 3, 6, 2, true, \"succomb\", 3, 6, 2},\n\t\t{\"irrité\", 2, 5, 4, true, \"irrit\", 2, 5, 4},\n\t\t{\"danger\", 3, 6, 2, true, \"dang\", 3, 4, 2},\n\t\t{\"sachant\", 3, 6, 2, true, \"sach\", 3, 4, 2},\n\t\t{\"reparaissaIent\", 3, 5, 2, true, \"reparaiss\", 3, 5, 2},\n\t\t{\"reconnaissant\", 3, 5, 2, true, \"reconnaiss\", 3, 5, 2},\n\t\t{\"faisant\", 4, 6, 2, true, \"fais\", 4, 4, 2},\n\t\t{\"arrangés\", 2, 5, 4, true, \"arrang\", 2, 5, 4},\n\t\t{\"emparés\", 2, 5, 4, true, \"empar\", 2, 5, 4},\n\t\t{\"choqUée\", 4, 7, 3, true, \"choqU\", 4, 5, 3},\n\t\t{\"gênait\", 3, 6, 2, true, \"gên\", 3, 3, 2},\n\t\t{\"croissante\", 5, 8, 3, true, \"croiss\", 5, 6, 3},\n\t\t{\"scié\", 4, 4, 3, true, \"sci\", 3, 3, 3},\n\t\t{\"reconnaissez\", 3, 5, 2, true, \"reconnaiss\", 3, 5, 2},\n\t\t{\"pliaIent\", 5, 7, 3, true, \"pli\", 3, 3, 3},\n\t\t{\"expédia\", 2, 5, 4, true, \"expédi\", 2, 5, 4},\n\t\t{\"déshabillaIent\", 3, 6, 2, true, \"déshabill\", 3, 6, 2},\n\t\t{\"appréciée\", 2, 6, 5, true, \"appréci\", 2, 6, 5},\n\t\t{\"amputés\", 2, 5, 4, true, \"amput\", 2, 5, 4},\n\t\t{\"dominait\", 3, 5, 2, true, \"domin\", 3, 5, 2},\n\t\t{\"vexantes\", 3, 5, 2, true, \"vex\", 3, 3, 2},\n\t\t{\"fabriqUées\", 3, 6, 2, true, \"fabriqU\", 3, 6, 2},\n\t\t{\"retomber\", 3, 5, 2, true, \"retomb\", 3, 5, 2},\n\t\t{\"exercer\", 2, 4, 3, true, \"exerc\", 2, 4, 3},\n\t\t{\"entourait\", 2, 6, 4, true, \"entour\", 2, 6, 4},\n\t\t{\"voYait\", 3, 6, 2, true, \"voY\", 3, 3, 2},\n\t\t{\"soupait\", 4, 7, 2, true, \"soup\", 4, 4, 2},\n\t\t{\"apportiez\", 2, 5, 4, true, \"apport\", 2, 5, 4},\n\t\t{\"tuée\", 4, 4, 2, true, \"tu\", 2, 2, 2},\n\t\t{\"proposait\", 4, 6, 3, true, \"propos\", 4, 6, 3},\n\t\t{\"citations\", 3, 5, 2, true, \"citat\", 3, 5, 2},\n\t\t{\"distinguée\", 3, 6, 2, true, \"distingu\", 3, 6, 2},\n\t\t{\"parlerez\", 3, 6, 3, true, \"parl\", 3, 4, 3},\n\t\t{\"stanislas\", 4, 6, 3, true, \"stanisl\", 4, 6, 3},\n\t\t{\"enlevée\", 2, 5, 4, true, \"enlev\", 2, 5, 4},\n\t\t{\"irriguaIent\", 2, 5, 4, true, \"irrigu\", 2, 5, 4},\n\t\t{\"contenant\", 3, 6, 2, true, \"conten\", 3, 6, 2},\n\t\t{\"empêchèrent\", 2, 5, 4, true, \"empêch\", 2, 5, 4},\n\t\t{\"inspirées\", 2, 6, 5, true, \"inspir\", 2, 6, 5},\n\t\t{\"basée\", 3, 5, 2, true, \"bas\", 3, 3, 2},\n\t\t{\"consultait\", 3, 6, 2, true, \"consult\", 3, 6, 2},\n\t\t{\"retardait\", 3, 5, 2, true, \"retard\", 3, 5, 2},\n\t\t{\"enlevât\", 2, 5, 4, true, \"enlev\", 2, 5, 4},\n\t\t{\"convenaIent\", 3, 6, 2, true, \"conven\", 3, 6, 2},\n\t\t{\"portât\", 3, 6, 2, true, \"port\", 3, 4, 2},\n\t\t{\"admirée\", 2, 5, 4, true, \"admir\", 2, 5, 4},\n\t\t{\"copiée\", 3, 6, 2, true, \"copi\", 3, 4, 2},\n\t\t{\"démenaIent\", 3, 5, 2, true, \"démen\", 3, 5, 2},\n\t\t{\"fortifiées\", 3, 6, 2, true, \"fortifi\", 3, 6, 2},\n\t\t{\"apercevrait\", 2, 4, 3, true, \"apercevr\", 2, 4, 3},\n\t\t{\"risqUer\", 3, 7, 2, true, \"risqU\", 3, 5, 2},\n\t\t{\"réclamer\", 3, 6, 2, true, \"réclam\", 3, 6, 2},\n\t\t{\"tremblaIent\", 4, 8, 3, true, \"trembl\", 4, 6, 3},\n\t\t{\"calomnier\", 3, 5, 2, true, \"calomni\", 3, 5, 2},\n\t\t{\"réclamée\", 3, 6, 2, true, \"réclam\", 3, 6, 2},\n\t\t{\"déposât\", 3, 5, 2, true, \"dépos\", 3, 5, 2},\n\t\t{\"filé\", 3, 4, 2, true, \"fil\", 3, 3, 2},\n\t\t{\"déchirée\", 3, 6, 2, true, \"déchir\", 3, 6, 2},\n\t\t{\"prononça\", 4, 6, 3, true, \"prononç\", 4, 6, 3},\n\t\t{\"précédé\", 4, 6, 3, true, \"précéd\", 4, 6, 3},\n\t\t{\"asseYait\", 2, 5, 4, true, \"asseY\", 2, 5, 4},\n\t\t{\"emploYés\", 2, 6, 5, true, \"emploY\", 2, 6, 5},\n\t\t{\"chagriner\", 4, 7, 3, true, \"chagrin\", 4, 7, 3},\n\t\t{\"dévorât\", 3, 5, 2, true, \"dévor\", 3, 5, 2},\n\t\t{\"remonté\", 3, 5, 2, true, \"remont\", 3, 5, 2},\n\t\t{\"emploYant\", 2, 6, 5, true, \"emploY\", 2, 6, 5},\n\t\t{\"redoublait\", 3, 6, 2, true, \"redoubl\", 3, 6, 2},\n\t\t{\"marchant\", 3, 7, 2, true, \"march\", 3, 5, 2},\n\t\t{\"pétrifiée\", 3, 6, 2, true, \"pétrifi\", 3, 6, 2},\n\t\t{\"enlevées\", 2, 5, 4, true, \"enlev\", 2, 5, 4},\n\t\t{\"donnassent\", 3, 6, 2, true, \"donn\", 3, 4, 2},\n\t\t{\"recomptait\", 3, 5, 2, true, \"recompt\", 3, 5, 2},\n\t\t{\"masqUait\", 3, 8, 2, true, \"masqU\", 3, 5, 2},\n\t\t{\"renouvelèrent\", 3, 6, 2, true, \"renouvel\", 3, 6, 2},\n\t\t{\"recoucher\", 3, 6, 2, true, \"recouch\", 3, 6, 2},\n\t\t{\"abrégea\", 2, 5, 4, true, \"abrég\", 2, 5, 4},\n\t\t{\"flattait\", 4, 8, 3, true, \"flatt\", 4, 5, 3},\n\t}\n\tromance.RunStepTest(t, step2b, testCases)\n}", "func Day8Part2(input []string) (string, error) {\n\n\timData := input[0]\n\timWidth, imHeight := 25, 6\n\n\tlayers := generateLayers(imData, imWidth, imHeight)\n\n\tmessage := \"\"\n\tfor y := 0; y < imHeight; y++ {\n\t\tfor x := 0; x < imWidth; x++ {\n\t\t\tmessage += getMessagePixel(layers, x, y)\n\t\t}\n\t\tmessage += \"\\n\"\n\t}\n\n\treturn message, nil\n}", "func gameOfLife(board [][]int) {\n\tm := len(board)\n\tn := len(board[0])\n\tfor y := 0; y < m; y++ {\n\t\tfor x := 0; x < n; x++ {\n\t\t\tneighbors := 0\n\t\t\tif y > 0 {\n\t\t\t\tneighbors += board[y-1][x] & 1\n\t\t\t\tif x > 0 {\n\t\t\t\t\tneighbors += board[y-1][x-1] & 1\n\t\t\t\t}\n\t\t\t\tif x < n-1 {\n\t\t\t\t\tneighbors += board[y-1][x+1] & 1\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif y < m-1 {\n\t\t\t\tneighbors += board[y+1][x] & 1\n\t\t\t\tif x > 0 {\n\t\t\t\t\tneighbors += board[y+1][x-1] & 1\n\t\t\t\t}\n\t\t\t\tif x < n-1 {\n\t\t\t\t\tneighbors += board[y+1][x+1] & 1\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif x > 0 {\n\t\t\t\tneighbors += board[y][x-1] & 1\n\t\t\t}\n\n\t\t\tif x < n-1 {\n\t\t\t\tneighbors += board[y][x+1] & 1\n\t\t\t}\n\n\t\t\tlive := 1 == (board[y][x] & 1)\n\t\t\tswitch {\n\t\t\tcase !live && neighbors == 3:\n\t\t\t\tboard[y][x] |= 2\n\t\t\tcase live && (neighbors == 2 || neighbors == 3):\n\t\t\t\tboard[y][x] |= 2\n\t\t\t}\n\t\t}\n\t}\n\n\tfor y := 0; y < m; y++ {\n\t\tfor x := 0; x < n; x++ {\n\t\t\tboard[y][x] >>= 1\n\t\t}\n\t}\n}", "func main() {\n\tinstructions := readLineByLine()\n\n\tvar accumulator int\n\tvar hasCycles bool\n\tinstructionsSwitched := make(map[int]instruction)\n\ti := 0\n\n\tfor i > -1 {\n\t\tfor k, v := range instructions {\n\t\t\tinstructionsSwitched[k] = v\n\t\t}\n\n\t\tif i > len(instructions) {\n\t\t\tbreak\n\t\t}\n\t\t// cycle through instructions and if found nop or jmp switch > create new instructions\n\t\t// calculate accumulator and if has cycles\n\t\taction := instructions[i].action\n\t\tif action == \"jmp\" || action == \"nop\" {\n\t\t\tif action == \"jmp\" {\n\t\t\t\tmove := instructions[i].move\n\t\t\t\tinstructionsSwitched[i] = instruction{\"nop\", move}\n\t\t\t\taccumulator, hasCycles = computeAcc(instructionsSwitched)\n\t\t\t}\n\t\t\tif action == \"nop\" {\n\t\t\t\tmove := instructions[i].move\n\t\t\t\tinstructionsSwitched[i] = instruction{\"jmp\", move}\n\t\t\t\taccumulator, hasCycles = computeAcc(instructionsSwitched)\n\t\t\t}\n\t\t\tif !hasCycles {\n\t\t\t\tfmt.Println(\"no cycle found\", i)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif hasCycles {\n\t\t\t\tfmt.Println(\"cycle found\", i)\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\t\tif action == \"acc\" {\n\t\t\ti++\n\t\t}\n\t}\n\n\tfmt.Println(accumulator)\n\t//fmt.Println(g, nodesMap)\n}", "func tictactoe(moves [][]int) string {\n\tgrid := [3][3]int{}\n\n\tbefore := 1\n\tfor _, move := range moves {\n\t\tgrid[move[0]][move[1]] = before\n\t\tswitch before {\n\t\tcase 1:\n\t\t\tbefore = 2\n\t\tcase 2:\n\t\t\tbefore = 1\n\t\t}\n\t}\n\n\t// if (9 - len(moves)) == 1 {\n\t// \tfor i := range grid {\n\t// \t\tfor j := range grid {\n\t// \t\t\tif grid[i][j] == 0 {\n\t// \t\t\t\tgrid[i][j] = 1\n\t// \t\t\t}\n\t// \t\t}\n\t// \t}\n\t// }\n\n\tfmt.Println(grid)\n\n\tend := func(this int) string {\n\t\tif this == 1 {\n\t\t\treturn \"A\"\n\t\t} else if this == 2 {\n\t\t\treturn \"B\"\n\t\t}\n\t\treturn \"\"\n\t}\n\n\thalf := (9 - len(moves)) / 2\n\taReft := half + (9-len(moves))%2\n\tbReft := half\n\n\taReach := 0\n\tbReach := 0\n\tfor i := 0; i < 3; i++ {\n\t\tif grid[0][i] == grid[1][i] && grid[1][i] == grid[2][i] {\n\t\t\tif winner := end(grid[1][i]); winner != \"\" {\n\t\t\t\treturn winner\n\t\t\t}\n\t\t}\n\t}\n\t// if aReach >= aReft && aReft != bReft {\n\n\t// }\n\n\taReach = 0\n\tbReach = 0\n\tfor i := 0; i < 3; i++ {\n\t\tif grid[i][0] == grid[i][1] && grid[i][1] == grid[i][2] {\n\t\t\tif winner := end(grid[i][1]); winner != \"\" {\n\t\t\t\treturn winner\n\t\t\t}\n\t\t}\n\t}\n\n\taReach = 0\n\tbReach = 0\n\tif grid[0][0] == grid[1][1] && grid[1][1] == grid[2][2] {\n\t\tif winner := end(grid[1][1]); winner != \"\" {\n\t\t\treturn winner\n\t\t}\n\t}\n\n\taReach = 0\n\tbReach = 0\n\tif grid[0][2] == grid[1][1] && grid[1][1] == grid[2][0] {\n\t\tif winner := end(grid[1][1]); winner != \"\" {\n\t\t\treturn winner\n\t\t}\n\t}\n\n\t// if len(moves) >= 8 {\n\tif len(moves) == 9 {\n\t\treturn \"Draw\"\n\t}\n\n\t// あと何回打てるか?\n\t// 自分の回数より多いとそっちの勝ち\n\n\t_ = aReft\n\t_ = bReft\n\t_ = aReach\n\t_ = bReach\n\n\treturn \"Pending\"\n}", "func (graph *Graph) GetSteps(path Path) int {\n\treturn len(path) - 1 // contains start point so -1\n}", "func Test_step2a(t *testing.T) {\n\ttestCases := []romance.StepTestCase{\n\t\t{\"épanoUit\", 2, 4, 3, true, \"épanoU\", 2, 4, 3},\n\t\t{\"faillirent\", 4, 7, 2, true, \"faill\", 4, 5, 2},\n\t\t{\"acabit\", 2, 4, 3, true, \"acab\", 2, 4, 3},\n\t\t{\"établissait\", 2, 4, 3, true, \"établ\", 2, 4, 3},\n\t\t{\"découvrir\", 3, 6, 2, true, \"découvr\", 3, 6, 2},\n\t\t{\"réjoUissait\", 3, 5, 2, true, \"réjoU\", 3, 5, 2},\n\t\t{\"trahiront\", 4, 6, 3, true, \"trah\", 4, 4, 3},\n\t\t{\"maintenir\", 4, 7, 2, true, \"mainten\", 4, 7, 2},\n\t\t{\"vendit\", 3, 6, 2, true, \"vend\", 3, 4, 2},\n\t\t{\"repartit\", 3, 5, 2, true, \"repart\", 3, 5, 2},\n\t\t{\"giletti\", 3, 5, 2, true, \"gilett\", 3, 5, 2},\n\t\t{\"rienzi\", 4, 6, 2, true, \"rienz\", 4, 5, 2},\n\t\t{\"punie\", 3, 5, 2, true, \"pun\", 3, 3, 2},\n\t\t{\"accueillir\", 2, 7, 4, true, \"accueill\", 2, 7, 4},\n\t\t{\"rétablit\", 3, 5, 2, true, \"rétabl\", 3, 5, 2},\n\t\t{\"ravis\", 3, 5, 2, true, \"rav\", 3, 3, 2},\n\t\t{\"xviIi\", 4, 5, 3, true, \"xviI\", 4, 4, 3},\n\t\t{\"blottie\", 4, 7, 3, true, \"blott\", 4, 5, 3},\n\t\t{\"approfondie\", 2, 6, 5, true, \"approfond\", 2, 6, 5},\n\t\t{\"infirmerie\", 2, 5, 4, true, \"infirmer\", 2, 5, 4},\n\t\t{\"scotti\", 4, 6, 3, true, \"scott\", 4, 5, 3},\n\t\t{\"adoucissait\", 2, 5, 3, true, \"adouc\", 2, 5, 3},\n\t\t{\"finissait\", 3, 5, 2, true, \"fin\", 3, 3, 2},\n\t\t{\"promit\", 4, 6, 3, true, \"prom\", 4, 4, 3},\n\t\t{\"franchies\", 4, 9, 3, true, \"franch\", 4, 6, 3},\n\t\t{\"franchissant\", 4, 8, 3, true, \"franch\", 4, 6, 3},\n\t\t{\"micheli\", 3, 6, 2, true, \"michel\", 3, 6, 2},\n\t\t{\"éteignit\", 2, 5, 3, true, \"éteign\", 2, 5, 3},\n\t\t{\"puni\", 3, 4, 2, true, \"pun\", 3, 3, 2},\n\t\t{\"apoplexie\", 2, 4, 3, true, \"apoplex\", 2, 4, 3},\n\t\t{\"désira\", 3, 5, 2, true, \"dés\", 3, 3, 2},\n\t\t{\"étourdi\", 2, 5, 3, true, \"étourd\", 2, 5, 3},\n\t\t{\"giovanni\", 4, 6, 2, true, \"giovann\", 4, 6, 2},\n\t\t{\"apprécie\", 2, 6, 5, true, \"appréc\", 2, 6, 5},\n\t\t{\"poésies\", 4, 7, 2, true, \"poés\", 4, 4, 2},\n\t\t{\"pairie\", 4, 6, 2, true, \"pair\", 4, 4, 2},\n\t\t{\"sortit\", 3, 6, 2, true, \"sort\", 3, 4, 2},\n\t\t{\"subi\", 3, 4, 2, true, \"sub\", 3, 3, 2},\n\t\t{\"aigrirait\", 3, 6, 3, true, \"aigr\", 3, 4, 3},\n\t\t{\"assailli\", 2, 6, 4, true, \"assaill\", 2, 6, 4},\n\t\t{\"bertolotti\", 3, 6, 2, true, \"bertolott\", 3, 6, 2},\n\t\t{\"recouvrir\", 3, 6, 2, true, \"recouvr\", 3, 6, 2},\n\t\t{\"visconti\", 3, 6, 2, true, \"viscont\", 3, 6, 2},\n\t\t{\"surgir\", 3, 6, 2, true, \"surg\", 3, 4, 2},\n\t\t{\"remercie\", 3, 5, 2, true, \"remerc\", 3, 5, 2},\n\t\t{\"joUissaIent\", 3, 5, 2, true, \"joU\", 3, 3, 2},\n\t\t{\"bondissant\", 3, 6, 2, true, \"bond\", 3, 4, 2},\n\t\t{\"saisi\", 4, 5, 2, true, \"sais\", 4, 4, 2},\n\t\t{\"missouri\", 3, 7, 2, true, \"missour\", 3, 7, 2},\n\t\t{\"remplirent\", 3, 7, 2, true, \"rempl\", 3, 5, 2},\n\t\t{\"envahi\", 2, 5, 4, true, \"envah\", 2, 5, 4},\n\t\t{\"tandis\", 3, 6, 2, true, \"tand\", 3, 4, 2},\n\t\t{\"trahit\", 4, 6, 3, true, \"trah\", 4, 4, 3},\n\t\t{\"trahissaIent\", 4, 6, 3, true, \"trah\", 4, 4, 3},\n\t\t{\"réunie\", 4, 6, 2, true, \"réun\", 4, 4, 2},\n\t\t{\"avarie\", 2, 4, 3, true, \"avar\", 2, 4, 3},\n\t\t{\"dilettanti\", 3, 5, 2, true, \"dilettant\", 3, 5, 2},\n\t\t{\"raidie\", 4, 6, 2, true, \"raid\", 4, 4, 2},\n\t\t{\"écuries\", 2, 4, 3, true, \"écur\", 2, 4, 3},\n\t\t{\"recouvrît\", 3, 6, 2, true, \"recouvr\", 3, 6, 2},\n\t\t{\"parsis\", 3, 6, 3, true, \"pars\", 3, 4, 3},\n\t\t{\"monti\", 3, 5, 2, true, \"mont\", 3, 4, 2},\n\t\t{\"reproduisit\", 3, 6, 2, true, \"reproduis\", 3, 6, 2},\n\t\t{\"étendit\", 2, 4, 3, true, \"étend\", 2, 4, 3},\n\t\t{\"suffi\", 3, 5, 2, true, \"suff\", 3, 4, 2},\n\t\t{\"pillaji\", 3, 6, 2, true, \"pillaj\", 3, 6, 2},\n\t\t{\"rougir\", 4, 6, 2, true, \"roug\", 4, 4, 2},\n\t\t{\"désirez\", 3, 5, 2, true, \"dés\", 3, 3, 2},\n\t\t{\"subit\", 3, 5, 2, true, \"sub\", 3, 3, 2},\n\t\t{\"fondirent\", 3, 6, 2, true, \"fond\", 3, 4, 2},\n\t\t{\"coqUineries\", 3, 6, 2, true, \"coqUiner\", 3, 6, 2},\n\t\t{\"venir\", 3, 5, 2, true, \"ven\", 3, 3, 2},\n\t\t{\"plaidoirie\", 5, 8, 3, true, \"plaidoir\", 5, 8, 3},\n\t\t{\"fournissant\", 4, 7, 2, true, \"fourn\", 4, 5, 2},\n\t\t{\"bonzeries\", 3, 6, 2, true, \"bonzer\", 3, 6, 2},\n\t\t{\"flétri\", 4, 6, 3, true, \"flétr\", 4, 5, 3},\n\t\t{\"faillit\", 4, 7, 2, true, \"faill\", 4, 5, 2},\n\t\t{\"hardie\", 3, 6, 2, true, \"hard\", 3, 4, 2},\n\t\t{\"compagnie\", 3, 6, 2, true, \"compagn\", 3, 6, 2},\n\t\t{\"vernis\", 3, 6, 2, true, \"vern\", 3, 4, 2},\n\t\t{\"attendit\", 2, 5, 4, true, \"attend\", 2, 5, 4},\n\t\t{\"blanchies\", 4, 9, 3, true, \"blanch\", 4, 6, 3},\n\t\t{\"choisie\", 5, 7, 3, true, \"chois\", 5, 5, 3},\n\t\t{\"rafraîchir\", 3, 7, 2, true, \"rafraîch\", 3, 7, 2},\n\t\t{\"choisir\", 5, 7, 3, true, \"chois\", 5, 5, 3},\n\t\t{\"nourrisse\", 4, 7, 2, true, \"nourr\", 4, 5, 2},\n\t\t{\"chancellerie\", 4, 7, 3, true, \"chanceller\", 4, 7, 3},\n\t\t{\"repartie\", 3, 5, 2, true, \"repart\", 3, 5, 2},\n\t\t{\"redira\", 3, 5, 2, true, \"red\", 3, 3, 2},\n\t\t{\"sentira\", 3, 6, 2, true, \"sent\", 3, 4, 2},\n\t\t{\"surgirait\", 3, 6, 2, true, \"surg\", 3, 4, 2},\n\t\t{\"cani\", 3, 4, 2, true, \"can\", 3, 3, 2},\n\t\t{\"gratis\", 4, 6, 3, true, \"grat\", 4, 4, 3},\n\t\t{\"médît\", 3, 5, 2, true, \"méd\", 3, 3, 2},\n\t\t{\"avertis\", 2, 4, 3, true, \"avert\", 2, 4, 3},\n\t\t{\"chirurgie\", 4, 6, 3, true, \"chirurg\", 4, 6, 3},\n\t\t{\"ironie\", 2, 4, 3, true, \"iron\", 2, 4, 3},\n\t\t{\"punîtes\", 3, 5, 2, true, \"pun\", 3, 3, 2},\n\t\t{\"compromis\", 3, 7, 2, true, \"comprom\", 3, 7, 2},\n\t\t{\"simonie\", 3, 5, 2, true, \"simon\", 3, 5, 2},\n\t}\n\tromance.RunStepTest(t, step2a, testCases)\n}", "func parseSteps(filename string) (int, map[string][]string) {\n\tdeps := make(map[string][]string)\n\trawLogs, _ := ioutil.ReadFile(filename)\n\tarr := strings.Split(string(rawLogs), \"\\n\")\n\tfor _, raw := range arr {\n\t\tif len(raw) > 0 {\n\t\t\tstep := string(raw[36])\n\t\t\tdep := string(raw[5])\n\t\t\tdeps[step] = append(deps[step], dep)\n\t\t}\n\t}\n\treturn len(arr) - 1, deps\n}", "func path(start Point) int {\n\tret := 0\n\tupret := 0\n\trightret := 0\n\tdownret := 0\n\tuppoint := start\n\tuppoint.Y = uppoint.Y + 1\n\tok := isPointOK(&uppoint)\n\tif ok {\n\t\tfmt.Printf(\"%+v\\n\", uppoint)\n\t\tsumpoint <- uppoint\n\t\tpathrecordpoint <- uppoint\n\t\tupret = path(uppoint)\n\n\t\tret = ret + 1\n\t}\n\trightpoint := start\n\trightpoint.X = rightpoint.X + 1\n\tok = isPointOK(&rightpoint)\n\tif ok {\n\t\tfmt.Printf(\"%+v\\n\", rightpoint)\n\t\tsumpoint <- rightpoint\n\t\tpathrecordpoint <- rightpoint\n\t\trightret = path(rightpoint)\n\t\tret = ret + 1\n\n\t}\n\n\treturn ret + upret + downret + rightret\n}", "func main() {\n\n\tvar t int\n\tfmt.Scanln(&t)\n\n\tfor ; t > 0; t-- {\n\n\t\tvar n, m, D, H int\n\t\tfmt.Scanln(&n, &m, &D)\n\n\t\tpassed := 0\n\t\theroi := 0\n\n\t\tfor ; heroi < n && passed < m; heroi++ {\n\t\t\tfmt.Scanln(&H)\n\t\t\tpassed += (H - 1) / D\n\t\t}\n\n\t\tfor ; heroi < n; heroi++ {\n\t\t\tvar dummy string\n\t\t\tfmt.Scanln(&dummy)\n\t\t}\n\n\t\tif passed >= m {\n\t\t\tfmt.Println(\"YES\")\n\t\t} else {\n\t\t\tfmt.Println(\"NO\")\n\t\t}\n\t}\n}", "func path(n, m int) int {\n\tif n == 1 || m == 1 {\n\t\treturn 1\n\t}\n\treturn path(n-1, m) + path(n, m-1)\n}", "func stepPerms(n int32) int32 {\n\tif n < 3 {\n\t\treturn n\n\t}\n\n\ta, b, c, current := 1, 2, 4, 0\n\n\tfor i := int32(3); i < n; i++ {\n\t\tcurrent = a + b + c\n\t\ta, b = b, c\n\t\tc = current\n\t}\n\n\treturn int32(c)\n}", "func testTrucks() map[string]string {\n\treturn map[string]string{\n\t\t`truck 1\n0 0 4 4 2\nendtruck\n`: `\n| ! ! ! ! |\n| ! ! ! ! |\n| ! ! ! ! |\n| ! ! ! ! |\n`,\n\t\t`truck 3\n0 0 4 3 4\n0 0 4 1 5\nendtruck\n`: `\n| ! ! ! @ |\n| ! ! ! @ |\n| ! ! ! @ |\n| ! ! ! @ |\n`,\n\t\t`truck 6\n0 0 4 2 7\n0 0 4 2 8\nendtruck\n`: `\n| ! ! @ @ |\n| ! ! @ @ |\n| ! ! @ @ |\n| ! ! @ @ |\n`,\n\t\t`truck 9 \n0 0 4 2 10 \n0 0 4 1 11 \nendtruck\n`: `\n| ! ! @ |\n| ! ! @ |\n| ! ! @ |\n| ! ! @ |\n`,\n\t\t`truck 12 \n0 0 4 2 13 \n0 0 3 2 14 \n0 0 1 1 15 \n0 0 1 1 16 \nendtruck\n`: `\n| ! ! @ @ |\n| ! ! @ @ |\n| ! ! @ @ |\n| ! ! # $ |\n`,\n\t\t`truck 17 \n0 0 4 2 18 \n0 0 2 1 19 \n0 0 2 1 20 \n0 0 2 1 21 \n0 0 1 1 22 \n0 0 1 1 23 \nendtruck\n`: `\n| ! ! @ # |\n| ! ! @ # |\n| ! ! $ % |\n| ! ! $ ^ |\n`,\n\t\t`truck 24\n0 0 4 1 25\n0 0 3 1 26\n0 0 1 1 27\n0 0 3 2 28\n0 0 2 1 29\nendtruck\n`: `\n| ! @ $ $ |\n| ! @ $ $ |\n| ! @ $ $ |\n| ! # % % |\n`,\n\t\t`truck 30\n0 0 3 3 31\n0 0 3 1 32\n0 0 1 2 33\n0 0 2 1 34\nendtruck\n`: `\n| ! ! ! # |\n| ! ! ! # |\n| ! ! ! $ |\n| @ @ @ $ |\n`,\n\t\t`truck 35\n0 0 3 3 36\n0 0 2 1 37\n0 0 1 1 38\n0 0 2 1 39\n0 0 1 1 40\n0 0 1 1 41\nendtruck\n`: `\n| ! ! ! $ |\n| ! ! ! $ |\n| ! ! ! % |\n| @ @ # ^ |\n`,\n\t\t`truck 42\n0 0 3 3 43\n0 0 1 1 44\n0 0 1 1 45\n0 0 1 1 46\n0 0 1 1 47\nendtruck\n`: `\n| ! ! ! % |\n| ! ! ! |\n| ! ! ! |\n| @ # $ |\n`,\n\t\t`truck 48\n0 0 3 2 49\n0 0 2 1 50\n0 0 3 1 51\n0 0 1 1 52\nendtruck\n`: `\n| ! ! # |\n| ! ! # |\n| ! ! # |\n| @ @ $ |\n`,\n\t\t`truck 53\n0 0 2 3 54\n0 0 1 1 55\n0 0 1 1 56\n0 0 2 2 57\nendtruck\n`: `\n| ! ! $ $ |\n| ! ! $ $ |\n| ! ! |\n| @ # |\n`,\n\t\t`truck 58\n0 0 3 1 59\n0 0 1 1 60\nendtruck\n`: `\n| ! |\n| ! |\n| ! |\n| @ |\n`,\n\t\t`truck 61 \n0 0 1 1 62 \n0 0 1 1 63 \n0 0 1 1 64 \n0 0 1 1 65 \nendtruck\n`: `\n| ! @ |\n| $ # |\n| |\n| |\n`,\n\t\t`truck 66\nendtruck\n`: `\n| |\n| |\n| |\n| |\n`,\n\t}\n}", "func getWays(n int, c []int) int {\n\t// Write your code here\n\t// Create table of size len(c)+1 and n+1\n\ttable := make([][]int, len(c)+1)\n\tfor row := 0; row <= len(c); row++ {\n\t\trow_ := []int{}\n\n\t\tfor col := 0; col <= n; col++ {\n\t\t\trow_ = append(row_, 0)\n\t\t}\n\t\ttable[row] = row_\n\t\ttable[row][0] = 1\n\t}\n\n\tfor r := 1; r <= len(c); r++ {\n\t\tfor co := 1; co <= n; co++ {\n\t\t\ttop := table[r-1][co]\n\t\t\tif co-c[r-1] < 0 {\n\t\t\t\ttable[r][co] = top + 0\n\t\t\t} else {\n\t\t\t\ttable[r][co] = top + table[r][co-c[r-1]]\n\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Println(table)\n\n\treturn table[len(c)][n]\n}", "func mo(s string) string {\n\tif \"\" == s {\n\t\treturn \"\"\n\t}\n\n\tfmt.Println(\"s:\", s)\n\tb := []byte(s)\n\tl := len(b)\n\tm := l / 2\n\teven := false\n\tif 0 == l%2 {\n\t\tfmt.Println(\"even\")\n\t\teven = true\n\t}\n\n\tvar win result\n\n\tdmax := m + 1\n\tfor d := 0; d < dmax; d++ {\n\n\t\tvar lodd result\n\t\tvar rodd result\n\t\tvar leven result\n\t\tvar reven result\n\n\t\tif even {\n\t\t\tfmt.Println(\"possible remaining\", (m-d)*2, l)\n\t\t\tif (m-d)*2 <= win.l {\n\t\t\t\treturn string(win.b)\n\t\t\t}\n\t\t\tlm := m - d\n\n\t\t\tfmt.Println(\"left even\")\n\t\t\tleven = findEven(b, lm, l)\n\t\t\tfmt.Println(\" \", leven.l, string(leven.b))\n\t\t\tif leven.l == l {\n\t\t\t\tfmt.Println(\" 🎂\")\n\t\t\t\treturn s\n\t\t\t}\n\n\t\t\trm := m + d + 1\n\n\t\t\tfmt.Println(\"right even\")\n\t\t\treven = findEven(b, rm-1, l)\n\t\t\tfmt.Println(\" \", reven.l, string(reven.b))\n\t\t\tif reven.l == l {\n\t\t\t\tfmt.Println(\" 🎂\")\n\t\t\t\treturn s\n\t\t\t}\n\n\t\t\tfmt.Println(\"left odd\")\n\t\t\tlodd = findOdd(b, lm, l)\n\t\t\tfmt.Println(\" \", lodd.l, string(lodd.b))\n\n\t\t\tfmt.Println(\"right odd\")\n\t\t\trodd = findOdd(b, rm-1, l)\n\t\t\tfmt.Println(\" \", rodd.l, string(rodd.b))\n\n\t\t} else {\n\t\t\tfmt.Println(\"possible remaining\", (dmax-d)*2, l)\n\t\t\tif (dmax-d)*2 <= win.l {\n\t\t\t\treturn string(win.b)\n\t\t\t}\n\n\t\t\tlm := m - d\n\n\t\t\tfmt.Println(\"left odd\")\n\t\t\tlodd = findOdd(b, lm, l)\n\t\t\tfmt.Println(\" \", lodd.l, string(lodd.b))\n\t\t\tif lodd.l == l {\n\t\t\t\tfmt.Println(\" 🎂\")\n\t\t\t\treturn s\n\t\t\t}\n\n\t\t\trm := m + d + 1\n\n\t\t\tfmt.Println(\"right odd\")\n\t\t\trodd = findOdd(b, rm, l)\n\t\t\tfmt.Println(\" \", rodd.l, string(rodd.b))\n\t\t\tif rodd.l == l {\n\t\t\t\tfmt.Println(\" 🎂\")\n\t\t\t\treturn s\n\t\t\t}\n\n\t\t\tfmt.Println(\"left even\")\n\t\t\tleven = findEven(b, lm, l)\n\t\t\tfmt.Println(\" \", leven.l, string(leven.b))\n\n\t\t\tfmt.Println(\"right even\")\n\t\t\treven = findEven(b, rm-1, l)\n\t\t\tfmt.Println(\" \", reven.l, string(reven.b))\n\t\t}\n\n\t\t// figure max remaining size from here\n\n\t\tif lodd.l > win.l {\n\t\t\twin = lodd\n\t\t}\n\n\t\tif rodd.l > win.l {\n\t\t\twin = rodd\n\t\t}\n\n\t\tif leven.l > win.l {\n\t\t\twin = leven\n\t\t}\n\n\t\tif reven.l > win.l {\n\t\t\twin = reven\n\t\t}\n\t}\n\n\treturn string(win.b)\n}", "func Day8Part1(input []string) (string, error) {\n\n\timData := input[0]\n\timWidth, imHeight := 25, 6\n\n\tlayers := generateLayers(imData, imWidth, imHeight)\n\n\tvar layerWithFewestZeros [][]int\n\tfewestZeros := imWidth * imHeight\n\tfor _, layer := range layers {\n\n\t\tzeros := 0\n\t\tfor y := 0; y < len(layer); y++ {\n\t\t\tfor x := 0; x < len(layer[y]); x++ {\n\t\t\t\tif layer[y][x] == 0 {\n\t\t\t\t\tzeros++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif zeros < fewestZeros {\n\t\t\tfewestZeros = zeros\n\t\t\tlayerWithFewestZeros = layer\n\t\t}\n\t}\n\n\tones, twos := 0, 0\n\tfor y := 0; y < len(layerWithFewestZeros); y++ {\n\t\tfor x := 0; x < len(layerWithFewestZeros[y]); x++ {\n\t\t\tswitch layerWithFewestZeros[y][x] {\n\t\t\tcase 1:\n\t\t\t\tones++\n\t\t\tcase 2:\n\t\t\t\ttwos++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn fmt.Sprintf(\"%d\", ones*twos), nil\n}", "func JumpIterationsHd(out1 *uint64) {\n\t*out1 = 0x5\n}", "func MinimumStepsPath(path []Point) int {\n\tif len(path) < 2 {\n\t\treturn 0\n\t}\n\tsteps := 0\n\tcurrent := path[0]\n\tfor i := 1; i < len(path); i++ {\n\t\tnext := path[i]\n\t\tdx, dy := delta(current, next)\n\t\tif dx < dy {\n\t\t\tsteps += dy\n\t\t} else {\n\t\t\tsteps += dx\n\t\t}\n\t\tcurrent = next\n\t}\n\treturn steps\n}", "func main() {\n\trand.Seed(time.Now().UnixNano())\n\tgconfig := Kiai.Connect(\"localhost:4000\", \"Easyfucka\", 1, 0) //Creates a variable with a GameConfig type. The output unit of connect function is Gameconfig which consists of multiple int data. Width,Height,MaxMoves,MaxFires,MaxHealth,PlayerCount,Timeout\n\tdefer Kiai.Disconnect() //Makes sure that at the end of the main function bot disconnects from server.\n\t\n\t\n\tfor {\n\t\tturn = Kiai.WaitForTurn() //Assigns the starting values of the wait for turn to turn variable.\n\t\t\n\t\tif start == false {\n\t\t\tfirstdecision(gconfig)\n\t\t}\n\t\t\n\t\tif iterate == maxiteration {\n\t\t\titerate = 0\n\t\t\tif path < 4 {\n\t\t\t\tpath += 1 \n\t\t\t} else {\n\t\t\t\tpath = 1\t\n\t\t\t}\t\t\n\t\t}\n\t\t\n\t\tif path == 1 { //This part is one of the four movement tactics that belong to a path. For all the moves left it directs the bot towards the corner and if corner is reached, it starts main offense.\n\t\t\t\n\t\t\tfor i := 0; i < turn.MovesLeft; i++ {\n\t\t\t\tfiring()\n\t\t\t\t\n\t\t\t\tif turn.X == 0 && turn.Y == 0 {\n\t\t\t\t\tmaintactic()\n\t\t\t\t\tbreak\n\t\t\t\t} else if turn.X != 0 && turn.Y != 0 {\n\t\t\t\t\tturn.Move(Kiai.NorthWest)\n\t\t\t\t} else if turn.X == 0 && turn.Y != 0 {\n\t\t\t\t\tturn.Move(Kiai.North)\n\t\t\t\t} else if turn.X != 0 && turn.Y == 0 {\n\t\t\t\t\tturn.Move(Kiai.West)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif path == 2 {\n\t\t\t\n\t\t\tfor i := 0; i < turn.MovesLeft; i++ {\n\t\t\t\tfiring()\n\t\t\t\t\n\t\t\t\tif turn.X == gconfig.Width-1 && turn.Y == 0 {\n\t\t\t\t\tmaintactic()\n\t\t\t\t\tbreak\n\t\t\t\t} else if turn.X != gconfig.Width-1 && turn.Y != 0 {\n\t\t\t\t\tturn.Move(Kiai.NorthEast)\n\t\t\t\t} else if turn.X == gconfig.Width-1 && turn.Y != 0 {\n\t\t\t\t\tturn.Move(Kiai.North)\n\t\t\t\t} else if turn.X != gconfig.Width-1 && turn.Y == 0 {\n\t\t\t\t\tturn.Move(Kiai.East)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif path == 3 {\n\t\t\t\n\t\t\tfor i := 0; i < turn.MovesLeft; i++ {\n\t\t\t\tfiring()\n\t\t\t\t\n\t\t\t\tif turn.X == gconfig.Width-1 && turn.Y == gconfig.Height-1 {\n\t\t\t\t\tmaintactic()\n\t\t\t\t\tbreak\n\t\t\t\t} else if turn.X != gconfig.Width-1 && turn.Y != gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.SouthEast)\n\t\t\t\t} else if turn.X == gconfig.Width-1 && turn.Y != gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.South)\n\t\t\t\t} else if turn.X != gconfig.Width-1 && turn.Y == gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.East)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif path == 4 {\n\t\t\t\n\t\t\tfor i := 0; i < turn.MovesLeft; i++ {\n\t\t\t\tfiring()\n\t\t\t\t\n\t\t\t\tif turn.X == 0 && turn.Y == gconfig.Height-1 {\n\t\t\t\t\tmaintactic()\n\t\t\t\t\tbreak\n\t\t\t\t} else if turn.X != 0 && turn.Y != gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.SouthWest)\n\t\t\t\t} else if turn.X == 0 && turn.Y != gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.South)\n\t\t\t\t} else if turn.X != 0 && turn.Y == gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.West)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n//This section just shoots randomly towards the middle of the board at the last move if someone is not seen around.\n\t\n\t\tif path == 1 {\n\t\t\tif turn.Y == 0 {\n\t\t\t\tturn.Fire(Kiai.SouthEast)\n\t\t\t} else {\n\t\t\t\tturn.Fire(Kiai.East)\n\t\t\t}\t \n\t\t} \n\t\t\n\t\tif path == 2 {\n\t\t\tif turn.X == gconfig.Width - 1 {\n\t\t\t\tturn.Fire(Kiai.SouthWest)\n\t\t\t} else {\n\t\t\t\tturn.Fire(Kiai.South)\n\t\t\t}\t\t\n\t\t}\n\t\t\n\t\tif path == 3 {\n\t\t\tif turn.Y == gconfig.Height - 1 {\n\t\t\t\tturn.Fire(Kiai.NorthWest)\n\t\t\t} else {\n\t\t\t\tturn.Fire(Kiai.West)\n\t\t\t}\n\t\t}\n\t\t\n\t\tif path == 4 {\n\t\t\tif turn.X == 0 {\n\t\t\t\tturn.Fire(Kiai.NorthEast)\n\t\t\t} else {\n\t\t\t\tturn.Fire(Kiai.North)\n\t\t\t}\n\t\t}\n\t\t\n\t\titerate += 1\n\t\tKiai.EndTurn()\n\t}\n}", "func solutionLvl2(puzzle string, parameters map[string]int) (answer int) {\n\tfor _, line := range strings.Split(puzzle, \"\\n\") {\n\t\tif line != \"\" {\n\t\t\tanswer += evaluateExpr2(line)\n\t\t}\n\t}\n\treturn\n}", "func solveAlgo6(g Solver, l *Line) {\n\t//l.print(\"solveAlgo6\")\n\trsg := l.getUnsolvedRanges()\n\n\tfor _, r := range rsg {\n\t\tcs := l.getPotentialCluesForRange(r)\n\n\t\tlongest := 0\n\t\tisFound, step := l.getStepToNextBlank(r, false)\n\t\tif isFound {\n\t\t\tisFound = false\n\t\t\tfor _, c := range cs {\n\t\t\t\tif c.index < l.ce {\n\t\t\t\t\tnext := l.clues[c.index+1]\n\t\t\t\t\tif step <= c.length-r.length() || step > next.length {\n\t\t\t\t\t\tisFound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlongest = max(longest, c.length-r.length())\n\t\t\t}\n\t\t\t//if we didn't find anyone, we can blank taking into account the longest trail\n\t\t\tif len(cs) > 1 && !isFound {\n\t\t\t\tfor i := longest + 1; i <= step; i++ {\n\t\t\t\t\tg.SetValue(l.squares[r.max+i], BLANK)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlongest = 0\n\t\tisFound, step = l.getStepToNextBlank(r, true)\n\t\tif isFound {\n\t\t\tisFound = false\n\t\t\tfor _, c := range cs {\n\t\t\t\tif c.index > l.cb {\n\t\t\t\t\tprevious := l.clues[c.index-1]\n\t\t\t\t\tif step <= c.length-r.length() || step > previous.length {\n\t\t\t\t\t\tisFound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlongest = max(longest, c.length-r.length())\n\t\t\t}\n\t\t\t//if we didn't find anyone, we can blank taking into account the longest trail\n\t\t\tif len(cs) > 1 && !isFound {\n\t\t\t\tfor i := longest + 1; i <= step; i++ {\n\t\t\t\t\tg.SetValue(l.squares[r.min-i], BLANK)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func slidingPuzzle(board [][]int) int {\n\n}", "func TowerOfHanoiMoves(disks int) []string {\n\treturn towerOfHanoi(disks, 1, 3, 2)\n}", "func gameOfLife(board [][]int) {\n\tm := len(board)\n\tn := len(board[0])\n\tr := make([][]int, m, m)\n\tfor i := 0; i < m; i++ {\n\t\tr[i] = make([]int, n, n)\n\t\tfor j := 0; j < n; j++ {\n\t\t\tr[i][j] = board[i][j]\n\t\t}\n\t}\n\tfor i := 0; i < m; i++ {\n\t\tfor j := 0; j < n; j++ {\n\t\t\tlives := 0\n\t\t\tif j > 0 {\n\t\t\t\tlives = lives + r[i][j-1]\n\t\t\t}\n\t\t\tif j < n-1 {\n\t\t\t\tlives = lives + r[i][j+1]\n\t\t\t}\n\t\t\tif i > 0 {\n\t\t\t\tlives = lives + r[i-1][j]\n\t\t\t\tif j > 0 {\n\t\t\t\t\tlives = lives + r[i-1][j-1]\n\t\t\t\t}\n\t\t\t\tif j < n-1 {\n\t\t\t\t\tlives = lives + r[i-1][j+1]\n\t\t\t\t}\n\t\t\t}\n\t\t\tif i < m-1 {\n\t\t\t\tlives = lives + r[i+1][j]\n\t\t\t\tif j > 0 {\n\t\t\t\t\tlives = lives + r[i+1][j-1]\n\t\t\t\t}\n\t\t\t\tif j < n-1 {\n\t\t\t\t\tlives = lives + r[i+1][j+1]\n\t\t\t\t}\n\t\t\t}\n\t\t\tl := r[i][j]\n\t\t\tswitch {\n\t\t\tcase l == 0 && lives == 3:\n\t\t\t\tboard[i][j] = 1\n\t\t\tcase l == 1 && (lives == 2 || lives == 3):\n\t\t\t\tboard[i][j] = 1\n\t\t\tdefault:\n\t\t\t\tboard[i][j] = 0\n\t\t\t}\n\t\t}\n\t}\n}", "func firstStep(y int) {\n\tfmt.Println(\"1.1\", y)\n\ty = 52 // 1.4 assign y to 52\n\tfmt.Println(\"1.2\", y)\n}", "func Step(a, b Universe) {\n\t//based on prev state of universe\n for i, row := range a {\n for j := range row {\n\t\t\tif a.Next(j, i) {\n\t\t\t\tb[i][j] = true\n\t\t\t} else {\n b[i][j] = false\n\t\t\t}\n\t\t}\n\t\tfmt.Println(\"\\x0c\")\n\t}\n}", "func main15() {\n\tgph := new(Graph)\n\tgph.Init(5)\n gph.AddDirectedEdge(0, 1, 3)\n gph.AddDirectedEdge(0, 4, 2)\n gph.AddDirectedEdge(1, 2, 1)\n gph.AddDirectedEdge(2, 3, 1)\n gph.AddDirectedEdge(4, 1, -2)\n gph.AddDirectedEdge(4, 3, 1)\n gph.BellmanFordShortestPath(0)\n}", "func (n *TreeNode) Step() (s Step, pass bool) {\n\treturn n.step, n.pass\n}", "func ways(n, goal, most int) [][]int {\n\tif goal < 0 || most*n < goal {\n\t\treturn nil\n\t}\n\n\tif n == 1 {\n\t\treturn [][]int{{goal}}\n\t}\n\n\taccumulate := make([][]int, 0)\n\n\tfor i := 0; i <= most; i++ {\n\t\tif below := ways(n-1, goal-i, i); below != nil {\n\t\t\taccumulate = append(accumulate, paint(i, below)...)\n\t\t}\n\t}\n\n\treturn accumulate\n}", "func run(input string) (interface{}, interface{}) {\n\tvar displays []sevenSegmentDisplay\n\n\tfor _, line := range strings.Split(input, \"\\n\") {\n\t\tdigitsAndTarget := strings.Split(line, \" | \")\n\t\tsegments := strings.Split(digitsAndTarget[0], \" \")\n\t\tval := strings.Split(digitsAndTarget[1], \" \")\n\t\t// sort them to enable the lookup table in the future\n\t\tfor i, s := range segments {\n\t\t\tsegments[i] = helpers.SortString(s)\n\t\t}\n\t\tfor i, s := range val {\n\t\t\tval[i] = helpers.SortString(s)\n\t\t}\n\t\tdisplays = append(displays, sevenSegmentDisplay{\n\t\t\tsegments: segments,\n\t\t\tvalues: val,\n\t\t})\n\t}\n\n\ttotalA := 0\n\tfor _, segment := range displays {\n\t\ttotalA += solveBasicSegments(segment)\n\t}\n\n\ttotalB := 0\n\tfor _, segment := range displays {\n\t\ttotalB += solveAllSegments(segment)\n\t}\n\n\treturn totalA, totalB\n}", "func minRefuelStops(target int, startFuel int, stations [][]int) int {\n \n}", "func (e *OptTester) OptSteps(verbose bool) (string, error) {\n\tvar buf bytes.Buffer\n\tvar prev, next string\n\tif verbose {\n\t\tfmt.Print(\"------ optsteps verbose output starts ------\\n\")\n\t}\n\toutput := func(format string, args ...interface{}) {\n\t\tfmt.Fprintf(&buf, format, args...)\n\t\tif verbose {\n\t\t\tfmt.Printf(format, args...)\n\t\t}\n\t}\n\tindent := func(str string) {\n\t\tstr = strings.TrimRight(str, \" \\n\\t\\r\")\n\t\tlines := strings.Split(str, \"\\n\")\n\t\tfor _, line := range lines {\n\t\t\toutput(\" %s\\n\", line)\n\t\t}\n\t}\n\tfor i := 0; ; i++ {\n\t\to := xform.NewOptimizer(&e.evalCtx)\n\n\t\t// Override SetOnRuleMatch to stop optimizing after the ith rule matches.\n\t\tsteps := i\n\t\tlastRuleName := opt.InvalidRuleName\n\t\to.SetOnRuleMatch(func(ruleName opt.RuleName) bool {\n\t\t\tif steps == 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tsteps--\n\t\t\tlastRuleName = ruleName\n\t\t\treturn true\n\t\t})\n\n\t\troot, required, err := e.buildExpr(o.Factory())\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tnext = o.Optimize(root, required).FormatString(e.Flags.Format)\n\t\tif steps != 0 {\n\t\t\t// All steps were not used, so must be done.\n\t\t\tbreak\n\t\t}\n\n\t\tif i == 0 {\n\t\t\toutput(\"*** Initial expr:\\n\")\n\t\t\t// Output starting tree.\n\t\t\tindent(next)\n\t\t} else {\n\t\t\toutput(\"\\n*** %s applied; \", lastRuleName.String())\n\n\t\t\tif prev == next {\n\t\t\t\t// The expression can be unchanged if a part of the memo changed that\n\t\t\t\t// does not affect the final best expression.\n\t\t\t\toutput(\"best expr unchanged.\\n\")\n\t\t\t} else {\n\t\t\t\toutput(\"best expr changed:\\n\")\n\t\t\t\tdiff := difflib.UnifiedDiff{\n\t\t\t\t\tA: difflib.SplitLines(prev),\n\t\t\t\t\tB: difflib.SplitLines(next),\n\t\t\t\t\tContext: 100,\n\t\t\t\t}\n\n\t\t\t\ttext, _ := difflib.GetUnifiedDiffString(diff)\n\t\t\t\t// Skip the \"@@ ... @@\" header (first line).\n\t\t\t\ttext = strings.SplitN(text, \"\\n\", 2)[1]\n\t\t\t\tindent(text)\n\t\t\t}\n\t\t}\n\n\t\tprev = next\n\t}\n\n\t// Output ending tree.\n\toutput(\"\\n*** Final best expr:\\n\")\n\tindent(next)\n\n\tif verbose {\n\t\tfmt.Print(\"------ optsteps verbose output ends ------\\n\")\n\t}\n\n\treturn buf.String(), nil\n}", "func MoveKnights(knights uint64) uint64 {\n\tnewKnights := knights\n\tmoves := [4]uint64{15, 17, 6, 10}\n\tfor i := 0; i < 4; i++ {\n\t\tnewKnights = newKnights | (knights << moves[i]) | knights>>moves[i]\n\t}\n\treturn newKnights\n}", "func uniquePathsWithObstacles(obstacleGrid [][]int) int {\n\trow, col := len(obstacleGrid), len(obstacleGrid[0])\n\t// if the starting point has obstacle, then we can't walk to anywhere\n\tif obstacleGrid[0][0] == 1 {\n\t\treturn 0\n\t}\n\n\t// if the starting point has no obstacle, then the number of path walking to starting point is 1\n\tobstacleGrid[0][0] = 1\n\n\t// for first column, if the cell has no obstacle , then set the number of path of that cell to 1, otherwise 0\n\tfor i := 1; i < row; i++ {\n\t\tif obstacleGrid[i][0] == 0 && obstacleGrid[i-1][0] == 1 {\n\t\t\tobstacleGrid[i][0] = 1\n\t\t} else {\n\t\t\tobstacleGrid[i][0] = 0\n\t\t}\n\t}\n\n\t// for the first row, if the cell has no obstacle, then set the number of path of that cell to 1, otherwise 0\n\tfor i := 1; i < col; i++ {\n\t\tif obstacleGrid[0][i] == 0 && obstacleGrid[0][i-1] == 1 {\n\t\t\tobstacleGrid[0][i] = 1\n\t\t} else {\n\t\t\tobstacleGrid[0][i] = 0\n\t\t}\n\t}\n\n\t// every cell can only be reached from up or left, if the cell has obstacle, we set the number of path walking to that cell to 0, otherwise\n\t// set it to the sum of up and left cell\n\tfor i := 1; i < row; i++ {\n\t\tfor j := 1; j < col; j++ {\n\t\t\tif obstacleGrid[i][j] == 0 {\n\t\t\t\tobstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1]\n\t\t\t} else {\n\t\t\t\tobstacleGrid[i][j] = 0\n\t\t\t}\n\t\t}\n\t}\n\n\treturn obstacleGrid[row-1][col-1]\n}", "func main() {\n\tfmt.Println(numTreesDp(19))\n}", "func main() {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tscanner.Buffer(make([]byte, 1000000), 1000000)\n\n\t// W: number of columns.\n\t// H: number of rows.\n\tvar W, H int\n\tscanner.Scan()\n\tfmt.Sscan(scanner.Text(),&W, &H)\n\n\tfor i := 0; i < H; i++ {\n\t\tscanner.Scan()\n\t\tLINE := scanner.Text() // represents a line in the grid and contains W integers. Each integer represents one room of a given type.\n\t\tre := regexp.MustCompile(\" \")\n\t\tstr := \"[\" + re.ReplaceAllString(LINE, \",\") + \"]\"\n\t\tvar ints []int\n\t\tjson.Unmarshal([]byte(str), &ints)\n\n\t}\n\t// EX: the coordinate along the X axis of the exit (not useful for this first mission, but must be read).\n\tvar EX int\n\tscanner.Scan()\n\tfmt.Sscan(scanner.Text(),&EX)\n\n\tfor {\n\t\tvar XI, YI int\n\t\tvar POS string\n\t\tscanner.Scan()\n\t\tfmt.Sscan(scanner.Text(),&XI, &YI, &POS)\n\n\n\t\t// fmt.Fprintln(os.Stderr, \"Debug messages...\")\n\n\t\t// One line containing the X Y coordinates of the room in which you believe Indy will be on the next turn.\n\t\tfmt.Println(\"0 0\")\n\t}\n}", "func kerDIF8(a []fr.Element, twiddles [][]fr.Element, stage int) {\n\n\tfr.Butterfly(&a[0], &a[4])\n\tfr.Butterfly(&a[1], &a[5])\n\tfr.Butterfly(&a[2], &a[6])\n\tfr.Butterfly(&a[3], &a[7])\n\ta[5].Mul(&a[5], &twiddles[stage+0][1])\n\ta[6].Mul(&a[6], &twiddles[stage+0][2])\n\ta[7].Mul(&a[7], &twiddles[stage+0][3])\n\tfr.Butterfly(&a[0], &a[2])\n\tfr.Butterfly(&a[1], &a[3])\n\tfr.Butterfly(&a[4], &a[6])\n\tfr.Butterfly(&a[5], &a[7])\n\ta[3].Mul(&a[3], &twiddles[stage+1][1])\n\ta[7].Mul(&a[7], &twiddles[stage+1][1])\n\tfr.Butterfly(&a[0], &a[1])\n\tfr.Butterfly(&a[2], &a[3])\n\tfr.Butterfly(&a[4], &a[5])\n\tfr.Butterfly(&a[6], &a[7])\n}", "func parent_step(x uint) uint {\n\t// xy01 -> x011\n\tk := level(x)\n\tone := uint(1)\n\treturn (x | (one << k)) & ^(one << (k + 1))\n}", "func path(b board) (p float64) {\n\tfor _, i := range lh {\n\t\tfor _, j := range lh {\n\t\t\tvar lrl float64\n\t\t\tfor _, k := range rh {\n\t\t\t\tlrl += t[b[i]][b[k]][b[j]]\n\t\t\t}\n\t\t\tp += pathpair[i][j] * (letterpair[b[i]][b[j]] + lrl)\n\t\t}\n\t}\n\tfor _, i := range rh {\n\t\tfor _, j := range rh {\n\t\t\tvar rlr float64\n\t\t\tfor _, k := range lh {\n\t\t\t\trlr += t[b[i]][b[k]][b[j]]\n\t\t\t}\n\t\t\tp += pathpair[i][j] * (letterpair[b[i]][b[j]] + rlr)\n\t\t}\n\t}\n\treturn\n}", "func day1B() {\n\t//Test comment\n\tvar nums = []int{+5, -11, +17, +9, -4, -2, +11, -10, -16, +18, +18, -2, -2, +17, +13, +14, -11, +19, -14, +8, +10, -3, -12, +13, -3, +18, -20, +8, +3, +8, +13, +9, +14, -11, -6, +16, -12, +14, -8, +3, -18, -11, +6, -2, -14, -2, +17, -2, +6, -1, -13, +20, +9, +14, -15, -16, +18, -4, -8, +5, +19, -1, +19, +11, -3, +16, -12, -6, +3, -7, -1, +4, -15, -5, +13, +9, +11, +2, +17, +12, -7, -16, +13, -11, -14, +22, +16, -8, +16, +8, -10, +8, -19, +17, -9, +8, -2, +18, +9, +1, +10, -14, +6, +2, +2, -15, -15, -6, +11, +16, -8, +14, -18, -12, +14, +7, -1, -13, -18, -13, +5, -3, -18, +7, -2, -2, +6, -12, +15, +1, +18, -8, +22, +6, -1, +9, +9, +17, +18, +9, +13, -8, -17, +16, +16, +12, -11, -6, -9, +13, +11, -8, -12, +8, -10, +17, -13, -17, +7, -10, -3, +4, +1, -11, +3, -6, +19, +4, +13, +1, +11, +6, -3, +16, +8, +1, +17, -10, +18, -3, -7, +20, +4, +1, -8, +1, -2, +12, -1, +8, +8, +18, -10, +6, -16, +1, -3, +10, -11, -1, -5, +15, -11, -10, +18, +4, +8, +14, +6, +16, +12, +2, -19, +18, -5, -16, -10, -7, -3, +13, +14, +16, +13, -12, +15, +8, +17, +10, +7, +6, +17, +19, +19, -16, +10, +4, -16, -14, +8, +7, -22, -8, -19, +13, +12, -18, -21, +10, -12, -2, -12, -11, -16, -20, +6, -3, +2, -16, +9, -13, +1, +2, -13, +15, +9, -7, +22, -2, +18, +5, +4, -20, +14, -17, -19, +16, -6, +19, +1, +5, +24, +11, -16, +15, +13, +15, -3, -5, -17, -1, +8, +5, -10, +9, -2, +7, -11, -17, -13, -1, -9, +4, -10, -26, -22, +16, +14, +21, -20, +43, +8, -12, +2, -7, +15, +12, +17, +12, -18, +16, -12, +13, +8, +14, -12, +26, -6, +18, -3, -7, +19, -5, +13, +12, -14, -7, -14, +13, +13, -18, -6, +3, -12, +5, -20, +19, -11, -7, -15, -11, +12, -14, +24, -1, +18, +24, -9, +11, +9, -3, +8, -21, +1, +17, +1, +4, +20, -12, -5, +23, -9, +6, -12, -36, +13, -3, +33, -2, +9, +11, +23, -18, +22, -11, +14, +9, +8, -12, +5, -3, -3, +8, +16, +6, -18, +10, -18, -6, -1, -2, +24, -17, +23, +16, -9, +10, +23, -10, +2, +2, -9, +13, +3, +18, +12, +15, +16, -3, -7, -7, -5, +9, +1, -3, -19, -7, +17, +3, +13, +25, -4, -1, -19, -7, +15, -21, +43, +17, +5, +19, +10, +14, -15, -12, +19, +19, -16, -7, -7, -15, +6, -8, +18, +12, -7, -18, +9, +18, +16, -23, -18, -3, +12, -15, +9, +3, -14, +16, +18, +13, +19, -1, +11, +14, -4, -16, +11, -12, +27, -1, -13, +9, +7, -9, -1, +14, -35, -28, +1, +4, +15, -18, +10, -6, +12, -2, -5, -23, +31, -23, -37, +6, -13, -3, +4, +38, -23, -28, -24, -15, +4, +3, -16, +32, +13, -24, -9, -41, -41, -13, -41, -17, +16, -3, -36, -136, -9, +7, -4, -54, +20, +3, +11, +13, +16, +6, +6, -29, -118, -68, -416, -393, -73804, +17, +8, -14, +12, -22, -19, -7, -3, -14, +8, -3, -3, +16, -14, +5, -19, +16, +15, +8, +11, -14, -13, +3, +14, -15, +19, +26, +8, -11, -12, +17, -12, -12, +20, +22, +13, +14, +13, -3, -2, -1, -4, -16, +7, +12, +18, -15, -11, +7, -15, +11, +16, +13, +16, -2, -9, -4, +6, -8, -27, +16, -7, +87, +17, +11, -12, -2, +11, -13, -9, -10, -21, +15, -23, -15, +13, +11, +37, +16, +22, +16, +12, +18, -9, -8, +19, -5, -4, +13, +8, +4, -9, +4, +9, +4, -19, -2, -11, -2, +16, +17, +6, -8, +19, -2, +6, +2, -10, +12, +6, -20, -6, +5, +14, +12, +20, -21, +22, -2, +9, -2, -14, -15, +14, +7, -2, +9, -19, -52, -20, +4, -1, -18, +9, +7, -17, -22, -20, -7, -2, -9, +8, -3, +11, +18, -7, +17, +22, -18, -15, -19, -8, +13, +3, -15, +17, -3, -43, -34, +9, -37, +41, +141, -16, +19, -10, +14, +4, -7, -17, +12, +23, +2, +16, +36, -61, -253, -41, -44, -17, +10, -9, -5, +15, +20, +16, -4, +3, -12, +21, -11, -9, +16, -24, -12, +5, -2, -6, -18, -15, +16, -10, -5, -4, +8, +6, -20, -3, -19, +7, +4, -3, -11, +20, +4, +17, -3, -5, -3, +6, -4, -16, -15, +3, +19, -18, +16, -9, +17, +15, -25, -12, -17, -17, -4, +13, -15, +4, +17, -7, +13, -18, +4, +3, +10, +5, -1, +12, +9, -19, +16, +2, -11, -14, -14, -14, -2, +6, -3, +1, -15, +3, +2, -11, -9, +4, -3, +13, -1, -20, -19, -13, -8, -1, +13, +8, +9, +2, +6, +8, -9, -20, -5, +11, +20, +2, +9, +15, +17, +3, +18, -20, -3, +7, +8, +15, -6, -10, -16, +19, +2, -32, -7, -11, +3, +11, -25, -11, +16, -3, +16, -35, +10, +16, +24, -3, +1, -15, -8, +20, +27, +23, +20, -1, -14, +34, +14, +3, -18, +6, +10, +9, -18, -27, -42, -41, -37, -12, -22, +15, +12, -19, -18, +17, -15, +18, -4, +20, -12, +17, -34, -23, -8, -27, -4, -8, +20, -10, -8, -19, +8, -4, +11, -1, -11, +9, +1, -4, +15, -6, +3, -10, -10, -4, +5, +28, -2, +15, -21, +19, -1, -6, -8, +13, -44, +3, -9, +3, -24, -19, +17, -3, +7, -16, +11, +17, -27, -15, -2, -11, -18, +9, -6, -17, +2, -16, +13, +16, -9, +1, -13, -5, -11, +4, -2, +8, +3, +25, +15, -20, +7, +2, +5, -3, -13, -17, -5, -6, +4, +20, +22, +8, +18, -7, +4, +13, -1, -6, -14, -4, -5, -25, +21, -5, -20, +15, +20, +1, +1, +3, +5, +3, +75248}\n\tsum := 0\n\tset := make(map[int]bool)\n\tset[0] = true\n\tm := false\n\tfor set[sum] {\n\t\tfor _, num := range nums {\n\t\t\t// map the freq and check if array has that value, if true print and break\n\t\t\tsum += num\n\t\t\tif set[sum] {\n\t\t\t\tfmt.Println(\"freq match\")\n\t\t\t\tm = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tset[sum] = true\n\t\t}\n\t\tif m {\n\t\t\tbreak\n\t\t}\n\t}\n\tfmt.Println(\"match:\", sum)\n}", "func convertStepToDays(insight SearchInsight) int {\n\tif insight.Step.Days != nil {\n\t\treturn *insight.Step.Days\n\t} else if insight.Step.Hours != nil {\n\t\treturn 0\n\t} else if insight.Step.Weeks != nil {\n\t\treturn *insight.Step.Weeks * 7\n\t} else if insight.Step.Months != nil {\n\t\treturn *insight.Step.Months * 30\n\t} else if insight.Step.Years != nil {\n\t\treturn *insight.Step.Years * 365\n\t}\n\n\treturn 0\n}", "func (p *Mach) Step() bool {\n\tinstr := p.Mem[p.Reg[p.P]%SZ]\n\ti, n := (instr>>4)&15, instr&15\n\tswitch i {\n\tcase 0: // LDN, but IDL if N==0\n\t\tif n == 0 {\n\t\t\t// NOP -- we have moved WAIT to 0x68.\n\t\t} else {\n\t\t\tp.D = p.Mem[p.Reg[n]%SZ]\n\t\t}\n\tcase 1: // INC rn\n\t\tp.Reg[n]++\n\tcase 2: // DEC rn\n\t\tp.Reg[n]--\n\tcase 3: // BR...\n\t\tswitch n {\n\t\tcase 0:\n\t\t\tp.shortBranch(true)\n\t\tcase 1:\n\t\t\tp.shortBranch(!p.Q)\n\t\tcase 2:\n\t\t\tp.shortBranch(p.D == 0)\n\t\tcase 3:\n\t\t\tp.shortBranch(p.DF)\n\t\tcase 4:\n\t\t\tp.shortBranch(16 == 16&(p.EF<<1))\n\t\tcase 5:\n\t\t\tp.shortBranch(16 == 16&(p.EF<<2))\n\t\tcase 6:\n\t\t\tp.shortBranch(16 == 16&(p.EF<<3))\n\t\tcase 7:\n\t\t\tp.shortBranch(16 == 16&(p.EF<<4))\n\n\t\tcase 8:\n\t\t\tp.shortBranch(false)\n\t\tcase 9:\n\t\t\tp.shortBranch(p.Q)\n\t\tcase 10:\n\t\t\tp.shortBranch(p.D != 0)\n\t\tcase 11:\n\t\t\tp.shortBranch(!p.DF)\n\t\tcase 12:\n\t\t\tp.shortBranch(0 == 16&(p.EF<<1))\n\t\tcase 13:\n\t\t\tp.shortBranch(0 == 16&(p.EF<<2))\n\t\tcase 14:\n\t\t\tp.shortBranch(0 == 16&(p.EF<<3))\n\t\tcase 15:\n\t\t\tp.shortBranch(0 == 16&(p.EF<<4))\n\t\t}\n\tcase 4: // LDA\n\t\tp.D = p.Mem[p.Reg[n]%SZ]\n\t\tp.Reg[n]++\n\tcase 5: // STR\n\t\tp.Mem[p.Reg[n]%SZ] = p.D\n\tcase 6: // I/O\n // Special case 0x68:\n\t\tif n == 8 {\n\t\t\treturn false // The spare opcode 0x68 becomes IDL/STOP (rather than opcode 0)\n\t\t}\n // Special case 0x60:\n\t\tif n == 0 {\n\t\t\tp.Reg[p.X]++ // IRX\n\t\t}\n // Inputs and Outputs\n\t\tif n < 8 {\n\t\t\tp.Out[n] = p.D // OUT n&7\n\t\t\t// println(\"OUT\", n, p.D)\n\t\t} else {\n\t\t\tp.D = p.In[(n & 7)] // IN n&7\n\t\t}\n\tcase 7: // misc...\n\t\tswitch n {\n\t\tcase 0: // RET\n\n\t\tcase 1: // DIS\n\n\t\tcase 2: // LDXA\n\t\t\tp.D = p.Mem[p.Reg[p.X]%SZ]\n\t\t\tp.Reg[p.X]++\n\t\tcase 3: // STXD\n\t\t\tp.Mem[p.Reg[p.X]%SZ] = p.D\n\t\t\tp.Reg[p.X]--\n\t\tcase 4: //\n\t\t\tb := p.dfByte()\n\t\t\tp.DF = (int(b)+int(p.D)+int(p.Mem[p.Reg[p.X]%SZ]) > 255)\n\t\t\tp.D += b + p.Mem[p.Reg[p.X]%SZ]\n\t\tcase 5: //\n\t\t\tb := p.dfByte()\n\t\t\tp.DF = (int(p.D) > int(p.Mem[p.Reg[p.X]%SZ])+int(b))\n\t\t\tp.D = b + p.Mem[p.Reg[p.X]%SZ] - p.D\n\t\tcase 6: // SHRC\n\t\t\tc := (p.D&1 == 128)\n\t\t\tp.D = (p.D >> 1) | (p.dfByte() << 8)\n\t\t\tp.DF = c\n\t\tcase 7: //\n\t\t\tb := p.dfByte()\n\t\t\tp.DF = (int(p.D)+int(b) < int(p.Mem[p.Reg[p.X]%SZ]))\n\t\t\tp.D = b + p.D - p.Mem[p.Reg[p.X]%SZ]\n\t\tcase 8: // LDI\n\t\t\tp.D = p.imm()\n\t\tcase 9: //\n\t\t\tp.D |= p.imm()\n\t\tcase 10: // REQ\n\t\t\tp.Q = false\n\t\tcase 11: // SEQ\n\t\t\tp.Q = true\n\t\tcase 12: // ADCI\n\t\t\tb := p.dfByte()\n\t\t\timm := p.imm()\n\t\t\tp.DF = (int(b)+int(p.D)+int(imm) > 255)\n\t\t\tp.D += b + imm\n\t\tcase 13: // SDBI\n\t\t\tb := p.dfByte()\n\t\t\timm := p.imm()\n\t\t\tp.DF = (p.D > b+imm)\n\t\t\tp.D = b + imm - p.D\n\t\tcase 14: // SHLC\n\t\t\tc := (p.D&128 == 128)\n\t\t\tp.D = (p.D << 1) | p.dfByte()\n\t\t\tp.DF = c\n\t\tcase 15: // SMBI\n\t\t\tb := p.dfByte()\n\t\t\timm := p.imm()\n\t\t\tp.DF = (b+p.D < imm)\n\t\t\tp.D = b + p.D - imm\n\t\t}\n\tcase 8: // Get Lo\n\t\tp.D = byte(p.Reg[n])\n\tcase 9: // Get Hi\n\t\tp.D = byte(p.Reg[n] >> 8)\n\tcase 10: // Set Lo\n\t\tp.Reg[n] = (p.Reg[n] & 0xFF00) | uint16(p.D)\n\tcase 11: // Set Hi\n\t\tp.Reg[n] = (p.Reg[n] & 0x00FF) | (uint16(p.D) << 8)\n\tcase 12: // LBR...\n\tcase 13: // Set P\n\t\tp.P = n\n\tcase 14: // Set X\n\t\tp.X = n\n\tcase 15: // misc...\n\n\t\tswitch n {\n\t\tcase 0: // LDX\n\t\t\tp.D = p.Mem[p.Reg[p.X]%SZ]\n\t\tcase 1: // OR\n\t\t\tp.D |= p.Mem[p.Reg[p.X]%SZ]\n\t\tcase 2: // AND\n\t\t\tp.D &= p.Mem[p.Reg[p.X]%SZ]\n\t\tcase 3: // XOR\n\t\t\tp.D ^= p.Mem[p.Reg[p.X]%SZ]\n\t\tcase 4: //\n\t\t\tp.DF = (int(p.D)+int(p.Mem[p.Reg[p.X]%SZ]) > 255)\n\t\t\tp.D += p.Mem[p.Reg[p.X]%SZ]\n\t\tcase 5: // SD\n\t\t\tp.DF = (int(p.D) > int(p.Mem[p.Reg[p.X]%SZ]))\n\t\t\tp.D = p.Mem[p.Reg[p.X]%SZ] - p.D\n\t\tcase 6: // SHR\n\t\t\tp.D = p.D >> 1\n\t\tcase 7: // SM\n\t\t\tp.DF = (int(p.D) < int(p.Mem[p.Reg[p.X]%SZ]))\n\t\t\tp.D = p.D - p.Mem[p.Reg[p.X]%SZ]\n\t\tcase 8: // LDI\n\t\t\tp.D = p.imm()\n\t\tcase 9: //\n\t\t\tp.D |= p.imm()\n\t\tcase 10: //\n\t\t\tp.D &= p.imm()\n\t\tcase 11: //\n\t\t\tp.D ^= p.imm()\n\t\tcase 12: //\n\t\t\timm := p.imm()\n\t\t\tp.DF = (p.D+imm > 255)\n\t\t\tp.D += imm\n\t\tcase 13: //\n\t\t\timm := p.imm()\n\t\t\tp.DF = (p.D > imm)\n\t\t\tp.D = imm - p.D\n\t\tcase 14: // SHL\n\t\t\tp.D = p.D << 1\n\t\tcase 15: //\n\t\t\timm := p.imm()\n\t\t\tp.DF = (p.D < imm)\n\t\t\tp.D = p.D - imm\n\t\t}\n\t}\n\tp.Reg[p.P]++\n\treturn true\n}", "func doTurn2(from, to []bool, stride int) {\n\tfor pos := range from {\n\t\tvar aliveNeighbors int\n\n\t\t// the following nested branches are ordered in most likely -> least likely\n\t\t// on a 100x100 grid, 9602/10000 cells will not go inside the outer branches\n\t\t// e.g.: most cells have have a direct up and left neighbor, only cells on the top and left borders do not, for which we wrap around\n\n\t\tvar upLeft int\n\n\t\t// try directly up and left\n\t\tif upLeft = pos - stride - 1; upLeft < 0 {\n\n\t\t\t// try directly up and wrapping to last col\n\t\t\tif upLeft = pos - 1; upLeft < 0 {\n\n\t\t\t\t// this cell is in the upper left corner, wrap to last row and col\n\t\t\t\tupLeft = len(from) - 1\n\t\t\t}\n\t\t}\n\n\t\tif from[upLeft] {\n\t\t\taliveNeighbors++\n\t\t}\n\n\t\tvar up int\n\n\t\t// try directly up\n\t\tif up = pos - stride; up < 0 {\n\n\t\t\t// this cell is in the top row, wrap to last row\n\t\t\tup = len(from) - (stride - pos)\n\t\t}\n\n\t\tif from[up] {\n\t\t\taliveNeighbors++\n\t\t}\n\n\t\tvar upRight int\n\n\t\t// try directly up and right\n\t\tif upRight = pos - stride + 1; upRight < 0 {\n\n\t\t\t// try directly up and wrapping to first col\n\t\t\tif upRight = pos - stride - stride + 1; upRight < 0 {\n\n\t\t\t\t// this cell is in the upper right corner, wrap to last row & first col\n\t\t\t\tupRight = len(from) - stride\n\t\t\t}\n\t\t}\n\n\t\tif from[upRight] {\n\t\t\taliveNeighbors++\n\t\t}\n\n\t\t// go directly left\n\t\tleft := pos - 1\n\t\t// cell is on the left border and pos-1 wrapped around, so move down 1 row\n\t\tif pos%stride == 0 {\n\t\t\tleft += stride\n\t\t}\n\n\t\tif from[left] {\n\t\t\taliveNeighbors++\n\t\t}\n\n\t\t// go directly right\n\t\tright := pos + 1\n\t\t// cell is n the right border and pos+1 wrapped around, so move up 1 row\n\t\tif pos%stride == stride-1 {\n\t\t\tright -= stride\n\t\t}\n\n\t\tif from[right] {\n\t\t\taliveNeighbors++\n\t\t}\n\n\t\tvar downLeft int\n\n\t\t// try directly down and left\n\t\tif downLeft = pos + stride - 1; downLeft >= len(from) {\n\n\t\t\t// try wrapping to last col\n\t\t\tif downLeft = pos + stride + stride - 1; downLeft >= len(from) {\n\n\t\t\t\t// we are in bottom left corner\n\t\t\t\tdownLeft = stride - 1\n\t\t\t}\n\t\t}\n\n\t\tif from[downLeft] {\n\t\t\taliveNeighbors++\n\t\t}\n\n\t\tvar down int\n\n\t\tif down = pos + stride; down >= len(from) {\n\n\t\t\t// we are in bottom row, wrap to top\n\t\t\tdown = stride - (len(from) - pos)\n\t\t}\n\n\t\tif from[down] {\n\t\t\taliveNeighbors++\n\t\t}\n\n\t\tvar downRight int\n\n\t\t// try directly down and right\n\t\tif downRight = pos + stride + 1; downRight >= len(from) {\n\n\t\t\t// we are on last col\n\t\t\tif downRight = pos + 1; downRight >= len(from) {\n\n\t\t\t\tdownRight = 0\n\t\t\t}\n\t\t}\n\n\t\tif from[downRight] {\n\t\t\taliveNeighbors++\n\t\t}\n\n\t\tto[pos] = (from[pos] && (aliveNeighbors == 2 || aliveNeighbors == 3)) || aliveNeighbors == 3\n\t}\n}", "func findDirections(x, y int, length *int, value int, directions []dirTable) int {\n num := 0\n numChecks := 0\n if value != wall || (getMaze(x, y) == path && setCell(x, y, check, noUpdate, *length, numChecks)) {\n minLength := [4]int {*length, *length, *length, *length}\n len := *length\n for {\n setInt(&dspLength, len)\n dirLength := [4]int {len, len, len, len}\n offset := rand.Intn(4)\n for i := 0; i < 4; i++ {\n dir := &stdDirection[(i + offset) % 4]\n num += look(dir.heading, x, y, dir.x, dir.y, num, value, directions, &dirLength[i] , &minLength[i], &numChecks)\n }\n if num > 0 || len < 0 {\n break\n }\n minLength := min( min(minLength[0], minLength[1]), min(minLength[2], minLength[3]) )\n if minLength <= 0 {\n minLength = 1\n }\n len -= minLength\n }\n if len == *length && len < getInt(&depth) {\n len++\n }\n *length = len\n if getMaze(x, y) == check {\n setMaze(x, y, path)\n }\n }\n if getInt(&maxChecks) < numChecks {\n setInt(&maxChecks , numChecks)\n }\n return (num);\n}", "func stepfrom(dir rune, x, y int) (sx, sy int) {\n\tswitch dir {\n\tcase 'N':\n\t\treturn x, y + 1\n\tcase 'S':\n\t\treturn x, y - 1\n\tcase 'W':\n\t\treturn x + 1, y\n\tcase 'E':\n\t\treturn x - 1, y\n\t}\n\tpanic(\"invalid stepfrom direction\")\n}", "func (w walk) cycleDepth() uint {\n\tif len(w) == 0 {\n\t\treturn 0\n\t}\n\tn := w[len(w)-1]\n\tc := uint(1)\n\tfor i := len(w) - 2; i >= 0; i-- {\n\t\tif n == w[i] {\n\t\t\tc++\n\t\t}\n\t}\n\treturn c\n}", "func shortestPathAllKeys(grid []string) int {\n \n}", "func Run() {\n\tinputInts := bp.Atoi(bp.GetN(\"day10/day10_input.txt\"))\n\tsort.Ints(inputInts)\n\n\toneJoltDiff, threeJoltDiff := 0, 0\n\tfor i := 0; i <= len(inputInts); i++ {\n\t\tcurr := 0\n\t\tif i == 0 {\n\t\t\tcurr = 0\n\t\t} else {\n\t\t\tcurr = inputInts[i-1]\n\t\t}\n\n\t\tnext := 0\n\t\tif len(inputInts) == i {\n\t\t\tnext = inputInts[i-1] + 3\n\t\t} else {\n\t\t\tnext = inputInts[i]\n\t\t}\n\n\t\tif next-curr == 1 {\n\t\t\toneJoltDiff++\n\t\t} else if next-curr == 3 {\n\t\t\tthreeJoltDiff++\n\t\t}\n\t}\n\n\tfmt.Println(\"\\tpart 1:\", oneJoltDiff*threeJoltDiff)\n\n\tinputInts = append([]int{0}, inputInts...)\n\tinputInts = append(inputInts, inputInts[len(inputInts)-1]+3)\n\n\tindices := make([]int, 1)\n\tfor i := 1; i < len(inputInts); i++ {\n\t\tif inputInts[i-1] == inputInts[i]-3 {\n\t\t\tindices = append(indices, i)\n\t\t}\n\t}\n\n\tres := 1\n\tfor i := 1; i < len(indices); i++ {\n\t\tpaths, prevIndex, currIndex := 0, indices[i-1], indices[i]\n\t\tnext(prevIndex, &inputInts, &paths, currIndex)\n\t\tres *= paths\n\t}\n\n\tfmt.Println(\"\\tpart 2:\", res)\n}", "func (d Day) SolvePartTwo() (string, error) {\n\txCycleLength := findCycleLength(d.moons, xDimension)\n\tyCycleLength := findCycleLength(d.moons, yDimension)\n\tzCycleLength := findCycleLength(d.moons, zDimension)\n\treturn fmt.Sprintf(\"%d\", util.LCM3(xCycleLength, yCycleLength, zCycleLength)), nil\n}", "func TestSwitchMotion(t *testing.T) {\n\talphabet := \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\tm, err := NewMachine(21, 1, 25, 5, 1, 2, alphabet)\n\tif err != nil {\n\t\tt.Fatalf(\"Could not complete NewMachine: %s\", err.Error())\n\t}\n\tvar tests = [][]int{\n\t\t{20, 0, 24, 4},\n\t\t{21, 1, 24, 4},\n\t\t{22, 2, 24, 4},\n\t\t{23, 3, 24, 4},\n\t\t{24, 3, 24, 5},\n\t\t{0, 3, 0, 5},\n\t\t{1, 4, 0, 5},\n\t\t{2, 5, 0, 5},\n\t}\n\tfor i, test := range tests {\n\t\tif m.sixes.position != test[0] ||\n\t\t\tm.fast.position != test[1] ||\n\t\t\tm.middle.position != test[2] ||\n\t\t\tm.slow.position != test[3] {\n\t\t\tt.Errorf(\"TestSwitchMotion fails after %d steps: [%d,%d,%d,%d], want %v\", i,\n\t\t\t\tm.sixes.position, m.fast.position, m.middle.position, m.slow.position, test)\n\t\t}\n\t\tm.step()\n\t}\n}", "func numIslands(grid [][]byte) int {\n\t//h := len(grid)\n\t//w := len(grid[0])\n\t//walkJudge := make([][]bool, h)\n\t//for i, _ := range walkJudge {\n\t//\twalkJudge[i] = make([]bool, w)\n\t//}\n\tcount := 0\n\n\tfor i, _ := range grid {\n\t\tfor j, _ := range grid[i] {\n\t\t\tif grid[i][j] == '1' {\n\t\t\t\tdfs(grid, i, j)\n\t\t\t\tcount += 1\n\t\t\t\t//fullPath(&walkJudge, grid,i, j)\n\t\t\t}\n\t\t}\n\t}\n\treturn count\n}", "func (v *Values) GetSteps() map[string]interface{} {\n\treturn v.m[\"step\"].(map[string]interface{})\n}", "func TestStepsFailedRetries(t *testing.T) {\n\twf := test.LoadTestWorkflow(\"testdata/steps-failed-retries.yaml\")\n\twoc := newWoc(*wf)\n\twoc.operate()\n\tassert.Equal(t, string(wfv1.NodeFailed), string(woc.wf.Status.Phase))\n}", "func solveAllSegments(display sevenSegmentDisplay) (result int) {\n\tlookupTable := make(map[string]int)\n\tcountPositions := make(map[rune]int)\n\tfor _, displayPos := range display.segments {\n\t\tfor _, char := range displayPos {\n\t\t\tcountPositions[char]++\n\t\t}\n\t}\n\n\tpositionSheet := make(map[int][]rune)\n\tfor char, val := range countPositions {\n\t\tpositionSheet[val] = append(positionSheet[val], char)\n\t}\n\n\tfor _, displayPos := range display.segments {\n\t\tswitch len(displayPos) {\n\t\tcase 2:\n\t\t\tlookupTable[displayPos] = 1\n\t\tcase 3:\n\t\t\tlookupTable[displayPos] = 7\n\t\tcase 4:\n\t\t\tlookupTable[displayPos] = 4\n\t\tcase 7:\n\t\t\tlookupTable[displayPos] = 8\n\t\tcase 5: // 2, 3 or 5\n\t\t\t// Only 2 has an empty space bottom-right\n\t\t\tif !strings.ContainsRune(displayPos, positionSheet[9][0]) {\n\t\t\t\tlookupTable[displayPos] = 2\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// if they have top and top-right it's 3 else 5\n\t\t\tif strings.ContainsRune(displayPos, positionSheet[8][0]) && strings.ContainsRune(displayPos, positionSheet[8][1]) {\n\t\t\t\tlookupTable[displayPos] = 3\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlookupTable[displayPos] = 5\n\t\tcase 6: // 0, 6 or 9\n\t\t\t// if they have bottom left they can be - 0 6 -\n\t\t\tif strings.ContainsRune(displayPos, positionSheet[4][0]) {\n\t\t\t\t// if they have top and top-right it's 0 else 6\n\t\t\t\tif strings.ContainsRune(displayPos, positionSheet[8][0]) && strings.ContainsRune(displayPos, positionSheet[8][1]) {\n\t\t\t\t\tlookupTable[displayPos] = 0\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlookupTable[displayPos] = 6\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlookupTable[displayPos] = 9\n\t\t}\n\t}\n\n\tvar resultString = \"\"\n\tfor _, value := range display.values {\n\t\tresultString += strconv.FormatInt(int64(lookupTable[value]), 10)\n\t}\n\n\treturn pkg.MustAtoi(resultString)\n}", "func (stem *Stem) step3() {\r\n\tif stem.k == stem.k0 {\r\n\t\treturn /*ForBug1*/\r\n\t}\r\n\tswitch stem.b[stem.k-1] {\r\n\tcase 'a':\r\n\t\tif stem.ends(\"ational\") {\r\n\t\t\tstem.r(\"ate\")\r\n\t\t}\r\n\t\tif stem.ends(\"tional\") {\r\n\t\t\tstem.r(\"tion\")\r\n\t\t}\r\n\tcase 'c':\r\n\t\tif stem.ends(\"enci\") {\r\n\t\t\tstem.r(\"ence\")\r\n\t\t}\r\n\t\tif stem.ends(\"anci\") {\r\n\t\t\tstem.r(\"ance\")\r\n\t\t\tbreak\r\n\t\t}\r\n\tcase 'e':\r\n\t\tif stem.ends(\"izer\") {\r\n\t\t\tstem.r(\"ize\")\r\n\t\t}\r\n\tcase 'l':\r\n\t\tif stem.ends(\"bli\") {\r\n\t\t\tstem.r(\"ble\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"alli\") {\r\n\t\t\tstem.r(\"al\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"entli\") {\r\n\t\t\tstem.r(\"ent\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"eli\") {\r\n\t\t\tstem.r(\"e\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"ousli\") {\r\n\t\t\tstem.r(\"ous\")\r\n\t\t\tbreak\r\n\t\t}\r\n\tcase 'o':\r\n\t\tif stem.ends(\"ization\") {\r\n\t\t\tstem.r(\"ize\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"ation\") {\r\n\t\t\tstem.r(\"ate\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"ator\") {\r\n\t\t\tstem.r(\"ate\")\r\n\t\t\tbreak\r\n\t\t}\r\n\tcase 's':\r\n\t\tif stem.ends(\"alism\") {\r\n\t\t\tstem.r(\"al\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"iveness\") {\r\n\t\t\tstem.r(\"ive\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"fulness\") {\r\n\t\t\tstem.r(\"ful\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"ousness\") {\r\n\t\t\tstem.r(\"ous\")\r\n\t\t\tbreak\r\n\t\t}\r\n\tcase 't':\r\n\t\tif stem.ends(\"aliti\") {\r\n\t\t\tstem.r(\"al\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"iviti\") {\r\n\t\t\tstem.r(\"ive\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif stem.ends(\"biliti\") {\r\n\t\t\tstem.r(\"ble\")\r\n\t\t\tbreak\r\n\t\t}\r\n\tcase 'g':\r\n\t\tif stem.ends(\"logi\") {\r\n\t\t\tstem.r(\"log\")\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n}", "func Part2(ctx context.Context, input string) (interface{}, error) {\n\tg1 := new4DSpace(strings.Split(input, \"\\n\"), \".\")\n\tg2 := new4DSpace(strings.Split(input, \"\\n\"), \".\")\n\n\tvar curr, next map[coordinate4D]string\n\tfor i := 0; i < 6; i++ {\n\t\tif i%2 == 0 {\n\t\t\tcurr = g1\n\t\t\tnext = g2\n\t\t} else {\n\t\t\tcurr = g2\n\t\t\tnext = g1\n\t\t}\n\n\t\tminX, maxX, minY, maxY, minZ, maxZ, minW, maxW := 0, 0, 0, 0, 0, 0, 0, 0\n\t\tfor c := range curr {\n\t\t\tif c.X < minX {\n\t\t\t\tminX = c.X\n\t\t\t}\n\t\t\tif c.X > maxX {\n\t\t\t\tmaxX = c.X\n\t\t\t}\n\n\t\t\tif c.Y < minY {\n\t\t\t\tminY = c.Y\n\t\t\t}\n\t\t\tif c.Y > maxY {\n\t\t\t\tmaxY = c.Y\n\t\t\t}\n\n\t\t\tif c.Z < minZ {\n\t\t\t\tminZ = c.Z\n\t\t\t}\n\t\t\tif c.Z > maxZ {\n\t\t\t\tmaxZ = c.Z\n\t\t\t}\n\n\t\t\tif c.W < minW {\n\t\t\t\tminW = c.W\n\t\t\t}\n\t\t\tif c.W > maxW {\n\t\t\t\tmaxW = c.W\n\t\t\t}\n\t\t}\n\t\tmaxX++\n\t\tmaxY++\n\t\tmaxZ++\n\t\tmaxW++\n\n\t\tfor x := minX - 1; x <= maxX; x++ {\n\t\t\tfor y := minY - 1; y <= maxY; y++ {\n\t\t\t\tfor z := minZ - 1; z <= maxZ; z++ {\n\t\t\t\t\tfor w := minW - 1; w <= maxW; w++ {\n\t\t\t\t\t\tc := coordinate4D{X: x, Y: y, Z: z, W: w}\n\t\t\t\t\t\tv := curr[c]\n\t\t\t\t\t\tif v == \"\" {\n\t\t\t\t\t\t\tv = \".\"\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tactiveCount := 0\n\t\t\t\t\t\tfor _, s := range c.Surrounding() {\n\t\t\t\t\t\t\tswitch curr[s] {\n\t\t\t\t\t\t\tcase \"#\":\n\t\t\t\t\t\t\t\tactiveCount++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif v == \"#\" && (activeCount != 2 && activeCount != 3) {\n\t\t\t\t\t\t\tnext[c] = \".\"\n\t\t\t\t\t\t} else if v == \".\" && activeCount == 3 {\n\t\t\t\t\t\t\tnext[c] = \"#\"\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tnext[c] = v\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Count\n\tc := 0\n\tfor _, v := range next {\n\t\tif v == \"#\" {\n\t\t\tc++\n\t\t}\n\t}\n\n\treturn c, nil\n}" ]
[ "0.631437", "0.6289041", "0.5995027", "0.5943802", "0.58128786", "0.5675189", "0.5543537", "0.55353135", "0.55158156", "0.5515774", "0.54764587", "0.54721206", "0.5456247", "0.5381262", "0.5378672", "0.53775716", "0.53614694", "0.5350701", "0.53365123", "0.53184175", "0.5297281", "0.52075386", "0.5199651", "0.5183207", "0.51633257", "0.5142028", "0.5129821", "0.5127829", "0.51167876", "0.5092953", "0.50871724", "0.5079805", "0.50724936", "0.50419986", "0.50326186", "0.5030932", "0.5019751", "0.5013328", "0.501022", "0.5006592", "0.50000155", "0.49951226", "0.4993729", "0.4989663", "0.49793044", "0.4973419", "0.49597302", "0.49575353", "0.4956297", "0.49517104", "0.49448442", "0.49382585", "0.49343315", "0.49208546", "0.48918927", "0.48904493", "0.48880407", "0.48875445", "0.4880187", "0.48763844", "0.4872424", "0.48612168", "0.48611537", "0.48546505", "0.48545483", "0.48475185", "0.48419672", "0.48208344", "0.48191342", "0.48144913", "0.48083836", "0.48070198", "0.48052353", "0.47980547", "0.47908816", "0.4789271", "0.47816625", "0.4770155", "0.47691897", "0.47674453", "0.47658598", "0.4764117", "0.47592124", "0.47559533", "0.4750269", "0.47481936", "0.47470096", "0.47283617", "0.4723456", "0.4717415", "0.4715442", "0.471541", "0.47064358", "0.47002098", "0.4675443", "0.46719924", "0.46713346", "0.46660152", "0.46621847", "0.466074", "0.46596295" ]
0.0
-1
/ 0 1 0 0 1 0 0 1 0 1 1 1 2 1 0 2 2 2 1 0 3 3 2 1 0
func findLargestIslandUtil(arr [][]int, maxCol int, maxRow int, currCol int, currRow int, traversed [][]bool) int { dir := [][]int{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}} var x, y int var sum = 1 // Traverse in all eight directions. for i := 0; i < 8; i++ { x = currCol + dir[i][0] y = currRow + dir[i][1] if x >= 0 && x < maxCol && y >= 0 && y < maxRow && traversed[x][y] == false && arr[x][y] == 1 { traversed[x][y] = true sum += findLargestIslandUtil(arr, maxCol, maxRow, x, y, traversed) } } return sum }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func createSet(input [9]int8) int16 {\n\tvar used int16 = 0\n\tfor i := 0; i < 9; i++ {\n\t\tused += (1 << uint(input[i] - 1))\n\t}\n\treturn used;\n}", "func duplicateZeros1(arr []int) {\n\tvar count int\n\tn := len(arr)\n\tfor _, v := range arr {\n\t\tif v == 0 {\n\t\t\tcount++\n\t\t}\n\t}\n\n\tfor i := n - 1; i >= 0; i-- {\n\t\tif i+count >= n {\n\t\t\tif arr[i] == 0 {\n\t\t\t\tif i+count-1 < n {\n\t\t\t\t\tarr[i+count-1] = 0\n\t\t\t\t}\n\t\t\t\tcount--\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif count != 0 {\n\t\t\tarr[i+count] = arr[i]\n\t\t\tif arr[i] == 0 {\n\t\t\t\tarr[i+count-1] = 0\n\t\t\t\tcount--\n\t\t\t}\n\t\t}\n\t}\n}", "func c1(n int) int { return n - WIDTH - 1 }", "func countInitialOccurrences(s []byte, x byte) int {\n\tfor i, c := range s {\n\t\tif c != x {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn len(s)\n}", "func rej(a []int16, buf []byte) int {\n\tctr, buflen, alen := 0, len(buf), len(a)\n\tfor pos := 0; pos+3 <= buflen && ctr < alen; pos += 3 {\n\t\tval0 := (uint16(buf[pos]) | (uint16(buf[pos+1]) << 8)) & 0xfff\n\t\tval1 := (uint16(buf[pos+1]>>4) | (uint16(buf[pos+2]) << 4)) & 0xfff\n\t\tif val0 < uint16(q) {\n\t\t\ta[ctr] = int16(val0)\n\t\t\tctr++\n\t\t}\n\t\tif val1 < uint16(q) && ctr != alen {\n\t\t\ta[ctr] = int16(val1)\n\t\t\tctr++\n\t\t}\n\t}\n\treturn ctr\n}", "func duplicateZeros(n int) string {\n\tvar zero string\n\tfor i := 0; i < n; i++ {\n\t\tzero += \"f0\"\n\t}\n\n\treturn zero\n}", "func slog(block uint32) uint16 {\n\tfor i := uint16(12); i <= 20; i++ {\n\t\tif block == (1 << i) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn 0\n}", "func countLeadingZeroes(i int, word int32) int {\n\tleading := 0\n\tfor word < powers10[i] {\n\t\ti--\n\t\tleading++\n\t}\n\treturn leading\n}", "func countLeadingZeroes(i int, word int32) int {\n\ttrace_util_0.Count(_mydecimal_00000, 25)\n\tleading := 0\n\tfor word < powers10[i] {\n\t\ttrace_util_0.Count(_mydecimal_00000, 27)\n\t\ti--\n\t\tleading++\n\t}\n\ttrace_util_0.Count(_mydecimal_00000, 26)\n\treturn leading\n}", "func TestDuplicateZeros(t *testing.T) {\n\tduplicateZeros1([]int{1, 0, 2, 3, 0, 4, 5, 0})\n\tduplicateZeros1([]int{1, 2, 3})\n}", "func countAndSay(n int) string {\n\tif n <= 1{\n\t\treturn \"1\"\n\t}\n\tvar last string = \"1\"\n\tfor i := 2;i <= n;i++{\n\t\tslow := 0\n\t\tfast := slow + 1\n\t\t//var cur string\n\t\tvar cur bytes.Buffer\n\t\tl := len(last)\n\t\tfor fast <= l{\n\t\t\tif fast < len(last) && last[slow] == last[fast]{\n\t\t\t\tfast++\n\t\t\t}else{\n\t\t\t\t//l := fast - slow\n\t\t\t\t//cnt := strconv.Itoa(l)\n\t\t\t\t//num := string(last[slow])\n\t\t\t\t//cur += cnt + num\n\t\t\t\tcur.WriteString(strconv.Itoa(fast - slow))\n\t\t\t\tcur.WriteByte(last[slow])\n\t\t\t\tslow = fast\n\t\t\t\tfast++\n\t\t\t}\n\t\t}\n\t\tlast = cur.String()\n\t\tif i == n{\n\t\t\treturn last\n\t\t}\n\t}\n\treturn last\n}", "func duplicateZerosV1(arr []int) {\n\tvar buf []int\n\tfor i := 0; i < len(arr); i++ {\n\t\tif arr[i] == 0 && i < len(arr)-1 {\n\t\t\tbuf = make([]int, len(arr)-i-1)\n\t\t\tcopy(buf, arr[i+1:i+len(buf)])\n\t\t\tarr[i+1] = 0\n\t\t\tfor j := 0; j < len(buf)-1; j++ {\n\t\t\t\tarr[i+2+j] = buf[j]\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t}\n}", "func increment(counter []byte) {\n\tfor i := len(counter) - 1; i >= 0; i-- {\n\t\tcounter[i]++\n\t\tif counter[i] != 0 {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func RepeatFasta(s []byte, count int) {\n pos := 0\n s2 := make([]byte, len(s)+WIDTH)\n copy(s2, s)\n copy(s2[len(s):], s)\n for count > 0 {\n line := min(WIDTH, count)\n out.Write(s2[pos : pos+line])\n out.WriteByte('\\n')\n pos += line\n if pos >= len(s) {\n pos -= len(s)\n }\n count -= line\n }\n}", "func init() {\n\tval := make([]byte, 4)\n\tfor i := 0; i < 256; i++ {\n\t\tfor j := 0; j < 4; j++ {\n\t\t\t// First base is the most significant digit.\n\t\t\tval[3-j] = Iton((i >> (2 * j)) & 3)\n\t\t}\n\t\tcopy(dnaFrom2bit[i][:], val)\n\t}\n}", "func countingValleys(n int32, s string) int32 {\n\tstartAr := []int32{0}\n\tvar start int32\n\tvar valleyPoint int32 = 1\n\tfor _, elem := range s {\n\t\tchar := string(elem)\n\t\tcheckInt := true\n\t\tcheckInt = math.Signbit(float64(start))\n\t\tif char == \"D\" {\n\t\t\tstart = start - 1\n\t\t} else {\n\t\t\tstart = start + 1\n\t\t}\n\n\t\tif start == 0 {\n\t\t\tif checkInt == true {\n\t\t\t\tvalleyPoint = valleyPoint + 1\n\t\t\t}\n\t\t}\n\t\tstartAr = append(startAr, start)\n\t}\n\tfmt.Println(startAr)\n\tvalley := valleyPoint - 1\n\treturn valley\n}", "func countAndSay(n int) string {\n\tif n == 1 { // special case\n\t\treturn \"1\"\n\t}\n\tpre, cur := \"\", \"1\"\n\thead, tail := 0, 0\n\n\ttmp := cur[0]\n\tlength := len(cur)\n\n\tfor i := 1; i < n; i++ { // 1 -> n -1\n\t\tlength = len(cur) // reset length\n\t\ttmp = cur[0] // reset tmp\n\t\thead = 0 // reset head and tail 0 0\n\t\tfor tail = 0; tail < length; tail++ {\n\t\t\tif cur[tail] == tmp { // find same as cache\n\t\t\t\thead++\n\t\t\t} else { // not found add tmp and cache pre then mark head -> 1\n\t\t\t\tpre = pre + strconv.Itoa(head) + string(tmp)\n\t\t\t\ttmp = cur[tail]\n\t\t\t\thead = 1\n\t\t\t}\n\n\t\t\tif tail == length-1 { // special case length-1 cache pre\n\t\t\t\tpre = pre + strconv.Itoa(head) + string(tmp)\n\t\t\t}\n\t\t}\n\t\tcur = pre // cur now\n\t\tpre = \"\" //reset\n\t}\n\treturn cur\n}", "func emitRepeat(dst []byte, offset, length int) int {\n\t// Repeat offset, make length cheaper\n\tlength -= 4\n\tif length <= 4 {\n\t\tdst[0] = uint8(length)<<2 | tagCopy1\n\t\tdst[1] = 0\n\t\treturn 2\n\t}\n\tif length < 8 && offset < 2048 {\n\t\t// Encode WITH offset\n\t\tdst[1] = uint8(offset)\n\t\tdst[0] = uint8(offset>>8)<<5 | uint8(length)<<2 | tagCopy1\n\t\treturn 2\n\t}\n\tif length < (1<<8)+4 {\n\t\tlength -= 4\n\t\tdst[2] = uint8(length)\n\t\tdst[1] = 0\n\t\tdst[0] = 5<<2 | tagCopy1\n\t\treturn 3\n\t}\n\tif length < (1<<16)+(1<<8) {\n\t\tlength -= 1 << 8\n\t\tdst[3] = uint8(length >> 8)\n\t\tdst[2] = uint8(length >> 0)\n\t\tdst[1] = 0\n\t\tdst[0] = 6<<2 | tagCopy1\n\t\treturn 4\n\t}\n\tconst maxRepeat = (1 << 24) - 1\n\tlength -= 1 << 16\n\tleft := 0\n\tif length > maxRepeat {\n\t\tleft = length - maxRepeat + 4\n\t\tlength = maxRepeat - 4\n\t}\n\tdst[4] = uint8(length >> 16)\n\tdst[3] = uint8(length >> 8)\n\tdst[2] = uint8(length >> 0)\n\tdst[1] = 0\n\tdst[0] = 7<<2 | tagCopy1\n\tif left > 0 {\n\t\treturn 5 + emitRepeat(dst[5:], offset, left)\n\t}\n\treturn 5\n}", "func singleNumberA(nums []int) int {\n result:=0\n for _,data := range nums{\n result^=data\n }\n return result\n}", "func table(w string) []int {\n\tvar (\n\t\tt []int = []int{-1}\n\t\tk int\n\t)\n\tfor j := 1; j < len(w); j++ {\n\t\tk = j - 1\n\t\tfor w[0:k] != w[j-k:j] && k > 0 {\n\t\t\tk--\n\t\t}\n\t\tt = append(t, k)\n\t}\n\treturn t\n}", "func ones(n int) []int {\n\ts := make([]int, n)\n\tfor i := range s {\n\t\ts[i] = 1\n\t}\n\treturn s\n}", "func findMaxSequenceOf1s(x int) int {\n\tmaxSequenceOf1s := 0\n\tcurrentSequenceOf1s := 0\n\t// Assume int has 32 bits.\n\tfor i := 0; i < 32; i++ {\n\t\tmask := 1 << i\n\t\tif x&mask > 0 {\n\t\t\tcurrentSequenceOf1s++\n\t\t} else {\n\t\t\tmaxSequenceOf1s = ix.Max(maxSequenceOf1s, currentSequenceOf1s)\n\t\t\tcurrentSequenceOf1s = 0\n\t\t}\n\t}\n\tmaxSequenceOf1s = ix.Max(maxSequenceOf1s, currentSequenceOf1s)\n\treturn maxSequenceOf1s\n}", "func countTrailingZeroes(i int, word int32) int {\n\ttrailing := 0\n\tfor word%powers10[i] == 0 {\n\t\ti++\n\t\ttrailing++\n\t}\n\treturn trailing\n}", "func get1N(indices *[]uint16, start, end int) []uint16 {\n\tif end > cap(*indices) {\n\t\t*indices = make([]uint16, end)\n\t\tfor i := range *indices {\n\t\t\t(*indices)[i] = uint16(i)\n\t\t}\n\t}\n\treturn (*indices)[start:end]\n}", "func steps(s []int) int {\n\tsteps := 0\n\n\tfor pos := 0; pos >= 0 && pos < len(s); steps += 1 {\n\t\tnewpos := pos + s[pos]\n\t\tif s[pos] >= 3 {\n\t\t\ts[pos] -= 1\n\t\t} else {\n\t\t\ts[pos] += 1\n\t\t}\n\t\tpos = newpos\n\t}\n\n\treturn steps\n}", "func Solution(N int) int {\n result := 0\n binaryRepresentation := strconv.FormatInt(int64(N), 2)\n currentGap := 0\n \n for _,value := range binaryRepresentation{\n //Converts the current rune to ASCII representation of the digit\n val := int(value -'0')\n if val == 1{\n if currentGap > result{\n result = currentGap\n currentGap = 0\n }\n }else{\n currentGap ++\n }\n }\n \n return result\n}", "func LeadingZeros(x uint) int { return UintSize - Len(x) }", "func part1() {\n\ts := \"abc\"\n\tcount := 0\n\ti := 0\n\th := md5.New()\n\tbuffer := bytes.NewBuffer(make([]byte, 64))\n\n\tfor count < 8 {\n\t\tbuffer.Reset()\n\t\tfmt.Fprintf(buffer, \"%s%d\", s, i)\n\n\t\th.Reset()\n\t\th.Write(buffer.Bytes())\n\t\tdigest := h.Sum(nil)\n\t\tif digest[0] == 0 && digest[1] == 0 && digest[2] < 16 {\n\t\t\tfmt.Printf(\"%x\", digest[2])\n\t\t\tcount++\n\t\t}\n\t\ti++\n\t}\n\tfmt.Println()\n}", "func bitVectorLetterAppearsOddNumberOfTimes(s string) uint32 {\n\tvar result uint32 = 0\n\n\tfor _, r := range s {\n\t\t// ignore non latin lowercase alphabet runes\n\t\tif r < 'a' || r > 'z' {\n\t\t\tcontinue\n\t\t}\n\n\t\ti := r - 'a' // number of letter r in alphabet\n\t\tresult ^= (1 << i) // toggle ith bit of v\n\t}\n\n\treturn result\n}", "func countingValleys(n int32, s string) int32 {\n\n l, v := 0, 0\n s = strings.ToLower(s)\n for _, r := range s {\n\n if r == 'u' {\n if l < 0 && l+1 == 0 {\n v++\n }\n l++\n\n } else {\n l--\n }\n }\n return int32(v)\n}", "func icecreamParlor(m int32, arr []int32) []int32 {\n prev := map[int32]int{};\n for i, a := range arr {\n if prev[m-a] != 0 {\n return []int32{int32(prev[m-a]), int32(i+1)}\n }\n\n prev[a] = i+1\n }\n\n return []int32{}\n}", "func viralAdvertising(n int32) int32 {\n\n\toutput := make([]int32, n)\n\n\toutput[0] = (5 / 2) * 3\n\n\tvar i int32 = 1\n\n\tvar total int32 = 2\n\n\tfor ; i < n; i++ {\n\t\tcurrentTotal := output[i-1] / 2\n\t\toutput[i] = currentTotal * 3\n\t\ttotal += currentTotal\n\t}\n\n\treturn total\n}", "func fnv1(x uint32, list string) uint32 {\n\tfor _, b := range list {\n\t\tx = x*16777619 ^ uint32(b)\n\t}\n\treturn x\n}", "func increment(b []byte) {\n\tfor i := range b {\n\t\tb[i]++\n\t\tif b[i] != 0 {\n\t\t\treturn\n\t\t}\n\t}\n}", "func increment(b []byte) {\n\tfor i := range b {\n\t\tb[i]++\n\t\tif b[i] != 0 {\n\t\t\treturn\n\t\t}\n\t}\n}", "func incSeq(seq *[24]byte) {\n\tn := uint32(1)\n\tfor i := 0; i < 8; i++ {\n\t\tn += uint32(seq[i])\n\t\tseq[i] = byte(n)\n\t\tn >>= 8\n\t}\n}", "func init() {\n\tfor i := range pc {\n\t\tpc[i] = pc[i/2] + byte(i&1)\n\t}\n}", "func main() {\n\t// input := []int{1, 2, 2, 1, 1, 3}\n\t// input := []int{1, 2}\n\tinput := []int{-3, 0, 1, -3, 1, 1, 1, -3, 10, 0}\n\toutput := uniqueOccurrences(input)\n\tfmt.Println(output)\n}", "func countTrailingZeroes(i int, word int32) int {\n\ttrace_util_0.Count(_mydecimal_00000, 28)\n\ttrailing := 0\n\tfor word%powers10[i] == 0 {\n\t\ttrace_util_0.Count(_mydecimal_00000, 30)\n\t\ti++\n\t\ttrailing++\n\t}\n\ttrace_util_0.Count(_mydecimal_00000, 29)\n\treturn trailing\n}", "func countDuplicates(s []byte) int {\n\tbytes := make(map[byte]int)\n\tfor _, b := range s {\n\t\tif _, ok := bytes[b]; ok != true {\n\t\t\tbytes[b] = 1\n\t\t} else {\n\t\t\tbytes[b]++\n\t\t}\n\t}\n\tnum := 0\n\tfor _, v := range bytes {\n\t\tif v > 1 {\n\t\t\tnum += v - 1\n\t\t}\n\t}\n\treturn num\n}", "func Test_BitTwiddle(t *testing.T) {\n\tvar b byte\n\tfor i:=0; i<512; i++ {\n\t\tvar bool1 bool = ((b >> 7) == 1)\n\t\tvar bool2 bool = ((b & 0x80) == 0x80)\n\t\tif bool1 != bool2 {\n\t\t\tt.Fatal()\n\t\t}\n\t\tb++\n\t}\n}", "func leadingDrawdownSequence(returns []Percent) ([]GrowthMultiplier, bool) {\n\tend := -1\n\tcumulativeReturns := cumulativeList(returns)[1:]\n\tfor i, value := range cumulativeReturns {\n\t\tif value >= 1 {\n\t\t\tend = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif end == -1 {\n\t\treturn cumulativeReturns, false\n\t}\n\treturn cumulativeReturns[0:end], true\n}", "func LeadingZeros(x uint) int { return int(benchmarks.SizeOfUintInBits) - Len(x) }", "func strobogrammatic(numCount int) []string {\n\tsbgNumbers := []int{1, 6, 8, 9, 0}\n\tn := numCount % 2\n\n\tvar numList []string\n\tvar f func(str string)\n\tf = func(str string) {\n\t\tif len(str) == numCount {\n\t\t\tnumList = append(numList, str)\n\t\t\treturn\n\t\t}\n\t\tfor _, x := range sbgNumbers {\n\t\t\ty := strconv.Itoa(x)\n\t\t\tif str == \"\" && n > 0 {\n\t\t\t\tif x == 6 || x == 9 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tf(y)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(str) == numCount-2 && x == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tz := y\n\t\t\tif x == 6 {\n\t\t\t\tz = \"9\"\n\t\t\t}\n\t\t\tif x == 9 {\n\t\t\t\tz = \"6\"\n\t\t\t}\n\t\t\tf(y + str + z)\n\t\t}\n\t}\n\tf(\"\")\n\n\treturn numList\n}", "func multiples(of []int, below int)[]int {\n\t// Using a hash as a poor man's set\n\tvalues := make(map[int]bool)\n\tfor _, num := range of {\n\t\tfor i := num; i < below; i += num {\n\t\t\tvalues[i] = true\n\t\t}\n\t}\n\tresults := make([]int, len(values))\n\tvar i int = 0\n\tfor n, _ := range values {\n\t\tresults[i] = n\n\t\ti++\n\t}\n\treturn results\n}", "func Day8Part1(input []string) (string, error) {\n\n\timData := input[0]\n\timWidth, imHeight := 25, 6\n\n\tlayers := generateLayers(imData, imWidth, imHeight)\n\n\tvar layerWithFewestZeros [][]int\n\tfewestZeros := imWidth * imHeight\n\tfor _, layer := range layers {\n\n\t\tzeros := 0\n\t\tfor y := 0; y < len(layer); y++ {\n\t\t\tfor x := 0; x < len(layer[y]); x++ {\n\t\t\t\tif layer[y][x] == 0 {\n\t\t\t\t\tzeros++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif zeros < fewestZeros {\n\t\t\tfewestZeros = zeros\n\t\t\tlayerWithFewestZeros = layer\n\t\t}\n\t}\n\n\tones, twos := 0, 0\n\tfor y := 0; y < len(layerWithFewestZeros); y++ {\n\t\tfor x := 0; x < len(layerWithFewestZeros[y]); x++ {\n\t\t\tswitch layerWithFewestZeros[y][x] {\n\t\t\tcase 1:\n\t\t\t\tones++\n\t\t\tcase 2:\n\t\t\t\ttwos++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn fmt.Sprintf(\"%d\", ones*twos), nil\n}", "func Test_BitTwiddle(t *testing.T) {\n\tvar b byte\n\tfor i := 0; i < 512; i++ {\n\t\tvar bool1 bool = ((b >> 7) == 1)\n\t\tvar bool2 bool = ((b & 0x80) == 0x80)\n\t\tif bool1 != bool2 {\n\t\t\tt.Fatal()\n\t\t}\n\t\tb++\n\t}\n}", "func trailingZeroes(n int) int {\n\tif n < 5 {\n\t\treturn 0\n\t}\n\tfives := n / 5\n\n\treturn fives + trailingZeroes(n/5)\n}", "func countDistinctBinStrings(n uint) uint {\n\tif n > 32 {\n\t\treturn 0\n\t}\n\tcount := uint(0)\n\tfor num := (1 << n) - 1; num >= 0; num-- {\n\t\tif hasNoConsecutive1s(num) {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}", "func Separate_0_1_2(in []int) (zeros, ones, twos int) {\n\n\tfor _, val := range in {\n\t\tif val == 0 {\n\t\t\tzeros++\n\t\t} else if val == 1 {\n\t\t\tones++\n\t\t} else {\n\t\t\ttwos++\n\t\t}\n\t}\n\treturn zeros, ones, twos\n}", "func count_X(x, y, z byte) int {\n\tcount := 0;\n\t// 'x' = 120\n\tif ( x == 120) {\n\t\tcount = count + 1\n\t}\n\tif ( y == 120) {\n\t\tcount = count + 1\n\t}\n\tif ( z == 120) {\n\t\tcount = count + 1\n\t}\n\treturn count\n}", "func row(k int) int { return k % 4 }", "func n926(S string) int {\n\tright := make([]int, len(S)+1)\n\tfor i := len(S) - 1; i >= 0; i-- {\n\t\tright[i] = right[i+1]\n\t\tif S[i] == '0' {\n\t\t\tright[i]++\n\t\t}\n\t}\n\tans := len(S)\n\tone_count := 0\n\tfor i, c := range S {\n\t\tif right[i]+one_count < ans {\n\t\t\tans = right[i] + one_count\n\t\t}\n\t\tif c == '1' {\n\t\t\tone_count++\n\t\t}\n\t}\n\tif one_count < ans {\n\t\treturn one_count // change all 1s to 0s\n\t} else {\n\t\treturn ans\n\t}\n}", "func minIncrementForUnique(A []int) int {\n\tarr := [80000]int{}\n\tfor _, v := range A {\n\t\tarr[v]++\n\t}\n\n\tvar (\n\t\tans int\n\t\ttoken int\n\t)\n\tfor i := 0; i < 80000; i++ {\n\t\tif arr[i] > 1 {\n\t\t\ttoken += arr[i] - 1\n\t\t\tans -= i * (arr[i] - 1)\n\t\t} else if token > 0 && arr[i] == 0 {\n\t\t\ttoken--\n\t\t\tans += i\n\t\t}\n\t}\n\n\treturn ans\n}", "func repeatedString(s string, n int64) int64 {\n l := float64(len(s))\n baseA := int64(0)\n for _, letter := range s {\n if letter == 'a' {\n baseA++\n }\n }\n incompleteRepeat := math.Floor(float64(n)/l)\n incompleteLength := incompleteRepeat * l\n\n\n reminder := n - int64(incompleteLength)\n\n reminderA := int64(0)\n for index := int64(0); index < reminder; index++ {\n if s[index] == 'a' {\n reminderA++\n }\n }\n\n return (baseA * int64(incompleteRepeat)) + reminderA\n}", "func OnesCount8(x uint8) int {\n\tx = x - ((x >> 1) & 0x55)\n\tx = (x & 0x33) + ((x >> 2) & 0x33)\n\tx = (x + (x >> 4)) & 0x0f\n\treturn int(x)\n}", "func countingValleys(n int32, s string) int32 {\n depth := 0\n valley := 0\n for i := 0; int32(i) < n; i++ {\n if s[i] == 'U' {\n depth++\n }\n if s[i] == 'D' {\n depth--\n }\n\n if depth == 0 && s[i] == 'U' {\n valley++\n }\n }\n return int32(valley)\n}", "func duplicateZeros(arr []int) {\n\tfor i := 0; i < len(arr); i++ {\n\t\tif arr[i] == 0 && i < len(arr)-1 {\n\t\t\tfor j := len(arr) - 1; j > i+1; j-- {\n\t\t\t\tarr[j] = arr[j-1]\n\t\t\t}\n\t\t\tarr[i+1] = 0\n\t\t\ti++\n\t\t}\n\t}\n}", "func duplicateZeros(arr []int) {\n\tif len(arr) <= 1 {\n\t\treturn\n\t}\n\t//j:=len(arr)-1\n\tfor i := 0; i < len(arr); i++ {\n\t\tif arr[i] == 0 {\n\t\t\tfor j := len(arr) - 1; j != i; j-- {\n\t\t\t\tarr[j] = arr[j-1]\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t}\n}", "func main() {\n\tch := make(chan int)\n\tgo func() {\n\t\tvar c1 int;\n\t\tvar c2 int;\n\t\tvar c3 int;\n\t\tfor {\n\t\t\tc1 = <- ch;\n\t\t\tc2 = <- ch;\n\t\t\tc3 = <- ch;\n\t\t\tprint(c1);\n\t\t\tprint(c2);\n\t\t\tprint(c3);\n\t\t}\n\t}()\n\tvar cnt int;\n\tcnt = 0;\n\tfor {\n\t\tch <- cnt;\n\t\tif cnt == 8 { cnt = 0 } else { cnt = cnt + 1 };\n\t}\n}", "func counting_bits(number int) []int {\n\tonesPositions := []int{}\n\tposition := 0\n\tfor number > 0 {\n\t\tif is1 := number & 1; is1 == 1 {\n\t\t\tonesPositions = append(onesPositions, position)\n\t\t}\n\t\tnumber = number >> 1\n\t\tposition++\n\t}\n\tresult := append([]int{len(onesPositions)}, onesPositions...)\n\treturn result\n}", "func main() {\n\tvar a [101]int\n\t//j is the trip\n\tfor j := 1; j <= 100; j++ {\n\t\t//k is the switch\n\t\tfor k := 1; k <= 100; k++ {\n\t\t\tif k%j == 0 {\n\t\t\t\ta[k]++\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := 1; i <= 100; i++ {\n\t\tif a[i]%2 == 1 {\n\t\t\tfmt.Printf(\"switch %v = nyala, dipencet %v kali\\n\", i, a[i])\n\t\t}\n\t}\n\n}", "func isLeadingNumZeroes(hash []byte) bool {\n\tif numLeadingZeroes == 0 {\n\t\treturn true\n\t} else {\n\t\ti := 0\n\t\tnumZeroes := numLeadingZeroes\n\t\tfor {\n\t\t\t// numZeroes <= 8, byte at hash[i] will determine validity\n\t\t\tif numZeroes-8 <= 0 {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\t// numZeroes is greater than 8, byte at hash[i] must be zero\n\t\t\t\tif hash[i] != 0 {\n\t\t\t\t\treturn false\n\t\t\t\t} else {\n\t\t\t\t\ti++\n\t\t\t\t\tnumZeroes -= 8\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// returns true if byte at hash[i] has the the minimum number of leading zeroes\n\t\t// if numZeroes is 8: hash[i] < 2^(8-8) == hash[1] < 1 == hash[i] must be (0000 0000)b.\n\t\t// if numZeroes is 1: hash[i] < 2^(8-1) == hash[1] < (1000 0000)b == hash[i] <= (0111 1111)b\n\t\treturn float64(hash[i]) < math.Pow(2, float64(8-numZeroes))\n\t}\n}", "func main() {\n\ttrailingZeroes(125)\n}", "func TestZeros(t *testing.T) {\n\tvect, err := os.Open(\"randvect.txt\")\n\tif err != nil {\n\t\tt.Error(\"could not find text vector file\")\n\t}\n\tdefer vect.Close()\n\tscanner := bufio.NewScanner(vect)\n\tscanner.Scan()\n\n\tvar rng ISAAC\n\trng.randInit(true)\n\n\tvar buf bytes.Buffer\n\tfor i := 0; i < 2; i++ {\n\t\trng.isaac()\n\t\tfor j := 0; j < 256; j++ {\n\t\t\tbuf.WriteString(fmt.Sprintf(\"%.8x\", rng.randrsl[j]))\n\t\t\tif (j & 7) == 7 {\n\t\t\t\tvar output = buf.String()\n\t\t\t\tif scanner.Text() == output {\n\t\t\t\t\tscanner.Scan()\n\t\t\t\t\tbuf.Reset()\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Printf(\"o: \" + output + \"\\n\" + \"v: \" + scanner.Text() + \"\\n\")\n\t\t\t\t\tt.Fail()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func findOnes(arr []string) []string {\n\tvar allPoss []string\n\tfor _, item := range arr {\n\t\tif strings.Contains(item, \"1\") {\n\t\t\tvar possibilities []string\n\t\t\tpossibilities = replaceWithFours(item, 0, possibilities)\n\t\t\tfor _, newPoss := range possibilities {\n\t\t\t\tallPoss = append(allPoss, newPoss)\n\t\t\t}\n\t\t}\n\t\tallPoss = append(allPoss, item)\n\t}\n\treturn allPoss\n}", "func makeNext(pattern string) ([]int, error) {\n\t// sanity check\n\tlength := len(pattern)\n\tif length == 0 {\n\t\treturn nil, errors.New(\"'pattern' must contain at least one character\")\n\t}\n\tif length == 1 {\n\t\treturn []int{-1}, nil\n\t}\n\tnext := make([]int, length)\n\tnext[0], next[1] = -1, 0\n\n\tpos, count := 2, 0\n\tfor pos < length {\n\t\tif pattern[pos-1] == pattern[count] {\n\t\t\tcount++\n\t\t\tnext[pos] = count\n\t\t\tpos++\n\t\t} else {\n\t\t\tif count > 0 {\n\t\t\t\tcount = next[count]\n\t\t\t} else {\n\t\t\t\tnext[pos] = 0\n\t\t\t\tpos++\n\t\t\t}\n\t\t}\n\t}\n\treturn next, nil\n}", "func generatePRData(l int) []byte {\n\tres := make([]byte, l)\n\tseed := uint64(1)\n\tfor i := 0; i < l; i++ {\n\t\tseed = seed * 48271 % 2147483647\n\t\tres[i] = byte(seed)\n\t}\n\treturn res\n}", "func leadingZeros(x uint32) (n int) {\n\tif x >= 1<<16 {\n\t\tx >>= 16\n\t\tn = 16\n\t}\n\tif x >= 1<<8 {\n\t\tx >>= 8\n\t\tn += 8\n\t}\n\tn += int(len8tab[x])\n\treturn 32 - n\n}", "func main() {\n\ttotal := int64(0)\n\tvectors := ways(10, top, 3)\n\tfor _, vector := range vectors {\n\t\ttotal += distribute(vector)\n\t}\n\n\tfmt.Println(\"172/ How many 18-digit numbers n (without leading zeros) are there such that no digit occurs more than three times in n?\")\n\tfmt.Println(total)\n}", "func duplicateZeros(arr []int) {\n\tfor i := 0; i < len(arr); i++ {\n\t\tif arr[i] == 0 {\n\t\t\tfor j := len(arr) - 1; j > i; j-- {\n\t\t\t\tarr[j] = arr[j-1]\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t}\n}", "func canPlaceFlowers(flowerbed []int, n int) bool {\n\tif n == 0 {\n\t\treturn true\n\t}\n\t// 很容易分析得知连续三个零可以种一朵花\n\t// 为了方便处理边界情况,可以在两边补 0,假设为没种花的情况\n\tflowerbed = append([]int{0}, flowerbed...)\n\tflowerbed = append(flowerbed, 0)\n\t// 从 1 开始遍历,遍历到倒数第二位\n\tfor i := 1; i < len(flowerbed)-1; i++ {\n\t\t// 连续三个 0\n\t\tif flowerbed[i] == 0 && flowerbed[i-1] == 0 && flowerbed[i+1] == 0 {\n\t\t\tflowerbed[i] = 1\n\t\t\tn--\n\t\t}\n\t\tif n < 1 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func jumpingOnClouds(c []int32) int32 {\n\tvar jumps int32\n\tfor i := 0; i < len(c)-1; i++ {\n\t\tjumps++\n\t\tif i+2 < len(c) && c[i+2] == 0 {\n\t\t\ti++\n\t\t}\n\t}\n\treturn jumps\n}", "func disturbs(candidate []int) []int {\r\n\tnew_candidate := make([]int, len(candidate))\r\n\tr := rand.Intn(len(candidate))\r\n\tcopy(new_candidate, candidate)\r\n\tif new_candidate[r] == 1 {\r\n\t\tnew_candidate[r] = 0\r\n\t} else {\r\n\t\tnew_candidate[r] = 1\r\n\t}\r\n\treturn new_candidate\r\n}", "func main() {\n\tfmt.Println(numberOfOnes(15))\n}", "func jumpingOnClouds(c []int32) int32 {\n // Write your code here\n const SAFE int32 = 0\n const AVOID int32 = 1\n var n int32 = int32(len(c))\n var count int32 = 0\n var cloud int32 = 0\n for {\n // can move to cloud c[cloud+2]? c[cloud+1]?\n // can c+2?\n // can c+1?\n if (cloud+2 < n) && (c[cloud+2] == SAFE) {\n cloud += 2\n count++\n } else if (cloud+1 < n) && (c[cloud+1] == SAFE) {\n cloud += 1\n count++\n } else {\n // cannot move\n break\n }\n }\n return count\n}", "func vn(x []u8, y []u8, n int) u32 {\n\tif len(x) != n {\n\t\treturn 0\n\t}\n\tif len(y) != n {\n\t\treturn 0\n\t}\n\n\tvar d u32\n\tfor i := 0; i < n; i++ {\n\t\td |= u32(x[i]) ^ u32(y[i])\n\t}\n\treturn (1 & ((d - 1) >> 8)) - 1\n}", "func g(i int) (n int) {\n\tfor n = 1; sf(n) != i; n++ {\n\t}\n\treturn\n}", "func stateG1(s *scanner, c byte) int {\n\tif '0' <= c && c <= '9' {\n\t\ts.step = stateG1\n\t\treturn scanContinue\n\t}\n\treturn stateG0(s, c)\n}", "func solve1(input string) string {\n\tlist := parseInput(input)\n\ti := 0\n\tn := 0\n\tfor i >= 0 && i < len(list) {\n\t\tj := list[i]\n\t\tlist[i]++\n\t\ti += j\n\t\tn++\n\t}\n\treturn fmt.Sprint(n)\n}", "func bufferValue(index uint16, buffer []byte) (uint8, bool) {\n\ti := int(index)\n\ttotal := uint8(0)\n\tswitch buffer[i] {\n\tcase '0':\n\tcase '1':\n\t\ttotal += 16 * 1\n\tcase '2':\n\t\ttotal += 16 * 2\n\tcase '3':\n\t\ttotal += 16 * 3\n\tcase '4':\n\t\ttotal += 16 * 4\n\tcase '5':\n\t\ttotal += 16 * 5\n\tcase '6':\n\t\ttotal += 16 * 6\n\tcase '7':\n\t\ttotal += 16 * 7\n\tcase '8':\n\t\ttotal += 16 * 8\n\tcase '9':\n\t\ttotal += 16 * 9\n\tcase 'a', 'A':\n\t\ttotal += 16 * 10\n\tcase 'b', 'B':\n\t\ttotal += 16 * 11\n\tcase 'c', 'C':\n\t\ttotal += 16 * 12\n\tcase 'd', 'D':\n\t\ttotal += 16 * 13\n\tcase 'e', 'E':\n\t\ttotal += 16 * 14\n\tcase 'f', 'F':\n\t\ttotal += 16 * 15\n\tdefault:\n\t\tprint(\"!bad character in payload hi byte(number #\", i, \"):\", buffer[i], \"\\n\")\n\t\treturn 0xff, false\n\t}\n\tswitch buffer[i+1] {\n\tcase '0':\n\tcase '1':\n\t\ttotal++\n\tcase '2':\n\t\ttotal += 2\n\tcase '3':\n\t\ttotal += 3\n\tcase '4':\n\t\ttotal += 4\n\tcase '5':\n\t\ttotal += 5\n\tcase '6':\n\t\ttotal += 6\n\tcase '7':\n\t\ttotal += 7\n\tcase '8':\n\t\ttotal += 8\n\tcase '9':\n\t\ttotal += 9\n\tcase 'a', 'A':\n\t\ttotal += 10\n\tcase 'b', 'B':\n\t\ttotal += 11\n\tcase 'c', 'C':\n\t\ttotal += 12\n\tcase 'd', 'D':\n\t\ttotal += 13\n\tcase 'e', 'E':\n\t\ttotal += 14\n\tcase 'f', 'F':\n\t\ttotal += 15\n\tdefault:\n\t\tprint(\"!bad character in payload low byte (number #\", i+1, \"):\", buffer[i+1], \"\\n\")\n\t\treturn 0xff, false\n\t}\n\treturn total, true\n}", "func bufferValue(index uint16, buffer []byte) (uint8, bool) {\n\ti := int(index)\n\ttotal := uint8(0)\n\tswitch buffer[i] {\n\tcase '0':\n\tcase '1':\n\t\ttotal += 16 * 1\n\tcase '2':\n\t\ttotal += 16 * 2\n\tcase '3':\n\t\ttotal += 16 * 3\n\tcase '4':\n\t\ttotal += 16 * 4\n\tcase '5':\n\t\ttotal += 16 * 5\n\tcase '6':\n\t\ttotal += 16 * 6\n\tcase '7':\n\t\ttotal += 16 * 7\n\tcase '8':\n\t\ttotal += 16 * 8\n\tcase '9':\n\t\ttotal += 16 * 9\n\tcase 'a', 'A':\n\t\ttotal += 16 * 10\n\tcase 'b', 'B':\n\t\ttotal += 16 * 11\n\tcase 'c', 'C':\n\t\ttotal += 16 * 12\n\tcase 'd', 'D':\n\t\ttotal += 16 * 13\n\tcase 'e', 'E':\n\t\ttotal += 16 * 14\n\tcase 'f', 'F':\n\t\ttotal += 16 * 15\n\tdefault:\n\t\tprint(\"!bad character in payload hi byte(number #\", i, \"):\", buffer[i], \"\\n\")\n\t\treturn 0xff, false\n\t}\n\tswitch buffer[i+1] {\n\tcase '0':\n\tcase '1':\n\t\ttotal++\n\tcase '2':\n\t\ttotal += 2\n\tcase '3':\n\t\ttotal += 3\n\tcase '4':\n\t\ttotal += 4\n\tcase '5':\n\t\ttotal += 5\n\tcase '6':\n\t\ttotal += 6\n\tcase '7':\n\t\ttotal += 7\n\tcase '8':\n\t\ttotal += 8\n\tcase '9':\n\t\ttotal += 9\n\tcase 'a', 'A':\n\t\ttotal += 10\n\tcase 'b', 'B':\n\t\ttotal += 11\n\tcase 'c', 'C':\n\t\ttotal += 12\n\tcase 'd', 'D':\n\t\ttotal += 13\n\tcase 'e', 'E':\n\t\ttotal += 14\n\tcase 'f', 'F':\n\t\ttotal += 15\n\tdefault:\n\t\tprint(\"!bad character in payload low byte (number #\", i+1, \"):\", buffer[i+1], \"\\n\")\n\t\treturn 0xff, false\n\t}\n\treturn total, true\n}", "func singleNumber(nums []int) []int {\n\tbitmap := 0\n\tfor _, num := range nums {\n\t\tbitmap = bitmap ^ num\n\t}\n\tdiff, x := bitmap&(-bitmap), 0\n\tfor _, num := range nums {\n\t\tif num&diff != 0 {\n\t\t\tx = x ^ num\n\t\t}\n\t}\n\treturn []int{x, bitmap ^ x}\n}", "func check(arr []int) bool {\n\tvar used [10]bool\n\tfor _, f := range field {\n\t\tfor i := 0; i <= 9; i++ {\n\t\t\tused[i] = false\n\t\t}\n\t\tfor i := 0; i < 9; i++ {\n\t\t\tif arr[f[i]-1] == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif used[arr[f[i]-1]] == true {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tused[arr[f[i]-1]] = true\n\t\t}\n\t}\n\treturn true\n}", "func main() {\n\n\tinput := []int{1, 1, 0, 1, 1, 1}\n\n\tresult := solution(input)\n\tfmt.Println(result)\n\n}", "func minimumBribes(q []int32) {\n\tbribes := 0\n\tqbribes := make([]int, len(q))\n\treverse := false\n\tfor i, j := 0, len(q)-1; i < len(q); {\n\t\tif !reverse {\n\t\t\tfor x := 0; x < len(q)-i-1; x++ {\n\t\t\t\tif q[x]-1 == int32(x) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif q[x] > q[x+1] {\n\t\t\t\t\tqbribes[q[x]-1]++\n\t\t\t\t\tif qbribes[q[x]-1] > 2 {\n\t\t\t\t\t\tfmt.Printf(\"Too chaotic\\n\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tq[x], q[x+1] = q[x+1], q[x]\n\t\t\t\t\tbribes++\n\t\t\t\t}\n\t\t\t}\n\t\t\ti++\n\t\t} else {\n\t\t\tfor x := j; x > i; x-- {\n\t\t\t\tif q[x]-1 == int32(x) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif q[x-1] > q[x] {\n\t\t\t\t\tqbribes[q[x-1]-1]++\n\t\t\t\t\tif qbribes[q[x-1]-1] > 2 {\n\t\t\t\t\t\tfmt.Printf(\"Too chaotic\\n\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tq[x-1], q[x] = q[x], q[x-1]\n\t\t\t\t\tbribes++\n\t\t\t\t}\n\t\t\t}\n\t\t\tj--\n\t\t}\n\t\treverse = !reverse\n\t}\n\tfmt.Printf(\"%d\\n\", bribes)\n}", "func nums(v int) int {\n\tres := 0\n\tfor i := 0; i < v; i++ {\n\t\tif i%3 == 0 || i%5 == 0 {\n\t\t\tres += i\n\t\t}\n\t}\n\treturn res\n}", "func findRun(a uint32) int {\n\treturn int(math.Log2(float64(a & -a)))\n}", "func backtrack(pos int, total *int, fill []int, avail map[int]bool) {\n\tif pos == len(fill) {\n\t\t*total++\n\t\treturn\n\t}\n\tfor n, ok := range avail {\n\t\tif !ok || (n%(pos+1) != 0 && (pos+1)%n != 0) {\n\t\t\tcontinue // Not beautiful!\n\t\t}\n\t\tavail[n] = false\n\t\tfill[pos] = n\n\t\tbacktrack(pos+1, total, fill, avail)\n\t\tavail[n] = true\n\t}\n}", "func numTilePossibilities(tiles string) int {\n\tvar m [26]int\n\tfor _, c := range tiles {\n\t\tm[c-'A']++\n\t}\n\tvar uniq []int\n\tfor _, v := range m {\n\t\tif v > 0 {\n\t\t\tuniq = append(uniq, v)\n\t\t}\n\t}\n\n\tr := 0\n\n\tfac := func(x int) int {\n\t\tv := 1\n\t\tfor x > 0 {\n\t\t\tv *= x\n\t\t\tx--\n\t\t}\n\t\treturn v\n\t}\n\n\tn := len(uniq)\n\tuses := make([]int, n)\n\tcalc := func() int {\n\t\ttotal := 0\n\t\tp := 1\n\t\tfor _, v := range uses {\n\t\t\ttotal += v\n\t\t\tp *= fac(v)\n\t\t}\n\t\tif total == 0 {\n\t\t\treturn 0\n\t\t}\n\n\t\treturn fac(total) / p\n\t}\n\n\tvar walk func(i int)\n\twalk = func(i int) {\n\t\tif i >= len(uniq) {\n\t\t\tr += calc()\n\t\t\treturn\n\t\t}\n\n\t\tfor j := 0; j <= uniq[i]; j++ {\n\t\t\tuses[i] = j\n\t\t\twalk(i + 1)\n\t\t}\n\t}\n\n\twalk(0)\n\treturn r\n}", "func coverZeros(input [][]float64) int {\n\n\treturn 0\n}", "func (this *SlicerH264) getOneNal1(data []byte) (nalData []byte, dataCur int) {\n\t//read start\n\tnalStart := 0\n\tnalEnd := 0\n\tfor {\n\t\tif nalStart+4 >= len(data) {\n\t\t\treturn\n\t\t}\n\t\tif data[nalStart] == 0x00 &&\n\t\t\tdata[nalStart+1] == 0x00 {\n\t\t\tif data[nalStart+2] == 0x01 {\n\t\t\t\tnalStart += 3\n\t\t\t\tbreak\n\t\t\t} else if data[nalStart+2] == 0x00 {\n\t\t\t\tif data[nalStart+3] == 0x01 {\n\t\t\t\t\tnalStart += 4\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnalStart += 2\n\t\t\t}\n\t\t}\n\t\tnalStart++\n\t}\n\t//read end\n\tnalEnd = nalStart\n\tfor nalEnd < len(data) {\n\t\tif nalEnd+4 > len(data) {\n\t\t\tnalEnd = len(data)\n\t\t\tbreak\n\t\t}\n\t\tif data[nalEnd] == 0x00 &&\n\t\t\tdata[nalEnd+1] == 0x00 {\n\t\t\tif data[nalEnd+2] == 0x01 {\n\t\t\t\tbreak\n\t\t\t} else if data[nalEnd+2] == 0x00 && data[nalEnd+3] == 0x01 {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tnalEnd += 2\n\t\t\t}\n\n\t\t}\n\t\tnalEnd++\n\t}\n\t//nal data\n\tnalData = data[nalStart:nalEnd]\n\tdataCur = nalEnd\n\treturn\n}", "func popcount(x uint64) int {\n\tx -= (x >> 1) & m1 //put count of each 2 bits into those 2 bits\n\tx = (x & m2) + ((x >> 2) & m2) //put count of each 4 bits into those 4 bits\n\tx = (x + (x >> 4)) & m4 //put count of each 8 bits into those 8 bits\n\treturn int((x * h01) >> 56) //returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24) + ...\n}", "func emptyhanded() int {\n\tfor i := 0; i < 26; i++ {\n\t\tif iven[i] != 0 {\n\t\t\tif i != c[WIELD] {\n\t\t\t\tif i != c[WEAR] {\n\t\t\t\t\tif i != c[SHIELD] {\n\t\t\t\t\t\treturn 0\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 1\n}", "func (s *Scratch) readNCount() error {\n\tvar (\n\t\tcharnum uint16\n\t\tprevious0 bool\n\t\tb = &s.br\n\t)\n\tiend := b.remain()\n\tif iend < 4 {\n\t\treturn errors.New(\"input too small\")\n\t}\n\tbitStream := b.Uint32()\n\tnbBits := uint((bitStream & 0xF) + minTablelog) // extract tableLog\n\tif nbBits > tablelogAbsoluteMax {\n\t\treturn errors.New(\"tableLog too large\")\n\t}\n\tbitStream >>= 4\n\tbitCount := uint(4)\n\n\ts.actualTableLog = uint8(nbBits)\n\tremaining := int32((1 << nbBits) + 1)\n\tthreshold := int32(1 << nbBits)\n\tgotTotal := int32(0)\n\tnbBits++\n\n\tfor remaining > 1 {\n\t\tif previous0 {\n\t\t\tn0 := charnum\n\t\t\tfor (bitStream & 0xFFFF) == 0xFFFF {\n\t\t\t\tn0 += 24\n\t\t\t\tif b.off < iend-5 {\n\t\t\t\t\tb.advance(2)\n\t\t\t\t\tbitStream = b.Uint32() >> bitCount\n\t\t\t\t} else {\n\t\t\t\t\tbitStream >>= 16\n\t\t\t\t\tbitCount += 16\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (bitStream & 3) == 3 {\n\t\t\t\tn0 += 3\n\t\t\t\tbitStream >>= 2\n\t\t\t\tbitCount += 2\n\t\t\t}\n\t\t\tn0 += uint16(bitStream & 3)\n\t\t\tbitCount += 2\n\t\t\tif n0 > maxSymbolValue {\n\t\t\t\treturn errors.New(\"maxSymbolValue too small\")\n\t\t\t}\n\t\t\tfor charnum < n0 {\n\t\t\t\ts.norm[charnum&0xff] = 0\n\t\t\t\tcharnum++\n\t\t\t}\n\n\t\t\tif b.off <= iend-7 || b.off+int(bitCount>>3) <= iend-4 {\n\t\t\t\tb.advance(bitCount >> 3)\n\t\t\t\tbitCount &= 7\n\t\t\t\tbitStream = b.Uint32() >> bitCount\n\t\t\t} else {\n\t\t\t\tbitStream >>= 2\n\t\t\t}\n\t\t}\n\n\t\tmax := (2*(threshold) - 1) - (remaining)\n\t\tvar count int32\n\n\t\tif (int32(bitStream) & (threshold - 1)) < max {\n\t\t\tcount = int32(bitStream) & (threshold - 1)\n\t\t\tbitCount += nbBits - 1\n\t\t} else {\n\t\t\tcount = int32(bitStream) & (2*threshold - 1)\n\t\t\tif count >= threshold {\n\t\t\t\tcount -= max\n\t\t\t}\n\t\t\tbitCount += nbBits\n\t\t}\n\n\t\tcount-- // extra accuracy\n\t\tif count < 0 {\n\t\t\t// -1 means +1\n\t\t\tremaining += count\n\t\t\tgotTotal -= count\n\t\t} else {\n\t\t\tremaining -= count\n\t\t\tgotTotal += count\n\t\t}\n\t\ts.norm[charnum&0xff] = int16(count)\n\t\tcharnum++\n\t\tprevious0 = count == 0\n\t\tfor remaining < threshold {\n\t\t\tnbBits--\n\t\t\tthreshold >>= 1\n\t\t}\n\t\tif b.off <= iend-7 || b.off+int(bitCount>>3) <= iend-4 {\n\t\t\tb.advance(bitCount >> 3)\n\t\t\tbitCount &= 7\n\t\t} else {\n\t\t\tbitCount -= (uint)(8 * (len(b.b) - 4 - b.off))\n\t\t\tb.off = len(b.b) - 4\n\t\t}\n\t\tbitStream = b.Uint32() >> (bitCount & 31)\n\t}\n\ts.symbolLen = charnum\n\n\tif s.symbolLen <= 1 {\n\t\treturn fmt.Errorf(\"symbolLen (%d) too small\", s.symbolLen)\n\t}\n\tif s.symbolLen > maxSymbolValue+1 {\n\t\treturn fmt.Errorf(\"symbolLen (%d) too big\", s.symbolLen)\n\t}\n\tif remaining != 1 {\n\t\treturn fmt.Errorf(\"corruption detected (remaining %d != 1)\", remaining)\n\t}\n\tif bitCount > 32 {\n\t\treturn fmt.Errorf(\"corruption detected (bitCount %d > 32)\", bitCount)\n\t}\n\tif gotTotal != 1<<s.actualTableLog {\n\t\treturn fmt.Errorf(\"corruption detected (total %d != %d)\", gotTotal, 1<<s.actualTableLog)\n\t}\n\tb.advance((bitCount + 7) >> 3)\n\treturn nil\n}", "func cyclicPattern(length int) []byte {\n data := make([]byte, length + (3 - length % 3))\n\n // generate cyclic pattern\n x, y, z := byte(65), byte(97), byte(48)\n for i := 0; i < length; i += 3 {\n data[i] = x\n data[i + 1] = y\n data[i + 2] = z\n\n // get the next cycle\n x, y, z = nextCycle(x, y, z)\n }\n\n // since data is a multiple of 3, cut it to length\n return data[:length]\n}", "func nonZeroToAllOnes(x uint32) uint32 {\n\treturn ((x - 1) >> 31) - 1\n}", "func nonZeroToAllOnes(x uint32) uint32 {\n\treturn ((x - 1) >> 31) - 1\n}", "func nextSystemRepeat(s *system, cmp *system) {\n\ts.advance()\n\txRepeat := int64(0)\n\tyRepeat := int64(0)\n\tzRepeat := int64(0)\n\tfor xRepeat == 0 || yRepeat == 0 || zRepeat == 0 {\n\t\ts.advance()\n\t\tif xRepeat == 0 && checkSystemDimension(s, cmp, func(m *moon) int { return m.p.x }, func(m *moon) int { return m.v.x }) {\n\t\t\txRepeat = s.timeStep\n\t\t}\n\t\tif yRepeat == 0 && checkSystemDimension(s, cmp, func(m *moon) int { return m.p.y }, func(m *moon) int { return m.v.y }) {\n\t\t\tyRepeat = s.timeStep\n\t\t}\n\t\tif zRepeat == 0 && checkSystemDimension(s, cmp, func(m *moon) int { return m.p.z }, func(m *moon) int { return m.v.z }) {\n\t\t\tzRepeat = s.timeStep\n\t\t}\n\t}\n\tfmt.Printf(\"Repeats at x: %d, y: %d, z: %d (lcm: %d)\\n\", xRepeat, yRepeat, zRepeat, lcm(xRepeat, yRepeat, zRepeat))\n\n}", "func countBattleships(board [][]byte) int {\n\t// O(1) extra space\n\tcount1, single1 := 0, 0\n\tfor i := 0; i < len(board); i++ {\n\t\tgood, bad := 0, 0\n\t\tfor j := 0; j <= len(board[0]); j++ {\n\t\t\tif j == len(board[0]) || board[i][j] == '.' {\n\t\t\t\tif good > 0 && bad == 0 {\n\t\t\t\t\tcount1++\n\t\t\t\t\tif good == 1 {\n\t\t\t\t\t\tsingle1++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgood, bad = 0, 0\n\t\t\t}\n\t\t\tif j < len(board[0]) && board[i][j] == 'X' {\n\t\t\t\tif (i-1 >= 0 && board[i-1][j] == 'X') || (i+1 < len(board) && board[i+1][j] == 'X') {\n\t\t\t\t\tbad++\n\t\t\t\t} else {\n\t\t\t\t\tgood++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tcount2, single2 := 0, 0\n\tfor j := 0; j < len(board[0]); j++ {\n\t\tgood, bad := 0, 0\n\t\tfor i := 0; i <= len(board); i++ {\n\t\t\tif i == len(board) || board[i][j] == '.' {\n\t\t\t\tif good > 0 && bad == 0 {\n\t\t\t\t\tcount2++\n\t\t\t\t\tif good == 1 {\n\t\t\t\t\t\tsingle2++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgood, bad = 0, 0\n\t\t\t}\n\t\t\tif i < len(board) && board[i][j] == 'X' {\n\t\t\t\tif (j-1 >= 0 && board[i][j-1] == 'X') || (j+1 < len(board[0]) && board[i][j+1] == 'X') {\n\t\t\t\t\tbad++\n\t\t\t\t} else {\n\t\t\t\t\tgood++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn count1 + count2 - single1\n}", "func kerDIF8(a []fr.Element, twiddles [][]fr.Element, stage int) {\n\n\tfr.Butterfly(&a[0], &a[4])\n\tfr.Butterfly(&a[1], &a[5])\n\tfr.Butterfly(&a[2], &a[6])\n\tfr.Butterfly(&a[3], &a[7])\n\ta[5].Mul(&a[5], &twiddles[stage+0][1])\n\ta[6].Mul(&a[6], &twiddles[stage+0][2])\n\ta[7].Mul(&a[7], &twiddles[stage+0][3])\n\tfr.Butterfly(&a[0], &a[2])\n\tfr.Butterfly(&a[1], &a[3])\n\tfr.Butterfly(&a[4], &a[6])\n\tfr.Butterfly(&a[5], &a[7])\n\ta[3].Mul(&a[3], &twiddles[stage+1][1])\n\ta[7].Mul(&a[7], &twiddles[stage+1][1])\n\tfr.Butterfly(&a[0], &a[1])\n\tfr.Butterfly(&a[2], &a[3])\n\tfr.Butterfly(&a[4], &a[5])\n\tfr.Butterfly(&a[6], &a[7])\n}" ]
[ "0.5901486", "0.57600516", "0.5691947", "0.56687385", "0.5632322", "0.56271887", "0.5624384", "0.5614425", "0.5581852", "0.557765", "0.5537337", "0.54688233", "0.5465581", "0.54486245", "0.54246455", "0.5421789", "0.541518", "0.54054135", "0.5336431", "0.5312148", "0.52895814", "0.52820474", "0.5267109", "0.52641284", "0.5263497", "0.52553654", "0.5255247", "0.52532685", "0.5249208", "0.5246304", "0.5230985", "0.5210601", "0.5207772", "0.5182032", "0.5182032", "0.51817924", "0.5168768", "0.516638", "0.516318", "0.5159327", "0.51561654", "0.51502085", "0.5149734", "0.5145273", "0.51444364", "0.5141065", "0.5122224", "0.5122152", "0.51182187", "0.5114608", "0.5110662", "0.51042485", "0.5097422", "0.5090538", "0.5088352", "0.50872856", "0.50871515", "0.50801325", "0.50605494", "0.5059073", "0.5056778", "0.5050024", "0.50443906", "0.5035605", "0.502991", "0.5027193", "0.502271", "0.5020718", "0.501662", "0.5011965", "0.5001754", "0.5000927", "0.49996725", "0.49989745", "0.4996437", "0.49939045", "0.49791563", "0.4978981", "0.4968537", "0.49683052", "0.49667358", "0.49667358", "0.49648935", "0.49616957", "0.49615607", "0.49568725", "0.49566016", "0.49545282", "0.49491417", "0.49454206", "0.49435008", "0.4940012", "0.493885", "0.49370372", "0.4936621", "0.49363992", "0.4933166", "0.4933166", "0.49307314", "0.49273986", "0.49198177" ]
0.0
-1
/ Largest Island: 12
func main() { main1() main2() main3() main4() main5() main6() main7() main8() main9() main10() main11() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func main() {\n\thighestStartingPoint := 0\n\thighestValue := 0\n\tfor i := 1; i < 1000000; i++ {\n\t\tlatz := collatz.From(i)\n\t\tif latz.Length > highestValue {\n\t\t\thighestStartingPoint = i\n\t\t\thighestValue = latz.Length\n\t\t}\n\t}\n\n\tfmt.Println(highestStartingPoint)\n}", "func findLargestIslandUtil(arr [][]int, maxCol int, maxRow int, currCol int, currRow int, traversed [][]bool) int {\n\tdir := [][]int{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}\n\tvar x, y int\n\tvar sum = 1\n\n\t// Traverse in all eight directions.\n\tfor i := 0; i < 8; i++ {\n\t\tx = currCol + dir[i][0]\n\t\ty = currRow + dir[i][1]\n\t\tif x >= 0 && x < maxCol && y >= 0 && y < maxRow && traversed[x][y] == false && arr[x][y] == 1 {\n\t\t\ttraversed[x][y] = true\n\t\t\tsum += findLargestIslandUtil(arr, maxCol, maxRow, x, y, traversed)\n\t\t}\n\t}\n\n\treturn sum\n}", "func getMaxArea(board *[][]int) int {\n\tinfinites := getInfinites(board)\n\tmaxMap := make(map[int]int)\n\tvar max int\n\tfor i := 0; i < len(*board); i++ {\n\t\tfor j := 0; j < len((*board)[i]); j++ {\n\t\t\tpos := (*board)[i][j]\n\t\t\t_, ok := infinites[pos]\n\t\t\tif !ok && pos != -1 {\n\t\t\t\tmaxMap[pos]++\n\t\t\t}\n\t\t\tif maxMap[pos] > max {\n\t\t\t\tmax = maxMap[pos]\n\t\t\t}\n\t\t}\t\n\t}\n\treturn max\n}", "func main() {\n fmt.Println(largestIsland([][]int{{1, 0}, {0, 1}}))\n fmt.Println(largestIsland([][]int{{1, 1}, {1, 0}}))\n fmt.Println(largestIsland([][]int{{1, 1}, {1, 1}}))\n x := [][]int{\n {0,0,0,0,0,0,0},{0,1,1,1,1,0,0},{0,1,0,0,1,0,0},{1,0,1,0,1,0,0},{0,1,0,0,1,0,0},{0,1,0,0,1,0,0},{0,1,1,1,1,0,0},\n }\n fmt.Println(largestIsland(x))\n}", "func main() {\n\tvar highest int\n\tflag.IntVar(&highest, \"highest\", 1000000, \"highest starting number to test\")\n\tflag.Parse()\n\n\tmaxl, maxn := 1, 1\n\tfor n := highest; n > 1; n-- {\n\t\tl := lenCollatz(n)\n\t\tif l > maxl {\n\t\t\tmaxl = l\n\t\t\tmaxn = n\n\t\t}\n\t}\n\tfmt.Println(maxn)\n}", "func main() {\n\td := []int{2, 3, 4, 5, 18, 17, 6}\n\tfmt.Println(maxArea(d))\n\n}", "func findMax(sum map[int64]int64) int64 {\n\tdx := int64(0)\n\n\tfor _, v := range sum {\n\t\tdx = int64(math.Max(float64(dx), float64(v)))\n\t}\n\treturn dx\n}", "func MaxHailstoneValue(n int) int {\n var max int = n\n for n > 1 {\n var temp int = h(n)\n if temp > max {\n max = temp\n }\n n = temp\n }\n return max\n}", "func maxRegion(grid [][]int32) int32 {\n\tvar maxRegion int32\n\tfor row := 0; row < len(grid); row++ {\n\t\tfor column := 0; column < len(grid[row]); column++ {\n\t\t\tif grid[row][column] == 1 {\n\t\t\t\tsize := getRegionSize(grid, row, column)\n\t\t\t\tfmt.Println(\"size\", size, \"maxRegion\", maxRegion)\n\t\t\t\tmaxRegion = int32(math.Max(float64(size), float64(maxRegion)))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn maxRegion\n}", "func maxArea(height []int) int {\n\treturn 0\n}", "func maxi(x int, y int) int {\n if x >= y {\n return x\n } else {\n return y\n }\n}", "func maxRegion(grid [][]int32) int32 {\n\tmax := int32(0)\n\tfor i := 0; i < len(grid); i++ {\n\t\tfor j := 0; j < len(grid[0]); j++ {\n\t\t\tif grid[i][j] == 1 {\n\t\t\t\treg := clearRegion(grid, i, j)\n\t\t\t\tfor i := 0; i < len(grid); i++ {\n\t\t\t\t\t//fmt.Println(grid[i])\n\t\t\t\t}\n\t\t\t\t//fmt.Println(\"----------------\")\n\t\t\t\tif reg > max {\n\t\t\t\t\tmax = reg\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn max\n}", "func numDistinctIslands(grid [][]int) int {\n\n}", "func FindTheCity(n int, edges [][]int, distanceThreshold int) int {\n\tvar graph [][]int = make([][]int,n)\n\tfor i := 0;i < n;i++{\n\t\tgraph[i] = make([]int,n)\n\t}\n\tfor i := 0;i < n;i++ {\n\t\tfor j := 0; j < n; j++ {\n\t\t\tif i == j {\n\t\t\t\tgraph[i][j] = 0\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgraph[i][j] = 2147483647\n\t\t}\n\t}\n\tvar l int = len(edges)\n\tfor i := 0;i < l;i++{\n\t\tgraph[edges[i][0]][edges[i][1]] = edges[i][2]\n\t\tgraph[edges[i][1]][edges[i][0]] = edges[i][2]\n\t}\n\tfor k := 0;k < n;k++{\n\t\tfor j := 0;j < n;j++{\n\t\t\tfor i := 0;i < n;i++{\n\t\t\t\tif graph[i][j] > graph[i][k] + graph[k][j]{\n\t\t\t\t\tgraph[i][j] = graph[i][k] + graph[k][j]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tvar min_cnt int = 2147483647\n\tvar res int = 0\n\tfor i := 0;i < n;i++{\n\t\tvar cnt int = 0\n\t\tfor j := 0;j < n;j++{\n\t\t\tif i == j{\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif graph[i][j] <= distanceThreshold{\n\t\t\t\tcnt++\n\t\t\t}\n\t\t}\n\t\tif cnt <= min_cnt{\n\t\t\tmin_cnt = cnt\n\t\t\tres = i\n\t\t}\n\t}\n\treturn res\n}", "func maxYmin(numeros []int) (int, int) { //indicamos los tipos que va retornar (int, int)\n\tvar max, min int\n\n\tfor _, v := range numeros {\n\t\tif v > max {\n\t\t\tmax = v\n\t\t}\n\n\t\tif v < min {\n\t\t\tmin = v\n\t\t}\n\t}\n\n\treturn max, min //indicamos el orden en el que se debe retornar\n}", "func HighestPeak(isWater [][]int) [][]int {\n\tvar rows int = len(isWater)\n\tvar columns int = len(isWater[0])\n\tvar res [][]int = make([][]int, rows)\n\tfor i := 0; i < rows; i++ {\n\t\tres[i] = make([]int, columns)\n\t\tfor j := 0; j < columns; j++ {\n\t\t\tres[i][j] = -1\n\t\t}\n\t}\n\tvar q list.List\n\tfor i := 0; i < rows; i++ {\n\t\tfor j := 0; j < columns; j++ {\n\t\t\tif isWater[i][j] == 1 {\n\t\t\t\tvar p point\n\t\t\t\tp.x = i\n\t\t\t\tp.y = j\n\t\t\t\tq.PushBack(p)\n\t\t\t\tres[i][j] = 0\n\t\t\t}\n\t\t}\n\t}\n\tvar dirs [][]int = [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}\n\tvar height int = 1\n\tfor q.Len() > 0 {\n\t\tvar l int = q.Len()\n\t\tfor i := 0; i < l; i++ {\n\t\t\tvar cur point = q.Front().Value.(point)\n\t\t\tq.Remove(q.Front())\n\t\t\tfor _, dir := range dirs {\n\t\t\t\tnext := cur\n\t\t\t\tnext.x += dir[0]\n\t\t\t\tnext.y += dir[1]\n\t\t\t\tif next.x >= 0 && next.x < rows && next.y >= 0 && next.y < columns {\n\t\t\t\t\tif res[next.x][next.y] == -1 {\n\t\t\t\t\t\tres[next.x][next.y] = height\n\t\t\t\t\t\tq.PushBack(next)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\theight++\n\t}\n\treturn res\n}", "func shortestBridge(grid [][]int) int {\n\tm := len(grid)\n\tn := len(grid[0])\n\tvar islands [][]int // 2 slice of locations of 2 islands\n\n\tvar collect func(x, y int, r *[]int)\n\tcollect = func(x, y int, r *[]int) {\n\t\tgrid[y][x] = 0\n\t\t*r = append(*r, x, y)\n\t\tif 0 <= x-1 && grid[y][x-1] == 1 {\n\t\t\tcollect(x-1, y, r)\n\t\t}\n\n\t\tif n > x+1 && grid[y][x+1] == 1 {\n\t\t\tcollect(x+1, y, r)\n\t\t}\n\n\t\tif 0 <= y-1 && grid[y-1][x] == 1 {\n\t\t\tcollect(x, y-1, r)\n\t\t}\n\n\t\tif m > y+1 && grid[y+1][x] == 1 {\n\t\t\tcollect(x, y+1, r)\n\t\t}\n\t}\n\n\tfor y := 0; y < m; y++ {\n\t\tfor x := 0; x < n; x++ {\n\t\t\tif grid[y][x] == 1 {\n\t\t\t\tvar xys []int\n\t\t\t\tcollect(x, y, &xys)\n\t\t\t\tislands = append(islands, xys)\n\t\t\t}\n\t\t}\n\t}\n\n\ta, b := islands[0], islands[1]\n\tbest := math.MaxInt32\n\tfor i := 0; i < len(a) && best > 1; i += 2 {\n\t\tx1, y1 := a[i], a[i+1]\n\t\tfor j := 0; j < len(b) && best > 1; j += 2 {\n\t\t\tx2, y2 := b[j], b[j+1]\n\t\t\td := abs(x2-x1) + abs(y2-y1) - 1\n\t\t\tif d < best {\n\t\t\t\tbest = d\n\t\t\t}\n\t\t}\n\t}\n\treturn best\n}", "func Max(x, y int32) int32 {\n\treturn x - (((x - y) >> 31) & (x - y))\n}", "func highBitLoc(n uint32) uint32 {\n\treturn uint32(math.Ilogb(float64(n)*2 + 1))\n}", "func getMaximumGold(grid [][]int) int {\n m := len(grid)\n n := len(grid[0])\n var ans int\n for i := 0; i<m;i++ {\n for j := 0;j < n; j++ {\n ans = max(ans, dfsGold(grid, m, n, i, j, 0))\n }\n }\n return ans\n}", "func largestTriangleArea(points [][]int) float64 {\n \n}", "func max(sf ...int64) int64 {\n\tvar max int64\n\tfor _, val := range sf {\n\t\tif val > max {\n\t\t\tmax = val\n\t\t}\n\t}\n\treturn max\n}", "func Max(x, y int64) int64 {\n if x > y {\n return x\n }\n return y\n}", "func getMaximumGold(grid [][]int) int {\n\tdirections := [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}\n\n\tif len(grid) == 0 {\n\t\treturn 0\n\t}\n\n\tm, n := len(grid), len(grid[0])\n\tresult := 0\n\n\tfor i := 0; i < m; i++ {\n\t\tfor j := 0; j < n; j++ {\n\t\t\tresult = Max(result, findMaxGold(grid, i, j, directions))\n\t\t}\n\t}\n\treturn result\n}", "func largestRectangleAreaUsingStack(heights []int) int {\n\tvar (\n\t\tmax = 0\n\t\tstack = newIntStack()\n\t)\n\n\tstack.push(-1)\n\n\tfor k := range heights {\n\t\tfor stack.top() != -1 && heights[stack.top()] >= heights[k] {\n\t\t\tmax = maxInt(max, heights[stack.pop()]*(k-stack.top()-1))\n\t\t}\n\t\tstack.push(k)\n\t}\n\n\tfor stack.top() != -1 {\n\t\tmax = maxInt(max, heights[stack.pop()]*(len(heights)-stack.top()-1))\n\t}\n\n\treturn max\n}", "func maxYmin2(numeros []int) (max int, min int) { //indicamos los tipos y nombre que va retornar (int, int)\n\tfor _, v := range numeros {\n\t\tif v > max {\n\t\t\tmax = v\n\t\t}\n\n\t\tif v < min {\n\t\t\tmin = v\n\t\t}\n\t}\n\n\treturn //ya no necesita return porque ya le indicamos como va retornar y que orden\n}", "func main(){\n\tdp := make([]uint, len(w)+1)\n\tfor i := 1; i < len(w)+1; i++{\n\t\tif i == 1 {\n\t\t\tdp[i] = w[i-1][2]\n\t\t}else {\n\t\t\tdp[i] = max(dp[i-1], (dp[free_slot(i-1, w)]+w[i-1][2]))\n\t\t}\n\t}\n\tfmt.Println(dp[len(w)])\n//\tfind_slot(dp)\n}", "func max(x, y int) int {\n\tif x < y {\n\t\treturn y\n\t}\n\treturn x\n}", "func max(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func max(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func max(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func max(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func max(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func (bl branchList) HighestBranchIndexes() []int {\n\tmaxHeight := uint64(0)\n\tvar br branch\n\tcols := []int{}\n\tfor i, b := range bl {\n\t\tif b.height > maxHeight {\n\t\t\tmaxHeight = b.height\n\t\t\tbr = b\n\t\t\tcols = []int{i}\n\t\t} else if b.height == maxHeight && b.addr == br.addr {\n\t\t\tcols = append(cols, i)\n\t\t}\n\t}\n\treturn cols\n}", "func getMaximumGold(grid [][]int) int {\n\tvisited := make([][]bool, len(grid))\n\tfor i := range visited {\n\t\tvisited[i] = make([]bool, len(grid[0]))\n\t}\n\tmax, cur := new(int), new(int)\n\tfor i := 0; i < len(grid); i++ {\n\t\tfor j := 0; j < len(grid[0]); j++ {\n\t\t\t// only start from edge cell\n\t\t\tif grid[i][j] > 0 {\n\t\t\t\tvisit(grid, visited, i, j, max, cur)\n\t\t\t}\n\t\t}\n\t}\n\treturn *max\n}", "func max(x, y int64) int64 {\n\tif x < y {\n\t\treturn y\n\t}\n\treturn x\n}", "func main() {\n\tgreatest := max(10, 20, 15, 8, 9, 6)\n\tfmt.Println(greatest)\n}", "func Find_Largest(arr []int ) {\n\tfmt.Println(\"FIND LARGEST VALUE\")\n\tvar largest = -99999999\n\tfor i:=1 ; i < len(arr) ; i++ {\n\t\t\t//fmt.Println(arr[i])\n\t\t\tif largest <= arr[i] {\n\t\t\t\tlargest = arr[i]\n\t\t\t}\n\t\t}\n\t\tfmt.Println(\"Largest: \" , largest )\n}", "func max(x int, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func MaxValue(freqMap map[string]int) int {\n m := 0\n firstTimeThrough := true\n\n for _, value := range freqMap {\n if firstTimeThrough || value > m {\n m = value\n firstTimeThrough = false\n }\n }\n\n return m\n}", "func maxArea(height []int) int {\n maxArea := 0\n maxheight := 0\n for i := 0; i < len(height) -1; i++ {\n for j := i+1; j < len(height); j++ {\n if height[i] >= height[j] {\n maxheight = height[j]\n } else {\n maxheight = height[i]\n }\n if maxArea < (maxheight * (j-i)) {\n maxArea = (maxheight * (j-i))\n }\n }\n }\n return maxArea\n}", "func (g *graph) find_max_value(chk *checklist) int {\n\tcurrent := 0\n\tidx := -1\n\tfor i,c := range chk.nodes_count {\n\t\tif c > current {\n\t\t\tidx = i\n\t\t\tcurrent = c\n\t\t}\n\t}\n\tif idx >= 0 { chk.nodes_count[idx] = -1 }\n\treturn idx\n}", "func findMax(number []int, max int) (int, func() []int) {\n\tvar res []int\n\tfor _, p := range number {\n\t\tif p <= max {\n\t\t\tres = append(res, p)\n\t\t}\n\t}\n\n\treturn len(res), func() []int {\n\t\treturn res\n\t}\n}", "func main() {\n\tfmt.Println(maxDistToClosest([]int{1, 0, 0, 0, 1, 0, 1}))\n\tfmt.Println(maxDistToClosest([]int{1, 0, 0, 0}))\n\tfmt.Println(maxDistToClosest([]int{0, 0, 0, 1}))\n}", "func (gossiper *Gossiper) getHighestFit(confirmedGossips []*packets.TLCMessage) (*packets.TLCMessage, int) {\n\tmaxFit := float32(0)\n\tvar maxGossip *packets.TLCMessage\n\tindex := 0\n\tfor i, gossip := range confirmedGossips {\n\t\tif gossip.Fitness > maxFit {\n\t\t\tmaxGossip = gossip\n\t\t\tmaxFit = gossip.Fitness\n\t\t\tindex = i\n\t\t}\n\t}\n\treturn maxGossip, index\n}", "func maxIndexSlo(arr []int) int {\n\tii, jj := 0, 0\n\tmaxDiff := 0\n\tfor i := range arr {\n\t\tfor j := i + 1; j < len(arr); j++ {\n\t\t\tif arr[i] <= arr[j] && (j-i) >= maxDiff {\n\t\t\t\tmaxDiff = j - i\n\t\t\t\tii, jj = i, j\n\t\t\t}\n\t\t}\n\t}\n\treturn jj - ii\n}", "func Day8Part1(filepath string) any {\n\tvar res int\n\n\t// open file\n\treadFile, _ := os.Open(filepath)\n\n\t// read line\n\tfileScanner := bufio.NewScanner(readFile)\n\tfileScanner.Split(bufio.ScanLines)\n\n\t// parse map in to [][]int\n\ttreeMap := parseMap(fileScanner)\n\t// fmt.Println(treeMap)\n\n\t// init visible trees 2D array\n\tvisible := make([][]bool, len(treeMap))\n\tfor i := range visible {\n\t\tvisible[i] = make([]bool, len(treeMap[0]))\n\t}\n\n\t// look from left to r\n\tfor i := range treeMap {\n\t\tmax := 0\n\t\tfor j := range treeMap[0] {\n\t\t\tif i == 0 || i == len(treeMap)-1 || j == 0 || j == len(treeMap[0])-1 || treeMap[i][j] > max {\n\t\t\t\tvisible[i][j] = true\n\t\t\t\tmax = treeMap[i][j]\n\t\t\t}\n\t\t}\n\t}\n\n\t// look from right to l\n\tfor i := range treeMap {\n\t\tmax := 0\n\t\tfor j := len(treeMap[0]) - 1; j >= 0; j-- {\n\t\t\tif i == 0 || i == len(treeMap)-1 || j == 0 || j == len(treeMap[0])-1 || treeMap[i][j] > max {\n\t\t\t\tvisible[i][j] = true\n\t\t\t\tmax = treeMap[i][j]\n\t\t\t}\n\t\t}\n\t}\n\n\t// look from up to down\n\tfor j := 0; j <= len(treeMap[0])-1; j++ {\n\t\tmax := 0\n\t\tfor i := 0; i <= len(treeMap)-1; i++ {\n\t\t\tif i == 0 || i == len(treeMap)-1 || j == 0 || j == len(treeMap[0])-1 || treeMap[i][j] > max {\n\t\t\t\tvisible[i][j] = true\n\t\t\t\tmax = treeMap[i][j]\n\t\t\t}\n\t\t}\n\t}\n\n\t// look from down to up\n\tfor j := 0; j <= len(treeMap[0])-1; j++ {\n\t\tmax := 0\n\t\tfor i := len(treeMap) - 1; i >= 0; i-- {\n\t\t\tif i == 0 || i == len(treeMap)-1 || j == 0 || j == len(treeMap[0])-1 || treeMap[i][j] > max {\n\t\t\t\tvisible[i][j] = true\n\t\t\t\tmax = treeMap[i][j]\n\t\t\t}\n\t\t}\n\t}\n\n\t// traverse visible trees 2D array and count visibles\n\tfor i := range visible {\n\t\tfor j := range visible[i] {\n\t\t\tif visible[i][j] {\n\t\t\t\tres++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res\n}", "func maxArea(height []int) int {\n\tmaxArea := 0\n\tfor i, v := range height {\n\t\tfor j := i + 1; j < len(height); j++ {\n\t\t\tcurrentArea := min(v, height[j]) * (j - i)\n\t\t\tif maxArea < currentArea {\n\t\t\t\tmaxArea = currentArea\n\t\t\t}\n\t\t}\n\t}\n\treturn maxArea\n}", "func findCheapestPrice(n int, flights [][]int, src int, dst int, K int) int {\n \n}", "func largestRectangleArea(heights []int) int {\n\tl := len(heights)\n\tif l == 1{\n\t\treturn heights[0]\n\t}\n\tvar s []int\n\tvar max int = 0\n\theights = append(heights, 0)\n\tl++\n\tfor i := 0;i < l;i++{\n\t\tif len(s) == 0 || heights[i] > heights[s[len(s) - 1]]{\n\t\t\ts = append(s,i)\n\t\t\tcontinue\n\t\t}\n\t\tfor len(s) > 0 && heights[i] < heights[s[len(s) - 1]] {\n\t\t\th := heights[s[len(s) - 1]]\n\t\t\ts = s[:len(s) - 1]\n\t\t\tvar res int = 0\n\t\t\tif len(s) == 0{\n\t\t\t\tres = h * i\n\t\t\t}else{\n\t\t\t\tres = h * (i - 1 - s[len(s) - 1])\n\t\t\t}\n\t\t\tif res > max{\n\t\t\t\tmax = res\n\t\t\t}\n\t\t}\n\t\ts = append(s,i)\n\t}\n\treturn max\n}", "func main() {\n\tn := max(1, 2, 3, 4, 5, 6, 7, 8, 9, 20)\n\tfmt.Println(n)\n}", "func findMaxConsecutiveOnes(nums []int) int {\n \n}", "func Max(x, y int) int {\n if x < y {\n return y\n }\n return x\n}", "func findShortestSubArray(nums []int) int {\n \n}", "func maxArea(height []int) int {\n\tmaxArea := 0.0\n\tright := len(height) - 1\n\tleft := 0\n\t//简化代码 简化的点在于go自带的min函数只能比float\n\tfor left < right {\n\t\tmaxArea = math.Max(maxArea, math.Min(float64(height[right]), float64(height[left]))*float64(right-left))\n\t\tif height[right] > height[left] {\n\t\t\tleft += 1\n\t\t} else {\n\t\t\tright -= 1\n\t\t}\n\t}\n\t/*for left<right {\n\t\tminHeight := 0\n\t\tif height[right] > height[left]{\n\t\t\tminHeight = height[left]\n\t\t\tleft+=1\n\t\t}else{\n\t\t\tminHeight = height[right]\n\t\t\tright -=1\n\t\t}\n\t\tif (right-left+1)* minHeight > maxArea{\n\t\t\tmaxArea = (right-left+1)* minHeight\n\t\t}\n\t}*/\n\treturn int(maxArea)\n}", "func max(m, n int) (int, bool) {\n\tif m > n {\n\t\treturn m, true\n\t}\n\treturn n, false\n}", "func MaxI(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func flatlandSpaceStations(n int32, c []int32) (maxDistance int32) {\n\tvar (\n\t\ttmpDistance int32\n\t\ttmpMaxDistance int32\n\t\tinitStation = false\n\t\tcities = populateCity(n, c)\n\t)\n\n\t//fmt.Println(cities)\n\n\tfor _, v := range cities {\n\t\tif !v.hasStation {\n\t\t\ttmpDistance++\n\t\t} else {\n\t\t\tif initStation {\n\t\t\t\ttmpMaxDistance = (tmpDistance + 1) / 2\n\t\t\t} else {\n\t\t\t\ttmpMaxDistance = tmpDistance\n\t\t\t}\n\n\t\t\t// Set the max distance\n\t\t\tif tmpMaxDistance >= maxDistance {\n\t\t\t\tmaxDistance = tmpMaxDistance\n\t\t\t}\n\n\t\t\ttmpDistance = 0\n\t\t\tinitStation = true\n\t\t}\n\t}\n\n\t// When does not exist station on the last city\n\tif tmpDistance != 0 {\n\t\ttmpMaxDistance = tmpDistance\n\t\tif tmpMaxDistance >= maxDistance {\n\t\t\tmaxDistance = tmpMaxDistance\n\t\t}\n\t}\n\treturn\n}", "func findHighestValue(matrix [][]score) (topValue, x, y int) {\n\tvar currLargest, currX, currY int\n\tvar currValue int\n\tfor i := 0; i < len(matrix); i++ {\n\t\tfor j := 0; j < len(matrix[i]); j++ {\n\t\t\tcurrValue = matrix[i][j].value\n\t\t\tif currValue > currLargest {\n\t\t\t\tcurrLargest = currValue\n\t\t\t\tcurrX = i\n\t\t\t\tcurrY = j\n\t\t\t}\n\t\t}\n\t}\n\treturn currLargest, currX, currY\n}", "func MaxLamport(x, y Lamport) Lamport {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func max(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t} else {\n\t\treturn y\n\t}\n}", "func largestRectangle(h []int32) int64 {\n\t// how can we easily keep track of the minimum?\n\t// naive approach - recalculate it each time\n\t// will be something like O(n^2) since calculating\n\t// minimum is O(n)\n\t// and brute-force trying all possible sets of buildings\n\t// is also O(n^2)\n\t// so maybe worse than n^2\n\n\t// array of answers where i = index of start\n\t// and k = index of end\n\t// will be a triangular array since k >= i\n\t// equivalently, could have array of i and length\n\t/*\n\t\teg for array [6 3 2 5 4 1]\n\t\twould look like (index, length)\n\t\t6 3 2 2 2 1\n\t\t3 2 2 2 1\n\t\t2 2 2 1\n\t\t5 4 1\n\t\t4 1\n\t\t1\n\t\tor (startindex, endindex)\n\t\t6 3 2 2 2 1\n\t\t- 3 2 2 2 1\n\t\t- - 2 2 2 1\n\t\t- - - 5 4 1\n\t\t- - - - 4 1\n\t\t- - - - - 1\n\t*/\n\n\t// build up 2D array of minimum heights\n\t// 0 index means length of 1\n\t// min(i, 0) = i\n\t// min(i, 1) = min(min(i, 0), i + 1)\n\t// min(i, k +1) = min(min(i, k), i+k+1)\n\t// in array notation:\n\t// arr[i][k+1] = min(arr[i][k], arr[i+k])\n\tvar minHeightArray = make([][]int64, len(h))\n\n\t// initialise array\n\tfor i, v := range h {\n\t\tminHeightArray[i] = make([]int64, len(h))\n\t\tminHeightArray[i][0] = int64(v)\n\t}\n\t// flesh out rest of array\n\tfor i := range h { // here j is length of slice\n\t\tfor j := 1; j < len(h)-i; j++ { // start index must be low enough to allow slice length\n\t\t\tminHeightArray[i][j] = minInt(minHeightArray[i][j-1], minHeightArray[i+j][0])\n\t\t}\n\t}\n\n\tvar area, maxArea int64\n\n\tfor i := range h {\n\t\tfor j := 1; j < len(h)-i; j++ {\n\t\t\tarea = int64(j+1) * minHeightArray[i][j]\n\t\t\tif area > maxArea {\n\t\t\t\tmaxArea = area\n\t\t\t}\n\t\t}\n\t}\n\n\treturn maxArea\n}", "func maxSlidingWindow(nums []int, k int) []int {\n\n\treturn nums\n}", "func findMaxLength(nums []int) int {\n\tm := map[int]int{} //key is count, value is index\n\n\tvar count, maxVal int\n\tm[0] = -1\n\tfor i, num := range nums {\n\t\tif num == 0 {\n\t\t\tcount--\n\t\t} else {\n\t\t\tcount++\n\t\t}\n\t\tidx, ok := m[count]\n\t\tif ok {\n\t\t\tmaxVal = max(maxVal, i-idx)\n\t\t} else {\n\t\t\tm[count] = i\n\t\t}\n\t}\n\n\treturn maxVal\n}", "func Max(x, y int) int {\n\tif x < y {\n\t\treturn y\n\t}\n\treturn x\n}", "func Max(x, y int) int {\n\tif y > x {\n\t\treturn y\n\t}\n\treturn x\n}", "func maxSideLength(mat [][]int, threshold int) int {\n\t// acc[i][j]: the accumulated sum right and bottom of point (i, j)\n\tm, n := len(mat), len(mat[0])\n acc := make([][]int, m+1)\n for i := range acc {\n \tacc[i] = make([]int, n+1)\n\t}\n\tfor i:=m-1; i>=0; i-- {\n\t\tfor j:=n-1; j>=0; j-- {\n\t\t\tacc[i][j] = mat[i][j]+acc[i+1][j]+acc[i][j+1]-acc[i+1][j+1]\n\t\t}\n\t}\n\t// binary search for low=0 and high=min(m,n). for each mid,\n\t// check if there exists one square with side length <= threshold\n\t// time is m*n*log(min(m,n))\n\tlo, hi := 1, m+1\n\tif m>n {\n\t\thi = n+1\n\t}\n\tfor lo<hi {\n\t\tmid := (lo+hi)/2\n\t\texist := false\n\t\touter: for i:=0; i+mid<=m; i++ {\n\t\t\tfor j:=0; j+mid<=n; j++ {\n\t\t\t\tarea := acc[i][j]-acc[i+mid][j]-acc[i][j+mid]+acc[i+mid][j+mid]\n\t\t\t\tif area<=threshold {\n\t\t\t\t\texist = true\n\t\t\t\t\tbreak outer\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// we want the max value of that CAN. so we search the first CAN'T. the candidate is 1 to n,\n\t\t// so we let lo=1, hi=n+1. the loop end with lo=hi with first that CAN'T. so lo-1 is max value that CAN.\n\t\tif exist {\n\t\t\tlo = mid+1\n\t\t} else {\n\t\t\thi = mid\n\t\t}\n\t}\n\treturn lo-1\n}", "func findLargestNumber(args ...int) int {\n\tnumber := args[0]\n\n\tfor _, value := range args {\n\t\tif value > number {\n\t\t\tnumber = value\n\t\t}\n\t}\n\treturn number\n}", "func Solution(C []int, k int) int {\n\tn := len(C) + 1\n\tdp := make([][]int, n)\n\tfor i := range dp {\n\t\tdp[i] = make([]int, k+1)\n\t}\n\n\tfor i := 0; i < n; i++ {\n\t\tdp[i][0] = 0\n\t}\n\n\tfor i := 1; i <= k; i++ {\n\t\tdp[0][i] = math.MaxInt64\n\t}\n\n\tfor i := 1; i < n; i++ {\n\t\tfor j := 1; j <= k; j++ {\n\t\t\tCmax := C[0]\n\t\t\tfor idx := 0; idx < i; idx++ {\n\t\t\t\tif C[idx] > j {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tCmax = C[idx]\n\t\t\t}\n\n\t\t\tdpij1 := dp[i][j-Cmax] + 1\n\t\t\tdpij2 := dp[i-1][j]\n\t\t\tif dpij1 <= dpij2 {\n\t\t\t\tdp[i][j] = dpij1\n\t\t\t} else {\n\t\t\t\tdp[i][j] = dpij2\n\t\t\t}\n\t\t}\n\t}\n\n\t//printDp(dp)\n\n\treturn dp[n-1][k]\n}", "func Max(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func Max(x, y int) int {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func getMaxLen(nums []int) int {\n\tmaxlen := 0\n\ts := -1\n\tfn, ln, negs := -1, -1, 0\n\tfor i:=0; i<=len(nums); i++ {\n\t\t// add zero at end to trigger final compute\n\t\tv := 0\n\t\tif i<len(nums) {\n\t\t\tv = nums[i]\n\t\t}\n\n\t\t// find an interval\n\t\tif v==0 { \n\t\t\tif i-s > 1 { // non-empty interval\n\t\t\t\tif negs%2==0 { // even negs, whole interval is ok\n\t\t\t\t\tmaxlen = max(maxlen, i-s-1)\n\t\t\t\t} else {\n\t\t\t\t\tmaxlen = max(maxlen, max(ln-s-1, i-fn-1))\n\t\t\t\t}\n\t\t\t}\n\t\t\tfn, ln, s = i, i, i\n\t\t\tnegs = 0\n\t\t}\n\n\t\t// find a value\n\t\tif v < 0 {\n\t\t\tnegs++\n\t\t\tif fn==s {\n\t\t\t\tfn = i\n\t\t\t}\n\t\t\tln = i\n\t\t}\n\t\t// if v > 0, do nothing\n\t}\n return maxlen\n}", "func findMax(vals []float64) float64 {\n\tmax := float64(vals[0])\n\tfor v := range vals {\n\t\tif vals[v] > max {\n\t\t\tmax = vals[v]\n\t\t}\n\t}\n\treturn float64(max)\n}", "func Max(x, y int64) int64 {\n\tif x > y {\n\t\treturn x\n\t}\n\treturn y\n}", "func Max(x int, y int) int {\n\tif x > y { return x }\n\treturn y\n}", "func Mimax(nums ...int) (int, int) {\n\tmin, max := nums[0], nums[0]\n\n\tfor _, num := range nums {\n\t\tif min > num {\n\t\t\tmin = num\n\t\t}\n\n\t\tif max < num {\n\t\t\tmax = num\n\t\t}\n\t}\n\n\treturn min, max\n}", "func (f *fragment) max(filter *Row, bitDepth uint) (max int64, count uint64, err error) {\n\tconsider := f.row(bsiExistsBit)\n\tif filter != nil {\n\t\tconsider = consider.Intersect(filter)\n\t}\n\n\t// If there are no columns to consider, return early.\n\tif !consider.Any() {\n\t\treturn 0, 0, nil\n\t}\n\n\t// Find lowest negative number w/o sign and negate, if no positives are available.\n\tpos := consider.Difference(f.row(bsiSignBit))\n\tif !pos.Any() {\n\t\tmax, count = f.minUnsigned(consider, bitDepth)\n\t\treturn -max, count, nil\n\t}\n\n\t// Otherwise find highest positive number.\n\tmax, count = f.maxUnsigned(pos, bitDepth)\n\treturn max, count, nil\n}", "func findCenter(edges [][]int) int {\n\tnumberMap, l := make(map[int]int), len(edges)\n\tfor _, edge := range edges {\n\t\tnumberMap[edge[0]]++\n\t\tnumberMap[edge[1]]++\n\t}\n\tfor key, value := range numberMap {\n\t\tif value == l {\n\t\t\treturn key\n\t\t}\n\t}\n\treturn -1\n}", "func max(x int) int {\n\treturn 40 + x\n}", "func main() {\n\n\thittable := make(map[int]bool)\n\tans := int64(0)\n\n\tfor i := 1; i*i <= top*9*9; i++ {\n\t\thittable[i*i] = true\n\t}\n\n\tfor i := range hittable {\n\t\tways, _ := enumerate(9, top, i)\n\t\tfor i := 0; i < len(ways); i++ {\n\t\t\tans += process(ways[i])\n\t\t\tans %= mod\n\t\t}\n\t}\n\n\tfmt.Println(\"171/ Find the last nine digits of the sum of all n, 0 < n < 10^20, such that f(n) is a perfect square\")\n\tfmt.Println(ans)\n}", "func main() {\n\tmountain = [5][5]int{\n\t\t{1, 2, 3, 4, 5},\n\t\t{16, 17, 18, 19, 6},\n\t\t{15, 24, 25, 20, 7},\n\t\t{14, 23, 22, 21, 8},\n\t\t{13, 12, 11, 10, 9},\n\t}\n\tmax := 0\n\n\tfor i := 0; i < 5; i++ {\n\t\tfor j := 0; j < 5; j++ {\n\t\t\tpath[i][j] = dfs(i, j) + 1\n\t\t\tif path[i][j] >= max {\n\t\t\t\tmax = path[i][j]\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Printf(\"the longest path size is %d %v\\n\", max, path)\n\n}", "func Max(i, j int) int {\n\tif i > j {\n\t\treturn i\n\t}\n\treturn j\n}", "func findMaxPosition(data []int) int {\n\tif len(data) == 0 {\n\t\treturn -1\n\t}\n\tvar position int\n\tmax := data[0]\n\n\tfor index := 0; index < len(data); index++ {\n\t\tif data[index] > max {\n\t\t\tmax = data[index]\n\t\t\tposition = index\n\t\t}\n\t}\n\treturn position\n}", "func Max(x, y int64) int64 {\n\treturn x ^ ((x ^ y) & ((x - y) >> 63))\n}", "func numIslands(grid [][]byte) int {\n\tx := len(grid)\n\tif x == 0 {\n\t\treturn 0\n\t}\n\ty := len(grid[0])\n\tcount := 0\n\tfor i := 0; i < x; i++ {\n\t\tfor j := 0; j < y; j++ {\n\t\t\tif grid[i][j] == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmarkIsland(grid, i, j, func(i, j int) bool {\n\t\t\t\tif i < 0 || j < 0 || i >= x || j >= y || grid[i][j] == 0 {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t})\n\t\t\tcount += 1\n\t\t}\n\t}\n\treturn count\n}", "func maximize() int64 {\n\tmax := 0\n\tmaxItem := int64(0)\n\t// var cache Cache\n\n\t// The larger the cache, the faster it is. Even without a\n\t// cache, it's only around a second on a modern machine, so\n\t// not that big of a deal.\n\t// cache.init(10000)\n\n\tfor x := int64(1); x < 1000000; x++ {\n\t\tcount := collatz2(x)\n\t\t// count := cache.chainLen(x)\n\t\tif count > max {\n\t\t\tmax = count\n\t\t\tmaxItem = x\n\t\t}\n\t}\n\tfmt.Printf(\"%d, %d\\n\", maxItem, max)\n\treturn maxItem\n}", "func rmax(data ArrType) float64 {\r\n\tvar i, idxCari, idxMax int\r\n\ti = 0\r\n\tidxCari = 1\r\n\tidxMax = 0\r\n\tfor i < N-1 { // N-1 karena idxCari = i + 1 sehingga data terakhir masih diperhitungkan\r\n\t\tif data[idxCari].f3 > data[idxMax].f3 {\r\n\t\t\tidxMax = idxCari\r\n\t\t}\r\n\t\tidxCari++\r\n\t\ti++\r\n\t}\r\n\treturn data[idxMax].f3\r\n}", "func findBiggest(numbers ...int) int {\n\tvar biggest int\n\t//iterate over numbers\n\tfor _, v := range numbers {\n\t\tif v > biggest {\n\t\t\tbiggest = v\n\t\t}\n\t}\n\n\treturn biggest\n}", "func MaximalRectangle(matrix [][]byte) int {\n type point struct {\n i, j int\n }\n // re map right bottom point to left top point for all rectangles which contain only \"1\"\n re := make(map[point]map[point]bool)\n var maxArea, area int\n for i := range matrix {\n for j := range matrix[i] {\n if matrix[i][j] == '0' {\n continue\n }\n re[point{i,j}] = map[point]bool{point{i,j}: true}\n if maxArea == 0 {\n maxArea = 1\n }\n\n if i > 0 {\n jLeftTop := j-1\n for jLeftTop >= 0 && matrix[i][jLeftTop] == '1' {\n jLeftTop--\n }\n m, exist := re[point{i-1, j}]\n if exist {\n for p := range m {\n if p.j > jLeftTop {\n re[point{i, j}][p] = true\n area = (i-p.i+1) * (j-p.j+1)\n if area > maxArea {\n maxArea = area\n }\n }\n }\n }\n }\n\n if j > 0 {\n iLeftTop := i-1\n for iLeftTop >= 0 && matrix[iLeftTop][j] == '1' {\n iLeftTop--\n }\n m, exist := re[point{i, j-1}]\n if exist {\n for p := range m {\n if p.i > iLeftTop {\n re[point{i, j}][p] = true\n area = (i-p.i+1) * (j-p.j+1)\n if area > maxArea {\n maxArea = area\n }\n }\n }\n }\n }\n }\n }\n\n return maxArea\n}", "func max(a, b int32) int32 {\n\tif a >= b {\n\t\treturn a\n\t}\n\treturn b\n}", "func lastPersonDistances(numStalls, numPeople uint64) (min uint64, max uint64) {\n\tb := newBathroom(numStalls)\n\n\tvar placed uint64\n\tfor numPeople > placed {\n\t\tvar count uint64\n\t\tmin, max, count = b.addPeople()\n\t\tplaced += count\n\t}\n\n\treturn min, max\n}", "func largestRectangleArea(heights []int) int {\n\theiList := []int{} // save height with grow\n\theiLengthList := []int{} // save line length with height\n\tmax := 0\n\tfor i, currHei := range heights {\n\t\tj := len(heiList) - 1\n\t\tcurrPos := i\n\t\tfor ; j >= 0; j-- {\n\t\t\t// if current height larger than the tail of heiList,remove it\n\t\t\tif heiList[j] >= currHei {\n\t\t\t\tarea := (i - heiLengthList[j]) * heiList[j]\n\t\t\t\tif area > max {\n\t\t\t\t\tmax = area\n\t\t\t\t}\n\t\t\t\tcurrPos = heiLengthList[j]\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\theiList = append(heiList[:j+1], currHei)\n\t\theiLengthList = append(heiLengthList[:j+1], currPos)\n\t}\n\tfor j := len(heiList) - 1; j >= 0; j-- {\n\t\tarea := (len(heights) - heiLengthList[j]) * heiList[j]\n\t\tif area > max {\n\t\t\tmax = area\n\t\t}\n\t}\n\treturn max\n}", "func maxSubArray(nums []int) int {\n\tstMax := -1\n\tvar max int\n\t// var endMax int\n\tfor st := 0; st < len(nums); st++ {\n\t\tsum := 0\n\t\tfor end := st; end < len(nums); end++ {\n\t\t\tsum += nums[end]\n\t\t\tif (stMax < 0) || (sum > max) {\n\t\t\t\tmax = sum\n\t\t\t\tstMax = st\n\t\t\t\t// end_max = end\n\t\t\t}\n\t\t}\n\t}\n\treturn max\n}", "func maxI(a int, b int) (res int) {\n\tif a < b {\n\t\tres = b\n\t} else {\n\t\tres = a\n\t}\n\n\treturn\n}", "func Solution(A []int) int {\n\t// write your code in Go 1.4\n\tvar peakIndex []int\n\t// var currentFlags int\n\tfor i, val := range A {\n\t\tif i == 0 || i == len(A)-1 {\n\t\t\tcontinue\n\t\t} else if val > A[i-1] && val > A[i+1] {\n\t\t\tfmt.Printf(\"masuk sini val %v\\n\", val)\n\t\t\tpeakIndex = append(peakIndex, i)\n\t\t}\n\t}\n\tk := len(peakIndex)\n\tif k == 0 {\n\t\treturn 0\n\t}\n\tfmt.Printf(\"peakIndex %v\\n\", peakIndex)\n\treturn k\n}", "func largestOpenInterval(intervals []Interval) Interval {\n\tresult := Interval{}\n\tif len(intervals) <= 1 {\n\t\treturn result\n\t}\n\n\tmaxTime := 0\n\tfor i := 1; i < len(intervals); i++ {\n\t\ttime := intervals[i].Start - intervals[i-1].End\n\t\tif time > maxTime {\n\t\t\tmaxTime = time\n\t\t\tresult.Start = intervals[i-1].End\n\t\t\tresult.End = intervals[i].Start\n\t\t}\n\t}\n\n\treturn result\n}", "func max(a, b int) int {\nif a < b {\nreturn b\n}\nreturn a\n}", "func MinimizeStops() int {\n\ttopography := parseMap()\n\tresult := 1\n\tfor _, angle := range [][2]int{{1, 1}, {3, 1}, {5, 1}, {7, 1}, {1, 2}} {\n\t\tresult *= topography.countTrees(angle[0], angle[1])\n\t}\n\treturn result\n}", "func thirdMax(nums []int) int {\n\tconst min = math.MinInt32-1\n\tfl,sl,tl := min,min,min\n\tfor _, v := range nums{\n\t\tif v>fl{\n\t\t\ttl=sl\n\t\t\tsl=fl\n\t\t\tfl=v\n\t\t} else if v>sl && v !=fl {\n\t\t\ttl=sl\n\t\t\tsl=v\n\t\t} else if v>tl && v !=sl && v!=fl {\n\t\t\ttl=v\n\t\t}\n\n\t}\n\tif tl== min{\n\t\treturn fl\n\t}\n\treturn tl\n}", "func Imax(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Imax(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}" ]
[ "0.66160476", "0.64744246", "0.618712", "0.61700565", "0.6037497", "0.5992314", "0.59851134", "0.59376025", "0.5864505", "0.5848303", "0.5829246", "0.5827219", "0.5810036", "0.5801721", "0.579599", "0.57703656", "0.57446194", "0.5703196", "0.57013416", "0.56909364", "0.56879175", "0.5681232", "0.567605", "0.56479347", "0.56289786", "0.5623089", "0.5620345", "0.5615831", "0.5612873", "0.5612873", "0.5612873", "0.5612873", "0.5612873", "0.55996966", "0.5596071", "0.5590753", "0.55866617", "0.55866235", "0.55814064", "0.5576806", "0.55712825", "0.55621094", "0.55552346", "0.55529076", "0.55514705", "0.5535398", "0.5530651", "0.55230564", "0.5519421", "0.5516746", "0.55153465", "0.551249", "0.55083853", "0.5504014", "0.55038786", "0.54935753", "0.54919267", "0.5486102", "0.54820377", "0.548072", "0.54793394", "0.5451168", "0.54459256", "0.54155886", "0.53969055", "0.53963274", "0.53925294", "0.5388972", "0.5381886", "0.5380906", "0.5380906", "0.5379438", "0.5377224", "0.53705865", "0.53584313", "0.53581846", "0.5358145", "0.53537625", "0.53537476", "0.53521377", "0.5349576", "0.53494143", "0.53485996", "0.53264964", "0.5323446", "0.5306227", "0.5292065", "0.52822655", "0.5279909", "0.527761", "0.5267588", "0.5266989", "0.52663356", "0.52656305", "0.52617174", "0.52574027", "0.52572197", "0.52569926", "0.52515006", "0.5249731", "0.5249731" ]
0.0
-1
create a master node and initialize its channels
func NewMaster() *Master { m := &Master{ subMap: map[string]*Submission{}, jobChan: make(chan *WorkerJob, 0), NodeHandles: map[string]*NodeHandle{}} http.Handle("/master/", websocket.Handler(func(ws *websocket.Conn) { m.Listen(ws) })) return m }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewMasterNode() *MasterNode {\n\tcurrentNode := MasterNode{}\n\tcurrentNode.Slaves = make(map[*websocket.Conn]bool)\n\tcurrentNode.broadcast = make(chan []byte)\n\treturn &currentNode\n}", "func (n *MasterNode) StartMasterNode(host string, port int) {\n\t// Configure websocket route\n\thttp.HandleFunc(\"/ws\", n.handleConnections)\n\n\t// Start listening for incoming chat messages\n\tgo n.readInputCommands()\n\tgo n.broadcastCommandsToRun()\n\n\t// Start the server on localhost port 8000 and log any errors\n\taddress := fmt.Sprintf(\"%s:%d\", host, port)\n\terr := http.ListenAndServe(address, nil)\n\tif err != nil {\n\t\tlog.Fatal(\"Stopped Server: \", err)\n\t}\n}", "func newNode(ready chan struct{}) {\n\t// Create & start node\n\tnode = nm.NewNodeDefault(config)\n\tnode.Start()\n\n\ttime.Sleep(time.Second)\n\n\tready <- struct{}{}\n\n\t// Sleep forever\n\tch := make(chan struct{})\n\t<-ch\n}", "func (s *RedisSystem) NewMaster(server string) {\n\tlogInfo(\"setting new master: %s\", server)\n\ts.currentMaster = NewRedisShim(server)\n}", "func InitMasterClusterComm(_routeHandlerMap RouteHandlerMap) {\n\trouteHandlerMap = _routeHandlerMap\n\n\t// Setup router\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"/KillAll\", killAllRoute).Methods(\"GET\")\n\trouter.HandleFunc(\"/CreateNode\", createNodeRoute).Methods(\"GET\")\n\trouter.HandleFunc(\"/Send\", sendRoute).Methods(\"GET\")\n\trouter.HandleFunc(\"/Receive\", receiveRoute).Methods(\"GET\")\n\trouter.HandleFunc(\"/ReceiveAll\", receiveAllRoute).Methods(\"GET\")\n\trouter.HandleFunc(\"/BeginSnapshot\", beginSnapshotRoute).Methods(\"GET\")\n\trouter.HandleFunc(\"/CollectState\", collectStateRoute).Methods(\"GET\")\n\trouter.HandleFunc(\"/PrintSnapshot\", printSnapshotRoute).Methods(\"GET\")\n\n\t// Starting Cluster Server\n\t// fmt.Println(\"\\nStarting Cluster Server @ http://localhost:8118\")\n\tif err := http.ListenAndServe(\":8118\", router); err != nil {\n\t\t// fmt.Printf(\"\\nmux server: %v\\n\", err)\n\t}\n}", "func init() {\n\tconfig = tendermint_test.ResetConfig(\"rpc_test_client_test\")\n\tchainID = config.GetString(\"chain_id\")\n\trpcAddr = config.GetString(\"rpc_laddr\")\n\tgrpcAddr = config.GetString(\"grpc_laddr\")\n\trequestAddr = rpcAddr\n\twebsocketAddr = rpcAddr\n\twebsocketEndpoint = \"/websocket\"\n\n\tclientURI = client.NewClientURI(requestAddr)\n\tclientJSON = client.NewClientJSONRPC(requestAddr)\n\tclientGRPC = core_grpc.StartGRPCClient(grpcAddr)\n\n\t// TODO: change consensus/state.go timeouts to be shorter\n\n\t// start a node\n\tready := make(chan struct{})\n\tgo newNode(ready)\n\t<-ready\n}", "func newChannelNode(t *testing.T) *testNode {\n\tch, err := tchannel.NewChannel(\"test\", nil)\n\trequire.NoError(t, err, \"channel must create successfully\")\n\n\t// Set the channel listening so it binds to the socket and we get a port\n\t// allocated by the OS\n\terr = ch.ListenAndServe(\"127.0.0.1:0\")\n\trequire.NoError(t, err, \"channel must listen\")\n\n\thostport := ch.PeerInfo().HostPort\n\tc := clock.NewMock()\n\tnode := NewNode(\"test\", hostport, ch.GetSubChannel(\"test\"), &Options{\n\t\tClock: c,\n\t})\n\n\treturn &testNode{node, ch, c}\n}", "func New(commandArgs common.CommandArgs) *Node {\n\n\tnode := Node{\n\t\tNodeCommon: common.NewNodeCommon(commandArgs, \"master\"),\n\t\t// FirstSlaveListenPort: 7500, // TODO(greg) make this an env parameter /TODO this is the *base* port that the new slave should try. incrementing if failing to get the port\n\t}\n\n\treturn &node\n}", "func masterMain(ln net.Listener) {\n\tm := &Master{}\n\tm.startTime = time.Now()\n\tm.lastInput = time.Now()\n\tm.suppressions = newPersistentSet(filepath.Join(*flagWorkdir, \"suppressions\"))\n\tm.crashers = newPersistentSet(filepath.Join(*flagWorkdir, \"crashers\"))\n\tm.corpus = newPersistentSet(filepath.Join(*flagWorkdir, \"corpus\"))\n\tif len(m.corpus.m) == 0 {\n\t\tm.corpus.add(Artifact{[]byte{}, 0, false})\n\t}\n\n\tm.slaves = make(map[int]*MasterSlave)\n\tgo masterLoop(m)\n\n\ts := rpc.NewServer()\n\ts.Register(m)\n\ts.Accept(ln)\n}", "func main() {\n\ts := master.New()\n\tif err := s.Run(port); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (s *Service) bootstrapMaster(ctx context.Context, runner Runner, config Config, bsCfg BootstrapConfig) {\n\t// Check HTTP server port\n\tcontainerHTTPPort, _, err := s.getHTTPServerPort()\n\tif err != nil {\n\t\ts.log.Fatal().Err(err).Msg(\"Cannot find HTTP server info\")\n\t}\n\tif !WaitUntilPortAvailable(config.BindAddress, containerHTTPPort, time.Second*5) {\n\t\ts.log.Fatal().Msgf(\"Port %d is already in use\", containerHTTPPort)\n\t}\n\n\t// Select storage engine\n\tstorageEngine := bsCfg.ServerStorageEngine\n\tif storageEngine == \"\" {\n\t\tstorageEngine = s.DatabaseFeatures().DefaultStorageEngine()\n\t\tbsCfg.ServerStorageEngine = storageEngine\n\t}\n\ts.log.Info().Msgf(\"Using storage engine '%s'\", bsCfg.ServerStorageEngine)\n\n\t// Create initial cluster configuration\n\thasAgent := boolFromRef(bsCfg.StartAgent, !s.mode.IsSingleMode())\n\thasDBServer := boolFromRef(bsCfg.StartDBserver, true)\n\thasCoordinator := boolFromRef(bsCfg.StartCoordinator, true)\n\thasResilientSingle := boolFromRef(bsCfg.StartResilientSingle, s.mode.IsActiveFailoverMode())\n\thasSyncMaster := boolFromRef(bsCfg.StartSyncMaster, true) && config.SyncEnabled\n\thasSyncWorker := boolFromRef(bsCfg.StartSyncWorker, true) && config.SyncEnabled\n\tme := NewPeer(s.id, config.OwnAddress, s.announcePort, 0, config.DataDir,\n\t\thasAgent, hasDBServer, hasCoordinator, hasResilientSingle,\n\t\thasSyncMaster, hasSyncWorker, s.IsSecure())\n\ts.myPeers.Initialize(me, bsCfg.AgencySize, storageEngine, s.cfg.Configuration.PersistentOptions)\n\ts.learnOwnAddress = config.OwnAddress == \"\"\n\n\t// Start HTTP listener\n\ts.startHTTPServer(config)\n\n\t// Permanent loop:\n\ts.log.Info().Msgf(\"Serving as master with ID '%s' on %s:%d...\", s.id, config.OwnAddress, s.announcePort)\n\n\t// Can we start right away?\n\tneedMorePeers := true\n\tif s.mode.IsSingleMode() {\n\t\tneedMorePeers = false\n\t} else if !s.myPeers.HaveEnoughAgents() {\n\t\tneedMorePeers = true\n\t} else if bsCfg.StartLocalSlaves {\n\t\tpeersNeeded := bsCfg.PeersNeeded()\n\t\tneedMorePeers = len(s.myPeers.AllPeers) < peersNeeded\n\t}\n\tif !needMorePeers {\n\t\t// We have all the agents that we need, start a single server/cluster right now\n\t\ts.saveSetup()\n\t\ts.log.Info().Msg(\"Starting service...\")\n\t\ts.startRunning(runner, config, bsCfg)\n\t\treturn\n\t}\n\n\twg := sync.WaitGroup{}\n\tif bsCfg.StartLocalSlaves {\n\t\t// Start additional local slaves\n\t\ts.createAndStartLocalSlaves(&wg, config, bsCfg)\n\t} else {\n\t\t// Show commands needed to start slaves\n\t\ts.log.Info().Msgf(\"Waiting for %d servers to show up.\\n\", s.myPeers.AgencySize)\n\t\ts.showSlaveStartCommands(runner, config)\n\t}\n\n\tfor {\n\t\ttime.Sleep(time.Second)\n\t\tselect {\n\t\tcase <-s.bootstrapCompleted.ctx.Done():\n\t\t\ts.saveSetup()\n\t\t\ts.log.Info().Msg(\"Starting service...\")\n\t\t\ts.startRunning(runner, config, bsCfg)\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t\tif ctx.Err() != nil {\n\t\t\t// Context is cancelled, stop now\n\t\t\tbreak\n\t\t}\n\t}\n\t// Wait for any local slaves to return.\n\twg.Wait()\n}", "func newMaster(name, binDir, rootDir string, loggers []Logger) *Master {\n\treturn &Master{\n\t\tprocBase: newProcBase(name, join(binDir, \"master\"), genLocalAddr(), loggers),\n\t\tmasterRoot: join(rootDir, name),\n\t\traftRoot: join(rootDir, name, \"raft\"),\n\t}\n}", "func MakeMaster(files []string, nReduce int) *Master {\n\tm := Master{}\n\n\t// Your code here.\n\tm.mu = sync.Mutex{}\n\tm.nReduce = nReduce\n\tm.files = files\n\t\n\tif nReduce > len(files) {\n\t\tm.taskCh = make(chan Task, nReduce)\n\t} else {\n\t\tm.taskCh = make(chan Task, len(m.files))\n\t}\n\n\tm.initMapTasks()\n\tgo m.tickSchedule()\n\n\tm.server()\n\tdisplay(\"master init...\")\n\treturn &m\n}", "func NewNodeHostWithMasterClientFactory(nhConfig config.NodeHostConfig,\n\tfactory MasterClientFactoryFunc) *NodeHost {\n\tlogBuildTagsAndVersion()\n\tif err := nhConfig.Validate(); err != nil {\n\t\tplog.Panicf(\"invalid nodehost config, %v\", err)\n\t}\n\tnh := &NodeHost{\n\t\tserverCtx: server.NewContext(nhConfig),\n\t\tnhConfig: nhConfig,\n\t\tstopper: syncutil.NewStopper(),\n\t\tduStopper: syncutil.NewStopper(),\n\t\tnodes: transport.NewNodes(streamConnections),\n\t\tinitializedC: make(chan struct{}),\n\t\ttransportLatency: newSample(),\n\t}\n\tnh.snapshotStatus = newSnapshotFeedback(nh.pushSnapshotStatus)\n\tnh.msgHandler = newNodeHostMessageHandler(nh)\n\tnh.clusterMu.requests = make(map[uint64]*server.MessageQueue)\n\tnh.createPools()\n\tnh.createTransport()\n\tif nhConfig.MasterMode() {\n\t\tplog.Infof(\"master servers specified, creating the master client\")\n\t\tnh.masterClient = newMasterClient(nh, factory)\n\t\tplog.Infof(\"master client type: %s\", nh.masterClient.Name())\n\t} else {\n\t\tplog.Infof(\"no master server specified, running in standalone mode\")\n\t\tdid := unmanagedDeploymentID\n\t\tif nhConfig.DeploymentID == 0 {\n\t\t\tplog.Warningf(\"DeploymentID not set in NodeHostConfig\")\n\t\t\tnh.transport.SetUnmanagedDeploymentID()\n\t\t} else {\n\t\t\tdid = nhConfig.DeploymentID\n\t\t\tnh.transport.SetDeploymentID(nhConfig.DeploymentID)\n\t\t}\n\t\tplog.Infof(\"DeploymentID set to %d\", unmanagedDeploymentID)\n\t\tnh.deploymentID = did\n\t\tnh.createLogDB(nhConfig, did)\n\t}\n\tctx, cancel := context.WithCancel(context.Background())\n\tnh.cancel = cancel\n\tinitializeFn := func() {\n\t\tif err := nh.initialize(ctx, nhConfig); err != nil {\n\t\t\tif err != context.Canceled && err != ErrCanceled {\n\t\t\t\tplog.Panicf(\"nh.initialize failed %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\tif nh.masterMode() {\n\t\tplog.Infof(\"master mode, nh.initialize() invoked in new goroutine\")\n\t\tnh.stopper.RunWorker(func() {\n\t\t\tinitializeFn()\n\t\t})\n\t} else {\n\t\tplog.Infof(\"standalone mode, nh.initialize() directly invoked\")\n\t\tinitializeFn()\n\t}\n\tnh.stopper.RunWorker(func() {\n\t\tnh.masterRequestHandler(ctx)\n\t})\n\t// info reporting worker is using a different stopper as we need to stop it\n\t// separately during monkey test\n\tnh.duStopper.RunWorker(func() {\n\t\tnh.reportingWorker(ctx)\n\t})\n\tnh.stopper.RunWorker(func() {\n\t\tnh.nodeMonitorMain(ctx, nhConfig)\n\t})\n\tnh.stopper.RunWorker(func() {\n\t\tnh.tickWorkerMain()\n\t})\n\tif nh.masterMode() {\n\t\tnh.waitUntilInitialized()\n\t}\n\tnh.logNodeHostDetails()\n\treturn nh\n}", "func Start() {\n\tIPs := DNS.GetAddr(Config.BootstrapDomainName)\n\tnodeContext = NC.NewNodeContext()\n\tnodeContext.SetLocalName(nameService.GetLocalName())\n\tnodeContext.LocalIp, _ = DNS.ExternalIP()\n\tmp = MP.NewMessagePasser(nodeContext.LocalName)\n\tstreamer = Streamer.NewStreamer(mp, nodeContext)\n\n\n\t// We use for loop to connect with all supernode one-by-one,\n\t// if a connection to one supernode fails, an error message\n\t// will be sent by messagePasser, and this message is further\n\t// processed in error handler.\n\t// init_fail: used in hello phase\n\t// exit: used when all supernode cannot be connected.\n\tmp.AddMappings([]string{\"exit\", \"init_fail\", \"super_fail\", \"ack\", \"loadtrack_result\"})\n\n\t// Initialize all the package structs\n\n\t// Define all the channel names and the binded functions\n\t// TODO: Register your channel name and binded eventhandlers here\n\t// The map goes as map[channelName][eventHandler]\n\t// All the messages with type channelName will be put in this channel by messagePasser\n\t// Then the binded handler of this channel will be called with the argument (*Message)\n\n\tchannelNames := map[string]func(*MP.Message){\n\t\t\"election_assign\": joinAssign,\n\t\t\"error\" : errorHandler,\n\n\t\t// The streaming related handlers goes here\n\t\t\"streaming_election\": streamer.HandleElection,\n\t\t\"streaming_join\": streamer.HandleJoin,\n\t\t\"streaming_data\": streamer.HandleStreamerData,\n\t\t\"streaming_stop\": streamer.HandleStop,\n\t\t\"streaming_assign\": streamer.HandleAssign,\n\t\t\"streaming_new_program\": streamer.HandleNewProgram,\n\t\t\"streaming_stop_program\": streamer.HandleStopProgram,\n\t\t\"streaming_quit\": streamer.HandleChildQuit,\n\t}\n\n\t// Init and listen\n\tfor channelName, handler := range channelNames {\n\t\t// Init all the channels listening on\n\t\tmp.Messages[channelName] = make(chan *MP.Message)\n\t\t// Bind all the functions listening on the channel\n\t\tgo listenOnChannel(channelName, handler)\n\t}\n\tgo nodeJoin(IPs)\n\tgo NodeCLIInterface(streamer)\n\twebInterface(streamer, nodeContext)\n\texitMsg := <- mp.Messages[\"exit\"]\n\tvar exitData string\n\tMP.DecodeData(&exitData, exitMsg.Data)\n\tfmt.Printf(\"Node: receiving force exit message [%s], node exit\\n\", exitData);\n}", "func createNode(id int, myConf *Config, sm *State_Machine) cluster.Server {\n\tinitNode(id, myConf, sm)\n\t//Set up details about cluster nodes form json file.\n\tserver, err := cluster.New(id, \"config/cluster_config.json\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn server\n}", "func MakeMaster(files []string, nReduce int) *Master {\r\n\tm := Master{}\r\n\r\n\t// Your code here.\r\n\tm.nextMapTaskNo = 1\r\n\tm.nextReduceTaskNo = 1\r\n\tm.inputFiles = make(chan string, 100)\r\n\tm.mapTasks = make(map[int]string)\r\n\tm.mapFinish = make(map[string]int)\r\n\tm.failedMapTaskNo = make(map[int]int)\r\n\tm.reduceTasks = make(map[int][]string)\r\n\tm.inputIntermediateFiles = make(chan []string, 100)\r\n\tm.done = make(chan bool)\r\n\tm.reduceFinish = make(map[int]bool)\r\n\tm.mapIntermediateFiles = make([][]string, 0)\r\n\tm.taskPhase = 0\r\n\tm.nReduce = nReduce\r\n\r\n\tfor _, file := range files {\r\n\t\tm.inputFiles <- file\r\n\t\tm.totalInputFiles++\r\n\t}\r\n\r\n\tm.server()\r\n\t// log.Println(\"-----Server Started------\")\r\n\treturn &m\r\n}", "func StartMaster(configFile *goconf.ConfigFile) {\n\tSubIOBufferSize(\"master\", configFile)\n\tGoMaxProc(\"master\", configFile)\n\tConBufferSize(\"master\", configFile)\n\tIOMOnitors(configFile)\n\n\thostname := GetRequiredString(configFile, \"default\", \"hostname\")\n\tpassword := GetRequiredString(configFile, \"default\", \"password\")\n\n\tm := NewMaster()\n\n\trest.Resource(\"jobs\", MasterJobController{m, password})\n\trest.Resource(\"nodes\", MasterNodeController{m, password})\n\n\trest.ResourceContentType(\"jobs\", \"application/json\")\n\trest.ResourceContentType(\"nodes\", \"application/json\")\n\n\tListenAndServeTLSorNot(hostname)\n}", "func NewMaster(addr string, port int, cert *services.HTTPCert) *Master {\n\tvar sm *services.HTTPService\n\n\tif cert == nil {\n\t\tsm = services.NewHTTPService(\"master\", addr, port, nil)\n\t} else {\n\t\tsm = services.NewHTTPSecureService(\"master\", addr, port, cert, nil)\n\t}\n\n\t// reg, err := sm.Select(\"register\")\n\t//\n\t// if err == nil {\n\t//\n\t// \treg.Terminal().Only(grids.ByPackets(func(g *grids.GridPacket) {\n\t// \t\tfmt.Println(\"/register receieves\", g)\n\t// \t}))\n\t// }\n\t//\n\t// disc, err := sm.Select(\"discover\")\n\t//\n\t// if err == nil {\n\t//\n\t// \tdisc.Terminal().Only(grids.ByPackets(func(g *grids.GridPacket) {\n\t// \t\tfmt.Println(\"/discover receieves\", g)\n\t// \t}))\n\t// }\n\t//\n\t// unreg, err := sm.Select(\"unregister\")\n\t//\n\t// if err == nil {\n\t//\n\t// \tunreg.Terminal().Only(grids.ByPackets(func(g *grids.GridPacket) {\n\t// \t\tfmt.Println(\"/unregister receieves\", g)\n\t// \t}))\n\t// }\n\n\treturn &Master{sm}\n}", "func newNode() *topicNode {\n\treturn &topicNode{\n\t\tchildren: children{},\n\t\tclients: make(clientOpts),\n\t\tshared: make(map[string]clientOpts),\n\t}\n}", "func NewMasterRouter() *MasterRouter {\n\tr := &MasterRouter{\n\t\tmessages: make(chan *routerpb.Message, 1),\n\t}\n\tgo func() {\n\t\tfor msg := range r.messages {\n\t\t\tfmt.Println(msg)\n\t\t}\n\t}()\n\treturn r\n}", "func main() {\n\tlog.LoadConfiguration(\"log.cfg\")\n\tlog.Info(\"Start Master\")\n\n\tcfg := loadMasterConfiguration()\n\n\tlog.Info(\"Setting go cpu number to \", cfg.Constants.CpuNumber, \" success: \", runtime.GOMAXPROCS(cfg.Constants.CpuNumber))\n\n\t// Start rest api server with tcp services for inserts and selects\n\tportNum := fmt.Sprintf(\":%d\", cfg.Ports.RestApi)\n\tvar server = restApi.Server{Port: portNum}\n\tchanReq := server.StartApi()\n\n\t// Initialize node manager\n\tlog.Info(\"Initialize node manager\")\n\tgo node.NodeManager.Manage()\n\tnodeBal := node.NewLoadBalancer(node.NodeManager.GetNodes())\n\tgo nodeBal.Balance(node.NodeManager.InfoChan)\n\n\t// Initialize reduce factory\n\tlog.Info(\"Initialize reduce factory\")\n\treduce.Initialize()\n\n\t// Initialize task manager (balancer)\n\tlog.Info(\"Initialize task manager\")\n\tgo task.TaskManager.Manage()\n\ttaskBal := task.NewBalancer(cfg.Constants.WorkersCount, cfg.Constants.JobForWorkerCount, nodeBal)\n\tgo taskBal.Balance(chanReq, cfg.Balancer.Timeout)\n\n\t// Initialize node listener\n\tlog.Info(\"Initialize node listener\")\n\tservice := fmt.Sprintf(\":%d\", cfg.Ports.NodeCommunication)\n\tlog.Debug(service)\n\tlist := node.NewListener(service)\n\tgo list.WaitForNodes(task.TaskManager.GetChan)\n\tdefer list.Close() // fire netListen.Close() when program ends\n\n\t// TODO: Wait for console instructions (q - quit for example)\n\t// Wait for some input end exit (only for now)\n\t//var i int\n\t//fmt.Scanf(\"%d\", &i)\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\t<-c\n\treturn\n}", "func init() {\n\t// This function will be executed before everything else.\n\t// Do some initialization here.\n\tSBC = data.NewBlockChain()\n\t// When server works\n\t// Peers = data.NewPeerList(Register(), 32)\n\t// While server doesn't work -> use port as id\n\tid, _ := strconv.ParseInt(os.Args[1], 10, 64)\n\tPeers = data.NewPeerList(int32(id), 32)\n\tifStarted = true\n}", "func initCluster() (_ *cluster, cbChan <-chan Callback) {\n cb := make(chan Callback)\n c := &cluster{\n nil,\n chan<- Callback(cb),\n make(map[Nid]*Node),\n make(map[Nid]*GossipNode),\n nil,\n sync.RWMutex{},\n }\n return c, (<-chan Callback)(cb)\n}", "func RegisterNodeToMaster(UID, nodehandler, nodeselector string) error {\n\tbody, err := GenerateNodeReqBody(UID, nodeselector)\n\tif err != nil {\n\t\tFatalf(\"Unmarshal body failed: %v\", err)\n\t\treturn err\n\t}\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{\n\t\tTransport: tr,\n\t}\n\n\tt := time.Now()\n\tnodebody, err := json.Marshal(body)\n\tif err != nil {\n\t\tFatalf(\"Marshal body failed: %v\", err)\n\t\treturn err\n\t}\n\tBodyBuf := bytes.NewReader(nodebody)\n\treq, err := http.NewRequest(http.MethodPost, nodehandler, BodyBuf)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tif err != nil {\n\t\tFatalf(\"Frame HTTP request failed: %v\", err)\n\t\treturn err\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tFatalf(\"Sending HTTP request failed: %v\", err)\n\t\treturn err\n\t}\n\tInfof(\"%s %s %v in %v\", req.Method, req.URL, resp.Status, time.Since(t))\n\tdefer resp.Body.Close()\n\n\tgomega.Expect(resp.StatusCode).Should(gomega.Equal(http.StatusCreated))\n\treturn nil\n}", "func createNodeDiscovery(c *SwarmContext) discovery.Backend {\n // we're to go through BeaconManger directly\n err := c.discoveryBack.Initialize(\"pc-beacon\", c.heartbeat, 0, getDiscoveryOpt(c))\n if err != nil {\n log.Fatal(err)\n }\n return c.discoveryBack\n}", "func (zk *ZookeeperMaster) Register() error {\n\tif err := zk.createSelfNode(); err != nil {\n\t\treturn err\n\t}\n\t//create event loop for master flag\n\tgo zk.masterLoop()\n\tgo zk.healthLoop()\n\treturn nil\n\n}", "func (self *RRSMNode) Build(addr string, initState RRSMState, configuration *RRSMConfig,\n\tRPCListenPort string, electionTimeout time.Duration, heartbeatInterval time.Duration) error {\n\tself.InitState = initState\n\tself.CurrentState = initState\n\tself.nodes = make(map[string]*rpc.RPCClient)\n\tself.addr = addr\n\n\t// init timer\n\tself.electionTimeoutTicker = nil\n\tself.electionTimeout = electionTimeout\n\tself.heartbeatTimeTicker = nil\n\tself.heartbeatInterval = heartbeatInterval\n\n\t// become a follower at the beginning\n\tself.character = RaftFOLLOWER\n\tself.currentTerm = uint64(0)\n\tself.haveVoted = false\n\n\t// init channels\n\tself.newTermChan = make(chan int, 1)\n\tself.accessLeaderChan = make(chan int, 1)\n\n\t// init lock\n\tself.termChangingLock = &sync.Mutex{}\n\tself.leaderChangingLock = &sync.Mutex{}\n\n\t// init node configuration\n\tif configuration == nil {\n\t\treturn fmt.Errorf(\"configuration is needed!\")\n\t}\n\tif len(configuration.Nodes) <= 0 {\n\t\treturn fmt.Errorf(\"config err: amounts of nodes needed to be a positive number!\")\n\t}\n\tself.config = *configuration\n\tself.amountsOfNodes = uint32(len(self.config.Nodes))\n\n\t// register rpc service\n\traftRPC := RaftRPC{\n\t\tnode: self,\n\t}\n\terr := rpc.RPCRegister(RPCListenPort, &raftRPC)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// build rpc connection with other nodes\n\tfor _, node := range self.config.Nodes {\n\t\tif node != addr {\n\t\t\tclient, err := rpc.RPCConnect(node)\n\t\t\tif err != nil {\n\t\t\t\t// need to connect with all the nodes at the period of building\n\t\t\t\treturn err\n\t\t\t} else {\n\t\t\t\tself.nodes[node] = client\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func main() {\n\t// init our channel new info listener\n\tinfo := make(chan string)\n\tgo printNewInfo(info)\n\t// open up listener\n\tlisten, err := net.Listen(\"tcp\", \"127.0.0.1:8001\")\n\tif err != nil {\n\t\t// fatal error starting up listener. Someone is occupying Port\n\t\tlog.Fatal(err)\n\t}\n\t// for loop while we haven't reached 5 nodes\n\tfor ; max_nodes > 0; max_nodes = max_nodes - 1 {\n\t\t// listen for new connection requests\n\t\tconn, err := listen.Accept()\n\n\t\tif err != nil {\n\t\t\t// not breaking error, that is a node side error\n\t\t\tfmt.Println(\"An error occured trying to accept new connection.\", err)\n\t\t}\n\n\t\t// node handler\n\t\tif _, ok := conn.RemoteAddr().(*net.TCPAddr); ok {\n\n\t\t\t// let's make the last node the leader (even if they aren't the closest)\n\t\t\tif max_nodes == 1 {\n\t\t\t\tleader = true\n\t\t\t}\n\n\t\t\tcheck := false\n\t\t\t// assign random ID\n\t\t\t// between 8002 and 8999\n\t\t\tvar ID int\n\t\t\tfor check == false {\n\n\t\t\t\tID = 8000 + rand.Intn(997) + 2\n\t\t\t\t// sanity check to see if someone has that ID\n\t\t\t\tln, err := net.Listen(\"tcp\", \"127.0.0.1:\"+strconv.Itoa(ID))\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tcheck = true\n\t\t\t\t_ = ln.Close()\n\t\t\t}\n\t\t\tnodeList[conn] = Node{ID: ID, Leader: false, Port: ID, Conn: conn}\n\t\t\tinfo <- \"Node: \" + strconv.Itoa(ID) + \" has joined\"\n\t\t\t// send the Node info to the node in question\n\t\t\tio.WriteString(conn, strconv.Itoa(ID) + \":\" + strconv.Itoa(ID) + \":\" + strconv.FormatBool(leader) + \"\\n\")\n\t\t\t// monitor the new connection in case it drops\n\t\t\tgo connectionCheck(conn, info, ID)\n\t\t}\n\n\t}\n\n\t// at this point we have gotten all 5 nodes on board\n\t// we now need to send an update to them\n\tfor conn, _ := range nodeList {\n\t\tgo sendInfo(conn)\n\t}\n\n\tvar empty int\n\tfmt.Scan(&empty)\n}", "func (server *Server) ConntectMaster(in *pb.ConnectionRequest, stream pb.Result_ConntectMasterServer) error {\n\n\tserver.addNewClient(in.Id, stream)\n\t// make the stream long lived\n\tfor {\n\t}\n\n}", "func (h *hub) start() error {\n\t// Start transport\n\tif err := h.transport.start(); err != nil {\n\t\treturn err\n\t}\n\n\t// Start hub channel listeners\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase client := <-h.registerc:\n\t\t\t\t// Handle register client request\n\t\t\t\th.registerClient(client)\n\t\t\tcase client := <-h.unregisterc:\n\t\t\t\t// Handle unregister client request\n\t\t\t\th.unregisterClient(client)\n\t\t\tcase msg := <-h.inboundc:\n\t\t\t\t// Handle message received from client\n\t\t\t\th.onClientMessage(msg)\n\t\t\tcase msg := <-h.peerc:\n\t\t\t\t// Handle message received from peer\n\t\t\t\th.onPeerMessage(msg)\n\t\t\tcase data := <-h.masterc:\n\t\t\t\t// Handle message received from master\n\t\t\t\th.onMasterMessage(data)\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn nil\n}", "func startNode(cfg *Config) error {\n\tapp, err := app.NewApplication(cfg.App())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttmcfg, nodeLogger, nodeKey, err := setupNode()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to setup config: %w\", err)\n\t}\n\n\tn, err := node.NewNode(tmcfg,\n\t\tprivval.LoadOrGenFilePV(tmcfg.PrivValidatorKeyFile(), tmcfg.PrivValidatorStateFile()),\n\t\tnodeKey,\n\t\tproxy.NewLocalClientCreator(app),\n\t\tnode.DefaultGenesisDocProviderFunc(tmcfg),\n\t\tnode.DefaultDBProvider,\n\t\tnode.DefaultMetricsProvider(tmcfg.Instrumentation),\n\t\tnodeLogger,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn n.Start()\n}", "func (instance *DBSyncSlave) init() {\n\tif nil != instance {\n\t\tif len(instance.Config.Uuid) > 0 {\n\t\t\tinstance.UID = instance.Config.Uuid\n\t\t} else {\n\t\t\tinstance.UID, _ = lygo_sys.ID()\n\t\t}\n\t\tif nil == instance.client {\n\t\t\tinstance.client = lygo_nio.NewNioClient(instance.Config.Host(), instance.Config.Port())\n\t\t\tinstance.client.OnConnect(instance.doConnect)\n\t\t\tinstance.client.OnDisconnect(instance.doDisconnect)\n\t\t}\n\t}\n}", "func (node *DataNode) Init() error {\n\tctx := context.Background()\n\n\treq := &datapb.RegisterNodeRequest{\n\t\tBase: &commonpb.MsgBase{\n\t\t\tSourceID: node.NodeID,\n\t\t},\n\t\tAddress: &commonpb.Address{\n\t\t\tIp: Params.IP,\n\t\t\tPort: int64(Params.Port),\n\t\t},\n\t}\n\n\tresp, err := node.dataService.RegisterNode(ctx, req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Register node failed: %v\", err)\n\t}\n\tif resp.Status.ErrorCode != commonpb.ErrorCode_Success {\n\t\treturn fmt.Errorf(\"Receive error when registering data node, msg: %s\", resp.Status.Reason)\n\t}\n\n\tselect {\n\tcase <-time.After(RPCConnectionTimeout):\n\t\treturn errors.New(\"Get DmChannels failed in 30 seconds\")\n\tcase <-node.watchDm:\n\t\tlog.Debug(\"insert channel names set\")\n\t}\n\n\tfor _, kv := range resp.InitParams.StartParams {\n\t\tswitch kv.Key {\n\t\tcase \"DDChannelName\":\n\t\t\tParams.DDChannelNames = []string{kv.Value}\n\t\tcase \"SegmentStatisticsChannelName\":\n\t\t\tParams.SegmentStatisticsChannelName = kv.Value\n\t\tcase \"TimeTickChannelName\":\n\t\t\tParams.TimeTickChannelName = kv.Value\n\t\tcase \"CompleteFlushChannelName\":\n\t\t\tParams.CompleteFlushChannelName = kv.Value\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"Invalid key: %v\", kv.Key)\n\t\t}\n\t}\n\n\treplica := newReplica()\n\n\tvar alloc allocatorInterface = newAllocator(node.masterService)\n\n\tchanSize := 100\n\tflushChan := make(chan *flushMsg, chanSize)\n\tnode.flushChan = flushChan\n\tnode.dataSyncService = newDataSyncService(node.ctx, flushChan, replica, alloc, node.msFactory)\n\tnode.dataSyncService.init()\n\tnode.metaService = newMetaService(node.ctx, replica, node.masterService)\n\tnode.replica = replica\n\n\treturn nil\n}", "func MakeMaster(files []string, nReduce int) *Master {\n\tm := Master{}\n\n\t// Your code here.\n\tm.init()\n\n\tm.server()\n\treturn &m\n}", "func initConsumer() sarama.Consumer {\n\tsarama.Logger = log.New(os.Stdout, \"\", log.Ltime)\n\n\tconfig := sarama.NewConfig()\n\tconfig.ClientID = CLIENTID\n\tconfig.Consumer.Return.Errors = true\n\n\tbrokers := []string{BROKERS}\n\n\tmaster, err := sarama.NewConsumer(brokers, config)\n\tif err != nil {\n\t\tfmt.Println(\"error create master consumer: \")\n\t\tpanic(err)\n\t}\n\n\treturn master\n}", "func (b *ClusterNodesBuilder) Master(value int) *ClusterNodesBuilder {\n\tb.master = &value\n\treturn b\n}", "func newNodes(c *Client) *nodes {\n\treturn &nodes{c}\n}", "func newSwimCluster(size int) *swimCluster {\n\tvar nodes []*Node\n\tvar channels []*tchannel.Channel\n\tfor i := 0; i < size; i++ {\n\t\tch, err := tchannel.NewChannel(\"test\", nil)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tif err := ch.ListenAndServe(\"127.0.0.1:0\"); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tchannels = append(channels, ch)\n\n\t\thostport := ch.PeerInfo().HostPort\n\t\tnode := NewNode(\"test\", hostport, ch.GetSubChannel(\"test\"), nil)\n\n\t\tnodes = append(nodes, node)\n\t}\n\treturn &swimCluster{nodes: nodes, channels: channels}\n}", "func main() {\n\trouter := mux.NewRouter()\n\t\n\t//initial nodes can be added form the command line \n\tif len(os.Args) > 1 {\n\t\tnodeEndpoints := strings.Split(os.Args[1], \",\")\n\t\tfor ind, node := range nodeEndpoints {\n\t\t\tcounternodes[node] = strconv.Itoa(ind) \n\t\t}\n\t} \n\n\n\tfmt.Println(\"master node started on : 8000\")\n\trouter.HandleFunc(\"/items\", UpdateCount).Methods(\"POST\")\n\trouter.HandleFunc(\"/items/{id}/count\", GetCount).Methods(\"GET\")\n\trouter.HandleFunc(\"/ping\", CheckStatus).Methods(\"GET\")\n\trouter.HandleFunc(\"/addnode\", AddCounterNode).Methods(\"POST\")\n\trouter.HandleFunc(\"/removenode\", RemoveCounterNode).Methods(\"POST\")\n\trouter.HandleFunc(\"/syncnode/{nodeid}\", SyncCounterNode).Methods(\"POST\")\n\tlog.Fatal(http.ListenAndServe(\":8000\", router))\n}", "func InitNetwork(nodes []Node, myself int) (network Network, err error) {\n\trC := make(chan Message, 65535) //Increased for TS\n\tsC := make(chan Message, 65535) //Increased for TS\n\tccC := make(chan *net.TCPConn, 65535)\n\tnetwork = Network{\n\t\tNodes: []Node{},\n\t\tConnections: map[int]*net.TCPConn{},\n\t\tClientConns: []*net.TCPConn{},\n\t\tReceiveChan: rC,\n\t\tSendChan: sC,\n\t\tClientConnChan: ccC,\n\t}\n\n\tfor _, node := range nodes {\n\t\tif node.ID == myself {\n\t\t\tfmt.Printf(\"You are number %v\\n\", myself)\n\t\t\tnetwork.Myself = node\n\t\t\tTCPsocket := network.Myself.IP + \":\" + strconv.Itoa(network.Myself.Port)\n\t\t\tnetwork.Myself.TCPaddr, err = net.ResolveTCPAddr(\"tcp\", TCPsocket)\n\t\t} else {\n\t\t\tTCPsocket := node.IP + \":\" + strconv.Itoa(node.Port)\n\t\t\taddr, _ := net.ResolveTCPAddr(\"tcp\", TCPsocket)\n\t\t\tnetwork.Nodes = append(network.Nodes, Node{\n\t\t\t\tID: node.ID,\n\t\t\t\tIP: node.IP,\n\t\t\t\tPort: node.Port,\n\t\t\t\tTCPaddr: addr,\n\t\t\t})\n\t\t}\n\t}\n\treturn network, err\n}", "func (m *Master) Build() {\n\toutChannel := make(chan [2]string, 100)\n\n\tvar channels [][]chan [2]string\n\tfor i := 0; i < len(m.workers); i++ {\n\t\tvar newChannels []chan [2]string\n\t\tfor j := 0; j < len(m.workers[i]); j++ {\n\t\t\tnewChannels = append(newChannels, make(chan [2]string, 100))\n\t\t}\n\t\tchannels = append(channels, newChannels)\n\t}\n\tfor j := 0; j < len(m.workers[0]); j++ {\n\t\tm.workers[0][j].init(1, channels[0][j], channels[1])\n\t}\n\tfor i := 1; i < len(m.workers)-1; i++ {\n\t\tfor j := 0; j < len(m.workers[i]); j++ {\n\t\t\tm.workers[i][j].init(len(m.workers[i-1]), channels[i][j], channels[i+1])\n\t\t}\n\t}\n\tlast := len(m.workers) - 1\n\tfor j := 0; j < len(m.workers[last]); j++ {\n\t\tm.workers[last][j].init(len(m.workers[last-1]), channels[last][j], []chan [2]string{outChannel})\n\t}\n\n\tm.input.init(channels[0])\n\n\tm.output.init(len(m.workers[last]), outChannel)\n\n\tm.output.numUpstream = len(m.workers[last])\n\tm.output.inChannel = outChannel\n\tm.output.endChannel = make(chan int)\n}", "func NewNODES(config configuration.CONFIGURATION) *NODES_IMPL {\r\n client := new(NODES_IMPL)\r\n client.config = config\r\n return client\r\n}", "func NewMasterConn(c net.Conn) (m Master, e error) {\n\tdefer func() {\n\t\tif e != nil {\n\t\t\tc.Close()\n\t\t}\n\t}()\n\n\tgobCon := gobplexer.NetConnection(c)\n\trootConnector := gobplexer.MultiplexConnector(gobCon)\n\tkeptAlive, err := gobplexer.KeepaliveConnector(rootConnector,\n\t\tpingInterval, pingMaxDelay)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconnector := gobplexer.MultiplexConnector(keptAlive)\n\tif conn, err := connector.Connect(); err != nil {\n\t\treturn nil, fmt.Errorf(\"connect for info: %s\", err)\n\t} else if infoObj, err := conn.Receive(); err != nil {\n\t\treturn nil, fmt.Errorf(\"read info: %s\", err)\n\t} else if info, ok := infoObj.(SlaveInfo); !ok {\n\t\treturn nil, fmt.Errorf(\"invalid info type: %T\", infoObj)\n\t} else {\n\t\tdoneChan := make(chan struct{})\n\t\tgo func() {\n\t\t\t// The other end leaves this sub-connection open so we\n\t\t\t// can poll from it to see when the connection dies.\n\t\t\tconn.Receive()\n\t\t\tc.Close()\n\t\t\tclose(doneChan)\n\t\t}()\n\t\treturn &masterConn{\n\t\t\tconnector: connector,\n\t\t\tdoneChan: doneChan,\n\t\t\tinfo: info,\n\t\t}, nil\n\t}\n}", "func initServer(ctx context.Context, n *Node) error {\n\n\tif n.index < int32(len(n.config.Nodes)) {\n\n\t\tle := n.config.Nodes[n.index]\n\t\tvar listener net.Listener\n\n\t\terr := backoff.Retry(\n\t\t\tfunc() error {\n\t\t\t\tvar err error\n\t\t\t\tlistener, err = net.Listen(\"tcp\", le)\n\t\t\t\treturn err\n\t\t\t},\n\t\t\tbackoff.WithMaxRetries(backoff.NewExponentialBackOff(), 3),\n\t\t)\n\n\t\t// listener, err := net.Listen(\"tcp\", le)\n\t\tif err != nil {\n\t\t\terr = raftErrorf(err, \"failed to acquire local TCP socket for gRPC\")\n\t\t\tn.logger.Errorw(\"initServer failed (some other application or previous instance still using socket?)\",\n\t\t\t\traftErrKeyword, err)\n\t\t\treturn err\n\t\t}\n\n\t\ts := &raftServer{\n\t\t\tnode: n,\n\t\t\tlocalListener: listener,\n\t\t\tlocalAddr: le,\n\t\t}\n\n\t\tn.messaging.server = s\n\t\tn.logger.Debugw(\"listener acquired local node address\", s.logKV()...)\n\n\t} else {\n\n\t\terr := raftErrorf(\n\t\t\tRaftErrorServerNotSetup, \"LocalNodeIndex in out of bounds of cluster Nodes configuration\")\n\t\tn.logger.Errorw(\"initServer failed\", raftErrKeyword, err)\n\t\treturn err\n\n\t}\n\n\treturn nil\n}", "func (agent *ActionAgent) InitMaster(ctx context.Context) (string, error) {\n\tif err := agent.lock(ctx); err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer agent.unlock()\n\n\t// Initializing as master implies undoing any previous \"do not replicate\".\n\tagent.setSlaveStopped(false)\n\n\t// we need to insert something in the binlogs, so we can get the\n\t// current position. Let's just use the mysqlctl.CreateReparentJournal commands.\n\tcmds := mysqlctl.CreateReparentJournal()\n\tif err := agent.MysqlDaemon.ExecuteSuperQueryList(ctx, cmds); err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// get the current replication position\n\tpos, err := agent.MysqlDaemon.MasterPosition()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// If using semi-sync, we need to enable it before going read-write.\n\tif err := agent.fixSemiSync(topodatapb.TabletType_MASTER); err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Set the server read-write, from now on we can accept real\n\t// client writes. Note that if semi-sync replication is enabled,\n\t// we'll still need some slaves to be able to commit transactions.\n\tstartTime := time.Now()\n\tif err := agent.MysqlDaemon.SetReadOnly(false); err != nil {\n\t\treturn \"\", err\n\t}\n\tagent.setExternallyReparentedTime(startTime)\n\n\t// Change our type to master if not already\n\tif _, err := agent.TopoServer.UpdateTabletFields(ctx, agent.TabletAlias, func(tablet *topodatapb.Tablet) error {\n\t\ttablet.Type = topodatapb.TabletType_MASTER\n\t\treturn nil\n\t}); err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// and refresh our state\n\tagent.initReplication = true\n\tif err := agent.refreshTablet(ctx, \"InitMaster\"); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn mysql.EncodePosition(pos), nil\n}", "func NewMasterNode(seed []byte) (*Node, error) {\n\t// Check if seed has valid size\n\tif len(seed) < minSeedSize || len(seed) > maxSeedSize {\n\t\treturn nil, errors.New(\"NewMasterNode: invalid seed size\")\n\t}\n\n\t// Generate HMAC-SHA512 with hardcoded seed as Key\n\th := hmac.New(hasher.SHA2_512.New, []byte(\"Bitcoin seed\"))\n\n\t// Data: H(seed)\n\th.Write(seed)\n\taux := h.Sum(nil)\n\n\t// Validate Private Key\n\terr := validatePrivateKey(aux[:keySize])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Export Key and Chain Code from aux\n\tnode := &Node{\n\t\tKey: aux[:keySize],\n\t\tCode: aux[keySize:],\n\t}\n\treturn node, nil\n}", "func (m *Master) server() {\n\trpc.Register(m)\n\trpc.HandleHTTP()\n\tos.Create(\"mr-socket\")\n\n\tl, e := net.Listen(\"tcp\", \"0.0.0.0:8080\")\n\tif e != nil {\n\t\tlog.Fatal(\"listen error:\", e)\n\t}\n\tlog.Printf(\"Server is running at %s\\n\", l.Addr().String())\n\tgo http.Serve(l, nil)\n}", "func init() {\n\n\t//Welcome Message\n\tfmt.Println(\"------------------------------------------------------------------\")\n\tfmt.Println(\"Starting Natyla...\")\n\tfmt.Println(\"Version: 1.02\")\n\n\t//Set the thread quantity based on the number of CPU's\n\tcoreNum := runtime.NumCPU()\n\n\tfmt.Println(\"Number of cores: \", coreNum)\n\n\t//read the config file\n\treadConfig()\n\n\t//create the data directory\n\tcreateDataDir()\n\n\t//set max memory form config\n\tmaxMemBytes, _ = config[\"memory\"].(json.Number).Int64()\n\tfmt.Println(\"Max memory defined as: \", maxMemBytes/1024/1024, \" Mbytes\")\n\n\truntime.GOMAXPROCS(coreNum)\n\n\t//Create a new doble-linked list to act as LRU\n\tlruList = list.New()\n\n\t//Create the channels\n\tlisChan = make(chan int, 1)\n\tLRUChan = make(chan int, 1)\n\tcollectionChan = make(chan int, 1)\n\n\tcollections = make(map[string]collectionChannel)\n\n\t//Read collections from disk\n\tnRead := readAllFromDisk()\n\tfmt.Println(\"Read\", nRead, \"entries from disk\")\n\n\tfmt.Println(\"Ready, API Listening on http://localhost:8080, Telnet on port 8081\")\n\tfmt.Println(\"------------------------------------------------------------------\")\n}", "func (n *Node) Init() {\n\tn.NodeNet.Init()\n\n\tn.NodeNet.Logger = n.Logger\n\tn.NodeBC.Logger = n.Logger\n\n\tn.NodeBC.MinterAddress = n.MinterAddress\n\n\tn.NodeBC.DBConn = n.DBConn\n\n\t// Nodes list storage\n\tn.NodeNet.SetExtraManager(NodesListStorage{n.DBConn, n.SessionID})\n\t// load list of nodes from config\n\tn.NodeNet.SetNodes([]net.NodeAddr{}, true)\n\n\tn.InitClient()\n\n\trand.Seed(time.Now().UTC().UnixNano())\n}", "func StartRPCClient(spawnChannel chan int, somechan chan bool,job *Job) {\n\tfmt.Print(\"\\n> Initating connection with master\")\n\tclient, err := rpc.Dial(\"tcp\", \"0.0.0.0:12345\")\n\tif err != nil {\n\t log.Fatal(err)\n\t}\n\n\tl := string(\"Test String\")\n\n\terr = client.Call(\"Master.EstConnection\", l, &job)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"\\n> Pusblising on mapper spawn channel\")\n\tspawnChannel <- job.NMappers\n\tsomechan <- true\n\tclose(spawnChannel)\n\tclose(somechan)\n}", "func (zk *ZookeeperMaster) Init() error {\n\tzk.isMaster = false\n\t//create connection to zookeeper\n\tzk.client = zkclient.NewZkClient(zk.zkHosts)\n\tif err := zk.client.ConnectEx(time.Second * 10); err != nil {\n\t\treturn fmt.Errorf(\"Init failed when connect zk, %s\", err.Error())\n\t}\n\treturn nil\n}", "func TcpManagerInit() *TcpManager {\n\tm := &TcpManager{\n\t\tbind: make(chan *TcpClient, 10),\n\t\tunbind: make(chan *TcpClient, 10),\n\t\tclose: make(chan *TcpClient, 10),\n\t\tbindClients: util.NewConcMap(),\n\t\tunbindClients: util.NewConcMap(),\n\t}\n\tants.Submit(m.Run)\n\treturn m\n}", "func (m *Master) Connect(a *ConnectArgs, r *ConnectRes) error {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\tm.idSeq++\n\ts := &MasterSlave{\n\t\tid: m.idSeq,\n\t\tprocs: a.Procs,\n\t\tlastSync: time.Now(),\n\t}\n\tm.slaves[s.id] = s\n\tr.ID = s.id\n\t// Give the slave initial corpus.\n\tfor _, a := range m.corpus.m {\n\t\tr.Corpus = append(r.Corpus, MasterInput{a.data, a.meta, execCorpus, !a.user, true})\n\t}\n\treturn nil\n}", "func init() {\n\tbackendQueue = make(chan *Backend, 10) \t//channel at a size of 10\n\t\t\t\t\t\t//This is a buffered channel.\n\t\t\t\t\t\t//This means that it can hold 10 Backends before it starts to block\n}", "func init() {\n\t// Reset commands, so `pegnetnode` is the only h\n\tpcmd.RootCmd.ResetCommands()\n\tpcmd.RootCmd.Flags().Bool(\"mock\", false, \"Do not actually connect to discord\")\n\tpcmd.RootCmd.Run = func(cmd *cobra.Command, args []string) {\n\t\tdiscordNode.Run(cmd, args)\n\t}\n}", "func newHub(id string, redis *predis.Client) *hub {\n\th := &hub{\n\t\tid: id,\n\t\tredis: redis,\n\t\tclients: make(map[string]*client),\n\t\tinboundc: make(chan *Message),\n\t\tpeerc: make(chan *Message),\n\t\tmasterc: make(chan []byte),\n\t\tregisterc: make(chan *client),\n\t\tunregisterc: make(chan *client),\n\t}\n\n\th.presence = newPresence(h.id, h.redis)\n\th.transport = newTransport(h.id, h.redis, h.masterc, h.peerc)\n\n\treturn h\n}", "func newResponseNode(model string, hash string, version *big.Int, sim *backends.SimulatedBackend) {\n\topts := mqtt.NewClientOptions().AddBroker(\"tcp://localhost:1883\")\n\tclient := mqtt.NewClient(opts)\n\ttoken := client.Connect()\n\tif token.Wait() && token.Error() != nil {\n\t\tlog.Fatalln(token.Error())\n\t}\n\n\tvar messageHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {\n\t\tcontract, _ := contracts.NewVerifier(common.HexToAddress(string(msg.Payload())), sim)\n\t\tsendResponse(sim, contract, hash, version)\n\t}\n\ttoken = client.Subscribe(model, 0, messageHandler)\n\tif token.Wait() && token.Error() != nil {\n\t\tlog.Fatalln(token.Error())\n\t}\n}", "func ConnectNodes(config *utils.Config) {\n\tnodes := config.Nodes\n\tip := config.Master.Ip\n\tport := config.Master.Port\n\tCONN := ip + \":\" + port\n\n//connect to master server for all nodes and then connect to each other\n\tfor j := range nodes {\n\t\t//dial into master server\n\t\tconn, err := net.Dial(\"tcp\", CONN)\n\t\tutils.Error(err)\n\t\tnodes[j].Conns = append(nodes[j].Conns, conn)\n\t}\n\tfor i := range nodes {\n\t\t//have it connect to all nodes including itself\n\t\tfor _, serverNode := range nodes {\n\t\t\tip := serverNode.Ip\n\t\t\tport := serverNode.Port\n\t\t\tCONN := ip + \":\" + port\n\t\t\t//connect to all other nodes\n\t\t\tconn, err := net.Dial(\"tcp\", CONN)\n\t\t\tutils.Error(err)\n\t\t\tnodes[i].Conns = append(nodes[i].Conns, conn)\n\t\t}\n\t}\n}", "func handleSlaveConnection(c net.Conn, msgchan chan Msg, addchan chan Slave) {\n\n\tlog.Printf(\"Handling new slave connection...\\n\")\n\tslaveReader := bufio.NewReader(c)\n\t//get number of files\n\tbuff1, _, _ := slaveReader.ReadLine() //get number of original files\n\tbuff2, _, _ := slaveReader.ReadLine() //get number of replicated files\n\tsize, _ := strconv.Atoi(string(buff1))\n\trsize, _ := strconv.Atoi(string(buff2))\n\tlog.Printf(\"Size: %d\\nRSize: %d\\n\", size, rsize)\n\t//create new slave\n\tnewClient := Slave{\n\t\tconnection: c,\n\t\tchunks: make([]string, 0, size),\n\t\trchunks: make([]string, 0, rsize),\n\t\tchannel: make(chan string, 2),\n\t\tresponse: \"nr\"}\n\tnewMsg := Msg{\n\t\tconnection: c}\n\t//receive original file names from slave\n\tfor i := 0; i < size; i++ {\n\t\tname, _, _ := slaveReader.ReadLine() //get Name of chunks\n\t\tnewClient.chunks = append(newClient.chunks, string(name))\n\t\tlog.Printf(\"Chunk # %d , Name: %s \\n\", i, string(name))\n\t}\n\t//receive replicated files names from slave\n\tfor i := 0; i < rsize; i++ {\n\t\tname, _, _ := slaveReader.ReadLine() //get Name of chunks\n\t\tnewClient.rchunks = append(newClient.rchunks, string(name))\n\t\tlog.Printf(\"RChunk # %d , Name: %s \\n\", i, string(name))\n\t}\n\tlog.Print(newClient)\n\t//sending new slave information to master thread\n\taddchan <- newClient\n\n\tcommand := \"nil\"\n\tfor {\n\t\tselect {\n\t\tcase x := <-newClient.channel:\n\t\t\tcommand = x\n\t\t\tfmt.Println(\"setting new command: \" + command)\n\t\tdefault:\n\n\t\t\tc.Write([]byte(command + \"\\n\"))\n\n\t\t\tcc, _, err := slaveReader.ReadLine()\n\t\t\tresponse := string(cc)\n\t\t\t//check for disconnectivity\n\t\t\tif response == \"\" || err != nil {\n\t\t\t\tlog.Println(\"Slave disconnected...\")\n\t\t\t\tnewMsg.msg = \"rmv\"\n\t\t\t\tmsgchan <- newMsg\n\t\t\t\treturn\n\t\t\t}\n\t\t\t//Parse reponse\n\t\t\tprsResp := strings.Split(response, \":\")\n\t\t\tlog.Print(prsResp[0])\n\t\t\t//set response of not found\n\t\t\tif prsResp[0] == \"not\" {\n\t\t\t\tcommand = \"nil\"\n\t\t\t\tnewMsg.msg = response\n\t\t\t\tmsgchan <- newMsg\n\t\t\t} else if prsResp[0] == \"done\" {\n\t\t\t\tcommand = \"nil\"\n\t\t\t\tnewMsg.msg = response\n\t\t\t\tmsgchan <- newMsg\n\t\t\t} else if prsResp[0] == \"nil\" {\n\t\t\t\tcommand = \"nil\"\n\t\t\t}\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t}\n\t}\n}", "func (n *Node) Start() error {\n\tgo n.mainLoop()\n\t// Wait until fully initialized\n\t<-n.initializedChan\n\treturn n.connect(NodeInfo{Ip: \"127.0.0.1\", Port: n.listenPort})\n}", "func init(){\n\tskeleton.RegisterChanRPC(reflect.TypeOf(&msg.Hello{}), handleHello)\n}", "func doStart(server common.Server, cfg *config.Config) (err error) {\n\tdebug.SetMaxThreads(20000)\n\n\ts, ok := server.(*DataNode)\n\tif !ok {\n\t\treturn errors.New(\"Invalid Node Type!\")\n\t}\n\n\ts.stopC = make(chan bool, 0)\n\n\t// parse the config file\n\tif err = s.parseConfig(cfg); err != nil {\n\t\treturn\n\t}\n\n\texporter.Init(ModuleName, cfg)\n\ts.registerMetrics()\n\ts.register(cfg)\n\n\t//parse the smux config\n\tif err = s.parseSmuxConfig(cfg); err != nil {\n\t\treturn\n\t}\n\t//connection pool must be created before initSpaceManager\n\ts.initConnPool()\n\n\t// init limit\n\tinitRepairLimit(s, cfg)\n\n\t// start the raft server\n\tif err = s.startRaftServer(cfg); err != nil {\n\t\treturn\n\t}\n\n\t// create space manager (disk, partition, etc.)\n\tif err = s.startSpaceManager(cfg); err != nil {\n\t\treturn\n\t}\n\n\t// check local partition compare with master ,if lack,then not start\n\tif err = s.checkLocalPartitionMatchWithMaster(); err != nil {\n\t\tlog.LogError(err)\n\t\texporter.Warning(err.Error())\n\t\treturn\n\t}\n\n\t// tcp listening & tcp connection pool\n\tif err = s.startTCPService(); err != nil {\n\t\treturn\n\t}\n\n\t//smux listening & smux connection pool\n\tif err = s.startSmuxService(cfg); err != nil {\n\t\treturn\n\t}\n\n\tgo s.registerHandler()\n\n\tgo s.startUpdateNodeInfo()\n\n\treturn\n}", "func MakeMaster(files []string, nReduce int) *Master {\n\tnMap := len(files)\n\tm := NewMaster(files, max(nMap, nReduce), masterTimeout, nReduce)\n\n\t// Your code here.\n\tm.server()\n\treturn m\n}", "func Initialize(configFileName string) error {\n\n\tif err := readConfigJSON(configFileName); err != nil {\n\t\treturn fmt.Errorf(\"initialize error: %v\", err)\n\t}\n\n\tmanager = &ManagerNode{\n\t\tManagerNodeID: ManagerNodeID(config.ManagerNodeID),\n\t\tTopicMap: make(map[string]*Topic),\n\t\tManagerPeers: make(map[ManagerNodeID]string),\n\t\tBrokerNodes: make(map[BrokerNodeID]string),\n\t\tTopicMutex: &sync.Mutex{},\n\t\tManagerMutex: &sync.Mutex{},\n\t\tBrokerMutex: &sync.Mutex{},\n\t\tMU: &sync.Mutex{},\n\t}\n\n\tcache, err := lru.New(cacheSize)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmanager.TransactionCache = cache\n\n\tlogger = govec.InitGoVector(string(manager.ManagerNodeID), fmt.Sprintf(\"%v-logfile\", manager.ManagerNodeID), govec.GetDefaultConfig())\n\tloggerOptions = govec.GetDefaultLogOptions()\n\n\tgo func() {\n\t\ttime.Sleep(time.Duration(100) * time.Millisecond)\n\t\tif len(config.PeerManagerNodeIP) != 0 {\n\t\t\tif err := manager.registerPeerRequest(config.PeerManagerNodeIP); err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t}()\n\n\tvar emptylist []string\n\tring = hashring.New(emptylist)\n\tspawnRPCServer()\n\treturn nil\n}", "func createChannel() Channel {\n\tchannel := channelStruct{}\n\treturn &channel\n}", "func (n *NodeConn) Init(arg interface {}) (interface {}) {\n\tn.ComplexComm.Init(c.ComplexCommInit{numChan:2})\n\treturn n\n}", "func main(){\n\tmc := master.LoadConfig()\n\terrList := master.Start(mc.Num_instances, mc.Selection_config, mc.Ports)\n\tfor i, err := range errList {\n\t\tlog.Println(\"ERR: \", i, \"th master terminated with error: \", err)\n\t}\n\n}", "func guildCreate(s *discordgo.Session, event *discordgo.GuildCreate) {\n\n\tif event.Guild.Unavailable {\n\t\treturn\n\t}\n\n\tfor _, channel := range event.Guild.Channels {\n\t\tif channel.ID == event.Guild.ID {\n\t\t\t_, _ = s.ChannelMessageSend(channel.ID, \"primitive-gobot is ready!\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func MakeMaster(files []string, nReduce int) *Master {\n\tm := Master{}\n\n\t// Your code here.\n\tm.nReduce = nReduce\n\tm.files = files\n\tm.nMap = len(files)\n\tm.mapStates = make([]mapState, m.nMap)\n\tm.reduceStates = make([]reduceState, m.nReduce)\n\tm.server()\n\treturn &m\n}", "func init() {\n\tSBC = data.NewBlockChain()\n\tid, _ := strconv.ParseInt(os.Args[1], 10, 32)\n\tPeers = data.NewPeerList( /*Register()*/ int32(id), 32) // Uses port number as ID since TA server is down\n\tprivateKey, publicKey = client.GenerateKeyPair()\n\tifStarted = false\n\tmpt.Initial()\n\tclientBalanceMap = make(map[string]int32)\n\tpendingTransaction = make(map[string]string)\n\ttransactionMpt.Initial()\n\tclientBalanceMap[string(client.PublicKeyToBytes(publicKey))] = 1000\n\thighestblockTransaction = 0\n}", "func MakeMaster(files []string, nReduce int) *Master {\n\tm := Master{}\n\tm.files = files\n\tm.record = map[string]*record{}\n\tm.tasks = map[int][]*record{}\n\tm.reduceTasks = map[int]*record{}\n\tm.nReduce = nReduce\n\tm.phase = TaskMapType\n\t// Your code here.\n\n\tm.server()\n\treturn &m\n}", "func (c *Client) init() {\n\tif c.domains == nil {\n\t\tc.domains = map[int]string{}\n\t}\n\tif c.cfg == nil {\n\t\tc.cfg = manager.NewAtomicConfig(tg.Config{})\n\t}\n\tc.ready = tdsync.NewResetReady()\n\tc.restart = make(chan struct{})\n\tc.migration = make(chan struct{}, 1)\n\tc.sessions = map[int]*pool.SyncSession{}\n\tc.subConns = map[int]CloseInvoker{}\n\tc.invoker = chainMiddlewares(InvokeFunc(c.invokeDirect), c.mw...)\n\tc.tg = tg.NewClient(c.invoker)\n}", "func NewConnectionToNodes(cycle int, nodes ...string) (Connection, error){\n disqueConn, err := connectToFirstAvailableNode(nodes...); if err != nil {\n return Connection{Cycle: cycle, Nodes: nodes}, err\n }\n\n return Connection{disqueConn, cycle, nodes}, nil\n}", "func InitNode(absPath string, metaData MetaData) {\n\tfmt.Println(\"Initiating Node.JS project\")\n\n\t// Create the new directory\n\tfmt.Println(\"Making Directories\")\n\tos.Mkdir(path.Join(absPath, \"src\"), 0777)\n\tos.Mkdir(path.Join(absPath, \"test\"), 0777)\n\tos.Mkdir(path.Join(absPath, \".circleci\"), 0777)\n\n\t// Get node version\n\tnodev, err := runCmd(\"node\", \"-v\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Write .nvmrc\n\tioutil.WriteFile(path.Join(absPath, \".nvmrc\"), []byte(nodev), 0666)\n\n\t// node version comes out like v10.9.0, so we need to trim the leading 'v'\n\tnodev = nodev[1:]\n\n\tfmt.Println(\"Getting Dependency Versions\")\n\tchaiv, err := runCmd(\"npm\", \"show\", \"chai\", \"version\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tmochav, err := runCmd(\"npm\", \"show\", \"mocha\", \"version\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\teslintv, err := runCmd(\"npm\", \"show\", \"eslint\", \"version\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tnycv, err := runCmd(\"npm\", \"show\", \"nyc\", \"version\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tpInfo := packageInfo{\n\t\tName: metaData.Name,\n\t\tAuthor: metaData.Author,\n\t\tNodeVersion: nodev,\n\t\tChaiVersion: chaiv,\n\t\tMochaVersion: mochav,\n\t\tESLintVersion: eslintv,\n\t\tNYCVersion: nycv,\n\t}\n\n\t// Initiate the project\n\terr = createFileFromTemplate(templates.PackageJSON(), path.Join(absPath, \"package.json\"), pInfo)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tnewFile, err := os.Create(path.Join(absPath, \"src\", \"index.js\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tnewFile.Close()\n\n\tfmt.Println(\"Installing dependencies\")\n\t_, err = runCmdFromDir(absPath, \"npm\", \"install\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = ioutil.WriteFile(path.Join(absPath, \".eslintrc.js\"), []byte(templates.ESLintRC()), 0666)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Setting up CircleCI\")\n\terr = createFileFromTemplate(templates.CircleNode(), path.Join(absPath, \".circleci\", \"config.yml\"), pInfo)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Fetching .gitignore\")\n\tresp, err := http.Get(\"https://raw.githubusercontent.com/github/gitignore/master/Node.gitignore\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tioutil.WriteFile(path.Join(absPath, \".gitignore\"), body, 0666)\n\n\terr = createFileFromTemplate(templates.ComposeNode(), path.Join(absPath, \"docker-compose.yml\"), pInfo)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (p *Pupil) setupEventChannel(eventChan chan []byte) {\n\tvar err error\n\tif p.sock, err = respondent.NewSocket(); err != nil {\n\t\tlog.Fatal(\"Couldn't open the event port\")\n\t}\n\tp.sock.AddTransport(tcp.NewTransport())\n\tlog.Printf(\"Dialing into the master at %s\\n\", p.MasterEventURL)\n\tif err = p.sock.Dial(p.MasterEventURL); err != nil {\n\t\tlog.Fatalf(\"Couldn't connect to the master's event port at - %s\\n\", p.MasterEventURL)\n\t}\n\tlog.Printf(\"pupil ready to receive events from the master\")\n}", "func MakeMaster(files []string, nReduce int) *Master {\n\tdelete()\n\tm := Master {\n\t\tmu: sync.RWMutex{},\n\t\tM: len(files),\n\t\tR: nReduce,\n\t\tidleTasks: [2]chan Task{make(chan Task, len(files)), make(chan Task, nReduce)},\n\t\tinProgress: [2]map[Task]bool{make(map[Task]bool), make(map[Task]bool)},\n\t\tcompletedTasks: [2]chan Task{make(chan Task, len(files)), make(chan Task, nReduce)},\n\t}\n\n\n\t// Your code here.\n\tfor i, file := range files {\n\t\ttask := Task{Type: \"map\", Filename: file, TaskNum: i, NReduce: nReduce}\n\t\tm.idleTasks[0] <- task\n\t}\n\n\tfor i:=0; i<nReduce ; i++ {\n\t\tm.idleTasks[1] <- Task{\n\t\t\tType: \"reduce\",\n\t\t\tFilename: \"\",\n\t\t\tTaskNum: i,\n\t\t\tNReduce: nReduce,\n\t\t}\n\t}\n\n\tm.server()\n\treturn &m\n}", "func Connect(token string) error {\n\tdg, err := discordgo.New(\"Bot \" + token)\n\tif err != nil {\n\t\tfmt.Println(\"error creating Discord session,\", err)\n\t\treturn err\n\t}\n\tdg.AddHandler(manager)\n\tchannels, _ := dg.GuildChannels(\"675106841436356628\")\n\n\tfor _, v := range channels {\n\t\tfmt.Printf(\"Channel id: %s Channel name: %s\\n\", v.ID, v.Name)\n\t}\n\n\t// This function sends message every hour concurrently.\n\tgo func() {\n\t\tfor range time.NewTicker(time.Hour).C {\n\t\t\t_, err := dg.ChannelMessageSend(\"675109890204762143\", \"dont forget washing ur hands!\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"couldn't send ticker message\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = dg.Open()\n\tif err != nil {\n\t\tfmt.Println(\"error opening connection,\", err)\n\t\treturn err\n\t}\n\t// Wait here until CTRL-C or other term signal is received.\n\tfmt.Println(\"Bot is now running. Press CTRL-C to exit.\")\n\tsc := make(chan os.Signal, 1)\n\tsignal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)\n\t<-sc\n\t// Cleanly close down the Discord session.\n\tdg.Close()\n\treturn nil\n}", "func init() {\n\tbinlogplayer.RegisterClientFactory(\"gorpc\", func() binlogplayer.Client {\n\t\treturn &client{}\n\t})\n}", "func InitiateAndStartQmlGrpcServer() {\n\tvar err error\n\n\tQmlServerObject.logger.WithFields(logrus.Fields{\n\t\t\"ID\": \"56b6419f-d714-4ab0-be62-f3c7f08b9558\",\n\t}).Info(\"Mother Server tries to start\")\n\n\t// Find first non allocated port from defined start port\n\t// TODO\n\n\tQmlServerObject.logger.WithFields(logrus.Fields{\n\t\t\"common_config.QmlServer_port): \": common_config.QmlServer_port,\n\t\t\"ID\": \"8f904ace-9d24-452b-891a-5b8e5c247ba2\",\n\t}).Info(\"Start listening on:\")\n\tlis, err = net.Listen(\"tcp\", string(common_config.QmlServer_port))\n\n\tif err != nil {\n\t\tQmlServerObject.logger.WithFields(logrus.Fields{\n\t\t\t\"err: \": err,\n\t\t\t\"ID\": \"0fbf0f08-6114-4cd8-9992-6a387955fb5f\",\n\t\t}).Fatal(\"failed to listen:\")\n\n\t} else {\n\t\tQmlServerObject.logger.WithFields(logrus.Fields{\n\t\t\t\"common_config.QmlServer_port): \": common_config.QmlServer_port,\n\t\t\t\"ID\": \"93496c07-2b6c-4edc-a1f9-3fd555fa1201\",\n\t\t}).Info(\"Success in listening on port:\")\n\n\t}\n\n\t// Creates a new RegisterMotherServer gRPC server\n\tgo func() {\n\t\tQmlServerObject.logger.WithFields(logrus.Fields{\n\t\t\t\"ID\": \"ebc26735-9d13-4b13-91b8-20999cd5e254\",\n\t\t}).Info(\"Starting QML gRPC Server\")\n\n\t\tregisterQmlGrpcServer = grpc.NewServer()\n\t\tqml_server_grpc_api.RegisterQmlGrpcServicesServer(registerQmlGrpcServer, &QMLgRrpServer_struct{})\n\n\t\tQmlServerObject.logger.WithFields(logrus.Fields{\n\t\t\t\"common_config.QmlServer_port): \": common_config.QmlServer_port,\n\t\t\t\"ID\": \"cfed87c4-55aa-4cd1-980a-a15eb75ab6fb\",\n\t\t}).Info(\"registerQmlGrpcServer for QMLs gRPC Server started\")\n\n\t\tregisterQmlGrpcServer.Serve(lis)\n\t}()\n}", "func (n *miniNode) Init() Nodes { return Nodes{} }", "func (s *Server) SetMaster(host string, config toolkit.M) error {\n\tif s.masterClient != nil {\n s.masterClient.Call(\"unfollow\", toolkit.M{}.Set(\"nodeid\", s.masterClient.Host), nil)\n\t\ts.masterClient.Close()\n\t}\n \n s.masterHost = host\n\tif host==\"\"{\n return nil \n }\n \n masterClient := NewClient(s.masterHost, config)\n\te := masterClient.Connect()\n\tif e != nil {\n\t\treturn errors.New(\"Server.SetMaster: \" + e.Error())\n\t}\n\n\te = masterClient.Call(\"follow\", toolkit.M{}.Set(\"nodeid\", s.Host), nil)\n\tif e != nil {\n\t\treturn errors.New(\"Server.SetMaster.Follow: \" + e.Error())\n\t}\n s.Log.AddLog(toolkit.Sprintf(\"Server %s is now following %s\", s.Host, host), \"INFO\") \t\n\treturn nil\n}", "func MakeMaster(files []string, nReduce int) *Master {\n\tm := Master{}\n\n\t// Your code here.\n\tm.ReduceTask = make(map[int]*ReduceTaskStatus)\n\tm.MapTask = make(map[int]*MapTaskStatus)\n\tm.inputFileList = files\n\tm.nReduce = nReduce\n\tm.State = Map\n\tfor i, _ := range files {\n\t\tm.MapTask[i] = &MapTaskStatus{\n\t\t\tStatus: UnInit,\n\t\t}\n\t}\n\n\tm.server()\n\treturn &m\n}", "func (c *Cluster) SetMaster(opts *pg.Options) error {\n\tconn, err := newConnection(opts, c.conf.ConnPingTimeout, c.conf.ConnCheckDelay)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.manager.master = conn\n\treturn nil\n}", "func InitRing(myIp string, myId int) {\n\tfmt.Println(\"\\n------------------------------------------------------------------------------\")\n\tfmt.Println(\"Test 1: creating/join chord ring ...\")\n\tstart1 := time.Now()\n\n\t// scan for ring\n\tfmt.Println(\"\\nScanning for ring ...\")\n\tipInRing, _ := chord.CheckRing()\n\tringSize := len(ipInRing)\n\tfmt.Println(\"Ring scan completed!\\nNodes in ring: \", ipInRing, \"\\nRing size: \", ringSize)\n\n\t// init node\n\tfmt.Println(\"\\nCreating node ...\")\n\tchord.ChordNode = &chord.Node{\n\t\tIdentifier: myId,\n\t\tIP: myIp,\n\t}\n\tfmt.Println(\"\\nActivating node ...\")\n\tgo node_listen(myIp)\n\n\t// create / join ring\n\tif ringSize == 0 {\n\t\t// Ring does NOT exists => CREATE ring\n\t\tfmt.Println(\"\\nRing does NOT exists!\\nCreating new ring at \", myIp)\n\t\tchord.ChordNode.CreateNodeAndJoin(nil)\n\t\tfmt.Println(\"New ring successfully created!\")\n\t} else {\n\t\t// Ring EXISTS => JOIN ring\n\t\tfmt.Println(\"\\nRing does EXISTS!\")\n\t\tremoteIp := ipInRing[0]\n\t\tremoteId := chord.Hash(remoteIp)\n\t\tremoteNode := &chord.RemoteNode{\n\t\t\tIdentifier: remoteId,\n\t\t\tIP: remoteIp,\n\t\t}\n\n\t\tchord.ChordNode.IP = myIp\n\t\tchord.ChordNode.Identifier = myId\n\n\t\tfmt.Println(\"Joining ring via \", remoteId, \"(\", remoteIp, \")\")\n\t\tchord.ChordNode.CreateNodeAndJoin(remoteNode)\n\t\tfmt.Println(\"Node \", myId, \" successfully joined ring!\")\n\t}\n\n\tend1 := time.Now()\n\tduration1 := end1.Sub(start1)\n\tfmt.Println(\"Test 1 COMPLETED!!!\\nDuration \", duration1)\n\tfmt.Println(\"------------------------------------------------------------------------------\\n \")\n\tchord.ChordNode.PrintNode()\n}", "func MakeMaster(filePath string, nReduce int) *Master {\n\n\tWriteDataIntoLists(filePath)\n\n\t// fmt.Println(courseList)\n\t// fmt.Println(roomList)\n\t// fmt.Println(timeSlotList)\n\n\tvar firstGeneration []Chrom\n\tfirstGeneration = CreateFirstGeneration(courseList, timeSlotList, roomList)\n\t//fmt.Println(len(firstGeneration))\n\t//PrintGeneration(firstGeneration)\n\t// for _, chrom := range firstGeneration {\n\t// \tfor _, gene := range chrom.genes {\n\t// \t\tPrintGene(gene)\n\t// \t}\n\t// }\n\n\tbestFitValue := float64(0)\n\tbestChromId := 0\n\n\tfor _, chrom := range firstGeneration {\n\t\tif chrom.FitnessScore > bestFitValue {\n\t\t\tbestChromId = chrom.Id\n\t\t\tbestFitValue = chrom.FitnessScore\n\t\t}\n\t}\n\n\tprevGeneration = firstGeneration\n\n\tbestChromInPrevGen := GetBestChromFromGen(prevGeneration)\n\twipGen = append(wipGen, bestChromInPrevGen)\n\tfmt.Println(\"------------------------------\")\n\tPrintGeneration(firstGeneration)\n\tfmt.Println(\"bestFitValue in initial generation is \", bestFitValue, \" chrom id is \", bestChromId)\n\n\tm := Master{}\n\n\tgo Monitor()\n\tm.server()\n\treturn &m\n}", "func connectToMaster(u url.URL, done chan error) {\n\tdefer func() {\n\t\tdone <- errors.New(\"Channel Closed\")\n\t}()\n\n\tlog.Printf(\"connecting to %s\", u.String())\n\n\tconn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)\n\tif err != nil {\n\t\tlog.Println(\"dial:\", err)\n\t\treturn\n\t}\n\tlog.Println(\"connect to master: SUCCESS\")\n\tslave := &BackupSlave{conn: conn, send: make(chan []byte, 256)}\n\tgo slave.writeBackupSlavePump()\n\tslave.readBackupSlavePump()\n\n}", "func New(APIaddr string, requiredUserAgent string, requiredPassword string, nodeParams node.NodeParams, loadStartTime time.Time) (*Server, error) {\n\t// Wait for the node to be done loading.\n\tsrv, errChan := NewAsync(APIaddr, requiredUserAgent, requiredPassword, nodeParams, loadStartTime)\n\tif err := <-errChan; err != nil {\n\t\t// Error occurred during async load. Close all modules.\n\t\tif build.Release == \"standard\" {\n\t\t\tfmt.Println(\"ERROR:\", err)\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn srv, nil\n}", "func Genesis() {\n\tserver.listen()\n\tserver.managePeers()\n}", "func main() {\n\tnode := node.New(\"modbus\")\n\tconfig := NewConfig()\n\n\tnode.OnConfig(updatedConfig(config))\n\twait := node.WaitForFirstConfig()\n\n\terr := node.Connect()\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t\treturn\n\t}\n\tlogrus.Info(\"Waiting for config from server\")\n\terr = wait()\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t\treturn\n\t}\n\n\tmodbusConnection := &Modbus{}\n\tlogrus.Infof(\"Connecting to modbus device: %s\", config.Device)\n\terr = modbusConnection.Connect()\n\n\tif err != nil {\n\t\tlogrus.Error(\"error connecting to modbus: \", err)\n\t\treturn\n\t}\n\n\tdefer modbusConnection.Close()\n\n\tresults, _ := modbusConnection.ReadInputRegister(214)\n\tlog.Println(\"REG_HC_TEMP_IN1: \", results)\n\tresults, _ = modbusConnection.ReadInputRegister(215)\n\tlog.Println(\"REG_HC_TEMP_IN2: \", results)\n\tresults, _ = modbusConnection.ReadInputRegister(216)\n\tlog.Println(\"REG_HC_TEMP_IN3: \", results)\n\tresults, _ = modbusConnection.ReadInputRegister(217)\n\tlog.Println(\"REG_HC_TEMP_IN4: \", results)\n\tresults, _ = modbusConnection.ReadInputRegister(218)\n\tlog.Println(\"REG_HC_TEMP_IN5: \", binary.BigEndian.Uint16(results))\n\tresults, _ = modbusConnection.ReadInputRegister(207)\n\tlog.Println(\"REG_HC_TEMP_LVL: \", results)\n\tresults, _ = modbusConnection.ReadInputRegister(301)\n\tlog.Println(\"REG_DAMPER_PWM: \", results)\n\tresults, _ = modbusConnection.ReadInputRegister(204)\n\tlog.Println(\"REG_HC_WC_SIGNAL: \", results)\n\tresults, _ = modbusConnection.ReadInputRegister(209)\n\tlog.Println(\"REG_HC_TEMP_LVL1-5: \", results)\n\tresults, _ = modbusConnection.ReadInputRegister(101)\n\tlog.Println(\"100 REG_FAN_SPEED_LEVEL: \", results)\n\n\t// connection := basenode.Connect()\n\tdev := &devices.Device{\n\t\tName: \"modbusDevice\",\n\t\tType: \"sensor\", // TODO if we add modbus write support we need to have another type\n\t\tID: devices.ID{ID: \"1\"},\n\t\tOnline: true,\n\t\tTraits: []string{},\n\t\tState: make(devices.State),\n\t}\n\n\tnode.AddOrUpdate(dev)\n\n\t// node.SetState(registers)\n\n\t// This worker recives all incomming commands\n\tticker := time.NewTicker(30 * time.Second)\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif len(config.Registers) == 0 {\n\t\t\t\tlogrus.Info(\"no configured registers to poll yet\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfetchRegisters(config.Registers, modbusConnection)\n\n\t\t\tnewState := make(devices.State)\n\t\t\tfor _, v := range config.Registers {\n\t\t\t\tnewState[v.Name] = v.Value\n\t\t\t}\n\t\t\tnode.UpdateState(dev.ID.ID, newState)\n\t\tcase <-node.Stopped():\n\t\t\tticker.Stop()\n\t\t\tlog.Println(\"Stopping modbus node\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func (m *Master) Start() error {\n\treturn m.start(\"-masterCfg\", join(m.masterRoot, \"master.cfg\"), \"-raftCfg\", join(m.masterRoot, \"raft.cfg\"))\n}", "func init() {\n\tiHub = NewHub()\n}", "func MakeMaster(files []string, nReduce int) *Master {\n\tm := Master{}\n\tm.nMap = len(files)\n\tm.ReduceOutNum = nReduce\n\tm.nReduce = 0\n\t// Your code here.\n\t// init task\n\tm.mapTasks = make([]Task, 0)\n\tm.reduceTasks = make([]Task, 0)\n\tm.reduceTaskFileLists = make([][]string, m.ReduceOutNum)\n\tm.hasGenerateReduceTasks = false\n\tinitMapTaskNum := len(files)\n\tfor i := 0; i < initMapTaskNum; i++ {\n\t\tm.mapTasks = append(m.mapTasks, Task{Id: i, State: GENERATED, TaskKind: MAPTASK, MapTaskFile: files[i]})\n\t}\n\n\tm.server()\n\treturn &m\n}", "func startNodeCommunication(nodeAddress string, bc *Blockchain) {\n\tlistener, err := net.Listen(protocol, nodeAddress)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer listener.Close()\n\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error: %s\\n\", err)\n\t\t}\n\t\tgo handleConnection(conn, bc)\n\t}\n}", "func initClientReader(player *models.Player, host string) {\n\taddr := net.JoinHostPort(host, sendPort)\n\tlog.Printf(\"[Reader] Client is making a connection to %s\", addr)\n\n\tconn, err := net.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Printf(\"[Reader] Client is connected\")\n\n\tgo addNewPlayer(player.Scene, conn)\n}", "func MakeMaster(files []string, nReduce int) *Master {\n\tm := Master{\n\t\tnReduce: nReduce,\n\t\tmapTask: []Task{},\n\t\tmasterState: newMaster,\n\t\tend: false,\n\t}\n\n\t// Your code here.\n\n\tfor i, file := range files {\n\t\tm.mapTask = append(m.mapTask, Task{\n\t\t\tType_: mapTask,\n\t\t\tId: i,\n\t\t\tFilename: file,\n\t\t\tState: initialState,\n\t\t\tNReduce: m.nReduce,\n\t\t})\n\t}\n\n\tgo m.server()\n\treturn &m\n}", "func InitRedis() {\n\tclient = redis.NewClient(&redis.Options{\n\t\tAddr: \"localhost:6379\", //default port of redis-server; lo-host when same machine\n\t})\n\n\ttileClient = redis.NewClient(&redis.Options{\n\t\tAddr: \"127.0.0.1:9851\",\n\t\t// OnConnect: func(conn *redis.Conn) error {\n\t\t//something here if needed on connect\n\t\t// },\n\t})\n\n}", "func (e *Engine) becomeMaster() {\n\te.syncClient.disable()\n\te.notifier.SetSource(config.SourceServer)\n\n\tif err := e.lbInterface.Up(); err != nil {\n\t\tlog.Fatalf(\"Failed to bring LB interface up: %v\", err)\n\t}\n}", "func createNodes(clusterSpec *ClusterSpec, role string, suffixNumberStart int, count int) error {\n\tfor suffix := suffixNumberStart; suffix < suffixNumberStart+count; suffix++ {\n\t\tcontainerID := \"\"\n\t\tvar err error\n\t\tif role == \"agent\" {\n\t\t\tcontainerID, err = createWorker(clusterSpec, suffix)\n\t\t} else if role == \"server\" {\n\t\t\tcontainerID, err = createServer(clusterSpec)\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to create %s-node\", role)\n\t\t\treturn err\n\t\t}\n\t\tlog.Infof(\"Created %s-node with ID %s\", role, containerID)\n\t}\n\treturn nil\n}", "func MakeMaster(files []string, nReduce int) *Master {\n\tm := Master{}\n\tm.inputFiles = files\n\tm.nReduceTasks = nReduce\n\tm.init()\n\n\tm.server()\n\treturn &m\n}" ]
[ "0.66622347", "0.64293945", "0.6145258", "0.60843116", "0.597381", "0.5962286", "0.5953004", "0.5896927", "0.5833437", "0.5825309", "0.5784566", "0.57775766", "0.5761488", "0.5743756", "0.5732949", "0.57158387", "0.56984013", "0.567924", "0.56664616", "0.5651798", "0.56275845", "0.5612432", "0.56040823", "0.559667", "0.5552994", "0.5542132", "0.55356544", "0.5530437", "0.5521687", "0.55215704", "0.5497209", "0.5467055", "0.5459234", "0.5457239", "0.5420649", "0.5407911", "0.54068696", "0.54032975", "0.538186", "0.53771824", "0.5369971", "0.53543395", "0.53487563", "0.5348469", "0.53416467", "0.5339597", "0.5327963", "0.5320998", "0.53204054", "0.5315996", "0.5300286", "0.5285585", "0.5275063", "0.5258566", "0.5257299", "0.52562886", "0.524225", "0.52305627", "0.52220064", "0.52101004", "0.52074796", "0.5205314", "0.5202509", "0.5198643", "0.51969546", "0.51957834", "0.51909006", "0.51877606", "0.51835555", "0.5182104", "0.5176219", "0.5174071", "0.5173699", "0.5172164", "0.5168719", "0.51661956", "0.5149521", "0.51465636", "0.51383805", "0.51346475", "0.5132236", "0.51249546", "0.51221496", "0.51190037", "0.51183265", "0.5117316", "0.5115932", "0.5114561", "0.51095945", "0.51070625", "0.5106652", "0.51034975", "0.5102346", "0.5101894", "0.51018083", "0.50941557", "0.5090593", "0.5089912", "0.5088521", "0.5087975" ]
0.60488987
4
sends a message to every connected worker
func (m *Master) Broadcast(msg *WorkerMessage) { m.nodeMu.RLock() logger.Debug("Broadcast(%v): to %v nodes", *msg, len(m.NodeHandles)) for _, nh := range m.NodeHandles { nh.BroadcastChan <- msg } m.nodeMu.RUnlock() logger.Debug("Broadcast(): done") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func handleMessages(){\r\n\tfor{\r\n\t\t// get next message from broadcast channel\r\n\t\tmsg := <- broadcast\r\n\r\n\t\t// send message to each currently connected client\r\n\t\tfor client := range clients{\r\n\t\t\terr := client.WriteJSON(msg)\r\n\r\n\t\t\tif err != nil{\r\n\t\t\t\tlog.Println(\"@ handleMessages()\");\r\n\t\t\t\tlog.Printf(\"error: %v\", err)\r\n\t\t\t\tclient.Close()\r\n\t\t\t\tdelete(clients, client)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "func (this Client) emit(message interface{}) {\n mu.Lock()\n for _, client := range clients {\n websocket.JSON.Send(client.Websocket, message)\n }\n mu.Unlock()\n}", "func (s *Websocket) broadcast(msg models.Message) {\n\ts.hmu.RLock()\n\n\tfor _, receiver := range s.hub {\n\t\tif err := receiver.Conn.WriteJSON(msg); err != nil {\n\t\t\ts.logger.Errorf(\"error sending message: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t}\n\n\ts.history = append(s.history, msg)\n\tif err := s.historyRepo.Add(msg); err != nil {\n\t\ts.logger.Errorf(\"error writing history to db: %v\", err)\n\t}\n\n\ts.hmu.RUnlock()\n}", "func handleMessages() {\n\tfor {\n\t\tmsg := <-broadcaster\n\n\t\tstoreInRedis(msg)\n\t\tmessageClients(msg)\n\t}\n}", "func (h *Hub) run() {\n\tfor {\n\t\tselect {\n\t\t// register a new client to a specific ws connection\n\t\tcase client := <-h.register:\n\t\t\th.clients[client] = true\n\t\t\tclient.send <- &Message{\n\t\t\t\tbroadcast: []byte(fmt.Sprintf(`{\"id\": \"%s\"}`, client.key)),\n\t\t\t}\n\t\t// de-register existing client\n\t\tcase client := <-h.unregister:\n\t\t\tif _, ok := h.clients[client]; ok {\n\t\t\t\tdelete(h.clients, client)\n\t\t\t\tclose(client.send)\n\t\t\t}\n\t\t// send message to each client\n\t\tcase message := <-h.broadcast:\n\t\t\tfor client := range h.clients {\n\t\t\t\t// don't send to creator of the broadcast\n\t\t\t\tif client.key == message.senderKey {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tselect {\n\t\t\t\tcase client.send <- message:\n\t\t\t\tdefault:\n\t\t\t\t\tclose(client.send)\n\t\t\t\t\tdelete(h.clients, client)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func worker() {\n\tworker, err := zmq4.NewSocket(zmq4.DEALER)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tdefer worker.Close()\n\tworker.Connect(\"inproc://backend\")\n\n\tfor {\n\t\tmsg, err := worker.RecvMessage(0)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\tid, content := pop(msg)\n\n\t\treplies := rand.Intn(5)\n\t\tfor reply := 0; reply < replies; reply++ {\n\t\t\ttime.Sleep(time.Duration(rand.Intn(1000)+1) * time.Millisecond)\n\t\t\tworker.SendMessage(id, content)\n\t\t}\n\t}\n}", "func SendWorker(ch chan RemoteCommandMessage, broadlink broadlinkrm.Broadlink, wg *sync.WaitGroup) {\n\tfor msg := range ch {\n\t\tfor _, cmd := range msg.commands {\n\t\t\tswitch cmd.commandType {\n\t\t\tcase SendCommand:\n\t\t\t\terr := broadlink.Execute(cmd.target, cmd.data)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error executing command: %v\", err)\n\t\t\t\t}\n\t\t\tcase Pause:\n\t\t\t\tinterval, err := strconv.Atoi(cmd.data)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error processing pause interval (%v): %v\", cmd.data, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ttime.Sleep(time.Duration(interval) * time.Millisecond)\n\t\t\tcase shutdown:\n\t\t\t\twg.Done()\n\t\t\t\tlog.Print(\"SendWorker terminated\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (server *Server) Broadcast(msg string) {\n\tfor _, socket := range server.connections {\n\t\tgo func(ws *websocket.Conn) {\n\t\t\twebsocket.Message.Send(ws, msg)\n\t\t}(socket)\n\t}\n}", "func broadcastMessage(msg protocol.Message) {\n\tencoded := msg.Encode()\n\tfor _, c := range clientHolder.GetClients() {\n\t\tc.conn.Write(encoded)\n\t}\n}", "func Worker() {\n\tlog.Println(\"Starting listening for messages to publish to datawarehouse\")\n\tfor {\n\t\tdataToPublish := <- DatawarehouseChannel\n\t\tpublishToDW(dataToPublish.TopicId, dataToPublish.Data, dataToPublish.Info)\n\t\ttime.Sleep(300*time.Second)\n\t}\n}", "func (w *websocketPeer) sendHandler() {\n\tdefer close(w.writerDone)\n\tfor msg := range w.wr {\n\t\tif msg == nil {\n\t\t\treturn\n\t\t}\n\t\tb, err := w.serializer.Serialize(msg.(wamp.Message))\n\t\tif err != nil {\n\t\t\tw.log.Print(err)\n\t\t}\n\n\t\tif err = w.conn.WriteMessage(w.payloadType, b); err != nil {\n\t\t\tif !wamp.IsGoodbyeAck(msg) {\n\t\t\t\tw.log.Print(err)\n\t\t\t}\n\t\t}\n\t}\n}", "func handleMessages() {\n\tfor {\n\t\tmsg := <-broadcast // grab next msg for broadcast\n\t\tfor client := range clients { // send to all clients\n\t\t\terr := client.WriteJSON(msg)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"error: %v\", err)\n\t\t\t\tclient.Close()\n\t\t\t\tdelete(clients, client)\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *connection) sendLoop() {\n\tc.group.Add(1)\n\tvar id int\n\tfor msg := range c.out {\n\t\ttime.Sleep(0)\n\t\tid = int(msg[0])\n\t\tif id == c.myId {\n\t\t\tc.in <- msg\n\t\t} else {\n\t\t\tif id >= len(c.peers) {\n\t\t\t\tgo func() {\n\t\t\t\t\ttime.Sleep(time.Millisecond * 500)\n\t\t\t\t\tc.out <- msg\n\t\t\t\t}()\n\t\t\t} else {\n\t\t\t\tmsg[0] = 1\n\n\t\t\t\twrite(c.peers[id].conn, msg)\n\t\t\t}\n\t\t}\n\t}\n\tc.running = false\n\tc.group.Done()\n\tc.group.Wait()\n\tclose(c.in)\n}", "func (si ServerInstance) SendAll(message Message) {\n\t\n\tsi.clientsMutex.Lock()\n\t\n\tfor id, conn := range si.Clients {\n\t\tencoder := gob.NewEncoder(conn)\n\t\tif err := encoder.Encode(message); err != nil {\n\t\t\tfmt.Printf(\n\t\t\t\t\"Server Error (message encoding ): encoding message = [%v] for sending to client with id = [%v], error = [%v]\\n\",\n\t\t\t\tmessage, id, err)\n\t\t}\n\t}\n\t\n\tsi.clientsMutex.Unlock()\n}", "func wsChanSend() {\n\tlog.Println(\"wschan running...\")\n\ti := 1\n\tfor {\n\t\t// send stuff to clients\n\t\t// TODO: solve multiple clients connecting\n\t\twsChan <- \"test: \" + strconv.Itoa(i)\n\t\ti++\n\t}\n}", "func handleMessages() {\n\tfor {\n\t\t// Grab the next message from the broadcast channel\n\t\tmsg := <-broadcast\n\n\t\t// Send it out to every client that is currently connected\n\t\tfor client := range clients {\n\t\t\terr := client.WriteJSON(msg)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"error: %v\", err)\n\t\t\t\tclient.Close()\n\t\t\t\tdelete(clients, client)\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *client) write() {\n\tfor {\n\t\ttoWrite := <-c.send\n\t\t_ = c.conn.WriteMessage(websocket.BinaryMessage, toWrite)\n\t}\n}", "func broadcast(message string) {\n\tfor _, socket := range server.Sockets() {\n\t\tsocket.Write(message)\n\t}\n}", "func (c *Client) listenWrite() {\n for {\n select {\n\n // send message to the client\n case msg := <-c.ch:\n websocket.JSON.Send(c.ws, msg)\n\n // receive done request\n case <-c.doneCh:\n c.grid.Del(c)\n c.doneCh <- true // for listenRead method\n return\n }\n }\n}", "func broadcastMessage(currentConn *WebSocketConnection, kind, message string) {\n\tfor _, eachConn := range connections {\n\t\tif eachConn == currentConn {\n\t\t\tcontinue\n\t\t}\n\n\t\t//for every connection other than itself, use the WriteJSON method provided by websocket to publish new messages\n\t\teachConn.WriteJSON(SocketResponse{\n\t\t\tFrom: currentConn.Username,\n\t\t\tType: kind,\n\t\t\tMessage: message,\n\t\t})\n\t}\n}", "func broadcast(msg string) {\n\tisBroadcasted[msg] = false\n\tbroadcastMsg := &Message{}\n\tbroadcastMsg.Broadcast = msg\n\tfor _, conn := range connections{\n\t\tgo send(broadcastMsg, conn)\n\t}\n}", "func (w *Worker) write() {\n\tvar id = w.ID\n\n\tw.Swarm.Logchan.Info <- \"Worker [\" + id + \"] started listening to write channel.\"\n\nloop:\n\tfor {\n\t\tw.Swarm.Logchan.Info <- \"Worker [\" + id + \"] listening to write...\"\n\t\tselect {\n\t\tcase <-w.killedWrite:\n\t\t\tbreak loop\n\n\t\tcase data := <-w.WriteData:\n\t\t\tw.Swarm.Logchan.Message <- string(log.NewMessage(id, data, false).JSON())\n\t\t\tw.Writer.WriteString(data)\n\t\t\tw.Writer.Flush()\n\t\t}\n\t}\n\n\tw.Swarm.Logchan.Info <- \"Worker [\" + id + \"] write channel closed.\"\n}", "func (r *Repeater) broadcast(message []byte) error {\n\t// TODO: 1. multithreading 2. asynchronous sending\n\th := r.Hub()\n\tfor client := range h.clients {\n\t\tselect {\n\t\tcase client.send <- message:\n\t\tdefault:\n\t\t\tclose(client.send)\n\t\t\tdelete(h.clients, client)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (h *Hub) run() {\n\tfor {\n\t\tselect {\n\t\tcase client := <-h.register:\n\t\t\th.clients[client] = true\n\t\tcase client := <-h.unregister:\n\t\t\tif _, ok := h.clients[client]; ok {\n\t\t\t\tdelete(h.clients, client)\n\t\t\t\tclose(client.send)\n\t\t\t}\n\t\tcase message := <-h.broadcast:\n\t\t\tfor client := range h.clients {\n\t\t\t\tselect {\n\t\t\t\tcase client.send <- message:\n\t\t\t\tdefault:\n\t\t\t\t\tclose(client.send)\n\t\t\t\t\tdelete(h.clients, client)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *Manager) enrichWorker(workerID int, jobs <-chan *RawMessage, results chan<- result) {\n\tfor j := range jobs {\n\t\tlog.Printf(\"worker %+v started job %+v\", workerID, j.UUID)\n\t\tenrichedItem, err := m.enricher.EnrichMessage(j, time.Now().UTC())\n\t\t// quit app if error isn't nil\n\t\tif err != nil {\n\t\t\tos.Exit(1)\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t\tlog.Printf(\"worker %+v finished job %+v\", workerID, j.UUID)\n\t\tresults <- result{id: workerID, enrichedItem: enrichedItem}\n\t}\n}", "func (c *Channel) SendLoop() {\n\tfor msg := range c.Messages {\n\t\tif !c.Alive {\n\t\t\treturn\n\t\t}\n\t\tc.LogF(\"Sending msg `%s` to `%d` members in `%s`\", msg, len(c.Members), c.GetName())\n\t\tfor _, v := range c.Members {\n\t\t\tv.Write(msg)\n\t\t}\n\t}\n}", "func (lbc *loadBalancerController) worker() {\n\tfor {\n\t\tkey, _ := lbc.queue.Get()\n\t\tglog.Infof(\"Sync triggered by service %v\", key)\n\t\tif err := lbc.sync(false); err != nil {\n\t\t\tglog.Infof(\"Requeuing %v because of error: %v\", key, err)\n\t\t\tlbc.queue.Add(key)\n\t\t} else {\n\t\t\tlbc.queue.Done(key)\n\t\t}\n\t}\n}", "func (this User) broadcast(message interface{}) {\n mu.Lock()\n for _, client := range clients {\n if client.User.Id != this.Id {\n websocket.JSON.Send(client.Websocket, message)\n }\n }\n mu.Unlock()\n}", "func (room *Room) broadcastToClientsInRoom(message []byte) {\n\tfor client := range room.clients {\n\t\tclient.send <- message\n\t}\n}", "func (h *hub) run() {\n for {\n select{\n case s := <- h.register:\n // fmt.Println(\"wild client has appeared in the brush!\")\n clients := h.channels[s.channel]\n if clients == nil {\n clients = make(map[*client]bool)\n h.channels[s.channel] = clients\n }\n h.channels[s.channel][s.client] = true\n //send the latest data for room (empty string if new room)\n //s.client.send <- []byte(contents[s.channel])\n case s := <- h.unregister:\n clients := h.channels[s.channel]\n if clients != nil {\n if _, ok := clients[s.client]; ok{\n delete(clients, s.client)\n close(s.client.send)\n if len(clients) == 0 {\n delete(h.channels, s.channel)\n if len(contents[s.channel]) != 0 {\n //delete contents for channel if no more clients using it.\n delete(contents, s.channel)\n }\n }\n }\n }\n case m := <- h.broadcast:\n clients := h.channels[m.channel]\n // fmt.Println(\"broadcasting message to \", clients, \"data is: \", string(m.data))\n for c := range clients {\n fmt.Println(\"broadcasting message to \", c, \"data is: \", string(m.data))\n select {\n case c.send <- m.data:\n contents[m.channel] = string(m.data)\n default:\n close(c.send)\n delete(clients, c)\n if len(clients) == 0 {\n delete(h.channels, m.channel)\n if len(contents[m.channel]) != 0 {\n //delete contents for channel if no more clients using it.\n delete(contents, m.channel)\n }\n }\n }\n }\n }\n }\n}", "func (w *Worker) Work() {\n\tfor {\n\t\tselect {\n\t\tcase <-w.done:\n\t\t\treturn\n\t\tdefault:\n\t\t\tevent := <-w.channel\n\t\t\tw.writeToBuffer(event)\n\t\t}\n\t}\n}", "func worker(clients <-chan api.Client) {\n\tfor c := range clients {\n\t\tlog.Printf(\"Fetching metrics from %s\", c.GetHost())\n\t\terr := c.FetchInventoryMetrics()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error updating %s: %v\", c.GetHost(), err)\n\t\t}\n\t}\n}", "func (s *Server) Run() {\n\tfor {\n\t\tselect {\n\t\tcase msg := <-s.broadcast:\n\t\t\tfor conn, m := range s.clients {\n\t\t\t\tm.Lock()\n\t\t\t\tconn.WriteMessage(websocket.TextMessage, msg)\n\t\t\t\tm.Unlock()\n\t\t\t}\n\t\tcase conn := <-s.add:\n\t\t\ts.clients[conn] = new(sync.Mutex)\n\t\t\tgo s.listen(conn)\n\t\tcase conn := <-s.del:\n\t\t\tif _, ok := s.clients[conn]; ok {\n\t\t\t\tdelete(s.clients, conn)\n\t\t\t}\n\t\t}\n\t}\n}", "func broadcastMessage(payload _message, logMessage string) {\n\tfor _, v := range peers {\n\t\t// fmt.Println(\"Sending to\", v)\n\t\tgo sendToAddr(payload, v, logMessage)\n\t}\n}", "func (g *game) broadcast(msg []byte) {\n\tfor i := 0; i < len(g.Players); i++ {\n\t\tif g.Players[i].Connection != nil {\n\t\t\tg.Players[i].Connection.Outbound <- msg\n\t\t}\n\t}\n}", "func (h *hub) update() {\n\t//send each channel its client state\n\tfor c := range h.connections {\n\t\tmsg := c.client.GetMessage()\n\t\tc.ws.WriteMessage(websocket.BinaryMessage, msg)\n\t}\n}", "func SendToWorker(job *lib.JobRequest) {\n\tworkChannel <- job\n}", "func (h *Hub) SendAll(messageType int, data []byte) {\n\tlogger.Info.Println(\"message delivered to all:\", string(data), \"message type:\", messageType)\n\tfor client, _ := range h.Clients {\n\t\tclient.WriteMessage(messageType, data)\n\t}\n}", "func (s *senderQueue) send(incoming []byte) {\n\tdefer s.wg.Done()\n\tdefer s.workers.Release()\n\n\tlogging.Debug(s.logger).Log(logging.MessageKey(), \"Sending message...\")\n\n\terr := s.connection.WriteMessage(websocket.BinaryMessage, incoming)\n\tif err != nil {\n\t\tlogging.Error(s.logger, emperror.Context(err)...).\n\t\t\tLog(logging.MessageKey(), \"Failed to send message\",\n\t\t\t\tlogging.ErrorKey(), err.Error(),\n\t\t\t\t\"msg\", string(incoming))\n\t\treturn\n\t}\n\n\tlogging.Debug(s.logger).Log(logging.MessageKey(), \"Message Sent\")\n}", "func sendLoop() {\n\tif currentWebsocket == nil {\n\t\tcolorLog(\"[INFO] BW: No connection, wait for it.\\n\")\n\t\tcmd := <-connectChannel\n\t\tif \"QUIT\" == cmd.Action {\n\t\t\treturn\n\t\t}\n\t}\n\n\tfor {\n\t\tnext, ok := <-toBrowserChannel\n\t\tif !ok {\n\t\t\tcolorLog(\"[WARN] BW: Send channel was closed.\\n\")\n\t\t\tbreak\n\t\t}\n\n\t\tif \"QUIT\" == next.Action {\n\t\t\tbreak\n\t\t}\n\n\t\tif currentWebsocket == nil {\n\t\t\tcolorLog(\"[INFO] BW: No connection, wait for it.\\n\")\n\t\t\tcmd := <-connectChannel\n\t\t\tif \"QUIT\" == cmd.Action {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\twebsocket.JSON.Send(currentWebsocket, &next)\n\t\tcolorLog(\"[SUCC] BW: Sent %v.\\n\", next)\n\t}\n\n\tcolorLog(\"[WARN] BW: Exit send loop.\\n\")\n}", "func (s *Server) Fire(data []byte) error {\n\tfor _, w := range s.workers {\n\t\t_, err := w.Write(data)\n\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func MsgServer(ws *websocket.Conn) {\r\n\tvar message string\r\n\t// all.(ws)\r\n\talive := true\r\n\tallconnections = append(allconnections, ws)\r\n\tfor {\r\n\t\twebsocket.Message.Receive(ws, &message)\r\n\t\tfor i, aWs := range allconnections {\r\n\r\n\t\t\tif _, err := aWs.Write([]byte(message)); err != nil {\r\n\t\t\t\tlog.Println(\"Error!!: \", err)\r\n\t\t\t\taWs.Close()\r\n\t\t\t\tallconnections = remove(allconnections, i)\r\n\t\t\t\talive = false\r\n\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t\tlog.Println(\"I hope I didn't crash: \")\r\n\t\tif !alive {\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n}", "func (broker *Broker) Serve(w http.ResponseWriter, flusher http.Flusher) {\n\tmessageChan := make(chan *msg.Msg)\n\tbroker.newClients <- messageChan\n\n\tnotify := w.(http.CloseNotifier).CloseNotify()\n\tgo func() {\n\t\t<-notify\n\t\tclose(messageChan)\n\t}()\n\n\tdefer func() {\n\t\tbroker.closingClients <- messageChan\n\t}()\n\n\tfor _, obj := range broker.cache {\n\t\tsendMsg(w, flusher, msg.New(\"add\", obj))\n\t}\n\n\tpingTicker := time.NewTicker(5 * time.Second)\n\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-pingTicker.C:\n\t\t\tsendText(w, flusher, \"event: ping\")\n\t\tcase m, open := <-messageChan:\n\t\t\tif !open {\n\t\t\t\tbreak loop\n\t\t\t}\n\t\t\tsendMsg(w, flusher, m)\n\t\t}\n\t}\n}", "func (r *Room) BroadcastAll(msg []byte) {\n\tfor _, client := range r.Clients {\n\t\tclient.WriteMessage(msg)\n\t}\n}", "func broadcast(channels []chan message, msg message) {\n\tfor _, channel := range channels {\n\t\tchannel <- msg\n\t}\n}", "func (h *adminHub) Broadcast(message []byte) error {\n\th.RLock()\n\tdefer h.RUnlock()\n\tmsg := NewQueuedMessage(message, true)\n\tfor _, c := range h.connections {\n\t\terr := c.Send(msg)\n\t\tif err != nil {\n\t\t\tlogger.ERROR.Println(err)\n\t\t}\n\t}\n\treturn nil\n}", "func (w *WSHandler) Serve() {\n\tfor {\n\t\tc := w.GetConnection()\n\t\tCONNS[c] = true\n\t\tc.ReadMessage()\n\t}\n}", "func (s *Websocket) system(text string) {\n\tmsg := models.Message{\n\t\tID: 0,\n\t\tSender: \"system\",\n\t\tReceiver: \"\",\n\t\tText: text,\n\t\tCreatedAt: time.Now(),\n\t}\n\n\ts.hmu.RLock()\n\n\tfor _, receiver := range s.hub {\n\t\tif err := receiver.Conn.WriteJSON(msg); err != nil {\n\t\t\ts.logger.Errorf(\"error sending message: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t}\n\n\ts.hmu.RUnlock()\n}", "func worker(id int, games <-chan Game) {\n\tfmt.Printf(\"Worker initialised ID:%v\\n\", id)\n\tfor g := range games {\n\t\tfmt.Printf(\"Worker running ID:%v\\n\", id)\n\t\tplayGame(g)\n\t\tfmt.Printf(\"Worker complete ID:%v\\n\", id)\n\t}\n}", "func (h *mysqlMetricStore) sendmessage() {\n\th.lock.Lock()\n\tdefer h.lock.Unlock()\n\tvar caches = new(MonitorMessageList)\n\tfor _, v := range h.PathCache {\n\t\t_, avg, max := calculate(&v.ResTime)\n\t\tmm := MonitorMessage{\n\t\t\tServiceID: h.ServiceID,\n\t\t\tPort: h.Port,\n\t\t\tMessageType: \"mysql\",\n\t\t\tKey: v.Key,\n\t\t\tHostName: h.HostName,\n\t\t\tCount: v.Count,\n\t\t\tAbnormalCount: v.UnusualCount,\n\t\t\tAverageTime: Round(avg, 2),\n\t\t\tMaxTime: Round(max, 2),\n\t\t\tCumulativeTime: Round(avg*float64(v.Count), 2),\n\t\t}\n\t\tcaches.Add(&mm)\n\t}\n\tsort.Sort(caches)\n\tif caches.Len() > 20 {\n\t\th.monitorMessageManage.Send(caches.Pop(20))\n\t\treturn\n\t}\n\th.monitorMessageManage.Send(caches)\n}", "func (c *Client) writePump() {\n\tfor {\n\t\tmessage, ok := <-c.send\n\t\tfmt.Println(\"new messsage incoming\")\n\n\t\tif !ok {\n\t\t\t// The hub closed the channel.\n\t\t\tfmt.Println(\"error in message\")\n\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\treturn\n\t\t}\n\n\t\tc.conn.WriteMessage(websocket.TextMessage, message)\n\t\tfmt.Println(\"sent message!\")\n\t}\n}", "func (server *Server) send(client *Client) {\n\tdefer client.socket.Close()\n\tencoder := json.NewEncoder(client.socket)\n\tfor {\n\t\tselect {\n\t\tcase job, ok := <-client.data:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tencoder.Encode(job)\n\t\t}\n\t}\n}", "func (c *Client) Send(ch <-chan *Message) error {\n\tfor msg := range ch {\n\t\t_, err := io.WriteString(c.conn, msg.Content)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Client) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t//// Add queued chat messages to the current websocket message.\n\t\t\t//n := len(c.send)\n\t\t\t//for i := 0; i < n; i++ {\n\t\t\t//\tw.Write(newline)\n\t\t\t//\tw.Write(<-c.send)\n\t\t\t//}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (r *Room) broadcastMsg(msg string) {\n\tr.RLock()\n\tdefer r.RUnlock()\n\tfor _, wc := range r.clients {\n\t\tgo func(wc chan<- string) {\n\t\t\twc <- msg\n\t\t}(wc)\n\t}\n}", "func (h *Hub) SendToAll(data []byte) {\n\th.mux.Lock()\n\tdefer h.mux.Unlock()\n\tfor conn := range h.conns {\n\t\th.Send(conn, data, websocket.TextMessage)\n\t}\n}", "func (broker *Broker) Run() {\n\tfor {\n\t\tselect {\n\t\tcase client := <-broker.Register:\n\t\t\tbroker.Clients[client] = true\n\t\t\tlog.Printf(\"Broker room %s: connect, size %d \", broker.Name, len(broker.Clients))\n\n\t\t\tfor client := range broker.Clients {\n\t\t\t\tclient.Conn.WriteMessage(1, []byte(\"Connected\"))\n\t\t\t}\n\t\t\tbreak\n\t\tcase client := <-broker.Unregister:\n\t\t\tdelete(broker.Clients, client)\n\t\t\tlog.Printf(\"Broker room %s: disconnect, size %d \", broker.Name, len(broker.Clients))\n\t\t\tif len(broker.Clients) == 0 && broker.Room.Status != \"ongoing\" {\n\t\t\t\tdatastore.DeleteGame(broker.Room.RoomCode)\n\t\t\t}\n\n\t\t\tfor client := range broker.Clients {\n\t\t\t\tclient.Conn.WriteMessage(1, []byte(\"Disconnected\"))\n\t\t\t}\n\t\t\tbreak\n\t\tcase move := <-broker.Broadcast:\n\t\t\tlog.Printf(\"Broker room %s, Move received: %+v\\n\", broker.Name, move)\n\t\t\t// Process move according to game rules and update state\n\t\t\tbroker.Room = rules.ProcessRules(move, broker.Room)\n\t\t\t// Save game state after the move is processed\n\t\t\tdatastore.UpdateGame(broker.Room)\n\n\t\t\tfor client := range broker.Clients {\n\t\t\t\tif err := client.Conn.WriteJSON(broker.Room); err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *Server) Worker(queue *Queue, srv Server_SubscribeServer) {\n\t// temp imitate unsibscribe\n\tvar exit = make(chan (struct{}))\n\ttime.AfterFunc(time.Second*10, func() { exit <- struct{}{} })\n\n\tfor {\n\t\tselect {\n\t\tcase <-exit:\n\t\t\tfmt.Println(\"Exit\")\n\t\t\ts.wg.Done()\n\t\t\treturn\n\t\tdefault:\n\t\t\tif queue.messages.Len() > 0 {\n\t\t\t\tel := queue.messages.Back()\n\t\t\t\tval := el.Value\n\n\t\t\t\tmessage, ok := val.(*Message)\n\t\t\t\tif ok {\n\t\t\t\t\tresp := &SubscribeResponse{QueueName: queue.queueName, Message: message}\n\n\t\t\t\t\tif err := srv.Send(resp); err != nil {\n\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tqueue.messages.Remove(el)\n\t\t\t}\n\t\t}\n\t}\n\n}", "func (b *base) broadcast(message *socket.RawMessage) {\n\tfor i := range b.connections {\n\t\tsocket.SendQueueMessageSocketID(*message, b.connections[i].socketID)\n\t}\n\tlog.Printf(\"[Match] -> Message %d broadcasted, Match: %s\", message.MessageType, b.info.ID)\n}", "func (c *client) send() {\nLoop:\n\tfor {\n\t\tmsg, err := readInput(c.Conn, \"\")\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tif msg == \"/quit\" {\n\t\t\tc.close()\n\t\t\tlog.Printf(\"%v has left..\", c.Name)\n\t\t\tbreak Loop\n\t\t}\n\n\t\t// Check if the message is a command.\n\t\tif c.command(msg) {\n\t\t\t// If the client is currently not connected to a room\n\t\t\tif c.Room == \"\"{\n\t\t\t\tlog.Printf(\"Error: \" + c.Name + \" is not in a room\")\n\t\t\t\twriteFormattedMsg(c.Conn, \"You are currently not in a room, please join a room.\")\n\t\t\t}else {\n\t\t\t\t// Client is connected to a room and the input is a regular message.\n\t\t\t\tlog.Printf(\"send: msg: %v from: %s\", msg, c.Name)\n\t\t\t\tsend := time.Now().Format(customTime) + \" * (\" + c.Name + \"): \\\"\" + msg + \"\\\"\"\n\n\t\t\t\t// Add message to the chat rooms history.\n\t\t\t\troomList[c.Room].history = append(roomList[c.Room].history, send)\n\n\t\t\t\t// Send out message to all clients connected to the current room.\n\t\t\t\tfor _, v := range roomList {\n\t\t\t\t\tfor k := range v.members {\n\t\t\t\t\t\tif k == c.Conn.RemoteAddr().String() {\n\t\t\t\t\t\t\tv.messages <- send\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *Server) broadcast(ctx context.Context) {\n\tfor res := range s.Broadcast {\n\t\ts.Clients.Broadcast(res)\n\t}\n}", "func (c *ControlConsumer) Send(message *ControlMessage) error {\n\n\tfor _, channel := range c.Channels {\n\t\tchannel <- message\n\t}\n\n\treturn nil\n}", "func (c *Client) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.ws.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\t// spew.Dump(c.clientID)\n\t\t\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.ws.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.ws.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tw.Write(newline)\n\t\t\t\tw.Write(<-c.send)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.ws.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Client) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tw.Write(newline)\n\t\t\t\tw.Write(<-c.send)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *MultiClusterController) worker() {\n\tfor c.processNextWorkItem() {\n\t}\n}", "func worker(worker int){\n\t// Recibir string del channel\n\tvalor := <- recursos\n\n\t//Imprimir el valor\n\tfmt.Printf(\"Worker: %d : %s\\n\", worker, valor)\n\n\t//Poner el string de regreso\n\trecursos <- valor\n}", "func (m *ConnManager) Broadcast(conn *websocket.Conn, msg *Message) {\n\tm.Foreach(func(k, v interface{}) {\n\t\tif c, ok := v.(*websocket.Conn); ok && c != conn {\n\t\t\tif err := websocket.JSON.Send(c, msg); err != nil {\n\t\t\t\tfmt.Println(\"Send msg error: \", err)\n\t\t\t}\n\t\t}\n\t})\n}", "func (s *Subscriber) writeMessage() {\n ticker := time.NewTicker(pingPeriod)\n defer func() {\n ticker.Stop()\n s.close()\n }()\n for {\n select {\n case m, ok := <- s.send:\n if !ok {\n s.write(websocket.CloseMessage, []byte{})\n return\n }\n if err := s.write(websocket.TextMessage, m); err != nil {\n return\n }\n case <-ticker.C:\n if err := s.write(websocket.PingMessage, []byte{}); err != nil {\n return\n }\n }\n }\n}", "func sendMessageAll(conn net.Conn, mess string) {\n\tfor key := range connMap {\n\t\tif connMap[key] != conn {\n\t\t\tconnMap[key].Write([]byte(\"TCCHAT_BCAST\\t\" + userMap[conn] + \"\\t\" + mess + \"\\n\"))\n\t\t}\n\t}\n}", "func (a *API) Notify(userID uint, msg *model.Message) {\n\tif clients, ok := a.getClients(userID); ok {\n\t\tgo func() {\n\t\t\tfor _, c := range clients {\n\t\t\t\tc.write <- msg\n\t\t\t}\n\t\t}()\n\t}\n}", "func websocketEventLoop(s *state.State) {\n\tfor {\n\t\tdata := <-s.Data\n\t\tfor client := range clients {\n\t\t\t// send data in separate go routine\n\t\t\tgo func(s *state.State, clients map[*websocket.Conn]bool, client *websocket.Conn, data []byte) {\n\t\t\t\terr := client.WriteMessage(websocket.TextMessage, data)\n\t\t\t\tif err != nil {\n\t\t\t\t\ts.Log.Warnln(\"[websocket] error sending message to client\", err)\n\t\t\t\t\tdelete(clients, client)\n\t\t\t\t}\n\t\t\t}(s, clients, client, data)\n\t\t}\n\t}\n}", "func (w *Worker) Run() {\n\tconn := w.Pool.Get()\n\tdefer conn.Close()\n\n\tvar msgs = make([]Impression, 0, w.Size)\n\ttick := time.NewTicker(w.Interval)\n\n\tw.verbose(\"active\")\n\n\tfor {\n\t\tselect {\n\t\tcase msg := <-w.Queue:\n\t\t\tw.verbose(\"buffer (%d/%d) %v\", len(msgs), w.Size, msg)\n\t\t\tmsgs = append(msgs, msg)\n\t\t\tif len(msgs) >= w.Size {\n\t\t\t\tw.verbose(\"exceeded %d messages – flushing\", w.Size)\n\t\t\t\tw.send(conn, msgs)\n\t\t\t\tmsgs = make([]Impression, 0, w.Size)\n\t\t\t}\n\t\tcase <-tick.C:\n\t\t\tif len(msgs) > 0 {\n\t\t\t\tw.verbose(\"interval reached - flushing %d\", len(msgs))\n\t\t\t\tw.send(conn, msgs)\n\t\t\t\tmsgs = make([]Impression, 0, w.Size)\n\t\t\t} else {\n\t\t\t\tw.verbose(\"interval reached – nothing to send\")\n\t\t\t}\n\t\tcase <-w.quit:\n\t\t\ttick.Stop()\n\t\t\tw.verbose(\"exit requested – draining msgs\")\n\t\t\t// drain the msg channel.\n\t\t\tfor msg := range w.Queue {\n\t\t\t\tw.verbose(\"buffer (%d/%d) %v\", len(msgs), w.Size, msg)\n\t\t\t\tmsgs = append(msgs, msg)\n\t\t\t}\n\t\t\tw.verbose(\"exit requested – flushing %d\", len(msgs))\n\t\t\tw.send(conn, msgs)\n\t\t\tw.verbose(\"exit\")\n\t\t\tw.shutdown <- struct{}{}\n\t\t\treturn\n\t\t}\n\t}\n}", "func (r *Room) SendBroadcast(msg Message) {\n\tfor _, client := range r.clients {\n\t\tclient.WriteMessage(msg)\n\t}\n}", "func runWorker(ch <-chan func()) {\n\tfor {\n\t\tf := <-ch\n\t\tf()\n\t}\n}", "func (c *Client) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tfmt.Println(\"Closing writePump\")\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tif !c.isAlive {\n\t\t\t\tfmt.Printf(\"Channel closed\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tw.Write(newline)\n\t\t\t\tw.Write(<-c.send)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Connection) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tw.Write(<-c.send)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func worker() {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase job := <-jobs:\n\t\t\t\tupdate(job)\n\t\t\t}\n\t\t}\n\t}()\n}", "func (c *Client) Run() {\n\tfor {\n\t\tselect {\n\t\tcase conn := <-c.register:\n\t\t\tc.connections[conn] = true\n\t\t\tgo conn.writePump()\n\t\t\tgo conn.readPump()\n\t\tcase conn := <-c.unregister:\n\t\t\tif _, ok := c.connections[conn]; ok {\n\t\t\t\tdelete(c.connections, conn)\n\t\t\t\tclose(conn.send)\n\t\t\t\tif len(c.connections) <= 0 {\n\t\t\t\t\tc.hub.unregister <- c.id\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\tcase incomingMessage := <-c.outbox:\n\t\t\tc.hub.messages <- incomingMessage\n\t\tcase outcomingMessage := <-c.inbox:\n\t\t\tfor conn := range c.connections {\n\t\t\t\tmsgBytes, err := outcomingMessage.GetData()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"invalid message data\")\n\t\t\t\t} else {\n\t\t\t\t\tconn.send <- msgBytes\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n}", "func ws_SendMsg(ws *websocket.Conn, send_channel SendChannel) {\n\tfor {\n\t\tselect {\n\t\tcase send_msg := <-send_channel.containers:\n\t\t\tlog.Printf(\"[%s] containers sendMessage= \", __FILE__, send_msg)\n\t\t\twebsocket.JSON.Send(ws, send_msg)\n\t\tcase send_msg := <-send_channel.updateinfo:\n\t\t\tlog.Printf(\"[%s] update sendMessage=\", __FILE__, send_msg)\n\t\t}\n\t}\n}", "func echo() {\n\tfor {\n\t\tval := <-broadcast\n\t\t// latlong := fmt.Sprintf(\"%f %f %s\", val.Lat, val.Long)\n\t\t// send to every client that is currently connected\n\t\tfor client := range clients {\n\t\t\terr := client.WriteMessage(websocket.TextMessage, []byte(val))\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Websocket error: %s\", err)\n\t\t\t\tclient.Close()\n\t\t\t\tdelete(clients, client)\n\t\t\t}\n\t\t}\n\t}\n}", "func runMessaging(ctx context.Context, wg *sync.WaitGroup, n *Node) {\n\n\tdefer wg.Done()\n\n\tfor _, client := range n.messaging.clients {\n\t\twg.Add(1)\n\t\tgo client.run(ctx, wg, n)\n\t}\n\n\twg.Add(1)\n\tgo n.messaging.server.run(ctx, wg, n)\n\n}", "func (c *UserClientWS) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\t/*n := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tw.Write(newline)\n\t\t\t\tw.Write(<-c.send)\n\t\t\t}*/\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *TCPServer) broadcast(msg *Msg) {\n\tlog.Printf(\"p2p server: broadcasting %s message to peers\\n\", msg.Mtype)\n\tfor _, p := range s.peers {\n\t\tselect {\n\t\tcase p.in <- msg:\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (hub *Hub) Run() () {\n\tfor {\n\t\tselect {\n\t\t\tcase conn := <- hub.Register:\n\t\t\t\tif oldConn, ok := hub.Clients[conn.Id]; ok {\n\t\t\t\t\t_ = oldConn.Conn.Close()\n\t\t\t\t}\n\t\t\t\thub.Clients[conn.Id] = conn\n\t\t\t\tfmt.Println(\"registering a client \" + conn.Id)\n\n\t\t\tcase conn := <- hub.Unregister:\n\t\t\t\tif oldConn, ok := hub.Clients[conn.Id]; ok {\n\t\t\t\t\t_ = oldConn.Conn.Close()\n\t\t\t\t}\n\n\t\t\tcase messageToSend := <- hub.Broadcast:\n\t\t\t\t/*\n\t\t\t\t\tfirst look for the client connection from the dictionary\n\t\t\t\t\tif there is such connection send to the user\n\t\t\t\t */\n\t\t\t\tif conn, ok := hub.Clients[messageToSend.ReceiverId]; ok {\n\t\t\t\t\t/*\n\t\t\t\t\t\tconvert the message to byte and send byte to the receiver connection\n\t\t\t\t\t */\n\t\t\t\t\tif messageByte, err := messageToSend.ConvertToByte(); err != nil {\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\t\tcase conn.Send <- messageByte:\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t\tthis means, an error has occurred while sending a message\n\t\t\t\t\t\t\t\t\t\twhich indicates that the client connection is no more valid\n\t\t\t\t\t\t\t\t\t\tthen remove it from the dictionary\n\t\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t\tclose(conn.Send)\n\t\t\t\t\t\t\t\tdelete(hub.Clients, conn.Id)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\t}\n}", "func (r *Room) broadcastMsg(msg string) {\n\tr.RLock()\n\tdefer r.RUnlock()\n\tfor _, cc := range r.clients {\n\t\tgo func(ch chan<- string) {\n\t\t\tch <- msg\n\t\t}(cc)\n\t}\n}", "func (client *wsClient) writeMessages() {\n\tdefer client.conn.Close()\n\tdefer log.Println(\"writeMessages exiting\")\n\tfor {\n\t\t// Read a message from the outbound channel\n\t\tmsg := <-client.outboundMsgs\n\t\t// Send message to the browser\n\t\terr := client.conn.WriteMessage(websocket.TextMessage, msg)\n\t\tif err != nil {\n\t\t\tlog.Println(\"writeMessages: \", err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func sendAll(count int, c chan int64) {\n\tfor i :=0; i < count; i++ {\n\t\tc <- 1\n\t}\n}", "func (h *wsHub) send(message []byte) {\n\th.broadcast <- message\n}", "func workerTask() {\n\tworker, err := zmq4.NewSocket(zmq4.REQ)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tdefer worker.Close()\n\tworker.Connect(\"ipc://backend.ipc\")\n\tworker.SendMessage(WorkerReady)\n\n\tfor {\n\n\t\tmsg, err := worker.RecvMessage(0)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\n\t\tmsg[len(msg)-1] = \"OK\"\n\t\tworker.SendMessage(msg)\n\t}\n\n}", "func (c *client) write() {\n\tfor msg := range c.send {\n\t\tif err := c.socket.WriteMessage(websocket.TextMessage, msg); err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tc.socket.Close()\n}", "func Worker(conn *websocket.Conn, user *models.User) {\n\n\tg, _ := game.GetGameByID(*user.GameID)\n\n\tdefer game.DeleteGame(g)\n\tplayer := g.Player1\n\n\tif g.Player1 == user {\n\t\tplayer = g.Player2\n\t}\n\n\tif player == nil {\n\t\treturn\n\t}\n\n\tfor {\n\n\t\tmt, message, err := conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"JSON Parse error user %s info: %#v\", err, user.UserID)\n\t\t\t//delete(clients, ws)\n\t\t\tif g.State == models.RUNNING {\n\t\t\t\tresp := models.GameResp{}\n\t\t\t\tresp.Type = \"opponentLeft\"\n\t\t\t\tplayer.Conn.WriteJSON(resp)\n\t\t\t\tconn.Close()\n\t\t\t\tg.State = models.ABANDONED\n\t\t\t}\n\t\t\tgame.DeleteUser(user)\n\n\t\t\tbreak\n\t\t}\n\t\tlog.Printf(\"message %s\", string(message))\n\t\t/*send the data received to player 2*/\n\t\tif player == nil {\n\t\t\tlog.Println(\"nil player\")\n\t\t} else {\n\t\t\tlog.Printf(\"sending message to %s\", player.UserID)\n\t\t\tplayer.Conn.WriteMessage(mt, []byte(message))\n\t\t}\n\t}\n\n}", "func (s *Socket) WriteMsg() {\r\n\tfor {\r\n\t\tselect {\r\n\t\tcase data := <-s.WriteChan:\r\n\t\t\tpref := intToBytes(len(data))\r\n\t\t\tvar buffer bytes.Buffer\r\n\t\t\tbuffer.Write(pref)\r\n\t\t\tbuffer.Write(data)\r\n\t\t\t_, err := s.Conn.Write(buffer.Bytes())\r\n\t\t\tif err != nil {\r\n\t\t\t\tfmt.Println(\"Send Error,\", err)\r\n\t\t\t}\r\n\t\tcase <-s.Ctx.Done():\r\n\t\t\tfmt.Println(\"Quit WriteMsg()\")\r\n\t\t\treturn\r\n\t\t}\r\n\t}\r\n}", "func (c *Client) worker(workerID string) {\n\tc.wg.Add(1)\n\n\ttimeout := make(chan bool, 1)\n\tloopControl := true\n\n\tgo func() {\n\t\tfor {\n\t\t\tif c.run == false {\n\t\t\t\ttimeout <- true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t}()\n\n\tmq, err := rabbitmq.NewClient(c.mqConfig)\n\tif err != nil {\n\t\tc.log.Sugar().Errorw(\"rabbitmq connect failed\", \"worker_id\", workerID, \"error\", err.Error())\n\t\t<-c.register\n\t\tc.wg.Done()\n\t\ttime.Sleep(time.Millisecond * 5)\n\t\treturn\n\t}\n\tdefer mq.Close()\n\n\tmsgs, err := mq.Consume(\"async_ff_telemetry_queue\", \"\", false, false, false, false, nil)\n\tif err != nil {\n\t\tc.log.Sugar().Errorw(\"queue declare failed\", \"worker_id\", workerID, \"error\", err.Error())\n\t\t<-c.register\n\t\tc.wg.Done()\n\t\ttime.Sleep(time.Millisecond * 5)\n\t\treturn\n\t}\n\n\tc.log.Sugar().Debugw(\"worker started\", \"worker_id\", workerID)\n\n\tfor loopControl {\n\t\tselect {\n\t\tcase <-timeout:\n\t\t\tloopControl = false\n\t\tcase task := <-msgs:\n\t\t\tstart := time.Now().Unix()\n\t\t\tstate := \"good\"\n\n\t\t\tif len(task.Body) < 1 {\n\t\t\t\tstate = \"badmq\"\n\t\t\t\tloopControl = false\n\t\t\t\tc.log.Sugar().Errorw(\"message queue failed\", \"worker_id\", workerID)\n\t\t\t} else {\n\t\t\t\tif err := c.process(&task); err != nil {\n\t\t\t\t\tstate = \"bad\"\n\t\t\t\t\tc.log.Sugar().Errorw(\"task process failed\", \"worker_id\", workerID, \"error\", err.Error())\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttask.Ack(false)\n\n\t\t\tc.log.Sugar().Debugw(\"telemetry processed\", \"worker_id\", workerID)\n\n\t\t\tc.prometheus.IncTelemetryProcessCount(state)\n\t\t\tc.prometheus.ObserveProcessDuration(start)\n\t\t}\n\t}\n\n\tc.log.Sugar().Debugw(\"worker stopped\", \"worker_id\", workerID)\n\n\t<-c.register\n\tc.wg.Done()\n}", "func (client *Client) sendMessage(msg interface{}) {\n\tstr, err := json.Marshal(msg)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\ts := string(str)\n\tmetrics.SendMessage(len(s))\n\tclient.socketTx <- s\n}", "func (s *remoteSealer) notifyWork() {\n\twork := s.currentWork\n\tblob, _ := json.Marshal(work)\n\ts.reqWG.Add(len(s.notifyURLs))\n\tfor _, url := range s.notifyURLs {\n\t\tgo s.sendNotification(s.notifyCtx, url, blob, work)\n\t}\n}", "func (h *Hub) Run() {\n\tfor {\n\t\tselect {\n\t\tcase client := <-h.register:\n\t\t\th.clients[client] = true\n\t\tcase client := <-h.unregister:\n\t\t\tif _, ok := h.clients[client]; ok {\n\t\t\t\tdelete(h.clients, client)\n\t\t\t\tclose(client.send)\n\t\t\t}\n\t\tcase message := <-h.broadcast:\n\t\t\tfor client := range h.clients {\n\t\t\t\tselect {\n\t\t\t\tcase client.send <- message:\n\t\t\t\tdefault:\n\t\t\t\t\tclose(client.send)\n\t\t\t\t\tdelete(h.clients, client)\n\t\t\t\t}\n\t\t\t}\n\t\tcase message := <-h.onMessage:\n\t\t\tvar msg Msg\n\t\t\tjson.NewDecoder(bytes.NewReader(message)).Decode(msg)\n\t\t\tvar fns = h.listeners[msg.Type]\n\n\t\t\tfor _, fn := range fns {\n\t\t\t\tfn(msg.Data)\n\t\t\t}\n\t\t}\n\t}\n}", "func (ls *LogStreamer) worker(ctx context.Context, id int) {\n\tls.logger.Debug(\"[LogStreamer/Worker#%d] Worker is starting...\", id)\n\n\tctx, setStat, done := status.AddSimpleItem(ctx, fmt.Sprintf(\"Log Streamer Worker %d\", id))\n\tdefer done()\n\tsetStat(\"🏃 Starting...\")\n\n\tfor {\n\t\tsetStat(\"⌚️ Waiting for chunk\")\n\n\t\t// Get the next chunk (pointer) from the queue. This will block\n\t\t// until something is returned.\n\t\tchunk := <-ls.queue\n\n\t\t// If the next chunk is nil, then there is no more work to do\n\t\tif chunk == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tsetStat(\"📨 Passing chunk to callback\")\n\n\t\t// Upload the chunk\n\t\terr := ls.callback(ctx, chunk)\n\t\tif err != nil {\n\t\t\tatomic.AddInt32(&ls.chunksFailedCount, 1)\n\n\t\t\tls.logger.Error(\"Giving up on uploading chunk %d, this will result in only a partial build log on Buildkite\", chunk.Order)\n\t\t}\n\n\t\t// Signal to the chunkWaitGroup that this one is done\n\t\tls.chunkWaitGroup.Done()\n\t}\n\n\tls.logger.Debug(\"[LogStreamer/Worker#%d] Worker has shutdown\", id)\n}", "func WsSend(channel, message string) (err error) {\n\tfor cs, _ := range ActiveClients[channel] {\n\t\terr = websocket.Message.Send(cs.websocket, message)\n\t\tif err != nil {\n\t\t\tlog.Println(channel, \"Could not send message to \", cs.clientIP, err.Error())\n\t\t}\n\t}\n\treturn\n}", "func (tcp *Server) Broadcast(msgId int64, data []byte) {\n\tfor _, client := range tcp.clients {\n\t\tclient.AsyncSend(msgId, data)\n\t}\n}", "func (s *Server) SendAll(msg *Message) {\n\ts.sendAllCh <- msg\n}" ]
[ "0.6683119", "0.66107297", "0.6527772", "0.64723986", "0.64621276", "0.64592254", "0.64288116", "0.64274037", "0.6404339", "0.6387626", "0.6385022", "0.63430643", "0.62988806", "0.6289499", "0.6284704", "0.62429345", "0.6237176", "0.62246853", "0.6220611", "0.62152636", "0.62107724", "0.6188203", "0.6145242", "0.6139642", "0.61143434", "0.61128443", "0.60748124", "0.6048376", "0.6046685", "0.60456914", "0.60389274", "0.60296196", "0.6016741", "0.6014323", "0.6006023", "0.6005027", "0.6003027", "0.5979912", "0.5961824", "0.5956678", "0.5943965", "0.59347427", "0.5933835", "0.5932359", "0.5931599", "0.59312373", "0.5929317", "0.59215724", "0.59172827", "0.59142476", "0.59110934", "0.5910548", "0.59105396", "0.58923525", "0.58773994", "0.58685666", "0.5866035", "0.5863875", "0.5861842", "0.5853176", "0.584627", "0.58330846", "0.5828725", "0.5826037", "0.5801187", "0.579863", "0.5797533", "0.5796435", "0.57956207", "0.57952815", "0.5793834", "0.5791517", "0.5790564", "0.5786417", "0.5785801", "0.57843965", "0.5761132", "0.5760728", "0.5742378", "0.5740169", "0.5739339", "0.5735414", "0.5728407", "0.5725174", "0.57228625", "0.572061", "0.57076263", "0.57075876", "0.5707127", "0.56984466", "0.56975186", "0.5694521", "0.5693716", "0.5687227", "0.56780326", "0.5674358", "0.5671931", "0.5668662", "0.56664217", "0.56635284" ]
0.6004114
36
remove node handles from the map used to store them as they disconnect
func (m *Master) RemoveNodeOnDeath(nh *NodeHandle) { logger.Debug("RemoveNodeOnDeath(%v)", nh.NodeId) <-nh.Con.DiedChan m.nodeMu.Lock() delete(m.NodeHandles, nh.NodeId) m.nodeMu.Unlock() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func cbRemoveConnection(hConn C.MQHCONN) {\n\t// Remove all of the hObj values for this hconn\n\tkey := makePartialKey(hConn)\n\tmapLock()\n\tfor k, _ := range cbMap {\n\t\tif strings.HasPrefix(k, key) {\n\t\t\tdelete(cbMap, k)\n\t\t}\n\t}\n\tmapUnlock()\n}", "func (g *Graph) cleanNodes() {\n\tcleaned := []*Node{}\n\n\tfor _, node := range g.Nodes {\n\t\tif node.Kind == \"cm\" || node.Kind == \"secret\" {\n\t\t\t_, isSource := g.linkSources[node.Uid]\n\t\t\tif !isSource {\n\t\t\t\t_, isTarget := g.linkTargets[node.Uid]\n\t\t\t\tif !isTarget {\n\t\t\t\t\t// this node is a cm or secret and is not linked to\n\t\t\t\t\t// anything else\n\t\t\t\t\tdelete(g.nodeMap, node.Uid)\n\t\t\t\t\tdelete(g.nameMap, nodeTitle(node.Kind, node.Name))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcleaned = append(cleaned, node)\n\t}\n\tg.Nodes = cleaned\n}", "func (m *mapReact) Clean() {\n\tm.ro.Lock()\n\tm.ma = make(map[SenderDetachCloser]bool)\n\tm.ro.Unlock()\n}", "func keepNodes(s *srvNodeInfo) {\n\tfor {\n\t\ttime.Sleep(time.Second * time.Duration(DefaultDuration))\n\t\tkillNodes := make([]int32, 0)\n\t\tnmmu.Lock()\n\t\tfor k, eni := range s.nodeMap {\n\t\t\tsub := time.Now().Sub(eni.LastAlive) / time.Second\n\t\t\tif sub > time.Duration(MaxDurationCount*DefaultDuration) {\n\t\t\t\tkillNodes = append(killNodes, k)\n\t\t\t}\n\t\t}\n\n\t\tif len(killNodes) > 0 {\n\t\t\t// remove nodes\n\t\t\t// flush nodelist\n\t\t\tlog.Printf(\"Kill Nodes by SynerexServer Timeout %#v\", killNodes)\n\t\t\tfor _, k := range killNodes {\n\t\t\t\t// we need to remove k from sxProfile\n\t\t\t\tni := s.nodeMap[k]\n\t\t\t\tif ni.NodeType == nodepb.NodeType_SERVER { // remove server from sxProfile\n\t\t\t\t\tfor jj, sv := range sxProfile {\n\t\t\t\t\t\tif sv.NodeId == k {\n\t\t\t\t\t\t\tsxProfile = append(sxProfile[:jj], sxProfile[jj+1:]...)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdelete(s.nodeMap, k)\n\t\t\t}\n\t\t\t// we need to notify killed nodes to synerex server to clean channels\n\t\t\taddPendingNodesToServers(killNodes)\n\t\t}\n\t\tnmmu.Unlock()\n\t\tif len(killNodes) > 0 {\n\t\t\tsaveNodeMap(s)\n\t\t}\n\t}\n}", "func (e *Entry) remove(c connection.Connection) {\n\te.connSync.Lock()\n\tdefer e.connSync.Unlock()\n\tif _, ok := e.idle[c.String()]; ok {\n\t\tc.Remove(e.listener[c.String()])\n\t\tdelete(e.idle, c.String())\n\t\tdelete(e.listener, c.String())\n\t}\n\treturn\n}", "func (h *MapInt16ToUint32) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func (pm partitionMap) cleanup() {\n\tfor ns, partitions := range pm {\n\t\tfor i := range partitions.Replicas {\n\t\t\tfor j := range partitions.Replicas[i] {\n\t\t\t\tpartitions.Replicas[i][j] = nil\n\t\t\t}\n\t\t\tpartitions.Replicas[i] = nil\n\t\t}\n\n\t\tpartitions.Replicas = nil\n\t\tpartitions.regimes = nil\n\n\t\tdelete(pm, ns)\n\t}\n}", "func (o *Overlay) nodeDelete(tok *Token) {\n\ttni, ok := o.instances[tok.ID()]\n\tif !ok {\n\t\tlog.Lvlf2(\"Node %x already gone\", tok.ID())\n\t\treturn\n\t}\n\tlog.Lvl4(\"Closing node\", tok.ID())\n\terr := tni.closeDispatch()\n\tif err != nil {\n\t\tlog.Error(\"Error while closing node:\", err)\n\t}\n\tdelete(o.instances, tok.ID())\n\t// mark it done !\n\to.instancesInfo[tok.ID()] = true\n}", "func DisconnectNodes(parent, child Node) {\n\tparent.DelChild(child)\n\tchild.DelParent(parent)\n}", "func (h *MapInt16ToUint8) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func (h *MapInt16ToUint) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func (h *MapInt16ToUint16) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func delExternalClientBlackholeFromNodes(nodes []v1.Node, routingTable, externalV4, externalV6 string, useV4 bool) {\n\tfor _, node := range nodes {\n\t\tif useV4 {\n\t\t\tout, err := runCommand(containerRuntime, \"exec\", node.Name, \"ip\", \"route\", \"del\", \"blackhole\", externalV4, \"table\", routingTable)\n\t\t\tframework.ExpectNoError(err, fmt.Sprintf(\"failed to delete blackhole route to %s on node %s table %s, out: %s\", externalV4, node.Name, routingTable, out))\n\t\t\tcontinue\n\t\t}\n\t\tout, err := runCommand(containerRuntime, \"exec\", node.Name, \"ip\", \"route\", \"del\", \"blackhole\", externalV6, \"table\", routingTable)\n\t\tframework.ExpectNoError(err, fmt.Sprintf(\"failed to delete blackhole route to %s on node %s table %s, out: %s\", externalV6, node.Name, routingTable, out))\n\t}\n}", "func (n *notifs) ListenSmapChanged() {\n\tif !n.p.ClusterStarted() {\n\t\treturn\n\t}\n\tsmap := n.p.owner.smap.get()\n\tif n.smapVer >= smap.Version {\n\t\treturn\n\t}\n\tn.smapVer = smap.Version\n\n\tn.nls.RLock()\n\tif n.nls.len() == 0 {\n\t\tn.nls.RUnlock()\n\t\treturn\n\t}\n\tvar (\n\t\tremnl = make(map[string]nl.Listener)\n\t\tremid = make(cos.StrKVs)\n\t)\n\tfor uuid, nl := range n.nls.m {\n\t\tnl.RLock()\n\t\tfor sid := range nl.ActiveNotifiers() {\n\t\t\tif node := smap.GetActiveNode(sid); node == nil {\n\t\t\t\tremnl[uuid] = nl\n\t\t\t\tremid[uuid] = sid\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tnl.RUnlock()\n\t}\n\tn.nls.RUnlock()\n\tif len(remnl) == 0 {\n\t\treturn\n\t}\n\tnow := time.Now().UnixNano()\n\tfor uuid, nl := range remnl {\n\t\ts := fmt.Sprintf(\"%s: stop waiting for %s\", n.p.si, nl)\n\t\tsid := remid[uuid]\n\t\terr := &errNodeNotFound{s, sid, n.p.si, smap}\n\t\tnl.Lock()\n\t\tnl.AddErr(err)\n\t\tnl.SetAborted()\n\t\tnl.Unlock()\n\t}\n\tn.fin.Lock()\n\tfor uuid, nl := range remnl {\n\t\tdebug.Assert(nl.UUID() == uuid)\n\t\tn.fin.add(nl, true /*locked*/)\n\t}\n\tn.fin.Unlock()\n\tn.nls.Lock()\n\tfor _, nl := range remnl {\n\t\tn.del(nl, true /*locked*/)\n\t}\n\tn.nls.Unlock()\n\n\tfor uuid, nl := range remnl {\n\t\tnl.Callback(nl, now)\n\t\t// cleanup\n\t\tdelete(remnl, uuid)\n\t\tdelete(remid, uuid)\n\t}\n}", "func (s *nodeSet) remove(tn *treeNode) {\n\tif nPtr, has := s.itemMap[tn]; has {\n\t\tremoveNode(nPtr)\n\t\tdelete(s.itemMap, tn)\n\t}\n}", "func (h *TunnelHandler) Clean() {\n\th.mu.Lock()\n\tremoved := make([]string, 0, len(h.tunnels))\n\tfor id, tunnel := range h.tunnels {\n\t\tselect {\n\t\tcase <-tunnel.chDone:\n\t\t\tremoved = append(removed, id)\n\t\tdefault:\n\t\t}\n\t}\n\th.mu.Unlock()\n\n\tfor _, id := range removed {\n\t\th.remove(id)\n\t}\n}", "func (w *wlockMap) unregister(ino uint64) {\n\tw.Lock()\n\tdefer w.Unlock()\n\n\tr := w.inodeLocks[ino]\n\tr.refCnt--\n\tif r.refCnt == 0 {\n\t\tdelete(w.inodeLocks, ino)\n\t}\n}", "func (pm *Map) Clear() {\n\tpm.root.decref()\n\tpm.root = nil\n}", "func (h *MapInt16ToUint64) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func (diffStore *utxoDiffStore) clearOldEntries() {\n\tdiffStore.mtx.HighPriorityWriteLock()\n\tdefer diffStore.mtx.HighPriorityWriteUnlock()\n\n\tvirtualBlueScore := diffStore.dag.VirtualBlueScore()\n\tminBlueScore := virtualBlueScore - maxBlueScoreDifferenceToKeepLoaded\n\tif maxBlueScoreDifferenceToKeepLoaded > virtualBlueScore {\n\t\tminBlueScore = 0\n\t}\n\n\ttips := diffStore.dag.virtual.tips()\n\n\ttoRemove := make(map[*blockNode]struct{})\n\tfor node := range diffStore.loaded {\n\t\tif node.blueScore < minBlueScore && !tips.contains(node) {\n\t\t\ttoRemove[node] = struct{}{}\n\t\t}\n\t}\n\tfor node := range toRemove {\n\t\tdelete(diffStore.loaded, node)\n\t}\n}", "func removeEdgesFrom(node string, graph map[edge]struct{}) {\n\tfor edge := range graph {\n\t\tif edge.from == node {\n\t\t\tdelete(graph, edge)\n\t\t}\n\t}\n}", "func (s *nodeSet) clear() {\n\ts.head.right = s.tail\n\ts.tail.left = s.head\n\ts.itemMap = make(map[*treeNode]*doubleListNode)\n}", "func (w *Widget) ClearMappings(app gowid.IApp) {\n\tfor k := range w.kmap {\n\t\tdelete(w.kmap, k)\n\t}\n}", "func (h *MapInt16ToUint8) Remove(k int16) {\n\tp := &h.slots[int(k)&h.mask]\n\tvar parent *entryInt16ToUint8\n\tfor e := *p; e != nil; e = e.next {\n\t\tif e.k == k {\n\t\t\tif parent == nil { // head\n\t\t\t\tif e.next == nil { // last in chain\n\t\t\t\t\th.used--\n\t\t\t\t}\n\t\t\t\t*p = e.next\n\t\t\t} else {\n\t\t\t\tparent.next = e.next\n\t\t\t}\n\t\t\th.free(e)\n\t\t\treturn\n\t\t}\n\t\tparent = e\n\t}\n}", "func (hm *MyHashMap) Remove(key int) {\n\tvar prev *Node\n\tentry := hm.Arrays[hm.HashFunc(key)]\n\tfor entry != nil && entry.Key != key {\n\t\tprev = entry\n\t\tentry = entry.Next\n\t}\n\n\tif entry == nil {\n\t\treturn\n\t}\n\n\tif prev == nil {\n\t\thm.Arrays[hm.HashFunc(key)] = entry.Next\n\t} else {\n\t\tprev.Next = entry.Next\n\t}\n\n\treturn\n}", "func (h *MapInt16ToUint32) Remove(k int16) {\n\tp := &h.slots[int(k)&h.mask]\n\tvar parent *entryInt16ToUint32\n\tfor e := *p; e != nil; e = e.next {\n\t\tif e.k == k {\n\t\t\tif parent == nil { // head\n\t\t\t\tif e.next == nil { // last in chain\n\t\t\t\t\th.used--\n\t\t\t\t}\n\t\t\t\t*p = e.next\n\t\t\t} else {\n\t\t\t\tparent.next = e.next\n\t\t\t}\n\t\t\th.free(e)\n\t\t\treturn\n\t\t}\n\t\tparent = e\n\t}\n}", "func (this *MyHashMap) Remove(key int) {\n\thashCode := key % 1111\n\ttemp := &Node{\n\t\t0,\n\t\t0,\n\t\tthis.buckets[hashCode],\n\t}\n\tpre := temp\n\tcur := temp.Next\n\tfor cur != nil {\n\t\tif cur.K == key {\n\t\t\tpre.Next = cur.Next\n\t\t\tbreak\n\t\t}\n\t\tpre, cur = cur, cur.Next\n\t}\n\tthis.buckets[hashCode] = temp.Next\n}", "func deletePathMap(pathMapsPtr *[]n.ApplicationGatewayURLPathMap, resourceID *string) *[]n.ApplicationGatewayURLPathMap {\n\tpathMaps := *pathMapsPtr\n\tdeleteIdx := -1\n\tfor idx, pathMap := range pathMaps {\n\t\tif *pathMap.ID == *resourceID {\n\t\t\tklog.V(5).Infof(\"[brownfield] Deleting %s\", *resourceID)\n\t\t\tdeleteIdx = idx\n\t\t}\n\t}\n\n\tif deleteIdx != -1 {\n\t\tpathMaps[deleteIdx] = pathMaps[len(pathMaps)-1]\n\t\t*pathMapsPtr = pathMaps[:len(pathMaps)-1]\n\t}\n\n\treturn pathMapsPtr\n}", "func (this *MyHashMap) Remove(key int) {\n\tkey = this.hash(key)\n\tif this.ht[key] == nil {\n\t\treturn\n\t}\n\tif this.ht[key].k == key {\n\t\tthis.ht[key] = this.ht[key].next\n\t\treturn\n\t}\n\tfor node := this.ht[key]; node.next != nil; node = node.next {\n\t\tif node.next.k == key {\n\t\t\tnode.next = node.next.next\n\t\t\treturn\n\t\t}\n\t}\n}", "func (this *MyHashMap) Remove(key int) {\n\ti := this.hashKey(key)\n\tnode := &this.list[i]\n\n\tif node.key == key {\n\n\t\tif node.next == nil {\n\t\t\t*node = LinkNode{\n\t\t\t\tvalue: -1,\n\t\t\t}\n\t\t} else {\n\t\t\t*node = *node.next\n\t\t}\n\n\t} else {\n\n\t\tupNode := node\n\n\t\tfor node.next != nil {\n\t\t\tupNode = node\n\t\t\tnode = node.next\n\t\t\tif node.key == key {\n\t\t\t\tupNode.next = node.next\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t}\n\t}\n}", "func (server *Server) remove(client *client) {\n\tserver.clientMutex.Lock()\n\tdefer server.clientMutex.Unlock()\n\n\t// remove the connections from the clients array\n\tfor i, check := range server.clients {\n\t\tif check == client {\n\t\t\tserver.clients = append(server.clients[:i], server.clients[i+1:]...)\n\t\t\tserver.clientIDs = append(server.clientIDs[:i], server.clientIDs[i+1:]...)\n\t\t}\n\t}\n\n\tclient.dataStreamer.CloseConnection()\n}", "func (c *RpcClusterClient) clear(addrs []string) {\n\tc.Lock()\n\tvar rm []*poolWeightClient\n\tfor _, cli := range c.clients {\n\t\tvar has_cli bool\n\t\tfor _, addr := range addrs {\n\t\t\tif cli.endpoint == addr {\n\t\t\t\thas_cli = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !has_cli {\n\t\t\trm = append(rm, cli)\n\t\t} else if cli.errcnt > 0 {\n\t\t\t/*\n\t\t\t\tif cli.weight >= errWeight*uint64(cli.errcnt) {\n\t\t\t\t\tcli.weight -= errWeight * uint64(cli.errcnt)\n\t\t\t\t\tcli.errcnt = 0\n\t\t\t\t\tif c.Len() >= minHeapSize {\n\t\t\t\t\t\t// cli will and only up, so it's ok here.\n\t\t\t\t\t\theap.Fix(c, cli.index)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t*/\n\t\t}\n\t}\n\n\tfor _, cli := range rm {\n\t\t// p will up, down, or not move, so append it to rm list.\n\t\tc.Debugf(\"remove cli: %s\", cli.endpoint)\n\n\t\theap.Remove(c, cli.index)\n\t\tcli.pool.Close()\n\t}\n\tc.Unlock()\n}", "func (e *entry) remove() {\n\te.prev.next = e.next\n\te.next.prev = e.prev\n\te.prev = nil\n\te.next = nil\n}", "func (h *MapInt16ToInt8) Remove(k int16) {\n\tp := &h.slots[int(k)&h.mask]\n\tvar parent *entryInt16ToInt8\n\tfor e := *p; e != nil; e = e.next {\n\t\tif e.k == k {\n\t\t\tif parent == nil { // head\n\t\t\t\tif e.next == nil { // last in chain\n\t\t\t\t\th.used--\n\t\t\t\t}\n\t\t\t\t*p = e.next\n\t\t\t} else {\n\t\t\t\tparent.next = e.next\n\t\t\t}\n\t\t\th.free(e)\n\t\t\treturn\n\t\t}\n\t\tparent = e\n\t}\n}", "func userDisconnect(username string) {\n\tfor key := range connMap {\n\t\tconnMap[key].Write([]byte(\"TCCHAT_USEROUT\\t\" + username + \"\\n\"))\n\t}\n\n\tvar temp = connMap[username] // Temporary copy of the connection associated to *username in connMap\n\tdelete(connMap, username) // Delete the connection associated to *username in connMap\n\tdelete(userMap, temp) // Delete the username associated to the previously deleted connection in userMap\n\tserverShutdown(temp) // Check whether or not to shutdown the server\n}", "func (n *notifier) removeFD(fd int32) {\n\tn.mu.Lock()\n\tdefer n.mu.Unlock()\n\n\t// Remove from map, then from epoll object.\n\tn.waitFD(fd, n.fdMap[fd], 0)\n\tdelete(n.fdMap, fd)\n}", "func (msh *Mesh) handleOrphanBlocks(blk *types.Block) {\n\tmsh.mutex.Lock()\n\tdefer msh.mutex.Unlock()\n\tif _, ok := msh.orphanBlocks[blk.Layer()]; !ok {\n\t\tmsh.orphanBlocks[blk.Layer()] = make(map[types.BlockID]struct{})\n\t}\n\tmsh.orphanBlocks[blk.Layer()][blk.ID()] = struct{}{}\n\tmsh.With().Debug(\"added block to orphans\", blk.ID())\n\tfor _, b := range append(blk.ForDiff, append(blk.AgainstDiff, blk.NeutralDiff...)...) {\n\t\tfor layerID, layermap := range msh.orphanBlocks {\n\t\t\tif _, has := layermap[b]; has {\n\t\t\t\tmsh.With().Debug(\"delete block from orphans\", b)\n\t\t\t\tdelete(layermap, b)\n\t\t\t\tif len(layermap) == 0 {\n\t\t\t\t\tdelete(msh.orphanBlocks, layerID)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}", "func (h *MapInt16ToInt16) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func removeDisconnected(clients []Client) []Client {\n\tj := 0\n\tfor i, client := range clients {\n\t\tselect {\n\t\tcase <-client.DisconnectCh():\n\t\t\t// Unset in backing array.\n\t\t\tclients[i] = nil\n\t\tdefault:\n\t\t\tclients[j] = client\n\t\t\tj++\n\t\t}\n\t}\n\treturn clients[:j]\n}", "func (hs *PeerHandleMapSync) Delete(name string) {\n\ths.Lock()\n\t// TODO-WORKSHOP-STEP-5: This code should remove the handle from the PeerHandleMap based on the key name\n\ths.Unlock()\n\tfmt.Println(\"UserHandle Removed for \", name)\n}", "func (n *node) nodeRemove() {\n\tn.evalTotal = n.evalTotal - n.entry.eval\n\tn.occupied = false\n\tparent := n.parent\n\tfor parent != nil {\n\t\tparent.evalTotal = parent.evalTotal - n.entry.eval\n\t\tparent = parent.parent\n\t}\n}", "func (f *freeClientPool) disconnect(address string) {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tif f.closed {\n\t\treturn\n\t}\n\te := f.addressMap[address]\n\tnow := f.clock.Now()\n\tif !e.connected {\n\t\tlog.Debug(\"Client already disconnected\", \"address\", address)\n\t\treturn\n\t}\n\n\tf.connPool.Remove(e.index)\n\tf.calcLogUsage(e, now)\n\te.connected = false\n\tf.disconnPool.Push(e, -e.logUsage)\n\tlog.Debug(\"Client disconnected\", \"address\", address)\n}", "func (m *mru) evict() {\n\tif len(m.hash) == 0 {\n\t\treturn\n\t}\n\tif len(m.hash) == 1 {\n\t\tnode := m.head\n\t\tm.head = nil\n\t\tm.last = nil\n\t\tdelete(m.hash, node.key)\n\t\treturn\n\t}\n\tdelete(m.hash, m.head.key)\n\tm.head.next.previous = nil\n\tm.head = m.head.next\n}", "func (h *MapInt16ToInt8) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func (h *MapInt16ToUint) Remove(k int16) {\n\tp := &h.slots[int(k)&h.mask]\n\tvar parent *entryInt16ToUint\n\tfor e := *p; e != nil; e = e.next {\n\t\tif e.k == k {\n\t\t\tif parent == nil { // head\n\t\t\t\tif e.next == nil { // last in chain\n\t\t\t\t\th.used--\n\t\t\t\t}\n\t\t\t\t*p = e.next\n\t\t\t} else {\n\t\t\t\tparent.next = e.next\n\t\t\t}\n\t\t\th.free(e)\n\t\t\treturn\n\t\t}\n\t\tparent = e\n\t}\n}", "func (h *MapInt16ToUint16) Remove(k int16) {\n\tp := &h.slots[int(k)&h.mask]\n\tvar parent *entryInt16ToUint16\n\tfor e := *p; e != nil; e = e.next {\n\t\tif e.k == k {\n\t\t\tif parent == nil { // head\n\t\t\t\tif e.next == nil { // last in chain\n\t\t\t\t\th.used--\n\t\t\t\t}\n\t\t\t\t*p = e.next\n\t\t\t} else {\n\t\t\t\tparent.next = e.next\n\t\t\t}\n\t\t\th.free(e)\n\t\t\treturn\n\t\t}\n\t\tparent = e\n\t}\n}", "func (h *MapInt16ToUint64) Remove(k int16) {\n\tp := &h.slots[int(k)&h.mask]\n\tvar parent *entryInt16ToUint64\n\tfor e := *p; e != nil; e = e.next {\n\t\tif e.k == k {\n\t\t\tif parent == nil { // head\n\t\t\t\tif e.next == nil { // last in chain\n\t\t\t\t\th.used--\n\t\t\t\t}\n\t\t\t\t*p = e.next\n\t\t\t} else {\n\t\t\t\tparent.next = e.next\n\t\t\t}\n\t\t\th.free(e)\n\t\t\treturn\n\t\t}\n\t\tparent = e\n\t}\n}", "func (h *MapInt16ToInt32) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func (em edgeMap) remove(from, to *Vertex) error {\n\temMu.Lock()\n\tdefer emMu.Unlock()\n\n\tif em == nil {\n\t\tem = make(edgeMap)\n\t}\n\tif !em.containsLocked(from, to) {\n\t\treturn fmt.Errorf(\"edge (%s, %s) not found\", from.Label, to.Label)\n\t}\n\tdelete(em[from.Label], to.Label)\n\treturn nil\n}", "func RemoveCounterNode(w http.ResponseWriter, r *http.Request) {\n\t//params := mux.Vars(r)\n\tvar node CounterNode\n\t_ = json.NewDecoder(r.Body).Decode(&node)\n\tdelete(counternodes, node.EndPoint)\n\tfmt.Println(\"node removed : \" + node.EndPoint + \" : \" + node.ID)\n\t\n\tw.WriteHeader(http.StatusOK)\n}", "func (h *MapInt16ToInt32) Remove(k int16) {\n\tp := &h.slots[int(k)&h.mask]\n\tvar parent *entryInt16ToInt32\n\tfor e := *p; e != nil; e = e.next {\n\t\tif e.k == k {\n\t\t\tif parent == nil { // head\n\t\t\t\tif e.next == nil { // last in chain\n\t\t\t\t\th.used--\n\t\t\t\t}\n\t\t\t\t*p = e.next\n\t\t\t} else {\n\t\t\t\tparent.next = e.next\n\t\t\t}\n\t\t\th.free(e)\n\t\t\treturn\n\t\t}\n\t\tparent = e\n\t}\n}", "func (this *MyHashMap) Remove(key int) {\n\tindex := this.nodeIndex(key)\n\tv := this.table[index]\n\tif v == nil {\n\t\treturn\n\t}\n\tif v.key == key {\n\t\tthis.table[index] = v.next\n\t\tthis.size--\n\t\treturn\n\t}\n\tfor v != nil && v.next != nil {\n\t\tif v.next.key == key {\n\t\t\tv.next = v.next.next\n\t\t\tthis.size--\n\t\t\treturn\n\t\t}\n\t\tv = v.next\n\t}\n}", "func (r *Registry) Clean(d time.Duration) {\n\tnow := clock.SyncedTime()\n\n\tfor _, v := range r.NodesView() {\n\t\tv.cMutex.Lock()\n\t\t// loop over the conflicts\n\t\tfor id, c := range v.Conflicts {\n\t\t\tif c.Timestamp.Add(d).Before(now) {\n\t\t\t\tdelete(v.Conflicts, id)\n\t\t\t}\n\t\t}\n\t\tv.cMutex.Unlock()\n\n\t\tv.tMutex.Lock()\n\t\t// loop over the timestamps\n\t\tfor id, t := range v.Timestamps {\n\t\t\tif t.Timestamp.Add(d).Before(now) {\n\t\t\t\tdelete(v.Timestamps, id)\n\t\t\t}\n\t\t}\n\t\tv.tMutex.Unlock()\n\t}\n}", "func (s *SignalMonkey) Remove(fn *SignalHandler) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\tfor i, x := range s.handlers {\n\t\tif x.ID == fn.ID {\n\t\t\t// Delete preserving order from here:\n\t\t\t// https://code.google.com/p/go-wiki/wiki/SliceTricks\n\t\t\tcopy(s.handlers[i:], s.handlers[i+1:])\n\t\t\ts.handlers[len(s.handlers)-1] = nil // or the zero value of T\n\t\t\ts.handlers = s.handlers[:len(s.handlers)-1]\n\t\t}\n\t}\n}", "func (h *MapInt16ToInt) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func removeMasterQueue(conn *connection) {\n for e := masterQueue.Front(); e != nil; e = e.Next() {\n curr := e.Value.(*connection)\n if curr == conn {\n masterQueue.Remove(e)\n return\n }\n }\n}", "func (cache *Cache) removeNodeInfoFromList(name string) {\n\tni, ok := cache.nodes[name]\n\tif !ok {\n\t\tklog.Errorf(\"No NodeInfo with name %v found in the cache\", name)\n\t\treturn\n\t}\n\n\tif ni.prev != nil {\n\t\tni.prev.next = ni.next\n\t}\n\tif ni.next != nil {\n\t\tni.next.prev = ni.prev\n\t}\n\t// if the removed item was at the head, we must update the head.\n\tif ni == cache.headNode {\n\t\tcache.headNode = ni.next\n\t}\n\n\tdelete(cache.nodes, name)\n}", "func removeRBDLocks(instance *ec2.Instance) {\n\taddress, found := hosts[instance.InstanceId]\n\tif !found {\n\t\tglog.Errorf(\"The instance: %s was not found in the hosts map\", instance.InstanceId)\n\t\treturn\n\t}\n\tglog.Infof(\"Instance: %s, address: %s, state: %s, checking for locks\", instance.InstanceId, address, instance.State.Name)\n\n\tvar deleted = false\n\n\tfor i := 0; i < 3; i++ {\n\t\terr := rbdClient.UnlockClient(address)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Failed to unlock the images, attempting again if possible\")\n\t\t\t<-time.After(time.Duration(5) * time.Second)\n\t\t}\n\t\tdeleted = true\n\t}\n\n\tif !deleted {\n\t\tglog.Errorf(\"Failed to unlock any images that could have been held by client: %s\", address)\n\t}\n\n\t// step: delete from the hosts map\n\tdelete(hosts, instance.InstanceId)\n}", "func (self *NodeInfoMaps) WatchNodeInfoMap() {\n\t_, _, ch, err := self.zk.GetZkConn().ChildrenW(\"/yundis/nodes\")\n\tif err != nil {\n\t\tlog.Errorf(\"Can not watch path /yundis/nodes, err:%s\", err)\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tevent := <-ch\n\t\t\tlog.Infof(\"node list change, %+v\", event)\n\t\t\tchildren, _, ch1, err1 := self.zk.GetZkConn().ChildrenW(\"/yundis/nodes\")\n\t\t\tif err1 == nil {\n\t\t\t\tch = ch1\n\t\t\t\t//handle the node list change event\n\t\t\t\tlog.Infof(\"node list changed : %s\", children)\n\t\t\t\tinfoMap := self.getNodeInfoMapFromZk()\n\t\t\t\t//change the slotinfo state.\n\t\t\t\tlog.Info(\"The node list changed, begin to change the affected slot's info.\")\n\t\t\t\tself.SetNodeInfoMap(infoMap) //refresh nodeinfo map by new zk data.\n\t\t\t\tself.ModifySlotState(infoMap)\n\t\t\t\tlog.Info(\"Refresh nodeinfo map by new zk data.\")\n\t\t\t} else {\n\t\t\t\tlog.Errorf(\"Can not watching the children of /yundis/nodes, err:%s\", err1)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t}()\n}", "func (h *MapInt16ToInt64) Remove(k int16) {\n\tp := &h.slots[int(k)&h.mask]\n\tvar parent *entryInt16ToInt64\n\tfor e := *p; e != nil; e = e.next {\n\t\tif e.k == k {\n\t\t\tif parent == nil { // head\n\t\t\t\tif e.next == nil { // last in chain\n\t\t\t\t\th.used--\n\t\t\t\t}\n\t\t\t\t*p = e.next\n\t\t\t} else {\n\t\t\t\tparent.next = e.next\n\t\t\t}\n\t\t\th.free(e)\n\t\t\treturn\n\t\t}\n\t\tparent = e\n\t}\n}", "func (server *TcpServer) disconnect(client *Client) {\n\tserver.mutex.Lock()\n\tdefer server.mutex.Unlock()\n\tfor i, check := range server.clients {\n\t\tif check == client {\n\t\t\tserver.clients = append(server.clients[:i], server.clients[i+1:]...)\n\t\t}\n\t}\n\tclient.Close()\n}", "func (r *Raft) removeNode(id uint64) {\n\t// Your Code Here (3A).\n}", "func (r *Raft) removeNode(id uint64) {\n\t// Your Code Here (3A).\n}", "func (h *MapInt16ToInt) Remove(k int16) {\n\tp := &h.slots[int(k)&h.mask]\n\tvar parent *entryInt16ToInt\n\tfor e := *p; e != nil; e = e.next {\n\t\tif e.k == k {\n\t\t\tif parent == nil { // head\n\t\t\t\tif e.next == nil { // last in chain\n\t\t\t\t\th.used--\n\t\t\t\t}\n\t\t\t\t*p = e.next\n\t\t\t} else {\n\t\t\t\tparent.next = e.next\n\t\t\t}\n\t\t\th.free(e)\n\t\t\treturn\n\t\t}\n\t\tparent = e\n\t}\n}", "func (h *MapInt16ToInt64) Clear() {\n\tfor i, e := range h.slots {\n\t\tif e != nil {\n\t\t\tfor e != nil {\n\t\t\t\tn := e.next\n\t\t\t\th.free(e)\n\t\t\t\te = n\n\t\t\t}\n\t\t\th.slots[i] = nil\n\t\t}\n\t}\n\th.used = 0\n}", "func (m *manager) Unsubscribe(nh datapath.NodeHandler) {\n\tm.nodeHandlersMu.Lock()\n\tdelete(m.nodeHandlers, nh)\n\tm.nodeHandlersMu.Unlock()\n}", "func (h *MapInt16ToInt16) Remove(k int16) {\n\tp := &h.slots[int(k)&h.mask]\n\tvar parent *entryInt16ToInt16\n\tfor e := *p; e != nil; e = e.next {\n\t\tif e.k == k {\n\t\t\tif parent == nil { // head\n\t\t\t\tif e.next == nil { // last in chain\n\t\t\t\t\th.used--\n\t\t\t\t}\n\t\t\t\t*p = e.next\n\t\t\t} else {\n\t\t\t\tparent.next = e.next\n\t\t\t}\n\t\t\th.free(e)\n\t\t\treturn\n\t\t}\n\t\tparent = e\n\t}\n}", "func (h *clientHub) Remove(c ClientConn) error {\n\th.Lock()\n\tdefer h.Unlock()\n\n\tuid := c.UID()\n\tuser := c.User()\n\n\tdelete(h.conns, uid)\n\n\t// try to find connection to delete, return early if not found.\n\tif _, ok := h.users[user]; !ok {\n\t\treturn nil\n\t}\n\tif _, ok := h.users[user][uid]; !ok {\n\t\treturn nil\n\t}\n\n\t// actually remove connection from hub.\n\tdelete(h.users[user], uid)\n\n\t// clean up users map if it's needed.\n\tif len(h.users[user]) == 0 {\n\t\tdelete(h.users, user)\n\t}\n\n\treturn nil\n}", "func (server *Server) RemoveClient(socket *websocket.Conn) {\n\tfor i, client := range server.connections {\n\t\tif client == socket {\n\t\t\tserver.connections = append(server.connections[:i], server.connections[i+1:]...)\n\t\t\tsocket.Close()\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (e *neighborEntry) removeLocked() {\n\te.mu.neigh.UpdatedAt = e.cache.nic.stack.clock.NowMonotonic()\n\te.dispatchRemoveEventLocked()\n\t// Set state to unknown to invalidate this entry if it's cached in a Route.\n\te.setStateLocked(Unknown)\n\te.cancelTimerLocked()\n\t// TODO(https://gvisor.dev/issues/5583): test the case where this function is\n\t// called during resolution; that can happen in at least these scenarios:\n\t//\n\t//\t- manual address removal during resolution\n\t//\n\t//\t- neighbor cache eviction during resolution\n\te.notifyCompletionLocked(&tcpip.ErrAborted{})\n}", "func closeAndRemove(f *Flamingo, conn *connection) {\n (*conn.conn).Close()\n f.cmdR.Lock()\n delete(f.cmdR.m,conn.cid)\n f.cmdR.Unlock()\n}", "func (item *MapItem) Remove() {\n\tnext := item.next\n\tprev := item.prev\n\tnext.prev = prev\n\tprev.next = next\n}", "func (c *HttpClusterClient) clear(addrs []string) {\n\tc.Lock()\n\tvar rm []*httpWeightClient\n\tfor _, cli := range c.clients {\n\t\tvar has_cli bool\n\t\tfor _, addr := range addrs {\n\t\t\tif cli.endpoint == addr {\n\t\t\t\thas_cli = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !has_cli {\n\t\t\trm = append(rm, cli)\n\t\t} else if cli.errcnt > 0 {\n\t\t\t/*\n\t\t\t\tif cli.weight >= errWeight*uint64(cli.errcnt) {\n\t\t\t\t\tcli.weight -= errWeight * uint64(cli.errcnt)\n\t\t\t\t\tcli.errcnt = 0\n\t\t\t\t\tif c.Len() >= minHeapSize {\n\t\t\t\t\t\theap.Fix(c, cli.index)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t*/\n\t\t}\n\t}\n\n\tfor _, cli := range rm {\n\t\t// p will up, down, or not move, so append it to rm list.\n\t\theap.Remove(c, cli.index)\n\t}\n\tc.Unlock()\n}", "func (c *HashRing) RemoveNode(elt string) {\n\tc.Lock()\n\tdefer c.Unlock()\n\n\tweight := c.weights[elt]\n\tfor i := 0; i < c.numberOfCubes*weight; i++ {\n\t\tdelete(c.ring, c.generateHash(c.generateKey(elt, i)))\n\t}\n\tdelete(c.members, elt)\n\tdelete(c.weights, elt)\n\tc.updateSortedRing()\n}", "func d18disconnectBranch(node *d18nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func unRegisterTrackerInstance(connStr string) {\n\tmanagedLock.Lock()\n\tdefer managedLock.Unlock()\n\tif managedTrackerInstance[connStr] == nil {\n\t\tlogger.Info(\"tracker instance not exists\")\n\t} else {\n\t\tdelete(managedTrackerInstance, connStr)\n\t}\n}", "func clearMap(store map[string]interface{}) {\n\tfor k := range store {\n\t\tdelete(store, k)\n\t}\n}", "func RemoveFromCircle(node node.Node, circle *treemap.Map) {\n\n\t//Generate a string identifier for redis node\n\tnodeStr := \"localhost:\" + strconv.Itoa(node.Port)\n\n\t//use this string identifier for removing the node from the treemap\n\tcircle.Remove(Hashcode(nodeStr))\n\tfmt.Println(\"Removed Node\", nodeStr, \"Hashcode\", Hashcode(nodeStr))\n}", "func (m MessageDescriptorMap) Cleanup() (deleted []string) {\n\tfor id, descriptor := range m {\n\t\tif !descriptor.Touched() {\n\t\t\tdelete(m, id)\n\t\t\tdeleted = append(deleted, id)\n\t\t}\n\t}\n\treturn\n}", "func d3disconnectBranch(node *d3nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func (n *Node) RemoveDups1() {\n\t// i'm pretty sure this doesn't count as a temp buffer i'm not holding\n\t// data to move from one stop to another\n\tm := make(map[int]struct{})\n\tfor n.Next != nil {\n\t\tif _, ok := m[n.Data]; ok {\n\t\t\t// pointers is needed to make sure data is overwritten\n\t\t\t*n = *deleteNode(n, n.Data)\n\t\t} else {\n\t\t\tm[n.Data] = struct{}{}\n\t\t\tn = n.Next\n\t\t}\n\t}\n}", "func (r *Raft) removeNode(id uint64) {\n\tif _, ok := r.Prs[id]; ok {\n\t\tdelete(r.Prs, id)\n\t\tif r.State == StateLeader {\n\t\t\tr.leaderCommit()\n\t\t}\n\t}\n\tr.PendingConfIndex = None\n}", "func (n *NeighborsTable) Del(nodeID NodeID) {\n\tn.m.Del(uint64(nodeID))\n}", "func d13disconnectBranch(node *d13nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func (hm *MyHashMap) Remove(key int) {\n\tidx := key % len(hm.HMap)\n\tcur, prev := hm.HMap[idx], &HMListNode{Next: hm.HMap[idx]}\n\tfor cur != nil {\n\t\tif cur.Key == key {\n\t\t\tif cur == hm.HMap[idx] {\n\t\t\t\thm.HMap[idx] = cur.Next\n\t\t\t} else {\n\t\t\t\tprev.Next = cur.Next\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tprev, cur = cur, cur.Next\n\t}\n\n}", "func removeNode(n *doc.Node) {\n\t// Check if this node exists.\n\tfor i, v := range localNodes {\n\t\tif n.ImportPath == v.ImportPath {\n\t\t\tlocalNodes = append(localNodes[:i], localNodes[i+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (DummyStore) DeleteMap(key string, fields ...string) error { return nil }", "func (s *Server) removeClient(c *Client) {\n\tc.conn.Close()\n\tfor i, cl := range s.clients {\n\t\tif cl == c {\n\t\t\ts.clients = append(s.clients[0:i], s.clients[i+1:]...)\n\t\t\tlog.Println(\"Client disconnected, \" + strconv.Itoa(len(s.clients)) + \" active clients\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func (tp *Tapestry) RemoveKeysAtNode(t *testing.T, node *Node) {\n\tfor key := range node.blobstore.blobs {\n\n\t\t// delete from Blobs\n\t\tdelete(tp.Blobs, key)\n\n\t\t// delete from Keys\n\t\ttp.RemoveKey(t, key)\n\t}\n}", "func (ns Nodes) Remove() {\n\n}", "func disconnect(a, b *PathNode) {\n\tif a != nil {\n\t\tif a.AdjL == b {\n\t\t\ta.AdjL = nil\n\t\t}\n\t\tif a.AdjR == b {\n\t\t\ta.AdjR = nil\n\t\t}\n\t\tif a.AdjU == b {\n\t\t\ta.AdjU = nil\n\t\t}\n\t\tif a.AdjD == b {\n\t\t\ta.AdjD = nil\n\t\t}\n\t}\n\tif b != nil {\n\t\tif b.AdjL == a {\n\t\t\tb.AdjL = nil\n\t\t}\n\t\tif b.AdjR == a {\n\t\t\tb.AdjR = nil\n\t\t}\n\t\tif b.AdjU == a {\n\t\t\tb.AdjU = nil\n\t\t}\n\t\tif b.AdjD == a {\n\t\t\tb.AdjD = nil\n\t\t}\n\t}\n}", "func (s *Switch) Disconnect(peer p2pcrypto.PublicKey) {\n\ts.inpeersMutex.Lock()\n\tif _, ok := s.inpeers[peer]; ok {\n\t\tdelete(s.inpeers, peer)\n\t\ts.inpeersMutex.Unlock()\n\t\ts.publishDelPeer(peer)\n\t\tmetrics.InboundPeers.Add(-1)\n\t\treturn\n\t}\n\ts.inpeersMutex.Unlock()\n\n\ts.outpeersMutex.Lock()\n\tif _, ok := s.outpeers[peer]; ok {\n\t\tdelete(s.outpeers, peer)\n\t} else {\n\t\ts.outpeersMutex.Unlock()\n\t\treturn\n\t}\n\ts.outpeersMutex.Unlock()\n\ts.publishDelPeer(peer)\n\tmetrics.OutboundPeers.Add(-1)\n\n\t// todo: don't remove if we know this is a valid peer for later\n\t// s.discovery.Remove(peer) // address doesn't matter because we only check dhtid\n\n\tselect {\n\tcase s.morePeersReq <- struct{}{}:\n\tcase <-s.shutdownCtx.Done():\n\t}\n}", "func d12disconnectBranch(node *d12nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func PrivateHandleRemove(rtype uint16) {\n\trtypestr, ok := TypeToString[rtype]\n\tif ok {\n\t\tdelete(TypeToRR, rtype)\n\t\tdelete(TypeToString, rtype)\n\t\tdelete(StringToType, rtypestr)\n\t}\n}", "func (m *metricMap) Reset() {\n\tm.mtx.Lock()\n\tdefer m.mtx.Unlock()\n\n\tfor h := range m.metrics {\n\t\tdelete(m.metrics, h)\n\t}\n}", "func removeNode(node *doubleListNode) {\n\tnode.right.left, node.left.right = node.left, node.right\n}", "func (p *prober) setNodes(added nodeMap, removed nodeMap) {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tfor _, n := range removed {\n\t\tfor elem := range n.Addresses() {\n\t\t\tp.RemoveIP(elem.IP)\n\t\t}\n\t}\n\n\tfor _, n := range added {\n\t\tfor elem, primary := range n.Addresses() {\n\t\t\t_, addr := resolveIP(&n, elem, \"icmp\", primary)\n\t\t\tif addr == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tip := ipString(elem.IP)\n\t\t\tresult := &models.ConnectivityStatus{}\n\t\t\tresult.Status = \"Connection timed out\"\n\t\t\tp.AddIPAddr(addr)\n\t\t\tp.nodes[ip] = n\n\n\t\t\tif p.results[ip] == nil {\n\t\t\t\tp.results[ip] = &models.PathStatus{\n\t\t\t\t\tIP: elem.IP,\n\t\t\t\t}\n\t\t\t}\n\t\t\tp.results[ip].Icmp = result\n\t\t}\n\t}\n}", "func RemoveAllSubscriptionsOnConnect(clientID string) {\n\tsubs := new(map[string]uint8)\n\tkey := fmt.Sprintf(\"chatterbox.client-subs.%s\", clientID)\n\tGlobalRedisClient.Fetch(key, subs)\n\n\tGlobalRedisClient.Delete(key)\n\n\tGlobalSubsLock.Lock()\n\tfor topic := range *subs {\n\t\tdelete(GlobalSubs[topic], clientID)\n\t}\n\tGlobalSubsLock.Unlock()\n\n}", "func (plugin *RouteConfigurator) clearMapping() {\n\tplugin.rtIndexes.Clear()\n\tplugin.rtCachedIndexes.Clear()\n}", "func (this *BlockSyncMgr) delNode(nodeId uint64) {\n\tthis.lock.Lock()\n\tdefer this.lock.Unlock()\n\tdelete(this.nodeWeights, nodeId)\n\tlog.Infof(\"delNode:%d\", nodeId)\n\tif len(this.nodeWeights) == 0 {\n\t\tlog.Warnf(\"no sync nodes\")\n\t}\n\tlog.Infof(\"OnDelNode:%d\", nodeId)\n}", "func (manager *syncerManager) garbageCollectSyncer() {\n\tmanager.mu.Lock()\n\tdefer manager.mu.Unlock()\n\tfor key, syncer := range manager.syncerMap {\n\t\tif syncer.IsStopped() && !syncer.IsShuttingDown() {\n\t\t\tdelete(manager.syncerMap, key)\n\t\t}\n\t}\n}" ]
[ "0.5977338", "0.57795995", "0.5744829", "0.56060827", "0.54988384", "0.5470038", "0.54184693", "0.5405626", "0.53601146", "0.53557134", "0.5353138", "0.53511405", "0.53385425", "0.53376305", "0.52991736", "0.52857304", "0.52746004", "0.52491444", "0.5248946", "0.52391887", "0.52211666", "0.52195567", "0.5209824", "0.52014446", "0.51987416", "0.51982033", "0.51917416", "0.5179001", "0.5176059", "0.5171977", "0.51643246", "0.5162018", "0.51465076", "0.5126317", "0.5117718", "0.51108706", "0.5109058", "0.51070607", "0.51065844", "0.5101831", "0.51010126", "0.51004946", "0.509531", "0.5092984", "0.5091884", "0.50872815", "0.5080025", "0.5076365", "0.507338", "0.507075", "0.5067663", "0.5063134", "0.5061824", "0.50589395", "0.50588167", "0.50572026", "0.5049489", "0.5045787", "0.5024168", "0.5022134", "0.5021074", "0.5013752", "0.5013752", "0.5007843", "0.50078243", "0.5006375", "0.49937114", "0.49878728", "0.49867862", "0.49805558", "0.49793577", "0.4977946", "0.49704283", "0.4954854", "0.4946381", "0.49382722", "0.49192566", "0.49184486", "0.4918102", "0.49158877", "0.4908569", "0.49070686", "0.48898733", "0.48898673", "0.48801115", "0.48787758", "0.48746744", "0.48702085", "0.4866678", "0.4849541", "0.48399064", "0.48375878", "0.4835021", "0.48277363", "0.4810372", "0.48093614", "0.4805234", "0.48040715", "0.48027307", "0.4797449", "0.47941026" ]
0.0
-1
/ The function NewObjectLength calls NewUnaryFunctionBase to create a function named OBJECT_LENGTH with an expression as input.
func NewObjectLength(operand Expression) Function { rv := &ObjectLength{ *NewUnaryFunctionBase("object_length", operand), } rv.expr = rv return rv }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *ObjectLength) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectLength(operands[0])\n\t}\n}", "func (this *ObjectLength) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectLength(operands[0])\n\t}\n}", "func (o *FakeObject) Length() int { return reflect.ValueOf(o.Value).Len() }", "func (String) Length(c *compiler.Compiler, this compiler.Expression) (expression compiler.Expression) {\n\texpression = c.NewExpression()\n\texpression.Type = Integer{}\n\texpression.Go.WriteString(`ctx.CountString(`)\n\texpression.Go.WriteB(this.Go)\n\texpression.Go.WriteString(`)`)\n\treturn expression\n}", "func (this *ObjectLength) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\treturn value.NewValue(float64(len(oa))), nil\n}", "func (this *ObjectLength) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\treturn value.NewValue(float64(len(oa))), nil\n}", "func builtinLen(args ...Object) (Object, error) {\n\tif len(args) != 1 {\n\t\treturn nil, ErrWrongNumArguments\n\t}\n\tswitch arg := args[0].(type) {\n\tcase *Array:\n\t\treturn &Int{Value: int64(len(arg.Value))}, nil\n\tcase *String:\n\t\treturn &Int{Value: int64(len(arg.Value))}, nil\n\tcase *Bytes:\n\t\treturn &Int{Value: int64(len(arg.Value))}, nil\n\tcase *Map:\n\t\treturn &Int{Value: int64(len(arg.Value))}, nil\n\tdefault:\n\t\treturn nil, ErrInvalidArgumentType{\n\t\t\tName: \"first\",\n\t\t\tExpected: \"array/string/bytes/map\",\n\t\t\tFound: arg.TypeName(),\n\t\t}\n\t}\n}", "func (object Object) Length() int {\n\treturn len(object)\n}", "func BlobLength32() LengthTypeInstance {\n return &blobLength32{}\n}", "func (this *ObjectLength) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (this *ObjectLength) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func EvalLength(ev *Evaluator, node *ast.CallExpr) (r *ISEXP) {\n\tTRACE := ev.Trace\n\tif TRACE {\n\t\tprintln(\"Length\")\n\t}\n\tex := node.Args[0]\n\tswitch ex.(type) {\n\tcase *ast.IndexExpr:\n\t\titerator := EvalIndexExpressionToIterator(ev, ex.(*ast.IndexExpr).Index)\n\t\treturn &ISEXP{ValuePos: node.Fun.Pos(), Integer: iterator.Length()}\n\tdefault:\n\t\tval := EvalExpr(ev, node.Args[0])\n\t\treturn &ISEXP{ValuePos: node.Fun.Pos(), Integer: val.Length()}\n\t}\n}", "func BlobLength64() LengthTypeInstance {\n return &blobLength64{}\n}", "func (sequence Sequence) Length(c *Compiler, this Expression) (expression Expression) {\n\treturn SequenceLength(c, this)\n}", "func BlobLength16() LengthTypeInstance {\n return &blobLength16{}\n}", "func (b *Builder) Length() *Builder {\n\tb.p.RegisterTransformation(impl.Length())\n\treturn b\n}", "func Len(obj string, length int, a ...any) {\n\tl := len(obj)\n\n\tif l != length {\n\t\tdefMsg := fmt.Sprintf(assertionMsg+\": got '%d', want '%d'\", l, length)\n\t\tDefault().reportAssertionFault(defMsg, a...)\n\t}\n}", "func len(v Type) int32 {}", "func BlobLength8() LengthTypeInstance {\n return &blobLength8{}\n}", "func NewObjectNames(operand Expression) Function {\n\trv := &ObjectNames{\n\t\t*NewUnaryFunctionBase(\"object_names\", operand),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func NewObjectNames(operand Expression) Function {\n\trv := &ObjectNames{\n\t\t*NewUnaryFunctionBase(\"object_names\", operand),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func (p Path) Length(reference, value interface{}) Path { return p.with(Length, reference, value) }", "func JSONObjLen(conn redis.Conn, key, path string) (res interface{}, err error) {\n\tname, args, _ := CommandBuilder(\"JSON.OBJLEN\", key, path)\n\treturn conn.Do(name, args...)\n}", "func ClosureNewObject(sizeofClosure uint32, object *Object) *Closure {\n\tc_sizeof_closure := (C.guint)(sizeofClosure)\n\n\tc_object := (*C.GObject)(C.NULL)\n\tif object != nil {\n\t\tc_object = (*C.GObject)(object.ToC())\n\t}\n\n\tretC := C.g_closure_new_object(c_sizeof_closure, c_object)\n\tretGo := ClosureNewFromC(unsafe.Pointer(retC))\n\n\treturn retGo\n}", "func (this *ObjectRemove) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectRemove(operands[0], operands[1])\n\t}\n}", "func NewRawDataLength(val int) RawDataLengthField {\n\treturn RawDataLengthField{quickfix.FIXInt(val)}\n}", "func (s *TestSuite) Len(object interface{}, length int, msgAndArgs ...interface{}) {\n\ts.Require().Len(object, length, msgAndArgs...)\n}", "func (this *ObjectLength) Type() value.Type { return value.NUMBER }", "func (this *ObjectLength) Type() value.Type { return value.NUMBER }", "func Length(min int, max int) BuiltInFieldRule {\n\treturn newLengthRule(MsgInvalidLengthFormat, &min, &max)\n}", "func (g *mapGen) genLen() {\n\tg.P(\"func (x *\", g.typeName, \") Len() int {\")\n\t// invalid map\n\tg.P(\"if x.m == nil {\")\n\tg.P(\"return 0\")\n\tg.P(\"}\")\n\t// valid map\n\tg.P(\"return len(*x.m)\")\n\tg.P(\"}\")\n\tg.P()\n}", "func length(i Instruction, ls *LuaState) {\n\ta, b, _ := i.ABC()\n\ta += 1\n\tb += 1\n\n\tluaLen(ls, b)\n\tluaReplace(ls, a)\n}", "func (jz *Jzon) Length() (l int, err error) {\n\tif jz.Type == JzTypeArr {\n\t\treturn len(jz.data.([]*Jzon)), nil\n\t}\n\n\tif jz.Type == JzTypeObj {\n\t\treturn len(jz.data.(map[string]*Jzon)), nil\n\t}\n\n\treturn -1, errors.New(\"expect node of type JzTypeArr or JzTypeObj\" +\n\t\t\", but the real type is \" + typeStrings[jz.Type])\n}", "func rcLength(p *TCompiler, code *TCode) (*value.Value, error) {\n\tvb := p.regGet(code.B)\n\tva := value.NewIntPtr(vb.Length())\n\tp.regSet(code.A, va)\n\tp.moveNext()\n\treturn va, nil\n}", "func (gdt *Vector3) Length() Real {\n\targ0 := gdt.getBase()\n\n\tret := C.go_godot_vector3_length(GDNative.api, arg0)\n\n\treturn Real(ret)\n}", "func (o Args) Len() int { return len(o) }", "func LengthModifier(i interface{}) (interface{}, error) {\n\tswitch v := i.(type) {\n\tcase string:\n\t\treturn len(v), nil\n\tcase float64:\n\t\t// TODO: this is not counting decimal portion\n\t\t// (probably because float error can make it really long for some values)\n\t\treturn getIntLength(int(v)), nil\n\tcase int:\n\t\treturn getIntLength(v), nil\n\tcase int64:\n\t\treturn getInt64Length(v), nil\n\tcase map[string]interface{}:\n\t\treturn len(v), nil\n\tcase []interface{}:\n\t\treturn len(v), nil\n\tcase []string:\n\t\treturn len(v), nil\n\tcase []int:\n\t\treturn len(v), nil\n\tcase []float64:\n\t\treturn len(v), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Invalid type (%v) for len()\", reflect.TypeOf(i))\n\t}\n}", "func Vec3Length(a Vec3) float32", "func (this *ObjectAdd) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectAdd(operands[0], operands[1], operands[2])\n\t}\n}", "func NewBodyLength(val int) BodyLengthField {\n\treturn BodyLengthField{quickfix.FIXInt(val)}\n}", "func (f *Fs) newObjectSizeAndNameOnly(o fs.Object, moName string, size int64) *Object {\n\treturn &Object{\n\t\tObject: o,\n\t\tf: f,\n\t\tmo: nil,\n\t\tmoName: moName,\n\t\tsize: size,\n\t\tmeta: nil,\n\t}\n}", "func (n Number) Length() int {\n\treturn 0\n}", "func (fn *formulaFuncs) LEN(argsList *list.List) formulaArg {\n\tif argsList.Len() != 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"LEN requires 1 string argument\")\n\t}\n\treturn newStringFormulaArg(strconv.Itoa(utf8.RuneCountInString(argsList.Front().Value.(formulaArg).String)))\n}", "func (this *ObjectLength) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectLength) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (*FunctionLength) Name() string {\n\treturn \"function-length\"\n}", "func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool {\n\treturn Len(a.t, object, length, msgAndArgs...)\n}", "func (this *ObjectUnwrap) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectUnwrap(operands[0])\n\t}\n}", "func LengthOfValue(value interface{}) (int, error) {\n\tv := reflect.ValueOf(value)\n\tswitch v.Kind() {\n\tcase reflect.String, reflect.Slice, reflect.Map, reflect.Array:\n\t\treturn v.Len(), nil\n\t}\n\treturn 0, fmt.Errorf(\"cannot get the length of %v\", v.Kind())\n}", "func (t *dataType) Length(n int) *dataType {\n\tt.str.Length(n)\n\treturn t\n}", "func (this *ObjectNames) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectNames(operands[0])\n\t}\n}", "func (this *ObjectNames) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectNames(operands[0])\n\t}\n}", "func (_AccessIndexor *AccessIndexorCaller) GetContentObjectsLength(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _AccessIndexor.contract.Call(opts, &out, \"getContentObjectsLength\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (f *PingFrame) Length(_ protocol.VersionNumber) protocol.ByteCount {\n\treturn 1\n}", "func (s newrelicByName) Len() int { return len(s) }", "func NewFileObject(obj *swift.ObjectOpenFile) (f *FileObject, err error) {\n\tf = &FileObject{obj: obj, loc: 0}\n\tf.length, err = obj.Length()\n\treturn f, err\n}", "func TestLen(t *testing.T) {\n\tv := New(1)\n\tv.Set(0, 2) // has length 2\n\tif v.Len() != 2 {\n\t\tt.Error(\"Len returned a wrong length\")\n\t}\n}", "func NewObjectAdd(first, second, third Expression) Function {\n\trv := &ObjectAdd{\n\t\t*NewTernaryFunctionBase(\"object_add\", first, second, third),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func NewLuaObject(L *lua.State, idx int) *LuaObject {\n tp := L.LTypename(idx)\n L.PushValue(idx)\n ref := L.Ref(lua.LUA_REGISTRYINDEX)\n return &LuaObject{L, ref, tp}\n}", "func (t CreatableRenewers38) Size(version int16) int32 {\n\tvar sz int32\n\tsz += sizeof.String(t.PrincipalType) // PrincipalType\n\tsz += sizeof.String(t.PrincipalName) // PrincipalName\n\treturn sz\n}", "func Len(scope common.Scope, args ...interface{}) interface{} {\n\tif s, ok := args[0].(string); ok {\n\t\treturn int64(len(s))\n\t}\n\treturn 0\n}", "func (t DescribedDelegationTokenRenewer41) Size(version int16) int32 {\n\tvar sz int32\n\tsz += sizeof.String(t.PrincipalType) // PrincipalType\n\tsz += sizeof.String(t.PrincipalName) // PrincipalName\n\treturn sz\n}", "func NewSignatureLength(val int) SignatureLengthField {\n\treturn SignatureLengthField{quickfix.FIXInt(val)}\n}", "func fnLen(ctx Context, doc *JDoc, params []string) interface{} {\n\tstats := ctx.Value(EelTotalStats).(*ServiceStats)\n\tif params == nil || len(params) != 1 {\n\t\tctx.Log().Error(\"error_type\", \"func_len\", \"op\", \"len\", \"cause\", \"wrong_number_of_parameters\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"wrong number of parameters in call to len function\"), \"len\", params})\n\t\treturn nil\n\t}\n\tvar obj interface{}\n\terr := json.Unmarshal([]byte(extractStringParam(params[0])), &obj)\n\tif err != nil {\n\t\treturn len(extractStringParam(params[0]))\n\t}\n\tswitch obj.(type) {\n\tcase []interface{}:\n\t\treturn len(obj.([]interface{}))\n\tcase map[string]interface{}:\n\t\treturn len(obj.(map[string]interface{}))\n\t}\n\treturn 0\n}", "func (d commandDefault) strlen(str string) string {\n\treturn markerLength + strconv.Itoa(len(str))\n}", "func (_BaseAccessControlGroup *BaseAccessControlGroupCaller) GetContentObjectsLength(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _BaseAccessControlGroup.contract.Call(opts, &out, \"getContentObjectsLength\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (this *ObjectPut) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectPut(operands[0], operands[1], operands[2])\n\t}\n}", "func NewObjectRemove(first, second Expression) Function {\n\trv := &ObjectRemove{\n\t\t*NewBinaryFunctionBase(\"object_remove\", first, second),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func Argsize(t *Type) int", "func (b *Base) GetObjectSize(req *GetObjectSizeReq) (*GetObjectSizeResp, error) {\n\treturn nil, ErrFunctionNotSupported\n}", "func (jbobject *JavaLangCharSequence) Length() int {\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"length\", javabind.Int)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn jret.(int)\n}", "func NewPattern(length int) Pattern {\n return Pattern{ length }\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) GetContentObjectsLength(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"getContentObjectsLength\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (node *GoValueNode) Length() (int, error) {\n\tif node.IsArray() || node.IsMap() || node.IsString() {\n\n\t\treturn node.thisValue.Len(), nil\n\t}\n\n\treturn 0, fmt.Errorf(\"this node identified as \\\"%s\\\" is not referencing an array, slice, map or string\", node.IdentifiedAs())\n}", "func (hm HashMap) Len(ctx context.Context) (int64, error) {\n\treq := newRequest(\"*2\\r\\n$4\\r\\nHLEN\\r\\n$\")\n\treq.addString(hm.name)\n\treturn hm.c.cmdInt(ctx, req)\n}", "func (a *Arguments) Len() int {\n\treturn len(a.exprs)\n}", "func CompactLength() LengthTypeInstance {\n return &compactLength{}\n}", "func (jbobject *JavaNioCharBuffer) Length() int {\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"length\", javabind.Int)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn jret.(int)\n}", "func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) bool {\n\tif h, ok := t.(tHelper); ok {\n\t\th.Helper()\n\t}\n\treturn Len(t, object, length, append([]interface{}{msg}, args...)...)\n}", "func (*testObject) MaxHeaderLength() uint16 {\n\treturn 0\n}", "func (f *PathResponseFrame) Length(_ protocol.VersionNumber) protocol.ByteCount {\n\treturn 1 + 8\n}", "func (self *Rectangle) Size1O(output *Point) *Point{\n return &Point{self.Object.Call(\"size\", output)}\n}", "func Sizeof(objs ...interface{}) (sz uint64) {\n\tfor i := range objs {\n\t\tsz += sizeofInternal(reflect.ValueOf(objs[i]), false, 0)\n\t}\n\treturn\n}", "func Sizeof(objs ...interface{}) (sz uint64) {\n\tfor i := range objs {\n\t\tsz += sizeofInternal(reflect.ValueOf(objs[i]), false, 0)\n\t}\n\treturn\n}", "func length(v interface{}) (int, error) {\n\tswitch val := v.(type) {\n\tcase string:\n\t\treturn len(val), nil\n\tcase []interface{}:\n\t\treturn len(val), nil\n\tcase map[string]interface{}:\n\t\treturn len(val), nil\n\tdefault:\n\t\treturn -1, errors.New(\"invalid type for length\")\n\t}\n}", "func (p *PathOptions) length(b *sql.Builder) {\n\tswitch {\n\tcase b.Dialect() == dialect.Postgres:\n\t\tb.WriteString(\"JSONB_ARRAY_LENGTH(\")\n\t\tp.pgTextPath(b)\n\t\tb.WriteByte(')')\n\tcase b.Dialect() == dialect.MySQL:\n\t\tp.mysqlFunc(\"JSON_LENGTH\", b)\n\tdefault:\n\t\tp.mysqlFunc(\"JSON_ARRAY_LENGTH\", b)\n\t}\n}", "func (com *hornComponent) Length() int {\n\treturn 222\n}", "func (this *Dcmp0_Chunk_LiteralBody) LenLiteral() (v int, err error) {\n\tif (this._f_lenLiteral) {\n\t\treturn this.lenLiteral, nil\n\t}\n\ttmp20, err := this.LenLiteralDiv2()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tthis.lenLiteral = int((tmp20 * 2))\n\tthis._f_lenLiteral = true\n\treturn this.lenLiteral, nil\n}", "func (t *BaseType) GetLength(v *Value) int32 {\n\treturn -1\n}", "func (obj object) Len() int {\n\treturn len(obj.keys)\n}", "func Length(i interface{}) (l int, ok bool) {\n\tv, k := preprocess(i)\n\tswitch k {\n\tcase reflect.Map, reflect.Array, reflect.Slice, reflect.String:\n\t\treturn v.Len(), true\n\t}\n\treturn 0, false\n}", "func (objs objectList) Len() int { return len(objs) }", "func (a Vector3) Length() float32 {\n\treturn float32(math.Sqrt(float64(a.X*a.X + a.Y*a.Y + a.Z*a.Z)))\n}", "func (f *Fields) Len() int", "func (v Vector3) Length() float64 {\n\treturn math.Sqrt(math.Pow(float64(v.X), 2) + math.Pow(float64(v.Y), 2) + math.Pow(float64(v.Z), 2))\n}", "func (radius *RADIUS) Len() (int, error) {\n\tn := radiusMinimumRecordSizeInBytes\n\tfor _, v := range radius.Attributes {\n\t\talen, err := attributeValueLength(v.Value)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tn += int(alen) + 2 // Added Type and Length\n\t}\n\treturn n, nil\n}", "func (m *CommandLineOptions) GetMaxObjNameLen() uint64 {\n\tif m != nil {\n\t\treturn m.MaxObjNameLen\n\t}\n\treturn 0\n}", "func (geom Geometry) Length() float64 {\n\tlength := C.OGR_G_Length(geom.cval)\n\treturn float64(length)\n}", "func (a *AdditionalGUTI) GetLen() (len uint16) {}" ]
[ "0.6523122", "0.6523122", "0.5879528", "0.585225", "0.57606673", "0.57606673", "0.57047075", "0.56010866", "0.5507508", "0.5425705", "0.5425705", "0.5403266", "0.53994787", "0.53820825", "0.5202233", "0.5193633", "0.5174063", "0.5164767", "0.5130811", "0.5112785", "0.5112785", "0.51125306", "0.51115525", "0.5045999", "0.5038918", "0.5018331", "0.49812493", "0.4955568", "0.4955568", "0.4924533", "0.48879114", "0.48660207", "0.48533323", "0.48517218", "0.48263907", "0.48063627", "0.48034155", "0.4792094", "0.4780229", "0.47770116", "0.47691065", "0.47645834", "0.47495502", "0.47464165", "0.47464165", "0.47339308", "0.47307196", "0.47216335", "0.47206673", "0.47175813", "0.47097516", "0.47097516", "0.4685058", "0.46848637", "0.4682387", "0.46581316", "0.46441278", "0.46273196", "0.46230918", "0.4620884", "0.45957115", "0.45686087", "0.45605862", "0.45568487", "0.45346886", "0.4529132", "0.4521522", "0.45186362", "0.45169815", "0.44896385", "0.44877398", "0.44843918", "0.44839975", "0.4482648", "0.44656578", "0.4464855", "0.44646165", "0.44629568", "0.4455946", "0.4453374", "0.4453191", "0.44392055", "0.44374666", "0.44374666", "0.44315565", "0.44302744", "0.44215858", "0.4419121", "0.44136137", "0.44115245", "0.4408191", "0.43909854", "0.43904725", "0.43728906", "0.43645683", "0.4360508", "0.43554425", "0.4351833", "0.4349061" ]
0.84461415
1
/ It calls the VisitFunction method by passing in the receiver to and returns the interface. It is a visitor pattern.
func (this *ObjectLength) Accept(visitor Visitor) (interface{}, error) { return visitor.VisitFunction(this) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *NowStr) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (e FunctionCallExpression) Visit(env Environment) Value {\n\treturn NoneValue()\n}", "func (i *InterfaceSet) Visit(n ast.Node) (w ast.Visitor) {\n\tswitch n := n.(type) {\n\tcase *ast.TypeSpec:\n\t\tif data, ok := n.Type.(*ast.InterfaceType); ok {\n\t\t\tr := InterfaceInfo{\n\t\t\t\tMethods: []*Method{},\n\t\t\t}\n\t\t\tmethods := data.Methods.List\n\t\t\tr.Name = n.Name.Name\n\t\t\tr.Doc = n.Doc.Text()\n\n\t\t\tfor _, m := range methods {\n\t\t\t\tfor _, name := range m.Names {\n\t\t\t\t\tr.Methods = append(r.Methods, &Method{\n\t\t\t\t\t\tMethodName: name.Name,\n\t\t\t\t\t\tDoc: m.Doc.Text(),\n\t\t\t\t\t\tParams: getParamList(m.Type.(*ast.FuncType).Params),\n\t\t\t\t\t\tResult: getParamList(m.Type.(*ast.FuncType).Results),\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t}\n\t\t\ti.Interfaces = append(i.Interfaces, r)\n\t\t}\n\t}\n\treturn i\n}", "func FuncInterface(_ T1) {}", "func (this *ExecuteFunction) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitExecuteFunction(this)\n}", "func (this *ObjectValues) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectValues) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectUnwrap) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (r *Resolver) Visitor() generated.VisitorResolver { return &visitorResolver{r} }", "func (this *ObjectInnerValues) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (f VisitorFunc) Visit(node Node, visitType int) error {\n\treturn f(node, visitType)\n}", "func (this *ObjectNames) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectNames) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ClockStr) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *NowMillis) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (statement *FunctionCall) Accept(visitor StatementVisitor) {\n\tvisitor.VisitFunctionCall(statement)\n}", "func (this *ObjectRemove) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *DateDiffStr) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectPairs) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectPairs) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectAdd) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectInnerPairs) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectPut) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (v Value) AsFunction() Callable {\n\treturn v.iface.(Callable)\n}", "func (bf *BuiltInFunc) Call(interpreter *Interpreter, args ...interface{}) interface{} {\n\t// we actually omit the `interpreter` because we already known how\n\t// to convert it into a go function.\n\treturn bf.call(bf.instance, args...)\n}", "func (this *ClockMillis) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (statement *NativeCall) Accept(visitor StatementVisitor) {\n\tvisitor.VisitNativeCall(statement)\n}", "func (this *DatePartStr) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func Visit(node Node, visitor func(Node)) {\n\tReplace(node, func(n Node) Node { visitor(n); return n })\n}", "func (n *Interface) Walk(v walker.Visitor) {\n\tif v.EnterNode(n) == false {\n\t\treturn\n\t}\n\n\tif n.InterfaceName != nil {\n\t\tvv := v.GetChildrenVisitor(\"InterfaceName\")\n\t\tn.InterfaceName.Walk(vv)\n\t}\n\n\tif n.Extends != nil {\n\t\tvv := v.GetChildrenVisitor(\"Extends\")\n\t\tn.Extends.Walk(vv)\n\t}\n\n\tif n.Stmts != nil {\n\t\tvv := v.GetChildrenVisitor(\"Stmts\")\n\t\tfor _, nn := range n.Stmts {\n\t\t\tif nn != nil {\n\t\t\t\tnn.Walk(vv)\n\t\t\t}\n\t\t}\n\t}\n\n\tv.LeaveNode(n)\n}", "func (this *Element) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitElement(this)\n}", "func (*Base) Visit(p ASTPass, node *ast.Node, ctx Context) {\n\n\tf := *(*node).OpenFodder()\n\tp.Fodder(p, &f, ctx)\n\t*(*node).OpenFodder() = f\n\n\tswitch node := (*node).(type) {\n\tcase *ast.Apply:\n\t\tp.Apply(p, node, ctx)\n\tcase *ast.ApplyBrace:\n\t\tp.ApplyBrace(p, node, ctx)\n\tcase *ast.Array:\n\t\tp.Array(p, node, ctx)\n\tcase *ast.ArrayComp:\n\t\tp.ArrayComp(p, node, ctx)\n\tcase *ast.Assert:\n\t\tp.Assert(p, node, ctx)\n\tcase *ast.Binary:\n\t\tp.Binary(p, node, ctx)\n\tcase *ast.Conditional:\n\t\tp.Conditional(p, node, ctx)\n\tcase *ast.Dollar:\n\t\tp.Dollar(p, node, ctx)\n\tcase *ast.Error:\n\t\tp.Error(p, node, ctx)\n\tcase *ast.Function:\n\t\tp.Function(p, node, ctx)\n\tcase *ast.Import:\n\t\tp.Import(p, node, ctx)\n\tcase *ast.ImportStr:\n\t\tp.ImportStr(p, node, ctx)\n\tcase *ast.ImportBin:\n\t\tp.ImportBin(p, node, ctx)\n\tcase *ast.Index:\n\t\tp.Index(p, node, ctx)\n\tcase *ast.InSuper:\n\t\tp.InSuper(p, node, ctx)\n\tcase *ast.LiteralBoolean:\n\t\tp.LiteralBoolean(p, node, ctx)\n\tcase *ast.LiteralNull:\n\t\tp.LiteralNull(p, node, ctx)\n\tcase *ast.LiteralNumber:\n\t\tp.LiteralNumber(p, node, ctx)\n\tcase *ast.LiteralString:\n\t\tp.LiteralString(p, node, ctx)\n\tcase *ast.Local:\n\t\tp.Local(p, node, ctx)\n\tcase *ast.Object:\n\t\tp.Object(p, node, ctx)\n\tcase *ast.ObjectComp:\n\t\tp.ObjectComp(p, node, ctx)\n\tcase *ast.Parens:\n\t\tp.Parens(p, node, ctx)\n\tcase *ast.Self:\n\t\tp.Self(p, node, ctx)\n\tcase *ast.Slice:\n\t\tp.Slice(p, node, ctx)\n\tcase *ast.SuperIndex:\n\t\tp.SuperIndex(p, node, ctx)\n\tcase *ast.Unary:\n\t\tp.Unary(p, node, ctx)\n\tcase *ast.Var:\n\t\tp.Var(p, node, ctx)\n\t}\n}", "func (this *StrToZoneName) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func Visit(visitor func(funcName string, backend TemplateFunc)) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tfor funcName, backend := range backends {\n\t\tvisitor(funcName, backend)\n\t}\n}", "func (this *DateDiffMillis) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *StrToUTC) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (u Unary) Accept(interpreter *Interpreter) Object {\n\treturn interpreter.visitUnary(u)\n}", "func (v *FuncVisitor) Visit(node ast.Node) ast.Visitor {\n\tswitch n := node.(type) {\n\tcase *ast.FuncDecl:\n\t\tif n.Body == nil {\n\t\t\t// Do not count declarations of assembly functions.\n\t\t\tbreak\n\t\t}\n\t\tstart := v.fset.Position(n.Pos())\n\t\tend := v.fset.Position(n.End())\n\n\t\tfe := &FuncExtent{\n\t\t\tName: v.signature(n),\n\t\t\tDecl: n,\n\t\t\tstartLine: start.Line,\n\t\t\tstartCol: start.Column,\n\t\t\tendLine: end.Line,\n\t\t\tendCol: end.Column,\n\t\t\tOffset: start.Offset,\n\t\t\tEnd: end.Offset,\n\t\t}\n\t\tv.funcs = append(v.funcs, fe)\n\t}\n\treturn v\n}", "func (this *DateAddStr) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *MillisToStr) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *Mod) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitMod(this)\n}", "func (this *StrToMillis) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (b Binary) Accept(interpreter *Interpreter) Object {\n\treturn interpreter.visitBinary(b)\n}", "func (this *MillisToUTC) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (v visitor) Visit(n ast.Node) ast.Visitor {\n\tif n == nil {\n\t\treturn nil\n\t}\n\n\tif ShouldPrintAbstractSyntaxTree {\n\t\tfmt.Printf(\"%s%T\\n\", strings.Repeat(\"\\t\", int(v)), n)\n\t\tfmt.Printf(\"%d\", v)\n\n\t\treturn v + 1\n\t}\n\n\tswitch d := n.(type) {\n\tcase *ast.Ident:\n\t\tif d.Obj == nil {\n\t\t\treturn v + 1\n\t\t}\n\n\t\tif d.Obj.Kind == ast.Typ {\n\t\t\tresult := parseStruct(d)\n\n\t\t\tfor i := range result {\n\t\t\t\t_, ok := Result[CurrentFile].StructScanResult[result[i].Name]\n\t\t\t\tif !ok {\n\t\t\t\t\tResult[CurrentFile].StructScanResult[result[i].Name] = result[i]\n\t\t\t\t}\n\t\t\t}\n\t\t} else if d.Obj.Kind == ast.Con || d.Obj.Kind == ast.Var {\n\t\t\tresult := parseConstantsAndVariables(d)\n\n\t\t\tfor i := range result {\n\t\t\t\t_, ok := Result[CurrentFile].ScanResult[result[i].Name]\n\t\t\t\tif !ok {\n\t\t\t\t\tResult[CurrentFile].ScanResult[result[i].Name] = result[i]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\tbreak\n\t}\n\n\treturn v + 1\n}", "func (p Passengers) Visit(visitor func(Passenger)) {\n\tfor _, one := range p {\n\t\tvisitor(one)\n\t}\n}", "func (p Passengers) Visit(visitor func(Passenger)) {\n\tfor _, one := range p {\n\t\tvisitor(one)\n\t}\n}", "func (this *MillisToZoneName) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *DateTruncStr) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (x AstSlice) Interface() interface{} { return asInterface(x.X, x.X == nil) }", "func (p *Parser) Interface() interface{} {\n\treturn p.data\n}", "func (*FuncExpr) iCallable() {}", "func (this *DateAddMillis) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (c *CallExpr) accept(v ExprVisitor) {\n\tv.VisitCall(c)\n}", "func (this *DatePartMillis) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (f *Function) Call(arg interface{}) {\n\tf.input <- arg\n}", "func (f WalkFunc) Walk(ctx context.Context, call *Call, path string) Node { return f(path) }", "func (l *List) Visit(f func(n *Node)) {\n\tp := l.head\n\tfor p != nil {\n\t\tf(p)\n\t\tp = p.next\n\t}\n}", "func Replace(node Node, visitor func(Node) Node) {\n\tswitch n := node.(type) {\n\tcase *Abort:\n\tcase *API:\n\t\tfor i, c := range n.Enums {\n\t\t\tn.Enums[i] = visitor(c).(*Enum)\n\t\t}\n\t\tfor i, c := range n.Definitions {\n\t\t\tn.Definitions[i] = visitor(c).(*Definition)\n\t\t}\n\t\tfor i, c := range n.Classes {\n\t\t\tn.Classes[i] = visitor(c).(*Class)\n\t\t}\n\t\tfor i, c := range n.Pseudonyms {\n\t\t\tn.Pseudonyms[i] = visitor(c).(*Pseudonym)\n\t\t}\n\t\tfor i, c := range n.Externs {\n\t\t\tn.Externs[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Subroutines {\n\t\t\tn.Subroutines[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Functions {\n\t\t\tn.Functions[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Methods {\n\t\t\tn.Methods[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Globals {\n\t\t\tn.Globals[i] = visitor(c).(*Global)\n\t\t}\n\t\tfor i, c := range n.StaticArrays {\n\t\t\tn.StaticArrays[i] = visitor(c).(*StaticArray)\n\t\t}\n\t\tfor i, c := range n.Maps {\n\t\t\tn.Maps[i] = visitor(c).(*Map)\n\t\t}\n\t\tfor i, c := range n.Pointers {\n\t\t\tn.Pointers[i] = visitor(c).(*Pointer)\n\t\t}\n\t\tfor i, c := range n.Slices {\n\t\t\tn.Slices[i] = visitor(c).(*Slice)\n\t\t}\n\t\tfor i, c := range n.References {\n\t\t\tn.References[i] = visitor(c).(*Reference)\n\t\t}\n\t\tfor i, c := range n.Signatures {\n\t\t\tn.Signatures[i] = visitor(c).(*Signature)\n\t\t}\n\tcase *ArrayAssign:\n\t\tn.To = visitor(n.To).(*ArrayIndex)\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase *ArrayIndex:\n\t\tn.Array = visitor(n.Array).(Expression)\n\t\tn.Index = visitor(n.Index).(Expression)\n\tcase *ArrayInitializer:\n\t\tn.Array = visitor(n.Array).(Type)\n\t\tfor i, c := range n.Values {\n\t\t\tn.Values[i] = visitor(c).(Expression)\n\t\t}\n\tcase *Slice:\n\t\tn.To = visitor(n.To).(Type)\n\tcase *SliceIndex:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\t\tn.Index = visitor(n.Index).(Expression)\n\tcase *SliceAssign:\n\t\tn.To = visitor(n.To).(*SliceIndex)\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase *Assert:\n\t\tn.Condition = visitor(n.Condition).(Expression)\n\tcase *Assign:\n\t\tn.LHS = visitor(n.LHS).(Expression)\n\t\tn.RHS = visitor(n.RHS).(Expression)\n\tcase *Annotation:\n\t\tfor i, c := range n.Arguments {\n\t\t\tn.Arguments[i] = visitor(c).(Expression)\n\t\t}\n\tcase *Block:\n\t\tfor i, c := range n.Statements {\n\t\t\tn.Statements[i] = visitor(c).(Statement)\n\t\t}\n\tcase BoolValue:\n\tcase *BinaryOp:\n\t\tif n.LHS != nil {\n\t\t\tn.LHS = visitor(n.LHS).(Expression)\n\t\t}\n\t\tif n.RHS != nil {\n\t\t\tn.RHS = visitor(n.RHS).(Expression)\n\t\t}\n\tcase *BitTest:\n\t\tn.Bitfield = visitor(n.Bitfield).(Expression)\n\t\tn.Bits = visitor(n.Bits).(Expression)\n\tcase *UnaryOp:\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\tcase *Branch:\n\t\tn.Condition = visitor(n.Condition).(Expression)\n\t\tn.True = visitor(n.True).(*Block)\n\t\tif n.False != nil {\n\t\t\tn.False = visitor(n.False).(*Block)\n\t\t}\n\tcase *Builtin:\n\tcase *Reference:\n\t\tn.To = visitor(n.To).(Type)\n\tcase *Call:\n\t\tn.Type = visitor(n.Type).(Type)\n\t\tn.Target = visitor(n.Target).(*Callable)\n\t\tfor i, a := range n.Arguments {\n\t\t\tn.Arguments[i] = visitor(a).(Expression)\n\t\t}\n\tcase *Callable:\n\t\tif n.Object != nil {\n\t\t\tn.Object = visitor(n.Object).(Expression)\n\t\t}\n\t\tn.Function = visitor(n.Function).(*Function)\n\tcase *Case:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, c := range n.Conditions {\n\t\t\tn.Conditions[i] = visitor(c).(Expression)\n\t\t}\n\t\tn.Block = visitor(n.Block).(*Block)\n\tcase *Cast:\n\t\tn.Object = visitor(n.Object).(Expression)\n\t\tn.Type = visitor(n.Type).(Type)\n\tcase *Class:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, f := range n.Fields {\n\t\t\tn.Fields[i] = visitor(f).(*Field)\n\t\t}\n\t\tfor i, m := range n.Methods {\n\t\t\tn.Methods[i] = visitor(m).(*Function)\n\t\t}\n\tcase *ClassInitializer:\n\t\tfor i, f := range n.Fields {\n\t\t\tn.Fields[i] = visitor(f).(*FieldInitializer)\n\t\t}\n\tcase *Choice:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, c := range n.Conditions {\n\t\t\tn.Conditions[i] = visitor(c).(Expression)\n\t\t}\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\tcase *Definition:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\tcase *DefinitionUsage:\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\t\tn.Definition = visitor(n.Definition).(*Definition)\n\tcase *DeclareLocal:\n\t\tn.Local = visitor(n.Local).(*Local)\n\t\tif n.Local.Value != nil {\n\t\t\tn.Local.Value = visitor(n.Local.Value).(Expression)\n\t\t}\n\tcase Documentation:\n\tcase *Enum:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, e := range n.Entries {\n\t\t\tn.Entries[i] = visitor(e).(*EnumEntry)\n\t\t}\n\tcase *EnumEntry:\n\tcase *Fence:\n\t\tif n.Statement != nil {\n\t\t\tn.Statement = visitor(n.Statement).(Statement)\n\t\t}\n\tcase *Field:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.Type = visitor(n.Type).(Type)\n\t\tif n.Default != nil {\n\t\t\tn.Default = visitor(n.Default).(Expression)\n\t\t}\n\tcase *FieldInitializer:\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase Float32Value:\n\tcase Float64Value:\n\tcase *Function:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tif n.Return != nil {\n\t\t\tn.Return = visitor(n.Return).(*Parameter)\n\t\t}\n\t\tfor i, c := range n.FullParameters {\n\t\t\tn.FullParameters[i] = visitor(c).(*Parameter)\n\t\t}\n\t\tif n.Block != nil {\n\t\t\tn.Block = visitor(n.Block).(*Block)\n\t\t}\n\t\tn.Signature = visitor(n.Signature).(*Signature)\n\tcase *Global:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\tcase *StaticArray:\n\t\tn.ValueType = visitor(n.ValueType).(Type)\n\t\tn.SizeExpr = visitor(n.SizeExpr).(Expression)\n\tcase *Signature:\n\tcase Int8Value:\n\tcase Int16Value:\n\tcase Int32Value:\n\tcase Int64Value:\n\tcase *Iteration:\n\t\tn.Iterator = visitor(n.Iterator).(*Local)\n\t\tn.From = visitor(n.From).(Expression)\n\t\tn.To = visitor(n.To).(Expression)\n\t\tn.Block = visitor(n.Block).(*Block)\n\tcase *MapIteration:\n\t\tn.IndexIterator = visitor(n.IndexIterator).(*Local)\n\t\tn.KeyIterator = visitor(n.KeyIterator).(*Local)\n\t\tn.ValueIterator = visitor(n.ValueIterator).(*Local)\n\t\tn.Map = visitor(n.Map).(Expression)\n\t\tn.Block = visitor(n.Block).(*Block)\n\tcase Invalid:\n\tcase *Length:\n\t\tn.Object = visitor(n.Object).(Expression)\n\tcase *Local:\n\t\tn.Type = visitor(n.Type).(Type)\n\tcase *Map:\n\t\tn.KeyType = visitor(n.KeyType).(Type)\n\t\tn.ValueType = visitor(n.ValueType).(Type)\n\tcase *MapAssign:\n\t\tn.To = visitor(n.To).(*MapIndex)\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase *MapContains:\n\t\tn.Key = visitor(n.Key).(Expression)\n\t\tn.Map = visitor(n.Map).(Expression)\n\tcase *MapIndex:\n\t\tn.Map = visitor(n.Map).(Expression)\n\t\tn.Index = visitor(n.Index).(Expression)\n\tcase *MapRemove:\n\t\tn.Map = visitor(n.Map).(Expression)\n\t\tn.Key = visitor(n.Key).(Expression)\n\tcase *MapClear:\n\t\tn.Map = visitor(n.Map).(Expression)\n\tcase *Member:\n\t\tn.Object = visitor(n.Object).(Expression)\n\t\tn.Field = visitor(n.Field).(*Field)\n\tcase *MessageValue:\n\t\tfor i, a := range n.Arguments {\n\t\t\tn.Arguments[i] = visitor(a).(*FieldInitializer)\n\t\t}\n\tcase *New:\n\t\tn.Type = visitor(n.Type).(*Reference)\n\tcase *Parameter:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.Type = visitor(n.Type).(Type)\n\tcase *Pointer:\n\t\tn.To = visitor(n.To).(Type)\n\tcase *Pseudonym:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.To = visitor(n.To).(Type)\n\t\tfor i, m := range n.Methods {\n\t\t\tn.Methods[i] = visitor(m).(*Function)\n\t\t}\n\tcase *Return:\n\t\tif n.Value != nil {\n\t\t\tn.Value = visitor(n.Value).(Expression)\n\t\t}\n\tcase *Select:\n\t\tn.Value = visitor(n.Value).(Expression)\n\t\tfor i, c := range n.Choices {\n\t\t\tn.Choices[i] = visitor(c).(*Choice)\n\t\t}\n\t\tif n.Default != nil {\n\t\t\tn.Default = visitor(n.Default).(Expression)\n\t\t}\n\tcase StringValue:\n\tcase *Switch:\n\t\tn.Value = visitor(n.Value).(Expression)\n\t\tfor i, c := range n.Cases {\n\t\t\tn.Cases[i] = visitor(c).(*Case)\n\t\t}\n\t\tif n.Default != nil {\n\t\t\tn.Default = visitor(n.Default).(*Block)\n\t\t}\n\tcase Uint8Value:\n\tcase Uint16Value:\n\tcase Uint32Value:\n\tcase Uint64Value:\n\tcase *Unknown:\n\tcase *Clone:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tcase *Copy:\n\t\tn.Src = visitor(n.Src).(Expression)\n\t\tn.Dst = visitor(n.Dst).(Expression)\n\tcase *Create:\n\t\tn.Type = visitor(n.Type).(*Reference)\n\t\tn.Initializer = visitor(n.Initializer).(*ClassInitializer)\n\tcase *Ignore:\n\tcase *Make:\n\t\tn.Type = visitor(n.Type).(*Slice)\n\t\tn.Size = visitor(n.Size).(Expression)\n\tcase Null:\n\tcase *PointerRange:\n\t\tn.Pointer = visitor(n.Pointer).(Expression)\n\t\tn.Range = visitor(n.Range).(*BinaryOp)\n\tcase *Read:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tcase *SliceContains:\n\t\tn.Value = visitor(n.Value).(Expression)\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tcase *SliceRange:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\t\tn.Range = visitor(n.Range).(*BinaryOp)\n\tcase *Write:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tdefault:\n\t\tpanic(fmt.Errorf(\"Unsupported semantic node type %T\", n))\n\t}\n}", "func (r *fakeResourceResult) Visit(fn resource.VisitorFunc) error {\n\tfor _, info := range r.Infos {\n\t\terr := fn(info, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (h *MapInt16ToInt) Visit(fn func(int16, int)) {\n\tfor _, e := range h.slots {\n\t\tfor ; e != nil; e = e.next {\n\t\t\tfn(e.k, e.v)\n\t\t}\n\t}\n}", "func FuncInterfaceCompatible(_ T1) {}", "func (b *Binary) Accept(v Visitor) {\n\tv.VisitBinary(b)\n}", "func (s *InterfaceStep) Interface() interface{} {\n\treturn s.value\n}", "func (h *MapInt16ToInt8) Visit(fn func(int16, int8)) {\n\tfor _, e := range h.slots {\n\t\tfor ; e != nil; e = e.next {\n\t\t\tfn(e.k, e.v)\n\t\t}\n\t}\n}", "func (s *Sequenced) Accept(v Visitor) {\n\tv.VisitSequenced(s)\n}", "func testVisitors(methodCalled *string) (*SimpleVisitor, []*SimpleVisitor) {\n\tv := &SimpleVisitor{\n\t\tDoVisitEnumNode: func(*EnumNode) error {\n\t\t\t*methodCalled = \"*EnumNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitEnumValueNode: func(*EnumValueNode) error {\n\t\t\t*methodCalled = \"*EnumValueNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitFieldDeclNode: func(FieldDeclNode) error {\n\t\t\t*methodCalled = \"FieldDeclNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitFieldNode: func(*FieldNode) error {\n\t\t\t*methodCalled = \"*FieldNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitGroupNode: func(*GroupNode) error {\n\t\t\t*methodCalled = \"*GroupNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitOneofNode: func(*OneofNode) error {\n\t\t\t*methodCalled = \"*OneofNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitMapTypeNode: func(*MapTypeNode) error {\n\t\t\t*methodCalled = \"*MapTypeNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitMapFieldNode: func(*MapFieldNode) error {\n\t\t\t*methodCalled = \"*MapFieldNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitFileNode: func(*FileNode) error {\n\t\t\t*methodCalled = \"*FileNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitSyntaxNode: func(*SyntaxNode) error {\n\t\t\t*methodCalled = \"*SyntaxNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitImportNode: func(*ImportNode) error {\n\t\t\t*methodCalled = \"*ImportNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitPackageNode: func(*PackageNode) error {\n\t\t\t*methodCalled = \"*PackageNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitIdentValueNode: func(IdentValueNode) error {\n\t\t\t*methodCalled = \"IdentValueNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitIdentNode: func(*IdentNode) error {\n\t\t\t*methodCalled = \"*IdentNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitCompoundIdentNode: func(*CompoundIdentNode) error {\n\t\t\t*methodCalled = \"*CompoundIdentNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitKeywordNode: func(*KeywordNode) error {\n\t\t\t*methodCalled = \"*KeywordNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitMessageDeclNode: func(MessageDeclNode) error {\n\t\t\t*methodCalled = \"MessageDeclNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitMessageNode: func(*MessageNode) error {\n\t\t\t*methodCalled = \"*MessageNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitExtendNode: func(*ExtendNode) error {\n\t\t\t*methodCalled = \"*ExtendNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitNode: func(Node) error {\n\t\t\t*methodCalled = \"Node\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitTerminalNode: func(TerminalNode) error {\n\t\t\t*methodCalled = \"TerminalNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitCompositeNode: func(CompositeNode) error {\n\t\t\t*methodCalled = \"CompositeNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitRuneNode: func(*RuneNode) error {\n\t\t\t*methodCalled = \"*RuneNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitEmptyDeclNode: func(*EmptyDeclNode) error {\n\t\t\t*methodCalled = \"*EmptyDeclNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitOptionNode: func(*OptionNode) error {\n\t\t\t*methodCalled = \"*OptionNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitOptionNameNode: func(*OptionNameNode) error {\n\t\t\t*methodCalled = \"*OptionNameNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitFieldReferenceNode: func(*FieldReferenceNode) error {\n\t\t\t*methodCalled = \"*FieldReferenceNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitCompactOptionsNode: func(*CompactOptionsNode) error {\n\t\t\t*methodCalled = \"*CompactOptionsNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitExtensionRangeNode: func(*ExtensionRangeNode) error {\n\t\t\t*methodCalled = \"*ExtensionRangeNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitRangeNode: func(*RangeNode) error {\n\t\t\t*methodCalled = \"*RangeNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitReservedNode: func(*ReservedNode) error {\n\t\t\t*methodCalled = \"*ReservedNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitServiceNode: func(*ServiceNode) error {\n\t\t\t*methodCalled = \"*ServiceNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitRPCNode: func(*RPCNode) error {\n\t\t\t*methodCalled = \"*RPCNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitRPCTypeNode: func(*RPCTypeNode) error {\n\t\t\t*methodCalled = \"*RPCTypeNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitValueNode: func(ValueNode) error {\n\t\t\t*methodCalled = \"ValueNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitStringValueNode: func(StringValueNode) error {\n\t\t\t*methodCalled = \"StringValueNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitStringLiteralNode: func(*StringLiteralNode) error {\n\t\t\t*methodCalled = \"*StringLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitCompoundStringLiteralNode: func(*CompoundStringLiteralNode) error {\n\t\t\t*methodCalled = \"*CompoundStringLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitIntValueNode: func(IntValueNode) error {\n\t\t\t*methodCalled = \"IntValueNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitUintLiteralNode: func(*UintLiteralNode) error {\n\t\t\t*methodCalled = \"*UintLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitPositiveUintLiteralNode: func(*PositiveUintLiteralNode) error {\n\t\t\t*methodCalled = \"*PositiveUintLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitNegativeIntLiteralNode: func(*NegativeIntLiteralNode) error {\n\t\t\t*methodCalled = \"*NegativeIntLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitFloatValueNode: func(FloatValueNode) error {\n\t\t\t*methodCalled = \"FloatValueNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitFloatLiteralNode: func(*FloatLiteralNode) error {\n\t\t\t*methodCalled = \"*FloatLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitSpecialFloatLiteralNode: func(*SpecialFloatLiteralNode) error {\n\t\t\t*methodCalled = \"*SpecialFloatLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitSignedFloatLiteralNode: func(*SignedFloatLiteralNode) error {\n\t\t\t*methodCalled = \"*SignedFloatLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitArrayLiteralNode: func(*ArrayLiteralNode) error {\n\t\t\t*methodCalled = \"*ArrayLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitMessageLiteralNode: func(*MessageLiteralNode) error {\n\t\t\t*methodCalled = \"*MessageLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitMessageFieldNode: func(*MessageFieldNode) error {\n\t\t\t*methodCalled = \"*MessageFieldNode\"\n\t\t\treturn nil\n\t\t},\n\t}\n\tothers := []*SimpleVisitor{\n\t\t{\n\t\t\tDoVisitEnumNode: v.DoVisitEnumNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitEnumValueNode: v.DoVisitEnumValueNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitFieldDeclNode: v.DoVisitFieldDeclNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitFieldNode: v.DoVisitFieldNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitGroupNode: v.DoVisitGroupNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitOneofNode: v.DoVisitOneofNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitMapTypeNode: v.DoVisitMapTypeNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitMapFieldNode: v.DoVisitMapFieldNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitFileNode: v.DoVisitFileNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitSyntaxNode: v.DoVisitSyntaxNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitImportNode: v.DoVisitImportNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitPackageNode: v.DoVisitPackageNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitIdentValueNode: v.DoVisitIdentValueNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitIdentNode: v.DoVisitIdentNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitCompoundIdentNode: v.DoVisitCompoundIdentNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitKeywordNode: v.DoVisitKeywordNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitMessageDeclNode: v.DoVisitMessageDeclNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitMessageNode: v.DoVisitMessageNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitExtendNode: v.DoVisitExtendNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitNode: v.DoVisitNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitTerminalNode: v.DoVisitTerminalNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitCompositeNode: v.DoVisitCompositeNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitRuneNode: v.DoVisitRuneNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitEmptyDeclNode: v.DoVisitEmptyDeclNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitOptionNode: v.DoVisitOptionNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitOptionNameNode: v.DoVisitOptionNameNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitFieldReferenceNode: v.DoVisitFieldReferenceNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitCompactOptionsNode: v.DoVisitCompactOptionsNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitExtensionRangeNode: v.DoVisitExtensionRangeNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitRangeNode: v.DoVisitRangeNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitReservedNode: v.DoVisitReservedNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitServiceNode: v.DoVisitServiceNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitRPCNode: v.DoVisitRPCNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitRPCTypeNode: v.DoVisitRPCTypeNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitValueNode: v.DoVisitValueNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitStringValueNode: v.DoVisitStringValueNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitStringLiteralNode: v.DoVisitStringLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitCompoundStringLiteralNode: v.DoVisitCompoundStringLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitIntValueNode: v.DoVisitIntValueNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitUintLiteralNode: v.DoVisitUintLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitPositiveUintLiteralNode: v.DoVisitPositiveUintLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitNegativeIntLiteralNode: v.DoVisitNegativeIntLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitFloatValueNode: v.DoVisitFloatValueNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitFloatLiteralNode: v.DoVisitFloatLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitSpecialFloatLiteralNode: v.DoVisitSpecialFloatLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitSignedFloatLiteralNode: v.DoVisitSignedFloatLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitArrayLiteralNode: v.DoVisitArrayLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitMessageLiteralNode: v.DoVisitMessageLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitMessageFieldNode: v.DoVisitMessageFieldNode,\n\t\t},\n\t}\n\treturn v, others\n}", "func _[T interface{ ~func(string) int }](f T) int {\n\treturn f(\"hello\")\n}", "func VisitedFunctions(prog *ssa.Program, packs []*ssa.Package, isOvl isOverloaded) (seen, usesGR map[*ssa.Function]bool) {\n\tvisit := visitor{\n\t\tprog: prog,\n\t\tpacks: packs, // new\n\t\tseen: make(map[*ssa.Function]bool),\n\t\tusesGR: make(map[*ssa.Function]bool),\n\t}\n\tvisit.program(isOvl)\n\t//fmt.Printf(\"DEBUG VisitedFunctions.usesGR %v\\n\", visit.usesGR)\n\t//fmt.Printf(\"DEBUG VisitedFunctions.seen %v\\n\", visit.seen)\n\treturn visit.seen, visit.usesGR\n}", "func (h *MapInt16ToInt32) Visit(fn func(int16, int32)) {\n\tfor _, e := range h.slots {\n\t\tfor ; e != nil; e = e.next {\n\t\t\tfn(e.k, e.v)\n\t\t}\n\t}\n}", "func (x *fastReflection_Evidence) Interface() protoreflect.ProtoMessage {\n\treturn (*Evidence)(x)\n}", "func (f *functionQuery) Evaluate(t iterator) interface{} {\n\treturn f.Func(f.Input, t)\n}", "func Visit(node Node, visitor func(node Node, next func() error) error) error {\n\tif reflect.ValueOf(node).IsNil() { // Workaround for Go's typed nil interfaces.\n\t\treturn nil\n\t}\n\treturn visitor(node, func() error {\n\t\tfor _, child := range node.children() {\n\t\t\tif err := Visit(child, visitor); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func (x *fastReflection_Output) Interface() protoreflect.ProtoMessage {\n\treturn (*Output)(x)\n}", "func (i I) I() I { return i }", "func (rf RendererFunc) Render(w io.Writer, v interface{}) error { return rf(w, v) }", "func (v Variable) Accept(interpreter *Interpreter) Object {\n\treturn interpreter.visitVariable(v)\n}", "func (*Base) Function(p ASTPass, node *ast.Function, ctx Context) {\n\tp.Parameters(p, &node.ParenLeftFodder, &node.Parameters, &node.ParenRightFodder, ctx)\n\tp.Visit(p, &node.Body, ctx)\n}", "func (t *FileTree) VisitorFn(fn func(file.Reference)) func(node.Node) {\n\treturn func(node node.Node) {\n\t\tfn(t.fileByPathID(node.ID()))\n\t}\n}", "func execNewInterface(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := types.NewInterface(args[0].([]*types.Func), args[1].([]*types.Named))\n\tp.Ret(2, ret)\n}", "func (h *MapInt16ToUint8) Visit(fn func(int16, uint8)) {\n\tfor _, e := range h.slots {\n\t\tfor ; e != nil; e = e.next {\n\t\t\tfn(e.k, e.v)\n\t\t}\n\t}\n}", "func FuncInterfaceCompatible2(_ io.Writer) {}", "func (h *MapInt16ToInt16) Visit(fn func(int16, int16)) {\n\tfor _, e := range h.slots {\n\t\tfor ; e != nil; e = e.next {\n\t\t\tfn(e.k, e.v)\n\t\t}\n\t}\n}", "func Function(sig *CallSignature) Type {\n\treturn Type{functionImpl{sig: sig}}\n}", "func (mi *ModifierInvocation) Visit(ctx *parser.ModifierInvocationContext) {\n\tmi.Start = ctx.GetStart()\n\tmi.Stop = ctx.GetStop()\n\tmi.Identifier = ctx.Identifier().GetText()\n\n\tif ctx.ExpressionList() != nil {\n\t\texpList := ctx.ExpressionList().(*parser.ExpressionListContext)\n\n\t\tfor _, exprCtx := range expList.AllExpression() {\n\t\t\texpression := NewExpression()\n\t\t\texpression.Visit(exprCtx.(*parser.ExpressionContext))\n\n\t\t\tmi.Expressions = append(mi.Expressions, expression)\n\t\t}\n\t}\n}", "func (x *fastReflection_Input) Interface() protoreflect.ProtoMessage {\n\treturn (*Input)(x)\n}", "func (a Assign) Accept(interpreter *Interpreter) Object {\n\treturn interpreter.visitAssign(a)\n}", "func (h *MapInt16ToUint) Visit(fn func(int16, uint)) {\n\tfor _, e := range h.slots {\n\t\tfor ; e != nil; e = e.next {\n\t\t\tfn(e.k, e.v)\n\t\t}\n\t}\n}", "func (_Contract *ContractCallerSession) InterfaceImplementer(node [32]byte, interfaceID [4]byte) (common.Address, error) {\n\treturn _Contract.Contract.InterfaceImplementer(&_Contract.CallOpts, node, interfaceID)\n}", "func (h *MapInt16ToUint32) Visit(fn func(int16, uint32)) {\n\tfor _, e := range h.slots {\n\t\tfor ; e != nil; e = e.next {\n\t\t\tfn(e.k, e.v)\n\t\t}\n\t}\n}", "func (g Grouping) Accept(interpreter *Interpreter) Object {\n\treturn interpreter.visitGrouping(g)\n}", "func Interface(ifname string) func(*NetworkTap) error {\n\treturn func(filterdev *NetworkTap) error {\n\t\terr := filterdev.SetInterface(int(filterdev.device.Fd()), ifname)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n}", "func (f *FlagSet) Visit(fn func(*Flag)) {\n\tfor _, flag := range sortFlags(f.actual) {\n\t\tfn(flag)\n\t}\n}", "func (_Contract *ContractFilterer) FilterInterfaceChanged(opts *bind.FilterOpts, node [][32]byte, interfaceID [][4]byte) (*ContractInterfaceChangedIterator, error) {\n\n\tvar nodeRule []interface{}\n\tfor _, nodeItem := range node {\n\t\tnodeRule = append(nodeRule, nodeItem)\n\t}\n\tvar interfaceIDRule []interface{}\n\tfor _, interfaceIDItem := range interfaceID {\n\t\tinterfaceIDRule = append(interfaceIDRule, interfaceIDItem)\n\t}\n\n\tlogs, sub, err := _Contract.contract.FilterLogs(opts, \"InterfaceChanged\", nodeRule, interfaceIDRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ContractInterfaceChangedIterator{contract: _Contract.contract, event: \"InterfaceChanged\", logs: logs, sub: sub}, nil\n}", "func (f *FlagSet) Visit(fn func(*Flag)) {\n\tif len(f.actual) == 0 {\n\t\treturn\n\t}\n\n\tvar flags []*Flag\n\tif f.SortFlags {\n\t\tif len(f.actual) != len(f.sortedActual) {\n\t\t\tf.sortedActual = sortFlags(f.actual)\n\t\t}\n\t\tflags = f.sortedActual\n\t} else {\n\t\tflags = f.orderedActual\n\t}\n\n\tfor _, flag := range flags {\n\t\tfn(flag)\n\t}\n}", "func (x *fastReflection_EventRetire) Interface() protoreflect.ProtoMessage {\n\treturn (*EventRetire)(x)\n}", "func execmInterfaceMethod(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := args[0].(*types.Interface).Method(args[1].(int))\n\tp.Ret(2, ret)\n}", "func (lambda PresenterFunc) Render(message interface{}) error {\n\treturn lambda(message)\n}", "func underlyingInterface(w v1alpha1.ExecutableWorkflow, node v1alpha1.ExecutableNode) (*core.TypedInterface, error) {\n\tiface := &core.TypedInterface{}\n\tif node.GetTaskID() != nil {\n\t\tt, err := w.GetTask(*node.GetTaskID())\n\t\tif err != nil {\n\t\t\t// Should never happen\n\t\t\treturn nil, err\n\t\t}\n\n\t\tiface.Outputs = t.CoreTask().GetInterface().Outputs\n\t} else if wfNode := node.GetWorkflowNode(); wfNode != nil {\n\t\tif wfRef := wfNode.GetSubWorkflowRef(); wfRef != nil {\n\t\t\tt := w.FindSubWorkflow(*wfRef)\n\t\t\tif t == nil {\n\t\t\t\t// Should never happen\n\t\t\t\treturn nil, errors.Errorf(errors.IllegalStateError, node.GetID(), \"Couldn't find subworkflow [%v].\", wfRef)\n\t\t\t}\n\n\t\t\tiface.Outputs = t.GetOutputs().VariableMap\n\t\t} else {\n\t\t\treturn nil, errors.Errorf(errors.IllegalStateError, node.GetID(), \"Unknown interface\")\n\t\t}\n\t} else if node.GetBranchNode() != nil {\n\t\tif ifBlock := node.GetBranchNode().GetIf(); ifBlock != nil && ifBlock.GetThenNode() != nil {\n\t\t\tbn, found := w.GetNode(*ifBlock.GetThenNode())\n\t\t\tif !found {\n\t\t\t\treturn nil, errors.Errorf(errors.IllegalStateError, node.GetID(), \"Couldn't find branch node [%v]\",\n\t\t\t\t\t*ifBlock.GetThenNode())\n\t\t\t}\n\n\t\t\treturn underlyingInterface(w, bn)\n\t\t}\n\n\t\treturn nil, errors.Errorf(errors.IllegalStateError, node.GetID(), \"Empty branch detected.\")\n\t} else {\n\t\treturn nil, errors.Errorf(errors.IllegalStateError, node.GetID(), \"Unknown interface.\")\n\t}\n\n\treturn iface, nil\n}" ]
[ "0.60175425", "0.5906299", "0.59027874", "0.5845828", "0.5825935", "0.5819577", "0.5819577", "0.580104", "0.5785162", "0.5777933", "0.5703701", "0.56876904", "0.56876904", "0.5627525", "0.5536116", "0.549273", "0.5463964", "0.5434355", "0.54164505", "0.54164505", "0.5402595", "0.5397546", "0.53573", "0.5347492", "0.5327222", "0.5282537", "0.52577364", "0.52453923", "0.5236527", "0.51695585", "0.5169153", "0.51691335", "0.5150039", "0.5100336", "0.5098669", "0.5096844", "0.5092909", "0.5025056", "0.5013577", "0.5006477", "0.4981647", "0.4977761", "0.49491403", "0.49481136", "0.49135387", "0.4902572", "0.4902572", "0.48868135", "0.48798364", "0.48651856", "0.48479375", "0.48444048", "0.48257497", "0.48061544", "0.47927007", "0.4789761", "0.47619694", "0.47598982", "0.47561255", "0.47533038", "0.47495225", "0.47481802", "0.47395724", "0.47342122", "0.47313806", "0.4717683", "0.47168908", "0.46870023", "0.46790814", "0.4676445", "0.4658523", "0.46575442", "0.46539652", "0.46523747", "0.46460128", "0.46418434", "0.46396607", "0.46377394", "0.46143577", "0.46142966", "0.46093234", "0.46074614", "0.46003863", "0.45997134", "0.45860335", "0.4582408", "0.4575352", "0.45601138", "0.45586434", "0.45583653", "0.4555357", "0.45495585", "0.4543396", "0.45388633", "0.4532948", "0.45328376", "0.45314434", "0.45284674", "0.45211044" ]
0.54699755
17
/ It returns a value type NUMBER.
func (this *ObjectLength) Type() value.Type { return value.NUMBER }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (v Value) Number() (Number, error) {\n\tr := bytes.NewReader(v.bytes)\n\treturn byteReaderToNumber(v.dataType, r)\n}", "func getNumber(v interface{}) (int64, error) {\n\tswitch v := v.(type) {\n\tcase int:\n\t\treturn int64(v), nil\n\tcase int8:\n\t\treturn int64(v), nil\n\tcase int16:\n\t\treturn int64(v), nil\n\tcase int32:\n\t\treturn int64(v), nil\n\tcase int64:\n\t\treturn v, nil\n\tcase uint:\n\t\treturn int64(v), nil\n\tcase uint8:\n\t\treturn int64(v), nil\n\tcase uint16:\n\t\treturn int64(v), nil\n\tcase uint32:\n\t\treturn int64(v), nil\n\tcase uint64:\n\t\treturn int64(v), nil\n\tcase []byte:\n\t\treturn parseString(string(v))\n\tcase string:\n\t\treturn parseString(v)\n\tcase sqltypes.Value:\n\t\treturn parseValue(v.Type(), v.Raw())\n\tcase *querypb.BindVariable:\n\t\treturn parseValue(v.Type, v.Value)\n\t}\n\treturn 0, fmt.Errorf(\"getNumber: unexpected type for %v: %T\", v, v)\n}", "func (v *Value) Number() (float64, error) {\n\tif v.kind == kindNumber {\n\t\treturn v.numberContent, nil\n\t}\n\treturn 0.0, errors.New(\"JSON value is not a number\")\n}", "func getNumber(e Expr) (float64, error) {\n\tswitch n := e.(type) {\n\tcase *NumberLiteral:\n\t\treturn n.Val, nil\n\tcase *NilLiteral:\n\t\treturn 0, nil\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"Literal is not a number: %v\", n)\n\t}\n}", "func NumberVal(v *big.Rat) cty.Value {\n\treturn cty.CapsuleVal(Number, v)\n}", "func (p *parser) number() Node {\n\ttoken := p.expect(TokenNumber)\n\tnum, err := newNumber(token.pos, token.val)\n\tif err != nil {\n\t\tp.error(err)\n\t}\n\treturn num\n}", "func (u *sqlSymUnion) numVal() *NumVal {\n\treturn u.val.(*NumVal)\n}", "func (u *sqlSymUnion) numVal() *NumVal {\n\treturn u.val.(*NumVal)\n}", "func (u *sqlSymUnion) numVal() *NumVal {\n\treturn u.val.(*NumVal)\n}", "func (u *sqlSymUnion) numVal() *NumVal {\n\treturn u.val.(*NumVal)\n}", "func (v *JSONValue) Number() float64 {\n\tv.parseNumber()\n\treturn v.valNumber\n}", "func ToNumber(v Value) (int64, float64, NumberType) {\n\tswitch v.iface.(type) {\n\tcase int64:\n\t\treturn v.AsInt(), 0, IsInt\n\tcase float64:\n\t\treturn 0, v.AsFloat(), IsFloat\n\tcase string:\n\t\ts := v.AsString()\n\t\treturn StringToNumber(strings.TrimSpace(s))\n\t}\n\treturn 0, 0, NaN\n}", "func (n SNumber) ToNum() float64 {\n\treturn float64(n)\n}", "func (n Number) Value() (driver.Value, error) {\n\treturn string(n), nil\n}", "func (v Value) NumberType() ValueType {\n\tswitch v.iface.(type) {\n\tcase int64:\n\t\treturn IntType\n\tcase float64:\n\t\treturn FloatType\n\t}\n\treturn UnknownType\n}", "func ToNumberValue(v Value) (Value, NumberType) {\n\tswitch v.NumberType() {\n\tcase IntType:\n\t\treturn v, IsInt\n\tcase FloatType:\n\t\treturn v, IsFloat\n\t}\n\tif s, ok := v.TryString(); ok {\n\t\tn, f, tp := StringToNumber(strings.TrimSpace(s))\n\t\tswitch tp {\n\t\tcase IsInt:\n\t\t\treturn IntValue(n), IsInt\n\t\tcase IsFloat:\n\t\t\treturn FloatValue(f), IsFloat\n\t\t}\n\t}\n\treturn v, NaN\n}", "func Number() {\n\tfmt.Println(232, reflect.TypeOf(232))\n\tfmt.Println(232.67, reflect.TypeOf(232.67))\n}", "func lvalNum(x int64) *lval {\n\tv := new(lval)\n\tv.ltype = lvalNumType\n\tv.num = x\n\treturn v\n}", "func NumberIntVal(v int64) cty.Value {\n\tbr := big.NewRat(v, 1)\n\treturn cty.CapsuleVal(Number, br)\n}", "func (j *JSONData) Number() *float64 {\n\tif j != nil && j.value != nil {\n\t\tif float, ok := (*j.value).(float64); ok {\n\t\t\treturn &float\n\t\t}\n\t}\n\treturn nil\n}", "func NewNumber(value float64) *Value {\n\treturn &Value{kind: kindNumber, numberContent: value}\n}", "func (rt *operatorRuntime) numVal(op func(float64) interface{}, vs parser.Scope,\n\tis map[string]interface{}, tid uint64) (interface{}, error) {\n\n\tvar ret interface{}\n\n\terrorutil.AssertTrue(len(rt.node.Children) == 1,\n\t\tfmt.Sprint(\"Operation requires 1 operand\", rt.node))\n\n\tres, err := rt.node.Children[0].Runtime.Eval(vs, is, tid)\n\tif err == nil {\n\n\t\t// Check if the value is a number\n\n\t\tresNum, ok := res.(float64)\n\n\t\tif !ok {\n\n\t\t\t// Produce a runtime error if the value is not a number\n\n\t\t\treturn nil, rt.erp.NewRuntimeError(util.ErrNotANumber,\n\t\t\t\trt.errorDetailString(rt.node.Children[0].Token, res), rt.node.Children[0])\n\t\t}\n\n\t\tret = op(resNum)\n\t}\n\n\treturn ret, err\n}", "func (v Value10) Get() any { return int(v) }", "func (t Token) Numberlike() float64 {\n\treturn float64(t)\n}", "func (l *lexer) getNumber() float64 {\n\tvalueEndIndex := l.pos + 1\n\tfor valueEndIndex < len(l.input) {\n\t\tch := l.input[valueEndIndex]\n\t\tif ch >= '0' && ch <= '9' {\n\t\t\tvalueEndIndex++\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\tvalue, err := strconv.ParseFloat(l.input[l.pos:valueEndIndex], 64)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tl.pos = valueEndIndex\n\treturn value\n}", "func ToNumber(o Value) (*Number, error) {\n\tswitch p := o.(type) {\n\tcase *Number:\n\t\treturn p, nil\n\tcase *Character:\n\t\treturn Integer(int(p.Value)), nil\n\tcase *Boolean:\n\t\tif p.Value {\n\t\t\treturn One, nil\n\t\t}\n\t\treturn Zero, nil\n\tcase *String:\n\t\tf, err := strconv.ParseFloat(p.Value, 64)\n\t\tif err == nil {\n\t\t\treturn Float(f), nil\n\t\t}\n\t}\n\treturn nil, NewError(ArgumentErrorKey, \"cannot convert to an number: \", o)\n}", "func (f Number) Native(context.Context) interface{} {\n\treturn float64(f)\n}", "func (n Int64String) Value() (driver.Value, error) {\n\tif n == 0 {\n\t\treturn nil, nil\n\t}\n\treturn float64(n), nil\n}", "func (e *Expect) Number(value float64) *Number {\n\topChain := e.chain.enter(\"Number()\")\n\tdefer opChain.leave()\n\n\treturn newNumber(opChain, value)\n}", "func (l *NumberLiteral) Type() Type {\n\treturn l.ExprType\n}", "func (p *Parser) number() {\n\tnum, _ := strconv.Atoi(p.previous.Literal)\n\tp.emitConstant(IntVal(num))\n}", "func (this *DateAddMillis) Type() value.Type { return value.NUMBER }", "func readNumber(pt *pathtokenizer, tokenType *int, token *string) (v float64, err error) {\n\tif *tokenType != scanNum {\n\t\treturn 0, fmt.Errorf(\"this token is not a Number but %d\", *tokenType)\n\t}\n\tv, err = strconv.ParseFloat(*token, 64) // parse float64\n\t*tokenType, *token = pt.get() // read next token\n\treturn\n}", "func (p *parser) number(val string) float64 {\n\tn, err := strconv.ParseInt(val, 0, 64)\n\tf := float64(n)\n\tif err != nil {\n\t\tf, err = strconv.ParseFloat(val, 64)\n\t}\n\tif err != nil {\n\t\tp.errorf(\"error parsing number: %s\", err)\n\t}\n\treturn f\n}", "func AllocNumber(val float64, numtype int) *GoJSON {\n\tchild := new(GoJSON)\n\n\tif numtype == JSON_INT {\n\t\tchild.Valint = int64(val)\n\t\tchild.Jsontype = JSON_INT\n\t} else if numtype == JSON_UINT {\n\t\tchild.Valuint = uint64(val)\n\t\tchild.Jsontype = JSON_UINT\n\t} else {\n\t\tchild.Valdouble = val\n\t\tchild.Jsontype = JSON_DOUBLE\n\t}\n\n\treturn child\n}", "func (n NullNumeric) Value() (driver.Value, error) {\n\tif !n.Valid {\n\t\treturn nil, nil\n\t}\n\treturn n.Numeric.Value()\n}", "func (l *Lexer) Number() float64 {\n\ts := l.pos // l.start is reset through the multiple scans\n\tif l.Peek() == '-' {\n\t\tl.pos += l.width\n\t}\n\tl.Scan(unicode.IsDigit)\n\tif l.Next() == \".\" {\n\t\tl.Scan(unicode.IsDigit)\n\t} else {\n\t\tl.Rewind()\n\t}\n\tif c := l.Next(); c == \"e\" || c == \"E\" {\n\t\tif l.Peek() == '-' || l.Peek() == '+' {\n\t\t\tl.pos += l.width\n\t\t}\n\t\tl.Scan(unicode.IsDigit)\n\t} else {\n\t\tl.Rewind()\n\t}\n\tl.start = s\n\tn, err := strconv.ParseFloat(l.Input[s:l.pos], 64)\n\tif err != nil {\n\t\t// This might be a bad idea in the long run.\n\t\treturn 0\n\t}\n\treturn n\n}", "func (*BigInt) Type() types.Type {\n\treturn types.Number\n}", "func (p *Parser) number(tok token.Token) (expr value.Expr, str string) {\n\tvar err error\n\ttext := tok.Text\n\tswitch tok.Type {\n\tcase token.Identifier:\n\t\texpr = p.variable(text)\n\tcase token.String:\n\t\t// TODO\n\t\tstr = \"<token.String>\"\n\tcase token.Number, token.Rational:\n\t\texpr, err = value.Parse(p.context.Config(), text)\n\tcase token.LeftParen:\n\t\texpr = p.expr(p.next())\n\t\ttok := p.next()\n\t\tif tok.Type != token.RightParen {\n\t\t\tp.errorf(\"expected right paren, found %s\", tok)\n\t\t}\n\t}\n\tif err != nil {\n\t\tp.errorf(\"%s: %s\", text, err)\n\t}\n\treturn expr, str\n}", "func Num(x Value) Value {\n\tif v, ok := x.(*ratVal); ok {\n\t\tx = v.Value\n\t}\n\treturn constant.Num(x)\n}", "func (number Number) Value() (value driver.Value, err error) {\n\tif number == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\tif err = number.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn number.String(), nil\n}", "func convertNumber(n json.Number) (interface{}, error) {\n\t// Attempt to convert to an int64 first\n\tif i, err := n.Int64(); err == nil {\n\t\treturn i, nil\n\t}\n\t// Return a float64 (default json.Decode() behavior)\n\t// An overflow will return an error\n\treturn n.Float64()\n}", "func (l *Lexer) readNumber() (token.TokenType, string) {\n\tposition := l.position\n\tdecimals := 0\n\tfor isDigit(l.ch) || l.ch == '.' {\n\t\tif l.ch == '.' {\n\t\t\tif decimals > 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdecimals++\n\t\t}\n\t\tl.readChar()\n\t}\n\tif decimals > 0 {\n\t\treturn token.FLOAT, l.input[position:l.position]\n\t}\n\n\treturn token.INT, l.input[position:l.position]\n}", "func (v Value10) Int() int { return int(v) }", "func numberType(f func(...Expression) Expression) func(...Expression) (Expression, error) {\n\n\treturn func(args ...Expression) (Expression, error) {\n\t\tfor _, arg := range args {\n\t\t\tif _, ok := arg.(Number); !ok {\n\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"Type Error: Recieved %T, Expected Number\", arg))\n\t\t\t}\n\t\t}\n\t\treturn f(args...), nil\n\t}\n}", "func (me TSAFPTPortugueseVatNumber) ToXsdtInteger() xsdt.Integer { return xsdt.Integer(me) }", "func IntValue(n int64) Value {\n\treturn Value{iface: n}\n}", "func (Integer) Type() types.Type {\n\treturn types.Number\n}", "func (p *parser) parseNumber() (num *tree.NumberExpr) {\n\tswitch p.tok {\n\tcase token.NUMBERFLOAT, token.NUMBERHEX:\n\t\tnum = &tree.NumberExpr{NumberToken: p.token()}\n\tdefault:\n\t\tp.error(p.off, \"'\"+token.NUMBERFLOAT.String()+\"' expected\")\n\t}\n\tp.next()\n\treturn\n}", "func (s *Scanner) scanNumber() Token {\n\tline, offset := s.line, s.lineOffset\n\tvar buf bytes.Buffer\n\tbuf.WriteByte(s.read())\n\tfor {\n\t\tif ch := s.read(); ch == eof {\n\t\t\tbreak\n\t\t} else if isNumber(ch) {\n\t\t\tbuf.WriteByte(ch)\n\t\t} else {\n\t\t\ts.unread()\n\t\t\tbreak\n\t\t}\n\t}\n\treturn Token{tpe: NUMBER, val: buf.String(), line: line, offset: offset}\n}", "func (s *Scanner) number() {\n\tfor s.isDigit(s.peek()) {\n\t\ts.advance()\n\t}\n\tif s.peek() == '.' && s.isDigit(s.peekNext()) {\n\t\ts.advance()\n\t\tfor s.isDigit(s.peek()) {\n\t\t\ts.advance()\n\t\t}\n\t}\n\t// this seems a bit convoluted just to cast []byte into []rune\n\tliteral := []rune(string(s.source[s.start:s.current]))\n\ts.addToken(token.NUMBER, literal)\n}", "func (p *Parser) number(tok scan.Token) (expr value.Expr, str string) {\n\tvar err error\n\ttext := tok.Text\n\tswitch tok.Type {\n\tcase scan.Identifier:\n\t\texpr = p.index(p.variable(text))\n\tcase scan.String:\n\t\tstr = value.ParseString(text)\n\tcase scan.Number, scan.Rational, scan.Complex:\n\t\texpr, err = value.Parse(p.context.Config(), text)\n\tcase scan.LeftParen:\n\t\texpr = p.expr()\n\t\ttok := p.next()\n\t\tif tok.Type != scan.RightParen {\n\t\t\tp.errorf(\"expected right paren, found %s\", tok)\n\t\t}\n\t}\n\tif err != nil {\n\t\tp.errorf(\"%s: %s\", text, err)\n\t}\n\treturn expr, str\n}", "func (t *Type) Val() *Type", "func AsNumber(f Field) uint32 {\n\tv, _ := f.(uint32)\n\treturn v\n}", "func (this *DateTruncMillis) Type() value.Type { return value.NUMBER }", "func execmNumberInt64(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret, ret1 := args[0].(json.Number).Int64()\n\tp.Ret(1, ret, ret1)\n}", "func IntValue(obj Value) int {\n\tif p, ok := obj.(*Number); ok {\n\t\treturn int(p.Value)\n\t}\n\treturn 0\n}", "func GetNumber(data []byte, keys ...string) (val float64, offset int, err error) {\n\tv, t, offset, e := Get(data, keys...)\n\n\tif e != nil {\n\t\treturn 0, offset, e\n\t}\n\n\tif t != Number {\n\t\treturn 0, offset, fmt.Errorf(\"Value is not a number: %s\", string(v))\n\t}\n\n\tval, err = strconv.ParseFloat(string(v), 64)\n\treturn\n}", "func processNumber(i interface{}) uint64 {\n\tvar n uint64\n\tswitch v := i.(type) {\n\tcase uint64:\n\t\tn = v\n\tcase string:\n\t\ts := strings.Split(v, \".\")\n\t\tn, _ = strconv.ParseUint(s[0], 10, 64)\n\tcase float64:\n\t\tn = uint64(v)\n\t}\n\treturn n\n}", "func (v *Value) GetNum() *string {\n\tret := C.zj_GetNumStr(v.V)\n\tif ret == nil {\n\t\treturn nil\n\t}\n\tretStr := C.GoString(ret)\n\treturn &retStr\n}", "func (self ValueKind) IsNumber() bool {\n\treturn bool(C.wasm_valkind_is_num(C.wasm_valkind_t(self)))\n}", "func (n *Number) Int() *big.Int {\n\tif !n.isInteger {\n\t\treturn nil\n\t}\n\treturn &n.integer\n}", "func (*Base) LiteralNumber(p ASTPass, node *ast.LiteralNumber, ctx Context) {\n}", "func (this *DatePartStr) Type() value.Type { return value.NUMBER }", "func readNumericToken(r *bufio.Reader) tok.Token {\n\tliteral, ok := readNumericLiteral(r)\n\tif !ok {\n\t\treturn tok.Token{TokenType: tok.Invalid, Literal: literal}\n\t}\n\n\tif ok := validateNumericLiteral(literal); !ok {\n\t\treturn tok.Token{TokenType: tok.Invalid, Literal: literal}\n\t}\n\n\ttokType := numericLiteralTokenType(literal)\n\n\treturn tok.Token{TokenType: tokType, Literal: literal}\n}", "func eeNumInt(v int) (n eeNum) {\r\n\t*n.int() = v\r\n\treturn\r\n}", "func (v Int) Native() interface{} {\n\treturn int64(v)\n}", "func (a *Argument) Number() float64 {\n\treturn float64(a.state.CheckNumber(a.number))\n}", "func (v Value2) Get() any { return int(v) }", "func (this *DatePartMillis) Type() value.Type { return value.NUMBER }", "func (d DecimalObj) Value() (driver.Value, error) {\n\tif !d.Valid {\n\t\treturn nil, nil\n\t}\n\treturn d.Number.Value()\n}", "func (lx *Lexer) numeralLiteral() Token {\n\tlx.token.Type = IntegerLiteral\n\tlx.token.Sub = Decimal\n\n\tdefer func() {\n\t\terr := recover()\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\n\t\t// FIXME: Show more helpful messages\n\t\tmsg := fmt.Sprintf(\"`%s` Illegal syntax of %s %s.\\n%s\",\n\t\t\tlx.token.Value(),\n\t\t\tlx.token.Sub,\n\t\t\tlx.token.Type,\n\t\t\terr,\n\t\t)\n\n\t\tpanic(lx.errf(msg))\n\t}()\n\n\tr, e := lx.peekChar()\n\tif e != nil {\n\t\tpanic(\"End of file nothing to read here\")\n\t}\n\n\tif r > '0' && r <= '9' {\n\t\tlx.consume()\n\t\tlx.separatedByUnderscore(IsNonZeroDigit, false)\n\t} else if r != '.' {\n\t\tlx.consume()\n\t\tp, _ := lx.peekChar()\n\t\tswitch {\n\t\tcase IsRuneIn(p, \"Xx\"):\n\t\t\tlx.token.Sub = Hex\n\t\t\tlx.consume()\n\n\t\t\t// 0x.BEEF is a valid float literal\n\t\t\t// but 0x is invalid integer literal\n\t\t\tif p, _ := lx.peekChar(); p != '.' {\n\t\t\t\tlx.separatedByUnderscore(IsHexDigit, true)\n\t\t\t}\n\n\t\tcase IsRuneIn(p, \"Bb\"):\n\t\t\tlx.token.Sub = Binary\n\t\t\tlx.consume()\n\t\t\tlx.separatedByUnderscore(IsBinaryDigit, true)\n\t\tcase IsDigit(p):\n\t\t\tif IsOctalDigit(p) {\n\t\t\t\tlx.token.Sub = Octal\n\t\t\t\tlx.separatedByUnderscore(IsOctalDigit, true)\n\t\t\t} else {\n\t\t\t\tpanic(\"Integer are too large.\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn lx.returnAndReset()\n}", "func (n SStr) ToNum() float64 {\n\tv, _ := strconv.ParseFloat(string(n), 64)\n\treturn v\n}", "func (i *Number) AsInt() int {\n\treturn int(i.value)\n}", "func ParseNumber(f float64) *types.TypedValue {\n\tw := &wrappers.DoubleValue{Value: f}\n\tbs, err := proto.Marshal(w)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &types.TypedValue{\n\t\tType: string(TypeNumber),\n\t\tValue: bs,\n\t}\n}", "func (n NullInt64) Value() (driver.Value, error) {\n\tif n == 0 {\n\t\treturn nil, nil\n\t}\n\treturn int64(n), nil\n}", "func (v Value) Integer() int {\n\tswitch v.Typ {\n\tdefault:\n\t\tn, _ := strconv.ParseInt(v.String(), 10, 64)\n\t\treturn int(n)\n\tcase ':':\n\t\treturn v.IntegerV\n\t}\n}", "func ParseNumberVal(s string) (cty.Value, error) {\n\t// The parsing done by big.Rat.SetString is more liberal than we want in\n\t// that it permits giving two numbers separated by a slash to give the\n\t// value as a fraction. We'll pre-screen the given string to make sure\n\t// it's using the subset of Rat number syntax we're expecting, and then\n\t// delegate to big.Rat.SetString only if it is.\n\n\tfor _, c := range s {\n\t\tif !((c >= '0' && c <= '9') || c == '.' || c == '-' || c == 'e' || c == 'E') {\n\t\t\treturn cty.NilVal, errors.New(\"invalid number syntax\")\n\t\t}\n\t}\n\n\tbr := new(big.Rat)\n\t_, ok := br.SetString(s)\n\tif !ok {\n\t\treturn cty.NilVal, errors.New(\"invalid number syntax\")\n\t}\n\treturn cty.CapsuleVal(Number, br), nil\n}", "func (p Packet) ValueNumbers() ([]Number, error) {\n\tr := make([]Number, len(p.DataTypes))\n\n\tvar err error\n\treader := bytes.NewReader(p.Bytes)\n\tfor i, t := range p.DataTypes {\n\t\tr[i], err = byteReaderToNumber(t, reader)\n\t\tif err != nil {\n\t\t\treturn []Number{}, err\n\t\t}\n\t}\n\treturn r, nil\n}", "func NewValue(s string, native bool) (*Value, error) {\n\tvar err error\n\tv := Value{\n\t\tnative: native,\n\t}\n\tmatches := valueRegex.FindStringSubmatch(s)\n\tif matches == nil {\n\t\treturn nil, fmt.Errorf(\"Invalid Number: %s\", s)\n\t}\n\tif len(matches[2])+len(matches[4]) > 32 {\n\t\treturn nil, fmt.Errorf(\"Overlong Number: %s\", s)\n\t}\n\tif matches[1] == \"-\" {\n\t\tv.negative = true\n\t}\n\tif len(matches[4]) == 0 {\n\t\tif v.num, err = strconv.ParseUint(matches[2], 10, 64); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Invalid Number: %s Reason: %s\", s, err.Error())\n\t\t}\n\t\tv.offset = 0\n\t} else {\n\t\tif v.num, err = strconv.ParseUint(matches[2]+matches[4], 10, 64); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Invalid Number: %s Reason: %s\", s, err.Error())\n\t\t}\n\t\tv.offset = -int64(len(matches[4]))\n\t}\n\tif len(matches[5]) > 0 {\n\t\texp, err := strconv.ParseInt(matches[7], 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Invalid Number: %s %s\", s, err.Error())\n\t\t}\n\t\tif matches[6] == \"-\" {\n\t\t\tv.offset -= exp\n\t\t} else {\n\t\t\tv.offset += exp\n\t\t}\n\t}\n\tif v.IsNative() && len(matches[3]) > 0 {\n\t\tv.offset += 6\n\t}\n\treturn &v, v.canonicalise()\n}", "func (p *PSParser) parseNumber() (PSObject, error) {\n\tisFloat := false\n\tallowSigns := true\n\tnumStr := \"\"\n\tfor {\n\t\tcommon.Log.Trace(\"Parsing number \\\"%s\\\"\", numStr)\n\t\tbb, err := p.reader.Peek(1)\n\t\tif err == io.EOF {\n\t\t\t// GH: EOF handling. Handle EOF like end of line. Can happen with\n\t\t\t// encoded object streams that the object is at the end.\n\t\t\t// In other cases, we will get the EOF error elsewhere at any rate.\n\t\t\tbreak // Handle like EOF\n\t\t}\n\t\tif err != nil {\n\t\t\tcommon.Log.Debug(\"PS ERROR: %s\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tif allowSigns && (bb[0] == '-' || bb[0] == '+') {\n\t\t\t// Only appear in the beginning, otherwise serves as a delimiter.\n\t\t\tb, _ := p.reader.ReadByte()\n\t\t\tnumStr += string(b)\n\t\t\tallowSigns = false // Only allowed in beginning, and after e (exponential).\n\t\t} else if pdfcore.IsDecimalDigit(bb[0]) {\n\t\t\tb, _ := p.reader.ReadByte()\n\t\t\tnumStr += string(b)\n\t\t} else if bb[0] == '.' {\n\t\t\tb, _ := p.reader.ReadByte()\n\t\t\tnumStr += string(b)\n\t\t\tisFloat = true\n\t\t} else if bb[0] == 'e' {\n\t\t\t// Exponential number format.\n\t\t\t// TODO: Is this supported in PS?\n\t\t\tb, _ := p.reader.ReadByte()\n\t\t\tnumStr += string(b)\n\t\t\tisFloat = true\n\t\t\tallowSigns = true\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif isFloat {\n\t\tfVal, err := strconv.ParseFloat(numStr, 64)\n\t\to := MakeReal(fVal)\n\t\treturn o, err\n\t}\n\tintVal, err := strconv.ParseInt(numStr, 10, 64)\n\to := MakeInteger(int(intVal))\n\treturn o, err\n}", "func (n SNumber) ToInt() int {\n\treturn int(n)\n}", "func (vl LongValue) GetType() int {\n\treturn ParticleType.INTEGER\n}", "func (vl LongValue) GetType() int {\n\treturn ParticleType.INTEGER\n}", "func (o *IncomeSummaryFieldNumber) GetValue() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Value\n}", "func (n Number) Int() int {\n\tif n == 0 {\n\t\treturn 0\n\t}\n\treturn int(math.Round(float64(n)))\n}", "func ToNumber(v interface{}) (f float64, err error) {\n\tswitch i := v.(type) {\n\tcase string:\n\t\tf, err = strconv.ParseFloat(i, 64)\n\tcase int:\n\t\tf = float64(i)\n\tcase int8:\n\t\tf = float64(i)\n\tcase int16:\n\t\tf = float64(i)\n\tcase int32:\n\t\tf = float64(i)\n\tcase int64:\n\t\tf = float64(i)\n\tcase uint:\n\t\tf = float64(i)\n\tcase uint8:\n\t\tf = float64(i)\n\tcase uint16:\n\t\tf = float64(i)\n\tcase uint32:\n\t\tf = float64(i)\n\tcase uint64:\n\t\tf = float64(i)\n\tcase float32:\n\t\tf = float64(i)\n\tcase float64:\n\t\tf = i\n\tdefault:\n\t\terr = errors.New(\"NaN\")\n\t}\n\treturn\n}", "func (s *Scanner) scanNumber() (RichToken, error) {\n\toffs := s.srcPos.Offset\n\tstartCol := s.srcPos.Column\n\ttok := NUMBER\n\tch := s.ch\n\tvar err error\n\n\t// if ch is -, move on to next digit\n\tif ch == '-' {\n\t\tch, err = s.next()\n\t}\n\n\tif ch == '0' {\n\t\tif isDecimal(s.peek()) {\n\t\t\treturn RichToken{}, fmt.Errorf(\"Column %d, Line %d: 0 cannot be followed by digit without . or exponent\",\n\t\t\t\ts.srcPos.Column, s.srcPos.Line)\n\t\t}\n\n\t\tch, err = s.next()\n\t}\n\n\t// can only have one 0, or arbitrary number of decimals\n\tif ch != '0' {\n\t\tfor isDecimal(ch) {\n\t\t\tch, err = s.next()\n\t\t}\n\t}\n\n\tif err != nil {\n\t\treturn RichToken{}, err\n\t}\n\n\t// can only have one ., following by arbitrary number of decimals\n\tif ch == '.' {\n\t\tch, err = s.next()\n\n\t\tif err != nil {\n\t\t\treturn RichToken{}, err\n\t\t} else if !isDecimal(ch) {\n\t\t\t// must have at least one decimal\n\t\t\treturn RichToken{}, fmt.Errorf(\"Column %d, Line %d: . must be followed by at least one digit\",\n\t\t\t\ts.srcPos.Column, s.srcPos.Line)\n\t\t}\n\n\t\tfor isDecimal(ch) {\n\t\t\tch, err = s.next()\n\n\t\t\tif err != nil {\n\t\t\t\treturn RichToken{}, err\n\t\t\t}\n\t\t}\n\t}\n\n\t// can have e or E\n\tif ch == 'e' || ch == 'E' {\n\t\tch, err = s.next()\n\n\t\tif err != nil {\n\t\t\treturn RichToken{}, err\n\t\t}\n\n\t\t// exponent has optional sign\n\t\tif ch == '+' || ch == '-' {\n\t\t\tch, err = s.next()\n\n\t\t\tif err != nil {\n\t\t\t\treturn RichToken{}, err\n\t\t\t}\n\t\t}\n\n\t\t// must have at least one decimal\n\t\tif !isDecimal(ch) {\n\t\t\treturn RichToken{}, fmt.Errorf(\"Column %d, Line %d: e or E must be followed by at least one digit\",\n\t\t\t\ts.srcPos.Column, s.srcPos.Line)\n\t\t}\n\n\t\t// exponent followed by arbitrary number of decimals\n\t\tfor isDecimal(ch) {\n\t\t\tch, err = s.next()\n\n\t\t\tif err != nil {\n\t\t\t\treturn RichToken{}, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn RichToken{\n\t\tpos: Position{\n\t\t\tOffset: offs,\n\t\t\tColumn: startCol,\n\t\t\tLine: s.srcPos.Line,\n\t\t},\n\t\ttok: tok,\n\t\tlit: string(s.src[offs:s.srcPos.Offset]),\n\t}, nil\n}", "func Number(in string) (out string, err error) {\n\tf := func(r rune) bool {\n\t\treturn !unicode.IsNumber(r)\n\t}\n\n\tout = strings.Join(strings.FieldsFunc(in, f), \"\")\n\tswitch {\n\tcase len(out) == 11 && out[0] == '1' && out[1] >= '2' && out[4] >= '2':\n\t\treturn out[1:], nil\n\tcase len(out) == 11 && out[0] > '1':\n\t\treturn \"\", fmt.Errorf(\"invalid number: %s\", in)\n\tcase len(out) < 10 || out[0] <= '1' || out[3] <= '1' || len(out) > 11:\n\t\treturn \"\", fmt.Errorf(\"invalid number: %s\", in)\n\t}\n\n\treturn out, nil\n}", "func (f *Feature) Number(x Example) float64 {\n\tif f.Kind != Feature_NUMERICAL {\n\t\treturn math.NaN()\n\t}\n\treturn numerify(x.GetExampleValue(f.Name))\n}", "func (n NullMoney) Value() (driver.Value, error) {\n\tif n == 0.0 {\n\t\treturn nil, nil\n\t}\n\treturn float64(n), nil\n}", "func Number(x string) (geometry.Number, error) {\n\tn, err := strconv.ParseFloat(x, 64)\n\tif err != nil {\n\t\treturn 0, ErrBadNumber\n\t}\n\treturn geometry.Number(n), nil\n}", "func lexNumber(l *lexer) stateFn {\r\nLoop:\r\n\tfor {\r\n\t\tswitch r := l.next(); {\r\n\t\tcase isDigit(r):\r\n\t\tcase r == '.':\r\n\t\t\treturn lexFloat\r\n\t\tdefault:\r\n\t\t\tl.backup()\r\n\t\t\tl.emit(TokInt)\r\n\t\t\tbreak Loop\r\n\t\t}\r\n\t}\r\n\treturn lexAny\r\n}", "func (lex *Lexer) NextNumberLit() {\n\tlex.nextWithSpecificMode(scanner.ScanNumberLit)\n}", "func (ns Int64) Value() (driver.Value, error) {\n\tif !ns.Valid {\n\t\treturn nil, nil\n\t}\n\treturn ns.Int64, nil\n}", "func (d *Document) Number(f float64) Node {\n\tid := uint(len(d.nodes))\n\tn := d.grow()\n\tn.reset(vNumber|infRoot, numjson.FormatFloat(f, 64), n.values[:0])\n\treturn d.Node(id)\n}", "func (this *Mod) Type() value.Type { return value.NUMBER }", "func (vl IntegerValue) GetType() int {\n\treturn ParticleType.INTEGER\n}", "func (vl IntegerValue) GetType() int {\n\treturn ParticleType.INTEGER\n}" ]
[ "0.70115584", "0.6969048", "0.6674587", "0.66428035", "0.6590476", "0.65527546", "0.64667314", "0.64667314", "0.64667314", "0.64667314", "0.63752025", "0.63733643", "0.6349295", "0.629919", "0.62977487", "0.62339395", "0.61801726", "0.6162864", "0.6155927", "0.6140079", "0.6071112", "0.59743387", "0.5972055", "0.59460396", "0.5890514", "0.5802353", "0.5730379", "0.57238716", "0.57128626", "0.5708427", "0.5703323", "0.5702209", "0.56894594", "0.5688472", "0.56862766", "0.5629518", "0.5628191", "0.5615868", "0.560862", "0.56066746", "0.56024617", "0.55752665", "0.5557112", "0.5553645", "0.5530039", "0.55238134", "0.55227566", "0.5506542", "0.548853", "0.54769737", "0.54720235", "0.5460816", "0.5433414", "0.54315597", "0.5429698", "0.5423063", "0.5417632", "0.54170835", "0.54163283", "0.54158217", "0.54091567", "0.538903", "0.53675133", "0.5362096", "0.53612256", "0.53593856", "0.5356899", "0.5353848", "0.5350605", "0.53496027", "0.5349367", "0.5331807", "0.5323824", "0.5316089", "0.53157616", "0.5315325", "0.53103894", "0.5306329", "0.53048944", "0.52937984", "0.5288532", "0.52840537", "0.5283257", "0.5283257", "0.5267216", "0.5260384", "0.52592754", "0.52590483", "0.5257478", "0.5254974", "0.52533257", "0.5253218", "0.5250494", "0.5236827", "0.522828", "0.522713", "0.52253157", "0.5220617", "0.5220617" ]
0.55151886
48
/ Calls the Eval method for unary functions and passes in the receiver, current item and current context.
func (this *ObjectLength) Evaluate(item value.Value, context Context) (value.Value, error) { return this.UnaryEval(this, item, context) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (fn NoArgFunc) Eval(ctx *Context, r Row) (interface{}, error) {\n\treturn fn.Logic(ctx, r)\n}", "func (bp *BinaryPlus) Eval() float64 {\n\treturn bp.left.(Eval).Eval() + bp.right.(Eval).Eval()\n}", "func (ast *Unary) Eval(env *Env, ctx *Codegen, gen *ssa.Generator) (\n\tssa.Value, bool, error) {\n\texpr, ok, err := ast.Expr.Eval(env, ctx, gen)\n\tif err != nil || !ok {\n\t\treturn ssa.Undefined, ok, err\n\t}\n\tswitch val := expr.ConstValue.(type) {\n\tcase bool:\n\t\tswitch ast.Type {\n\t\tcase UnaryNot:\n\t\t\treturn gen.Constant(!val, types.Bool), true, nil\n\t\tdefault:\n\t\t\treturn ssa.Undefined, false, ctx.Errorf(ast.Expr,\n\t\t\t\t\"invalid unary expression: %s%T\", ast.Type, val)\n\t\t}\n\tcase int32:\n\t\tswitch ast.Type {\n\t\tcase UnaryMinus:\n\t\t\treturn gen.Constant(-val, types.Int32), true, nil\n\t\tdefault:\n\t\t\treturn ssa.Undefined, false, ctx.Errorf(ast.Expr,\n\t\t\t\t\"Unary.Eval: '%s%T' not implemented yet\", ast.Type, val)\n\t\t}\n\tdefault:\n\t\treturn ssa.Undefined, false, ctx.Errorf(ast.Expr,\n\t\t\t\"invalid value %s%T\", ast.Type, val)\n\t}\n}", "func Eval(ctx context.Context, e Expr, vs Values) (interface{}, error) {\r\n\tfn, err := FuncOf(ctx, e, vs)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\treturn fn.Call(ctx, vs)\r\n}", "func (f *function) Eval(a *Apl) (Value, error) {\n\tvar err error\n\tvar l, r Value\n\n\t// The right argument must be evaluated first.\n\t// Otherwise this A←1⋄A+(A←2) evaluates to 3,\n\t// but it should evaluate to 4.\n\tr, err = f.right.Eval(a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif f.left != nil {\n\n\t\t// Special case for modified assignments.\n\t\t// Defer evaluation of the left argument.\n\t\tif d, ok := f.Function.(*derived); ok && d.op == \"←\" {\n\t\t\tl = assignment{f.left}\n\t\t} else {\n\t\t\tl, err = f.left.Eval(a)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Special case: the last function in a selective assignment uses Select instead of Call.\n\tif _, ok := f.right.(numVar); ok && f.selection {\n\t\tif d, ok := f.Function.(*derived); ok == true {\n\t\t\treturn d.Select(a, l, r)\n\t\t} else if p, ok := f.Function.(Primitive); ok == false {\n\t\t\treturn nil, fmt.Errorf(\"cannot use %T in selective assignment\", f.Function)\n\t\t} else {\n\t\t\treturn p.Select(a, l, r)\n\t\t}\n\t}\n\treturn f.Function.Call(a, l, r)\n}", "func Eval(txApp *sysl.Application, assign Scope, e *sysl.Expr) *sysl.Value {\n\tswitch x := e.Expr.(type) {\n\tcase *sysl.Expr_Transform_:\n\t\treturn evalTransform(txApp, assign, x, e)\n\tcase *sysl.Expr_Binexpr:\n\t\treturn evalBinExpr(txApp, assign, x.Binexpr)\n\tcase *sysl.Expr_Call_:\n\t\treturn evalCall(txApp, assign, x)\n\tcase *sysl.Expr_Name:\n\t\treturn evalName(assign, x)\n\tcase *sysl.Expr_GetAttr_:\n\t\treturn evalGetAttr(txApp, assign, x)\n\tcase *sysl.Expr_Ifelse:\n\t\treturn evalIfelse(txApp, assign, x)\n\tcase *sysl.Expr_Literal:\n\t\treturn x.Literal\n\tcase *sysl.Expr_Set:\n\t\treturn evalSet(txApp, assign, x)\n\tcase *sysl.Expr_List_:\n\t\treturn evalList(txApp, assign, x)\n\tcase *sysl.Expr_Unexpr:\n\t\treturn evalUnaryFunc(x.Unexpr.Op, Eval(txApp, assign, x.Unexpr.Arg))\n\tdefault:\n\t\tlogrus.Warnf(\"Skipping Expr of type %T\\n\", x)\n\t\treturn nil\n\t}\n}", "func (op *OpMinus) Eval(x, y float32) float32 {\n\treturn op.LeftChild.Eval(x, y) - op.RightChild.Eval(x, y)\n}", "func (op *OpPlus) Eval(x, y float32) float32 {\n\treturn op.LeftChild.Eval(x, y) + op.RightChild.Eval(x, y)\n}", "func (op *OpPlus) Eval(x, y float32) float32 {\n\treturn op.LeftChild.Eval(x, y) + op.RightChild.Eval(x, y)\n}", "func (e *Exp) Eval() float64 {\n\te.init()\n\tresult, _ := e.eval(e.opTree)\n\treturn result\n}", "func (f *FunctionLike) Eval(env types.Env) (types.Expr, error) {\n\treturn nil, fmt.Errorf(\"interpreterTypes.FunctionLike: cannot eval a function-like: %s\", f)\n}", "func (form *Form) Eval(scope Scope, args ...interface{}) interface{} {\n\treturn form.Fn(scope, args...)\n}", "func (op *OpX) Eval(x, y float32) float32 {\n\treturn x\n}", "func (op *OpX) Eval(x, y float32) float32 {\n\treturn x\n}", "func ExampleEval() {\n\tfmt.Println(Eval(\"5\"))\n\tfmt.Println(Eval(\"1 + 2\"))\n\tfmt.Println(Eval(\"1 - 2 + 3\"))\n\tfmt.Println(Eval(\"3 * ( 3 + 1 * 3 ) / 2\"))\n\tfmt.Println(Eval(\"3 * ( ( 3 + 1 ) * 3 ) / 2\"))\n\t//OutPut:\n\t//5\n\t//3\n\t//2\n\t//9\n\t//18\n}", "func (this *ObjectUnwrap) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (rt *invalidRuntime) Eval(vs parser.Scope, is map[string]interface{}, tid uint64) (interface{}, error) {\n\t_, err := rt.baseRuntime.Eval(vs, is, tid)\n\tif err == nil {\n\t\terr = rt.erp.NewRuntimeError(util.ErrInvalidConstruct, fmt.Sprintf(\"Unknown node: %s\", rt.node.Name), rt.node)\n\t}\n\treturn nil, err\n}", "func (this *Not) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (rt *voidRuntime) Eval(vs parser.Scope, is map[string]interface{}, tid uint64) (interface{}, error) {\n\treturn rt.baseRuntime.Eval(vs, is, tid)\n}", "func (le ListExpr) Eval(scope Scope) (interface{}, error) {\n\tif len(le.List) == 0 {\n\t\treturn le.List, nil\n\t}\n\n\tval, err := le.List[0].Eval(scope)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif macroFn, ok := val.(MacroFunc); ok {\n\t\tvar name string\n\t\tif sym, ok := le.List[0].(SymbolExpr); ok {\n\t\t\tname = sym.Symbol\n\t\t}\n\t\treturn macroFn(scope, name, le.List[1:])\n\t}\n\n\targs := []interface{}{}\n\tfor i := 1; i < len(le.List); i++ {\n\t\targ, err := le.List[i].Eval(scope)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\targs = append(args, arg)\n\t}\n\n\tif scopedFn, ok := val.(ScopedFunc); ok {\n\t\treturn scopedFn(scope, args...)\n\t}\n\n\treturn reflection.Call(val, args...)\n}", "func (o Nil) Eval(*Vm) (Object, error) { return o, nil }", "func Eval(node ast.Node, env *object.Environment, stop <-chan struct{}) object.Object {\n\tselect {\n\tcase <-stop:\n\t\treturn ConstNil\n\tdefault:\n\t}\n\n\tswitch node := node.(type) {\n\t// statements\n\tcase *ast.Program:\n\t\treturn evalProgram(node, env, stop)\n\tcase *ast.LetStatement:\n\t\tval := Eval(node.Value, env, stop)\n\t\tif isError(val) {\n\t\t\treturn val\n\t\t}\n\t\tenv.Set(node.Name.Value, val)\n\tcase *ast.ReturnStatement:\n\t\tval := Eval(node.Value, env, stop)\n\t\tif isError(val) {\n\t\t\treturn val\n\t\t}\n\t\treturn &object.ReturnValue{Value: val}\n\tcase *ast.BlockStatement:\n\t\treturn evalBlockStatement(node, env, stop)\n\tcase *ast.ExpressionStatement:\n\t\treturn Eval(node.Expression, env, stop)\n\n\t\t// expressions\n\tcase *ast.PrefixExpression:\n\t\tright := Eval(node.Right, env, stop)\n\t\tif isError(right) {\n\t\t\treturn right\n\t\t}\n\t\treturn evalPrefixExpr(node.Token, right)\n\tcase *ast.InfixExpression:\n\t\tif node.Operator == token.Assign {\n\t\t\treturn evalAssign(node, env, stop)\n\t\t}\n\n\t\tleft := Eval(node.Left, env, stop)\n\t\tif isError(left) {\n\t\t\treturn left\n\t\t}\n\t\tright := Eval(node.Right, env, stop)\n\t\tif isError(right) {\n\t\t\treturn right\n\t\t}\n\t\treturn evalInfixExpr(node.Token, left, right)\n\tcase *ast.IndexExpression:\n\t\tleft := Eval(node.Left, env, stop)\n\t\tif isError(left) {\n\t\t\treturn left\n\t\t}\n\n\t\tindex := Eval(node.Index, env, stop)\n\t\tif isError(index) {\n\t\t\treturn index\n\t\t}\n\t\treturn evalIndexExpr(node.Token, left, index)\n\tcase *ast.IfExpression:\n\t\treturn evalIfExpr(node, env, stop)\n\tcase *ast.WhileExpression:\n\t\treturn evalWhileExpr(node, env, stop)\n\tcase *ast.CallExpression:\n\t\tfunction := Eval(node.Func, env, stop)\n\t\tif isError(function) {\n\t\t\treturn function\n\t\t}\n\n\t\targs, err := evalExpressions(node.Args, env, stop)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn doFunction(node.Token, function, args, stop)\n\n\t\t// literals\n\tcase *ast.IntegerLiteral:\n\t\treturn &object.Integer{Value: node.Value}\n\tcase *ast.FloatLiteral:\n\t\treturn &object.Float{Value: node.Value}\n\tcase *ast.BooleanLiteral:\n\t\treturn boolToBoolean(node.Value)\n\tcase *ast.NilLiteral:\n\t\treturn ConstNil\n\tcase *ast.FunctionLiteral:\n\t\treturn &object.Function{Params: node.Params, Body: node.Body, Env: env}\n\tcase *ast.StringLiteral:\n\t\treturn &object.String{Value: node.Value}\n\tcase *ast.ArrayLiteral:\n\t\telems, err := evalExpressions(node.Elements, env, stop)\n\t\tif len(elems) == 1 && err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn &object.Array{Elements: elems}\n\tcase *ast.Identifier:\n\t\treturn evalIdentifier(node, env)\n\tcase *ast.AccessIdentifier:\n\t\treturn evalAccessIdentifier(node, env)\n\t}\n\treturn nil\n}", "func (inst *hiddenInstance) Eval(expr ast.Expr) Value {\n\tv := inst.Value()\n\treturn v.Context().BuildExpr(expr, Scope(v), InferBuiltins(true))\n}", "func (a *AddActivity) Eval(context activity.Context) (done bool, err error) {\n\n\t//mv := context.GetInput(ivMessage)\n\tnum1, _ := context.GetInput(ivNum1).(int)\n\tnum2, _ := context.GetInput(ivNum2).(int)\n\n\tactivityLog.Info(fmt.Sprintf(\"Num1: %d, Num2: %d\", num1, num2))\n\tactivityLog.Info(fmt.Sprintf(\"Addition is : %d\", num1+num2))\n\tcontext.SetOutput(ovAddition, num1+num2)\n\n\treturn true, nil\n}", "func (o Args) Eval(*Vm) (Object, error) { return o, nil }", "func (n *NotLikeOp) Evaluate(left, right EvalResult) (EvalResult, error) {\n\tpanic(\"implement me\")\n}", "func eval(list []*Item) int {\n\n\tvar stack *Item\n\n\tfor _, node := range list {\n\n\t\tif node.Typ == Number {\n\t\t\tstack = stack.Push(node)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar left, right *Item\n\n\t\tstack, right = stack.Pop()\n\t\tstack, left = stack.Pop()\n\n\t\tvar val int\n\t\tswitch node.Operation {\n\t\tcase \"+\":\n\t\t\tval = left.Value + right.Value\n\t\tcase \"-\":\n\t\t\tval = left.Value - right.Value\n\t\tcase \"/\":\n\t\t\t// Watch for div-by-zero\n\t\t\tval = left.Value / right.Value\n\t\tcase \"*\":\n\t\t\tval = left.Value * right.Value\n\t\t}\n\t\tstack = stack.Push(&Item{Typ: Number, Value: val})\n\t}\n\n\treturn stack.Value\n}", "func (e *BinExpr) Eval(ctx context.Context, local Scope) (_ Value, err error) {\n\ta, err := e.a.Eval(ctx, local)\n\tif err != nil {\n\t\treturn nil, WrapContextErr(err, e, local)\n\t}\n\n\tb, err := e.b.Eval(ctx, local)\n\tif err != nil {\n\t\treturn nil, WrapContextErr(err, e, local)\n\t}\n\tval, err := e.eval(ctx, a, b, local)\n\tif err != nil {\n\t\treturn nil, WrapContextErr(err, e, local)\n\t}\n\treturn val, nil\n}", "func (m *Message) Eval(vm *VM, locals Interface) (result Interface) {\n\treturn m.Send(vm, locals, locals)\n}", "func eval(sc *scope, e sexpr) sexpr {\n\te = transform(sc, e)\n\tswitch e := e.(type) {\n\tcase cons: // a function to evaluate\n\t\tcons := e\n\t\tcar := eval(sc, cons.car)\n\t\tif !isFunction(car) && !isPrimitive(car) {\n\t\t\tpanic(\"Attempted application on non-function\")\n\t\t}\n\t\tcdr := cons.cdr\n\t\targs := flatten(cdr)\n\t\tif isPrimitive(car) {\n\t\t\treturn (car.(primitive))(sc, args)\n\t\t}\n\t\tf := car.(function)\n\t\t// This is a function - evaluate all arguments\n\t\tfor i, a := range args {\n\t\t\targs[i] = eval(sc, a)\n\t\t}\n\t\treturn f(sc, args)\n\tcase sym:\n\t\treturn sc.lookup(e)\n\t}\n\treturn e\n}", "func (p *Qlang) Eval(expr string) (err error) {\n\n\treturn p.Exec([]byte(expr), \"\")\n}", "func (mr *MockExpressionNodeMockRecorder) Eval() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Eval\", reflect.TypeOf((*MockExpressionNode)(nil).Eval))\n}", "func (this *Self) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn item, nil\n}", "func (n *NotInOp) Evaluate(left, right EvalResult) (EvalResult, error) {\n\tpanic(\"implement me\")\n}", "func (f *Function) Eval(inputs ...interface{}) (args.Const, error) {\n\tlenInputs := len(inputs)\n\tif lenInputs != f.numVars {\n\t\treturn nil, errors.New(\"Number of inputs is not equal to the number of variables in function\")\n\t}\n\n\tvar operand1 args.Const\n\tvar operand2 args.Const\n\tvar operandStack []args.Const\n\n\ti := 0\n\tfor i < len(f.Args) {\n\t\tif f.typeInput(i) == args.Constant || f.typeInput(i) == args.Variable {\n\t\t\tvariable, err := f.getVar(i)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif lenInputs != 0 {\n\t\t\t\toperand, err := variable.Eval(inputs[f.varNum[variable]])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\toperandStack = append(operandStack, operand)\n\t\t\t} else {\n\t\t\t\t// If length inputs is 0, then all variables must be constant.\n\t\t\t\t// This code assumes variable is a constant and so uses 0 as an input\n\t\t\t\t// to MustEval as it will never fail as the input does not matter for constants\n\t\t\t\toperandStack = append(operandStack, variable.MustEval(0))\n\t\t\t}\n\t\t} else if f.typeInput(i) == args.Operation {\n\t\t\toperation, err := f.getOp(i)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif h, ok := unaryFuncs[operation]; ok {\n\t\t\t\tif len(operandStack) == 0 {\n\t\t\t\t\treturn nil, errors.New(\"Not enough operands\")\n\t\t\t\t}\n\n\t\t\t\toperand1, operandStack = operandStack[len(operandStack)-1], operandStack[:len(operandStack)-1]\n\t\t\t\tresult, err := h(operand1)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\toperandStack = append(operandStack, result)\n\t\t\t} else if h, ok := binaryFuncs[operation]; ok {\n\t\t\t\tif len(operandStack) < 2 {\n\t\t\t\t\treturn nil, errors.New(\"Not enough operands\")\n\t\t\t\t}\n\n\t\t\t\toperand2, operandStack = operandStack[len(operandStack)-1], operandStack[:len(operandStack)-1]\n\t\t\t\toperand1, operandStack = operandStack[len(operandStack)-1], operandStack[:len(operandStack)-1]\n\t\t\t\tresult, err := h(operand1, operand2)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\toperandStack = append(operandStack, result)\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"Operation not supported\")\n\t\t\t}\n\t\t}\n\t\ti++\n\t}\n\n\tif len(operandStack) > 1 {\n\t\treturn nil, errors.New(\"To many operands left over after calculation\")\n\t}\n\n\treturn operandStack[0], nil\n}", "func (op *OpSine) Eval(x, y float32) float32 {\n\treturn float32(math.Sin(float64(op.Child.Eval(x, y))))\n}", "func (b *Builder) Eval(desc string, f predicate.TransformFunc) *Builder {\n\tb.p.RegisterTransformation(impl.Eval(desc, f))\n\treturn b\n}", "func (e *Evaluator) Eval(expr string) (interface{}, error) {\n\tn := e.n.Copy()\n\t_expr, err := xpath.Compile(expr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"expr cannot compile: %w\", err)\n\t}\n\n\tv := _expr.Evaluate(n)\n\tswitch v := v.(type) {\n\tcase *xpath.NodeIterator:\n\t\tns := nodes(v)\n\t\tvs := make([]interface{}, 0, len(ns))\n\t\tfor i := range ns {\n\t\t\tswitch n := ns[i].(type) {\n\t\t\tcase attr:\n\t\t\t\tvs = append(vs, n.val)\n\t\t\t}\n\t\t}\n\t\tif len(vs) == len(ns) {\n\t\t\treturn vs, nil\n\t\t}\n\t\treturn ns, nil\n\t}\n\n\treturn v, nil\n}", "func (rt *baseRuntime) Eval(vs parser.Scope, is map[string]interface{}, tid uint64) (interface{}, error) {\n\tvar err error\n\n\terrorutil.AssertTrue(rt.validated, \"Runtime component has not been validated - please call Validate() before Eval()\")\n\n\tif rt.erp.Debugger != nil {\n\t\terr = rt.erp.Debugger.VisitState(rt.node, vs, tid)\n\t\trt.erp.Debugger.SetLockingState(rt.erp.MutexeOwners, rt.erp.MutexLog)\n\t\trt.erp.Debugger.SetThreadPool(rt.erp.Processor.ThreadPool())\n\t}\n\n\treturn nil, err\n}", "func (n *NotRegexpOp) Evaluate(left, right EvalResult) (EvalResult, error) {\n\tpanic(\"implement me\")\n}", "func (s *Subtraction) Evaluate(left, right EvalResult) (EvalResult, error) {\n\treturn subtractNumericWithError(left, right)\n}", "func (this *ObjectValues) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (this *ObjectValues) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (c *Context) Eval(script string) (*Value, error) {\n\t// When PHP compiles code with a non-NULL return value expected, it simply\n\t// prepends a `return` call to the code, thus breaking simple scripts that\n\t// would otherwise work. Thus, we need to wrap the code in a closure, and\n\t// call it immediately.\n\ts := C.CString(\"call_user_func(function(){\" + script + \"});\")\n\tdefer C.free(unsafe.Pointer(s))\n\n\tvptr, err := C.context_eval(c.context, s)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error executing script '%s' in context\", script)\n\t}\n\n\tval, err := NewValueFromPtr(vptr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn val, nil\n}", "func (f *CallExpression) Evaluate(ctx *Context) Value {\n\tcallable := f.Callable.Evaluate(ctx)\n\n\tif callable.Type == vtVariable {\n\t\tcallable = callable.Evaluate(ctx)\n\t}\n\n\tif callable.isCallable() {\n\t\tnewCtx := NewContext(\"\", nil)\n\t\targs := f.Args.EvaluateAll(ctx)\n\t\treturn callable.callable().Execute(newCtx, &args)\n\t}\n\n\tpanic(NewNotCallableError(callable))\n}", "func (lscript *Scripting) Eval(luacmd string, arguments ...interface{}) (*ScriptingReturnValues, error) {\n\targs := asScriptingArgs(arguments...)\n\tlargs := forLua(args)\n\tfor _, larg := range largs {\n\t\tlscript.Push(larg)\n\t}\n\tvar r *ScriptingReturnValues\n\terr := lscript.DoString(luacmd)\n\tif err != nil {\n\t\tT().P(\"script\", \"lua\").Errorf(\"scripting error: %s\", err.Error())\n\t} else {\n\t\tif err == nil {\n\t\t\tT().P(\"lua\", \"eval\").Debugf(\"%d return values on the stack\", lscript.GetTop())\n\t\t\tr = lscript.returnFromScripting(lscript.GetTop()) // return all values on the stack\n\t\t}\n\t}\n\treturn r, err\n}", "func (e *binaryExprEvaluator) eval(lhs, rhs interface{}) interface{} {\n\tswitch e.op {\n\tcase ADD:\n\t\treturn lhs.(float64) + rhs.(float64)\n\tcase SUB:\n\t\treturn lhs.(float64) - rhs.(float64)\n\tcase MUL:\n\t\treturn lhs.(float64) * rhs.(float64)\n\tcase DIV:\n\t\trhs := rhs.(float64)\n\t\tif rhs == 0 {\n\t\t\treturn float64(0)\n\t\t}\n\t\treturn lhs.(float64) / rhs\n\tdefault:\n\t\t// TODO: Validate operation & data types.\n\t\tpanic(\"invalid operation: \" + e.op.String())\n\t}\n}", "func (p *Qlang) SafeEval(expr string) (err error) {\n\n\treturn p.SafeExec([]byte(expr), \"\")\n}", "func Eval(input string, context map[string]interface{}) float64 {\n\tnode, err := Parse(input)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\texpr := &expression{node, context}\n\treturn expr.eval(expr.ast)\n}", "func (op *OpAtan) Eval(x, y float32) float32 {\n\treturn float32(math.Atan(float64(op.Child.Eval(x, y))))\n}", "func (op *OpMult) Eval(x, y float32) float32 {\n\treturn op.LeftChild.Eval(x, y) * op.RightChild.Eval(x, y)\n}", "func (i *InOp) Evaluate(left, right EvalResult) (EvalResult, error) {\n\tpanic(\"implement me\")\n}", "func prepareEvalInfixExp(opfStack, opftStack, opfdStack, argsStack *Stack) {\n\t// current token is function stop\n\tfor opftStack.Peek().(efp.Token) != opfStack.Peek().(efp.Token) {\n\t\t// calculate trigger\n\t\ttopOpt := opftStack.Peek().(efp.Token)\n\t\tif err := calculate(opfdStack, topOpt); err != nil {\n\t\t\targsStack.Peek().(*list.List).PushBack(newErrorFormulaArg(err.Error(), err.Error()))\n\t\t\topftStack.Pop()\n\t\t\tcontinue\n\t\t}\n\t\topftStack.Pop()\n\t}\n\targument := true\n\tif opftStack.Len() > 2 && opfdStack.Len() == 1 {\n\t\ttopOpt := opftStack.Pop()\n\t\tif opftStack.Peek().(efp.Token).TType == efp.TokenTypeOperatorInfix {\n\t\t\targument = false\n\t\t}\n\t\topftStack.Push(topOpt)\n\t}\n\t// push opfd to args\n\tif argument && opfdStack.Len() > 0 {\n\t\targsStack.Peek().(*list.List).PushBack(opfdStack.Pop().(formulaArg))\n\t}\n}", "func (e PackageExpr) Eval(_ rel.Scope) (rel.Value, error) {\n\treturn e.a.Eval(stdScope())\n}", "func (p *prog) Eval(input any) (v ref.Val, det *EvalDetails, err error) {\n\t// Configure error recovery for unexpected panics during evaluation. Note, the use of named\n\t// return values makes it possible to modify the error response during the recovery\n\t// function.\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tswitch t := r.(type) {\n\t\t\tcase interpreter.EvalCancelledError:\n\t\t\t\terr = t\n\t\t\tdefault:\n\t\t\t\terr = fmt.Errorf(\"internal error: %v\", r)\n\t\t\t}\n\t\t}\n\t}()\n\t// Build a hierarchical activation if there are default vars set.\n\tvar vars interpreter.Activation\n\tswitch v := input.(type) {\n\tcase interpreter.Activation:\n\t\tvars = v\n\tcase map[string]any:\n\t\tvars = activationPool.Setup(v)\n\t\tdefer activationPool.Put(vars)\n\tdefault:\n\t\treturn nil, nil, fmt.Errorf(\"invalid input, wanted Activation or map[string]any, got: (%T)%v\", input, input)\n\t}\n\tif p.defaultVars != nil {\n\t\tvars = interpreter.NewHierarchicalActivation(p.defaultVars, vars)\n\t}\n\tv = p.interpretable.Eval(vars)\n\t// The output of an internal Eval may have a value (`v`) that is a types.Err. This step\n\t// translates the CEL value to a Go error response. This interface does not quite match the\n\t// RPC signature which allows for multiple errors to be returned, but should be sufficient.\n\tif types.IsError(v) {\n\t\terr = v.(*types.Err)\n\t}\n\treturn\n}", "func (this *ObjectAdd) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.TernaryEval(this, item, context)\n}", "func (op *OpSin) Eval(x, y float32) float32 {\n\treturn float32(math.Sin(float64(op.Child.Eval(x, y))))\n}", "func (l *LikeOp) Evaluate(left, right EvalResult) (EvalResult, error) {\n\tpanic(\"implement me\")\n}", "func (e *ExpressionAtom) Evaluate(dataContext IDataContext, memory *WorkingMemory) (reflect.Value, error) {\n\tif e.Evaluated == true {\n\t\treturn e.Value, nil\n\t}\n\tif e.Variable != nil {\n\t\tval, err := e.Variable.Evaluate(dataContext, memory)\n\t\tif err != nil {\n\t\t\treturn reflect.Value{}, err\n\t\t}\n\t\te.Value = val\n\t\te.Evaluated = true\n\t\treturn val, err\n\t}\n\tif e.FunctionCall != nil {\n\t\tvalueNode := dataContext.Get(\"DEFUNC\")\n\t\targs, err := e.FunctionCall.EvaluateArgumentList(dataContext, memory)\n\t\tif err != nil {\n\t\t\treturn reflect.Value{}, err\n\t\t}\n\t\tret, err := valueNode.CallFunction(e.FunctionCall.FunctionName, args...)\n\t\tif err != nil {\n\t\t\treturn reflect.Value{}, err\n\t\t}\n\t\te.Value = ret\n\t\te.Evaluated = true\n\t\treturn ret, err\n\t}\n\tpanic(\"should not be reached\")\n}", "func (this *ObjectRemove) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.BinaryEval(this, item, context)\n}", "func (s *ScriptReal) Eval(c Scripter, keys []string, args ...interface{}) *redis.Cmd {\n\treturn s.script.Eval(c, keys, args...)\n}", "func (this *ObjectInnerValues) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (p Primitive) Eval(a *Apl) (Value, error) {\n\treturn p, nil\n}", "func (this *Element) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.BinaryEval(this, item, context)\n}", "func (op *OpY) Eval(x, y float32) float32 {\n\treturn y\n}", "func (op *OpY) Eval(x, y float32) float32 {\n\treturn y\n}", "func (s *String) Eval(_, _ *Scope) (Value, error) {\n\treturn s, nil\n}", "func (ev *Evaler) Eval(name, text string, n *parse.Chunk, ports []*Port) error {\n\top, err := ev.Compile(n)\n\tif err != nil {\n\t\treturn err\n\t}\n\tec := NewTopEvalCtx(ev, name, text, ports)\n\treturn ec.PEval(op)\n}", "func TestEval(t *testing.T) {\n\tany := `.+`\n\ttestCases := []struct {\n\t\tname string\n\t\tquery string\n\t\twantErr string\n\t\twant []values.Value\n\t}{\n\t\t{\n\t\t\tname: \"string interpolation\",\n\t\t\tquery: `\n\t\t\t\tstr = \"str\"\n\t\t\t\ting = \"ing\"\n\t\t\t\t\"str + ing = ${str+ing}\"`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewString(\"str + ing = string\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"string interpolation missing field\",\n\t\t\tquery: `\n\t\t\t\tr = makeRecord(o: {a: \"foo\", b: 42})\n\t\t\t\t\"r._value = ${r._value}\"`,\n\t\t\twantErr: any,\n\t\t},\n\t\t{\n\t\t\tname: \"string interpolation non-string type\",\n\t\t\tquery: `\n\t\t\t\tr = makeRecord(o: {a: \"foo\", b: 42})\n\t\t\t\t\"r._value = ${r.b}\"`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewString(\"r._value = 42\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"string interpolation wrong type\",\n\t\t\tquery: `\n\t\t\t\tr = makeRecord(o: {a: \"foo\", b: 42})\n\t\t\t\t\"r = ${r}\"`,\n\t\t\twantErr: any,\n\t\t},\n\t\t{\n\t\t\tname: \"call builtin function\",\n\t\t\tquery: \"six()\",\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewFloat(6.0),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"call function with fail\",\n\t\t\tquery: \"fail()\",\n\t\t\twantErr: any,\n\t\t},\n\t\t{\n\t\t\tname: \"call function with duplicate args\",\n\t\t\tquery: \"plusOne(x:1.0, x:2.0)\",\n\t\t\twantErr: any,\n\t\t},\n\t\t{\n\t\t\tname: \"binary expressions\",\n\t\t\tquery: `\n\t\t\tsix_value = six()\n\t\t\tnine_value = nine()\n\n\t\t\tfortyTwo() == six_value * nine_value\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(false),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"logical expressions short circuit\",\n\t\t\tquery: `\n six_value = six()\n nine_value = nine()\n\n not (fortyTwo() == six_value * nine_value) or fail()\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"function\",\n\t\t\tquery: `\n plusSix = (r) => r + six()\n plusSix(r:1.0) == 7.0 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"function block\",\n\t\t\tquery: `\n f = (r) => {\n r1 = 1.0 + r\n return (r + r1) / r\n }\n f(r:1.0) == 3.0 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"function block polymorphic\",\n\t\t\tquery: `\n f = (r) => {\n r2 = r * r\n return r2 / r\n }\n f(r:2.0) == 2.0 or fail()\n f(r:2) == 2 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"function with default param\",\n\t\t\tquery: `\n addN = (r,n=4) => r + n\n addN(r:2) == 6 or fail()\n addN(r:3,n:1) == 4 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"scope closing\",\n\t\t\tquery: `\n\t\t\tx = 5\n plusX = (r) => r + x\n plusX(r:2) == 7 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"nested scope mutations not visible outside\",\n\t\t\tquery: `\n\t\t\tx = 5\n xinc = () => {\n x = x + 1\n return x\n }\n xinc() == 6 or fail()\n x == 5 or fail()\n\t\t\t`,\n\t\t},\n\t\t// TODO(jsternberg): This test seems to not\n\t\t// infer the type constraints correctly for m.a,\n\t\t// but it doesn't fail.\n\t\t{\n\t\t\tname: \"return map from func\",\n\t\t\tquery: `\n toMap = (a,b) => ({\n a: a,\n b: b,\n })\n m = toMap(a:1, b:false)\n m.a == 1 or fail()\n not m.b or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"pipe expression\",\n\t\t\tquery: `\n\t\t\tadd = (a=<-,b) => a + b\n\t\t\tone = 1\n\t\t\tone |> add(b:2) == 3 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"ignore pipe default\",\n\t\t\tquery: `\n\t\t\tadd = (a=<-,b) => a + b\n\t\t\tadd(a:1, b:2) == 3 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"pipe expression function\",\n\t\t\tquery: `\n\t\t\tadd = (a=<-,b) => a + b\n\t\t\tsix() |> add(b:2.0) == 8.0 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"pipe builtin function\",\n\t\t\tquery: `\n\t\t\tsix() |> plusOne() == 7.0 or fail()\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"regex match\",\n\t\t\tquery: `\n\t\t\t\"abba\" =~ /^a.*a$/ or fail()\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"regex not match\",\n\t\t\tquery: `\n\t\t\t\"abc\" =~ /^a.*a$/ and fail()\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(false),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"not regex match\",\n\t\t\tquery: `\n\t\t\t\"abc\" !~ /^a.*a$/ or fail()\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"not regex not match\",\n\t\t\tquery: `\n\t\t\t\"abba\" !~ /^a.*a$/ and fail()\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(false),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"options metadata\",\n\t\t\tquery: `\n\t\t\toption task = {\n\t\t\t\tname: \"foo\",\n\t\t\t\trepeat: 100,\n\t\t\t}\n\t\t\ttask.name == \"foo\" or fail()\n\t\t\ttask.repeat == 100 or fail()\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(true),\n\t\t\t\tvalues.NewBool(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"query with side effects\",\n\t\t\tquery: `sideEffect() == 0 or fail()`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewInt(0),\n\t\t\t\tvalues.NewBool(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"array index expression\",\n\t\t\tquery: `\n\t\t\t\ta = [1, 2, 3]\n\t\t\t\tx = a[1]\n\t\t\t\tx == 2 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"dict expression\",\n\t\t\tquery: `\n\t\t\t\tm = [\"a\" + \"b\": 0, \"c\" + \"d\": 1]\n\t\t\t\tx = get(dict: m, key: \"ab\", default: 2)\n\t\t\t\ty = get(dict: m, key: \"cd\", default: 2)\n\t\t\t\tz = get(dict: m, key: \"ef\", default: 2)\n\t\t\t\tx == 0 and y == 1 and z == 2 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"empy dictionary\",\n\t\t\tquery: `\n\t\t\t\tm0 = [:]\n\t\t\t\tm1 = insert(dict: m0, key: \"a\", value: 0)\n\t\t\t\tm2 = insert(dict: m0, key: 0, value: \"a\")\n\t\t\t\tv1 = get(dict: m1, key: \"a\", default: -1)\n\t\t\t\tv2 = get(dict: m2, key: 0, default: \"b\")\n\t\t\t\tv1 == 0 and v2 == \"a\" or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"array index expression out of bounds low\",\n\t\t\tquery: `\n\t\t\t\ta = [1, 2, 3]\n\t\t\t\ti = -1\n\t\t\t\tx = a[i]\n\t\t\t`,\n\t\t\twantErr: any,\n\t\t},\n\t\t{\n\t\t\tname: \"array index expression out of bounds high\",\n\t\t\tquery: `\n\t\t\t\ta = [1, 2, 3]\n\t\t\t\ti = 3\n\t\t\t\tx = a[i]\n\t\t\t`,\n\t\t\twantErr: any,\n\t\t},\n\t\t{\n\t\t\tname: \"array with complex index expression\",\n\t\t\tquery: `\n\t\t\t\tf = () => ({l: 0, m: 1, n: 2})\n\t\t\t\ta = [1, 2, 3]\n\t\t\t\tx = a[f().l]\n\t\t\t\ty = a[f().m]\n\t\t\t\tz = a[f().n]\n\t\t\t\tx == 1 or fail()\n\t\t\t\ty == 2 or fail()\n\t\t\t\tz == 3 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"short circuit logical and\",\n\t\t\tquery: `\n false and fail()\n `,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(false),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"short circuit logical or\",\n\t\t\tquery: `\n true or fail()\n `,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"no short circuit logical and\",\n\t\t\tquery: `\n true and fail()\n `,\n\t\t\twantErr: any,\n\t\t},\n\t\t{\n\t\t\tname: \"no short circuit logical or\",\n\t\t\tquery: `\n false or fail()\n `,\n\t\t\twantErr: any,\n\t\t},\n\t\t{\n\t\t\tname: \"conditional true\",\n\t\t\tquery: `\n\t\t\t\tif 1 != 0 then 10 else 100\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewInt(10),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"conditional false\",\n\t\t\tquery: `\n\t\t\t\tif 1 == 0 then 10 else 100\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewInt(100),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"conditional in function\",\n\t\t\tquery: `\n\t\t\t\tf = (t, c, a) => if t then c else a\n\t\t\t\t{\n\t\t\t\t\tv1: f(t: false, c: 30, a: 300),\n\t\t\t\t\tv2: f(t: true, c: \"cats\", a: \"dogs\"),\n\t\t\t\t}\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewObjectWithValues(map[string]values.Value{\n\t\t\t\t\t\"v1\": values.NewInt(300),\n\t\t\t\t\t\"v2\": values.NewString(\"cats\"),\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"exists\",\n\t\t\tquery: `hasValue(o: makeRecord(o: {value: 1}))`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"exists null\",\n\t\t\tquery: `hasValue(o: makeRecord(o: {val: 2}))`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(false),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"invalid function parameter\",\n\t\t\tquery: `from(bucket: \"telegraf\") |> window(every: 0s)`,\n\t\t\twantErr: `error calling function \"window\" @\\d+:\\d+-\\d+:\\d+: window function requires at least one of \"every\" or \"period\" to be set and non-zero`,\n\t\t},\n\t\t{\n\t\t\t// tests that we don't nest error messages when\n\t\t\t// a function call fails and gets piped into another\n\t\t\t// function.\n\t\t\tname: \"nested function error\",\n\t\t\tquery: `from(bucket: \"telegraf\") |> window(every: 0s) |> mean()`,\n\t\t\twantErr: `error calling function \"window\" @\\d+:\\d+-\\d+:\\d+: window function requires at least one of \"every\" or \"period\" to be set and non-zero`,\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tsrc := prelude + tc.query\n\n\t\t\tctx, deps := dependency.Inject(context.Background(), dependenciestest.Default())\n\t\t\tdefer deps.Finish()\n\n\t\t\tsideEffects, _, err := runtime.Eval(ctx, src)\n\t\t\tif err != nil {\n\t\t\t\tif tc.wantErr == \"\" {\n\t\t\t\t\tt.Fatalf(\"unexpected error: %s\", err)\n\t\t\t\t}\n\n\t\t\t\t// We expect an error, so it should be a non-internal Flux error.\n\t\t\t\tif code := flux.ErrorCode(err); code == codes.Internal || code == codes.Unknown {\n\t\t\t\t\tt.Errorf(\"expected non-internal error code, got %s\", code)\n\t\t\t\t}\n\n\t\t\t\tre := regexp.MustCompile(tc.wantErr)\n\t\t\t\tif got := err.Error(); !re.MatchString(got) {\n\t\t\t\t\tt.Errorf(\"expected error to match pattern %q, but error was %q\", tc.wantErr, got)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t} else if tc.wantErr != \"\" {\n\t\t\t\tt.Fatal(\"expected error\")\n\t\t\t}\n\n\t\t\tvs := getSideEffectsValues(sideEffects)\n\t\t\tif tc.want != nil && !cmp.Equal(tc.want, vs, semantictest.CmpOptions...) {\n\t\t\t\tt.Fatalf(\"unexpected side effect values -want/+got: \\n%s\", cmp.Diff(tc.want, vs, semantictest.CmpOptions...))\n\t\t\t}\n\t\t})\n\t}\n}", "func (ev *Evaler) Eval(name, text string, n *parse.Chunk, ports []*Port) error {\n\top, err := ev.Compile(name, text, n)\n\tif err != nil {\n\t\treturn err\n\t}\n\tec := NewTopEvalCtx(ev, name, text, ports)\n\treturn ec.PEval(op)\n}", "func (e *Evaluator) Eval(expr *tipb.Expr) (types.Datum, error) {\n\tswitch expr.GetTp() {\n\tcase tipb.ExprType_Null:\n\t\treturn types.Datum{}, nil\n\tcase tipb.ExprType_Int64:\n\t\treturn e.evalInt(expr.Val)\n\tcase tipb.ExprType_Uint64:\n\t\treturn e.evalUint(expr.Val)\n\tcase tipb.ExprType_String:\n\t\treturn e.evalString(expr.Val)\n\tcase tipb.ExprType_Bytes:\n\t\treturn types.NewBytesDatum(expr.Val), nil\n\tcase tipb.ExprType_Float32:\n\t\treturn e.evalFloat(expr.Val, true)\n\tcase tipb.ExprType_Float64:\n\t\treturn e.evalFloat(expr.Val, false)\n\tcase tipb.ExprType_MysqlDecimal:\n\t\treturn e.evalDecimal(expr.Val)\n\tcase tipb.ExprType_MysqlDuration:\n\t\treturn e.evalDuration(expr.Val)\n\tcase tipb.ExprType_ColumnRef:\n\t\treturn e.evalColumnRef(expr.Val)\n\tcase tipb.ExprType_LT:\n\t\treturn e.evalLT(expr)\n\tcase tipb.ExprType_LE:\n\t\treturn e.evalLE(expr)\n\tcase tipb.ExprType_EQ:\n\t\treturn e.evalEQ(expr)\n\tcase tipb.ExprType_NE:\n\t\treturn e.evalNE(expr)\n\tcase tipb.ExprType_GE:\n\t\treturn e.evalGE(expr)\n\tcase tipb.ExprType_GT:\n\t\treturn e.evalGT(expr)\n\tcase tipb.ExprType_NullEQ:\n\t\treturn e.evalNullEQ(expr)\n\tcase tipb.ExprType_And:\n\t\treturn e.evalAnd(expr)\n\tcase tipb.ExprType_Or:\n\t\treturn e.evalOr(expr)\n\tcase tipb.ExprType_Like:\n\t\treturn e.evalLike(expr)\n\tcase tipb.ExprType_Not:\n\t\treturn e.evalNot(expr)\n\tcase tipb.ExprType_In:\n\t\treturn e.evalIn(expr)\n\tcase tipb.ExprType_Plus, tipb.ExprType_Div:\n\t\treturn e.evalArithmetic(expr)\n\t}\n\treturn types.Datum{}, nil\n}", "func (this *Mod) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.BinaryEval(this, item, context)\n}", "func (this *NowStr) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.Eval(this, item, context)\n}", "func (*Base) Unary(p ASTPass, node *ast.Unary, ctx Context) {\n\tp.Visit(p, &node.Expr, ctx)\n}", "func (i *IntNode) Eval(m memory.M) dragonscript.Value {\n\treturn dragonscript.Integer(i.value)\n}", "func (this *ObjectNames) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (this *ObjectNames) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (op *OpDiv) Eval(x, y float32) float32 {\n\treturn op.LeftChild.Eval(x, y) / op.RightChild.Eval(x, y)\n}", "func (e *Not) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {\n\tv, err := e.Child.Eval(ctx, row)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif v == nil {\n\t\treturn nil, nil\n\t}\n\n\treturn !v.(bool), nil\n}", "func (l *ListType) eval() Value {\n\treturn l\n}", "func eval(x interface{}, env map[string]interface{}) interface{} {\r\n if str, ok := isSymbol(x); ok { // variable reference\r\n\treturn env[str]\r\n }\r\n l, ok := isList(x)\r\n if !ok { // constant literal\r\n\treturn x\r\n }\r\n if len(l) == 0 {\r\n\tpanic(\"empty list\")\r\n }\r\n if str, ok := isSymbol(l[0]); ok {\r\n\tswitch (str) {\r\n\tcase \"quote\": // (quote exp)\r\n\t return l[1]\r\n\tcase \"if\": // (if test conseq alt)\r\n\t test := l[1]\r\n\t conseq := l[2]\r\n\t alt := l[3]\r\n\t r := eval(test, env)\r\n\t if b, ok := isFalse(r); ok && !b {\r\n\t\treturn eval(alt, env)\r\n\t } else {\r\n\t\treturn eval(conseq, env)\r\n\t }\r\n\tcase \"define\": // (define var exp)\r\n\t car := l[1]\r\n\t cdr := l[2]\r\n\t if str, ok = isSymbol(car); ok {\r\n\t\tenv[str] = eval(cdr, env)\r\n\t\treturn env[str]\r\n\t } else {\r\n\t\tpanic(\"define needs a symbol\")\r\n\t }\r\n\tdefault: // (proc arg...)\r\n\t car := eval(l[0], env)\r\n\t proc, ok := car.(func([]interface{})interface{})\r\n\t if !ok {\r\n\t\tpanic(\"not a procedure\")\r\n\t }\r\n args := makeArgs(l[1:], env)\r\n return proc(args)\r\n\t}\r\n }\r\n return nil\r\n}", "func (e *Not) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {\n\tv, err := e.Child.Eval(ctx, row)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif v == nil {\n\t\treturn nil, nil\n\t}\n\n\tb, ok := v.(bool)\n\tif !ok {\n\t\tb, err = types.ConvertToBool(v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn !b, nil\n}", "func (op *OpCos) Eval(x, y float32) float32 {\n\treturn float32(math.Cos(float64(op.Child.Eval(x, y))))\n}", "func evaluateExpression(c *Context, exp interface{}) interface{} {\r\n var val interface{}\r\n\r\n // fmt.Printf(\"Evaluating type %T, \\n\", exp)\r\n switch t := exp.(type) {\r\n case int:\r\n // fmt.Printf(\"Returning int %d\\n\", t)\r\n val = t\r\n case *Integer:\r\n val = t.Number\r\n case *StringPrimitive:\r\n val = t.str\r\n case string:\r\n val = t\r\n case []interface{}:\r\n val = t\r\n case *InfixExpression:\r\n // fmt.Printf(\"Evaluating infix expresison %T l: %T, r:%T\\n\", t,t.leftNode.Exp, t.rightNode.Exp)\r\n //Get the value of the left node and right\r\n lVal := evaluateExpression(c, t.leftNode.Exp)\r\n rVal := evaluateExpression(c, t.rightNode.Exp)\r\n\r\n\r\n //then apply the correct infix operator to the values\r\n val = evaluateInfixExpression(c, t.opType, lVal, rVal)\r\n\r\n case *Identifier:\r\n // fmt.Printf(\"Was identifier returning %v\\n\", t.id)\r\n if(t.id == \"nil\") {\r\n val = NewNil(0)\r\n } else {\r\n // fmt.Printf(\"Posssible indeitEifer %T\\n\", c.values[t.id])\r\n val = evaluateExpression(c, c.values[t.id])\r\n }\r\n case *CallExpression:\r\n // fmt.Printf(\"Evaluation call to %s\\n\",t.callee)\r\n\r\n //get declaration of call\r\n callDec := c.lookup(t.callee).(*FuncDeclaration)\r\n if(callDec.returnType == \"\") { //no rreturn type = unit\r\n val = &UnitType{}\r\n } else { //Evaluate the expression of the body for a value\r\n //This should produce a value and will execute all\r\n //of the code of the body as well\r\n for i, _ := range callDec.paramNodes {\r\n paramDec := callDec.paramNodes[i].Exp.(*Param)\r\n paramValue := t.paramNodes[i].Exp\r\n c.values[paramDec.id] = evaluateExpression(c, paramValue)\r\n val = c.values[paramDec.id]\r\n }\r\n\r\n }\r\n\r\n if(t.callee == \"printi\") {\r\n invokePrintI(c, t)\r\n } else if(t.callee == \"print\") {\r\n invokePrint(c, t)\r\n } else if(t.callee == \"not\") {\r\n invokeNot(c, t)\r\n } else { //Regular other user defined function do your thing!\r\n //invoke the body\r\n //Get the declaration of the calling function so we can execute it\r\n callDec := c.lookup(t.callee).(*FuncDeclaration)\r\n // fmt.Printf(\"Invoking random func \\n\")\r\n evaluateExpression(c, callDec.body.Exp)\r\n }\r\n case *IfThenElseExpression:\r\n condition := evaluateExpression(c, t.condNode.Exp).(bool)\r\n // fmt.Printf(\"Cond was %v \\n\", condition)\r\n //If else is nil then its an IfThen Exp\r\n if(t.elseNode == nil) {\r\n val = &UnitType{}\r\n if(condition) { //if the condition is true evaluatie the code inside\r\n evaluateExpression(c, t.thenNode.Exp)\r\n }\r\n } else { //otherwise its and ifThenElse\r\n if(condition) {\r\n val = evaluateExpression(c, t.thenNode.Exp)\r\n } else {\r\n val = evaluateExpression(c, t.elseNode.Exp)\r\n }\r\n }\r\n case *SeqExpression:\r\n // Value is equivalent to the last node of the seqence expression\r\n if(len(t.nodes) == 0) {\r\n val = &UnitType{}\r\n } else {\r\n // fmt.Printf(\"Seq type was %T\\n\", t.nodes[len(t.nodes)-1].Exp)\r\n val = evaluateExpression(c, t.nodes[len(t.nodes)-1].Exp)\r\n }\r\n case *Nil:\r\n val = NewNil(0)\r\n case *ArrayExp:\r\n arrType := getType(c, c.lookup(t.typeId)).(*Identifier)\r\n val = c.lookup(arrType.id)\r\n case *ForExpression:\r\n val = &UnitType{}\r\n case *LetExpression:\r\n if(len(t.exps) == 0) {\r\n val = &UnitType{}\r\n } else {\r\n // fmt.Printf(\"%T is last exp type\\n\", t.exps[len(t.exps)-1].Exp)\r\n // val = getType(c, t.exps[len(t.exps)-1].Exp)\r\n }\r\n case *Assignment:\r\n val = &UnitType{}\r\n case *RecordExp:\r\n var slc []interface{}\r\n for _, fcNode := range t.fieldCreateNodes {\r\n if b, isABinding := fcNode.Exp.(*Binding); isABinding {\r\n slc = append(slc, evaluateExpression(c, b.exp.Exp))\r\n }\r\n }\r\n val = slc\r\n default:\r\n fmt.Fprintf(os.Stderr, \"Could not evaluate exp %T\\n\", t)\r\n os.Exit(4)\r\n }\r\n\r\n return val\r\n}", "func (da *DateArith) Eval(ctx context.Context, args map[interface{}]interface{}) (interface{}, error) {\n\tt, years, months, days, durations, err := da.evalArgs(ctx, args)\n\tif t.IsZero() || err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tif !da.isAdd() {\n\t\tyears, months, days, durations = -years, -months, -days, -durations\n\t}\n\tt.Time = t.Time.Add(durations)\n\tt.Time = t.Time.AddDate(int(years), int(months), int(days))\n\n\t// \"2011-11-11 10:10:20.000000\" outputs \"2011-11-11 10:10:20\".\n\tif t.Time.Nanosecond() == 0 {\n\t\tt.Fsp = 0\n\t}\n\n\treturn t, nil\n}", "func Eval(node ast.Node, env *object.Environment) object.Object {\n\tswitch node := node.(type) {\n\n\t// Statements\n\tcase *ast.RootNode:\n\t\treturn evalRootNode(node, env)\n\n\tcase *ast.BlockStatement:\n\t\treturn evalBlockStmt(node, env)\n\n\tcase *ast.ExpressionStatement:\n\t\treturn Eval(node.Expression, env)\n\n\tcase *ast.ReturnStatement:\n\t\tval := Eval(node.ReturnValue, env)\n\t\tif isError(val) {\n\t\t\treturn val\n\t\t}\n\t\treturn &object.ReturnValue{Value: val}\n\n\tcase *ast.LetStatement:\n\t\tval := Eval(node.Value, env)\n\t\tif isError(val) {\n\t\t\treturn val\n\t\t}\n\t\tenv.Set(node.Name.Value, val)\n\n\tcase *ast.ConstStatement:\n\t\tval := Eval(node.Value, env)\n\t\tif isError(val) {\n\t\t\treturn val\n\t\t}\n\t\tenv.Set(node.Name.Value, val)\n\n\t// Expressions\n\tcase *ast.IntegerLiteral:\n\t\treturn &object.Integer{Value: node.Value}\n\n\tcase *ast.StringLiteral:\n\t\treturn &object.String{Value: node.Value}\n\n\tcase *ast.Boolean:\n\t\treturn nativeBoolToBooleanObj(node.Value)\n\n\tcase *ast.PrefixExpression:\n\t\tright := Eval(node.Right, env)\n\t\tif isError(right) {\n\t\t\treturn right\n\t\t}\n\t\treturn evalPrefixExpr(node.Operator, right, node.Token.Line)\n\n\tcase *ast.InfixExpression:\n\t\tleft := Eval(node.Left, env)\n\t\tif isError(left) {\n\t\t\treturn left\n\t\t}\n\t\tright := Eval(node.Right, env)\n\t\tif isError(right) {\n\t\t\treturn right\n\t\t}\n\t\treturn evalInfixExpr(node.Operator, left, right, node.Token.Line)\n\n\tcase *ast.PostfixExpression:\n\t\treturn evalPostfixExpr(env, node.Operator, node)\n\n\tcase *ast.IfExpression:\n\t\treturn evalIfExpr(node, env)\n\n\tcase *ast.Identifier:\n\t\treturn evalIdentifier(node, env)\n\n\tcase *ast.FunctionLiteral:\n\t\tparams := node.Parameters\n\t\tbody := node.Body\n\t\treturn &object.Function{\n\t\t\tParameters: params,\n\t\t\tBody: body,\n\t\t\tEnv: env,\n\t\t}\n\n\tcase *ast.CallExpression:\n\t\tfn := Eval(node.Function, env)\n\t\tif isError(fn) {\n\t\t\treturn fn\n\t\t}\n\t\targs := evalExprs(node.Arguments, env)\n\t\tif len(args) == 1 && isError(args[0]) {\n\t\t\treturn args[0]\n\t\t}\n\t\treturn applyFunction(fn, args, node.Token.Line)\n\n\tcase *ast.ArrayLiteral:\n\t\telements := evalExprs(node.Elements, env)\n\t\tif len(elements) == 1 && isError(elements[0]) {\n\t\t\treturn elements[0]\n\t\t}\n\t\treturn &object.Array{Elements: elements}\n\n\tcase *ast.IndexExpression:\n\t\tleft := Eval(node.Left, env)\n\t\tif isError(left) {\n\t\t\treturn left\n\t\t}\n\t\tindex := Eval(node.Index, env)\n\t\tif isError(index) {\n\t\t\treturn index\n\t\t}\n\t\treturn evalIndexExpr(left, index, node.Token.Line)\n\n\tcase *ast.HashLiteral:\n\t\treturn evalHashLiteral(node, env)\n\t}\n\n\treturn nil\n}", "func Evaluate(item interface{}, passedContext interface{}) map[string]float64 {\n\t//fmt.Fprintf(os.Stderr, \"eval:: %v %T\\n\", item, item)\n\n\tif item != nil {\n\t\tswitch passedContext.(type) {\n\t\tcase *DimContext:\n\t\t\t{\n\t\t\t\t//fmt.Fprintf(os.Stderr, \"here before processMember %v\\n\", item)\n\t\t\t\tprocessMember(item, passedContext)\n\t\t\t\t//fmt.Fprintf(os.Stderr, \"here after processMember %v %T\\n\", item, item)\n\t\t\t}\n\t\t}\n\t\tswitch v := item.(type) {\n\t\tcase hasResults:\n\t\t\t{\n\t\t\t\treturn v.Results()\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (sf *ScalarFunction) Eval(row chunk.Row) (d types.Datum, err error) {\n\tvar (\n\t\tres interface{}\n\t\tisNull bool\n\t)\n\tswitch tp, evalType := sf.GetType(), sf.GetType().EvalType(); evalType {\n\tcase types.ETInt:\n\t\tvar intRes int64\n\t\tintRes, isNull, err = sf.EvalInt(sf.GetCtx(), row)\n\t\tif mysql.HasUnsignedFlag(tp.Flag) {\n\t\t\tres = uint64(intRes)\n\t\t} else {\n\t\t\tres = intRes\n\t\t}\n\tcase types.ETString:\n\t\tres, isNull, err = sf.EvalString(sf.GetCtx(), row)\n\t}\n\n\tif isNull || err != nil {\n\t\td.SetNull()\n\t\treturn d, err\n\t}\n\td.SetValue(res, sf.RetType)\n\treturn\n}", "func (s server) Eval(ctx context.Context, req *entity.Request) (*entity.Result, error) {\n\tlog.Printf(\"Received a request: %+v\\n\", req)\n\tresult := &entity.Result{}\n\tres, err := s.usecase.Eval(req.Value)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tresult.Value = strconv.FormatFloat(res, 'G', -1, 64)\n\treturn result, nil\n}", "func execEval(_ int, p *gop.Context) {\n\targs := p.GetArgs(4)\n\tret, ret1 := types.Eval(args[0].(*token.FileSet), args[1].(*types.Package), token.Pos(args[2].(int)), args[3].(string))\n\tp.Ret(4, ret, ret1)\n}", "func (p Polynomial) Eval(arg int) ed25519.Scalar {\n\tx := ed25519.New_scalar(*big.NewInt(int64(arg)))\n\tresult := p.coeffs[0].Add(p.coeffs[1].Mul(x))\n\tx_pow := x.Copy()\n\tfor i := 2; i < len(p.coeffs); i++ {\n\t\tx_pow = x_pow.Mul(x)\n\t\tresult = result.Add(p.coeffs[i].Mul(x_pow))\n\t}\n\treturn result\n}", "func (s Scope) Eval(ctx context.Context, local Scope) (Value, error) {\n\ttuple := NewTuple()\n\tfor e := s.Enumerator(); e.MoveNext(); {\n\t\tname, expr := e.Current()\n\t\tvalue, err := expr.Eval(ctx, local)\n\t\tif err != nil {\n\t\t\treturn nil, WrapContextErr(err, expr, local)\n\t\t}\n\t\ttuple = tuple.With(name, value)\n\t}\n\treturn tuple, nil\n}", "func (t *Check) Eval(r, s string) (bool, error) {\n\treturn false, errors.New(\"Not implemented\")\n}", "func (r *Rule) Eval(devices *devices.List, rules map[string]bool) (bool, error) {\n\treturn eval(r.Expression(), devices, rules, r.ast)\n}", "func lvalCall(e *LEnv, f *LVal, a *LVal) *LVal {\n\t//If it is a builtin function, return the result of running that function\n\tif f.Builtin != nil {\n\t\treturn f.Builtin(e, a)\n\t}\n\n\t//Bind the arguments that were passed into the function\n\tfor len(a.Cell) > 0 {\n\t\tif len(f.Formals.Cell) == 0 {\n\t\t\treturn lvalErr(\"Function passed too many arguments\")\n\t\t}\n\n\t\tsym := lvalPop(f.Formals, 0)\n\n\t\tif sym.Sym == \"&\" {\n\t\t\tif len(f.Formals.Cell) != 1 {\n\t\t\t\treturn lvalErr(\"Symbol & not followed by a single symbol.\")\n\t\t\t}\n\n\t\t\tnsym := lvalPop(f.Formals, 0)\n\t\t\tlenvPut(f.Env, nsym, builtinList(e, a))\n\t\t}\n\n\t\tval := lvalPop(a, 0)\n\n\t\tlenvPut(f.Env, sym, val)\n\t}\n\n\tif len(f.Formals.Cell) == 0 {\n\t\tf.Env.Par = e\n\n\t\treturn builtinEval(f.Env, lvalAdd(lvalSexpr(), lvalCopy(f.Body)))\n\t} else {\n\t\treturn lvalCopy(f)\n\t}\n}", "func unary(typ int, op string, od1 *expr) *expr {\n\treturn &expr{\n\t\tsexp: append(exprlist{atomic(typ, op)}, od1),\n\t}\n}", "func (f UnFunc) Apply(ctx context.Context, data interface{}) (interface{}, error) {\n\treturn f(ctx, data)\n}", "func (ev *evaluator) eval(expr Expr) model.Value {\n\t// This is the top-level evaluation method.\n\t// Thus, we check for timeout/cancellation here.\n\tif err := contextDone(ev.ctx, \"expression evaluation\"); err != nil {\n\t\tev.error(err)\n\t}\n\n\tswitch e := expr.(type) {\n\tcase *AggregateExpr:\n\t\tvector := ev.evalVector(e.Expr)\n\t\treturn ev.aggregation(e.Op, e.Grouping, e.Without, e.KeepCommonLabels, e.Param, vector)\n\n\tcase *BinaryExpr:\n\t\tlhs := ev.evalOneOf(e.LHS, model.ValScalar, model.ValVector)\n\t\trhs := ev.evalOneOf(e.RHS, model.ValScalar, model.ValVector)\n\n\t\tswitch lt, rt := lhs.Type(), rhs.Type(); {\n\t\tcase lt == model.ValScalar && rt == model.ValScalar:\n\t\t\treturn &model.Scalar{\n\t\t\t\tValue: scalarBinop(e.Op, lhs.(*model.Scalar).Value, rhs.(*model.Scalar).Value),\n\t\t\t\tTimestamp: ev.Timestamp,\n\t\t\t}\n\n\t\tcase lt == model.ValVector && rt == model.ValVector:\n\t\t\tswitch e.Op {\n\t\t\tcase itemLAND:\n\t\t\t\treturn ev.vectorAnd(lhs.(vector), rhs.(vector), e.VectorMatching)\n\t\t\tcase itemLOR:\n\t\t\t\treturn ev.vectorOr(lhs.(vector), rhs.(vector), e.VectorMatching)\n\t\t\tcase itemLUnless:\n\t\t\t\treturn ev.vectorUnless(lhs.(vector), rhs.(vector), e.VectorMatching)\n\t\t\tdefault:\n\t\t\t\treturn ev.vectorBinop(e.Op, lhs.(vector), rhs.(vector), e.VectorMatching, e.ReturnBool)\n\t\t\t}\n\t\tcase lt == model.ValVector && rt == model.ValScalar:\n\t\t\treturn ev.vectorScalarBinop(e.Op, lhs.(vector), rhs.(*model.Scalar), false, e.ReturnBool)\n\n\t\tcase lt == model.ValScalar && rt == model.ValVector:\n\t\t\treturn ev.vectorScalarBinop(e.Op, rhs.(vector), lhs.(*model.Scalar), true, e.ReturnBool)\n\t\t}\n\n\tcase *Call:\n\t\treturn e.Func.Call(ev, e.Args)\n\n\tcase *MatrixSelector:\n\t\treturn ev.matrixSelector(e)\n\n\tcase *NumberLiteral:\n\t\treturn &model.Scalar{Value: e.Val, Timestamp: ev.Timestamp}\n\n\tcase *ParenExpr:\n\t\treturn ev.eval(e.Expr)\n\n\tcase *StringLiteral:\n\t\treturn &model.String{Value: e.Val, Timestamp: ev.Timestamp}\n\n\tcase *UnaryExpr:\n\t\tse := ev.evalOneOf(e.Expr, model.ValScalar, model.ValVector)\n\t\t// Only + and - are possible operators.\n\t\tif e.Op == itemSUB {\n\t\t\tswitch v := se.(type) {\n\t\t\tcase *model.Scalar:\n\t\t\t\tv.Value = -v.Value\n\t\t\tcase vector:\n\t\t\t\tfor i, sv := range v {\n\t\t\t\t\tv[i].Value = -sv.Value\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn se\n\n\tcase *VectorSelector:\n\t\treturn ev.vectorSelector(e)\n\t}\n\tpanic(fmt.Errorf(\"unhandled expression of type: %T\", expr))\n}", "func (m *MockExpressionNode) Eval() func(backend.Row) (core.Value, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Eval\")\n\tret0, _ := ret[0].(func(backend.Row) (core.Value, error))\n\treturn ret0\n}", "func (o NotOperator) Evaluate(ctx interface{}) (bool, error) {\n\t// fmt.Println(\"Not.Evaluate()\")\n\tresult, err := o.Operand.Evaluate(ctx)\n\treturn !result, err\n}", "func evaluate(arg1 *vector.Vector, oper *vector.Vector, arg2 *vector.Vector) *vector.Vector {\n\t//Store the operator in a temp string, to save typing it out\n\tvar operS string\n\toperS = oper.At(0).(string)\n\tvar val1, val2 int \n\tvar err1, err2 os.Error\n\tval1, err1 = strconv.Atoi(arg1.At(0).(string))\n\tval2, err2 = strconv.Atoi(arg2.At(0).(string))\n\t//screens for consecutive operators\n\tif(err1 != nil || err2 != nil){\n\t\tfmt.Println(\"expr: syntax error\")\n\t\tos.Exit(-2)\n\t}\n\tvar result int = -1\n\t//Evaluate based on the operator\n\tif operS == \"+\" {\n\t\tresult = val1 + val2\n\t} else if operS == \"-\" {\n\t\tresult = val1 - val2\n\t} else if operS == \"/\" {\n\t\tresult = val1 / val2\n\t} else if operS == \"*\" {\n\t\tresult = val1 * val2\n\t} else if operS == \"%\" {\n\t\tresult = val1 % val2\n\t}\n\t//Clear the arg1 vector and add the result to it, then return\n\t//(saves memory by not creating a new vector)\n\targ1.Cut(0, arg1.Len())\n\targ1.Push(strconv.Itoa(result))\n\treturn arg1\n}" ]
[ "0.65601635", "0.62554264", "0.610906", "0.6098628", "0.60711527", "0.6037241", "0.5988044", "0.5928711", "0.5928711", "0.58814615", "0.587307", "0.58361375", "0.5803793", "0.5803793", "0.5791637", "0.5744556", "0.57429147", "0.5731631", "0.5702675", "0.5695341", "0.56899124", "0.5676062", "0.56697935", "0.56211776", "0.5592483", "0.55849653", "0.558394", "0.5576499", "0.5535295", "0.5528006", "0.55279297", "0.55061173", "0.54976064", "0.54953825", "0.5475016", "0.54588026", "0.5454834", "0.5397715", "0.5373656", "0.53727204", "0.5368078", "0.5363978", "0.5363978", "0.53551155", "0.5354837", "0.5352133", "0.53508174", "0.5330089", "0.53097206", "0.5306045", "0.5288367", "0.528527", "0.5282669", "0.52825105", "0.5278601", "0.5274988", "0.5264876", "0.5263729", "0.5260502", "0.5253249", "0.52510667", "0.52458805", "0.52344036", "0.52322716", "0.5227688", "0.5227688", "0.52232075", "0.5196801", "0.51947314", "0.5179887", "0.5176868", "0.51663756", "0.5158357", "0.51531756", "0.51372516", "0.5130771", "0.5130771", "0.51301783", "0.5125869", "0.5124272", "0.512265", "0.5111888", "0.511074", "0.51081043", "0.51079035", "0.5107867", "0.5105482", "0.5097828", "0.50875163", "0.50613976", "0.50544703", "0.5051202", "0.50444084", "0.50313026", "0.50251466", "0.50213575", "0.5020417", "0.5013555", "0.50101", "0.5006659", "0.50044125" ]
0.0
-1
/ This method returns the length of the object. If the type of input is missing then return a missing value, and if not an object return a null value. Convert it to a valid Go type. Cast it to a map from string to interface and return its length by using the len function by casting it to float64.
func (this *ObjectLength) Apply(context Context, arg value.Value) (value.Value, error) { if arg.Type() == value.MISSING { return value.MISSING_VALUE, nil } else if arg.Type() != value.OBJECT { return value.NULL_VALUE, nil } oa := arg.Actual().(map[string]interface{}) return value.NewValue(float64(len(oa))), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *FakeObject) Length() int { return reflect.ValueOf(o.Value).Len() }", "func length(v interface{}) (int, error) {\n\tswitch val := v.(type) {\n\tcase string:\n\t\treturn len(val), nil\n\tcase []interface{}:\n\t\treturn len(val), nil\n\tcase map[string]interface{}:\n\t\treturn len(val), nil\n\tdefault:\n\t\treturn -1, errors.New(\"invalid type for length\")\n\t}\n}", "func (p MapStringToFloat64Ptrs) Len() int {\n\treturn len(p)\n}", "func (i StringHashMap[T, V]) Len() int {\n\t// DEBUG:\n\tif len(i.hashToKey) != len(i.hashToVal) {\n\t\tpanic(\"hashToKey and hashToVal have different lengths\")\n\t}\n\treturn len(i.hashToKey)\n}", "func (e *EventDTO) Size() int {\n\tsize := 1024\n\tif e.Properties == nil {\n\t\treturn size\n\t}\n\n\tfor key, value := range e.Properties {\n\t\tsize += len(key)\n\t\tswitch typedValue := value.(type) {\n\t\tcase string:\n\t\t\tsize += len(typedValue)\n\t\tdefault:\n\t\t}\n\t}\n\treturn size\n}", "func (d *Data) Len() int {\n\tif d.Value == nil {\n\t\treturn 0\n\t}\n\tif d.IsSlice() {\n\t\treturn d.ValueOf().Len()\n\t}\n\tif n, ok := d.IsKeys(); ok {\n\t\treturn n\n\t}\n\n\treturn 1\n}", "func (that *StrAnyMap) Size() int {\n\tthat.mu.RLock()\n\tlength := len(that.data)\n\tthat.mu.RUnlock()\n\treturn length\n}", "func SizeOf(val reflect.Value) int64 {\n\ttk := val.Type().Kind()\n\n\tif tk == reflect.Ptr {\n\t\tif val.IsNil() {\n\t\t\treturn 0\n\t\t}\n\t\tval = val.Elem()\n\t\treturn SizeOf(val)\n\t}\n\n\tif tk == reflect.Slice {\n\t\tvar size int64 = 0\n\t\tfor i := 0; i < val.Len(); i++ {\n\t\t\tsize += SizeOf(val.Index(i))\n\t\t}\n\t\treturn size\n\t} else if tk == reflect.Struct {\n\t\tvar size int64 = 0\n\t\tfor i := 0; i < val.Type().NumField(); i++ {\n\t\t\tsize += SizeOf(val.Field(i))\n\t\t}\n\t\treturn size\n\n\t} else if tk == reflect.Map {\n\t\tvar size int64 = 0\n\t\tkeys := val.MapKeys()\n\t\tfor i := 0; i < len(keys); i++ {\n\t\t\tsize += SizeOf(keys[i])\n\t\t\tsize += SizeOf(val.MapIndex(keys[i]))\n\t\t}\n\t\treturn size\n\t}\n\n\tswitch val.Type().Name() {\n\tcase \"BOOLEAN\":\n\t\treturn 1\n\tcase \"INT32\":\n\t\treturn 4\n\tcase \"INT64\":\n\t\treturn 8\n\tcase \"INT96\":\n\t\treturn 12\n\tcase \"FLOAT\":\n\t\treturn 4\n\tcase \"DOUBLE\":\n\t\treturn 8\n\tcase \"BYTE_ARRAY\":\n\t\treturn int64(val.Len())\n\tcase \"FIXED_LEN_BYTE_ARRAY\":\n\t\treturn int64(val.Len())\n\tcase \"UTF8\":\n\t\treturn int64(val.Len())\n\tcase \"INT_8\":\n\t\treturn 4\n\tcase \"INT_16\":\n\t\treturn 4\n\tcase \"INT_32\":\n\t\treturn 4\n\tcase \"INT_64\":\n\t\treturn 8\n\tcase \"UINT_8\":\n\t\treturn 4\n\tcase \"UINT_16\":\n\t\treturn 4\n\tcase \"UINT_32\":\n\t\treturn 4\n\tcase \"UINT_64\":\n\t\treturn 8\n\tcase \"DATE\":\n\t\treturn 4\n\tcase \"TIME_MILLIS\":\n\t\treturn 4\n\tcase \"TIME_MICROS\":\n\t\treturn 8\n\tcase \"TIMESTAMP_MILLIS\":\n\t\treturn 8\n\tcase \"TIMESTAMP_MICROS\":\n\t\treturn 8\n\tcase \"INTERVAL\":\n\t\treturn 12\n\tcase \"DECIMAL\":\n\t\treturn int64(val.Len())\n\t}\n\n\treturn 4\n}", "func (s *sortMap) Len() int {\n\treturn reflect.ValueOf(s.data).Len()\n}", "func (obj object) Len() int {\n\treturn len(obj.keys)\n}", "func (object Object) Length() int {\n\treturn len(object)\n}", "func (o *Object) Size() int64 {\n\terr := o.readMetaData(context.TODO())\n\tif err != nil {\n\t\tfs.Logf(o, \"Failed to read metadata: %v\", err)\n\t\treturn 0\n\t}\n\treturn o.size\n}", "func Length(i interface{}) (l int, ok bool) {\n\tv, k := preprocess(i)\n\tswitch k {\n\tcase reflect.Map, reflect.Array, reflect.Slice, reflect.String:\n\t\treturn v.Len(), true\n\t}\n\treturn 0, false\n}", "func Size(d interface{}) int {\n\treturn size(reflect.ValueOf(d))\n}", "func (o *Object) Size() int64 {\n\tctx := context.TODO()\n\terr := o.readMetaData(ctx)\n\tif err != nil {\n\t\tfs.Logf(o, \"Failed to read metadata: %v\", err)\n\t\treturn 0\n\t}\n\treturn o.size\n}", "func (pmap *PropertyMap) Size() int {\n\tif pmap == nil {\n\t\treturn 0\n\t}\n\treturn len(pmap.m)\n}", "func (node *GoValueNode) Length() (int, error) {\n\tif node.IsArray() || node.IsMap() || node.IsString() {\n\n\t\treturn node.thisValue.Len(), nil\n\t}\n\n\treturn 0, fmt.Errorf(\"this node identified as \\\"%s\\\" is not referencing an array, slice, map or string\", node.IdentifiedAs())\n}", "func LengthOfValue(value interface{}) (int, error) {\n\tv := reflect.ValueOf(value)\n\tswitch v.Kind() {\n\tcase reflect.String, reflect.Slice, reflect.Map, reflect.Array:\n\t\treturn v.Len(), nil\n\t}\n\treturn 0, fmt.Errorf(\"cannot get the length of %v\", v.Kind())\n}", "func (k *K) Len() int {\n\tif k.Type < K0 || k.Type >= KFUNC {\n\t\treturn 1\n\t} else if k.Type >= K0 && k.Type <= KT {\n\t\treturn reflect.ValueOf(k.Data).Len()\n\t} else if k.Type == XD {\n\t\treturn k.Data.(Dict).Key.Len()\n\t} else if k.Type == XT {\n\t\treturn k.Data.(Table).Data[0].Len()\n\t} else {\n\t\treturn -1\n\t}\n}", "func (hm *HashMap) Len() int {\n\treturn hm.np.elemNum()\n}", "func Length(i interface{}) (l int, ok bool) {\n\tswitch i := i.(type) {\n\tcase string:\n\t\treturn len(i), true\n\tcase []interface{}:\n\t\treturn len(i), true\n\tcase map[string]interface{}:\n\t\treturn len(i), true\n\tcase []int64:\n\t\treturn len(i), true\n\tcase []float64:\n\t\treturn len(i), true\n\tcase []bool:\n\t\treturn len(i), true\n\tcase map[string]float64:\n\t\treturn len(i), true\n\tcase map[string]string:\n\t\treturn len(i), true\n\tcase map[string]bool:\n\t\treturn len(i), true\n\tdefault:\n\t\treturn 0, false\n\t}\n}", "func (self *Map) Len() int {\n\treturn len(self.MapNative())\n}", "func (m Map) Length() int {\n\treturn len(m)\n}", "func (i IntHashMap[T, V]) Len() int {\n\t// DEBUG:\n\tif len(i.hashToKey) != len(i.hashToVal) {\n\t\tpanic(\"hashToKey and hashToVal have different lengths\")\n\t}\n\treturn len(i.hashToKey)\n}", "func GetSize(i interface{}) (int, error) {\n\tb := new(bytes.Buffer)\n if err := json.NewEncoder(b).Encode(i); err != nil {\n\t\treturn 0, fmt.Errorf(\"Failed to encode object of type (%T): %v\", i, err)\n\t}\n\treturn b.Len(), nil\n}", "func (o *Object) Size() int64 {\n\tif o.meta == nil {\n\t\treturn o.size\n\t}\n\treturn o.meta.Size\n}", "func (o *Object) Size() int64 {\n\treturn o.size\n}", "func Len(m Map) int {\n\treturn m.count()\n}", "func (m *OrderedMap[K, V]) Len() int {\n\tif m == nil {\n\t\treturn 0\n\t}\n\treturn m.len\n}", "func (hm HashMap) Len(ctx context.Context) (int64, error) {\n\treq := newRequest(\"*2\\r\\n$4\\r\\nHLEN\\r\\n$\")\n\treq.addString(hm.name)\n\treturn hm.c.cmdInt(ctx, req)\n}", "func (d *MetadataAsDictionary) Size() int {\n\tif d.metadata != nil {\n\t\treturn len(d.metadata)\n\t}\n\n\treturn len(d.source)\n}", "func Len(val Value) (int, error) {\n\tif val == nil {\n\t\treturn 0, nil\n\t}\n\tr := reflect.Indirect(reflect.ValueOf(val))\n\tswitch r.Kind() {\n\tcase reflect.Slice, reflect.Array, reflect.Map:\n\t\treturn r.Len(), nil\n\t}\n\treturn 0, fmt.Errorf(`stick: could not get Length of %s \"%v\"`, r.Kind(), val)\n}", "func (v *Value) Size() JSONSize {\n\treturn JSONSize(C.zj_SizeOf(v.V))\n}", "func (o *Object) Size() int64 {\n\treturn o.bytes\n}", "func (m *Map[K, V]) Len() int {\n\tm.mu.RLock()\n\tdefer m.mu.RUnlock()\n\n\treturn len(m.inner)\n}", "func (jz *Jzon) Length() (l int, err error) {\n\tif jz.Type == JzTypeArr {\n\t\treturn len(jz.data.([]*Jzon)), nil\n\t}\n\n\tif jz.Type == JzTypeObj {\n\t\treturn len(jz.data.(map[string]*Jzon)), nil\n\t}\n\n\treturn -1, errors.New(\"expect node of type JzTypeArr or JzTypeObj\" +\n\t\t\", but the real type is \" + typeStrings[jz.Type])\n}", "func (this *ExDomain) Size() int {\n\treturn len(this.Values) // assumes no mappings to false\n}", "func (this *ObjectLength) Type() value.Type { return value.NUMBER }", "func (this *ObjectLength) Type() value.Type { return value.NUMBER }", "func (sm *ScanMap) Length() int {\n\treturn len(sm.hashMap)\n}", "func (tt Map) Len() int {\n\treturn len(tt)\n}", "func (m Map) Len() int {\n\treturn m.n\n}", "func (f DFields) Len() int { return len(f) }", "func sizeof(v reflect.Value, t reflect.Type) int {\n\tswitch t.Kind() {\n\tcase reflect.Array:\n\t\tif s := sizeof(v, t.Elem()); s >= 0 {\n\t\t\treturn s * t.Len()\n\t\t}\n\n\tcase reflect.Struct:\n\t\tsum := 0\n\t\tfor i, n := 0, t.NumField(); i < n; i++ {\n\t\t\ts := dataSize(v.Field(i))\n\t\t\tif s < 0 {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\tsum += s\n\t\t}\n\t\treturn sum\n\n\tcase reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint,\n\t\treflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int,\n\t\treflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128,\n\t\treflect.Uintptr, reflect.Ptr:\n\t\treturn int(t.Size())\n\n\tcase reflect.String:\n\t\treturn len(v.String())\n\n\tcase reflect.Map:\n\t\tsum := 0\n\t\tfor _, mapKey := range v.MapKeys() {\n\t\t\tkeySize := dataSize(mapKey)\n\t\t\tvalueSize := dataSize(v.MapIndex(mapKey))\n\t\t\tif keySize < 0 || valueSize < 0 {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\tsum += keySize + valueSize\n\t\t}\n\t\treturn sum\n\t}\n\n\treturn -1\n}", "func (geom Geometry) Length() float64 {\n\tlength := C.OGR_G_Length(geom.cval)\n\treturn float64(length)\n}", "func (v valuer) Len() int {\n\treturn len(v.data)\n}", "func size(v interface{}) int {\n\treturn dataSize(reflect.Indirect(reflect.ValueOf(v)))\n}", "func fnLen(ctx Context, doc *JDoc, params []string) interface{} {\n\tstats := ctx.Value(EelTotalStats).(*ServiceStats)\n\tif params == nil || len(params) != 1 {\n\t\tctx.Log().Error(\"error_type\", \"func_len\", \"op\", \"len\", \"cause\", \"wrong_number_of_parameters\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"wrong number of parameters in call to len function\"), \"len\", params})\n\t\treturn nil\n\t}\n\tvar obj interface{}\n\terr := json.Unmarshal([]byte(extractStringParam(params[0])), &obj)\n\tif err != nil {\n\t\treturn len(extractStringParam(params[0]))\n\t}\n\tswitch obj.(type) {\n\tcase []interface{}:\n\t\treturn len(obj.([]interface{}))\n\tcase map[string]interface{}:\n\t\treturn len(obj.(map[string]interface{}))\n\t}\n\treturn 0\n}", "func Size(v interface{}) int {\n\treturn dataSize(reflect.Indirect(reflect.ValueOf(v)))\n}", "func (fm *FieldModelMapInt32OptionalBytes) Size() int {\n if (fm.buffer.Offset() + fm.FBEOffset() + fm.FBESize()) > fm.buffer.Size() {\n return 0\n }\n\n fbeMapOffset := int(fbe.ReadUInt32(fm.buffer.Data(), fm.buffer.Offset() + fm.FBEOffset()))\n if (fbeMapOffset == 0) || ((fm.buffer.Offset() + fbeMapOffset + 4) > fm.buffer.Size()) {\n return 0\n }\n\n fbeMapSize := int(fbe.ReadUInt32(fm.buffer.Data(), fm.buffer.Offset() + fbeMapOffset))\n return fbeMapSize\n}", "func (m *Map) Len() int {\n\treturn int(m.len)\n}", "func (o Object) Size() Size {\n\treturn o.size\n}", "func (t colType) length() (int64, bool) {\n\tif !t.valid ||\n\t\tt.options&hasPrec != 0 || t.options&hasScale != 0 {\n\t\treturn 0, false\n\t}\n\n\t// long types\n\tif t.options&isLong != 0 {\n\t\tif t.dataType == longCharType {\n\t\t\treturn int64(t.size / 2), true\n\t\t}\n\t\tif t.encodingProps.scanType == reflect.TypeOf(\"\") {\n\t\t\treturn int64(t.size), true\n\t\t}\n\t\treturn math.MaxInt32, true\n\t}\n\n\treturn int64(t.size), t.options&hasLength != 0\n}", "func (f Floats) Len() int {\n\tw, h := f.Size()\n\treturn w * h\n}", "func (wm *W3CMap) Length() int {\n\tif wm == nil {\n\t\treturn 0\n\t}\n\treturn len(wm.forNode.HTMLNode().Attr)\n}", "func ilen(data interface{}) (int, error) {\n\n\tswitch data.(type) {\n\tcase []float64:\n\t\treturn len(data.([]float64)), nil\n\tcase []string:\n\t\treturn len(data.([]string)), nil\n\tcase []int64:\n\t\treturn len(data.([]int64)), nil\n\tcase []int32:\n\t\treturn len(data.([]int32)), nil\n\tcase []float32:\n\t\treturn len(data.([]float32)), nil\n\tcase []int16:\n\t\treturn len(data.([]int16)), nil\n\tcase []int8:\n\t\treturn len(data.([]int8)), nil\n\tcase []uint64:\n\t\treturn len(data.([]uint64)), nil\n\tcase []time.Time:\n\t\treturn len(data.([]time.Time)), nil\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"Unknown data type\")\n\t}\n}", "func (m *TMap) Length() int {\n\treturn m.root.Length()\n}", "func (mm Uint64Uint64Map) Size() int {\n\treturn len(mm)\n}", "func (m *OrderedMap[K,V]) Len() int {\n\treturn len(m.mp)\n}", "func (v *Value) len(params ...interface{}) (interface{}, error) {\n\tif len(params) != 0 {\n\t\treturn nil, newParamLenErr(len(params), 0)\n\t}\n\n\treturn len(*v), nil\n}", "func (m *Mapping) Len() int { return len(m.Pairs) }", "func (m *mapReact) Length() int {\n\tvar l int\n\tm.ro.RLock()\n\tl = len(m.ma)\n\tm.ro.RUnlock()\n\treturn l\n}", "func (f *Fields) Len() int", "func len(v Type) int32 {}", "func Sizeof(objs ...interface{}) (sz uint64) {\n\tfor i := range objs {\n\t\tsz += sizeofInternal(reflect.ValueOf(objs[i]), false, 0)\n\t}\n\treturn\n}", "func Sizeof(objs ...interface{}) (sz uint64) {\n\tfor i := range objs {\n\t\tsz += sizeofInternal(reflect.ValueOf(objs[i]), false, 0)\n\t}\n\treturn\n}", "func (s *Int64Map) Len() int {\n\treturn int(atomic.LoadInt64(&s.length))\n}", "func (hm HashMap) Len() uint32 {\n\treturn hm.len\n}", "func (radius *RADIUS) Len() (int, error) {\n\tn := radiusMinimumRecordSizeInBytes\n\tfor _, v := range radius.Attributes {\n\t\talen, err := attributeValueLength(v.Value)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tn += int(alen) + 2 // Added Type and Length\n\t}\n\treturn n, nil\n}", "func (m LoyaltyPoints) Len() int64 {\n\treturn AssetTypeLen\n}", "func (sp DiscreteObjectSpace) Size() int {\n\treturn len(sp.Objects)\n}", "func CalcLength(val interface{}) int {\n\tif val == nil {\n\t\treturn -1\n\t}\n\n\t// string length\n\tif str, ok := val.(string); ok {\n\t\treturn len(str)\n\t}\n\treturn ValueLen(reflect.ValueOf(val))\n}", "func size(v Type) int32 {}", "func (m *MapStringUint64) Len() int {\n\tm.mu.RLock()\n\tl := len(m.m)\n\tm.mu.RUnlock()\n\treturn l\n}", "func (p *SliceOfMap) Len() int {\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn len(*p)\n}", "func (c *StringValueMap) Len() int {\n\treturn len(c.value)\n}", "func (f CFields) Len() int { return len(f) }", "func (m Map) Len() (n int) {\n\treturn len(m)\n}", "func lengthdict(interpreter *Interpreter) {\n\tdictionary := interpreter.Pop().(Dictionary)\n\tinterpreter.Push(float64(len(dictionary)))\n}", "func (m *HashMap) Len() int {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\treturn len(m.data)\n}", "func (fi *FastIntegerHashMap) Len() uint64 {\n\treturn fi.count\n}", "func nodeLen(data interface{}) int {\n\tif data == nil {\n\t\treturn 0\n\t}\n\tswitch d := data.(type) {\n\tcase []interface{}:\n\t\treturn len(d)\n\tcase map[string]interface{}:\n\t\treturn len(d)\n\tcase string, int, float64, bool:\n\t\treturn 1\n\t}\n\treturn 0\n}", "func (s *SliceOfFloat64) Len() int {\n\treturn len(s.items)\n}", "func (m OrderedMap[K, V]) Len() int {\n\treturn len(m.items)\n}", "func (this ActivityStreamsImageProperty) Len() (length int) {\n\treturn len(this.properties)\n}", "func (b *byWidth) Len() int {\n\treturn len(b.Values)\n}", "func (m *OrderedMap) Len() int { return len(m.m) }", "func (tt PMap) Len() int {\n\treturn len(tt)\n}", "func (h Handle) Len() int {\n\tl := 8 + 8 + 4 + len(h.Type) + len(h.Name)\n\tif h.MD != nil {\n\t\tswitch h.MD.(type) {\n\t\tcase *AlpcPortInfo:\n\t\t\tl += 16\n\t\tcase *MutantInfo:\n\t\t\tl += 5\n\t\tcase *FileInfo:\n\t\t\tl++\n\t\t}\n\t}\n\treturn l\n}", "func (h *MapInt16ToInt64) Size() int {\n\treturn h.size\n}", "func (t *Map) Len() int {\n\treturn t.keys.Len()\n}", "func (t *Struct) Size() int32 {\n\tret := int32(0)\n\tfor _, field := range t.Fields {\n\t\tret += field.Size()\n\t}\n\treturn ret\n}", "func LengthModifier(i interface{}) (interface{}, error) {\n\tswitch v := i.(type) {\n\tcase string:\n\t\treturn len(v), nil\n\tcase float64:\n\t\t// TODO: this is not counting decimal portion\n\t\t// (probably because float error can make it really long for some values)\n\t\treturn getIntLength(int(v)), nil\n\tcase int:\n\t\treturn getIntLength(v), nil\n\tcase int64:\n\t\treturn getInt64Length(v), nil\n\tcase map[string]interface{}:\n\t\treturn len(v), nil\n\tcase []interface{}:\n\t\treturn len(v), nil\n\tcase []string:\n\t\treturn len(v), nil\n\tcase []int:\n\t\treturn len(v), nil\n\tcase []float64:\n\t\treturn len(v), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Invalid type (%v) for len()\", reflect.TypeOf(i))\n\t}\n}", "func (d Datapoints) Len() int { return len(d) }", "func JSONObjLen(conn redis.Conn, key, path string) (res interface{}, err error) {\n\tname, args, _ := CommandBuilder(\"JSON.OBJLEN\", key, path)\n\treturn conn.Do(name, args...)\n}", "func (cm *CMap) Size() int {\n\treturn len(cm.Entries)\n}", "func (info *Metadata) Length() int {\n\treturn info.length\n}", "func (v Value) Len() int {\n\treturn len(v.val)\n}", "func (s *f64) Len() int {\n\treturn len(s.buffer)\n}" ]
[ "0.6576737", "0.641415", "0.6306101", "0.6094734", "0.60418206", "0.6018301", "0.5996876", "0.59715265", "0.5953909", "0.5932843", "0.590009", "0.5885789", "0.5872587", "0.58563036", "0.58299994", "0.57967377", "0.57810503", "0.576028", "0.5746586", "0.57231796", "0.5718099", "0.57130563", "0.5712192", "0.57087547", "0.56960803", "0.5650257", "0.5621568", "0.561032", "0.5605109", "0.55665344", "0.55663556", "0.5564296", "0.5555391", "0.5552163", "0.5544846", "0.55388975", "0.55151737", "0.55142874", "0.55142874", "0.5507523", "0.5505992", "0.5501291", "0.550112", "0.54994816", "0.5495123", "0.54892087", "0.54853606", "0.54722005", "0.54714847", "0.5469408", "0.5469076", "0.54653263", "0.5453398", "0.5427858", "0.5427081", "0.5424623", "0.5411553", "0.54099095", "0.5407363", "0.5405828", "0.5396861", "0.5395147", "0.5390425", "0.5381282", "0.5378466", "0.5378466", "0.5377639", "0.53730893", "0.5373045", "0.53711814", "0.53625077", "0.5336773", "0.53339994", "0.5330068", "0.53290534", "0.5307847", "0.53043723", "0.52982235", "0.5295901", "0.5295243", "0.5291098", "0.52894986", "0.5288736", "0.52838606", "0.5281311", "0.5280893", "0.5269588", "0.52664614", "0.52635926", "0.52607536", "0.5234855", "0.5226513", "0.5221009", "0.5217836", "0.52177435", "0.5216008", "0.52087706", "0.5207614", "0.51922244" ]
0.596643
9
/ The constructor returns a NewObjectLength with the an operand cast to a Function as the FunctionConstructor.
func (this *ObjectLength) Constructor() FunctionConstructor { return func(operands ...Expression) Function { return NewObjectLength(operands[0]) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *ObjectAdd) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectAdd(operands[0], operands[1], operands[2])\n\t}\n}", "func (this *ObjectRemove) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectRemove(operands[0], operands[1])\n\t}\n}", "func (this *ObjectUnwrap) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectUnwrap(operands[0])\n\t}\n}", "func (this *ObjectPut) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectPut(operands[0], operands[1], operands[2])\n\t}\n}", "func (this *ObjectValues) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectValues(operands[0])\n\t}\n}", "func (this *ObjectValues) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectValues(operands[0])\n\t}\n}", "func (this *ObjectNames) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectNames(operands[0])\n\t}\n}", "func (this *ObjectNames) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectNames(operands[0])\n\t}\n}", "func (this *DateAddMillis) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewDateAddMillis(operands[0], operands[1], operands[2])\n\t}\n}", "func (this *DateAddStr) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewDateAddStr(operands[0], operands[1], operands[2])\n\t}\n}", "func NewObjectLength(operand Expression) Function {\n\trv := &ObjectLength{\n\t\t*NewUnaryFunctionBase(\"object_length\", operand),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func NewObjectLength(operand Expression) Function {\n\trv := &ObjectLength{\n\t\t*NewUnaryFunctionBase(\"object_length\", operand),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func (this *DateDiffMillis) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewDateDiffMillis(operands[0], operands[1], operands[2])\n\t}\n}", "func (this *DateDiffStr) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewDateDiffStr(operands[0], operands[1], operands[2])\n\t}\n}", "func (this *Mod) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewMod(operands[0], operands[1])\n\t}\n}", "func (this *ObjectInnerValues) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectInnerValues(operands[0])\n\t}\n}", "func (this *ObjectPairs) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectPairs(operands[0])\n\t}\n}", "func (this *ObjectPairs) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectPairs(operands[0])\n\t}\n}", "func NewConstructor(x interface{}) (*Constructor, error) {\n\tif x == nil {\n\t\treturn nil, kerror.New(kerror.EViolation, \"function expected, nil given\")\n\t}\n\tft := reflect.TypeOf(x)\n\tfv := reflect.ValueOf(x)\n\tif ft.Kind() != reflect.Func {\n\t\treturn nil, kerror.Newf(kerror.EViolation, \"function expected, %s given\", ft)\n\t}\n\tif fv.IsNil() {\n\t\treturn nil, kerror.New(kerror.EViolation, \"function expected, nil given\")\n\t}\n\tc := &Constructor{\n\t\tfunction: fv,\n\t}\n\tnumIn := ft.NumIn()\n\tif ft.IsVariadic() {\n\t\tnumIn--\n\t}\n\tc.inTypes = make([]reflect.Type, numIn)\n\tfor i := 0; i < numIn; i++ {\n\t\tc.inTypes[i] = ft.In(i)\n\t}\n\tswitch ft.NumOut() {\n\tdefault:\n\t\treturn nil, kerror.Newf(kerror.EViolation, \"function %s is not a constructor\", ft)\n\tcase 1:\n\t\tc.t = ft.Out(0)\n\t\tc.objectOutIndex = 0\n\t\tc.destructorOutIndex = -1\n\t\tc.errorOutIndex = -1\n\tcase 2:\n\t\tif ft.Out(1) != errorType {\n\t\t\treturn nil, kerror.Newf(kerror.EViolation, \"function %s is not a constructor\", ft)\n\t\t}\n\t\tc.t = ft.Out(0)\n\t\tc.objectOutIndex = 0\n\t\tc.destructorOutIndex = -1\n\t\tc.errorOutIndex = 1\n\tcase 3:\n\t\tif ft.Out(1) != destructorType || ft.Out(2) != errorType {\n\t\t\treturn nil, kerror.Newf(kerror.EViolation, \"function %s is not a constructor\", ft)\n\t\t}\n\t\tc.t = ft.Out(0)\n\t\tc.objectOutIndex = 0\n\t\tc.destructorOutIndex = 1\n\t\tc.errorOutIndex = 2\n\t}\n\treturn c, nil\n}", "func (this *NowMillis) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function { return _NOW_MILLIS }\n}", "func (this *DateTruncStr) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewDateTruncStr(operands[0], operands[1])\n\t}\n}", "func (this *DatePartStr) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewDatePartStr(operands[0], operands[1])\n\t}\n}", "func (this *StrToMillis) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewStrToMillis(operands[0])\n\t}\n}", "func (this *DatePartMillis) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewDatePartMillis(operands[0], operands[1])\n\t}\n}", "func (this *StrToZoneName) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewStrToZoneName(operands[0], operands[1])\n\t}\n}", "func (this *Element) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewElement(operands[0], operands[1])\n\t}\n}", "func (this *ObjectInnerPairs) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectInnerPairs(operands[0])\n\t}\n}", "func (this *DateTruncMillis) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewDateTruncMillis(operands[0], operands[1])\n\t}\n}", "func (this *NowStr) Constructor() FunctionConstructor { return NewNowStr }", "func (this *ClockMillis) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function { return _CLOCK_MILLIS }\n}", "func Function(args ...Type) *Operator {\n\treturn &Operator{functionName, args}\n}", "func New(spec *Spec) Function {\n\tf := Function{\n\t\tspec: spec,\n\t}\n\treturn f\n}", "func (this *StrToUTC) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewStrToUTC(operands[0])\n\t}\n}", "func (this *Not) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewNot(operands[0])\n\t}\n}", "func (f Function) New(ctx string) error {\n\treturn f.unsafeWrap(errors.New(ctx), ctx, \"\")\n}", "func NewFunction(retType types.WaccType, ident *Ident, params ParamList,\n\tstats Statement, pos errors.Position) *Function {\n\tfn := &Function{\n\t\tretType: retType,\n\t\tident: ident,\n\t\tparams: params,\n\t\tpos: pos,\n\t}\n\tswitch st := stats.(type) {\n\tcase StatMultiple:\n\t\tfn.stats = st\n\tdefault:\n\t\tfn.stats = StatMultiple{st}\n\t}\n\treturn fn\n}", "func (this *MillisToStr) Constructor() FunctionConstructor { return NewMillisToStr }", "func NewFunction(name string, typ semantic.Type, call func(args Object) (Value, error), sideEffect bool) Function {\n\treturn &function{\n\t\tname: name,\n\t\tt: typ,\n\t\tcall: call,\n\t\thasSideEffect: sideEffect,\n\t}\n}", "func NewFunction(ctx sctx.Context, funcName string, retType *types.FieldType, args ...Expression) (Expression, error) {\n\treturn newFunctionImpl(ctx, true, funcName, retType, args...)\n}", "func tcNew(n *ir.UnaryExpr) ir.Node {\n\tif n.X == nil {\n\t\t// Fatalf because the OCALL above checked for us,\n\t\t// so this must be an internally-generated mistake.\n\t\tbase.Fatalf(\"missing argument to new\")\n\t}\n\tl := n.X\n\tl = typecheck(l, ctxType)\n\tt := l.Type()\n\tif t == nil {\n\t\tn.SetType(nil)\n\t\treturn n\n\t}\n\tn.X = l\n\tn.SetType(types.NewPtr(t))\n\treturn n\n}", "func NewFunc(name string, typ Type) *Func {\n\treturn &Func{object: object{scope: nil, name: name, typ: typ}}\n}", "func NewFunction(ifunc IFunction, name string) IQueryField {\n\treturn &SFunctionFieldBase{\n\t\tIFunction: ifunc,\n\t\talias: name,\n\t}\n}", "func (this *ClockStr) Constructor() FunctionConstructor { return NewClockStr }", "func newFunction(p *Package, fl *File, f *ast.FuncDecl) *Function {\n\tres := &Function{\n\t\tpkg: p,\n\t\tfile: fl,\n\t\tfn: f,\n\t\tname: nameFromIdent(f.Name),\n\t\tdef: getFunc(p, fl, f.Type).(*FuncType),\n\t}\n\n\tif res.fn.Recv != nil {\n\t\tn := \"\"\n\t\tif res.fn.Recv.List[0].Names != nil {\n\t\t\tn = nameFromIdent(res.fn.Recv.List[0].Names[0])\n\t\t}\n\t\tres.receiver = newVariableFromExpr(res.pkg, res.file, n, res.fn.Recv.List[0].Type)\n\t\tvar def Definition\n\t\tvar def2 *StarType\n\t\tdef = res.receiver.def\n\t\tdef2, res.receiverPointer = def.(*StarType)\n\t\tif res.receiverPointer {\n\t\t\tdef = def2.Target()\n\t\t}\n\t\tres.receiverClass = def.String()\n\t}\n\treturn res\n}", "func (this *MillisToZoneName) Constructor() FunctionConstructor { return NewMillisToZoneName }", "func NewFunction(name, cname, comment, member string, typ Type) *Function {\n\tfunctionName := UpperFirstCharacter(name)\n\treceiverType := TrimLanguagePrefix(cname)\n\treceiverName := CommonReceiverName(receiverType)\n\n\tf := &Function{\n\t\tIncludeFiles: NewIncludeFiles(),\n\t\tName: functionName,\n\t\tCName: cname,\n\t\tComment: comment,\n\t\tParameters: []FunctionParameter{ // TODO(go-clang): this might not be needed if the receiver code is refactored: https://github.com/go-clang/gen/issues/52\n\t\t\t{\n\t\t\t\tName: receiverName,\n\t\t\t\tCName: cname,\n\t\t\t\tType: Type{\n\t\t\t\t\tGoName: receiverType,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tReturnType: typ,\n\t\tReceiver: Receiver{\n\t\t\tName: receiverName,\n\t\t\tType: Type{\n\t\t\t\tGoName: receiverType,\n\t\t\t},\n\t\t},\n\t\tMember: &FunctionParameter{\n\t\t\tName: member,\n\t\t\tType: typ,\n\t\t},\n\t}\n\n\treturn f\n}", "func (this *MillisToUTC) Constructor() FunctionConstructor { return NewMillisToUTC }", "func NewFunction(fnLit *ast.FunctionLiteral, env *Environment) *Function {\n\treturn &Function{\n\t\tParameters: fnLit.Parameters,\n\t\tBody: fnLit.Body,\n\t\tEnv: env,\n\t}\n}", "func Constructor() MapSum {\n\treturn MapSum{}\n}", "func execNewFunc(_ int, p *gop.Context) {\n\targs := p.GetArgs(4)\n\tret := types.NewFunc(token.Pos(args[0].(int)), args[1].(*types.Package), args[2].(string), args[3].(*types.Signature))\n\tp.Ret(4, ret)\n}", "func NewFunction(config *truce.HTTP, function truce.Function) (*Function, error) {\n\tif function.Transports.HTTP == nil {\n\t\treturn nil, nil\n\t}\n\n\ttransport := *function.Transports.HTTP\n\n\tb := &Function{\n\t\tDefinition: function,\n\t\tQuery: map[string]QueryParam{},\n\t}\n\n\ttype argument struct {\n\t\tvariable string\n\t\tposVariable string\n\t\ttyp string\n\t}\n\n\tvar (\n\t\tpathMappings = map[string]string{}\n\t\targs = map[string]argument{}\n\t)\n\n\tfor i, field := range function.Arguments {\n\t\targs[field.Name] = argument{\n\t\t\ttyp: string(field.Type),\n\t\t\tposVariable: fmt.Sprintf(\"v%d\", i),\n\t\t\tvariable: field.Name,\n\t\t}\n\t}\n\n\tif function.Return.Present && function.Return.Name != \"\" {\n\t\tb.HasReturn = true\n\t\tb.ReturnType = string(function.Return.Type)\n\n\t\tif len(b.ReturnType) < 1 {\n\t\t\treturn nil, errors.New(\"return type cannot be empty\")\n\t\t}\n\n\t\tif b.ReturnType[0] == '*' {\n\t\t\tb.ReturnType = b.ReturnType[1:]\n\t\t\tb.ReturnIsPtr = true\n\t\t}\n\t}\n\n\tb.Method = transport.Method\n\n\t// Sort the arguments by name for consistent positional ordering.\n\tvar argVals []truce.ArgumentValue\n\tfor _, arg := range transport.Arguments {\n\t\targVals = append(argVals, arg)\n\t}\n\tsort.Slice(argVals, func(i, j int) bool {\n\t\treturn argVals[i].Name < argVals[j].Name\n\t})\n\n\tvar qpos int\n\tfor _, arg := range argVals {\n\t\ta, ok := args[arg.Name]\n\n\t\tswitch arg.From {\n\t\tcase \"body\":\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tb.BodyVar = a.posVariable\n\t\t\tb.BodyType = a.typ\n\t\tcase \"path\":\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpathMappings[arg.Var] = args[arg.Name].variable\n\t\tcase \"query\":\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tb.Query[arg.Var] = QueryParam{\n\t\t\t\tPos: qpos,\n\t\t\t\tQueryVar: arg.Var,\n\t\t\t\tGoVar: a.posVariable,\n\t\t\t\tType: a.typ,\n\t\t\t}\n\n\t\t\tqpos++\n\t\tcase \"static\":\n\t\t\t// TODO(georgemac)\n\t\t}\n\t}\n\n\tfor _, part := range strings.Split(config.Prefix, \"/\") {\n\t\tif part == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tb.Path = append(b.Path, Element{Type: \"static\", Value: part})\n\t}\n\n\tb.Path = append(b.Path, parsePath(pathMappings, transport.Path)...)\n\n\treturn b, nil\n}", "func NewConstructor(o Options) func(http.Handler) http.Handler {\n\tif o.Timeout <= 0 {\n\t\treturn xhttp.NilConstructor\n\t}\n\n\t// nolint: typecheck\n\tif o.TimedOut == nil {\n\t\to.TimedOut = defaultTimedOut\n\t}\n\n\treturn func(next http.Handler) http.Handler {\n\t\treturn &timeoutHandler{\n\t\t\ttimeout: o.Timeout,\n\t\t\ttimedOut: o.TimedOut,\n\t\t\tnext: next,\n\t\t}\n\t}\n}", "func (o *FakeObject) New(args ...interface{}) Object { return o.Invoke(args) }", "func (er *expressionRewriter) newFunction(funcName string, retType *types.FieldType, args ...expression.Expression) (expression.Expression, error) {\n\ttrace_util_0.Count(_expression_rewriter_00000, 275)\n\tif er.disableFoldCounter > 0 {\n\t\ttrace_util_0.Count(_expression_rewriter_00000, 277)\n\t\treturn expression.NewFunctionBase(er.ctx, funcName, retType, args...)\n\t}\n\ttrace_util_0.Count(_expression_rewriter_00000, 276)\n\treturn expression.NewFunction(er.ctx, funcName, retType, args...)\n}", "func (s *Prototype) Constructor() Value { return s.constructor }", "func NewFunction(ctx openedge.Context, cfg FunctionInfo) *Function {\n\tf := &Function{\n\t\tcfg: cfg,\n\t\tctx: ctx,\n\t\tids: make(chan string, cfg.Instance.Max),\n\t\tlog: logger.WithField(\"function\", cfg.Name),\n\t}\n\tfor index := 1; index <= cfg.Instance.Max; index++ {\n\t\tf.ids <- fmt.Sprintf(\"f%d\", index)\n\t}\n\tpc := pool.NewDefaultPoolConfig()\n\tpc.MinIdle = cfg.Instance.Min\n\tpc.MaxIdle = cfg.Instance.Max\n\tpc.MaxTotal = cfg.Instance.Max\n\tpc.MinEvictableIdleTime = cfg.Instance.IdleTime\n\tpc.TimeBetweenEvictionRuns = cfg.Instance.EvictTime\n\tf.pool = pool.NewObjectPool(context.Background(), newFactory(f), pc)\n\treturn f\n}", "func newInstance0(frame *rtda.Frame) {\n\tvars := frame.LocalVars()\n\tconstructorObj := vars.GetRef(0)\n\targArrObj := vars.GetRef(1)\n\n\tgoConstructor := getExtra(constructorObj)\n\tgoClass := goConstructor.Class()\n\tobj := goClass.NewObj()\n\tstack := frame.OperandStack()\n\tstack.PushRef(obj)\n\n\t// call <init>\n\targs := actualConstructorArgs(obj, argArrObj, goConstructor)\n\tframe.Thread().InvokeMethodWithShim(goConstructor, args)\n}", "func New() *Compiler {\n\tmainScope := CompilationScope{\n\t\tinstructions: code.Instructions{},\n\t\tlastInstruction: EmittedInstruction{},\n\t\tpreviousInstruction: EmittedInstruction{},\n\t}\n\ttable := NewSymbolTable()\n\tfor i, fn := range object.GetBuiltins() {\n\t\ttable.DefineBuiltin(i, fn.Name)\n\t}\n\treturn &Compiler{\n\t\tconstants: []object.Object{},\n\t\tscopes: []CompilationScope{mainScope},\n\t\tscopeIndex: 0,\n\t\tsymbolTable: table,\n\t}\n}", "func NewCommand(cmd uint32, count int) Command {\n\treturn Command((cmd & 0x7) | (uint32(count) << 3))\n}", "func New(chainFunc ...interface{}) *Chain {\n\tc := &Chain{}\n\tc.Add(chainFunc...)\n\treturn c\n}", "func TermConstructor(t TermT) TermConstructorT {\n\treturn TermConstructorT(C.yices_term_constructor(C.term_t(t)))\n}", "func NewConstructor() *Constructor {\n\treturn &Constructor{}\n}", "func NewFunction0(name string, sqlType Type, logic EvalLogic) Function0 {\n\tfn := func() Expression {\n\t\treturn NoArgFunc{name, sqlType, logic}\n\t}\n\n\treturn Function0{Name: name, Fn: fn}\n}", "func NewConstructor() Constructor {\n\treturn func(ctx context.Context, cmw configmap.Watcher) *controller.Impl {\n\t\treturn NewController(ctx, cmw)\n\t}\n}", "func Constructor() MapSum {\n \n}", "func Constructor() MyStack {\n\treturn MyStack{New(), New(), 1}\n}", "func Constructor() MapSum {\n\treturn MapSum{\n\t\troot: &TrieNode{},\n\t}\n}", "func ClosureNew(f interface{}) *C.GClosure {\n\tclosure := C._g_closure_new()\n\tclosures.Lock()\n\tclosures.m[closure] = reflect.ValueOf(f)\n\tclosures.Unlock()\n\treturn closure\n}", "func (sf *ScalarFunction) Clone() Expression {\n\tc := &ScalarFunction{\n\t\tFuncName: sf.FuncName,\n\t\tRetType: sf.RetType,\n\t\tFunction: sf.Function.Clone(),\n\t}\n\treturn c\n}", "func Function(sig *CallSignature) Type {\n\treturn Type{functionImpl{sig: sig}}\n}", "func newFunctionImpl(ctx sctx.Context, fold bool, funcName string, retType *types.FieldType, args ...Expression) (Expression, error) {\n\tif retType == nil {\n\t\treturn nil, errors.Errorf(\"RetType cannot be nil for ScalarFunction.\")\n\t}\n\tfc, ok := funcs[funcName]\n\tif !ok {\n\t\tdb := ctx.GetSessionVars().CurrentDB\n\t\tif db == \"\" {\n\t\t\treturn nil, errors.Trace(ErrNoDB)\n\t\t}\n\n\t\treturn nil, errFunctionNotExists.GenWithStackByArgs(\"FUNCTION\", db+\".\"+funcName)\n\t}\n\tfuncArgs := make([]Expression, len(args))\n\tcopy(funcArgs, args)\n\tf, err := fc.getFunction(ctx, funcArgs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif builtinRetTp := f.getRetTp(); builtinRetTp.Tp != mysql.TypeUnspecified || retType.Tp == mysql.TypeUnspecified {\n\t\tretType = builtinRetTp\n\t}\n\tsf := &ScalarFunction{\n\t\tFuncName: model.NewCIStr(funcName),\n\t\tRetType: retType,\n\t\tFunction: f,\n\t}\n\treturn sf, nil\n}", "func NewSelf() Function {\n\trv := &Self{\n\t\t*NewNullaryFunctionBase(\"self\"),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func Constructor() Trie {\n\treturn Trie{100, false, [26]*Trie{}}\n}", "func (c *Constructor) Create(a ...reflect.Value) (reflect.Value, kdone.Destructor, error) {\n\tif c == nil {\n\t\treturn reflect.Value{}, kdone.Noop, nil\n\t}\n\tif len(a) != len(c.inTypes) {\n\t\treturn reflect.Value{}, nil, kerror.Newf(kerror.EViolation,\n\t\t\t\"%s constructor expects %d argument(s), %d given\",\n\t\t\tc.t, len(c.inTypes), len(a))\n\t}\n\tfor i, v := range a {\n\t\tif v.Type() != c.inTypes[i] {\n\t\t\treturn reflect.Value{}, nil, kerror.Newf(kerror.EViolation,\n\t\t\t\t\"%s constructor expects argument %d to be of %s type, %s given\",\n\t\t\t\tc.t, i+1, c.inTypes[i], v.Type())\n\t\t}\n\t}\n\tout := c.function.Call(a)\n\tobj := out[c.objectOutIndex]\n\tvar dtor kdone.Destructor = kdone.Noop\n\tif c.destructorOutIndex >= 0 {\n\t\tif v := out[c.destructorOutIndex].Interface(); v != nil {\n\t\t\tdtor = v.(kdone.Destructor)\n\t\t}\n\t}\n\tvar err error\n\tif c.errorOutIndex >= 0 {\n\t\tif v := out[c.errorOutIndex].Interface(); v != nil {\n\t\t\terr = v.(error)\n\t\t}\n\t}\n\treturn obj, dtor, err\n}", "func New(length int) func() *Float32s {\r\n\treturn func() *Float32s {\r\n\t\tresult := make(Float32s, length)\r\n\t\tfor i := 0; i < length; i++ {\r\n\t\t\tresult[i] = randFloat32()\r\n\t\t}\r\n\t\treturn &result\r\n\t}\r\n}", "func NewFunctionCall(callee Expression, arguments []Expression, trailing *TrailingFunction, metadata *Metadata) *FunctionCall {\n\treturn &FunctionCall{callee, arguments, trailing, metadata}\n}", "func ClosureNewObject(sizeofClosure uint32, object *Object) *Closure {\n\tc_sizeof_closure := (C.guint)(sizeofClosure)\n\n\tc_object := (*C.GObject)(C.NULL)\n\tif object != nil {\n\t\tc_object = (*C.GObject)(object.ToC())\n\t}\n\n\tretC := C.g_closure_new_object(c_sizeof_closure, c_object)\n\tretGo := ClosureNewFromC(unsafe.Pointer(retC))\n\n\treturn retGo\n}", "func NewFunc(name string, nestDepth uint32) *FuncInfo {\n\tif name != \"\" {\n\t\treturn &FuncInfo{name: name}\n\t}\n\treturn &FuncInfo{closure: &printer.ReservedExpr{}}\n}", "func NewFunctionBase(ctx sctx.Context, funcName string, retType *types.FieldType, args ...Expression) (Expression, error) {\n\treturn newFunctionImpl(ctx, false, funcName, retType, args...)\n}", "func NewOperator(kind string, in, out reflect.Type, f func(ctx context.Context, field string, object interface{}) (interface{}, error)) Operator {\n\treturn &operator{\n\t\tkind: kind,\n\t\tin: in,\n\t\tout: out,\n\t\tf: f,\n\t}\n}", "func New(fn interface{}, validateFunc func(*FunctionCache) error) (*GenericFunc, error) {\n\tcache := &FunctionCache{}\n\tcache.FnValue = reflect.ValueOf(fn)\n\n\tif cache.FnValue.Kind() != reflect.Func {\n\t\treturn nil, errors.New(\"GenericFunc.New: fn is not a function\")\n\t}\n\n\tcache.FnType = cache.FnValue.Type()\n\tnumTypesIn := cache.FnType.NumIn()\n\tcache.TypesIn = make([]reflect.Type, numTypesIn)\n\tfor i := 0; i < numTypesIn; i++ {\n\t\tcache.TypesIn[i] = cache.FnType.In(i)\n\t}\n\n\tnumTypesOut := cache.FnType.NumOut()\n\tcache.TypesOut = make([]reflect.Type, numTypesOut)\n\tfor i := 0; i < numTypesOut; i++ {\n\t\tcache.TypesOut[i] = cache.FnType.Out(i)\n\t}\n\tif err := validateFunc(cache); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &GenericFunc{Cache: cache}, nil\n}", "func Constructor() Trie {\n\treturn Trie{\n\t\tnext: [26]*Trie{},\n\t}\n}", "func NewFunction(f func(float64) float64) *Function {\n\treturn &Function{\n\t\tF: f,\n\t\tSamples: 50,\n\t\tLineStyle: plotter.DefaultLineStyle,\n\t}\n}", "func NewFunctionCall(name string, params []Expression, returnType Type) Expression {\n\treturn &functionCall{\n\t\tname: name,\n\t\tparams: params,\n\t\treturnType: returnType,\n\t}\n}", "func NewCurry(fn interface{}) (*Curry, error) {\n\ttyp := reflect.TypeOf(fn)\n\n\tif typ.Kind() != reflect.Func {\n\t\treturn nil, fmt.Errorf(\"Handler is not a function!\")\n\t}\n\n\tc := &Curry{\n\t\tname: getFunctionName(fn),\n\t\tfnType: typ,\n\t\tfn: fn,\n\t}\n\n\treturn c, nil\n}", "func New() Object {\n\treturn Object{}\n}", "func new_(e interface{}) func() Event {\n\ttyp := reflect.TypeOf(e)\n\treturn func() Event {\n\t\treturn reflect.New(typ).Interface().(Event)\n\t}\n}", "func NewFunctionCall(name string, context string, args ...interface{}) FunctionCall {\n\treturn FunctionCall{name, context, args}\n}", "func NewLambda(vs []Argument, u bool, as []Argument, e Expression, t types.Type) Lambda {\n\treturn Lambda{as, e, t, vs, u}\n}", "func Constructor() MinStack {\r\n\treturn MinStack{}\r\n}", "func Constructor() MinStack {\n\treturn MinStack{atoms: []atom{}}\n}", "func New(hashFunc func(i interface{}) int64) *rbTree {\n\treturn &rbTree{hashFunc: hashFunc}\n}", "func NewFunction(pkg, name string,\n\tparams, ret, block []jen.Code) *Function {\n\treturn &Function{\n\t\tqual: jen.Qual(pkg, name),\n\t\tname: name,\n\t\tparams: params,\n\t\tret: ret,\n\t\tblock: block,\n\t}\n}", "func Constructor() TwoSum {\n\treturn TwoSum{data: map[int]int{}}\n}", "func NewMapper(m func(srcPtr interface{}, destPtr interface{}) error) Mapper {\n return funcMapper(m)\n}", "func Constructor() MinStack {\n\treturn MinStack{}\n}", "func Constructor() MinStack {\n\treturn MinStack{}\n}", "func Constructor() MinStack {\n\treturn MinStack{}\n}", "func Constructor() MinStack {\n\treturn MinStack{}\n}" ]
[ "0.7275384", "0.69671285", "0.6962341", "0.68921953", "0.6845353", "0.6845353", "0.68416286", "0.68416286", "0.6744794", "0.6708235", "0.6654913", "0.6654913", "0.66427934", "0.6617833", "0.6557411", "0.6531051", "0.65282565", "0.65282565", "0.6448263", "0.6430938", "0.642644", "0.6416298", "0.6379176", "0.6367499", "0.6366126", "0.62883306", "0.62635535", "0.62385595", "0.6231371", "0.62291867", "0.6165766", "0.6147356", "0.6105036", "0.6083122", "0.6003783", "0.5977542", "0.5927735", "0.5885979", "0.58768934", "0.5810873", "0.57859194", "0.5747765", "0.5736086", "0.57057744", "0.56806284", "0.55061185", "0.5496205", "0.5493704", "0.5482538", "0.54738533", "0.54588", "0.5443965", "0.54094404", "0.5387287", "0.5387196", "0.5361126", "0.53487706", "0.53166324", "0.5306954", "0.52919453", "0.52906483", "0.52859384", "0.52840936", "0.52802795", "0.52708143", "0.52690405", "0.5266685", "0.526243", "0.52523154", "0.52483165", "0.5243988", "0.52162164", "0.5211306", "0.5206393", "0.5202841", "0.5189611", "0.51715684", "0.5158675", "0.5157257", "0.5144621", "0.5138274", "0.51364094", "0.512137", "0.5120366", "0.51169324", "0.5115708", "0.5115569", "0.51068395", "0.5095257", "0.5093496", "0.5088127", "0.50878847", "0.50815326", "0.5076853", "0.507033", "0.5065051", "0.5065051", "0.5065051", "0.5065051" ]
0.79440147
1
/ The function NewObjectNames calls NewUnaryFunctionBase to create a function named OBJECT_NAMES with an expression as input.
func NewObjectNames(operand Expression) Function { rv := &ObjectNames{ *NewUnaryFunctionBase("object_names", operand), } rv.expr = rv return rv }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *ObjectNames) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectNames(operands[0])\n\t}\n}", "func (this *ObjectNames) Constructor() FunctionConstructor {\n\treturn func(operands ...Expression) Function {\n\t\treturn NewObjectNames(operands[0])\n\t}\n}", "func (s Obj_value) NewName(n int32) (capnp.TextList, error) {\n\ts.Struct.SetUint16(4, 0)\n\tl, err := capnp.NewTextList(s.Struct.Segment(), n)\n\tif err != nil {\n\t\treturn capnp.TextList{}, err\n\t}\n\terr = s.Struct.SetPtr(0, l.List.ToPtr())\n\treturn l, err\n}", "func execNewNamed(_ int, p *gop.Context) {\n\targs := p.GetArgs(3)\n\tret := types.NewNamed(args[0].(*types.TypeName), args[1].(types.Type), args[2].([]*types.Func))\n\tp.Ret(3, ret)\n}", "func NewObjectValues(operand Expression) Function {\n\trv := &ObjectValues{\n\t\t*NewUnaryFunctionBase(\"object_values\", operand),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func NewObjectValues(operand Expression) Function {\n\trv := &ObjectValues{\n\t\t*NewUnaryFunctionBase(\"object_values\", operand),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func InitNames() {\n\tsyscall.Syscall(gpInitNames, 0, 0, 0, 0)\n}", "func Names(v interface{}) []string {\n\treturn New(v).Names()\n}", "func createList(arg string) []string {\n\tvar retObject = []string{arg}\n\treturn retObject\n}", "func NewNameIn(vs ...string) predicate.User {\n\treturn predicate.User(sql.FieldIn(FieldNewName, vs...))\n}", "func NewNameIn(vs ...string) predicate.User {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.User(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldNewName), v...))\n\t})\n}", "func RegisterObject(name string, f NewObjectFct) {\n\tObjectList[name] = f\n}", "func NewNameGTE(v string) predicate.User {\n\treturn predicate.User(sql.FieldGTE(FieldNewName, v))\n}", "func NewOperationNamesStorage(\n\tsession cassandra.Session,\n\twriteCacheTTL time.Duration,\n\tmetricsFactory metrics.Factory,\n\tlogger *zap.Logger,\n) *OperationNamesStorage {\n\treturn &OperationNamesStorage{\n\t\tsession: session,\n\t\tInsertStmt: insertOperationName,\n\t\tQueryStmt: queryOperationNames,\n\t\tmetrics: casMetrics.NewTable(metricsFactory, \"OperationNames\"),\n\t\twriteCacheTTL: writeCacheTTL,\n\t\tlogger: logger,\n\t\toperationNames: cache.NewLRUWithOptions(\n\t\t\t100000,\n\t\t\t&cache.Options{\n\t\t\t\tTTL: writeCacheTTL,\n\t\t\t\tInitialCapacity: 0000,\n\t\t\t}),\n\t}\n}", "func newnamel(pos src.XPos, s *types.Sym) *Node {\n\tif s == nil {\n\t\tFatalf(\"newnamel nil\")\n\t}\n\n\tvar x struct {\n\t\tn Node\n\t\tm Name\n\t\tp Param\n\t}\n\tn := &x.n\n\tn.Name = &x.m\n\tn.Name.Param = &x.p\n\n\tn.Op = ONAME\n\tn.Pos = pos\n\tn.Orig = n\n\n\tn.Sym = s\n\treturn n\n}", "func objToNames(obj interface{}, names []string, tag string) []string {\n\tvar typ reflect.Type\n\n\tif sf, ok := obj.(reflect.StructField); ok {\n\t\ttyp = sf.Type\n\t} else {\n\t\ttyp = reflect.TypeOf(obj)\n\t\tif typ.Kind() == reflect.Ptr {\n\t\t\ttyp = typ.Elem()\n\t\t}\n\t}\n\n\tfor i := 0; i < typ.NumField(); i++ {\n\t\tfield := typ.Field(i)\n\n\t\tif field.Type.Kind() == reflect.Struct {\n\t\t\tnames = objToNames(field, names, tag)\n\t\t\tcontinue\n\t\t}\n\n\t\t// If tag is passed to the function, we only append if the field is tagged and that it matches tag.\n\t\tif tag == \"\" || field.Tag.Get(tag) != \"\" {\n\t\t\tnames = append(names, field.Name)\n\t\t}\n\t}\n\n\treturn names\n}", "func NewObject(t ...[2]*Term) Object {\n\tobj := newobject(len(t))\n\tfor i := range t {\n\t\tobj.Insert(t[i][0], t[i][1])\n\t}\n\treturn obj\n}", "func NewObjectRemove(first, second Expression) Function {\n\trv := &ObjectRemove{\n\t\t*NewBinaryFunctionBase(\"object_remove\", first, second),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func NewObjectLength(operand Expression) Function {\n\trv := &ObjectLength{\n\t\t*NewUnaryFunctionBase(\"object_length\", operand),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func NewObjectLength(operand Expression) Function {\n\trv := &ObjectLength{\n\t\t*NewUnaryFunctionBase(\"object_length\", operand),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func GetNewRegisteredUserNames(miscTable *db.Table) ([]string, error) {\n\tnewRegisteredUserNames := []string{}\n\terr := miscTable.GetObj(keyNewRegisteredUsers, &newRegisteredUserNames)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newRegisteredUserNames, nil\n}", "func (s *BasePlSqlParserListener) EnterRename_object(ctx *Rename_objectContext) {}", "func InitNames() {\n\tC.glowInitNames(gpInitNames)\n}", "func newname(s *types.Sym) *Node {\n\tn := newnamel(lineno, s)\n\tn.Name.Curfn = Curfn\n\treturn n\n}", "func NewObjectPairs(operand Expression) Function {\n\trv := &ObjectPairs{\n\t\t*NewUnaryFunctionBase(\"object_pairs\", operand),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func NewObjectPairs(operand Expression) Function {\n\trv := &ObjectPairs{\n\t\t*NewUnaryFunctionBase(\"object_pairs\", operand),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func NewActionNames() *ActionNames {\n\tv := &ActionNames{}\n\treturn v\n}", "func NewObjectAdd(first, second, third Expression) Function {\n\trv := &ObjectAdd{\n\t\t*NewTernaryFunctionBase(\"object_add\", first, second, third),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func (*Object) Name() string { return \"object\" }", "func NamesFrom(list []string) Names {\n\tn := []Name{}\n\tfor _, v := range list {\n\t\tn = append(n, Name(v))\n\t}\n\treturn Names(n)\n}", "func NNames(w http.ResponseWriter) error {\n\tv, err := getProperty(\"NNames\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprop := Property{\n\t\tProperty: \"NNames\",\n\t\tValue: fmt.Sprint(v.Value().(uint32)),\n\t}\n\n\treturn share.JSONResponse(prop, w)\n}", "func FieldArgNames(obj any, allArgs map[string]reflect.Value) {\n\tfieldArgNamesStruct(obj, \"\", false, allArgs)\n}", "func execNewTypeName(_ int, p *gop.Context) {\n\targs := p.GetArgs(4)\n\tret := types.NewTypeName(token.Pos(args[0].(int)), args[1].(*types.Package), args[2].(string), args[3].(types.Type))\n\tp.Ret(4, ret)\n}", "func (this *ObjectNames) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func (this *ObjectNames) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.UnaryEval(this, item, context)\n}", "func GenerateLabels(object CommonInterface) map[string]string {\n\tkind := object.GroupVersionKind().Kind\n\tgroup := object.GroupVersionKind().Group\n\tname := object.GetName()\n\tkey := strings.ToLower(kind) + \".\" + group + \"/name\"\n\tlabels := make(map[string]string)\n\tlabels[key] = name\n\treturn labels\n}", "func GenerateLabels(object CommonInterface) map[string]string {\n\tkind := object.GroupVersionKind().Kind\n\tgroup := object.GroupVersionKind().Group\n\tname := object.GetName()\n\tkey := strings.ToLower(kind) + \".\" + group + \"/name\"\n\tlabels := make(map[string]string)\n\tlabels[key] = name\n\treturn labels\n}", "func NewGNames(\n\tcfg config.Config,\n\tvf verifier.Verifier,\n\tfc facet.Facet,\n) GNames {\n\treturn gnames{\n\t\tcfg: cfg,\n\t\tvf: vf,\n\t\tfacet: fc,\n\t\tmatcher: matcher.New(cfg.MatcherURL),\n\t}\n}", "func Names() []string {\n\t// TODO eliminate duplicates\n\tvar names []string\n\tfor _, f := range factories {\n\t\tnames = append(names, f.Names()...)\n\t}\n\treturn names\n}", "func UConverterOpenStandardNames(arg1 string, arg2 string, arg3 *UErrorCode) (_swig_ret X_UEnumeration)", "func NewLiteral(value Object) Expression {\n\treturn &literal{value: value}\n}", "func (e *Enforcer) GetAllNamedObjects(ctx context.Context, ptype string) ([]string, error) {\n\tres, err := e.client.remoteClient.GetAllNamedObjects(ctx, &pb.SimpleGetRequest{\n\t\tEnforcerHandler: e.handler,\n\t\tPType: ptype,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res.Array, nil\n}", "func NewNameGTE(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.GTE(s.C(FieldNewName), v))\n\t})\n}", "func NewtnsnamesParser(input antlr.TokenStream) *tnsnamesParser {\n\tthis := new(tnsnamesParser)\n\tdeserializer := antlr.NewATNDeserializer(nil)\n\tdeserializedATN := deserializer.DeserializeFromUInt16(parserATN)\n\tdecisionToDFA := make([]*antlr.DFA, len(deserializedATN.DecisionToState))\n\tfor index, ds := range deserializedATN.DecisionToState {\n\t\tdecisionToDFA[index] = antlr.NewDFA(ds, index)\n\t}\n\tthis.BaseParser = antlr.NewBaseParser(input)\n\n\tthis.Interpreter = antlr.NewParserATNSimulator(this, deserializedATN, decisionToDFA, antlr.NewPredictionContextCache())\n\tthis.RuleNames = ruleNames\n\tthis.LiteralNames = literalNames\n\tthis.SymbolicNames = symbolicNames\n\tthis.GrammarFileName = \"tnsnamesParser.g4\"\n\n\treturn this\n}", "func (this *ObjectNames) Apply(context Context, arg value.Value) (value.Value, error) {\n\tif arg.Type() == value.MISSING {\n\t\treturn value.MISSING_VALUE, nil\n\t} else if arg.Type() != value.OBJECT {\n\t\treturn value.NULL_VALUE, nil\n\t}\n\n\toa := arg.Actual().(map[string]interface{})\n\tkeys := make(sort.StringSlice, 0, len(oa))\n\tfor key, _ := range oa {\n\t\tkeys = append(keys, key)\n\t}\n\n\tsort.Sort(keys)\n\tra := make([]interface{}, len(keys))\n\tfor i, k := range keys {\n\t\tra[i] = k\n\t}\n\n\treturn value.NewValue(ra), nil\n}", "func NewObjectInnerValues(operand Expression) Function {\n\trv := &ObjectInnerValues{\n\t\t*NewUnaryFunctionBase(\"object_innervalues\", operand),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func mustGetNames(objects []runtime.Object) []string {\n\tvar names []string\n\tfor _, obj := range objects {\n\t\tmetaAccessor, err := meta.Accessor(obj)\n\t\tif err != nil {\n\t\t\tframework.Failf(\"error getting accessor for %T: %v\", obj, err)\n\t\t}\n\t\tname := metaAccessor.GetName()\n\t\tnames = append(names, name)\n\t}\n\tsort.Strings(names)\n\treturn names\n}", "func VisitObjectStrings(obj interface{}, visitor func(string) string) {\n\tvisitValue(reflect.ValueOf(obj), visitor)\n}", "func (g *grpc) objectNamed(name string) generator.Object {\n\tg.gen.RecordTypeUse(name)\n\treturn g.gen.ObjectNamed(name)\n}", "func newObjectList() *ObjectList {\n\treturn &ObjectList{\n\t\tObjectIDs: make([]int, 0, 200),\n\t}\n}", "func (s *BasePlSqlParserListener) EnterObject_name(ctx *Object_nameContext) {}", "func NewNameArray(sVars ...string) PDFArray {\n\n\ta := PDFArray{}\n\n\tfor _, s := range sVars {\n\t\ta = append(a, PDFName(s))\n\t}\n\n\treturn a\n}", "func Names(v interface{}, prev ...string) [][]string {\n\tval := reflect.ValueOf(v)\n\treturn names(val, prev)\n}", "func InitNames() {\n C.glowInitNames(gpInitNames)\n}", "func UConverterOpenAllNames(arg1 *UErrorCode) (_swig_ret X_UEnumeration)", "func NewNameContains(v string) predicate.User {\n\treturn predicate.User(sql.FieldContains(FieldNewName, v))\n}", "func (r *Registry) RegisteredObjects() map[string]client.Object {\n\tout := make(map[string]client.Object, len(r.nameToObject))\n\tfor name, object := range r.nameToObject {\n\t\tout[name] = object.obj\n\t}\n\treturn out\n}", "func TestIsValidObjectName(t *testing.T) {\n\ttestCases := []struct {\n\t\tobjectName string\n\t\tshouldPass bool\n\t}{\n\t\t// cases which should pass the test.\n\t\t// passing in valid object name.\n\t\t{\"object\", true},\n\t\t{\"The Shining Script <v1>.pdf\", true},\n\t\t{\"Cost Benefit Analysis (2009-2010).pptx\", true},\n\t\t{\"117Gn8rfHL2ACARPAhaFd0AGzic9pUbIA/5OCn5A\", true},\n\t\t{\"SHØRT\", true},\n\t\t{\"There are far too many object names, and far too few bucket names!\", true},\n\t\t// cases for which test should fail.\n\t\t// passing invalid object names.\n\t\t{\"\", false},\n\t\t{string([]byte{0xff, 0xfe, 0xfd}), false},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tisValidObjectName := IsValidObjectName(testCase.objectName)\n\t\tif testCase.shouldPass && !isValidObjectName {\n\t\t\tt.Errorf(\"Test case %d: Expected \\\"%s\\\" to be a valid object name\", i+1, testCase.objectName)\n\t\t}\n\t\tif !testCase.shouldPass && isValidObjectName {\n\t\t\tt.Errorf(\"Test case %d: Expected object name \\\"%s\\\" to be invalid\", i+1, testCase.objectName)\n\t\t}\n\t}\n}", "func ClosureNewObject(sizeofClosure uint32, object *Object) *Closure {\n\tc_sizeof_closure := (C.guint)(sizeofClosure)\n\n\tc_object := (*C.GObject)(C.NULL)\n\tif object != nil {\n\t\tc_object = (*C.GObject)(object.ToC())\n\t}\n\n\tretC := C.g_closure_new_object(c_sizeof_closure, c_object)\n\tretGo := ClosureNewFromC(unsafe.Pointer(retC))\n\n\treturn retGo\n}", "func CloneTableNames(n TableNames) TableNames {\n\tres := make(TableNames, 0, len(n))\n\tfor _, x := range n {\n\t\tres = append(res, CloneTableName(x))\n\t}\n\treturn res\n}", "func getSwiftObjectNames(t *testing.T, osClient *gophercloud.ServiceClient, container string) (objectNames []string) {\n\t_ = objects.List(osClient, container, nil).EachPage(func(page pagination.Page) (bool, error) {\n\t\t// Get a slice of object names\n\t\tnames, err := objects.ExtractNames(page)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error extracting object names from page: %s\", err)\n\t\t}\n\t\tfor _, object := range names {\n\t\t\tobjectNames = append(objectNames, object)\n\t\t}\n\n\t\treturn true, nil\n\t})\n\treturn\n}", "func (a *Client) ReplaceInstancesObjectsObjectNameDefinitions(params *ReplaceInstancesObjectsObjectNameDefinitionsParams) (*ReplaceInstancesObjectsObjectNameDefinitionsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewReplaceInstancesObjectsObjectNameDefinitionsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"replaceInstancesObjectsObjectNameDefinitions\",\n\t\tMethod: \"PUT\",\n\t\tPathPattern: \"/instances/objects/{objectName}/definitions\",\n\t\tProducesMediaTypes: []string{\"\"},\n\t\tConsumesMediaTypes: []string{\"\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ReplaceInstancesObjectsObjectNameDefinitionsReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*ReplaceInstancesObjectsObjectNameDefinitionsOK), nil\n\n}", "func (o *Object) Rename(n, m string) {\n\tfor _, nat := range *o {\n\t\tif nat.Name == n {\n\t\t\tnat.Name = m\n\t\t\treturn\n\t\t}\n\t}\n}", "func (*unifinames) Name() string { return \"unifi-names\" }", "func NewSlice(a ...Name) []Name {\n\treturn a\n}", "func NewLuaObjectFromName(L *lua.State, path string) *LuaObject {\n Lookup(L, path, 0)\n return NewLuaObject(L, -1)\n}", "func NewLuaObject(L *lua.State, idx int) *LuaObject {\n tp := L.LTypename(idx)\n L.PushValue(idx)\n ref := L.Ref(lua.LUA_REGISTRYINDEX)\n return &LuaObject{L, ref, tp}\n}", "func (f *Fs) newObjectSizeAndNameOnly(o fs.Object, moName string, size int64) *Object {\n\treturn &Object{\n\t\tObject: o,\n\t\tf: f,\n\t\tmo: nil,\n\t\tmoName: moName,\n\t\tsize: size,\n\t\tmeta: nil,\n\t}\n}", "func objectName(u *unstructured.Unstructured) string {\n\treturn strings.ToLower(fmt.Sprintf(\"%s-%s\", u.GetKind(), strings.Replace(u.GetName(), \":\", \"-\", -1)))\n}", "func (n *LibPcreRegexp) SubexpNames() []string {\n\treturn n.namedGroups\n}", "func (s *BasePlSqlParserListener) ExitRename_object(ctx *Rename_objectContext) {}", "func ObjectName(obj *Object) (string, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get metadata accessor from object: %v\", err)\n\t}\n\treturn accessor.GetName(), nil\n}", "func NewObjectUnwrap(operand Expression) Function {\n\trv := &ObjectUnwrap{\n\t\t*NewUnaryFunctionBase(\"object_unwrap\", operand),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func NewObjectInnerPairs(operand Expression) Function {\n\trv := &ObjectInnerPairs{\n\t\t*NewUnaryFunctionBase(\"object_innerpairs\", operand),\n\t}\n\n\trv.expr = rv\n\treturn rv\n}", "func makeNames(fullMethod string) (names api.Names) {\n\t// Strip the leading slash. It should always be present in practice.\n\tif len(fullMethod) > 0 && fullMethod[0] == '/' {\n\t\tfullMethod = fullMethod[1:]\n\t}\n\n\t// Parse the slash separated service and method name. The separating slash\n\t// should always be present in practice.\n\tif slashIndex := strings.Index(fullMethod, \"/\"); slashIndex != -1 {\n\t\tnames.RawService = fullMethod[0:slashIndex]\n\t\tnames.Method = fullMethod[slashIndex+1:]\n\t}\n\n\tnames.Service = serviceReplacer.Replace(names.RawService)\n\tnames.MetricKey = append(names.MetricKey, strings.Split(names.Service, \".\")...)\n\tnames.MetricKey = append(names.MetricKey, methodMetricKeyReplacer.Replace(names.Method))\n\tfor i := range names.MetricKey {\n\t\tnames.MetricKey[i] = metricKey(names.MetricKey[i])\n\t}\n\treturn names\n}", "func (l Lambda) ArgumentNames() []string {\n\treturn argumentsToNames(l.arguments)\n}", "func NewNameContains(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.Contains(s.C(FieldNewName), v))\n\t})\n}", "func NewName(v string) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldNewName), v))\n\t})\n}", "func IncludeNamesFilter(names ...string) factory.EventFilterFunc {\n\tnameSet := sets.NewString(names...)\n\treturn func(obj interface{}) bool {\n\t\tmetaObj := obj.(metav1.Object)\n\t\treturn nameSet.Has(metaObj.GetName())\n\t}\n}", "func NewName(v string) predicate.User {\n\treturn predicate.User(sql.FieldEQ(FieldNewName, v))\n}", "func NewObjectExpression() *ObjectExpression {\n\treturn &ObjectExpression{\n\t\tprops: make(map[string]Expression),\n\t}\n}", "func NewCardNames() *CardNames {\n\tcounts := make(map[string]int)\n\treturn &CardNames{Counts: counts}\n}", "func NewObjectDependencies(\n\tobj interface{},\n) (ObjectDependency, ObjectDependencies) {\n\tdeps := make(ObjectDependencies)\n\tvirtual := obj.(*cisapiv1.VirtualServer)\n\t// TODO => dep can be replaced with internal DS rqkey\n\tkey := ObjectDependency{\n\t\tKind: VirtualServer,\n\t\tName: virtual.ObjectMeta.Name,\n\t\tNamespace: virtual.ObjectMeta.Namespace,\n\t}\n\n\tdeps[key] = 1\n\tfor _, pool := range virtual.Spec.Pools {\n\t\tdep := ObjectDependency{\n\t\t\tKind: RuleDep,\n\t\t\tNamespace: virtual.ObjectMeta.Namespace,\n\t\t\tName: virtual.Spec.Host + pool.Path,\n\t\t\tService: pool.Service,\n\t\t}\n\t\tdeps[dep]++\n\t}\n\treturn key, deps\n}", "func addStrings(s *scope, name string, obj pyObject, f func(string)) {\n\tif obj != nil && obj != None {\n\t\tl, ok := asList(obj)\n\t\tif !ok {\n\t\t\ts.Error(\"Argument %s must be a list, not %s\", name, obj.Type())\n\t\t}\n\t\tfor _, li := range l {\n\t\t\tstr, ok := li.(pyString)\n\t\t\tif !ok && li != None {\n\t\t\t\ts.Error(\"%s must be strings\", name)\n\t\t\t}\n\t\t\tif str != \"\" && li != None {\n\t\t\t\tf(string(str))\n\t\t\t}\n\t\t}\n\t}\n}", "func getNames(sub pkix.Name) []Name {\n\t// anonymous func for finding the max of a list of integer\n\tmax := func(v1 int, vn ...int) (max int) {\n\t\tmax = v1\n\t\tfor i := 0; i < len(vn); i++ {\n\t\t\tif vn[i] > max {\n\t\t\t\tmax = vn[i]\n\t\t\t}\n\t\t}\n\t\treturn max\n\t}\n\n\tnc := len(sub.Country)\n\tnorg := len(sub.Organization)\n\tnou := len(sub.OrganizationalUnit)\n\tnl := len(sub.Locality)\n\tnp := len(sub.Province)\n\n\tn := max(nc, norg, nou, nl, np)\n\n\tnames := make([]Name, n)\n\tfor i := range names {\n\t\tif i < nc {\n\t\t\tnames[i].C = sub.Country[i]\n\t\t}\n\t\tif i < norg {\n\t\t\tnames[i].O = sub.Organization[i]\n\t\t}\n\t\tif i < nou {\n\t\t\tnames[i].OU = sub.OrganizationalUnit[i]\n\t\t}\n\t\tif i < nl {\n\t\t\tnames[i].L = sub.Locality[i]\n\t\t}\n\t\tif i < np {\n\t\t\tnames[i].ST = sub.Province[i]\n\t\t}\n\t}\n\treturn names\n}", "func (o *objectSet) nameMatches(nameRegex string) *objectSet {\n\tret := &objectSet{}\n\tfor k, v := range o.objMap {\n\t\t_, _, objName := object.FromHash(k)\n\t\tm, err := regexp.MatchString(nameRegex, objName)\n\t\tif err != nil && m {\n\t\t\tret.append(v)\n\t\t}\n\t}\n\treturn ret\n}", "func setPatchNames(patches []string, jsonPatches []kustomize.PatchJSON6902) ([]string, []kustomize.PatchJSON6902) {\n\tfixedPatches := make([]string, len(patches))\n\tfixedJSONPatches := make([]kustomize.PatchJSON6902, len(jsonPatches))\n\tfor i, patch := range patches {\n\t\t// insert the generated name metadata\n\t\tfixedPatches[i] = fmt.Sprintf(\"metadata:\\nname: %s\\n%s\", kubeadm.ObjectName, patch)\n\t}\n\tfor i, patch := range jsonPatches {\n\t\t// insert the generated name metadata\n\t\tpatch.Name = kubeadm.ObjectName\n\t\tfixedJSONPatches[i] = patch\n\t}\n\treturn fixedPatches, fixedJSONPatches\n}", "func (n *piName) FreeNames() []Name {\n\treturn []Name{n}\n}", "func NewListName(val string) ListNameField {\n\treturn ListNameField{quickfix.FIXString(val)}\n}", "func execNewPkgName(_ int, p *gop.Context) {\n\targs := p.GetArgs(4)\n\tret := types.NewPkgName(token.Pos(args[0].(int)), args[1].(*types.Package), args[2].(string), args[3].(*types.Package))\n\tp.Ret(4, ret)\n}", "func New(e *eme.EMECipher, longNames bool, raw64 bool) *NameTransform {\n\tb64 := base64.URLEncoding\n\tif raw64 {\n\t\tb64 = base64.RawURLEncoding\n\t}\n\treturn &NameTransform{\n\t\temeCipher: e,\n\t\tlongNames: longNames,\n\t\tB64: b64,\n\t}\n}", "func NewFunctionCall(name string, params []Expression, returnType Type) Expression {\n\treturn &functionCall{\n\t\tname: name,\n\t\tparams: params,\n\t\treturnType: returnType,\n\t}\n}", "func (t *targetrunner) renameObject(w http.ResponseWriter, r *http.Request, msg *cmn.ActionMsg) {\n\tapitems, err := t.checkRESTItems(w, r, 2, false, cmn.Version, cmn.Objects)\n\tif err != nil {\n\t\treturn\n\t}\n\tbucket, objNameFrom := apitems[0], apitems[1]\n\tbck, err := newBckFromQuery(bucket, r.URL.Query())\n\tif err != nil {\n\t\tt.invalmsghdlr(w, r, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tlom := &cluster.LOM{T: t, ObjName: objNameFrom}\n\tif err = lom.Init(bck.Bck); err != nil {\n\t\tt.invalmsghdlr(w, r, err.Error())\n\t\treturn\n\t}\n\tif lom.Bck().IsRemote() {\n\t\tt.invalmsghdlr(w, r, fmt.Sprintf(\"%s: cannot rename object from remote bucket\", lom))\n\t\treturn\n\t}\n\tif lom.Bck().Props.EC.Enabled {\n\t\tt.invalmsghdlr(w, r, fmt.Sprintf(\"%s: cannot rename erasure-coded object\", lom))\n\t\treturn\n\t}\n\n\tbuf, slab := t.gmm.Alloc()\n\tri := &replicInfo{smap: t.owner.smap.get(), t: t, bckTo: lom.Bck(), buf: buf, localOnly: false, finalize: true}\n\tcopied, err := ri.copyObject(lom, msg.Name /* new object name */)\n\tslab.Free(buf)\n\tif err != nil {\n\t\tt.invalmsghdlr(w, r, err.Error())\n\t\treturn\n\t}\n\tif copied {\n\t\tlom.Lock(true)\n\t\tif err = lom.Remove(); err != nil {\n\t\t\tt.invalmsghdlr(w, r, err.Error())\n\t\t}\n\t\tlom.Unlock(true)\n\t}\n}", "func (e *Enforcer) GetAllNamedObjects(ptype string) []string {\n\treturn e.model.GetValuesForFieldInPolicy(\"p\", ptype, 1)\n}", "func (a *Client) GetInstancesObjectsObjectNameDefinitions(params *GetInstancesObjectsObjectNameDefinitionsParams) (*GetInstancesObjectsObjectNameDefinitionsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetInstancesObjectsObjectNameDefinitionsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getInstancesObjectsObjectNameDefinitions\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/instances/objects/{objectName}/definitions\",\n\t\tProducesMediaTypes: []string{\"\"},\n\t\tConsumesMediaTypes: []string{\"\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetInstancesObjectsObjectNameDefinitionsReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetInstancesObjectsObjectNameDefinitionsOK), nil\n\n}", "func (m *MockIDistributedEnforcer) GetAllNamedObjects(arg0 string) []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAllNamedObjects\", arg0)\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func (b *JSONSupportGeneratorBuilder) Names(value *NamesCalculator) *JSONSupportGeneratorBuilder {\n\tb.names = value\n\treturn b\n}", "func NewFunctionCall(name string, context string, args ...interface{}) FunctionCall {\n\treturn FunctionCall{name, context, args}\n}", "func SetIterationNames(names []string) CustomizeIterationFunc {\n\treturn func(fxt *TestFixture, idx int) error {\n\t\tif len(fxt.Iterations) != len(names) {\n\t\t\treturn errs.Errorf(\"number of names (%d) must match number of iterations to create (%d)\", len(names), len(fxt.Iterations))\n\t\t}\n\t\tfxt.Iterations[idx].Name = names[idx]\n\t\treturn nil\n\t}\n}" ]
[ "0.58631206", "0.58631206", "0.5818655", "0.5258608", "0.5123252", "0.5123252", "0.50969934", "0.5032237", "0.50116974", "0.5003598", "0.49712798", "0.48637605", "0.48614097", "0.4857428", "0.48428673", "0.4813975", "0.48088303", "0.4790116", "0.478159", "0.478159", "0.47766036", "0.4755525", "0.47224835", "0.47171596", "0.47112864", "0.47112864", "0.4705204", "0.4694117", "0.46838522", "0.46733025", "0.46570423", "0.4647531", "0.4644537", "0.46311185", "0.46311185", "0.46196118", "0.46196118", "0.46177626", "0.46132615", "0.46020743", "0.45829603", "0.45678264", "0.45461628", "0.45407197", "0.45389766", "0.45360643", "0.45280933", "0.45241615", "0.45132384", "0.45014986", "0.45002106", "0.44986975", "0.44884658", "0.44849864", "0.4468415", "0.44632208", "0.44623184", "0.44584042", "0.44497758", "0.44382828", "0.4434107", "0.44134033", "0.4406137", "0.44021538", "0.43966252", "0.438765", "0.43843558", "0.43735844", "0.4363224", "0.43632093", "0.43620384", "0.4353397", "0.43489394", "0.4343304", "0.43261543", "0.43088523", "0.43066993", "0.43056569", "0.43054876", "0.42953077", "0.42924753", "0.42914975", "0.4289419", "0.42845523", "0.428279", "0.42779234", "0.42585278", "0.42527956", "0.4248512", "0.42462602", "0.42201364", "0.42196143", "0.4219444", "0.42172572", "0.4215325", "0.42120495", "0.42098132", "0.42085797", "0.41999185" ]
0.8870936
1
/ It calls the VisitFunction method by passing in the receiver to and returns the interface. It is a visitor pattern.
func (this *ObjectNames) Accept(visitor Visitor) (interface{}, error) { return visitor.VisitFunction(this) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *NowStr) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (e FunctionCallExpression) Visit(env Environment) Value {\n\treturn NoneValue()\n}", "func (i *InterfaceSet) Visit(n ast.Node) (w ast.Visitor) {\n\tswitch n := n.(type) {\n\tcase *ast.TypeSpec:\n\t\tif data, ok := n.Type.(*ast.InterfaceType); ok {\n\t\t\tr := InterfaceInfo{\n\t\t\t\tMethods: []*Method{},\n\t\t\t}\n\t\t\tmethods := data.Methods.List\n\t\t\tr.Name = n.Name.Name\n\t\t\tr.Doc = n.Doc.Text()\n\n\t\t\tfor _, m := range methods {\n\t\t\t\tfor _, name := range m.Names {\n\t\t\t\t\tr.Methods = append(r.Methods, &Method{\n\t\t\t\t\t\tMethodName: name.Name,\n\t\t\t\t\t\tDoc: m.Doc.Text(),\n\t\t\t\t\t\tParams: getParamList(m.Type.(*ast.FuncType).Params),\n\t\t\t\t\t\tResult: getParamList(m.Type.(*ast.FuncType).Results),\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t}\n\t\t\ti.Interfaces = append(i.Interfaces, r)\n\t\t}\n\t}\n\treturn i\n}", "func FuncInterface(_ T1) {}", "func (this *ExecuteFunction) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitExecuteFunction(this)\n}", "func (this *ObjectValues) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectValues) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectUnwrap) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (r *Resolver) Visitor() generated.VisitorResolver { return &visitorResolver{r} }", "func (this *ObjectInnerValues) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (f VisitorFunc) Visit(node Node, visitType int) error {\n\treturn f(node, visitType)\n}", "func (this *ClockStr) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *NowMillis) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (statement *FunctionCall) Accept(visitor StatementVisitor) {\n\tvisitor.VisitFunctionCall(statement)\n}", "func (this *ObjectLength) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectLength) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectRemove) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *DateDiffStr) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectPairs) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectPairs) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectAdd) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectInnerPairs) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *ObjectPut) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (v Value) AsFunction() Callable {\n\treturn v.iface.(Callable)\n}", "func (bf *BuiltInFunc) Call(interpreter *Interpreter, args ...interface{}) interface{} {\n\t// we actually omit the `interpreter` because we already known how\n\t// to convert it into a go function.\n\treturn bf.call(bf.instance, args...)\n}", "func (this *ClockMillis) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (statement *NativeCall) Accept(visitor StatementVisitor) {\n\tvisitor.VisitNativeCall(statement)\n}", "func (this *DatePartStr) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func Visit(node Node, visitor func(Node)) {\n\tReplace(node, func(n Node) Node { visitor(n); return n })\n}", "func (*Base) Visit(p ASTPass, node *ast.Node, ctx Context) {\n\n\tf := *(*node).OpenFodder()\n\tp.Fodder(p, &f, ctx)\n\t*(*node).OpenFodder() = f\n\n\tswitch node := (*node).(type) {\n\tcase *ast.Apply:\n\t\tp.Apply(p, node, ctx)\n\tcase *ast.ApplyBrace:\n\t\tp.ApplyBrace(p, node, ctx)\n\tcase *ast.Array:\n\t\tp.Array(p, node, ctx)\n\tcase *ast.ArrayComp:\n\t\tp.ArrayComp(p, node, ctx)\n\tcase *ast.Assert:\n\t\tp.Assert(p, node, ctx)\n\tcase *ast.Binary:\n\t\tp.Binary(p, node, ctx)\n\tcase *ast.Conditional:\n\t\tp.Conditional(p, node, ctx)\n\tcase *ast.Dollar:\n\t\tp.Dollar(p, node, ctx)\n\tcase *ast.Error:\n\t\tp.Error(p, node, ctx)\n\tcase *ast.Function:\n\t\tp.Function(p, node, ctx)\n\tcase *ast.Import:\n\t\tp.Import(p, node, ctx)\n\tcase *ast.ImportStr:\n\t\tp.ImportStr(p, node, ctx)\n\tcase *ast.ImportBin:\n\t\tp.ImportBin(p, node, ctx)\n\tcase *ast.Index:\n\t\tp.Index(p, node, ctx)\n\tcase *ast.InSuper:\n\t\tp.InSuper(p, node, ctx)\n\tcase *ast.LiteralBoolean:\n\t\tp.LiteralBoolean(p, node, ctx)\n\tcase *ast.LiteralNull:\n\t\tp.LiteralNull(p, node, ctx)\n\tcase *ast.LiteralNumber:\n\t\tp.LiteralNumber(p, node, ctx)\n\tcase *ast.LiteralString:\n\t\tp.LiteralString(p, node, ctx)\n\tcase *ast.Local:\n\t\tp.Local(p, node, ctx)\n\tcase *ast.Object:\n\t\tp.Object(p, node, ctx)\n\tcase *ast.ObjectComp:\n\t\tp.ObjectComp(p, node, ctx)\n\tcase *ast.Parens:\n\t\tp.Parens(p, node, ctx)\n\tcase *ast.Self:\n\t\tp.Self(p, node, ctx)\n\tcase *ast.Slice:\n\t\tp.Slice(p, node, ctx)\n\tcase *ast.SuperIndex:\n\t\tp.SuperIndex(p, node, ctx)\n\tcase *ast.Unary:\n\t\tp.Unary(p, node, ctx)\n\tcase *ast.Var:\n\t\tp.Var(p, node, ctx)\n\t}\n}", "func (this *Element) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitElement(this)\n}", "func (n *Interface) Walk(v walker.Visitor) {\n\tif v.EnterNode(n) == false {\n\t\treturn\n\t}\n\n\tif n.InterfaceName != nil {\n\t\tvv := v.GetChildrenVisitor(\"InterfaceName\")\n\t\tn.InterfaceName.Walk(vv)\n\t}\n\n\tif n.Extends != nil {\n\t\tvv := v.GetChildrenVisitor(\"Extends\")\n\t\tn.Extends.Walk(vv)\n\t}\n\n\tif n.Stmts != nil {\n\t\tvv := v.GetChildrenVisitor(\"Stmts\")\n\t\tfor _, nn := range n.Stmts {\n\t\t\tif nn != nil {\n\t\t\t\tnn.Walk(vv)\n\t\t\t}\n\t\t}\n\t}\n\n\tv.LeaveNode(n)\n}", "func (this *StrToZoneName) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func Visit(visitor func(funcName string, backend TemplateFunc)) {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tfor funcName, backend := range backends {\n\t\tvisitor(funcName, backend)\n\t}\n}", "func (this *DateDiffMillis) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *StrToUTC) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (u Unary) Accept(interpreter *Interpreter) Object {\n\treturn interpreter.visitUnary(u)\n}", "func (v *FuncVisitor) Visit(node ast.Node) ast.Visitor {\n\tswitch n := node.(type) {\n\tcase *ast.FuncDecl:\n\t\tif n.Body == nil {\n\t\t\t// Do not count declarations of assembly functions.\n\t\t\tbreak\n\t\t}\n\t\tstart := v.fset.Position(n.Pos())\n\t\tend := v.fset.Position(n.End())\n\n\t\tfe := &FuncExtent{\n\t\t\tName: v.signature(n),\n\t\t\tDecl: n,\n\t\t\tstartLine: start.Line,\n\t\t\tstartCol: start.Column,\n\t\t\tendLine: end.Line,\n\t\t\tendCol: end.Column,\n\t\t\tOffset: start.Offset,\n\t\t\tEnd: end.Offset,\n\t\t}\n\t\tv.funcs = append(v.funcs, fe)\n\t}\n\treturn v\n}", "func (this *DateAddStr) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *MillisToStr) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *Mod) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitMod(this)\n}", "func (this *StrToMillis) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (b Binary) Accept(interpreter *Interpreter) Object {\n\treturn interpreter.visitBinary(b)\n}", "func (this *MillisToUTC) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (v visitor) Visit(n ast.Node) ast.Visitor {\n\tif n == nil {\n\t\treturn nil\n\t}\n\n\tif ShouldPrintAbstractSyntaxTree {\n\t\tfmt.Printf(\"%s%T\\n\", strings.Repeat(\"\\t\", int(v)), n)\n\t\tfmt.Printf(\"%d\", v)\n\n\t\treturn v + 1\n\t}\n\n\tswitch d := n.(type) {\n\tcase *ast.Ident:\n\t\tif d.Obj == nil {\n\t\t\treturn v + 1\n\t\t}\n\n\t\tif d.Obj.Kind == ast.Typ {\n\t\t\tresult := parseStruct(d)\n\n\t\t\tfor i := range result {\n\t\t\t\t_, ok := Result[CurrentFile].StructScanResult[result[i].Name]\n\t\t\t\tif !ok {\n\t\t\t\t\tResult[CurrentFile].StructScanResult[result[i].Name] = result[i]\n\t\t\t\t}\n\t\t\t}\n\t\t} else if d.Obj.Kind == ast.Con || d.Obj.Kind == ast.Var {\n\t\t\tresult := parseConstantsAndVariables(d)\n\n\t\t\tfor i := range result {\n\t\t\t\t_, ok := Result[CurrentFile].ScanResult[result[i].Name]\n\t\t\t\tif !ok {\n\t\t\t\t\tResult[CurrentFile].ScanResult[result[i].Name] = result[i]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\tbreak\n\t}\n\n\treturn v + 1\n}", "func (p Passengers) Visit(visitor func(Passenger)) {\n\tfor _, one := range p {\n\t\tvisitor(one)\n\t}\n}", "func (p Passengers) Visit(visitor func(Passenger)) {\n\tfor _, one := range p {\n\t\tvisitor(one)\n\t}\n}", "func (this *MillisToZoneName) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (this *DateTruncStr) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (x AstSlice) Interface() interface{} { return asInterface(x.X, x.X == nil) }", "func (p *Parser) Interface() interface{} {\n\treturn p.data\n}", "func (*FuncExpr) iCallable() {}", "func (this *DateAddMillis) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (c *CallExpr) accept(v ExprVisitor) {\n\tv.VisitCall(c)\n}", "func (this *DatePartMillis) Accept(visitor Visitor) (interface{}, error) {\n\treturn visitor.VisitFunction(this)\n}", "func (f *Function) Call(arg interface{}) {\n\tf.input <- arg\n}", "func (l *List) Visit(f func(n *Node)) {\n\tp := l.head\n\tfor p != nil {\n\t\tf(p)\n\t\tp = p.next\n\t}\n}", "func (f WalkFunc) Walk(ctx context.Context, call *Call, path string) Node { return f(path) }", "func (r *fakeResourceResult) Visit(fn resource.VisitorFunc) error {\n\tfor _, info := range r.Infos {\n\t\terr := fn(info, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Replace(node Node, visitor func(Node) Node) {\n\tswitch n := node.(type) {\n\tcase *Abort:\n\tcase *API:\n\t\tfor i, c := range n.Enums {\n\t\t\tn.Enums[i] = visitor(c).(*Enum)\n\t\t}\n\t\tfor i, c := range n.Definitions {\n\t\t\tn.Definitions[i] = visitor(c).(*Definition)\n\t\t}\n\t\tfor i, c := range n.Classes {\n\t\t\tn.Classes[i] = visitor(c).(*Class)\n\t\t}\n\t\tfor i, c := range n.Pseudonyms {\n\t\t\tn.Pseudonyms[i] = visitor(c).(*Pseudonym)\n\t\t}\n\t\tfor i, c := range n.Externs {\n\t\t\tn.Externs[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Subroutines {\n\t\t\tn.Subroutines[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Functions {\n\t\t\tn.Functions[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Methods {\n\t\t\tn.Methods[i] = visitor(c).(*Function)\n\t\t}\n\t\tfor i, c := range n.Globals {\n\t\t\tn.Globals[i] = visitor(c).(*Global)\n\t\t}\n\t\tfor i, c := range n.StaticArrays {\n\t\t\tn.StaticArrays[i] = visitor(c).(*StaticArray)\n\t\t}\n\t\tfor i, c := range n.Maps {\n\t\t\tn.Maps[i] = visitor(c).(*Map)\n\t\t}\n\t\tfor i, c := range n.Pointers {\n\t\t\tn.Pointers[i] = visitor(c).(*Pointer)\n\t\t}\n\t\tfor i, c := range n.Slices {\n\t\t\tn.Slices[i] = visitor(c).(*Slice)\n\t\t}\n\t\tfor i, c := range n.References {\n\t\t\tn.References[i] = visitor(c).(*Reference)\n\t\t}\n\t\tfor i, c := range n.Signatures {\n\t\t\tn.Signatures[i] = visitor(c).(*Signature)\n\t\t}\n\tcase *ArrayAssign:\n\t\tn.To = visitor(n.To).(*ArrayIndex)\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase *ArrayIndex:\n\t\tn.Array = visitor(n.Array).(Expression)\n\t\tn.Index = visitor(n.Index).(Expression)\n\tcase *ArrayInitializer:\n\t\tn.Array = visitor(n.Array).(Type)\n\t\tfor i, c := range n.Values {\n\t\t\tn.Values[i] = visitor(c).(Expression)\n\t\t}\n\tcase *Slice:\n\t\tn.To = visitor(n.To).(Type)\n\tcase *SliceIndex:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\t\tn.Index = visitor(n.Index).(Expression)\n\tcase *SliceAssign:\n\t\tn.To = visitor(n.To).(*SliceIndex)\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase *Assert:\n\t\tn.Condition = visitor(n.Condition).(Expression)\n\tcase *Assign:\n\t\tn.LHS = visitor(n.LHS).(Expression)\n\t\tn.RHS = visitor(n.RHS).(Expression)\n\tcase *Annotation:\n\t\tfor i, c := range n.Arguments {\n\t\t\tn.Arguments[i] = visitor(c).(Expression)\n\t\t}\n\tcase *Block:\n\t\tfor i, c := range n.Statements {\n\t\t\tn.Statements[i] = visitor(c).(Statement)\n\t\t}\n\tcase BoolValue:\n\tcase *BinaryOp:\n\t\tif n.LHS != nil {\n\t\t\tn.LHS = visitor(n.LHS).(Expression)\n\t\t}\n\t\tif n.RHS != nil {\n\t\t\tn.RHS = visitor(n.RHS).(Expression)\n\t\t}\n\tcase *BitTest:\n\t\tn.Bitfield = visitor(n.Bitfield).(Expression)\n\t\tn.Bits = visitor(n.Bits).(Expression)\n\tcase *UnaryOp:\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\tcase *Branch:\n\t\tn.Condition = visitor(n.Condition).(Expression)\n\t\tn.True = visitor(n.True).(*Block)\n\t\tif n.False != nil {\n\t\t\tn.False = visitor(n.False).(*Block)\n\t\t}\n\tcase *Builtin:\n\tcase *Reference:\n\t\tn.To = visitor(n.To).(Type)\n\tcase *Call:\n\t\tn.Type = visitor(n.Type).(Type)\n\t\tn.Target = visitor(n.Target).(*Callable)\n\t\tfor i, a := range n.Arguments {\n\t\t\tn.Arguments[i] = visitor(a).(Expression)\n\t\t}\n\tcase *Callable:\n\t\tif n.Object != nil {\n\t\t\tn.Object = visitor(n.Object).(Expression)\n\t\t}\n\t\tn.Function = visitor(n.Function).(*Function)\n\tcase *Case:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, c := range n.Conditions {\n\t\t\tn.Conditions[i] = visitor(c).(Expression)\n\t\t}\n\t\tn.Block = visitor(n.Block).(*Block)\n\tcase *Cast:\n\t\tn.Object = visitor(n.Object).(Expression)\n\t\tn.Type = visitor(n.Type).(Type)\n\tcase *Class:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, f := range n.Fields {\n\t\t\tn.Fields[i] = visitor(f).(*Field)\n\t\t}\n\t\tfor i, m := range n.Methods {\n\t\t\tn.Methods[i] = visitor(m).(*Function)\n\t\t}\n\tcase *ClassInitializer:\n\t\tfor i, f := range n.Fields {\n\t\t\tn.Fields[i] = visitor(f).(*FieldInitializer)\n\t\t}\n\tcase *Choice:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, c := range n.Conditions {\n\t\t\tn.Conditions[i] = visitor(c).(Expression)\n\t\t}\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\tcase *Definition:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\tcase *DefinitionUsage:\n\t\tn.Expression = visitor(n.Expression).(Expression)\n\t\tn.Definition = visitor(n.Definition).(*Definition)\n\tcase *DeclareLocal:\n\t\tn.Local = visitor(n.Local).(*Local)\n\t\tif n.Local.Value != nil {\n\t\t\tn.Local.Value = visitor(n.Local.Value).(Expression)\n\t\t}\n\tcase Documentation:\n\tcase *Enum:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tfor i, e := range n.Entries {\n\t\t\tn.Entries[i] = visitor(e).(*EnumEntry)\n\t\t}\n\tcase *EnumEntry:\n\tcase *Fence:\n\t\tif n.Statement != nil {\n\t\t\tn.Statement = visitor(n.Statement).(Statement)\n\t\t}\n\tcase *Field:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.Type = visitor(n.Type).(Type)\n\t\tif n.Default != nil {\n\t\t\tn.Default = visitor(n.Default).(Expression)\n\t\t}\n\tcase *FieldInitializer:\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase Float32Value:\n\tcase Float64Value:\n\tcase *Function:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tif n.Return != nil {\n\t\t\tn.Return = visitor(n.Return).(*Parameter)\n\t\t}\n\t\tfor i, c := range n.FullParameters {\n\t\t\tn.FullParameters[i] = visitor(c).(*Parameter)\n\t\t}\n\t\tif n.Block != nil {\n\t\t\tn.Block = visitor(n.Block).(*Block)\n\t\t}\n\t\tn.Signature = visitor(n.Signature).(*Signature)\n\tcase *Global:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\tcase *StaticArray:\n\t\tn.ValueType = visitor(n.ValueType).(Type)\n\t\tn.SizeExpr = visitor(n.SizeExpr).(Expression)\n\tcase *Signature:\n\tcase Int8Value:\n\tcase Int16Value:\n\tcase Int32Value:\n\tcase Int64Value:\n\tcase *Iteration:\n\t\tn.Iterator = visitor(n.Iterator).(*Local)\n\t\tn.From = visitor(n.From).(Expression)\n\t\tn.To = visitor(n.To).(Expression)\n\t\tn.Block = visitor(n.Block).(*Block)\n\tcase *MapIteration:\n\t\tn.IndexIterator = visitor(n.IndexIterator).(*Local)\n\t\tn.KeyIterator = visitor(n.KeyIterator).(*Local)\n\t\tn.ValueIterator = visitor(n.ValueIterator).(*Local)\n\t\tn.Map = visitor(n.Map).(Expression)\n\t\tn.Block = visitor(n.Block).(*Block)\n\tcase Invalid:\n\tcase *Length:\n\t\tn.Object = visitor(n.Object).(Expression)\n\tcase *Local:\n\t\tn.Type = visitor(n.Type).(Type)\n\tcase *Map:\n\t\tn.KeyType = visitor(n.KeyType).(Type)\n\t\tn.ValueType = visitor(n.ValueType).(Type)\n\tcase *MapAssign:\n\t\tn.To = visitor(n.To).(*MapIndex)\n\t\tn.Value = visitor(n.Value).(Expression)\n\tcase *MapContains:\n\t\tn.Key = visitor(n.Key).(Expression)\n\t\tn.Map = visitor(n.Map).(Expression)\n\tcase *MapIndex:\n\t\tn.Map = visitor(n.Map).(Expression)\n\t\tn.Index = visitor(n.Index).(Expression)\n\tcase *MapRemove:\n\t\tn.Map = visitor(n.Map).(Expression)\n\t\tn.Key = visitor(n.Key).(Expression)\n\tcase *MapClear:\n\t\tn.Map = visitor(n.Map).(Expression)\n\tcase *Member:\n\t\tn.Object = visitor(n.Object).(Expression)\n\t\tn.Field = visitor(n.Field).(*Field)\n\tcase *MessageValue:\n\t\tfor i, a := range n.Arguments {\n\t\t\tn.Arguments[i] = visitor(a).(*FieldInitializer)\n\t\t}\n\tcase *New:\n\t\tn.Type = visitor(n.Type).(*Reference)\n\tcase *Parameter:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.Type = visitor(n.Type).(Type)\n\tcase *Pointer:\n\t\tn.To = visitor(n.To).(Type)\n\tcase *Pseudonym:\n\t\tfor i, c := range n.Annotations {\n\t\t\tn.Annotations[i] = visitor(c).(*Annotation)\n\t\t}\n\t\tn.To = visitor(n.To).(Type)\n\t\tfor i, m := range n.Methods {\n\t\t\tn.Methods[i] = visitor(m).(*Function)\n\t\t}\n\tcase *Return:\n\t\tif n.Value != nil {\n\t\t\tn.Value = visitor(n.Value).(Expression)\n\t\t}\n\tcase *Select:\n\t\tn.Value = visitor(n.Value).(Expression)\n\t\tfor i, c := range n.Choices {\n\t\t\tn.Choices[i] = visitor(c).(*Choice)\n\t\t}\n\t\tif n.Default != nil {\n\t\t\tn.Default = visitor(n.Default).(Expression)\n\t\t}\n\tcase StringValue:\n\tcase *Switch:\n\t\tn.Value = visitor(n.Value).(Expression)\n\t\tfor i, c := range n.Cases {\n\t\t\tn.Cases[i] = visitor(c).(*Case)\n\t\t}\n\t\tif n.Default != nil {\n\t\t\tn.Default = visitor(n.Default).(*Block)\n\t\t}\n\tcase Uint8Value:\n\tcase Uint16Value:\n\tcase Uint32Value:\n\tcase Uint64Value:\n\tcase *Unknown:\n\tcase *Clone:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tcase *Copy:\n\t\tn.Src = visitor(n.Src).(Expression)\n\t\tn.Dst = visitor(n.Dst).(Expression)\n\tcase *Create:\n\t\tn.Type = visitor(n.Type).(*Reference)\n\t\tn.Initializer = visitor(n.Initializer).(*ClassInitializer)\n\tcase *Ignore:\n\tcase *Make:\n\t\tn.Type = visitor(n.Type).(*Slice)\n\t\tn.Size = visitor(n.Size).(Expression)\n\tcase Null:\n\tcase *PointerRange:\n\t\tn.Pointer = visitor(n.Pointer).(Expression)\n\t\tn.Range = visitor(n.Range).(*BinaryOp)\n\tcase *Read:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tcase *SliceContains:\n\t\tn.Value = visitor(n.Value).(Expression)\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tcase *SliceRange:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\t\tn.Range = visitor(n.Range).(*BinaryOp)\n\tcase *Write:\n\t\tn.Slice = visitor(n.Slice).(Expression)\n\tdefault:\n\t\tpanic(fmt.Errorf(\"Unsupported semantic node type %T\", n))\n\t}\n}", "func (h *MapInt16ToInt) Visit(fn func(int16, int)) {\n\tfor _, e := range h.slots {\n\t\tfor ; e != nil; e = e.next {\n\t\t\tfn(e.k, e.v)\n\t\t}\n\t}\n}", "func FuncInterfaceCompatible(_ T1) {}", "func (b *Binary) Accept(v Visitor) {\n\tv.VisitBinary(b)\n}", "func (s *InterfaceStep) Interface() interface{} {\n\treturn s.value\n}", "func (h *MapInt16ToInt8) Visit(fn func(int16, int8)) {\n\tfor _, e := range h.slots {\n\t\tfor ; e != nil; e = e.next {\n\t\t\tfn(e.k, e.v)\n\t\t}\n\t}\n}", "func (s *Sequenced) Accept(v Visitor) {\n\tv.VisitSequenced(s)\n}", "func testVisitors(methodCalled *string) (*SimpleVisitor, []*SimpleVisitor) {\n\tv := &SimpleVisitor{\n\t\tDoVisitEnumNode: func(*EnumNode) error {\n\t\t\t*methodCalled = \"*EnumNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitEnumValueNode: func(*EnumValueNode) error {\n\t\t\t*methodCalled = \"*EnumValueNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitFieldDeclNode: func(FieldDeclNode) error {\n\t\t\t*methodCalled = \"FieldDeclNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitFieldNode: func(*FieldNode) error {\n\t\t\t*methodCalled = \"*FieldNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitGroupNode: func(*GroupNode) error {\n\t\t\t*methodCalled = \"*GroupNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitOneofNode: func(*OneofNode) error {\n\t\t\t*methodCalled = \"*OneofNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitMapTypeNode: func(*MapTypeNode) error {\n\t\t\t*methodCalled = \"*MapTypeNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitMapFieldNode: func(*MapFieldNode) error {\n\t\t\t*methodCalled = \"*MapFieldNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitFileNode: func(*FileNode) error {\n\t\t\t*methodCalled = \"*FileNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitSyntaxNode: func(*SyntaxNode) error {\n\t\t\t*methodCalled = \"*SyntaxNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitImportNode: func(*ImportNode) error {\n\t\t\t*methodCalled = \"*ImportNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitPackageNode: func(*PackageNode) error {\n\t\t\t*methodCalled = \"*PackageNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitIdentValueNode: func(IdentValueNode) error {\n\t\t\t*methodCalled = \"IdentValueNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitIdentNode: func(*IdentNode) error {\n\t\t\t*methodCalled = \"*IdentNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitCompoundIdentNode: func(*CompoundIdentNode) error {\n\t\t\t*methodCalled = \"*CompoundIdentNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitKeywordNode: func(*KeywordNode) error {\n\t\t\t*methodCalled = \"*KeywordNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitMessageDeclNode: func(MessageDeclNode) error {\n\t\t\t*methodCalled = \"MessageDeclNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitMessageNode: func(*MessageNode) error {\n\t\t\t*methodCalled = \"*MessageNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitExtendNode: func(*ExtendNode) error {\n\t\t\t*methodCalled = \"*ExtendNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitNode: func(Node) error {\n\t\t\t*methodCalled = \"Node\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitTerminalNode: func(TerminalNode) error {\n\t\t\t*methodCalled = \"TerminalNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitCompositeNode: func(CompositeNode) error {\n\t\t\t*methodCalled = \"CompositeNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitRuneNode: func(*RuneNode) error {\n\t\t\t*methodCalled = \"*RuneNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitEmptyDeclNode: func(*EmptyDeclNode) error {\n\t\t\t*methodCalled = \"*EmptyDeclNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitOptionNode: func(*OptionNode) error {\n\t\t\t*methodCalled = \"*OptionNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitOptionNameNode: func(*OptionNameNode) error {\n\t\t\t*methodCalled = \"*OptionNameNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitFieldReferenceNode: func(*FieldReferenceNode) error {\n\t\t\t*methodCalled = \"*FieldReferenceNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitCompactOptionsNode: func(*CompactOptionsNode) error {\n\t\t\t*methodCalled = \"*CompactOptionsNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitExtensionRangeNode: func(*ExtensionRangeNode) error {\n\t\t\t*methodCalled = \"*ExtensionRangeNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitRangeNode: func(*RangeNode) error {\n\t\t\t*methodCalled = \"*RangeNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitReservedNode: func(*ReservedNode) error {\n\t\t\t*methodCalled = \"*ReservedNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitServiceNode: func(*ServiceNode) error {\n\t\t\t*methodCalled = \"*ServiceNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitRPCNode: func(*RPCNode) error {\n\t\t\t*methodCalled = \"*RPCNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitRPCTypeNode: func(*RPCTypeNode) error {\n\t\t\t*methodCalled = \"*RPCTypeNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitValueNode: func(ValueNode) error {\n\t\t\t*methodCalled = \"ValueNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitStringValueNode: func(StringValueNode) error {\n\t\t\t*methodCalled = \"StringValueNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitStringLiteralNode: func(*StringLiteralNode) error {\n\t\t\t*methodCalled = \"*StringLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitCompoundStringLiteralNode: func(*CompoundStringLiteralNode) error {\n\t\t\t*methodCalled = \"*CompoundStringLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitIntValueNode: func(IntValueNode) error {\n\t\t\t*methodCalled = \"IntValueNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitUintLiteralNode: func(*UintLiteralNode) error {\n\t\t\t*methodCalled = \"*UintLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitPositiveUintLiteralNode: func(*PositiveUintLiteralNode) error {\n\t\t\t*methodCalled = \"*PositiveUintLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitNegativeIntLiteralNode: func(*NegativeIntLiteralNode) error {\n\t\t\t*methodCalled = \"*NegativeIntLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitFloatValueNode: func(FloatValueNode) error {\n\t\t\t*methodCalled = \"FloatValueNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitFloatLiteralNode: func(*FloatLiteralNode) error {\n\t\t\t*methodCalled = \"*FloatLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitSpecialFloatLiteralNode: func(*SpecialFloatLiteralNode) error {\n\t\t\t*methodCalled = \"*SpecialFloatLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitSignedFloatLiteralNode: func(*SignedFloatLiteralNode) error {\n\t\t\t*methodCalled = \"*SignedFloatLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitArrayLiteralNode: func(*ArrayLiteralNode) error {\n\t\t\t*methodCalled = \"*ArrayLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitMessageLiteralNode: func(*MessageLiteralNode) error {\n\t\t\t*methodCalled = \"*MessageLiteralNode\"\n\t\t\treturn nil\n\t\t},\n\t\tDoVisitMessageFieldNode: func(*MessageFieldNode) error {\n\t\t\t*methodCalled = \"*MessageFieldNode\"\n\t\t\treturn nil\n\t\t},\n\t}\n\tothers := []*SimpleVisitor{\n\t\t{\n\t\t\tDoVisitEnumNode: v.DoVisitEnumNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitEnumValueNode: v.DoVisitEnumValueNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitFieldDeclNode: v.DoVisitFieldDeclNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitFieldNode: v.DoVisitFieldNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitGroupNode: v.DoVisitGroupNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitOneofNode: v.DoVisitOneofNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitMapTypeNode: v.DoVisitMapTypeNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitMapFieldNode: v.DoVisitMapFieldNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitFileNode: v.DoVisitFileNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitSyntaxNode: v.DoVisitSyntaxNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitImportNode: v.DoVisitImportNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitPackageNode: v.DoVisitPackageNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitIdentValueNode: v.DoVisitIdentValueNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitIdentNode: v.DoVisitIdentNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitCompoundIdentNode: v.DoVisitCompoundIdentNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitKeywordNode: v.DoVisitKeywordNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitMessageDeclNode: v.DoVisitMessageDeclNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitMessageNode: v.DoVisitMessageNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitExtendNode: v.DoVisitExtendNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitNode: v.DoVisitNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitTerminalNode: v.DoVisitTerminalNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitCompositeNode: v.DoVisitCompositeNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitRuneNode: v.DoVisitRuneNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitEmptyDeclNode: v.DoVisitEmptyDeclNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitOptionNode: v.DoVisitOptionNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitOptionNameNode: v.DoVisitOptionNameNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitFieldReferenceNode: v.DoVisitFieldReferenceNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitCompactOptionsNode: v.DoVisitCompactOptionsNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitExtensionRangeNode: v.DoVisitExtensionRangeNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitRangeNode: v.DoVisitRangeNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitReservedNode: v.DoVisitReservedNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitServiceNode: v.DoVisitServiceNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitRPCNode: v.DoVisitRPCNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitRPCTypeNode: v.DoVisitRPCTypeNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitValueNode: v.DoVisitValueNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitStringValueNode: v.DoVisitStringValueNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitStringLiteralNode: v.DoVisitStringLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitCompoundStringLiteralNode: v.DoVisitCompoundStringLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitIntValueNode: v.DoVisitIntValueNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitUintLiteralNode: v.DoVisitUintLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitPositiveUintLiteralNode: v.DoVisitPositiveUintLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitNegativeIntLiteralNode: v.DoVisitNegativeIntLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitFloatValueNode: v.DoVisitFloatValueNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitFloatLiteralNode: v.DoVisitFloatLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitSpecialFloatLiteralNode: v.DoVisitSpecialFloatLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitSignedFloatLiteralNode: v.DoVisitSignedFloatLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitArrayLiteralNode: v.DoVisitArrayLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitMessageLiteralNode: v.DoVisitMessageLiteralNode,\n\t\t},\n\t\t{\n\t\t\tDoVisitMessageFieldNode: v.DoVisitMessageFieldNode,\n\t\t},\n\t}\n\treturn v, others\n}", "func _[T interface{ ~func(string) int }](f T) int {\n\treturn f(\"hello\")\n}", "func VisitedFunctions(prog *ssa.Program, packs []*ssa.Package, isOvl isOverloaded) (seen, usesGR map[*ssa.Function]bool) {\n\tvisit := visitor{\n\t\tprog: prog,\n\t\tpacks: packs, // new\n\t\tseen: make(map[*ssa.Function]bool),\n\t\tusesGR: make(map[*ssa.Function]bool),\n\t}\n\tvisit.program(isOvl)\n\t//fmt.Printf(\"DEBUG VisitedFunctions.usesGR %v\\n\", visit.usesGR)\n\t//fmt.Printf(\"DEBUG VisitedFunctions.seen %v\\n\", visit.seen)\n\treturn visit.seen, visit.usesGR\n}", "func (h *MapInt16ToInt32) Visit(fn func(int16, int32)) {\n\tfor _, e := range h.slots {\n\t\tfor ; e != nil; e = e.next {\n\t\t\tfn(e.k, e.v)\n\t\t}\n\t}\n}", "func (x *fastReflection_Evidence) Interface() protoreflect.ProtoMessage {\n\treturn (*Evidence)(x)\n}", "func (f *functionQuery) Evaluate(t iterator) interface{} {\n\treturn f.Func(f.Input, t)\n}", "func Visit(node Node, visitor func(node Node, next func() error) error) error {\n\tif reflect.ValueOf(node).IsNil() { // Workaround for Go's typed nil interfaces.\n\t\treturn nil\n\t}\n\treturn visitor(node, func() error {\n\t\tfor _, child := range node.children() {\n\t\t\tif err := Visit(child, visitor); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func (x *fastReflection_Output) Interface() protoreflect.ProtoMessage {\n\treturn (*Output)(x)\n}", "func (i I) I() I { return i }", "func (rf RendererFunc) Render(w io.Writer, v interface{}) error { return rf(w, v) }", "func (v Variable) Accept(interpreter *Interpreter) Object {\n\treturn interpreter.visitVariable(v)\n}", "func (*Base) Function(p ASTPass, node *ast.Function, ctx Context) {\n\tp.Parameters(p, &node.ParenLeftFodder, &node.Parameters, &node.ParenRightFodder, ctx)\n\tp.Visit(p, &node.Body, ctx)\n}", "func (t *FileTree) VisitorFn(fn func(file.Reference)) func(node.Node) {\n\treturn func(node node.Node) {\n\t\tfn(t.fileByPathID(node.ID()))\n\t}\n}", "func execNewInterface(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := types.NewInterface(args[0].([]*types.Func), args[1].([]*types.Named))\n\tp.Ret(2, ret)\n}", "func (h *MapInt16ToUint8) Visit(fn func(int16, uint8)) {\n\tfor _, e := range h.slots {\n\t\tfor ; e != nil; e = e.next {\n\t\t\tfn(e.k, e.v)\n\t\t}\n\t}\n}", "func FuncInterfaceCompatible2(_ io.Writer) {}", "func (h *MapInt16ToInt16) Visit(fn func(int16, int16)) {\n\tfor _, e := range h.slots {\n\t\tfor ; e != nil; e = e.next {\n\t\t\tfn(e.k, e.v)\n\t\t}\n\t}\n}", "func Function(sig *CallSignature) Type {\n\treturn Type{functionImpl{sig: sig}}\n}", "func (mi *ModifierInvocation) Visit(ctx *parser.ModifierInvocationContext) {\n\tmi.Start = ctx.GetStart()\n\tmi.Stop = ctx.GetStop()\n\tmi.Identifier = ctx.Identifier().GetText()\n\n\tif ctx.ExpressionList() != nil {\n\t\texpList := ctx.ExpressionList().(*parser.ExpressionListContext)\n\n\t\tfor _, exprCtx := range expList.AllExpression() {\n\t\t\texpression := NewExpression()\n\t\t\texpression.Visit(exprCtx.(*parser.ExpressionContext))\n\n\t\t\tmi.Expressions = append(mi.Expressions, expression)\n\t\t}\n\t}\n}", "func (x *fastReflection_Input) Interface() protoreflect.ProtoMessage {\n\treturn (*Input)(x)\n}", "func (a Assign) Accept(interpreter *Interpreter) Object {\n\treturn interpreter.visitAssign(a)\n}", "func (h *MapInt16ToUint) Visit(fn func(int16, uint)) {\n\tfor _, e := range h.slots {\n\t\tfor ; e != nil; e = e.next {\n\t\t\tfn(e.k, e.v)\n\t\t}\n\t}\n}", "func (h *MapInt16ToUint32) Visit(fn func(int16, uint32)) {\n\tfor _, e := range h.slots {\n\t\tfor ; e != nil; e = e.next {\n\t\t\tfn(e.k, e.v)\n\t\t}\n\t}\n}", "func (_Contract *ContractCallerSession) InterfaceImplementer(node [32]byte, interfaceID [4]byte) (common.Address, error) {\n\treturn _Contract.Contract.InterfaceImplementer(&_Contract.CallOpts, node, interfaceID)\n}", "func (g Grouping) Accept(interpreter *Interpreter) Object {\n\treturn interpreter.visitGrouping(g)\n}", "func Interface(ifname string) func(*NetworkTap) error {\n\treturn func(filterdev *NetworkTap) error {\n\t\terr := filterdev.SetInterface(int(filterdev.device.Fd()), ifname)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n}", "func (f *FlagSet) Visit(fn func(*Flag)) {\n\tfor _, flag := range sortFlags(f.actual) {\n\t\tfn(flag)\n\t}\n}", "func (_Contract *ContractFilterer) FilterInterfaceChanged(opts *bind.FilterOpts, node [][32]byte, interfaceID [][4]byte) (*ContractInterfaceChangedIterator, error) {\n\n\tvar nodeRule []interface{}\n\tfor _, nodeItem := range node {\n\t\tnodeRule = append(nodeRule, nodeItem)\n\t}\n\tvar interfaceIDRule []interface{}\n\tfor _, interfaceIDItem := range interfaceID {\n\t\tinterfaceIDRule = append(interfaceIDRule, interfaceIDItem)\n\t}\n\n\tlogs, sub, err := _Contract.contract.FilterLogs(opts, \"InterfaceChanged\", nodeRule, interfaceIDRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ContractInterfaceChangedIterator{contract: _Contract.contract, event: \"InterfaceChanged\", logs: logs, sub: sub}, nil\n}", "func (f *FlagSet) Visit(fn func(*Flag)) {\n\tif len(f.actual) == 0 {\n\t\treturn\n\t}\n\n\tvar flags []*Flag\n\tif f.SortFlags {\n\t\tif len(f.actual) != len(f.sortedActual) {\n\t\t\tf.sortedActual = sortFlags(f.actual)\n\t\t}\n\t\tflags = f.sortedActual\n\t} else {\n\t\tflags = f.orderedActual\n\t}\n\n\tfor _, flag := range flags {\n\t\tfn(flag)\n\t}\n}", "func (x *fastReflection_EventRetire) Interface() protoreflect.ProtoMessage {\n\treturn (*EventRetire)(x)\n}", "func execmInterfaceMethod(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := args[0].(*types.Interface).Method(args[1].(int))\n\tp.Ret(2, ret)\n}", "func (lambda PresenterFunc) Render(message interface{}) error {\n\treturn lambda(message)\n}", "func underlyingInterface(w v1alpha1.ExecutableWorkflow, node v1alpha1.ExecutableNode) (*core.TypedInterface, error) {\n\tiface := &core.TypedInterface{}\n\tif node.GetTaskID() != nil {\n\t\tt, err := w.GetTask(*node.GetTaskID())\n\t\tif err != nil {\n\t\t\t// Should never happen\n\t\t\treturn nil, err\n\t\t}\n\n\t\tiface.Outputs = t.CoreTask().GetInterface().Outputs\n\t} else if wfNode := node.GetWorkflowNode(); wfNode != nil {\n\t\tif wfRef := wfNode.GetSubWorkflowRef(); wfRef != nil {\n\t\t\tt := w.FindSubWorkflow(*wfRef)\n\t\t\tif t == nil {\n\t\t\t\t// Should never happen\n\t\t\t\treturn nil, errors.Errorf(errors.IllegalStateError, node.GetID(), \"Couldn't find subworkflow [%v].\", wfRef)\n\t\t\t}\n\n\t\t\tiface.Outputs = t.GetOutputs().VariableMap\n\t\t} else {\n\t\t\treturn nil, errors.Errorf(errors.IllegalStateError, node.GetID(), \"Unknown interface\")\n\t\t}\n\t} else if node.GetBranchNode() != nil {\n\t\tif ifBlock := node.GetBranchNode().GetIf(); ifBlock != nil && ifBlock.GetThenNode() != nil {\n\t\t\tbn, found := w.GetNode(*ifBlock.GetThenNode())\n\t\t\tif !found {\n\t\t\t\treturn nil, errors.Errorf(errors.IllegalStateError, node.GetID(), \"Couldn't find branch node [%v]\",\n\t\t\t\t\t*ifBlock.GetThenNode())\n\t\t\t}\n\n\t\t\treturn underlyingInterface(w, bn)\n\t\t}\n\n\t\treturn nil, errors.Errorf(errors.IllegalStateError, node.GetID(), \"Empty branch detected.\")\n\t} else {\n\t\treturn nil, errors.Errorf(errors.IllegalStateError, node.GetID(), \"Unknown interface.\")\n\t}\n\n\treturn iface, nil\n}" ]
[ "0.601801", "0.59070253", "0.59054166", "0.58446676", "0.58266926", "0.5820728", "0.5820728", "0.5802115", "0.57868934", "0.577937", "0.57069504", "0.5627799", "0.5535857", "0.5494115", "0.5471187", "0.5471187", "0.5465064", "0.5435572", "0.54174775", "0.54174775", "0.5403646", "0.5398771", "0.535826", "0.53455204", "0.5325374", "0.5281957", "0.52587587", "0.5246482", "0.52396625", "0.5171417", "0.51708597", "0.51699823", "0.5150497", "0.5102451", "0.5098949", "0.50967133", "0.50936455", "0.5027757", "0.5014371", "0.50071734", "0.49832156", "0.4978006", "0.49501696", "0.4947642", "0.49169374", "0.4905309", "0.4905309", "0.4886982", "0.48809353", "0.4865095", "0.48484156", "0.4842497", "0.48256105", "0.4806719", "0.47928524", "0.478826", "0.47633818", "0.47612065", "0.47563323", "0.4756313", "0.47518948", "0.47470203", "0.47409767", "0.47342384", "0.47334284", "0.47197035", "0.4717382", "0.46857443", "0.4679505", "0.46787944", "0.46590173", "0.46579817", "0.4657036", "0.4652146", "0.46448997", "0.46417892", "0.46409145", "0.46362963", "0.461541", "0.46128434", "0.46116787", "0.46064425", "0.46029806", "0.45986757", "0.45887613", "0.4581343", "0.45772165", "0.45628566", "0.4561018", "0.45593852", "0.4557327", "0.4549671", "0.45452303", "0.45387414", "0.45345315", "0.45330152", "0.45300865", "0.45288858", "0.45200968" ]
0.56891
12