code
stringlengths 67
15.9k
| labels
listlengths 1
4
|
---|---|
package main
import "fmt"
func intSeq(i int) func() int{
return func() int{
i = i + 1
return i
}
}
func main(){
f := intSeq(5)
fmt.Println(f())
fmt.Println(f())
fmt.Println(f())
fmt.Println(f())
fmt.Println(f())
fmt.Println(f())
fmt.Println(f())
f1 := intSeq(0)
fmt.Println(f1())
}
|
[
0
] |
package main
import (
"fmt"
"sort"
"time"
)
const size = 60_000_000
const nLoop = 21
var arr [size]int
func main() {
sl := make([]int, size)
process("local mixed", mixed(sl))
process("local 1x", multi(mixed(sl), 1))
process("local 2x", multi(mixed(sl), 2))
process("local 3x", multi(mixed(sl), 3))
process("local ordered", ordered(sl))
process("local sorted", sorted(mixed(sl)))
sl = arr[:]
process("global mixed", mixed(sl))
process("global 1x", multi(mixed(sl), 1))
process("global 2x", multi(mixed(sl), 2))
process("global 3x", multi(mixed(sl), 3))
process("global ordered", ordered(sl))
process("global sorted", sorted(mixed(sl)))
}
func mixed(sl []int) []int {
for i := 0; i < size; i = i + 2 {
sl[i] = i + 1
}
for i := 1; i < size; i = i + 2 {
sl[i] = -(i + 1)
}
return sl
}
func multi(sl []int, k int) []int {
for i := 0; i < size; i = i + 3 {
sl[i] = sl[i] % k
}
return sl
}
func sorted(sl []int) []int {
sort.Ints(sl)
return sl
}
func ordered(sl []int) []int {
for i := 0; i < size; i++ {
sl[i] = i + 1
}
return sl
}
func process(name string, sl []int) {
start := time.Now()
sum := 0
for ir := 0; ir < nLoop; ir++ {
for _, v := range sl {
if v > 100 {
sum += v
}
}
}
dur := time.Since(start)
fmt.Printf("%-14s duration=%-15v sum=%v\n", name, dur, sum)
}
|
[
0
] |
package mredis
import (
"crypto/tls"
"fmt"
"github.com/silenceper/wechat/v2/cache"
"sync"
"time"
"github.com/go-redis/redis"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
const WX_ACCESS_TOKEN_KEY = "wx_access_token"
var initOnce sync.Once
type WXRedisCache struct {
cli *redis.Client
}
var wx_cache *WXRedisCache
func GetRedisCache() cache.Cache {
initOnce.Do(func() {
cfg := viper.Get("redis").(map[string]string)
conn_Addr := fmt.Sprintf("%s:%s", cfg["Host"], cfg["Port"])
logrus.Infof("%+v", cfg)
logrus.Info(conn_Addr)
rcli := redis.NewClient(&redis.Options{
Addr: conn_Addr,
DB: 1,
TLSConfig: &tls.Config{
ServerName: cfg["Host"],
InsecureSkipVerify: true},
})
wx_cache = &WXRedisCache{
cli: rcli,
}
})
return wx_cache
}
func (c *WXRedisCache) Get(key string) interface{} {
if res, err := c.cli.Get(key).Result(); err != nil {
logrus.Errorf("Get AccessToken Failed: %v", err.Error())
return nil
} else {
logrus.Infof("Get AccessToken: %s", res)
return res
}
}
func (c *WXRedisCache) Set(key string, val interface{}, timeout time.Duration) error {
logrus.Infof("Set AccessToken: %s:%v", key, val)
if err := c.cli.Set(key, val, time.Second*7200).Err(); err != nil {
logrus.Error(err.Error())
return err
}
return nil
}
func (c *WXRedisCache) IsExist(Key string) bool {
if res, err := c.cli.Exists(Key).Result(); err != nil {
return false
} else {
return res == 1
}
}
func (c *WXRedisCache) Delete(key string) error {
return c.cli.Del(key).Err()
}
|
[
2
] |
package simplecqrs
import (
"errors"
"log"
ycq "github.com/jetbasrawi/go.cqrs"
)
var bullShitDatabase *BullShitDatabase
// ReadModelFacade is an interface for the readmodel facade
type ReadModelFacade interface {
GetEmployees() []*EmployeeListDto
GetEmployeeDetails(uuid string) *EmployeeDetailsDto
}
// EmployeeDetailsDto holds details for an Employee item.
type EmployeeDetailsDto struct {
ID string
Name string
CurrentCount int
Version int
}
// EmployeeListDto provides a lightweight lookup view of an Employee item
type EmployeeListDto struct {
ID string
Name string
}
// ReadModel is an implementation of the ReadModelFacade interface.
//
// ReadModel provides an in memory read model.
type ReadModel struct {
}
// NewReadModel constructs a new read model
func NewReadModel() *ReadModel {
if bullShitDatabase == nil {
bullShitDatabase = NewBullShitDatabase()
}
return &ReadModel{}
}
// GetEmployees returns a slice of all Employee items
func (m *ReadModel) GetEmployees() []*EmployeeListDto {
return bullShitDatabase.List
}
// GetEmployeeDetails gets an EmployeeDetailsDto by ID
func (m *ReadModel) GetEmployeeDetails(uuid string) *EmployeeDetailsDto {
if i, ok := bullShitDatabase.Details[uuid]; ok {
return i
}
return nil
}
// EmployeeListView handles messages related to Employee and builds an
// in memory read model of Employee item summaries in a list.
type EmployeeListView struct {
}
// NewEmployeeListView constructs a new EmployeeListView
func NewEmployeeListView() *EmployeeListView {
if bullShitDatabase == nil {
bullShitDatabase = NewBullShitDatabase()
}
return &EmployeeListView{}
}
// Handle processes events related to Employee and builds an in memory read model
func (v *EmployeeListView) Handle(message ycq.EventMessage) {
switch event := message.Event().(type) {
case *EmployeeCreated:
bullShitDatabase.List = append(bullShitDatabase.List, &EmployeeListDto{
ID: message.AggregateID(),
Name: event.Name,
})
// case *EmployeeRenamed:
// for _, v := range bullShitDatabase.List {
// if v.ID == message.AggregateID() {
// v.Name = event.NewName
// break
// }
// }
// case *EmployeeDeactivated:
// i := -1
// for k, v := range bullShitDatabase.List {
// if v.ID == message.AggregateID() {
// i = k
// break
// }
// }
// if i >= 0 {
// bullShitDatabase.List = append(
// bullShitDatabase.List[:i],
// bullShitDatabase.List[i+1:]...,
// )
// }
}
}
// EmployeeDetailView handles messages related to Employee and builds an
// in memory read model of Employee item details.
type EmployeeDetailView struct {
}
// NewEmployeeDetailView constructs a new EmployeeDetailView
func NewEmployeeDetailView() *EmployeeDetailView {
if bullShitDatabase == nil {
bullShitDatabase = NewBullShitDatabase()
}
return &EmployeeDetailView{}
}
// Handle handles events and build the projection
func (v *EmployeeDetailView) Handle(message ycq.EventMessage) {
switch event := message.Event().(type) {
case *EmployeeCreated:
bullShitDatabase.Details[message.AggregateID()] = &EmployeeDetailsDto{
ID: message.AggregateID(),
Name: event.Name,
Version: 0,
}
case *ItemsRemovedFromEmployee:
d, err := v.GetDetailsItem(message.AggregateID())
if err != nil {
log.Fatal(err)
}
d.CurrentCount -= event.Count
case *ItemsCheckedIntoEmployee:
d, err := v.GetDetailsItem(message.AggregateID())
if err != nil {
log.Fatal(err)
}
d.CurrentCount += event.Count
}
}
// GetDetailsItem gets an EmployeeDetailsDto by ID
func (v *EmployeeDetailView) GetDetailsItem(id string) (*EmployeeDetailsDto, error) {
d, ok := bullShitDatabase.Details[id]
if !ok {
return nil, errors.New("did not find the original Employee this shouldn't not happen")
}
return d, nil
}
// BullShitDatabase is a simple in memory repository
type BullShitDatabase struct {
Details map[string]*EmployeeDetailsDto
List []*EmployeeListDto
}
// NewBullShitDatabase constructs a new BullShitDatabase
func NewBullShitDatabase() *BullShitDatabase {
return &BullShitDatabase{
Details: make(map[string]*EmployeeDetailsDto),
}
}
|
[
7
] |
// Copyright (c) 2017-2018 The qitmeer developers
// Copyright (c) 2013-2016 The btcsuite developers
// Copyright (c) 2017-2018 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package node
import (
"fmt"
"github.com/Qitmeer/qitmeer/common/math"
"github.com/Qitmeer/qitmeer/common/roughtime"
"github.com/Qitmeer/qitmeer/core/blockchain"
"github.com/Qitmeer/qitmeer/core/blockdag"
"github.com/Qitmeer/qitmeer/core/json"
"github.com/Qitmeer/qitmeer/core/protocol"
"github.com/Qitmeer/qitmeer/core/types/pow"
"github.com/Qitmeer/qitmeer/params"
"github.com/Qitmeer/qitmeer/rpc"
"github.com/Qitmeer/qitmeer/rpc/client/cmds"
"github.com/Qitmeer/qitmeer/services/common"
"github.com/Qitmeer/qitmeer/version"
"math/big"
"strconv"
"time"
)
func (nf *QitmeerFull) apis() []rpc.API {
return []rpc.API{
{
NameSpace: cmds.DefaultServiceNameSpace,
Service: NewPublicBlockChainAPI(nf),
Public: true,
},
{
NameSpace: cmds.TestNameSpace,
Service: NewPrivateBlockChainAPI(nf),
Public: false,
},
{
NameSpace: cmds.LogNameSpace,
Service: NewPrivateLogAPI(nf),
Public: false,
},
}
}
type PublicBlockChainAPI struct {
node *QitmeerFull
}
func NewPublicBlockChainAPI(node *QitmeerFull) *PublicBlockChainAPI {
return &PublicBlockChainAPI{node}
}
// Return the node info
func (api *PublicBlockChainAPI) GetNodeInfo() (interface{}, error) {
best := api.node.blockManager.GetChain().BestSnapshot()
node := api.node.blockManager.GetChain().BlockDAG().GetBlock(&best.Hash)
powNodes := api.node.blockManager.GetChain().GetCurrentPowDiff(node, pow.MEERXKECCAKV1)
ret := &json.InfoNodeResult{
ID: api.node.node.peerServer.PeerID().String(),
Version: int32(1000000*version.Major + 10000*version.Minor + 100*version.Patch),
BuildVersion: version.String(),
ProtocolVersion: int32(protocol.ProtocolVersion),
TotalSubsidy: best.TotalSubsidy,
TimeOffset: int64(api.node.blockManager.GetChain().TimeSource().Offset().Seconds()),
Connections: int32(len(api.node.node.peerServer.Peers().Connected())),
PowDiff: &json.PowDiff{
CurrentDiff: getDifficultyRatio(powNodes, api.node.node.Params, pow.MEERXKECCAKV1),
},
Network: params.ActiveNetParams.Name,
Confirmations: blockdag.StableConfirmations,
CoinbaseMaturity: int32(api.node.node.Params.CoinbaseMaturity),
Modules: []string{cmds.DefaultServiceNameSpace, cmds.MinerNameSpace, cmds.TestNameSpace, cmds.LogNameSpace},
}
ret.GraphState = GetGraphStateResult(best.GraphState)
hostdns := api.node.node.peerServer.HostDNS()
if hostdns != nil {
ret.DNS = hostdns.String()
}
if api.node.node.peerServer.Node() != nil {
ret.QNR = api.node.node.peerServer.Node().String()
}
if len(api.node.node.peerServer.HostAddress()) > 0 {
ret.Addresss = api.node.node.peerServer.HostAddress()
}
// soft forks
ret.ConsensusDeployment = make(map[string]*json.ConsensusDeploymentDesc)
for deployment, deploymentDetails := range params.ActiveNetParams.Deployments {
// Map the integer deployment ID into a human readable
// fork-name.
var forkName string
switch deployment {
case params.DeploymentTestDummy:
forkName = "dummy"
case params.DeploymentToken:
forkName = "token"
default:
return nil, fmt.Errorf("Unknown deployment %v detected\n", deployment)
}
// Query the chain for the current status of the deployment as
// identified by its deployment ID.
deploymentStatus, err := api.node.blockManager.GetChain().ThresholdState(uint32(deployment))
if err != nil {
return nil, fmt.Errorf("Failed to obtain deployment status\n")
}
// Finally, populate the soft-fork description with all the
// information gathered above.
ret.ConsensusDeployment[forkName] = &json.ConsensusDeploymentDesc{
Status: deploymentStatus.HumanString(),
Bit: deploymentDetails.BitNumber,
StartTime: int64(deploymentDetails.StartTime),
Timeout: int64(deploymentDetails.ExpireTime),
}
if deploymentDetails.PerformTime != 0 {
ret.ConsensusDeployment[forkName].Perform = int64(deploymentDetails.PerformTime)
}
if deploymentDetails.StartTime >= blockchain.CheckerTimeThreshold {
if time.Unix(int64(deploymentDetails.ExpireTime), 0).After(best.MedianTime) {
startTime := time.Unix(int64(deploymentDetails.StartTime), 0)
ret.ConsensusDeployment[forkName].Since = best.MedianTime.Sub(startTime).String()
}
}
}
return ret, nil
}
// getDifficultyRatio returns the proof-of-work difficulty as a multiple of the
// minimum difficulty using the passed bits field from the header of a block.
func getDifficultyRatio(target *big.Int, params *params.Params, powType pow.PowType) float64 {
instance := pow.GetInstance(powType, 0, []byte{})
instance.SetParams(params.PowConfig)
// The minimum difficulty is the max possible proof-of-work limit bits
// converted back to a number. Note this is not the same as the proof of
// work limit directly because the block difficulty is encoded in a block
// with the compact form which loses precision.
base := instance.GetSafeDiff(0)
var difficulty *big.Rat
if powType == pow.BLAKE2BD || powType == pow.MEERXKECCAKV1 ||
powType == pow.QITMEERKECCAK256 ||
powType == pow.X8R16 ||
powType == pow.X16RV3 ||
powType == pow.CRYPTONIGHT {
if target.Cmp(big.NewInt(0)) > 0 {
difficulty = new(big.Rat).SetFrac(base, target)
}
} else {
difficulty = new(big.Rat).SetFrac(target, base)
}
outString := difficulty.FloatString(8)
diff, err := strconv.ParseFloat(outString, 64)
if err != nil {
log.Error(fmt.Sprintf("Cannot get difficulty: %v", err))
return 0
}
return diff
}
// Return the peer info
func (api *PublicBlockChainAPI) GetPeerInfo(verbose *bool, network *string) (interface{}, error) {
vb := false
if verbose != nil {
vb = *verbose
}
networkName := ""
if network != nil {
networkName = *network
}
if len(networkName) <= 0 {
networkName = params.ActiveNetParams.Name
}
ps := api.node.node.peerServer
peers := ps.Peers().StatsSnapshots()
infos := make([]*json.GetPeerInfoResult, 0, len(peers))
for _, p := range peers {
if len(networkName) != 0 && networkName != "all" {
if p.Network != networkName {
continue
}
}
if !vb {
if !p.State.IsConnected() {
continue
}
}
info := &json.GetPeerInfoResult{
ID: p.PeerID,
Name: p.Name,
Address: p.Address,
BytesSent: p.BytesSent,
BytesRecv: p.BytesRecv,
Circuit: p.IsCircuit,
Bads: p.Bads,
}
info.Protocol = p.Protocol
info.Services = p.Services.String()
if p.Genesis != nil {
info.Genesis = p.Genesis.String()
}
if p.IsTheSameNetwork() {
info.State = p.State.String()
}
if len(p.Version) > 0 {
info.Version = p.Version
}
if len(p.Network) > 0 {
info.Network = p.Network
}
if p.State.IsConnected() {
info.TimeOffset = p.TimeOffset
if p.Genesis != nil {
info.Genesis = p.Genesis.String()
}
info.Direction = p.Direction.String()
if p.GraphState != nil {
info.GraphState = GetGraphStateResult(p.GraphState)
}
if ps.PeerSync().SyncPeer() != nil {
info.SyncNode = p.PeerID == ps.PeerSync().SyncPeer().GetID().String()
} else {
info.SyncNode = false
}
info.ConnTime = p.ConnTime.Truncate(time.Second).String()
info.GSUpdate = p.GraphStateDur.Truncate(time.Second).String()
}
if !p.LastSend.IsZero() {
info.LastSend = p.LastSend.String()
}
if !p.LastRecv.IsZero() {
info.LastRecv = p.LastRecv.String()
}
if len(p.QNR) > 0 {
info.QNR = p.QNR
}
infos = append(infos, info)
}
return infos, nil
}
// Return the RPC info
func (api *PublicBlockChainAPI) GetRpcInfo() (interface{}, error) {
rs := api.node.node.rpcServer.ReqStatus
jrs := []*cmds.JsonRequestStatus{}
for _, v := range rs {
jrs = append(jrs, v.ToJson())
}
return jrs, nil
}
func GetGraphStateResult(gs *blockdag.GraphState) *json.GetGraphStateResult {
if gs != nil {
mainTip := gs.GetMainChainTip()
tips := []string{mainTip.String() + " main"}
for k := range gs.GetTips().GetMap() {
if k.IsEqual(mainTip) {
continue
}
tips = append(tips, k.String())
}
return &json.GetGraphStateResult{
Tips: tips,
MainOrder: uint32(gs.GetMainOrder()),
Layer: uint32(gs.GetLayer()),
MainHeight: uint32(gs.GetMainHeight()),
}
}
return nil
}
func (api *PublicBlockChainAPI) GetTimeInfo() (interface{}, error) {
return fmt.Sprintf("Now:%s offset:%s", roughtime.Now(), roughtime.Offset()), nil
}
func (api *PublicBlockChainAPI) GetNetworkInfo() (interface{}, error) {
ps := api.node.node.peerServer
peers := ps.Peers().StatsSnapshots()
nstat := &json.NetworkStat{MaxConnected: ps.Config().MaxPeers,
MaxInbound: ps.Config().MaxInbound, Infos: []*json.NetworkInfo{}}
infos := map[string]*json.NetworkInfo{}
gsups := map[string][]time.Duration{}
for _, p := range peers {
nstat.TotalPeers++
if p.Services&protocol.Relay > 0 {
nstat.TotalRelays++
}
//
if len(p.Network) <= 0 {
continue
}
info, ok := infos[p.Network]
if !ok {
info = &json.NetworkInfo{Name: p.Network}
infos[p.Network] = info
nstat.Infos = append(nstat.Infos, info)
gsups[p.Network] = []time.Duration{0, 0, math.MaxInt64}
}
info.Peers++
if p.State.IsConnected() {
info.Connecteds++
nstat.TotalConnected++
gsups[p.Network][0] = gsups[p.Network][0] + p.GraphStateDur
if p.GraphStateDur > gsups[p.Network][1] {
gsups[p.Network][1] = p.GraphStateDur
}
if p.GraphStateDur < gsups[p.Network][2] {
gsups[p.Network][2] = p.GraphStateDur
}
}
if p.Services&protocol.Relay > 0 {
info.Relays++
}
}
for k, gu := range gsups {
info, ok := infos[k]
if !ok {
continue
}
if info.Connecteds > 0 {
avegs := time.Duration(0)
if info.Connecteds > 2 {
avegs = gu[0] - gu[1] - gu[2]
if avegs < 0 {
avegs = 0
}
cons := info.Connecteds - 2
avegs = time.Duration(int64(avegs) / int64(cons))
} else {
avegs = time.Duration(int64(gu[0]) / int64(info.Connecteds))
}
info.AverageGS = avegs.Truncate(time.Second).String()
info.MaxGS = gu[1].Truncate(time.Second).String()
info.MinGS = gu[2].Truncate(time.Second).String()
}
}
return nstat, nil
}
func (api *PublicBlockChainAPI) GetSubsidy() (interface{}, error) {
best := api.node.blockManager.GetChain().BestSnapshot()
sc := api.node.blockManager.GetChain().GetSubsidyCache()
info := &json.SubsidyInfo{Mode: sc.GetMode(), TotalSubsidy: best.TotalSubsidy, BaseSubsidy: params.ActiveNetParams.BaseSubsidy}
if params.ActiveNetParams.TargetTotalSubsidy > 0 {
info.TargetTotalSubsidy = params.ActiveNetParams.TargetTotalSubsidy
info.LeftTotalSubsidy = info.TargetTotalSubsidy - int64(info.TotalSubsidy)
if info.LeftTotalSubsidy < 0 {
info.TargetTotalSubsidy = 0
}
totalTime := time.Duration(info.TargetTotalSubsidy / info.BaseSubsidy * int64(params.ActiveNetParams.TargetTimePerBlock))
info.TotalTime = totalTime.Truncate(time.Second).String()
firstMBlock := api.node.blockManager.GetChain().BlockDAG().GetBlockByOrder(1)
startTime := time.Unix(firstMBlock.GetData().GetTimestamp(), 0)
leftTotalTime := totalTime - time.Since(startTime)
if leftTotalTime < 0 {
leftTotalTime = 0
}
info.LeftTotalTime = leftTotalTime.Truncate(time.Second).String()
}
info.NextSubsidy = sc.CalcBlockSubsidy(api.node.blockManager.GetChain().BlockDAG().GetBlueInfo(api.node.blockManager.GetChain().BlockDAG().GetMainChainTip()))
return info, nil
}
type PrivateBlockChainAPI struct {
node *QitmeerFull
}
func NewPrivateBlockChainAPI(node *QitmeerFull) *PrivateBlockChainAPI {
return &PrivateBlockChainAPI{node}
}
// Stop the node
func (api *PrivateBlockChainAPI) Stop() (interface{}, error) {
select {
case api.node.node.rpcServer.RequestedProcessShutdown() <- struct{}{}:
default:
}
return "Qitmeer stopping.", nil
}
// Banlist
func (api *PrivateBlockChainAPI) Banlist() (interface{}, error) {
bl := api.node.node.peerServer.GetBanlist()
bls := []*json.GetBanlistResult{}
for k, v := range bl {
bls = append(bls, &json.GetBanlistResult{ID: k, Bads: v})
}
return bls, nil
}
// RemoveBan
func (api *PrivateBlockChainAPI) RemoveBan(id *string) (interface{}, error) {
ho := ""
if id != nil {
ho = *id
}
api.node.node.peerServer.RemoveBan(ho)
return true, nil
}
// SetRpcMaxClients
func (api *PrivateBlockChainAPI) SetRpcMaxClients(max int) (interface{}, error) {
if max <= 0 {
err := fmt.Errorf("error:Must greater than 0 (cur max =%d)", api.node.node.Config.RPCMaxClients)
return api.node.node.Config.RPCMaxClients, err
}
api.node.node.Config.RPCMaxClients = max
return api.node.node.Config.RPCMaxClients, nil
}
type PrivateLogAPI struct {
node *QitmeerFull
}
func NewPrivateLogAPI(node *QitmeerFull) *PrivateLogAPI {
return &PrivateLogAPI{node}
}
// set log
func (api *PrivateLogAPI) SetLogLevel(level string) (interface{}, error) {
err := common.ParseAndSetDebugLevels(level)
if err != nil {
return nil, err
}
return level, nil
}
|
[
0,
1
] |
//+build linux
package fsnotify
// watcher tracks the following events:
// - dir create, delete, move
// - file write, delete, move
//
// configFile changes and directory moves always trigger a full reload.
// It's not incremental.
//
// Also, any incremental changes to page files (*.page.*) will recreate
// static site completely (if StaticSite=true). There is no "incremental"
// generation of static site data, because tags, feeds and dir indexes
// can refer to files beyond a single file change.
//
// For these MACRO updates (full reload, createStatic), the system will
// bundle the updates and do it once at the end of processing a bunch of reads.
//
// syscall.Read is typically a blocking call.
// Thus, we SHOULDN'T close it from a different thread, since the behaviour
// in linux is undefined.
//
// To accomodate, we use select with a 1 second timeout, and use non-blocking
// reads, so read never hangs. We then also close the file descriptor within the
// readEvents loop.
//
// The design affords the following:
// - User can use a sleep to allow events to be delivered as a batch.
// This can help prevent running the same macro operation multiple times
// because events came in one at a time.
// The sleep also allows inotify to coalese similar events together.
// - Access to underlying linux events, so finer handling of moves, etc.
import (
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"unsafe"
"github.com/ugorji/go-common/errorutil"
"github.com/ugorji/go-common/logging"
)
var log = logging.PkgLogger()
var ClosedErr = errorutil.String("<watcher closed>")
// Use select, so read doesn't block
const useSelect = true
// Use non-block, so we don't block on read.
const useNonBlock = true
type WatchEvent struct {
syscall.InotifyEvent
Path string
Name string
}
func (e *WatchEvent) String() string {
s := make([]string, 0, 4)
x := e.Mask
if x&syscall.IN_ISDIR != 0 {
s = append(s, "IN_ISDIR")
}
if x&syscall.IN_CREATE != 0 {
s = append(s, "IN_CREATE")
}
if x&syscall.IN_CLOSE_WRITE != 0 {
s = append(s, "IN_CLOSE_WRITE")
}
if x&syscall.IN_MOVED_TO != 0 {
s = append(s, "IN_MOVED_TO")
}
if x&syscall.IN_MOVED_FROM != 0 {
s = append(s, "IN_MOVED_FROM")
}
if x&syscall.IN_DELETE != 0 {
s = append(s, "IN_DELETE")
}
if x&syscall.IN_DELETE_SELF != 0 {
s = append(s, "IN_DELETE_SELF")
}
if x&syscall.IN_MOVE_SELF != 0 {
s = append(s, "IN_MOVE_SELF")
}
return fmt.Sprintf("WatchEvent: Path: %s, Name: %s, Wd: %v, Cookie: %v, Mask: %b, %v",
e.Path, e.Name, e.Wd, e.Cookie, e.Mask, s)
}
// Watcher implements a watch service.
// It allows user to handle events natively, but does
// management of event bus and delivery.
// User just provides a callback function.
type Watcher struct {
sl time.Duration
fd int
closed uint32
wds map[int32]string
flags map[string]uint32
mu sync.Mutex
fn func([]*WatchEvent)
ev chan []*WatchEvent
sysbufsize int
}
// NewWatcher returns a new Watcher instance.
// - bufsize: chan size (ie max number of batches available to be processed)
// - sysBufSize: syscall Inotify Buf size (ie max number of inotify events in each read)
// - sleepTime: sleep time between reads.
// Allows system coalese events, and allows us user handle events in batches.
// - fn: function to call for each batch of events read
func NewWatcher(bufsize, sysBufSize int, sleepTime time.Duration, fn func([]*WatchEvent),
) (w *Watcher, err error) {
fd, err := syscall.InotifyInit()
if err != nil {
return
}
if fd == -1 {
err = os.NewSyscallError("inotify_init", err)
return
}
if useNonBlock {
syscall.SetNonblock(fd, true)
}
w = &Watcher{
fd: fd,
fn: fn,
ev: make(chan []*WatchEvent, bufsize),
wds: make(map[int32]string),
flags: make(map[string]uint32),
sl: sleepTime,
sysbufsize: sysBufSize,
}
go w.readEvents()
go w.handleEvents()
return
}
func (w *Watcher) AddAll(ignoreErr, clear, recursive bool, flags uint32, fpaths ...string) error {
if atomic.LoadUint32(&w.closed) != 0 {
return ClosedErr
}
w.mu.Lock()
defer w.mu.Unlock()
var merr errorutil.Multi
fnErr := func(err error, message string, params ...interface{}) bool {
if ignoreErr {
log.IfError(nil, err, message, params...)
return false
} else {
errorutil.OnErrorf(&err, message, params...)
merr = append(merr, err)
return true
}
}
if clear && fnErr(w.clear(), "Error clearing Watcher") {
return merr.NonNilError()
}
for _, fpath := range fpaths {
var walkDoneErr = errorutil.String("DONE")
first := true
walkFn := func(f string, info os.FileInfo, inerr error) error {
if first || info.Mode().IsDir() {
if fnErr(w.add(f, flags), "Error adding path: %s", f) {
return walkDoneErr
}
}
if first && !recursive {
return walkDoneErr
}
first = false
return nil
}
if err := filepath.Walk(fpath, walkFn); err == walkDoneErr {
break
}
}
return merr.NonNilError()
}
func (w *Watcher) Add(fpath string, flags uint32) error {
if atomic.LoadUint32(&w.closed) != 0 {
return ClosedErr
}
w.mu.Lock()
defer w.mu.Unlock()
return w.add(fpath, flags)
}
func (w *Watcher) add(fpath string, flags uint32) error {
if flags == 0 {
flags =
// delete: false
syscall.IN_CREATE |
syscall.IN_CLOSE_WRITE |
syscall.IN_MOVED_TO |
// delete: true
syscall.IN_MOVED_FROM |
syscall.IN_DELETE |
syscall.IN_DELETE_SELF |
syscall.IN_MOVE_SELF
}
// user can add more flags by passing the syscall.IN_MASK_ADD
wd, err := syscall.InotifyAddWatch(w.fd, fpath, flags)
if err != nil {
errorutil.OnErrorf(&err, "Error adding watch for path: %s", fpath)
return err
}
w.wds[int32(wd)] = fpath
w.flags[fpath] = flags
return nil
}
func (w *Watcher) Remove(fpath string) (err error) {
if atomic.LoadUint32(&w.closed) != 0 {
return ClosedErr
}
w.mu.Lock()
defer w.mu.Unlock()
return w.remove(fpath)
}
func (w *Watcher) remove(fpath string) (err error) {
for k, v := range w.wds {
if v == fpath {
_, err = syscall.InotifyRmWatch(w.fd, uint32(k))
delete(w.wds, k)
delete(w.flags, v)
break
}
}
return
}
func (w *Watcher) Clear() error {
if atomic.LoadUint32(&w.closed) != 0 {
return ClosedErr
}
w.mu.Lock()
defer w.mu.Unlock()
return w.clear()
}
func (w *Watcher) clear() error {
var merr errorutil.Multi
for k, v := range w.wds {
if _, err := syscall.InotifyRmWatch(w.fd, uint32(k)); err != nil {
errorutil.OnErrorf(&err, "Error removing watch for path: %s", v)
merr = append(merr, err)
}
}
w.wds = make(map[int32]string)
w.flags = make(map[string]uint32)
return merr.NonNilError()
}
func (w *Watcher) Close() (err error) {
// Note that, with blocking read, Close is best effort. This is because read in linux
// does not error if the file descriptor is closed. Thus the "read" syscall may not unblock.
//
// To mitigate, we use select AND NonBlocking IO during the read.
if !atomic.CompareAndSwapUint32(&w.closed, 0, 1) {
return
}
w.mu.Lock()
defer w.mu.Unlock()
w.clear()
close(w.ev)
if !(useSelect || useNonBlock) {
log.IfError(nil, syscall.Close(w.fd), "Error closing Watcher")
}
return nil
}
func (w *Watcher) readEvents() {
if useSelect || useNonBlock {
defer func() {
log.IfError(nil, syscall.Close(w.fd), "Error closing Watcher")
}()
}
// inotify events come very quickly, so we can't handle them inline.
// Instead, we grab the list of events we read and put on a queue.
// This way, we can still work on a bunch of events at same time.
var buf = make([]byte, syscall.SizeofInotifyEvent*w.sysbufsize)
for {
// always check closed right before syscalls (read/select/sleep), to minimize chance
// of race condition where fd is closed, OS assigns to someone else, and we try to read.
// slight sleep gives a chance to coalese similar events into one
if w.sl != 0 {
if atomic.LoadUint32(&w.closed) != 0 {
return
}
time.Sleep(w.sl)
}
if useSelect {
if atomic.LoadUint32(&w.closed) != 0 {
return
}
// println(">>>>> select: Checking to read")
fdset := new(syscall.FdSet)
fdset.Bits[w.fd/64] |= 1 << (uint(w.fd) % 64) // FD_SET
// fdIsSet := (fdset.Bits[w.fd/64] & (1 << (uint(w.fd) % 64))) != 0 // FD_ISSET
// for i := range fdset.Bits { fdset.Bits[i] = 0 } // FD_ZERO
selTimeout := syscall.NsecToTimeval(int64(1 * time.Second))
num, err := syscall.Select(w.fd+1, fdset, nil, nil, &selTimeout)
// if err != nil || num == 0 {
if (fdset.Bits[w.fd/64] & (1 << (uint(w.fd) % 64))) == 0 { // FD_ISSET
log.IfError(nil, err, "Error during Watcher select, which returned: %d", num)
continue
}
// println(">>>>> select: will read")
}
if atomic.LoadUint32(&w.closed) != 0 {
return
}
n, err := syscall.Read(w.fd, buf[0:])
if useNonBlock && err == syscall.EAGAIN {
// println(">>>>> non-block: EAGAIN")
continue
}
// even if there is an error, see if any events already read and process them.
log.IfError(nil, err, "Error during Watcher read, which returned %d bytes", n)
if n == 0 {
break // EOF
}
if n < syscall.SizeofInotifyEvent {
continue // short read
}
var offset uint32
wevs := make([]*WatchEvent, 0, n/(syscall.SizeofInotifyEvent*2))
for offset <= uint32(n-syscall.SizeofInotifyEvent) {
// raw.Wd, raw.Mask, raw.Cookie, raw.Len (all uint32)
raw := (*syscall.InotifyEvent)(unsafe.Pointer(&buf[offset]))
fpath := w.wds[raw.Wd]
// skip some events
if raw.Mask&syscall.IN_IGNORED != 0 ||
raw.Mask&syscall.IN_Q_OVERFLOW != 0 ||
raw.Mask&syscall.IN_UNMOUNT != 0 ||
fpath == "" {
offset += syscall.SizeofInotifyEvent + raw.Len
continue
}
wev := &WatchEvent{InotifyEvent: *raw, Path: fpath}
if raw.Len != 0 {
bs := (*[syscall.PathMax]byte)(unsafe.Pointer(&buf[offset+syscall.SizeofInotifyEvent]))
wev.Name = strings.TrimRight(string(bs[0:raw.Len]), "\000")
}
wevs = append(wevs, wev)
offset += syscall.SizeofInotifyEvent + raw.Len
}
select {
case w.ev <- wevs:
case <-time.After(10 * time.Millisecond):
// drop if after 30 milliseconds and no one to accept
}
}
}
func (w *Watcher) handleEvents() {
for x := range w.ev {
w.fn(x)
}
}
|
[
1
] |
package main
import (
"context"
"flag"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"os"
"strings"
"time"
"github.com/minio/minio-go"
"github.com/minio/minio-go/pkg/credentials"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
)
var (
logLevel = flag.String("l", "info", "Log level")
endpoint = flag.String("e", "default-s3-endpoint:9000", "S3 endpoint host:port")
accessKeyID = flag.String("a", "TEMP_DEMO_ACCESS_KEY", "S3 access key ID")
secretAccessKey = flag.String("k", "TEMP_DEMO_SECRET_KEY", "S3 secret key")
useSSL = flag.Bool("s", false, "Use SSL (default disabled)")
writeBucketName = "s3-loadgen-writes"
readBucketName = "s3-loadgen-reads"
location = "us-east-1"
writeOpCounter = prometheus.NewCounter(prometheus.CounterOpts{
Name: "s3_write_counter",
Help: "s3 writes operations counter.",
})
writeErrCounter = prometheus.NewCounter(prometheus.CounterOpts{
Name: "s3_write_err_counter",
Help: "s3 writes errors counter.",
})
readOpCounter = prometheus.NewCounter(prometheus.CounterOpts{
Name: "s3_read_counter",
Help: "s3 reads operations counter.",
})
readMissCounter = prometheus.NewCounter(prometheus.CounterOpts{
Name: "s3_read_miss_counter",
Help: "s3 reads miss counter.",
})
readHitCounter = prometheus.NewCounter(prometheus.CounterOpts{
Name: "s3_read_hit_counter",
Help: "s3 reads hit counter.",
})
readErrCounter = prometheus.NewCounter(prometheus.CounterOpts{
Name: "s3_read_err_counter",
Help: "s3 read errors counter.",
})
writeDurationsHistogram = prometheus.NewHistogram(prometheus.HistogramOpts{
Name: "s3_write_durations_histogram_seconds",
Help: "S3 write operations latency distributions.",
Buckets: []float64{0.02, 0.03, 0.035, 0.04, 0.045, 0.05, 0.055, 0.06, 0.065, 0.07, 0.08, 0.09, 0.1, 0.11, 0.125, 0.15, 0.16, 0.18, 0.2, 0.3, 0.4, 0.5},
})
readDurationsHistogram = prometheus.NewHistogram(prometheus.HistogramOpts{
Name: "s3_read_durations_histogram_seconds",
Help: "S3 read operations latency distributions.",
Buckets: []float64{0.006, 0.01, 0.012, 0.013, 0.014, 0.015, 0.016, 0.018, 0.02, 0.024, 0.028, 0.035, 0.05, 0.075, 0.1, 0.125, 0.15, 0.2, 0.3, 0.4, 0.5},
})
)
const letterBytes = "\nabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\n"
func usage() {
fmt.Fprintf(os.Stderr, "Usage:\n")
fmt.Fprintf(os.Stderr, " ./s3-loadgen -e <HOST:PORT> -a <S3_ID> -k <S3_secret> [-s] [-l <loglevel>]\n")
os.Exit(2)
}
func initPrometheus() {
prometheus.MustRegister(writeOpCounter)
prometheus.MustRegister(writeErrCounter)
prometheus.MustRegister(writeDurationsHistogram)
prometheus.MustRegister(readOpCounter)
prometheus.MustRegister(readHitCounter)
prometheus.MustRegister(readMissCounter)
prometheus.MustRegister(readErrCounter)
prometheus.MustRegister(readDurationsHistogram)
}
func initLogger() {
log.SetFormatter(&log.TextFormatter{
DisableColors: false,
FullTimestamp: true,
})
log.SetOutput(os.Stdout)
log.SetLevel(log.InfoLevel)
level, err := log.ParseLevel(*logLevel)
if err != nil {
log.Warn("Impossible to parse log level (-l), fallback to info")
} else {
log.SetLevel(level)
}
}
func prepareBuckets(minioClient *minio.Client) {
// Verify & creates new buckets for reads and writes operations.
// Create write bucket
err := minioClient.MakeBucket(writeBucketName, location)
if err != nil {
// Check to see if we already own this bucket (which happens if you run this twice)
exists, err := minioClient.BucketExists(writeBucketName)
if err == nil && exists {
log.Printf("We already own %s bucket\n", writeBucketName)
} else {
log.Fatalln(err)
}
} else {
log.Printf("Successfully created %s bucket\n", writeBucketName)
}
// Create read bucket
err = minioClient.MakeBucket(readBucketName, location)
if err != nil {
// Check to see if we already own this bucket (which happens if you run this twice)
exists, err := minioClient.BucketExists(readBucketName)
if err == nil && exists {
log.Printf("We already own %s bucket\n", readBucketName)
} else {
log.Fatalln(err)
}
} else {
log.Printf("Successfully created %s bucket\n", readBucketName)
lifecycle1d := `<LifecycleConfiguration>
<Rule>
<ID>expire-bucket</ID>
<Prefix></Prefix>
<Status>Enabled</Status>
<Expiration>
<Days>1</Days>
</Expiration>
</Rule>
</LifecycleConfiguration>`
minioClient.SetBucketLifecycle(readBucketName, lifecycle1d)
}
}
func fillReadBucket(minioClient *minio.Client) {
for i := 1; i <= 10000; i++ {
writeObjectWithID(i, minioClient)
}
}
func randomAlphaString(len int) string {
b := make([]byte, len)
for i := range b {
b[i] = letterBytes[rand.Intn(54)]
}
return string(b)
}
func writeObjectWithID(id int, minioClient *minio.Client) {
objectNameWithID := fmt.Sprintf("s3-loadgen-%d", id)
n, err := minioClient.PutObject(readBucketName, objectNameWithID, strings.NewReader(randomAlphaString(250000)), 250000, minio.PutObjectOptions{ContentType: "text/plain"})
if err != nil {
log.Error("Cannot put S3 Object: ", err)
return
}
log.Debugf("Object stored in read bucket: %s (%dB)", objectNameWithID, n)
}
func readRndObject(minioClient *minio.Client) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
readOpCounter.Inc()
objectNameWithID := fmt.Sprintf("s3-loadgen-%d", rand.Intn(10000)+1)
start := time.Now()
obj, err := minioClient.GetObjectWithContext(ctx, readBucketName, objectNameWithID, minio.GetObjectOptions{})
if err != nil {
log.Errorf("Cannot touch S3 object %s : %s", objectNameWithID, err)
readErrCounter.Inc()
return
}
defer obj.Close()
stat, err := obj.Stat()
if err != nil {
if err.Error() == "The specified key does not exist." {
log.Warnf("Object %s is missing in read bucket !", objectNameWithID)
readMissCounter.Inc()
return
}
log.Errorf("Cannot stats S3 object %s : %s", objectNameWithID, err)
readErrCounter.Inc()
return
}
n, err := io.CopyN(ioutil.Discard, obj, stat.Size)
readDuration := time.Since(start)
if err != nil {
log.Errorf("Cannot read S3 object %s : %s", objectNameWithID, err)
readErrCounter.Inc()
return
}
readDurationsHistogram.Observe(readDuration.Seconds())
readHitCounter.Inc()
log.Debugf("Object fetched: %s (%dB) in %f seconds", objectNameWithID, n, readDuration.Seconds())
}
func writeRndObject(minioClient *minio.Client) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
writeOpCounter.Inc()
objectRandomName := fmt.Sprintf("s3-loadgen-%d", rand.Intn(9999999999)+1)
start := time.Now()
n, err := minioClient.PutObjectWithContext(ctx, writeBucketName, objectRandomName, strings.NewReader(randomAlphaString(250000)), 250000, minio.PutObjectOptions{ContentType: "text/plain"})
writeDuration := time.Since(start)
if err != nil {
log.Error("Cannot put S3 Object: ", err)
writeErrCounter.Inc()
return
}
writeDurationsHistogram.Observe(writeDuration.Seconds())
log.Debugf("Object stored: %s (%dB) in %f seconds", objectRandomName, n, writeDuration.Seconds())
}
func main() {
flag.Usage = usage
flag.Parse()
rand.Seed(time.Now().UnixNano())
initLogger()
initPrometheus()
// Initialize Prometheus metrics endpoint
log.Info("Serving Prometheus metrics endpoint at :9090")
http.Handle("/metrics", promhttp.Handler())
go http.ListenAndServe(":9090", nil)
// Initialize minio client object
log.Infof("Connecting to %s", *endpoint)
// minioClient, err := minio.NewV2(*endpoint, *accessKeyID, *secretAccessKey, *useSSL)
opts := minio.Options{
Creds: credentials.NewStaticV4(*accessKeyID, *secretAccessKey, ""),
Secure: *useSSL,
Region: location,
BucketLookup: minio.BucketLookupPath,
}
minioClient, err := minio.NewWithOptions(*endpoint, &opts)
if err != nil {
log.Fatalln(err)
}
log.Info("Minio S3 client successfully bootstrapped")
log.Debugf("%#v\n", minioClient) // Debug minioClient instance
prepareBuckets(minioClient)
fillReadBucket(minioClient)
tickerWrites := time.NewTicker(150 * time.Millisecond)
tickerReads := time.NewTicker(75 * time.Millisecond)
for {
select {
case <-tickerWrites.C:
go writeRndObject(minioClient)
case <-tickerReads.C:
go readRndObject(minioClient)
}
}
}
|
[
1
] |
package Network
import (
. "../Def"
"encoding/json"
"fmt"
"net"
"reflect"
"sort"
"strings"
"time"
)
const interval = 20 * time.Millisecond
const timeout = 100 * time.Millisecond
func TransmitterPeers(port int, id string, transmitEnableCh <-chan bool, newPeerTransmitMessageCh <-chan DriverState) {
currentDriverState := DriverState{id, 1, -1}
peerTransmitMessageCh := make(chan DriverState, 1)
conn := DialBroadcastUDP(port)
addr, _ := net.ResolveUDPAddr("udp4", fmt.Sprintf("255.255.255.255:%d", port))
selectCases := make([]reflect.SelectCase, 1)
typeNames := make([]string, 1)
selectCases[0] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(peerTransmitMessageCh)}
typeNames[0] = reflect.TypeOf(peerTransmitMessageCh).Elem().String()
enable := true
for {
select {
case enable = <-transmitEnableCh:
case currentDriverState = <-newPeerTransmitMessageCh:
case <-time.After(interval):
}
peerTransmitMessageCh <- currentDriverState
if enable {
chosen, value, _ := reflect.Select(selectCases)
buf, _ := json.Marshal(value.Interface())
conn.WriteTo([]byte(typeNames[chosen]+string(buf)), addr)
}
}
}
func ReceiverPeers(ElevId string, port int, peerUpdateCh chan<- PeerUpdate, updatePeersOnQueueCh chan<- DriverState) {
var buf [1024]byte
var p PeerUpdate
lastSeen := make(map[string]time.Time)
conn := DialBroadcastUDP(port)
newMessageCh := make(chan DriverState, 1)
for {
message := DriverState{"NONEW", 0, 0}
updated := false
conn.SetReadDeadline(time.Now().Add(interval))
n, _, _ := conn.ReadFrom(buf[0:])
T := reflect.TypeOf(newMessageCh).Elem()
typename := T.String()
if strings.HasPrefix(string(buf[:n])+"{", typename) {
v := reflect.New(T)
json.Unmarshal(buf[len(typename):n], v.Interface())
reflect.Select([]reflect.SelectCase{{
Dir: reflect.SelectSend,
Chan: reflect.ValueOf(newMessageCh),
Send: reflect.Indirect(v),
}})
message = <-newMessageCh
updatePeersOnQueueCh <- message
}
if (message.Id != "NONEW") && (message.Id != ElevId) {
// Adding new connection
p.New = ""
if message.Id != "" {
if _, idExists := lastSeen[message.Id]; !idExists {
p.New = message.Id
updated = true
}
lastSeen[message.Id] = time.Now()
}
// Removing dead connection
p.Lost = make([]string, 0)
for k, v := range lastSeen {
if time.Now().Sub(v) > timeout {
updated = true
p.Lost = append(p.Lost, k)
delete(lastSeen, k)
}
}
// Sending update
if updated {
p.Peers = make([]string, 0, len(lastSeen))
for k, _ := range lastSeen {
p.Peers = append(p.Peers, k)
}
sort.Strings(p.Peers)
sort.Strings(p.Lost)
peerUpdateCh <- p
}
}
}
}
|
[
2
] |
package ipv6
import (
"encoding/csv"
"fmt"
"io"
"regexp"
"strconv"
"strings"
"github.com/pkg/errors"
"github.com/tidwall/buntdb"
)
const collection = "address"
const expectedCSVColumns = 10
const coordinatePrecision = "%f"
var data map[string]int32 // lat,long:count
var buntdbValueRegex = regexp.MustCompile(`\[([\d-\.]+) ([\d-\.]+)\]`) // parses `lat` `long` info from `[lat long]`
// List fetches a list of IPv6 models according to the specified (optional) `Filters`.
func List(db *buntdb.DB, f Filters) (ListResult, error) {
result := ListResult{}
var maxCount int32
err := db.View(func(tx *buntdb.Tx) error {
// Fetch results from our buntdb index using the supplied filters.
query := fmt.Sprintf("[%f %f],[%f %f]", f.MinLongitude, f.MinLatitude, f.MaxLongitude, f.MaxLatitude)
err := tx.Intersects(collection, query, func(key, value string) bool {
matches := buntdbValueRegex.FindStringSubmatch(value)
longitude, _ := strconv.ParseFloat(matches[1], 64)
latitude, _ := strconv.ParseFloat(matches[2], 64)
count := data[fmt.Sprintf("%f,%f", latitude, longitude)]
// Keep track of the max count for this result set.
if count > maxCount {
maxCount = count
}
result.Results = append(result.Results, &Address{
Latitude: latitude,
Longitude: longitude,
Count: count,
})
return true
})
return err
})
if err != nil {
return result, errors.Wrap(err, "failed running intersection query")
}
result.MaxCount = maxCount
return result, err
}
// LoadData parses the data from the supplied source and populates our "persistence" layer.
func LoadData(db *buntdb.DB, source io.Reader) error {
// Reset our "database".
data = map[string]int32{}
// Ensure we have a spatial index on our geo coords.
db.CreateSpatialIndex(collection, fmt.Sprintf("%s:*:coords", collection), buntdb.IndexRect)
// Setup a CSV reader on our data source.
reader := csv.NewReader(source)
if reader == nil {
return errors.New("nil reader returned")
}
// Throwaway the first header line.
_, err := reader.Read()
if err != nil {
return errors.Wrap(err, "failed reading from CSV reader")
}
// Populate our `data` with a map of `latitude,longitude : count`
for {
// Read the record.
record, err := reader.Read()
if err == io.EOF {
break
}
if err != nil {
return errors.Wrap(err, "failed reading from CSV reader")
}
if len(record) != expectedCSVColumns {
return errors.Wrapf(fmt.Errorf("failed while reading record"), "expected %d columns in record, found %d", expectedCSVColumns, len(record))
}
// Grab the lat/long from the record.
latitude, err := strconv.ParseFloat(record[7], 64)
if err != nil {
return errors.Wrap(err, "failed while parsing latitude float")
}
longitude, err := strconv.ParseFloat(record[8], 64)
if err != nil {
return errors.Wrap(err, "failed while parsing longitude float")
}
// Increment the count for this lat/long combo.
key := fmt.Sprintf(coordinatePrecision+","+coordinatePrecision, latitude, longitude)
data[key] = data[key] + 1
}
// Now that we have our `data` populated, index the coordinates in buntdb for fast lookups.
err = db.Update(func(tx *buntdb.Tx) error {
i := 0
for coords := range data {
key := fmt.Sprintf("%s:%d:coords", collection, i)
latitude := strings.Split(coords, ",")[0]
longitude := strings.Split(coords, ",")[1]
value := fmt.Sprintf("[%s %s]", longitude, latitude)
_, _, err := tx.Set(key, value, nil)
if err != nil {
return errors.Wrapf(err, "failed while indexing %s : %s", key, value)
}
i++
}
return nil
})
return nil
}
|
[
0
] |
package csn
import (
"dna"
)
// SongUrl defines a struct for format field of csnsongs
type SongUrl struct {
Link dna.String `json:"link"`
Type dna.String `json:"type"`
Size dna.Int `json:"file_size"`
Bitrate dna.String `json:"bitrate"`
}
// VideoUrl defines a struct for format field of csnsongs
type VideoUrl struct {
Link dna.String `json:"link"`
Type dna.String `json:"type"`
Size dna.Int `json:"file_size"`
Resolution dna.String `json:"resolution"`
}
func NewSongUrl() *SongUrl {
su := new(SongUrl)
su.Link = ""
su.Type = ""
su.Size = 0
su.Bitrate = ""
return su
}
func NewVideoUrl() *VideoUrl {
su := new(VideoUrl)
su.Link = ""
su.Type = ""
su.Size = 0
su.Resolution = ""
return su
}
func getType(str dna.String) dna.String {
switch {
case str.Match(`(?mis)MP3`) == true:
return "mp3"
case str.Match(`(?mis)M4A`) == true:
return "m4a"
case str.Match(`(?mis)MP4`) == true:
return "mp4"
case str.Match(`(?mis)FLAC`) == true:
return "flac"
case str.Match(`(?mis)FLV`) == true:
return "flv"
default:
dna.Log("No type found at: " + str.String())
return ""
}
}
func getSongUrl(str, bitrate dna.String) *SongUrl {
su := NewSongUrl()
su.Bitrate = bitrate
su.Type = getType(str)
su.Link = str.GetTagAttributes("href").ReplaceWithRegexp(`(http.+/).+(\..+$)`, "${1}file-name${2}")
size := str.FindAllString(`[0-9\.]+ MB`, -1)
if size.Length() > 0 {
su.Size = size[0].ParseBytesFormat() / 1000
}
return su
}
func getVideoUrl(str, resolution dna.String) *VideoUrl {
su := NewVideoUrl()
su.Resolution = resolution
su.Type = getType(str)
su.Link = str.GetTagAttributes("href").ReplaceWithRegexp(`(http.+/).+(\..+$)`, "${1}file-name${2}")
size := str.FindAllString(`[0-9\.]+ MB`, -1)
if size.Length() > 0 {
su.Size = size[0].ParseBytesFormat() / 1000
}
return su
}
func getStringifiedSongUrls(urls dna.StringArray) dna.String {
var baseLink = dna.String("")
songUrls := []SongUrl{}
urls.ForEach(func(val dna.String, idx dna.Int) {
// dna.Log(val)
// Finding bitrate
switch {
case val.Match(`128kbps`) == true:
songUrl := getSongUrl(val, "128kbps")
baseLink = songUrl.Link.ReplaceWithRegexp(`[0-9]+/file-name.+`, "")
songUrls = append(songUrls, *songUrl)
case val.Match(`320kbps`) == true:
songUrl := getSongUrl(val, "320kbps")
baseLink = songUrl.Link.ReplaceWithRegexp(`[0-9]+/file-name.+`, "")
songUrls = append(songUrls, *songUrl)
case val.Match(`32kbps`) == true:
songUrl := getSongUrl(val, "32kbps")
baseLink = songUrl.Link.ReplaceWithRegexp(`[0-9]+/file-name.+`, "")
songUrls = append(songUrls, *songUrl)
case val.Match(`500kbps`) == true:
songUrl := getSongUrl(val, "500kbps")
songUrl.Link = baseLink + "m4a/file-name.m4a"
songUrls = append(songUrls, *songUrl)
case val.Match(`Lossless`) == true:
songUrl := getSongUrl(val, "Lossless")
songUrl.Link = baseLink + "flac/file-name.flac"
songUrls = append(songUrls, *songUrl)
}
})
// http://data.chiasenhac.com/downloads/1184/2/1183017-cfc5f7df/flac/file-name.flac
// replace the link 500kps and lossless with available link, apply for registered user only
// and reduce the link length
var ret = dna.StringArray{}
for _, songUrl := range songUrls {
var br dna.String
if songUrl.Bitrate == "Lossless" {
br = "1411"
} else {
br = songUrl.Bitrate.Replace("kbps", "")
}
t := `"(` + songUrl.Link + "," + songUrl.Type + "," + songUrl.Size.ToString() + "," + br + `)"`
ret.Push(t)
}
// dna.Log(`{` + ret.Join(",") + `}`)
return `{` + ret.Join(",") + `}`
}
func getStringifiedVideoUrls(urls dna.StringArray) dna.String {
var baseLink = dna.String("")
videoUrls := []VideoUrl{}
urls.ForEach(func(val dna.String, idx dna.Int) {
// dna.Log(val)
// Finding bitrate
switch {
case val.Match(`MV 360p`) == true:
songUrl := getVideoUrl(val, "360p")
baseLink = songUrl.Link.ReplaceWithRegexp(`[0-9]+/file-name.+`, "")
videoUrls = append(videoUrls, *songUrl)
case val.Match(`MV 480p`) == true:
songUrl := getVideoUrl(val, "480p")
baseLink = songUrl.Link.ReplaceWithRegexp(`[0-9]+/file-name.+`, "")
videoUrls = append(videoUrls, *songUrl)
case val.Match(`MV 180p`) == true:
songUrl := getVideoUrl(val, "180p")
baseLink = songUrl.Link.ReplaceWithRegexp(`[0-9]+/file-name.+`, "")
videoUrls = append(videoUrls, *songUrl)
case val.Match(`HD 720p`) == true:
songUrl := getVideoUrl(val, "720p")
songUrl.Link = baseLink + "m4a/file-name.mp4"
videoUrls = append(videoUrls, *songUrl)
case val.Match(`HD 1080p`) == true:
songUrl := getVideoUrl(val, "1080p")
songUrl.Link = baseLink + "flac/file-name.mp4"
videoUrls = append(videoUrls, *songUrl)
}
})
var ret = dna.StringArray{}
for _, videoUrl := range videoUrls {
t := `"(` + videoUrl.Link + "," + videoUrl.Type + "," + videoUrl.Size.ToString() + "," + videoUrl.Resolution.Replace("p", "") + `)"`
ret.Push(t)
}
// dna.Log(`{` + ret.Join(",") + `}`)
return `{` + ret.Join(",") + `}`
}
// GetFormats returns proper formatStr for a song or a video.
// If it is a song, IsSong will be set to true. Otherwise, it will set to false false.
func GetFormats(urls dna.StringArray) (formatStr dna.String, IsSong dna.Bool) {
switch getType(urls.Join("")) {
case "mp3", "m4a", "flac":
formatStr, IsSong = getStringifiedSongUrls(urls), IS_SONG
return formatStr, IsSong
case "mp4", "flv":
formatStr, IsSong = getStringifiedVideoUrls(urls), IS_VIDEO
return formatStr, IsSong
default:
panic("Wrong type. Cannot indentify song or video")
}
return "", false
}
|
[
2
] |
package inmem
import (
"sync"
"github.com/aperezg/feature-flags/project"
)
type projectRepository struct {
mtx sync.RWMutex
projects map[string]*project.Project
}
// NewProjectRepository returns a new instance of a in-memory project repository.
func NewProjectRepository() project.Repository {
return &projectRepository{
projects: make(map[string]*project.Project),
}
}
func (r *projectRepository) FindAll() ([]*project.Project, error) {
r.mtx.Lock()
defer r.mtx.Unlock()
p := make([]*project.Project, 0, len(r.projects))
for _, val := range r.projects {
p = append(p, val)
}
return p, nil
}
func (r *projectRepository) FindByName(name string) (project.Project, error) {
r.mtx.Lock()
defer r.mtx.Unlock()
for _, val := range r.projects {
if val.Name == name {
return *val, nil
}
}
return project.Project{}, nil
}
func (r *projectRepository) FindByID(ID string) (project.Project, error) {
r.mtx.Lock()
defer r.mtx.Unlock()
return *r.projects[ID], nil
}
func (r *projectRepository) Persist(project *project.Project) error {
r.mtx.Lock()
defer r.mtx.Unlock()
r.projects[project.ID] = project
return nil
}
func (r *projectRepository) Remove(ID string) error {
r.mtx.Lock()
defer r.mtx.Unlock()
delete(r.projects, ID)
return nil
}
|
[
2
] |
package Day25
import (
"time"
"github.com/bznein/AoC2020/pkg/input"
"github.com/bznein/AoC2020/pkg/timing"
)
func Solve(inputF string) (int, int) {
defer timing.TimeTrack(time.Now())
n := input.InputToIntSlice(inputF)
loopSize := 0
v := 1
n1Transformed := 1
n0Transformed := 1
for {
if v == n[0] {
return n1Transformed, -1
}
if v == n[1] {
return n0Transformed, -1
}
v *= 7
v = v % 20201227
n1Transformed *= n[1]
n1Transformed = n1Transformed % 20201227
n0Transformed *= n[0]
n0Transformed = n0Transformed % 20201227
loopSize++
}
}
|
[
0
] |
package main
import (
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
)
func main() {
inputFilename := os.Args[1]
start, end := readInputFile(inputFilename)
candidates := CountCandidates(start, end)
fmt.Printf("Part one - candidates: %d\n", candidates)
restrictedCandidates := CountRestrictedCandidates(start, end)
fmt.Printf("Part two - restricted candidates: %d\n", restrictedCandidates)
}
func readInputFile(inputFileName string) (int, int) {
bytes, err := ioutil.ReadFile(inputFileName)
if err != nil {
panic("Can't open the input file")
}
numbers := strings.Split(string(bytes), "-")
if len(numbers) != 2 {
panic(fmt.Sprintf("Input has %d numbers", len(numbers)))
}
start, err := strconv.Atoi(numbers[0])
if err != nil {
panic(fmt.Sprintf("Can't convert %s to int", numbers[0]))
}
end, err := strconv.Atoi(numbers[1])
if err != nil {
panic(fmt.Sprintf("Can't convert %s to int", numbers[1]))
}
return start, end
}
// CountCandidates ...
func CountCandidates(start, end int) int {
count := 0
for n := start; n <= end; n++ {
if HasRepeatingDigit(n) && HasIncreasingDigits(n) {
count++
}
}
return count
}
// CountRestrictedCandidates ...
func CountRestrictedCandidates(start, end int) int {
count := 0
for n := start; n <= end; n++ {
if HasDouble(n) && HasIncreasingDigits(n) {
count++
}
}
return count
}
// HasRepeatingDigit ...
func HasRepeatingDigit(number int) bool {
prev := number % 10
number = number / 10
for number > 0 {
curr := number % 10
if curr == prev {
return true
}
prev = curr
number = number / 10
}
return false
}
// HasDouble ...
func HasDouble(number int) bool {
doubleCandidate := -1
consecutive := 1
prev, number := number%10, number/10
for number > 0 {
curr := number % 10
if curr != prev {
if doubleCandidate != -1 && consecutive == 2 {
return true
}
doubleCandidate = -1
consecutive = 1
} else {
doubleCandidate = curr
consecutive++
}
prev, number = curr, number/10
}
return doubleCandidate != -1 && consecutive == 2
}
// HasIncreasingDigits ...
func HasIncreasingDigits(number int) bool {
// We're going backwards in digits, so need to check they
// are decreasing
prev := number % 10
number = number / 10
for number > 0 {
curr := number % 10
if curr > prev {
return false
}
prev = curr
number = number / 10
}
return true
}
|
[
0
] |
package main
import (
"crypto/tls"
"errors"
"fmt"
"net"
"net/http"
"strconv"
"time"
)
// DialConfigs dial multiple connections at same time
func DialConfigs(confs []Config, print func(a ...interface{})) error {
ch := make(chan error)
for _, config := range confs {
go func(conf Config) {
conn, err := BuildConn(&conf)
if err != nil {
ch <- fmt.Errorf("Invalid connection %#v: %v", conf, err)
return
}
ch <- DialConn(conn, &conf, print)
}(config)
}
for i := 0; i < len(confs); i++ {
if err := <-ch; err != nil {
return err
}
}
return nil
}
// DialConn check if the connection is available
func DialConn(conn *Connection, conf *Config, print func(a ...interface{})) error {
print("Waiting " + strconv.Itoa(conf.Timeout) + " seconds")
if err := pingHost(conn, conf, print); err != nil {
return err
}
if conn.URL.Scheme == "http" || conn.URL.Scheme == "https" {
return pingAddress(conn, conf, print)
}
return nil
}
// pingAddress check if the full address is responding properly
func pingAddress(conn *Connection, conf *Config, print func(a ...interface{})) error {
timeout := time.Duration(conf.Timeout) * time.Second
start := time.Now()
address := conn.URL.String()
print("Ping http address: " + address)
if conf.Status > 0 {
print("Expect HTTP status" + strconv.Itoa(conf.Status))
}
client := &http.Client{}
if conf.Insecure {
client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
req, err := http.NewRequest("GET", address, nil)
if err != nil {
return fmt.Errorf("Error creating request: %v", err)
}
for k, v := range conf.Headers {
print("Adding header " + k + ": " + v)
req.Header.Add(k, v)
}
for {
resp, err := client.Do(req)
if resp != nil {
print("Ping http address " + address + " " + resp.Status)
}
if err == nil {
if conf.Status > 0 && conf.Status == resp.StatusCode {
return nil
} else if conf.Status == 0 && resp.StatusCode < http.StatusInternalServerError {
return nil
}
}
if time.Since(start) > timeout {
return errors.New(resp.Status)
}
time.Sleep(time.Duration(conf.Retry) * time.Millisecond)
}
}
// pingHost check if the host (hostname:port) is responding properly
func pingHost(conn *Connection, conf *Config, print func(a ...interface{})) error {
timeout := time.Duration(conf.Timeout) * time.Second
start := time.Now()
address := conn.URL.Host
print("Ping host: " + address)
for {
_, err := net.DialTimeout(conn.NetworkType, address, time.Second)
print("Ping host: " + address)
if err == nil {
print("Up: " + address)
return nil
}
print("Down: " + address)
print(err)
if time.Since(start) > timeout {
return err
}
time.Sleep(time.Duration(conf.Retry) * time.Millisecond)
}
}
|
[
1
] |
package main
import (
"fmt"
"github.com/google/uuid"
"sync"
"time"
)
type Connection struct {
ID string
ConnectAt time.Time
IsClosed bool
}
type ConPool struct {
mu sync.Mutex
Cap int
Pool chan *Connection
}
func NewConPool(cap int) (conPool *ConPool) {
conPool = &ConPool{
Cap: cap,
Pool: make(chan *Connection, cap),
}
for i:=0; i < conPool.Cap; i++ {
conPool.Pool <- &Connection{ID: getConnectionId(), ConnectAt: time.Now(), IsClosed: false}
}
return
}
func (p *ConPool) Get() (con *Connection) {
for {
select {
case con = <- p.Pool:
return
}
}
}
func (p *ConPool) Put() {
p.mu.Lock()
defer p.mu.Unlock()
select {
case p.Pool <- &Connection{ID: getConnectionId(), ConnectAt: time.Now(), IsClosed: false}:
fmt.Println("添加一个连接")
default:
fmt.Println("连接池已满")
}
}
func getConnectionId() string {
id, _ := uuid.NewUUID()
return id.String()
}
|
[
1
] |
package main
import (
"fmt"
"sort"
)
func main() {
/*
https://www.safaribooksonline.com/library/view/the-go-programming/9780134190570/ebook_split_037.html
In Go, a map is a reference to a hash table, and a map type is written
map[K]V, where K and V are the types of its keys and values. All of the keys
in a given map are of the same type, and all of the values are of the same
type, but the keys need not be of the same type as the values. The key type K
must be comparable using ==, so that the map can test whether a given key is
equal to one already within it.
*/
fmt.Println( "*** Map Basics ***")
ages1 := make(map[string]int) // mapping from strings to ints
fmt.Println(ages1)
/* An alternative expression for a new empty map is: */
ages2 := map[string]int{}
fmt.Println(ages2)
/*
We can also use a map literal to create a new map populated with some
initial key/value pairs:
*/
ages3 := map[string]int{
"alice": 31,
"charlie": 34,
}
fmt.Println(ages3)
/* This is equivalent to */
ages4 := make(map[string]int)
ages4["alice"] = 31
ages4["charlie"] = 34
fmt.Println(ages4)
/* Map elements are accessed through the usual subscript notation: */
fmt.Println( "*** Map Access ***")
ages4["alice"] = 32
fmt.Println(ages4["alice"]) // "32"
/* Remove elements works with the built-in function delete: */
fmt.Println( "*** Map Delete ***")
delete(ages4, "alice") // remove element ages["alice"]
fmt.Println(ages4)
/*
All of these operations are safe even if the element isn’t in the map; a
map lookup using a key that isn’t present returns the zero value for its
type, so, for instance, the following works even when "bob" is not yet a
key in the map because the value of ages["bob"] will be 0.
*/
fmt.Println( "*** Adding Bob into the Map ***")
ages4["bob"] = ages4["bob"] + 1 // happy birthday!
fmt.Println(ages4)
/*
The shorthand assignment forms x += y and x++ also work for map
elements, so we can rewrite the statement above as
*/
ages4["bob"] += 1
fmt.Println(ages4)
/* or even more concisely as... */
ages4["bob"]++
fmt.Println(ages4)
/*
But a map element is not a variable, and we cannot take its address:
_ = &ages4["bob"] // compile error: cannot take address of map element
One reason that we can’t take the address of a map element is that growing
a map might cause rehashing of existing elements into new storage
locations, thus potentially invalidating the address.
*/
/*
To enumerate all the key/value pairs in the map, we use a range-based
for loop similar to those we saw for slices. Successive iterations of
the loop cause the name and age variables to be set to the next
key/value pair:
Note: The order of map iteration is unspecified, and different
implementations might use a different hash function, leading to a
different ordering. In practice, the order is random,
*/
fmt.Println( "*** Enumeration ***")
for name, age := range ages4 {
fmt.Printf("%s\t%d\n", name, age)
}
/*
To enumerate the key/value pairs in order, we must sort the keys
explicitly, for instance, using the Strings function from the sort
package if the keys are strings. This is a common pattern:
*/
fmt.Println( "*** Sorted ***")
ages4["tom"] = ages4["tom"] + 1
ages4["cindy"] = ages4["cindy"] + 1
ages4["mary"] = ages4["mary"] + 1
// Since we know the final size of names from the outset, it is more
// efficient to allocate an array of the required size up front.
// I.E. Instead of:
//
// var names []string
//
names := make([]string, 0, len(ages4)) // initially empty, but has capacity for ages4
for name := range ages4 {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
fmt.Printf("%s\t%d\n", name, ages4[name])
}
/*
The zero value for a map type is nil, that is, a reference to no hash
table at all.
Most operations on maps, including lookup, delete, len, and range loops,
are safe to perform on a nil map reference, since it behaves like an
empty map. But storing to a nil map causes a panic:
ages["carol"] = 21 // panic: assignment to entry in nil map
*/
fmt.Println( "*** Handling NIL Maps ***")
var ages map[string]int
fmt.Println(ages == nil) // "true"
fmt.Println(len(ages) == 0) // "true"
}
|
[
0
] |
package cgoconverter
/*
#include <stdlib.h>
*/
import "C"
import (
"math"
"sync/atomic"
"unsafe"
"github.com/milvus-io/milvus/pkg/util/typeutil"
)
const maxByteArrayLen = math.MaxInt32
var globalConverter = NewBytesConverter()
type BytesConverter struct {
pointers *typeutil.ConcurrentMap[int32, unsafe.Pointer] // leaseId -> unsafe.Pointer
nextLease int32
}
func NewBytesConverter() *BytesConverter {
return &BytesConverter{
pointers: typeutil.NewConcurrentMap[int32, unsafe.Pointer](),
nextLease: 0,
}
}
func (converter *BytesConverter) add(p unsafe.Pointer) int32 {
lease := atomic.AddInt32(&converter.nextLease, 1)
converter.pointers.Insert(lease, p)
return lease
}
// Return a lease and []byte from C bytes (typically char*)
// which references the same memory of C bytes
// Call Release(lease) after you don't need the returned []byte
func (converter *BytesConverter) UnsafeGoBytes(cbytes *unsafe.Pointer, len int) (int32, []byte) {
var (
goBytes []byte
lease int32
)
if len > maxByteArrayLen {
// C.GoBytes takes the length as C.int,
// which is always 32-bit (not depends on platform)
panic("UnsafeGoBytes: out of length")
}
goBytes = (*[maxByteArrayLen]byte)(*cbytes)[:len:len]
lease = converter.add(*cbytes)
*cbytes = nil
return lease, goBytes
}
func (converter *BytesConverter) Release(lease int32) {
p := converter.Extract(lease)
C.free(p)
}
func (converter *BytesConverter) Extract(lease int32) unsafe.Pointer {
p, ok := converter.pointers.GetAndRemove(lease)
if !ok {
panic("try to release the resource that doesn't exist")
}
return p
}
// Make sure only the caller own the converter
// or this would release someone's memory
func (converter *BytesConverter) ReleaseAll() {
converter.pointers.Range(func(lease int32, pointer unsafe.Pointer) bool {
converter.pointers.GetAndRemove(lease)
C.free(pointer)
return true
})
}
func UnsafeGoBytes(cbytes *unsafe.Pointer, len int) (int32, []byte) {
return globalConverter.UnsafeGoBytes(cbytes, len)
}
func Release(lease int32) {
globalConverter.Release(lease)
}
func Extract(lease int32) unsafe.Pointer {
return globalConverter.Extract(lease)
}
// DO NOT provide ReleaseAll() method for global converter
|
[
1
] |
package storage
import (
"errors"
"github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/html"
"io/fs"
"os"
"regexp"
"strconv"
"strings"
)
var defaultFilePermission fs.FileMode = 0755
var defaultDirectoryPermission fs.FileMode = 0755
var renderer markdown.Renderer
var filenameValidationRegexp *regexp.Regexp
var FilenameEmptyValidation string = "Filename cannot be empty"
var InvalidFilenameValidation string = "Invalid filename, valid examples: wiki_page_1.md, flowers-and-animals.md, page106.md"
var SamePageExistsValidation string = "Page with same name already exists"
func init() {
htmlFlags := html.CommonFlags
opts := html.RendererOptions{Flags: htmlFlags}
renderer = html.NewRenderer(opts)
filenameValidationRegexp, _ = regexp.Compile("^[\\w-\\\\.]+[^\\W]{1}$")
}
func newPage(filename string, content []byte) *Page {
name, version := parsePageFilename(filename)
return &Page{
Filename: filename,
Name: name,
Version: version,
Content: ToMarkdown(content),
RawContent: string(content[:]),
}
}
func ToMarkdown(content []byte) string {
contentString := strings.NewReplacer("\r\n", "\n").Replace(string(content))
return string(markdown.ToHTML([]byte(contentString), nil, renderer))
}
func FixPageExtension(uri string) string {
page := strings.TrimSpace(uri)
if page != "" && !strings.HasSuffix(page, ".md") {
page = page + ".md"
}
return page
}
func ValidateFilename(filename string) error {
if strings.TrimSpace(filename) == "" {
return errors.New(FilenameEmptyValidation)
}
if !filenameValidationRegexp.MatchString(filename) {
return errors.New(InvalidFilenameValidation)
}
return nil
}
func fsExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func parsePageFilename(filename string) (string, int64) {
parts := strings.Split(filename, "__")
if len(parts) > 1 {
f := strings.Join(parts[:len(parts)-1], "__")
ts, err := strconv.ParseInt(parts[len(parts)-1], 10, 64)
if err != nil {
return f, 0
}
return f, ts
}
return filename, 0
}
|
[
0
] |
package main
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
)
var SessionMngr SessionManager
func main() {
fmt.Println("Panthera.Go")
MakeDefaultSession()
HttpServe()
}
func MakeDefaultSession() {
SessionMngr = SessionManager{Sessions: map[string]*Session{}}
SessionMngr.Make()
SessionMngr.ComponentSrcs = map[string]*ComponentSrc{
// Root is a virtual component at Session.RootComp of every Session. Think it as a global variable store for Session
"root": ComponentSrc{}.Make("root", func() string { return "" }), // No need of source for Root
"dash": ComponentSrc{}.Make("dash", URIProvider("dash.go.html")),
"footer": ComponentSrc{}.Make("footer", URIProvider("footer.go.html")),
"sessionview": ComponentSrc{}.Make("sessionview", URIProvider("sessionview.go.html")),
"counter": ComponentSrc{}.Make("counter", URIProvider("counter.go.html")).SetVarsOnNew(map[string]string{"count": "100"}),
}
DefaultSession := Session{ID: "Default", ComponentSrcProvider: SessionMngr.ComponentSrcProvider}
DefaultSession.MakeRoot()
DefaultSession.SetVar("root.var1", "This variable is available throughout the session")
DefaultSession.SetVar("root.company-name", "Bitblazers")
DefaultSession.SetVar("root.dash1.company-name", "Bitblazers")
DefaultSession.SetVar("root.dash1.bigtext", "PantheraGo is a HTML DOM manipulator written in <strong> Go Language. </strong> PantheraGo can run in the browser using Web Assembly and also, it can function as a webserver running on Linux, Mac, Windows and Android natively ")
DefaultSession.SetVar("root.dash1.myvar", "123")
RootSrc := SessionMngr.ComponentSrcProvider("root")
RootSrc.SetFunc("time", func_Root_Time)
SessionViewSrc := SessionMngr.ComponentSrcProvider("sessionview")
SessionViewSrc.SetFunc("sessionjson", func(c *Component) string {
jsn, jerr := json.MarshalIndent(c.Session.Stash(), "", "\t")
if jerr != nil {
return "Serializing Session to JSON failed"
} else {
return `<textarea style="width: 100%; height: 20em;">` + string(jsn) + ` </textarea>`
}
})
// DefaultSession.SetFunc("dash.sayhello", SayTime)
// DefaultSession.ResolveCompPath("dash").r
// DefaultSession.SetEvent("root.btn-count-click", BtnCountClick)
// DefaultSession.SetEvent("root.txt-name-change", TxtNameChanged)
SessionMngr.DefaultSessionStash = DefaultSession.Stash()
}
func URIProvider(uri string) func() string {
return func() string {
HTML, _ := LoadURIToString(uri)
return HTML
}
}
func ServePanthera(Req *SvrRequest) Response {
HTML, _ := LoadURIToString(Req.Paths[0])
CurrentSession := Req.AuthSession()
CurrentSession.SetVar("root.panthera-session", CurrentSession.ID)
Panthtml := CurrentSession.RootComp.RenderSource(HTML)
return StringResponse(Panthtml)
}
func APIGoEvent(Req *SvrRequest) Response {
if len(Req.Paths) != 4 {
println("API path error : " + strings.Join(Req.Paths, " - "))
return StringResponse("error:500")
}
CurrentSession := Req.AuthSession()
if CurrentSession == nil {
println("Error. No Session")
return StringResponse("NoSession")
}
evrsp := CurrentSession.CallEvent(Req.Paths[1], Req.Paths[2], Req.Paths[3])
brsp, jerr := json.Marshal(evrsp)
if jerr != nil {
PrintError(jerr)
}
return BodyResponse(brsp)
}
func func_Root_Time(c *Component) string {
return time.Now().String()
}
// func BtnCountClick(sender, Para string) EventResponse {
// println("Event raised : From " + sender + " : Para " + Para)
// count, err := strconv.Atoi(GetVar("count"))
// if err != nil {
// count = 0
// }
// count++
// SetVar("count", strconv.Itoa(count))
// SetVar("myvar", "Whole document can be reloaded on each event "+strconv.Itoa(count))
// return EventResponse{Reload: true}
// }
// func TxtNameChanged(sender, Para string) EventResponse {
// if len(Para) == 0 {
// return EventResponse{Reload: false, Update: false}
// }
// var ch chan string = make(chan string)
// go BuildSomeLongText(Para, ch)
// var buffer bytes.Buffer
// for perm := range ch {
// buffer.WriteString(perm)
// }
// R := buffer.String()
// SetVar("name-result", R)
// return EventResponse{Reload: false, Update: true, ID: "name-result", Content: R}
// }
func BuildSomeLongText(s string, ch chan string) {
ch <- " <br>"
for i := 0; i < len(s)*10; i++ {
ch <- s + " " + strconv.Itoa(i) + " <br>"
}
close(ch)
}
|
[
2
] |
package main
import (
"fmt"
)
func main() {
xi := []int{1,2,3,4,5,6,7,8,9}
ret := sum(xi...) // because we already have a slice, we need to unravel it or unroll it, basically it undoes the slice to many ints
fmt.Println(ret)
// we could also pass in nothing
sum1 := sum()
fmt.Println(sum1)
newSum := helloSum("kevin", xi...)
fmt.Println(newSum)
}
func sum(x ...int) int { // turns x into a slice
fmt.Println(x)
fmt.Printf("%T\n", x)
sum := 0
for _, v := range x {
sum = sum + v
}
return sum
}
// if there are multiple parameters and a variadic parameter is one of them, it must be the final parameter, because you can pass 0 or more
func helloSum(s string, x ...int) int {
fmt.Println(x)
fmt.Printf("%T\n", x)
fmt.Println(s)
sum := 0
for _, v := range x {
sum = sum + v
}
return sum
}
|
[
0
] |
package tests
import (
"context"
"strings"
"testing"
"github.com/ipfs/go-cid"
iface "github.com/ipfs/interface-go-ipfs-core"
opt "github.com/ipfs/interface-go-ipfs-core/options"
mbase "github.com/multiformats/go-multibase"
)
func (tp *TestSuite) TestKey(t *testing.T) {
tp.hasApi(t, func(api iface.CoreAPI) error {
if api.Key() == nil {
return errAPINotImplemented
}
return nil
})
t.Run("TestListSelf", tp.TestListSelf)
t.Run("TestRenameSelf", tp.TestRenameSelf)
t.Run("TestRemoveSelf", tp.TestRemoveSelf)
t.Run("TestGenerate", tp.TestGenerate)
t.Run("TestGenerateSize", tp.TestGenerateSize)
t.Run("TestGenerateType", tp.TestGenerateType)
t.Run("TestGenerateExisting", tp.TestGenerateExisting)
t.Run("TestList", tp.TestList)
t.Run("TestRename", tp.TestRename)
t.Run("TestRenameToSelf", tp.TestRenameToSelf)
t.Run("TestRenameToSelfForce", tp.TestRenameToSelfForce)
t.Run("TestRenameOverwriteNoForce", tp.TestRenameOverwriteNoForce)
t.Run("TestRenameOverwrite", tp.TestRenameOverwrite)
t.Run("TestRenameSameNameNoForce", tp.TestRenameSameNameNoForce)
t.Run("TestRenameSameName", tp.TestRenameSameName)
t.Run("TestRemove", tp.TestRemove)
}
func (tp *TestSuite) TestListSelf(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
api, err := tp.makeAPI(ctx)
if err != nil {
t.Fatal(err)
return
}
self, err := api.Key().Self(ctx)
if err != nil {
t.Fatal(err)
}
keys, err := api.Key().List(ctx)
if err != nil {
t.Fatalf("failed to list keys: %s", err)
return
}
if len(keys) != 1 {
t.Fatalf("there should be 1 key (self), got %d", len(keys))
return
}
if keys[0].Name() != "self" {
t.Errorf("expected the key to be called 'self', got '%s'", keys[0].Name())
}
if keys[0].Path().String() != "/ipns/"+iface.FormatKeyID(self.ID()) {
t.Errorf("expected the key to have path '/ipns/%s', got '%s'", iface.FormatKeyID(self.ID()), keys[0].Path().String())
}
}
func (tp *TestSuite) TestRenameSelf(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
api, err := tp.makeAPI(ctx)
if err != nil {
t.Fatal(err)
return
}
_, _, err = api.Key().Rename(ctx, "self", "foo")
if err == nil {
t.Error("expected error to not be nil")
} else {
if !strings.Contains(err.Error(), "cannot rename key with name 'self'") {
t.Fatalf("expected error 'cannot rename key with name 'self'', got '%s'", err.Error())
}
}
_, _, err = api.Key().Rename(ctx, "self", "foo", opt.Key.Force(true))
if err == nil {
t.Error("expected error to not be nil")
} else {
if !strings.Contains(err.Error(), "cannot rename key with name 'self'") {
t.Fatalf("expected error 'cannot rename key with name 'self'', got '%s'", err.Error())
}
}
}
func (tp *TestSuite) TestRemoveSelf(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
api, err := tp.makeAPI(ctx)
if err != nil {
t.Fatal(err)
return
}
_, err = api.Key().Remove(ctx, "self")
if err == nil {
t.Error("expected error to not be nil")
} else {
if !strings.Contains(err.Error(), "cannot remove key with name 'self'") {
t.Fatalf("expected error 'cannot remove key with name 'self'', got '%s'", err.Error())
}
}
}
func (tp *TestSuite) TestGenerate(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
api, err := tp.makeAPI(ctx)
if err != nil {
t.Fatal(err)
}
k, err := api.Key().Generate(ctx, "foo")
if err != nil {
t.Fatal(err)
return
}
if k.Name() != "foo" {
t.Errorf("expected the key to be called 'foo', got '%s'", k.Name())
}
verifyIPNSPath(t, k.Path().String())
}
func verifyIPNSPath(t *testing.T, p string) bool {
t.Helper()
if !strings.HasPrefix(p, "/ipns/") {
t.Errorf("path %q does not look like an IPNS path", p)
return false
}
k := p[len("/ipns/"):]
c, err := cid.Decode(k)
if err != nil {
t.Errorf("failed to decode IPNS key %q (%v)", k, err)
return false
}
b36, err := c.StringOfBase(mbase.Base36)
if err != nil {
t.Fatalf("cid cannot format itself in b36")
return false
}
if b36 != k {
t.Errorf("IPNS key is not base36")
}
return true
}
func (tp *TestSuite) TestGenerateSize(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
api, err := tp.makeAPI(ctx)
if err != nil {
t.Fatal(err)
}
k, err := api.Key().Generate(ctx, "foo", opt.Key.Size(2048))
if err != nil {
t.Fatal(err)
return
}
if k.Name() != "foo" {
t.Errorf("expected the key to be called 'foo', got '%s'", k.Name())
}
verifyIPNSPath(t, k.Path().String())
}
func (tp *TestSuite) TestGenerateType(t *testing.T) {
t.Skip("disabled until libp2p/specs#111 is fixed")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
api, err := tp.makeAPI(ctx)
if err != nil {
t.Fatal(err)
}
k, err := api.Key().Generate(ctx, "bar", opt.Key.Type(opt.Ed25519Key))
if err != nil {
t.Fatal(err)
return
}
if k.Name() != "bar" {
t.Errorf("expected the key to be called 'foo', got '%s'", k.Name())
}
// Expected to be an inlined identity hash.
if !strings.HasPrefix(k.Path().String(), "/ipns/12") {
t.Errorf("expected the key to be prefixed with '/ipns/12', got '%s'", k.Path().String())
}
}
func (tp *TestSuite) TestGenerateExisting(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
api, err := tp.makeAPI(ctx)
if err != nil {
t.Fatal(err)
}
_, err = api.Key().Generate(ctx, "foo")
if err != nil {
t.Fatal(err)
return
}
_, err = api.Key().Generate(ctx, "foo")
if err == nil {
t.Error("expected error to not be nil")
} else {
if !strings.Contains(err.Error(), "key with name 'foo' already exists") {
t.Fatalf("expected error 'key with name 'foo' already exists', got '%s'", err.Error())
}
}
_, err = api.Key().Generate(ctx, "self")
if err == nil {
t.Error("expected error to not be nil")
} else {
if !strings.Contains(err.Error(), "cannot create key with name 'self'") {
t.Fatalf("expected error 'cannot create key with name 'self'', got '%s'", err.Error())
}
}
}
func (tp *TestSuite) TestList(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
api, err := tp.makeAPI(ctx)
if err != nil {
t.Fatal(err)
}
_, err = api.Key().Generate(ctx, "foo")
if err != nil {
t.Fatal(err)
return
}
l, err := api.Key().List(ctx)
if err != nil {
t.Fatal(err)
return
}
if len(l) != 2 {
t.Fatalf("expected to get 2 keys, got %d", len(l))
return
}
if l[0].Name() != "self" {
t.Fatalf("expected key 0 to be called 'self', got '%s'", l[0].Name())
return
}
if l[1].Name() != "foo" {
t.Fatalf("expected key 1 to be called 'foo', got '%s'", l[1].Name())
return
}
verifyIPNSPath(t, l[0].Path().String())
verifyIPNSPath(t, l[1].Path().String())
}
func (tp *TestSuite) TestRename(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
api, err := tp.makeAPI(ctx)
if err != nil {
t.Fatal(err)
}
_, err = api.Key().Generate(ctx, "foo")
if err != nil {
t.Fatal(err)
return
}
k, overwrote, err := api.Key().Rename(ctx, "foo", "bar")
if err != nil {
t.Fatal(err)
return
}
if overwrote {
t.Error("overwrote should be false")
}
if k.Name() != "bar" {
t.Errorf("returned key should be called 'bar', got '%s'", k.Name())
}
}
func (tp *TestSuite) TestRenameToSelf(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
api, err := tp.makeAPI(ctx)
if err != nil {
t.Fatal(err)
}
_, err = api.Key().Generate(ctx, "foo")
if err != nil {
t.Fatal(err)
return
}
_, _, err = api.Key().Rename(ctx, "foo", "self")
if err == nil {
t.Error("expected error to not be nil")
} else {
if !strings.Contains(err.Error(), "cannot overwrite key with name 'self'") {
t.Fatalf("expected error 'cannot overwrite key with name 'self'', got '%s'", err.Error())
}
}
}
func (tp *TestSuite) TestRenameToSelfForce(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
api, err := tp.makeAPI(ctx)
if err != nil {
t.Fatal(err)
}
_, err = api.Key().Generate(ctx, "foo")
if err != nil {
t.Fatal(err)
return
}
_, _, err = api.Key().Rename(ctx, "foo", "self", opt.Key.Force(true))
if err == nil {
t.Error("expected error to not be nil")
} else {
if !strings.Contains(err.Error(), "cannot overwrite key with name 'self'") {
t.Fatalf("expected error 'cannot overwrite key with name 'self'', got '%s'", err.Error())
}
}
}
func (tp *TestSuite) TestRenameOverwriteNoForce(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
api, err := tp.makeAPI(ctx)
if err != nil {
t.Fatal(err)
}
_, err = api.Key().Generate(ctx, "foo")
if err != nil {
t.Fatal(err)
return
}
_, err = api.Key().Generate(ctx, "bar")
if err != nil {
t.Fatal(err)
return
}
_, _, err = api.Key().Rename(ctx, "foo", "bar")
if err == nil {
t.Error("expected error to not be nil")
} else {
if !strings.Contains(err.Error(), "key by that name already exists, refusing to overwrite") {
t.Fatalf("expected error 'key by that name already exists, refusing to overwrite', got '%s'", err.Error())
}
}
}
func (tp *TestSuite) TestRenameOverwrite(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
api, err := tp.makeAPI(ctx)
if err != nil {
t.Fatal(err)
}
kfoo, err := api.Key().Generate(ctx, "foo")
if err != nil {
t.Fatal(err)
return
}
_, err = api.Key().Generate(ctx, "bar")
if err != nil {
t.Fatal(err)
return
}
k, overwrote, err := api.Key().Rename(ctx, "foo", "bar", opt.Key.Force(true))
if err != nil {
t.Fatal(err)
return
}
if !overwrote {
t.Error("overwrote should be true")
}
if k.Name() != "bar" {
t.Errorf("returned key should be called 'bar', got '%s'", k.Name())
}
if k.Path().String() != kfoo.Path().String() {
t.Errorf("k and kfoo should have equal paths, '%s'!='%s'", k.Path().String(), kfoo.Path().String())
}
}
func (tp *TestSuite) TestRenameSameNameNoForce(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
api, err := tp.makeAPI(ctx)
if err != nil {
t.Fatal(err)
}
_, err = api.Key().Generate(ctx, "foo")
if err != nil {
t.Fatal(err)
return
}
k, overwrote, err := api.Key().Rename(ctx, "foo", "foo")
if err != nil {
t.Fatal(err)
return
}
if overwrote {
t.Error("overwrote should be false")
}
if k.Name() != "foo" {
t.Errorf("returned key should be called 'foo', got '%s'", k.Name())
}
}
func (tp *TestSuite) TestRenameSameName(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
api, err := tp.makeAPI(ctx)
if err != nil {
t.Fatal(err)
}
_, err = api.Key().Generate(ctx, "foo")
if err != nil {
t.Fatal(err)
return
}
k, overwrote, err := api.Key().Rename(ctx, "foo", "foo", opt.Key.Force(true))
if err != nil {
t.Fatal(err)
return
}
if overwrote {
t.Error("overwrote should be false")
}
if k.Name() != "foo" {
t.Errorf("returned key should be called 'foo', got '%s'", k.Name())
}
}
func (tp *TestSuite) TestRemove(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
api, err := tp.makeAPI(ctx)
if err != nil {
t.Fatal(err)
}
k, err := api.Key().Generate(ctx, "foo")
if err != nil {
t.Fatal(err)
return
}
l, err := api.Key().List(ctx)
if err != nil {
t.Fatal(err)
return
}
if len(l) != 2 {
t.Fatalf("expected to get 2 keys, got %d", len(l))
return
}
p, err := api.Key().Remove(ctx, "foo")
if err != nil {
t.Fatal(err)
return
}
if k.Path().String() != p.Path().String() {
t.Errorf("k and p should have equal paths, '%s'!='%s'", k.Path().String(), p.Path().String())
}
l, err = api.Key().List(ctx)
if err != nil {
t.Fatal(err)
return
}
if len(l) != 1 {
t.Fatalf("expected to get 1 key, got %d", len(l))
return
}
if l[0].Name() != "self" {
t.Errorf("expected the key to be called 'self', got '%s'", l[0].Name())
}
}
|
[
4
] |
// Package config uses a struct as input and populates the
// fields of this struct with parameters fom command
// line, environment variables and configuration file.
package config
import (
"errors"
"fmt"
"os"
"path"
"path/filepath"
"crg.eti.br/go/config/goenv"
"crg.eti.br/go/config/goflags"
"crg.eti.br/go/config/structtag"
"crg.eti.br/go/config/validate"
)
// Fileformat struct holds the functions to Load the file containing the settings.
type Fileformat struct {
Extension string
Load func(config interface{}) (err error)
PrepareHelp func(config interface{}) (help string, err error)
}
var (
// Tag to set main name of field.
Tag = "cfg"
// TagDefault to set default value.
TagDefault = "cfgDefault"
// TagHelper to set usage help line.
TagHelper = "cfgHelper"
// Path sets default config path.
Path string
// File name of default config file.
File string
// FileRequired config file required.
FileRequired bool
// HelpString temporarily saves help.
HelpString string
// PrefixFlag is a string that would be placed at the beginning of the generated Flag tags.
PrefixFlag string
// PrefixEnv is a string that would be placed at the beginning of the generated Event tags.
PrefixEnv string
// ErrFileFormatNotDefined Is the error that is returned when there is no defined configuration file format.
ErrFileFormatNotDefined = errors.New("file format not defined")
Usage func()
// Formats is the list of registered formats.
Formats []Fileformat
// FileEnv is the enviroment variable that define the config file.
FileEnv string
// PathEnv is the enviroment variable that define the config file path.
PathEnv string
// WatchConfigFile is the flag to update the config when the config file changes.
WatchConfigFile bool
// DisableFlags on the command line.
DisableFlags bool
)
func findFileFormat(extension string) (format Fileformat, err error) {
format = Fileformat{}
for _, f := range Formats {
if f.Extension == extension {
format = f
return
}
}
err = ErrFileFormatNotDefined
return
}
func init() {
Usage = DefaultUsage
Path = "./"
File = ""
FileRequired = false
FileEnv = "GO_CONFIG_FILE"
PathEnv = "GO_CONFIG_PATH"
WatchConfigFile = false
}
// Parse configuration.
func Parse(config interface{}) (err error) {
goenv.Prefix = PrefixEnv
goenv.Setup(Tag, TagDefault)
err = structtag.SetBoolDefaults(config, "")
if err != nil {
return
}
lookupEnv()
ext := path.Ext(File)
if ext != "" {
if err = loadConfigFromFile(ext, config); err != nil {
return
}
}
goenv.Prefix = PrefixEnv
goenv.Setup(Tag, TagDefault)
err = goenv.Parse(config)
if err != nil {
return
}
if !DisableFlags {
goflags.Prefix = PrefixFlag
goflags.Setup(Tag, TagDefault, TagHelper)
goflags.Usage = Usage
goflags.Preserve = true
err = goflags.Parse(config)
if err != nil {
return
}
}
validate.Prefix = PrefixFlag
validate.Setup(Tag, TagDefault)
err = validate.Parse(config)
return
}
// PrintDefaults print the default help.
func PrintDefaults() {
if File != "" {
fmt.Printf("Config file %q:\n", filepath.Join(Path, File))
fmt.Println(HelpString)
}
}
// DefaultUsage is assigned for Usage function by default.
func DefaultUsage() {
fmt.Println("Usage")
goflags.PrintDefaults()
goenv.PrintDefaults()
PrintDefaults()
}
func lookupEnv() {
pref := PrefixEnv
if pref != "" {
pref = pref + structtag.TagSeparator
}
if val, set := os.LookupEnv(pref + FileEnv); set {
File = val
}
if val, set := os.LookupEnv(pref + PathEnv); set {
Path = val
}
}
func loadConfigFromFile(ext string, config interface{}) (err error) {
var format Fileformat
format, err = findFileFormat(ext)
if err != nil {
return
}
err = format.Load(config)
if err != nil {
return
}
HelpString, err = format.PrepareHelp(config)
return
}
|
[
0
] |
package main
import (
"fmt"
"sort"
)
func main() {
var n int
fmt.Scan(&n)
set(n)
}
func set(n int) {
var sum, total, tmp, tmp1, k, p int
sum = 0
a := make([]int, n)
for i := 0; i < n; i++ {
fmt.Scan(&a[i])
}
sort.Ints(a)
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
a[i], a[j] = a[j], a[i]
}
for _, k = range a {
sum = sum + k
}
total = (sum / 2) + 1
tmp = 0
tmp1 = 0
for _, p = range a {
tmp = tmp + p
tmp1 = tmp1 + 1
if tmp >= total {
break
}
}
fmt.Println(tmp1)
}
|
[
0
] |
package subjects
import (
"fmt"
)
func hello(a int, b ...int) {
}
func find(num int, nums ...int) {
fmt.Printf("type of nums is %T\n", nums)
found := false
for i, v := range nums {
if v == num {
fmt.Println(num, "found at index", i, "in", nums)
found = true
}
}
if !found {
fmt.Println(num, "not found in ", nums)
}
fmt.Println()
}
func change(s...string) {
s[0] = "Go"
}
func change2(s...string){
s[0] = "Go"
s = append(s, "playground")
fmt.Println(s)
}
func PrintVariadicFunctions(print string) {
if print == "yes" {
hello(1)
hello(1,2)
hello(5, 6, 7, 8, 9)
fmt.Println()
find(89, 89, 90, 95)
find(45, 56, 67, 45, 90, 109)
find(78, 38, 56, 98)
find(87)
nums := []int{89, 90, 95}
find(89, nums...)
fmt.Println()
welcome := []string{"hello","world"}
change(welcome...)
fmt.Println(welcome)
fmt.Println()
welcome2 := []string{"hello","world"}
change2(welcome2...)
fmt.Println(welcome2)
} else {
// Do nothing
}
}
|
[
1
] |
package main
import (
"encoding/json"
"fmt"
)
type country struct {
Name string
}
func main() {
country_code := "US"
the_country := country{}
switch country_code {
case "US":
the_country.Name = "United States"
}
c, err := json.Marshal(the_country)
if err != nil {
panic(err)
}
// c is now a []byte containing the encoded JSON
fmt.Print(string(c))
}
|
[
7
] |
package migration
import "gorm.io/gorm"
type Inventory struct {
gorm.Model
Name string `gorm:"default:null"`
Price int64 `gorm:"default:null"`
FileName string `gorm:"default:null"`
Description string `sql:"type:text;"`
Stock int `gorm:"default:0"`
UserID uint `gorm:"default:null"`
}
func (Inventory) TableName() string {
return "inventories"
}
func (Inventory) Pk() string {
return "id"
}
func (I Inventory) Ref() string {
return I.TableName() + "(" + I.Pk() + ")"
}
|
[
2
] |
package bmp280
import (
"fmt"
"math"
"periph.io/x/periph/conn/i2c"
)
// BMP a BMP280 sensor
type BMP struct {
device *i2c.Dev
config *Configuration
lastTemperatureMeasurement float64
tempCalibration []calibrationData
pressCalibration []calibrationData
}
// NewBMP280 create an initialize a new BMP280 sensor. Returns the newly created BMP280 sensor
func NewBMP280(dev *i2c.Dev) (*BMP, error) {
bmp := &BMP{
device: dev,
tempCalibration: make([]calibrationData, 3),
pressCalibration: make([]calibrationData, 9),
lastTemperatureMeasurement: math.NaN(),
}
err := bmp.Init()
return bmp, err
}
// NewBMP280WithConfig create an initialize a new BMP280 sensor and set up its initial configuration. Returns the newly created BMP280 sensor or any errors that occurred when configuring it.
func NewBMP280WithConfig(dev *i2c.Dev, cfg *Configuration) (*BMP, error) {
bmp := &BMP{
device: dev,
config: cfg,
tempCalibration: make([]calibrationData, 3),
pressCalibration: make([]calibrationData, 9),
lastTemperatureMeasurement: math.NaN(),
}
if err := bmp.SetConfiguration(cfg); err != nil {
return bmp, err
}
err := bmp.Init()
return bmp, err
}
// Init initializes the BMP280 sensor with calibration data saved in the BMP280's registers
func (me *BMP) Init() error {
d, err := me.readCalibrationValues(regsTempCalibration...)
if err != nil {
return fmt.Errorf("Error reading temperature calibration values: %s", err.Error())
}
me.tempCalibration = d
if d, err = me.readCalibrationValues(regsPressureCalibration...); err != nil {
return fmt.Errorf("Error reading pressure calibration values: %s", err.Error())
}
me.pressCalibration = d
return nil
}
// Configuration get the current configuration for this BMP280 sensor
func (me *BMP) Configuration() *Configuration {
return me.config
}
// SetConfiguration set up the configuration for how this BMP280 sensor should operate. Returns any errors that occur when configuring the sensor
func (me *BMP) SetConfiguration(cfg *Configuration) error {
me.config = cfg
_, err := me.device.Write(cfg.bytes())
return err
}
// Reset perform a full reset on the BMP280 device as if it had first powered on
func (me *BMP) Reset() error {
_, err := me.device.Write([]byte{uint8(regReset), resetCode})
return err
}
// ReadAll reads both temperature and pressure sensor data at once. Returns temperature value, pressure value, or any errors that occurred
func (me *BMP) ReadAll() (float64, float64, error) {
intVals, err := me.readSensorValues(regTemperature, regPressure)
if err != nil {
return math.NaN(), math.NaN(), err
}
temp := me.computeTemperature(intVals[0])
press := me.computePressure(intVals[1])
return temp, press, nil
}
// ReadTemperature read the latest temperature reading from the BMP280. Returns the temperature in Celsius or any i2c errors that occurred
func (me *BMP) ReadTemperature() (float64, error) {
intVals, err := me.readSensorValues(regTemperature)
if err != nil {
return math.NaN(), err
}
return me.computeTemperature(intVals[0]), nil
}
// ReadPressure read the latest pressure reading from the BMP280. Returns the pressure in Pascals or any i2c errors that occurred
func (me *BMP) ReadPressure() (float64, error) {
if math.IsNaN(float64(me.lastTemperatureMeasurement)) {
if _, err := me.ReadTemperature(); err != nil {
return float64(math.NaN()), err
}
}
vals, err := me.readSensorValues(regPressure)
if err != nil {
return math.NaN(), err
}
return me.computePressure(vals[0]), nil
}
func (me *BMP) computeTemperature(intVal sensorData) float64 {
floatVal := float64(intVal)
var1 := (floatVal/16384.0 - me.pressCalibration[0].f()/1024.0) * me.pressCalibration[1].f()
var2 := ((floatVal/131072.0 - me.pressCalibration[0].f()/8192.0) * (floatVal/131072.0 - me.pressCalibration[0].f()/8192.0)) * me.pressCalibration[2].f()
me.lastTemperatureMeasurement = var1 + var2
return me.lastTemperatureMeasurement / 5120.0
}
func (me *BMP) computePressure(intVal sensorData) float64 {
floatVal := float64(intVal)
var1 := me.lastTemperatureMeasurement/2.0 - 64000.0
var2 := var1 * var1 * me.pressCalibration[5].f() / 32768.0
var2 = var2 + var1*me.pressCalibration[4].f()*2.0
var2 = var2/4.0 + me.pressCalibration[3].f()*65536.0
var1 = (me.pressCalibration[2].f()*var1*var1/524288.0 + me.pressCalibration[1].f()*var1) / 524288.0
var1 = (1.0 + var1/32768.0) * me.pressCalibration[0].f()
if var1 == 0.0 {
return 0.0
}
p := 1048576.0 - floatVal
p = (p - (var2 / 4096.0)) * 6250.0 / var1
var1 = me.pressCalibration[8].f() * p * p / 2147483648.0
var2 = p * me.pressCalibration[7].f() / 32768.0
p = p + (var1+var2+me.pressCalibration[6].f())/16.0
return p
}
func (me *BMP) readCalibrationValues(registers ...register) ([]calibrationData, error) {
b, err := me.readRegisters(2, registers...)
if err != nil {
return nil, err
}
vals := make([]calibrationData, len(registers))
for i := 0; i < len(b); i += 2 {
vals[i/2] = newCalibrationData(b, i, i == 0)
}
return vals, nil
}
func (me *BMP) readSensorValues(registers ...register) ([]sensorData, error) {
b, err := me.readRegisters(3, registers...)
if err != nil {
return nil, err
}
vals := make([]sensorData, len(registers))
for i := 0; i < len(b); i += 3 {
vals[i/3] = newSensorData(b, i)
}
return vals, nil
}
func (me *BMP) readRegisters(size int, registers ...register) ([]byte, error) {
w := make([]byte, len(registers)*size)
r := make([]byte, len(w))
if err := me.device.Bus.Tx(me.device.Addr, w, r); err != nil {
return nil, err
}
return r, nil
}
func (me *BMP) convertUInt16(b []byte, offset int) uint16 {
if offset+2 > len(b) {
panic("Offset and length must fit within size of slice")
}
return uint16(b[offset+1])<<8 | (0xFF & uint16(b[offset]))
}
func (me *BMP) convertInt16(b []byte, offset int) int16 {
if offset+2 > len(b) {
panic("Offset and length must fit within size of slice")
}
return int16(b[offset+1])<<8 | (0xFF & int16(b[offset]))
}
|
[
0
] |
package utils
func IntMin(x, y int) int {
if x < y {
return x
}
return y
}
func IntMax(x, y int) int {
if x > y {
return x
}
return y
}
func IntSwap(x, y *int) {
*x = *x ^ *y
*y = *x ^ *y
*x = *x ^ *y
}
|
[
0
] |
package main
// 差分
func corpFlightBookings(bookings [][]int, n int) []int {
lenb := len(bookings)
diff := make([]int, n)
for i := 0; i < lenb; i ++ {
// start: bookings[i][0]
// end: bookings[i][1]
start := bookings[i][0] - 1
end := bookings[i][1] - 1
value := bookings[i][2]
diff[start] += value
if end + 1 < n {
diff[end + 1] -= value
}
}
pre := diff[0]
for i := 1; i < n; i ++ {
diff[i] = diff[i] + pre
pre = diff[i]
}
return diff
}
|
[
0
] |
/*
#Time : 2019/5/15 上午10:21
#Author : [email protected]
#File : selectTest.go
#Software : GoLand
*/
package main
import (
"fmt"
"time"
)
var (
Test1 chan string
Test2 = make(chan string)
a = "123"
)
func main() {
// go SendChannel()
// SelectTest()
// fmt.Println(time.Now().UnixNano())
// fmt.Println(time.Now().Unix())
// test2()
// selectChannel()
switchTest(a)
}
func switchTest(a interface{}) {
switch v := a.(type) {
case string:
fmt.Print(v)
}
}
func selectChannel() {
for {
select {
case a := <-Test2:
fmt.Println(a)
return
default:
fmt.Println("==yes===")
time.Sleep(1 * time.Second)
}
}
}
func test2() {
for {
select {
case <-Test2:
fmt.Println(1111)
goto L
default:
time.Sleep(1 * time.Second)
fmt.Println(2222)
}
}
L:
fmt.Println(33333)
}
func SelectTest() {
for {
select {
case <-Test1:
fmt.Println("111111")
case msg := <-Test2:
fmt.Println("222:", msg)
fmt.Println("22222")
goto Loop
default:
fmt.Println("333333")
time.Sleep(1 * time.Second)
}
}
Loop:
fmt.Println("444444444")
}
func SendChannel() {
for {
time.Sleep(5 * time.Second)
fmt.Println("yes")
Test2 <- "yes"
}
}
|
[
7
] |
package crawler
import (
"fmt"
"github.com/gearboxworks/go-status/only"
"github.com/gocolly/colly"
"github.com/gocolly/colly/debug"
"github.com/gocolly/colly/storage"
"github.com/sirupsen/logrus"
"net/http"
"net/url"
"os"
"strings"
"time"
"website-indexer/config"
"website-indexer/global"
"website-indexer/hosters"
"website-indexer/hosters/algolia"
"website-indexer/pages"
"website-indexer/persist"
"website-indexer/util"
)
const (
NoPatternDefined = "No pattern defined in LimitRule"
)
var _ debug.Debugger = (*Debugger)(nil)
type Debugger struct{}
func (me *Debugger) Init() error {
return nil
}
func (me *Debugger) Event(e *debug.Event) {
return
}
type Crawler struct {
*config.Config
Collector *colly.Collector
Host hosters.IndexHoster
Storage persist.Storager
Page *pages.Page
}
func NewCrawler(cfg *config.Config) (c *Crawler) {
for range only.Once {
cc := colly.NewCollector(
colly.CacheDir(cfg.CacheDir),
colly.ParseHTTPErrorResponse(),
colly.AllowedDomains("www."+cfg.Domain, cfg.Domain),
colly.Debugger(&Debugger{}),
)
cc.RedirectHandler = func(req *http.Request, via []*http.Request) error {
return nil
}
c = &Crawler{
Config: cfg,
Collector: cc,
}
fp := persist.GetDbFilepath(cfg)
c.Storage = &persist.Storage{
Config: cfg,
Filename: fp,
}
err := cc.SetStorage(c.Storage.(storage.Storage))
if err != nil {
logrus.Fatalf("Unable to open crawl DB: %s", fp, err)
break
}
err = c.Collector.Limit(&colly.LimitRule{
Delay: 250 * time.Millisecond,
})
if err == nil {
break
}
if err.Error() == NoPatternDefined {
break
}
logrus.Fatalf("Unable to set crawl delay: %s", err)
}
return c
}
func (me *Crawler) HasQueuedUrls() bool {
n, _ := me.Storage.QueueSize()
return n != 0
}
func (me *Crawler) Crawl() *Crawler {
me.Host = algolia.NewAlgolia(me.Config)
me.Collector.OnHTML("*", me.onHtml)
me.Collector.OnRequest(me.onRequest)
me.Collector.OnScraped(me.onScraped)
if !me.HasQueuedUrls() {
me.QueueUrl(me.RootUrl())
}
me.VisitQueued()
return me
}
func (me *Crawler) RootUrl() global.Url {
return fmt.Sprintf("https://www.%s/", me.Config.Domain)
}
func (me *Crawler) Close() {
err := me.Storage.Close()
if err != nil {
logrus.Errorf("unable to close Sqlite storage")
}
}
// AddURL adds a new URL to the queue
func (me *Crawler) AddUrl(URL string) (err error) {
for range only.Once {
var u *url.URL
u, err = url.Parse(URL)
if err != nil {
break
}
if u.Path == "" {
u.Path = "/"
}
r := &colly.Request{
URL: u,
Method: "GET",
}
var b []byte
b, err = r.Marshal()
if err != nil {
break
}
err = me.Storage.AddRequest(b)
if err != nil {
break
}
}
return err
}
func (me *Crawler) QueueUrl(url global.Url) {
err := me.AddUrl(url)
if err != nil {
logrus.Errorf("URL '%s' not added to queue", url)
}
}
func (me *Crawler) VisitQueued() {
var err error
var retries int
for {
if err != nil {
logrus.Errorf("unable to visit queued resources: %s", err)
err = nil
if retries > 3 {
logrus.Fatal("too many errors; terminating")
os.Exit(1)
}
retries++
}
var b []byte
b, err = me.Storage.GetRequest()
if err != nil {
break
}
if b == nil {
break
}
if string(b) == "null" {
logrus.Errorf("request to get queued item returned 'null':", err)
continue
}
var res *persist.Resource
res, err = me.Storage.UnmarshalResource(b)
if err != nil {
continue
}
var u global.Url
u, err = res.Url()
if err == persist.ErrNonIndexableUrl {
_ = me.Storage.DequeueResource(*res)
err = nil
continue
}
if err != nil {
continue
}
err = me.Collector.Visit(u)
if err == nil {
continue
}
if err == colly.ErrAlreadyVisited {
err = nil
continue
}
if err == colly.ErrForbiddenDomain {
err = nil
continue
}
}
if err != nil {
me.Config.OnFailedVisit(err, "", "visiting queued", true)
}
}
func (me *Crawler) onRequest(r *colly.Request) {
fmt.Print("\nVisiting ", r.URL)
me.Page = pages.NewPage(r.URL)
}
func (me *Crawler) onHtml(e *global.HtmlElement) {
for range only.Once {
if me.Page == nil {
logrus.Errorf("page not registered for URL '%s'", e.Request.URL.String())
break
}
if me.HasElementName(e, global.IgnoreElemsType) {
break
}
if me.HasElementName(e, global.CollectElemsType) {
me.Page.AppendElement(e)
}
switch e.Name {
case "a":
me.onA(e)
case "iframe":
me.onIFrame(e)
case "title":
me.onTitle(e)
case "link":
me.onLink(e)
case "meta":
me.onMeta(e)
case "body":
me.onBody(e)
default:
logrus.Warnf("Unhandled HTML element <%s> in %s: %s",
e.Name,
e.Request.URL.String(),
util.StripWhitespace(e.Text),
)
}
}
}
func (me *Crawler) onScraped(r *colly.Response) {
for range only.Once {
p := me.Page
p.Url = r.Request.URL.String()
p.Id = pages.NewHash(p.Url)
if !me.Host.IndexPage(p) {
logrus.Warnf("No attributes collected for %s", p.Url)
break
}
// Reset pause
me.Config.OnErrPause = config.InitialPause
}
}
func (me *Crawler) onLink(e *global.HtmlElement) {
for range only.Once {
if !me.HasElementRel(e, global.LinkElemsType) {
break
}
me.Page.AddHeader(
e.Attr("rel"),
e.Request.AbsoluteURL(e.Attr("href")),
)
}
}
func (me *Crawler) onTitle(e *global.HtmlElement) {
texts := strings.Split(e.Text+"|", "|")
me.Page.Title = strings.TrimSpace(texts[0])
}
func (me *Crawler) onA(e *global.HtmlElement) {
for range only.Once {
u := e.Request.AbsoluteURL(e.Attr("href"))
if !pages.IsIndexable(u) {
break
}
me.requestVisit(u, e)
}
}
func (me *Crawler) onIFrame(e *global.HtmlElement) {
for range only.Once {
u := e.Request.AbsoluteURL(e.Attr("src"))
if !pages.IsIndexable(u) {
break
}
me.requestVisit(u, e)
}
}
func (me *Crawler) onMeta(e *global.HtmlElement) {
for range only.Once {
if !me.HasElementMeta(e) {
break
}
me.Page.AddHeader(
e.Attr(global.MetaName),
e.Attr(global.MetaContent),
)
}
}
func (me *Crawler) onBody(e *global.HtmlElement) {
me.Page.Body = append(
me.Page.Body,
pages.NewElement(e).GetHtml(),
)
}
func (me *Crawler) requestVisit(url global.Url, e *global.HtmlElement) {
for range only.Once {
if !pages.IsIndexable(url) {
break
}
err := me.AddUrl(url)
if err != nil {
switch err.Error() {
case "URL already visited":
case "Forbidden domain":
case "Missing URL":
case "Not Found":
break
default:
logrus.Errorf("On <%s>: %s", e.Name, err)
}
}
}
}
|
[
2
] |
package publisher
import (
"encoding/json"
"log"
"net/http"
"net/url"
"fmt"
"io/ioutil"
"github.com/devopsgig/utilities/src/utilities"
)
const addr = "http://192.168.50.3"
const port = "8080"
// Meta hold the base fields with information for a publisher type
type Meta struct {
UUID string `json:"UUID"`
TaskType string `json:"task"`
}
// Task interface set the contract for publisher types
// which want to implement the publisher.Task interface
type Task interface {
SetUUID(UUID string)
SetTaskType()
GetTaskType() string
}
// Send function receives tasks of type publisher.Task,
// send them to the respective endpoint in the REST API
// and transmit the server response through the response channel
func Send(task Task, respCh chan string) {
// Get new UUID
UUID, err := utilities.UUID()
if err != nil {
log.Fatal(err)
}
// Set UUID to task
task.SetUUID(UUID)
// Parse task to JSON format
taskJSON, err := json.Marshal(task)
if err != nil {
log.Fatal(err)
}
// Get the url endpoint for the task type
endpoint, err := endpoint(task.GetTaskType())
if err != nil {
log.Fatal(err)
}
// Form the URL
URL := fmt.Sprintf("%s:%s/%s", addr, port, endpoint)
// Send task in json format as POST request to REST API
data := url.Values{"task": []string{string(taskJSON)}}
// POST request
resp, err := http.PostForm(URL, data)
if err != nil {
log.Fatal(err)
}
// Read the server response
result, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// Send the result back to the caller
respCh <- string(result)
}
// endpoint returns the endpoint for the taskType
func endpoint(taskType string) (string, error) {
switch taskType {
case "arithmetic":
return "arith", nil
}
return "", fmt.Errorf("Task %s is not supported", taskType)
}
|
[
7
] |
package controllers
import (
"blog/internal/core"
"github.com/gin-gonic/gin"
"io"
"net/http"
"os"
"path"
"strconv"
"strings"
"time"
)
func UEditor(c *gin.Context) {
action := c.Query("action")
switch action {
case "config":
c.Header("Content-type", "application/json; charset=utf-8")
c.String(200, CONFIG_JSON)
return
case "uploadimage":
c.Header("Content-type", "application/json; charset=utf-8")
result := upload(core.RootPath+"web/statics/ueditor/upload/image/", c.Request)
result["url"] = "/static" + strings.TrimPrefix(result["url"], core.RootPath+"web/statics")
c.JSON(200, result)
return
}
}
func newFileName() string {
var now = time.Now()
var fileName = now.Format("200601021504")
fileName = fileName + strconv.Itoa(now.Nanosecond())
return fileName
}
func upload(pathString string, request *http.Request) map[string]string {
var file, header, err = request.FormFile("upfile")
if err != nil {
panic(err)
}
defer file.Close()
var filename = newFileName() + path.Ext(header.Filename)
err = os.MkdirAll(pathString, 0775)
if err != nil {
panic(err)
}
targetFile, err := os.Create(path.Join(pathString, filename))
if err != nil {
panic(err)
}
defer targetFile.Close()
io.Copy(targetFile, file)
return map[string]string{
"url": pathString + filename,
"title": "",
"original": header.Filename,
"state": "SUCCESS",
}
}
const CONFIG_JSON = `{
"imageActionName": "uploadimage",
"imageUrlPrefix": "",
"imageFieldName": "upfile",
"imageMaxSize": 20480000,
"imageAllowFiles": [
".png",
".jpg",
".jpeg",
".gif",
".bmp"
],
"imageManagerActionName": "listimage",
"imageManagerListSize": 20,
"imageManagerUrlPrefix": "",
"imageManagerInsertAlign": "none",
"imageManagerAllowFiles": [
".png",
".jpg",
".jpeg",
".gif",
".bmp"
],
"fileActionName": "uploadfile",
"fileFieldName": "upfile",
"fileUrlPrefix": "",
"fileMaxSize": 51200000,
"fileAllowFiles": [
".png",
".jpg",
".jpeg",
".gif",
".bmp",
".flv",
".swf",
".mkv",
".avi",
".rm",
".rmvb",
".mpeg",
".mpg",
".ogg",
".ogv",
".mov",
".wmv",
".mp4",
".webm",
".mp3",
".wav",
".mid",
".rar",
".zip",
".tar",
".gz",
".7z",
".bz2",
".cab",
".iso",
".doc",
".docx",
".xls",
".xlsx",
".ppt",
".pptx",
".pdf",
".txt",
".md",
".xml"
],
"fileManagerActionName": "listfile",
"fileManagerUrlPrefix": "",
"fileManagerListSize": 20,
"fileManagerAllowFiles": [
".png",
".jpg",
".jpeg",
".gif",
".bmp",
".flv",
".swf",
".mkv",
".avi",
".rm",
".rmvb",
".mpeg",
".mpg",
".ogg",
".ogv",
".mov",
".wmv",
".mp4",
".webm",
".mp3",
".wav",
".mid",
".rar",
".zip",
".tar",
".gz",
".7z",
".bz2",
".cab",
".iso",
".doc",
".docx",
".xls",
".xlsx",
".ppt",
".pptx",
".pdf",
".txt",
".md",
".xml"
]
}
`
|
[
0
] |
// Copyright 2017 Google Inc. 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 directory
import (
"context"
"database/sql"
"testing"
"time"
"github.com/golang/protobuf/proto"
"github.com/google/go-cmp/cmp"
"github.com/google/keytransparency/core/directory"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/google/trillian/crypto/keyspb"
_ "github.com/mattn/go-sqlite3"
)
func newStorage(t *testing.T) (s directory.Storage, close func()) {
t.Helper()
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
t.Fatalf("sql.Open(): %v", err)
}
closeFunc := func() { db.Close() }
s, err = NewStorage(db)
if err != nil {
closeFunc()
t.Fatalf("Failed to create adminstorage: %v", err)
}
return s, closeFunc
}
func TestList(t *testing.T) {
ctx := context.Background()
s, closeF := newStorage(t)
defer closeF()
for _, tc := range []struct {
directories []*directory.Directory
readDeleted bool
}{
{
directories: []*directory.Directory{
{
DirectoryID: "directory1",
MapID: 1,
LogID: 2,
VRF: &keyspb.PublicKey{Der: []byte("pubkeybytes")},
VRFPriv: &keyspb.PrivateKey{Der: []byte("privkeybytes")},
MinInterval: 1 * time.Second,
MaxInterval: 5 * time.Second,
},
{
DirectoryID: "directory2",
MapID: 1,
LogID: 2,
VRF: &keyspb.PublicKey{Der: []byte("pubkeybytes")},
VRFPriv: &keyspb.PrivateKey{Der: []byte("privkeybytes")},
MinInterval: 5 * time.Hour,
MaxInterval: 500 * time.Hour,
},
},
},
} {
for _, d := range tc.directories {
if err := s.Write(ctx, d); err != nil {
t.Errorf("Write(): %v", err)
continue
}
}
directories, err := s.List(ctx, tc.readDeleted)
if err != nil {
t.Errorf("List(): %v", err)
continue
}
if got, want := directories, tc.directories; !cmp.Equal(got, want, cmp.Comparer(proto.Equal)) {
t.Errorf("List(): %#v, want %#v, diff: \n%v", got, want, cmp.Diff(got, want))
}
}
}
func TestWriteReadDelete(t *testing.T) {
ctx := context.Background()
s, closeF := newStorage(t)
defer closeF()
for _, tc := range []struct {
desc string
d directory.Directory
write bool
wantWriteErr bool
setDelete, isDeleted bool
readDeleted bool
wantReadErr bool
}{
{
desc: "Success",
write: true,
d: directory.Directory{
DirectoryID: "testdirectory",
MapID: 1,
LogID: 2,
VRF: &keyspb.PublicKey{Der: []byte("pubkeybytes")},
VRFPriv: &keyspb.PrivateKey{Der: []byte("privkeybytes")},
MinInterval: 1 * time.Second,
MaxInterval: 5 * time.Second,
},
},
{
desc: "Duplicate DirectoryID",
write: true,
d: directory.Directory{
DirectoryID: "testdirectory",
MapID: 1,
LogID: 2,
VRF: &keyspb.PublicKey{Der: []byte("pubkeybytes")},
VRFPriv: &keyspb.PrivateKey{Der: []byte("privkeybytes")},
MinInterval: 1 * time.Second,
MaxInterval: 5 * time.Second,
},
wantWriteErr: true,
},
{
desc: "Delete",
d: directory.Directory{
DirectoryID: "testdirectory",
MapID: 1,
LogID: 2,
VRF: &keyspb.PublicKey{Der: []byte("pubkeybytes")},
VRFPriv: &keyspb.PrivateKey{Der: []byte("privkeybytes")},
MinInterval: 1 * time.Second,
MaxInterval: 5 * time.Second,
},
setDelete: true,
isDeleted: true,
readDeleted: false,
wantReadErr: true,
},
{
desc: "Read deleted",
d: directory.Directory{
DirectoryID: "testdirectory",
MapID: 1,
LogID: 2,
VRF: &keyspb.PublicKey{Der: []byte("pubkeybytes")},
VRFPriv: &keyspb.PrivateKey{Der: []byte("privkeybytes")},
MinInterval: 1 * time.Second,
MaxInterval: 5 * time.Second,
},
setDelete: true,
isDeleted: true,
readDeleted: true,
wantReadErr: false,
},
{
desc: "Undelete",
d: directory.Directory{
DirectoryID: "testdirectory",
MapID: 1,
LogID: 2,
VRF: &keyspb.PublicKey{Der: []byte("pubkeybytes")},
VRFPriv: &keyspb.PrivateKey{Der: []byte("privkeybytes")},
MinInterval: 1 * time.Second,
MaxInterval: 5 * time.Second,
},
setDelete: true,
isDeleted: false,
readDeleted: false,
wantReadErr: false,
},
} {
t.Run(tc.desc, func(t *testing.T) {
if tc.write {
err := s.Write(ctx, &tc.d)
if got, want := err != nil, tc.wantWriteErr; got != want {
t.Errorf("Write(): %v, want err: %v", err, want)
return
}
if err != nil {
return
}
}
if tc.setDelete {
tc.d.DeletedTimestamp = time.Now().Truncate(time.Second)
tc.d.Deleted = tc.isDeleted
if err := s.SetDelete(ctx, tc.d.DirectoryID, tc.isDeleted); err != nil {
t.Errorf("SetDelete(%v, %v): %v", tc.d.DirectoryID, tc.isDeleted, err)
return
}
}
directory, err := s.Read(ctx, tc.d.DirectoryID, tc.readDeleted)
if got, want := err != nil, tc.wantReadErr; got != want {
t.Errorf("Read(): %v, want err: %v", err, want)
}
if err != nil {
return
}
if got, want := *directory, tc.d; !cmp.Equal(got, want, cmp.Comparer(proto.Equal)) {
t.Errorf("Read(%v, %v): %#v, want %#v, diff: \n%v",
tc.d.DirectoryID, tc.readDeleted, got, want, cmp.Diff(got, want))
}
})
}
}
func TestDelete(t *testing.T) {
ctx := context.Background()
s, closeF := newStorage(t)
defer closeF()
for _, tc := range []struct {
directoryID string
}{
{directoryID: "test"},
} {
d := &directory.Directory{
DirectoryID: tc.directoryID,
VRF: &keyspb.PublicKey{Der: []byte("pubkeybytes")},
VRFPriv: &keyspb.PrivateKey{Der: []byte("privkeybytes")},
}
if err := s.Write(ctx, d); err != nil {
t.Errorf("Write(): %v", err)
}
if err := s.Delete(ctx, tc.directoryID); err != nil {
t.Errorf("Delete(): %v", err)
}
_, err := s.Read(ctx, tc.directoryID, true)
if got, want := status.Code(err), codes.NotFound; got != want {
t.Errorf("Read(): %v, wanted %v", got, want)
}
_, err = s.Read(ctx, tc.directoryID, false)
if got, want := status.Code(err), codes.NotFound; got != want {
t.Errorf("Read(): %v, wanted %v", got, want)
}
}
}
|
[
1
] |
package ts
import (
"testing"
"time"
)
func TestParseTf(t *testing.T) {
tf, err := ParseTf("4h")
if err != nil {
t.Error(err)
}
if tf.Unit != TfHour || tf.N != 4 {
t.Errorf("unexpected values 4h")
}
tf, err = ParseTf("m")
if err != nil {
t.Error(err)
}
if tf.Unit != TfMinute || tf.N != 1 {
t.Errorf("unexpected values m")
}
}
func TestTimeframe_IsValid(t *testing.T) {
tf := Timeframe{
N: 2,
Unit: TfHour,
}
if !tf.IsValid() {
t.Errorf("h4 should be valid")
}
tf.Unit = "fail"
if tf.IsValid() {
t.Error("tf shouldnt be valid")
}
}
func TestDurationToTf(t *testing.T) {
tf, err := DurationToTf(time.Second)
if err == nil {
t.Errorf("expected error for < 1m")
}
tf, err = DurationToTf(time.Minute + time.Second)
if err == nil {
t.Errorf("expected error for not modulo minute")
}
tf, err = DurationToTf(time.Hour * 48)
if err != nil {
t.Errorf("2 day duration should be valid")
} else {
if tf.Unit != TfDay || tf.N != 2 {
t.Errorf("unexpected value for 48h")
}
}
}
|
[
4
] |
package driverin
import (
"bufio"
"flag"
"fmt"
"gophercise1/app/quiz"
"log"
"os"
"strings"
)
type CLIAdapter struct {
Quiz quiz.Port
}
func NewCLIAdapter(quiz quiz.Port) *CLIAdapter {
return &CLIAdapter{
Quiz: quiz,
}
}
func (C *CLIAdapter) Run() {
var fileLocation string
var timeLimit int
parseFlags(&fileLocation, &timeLimit)
err := C.Quiz.Setup(fileLocation)
if err != nil {
log.Fatal(err)
}
questionCh := C.Quiz.Questions()
timesUp := C.Quiz.StartTimer(timeLimit)
scanner := bufio.NewReader(os.Stdin)
for question := range questionCh {
answerCh := make(chan bool)
go func() {
fmt.Printf("%v) %v : ", question.QuestionNumber, question.Question)
str, _ := scanner.ReadString('\n')
answerCh <- strings.TrimSpace(str) == question.Answer
}()
select {
case <-timesUp:
fmt.Printf("\nYou got %v out of %v right.\n", C.Quiz.Score(), C.Quiz.NumOfQuestions())
return
case isCorrect := <-answerCh:
if isCorrect {
C.Quiz.IncrementScore()
}
}
}
fmt.Printf("You got %v out of %v right.\n", C.Quiz.Score(), C.Quiz.NumOfQuestions())
}
func parseFlags(fileLocation *string, timeLimit *int) {
flag.StringVar(fileLocation, "fileLocation", "problems.csv", "location of the csv file")
flag.IntVar(timeLimit, "timeLimit", 30, "time limit of quiz")
flag.Parse()
}
|
[
2
] |
// File deduplication
package main
import (
"bufio"
"flag"
"fmt"
"os"
"strconv"
"strings"
)
// Return value of promptKeep()
const (
// Keep the first one and remove the rest.
PROMPT_ANSWER_YES = iota
// Do not remove duplicated files this time,
// will prompt again when duplication happens next time.
PROMPT_ANSWER_SKIP
// Do not prompt again and remove all duplicated files.
PROMPT_ANSWER_CONTINUE
// Abort program.
PROMPT_ANSWER_QUIT
)
func usage() {
fmt.Println("Copyright 2015 (C) Alex Jin ([email protected])")
fmt.Println("Remove duplicated files from your system.")
fmt.Println()
fmt.Println("Usage: dedup [-v] [-f] [-l] [-i <TYPE>,...] [-e <TYPE>,...] [-p <POLICY>,...] <path>...")
fmt.Println()
fmt.Println("Options and Arguments:")
fmt.Println(" -v: Verbose mode.")
fmt.Println(" -f: Do not prompt before removing each duplicated file.")
fmt.Println(" -l: List duplicated files only, do not remove them.")
fmt.Println(" -i: Include filters (Scan & remove specified files only).")
fmt.Println(" -e: Exclude filters (Do NOT scan & remove specified files).")
fmt.Println(" -p: When duplication happens, which file will be removed.")
fmt.Println()
fmt.Println("-i <TYPE>, -e <TYPE>:")
fmt.Println(" audio: Audio files.")
fmt.Println(" office: Microsoft Office documents.")
fmt.Println(" photo: Photo (picture) files.")
fmt.Println(" video: Video files.")
fmt.Println(" package: Tarball, compressed, ISO, installation packages, etc.")
fmt.Println()
fmt.Println(" Remark: If both include and exclude filters are not set,")
fmt.Println(" then all files will be scanned.")
fmt.Println()
fmt.Println("-p <POLICY>:")
fmt.Println(" longname: Remove duplicated files with longer file name.")
fmt.Println(" shortname: Remove duplicated files with shorter file name.")
fmt.Println(" longpath: Remove duplicated files with longer full path.")
fmt.Println(" shortpath: Remove duplicated files with shorter full path.")
fmt.Println(" new: Remove duplicated files with newer last modification time.")
fmt.Println(" old: Remove duplicated files with older last modification time.")
fmt.Println()
fmt.Println(" Remark: If \"-p <POLICY>\" is not set, then default policy")
fmt.Println(" \"longname,longpath,new\" will be used.")
fmt.Println()
fmt.Println("Examples:")
fmt.Println(" > dedup -l d:\\data e:\\data")
fmt.Println(" List duplicated files.")
fmt.Println()
fmt.Println(" > dedup -i photo,video d:\\data e:\\data")
fmt.Println(" Remove duplicated photo & video.")
fmt.Println()
}
// Input paths might be relative and duplicated,
// we need to convert to absolute paths and remove duplicated.
func getAbsUniquePaths(paths []string) ([]string, error) {
// For storing unique paths.
uniquePaths := make([]string, 0, len(paths))
for _, path := range paths {
// First, convert to absolute path.
abs, err := GetAbsPath(path)
if len(abs) == 0 && err == nil {
err = ErrRootPathNotPermitted
}
if err != nil {
fmt.Fprintf(os.Stderr, "Invalid argument %v (%v)\n", path, err)
return nil, err
}
// Second, check if it's parent (or child) folder
// of a path in the array.
var i int
for i = 0; i < len(uniquePaths); i++ {
if SameOrIsChild(uniquePaths[i], abs) {
break
} else if SameOrIsChild(abs, uniquePaths[i]) {
uniquePaths[i] = abs
break
}
}
if i == len(uniquePaths) {
if _, err := os.Stat(abs); err != nil {
fmt.Fprintf(os.Stderr, "%v (%v)", err, path)
return nil, err
}
uniquePaths = append(uniquePaths, abs)
}
}
return uniquePaths, nil
}
func showDuplicatedFiles(files []*FileAttr) {
fmt.Printf("* 1) %v\n", files[0].Path)
for i := 1; i < len(files); i++ {
fmt.Printf(" %v) %v\n", i+1, files[i].Path)
}
}
// Return value is PROMPT_ANSWER_???
//
// Note that this function might modify input slice "files".
// If return value is PROMPT_ANSWER_YES or PROMPT_ANSWER_CONTINUE,
// the first file of slice "files" needs to keep and the rest
// of files could be removed.
func promptKeep(files []*FileAttr) int {
// Create a buffered reader.
reader := bufio.NewReader(os.Stdin)
for {
// Print duplicated files.
showDuplicatedFiles(files)
fmt.Printf("Which file do you want to keep? (1-%v,Skip,Continue,Quit):", len(files))
if line, _, err := reader.ReadLine(); err == nil {
cmd := strings.ToLower(string(line))
switch cmd {
case "s", "skip":
return PROMPT_ANSWER_SKIP
case "c", "continue":
return PROMPT_ANSWER_CONTINUE
case "q", "quit":
return PROMPT_ANSWER_QUIT
default:
if len(line) > 0 {
index, err := strconv.Atoi(cmd)
if err != nil || index < 1 || index > len(files) {
fmt.Fprintf(os.Stderr, "Invalid Command: %v\n\n", string(line))
} else {
if index != 1 {
tmp := files[0]
files[0] = files[index-1]
files[index-1] = tmp
}
return PROMPT_ANSWER_YES
}
} else {
fmt.Println()
}
}
}
}
}
func main_i() int {
var verbose bool
var force bool
var list bool
var includes string
var excludes string
var policySpec string
// Parse command line options.
flag.BoolVar(&verbose, "v", false, "Verbose mode.")
flag.BoolVar(&force, "f", false, "Do not prompt before removing files.")
flag.BoolVar(&list, "l", false, "List duplicated files only, do not remove them.")
flag.StringVar(&includes, "i", "", "Include filters.")
flag.StringVar(&excludes, "e", "", "Exclude filters.")
flag.StringVar(&policySpec, "p", "", "When duplication happens, which file will be removed.")
flag.Parse()
// If argument is missing, then exit.
if flag.NArg() == 0 {
usage()
return 1
}
// Create policy object to determine
// which file to delete when duplication happens.
policy, err := NewPolicy(policySpec)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
return 1
}
// Create filter object.
filter, err := NewFilter(includes, excludes)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
return 1
}
// Convert input paths to absolute.
paths, err := getAbsUniquePaths(flag.Args())
if err != nil {
return 1
}
// Create status updater.
updater := NewUpdater(verbose)
// Create file scanner.
scanner := NewFileScanner(paths, filter, updater)
// Ignore error because cache is not very important.
scanner.ReadCache()
// Scan files.
if err := scanner.Scan(); err != nil {
return 1
}
// Result variables
var deletedFiles int = 0
var deletedBytes int64 = 0
var first_duplication = true
// Iterate all scanned files.
for _, item := range scanner.GetScannedFiles() {
// If no duplicated files, then skip.
if len(item) <= 1 {
continue
}
if first_duplication {
first_duplication = false
updater.Log(LOG_INFO, "<Duplicated Files>")
} else {
if !list && !force {
updater.Log(LOG_INFO, "")
}
}
// Once returned, item[0] needs to keep
// and the rest could be removed.
policy.Sort(item)
if list {
showDuplicatedFiles(item)
deletedFiles += len(item) - 1
for i := 1; i < len(item); i++ {
deletedBytes += item[i].Size
}
} else {
if !force {
// Prompt before remove file.
if result := promptKeep(item); result == PROMPT_ANSWER_SKIP {
continue
} else if result == PROMPT_ANSWER_QUIT {
scanner.SaveCache()
return 1
} else if result == PROMPT_ANSWER_CONTINUE {
force = true
}
}
// Delete duplicated files, range [1,len).
for i := 1; i < len(item); i++ {
if err := os.Remove(item[i].Path); err != nil {
updater.IncreaseErrors()
updater.Log(LOG_ERROR, "Could not delete file %v (%v).",
item[i].Path, err)
continue
}
// Write log and update file count.
updater.Log(LOG_INFO, "%v was deleted.", item[i].Path)
deletedBytes += item[i].Size
deletedFiles++
// Update cache file.
scanner.OnFileRemoved(item[i])
}
}
}
// Update local cache.
scanner.SaveCache()
if deletedFiles > 0 {
updater.Log(LOG_INFO, "")
}
updater.Log(LOG_INFO, "<Summary>")
updater.Log(LOG_INFO, "Total Files: %v", scanner.GetTotalFiles())
updater.Log(LOG_INFO, "Total Folders: %v", scanner.GetTotalFolders())
updater.Log(LOG_INFO, "Total Size: %.3f MB", float64(scanner.GetTotalBytes())/(1024*1024))
if list {
updater.Log(LOG_INFO, "Duplicated Files: %v", deletedFiles)
updater.Log(LOG_INFO, "Duplicated Size: %.3f MB", float64(deletedBytes)/(1024*1024))
} else {
updater.Log(LOG_INFO, "Deleted Files: %v", deletedFiles)
updater.Log(LOG_INFO, "Deleted Size: %.3f MB", float64(deletedBytes)/(1024*1024))
}
if updater.Errors() > 0 {
updater.Log(LOG_INFO, "Errors: %v", updater.Errors())
}
return 0
}
func main() {
result := main_i()
os.Exit(result)
}
|
[
4
] |
package radix
import (
"crypto/rand"
"fmt"
"reflect"
"testing"
)
// generateUUID is used to generate a random UUID
func generateUUID() string {
buf := make([]byte, 16)
if _, err := rand.Read(buf); err != nil {
panic(fmt.Errorf("failed to read random bytes: %v", err))
}
return fmt.Sprintf("%08x-%04x-%04x-%04x-%12x",
buf[0:4],
buf[4:6],
buf[6:8],
buf[8:10],
buf[10:16])
}
func TestRadix(t *testing.T) {
var min, max string
inp := make(map[string]int)
for i := 0; i < 1000; i++ {
gen := generateUUID()
inp[gen] = i
if gen < min || i == 0 {
min = gen
}
if gen > max || i == 0 {
max = gen
}
}
r := NewFromMap(inp)
if r.Len() != len(inp) {
t.Fatalf("bad length: %v %v", r.Len(), len(inp))
}
// Check min and max
outMin, _, _ := r.Minimum()
if string(outMin) != min {
t.Fatalf("bad minimum: %s %v", outMin, min)
}
outMax, _, _ := r.Maximum()
if string(outMax) != max {
t.Fatalf("bad maximum: %s %v", outMax, max)
}
for k, v := range inp {
out, ok := r.Get([]byte(k))
if !ok {
t.Fatalf("missing key: %v", k)
}
if out != v {
t.Fatalf("value mis-match: %v %v", out, v)
}
}
}
func TestDeletePrefix(t *testing.T) {
type exp struct {
inp []string
prefix string
out []string
numDeleted int
}
cases := []exp{
{[]string{"", "A", "AB", "ABC", "R", "S"}, "A", []string{"", "R", "S"}, 3},
{[]string{"", "A", "AB", "ABC", "R", "S"}, "ABC", []string{"", "A", "AB", "R", "S"}, 1},
{[]string{"", "A", "AB", "ABC", "R", "S"}, "", []string{}, 6},
{[]string{"", "A", "AB", "ABC", "R", "S"}, "S", []string{"", "A", "AB", "ABC", "R"}, 1},
{[]string{"", "A", "AB", "ABC", "R", "S"}, "SS", []string{"", "A", "AB", "ABC", "R", "S"}, 0},
}
for _, test := range cases {
r := New()
for _, ss := range test.inp {
r.Insert([]byte(ss), 1)
}
deleted := r.DeletePrefix([]byte(test.prefix))
if deleted != test.numDeleted {
t.Fatalf("Bad delete, expected %v to be deleted but got %v", test.numDeleted, deleted)
}
out := []string{}
fn := func(s []byte, v int) bool {
out = append(out, string(s))
return false
}
recursiveWalk(r.root, fn)
if !reflect.DeepEqual(out, test.out) {
t.Fatalf("mis-match: %v %v", out, test.out)
}
}
}
func TestInsert_Duplicate(t *testing.T) {
r := New()
vv, ok := r.Insert([]byte("cpu"), 1)
if vv != 1 {
t.Fatalf("value mismatch: got %v, exp %v", vv, 1)
}
if !ok {
t.Fatalf("value mismatch: got %v, exp %v", ok, true)
}
// Insert a dup with a different type should fail
vv, ok = r.Insert([]byte("cpu"), 2)
if vv != 1 {
t.Fatalf("value mismatch: got %v, exp %v", vv, 1)
}
if ok {
t.Fatalf("value mismatch: got %v, exp %v", ok, false)
}
}
//
// benchmarks
//
func BenchmarkTree_Insert(b *testing.B) {
t := New()
keys := make([][]byte, 0, 10000)
for i := 0; i < cap(keys); i++ {
k := []byte(fmt.Sprintf("cpu,host=%d", i))
if v, ok := t.Insert(k, 1); v != 1 || !ok {
b.Fatalf("insert failed: %v != 1 || !%v", v, ok)
}
keys = append(keys, k)
}
b.SetBytes(int64(len(keys)))
b.ReportAllocs()
b.ResetTimer()
for j := 0; j < b.N; j++ {
for _, key := range keys {
if v, ok := t.Insert(key, 1); v != 1 || ok {
b.Fatalf("insert failed: %v != 1 || !%v", v, ok)
}
}
}
}
func BenchmarkTree_InsertNew(b *testing.B) {
keys := make([][]byte, 0, 10000)
for i := 0; i < cap(keys); i++ {
k := []byte(fmt.Sprintf("cpu,host=%d", i))
keys = append(keys, k)
}
b.SetBytes(int64(len(keys)))
b.ReportAllocs()
b.ResetTimer()
for j := 0; j < b.N; j++ {
t := New()
for _, key := range keys {
t.Insert(key, 1)
}
}
}
|
[
1
] |
package dfs_bfs
import "github.com/leetcodeProblem/data"
// Given the root of a Binary Search Tree (BST), convert it to a Greater Tree
// such that every key of the original BST is changed to the original key plus
// sum of all keys greater than the original key in BST.
// As a reminder, a binary search tree is a tree that satisfies these constraints:
// The left subtree of a node contains only nodes with keys less than the node's key.
// The right subtree of a node contains only nodes with keys greater than the node's key.
// Both the left and right subtrees must also be binary search trees.
// Note: This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/
// Example 1:
// Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
// Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
// Example 2:
// Input: root = [0,null,1]
// Output: [1,null,1]
// Example 3:
// Input: root = [1,0,2]
// Output: [3,3,2]
// Example 4:
// Input: root = [3,2,4,1]
// Output: [7,9,4,10]
// Constraints:
// The number of nodes in the tree is in the range [0, 104].
// -104 <= Node.val <= 104
// All the values in the tree are unique.
// root is guaranteed to be a valid binary search tree.
func convertBST(root *data.TreeNode) *data.TreeNode {
sum := 0
dfs538(root, &sum)
return root
}
func dfs538(node *data.TreeNode, sum *int) {
if node == nil {
return
}
dfs538(node.Right, sum)
*sum = *sum + node.Val
node.Val = *sum
dfs538(node.Left, sum)
}
|
[
0
] |
package src
import "unicode"
/*
784. 字母大小写全排列
示例:
输入: S = "a1b2"
输出: ["a1b2", "a1B2", "A1b2", "A1B2"]
s[k+1]= s[k]+A & a[k]+a
*/
func letterCasePermutation(S string) []string {
var res []string
for _, i := range S {
if unicode.IsLetter(i) {
var temp []string
if res != nil {
for j := 0; j < len(res); j++ {
temp = append(temp, res[j]+string(unicode.ToLower(i)))
temp = append(temp, res[j]+string(unicode.ToUpper(i)))
}
} else {
temp = append(temp, string(unicode.ToLower(i)))
temp = append(temp, string(unicode.ToUpper(i)))
}
res = temp
} else {
if res != nil {
for j := 0; j < len(res); j++ {
res[j] += string(i)
}
} else {
res = append(res, string(i))
}
}
}
return res
}
|
[
2
] |
// Package static implements a simple static registry
// backend which uses statically configured routes.
package static
import (
"encoding/json"
"git.inke.cn/tpc/inf/go-upstream/config"
"git.inke.cn/tpc/inf/go-upstream/registry"
)
type be struct {
clusters []*registry.Cluster
}
func NewBackend(routes string) (registry.Backend, error) {
b := be{}
err := json.Unmarshal([]byte(routes), &(b.clusters))
return &b, err
}
func (b *be) Register(*config.Register) error {
return nil
}
func (b *be) Deregister(*config.Register) error {
return nil
}
func (b *be) OverrideTags([]string) {
}
func (b *be) ReadManual(KVPath string) (value string, version uint64, err error) {
return "", 0, nil
}
func (b *be) WriteManual(KVPath, value string, version uint64) (ok bool, err error) {
return false, nil
}
// func (b *be) WatchServices() chan string {
func (b *be) WatchServices(name string, status []string, dc string) chan []*registry.Cluster {
ch := make(chan []*registry.Cluster, 1)
ch <- b.clusters
return ch
}
func (b *be) WatchManual(KVPath string) chan string {
return make(chan string)
}
func (b *be) WatchPrefixManual(KVPath string) chan map[string]string {
return make(chan map[string]string)
}
|
[
2
] |
package pgsql
import (
"fmt"
"log"
"strings"
schema "github.com/davidwalter0/go-persist/schema"
"database/sql"
_ "github.com/lib/pq"
)
var debugging = false
func checkErr(err error) {
if err != nil {
log.Println(err)
panic(err)
}
}
// Connect using driver and database name
func Connect(driver, db string) *sql.DB {
DB, err := sql.Open(driver, db)
checkErr(err)
return DB
}
// Schema given that permissions grant table configuration, initialize the
// current database tables for this project.
var Schema = schema.DBSchema{
"pages": schema.SchemaText{
`CREATE TABLE pages (
id serial primary key,
page_guid varchar(256) NOT NULL DEFAULT '' unique,
page_title varchar(256) DEFAULT NULL,
page_content text,
page_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP)`,
`CREATE OR REPLACE FUNCTION update_page_date_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.page_date = now();
RETURN NEW;
END;
$$ language 'plpgsql'`,
`CREATE TRIGGER update_ab_changetimestamp
BEFORE UPDATE ON pages
FOR EACH ROW EXECUTE PROCEDURE update_page_date_column()`,
},
"comments": schema.SchemaText{
`CREATE TABLE comments (
id serial primary key,
page_id int,
comment_guid varchar(256) DEFAULT NULL,
comment_name varchar(64) DEFAULT NULL,
comment_email varchar(128) DEFAULT NULL,
comment_text text,
comment_date timestamp NULL DEFAULT CURRENT_TIMESTAMP)`,
`CREATE OR REPLACE FUNCTION update_comments_date_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.comment_date = now();
RETURN NEW;
END;
$$ language 'plpgsql'`,
`CREATE TRIGGER update_comments_changetimestamp
BEFORE UPDATE ON comments
FOR EACH ROW EXECUTE PROCEDURE update_page_date_column()`,
},
"users": schema.SchemaText{
`CREATE TABLE users (
id serial primary key,
user_name varchar(32) NOT NULL DEFAULT '',
user_guid varchar(256) NOT NULL DEFAULT '',
user_email varchar(128) NOT NULL DEFAULT '',
user_password varchar(128) NOT NULL DEFAULT '',
user_salt varchar(128) NOT NULL DEFAULT '',
user_joined_timestamp timestamp NULL DEFAULT NULL)`,
`CREATE OR REPLACE FUNCTION update_comments_date_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.comment_date = now();
RETURN NEW;
END;
$$ language 'plpgsql';
`,
`CREATE TRIGGER update_comments_changetimestamp
BEFORE UPDATE ON comments
FOR EACH ROW EXECUTE PROCEDURE update_comments_date_column()`,
},
"sessions": schema.SchemaText{
`CREATE TABLE sessions (
id serial primary key,
session_id varchar(256) NOT NULL unique,
user_id int DEFAULT NULL,
session_start timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
session_update timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
session_active int NOT NULL)`,
`CREATE OR REPLACE FUNCTION update_sessions_start_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.session_start = now();
RETURN NEW;
END;
$$ language 'plpgsql'`,
`CREATE TRIGGER update_sessions_changetimestamp
BEFORE UPDATE ON sessions
FOR EACH ROW EXECUTE PROCEDURE update_sessions_start_column()`,
},
}
// DropAll remove the tables in this schema
func DropAll(db *sql.DB, Schema schema.DBSchema) {
for table := range Schema {
if debugging {
fmt.Println("DROP TABLE", table)
}
_, err := db.Exec(fmt.Sprintf(`DROP TABLE %s cascade;`, table))
if err != nil && strings.Index(fmt.Sprintf("%v", err), "does not exist") == -1 {
panic(fmt.Sprintf("%v", err))
}
}
}
// Initialize a database from the given schema, the create operation
// is idempotent, and can be called multiple times without issues, if
// DropAll is false. Assumes that the uid running the process has
// given that permissions granted for table configuration, initialize
// the current database tables for this project.
func Initialize(db *sql.DB, Schema schema.DBSchema) {
for table, schema := range Schema {
// fmt.Println(db.QueryRow(`DROP TABLE pages cascade;`))
for _, scheme := range schema {
if debugging {
fmt.Printf("\ndb.QueryRow: %s:\n%s\n", table, scheme)
}
_, err := db.Exec(scheme)
if err != nil {
panic(fmt.Sprintf("%v", err))
}
}
}
}
|
[
2
] |
package models
type TopicModel struct {
}
type TopicData struct {
Id int
Topic string
Class string
Function string
}
func (Topic *TopicModel) GetAll() {
rows, err := DB.Query("SELECT * FROM " + Topic.GetTable())
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
}
}
func (Topic *TopicModel) GetTable() string {
return "topic"
}
func (Topic *TopicModel) Insert(data *TopicData) int64 {
stmt, err := DB.Prepare("INSERT INTO " + Topic.GetTable() + "VALUES(?, ?, ?)")
if err != nil {
panic(err)
}
defer stmt.Close()
result, err := stmt.Exec(data.Topic, data.Class, data.Function)
if err != nil {
panic(err)
}
lastId, err := result.LastInsertId()
if err != nil {
panic(err)
}
return lastId
}
func (topic *TopicModel) GetListByChannel(channel string) []TopicData {
topicSubscribeList := []TopicData{}
rows, _ := DB.Query("SELECT * FROM " + topic.GetTable() + " WHERE topic = ?", channel)
defer rows.Close()
for rows.Next() {
var tmp TopicData
rows.Scan(&tmp.Id, &tmp.Topic, &tmp.Class, &tmp.Function)
topicSubscribeList = append(topicSubscribeList, tmp)
}
if len(topicSubscribeList) != 0 {
return topicSubscribeList
}
return []TopicData{}
}
|
[
2
] |
package wechat
import (
"fmt"
"log"
"time"
"github.com/esap/wechat/util"
)
// FetchDelay 默认5分钟同步一次
var FetchDelay time.Duration = 5 * time.Minute
// AccessToken 回复体
type AccessToken struct {
AccessToken string `json:"access_token"`
ExpiresIn int64 `json:"expires_in"`
WxErr
}
// GetAccessToken 读取AccessToken
func (s *Server) GetAccessToken() string {
s.Lock()
defer s.Unlock()
var err error
if s.AccessToken == nil || s.AccessToken.ExpiresIn < time.Now().Unix() {
for i := 0; i < 3; i++ {
err = s.getAccessToken()
if err == nil {
break
}
log.Printf("GetAccessToken[%v] %v", s.AgentId, err)
time.Sleep(time.Second)
}
if err != nil {
return ""
}
}
return s.AccessToken.AccessToken
}
// GetUserAccessToken 获取企业微信通讯录AccessToken
func (s *Server) GetUserAccessToken() string {
if us, ok := UserServerMap[s.AppId]; ok {
return us.GetAccessToken()
}
return s.GetAccessToken()
}
func (s *Server) getAccessToken() (err error) {
if s.ExternalTokenHandler != nil {
Printf("使用外部函数获取token")
s.AccessToken = s.ExternalTokenHandler(s.AppId)
return
}
Printf("使用本地机制获取token")
url := fmt.Sprintf(s.TokenUrl, s.AppId, s.Secret)
Printf(url)
at := new(AccessToken)
if err = util.GetJson(url, at); err != nil {
return
}
if at.ErrCode > 0 {
return at.Error()
}
Printf("[%v::%v]:%+v", s.AppId, s.AgentId, *at)
at.ExpiresIn = time.Now().Unix() + at.ExpiresIn - 5
s.AccessToken = at
return
}
// Ticket JS-SDK
type Ticket struct {
Ticket string `json:"ticket"`
ExpiresIn int64 `json:"expires_in"`
WxErr
}
// GetTicket 读取获取Ticket
func (s *Server) GetTicket() string {
if s.ticket == nil || s.ticket.ExpiresIn < time.Now().Unix() {
for i := 0; i < 3; i++ {
err := s.getTicket()
if err != nil {
log.Printf("getTicket[%v] err:%v", s.AgentId, err)
time.Sleep(time.Second)
continue
}
break
}
}
return s.ticket.Ticket
}
func (s *Server) getTicket() (err error) {
url := s.JsApi + s.GetAccessToken()
at := new(Ticket)
if err = util.GetJson(url, at); err != nil {
return
}
if at.ErrCode > 0 {
return at.Error()
}
Printf("[%v::%v-JsApi] >>> %+v", s.AppId, s.AgentId, *at)
at.ExpiresIn = time.Now().Unix() + 500
s.ticket = at
return
}
// JsConfig Jssdk配置
type JsConfig struct {
Beta bool `json:"beta"`
Debug bool `json:"debug"`
AppId string `json:"appId"`
Timestamp int64 `json:"timestamp"`
Nonsestr string `json:"nonceStr"`
Signature string `json:"signature"`
JsApiList []string `json:"jsApiList"`
Url string `json:"jsurl"`
App int `json:"jsapp"`
}
// GetJsConfig 获取Jssdk配置
func (s *Server) GetJsConfig(Url string) *JsConfig {
jc := &JsConfig{Beta: true, Debug: Debug, AppId: s.AppId}
jc.Timestamp = time.Now().Unix()
jc.Nonsestr = "esap"
jc.Signature = sortSha1(fmt.Sprintf("jsapi_ticket=%v&noncestr=%v×tamp=%v&url=%v", s.GetTicket(), jc.Nonsestr, jc.Timestamp, Url))
// TODO:可加入其他apilist
jc.JsApiList = []string{"scanQRCode"}
jc.Url = Url
jc.App = s.AgentId
Println("jsconfig:", jc) // Debug
return jc
}
|
[
2
] |
package src
import "fmt"
/*501. 二叉搜索树中的众数*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findMode(root *TreeNode) []int {
if root == nil {
return nil
}
mmap := make(map[int]int)
inOrder(root, mmap)
max := 1
var res []int
for k, v := range mmap {
if v > max {
res = []int{}
res = append(res, k)
max = v
} else if v == max {
res = append(res, k)
}
}
return res
}
func inOrder(root *TreeNode, mmap map[int]int) {
if root == nil {
return
}
inOrder(root.Left, mmap)
if _, ok := mmap[root.Val]; ok {
mmap[root.Val] = mmap[root.Val] + 1
} else {
mmap[root.Val] = 1
}
inOrder(root.Right, mmap)
}
func Test_findMode() {
root := &TreeNode{
Val: 1,
Left: nil,
Right: &TreeNode{
Val: 2,
Left: &TreeNode{
Val: 2,
Left: nil,
Right: nil,
},
Right: nil,
},
}
res := findMode(root)
fmt.Println(res)
}
|
[
0
] |
package main
import (
"fmt"
)
func main() {
var N int64
fmt.Scanf("%d", &N)
var i, v int64
m := make(map[int64]int)
for i=2; i*i<=N; i++{
v = i
for j:=0; ; j++{
v = v * i
if v <= N{
_, isThere := m[v]
if !isThere {
m[v] = 1
}
} else {
break
}
}
}
result := N - int64(len(m))
fmt.Printf("%d\n", result)
}
|
[
0
] |
package set
import (
"fmt"
"math"
)
type BitMap struct {
bits *[]byte
}
// 添加一个元素
func (bs *BitMap) Add(num int) {
byteLen := len(*bs.bits)
// 计算落在哪一个字节
bytePos := num / byteLen
// 计算落在哪个位
bitPos := num % 8
a := *bs.bits
a[bytePos] |= 1 << bitPos
}
// 判断给定数字是否已存在
func (bs *BitMap) Has(num int) bool {
bol := false
byteLen := len(*bs.bits)
// 计算落在哪一个字节
bytePos := num / byteLen
// 计算落在哪个位
bitPos := num % 8
bits := *bs.bits
if bits[bytePos] == (bits[bytePos] | 1 << bitPos) {
bol = true
}
return bol
}
func (bs *BitMap) PrintMap() {
fmt.Printf("%b", *bs.bits)
}
func NewBitMap(cap int32) *BitMap {
// 一个byte可以放8个数,
bytesLen := int32(math.Ceil(float64(cap / 8)))
b := make([]byte, bytesLen)
return &BitMap{bits: &b}
}
|
[
1
] |
/*
* http://projecteuler.net
*
* Задача №1
*
* Якщо виписати всі натуральні числа менше 10, кратні 3 або 5,
* то отримаємо 3, 5, 6 і 9. Сума цих чисел - 23.
*
* Знайти суму всіх числел менше 1000, кратних 3 або 5.
*/
package main
import "fmt"
import "time"
func mySolution() int {
var result int = 0
for i := 1; i <= 999; i++ {
if i % 3 == 0 || i % 5 == 0 {
result = result + i
}
}
return result
}
func sumDivisibleBy(value int) int {
var target = 999
var p = target / value
return value * (p * (p + 1)) / 2
}
func bestSolution() int {
return (sumDivisibleBy(3) + sumDivisibleBy(5) - sumDivisibleBy(15))
}
func main() {
fmt.Println(time.Now())
fmt.Println("Сума чисел 1: ", mySolution())
fmt.Println(time.Now())
fmt.Println("Сума чисел 2: ", bestSolution());
fmt.Println(time.Now())
}
/*
* Сума чисел: 233168
*
* Час: 0m0.020s
*/
|
[
0
] |
package parawri
import (
"fmt"
"io"
"sync"
ansi "github.com/k0kubun/go-ansi"
)
type Parallel struct {
w io.Writer
cnt int
mu sync.Mutex
}
func NewParallelStdout() *Parallel {
return &Parallel{w: ansi.NewAnsiStdout()}
}
func NewParallelStderr() *Parallel {
return &Parallel{w: ansi.NewAnsiStderr()}
}
func (p *Parallel) NewAppendWriter() io.Writer {
return &Writer{p: p, a: true}
}
func (p *Parallel) NewWriter() io.Writer {
return &Writer{p: p, a: false}
}
type Writer struct {
p *Parallel
idx int
str string
a bool
}
func (w *Writer) Write(p []byte) (int, error) {
w.p.mu.Lock()
defer w.p.mu.Unlock()
if w.a {
w.str = w.str + string(p)
} else {
w.str = string(p)
}
if w.idx == 0 {
w.p.cnt = w.p.cnt + 1
w.idx = w.p.cnt
fmt.Fprintln(w.p.w, w.str)
return len(p), nil
}
diff := w.p.cnt - w.idx + 1
ansi.CursorPreviousLine(diff)
ansi.EraseInLine(1)
fmt.Fprint(w.p.w, w.str)
ansi.CursorNextLine(diff)
return len(p), nil
}
|
[
0
] |
// THE AUTOGENERATED LICENSE. ALL THE RIGHTS ARE RESERVED BY ROBOTS.
// WARNING: This file has automatically been generated on Sun, 27 Jan 2019 19:16:53 GMT.
// Code generated by https://git.io/c-for-go. DO NOT EDIT.
package lv2host
/*
#cgo pkg-config: lilv-0
#cgo LDFLAGS: -L./lv2host/build/ -llv2host-c -lstdc++
#include "lv2host/lv2host-c.h"
#include <stdlib.h>
#include "cgo_helpers.h"
*/
import "C"
import (
"sync"
"unsafe"
)
// cgoAllocMap stores pointers to C allocated memory for future reference.
type cgoAllocMap struct {
mux sync.RWMutex
m map[unsafe.Pointer]struct{}
}
var cgoAllocsUnknown = new(cgoAllocMap)
func (a *cgoAllocMap) Add(ptr unsafe.Pointer) {
a.mux.Lock()
if a.m == nil {
a.m = make(map[unsafe.Pointer]struct{})
}
a.m[ptr] = struct{}{}
a.mux.Unlock()
}
func (a *cgoAllocMap) IsEmpty() bool {
a.mux.RLock()
isEmpty := len(a.m) == 0
a.mux.RUnlock()
return isEmpty
}
func (a *cgoAllocMap) Borrow(b *cgoAllocMap) {
if b == nil || b.IsEmpty() {
return
}
b.mux.Lock()
a.mux.Lock()
for ptr := range b.m {
if a.m == nil {
a.m = make(map[unsafe.Pointer]struct{})
}
a.m[ptr] = struct{}{}
delete(b.m, ptr)
}
a.mux.Unlock()
b.mux.Unlock()
}
func (a *cgoAllocMap) Free() {
a.mux.Lock()
for ptr := range a.m {
C.free(ptr)
delete(a.m, ptr)
}
a.mux.Unlock()
}
// safeString ensures that the string is NULL-terminated, a NULL-terminated copy is created otherwise.
func safeString(str string) string {
if len(str) > 0 && str[len(str)-1] != '\x00' {
str = str + "\x00"
} else if len(str) == 0 {
str = "\x00"
}
return str
}
// unpackPCharString represents the data from Go string as *C.char and avoids copying.
func unpackPCharString(str string) (*C.char, *cgoAllocMap) {
str = safeString(str)
h := (*stringHeader)(unsafe.Pointer(&str))
return (*C.char)(h.Data), cgoAllocsUnknown
}
type stringHeader struct {
Data unsafe.Pointer
Len int
}
type sliceHeader struct {
Data unsafe.Pointer
Len int
Cap int
}
|
[
0
] |
package main
import (
"github.com/jraams/aoc-2020/helpers"
"github.com/thoas/go-funk"
)
type valueCupMap map[int]*cup
type cup struct {
value int
next *cup
}
func load(labels string, extendCups bool) (valueCupMap, *cup) {
// Your labeling is still correct for the first few cups;
var intValues []int
for _, b := range []byte(labels) {
intValues = append(intValues, helpers.MustAtoi(string(b)))
}
// after that, the remaining cups are just numbered in an increasing fashion starting from the number after the
// highest number in your list and proceeding one by one until one million is reached.
if extendCups {
for i := len(labels) + 1; i <= 1000000; i++ {
intValues = append(intValues, i)
}
}
vc := valueCupMap{}
var prev *cup
for _, i := range intValues {
c := &cup{
value: i,
}
vc[i] = c
if prev != nil {
prev.next = c
}
prev = c
}
prev.next = vc[intValues[0]]
// Before the crab starts, it will designate the first cup in your list as the current cup.
return vc, prev
}
func playCrabGame(vc valueCupMap, currentCup *cup, moves int) {
// The crab is then going to do N moves.
for i := 1; i <= moves; i++ {
// The crab selects a new current cup: the cup which is immediately clockwise of the current cup.
currentCup = currentCup.next
// The crab picks up the three cups that are immediately clockwise of the current cup.
pickedUpCups := []*cup{
currentCup.next,
currentCup.next.next,
currentCup.next.next.next,
}
// They are removed from the circle;
currentCup.next = currentCup.next.next.next.next
// The crab selects a destination cup
destinationVal := currentCup.value
searchingDest := true
for searchingDest {
destinationVal = destinationVal - 1
if destinationVal <= 0 {
destinationVal = len(vc)
}
if !funk.Contains(pickedUpCups, vc[destinationVal]) {
searchingDest = false
}
}
destination := vc[destinationVal]
// The crab places the cups it just picked up so that they are immediately clockwise of the destination cup.
pickedUpCups[2].next = destination.next
destination.next = pickedUpCups[0]
}
}
|
[
0
] |
package features
// Feature that gets the first number in a string (mod 256).
// NOTE: We allow the user to specify the number of times they want this feature repeated
// (poor man's weighting).
import (
"strconv"
"strings"
)
const first_number_default_count = 20
type firstNumber struct {
Count byte
}
//----------------------------------------------------------------------------------------------------
// Provide featureSetConfig
func (fn firstNumber) Size() int32 {
return int32(fn.Count)
}
func (fn firstNumber) FromStringInPlace(input string, featureArray []byte) {
firstNum := GetFirstNumber(input)
for i := byte(0); i < fn.Count; i++ {
featureArray[i] = firstNum
}
}
func deserializeFirstNumberMap(confMap map[string]string) (config featureSetConfig, ok bool) {
if countStr, ok := confMap["count"]; ok {
if count, err := strconv.Atoi(countStr); err == nil {
return firstNumber{byte(count)}, true
} else {
return nil, false
}
}
return firstNumber{byte(first_number_default_count)}, true
}
//----------------------------------------------------------------------------------------------------
// Do this from scratch instead of using regular expressions. Much faster.
func GetFirstNumber(input string) byte {
num := 0
inNum := false
for _, ch := range input {
if ch >= '0' && ch <= '9' {
if inNum {
num = (num * 10) + int(ch-'0')
} else {
num = int(ch - '0')
inNum = true
}
} else {
if inNum {
if ch >= 'a' && ch <= 'z' {
// Heuristic: this wasn't an actual number, more like "1st" or "3A"
num = 0
inNum = false
} else {
// we were inside the number but just fell out, so we're done
return byte(num % 256)
}
}
}
}
// if the number was at the end of the string
return byte(num % 256)
}
// Same as above, but return a string.
func GetFirstNumberAsString(input string) string {
var num strings.Builder
inNum := false
for _, ch := range input {
if ch >= '0' && ch <= '9' {
num.WriteByte(byte(ch))
inNum = true
} else {
if inNum {
if ch >= 'a' && ch <= 'z' {
// Heuristic: this wasn't an actual number, more like "1st" or "3A"
num.Reset()
inNum = false
} else {
// we were inside the number but just fell out, so we're done
return strings.TrimLeft(num.String(), "0")
}
}
}
}
// if the number was at the end of the string
return strings.TrimLeft(num.String(), "0")
}
|
[
4
] |
package crmcontrol
import "sort"
type IntSet struct {
set map[int]struct{}
}
func NewIntSet() *IntSet {
return &IntSet{set: make(map[int]struct{})}
}
func (s *IntSet) Keys() []int {
var keys []int
for k := range s.set {
keys = append(keys, k)
}
return keys
}
func (s *IntSet) Add(k int) {
s.set[k] = struct{}{}
}
func (s *IntSet) Len() int { return len(s.set) }
func (s *IntSet) SortedKeys() []int {
keys := s.Keys()
sort.Ints(keys)
return keys
}
func (s *IntSet) ReverseSortedKeys() []int {
keys := s.Keys()
sort.Sort(sort.Reverse(sort.IntSlice(keys)))
return keys
}
func (s *IntSet) GetFree(min, max int) (int, bool) {
for i := min; i <= max; i++ {
if _, ok := s.set[i]; !ok {
return i, true
}
}
return 0, false
}
|
[
1
] |
package main
import (
"fmt"
"os"
)
func main() {
var n int
fmt.Fscan(os.Stdin, &n)
var value, count int
var slice []int
for i := 0; i < n; i++ {
fmt.Fscan(os.Stdin, &value)
slice = append(slice, value)
}
var min int = slice[0]
for _, val := range slice {
if val < min {
min = val
}
}
for _, val := range slice {
if val == min {
count++
}
}
fmt.Printf("%d", count)
}
/*
Количество минимумов
Найдите количество минимальных элементов в последовательности.
Входные данные
Вводится натуральное число N, а затем N чисел.
Выходные данные
Выведите количество минимальных элементов.
Sample Input:
3
21 11 4
Sample Output:
1
*/
|
[
1
] |
package chia
import (
"chianoob_linux/models"
"chianoob_linux/myfunc"
"fmt"
"github.com/astaxie/beego"
"os/exec"
"strconv"
"strings"
"time"
)
var ChiaConfig = `/home/cykj/chia-plotter/build/chia_plot -n -1 -r THR -u BUK -t SSDPT -2 SSDP2 -d HHDP -p PPK -f FPK`
var HpoolYaml = `token: ""
path:
- /home/cykj/HHD0
- /home/cykj/HHD1
- /home/cykj/HHD2
- /home/cykj/HHD3
- /home/cykj/HHD4
- /home/cykj/HHD5
- /home/cykj/HHD6
- /home/cykj/HHD7
- /home/cykj/HHD8
- /home/cykj/HHD9
- /home/cykj/HHD10
- /home/cykj/HHD11
minerName: Pname
apiKey: Poolkey
cachePath: ""
deviceId: ""
extraParams: {}
log:
lv: info
path: ./log/
name: miner.log
url:
proxy: ""
scanPath: false
scanMinute: 60
`
func Initconfig(chiaConfig string) (commend string, err error) {
pool()
myfunc.GetTodesk()
if len(models.Todesk) > 4 {
models.Todesk = models.Todesk[:len(models.Todesk)-4]
}
fmt.Println("Todesk:", models.Todesk)
models.Pnum, _ = strconv.Atoi(models.Conf.GetValue("chia", "today_pnum"))
ssdpt, ssdp2, hhdp, err := GetRunPath("1")
if err != nil {
fmt.Println(err)
cmd := exec.Command("sh", "-c", `/www/server/chiabee/mount_disk.sh`)
cmd.Output()
time.Sleep(30 * time.Second)
return "", err
}
ssdpt = ssdpt + "chia1/"
ssdp2 = ssdp2 + "chia1/"
myfunc.CMD("rm -rf", "/var/log/syslog")
myfunc.CMD("rm -rf", ssdpt)
myfunc.CMD("rm -rf", ssdp2)
myfunc.CMD("mkdir", ssdpt)
myfunc.CMD("mkdir", ssdp2)
THR := beego.AppConfig.String("THR")
FPK := beego.AppConfig.String("FPK")
PPK := beego.AppConfig.String("PPK")
BUK := beego.AppConfig.String("BUK")
fmt.Println("get path ssdt:", ssdpt, " ssdp2:", ssdp2, " hhdp:", hhdp)
chiaConfig = strings.Replace(ChiaConfig, "FPK", FPK, -1)
chiaConfig = strings.Replace(chiaConfig, "PPK", PPK, -1)
chiaConfig = strings.Replace(chiaConfig, "THR", THR, -1)
chiaConfig = strings.Replace(chiaConfig, "BUK", BUK, -1)
chiaConfig = strings.Replace(chiaConfig, "SSDPT", ssdpt, -1)
chiaConfig = strings.Replace(chiaConfig, "SSDP2", ssdp2, -1)
commend = strings.Replace(chiaConfig, "HHDP", hhdp, -1)
fmt.Println("commend : ", commend)
return commend, nil
}
func pool() {
fmt.Println("Phool start")
Hpool := beego.AppConfig.String("Hpool")
poolpath := beego.AppConfig.String("hpoolmincof")
if poolpath != "" {
pname := beego.AppConfig.String("porname")
if pname == "" {
pname = myfunc.LocalIp()
}
hpoolyaml := strings.Replace(HpoolYaml, "Pname", pname, -1)
hpoolyaml = strings.Replace(hpoolyaml, "Poolkey", Hpool, -1)
myfunc.WriteToFile(poolpath, hpoolyaml)
}
}
|
[
0
] |
package client
import (
"encoding/xml"
"log"
)
type jobDefinitionUnmarshaler func(*xml.Decoder, xml.StartElement) (JobDefinition, error)
var jobDefinitionUnmarshalFunc = map[string]jobDefinitionUnmarshaler{}
type JobDefinitionXml struct {
Item JobDefinition
}
type JobDefinition interface {
GetType() JobDefinitionType
}
func (jobDefinition *JobDefinitionXml) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return e.EncodeElement(jobDefinition.Item, start)
}
func (jobDefinition *JobDefinitionXml) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
for _, attr := range start.Attr {
switch attr.Name.Local {
case "class":
if unmarshalXML, ok := jobDefinitionUnmarshalFunc[attr.Value]; ok {
newDefItem, err := unmarshalXML(d, start)
if err != nil {
return err
}
jobDefinition.Item = newDefItem
return nil
}
}
}
log.Println("[WARN] Unable to unmarshal definition xml. Unknown or missing class")
var err error
// must read all of doc or it complains
for _, err := d.Token(); err == nil; _, err = d.Token() {
}
return err
}
|
[
7
] |
package main
import (
"runtime"
"time"
)
// INTERVAL is the time range to adjust cpu usage
const INTERVAL int = 50
var (
busyTime int
)
// take up cpu
// refresh cpu usage every second
func takeUpCPU() {
defer wg.Done()
runtime.LockOSThread()
busyTime = int(float64(INTERVAL) * cpuUsage)
// TODO: quick estimation
for {
// reset every 1 second
idleTime := INTERVAL - busyTime
for i := 0; i < 1000/INTERVAL; i++ {
// supposed calculating cpu usage is pretty fast
// sampling
prevTicks, _ := getCPUTicks()
takeNap(INTERVAL, idleTime)
// sampling again and update idleTime
ticks, _ := getCPUTicks()
for i := 0; i < 8; i++ {
ticks[i] = ticks[i] - prevTicks[i]
}
var total uint64
for i := 0; i < 8; i++ {
total += ticks[i]
}
idle := ticks[3] + ticks[4]
delta := float64(idleTime) * (float64(idle)/float64(total) - (1.0 - cpuUsage)) / 0.75
idleTime -= int(delta)
}
}
runtime.UnlockOSThread()
}
func takeNap(interval, idleTime int) {
startTime := time.Now()
time.Sleep(time.Duration(idleTime) * time.Millisecond)
// tick time
d := time.Duration(interval) * time.Millisecond
for time.Now().Sub(startTime) < d {
// just to consume cpu
}
}
|
[
0
] |
// Copyright 2014-2015, Truveris Inc. All Rights Reserved.
// Use of this source code is governed by the ISC license in the LICENSE file.
package sqs
import (
"encoding/xml"
"errors"
"io/ioutil"
"net"
"net/http"
"strings"
"time"
"github.com/mikedewar/aws4"
)
var (
// Ref:
// http://docs.aws.amazon.com/general/latest/gr/rande.html#sqs_region
EndPoints = map[string]string{
"ap-northeast-1": "https://sqs.ap-northeast-1.amazonaws.com",
"ap-southeast-1": "https://sqs.ap-southeast-1.amazonaws.com",
"ap-southeast-2": "https://sqs.ap-southeast-2.amazonaws.com",
"eu-west-1": "https://sqs.eu-west-1.amazonaws.com",
"sa-east-1": "https://sqs.sa-east-1.amazonaws.com",
"us-east-1": "https://sqs.us-east-1.amazonaws.com",
"us-west-1": "https://sqs.us-west-1.amazonaws.com",
"us-west-2": "https://sqs.us-west-2.amazonaws.com",
}
HTTPTimeout = 25 * time.Second
)
type Client struct {
Aws4Client *aws4.Client
EndPointURL string
}
func dialTimeout(network, addr string) (net.Conn, error) {
return net.DialTimeout(network, addr, HTTPTimeout)
}
func NewClient(AccessKey, SecretKey, RegionCode string) (*Client, error) {
keys := &aws4.Keys{
AccessKey: AccessKey,
SecretKey: SecretKey,
}
EndPointURL := EndPoints[RegionCode]
if EndPointURL == "" {
return nil, errors.New("Unknown region: " + RegionCode)
}
transport := &http.Transport{Dial: dialTimeout, ResponseHeaderTimeout: HTTPTimeout}
client := &http.Client{Transport: transport}
return &Client{
Aws4Client: &aws4.Client{Keys: keys, Client: client},
EndPointURL: EndPointURL,
}, nil
}
// Simple wrapper around the aws4 client Post() but less verbose.
func (client *Client) Post(queueURL, data string) (*http.Response, error) {
return client.Aws4Client.Post(queueURL, SQSContentType,
strings.NewReader(data))
}
// Simple wrapper around the aws4 Get() to keep it consistent.
func (client *Client) Get(url string) (*http.Response, error) {
return client.Aws4Client.Get(url)
}
// Return a single message body, with its ReceiptHandle. A lack of message is
// not considered an error but *Message will be nil.
func (client *Client) GetMessagesFromRequest(request *Request) ([]*Message, error) {
resp, err := client.Get(request.URL())
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, errors.New(string(data))
}
r, err := NewReceiveMessageResponse(data)
if err != nil {
return nil, err
}
return r.GetMessages(request.QueueURL)
}
// Return a single message with its ReceiptHandle. A lack of message is not
// considered an error but the return message will be nil.
func (client *Client) GetSingleMessage(url string) (*Message, error) {
request := NewReceiveMessageRequest(url)
request.Set("MaxNumberOfMessages", "1")
messages, err := client.GetMessagesFromRequest(request)
if err != nil {
return nil, err
}
return messages[0], nil
}
// Return queue messages, with its ReceiptHandle. A lack of message is
// not considered an error but the return message will be nil.
func (client *Client) GetMessages(url string) ([]*Message, error) {
request := NewReceiveMessageRequest(url)
request.Set("MaxNumberOfMessages", "10")
return client.GetMessagesFromRequest(request)
}
// Conduct a DeleteMessage API call on the given queue, using the receipt
// handle from a previously fetched message.
func (client *Client) DeleteMessageFromReceipt(queueURL, receipt string) error {
url := NewDeleteMessageRequest(queueURL, receipt).URL()
resp, err := client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}
// Conduct a DeleteMessage API call on the given queue, using the receipt
// handle from a previously fetched message.
func (client *Client) DeleteMessage(msg *Message) error {
url := NewDeleteMessageRequest(msg.QueueURL, msg.ReceiptHandle).URL()
resp, err := client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}
// Conduct a SendMessage API call (POST) on the given queue.
func (client *Client) SendMessage(queueURL, message string) error {
data := NewSendMessageRequest(queueURL, message).Query()
resp, err := client.Post(queueURL, data)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.New(string(body))
}
return nil
}
// Get the queue URL from its name.
func (client *Client) GetQueueURL(name string) (string, error) {
var parsedResponse GetQueueURLResult
url := NewGetQueueURLRequest(client.EndPointURL, name).URL()
resp, err := client.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode != 200 {
return "", errors.New(string(body))
}
err = xml.Unmarshal(body, &parsedResponse)
if err != nil {
return "", err
}
return parsedResponse.QueueURL, nil
}
// Create a queue using the provided attributes and return its URL. This
// function can be used to obtain the QueueURL for a queue even if it already
// exists.
func (client *Client) CreateQueueWithAttributes(name string, attributes CreateQueueAttributes) (string, error) {
var parsedResponse CreateQueueResult
url := buildCreateQueueURL(client.EndPointURL, name, attributes)
resp, err := client.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode != 200 {
return "", errors.New(string(body))
}
err = xml.Unmarshal(body, &parsedResponse)
if err != nil {
return "", err
}
return parsedResponse.QueueURL, nil
}
// Create a queue with default parameters and return its URL. This function can
// be used to obtain the QueueURL for a queue even if it already exists.
func (client *Client) CreateQueue(name string) (string, error) {
url, err := client.CreateQueueWithAttributes(name, CreateQueueAttributes{})
return url, err
}
|
[
2
] |
package main
import "fmt"
type Foo struct {
A int
B string
}
func (f Foo) String() string {
return fmt.Sprintf("A: %d and B: %s", f.A, f.B)
}
func (f *Foo) Double() {
f.A = f.A * 2
}
func main() {
f := Foo{
A: 10,
B: "Hello",
}
fmt.Println(f.String())
f.Double()
fmt.Println(f.String())
}
|
[
0
] |
package main
import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
"os"
)
func usage() {
fmt.Println("Simple tool to print formatted json string from stdin")
fmt.Println("")
fmt.Println(" $ cmd | dump-json")
fmt.Println(" $ dump-json < <unformatted-json-file>")
fmt.Println("")
}
func main() {
var jsonText bytes.Buffer
var jsonFile string
flag.Usage = usage
flag.Parse()
reader := bufio.NewReader(os.Stdin)
for {
line, _, err := reader.ReadLine()
if err != nil {
break
}
jsonFile = jsonFile + string(line)
}
err := json.Indent(&jsonText, []byte(jsonFile), "", "\t")
if err != nil {
fmt.Println("BAD Json", jsonFile)
} else {
jsonText.WriteTo(os.Stdout)
}
}
|
[
0
] |
package main
import (
"fmt"
"flag"
)
func makeWorker(beginIsEven bool, begin, end float64, write chan float64) {
go func() {
var sum float64 = 0.0
shouldAdd := beginIsEven
for i := begin; i <= end; i = i + 1.0 {
addend := 4.0 / (2*i + float64(1.0))
if shouldAdd {
sum += addend
} else {
sum -= addend
}
shouldAdd = !shouldAdd
}
write <- sum
}()
}
func main() {
workers := flag.Uint64("workers", 0, "max integer to try")
rng := flag.Uint64("range", 0, "max integer to try")
flag.Parse()
chans := make(chan float64, 1000000)
quit := make(chan bool)
go func() {
var pi float64 = 0.0
for i := uint64(0); i < *workers; i++ {
pi += <- chans
}
fmt.Printf("Approximate Pi = %v\n", pi)
quit <- true
}()
var i uint64 = 0
for ; i < *workers; i++ {
makeWorker((0 == ((i * *rng) % 2)), float64(i * *rng), float64((i + 1) * *rng - 1), chans)
}
<- quit
}
|
[
0
] |
package golang
// leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func rotateRight(head *ListNode, k int) *ListNode {
if head == nil || head.Next == nil {
return head
}
l := 1
tail := head
for tail.Next != nil {
l++
tail = tail.Next
}
k = k % l
if k == 0 {
return head
}
var newHead, pre *ListNode = head, nil
for i := 0; i < l-k; i++ {
pre = newHead
newHead = newHead.Next
if i == l-k-1 {
pre.Next = nil
tail.Next = head
}
}
return newHead
}
// leetcode submit region end(Prohibit modification and deletion)
|
[
0
] |
package main
import (
"encoding/json"
"fmt"
"io"
"sync"
"time"
"github.com/siddontang/go/log"
"github.com/davecgh/go-spew/spew"
"github.com/tidwall/gjson"
"golang.org/x/net/context"
elastic "gopkg.in/olivere/elastic.v5"
)
// Scene 场景
type Scene struct {
Name string
IndexNamePerfix string `mapstructure:"index_name_perfix" json:"index_name_perfix"`
Cron string
TimeRange int `mapstructure:"time_range" json:"time_range"`
Worker int
Taches map[string]Tache
Links []Link
FirstTache string `mapstructure:"first_tache" json:"first_tache"`
ESUrl []string `mapstructure:"es_url" json:"es_url"`
Running bool
Hits chan elastic.SearchHit
ESClinet *elastic.Client
} // Scene 场景
// Join 开始日志合并
func (s *Scene) Join() {
defer func() {
if r := recover(); r != nil {
log.Errorf("场景 '%s' 执行异常", s.Name)
}
}()
client, err := elastic.NewClient(elastic.SetURL(s.ESUrl...), elastic.SetSniff(false))
if err != nil {
// Handle error
log.Errorf("场景 '%s' 执行异常:%s", s.Name, err)
return
}
s.ESClinet = client
s.Hits = make(chan elastic.SearchHit, 200)
go s.GetAllRecodes()
s.CheckAll()
}
// CheckAll 并发确认每条记录
func (s *Scene) CheckAll() {
var wg sync.WaitGroup
logger.Debugf("场景 '%s' 共有确认线程 %d 个", s.Name, s.Worker)
for w := 0; w < s.Worker; w++ {
wn := w
wg.Add(1)
go func() {
logger.Debugf("场景 '%s' 确认线程 %d 启动", s.Name, wn)
for hit := range s.Hits {
s.Check(hit)
}
logger.Debugf("场景 '%s' 确认线程 %d 完毕", s.Name, wn)
wg.Done()
}()
}
wg.Wait()
logger.Infof("完成场景 '%s' 所有工作", s.Name)
}
// Check 检验一条记录是否完成,如 完成返回
func (s *Scene) Check(hit elastic.SearchHit) {
var firstHitJSON map[string]interface{}
firstHitChar, err := hit.Source.MarshalJSON()
if err != nil {
logger.Errorf("场景 '%s' 返序列化开始环节日志失败,ES-id= '%s'", s.Name, hit.Id)
// return nil, false
return
}
json.Unmarshal(firstHitChar, &firstHitJSON)
if err != nil {
logger.Errorf("场景 '%s' 返序列化开始环节日志失败,ES-id= '%s'", s.Name, hit.Id)
// return nil, false
return
}
checkedHits := map[string][]*elastic.SearchHit{}
s.AddHits(&checkedHits, s.FirstTache, []*elastic.SearchHit{&hit})
// var sdfsdf Hits =
// checkedHits = append(checkedHits, Hits{Tache: s.FirstTache, Hit: []elastic.SearchHit{hit}})
// 把首环节日志放入以获取的日志列表
// lastTaches := s.FirstTache
links, taches := s.GetNextTache([]string{s.FirstTache})
logger.Debugf("场景 '%s' 获取到起始环节 '%s' 的下属环节 %d 个分别为:%s", s.Name, s.FirstTache, len(links), spew.Sprint(links))
for len(links) > 0 {
// 一条线一条线处理
for _, link := range links {
// 每条线获取源头有多少条记录
termQureys := []elastic.Query{}
for _, fromTache := range checkedHits[link.From.Tache] {
// 由于无法确认环节一对多的情况下暂时无法判断对应关系,所以为每条记录添加一个 termQureys 有匹配到就算是有记录
// 默认前端为 logstash 5.x 需要添加 keyword 才能全文匹配
tmpHitChar, _ := fromTache.Source.MarshalJSON()
tmpHitKey := gjson.Get(string(tmpHitChar), link.From.Field).String()
if tmpHitKey == "null" {
return
}
termQureys = append(termQureys, elastic.NewTermQuery(link.To.Field+".keyword", tmpHitKey))
}
q := elastic.NewBoolQuery().Should(termQureys...)
// termQuery := elastic.NewTermQuery(link.To.Field, hitJSON[link.From.Field])
ctx := context.Background()
searchquery := s.ESClinet.Search(s.Taches[link.To.Tache].IndexNamePerfix + "*").Query(q)
searchResult, err := searchquery.Do(ctx)
if err != nil {
logger.Errorf("场景 '%s' 查询失败 ,错误内容为%s", s.Name, err)
}
// 如果没有记录就马上返回
if searchResult.TotalHits() == 0 {
return
}
// 如果有记录就加入到 checkedHits
s.AddHits(&checkedHits, link.To.Tache, searchResult.Hits.Hits)
}
links, taches = s.GetNextTache(taches)
}
spew.Dump(checkedHits)
return
}
func (s *Scene) AddHits(checkedHits *map[string][]*elastic.SearchHit, tacheName string, newHits []*elastic.SearchHit) {
// 校验每一天新记录
for _, newHit := range newHits {
same := false
for _, oldHit := range (*checkedHits)[tacheName] {
if newHit.Id == oldHit.Id {
same = true
break
}
}
// 如果没有找到匹配项目 就加入新 Hits
if same == false {
hitList, exit := (*checkedHits)[tacheName]
if exit {
(*checkedHits)[tacheName] = append(hitList, newHit)
} else {
(*checkedHits)[tacheName] = []*elastic.SearchHit{newHit}
}
}
}
}
func (s *Scene) GetNextTache(ts []string) ([]Link, []string) {
retLink := []Link{}
retTache := []string{}
for _, t := range ts {
for _, link := range s.Links {
if link.From.Tache == t {
retLink = append(retLink, link)
retTache = append(retTache, link.To.Tache)
}
}
}
return retLink, retTache
}
// GetAllRecodes 获取所有的开始环节记录
func (s *Scene) GetAllRecodes() {
logger.Debugf("连接 ES URL = %s", s.ESUrl)
ctx := context.Background()
logger.Debugf("正在为场景 '%s' 获取第一环节 '%s' 的未串联日志,获取的时间段为,%s 到 %s ",
s.Name, s.FirstTache, time.Now().Add(time.Minute*time.Duration(s.TimeRange*-1)), time.Now())
q := elastic.NewRangeQuery(s.Taches[s.FirstTache].TimeField).
Gte(time.Now().Add(time.Minute * time.Duration(s.TimeRange*-1)).Format("2006-01-02T15:04:05-07:00")).
Lte("now")
scroll := s.ESClinet.Scroll(s.Taches[s.FirstTache].IndexNamePerfix + "*").
Size(10000).
Query(q)
i := 0
for {
results, err := scroll.Do(ctx)
if err == io.EOF {
if i == 0 {
logger.Infof("场景 '%s' 没找到未串联记录记录失败:", s.Name)
}
break
}
if err != nil {
// Handle error
logger.Errorf("场景 '%s' 寻找为串联记录记录失败:%s ", s.Name, err)
break
}
i = i + len(results.Hits.Hits)
logger.Debugf("场景 '%s' 找到 %d 条记录", s.Name, len(results.Hits.Hits))
for _, hit := range results.Hits.Hits {
s.Hits <- *hit
}
logger.Infof("场景 '%s' 共找到 %d 条记录", s.Name, i)
}
close(s.Hits)
}
// SetFirstTache 获取开始环节,开始环节只能有一个
func (s *Scene) SetFirstTache() error {
// 如果有配置,检查一下配置,通过检查就直接返回配置的值
if s.FirstTache != "" {
if s.CheckFirstTache(s.FirstTache) {
return nil
}
logger.Warningf("场景 %s 配置了开始环节为 %s,但经检查 %s 不满足开始环节条件,开始尝试搜索开始环节",
s.Name, s.FirstTache, s.FirstTache)
}
logger.Infof("场景 %s 未配置开始环节,尝试自动搜索开始环节", s.Name)
for k := range s.Taches {
if s.CheckFirstTache(k) {
(*s).FirstTache = k
logger.Infof("将场景 %s 的开始环节配置为 %s", s.Name, s.FirstTache)
// logger.Info(spew.Sdump(s))
return nil
}
}
logger.Errorf("无法为场景 %s 找到开始环节,请检查配置文件。", s.Name)
return fmt.Errorf("无法为场景 %s 找到开始环节,请检查配置文件。", s.Name)
}
// CheckFirstTache 用于判断是否为初始环节
func (s *Scene) CheckFirstTache(name string) bool {
if _, ok := s.Taches[name]; !ok {
return false
}
for _, v := range s.Links {
if v.To.Tache == name {
return false
}
}
return true
}
// // GetNextTaches 获取下一环节,下一环节可能会有多个
// func (s *Scene) GetNextTaches(tacheName string) []string {
// }
|
[
0
] |
/* https://leetcode.com/problems/sum-of-even-numbers-after-queries/description/
We have an array A of integers, and an array queries of queries.
For the i-th query val = queries[i][0], index = queries[i][1], we add val to A[index]. Then, the answer to the i-th query is the sum of the even values of A.
(Here, the given index = queries[i][1] is a 0-based index, and each query permanently modifies the array A.)
Return the answer to all queries. Your answer array should have answer[i] as the answer to the i-th query.
Example 1:
Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
Output: [8,6,2,4]
Explanation:
At the beginning, the array is [1,2,3,4].
After adding 1 to A[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to A[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.
After adding -4 to A[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.
After adding 2 to A[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.
Note:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
1 <= queries.length <= 10000
-10000 <= queries[i][0] <= 10000
0 <= queries[i][1] < A.length
*/
package larray
func sumEvenAfterQueries(A []int, queries [][]int) []int {
tmp := make([]int, len(A), len(A))
copy(tmp, A)
sum := 0
for _, value := range tmp {
if value%2 == 0 {
sum += value
}
}
res := make([]int, len(A), len(A))
for i, query := range queries {
value, idx := query[0], query[1]
old := tmp[idx]
tmp[idx] += value
if tmp[idx]%2 == 0 {
if old%2 == 0 {
sum += value
} else {
sum += tmp[idx]
}
} else {
if old%2 == 0 {
sum = sum - old
}
}
res[i] = sum
}
return res
}
|
[
0,
2
] |
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
var n, a int
in := bufio.NewReader(os.Stdin)
fmt.Fscan(in, &n)
a1 := make(map[int]int, n)
a2 := make(map[int]int, n-1)
for i := 0; i < n; i++ {
fmt.Fscan(in, &a)
a1[a] = a1[a] + 1
}
for i := 0; i < n-1; i++ {
fmt.Fscan(in, &a)
a2[a] = a2[a] + 1
a1[a] = a1[a] - 1
}
for i := 0; i < n-2; i++ {
fmt.Fscan(in, &a)
a2[a] = a2[a] - 1
}
ans1 := 0
for k, v := range a1 {
if v > 0 {
ans1 = k
}
}
ans2 := 0
for k, v := range a2 {
if v > 0 {
ans2 = k
}
}
fmt.Println(ans1)
fmt.Println(ans2)
}
|
[
0
] |
package circuitbreaker_test
import (
"net/http"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/andrew-bodine/circuitbreaker"
)
type HttpCaller struct{}
func (h *HttpCaller) Call(args ...interface{}) (interface{}, error) {
method := args[0].(string)
resource := args[1].(string)
switch method {
default:
return http.Get(resource)
}
}
// Validate basic usage.
var _ = Describe("circuitbreaker", func() {
var cb circuitbreaker.CircuitBreaker
BeforeEach(func() {
cb = circuitbreaker.New(&HttpCaller{})
})
Context("basic usage", func() {
Context("with an endpoint that is never down", func() {
It("happily fetches the content", func() {
resp, err := cb.Call(http.MethodGet, "https://www.google.com")
Expect(err).To(BeNil())
Expect(resp).NotTo(BeNil())
})
})
})
})
|
[
7
] |
package certs
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"reflect"
)
// decodeCertPEM attempts to return a decoded certificate or nil
// if the encoded input does not contain a certificate.
func decodeCertPEM(encoded []byte) (*x509.Certificate, error) {
if len(encoded) == 0 {
return nil, fmt.Errorf("empty certificate")
}
block, _ := pem.Decode(encoded)
if block == nil {
return nil, fmt.Errorf("unable to decode PEM encoded text")
}
return x509.ParseCertificate(block.Bytes)
}
func parsePrivateKey(der []byte) (*rsa.PrivateKey, error) {
key, err := x509.ParsePKCS1PrivateKey(der)
if err == nil {
return key, nil
}
rsaOrEcKey, err := x509.ParsePKCS8PrivateKey(der)
if err != nil {
return nil, fmt.Errorf("Failed to parse key in either PKCS#1 or PKCS#8 format")
}
switch v := rsaOrEcKey.(type) {
case *rsa.PrivateKey:
return v, nil
}
return nil, fmt.Errorf("Expecting RSA key, found: %v", reflect.TypeOf(rsaOrEcKey))
}
// decodePrivateKeyPEM attempts to return a decoded key or nil
// if the encoded input does not contain a private key.
func decodePrivateKeyPEM(encoded []byte) (*rsa.PrivateKey, error) {
if len(encoded) == 0 {
return nil, fmt.Errorf("empty private key")
}
block, _ := pem.Decode(encoded)
if block == nil {
return nil, fmt.Errorf("unable to decode PEM encoded text")
}
return parsePrivateKey(block.Bytes)
}
|
[
7
] |
package main
import (
"context"
"encoding/json"
"html/template"
"log"
"net/http"
"os"
"time"
"github.com/Luzifer/go_helpers/github"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/nicksnyder/go-i18n/i18n"
)
const (
// Time allowed to write a message to the peer.
writeWait = 10 * time.Second
// Maximum message size allowed from peer.
maxMessageSize = 8192
// Time allowed to read the next pong message from the peer.
pongWait = 60 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
// Number of concurrent calculations per socket
calculationPoolSize = 3
)
var upgrader = websocket.Upgrader{}
type routeRequest struct {
StartSystemID int64 `json:"start_system_id"`
TargetSystemID int64 `json:"target_system_id"`
RouteRequestID string `json:"route_request_id"`
StopDistance float64 `json:"stop_distance"`
}
type routeResponse struct {
Counter int64 `json:"counter"`
Success bool `json:"success"`
ErrorMessage string `json:"error_message"`
RouteRequestID string `json:"route_request_id"`
Result traceResult `json:"result"`
}
type jsonResponse struct {
Success bool `json:"success"`
ErrorMessage string `json:"error_message"`
Data map[string]interface{} `json:"data"`
}
func (j jsonResponse) Send(res http.ResponseWriter, cachingAllowed bool) error {
res.Header().Set("Content-Type", "application/json")
if cachingAllowed {
res.Header().Set("Cache-Control", "public, max-age=3600")
} else {
res.Header().Set("Cache-Control", "no-cache")
}
return json.NewEncoder(res).Encode(j)
}
func startWebService() {
r := mux.NewRouter()
r.HandleFunc("/", handleFrontend)
r.HandleFunc("/assets/application.js", handleJS)
r.HandleFunc("/api/system-by-name", handleSystemByName)
r.HandleFunc("/api/route", handleRouteSocket)
r.HandleFunc("/api/control/shutdown", handleShutdown)
r.HandleFunc("/api/control/update", handleUpdate)
r.HandleFunc("/api/control/update-database", handleUpdateDatabase)
verboseLog("Webserver started and listening on %s", cfg.Listen)
log.Fatalf("Unable to listen for web connections: %s", http.ListenAndServe(cfg.Listen, r))
}
func getTranslator(r *http.Request) i18n.TranslateFunc {
c, _ := r.Cookie("lang")
var cookieLang string
if c != nil {
cookieLang = c.Value
}
acceptLang := r.Header.Get("Accept-Language")
defaultLang := "en-US" // known valid language
T, _ := i18n.Tfunc(cookieLang, acceptLang, defaultLang)
return T
}
func handleFrontend(res http.ResponseWriter, r *http.Request) {
T := getTranslator(r)
frontend, err := Asset("assets/frontend.html")
if err != nil {
http.Error(res, "Could not load frontend: "+err.Error(), http.StatusInternalServerError)
return
}
tpl, err := template.New("frontend").Funcs(template.FuncMap{"T": T}).Parse(string(frontend))
if err != nil {
http.Error(res, "Could not parse frontend: "+err.Error(), http.StatusInternalServerError)
return
}
if err := tpl.Execute(res, map[string]interface{}{
"version": version,
"disableSoftwareControl": cfg.DisableSoftwareControl,
}); err != nil {
http.Error(res, "Could not execute frontend: "+err.Error(), http.StatusInternalServerError)
return
}
}
func handleJS(res http.ResponseWriter, r *http.Request) {
js, _ := Asset("assets/application.js")
res.Header().Set("Content-Type", "application/javascript")
res.Write(js)
}
func handleShutdown(res http.ResponseWriter, r *http.Request) {
T := getTranslator(r)
if cfg.DisableSoftwareControl {
http.Error(res, "Controls are disabled", http.StatusForbidden)
return
}
defer os.Exit(0)
jsonResponse{
Success: true,
ErrorMessage: T("warn_service_will_shutdown"),
}.Send(res, false)
<-time.After(time.Second) // Give the response a second to send
}
func handleUpdate(res http.ResponseWriter, r *http.Request) {
T := getTranslator(r)
if cfg.DisableSoftwareControl {
http.Error(res, "Controls are disabled", http.StatusForbidden)
return
}
updater, err := github.NewUpdater(autoUpdateRepo, version)
if err != nil {
jsonResponse{
Success: false,
ErrorMessage: T("warn_no_new_version_found"),
}.Send(res, false)
log.Printf("Could not initialize update engine: %s", err)
return
}
if hasUpdate, err := updater.HasUpdate(true); err != nil {
jsonResponse{
Success: false,
ErrorMessage: err.Error(),
}.Send(res, false)
return
} else {
if !hasUpdate {
jsonResponse{
Success: false,
ErrorMessage: T("warn_no_new_version_found"),
}.Send(res, false)
return
}
}
if err := updater.Apply(); err != nil {
jsonResponse{
Success: false,
ErrorMessage: err.Error(),
}.Send(res, false)
} else {
jsonResponse{
Success: true,
ErrorMessage: T("warn_service_update_success"),
}.Send(res, false)
}
}
func handleUpdateDatabase(res http.ResponseWriter, r *http.Request) {
T := getTranslator(r)
if cfg.DisableSoftwareControl {
http.Error(res, "Controls are disabled", http.StatusForbidden)
return
}
if err := refreshEDSMData(); err != nil {
jsonResponse{
Success: false,
ErrorMessage: T("warn_database_update_failed"),
}.Send(res, false)
log.Printf("Database update failed: %s", err)
return
}
jsonResponse{
Success: true,
ErrorMessage: T("warn_database_update_success"),
}.Send(res, false)
}
func handleSystemByName(res http.ResponseWriter, r *http.Request) {
T := getTranslator(r)
search := r.URL.Query().Get("system_name")
if len(search) < 3 {
jsonResponse{
Success: false,
ErrorMessage: T("warn_too_few_characers"),
}.Send(res, true)
return
}
if sys := starSystems.GetSystemByName(search); sys != nil {
jsonResponse{
Success: true,
Data: map[string]interface{}{
"system": sys,
},
}.Send(res, true)
} else {
jsonResponse{
Success: false,
ErrorMessage: T("warn_no_matching_system_found"),
}.Send(res, true)
return
}
}
func handleRouteSocket(res http.ResponseWriter, r *http.Request) {
T := getTranslator(r)
// In case socket quits also quit all child operations
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ws, err := upgrader.Upgrade(res, r, nil)
if err != nil {
http.Error(res, "Could not open socket", http.StatusInternalServerError)
return
}
defer ws.Close()
doneChan := make(chan struct{})
defer close(doneChan)
go pingSocket(ws, doneChan)
messageChan := make(chan routeResponse, 500)
defer close(messageChan)
go func(ws *websocket.Conn, m chan routeResponse) {
for msg := range m {
ws.WriteJSON(msg)
}
}(ws, messageChan)
ws.SetReadLimit(maxMessageSize)
ws.SetReadDeadline(time.Now().Add(pongWait))
ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
calculationPool := make(chan *struct{}, calculationPoolSize)
for {
msg := routeRequest{}
if err := ws.ReadJSON(&msg); err != nil {
log.Printf("Experienced error: %s", err)
break
}
if msg.RouteRequestID == "" || msg.StartSystemID == 0 || msg.TargetSystemID == 0 {
messageChan <- routeResponse{
Success: false,
ErrorMessage: T("warn_required_field_missing"),
}
continue
}
if msg.StopDistance < cfg.WebRouteStopMin {
messageChan <- routeResponse{
Success: false,
ErrorMessage: T("warn_stop_distance_too_small", cfg),
}
continue
}
go processSocketRouting(ctx, messageChan, msg, calculationPool)
}
cancel()
}
func processSocketRouting(parentCtx context.Context, msgChan chan routeResponse, r routeRequest, calculationPool chan *struct{}) {
start := starSystems.GetSystemByID(r.StartSystemID)
target := starSystems.GetSystemByID(r.TargetSystemID)
calculationPool <- nil
defer func() { <-calculationPool }()
ctx, cancel := context.WithTimeout(parentCtx, cfg.WebRouteTimeout)
defer cancel()
rChan, eChan := starSystems.CalculateRoute(ctx, start, target, r.StopDistance)
var counter int64
for {
select {
case stop, ok := <-rChan:
if ok {
msgChan <- routeResponse{
Counter: counter,
Success: true,
RouteRequestID: r.RouteRequestID,
Result: stop,
}
if stop.TraceType == traceTypeFlightStop {
counter++
}
} else {
return
}
case err := <-eChan:
if err != nil {
msgChan <- routeResponse{
Success: false,
ErrorMessage: err.Error(),
}
return
}
}
}
}
func pingSocket(ws *websocket.Conn, done chan struct{}) {
ticker := time.NewTicker(pingPeriod)
defer ticker.Stop()
for {
select {
case <-ticker.C:
ws.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(writeWait))
case <-done:
return
}
}
}
|
[
4
] |
package libs
import (
"log"
"crypto/rand"
mrand "math/rand"
"net"
"errors"
"strings"
"strconv"
"crypto/hmac"
"crypto/sha1"
"encoding/binary"
"time"
"unsafe"
)
func getRelayAddress() (raddr net.IP) {
if external_ip != nil{
if IsValidIPv4(*external_ip) {
raddr = net.ParseIP(*external_ip).To4()
return
}
}
ipAddress , err := HostIP()
if err != nil {
raddr = net.ParseIP("110.110.110.110").To4()
Log.Error("Can not find relay address")
}else{
raddr = ipAddress
}
return
}
func strBytes2Int64(b []byte) int64 {
var x int64
for _, c := range b {
x = x*10 + int64(c - '0')
}
return x
}
func HmacSha1(value,key []byte) []byte {
hasher := hmac.New(sha1.New,key)
hasher.Write(value)
digest := hasher.Sum(nil)
return digest
}
func RandBytes(length int) (r []byte) {
if length < 64 {
r = make([]byte, length)
_, err := rand.Read(r)
if err != nil {
log.Panicln(err)
}
}else {
log.Panicf("the max length of randbyte is 64 , %d not supported \n",length)
}
return
}
func PrintModuleLoaded(moduleName string) {
log.Printf("< %s > module loads successfully",moduleName)
}
func PrintModuleRelease(moduleName string) {
log.Printf("< %s > module releases successfully",moduleName)
}
func HostIP() (ipAddress net.IP, err error) {
var ifaces []net.Interface
ifaces, err = net.Interfaces()
if err != nil {
return
}
for _, iface := range ifaces {
if iface.Flags&net.FlagUp == 0 {
continue // interface down
}
if iface.Flags&net.FlagLoopback != 0 {
continue // loopback interface
}
var addrs []net.Addr
addrs, err = iface.Addrs()
if err != nil {
return
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip == nil || ip.IsLoopback() {
continue
}
ip = ip.To4()
if ip == nil {
continue // not an ipv4 address
}
ipAddress = ip
return
}
}
err = errors.New("are you connected to the network?")
return
}
func IsValidIPv4(host string) bool {
parts := strings.Split(host, ".")
if len(parts) < 4 {
return false
}
for _,x := range parts {
if i, err := strconv.Atoi(x); err == nil {
if i < 0 || i > 255 {
return false
}
} else {
return false
}
}
return true
}
func RandIntRange(max,min int) int {
mrand.Seed(time.Now().UnixNano())
num := mrand.Intn(max - min) + min
Log.Infof("random :%d",num)
return num
}
func parseAddressV4(strAddress string) *net.UDPAddr {
arrAddr := strings.Split(strAddress,":")
port , _ := strconv.Atoi(arrAddr[1])
address := new(net.UDPAddr)
address.IP = net.ParseIP(arrAddr[0])
address.Port = port
return address
}
func generateTransactionID() []byte {
transID := make([]byte, 16)
binary.BigEndian.PutUint32(transID[:4], magicCookie)
rand.Read(transID[4:])
return transID
}
func str2bytes(s string)[] byte {
x := (*[2]uintptr)(unsafe.Pointer(&s))
h := [3]uintptr{x[0],x[1],x[1]}
return *(*[]byte)(unsafe.Pointer(&h))
}
func bytes2str(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
|
[
1
] |
package main
import (
"fmt"
)
func main() {
size := 10000
D := make([]int, size)
for i := 4; i < size; i++ {
d := 1
for j := 2; j*j <= i; j++ {
if i%j == 0 {
if q := i / j; q == j {
d = d + j
} else {
d = d + j + i/j
}
}
}
D[i] = d
}
sum := 0
for i := 4; i < size; i++ {
if D[i] != 1 {
for j := i + 1; j < size; j++ {
if D[i] == j && D[j] == i {
fmt.Printf("(%v, %v), ", i, j)
sum = sum + i + j
}
}
}
}
fmt.Println("")
fmt.Println("Sum of amicable numbers : ", sum)
}
|
[
0
] |
package parser
import (
"encoding/base64"
"github.com/aws/aws-lambda-go/events"
"testing"
)
const testBody = `POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"
text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file"; filename="file.txt"
Content-Type: text/plain
Hello World :)
-----------------------------9051914041544843365972754266`
const testContentType = "multipart/form-data; boundary=---------------------------9051914041544843365972754266"
func TestParse(t *testing.T) {
e := events.APIGatewayProxyRequest{
Body: testBody,
Headers: map[string]string{
"Content-Type": testContentType,
},
}
data, err := Parse(e)
if err != nil {
t.Errorf("unexpected error: %v", err)
return
}
txt, ok := data.Get("text")
if !ok {
t.Errorf("Expected to have a field for name 'text'.")
} else {
if txt != "text default" {
t.Errorf("Expected to have 'text default' in field 'text', but got: %s.\n", txt)
}
}
file, ok := data.File("file")
if !ok {
t.Errorf("Expected to have a file for name 'file'.")
} else {
if file.Type != "file" {
t.Errorf("Expected file type to be 'file', but got: %s", file.Type)
}
if file.Filename != "file.txt" {
t.Errorf("Expected filename to be 'file.txt', but got: %s", file.Filename)
}
if file.ContentType != "text/plain" {
t.Errorf("Expected content type to be 'text/plain' but got: %s", file.ContentType)
}
if string(file.Content) != "Hello World :)" {
t.Errorf("Exepected content to be 'Hello World :)' but got: %s", string(file.Content))
}
}
}
func TestParseWithBase64(t *testing.T) {
data := base64.StdEncoding.EncodeToString([]byte(testBody))
e := events.APIGatewayProxyRequest{
Body: data,
IsBase64Encoded: true,
Headers: map[string]string{
"Content-Type": testContentType,
},
}
_, err := Parse(e)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
t.Run("Invalid Base64 Data", func(t *testing.T) {
e := events.APIGatewayProxyRequest{
Body: "this isn't base64 data ;)",
IsBase64Encoded: true,
Headers: map[string]string{
"Content-Type": testContentType,
},
}
_, err := Parse(e)
if err == nil {
t.Errorf("expected an error")
}
})
}
func TestGetBoundary(t *testing.T) {
e := events.APIGatewayProxyRequest{
Headers: map[string]string{
"Content-Type": testContentType,
},
Body: testBody,
}
_, err := Parse(e)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
t.Run("Missing Content-Type Header", func(t *testing.T) {
e := events.APIGatewayProxyRequest{}
_, err := Parse(e)
if err == nil {
t.Errorf("expected an error")
}
})
t.Run("Invalid Content-Type Header", func(t *testing.T) {
e := events.APIGatewayProxyRequest{
Headers: map[string]string{
"Content-Type": "application/json",
},
}
_, err := Parse(e)
if err == nil {
t.Errorf("expected an error")
}
})
}
func BenchmarkParse(b *testing.B) {
b.SetBytes(int64(len(testContentType)))
e := events.APIGatewayProxyRequest{
Headers: map[string]string{
"Content-Type": testContentType,
},
Body: testBody,
}
for i := 0; i < b.N; i++ {
_, _ = Parse(e)
}
}
|
[
4
] |
package api
type ResolverServicePreferences struct {
s TypeServicePreferences
}
func (R *ResolverServicePreferences) Set(s TypeServicePreferences) {
R.s = s
}
func (R ResolverServicePreferences) ServiceId() int32 {
return R.s.ServiceId
}
func (R ResolverServicePreferences) PreferencesKey() *string {
return R.s.PreferencesKey
}
func (R ResolverServicePreferences) PreferencesValue() *string {
return R.s.PreferencesValue
}
func GenGqlTypeServicePreferences(extra string) string {
return "type ServicePreferences { " + extra + `
ServiceId: Int,
PreferencesKey: String,
PreferencesValue: String,
}`
}
|
[
2
] |
package main
import (
"log"
"github.com/veandco/go-sdl2/sdl"
)
type color struct {
r, g, b byte
}
func setPixels(x, y int, c color, pixels []byte) {
index := (y*800 + x) * 4
if index < len(pixels)-4 && index >= 0 {
pixels[index] = c.r
pixels[index+1] = c.g
pixels[index+2] = c.b
}
}
func main() {
err := sdl.Init(sdl.INIT_EVERYTHING)
if err != nil {
log.Fatal(err)
return
}
wind, e := sdl.CreateWindow("game_demo", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
800, 600, sdl.WINDOW_SHOWN)
if e != nil {
log.Fatal(e)
}
defer wind.Destroy()
renderer, err := sdl.CreateRenderer(wind, -1, sdl.RENDERER_ACCELERATED)
if err != nil {
log.Fatal(err)
}
defer renderer.Destroy()
tex, err := renderer.CreateTexture(sdl.PIXELFORMAT_ABGR8888, sdl.TEXTUREACCESS_STREAMING, 800, 600)
if err != nil {
log.Fatal(err)
return
}
defer tex.Destroy()
pixels := make([]byte, 800*600*4)
for y := 0; y < 600; y++ {
for x := 0; x < 800; x++ {
setPixels(x, y, color{byte(x % 255), 0, byte(y % 255)}, pixels)
}
}
_ = tex.Update(nil, pixels, 800*4)
_ = renderer.Copy(tex, nil, nil)
renderer.Present()
for {
for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
switch event.(type) {
case *sdl.QuitEvent:
return
}
}
sdl.Delay(16)
}
}
|
[
7
] |
package githttpxfer
import (
"net/http"
"net/url"
"testing"
)
func Test_Router_Append_should_append_route(t *testing.T) {
router := &router{}
router.Add(&Route{
http.MethodPost,
func(u *url.URL) *Match {
return matchSuffix(u.Path, "/foo")
},
func(ctx Context) {},
})
router.Add(&Route{
http.MethodPost,
func(u *url.URL) *Match {
return matchSuffix(u.Path, "/bar")
},
func(ctx Context) {},
})
length := len(router.routes)
expected := 2
if expected != length {
t.Errorf("router length is not %d . result: %d", expected, length)
}
}
func Test_Router_Match_should_match_route(t *testing.T) {
router := &router{}
router.Add(&Route{
http.MethodPost,
func(u *url.URL) *Match {
return matchSuffix(u.Path, "/foo")
},
func(ctx Context) {},
})
match, route, err := router.Match(http.MethodPost, &url.URL{Path: "/base/foo"})
if err != nil {
t.Errorf("error is %s", err.Error())
}
if http.MethodPost != route.Method {
t.Errorf("http method is not %s . result: %s", http.MethodPost, route.Method)
}
if "foo" != match.FilePath {
t.Errorf("match is not %s . result: %s", "foo", match.FilePath)
}
}
func Test_Router_Match_should_return_UrlNotFound_error(t *testing.T) {
router := &router{}
router.Add(&Route{
http.MethodPost,
func(u *url.URL) *Match {
return matchSuffix(u.Path, "/foo")
},
func(ctx Context) {},
})
match, route, err := router.Match(http.MethodPost, &url.URL{Path: "/base/hoge"})
if err == nil {
t.Error("error is nil.")
}
if match != nil {
t.Error("match is not empty.")
}
if route != nil {
t.Error("route is not nil.")
}
switch err.(type) {
case *URLNotFoundError:
return
}
t.Errorf("error is not UrlNotFound. %s", err.Error())
}
func Test_Router_Match_should_return_MethodNotAllowed_error(t *testing.T) {
router := &router{}
router.Add(&Route{
http.MethodPost,
func(u *url.URL) *Match {
return matchSuffix(u.Path, "/foo")
},
func(ctx Context) {},
})
match, route, err := router.Match(http.MethodGet, &url.URL{Path: "/base/foo"})
if err == nil {
t.Error("error is nil.")
}
if match != nil {
t.Error("match is not empty.")
}
if route != nil {
t.Error("route is not nil.")
}
if _, is := err.(*MethodNotAllowedError); !is {
t.Errorf("error is not MethodNotAllowed. %s", err.Error())
return
}
}
|
[
7
] |
package supportbundle
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"reflect"
"github.com/pkg/errors"
analyze "github.com/replicatedhq/troubleshoot/pkg/analyze"
troubleshootv1beta2 "github.com/replicatedhq/troubleshoot/pkg/apis/troubleshoot/v1beta2"
"github.com/replicatedhq/troubleshoot/pkg/collect"
"github.com/replicatedhq/troubleshoot/pkg/constants"
"github.com/replicatedhq/troubleshoot/pkg/convert"
"github.com/replicatedhq/troubleshoot/pkg/version"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"gopkg.in/yaml.v2"
"k8s.io/client-go/kubernetes"
)
func runHostCollectors(ctx context.Context, hostCollectors []*troubleshootv1beta2.HostCollect, additionalRedactors *troubleshootv1beta2.Redactor, bundlePath string, opts SupportBundleCreateOpts) (collect.CollectorResult, error) {
collectSpecs := make([]*troubleshootv1beta2.HostCollect, 0)
collectSpecs = append(collectSpecs, hostCollectors...)
allCollectedData := make(map[string][]byte)
var collectors []collect.HostCollector
for _, desiredCollector := range collectSpecs {
collector, ok := collect.GetHostCollector(desiredCollector, bundlePath)
if ok {
collectors = append(collectors, collector)
}
}
for _, collector := range collectors {
// TODO: Add context to host collectors
_, span := otel.Tracer(constants.LIB_TRACER_NAME).Start(ctx, collector.Title())
span.SetAttributes(attribute.String("type", reflect.TypeOf(collector).String()))
isExcluded, _ := collector.IsExcluded()
if isExcluded {
opts.ProgressChan <- fmt.Sprintf("[%s] Excluding host collector", collector.Title())
span.SetAttributes(attribute.Bool(constants.EXCLUDED, true))
span.End()
continue
}
opts.ProgressChan <- fmt.Sprintf("[%s] Running host collector...", collector.Title())
result, err := collector.Collect(opts.ProgressChan)
if err != nil {
span.SetStatus(codes.Error, err.Error())
opts.ProgressChan <- errors.Errorf("failed to run host collector: %s: %v", collector.Title(), err)
}
span.End()
for k, v := range result {
allCollectedData[k] = v
}
}
collectResult := allCollectedData
globalRedactors := []*troubleshootv1beta2.Redact{}
if additionalRedactors != nil {
globalRedactors = additionalRedactors.Spec.Redactors
}
if opts.Redact {
_, span := otel.Tracer(constants.LIB_TRACER_NAME).Start(ctx, "Host collectors")
span.SetAttributes(attribute.String("type", "Redactors"))
err := collect.RedactResult(bundlePath, collectResult, globalRedactors)
if err != nil {
err = errors.Wrap(err, "failed to redact host collector results")
span.SetStatus(codes.Error, err.Error())
return collectResult, err
}
span.End()
}
return collectResult, nil
}
func runCollectors(ctx context.Context, collectors []*troubleshootv1beta2.Collect, additionalRedactors *troubleshootv1beta2.Redactor, bundlePath string, opts SupportBundleCreateOpts) (collect.CollectorResult, error) {
var allCollectors []collect.Collector
var foundForbidden bool
collectSpecs := make([]*troubleshootv1beta2.Collect, 0)
collectSpecs = append(collectSpecs, collectors...)
collectSpecs = collect.EnsureCollectorInList(collectSpecs, troubleshootv1beta2.Collect{ClusterInfo: &troubleshootv1beta2.ClusterInfo{}})
collectSpecs = collect.EnsureCollectorInList(collectSpecs, troubleshootv1beta2.Collect{ClusterResources: &troubleshootv1beta2.ClusterResources{}})
collectSpecs = collect.DedupCollectors(collectSpecs)
collectSpecs = collect.EnsureClusterResourcesFirst(collectSpecs)
opts.KubernetesRestConfig.QPS = constants.DEFAULT_CLIENT_QPS
opts.KubernetesRestConfig.Burst = constants.DEFAULT_CLIENT_BURST
opts.KubernetesRestConfig.UserAgent = fmt.Sprintf("%s/%s", constants.DEFAULT_CLIENT_USER_AGENT, version.Version())
k8sClient, err := kubernetes.NewForConfig(opts.KubernetesRestConfig)
if err != nil {
return nil, errors.Wrap(err, "failed to instantiate Kubernetes client")
}
allCollectorsMap := make(map[reflect.Type][]collect.Collector)
allCollectedData := make(map[string][]byte)
for _, desiredCollector := range collectSpecs {
if collectorInterface, ok := collect.GetCollector(desiredCollector, bundlePath, opts.Namespace, opts.KubernetesRestConfig, k8sClient, opts.SinceTime); ok {
if collector, ok := collectorInterface.(collect.Collector); ok {
err := collector.CheckRBAC(ctx, collector, desiredCollector, opts.KubernetesRestConfig, opts.Namespace)
if err != nil {
return nil, errors.Wrap(err, "failed to check RBAC for collectors")
}
collectorType := reflect.TypeOf(collector)
allCollectorsMap[collectorType] = append(allCollectorsMap[collectorType], collector)
}
}
}
for _, collectors := range allCollectorsMap {
if mergeCollector, ok := collectors[0].(collect.MergeableCollector); ok {
mergedCollectors, err := mergeCollector.Merge(collectors)
if err != nil {
msg := fmt.Sprintf("failed to merge collector: %s: %s", mergeCollector.Title(), err)
opts.CollectorProgressCallback(opts.ProgressChan, msg)
}
allCollectors = append(allCollectors, mergedCollectors...)
} else {
allCollectors = append(allCollectors, collectors...)
}
foundForbidden = false
for _, collector := range collectors {
for _, e := range collector.GetRBACErrors() {
foundForbidden = true
opts.ProgressChan <- e
}
}
}
if foundForbidden && !opts.CollectWithoutPermissions {
return nil, collect.ErrInsufficientPermissionsToRun
}
for _, collector := range allCollectors {
_, span := otel.Tracer(constants.LIB_TRACER_NAME).Start(ctx, collector.Title())
span.SetAttributes(attribute.String("type", reflect.TypeOf(collector).String()))
isExcluded, _ := collector.IsExcluded()
if isExcluded {
msg := fmt.Sprintf("excluding %q collector", collector.Title())
opts.CollectorProgressCallback(opts.ProgressChan, msg)
span.SetAttributes(attribute.Bool(constants.EXCLUDED, true))
span.End()
continue
}
// skip collectors with RBAC errors unless its the ClusterResources collector
if collector.HasRBACErrors() {
if _, ok := collector.(*collect.CollectClusterResources); !ok {
msg := fmt.Sprintf("skipping collector %q with insufficient RBAC permissions", collector.Title())
opts.CollectorProgressCallback(opts.ProgressChan, msg)
span.SetStatus(codes.Error, "skipping collector, insufficient RBAC permissions")
span.End()
continue
}
}
opts.CollectorProgressCallback(opts.ProgressChan, collector.Title())
result, err := collector.Collect(opts.ProgressChan)
if err != nil {
span.SetStatus(codes.Error, err.Error())
opts.ProgressChan <- errors.Errorf("failed to run collector: %s: %v", collector.Title(), err)
}
for k, v := range result {
allCollectedData[k] = v
}
span.End()
}
collectResult := allCollectedData
globalRedactors := []*troubleshootv1beta2.Redact{}
if additionalRedactors != nil {
globalRedactors = additionalRedactors.Spec.Redactors
}
if opts.Redact {
// TODO: Should we record how long each redactor takes?
_, span := otel.Tracer(constants.LIB_TRACER_NAME).Start(ctx, "In-cluster collectors")
span.SetAttributes(attribute.String("type", "Redactors"))
err := collect.RedactResult(bundlePath, collectResult, globalRedactors)
if err != nil {
err := errors.Wrap(err, "failed to redact in cluster collector results")
span.SetStatus(codes.Error, err.Error())
span.End()
return collectResult, err
}
span.End()
}
return collectResult, nil
}
func findFileName(basename, extension string) (string, error) {
n := 1
name := basename
for {
filename := name + "." + extension
if _, err := os.Stat(filename); os.IsNotExist(err) {
return filename, nil
} else if err != nil {
return "", errors.Wrap(err, "check file exists")
}
name = fmt.Sprintf("%s (%d)", basename, n)
n = n + 1
}
}
func getVersionFile() (io.Reader, error) {
version := troubleshootv1beta2.SupportBundleVersion{
ApiVersion: "troubleshoot.sh/v1beta2",
Kind: "SupportBundle",
Spec: troubleshootv1beta2.SupportBundleVersionSpec{
VersionNumber: version.Version(),
},
}
b, err := yaml.Marshal(version)
if err != nil {
return nil, errors.Wrap(err, "failed to marshal version data")
}
return bytes.NewBuffer(b), nil
}
const AnalysisFilename = "analysis.json"
func getAnalysisFile(analyzeResults []*analyze.AnalyzeResult) (io.Reader, error) {
data := convert.FromAnalyzerResult(analyzeResults)
analysis, err := json.MarshalIndent(data, "", " ")
if err != nil {
return nil, errors.Wrap(err, "failed to marshal analysis")
}
return bytes.NewBuffer(analysis), nil
}
|
[
0
] |
package main
import "fmt"
type heap interface {
Less(i, j int) bool
Swap(i, j int)
Len() int
Push(x interface{})
Pop() interface{}
}
func buildHeap(h heap) {
n := h.Len()
for i := n/2-1; i >= 0; i-- {
down(h, i, n)
}
}
func up(h heap, i int) {
for {
j := (i-1)/2
if j == i || !h.Less(i, j) {
break
}
h.Swap(i, j)
i = j
}
}
func down(h heap, i, n int) bool { // n is the length of h, so j1 can't be equal to n
i0 := i
smallest := i
for {
j1 := 2*i+1
if j1 >= n || j1 < 0 {
break
}
if h.Less(j1, smallest) {
smallest = j1
}
j2 := j1+1
if j2 < n && h.Less(j2, smallest) {
smallest = j2
}
if i == smallest {
break
}
h.Swap(i, smallest)
i = smallest
}
return i0 < smallest
}
func Remove(h heap, i int) {
n := h.Len() - 1
if n != i {
h.Swap(i, n)
if !down(h, i, n) {
up(h, i)
}
}
}
func Fix(h heap, i int) {
if !down(h, i, h.Len()) {
up(h, i)
}
}
func HeapSortv2(h heap) {
buildHeap(h)
n := h.Len()-1
for n > 0 {
h.Swap(0, n)
down(h, 0, n)
n--
}
}
func Push(h heap, x interface{}) {
h.Push(x)
up(h, h.Len()-1)
}
func Pop(h heap) interface{} {
n := h.Len() - 1
h.Swap(0, n)
down(h, 0, n)
return h.Pop()
}
type tmp []int
func (t tmp) Len() int {
return len(t)
}
func (t tmp) Swap(i, j int) {
t[i], t[j] = t[j], t[i]
}
func (t tmp) Less(i, j int) bool {
return t[i] < t[j]
}
func (t *tmp) Push(x interface{}) {
*t = append(*t, x.(int))
}
func (t *tmp) Pop() interface{} {
old := *t
n := len(old)
x := old[n-1]
*t = old[0 : n-1]
return x
}
func TopM(M int, input []int) *tmp{
MinQ := &tmp{}
buildHeap(MinQ)
for _, x := range input {
Push(MinQ, x)
if MinQ.Len() > M {
Pop(MinQ)
}
}
return MinQ
}
func main() {
input := []int{1, 3, 4, 9, 10, 5, 7, 4, 9, 10, 22, 33, 99, 1, 100, 98}
r :=TopM(3, input)
fmt.Println(*r)
}
|
[
2
] |
package cmd
type Settings struct {
Persistent *persistent `json:"persistent"`
}
type persistent struct {
Cluster *cluster `json:"cluster,omitempty"`
Script *script `json:"script,omitempty"`
Indices *indices `json:"indices,omitempty"`
}
type cluster struct {
Routing *routing `json:"routing,omitempty"`
MaxShardsPerNode string `json:"max_shards_per_node,omitempty"`
}
type script struct {
MaxCompilationsRate string `json:"max_compilations_rate,omitempty"`
}
type indices struct {
Breaker *breaker `json:"breaker,omitempty"`
Recovery *recovery `json:"recovery,omitempty"`
}
type recovery struct {
MaxBytesPerSec string `json:"max_bytes_per_sec,omitempty"`
}
type routing struct {
Allocation *allocation `json:"allocation,omitempty"`
}
type allocation struct {
ClusterConcurrentRebalanced string `json:"cluster_concurrent_rebalance,omitempty"`
NodeConcurrentRecoveries string `json:"node_concurrent_recoveries,omitempty"`
NodeInitialPrimariesRecoveries string `json:"node_initial_primaries_recoveries,omitempty"`
Disk *disk `json:"disk,omitempty"`
Enable string `json:"enable,omitempty"`
}
type disk struct {
Watermark *watermark `json:"watermark,omitempty"`
}
type watermark struct {
High string `json:"high,omitempty"`
Low string `json:"low,omitempty"`
}
type breaker struct {
Fielddata *fielddata `json:"fielddata,omitempty"`
Request *request `json:"request,omitempty"`
Total *total `json:"total,omitempty"`
}
type fielddata struct {
Limit string `json:"limit,omitempty"`
}
type request struct {
Limit string `json:"limit,omitempty"`
}
type total struct {
Limit string `json:"limit,omitempty"`
}
func (S *Settings) WithAllocationSettings(ClusterConcurrentRebalanced, NodeConcurrentRecoveries, NodeInitialPrimariesRecoveries, Enable string) *Settings {
if len(ClusterConcurrentRebalanced) == 0 && len(NodeConcurrentRecoveries) == 0 && len(NodeInitialPrimariesRecoveries) == 0 && len(Enable) == 0 {
return S
}
if S.Persistent.Cluster != nil && S.Persistent.Cluster.Routing != nil {
if S.Persistent.Cluster.Routing.Allocation != nil {
S.Persistent.Cluster.Routing.Allocation.NodeInitialPrimariesRecoveries = NodeInitialPrimariesRecoveries
S.Persistent.Cluster.Routing.Allocation.ClusterConcurrentRebalanced = ClusterConcurrentRebalanced
S.Persistent.Cluster.Routing.Allocation.NodeConcurrentRecoveries = NodeConcurrentRecoveries
S.Persistent.Cluster.Routing.Allocation.Enable = Enable
} else {
S.Persistent.Cluster.Routing.Allocation = &allocation{
ClusterConcurrentRebalanced: ClusterConcurrentRebalanced,
NodeConcurrentRecoveries: NodeConcurrentRecoveries,
NodeInitialPrimariesRecoveries: NodeInitialPrimariesRecoveries,
Enable: Enable,
}
}
} else {
S.Persistent.Cluster = &cluster{
Routing: &routing{
Allocation: &allocation{
ClusterConcurrentRebalanced: ClusterConcurrentRebalanced,
NodeConcurrentRecoveries: NodeConcurrentRecoveries,
NodeInitialPrimariesRecoveries: NodeInitialPrimariesRecoveries,
Enable: Enable,
},
},
}
}
return S
}
func (S *Settings) WithBreakerFielddata(BreakerFielddata string) *Settings {
if len(BreakerFielddata) == 0 {
return S
}
if S.Persistent.Indices != nil {
S.Persistent.Indices.Breaker.Fielddata = &fielddata{
Limit: BreakerFielddata,
}
} else {
S.Persistent.Indices = &indices{
Breaker: &breaker{
Fielddata: &fielddata{
Limit: BreakerFielddata,
},
},
}
}
return S
}
func (S *Settings) WithBreakerRequest(BreakerRequest string) *Settings {
if len(BreakerRequest) == 0 {
return S
}
if S.Persistent.Indices != nil {
S.Persistent.Indices.Breaker.Request = &request{
Limit: BreakerRequest,
}
} else {
S.Persistent.Indices = &indices{
Breaker: &breaker{
Request: &request{
Limit: BreakerRequest,
},
},
}
}
return S
}
func (S *Settings) WithBreakerTotal(BreakerTotal string) *Settings {
if len(BreakerTotal) == 0 {
return S
}
if S.Persistent.Indices != nil {
S.Persistent.Indices.Breaker.Total = &total{
Limit: BreakerTotal,
}
} else {
S.Persistent.Indices = &indices{
Breaker: &breaker{
Total: &total{
Limit: BreakerTotal,
},
},
}
}
return S
}
func (S *Settings) WithWatermark(High, Low string) *Settings {
if len(High) == 0 && len(Low) == 0 {
return S
}
if S.Persistent.Cluster != nil && S.Persistent.Cluster.Routing != nil {
S.Persistent.Cluster.Routing.Allocation.Disk = &disk{
Watermark: &watermark{
Low: Low,
High: High,
},
}
} else {
S.Persistent.Cluster = &cluster{
Routing: &routing{
Allocation: &allocation{
Disk: &disk{
Watermark: &watermark{
Low: Low,
High: High,
},
},
},
},
}
}
return S
}
func (S *Settings) WithRecovery(MaxBytesPerSec string) *Settings {
if len(MaxBytesPerSec) == 0 {
return S
}
if S.Persistent.Indices != nil {
S.Persistent.Indices.Recovery = &recovery{
MaxBytesPerSec: MaxBytesPerSec,
}
} else {
S.Persistent.Indices = &indices{
Recovery: &recovery{
MaxBytesPerSec: MaxBytesPerSec,
},
}
}
return S
}
func (S *Settings) WithMaxShardsPerNode(MaxShardsPerNode string) *Settings {
if len(MaxShardsPerNode) == 0 {
return S
}
if S.Persistent.Cluster != nil {
S.Persistent.Cluster.MaxShardsPerNode = MaxShardsPerNode
} else {
S.Persistent.Cluster = &cluster{
MaxShardsPerNode: MaxShardsPerNode,
}
}
return S
}
func (S *Settings) WithMaxCompilationsRate(MaxCompilationsRate string) *Settings {
if len(MaxCompilationsRate) == 0 {
return S
}
S.Persistent.Script = &script{MaxCompilationsRate: MaxCompilationsRate}
return S
}
func NewSettings() *Settings {
return &Settings{Persistent: &persistent{}}
}
|
[
2
] |
package tools
import "fmt"
import "io/ioutil"
import "io"
import "path"
import "time"
import "os"
import "strings"
func FindImgs(){
i:=0
fmt.Println("整理图片开始")
tstr:=time.Now().Format("2006_01_02_15_04_05")
folerName:="整理图片"+tstr
os.Mkdir(folerName,os.ModePerm)
files,_:=ioutil.ReadDir("./")
for _,f := range files{
fname:=f.Name()
fmt.Println("扫描文件",fname)
lowname := strings.ToLower(fname)
if strings.HasSuffix(lowname,".jpg") ||
strings.HasSuffix(lowname,".gif") ||
strings.HasSuffix(lowname,".png") ||
strings.HasSuffix(lowname,".jpeg") {
fmt.Println("正在整理:",fname)
copyToFolder(folerName,fname)
i=i+1
}
}
fmt.Println("正在整理完毕共",i,"个")
time.Sleep(3*1000*1000*1000)
}
func copyToFolder(folderName,file string)(int64, error){
sFile,err:= os.Open(file)
defer sFile.Close()
if err!=nil {
return 999,err
}
dFile,err:=os.OpenFile(path.Join(folderName,file),os.O_WRONLY|os.O_CREATE,0)
defer dFile.Close()
if err != nil {
return 998,err
}
return io.Copy(dFile,sFile)
}
|
[
0
] |
// 解説AC。問題文読み違えて苦戦
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func max(nums ...int) int {
ret := nums[0]
for _, v := range nums {
if v > ret {
ret = v
}
}
return ret
}
func min(nums ...int) int {
ret := nums[0]
for _, v := range nums {
if v < ret {
ret = v
}
}
return ret
}
func main() {
sc.Split(bufio.ScanWords)
n := nextInt()
col := make([]int, 9)
for i := 0; i < n; i++ {
r := nextInt() / 400
if r >= 9 {
r = 8
}
col[r]++
}
maxAns := 0
for i := 0; i < 8; i++ {
if col[i] > 0 {
maxAns++
}
}
maxAns = maxAns + col[8]
minAns := 0
for i := 0; i < 8; i++ {
if col[i] > 0 {
minAns++
}
}
if minAns == 0 {
minAns = 1
}
puts(minAns, maxAns)
wt.Flush()
}
var (
sc = bufio.NewScanner(os.Stdin)
wt = bufio.NewWriter(os.Stdout)
)
func next() string {
sc.Scan()
return sc.Text()
}
func nextInt() int {
i, _ := strconv.Atoi(next())
return i
}
func puts(a ...interface{}) {
fmt.Fprintln(wt, a...)
}
|
[
0
] |
package goshopify
import (
"context"
"fmt"
"time"
)
const webhooksBasePath = "admin/webhooks"
// WebhookService is an interface for interfacing with the webhook endpoints of
// the Shopify API.
// See: https://help.shopify.com/api/reference/webhook
type WebhookService interface {
List(context.Context, interface{}) ([]Webhook, error)
Count(context.Context, interface{}) (int, error)
Get(context.Context, int, interface{}) (*Webhook, error)
Create(context.Context, Webhook) (*Webhook, error)
Update(context.Context, Webhook) (*Webhook, error)
Delete(context.Context, int) error
}
// WebhookServiceOp handles communication with the webhook-related methods of
// the Shopify API.
type WebhookServiceOp struct {
client *Client
}
// Webhook represents a Shopify webhook
type Webhook struct {
ID int `json:"id"`
Address string `json:"address"`
Topic string `json:"topic"`
Format string `json:"format"`
CreatedAt *time.Time `json:"created_at,omitempty"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
Fields []string `json:"fields"`
MetafieldNamespaces []string `json:"metafield_namespaces"`
}
// WebhookOptions can be used for filtering webhooks on a List request.
type WebhookOptions struct {
Address string `url:"address,omitempty"`
Topic string `url:"topic,omitempty"`
}
// WebhookResource represents the result from the admin/webhooks.json endpoint
type WebhookResource struct {
Webhook *Webhook `json:"webhook"`
}
// WebhooksResource is the root object for a webhook get request.
type WebhooksResource struct {
Webhooks []Webhook `json:"webhooks"`
}
// List webhooks
func (s *WebhookServiceOp) List(ctx context.Context, options interface{}) ([]Webhook, error) {
path := fmt.Sprintf("%s.json", webhooksBasePath)
resource := new(WebhooksResource)
err := s.client.Get(ctx, path, resource, options)
return resource.Webhooks, err
}
// Count webhooks
func (s *WebhookServiceOp) Count(ctx context.Context, options interface{}) (int, error) {
path := fmt.Sprintf("%s/count.json", webhooksBasePath)
return s.client.Count(ctx, path, options)
}
// Get individual webhook
func (s *WebhookServiceOp) Get(ctx context.Context, webhookdID int, options interface{}) (*Webhook, error) {
path := fmt.Sprintf("%s/%d.json", webhooksBasePath, webhookdID)
resource := new(WebhookResource)
err := s.client.Get(ctx, path, resource, options)
return resource.Webhook, err
}
// Create a new webhook
func (s *WebhookServiceOp) Create(ctx context.Context, webhook Webhook) (*Webhook, error) {
path := fmt.Sprintf("%s.json", webhooksBasePath)
wrappedData := WebhookResource{Webhook: &webhook}
resource := new(WebhookResource)
err := s.client.Post(ctx, path, wrappedData, resource)
return resource.Webhook, err
}
// Update an existing webhook.
func (s *WebhookServiceOp) Update(ctx context.Context, webhook Webhook) (*Webhook, error) {
path := fmt.Sprintf("%s/%d.json", webhooksBasePath, webhook.ID)
wrappedData := WebhookResource{Webhook: &webhook}
resource := new(WebhookResource)
err := s.client.Put(ctx, path, wrappedData, resource)
return resource.Webhook, err
}
// Delete an existing webhooks
func (s *WebhookServiceOp) Delete(ctx context.Context, ID int) error {
return s.client.Delete(ctx, fmt.Sprintf("%s/%d.json", webhooksBasePath, ID))
}
|
[
2
] |
package http
import (
"crypto/tls"
"crypto/x509"
ioutil2 "io/ioutil"
"log"
"net"
"net/http"
"sync"
"time"
"github.com/vadv/gopher-lua-libs/aws/cloudwatch"
"github.com/vadv/gopher-lua-libs/cert_util"
"github.com/vadv/gopher-lua-libs/chef"
"github.com/vadv/gopher-lua-libs/cmd"
"github.com/vadv/gopher-lua-libs/crypto"
"github.com/vadv/gopher-lua-libs/db"
"github.com/vadv/gopher-lua-libs/filepath"
"github.com/vadv/gopher-lua-libs/goos"
http_client "github.com/vadv/gopher-lua-libs/http/client"
http_util "github.com/vadv/gopher-lua-libs/http/util"
"github.com/vadv/gopher-lua-libs/humanize"
"github.com/vadv/gopher-lua-libs/inspect"
"github.com/vadv/gopher-lua-libs/ioutil"
"github.com/vadv/gopher-lua-libs/json"
lua_log "github.com/vadv/gopher-lua-libs/log"
"github.com/vadv/gopher-lua-libs/prometheus/client"
"github.com/vadv/gopher-lua-libs/regexp"
"github.com/vadv/gopher-lua-libs/runtime"
"github.com/vadv/gopher-lua-libs/storage"
"github.com/vadv/gopher-lua-libs/strings"
"github.com/vadv/gopher-lua-libs/tac"
"github.com/vadv/gopher-lua-libs/tcp"
"github.com/vadv/gopher-lua-libs/telegram"
"github.com/vadv/gopher-lua-libs/template"
lua_time "github.com/vadv/gopher-lua-libs/time"
"github.com/vadv/gopher-lua-libs/xmlpath"
"github.com/vadv/gopher-lua-libs/yaml"
"github.com/vadv/gopher-lua-libs/zabbix"
lua "github.com/yuin/gopher-lua"
)
type luaServer struct {
*http.Server
net.Listener
sync.Mutex
serveData chan *serveData
err error
}
type serveData struct {
w http.ResponseWriter
req *http.Request
done chan bool
}
func checkServer(L *lua.LState, n int) *luaServer {
ud := L.CheckUserData(n)
if v, ok := ud.Value.(*luaServer); ok {
return v
}
L.ArgError(n, "http server excepted")
return nil
}
// run serve
func (s *luaServer) serve(L *lua.LState) {
// start serve
go func() {
s.err = http.Serve(s.Listener, s)
}()
// process shutdown
go func(s *luaServer) {
ctx := L.Context()
if ctx != nil {
select {
case <-ctx.Done():
s.Listener.Close()
}
}
}(s)
}
// http.server(bind, handler) returns (user data, error)
func New(L *lua.LState) int {
var tlsConfig *tls.Config
bind := "127.0.0.1:0"
switch bindOrTable := L.CheckAny(1).(type) {
case lua.LString:
bind = string(bindOrTable)
case *lua.LTable:
if addr, ok := L.GetField(bindOrTable, "addr").(lua.LString); ok {
bind = string(addr)
}
serverPublicCertPEMFile := L.GetField(bindOrTable, `server_public_cert_pem_file`)
serverPrivateKeyPemFile := L.GetField(bindOrTable, `server_private_key_pem_file`)
if serverPublicCertPEMFile != lua.LNil && serverPrivateKeyPemFile != lua.LNil {
serverCert, err := tls.LoadX509KeyPair(serverPublicCertPEMFile.String(), serverPrivateKeyPemFile.String())
if err != nil {
L.RaiseError("error loading server cert: %v", err)
}
tlsConfig = &tls.Config{
Certificates: []tls.Certificate{serverCert},
}
clientAuth := L.GetField(bindOrTable, "client_auth")
if clientAuth != lua.LNil {
if _, ok := clientAuth.(lua.LString); !ok {
L.ArgError(1, "client_auth should be a string")
}
switch clientAuth.String() {
case "NoClientCert":
tlsConfig.ClientAuth = tls.NoClientCert
case "RequestClientCert":
tlsConfig.ClientAuth = tls.RequestClientCert
case "RequireAnyClientCert":
tlsConfig.ClientAuth = tls.RequireAnyClientCert
case "VerifyClientCertIfGiven":
tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven
case "RequireAndVerifyClientCert":
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
}
}
clientCAs := L.GetField(bindOrTable, "client_cas_pem_file")
if clientCAs != lua.LNil {
if _, ok := clientCAs.(lua.LString); !ok {
L.ArgError(1, "client_cas_pem_file must be a string")
}
data, err := ioutil2.ReadFile(clientCAs.String())
if err != nil {
L.RaiseError("error reading %s: %v", clientCAs, err)
}
tlsConfig.ClientCAs = x509.NewCertPool()
if !tlsConfig.ClientCAs.AppendCertsFromPEM(data) {
L.RaiseError("no certs loaded from %s", clientCAs)
}
}
}
}
l, err := net.Listen(`tcp`, bind)
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
if tlsConfig != nil {
l = tls.NewListener(l, tlsConfig)
}
server := &luaServer{
Listener: l,
serveData: make(chan *serveData, 1),
}
server.serve(L)
ud := L.NewUserData()
ud.Value = server
L.SetMetatable(ud, L.GetTypeMetatable("http_server_ud"))
L.Push(ud)
return 1
}
// Accept lua http_server_ud:accept() returns request_table, http_server_response_writer_ud
func Accept(L *lua.LState) int {
s := checkServer(L, 1)
select {
case data := <-s.serveData:
L.Push(NewRequest(L, data.req))
L.Push(NewWriter(L, data.w, data.req, data.done))
return 2
}
}
// Addr returns the address if, for instance, one listens on :0
func Addr(L *lua.LState) int {
s := checkServer(L, 1)
L.Push(lua.LString(s.Listener.Addr().String()))
return 1
}
func newHandlerState(data *serveData) *lua.LState {
state := lua.NewState()
lua_time.Preload(state)
strings.Preload(state)
filepath.Preload(state)
ioutil.Preload(state)
regexp.Preload(state)
tac.Preload(state)
inspect.Preload(state)
yaml.Preload(state)
cmd.Preload(state)
json.Preload(state)
tcp.Preload(state)
xmlpath.Preload(state)
db.Preload(state)
cert_util.Preload(state)
runtime.Preload(state)
telegram.Preload(state)
zabbix.Preload(state)
crypto.Preload(state)
goos.Preload(state)
storage.Preload(state)
humanize.Preload(state)
chef.Preload(state)
template.Preload(state)
http_client.Preload(state)
lua_log.Preload(state)
cloudwatch.Preload(state)
http_util.Preload(state)
prometheus_client.Preload(state)
httpServerResponseWriterUD := state.NewTypeMetatable(`http_server_response_writer_ud`)
state.SetGlobal(`http_server_response_writer_ud`, httpServerResponseWriterUD)
state.SetField(httpServerResponseWriterUD, "__index", state.SetFuncs(state.NewTable(), map[string]lua.LGFunction{
"code": HeaderCode,
"header": Header,
"write": Write,
"redirect": Redirect,
"done": Done,
}))
state.SetGlobal("request", NewRequest(state, data.req))
state.SetGlobal("response", NewWriter(state, data.w, data.req, data.done))
return state
}
// HandleFile lua http_server_ud:handler_file(filename)
func HandleFile(L *lua.LState) int {
s := checkServer(L, 1)
file := L.CheckString(2)
for {
select {
case data := <-s.serveData:
go func(sData *serveData, filename string) {
state := newHandlerState(data)
defer state.Close()
if err := state.DoFile(filename); err != nil {
log.Printf("[ERROR] handle file %s: %s\n", filename, err.Error())
data.done <- true
log.Printf("[ERROR] closed connection\n")
}
}(data, file)
}
}
return 0
}
// HandleString lua http_server_ud:handle_string(body)
func HandleString(L *lua.LState) int {
s := checkServer(L, 1)
body := L.CheckString(2)
for {
select {
case data := <-s.serveData:
go func(sData *serveData, content string) {
state := newHandlerState(sData)
defer state.Close()
if err := state.DoString(content); err != nil {
log.Printf("[ERROR] handle: %s\n", err.Error())
data.done <- true
log.Printf("[ERROR] closed connection\n")
}
}(data, body)
}
}
return 0
}
// HandleFunction lua http_server_ud:handle_function(func(response, request))
func HandleFunction(L *lua.LState) int {
s := checkServer(L, 1)
f := L.CheckFunction(2)
if len(f.Upvalues) > 0 {
L.ArgError(2, "cannot pass closures")
}
// Stash any args to pass to the function beyond response and request
var args []lua.LValue
top := L.GetTop()
for i := 3; i <= top; i++ {
args = append(args, L.Get(i))
}
for {
select {
case data := <-s.serveData:
go func(sData *serveData) {
state := newHandlerState(sData)
defer state.Close()
response := state.GetGlobal("response")
request := state.GetGlobal("request")
f := state.NewFunctionFromProto(f.Proto)
state.Push(f)
state.Push(response)
state.Push(request)
// Push any extra args
for _, arg := range args {
state.Push(arg)
}
if err := state.PCall(2+len(args), 0, nil); err != nil {
log.Printf("[ERROR] handle: %s\n", err.Error())
data.done <- true
log.Printf("[ERROR] closed connection\n")
}
state.Pop(state.GetTop())
}(data)
}
}
}
// ServeHTTP interface realisation
func (s *luaServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
doneChan := make(chan bool)
data := &serveData{w: w, req: req, done: doneChan}
// send data for lua
s.serveData <- data
// wait response from lua
select {
case <-doneChan:
return
case <-time.After(time.Minute):
doneChan <- true
}
}
|
[
2
] |
// Package pythagorean implements finding Pythagorean triplets.
package pythagorean
type Triplet [3]int
// Sum returns a list of all Pythagorean triplets where the sum a+b+c
// (the perimeter) is equal to p.
func Sum(sum int) (out []Triplet) {
for _, x := range Range(1, sum/2) {
if x[0]+x[1]+x[2] == sum {
out = append(out, x)
}
}
return
}
// Range returns a list of all Pythagorean triplets with sides in the
// range min to max inclusive.
func Range(min, max int) (out []Triplet) {
out0 := append(out, Triplet{0, 0, 0})
for a := min; a <= max; a++ {
for b := a; b <= max; b++ {
for c := b; c <= max; c++ {
if c*c == a*a+b*b {
out0 = append(out0, Triplet{a, b, c})
}
}
}
}
out = out0[1:]
return
}
|
[
1
] |
package conf
import (
"fmt"
"math"
"strings"
cfg "github.com/splitio/go-split-commons/v3/conf"
)
const (
defaultImpressionSyncOptimized = 300
defaultImpressionSync = 60
minImpressionSyncDebug = 1
)
func checkImpressionsPostRate() error {
if Data.ImpressionsPostRate == 0 {
Data.ImpressionsPostRate = defaultImpressionSyncOptimized
} else {
if Data.ImpressionsPostRate < defaultImpressionSync {
return fmt.Errorf("ImpressionsPostRate must be >= %d. Actual is: %d", defaultImpressionSync, Data.ImpressionsPostRate)
}
Data.ImpressionsPostRate = int(math.Max(float64(defaultImpressionSync), float64(Data.ImpressionsPostRate)))
}
return nil
}
// ValidConfigs checks configs
func ValidConfigs() error {
Data.ImpressionsMode = strings.ToLower(Data.ImpressionsMode)
switch Data.ImpressionsMode {
case cfg.ImpressionsModeOptimized:
return checkImpressionsPostRate()
case cfg.ImpressionsModeDebug:
if Data.ImpressionsPostRate == 0 {
Data.ImpressionsPostRate = defaultImpressionSync
} else {
if Data.ImpressionsPostRate < minImpressionSyncDebug {
return fmt.Errorf("ImpressionsPostRate must be >= %d. Actual is: %d", minImpressionSyncDebug, Data.ImpressionsPostRate)
}
}
default:
fmt.Println(`You passed an invalid impressionsMode, impressionsMode should be one of the following values: 'debug' or 'optimized'. Defaulting to 'optimized' mode.`)
Data.ImpressionsMode = cfg.ImpressionsModeOptimized
return checkImpressionsPostRate()
}
return nil
}
|
[
4
] |
package metadata
import (
"encoding/json"
"fmt"
"strings"
"github.com/docker/infrakit/pkg/cli"
"github.com/docker/infrakit/pkg/spi/metadata"
"github.com/docker/infrakit/pkg/types"
"github.com/sergi/go-diff/diffmatchpatch"
"github.com/spf13/cobra"
)
func prettyPrintYAML(any *types.Any) ([]byte, error) {
return any.MarshalYAML()
}
func prettyPrintJSON(any *types.Any) ([]byte, error) {
var v interface{}
err := any.Decode(&v)
if err != nil {
return any.MarshalJSON()
}
return json.MarshalIndent(v, "", " ")
}
// Change returns the Change command
func Change(name string, services *cli.Services) *cobra.Command {
change := &cobra.Command{
Use: "change k1=v1 [, k2=v2]+",
Short: "Update metadata where args are key=value pairs and keys are within namespace of the plugin.",
}
printYAML := change.Flags().BoolP("yaml", "y", false, "Show diff in YAML")
commitChange := change.Flags().BoolP("commit", "c", false, "Commit changes")
updatablePlugin, err := loadPluginUpdatable(services.Scope.Plugins(), name)
if err != nil {
return nil
}
cli.MustNotNil(updatablePlugin, "updatable metadata plugin not found", "name", name)
change.RunE = func(cmd *cobra.Command, args []string) error {
printer := prettyPrintJSON
if *printYAML {
printer = prettyPrintYAML
}
// get the changes
changes, err := changeSet(args)
if err != nil {
return err
}
current, proposed, cas, err := updatablePlugin.Changes(changes)
if err != nil {
return err
}
currentBuff, err := printer(current)
if err != nil {
return err
}
proposedBuff, err := printer(proposed)
if err != nil {
return err
}
if *commitChange {
fmt.Printf("Committing %d changes, hash=%s\n", len(changes), cas)
} else {
fmt.Printf("Proposing %d changes, hash=%s\n", len(changes), cas)
}
// Render the delta
dmp := diffmatchpatch.New()
diffs := dmp.DiffMain(string(currentBuff), string(proposedBuff), false)
fmt.Println(dmp.DiffPrettyText(diffs))
if *commitChange {
return updatablePlugin.Commit(proposed, cas)
}
return nil
}
return change
}
// changeSet returns a set of changes from the input pairs of path / value
func changeSet(kvPairs []string) ([]metadata.Change, error) {
changes := []metadata.Change{}
for _, kv := range kvPairs {
parts := strings.SplitN(kv, "=", 2)
key := strings.Trim(parts[0], " \t\n")
value := strings.Trim(parts[1], " \t\n")
change := metadata.Change{
Path: types.PathFromString(key),
Value: types.AnyYAMLMust([]byte(value)),
}
changes = append(changes, change)
}
return changes, nil
}
|
[
1
] |
// Copyright 2014,2015,2016,2017,2018,2019,2020,2021 SeukWon Kang ([email protected])
// 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 clientfloor
import (
"fmt"
"math/rand"
"time"
"github.com/kasworld/findnear"
"github.com/kasworld/goguelike/enum/way9type"
"github.com/kasworld/goguelike/game/bias"
"github.com/kasworld/goguelike/game/tilearea"
"github.com/kasworld/goguelike/game/tilearea4pathfind"
"github.com/kasworld/goguelike/game/visitarea"
"github.com/kasworld/goguelike/lib/uuidposman_map"
"github.com/kasworld/goguelike/lib/uuidposmani"
"github.com/kasworld/goguelike/protocol_c2t/c2t_obj"
"github.com/kasworld/wrapper"
)
type ClientFloor struct {
FloorInfo *c2t_obj.FloorInfo
Tiles tilearea.TileArea `prettystring:"simple"`
Visited *visitarea.VisitArea `prettystring:"simple"`
XWrapper *wrapper.Wrapper `prettystring:"simple"`
YWrapper *wrapper.Wrapper `prettystring:"simple"`
XWrapSafe func(i int) int
YWrapSafe func(i int) int
Tiles4PathFind *tilearea4pathfind.TileArea4PathFind `prettystring:"simple"`
visitTime time.Time `prettystring:"simple"`
FieldObjPosMan uuidposmani.UUIDPosManI `prettystring:"simple"`
}
func New(FloorInfo *c2t_obj.FloorInfo) *ClientFloor {
cf := ClientFloor{
Tiles: tilearea.New(FloorInfo.W, FloorInfo.H),
Visited: visitarea.New(FloorInfo),
FloorInfo: FloorInfo,
XWrapper: wrapper.New(FloorInfo.W),
YWrapper: wrapper.New(FloorInfo.H),
}
cf.XWrapSafe = cf.XWrapper.GetWrapSafeFn()
cf.YWrapSafe = cf.YWrapper.GetWrapSafeFn()
cf.Tiles4PathFind = tilearea4pathfind.New(cf.Tiles)
cf.FieldObjPosMan = uuidposman_map.New(FloorInfo.W, FloorInfo.H)
return &cf
}
func (cf *ClientFloor) Cleanup() {
cf.Tiles = nil
if v := cf.Visited; v != nil {
v.Cleanup()
}
cf.Visited = nil
if t := cf.Tiles4PathFind; t != nil {
t.Cleanup()
}
cf.Tiles4PathFind = nil
if i := cf.FieldObjPosMan; i != nil {
i.Cleanup()
}
cf.FieldObjPosMan = nil
}
func (cf *ClientFloor) Forget() {
FloorInfo := cf.FloorInfo
cf.Tiles = tilearea.New(FloorInfo.W, FloorInfo.H)
cf.Tiles4PathFind = tilearea4pathfind.New(cf.Tiles)
cf.Visited = visitarea.New(FloorInfo)
}
func (cf *ClientFloor) ReplaceFloorTiles(fta *c2t_obj.NotiFloorTiles_data) {
for x, xv := range fta.Tiles {
xpos := fta.X + x
for y, yv := range xv {
ypos := fta.Y + y
cf.Tiles[xpos][ypos] = yv
if yv != 0 {
cf.Visited.CheckAndSetNolock(xpos, ypos)
}
}
}
return
}
func (cf *ClientFloor) String() string {
return fmt.Sprintf("ClientFloor[%v %v %v %v]",
cf.FloorInfo.Name,
cf.Visited,
cf.XWrapper.GetWidth(),
cf.YWrapper.GetWidth(),
)
}
func (cf *ClientFloor) UpdateFromViewportTile(
vp *c2t_obj.NotiVPTiles_data,
vpXYLenList findnear.XYLenList,
) error {
if cf.FloorInfo.Name != vp.FloorName {
return fmt.Errorf("vptile data floor not match %v %v",
cf.FloorInfo.Name, vp.FloorName)
}
cf.Visited.UpdateByViewport2(vp.VPX, vp.VPY, vp.VPTiles, vpXYLenList)
for i, v := range vpXYLenList {
fx := cf.XWrapSafe(v.X + vp.VPX)
fy := cf.YWrapSafe(v.Y + vp.VPY)
if vp.VPTiles[i] != 0 {
cf.Tiles[fx][fy] = vp.VPTiles[i]
}
}
return nil
}
func (cf *ClientFloor) UpdateFieldObjList(folsit []*c2t_obj.FieldObjClient) {
for _, v := range folsit {
cf.FieldObjPosMan.AddOrUpdateToXY(v, v.X, v.Y)
}
}
func (cf *ClientFloor) PosAddDir(x, y int, dir way9type.Way9Type) (int, int) {
nextX := x + dir.Dx()
nextY := y + dir.Dy()
nextX = cf.XWrapper.Wrap(nextX)
nextY = cf.YWrapper.Wrap(nextY)
return nextX, nextY
}
func (cf *ClientFloor) FindMovableDir(x, y int, dir way9type.Way9Type) way9type.Way9Type {
dirList := []way9type.Way9Type{
dir,
dir.TurnDir(1),
dir.TurnDir(-1),
dir.TurnDir(2),
dir.TurnDir(-2),
}
if rand.Float64() >= 0.5 {
dirList = []way9type.Way9Type{
dir,
dir.TurnDir(-1),
dir.TurnDir(1),
dir.TurnDir(-2),
dir.TurnDir(2),
}
}
for _, dir := range dirList {
nextX, nextY := cf.PosAddDir(x, y, dir)
if cf.Tiles[nextX][nextY].CharPlaceable() {
return dir
}
}
return way9type.Center
}
func (cf *ClientFloor) IsValidPos(x, y int) bool {
return cf.XWrapper.IsIn(x) && cf.YWrapper.IsIn(y)
}
func (cf *ClientFloor) GetBias() bias.Bias {
if cf.FloorInfo != nil {
return cf.FloorInfo.Bias
} else {
return bias.Bias{}
}
}
func (cf *ClientFloor) EnterFloor() {
cf.visitTime = time.Now()
}
func (cf *ClientFloor) GetFieldObjAt(x, y int) *c2t_obj.FieldObjClient {
po, ok := cf.FieldObjPosMan.Get1stObjAt(x, y).(*c2t_obj.FieldObjClient)
if !ok {
return nil
}
return po
}
|
[
2
] |
package main
import (
"fmt"
"log"
"net/http"
"net/smtp"
"william/utility"
"github.com/gin-gonic/gin"
"github.com/robfig/cron/v3"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
const sqliteDatabasePath = "./material/sqliteDB.sqlite3" // 把資料庫存放在material資料夾下
type DatabaseType int8
const (
Sqlite3 DatabaseType = 0 // 支援Sqlite3
MySql DatabaseType = 1 // 支援MySql
)
// 資料表的長相
type Product struct {
gorm.Model
Code string `json:"code" gorm:"index:idx_name,unique"`
Price uint `json:"price"`
}
// 使用Gmail寄信的資訊
type gmailInformation struct {
fromMail string
toMail string
password string
host string
port uint
title string
message string
}
func init() {
log.SetFlags(log.Lshortfile | log.LstdFlags)
}
func main() {
go cronSchedule()
error := initSetting()
utility.Println(error)
}
// 初始設定
func initSetting() error {
database, error := Sqlite3.createDatabase(sqliteDatabasePath)
if error != nil {
return error
}
error = createTables(database)
if error != nil {
return error
}
initRouter(database)
return nil
}
// 初始化Router相關設定
func initRouter(database *gorm.DB) {
router := gin.Default()
router.MaxMultipartMemory = 8 << 20
registerWebAPI(router, database)
router.Run(":8080")
}
// 建立資料庫
func (dbType DatabaseType) createDatabase(path string) (*gorm.DB, error) {
var database *gorm.DB
var error error
switch dbType {
case Sqlite3:
database, error = gorm.Open(sqlite.Open(path), &gorm.Config{})
case MySql:
break
}
return database, error
}
// 建立表格
func createTables(database *gorm.DB) error {
return database.AutoMigrate(&Product{})
}
// 註冊API
func registerWebAPI(router *gin.Engine, database *gorm.DB) {
insertProduct(router, database)
selectProduct(router, database)
deleteProduct(router, database)
partialUpdateProduct(router, database)
selectAllProduct(router, database)
mailServer(router, database)
}
// MARK: - WebAPI
// <POST>新增單一商品 => http://localhost:8080/product + {"code":"iPhone","price":20000}
func insertProduct(router *gin.Engine, database *gorm.DB) {
var emptyProduct Product
router.POST("/product", func(context *gin.Context) {
dictionary := utility.RequestBodyToMap(context)
result, error := emptyProduct._Insert(database, dictionary)
utility.ContextJSON(context, http.StatusOK, result, error)
})
}
// <GET>搜尋單一商品 => http://localhost:8080/product/87
func selectProduct(router *gin.Engine, database *gorm.DB) {
var emptyProduct Product
router.GET("/product/:id", func(context *gin.Context) {
id, error := utility.StringToInt(context.Param("id"))
result := emptyProduct._Select(database, uint(id))
if result.ID == 0 {
utility.ContextJSON(context, http.StatusOK, nil, error)
return
}
utility.ContextJSON(context, http.StatusOK, result, error)
})
}
// <DELETE>刪除單一商品 => http://localhost:8080/product/87
func deleteProduct(router *gin.Engine, database *gorm.DB) {
var emptyProduct Product
router.DELETE("/product/:id", func(context *gin.Context) {
id, error := utility.StringToInt(context.Param("id"))
isSuccess := emptyProduct._Delete(database, uint(id))
result := map[string]interface{}{"isSuccess": isSuccess}
utility.ContextJSON(context, http.StatusOK, result, error)
})
}
// [<PATCH>更新單一商品部分內容](https://ihower.tw/blog/archives/6483) => http://localhost:8080/product/87
func partialUpdateProduct(router *gin.Engine, database *gorm.DB) {
var emptyProduct Product
router.PATCH("/product/:id", func(context *gin.Context) {
id, error := utility.StringToInt(context.Param("id"))
dictionary := utility.RequestBodyToMap(context)
result := emptyProduct._PartialUpdate(database, uint(id), dictionary)
utility.ContextJSON(context, http.StatusOK, result, error)
})
}
// [<GET>搜尋部分商品](https://stackoverflow.com/questions/51534285/how-to-access-gorm-model-id/71865857) => http://localhost:8080/product?price=1487&code=iPhone
func selectAllProduct(router *gin.Engine, database *gorm.DB) {
var emptyProduct Product
router.GET("/product", func(context *gin.Context) {
code := context.Query("code")
price := context.Query("price")
dictionary := map[string]interface{}{
"code": code,
"price": price,
}
utility.Println(dictionary)
result := emptyProduct._SelectAll(database, dictionary)
utility.ContextJSON(context, http.StatusOK, result, nil)
})
}
// [<POST>寄垃圾信](https://gist.github.com/jpillora/cb46d183eca0710d909a) => http://localhost:8080/mail + {"to":"[email protected]","title":"垃垃信測試","message":"2022/4/14 Golang smtp test!!!!"}
func mailServer(router *gin.Engine, database *gorm.DB) {
router.POST("/mail", func(context *gin.Context) {
dictionary := utility.RequestBodyToMap(context)
info := gmailInformation{
fromMail: "[email protected]",
password: "<password>",
host: "smtp.gmail.com",
port: 587,
toMail: dictionary["to"].(string),
title: dictionary["title"].(string),
message: dictionary["message"].(string),
}
result, error := gmailServer(info)
utility.ContextJSON(context, http.StatusOK, result, error)
})
}
// MARK: - [Product小工具](https://gorm.io/zh_CN/docs/query.html)
// 新增單一商品 => ["code":"iPhone","price":20000]
func (_product *Product) _Insert(database *gorm.DB, dictionary map[string]interface{}) (map[string]interface{}, error) {
code := dictionary["code"].(string)
price := uint(dictionary["price"].(float64))
isSuccess := false
error := database.Create(&Product{Code: code, Price: price}).Error
if error == nil {
isSuccess = true
}
result := map[string]interface{}{"isSuccess": isSuccess}
return result, error
}
// 搜尋單一商品 => id = 87
func (_product *Product) _Select(database *gorm.DB, id uint) Product {
var product Product
database.Take(&product, "id=?", id)
return product
}
// 刪除單一商品 => http://localhost:8080/product/87
func (_product *Product) _Delete(database *gorm.DB, id uint) bool {
product := _product._Select(database, id)
database.Delete(&product, id)
return product.ID != 0
}
// 更新單一商品部分內容 => http://localhost:8080/product/87
func (_product *Product) _PartialUpdate(database *gorm.DB, id uint, dictionary map[string]interface{}) map[string]interface{} {
isSuccess := false
product := _product._Select(database, id)
error := database.Model(&product).Updates(dictionary).Error
if error == nil {
isSuccess = true
}
result := map[string]interface{}{}
result["isSuccess"] = isSuccess
return result
}
// 搜尋部分商品 (過濾條件) => http://localhost:8080/product
func (_product *Product) _SelectAll(database *gorm.DB, dictionary map[string]interface{}) []Product {
var products []Product
var _database = database
code := dictionary["code"].(string)
price, _ := utility.StringToInt(dictionary["price"].(string))
if len(code) != 0 {
_database = _database.Where("code LIKE ?", "%"+code+"%")
}
if price > 0 {
_database = _database.Where("price >= ?", price)
}
_database.Find(&products)
return products
}
// [使用Gmail寄信](https://support.google.com/mail/?p=InvalidSecondFactor)
func gmailServer(info gmailInformation) (map[string]interface{}, error) {
var isSuccess bool = false
var error error = nil
smtpServer := fmt.Sprintf("%s:%d", info.host, info.port)
message := fmt.Sprintf("From: %s\nTo: %s\nSubject: %s\n\n %s", info.fromMail, info.toMail, info.title, info.message)
authentication := smtp.PlainAuth("", info.fromMail, info.password, info.host)
error = smtp.SendMail(smtpServer, authentication, info.fromMail, []string{info.toMail}, []byte(message))
if error == nil {
isSuccess = true
}
result := map[string]interface{}{"isSuccess": isSuccess}
return result, error
}
// [定時排程任務](https://www.readfog.com/a/1637371620314157056)
func cronSchedule() {
schedule := cron.New(cron.WithSeconds())
index := 1
schedule.AddFunc("* * * * * *", func() {
utility.Println("每一秒執行一次", index)
index++
})
schedule.Start()
// time.Sleep(time.Minute * 1)
select {}
}
|
[
1
] |
package main
import (
"fmt"
"math"
)
func SqrtTemp(x float64) float64 {
z := float64(1)
fmt.Println("Sqrt Temp ...");
for i := 0; i < 10; i++ {
z = z - (((z * z) - x) / (2 * z))
fmt.Println(z);
}
return z
}
func Sqrt(x float64) float64 {
z := float64(1)
prev := float64(0)
fmt.Println("Sqrt ...");
for math.Abs(prev - z) > 0.00000000001 {
prev = z
z = z - (((z * z) - x) / (2 * z))
fmt.Println(z);
}
return z
}
func main() {
fmt.Println(Sqrt(10))
fmt.Println(SqrtTemp(10))
}
|
[
0
] |
package golang
/**
给你一个长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。
示例:
输入: [1,2,3,4]
输出: [24,12,8,6]
提示:题目数据保证数组之中任意元素的全部前缀元素和后缀(甚至是整个数组)的乘积都在 32 位整数范围内。
说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。
链接:https://leetcode-cn.com/problems/product-of-array-except-self
思路:第i位的结果等于nums数组中,小于i的元素的乘积(左边,或称前缀),乘以大于i的元素的乘积(右边,或称后缀)
*/
func ProductExceptSelf(nums []int) []int {
result := make([]int, len(nums))
// result先保存前缀。刚开始左边没有元素,所以result[0]=1
result[0] = 1
// 算出前缀。
for i := 1; i < len(nums); i++ {
result[i] = result[i-1] * nums[i-1]
}
// R用于记录每次遍历的后缀。刚开始右边没有元素,所以R=1
R := 1
// 遍历乘上后缀,即所求数组
for i := len(nums) - 1; i >= 0; i-- {
result[i] = result[i] * R
R *= nums[i]
}
return result
}
|
[
0
] |
// Copyright (c) 2021 Palantir Technologies. 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 internal
import (
"math"
"sync"
"sync/atomic"
"time"
)
const (
decaysPerHalfLife = 10
)
var (
decayFactor = math.Pow(0.5, 1.0/decaysPerHalfLife)
)
type CourseExponentialDecayReservoir interface {
Update(updates float64)
Get() float64
}
var _ CourseExponentialDecayReservoir = (*reservoir)(nil)
type reservoir struct {
lastDecay int64
nanoClock func() int64
decayIntervalNanoseconds int64
mu sync.Mutex
value float64
}
func NewCourseExponentialDecayReservoir(nanoClock func() int64, halfLife time.Duration) CourseExponentialDecayReservoir {
return &reservoir{
lastDecay: nanoClock(),
nanoClock: nanoClock,
decayIntervalNanoseconds: halfLife.Nanoseconds() / decaysPerHalfLife,
}
}
func (r *reservoir) Update(updates float64) {
r.decayIfNecessary()
r.mu.Lock()
defer r.mu.Unlock()
r.value = r.value + updates
}
func (r *reservoir) Get() float64 {
r.decayIfNecessary()
r.mu.Lock()
defer r.mu.Unlock()
return r.value
}
func (r *reservoir) decayIfNecessary() {
now := r.nanoClock()
lastDecaySnapshot := r.lastDecay
nanosSinceLastDecay := now - lastDecaySnapshot
decays := nanosSinceLastDecay / r.decayIntervalNanoseconds
// If CAS fails another thread will execute decay instead
if decays > 0 && atomic.CompareAndSwapInt64(&r.lastDecay, lastDecaySnapshot, lastDecaySnapshot+decays*r.decayIntervalNanoseconds) {
r.decay(decays)
}
}
func (r *reservoir) decay(decayIterations int64) {
r.mu.Lock()
defer r.mu.Unlock()
r.value = r.value * math.Pow(decayFactor, float64(decayIterations))
}
|
[
0
] |
package day1
import (
"fmt"
"strconv"
"strings"
)
// Run runs day 1
func Run(bytes []byte) {
parsed := parse(bytes)
part1 := part1(parsed)
fmt.Printf("Day 1 - Part 1: ")
fmt.Println(part1)
part2 := part2(parsed)
fmt.Printf("Day 1 - Part 2: ")
fmt.Println(part2)
}
func parse(bytes []byte) (masses []int64) {
input := string(bytes)
lines := strings.Split(input, "\n")
for _, line := range lines {
mass, err := strconv.Atoi(line)
// Last line might be empty so let's just ignore it
if err != nil {
continue
}
masses = append(masses, int64(mass))
}
return
}
func part1(masses []int64) (fuel int64) {
for _, mass := range masses {
fuel = fuel + fuelFor(mass)
}
return
}
func part2(masses []int64) (totalFuel int64) {
for _, mass := range masses {
totalFuel = totalFuel + fuelForModule(mass)
}
return
}
func fuelFor(mass int64) (fuel int64) {
fuel = mass/3 - 2
return
}
func fuelForModule(mass int64) (totalFuel int64) {
fuel := fuelFor(mass)
totalFuel = fuel
for fuel != 0 {
fuel = fuelFor(fuel)
if fuel < 0 {
fuel = 0
}
totalFuel = totalFuel + fuel
}
return
}
|
[
0
] |
/*
Package guest_file_open - open file inside guest and returns it handle
Example:
{ "execute": "guest-file-open", "arguments": {
"path": string // required, file path
"mode": string // optional, file open mode
}
}
*/
package guest_file_open
import (
"encoding/json"
"os"
"github.com/vtolstov/cloudagent/qga"
)
func init() {
qga.RegisterCommand(&qga.Command{
Name: "guest-file-open",
Func: fnGuestFileOpen,
Enabled: true,
Returns: true,
Arguments: true,
})
}
func fnGuestFileOpen(req *qga.Request) *qga.Response {
res := &qga.Response{ID: req.ID}
reqData := struct {
Path string `json:"path"`
Mode string `json:"mode,omitempty"`
}{}
err := json.Unmarshal(req.RawArgs, &reqData)
if err != nil {
res.Error = &qga.Error{Code: -1, Desc: err.Error()}
return res
}
var flag int
if reqData.Mode != "" {
for _, s := range reqData.Mode {
switch s {
case 'a':
flag = flag | os.O_APPEND | os.O_CREATE | os.O_WRONLY
case '+':
flag = flag | os.O_RDWR
case 'w':
flag = flag | os.O_TRUNC | os.O_WRONLY
case 'r':
flag = flag | os.O_RDONLY
}
}
} else {
flag = flag | os.O_RDONLY
}
if f, err := os.OpenFile(reqData.Path, flag, os.FileMode(0600)); err == nil {
fd := int(f.Fd())
qga.StoreSet("guest-file", fd, f)
res.Return = fd
} else {
res.Error = &qga.Error{Code: -1, Desc: err.Error()}
}
return res
}
|
[
0
] |
package trakttv
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
)
// Test shit
func (t *TraktTv) request(URL string, q *Query, result interface{}) error {
// Add the query options to the URL
u, err := url.Parse(URL)
if err != nil {
return err
}
u.RawQuery = q.urlValues().Encode()
URL = u.String()
req, err := http.NewRequest("GET", URL, nil)
if err != nil {
return err
}
req.Header.Add("Content-type", "application/json")
req.Header.Add("trakt-api-key", t.Key)
req.Header.Add("trakt-api-version", "2")
resp, err := t.HTTPClient.Do(req)
if err != nil {
return err
}
if os.Getenv("DEBUG") == "1" {
fmt.Println("debug mode")
fmt.Println("===============")
fmt.Printf("URL: %q\n", URL)
fmt.Println("===============")
fmt.Printf("Status : %q", resp.Status)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
fmt.Println(string(body))
fmt.Println("===============")
return json.Unmarshal(body, result)
}
return json.NewDecoder(resp.Body).Decode(result)
}
|
[
2
] |
package main
import (
"encoding/xml"
"fmt"
"io"
"os"
)
type Post struct {
XMLName xml.Name `xml:"post"`
Id string `xml:"id,attr"`
Content string `xml:"content"`
Author Author `xml:"author"`
Xml string `xml:",innerxml"`
Comments []Comment `xml:"comments>comment"`
}
type Author struct {
Id string `xml:"id,attr"`
Name string `xml:"chardata"`
}
type Comment struct {
Id string `xml:"id,attr"`
Content string `xml:"content"`
Author Author `xml:"author"`
}
func main() {
xmlFile, err := os.Open("post.xml")
if err != nil {
fmt.Println("Error opening XML file:", err)
return
}
defer xmlFile.Close()
// Creates decoder from XML data
decoder := xml.NewDecoder(xml)
// Iterates through XML data in decoder
for {
// Gets token from decoder at each iteration
r, err := decoder.Token()
if err == io.EOF {
break
}
if err != nil {
fmt.Println("Error decoding XML into tokens:", err)
return
}
// Checks type of tokens
switch se := t.(type) {
case xml.StartElement:
if se.Name.Local == "comment" {
// Decodes XML data into struct
decoder.DecodeElement(&comment, &se)
}
}
}
}
|
[
7
] |
package hello
import "fmt"
// Interface ...
type Interface interface {
SayHello(FirstName string) string
}
// Hello ...
type Hello struct {
LastName string
}
var h *Hello
var hi Interface
// New ...
func New(i Interface) Interface {
hi = i
if hello, ok := i.(*Hello); ok {
h = hello
}
return hi
}
// SayHello ...
func (h *Hello) SayHello(firstName string) string {
r := fmt.Sprintf("Hello, %s %s!", h.LastName, firstName)
r = r + h.SayWorld()
fmt.Println(r)
return r
}
// SayWorld ...
func (h *Hello) SayWorld() string {
return " world!"
}
// SayHello ...
func SayHello(firstName string) string {
return hi.SayHello(firstName)
}
|
[
0
] |
package rlepluslazy
import (
"math/rand"
"testing"
"github.com/filecoin-project/go-bitfield/rle/internal/rleplus"
"github.com/stretchr/testify/assert"
)
func TestDecode(t *testing.T) {
// Encoding bitvec![LittleEndian; 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
// in the Rust reference implementation gives an encoding of [223, 145, 136, 0] (without version field)
// The bit vector is equivalent to the integer set { 0, 2, 4, 5, 6, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 }
// This is the above reference output with a version header "00" manually added
referenceEncoding := []byte{124, 71, 34, 2}
expectedNumbers := []uint64{0, 2, 4, 5, 6, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27}
runs, err := RunsFromBits(BitsFromSlice(expectedNumbers))
assert.NoError(t, err)
encoded, err := EncodeRuns(runs, []byte{})
assert.NoError(t, err)
// Our encoded bytes are the same as the ref bytes
assert.Equal(t, len(referenceEncoding), len(encoded))
assert.Equal(t, referenceEncoding, encoded)
rle, err := FromBuf(encoded)
assert.NoError(t, err)
decoded := make([]uint64, 0, len(expectedNumbers))
rit, err := rle.RunIterator()
assert.NoError(t, err)
it, err := BitsFromRuns(rit)
assert.NoError(t, err)
for it.HasNext() {
bit, err := it.Next()
assert.NoError(t, err)
decoded = append(decoded, bit)
}
// Our decoded integers are the same as expected
assert.Equal(t, expectedNumbers, decoded)
}
func TestGoldenGen(t *testing.T) {
t.SkipNow()
N := 10000
mod := uint32(1) << 20
runExProp := float32(0.93)
bits := make([]uint64, N)
for i := 0; i < N; i++ {
x := rand.Uint32() % mod
bits[i] = uint64(x)
for rand.Float32() < runExProp && i+1 < N {
i++
x = (x + 1) % mod
bits[i] = uint64(x)
}
}
out, _, err := rleplus.Encode(bits)
assert.NoError(t, err)
t.Logf("%#v", out)
_, runs := rleplus.RunLengths(bits)
t.Logf("runs: %v", runs)
t.Logf("len: %d", len(out))
}
func TestGolden(t *testing.T) {
expected, _ := rleplus.Decode(goldenRLE)
res := make([]uint64, 0, len(expected))
rle, err := FromBuf(goldenRLE)
assert.NoError(t, err)
rit, err := rle.RunIterator()
assert.NoError(t, err)
it, err := BitsFromRuns(rit)
assert.NoError(t, err)
for it.HasNext() {
bit, err := it.Next()
assert.NoError(t, err)
res = append(res, bit)
}
assert.Equal(t, expected, res)
}
func TestGoldenLoop(t *testing.T) {
rle, err := FromBuf(goldenRLE)
assert.NoError(t, err)
rit, err := rle.RunIterator()
assert.NoError(t, err)
buf, err := EncodeRuns(rit, nil)
assert.NoError(t, err)
assert.Equal(t, goldenRLE, buf)
}
func TestEncodeConsecutiveFails(t *testing.T) {
ra := &RunSliceIterator{
Runs: []Run{
{Val: true, Len: 5},
{Val: true, Len: 8},
},
}
_, err := EncodeRuns(ra, nil)
if err != ErrSameValRuns {
t.Fatal("expected ErrSameValRuns")
}
}
var Res uint64 = 0
func BenchmarkRunIterator(b *testing.B) {
b.ReportAllocs()
var r uint64
for i := 0; i < b.N; i++ {
rle, _ := FromBuf(goldenRLE)
rit, _ := rle.RunIterator()
for rit.HasNext() {
run, _ := rit.NextRun()
if run.Val {
r = r + run.Len
}
}
}
Res = Res + r
}
func BenchmarkRunsToBits(b *testing.B) {
b.ReportAllocs()
var r uint64
for i := 0; i < b.N; i++ {
rle, _ := FromBuf(goldenRLE)
rit, _ := rle.RunIterator()
it, _ := BitsFromRuns(rit)
for it.HasNext() {
bit, _ := it.Next()
if bit < 1<<63 {
r++
}
}
}
Res = Res + r
}
func BenchmarkOldRLE(b *testing.B) {
b.ReportAllocs()
var r uint64
for i := 0; i < b.N; i++ {
rle, _ := rleplus.Decode(goldenRLE)
r = r + uint64(len(rle))
}
Res = Res + r
}
func BenchmarkDecodeEncode(b *testing.B) {
b.ReportAllocs()
var r uint64
out := make([]byte, 0, len(goldenRLE))
for i := 0; i < b.N; i++ {
rle, _ := FromBuf(goldenRLE)
rit, _ := rle.RunIterator()
out, _ = EncodeRuns(rit, out)
r = r + uint64(len(out))
}
/*
for i := 0; i < b.N; i++ {
rle, _ := rleplus.Decode(goldenRLE)
out, _, _ := rleplus.Encode(rle)
r = r + uint64(len(out))
}
*/
Res = Res + r
}
|
[
0
] |
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strconv"
)
var materias = map[string]map[string]float64{}
var alumnos = map[string]map[string]float64{}
func loadHTML(htmlDocument string) string {
html, _ := ioutil.ReadFile(htmlDocument)
return string(html)
}
func index(response http.ResponseWriter, request *http.Request) {
response.Header().Set(
"Content-Type",
"text.html",
)
fmt.Fprintf(
response,
loadHTML("index.html"),
)
}
func postReceiver(response http.ResponseWriter, request *http.Request) {
var message string
switch request.Method {
case "POST":
if err := request.ParseForm(); err != nil {
fmt.Fprintf(response, "ParseForm() error %v", err)
return
}
aux := request.FormValue("calificacion")
alumno := request.FormValue("nombreAlumno")
materia := request.FormValue("materia")
// Convertimos el string de la calificacion del form en float.
if calificacion, err := strconv.ParseFloat(aux, 32); err == nil {
if _, alumnoExists := alumnos[alumno]; alumnoExists {
if _, materiaExists := alumnos[alumno][materia]; materiaExists {
message = "Calificacion existente. Imposible modificar."
// Si existe el alumno, y la materia *para ese alumno*, quiere decir que ya existe calificacion y no es modificable.
} else {
// Veamos si la materia ya existe en el mapa; que haya sido generada por el registro de otro alumno.
if _, materiaExists := materias[materia]; materiaExists {
alumnos[alumno][materia] = calificacion
materias[materia][alumno] = calificacion
} else {
alumnos[alumno][materia] = calificacion
materias[materia] = make(map[string]float64)
materias[materia][alumno] = calificacion
// Creamos la nueva materia.
}
message = "Registro realizado con exito"
}
} else {
// Si no existe el alumno, necesitamos revisar si existe o no la materia.
if _, materiaExists := materias[materia]; materiaExists {
alumnos[alumno] = make(map[string]float64)
alumnos[alumno][materia] = calificacion
materias[materia][alumno] = calificacion
} else {
// Si no existen ninguno de los dos, los creamos y les damos sus valores.
alumnos[alumno] = make(map[string]float64)
alumnos[alumno][materia] = calificacion
materias[materia] = make(map[string]float64)
materias[materia][alumno] = calificacion
}
message = "Registro realizado con exito"
}
} else {
fmt.Println(err)
return
}
fmt.Println("Alumnos:", alumnos)
fmt.Println("Materias:", materias)
response.Header().Set(
"Content-Type",
"text.html",
)
fmt.Fprintf(
response,
loadHTML("postReceiver.html"),
message,
)
}
}
func obtenerPromedioIndividual(nombreAlumno string) float64 {
promedio, contadorMaterias := 0.0, 0.0
if _, alumnoExists := alumnos[nombreAlumno]; alumnoExists {
for _, value := range alumnos[nombreAlumno] {
promedio += value
contadorMaterias++
}
promedio /= contadorMaterias
return promedio
}
return -1
}
func promedioIndividual(response http.ResponseWriter, request *http.Request) {
var message string
switch request.Method {
case "GET":
if err := request.ParseForm(); err != nil {
fmt.Fprintf(response, "ParseForm() error %v", err)
return
}
alumno := request.FormValue("promedioIndividual")
promedio := obtenerPromedioIndividual(alumno)
if promedio == -1 {
message = "Alumno no existente"
} else {
aux := fmt.Sprintf("%f", promedio)
message = "<tr>" +
"<td>" + alumno + "</td>" +
"<td>" + aux + "</td>" +
"</tr>"
}
response.Header().Set(
"Content-Type",
"text.html",
)
fmt.Fprintf(
response,
loadHTML("promedioIndividual.html"),
message,
)
}
}
func promedioGeneral(response http.ResponseWriter, request *http.Request) {
var message string
promedio := 0.0
if len(alumnos) == 0 {
message = "No hay alumnos registrados"
} else {
for alumno := range alumnos {
promedio += obtenerPromedioIndividual(alumno)
}
promedio /= float64(len(alumnos))
aux := fmt.Sprintf("%f", promedio)
message = "<tr>" +
"<td>" + "General" + "</td>" +
"<td>" + aux + "</td>" +
"</tr>"
}
response.Header().Set(
"Content-Type",
"text.html",
)
fmt.Fprintf(
response,
loadHTML("promedioIndividual.html"),
message,
)
}
func obtenerPromedioMateria(nombreMateria string) float64 {
promedio, contadorAlumnos := 0.0, 0.0
if _, materiaExists := materias[nombreMateria]; materiaExists {
for _, value := range materias[nombreMateria] {
promedio += value
contadorAlumnos++
}
promedio /= contadorAlumnos
return promedio
}
return -1
}
func promedioMateria(response http.ResponseWriter, request *http.Request) {
var message string
objetivo := request.FormValue("promedioMateria")
promedio := obtenerPromedioMateria(objetivo)
if promedio == -1 {
message = "Materia no existente"
} else {
aux := fmt.Sprintf("%f", promedio)
message = "<tr>" +
"<td>" + objetivo + "</td>" +
"<td>" + aux + "</td>" +
"</tr>"
}
response.Header().Set(
"Content-Type",
"text.html",
)
fmt.Fprintf(
response,
loadHTML("promedioMateria.html"),
message,
)
}
func main() {
http.HandleFunc("/", index)
http.HandleFunc("/postReceiver", postReceiver)
http.HandleFunc("/promedioIndividual", promedioIndividual)
http.HandleFunc("/promedioGeneral", promedioGeneral)
http.HandleFunc("/promedioMateria", promedioMateria)
fmt.Println("Servidor en ejecucion...")
http.ListenAndServe(":9000", nil)
}
|
[
7
] |
package main
import "fmt"
/*
* @lc app=leetcode.cn id=84 lang=golang
*
* [84] 柱状图中最大的矩形
*
* https://leetcode-cn.com/problems/largest-rectangle-in-histogram/description/
*
* algorithms
* Hard (38.69%)
* Likes: 460
* Dislikes: 0
* Total Accepted: 30.8K
* Total Submissions: 78.8K
* Testcase Example: '[2,1,5,6,2,3]'
*
* 给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
*
* 求在该柱状图中,能够勾勒出来的矩形的最大面积。
*
*
*
*
*
* 以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。
*
*
*
*
*
* 图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。
*
*
*
* 示例:
*
* 输入: [2,1,5,6,2,3]
* 输出: 10
*
*/
// @lc code=start
func largestRectangleArea(heights []int) int {
if len(heights) <= 0 {
return 0
}
// 栈
s := newStack(len(heights))
s.push(-1)
maxArea := 0
for i := range heights {
for s.top() != -1 && heights[s.top()] >= heights[i] {
maxArea = max(heights[s.pop()]*(i-s.top()-1), maxArea)
}
s.push(i)
}
for s.top() != -1 {
maxArea = max(heights[s.pop()]*(len(heights)-s.top()-1), maxArea)
}
return maxArea
}
type stack struct {
data []int
len, cap int
}
func (s *stack) String() string {
return fmt.Sprintf("data:%v, len:%d, cap:%d", s.data, s.len, s.cap)
}
// func (s *stack) len() int {
// return s.len
// }
func (s *stack) top() int {
if s.len > 0 {
return s.data[s.len-1]
}
return -1
}
func (s *stack) pop() int {
if s.len > 0 {
s.len--
return s.data[s.len]
}
return 0
}
func (s *stack) push(val int) {
s.data[s.len] = val
s.len++
}
func newStack(cap int) *stack {
return &stack{
data: make([]int, cap+1),
cap: cap,
}
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
// @lc code=end
func main() {
// fmt.Println(largestRectangleArea([]int{2, 1, 5, 6, 2, 3}))
// fmt.Println(largestRectangleArea([]int{}))
// fmt.Println(largestRectangleArea([]int{0}))
// fmt.Println(largestRectangleArea([]int{2}))
// fmt.Println(largestRectangleArea([]int{2, 2}))
fmt.Println(largestRectangleArea([]int{2, 1, 2}))
}
|
[
1
] |
package storage
import (
"bytes"
"io"
)
type readSeeker struct {
io.Reader
buf []byte
offset int
}
func newReadSeeker(buf []byte) io.ReadSeeker {
return &readSeeker{
Reader: bytes.NewReader(buf),
buf: buf,
}
}
func (r *readSeeker) Seek(off int64, whence int) (int64, error) {
offset := int(off)
switch whence {
case io.SeekStart:
if offset < 0 || offset > len(r.buf) {
return 0, io.EOF
}
r.offset = offset
r.Reader = bytes.NewReader(r.buf[offset:])
case io.SeekEnd:
if offset < 0 || offset > len(r.buf) {
return 0, io.EOF
}
r.offset = len(r.buf) - offset
r.Reader = bytes.NewReader(r.buf[len(r.buf)-offset:])
case io.SeekCurrent:
if offset+r.offset > len(r.buf) ||
offset+r.offset < 0 {
return 0, io.EOF
}
r.offset = r.offset + offset
r.Reader = bytes.NewReader(r.buf[r.offset:])
default:
panic("wrong whence arg")
}
return int64(r.offset), nil
}
|
[
0
] |
package proto
import (
"bufio"
"io"
"net"
"net/rpc"
"strings"
"gopkg.in/inconshreveable/log15.v2"
"github.com/juju/errors"
)
var methodMap = map[string]string{
"ping": "KV.Ping",
"get": "KV.Read",
"set": "KV.Apply",
"del": "KV.Apply",
}
var actionMap = map[string]Action{
"ping": OpPing,
"get": OpRead,
"set": OpWrite,
"del": OpDelete,
}
type RedisServerCodec struct {
c io.Closer
r *bufio.Reader
w *bufio.Writer
seq uint64
msg *Message
req Request
}
func NewRedisServerCodec(conn net.Conn) *RedisServerCodec {
return &RedisServerCodec{
c: conn,
r: bufio.NewReader(conn),
w: bufio.NewWriter(conn),
}
}
func (c *RedisServerCodec) ReadRequestHeader(r *rpc.Request) error {
err := c.innerReadRequestHeader(r)
if err != nil && err != io.EOF {
log15.Error("ReadRequestHeader", "error", err)
WriteArbitrary(c.w, err)
c.w.Flush()
}
return err
}
func (c *RedisServerCodec) innerReadRequestHeader(r *rpc.Request) (err error) {
defer func() {
if ret := recover(); ret != nil {
err = errors.Errorf("Read Header:%s", ret)
}
}()
m, err := bufioReadMessage(c.r)
if err != nil {
return
}
arr, err := m.Array()
if err != nil {
err = errors.Errorf("must by array type:%v", m.Type)
return
}
op, _ := arr[0].Str()
op = strings.ToLower(op)
method, ok := methodMap[op]
if !ok {
err = errors.Errorf("method not supported:%s", op)
return
}
r.ServiceMethod = method
c.seq++
r.Seq = c.seq
c.msg = m
return nil
}
func (c *RedisServerCodec) ReadRequestBody(x interface{}) error {
err := c.innerReadRequestBody(x)
if err != nil {
log15.Error("ReadRequestBody", "error", err)
}
return err
}
func (c *RedisServerCodec) innerReadRequestBody(x interface{}) (err error) {
defer func() {
if ret := recover(); ret != nil {
err = errors.Errorf("Read Body:%s", ret)
}
}()
if x == nil {
return nil
}
if c.msg == nil {
return errors.New("empty message")
}
req, ok := x.(*Request)
if !ok {
return errors.New("body must be *Request")
}
arr, _ := c.msg.Array()
op, _ := arr[0].Str()
// clear message
c.msg = nil
req.Action = actionMap[op]
// ping need zero param
if req.Action != OpPing {
key, _ := arr[1].Bytes()
req.Key = key
}
switch op {
case "set":
value, _ := arr[2].Bytes()
req.Data = value
}
c.req = *req
return nil
}
func (c *RedisServerCodec) WriteResponse(r *rpc.Response, x interface{}) error {
err := c.innerWriteResponse(r, x)
if err != nil {
log15.Error("WriteResponse", "error", err)
}
return err
}
func (c *RedisServerCodec) innerWriteResponse(r *rpc.Response, x interface{}) error {
if r.Error != "" {
WriteArbitrary(c.w, errors.New(r.Error))
return c.w.Flush()
}
rep, ok := x.(*Reply)
if !ok {
return errors.Errorf("response must be *Reply:%T", x)
}
switch c.req.Action {
case OpPing:
WriteArbitrary(c.w, "pong")
case OpRead:
WriteArbitrary(c.w, rep.Data)
default:
WriteArbitrary(c.w, "OK")
}
return c.w.Flush()
}
func (c *RedisServerCodec) Close() error {
return c.c.Close()
}
func ServeRedis(l net.Listener, s *rpc.Server) error {
for {
conn, err := l.Accept()
if err != nil {
return err
}
codec := NewRedisServerCodec(conn)
go s.ServeCodec(codec)
}
}
|
[
7
] |
package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func mergeKLists(lists []*ListNode) *ListNode {
var head = &ListNode{0, nil}
var node *ListNode
var value int
node = head
for !listnil(lists) {
value, lists = minAndNext(lists)
node.Next = &ListNode{value, nil}
node = node.Next
}
return head.Next
}
func listnil(lists []*ListNode) bool{
for _, list := range lists{
if list != nil {
return false
}
}
return true
}
func minAndNext(lists []*ListNode) (int, []*ListNode){
var min = 10000
for _, list := range lists{
if list != nil && list.Val < min {
min = list.Val
}
}
for k, list := range lists{
if list != nil && list.Val == min {
lists[k] = lists[k].Next
break
}
}
return min, lists
}
func main() {
l1 := &ListNode{1,nil}
l1.Next = &ListNode{4, nil}
l1.Next.Next = &ListNode{5, nil}
l2 := &ListNode{1, nil}
l2.Next = &ListNode{3, nil}
l2.Next.Next = &ListNode{4, nil}
l3 := &ListNode{2, nil}
l3.Next = &ListNode{6, nil}
l := []*ListNode{l1, l2, l3}
t := mergeKLists(l)
for t != nil {
fmt.Println(t.Val)
t = t.Next
}
}
|
[
1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.