text
stringlengths 11
4.05M
|
|---|
package main
import "os"
import "fmt"
import "log"
func create() {
println("creating stuff")
file, _ := os.Create("cheese.txt")
defer file.Close()
fmt.Fprint(file, "CHEESE BITCHES :P")
}
/*
func write() {
file, err := os.Open("cheese.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
fmt.Fprint(file, "MORE CHEESE BITCHES :)")
file.Write("MORE CHEESE BITCHES :)")
}
*/
func read() {
println("reading stuff")
file, err := os.Open("cheese.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
data := make([]byte, 100)
stuff, _ := file.Read(data)
fmt.Printf("read %d bytes: %q\n", stuff, data[:stuff])
}
func main() {
create()
//write()
read()
}
|
package main
import (
"bufio"
"fmt"
"log"
"net/http"
)
func main() {
res, err := http.Get("http://www.gutenberg.org/files/2701/old/moby10b.txt")
if err != nil {
log.Fatal(err)
}
// scan the page
scanner := bufio.NewScanner(res.Body)
defer res.Body.Close()
// set the split function for the scanning operation
scanner.Split(bufio.ScanWords)
// create slice to hold counts
buckets := make([]int, 200)
// loop over the words
for scanner.Scan() {
n := hashBucket(scanner.Text())
buckets[n]++
}
for i := 65; i < 126; i++ {
fmt.Printf("%v - %c - %v \n", i, i, buckets[i])
}
}
func hashBucket(word string) int {
return int(word[0])
}
// 65 - A - 1790
// 66 - B - 1260
// 67 - C - 910
// 68 - D - 522
// 69 - E - 325
// 70 - F - 658
// 71 - G - 473
// 72 - H - 812
// 73 - I - 2829
// 74 - J - 244
// 75 - K - 80
// 76 - L - 504
// 77 - M - 563
// 78 - N - 672
// 79 - O - 433
// 80 - P - 816
// 81 - Q - 291
// 82 - R - 259
// 83 - S - 1671
// 84 - T - 1771
// 85 - U - 87
// 86 - V - 119
// 87 - W - 1080
// 88 - X - 5
// 89 - Y - 205
// 90 - Z - 15
// 91 - [ - 21
// 92 - \ - 0
// 93 - ] - 0
// 94 - ^ - 0
// 95 - _ - 2
// 96 - ` - 0
// 97 - a - 21787
// 98 - b - 9692
// 99 - c - 7385
// 100 - d - 5219
// 101 - e - 3614
// 102 - f - 7576
// 103 - g - 3016
// 104 - h - 12620
// 105 - i - 11607
// 106 - j - 582
// 107 - k - 852
// 108 - l - 5321
// 109 - m - 7765
// 110 - n - 4060
// 111 - o - 13798
// 112 - p - 5256
// 113 - q - 395
// 114 - r - 3592
// 115 - s - 16260
// 116 - t - 33335
// 117 - u - 2591
// 118 - v - 1452
// 119 - w - 13314
// 120 - x - 1
// 121 - y - 2272
// 122 - z - 19
// 123 - { - 0
// 124 - | - 0
// 125 - } - 0
|
package agent_test
import (
"context"
"fmt"
"math/rand"
"strings"
"testing"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/rt"
power2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/power"
states2 "github.com/filecoin-project/specs-actors/v2/actors/states"
vm_test2 "github.com/filecoin-project/specs-actors/v2/support/vm"
states3 "github.com/filecoin-project/specs-actors/v3/actors/states"
vm_test3 "github.com/filecoin-project/specs-actors/v3/support/vm"
cid "github.com/ipfs/go-cid"
cbor "github.com/ipfs/go-ipld-cbor"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/filecoin-project/specs-actors/v4/actors/builtin"
"github.com/filecoin-project/specs-actors/v4/actors/builtin/exported"
"github.com/filecoin-project/specs-actors/v4/actors/builtin/power"
"github.com/filecoin-project/specs-actors/v4/actors/migration/nv10"
"github.com/filecoin-project/specs-actors/v4/actors/states"
"github.com/filecoin-project/specs-actors/v4/actors/util/adt"
"github.com/filecoin-project/specs-actors/v4/support/agent"
"github.com/filecoin-project/specs-actors/v4/support/ipld"
vm_test "github.com/filecoin-project/specs-actors/v4/support/vm"
)
func TestCreate20Miners(t *testing.T) {
ctx := context.Background()
initialBalance := big.Mul(big.NewInt(1000), big.NewInt(1e18))
minerCount := 20
rnd := rand.New(rand.NewSource(42))
sim := agent.NewSim(ctx, t, newBlockStore, agent.SimConfig{Seed: rnd.Int63()})
accounts := vm_test.CreateAccounts(ctx, t, getV3VM(t, sim), minerCount, initialBalance, rnd.Int63())
sim.AddAgent(agent.NewMinerGenerator(
accounts,
agent.MinerAgentConfig{
PrecommitRate: 2.5,
ProofType: abi.RegisteredSealProof_StackedDrg32GiBV1_1,
StartingBalance: initialBalance,
MinMarketBalance: big.Zero(),
MaxMarketBalance: big.Zero(),
},
1.0, // create miner probability of 1 means a new miner is created every tick
rnd.Int63(),
))
// give it twice the number of ticks to account for variation in the rate
for i := 0; i < 2*minerCount; i++ {
require.NoError(t, sim.Tick())
}
// add 1 agent for miner generator
assert.Equal(t, minerCount+1, len(sim.Agents))
for _, a := range sim.Agents {
miner, ok := a.(*agent.MinerAgent)
if ok {
actor, found, err := sim.GetVM().GetActor(miner.IDAddress)
require.NoError(t, err)
require.True(t, found)
// demonstrate actor is created and has correct balance
assert.Equal(t, initialBalance, actor.Balance)
}
}
}
// This test covers all the simulation functionality.
// 500 epochs is long enough for most, not all, important processes to take place, but runs fast enough
// to keep in CI.
func Test500Epochs(t *testing.T) {
ctx := context.Background()
initialBalance := big.Mul(big.NewInt(1e8), big.NewInt(1e18))
cumulativeStats := make(vm_test.StatsByCall)
minerCount := 10
clientCount := 9
// set up sim
rnd := rand.New(rand.NewSource(42))
sim := agent.NewSim(ctx, t, newBlockStore, agent.SimConfig{
Seed: rnd.Int63(),
CheckpointEpochs: 1000,
})
// create miners
workerAccounts := vm_test.CreateAccounts(ctx, t, getV3VM(t, sim), minerCount, initialBalance, rnd.Int63())
sim.AddAgent(agent.NewMinerGenerator(
workerAccounts,
agent.MinerAgentConfig{
PrecommitRate: 2.0,
FaultRate: 0.0001,
RecoveryRate: 0.0001,
UpgradeSectors: true,
ProofType: abi.RegisteredSealProof_StackedDrg32GiBV1_1,
StartingBalance: big.Div(initialBalance, big.NewInt(2)),
MinMarketBalance: big.NewInt(1e18),
MaxMarketBalance: big.NewInt(2e18),
},
1.0, // create miner probability of 1 means a new miner is created every tick
rnd.Int63(),
))
clientAccounts := vm_test.CreateAccounts(ctx, t, getV3VM(t, sim), clientCount, initialBalance, rnd.Int63())
dealAgents := agent.AddDealClientsForAccounts(sim, clientAccounts, rnd.Int63(), agent.DealClientConfig{
DealRate: .05,
MinPieceSize: 1 << 29,
MaxPieceSize: 32 << 30,
MinStoragePrice: big.Zero(),
MaxStoragePrice: abi.NewTokenAmount(200_000_000),
MinMarketBalance: big.NewInt(1e18),
MaxMarketBalance: big.NewInt(2e18),
})
var pwrSt power.State
for i := 0; i < 500; i++ {
require.NoError(t, sim.Tick())
epoch := sim.GetVM().GetEpoch()
if epoch%100 == 0 {
// compute number of deals
deals := 0
for _, da := range dealAgents {
deals += da.DealCount
}
stateTree, err := getV3VM(t, sim).GetStateTree()
require.NoError(t, err)
totalBalance, err := getV3VM(t, sim).GetTotalActorBalance()
require.NoError(t, err)
acc, err := states.CheckStateInvariants(stateTree, totalBalance, sim.GetVM().GetEpoch()-1)
require.NoError(t, err)
require.True(t, acc.IsEmpty(), strings.Join(acc.Messages(), "\n"))
require.NoError(t, sim.GetVM().GetState(builtin.StoragePowerActorAddr, &pwrSt))
// assume each sector is 32Gb
sectorCount := big.Div(pwrSt.TotalBytesCommitted, big.NewInt(32<<30))
fmt.Printf("Power at %d: raw: %v cmtRaw: %v cmtSecs: %d msgs: %d deals: %d gets: %d puts: %d write bytes: %d read bytes: %d\n",
epoch, pwrSt.TotalRawBytePower, pwrSt.TotalBytesCommitted, sectorCount.Uint64(),
sim.MessageCount, deals, getV3VM(t, sim).StoreReads(), getV3VM(t, sim).StoreWrites(),
getV3VM(t, sim).StoreReadBytes(), getV3VM(t, sim).StoreWriteBytes())
}
cumulativeStats.MergeAllStats(sim.GetCallStats())
}
}
func TestCommitPowerAndCheckInvariants(t *testing.T) {
t.Skip("this is slow")
ctx := context.Background()
initialBalance := big.Mul(big.NewInt(1e9), big.NewInt(1e18))
minerCount := 1
rnd := rand.New(rand.NewSource(42))
sim := agent.NewSim(ctx, t, newBlockStore, agent.SimConfig{Seed: rnd.Int63()})
accounts := vm_test.CreateAccounts(ctx, t, getV3VM(t, sim), minerCount, initialBalance, rnd.Int63())
sim.AddAgent(agent.NewMinerGenerator(
accounts,
agent.MinerAgentConfig{
PrecommitRate: 0.1,
FaultRate: 0.00001,
RecoveryRate: 0.0001,
ProofType: abi.RegisteredSealProof_StackedDrg32GiBV1_1,
StartingBalance: initialBalance,
MinMarketBalance: big.Zero(),
MaxMarketBalance: big.Zero(),
},
1.0, // create miner probability of 1 means a new miner is created every tick
rnd.Int63(),
))
var pwrSt power.State
for i := 0; i < 100_000; i++ {
require.NoError(t, sim.Tick())
epoch := sim.GetVM().GetEpoch()
if epoch%100 == 0 {
stateTree, err := getV3VM(t, sim).GetStateTree()
require.NoError(t, err)
totalBalance, err := getV3VM(t, sim).GetTotalActorBalance()
require.NoError(t, err)
acc, err := states.CheckStateInvariants(stateTree, totalBalance, sim.GetVM().GetEpoch()-1)
require.NoError(t, err)
require.True(t, acc.IsEmpty(), strings.Join(acc.Messages(), "\n"))
require.NoError(t, sim.GetVM().GetState(builtin.StoragePowerActorAddr, &pwrSt))
// assume each sector is 32Gb
sectorCount := big.Div(pwrSt.TotalBytesCommitted, big.NewInt(32<<30))
fmt.Printf("Power at %d: raw: %v cmtRaw: %v cmtSecs: %d cnsMnrs: %d avgWins: %.3f msgs: %d\n",
epoch, pwrSt.TotalRawBytePower, pwrSt.TotalBytesCommitted, sectorCount.Uint64(),
pwrSt.MinerAboveMinPowerCount, float64(sim.WinCount)/float64(epoch), sim.MessageCount)
}
}
}
func TestMigration(t *testing.T) {
t.Skip("slow")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
initialBalance := big.Mul(big.NewInt(1e8), big.NewInt(1e18))
minerCount := 10
clientCount := 9
blkStore := newBlockStore()
v := vm_test2.NewVMWithSingletons(ctx, t, blkStore)
v2VMFactory := func(ctx context.Context, impl vm_test2.ActorImplLookup, store adt.Store, stateRoot cid.Cid, epoch abi.ChainEpoch) (agent.SimVM, error) {
return vm_test2.NewVMAtEpoch(ctx, impl, store, stateRoot, epoch)
}
v2MinerFactory := func(ctx context.Context, root cid.Cid) (agent.SimMinerState, error) {
return &agent.MinerStateV2{
Ctx: ctx,
Root: root,
}, nil
}
// set up sim
rnd := rand.New(rand.NewSource(42))
sim := agent.NewSimWithVM(ctx, t, v, v2VMFactory, agent.ComputePowerTableV2, blkStore, newBlockStore, v2MinerFactory, agent.SimConfig{
Seed: rnd.Int63(),
CheckpointEpochs: 1000,
}, agent.CreateMinerParamsV2)
// create miners
workerAccounts := vm_test2.CreateAccounts(ctx, t, v, minerCount, initialBalance, rnd.Int63())
sim.AddAgent(agent.NewMinerGenerator(
workerAccounts,
agent.MinerAgentConfig{
PrecommitRate: 2.0,
FaultRate: 0.00001,
RecoveryRate: 0.0001,
UpgradeSectors: true,
ProofType: abi.RegisteredSealProof_StackedDrg32GiBV1_1,
StartingBalance: big.Div(initialBalance, big.NewInt(2)),
MinMarketBalance: big.NewInt(1e18),
MaxMarketBalance: big.NewInt(2e18),
},
1.0, // create miner probability of 1 means a new miner is created every tick
rnd.Int63(),
))
clientAccounts := vm_test2.CreateAccounts(ctx, t, v, clientCount, initialBalance, rnd.Int63())
agent.AddDealClientsForAccounts(sim, clientAccounts, rnd.Int63(), agent.DealClientConfig{
DealRate: .05,
MinPieceSize: 1 << 29,
MaxPieceSize: 32 << 30,
MinStoragePrice: big.Zero(),
MaxStoragePrice: abi.NewTokenAmount(200_000_000),
MinMarketBalance: big.NewInt(1e18),
MaxMarketBalance: big.NewInt(2e18),
})
// Run v2 for 5000 epochs
var pwrSt power2.State
for i := 0; i < 5000; i++ {
require.NoError(t, sim.Tick())
epoch := sim.GetVM().GetEpoch()
if epoch%100 == 0 {
stateTree, err := states2.LoadTree(sim.GetVM().Store(), sim.GetVM().StateRoot())
require.NoError(t, err)
totalBalance, err := sim.GetVM().GetTotalActorBalance()
require.NoError(t, err)
acc, err := states2.CheckStateInvariants(stateTree, totalBalance, sim.GetVM().GetEpoch()-1)
require.NoError(t, err)
require.True(t, acc.IsEmpty(), strings.Join(acc.Messages(), "\n"))
require.NoError(t, sim.GetVM().GetState(builtin.StoragePowerActorAddr, &pwrSt))
// assume each sector is 32Gb
sectorCount := big.Div(pwrSt.TotalBytesCommitted, big.NewInt(32<<30))
fmt.Printf("Power at %d: raw: %v cmtRaw: %v cmtSecs: %d cnsMnrs: %d avgWins: %.3f msgs: %d\n",
epoch, pwrSt.TotalRawBytePower, pwrSt.TotalBytesCommitted, sectorCount.Uint64(),
pwrSt.MinerAboveMinPowerCount, float64(sim.WinCount)/float64(epoch), sim.MessageCount)
}
}
// Migrate
v2 := sim.GetVM()
log := nv10.TestLogger{TB: t}
priorEpoch := v2.GetEpoch() - 1 // on tick sim internally creates new vm with epoch set to the next one
nextRoot, err := nv10.MigrateStateTree(ctx, v2.Store(), v2.StateRoot(), priorEpoch, nv10.Config{MaxWorkers: 1}, log, nv10.NewMemMigrationCache())
require.NoError(t, err)
lookup := map[cid.Cid]rt.VMActor{}
for _, ba := range exported.BuiltinActors() {
lookup[ba.Code()] = ba
}
v3, err := vm_test3.NewVMAtEpoch(ctx, lookup, v2.Store(), nextRoot, priorEpoch+1)
require.NoError(t, err)
stateTree, err := v3.GetStateTree()
require.NoError(t, err)
totalBalance, err := v3.GetTotalActorBalance()
require.NoError(t, err)
msgs, err := states3.CheckStateInvariants(stateTree, totalBalance, priorEpoch)
require.NoError(t, err)
assert.Zero(t, len(msgs.Messages()), strings.Join(msgs.Messages(), "\n"))
v3VMFactory := func(ctx context.Context, impl vm_test2.ActorImplLookup, store adt.Store, stateRoot cid.Cid, epoch abi.ChainEpoch) (agent.SimVM, error) {
return vm_test.NewVMAtEpoch(ctx, vm_test.ActorImplLookup(impl), store, stateRoot, epoch)
}
v3MinerFactory := func(ctx context.Context, root cid.Cid) (agent.SimMinerState, error) {
return &agent.MinerStateV3{
Ctx: ctx,
Root: root,
}, nil
}
sim.SwapVM(v3, agent.VMFactoryFunc(v3VMFactory), v3MinerFactory, agent.ComputePowerTableV3, agent.CreateMinerParamsV3)
// Run v3 for 5000 epochs
for i := 0; i < 5000; i++ {
require.NoError(t, sim.Tick())
epoch := sim.GetVM().GetEpoch()
if epoch%100 == 0 {
stateTree, err := states.LoadTree(sim.GetVM().Store(), sim.GetVM().StateRoot())
require.NoError(t, err)
totalBalance, err := sim.GetVM().GetTotalActorBalance()
require.NoError(t, err)
acc, err := states.CheckStateInvariants(stateTree, totalBalance, sim.GetVM().GetEpoch()-1)
require.NoError(t, err)
require.True(t, acc.IsEmpty(), strings.Join(acc.Messages(), "\n"))
require.NoError(t, sim.GetVM().GetState(builtin.StoragePowerActorAddr, &pwrSt))
// assume each sector is 32Gb
sectorCount := big.Div(pwrSt.TotalBytesCommitted, big.NewInt(32<<30))
fmt.Printf("Power at %d: raw: %v cmtRaw: %v cmtSecs: %d cnsMnrs: %d avgWins: %.3f msgs: %d\n",
epoch, pwrSt.TotalRawBytePower, pwrSt.TotalBytesCommitted, sectorCount.Uint64(),
pwrSt.MinerAboveMinPowerCount, float64(sim.WinCount)/float64(epoch), sim.MessageCount)
}
}
}
func TestCommitAndCheckReadWriteStats(t *testing.T) {
t.Skip("this is slow")
ctx := context.Background()
initialBalance := big.Mul(big.NewInt(1e8), big.NewInt(1e18))
cumulativeStats := make(vm_test.StatsByCall)
minerCount := 10
clientCount := 9
// set up sim
rnd := rand.New(rand.NewSource(42))
sim := agent.NewSim(ctx, t, newBlockStore, agent.SimConfig{
Seed: rnd.Int63(),
CheckpointEpochs: 1000,
})
// create miners
workerAccounts := vm_test.CreateAccounts(ctx, t, getV3VM(t, sim), minerCount, initialBalance, rnd.Int63())
sim.AddAgent(agent.NewMinerGenerator(
workerAccounts,
agent.MinerAgentConfig{
PrecommitRate: 2.0,
FaultRate: 0.00001,
RecoveryRate: 0.0001,
UpgradeSectors: true,
ProofType: abi.RegisteredSealProof_StackedDrg32GiBV1_1,
StartingBalance: big.Div(initialBalance, big.NewInt(2)),
MinMarketBalance: big.NewInt(1e18),
MaxMarketBalance: big.NewInt(2e18),
},
1.0, // create miner probability of 1 means a new miner is created every tick
rnd.Int63(),
))
clientAccounts := vm_test.CreateAccounts(ctx, t, getV3VM(t, sim), clientCount, initialBalance, rnd.Int63())
dealAgents := agent.AddDealClientsForAccounts(sim, clientAccounts, rnd.Int63(), agent.DealClientConfig{
DealRate: .05,
MinPieceSize: 1 << 29,
MaxPieceSize: 32 << 30,
MinStoragePrice: big.Zero(),
MaxStoragePrice: abi.NewTokenAmount(200_000_000),
MinMarketBalance: big.NewInt(1e18),
MaxMarketBalance: big.NewInt(2e18),
})
var pwrSt power.State
for i := 0; i < 20_000; i++ {
require.NoError(t, sim.Tick())
epoch := sim.GetVM().GetEpoch()
if epoch%100 == 0 {
// compute number of deals
deals := 0
for _, da := range dealAgents {
deals += da.DealCount
}
require.NoError(t, sim.GetVM().GetState(builtin.StoragePowerActorAddr, &pwrSt))
// assume each sector is 32Gb
sectorCount := big.Div(pwrSt.TotalBytesCommitted, big.NewInt(32<<30))
fmt.Printf("Power at %d: raw: %v cmtRaw: %v cmtSecs: %d msgs: %d deals: %d gets: %d puts: %d write bytes: %d read bytes: %d\n",
epoch, pwrSt.TotalRawBytePower, pwrSt.TotalBytesCommitted, sectorCount.Uint64(),
sim.MessageCount, deals, getV3VM(t, sim).StoreReads(), getV3VM(t, sim).StoreWrites(),
getV3VM(t, sim).StoreReadBytes(), getV3VM(t, sim).StoreWriteBytes())
}
cumulativeStats.MergeAllStats(sim.GetCallStats())
if sim.GetVM().GetEpoch()%1000 == 0 {
for method, stats := range cumulativeStats {
printCallStats(method, stats, "")
}
cumulativeStats = make(vm_test.StatsByCall)
}
}
}
func TestCreateDeals(t *testing.T) {
t.Skip("this is slow")
ctx := context.Background()
initialBalance := big.Mul(big.NewInt(1e9), big.NewInt(1e18))
minerCount := 3
clientCount := 9
// set up sim
rnd := rand.New(rand.NewSource(42))
sim := agent.NewSim(ctx, t, newBlockStore, agent.SimConfig{Seed: rnd.Int63()})
// create miners
workerAccounts := vm_test.CreateAccounts(ctx, t, getV3VM(t, sim), minerCount, initialBalance, rnd.Int63())
sim.AddAgent(agent.NewMinerGenerator(
workerAccounts,
agent.MinerAgentConfig{
PrecommitRate: 0.1,
FaultRate: 0.0001,
RecoveryRate: 0.0001,
ProofType: abi.RegisteredSealProof_StackedDrg32GiBV1_1,
StartingBalance: big.Div(initialBalance, big.NewInt(2)),
MinMarketBalance: big.NewInt(1e18),
MaxMarketBalance: big.NewInt(2e18),
},
1.0, // create miner probability of 1 means a new miner is created every tick
rnd.Int63(),
))
clientAccounts := vm_test.CreateAccounts(ctx, t, getV3VM(t, sim), clientCount, initialBalance, rnd.Int63())
dealAgents := agent.AddDealClientsForAccounts(sim, clientAccounts, rnd.Int63(), agent.DealClientConfig{
DealRate: .01,
MinPieceSize: 1 << 29,
MaxPieceSize: 32 << 30,
MinStoragePrice: big.Zero(),
MaxStoragePrice: abi.NewTokenAmount(200_000_000),
MinMarketBalance: big.NewInt(1e18),
MaxMarketBalance: big.NewInt(2e18),
})
var pwrSt power.State
for i := 0; i < 100_000; i++ {
require.NoError(t, sim.Tick())
epoch := sim.GetVM().GetEpoch()
if epoch%100 == 0 {
stateTree, err := getV3VM(t, sim).GetStateTree()
require.NoError(t, err)
totalBalance, err := getV3VM(t, sim).GetTotalActorBalance()
require.NoError(t, err)
acc, err := states.CheckStateInvariants(stateTree, totalBalance, sim.GetVM().GetEpoch()-1)
require.NoError(t, err)
require.True(t, acc.IsEmpty(), strings.Join(acc.Messages(), "\n"))
require.NoError(t, sim.GetVM().GetState(builtin.StoragePowerActorAddr, &pwrSt))
// assume each sector is 32Gb
sectorCount := big.Div(pwrSt.TotalBytesCommitted, big.NewInt(32<<30))
// compute number of deals
deals := 0
for _, da := range dealAgents {
deals += da.DealCount
}
fmt.Printf("Power at %d: raw: %v cmtRaw: %v cmtSecs: %d cnsMnrs: %d avgWins: %.3f msgs: %d deals: %d\n",
epoch, pwrSt.TotalRawBytePower, pwrSt.TotalBytesCommitted, sectorCount.Uint64(),
pwrSt.MinerAboveMinPowerCount, float64(sim.WinCount)/float64(epoch), sim.MessageCount, deals)
}
}
}
func TestCCUpgrades(t *testing.T) {
t.Skip("this is slow")
ctx := context.Background()
initialBalance := big.Mul(big.NewInt(1e10), big.NewInt(1e18))
minerCount := 10
clientCount := 9
// set up sim
rnd := rand.New(rand.NewSource(42))
sim := agent.NewSim(ctx, t, newBlockStore, agent.SimConfig{Seed: rnd.Int63()})
// create miners
workerAccounts := vm_test.CreateAccounts(ctx, t, getV3VM(t, sim), minerCount, initialBalance, rnd.Int63())
sim.AddAgent(agent.NewMinerGenerator(
workerAccounts,
agent.MinerAgentConfig{
PrecommitRate: 2.0,
FaultRate: 0.00001,
RecoveryRate: 0.0001,
UpgradeSectors: true,
ProofType: abi.RegisteredSealProof_StackedDrg32GiBV1_1,
StartingBalance: big.Div(initialBalance, big.NewInt(2)),
MinMarketBalance: big.NewInt(1e18),
MaxMarketBalance: big.NewInt(2e18),
},
1.0, // create miner probability of 1 means a new miner is created every tick
rnd.Int63(),
))
clientAccounts := vm_test.CreateAccounts(ctx, t, getV3VM(t, sim), clientCount, initialBalance, rnd.Int63())
agent.AddDealClientsForAccounts(sim, clientAccounts, rnd.Int63(), agent.DealClientConfig{
DealRate: .01,
MinPieceSize: 1 << 29,
MaxPieceSize: 32 << 30,
MinStoragePrice: big.Zero(),
MaxStoragePrice: abi.NewTokenAmount(200_000_000),
MinMarketBalance: big.NewInt(1e18),
MaxMarketBalance: big.NewInt(2e18),
})
var pwrSt power.State
for i := 0; i < 100_000; i++ {
require.NoError(t, sim.Tick())
epoch := sim.GetVM().GetEpoch()
if epoch%100 == 0 {
stateTree, err := getV3VM(t, sim).GetStateTree()
require.NoError(t, err)
totalBalance, err := getV3VM(t, sim).GetTotalActorBalance()
require.NoError(t, err)
acc, err := states.CheckStateInvariants(stateTree, totalBalance, sim.GetVM().GetEpoch()-1)
require.NoError(t, err)
require.True(t, acc.IsEmpty(), strings.Join(acc.Messages(), "\n"))
require.NoError(t, sim.GetVM().GetState(builtin.StoragePowerActorAddr, &pwrSt))
// assume each sector is 32Gb
sectorCount := big.Div(pwrSt.TotalBytesCommitted, big.NewInt(32<<30))
// compute stats
deals := 0
upgrades := uint64(0)
for _, a := range sim.Agents {
switch agnt := a.(type) {
case *agent.MinerAgent:
upgrades += agnt.UpgradedSectors
case *agent.DealClientAgent:
deals += agnt.DealCount
}
}
// compute upgrades
fmt.Printf("Power at %d: raw: %v cmtRaw: %v cmtSecs: %d msgs: %d deals: %d upgrades: %d\n",
epoch, pwrSt.TotalRawBytePower, pwrSt.TotalBytesCommitted, sectorCount.Uint64(),
sim.MessageCount, deals, upgrades)
}
}
}
func newBlockStore() cbor.IpldBlockstore {
return ipld.NewBlockStoreInMemory()
}
func printCallStats(method vm_test.MethodKey, stats *vm_test.CallStats, indent string) { // nolint:unused
fmt.Printf("%s%v:%d: calls: %d gets: %d puts: %d read: %d written: %d avg gets: %.2f, avg puts: %.2f\n",
indent, builtin.ActorNameByCode(method.Code), method.Method, stats.Calls, stats.Reads, stats.Writes,
stats.ReadBytes, stats.WriteBytes, float32(stats.Reads)/float32(stats.Calls),
float32(stats.Writes)/float32(stats.Calls))
if stats.SubStats == nil {
return
}
for m, s := range stats.SubStats {
printCallStats(m, s, indent+" ")
}
}
func getV3VM(t *testing.T, sim *agent.Sim) *vm_test.VM {
vm, ok := sim.GetVM().(*vm_test.VM)
require.True(t, ok)
return vm
}
|
package main
import (
"github.com/Shopify/sarama"
"log"
"os"
"os/signal"
)
func main() {
config := sarama.NewConfig()
config.Consumer.Return.Errors = true
client, err := sarama.NewClient([]string{"localhost:9192", "localhost:9292", "localhost:9392"}, config)
defer client.Close()
if err != nil {
panic(err)
}
consumer, err := sarama.NewConsumerFromClient(client)
defer consumer.Close()
if err != nil {
panic(err)
}
// get partitionId list
partitions, err := consumer.Partitions("my_topic")
if err != nil {
panic(err)
}
for _, partitionId := range partitions {
// create partitionConsumer for every partitionId
partitionConsumer, err := consumer.ConsumePartition("my_topic", partitionId, sarama.OffsetNewest)
if err != nil {
panic(err)
}
go func(pc *sarama.PartitionConsumer) {
defer (*pc).Close()
// block
for message := range (*pc).Messages() {
value := string(message.Value)
log.Printf("Partitionid: %d; offset:%d, value: %s\n", message.Partition, message.Offset, value)
}
}(&partitionConsumer)
}
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
select {
case <-signals:
}
}
|
package util
import (
"fmt"
"reflect"
)
type Animal interface {
MakeSound() string
}
type Dog struct{}
func (d *Dog) MakeSound() string {
return "Bark"
}
type Cat struct {
}
func (c Cat) MakeSound() string {
return "Meow"
}
func IsNil(i interface{}) bool {
fmt.Println(i, i == nil, reflect.ValueOf(i).IsNil())
return i == nil || reflect.ValueOf(i).IsNil()
}
func IsNilFixed(i interface{}) bool {
if i == nil {
return true
}
switch reflect.TypeOf(i).Kind() {
case reflect.Ptr, reflect.Map, reflect.Slice, reflect.Chan, reflect.Array:
return reflect.ValueOf(i).IsNil()
}
return false
}
func IsNilBetter(i Animal) bool {
var ret bool
switch i.(type) {
case *Dog:
v := i.(*Dog)
ret = v == nil
case Cat:
ret = false
}
return ret
}
|
package Gophp
import (
"os"
"path/filepath"
)
// FileExists file_exists()
func FileExists(filename string) bool {
_, err := os.Stat(filename)
if err != nil && os.IsNotExist(err) {
return false
}
return true
}
// IsFile is_file()
func IsFile(filename string) bool {
_, err := os.Stat(filename)
if err != nil && os.IsNotExist(err) {
return false
}
return true
}
// IsDir is_dir()
func IsDir(filename string) (bool, error) {
fd, err := os.Stat(filename)
if err != nil {
return false, err
}
fm := fd.Mode()
return fm.IsDir(), nil
}
// FileSize filesize()
func FileSize(filename string) (int64, error) {
info, err := os.Stat(filename)
if err != nil && os.IsNotExist(err) {
return 0, err
}
return info.Size(), nil
}
// Unlink unlink()
func Unlink(filename string) error {
return os.Remove(filename)
}
// Touch touch()
func Touch(filename string) (bool, error) {
fd, err := os.OpenFile(filename, os.O_RDONLY|os.O_CREATE, 0666)
if err != nil {
return false, err
}
fd.Close()
return true, nil
}
// Mkdir mkdir()
func Mkdir(filename string, mode os.FileMode) error {
return os.Mkdir(filename, mode)
}
//创建目录
func Mkdirs(dir string) error {
if FileExists(dir) {
return nil
}
err := os.MkdirAll(dir, os.ModePerm)
if err != nil {
return err
}
return nil
}
// Getcwd getcwd()
func Getcwd() (string, error) {
dir, err := os.Getwd()
return dir, err
}
// Realpath realpath()
func Realpath(path string) (string, error) {
return filepath.Abs(path)
}
// Basename basename()
func Basename(path string) string {
return filepath.Base(path)
}
// Filemtime filemtime()
func Filemtime(filename string) (int64, error) {
fd, err := os.Open(filename)
if err != nil {
return 0, err
}
defer fd.Close()
fileinfo, err := fd.Stat()
if err != nil {
return 0, err
}
return fileinfo.ModTime().Unix(), nil
}
|
package util_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"opendev.org/airship/airshipctl/pkg/util"
)
func TestReadYAMLFile(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
var actual map[string]interface{}
err := util.ReadYAMLFile("testdata/test.yaml", &actual)
require.NoError(err, "Error while reading YAML")
actualString := actual["testString"]
expectedString := "test"
assert.Equal(expectedString, actualString)
}
|
package versions
import (
"fmt"
"strings"
"github.com/blang/semver/v4"
"github.com/mmcdole/gofeed"
)
func LatestVersion(repo string, currentVersion semver.Version, upgradeMajor, includePreReleases bool) (string, error) {
fp := gofeed.NewParser()
feed, err := fp.ParseURL(repo + "/releases.atom")
if err != nil {
return "", err
}
if len(feed.Items) == 0 {
return "", fmt.Errorf("no entry in releases feed")
}
for _, item := range feed.Items {
IDElements := strings.Split(item.GUID, "/")
if len(IDElements) < 3 {
continue // entry is malformed, skip it
}
v, err := semver.ParseTolerant(IDElements[2])
if err != nil {
continue // this is not a semver, skip it
}
if v.Pre != nil && !includePreReleases {
continue // this is a pre-release, skip it
}
if v.Major > currentVersion.Major && !upgradeMajor {
continue // this is a new major version, skip ip
}
return fmt.Sprintf("v%s", v.String()), nil
}
return "", fmt.Errorf("no parseable version found in releases feed")
}
|
package util
import "fmt"
func BuildError(info string, err error) string {
return fmt.Sprintf("%s, 错误信息: [ %s ]", info, err)
}
|
package mobile
import (
"fmt"
"net/http"
"os"
"strings"
"testing"
"github.com/golang/protobuf/proto"
icid "github.com/ipfs/go-cid"
"github.com/libp2p/go-libp2p-core/peerstore"
"github.com/segmentio/ksuid"
"github.com/textileio/go-textile/core"
"github.com/textileio/go-textile/ipfs"
"github.com/textileio/go-textile/pb"
)
var cafesTestVars = struct {
mobilePath string
mobile *Mobile
cafePath string
cafe *core.Textile
cafeApiPort string
}{
mobilePath: "./testdata/.textile3",
cafePath: "./testdata/.textile4",
cafeApiPort: "5000",
}
func TestMobile_SetupCafes(t *testing.T) {
var err error
cafesTestVars.mobile, err = createAndStartPeer(InitConfig{
RepoPath: cafesTestVars.mobilePath,
Debug: true,
}, true, &testHandler{}, &testMessenger{})
if err != nil {
t.Fatal(err)
}
cafesTestVars.cafe, err = core.CreateAndStartPeer(core.InitConfig{
RepoPath: cafesTestVars.cafePath,
Debug: true,
SwarmPorts: "4001",
CafeApiAddr: "0.0.0.0:" + cafesTestVars.cafeApiPort,
CafeURL: "http://127.0.0.1:" + cafesTestVars.cafeApiPort,
CafeOpen: true,
}, true)
if err != nil {
t.Fatal(err)
}
}
func TestMobile_RegisterCafe(t *testing.T) {
token, err := cafesTestVars.cafe.CreateCafeToken("", true)
if err != nil {
t.Fatal(err)
}
ok, err := cafesTestVars.cafe.ValidateCafeToken(token)
if !ok || err != nil {
t.Fatal(err)
}
// register with cafe
cafeID := cafesTestVars.cafe.Ipfs().Identity
cafesTestVars.mobile.node.Ipfs().Peerstore.AddAddrs(
cafeID, cafesTestVars.cafe.Ipfs().PeerHost.Addrs(), peerstore.PermanentAddrTTL)
err = cafesTestVars.mobile.registerCafe(cafeID.Pretty(), token)
if err != nil {
t.Fatal(err)
}
// add some data
err = addTestData(cafesTestVars.mobile)
if err != nil {
t.Fatal(err)
}
}
func TestMobile_HandleCafeRequests(t *testing.T) {
// manually flush until empty
err := flush(10)
if err != nil {
t.Fatal(err)
}
m := cafesTestVars.mobile
c := cafesTestVars.cafe
err = m.node.Datastore().CafeRequests().DeleteCompleteSyncGroups()
if err != nil {
t.Fatal(err)
}
// ensure all requests have been deleted
cnt := m.node.Datastore().CafeRequests().Count(-1)
if cnt != 0 {
t.Fatalf("expected all requests to be handled, got %d", cnt)
}
// check if blocks are pinned
var blocks []string
var datas []string
list := m.node.Blocks("", -1, "")
for _, b := range list.Items {
blocks = append(blocks, b.Id)
if b.Type == pb.Block_FILES {
datas = append(datas, b.Data)
}
}
missingBlockPins, err := ipfs.NotPinned(c.Ipfs(), blocks)
if err != nil {
t.Fatal(err)
}
if len(missingBlockPins) != 0 {
var strs []string
for _, id := range missingBlockPins {
strs = append(strs, id.Hash().B58String())
}
t.Fatalf("blocks not pinned: %s", strings.Join(strs, ", "))
}
// check if datas are pinned
missingDataPins, err := ipfs.NotPinned(c.Ipfs(), datas)
if err != nil {
t.Fatal(err)
}
if len(missingDataPins) != 0 {
var strs []string
for _, id := range missingDataPins {
strs = append(strs, id.Hash().B58String())
}
t.Fatalf("datas not pinned: %s", strings.Join(strs, ", "))
}
// try unpinning data
if len(datas) > 0 {
dec, err := icid.Decode(datas[0])
if err != nil {
t.Fatal(err)
}
err = ipfs.UnpinCid(c.Ipfs(), dec, true)
if err != nil {
t.Fatal(err)
}
not, err := ipfs.NotPinned(c.Ipfs(), []string{datas[0]})
if err != nil {
t.Fatal(err)
}
if len(not) == 0 || not[0].Hash().B58String() != datas[0] {
t.Fatal("data was not recursively unpinned")
}
}
}
func TestMobile_TeardownCafes(t *testing.T) {
_ = cafesTestVars.mobile.Stop()
_ = cafesTestVars.cafe.Stop()
cafesTestVars.mobile = nil
cafesTestVars.cafe = nil
}
func addTestData(m *Mobile) error {
thrd, err := addTestThread(m, &pb.AddThreadConfig{
Key: ksuid.New().String(),
Name: "test",
Schema: &pb.AddThreadConfig_Schema{
Preset: pb.AddThreadConfig_Schema_MEDIA,
},
Type: pb.Thread_PRIVATE,
Sharing: pb.Thread_INVITE_ONLY,
})
if err != nil {
return err
}
_, err = m.addFiles([]string{"../mill/testdata/image.jpeg"}, thrd.Id, "hi")
if err != nil {
return err
}
_, err = m.AddMessage(thrd.Id, "hi")
if err != nil {
return err
}
hash, err := m.addFiles([]string{"../mill/testdata/image.png"}, thrd.Id, "hi")
if err != nil {
return err
}
_, err = m.AddComment(hash.B58String(), "nice")
if err != nil {
return err
}
hash, err = m.addFiles([]string{"../mill/testdata/image.jpeg", "../mill/testdata/image.png"}, thrd.Id, "hi")
if err != nil {
return err
}
_, err = m.AddLike(hash.B58String())
if err != nil {
return err
}
_, err = m.AddMessage(thrd.Id, "bye")
if err != nil {
return err
}
return nil
}
/*
Handle the request queue.
1. List some requests
2. Write the HTTP request for each
3. Handle them (set to pending, send to cafe)
4. Delete failed (reties not handled here)
5. Set successful to complete
*/
func flushCafeRequests(limit int) (int, error) {
var count int
res, err := cafesTestVars.mobile.CafeRequests(limit)
if err != nil {
return count, err
}
ids := new(pb.Strings)
err = proto.Unmarshal(res, ids)
if err != nil {
return count, err
}
count = len(ids.Values)
// write the req for each group
reqs := make(map[string]*pb.CafeHTTPRequest)
for _, g := range ids.Values {
res, err = cafesTestVars.mobile.writeCafeRequest(g)
if err != nil {
return count, err
}
req := new(pb.CafeHTTPRequest)
err = proto.Unmarshal(res, req)
if err != nil {
return count, err
}
reqs[g] = req
}
// mark each as pending (new loops for clarity)
for g := range reqs {
err = cafesTestVars.mobile.CafeRequestPending(g)
if err != nil {
return count, err
}
}
// handle each
for g, req := range reqs {
res, err := handleReq(req)
if err != nil {
return count, err
}
if res.StatusCode >= 300 {
reason := fmt.Sprintf("got bad status: %d\n", res.StatusCode)
fmt.Println(reason)
err = cafesTestVars.mobile.FailCafeRequest(g, reason)
} else {
err = cafesTestVars.mobile.CompleteCafeRequest(g)
}
if err != nil {
return count, err
}
res.Body.Close()
}
return count, nil
}
func flush(batchSize int) error {
count, err := flushCafeRequests(batchSize)
if err != nil {
return err
}
if count > 0 {
return flush(batchSize)
}
return nil
}
func printSyncGroupStatus(status *pb.CafeSyncGroupStatus) {
fmt.Println(">>> " + status.Id)
fmt.Println(fmt.Sprintf("num. pending: %d", status.NumPending))
fmt.Println(fmt.Sprintf("num. complete: %d", status.NumComplete))
fmt.Println(fmt.Sprintf("num. total: %d", status.NumTotal))
fmt.Println(fmt.Sprintf("size pending: %d", status.SizePending))
fmt.Println(fmt.Sprintf("size complete: %d", status.SizeComplete))
fmt.Println(fmt.Sprintf("size total: %d", status.SizeTotal))
fmt.Println("<<<")
}
func handleReq(r *pb.CafeHTTPRequest) (*http.Response, error) {
f, err := os.Open(r.Path)
if err != nil {
return nil, err
}
defer f.Close()
req, err := http.NewRequest(r.Type.String(), r.Url, f)
if err != nil {
return nil, err
}
for k, v := range r.Headers {
req.Header.Set(k, v)
}
client := &http.Client{}
return client.Do(req)
}
|
package main
import "syscall"
func getSyscall(r *syscall.PtraceRegs) int {
return int(r.Orig_eax)
}
func getArgAddr(r *syscall.PtraceRegs, argnum int) uintptr {
switch argnum {
case 0:
return uintptr(r.Ebx)
case 1:
return uintptr(r.Ecx)
case 2:
return uintptr(r.Edx)
}
return 0
}
func getArgInt(r *syscall.PtraceRegs, argnum int) int {
switch argnum {
case 0:
return int(r.Ebx)
case 1:
return int(r.Ecx)
case 2:
return int(r.Edx)
}
return 0
}
var syscallTypes = map[int]int{
syscall.SYS_ACCESS: SyscallPath,
syscall.SYS_CHDIR: SyscallPath,
syscall.SYS_CREAT: SyscallPath,
syscall.SYS_EXECVE: SyscallPath,
syscall.SYS_LCHOWN: SyscallPath,
syscall.SYS_LINK: SyscallPath,
syscall.SYS_LSTAT: SyscallPath,
syscall.SYS_MKDIR: SyscallPath,
syscall.SYS_OPEN: SyscallPath,
syscall.SYS_READLINK: SyscallPath,
syscall.SYS_RMDIR: SyscallPath,
syscall.SYS_STAT: SyscallPath,
syscall.SYS_STATFS: SyscallPath,
syscall.SYS_SYMLINK: SyscallPath,
syscall.SYS_TRUNCATE: SyscallPath,
syscall.SYS_UNLINK: SyscallPath,
syscall.SYS_UTIMES: SyscallPath,
syscall.SYS_FCHDIR: SyscallFile,
syscall.SYS_FCNTL: SyscallFile,
syscall.SYS_FACCESSAT: SyscallFilePath,
syscall.SYS_FCHMODAT: SyscallFilePath,
syscall.SYS_FCHOWNAT: SyscallFilePath,
syscall.SYS_LINKAT: SyscallFilePath,
syscall.SYS_MKDIRAT: SyscallFilePath,
syscall.SYS_MKNODAT: SyscallFilePath,
syscall.SYS_OPENAT: SyscallFilePath,
syscall.SYS_READLINKAT: SyscallFilePath,
syscall.SYS_UNLINKAT: SyscallFilePath,
}
|
package kubeconfig
import (
"strconv"
"sync"
"github.com/pkg/errors"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/clientcmd/api"
)
var loadOnceMutext sync.Mutex
var loadOnce sync.Once
var loadedConfig clientcmd.ClientConfig
// AuthCommand is the name of the command used to get auth token for kube-context of Spaces
const AuthCommand = "devspace"
// NewConfig loads a new kube config
func (l *loader) NewConfig() clientcmd.ClientConfig {
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(clientcmd.NewDefaultClientConfigLoadingRules(), &clientcmd.ConfigOverrides{})
}
// LoadConfig loads the kube config with the default loading rules
func (l *loader) LoadConfig() clientcmd.ClientConfig {
loadOnceMutext.Lock()
defer loadOnceMutext.Unlock()
loadOnce.Do(func() {
loadedConfig = l.NewConfig()
})
return loadedConfig
}
// LoadRawConfig loads the raw kube config with the default loading rules
func (l *loader) LoadRawConfig() (*api.Config, error) {
config, err := l.LoadConfig().RawConfig()
if err != nil {
return nil, err
}
return &config, nil
}
// GetCurrentContext retrieves the current kube context
func (l *loader) GetCurrentContext() (string, error) {
config, err := l.LoadRawConfig()
if err != nil {
return "", err
}
return config.CurrentContext, nil
}
// SaveConfig writes the kube config back to the specified filename
func (l *loader) SaveConfig(config *api.Config) error {
loadOnceMutext.Lock()
defer loadOnceMutext.Unlock()
err := clientcmd.ModifyConfig(clientcmd.NewDefaultClientConfigLoadingRules(), *config, false)
if err != nil {
return err
}
// Since the config has changed now we reset the loadOnce
loadOnce = sync.Once{}
return nil
}
// IsCloudSpace returns true of this context belongs to a Space created by DevSpace Cloud
func (l *loader) IsCloudSpace(context string) (bool, error) {
kubeConfig, err := l.LoadRawConfig()
if err != nil {
return false, err
}
// Get AuthInfo for context
authInfo, err := getAuthInfo(kubeConfig, context)
if err != nil {
return false, errors.Errorf("Unable to get AuthInfo for kube-context: %v", err)
}
return authInfo.Exec != nil && authInfo.Exec.Command == AuthCommand, nil
}
// GetSpaceID returns the id of the Space and the cloud provider URL that belongs to the context with this name
func (l *loader) GetSpaceID(context string) (int, string, error) {
kubeConfig, err := l.LoadRawConfig()
if err != nil {
return 0, "", err
}
// Get AuthInfo for context
authInfo, err := getAuthInfo(kubeConfig, context)
if err != nil {
return 0, "", errors.Errorf("Unable to get AuthInfo for kube-context: %v", err)
}
if authInfo.Exec == nil || authInfo.Exec.Command != AuthCommand {
return 0, "", errors.Errorf("Kube-context does not belong to a Space")
}
if len(authInfo.Exec.Args) < 6 {
return 0, "", errors.Errorf("Kube-context is misconfigured. Please run `devspace use space [SPACE_NAME]` to setup a new context")
}
spaceID, err := strconv.Atoi(authInfo.Exec.Args[5])
return spaceID, authInfo.Exec.Args[3], err
}
// getAuthInfo returns the AuthInfo of the context with this name
func getAuthInfo(kubeConfig *api.Config, context string) (*api.AuthInfo, error) {
// Get context
contextRaw, ok := kubeConfig.Contexts[context]
if !ok {
return nil, errors.Errorf("Unable to find kube-context '%s' in kube-config file", context)
}
// Get AuthInfo for context
authInfo, ok := kubeConfig.AuthInfos[contextRaw.AuthInfo]
if !ok {
return nil, errors.Errorf("Unable to find user information for context in kube-config file")
}
return authInfo, nil
}
// DeleteKubeContext removes the specified devspace id from the kube context if it exists
func (l *loader) DeleteKubeContext(kubeConfig *api.Config, kubeContext string) error {
// Get context
contextRaw, ok := kubeConfig.Contexts[kubeContext]
if !ok {
// return errors.Errorf("Unable to find current kube-context '%s' in kube-config file", kubeContext)
// This is debatable but usually we don't care when the context is not there
return nil
}
// Remove context
delete(kubeConfig.Contexts, kubeContext)
removeAuthInfo := true
removeCluster := true
// Check if AuthInfo or Cluster is used by any other context
for name, ctx := range kubeConfig.Contexts {
if name != kubeContext && ctx.AuthInfo == contextRaw.AuthInfo {
removeAuthInfo = false
}
if name != kubeContext && ctx.Cluster == contextRaw.Cluster {
removeCluster = false
}
}
// Remove AuthInfo if not used by any other context
if removeAuthInfo {
delete(kubeConfig.AuthInfos, contextRaw.AuthInfo)
}
// Remove Cluster if not used by any other context
if removeCluster {
delete(kubeConfig.Clusters, contextRaw.Cluster)
}
if kubeConfig.CurrentContext == kubeContext {
kubeConfig.CurrentContext = ""
if len(kubeConfig.Contexts) > 0 {
for context, contextObj := range kubeConfig.Contexts {
if contextObj != nil {
kubeConfig.CurrentContext = context
break
}
}
}
}
return nil
}
|
// Based on text/template/parse/lex.go
package pydict
import (
"fmt"
"strings"
"unicode/utf8"
)
var _ = fmt.Println
const eof = -1
const (
itemError = iota
itemEOF
itemLeftBrace
itemRightBrace
itemLeftBracket
itemRightBracket
itemString
itemComma
itemColon
)
type itemType int
type item struct {
iType itemType
value string
}
type stateFunc func(*lexer) stateFunc
type lexer struct {
input string
start int
width int
pos int
state stateFunc
out chan item
}
func lex(input string) *lexer {
out := make(chan item)
l := &lexer{input, 0, 0, 0, nil, out}
go l.run()
return l
}
func (l *lexer) next() rune {
if l.pos >= len(l.input) {
return eof
}
r, w := utf8.DecodeRuneInString(l.input[l.pos:])
l.width = w
l.pos += w
return r
}
func (l *lexer) peek() rune {
r := l.next()
l.backup()
return r
}
func (l *lexer) backup() {
l.pos -= l.width
}
func (l *lexer) emit(i itemType) {
l.out <- item{i, l.input[l.start:l.pos]}
l.start = l.pos
}
func (l *lexer) run() {
for l.state = startState; l.state != nil; {
l.state = l.state(l)
}
}
func (l *lexer) nextItem() item {
i := <-l.out
return i
}
func startState(l *lexer) stateFunc {
for {
r := l.next()
if r == eof {
break
}
switch r {
case '{':
l.emit(itemLeftBrace)
case '}':
l.emit(itemRightBrace)
case '[':
l.emit(itemLeftBracket)
case ']':
l.emit(itemRightBracket)
case ',':
l.emit(itemComma)
case ':':
l.emit(itemColon)
case '\'':
return stringState
case '#':
return commentState
default:
l.start += 1
}
}
l.emit(itemEOF)
return nil
}
// ugly.......
func stringState(l *lexer) stateFunc {
i := strings.Index(l.input[l.pos:], "'")
if i < 0 {
l.emit(itemError)
l.pos = len(l.input)
} else {
l.start += 1
l.pos += i
l.emit(itemString)
l.start += 1
l.pos += 1
}
return startState
}
func commentState(l *lexer) stateFunc {
i := strings.Index(l.input[l.pos:], "\n")
if i < 0 {
l.pos = len(l.input)
} else {
l.start = i
l.pos = i
}
return startState
}
|
package entity
// List struct (Model)
type List struct {
ID string `json:"ID"`
UID string `json:"UID"`
Name string `json:"Name"`
}
// Task struct (Model)
type Task struct {
ID string `json:"ID"`
ListID string `json:"ListID"`
UID string `json:"UID"`
Name string `json:"Name"`
}
|
package main
import (
"fmt"
"unicode"
"bufio"
"os"
)
func to_celsius(f float64) float64 { return (f - 32) * 5/9 }
func to_fahrenheit(c float64) float64 { return (c * 9/5) + 32 }
func main() {
fmt.Println("Press C to convert from Fahrenheit to Celsius.")
fmt.Println("Press F to convert from Celsius to Fahrenheit.")
fmt.Print("Your choice: ")
reader := bufio.NewReader(os.Stdin)
choice, _, _ := reader.ReadRune() // error handling? lol
var temp float64
switch unicode.ToLower(choice) {
case 'c':
fmt.Print("Please enter the temperature in Fahrenheit: ")
fmt.Scanf("%f", &temp)
fmt.Printf("The temperature in Celsius is %f\n", to_celsius(temp))
case 'f':
fmt.Print("Please enter the temperature in Celsius: ")
fmt.Scanf("%f", &temp)
fmt.Printf("The temperature in Fahrenheit is %f\n", to_fahrenheit(temp))
default:
fmt.Println("Not a valid selection")
}
}
|
package cli
import (
"context"
"fmt"
"github.com/evan-buss/openbooks/core"
"github.com/evan-buss/openbooks/irc"
)
type Config struct {
UserName string // Username to use when connecting to IRC
Log bool // True if IRC messages should be logged
Dir string
Server string
irc *irc.Conn
}
// StartInteractive instantiates the OpenBooks CLI interface
func StartInteractive(config Config) {
fmt.Println("=======================================")
fmt.Println(" Welcome to OpenBooks ")
fmt.Println("=======================================")
conn := instantiate(config)
config.irc = conn
ctx, cancel := context.WithCancel(context.Background())
registerShutdown(conn, cancel)
handler := fullHandler(config)
if config.Log {
file := config.setupLogger(handler)
defer file.Close()
}
go core.StartReader(ctx, conn, handler)
terminalMenu(conn)
<-ctx.Done()
}
func StartDownload(config Config, download string) {
conn := instantiate(config)
defer conn.Close()
ctx, cancel := context.WithCancel(context.Background())
handler := core.EventHandler{}
handler[core.BookResult] = func(text string) {
fmt.Printf("%sReceived file response.\n", clearLine)
config.downloadHandler(text)
cancel()
}
if config.Log {
file := config.setupLogger(handler)
defer file.Close()
}
fmt.Printf("Sending download request.")
go core.StartReader(ctx, conn, handler)
core.DownloadBook(conn, download)
fmt.Printf("%sSent download request.", clearLine)
fmt.Printf("Waiting for file response.")
registerShutdown(conn, cancel)
<-ctx.Done()
}
func StartSearch(config Config, query string) {
conn := instantiate(config)
defer conn.Close()
ctx, cancel := context.WithCancel(context.Background())
handler := core.EventHandler{}
handler[core.SearchResult] = func(text string) {
fmt.Printf("%sReceived file response.\n", clearLine)
config.searchHandler(text)
cancel()
}
handler[core.MatchesFound] = config.matchesFoundHandler
if config.Log {
file := config.setupLogger(handler)
defer file.Close()
}
fmt.Printf("Sending search request.")
go core.StartReader(ctx, conn, handler)
core.SearchBook(conn, query)
fmt.Printf("%sSent search request.", clearLine)
fmt.Printf("Waiting for file response.")
registerShutdown(conn, cancel)
<-ctx.Done()
}
|
package target
import (
"encoding/json"
"fmt"
)
type TargetResult struct {
Name string `json:"name"`
Options TargetResultOptions `json:"options"`
}
func newTargetResult(name string, options TargetResultOptions) *TargetResult {
return &TargetResult{
Name: name,
Options: options,
}
}
type TargetResultOptions interface {
isTargetResultOptions()
}
type rawTargetResult struct {
Name string `json:"name"`
Options json.RawMessage `json:"options"`
}
func (targetResult *TargetResult) UnmarshalJSON(data []byte) error {
var rawTR rawTargetResult
err := json.Unmarshal(data, &rawTR)
if err != nil {
return err
}
options, err := UnmarshalTargetResultOptions(rawTR.Name, rawTR.Options)
if err != nil {
return err
}
targetResult.Name = rawTR.Name
targetResult.Options = options
return nil
}
func UnmarshalTargetResultOptions(trName string, rawOptions json.RawMessage) (TargetResultOptions, error) {
var options TargetResultOptions
switch trName {
case "org.osbuild.aws":
options = new(AWSTargetResultOptions)
case "org.osbuild.aws.s3":
options = new(AWSS3TargetResultOptions)
case "org.osbuild.gcp":
options = new(GCPTargetResultOptions)
case "org.osbuild.azure.image":
options = new(AzureImageTargetResultOptions)
default:
return nil, fmt.Errorf("Unexpected target result name: %s", trName)
}
err := json.Unmarshal(rawOptions, options)
return options, err
}
|
package database
type TbSchedule struct {
ID uint
IntervalForReading int `gorm:"column:intervalforreading"`
IntervalForEvent int `gorm:"column:intervalforevent"`
}
func (TbSchedule) TableName() string {
return "tb_schedule"
}
|
package log
import (
"io"
stdLog "log"
)
// Отключение логгирования
const NONE = 0
// Система находится в неработоспособном состоянии
const EMERGENCY = 1
// Требуется немедленное реагирование (например, база не доступна)
const ALERT = 2
// Критическая ошибка (что-то не работает, требует исправления)
const CRITICAL = 3
// Ошибка (рантайм, не требующая немедленных действий)
const ERROR = 4
// Предупреждение (необычная ситуация, но не ошибка)
const WARNING = 5
// Важная информация
const NOTICE = 6
// Обычная информация
const INFO = 7
// Детализированная отладочная информация
const DEBUG = 8
const sEMERGENCY = "EMERGENCY"
const sALERT = "ALERT"
const sCRITICAL = "CRITICAL"
const sERROR = "ERROR"
const sWARNING = "WARNING"
const sNOTICE = "NOTICE"
const sINFO = "INFO"
const sDEBUG = "DEBUG"
var log *Logger
type Logger struct {
level uint8
logger *stdLog.Logger
}
func Init(w io.Writer, level uint8) {
log = new(Logger)
log.level = level
log.logger = stdLog.New(w, "", stdLog.LstdFlags)
}
func (logger *Logger) write(level uint8, message *string, v ...interface{}) {
var levelCaption string
switch level {
case NONE:
return
case EMERGENCY:
levelCaption = sEMERGENCY
case ALERT:
levelCaption = sALERT
case CRITICAL:
levelCaption = sCRITICAL
case ERROR:
levelCaption = sERROR
case WARNING:
levelCaption = sWARNING
case NOTICE:
levelCaption = sNOTICE
case INFO:
levelCaption = sINFO
case DEBUG:
levelCaption = sDEBUG
}
logger.logger.Printf("["+levelCaption+"] "+*message, v...)
}
func Emergency(message string, v ...interface{}) {
log.write(EMERGENCY, &message, v...)
}
func Alert(message string, v ...interface{}) {
log.write(ALERT, &message, v...)
}
func Critical(message string, v ...interface{}) {
log.write(CRITICAL, &message, v...)
}
func Error(message string, v ...interface{}) {
log.write(ERROR, &message, v...)
}
func Warning(message string, v ...interface{}) {
log.write(WARNING, &message, v...)
}
func Notice(message string, v ...interface{}) {
log.write(NOTICE, &message, v...)
}
func Info(message string, v ...interface{}) {
log.write(INFO, &message, v...)
}
func Debug(message string, v ...interface{}) {
log.write(DEBUG, &message, v...)
}
|
package main
import (
"fmt"
"log"
"net/http"
"sync"
)
var url = []string{
"https://google.com",
"https://www.twitter.com",
"https://facebook.com",
}
func fetchstatus(w http.ResponseWriter, r *http.Request) {
var wg sync.WaitGroup
// for _, urls := range url {
wg.Add(1)
func() {
resp, err := http.Get("http://google.com")
if err != nil {
fmt.Fprint(w, "%+v", err)
}
fmt.Fprint(w, "%+v", resp)
wg.Done()
}()
//}
wg.Wait()
}
func main() {
fmt.Println("execution started ")
http.HandleFunc("/", fetchstatus)
log.Fatal(http.ListenAndServe(":8080", nil))
fmt.Println("execution ended")
}
|
package movie
type Ne_Movie struct {
//Movie
Title string //片名
PriceCode int //价格代号
}
func (m Ne_Movie) GetCharge(daysRented int) float64 {
result := 0.0
result += float64(daysRented) * float64(3)
return result
}
func (m Ne_Movie) GetPoint(daysRented int) int {
if daysRented > 1 {
return 2
} else {
return 1
}
}
|
package client
import (
"github.com/devopstoday11/tarian/pkg/tarianpb"
"google.golang.org/grpc"
)
func NewConfigClient(serverAddress string, opts ...grpc.DialOption) (tarianpb.ConfigClient, error) {
grpcConn, err := grpc.Dial(serverAddress, opts...)
return tarianpb.NewConfigClient(grpcConn), err
}
func NewEventClient(serverAddress string, opts ...grpc.DialOption) (tarianpb.EventClient, error) {
grpcConn, err := grpc.Dial(serverAddress, opts...)
return tarianpb.NewEventClient(grpcConn), err
}
|
package main
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// 迭代 + 队列 实现层序遍历
func levelOrder(root *TreeNode) [][]int {
if root == nil {
return [][]int{}
}
levelOrderSequence := make([][]int, 0)
queue := make([]*TreeNode, 0)
queue = append(queue, root)
for len(queue) != 0 {
size := len(queue)
nowOrderSequence := make([]int, 0)
for i := 0; i < size; i++ {
top := queue[0]
queue = queue[1:]
nowOrderSequence = append(nowOrderSequence, top.Val)
if top.Left != nil {
queue = append(queue, top.Left)
}
if top.Right != nil {
queue = append(queue, top.Right)
}
}
levelOrderSequence = append(levelOrderSequence, nowOrderSequence)
}
return levelOrderSequence
}
/*
题目链接: https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
*/
|
package config
type channels struct {
Console string `yaml:"console,omitempty"`
Errors string `yaml:"errors,omitempty"`
Logs string `yaml:"logs,omitempty"`
}
type bot struct {
GuildID string `yaml:"guild_id,omitempty"`
Channels channels `yaml:"channels,omitempty"`
Templates string `yaml:"templates,omitempty"`
Log *Log `yaml:"log,omitempty"`
}
|
package talkio
import (
"errors"
"io"
"unicode/utf8"
)
// A StringReader implements the io.StringReader, io.ReaderAt, io.Seeker, io.WriterTo,
// io.ByteScanner, and io.RuneScanner interfaces by reading
// from a string.
type StringReader struct {
s string
i int64 // current reading index
prevRune int // index of previous rune; or < 0
}
// Len returns the number of bytes of the unread portion of the
// string.
func (r *StringReader) Len() int {
if r.i >= int64(len(r.s)) {
return 0
}
return int(int64(len(r.s)) - r.i)
}
// Size returns the original length of the underlying string.
// Size is the number of bytes available for reading via ReadAt.
// The returned value is always the same and is not affected by calls
// to any other method.
func (r *StringReader) Size() int64 { return int64(len(r.s)) }
func (r *StringReader) Read(b []byte) (n int, err error) {
if r.i >= int64(len(r.s)) {
return 0, io.EOF
}
r.prevRune = -1
n = copy(b, r.s[r.i:])
r.i += int64(n)
return
}
func (r *StringReader) ReadAt(b []byte, off int64) (n int, err error) {
// cannot modify state - see io.ReaderAt
if off < 0 {
return 0, errors.New("strings.StringReader.ReadAt: negative offset")
}
if off >= int64(len(r.s)) {
return 0, io.EOF
}
n = copy(b, r.s[off:])
if n < len(b) {
err = io.EOF
}
return
}
func (r *StringReader) ReadByte() (byte, error) {
r.prevRune = -1
if r.i >= int64(len(r.s)) {
return 0, io.EOF
}
b := r.s[r.i]
r.i++
return b, nil
}
func (r *StringReader) UnreadByte() error {
r.prevRune = -1
if r.i <= 0 {
return errors.New("strings.StringReader.UnreadByte: at beginning of string")
}
r.i--
return nil
}
func (r *StringReader) ReadRune() (ch rune, size int, err error) {
if r.i >= int64(len(r.s)) {
r.prevRune = -1
return 0, 0, io.EOF
}
r.prevRune = int(r.i)
if c := r.s[r.i]; c < utf8.RuneSelf {
r.i++
return rune(c), 1, nil
}
ch, size = utf8.DecodeRuneInString(r.s[r.i:])
r.i += int64(size)
return
}
func (r *StringReader) ReadRunes(amount int64) ([]rune, error) {
var i int64
var runes []rune
for i = 0; i < amount; i++ {
character, _, err := r.ReadRune()
if err != nil {
return runes, err
}
runes = append(runes, character)
}
return runes, nil
}
func (r *StringReader) UnreadRune() error {
if r.prevRune < 0 {
return errors.New("strings.StringReader.UnreadRune: previous operation was not ReadRune")
}
r.i = int64(r.prevRune)
r.prevRune = -1
return nil
}
func (r *StringReader) PeekRune() rune {
character, err := r.PeekRuneError()
if err != nil {
panic("error rune peeking")
}
return character
}
func (r *StringReader) PeekRuneError() (ch rune, err error) {
if r.i >= int64(len(r.s)) {
r.prevRune = -1
return 0, io.EOF
}
if c := r.s[r.i]; c < utf8.RuneSelf {
return rune(c), nil
}
ch, _ = utf8.DecodeRuneInString(r.s[r.i:])
return
}
func (r *StringReader) PeekRuneFor(character rune) bool {
if r.AtEnd() {
return false
}
nextRune, _, _ := r.ReadRune()
if character == nextRune {
return true
}
r.Skip(-1)
return false
}
func (r *StringReader) GetPosition() int64 {
return r.i
}
func (r *StringReader) SetPosition(position int64) (int64, error) {
if position > int64(len(r.s)) || position < 0 {
return -1, errors.New("strings.StringReader.SetPosition: invalid position")
}
r.i = position
r.prevRune = (int)(r.i - 1)
return r.i, nil
}
func (r *StringReader) Skip(posOffset int64) (int64, error) {
position, err := r.SetPosition(r.i + posOffset)
return position, err
}
func (r *StringReader) AtEnd() bool {
if r.i >= int64(len(r.s)) {
return true
} else {
return false
}
}
// WriteTo implements the io.WriterTo interface.
func (r *StringReader) WriteTo(w io.Writer) (n int64, err error) {
r.prevRune = -1
if r.i >= int64(len(r.s)) {
return 0, nil
}
s := r.s[r.i:]
m, err := io.WriteString(w, s)
if m > len(s) {
panic("strings.StringReader.WriteTo: invalid WriteString count")
}
r.i += int64(m)
n = int64(m)
if m != len(s) && err == nil {
err = io.ErrShortWrite
}
return
}
// Reset resets the StringReader to be reading from s.
func (r *StringReader) Reset(s string) { *r = StringReader{s, 0, -1} }
// NewReader returns a new StringReader reading from s.
// It is similar to bytes.NewBufferString but more efficient and read-only.
func NewReader(s string) *StringReader { return &StringReader{s, 0, -1} }
|
// Copyright 2018 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tracing
import (
"context"
"fmt"
"testing"
)
// BenchmarkNoopLogKV benchs the cost of noop's `LogKV`.
func BenchmarkNoopLogKV(b *testing.B) {
sp := noopSpan()
for i := 0; i < b.N; i++ {
sp.LogKV("event", "noop is finished")
}
}
// BenchmarkNoopLogKVWithF benchs the the cosst of noop's `LogKV` when
// used with `fmt.Sprintf`
func BenchmarkNoopLogKVWithF(b *testing.B) {
sp := noopSpan()
for i := 0; i < b.N; i++ {
sp.LogKV("event", fmt.Sprintf("this is format %s", "noop is finished"))
}
}
// BenchmarkSpanFromContext benchs the cost of `SpanFromContext`.
func BenchmarkSpanFromContext(b *testing.B) {
ctx := context.TODO()
for i := 0; i < b.N; i++ {
SpanFromContext(ctx)
}
}
// BenchmarkChildFromContext benchs the cost of `ChildSpanFromContxt`.
func BenchmarkChildFromContext(b *testing.B) {
ctx := context.TODO()
for i := 0; i < b.N; i++ {
ChildSpanFromContxt(ctx, "child")
}
}
|
package database
import (
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"encoding/json"
_ "log"
"math/rand"
"net/http"
"strconv"
"time"
)
type UserStore struct {
db *gorm.DB
}
type UserResource struct {
Store *UserStore
Ctl *Control
}
type MyUser struct {
gorm.Model
Firebase_id string `gorm:"unique;not null;index:fid"`
Name string
}
func NewUserResource(db *gorm.DB, ctl *Control) *UserResource {
db.AutoMigrate(&MyUser{})
us := &UserStore{
db: db,
}
return &UserResource{
Store: us,
Ctl: ctl,
}
}
func (c *UserResource) createMyUser(usr *MyUser) error {
c.Ctl.IncrementUser()
return c.Store.db.Create(&usr).Error
}
func (c *UserResource) getMyUser(usr *MyUser) error {
return c.Store.db.Where("Firebase_id = ?", usr.Firebase_id).First(usr).Error
}
func (c *UserResource) updateMyUser(usr *MyUser) error {
c.Ctl.IncrementUser()
return c.Store.db.Save(usr).Error
}
func (c *UserResource) getMyUsers(limit int) ([]MyUser, error) {
sesItem := make([]MyUser, limit)
err := c.Store.db.Limit(limit).Find(&sesItem).Error
return sesItem, err
}
func (c *UserResource) deleteMyUser(cc *MyUser) error {
c.Ctl.IncrementUser()
return c.Store.db.Delete(cc).Error
}
func (c *UserResource) getRandomUsers(count int) ([]MyUser, error) {
rand.Seed(time.Now().UTC().UnixNano())
max := 0
c.Store.db.Model(&MyUser{}).Count(&max)
mUsers := make([]MyUser, count)
finished := 0
for finished < count {
var usr MyUser
if err := c.Store.db.Where("id = ? ", rand.Intn(max)).Find(&usr).Error; err != nil {
continue
}
mUsers[finished] = usr
finished++
}
return mUsers, nil
}
func (c *UserResource) List(w http.ResponseWriter, r *http.Request) {
di, err := c.getMyUsers(20)
if err != nil {
c.Ctl.Render.RespondWithError(w, http.StatusInternalServerError, err.Error())
}
c.Ctl.Render.RespondWithJSON(w, http.StatusOK, di)
}
func (c *UserResource) ListRandom(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
num, err := strconv.Atoi(vars["num"])
di, err := c.getRandomUsers(num)
if err != nil {
c.Ctl.Render.RespondWithError(w, http.StatusInternalServerError, err.Error())
}
c.Ctl.Render.RespondWithJSON(w, http.StatusOK, di)
}
func (c *UserResource) Create(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var count MyUser
err := decoder.Decode(&count)
if err != nil {
c.Ctl.Render.RespondWithError(w, http.StatusBadRequest, err.Error())
return
}
c.createMyUser(&count)
c.Ctl.Render.RespondOK(w)
}
func (c *UserResource) Get(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
count := MyUser{}
id, err := strconv.Atoi(vars["ID"])
count.ID = uint(id)
if err != nil {
c.Ctl.Render.RespondWithError(w, http.StatusInternalServerError, err.Error())
return
}
err = c.getMyUser(&count)
if err != nil {
c.Ctl.Render.RespondWithError(w, http.StatusInternalServerError, err.Error())
return
}
c.Ctl.Render.RespondWithJSON(w, http.StatusOK, count)
}
func (c *UserResource) Update(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var count MyUser
err := decoder.Decode(&count)
if err != nil {
c.Ctl.Render.RespondWithError(w, http.StatusBadRequest, err.Error())
return
}
c.updateMyUser(&count)
if err != nil {
c.Ctl.Render.RespondWithError(w, http.StatusBadRequest, err.Error())
return
}
c.Ctl.Render.RespondOK(w)
}
func (c *UserResource) Delete(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
count := MyUser{}
id, err := strconv.Atoi(vars["ID"])
count.ID = uint(id)
if err != nil {
c.Ctl.Render.RespondWithError(w, http.StatusInternalServerError, err.Error())
return
}
err = c.deleteMyUser(&count)
if err != nil {
c.Ctl.Render.RespondWithError(w, http.StatusInternalServerError, err.Error())
return
}
c.Ctl.Render.RespondOK(w)
}
func (c *UserResource) GetRouter(mw mux.MiddlewareFunc) *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/", c.List).Methods("GET")
rc := r.PathPrefix("/admin/").Subrouter()
rc.Use(mw)
r.HandleFunc("/", c.Create).Methods("POST")
rc.HandleFunc("/random/{num}", c.List).Methods("GET")
r.HandleFunc("/{ID}", c.Get).Methods("GET")
r.HandleFunc("/{ID}", c.Update).Methods("PUT")
r.HandleFunc("/{ID}", c.Delete).Methods("DELETE")
return r
}
|
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"os/exec"
"strings"
)
type Library struct {
Genres map[string]map[string]Song `json:"genres"`
}
type Song struct {
Artists []string `json:"artists"`
Links []string `json:"links"`
}
func main() {
config := flag.String("f", "", "file containing your library")
rootPath := flag.String("p", "", "the path to the folder in which it should downloaded the music")
flag.Parse()
if *rootPath == "" || *config == "" {
fmt.Println("Arguments -f and -p must be provided")
return
}
//Read file
file, err := os.ReadFile(*config)
if err != nil {
panic(err)
}
var library Library
err = json.Unmarshal(file, &library)
if err != nil {
panic(err)
}
//Check directory music
err = createFolderIfNotExist(*rootPath)
if err != nil {
panic(err)
}
for genreName, genre := range library.Genres {
createFolderIfNotExist(*rootPath+ "/" + genreName)
if err != nil {
panic(err)
}
for songName, song := range genre {
artists := strings.Join(song.Artists, ", ")
songName = artists + " - " + songName + ""
path := *rootPath + "/" + genreName + "/" + songName + ".%(ext)s"
// check if song already present
_, err := os.Stat(path)
if err == nil {
fmt.Println("file already present", err)
continue
}
fmt.Println("Downloading", path)
for _, url := range song.Links {
err = exec.Command(
"youtube-dl",
"-x",
"--audio-format",
"m4a",
"--prefer-ffmpeg",
url,
"-o",
path,
).Run()
if err != nil {
continue
}
}
}
}
}
func createFolderIfNotExist(path string) error {
folderInfo, err := os.Stat(path)
if err != nil || !folderInfo.IsDir() {
err = os.Mkdir(path, 0755)
if err != nil {
return err
}
}
return nil
}
// Command to download:
// yoltube-dl -x --audio-format m4a --prefer-ffmpeg <URL> -o "<ARTIST> - <TITLE>.%(ext)s"
|
package common
const (
GUEST_LOGIN = uint32(1) // 游客登录
FYSDK_ONLINE = uint32(2) // FYSDK联网版本
FYSDK_OFFLINE = uint32(3) // FYSDK单机版本
)
|
package main
import (
"context"
"flag"
"log"
"os"
"time"
"github.com/hypoballad/toecutter/toecuttergrpc"
"google.golang.org/grpc"
)
var addr = flag.String("addr", "localhost:50051", "server address")
var name = flag.String("name", "", "hashes|reward|account/stats|account/site|account/payments|sitestats|payment1mhash")
func main() {
flag.Parse()
conn, err := grpc.Dial(*addr, grpc.WithInsecure(), grpc.WithBlock())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := toecuttergrpc.NewCoinimpClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
switch *name {
case "hashes":
empty := &toecuttergrpc.Empty{}
respHashes, err := c.Hashes(ctx, empty)
if err != nil {
log.Fatalln(err)
}
log.Printf("message: %d, status: %s\n", respHashes.GetMessage(), respHashes.GetStatus())
case "reward":
empty := &toecuttergrpc.Empty{}
respReward, err := c.Reward(ctx, empty)
if err != nil {
log.Fatalln(err)
}
log.Printf("message: %s, status: %s\n", respReward.GetMessage(), respReward.GetStatus())
case "account/stats":
empty := &toecuttergrpc.Empty{}
respStats, err := c.AccountStats(ctx, empty)
if err != nil {
log.Fatalln(err)
}
log.Printf("hasherate: %f, hashes: %d, reward: %s, rewardpending: %s, status: %s\n", respStats.GetHasherate(), respStats.GetHashes(), respStats.GetReward(), respStats.GetRewardpending(), respStats.GetStatus())
case "account/site":
empty := &toecuttergrpc.Empty{}
respSite, err := c.AccountSite(ctx, empty)
if err != nil {
log.Fatalln(err)
}
log.Printf("message: %v, status: %s\n", respSite.GetSites(), respSite.GetStatus())
case "account/payments":
empty := &toecuttergrpc.Empty{}
respPayments, err := c.AccountPayments(ctx, empty)
if err != nil {
log.Fatalln(err)
}
log.Printf("payments: %v, status: %s\n", respPayments.GetPayments(), respPayments.GetStatus())
case "sitestats":
empty := &toecuttergrpc.Empty{}
respSiteStats, err := c.SiteStats(ctx, empty)
if err != nil {
log.Fatalln(err)
}
log.Printf("name: %s, hashrate: %f, hashes: %d, reward: %s\n", respSiteStats.GetName(), respSiteStats.GetHashrate(), respSiteStats.GetHashes, respSiteStats.GetReward())
case "payment1mhash":
empty := &toecuttergrpc.Empty{}
respPayout, err := c.Payout1MHash(ctx, empty)
if err != nil {
log.Fatalln(err)
}
log.Printf("result: %s, status: %s\n", respPayout.GetResult(), respPayout.GetStatus())
default:
log.Println("name required")
}
os.Exit(0)
}
|
package keys
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"github.com/bbucko/cli-iec/common/ini-repo"
"log"
)
type RSAKey struct {
KeyName string
PrivateKey string
PublicKey string
}
func FetchRSAKeyByName(name string) (key RSAKey, err error) {
log.Printf("Searching repository for RSA key with name: [%v]", name)
privateKey, err := ini_repo.GetValue("keys", fmt.Sprintf("%v_private", name))
if err != nil {
log.Fatal(err)
return
}
publicKey, err := ini_repo.GetValue("keys", fmt.Sprintf("%v_public", name))
if err != nil {
log.Fatal(err)
return
}
return RSAKey{name, privateKey, publicKey}, nil
}
func CreateRSAKey(name string, bits int) (RSAKey, error) {
log.Printf("Creating RSA key with name [%v] with size [%v] bits", name, bits)
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
log.Println(err)
return RSAKey{}, err
}
privateKeyPem := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
}
publicKeyPem := &pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: x509.MarshalPKCS1PublicKey(&privateKey.PublicKey),
}
return RSAKey{name, string(pem.EncodeToMemory(privateKeyPem)), string(pem.EncodeToMemory(publicKeyPem))}, nil
}
func (key RSAKey) Persist() {
log.Printf("Saving RSA key: %v", key)
ini_repo.Persist("keys", key.PublicKeySectionName(), key.PublicKey)
ini_repo.Persist("keys", key.PrivateKeySectionName(), key.PrivateKey)
}
func (key RSAKey) PublicKeySectionName() string {
return fmt.Sprintf("%v_public", key.KeyName)
}
func (key RSAKey) PrivateKeySectionName() string {
return fmt.Sprintf("%v_private", key.KeyName)
}
func (key RSAKey) String() string {
return fmt.Sprintf("[name: %v]", key.KeyName)
}
|
package main
import (
"bufio"
"flag"
"fmt"
"math/big"
"os"
"time"
)
// TimeEntry
type TimeEntry struct {
Project string `json:"project"`
Task string `json:"task"`
Duration int `json:"duration"`
Start time.Time `json:"start"`
End time.Time `json:"end"`
}
func NewTimer(project string, task string) {
fmt.Println(project)
entry := TimeEntry{
Task: task,
Project: project,
}
startTime := time.Now()
fmt.Printf("Start: \t %s \n", startTime.Format(time.ANSIC))
fmt.Printf("Project:\t %s \n", project)
fmt.Printf("Task: \t %s \n", task)
fmt.Println()
fmt.Printf("\rElapsed Time:\t 00:00:00")
ticker := time.NewTicker(1 * time.Second)
if entry.Project == "" {
}
//timeEntryChannel := make(chan TimeEntry)
go func() {
for range ticker.C {
h := big.NewInt(int64(time.Since(startTime).Hours()))
m := big.NewInt(int64(time.Since(startTime).Minutes()))
s := big.NewInt(int64(time.Since(startTime).Seconds()))
s = s.Mod(s, big.NewInt(60))
m = m.Mod(m, big.NewInt(60))
fmt.Printf("\rElapsed Time:\t %02d:%02d:%02d", h, m, s)
}
}()
//output, err := json.Marshal(entry)
//if err != nil {
// fmt.Print("could not marshal json")
//}
//fmt.Print(string(output))
}
func main() {
listCommand := flag.NewFlagSet("list", flag.ExitOnError)
timeCommand := flag.NewFlagSet("time", flag.ExitOnError)
// time command flags
timeProjectPtr := timeCommand.String("project", "default", "Select which project should be used for time tracking")
timeTaskPtr := timeCommand.String("task", "default", "Select which task should be used for time tracking")
if len(os.Args) < 2 {
listCommand.PrintDefaults()
timeCommand.PrintDefaults()
os.Exit(1)
}
switch os.Args[1] {
case "list":
listCommand.Parse(os.Args[2:])
case "time":
timeCommand.Parse(os.Args[2:])
default:
flag.PrintDefaults()
os.Exit(1)
}
if timeCommand.Parsed() {
if *timeProjectPtr == "" {
timeCommand.PrintDefaults()
os.Exit(1)
}
if *timeTaskPtr == "" {
timeCommand.PrintDefaults()
os.Exit(1)
}
NewTimer(*timeProjectPtr, *timeTaskPtr)
}
reader := bufio.NewReader(os.Stdin)
var input string
for input != "exit\n" {
input, _ = reader.ReadString('\n')
}
}
|
package env
import (
"errors"
"github.com/andybar2/team/store"
"github.com/spf13/cobra"
)
var setParams struct {
Stage string
Name string
Value string
}
var setCmd = &cobra.Command{
Use: "set",
Short: "Set an environment variable",
RunE: runSetCmd,
}
func init() {
setCmd.Flags().StringVarP(&setParams.Stage, "stage", "s", "", "Stage name")
setCmd.Flags().StringVarP(&setParams.Name, "name", "n", "", "Variable name")
setCmd.Flags().StringVarP(&setParams.Value, "value", "v", "", "Variable value")
EnvCmd.AddCommand(setCmd)
}
func runSetCmd(cmd *cobra.Command, args []string) error {
if setParams.Stage == "" {
return errors.New("invalid stage name")
}
if setParams.Name == "" {
return errors.New("invalid variable name")
}
s, err := store.New()
if err != nil {
return err
}
return s.EnvSet(setParams.Stage, setParams.Name, setParams.Value)
}
|
package cmd
import (
"fmt"
"os"
"strings"
"io/ioutil"
"path/filepath"
"code.cloudfoundry.org/cfdev/config"
"code.cloudfoundry.org/cfdev/env"
"code.cloudfoundry.org/cfdev/resource"
)
type Download struct {
Exit chan struct{}
UI UI
Config config.Config
}
func (d *Download) Run(args []string) error {
go func() {
<-d.Exit
os.Exit(128)
}()
if err := env.Setup(d.Config); err != nil {
return nil
}
d.UI.Say("Downloading Resources...")
return download(d.Config.Dependencies, d.Config.CacheDir)
}
func download(dependencies resource.Catalog, cacheDir string) error {
logCatalog(dependencies, cacheDir)
downloader := resource.Downloader{}
skipVerify := strings.ToLower(os.Getenv("CFDEV_SKIP_ASSET_CHECK"))
cache := resource.Cache{
Dir: cacheDir,
DownloadFunc: downloader.Start,
SkipAssetVerification: skipVerify == "true",
}
if err := cache.Sync(&dependencies); err != nil {
return fmt.Errorf("Unable to sync assets: %v\n", err)
}
return nil
}
func logCatalog(dependencies resource.Catalog, cacheDir string) {
ioutil.WriteFile(filepath.Join(cacheDir, "catalog.txt"), []byte(fmt.Sprintf("%+v", dependencies.Items)), 0644)
}
|
package disk
import (
"bytes"
"fmt"
"syscall"
"text/template"
"time"
"github.com/pelletier/go-toml"
"github.com/rumpelsepp/i3gostatus/lib/config"
"github.com/rumpelsepp/i3gostatus/lib/model"
"github.com/rumpelsepp/i3gostatus/lib/utils"
)
const (
name = "disk"
moduleName = "i3gostatus.modules." + name
defaultFormat = "{{.Used}}/{{.Total}} [{{.Avail}}]"
defaultPath = "/"
defaultPeriod = 5000
)
type Config struct {
model.BaseConfig
Path string
}
func (c *Config) ParseConfig(configTree *toml.TomlTree) {
c.BaseConfig.Parse(name, configTree)
c.Period = config.GetDurationMs(configTree, c.Name+".period", defaultPeriod)
c.Format = config.GetString(configTree, name+".format", defaultFormat)
c.Path = config.GetString(configTree, name+".path", defaultPath)
}
type space struct {
Avail string
Used string
Total string
}
func getSpace(path string) *space {
var stat syscall.Statfs_t
syscall.Statfs(path, &stat)
avail := utils.HumanReadableByteCount(stat.Bavail * uint64(stat.Bsize))
used := utils.HumanReadableByteCount((stat.Blocks - stat.Bavail) * uint64(stat.Bsize))
total := utils.HumanReadableByteCount(stat.Blocks * uint64(stat.Bsize))
return &space{avail, used, total}
}
func (c *Config) Run(args *model.ModuleArgs) {
outputBlock := model.NewBlock(moduleName, c.BaseConfig, args.Index)
var outStr string
t := template.Must(template.New("disk").Parse(c.Format))
for range time.NewTicker(c.Period).C {
buf := bytes.NewBufferString(outStr)
space := getSpace(c.Path)
if err := t.Execute(buf, space); err == nil {
outputBlock.FullText = buf.String()
} else {
outputBlock.FullText = fmt.Sprint(err)
}
args.OutCh <- outputBlock
}
}
|
// Copyright 2014 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License. See the AUTHORS file
// for names of contributors.
//
// Author: Tobias Schottdorf (tobias.schottdorf@gmail.com)
package encoding
import (
"math"
"reflect"
"testing"
)
func TestEncoding(t *testing.T) {
k := []byte("asd")
n := int64(3142595)
encoded, err := Encode(k, int64(n))
if err != nil {
t.Errorf("encoding error for %d", n)
}
decoded, err := Decode(k, encoded)
if err != nil {
t.Errorf("decoding error for %d", n)
}
switch v := decoded.(type) {
case int64:
if v != n {
t.Errorf("int64 decoding error, got the wrong result")
}
default:
t.Errorf("int64 decoding error, did not get a uint64 back but instead type %v: %v", reflect.TypeOf(v), v)
}
}
func TestChecksums(t *testing.T) {
testKey := []byte("whatever")
doubleWrap := func(a []byte) bool {
_, err := unwrapChecksum(testKey, wrapChecksum(testKey, a))
return err == nil
}
_, err := unwrapChecksum([]byte("does not matter"), []byte("srt"))
if err == nil {
t.Fatalf("expected error unwrapping a too short string")
}
testCases := [][]byte{
[]byte(""),
[]byte("Hello"),
[]byte(" tab "),
func() []byte {
b := make([]byte, math.MaxUint8, math.MaxUint8)
for i := 0; i < math.MaxUint8; i++ {
b[i] = 'z'
}
return b
}(),
[]byte("لاحول ولا قوة الا بالله"),
}
for i, c := range testCases {
if !doubleWrap(c) {
t.Errorf("unexpected integrity error for '%v'", c)
}
// Glue an extra byte to a copy that kills the checksum.
distorted := append(wrapChecksum(testKey, append([]byte(nil), c...)), '1')
if _, err := unwrapChecksum(testKey, distorted); err == nil {
t.Errorf("%d: unexpected integrity match for corrupt value", i)
}
}
}
func TestWillOverflow(t *testing.T) {
testCases := []struct {
a, b int64
overflow bool // will a+b over- or underflow?
}{
{0, 0, false},
{math.MaxInt64, 0, false},
{math.MaxInt64, 1, true},
{math.MaxInt64, math.MinInt64, false},
{math.MinInt64, 0, false},
{math.MinInt64, -1, true},
{math.MinInt64, math.MinInt64, true},
}
for i, c := range testCases {
if WillOverflow(c.a, c.b) != c.overflow ||
WillOverflow(c.b, c.a) != c.overflow {
t.Errorf("%d: overflow recognition error", i)
}
}
}
|
package main
import (
"flag"
"fmt"
"log"
"net"
"strconv"
"google.golang.org/grpc"
auth_rep "2019_2_IBAT/pkg/app/auth/repository"
"2019_2_IBAT/pkg/app/auth/service"
"2019_2_IBAT/pkg/app/auth/session"
"2019_2_IBAT/pkg/pkg/config"
)
func main() {
lis, err := net.Listen("tcp", ":"+strconv.Itoa(config.AuthServicePort))
if err != nil {
log.Fatalln("cant listet port", err)
}
fmt.Println("auth base test")
redisAddr := flag.String(config.RedisHostname, config.RedisHostname+":"+strconv.Itoa(config.ReddisPort), "")
fmt.Printf("redisAddr: %s", *redisAddr)
server := grpc.NewServer()
session.RegisterServiceServer(server, service.AuthService{
Storage: auth_rep.NewSessionManager(auth_rep.RedNewPool(*redisAddr)),
})
fmt.Println("starting server at " + strconv.Itoa(config.AuthServicePort))
server.Serve(lis)
}
|
// BCM2835Bridge
// package BCM2835Bridge
// #cgo LDFLAGS: -l bcm2835 -static
package main
import (
"C"
"bcm2835"
"fmt"
"log"
)
func main() {
fmt.Println("SPI loop back!")
// Initialize the library
if err := bcm2835.Init(); err != nil {
log.Fatal(err)
}
// continues on the next slide
// SPLIT OMIT
bcm2835.SpiBegin()
defer bcm2835.Close()
defer bcm2835.SpiEnd()
// All defaults
bcm2835.SpiSetBitOrder(bcm2835.BCM2835_SPI_BIT_ORDER_MSBFIRST)
bcm2835.SpiSetDataMode(bcm2835.BCM2835_SPI_MODE0)
bcm2835.SpiSetClockDivider(bcm2835.BCM2835_SPI_CLOCK_DIVIDER_65536)
bcm2835.SpiChipSelect(bcm2835.BCM2835_SPI_CS0)
bcm2835.SpiSetChipSelectPolarity(bcm2835.BCM2835_SPI_CS0, bcm2835.LOW)
// Send a byte to the slave and simultaneously read a byte back from the slave
// If you tie MISO to MOSI, you should read back what was sent
fmt.Printf("Read from SPI: %#X\n", bcm2835.SpiTransfer(0x23))
}
|
package cp
import (
"dappapi/models"
"dappapi/tools/app"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/sirupsen/logrus"
)
func Report(c *gin.Context) {
cCp := c.Copy()
go func() {
var report models.JsonBody
err := cCp.ShouldBindWith(&report, binding.JSON)
if err != nil {
logrus.WithField("logFile", "asyncerror").Error(report)
} else {
logrus.WithField("logFile", "async").Info(report)
report.Handle()
}
}()
app.OK(c, gin.H{}, "success")
}
|
/*
* Copyright (C) 2016-Present Pivotal Software, Inc. All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the under the Apache License, Version 2.0 (the "License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eureka
import (
"fmt"
"code.cloudfoundry.org/cli/plugin"
"github.com/pivotal-cf/spring-cloud-services-cli-plugin/cfutil"
"github.com/pivotal-cf/spring-cloud-services-cli-plugin/format"
"github.com/pivotal-cf/spring-cloud-services-cli-plugin/httpclient"
"github.com/pivotal-cf/spring-cloud-services-cli-plugin/serviceutil"
)
const (
UnknownCfAppName = "?????"
UnknownCfInstanceIndex = "?"
)
type Instance struct {
App string
InstanceId string
Status string
Metadata struct {
CfAppGuid string
CfInstanceIndex string
Zone string
}
}
type ApplicationInstance struct {
Instance []Instance
}
type ListResp struct {
Applications struct {
Application []ApplicationInstance
}
}
type SummaryResp struct {
Name string
}
type SummaryFailure struct {
Code int
Description string
ErrorCode string
}
func List(cliConnection plugin.CliConnection, srInstanceName string, authClient httpclient.AuthenticatedClient, serviceInstanceUrlResolver serviceutil.ServiceInstanceResolver) (string, error) {
accessToken, err := cfutil.GetToken(cliConnection)
if err != nil {
return "", err
}
eureka, err := serviceInstanceUrlResolver.GetServiceInstanceUrl(srInstanceName, accessToken)
if err != nil {
return "", fmt.Errorf("Error obtaining service registry URL: %s", err)
}
registeredApps, err := getAllRegisteredApps(cliConnection, authClient, accessToken, eureka)
if err != nil {
return "", err
}
return formatAppList(registeredApps, eureka, srInstanceName), nil
}
func formatAppList(registeredApps []eurekaAppRecord, eurekaUrl string, srInstanceName string) string {
tab := &format.Table{}
tab.Entitle([]string{"eureka app name", "cf app name", "cf instance index", "zone", "status"})
if len(registeredApps) == 0 {
return fmt.Sprintf("Service instance: %s\nServer URL: %s\n\nNo registered applications found\n", srInstanceName, eurekaUrl)
}
for _, app := range registeredApps {
tab.AddRow([]string{app.eurekaAppName, app.cfAppName, app.instanceIndex, app.zone, app.status})
}
return fmt.Sprintf("Service instance: %s\nServer URL: %s\n\n%s", srInstanceName, eurekaUrl, tab.String())
}
|
package handler
import (
"context"
"errors"
"fmt"
"time"
"github.com/jinmukeji/jiujiantang-services/subscription/mysqldb"
proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/subscription/v1"
)
// AddUsersIntoSubscription 将用户添加到订阅中
func (j *SubscriptionService) AddUsersIntoSubscription(ctx context.Context, req *proto.AddUsersIntoSubscriptionRequest, resp *proto.AddUsersIntoSubscriptionResponse) error {
token, ok := TokenFromContext(ctx)
if !ok {
return NewError(ErrInvalidUser, errors.New("failed to get token from context"))
}
userID, err := j.datastore.FindUserIDByToken(ctx, token)
if err != nil {
return NewError(ErrDatabase, fmt.Errorf("failed to find userID from token: %s", err.Error()))
}
if userID != req.OwnerId {
return NewError(ErrInvalidUser, fmt.Errorf("current user %d from token is not the owner %d", userID, req.OwnerId))
}
users := make([]*mysqldb.UserSubscriptionSharing, len(req.UserIdList))
now := time.Now()
for idx, uid := range req.UserIdList {
users[idx] = &mysqldb.UserSubscriptionSharing{
SubscriptionID: req.SubscriptionId,
UserID: uid,
CreatedAt: now,
UpdatedAt: now,
}
}
errCreateUserSubscriptionSharing := j.datastore.CreateMultiUserSubscriptionSharing(ctx, users)
if errCreateUserSubscriptionSharing != nil {
return NewError(ErrDatabase, fmt.Errorf("failed to create multi user subscription sharing: %s", errCreateUserSubscriptionSharing.Error()))
}
return nil
}
|
package _132_Palindrome_Partitioning_2
import (
"math"
)
func minCut(s string) int {
n := len(s)
judge := make([][]bool, n)
for idx := range judge {
judge[idx] = make([]bool, n)
}
dp := make([]int, n) // dp[i]为s中第i位到第n-1位的子字符串中,最小分割次数
for i := n - 1; i >= 0; i-- {
dp[i] = math.MaxInt32
for j := i; j < n; j++ {
if s[j] == s[i] && (j-i <= 1 || judge[i+1][j-1]) {
judge[i][j] = true
if j+1 < n {
dp[i] = int(math.Min(float64(dp[i]), 1+float64(dp[j+1])))
} else {
dp[i] = 0
}
}
}
}
return dp[0]
}
|
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
paths := os.Args[1:]
for _, path := range paths {
xx(path)
}
}
// Connect to an url by turning off wi-fi or not
func xx(url string) {
type expected struct{}
defer func() {
if p := recover(); p != nil {
switch p {
case nil:
fmt.Println("no error\n")
case expected{}:
fmt.Printf("expected error\n")
case 1:
fmt.Printf("expected error: %v\n", p)
default:
panic(p)
}
}
}()
fmt.Printf("url: %s\n", url)
r, err := http.Get(url)
// Change a condition below.
if err != nil {
panic(1)
} else {
panic(expected{})
}
fmt.Println(r)
}
|
package queue
import (
"testing"
"time"
. "github.com/smartystreets/goconvey/convey"
)
func TestArrayQueue(t *testing.T) {
Convey("array queue", t, func() {
q := &ArrayQueue{}
q.Push(1)
So(q.Len(), ShouldEqual, 1)
q.Push(2)
So(q.Len(), ShouldEqual, 2)
e := q.Pop()
So(e, ShouldEqual, 2)
So(q.Len(), ShouldEqual, 1)
b := q.Pop()
So(b, ShouldEqual, 1)
So(q.Len(), ShouldEqual, 0)
})
}
func TestArrayQueueConccurent(t *testing.T) {
Convey("array concurrent queue", t, func() {
q := &ArrayQueue{}
num := 4000
for i := 1; i <= num; i++ {
go func(j int) {
q.Push(j)
}(i)
}
time.Sleep(5 * time.Second)
So(q.Len(), ShouldEqual, num)
var count int
for i := 1; i <= num; i++ {
if b, ok := q.Pop().(int); ok {
count = count + b
}
}
So(count, ShouldEqual, (1+num)*num/2)
})
}
func TestArrayQueueSwap(t *testing.T) {
Convey("swap", t, func() {
q := &ArrayQueue{}
q.Push(NewElement(30))
q.Push(NewElement(20))
So(q.Less(0, 1), ShouldEqual, false)
So(q.Less(1, 0), ShouldEqual, true)
})
}
type Element struct {
I int
}
func NewElement(score int) *Element {
return &Element{
I: score,
}
}
func (e *Element) Less(i interface{}) bool {
if b, ok := i.(*Element); ok {
return e.I < b.I
}
panic("gg")
}
|
package dockerfile
import (
"bytes"
"github.com/mitchellh/packer/builder/docker"
)
// MockDriver is a driver implementation that can be used for tests.
type MockDriver struct {
*docker.MockDriver
BuildImageCalled bool
BuildImageDockerfile *bytes.Buffer
BuildImageErr error
}
func (d *MockDriver) BuildImage(dockerfile *bytes.Buffer) (string, error) {
d.BuildImageCalled = true
d.BuildImageDockerfile = dockerfile
return "1234567890abcdef", d.BuildImageErr
}
|
// Copyright 2023 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"context"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl"
emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto"
alphapb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/gkehub/alpha/gkehub_alpha_go_proto"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/gkehub/alpha"
)
// FleetServer implements the gRPC interface for Fleet.
type FleetServer struct{}
// ProtoToFleet converts a Fleet resource from its proto representation.
func ProtoToFleet(p *alphapb.GkehubAlphaFleet) *alpha.Fleet {
obj := &alpha.Fleet{
Name: dcl.StringOrNil(p.GetName()),
DisplayName: dcl.StringOrNil(p.GetDisplayName()),
CreateTime: dcl.StringOrNil(p.GetCreateTime()),
UpdateTime: dcl.StringOrNil(p.GetUpdateTime()),
Uid: dcl.StringOrNil(p.GetUid()),
ManagedNamespaces: dcl.Bool(p.GetManagedNamespaces()),
Project: dcl.StringOrNil(p.GetProject()),
Location: dcl.StringOrNil(p.GetLocation()),
}
return obj
}
// FleetToProto converts a Fleet resource to its proto representation.
func FleetToProto(resource *alpha.Fleet) *alphapb.GkehubAlphaFleet {
p := &alphapb.GkehubAlphaFleet{}
p.SetName(dcl.ValueOrEmptyString(resource.Name))
p.SetDisplayName(dcl.ValueOrEmptyString(resource.DisplayName))
p.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))
p.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime))
p.SetUid(dcl.ValueOrEmptyString(resource.Uid))
p.SetManagedNamespaces(dcl.ValueOrEmptyBool(resource.ManagedNamespaces))
p.SetProject(dcl.ValueOrEmptyString(resource.Project))
p.SetLocation(dcl.ValueOrEmptyString(resource.Location))
return p
}
// applyFleet handles the gRPC request by passing it to the underlying Fleet Apply() method.
func (s *FleetServer) applyFleet(ctx context.Context, c *alpha.Client, request *alphapb.ApplyGkehubAlphaFleetRequest) (*alphapb.GkehubAlphaFleet, error) {
p := ProtoToFleet(request.GetResource())
res, err := c.ApplyFleet(ctx, p)
if err != nil {
return nil, err
}
r := FleetToProto(res)
return r, nil
}
// applyGkehubAlphaFleet handles the gRPC request by passing it to the underlying Fleet Apply() method.
func (s *FleetServer) ApplyGkehubAlphaFleet(ctx context.Context, request *alphapb.ApplyGkehubAlphaFleetRequest) (*alphapb.GkehubAlphaFleet, error) {
cl, err := createConfigFleet(ctx, request.GetServiceAccountFile())
if err != nil {
return nil, err
}
return s.applyFleet(ctx, cl, request)
}
// DeleteFleet handles the gRPC request by passing it to the underlying Fleet Delete() method.
func (s *FleetServer) DeleteGkehubAlphaFleet(ctx context.Context, request *alphapb.DeleteGkehubAlphaFleetRequest) (*emptypb.Empty, error) {
cl, err := createConfigFleet(ctx, request.GetServiceAccountFile())
if err != nil {
return nil, err
}
return &emptypb.Empty{}, cl.DeleteFleet(ctx, ProtoToFleet(request.GetResource()))
}
// ListGkehubAlphaFleet is a no-op method because Fleet has no list method.
func (s *FleetServer) ListGkehubAlphaFleet(_ context.Context, _ *alphapb.ListGkehubAlphaFleetRequest) (*alphapb.ListGkehubAlphaFleetResponse, error) {
return nil, nil
}
func createConfigFleet(ctx context.Context, service_account_file string) (*alpha.Client, error) {
conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file))
return alpha.NewClient(conf), nil
}
|
package app
import (
"errors"
"fmt"
"math/rand"
"net/http"
"strconv"
"strings"
"text/template"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres" // cockroachdb
otp "github.com/pquerna/otp/totp"
"github.com/wader/gormstore"
"golang.org/x/crypto/bcrypt"
"gopkg.in/ini.v1"
)
//App is the container for the voting applciation
// containing the http router, db, and session store.
type App struct {
Router *mux.Router
DB *gorm.DB
Store *gormstore.Store
}
var s Settings
// Initialize starts the application
func (a *App) Initialize(filename string) {
fmt.Println("init")
cfg, err := ini.Load(filename)
if err != nil {
panic(err)
}
s = Settings{}
err = cfg.MapTo(&s)
fmt.Println(s)
if err != nil {
fmt.Println(err)
}
a.DB, err = gorm.Open("postgres", s.getDB())
if err != nil {
fmt.Println("Error opening DB")
fmt.Println(err)
}
a.DB.AutoMigrate(Voter{}, Issue{}, VoteMap{}, DelegateMap{}, UsernameChange{})
a.CreateAccount("test", "test", "6455P3ACHPDUM42DDVLVWUXDV3MQ7SPN")
a.Store = gormstore.New(a.DB, []byte(s.SessionSecret))
// TODO: Generate code randomly. Change all store codes.
}
//CreateAccount makes an account using a username, password, and totp string
func (a *App) CreateAccount(username string, password string, totp string) error {
hash, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
voter := &Voter{
Username: username,
TOTPSecret: totp,
}
a.DB.Where("username = ?", username).Find(voter)
if voter.ID != 0 {
return errors.New("account already exists")
}
voter.PasswordHash = string(hash)
a.DB.Create(voter)
return nil
}
//Run executes the http handler for the App.
func (a *App) Run() {
m := mux.NewRouter()
m.HandleFunc("/", a.IndexHandler)
m.HandleFunc("/login", a.LoginHandler)
m.HandleFunc("/logout", a.LogoutHandler)
m.HandleFunc("/vote", a.VoteHandler)
m.HandleFunc("/delegate", a.DelegationHandler)
m.HandleFunc("/account", a.AccountHandler)
m.HandleFunc("/admin", a.AdminHandler)
m.HandleFunc("/admin/create", a.AdminUserCreateHandler)
m.HandleFunc("/invite", a.InviteHandler)
m.Use(a.AuthorizationMiddleware)
fmt.Println(http.ListenAndServe(s.ListenAddr, m))
}
//VoteMap creates a link between a user, a vote, and decides votestatus.
type VoteMap struct {
gorm.Model
VoterRefer uint
IssueRefer uint
VoteStatus bool
}
//UsernameChange is used to process username change requests // TODO: FEATURE
type UsernameChange struct {
gorm.Model
VoterRefer uint
FullName string
Username string
ChangePin uint32
}
//DelegateMap creates a link between voters and delegates.
type DelegateMap struct {
gorm.Model
VoterRefer uint
Username string
DelegateRefer uint
}
// Voter is the user object.
type Voter struct {
gorm.Model
Username string
TOTPSecret string
PasswordHash string
PublicKey string
Delegate bool
IsAdmin bool
UpdatePassword bool
UpdateTOTP bool
}
// Issue is a bill/resolution/amendment to describe a change to be made.
type Issue struct {
gorm.Model
BillType string
Title string
Summary string `sql:"type:text"`
Text string
}
//IssueStatus weird mapping, FIXME!!!
type IssueStatus struct {
Issues map[Issue]int
PageCount int
}
// Settings contains the settings for the application
type Settings struct {
ListenAddr string
DBType string
DBUsername string
DBPassword string
DBName string
DBHost string
DBPort string
SSL bool
SessionSecret string
}
//UserGenerate is a way of storing generated users.
type UserGenerate struct {
Username string
Password string
QR string
}
//UsernameChangeRequest inserts a request for a username change
func UsernameChangeRequest(db *gorm.DB, userID uint, fullName string, newUsername string) {
uc := &UsernameChange{
Username: newUsername,
FullName: fullName,
ChangePin: rand.Uint32(),
VoterRefer: userID,
}
qc := &UsernameChange{}
db.Where("voter_refer = ?", userID).First(qc)
if qc.ID == 0 {
db.Save(uc)
}
fmt.Println(uc)
}
//UsernameChangeRequestExist checks if a username change request exists
func UsernameChangeRequestExist(db *gorm.DB, userID uint) bool {
qc := &UsernameChange{}
db.Where("voter_refer = ?", userID).Find(qc)
return qc.ID != 0
}
//UpdatePassword updates the password of a user id from the old password to the new password.
func UpdatePassword(db *gorm.DB, userid uint, currentPassword string, newPassword string) error {
if currentPassword == newPassword {
return errors.New("Must update password")
}
voter := &Voter{}
db.Where("id = ?", userid).First(voter)
if voter.ID == 0 {
return errors.New("User not found")
}
err := bcrypt.CompareHashAndPassword([]byte(voter.PasswordHash), []byte(currentPassword))
if err != nil {
return errors.New("Incorrect password")
}
hash, _ := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.MinCost)
voter.PasswordHash = string(hash)
db.Save(voter)
return nil
}
//ValidateUser checks if the user is valid in the SQL database.
func ValidateUser(db *gorm.DB, username string, password string, totp string) (*Voter, error) {
voter := &Voter{}
db.Where("username = ?", username).First(voter)
if voter.ID == 0 {
return voter, errors.New("no username found")
}
err := bcrypt.CompareHashAndPassword([]byte(voter.PasswordHash), []byte(password))
if err != nil {
return voter, errors.New("wrong password")
}
if !otp.Validate(totp, voter.TOTPSecret) {
return voter, errors.New("wrong totp")
}
return voter, nil
}
func ToggleDelegate(db *gorm.DB, delegateStatus string, voter uint) {
ds := (delegateStatus == "delegate")
v := &Voter{}
db.Where("id = ?", voter).Find(v)
v.Delegate = ds
db.Save(v)
fmt.Printf("%s set delegate status: %v", v.Username, v.Delegate)
}
//UndelegateUser removes a map between a delegate and a user.
func UndelegateUser(db *gorm.DB, voter uint, delegate string) error {
dm := DelegateMap{}
d := Voter{}
fmt.Println(delegate)
db.Where("username = ?", delegate).First(&d)
fmt.Println(d.Username, d.ID)
db.Where("delegate_refer = ?", d.ID).Where("voter_refer = ?", voter).First(&dm)
if dm.ID != 0 {
fmt.Println("Found map to delete", dm)
db.Unscoped().Delete(dm)
return nil
}
return errors.New("Delegate not found")
}
//DelegateUser maps a voter to a delegate. It verifies that the user is actually a delegate
func DelegateUser(db *gorm.DB, voter uint, delegate string) error {
v := &Voter{}
db.Where("ID = ?", voter).First(v)
del := &Voter{}
fmt.Println("Searching for delegate", delegate)
db.Where("username = ?", delegate).First(del)
if v.ID == 0 {
return errors.New("No voter found")
}
if del.ID == 0 || !del.Delegate {
return errors.New("No delegate found")
}
if del.ID == v.ID {
return errors.New("Can't delegate yourself")
}
dm := &DelegateMap{}
db.Where("voter_refer = ?", v.ID).Where("delegate_refer = ?", del.ID).First(dm)
if dm.ID == 0 {
dm.VoterRefer = v.ID
dm.DelegateRefer = del.ID
db.Create(dm)
}
return nil
}
func (s Settings) getDB() string {
return fmt.Sprintf(
"host=%v port=%v user=%v dbname=%v sslmode=disable", s.DBHost, s.DBPort, s.DBUsername, s.DBName)
}
// Invite allows for users to generate an invite code for a new user.
// From the invite, we can create the Voter user.
type Invite struct {
FirstName string
LastName string
StreetAddress string
City string
Zip string
}
// generateVoter creates the actual voter object in the database.
// when a user invite is printed, this is generated using the SOS number and name
func generateVoter(db *gorm.DB, username string) Voter {
return Voter{}
}
// registerVoter allows a user to set a password
func (v Voter) registerVoter(db *gorm.DB, username string) Voter {
return v
}
//InviteHandler renders the invite page for users.
func (a App) InviteHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Ima invite you!")
}
//AdminHandler renders the admin page
func (a App) AdminHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hi admin")
}
func (a App) AdminUserCreateHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "U even an admin?")
}
//AccountHandler renders the account page; update password, update username request,
//update token, and become delegate
func (a App) AccountHandler(w http.ResponseWriter, r *http.Request) {
ses, _ := a.Store.Get(r, "session")
var err error
uid := ses.Values["user_id"].(uint)
if r.Method == http.MethodPost {
r.ParseForm()
if r.FormValue("password_change") == "pc" {
err = UpdatePassword(a.DB, uid,
r.FormValue("current_password"), r.FormValue("new_password"))
}
if r.FormValue("username_change") == "uc" {
UsernameChangeRequest(a.DB, uid, r.FormValue("name"), r.FormValue("username"))
}
if r.FormValue("become_delegate") == "del" {
ToggleDelegate(a.DB, r.FormValue("delegate"), uid)
}
}
v := Voter{}
a.DB.Where("ID = ?", uid).Find(&v)
templates.ExecuteTemplate(w, "account.html", struct {
Err error
UC bool
Voter Voter
}{
Err: err,
UC: UsernameChangeRequestExist(a.DB, uid),
Voter: v,
})
}
//IndexHandler renders the index page
func (a App) IndexHandler(rw http.ResponseWriter, r *http.Request) {
rw.Write([]byte("<html>"))
ses, _ := a.Store.Get(r, "session")
var v Voter
a.DB.Where("id = ?", ses.Values["user_id"]).Find(&v)
rw.Write([]byte(fmt.Sprintf("<p>Hello %s</p>", v.Username)))
rw.Write([]byte("<a href='/vote'>Click here to vote.</a>"))
var vm []VoteMap
a.DB.Find(&vm)
var issueUnique []VoteMap
a.DB.Select("DISTINCT(issue_refer)").Find(&issueUnique)
count2 := len(issueUnique)
rw.Write([]byte(fmt.Sprintf("<p>Total Votes: %d</p> <p>Total Issues Voted On: %v</p>", len(vm), count2)))
a.DB.Where("voter_refer = ?", ses.Values["user_id"]).Find(&vm)
rw.Write([]byte(fmt.Sprintf("Your personal votes: %d </html>", len(vm))))
}
var templates = template.Must(template.New("").Funcs(funcMap).ParseGlob("templates/*"))
var funcMap = template.FuncMap{
// The name "inc" is what the function will be called in the template text.
"add": func(i int) int {
return i + 1
},
"sub": func(i int) int {
return i - 1
},
}
//DelegationHandler allows users to remove/add delegates for their votes.
func (a App) DelegationHandler(w http.ResponseWriter, r *http.Request) {
username := ""
ses, err := a.Store.Get(r, "session")
user := ses.Values["user_id"].(uint)
fmt.Println(user)
if r.Method == http.MethodPost {
r.ParseForm()
if r.FormValue("removal") == "true" {
for _, x := range r.Form["remove_user"] {
err = UndelegateUser(a.DB, user, x)
}
}
if r.FormValue("delegate_trigger") == "true" {
err = DelegateUser(a.DB, user, r.FormValue("delegate"))
}
}
v := []Voter{}
a.DB.Joins("join delegate_maps on voters.id = delegate_maps.delegate_refer").Where("delegate_maps.voter_refer = ?", user).Find(&v)
errorString := ""
info := []string{username}
if err != nil {
fmt.Println(err)
info = append(info, err.Error())
errorString = err.Error()
}
err = templates.Funcs(funcMap).ExecuteTemplate(w, "delegate.html", struct {
Voters []Voter
Err string
}{Voters: v, Err: errorString})
}
//AuthorizationMiddleware verifies a user's session. If the session is invalid, it boots them to login.
func (a App) AuthorizationMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ses, err := a.Store.Get(r, "session")
fmt.Printf("%v - %v accessed %v\n", r.RemoteAddr, ses.Values["username"], r.RequestURI)
if (err != nil || ses.Values["user_id"] == nil) && !strings.Contains(r.RequestURI, "login") {
fmt.Println(err)
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
return
}
if strings.Contains(r.RequestURI, "admin") && ses.Values["is_admin"] == nil {
fmt.Println("Non-admin access")
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
next.ServeHTTP(w, r)
})
}
//VoteHandler handles the voting method.
func (a App) VoteHandler(w http.ResponseWriter, r *http.Request) {
//TODO: Redo this entire form.
r.ParseForm()
ses, err := a.Store.Get(r, "session")
if err != nil {
fmt.Println(err)
}
voterID := ses.Values["user_id"].(uint)
loggedVote := &VoteMap{}
if r.Method == http.MethodPost {
for i, x := range r.Form {
issueID, err := strconv.Atoi(i)
if err != nil {
fmt.Println(err)
}
fmt.Println(issueID)
vote := &VoteMap{
IssueRefer: uint(issueID),
VoterRefer: voterID,
}
loggedVote = &VoteMap{}
fmt.Println(loggedVote)
a.DB.Find(loggedVote, vote)
fmt.Println(loggedVote)
isAye := (x[0] == "aye")
fmt.Println(loggedVote)
vote.VoteStatus = isAye
//TODO cleanup this shitstorm.
if x[0] == "undecided" {
if loggedVote.ID == 0 {
continue
}
fmt.Println(x[0])
fmt.Println("Deleting records ", loggedVote)
a.DB.Unscoped().Delete(loggedVote)
} else if loggedVote.ID == 0 {
a.DB.Create(vote)
} else if loggedVote.VoteStatus != isAye {
loggedVote.VoteStatus = isAye
a.DB.Save(&loggedVote)
}
}
}
page, err := strconv.Atoi(r.FormValue("page"))
if err != nil {
page = 0
}
issues := []Issue{}
a.DB.Offset(page * 10).Limit(10).Find(&issues)
issueVoteRecord := IssueStatus{}
issueVoteRecord.PageCount = page
issueVoteRecord.Issues = make(map[Issue]int)
for _, x := range issues {
loggedVote := &VoteMap{}
a.DB.Find(loggedVote, &VoteMap{
IssueRefer: x.ID,
VoterRefer: voterID,
})
voteStatus := 1
if loggedVote.ID == 0 {
voteStatus = 2
}
if loggedVote.VoteStatus {
voteStatus = 0
}
issueVoteRecord.Issues[x] = voteStatus
}
err = templates.Funcs(funcMap).ExecuteTemplate(w, "vote.html", issueVoteRecord)
if err != nil {
fmt.Println(err)
}
}
//LogoutHandler removes the user from login.
func (a App) LogoutHandler(w http.ResponseWriter, r *http.Request) {
ses, err := a.Store.Get(r, "session")
if err != nil {
fmt.Println(err)
}
ses.Options.MaxAge = -1
err = ses.Save(r, w)
if err != nil {
fmt.Println(err)
}
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
}
// LoginHandler logs the login event and validates the user is valid.
// It also renders the login page.
func (a App) LoginHandler(rw http.ResponseWriter, r *http.Request) {
r.ParseForm()
var loginErr error
if r.FormValue("logon") == "Login" {
var voter *Voter
voter, loginErr = ValidateUser(a.DB, r.FormValue("username"), r.FormValue("password"), r.FormValue("totp"))
if loginErr == nil {
session, _ := a.Store.Get(r, "session")
session.Values["user_id"] = voter.ID
session.Values["username"] = voter.Username
if voter.IsAdmin {
session.Values["is_admin"] = true
}
a.Store.Save(r, rw, session)
http.Redirect(rw, r, "/", http.StatusTemporaryRedirect)
return
}
}
templates.ExecuteTemplate(rw, "login.html", loginErr)
}
// InviteHandler allows an authenticated voter to invite another voter
// to the site
func InviteHandler(rw http.ResponseWriter, r *http.Request) {
templates.ExecuteTemplate(rw, "invite.html", nil)
}
|
/*
Бот создан в рамках проекта Bablofil, подробнее тут
https://bablofil.ru/vnutrenniy-arbitraj-chast-2/
или на форуме https://forum.bablofil.ru/
*/
package main
import (
"sync"
)
/* Структуры для деревьев хранения стаканов */
type leaf struct {
left *leaf
price float64 // Depth level price
vol float64 // Depth level volume
right *leaf
}
/* По каждой паре храним два стакана, текущие лучшие цены из каждого,
объемы текущих лучших цен, пару и время последнего обновления
*/
type SymbolObj struct {
BTree *leaf // Bid depth
ATree *leaf // Ask depth
CurrB float64 //Best bid price
CurrA float64 // Best ask price
CurrBVol float64 // Best bid position volume
CurrAVol float64 //Best ask position volume
Symbol symbol_struct // Pair
LastUpdated string // Last update DT
}
/*
Ссылка на потенциальную сделку
*/
type DealObj struct {
S *SymbolObj // Pointer to SymbolObj - depth, rates etc.
Type string // Deal type (buy, sell)
MinCoins float64 // Min coins amount to buy|sell (calculates on demand)
}
/*
Эта структура данных олицетворяет цепь сделок, прибыль по ним и прочее.
Когда приходит время торговать, специальный указатель ссылается на экзмепляр такой структуры, и код создает/проверяет ордера в соответствии с ней.
*/
type ProfitObj struct {
Chain [CHAIN_LEN]*DealObj // Цепь сделок, которые нужно провести
Profit float64 // Потенциальная прибыль после выполнения сделок
Description string // Сформированная строка, которая выводится в лог для отладки и информации
Fits bool // Признак того, что объем каждой сделки в цепи содержит минимально нужный объем
MultyFactor float64 // Если объем сделок выше нашего минимального, то увеличить объем покупок до нашего максимального
Phase int32 // Какое звено chain сейчас исполняется
OrderId int64 // Какой ордер нужно отслеживать (если есть)
mx sync.Mutex // Для блокировки параллельного доступа
}
/* exchange info - структуры, репрезентующие exchangeInfo binance */
type limit_struct struct {
RateLimitType string `json:rateLimitType`
Interval string `json:interval`
Limit int32 `json:limit`
}
type symbol_struct struct {
Symbol string `json:symbol`
Status string `json:status`
BaseAsset string `json:baseAsset`
BaseAssetPrecision int32 `json:baseAssetPrecision`
QuoteAsset string `json:quoteAsset`
QuotePrecision int32 `json:quotePrecision`
OrderTypes []string `json:orderTypes`
IcebergAllowed bool `json:icebergAllowed`
Filters []interface{} `json:filters`
}
type exchangeInfo_struct struct {
Timezone string `json:timezone`
ServerTime int64 `json:serverTime`
RateLimits []limit_struct `json:rateLimits`
ExchangeFilters []string `json:exchangeFilters`
Symbols []symbol_struct `json:symbols`
}
/* Для парсинга данных о стаканах из сокетов*/
type partial_depth struct {
e string `json:"e"`
E int64 `json:"E"`
Symbol string `json:"s"`
U int64 `json:"U"`
Bids [][]string `json:"b"`
Asks [][]string `json:"a"`
}
/* Для парсинга rest depth*/
type Depth struct {
LastUpdateId int32 `json:"lastUpdateId"`
Bids [][]string `json:"bids"`
Asks [][]string `json:"asks"`
}
/* Получение ключа для подписки на user-data-stream */
type ListenKeyObj struct {
ListenKey string `json:"listenKey"`
}
/* Информация об созданном ордере, полученная через rest*/
type OrderResult struct {
Symbol string `json: "symbol"`
OrderId int64 `json: "orderId"`
ClientOrderId string `json: "clientOrderId"`
TransactTime int64 `json:"transactTime"`
Price string `json:"price"`
OrigQty string `json:"origQty"`
ExecutedQty string `json: "executedQty"`
CummulativeQuoteQty string `json: "cummulativeQuoteQty"`
Status string `json:"status"`
TimeInForce string `json:"timeInForce"`
Type string `json:"type"`
Side string `json:"side"`
}
/* Информация об созданном ордере, полученная через сокеты*/
type ExecutionReport struct {
eventType string `json:"e"` // Event type
EventTime int64 `json:"E"` // Event time
Symbol string `json:"s"` // Symbol
ClientOrderId string `json:"c"` // Client order ID
Side string `json:"S"` // Side
OrderType string `json:"o"` // Order type
TimeInForce string `json:"f"` // Time in force
Quantity string `json: "q"` // Order quantity
Price string `json: "p"` // Order price
StopPrice string `json:"P"` // Stop price
IcebergQuantity string `json:"F"` // Iceberg quantity
Dummy int64 `json:"g"` // Ignore
OriginalClientOrderId string `json:"C"` // Original client order ID; This is the ID of the order being canceled
ExecutionType string `json:"x"` // Current execution type
Status string `json:"X"` // Current order status
RejectReason string `json: "r"` // Order reject reason; will be an error code.
OrderId int64 `json:"i"` // Order ID
LastExecutedQuantity string `json: "l"` // Last executed quantity
CumulativeFilledQuantity string `json:"z"` // Cumulative filled quantity
LastExecutedPrice string `json:"L"` // Last executed price
ComissionAmount string `json:"n"` // Commission amount
ComissionAsset string `json: "N"` // Commission asset
TransactionTime int64 `json:"T"` // Transaction time
TradeId int64 `json:"t"` // Trade ID
Dummy2 int64 `json:"I"` // Ignore
IsWorking bool `json: "w"` // Is the order working? Stops will have
IsMaker bool `json:"m"` // Is this trade the maker side?
Dummy3 bool `json:"M"` // Ignore
OrderCreated int64 `json:"O"` // Order creation time
CumulativeQuoteQuantity string `json:"Z"` // Cumulative quote asset transacted quantity
LastQuoteQuantity string `json:"Y"` // Last quote asset transacted quantity (i.e. lastPrice * lastQty)
}
/* Внутренняя структура для хранения некоторых полей ордера */
type OrderInfo struct {
OrderId int64
Symbol string
Side string
SpentQty float64
GotQty float64
}
|
package main
// 迭代 求 n! 尾部有多少个零
func trailingZeroes(n int) int {
ans := 0
for n != 0 {
ans += n / 5
n = n / 5
}
return ans
}
/*
题目链接: https://leetcode-cn.com/problems/factorial-trailing-zeroes/comments/
*/
/*
总结
1. 要求n!有多少个零,就是求n!由多少个10相乘。
那么由于10由质因子2和5组成,那么我们只需要求n!有多少个因子2和因子5就可以了,再取二者的最小值就可以了。
又由于n!中,2的因子一定多于5的因子,所以我们只需要算5的因子。 (小伙伴可以验证下)
2. 如何算n!中5的因子呢?
我们注意到 [1,5]之间只有1个5,而[1,10]之间有2个5(5贡献1个,10贡献一个)
[1,30]里面有7个5。 (5,10,15,20,30分别贡献1个,而25贡献2个)
于是我们可以当做 (5,10,15,20,25,30先贡献1个,之后25再贡献1个)
于是就可以得到 n!中5个因子 = n/5 + n/25 + n / 125 + .... + n / (5^k) (k>=1,k∈Z)
*/
|
package auth
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01800101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:auth.018.001.01 Document"`
Message *ContractRegistrationRequestV01 `xml:"CtrctRegnReq"`
}
func (d *Document01800101) AddMessage() *ContractRegistrationRequestV01 {
d.Message = new(ContractRegistrationRequestV01)
return d.Message
}
// The ContractRegistrationRequest message is sent by the reporting party to the registration agent to initiate the registration of a new contract subject to currency control.
type ContractRegistrationRequestV01 struct {
// Characteristics shared by all individual items included in the message.
GroupHeader *iso20022.CurrencyControlHeader1 `xml:"GrpHdr"`
// Identifies the currency control contract details for which the registration is requested.
ContractRegistration []*iso20022.ContractRegistration1 `xml:"CtrctRegn"`
// Additional information that cannot be captured in the structured elements and/or any other specific block.
SupplementaryData []*iso20022.SupplementaryData1 `xml:"SplmtryData,omitempty"`
}
func (c *ContractRegistrationRequestV01) AddGroupHeader() *iso20022.CurrencyControlHeader1 {
c.GroupHeader = new(iso20022.CurrencyControlHeader1)
return c.GroupHeader
}
func (c *ContractRegistrationRequestV01) AddContractRegistration() *iso20022.ContractRegistration1 {
newValue := new(iso20022.ContractRegistration1)
c.ContractRegistration = append(c.ContractRegistration, newValue)
return newValue
}
func (c *ContractRegistrationRequestV01) AddSupplementaryData() *iso20022.SupplementaryData1 {
newValue := new(iso20022.SupplementaryData1)
c.SupplementaryData = append(c.SupplementaryData, newValue)
return newValue
}
|
package jdsfapi
import (
"fmt"
"github.com/hashicorp/consul/api"
"math/rand"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"time"
)
const consulHostEnv = "CONSUL_HOST"
const consulPortEnv ="CONSUL_PORT"
type RegistryClient struct {
Address string
Port int
Scheme string
Client *api.Client
}
var(
JDSFRegistryClient *RegistryClient
)
func NewRegistryClient() *RegistryClient {
registryClient := new (RegistryClient)
consulConfig :=JDSFGlobalConfig.Consul
host := os.Getenv(consulHostEnv)
port := os.Getenv(consulPortEnv)
if host !=""{
consulConfig.Address = host
}
if port !=""{
portValue ,err := strconv.ParseInt(port,10,32)
if err != nil{
println(err)
}else{
if portValue >0{
consulConfig.Port = int32(portValue)
}
}
}
registryClient.Port = int(consulConfig.Port)
registryClient.Address = consulConfig.Address
JDSFRegistryClient = registryClient
return registryClient
}
func (r *RegistryClient)GetConsulClient() *api.Client {
if r.Client != nil {
return r.Client
}
consulConfig :=JDSFGlobalConfig.Consul
defaultConfig := api.DefaultConfig()
consulPortStr := strconv.Itoa(int(consulConfig.Port))
defaultConfig.Address = consulConfig.Address+":"+consulPortStr
fmt.Println(defaultConfig.Address)
defaultConfig.Scheme = consulConfig.Scheme
client, err := api.NewClient(defaultConfig)
if err != nil{
fmt.Println(err)
return nil
}
r.Client = client
return client
}
func (r *RegistryClient)RegistryService() {
appConfig :=JDSFGlobalConfig.AppConfig
ConsulDiscoverConfig := JDSFGlobalConfig.Consul.Discover
portStr := strconv.Itoa(int(appConfig.ServerPort))
client := r.Client
if client == nil{
client = r.GetConsulClient()
}
agentService := new(api.AgentServiceRegistration)
agentService.Port = int(appConfig.ServerPort)
agentService.Address = appConfig.HostIp
agentService.Kind = ""
agentService.Name = appConfig.AppName
agentService.ID = ConsulDiscoverConfig.ServiceInstanceId
agentCheck :=new(api.AgentServiceCheck)
agentCheck.Name = appConfig.AppName
agentCheck.CheckID = ConsulDiscoverConfig.ServiceInstanceId
agentCheck.HTTP = "http://"+appConfig.HostIp+":"+portStr+ConsulDiscoverConfig.CheckUrl
agentCheck.Method = "GET"
agentCheck.Interval= "30s"
agentService.Check = agentCheck
regErr:=client.Agent().ServiceRegister(agentService)
if regErr!=nil{
fmt.Println(regErr)
}
}
func (r *RegistryClient)ServiceRequestLoadBlance(rawURL string) string {
reqURL, err := url.Parse(rawURL)
if err != nil {
fmt.Println(err)
return rawURL
}
serviceName := ""
serviceNameAndPort := reqURL.Host
serviceNameAndPortArray := strings.Split(serviceNameAndPort, ":")
if len(serviceNameAndPortArray) > 0 {
serviceName = serviceNameAndPortArray[0]
}
isMatch, err := regexp.MatchString("((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))", serviceName)
if isMatch {
return rawURL
}
client := r.Client
serviceEntry, _, err := client.Health().Service(serviceName, "", true, nil)
if err != nil {
return rawURL
}
if len(serviceEntry) == 0 {
fmt.Println("not found service name is ", serviceName)
return rawURL
}
service := new(api.ServiceEntry)
if len(serviceEntry) > 0 {
rand.Seed(time.Now().UnixNano())
serviceInstanceCount := len(serviceEntry)
serviceIndex := rand.Intn(serviceInstanceCount)
service = serviceEntry[serviceIndex]
}
if service.Service != nil {
requestFinalHost := service.Service.Address + ":" + strconv.Itoa(service.Service.Port)
reqURL.Host = requestFinalHost
return reqURL.String()
}
return rawURL
}
|
package tsrv
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00500101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:tsrv.005.001.01 Document"`
Message *UndertakingAmendmentV01 `xml:"UdrtkgAmdmnt"`
}
func (d *Document00500101) AddMessage() *UndertakingAmendmentV01 {
d.Message = new(UndertakingAmendmentV01)
return d.Message
}
// The UndertakingAmendment message is sent (and is thus issued) by the party that issued the undertaking. The message may be sent either directly to the beneficiary or via an advising party. The proposed undertaking amendment could be to a demand guarantee, standby letter of credit, or counter-undertaking (counter-guarantee or counter-standby). The message provides details on proposed changes to the undertaking, for example, to the expiry date, the amount, and terms and conditions of the undertaking. It may also be used to propose the termination or cancellation of the undertaking. Under practice and law, this communication binds the party issuing it. The message constitutes an operative financial instrument.
type UndertakingAmendmentV01 struct {
// Details related to the proposed undertaking amendment.
UndertakingAmendmentDetails *iso20022.Amendment1 `xml:"UdrtkgAmdmntDtls"`
// Additional information specific to the bank-to-bank communication.
BankToBankInformation []*iso20022.Max2000Text `xml:"BkToBkInf,omitempty"`
// Digital signature of the proposed undertaking amendment.
DigitalSignature []*iso20022.PartyAndSignature2 `xml:"DgtlSgntr,omitempty"`
}
func (u *UndertakingAmendmentV01) AddUndertakingAmendmentDetails() *iso20022.Amendment1 {
u.UndertakingAmendmentDetails = new(iso20022.Amendment1)
return u.UndertakingAmendmentDetails
}
func (u *UndertakingAmendmentV01) AddBankToBankInformation(value string) {
u.BankToBankInformation = append(u.BankToBankInformation, (*iso20022.Max2000Text)(&value))
}
func (u *UndertakingAmendmentV01) AddDigitalSignature() *iso20022.PartyAndSignature2 {
newValue := new(iso20022.PartyAndSignature2)
u.DigitalSignature = append(u.DigitalSignature, newValue)
return newValue
}
|
package terminal
import (
"fmt"
"strconv"
)
func CursorUp(n int) {
fmt.Print("\x1b[" + strconv.Itoa(n) + "A")
}
func CursorDown(n int) {
fmt.Print("\x1b[" + strconv.Itoa(n) + "B")
}
func CursorRight(n int) {
fmt.Print("\x1b[" + strconv.Itoa(n) + "C")
}
func CursorLeft(n int) {
fmt.Print("\x1b[" + strconv.Itoa(n) + "D")
}
|
package controller
import (
"database/sql"
"github.com/go-redis/redis/v8"
)
type Controller struct {
Rds *redis.Client
DB *sql.DB
}
|
/*
Copyright The Helm Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main // import "helm.sh/helm/v3/cmd/helm"
import (
"fmt"
"io"
"log"
"os"
"strings"
"github.com/spf13/cobra"
"sigs.k8s.io/yaml"
// Import to initialize client auth plugins.
_ "k8s.io/client-go/plugin/pkg/client/auth"
"helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/cli"
"helm.sh/helm/v3/pkg/kube"
kubefake "helm.sh/helm/v3/pkg/kube/fake"
"helm.sh/helm/v3/pkg/release"
"helm.sh/helm/v3/pkg/storage/driver"
)
var settings = cli.New()
func init() {
log.SetFlags(log.Lshortfile)
}
func debug(format string, v ...interface{}) {
if settings.Debug {
format = fmt.Sprintf("[debug] %s\n", format)
log.Output(2, fmt.Sprintf(format, v...))
}
}
func warning(format string, v ...interface{}) {
format = fmt.Sprintf("WARNING: %s\n", format)
fmt.Fprintf(os.Stderr, format, v...)
}
func main() {
// Setting the name of the app for managedFields in the Kubernetes client.
// It is set here to the full name of "helm" so that renaming of helm to
// another name (e.g., helm2 or helm3) does not change the name of the
// manager as picked up by the automated name detection.
kube.ManagedFieldsManager = "helm"
actionConfig := new(action.Configuration)
cmd, err := newRootCmd(actionConfig, os.Stdout, os.Args[1:])
if err != nil {
warning("%+v", err)
os.Exit(1)
}
// run when each command's execute method is called
cobra.OnInitialize(func() {
helmDriver := os.Getenv("HELM_DRIVER")
if err := actionConfig.Init(settings.RESTClientGetter(), settings.Namespace(), helmDriver, debug); err != nil {
log.Fatal(err)
}
if helmDriver == "memory" {
loadReleasesInMemory(actionConfig)
}
})
if err := cmd.Execute(); err != nil {
debug("%+v", err)
switch e := err.(type) {
case pluginError:
os.Exit(e.code)
default:
os.Exit(1)
}
}
}
// This function loads releases into the memory storage if the
// environment variable is properly set.
func loadReleasesInMemory(actionConfig *action.Configuration) {
filePaths := strings.Split(os.Getenv("HELM_MEMORY_DRIVER_DATA"), ":")
if len(filePaths) == 0 {
return
}
store := actionConfig.Releases
mem, ok := store.Driver.(*driver.Memory)
if !ok {
// For an unexpected reason we are not dealing with the memory storage driver.
return
}
actionConfig.KubeClient = &kubefake.PrintingKubeClient{Out: io.Discard}
for _, path := range filePaths {
b, err := os.ReadFile(path)
if err != nil {
log.Fatal("Unable to read memory driver data", err)
}
releases := []*release.Release{}
if err := yaml.Unmarshal(b, &releases); err != nil {
log.Fatal("Unable to unmarshal memory driver data: ", err)
}
for _, rel := range releases {
if err := store.Create(rel); err != nil {
log.Fatal(err)
}
}
}
// Must reset namespace to the proper one
mem.SetNamespace(settings.Namespace())
}
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package format contains types for defining language-specific formatting of
// values.
//
// This package is internal now, but will eventually be exposed after the API
// settles.
package format
import (
"fmt"
"gx/ipfs/QmVcxhXDbXjNoAdmYBWbY1eU67kQ8eZUHjG4mAYZUtZZu3/go-text/language"
)
// State represents the printer state passed to custom formatters. It provides
// access to the fmt.State interface and the sentence and language-related
// context.
type State interface {
fmt.State
// Language reports the requested language in which to render a message.
Language() language.Tag
// TODO: consider this and removing rune from the Format method in the
// Formatter interface.
//
// Verb returns the format variant to render, analogous to the types used
// in fmt. Use 'v' for the default or only variant.
// Verb() rune
// TODO: more info:
// - sentence context such as linguistic features passed by the translator.
}
// Formatter is analogous to fmt.Formatter.
type Formatter interface {
Format(state State, verb rune)
}
|
//+build wireinject
package service
import (
"sync"
"github.com/google/wire"
)
// Container contains all the services of the api.
// If you create a new service, be sure to add it in the Container and add its provider to the ServiceProviderSet
type Container struct {
Connection *Connection
Logger *Logger
Migrator *Migrator
}
var serviceProviderSet = wire.NewSet(
wire.Struct(new(Container), "*"),
ProvideConnection,
ProvideLogger,
ProvideMigrator,
)
var containerOnce sync.Once
var containerInstance *Container
func initializeContainer() (*Container, error) {
wire.Build(serviceProviderSet)
return &Container{}, nil
}
// GetContainer returns always the same Container using a thread-safe singleton
func GetContainer() (*Container, error) {
var err error = nil
containerOnce.Do(func() {
containerInstance, err = initializeContainer()
})
if err != nil {
return nil, err
}
return containerInstance, nil
}
|
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/opentracing/opentracing-go"
openlog "github.com/opentracing/opentracing-go/log"
"gopkg.in/oauth2.v3/utils/uuid"
"log"
"net/http"
"sort"
"strconv"
)
// PingPong return a pong
func PingPong(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
}
// ShowHighScores returns a specific user and playlist highscore
func ShowHighScores(ctx context.Context, user string, playlist string, c *gin.Context) ([]Score, int) {
span, _ := opentracing.StartSpanFromContext(ctx, "ShowHighScores")
span.SetTag(method, "ShowHighScores")
defer span.Finish()
key := user + ":" + playlist
res, err := db.Cmd(keyExists, key).Int()
if err != nil {
log.Fatal(err)
}
exists := res != 0
var redisResult []Score
if !exists {
span.LogFields(
openlog.String(statusCode, "404"),
openlog.String(spanBody, "not found"),
)
span.Finish()
localUUID := createGUID()
notFoundError := ErrorModel{
Message: "Could not find combination of user: " + user + " & list: " + playlist,
UniqueCode: localUUID}
respondWithJSON(ctx, c, http.StatusNotFound, notFoundError)
return nil, 0
}
result, err := db.Cmd("HGETALL", key).Map()
if err != nil {
log.Fatal(err)
}
for drink, score := range result {
i, err := strconv.Atoi(score)
if err != nil {
log.Fatal("cannot convert string to int")
}
newScore := Score{
Drink: drink,
Rolled: i}
redisResult = append(redisResult, newScore)
}
body, _ := json.Marshal(redisResult)
span.LogFields(
openlog.String(statusCode, "200"),
openlog.String(spanBody, string(body)),
)
sort.Slice(redisResult, func(i, j int) bool {
return redisResult[i].Rolled > redisResult[j].Rolled
})
return redisResult, http.StatusOK
}
// CreateNewHighScore creates a new highscore for a user and playlist combination
func CreateNewHighScore(user string, playlist string, drink string) {
key := user + ":" + playlist
exists := keyExistsInRedis(key)
if !exists {
err := db.Cmd(keySet, key, drink, 1).Err
if err != nil {
log.Fatal(err)
}
IncreaseGlobalCount(drink)
return
}
err := db.Cmd(keyIncrease, key, drink, 1).Err
if err != nil {
log.Fatal(err)
}
go IncreaseGlobalCount(drink)
return
}
// IncreaseGlobalCount global should be increased with every normal increase
func IncreaseGlobalCount(drink string) {
key := GLOBALNAME + ":" + GLOBALLIST
exists := keyExistsInRedis(key)
if !exists {
err := db.Cmd(keySet, key, drink, 1).Err
if err != nil {
log.Fatal(err)
}
return
}
err := db.Cmd(keyIncrease, key, drink, 1).Err
if err != nil {
log.Fatal(err)
}
return
}
func ReadQueue() {
ch, _ := rabbitConn.Channel()
q, _ := ch.QueueDeclare(
"highscores", // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
msgs, _ := ch.Consume(
q.Name, // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
forever := make(chan bool)
go func() {
for msg := range msgs {
var highscore HighScoreObject
err := json.Unmarshal(msg.Body, &highscore)
if err != nil {
print(err)
}
go CreateNewHighScore(highscore.Username, highscore.Playlist, highscore.Result)
}
}()
<-forever
}
func createGUID() string {
b, _ := uuid.NewRandom()
uuid := fmt.Sprintf("%x-%x-%x-%x-%x",
b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
return uuid
}
func keyExistsInRedis(key string) bool {
res, err := db.Cmd(keyExists, key).Int()
if err != nil {
log.Fatal(err)
}
exists := res != 0
return exists
}
|
package cfg
import (
"strings"
)
func emptyGetter(keys ...string) interface{} {
return nil
}
var values = map[string]interface{}{
"Str": "foobar",
"Int": 1,
"Nested.Level2_Int": 2,
"str": "foobar",
"int": 1,
"int64": int64(1),
"uint16": uint16(1),
}
func getter(keys ...string) interface{} {
return values[strings.Join(keys, ".")]
}
|
/*
* @lc app=leetcode.cn id=842 lang=golang
*
* [842] 将数组拆分成斐波那契序列
*/
package main
import (
"math"
)
// @lc code=start
func splitIntoFibonacci(num string) []int {
ret := []int{}
var backtrack func(index, sum, pre int) bool
backtrack = func(index, sum, pre int) bool {
if index == len(num) {
return len(ret) >= 3
}
cur := 0
for i := index; i < len(num); i++ {
if i > index && num[index] == '0' {
break
}
cur = cur*10 + int(num[i]-'0')
if cur > math.MaxInt32 {
break
}
if len(ret) >= 2 {
if cur < sum {
continue
}
if cur > sum {
break
}
}
ret = append(ret, cur)
if backtrack(i+1, pre+cur, cur) {
return true
}
ret = ret[:len(ret)-1]
}
return false
}
backtrack(0, 0, 0)
return ret
}
// func main() {
// fmt.Println(splitIntoFibonacci("1101111"))
// fmt.Println(splitIntoFibonacci("112358130"))
// }
// @lc code=end
|
package volume
import (
"errors"
"fmt"
"strconv"
"github.com/Huawei/eSDK_K8S_Plugin/src/storage/oceanstor/client"
"github.com/Huawei/eSDK_K8S_Plugin/src/storage/oceanstor/smartx"
"github.com/Huawei/eSDK_K8S_Plugin/src/utils/log"
)
const (
HYPERMETROPAIR_HEALTH_STATUS_FAULT = "2"
HYPERMETROPAIR_RUNNING_STATUS_NORMAL = "1"
HYPERMETROPAIR_RUNNING_STATUS_TO_SYNC = "100"
HYPERMETROPAIR_RUNNING_STATUS_SYNCING = "23"
HYPERMETROPAIR_RUNNING_STATUS_UNKNOWN = "0"
HYPERMETROPAIR_RUNNING_STATUS_PAUSE = "41"
HYPERMETROPAIR_RUNNING_STATUS_ERROR = "94"
HYPERMETROPAIR_RUNNING_STATUS_INVALID = "35"
HYPERMETRODOMAIN_RUNNING_STATUS_NORMAL = "1"
)
type Base struct {
cli *client.Client
metroRemoteCli *client.Client
replicaRemoteCli *client.Client
}
func (p *Base) commonPreCreate(params map[string]interface{}) error {
analyzers := [...]func(map[string]interface{}) error{
p.getAllocType,
p.getCloneSpeed,
p.getPoolID,
p.getQoS,
}
for _, analyzer := range analyzers {
err := analyzer(params)
if err != nil {
return err
}
}
return nil
}
func (p *Base) getAllocType(params map[string]interface{}) error {
if v, exist := params["alloctype"].(string); exist && v == "thick" {
params["alloctype"] = 0
} else {
params["alloctype"] = 1
}
return nil
}
func (p *Base) getCloneSpeed(params map[string]interface{}) error {
_, cloneExist := params["clonefrom"].(string)
_, srcVolumeExist := params["sourcevolumename"].(string)
_, srcSnapshotExist := params["sourcesnapshotname"].(string)
if !(cloneExist || srcVolumeExist || srcSnapshotExist) {
return nil
}
if v, exist := params["clonespeed"].(string); exist && v != "" {
speed, err := strconv.Atoi(v)
if err != nil || speed < 1 || speed > 4 {
return fmt.Errorf("error config %s for clonespeed", v)
}
params["clonespeed"] = speed
} else {
params["clonespeed"] = 3
}
return nil
}
func (p *Base) getPoolID(params map[string]interface{}) error {
poolName, exist := params["storagepool"].(string)
if !exist || poolName == "" {
return errors.New("must specify storage pool to create volume")
}
pool, err := p.cli.GetPoolByName(poolName)
if err != nil {
log.Errorf("Get storage pool %s info error: %v", poolName, err)
return err
}
if pool == nil {
return fmt.Errorf("Storage pool %s doesn't exist", poolName)
}
params["poolID"] = pool["ID"].(string)
return nil
}
func (p *Base) getQoS(params map[string]interface{}) error {
if v, exist := params["qos"].(string); exist && v != "" {
qos, err := smartx.VerifyQos(v)
if err != nil {
log.Errorf("Verify qos %s error: %v", v, err)
return err
}
params["qos"] = qos
}
return nil
}
func (p *Base) getRemotePoolID(params map[string]interface{}, remoteCli *client.Client) (string, error) {
remotePool, exist := params["remotestoragepool"].(string)
if !exist || len(remotePool) == 0 {
msg := "no remote pool is specified"
log.Errorln(msg)
return "", errors.New(msg)
}
pool, err := remoteCli.GetPoolByName(remotePool)
if err != nil {
log.Errorf("Get remote storage pool %s info error: %v", remotePool, err)
return "", err
}
if pool == nil {
return "", fmt.Errorf("remote storage pool %s doesn't exist", remotePool)
}
return pool["ID"].(string), nil
}
func (p *Base) preExpandCheckCapacity(params, taskResult map[string]interface{}) (map[string]interface{}, error) {
// check the local pool
localParentName := params["localParentName"].(string)
expandSize := params["expandSize"].(int64)
pool, err := p.cli.GetPoolByName(localParentName)
if err != nil || pool == nil {
msg := fmt.Sprintf("Get storage pool %s info error: %v", localParentName, err)
log.Errorf(msg)
return nil, errors.New(msg)
}
freeCapacity, _ := strconv.ParseInt(pool["USERFREECAPACITY"].(string), 10, 64)
if freeCapacity < expandSize {
msg := fmt.Sprintf("storage pool %s free capacity %s is not enough to expand to %v",
localParentName, pool["USERFREECAPACITY"], expandSize)
log.Errorln(msg)
return nil, errors.New(msg)
}
return nil, nil
}
func (p *Base) getSnapshotReturnInfo(snapshot map[string]interface{}, snapshotSize int64) map[string]interface{} {
snapshotCreated, _ := strconv.ParseInt(snapshot["TIMESTAMP"].(string), 10, 64)
snapshotSizeBytes := snapshotSize * 512
return map[string]interface{}{
"CreationTime": snapshotCreated,
"SizeBytes": snapshotSizeBytes,
"ParentID": snapshot["PARENTID"].(string),
}
}
func (p *Base) createReplicationPair(params, taskResult map[string]interface{}) (map[string]interface{}, error) {
resType := taskResult["resType"].(int)
remoteDeviceID := taskResult["remoteDeviceID"].(string)
var localID string
var remoteID string
if resType == 11 {
localID = taskResult["localLunID"].(string)
remoteID = taskResult["remoteLunID"].(string)
} else {
localID = taskResult["localFSID"].(string)
remoteID = taskResult["remoteFSID"].(string)
}
data := map[string]interface{}{
"LOCALRESID": localID,
"LOCALRESTYPE": resType,
"REMOTEDEVICEID": remoteDeviceID,
"REMOTERESID": remoteID,
"REPLICATIONMODEL": 2, // asynchronous replication
"SYNCHRONIZETYPE": 2, // timed wait after synchronization begins
"SPEED": 4, // highest speed
}
replicationSyncPeriod, exist := params["replicationSyncPeriod"]
if exist {
data["TIMINGVAL"] = replicationSyncPeriod
}
vStorePairID, exist := taskResult["vStorePairID"]
if exist {
data["VSTOREPAIRID"] = vStorePairID
}
pair, err := p.cli.CreateReplicationPair(data)
if err != nil {
log.Errorf("Create replication pair error: %v", err)
return nil, err
}
pairID := pair["ID"].(string)
err = p.cli.SyncReplicationPair(pairID)
if err != nil {
log.Errorf("Sync replication pair %s error: %v", pairID, err)
p.cli.DeleteReplicationPair(pairID)
return nil, err
}
return nil, nil
}
func (p *Base) getRemoteDeviceID(deviceSN string) (string, error) {
remoteDevice, err := p.cli.GetRemoteDeviceBySN(deviceSN)
if err != nil {
log.Errorf("Get remote device %s error: %v", deviceSN, err)
return "", err
}
if remoteDevice == nil {
msg := fmt.Sprintf("Remote device of SN %s does not exist", deviceSN)
log.Errorln(msg)
return "", errors.New(msg)
}
if remoteDevice["HEALTHSTATUS"] != REMOTE_DEVICE_HEALTH_STATUS ||
remoteDevice["RUNNINGSTATUS"] != REMOTE_DEVICE_RUNNING_STATUS_LINK_UP {
msg := fmt.Sprintf("Remote device %s status is not normal", deviceSN)
log.Errorln(msg)
return "", errors.New(msg)
}
return remoteDevice["ID"].(string), nil
}
|
package gateway
import (
"bytes"
"testing"
)
func TestMac_MarshalText(t *testing.T) {
m := Mac{1, 2, 3, 4, 5, 6, 7, 8}
text, err := m.MarshalText()
if err != nil {
t.Error(err)
}
if !bytes.Equal(text, []byte("0102030405060708")) {
t.Errorf("Expected text to be 12345678 but was %s", string(text))
}
}
func TestMac_UnmarshalText(t *testing.T) {
m := Mac{}
err := m.UnmarshalText([]byte("0102030405060708"))
if err != nil {
t.Error(err)
}
if m.String() != "0102030405060708" {
t.Errorf("Expected mac to be 0102030405060708 but was %s", m.String())
}
}
|
package depth
import s "github.com/SimonRichardson/depth/selectors"
type transaction struct {
list *List
stash s.Iterator
}
func NewTransaction() s.Transaction {
return &transaction{
list: NewList(),
}
}
func (t *transaction) Undo() (s.Action, bool) {
if action, ok := t.list.Left(); ok {
return action, action.Revert()
}
return nil, false
}
func (t *transaction) Redo() (s.Action, bool) {
if action, ok := t.list.Right(); ok {
return action, action.Commit()
}
return nil, false
}
func (t *transaction) Commit() bool {
t.stash = t.list.LeftIter()
iter := t.stash.Clone()
for iter.HasNext() {
action := iter.Next()
if !action.Commit() {
return false
}
}
return true
}
func (t *transaction) Revert() bool {
if t.stash == nil {
return false
}
var (
iter = t.stash
list = NewList()
)
for iter.HasNext() {
action := iter.Next()
if !action.Revert() {
return false
}
list.Push(action)
}
t.list = list
t.stash = nil
return true
}
type transactionReadWriter struct {
transaction *transaction
}
func NewTransactionReadWriter(t *transaction) *transactionReadWriter {
return &transactionReadWriter{
transaction: t,
}
}
func (t *transactionReadWriter) Read(p []byte) (int, error) {
return -1, nil
}
func (t *transactionReadWriter) Write(p []byte) (int, error) {
return -1, nil
}
|
package controller
import (
"encoding/json"
"time"
"github.com/therecipe/qt/core"
"github.com/therecipe/qt/internal/examples/showcases/wallet/files/model"
)
var FilesController *filesController
type filesController struct {
core.QObject
_ func() `constructor:"init"`
_ *model.FilesModel `property:"model"`
}
func (c *filesController) init() {
FilesController = c
c.SetModel(model.NewFilesModel(nil))
go c.loop()
}
func (c *filesController) loop() {
for range time.NewTicker(1 * time.Second).C {
if DEMO {
var df []model.File
json.Unmarshal([]byte(DEMO_FILES), &df)
c.Model().UpdateWith(df)
}
}
}
|
package main
import (
"encoding/json"
"fmt"
"os"
"time"
"go.uber.org/zap/zapcore"
"go.uber.org/zap"
)
func main() {
fmt.Printf("*** Build a logger from a json\n\n")
rawJSONConfig := []byte(`{
"level": "info",
"encoding": "console",
"outputPaths": ["stdout", "/tmp/logs"],
"errorOutputPaths": ["/tmp/errorlogs"],
"initialFields": {"initFieldKey": "fieldValue"},
"encoderConfig": {
"messageKey": "message",
"levelKey": "level",
"nameKey": "logger",
"timeKey": "time",
"callerKey": "logger",
"stacktraceKey": "stacktrace",
"callstackKey": "callstack",
"errorKey": "error",
"timeEncoder": "iso8601",
"fileKey": "file",
"levelEncoder": "capitalColor",
"durationEncoder": "second",
"callerEncoder": "full",
"nameEncoder": "full",
"sampling": {
"initial": "3",
"thereafter": "10"
}
}
}`)
config := zap.Config{}
if err := json.Unmarshal(rawJSONConfig, &config); err != nil {
panic(err)
}
logger, err := config.Build()
if err != nil {
panic(err)
}
logger.Debug("This is a DEBUG message")
logger.Info("This should have an ISO8601 based time stamp")
logger.Warn("This is a WARN message")
logger.Error("This is an ERROR message")
//logger.Fatal("This is a FATAL message") // would exit if uncommented
//logger.DPanic("This is a DPANIC message") // would exit if uncommented
const url = "http://example.com"
logger.Info("Failed to fetch URL.",
zap.String("url", url),
zap.Int("attempt", 3),
zap.Duration("backoff", time.Second),
)
fmt.Printf("\n*** Using a JSON encoder, at debug level, sending output to stdout, no key specified\n\n")
logger, _ = zap.Config{
Encoding: "json",
Level: zap.NewAtomicLevelAt(zapcore.DebugLevel),
OutputPaths: []string{"stdout"},
}.Build()
logger.Debug("This is a DEBUG message")
logger.Info("This is an INFO message")
logger.Info("This is an INFO message with fields", zap.String("region", "us-west"), zap.Int("id", 2))
fmt.Printf("\n*** Using a JSON encoder, at debug level, sending output to stdout, message key only specified\n\n")
logger, _ = zap.Config{
Encoding: "json",
Level: zap.NewAtomicLevelAt(zapcore.DebugLevel),
OutputPaths: []string{"stdout"},
EncoderConfig: zapcore.EncoderConfig{
MessageKey: "message",
},
}.Build()
logger.Debug("This is a DEBUG message")
logger.Info("This is an INFO message")
logger.Info("This is an INFO message with fields", zap.String("region", "us-west"), zap.Int("id", 2))
fmt.Printf("\n*** Using a JSON encoder, at debug level, sending output to stdout, all possible keys specified\n\n")
cfg := zap.Config{
Encoding: "json",
Level: zap.NewAtomicLevelAt(zapcore.DebugLevel),
OutputPaths: []string{"stdout"},
EncoderConfig: zapcore.EncoderConfig{
MessageKey: "message",
LevelKey: "level",
EncodeLevel: zapcore.CapitalLevelEncoder,
TimeKey: "time",
EncodeTime: zapcore.ISO8601TimeEncoder,
CallerKey: "caller",
EncodeCaller: zapcore.ShortCallerEncoder,
},
}
logger, _ = cfg.Build()
logger.Debug("This is a DEBUG message")
logger.Info("This is an INFO message")
logger.Info("This is an INFO message with fields", zap.String("region", "us-west"), zap.Int("id", 2))
fmt.Printf("\n*** Same logger with console logging enabled instead\n\n")
logger.WithOptions(
zap.WrapCore(func(zapcore.Core) zapcore.Core {
return zapcore.NewCore(zapcore.NewConsoleEncoder(cfg.EncoderConfig), zapcore.AddSync(os.Stderr), zapcore.DebugLevel)
}),
).Info("This is an INFO message")
}
|
package main
import "fmt"
func multipicao(a, b int) int {
return a * b
}
func exec(funcao func(int, int) int, parametro1, parametro2 int) int {
return funcao(parametro1, parametro2)
}
func main() {
resultado := exec(multipicao, 4, 3)
fmt.Println("Resultado:", resultado)
}
|
package utils
import (
"errors"
"github.com/darkliquid/leader1/database"
"strings"
"time"
)
func LikeTrack(nick, track string) (bool, error) {
db, err := database.DB()
if err != nil {
return false, err
}
if strings.TrimSpace(nick) == "" {
return false, errors.New("Empty nick")
}
if strings.TrimSpace(track) == "" {
return false, errors.New("Empty track")
}
_, err = db.Exec("INSERT INTO likelogs (type, user, song, date) VALUES ('like', ?, ?, ?)", nick, track, time.Now().Unix())
if err != nil {
logger.Printf("DB ERROR: %s", err.Error())
return false, err
}
return true, nil
}
func HateTrack(nick, track string) (bool, error) {
db, err := database.DB()
if err != nil {
return false, err
}
if strings.TrimSpace(nick) == "" {
return false, errors.New("Empty nick")
}
if strings.TrimSpace(track) == "" {
return false, errors.New("Empty track")
}
_, err = db.Exec("INSERT INTO likelogs (type, user, song, date) VALUES ('dislike', ?, ?, ?)", nick, track, time.Now().Unix())
if err != nil {
logger.Printf("DB ERROR: %s", err.Error())
return false, err
}
return true, nil
}
func Request(nick, request string) (bool, error) {
db, err := database.DB()
if err != nil {
return false, err
}
if strings.TrimSpace(nick) == "" {
return false, errors.New("Empty nick")
}
if strings.TrimSpace(request) == "" {
return false, errors.New("Empty request")
}
_, err = db.Exec("INSERT INTO requests (user, song, date) VALUES (?, ?, ?)", nick, request, time.Now().Unix())
if err != nil {
logger.Printf("DB ERROR: %s", err.Error())
return false, err
}
return true, nil
}
|
package server
import (
"net/http"
"github.com/gorilla/mux"
)
type API2 struct {
Mux http.Handler
}
func NewAPI2() *API2 {
m := mux.NewRouter()
a := &API2{
Mux: m,
}
return a
}
|
package main
import (
"math/rand"
"os"
"time"
"k8s.io/component-base/logs"
"k8s.io/kubernetes/cmd/cloud-controller-manager/app"
_ "k8s.io/component-base/metrics/prometheus/clientgo" // load all the prometheus client-go plugins
_ "k8s.io/component-base/metrics/prometheus/version" // for version metric registration
_ "github.com/exoscale/exoscale-cloud-controller-manager/exoscale"
)
func main() {
rand.Seed(time.Now().UnixNano())
command := app.NewCloudControllerManagerCommand()
logs.InitLogs()
defer logs.FlushLogs()
if err := command.Execute(); err != nil {
os.Exit(1)
}
}
|
/*
Copyright 2021 The KubeDiag Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package executor
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os/exec"
"syscall"
"time"
"github.com/go-logr/logr"
"github.com/kubediag/kubediag/pkg/processors"
)
// CommandExecutorRequest is the request body data struct of command executor.
type CommandExecutorRequest struct {
// Parameter is the parameter for executing a command.
Parameter string `json:"parameter"`
}
// CommandExecutorRequestParameter is the parameter for executing a command.
type CommandExecutorRequestParameter struct {
// Command represents a command being prepared and run.
Command string `json:"command"`
// Args is arguments to the command.
Args []string `json:"args,omitempty"`
// Number of seconds after which the command times out.
// Defaults to 30 seconds. Minimum value is 1.
TimeoutSeconds *int32 `json:"timeoutSeconds,omitempty"`
}
// CommandExecutorResponse is the response body data struct of command executor.
type CommandExecutorResponse struct {
// Stdout is standard output of the command.
Stdout string `json:"stdout,omitempty"`
// Stderr is standard error of the command.
Stderr string `json:"stderr,omitempty"`
}
// TODO: Support script type operations.
// commandExecutor handles request for running specified command and respond with command result.
type commandExecutor struct {
// Context carries values across API boundaries.
context.Context
// Logger represents the ability to log messages.
logr.Logger
// commandExecutorEnabled indicates whether commandExecutor is enabled.
commandExecutorEnabled bool
}
// NewCommandExecutor creates a new commandExecutor.
func NewCommandExecutor(
ctx context.Context,
logger logr.Logger,
commandExecutorEnabled bool,
) processors.Processor {
return &commandExecutor{
Context: ctx,
Logger: logger,
commandExecutorEnabled: commandExecutorEnabled,
}
}
// Handler handles http requests for executing a command.
func (ce *commandExecutor) Handler(w http.ResponseWriter, r *http.Request) {
if !ce.commandExecutorEnabled {
http.Error(w, fmt.Sprintf("command executor is not enabled"), http.StatusUnprocessableEntity)
return
}
switch r.Method {
case "POST":
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, fmt.Sprintf("unable to read request body: %v", err), http.StatusBadRequest)
return
}
defer r.Body.Close()
var commandExecutorRequest CommandExecutorRequest
err = json.Unmarshal(body, &commandExecutorRequest)
if err != nil {
http.Error(w, fmt.Sprintf("unable to unmarshal request body: %v", err), http.StatusNotAcceptable)
return
}
var parameter CommandExecutorRequestParameter
err = json.Unmarshal([]byte(commandExecutorRequest.Parameter), ¶meter)
if err != nil {
http.Error(w, fmt.Sprintf("unable to unmarshal command executor request parameter: %v", err), http.StatusNotAcceptable)
return
}
var commandExecutorResponse CommandExecutorResponse
stdout, stderr, err := ce.executeCommand(parameter.Command, parameter.Args, parameter.TimeoutSeconds)
if stdout != "" {
commandExecutorResponse.Stdout = stdout
}
if stderr != "" {
commandExecutorResponse.Stderr = stderr
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data, err := json.Marshal(commandExecutorResponse)
if err != nil {
http.Error(w, fmt.Sprintf("failed to marshal command executor response: %v", err), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
default:
http.Error(w, fmt.Sprintf("method %s is not supported", r.Method), http.StatusMethodNotAllowed)
}
}
// RunCommandExecutor runs the command with timeout.
// It returns stdout, stderr and an error.
func (ce *commandExecutor) executeCommand(name string, args []string, timeoutSeconds *int32) (string, string, error) {
if name == "" {
return "", "", fmt.Errorf("invalid command name")
}
var buf bytes.Buffer
cmd := exec.Command(name, args...)
// Setting a new process group id to avoid suicide.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Stdout = &buf
cmd.Stderr = &buf
err := cmd.Start()
if err != nil {
return "", "", err
}
// Wait and signal completion of command.
done := make(chan error)
go func() {
done <- cmd.Wait()
}()
var timeout <-chan time.Time
if timeoutSeconds != nil {
timeout = time.After(time.Duration(*timeoutSeconds) * time.Second)
} else {
timeout = time.After(time.Duration(processors.DefaultTimeoutSeconds) * time.Second)
}
select {
// Kill the process if timeout happened.
case <-timeout:
// Kill the process and all of its children with its process group id.
// TODO: Kill timed out process on failure.
pgid, err := syscall.Getpgid(cmd.Process.Pid)
if err != nil {
ce.Error(err, "failed to get process group id on command timed out", "command", name)
} else {
err = syscall.Kill(-pgid, syscall.SIGKILL)
if err != nil {
ce.Error(err, "failed to kill process on command timed out", "command", name)
}
}
return "", "", fmt.Errorf("command %v timed out", name)
// Set output and error if command completed before timeout.
case err := <-done:
if err != nil {
if cmd.Stderr != nil {
return "", "", fmt.Errorf(buf.String())
}
return "", "", err
}
return buf.String(), "", nil
}
}
|
package services
import (
"crypto/rsa"
"fmt"
jwt "github.com/dgrijalva/jwt-go"
"github.com/RicardoCampos/goauth/oauth2"
)
type tokenPayload struct {
Issuer string `json:"iss"`
Scope string `json:"scope"`
}
func signToken(input jwt.StandardClaims, rsaKey *rsa.PrivateKey) (string, error) {
// get the signing alg
alg := jwt.GetSigningMethod("RS512")
if alg == nil {
return "Couldn't find signing method", fmt.Errorf("Couldn't find signing method: %v", "RS512")
}
// create a new token
token := jwt.NewWithClaims(alg, input)
// sign it
out, err := token.SignedString(rsaKey)
if err == nil {
return out, nil
}
return fmt.Sprintf("Error signing token: %v", err), fmt.Errorf("Error signing token: %v", err)
}
func validateToken(r oauth2.ReferenceToken, key *rsa.PublicKey) bool {
if r == nil {
return false
}
// expiry check
if r.Expiry() < oauth2.GetNowInEpochTime() {
return false
}
token, err := jwt.Parse(r.AccessToken(), func(token *jwt.Token) (interface{}, error) {
// Validate algorithm
// TODO: we load by `kid` to support multiple certs
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
// TODO: return typed error
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return key, nil
})
if err != nil {
return false
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
// Because we are paranoid, check that the data in the token matches the convenience fields in the reference token (in case database has compromises)
if claims["jti"] != r.TokenID() {
return false
}
if claims["exp"] != float64(r.Expiry()) { //TODO: raise PR as this is a bug. All inputs are int64 but it gets mapped to float64
return false
}
if claims["sub"] != r.ClientID() {
return false
}
return true
}
return false
}
|
package reset
import (
"os"
"github.com/devspace-cloud/devspace/pkg/devspace/dependency"
"github.com/devspace-cloud/devspace/pkg/util/factory"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
type dependenciesCmd struct {
}
func newDependenciesCmd(f factory.Factory) *cobra.Command {
cmd := &dependenciesCmd{}
dependenciesCmd := &cobra.Command{
Use: "dependencies",
Short: "Resets the dependencies cache",
Long: `
#######################################################
############ devspace reset dependencies ##############
#######################################################
Deletes the complete dependency cache
Examples:
devspace reset dependencies
#######################################################
`,
Args: cobra.NoArgs,
RunE: func(cobraCmd *cobra.Command, args []string) error {
return cmd.RunResetDependencies(f, cobraCmd, args)
}}
return dependenciesCmd
}
// RunResetDependencies executes the reset dependencies command logic
func (cmd *dependenciesCmd) RunResetDependencies(f factory.Factory, cobraCmd *cobra.Command, args []string) error {
log := f.GetLog()
err := os.RemoveAll(dependency.DependencyFolderPath)
if err != nil {
return errors.Wrapf(err, "delete %s", dependency.DependencyFolderPath)
}
log.Done("Successfully reseted the dependency cache")
return nil
}
|
package KMP
/*
字符串匹配。给你两个字符串,寻找其中一个字符串是否包含另一个字符串,如果包含,返回包含的起始位置。
字符串长度分别为n,m (n > m).
算法复杂度O(n + m).
充分利用了目标字符串ptr的性质(比如里面部分字符串的重复性,即使不存在重复字段,在比较时,实现最大的移动量)。
考察目标字符串ptr:
ababaca
这里我们要计算一个长度为m的转移函数next。
next数组的含义就是一个固定字符串的最长前缀和最长后缀相同的长度。
比如:abcjkdabc,那么这个数组的最长前缀和最长后缀相同必然是abc。
cbcbc,最长前缀和最长后缀相同是cbc。
abcbc,最长前缀和最长后缀相同是不存在的。
**注意最长前缀:是说以第一个字符开始,但是不包含最后一个字符。比如aaaa相同的最长前缀和最长后缀是aaa。**
对于目标字符串ptr = ababaca,长度是7,所以next[0],next[1],next[2],next[3],next[4],next[5],next[6]分别计算的是
a,ab,aba,abab,ababa,ababac,ababaca的相同的最长前缀和最长后缀的长度。
由于a,ab,aba,abab,ababa,ababac,ababaca的相同的最长前缀和最长后缀是“”,“”,“a”,“ab”,“aba”,“”,“a”,
所以next数组的值是[-1,-1,0,1,2,-1,0],这里-1表示不存在,0表示存在长度为1,2表示存在长度为3。这是为了和代码相对应。
*** 求解next过程:
1. 对于字符串ptr, 第一位是-1(p=0,k=-1, next[p]=k);
2. p,k 从第二位开始(数组下标为1, p=1,k=0, 当第k位等于第p位时或者k==-1时,next[p]=k, p+=1,k+=1;继续步骤2;
3. 否则回溯k=next[k],继续步骤2,直到p = len(ptr) - 1;
*/
// calNext getNext,同一种思想,两种不同的写法
func calNext(str string) []int {
slen := len(str)
next := make([]int, slen)
next[0] = -1
k := -1
for q := 1; q < slen; q ++ {
for k > -1 && str[k+1] != str[q] {
k = next[k]
}
if str[k+1] == str[q] {
k += 1
}
next[q] = k
}
return next
}
func KMP(src, reg string) int {
next := calNext(reg)
k := -1
for i := 0; i < len(src); i ++ {
for k > -1 && reg[k+1] != src[i] {
k = next[k]
}
if reg[k+1] == src[i] {
k += 1
}
if k == len(reg) - 1 {
return i - k
}
}
return -1
}
func getNext(str string) []int {
slen := len(str)
next := make([]int, slen)
k := -1
for j := 0; j < slen; {
if k == -1 || str[j] == str[k] {
next[j] = k
j, k = j+1, k+1
} else {
k = next[k]
}
}
return next
}
func KMP_BASIC(src, reg string) int {
next := getNext(reg)
i, j := 0, 0
for i < len(src) && j < len(reg) {
if j == -1 || src[i] == reg[j] {
i, j = i+1, j+1
} else {
j = next[j]
}
}
if j == len(reg) {
return i - j
}
return -1
}
|
/*
Description
Uniform Resource Identifiers (or URIs) are strings like http://icpc.baylor.edu/icpc/, mailto:foo@bar.org, ftp://127.0.0.1/pub/linux, or even just readme.txt that are used to identify a resource, usually on the Internet or a local computer. Certain characters are reserved within URIs, and if a reserved character is part of an identifier then it must be percent-encoded by replacing it with a percent sign followed by two hexadecimal digits representing the ASCII code of the character. A table of seven reserved characters and their encodings is shown below. Your job is to write a program that can percent-encode a string of characters.
Character Encoding
" " (space) %20
"!" (exclamation point) %21
"$" (dollar sign) %24
"%" (percent sign) %25
"(" (left parenthesis) %28
")" (right parenthesis) %29
"*" (asterisk) %2a
Input
The input consists of one or more strings, each 1–79 characters long and on a line by itself, followed by a line containing only "#" that signals the end of the input. The character "#" is used only as an end-of-input marker and will not appear anywhere else in the input. A string may contain spaces, but not at the beginning or end of the string, and there will never be two or more consecutive spaces.
Output
For each input string, replace every occurrence of a reserved character in the table above by its percent-encoding, exactly as shown, and output the resulting string on a line by itself. Note that the percent-encoding for an asterisk is %2a (with a lowercase "a") rather than %2A (with an uppercase "A").
Sample Input
Happy Joy Joy!
http://icpc.baylor.edu/icpc/
plain_vanilla
(**)
?
the 7% solution
#
Sample Output
Happy%20Joy%20Joy%21
http://icpc.baylor.edu/icpc/
plain_vanilla
%28%2a%2a%29
?
the%207%25%20solution
Source
Mid-Central USA 2007
*/
package main
import (
"bytes"
)
func main() {
assert(escape("Happy Joy Joy!") == "Happy%20Joy%20Joy%21")
assert(escape("http://icpc.baylor.edu/icpc/") == "http://icpc.baylor.edu/icpc/")
assert(escape("plain_vanilla") == "plain_vanilla")
assert(escape("(**)") == "%28%2a%2a%29")
assert(escape("?") == "?")
assert(escape("the 7% solution") == "the%207%25%20solution")
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func escape(s string) string {
m := map[rune]string{
' ': "%20",
'!': "%21",
'$': "%24",
'%': "%25",
'(': "%28",
')': "%29",
'*': "%2a",
}
w := new(bytes.Buffer)
for _, r := range s {
if t := m[r]; t != "" {
w.WriteString(t)
} else {
w.WriteRune(r)
}
}
return w.String()
}
|
package models
type ToDo struct {
Id string `json:"Id" bson:"_id,omitempty"`
Title string `json:"Title"`
Description string `json:"Description"`
Completed bool `json:"Completed"`
}
|
package ibeplus
import (
"encoding/xml"
"github.com/otwdev/ibepluslib/models"
"github.com/otwdev/galaxylib"
)
const rtURL = "http://ibeplus.travelsky.com/ota/xml/AirResRet"
type RT struct {
PNR *models.PnrInfo
}
func NewRT(pnr *models.PnrInfo) *RT {
return &RT{pnr}
}
func (r *RT) RTPNR() (rs *RTRSOTA_AirResRetRS, err *galaxylib.GalaxyError) {
rq := &RTRQOTA_AirResRetRQ{}
rq.AttrRetCreateTimeInd = "true"
rq.RTRQPOS = &RTRQPOS{}
rq.RTRQPOS.RTRQSource = &RTRQSource{}
rq.RTRQPOS.RTRQSource.AttrPseudoCityCode = r.PNR.OfficeNumber
rq.RTRQBookingReferenceID = &RTRQBookingReferenceID{r.PNR.PnrCode}
var ret []byte
ibe := NewIBE(rtURL, rq)
ret, err = ibe.Reqeust()
if err != nil {
return nil, err
}
//var rs *RTRSOTA_AirResRetRS
if er := xml.Unmarshal(ret, &rs); er != nil {
err = galaxylib.DefaultGalaxyError.FromError(1, err)
return
}
if rs.RTRSErrors != nil {
err = galaxylib.DefaultGalaxyError.FromText(1, rs.RTRSErrors.RTRSError.AttrShortTextZH)
return
}
return
}
type RTRSAirResRet struct {
RTRSAirTraveler []*RTRSAirTraveler `xml:" AirTraveler,omitempty" json:"AirTraveler,omitempty"`
RTRSBookingReferenceID *RTRSBookingReferenceID `xml:" BookingReferenceID,omitempty" json:"BookingReferenceID,omitempty"`
RTRSContactInfo []*RTRSContactInfo `xml:" ContactInfo,omitempty" json:"ContactInfo,omitempty"`
RTRSCreateTime *RTRSCreateTime `xml:" CreateTime,omitempty" json:"CreateTime,omitempty"`
RTRSFN *RTRSFN `xml:" FN,omitempty" json:"FN,omitempty"`
RTRSFP *RTRSFP `xml:" FP,omitempty" json:"FP,omitempty"`
RTRSFlightSegments *RTRSFlightSegments `xml:" FlightSegments,omitempty" json:"FlightSegments,omitempty"`
RTRSOtherServiceInformation []*RTRSOtherServiceInformation `xml:" OtherServiceInformation,omitempty" json:"OtherServiceInformation,omitempty"`
RTRSOthers []*RTRSOthers `xml:" Others,omitempty" json:"Others,omitempty"`
RTRSResponsibility *RTRSResponsibility `xml:" Responsibility,omitempty" json:"Responsibility,omitempty"`
RTRSSpecialRemark []*RTRSSpecialRemark `xml:" SpecialRemark,omitempty" json:"SpecialRemark,omitempty"`
RTRSSpecialServiceRequest []*RTRSSpecialServiceRequest `xml:" SpecialServiceRequest,omitempty" json:"SpecialServiceRequest,omitempty"`
RTRSTicketItemInfo []*RTRSTicketItemInfo `xml:" TicketItemInfo,omitempty" json:"TicketItemInfo,omitempty"`
RTRSTicketing *RTRSTicketing `xml:" Ticketing,omitempty" json:"Ticketing,omitempty"`
}
type RTRSAirTraveler struct {
AttrRPH string `xml:" RPH,attr" json:",omitempty"`
RTRSPassengerTypeQuantity *RTRSPassengerTypeQuantity `xml:" PassengerTypeQuantity,omitempty" json:"PassengerTypeQuantity,omitempty"`
RTRSPersonName *RTRSPersonName `xml:" PersonName,omitempty" json:"PersonName,omitempty"`
}
type RTRSAirline struct {
AttrCode string `xml:" Code,attr" json:",omitempty"`
}
type RTRSArrivalAirport struct {
AttrLocationCode string `xml:" LocationCode,attr" json:",omitempty"`
AttrTerminal string `xml:" Terminal,attr" json:",omitempty"`
}
type RTRSBookingClassAvail struct {
AttrResBookDesigCode string `xml:" ResBookDesigCode,attr" json:",omitempty"`
}
type RTRSBookingReferenceID struct {
AttrID string `xml:" ID,attr" json:",omitempty"`
}
type RTRSRoot struct {
RTRSOTA_AirResRetRS *RTRSOTA_AirResRetRS `xml:" OTA_AirResRetRS,omitempty" json:"OTA_AirResRetRS,omitempty"`
}
type RTRSContactInfo struct {
AttrContactCity string `xml:" ContactCity,attr" json:",omitempty"`
AttrContactInfo string `xml:" ContactInfo,attr" json:",omitempty"`
AttrRPH string `xml:" RPH,attr" json:",omitempty"`
}
type RTRSCreateTime struct {
Text string `xml:",chardata" json:",omitempty"`
}
type RTRSDepartureAirport struct {
AttrLocationCode string `xml:" LocationCode,attr" json:",omitempty"`
AttrTerminal string `xml:" Terminal,attr" json:",omitempty"`
}
type RTRSError struct {
AttrCode string `xml:" Code,attr" json:",omitempty"`
AttrShortText string `xml:" ShortText,attr" json:",omitempty"`
AttrShortTextZH string `xml:" ShortTextZH,attr" json:",omitempty"`
AttrType string `xml:" Type,attr" json:",omitempty"`
RTRSTrace *RTRSTrace `xml:" Trace,omitempty" json:"Trace,omitempty"`
}
type RTRSErrors struct {
RTRSError *RTRSError `xml:" Error,omitempty" json:"Error,omitempty"`
}
type RTRSFN struct {
AttrRPH string `xml:" RPH,attr" json:",omitempty"`
AttrText string `xml:" Text,attr" json:",omitempty"`
}
type RTRSFP struct {
AttrCurrency string `xml:" Currency,attr" json:",omitempty"`
AttrIsInfant string `xml:" IsInfant,attr" json:",omitempty"`
AttrPayType string `xml:" PayType,attr" json:",omitempty"`
AttrRPH string `xml:" RPH,attr" json:",omitempty"`
AttrRemark string `xml:" Remark,attr" json:",omitempty"`
}
type RTRSFlightSegment struct {
AttrArrivalDateTime string `xml:" ArrivalDateTime,attr" json:",omitempty"`
AttrDepartureDateTime string `xml:" DepartureDateTime,attr" json:",omitempty"`
AttrFlightNumber string `xml:" FlightNumber,attr" json:",omitempty"`
AttrIsChanged string `xml:" IsChanged,attr" json:",omitempty"`
AttrNumberInParty string `xml:" NumberInParty,attr" json:",omitempty"`
AttrRPH string `xml:" RPH,attr" json:",omitempty"`
AttrSegmentType string `xml:" SegmentType,attr" json:",omitempty"`
AttrStatus string `xml:" Status,attr" json:",omitempty"`
AttrTicket string `xml:" Ticket,attr" json:",omitempty"`
RTRSArrivalAirport *RTRSArrivalAirport `xml:" ArrivalAirport,omitempty" json:"ArrivalAirport,omitempty"`
RTRSBookingClassAvail *RTRSBookingClassAvail `xml:" BookingClassAvail,omitempty" json:"BookingClassAvail,omitempty"`
RTRSDepartureAirport *RTRSDepartureAirport `xml:" DepartureAirport,omitempty" json:"DepartureAirport,omitempty"`
RTRSMarketingAirline *RTRSMarketingAirline `xml:" MarketingAirline,omitempty" json:"MarketingAirline,omitempty"`
}
type RTRSFlightSegments struct {
RTRSFlightSegment []*RTRSFlightSegment `xml:" FlightSegment,omitempty" json:"FlightSegment,omitempty"`
}
type RTRSMarketingAirline struct {
AttrCode string `xml:" Code,attr" json:",omitempty"`
}
type RTRSNamePNR struct {
Text string `xml:",chardata" json:",omitempty"`
}
type RTRSOTA_AirResRetRS struct {
RTRSAirResRet *RTRSAirResRet `xml:" AirResRet,omitempty" json:"AirResRet,omitempty"`
RTRSErrors *RTRSErrors `xml:" Errors,omitempty" json:"Errors,omitempty"`
}
type RTRSOtherServiceInformation struct {
AttrRPH string `xml:" RPH,attr" json:",omitempty"`
RTRSText *RTRSText `xml:" Text,omitempty" json:"Text,omitempty"`
}
type RTRSOthers struct {
AttrRPH string `xml:" RPH,attr" json:",omitempty"`
AttrText string `xml:" Text,attr" json:",omitempty"`
}
type RTRSPassengerTypeQuantity struct {
AttrCode string `xml:" Code,attr" json:",omitempty"`
}
type RTRSPersonName struct {
RTRSNamePNR *RTRSNamePNR `xml:" NamePNR,omitempty" json:"NamePNR,omitempty"`
RTRSSurname *RTRSSurname `xml:" Surname,omitempty" json:"Surname,omitempty"`
}
type RTRSResponsibility struct {
AttrOfficeCode string `xml:" OfficeCode,attr" json:",omitempty"`
AttrRPH string `xml:" RPH,attr" json:",omitempty"`
}
type RTRSSpecialRemark struct {
AttrRPH string `xml:" RPH,attr" json:",omitempty"`
RTRSText *RTRSText `xml:" Text,omitempty" json:"Text,omitempty"`
}
type RTRSSpecialServiceRequest struct {
AttrRPH string `xml:" RPH,attr" json:",omitempty"`
AttrSSRCode string `xml:" SSRCode,attr" json:",omitempty"`
AttrStatus string `xml:" Status,attr" json:",omitempty"`
RTRSAirline *RTRSAirline `xml:" Airline,omitempty" json:"Airline,omitempty"`
RTRSText *RTRSText `xml:" Text,omitempty" json:"Text,omitempty"`
RTRSTravelerRefNumber *RTRSTravelerRefNumber `xml:" TravelerRefNumber,omitempty" json:"TravelerRefNumber,omitempty"`
}
type RTRSSurname struct {
Text string `xml:",chardata" json:",omitempty"`
}
type RTRSText struct {
Text string `xml:",chardata" json:",omitempty"`
}
type RTRSTicketItemInfo struct {
AttrRPH string `xml:" RPH,attr" json:",omitempty"`
AttrTicketNumber string `xml:" TicketNumber,attr" json:",omitempty"`
RTRSTravelerRefNumber *RTRSTravelerRefNumber `xml:" TravelerRefNumber,omitempty" json:"TravelerRefNumber,omitempty"`
}
type RTRSTicketing struct {
AttrIsIssued string `xml:" IsIssued,attr" json:",omitempty"`
AttrIssuedType string `xml:" IssuedType,attr" json:",omitempty"`
AttrRPH string `xml:" RPH,attr" json:",omitempty"`
AttrRemark string `xml:" Remark,attr" json:",omitempty"`
}
type RTRSTrace struct {
AttrText string `xml:" Text,attr" json:",omitempty"`
}
type RTRSTravelerRefNumber struct {
AttrRPH string `xml:" RPH,attr" json:",omitempty"`
}
/********************************************
RT RQ
********************************************/
type RTRQBookingReferenceID struct {
AttrID string `xml:" ID,attr" json:",omitempty"`
}
type RTRQRoot struct {
RTRQOTA_AirResRetRQ *RTRQOTA_AirResRetRQ `xml:" OTA_AirResRetRQ,omitempty" json:"OTA_AirResRetRQ,omitempty"`
}
type RTRQOTA_AirResRetRQ struct {
AttrRetCreateTimeInd string `xml:" RetCreateTimeInd,attr" json:",omitempty"`
RTRQBookingReferenceID *RTRQBookingReferenceID `xml:" BookingReferenceID,omitempty" json:"BookingReferenceID,omitempty"`
RTRQPOS *RTRQPOS `xml:" POS,omitempty" json:"POS,omitempty"`
}
type RTRQPOS struct {
RTRQSource *RTRQSource `xml:" Source,omitempty" json:"Source,omitempty"`
}
type RTRQSource struct {
AttrPseudoCityCode string `xml:" PseudoCityCode,attr" json:",omitempty"`
}
|
// Licensed to SolID under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. SolID licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package oidc
// Grant types -----------------------------------------------------------------
const (
// GrantTypeAuthorizationCode represents AuthorizationCode grant type name.
GrantTypeAuthorizationCode = "authorization_code"
// GrantTypeClientCredentials represents ClientCredentials grant type name.
GrantTypeClientCredentials = "client_credentials"
// GrantTypeDeviceCode represents DeviceCode grant type name.
GrantTypeDeviceCode = "urn:ietf:params:oauth:grant-type:device_code"
// GrantTypeRefreshToken represents RefreshToken grant type name.
GrantTypeRefreshToken = "refresh_token"
// GrantTypeJWTBearer represents JWT Bearer Token grant type name.
GrantTypeJWTBearer = "urn:ietf:params:oauth:grant-type:jwt-bearer"
// GrantTypeSAML2Bearer represents SAML 2 Bearer token grant type.
GrantTypeSAML2Bearer = "urn:ietf:params:oauth:grant-type:saml2-bearer"
)
// Scopes ----------------------------------------------------------------------
const (
// ScopeOpenID represents OpenID scope name.
ScopeOpenID = "openid"
// ScopeOfflineAccess represents offline access scope name.
ScopeOfflineAccess = "offline_access"
)
// Code Challenge Methods ------------------------------------------------------
const (
// CodeChallengeMethodSha256 represents sha256 code challenge method name.
CodeChallengeMethodSha256 = "S256"
)
// Assertion Types -------------------------------------------------------------
const (
// AssertionTypeJWTBearer repesents JWT Bearer assertion name.
AssertionTypeJWTBearer = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
)
// Response Types --------------------------------------------------------------
const (
// ResponseTypeCode represents the authorization code response type defined
// in OAuth 2.0
ResponseTypeCode = "code"
// ResponseTypeToken represents the implicit response type defined in OAuth 2.0
ResponseTypeToken = "token"
)
// Authentication Methods ------------------------------------------------------
const (
// AuthMethodNone : The client is a public client as defined in OAuth 2.0
AuthMethodNone = "none"
// AuthMethodClientSecretPost : The client uses the HTTP POST parameters as
// defined in OAuth 2.0
AuthMethodClientSecretPost = "client_secret_post"
// AuthMethodClientSecretBasic : The client uses HTTP Basic as defined in
// OAuth 2.0
AuthMethodClientSecretBasic = "client_secret_basic"
// AuthMethodPrivateKeyJWT : The client uses JWT assertion.
AuthMethodPrivateKeyJWT = "private_key_jwt"
)
// Application Type ------------------------------------------------------------
const (
// ApplicationTypeServerSideWeb is a web application with authorization logic on the server side.
ApplicationTypeServerSideWeb = "web"
// ApplicationTypeClientSideWeb is a rich client web application with all authorization logic in browser.
ApplicationTypeClientSideWeb = "browser"
// ApplicationTypeNative is a desktop or a mobile application able to request authorization token non-interactively.
ApplicationTypeNative = "native"
// ApplicationTypeService is a script that needs to access resources on behalf of itself.
ApplicationTypeService = "service"
// ApplicationTypeDevice is is designed for devices that either do not have access to a browser or have limited input capabilities.
ApplicationTypeDevice = "device"
)
// Subject Type ----------------------------------------------------------------
// https://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes
const (
// SubjectTypePublic defines subject as public data. This provides the same sub (subject) value to all Clients.
// It is the default if the provider has no subject_types_supported element in its discovery document.
SubjectTypePublic = "public"
// SubjectTypePairwise defines subject masquerade strategy. This provides a different sub value to each Client,
// so as not to enable Clients to correlate the End-User's activities without permission.
SubjectTypePairwise = "pairwise"
)
|
package command
import (
"fmt"
"strings"
"time"
"github.com/jixwanwang/jixbot/channel"
)
const (
commandFilePath = "data/textcommands/"
configFilePath = "data/config/"
globalChannel = "_global"
)
type Command interface {
ID() string
Init()
Response(username, message string, whisper bool)
}
var BadCommandError = fmt.Errorf("Bad command")
var NotPermittedError = fmt.Errorf("Not permitted to use this command")
type subCommand struct {
command string
numArgs int
cooldown time.Duration
lastCalled time.Time
clearance channel.Level
}
func (C *subCommand) parse(message string, clearance channel.Level) ([]string, error) {
args := []string{}
if clearance < C.clearance {
return args, NotPermittedError
}
// Rate limit
if C.cooldown.Nanoseconds() > 0 &&
time.Since(C.lastCalled).Nanoseconds() < C.cooldown.Nanoseconds() {
return args, BadCommandError
}
parts := strings.Split(message, " ")
if strings.ToLower(parts[0]) != C.command {
return args, BadCommandError
}
if len(parts)-1 < C.numArgs {
return args, BadCommandError
}
prefix := strings.Join(parts[:C.numArgs+1], " ")
// There will be a trailing space on the prefix if the message has more than enough parts
if C.numArgs < len(parts)-1 {
prefix = prefix + " "
}
if strings.HasPrefix(message, prefix) {
args = parts[1 : C.numArgs+1]
remaining := strings.TrimPrefix(message, prefix)
if len(remaining) > 0 {
args = append(args, strings.TrimSpace(strings.TrimPrefix(message, prefix)))
}
C.lastCalled = time.Now()
return args, nil
}
return args, BadCommandError
}
|
package main
func Combination1(nums []int, n int) [][]int {
ps := Powerset2(nums)
result := make([][]int, CombinationCount(len(nums), n))
index := 0
for _, s := range ps {
if len(s) == n {
result[index] = s
index++
}
}
return result
}
func Combination2(nums []int, n int) [][]int {
size := len(nums)
result := make([][]int, CombinationCount(len(nums), n))
bi := (1 << uint(n)) - 1
max := 1 << uint(size)
index := 0
for bi < max {
bi = Combination2NextIndex(bi)
flags := bi
s := []int{}
for _, n := range nums {
if flags%2 != 0 {
s = append(s, n)
}
flags /= 2
}
result[index] = s
index++
}
return result
}
func CombinationCount(n, m int) int {
return Fact(n) / (Fact(n-m) * Fact(m))
}
func Fact(n int) int {
if n == 0 {
return 1
} else {
return n * Fact(n-1)
}
}
func Combination2NextIndex(n int) int {
// (1) 2 進数で 1 になっている一番下の桁を取得
smallest := n & -n
// (2) 1 になっている一番下の桁に 1 を足す
ripple := n + smallest
// (3) 新たに 1 になっている一番下の桁を取得
newSmallest := ripple & -ripple
// (3) / (1) で (2) の操作により増えた 0 の数(失われた 1 の数)が算出され
// - 1 することで補填するべき 1 のビット列を取得する
ones := ((newSmallest / smallest) >> 1) - 1
// ripple に ones を補填して新しいインデックスとする
return ripple | ones
}
|
package protoform
import "fmt"
const (
message = iota
enum
)
// protobufType is one of message, or enum
type protobufType uint8
// Proto is a struct which contains the components of a protobuf file
type Proto struct {
FileName string
Type string
Syntax string
Package string
Properties []MessageProperty
Imports []string
}
// MessageProperty represents a specific field
type MessageProperty struct {
Type string
Name string
Number int
}
func (p protobufType) Print() {
if p == message {
fmt.Println("message")
} else if p == enum {
fmt.Println("enum")
}
}
func (p protobufType) Sprint() (s string) {
if p == message {
s = "message"
} else if p == enum {
s = "enum"
}
return s
}
// Template returns a templatized version of a protobuf file.
func (p Proto) Template() string {
return `syntax = "{{- .Syntax }}";
package {{ .Package }};
{{- range .Imports }}
import {{ . -}};
{{- end }}
message {{ .Type }} {
{{- range .Properties }}
{{ .Type }} {{ .Name }} = {{ .Number -}};
{{- end }}
}`
}
|
package main
import (
"fmt"
)
func twoSum(nums []int, target int) []int {
m := make(map[int]int)
for i, n := range nums {
fmt.Println(m[n])
fmt.Println(i)
_, prs := m[n]
fmt.Println(prs)
if prs {
return []int{m[n], i}
} else {
m[target-n] = i
}
}
return nil
}
func main() {
num := []int{-10,7,19,15, 22}
target := 22
twoSum(num, target)
fmt.Println("Test")
}
|
package publishtweet
import (
"io/ioutil"
"testing"
"github.com/TIBCOSoftware/flogo-lib/core/activity"
)
var activityMetadata *activity.Metadata
func getActivityMetadata() *activity.Metadata {
if activityMetadata == nil {
jsonMetadataBytes, err := ioutil.ReadFile("activity.json")
if err != nil {
panic("No Json Metadata found for activity.json path")
}
activityMetadata = activity.NewMetadata(string(jsonMetadataBytes))
}
return activityMetadata
}
func TestCreate(t *testing.T) {
act := NewActivity(getActivityMetadata())
if act == nil {
t.Error("Activity Not Created")
t.Fail()
return
}
}
// func TestTwitterFunction_Tweet(t *testing.T) {
//
// defer func() {
// if r := recover(); r != nil {
// t.Failed()
// t.Errorf("panic during execution: %v", r)
// }
// }()
//
// act := NewActivity(getActivityMetadata())
//
// tc := test.NewTestActivityContext(getActivityMetadata())
//
// //setup attrs
//
// tc.SetInput("consumerKey", "")
// tc.SetInput("consumerSecret", "")
// tc.SetInput("accessToken", "")
// tc.SetInput("accessTokenSecret", "")
// tc.SetInput("twitterFunction", "Tweet")
// tc.SetInput("text", "Testing twitter new connector AllStars :)")
//
// act.Eval(tc)
//
// //check result attr
//
// code := tc.GetOutput("statusCode")
//
// msg := tc.GetOutput("message")
// fmt.Print(msg)
// assert.Equal(t, code, "200")
//
// }
// func TestTwitterFunction_ReTweet(t *testing.T) {
//
// defer func() {
// if r := recover(); r != nil {
// t.Failed()
// t.Errorf("panic during execution: %v", r)
// }
// }()
//
// act := NewActivity(getActivityMetadata())
//
// tc := test.NewTestActivityContext(getActivityMetadata())
//
// //setup attrs
//
// tc.SetInput("consumerKey", "")
// tc.SetInput("consumerSecret", "")
// tc.SetInput("accessToken", "")
// tc.SetInput("accessTokenSecret", "")
// tc.SetInput("twitterFunction", "ReTweet")
// tc.SetInput("user", "992714282587455488")
// tc.SetInput("text", "Retweeting my previous tweet again, I know weird but connector test karne k liye karna padta hai :p")
//
// act.Eval(tc)
//
// //check result attr
//
// code := tc.GetOutput("statusCode")
//
// msg := tc.GetOutput("message")
// fmt.Print(msg)
// assert.Equal(t, code, "200")
//
// }
// func TestTwitterFunction_Block(t *testing.T) {
//
// defer func() {
// if r := recover(); r != nil {
// t.Failed()
// t.Errorf("panic during execution: %v", r)
// }
// }()
//
// act := NewActivity(getActivityMetadata())
//
// tc := test.NewTestActivityContext(getActivityMetadata())
//
// //setup attrs
//
// tc.SetInput("consumerKey", "")
// tc.SetInput("consumerSecret", "")
// tc.SetInput("accessToken", "")
// tc.SetInput("accessTokenSecret", "")
// tc.SetInput("twitterFunction", "Block")
// tc.SetInput("user", "@FLOGOALLSTARS")
// //tc.SetInput("text", "Retweeting my previous tweet again, I know weird but connector test karne k liye karna padta hai :p")
//
// act.Eval(tc)
//
// //check result attr
//
// code := tc.GetOutput("statusCode")
//
// msg := tc.GetOutput("message")
// fmt.Print(msg)
// assert.Equal(t, code, "200")
//
// }
//
//
// func TestTwitterFunction_Unblock(t *testing.T) {
//
// defer func() {
// if r := recover(); r != nil {
// t.Failed()
// t.Errorf("panic during execution: %v", r)
// }
// }()
//
// act := NewActivity(getActivityMetadata())
//
// tc := test.NewTestActivityContext(getActivityMetadata())
//
// //setup attrs
//
// tc.SetInput("consumerKey", "")
// tc.SetInput("consumerSecret", "")
// tc.SetInput("accessToken", "")
// tc.SetInput("accessTokenSecret", "")
// tc.SetInput("twitterFunction", "Unblock")
// tc.SetInput("user", "@FLOGOALLSTARS")
// //tc.SetInput("text", "Retweeting my previous tweet again, I know weird but connector test karne k liye karna padta hai :p")
//
// act.Eval(tc)
//
// //check result attr
//
// code := tc.GetOutput("statusCode")
//
// msg := tc.GetOutput("message")
// fmt.Print(msg)
// assert.Equal(t, code, "200")
//
// }
// func TestTwitterFunction_Follow(t *testing.T) {
//
// defer func() {
// if r := recover(); r != nil {
// t.Failed()
// t.Errorf("panic during execution: %v", r)
// }
// }()
//
// act := NewActivity(getActivityMetadata())
//
// tc := test.NewTestActivityContext(getActivityMetadata())
//
// //setup attrs
//
// tc.SetInput("consumerKey", "")
// tc.SetInput("consumerSecret", "")
// tc.SetInput("accessToken", "")
// tc.SetInput("accessTokenSecret", "")
// tc.SetInput("twitterFunction", "Follow")
// tc.SetInput("user", "@FLOGOALLSTARS")
// //tc.SetInput("text", "Retweeting my previous tweet again, I know weird but connector test karne k liye karna padta hai :p")
//
// act.Eval(tc)
//
// //check result attr
//
// code := tc.GetOutput("statusCode")
//
// msg := tc.GetOutput("message")
// fmt.Print(msg)
// assert.Equal(t, code, "200")
//
// }
// func TestTwitterFunction_Unfollow(t *testing.T) {
//
// defer func() {
// if r := recover(); r != nil {
// t.Failed()
// t.Errorf("panic during execution: %v", r)
// }
// }()
//
// act := NewActivity(getActivityMetadata())
//
// tc := test.NewTestActivityContext(getActivityMetadata())
//
// //setup attrs
//
// tc.SetInput("consumerKey", "")
// tc.SetInput("consumerSecret", "")
// tc.SetInput("accessToken", "")
// tc.SetInput("accessTokenSecret", "")
// tc.SetInput("twitterFunction", "Unfollow")
// tc.SetInput("user", "@FLOGOALLSTARS")
// //tc.SetInput("text", "Retweeting my previous tweet again, I know weird but connector test karne k liye karna padta hai :p")
//
// act.Eval(tc)
//
// //check result attr
//
// code := tc.GetOutput("statusCode")
//
// msg := tc.GetOutput("message")
// fmt.Print(msg)
// assert.Equal(t, code, "200")
//
// }
// func TestTwitterFunction_DM(t *testing.T) {
//
// defer func() {
// if r := recover(); r != nil {
// t.Failed()
// t.Errorf("panic during execution: %v", r)
// }
// }()
//
// act := NewActivity(getActivityMetadata())
//
// tc := test.NewTestActivityContext(getActivityMetadata())
//
// //setup attrs
//
// tc.SetInput("consumerKey", "")
// tc.SetInput("consumerSecret", "")
// tc.SetInput("accessToken", "")
// tc.SetInput("accessTokenSecret", "")
// tc.SetInput("twitterFunction", "DM")
// tc.SetInput("user", "@FLOGOALLSTARS")
// tc.SetInput("text", "ping")
//
// act.Eval(tc)
//
// //check result attr
//
// code := tc.GetOutput("statusCode")
//
// msg := tc.GetOutput("message")
// fmt.Print(msg)
// assert.Equal(t, code, "200")
//
// }
// func TestTwitterFunction_EmptyConsumerKey(t *testing.T) {
//
// defer func() {
// if r := recover(); r != nil {
// t.Failed()
// t.Errorf("panic during execution: %v", r)
// }
// }()
//
// act := NewActivity(getActivityMetadata())
//
// tc := test.NewTestActivityContext(getActivityMetadata())
//
// //setup attrs
//
// tc.SetInput("consumerKey", "")
// tc.SetInput("consumerSecret", "1234")
// tc.SetInput("accessToken", "xtz")
// tc.SetInput("accessTokenSecret", "qwer")
// tc.SetInput("twitterFunction", "Follow")
// tc.SetInput("user", "@FLOGOALLSTARS")
// //tc.SetInput("text", "Retweeting my previous tweet again, I know weird but connector test karne k liye karna padta hai :p")
//
// act.Eval(tc)
//
// //check result attr
//
// code := tc.GetOutput("statusCode")
//
// msg := tc.GetOutput("message")
// fmt.Print(msg)
// assert.Equal(t, code, "101")
//
// }
//
// func TestTwitterFunction_EmptyConsumerSecret(t *testing.T) {
//
// defer func() {
// if r := recover(); r != nil {
// t.Failed()
// t.Errorf("panic during execution: %v", r)
// }
// }()
//
// act := NewActivity(getActivityMetadata())
//
// tc := test.NewTestActivityContext(getActivityMetadata())
//
// //setup attrs
//
// tc.SetInput("consumerKey", "xyz")
// tc.SetInput("consumerSecret", "")
// tc.SetInput("accessToken", "1234")
// tc.SetInput("accessTokenSecret", "1234")
// tc.SetInput("twitterFunction", "Follow")
// tc.SetInput("user", "@FLOGOALLSTARS")
// //tc.SetInput("text", "Retweeting my previous tweet again, I know weird but connector test karne k liye karna padta hai :p")
//
// act.Eval(tc)
//
// //check result attr
//
// code := tc.GetOutput("statusCode")
//
// msg := tc.GetOutput("message")
// fmt.Print(msg)
// assert.Equal(t, code, "102")
//
// }
// func TestTwitterFunction_EmptyAccessToken(t *testing.T) {
//
// defer func() {
// if r := recover(); r != nil {
// t.Failed()
// t.Errorf("panic during execution: %v", r)
// }
// }()
//
// act := NewActivity(getActivityMetadata())
//
// tc := test.NewTestActivityContext(getActivityMetadata())
//
// //setup attrs
//
// tc.SetInput("consumerKey", "123")
// tc.SetInput("consumerSecret", "1234")
// tc.SetInput("accessToken", "")
// tc.SetInput("accessTokenSecret", "qwer")
// tc.SetInput("twitterFunction", "Follow")
// tc.SetInput("user", "@FLOGOALLSTARS")
// //tc.SetInput("text", "Retweeting my previous tweet again, I know weird but connector test karne k liye karna padta hai :p")
//
// act.Eval(tc)
//
// //check result attr
//
// code := tc.GetOutput("statusCode")
//
// msg := tc.GetOutput("message")
// fmt.Print(msg)
// assert.Equal(t, code, "103")
//
// }
//
// func TestTwitterFunction_EmptyAccessTokenSecret(t *testing.T) {
//
// defer func() {
// if r := recover(); r != nil {
// t.Failed()
// t.Errorf("panic during execution: %v", r)
// }
// }()
//
// act := NewActivity(getActivityMetadata())
//
// tc := test.NewTestActivityContext(getActivityMetadata())
//
// //setup attrs
//
// tc.SetInput("consumerKey", "xyz")
// tc.SetInput("consumerSecret", "asd")
// tc.SetInput("accessToken", "qwe")
// tc.SetInput("accessTokenSecret", "")
// tc.SetInput("twitterFunction", "Follow")
// tc.SetInput("user", "@FLOGOALLSTARS")
// //tc.SetInput("text", "Retweeting my previous tweet again, I know weird but connector test karne k liye karna padta hai :p")
//
// act.Eval(tc)
//
// //check result attr
//
// code := tc.GetOutput("statusCode")
//
// msg := tc.GetOutput("message")
// fmt.Print(msg)
// assert.Equal(t, code, "104")
//
// }
//
// func TestTwitterFunction_EmptyTwitterFunction(t *testing.T) {
//
// defer func() {
// if r := recover(); r != nil {
// t.Failed()
// t.Errorf("panic during execution: %v", r)
// }
// }()
//
// act := NewActivity(getActivityMetadata())
//
// tc := test.NewTestActivityContext(getActivityMetadata())
//
// //setup attrs
//
// tc.SetInput("consumerKey", "xyz")
// tc.SetInput("consumerSecret", "asd")
// tc.SetInput("accessToken", "qwe")
// tc.SetInput("accessTokenSecret", "qq")
// tc.SetInput("twitterFunction", "")
// tc.SetInput("user", "@FLOGOALLSTARS")
// //tc.SetInput("text", "Retweeting my previous tweet again, I know weird but connector test karne k liye karna padta hai :p")
//
// act.Eval(tc)
//
// //check result attr
//
// code := tc.GetOutput("statusCode")
//
// msg := tc.GetOutput("message")
// fmt.Print(msg)
// assert.Equal(t, code, "105")
//
// }
|
package internal
import (
"testing"
"time"
)
const testApplicationNamespace = "test_diane"
var whois = NewWhoisClient(testApplicationNamespace)
type whoisTestData struct {
target string
domain string
hasExpiration bool
expiration time.Time
}
func TestWhoisClientAvailable(t *testing.T) {
var tests = []whoisTestData{
{target: "somethingmadeup123.com"},
}
for _, tt := range tests {
t.Run(tt.target, func(t *testing.T) {
resp := whois.Query(tt.target)
if resp.err != nil {
t.Errorf("whoisQuery(%s) error %s", tt.target, resp.err.Error())
} else if resp.raw == "" {
t.Errorf("whoisQuery(%s) expected non empty raw response.", tt.target)
} else if resp.target == "" {
t.Errorf("whoisQuery(%s) expected non empty target.", tt.target)
} else if resp.hostPort == "" {
t.Errorf("whoisQuery(%s) expected non empty hostPort. %v", tt.target, resp.hostPort)
} else if resp.status != ResponseAvailable {
t.Errorf("whoisQuery(%s) expected to be available.", tt.target)
}
})
}
}
func TestWhoisClientNotAvailable(t *testing.T) {
var tests = []whoisTestData{
{target: "example.com"},
}
for _, tt := range tests {
t.Run(tt.target, func(t *testing.T) {
resp := whois.Query(tt.target)
if resp.err != nil {
t.Errorf("whoisQuery(%s) error %s", tt.target, resp.err.Error())
} else if resp.raw == "" {
t.Errorf("whoisQuery(%s) expected non empty raw response.", tt.target)
} else if resp.target == "" {
t.Errorf("whoisQuery(%s) expected non empty target.", tt.target)
} else if resp.status == ResponseAvailable {
t.Errorf("whoisQuery(%s) expected to be not available. %+v", tt.target, resp.raw)
} else if resp.hostPort == "" {
t.Errorf("whoisQuery(%s) expected non empty hostPort. %v", tt.target, resp.hostPort)
}
})
}
}
func TestWhoisClientExampleNoRefer(t *testing.T) {
var tests = []whoisTestData{
{target: "example.com", domain: "example.com"},
{target: "example.net", domain: "example.net"},
}
for _, tt := range tests {
t.Run(tt.target, func(t *testing.T) {
resp := whois.Query(tt.target)
if resp.err != nil {
t.Errorf("whoisQuery(%s) error %s", tt.target, resp.err.Error())
} else if resp.hostPort == "" {
t.Errorf("whoisQuery(%s) expected non empty hostPort. %v", tt.target, resp.hostPort)
} else if resp.target == "" {
t.Errorf("whoisQuery(%s) expected non empty target.", tt.target)
} else if resp.domain != tt.domain {
t.Errorf("whois.Query(%s) got domain %v, expected %v", tt.target, resp.domain, tt.domain)
}
})
}
}
func TestWhoisClientExampleWithRefer(t *testing.T) {
var tests = []whoisTestData{
{target: "example.edu", domain: "example.edu"},
{target: "example.org", domain: "example.org"},
}
for _, tt := range tests {
t.Run(tt.domain, func(t *testing.T) {
resp := whois.Query(tt.domain)
if resp.err != nil {
t.Errorf("whoisQuery(%s) error %s", tt.target, resp.err.Error())
} else if resp.hostPort == "" {
t.Errorf("whoisQuery(%s) expected non empty hostPort. %v", tt.target, resp.hostPort)
} else if resp.target == "" {
t.Errorf("whoisQuery(%s) expected non empty target.", tt.target)
} else if resp.domain != tt.domain {
t.Errorf("whois.Query(%s) got domain %v, expected %v", tt.target, resp.domain, tt.domain)
}
})
}
}
func TestWhoisClientForExpirations(t *testing.T) {
var tests = []whoisTestData{
{target: "example.com", domain: "example.com", hasExpiration: false},
{target: "example.net", domain: "example.net", hasExpiration: false},
{target: "example.edu", domain: "example.edu", hasExpiration: true, expiration: time.Date(2023, 7, 31, 0, 0, 0, 0, time.UTC)},
{target: "example.org", domain: "example.org", hasExpiration: true, expiration: time.Date(2010, 8, 30, 0, 0, 0, 0, time.UTC)},
{target: "github.com", domain: "github.com", hasExpiration: true, expiration: time.Date(2022, 10, 9, 0, 0, 0, 0, time.UTC)},
{target: "gitlab.com", domain: "gitlab.com", hasExpiration: true, expiration: time.Date(2025, 1, 15, 0, 0, 0, 0, time.UTC)},
}
for _, tt := range tests {
t.Run(tt.target, func(t *testing.T) {
resp := whois.Query(tt.target)
if resp.err != nil {
t.Errorf("whoisQuery(%s) error %s", tt.target, resp.err.Error())
} else if resp.hostPort == "" {
t.Errorf("whoisQuery(%s) expected non empty hostPort. %v", tt.target, resp.hostPort)
} else if resp.target == "" {
t.Errorf("whoisQuery(%s) expected non empty target.", tt.target)
} else if resp.domain != tt.domain {
t.Errorf("whois.Query(%s) domain was %v, expected %v", tt.target, resp.domain, tt.domain)
} else if resp.hasExpiration != tt.hasExpiration {
t.Errorf("whois.Query(%s) hasExpiration was %v, expected %v", tt.target, resp.hasExpiration, tt.hasExpiration)
} else if resp.hasExpiration {
// TODO: Check year, month, day only for now.
if resp.expiration.Year() != tt.expiration.Year() ||
resp.expiration.Month() != tt.expiration.Month() ||
resp.expiration.Day() != tt.expiration.Day() {
t.Errorf("whois.Query(%s) expiration was %v, expected %v", tt.target, resp.expiration.Local(), tt.expiration.Local())
}
}
})
}
}
func TestWhoisClientForNotAuthorized(t *testing.T) {
// Apparently .es uses an unconventional whois server.
// https://en.wikipedia.org/wiki/.es
var tests = []whoisTestData{
{target: "example.es", domain: "example.es"},
}
for _, tt := range tests {
t.Run(tt.target, func(t *testing.T) {
resp := whois.Query(tt.target)
if resp.err != nil {
t.Errorf("whoisQuery(%s) error %s", tt.target, resp.err.Error())
} else if resp.hostPort == "" {
t.Errorf("whoisQuery(%s) expected non empty hostPort. %v", tt.target, resp.hostPort)
} else if resp.target == "" {
t.Errorf("whoisQuery(%s) expected non empty target.", tt.target)
} else if resp.status != ResponseUnauthorized {
t.Errorf("whois.Query(%s) expected to return unauthorized.", tt.target)
}
})
}
}
|
package problem0206
// ListNode singly-linked list
type ListNode struct {
Val int
Next *ListNode
}
func reverseList(head *ListNode) *ListNode {
var newHead *ListNode
cur := head
for cur != nil {
// 要处理的下个指针
next := cur.Next
// 反转指针
cur.Next = newHead
// 新的队头
newHead = cur
// 更新指针
cur = next
}
return newHead
}
func reverseListRecu(head *ListNode) *ListNode {
// 定义基准情况
if head == nil || head.Next == nil {
return head
}
newHead := reverseListRecu(head.Next)
// head.Next 是 newHead 的最后一个节点
head.Next.Next = head
// 清空 head.Next 指针
head.Next = nil
return newHead
}
|
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package trace
import (
"context"
"os"
"path"
"testing"
"time"
"github.com/opentracing/opentracing-go"
"github.com/stretchr/testify/require"
)
func jobA(ctx context.Context) {
if span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil {
span1 := span.Tracer().StartSpan("jobA", opentracing.ChildOf(span.Context()))
defer span1.Finish()
ctx = opentracing.ContextWithSpan(ctx, span1)
}
jobB(ctx)
time.Sleep(100 * time.Millisecond)
}
func jobB(ctx context.Context) {
if span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil {
span1 := span.Tracer().StartSpan("jobB", opentracing.ChildOf(span.Context()))
defer span1.Finish()
}
time.Sleep(100 * time.Millisecond)
}
func TestSpan(t *testing.T) {
filename := path.Join(t.TempDir(), "br.trace")
getTraceFileName = func() string {
return filename
}
defer func() {
getTraceFileName = timestampTraceFileName
}()
ctx, store := TracerStartSpan(context.Background())
jobA(ctx)
TracerFinishSpan(ctx, store)
content, err := os.ReadFile(filename)
require.NoError(t, err)
s := string(content)
// possible result:
// "jobA 22:02:02.545296 200.621764ms\n"
// " └─jobB 22:02:02.545297 100.293444ms\n"
require.Regexp(t, `^jobA.*2[0-9][0-9]\.[0-9]+ms\n └─jobB.*1[0-9][0-9]\.[0-9]+ms\n$`, s)
}
|
package rediscookiestore
import (
"encoding/json"
"fmt"
"github.com/go-redis/redis"
"github.com/rmdashrf/go-misc/cookiejar2"
)
var (
// SETANDPUB <setkey> <pubkey> <val> <token>
// will set <setkey> to <val>, and then publish <token>
// to the pubsub key <pubkey>
scriptSetAndPublishSrc = `
local val = ARGV[1]
local token = ARGV[2]
local key = KEYS[1]
local publish_key = KEYS[2]
redis.call("SET", key, val)
redis.call("PUBLISH", publish_key, token)
return "OK"
`
scriptSetAndPub = redis.NewScript(scriptSetAndPublishSrc)
)
func SetCookies(r *redis.Client, key string, entries cookiejar2.CookieEntries, id string) (err error) {
var contents []byte
contents, err = json.Marshal(entries)
if err != nil {
return
}
storeName := StoreName(key)
invalidationName := InvalidationName(key)
err = scriptSetAndPub.Run(r, []string{storeName, invalidationName}, contents, id).Err()
return
}
func StoreName(key string) string {
return fmt.Sprintf("%s:store", key)
}
func InvalidationName(key string) string {
return fmt.Sprintf("%s:invalidation", key)
}
|
package stash
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
var (
branches string = `
{
"isLastPage" : true,
"filter" : null,
"values" : [
{
"displayId" : "develop",
"isDefault" : true,
"latestChangeset" : "e680a10f3e0afb5e3a5978dea02d37ac884da21",
"id" : "refs/heads/develop"
},
{
"displayId" : "master",
"isDefault" : false,
"latestChangeset" : "8d0f23745dfe4bacef9509bb4ecd7722b9aff82",
"id" : "refs/heads/master"
},
{
"displayId" : "feature/PRJ-447",
"isDefault" : false,
"latestChangeset" : "8d9c0642da6b3f06629cf115683da105d8e0654",
"id" : "refs/heads/feature/PRJ-447"
},
{
"displayId" : "bug/PRJ-442",
"isDefault" : false,
"latestChangeset" : "a57a403996161f24d1d0605ea8b5030927a0d3d",
"id" : "refs/heads/bug/PRJ-442"
}
],
"limit" : 25,
"start" : 0,
"size" : 7
}
`
)
func TestGetBranches(t *testing.T) {
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
t.Fatalf("wanted GET but found %s\n", r.Method)
}
url := *r.URL
if url.Path != "/rest/api/1.0/projects/PRJ/repos/widge/branches" {
t.Fatalf("GetBranches() URL path expected to be /rest/api/1.0/projects/PRJ/repos/widge/branches but found %s\n", url.Path)
}
if r.Header.Get("Accept") != "application/json" {
t.Fatalf("GetBranches() expected request Accept header to be application/json but found %s\n", r.Header.Get("Accept"))
}
if r.Header.Get("Authorization") != "Basic dTpw" {
t.Fatalf("Want Basic dTpw but found %s\n", r.Header.Get("Authorization"))
}
fmt.Fprintln(w, branches)
}))
defer testServer.Close()
url, _ := url.Parse(testServer.URL)
stashClient := NewClient("u", "p", url)
branches, err := stashClient.GetBranches("PRJ", "widge")
if err != nil {
t.Fatalf("GetBranches() not expecting an error, but received: %v\n", err)
}
if len(branches) != 4 {
t.Fatalf("GetBranches() expected to return map of size 4, but received map of size %d\n", len(branches))
}
for _, i := range []string{"master", "develop", "feature/PRJ-447", "bug/PRJ-442"} {
if _, ok := branches[i]; !ok {
t.Fatalf("Wanted a branch with displayID==%s but found none\n", i)
}
}
}
func TestGetBranches500(t *testing.T) {
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
t.Fatalf("wanted GET but found %s\n", r.Method)
}
url := *r.URL
if url.Path != "/rest/api/1.0/projects/PRJ/repos/widge/branches" {
t.Fatalf("GetBranches() URL path expected to be /rest/api/1.0/projects/PRJ/repos/widge/branches but found %s\n", url.Path)
}
if r.Header.Get("Accept") != "application/json" {
t.Fatalf("GetBranches() expected request Accept header to be application/json but found %s\n", r.Header.Get("Accept"))
}
if r.Header.Get("Authorization") != "Basic dTpw" {
t.Fatalf("Want Basic dTpw but found %s\n", r.Header.Get("Authorization"))
}
w.WriteHeader(500)
}))
defer testServer.Close()
url, _ := url.Parse(testServer.URL)
stashClient := NewClient("u", "p", url)
if _, err := stashClient.GetBranches("PRJ", "widge"); err == nil {
t.Fatalf("GetBranches() expecting an error but received none\n")
}
}
|
// Copyright 2022 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package executor_test
import (
"testing"
"github.com/pingcap/tidb/errno"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/testkit"
)
func TestCharsetFeature(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
tk.MustExec("set names gbk")
tk.MustQuery("select @@character_set_connection").Check(testkit.Rows("gbk"))
tk.MustQuery("select @@collation_connection").Check(testkit.Rows("gbk_chinese_ci"))
tk.MustExec("set @@character_set_client=gbk")
tk.MustQuery("select @@character_set_client").Check(testkit.Rows("gbk"))
tk.MustExec("set names utf8mb4")
tk.MustExec("set @@character_set_connection=gbk")
tk.MustQuery("select @@character_set_connection").Check(testkit.Rows("gbk"))
tk.MustQuery("select @@collation_connection").Check(testkit.Rows("gbk_chinese_ci"))
tk.MustGetErrCode("select _gbk 'a'", errno.ErrUnknownCharacterSet)
tk.MustExec("use test")
tk.MustExec("create table t1(a char(10) charset gbk)")
tk.MustExec("create table t2(a char(10) charset gbk collate gbk_bin)")
tk.MustExec("create table t3(a char(10)) charset gbk")
tk.MustExec("alter table t3 add column b char(10) charset gbk")
tk.MustQuery("show create table t3").Check(testkit.Rows("t3 CREATE TABLE `t3` (\n" +
" `a` char(10) DEFAULT NULL,\n" +
" `b` char(10) DEFAULT NULL\n" +
") ENGINE=InnoDB DEFAULT CHARSET=gbk COLLATE=gbk_chinese_ci",
))
tk.MustExec("create table t4(a char(10))")
tk.MustExec("alter table t4 add column b char(10) charset gbk")
tk.MustQuery("show create table t4").Check(testkit.Rows("t4 CREATE TABLE `t4` (\n" +
" `a` char(10) DEFAULT NULL,\n" +
" `b` char(10) CHARACTER SET gbk COLLATE gbk_chinese_ci DEFAULT NULL\n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin",
))
tk.MustExec("create table t5(a char(20), b char(20) charset utf8, c binary) charset gbk collate gbk_bin")
tk.MustExec("create database test_gbk charset gbk")
tk.MustExec("use test_gbk")
tk.MustExec("create table t1(a char(10))")
tk.MustQuery("show create table t1").Check(testkit.Rows("t1 CREATE TABLE `t1` (\n" +
" `a` char(10) DEFAULT NULL\n" +
") ENGINE=InnoDB DEFAULT CHARSET=gbk COLLATE=gbk_chinese_ci",
))
}
func TestCharsetFeatureCollation(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
tk.MustExec("create table t" +
"(ascii_char char(10) character set ascii," +
"gbk_char char(10) character set gbk collate gbk_bin," +
"latin_char char(10) character set latin1," +
"utf8mb4_char char(10) character set utf8mb4)",
)
tk.MustExec("insert into t values ('a', 'a', 'a', 'a'), ('a', '啊', '€', 'ㅂ')")
tk.MustQuery("select collation(concat(ascii_char, gbk_char)) from t").Check(testkit.Rows("gbk_bin", "gbk_bin"))
tk.MustQuery("select collation(concat(gbk_char, ascii_char)) from t").Check(testkit.Rows("gbk_bin", "gbk_bin"))
tk.MustQuery("select collation(concat(utf8mb4_char, gbk_char)) from t").Check(testkit.Rows("utf8mb4_bin", "utf8mb4_bin"))
tk.MustQuery("select collation(concat(gbk_char, utf8mb4_char)) from t").Check(testkit.Rows("utf8mb4_bin", "utf8mb4_bin"))
tk.MustQuery("select collation(concat('啊', convert('啊' using gbk) collate gbk_bin))").Check(testkit.Rows("gbk_bin"))
tk.MustQuery("select collation(concat(_latin1 'a', convert('啊' using gbk) collate gbk_bin))").Check(testkit.Rows("gbk_bin"))
tk.MustGetErrCode("select collation(concat(latin_char, gbk_char)) from t", mysql.ErrCantAggregate2collations)
tk.MustGetErrCode("select collation(concat(convert('€' using latin1), convert('啊' using gbk) collate gbk_bin))", mysql.ErrCantAggregate2collations)
tk.MustGetErrCode("select collation(concat(utf8mb4_char, gbk_char collate gbk_bin)) from t", mysql.ErrCantAggregate2collations)
tk.MustGetErrCode("select collation(concat('ㅂ', convert('啊' using gbk) collate gbk_bin))", mysql.ErrCantAggregate2collations)
tk.MustGetErrCode("select collation(concat(ascii_char collate ascii_bin, gbk_char)) from t", mysql.ErrCantAggregate2collations)
}
func TestCharsetWithPrefixIndex(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
tk.MustExec("create table t(a char(20) charset gbk, b char(20) charset gbk, primary key (a(2)))")
tk.MustExec("insert into t values ('a', '中文'), ('中文', '中文'), ('一二三', '一二三'), ('b', '一二三')")
tk.MustQuery("select * from t;").Sort().Check(testkit.Rows("a 中文", "b 一二三", "一二三 一二三", "中文 中文"))
tk.MustExec("drop table t")
tk.MustExec("create table t(a char(20) charset gbk, b char(20) charset gbk, unique index idx_a(a(2)))")
tk.MustExec("insert into t values ('a', '中文'), ('中文', '中文'), ('一二三', '一二三'), ('b', '一二三')")
tk.MustQuery("select * from t;").Sort().Check(testkit.Rows("a 中文", "b 一二三", "一二三 一二三", "中文 中文"))
}
|
package model
import (
"github.com/mongodb/mongo-go-driver/bson"
"github.com/mongodb/mongo-go-driver/bson/primitive"
)
// IPFS ...
type IPFS struct {
Model `bson:",inline"`
MediaID primitive.ObjectID `bson:"media_id"`
FileID string `bson:"file_id"`
IPFSAddress string `bson:"ipfs_address"`
IPNSAddress string `bson:"ipns_address"`
IpnsKey string `bson:"ipns_key"`
Status string `bson:"status"`
}
// NewIPFS ...
func NewIPFS() *IPFS {
return &IPFS{
Model: model(),
}
}
// CreateIfNotExist ...
func (i *IPFS) CreateIfNotExist() error {
return CreateIfNotExist(i)
}
// Create ...
func (i *IPFS) Create() error {
return InsertOne(i)
}
// Update ...
func (i *IPFS) Update() error {
return UpdateOne(i)
}
// Delete ...
func (i *IPFS) Delete() error {
return DeleteByID(i)
}
// FindByFileID ...
func (i *IPFS) FindByFileID() error {
return FindOne(i, bson.M{
"file_id": i.FileID,
})
}
// Find ...
func (i *IPFS) Find() error {
return FindByID(i)
}
func (i *IPFS) _Name() string {
return "ipfs"
}
|
package main
import (
"fmt"
)
func Hello() {
fmt.Println("Hello from: hello.go")
}
|
// Packge gdbm implements a wrapper around libgdbm, the GNU DataBase Manager
// library, for Go.
package gdbm
// #cgo CFLAGS: -std=gnu99
// #cgo LDFLAGS: -lgdbm
// #include <stdlib.h>
// #include <gdbm.h>
// #include <string.h>
// inline datum mk_datum(char * s) {
// datum d;
// d.dptr = s;
// d.dsize = strlen(s);
// return d;
// }
import "C"
import (
"errors"
"unsafe"
)
// GDBM database "connection" type.
type Database struct {
dbf C.GDBM_FILE
mode int
}
// GDBM database configuration type that can be used to specify how the
// database is created and treated. The `Mode` determines what the user of the
// `Database` object can do with it. The field can be a string, either "r" for
// Read-only, "w" for Read-Write, "c" for Read-Write and create if it doesn't
// exist, and "n" for Read-Write and always recreate database, even if it
// exists. TODO: write descriptions for other params... too lazy right now
type DatabaseCfg struct {
Mode string
BlockSize int
Permissions int
}
var (
// The error received when the end of the database is reached
NoError = errors.New("No error")
)
func lastError() error {
str := C.GoString(C.gdbm_strerror(C.gdbm_errno))
if str == "No error" {
return NoError
}
return errors.New(str)
}
// return the gdbm release build string
func Version() (version string) {
return C.GoString(C.gdbm_version)
}
/*
Simple function to open a database file with default parameters (block size
is default for the filesystem and file permissions are set to 0666).
mode is one of:
"r" - reader
"w" - writer
"c" - rw / create
"n" - new db
*/
func Open(filename string, mode string) (db *Database, err error) {
return OpenWithCfg(filename, DatabaseCfg{mode, 0, 0666})
}
// More complex database initialization function that takes in a `DatabaseCfg`
// struct to allow more fine-grained control over database settings.
func OpenWithCfg(filename string, cfg DatabaseCfg) (db *Database, err error) {
db = new(Database)
// Convert a human-readable mode string into a libgdbm-usable constant.
switch cfg.Mode {
case "r":
db.mode = C.GDBM_READER
case "w":
db.mode = C.GDBM_WRITER
case "c":
db.mode = C.GDBM_WRCREAT
case "n":
db.mode = C.GDBM_NEWDB
}
cs := C.CString(filename)
defer C.free(unsafe.Pointer(cs))
db.dbf = C.gdbm_open(cs, C.int(cfg.BlockSize), C.int(db.mode), C.int(cfg.Permissions), nil)
if db.dbf == nil {
err = lastError()
}
return db, err
}
// Closes a database's internal file pointer.
func (db *Database) Close() {
C.gdbm_close(db.dbf)
}
// Internal helper method to hide the two constants GDBM_INSERT and
// GDBM_REPLACE from the user.
func (db *Database) update(key string, value string, flag C.int) (err error) {
// Convert key and value into libgdbm's `datum` data structure. See the
// C definition at the top for the implementation of C.mk_datum(string).
kcs := C.CString(key)
vcs := C.CString(value)
k := C.mk_datum(kcs)
v := C.mk_datum(vcs)
defer C.free(unsafe.Pointer(kcs))
defer C.free(unsafe.Pointer(vcs))
retv := C.gdbm_store(db.dbf, k, v, flag)
if retv != 0 {
err = lastError()
}
return err
}
// Inserts a key-value pair into the database. If the database is opened
// in "r" mode, this will return an error. Also, if the key already exists in
// the database, and error will be returned.
func (db *Database) Insert(key string, value string) (err error) {
return db.update(key, value, C.GDBM_INSERT)
}
// Updates a key-value pair to use a new value, specified by the `value` string
// parameter. An error will be returned if the database is opened in "r" mode.
func (db *Database) Replace(key string, value string) (err error) {
return db.update(key, value, C.GDBM_REPLACE)
}
// Returns true or false, depending on whether the specified key exists in the
// database.
func (db *Database) Exists(key string) bool {
kcs := C.CString(key)
k := C.mk_datum(kcs)
defer C.free(unsafe.Pointer(kcs))
e := C.gdbm_exists(db.dbf, k)
if e == 1 {
return true
}
return false
}
// Returns the firstkey in this gdbm.Database.
// The traversal is ordered by gdbm‘s internal hash values, and won’t be sorted by the key values
// If there is not a key, an error will be returned in err.
func (db *Database) FirstKey() (value string, err error) {
vdatum := C.gdbm_firstkey(db.dbf)
if vdatum.dptr == nil {
return "", lastError()
}
value = C.GoStringN(vdatum.dptr, vdatum.dsize)
defer C.free(unsafe.Pointer(vdatum.dptr))
return value, nil
}
/*
Returns the nextkey after `key`. If there is not a next key, an
NoError error will be returned.
An Iteration might look like:
k, err := db.FirstKey()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
for {
v, err := db.Fetch(k)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println(v)
k, err = db.NextKey(k)
if err == gdbm.NoError {
break
} else if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
*/
func (db *Database) NextKey(key string) (value string, err error) {
kcs := C.CString(key)
k := C.mk_datum(kcs)
defer C.free(unsafe.Pointer(kcs))
vdatum := C.gdbm_nextkey(db.dbf, k)
if vdatum.dptr == nil {
return "", lastError()
}
value = C.GoStringN(vdatum.dptr, vdatum.dsize)
defer C.free(unsafe.Pointer(vdatum.dptr))
return value, nil
}
// Fetches the value of the given key. If the key is not in the database, an
// error will be returned in err. Otherwise, value will be the value string
// that is keyed by `key`.
func (db *Database) Fetch(key string) (value string, err error) {
kcs := C.CString(key)
k := C.mk_datum(kcs)
defer C.free(unsafe.Pointer(kcs))
vdatum := C.gdbm_fetch(db.dbf, k)
if vdatum.dptr == nil {
return "", lastError()
}
value = C.GoStringN(vdatum.dptr, vdatum.dsize)
defer C.free(unsafe.Pointer(vdatum.dptr))
return value, nil
}
// Removes a key-value pair from the database. If the database is opened in "r"
// mode, an error is returned
func (db *Database) Delete(key string) (err error) {
kcs := C.CString(key)
k := C.mk_datum(kcs)
defer C.free(unsafe.Pointer(kcs))
retv := C.gdbm_delete(db.dbf, k)
if retv == -1 && db.mode == C.GDBM_READER {
err = lastError()
}
return err
}
// Reorganizes the database for more efficient use of disk space. This method
// can be used if Delete(k) is called many times.
func (db *Database) Reorganize() {
C.gdbm_reorganize(db.dbf)
}
// Synchronizes all pending database changes to the disk. TODO: note this is
// only needed in FAST mode, and FAST mode needs implemented!
func (db *Database) Sync() {
C.gdbm_sync(db.dbf)
}
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package policygen
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"cloud.google.com/go/storage"
"github.com/GoogleCloudPlatform/healthcare-data-protection-suite/internal/hcl"
"github.com/GoogleCloudPlatform/healthcare-data-protection-suite/internal/jsonschema"
"github.com/GoogleCloudPlatform/healthcare-data-protection-suite/internal/terraform"
"github.com/ghodss/yaml"
"github.com/hashicorp/hcl/v2/hclsimple"
"github.com/hashicorp/terraform/states"
"github.com/zclconf/go-cty/cty"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
)
// config is the struct representing the Policy Generator configuration.
type config struct {
// Optional constraint on the binary version required for this config.
// Syntax: https://www.terraform.io/docs/configuration/version-constraints.html
Version string `hcl:"version,optional" json:"version,omitempty"`
TemplateDir string `hcl:"template_dir" json:"template_dir"`
// HCL decoder can't unmarshal into map[string]interface{},
// so make it unmarshal to a cty.Value and manually convert to map.
// TODO(https://github.com/hashicorp/hcl/issues/291): Remove the need for ForsetiPoliciesCty and GCPOrgPoliciesCty.
ForsetiPoliciesCty *cty.Value `hcl:"forseti_policies,optional" json:"-"`
ForsetiPolicies map[string]interface{} `json:"forseti_policies"`
}
func loadConfig(path string) (*config, error) {
b, err := ioutil.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read config %q: %v", path, err)
}
// Convert yaml to json so hcl decoder can parse it.
if filepath.Ext(path) == ".yaml" {
b, err = yaml.YAMLToJSON(b)
if err != nil {
return nil, err
}
// hclsimple.Decode doesn't actually use the path for anything other
// than its extension, so just pass in any file name ending with json so
// the library knows to treat these bytes as json and not yaml.
path = "file.json"
}
c := new(config)
if err := hclsimple.Decode(path, b, nil, c); err != nil {
return nil, err
}
if err := c.init(); err != nil {
return nil, err
}
return c, nil
}
func (c *config) init() error {
var err error
if c.ForsetiPoliciesCty != nil {
c.ForsetiPolicies, err = hcl.CtyValueToMap(c.ForsetiPoliciesCty)
if err != nil {
return fmt.Errorf("failed to convert %v to map: %v", c.ForsetiPoliciesCty, err)
}
}
sj, err := hcl.ToJSON(Schema)
if err != nil {
return fmt.Errorf("convert schema to JSON: %v", err)
}
cj, err := json.Marshal(c)
if err != nil {
return err
}
return jsonschema.ValidateJSONBytes(sj, cj)
}
// loadResources loads Terraform state resources from the given path.
// - If the path is a single local file, it loads resouces from it, regardless of the file name.
// - If the path is a local directory, it walks the directory recursively and loads resources from each .tfstate file.
// - If the path is a Cloud Storage bucket (indicated by 'gs://' prefix), it walks the bucket recursively and loads resources from each .tfstate file.
// It only reads the bucket name from the path and ignores the file/dir, if specified. All .tfstate file from the bucket will be read.
func loadResources(ctx context.Context, path string) ([]*states.Resource, error) {
if strings.HasPrefix(path, "gs://") {
return loadResourcesFromCloudStorageBucket(ctx, path)
}
fi, err := os.Stat(path)
if os.IsNotExist(err) {
return nil, err
}
// If the input is a file, also process it even if the extension is not .tfstate.
if !fi.IsDir() {
return loadResourcesFromSingleLocalFile(path)
}
return loadResourcesFromLocalDir(path)
}
func loadResourcesFromLocalDir(path string) ([]*states.Resource, error) {
var allResources []*states.Resource
fn := func(path string, _ os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("walk path %q: %v", path, err)
}
if filepath.Ext(path) != terraform.StateFileExtension {
return nil
}
resources, err := loadResourcesFromSingleLocalFile(path)
if err != nil {
return err
}
allResources = append(allResources, resources...)
return nil
}
if err := filepath.Walk(path, fn); err != nil {
return nil, err
}
return allResources, nil
}
func loadResourcesFromSingleLocalFile(path string) ([]*states.Resource, error) {
resources, err := terraform.ResourcesFromStateFile(path)
if err != nil {
return nil, fmt.Errorf("read resources from Terraform state file %q: %v", path, err)
}
return resources, nil
}
func loadResourcesFromCloudStorageBucket(ctx context.Context, path string) ([]*states.Resource, error) {
// Trim the 'gs://' prefix and split the path into the bucket name and cloud storage file path.
bucketName := strings.SplitN(strings.TrimPrefix(path, "gs://"), "/", 2)[0]
log.Printf("Reading state files from Cloud Storage bucket %q", bucketName)
client, err := storage.NewClient(ctx, option.WithScopes(storage.ScopeReadOnly))
if err != nil {
return nil, fmt.Errorf("start cloud storage client: %v", err)
}
bucket := client.Bucket(bucketName)
// Stat the bucket, check existence and caller permission.
if _, err := bucket.Attrs(ctx); err != nil {
return nil, fmt.Errorf("read bucket: %v", err)
}
var names []string
it := bucket.Objects(ctx, &storage.Query{})
for {
attrs, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
name := attrs.Name
if filepath.Ext(name) != terraform.StateFileExtension {
continue
}
names = append(names, name)
}
var allResources []*states.Resource
for _, name := range names {
log.Printf("reading remote file: gs://%s/%s", bucketName, name)
obj := bucket.Object(name)
r, err := obj.NewReader(ctx)
if err != nil {
return nil, err
}
defer r.Close()
resources, err := terraform.ResourcesFromState(r)
if err != nil {
return nil, err
}
allResources = append(allResources, resources...)
}
return allResources, nil
}
|
package x
// GENERATED BY XO. DO NOT EDIT.
import (
"errors"
"strings"
//"time"
"ms/sun/shared/helper"
"strconv"
"github.com/jmoiron/sqlx"
)
// (shortname .TableNameGo "err" "res" "sqlstr" "db" "XOLog") -}}//(schema .Schema .Table.TableName) -}}// .TableNameGo}}// PostMedia represents a row from 'sun.post_media'.
// Manualy copy this to project
type PostMedia__ struct {
MediaId int `json:"MediaId"` // MediaId -
UserId int `json:"UserId"` // UserId -
PostId int `json:"PostId"` // PostId -
AlbumId int `json:"AlbumId"` // AlbumId -
MediaTypeEnum int `json:"MediaTypeEnum"` // MediaTypeEnum -
Width int `json:"Width"` // Width -
Height int `json:"Height"` // Height -
Size int `json:"Size"` // Size -
Duration int `json:"Duration"` // Duration -
Extension string `json:"Extension"` // Extension -
Md5Hash string `json:"Md5Hash"` // Md5Hash -
Color string `json:"Color"` // Color -
CreatedTime int `json:"CreatedTime"` // CreatedTime -
ViewCount int `json:"ViewCount"` // ViewCount -
Extra string `json:"Extra"` // Extra -
// xo fields
_exists, _deleted bool
}
// Exists determines if the PostMedia exists in the database.
func (pm *PostMedia) Exists() bool {
return pm._exists
}
// Deleted provides information if the PostMedia has been deleted from the database.
func (pm *PostMedia) Deleted() bool {
return pm._deleted
}
// Insert inserts the PostMedia to the database.
func (pm *PostMedia) Insert(db XODB) error {
var err error
// if already exist, bail
if pm._exists {
return errors.New("insert failed: already exists")
}
// sql insert query, primary key must be provided
const sqlstr = `INSERT INTO sun.post_media (` +
`MediaId, UserId, PostId, AlbumId, MediaTypeEnum, Width, Height, Size, Duration, Extension, Md5Hash, Color, CreatedTime, ViewCount, Extra` +
`) VALUES (` +
`?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?` +
`)`
// run query
if LogTableSqlReq.PostMedia {
XOLog(sqlstr, pm.MediaId, pm.UserId, pm.PostId, pm.AlbumId, pm.MediaTypeEnum, pm.Width, pm.Height, pm.Size, pm.Duration, pm.Extension, pm.Md5Hash, pm.Color, pm.CreatedTime, pm.ViewCount, pm.Extra)
}
_, err = db.Exec(sqlstr, pm.MediaId, pm.UserId, pm.PostId, pm.AlbumId, pm.MediaTypeEnum, pm.Width, pm.Height, pm.Size, pm.Duration, pm.Extension, pm.Md5Hash, pm.Color, pm.CreatedTime, pm.ViewCount, pm.Extra)
if err != nil {
return err
}
// set existence
pm._exists = true
OnPostMedia_AfterInsert(pm)
return nil
}
// Insert inserts the PostMedia to the database.
func (pm *PostMedia) Replace(db XODB) error {
var err error
// sql query
const sqlstr = `REPLACE INTO sun.post_media (` +
`MediaId, UserId, PostId, AlbumId, MediaTypeEnum, Width, Height, Size, Duration, Extension, Md5Hash, Color, CreatedTime, ViewCount, Extra` +
`) VALUES (` +
`?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?` +
`)`
// run query
if LogTableSqlReq.PostMedia {
XOLog(sqlstr, pm.MediaId, pm.UserId, pm.PostId, pm.AlbumId, pm.MediaTypeEnum, pm.Width, pm.Height, pm.Size, pm.Duration, pm.Extension, pm.Md5Hash, pm.Color, pm.CreatedTime, pm.ViewCount, pm.Extra)
}
_, err = db.Exec(sqlstr, pm.MediaId, pm.UserId, pm.PostId, pm.AlbumId, pm.MediaTypeEnum, pm.Width, pm.Height, pm.Size, pm.Duration, pm.Extension, pm.Md5Hash, pm.Color, pm.CreatedTime, pm.ViewCount, pm.Extra)
if err != nil {
if LogTableSqlReq.PostMedia {
XOLogErr(err)
}
return err
}
pm._exists = true
OnPostMedia_AfterInsert(pm)
return nil
}
// Update updates the PostMedia in the database.
func (pm *PostMedia) Update(db XODB) error {
var err error
// if doesn't exist, bail
if !pm._exists {
return errors.New("update failed: does not exist")
}
// if deleted, bail
if pm._deleted {
return errors.New("update failed: marked for deletion")
}
// sql query
const sqlstr = `UPDATE sun.post_media SET ` +
`UserId = ?, PostId = ?, AlbumId = ?, MediaTypeEnum = ?, Width = ?, Height = ?, Size = ?, Duration = ?, Extension = ?, Md5Hash = ?, Color = ?, CreatedTime = ?, ViewCount = ?, Extra = ?` +
` WHERE MediaId = ?`
// run query
if LogTableSqlReq.PostMedia {
XOLog(sqlstr, pm.UserId, pm.PostId, pm.AlbumId, pm.MediaTypeEnum, pm.Width, pm.Height, pm.Size, pm.Duration, pm.Extension, pm.Md5Hash, pm.Color, pm.CreatedTime, pm.ViewCount, pm.Extra, pm.MediaId)
}
_, err = db.Exec(sqlstr, pm.UserId, pm.PostId, pm.AlbumId, pm.MediaTypeEnum, pm.Width, pm.Height, pm.Size, pm.Duration, pm.Extension, pm.Md5Hash, pm.Color, pm.CreatedTime, pm.ViewCount, pm.Extra, pm.MediaId)
if LogTableSqlReq.PostMedia {
XOLogErr(err)
}
OnPostMedia_AfterUpdate(pm)
return err
}
// Save saves the PostMedia to the database.
func (pm *PostMedia) Save(db XODB) error {
if pm.Exists() {
return pm.Update(db)
}
return pm.Replace(db)
}
// Delete deletes the PostMedia from the database.
func (pm *PostMedia) Delete(db XODB) error {
var err error
// if doesn't exist, bail
if !pm._exists {
return nil
}
// if deleted, bail
if pm._deleted {
return nil
}
// sql query
const sqlstr = `DELETE FROM sun.post_media WHERE MediaId = ?`
// run query
if LogTableSqlReq.PostMedia {
XOLog(sqlstr, pm.MediaId)
}
_, err = db.Exec(sqlstr, pm.MediaId)
if err != nil {
if LogTableSqlReq.PostMedia {
XOLogErr(err)
}
return err
}
// set deleted
pm._deleted = true
OnPostMedia_AfterDelete(pm)
return nil
}
////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// Querify gen - ME /////////////////////////////////////////
//.TableNameGo= table name
// _Deleter, _Updater
// orma types
type __PostMedia_Deleter struct {
wheres []whereClause
whereSep string
dollarIndex int
isMysql bool
}
type __PostMedia_Updater struct {
wheres []whereClause
// updates map[string]interface{}
updates []updateCol
whereSep string
dollarIndex int
isMysql bool
}
type __PostMedia_Selector struct {
wheres []whereClause
selectCol string
whereSep string
orderBy string //" order by id desc //for ints
limit int
offset int
dollarIndex int
isMysql bool
}
func NewPostMedia_Deleter() *__PostMedia_Deleter {
d := __PostMedia_Deleter{whereSep: " AND ", isMysql: true}
return &d
}
func NewPostMedia_Updater() *__PostMedia_Updater {
u := __PostMedia_Updater{whereSep: " AND ", isMysql: true}
//u.updates = make(map[string]interface{},10)
return &u
}
func NewPostMedia_Selector() *__PostMedia_Selector {
u := __PostMedia_Selector{whereSep: " AND ", selectCol: "*", isMysql: true}
return &u
}
/*/// mysql or cockroach ? or $1 handlers
func (m *__PostMedia_Selector)nextDollars(size int) string {
r := DollarsForSqlIn(size,m.dollarIndex,m.isMysql)
m.dollarIndex += size
return r
}
func (m *__PostMedia_Selector)nextDollar() string {
r := DollarsForSqlIn(1,m.dollarIndex,m.isMysql)
m.dollarIndex += 1
return r
}
*/
/////////////////////////////// Where for all /////////////////////////////
//// for ints all selector updater, deleter
/// mysql or cockroach ? or $1 handlers
func (m *__PostMedia_Deleter) nextDollars(size int) string {
r := DollarsForSqlIn(size, m.dollarIndex, m.isMysql)
m.dollarIndex += size
return r
}
func (m *__PostMedia_Deleter) nextDollar() string {
r := DollarsForSqlIn(1, m.dollarIndex, m.isMysql)
m.dollarIndex += 1
return r
}
////////ints
func (u *__PostMedia_Deleter) Or() *__PostMedia_Deleter {
u.whereSep = " OR "
return u
}
func (u *__PostMedia_Deleter) MediaId_In(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) MediaId_Ins(ins ...int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) MediaId_NotIn(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Deleter) MediaId_Eq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) MediaId_NotEq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) MediaId_LT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) MediaId_LE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) MediaId_GT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) MediaId_GE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Deleter) UserId_In(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " UserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) UserId_Ins(ins ...int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " UserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) UserId_NotIn(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " UserId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Deleter) UserId_Eq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) UserId_NotEq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) UserId_LT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) UserId_LE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) UserId_GT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) UserId_GE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Deleter) PostId_In(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) PostId_Ins(ins ...int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) PostId_NotIn(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Deleter) PostId_Eq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) PostId_NotEq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) PostId_LT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) PostId_LE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) PostId_GT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) PostId_GE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Deleter) AlbumId_In(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " AlbumId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) AlbumId_Ins(ins ...int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " AlbumId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) AlbumId_NotIn(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " AlbumId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Deleter) AlbumId_Eq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) AlbumId_NotEq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) AlbumId_LT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) AlbumId_LE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) AlbumId_GT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) AlbumId_GE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Deleter) MediaTypeEnum_In(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaTypeEnum IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) MediaTypeEnum_Ins(ins ...int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaTypeEnum IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) MediaTypeEnum_NotIn(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaTypeEnum NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Deleter) MediaTypeEnum_Eq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) MediaTypeEnum_NotEq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) MediaTypeEnum_LT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) MediaTypeEnum_LE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) MediaTypeEnum_GT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) MediaTypeEnum_GE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Deleter) Width_In(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Width IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) Width_Ins(ins ...int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Width IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) Width_NotIn(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Width NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Deleter) Width_Eq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Width_NotEq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Width_LT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Width_LE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Width_GT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Width_GE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Deleter) Height_In(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Height IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) Height_Ins(ins ...int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Height IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) Height_NotIn(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Height NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Deleter) Height_Eq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Height_NotEq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Height_LT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Height_LE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Height_GT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Height_GE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Deleter) Size_In(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Size IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) Size_Ins(ins ...int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Size IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) Size_NotIn(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Size NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Deleter) Size_Eq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Size_NotEq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Size_LT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Size_LE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Size_GT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Size_GE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Deleter) Duration_In(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Duration IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) Duration_Ins(ins ...int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Duration IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) Duration_NotIn(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Duration NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Deleter) Duration_Eq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Duration_NotEq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Duration_LT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Duration_LE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Duration_GT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Duration_GE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Deleter) CreatedTime_In(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) CreatedTime_Ins(ins ...int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) CreatedTime_NotIn(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Deleter) CreatedTime_Eq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) CreatedTime_NotEq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) CreatedTime_LT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) CreatedTime_LE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) CreatedTime_GT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) CreatedTime_GE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Deleter) ViewCount_In(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ViewCount IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) ViewCount_Ins(ins ...int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ViewCount IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) ViewCount_NotIn(ins []int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ViewCount NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Deleter) ViewCount_Eq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) ViewCount_NotEq(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) ViewCount_LT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) ViewCount_LE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) ViewCount_GT(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) ViewCount_GE(val int) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
/// mysql or cockroach ? or $1 handlers
func (m *__PostMedia_Updater) nextDollars(size int) string {
r := DollarsForSqlIn(size, m.dollarIndex, m.isMysql)
m.dollarIndex += size
return r
}
func (m *__PostMedia_Updater) nextDollar() string {
r := DollarsForSqlIn(1, m.dollarIndex, m.isMysql)
m.dollarIndex += 1
return r
}
////////ints
func (u *__PostMedia_Updater) Or() *__PostMedia_Updater {
u.whereSep = " OR "
return u
}
func (u *__PostMedia_Updater) MediaId_In(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) MediaId_Ins(ins ...int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) MediaId_NotIn(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Updater) MediaId_Eq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) MediaId_NotEq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) MediaId_LT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) MediaId_LE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) MediaId_GT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) MediaId_GE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Updater) UserId_In(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " UserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) UserId_Ins(ins ...int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " UserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) UserId_NotIn(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " UserId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Updater) UserId_Eq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) UserId_NotEq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) UserId_LT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) UserId_LE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) UserId_GT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) UserId_GE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Updater) PostId_In(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) PostId_Ins(ins ...int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) PostId_NotIn(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Updater) PostId_Eq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) PostId_NotEq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) PostId_LT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) PostId_LE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) PostId_GT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) PostId_GE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Updater) AlbumId_In(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " AlbumId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) AlbumId_Ins(ins ...int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " AlbumId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) AlbumId_NotIn(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " AlbumId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Updater) AlbumId_Eq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) AlbumId_NotEq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) AlbumId_LT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) AlbumId_LE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) AlbumId_GT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) AlbumId_GE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Updater) MediaTypeEnum_In(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaTypeEnum IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) MediaTypeEnum_Ins(ins ...int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaTypeEnum IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) MediaTypeEnum_NotIn(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaTypeEnum NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Updater) MediaTypeEnum_Eq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) MediaTypeEnum_NotEq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) MediaTypeEnum_LT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) MediaTypeEnum_LE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) MediaTypeEnum_GT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) MediaTypeEnum_GE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Updater) Width_In(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Width IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) Width_Ins(ins ...int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Width IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) Width_NotIn(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Width NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Updater) Width_Eq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Width_NotEq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Width_LT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Width_LE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Width_GT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Width_GE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Updater) Height_In(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Height IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) Height_Ins(ins ...int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Height IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) Height_NotIn(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Height NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Updater) Height_Eq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Height_NotEq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Height_LT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Height_LE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Height_GT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Height_GE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Updater) Size_In(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Size IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) Size_Ins(ins ...int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Size IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) Size_NotIn(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Size NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Updater) Size_Eq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Size_NotEq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Size_LT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Size_LE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Size_GT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Size_GE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Updater) Duration_In(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Duration IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) Duration_Ins(ins ...int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Duration IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) Duration_NotIn(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Duration NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Updater) Duration_Eq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Duration_NotEq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Duration_LT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Duration_LE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Duration_GT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Duration_GE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Updater) CreatedTime_In(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) CreatedTime_Ins(ins ...int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) CreatedTime_NotIn(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Updater) CreatedTime_Eq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) CreatedTime_NotEq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) CreatedTime_LT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) CreatedTime_LE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) CreatedTime_GT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) CreatedTime_GE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Updater) ViewCount_In(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ViewCount IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) ViewCount_Ins(ins ...int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ViewCount IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) ViewCount_NotIn(ins []int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ViewCount NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Updater) ViewCount_Eq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) ViewCount_NotEq(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) ViewCount_LT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) ViewCount_LE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) ViewCount_GT(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) ViewCount_GE(val int) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
/// mysql or cockroach ? or $1 handlers
func (m *__PostMedia_Selector) nextDollars(size int) string {
r := DollarsForSqlIn(size, m.dollarIndex, m.isMysql)
m.dollarIndex += size
return r
}
func (m *__PostMedia_Selector) nextDollar() string {
r := DollarsForSqlIn(1, m.dollarIndex, m.isMysql)
m.dollarIndex += 1
return r
}
////////ints
func (u *__PostMedia_Selector) Or() *__PostMedia_Selector {
u.whereSep = " OR "
return u
}
func (u *__PostMedia_Selector) MediaId_In(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) MediaId_Ins(ins ...int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) MediaId_NotIn(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Selector) MediaId_Eq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) MediaId_NotEq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) MediaId_LT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) MediaId_LE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) MediaId_GT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) MediaId_GE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Selector) UserId_In(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " UserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) UserId_Ins(ins ...int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " UserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) UserId_NotIn(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " UserId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Selector) UserId_Eq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) UserId_NotEq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) UserId_LT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) UserId_LE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) UserId_GT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) UserId_GE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " UserId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Selector) PostId_In(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) PostId_Ins(ins ...int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) PostId_NotIn(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Selector) PostId_Eq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) PostId_NotEq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) PostId_LT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) PostId_LE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) PostId_GT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) PostId_GE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Selector) AlbumId_In(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " AlbumId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) AlbumId_Ins(ins ...int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " AlbumId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) AlbumId_NotIn(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " AlbumId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Selector) AlbumId_Eq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) AlbumId_NotEq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) AlbumId_LT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) AlbumId_LE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) AlbumId_GT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) AlbumId_GE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AlbumId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Selector) MediaTypeEnum_In(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaTypeEnum IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) MediaTypeEnum_Ins(ins ...int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaTypeEnum IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) MediaTypeEnum_NotIn(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " MediaTypeEnum NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Selector) MediaTypeEnum_Eq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) MediaTypeEnum_NotEq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) MediaTypeEnum_LT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) MediaTypeEnum_LE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) MediaTypeEnum_GT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) MediaTypeEnum_GE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " MediaTypeEnum >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Selector) Width_In(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Width IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) Width_Ins(ins ...int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Width IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) Width_NotIn(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Width NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Selector) Width_Eq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Width_NotEq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Width_LT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Width_LE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Width_GT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Width_GE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Width >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Selector) Height_In(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Height IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) Height_Ins(ins ...int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Height IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) Height_NotIn(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Height NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Selector) Height_Eq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Height_NotEq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Height_LT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Height_LE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Height_GT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Height_GE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Height >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Selector) Size_In(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Size IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) Size_Ins(ins ...int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Size IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) Size_NotIn(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Size NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Selector) Size_Eq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Size_NotEq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Size_LT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Size_LE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Size_GT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Size_GE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Size >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Selector) Duration_In(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Duration IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) Duration_Ins(ins ...int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Duration IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) Duration_NotIn(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Duration NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Selector) Duration_Eq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Duration_NotEq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Duration_LT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Duration_LE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Duration_GT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Duration_GE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Duration >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Selector) CreatedTime_In(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) CreatedTime_Ins(ins ...int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) CreatedTime_NotIn(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Selector) CreatedTime_Eq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) CreatedTime_NotEq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) CreatedTime_LT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) CreatedTime_LE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) CreatedTime_GT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) CreatedTime_GE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Selector) ViewCount_In(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ViewCount IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) ViewCount_Ins(ins ...int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ViewCount IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) ViewCount_NotIn(ins []int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ViewCount NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Selector) ViewCount_Eq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) ViewCount_NotEq(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) ViewCount_LT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) ViewCount_LE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) ViewCount_GT(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) ViewCount_GE(val int) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ViewCount >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
///// for strings //copy of above with type int -> string + rm if eq + $ms_str_cond
////////ints
func (u *__PostMedia_Deleter) Extension_In(ins []string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Extension IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) Extension_NotIn(ins []string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Extension NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__PostMedia_Deleter) Extension_Like(val string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extension LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Deleter) Extension_Eq(val string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extension = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Extension_NotEq(val string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extension != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Deleter) Md5Hash_In(ins []string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Md5Hash IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) Md5Hash_NotIn(ins []string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Md5Hash NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__PostMedia_Deleter) Md5Hash_Like(val string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Md5Hash LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Deleter) Md5Hash_Eq(val string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Md5Hash = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Md5Hash_NotEq(val string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Md5Hash != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Deleter) Color_In(ins []string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Color IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) Color_NotIn(ins []string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Color NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__PostMedia_Deleter) Color_Like(val string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Color LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Deleter) Color_Eq(val string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Color = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Color_NotEq(val string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Color != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Deleter) Extra_In(ins []string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Extra IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Deleter) Extra_NotIn(ins []string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Extra NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__PostMedia_Deleter) Extra_Like(val string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extra LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Deleter) Extra_Eq(val string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extra = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Deleter) Extra_NotEq(val string) *__PostMedia_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extra != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
////////ints
func (u *__PostMedia_Updater) Extension_In(ins []string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Extension IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) Extension_NotIn(ins []string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Extension NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__PostMedia_Updater) Extension_Like(val string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extension LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Updater) Extension_Eq(val string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extension = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Extension_NotEq(val string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extension != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Updater) Md5Hash_In(ins []string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Md5Hash IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) Md5Hash_NotIn(ins []string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Md5Hash NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__PostMedia_Updater) Md5Hash_Like(val string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Md5Hash LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Updater) Md5Hash_Eq(val string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Md5Hash = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Md5Hash_NotEq(val string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Md5Hash != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Updater) Color_In(ins []string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Color IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) Color_NotIn(ins []string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Color NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__PostMedia_Updater) Color_Like(val string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Color LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Updater) Color_Eq(val string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Color = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Color_NotEq(val string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Color != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Updater) Extra_In(ins []string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Extra IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Updater) Extra_NotIn(ins []string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Extra NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__PostMedia_Updater) Extra_Like(val string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extra LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Updater) Extra_Eq(val string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extra = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Updater) Extra_NotEq(val string) *__PostMedia_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extra != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
////////ints
func (u *__PostMedia_Selector) Extension_In(ins []string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Extension IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) Extension_NotIn(ins []string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Extension NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__PostMedia_Selector) Extension_Like(val string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extension LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Selector) Extension_Eq(val string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extension = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Extension_NotEq(val string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extension != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Selector) Md5Hash_In(ins []string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Md5Hash IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) Md5Hash_NotIn(ins []string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Md5Hash NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__PostMedia_Selector) Md5Hash_Like(val string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Md5Hash LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Selector) Md5Hash_Eq(val string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Md5Hash = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Md5Hash_NotEq(val string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Md5Hash != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Selector) Color_In(ins []string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Color IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) Color_NotIn(ins []string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Color NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__PostMedia_Selector) Color_Like(val string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Color LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Selector) Color_Eq(val string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Color = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Color_NotEq(val string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Color != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__PostMedia_Selector) Extra_In(ins []string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Extra IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__PostMedia_Selector) Extra_NotIn(ins []string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Extra NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__PostMedia_Selector) Extra_Like(val string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extra LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__PostMedia_Selector) Extra_Eq(val string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extra = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__PostMedia_Selector) Extra_NotEq(val string) *__PostMedia_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Extra != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
/// End of wheres for selectors , updators, deletor
/////////////////////////////// Updater /////////////////////////////
//ints
func (u *__PostMedia_Updater) MediaId(newVal int) *__PostMedia_Updater {
up := updateCol{" MediaId = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" MediaId = " + u.nextDollar()] = newVal
return u
}
func (u *__PostMedia_Updater) MediaId_Increment(count int) *__PostMedia_Updater {
if count > 0 {
up := updateCol{" MediaId = MediaId+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" MediaId = MediaId+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" MediaId = MediaId- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" MediaId = MediaId- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__PostMedia_Updater) UserId(newVal int) *__PostMedia_Updater {
up := updateCol{" UserId = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" UserId = " + u.nextDollar()] = newVal
return u
}
func (u *__PostMedia_Updater) UserId_Increment(count int) *__PostMedia_Updater {
if count > 0 {
up := updateCol{" UserId = UserId+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" UserId = UserId+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" UserId = UserId- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" UserId = UserId- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__PostMedia_Updater) PostId(newVal int) *__PostMedia_Updater {
up := updateCol{" PostId = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" PostId = " + u.nextDollar()] = newVal
return u
}
func (u *__PostMedia_Updater) PostId_Increment(count int) *__PostMedia_Updater {
if count > 0 {
up := updateCol{" PostId = PostId+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" PostId = PostId+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" PostId = PostId- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" PostId = PostId- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__PostMedia_Updater) AlbumId(newVal int) *__PostMedia_Updater {
up := updateCol{" AlbumId = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" AlbumId = " + u.nextDollar()] = newVal
return u
}
func (u *__PostMedia_Updater) AlbumId_Increment(count int) *__PostMedia_Updater {
if count > 0 {
up := updateCol{" AlbumId = AlbumId+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" AlbumId = AlbumId+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" AlbumId = AlbumId- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" AlbumId = AlbumId- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__PostMedia_Updater) MediaTypeEnum(newVal int) *__PostMedia_Updater {
up := updateCol{" MediaTypeEnum = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" MediaTypeEnum = " + u.nextDollar()] = newVal
return u
}
func (u *__PostMedia_Updater) MediaTypeEnum_Increment(count int) *__PostMedia_Updater {
if count > 0 {
up := updateCol{" MediaTypeEnum = MediaTypeEnum+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" MediaTypeEnum = MediaTypeEnum+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" MediaTypeEnum = MediaTypeEnum- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" MediaTypeEnum = MediaTypeEnum- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__PostMedia_Updater) Width(newVal int) *__PostMedia_Updater {
up := updateCol{" Width = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" Width = " + u.nextDollar()] = newVal
return u
}
func (u *__PostMedia_Updater) Width_Increment(count int) *__PostMedia_Updater {
if count > 0 {
up := updateCol{" Width = Width+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" Width = Width+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" Width = Width- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" Width = Width- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__PostMedia_Updater) Height(newVal int) *__PostMedia_Updater {
up := updateCol{" Height = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" Height = " + u.nextDollar()] = newVal
return u
}
func (u *__PostMedia_Updater) Height_Increment(count int) *__PostMedia_Updater {
if count > 0 {
up := updateCol{" Height = Height+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" Height = Height+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" Height = Height- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" Height = Height- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__PostMedia_Updater) Size(newVal int) *__PostMedia_Updater {
up := updateCol{" Size = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" Size = " + u.nextDollar()] = newVal
return u
}
func (u *__PostMedia_Updater) Size_Increment(count int) *__PostMedia_Updater {
if count > 0 {
up := updateCol{" Size = Size+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" Size = Size+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" Size = Size- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" Size = Size- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__PostMedia_Updater) Duration(newVal int) *__PostMedia_Updater {
up := updateCol{" Duration = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" Duration = " + u.nextDollar()] = newVal
return u
}
func (u *__PostMedia_Updater) Duration_Increment(count int) *__PostMedia_Updater {
if count > 0 {
up := updateCol{" Duration = Duration+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" Duration = Duration+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" Duration = Duration- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" Duration = Duration- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
//string
func (u *__PostMedia_Updater) Extension(newVal string) *__PostMedia_Updater {
up := updateCol{"Extension = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" Extension = "+ u.nextDollar()] = newVal
return u
}
//ints
//string
func (u *__PostMedia_Updater) Md5Hash(newVal string) *__PostMedia_Updater {
up := updateCol{"Md5Hash = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" Md5Hash = "+ u.nextDollar()] = newVal
return u
}
//ints
//string
func (u *__PostMedia_Updater) Color(newVal string) *__PostMedia_Updater {
up := updateCol{"Color = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" Color = "+ u.nextDollar()] = newVal
return u
}
//ints
func (u *__PostMedia_Updater) CreatedTime(newVal int) *__PostMedia_Updater {
up := updateCol{" CreatedTime = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" CreatedTime = " + u.nextDollar()] = newVal
return u
}
func (u *__PostMedia_Updater) CreatedTime_Increment(count int) *__PostMedia_Updater {
if count > 0 {
up := updateCol{" CreatedTime = CreatedTime+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" CreatedTime = CreatedTime+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" CreatedTime = CreatedTime- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" CreatedTime = CreatedTime- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__PostMedia_Updater) ViewCount(newVal int) *__PostMedia_Updater {
up := updateCol{" ViewCount = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" ViewCount = " + u.nextDollar()] = newVal
return u
}
func (u *__PostMedia_Updater) ViewCount_Increment(count int) *__PostMedia_Updater {
if count > 0 {
up := updateCol{" ViewCount = ViewCount+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" ViewCount = ViewCount+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" ViewCount = ViewCount- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" ViewCount = ViewCount- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
//string
func (u *__PostMedia_Updater) Extra(newVal string) *__PostMedia_Updater {
up := updateCol{"Extra = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" Extra = "+ u.nextDollar()] = newVal
return u
}
/////////////////////////////////////////////////////////////////////
/////////////////////// Selector ///////////////////////////////////
//Select_* can just be used with: .GetString() , .GetStringSlice(), .GetInt() ..GetIntSlice()
func (u *__PostMedia_Selector) OrderBy_MediaId_Desc() *__PostMedia_Selector {
u.orderBy = " ORDER BY MediaId DESC "
return u
}
func (u *__PostMedia_Selector) OrderBy_MediaId_Asc() *__PostMedia_Selector {
u.orderBy = " ORDER BY MediaId ASC "
return u
}
func (u *__PostMedia_Selector) Select_MediaId() *__PostMedia_Selector {
u.selectCol = "MediaId"
return u
}
func (u *__PostMedia_Selector) OrderBy_UserId_Desc() *__PostMedia_Selector {
u.orderBy = " ORDER BY UserId DESC "
return u
}
func (u *__PostMedia_Selector) OrderBy_UserId_Asc() *__PostMedia_Selector {
u.orderBy = " ORDER BY UserId ASC "
return u
}
func (u *__PostMedia_Selector) Select_UserId() *__PostMedia_Selector {
u.selectCol = "UserId"
return u
}
func (u *__PostMedia_Selector) OrderBy_PostId_Desc() *__PostMedia_Selector {
u.orderBy = " ORDER BY PostId DESC "
return u
}
func (u *__PostMedia_Selector) OrderBy_PostId_Asc() *__PostMedia_Selector {
u.orderBy = " ORDER BY PostId ASC "
return u
}
func (u *__PostMedia_Selector) Select_PostId() *__PostMedia_Selector {
u.selectCol = "PostId"
return u
}
func (u *__PostMedia_Selector) OrderBy_AlbumId_Desc() *__PostMedia_Selector {
u.orderBy = " ORDER BY AlbumId DESC "
return u
}
func (u *__PostMedia_Selector) OrderBy_AlbumId_Asc() *__PostMedia_Selector {
u.orderBy = " ORDER BY AlbumId ASC "
return u
}
func (u *__PostMedia_Selector) Select_AlbumId() *__PostMedia_Selector {
u.selectCol = "AlbumId"
return u
}
func (u *__PostMedia_Selector) OrderBy_MediaTypeEnum_Desc() *__PostMedia_Selector {
u.orderBy = " ORDER BY MediaTypeEnum DESC "
return u
}
func (u *__PostMedia_Selector) OrderBy_MediaTypeEnum_Asc() *__PostMedia_Selector {
u.orderBy = " ORDER BY MediaTypeEnum ASC "
return u
}
func (u *__PostMedia_Selector) Select_MediaTypeEnum() *__PostMedia_Selector {
u.selectCol = "MediaTypeEnum"
return u
}
func (u *__PostMedia_Selector) OrderBy_Width_Desc() *__PostMedia_Selector {
u.orderBy = " ORDER BY Width DESC "
return u
}
func (u *__PostMedia_Selector) OrderBy_Width_Asc() *__PostMedia_Selector {
u.orderBy = " ORDER BY Width ASC "
return u
}
func (u *__PostMedia_Selector) Select_Width() *__PostMedia_Selector {
u.selectCol = "Width"
return u
}
func (u *__PostMedia_Selector) OrderBy_Height_Desc() *__PostMedia_Selector {
u.orderBy = " ORDER BY Height DESC "
return u
}
func (u *__PostMedia_Selector) OrderBy_Height_Asc() *__PostMedia_Selector {
u.orderBy = " ORDER BY Height ASC "
return u
}
func (u *__PostMedia_Selector) Select_Height() *__PostMedia_Selector {
u.selectCol = "Height"
return u
}
func (u *__PostMedia_Selector) OrderBy_Size_Desc() *__PostMedia_Selector {
u.orderBy = " ORDER BY Size DESC "
return u
}
func (u *__PostMedia_Selector) OrderBy_Size_Asc() *__PostMedia_Selector {
u.orderBy = " ORDER BY Size ASC "
return u
}
func (u *__PostMedia_Selector) Select_Size() *__PostMedia_Selector {
u.selectCol = "Size"
return u
}
func (u *__PostMedia_Selector) OrderBy_Duration_Desc() *__PostMedia_Selector {
u.orderBy = " ORDER BY Duration DESC "
return u
}
func (u *__PostMedia_Selector) OrderBy_Duration_Asc() *__PostMedia_Selector {
u.orderBy = " ORDER BY Duration ASC "
return u
}
func (u *__PostMedia_Selector) Select_Duration() *__PostMedia_Selector {
u.selectCol = "Duration"
return u
}
func (u *__PostMedia_Selector) OrderBy_Extension_Desc() *__PostMedia_Selector {
u.orderBy = " ORDER BY Extension DESC "
return u
}
func (u *__PostMedia_Selector) OrderBy_Extension_Asc() *__PostMedia_Selector {
u.orderBy = " ORDER BY Extension ASC "
return u
}
func (u *__PostMedia_Selector) Select_Extension() *__PostMedia_Selector {
u.selectCol = "Extension"
return u
}
func (u *__PostMedia_Selector) OrderBy_Md5Hash_Desc() *__PostMedia_Selector {
u.orderBy = " ORDER BY Md5Hash DESC "
return u
}
func (u *__PostMedia_Selector) OrderBy_Md5Hash_Asc() *__PostMedia_Selector {
u.orderBy = " ORDER BY Md5Hash ASC "
return u
}
func (u *__PostMedia_Selector) Select_Md5Hash() *__PostMedia_Selector {
u.selectCol = "Md5Hash"
return u
}
func (u *__PostMedia_Selector) OrderBy_Color_Desc() *__PostMedia_Selector {
u.orderBy = " ORDER BY Color DESC "
return u
}
func (u *__PostMedia_Selector) OrderBy_Color_Asc() *__PostMedia_Selector {
u.orderBy = " ORDER BY Color ASC "
return u
}
func (u *__PostMedia_Selector) Select_Color() *__PostMedia_Selector {
u.selectCol = "Color"
return u
}
func (u *__PostMedia_Selector) OrderBy_CreatedTime_Desc() *__PostMedia_Selector {
u.orderBy = " ORDER BY CreatedTime DESC "
return u
}
func (u *__PostMedia_Selector) OrderBy_CreatedTime_Asc() *__PostMedia_Selector {
u.orderBy = " ORDER BY CreatedTime ASC "
return u
}
func (u *__PostMedia_Selector) Select_CreatedTime() *__PostMedia_Selector {
u.selectCol = "CreatedTime"
return u
}
func (u *__PostMedia_Selector) OrderBy_ViewCount_Desc() *__PostMedia_Selector {
u.orderBy = " ORDER BY ViewCount DESC "
return u
}
func (u *__PostMedia_Selector) OrderBy_ViewCount_Asc() *__PostMedia_Selector {
u.orderBy = " ORDER BY ViewCount ASC "
return u
}
func (u *__PostMedia_Selector) Select_ViewCount() *__PostMedia_Selector {
u.selectCol = "ViewCount"
return u
}
func (u *__PostMedia_Selector) OrderBy_Extra_Desc() *__PostMedia_Selector {
u.orderBy = " ORDER BY Extra DESC "
return u
}
func (u *__PostMedia_Selector) OrderBy_Extra_Asc() *__PostMedia_Selector {
u.orderBy = " ORDER BY Extra ASC "
return u
}
func (u *__PostMedia_Selector) Select_Extra() *__PostMedia_Selector {
u.selectCol = "Extra"
return u
}
func (u *__PostMedia_Selector) Limit(num int) *__PostMedia_Selector {
u.limit = num
return u
}
func (u *__PostMedia_Selector) Offset(num int) *__PostMedia_Selector {
u.offset = num
return u
}
func (u *__PostMedia_Selector) Order_Rand() *__PostMedia_Selector {
u.orderBy = " ORDER BY RAND() "
return u
}
///////////////////////// Queryer Selector //////////////////////////////////
func (u *__PostMedia_Selector) _stoSql() (string, []interface{}) {
sqlWherrs, whereArgs := whereClusesToSql(u.wheres, u.whereSep)
sqlstr := "SELECT " + u.selectCol + " FROM sun.post_media"
if len(strings.Trim(sqlWherrs, " ")) > 0 { //2 for safty
sqlstr += " WHERE " + sqlWherrs
}
if u.orderBy != "" {
sqlstr += u.orderBy
}
if u.limit != 0 {
sqlstr += " LIMIT " + strconv.Itoa(u.limit)
}
if u.offset != 0 {
sqlstr += " OFFSET " + strconv.Itoa(u.offset)
}
return sqlstr, whereArgs
}
func (u *__PostMedia_Selector) GetRow(db *sqlx.DB) (*PostMedia, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.PostMedia {
XOLog(sqlstr, whereArgs)
}
row := &PostMedia{}
//by Sqlx
err = db.Get(row, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.PostMedia {
XOLogErr(err)
}
return nil, err
}
row._exists = true
OnPostMedia_LoadOne(row)
return row, nil
}
func (u *__PostMedia_Selector) GetRows(db *sqlx.DB) ([]*PostMedia, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.PostMedia {
XOLog(sqlstr, whereArgs)
}
var rows []*PostMedia
//by Sqlx
err = db.Unsafe().Select(&rows, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.PostMedia {
XOLogErr(err)
}
return nil, err
}
/*for i:=0;i< len(rows);i++ {
rows[i]._exists = true
}*/
for i := 0; i < len(rows); i++ {
rows[i]._exists = true
}
OnPostMedia_LoadMany(rows)
return rows, nil
}
//dep use GetRows()
func (u *__PostMedia_Selector) GetRows2(db *sqlx.DB) ([]PostMedia, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.PostMedia {
XOLog(sqlstr, whereArgs)
}
var rows []*PostMedia
//by Sqlx
err = db.Unsafe().Select(&rows, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.PostMedia {
XOLogErr(err)
}
return nil, err
}
/*for i:=0;i< len(rows);i++ {
rows[i]._exists = true
}*/
for i := 0; i < len(rows); i++ {
rows[i]._exists = true
}
OnPostMedia_LoadMany(rows)
rows2 := make([]PostMedia, len(rows))
for i := 0; i < len(rows); i++ {
cp := *rows[i]
rows2[i] = cp
}
return rows2, nil
}
func (u *__PostMedia_Selector) GetString(db *sqlx.DB) (string, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.PostMedia {
XOLog(sqlstr, whereArgs)
}
var res string
//by Sqlx
err = db.Get(&res, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.PostMedia {
XOLogErr(err)
}
return "", err
}
return res, nil
}
func (u *__PostMedia_Selector) GetStringSlice(db *sqlx.DB) ([]string, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.PostMedia {
XOLog(sqlstr, whereArgs)
}
var rows []string
//by Sqlx
err = db.Select(&rows, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.PostMedia {
XOLogErr(err)
}
return nil, err
}
return rows, nil
}
func (u *__PostMedia_Selector) GetIntSlice(db *sqlx.DB) ([]int, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.PostMedia {
XOLog(sqlstr, whereArgs)
}
var rows []int
//by Sqlx
err = db.Select(&rows, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.PostMedia {
XOLogErr(err)
}
return nil, err
}
return rows, nil
}
func (u *__PostMedia_Selector) GetInt(db *sqlx.DB) (int, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.PostMedia {
XOLog(sqlstr, whereArgs)
}
var res int
//by Sqlx
err = db.Get(&res, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.PostMedia {
XOLogErr(err)
}
return 0, err
}
return res, nil
}
///////////////////////// Queryer Update Delete //////////////////////////////////
func (u *__PostMedia_Updater) Update(db XODB) (int, error) {
var err error
var updateArgs []interface{}
var sqlUpdateArr []string
/*for up, newVal := range u.updates {
sqlUpdateArr = append(sqlUpdateArr, up)
updateArgs = append(updateArgs, newVal)
}*/
for _, up := range u.updates {
sqlUpdateArr = append(sqlUpdateArr, up.col)
updateArgs = append(updateArgs, up.val)
}
sqlUpdate := strings.Join(sqlUpdateArr, ",")
sqlWherrs, whereArgs := whereClusesToSql(u.wheres, u.whereSep)
var allArgs []interface{}
allArgs = append(allArgs, updateArgs...)
allArgs = append(allArgs, whereArgs...)
sqlstr := `UPDATE sun.post_media SET ` + sqlUpdate
if len(strings.Trim(sqlWherrs, " ")) > 0 { //2 for safty
sqlstr += " WHERE " + sqlWherrs
}
if LogTableSqlReq.PostMedia {
XOLog(sqlstr, allArgs)
}
res, err := db.Exec(sqlstr, allArgs...)
if err != nil {
if LogTableSqlReq.PostMedia {
XOLogErr(err)
}
return 0, err
}
num, err := res.RowsAffected()
if err != nil {
if LogTableSqlReq.PostMedia {
XOLogErr(err)
}
return 0, err
}
return int(num), nil
}
func (d *__PostMedia_Deleter) Delete(db XODB) (int, error) {
var err error
var wheresArr []string
for _, w := range d.wheres {
wheresArr = append(wheresArr, w.condition)
}
wheresStr := strings.Join(wheresArr, d.whereSep)
var args []interface{}
for _, w := range d.wheres {
args = append(args, w.args...)
}
sqlstr := "DELETE FROM sun.post_media WHERE " + wheresStr
// run query
if LogTableSqlReq.PostMedia {
XOLog(sqlstr, args)
}
res, err := db.Exec(sqlstr, args...)
if err != nil {
if LogTableSqlReq.PostMedia {
XOLogErr(err)
}
return 0, err
}
// retrieve id
num, err := res.RowsAffected()
if err != nil {
if LogTableSqlReq.PostMedia {
XOLogErr(err)
}
return 0, err
}
return int(num), nil
}
///////////////////////// Mass insert - replace for PostMedia ////////////////
func MassInsert_PostMedia(rows []PostMedia, db XODB) error {
if len(rows) == 0 {
return errors.New("rows slice should not be empty - inserted nothing")
}
var err error
ln := len(rows)
// insVals_:= strings.Repeat(s, ln)
// insVals := insVals_[0:len(insVals_)-1]
insVals := helper.SqlManyDollars(15, ln, true)
// sql query
sqlstr := "INSERT INTO sun.post_media (" +
"MediaId, UserId, PostId, AlbumId, MediaTypeEnum, Width, Height, Size, Duration, Extension, Md5Hash, Color, CreatedTime, ViewCount, Extra" +
") VALUES " + insVals
// run query
vals := make([]interface{}, 0, ln*5) //5 fields
for _, row := range rows {
// vals = append(vals,row.UserId)
vals = append(vals, row.MediaId)
vals = append(vals, row.UserId)
vals = append(vals, row.PostId)
vals = append(vals, row.AlbumId)
vals = append(vals, row.MediaTypeEnum)
vals = append(vals, row.Width)
vals = append(vals, row.Height)
vals = append(vals, row.Size)
vals = append(vals, row.Duration)
vals = append(vals, row.Extension)
vals = append(vals, row.Md5Hash)
vals = append(vals, row.Color)
vals = append(vals, row.CreatedTime)
vals = append(vals, row.ViewCount)
vals = append(vals, row.Extra)
}
if LogTableSqlReq.PostMedia {
XOLog(sqlstr, " MassInsert len = ", ln, vals)
}
_, err = db.Exec(sqlstr, vals...)
if err != nil {
if LogTableSqlReq.PostMedia {
XOLogErr(err)
}
return err
}
return nil
}
func MassReplace_PostMedia(rows []PostMedia, db XODB) error {
if len(rows) == 0 {
return errors.New("rows slice should not be empty - inserted nothing")
}
var err error
ln := len(rows)
// insVals_:= strings.Repeat(s, ln)
// insVals := insVals_[0:len(insVals_)-1]
insVals := helper.SqlManyDollars(15, ln, true)
// sql query
sqlstr := "REPLACE INTO sun.post_media (" +
"MediaId, UserId, PostId, AlbumId, MediaTypeEnum, Width, Height, Size, Duration, Extension, Md5Hash, Color, CreatedTime, ViewCount, Extra" +
") VALUES " + insVals
// run query
vals := make([]interface{}, 0, ln*5) //5 fields
for _, row := range rows {
// vals = append(vals,row.UserId)
vals = append(vals, row.MediaId)
vals = append(vals, row.UserId)
vals = append(vals, row.PostId)
vals = append(vals, row.AlbumId)
vals = append(vals, row.MediaTypeEnum)
vals = append(vals, row.Width)
vals = append(vals, row.Height)
vals = append(vals, row.Size)
vals = append(vals, row.Duration)
vals = append(vals, row.Extension)
vals = append(vals, row.Md5Hash)
vals = append(vals, row.Color)
vals = append(vals, row.CreatedTime)
vals = append(vals, row.ViewCount)
vals = append(vals, row.Extra)
}
if LogTableSqlReq.PostMedia {
XOLog(sqlstr, " MassReplace len = ", ln, vals)
}
_, err = db.Exec(sqlstr, vals...)
if err != nil {
if LogTableSqlReq.PostMedia {
XOLogErr(err)
}
return err
}
return nil
}
//////////////////// Play ///////////////////////////////
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
|
package model
import "strconv"
const (
// Black is one of the two chess colors
Black = Color(iota)
// White is one of the two chess colors
White = Color(iota)
)
type (
// Color of a piece or player
Color uint8
// Position is a struct representing a chess piece's position
Position struct {
File, Rank uint8
}
// Board is a chess board of pieces
Board [8][8]*Piece
// SerializableBoard is a chess board of pieces that can be serialized
SerializableBoard []Piece
)
// NewPosition creates a new position
func NewPosition(file, rank uint8) Position {
switch {
case file >= 8:
panic("Error: Invalid file " + string(file))
case rank >= 8:
panic("Error: Invalid rank " + string(rank))
}
return Position{file, rank}
}
func newFullBoard() Board {
var board Board
// Create the pawns.
for i := uint8(0); i < 16; i++ {
color := Black
rank := uint8(6)
if i > 7 {
color = White
rank = 1
}
piece := NewPiece(Pawn, NewPosition(uint8(i%8), rank), color)
board[piece.Position.File][piece.Position.Rank] = piece
}
// Create the rest.
createTheBackLine(&board)
return board
}
func newBoardNoPawns() Board {
var board Board
createTheBackLine(&board)
return board
}
func newBoardFromSerializableBoard(serializableBoard SerializableBoard) *Board {
var board Board
for _, piece := range serializableBoard {
pieceCopy := piece
board[piece.File()][piece.Rank()] = &pieceCopy
}
return &board
}
func createTheBackLine(board *Board) {
for i := uint8(0); i < 4; i++ {
board[i][7] = NewPiece(PieceType(i), NewPosition(uint8(i), 7), Black)
board[i][0] = NewPiece(PieceType(i), NewPosition(uint8(i), 0), White)
pieceType := PieceType(i)
if i == 3 {
pieceType = PieceType(i + 1)
}
board[7-i][7] = NewPiece(pieceType, NewPosition(uint8(7-i), 7), Black)
board[7-i][0] = NewPiece(pieceType, NewPosition(uint8(7-i), 0), White)
}
}
// Piece get a piece from the board
func (board Board) Piece(pos Position) *Piece {
return board[pos.File][pos.Rank]
}
func (board Board) String() string {
out := ""
for rank := 7; rank >= 0; rank-- {
for file := 0; file < 8; file++ {
out += board[file][rank].String() + " "
}
out += "\n"
}
return out
}
func (pos Position) String() string {
return strconv.Itoa(int(pos.File)) + "," + strconv.Itoa(int(pos.Rank))
}
|
package goSolution
func longestConsecutive(nums []int) int {
set := make(map[int]bool)
for _, num := range nums {
set[num] = true
}
ret := 0
for _, num := range nums {
if set[num] {
t := 1
for l := num - 1; set[l]; l-- {
t += 1
set[l] = false
}
for r := num + 1; set[r]; r++ {
t += 1
set[r] = false
}
ret = max(ret, t)
}
}
return ret
}
|
// Package compute contains the client for Dimension Data's cloud compute API.
package compute
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"sync"
"time"
"github.com/DimensionDataResearch/go-dd-cloud-compute/compute/requests"
"github.com/pkg/errors"
)
// Client is the client for Dimension Data's cloud compute API.
type Client struct {
baseAddress string
username string
password string
maxRetryCount int
retryDelay time.Duration
stateLock *sync.Mutex
httpClient *http.Client
account *Account
isCancellationRequested bool
isExtendedLoggingEnabled bool
}
// NewClient creates a new cloud compute API client.
// region is the cloud compute region identifier.
func NewClient(region string, username string, password string) *Client {
baseAddress := fmt.Sprintf("https://api-%s.dimensiondata.com", region)
return NewClientWithBaseAddress(baseAddress, username, password)
}
// NewClientWithBaseAddress creates a new cloud compute API client using a custom end-point base address.
// baseAddress is the base URL of the CloudControl API end-point.
func NewClientWithBaseAddress(baseAddress string, username string, password string) *Client {
_, isExtendedLoggingEnabled := os.LookupEnv("MCP_EXTENDED_LOGGING")
return &Client{
baseAddress,
username,
password,
0,
0 * time.Second,
&sync.Mutex{},
&http.Client{},
nil,
false, // isCancellationRequested
isExtendedLoggingEnabled,
}
}
// Cancel cancels all pending WaitForXXX or HTTP request operations.
func (client *Client) Cancel() {
client.stateLock.Lock()
defer client.stateLock.Unlock()
client.isCancellationRequested = true
}
// Reset clears all cached data from the Client and resets cancellation (if required).
func (client *Client) Reset() {
client.stateLock.Lock()
defer client.stateLock.Unlock()
client.account = nil
client.isCancellationRequested = false
}
// EnableExtendedLogging enables logging of HTTP requests and responses.
func (client *Client) EnableExtendedLogging() {
client.stateLock.Lock()
defer client.stateLock.Unlock()
client.isExtendedLoggingEnabled = true
}
// DisableExtendedLogging disables logging of HTTP requests and responses.
func (client *Client) DisableExtendedLogging() {
client.stateLock.Lock()
defer client.stateLock.Unlock()
client.isExtendedLoggingEnabled = false
}
// IsExtendedLoggingEnabled determines if logging of HTTP requests and responses is enabled.
func (client *Client) IsExtendedLoggingEnabled() bool {
return client.isExtendedLoggingEnabled
}
// ConfigureRetry configures the client's retry facility.
// Set maxRetryCount to 0 (the default) to disable retry.
func (client *Client) ConfigureRetry(maxRetryCount int, retryDelay time.Duration) {
client.stateLock.Lock()
defer client.stateLock.Unlock()
if maxRetryCount < 0 {
maxRetryCount = 0
}
if retryDelay < 0*time.Second {
retryDelay = 5 * time.Second
}
client.maxRetryCount = maxRetryCount
client.retryDelay = retryDelay
}
// getOrganizationID gets the current user's organisation Id.
func (client *Client) getOrganizationID() (organizationID string, err error) {
account, err := client.GetAccount()
if err != nil {
return "", err
}
return account.OrganizationID, nil
}
// executeRequest performs the specified request and returns the entire response body, together with the HTTP status code.
func (client *Client) executeRequest(request *http.Request) (responseBody []byte, statusCode int, err error) {
haveRequestBody := request.Body != nil
// Cache request to enable retry.
var snapshot *requests.Snapshot
snapshot, err = requests.CreateSnapshotAndClose(request)
if err != nil {
return
}
if client.IsExtendedLoggingEnabled() {
var requestBody []byte
requestBody = snapshot.GetCachedRequestBody()
log.Printf("Invoking '%s' request to '%s'...",
request.Method,
request.URL.String(),
)
if len(requestBody) > 0 {
log.Printf("Request body: '%s'", string(requestBody))
} else {
switch request.Method {
case http.MethodGet:
case http.MethodHead:
break
default:
log.Printf("Request body is empty.")
}
}
}
request, err = snapshot.Copy()
if err != nil {
return
}
if haveRequestBody {
defer request.Body.Close()
}
response, err := client.httpClient.Do(request)
if err != nil {
log.Printf("Unexpected error while performing '%s' request to '%s': %s.",
request.Method,
request.URL.String(),
err,
)
for retryCount := 0; retryCount < client.maxRetryCount; retryCount++ {
if client.IsExtendedLoggingEnabled() {
log.Printf("Retrying '%s' request to '%s' (%d retries remaining)...",
request.Method,
request.URL.String(),
retryCount-client.maxRetryCount,
)
}
if client.isCancellationRequested {
log.Printf("Client indicates that cancellation of pending requests has been requested.")
err = &OperationCancelledError{
OperationDescription: fmt.Sprintf("%s of '%s'",
request.Method,
request.RequestURI,
),
}
return
}
// Try again with a fresh request.
request, err = snapshot.Copy()
if err != nil {
return
}
if haveRequestBody {
defer request.Body.Close()
}
response, err = client.httpClient.Do(request)
if err != nil {
if client.IsExtendedLoggingEnabled() {
log.Printf("Still failing - '%s' request to '%s': %s.",
request.Method,
request.URL.String(),
err,
)
}
continue
}
if client.IsExtendedLoggingEnabled() {
log.Printf("'%s' request to '%s' succeeded.",
request.Method,
request.URL.String(),
)
}
break
}
if err != nil {
err = errors.Wrapf(err, "Unexpected error while performing '%s' request to '%s': %s",
request.Method,
request.URL.String(),
err,
)
return
}
}
defer response.Body.Close()
statusCode = response.StatusCode
responseBody, err = ioutil.ReadAll(response.Body)
if err != nil {
err = errors.Wrapf(err, "error reading response body for '%s'", request.URL.String())
}
if client.IsExtendedLoggingEnabled() {
log.Printf("Response from '%s' (%d): '%s'",
request.URL.String(),
statusCode,
string(responseBody),
)
}
return
}
// Create a basic request for the compute API (V1, XML).
func (client *Client) newRequestV1(relativeURI string, method string, body interface{}) (*http.Request, error) {
requestURI := fmt.Sprintf("%s/oec/0.9/%s", client.baseAddress, relativeURI)
var (
request *http.Request
bodyReader io.Reader
err error
)
bodyReader, err = newReaderFromXML(body)
if err != nil {
return nil, err
}
request, err = http.NewRequest(method, requestURI, bodyReader)
if err != nil {
return nil, err
}
request.SetBasicAuth(client.username, client.password)
request.Header.Set("Accept", "text/xml; charset=utf-8")
if bodyReader != nil {
request.Header.Set("Content-Type", "text/xml")
}
return request, nil
}
// Create a basic request for the compute API (V2.2, JSON).
func (client *Client) newRequestV22(relativeURI string, method string, body interface{}) (*http.Request, error) {
return client.newRequestV2x(2, relativeURI, method, body)
}
// Create a basic request for the compute API (V2.3, JSON).
func (client *Client) newRequestV23(relativeURI string, method string, body interface{}) (*http.Request, error) {
return client.newRequestV2x(3, relativeURI, method, body)
}
// Create a basic request for the compute API (V2.4, JSON).
func (client *Client) newRequestV24(relativeURI string, method string, body interface{}) (*http.Request, error) {
return client.newRequestV2x(4, relativeURI, method, body)
}
// Create a basic request for the compute API (V2.5, JSON).
func (client *Client) newRequestV25(relativeURI string, method string, body interface{}) (*http.Request, error) {
return client.newRequestV2x(5, relativeURI, method, body)
}
// Create a basic request for the compute API (V2.5, JSON).
func (client *Client) newRequestV26(relativeURI string, method string, body interface{}) (*http.Request, error) {
return client.newRequestV2x(6, relativeURI, method, body)
}
// Create a basic request for the compute API (V2.9, JSON).
func (client *Client) newRequestV29(relativeURI string, method string, body interface{}) (*http.Request, error) {
return client.newRequestV2x(9, relativeURI, method, body)
}
// Create a basic request for the compute API (V2.9, JSON).
func (client *Client) newRequestV210(relativeURI string, method string, body interface{}) (*http.Request, error) {
return client.newRequestV2x(10, relativeURI, method, body)
}
// Create a basic request for the compute API (V2.13, JSON).
func (client *Client) newRequestV213(relativeURI string, method string, body interface{}) (*http.Request, error) {
return client.newRequestV2x(13, relativeURI, method, body)
}
// Create a basic request for the compute API (V2.x, JSON).
func (client *Client) newRequestV2x(minorVersion int, relativeURI string, method string, body interface{}) (*http.Request, error) {
requestURI := fmt.Sprintf("%s/caas/2.%d/%s", client.baseAddress, minorVersion, relativeURI)
var (
request *http.Request
bodyReader io.Reader
err error
)
bodyReader, err = newReaderFromJSON(body)
if err != nil {
return nil, err
}
request, err = http.NewRequest(method, requestURI, bodyReader)
if err != nil {
return nil, err
}
request.SetBasicAuth(client.username, client.password)
request.Header.Add("Accept", "application/json")
if bodyReader != nil {
request.Header.Set("Content-Type", "application/json")
}
return request, nil
}
// Read an APIResponseV1 (as XML) from the response body.
func readAPIResponseV1(responseBody []byte, statusCode int) (apiResponse *APIResponseV1, err error) {
apiResponse = &APIResponseV1{}
err = xml.Unmarshal(responseBody, apiResponse)
if err != nil {
err = errors.Wrapf(err, "error reading API response (v1) from XML")
return
}
if len(apiResponse.Result) == 0 {
apiResponse.Result = "UNKNOWN_RESULT"
}
if len(apiResponse.Message) == 0 {
apiResponse.Message = "An unexpected response was received from the compute API."
}
return
}
// Read an APIResponseV2 (as JSON) from the response body.
func readAPIResponseAsJSON(responseBody []byte, statusCode int) (apiResponse *APIResponseV2, err error) {
apiResponse = &APIResponseV2{}
err = json.Unmarshal(responseBody, apiResponse)
if err != nil {
err = errors.Wrapf(err, "error reading API response (v2) from JSON")
return
}
if len(apiResponse.ResponseCode) == 0 {
apiResponse.ResponseCode = "UNKNOWN_RESPONSE_CODE"
}
if len(apiResponse.Message) == 0 {
apiResponse.Message = "An unexpected response was received from the compute API."
}
return
}
// newReaderFromJSON serialises the specified data as JSON and returns an io.Reader over that JSON.
func newReaderFromJSON(data interface{}) (io.Reader, error) {
if data == nil {
return nil, nil
}
jsonData, err := json.Marshal(data)
if err != nil {
return nil, err
}
return bytes.NewReader(jsonData), nil
}
// newReaderFromXML serialises the specified data as XML and returns an io.Reader over that XML.
func newReaderFromXML(data interface{}) (io.Reader, error) {
if data == nil {
return nil, nil
}
xmlData, err := xml.Marshal(data)
if err != nil {
return nil, err
}
return bytes.NewReader(xmlData), nil
}
|
package service_example
import (
"fmt"
"github.com/muka/go-bluetooth/bluez/profile/gatt"
"github.com/muka/go-bluetooth/service"
log "github.com/sirupsen/logrus"
)
func registerApplication(adapterID string) (*service.Application, error) {
cfg := &service.ApplicationConfig{
AdapterID: adapterID,
UUIDSuffix: "-0000-1000-8000-00805F9B34FB",
UUID: "AAAA",
ObjectName: objectName,
ObjectPath: objectPath,
LocalName: "gobluetooth",
}
app, err := service.NewApplication(cfg)
if err != nil {
log.Errorf("Failed to initialize app: %s", err.Error())
return nil, err
}
err = app.Run()
if err != nil {
log.Errorf("Failed to run: %s", err.Error())
return nil, err
}
err = exposeService(
app,
app.GenerateUUID("1111"),
app.GenerateUUID("1111"),
app.GenerateUUID("1111"),
true,
)
if err != nil {
return nil, err
}
// err = exposeService(
// app,
// app.GenerateUUID("2222"),
// app.GenerateUUID("2222"),
// app.GenerateUUID("2222"),
// false,
// )
// if err != nil {
// return nil, err
// }
log.Info("Registering application to DBus")
//Register Application
gattManager, err := app.GetAdapter().GetGattManager()
if err != nil {
return nil, fmt.Errorf("GetGattManager: %s", err)
}
log.Debugf("Application path %s", app.Path())
err = gattManager.RegisterApplication(app.Path(), map[string]interface{}{})
if err != nil {
return nil, fmt.Errorf("RegisterApplication: %s", err.Error())
}
log.Info("Starting device advertising")
// Register our advertisement
err = app.StartAdvertising()
if err != nil {
return nil, fmt.Errorf("StartAdvertising: %s", err)
}
log.Info("Application is ready.")
return app, nil
}
func exposeService(
app *service.Application,
serviceUUID, characteristicUUID, descriptorUUID string,
advertise bool,
) error {
serviceProps := service.NewGattService1Properties(serviceUUID)
// Set this service to be advertised
service1, err := app.CreateService(serviceProps, advertise)
if err != nil {
log.Errorf("Failed to create service: %s", err.Error())
return err
}
err = app.AddService(service1)
if err != nil {
log.Errorf("Failed to add service: %s", err.Error())
return err
}
charProps := &gatt.GattCharacteristic1Properties{
UUID: characteristicUUID,
Flags: []string{
gatt.FlagCharacteristicRead,
gatt.FlagCharacteristicWrite,
},
}
char, err := service1.CreateCharacteristic(charProps)
if err != nil {
log.Errorf("Failed to create char: %s", err)
return err
}
err = service1.AddCharacteristic(char)
if err != nil {
log.Errorf("Failed to add char: %s", err)
return err
}
descProps := &gatt.GattDescriptor1Properties{
UUID: descriptorUUID,
Flags: []string{
gatt.FlagDescriptorRead,
gatt.FlagDescriptorWrite,
},
}
desc, err := char.CreateDescriptor(descProps)
if err != nil {
log.Errorf("Failed to create char: %s", err.Error())
return err
}
err = char.AddDescriptor(desc)
if err != nil {
log.Errorf("Failed to add desc: %s", err.Error())
return err
}
return nil
}
|
package ackhandler
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Send Mode", func() {
It("has a string representation", func() {
Expect(SendNone.String()).To(Equal("none"))
Expect(SendAny.String()).To(Equal("any"))
Expect(SendAck.String()).To(Equal("ack"))
Expect(SendRTO.String()).To(Equal("rto"))
Expect(SendTLP.String()).To(Equal("tlp"))
Expect(SendRetransmission.String()).To(Equal("retransmission"))
Expect(SendMode(123).String()).To(Equal("invalid send mode: 123"))
})
})
|
package models
import (
"fmt"
"time"
"github.com/mmcdole/gofeed/extensions"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type User struct {
ID bson.ObjectId `bson:"_id"`
Username string `bson:"username"`
Lastname string `bson:"lastname"`
Firstname string `bson:"firstname"`
Photourl string `bson:"photourl"`
Hash string `bson:"hash"`
SubscribeFeedURLs []string `bson:"subscribeFeedURLs"`
UnReadItems []bson.ObjectId `bson:"unReadItems"`
StarItems []bson.ObjectId `bson:"starItems"`
ReadItLaterItems []bson.ObjectId `bson:"readItLaterItems"`
}
// Unique field "FeedURL" in order to prevent feed polution
type Feed struct {
ID bson.ObjectId `bson:"_id"`
FeedURL string `bson:"feedURL"`
Title string `bson:"title"`
Description string `bson:"description"`
Link string `bson:"link"`
FeedLink string `bson:"feedLink"`
Updated string `bson:"updated"`
UpdatedParsed *time.Time `bson:"updatedParsed"`
Published string `bson:"published"`
PublishedParsed *time.Time `bson:"publishedParsed"`
Author *Person `bson:"author"`
Language string `bson:"language"`
Image *Image `bson:"image"`
Copyright string `bson:"copyright"`
Generator string `bson:"generator"`
Categories []string `bson:"categories"`
Extensions ext.Extensions `bson:"extensions"`
Custom map[string]string `bson:"custom"`
FeedType string `bson:"feedType"`
FeedVersion string `bson:"feedVersion"`
SubscribeCount int `bson:"subscribeCount"`
}
// Item is the universal Item type that atom.Entry
// and rss.Item gets translated to. It represents
// a single entry in a given feed.
type Item struct {
FeedID bson.ObjectId `bson:"feedID"`
Title string `bson:"title"`
Description string `bson:"description"`
Content string `bson:"content"`
Link string `bson:"link"`
Updated string `bson:"updated"`
UpdatedParsed *time.Time `bson:"updatedParsed"`
Published string `bson:"published"`
PublishedParsed *time.Time `bson:"publishedParsed"`
Author *Person `bson:"author"`
GUID string `bson:"guid"`
Image *Image `bson:"image"`
Categories []string `bson:"categories"`
Enclosures []*Enclosure `bson:"enclosures"`
Extensions ext.Extensions `bson:"extensions"`
Custom map[string]string `bson:"custom"`
StarCount int `bson:"starCount"`
}
// Person is an individual specified in a feed
// (e.g. an author)
type Person struct {
Name string `bson:"name"`
Email string `bson:"email"`
}
// Image is an image that is the artwork for a given
// feed or item.
type Image struct {
URL string `bson:"url"`
Title string `bson:"title"`
}
// Enclosure is a file associated with a given Item.
type Enclosure struct {
URL string `bson:"url"`
Length string `bson:"length"`
Type string `bson:"type"`
}
//
type Thing struct {
ID int
Name string
Content string
CreateTime time.Time
}
type Note struct {
ID int
Name string
Content string
CreateTime time.Time
}
type Session struct {
ID bson.ObjectId `bson:"_id"`
SessionID string `bson:"SessionId"`
}
var DBConfig = struct {
Username string
Password string
Host string
Port string
DBName string
}{}
//= =!
var Users *mgo.Collection
var Feeds *mgo.Collection
var Items *mgo.Collection
var Sessions *mgo.Collection
func Init() {
url := "mongodb://admin:feedall@127.0.0.1:27017/feedall"
Session, err := mgo.Dial(url)
if err != nil {
panic(err)
}
fmt.Println("Start dial mongodb!")
Users = Session.DB("feedall").C("users")
Feeds = Session.DB("feedall").C("feeds")
Items = Session.DB("feedall").C("items")
Sessions = Session.DB("feedall").C("sessions")
}
func Insert(collection *mgo.Collection, i interface{}) error {
return collection.Insert(i)
}
func FindOne(collection *mgo.Collection, q interface{}, i interface{}) error {
return collection.Find(q).One(i)
}
func FindAll(collection *mgo.Collection, q interface{}, i interface{}) error {
return collection.Find(q).All(i)
}
func FindSortLimit(collection *mgo.Collection, q interface{}, s string, n int, i interface{}) error {
return collection.Find(q).Sort(s).Limit(n).All(i)
}
func PipeAll(collection *mgo.Collection, q interface{}, i interface{}) error {
return collection.Pipe(q).All(i)
}
func PipeOne(collection *mgo.Collection, q interface{}, i interface{}) error {
return collection.Pipe(q).One(i)
}
func Update(collection *mgo.Collection, q interface{}, i interface{}) error {
return collection.Update(q, i)
}
func Upsert(collection *mgo.Collection, q interface{}, i interface{}) (info *mgo.ChangeInfo, err error) {
return collection.Upsert(q, i)
}
|
package api
import (
"bytes"
"fmt"
"github.com/gocarina/gocsv"
"os"
"regexp"
)
type Stop struct {
ID string `csv:"stop_id"`
Name string `csv:"stop_name"`
ParentID string `csv:"parent_station"`
stationID string
ChildIDs []string
}
type Station struct {
ID int
StopIDs []string
Name string
transfers []Transfer
}
type Transfer struct {
FromID string `csv:"from_stop_id"`
ToID string `csv:"to_stop_id"`
Time string `csv:"min_transfer_time"`
}
type StationManager struct {
stops map[string]Stop
stations map[int]Station
stationsByName map[string]int
nextStationID int
}
func NewStationManager() StationManager {
var sr = StationManager{}
sr.loadStops()
sr.initializeStations()
return sr
}
func (sr StationManager) GetStop(id string) Stop {
return sr.stops[id]
}
func (sr StationManager) GetStation(id int) Station {
return sr.stations[id]
}
func (sr StationManager) Stops() []Stop {
stops := make([]Stop, 0, len(sr.stops))
for _, stop := range sr.stops {
stops = append(stops, stop)
}
return stops
}
func (sr StationManager) StationsMatching(query string) (stations []Station) {
re, err := regexp.Compile(fmt.Sprintf("(?i).*%s.*", query))
if err != nil {
return stations
}
for name, id := range sr.stationsByName {
if re.MatchString(name) {
stations = append(stations, sr.stations[id])
}
}
return stations
}
func (s Station) HasStop(stop Stop) bool {
for _, stopID := range s.StopIDs {
if stopID == stop.ID {
return true
}
}
return false
}
func (sr *StationManager) loadStops() {
var stops = []Stop{}
stopsFile, err := os.OpenFile("./data/stops.csv", os.O_RDWR|os.O_CREATE, os.ModePerm)
if err != nil {
panic(err)
}
defer stopsFile.Close()
if err := gocsv.UnmarshalFile(stopsFile, &stops); err != nil {
panic(err)
}
sr.stops = make(map[string]Stop, len(stops))
for _, stop := range stops {
sr.stops[stop.ID] = stop
if stop.ParentID != "" {
// Assumes parents always read in first
parent := sr.stops[stop.ParentID]
parent.ChildIDs = append(parent.ChildIDs, stop.ID)
sr.stops[stop.ParentID] = parent
}
}
}
func (sr *StationManager) initializeStations() {
var transfers = []Transfer{}
transfersFile, err := os.OpenFile("./data/transfers.csv", os.O_RDWR|os.O_CREATE, os.ModePerm)
if err != nil {
panic(err)
}
defer transfersFile.Close()
if err := gocsv.UnmarshalFile(transfersFile, &transfers); err != nil {
panic(err)
}
sr.stations = make(map[int]Station, len(sr.stops))
sr.stationsByName = make(map[string]int, len(sr.stops))
sr.nextStationID = 1
for _, transfer := range transfers {
fstop := sr.stops[transfer.FromID]
tstop := sr.stops[transfer.ToID]
if fstop.Name == tstop.Name {
st := sr.getStationByName(fstop.Name)
if st.Name == "" {
st = sr.createStation(fstop.Name)
}
st.transfers = append(st.transfers, transfer)
st.addStops([]Stop{fstop, tstop})
st.addStops(sr.childStops(fstop))
st.addStops(sr.childStops(tstop))
sr.registerStation(st)
}
}
updatedStations := []Station{}
for _, station := range sr.stations {
stopIDSets := findDisjointStopIDSets(station.transfers)
if len(stopIDSets) > 1 {
var stationToModify Station
// split station into new station for each set
for idx, stopIDList := range stopIDSets {
if idx == 0 {
// cut down existing station
stationToModify = station
stationToModify.StopIDs = []string{}
} else {
// create new station for any additional sets
stationToModify = sr.createStation(station.Name)
}
for _, stopID := range stopIDList {
stop := sr.GetStop(stopID)
stationToModify.addStops([]Stop{stop})
stationToModify.addStops(sr.childStops(stop))
}
stationToModify.computeName()
updatedStations = append(updatedStations, stationToModify)
}
} else {
station.computeName()
updatedStations = append(updatedStations, station)
}
}
sr.resetStations()
for _, updatedStation := range updatedStations {
sr.registerStation(updatedStation)
}
}
func (sr *StationManager) createStation(name string) (s Station) {
s.ID = sr.nextStationID
s.Name = name
sr.nextStationID++
return s
}
func (sr *StationManager) registerStation(s Station) {
sr.stations[s.ID] = s
sr.stationsByName[s.Name] = s.ID
}
func (sr *StationManager) resetStations() {
sr.stations = map[int]Station{}
sr.stationsByName = map[string]int{}
}
func (sr StationManager) getStationByName(name string) Station {
return sr.stations[sr.stationsByName[name]]
}
func (s *Station) addStops(stops []Stop) {
for _, stop := range stops {
if s.HasStop(stop) {
continue
}
s.StopIDs = append(s.StopIDs, stop.ID)
}
}
func (s *Station) computeName() {
lines := map[rune]bool{}
for _, stopID := range s.StopIDs {
lines[rune(stopID[0])] = true
}
var name bytes.Buffer
name.WriteString(s.Name)
name.WriteString(" (")
idx := 0
for line := range lines {
name.WriteRune(line)
if idx < len(lines)-1 {
name.WriteRune(',')
}
idx++
}
name.WriteRune(')')
s.Name = name.String()
}
func (sr StationManager) childStops(s Stop) (children []Stop) {
for _, id := range s.ChildIDs {
children = append(children, sr.GetStop(id))
}
return children
}
func (t Transfer) stopIDs() []string {
return []string{t.FromID, t.ToID}
}
func findDisjointStopIDSets(transfers []Transfer) [][]string {
sets := make([]map[string]bool, 0)
for _, transfer := range transfers {
// keep track of which sets we find the transfer in
foundIn := make([]int, 0)
for setIdx, set := range sets {
if set[transfer.ToID] || set[transfer.FromID] {
set[transfer.ToID] = true
set[transfer.FromID] = true
foundIn = append(foundIn, setIdx)
}
}
if len(foundIn) > 1 {
// merge found in sets down to one set
newSets := make([]map[string]bool, 0)
combinedSet := make(map[string]bool, 0)
for setIdx, set := range sets {
if contains(foundIn, setIdx) {
for item := range set {
combinedSet[item] = true
}
} else {
newSets = append(newSets, set)
}
}
sets = append(newSets, combinedSet)
} else if len(foundIn) == 0 {
// create new set and add transfer to it
set := map[string]bool{transfer.ToID: true, transfer.FromID: true}
sets = append(sets, set)
}
}
results := [][]string{}
for _, set := range sets {
setArray := []string{}
for item := range set {
setArray = append(setArray, item)
}
results = append(results, setArray)
}
return results
}
func contains(nums []int, num int) bool {
for _, n := range nums {
if n == num {
return true
}
}
return false
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.