text stringlengths 11 4.05M |
|---|
package basic
import (
"fmt"
"reflect"
"runtime"
)
// 可以返回多个值
func Div(a, b int) (int, int) {
return a / b, a % b
}
func Apply(op func(int, int) int, a, b int) int {
pointer := reflect.ValueOf(op).Pointer()
opName := runtime.FuncForPC(pointer).Name()
fmt.Printf("Calling function %s with args (%d, %d) \n", opName, a, b)
return op(a, b)
}
func Sum2(nums ...int) int {
s := 0
for i := range nums {
s += i
}
return s
}
|
package slaveMonitor
import (
"fmt"
"master/master"
"master/master/proxyMonitor"
"net"
"net/http"
"network"
"strings"
"time"
)
func ReceiveSlaveHeartbeat(request *http.Request, slaveMap map[string]master.Slave) (updatedSlaveMap map[string]master.Slave) {
slaveName, slaveAddress := processSlaveHeartbeatRequest(request)
if _, existsInMap := slaveMap[slaveName]; existsInMap {
updateSlaveHeartbeat(slaveMap, slaveAddress, slaveName)
} else {
addNewSlaveToMap(slaveMap, slaveAddress, slaveName)
if proxyMonitor.IS_USING_PROXY {
proxyMonitor.RequestProxyToAddNewSlaveToIPTables(proxyMonitor.PROXY_URL, splitProtocolAndPortFromIP(slaveAddress))
}
}
return slaveMap
}
// TODO: change slaveAddress to slaveURL
func processSlaveHeartbeatRequest(request *http.Request) (slaveName, slaveAddress string) {
slaveName = request.PostFormValue("slaveName")
slavePort := request.PostFormValue("slavePort")
slaveIP, _, _ := net.SplitHostPort(request.RemoteAddr)
slaveAddress = "http://" + slaveIP + ":" + slavePort
return
}
func updateSlaveHeartbeat(slaveMap map[string]master.Slave, slaveAddress, slaveName string) {
slaveInstance := slaveMap[slaveName]
if slaveInstance.URL != slaveAddress {
killDuplicateSlave(slaveName, slaveAddress)
} else {
slaveInstance.Heartbeat = time.Now()
slaveMap[slaveName] = slaveInstance
}
}
func killDuplicateSlave(slaveName, slaveAddress string) {
fmt.Println("WARNING: Received signal from slave with duplicate name.")
fmt.Printf("Slave with name \"%v\" already exists.\n", slaveName)
fmt.Printf("Sending kill signal to duplicate slave at URL %v.\n\n", slaveAddress)
err := sendKillSignalToSlave(slaveAddress)
network.ErrorHandler(err, "Error encountered killing slave: %v\n")
}
func sendKillSignalToSlave(slaveAddress string) (err error) {
client := &http.Client{}
form := network.CreateFormWithInitialValues(map[string]string{"message": "die"})
_, err = client.PostForm(slaveAddress+"/receive_killsignal", form)
return
}
func addNewSlaveToMap(slaveMap map[string]master.Slave, slaveAddress, slaveName string) {
fmt.Printf("Slave added with name \"%v\", URL %v.\n\n", slaveName, slaveAddress)
slaveMap[slaveName] = master.Slave{URL: slaveAddress, Heartbeat: time.Now(), PreviouslyDisplayedURL: "http://google.com", DisplayedURL: "http://google.com"}
fmt.Println(slaveMap[slaveName])
}
func splitProtocolAndPortFromIP(address string) (ip string) {
host, _, _ := net.SplitHostPort(address)
ip = strings.TrimPrefix(host, "http://")
return
}
func MonitorSlaves(timeInterval int, slaveMap map[string]master.Slave) {
timer := time.Tick(time.Duration(timeInterval) * time.Second)
for _ = range timer {
removeDeadSlaves(timeInterval, slaveMap)
}
}
func removeDeadSlaves(deadTime int, slaveMap map[string]master.Slave) {
slavesToRemove := getDeadSlaves(deadTime, slaveMap)
if len(slavesToRemove) > 0 {
fmt.Printf("\nREMOVING DEAD SLAVES: %v\n", slavesToRemove)
for _, deadSlaveName := range slavesToRemove {
if proxyMonitor.IS_USING_PROXY {
proxyMonitor.RequestProxyToRemoveDeadSlaveFromIPTables(proxyMonitor.PROXY_URL, splitProtocolAndPortFromIP(slaveMap[deadSlaveName].URL))
}
delete(slaveMap, deadSlaveName)
}
printSlaveNamesInMap(slaveMap)
}
}
func getDeadSlaves(deadTime int, slaveMap map[string]master.Slave) (deadSlaves []string) {
for slaveName, slave := range slaveMap {
timeDifference := time.Now().Sub(slave.Heartbeat)
timeThreshold := time.Duration(deadTime) * time.Second
if timeDifference > timeThreshold {
deadSlaves = append(deadSlaves, slaveName)
}
}
return
}
func printSlaveNamesInMap(slaveMap map[string]master.Slave) {
fmt.Println("Current slaves are: ")
if len(slaveMap) == 0 {
fmt.Println("No slaves available.\n")
} else {
for slaveName, _ := range slaveMap {
fmt.Println(slaveName)
}
}
}
func ListSlaveNames(slaveMap map[string]master.Slave) (slaveNames []string) {
slaveNames = make([]string, 0, len(slaveMap))
for k := range slaveMap {
slaveNames = append(slaveNames, k)
}
return slaveNames
}
|
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"path"
"runtime"
"strings"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
f, err := os.Open(fmt.Sprintf("%s/public%s", parentFilePathHelper(), r.URL.Path))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Println(err)
return
}
defer f.Close()
// need to set the content type so that it is rendered correctly, otherwise it renders as plain text
var contentType string
switch {
case strings.HasSuffix(r.URL.Path, "css"):
contentType = "text/css"
case strings.HasSuffix(r.URL.Path, "html"):
contentType = "text/html"
case strings.HasSuffix(r.URL.Path, "png"):
contentType = "image/png"
default:
contentType = "text/plain"
}
w.Header().Add("Content-Type", contentType)
io.Copy(w, f)
})
http.ListenAndServe(":8000", nil)
}
// urlHelper - returns the absolute path for the main file, go run main.go does not have the same path as an executable
func parentFilePathHelper() string {
_, filename, _, ok := runtime.Caller(0)
if !ok {
panic("No caller information")
}
fmt.Printf("Filename : %q, Dir : %q\n", filename, path.Dir(filename))
return strings.Replace(path.Dir(filename), "src/main", "", 1)
}
|
package macro
import (
_ "github.com/micro/go-plugins/agent/command/animate"
_ "github.com/micro/go-plugins/agent/command/geocode"
_ "github.com/micro/go-plugins/agent/command/whereareyou"
_ "github.com/micro/go-plugins/broker/gocloud"
_ "github.com/micro/go-plugins/broker/googlepubsub"
_ "github.com/micro/go-plugins/broker/grpc"
_ "github.com/micro/go-plugins/broker/grpc/proto"
_ "github.com/micro/go-plugins/broker/http"
_ "github.com/micro/go-plugins/broker/kafka"
_ "github.com/micro/go-plugins/broker/memory"
_ "github.com/micro/go-plugins/broker/mqtt"
_ "github.com/micro/go-plugins/broker/nats"
_ "github.com/micro/go-plugins/broker/nsq"
_ "github.com/micro/go-plugins/broker/proxy"
_ "github.com/micro/go-plugins/broker/rabbitmq"
_ "github.com/micro/go-plugins/broker/redis"
_ "github.com/micro/go-plugins/broker/service"
_ "github.com/micro/go-plugins/broker/snssqs"
_ "github.com/micro/go-plugins/broker/sqs"
_ "github.com/micro/go-plugins/broker/stan"
_ "github.com/micro/go-plugins/broker/stomp"
_ "github.com/micro/go-plugins/client/http"
_ "github.com/micro/go-plugins/client/http/test"
_ "github.com/micro/go-plugins/client/selector/label"
_ "github.com/micro/go-plugins/client/selector/shard"
_ "github.com/micro/go-plugins/client/selector/static"
_ "github.com/micro/go-plugins/codec/bsonrpc"
_ "github.com/micro/go-plugins/codec/jsonrpc2"
_ "github.com/micro/go-plugins/codec/msgpackrpc"
_ "github.com/micro/go-plugins/config/source/configmap"
_ "github.com/micro/go-plugins/config/source/consul"
_ "github.com/micro/go-plugins/config/source/grpc"
_ "github.com/micro/go-plugins/config/source/grpc/proto"
_ "github.com/micro/go-plugins/config/source/runtimevar"
_ "github.com/micro/go-plugins/config/source/url"
_ "github.com/micro/go-plugins/config/source/vault"
_ "github.com/micro/go-plugins/micro/auth"
_ "github.com/micro/go-plugins/micro/auth/basic"
_ "github.com/micro/go-plugins/micro/auth/digest"
_ "github.com/micro/go-plugins/micro/auth/ldap"
_ "github.com/micro/go-plugins/micro/cors"
_ "github.com/micro/go-plugins/micro/disable_rpc"
_ "github.com/micro/go-plugins/micro/gzip"
_ "github.com/micro/go-plugins/micro/header"
_ "github.com/micro/go-plugins/micro/index"
_ "github.com/micro/go-plugins/micro/ip_whitelist"
_ "github.com/micro/go-plugins/micro/metadata"
_ "github.com/micro/go-plugins/micro/metrics"
_ "github.com/micro/go-plugins/micro/metrics/prometheus"
_ "github.com/micro/go-plugins/micro/router"
_ "github.com/micro/go-plugins/micro/stats_auth"
_ "github.com/micro/go-plugins/micro/trace/awsxray"
_ "github.com/micro/go-plugins/micro/trace/uuid"
_ "github.com/micro/go-plugins/micro/whitelist"
_ "github.com/micro/go-plugins/proxy/http"
_ "github.com/micro/go-plugins/registry/cache"
_ "github.com/micro/go-plugins/registry/consul"
_ "github.com/micro/go-plugins/registry/etcd"
_ "github.com/micro/go-plugins/registry/etcdv3"
_ "github.com/micro/go-plugins/registry/eureka"
_ "github.com/micro/go-plugins/registry/eureka/mock"
_ "github.com/micro/go-plugins/registry/gossip"
_ "github.com/micro/go-plugins/registry/gossip/proto"
_ "github.com/micro/go-plugins/registry/kubernetes"
_ "github.com/micro/go-plugins/registry/kubernetes/client"
_ "github.com/micro/go-plugins/registry/kubernetes/client/api"
_ "github.com/micro/go-plugins/registry/kubernetes/client/mock"
_ "github.com/micro/go-plugins/registry/kubernetes/client/watch"
_ "github.com/micro/go-plugins/registry/mdns"
_ "github.com/micro/go-plugins/registry/memory"
_ "github.com/micro/go-plugins/registry/multi"
_ "github.com/micro/go-plugins/registry/nats"
_ "github.com/micro/go-plugins/registry/proxy"
_ "github.com/micro/go-plugins/registry/service"
_ "github.com/micro/go-plugins/registry/zookeeper"
_ "github.com/micro/go-plugins/server/http"
_ "github.com/micro/go-plugins/service/kubernetes"
_ "github.com/micro/go-plugins/store/consul"
_ "github.com/micro/go-plugins/store/memcached"
_ "github.com/micro/go-plugins/store/redis"
_ "github.com/micro/go-plugins/sync/leader/consul"
_ "github.com/micro/go-plugins/sync/lock/consul"
_ "github.com/micro/go-plugins/sync/lock/redis"
_ "github.com/micro/go-plugins/transport/grpc"
_ "github.com/micro/go-plugins/transport/http"
_ "github.com/micro/go-plugins/transport/memory"
_ "github.com/micro/go-plugins/transport/nats"
_ "github.com/micro/go-plugins/transport/quic"
_ "github.com/micro/go-plugins/transport/rabbitmq"
_ "github.com/micro/go-plugins/transport/tcp"
_ "github.com/micro/go-plugins/transport/utp"
_ "github.com/micro/go-plugins/web/kubernetes"
_ "github.com/micro/go-plugins/wrapper/breaker/gobreaker"
_ "github.com/micro/go-plugins/wrapper/breaker/hystrix"
_ "github.com/micro/go-plugins/wrapper/endpoint"
_ "github.com/micro/go-plugins/wrapper/monitoring/prometheus"
_ "github.com/micro/go-plugins/wrapper/ratelimiter/ratelimit"
_ "github.com/micro/go-plugins/wrapper/ratelimiter/uber"
_ "github.com/micro/go-plugins/wrapper/select/roundrobin"
_ "github.com/micro/go-plugins/wrapper/select/shard"
_ "github.com/micro/go-plugins/wrapper/select/version"
_ "github.com/micro/go-plugins/wrapper/service"
_ "github.com/micro/go-plugins/wrapper/trace/awsxray"
_ "github.com/micro/go-plugins/wrapper/trace/datadog"
_ "github.com/micro/go-plugins/wrapper/trace/opencensus"
_ "github.com/micro/go-plugins/wrapper/trace/opentracing"
_ "github.com/micro/go-plugins/wrapper/validator"
)
|
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
numbers := []string{"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve"}
for {
if len(numbers) == 0 {
break
}
fmt.Printf("len(numbers) = %d ", len(numbers))
rand.Seed(time.Now().UnixNano())
i := rand.Intn(len(numbers))
fmt.Printf("random number: %s\n", numbers[i])
numbers = append(numbers[:i], numbers[i+1:]...)
continue
}
println("-----")
}
|
// Copyright (c) 2013 ActiveState Software Inc. All rights reserved.
package watch
import (
"gopkg.in/fsnotify.v0"
"log"
"sync"
)
type InotifyTracker struct {
mux sync.Mutex
watchers map[*fsnotify.Watcher]bool
}
func NewInotifyTracker() *InotifyTracker {
t := new(InotifyTracker)
t.watchers = make(map[*fsnotify.Watcher]bool)
return t
}
func (t *InotifyTracker) NewWatcher() (*fsnotify.Watcher, error) {
t.mux.Lock()
defer t.mux.Unlock()
w, err := fsnotify.NewWatcher()
if err == nil {
t.watchers[w] = true
}
return w, err
}
func (t *InotifyTracker) CloseWatcher(w *fsnotify.Watcher) (err error) {
t.mux.Lock()
defer t.mux.Unlock()
if _, ok := t.watchers[w]; ok {
err = w.Close()
delete(t.watchers, w)
}
return
}
func (t *InotifyTracker) CloseAll() {
t.mux.Lock()
defer t.mux.Unlock()
for w, _ := range t.watchers {
if err := w.Close(); err != nil {
log.Printf("Error closing watcher: %v", err)
}
delete(t.watchers, w)
}
}
|
package main
// https://leetcode-cn.com/problems/reorder-list/
func reorderList(head *ListNode) {
if head == nil || head.Next == nil {
return
}
slow := head
for fast := head; fast != nil && fast.Next != nil; {
fast = fast.Next.Next
slow = slow.Next
}
halfHead, half := &ListNode{}, slow.Next
slow.Next = nil
for next := half; next != nil; {
tmp := next.Next
next.Next = halfHead.Next
halfHead.Next = next
next = tmp
}
for i, j := head, halfHead.Next; i != slow && j != nil; {
tmpi, tmpj := i.Next, j.Next
i.Next, j.Next = j, tmpi
i, j = tmpi, tmpj
}
}
|
/*
Copyright 2020 The Qmgo Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package qmgo
import (
"context"
"fmt"
"testing"
"time"
"github.com/qiniu/qmgo/operator"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type QueryTestItem struct {
Id primitive.ObjectID `bson:"_id"`
Name string `bson:"name"`
Age int `bson:"age"`
Instock []struct {
Warehouse string `bson:"warehouse"`
Qty int `bson:"qty"`
} `bson:"instock"`
}
type QueryTestItem2 struct {
Class string `bson:"class"`
}
func TestQuery_One(t *testing.T) {
ast := require.New(t)
cli := initClient("test")
defer cli.Close(context.Background())
defer cli.DropCollection(context.Background())
cli.EnsureIndexes(context.Background(), nil, []string{"name"})
id1 := primitive.NewObjectID()
id2 := primitive.NewObjectID()
id3 := primitive.NewObjectID()
docs := []interface{}{
bson.D{{Key: "_id", Value: id1}, {Key: "name", Value: "Alice"}, {Key: "age", Value: 18}},
bson.D{{Key: "_id", Value: id2}, {Key: "name", Value: "Alice"}, {Key: "age", Value: 19}},
bson.D{{Key: "_id", Value: id3}, {Key: "name", Value: "Lucas"}, {Key: "age", Value: 20}},
}
_, _ = cli.InsertMany(context.Background(), docs)
var err error
var res QueryTestItem
filter1 := bson.M{
"name": "Alice",
}
projection1 := bson.M{
"age": 0,
}
err = cli.Find(context.Background(), filter1).Select(projection1).Sort("age").Limit(1).Skip(1).One(&res)
ast.Nil(err)
ast.Equal(id2, res.Id)
ast.Equal("Alice", res.Name)
res = QueryTestItem{}
filter2 := bson.M{
"name": "Lily",
}
err = cli.Find(context.Background(), filter2).One(&res)
ast.Error(err)
ast.Empty(res)
// filter is bson.M{},match all and return one
res = QueryTestItem{}
filter3 := bson.M{}
err = cli.Find(context.Background(), filter3).One(&res)
ast.NoError(err)
ast.NotEmpty(res)
// filter is nil,error
res = QueryTestItem{}
err = cli.Find(context.Background(), nil).One(&res)
ast.Error(err)
ast.Empty(res)
// res is nil or can't parse
err = cli.Find(context.Background(), filter1).One(nil)
ast.Error(err)
var tv int
err = cli.Find(context.Background(), filter1).One(&tv)
ast.Error(err)
// res is a parseable object, but the bson tag is inconsistent with the mongodb record, no error is reported, res is the initialization state of the data structure
var tt QueryTestItem2
err = cli.Find(context.Background(), filter1).One(&tt)
ast.NoError(err)
ast.Empty(tt)
}
func TestQuery_All(t *testing.T) {
ast := require.New(t)
cli := initClient("test")
defer cli.Close(context.Background())
defer cli.DropCollection(context.Background())
cli.EnsureIndexes(context.Background(), nil, []string{"name"})
id1 := primitive.NewObjectID()
id2 := primitive.NewObjectID()
id3 := primitive.NewObjectID()
id4 := primitive.NewObjectID()
docs := []interface{}{
bson.M{"_id": id1, "name": "Alice", "age": 18},
bson.M{"_id": id2, "name": "Alice", "age": 19},
bson.M{"_id": id3, "name": "Lucas", "age": 20},
bson.M{"_id": id4, "name": "Lucas", "age": 21},
}
_, _ = cli.InsertMany(context.Background(), docs)
var err error
var res []QueryTestItem
filter1 := bson.M{
"name": "Alice",
}
projection1 := bson.M{
"name": 0,
}
err = cli.Find(context.Background(), filter1).Select(projection1).Sort("age").Limit(2).Skip(1).All(&res)
ast.NoError(err)
ast.Equal(1, len(res))
res = make([]QueryTestItem, 0)
filter2 := bson.M{
"name": "Lily",
}
err = cli.Find(context.Background(), filter2).All(&res)
ast.NoError(err)
ast.Empty(res)
// filter is bson.M{}, which means to match all, will return all records in the collection
res = make([]QueryTestItem, 0)
filter3 := bson.M{}
err = cli.Find(context.Background(), filter3).All(&res)
ast.NoError(err)
ast.Equal(4, len(res))
res = make([]QueryTestItem, 0)
err = cli.Find(context.Background(), nil).All(&res)
ast.Error(err)
ast.Empty(res)
err = cli.Find(context.Background(), filter1).All(nil)
ast.Error(err)
var tv int
err = cli.Find(context.Background(), filter1).All(&tv)
ast.Error(err)
// res is a parseable object, but the bson tag is inconsistent with the mongodb record, and no error is reported
// The corresponding value will be mapped according to the bson tag of the res data structure, and the tag without the value will be the default value of the corresponding type
// The length of res is the number of records filtered by the filter condition
var tt []QueryTestItem2
err = cli.Find(context.Background(), filter1).All(&tt)
ast.NoError(err)
ast.Equal(2, len(tt))
}
func TestQuery_Count(t *testing.T) {
ast := require.New(t)
cli := initClient("test")
defer cli.Close(context.Background())
defer cli.DropCollection(context.Background())
cli.EnsureIndexes(context.Background(), nil, []string{"name"})
id1 := primitive.NewObjectID()
id2 := primitive.NewObjectID()
id3 := primitive.NewObjectID()
id4 := primitive.NewObjectID()
docs := []interface{}{
bson.M{"_id": id1, "name": "Alice", "age": 18},
bson.M{"_id": id2, "name": "Alice", "age": 19},
bson.M{"_id": id3, "name": "Lucas", "age": 20},
bson.M{"_id": id4, "name": "Lucas", "age": 21},
}
_, _ = cli.InsertMany(context.Background(), docs)
var err error
var cnt int64
filter1 := bson.M{
"name": "Alice",
}
cnt, err = cli.Find(context.Background(), filter1).Limit(2).Skip(1).Count()
ast.NoError(err)
ast.Equal(int64(1), cnt)
filter2 := bson.M{
"name": "Lily",
}
cnt, err = cli.Find(context.Background(), filter2).Count()
ast.NoError(err)
ast.Zero(cnt)
filter3 := bson.M{}
cnt, err = cli.Find(context.Background(), filter3).Count()
ast.NoError(err)
ast.Equal(int64(4), cnt)
cnt, err = cli.Find(context.Background(), nil).Count()
ast.Error(err)
ast.Zero(cnt)
}
func TestQuery_Skip(t *testing.T) {
ast := require.New(t)
cli := initClient("test")
defer cli.Close(context.Background())
defer cli.DropCollection(context.Background())
cli.EnsureIndexes(context.Background(), nil, []string{"name"})
id1 := primitive.NewObjectID()
id2 := primitive.NewObjectID()
id3 := primitive.NewObjectID()
id4 := primitive.NewObjectID()
docs := []interface{}{
bson.M{"_id": id1, "name": "Alice", "age": 18},
bson.M{"_id": id2, "name": "Alice", "age": 19},
bson.M{"_id": id3, "name": "Lucas", "age": 20},
bson.M{"_id": id4, "name": "Lucas", "age": 21},
}
_, _ = cli.InsertMany(context.Background(), docs)
var err error
var res []QueryTestItem
// filter can match records, skip 1 record, and return the remaining records
filter1 := bson.M{
"name": "Alice",
}
err = cli.Find(context.Background(), filter1).Skip(1).All(&res)
ast.NoError(err)
ast.Equal(1, len(res))
// filter can match the records, the number of skips is greater than the total number of existing records, res returns empty
res = make([]QueryTestItem, 0)
err = cli.Find(context.Background(), filter1).Skip(3).All(&res)
ast.NoError(err)
ast.Empty(res)
res = make([]QueryTestItem, 0)
err = cli.Find(context.Background(), filter1).Skip(-3).All(&res)
ast.Error(err)
ast.Empty(res)
}
func TestQuery_Limit(t *testing.T) {
ast := require.New(t)
cli := initClient("test")
defer cli.Close(context.Background())
defer cli.DropCollection(context.Background())
cli.EnsureIndexes(context.Background(), nil, []string{"name"})
id1 := primitive.NewObjectID()
id2 := primitive.NewObjectID()
id3 := primitive.NewObjectID()
id4 := primitive.NewObjectID()
docs := []interface{}{
bson.M{"_id": id1, "name": "Alice", "age": 18},
bson.M{"_id": id2, "name": "Alice", "age": 19},
bson.M{"_id": id3, "name": "Lucas", "age": 20},
bson.M{"_id": id4, "name": "Lucas", "age": 21},
}
_, _ = cli.InsertMany(context.Background(), docs)
var err error
var res []QueryTestItem
filter1 := bson.M{
"name": "Alice",
}
err = cli.Find(context.Background(), filter1).Limit(1).All(&res)
ast.NoError(err)
ast.Equal(1, len(res))
res = make([]QueryTestItem, 0)
err = cli.Find(context.Background(), filter1).Limit(3).All(&res)
ast.NoError(err)
ast.Equal(2, len(res))
res = make([]QueryTestItem, 0)
var cursor CursorI
cursor = cli.Find(context.Background(), filter1).Limit(-2).Cursor()
ast.NoError(cursor.Err())
ast.NotNil(cursor)
}
func TestQuery_Sort(t *testing.T) {
ast := require.New(t)
cli := initClient("test")
defer cli.Close(context.Background())
defer cli.DropCollection(context.Background())
cli.EnsureIndexes(context.Background(), nil, []string{"name"})
id1 := primitive.NewObjectID()
id2 := primitive.NewObjectID()
id3 := primitive.NewObjectID()
id4 := primitive.NewObjectID()
docs := []interface{}{
bson.M{"_id": id1, "name": "Alice", "age": 18},
bson.M{"_id": id2, "name": "Alice", "age": 19},
bson.M{"_id": id3, "name": "Lucas", "age": 18},
bson.M{"_id": id4, "name": "Lucas", "age": 19},
}
_, _ = cli.InsertMany(context.Background(), docs)
var err error
var res []QueryTestItem
// Sort a single field in ascending order
filter1 := bson.M{
"name": "Alice",
}
err = cli.Find(context.Background(), filter1).Sort("age").All(&res)
ast.NoError(err)
ast.Equal(2, len(res))
ast.Equal(id1, res[0].Id)
ast.Equal(id2, res[1].Id)
// Sort a single field in descending order
err = cli.Find(context.Background(), filter1).Sort("-age").All(&res)
ast.NoError(err)
ast.Equal(2, len(res))
ast.Equal(id2, res[0].Id)
ast.Equal(id1, res[1].Id)
// Sort a single field in descending order, and sort the other field in ascending order
err = cli.Find(context.Background(), bson.M{}).Sort("-age", "+name").All(&res)
ast.NoError(err)
ast.Equal(4, len(res))
ast.Equal(id2, res[0].Id)
ast.Equal(id4, res[1].Id)
ast.Equal(id1, res[2].Id)
ast.Equal(id3, res[3].Id)
// fields is "",panic
res = make([]QueryTestItem, 0)
ast.Panics(func() {
cli.Find(context.Background(), filter1).Sort("").All(&res)
})
// fields is empty, does not panic or error (#128)
err = cli.Find(context.Background(), bson.M{}).Sort().All(&res)
ast.NoError(err)
ast.Equal(4, len(res))
}
func TestQuery_Distinct(t *testing.T) {
ast := require.New(t)
cli := initClient("test")
defer cli.Close(context.Background())
defer cli.DropCollection(context.Background())
cli.EnsureIndexes(context.Background(), nil, []string{"name"})
id1 := primitive.NewObjectID()
id2 := primitive.NewObjectID()
id3 := primitive.NewObjectID()
id4 := primitive.NewObjectID()
id5 := primitive.NewObjectID()
id6 := primitive.NewObjectID()
docs := []interface{}{
bson.M{"_id": id1, "name": "Alice", "age": 18},
bson.M{"_id": id2, "name": "Alice", "age": 19},
bson.M{"_id": id3, "name": "Lucas", "age": 20},
bson.M{"_id": id4, "name": "Lucas", "age": 21},
bson.M{"_id": id5, "name": "Kitty", "age": 23, "detail": bson.M{"errInfo": "timeout", "extra": "i/o"}},
bson.M{"_id": id6, "name": "Kitty", "age": "23", "detail": bson.M{"errInfo": "timeout", "extra": "i/o"}},
}
_, _ = cli.InsertMany(context.Background(), docs)
var err error
filter1 := bson.M{
"name": "Lily",
}
var res1 []int32
err = cli.Find(context.Background(), filter1).Distinct("age", &res1)
ast.NoError(err)
ast.Equal(0, len(res1))
filter2 := bson.M{
"name": "Alice",
}
var res2 []int32
err = cli.Find(context.Background(), filter2).Distinct("age", &res2)
ast.NoError(err)
ast.Equal(2, len(res2))
var res3 []int32
err = cli.Find(context.Background(), filter2).Distinct("age", res3)
ast.EqualError(err, ErrQueryNotSlicePointer.Error())
var res4 int
err = cli.Find(context.Background(), filter2).Distinct("age", &res4)
ast.EqualError(err, ErrQueryNotSliceType.Error())
var res5 []string
err = cli.Find(context.Background(), filter2).Distinct("age", &res5)
ast.EqualError(err, ErrQueryResultTypeInconsistent.Error())
// different behavior with different version of mongod, v4.4.0 return err and v4.0.19 return nil
//var res6 []int32
//err = cli.Find(context.Background(), filter2).Distinct("", &res6)
//ast.Error(err) // (Location40352) FieldPath cannot be constructed with empty string
//ast.Equal(0, len(res6))
var res7 []int32
filter3 := 1
err = cli.Find(context.Background(), filter3).Distinct("age", &res7)
ast.Error(err)
ast.Equal(0, len(res7))
var res8 interface{}
res8 = []string{}
err = cli.Find(context.Background(), filter2).Distinct("age", &res8)
ast.NoError(err)
ast.NotNil(res8)
res9, ok := res8.(primitive.A)
ast.Equal(true, ok)
ast.Len(res9, 2)
filter4 := bson.M{}
var res10 []int32
err = cli.Find(context.Background(), filter4).Distinct("detail", &res10)
ast.EqualError(err, ErrQueryResultTypeInconsistent.Error())
type tmpStruct struct {
ErrInfo string `bson:"errInfo"`
Extra string `bson:"extra"`
}
var res11 []tmpStruct
err = cli.Find(context.Background(), filter4).Distinct("detail", &res11)
ast.NoError(err)
type tmpErrStruct struct {
ErrInfo string `bson:"errInfo"`
Extra time.Time `bson:"extra"`
}
var res12 []tmpErrStruct
err = cli.Find(context.Background(), filter4).Distinct("detail", &res12)
ast.EqualError(err, ErrQueryResultTypeInconsistent.Error())
var res13 []int32
err = cli.Find(context.Background(), filter4).Distinct("age", &res13)
ast.EqualError(err, ErrQueryResultTypeInconsistent.Error())
var res14 []interface{}
err = cli.Find(context.Background(), filter4).Distinct("age", &res14)
ast.NoError(err)
ast.Len(res14, 6)
for _, v := range res14 {
switch v.(type) {
case int32:
fmt.Printf("int32 :%d\n", v)
case string:
fmt.Printf("string :%s\n", v)
default:
fmt.Printf("defalut err: %v %T\n", v, v)
}
}
}
func TestQuery_Select(t *testing.T) {
ast := require.New(t)
cli := initClient("test")
defer cli.Close(context.Background())
defer cli.DropCollection(context.Background())
cli.EnsureIndexes(context.Background(), nil, []string{"name"})
id1 := primitive.NewObjectID()
id2 := primitive.NewObjectID()
id3 := primitive.NewObjectID()
id4 := primitive.NewObjectID()
docs := []interface{}{
bson.M{"_id": id1, "name": "Alice", "age": 18},
bson.M{"_id": id2, "name": "Alice", "age": 19},
bson.M{"_id": id3, "name": "Lucas", "age": 20},
bson.M{"_id": id4, "name": "Lucas", "age": 21},
}
_, _ = cli.InsertMany(context.Background(), docs)
var err error
var res QueryTestItem
filter1 := bson.M{
"_id": id1,
}
projection1 := bson.M{
"age": 1,
}
err = cli.Find(context.Background(), filter1).Select(projection1).One(&res)
ast.NoError(err)
ast.NotNil(res)
ast.Equal("", res.Name)
ast.Equal(18, res.Age)
ast.Equal(id1, res.Id)
res = QueryTestItem{}
projection2 := bson.M{
"age": 0,
}
err = cli.Find(context.Background(), filter1).Select(projection2).One(&res)
ast.NoError(err)
ast.NotNil(res)
ast.Equal("Alice", res.Name)
ast.Equal(0, res.Age)
ast.Equal(id1, res.Id)
res = QueryTestItem{}
projection3 := bson.M{
"_id": 0,
}
err = cli.Find(context.Background(), filter1).Select(projection3).One(&res)
ast.NoError(err)
ast.NotNil(res)
ast.Equal("Alice", res.Name)
ast.Equal(18, res.Age)
ast.Equal(primitive.NilObjectID, res.Id)
}
func TestQuery_Cursor(t *testing.T) {
ast := require.New(t)
cli := initClient("test")
defer cli.Close(context.Background())
defer cli.DropCollection(context.Background())
cli.EnsureIndexes(context.Background(), nil, []string{"name"})
id1 := primitive.NewObjectID()
id2 := primitive.NewObjectID()
id3 := primitive.NewObjectID()
id4 := primitive.NewObjectID()
docs := []interface{}{
bson.D{{"_id", id1}, {"name", "Alice"}, {"age", 18}},
bson.D{{"_id", id2}, {"name", "Alice"}, {"age", 19}},
bson.D{{"_id", id3}, {"name", "Lucas"}, {"age", 20}},
bson.D{{"_id", id4}, {"name", "Lucas"}, {"age", 21}},
}
_, _ = cli.InsertMany(context.Background(), docs)
var res QueryTestItem
filter1 := bson.M{
"name": "Alice",
}
projection1 := bson.M{
"name": 0,
}
cursor := cli.Find(context.Background(), filter1).Select(projection1).Sort("age").Limit(2).Skip(1).Cursor()
ast.NoError(cursor.Err())
ast.NotNil(cursor)
val := cursor.Next(&res)
ast.Equal(true, val)
ast.Equal(id2, res.Id)
val = cursor.Next(&res)
ast.Equal(false, val)
filter2 := bson.M{
"name": "Lily",
}
cursor = cli.Find(context.Background(), filter2).Cursor()
ast.NoError(cursor.Err())
ast.NotNil(cursor)
res = QueryTestItem{}
val = cursor.Next(&res)
ast.Equal(false, val)
ast.Empty(res)
filter3 := 1
cursor = cli.Find(context.Background(), filter3).Cursor()
ast.Error(cursor.Err())
}
func TestQuery_Hint(t *testing.T) {
ast := require.New(t)
cli := initClient("test")
defer cli.Close(context.Background())
defer cli.DropCollection(context.Background())
cli.EnsureIndexes(context.Background(), nil, []string{"name", "age"})
id1 := primitive.NewObjectID()
id2 := primitive.NewObjectID()
id3 := primitive.NewObjectID()
id4 := primitive.NewObjectID()
docs := []interface{}{
bson.M{"_id": id1, "name": "Alice", "age": 18},
bson.M{"_id": id2, "name": "Alice", "age": 19},
bson.M{"_id": id3, "name": "Lucas", "age": 20},
bson.M{"_id": id4, "name": "Lucas", "age": 21},
}
_, _ = cli.InsertMany(context.Background(), docs)
var err error
var res []QueryTestItem
filter1 := bson.M{
"name": "Alice",
"age": 18,
}
// index name as hint
err = cli.Find(context.Background(), filter1).Hint("age_1").All(&res)
ast.NoError(err)
ast.Equal(1, len(res))
// index name as hint
var resOne QueryTestItem
err = cli.Find(context.Background(), filter1).Hint("name_1").One(&resOne)
ast.NoError(err)
// not index name as hint
err = cli.Find(context.Background(), filter1).Hint("age").All(&res)
ast.Error(err)
// nil hint
err = cli.Find(context.Background(), filter1).Hint(nil).All(&res)
ast.NoError(err)
}
func TestQuery_Apply(t *testing.T) {
ast := require.New(t)
cli := initClient("test")
defer cli.Close(context.Background())
defer cli.DropCollection(context.Background())
cli.EnsureIndexes(context.Background(), nil, []string{"name"})
id1 := primitive.NewObjectID()
id2 := primitive.NewObjectID()
id3 := primitive.NewObjectID()
docs := []interface{}{
bson.M{"_id": id1, "name": "Alice", "age": 18},
bson.M{"_id": id2, "name": "Alice", "age": 19},
bson.M{"_id": id3, "name": "Lucas", "age": 20, "instock": []bson.M{
{"warehouse": "B", "qty": 15},
{"warehouse": "C", "qty": 35},
{"warehouse": "E", "qty": 15},
{"warehouse": "F", "qty": 45},
}}}
_, _ = cli.InsertMany(context.Background(), docs)
var err error
res1 := QueryTestItem{}
filter1 := bson.M{
"name": "Tom",
}
change1 := Change{}
err = cli.Find(context.Background(), filter1).Apply(change1, &res1)
ast.EqualError(err, mongo.ErrNilDocument.Error())
change1.Update = bson.M{
operator.Set: bson.M{
"name": "Tom",
"age": 18,
},
}
err = cli.Find(context.Background(), filter1).Apply(change1, &res1)
ast.EqualError(err, mongo.ErrNoDocuments.Error())
change1.ReturnNew = true
err = cli.Find(context.Background(), filter1).Apply(change1, &res1)
ast.EqualError(err, mongo.ErrNoDocuments.Error())
change1.ReturnNew = false
change1.Upsert = true
err = cli.Find(context.Background(), filter1).Apply(change1, &res1)
ast.NoError(err)
ast.Equal("", res1.Name)
ast.Equal(0, res1.Age)
change1.Update = bson.M{
operator.Set: bson.M{
"name": "Tom",
"age": 19,
},
}
change1.ReturnNew = true
change1.Upsert = true
err = cli.Find(context.Background(), filter1).Apply(change1, &res1)
ast.NoError(err)
ast.Equal("Tom", res1.Name)
ast.Equal(19, res1.Age)
res2 := QueryTestItem{}
filter2 := bson.M{
"name": "Alice",
}
change2 := Change{
ReturnNew: true,
Update: bson.M{
operator.Set: bson.M{
"name": "Alice",
"age": 22,
},
},
}
projection2 := bson.M{
"age": 1,
}
err = cli.Find(context.Background(), filter2).Sort("age").Select(projection2).Apply(change2, &res2)
ast.NoError(err)
ast.Equal("", res2.Name)
ast.Equal(22, res2.Age)
res3 := QueryTestItem{}
filter3 := bson.M{
"name": "Bob",
}
change3 := Change{
Remove: true,
}
err = cli.Find(context.Background(), filter3).Apply(change3, &res3)
ast.EqualError(err, mongo.ErrNoDocuments.Error())
res3 = QueryTestItem{}
filter3 = bson.M{
"name": "Alice",
}
projection3 := bson.M{
"age": 1,
}
err = cli.Find(context.Background(), filter3).Sort("age").Select(projection3).Apply(change3, &res3)
ast.NoError(err)
ast.Equal("", res3.Name)
ast.Equal(19, res3.Age)
res4 := QueryTestItem{}
filter4 := bson.M{
"name": "Bob",
}
change4 := Change{
Replace: true,
Update: bson.M{
operator.Set: bson.M{
"name": "Bob",
"age": 23,
},
},
}
err = cli.Find(context.Background(), filter4).Apply(change4, &res4)
ast.EqualError(err, ErrReplacementContainUpdateOperators.Error())
change4.Update = bson.M{"name": "Bob", "age": 23}
err = cli.Find(context.Background(), filter4).Apply(change4, &res4)
ast.EqualError(err, mongo.ErrNoDocuments.Error())
change4.ReturnNew = true
err = cli.Find(context.Background(), filter4).Apply(change4, &res4)
ast.EqualError(err, mongo.ErrNoDocuments.Error())
change4.Upsert = true
change4.ReturnNew = true
err = cli.Find(context.Background(), filter4).Apply(change4, &res4)
ast.NoError(err)
ast.Equal("Bob", res4.Name)
ast.Equal(23, res4.Age)
change4 = Change{
Replace: true,
Update: bson.M{"name": "Bob", "age": 25},
Upsert: true,
ReturnNew: false,
}
projection4 := bson.M{
"age": 1,
"name": 1,
}
err = cli.Find(context.Background(), filter4).Sort("age").Select(projection4).Apply(change4, &res4)
ast.NoError(err)
ast.Equal("Bob", res4.Name)
ast.Equal(23, res4.Age)
res4 = QueryTestItem{}
filter4 = bson.M{
"name": "James",
}
change4 = Change{
Replace: true,
Update: bson.M{"name": "James", "age": 26},
Upsert: true,
ReturnNew: false,
}
err = cli.Find(context.Background(), filter4).Apply(change4, &res4)
ast.NoError(err)
ast.Equal("", res4.Name)
ast.Equal(0, res4.Age)
var res5 = QueryTestItem{}
filter5 := bson.M{"name": "Lucas"}
change5 := Change{
Update: bson.M{"$set": bson.M{"instock.$[elem].qty": 100}},
ReturnNew: true,
}
err = cli.Find(context.Background(), filter5).SetArrayFilters(&options.ArrayFilters{Filters: []interface{}{
bson.M{"elem.warehouse": bson.M{"$in": []string{"C", "F"}}},
}}).Apply(change5, &res5)
ast.NoError(err)
for _, item := range res5.Instock {
switch item.Warehouse {
case "C", "F":
ast.Equal(100, item.Qty)
case "B", "E":
ast.Equal(15, item.Qty)
}
}
}
func TestQuery_BatchSize(t *testing.T) {
ast := require.New(t)
cli := initClient("test")
defer cli.Close(context.Background())
defer cli.DropCollection(context.Background())
cli.EnsureIndexes(context.Background(), nil, []string{"name"})
id1 := primitive.NewObjectID()
id2 := primitive.NewObjectID()
id3 := primitive.NewObjectID()
id4 := primitive.NewObjectID()
docs := []interface{}{
bson.M{"_id": id1, "name": "Alice", "age": 18},
bson.M{"_id": id2, "name": "Alice", "age": 19},
bson.M{"_id": id3, "name": "Lucas", "age": 20},
bson.M{"_id": id4, "name": "Lucas", "age": 21},
}
_, _ = cli.InsertMany(context.Background(), docs)
var res []QueryTestItem
err := cli.Find(context.Background(), bson.M{"name": "Alice"}).BatchSize(1).All(&res)
ast.NoError(err)
ast.Len(res, 2)
}
|
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package commitment
import (
"crypto"
"github.com/trustbloc/edge-core/pkg/log"
"github.com/trustbloc/sidetree-core-go/pkg/canonicalizer"
"github.com/trustbloc/sidetree-core-go/pkg/docutil"
"github.com/trustbloc/sidetree-core-go/pkg/hashing"
"github.com/trustbloc/sidetree-core-go/pkg/jws"
)
var logger = log.New("sidetree-core-commitment")
// Calculate will calculate commitment hash from JWK.
func Calculate(jwk *jws.JWK, multihashCode uint, hash crypto.Hash) (string, error) {
data, err := canonicalizer.MarshalCanonical(jwk)
if err != nil {
return "", err
}
logger.Debugf("calculating commitment from JWK: %s", string(data))
dataHash, err := hashing.GetHash(hash, data)
if err != nil {
return "", err
}
multiHash, err := docutil.ComputeMultihash(multihashCode, dataHash)
if err != nil {
return "", err
}
return docutil.EncodeToString(multiHash), nil
}
|
package common
import (
micro "github.com/micro/go-micro"
"github.com/micro/go-micro/client"
tracingWrapper "github.com/micro/go-plugins/wrapper/trace/opentracing"
opentracing "github.com/opentracing/opentracing-go"
"io"
"log"
"mix/test/utils/flags"
"mix/test/utils/trace"
)
var TracerCloser io.Closer
func initOpenTracing(serviceFlags *flags.Flags, microService micro.Service) {
tracer, closer, err := trace.NewTracer(&trace.Config{
ServiceName: serviceFlags.ServiceName,
JaegerHost: Config.Tracing.Jaeger.GetHost(),
JaegerPort: Config.Tracing.Jaeger.GetPort(),
SamplerType: Config.Tracing.Jaeger.GetSamplerType(),
SamplerParam: Config.Tracing.Jaeger.GetSamplerParam(),
ReporterLogSpans: Config.Tracing.Jaeger.GetReporterLogSpans(),
})
if err != nil {
log.Fatal(err)
}
TracerCloser = closer
opentracing.SetGlobalTracer(tracer)
err = microService.Client().Init(
client.WrapCall(tracingWrapper.NewCallWrapper(tracer)),
)
if err != nil {
log.Fatal(err)
}
}
|
// This file was generated for SObject LightningComponentResource, API Version v43.0 at 2018-07-30 03:48:05.787449968 -0400 EDT m=+52.132012535
package sobjects
import (
"fmt"
"strings"
)
type LightningComponentResource struct {
BaseSObject
CreatedById string `force:",omitempty"`
CreatedDate string `force:",omitempty"`
FilePath string `force:",omitempty"`
Format string `force:",omitempty"`
Id string `force:",omitempty"`
IsDeleted bool `force:",omitempty"`
LastModifiedById string `force:",omitempty"`
LastModifiedDate string `force:",omitempty"`
LightningComponentBundleId string `force:",omitempty"`
Source string `force:",omitempty"`
SystemModstamp string `force:",omitempty"`
}
func (t *LightningComponentResource) ApiName() string {
return "LightningComponentResource"
}
func (t *LightningComponentResource) String() string {
builder := strings.Builder{}
builder.WriteString(fmt.Sprintf("LightningComponentResource #%s - %s\n", t.Id, t.Name))
builder.WriteString(fmt.Sprintf("\tCreatedById: %v\n", t.CreatedById))
builder.WriteString(fmt.Sprintf("\tCreatedDate: %v\n", t.CreatedDate))
builder.WriteString(fmt.Sprintf("\tFilePath: %v\n", t.FilePath))
builder.WriteString(fmt.Sprintf("\tFormat: %v\n", t.Format))
builder.WriteString(fmt.Sprintf("\tId: %v\n", t.Id))
builder.WriteString(fmt.Sprintf("\tIsDeleted: %v\n", t.IsDeleted))
builder.WriteString(fmt.Sprintf("\tLastModifiedById: %v\n", t.LastModifiedById))
builder.WriteString(fmt.Sprintf("\tLastModifiedDate: %v\n", t.LastModifiedDate))
builder.WriteString(fmt.Sprintf("\tLightningComponentBundleId: %v\n", t.LightningComponentBundleId))
builder.WriteString(fmt.Sprintf("\tSource: %v\n", t.Source))
builder.WriteString(fmt.Sprintf("\tSystemModstamp: %v\n", t.SystemModstamp))
return builder.String()
}
type LightningComponentResourceQueryResponse struct {
BaseQuery
Records []LightningComponentResource `json:"Records" force:"records"`
}
|
package client
import (
"reflect"
"testing"
)
func Test_strinifyEnv(t *testing.T) {
cases := []struct {
name string
input map[string]string
expect string
}{
{
name: "empty env",
input: map[string]string{},
expect: "",
},
{
name: "normal env",
input: map[string]string{
"CWD": "/a/b/c",
},
expect: "CWD=\"/a/b/c\"",
},
{
name: "enquote",
input: map[string]string{
"CMD": "a\\b\"c",
},
expect: "CMD=\"a\\\\b\\\"c\"", // CMD="a\\b\"c"
},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
data := stringifyEnv(tt.input)
if data != tt.expect {
t.Errorf("unmatched data, expect -> %s, actual -> %s", tt.expect, data)
}
})
}
}
func Test_parseEnv(t *testing.T) {
cases := []struct {
name string
input string
expect map[string]string
}{
{
name: "empty parse",
input: "",
expect: map[string]string{},
},
{
name: "normal parse",
input: `A="12B",B="24C",C123="QQR"`,
expect: map[string]string{
"A": "12B",
"B": "24C",
"C123": "QQR",
},
},
{
name: "with quote",
input: `A="这是一个\"\\",B="normal string "`,
expect: map[string]string{
"A": `这是一个"\`,
"B": "normal string ",
},
},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
out, err := parseEnv(tt.input)
if err != nil {
t.Errorf("an error happened: %s", err.Error())
}
if !reflect.DeepEqual(out, tt.expect) {
t.Errorf("not match: expect -> %v, got -> %v", tt.expect, out)
}
})
}
}
|
package common
import "github.com/robertang/collector/cncf"
type MetricModule struct {
NewMetric func(config cncf.MetricConfig) Metric
}
type OutputModule struct {
NewOutput func(oc cncf.OutputConfig) Output
}
type Output interface {
Output(text interface{}) error
}
type Metric interface {
Collect(host string) (interface{}, error)
Start(output Output)
}
|
package gunit
import (
"bytes"
"io/ioutil"
"strings"
)
// lines cache
// fileName -> []line
type linesCache map[string][]string
func newLinesCache() linesCache {
rv := make(map[string][]string)
return linesCache(rv)
}
func (self linesCache) Put(fileName string) ([]string, error) {
lines, found := self[fileName]
if found {
return lines, nil
}
return readLines(fileName)
}
const lineDelimString = "\n"
var lineDelim = byte(lineDelimString[0])
func readLines(fileName string) ([]string, error) {
var originData []byte
var err error
if originData, err = ioutil.ReadFile(fileName); err != nil {
return nil, err
}
buf := bytes.NewBuffer(originData)
lines := make([]string, 0, 128)
for err == nil {
var line string
line, err = buf.ReadString(lineDelim)
line = strings.TrimSuffix(line, lineDelimString)
lines = append(lines, line)
}
return lines, err
}
|
/*
Copyright 2021 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package common
import (
"context"
"encoding/json"
"strings"
"github.com/pkg/errors"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/yaml"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/apis/types"
cmdutil "github.com/oam-dev/kubevela/pkg/utils/util"
)
// InstallComponentDefinition will add a component into K8s cluster and install its controller
func InstallComponentDefinition(client client.Client, componentData []byte, ioStreams cmdutil.IOStreams) error {
var cd v1beta1.ComponentDefinition
var err error
if componentData == nil {
return errors.New("componentData is nil")
}
if err = yaml.Unmarshal(componentData, &cd); err != nil {
return err
}
cd.Namespace = types.DefaultKubeVelaNS
ioStreams.Info("Installing component: " + cd.Name)
if err = client.Create(context.Background(), &cd); err != nil && !apierrors.IsAlreadyExists(err) {
return err
}
return nil
}
// InstallTraitDefinition will add a trait into K8s cluster and install it's controller
func InstallTraitDefinition(client client.Client, traitdata []byte, ioStreams cmdutil.IOStreams) error {
var td v1beta1.TraitDefinition
var err error
if err = yaml.Unmarshal(traitdata, &td); err != nil {
return err
}
td.Namespace = types.DefaultKubeVelaNS
ioStreams.Info("Installing trait " + td.Name)
if err = client.Create(context.Background(), &td); err != nil && !apierrors.IsAlreadyExists(err) {
return err
}
return nil
}
func addSourceIntoExtension(in *runtime.RawExtension, source *types.Source) error {
var extension map[string]interface{}
err := json.Unmarshal(in.Raw, &extension)
if err != nil {
return err
}
extension["source"] = source
data, err := json.Marshal(extension)
if err != nil {
return err
}
in.Raw = data
return nil
}
// CheckLabelExistence checks whether a label `key=value` exists in definition labels
func CheckLabelExistence(labels map[string]string, label string) bool {
splitLabel := strings.Split(label, "=")
if len(splitLabel) < 2 {
return false
}
k, v := splitLabel[0], splitLabel[1]
if labelValue, ok := labels[k]; ok {
if labelValue == v {
return true
}
}
return false
}
|
package base
import (
"bytes"
"io"
"io/ioutil"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
type fakeOpError struct {
timeout bool
temporary bool
}
func (f fakeOpError) Error() string {
return "fake error"
}
func (f fakeOpError) Timeout() bool {
return f.timeout
}
func (f fakeOpError) Temporary() bool {
return f.temporary
}
func TestOpError(t *testing.T) {
at := assert.New(t)
tests := []struct {
url string
op string
err error
timeout bool
temporary bool
errString string
}{
{"http://domain/abc", "post(write) to", io.EOF, false, false, "post(write) to http://domain/abc: EOF"},
{"http://domain/abc", "get(read) from", io.EOF, false, false, "get(read) from http://domain/abc: EOF"},
{"http://domain/abc", "post(write) to", fakeOpError{true, false}, true, false, "post(write) to http://domain/abc: fake error"},
{"http://domain/abc", "get(read) from", fakeOpError{false, true}, false, true, "get(read) from http://domain/abc: fake error"},
}
for _, test := range tests {
err := OpErr(test.url, test.op, test.err)
e, ok := err.(*OpError)
at.True(ok)
at.Equal(test.timeout, e.Timeout())
at.Equal(test.temporary, e.Temporary())
at.Equal(test.errString, e.Error())
}
}
func TestFrameType(t *testing.T) {
at := assert.New(t)
tests := []struct {
b byte
typ FrameType
outb byte
}{
{0, FrameString, 0},
{1, FrameBinary, 1},
}
for _, test := range tests {
typ := ByteToFrameType(test.b)
at.Equal(test.typ, typ)
b := typ.Byte()
at.Equal(test.outb, b)
}
}
func TestConnParameters(t *testing.T) {
at := assert.New(t)
tests := []struct {
para ConnParameters
out string
}{
{
ConnParameters{
time.Second * 10,
time.Second * 5,
"vCcJKmYQcIf801WDAAAB",
[]string{"websocket", "polling"},
},
"{\"sid\":\"vCcJKmYQcIf801WDAAAB\",\"upgrades\":[\"websocket\",\"polling\"],\"pingInterval\":10000,\"pingTimeout\":5000}\n",
},
}
for _, test := range tests {
buf := bytes.NewBuffer(nil)
n, err := test.para.WriteTo(buf)
at.Nil(err)
at.Equal(int64(len(test.out)), n)
at.Equal(test.out, buf.String())
conn, err := ReadConnParameters(buf)
at.Nil(err)
at.Equal(test.para, conn)
}
}
func BenchmarkConnParameters(b *testing.B) {
param := ConnParameters{
time.Second * 10,
time.Second * 5,
"vCcJKmYQcIf801WDAAAB",
[]string{"websocket", "polling"},
}
discarder := ioutil.Discard
b.ResetTimer()
for i := 0; i < b.N; i++ {
param.WriteTo(discarder)
}
}
|
/*
Given a number between 1-26, return what letter is at that position in the alphabet. Return "invalid" if the number given is not within that range, or isn't an integer.
Examples
letterAtPosition(1) ➞ "a"
letterAtPosition(26.0) ➞ "z"
letterAtPosition(0) ➞ "invalid"
letterAtPosition(4.5) ➞ "invalid"
Notes
Return a lowercase letter.
Numbers that end with ".0" are valid.
*/
package main
import (
"fmt"
"math"
)
func main() {
assert(letterpos(1) == "a")
assert(letterpos(2) == "b")
assert(letterpos(3) == "c")
assert(letterpos(4) == "d")
assert(letterpos(5) == "e")
assert(letterpos(6) == "f")
assert(letterpos(7) == "g")
assert(letterpos(8) == "h")
assert(letterpos(9) == "i")
assert(letterpos(10) == "j")
assert(letterpos(11) == "k")
assert(letterpos(12) == "l")
assert(letterpos(13) == "m")
assert(letterpos(14) == "n")
assert(letterpos(15) == "o")
assert(letterpos(16) == "p")
assert(letterpos(17) == "q")
assert(letterpos(18) == "r")
assert(letterpos(19) == "s")
assert(letterpos(20) == "t")
assert(letterpos(21) == "u")
assert(letterpos(22) == "v")
assert(letterpos(23) == "w")
assert(letterpos(24) == "x")
assert(letterpos(25) == "y")
assert(letterpos(26) == "z")
assert(letterpos(0) == "invalid")
assert(letterpos(4.5) == "invalid")
assert(letterpos(4.0) == "d")
assert(letterpos(1.0) == "a")
assert(letterpos(26.0) == "z")
}
func letterpos(p float64) string {
i, f := math.Modf(p)
if f != 0 || !(1 <= i && i <= 26) {
return "invalid"
}
return fmt.Sprintf("%c", 'a'+int(i)-1)
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
|
package main
import (
"fmt"
"runtime"
"sync"
)
const MAX int = 10
var (
counter int = 0
wg sync.WaitGroup
)
func Count(channel chan int) {
defer wg.Done()
count, ok := <- channel
if !ok {
return
}
value := count
runtime.Gosched()
value ++
count = value
if count == MAX {
close(channel)
counter = count
return
}
channel <- count
}
func main() {
wg.Add(MAX)
channel := make(chan int)
for i:=0; i<MAX; i++ {
go Count(channel)
}
channel <- counter
wg.Wait()
fmt.Println("channel final counter: ", counter)
}
|
// package main
// import (
// "fmt"
// "os"
// "strconv"
// )
// level 3: doopprog
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
args := os.Args
if len(args) != 4 {
return
}
if args[2] != "+" && args[2] != "-" && args[2] != "/" && args[2] != "*" && args[2] != "%" {
fmt.Println(0)
return
}
// arg1 := getArg(args[1])
arg1, err := strconv.Atoi(args[1])
if err != nil {
fmt.Println(0)
return
}
//fmt.Println("Arg1: ", arg1)
arg2, err := strconv.Atoi(args[3])
if err != nil {
fmt.Println(0)
return
}
//fmt.Println("Arg2: ", arg2)
if args[2] == "+" {
Add(int64(arg1), int64(arg2))
} else if args[2] == "-" {
Subs(int64(arg1), int64(arg2))
} else if args[2] == "/" {
Div(int64(arg1), int64(arg2))
} else if args[2] == "*" {
Multip(int64(arg1), int64(arg2))
} else if args[2] == "%" {
Modulo(int64(arg1), int64(arg2))
}
}
var max int64 = 9223372036854775807
var min int64 = -9223372036854775808
func Add(x, y int64) {
if x >= 0 && y < 0 {
Subs(x, -y)
return
} else if x < 0 && y >= 0 {
Subs(y, -x)
return
} else if x < 0 && y < 0 {
if x >= min-y {
fmt.Println(x + y)
return
} else {
fmt.Println(0)
return
}
}
if x <= max-y {
fmt.Println(x + y)
} else {
fmt.Println(0)
return
}
}
func Subs(x, y int64) {
if x >= 0 && y < 0 {
Add(x, -y)
return
} else if x < 0 && y >= 0 {
Add(-y, x)
return
} else if x < 0 && y < 0 {
Subs(-y, -x)
return
}
if x >= min+y {
fmt.Println(x - y)
return
} else {
fmt.Println(0)
return
}
}
func Multip(x, y int64) {
if x >= 0 && y >= 0 {
if x <= max/y {
fmt.Println(x * y)
return
} else {
fmt.Println(0)
return
}
} else if x < 0 && y < 0 {
if x > max/y {
fmt.Println(x * y)
return
} else {
fmt.Println(0)
return
}
} else {
if x >= min/y {
fmt.Println(x * y)
return
} else {
fmt.Println(0)
return
}
}
}
func Div(x, y int64) {
if y == 0 {
fmt.Println("No division by 0")
return
}
if x == min && y == -1 {
fmt.Println(0)
return
}
fmt.Println(x / y)
return
}
func Modulo(x, y int64) {
if y == 0 {
fmt.Println("No modulo by 0")
return
}
if y == min && x == -1 {
fmt.Println(0)
return
}
fmt.Println(x % y)
return
}
//9223372036854775807
// func main() {
// if len(os.Args) == 4 {
// var result int
// firstArg, err := strconv.Atoi(os.Args[1])
// if err != nil {
// fmt.Println(0)
// return
// }
// operator := os.Args[2]
// secondArg, err1 := strconv.Atoi(os.Args[3])
// if err1 != nil {
// fmt.Println(0)
// return
// }
// if secondArg == 0 && operator == "/" {
// fmt.Println("No division by 0")
// return
// } else if secondArg == 0 && operator == "%" {
// fmt.Println("No modulo by 0")
// return
// } else if operator == "+" {
// result = firstArg + secondArg
// if !((result > firstArg) == (secondArg > 0)) {
// fmt.Println(0)
// return
// }
// } else if operator == "-" {
// result = firstArg - secondArg
// if !((result < firstArg) == (secondArg > 0)) {
// fmt.Println(0)
// return
// }
// } else if operator == "/" {
// result = firstArg / secondArg
// } else if operator == "*" {
// result = firstArg * secondArg
// if firstArg != 0 && (result/firstArg != secondArg) {
// fmt.Println(0)
// return
// }
// } else if operator == "%" {
// result = firstArg % secondArg
// }
// fmt.Println(result)
// }
// }
|
package psql
import (
"TruckMonitor-Backend/dao"
"TruckMonitor-Backend/model"
"database/sql"
)
type psqlClient struct {
context PsqlContext
}
func ClientDao(context PsqlContext) dao.ClientDao {
return &psqlClient{context}
}
func (dao *psqlClient) db() *sql.DB {
return dao.context.GetDb()
}
func (dao *psqlClient) FindById(id int) (*model.Client, error) {
var data model.Client
row := dao.db().QueryRow("SELECT * FROM client WHERE id=$1", id)
if err := row.Scan(&data.Id, &data.Name, &data.Itn, &data.Iec, &data.Address); err != nil {
return nil, err
}
return &data, nil
}
|
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
)
//type KongResult struct {
// Total int `json:"total"`
// Next int `json:"next"`
// Data []struct {
// StripURI bool `json:"strip_uri"`
// Name string `json:"name"`
// UpstreamURL string `json:"upstream_url"`
// Uris []string `json:"uris"`
// Hosts []string `json:"hosts"`
// PreserveHost bool `json:"preserve_host"`
// } `json:"data"`
//}
type SingleService struct {
Name string `json:"name"`
Uris []string `json:"uris"`
Hosts []string `json:"hosts,omitempty"`
UpstreamURL string `json:"upstream_url"`
PreserveHost bool `json:"preserve_host"`
StripURI bool `json:"strip_uri"`
}
func main() {
env := flag.String("env", "dev", "dev,stg,pro")
flag.Parse()
var service SingleService
var url string
result := make(map[string]SingleService)
switch *env {
case "dev":
url = "http://192.168.1.12:8001/apis/"
default:
log.Fatal("env error:", *env)
}
//h5 response
h5_resp, err := http.Get(url + "h5-api-waimai")
if err != nil {
log.Println("connect to gateway server failed:", err)
}
defer h5_resp.Body.Close()
h5_body, err := ioutil.ReadAll(h5_resp.Body)
//h5_body{}
json.Unmarshal(h5_body, &service)
result["h5"] = service
log.Println(service.Uris)
log.Println(service)
//api response
api_resp, err := http.Get(url + "api-waimai")
if err != nil {
log.Println("connect to gateway server failed:", err)
}
defer api_resp.Body.Close()
api_body, err := ioutil.ReadAll(api_resp.Body)
json.Unmarshal(api_body, &service)
log.Println(service.Uris)
log.Println(service)
result["api"] = service
api_res, err := json.MarshalIndent(result, "", " ")
if err != nil {
log.Println("api json decode error:", err)
}
fmt.Println(string(api_res))
}
|
// Package contextutil contains functions for working with contexts.
package contextutil
import (
"context"
"time"
)
type mergedCtx struct {
ctx1, ctx2 context.Context
doneCtx context.Context
doneCancel context.CancelFunc
}
// Merge merges two contexts into a single context.
func Merge(ctx1, ctx2 context.Context) (context.Context, context.CancelFunc) {
mc := &mergedCtx{
ctx1: ctx1,
ctx2: ctx2,
}
mc.doneCtx, mc.doneCancel = context.WithCancel(context.Background())
go func() {
select {
case <-ctx1.Done():
case <-ctx2.Done():
case <-mc.doneCtx.Done():
}
mc.doneCancel()
}()
return mc, mc.doneCancel
}
func (mc *mergedCtx) Deadline() (deadline time.Time, ok bool) {
if deadline, ok = mc.ctx1.Deadline(); ok {
return deadline, ok
}
if deadline, ok = mc.ctx2.Deadline(); ok {
return deadline, ok
}
return mc.doneCtx.Deadline()
}
func (mc *mergedCtx) Done() <-chan struct{} {
return mc.doneCtx.Done()
}
func (mc *mergedCtx) Err() error {
if err := mc.ctx1.Err(); err != nil {
return mc.ctx1.Err()
}
if err := mc.ctx2.Err(); err != nil {
return mc.ctx2.Err()
}
return mc.doneCtx.Err()
}
func (mc *mergedCtx) Value(key interface{}) interface{} {
if value := mc.ctx1.Value(key); value != nil {
return value
}
if value := mc.ctx2.Value(key); value != nil {
return value
}
return mc.doneCtx.Value(key)
}
|
package mc_pb
import (
"errors"
"io"
msgio "gx/ipfs/QmcxL9MDzSU5Mj1GcWZD8CXkAFuJXjdbjotZ93o371bKSf/go-msgio"
proto "gx/ipfs/QmdxUuburamoF6zF9qjeQC4WYcWGbWuRmdLacMEsW8ioD8/gogo-protobuf/proto"
mc "gx/ipfs/QmYMiyZRYDmhMr2phMc4FGrYbsyzvR751BgeobnWroiq2z/go-multicodec"
)
var Header []byte
var HeaderMsgio []byte
var ErrNotProtobuf = errors.New("not a protobuf")
func init() {
Header = mc.Header([]byte("/protobuf"))
HeaderMsgio = mc.Header([]byte("/protobuf/msgio"))
}
type codec struct {
mc bool
msgio bool
}
func Codec(m proto.Message) mc.Codec {
return &codec{mc: false, msgio: true} // cannot do without atm.
}
func Multicodec(m proto.Message) mc.Multicodec {
return &codec{mc: true, msgio: true} // cannot do without atm.
}
func (c *codec) Encoder(w io.Writer) mc.Encoder {
return &encoder{
w: w,
buf: proto.NewBuffer(nil),
c: c,
}
}
func (c *codec) Decoder(r io.Reader) mc.Decoder {
return &decoder{
r: r,
c: c,
}
}
func (c *codec) Header() []byte {
if c.msgio {
return HeaderMsgio
}
return Header
}
type encoder struct {
w io.Writer
buf *proto.Buffer
c *codec
}
type decoder struct {
r io.Reader
c *codec
}
func (c *encoder) Encode(v interface{}) error {
w := c.w
if c.c.mc {
// if multicodec, write the header first
if _, err := c.w.Write(c.c.Header()); err != nil {
return err
}
}
if c.c.msgio {
w = msgio.NewWriter(w)
}
pbv, ok := v.(proto.Message)
if !ok {
return ErrNotProtobuf
}
defer c.buf.Reset()
if err := c.buf.Marshal(pbv); err != nil {
return err
}
_, err := w.Write(c.buf.Bytes())
return err
}
func (c *decoder) Decode(v interface{}) error {
pbv, ok := v.(proto.Message)
if !ok {
return ErrNotProtobuf
}
if c.c.mc {
// if multicodec, consume the header first
if err := mc.ConsumeHeader(c.r, c.c.Header()); err != nil {
return err
}
}
if c.c.msgio {
msg, err := msgio.NewReader(c.r).ReadMsg()
if err != nil {
return err
}
return proto.Unmarshal(msg, pbv)
}
return errors.New("protobuf without msgio not supported yet")
}
|
package keyboard
import tb "gopkg.in/tucnak/telebot.v2"
var (
EthButton = tb.ReplyButton{Text: "ETH"}
EtcButton = tb.ReplyButton{Text: "ETC"}
BtcButton = tb.ReplyButton{Text: "BTC"}
BchButton = tb.ReplyButton{Text: "BCH"}
LtcButton = tb.ReplyButton{Text: "LTC"}
SubscriptionStatus = tb.ReplyButton{Text: "Subscription status"}
MainMenu = [][]tb.ReplyButton{
[]tb.ReplyButton{SubscriptionStatus},
[]tb.ReplyButton{EthButton, EtcButton, BtcButton},
[]tb.ReplyButton{BchButton, LtcButton},
}
)
|
package user
import (
//For swagger
_ "go-mysql/docs"
"fmt"
"go-mysql/config"
"go-mysql/connection"
"go-mysql/customlogger"
"strconv"
)
//Order variables of struct must same with in table users and call body in postman
/*
== samples in post ==
{
"name": "Ferdian",
"age":29,
"location":"Indonesia"
}
*/
type User struct {
ID int64 `json:"id,omitempty"`
Name string `json:"name"`
Age int8 `json:"age,omitempty"`
Location string `json:"location"`
}
type ResponseUser struct {
Message string `json:"message"`
Data []User `json:"data"`
}
func InsertUser(usr User) ResponseUser {
logger :=customlogger.GetInstance()
logger.Println("Starting proccess insert user ...")
//dbgoblog := config.GetDbByPath("goblog").GetDb()
//dbgoblog.SetMaxIdleConns(0)
//dbgoblog.SetConnMaxLifetime(300 * time.Second)
var userModel []User
dbgoblog := connection.GetGoblogConn()
sqlStat, err := dbgoblog.Prepare("INSERT INTO users (name, age, location) VALUES (?, ?, ?)")
defer sqlStat.Close()
//Exec executes a prepared statement with the given arguments and returns a Result summarizing the effect of the statement.
res, er := sqlStat.Exec(usr.Name, usr.Age, usr.Location)
if err != nil || config.FancyHandleError(er) {
logger.Printf("Unable to execute the query. %v, %v", er, err)
response := ResponseUser{
Message: fmt.Sprintf("Unable to execute the query. %v, %v", er, err),
Data: nil,
}
sqlStat.Close()
return response
}
//Get id from data was inserted
var s int64
s, _ = res.LastInsertId()
str := strconv.FormatInt(s, 10)
usr.ID = s
response := ResponseUser{
Message: fmt.Sprintf("Success inserted a single record with id : %v", str),
Data: append(userModel, usr),
}
logger.Println(fmt.Sprintf("Success inserted a single record with id : %v", str))
return response
}
func GetUser(id int64) ResponseUser {
logger := customlogger.GetInstance()
logger.Println(fmt.Sprintf("Started get data user by id : %v", id))
dbgoblog := connection.GetGoblogConn()
var userModel User
var userData []User
sqlStat := `SELECT * FROM users where userid = ?`
//QueryRow executes a query that is expected to return at most one row
result := dbgoblog.QueryRow(sqlStat, id)
//Scan copies the columns from the matched row into the values pointed at by dest
err := result.Scan(&userModel.ID, &userModel.Name, &userModel.Age, &userModel.Location)
if config.FancyHandleError(err) {
logger.Println("Scan query select result : Error " + err.Error())
response := ResponseUser{
Message: "Scan query select result : Error " + err.Error(),
Data: nil,
}
return response
}
response := ResponseUser{
Message: "Success",
Data: append(userData, userModel),
}
return response
}
func GetAllUser () ResponseUser {
logger := customlogger.GetInstance()
dbgoblog := connection.GetGoblogConn()
var userModel []User
sqlStat := `SELECT * FROM users`
//Query executes a query that returns rows, typically a SELECT
rows, err := dbgoblog.Query(sqlStat)
defer rows.Close()
if config.FancyHandleError(err) {
logger.Println(fmt.Sprintf("Unable to execute the query. %v", err))
rows.Close()
response := ResponseUser{
Message: err.Error(),
Data: nil,
}
return response
}
for rows.Next() {
var userData User
er := rows.Scan(&userData.ID, &userData.Name, &userData.Age, &userData.Location)
if er != nil {
logger.Println(fmt.Sprintf(`Unable to scan the row %v`, er))
} else {
userModel = append(userModel, userData)
}
}
response := ResponseUser{
Message: "Success",
Data: userModel,
}
return response
}
func UpdateUser (id int64, usr User) ResponseUser {
logger := customlogger.GetInstance()
logger.Println("Start update user ...")
dbgoblog := connection.GetGoblogConn()
var mess string
var UserData []User
sqlStat := fmt.Sprintf(`UPDATE users SET name = '%v', age = '%v', location = '%v' WHERE userid = '%v'`, usr.Name, usr.Age, usr.Location, id)
conn, _ := dbgoblog.Begin()
res, err := conn.Prepare(sqlStat)
if config.FancyHandleError(err) {
logger.Println("Failed update user, " + err.Error())
logger.Println(sqlStat)
conn.Rollback()
response := ResponseUser{
Message: "Failed update user, " + err.Error(),
Data: nil,
}
return response
}
result, er := res.Exec()
//check how many rows affected
rowsAffected, f := result.RowsAffected()
if f != nil {
logger.Printf("Error while checking the affected rows in update user with id : %v, error : %v", id, f)
} else {
logger.Printf("Total rows/records affected in update user with id : %v is : %v", id, rowsAffected)
}
defer res.Close()
if config.FancyHandleError(er) {
logger.Println("Failed update user, " + er.Error())
conn.Rollback()
response := ResponseUser{
Message: "Failed update user, " + er.Error(),
Data: nil,
}
return response
}
usr.ID = id
conn.Commit()
if rowsAffected > 0 {
mess = fmt.Sprintf("Success, %v data was updated by userid : %v", rowsAffected, id)
} else {
mess = fmt.Sprintf("No data was updated by userid : %v", id)
}
response := ResponseUser{
Message: mess,
Data: UserData,
}
return response
}
func DeleteUser(id int64) ResponseUser {
logger := customlogger.GetInstance()
logger.Printf("Starting delete user with id : %v", id)
var mess string
var userData []User
dbgoblog := connection.GetGoblogConn()
sqlStat := `DELETE FROM users WHERE userid = ?`
res, err := dbgoblog.Exec(sqlStat, id)
if config.FancyHandleError(err) {
logger.Printf("Failed in delete user with id : %v, error : %v", id, err)
response := ResponseUser{
Message: fmt.Sprintf("Failed in delete user with id : %v, error : %v", id, err),
Data: nil,
}
return response
}
rowsAffected, f := res.RowsAffected()
if config.FancyHandleError(f) {
logger.Printf("Error while checking the affected rows in delete with id : %v, error : %v", id, f)
mess = fmt.Sprintf("Error while checking the affected rows in delete with id : %v, error : %v", id, f)
} else if rowsAffected == 0 {
logger.Printf("No data user was deleted by id : %v", id)
mess = fmt.Sprintf("No data user was deleted by id : %v", id)
} else {
logger.Printf("Total rows/records affected in delete user with id : %v is : %v", id, rowsAffected)
mess = fmt.Sprintf("Total rows/records affected in delete user with id : %v is : %v", id, rowsAffected)
}
response := ResponseUser{
Message: mess,
Data: userData,
}
return response
} |
package tumblr
type ActivityEnvelope struct {
Id string `json:"id"`
Timestamp int64 `json:"timestamp"`
Version string `json:"version"`
ActivityPrivacy string `json:"activity_privacy"`
ActivityType string `json:"activity_type"`
Activity Activity `json:"activity"`
}
|
/*
Heading into the final day of regular season games for the 2023 NBA season, the fifth to ninth seeds in the Western Conference were still very undecided. Four games would determine the seeding:
New Orleans (N) at Minnesota (M)
Utah at LA Lakers (L)
Golden State (G) at Portland
LA Clippers (C) at Phoenix
Let the Boolean variables M L G C denote the event of the respective team winning. Then the seeding depends on these variables as follows (taken from this Twitter post):
M L G C | 5 6 7 8 9
0 0 0 0 | N G C L M
0 0 0 1 | C N G L M
0 0 1 0 | G N C L M
0 0 1 1 | C G N L M
0 1 0 0 | N C L G M
0 1 0 1 | C L N G M
0 1 1 0 | G N C L M
0 1 1 1 | C G L N M
1 0 0 0 | C G M L N
1 0 0 1 | C G M L N
1 0 1 0 | G C M L N
1 0 1 1 | C G M L N
1 1 0 0 | C L G M N
1 1 0 1 | C L G M N
1 1 1 0 | G C L M N
1 1 1 1 | C G L M N
Task
Given the bits M L G C, output the corresponding permutation of C G L M N, with the fifth seed first. For example, the input M L G C = 1 0 1 0 should give G C M L N. You may use any five distinct symbols for the teams and may format the permutation in any reasonable manner.
Instead of taking M you may take its inverse N, with results altered accordingly (so the input N L G C = 1 0 1 0 gives the same result as M L G C = 0 0 1 0, i.e. G N C L M). You may also combine the Boolean inputs into a single four-bit integer, but in any case you must clearly indicate which bit or bit position corresponds to which game.
This is code-golf; fewest bytes wins.
*/
package main
import "fmt"
func main() {
for i := 0; i < 16; i++ {
fmt.Println(seedings(i))
}
}
func seedings(n int) string {
tab := []string{
"NGCLM",
"CNGLM",
"GNCLM",
"CGNLM",
"NCLGM",
"CLNGM",
"GNCLM",
"CGLNM",
"CGMLN",
"CGMLN",
"GCMLN",
"CGMLN",
"CLGMN",
"CLGMN",
"GCLMN",
"CGLMN",
}
if n < 0 || n >= len(tab) {
return ""
}
return tab[n]
}
|
package utils
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
)
func StringToInt64(e string) (int64, error) {
return strconv.ParseInt(e, 10, 64)
}
func IntToString(e int) string {
return strconv.Itoa(e)
}
func Float64ToString(e float64) string {
return strconv.FormatFloat(e, 'E', -1, 64)
}
func Int64ToString(e int64) string {
return strconv.FormatInt(e, 10)
}
//获取URL中批量id并解析
func IdsStrToIdsInt64Group(key string, c *gin.Context) []int64 {
IDS := make([]int64, 0)
ids := strings.Split(c.Param(key), ",")
for i := 0; i < len(ids); i++ {
ID, _ := strconv.ParseInt(ids[i], 10, 64)
IDS = append(IDS, ID)
}
return IDS
}
func GetCurrntTime() string {
return time.Now().Format("2006/01/02 15:04:05")
}
func GetLocation(ip string) string {
if ip == "127.0.0.1" || ip == "localhost" {
return "内部IP"
}
resp, err := http.Get("https://restapi.amap.com/v3/ip?ip=" + ip + "&key=3fabc36c20379fbb9300c79b19d5d05e")
if err != nil {
panic(err)
}
defer resp.Body.Close()
s, err := ioutil.ReadAll(resp.Body)
fmt.Printf(string(s))
m := make(map[string]string)
err = json.Unmarshal(s, &m)
if err != nil {
fmt.Println("Umarshal failed:", err)
}
if m["province"] == "" {
return "未知位置"
}
return m["province"] + "-" + m["city"]
}
func StructToJsonStr(e interface{}) (string, error) {
if b, err := json.Marshal(e); err == nil {
return string(b), err
} else {
return "", err
}
}
func GetBodyString(c *gin.Context) (string, error) {
body, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
fmt.Printf("read body err, %v\n", err)
return string(body), nil
} else {
return "", err
}
}
func JsonStrToMap(e string) (map[string]interface{}, error) {
var dict map[string]interface{}
if err := json.Unmarshal([]byte(e), &dict); err == nil {
return dict, err
} else {
return nil, err
}
}
|
package syslog
import (
"bytes"
"errors"
"fmt"
"log"
"log/syslog"
"net"
"os"
"reflect"
"text/template"
"time"
"strings"
"github.com/gliderlabs/logspout/router"
)
var hostname string
func GetIndex(slice []string, value string) int {
for p, v := range slice {
if (strings.Contains(v, value)) {
return p
}
}
return -1
}
func ConvertAppName(envvar []string) string {
index := GetIndex(envvar, "MARATHON_APP_ID")
if index != -1 {
MarathonApp := strings.Split(envvar[index], "=")
return (MarathonApp[1])
}
return "noMarathonApp"
}
func init() {
hostname, _ = os.Hostname()
router.AdapterFactories.Register(NewSyslogAdapter, "syslog")
}
func getopt(name, dfault string) string {
value := os.Getenv(name)
if value == "" {
value = dfault
}
return value
}
func NewSyslogAdapter(route *router.Route) (router.LogAdapter, error) {
transport, found := router.AdapterTransports.Lookup(route.AdapterTransport("udp"))
if !found {
return nil, errors.New("bad transport: " + route.Adapter)
}
conn, err := transport.Dial(route.Address, route.Options)
if err != nil {
return nil, err
}
format := getopt("SYSLOG_FORMAT", "rfc5424")
priority := getopt("SYSLOG_PRIORITY", "{{.Priority}}")
hostname := getopt("SYSLOG_HOSTNAME", "{{.Hostname}}")
envs := getopt("SYSLOG_ENVS", "{{.ContainerConfigEnv}}")
elktype := getopt("SYSLOG_ELKTYPE", "mesoscontainer")
pid := getopt("SYSLOG_PID", "{{.Container.State.Pid}}")
tag := getopt("SYSLOG_TAG", "{{.ContainerName}}"+route.Options["append_tag"])
structuredData := getopt("SYSLOG_STRUCTURED_DATA", "")
if route.Options["structured_data"] != "" {
structuredData = route.Options["structured_data"]
}
data := getopt("SYSLOG_DATA", "{{.Data}}")
var tmplStr string
switch format {
case "rfc5424":
tmplStr = fmt.Sprintf("<%s>1 {{.Timestamp}} %s %s %s - [%s] %s %s %s\n",
priority, hostname, elktype, envs, tag, pid, structuredData, data)
case "rfc3164":
tmplStr = fmt.Sprintf("<%s>{{.Timestamp}} %s %s[%s]: %s\n",
priority, hostname, elktype, pid, data)
default:
return nil, errors.New("unsupported syslog format: " + format)
}
tmpl, err := template.New("syslog").Parse(tmplStr)
if err != nil {
return nil, err
}
return &SyslogAdapter{
route: route,
conn: conn,
tmpl: tmpl,
}, nil
}
type SyslogAdapter struct {
conn net.Conn
route *router.Route
tmpl *template.Template
}
func (a *SyslogAdapter) Stream(logstream chan *router.Message) {
for message := range logstream {
m := &SyslogMessage{message}
buf, err := m.Render(a.tmpl)
if err != nil {
log.Println("syslog:", err)
return
}
_, err = a.conn.Write(buf)
if err != nil {
log.Println("syslog:", err)
if reflect.TypeOf(a.conn).String() != "*net.UDPConn" {
return
}
}
}
}
type SyslogMessage struct {
*router.Message
}
func (m *SyslogMessage) Render(tmpl *template.Template) ([]byte, error) {
buf := new(bytes.Buffer)
err := tmpl.Execute(buf, m)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (m *SyslogMessage) Priority() syslog.Priority {
switch m.Message.Source {
case "stdout":
return syslog.LOG_USER | syslog.LOG_INFO
case "stderr":
return syslog.LOG_USER | syslog.LOG_ERR
default:
return syslog.LOG_DAEMON | syslog.LOG_INFO
}
}
func (m *SyslogMessage) Hostname() string {
return hostname
}
func (m *SyslogMessage) Timestamp() string {
return m.Message.Time.Format(time.RFC3339)
}
func (m *SyslogMessage) ContainerConfigEnv() string {
return ConvertAppName(m.Message.Container.Config.Env)
}
func (m *SyslogMessage) ContainerName() string {
return m.Message.Container.Name[1:]
}
|
package cache
import (
"context"
"strconv"
"sync"
"testing"
"time"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/Juniper/contrail/pkg/models"
"github.com/Juniper/contrail/pkg/services"
)
const numEvent = 4
const timeOut = 10 * time.Second
func addWatcher(t *testing.T, wg *sync.WaitGroup, cache *DB) {
ctx, cancel := context.WithTimeout(context.Background(), timeOut)
watcher, _ := cache.AddWatcher(ctx, 0)
go func() {
wg.Add(1)
defer wg.Done()
defer cancel()
for i := 0; i < numEvent; i++ {
select {
case <-ctx.Done():
log.Debugf("[watcher %d] time out on test", watcher.id)
assert.Fail(t, "timeout")
case e := <-watcher.ch:
log.Debugf("[watcher %d] got event version %d", watcher.id, e.Version)
assert.Equal(t, uint64(i), e.Version)
}
}
}()
}
func notifyEvent(cache *DB, version uint64) {
event := &services.Event{
Version: version,
Request: &services.Event_CreateVirtualNetworkRequest{
CreateVirtualNetworkRequest: &services.CreateVirtualNetworkRequest{
VirtualNetwork: &models.VirtualNetwork{
UUID: "vn" + strconv.FormatUint(version, 10),
},
},
},
}
cache.Process(context.Background(), event) // nolint: errcheck
}
// nolint: unused
func notifyDelete(cache *DB, version uint64) {
event := &services.Event{
Version: version,
Request: &services.Event_DeleteVirtualNetworkRequest{
DeleteVirtualNetworkRequest: &services.DeleteVirtualNetworkRequest{
ID: "vn" + strconv.FormatUint(version, 10),
},
},
}
cache.Process(context.Background(), event) // nolint: errcheck
}
func TestCache(t *testing.T) {
log.SetLevel(log.DebugLevel)
cache := NewDB(1)
wg := &sync.WaitGroup{}
addWatcher(t, wg, cache)
addWatcher(t, wg, cache)
notifyEvent(cache, 0)
notifyEvent(cache, 1)
addWatcher(t, wg, cache)
addWatcher(t, wg, cache)
// test cancelation of channel.
// expect no panic or blocking.
ctx2, cancel := context.WithCancel(context.Background())
cache.AddWatcher(ctx2, 0) // nolint: errcheck
cancel()
//timeout watcher
//Don't actually receiving events.
ctx3 := context.Background()
cache.AddWatcher(ctx3, 0) // nolint: errcheck
notifyEvent(cache, 2)
notifyEvent(cache, 3)
addWatcher(t, wg, cache)
wg.Wait()
// notifyDelete(t, cache, 0)
// notifyDelete(t, cache, 1)
// notifyDelete(t, cache, 2)
// notifyDelete(t, cache, 3)
// _, ok := cache.idMap["vn0"]
// assert.Equal(t, false, ok, "compaction failed")
}
func TestDependencyResolution(t *testing.T) {
log.SetLevel(log.DebugLevel)
cache := NewDB(6)
vnTestUUID := "vn_blue"
vn := makeTestVirtualNetwork(&baseResourceParams{uuid: vnTestUUID})
event1, err := cache.processTestEvent(&services.Event{
Version: 0,
Request: &services.Event_CreateVirtualNetworkRequest{
CreateVirtualNetworkRequest: &services.CreateVirtualNetworkRequest{
VirtualNetwork: vn,
},
},
})
assert.NoError(t, err)
assert.Equal(t, vnTestUUID, vn.UUID)
e := cache.Get(vnTestUUID)
assert.Equal(t, event1, e)
assert.Equal(t, "", e.GetResource().GetParentUUID())
vn.ParentUUID = "domain"
event2, err := cache.processTestEvent(&services.Event{
Version: 1,
Request: &services.Event_UpdateVirtualNetworkRequest{
UpdateVirtualNetworkRequest: &services.UpdateVirtualNetworkRequest{
VirtualNetwork: vn,
},
},
})
assert.NoError(t, err)
assert.Equal(t, e.GetResource().GetParentUUID(), "domain")
e = cache.Get(vnTestUUID)
assert.Equal(t, event2, e)
assert.NotEqual(t, event1, event2)
riUUID1 := "ri_uuid1"
ri := makeTestRoutingInstance(&riParams{
baseResourceParams: baseResourceParams{
uuid: riUUID1, parentUUID: vn.GetUUID(),
},
})
_, err = cache.processTestEvent(&services.Event{
Version: 2,
Request: &services.Event_CreateRoutingInstanceRequest{
CreateRoutingInstanceRequest: &services.CreateRoutingInstanceRequest{
RoutingInstance: ri,
},
},
})
assert.NoError(t, err)
e = cache.Get(vnTestUUID)
vn = e.GetUpdateVirtualNetworkRequest().GetVirtualNetwork()
assert.Len(t, vn.RoutingInstances, 1)
assert.Equal(t, riUUID1, vn.RoutingInstances[0].UUID)
riUUID2 := "ri_uuid2"
ri = makeTestRoutingInstance(&riParams{
baseResourceParams: baseResourceParams{
uuid: riUUID2, parentUUID: vn.GetUUID()}, riRefs: []*models.RoutingInstanceRoutingInstanceRef{
{UUID: riUUID1},
},
})
_, err = cache.processTestEvent(&services.Event{
Version: 3,
Request: &services.Event_CreateRoutingInstanceRequest{
CreateRoutingInstanceRequest: &services.CreateRoutingInstanceRequest{
RoutingInstance: ri,
},
},
})
assert.NoError(t, err)
e = cache.Get(vnTestUUID)
vn = e.GetUpdateVirtualNetworkRequest().GetVirtualNetwork()
assert.Len(t, vn.RoutingInstances, 2)
assert.Equal(t, riUUID2, vn.RoutingInstances[1].UUID)
e = cache.Get(riUUID1)
ri = e.GetCreateRoutingInstanceRequest().GetRoutingInstance()
assert.Len(t, ri.RoutingInstanceBackRefs, 1)
assert.Equal(t, riUUID2, ri.RoutingInstanceBackRefs[0].UUID)
event4, err := cache.processTestEvent(&services.Event{
Version: 4,
Request: &services.Event_DeleteRoutingInstanceRequest{
DeleteRoutingInstanceRequest: &services.DeleteRoutingInstanceRequest{
ID: riUUID2,
},
},
})
assert.NoError(t, err)
e = cache.Get(riUUID2)
assert.Equal(t, event4, e)
e = cache.Get(vnTestUUID)
vn = e.GetUpdateVirtualNetworkRequest().GetVirtualNetwork()
assert.Len(t, vn.RoutingInstances, 1)
assert.Equal(t, riUUID1, vn.RoutingInstances[0].UUID)
e = cache.Get(riUUID1)
ri = e.GetCreateRoutingInstanceRequest().GetRoutingInstance()
assert.Len(t, ri.RoutingInstanceBackRefs, 0)
event5, err := cache.processTestEvent(&services.Event{
Version: 5,
Request: &services.Event_DeleteVirtualNetworkRequest{
DeleteVirtualNetworkRequest: &services.DeleteVirtualNetworkRequest{
ID: vnTestUUID,
},
},
})
assert.NoError(t, err)
e = cache.Get(vnTestUUID)
r := e.GetResource()
assert.Equal(t, event5, e)
assert.Equal(t, services.OperationDelete, e.Operation())
assert.NotEqual(t, vn.ParentUUID, r.GetParentUUID())
}
type baseResourceParams struct {
uuid string
parentUUID string
}
func makeTestVirtualNetwork(vnParams *baseResourceParams) *models.VirtualNetwork {
vn := models.MakeVirtualNetwork()
vn.UUID = vnParams.uuid
vn.ParentUUID = vnParams.parentUUID
return vn
}
type riParams struct {
baseResourceParams
riRefs []*models.RoutingInstanceRoutingInstanceRef
}
func makeTestRoutingInstance(rip *riParams) *models.RoutingInstance {
ri := models.MakeRoutingInstance()
ri.UUID = rip.uuid
ri.ParentUUID = rip.parentUUID
ri.RoutingInstanceRefs = rip.riRefs
return ri
}
func (cache *DB) processTestEvent(event *services.Event) (*services.Event, error) {
return cache.Process(context.Background(), event)
}
|
package errorcode
// APIError API錯誤格式
type APIError struct {
Code string `json:"error_code"`
Text string `json:"error_text"`
}
// ErrorCode 錯誤代碼
func (e APIError) ErrorCode() string {
return e.Code
}
// ErrorText 錯誤訊息
func (e APIError) ErrorText() string {
return e.Text
}
// Error API錯誤訊息
func (e APIError) Error() string {
return e.Text + " (" + e.Code + ")"
}
|
package distance
const (
CHEBYSHEV = "Chebyshev"
EUCLIDEAN = "Euclidean"
MANHATTAN = "Manhattan"
)
type req struct {
a, b []float64
}
func Get(a, b []float64, chs string) float64 {
r := req{
a: a,
b: b,
}
ln_a, ln_b := len(a), len(b)
r.Check(ln_a, ln_b)
switch chs {
case CHEBYSHEV:
return r.Chebyshev()
case EUCLIDEAN:
return r.Euclidean()
case MANHATTAN:
return r.Manhattan()
default:
panic("unknow distance")
}
}
func (r *req) Check(a, b int) {
if a != b {
panic("len_a != len_b in distance")
}
}
|
package twofer
//package main
import (
"fmt"
)
func ShareWith(name string) string {
if name=="" {
return "One for you, one for me."
}
var res string
res = "One for "+name+", one for me."
return res
}
func twofer() {
fmt.Println(ShareWith("Zaphod"))
}
|
package et
import (
"encoding/json"
"io/ioutil"
"sync"
)
type parsers struct {
sync.Mutex
items map[string]*Parser
}
func (p *parsers) get(fname string, refresh bool) (*Parser, error) {
p.Lock()
defer p.Unlock()
if !refresh && p.items[fname] != nil {
return p.items[fname], nil
}
content, err := ioutil.ReadFile(fname)
if err != nil {
return nil, err
}
parser := new(Parser)
if err := json.Unmarshal(content, parser); err != nil {
return nil, err
}
p.items[fname] = parser
return parser, nil
}
var pool = &parsers{items: make(map[string]*Parser)}
func Parse(fname, url, page string) ([]map[string]interface{}, error) {
p, err := pool.get(fname, false)
if err != nil {
return nil, err
}
_, ret, err := p.Parse(page, url)
return ret, err
}
func ParseExt(fname, url, page string) (string, error) {
ret, err := Parse(fname, url, page)
if err != nil {
return "", err
}
b, err := json.Marshal(ret)
if err != nil {
return "", err
}
return string(b), nil
}
|
package main
import (
"fmt"
"log"
"os"
"github.wtf/Brotchu/maze"
)
func main() {
maze, err := maze.LoadMaze(os.Args[1])
if err != nil {
log.Fatal(err)
}
fmt.Println(maze)
}
|
package k8sml
type Infrastructure interface {
GetID() string
GetVariableValue(variable string) interface{}
ExportModule() error
AddRuntimeVariable(key, value string)
GetRuntimeVariables() map[string]string
} |
// Copyright 2023 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package alpha
import (
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"time"
"google.golang.org/api/googleapi"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl"
)
type Feature struct {
Name *string `json:"name"`
Labels map[string]string `json:"labels"`
ResourceState *FeatureResourceState `json:"resourceState"`
Spec *FeatureSpec `json:"spec"`
State *FeatureState `json:"state"`
CreateTime *string `json:"createTime"`
UpdateTime *string `json:"updateTime"`
DeleteTime *string `json:"deleteTime"`
Project *string `json:"project"`
Location *string `json:"location"`
}
func (r *Feature) String() string {
return dcl.SprintResource(r)
}
// The enum FeatureResourceStateStateEnum.
type FeatureResourceStateStateEnum string
// FeatureResourceStateStateEnumRef returns a *FeatureResourceStateStateEnum with the value of string s
// If the empty string is provided, nil is returned.
func FeatureResourceStateStateEnumRef(s string) *FeatureResourceStateStateEnum {
v := FeatureResourceStateStateEnum(s)
return &v
}
func (v FeatureResourceStateStateEnum) Validate() error {
if string(v) == "" {
// Empty enum is okay.
return nil
}
for _, s := range []string{"STATE_UNSPECIFIED", "ENABLING", "ACTIVE", "DISABLING", "UPDATING", "SERVICE_UPDATING"} {
if string(v) == s {
return nil
}
}
return &dcl.EnumInvalidError{
Enum: "FeatureResourceStateStateEnum",
Value: string(v),
Valid: []string{},
}
}
// The enum FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum.
type FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum string
// FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnumRef returns a *FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum with the value of string s
// If the empty string is provided, nil is returned.
func FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnumRef(s string) *FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum {
v := FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum(s)
return &v
}
func (v FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum) Validate() error {
if string(v) == "" {
// Empty enum is okay.
return nil
}
for _, s := range []string{"MODE_UNSPECIFIED", "COPY", "MOVE"} {
if string(v) == s {
return nil
}
}
return &dcl.EnumInvalidError{
Enum: "FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum",
Value: string(v),
Valid: []string{},
}
}
// The enum FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum.
type FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum string
// FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnumRef returns a *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum with the value of string s
// If the empty string is provided, nil is returned.
func FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnumRef(s string) *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum {
v := FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum(s)
return &v
}
func (v FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum) Validate() error {
if string(v) == "" {
// Empty enum is okay.
return nil
}
for _, s := range []string{"MODE_UNSPECIFIED", "COPY", "MOVE"} {
if string(v) == s {
return nil
}
}
return &dcl.EnumInvalidError{
Enum: "FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum",
Value: string(v),
Valid: []string{},
}
}
// The enum FeatureStateStateCodeEnum.
type FeatureStateStateCodeEnum string
// FeatureStateStateCodeEnumRef returns a *FeatureStateStateCodeEnum with the value of string s
// If the empty string is provided, nil is returned.
func FeatureStateStateCodeEnumRef(s string) *FeatureStateStateCodeEnum {
v := FeatureStateStateCodeEnum(s)
return &v
}
func (v FeatureStateStateCodeEnum) Validate() error {
if string(v) == "" {
// Empty enum is okay.
return nil
}
for _, s := range []string{"CODE_UNSPECIFIED", "OK", "WARNING", "ERROR"} {
if string(v) == s {
return nil
}
}
return &dcl.EnumInvalidError{
Enum: "FeatureStateStateCodeEnum",
Value: string(v),
Valid: []string{},
}
}
// The enum FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum.
type FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum string
// FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnumRef returns a *FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum with the value of string s
// If the empty string is provided, nil is returned.
func FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnumRef(s string) *FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum {
v := FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum(s)
return &v
}
func (v FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum) Validate() error {
if string(v) == "" {
// Empty enum is okay.
return nil
}
for _, s := range []string{"LEVEL_UNSPECIFIED", "ERROR", "WARNING", "INFO"} {
if string(v) == s {
return nil
}
}
return &dcl.EnumInvalidError{
Enum: "FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum",
Value: string(v),
Valid: []string{},
}
}
type FeatureResourceState struct {
empty bool `json:"-"`
State *FeatureResourceStateStateEnum `json:"state"`
HasResources *bool `json:"hasResources"`
}
type jsonFeatureResourceState FeatureResourceState
func (r *FeatureResourceState) UnmarshalJSON(data []byte) error {
var res jsonFeatureResourceState
if err := json.Unmarshal(data, &res); err != nil {
return err
}
var m map[string]interface{}
json.Unmarshal(data, &m)
if len(m) == 0 {
*r = *EmptyFeatureResourceState
} else {
r.State = res.State
r.HasResources = res.HasResources
}
return nil
}
// This object is used to assert a desired state where this FeatureResourceState is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyFeatureResourceState *FeatureResourceState = &FeatureResourceState{empty: true}
func (r *FeatureResourceState) Empty() bool {
return r.empty
}
func (r *FeatureResourceState) String() string {
return dcl.SprintResource(r)
}
func (r *FeatureResourceState) HashCode() string {
// Placeholder for a more complex hash method that handles ordering, etc
// Hash resource body for easy comparison later
hash := sha256.New().Sum([]byte(r.String()))
return fmt.Sprintf("%x", hash)
}
type FeatureSpec struct {
empty bool `json:"-"`
Multiclusteringress *FeatureSpecMulticlusteringress `json:"multiclusteringress"`
Cloudauditlogging *FeatureSpecCloudauditlogging `json:"cloudauditlogging"`
Fleetobservability *FeatureSpecFleetobservability `json:"fleetobservability"`
}
type jsonFeatureSpec FeatureSpec
func (r *FeatureSpec) UnmarshalJSON(data []byte) error {
var res jsonFeatureSpec
if err := json.Unmarshal(data, &res); err != nil {
return err
}
var m map[string]interface{}
json.Unmarshal(data, &m)
if len(m) == 0 {
*r = *EmptyFeatureSpec
} else {
r.Multiclusteringress = res.Multiclusteringress
r.Cloudauditlogging = res.Cloudauditlogging
r.Fleetobservability = res.Fleetobservability
}
return nil
}
// This object is used to assert a desired state where this FeatureSpec is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyFeatureSpec *FeatureSpec = &FeatureSpec{empty: true}
func (r *FeatureSpec) Empty() bool {
return r.empty
}
func (r *FeatureSpec) String() string {
return dcl.SprintResource(r)
}
func (r *FeatureSpec) HashCode() string {
// Placeholder for a more complex hash method that handles ordering, etc
// Hash resource body for easy comparison later
hash := sha256.New().Sum([]byte(r.String()))
return fmt.Sprintf("%x", hash)
}
type FeatureSpecMulticlusteringress struct {
empty bool `json:"-"`
ConfigMembership *string `json:"configMembership"`
}
type jsonFeatureSpecMulticlusteringress FeatureSpecMulticlusteringress
func (r *FeatureSpecMulticlusteringress) UnmarshalJSON(data []byte) error {
var res jsonFeatureSpecMulticlusteringress
if err := json.Unmarshal(data, &res); err != nil {
return err
}
var m map[string]interface{}
json.Unmarshal(data, &m)
if len(m) == 0 {
*r = *EmptyFeatureSpecMulticlusteringress
} else {
r.ConfigMembership = res.ConfigMembership
}
return nil
}
// This object is used to assert a desired state where this FeatureSpecMulticlusteringress is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyFeatureSpecMulticlusteringress *FeatureSpecMulticlusteringress = &FeatureSpecMulticlusteringress{empty: true}
func (r *FeatureSpecMulticlusteringress) Empty() bool {
return r.empty
}
func (r *FeatureSpecMulticlusteringress) String() string {
return dcl.SprintResource(r)
}
func (r *FeatureSpecMulticlusteringress) HashCode() string {
// Placeholder for a more complex hash method that handles ordering, etc
// Hash resource body for easy comparison later
hash := sha256.New().Sum([]byte(r.String()))
return fmt.Sprintf("%x", hash)
}
type FeatureSpecCloudauditlogging struct {
empty bool `json:"-"`
AllowlistedServiceAccounts []string `json:"allowlistedServiceAccounts"`
}
type jsonFeatureSpecCloudauditlogging FeatureSpecCloudauditlogging
func (r *FeatureSpecCloudauditlogging) UnmarshalJSON(data []byte) error {
var res jsonFeatureSpecCloudauditlogging
if err := json.Unmarshal(data, &res); err != nil {
return err
}
var m map[string]interface{}
json.Unmarshal(data, &m)
if len(m) == 0 {
*r = *EmptyFeatureSpecCloudauditlogging
} else {
r.AllowlistedServiceAccounts = res.AllowlistedServiceAccounts
}
return nil
}
// This object is used to assert a desired state where this FeatureSpecCloudauditlogging is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyFeatureSpecCloudauditlogging *FeatureSpecCloudauditlogging = &FeatureSpecCloudauditlogging{empty: true}
func (r *FeatureSpecCloudauditlogging) Empty() bool {
return r.empty
}
func (r *FeatureSpecCloudauditlogging) String() string {
return dcl.SprintResource(r)
}
func (r *FeatureSpecCloudauditlogging) HashCode() string {
// Placeholder for a more complex hash method that handles ordering, etc
// Hash resource body for easy comparison later
hash := sha256.New().Sum([]byte(r.String()))
return fmt.Sprintf("%x", hash)
}
type FeatureSpecFleetobservability struct {
empty bool `json:"-"`
LoggingConfig *FeatureSpecFleetobservabilityLoggingConfig `json:"loggingConfig"`
}
type jsonFeatureSpecFleetobservability FeatureSpecFleetobservability
func (r *FeatureSpecFleetobservability) UnmarshalJSON(data []byte) error {
var res jsonFeatureSpecFleetobservability
if err := json.Unmarshal(data, &res); err != nil {
return err
}
var m map[string]interface{}
json.Unmarshal(data, &m)
if len(m) == 0 {
*r = *EmptyFeatureSpecFleetobservability
} else {
r.LoggingConfig = res.LoggingConfig
}
return nil
}
// This object is used to assert a desired state where this FeatureSpecFleetobservability is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyFeatureSpecFleetobservability *FeatureSpecFleetobservability = &FeatureSpecFleetobservability{empty: true}
func (r *FeatureSpecFleetobservability) Empty() bool {
return r.empty
}
func (r *FeatureSpecFleetobservability) String() string {
return dcl.SprintResource(r)
}
func (r *FeatureSpecFleetobservability) HashCode() string {
// Placeholder for a more complex hash method that handles ordering, etc
// Hash resource body for easy comparison later
hash := sha256.New().Sum([]byte(r.String()))
return fmt.Sprintf("%x", hash)
}
type FeatureSpecFleetobservabilityLoggingConfig struct {
empty bool `json:"-"`
DefaultConfig *FeatureSpecFleetobservabilityLoggingConfigDefaultConfig `json:"defaultConfig"`
FleetScopeLogsConfig *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig `json:"fleetScopeLogsConfig"`
}
type jsonFeatureSpecFleetobservabilityLoggingConfig FeatureSpecFleetobservabilityLoggingConfig
func (r *FeatureSpecFleetobservabilityLoggingConfig) UnmarshalJSON(data []byte) error {
var res jsonFeatureSpecFleetobservabilityLoggingConfig
if err := json.Unmarshal(data, &res); err != nil {
return err
}
var m map[string]interface{}
json.Unmarshal(data, &m)
if len(m) == 0 {
*r = *EmptyFeatureSpecFleetobservabilityLoggingConfig
} else {
r.DefaultConfig = res.DefaultConfig
r.FleetScopeLogsConfig = res.FleetScopeLogsConfig
}
return nil
}
// This object is used to assert a desired state where this FeatureSpecFleetobservabilityLoggingConfig is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyFeatureSpecFleetobservabilityLoggingConfig *FeatureSpecFleetobservabilityLoggingConfig = &FeatureSpecFleetobservabilityLoggingConfig{empty: true}
func (r *FeatureSpecFleetobservabilityLoggingConfig) Empty() bool {
return r.empty
}
func (r *FeatureSpecFleetobservabilityLoggingConfig) String() string {
return dcl.SprintResource(r)
}
func (r *FeatureSpecFleetobservabilityLoggingConfig) HashCode() string {
// Placeholder for a more complex hash method that handles ordering, etc
// Hash resource body for easy comparison later
hash := sha256.New().Sum([]byte(r.String()))
return fmt.Sprintf("%x", hash)
}
type FeatureSpecFleetobservabilityLoggingConfigDefaultConfig struct {
empty bool `json:"-"`
Mode *FeatureSpecFleetobservabilityLoggingConfigDefaultConfigModeEnum `json:"mode"`
}
type jsonFeatureSpecFleetobservabilityLoggingConfigDefaultConfig FeatureSpecFleetobservabilityLoggingConfigDefaultConfig
func (r *FeatureSpecFleetobservabilityLoggingConfigDefaultConfig) UnmarshalJSON(data []byte) error {
var res jsonFeatureSpecFleetobservabilityLoggingConfigDefaultConfig
if err := json.Unmarshal(data, &res); err != nil {
return err
}
var m map[string]interface{}
json.Unmarshal(data, &m)
if len(m) == 0 {
*r = *EmptyFeatureSpecFleetobservabilityLoggingConfigDefaultConfig
} else {
r.Mode = res.Mode
}
return nil
}
// This object is used to assert a desired state where this FeatureSpecFleetobservabilityLoggingConfigDefaultConfig is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyFeatureSpecFleetobservabilityLoggingConfigDefaultConfig *FeatureSpecFleetobservabilityLoggingConfigDefaultConfig = &FeatureSpecFleetobservabilityLoggingConfigDefaultConfig{empty: true}
func (r *FeatureSpecFleetobservabilityLoggingConfigDefaultConfig) Empty() bool {
return r.empty
}
func (r *FeatureSpecFleetobservabilityLoggingConfigDefaultConfig) String() string {
return dcl.SprintResource(r)
}
func (r *FeatureSpecFleetobservabilityLoggingConfigDefaultConfig) HashCode() string {
// Placeholder for a more complex hash method that handles ordering, etc
// Hash resource body for easy comparison later
hash := sha256.New().Sum([]byte(r.String()))
return fmt.Sprintf("%x", hash)
}
type FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig struct {
empty bool `json:"-"`
Mode *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfigModeEnum `json:"mode"`
}
type jsonFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig
func (r *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig) UnmarshalJSON(data []byte) error {
var res jsonFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig
if err := json.Unmarshal(data, &res); err != nil {
return err
}
var m map[string]interface{}
json.Unmarshal(data, &m)
if len(m) == 0 {
*r = *EmptyFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig
} else {
r.Mode = res.Mode
}
return nil
}
// This object is used to assert a desired state where this FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyFeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig = &FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig{empty: true}
func (r *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig) Empty() bool {
return r.empty
}
func (r *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig) String() string {
return dcl.SprintResource(r)
}
func (r *FeatureSpecFleetobservabilityLoggingConfigFleetScopeLogsConfig) HashCode() string {
// Placeholder for a more complex hash method that handles ordering, etc
// Hash resource body for easy comparison later
hash := sha256.New().Sum([]byte(r.String()))
return fmt.Sprintf("%x", hash)
}
type FeatureState struct {
empty bool `json:"-"`
State *FeatureStateState `json:"state"`
Servicemesh *FeatureStateServicemesh `json:"servicemesh"`
}
type jsonFeatureState FeatureState
func (r *FeatureState) UnmarshalJSON(data []byte) error {
var res jsonFeatureState
if err := json.Unmarshal(data, &res); err != nil {
return err
}
var m map[string]interface{}
json.Unmarshal(data, &m)
if len(m) == 0 {
*r = *EmptyFeatureState
} else {
r.State = res.State
r.Servicemesh = res.Servicemesh
}
return nil
}
// This object is used to assert a desired state where this FeatureState is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyFeatureState *FeatureState = &FeatureState{empty: true}
func (r *FeatureState) Empty() bool {
return r.empty
}
func (r *FeatureState) String() string {
return dcl.SprintResource(r)
}
func (r *FeatureState) HashCode() string {
// Placeholder for a more complex hash method that handles ordering, etc
// Hash resource body for easy comparison later
hash := sha256.New().Sum([]byte(r.String()))
return fmt.Sprintf("%x", hash)
}
type FeatureStateState struct {
empty bool `json:"-"`
Code *FeatureStateStateCodeEnum `json:"code"`
Description *string `json:"description"`
UpdateTime *string `json:"updateTime"`
}
type jsonFeatureStateState FeatureStateState
func (r *FeatureStateState) UnmarshalJSON(data []byte) error {
var res jsonFeatureStateState
if err := json.Unmarshal(data, &res); err != nil {
return err
}
var m map[string]interface{}
json.Unmarshal(data, &m)
if len(m) == 0 {
*r = *EmptyFeatureStateState
} else {
r.Code = res.Code
r.Description = res.Description
r.UpdateTime = res.UpdateTime
}
return nil
}
// This object is used to assert a desired state where this FeatureStateState is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyFeatureStateState *FeatureStateState = &FeatureStateState{empty: true}
func (r *FeatureStateState) Empty() bool {
return r.empty
}
func (r *FeatureStateState) String() string {
return dcl.SprintResource(r)
}
func (r *FeatureStateState) HashCode() string {
// Placeholder for a more complex hash method that handles ordering, etc
// Hash resource body for easy comparison later
hash := sha256.New().Sum([]byte(r.String()))
return fmt.Sprintf("%x", hash)
}
type FeatureStateServicemesh struct {
empty bool `json:"-"`
AnalysisMessages []FeatureStateServicemeshAnalysisMessages `json:"analysisMessages"`
}
type jsonFeatureStateServicemesh FeatureStateServicemesh
func (r *FeatureStateServicemesh) UnmarshalJSON(data []byte) error {
var res jsonFeatureStateServicemesh
if err := json.Unmarshal(data, &res); err != nil {
return err
}
var m map[string]interface{}
json.Unmarshal(data, &m)
if len(m) == 0 {
*r = *EmptyFeatureStateServicemesh
} else {
r.AnalysisMessages = res.AnalysisMessages
}
return nil
}
// This object is used to assert a desired state where this FeatureStateServicemesh is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyFeatureStateServicemesh *FeatureStateServicemesh = &FeatureStateServicemesh{empty: true}
func (r *FeatureStateServicemesh) Empty() bool {
return r.empty
}
func (r *FeatureStateServicemesh) String() string {
return dcl.SprintResource(r)
}
func (r *FeatureStateServicemesh) HashCode() string {
// Placeholder for a more complex hash method that handles ordering, etc
// Hash resource body for easy comparison later
hash := sha256.New().Sum([]byte(r.String()))
return fmt.Sprintf("%x", hash)
}
type FeatureStateServicemeshAnalysisMessages struct {
empty bool `json:"-"`
MessageBase *FeatureStateServicemeshAnalysisMessagesMessageBase `json:"messageBase"`
Description *string `json:"description"`
ResourcePaths []string `json:"resourcePaths"`
Args map[string]string `json:"args"`
}
type jsonFeatureStateServicemeshAnalysisMessages FeatureStateServicemeshAnalysisMessages
func (r *FeatureStateServicemeshAnalysisMessages) UnmarshalJSON(data []byte) error {
var res jsonFeatureStateServicemeshAnalysisMessages
if err := json.Unmarshal(data, &res); err != nil {
return err
}
var m map[string]interface{}
json.Unmarshal(data, &m)
if len(m) == 0 {
*r = *EmptyFeatureStateServicemeshAnalysisMessages
} else {
r.MessageBase = res.MessageBase
r.Description = res.Description
r.ResourcePaths = res.ResourcePaths
r.Args = res.Args
}
return nil
}
// This object is used to assert a desired state where this FeatureStateServicemeshAnalysisMessages is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyFeatureStateServicemeshAnalysisMessages *FeatureStateServicemeshAnalysisMessages = &FeatureStateServicemeshAnalysisMessages{empty: true}
func (r *FeatureStateServicemeshAnalysisMessages) Empty() bool {
return r.empty
}
func (r *FeatureStateServicemeshAnalysisMessages) String() string {
return dcl.SprintResource(r)
}
func (r *FeatureStateServicemeshAnalysisMessages) HashCode() string {
// Placeholder for a more complex hash method that handles ordering, etc
// Hash resource body for easy comparison later
hash := sha256.New().Sum([]byte(r.String()))
return fmt.Sprintf("%x", hash)
}
type FeatureStateServicemeshAnalysisMessagesMessageBase struct {
empty bool `json:"-"`
Type *FeatureStateServicemeshAnalysisMessagesMessageBaseType `json:"type"`
Level *FeatureStateServicemeshAnalysisMessagesMessageBaseLevelEnum `json:"level"`
DocumentationUrl *string `json:"documentationUrl"`
}
type jsonFeatureStateServicemeshAnalysisMessagesMessageBase FeatureStateServicemeshAnalysisMessagesMessageBase
func (r *FeatureStateServicemeshAnalysisMessagesMessageBase) UnmarshalJSON(data []byte) error {
var res jsonFeatureStateServicemeshAnalysisMessagesMessageBase
if err := json.Unmarshal(data, &res); err != nil {
return err
}
var m map[string]interface{}
json.Unmarshal(data, &m)
if len(m) == 0 {
*r = *EmptyFeatureStateServicemeshAnalysisMessagesMessageBase
} else {
r.Type = res.Type
r.Level = res.Level
r.DocumentationUrl = res.DocumentationUrl
}
return nil
}
// This object is used to assert a desired state where this FeatureStateServicemeshAnalysisMessagesMessageBase is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyFeatureStateServicemeshAnalysisMessagesMessageBase *FeatureStateServicemeshAnalysisMessagesMessageBase = &FeatureStateServicemeshAnalysisMessagesMessageBase{empty: true}
func (r *FeatureStateServicemeshAnalysisMessagesMessageBase) Empty() bool {
return r.empty
}
func (r *FeatureStateServicemeshAnalysisMessagesMessageBase) String() string {
return dcl.SprintResource(r)
}
func (r *FeatureStateServicemeshAnalysisMessagesMessageBase) HashCode() string {
// Placeholder for a more complex hash method that handles ordering, etc
// Hash resource body for easy comparison later
hash := sha256.New().Sum([]byte(r.String()))
return fmt.Sprintf("%x", hash)
}
type FeatureStateServicemeshAnalysisMessagesMessageBaseType struct {
empty bool `json:"-"`
DisplayName *string `json:"displayName"`
Code *string `json:"code"`
}
type jsonFeatureStateServicemeshAnalysisMessagesMessageBaseType FeatureStateServicemeshAnalysisMessagesMessageBaseType
func (r *FeatureStateServicemeshAnalysisMessagesMessageBaseType) UnmarshalJSON(data []byte) error {
var res jsonFeatureStateServicemeshAnalysisMessagesMessageBaseType
if err := json.Unmarshal(data, &res); err != nil {
return err
}
var m map[string]interface{}
json.Unmarshal(data, &m)
if len(m) == 0 {
*r = *EmptyFeatureStateServicemeshAnalysisMessagesMessageBaseType
} else {
r.DisplayName = res.DisplayName
r.Code = res.Code
}
return nil
}
// This object is used to assert a desired state where this FeatureStateServicemeshAnalysisMessagesMessageBaseType is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyFeatureStateServicemeshAnalysisMessagesMessageBaseType *FeatureStateServicemeshAnalysisMessagesMessageBaseType = &FeatureStateServicemeshAnalysisMessagesMessageBaseType{empty: true}
func (r *FeatureStateServicemeshAnalysisMessagesMessageBaseType) Empty() bool {
return r.empty
}
func (r *FeatureStateServicemeshAnalysisMessagesMessageBaseType) String() string {
return dcl.SprintResource(r)
}
func (r *FeatureStateServicemeshAnalysisMessagesMessageBaseType) HashCode() string {
// Placeholder for a more complex hash method that handles ordering, etc
// Hash resource body for easy comparison later
hash := sha256.New().Sum([]byte(r.String()))
return fmt.Sprintf("%x", hash)
}
// Describe returns a simple description of this resource to ensure that automated tools
// can identify it.
func (r *Feature) Describe() dcl.ServiceTypeVersion {
return dcl.ServiceTypeVersion{
Service: "gke_hub",
Type: "Feature",
Version: "alpha",
}
}
func (r *Feature) ID() (string, error) {
if err := extractFeatureFields(r); err != nil {
return "", err
}
nr := r.urlNormalized()
params := map[string]interface{}{
"name": dcl.ValueOrEmptyString(nr.Name),
"labels": dcl.ValueOrEmptyString(nr.Labels),
"resource_state": dcl.ValueOrEmptyString(nr.ResourceState),
"spec": dcl.ValueOrEmptyString(nr.Spec),
"state": dcl.ValueOrEmptyString(nr.State),
"create_time": dcl.ValueOrEmptyString(nr.CreateTime),
"update_time": dcl.ValueOrEmptyString(nr.UpdateTime),
"delete_time": dcl.ValueOrEmptyString(nr.DeleteTime),
"project": dcl.ValueOrEmptyString(nr.Project),
"location": dcl.ValueOrEmptyString(nr.Location),
}
return dcl.Nprintf("projects/{{project}}/locations/{{location}}/features/{{name}}", params), nil
}
const FeatureMaxPage = -1
type FeatureList struct {
Items []*Feature
nextToken string
pageSize int32
resource *Feature
}
func (l *FeatureList) HasNext() bool {
return l.nextToken != ""
}
func (l *FeatureList) Next(ctx context.Context, c *Client) error {
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
if !l.HasNext() {
return fmt.Errorf("no next page")
}
items, token, err := c.listFeature(ctx, l.resource, l.nextToken, l.pageSize)
if err != nil {
return err
}
l.Items = items
l.nextToken = token
return err
}
func (c *Client) ListFeature(ctx context.Context, project, location string) (*FeatureList, error) {
ctx = dcl.ContextWithRequestID(ctx)
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
return c.ListFeatureWithMaxResults(ctx, project, location, FeatureMaxPage)
}
func (c *Client) ListFeatureWithMaxResults(ctx context.Context, project, location string, pageSize int32) (*FeatureList, error) {
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
// Create a resource object so that we can use proper url normalization methods.
r := &Feature{
Project: &project,
Location: &location,
}
items, token, err := c.listFeature(ctx, r, "", pageSize)
if err != nil {
return nil, err
}
return &FeatureList{
Items: items,
nextToken: token,
pageSize: pageSize,
resource: r,
}, nil
}
func (c *Client) GetFeature(ctx context.Context, r *Feature) (*Feature, error) {
ctx = dcl.ContextWithRequestID(ctx)
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
// This is *purposefully* supressing errors.
// This function is used with url-normalized values + not URL normalized values.
// URL Normalized values will throw unintentional errors, since those values are not of the proper parent form.
extractFeatureFields(r)
b, err := c.getFeatureRaw(ctx, r)
if err != nil {
if dcl.IsNotFound(err) {
return nil, &googleapi.Error{
Code: 404,
Message: err.Error(),
}
}
return nil, err
}
result, err := unmarshalFeature(b, c, r)
if err != nil {
return nil, err
}
result.Project = r.Project
result.Location = r.Location
result.Name = r.Name
c.Config.Logger.InfoWithContextf(ctx, "Retrieved raw result state: %v", result)
c.Config.Logger.InfoWithContextf(ctx, "Canonicalizing with specified state: %v", r)
result, err = canonicalizeFeatureNewState(c, result, r)
if err != nil {
return nil, err
}
if err := postReadExtractFeatureFields(result); err != nil {
return result, err
}
c.Config.Logger.InfoWithContextf(ctx, "Created result state: %v", result)
return result, nil
}
func (c *Client) DeleteFeature(ctx context.Context, r *Feature) error {
ctx = dcl.ContextWithRequestID(ctx)
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
if r == nil {
return fmt.Errorf("Feature resource is nil")
}
c.Config.Logger.InfoWithContext(ctx, "Deleting Feature...")
deleteOp := deleteFeatureOperation{}
return deleteOp.do(ctx, r, c)
}
// DeleteAllFeature deletes all resources that the filter functions returns true on.
func (c *Client) DeleteAllFeature(ctx context.Context, project, location string, filter func(*Feature) bool) error {
listObj, err := c.ListFeature(ctx, project, location)
if err != nil {
return err
}
err = c.deleteAllFeature(ctx, filter, listObj.Items)
if err != nil {
return err
}
for listObj.HasNext() {
err = listObj.Next(ctx, c)
if err != nil {
return nil
}
err = c.deleteAllFeature(ctx, filter, listObj.Items)
if err != nil {
return err
}
}
return nil
}
func (c *Client) ApplyFeature(ctx context.Context, rawDesired *Feature, opts ...dcl.ApplyOption) (*Feature, error) {
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
ctx = dcl.ContextWithRequestID(ctx)
var resultNewState *Feature
err := dcl.Do(ctx, func(ctx context.Context) (*dcl.RetryDetails, error) {
newState, err := applyFeatureHelper(c, ctx, rawDesired, opts...)
resultNewState = newState
if err != nil {
// If the error is 409, there is conflict in resource update.
// Here we want to apply changes based on latest state.
if dcl.IsConflictError(err) {
return &dcl.RetryDetails{}, dcl.OperationNotDone{Err: err}
}
return nil, err
}
return nil, nil
}, c.Config.RetryProvider)
return resultNewState, err
}
func applyFeatureHelper(c *Client, ctx context.Context, rawDesired *Feature, opts ...dcl.ApplyOption) (*Feature, error) {
c.Config.Logger.InfoWithContext(ctx, "Beginning ApplyFeature...")
c.Config.Logger.InfoWithContextf(ctx, "User specified desired state: %v", rawDesired)
// 1.1: Validation of user-specified fields in desired state.
if err := rawDesired.validate(); err != nil {
return nil, err
}
if err := extractFeatureFields(rawDesired); err != nil {
return nil, err
}
initial, desired, fieldDiffs, err := c.featureDiffsForRawDesired(ctx, rawDesired, opts...)
if err != nil {
return nil, fmt.Errorf("failed to create a diff: %w", err)
}
diffs, err := convertFieldDiffsToFeatureDiffs(c.Config, fieldDiffs, opts)
if err != nil {
return nil, err
}
// TODO(magic-modules-eng): 2.2 Feasibility check (all updates are feasible so far).
// 2.3: Lifecycle Directive Check
var create bool
lp := dcl.FetchLifecycleParams(opts)
if initial == nil {
if dcl.HasLifecycleParam(lp, dcl.BlockCreation) {
return nil, dcl.ApplyInfeasibleError{Message: fmt.Sprintf("Creation blocked by lifecycle params: %#v.", desired)}
}
create = true
} else if dcl.HasLifecycleParam(lp, dcl.BlockAcquire) {
return nil, dcl.ApplyInfeasibleError{
Message: fmt.Sprintf("Resource already exists - apply blocked by lifecycle params: %#v.", initial),
}
} else {
for _, d := range diffs {
if d.RequiresRecreate {
return nil, dcl.ApplyInfeasibleError{
Message: fmt.Sprintf("infeasible update: (%v) would require recreation", d),
}
}
if dcl.HasLifecycleParam(lp, dcl.BlockModification) {
return nil, dcl.ApplyInfeasibleError{Message: fmt.Sprintf("Modification blocked, diff (%v) unresolvable.", d)}
}
}
}
// 2.4 Imperative Request Planning
var ops []featureApiOperation
if create {
ops = append(ops, &createFeatureOperation{})
} else {
for _, d := range diffs {
ops = append(ops, d.UpdateOp)
}
}
c.Config.Logger.InfoWithContextf(ctx, "Created plan: %#v", ops)
// 2.5 Request Actuation
for _, op := range ops {
c.Config.Logger.InfoWithContextf(ctx, "Performing operation %T %+v", op, op)
if err := op.do(ctx, desired, c); err != nil {
c.Config.Logger.InfoWithContextf(ctx, "Failed operation %T %+v: %v", op, op, err)
return nil, err
}
c.Config.Logger.InfoWithContextf(ctx, "Finished operation %T %+v", op, op)
}
return applyFeatureDiff(c, ctx, desired, rawDesired, ops, opts...)
}
func applyFeatureDiff(c *Client, ctx context.Context, desired *Feature, rawDesired *Feature, ops []featureApiOperation, opts ...dcl.ApplyOption) (*Feature, error) {
// 3.1, 3.2a Retrieval of raw new state & canonicalization with desired state
c.Config.Logger.InfoWithContext(ctx, "Retrieving raw new state...")
rawNew, err := c.GetFeature(ctx, desired)
if err != nil {
return nil, err
}
// Get additional values from the first response.
// These values should be merged into the newState above.
if len(ops) > 0 {
lastOp := ops[len(ops)-1]
if o, ok := lastOp.(*createFeatureOperation); ok {
if r, hasR := o.FirstResponse(); hasR {
c.Config.Logger.InfoWithContext(ctx, "Retrieving raw new state from operation...")
fullResp, err := unmarshalMapFeature(r, c, rawDesired)
if err != nil {
return nil, err
}
rawNew, err = canonicalizeFeatureNewState(c, rawNew, fullResp)
if err != nil {
return nil, err
}
}
}
}
c.Config.Logger.InfoWithContextf(ctx, "Canonicalizing with raw desired state: %v", rawDesired)
// 3.2b Canonicalization of raw new state using raw desired state
newState, err := canonicalizeFeatureNewState(c, rawNew, rawDesired)
if err != nil {
return rawNew, err
}
c.Config.Logger.InfoWithContextf(ctx, "Created canonical new state: %v", newState)
// 3.3 Comparison of the new state and raw desired state.
// TODO(magic-modules-eng): EVENTUALLY_CONSISTENT_UPDATE
newDesired, err := canonicalizeFeatureDesiredState(rawDesired, newState)
if err != nil {
return newState, err
}
if err := postReadExtractFeatureFields(newState); err != nil {
return newState, err
}
// Need to ensure any transformations made here match acceptably in differ.
if err := postReadExtractFeatureFields(newDesired); err != nil {
return newState, err
}
c.Config.Logger.InfoWithContextf(ctx, "Diffing using canonicalized desired state: %v", newDesired)
newDiffs, err := diffFeature(c, newDesired, newState)
if err != nil {
return newState, err
}
if len(newDiffs) == 0 {
c.Config.Logger.InfoWithContext(ctx, "No diffs found. Apply was successful.")
} else {
c.Config.Logger.InfoWithContextf(ctx, "Found diffs: %v", newDiffs)
diffMessages := make([]string, len(newDiffs))
for i, d := range newDiffs {
diffMessages[i] = fmt.Sprintf("%v", d)
}
return newState, dcl.DiffAfterApplyError{Diffs: diffMessages}
}
c.Config.Logger.InfoWithContext(ctx, "Done Apply.")
return newState, nil
}
|
package problem1034
func colorBorder(grid [][]int, r0 int, c0 int, color int) [][]int {
if len(grid) == 0 {
return grid
}
oldColor := grid[r0][c0]
height := len(grid)
width := len(grid[0])
bfs(grid, r0, c0, height, width, oldColor, color)
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
if grid[i][j] == -1 {
grid[i][j] = oldColor
} else if grid[i][j] == -2 {
grid[i][j] = color
}
}
}
return grid
}
func bfs(grid [][]int, r0, c0, height, width, oldColor, newColor int) {
if !isPosLegal(r0, c0, height, width) {
return
}
if grid[r0][c0] < 0 {
return
}
if grid[r0][c0] != oldColor {
return
}
directions := [][]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
bound := false
for _, direction := range directions {
r1 := direction[0] + r0
c1 := direction[1] + c0
if !isPosLegal(r1, c1, height, width) {
bound = true
} else {
nextColor := grid[r1][c1]
if nextColor != oldColor && nextColor > 0 {
bound = true
}
}
}
if bound {
grid[r0][c0] = -2
} else {
// 用-1来标记已经访问
grid[r0][c0] = -1
}
for _, direction := range directions {
r1 := direction[0] + r0
c1 := direction[1] + c0
bfs(grid, r1, c1, height, width, oldColor, newColor)
}
}
func isPosLegal(r, c, h, w int) bool {
return r >= 0 && r < h && c >= 0 && c < w
}
|
package main
import (
"bytes"
"io"
"log"
"os"
"strconv"
"sync"
"time"
)
var pool = sync.Pool{
New: func() interface{} {
log.Println("allocation new bytes.Buffer")
return new(bytes.Buffer)
},
}
func main() {
var wg sync.WaitGroup
for i := 1; i < 20; i++ {
wg.Add(1)
customLog(os.Stdout, "debug-string-"+strconv.Itoa(i), &wg)
}
wg.Wait()
}
func customLog(w io.Writer, debug string, wg *sync.WaitGroup) {
// var b bytes.Buffer
defer wg.Done()
b := pool.Get().(*bytes.Buffer) // Getting from pool
b.Reset() // reset buffer to erase old call content
// log.Printf("The Object Reference of buffer : %p\n", &b)
b.WriteString(time.Now().Format("15:04:03"))
b.WriteString(" : ")
b.WriteString(debug)
b.WriteString("\n")
w.Write(b.Bytes())
pool.Put(b) // putting back to pool
}
/*
WITHOUT Having Pool : (creating buffer object every time)
====================
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e000
12:32:12 : debug-string-1
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e060
12:32:12 : debug-string-2
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e090
12:32:12 : debug-string-3
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e0c0
12:32:12 : debug-string-4
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e0f0
12:32:12 : debug-string-5
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e120
12:32:12 : debug-string-6
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e150
12:32:12 : debug-string-7
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e180
12:32:12 : debug-string-8
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e1b0
12:32:12 : debug-string-9
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e1e0
12:32:12 : debug-string-10
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e210
12:32:12 : debug-string-11
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e240
12:32:12 : debug-string-12
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e270
12:32:12 : debug-string-13
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e2a0
12:32:12 : debug-string-14
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e2d0
12:32:12 : debug-string-15
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e300
12:32:12 : debug-string-16
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e330
12:32:12 : debug-string-17
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e360
12:32:12 : debug-string-18
2021/06/06 12:32:49 The Object Reference of buffer : 0xc00010e390
12:32:12 : debug-string-19
WITH POOL:
==========
raja@raja-Latitude-3460:~/Documents/coding/golang/go-by-concurrency$ go run sync/pool.go
2021/06/06 12:38:33 allocation new bytes.Buffer
12:38:12 : debug-string-1
12:38:12 : debug-string-2
12:38:12 : debug-string-3
12:38:12 : debug-string-4
12:38:12 : debug-string-5
12:38:12 : debug-string-6
12:38:12 : debug-string-7
12:38:12 : debug-string-8
12:38:12 : debug-string-9
12:38:12 : debug-string-10
12:38:12 : debug-string-11
12:38:12 : debug-string-12
12:38:12 : debug-string-13
12:38:12 : debug-string-14
12:38:12 : debug-string-15
12:38:12 : debug-string-16
12:38:12 : debug-string-17
12:38:12 : debug-string-18
12:38:12 : debug-string-19
*/
|
package db
import (
"strconv"
"strings"
"time"
)
type InputDatetime struct {
year string
month string
date string
hour string
minute string
second string
}
func FormatDatetime(input *InputDatetime) string {
// Handle more faster
day := strings.Join([]string{input.year, input.month, input.date}, "-")
time := strings.Join([]string{input.hour, input.minute, input.second}, ":")
return strings.Join([]string{day, time}, " ")
}
func GetNowFormattedStr() string {
t := time.Now()
input := InputDatetime{
year: strconv.Itoa(t.Year()),
month: t.Month().String(),
date: strconv.Itoa(t.Day()),
hour: strconv.Itoa(t.Hour()),
minute: strconv.Itoa(t.Minute()),
second: strconv.Itoa(t.Second()),
}
return FormatDatetime(&input)
}
|
/*
* Copyright 2017 Manuel Gauto (github.com/twa16)
*
* 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 userspaced
import (
"os"
"time"
"github.com/fsouza/go-dockerclient"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/op/go-logging"
"github.com/spf13/viper"
)
//This is where I found the bug with Gogland haha (GO-3377)
//region Model Structs
//OrchestratorInfo This struct has the data that is sent to clients when they connect
type OrchestratorInfo struct {
SupportsCAS bool `json:"supports_cas"` //True if the daemon supports CAS authentication
CASURL string `json:"cas_url"` //Hostname that is used to connect to the CAS server
AllowsLocalLogin bool `json:"supports_local_login"` //True is the daemon supports local users
AllowsRegistration bool `json:"allows_registration"` //True if the daemon allows registration for local users
}
//Space Struct that represents the space
type Space struct {
ID uint `gorm:"primary_key"` // Primary Key and ID of container
CreatedAt time.Time `json:"-"` // Creation time
ArchiveDate time.Time `json:"archive_date,omitempty"` // This is the timestamp of when the space was archived. This is set if the space was archived.
Archived bool `json:"archived,omitempty"` // This value is true if the space was deleted as a result of inactivity. All data is lost but metadata is preserved.
ImageID uint `json:"image_id,omitempty"` // This is the image that is used by the container that contains the space. This is a link to SpaceImage.
LastNetAccess string `json:"last_net_access,omitempty"` // The time this space was last accessed over the network but not SSH. This may be empty if the space was never accessed.
LastSSHAccess time.Time `json:"last_ssh_access,omitempty"` // The time this space was last accessed over SSH. This may be empty if the space was never accessed.
OwnerID uint `json:"owner_id,omitempty"` // Unique ID of the user that owns the Space. This is a link to User.
HostID uint `json:"host_id,omitempty"` // ID of the host that contains this space
FriendlyName string `json:"space_name,omitempty"` // Friendly name of this space
ContainerID string `json:"space_id,omitempty"` // ID of Docker container running this space
SpaceState string `json:"space_state,omitempty"` // Running State of Space (running, paused, archived, error)
SSHKeyID uint `json:"ssh_key_id,omitempty"` // ID of the SSH Key that this container is using
PortLinks []SpacePortLink `json:"port_links,omitempty"` // Shows what external ports are bound to the ports on the space
KeepAlive bool `json:"keep_alive,omitempty"` // If true, this container will be started if found to be 'exited'
}
//SpacePortLink A link between container port and host port
type SpacePortLink struct {
ID uint `gorm:"primary_key" json:"-"` // Primary Key and ID of container
CreatedAt time.Time `json:"-"` //Timestamp of creation
SpacePort uint16 `json:"space_port"` //Port on the Space
ExternalPort uint16 `json:"external_port"` //Port that is exposed on the host
ExternalAddress string `json:"external_address"` //External address that clients would connect to the reach the space
DisplayAddress string `json:"external_display_address"` //Address that is displayed to clients as the external address
SpaceID uint `json:"-"` // ID of the space that this record is associated with
}
// SpaceImage Image that is used to create the underlying container for a space
type SpaceImage struct {
ID uint `gorm:"primary_key" json:"image_id"` //Primary Key
CreatedAt time.Time `json:"-"` //Creation time
Active bool `json:"active"` // If this is set to false, the user cannot use the image and is only kept to avoid breaking older spaces.
Description string `json:"description"` // Friendly description of this image.
DockerImage string `json:"docker_image"` // This is the full URI of the docker image.
DockerImageTag string `json:"docker_image_tag"` // Tag to use when retrieving the image
Name string `json:"name"` // Friendly name of this image.
}
// SpaceUsageReport This object stores the metrics for a space at a specific point in time. The reports are not reset each time therefore the difference between two reports will show the increase in the time between the reports.
type SpaceUsageReport struct {
ID uint `gorm:"primary_key" json:"-"` //Primary Key
CreatedAt time.Time `json:"-"` //Creation time
ContainerID string `json:"container_id"` // ID of the container
DiskUsageBytes int64 `json:"disk_usage_bytes"` // Number of bytes that the space is taking up on disk.
NetworkInBytes int64 `json:"network_in_bytes"` // Number of bytes that the space has received over the network. This does include SSH.
NetworkOutBytes int64 `json:"network_out_bytes"` // Number of bytes that the space has sent over the network. This includes SSH.
ReportID int64 `json:"report_id"` // ID of the report
SSHSessionCount int64 `json:"ssh_session_count"` // This is the number of SSH sessions the space has received.
Timestamp time.Time `json:"timestamp"` // Time this data was recorded
}
//UserPublicKey Represents a stored user public ssh key
type UserPublicKey struct {
ID uint `gorm:"primary_key" json:"-"` // Primary Key
PublicID string `gorm:"index" json:"space_id"` // Public UUID of this Key
CreatedAt time.Time `json:"-"` // Creation time
OwnerID uint `json:"user_id"` // ID of user tha owns this key
Name string `json:"name"` // Friendly name of this key
PublicKey string `json:"public_key"` // Public key
}
//DockerInstance Struct representing a docker instance to use for containers
type DockerInstance struct {
ID uint `gorm:"primary_key" json:"-"` //Primary Key
CreatedAt time.Time `json:"-"` //Creation Time
UpdatedAt time.Time `json:"-"` //Last Update time
Name string `json:"name"` //Friendly name of this docker instance
ConnectionType string `json:"connection_type"` //Type of connection to use when connecting a docker instance (local,tls)
Endpoint string `json:"sock_path"` //Path to the sock if the connection type is local or remote address if the type is tls
CaCertPath string `json:"ca_cert_path"` //Path to the CA certificate if the connection type is tls
ClientCertPath string `json:"client_cert_path"` //Path to the Client certificate if the connection type is tls
ClientKeyPath string `json:"client_key_path"` //Path to the Client key if the connection type is tls
IsConnected bool `json:"is_connected"` //This is true if the daemon is reporting it is connected to the Docker host
DockerClient *docker.Client `gorm:"-" json:"-"` //Connection to the Docker instance
ExternalAddress string `json:"external_address"` //External address that the spaces will use
ExternalDisplayAddress string `json:"external_display_address"` //External addresses that users will see
}
//endregion
//region Internal Structs
//endregion
//This should only be 4 chars or you have to change our fancy banner
var VERSION = "0.2A"
var log = logging.MustGetLogger("userspace-daemon")
var database *gorm.DB
func main() {
Init()
}
//All code that would normally be in main() is put here in case we want to separate this into another package so it can be used as a library
func Init() {
initLogging()
log.Infof(
"\n====================================\n"+
"== Userspace Daemon ==\n"+
"== Version: %s ==\n"+
"== Manuel Gauto(github.com/twa16) ==\n"+
"== With <3 to SRCT (srct.gmu.edu) ==\n"+
"====================================\n", VERSION)
//Load the Configuration
loadConfig()
//Init DB
log.Info("Connecting to database...")
db, err := gorm.Open("sqlite3", "./userspace.db")
//db.LogMode(true)
database = db
defer database.Close()
if err != nil {
log.Fatalf("Failed to connect to database. Error: %s\n", err.Error())
os.Exit(1)
}
//Migrate Models
log.Info("Migrating Models...")
database.AutoMigrate(&Space{})
database.AutoMigrate(&SpacePortLink{})
database.AutoMigrate(&SpaceImage{})
database.AutoMigrate(&SpaceUsageReport{})
database.AutoMigrate(&DockerInstance{})
database.AutoMigrate(&UserPublicKey{})
log.Info("Migration Complete.")
if viper.GetBool("UseLocalDockerHost") {
log.Info("Checking if there are any existing Docker hosts")
existingDockerHosts := getAllDockerInstanceConfigurations(db)
if len(existingDockerHosts) == 0 {
localDocker := DockerInstance{
Name: "Local Host",
ConnectionType: "local",
}
addAndConnectToDockerInstance(db, &localDocker)
log.Warning("Added local machine as Docker host!")
}
}
//Connect to docker hosts
initDockerHosts(database)
//Check if we need starter images
if viper.GetBool("PullStarterImages") {
ensureStarterImages(database)
}
log.Info("Synchronizing Images with Hosts")
downloadDockerImages(database)
log.Info("Initiating CAS Handler")
initCAS()
log.Info("Starting Space State Watcher")
go func(db *gorm.DB) {
log.Info("Space State Monitor Started")
for true {
updateSpaceStates(db)
time.Sleep(time.Second * 5)
}
}(db)
startAPI()
}
//initLogging Configures and initializes logging for the daemon
func initLogging() {
// Example format string. Everything except the message has a custom color
// which is dependent on the log level. Many fields have a custom output
// formatting too, eg. the time returns the hour down to the milli second.
var format = logging.MustStringFormatter(
`%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}`,
)
backend := logging.NewLogBackend(os.Stderr, "", 0)
// For messages written to backend2 we want to add some additional
// information to the output, including the used log level and the name of
// the function.
backendFormatter := logging.NewBackendFormatter(backend, format)
logging.SetBackend(backendFormatter)
}
//loadConfig I bet you can guess what this function does
func loadConfig() {
viper.SetConfigName("config") // name of config file (without extension)
viper.AddConfigPath("./config") // path to look for the config file in
viper.AddConfigPath("/etc/userspace/config") // path to look for the config file in
viper.AddConfigPath(".") // optionally look for config in the working directory
err := viper.ReadInConfig() // Find and read the config file
if err != nil {
log.Fatalf("Fatal error config file: %s \n", err) // Handle errors reading the config file
panic(err)
}
log.Infof("Using config file: %s", viper.ConfigFileUsed())
for _, key := range viper.AllKeys() {
log.Infof("Loaded: %s as %s", key, viper.GetString(key))
}
//viper.SetDefault("k", "v")
}
//updateSpaceStates Synchronizes the state of a space and its underlying container
func updateSpaceStates(db *gorm.DB) {
spaces := []Space{}
db.Find(&spaces)
for _, space := range spaces {
//Get the host of the Space
hostID := space.HostID
host := getHostByID(hostID)
//If the host is disconnected the start should be changed
if !host.IsConnected {
log.Infof("Updated Space %s(%d) to state %s from %s\n", space.FriendlyName, space.ID, "host error", space.SpaceState)
log.Criticalf("Host %s(%d) in Error State\n", host.Name, host.ID)
space.SpaceState = "host error"
db.Save(space)
continue
}
//Ignore spaces that are just starting or being removed
if space.SpaceState == "started" ||
space.SpaceState == "deleting" {
continue
}
//Get the client from the host
dClient := host.DockerClient
//Now let's grab the actual container
container, err := dClient.InspectContainer(space.ContainerID)
if err != nil {
//No need to continuously complain about containers that are already in error state
if space.SpaceState == "error" {
continue
}
log.Critical("Error updating space state: " + err.Error())
log.Infof("Updated Space %s(%d) to state %s from %s\n", space.FriendlyName, space.ID, "error", space.SpaceState)
space.SpaceState = "error"
db.Save(space)
continue
}
if container.State.Status == "exited" {
err = dClient.StartContainer(container.ID, nil)
if err == nil {
log.Infof("Restarted Space %s(%d) that was exited. [%s]\n", space.FriendlyName, space.ID, space.ContainerID)
space.SpaceState = "running"
db.Save(space)
continue
} else {
log.Critical("Failed to restart exited Space %s(%d). [%s]", space.FriendlyName, space.ID, space.ContainerID)
space.SpaceState = "error"
db.Save(space)
}
}
//Save the status
if container.State.Status != space.SpaceState {
log.Infof("Updated Space %s(%d) to state %s from %s\n", space.FriendlyName, space.ID, container.State.Status, space.SpaceState)
space.SpaceState = container.State.Status
db.Save(space)
continue
}
}
}
//GetSpaceArrayAssociation Retrieves associated records for an array of Spaces. Internally, this calls GetSpaceAssociation
func GetSpaceArrayAssociation(db *gorm.DB, spaces []Space) ([]Space, error) {
var processedSpaces []Space
for _, space := range spaces {
procSpace, err := GetSpaceAssociation(db, space)
if err != nil {
return processedSpaces, err
}
processedSpaces = append(processedSpaces, procSpace)
}
return processedSpaces, nil
}
//GetSpaceAssociation Retreives associated records for a Space
func GetSpaceAssociation(db *gorm.DB, space Space) (Space, error) {
err := db.Model(&space).Related(&space.PortLinks).Error
return space, err
}
|
//comecando os estudos com o livro "A Linguagem de Progrmação Go"
//programa que imprime "Olá Mundo!"package hello_world
//go run nome_do_programa.go compila e executa o codigo
//go build nome_do_programa.go compila, cria um executavel e executa o codigo
package main
import "fmt"
func main() {
fmt.Println("Olá Mundo!")
}
|
package rest
func setupNumbersRoutes(s *server) {
handler, err := loadNumbersHandler()
checkError(err)
s.router.GET("/numbers/:number/words", handler.ToWords)
}
|
/*
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
*/
package main
import (
"fmt"
"math/big"
)
func main() {
fmt.Println(solve(1000))
}
func solve(n int) int {
a := big.NewInt(1)
b := big.NewInt(1)
r := 1
for ; ; r++ {
if p := a.String(); len(p) >= n {
break
}
c := new(big.Int)
c.Add(a, b)
a, b = b, c
}
return r
}
|
package main
import "testing"
func TestInput1(t *testing.T) {
res := part1(9, 25)
if res != 32 {
t.Fatalf("Expected 32, got %s", res)
}
}
func TestInput2(t *testing.T) {
res := part1(1, 48)
if res != 95 {
t.Fatalf("Expected 32, got %s", res)
}
}
func TestInput3(t *testing.T) {
res := part1(9, 48)
if res != 63 {
t.Fatalf("Expected 32, got %s", res)
}
}
func TestInput4(t *testing.T) {
res := part1(10, 1618)
if res != 8317 {
t.Fatalf("Expected 32, got %s", res)
}
}
func TestInput5(t *testing.T) {
res := part1(13, 7999)
if res != 146373 {
t.Fatalf("Expected 32, got %s", res)
}
}
func TestInput6(t *testing.T) {
res := part1(17, 1104)
if res != 2764 {
t.Fatalf("Expected 32, got %s", res)
}
}
func TestInput7(t *testing.T) {
res := part1(21, 6111)
if res != 54718 {
t.Fatalf("Expected 32, got %s", res)
}
}
func TestInput8(t *testing.T) {
res := part1(30, 5807)
if res != 37305 {
t.Fatalf("Expected 32, got %s", res)
}
}
|
package core
import (
"strings"
"github.com/golang/protobuf/ptypes"
mh "github.com/multiformats/go-multihash"
"github.com/textileio/go-textile/pb"
)
// AddComment adds an outgoing comment block
func (t *Thread) AddComment(target string, body string) (mh.Multihash, error) {
t.mux.Lock()
defer t.mux.Unlock()
if !t.annotatable(t.config.Account.Address) {
return nil, ErrNotAnnotatable
}
body = strings.TrimSpace(body)
msg := &pb.ThreadComment{
Target: target,
Body: body,
}
res, err := t.commitBlock(msg, pb.Block_COMMENT, true, nil)
if err != nil {
return nil, err
}
err = t.indexBlock(&pb.Block{
Id: res.hash.B58String(),
Thread: t.Id,
Author: res.header.Author,
Type: pb.Block_COMMENT,
Date: res.header.Date,
Target: target,
Body: body,
Status: pb.Block_QUEUED,
}, false)
if err != nil {
return nil, err
}
log.Debugf("added COMMENT to %s: %s", t.Id, res.hash.B58String())
return res.hash, nil
}
// handleCommentBlock handles an incoming comment block
func (t *Thread) handleCommentBlock(block *pb.ThreadBlock) (handleResult, error) {
var res handleResult
msg := new(pb.ThreadComment)
err := ptypes.UnmarshalAny(block.Payload, msg)
if err != nil {
return res, err
}
if !t.readable(t.config.Account.Address) {
return res, ErrNotReadable
}
if !t.annotatable(block.Header.Address) {
return res, ErrNotAnnotatable
}
res.oldTarget = msg.Target
res.body = msg.Body
return res, nil
}
|
package contexts
import (
"encoding/json"
"github.com/MerinEREN/iiPackages/datastore/context"
)
// ContextWithValueOnly is used for page context request's response body.
type ContextWithValueOnly struct {
Value string `json:"value"`
}
// GetLangValue returns context or contexts only with value of the corresponding language.
func GetLangValue(cs context.Contexts, lang string) (interface{}, error) {
cwvos := make(map[string]ContextWithValueOnly)
var err error
for i, v := range cs {
contextValues := make(map[string]string)
err = json.Unmarshal(v.ValuesBS, &contextValues)
if err != nil {
return nil, err
}
cwvo := ContextWithValueOnly{contextValues[lang]}
if len(cs) == 1 {
return cwvo, err
}
cwvos[i] = cwvo
}
return cwvos, err
}
|
package main
import f "fmt"
func main() {
f.Println("패닉 복구")
printArray(1, 2, 3)
f.Println("Hello, World")
}
func printArray(a int, b int, c int) {
defer func() {
s := recover()
f.Println(s)
}()
array := [...]int{a, b, c}
for i := 0; i < 5; i++ {
f.Println(array[i])
}
}
|
package main
import (
"fmt"
)
func main() {
Mercado := []string{"Banana", "Arroz", "Feijão", "Tomate", "Frango", "Acucar"}
for lista := 0; lista < 6; lista++{
fmt.Printf("%d %s\n", lista, Mercado[lista])
}
}
|
package xcrypto
import (
"encoding/base64"
"encoding/hex"
)
type EncodeType uint
const (
ENCODE_UNSAFE_TYPE_RAW EncodeType = iota
ENCODE_SAFE_TYPE_BASE64
ENCODE_SAFE_TYPE_HEX
)
type Cipher struct {
encodeType EncodeType
}
func (c *Cipher) SetEncodeType(encodeType EncodeType) *Cipher {
c.encodeType = encodeType
return c
}
func (c *Cipher) EncodeData(encrypt []byte) []byte {
switch c.encodeType {
case ENCODE_SAFE_TYPE_BASE64:
return []byte(base64.StdEncoding.EncodeToString(encrypt))
case ENCODE_SAFE_TYPE_HEX:
return []byte(hex.EncodeToString(encrypt))
}
return encrypt
}
func (c *Cipher) DecodeData(decrypt string) ([]byte, error) {
switch c.encodeType {
case ENCODE_SAFE_TYPE_BASE64:
return base64.StdEncoding.DecodeString(decrypt)
case ENCODE_SAFE_TYPE_HEX:
return hex.DecodeString(decrypt)
}
return []byte(decrypt), nil
}
|
// Copyright (c) 2017 Intel Corporation
//
// 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 virtcontainers
import (
"syscall"
"github.com/sirupsen/logrus"
)
// VC is the Virtcontainers interface
type VC interface {
SetLogger(logger logrus.FieldLogger)
CreatePod(podConfig PodConfig) (VCPod, error)
DeletePod(podID string) (VCPod, error)
ListPod() ([]PodStatus, error)
PausePod(podID string) (VCPod, error)
ResumePod(podID string) (VCPod, error)
RunPod(podConfig PodConfig) (VCPod, error)
StartPod(podID string) (VCPod, error)
StatusPod(podID string) (PodStatus, error)
StopPod(podID string) (VCPod, error)
CreateContainer(podID string, containerConfig ContainerConfig) (VCPod, VCContainer, error)
DeleteContainer(podID, containerID string) (VCContainer, error)
EnterContainer(podID, containerID string, cmd Cmd) (VCPod, VCContainer, *Process, error)
KillContainer(podID, containerID string, signal syscall.Signal, all bool) error
StartContainer(podID, containerID string) (VCContainer, error)
StatusContainer(podID, containerID string) (ContainerStatus, error)
StopContainer(podID, containerID string) (VCContainer, error)
ProcessListContainer(podID, containerID string, options ProcessListOptions) (ProcessList, error)
}
// VCPod is the Pod interface
// (required since virtcontainers.Pod only contains private fields)
type VCPod interface {
Annotations(key string) (string, error)
GetAllContainers() []VCContainer
GetAnnotations() map[string]string
GetContainer(containerID string) VCContainer
ID() string
SetAnnotations(annotations map[string]string) error
}
// VCContainer is the Container interface
// (required since virtcontainers.Container only contains private fields)
type VCContainer interface {
GetAnnotations() map[string]string
GetPid() int
GetToken() string
ID() string
Pod() VCPod
Process() Process
SetPid(pid int) error
}
|
package redis
import (
"sync"
"time"
"github.com/dvirsky/go-pylog/logging"
"github.com/garyburd/redigo/redis"
"github.com/EverythingMe/meduza/driver"
"github.com/EverythingMe/meduza/errors"
"github.com/EverythingMe/meduza/query"
"github.com/EverythingMe/meduza/schema"
"golang.org/x/text/language"
)
// connection pool for dealing with redis
var pool *redis.Pool
// data encoder for encoding data to redis
var encoder schema.Encoder
// data deocder to decode data coming from redis into primitive types
var decoder schema.Decoder
func init() {
encoder = Encoder{}
decoder = Decoder{}
}
var normalizerPool = sync.Pool{
New: func() interface{} {
return schema.NewNormalizer(language.Und, true, false)
},
}
func getNormalizer() schema.TextNormalizer {
return normalizerPool.Get().(schema.TextNormalizer)
}
func putNormalizer(n schema.TextNormalizer) {
if n != nil {
normalizerPool.Put(n)
}
}
// Driver is the driver implementation over a redis data store
type Driver struct {
tableLock sync.RWMutex
tables map[string]*table
schemas map[string]*schema.Schema
}
// NewDriver creates a new redis driver instance
func NewDriver() *Driver {
return &Driver{
tables: make(map[string]*table),
schemas: make(map[string]*schema.Schema),
}
}
func initPool(config Config) {
timeout := time.Duration(config.Timeout) * time.Millisecond
pool = &redis.Pool{
MaxIdle: 10,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.DialTimeout(config.Network, config.Addr, timeout, timeout, timeout)
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, pooledTime time.Time) error {
// for connections that were idle for over a second, let's make sure they can still talk to redis before doing anything with them
if time.Since(pooledTime) > time.Second {
_, err := c.Do("PING")
return err
}
return nil
},
}
}
func (r *Driver) getTable(name string) (*table, bool) {
r.tableLock.RLock()
defer r.tableLock.RUnlock()
t, f := r.tables[name]
if !f {
logging.Warning("Non existing table name: %s", name)
}
return t, f
}
func (r *Driver) newTable(desc schema.Table) (*table, error) {
tbl := &table{
desc: desc,
indexes: make([]index, 0, len(desc.Indexes)),
}
for _, idx := range desc.Indexes {
logging.Debug("Creating index %s (type %s) on table %s", idx.Name, idx.Type, desc.Name)
tbl.AddIndex(idx)
}
if desc.Primary == nil {
tbl.primary = newRandomPrimary(desc.Primary, tbl)
} else {
switch desc.Primary.Type {
case schema.PrimaryCompound:
tbl.primary = newCompounPrimary(desc.Primary, tbl)
case schema.PrimaryRandom:
tbl.primary = newRandomPrimary(desc.Primary, tbl)
default:
return nil, errors.NewError("Unknown primary type: %s", desc.Primary.Type)
}
}
return tbl, nil
}
// The minimal frequency for the repair loop. We do this because we don't want to take up too much CPU
// time on repair loops
const MinRepairFrequency = 10 //ms
// Init initializes and configures the redis driver
func (r *Driver) Init(sp schema.SchemaProvider, config interface{}) error {
conf, ok := config.(Config)
if !ok {
return errors.NewError("Invalid configuration provided")
}
initPool(conf)
DefaultConfig = conf
encoder = NewEncoder(conf.TextCompressThreshold)
for _, sc := range sp.Schemas() {
r.handleSchema(sc)
}
go r.monitorChanges(sp)
if conf.Master && conf.RepairEnabled {
if conf.RepairFrequency < MinRepairFrequency {
conf.RepairFrequency = MinRepairFrequency
}
logging.Info("Running repair loop, frequency %dms", conf.RepairFrequency)
go r.repairLoop(time.Duration(conf.RepairFrequency) * time.Millisecond)
}
return nil
}
// handleSchema takes a schema spec and breaks it into tables, putting them in the table scec of the driver
func (r *Driver) handleSchema(sc *schema.Schema) error {
for _, desc := range sc.Tables {
logging.Debug("Creating table %s on schema %s", desc.Name, sc.Name)
tbl, err := r.newTable(*desc)
if err != nil {
logging.Error("Could not load schema into redis driver - bad schema: %s", err)
return err
}
r.tableLock.Lock()
r.tables[desc.Name] = tbl
r.tableLock.Unlock()
}
r.schemas[sc.Name] = sc
return nil
}
// Put executes a PUT query on the driver, inserting/updating one or more entities
func (r *Driver) Put(q query.PutQuery) *query.PutResponse {
ret := query.NewPutResponse(nil)
defer ret.Done()
if tbl, found := r.getTable(q.Table); !found {
ret.Error = errors.InvalidTableError
} else {
ids, err := tbl.Put(q.Entities...)
ret.Error = errors.Wrap(err)
ret.Ids = ids
}
return ret
}
// Get executes a GET query on the driver, selecting any number of entities
func (r *Driver) Get(q query.GetQuery) *query.GetResponse {
ret := query.NewGetResponse(nil)
defer ret.Done()
if tbl, found := r.getTable(q.Table); !found {
ret.Error = errors.InvalidTableError
} else {
tbl.Get(q, ret)
}
return ret
}
// Dump a specific table's records as a stream of entities.
//
// The function also returns a channel for erros that may occur, and a bool channel allowing its caller to
// stop it if an error has happened upstream
func (r *Driver) Dump(table string) (<-chan schema.Entity, <-chan error, chan<- bool, error) {
if tbl, found := r.getTable(table); !found {
return nil, nil, nil, errors.InvalidTableError
} else {
chunkSize := 50
idch, stopch := tbl.primary.Scan(chunkSize)
chunk := make([]schema.Key, chunkSize)
ch := make(chan schema.Entity)
errch := make(chan error)
rstopch := make(chan bool)
go func() {
defer close(ch)
i := 0
for id := range idch {
chunk[i] = id
i++
if i == chunkSize {
//logging.Debug("Dumping keys %v", chunk)
i = 0
ents, err := tbl.load(chunk)
if err != nil {
logging.Error("error loading entities for dumping: %s", err)
stopch <- true
errch <- err
return
}
for _, ent := range ents {
select {
case ch <- ent:
case <-rstopch:
logging.Info("Stopping iteration from caller")
stopch <- true
return
}
}
}
}
if i > 0 {
ents, err := tbl.load(chunk[:i])
if err != nil {
logging.Error("error loading entities for dumping: %s", err)
errch <- err
}
for _, ent := range ents {
ch <- ent
}
}
errch <- nil
}()
return ch, errch, rstopch, nil
}
}
// Delete executes a DEL query on the driver, deleting entities based on filter criteria
func (r *Driver) Delete(q query.DelQuery) *query.DelResponse {
ret := query.NewDelResponse(nil, 0)
defer ret.Done()
if tbl, found := r.getTable(q.Table); !found {
ret.Error = errors.InvalidTableError
} else {
num, err := tbl.Delete(q.Filters)
ret.Error = errors.Wrap(err)
ret.Num = num
}
return ret
}
// Update executes an UPDATE query on the driver, performing a series of changes on entities specified
// by a set of filters
func (r *Driver) Update(q query.UpdateQuery) *query.UpdateResponse {
ret := query.NewUpdateResponse(nil, 0)
defer ret.Done()
if tbl, found := r.getTable(q.Table); !found {
ret.Error = errors.InvalidTableError
} else {
num, err := tbl.Update(q)
ret.Error = errors.Wrap(err)
ret.Num = num
}
return ret
}
// Status returns an error if the driver is not properly running and has at least one schema active
func (r *Driver) Status() error {
if len(r.schemas) == 0 {
return errors.NewError("redis driver: no loaded schema")
}
if len(r.tables) == 0 {
return errors.NewError("redis driver: no loaded table")
}
conn := pool.Get()
if conn == nil {
return errors.NewError("redis driver: no connection to server")
}
defer conn.Close()
_, err := conn.Do("PING")
if err != nil {
return errors.NewError("redis driver: cannot ping server: %s", err)
}
return nil
}
func (r *Driver) monitorChanges(sp schema.SchemaProvider) {
logging.Debug("Monitoring schema changes in redis driver")
ch, err := sp.Updates()
if err != nil {
logging.Error("Cannot monitor changes in schema provider: %s", err)
return
}
for sc := range ch {
if sc != nil {
logging.Info("Detected change in schema: %s", sc.Name)
r.handleSchema(sc)
}
}
}
const SampleSize = 100
func (r *Driver) Stats() (*driver.Stats, error) {
ret := &driver.Stats{
Tables: make(map[string]*driver.TableStats),
}
var err error
for _, tbl := range r.tables {
if ret.Tables[tbl.desc.Name], err = tbl.Stats(SampleSize); err != nil {
logging.Error("Error sampling data: %s", err)
}
}
return ret, nil
}
|
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
var TARGET int = 19690720
func main() {
handle, _ := os.Open("../resources/pwd-layers.txt")
defer handle.Close()
scanner := bufio.NewScanner(handle)
var pixels []int
width := 25
height := 6
for scanner.Scan() {
tmp := strings.Split(scanner.Text(), "")
for _, p := range tmp {
pInt, _ := strconv.Atoi(p)
pixels = append(pixels, pInt)
}
}
/*
0 => black
1 => white
2 => transparent
*/
var curr []int
var layers [][]int
for len(pixels) > 0 {
curr, pixels = pixels[:width*height], pixels[width*height:]
layers = append(layers, curr)
}
fmt.Println("first layer: ", layers[0])
rendered := make([]int, width*height)
for i := 0; i < width*height; i++ {
for _, l := range layers {
if l[i] == 2 {
continue
} else {
rendered[i] = l[i]
break
}
}
}
// convert layers to more readable characters
renderedText := []string{}
for _, v := range rendered {
if v == 0 {
renderedText = append(renderedText, " ")
} else {
renderedText = append(renderedText, "#")
}
}
fmt.Println("Final render: ")
var line []string
for i := 0; i < height; i++ {
line, renderedText = renderedText[:width], renderedText[width:]
fmt.Println(strings.Join(line, ""))
}
}
|
package goauth
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// testResourceOwnerPasswordGrant implements the ResourceOwnerPasswordGrant interface and
// is intended for use only in testing.
type testResourceOwnerPasswordGrant struct {
client *testClient
username string
password Secret
}
// GetClientWithSecret returns a Client given a clientID or an error if the client is not found. It is implemented for testing purposes only.
func (t *testResourceOwnerPasswordGrant) GetClientWithSecret(clientID string, clientSecret Secret) (Client, error) {
if clientID == t.client.ID && clientSecret.RawString() == t.client.secret {
return t.client, nil
}
return nil, ErrorUnauthorizedClient
}
// AuthorizeResourceOwner checks the username and password against the configured properties of t. It returns an error if they do not match. It
// is implemented for testing purposes only.
func (t *testResourceOwnerPasswordGrant) AuthorizeResourceOwner(username string, password Secret, scope []string) ([]string, error) {
if username != t.username {
return nil, ErrorAccessDenied
}
if password != t.password {
return nil, ErrorAccessDenied
}
return scope, nil
}
func TestResourceOwnerPasswordGrantHandler(t *testing.T) {
// Set the default expiry for authorization codes to a low value
DefaultAuthorizationCodeExpiry = time.Millisecond
// Create a new instance of the mem session store
DefaultSessionStore = NewSessionStore(NewMemSessionStoreBackend())
server := newTestHandler()
// Generate a method to check the authentication of a request
securedHandler := server.Secure([]string{"testscope"}, func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("approved"))
})
// Generate a method to check the authentication of a request with a slightly different scope
securedHandlerDifferentScope := server.Secure([]string{"securescope"}, func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("approved"))
})
testCases([]testCase{
// Should return an error as the request does not contain the correct grant type
{
"POST",
"",
nil,
server.handleResourceOwnerPasswordCredentialsGrant,
func(r *http.Request) {
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
},
func(r *httptest.ResponseRecorder) {
if r.Code != 400 {
t.Errorf("Test failed, status %v", r.Code)
}
expected := []byte(`{"code":"invalid_request","description":"The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed."}` + "\n")
if !bytes.Equal(r.Body.Bytes(), expected) {
t.Errorf("Test failed, expected %s but got %s", expected, r.Body.Bytes())
}
},
},
// Should return an error as the request does not contain the correct grant type
{
"POST",
"",
strings.NewReader("grant_type=password"),
server.handleResourceOwnerPasswordCredentialsGrant,
func(r *http.Request) {
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
},
func(r *httptest.ResponseRecorder) {
if r.Code != 401 {
t.Errorf("Test failed, status %v", r.Code)
}
expected := []byte(`{"code":"access_denied","description":"The resource owner or authorization server denied the request."}` + "\n")
if !bytes.Equal(r.Body.Bytes(), expected) {
t.Errorf("Test failed, expected %s but got %s", expected, r.Body.Bytes())
}
},
},
// Should return a valid access token
{
"POST",
"",
strings.NewReader("grant_type=password&username=testusername&password=testpassword&scope=testscope"),
server.handleResourceOwnerPasswordCredentialsGrant,
func(r *http.Request) {
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.SetBasicAuth("testclientid", "testclientsecret")
},
func(r *httptest.ResponseRecorder) {
if r.Code != 200 {
t.Errorf("Test failed, status %v", r.Code)
}
m := make(map[string]interface{})
err := json.Unmarshal(r.Body.Bytes(), &m)
if err != nil {
t.Fatal(err)
}
if m["access_token"] != "testtoken" {
t.Errorf("Test failed, got %s but expected something else", r.Body.Bytes())
}
if m["refresh_token"] != "testtoken" {
t.Errorf("Test failed, got %s but expected something else", r.Body.Bytes())
}
if m["expires_in"] != 3600.00 {
t.Errorf("Test failed, got %s but expected something else", r.Body.Bytes())
}
if m["token_type"] != "bearer" {
t.Errorf("Test failed, got %s but expected something else", r.Body.Bytes())
}
if m["scope"] != "testscope" {
t.Errorf("Test failed, got %s but expected something else", r.Body.Bytes())
}
},
},
// Should throw an error attempting to access a secure resource
{
"GET",
"",
nil,
securedHandler,
func(r *http.Request) {
},
func(r *httptest.ResponseRecorder) {
if r.Code != 401 {
t.Errorf("Test failed, status %v", r.Code)
}
expected := []byte(`{"code":"access_denied","description":"The resource owner or authorization server denied the request."}` + "\n")
if !bytes.Equal(r.Body.Bytes(), expected) {
t.Errorf("Test failed, expected %s but got %s", expected, r.Body.Bytes())
}
},
},
// Should disallow the request as the client is not authorized for this scope
{
"GET",
"",
nil,
securedHandlerDifferentScope,
func(r *http.Request) {
r.Header.Set("Authorization", "Bearer testtoken")
},
func(r *httptest.ResponseRecorder) {
if r.Code != 401 {
t.Errorf("Test failed, status %v", r.Code)
}
expected := []byte(`{"code":"access_denied","description":"The resource owner or authorization server denied the request."}` + "\n")
if !bytes.Equal(r.Body.Bytes(), expected) {
t.Errorf("Test failed, expected %s but got %s", expected, r.Body.Bytes())
}
},
},
// Should allow the request as a valid token is passed
{
"GET",
"",
nil,
securedHandler,
func(r *http.Request) {
r.Header.Set("Authorization", "Bearer testtoken")
},
func(r *httptest.ResponseRecorder) {
if r.Code != 200 {
t.Errorf("Test failed, status %v", r.Code)
}
expected := []byte(`approved`)
if !bytes.Equal(r.Body.Bytes(), expected) {
t.Errorf("Test failed, expected %s but got %s", expected, r.Body.Bytes())
}
},
},
})
}
|
package game_map
import (
"fmt"
"github.com/steelx/go-rpg-cgm/combat"
"github.com/steelx/go-rpg-cgm/world"
"math"
"reflect"
)
var CombatActions = map[world.Action]func(state *CombatState, owner *combat.Actor, targets []*combat.Actor, defI interface{}){
world.HpRestore: HpRestore,
world.MpRestore: MpRestore,
world.Revive: Revive,
world.ElementSpell: elementSpell,
}
func HpRestore(state *CombatState, owner *combat.Actor, targets []*combat.Actor, defI interface{}) {
def := reflect.ValueOf(defI).Interface().(world.Item)
restoreAmount := def.Use.Restore
animEffect := Entities["fx_restore_hp"]
restoreColor := "#00ff45"
for _, v := range targets {
stats, _, entity := StatsCharEntity(state, v)
maxHP := stats.Get("HpMax")
nowHP := stats.Get("HpNow")
if nowHP > 0 {
AddTextNumberEffect(state, entity, restoreAmount, restoreColor)
nowHP = math.Min(maxHP, nowHP+restoreAmount)
stats.Set("HpNow", nowHP)
}
AddAnimEffect(state, entity, animEffect, 0.1)
}
}
func MpRestore(state *CombatState, owner *combat.Actor, targets []*combat.Actor, defI interface{}) {
def := reflect.ValueOf(defI).Interface().(world.Item)
restoreAmount := def.Use.Restore
animEffect := Entities["fx_restore_mp"]
restoreColor := "#00ffff"
for _, v := range targets {
stats, _, entity := StatsCharEntity(state, v)
maxMP := stats.Get("MpMax")
nowMP := stats.Get("MpNow")
nowHP := stats.Get("HpNow")
if nowHP > 0 {
AddTextNumberEffect(state, entity, restoreAmount, restoreColor)
nowMP = math.Min(maxMP, nowMP+restoreAmount)
stats.Set("MpNow", nowHP)
}
AddAnimEffect(state, entity, animEffect, 0.1)
}
}
func Revive(state *CombatState, owner *combat.Actor, targets []*combat.Actor, defI interface{}) {
def := reflect.ValueOf(defI).Interface().(world.Item)
restoreAmount := def.Use.Restore
animEffect := Entities["fx_revive"]
restoreColor := "#00ff00"
for _, v := range targets {
stats, character, entity := StatsCharEntity(state, v)
maxHP := stats.Get("HpMax")
nowHP := stats.Get("HpNow")
if nowHP <= 0 {
nowHP = math.Min(maxHP, nowHP+restoreAmount)
// the character will get a CETurn event automatically
// assigned next update
character.Controller.Change(csStandby, csStandby)
stats.Set("HpNow", nowHP)
AddTextNumberEffect(state, entity, restoreAmount, restoreColor)
}
AddAnimEffect(state, entity, animEffect, 0.1)
}
}
func AddAnimEffect(state *CombatState, entity *Entity, fxEntityDef EntityDefinition, spf float64) {
pos := entity.GetSelectPosition()
x := pos.X
y := pos.Y
effect := AnimEntityFxCreate(x, y, fxEntityDef, fxEntityDef.Frames, spf)
state.AddEffect(effect)
}
func AddTextNumberEffect(state *CombatState, entity *Entity, num float64, hexColor string) {
pos := entity.GetSelectPosition()
x, y := pos.X, pos.Y-entity.Height/2
fxText := fmt.Sprintf("+%v", num)
textEffect := CombatTextFXCreate(x, y, fxText, hexColor)
state.AddEffect(textEffect)
}
func StatsCharEntity(state *CombatState, actor *combat.Actor) (world.Stats, *Character, *Entity) {
stats := actor.Stats
character := state.ActorCharMap[actor]
entity := character.Entity
return stats, character, entity
}
func elementSpell(state *CombatState, owner *combat.Actor, targets []*combat.Actor, defI interface{}) {
def := reflect.ValueOf(defI).Interface().(world.SpecialItem)
for _, v := range targets {
_, _, entity := StatsCharEntity(state, v)
damage, hitResult := MagicAttack(state, owner, v, def)
if hitResult == HitResultHit {
state.ApplyDamage(v, damage, true)
}
if def.Element == world.SpellFire {
AddAnimEffect(state, entity, Entities["fx_fire"], 0.06)
} else if def.Element == world.SpellBolt {
AddAnimEffect(state, entity, Entities["fx_electric"], 0.12)
} else if def.Element == world.SpellIce {
AddAnimEffect(state, entity, Entities["fx_ice_1"], 0.1)
pos := entity.GetSelectPosition()
x := pos.X
y := pos.Y
spark := Entities["fx_ice_spark"]
effect := AnimEntityFxCreate(x, y, spark, spark.Frames, 0.12)
state.AddEffect(effect)
x2 := x + entity.Width*0.8
ice2 := Entities["fx_ice_2"]
effect = AnimEntityFxCreate(x2, y, ice2, ice2.Frames, 0.1)
state.AddEffect(effect)
x3 := x - entity.Width*0.8
y3 := y - entity.Height*0.6
ice3 := Entities["fx_ice_3"]
effect = AnimEntityFxCreate(x3, y3, ice3, ice3.Frames, 0.1)
state.AddEffect(effect)
}
}
}
|
package match
import (
"fmt"
"gorm.io/gorm"
"match-go/app/model/mysql/common"
)
type SQL struct {
master *gorm.DB
table string
}
type Model struct {
ID uint64 `gorm:"primarykey"`
Name string `gorm:"type:varchar(255);default:'';not null;comment:比赛名称"`
Pic string `gorm:"type:varchar(255);default:'';not null;comment:比赛图片"`
Description string `gorm:"type:varchar(255);default:'';not null;comment:比赛描述"`
common.Model `gorm:"embedded"`
}
func (m *Model) TableName() string {
return "match"
}
func NewMatchSQL(master *gorm.DB) *SQL {
return &SQL{
master: master,
table: "match",
}
}
func (m *SQL) GetAll() []Model {
res := make([]Model, 0)
if err := m.master.Table(m.table).Find(&res).Error; err != nil {
fmt.Println("error", err)
}
return res
}
|
package webrpc
import (
"net/http/httptest"
"net/url"
"strconv"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func makeTestServer() *httptest.Server {
i := 0
mutex := sync.RWMutex{}
globalnicks := map[string]struct{}{}
rpcserv := NewServer()
rpcserv.OnConnect(func(c *Conn) {
chans := map[string]struct{}{}
nick := ""
// Set user nick.
setNick := func(new string) bool {
// Lock mutex to block race conditions.
mutex.Lock()
defer mutex.Unlock()
// Fail if name in use.
if _, ok := globalnicks[new]; ok {
return false
}
// Broadcast change.
for ch := range chans {
err := c.Broadcast(ch, "nick", nick, new)
if err != nil {
panic(err)
}
}
// Update global nick map.
delete(globalnicks, nick)
globalnicks[new] = struct{}{}
nick = new
return true
}
c.On("nick", setNick)
c.On("join", func(ch string) bool {
c.Join(ch)
err := c.Broadcast(ch, "join", ch, nick)
if err != nil {
return false
}
chans[ch] = struct{}{}
return true
})
c.On("part", func(ch string) bool {
err := c.Broadcast(ch, "part", ch, nick)
c.Leave(ch)
if err != nil {
return false
}
delete(chans, ch)
return true
})
c.On("message", func(ch string, msg string) bool {
return c.Broadcast(ch, "message", ch, nick, msg) == nil
})
c.On("action", func(ch string, msg string) bool {
return c.Broadcast(ch, "action", ch, nick, msg) == nil
})
c.On("quit", func() {
c.Close()
})
c.OnClose(func() {
return
})
setNick("Guest" + strconv.Itoa(100000+i))
c.Emit("nick", "", nick)
i++
})
return httptest.NewServer(rpcserv)
}
func otherClient(urlstr string) {
cl, err := Dial(urlstr)
if err != nil {
panic(err)
}
defer cl.Close()
cl.Emit("join", "#general")
cl.Emit("nick", "Test2")
cl.Emit("message", "#general", "Hello!")
cl.Emit("message", "#general", "Anyone around?")
cl.Emit("part", "#general")
cl.Emit("join", "#riot")
cl.Emit("message", "#riot", "Hello?")
cl.Emit("part", "#riot")
cl.Emit("quit")
cl.Dispatch()
}
func TestServer(t *testing.T) {
ts := makeTestServer()
defer ts.Close()
u, _ := url.Parse(ts.URL)
u.Scheme = "ws"
urlstr := u.String()
cl, err := Dial(urlstr)
require.Nil(t, err)
defer cl.Close()
nicks := [][2]string{
{"", "Guest100000"},
{"Guest100001", "Test2"},
}
messages := [][3]string{
{"#general", "Test2", "Hello!"},
{"#general", "Test2", "Anyone around?"},
}
cl.On("nick", func(old string, new string) {
assert.Equal(t, nicks[0][0], old)
assert.Equal(t, nicks[0][1], new)
nicks = nicks[1:]
})
cl.On("message", func(chname string, name string, message string) {
assert.Equal(t, messages[0][0], chname)
assert.Equal(t, messages[0][1], name)
assert.Equal(t, messages[0][2], message)
messages = messages[1:]
})
cl.Emit("join", "#general")
cl.Emit("nick", "Test1", func(result bool) {
assert.True(t, result)
otherClient(urlstr)
cl.Emit("quit")
})
cl.Dispatch()
// Make sure all assertions were hit.
assert.Empty(t, nicks)
assert.Empty(t, messages)
}
|
package alerts
import (
"github.com/dennor/go-paddle/events/types"
"github.com/dennor/phpserialize"
"github.com/shopspring/decimal"
)
const PaymentDisputeClosedAlertName = "payment_dispute_closed"
// PaymentDisputeClosed refer to https://paddle.com/docs/reference-using-webhooks/#payment_dispute_closed
type PaymentDisputeClosed struct {
AlertName string `json:"alert_name"`
Amount *decimal.Decimal `json:"amount,string"`
CheckoutID string `json:"checkout_id"`
Currency string `json:"currency"`
Email string `json:"email"`
EventTime *types.Datetime `json:"event_time,string"`
FeeUsd *decimal.Decimal `json:"fee_usd,string"`
MarketingConsent *types.MarketingConsent `json:"marketing_consent,string"`
OrderID int `json:"order_id,string"`
Passthrough string `json:"passthrough"`
Status string `json:"status"`
PSignature string `json:"p_signature" php:"-"`
}
func (p *PaymentDisputeClosed) Serialize() ([]byte, error) {
return phpserialize.Marshal(p)
}
func (p *PaymentDisputeClosed) Signature() ([]byte, error) {
return []byte(p.PSignature), nil
}
|
package operatorlister
import (
"fmt"
"sync"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/metadata/metadatalister"
)
// UnionCustomResourceDefinitionLister is a custom implementation of an CustomResourceDefinition lister that allows a new
// Lister to be registered on the fly.
type UnionCustomResourceDefinitionLister struct {
CustomResourceDefinitionLister metadatalister.Lister
CustomResourceDefinitionLock sync.RWMutex
}
func (ucl *UnionCustomResourceDefinitionLister) Namespace(namespace string) metadatalister.NamespaceLister {
ucl.CustomResourceDefinitionLock.RLock()
defer ucl.CustomResourceDefinitionLock.RUnlock()
if ucl.CustomResourceDefinitionLister == nil {
panic(fmt.Errorf("no CustomResourceDefinition lister registered"))
}
return ucl.CustomResourceDefinitionLister.Namespace(namespace)
}
// List lists all CustomResourceDefinitions in the indexer.
func (ucl *UnionCustomResourceDefinitionLister) List(selector labels.Selector) (ret []*metav1.PartialObjectMetadata, err error) {
ucl.CustomResourceDefinitionLock.RLock()
defer ucl.CustomResourceDefinitionLock.RUnlock()
if ucl.CustomResourceDefinitionLister == nil {
return nil, fmt.Errorf("no CustomResourceDefinition lister registered")
}
return ucl.CustomResourceDefinitionLister.List(selector)
}
// Get retrieves the CustomResourceDefinition with the given name
func (ucl *UnionCustomResourceDefinitionLister) Get(name string) (*metav1.PartialObjectMetadata, error) {
ucl.CustomResourceDefinitionLock.RLock()
defer ucl.CustomResourceDefinitionLock.RUnlock()
if ucl.CustomResourceDefinitionLister == nil {
return nil, fmt.Errorf("no CustomResourceDefinition lister registered")
}
return ucl.CustomResourceDefinitionLister.Get(name)
}
// RegisterCustomResourceDefinitionLister registers a new CustomResourceDefinitionLister
func (ucl *UnionCustomResourceDefinitionLister) RegisterCustomResourceDefinitionLister(lister metadatalister.Lister) {
ucl.CustomResourceDefinitionLock.Lock()
defer ucl.CustomResourceDefinitionLock.Unlock()
ucl.CustomResourceDefinitionLister = lister
}
func (l *apiExtensionsV1Lister) RegisterCustomResourceDefinitionLister(lister metadatalister.Lister) {
l.customResourceDefinitionLister.RegisterCustomResourceDefinitionLister(lister)
}
func (l *apiExtensionsV1Lister) CustomResourceDefinitionLister() metadatalister.Lister {
return l.customResourceDefinitionLister
}
|
package main
import (
"context"
"errors"
"fmt"
"github.com/go-chi/chi"
"github.com/kreyyser/transshipment/common/config"
"github.com/kreyyser/transshipment/common/router"
"github.com/kreyyser/transshipment/restgateway/internal/ports"
"github.com/spf13/pflag"
"google.golang.org/grpc"
"log"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
cfg, err := loadConfig()
if err != nil {
return err
}
return initServer(cfg)
}
func loadConfig() (*config.ConfigManager, error) {
// Handle command line options
flagset := pflag.NewFlagSet("restgateway", pflag.ExitOnError)
configPath := flagset.StringP("config", "c", "", "Path to transhipment config yaml")
_ = flagset.Parse(os.Args[1:])
//Transhipment config file should exist in the file system
if _, err := os.Stat(*configPath); os.IsNotExist(err) {
return nil, errors.New("no config file provided")
}
// Build the Config Manager
cfmgr := config.NewManager(*configPath)
// Load configuration file
if err := cfmgr.Load(); err != nil {
return nil, fmt.Errorf("failed to load config file: %s", err)
}
return cfmgr, nil
}
func signaledCtx() (context.Context, context.CancelFunc) {
ctx, cncl := context.WithCancel(context.Background())
{
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
select {
case <-ctx.Done():
log.Println("ctx is done")
case sig := <-sigs:
log.Printf("signal received: %v", sig)
cncl()
}
}()
}
return ctx, cncl
}
func initServer(c *config.ConfigManager) error {
pc, err := c.GetServiceConfig("ports")
if err != nil {
return err
}
rg, err := c.GetServiceConfig("restgateway")
if err != nil {
return err
}
var conn *grpc.ClientConn
for i := 0; i < 3; i++ {
var conErr error
conn, conErr = grpc.Dial(fmt.Sprintf("%s%s", "ports", pc.Address), grpc.WithInsecure())
if conErr != nil && i == 2{
return err
}
if conErr == nil {
break
}
fmt.Println("giving grpc client time to catch up")
time.Sleep(time.Second * 2)
}
routes := [][]router.Route{
// TODO a place to add any other modules routes
ports.Routes(conn),
}
var apiRoutes []router.Route
for _, r := range routes {
apiRoutes = append(apiRoutes, r...)
}
rtr := chi.NewRouter()
for _, rt := range apiRoutes {
rtr.MethodFunc(rt.Method, rt.Path, rt.Handler)
}
srvr, err := New(rg.Address, rtr)
if err != nil {
return err
}
ctx, cncl := signaledCtx()
defer cncl()
return runSrvr(ctx, srvr)
}
func runSrvr(ctx context.Context, server *Server) error {
errs := make(chan error, 1)
go func(s *Server) {
defer func() {
_ = s.Close()
}()
err := s.Run(ctx)
if err != nil {
err = fmt.Errorf("run server error: %w", err)
}
errs <- err
}(server)
return <-errs
} |
package main
import (
"fmt"
"os"
"github.com/jessevdk/go-flags"
"github.com/contraband/gaol/commands"
)
type command struct {
name string
description string
command interface{}
}
func main() {
parser := flags.NewParser(&commands.Globals, flags.HelpFlag|flags.PassDoubleDash)
commands := []command{
{"ping", "check to see if the garden host is up", &commands.Ping{}},
{"create", "create a container", &commands.Create{}},
{"destroy", "destroy a container", &commands.Destroy{}},
{"list", "list running containers", &commands.List{}},
{"run", "run a command in the container", &commands.Run{}},
{"attach", "attach to a commmand running inside the container", &commands.Attach{}},
{"shell", "open a shell in the container", &commands.Shell{}},
{"stream-in", "stream data into the container", &commands.StreamIn{}},
{"stream-out", "stream data out of the container", &commands.StreamOut{}},
{"net-in", "map a port on the host to a port in the container", &commands.NetIn{}},
{"net-out", "whitelist an IP and port range for a container", &commands.NetOut{}},
{"properties", "list properties for a container", &commands.Properties{}},
{"set-gracetime", "set the grace time for a container", &commands.SetGraceTime{}},
}
for _, command := range commands {
_, err := parser.AddCommand(
command.name,
command.description,
"",
command.command,
)
if err != nil {
panic(err)
}
}
_, err := parser.Parse()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
|
package requestBody
type Message struct {
MsgContent string `json:"msg_content"`
Title string `json:"title,omitempty"`
ContentType string `json:"content_type,omitempty"`
Extras map[string]interface{} `json:"extras,omitempty"`
}
func (m *Message) SetMsgContent(c string) {
m.MsgContent = c
}
func (m *Message) SetTitle(t string) {
m.Title = t
}
func (m *Message) SetContentType(c string) {
m.ContentType = c
}
func (m *Message) SetExtras(key string, value interface{}) {
if m.Extras == nil {
m.Extras = make(map[string]interface{})
}
m.Extras[key] = value
}
|
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// Code generated from the elasticsearch-specification DO NOT EDIT.
// https://github.com/elastic/elasticsearch-specification/tree/33e8a1c9cad22a5946ac735c4fba31af2da2cec2
// Instantiates a data frame analytics job.
package putdataframeanalytics
import (
gobytes "bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/elastic/elastic-transport-go/v8/elastictransport"
"github.com/elastic/go-elasticsearch/v8/typedapi/types"
)
const (
idMask = iota + 1
)
// ErrBuildPath is returned in case of missing parameters within the build of the request.
var ErrBuildPath = errors.New("cannot build path, check for missing path parameters")
type PutDataFrameAnalytics struct {
transport elastictransport.Interface
headers http.Header
values url.Values
path url.URL
buf *gobytes.Buffer
req *Request
deferred []func(request *Request) error
raw io.Reader
paramSet int
id string
}
// NewPutDataFrameAnalytics type alias for index.
type NewPutDataFrameAnalytics func(id string) *PutDataFrameAnalytics
// NewPutDataFrameAnalyticsFunc returns a new instance of PutDataFrameAnalytics with the provided transport.
// Used in the index of the library this allows to retrieve every apis in once place.
func NewPutDataFrameAnalyticsFunc(tp elastictransport.Interface) NewPutDataFrameAnalytics {
return func(id string) *PutDataFrameAnalytics {
n := New(tp)
n.Id(id)
return n
}
}
// Instantiates a data frame analytics job.
//
// https://www.elastic.co/guide/en/elasticsearch/reference/{branch}/put-dfanalytics.html
func New(tp elastictransport.Interface) *PutDataFrameAnalytics {
r := &PutDataFrameAnalytics{
transport: tp,
values: make(url.Values),
headers: make(http.Header),
buf: gobytes.NewBuffer(nil),
req: NewRequest(),
}
return r
}
// Raw takes a json payload as input which is then passed to the http.Request
// If specified Raw takes precedence on Request method.
func (r *PutDataFrameAnalytics) Raw(raw io.Reader) *PutDataFrameAnalytics {
r.raw = raw
return r
}
// Request allows to set the request property with the appropriate payload.
func (r *PutDataFrameAnalytics) Request(req *Request) *PutDataFrameAnalytics {
r.req = req
return r
}
// HttpRequest returns the http.Request object built from the
// given parameters.
func (r *PutDataFrameAnalytics) HttpRequest(ctx context.Context) (*http.Request, error) {
var path strings.Builder
var method string
var req *http.Request
var err error
if len(r.deferred) > 0 {
for _, f := range r.deferred {
deferredErr := f(r.req)
if deferredErr != nil {
return nil, deferredErr
}
}
}
if r.raw != nil {
r.buf.ReadFrom(r.raw)
} else if r.req != nil {
data, err := json.Marshal(r.req)
if err != nil {
return nil, fmt.Errorf("could not serialise request for PutDataFrameAnalytics: %w", err)
}
r.buf.Write(data)
}
r.path.Scheme = "http"
switch {
case r.paramSet == idMask:
path.WriteString("/")
path.WriteString("_ml")
path.WriteString("/")
path.WriteString("data_frame")
path.WriteString("/")
path.WriteString("analytics")
path.WriteString("/")
path.WriteString(r.id)
method = http.MethodPut
}
r.path.Path = path.String()
r.path.RawQuery = r.values.Encode()
if r.path.Path == "" {
return nil, ErrBuildPath
}
if ctx != nil {
req, err = http.NewRequestWithContext(ctx, method, r.path.String(), r.buf)
} else {
req, err = http.NewRequest(method, r.path.String(), r.buf)
}
req.Header = r.headers.Clone()
if req.Header.Get("Content-Type") == "" {
if r.buf.Len() > 0 {
req.Header.Set("Content-Type", "application/vnd.elasticsearch+json;compatible-with=8")
}
}
if req.Header.Get("Accept") == "" {
req.Header.Set("Accept", "application/vnd.elasticsearch+json;compatible-with=8")
}
if err != nil {
return req, fmt.Errorf("could not build http.Request: %w", err)
}
return req, nil
}
// Perform runs the http.Request through the provided transport and returns an http.Response.
func (r PutDataFrameAnalytics) Perform(ctx context.Context) (*http.Response, error) {
req, err := r.HttpRequest(ctx)
if err != nil {
return nil, err
}
res, err := r.transport.Perform(req)
if err != nil {
return nil, fmt.Errorf("an error happened during the PutDataFrameAnalytics query execution: %w", err)
}
return res, nil
}
// Do runs the request through the transport, handle the response and returns a putdataframeanalytics.Response
func (r PutDataFrameAnalytics) Do(ctx context.Context) (*Response, error) {
response := NewResponse()
res, err := r.Perform(ctx)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode < 299 {
err = json.NewDecoder(res.Body).Decode(response)
if err != nil {
return nil, err
}
return response, nil
}
errorResponse := types.NewElasticsearchError()
err = json.NewDecoder(res.Body).Decode(errorResponse)
if err != nil {
return nil, err
}
if errorResponse.Status == 0 {
errorResponse.Status = res.StatusCode
}
return nil, errorResponse
}
// Header set a key, value pair in the PutDataFrameAnalytics headers map.
func (r *PutDataFrameAnalytics) Header(key, value string) *PutDataFrameAnalytics {
r.headers.Set(key, value)
return r
}
// Id Identifier for the data frame analytics job. This identifier can contain
// lowercase alphanumeric characters (a-z and 0-9), hyphens, and
// underscores. It must start and end with alphanumeric characters.
// API Name: id
func (r *PutDataFrameAnalytics) Id(id string) *PutDataFrameAnalytics {
r.paramSet |= idMask
r.id = id
return r
}
// AllowLazyStart Specifies whether this job can start when there is insufficient machine
// learning node capacity for it to be immediately assigned to a node. If
// set to `false` and a machine learning node with capacity to run the job
// cannot be immediately found, the API returns an error. If set to `true`,
// the API does not return an error; the job waits in the `starting` state
// until sufficient machine learning node capacity is available. This
// behavior is also affected by the cluster-wide
// `xpack.ml.max_lazy_ml_nodes` setting.
// API name: allow_lazy_start
func (r *PutDataFrameAnalytics) AllowLazyStart(allowlazystart bool) *PutDataFrameAnalytics {
r.req.AllowLazyStart = &allowlazystart
return r
}
// Analysis The analysis configuration, which contains the information necessary to
// perform one of the following types of analysis: classification, outlier
// detection, or regression.
// API name: analysis
func (r *PutDataFrameAnalytics) Analysis(analysis *types.DataframeAnalysisContainer) *PutDataFrameAnalytics {
r.req.Analysis = *analysis
return r
}
// AnalyzedFields Specifies `includes` and/or `excludes` patterns to select which fields
// will be included in the analysis. The patterns specified in `excludes`
// are applied last, therefore `excludes` takes precedence. In other words,
// if the same field is specified in both `includes` and `excludes`, then
// the field will not be included in the analysis. If `analyzed_fields` is
// not set, only the relevant fields will be included. For example, all the
// numeric fields for outlier detection.
// The supported fields vary for each type of analysis. Outlier detection
// requires numeric or `boolean` data to analyze. The algorithms don’t
// support missing values therefore fields that have data types other than
// numeric or boolean are ignored. Documents where included fields contain
// missing values, null values, or an array are also ignored. Therefore the
// `dest` index may contain documents that don’t have an outlier score.
// Regression supports fields that are numeric, `boolean`, `text`,
// `keyword`, and `ip` data types. It is also tolerant of missing values.
// Fields that are supported are included in the analysis, other fields are
// ignored. Documents where included fields contain an array with two or
// more values are also ignored. Documents in the `dest` index that don’t
// contain a results field are not included in the regression analysis.
// Classification supports fields that are numeric, `boolean`, `text`,
// `keyword`, and `ip` data types. It is also tolerant of missing values.
// Fields that are supported are included in the analysis, other fields are
// ignored. Documents where included fields contain an array with two or
// more values are also ignored. Documents in the `dest` index that don’t
// contain a results field are not included in the classification analysis.
// Classification analysis can be improved by mapping ordinal variable
// values to a single number. For example, in case of age ranges, you can
// model the values as `0-14 = 0`, `15-24 = 1`, `25-34 = 2`, and so on.
// API name: analyzed_fields
func (r *PutDataFrameAnalytics) AnalyzedFields(analyzedfields *types.DataframeAnalysisAnalyzedFields) *PutDataFrameAnalytics {
r.req.AnalyzedFields = analyzedfields
return r
}
// Description A description of the job.
// API name: description
func (r *PutDataFrameAnalytics) Description(description string) *PutDataFrameAnalytics {
r.req.Description = &description
return r
}
// Dest The destination configuration.
// API name: dest
func (r *PutDataFrameAnalytics) Dest(dest *types.DataframeAnalyticsDestination) *PutDataFrameAnalytics {
r.req.Dest = *dest
return r
}
// API name: headers
func (r *PutDataFrameAnalytics) Headers(httpheaders types.HttpHeaders) *PutDataFrameAnalytics {
r.req.Headers = httpheaders
return r
}
// MaxNumThreads The maximum number of threads to be used by the analysis. Using more
// threads may decrease the time necessary to complete the analysis at the
// cost of using more CPU. Note that the process may use additional threads
// for operational functionality other than the analysis itself.
// API name: max_num_threads
func (r *PutDataFrameAnalytics) MaxNumThreads(maxnumthreads int) *PutDataFrameAnalytics {
r.req.MaxNumThreads = &maxnumthreads
return r
}
// ModelMemoryLimit The approximate maximum amount of memory resources that are permitted for
// analytical processing. If your `elasticsearch.yml` file contains an
// `xpack.ml.max_model_memory_limit` setting, an error occurs when you try
// to create data frame analytics jobs that have `model_memory_limit` values
// greater than that setting.
// API name: model_memory_limit
func (r *PutDataFrameAnalytics) ModelMemoryLimit(modelmemorylimit string) *PutDataFrameAnalytics {
r.req.ModelMemoryLimit = &modelmemorylimit
return r
}
// Source The configuration of how to source the analysis data.
// API name: source
func (r *PutDataFrameAnalytics) Source(source *types.DataframeAnalyticsSource) *PutDataFrameAnalytics {
r.req.Source = *source
return r
}
// API name: version
func (r *PutDataFrameAnalytics) Version(versionstring string) *PutDataFrameAnalytics {
r.req.Version = &versionstring
return r
}
|
package oidcsdk
import (
"github.com/identityOrg/oidcsdk/util"
"strings"
)
type RequestProfile map[string]string
func NewRequestProfile() RequestProfile {
return make(map[string]string)
}
func (r RequestProfile) GetUsername() string {
return r["username"]
}
func (r RequestProfile) SetUsername(username string) {
r["username"] = username
}
func (r RequestProfile) GetClientID() string {
return r["client_id"]
}
func (r RequestProfile) SetClientID(username string) {
r["client_id"] = username
}
func (r RequestProfile) GetState() string {
return r["state"]
}
func (r RequestProfile) SetState(state string) {
r["state"] = state
}
func (r RequestProfile) GetNonce() string {
return r["nonce"]
}
func (r RequestProfile) SetNonce(nonce string) {
r["nonce"] = nonce
}
func (r RequestProfile) GetRedirectURI() string {
return r["redirect_uri"]
}
func (r RequestProfile) SetRedirectURI(redirectUri string) {
r["redirect_uri"] = redirectUri
}
func (r RequestProfile) GetScope() Arguments {
s := r["scope"]
if s != "" {
return util.RemoveEmpty(strings.Split(s, " "))
}
return []string{}
}
func (r RequestProfile) SetScope(scopes Arguments) {
r["scope"] = strings.Join(scopes, " ")
}
func (r RequestProfile) GetAudience() Arguments {
s := r["audience"]
if s != "" {
return util.RemoveEmpty(strings.Split(s, " "))
}
return []string{}
}
func (r RequestProfile) SetAudience(aud Arguments) {
r["audience"] = strings.Join(aud, " ")
}
func (r RequestProfile) IsClient() bool {
return r["domain"] == ""
}
func (r RequestProfile) GetDomain() string {
return r["domain"]
}
func (r RequestProfile) SetDomain(domain string) {
r["domain"] = domain
}
func (r RequestProfile) GetCodeChallenge() string {
return r["code_challenge"]
}
func (r RequestProfile) SetCodeChallenge(challenge string) {
r["code_challenge"] = challenge
}
func (r RequestProfile) GetCodeChallengeMethod() string {
return r["code_challenge_method"]
}
func (r RequestProfile) SetCodeChallengeMethod(challengeMethod string) {
r["code_challenge_method"] = challengeMethod
}
func (r RequestProfile) GetGrantType() string {
return r["grant_type"]
}
func (r RequestProfile) SetGrantType(challengeMethod string) {
r["grant_type"] = challengeMethod
}
|
package TriUI
import (
"strconv"
pf "trident.li/pitchfork/lib"
pu "trident.li/pitchfork/ui"
)
func h_group_vcp(cui pu.PfUI) {
criterias := []string{"Unmarked", "Dunno", "Vouched"}
limits := []int{10, 25, 50}
criteria, err := cui.FormValue("criteria")
if err != nil || (criteria != "Unmarked" && criteria != "Dunno" && criteria != "Vouched") {
criteria = "Unmarked"
}
limit := 25
limit_v, err := cui.FormValue("limit")
if err == nil {
limit_t, err2 := strconv.Atoi(limit_v)
if err2 == nil && limit_t < 51 {
limit = limit_t
}
}
offset := 0
offset_v, err := cui.FormValue("offset")
if err == nil {
offset_t, err2 := strconv.Atoi(offset_v)
if err2 == nil && offset_t < 50 {
offset = offset_t
}
}
if cui.IsPOST() {
marks, err := cui.FormValueM("marked[]")
if err == nil {
for _, m := range marks {
q := ""
if criteria == "Unmarked" {
q = "INSERT INTO member_vouch " +
"(vouchor, vouchee, trustgroup, positive) " +
"VALUES ($1, $2, $3, FALSE)"
} else {
positivity := "positive"
if criteria == "Dunno" {
positivity = "NOT positive"
} else if criteria == "Vouched" {
positivity = "positive"
} else {
cui.Errf("Unknown Criteria: %s", criteria)
pu.H_errtxt(cui, "Invalid")
return
}
q = "DELETE FROM member_vouch mv " +
"WHERE mv.vouchor = $1 " +
"AND mv.vouchee = $2 " +
"AND mv.trustgroup = $3 " +
"AND " + positivity
}
err = pf.DB.Exec(cui, "Update vouch: vouchor: $1, vouchee: $2, group: $3", 1, q, cui.TheUser().GetUserName(), m, cui.SelectedGroup().GetGroupName())
}
}
}
type VCP struct {
UserName string
FullName string
Affiliation string
}
/* Criteria "Unmarked" */
and_where := "AND mv.vouchee IS NULL"
action := "Dunno"
switch criteria {
case "Dunno":
and_where = "AND mv.vouchee IS NOT NULL AND NOT mv.positive"
action = "Reconsider"
break
case "Vouched":
and_where = "AND mv.vouchee IS NOT NULL AND mv.positive"
action = "Unvouch"
break
}
total := 0
q := "SELECT COUNT(*) " +
"FROM member m " +
"JOIN member_trustgroup mt ON (mt.member = m.ident " +
" AND mt.trustgroup = $1 " +
" AND mt.member <> $2) " +
"JOIN member_state ms ON (ms.ident = mt.state) " +
"LEFT OUTER JOIN member_vouch mv " +
"ON (mv.trustgroup = mt.trustgroup " +
" AND mv.vouchee = m.ident " +
" AND mv.vouchor = $2) " +
"WHERE NOT ms.hidden " + and_where
err = pf.DB.QueryRow(q, cui.SelectedGroup().GetGroupName(), cui.TheUser().GetUserName()).Scan(&total)
if err != nil {
pu.H_errtxt(cui, "Query broken")
return
}
q = "SELECT m.ident, m.descr, m.affiliation " +
"FROM member m " +
"JOIN member_trustgroup mt ON (mt.member = m.ident " +
" AND mt.trustgroup = $1 " +
" AND mt.member <> $2) " +
"JOIN member_state ms ON (ms.ident = mt.state) " +
"LEFT OUTER JOIN member_vouch mv " +
"ON (mv.trustgroup = mt.trustgroup " +
" AND mv.vouchee = m.ident " +
" AND mv.vouchor = $2) " +
"WHERE NOT ms.hidden " + and_where + " " +
"ORDER BY mt.entered " +
"LIMIT $3 OFFSET $4"
rows, err := pf.DB.Query(q, cui.SelectedGroup().GetGroupName(), cui.TheUser().GetUserName(), limit, offset)
if err != nil {
pu.H_errmsg(cui, err)
return
}
defer rows.Close()
var vcps []VCP
for rows.Next() {
var vcp VCP
err = rows.Scan(&vcp.UserName, &vcp.FullName, &vcp.Affiliation)
if err != nil {
return
}
vcps = append(vcps, vcp)
}
/* Output the page */
type Page struct {
*pu.PfPage
PagerOffset int
PagerTotal int
GroupName string
Members []VCP
Action string
Criteria string
Criterias []string
Limit int
Limits []int
}
p := Page{cui.Page_def(), offset, total, cui.SelectedGroup().GetGroupName(), vcps, action, criteria, criterias, limit, limits}
cui.Page_show("group/vcp.tmpl", p)
}
|
package main
import "fmt"
func main() {
fmt.Println(differenceOfDistinctValues([][]int{
{1, 2, 3},
{3, 1, 5},
{3, 2, 1},
}))
}
func differenceOfDistinctValues(grid [][]int) [][]int {
m, n := len(grid), len(grid[0])
ans := make([][]int, m)
for i := range ans {
ans[i] = make([]int, n)
}
abs := func(a int) int {
if a < 0 {
return -a
}
return a
}
get := func(i, j, flag int) int {
mm := make(map[int]bool)
var c int
for ii, jj := i+flag, j+flag; ii >= 0 && jj >= 0 && ii < m && jj < n; ii, jj = ii+flag, jj+flag {
if !mm[grid[ii][jj]] {
c++
mm[grid[ii][jj]] = true
}
}
return c
}
for i, row := range grid {
for j, _ := range row {
ans[i][j] = abs(get(i, j, -1) - get(i, j, 1))
}
}
return ans
}
|
package main
import (
"bufio"
"fmt"
"os"
"regexp"
"strings"
)
// A Word refers to an N event (action or object).
type Word string
func (w Word) isNoun() bool {
re := "^[0-9]+$" // zero draft simplification
b, _ := regexp.MatchString(re, string(w))
return b
}
func (w Word) isVerb() bool {
re := "^[!#$%&*+,-;<=>?@|]$"
b, _ := regexp.MatchString(re, string(w))
return b
}
func (w Word) isPronom() bool {
re:= "^[A-Za-z]+$"
b, _ := regexp.MatchString(re, string(w))
return b
}
// A Sentence is a stack of Words.
type Sentence []Word
// Introduce a Word to the end of a Sentence.
func (s Sentence) intr(w Word) Sentence {
return append(s, w)
}
// Eliminate the Word at the end of a Sentence.
func (s Sentence) elim() Sentence {
return s[:len(s)-1]
}
// last Word of a Sentence.
func (s Sentence) last() Word {
return s[len(s)-1]
}
// VERY ineffecient where for sentences.
func (s Sentence) where(Q func(Word)bool) []int {
var N []int
for i, w := range s {
if Q(w) {
N = append(N,i)
}
}
return N
}
func (s Sentence) String() string {
var ss []string
for _, w := range s {
ss = append(ss, string(w))
}
return strings.Join(ss, " ")
}
type Noun Word
type Verb Word
type Adverb Word
type Pronom Word
type Copula Word
func main() {
x := read()
fmt.Println(x)
fmt.Println("Words:",len(x))
fmt.Println("Nouns:",x.where(Word.isNoun))
fmt.Println("Verbs:", x.where(Word.isVerb))
fmt.Println("Pronoms:", x.where(Word.isPronom))
}
func read() Sentence {
fmt.Print(" ") // prompt
in, _ := bufio.NewReader(os.Stdin).ReadString('\n') // read line from prompt
// ^ ignores reader errror!!!
in = strings.TrimSpace(in)
ss := regexp.MustCompile(" +").Split(in, -1) // assumes space separated words
var out Sentence
for _, s := range ss {
out = out.intr(Word(s))
}
return out
}
// Reverse a string with rev.
func rev(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
|
/* RZFeeser | Alta3 Research
Writing out to a YAML file */
package main
import (
"fmt"
"io/ioutil"
"log"
"gopkg.in/yaml.v3"
)
type User struct {
Name string
Occupation string
}
func main() {
users := map[string]User{"user 1": {"John Doe", "gardener"},
"user 2": {"Lucy Black", "teacher"}}
data, err := yaml.Marshal(&users)
if err != nil {
log.Fatal(err)
}
err2 := ioutil.WriteFile("users.yaml", data, 0)
if err2 != nil {
log.Fatal(err2)
}
fmt.Println("data written")
}
|
package user
import (
"context"
"fmt"
"github.com/gorilla/mux"
"github.com/heptiolabs/healthcheck"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"net/http"
"runtime"
"time"
)
var getUserRequestsTotal prometheus.Gauge
var getUserRequestsError prometheus.Gauge
var getUserRequestsSuccess prometheus.Gauge
var httpStatusCodes *prometheus.CounterVec
var (
httpDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "redis_cache_example_user_http_request_duration_seconds",
Help: "Duration of HTTP requests.",
}, []string{"path"})
userGetDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "redis_cache_example_user_get_duration_seconds",
Help: "Duration of get user operations.",
}, []string{"id"})
)
func init() {
getUserRequestsTotal = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "redis_cache_example_user_get_request_total",
Help: "Total requests for user endpoint",
})
prometheus.MustRegister(getUserRequestsTotal)
getUserRequestsError = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "redis_cache_example_user_get_request_error",
Help: "Error requests for user endpoint",
})
prometheus.MustRegister(getUserRequestsError)
getUserRequestsSuccess = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "redis_cache_example_user_get_request_success",
Help: "Success requests for user endpoint",
})
prometheus.MustRegister(getUserRequestsSuccess)
httpStatusCodes = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "redis_cache_example_user_get_handler_request_total",
Help: "Total number of get users by HTTP status code.",
},
[]string{"code", "method"})
prometheus.MustRegister(httpStatusCodes)
}
func GoroutineCountCheck(threshold int) healthcheck.Check {
return func() error {
count := runtime.NumGoroutine()
if count > threshold {
return fmt.Errorf("too many goroutines (%d > %d)", count, threshold)
}
return nil
}
}
func DatabasePingCheck(db Storage, timeout time.Duration) healthcheck.Check {
return func() error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
if db == nil {
return fmt.Errorf("database is nil")
}
return db.PingPool(ctx)
}
}
func CachePingCheck(cache Cache, timeout time.Duration) healthcheck.Check {
return func() error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
if cache == nil {
return fmt.Errorf("database is nil")
}
return cache.PingClient(ctx)
}
}
func PrometheusHTTPDurationMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
route := mux.CurrentRoute(r)
path, _ := route.GetPathTemplate()
timer := prometheus.NewTimer(httpDuration.WithLabelValues(path))
next.ServeHTTP(w, r)
timer.ObserveDuration()
})
}
|
package models
import (
"github.com/jinzhu/gorm"
"github.com/gophergala2016/source/core/foundation"
"github.com/gophergala2016/source/core/net/context/accessor"
)
// RootRepository is base struct for repository
type RootRepository struct {
Ctx foundation.Context
Orm *gorm.DB
}
// NewRootRepository creates new NewRootRepository
func NewRootRepository(ctx foundation.Context) RootRepository {
r := RootRepository{}
r.Ctx = ctx
r.Orm = accessor.GetDatabase(ctx)
return r
}
|
package config
import (
"fmt"
"os"
"strconv"
"time"
"github.com/DATA-DOG/go-sqlmock"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
// Init returns connector to Soteria database
func NewMySQL() (*sqlx.DB, sqlmock.Sqlmock) {
var db *sqlx.DB
var mock sqlmock.Sqlmock
var err error
env := os.Getenv("ENV")
if env == "test" || env == "" {
_, mock, err = sqlmock.NewWithDSN("sqlmock_db")
db, err = sqlx.Open("sqlmock", "sqlmock_db")
if err != nil {
panic(err.Error())
}
} else {
dbUsername := os.Getenv("DATABASE_USERNAME")
dbPassword := os.Getenv("DATABASE_PASSWORD")
dbHost := os.Getenv("DATABASE_HOST")
dbName := os.Getenv("DATABASE_NAME")
dbPort := os.Getenv("DATABASE_PORT")
if dbPort == "" {
dbPort = "3306"
}
if env == "development" || env == "staging" {
fmt.Printf("Connecting to [USERNAME]:[PASSWORD]@(%s:%v)/%s?parseTime=true\n", dbHost, dbPort, dbName)
}
dataSourceName := fmt.Sprintf("%s:%v@(%s:%v)/%s?parseTime=true", dbUsername, dbPassword, dbHost, dbPort, dbName)
db, _ = sqlx.Open("mysql", dataSourceName)
if err := db.Ping(); err != nil {
panic(err.Error())
}
if dp, err := strconv.Atoi(os.Getenv("DATABASE_POOL")); err == nil && dp > 0 {
db.SetMaxIdleConns(dp)
}
db.SetConnMaxLifetime(time.Minute)
}
return db, mock
}
|
package main
import "fmt"
func main() {
items := []int{0, 1, 2, 1}
fmt.Println(items)
for i := 0; i < len(items); i++ {
if items[i] == 1 {
items = append(items, 10)
}
}
fmt.Println(items)
}
|
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2021/12/28 9:13 上午
# @File : lt_38_外观数列_test.go.go
# @Description :
# @Attention :
*/
package hot100
import (
"fmt"
"testing"
"time"
)
func Test_countAndSay(t *testing.T) {
fmt.Println(countAndSay(4))
}
func Test_Sleep(t *testing.T) {
ars := []int{1, 2, 3}
for _, v := range ars {
go func() {
fmt.Println(v)
}()
time.Sleep(time.Second)
}
}
func TestClosure(t *testing.T) {
addrList := []string{
"上地",
"马连洼",
"五道口",
"西二旗",
}
for _, addr := range addrList {
//v := addr
test := func(addrPassedByValue string) {
testFunc1(addrPassedByValue)
testFunc2(addr)
}
go runTest(test, addr)
time.Sleep(time.Millisecond)
}
time.Sleep(5 * time.Second)
}
func runTest(f func(string), arg string) {
f(arg)
}
func testFunc1(addrPassedByValue string) {
fmt.Printf("testFunc1 addrPassedByValue: %s\n", addrPassedByValue)
}
func testFunc2(addr string) {
fmt.Printf("testFunc2 addr: %s\n", addr)
}
func TestEcho(t *testing.T) {
f := func() {
fmt.Println(1)
defer func() { fmt.Println(2) }()
defer func() { fmt.Println(3) }()
}
f()
}
type A struct {
name string
}
func TestEEE(t *testing.T) {
a := &A{name: "charlie"}
f := func(v **A) {
b:=&A{name: "joker"}
*v=b
}
f(&a)
fmt.Println(a.name)
}
|
package mira
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"regexp"
"strings"
)
// Short runes to variablize our types.
const (
submissionType = "s"
subredditType = "b"
commentType = "c"
redditorType = "r"
meType = "m"
)
func (c *Reddit) checkType(rtype ...string) (string, string, error) {
name, ttype := c.getQueue()
if name == "" {
return "", "", fmt.Errorf("identifier is empty")
}
if !findElem(ttype, rtype) {
return "", "", fmt.Errorf(
"the passed type is not a valid type for this call | expected: %s",
strings.Join(rtype, ", "))
}
return name, ttype, nil
}
func (c *Reddit) addQueue(name string, ttype string) *Reddit {
c.Chain <- &ChainVals{Name: name, Type: ttype}
return c
}
func (c *Reddit) getQueue() (string, string) {
if len(c.Chain) < 1 {
return "", ""
}
temp := <-c.Chain
return temp.Name, temp.Type
}
func findElem(elem string, arr []string) bool {
for _, v := range arr {
if elem == v {
return true
}
}
return false
}
// RedditErr is a struct to store reddit error messages.
type RedditErr struct {
Message string `json:"message"`
Error string `json:"error"`
}
func findRedditError(data []byte) error {
object := &RedditErr{}
json.Unmarshal(data, object)
if object.Message != "" || object.Error != "" {
return fmt.Errorf("%s | error code: %s", object.Message, object.Error)
}
return nil
}
// ReadCredsFromFile reads mira credentials from a given file path
func ReadCredsFromFile(file string) Credentials {
// Declare all regexes
ClientID, _ := regexp.Compile(`CLIENT_ID\s*=\s*(.+)`)
ClientSecret, _ := regexp.Compile(`CLIENT_SECRET\s*=\s*(.+)`)
Username, _ := regexp.Compile(`USERNAME\s*=\s*(.+)`)
Password, _ := regexp.Compile(`PASSWORD\s*=\s*(.+)`)
UserAgent, _ := regexp.Compile(`USER_AGENT\s*=\s*(.+)`)
data, err := ioutil.ReadFile(file)
if err != nil {
return Credentials{}
}
s := string(data)
creds := Credentials{
ClientID.FindStringSubmatch(s)[1],
ClientSecret.FindStringSubmatch(s)[1],
Username.FindStringSubmatch(s)[1],
Password.FindStringSubmatch(s)[1],
UserAgent.FindStringSubmatch(s)[1],
}
return creds
}
// ReadCredsFromEnv reads mira credentials from environment
func ReadCredsFromEnv() Credentials {
return Credentials{
os.Getenv("BOT_CLIENT_ID"),
os.Getenv("BOT_CLIENT_SECRET"),
os.Getenv("BOT_USERNAME"),
os.Getenv("BOT_PASSWORD"),
os.Getenv("BOT_USER_AGENT"),
}
}
|
package certificate
import (
"io/ioutil"
"path"
"time"
"github.com/go-acme/lego/v3/certcrypto"
"github.com/urfave/cli/v2"
"github.com/alphatr/acme-lego/common"
"github.com/alphatr/acme-lego/common/bootstrap"
"github.com/alphatr/acme-lego/common/config"
"github.com/alphatr/acme-lego/common/errors"
"github.com/alphatr/acme-lego/model/account"
"github.com/alphatr/acme-lego/model/client"
)
// Renew 续期域名证书
func Renew(ctx *cli.Context) error {
acc, err := account.GetAccount(config.Config.RootDir)
if err != nil {
err := errors.NewError(errors.ConGetAccountErrno, err)
return cli.NewExitError(err.Error(), 401)
}
lego, err := client.NewClient(acc)
if err != nil {
err := errors.NewError(errors.ConInitClientErrno, err)
return cli.NewExitError(err.Error(), 402)
}
hasRenewSuccess := false
domain := ctx.String("domain")
if len(domain) > 0 {
conf, ok := config.Config.DomainGroup[domain]
if !ok {
err := errors.NewError(errors.ConErrorParamErrno, nil, "domain")
return cli.NewExitError(err.Error(), 403)
}
if err := renewDomain(domain, lego, conf); err != nil {
if err.Content.Errno == errors.ConCertRenewIgnoreErrno {
return nil
}
err := errors.NewError(errors.ConCertRenewDomainErrno, err, domain)
return cli.NewExitError(err.Error(), 404)
}
bootstrap.Log.Infof("[success] renew-certificate: %s\n", domain)
} else {
for domain, conf := range config.Config.DomainGroup {
if err := renewDomain(domain, lego, conf); err != nil {
if err.Content.Errno == errors.ConCertRenewIgnoreErrno {
continue
}
err := errors.NewError(errors.ConCertRenewDomainErrno, err, domain)
return cli.NewExitError(err.Error(), 404)
}
hasRenewSuccess = true
bootstrap.Log.Infof("[success] renew-certificate: %s\n", domain)
}
}
if len(config.Config.AfterRenew) > 0 && hasRenewSuccess {
result, err := common.RunCommand(config.Config.AfterRenew)
if err != nil {
return errors.NewError(errors.ConCertRunAfterRenewErrno, err)
}
if result != "" {
bootstrap.Log.Debugf("after-renew-output: %s", result)
}
}
return nil
}
func renewDomain(domain string, cli *client.Client, conf *config.DomainConf) *errors.Error {
for _, keyType := range conf.KeyType {
if err := cli.SetupChallenge(conf.Challenge, domain, conf); err != nil {
return errors.NewError(errors.ConCertSetupChallengeErrno, err)
}
certPath := path.Join(config.Config.RootDir, "certificates", domain)
files := generateFilePath(certPath, keyType)
content, errs := ioutil.ReadFile(files.Cert)
if errs != nil {
return errors.NewError(errors.CommonFileReadErrno, errs, files.Cert)
}
cert, errs := certcrypto.ParsePEMCertificate(content)
if errs != nil {
return errors.NewError(errors.CommonParseCertificateErrno, errs, domain, keyType)
}
if cert.NotAfter.After(time.Now().Add(config.Config.Expires)) {
bootstrap.Log.Debugf("ignore-cert-renew: %s", domain)
return errors.NewError(errors.ConCertRenewIgnoreErrno, nil)
}
privateKey, err := common.LoadPrivateKey(files.Prev)
if err != nil {
return errors.NewError(errors.ConCertLoadPrivateErrno, err, domain, keyType)
}
newCert, err := cli.CertificateObtain(conf.Domains, privateKey)
if err != nil {
return errors.NewError(errors.ConCertObtainErrno, err, domain, keyType)
}
if err := checkFolder(certPath); err != nil {
return errors.NewError(errors.ConCertCheckFolderErrno, err, domain)
}
if err := saveCertRes(newCert, certPath, keyType); err != nil {
return errors.NewError(errors.ConCertSaveCertErrno, err, domain, keyType)
}
}
return nil
}
|
package main
import (
"go.uber.org/zap"
"testing"
)
func TestLogOut(t *testing.T) {
cfg := zap.NewProductionConfig()
cfg.OutputPaths = []string{
"./zap.log",
}
}
func TestLog(t *testing.T) {
//logger, _ := tests.NewProduction() // 生产环境
logger, _ := zap.NewDevelopment() // 开发环境
defer logger.Sync() // flushes buffer, if any
//sugar := logger.Sugar()
//url := "http://localhost:9000"
logger.Info("Failed to fetch URL: %s")
//sugar.Infow("failed to fetch URL",
// // Structured context as loosely typed key-value pairs.
// "url", url,
// "attempt", 3,
// "backoff", time.Second,
//)
//sugar.Infof("Failed to fetch URL: %s", url)
}
|
// Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package autoid_test
import (
"context"
"math"
"testing"
"github.com/pingcap/tidb/meta/autoid"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/parser/terror"
"github.com/pingcap/tidb/store/mockstore"
"github.com/pingcap/tidb/types"
"github.com/stretchr/testify/require"
)
func TestInMemoryAlloc(t *testing.T) {
store, err := mockstore.NewMockStore()
require.NoError(t, err)
defer func() {
err := store.Close()
require.NoError(t, err)
}()
columnInfo := &model.ColumnInfo{
FieldType: types.NewFieldTypeBuilder().SetFlag(mysql.AutoIncrementFlag).Build(),
}
tblInfo := &model.TableInfo{
Columns: []*model.ColumnInfo{columnInfo},
}
alloc := autoid.NewAllocatorFromTempTblInfo(tblInfo)
require.NotNil(t, alloc)
// alloc 1
ctx := context.Background()
id, err := alloc.NextGlobalAutoID()
require.NoError(t, err)
require.Equal(t, int64(1), id)
_, id, err = alloc.Alloc(ctx, 1, 1, 1)
require.NoError(t, err)
require.Equal(t, int64(1), id)
id, err = alloc.NextGlobalAutoID()
require.NoError(t, err)
require.Equal(t, int64(2), id)
_, id, err = alloc.Alloc(ctx, 1, 1, 1)
require.NoError(t, err)
require.Equal(t, int64(2), id)
// alloc N
_, id, err = alloc.Alloc(ctx, 10, 1, 1)
require.NoError(t, err)
require.Equal(t, int64(12), id)
// increment > N
_, id, err = alloc.Alloc(ctx, 1, 10, 1)
require.NoError(t, err)
require.Equal(t, int64(21), id)
// offset
_, id, err = alloc.Alloc(ctx, 1, 1, 30)
require.NoError(t, err)
require.Equal(t, int64(30), id)
// rebase
err = alloc.Rebase(context.Background(), int64(40), true)
require.NoError(t, err)
_, id, err = alloc.Alloc(ctx, 1, 1, 1)
require.NoError(t, err)
require.Equal(t, int64(41), id)
id, err = alloc.NextGlobalAutoID()
require.NoError(t, err)
require.Equal(t, int64(42), id)
err = alloc.Rebase(context.Background(), int64(10), true)
require.NoError(t, err)
_, id, err = alloc.Alloc(ctx, 1, 1, 1)
require.NoError(t, err)
require.Equal(t, int64(42), id)
// maxInt64
err = alloc.Rebase(context.Background(), int64(math.MaxInt64-2), true)
require.NoError(t, err)
_, id, err = alloc.Alloc(ctx, 1, 1, 1)
require.NoError(t, err)
require.Equal(t, int64(math.MaxInt64-1), id)
_, _, err = alloc.Alloc(ctx, 1, 1, 1)
require.True(t, terror.ErrorEqual(err, autoid.ErrAutoincReadFailed))
// test unsigned
columnInfo.FieldType.AddFlag(mysql.UnsignedFlag)
alloc = autoid.NewAllocatorFromTempTblInfo(tblInfo)
require.NotNil(t, alloc)
var n uint64 = math.MaxUint64 - 2
err = alloc.Rebase(context.Background(), int64(n), true)
require.NoError(t, err)
id, err = alloc.NextGlobalAutoID()
require.NoError(t, err)
require.Equal(t, int64(n+1), id)
_, id, err = alloc.Alloc(ctx, 1, 1, 1)
require.NoError(t, err)
require.Equal(t, int64(n+1), id)
_, _, err = alloc.Alloc(ctx, 1, 1, 1)
require.True(t, terror.ErrorEqual(err, autoid.ErrAutoincReadFailed))
// test initial base
tblInfo.AutoIncID = 100
alloc = autoid.NewAllocatorFromTempTblInfo(tblInfo)
require.NotNil(t, alloc)
id, err = alloc.NextGlobalAutoID()
require.NoError(t, err)
require.Equal(t, int64(100), id)
_, id, err = alloc.Alloc(ctx, 1, 1, 1)
require.NoError(t, err)
require.Equal(t, int64(100), id)
}
|
package s3remote
import (
"io"
"path"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/external"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
type S3RemoteStore struct {
Bucket string
Root string
client *s3.S3
cfg *aws.Config
}
func (store *S3RemoteStore) GetMeta(name string) (stream io.ReadCloser, size int64, err error) {
key := path.Join(store.Root, name)
input_ := &s3.GetObjectInput{
Bucket: &store.Bucket,
Key: &key,
}
req := store.client.GetObjectRequest(input_)
output_, err := req.Send()
if err != nil {
return
}
return output_.Body, *output_.ContentLength, nil
}
func (store *S3RemoteStore) GetTarget(name string) (stream io.ReadCloser, size int64, err error) {
key := path.Join(store.Root, "targets", name)
input_ := &s3.GetObjectInput{
Bucket: &store.Bucket,
Key: &key,
}
req := store.client.GetObjectRequest(input_)
output_, err := req.Send()
if err != nil {
return nil, 0, err
}
return output_.Body, *output_.ContentLength, nil
}
func New(bucket string, rootKey string, cfg *aws.Config) (store *S3RemoteStore, err error) {
if cfg == nil {
newConfig, err := external.LoadDefaultAWSConfig()
if err != nil {
return nil, err
}
cfg = &newConfig
}
client := s3.New(*cfg)
return &S3RemoteStore{
Bucket: bucket,
Root: rootKey,
client: client,
cfg: cfg,
}, nil
}
|
package database
import (
"context"
"errors"
"github.com/anshap1719/authentication/models"
"github.com/gofrs/uuid"
"github.com/mrjones/oauth"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"time"
)
var ErrTwitterAccountNotFound = errors.New("No TwitterAccount found in the database")
var ErrTwitterConnectionNotFound = errors.New("No TwitterConnection found in the database")
var ErrTwitterRegisterNotFound = errors.New("No TwitterRegister found in the database")
type TwitterRegister struct {
TwitterID string `bson:"facebookId"`
ID uuid.UUID `bson:"id"`
TimeCreated time.Time `bson:"timeCreated"`
}
type TwitterConnection struct {
MergeToken uuid.UUID `bson:"mergeToken"`
Purpose int `bson:"purpose"`
State uuid.UUID `bson:"state"`
TimeCreated time.Time `bson:"timeCreated"`
}
type TwitterAccount struct {
ID string `bson:"id"`
UserID string `bson:"userId"`
}
func CreateTwitterAccount(ctx context.Context, newTwitterAccount *TwitterAccount) (err error) {
if _, err := models.TwitterAccountCollection.InsertOne(ctx, newTwitterAccount); err != nil {
return err
}
return nil
}
func GetTwitterAccount(ctx context.Context, ID string) (*TwitterAccount, error) {
var fb TwitterAccount
res := models.TwitterAccountCollection.FindOne(ctx, bson.M{"id": ID})
if res.Err() == mongo.ErrNoDocuments {
return nil, ErrTwitterAccountNotFound
} else if res.Err() != nil {
return nil, res.Err()
}
if err := res.Decode(&fb); err != nil {
return nil, err
}
return &fb, nil
}
func DeleteTwitterAccount(ctx context.Context, ID string) error {
_, err := models.TwitterAccountCollection.DeleteOne(ctx, bson.M{"id": ID})
return err
}
func QueryTwitterAccountUser(ctx context.Context, UserID string) (string, error) {
var fb TwitterAccount
res := models.TwitterAccountCollection.FindOne(ctx, bson.M{"userId": UserID})
if res.Err() == mongo.ErrNoDocuments {
return "", ErrTwitterAccountNotFound
} else if res.Err() != nil {
return "", res.Err()
}
if err := res.Decode(&fb); err != nil {
return "", err
}
return fb.ID, nil
}
func CreateTwitterConnection(ctx context.Context, newTwitterConnection *TwitterConnection) (State uuid.UUID, err error) {
uid, err := uuid.NewV4()
if err != nil {
return uuid.Nil, err
}
newTwitterConnection.State = uid
if _, err := models.TwitterConnectionCollection.InsertOne(ctx, newTwitterConnection); err != nil {
return uuid.Nil, err
}
return uid, nil
}
func GetTwitterConnection(ctx context.Context, State uuid.UUID) (*TwitterConnection, error) {
var fb TwitterConnection
res := models.TwitterConnectionCollection.FindOne(ctx, bson.M{"state": State})
if res.Err() == mongo.ErrNoDocuments {
return nil, ErrTwitterConnectionNotFound
} else if res.Err() != nil {
return nil, res.Err()
}
if err := res.Decode(&fb); err != nil {
return nil, err
}
return &fb, nil
}
func DeleteTwitterConnection(ctx context.Context, State uuid.UUID) error {
_, err := models.TwitterConnectionCollection.DeleteOne(ctx, bson.M{"state": State})
return err
}
func CreateTwitterRegister(ctx context.Context, newTwitterRegister *TwitterRegister) (ID uuid.UUID, err error) {
uid, err := uuid.NewV4()
if err != nil {
return uuid.Nil, err
}
newTwitterRegister.ID = uid
if _, err := models.TwitterRegisterCollection.InsertOne(ctx, newTwitterRegister); err != nil {
return uuid.Nil, err
}
return uid, nil
}
func GetTwitterRegister(ctx context.Context, ID uuid.UUID) (*TwitterRegister, error) {
var fb TwitterRegister
res := models.TwitterRegisterCollection.FindOne(ctx, bson.M{"id": ID})
if res.Err() == mongo.ErrNoDocuments {
return nil, ErrTwitterRegisterNotFound
} else if res.Err() != nil {
return nil, res.Err()
}
if err := res.Decode(&fb); err != nil {
return nil, err
}
return &fb, nil
}
func DeleteTwitterRegister(ctx context.Context, ID uuid.UUID) error {
_, err := models.TwitterRegisterCollection.DeleteOne(ctx, bson.M{"id": ID})
return err
}
func GetTwitterToken(key string) (*oauth.RequestToken, error) {
var token struct {
Key string
Token oauth.RequestToken
}
ctx := context.TODO()
res := models.TwitterTokenCollection.FindOne(ctx, bson.M{"key": key})
if res.Err() != nil {
return nil, res.Err()
}
if err := res.Decode(&token); err != nil {
return nil, err
}
return &token.Token, nil
}
func CreateTwitterToken(key string, token oauth.RequestToken) error {
var t = struct {
Key string
Token oauth.RequestToken
}{
Key: key,
Token: token,
}
ctx := context.TODO()
_, err := models.TwitterTokenCollection.InsertOne(ctx, &t)
return err
}
func DeleteTwitterToken(key string) error {
ctx := context.TODO()
_, err := models.TwitterTokenCollection.DeleteOne(ctx, bson.M{"key": key})
return err
}
|
package controller
import (
"github.com/gin-gonic/gin"
"net/http"
"ginTest/model"
"strconv"
)
func GetBillList(c *gin.Context) {
order, err := model.FindAllBill()
if err!=nil{
c.JSON(http.StatusOK,gin.H{
"msg":"not find",
})
}
c.HTML(http.StatusOK,"billList.html",gin.H{
"data":order,
})
}
func GetBillAdd(c *gin.Context) {
c.HTML(http.StatusOK,"billAdd.html",nil)
}
func GetBillUpdate(c *gin.Context) {
orderId:=c.Param("orderId")
order, err := model.FindOneBill(orderId)
if err!=nil{
c.JSON(http.StatusOK,gin.H{
"msg":"find failed",
})
}
c.HTML(http.StatusOK,"billUpdate.html",gin.H{
"data":order,
})
}
func GetMoreBill(c *gin.Context) {
goodsName:=c.Query("goods_name")
supplier:=c.Query("supplier_name")
payStatus:=c.Query("pay_status")
py,_:=strconv.Atoi(payStatus)
order, err := model.FindMoreBill(goodsName, supplier, py)
if err!=nil{
c.JSON(http.StatusBadRequest,gin.H{
"error":"not find",
})
}
c.String(http.StatusOK,"data",order)
}
func PostBillAdd(c *gin.Context) {
var (
order model.Orders
err error
)
if err=c.ShouldBind(&order);err!=nil{
c.JSON(http.StatusBadRequest,gin.H{
"error":"json invalid failed",
})
}
if n:=model.FindSameOrderCode(order.OrderCode);n!=0{
c.JSON(http.StatusBadRequest,gin.H{
"error":"not sane orderCode",
})
return
}
if err=model.AddOrders(order);err!=nil{
c.JSON(http.StatusBadRequest,gin.H{
"error":"add failed!",
})
}else {
c.JSON(http.StatusOK,gin.H{
"msg":"add success!",
})
}
}
func GetBillOneView(c *gin.Context) {
orderId:=c.Param("orderId")
order, err := model.FindOneBill(orderId)
if err!=nil{
c.JSON(http.StatusOK,gin.H{
"msg":"find failed",
})
}
c.HTML(http.StatusOK,"billView.html",gin.H{
"data":order,
})
}
func UpdateBillOneView(c *gin.Context){
orderId:=c.Param("orderId")
order, err := model.UpdateOneBill(orderId)
if err!=nil{
c.JSON(http.StatusOK,gin.H{
"error":"modify failed",
})
}else{
c.ShouldBindJSON(&order)
if err:=model.SaveOneBill(order);err!=nil{
c.JSON(http.StatusOK,gin.H{
"error":"save failed",
})
}
c.JSON(http.StatusOK,gin.H{
"msg":"modify success",
})
}
}
func DeleteBillOneView(c *gin.Context){
orderId:=c.Param("orderId")
if err := model.DeleteOneBill(orderId);err!=nil{
c.JSON(http.StatusOK,gin.H{
"msg":"delete failed",
})
}else{
c.JSON(http.StatusOK,gin.H{
"msg":"delete success",
})
}
} |
package main
import "fmt"
func main() {
var dazed = map[string]bool{
"Calisca": true,
"Heodan": true,
}
if dazed["Calisca"] {
fmt.Println("Calisca is dazed.")
}
// an empty struct as a sentinel
var charmed = map[string]struct{}{
"Calisca": struct{}{},
}
if _, ok := charmed["Heodan"]; ok {
fmt.Println("Heodan is charmed.")
}
}
|
package log
import (
"filemanager/constant"
"fmt"
"os"
"github.com/sirupsen/logrus"
)
// Log はログの本体です
var Log = logrus.New()
// SetLog はログの設定を行います。
func SetLog() {
if _, err := os.Stat(constant.LogFileName); err == nil {
err = os.Remove(constant.LogFileName)
}
errorLogFile, err := os.OpenFile(constant.LogFileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
panic(fmt.Sprintf("[Error]: %s", err))
}
Log.Out = errorLogFile
}
|
package client
import (
"errors"
"fmt"
"github.com/imroc/req"
)
func (c *AppDClient) CreateHealthRule(healthRule *HealthRule, applicationId int) (*HealthRule, error) {
resp, err := req.Post(c.createHealthRulesUrl(applicationId), c.createAuthHeader(), req.BodyJSON(&healthRule))
if err != nil {
return nil, err
}
if resp.Response().StatusCode != 201 {
respString, _ := resp.ToString()
return nil, errors.New(fmt.Sprintf("Error creating Health Rule: %d, %s", resp.Response().StatusCode, respString))
}
updated := HealthRule{}
err = resp.ToJSON(&updated)
if err != nil {
return nil, err
}
return &updated, nil
}
func (c *AppDClient) UpdateHealthRule(healthRule *HealthRule, applicationId int) (*HealthRule, error) {
resp, err := req.Put(c.createHealthRuleUrl(healthRule.ID, applicationId), c.createAuthHeader(), req.BodyJSON(&healthRule))
if err != nil {
return nil, err
}
if resp.Response().StatusCode != 200 {
respString, _ := resp.ToString()
return nil, errors.New(fmt.Sprintf("Error updating Health Rule: %d, %s", resp.Response().StatusCode, respString))
}
updated := HealthRule{}
err = resp.ToJSON(&updated)
if err != nil {
return nil, err
}
return &updated, nil
}
func (c *AppDClient) DeleteHealthRule(applicationId int, healthRuleId int) error {
_, err := req.Delete(c.createHealthRuleUrl(healthRuleId, applicationId), c.createAuthHeader())
if err != nil {
return err
}
return nil
}
func (c *AppDClient) GetHealthRule(healthRuleId int, applicationId int) (*HealthRule, error) {
resp, err := req.Get(c.createHealthRuleUrl(healthRuleId, applicationId), c.createAuthHeader())
if err != nil {
return nil, err
}
if resp.Response().StatusCode != 200 {
respString, _ := resp.ToString()
return nil, errors.New(fmt.Sprintf("Error getting Health TransactionRule: %d, %s, %s", resp.Response().StatusCode, c.createHealthRuleUrl(healthRuleId, applicationId), respString))
}
updated := HealthRule{}
err = resp.ToJSON(&updated)
if err != nil {
return nil, err
}
return &updated, nil
}
func (c *AppDClient) createHealthRulesUrl(applicationId int) string {
return fmt.Sprintf("%s/%s", c.createUrl(applicationId), "health-rules")
}
func (c *AppDClient) createHealthRuleUrl(healthRuleId int, applicationId int) string {
return fmt.Sprintf("%s/%d", c.createHealthRulesUrl(applicationId), healthRuleId)
}
type HealthRule struct {
ID int `json:"id"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
UseDataFromLastNMinutes int `json:"useDataFromLastNMinutes"`
WaitTimeAfterViolation int `json:"waitTimeAfterViolation"`
Affects *Affects `json:"affects"`
Criterias *Criterias `json:"evalCriterias"`
}
type Criterias struct {
Critical *Criteria `json:"criticalCriteria"`
Warning *Criteria `json:"warningCriteria"`
}
type Criteria struct {
ConditionAggregationType string `json:"conditionAggregationType"`
Conditions []*Condition `json:"conditions"`
}
type Condition struct {
Name string `json:"name"`
ShortName string `json:"shortName"`
EvaluateToTrueOnNoData bool `json:"evaluateToTrueOnNoData"`
EvalDetail *EvalDetail `json:"evalDetail"`
}
type EvalDetail struct {
EvalDetailType string `json:"evalDetailType"`
MetricAggregateFunction string `json:"metricAggregateFunction"`
MetricPath string `json:"metricPath"`
MetricEvalDetail *MetricEvalDetail `json:"metricEvalDetail"`
}
type MetricEvalDetail struct {
MetricEvalDetailType string `json:"metricEvalDetailType"`
BaselineCondition *string `json:"baselineCondition"`
BaselineName *string `json:"baselineName"`
BaselineUnit *string `json:"baselineUnit"`
CompareValue float64 `json:"compareValue"`
CompareCondition *string `json:"compareCondition"`
}
type Affects struct {
AffectedEntityType string `json:"affectedEntityType"`
AffectedBusinessTransactions *Transaction `json:"affectedBusinessTransactions"`
}
type Transaction struct {
BusinessTransactionScope string `json:"businessTransactionScope"`
BusinessTransactions *[]interface{} `json:"businessTransactions"`
SpecificTiers *[]interface{} `json:"specificTiers"`
}
|
package game
import "go-mod/util"
// Draw function draws the updated pixels of Paddle to the screen as texture
func (p *Paddle) Draw(pixels []byte) {
startX, startY := p.X-p.W/2, p.Y-p.H/2
for y := 0; y < int(p.H); y++ {
for x := 0; x < int(p.W); x++ {
SetPixel(startX+float32(x), startY+float32(y), p.Color, pixels)
}
}
numX := util.Lerp(p.X, GetCenter().X, 0.2)
DrawNumber(Pos{numX, 35}, p.Color, 10, p.Score, pixels)
}
// Draw function draws the updated pixels of Ball to the screen as texture
func (b *Ball) Draw(pixels []byte) {
for y := -b.Radius; y < b.Radius; y++ {
for x := -b.Radius; x < b.Radius; x++ {
if x*x+y*y < b.Radius*b.Radius {
SetPixel(b.X+x, b.Y+y, b.Color, pixels)
}
}
}
}
|
// Copyright 2019 The OpenSDS Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package targets
import (
"bytes"
"errors"
"io"
"os"
"os/exec"
"strings"
log "github.com/golang/glog"
"github.com/sodafoundation/dock/pkg/utils"
)
const (
opensdsNvmeofPrefix = "opensds-Nvmeof"
NvmetDir = "/sys/kernel/config/nvmet"
)
type NvmeofTarget interface {
AddNvmeofSubsystem(volId, tgtNqn, path, initiator string) (string, error)
RemoveNvmeofSubsystem(volId, nqn string) error
GetNvmeofSubsystem(nqn string) (string, error)
CreateNvmeofTarget(volId, tgtIqn, path, initiator, transtype string) error
GetNvmeofTarget(nqn, transtype string) (bool, error)
RemoveNvmeofTarget(volId, nqn, transtype string) error
}
func NewNvmeofTarget(bip, tgtConfDir string) NvmeofTarget {
return &NvmeoftgtTarget{
TgtConfDir: tgtConfDir,
BindIp: bip,
}
}
type NvmeoftgtTarget struct {
BindIp string
TgtConfDir string
}
func (t *NvmeoftgtTarget) init() {
t.execCmd("modprobe", "nvmet")
t.execCmd("modprobe", "nvmet-rdma")
t.execCmd("modprobe", "nvmet-tcp")
t.execCmd("modprobe", "nvmet-fc")
}
func (t *NvmeoftgtTarget) getTgtConfPath(volId string) string {
return NvmetDir + "/" + opensdsNvmeofPrefix + volId
}
func (t *NvmeoftgtTarget) convertTranstype(transtype string) string {
var portid string
switch transtype {
case "fc":
portid = "3"
case "rdma":
portid = "2"
default:
portid = "1"
log.Infof("default nvmeof transtype : tcp")
}
return portid
}
func (t *NvmeoftgtTarget) AddNvmeofSubsystem(volId, tgtNqn, path, initiator string) (string, error) {
if exist, _ := utils.PathExists(NvmetDir); !exist {
os.MkdirAll(NvmetDir, 0755)
}
sysdir := NvmetDir + "/subsystems/" + tgtNqn
if exist, _ := utils.PathExists(sysdir); !exist {
os.MkdirAll(sysdir, 0755)
}
var err error
if initiator == "ALL" {
// echo 1 > attr_allow_any_host
attrfile := sysdir + "/attr_allow_any_host"
content := "1"
err = t.WriteWithIo(attrfile, content)
if err != nil {
log.Errorf("can not set attr_allow_any_host ")
t.RemoveNvmeofSubsystem(volId, tgtNqn)
return "", err
}
} else {
// allow specific initiators to connect to this target
var initiatorInfo = initiator
hostpath := NvmetDir + "/hosts"
if exist, _ := utils.PathExists(hostpath); !exist {
os.MkdirAll(hostpath, 0755)
}
hostDir := hostpath + "/" + initiatorInfo
if exist, _ := utils.PathExists(hostDir); !exist {
os.MkdirAll(hostDir, 0755)
}
// create symbolic link of host
hostsys := sysdir + "/allowed_hosts/"
_, err = t.execCmd("ln", "-s", hostDir, hostsys)
if err != nil {
log.Errorf("Fail to create host link: " + initiatorInfo)
t.RemoveNvmeofSubsystem(volId, tgtNqn)
return "", err
}
}
// get volume namespaceid
namespaceid := t.Getnamespaceid(volId)
if namespaceid == "" {
t.RemoveNvmeofSubsystem(volId, tgtNqn)
return "", errors.New("null namesapce")
}
namespace := sysdir + "/namespaces/" + namespaceid
if exist, _ := utils.PathExists(namespace); !exist {
os.MkdirAll(namespace, 0755)
}
// volid as device path
devpath := namespace + "/device_path"
err = t.WriteWithIo(devpath, path)
if err != nil {
log.Errorf("Fail to set device path")
t.RemoveNvmeofSubsystem(volId, tgtNqn)
return "", err
}
enablepath := namespace + "/enable"
err = t.WriteWithIo(enablepath, "1")
if err != nil {
log.Errorf("Fail to set device path")
t.RemoveNvmeofSubsystem(volId, tgtNqn)
return "", err
}
log.Infof("new added subsys : %s", sysdir)
return sysdir, nil
}
func (t *NvmeoftgtTarget) GetNvmeofSubsystem(nqn string) (string, error) {
subsysdir := NvmetDir + "/subsystems/" + nqn
if _, err := os.Stat(subsysdir); err == nil {
return subsysdir, nil
} else if os.IsNotExist(err) {
return "", nil
} else {
log.Errorf("can not get nvmeof subsystem")
return "", err
}
}
func (t *NvmeoftgtTarget) CreateNvmeofTarget(volId, tgtNqn, path, initiator, transtype string) error {
if tgtexisted, err := t.GetNvmeofTarget(tgtNqn, transtype); tgtexisted == true && err == nil {
log.Infof("Nvmeof target %s with transtype %s has existed", tgtNqn, transtype)
return nil
} else if err != nil {
log.Errorf("can not get nvmeof target %s with transport type %s", tgtNqn, transtype)
return err
}
var subexisted string
subexisted, err := t.GetNvmeofSubsystem(tgtNqn)
if err != nil {
log.Errorf("can not get nvmeof subsystem %s ", tgtNqn)
return err
} else if subexisted == "" {
log.Infof("add new nqn subsystem %s", tgtNqn)
subexisted, err = t.AddNvmeofSubsystem(volId, tgtNqn, path, initiator)
log.Infof("new subdir: %s", subexisted)
} else {
log.Infof("%s subsystem has existed", tgtNqn)
}
subexisted = NvmetDir + "/subsystems/" + tgtNqn
log.Infof("new subdir: %s", subexisted)
// subexisted, err = t.GetNvmeofSubsystem(tgtNqn)
// log.Infof("new subdir: %s ", subexisted)
// if subexisted == "" {
// log.Infof("still no subsystem after add new subsystem")
// //t.RemoveNvmeofSubsystem(volId, tgtNqn)
// return errors.New("still can not get subsystem after add new one")
// }
//
//create port
portid := t.convertTranstype(transtype)
portspath := NvmetDir + "/ports/" + portid
if exist, _ := utils.PathExists(portspath); !exist {
//log.Errorf(portspath)
os.MkdirAll(portspath, 0755)
}
// get target ip
// here the ip should be the ip interface of the specific nic
// for example, if transport type is rdma, then the rdma ip should be used.
// here just set the generic ip address since tcp is the default choice.
ippath := portspath + "/addr_traddr"
ip, err := t.execCmd("hostname", "-I")
if err != nil {
log.Errorf("fail to get target ipv4 address")
t.RemoveNvmeofTarget(volId, tgtNqn, transtype)
return err
}
ip = strings.Split(ip, " ")[0]
err = t.WriteWithIo(ippath, ip)
if err != nil {
log.Errorf("Fail to set target ip")
t.RemoveNvmeofTarget(volId, tgtNqn, transtype)
return err
}
trtypepath := portspath + "/addr_trtype"
err = t.WriteWithIo(trtypepath, transtype)
if err != nil {
log.Errorf("Fail to set transport type")
t.RemoveNvmeofTarget(volId, tgtNqn, transtype)
return err
}
trsvcidpath := portspath + "/addr_trsvcid"
err = t.WriteWithIo(trsvcidpath, "4420")
if err != nil {
log.Errorf("Fail to set ip port")
t.RemoveNvmeofTarget(volId, tgtNqn, transtype)
return err
}
adrfampath := portspath + "/addr_adrfam"
err = t.WriteWithIo(adrfampath, "ipv4")
if err != nil {
log.Errorf("Fail to set ip family")
t.RemoveNvmeofTarget(volId, tgtNqn, transtype)
return err
}
// create a soft link
portssub := portspath + "/subsystems/" + tgtNqn
_, err = t.execCmd("ln", "-s", subexisted, portssub)
if err != nil {
log.Errorf("Fail to create link")
t.RemoveNvmeofTarget(volId, tgtNqn, transtype)
return err
}
// check
info, err := t.execBash("dmesg | grep 'enabling port' ")
if err != nil || info == "" {
log.Errorf("nvme target is not listening on the port")
t.RemoveNvmeofTarget(volId, tgtNqn, transtype)
return err
}
log.Info("create nvme target")
return nil
}
func (t *NvmeoftgtTarget) GetNvmeofTarget(nqn, transtype string) (bool, error) {
portid := t.convertTranstype(transtype)
targetlinkpath := NvmetDir + "/ports/" + portid + "/subsystems/" + nqn
if _, err := os.Lstat(targetlinkpath); err == nil {
return true, nil
} else if os.IsNotExist(err) {
return false, nil
} else {
log.Errorf("can not get nvmeof target")
return false, err
}
}
func (t *NvmeoftgtTarget) RemoveNvmeofSubsystem(volId, nqn string) error {
log.Info("removing subsystem", nqn)
tgtConfPath := NvmetDir + "/subsystems/" + nqn
if exist, _ := utils.PathExists(tgtConfPath); !exist {
log.Warningf("Volume path %s does not exist, nothing to remove.", tgtConfPath)
return nil
}
// remove namespace, whether it succeed or not, the removement should be executed.
ns := t.Getnamespaceid(volId)
if ns == "" {
log.Infof("can not find volume %s's namespace", volId)
// return errors.New("null namespace")
}
naspPath := NvmetDir + "/subsystems/" + nqn + "/namespaces/" + ns
info, err := t.execCmd("rmdir", naspPath)
if err != nil {
log.Infof("can not rm nasp")
// return err
}
// remove namespaces ; if it allows all initiators ,then this dir should be empty
// if it allow specific hosts ,then here remove all the hosts
cmd := "rm -f " + NvmetDir + "/subsystems/" + nqn + "/allowed_hosts/" + "*"
info, err = t.execBash(cmd)
if err != nil {
log.Infof("can not rm allowed hosts")
log.Infof(info)
// return err
}
// remove subsystem
syspath := NvmetDir + "/subsystems/" + nqn
info, err = t.execCmd("rmdir", syspath)
if err != nil {
log.Infof("can not rm subsys")
return err
}
return nil
}
func (t *NvmeoftgtTarget) RemoveNvmeofPort(nqn, transtype string) error {
log.Infof("removing nvmeof port %s", transtype)
portid := t.convertTranstype(transtype)
portpath := NvmetDir + "/ports/" + portid + "/subsystems/" + nqn
// port's link has to be removed first or the subsystem cannot be removed
tgtConfPath := NvmetDir + "/subsystems/" + nqn
if exist, _ := utils.PathExists(tgtConfPath); !exist {
log.Warningf("Volume path %s does not exist, nothing to remove.", tgtConfPath)
return nil
}
info, err := t.execCmd("rm", "-f", portpath)
if err != nil {
log.Errorf("can not rm nvme port transtype: %s, nqn: %s", transtype, nqn)
log.Errorf(info)
return err
}
return nil
}
func (t *NvmeoftgtTarget) RemoveNvmeofTarget(volId, nqn, transtype string) error {
log.Infof("removing target %s", nqn)
if tgtexisted, err := t.GetNvmeofTarget(nqn, transtype); err != nil {
log.Errorf("can not get nvmeof target %s with type %s", nqn, transtype)
return err
} else if tgtexisted == false {
log.Infof("nvmeof target %s with type %s does not exist", nqn, transtype)
} else {
err = t.RemoveNvmeofPort(nqn, transtype)
if err != nil {
return err
}
}
if subexisted, err := t.GetNvmeofSubsystem(nqn); err != nil {
log.Errorf("can not get nvmeof subsystem %s ", nqn)
return err
} else if subexisted == "" {
log.Errorf("subsystem %s does not exist", nqn)
return nil
} else {
err = t.RemoveNvmeofSubsystem(volId, nqn)
if err != nil {
log.Errorf("can not remove nvme subsystem %s", nqn)
return err
}
}
return nil
}
func (*NvmeoftgtTarget) execCmd(name string, cmd ...string) (string, error) {
ret, err := exec.Command(name, cmd...).Output()
if err != nil {
log.Errorf("error info: %v", err)
}
return string(ret), err
}
func (*NvmeoftgtTarget) execBash(name string) (string, error) {
ret, err := exec.Command("/bin/sh", "-c", name).Output()
if err != nil {
log.Errorf("error info in sh %v ", err)
}
return string(ret), err
}
func (*NvmeoftgtTarget) WriteWithIo(name, content string) error {
fileObj, err := os.OpenFile(name, os.O_RDWR, 0644)
if err != nil {
log.Errorf("Failed to open the file %v", err)
return err
}
if _, err := io.WriteString(fileObj, content); err == nil {
log.Infof("Successful appending to the file with os.OpenFile and io.WriteString.%s", content)
return nil
}
return err
}
func (t *NvmeoftgtTarget) Getnamespaceid(volId string) string {
var buffer bytes.Buffer
for _, rune := range volId {
// nvme target namespace dir should not be like 00 or 0 ,
// so only digits range from 1 to 9 are accepted
if rune >= '1' && rune <= '9' {
buffer.WriteRune(rune)
}
}
return buffer.String()[0:2]
}
|
package day1119test
import "strings"
/*
Go语言中的测试依赖go test命令,编写测试代码和编写普通的Go代码过程是类似的,不需要学习新的语法、规则或工具
在包目录内,所有以_test.go为后缀名的源代码文件都是go test测试的一部分,不会被go build编译到最终的可执行文件中去
在*_test.go文件中有三种类型的函数,单元测试函数、基准测试函数和示例函数
类型 格式 作用
测试函数 函数名前缀为Test 测试程序的一些逻辑行为是否正确
基准函数 函数名前缀为Benchmark 测试函数的性能
示例函数 函数名前缀为Example 为文档提供示例文档
测试函数:必须导入testing包
格式 func TestName(t *testing.T){}
测试函数的名字必须以Test开头,可选的后缀名必须以大写字母开头,其中参数t用于报告测试失败和附加的日志信息
基准函数
在一定的工作负载之下检测程序性能的一种方法,基本格式如下
func BenchmarkName(b *testing.B){
//
}
以Benchmark为前缀,需要一个*testing.B类型的参数b,基准测试必须要执行b.N次,这样的测试
才有对照性
示例函数
它们的函数是以Example为前缀,它们既没有参数也没有返回值
格式如下
func ExampleName(){}
*/
func Split(s, sep string) (result []string) {
i := strings.Index(s, sep)
for i > -1 {
result = append(result, s[:i])
s = s[i+len(sep):]
i = strings.Index(s, sep)
}
result = append(result, s)
return
}
|
package inspect
import (
"github.com/spf13/cobra"
kumactl_cmd "github.com/kumahq/kuma/app/kumactl/pkg/cmd"
"github.com/kumahq/kuma/app/kumactl/pkg/output"
kuma_cmd "github.com/kumahq/kuma/pkg/cmd"
)
func NewInspectCmd(pctx *kumactl_cmd.RootContext) *cobra.Command {
inspectCmd := &cobra.Command{
Use: "inspect",
Short: "Inspect Kuma resources",
Long: `Inspect Kuma resources.`,
}
inspectCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
if err := kumactl_cmd.RunParentPreRunE(inspectCmd, args); err != nil {
return err
}
if err := pctx.CheckServerVersionCompatibility(); err != nil {
cmd.PrintErrln(err)
}
return nil
}
// flags
inspectCmd.PersistentFlags().StringVarP(&pctx.InspectContext.Args.OutputFormat, "output", "o", string(output.TableFormat), kuma_cmd.UsageOptions("output format", output.TableFormat, output.YAMLFormat, output.JSONFormat))
// sub-commands
inspectCmd.AddCommand(newInspectDataplanesCmd(pctx))
inspectCmd.AddCommand(newInspectZoneIngressesCmd(pctx))
inspectCmd.AddCommand(newInspectZonesCmd(pctx))
inspectCmd.AddCommand(newInspectMeshesCmd(pctx))
inspectCmd.AddCommand(newInspectServicesCmd(pctx))
return inspectCmd
}
|
package remento
import (
"github.com/fncodr/godbase"
)
type Cx struct {
godbase.BasicCx
Settings Settings
user *User
}
func NewCx(db *Db) *Cx {
return new(Cx).Init(db)
}
func (self *Cx) Init(db *Db) *Cx {
self.BasicCx.Init(db)
self.Settings.Init(self)
return self
}
func (self *Cx) SetUser(u *User) {
self.user = u
}
|
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"sort"
)
type Player struct {
PlayerName string
CountryCode string
Skill int
OverallPoint float64
SelectedPercentage float64
PlayerValue float64
Score float64 `json:"-"`
}
type Data struct {
Value []Player
}
type Response struct {
Data Data
}
const (
SkillGoalkeeper int = 1
SkillDefender int = 2
SkillMidfield int = 3
SkillForward int = 4
)
func printPlayersToCsv(players []Player, fileName string) {
f, err := os.Create(fileName)
if err != nil {
log.Fatal(err)
return
}
defer f.Close()
f.WriteString("PlayerName,CountryCode,Skill,OverallPoint,SelectedPercentage,PlayerValue,Score\n")
for _, p := range players {
s := fmt.Sprintf("%s,%s,%d,%f,%f,%f,%f\n", p.PlayerName, p.CountryCode, p.Skill, p.OverallPoint, p.SelectedPercentage, p.PlayerValue, p.Score)
f.WriteString(s)
}
f.Sync()
}
func main() {
resp, err := http.Get("https://fantasy.fifa.com/services/api/statistics/statsdetail?optType=1&gamedayId=1&language=en&buster=default")
if err != nil {
log.Fatal(err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
return
}
r := &Response{}
err = json.Unmarshal(body, r)
if err != nil {
log.Fatal(err)
return
}
players := r.Data.Value
for i, p := range players {
players[i].Score = p.OverallPoint / p.PlayerValue * p.SelectedPercentage
}
sort.Slice(players, func(i, j int) bool {
if players[i].Score != players[j].Score {
return players[i].Score > players[j].Score
}
return players[i].PlayerValue < players[j].PlayerValue
})
printPlayersToCsv(players, "list.csv")
}
|
package main
import "fmt"
func producer(ch chan int) {
for n := 0; n<10; n++ {
ch<-n
}
close(ch)
}
func main() {
ch := make(chan int)
go producer(ch)
for v := range ch {
fmt.Println("Received", v)
}
}
|
/*
Generate protobuf go firstly by follow command in path igoexample/grpc/load_balancing/pb_echo:
protoc --proto_path=. --go_out=plugins=grpc:. ./*.proto
*/
package main
import (
"context"
"flag"
"github.com/fs714/igoexample/grpc/load_balancing/pb_echo"
"github.com/hashicorp/consul/api"
"github.com/satori/go.uuid"
"google.golang.org/grpc"
"log"
"net"
"os"
"strconv"
)
type EchoServer struct {
Name string
Address string
}
func (es EchoServer) UnaryEcho(ctx context.Context, request *pb_echo.EchoRequest) (reply *pb_echo.EchoReply, err error) {
reply = &pb_echo.EchoReply{Message: "Request: " + request.Message + ", ServerName: " + es.Name + ", ServerAddr: " + es.Address}
return
}
func NewConsulRegistry(addr string) (cr ConsulRegistry, err error) {
cfg := api.DefaultConfig()
cfg.Address = addr
c, err := api.NewClient(cfg)
if err != nil {
return
}
cr.ConsulClient = c
return
}
type ConsulRegistry struct {
ConsulClient *api.Client
}
func (cr *ConsulRegistry) Register(name string, port int) (id string, err error) {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
log.Fatalln("Unable to determine local addr with err: " + err.Error())
return
}
defer func() {
_ = conn.Close()
}()
id = uuid.Must(uuid.NewV1()).String()
localAddr := conn.LocalAddr().(*net.UDPAddr)
reg := &api.AgentServiceRegistration{
ID: id,
Name: name,
Port: port,
Address: localAddr.IP.String(),
}
err = cr.ConsulClient.Agent().ServiceRegister(reg)
return
}
func (cr *ConsulRegistry) Deregister(id string) (err error) {
err = cr.ConsulClient.Agent().ServiceDeregister(id)
return
}
var consulAddr string
var consulPort int
var serviceName string
var servicePort int
func init() {
flag.StringVar(&consulAddr, "ca", "127.0.0.1", "Consul IP address")
flag.IntVar(&consulPort, "cp", 8500, "Consul port")
flag.StringVar(&serviceName, "n", "_grpclb._tcp.echo-server", "RPC service name")
flag.IntVar(&servicePort, "sp", 50051, "RPC service port")
flag.Parse()
}
func main() {
cr, err := NewConsulRegistry(consulAddr + ":" + strconv.Itoa(consulPort))
if err != nil {
log.Fatalf("Failed to new consul registry: %s", err.Error())
os.Exit(0)
}
es := &EchoServer{Name: serviceName, Address: "0.0.0.0:" + strconv.Itoa(servicePort)}
id, err := cr.Register(serviceName, servicePort)
if err != nil {
log.Fatalf("Failed to register service: %s", err.Error())
os.Exit(0)
}
defer func() {
_ = cr.Deregister(id)
}()
lis, err := net.Listen("tcp", es.Address)
if err != nil {
log.Fatalf("failed to listen: %v", err)
os.Exit(0)
}
s := grpc.NewServer()
pb_echo.RegisterEchoServer(s, es)
log.Println("Server " + es.Name + " listen on " + es.Address)
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
|
package main
import (
"bufio"
"fmt"
"math"
"os"
"sort"
"strconv"
"strings"
)
func main() {
s := bufio.NewScanner(os.Stdin)
s.Scan()
t, _ := strconv.Atoi(s.Text())
for i := 0; i < t; i++ {
s.Scan()
n, _ := strconv.Atoi(s.Text())
chocs := make([]int, n)
s.Scan()
for i, v := range strings.Split(s.Text(), " ") {
temp, _ := strconv.Atoi(v)
chocs[i] = temp
}
fmt.Println(mincount(chocs))
}
}
func mincount(n []int) int {
// sort
sort.Ints(n)
// do a diff
diff := make([]int, len(n)-1)
for i := 1; i < len(n); i++ {
// fmt.Println(i)
differ := int(math.Abs(float64(n[i] - n[i-1])))
diff[i-1] = differ
}
var min int
for i := 0; i < len(diff)-1; i++ {
// fmt.Println(diff, i)
if diff[i] > 0 {
// fmt.Println(diff[i+1])
diff[i+1] = diff[i+1] + diff[i]
// fmt.Println("after", diff)
min += getMin(diff[i])
// fmt.Println("min", min)
diff[i] = 0
}
}
// fmt.Println(diff)
last := diff[len(diff)-1]
// fmt.Println("last", last)
min += getMin(last)
return min
}
func getMin(n int) int {
var min int
if n >= 5 {
if n%5 == 0 {
// fmt.Println(n / 5)
return n / 5
} else {
min += n / 5
n = n % 5
}
}
if n%2 == 0 {
min += n / 2
return min
} else {
min += n / 2
min += 1
}
return min
}
|
/*
Many years ago after another unfruitful day in Cubicle Land, banging her head against yet another cutting edge, marketing buzzword-filled JavaScript framework, Janice the engineer looked out of the window and decided that time was ripe for a change.
So swapping her keyboard and mouse for a fork and a spade, she started her own gardening company.
After years of hard outdoor work Janice now has biceps like Van Damme and owns the premiere landscaping company in the whole of the South West, and has just been lucky enough to broker a large contract to sow lawns for landed gentry.
Each contract details the size of the lawns that need to be seeded, and the cost of seed per square metre. How much do you need to spend on seed?
Input
One line containing a real number C (0<C≤100), the cost of seed to sow one square metre of lawn.
One line containing an integer L (0<L≤100), the number of lawns to sow.
L lines, each containing two positive real numbers: wi (0≤wi≤100), the width of the lawn, and li (0≤li≤100), the length of the lawn.
All real numbers are given with at most 8 decimals after the decimal point.
Output
One line containing a real number: the cost to sow all of the lawns.
All output must be accurate to an absolute or relative error of at most 10^-6.
*/
package main
import (
"fmt"
"math"
)
func main() {
test(2, [][2]float64{{2, 3}, {4, 5}, {5, 6}}, 112)
test(0.75, [][2]float64{{2, 3.333}, {3.41, 4.567}}, 16.6796025)
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func test(c float64, l [][2]float64, r float64) {
p := cost(c, l)
fmt.Println(p)
assert(math.Abs(p-r) < 1e-8)
}
func cost(c float64, l [][2]float64) float64 {
r := 0.0
for _, v := range l {
r += c * v[0] * v[1]
}
return r
}
|
package server
import (
"bufio"
"compress/zlib"
"crypto/tls"
"encoding/binary"
"encoding/json"
"errors"
"io"
"log"
"net"
"sync"
"time"
"github.com/urso/go-lumber/v2/protocol"
)
type Server struct {
listener net.Listener
opts options
ch chan *Batch
done chan struct{}
wg sync.WaitGroup
}
type Batch struct {
Events []interface{}
ack chan struct{}
}
type Option func(*options) error
type options struct {
timeout time.Duration
keepalive time.Duration
decoder jsonDecoder
tls *tls.Config
}
type conn struct {
server *Server
c net.Conn
reader *reader
to time.Duration
keepalive time.Duration
signal chan struct{}
ch chan *Batch
}
type reader struct {
in *bufio.Reader
conn net.Conn
buf []byte
opts options
}
type jsonDecoder func([]byte, interface{}) error
var (
// ErrProtocolError is returned if an protocol error was detected in the
// conversation with lumberjack server.
ErrProtocolError = errors.New("lumberjack protocol error")
)
func JSONDecoder(decoder func([]byte, interface{}) error) Option {
return func(opt *options) error {
opt.decoder = decoder
return nil
}
}
func Keepalive(kl time.Duration) Option {
return func (opt *options) error {
if kl < 0 {
return errors.New("keepalive must not be negative")
}
opt.keepalive = kl
return nil;
}
}
func Timeout(to time.Duration) Option {
return func(opt *options) error {
if to < 0 {
return errors.New("timeouts must not be negative")
}
opt.timeout = to
return nil
}
}
func TLS(tls *tls.Config) Option {
return func(opt *options) error {
opt.tls = tls
return nil
}
}
func applyOptions(opts []Option) (options, error) {
o := options{
decoder: json.Unmarshal,
timeout: 30 * time.Second,
keepalive: 3 * time.Second,
tls: nil,
}
for _, opt := range opts {
if err := opt(&o); err != nil {
return o, err
}
}
return o, nil
}
func (b *Batch) ACK() {
close(b.ack)
}
func NewWithListener(l net.Listener, opts ...Option) (*Server, error) {
o, err := applyOptions(opts)
if err != nil {
return nil, err
}
s := &Server{
listener: l,
done: make(chan struct{}),
ch: make(chan *Batch, 128),
opts: o,
}
s.wg.Add(1)
go s.run()
return s, nil
}
func ListenAndServeWith(
binder func(network, addr string) (net.Listener, error),
addr string,
opts ...Option,
) (*Server, error) {
l, err := binder("tcp", addr)
if err != nil {
return nil, err
}
return NewWithListener(l, opts...)
}
func ListenAndServe(addr string, opts ...Option) (*Server, error) {
binder := net.Listen
o, err := applyOptions(opts)
if err != nil {
return nil, err
}
if o.tls != nil {
binder = func(network, addr string) (net.Listener, error) {
return tls.Listen(network, addr, o.tls)
}
}
return ListenAndServeWith(binder, addr, opts...)
}
func (s *Server) Close() error {
close(s.done)
err := s.listener.Close()
s.wg.Wait()
close(s.ch)
return err
}
func (s *Server) Receive() *Batch {
select {
case <-s.done:
return nil
case b := <-s.ch:
return b
}
}
func (s *Server) ReceiveChan() <-chan *Batch {
return s.ch
}
func (s *Server) run() {
defer s.wg.Done()
for {
client, err := s.listener.Accept()
if err != nil {
break
}
log.Printf("New connection from %v", client.RemoteAddr())
conn := newConn(s, client, s.opts.timeout, s.opts.keepalive)
s.wg.Add(1)
go conn.run()
}
}
func newConn(server *Server, c net.Conn, to, keepalive time.Duration) *conn {
conn := &conn{
server: server,
c: c,
to: to,
keepalive: keepalive,
reader: newReader(c, server.opts),
signal: make(chan struct{}),
ch: make(chan *Batch),
}
return conn
}
func (c *conn) run() {
go func() {
defer c.server.wg.Done()
defer close(c.ch)
defer close(c.signal)
if err := c.handle(); err != nil {
log.Print(err)
}
}()
go c.ackLoop()
select {
case <-c.signal: // client connection closed
log.Printf("handle close signal")
case <-c.server.done: // handle server shutdown
log.Printf("handle server shutdown")
}
_ = c.c.Close()
}
func (c *conn) handle() error {
log.Printf("Start client handler")
defer log.Printf("Stop client handler")
for {
// 1. read data into batch
b, err := c.reader.readBatch()
if err != nil {
return err
}
// read next batch if empty batch has been received
if b == nil {
continue
}
// 2. push batch to ACK queue
select {
case <-c.server.done:
return nil
case c.ch <- b:
}
// 3. push batch to server receive queue:
select {
case <-c.server.done:
return nil
case c.server.ch <- b:
}
}
}
func (c *conn) ackLoop() {
log.Println("start client ack loop")
defer log.Println("client ack loop stopped")
// drain queue on shutdown.
// Stop ACKing batches in case of error, forcing client to reconnect
defer func() {
log.Println("drain ack loop")
for range c.ch {
}
}()
for {
select {
case <-c.signal: // return on client/server shutdown
log.Println("receive client connection close signal")
return
case b, open := <-c.ch:
if !open {
return
}
if err := c.waitACK(b); err != nil {
return
}
}
}
}
func (c *conn) waitACK(batch *Batch) error {
n := len(batch.Events)
for {
select {
case <-c.signal:
return nil
case <-batch.ack:
// send ack
return c.sendACK(n)
case <-time.After(c.keepalive):
if err := c.sendACK(0); err != nil {
return err
}
}
}
}
func (c *conn) sendACK(n int) error {
var buf [6]byte
buf[0] = protocol.CodeVersion
buf[1] = protocol.CodeACK
binary.BigEndian.PutUint32(buf[2:], uint32(n))
if err := c.c.SetWriteDeadline(time.Now().Add(c.to)); err != nil {
return err
}
tmp := buf[:]
for len(tmp) > 0 {
n, err := c.c.Write(tmp)
if err != nil {
return err
}
tmp = tmp[n:]
}
return nil
}
func newReader(c net.Conn, opts options) *reader {
r := &reader{
in: bufio.NewReader(c),
conn: c,
buf: make([]byte, 0, 64),
opts: opts,
}
return r
}
func (r *reader) readBatch() (*Batch, error) {
// 1. read window size
var win [6]byte
if err := readFull(r.in, win[:]); err != nil {
return nil, err
}
if win[0] != protocol.CodeVersion && win[1] != protocol.CodeWindowSize {
return nil, ErrProtocolError
}
count := int(binary.BigEndian.Uint32(win[2:]))
if count == 0 {
return nil, nil
}
if err := r.conn.SetReadDeadline(time.Now().Add(r.opts.timeout)); err != nil {
return nil, err
}
events, err := r.readEvents(r.in, make([]interface{}, 0, count))
if events == nil || err != nil {
return nil, err
}
batch := &Batch{
Events: events,
ack: make(chan struct{}, 1),
}
return batch, nil
}
func (r *reader) readEvents(in io.Reader, events []interface{}) ([]interface{}, error) {
for len(events) < cap(events) {
var hdr [2]byte
if err := readFull(in, hdr[:]); err != nil {
return nil, err
}
if hdr[0] != protocol.CodeVersion {
return nil, ErrProtocolError
}
switch hdr[1] {
case 'J':
event, err := r.readJSONEvent(in)
if err != nil {
return nil, err
}
events = append(events, event)
case 'C':
readEvents, err := r.readCompressed(in, events)
if err != nil {
return nil, err
}
events = readEvents
default:
return nil, ErrProtocolError
}
}
return events, nil
}
func (r *reader) readJSONEvent(in io.Reader) (interface{}, error) {
var hdr [8]byte
if err := readFull(in, hdr[:]); err != nil {
return nil, err
}
payloadSz := int(binary.BigEndian.Uint32(hdr[4:]))
if payloadSz > len(r.buf) {
r.buf = make([]byte, payloadSz)
}
buf := r.buf[:payloadSz]
if err := readFull(in, buf); err != nil {
return nil, err
}
var event interface{}
err := r.opts.decoder(buf, &event)
return event, err
}
func (r *reader) readCompressed(in io.Reader, events []interface{}) ([]interface{}, error) {
var hdr [4]byte
if err := readFull(in, hdr[:]); err != nil {
return nil, err
}
payloadSz := binary.BigEndian.Uint32(hdr[:])
limit := io.LimitReader(in, int64(payloadSz))
reader, err := zlib.NewReader(limit)
if err != nil {
return nil, err
}
events, err = r.readEvents(reader, events)
if err != nil {
_ = reader.Close()
return nil, err
}
if err := reader.Close(); err != nil {
return nil, err
}
return events, nil
}
func readFull(in io.Reader, buf []byte) error {
_, err := io.ReadFull(in, buf)
return err
}
|
package utils
import (
"errors"
"fmt"
"regexp"
)
func VaditationEmail(email string) error {
if email == "" {
return errors.New("email is required")
}
var emailRegex = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
if len(email) < 3 && len(email) > 254 {
return fmt.Errorf("email length should from %d to %d", 3, 254)
}
if !emailRegex.MatchString(email) {
return errors.New("invalid email format")
}
return nil
}
func GetAllEmail(text string) []string{
re:=regexp.MustCompile(`[a-zA-Z0-9]+@[a-zA-Z0-9\.]+\.[a-zA-Z0-9]+`)
match:=re.FindAllString(text,-1)
return match
}
func RemoveDuplicates(elements []string) []string{
keys := make(map[string]bool)
list := []string{}
for _, entry := range elements {
if _, value := keys[entry]; !value {
keys[entry] = true
list = append(list, entry)
}
}
return list
} |
package hive
import (
"bufio"
"errors"
"sync"
"time"
"github.com/gosexy/to"
"github.com/tarm/serial"
"github.com/xiam/resp"
)
var (
ErrNilReply = errors.New(`Received a nil response.`)
ErrMaxReadAttemptsExceeded = errors.New(`Exceeded maximum read attempts.`)
)
var (
defaultTimeout = time.Second * 5
defaultConnectWait = time.Second * 3
maxReadAttempts = 50
maxReadAttemptsWait = 5
)
func toBytesArray(values ...interface{}) [][]byte {
cvalues := make([][]byte, len(values))
for i := 0; i < len(values); i++ {
cvalues[i] = to.Bytes(values[i])
}
return cvalues
}
type Client struct {
cfg *serial.Config
port *serial.Port
mu sync.Mutex
encoder *resp.Encoder
decoder *resp.Decoder
reader *bufio.Reader
writer *bufio.Writer
}
func NewClient(port string, speed int) (*Client, error) {
var err error
c := new(Client)
c.cfg = &serial.Config{
Name: port,
Baud: speed,
ReadTimeout: defaultTimeout,
}
if c.port, err = serial.OpenPort(c.cfg); err != nil {
return nil, err
}
c.reader = bufio.NewReader(c.port)
c.writer = bufio.NewWriter(c.port)
c.encoder = resp.NewEncoder(c.writer)
c.decoder = resp.NewDecoder(c.reader)
time.Sleep(defaultConnectWait)
return c, nil
}
func (c *Client) Command(dest interface{}, arguments ...interface{}) error {
var err error
c.mu.Lock()
defer c.mu.Unlock()
command := toBytesArray(arguments...)
if err = c.encoder.Encode(command); err != nil {
return err
}
if err = c.writer.Flush(); err != nil {
return err
}
for i := 0; ; i++ {
err = c.decoder.Decode(dest)
if err == resp.ErrInvalidInput {
time.Sleep(time.Millisecond * time.Duration(i*maxReadAttemptsWait))
} else {
break
}
if i > maxReadAttempts {
return ErrMaxReadAttemptsExceeded
}
}
if dest == nil && err == resp.ErrExpectingDestination {
return nil
}
if err == resp.ErrMessageIsNil {
return ErrNilReply
}
return err
}
|
package target
import (
"github.com/smallfish/simpleyaml"
"path/filepath"
"strings"
)
func GetStringArray(key string, data *simpleyaml.Yaml,
packageroot, curwd string) []string {
value := data.Get(key)
if value == nil {
return make([]string, 0)
}
value_arr, _ := value.Array()
string_array := make([]string, len(value_arr))
for i := 0; i < len(value_arr); i++ {
str_val, _ := value.GetIndex(i).String()
if !filepath.IsAbs(str_val) {
str_val = GetFQTN(str_val, packageroot, curwd)
//str_val = filepath.Join(curwd, str_val)
}
string_array[i] = str_val
}
return string_array
}
func GetFQTN(target, packageroot, curdir string) string {
if IsAbs(target) {
return target
}
var curpkg string
if strings.HasPrefix(curdir, packageroot) {
curpkg = strings.Replace(curdir, packageroot, "/", 1)
} else {
curpkg = curdir
}
arr := make([]string, 2)
arr[0] = curpkg
arr[1] = target
return strings.Join(arr, "/")
}
func IsAbs(target string) bool {
return strings.HasPrefix(target, "//")
}
|
package devto
import "strconv"
type RetrieveArticlesOption struct {
Page int
PerPage int
Tag string
Username string
State State
Top int
CollectionId int
}
type State string
const (
StateFresh State = "fresh"
StateRising = "rising"
StateAll = "all"
)
type RetrieveUserArticlesOption struct {
Page int
PerPage int
}
/* GET /articles */
func (c *Client) RetrieveArticles(option *RetrieveArticlesOption) ([]*Article, error) {
var res []*Article
err := GetWithQuery("/articles", c.ApiKey, option, &res)
if err != nil {
return nil, err
}
return res, nil
}
/* GET /articles/:id */
func (c *Client) RetrieveArticleById(id int) (*Article, error) {
res := &Article{}
err := SimpleGet("/articles/"+strconv.Itoa(id), c.ApiKey, res)
if err != nil {
return nil, err
}
return res, nil
}
/* GET /articles/me */
func (c *Client) RetrieveUserArticles(option *RetrieveUserArticlesOption) ([]*Article, error) {
var res []*Article
err := GetWithQuery("/articles/me", c.ApiKey, option, &res)
if err != nil {
return nil, err
}
return res, nil
}
/* GET /articles/me/published */
func (c *Client) RetrieveUserPublishedArticles(option *RetrieveUserArticlesOption) ([]*Article, error) {
var res []*Article
err := GetWithQuery("/articles/me/published", c.ApiKey, option, &res)
if err != nil {
return nil, err
}
return res, nil
}
/* GET /articles/me/unpublished */
func (c *Client) RetrieveUserUnpublishedArticles(option *RetrieveUserArticlesOption) ([]*Article, error) {
var res []*Article
err := GetWithQuery("/articles/me/unpublished", c.ApiKey, option, &res)
if err != nil {
return nil, err
}
return res, nil
}
/* GET /articles/me/all */
func (c *Client) RetrieveUserAllArticles(option *RetrieveUserArticlesOption) ([]*Article, error) {
var res []*Article
err := GetWithQuery("/articles/me/all", c.ApiKey, option, &res)
if err != nil {
return nil, err
}
return res, nil
}
type ArticleContent struct {
Title string `json:"title"`
BodyMarkdown string `json:"body_markdown"`
Published bool `json:"published"`
Series string `json:"series"`
MainImage string `json:"main_image"`
CanonicalUrl string `json:"canonical_url"`
Description string `json:"description"`
Tags []string `json:"tags"`
OrganizationId int `json:"organization_id"`
}
type DraftArticle struct {
Article ArticleContent `json:"article"`
}
/* POST /articles */
func (c *Client) AddArticle(option *DraftArticle) (*Article, error) {
var res *Article
err := PostWithJSON("/articles", c.ApiKey, option, &res)
if err != nil {
return nil, err
}
return res, nil
}
func (c *Client) ModifyArticle(id int, option *DraftArticle) (*Article, error) {
var res *Article
err := PutWithJSON("/articles/"+strconv.Itoa(id), c.ApiKey, option, &res)
if err != nil {
return nil, err
}
return res, nil
}
|
// Copyright 2019 The bigfile Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package migrate
import (
"testing"
"github.com/bigfile/bigfile/config"
"github.com/bigfile/bigfile/databases"
"github.com/jinzhu/gorm"
"github.com/stretchr/testify/assert"
)
type UserModelTest struct {
Name string `gorm:"type:varchar(255);not null"`
}
func (u UserModelTest) TableName() string {
return "user_model_test"
}
type CreateUserTableMigration20190725 struct{}
func (c CreateUserTableMigration20190725) Name() string {
return "CreateUserTableMigration20190725"
}
func (c CreateUserTableMigration20190725) Up(conn *gorm.DB) error {
return conn.CreateTable(&UserModelTest{}).Error
}
func (c CreateUserTableMigration20190725) Down(conn *gorm.DB) error {
return conn.DropTable(&UserModelTest{}).Error
}
func getDBConnection(t *testing.T) *gorm.DB {
dbConfig := &config.Database{
Driver: "sqlite3",
DBFile: ":memory:",
}
connection, err := databases.NewConnection(dbConfig)
if err != nil {
t.Fatal(err)
}
return connection
}
func TestMigrationCollection_CreateMigrateTable(t *testing.T) {
connection := getDBConnection(t)
DefaultMC.SetConnection(connection)
DefaultMC.CreateMigrateTable()
if !connection.HasTable(&MigrationModel{}) {
t.Fatal("migrations table should been created already!")
}
defer connection.DropTableIfExists(&MigrationModel{})
}
func TestMigrationCollection_MaxBatch(t *testing.T) {
connection := getDBConnection(t)
DefaultMC.SetConnection(connection)
if DefaultMC.MaxBatch() != 0 {
t.Fatal("max batch of empty migrations table should be 0")
}
defer connection.DropTableIfExists(&MigrationModel{})
}
func TestMigrationCollection_Register(t *testing.T) {
DefaultMC.Register(&CreateUserTableMigration20190725{})
assert.Equal(t, 1, len(DefaultMC.migrations))
}
func TestMigrationCollection_Upgrade(t *testing.T) {
connection := getDBConnection(t)
DefaultMC.SetConnection(connection)
DefaultMC.Register(&CreateUserTableMigration20190725{})
DefaultMC.Upgrade()
if !connection.HasTable(&UserModelTest{}) {
t.Fatalf("table %s should be already existed in database\n", UserModelTest{}.TableName())
}
if DefaultMC.MaxBatch() != 1 {
t.Fatal("max batch of migrations table should be 1")
}
defer connection.DropTableIfExists(&MigrationModel{})
defer connection.DropTableIfExists(&UserModelTest{})
}
func TestMigrationCollection_Rollback(t *testing.T) {
connection := getDBConnection(t)
DefaultMC.SetConnection(connection)
DefaultMC.Register(&CreateUserTableMigration20190725{})
DefaultMC.Upgrade()
DefaultMC.Rollback(1)
if connection.HasTable(&UserModelTest{}) {
t.Fatalf("table %s should be already deleted in database\n", UserModelTest{}.TableName())
}
if DefaultMC.MaxBatch() != 0 {
t.Fatal("max batch of migrations table should be 0")
}
defer connection.DropTableIfExists(&MigrationModel{})
defer connection.DropTableIfExists(&UserModelTest{})
}
|
package internal
import (
"log"
"regexp"
"strings"
"time"
)
type WhoisResponseType int
const (
ResponseUnknown WhoisResponseType = iota
ResponseOk
ResponseError
ResponseAvailable
ResponseUnauthorized
ResponseExceededRate
)
func (wrt WhoisResponseType) String() string {
return [...]string{"Unknown", "OK", "Error", "Available", "Unauthorized", "ExceededRate"}[wrt]
}
// Non-exhaustive list of values from a whois query.
type WhoisResponse struct {
target string // What we queried.
hostPort string // Who we queried.
raw string // Raw response.
status WhoisResponseType // Response status using enums above.
err error // Error exception caught for ResponseError use cases.
// Parsed values below.
refer string // Parsed refer response in case of another query is required.
domain string // Parsed domain in the final response.
hasExpiration bool // Determines if expiry was parsed.
expiration time.Time // Actual expiry that was parsed.
}
func NewWhoisResponse() WhoisResponse {
resp := WhoisResponse{}
resp.status = ResponseUnknown
resp.hasExpiration = false
return resp
}
func (r *WhoisResponse) ParseRawResponse(raw string) {
r.raw = raw
r.status = ResponseOk // Default to OK at this point unless we have a value below.
if hasRefer(raw) {
r.refer = getRefer(raw)
}
if noMatchFound(raw) {
r.status = ResponseAvailable
}
if hasDomain(raw) {
r.domain = getDomain(raw)
}
if hasExpiration(raw) {
r.hasExpiration = true
r.expiration = getExpiration(raw)
}
if hasExceededQueries(raw) {
r.status = ResponseExceededRate
}
if notAuthorized(raw) {
r.status = ResponseUnauthorized
}
}
func hasRefer(text string) bool {
re := regexp.MustCompile(`(?i)refer:`)
return re.MatchString(strings.TrimSpace(text))
}
func getRefer(text string) string {
result := ""
if hasRefer(text) {
re := regexp.MustCompile(`(?is)refer:\s+(.*?)\s+`)
match := re.FindStringSubmatch(text)
if match != nil {
result = match[1]
}
}
return result
}
func noMatchFound(text string) bool {
re := regexp.MustCompile(`(?im)((no match for)|(not found)|(no data found))`)
return re.MatchString(strings.TrimSpace(text))
}
func hasDomain(text string) bool {
re := regexp.MustCompile(`(?i)\s*((domain)|(domain name)):\s+(.*?)\s+`)
return re.MatchString(strings.TrimSpace(text))
}
func getDomain(text string) string {
result := ""
if hasDomain(text) {
re := regexp.MustCompile(`(?i)\s*?((domain)|(domain name)):\s+(.*?)\s+`)
match := re.FindStringSubmatch(strings.ToLower(text))
if match != nil {
result = strings.TrimSpace(match[4])
}
}
return result
}
func hasExpiration(text string) bool {
re := regexp.MustCompile(`(?i)((domain expires)|(registry expiry date)|(expiry date)|(expire date)|(expires)):\s+.*?\s+`)
return re.MatchString(strings.TrimSpace(text))
}
func getExpiration(text string) time.Time {
if hasExpiration(text) {
re := regexp.MustCompile(`(?i).*?expir.*?:\s+(.*?)\s+`)
match := re.FindStringSubmatch(text)
if match != nil {
value := strings.TrimSpace(match[1])
result, err := time.Parse(time.RFC3339, value)
if err != nil {
// OK, RFC3339 parse fail, try one of two short forms.
const shortForm = "02-Jan-2006"
result, err = time.Parse(shortForm, value)
if err != nil {
// OK, one more time.
const shortForm2 = "2006-01-02"
result, err = time.Parse(shortForm2, value)
if err != nil {
log.Println("error in parsing both short forms", err.Error())
result = time.Now()
}
}
}
return result
}
}
return time.Date(2002, 3, 4, 5, 6, 7, 8, time.UTC)
}
func notAuthorized(text string) bool {
re := regexp.MustCompile(`(?i)( not authorised )`)
return re.MatchString(strings.TrimSpace(text))
}
func hasExceededQueries(text string) bool {
re := regexp.MustCompile(`(?i)^.*( queries exceeded.)$`)
return re.MatchString(strings.TrimSpace(text))
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.