text stringlengths 11 4.05M |
|---|
package client
import (
"io/ioutil"
"log"
"net/http"
)
func DetectConnection(ip string) bool {
log.Println("Connecting to " + ip)
test, err := http.Get(ip)
if test != nil {
log.Println("found in request: ")
log.Println(test)
} else {
log.Println(err)
return false
}
defer test.Body.Close()
Output, err := ioutil.ReadAll(test.Body)
if err != nil {
log.Fatal(err)
}
if string(Output) != "" {
return true
} else {
return false
}
}
|
package main
import "fmt"
func main() {
var grade string
switch level:=1; level {
case 1:
grade = "A"
case 2:
grade = "B"
case 3, 4, 5:
grade = "C"
default:
grade = "D"
}
switch {
case grade == "A":
fmt.Println("优秀")
case grade == "B", grade == "C":
fmt.Println("良好")
default:
fmt.Println("差")
}
///////////////////////////////
var x interface{}
switch i := x.(type) {
case nil:
fmt.Printf("x 的类型 :%T", i)
case int:
fmt.Printf("x 是 int 型")
case float64:
fmt.Printf("x 是 float64 型")
case func(int) float64:
fmt.Printf("x 是 func(int) 型")
case bool, string:
fmt.Printf("x 是 bool 或 string 型")
default:
fmt.Printf("未知型")
}
}
//优秀
//x 的类型 :<nil>
|
package fieldutils
import "strings"
func NormalizedStringField(str string) string {
return strings.TrimSpace(strings.Join(strings.Fields(str), ""))
}
|
package models
import (
"encoding/json"
"fmt"
"os"
"path"
"github.com/gofrs/uuid"
SMP "github.com/layer5io/service-mesh-performance/spec"
"github.com/pkg/errors"
"github.com/prologic/bitcask"
"github.com/sirupsen/logrus"
)
// BitCaskTestProfilesPersister assists with persisting session in a Bitcask store
type BitCaskTestProfilesPersister struct {
fileName string
db *bitcask.Bitcask
}
// UserTestProfiles - represents a page of user test configs
type UserTestProfiles struct {
Page uint64 `json:"page"`
PageSize uint64 `json:"page_size"`
TotalCount int `json:"total_count"`
TestConfigs []*SMP.PerformanceTestConfig `json:"test_configs"`
}
// NewBitCaskTestProfilesPersister creates a new BitCaskTestProfilesPersister instance
func NewBitCaskTestProfilesPersister(folderName string) (*BitCaskTestProfilesPersister, error) {
_, err := os.Stat(folderName)
if err != nil {
if os.IsNotExist(err) {
err = os.MkdirAll(folderName, os.ModePerm)
if err != nil {
logrus.Errorf("Unable to create the directory '%s' due to error: %v.", folderName, err)
return nil, err
}
} else {
logrus.Errorf("Unable to find/stat the folder '%s': %v,", folderName, err)
return nil, err
}
}
fileName := path.Join(folderName, "testConfigDB")
db, err := bitcask.Open(fileName, bitcask.WithSync(true))
if err != nil {
logrus.Errorf("Unable to open database: %v.", err)
return nil, err
}
bd := &BitCaskTestProfilesPersister{
fileName: fileName,
db: db,
}
return bd, nil
}
// GetTestConfigs - gets result for the page and pageSize
func (s *BitCaskTestProfilesPersister) GetTestConfigs(page, pageSize uint64) ([]byte, error) {
if s.db == nil {
return nil, errors.New("connection to DB does not exist")
}
RETRY:
locked, err := s.db.TryRLock()
if err != nil {
err = errors.Wrapf(err, "unable to obtain read lock from bitcask store")
logrus.Error(err)
}
if !locked {
goto RETRY
}
defer func() {
_ = s.db.Unlock()
}()
total := s.db.Len()
testConfigs := []*SMP.PerformanceTestConfig{}
start := page * pageSize
end := (page+1)*pageSize - 1
logrus.Debugf("received page: %d, page size: %d, total: %d", page, pageSize, total)
logrus.Debugf("computed start index: %d, end index: %d", start, end)
if start > uint64(total) {
return nil, fmt.Errorf("index out of range")
}
var localIndex uint64
for k := range s.db.Keys() {
if localIndex >= start && localIndex <= end {
dd, err := s.db.Get(k)
if err != nil {
err = errors.Wrapf(err, "unable to read data from bitcask store")
logrus.Error(err)
return nil, err
}
if len(dd) > 0 {
testConfig := &SMP.PerformanceTestConfig{}
if err := json.Unmarshal(dd, testConfig); err != nil {
err = errors.Wrapf(err, "unable to unmarshal data.")
logrus.Error(err)
return nil, err
}
testConfigs = append(testConfigs, testConfig)
}
}
localIndex++
}
bd, err := json.Marshal(&UserTestProfiles{
Page: page,
PageSize: pageSize,
TotalCount: total,
TestConfigs: testConfigs,
})
if err != nil {
err = errors.Wrapf(err, "unable to marshal result data.")
logrus.Error(err)
return nil, err
}
return bd, nil
}
// GetTestConfig - gets result for a specific key
func (s *BitCaskTestProfilesPersister) GetTestConfig(key uuid.UUID) (*SMP.PerformanceTestConfig, error) {
if s.db == nil {
return nil, errors.New("connection to DB does not exist")
}
RETRY:
locked, err := s.db.TryRLock()
if err != nil {
err = errors.Wrapf(err, "unable to obtain read lock from bitcask store")
logrus.Error(err)
}
if !locked {
goto RETRY
}
defer func() {
_ = s.db.Unlock()
}()
keyb := key.Bytes()
if !s.db.Has(keyb) {
err = errors.New("given key not found")
logrus.Error(err)
return nil, err
}
data, err := s.db.Get(keyb)
if err != nil {
err = errors.Wrapf(err, "unable to fetch result data")
logrus.Error(err)
return nil, err
}
testConfig := &SMP.PerformanceTestConfig{}
err = json.Unmarshal(data, testConfig)
if err != nil {
err = errors.Wrapf(err, "unable to marshal testConfig data.")
logrus.Error(err)
return nil, err
}
return testConfig, nil
}
// DeleteTestConfig - delete result for a specific key
func (s *BitCaskTestProfilesPersister) DeleteTestConfig(key uuid.UUID) error {
if s.db == nil {
return errors.New("connection to DB does not exist")
}
RETRY:
locked, err := s.db.TryRLock()
if err != nil {
err = errors.Wrapf(err, "unable to obtain read lock from bitcask store")
logrus.Error(err)
}
if !locked {
goto RETRY
}
defer func() {
_ = s.db.Unlock()
}()
keyb := key.Bytes()
if !s.db.Has(keyb) {
err = errors.New("given key not found")
logrus.Error(err)
return err
}
err = s.db.Delete(keyb)
if err != nil {
err = errors.Wrapf(err, "unable to fetch result data")
logrus.Error(err)
return err
}
return nil
}
// WriteTestConfig persists the result
func (s *BitCaskTestProfilesPersister) WriteTestConfig(key uuid.UUID, result []byte) error {
if s.db == nil {
return errors.New("connection to DB does not exist")
}
if result == nil {
return errors.New("given result data is nil")
}
RETRY:
locked, err := s.db.TryLock()
if err != nil {
err = errors.Wrapf(err, "unable to obtain write lock from bitcask store")
logrus.Error(err)
}
if !locked {
goto RETRY
}
defer func() {
_ = s.db.Unlock()
}()
if err := s.db.Put(key.Bytes(), result); err != nil {
err = errors.Wrapf(err, "unable to persist result data.")
logrus.Error(err)
return err
}
return nil
}
// CloseTestConfigsPersister closes the badger store
func (s *BitCaskTestProfilesPersister) CloseTestConfigsPersister() {
if s.db == nil {
return
}
_ = s.db.Close()
}
|
package core
import "sync"
type Set map[interface{}]bool
func (h Set) Add(key interface{}) {
h[key] = true
}
func (h Set) Delete(key interface{}) {
if _, ok := h[key]; ok {
delete (h, key)
}
}
func (h Set) Exists(key interface{}) bool {
_, ok := h[key]
return ok
}
type AtomSet struct {
set Set
mutex sync.RWMutex
}
func (h *AtomSet) Add(key interface{}) {
defer h.mutex.Unlock()
h.mutex.Lock()
h.set.Add(key)
}
func (h *AtomSet) Delete(key interface{}) {
defer h.mutex.Unlock()
h.mutex.Lock()
h.Delete(key)
}
func (h *AtomSet) Exists(key interface{}) bool {
defer h.mutex.RUnlock()
h.mutex.RLock()
return h.Exists(key)
} |
package service
import (
"context"
"fmt"
"sync/atomic"
"github.com/go-ocf/cloud/grpc-gateway/pb"
pbCQRS "github.com/go-ocf/cloud/resource-aggregate/pb"
pbRA "github.com/go-ocf/cloud/resource-aggregate/pb"
kitNetGrpc "github.com/go-ocf/kit/net/grpc"
"github.com/gofrs/uuid"
grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
)
func (r *RequestHandler) RetrieveResourceFromDevice(ctx context.Context, req *pb.RetrieveResourceFromDeviceRequest) (*pb.RetrieveResourceFromDeviceResponse, error) {
accessToken, err := grpc_auth.AuthFromMD(ctx, "bearer")
if err != nil {
return nil, logAndReturnError(status.Errorf(codes.Unauthenticated, "cannot retrieve resource from device: %v", err))
}
if req.ResourceId == nil {
return nil, logAndReturnError(status.Errorf(codes.InvalidArgument, "cannot retrieve resource from device: invalid ResourceId"))
}
deviceID := req.GetResourceId().GetDeviceId()
href := req.GetResourceId().GetResourceLinkHref()
errorMsg := fmt.Sprintf("cannot retrieve resource from device /%v%v", deviceID, href) + ": %v"
correlationIDUUID, err := uuid.NewV4()
if err != nil {
return nil, logAndReturnError(status.Errorf(codes.Internal, errorMsg, err))
}
correlationID := correlationIDUUID.String()
resourceID := GrpcResourceID2ResourceID(req.ResourceId)
notify := r.retrieveNotificationContainer.Add(correlationID)
defer r.retrieveNotificationContainer.Remove(correlationID)
loaded, err := r.resourceProjection.Register(ctx, deviceID)
if err != nil {
return nil, logAndReturnError(status.Errorf(codes.NotFound, errorMsg, fmt.Errorf("cannot register device to projection: %w", err)))
}
defer r.resourceProjection.Unregister(deviceID)
if !loaded {
if len(r.resourceProjection.Models(deviceID, resourceID)) == 0 {
err = r.resourceProjection.ForceUpdate(ctx, deviceID, resourceID)
if err != nil {
return nil, logAndReturnError(status.Errorf(codes.NotFound, errorMsg, err))
}
}
}
connectionID := "grpc-gateway"
peer, ok := peer.FromContext(ctx)
if ok {
connectionID = peer.Addr.String()
}
seq := atomic.AddUint64(&r.seqNum, 1)
raReq := pbRA.RetrieveResourceRequest{
ResourceId: resourceID,
ResourceInterface: req.GetResourceInterface(),
CorrelationId: correlationID,
CommandMetadata: &pbCQRS.CommandMetadata{
ConnectionId: connectionID,
Sequence: seq,
},
}
_, err = r.resourceAggregateClient.RetrieveResource(kitNetGrpc.CtxWithToken(ctx, accessToken), &raReq)
if err != nil {
return nil, logAndReturnError(kitNetGrpc.ForwardErrorf(codes.Internal, errorMsg, err))
}
timeoutCtx, cancel := context.WithTimeout(ctx, r.timeoutForRequests)
defer cancel()
select {
case processed := <-notify:
content, err := eventContentToContent(processed.GetStatus(), processed.GetContent())
if err != nil {
return nil, err
}
return &pb.RetrieveResourceFromDeviceResponse{
Content: content,
}, nil
case <-timeoutCtx.Done():
}
return nil, logAndReturnError(status.Errorf(codes.DeadlineExceeded, errorMsg, fmt.Errorf("timeout")))
}
|
package solutions
import (
"fmt"
"testing"
)
func TestSpiralOrder(t *testing.T) {
t.Run("Test [[1,2,3],[4,5,6],[7,8,9]]", func(t *testing.T) {
input := [][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
want := fmt.Sprint([]int{1, 2, 3, 6, 9, 8, 7, 4, 5})
r := fmt.Sprint(spiralOrder(input))
if want != r {
t.Errorf("got %v, want %v", r, want)
}
})
t.Run("Test [[1,2,3,4],[5,6,7,8],[9,10,11,12]]", func(t *testing.T) {
input := [][]int{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
}
want := fmt.Sprint([]int{1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7})
r := fmt.Sprint(spiralOrder(input))
if want != r {
t.Errorf("got %v, want %v", r, want)
}
})
}
|
package message
type ErrorMessage string
type WalletMessage string
type TransactionMessage string
const (
DATABASE_ERROR = ErrorMessage("A database error has occured, please check system logs for more details")
DB_ERROR_OCCURED = ErrorMessage("Database Error occurred : %v")
)
const (
DEBIT_WALLET_DOES_NOT_EXIST = WalletMessage("Debit wallet does not exist")
CREDIT_WALLET_DOES_NOT_EXIST = WalletMessage("Credit wallet does not exist")
WALLET_ALREADY_EXISTS = WalletMessage("Wallet with phone number already exists")
WALLET_IS_DISABLED = WalletMessage("Wallet is disabled, please contact the administrator")
WALLET_SUCCESSFULLY_CREATED = WalletMessage("Wallet successfully created")
WALLET_NOT_SUCCESSFULLY_CREATED = WalletMessage("Wallet not successfully created")
WALLET_SUCCESSFULLY_ENABLED = WalletMessage("Wallet Successfully Enabled")
WALLET_NOT_SUCCESSFULLY_ENABLED = WalletMessage("Wallet not Successfully Enabled")
WALLET_SUCCESSFULLY_DISABLED = WalletMessage("Wallet Successfully Disabled")
WALLET_NOT_SUCCESSFULLY_DISABLED = WalletMessage("Wallet not Successfully Disabled")
WALLET_ALREADY_ENABLED = WalletMessage("Wallet Already enabled")
WALLET_ALREADY_DISABLED = WalletMessage("Wallet Already disabled")
WALLET_NOT_EXIST = WalletMessage("Wallet does not exist")
)
const (
TRANSACTION_APPROVED = TransactionMessage("Transaction Approved")
TRANSACTION_DECLINED = TransactionMessage("Transaction Declined")
INSUFFICIEND_FUND = TransactionMessage("Insufficient Funds")
)
func (e ErrorMessage) String() string {
return string(e)
}
func (w WalletMessage) String() string {
return string(w)
}
func (t TransactionMessage) String() string {
return string(t)
}
|
package lib
import (
"github.com/hailongz/kk-lib/dynamic"
"github.com/hailongz/kk-logic/logic"
)
type ContentLogic struct {
logic.Logic
}
func (L *ContentLogic) Exec(ctx logic.IContext, app logic.IApp) error {
L.Logic.Exec(ctx, app)
contentType := dynamic.StringValue(L.Get(ctx, app, "contentType"), "")
content := L.Get(ctx, app, "content")
v := logic.Content{
ContentType: contentType,
}
if content == nil {
v.Content = []byte{}
}
if v.Content == nil {
b, ok := content.([]byte)
if ok {
v.Content = b
}
}
if v.Content == nil {
b, ok := content.(string)
if ok {
v.Content = []byte(b)
}
}
if v.Content == nil {
v.Content = []byte{}
}
dynamic.Each(L.Get(ctx, app, "headers"), func(key interface{}, value interface{}) bool {
v.Header[dynamic.StringValue(key, "")] = []string{dynamic.StringValue(value, "")}
return true
})
return &v
}
func init() {
logic.Openlib("kk.Logic.Content", func(object interface{}) logic.ILogic {
v := ContentLogic{}
v.Init(object)
return &v
})
}
|
// Package gate provides primitive to limit number of concurrent goroutine
// workers. Useful when sync.Locker or sync.WaitGroup is not enough.
package gate
import (
"runtime"
"sync"
)
// A Gate is a primitive intended to help in limiting concurrency in some
// scenarios. Think of it as a close sync.WaitGroup analog which has upper
// limit on its counter or a sync.Locker which allows up to max number of
// concurrent lockers to be held.
type Gate struct {
c chan struct{}
m sync.Mutex
}
var defaultGate = New(runtime.NumCPU())
// Lock locks default gate with capacity defined by runtime.NumCPU()
func Lock() { defaultGate.Lock() }
// Unlock unlocks default gate
func Unlock() { defaultGate.Unlock() }
// Add adds n to default gate counter. Absolute value of n should be no more
// than runtime.NumCPU()
func Add(n int) { defaultGate.Add(n) }
// Done decrements default gate counter
func Done() { defaultGate.Done() }
// Wait blocks until default gate is not locked
func Wait() { defaultGate.Wait() }
// New returns new Gate with provided capacity. If capacity is non-positive,
// New would panic.
func New(max int) *Gate { return &Gate{c: make(chan struct{}, max)} }
// Lock implements sync.Locker interface. Gate capacity determines number of
// non-blocking Lock calls, when max number is reached, Lock would block until
// some other goroutine calls Unlock. Lock is safe for concurrent use.
func (g *Gate) Lock() { g.c <- struct{}{} }
// Unlock implements sync.Locker interface. Unlock is safe for concurrent use.
func (g *Gate) Unlock() { <-g.c }
// Add implements similar semantic to sync.WaitGroup.Add. If Add is called with
// positive argument N, it essentially calls Lock N times; if N is negative, it
// calls Unlock N times. If absolute value of N is greater than Gate capacity,
// Add would panic. Add is safe for concurrent use, but should be used with
// care as deadlocks are possible.
func (g *Gate) Add(n int) {
if c := cap(g.c); n > c || -n > c {
panic("gate: out of range Add argument")
}
if n > 0 {
for i := 0; i < n; i++ {
g.c <- struct{}{}
}
return
}
for i := 0; i < (-n); i++ {
<-g.c
}
}
// Done semantic is the same as sync.WaitGroup.Done.
func (g *Gate) Done() { <-g.c }
// Wait blocks until nothing holds a single Gate lock. Its semantic is the same
// as sync.WaitGroup.Wait.
func (g *Gate) Wait() {
g.m.Lock()
defer g.m.Unlock()
for i := 0; i < cap(g.c); i++ {
g.c <- struct{}{}
}
for i := 0; i < cap(g.c); i++ {
<-g.c
}
}
|
package main
import (
"fmt"
"log"
"time"
)
func main() {
log.Println(time.Now())
fmt.Println(time.Now())
log.Println(time.Now().Format(time.RFC3339))
fmt.Println(time.Now().Format(time.RFC3339))
}
/*
// Parse a time value from a string in the standard Unix format.
t, err := time.Parse(time.UnixDate, "Sat Mar 7 11:06:39 PST 2015")
if err != nil { // Always check errors even if they should not happen.
panic(err)
}
// time.Time's Stringer method is useful without any format.
fmt.Println("default format:", t)
// Predefined constants in the package implement common layouts.
fmt.Println("Unix format:", t.Format(time.UnixDate))
// The time zone attached to the time value affects its output.
fmt.Println("Same, in UTC:", t.UTC().Format(time.UnixDate))
*/
|
package main
import (
"math/rand"
"github.com/goml/gobrain"
)
type FizzBuzz []float64
func (f FizzBuzz) Type() int {
for i, f := range f {
if f > 0.4 {
return i
}
}
panic("Wrong")
}
func teacher(n int) []float64 {
switch {
case n%15 == 0:
return []float64{1, 0, 0, 0}
case n%3 == 0:
return []float64{0, 1, 0, 0}
case n%5 == 0:
return []float64{0, 0, 1, 0}
default:
return []float64{0, 0, 0, 1}
}
}
func bin(n int) []float64 {
f := [8]float64{}
for i := uint(0); i < 8; i++ {
f[i] = float64((n >> i) & 1)
}
return f[:]
}
func main() {
rand.Seed(0)
patterns := [][][]float64{}
for i := 1; i <= 100; i++ {
patterns = append(patterns, [][]float64{
bin(i), teacher(i),
})
}
ff := &gobrain.FeedForward{}
ff.Init(8, 100, 4)
ff.Train(patterns, 1000, 0.6, 0.4, false)
for i := 1; i < 100; i++ {
switch FizzBuzz(ff.Update(bin(i))).Type() {
case 0:
println(i, ":: ", "FizzBuzz")
case 1:
println(i, ":: ", "Fizz")
case 2:
println(i, ":: ", "Buzz")
case 3:
println(i, ":: ", i)
}
}
}
|
package message
// ConfigNotFound should be used if devspace.yaml cannot be found
const ConfigNotFound = "Cannot find a devspace.yaml for this project. Please run `devspace init`"
// ConfigNoImages should be used if devpsace.yaml does not contain any images
const ConfigNoImages = "This project's devspace.yaml does not contain any images. Interactive mode requires at least one image because it overrides the entrypoint of one of the specified images. \n\nAlternative commands: \n- `devspace enter` to open a terminal (without port-forwarding and file sync) \n- `devspace dev -t` to start development mode (port-forwarding and file sync) but open the terminal instead of streaming the logs"
// SpaceNotFound should be used if the Space %s does not exist
const SpaceNotFound = "Cannot find Space '%s' \n\nYou may need to run `devspace login` or prefix the Space name with the name of its owner, e.g. USER:SPACE"
// SpaceQueryError should be used if a graphql query for a space fails
const SpaceQueryError = "Error retrieving Space details"
// SelectorErrorPod should be used if there is an error selecting a pod
const SelectorErrorPod = "Error selecting pod"
// SelectorLabelNotFound should be used when selecting pod via labelSelector finds no pods
const SelectorLabelNotFound = "Cannot find a pod using label selector '%s' in namespace '%s' \n\nTo get a list of all pods with their labels, run: kubectl get pods --show-labels"
// PodStatusCritical should be used if a pod has a critial status but is expected to be running (or completed)
const PodStatusCritical = "Pod '%s' has critical status '%s' \n\nTo get more information about this pod's status, run: kubectl describe pod %s"
// ServiceNotFound should be used if there are no Kubernetes services resources
const ServiceNotFound = "Cannot find any services in namespace '%s'. Please make sure you have a service that this ingress can connect to. \n\nTo get a list of services in your current namespace, run: kubectl get services"
|
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package math32
// Box3 represents a 3D bounding box defined by two points:
// the point with minimum coordinates and the point with maximum coordinates.
type Box3 struct {
Min Vector3
Max Vector3
}
// NewBox3 creates and returns a pointer to a new Box3 defined
// by its minimum and maximum coordinates.
func NewBox3(min, max *Vector3) *Box3 {
b := new(Box3)
b.Set(min, max)
return b
}
// Set sets this bounding box minimum and maximum coordinates.
// Returns pointer to this updated bounding box.
func (b *Box3) Set(min, max *Vector3) *Box3 {
if min != nil {
b.Min = *min
} else {
b.Min.Set(Infinity, Infinity, Infinity)
}
if max != nil {
b.Max = *max
} else {
b.Max.Set(-Infinity, -Infinity, -Infinity)
}
return b
}
// SetFromPoints set this bounding box from the specified array of points.
// Returns pointer to this updated bounding box.
func (b *Box3) SetFromPoints(points []Vector3) *Box3 {
b.MakeEmpty()
for i := 0; i < len(points); i++ {
b.ExpandByPoint(&points[i])
}
return b
}
// SetFromCenterAndSize set this bounding box from a center point and size.
// Size is a vector from the minimum point to the maximum point.
// Returns pointer to this updated bounding box.
func (b *Box3) SetFromCenterAndSize(center, size *Vector3) *Box3 {
v1 := NewVector3(0, 0, 0)
halfSize := v1.Copy(size).MultiplyScalar(0.5)
b.Min.Copy(center).Sub(halfSize)
b.Max.Copy(center).Add(halfSize)
return b
}
// Copy copy other to this bounding box.
// Returns pointer to this updated bounding box.
func (b *Box3) Copy(other *Box3) *Box3 {
b.Min = other.Min
b.Max = other.Max
return b
}
// MakeEmpty set this bounding box to empty.
// Returns pointer to this updated bounding box.
func (b *Box3) MakeEmpty() *Box3 {
b.Min.X = Infinity
b.Min.Y = Infinity
b.Min.Z = Infinity
b.Max.X = -Infinity
b.Max.Y = -Infinity
b.Max.Z = -Infinity
return b
}
// Empty returns if this bounding box is empty.
func (b *Box3) Empty() bool {
return (b.Max.X < b.Min.X) || (b.Max.Y < b.Min.Y) || (b.Max.Z < b.Min.Z)
}
// Center calculates the center point of this bounding box and
// stores its pointer to optionalTarget, if not nil, and also returns it.
func (b *Box3) Center(optionalTarget *Vector3) *Vector3 {
var result *Vector3
if optionalTarget == nil {
result = NewVector3(0, 0, 0)
} else {
result = optionalTarget
}
return result.AddVectors(&b.Min, &b.Max).MultiplyScalar(0.5)
}
// Size calculates the size of this bounding box: the vector from
// its minimum point to its maximum point.
// Store pointer to the calculated size into optionalTarget, if not nil,
// and also returns it.
func (b *Box3) Size(optionalTarget *Vector3) *Vector3 {
var result *Vector3
if optionalTarget == nil {
result = NewVector3(0, 0, 0)
} else {
result = optionalTarget
}
return result.SubVectors(&b.Min, &b.Max)
}
// ExpandByPoint may expand this bounding box to include the specified point.
// Returns pointer to this updated bounding box.
func (b *Box3) ExpandByPoint(point *Vector3) *Box3 {
b.Min.Min(point)
b.Max.Max(point)
return b
}
// ExpandByVector expands this bounding box by the specified vector.
// Returns pointer to this updated bounding box.
func (b *Box3) ExpandByVector(vector *Vector3) *Box3 {
b.Min.Sub(vector)
b.Max.Add(vector)
return b
}
// ExpandByScalar expands this bounding box by the specified scalar.
// Returns pointer to this updated bounding box.
func (b *Box3) ExpandByScalar(scalar float32) *Box3 {
b.Min.AddScalar(-scalar)
b.Max.AddScalar(scalar)
return b
}
// ContainsPoint returns if this bounding box contains the specified point.
func (b *Box3) ContainsPoint(point *Vector3) bool {
if point.X < b.Min.X || point.X > b.Max.X ||
point.Y < b.Min.Y || point.Y > b.Max.Y ||
point.Z < b.Min.Z || point.Z > b.Max.Z {
return false
}
return true
}
// ContainsBox returns if this bounding box contains other box.
func (b *Box3) ContainsBox(box *Box3) bool {
if (b.Min.X <= box.Max.X) && (box.Max.X <= b.Max.X) &&
(b.Min.Y <= box.Min.Y) && (box.Max.Y <= b.Max.Y) &&
(b.Min.Z <= box.Min.Z) && (box.Max.Z <= b.Max.Z) {
return true
}
return false
}
// IsIntersectionBox returns if other box intersects this one.
func (b *Box3) IsIntersectionBox(other *Box3) bool {
// using 6 splitting planes to rule out intersections.
if other.Max.X < b.Min.X || other.Min.X > b.Max.X ||
other.Max.Y < b.Min.Y || other.Min.Y > b.Max.Y ||
other.Max.Z < b.Min.Z || other.Min.Z > b.Max.Z {
return false
}
return true
}
// ClampPoint calculates a new point which is the specified point clamped inside this box.
// Stores the pointer to this new point into optionaTarget, if not nil, and also returns it.
func (b *Box3) ClampPoint(point *Vector3, optionalTarget *Vector3) *Vector3 {
var result *Vector3
if optionalTarget == nil {
result = NewVector3(0, 0, 0)
} else {
result = optionalTarget
}
return result.Copy(point).Clamp(&b.Min, &b.Max)
}
// DistanceToPoint returns the distance from this box to the specified point.
func (b *Box3) DistanceToPoint(point *Vector3) float32 {
var v1 Vector3
clampedPoint := v1.Copy(point).Clamp(&b.Min, &b.Max)
return clampedPoint.Sub(point).Length()
}
// GetBoundingSphere creates a bounding sphere to this bounding box.
// Store its pointer into optionalTarget, if not nil, and also returns it.
func (b *Box3) GetBoundingSphere(optionalTarget *Sphere) *Sphere {
var v1 Vector3
var result *Sphere
if optionalTarget == nil {
result = NewSphere(nil, 0)
} else {
result = optionalTarget
}
result.Center = *b.Center(nil)
result.Radius = b.Size(&v1).Length() * 0.5
return result
}
// Intersect sets this box to the intersection with other box.
// Returns pointer to this updated bounding box.
func (b *Box3) Intersect(other *Box3) *Box3 {
b.Min.Max(&other.Min)
b.Max.Min(&other.Max)
return b
}
// Union set this box to the union with other box.
// Returns pointer to this updated bounding box.
func (b *Box3) Union(other *Box3) *Box3 {
b.Min.Min(&other.Min)
b.Max.Max(&other.Max)
return b
}
// ApplyMatrix4 applies the specified matrix to the vertices of this bounding box.
// Returns pointer to this updated bounding box.
func (b *Box3) ApplyMatrix4(m *Matrix4) *Box3 {
xax := m[0] * b.Min.X
xay := m[1] * b.Min.X
xaz := m[2] * b.Min.X
xbx := m[0] * b.Max.X
xby := m[1] * b.Max.X
xbz := m[2] * b.Max.X
yax := m[4] * b.Min.Y
yay := m[5] * b.Min.Y
yaz := m[6] * b.Min.Y
ybx := m[4] * b.Max.Y
yby := m[5] * b.Max.Y
ybz := m[6] * b.Max.Y
zax := m[8] * b.Min.Z
zay := m[9] * b.Min.Z
zaz := m[10] * b.Min.Z
zbx := m[8] * b.Max.Z
zby := m[9] * b.Max.Z
zbz := m[10] * b.Max.Z
b.Min.X = Min(xax, xbx) + Min(yax, ybx) + Min(zax, zbx) + m[12]
b.Min.Y = Min(xay, xby) + Min(yay, yby) + Min(zay, zby) + m[13]
b.Min.Z = Min(xaz, xbz) + Min(yaz, ybz) + Min(zaz, zbz) + m[14]
b.Max.X = Max(xax, xbx) + Max(yax, ybx) + Max(zax, zbx) + m[12]
b.Max.Y = Max(xay, xby) + Max(yay, yby) + Max(zay, zby) + m[13]
b.Max.Z = Max(xaz, xbz) + Max(yaz, ybz) + Max(zaz, zbz) + m[14]
return b
}
// Translate translates the position of this box by offset.
// Returns pointer to this updated box.
func (b *Box3) Translate(offset *Vector3) *Box3 {
b.Min.Add(offset)
b.Max.Add(offset)
return b
}
// Equals returns if this box is equal to other
func (b *Box3) Equals(other *Box3) bool {
return other.Min.Equals(&b.Min) && other.Max.Equals(&b.Max)
}
// Clone creates and returns a pointer to copy of this bounding box
func (b *Box3) Clone() *Box3 {
return NewBox3(&b.Min, &b.Max)
}
|
package client
import (
"fmt"
"log"
"net/rpc"
"github.com/samqintw/road2go/rpc/rpc_simple/contract"
)
const port = 1234
type MyClient struct {
*rpc.Client
}
func CreateClient() *MyClient {
client, err := rpc.Dial("tcp", fmt.Sprintf("localhost:%v", port))
if err != nil {
log.Fatal("dialing:", err)
}
return &MyClient{client}
}
func (my MyClient) PerformRequest() contract.HelloWorldResponse {
args := &contract.HelloWorldRequest{Name: "World Smchin"}
var reply contract.HelloWorldResponse
err := my.Call("HelloWorldHandler.HelloWorld", args, &reply)
if err != nil {
log.Fatal("error:", err)
}
return reply
} |
package workload
import (
"github.com/projecteru2/cli/cmd/utils"
"github.com/projecteru2/core/strategy"
"github.com/urfave/cli/v2"
)
const (
workloadArgsUsage = "workloadID(s)"
specFileURI = "<spec file uri>"
copyArgsUsage = "workloadID:path1,path2,...,pathn"
sendArgsUsage = "path1,path2,...pathn"
)
// Command exports workload subommands
func Command() *cli.Command {
return &cli.Command{
Name: "workload",
Aliases: []string{"container"},
Usage: "workload commands",
Subcommands: []*cli.Command{
{
Name: "get",
Usage: "get workload(s)",
ArgsUsage: workloadArgsUsage,
Action: utils.ExitCoder(cmdWorkloadGet),
},
{
Name: "logs",
Usage: "get workload stream logs",
ArgsUsage: "workloadID",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "tail",
Value: "all",
Usage: `number of lines to show from the end of the logs (default "all")`,
},
&cli.StringFlag{
Name: "since",
Usage: "show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)",
},
&cli.StringFlag{
Name: "until",
Usage: "show logs before a timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)",
},
&cli.BoolFlag{
Name: "follow",
Aliases: []string{"f"},
Usage: "follow log output",
},
},
Action: utils.ExitCoder(cmdWorkloadLogs),
},
{
Name: "get-status",
Usage: "get workload status",
ArgsUsage: workloadArgsUsage,
Action: utils.ExitCoder(cmdWorkloadGetStatus),
},
{
Name: "set-status",
Usage: "set workload status",
ArgsUsage: workloadArgsUsage,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "running",
Usage: "Running",
},
&cli.BoolFlag{
Name: "healthy",
Usage: "Healthy",
},
&cli.Int64Flag{
Name: "ttl",
Usage: "ttl",
Value: 0,
},
&cli.StringSliceFlag{
Name: "network",
Usage: "network, can set multiple times, name=ip",
},
&cli.StringFlag{
Name: "extension",
Usage: "extension things",
},
},
Action: utils.ExitCoder(cmdWorkloadSetStatus),
},
{
Name: "list",
Usage: "list workload(s) by appname",
ArgsUsage: "[appname]",
Action: utils.ExitCoder(cmdWorkloadList),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "entry",
Usage: "filter by entry",
},
&cli.StringFlag{
Name: "nodename",
Usage: "filter by nodename",
},
&cli.StringSliceFlag{
Name: "label",
Usage: "label filter can set multiple times",
},
&cli.Int64Flag{
Name: "limit",
Usage: "limit data size",
},
&cli.StringSliceFlag{
Name: "match-ip",
Usage: "filter by IP",
},
&cli.StringSliceFlag{
Name: "skip-ip",
Usage: "filter out IP",
},
&cli.StringSliceFlag{
Name: "pod",
Usage: "filter by Pod",
},
&cli.BoolFlag{
Name: "statistics",
Usage: "Display the statistics of Workloads",
},
},
},
{
Name: "stop",
Usage: "stop workload(s)",
ArgsUsage: workloadArgsUsage,
Action: utils.ExitCoder(cmdWorkloadStop),
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "force",
Usage: "force to stop",
Aliases: []string{"f"},
Value: false,
},
},
},
{
Name: "start",
Usage: "start workload(s)",
ArgsUsage: workloadArgsUsage,
Action: utils.ExitCoder(cmdWorkloadStart),
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "force",
Usage: "force to start",
Aliases: []string{"f"},
Value: false,
},
},
},
{
Name: "restart",
Usage: "restart workload(s)",
ArgsUsage: workloadArgsUsage,
Action: utils.ExitCoder(cmdWorkloadRestart),
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "force",
Usage: "force to restart",
Aliases: []string{"f"},
Value: false,
},
},
},
{
Name: "remove",
Usage: "remove workload(s)",
ArgsUsage: workloadArgsUsage,
Action: utils.ExitCoder(cmdWorkloadRemove),
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "force",
Usage: "force to remove",
Aliases: []string{"f"},
Value: false,
},
&cli.IntFlag{
Name: "step",
Usage: "concurrent remove step",
Aliases: []string{"s"},
Value: 1,
},
},
},
{
Name: "copy",
Usage: "copy file(s) from workload(s)",
ArgsUsage: copyArgsUsage,
Action: utils.ExitCoder(cmdWorkloadCopy),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "dir",
Usage: "where to store",
Aliases: []string{"d"},
Value: "/tmp",
},
},
},
{
Name: "send",
Usage: "send file(s) to workload(s)",
ArgsUsage: sendArgsUsage,
Action: utils.ExitCoder(cmdWorkloadSend),
Flags: []cli.Flag{
&cli.StringSliceFlag{
Name: "file",
Usage: "copy local files to workload, can use multiple times. src_path:dst_path[:mode[:uid:gid]]",
},
},
},
{
Name: "dissociate",
Usage: "dissociate workload(s) from eru, return it resource but not remove it",
ArgsUsage: workloadArgsUsage,
Action: utils.ExitCoder(cmdWorkloadDissociate),
},
{
Name: "realloc",
Usage: "realloc workloads resource",
ArgsUsage: workloadArgsUsage,
Action: utils.ExitCoder(cmdWorkloadRealloc),
Flags: []cli.Flag{
&cli.Float64Flag{
Name: "cpu-request",
Usage: "cpu request increment/decrement",
Value: 0,
},
&cli.Float64Flag{
Name: "cpu-limit",
Usage: "cpu limit increment/decrement",
Value: 0,
},
&cli.Float64Flag{
Name: "cpu",
Usage: "shortcut to set cpu-limit/request equally to this value",
Value: 0,
},
&cli.StringFlag{
Name: "memory-request",
Usage: "memory request increment/decrement, like -1M or 1G, support K, M, G, T",
},
&cli.StringFlag{
Name: "memory-limit",
Usage: "memory limit increment/decrement, like -1M or 1G, support K, M, G, T",
},
&cli.StringFlag{
Name: "memory",
Usage: "shortcut to set memory-limit/request equally to this value",
},
&cli.StringFlag{
Name: "volumes-request",
Usage: `volumes request increment/decrement, like "AUTO:/data:rw:-1G,/tmp:/tmp"`,
},
&cli.StringFlag{
Name: "volumes-limit",
Usage: `volumes limit increment/decrement, like "AUTO:/data:rw:-1G,/tmp:/tmp"`,
},
&cli.BoolFlag{
Name: "cpu-bind",
Usage: `bind fixed cpu(s) with workload`,
},
&cli.BoolFlag{
Name: "cpu-unbind",
Usage: `unbind the workload relation with cpu`,
},
&cli.StringFlag{
Name: "storage-request",
Usage: `storage request incr/decr, like "-1G"`,
},
&cli.StringFlag{
Name: "storage-limit",
Usage: `storage limit incr/decr, like "-1G"`,
},
&cli.StringFlag{
Name: "storage",
Usage: "shortcut to set storage-limit/request equally to this value",
},
},
},
{
Name: "exec",
Usage: "run a command in a running workload",
ArgsUsage: "workloadID -- cmd1 cmd2 cmd3",
Action: utils.ExitCoder(cmdWorkloadExec),
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "interactive",
Aliases: []string{"i"},
Value: false,
},
&cli.StringSliceFlag{
Name: "env",
Aliases: []string{"e"},
Usage: "ENV=value",
},
&cli.StringFlag{
Name: "workdir",
Aliases: []string{"w"},
Usage: "/path/to/workdir",
Value: "/",
},
},
},
{
Name: "replace",
Usage: "replace workloads by params",
ArgsUsage: specFileURI,
Action: utils.ExitCoder(cmdWorkloadReplace),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "pod",
Usage: "where to replace",
},
&cli.StringFlag{
Name: "entry",
Usage: "which entry",
},
&cli.StringFlag{
Name: "image",
Usage: "which to replace",
},
&cli.StringSliceFlag{
Name: "node",
Usage: "which node to replace",
},
&cli.IntFlag{
Name: "count",
Usage: "run simultaneously",
Value: 1,
},
&cli.BoolFlag{
Name: "network-inherit",
Usage: "use old workload network configuration",
Value: false,
},
&cli.StringFlag{
Name: "network",
Usage: "SDN name or host mode",
// Value: "host",
},
&cli.StringSliceFlag{
Name: "env",
Usage: "set env can use multiple times, e.g., GO111MODULE=on",
},
&cli.StringFlag{
Name: "user",
Usage: "which user",
Value: "root",
},
&cli.StringSliceFlag{
Name: "label",
Usage: "filter workload by labels",
},
&cli.StringSliceFlag{
Name: "file",
Usage: "copy local files to workload, can use multiple times. src_path:dst_path",
},
&cli.StringSliceFlag{
Name: "copy",
Usage: "copy old workload files to new workload, can use multiple times. src_path:dst_path",
},
&cli.BoolFlag{
Name: "debug",
Usage: "enable debug mode for workload send their logs to default log driver",
},
&cli.BoolFlag{
Name: "ignore-hook",
Usage: "ignore-hook result",
Value: false,
},
&cli.StringSliceFlag{
Name: "after-create",
Usage: "run commands after create",
},
},
},
{
Name: "deploy",
Usage: "deploy workloads by params",
ArgsUsage: specFileURI,
Action: utils.ExitCoder(cmdWorkloadDeploy),
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "dry-run",
Usage: "dry run show capacity",
},
&cli.StringFlag{
Name: "pod",
Usage: "where to run",
},
&cli.StringFlag{
Name: "entry",
Usage: "which entry",
},
&cli.StringFlag{
Name: "image",
Usage: "which to run",
},
&cli.StringSliceFlag{
Name: "node",
Usage: "which node to run",
},
&cli.IntFlag{
Name: "count",
Usage: "how many",
Value: 1,
},
&cli.StringFlag{
Name: "network",
Usage: "SDN name or host mode",
Value: "host",
},
&cli.Float64Flag{
Name: "cpu-request",
Usage: "how many cpu to request",
Value: 0,
},
&cli.Float64Flag{
Name: "cpu-limit",
Usage: "how many cpu to limit; can specify limit without request",
Value: 1.0,
},
&cli.Float64Flag{
Name: "cpu",
Usage: "shortcut for cpu-request/limit, set them equally to this value",
Value: 1.0,
},
&cli.StringFlag{
Name: "memory-request",
Usage: "how many memory to request like 1M or 1G, support K, M, G, T",
Value: "",
},
&cli.StringFlag{
Name: "memory-limit",
Usage: "how many memory to limit like 1M or 1G, support K, M, G, T; can specify limit without request",
Value: "512M",
},
&cli.StringFlag{
Name: "memory",
Usage: "shortcut for memory-request/limit, set them equally to this value",
Value: "512M",
},
&cli.StringFlag{
Name: "storage-request",
Usage: "how many storage to request quota like 1M or 1G, support K, M, G, T",
Value: "",
},
&cli.StringFlag{
Name: "storage-limit",
Usage: "how many storage to limit quota like 1M or 1G, support K, M, G, T; can specify limit without request",
Value: "",
},
&cli.StringFlag{
Name: "storage",
Usage: "shortcut for storage-request/limit, set them equally to this value",
Value: "",
},
&cli.StringSliceFlag{
Name: "env",
Usage: "set env can use multiple times, e.g., GO111MODULE=on",
},
&cli.StringSliceFlag{
Name: "nodelabel",
Usage: "filter nodes by labels",
},
&cli.StringFlag{
Name: "deploy-strategy",
Usage: "deploy method auto/fill/each/global/dummy",
Value: strategy.Auto,
},
&cli.StringFlag{
Name: "user",
Usage: "which user",
Value: "root",
},
&cli.StringSliceFlag{
Name: "file",
Usage: "copy local file to workload, can use multiple times. src_path:dst_path",
},
&cli.StringSliceFlag{
Name: "after-create",
Usage: "run commands after create",
},
&cli.BoolFlag{
Name: "debug",
Usage: "enable debug mode for workload send their logs to default log driver",
},
&cli.IntFlag{
Name: "nodes-limit",
Usage: "Limit nodes count in fill and each mode",
Value: 0,
},
&cli.BoolFlag{
Name: "auto-replace",
Usage: "create or replace automatically",
},
&cli.BoolFlag{
Name: "cpu-bind",
Usage: "bind cpu or not",
Value: false,
},
&cli.BoolFlag{
Name: "ignore-hook",
Usage: "ignore hook process",
Value: false,
},
&cli.StringFlag{
Name: "raw-args",
Usage: "raw args in json (for docker engine)",
Value: "",
},
},
},
},
}
}
// returns --memory-request, --memory-limit
// or shortcut --memory to override them
func memoryOption(c *cli.Context) (int64, int64, error) {
memRequest, err := utils.ParseRAMInHuman(c.String("memory-request"))
if err != nil {
return 0, 0, err
}
memLimit, err := utils.ParseRAMInHuman(c.String("memory-limit"))
if err != nil {
return 0, 0, err
}
// if cpu shortcut is set, then override the above
if c.IsSet("memory") {
if memory, err := utils.ParseRAMInHuman(c.String("memory")); err == nil {
memRequest = memory
memLimit = memory
}
}
return memRequest, memLimit, nil
}
// returns --storage-request, --storage-limit
// or shortcut --storage to override them
func storageOption(c *cli.Context) (int64, int64, error) {
storageRequest, err := utils.ParseRAMInHuman(c.String("storage-request"))
if err != nil {
return 0, 0, err
}
storageLimit, err := utils.ParseRAMInHuman(c.String("storage-limit"))
if err != nil {
return 0, 0, err
}
// if storage shortcut is set, then override the above
if c.IsSet("storage") {
if storage, err := utils.ParseRAMInHuman(c.String("storage")); err == nil {
storageRequest = storage
storageLimit = storage
}
}
return storageRequest, storageLimit, nil
}
// returns --cpu-request, --cpu-limit
// or shortcut --cpu to override them
func cpuOption(c *cli.Context) (float64, float64) {
cpuRequest := c.Float64("cpu-request")
cpuLimit := c.Float64("cpu-limit")
// if cpu shortcut is set, then override the above
if c.IsSet("cpu") {
cpu := c.Float64("cpu")
cpuRequest = cpu
cpuLimit = cpu
}
return cpuRequest, cpuLimit
}
|
package admin
type DashboardController struct {
BaseController
}
func (c *DashboardController) Dashboard() {
c.Layout = "admin/layout.tpl"
c.LayoutSections = make(map[string]string)
c.LayoutSections["LayoutSidebar"] = "admin/sidebar.tpl"
c.LayoutSections["LayoutHeader"] = "admin/header.tpl"
c.TplName = "admin/dashboard.tpl"
}
|
package solutions
import (
util "./util"
)
func Length(ss []string) int {
return util.LenWrapperU(ss)
}
// func NotUsed() {
// }
|
package logengine_test
import (
"context"
"fmt"
"testing"
"time"
"github.com/direktiv/direktiv/pkg/refactor/logengine"
"github.com/google/uuid"
"go.uber.org/zap"
)
func Test_ChachedSQLLogStore(t *testing.T) {
dbMock := make(chan logengine.LogEntry, 1)
logger, logWorker, closeLogWorkers := logengine.NewCachedLogger(1,
func(
ctx context.Context,
timestamp time.Time,
level logengine.LogLevel,
msg string,
keysAndValues map[string]interface{},
) error {
tagsCopy := map[string]interface{}{}
for k, v := range keysAndValues {
tagsCopy[k] = v
}
tagsCopy["level"] = level
l := logengine.LogEntry{
T: time.Now().UTC(),
Msg: msg,
Fields: tagsCopy,
}
dbMock <- l
return nil
},
func(objectID uuid.UUID, objectType string) {},
func(template string, args ...interface{}) {
t.Errorf(template, args...)
})
go logWorker()
defer closeLogWorkers()
tags := map[string]string{}
tags["recipientType"] = "server"
tagsCopy := map[string]string{}
for k, v := range tags {
tagsCopy[k] = v
}
// simple test
source := uuid.New()
logger.Debugf(context.Background(), source, tagsCopy, "test msg")
logs, err := waitForTrigger(t, dbMock)
if err != nil {
t.Error("expected to get logs but got none")
}
if logs.Msg != "test msg" {
t.Error("got wrong log entry")
}
if logs.T.After(time.Now().UTC()) {
t.Error("some thing is broken with the timestamp")
}
gotSource, ok := logs.Fields["source"]
if !ok {
t.Error("better logger was expected to add the source to the log tags")
}
if gotSource != source && gotSource != source.String() {
t.Errorf("want source id %v got %v", source, gotSource)
}
source = uuid.New()
// smart instance logs test
tags = map[string]string{}
tags["recipientType"] = "instance"
tags["callpath"] = "/"
tags["instance-id"] = source.String()
tagsCopy = map[string]string{}
for k, v := range tags {
tagsCopy[k] = v
}
logger.Debugf(context.Background(), source, tagsCopy, "test msg2")
logs, err = waitForTrigger(t, dbMock)
if err != nil {
t.Error("expected to get logs but got none")
}
if logs.Msg != "test msg2" {
t.Error("got wrong log entry")
}
if logs.T.After(time.Now().UTC()) {
t.Error("some thing is broken with the timestamp")
}
gotSource, ok = logs.Fields["source"]
if !ok {
t.Error("better logger was expected to add the source to the log tags")
}
if gotSource != source && gotSource != source.String() {
t.Errorf("want source id %v got %v", source, gotSource)
}
gotCallpath, ok := logs.Fields["callpath"]
if !ok {
t.Error("better logger was expected to add the source to the log tags")
}
callpath := "/" + source.String()
if gotCallpath != callpath {
t.Errorf("want callpath %v got %v", callpath, gotCallpath)
}
}
func Test_TracingLogger(t *testing.T) {
traceTagsMock := false
logger := logengine.SugarBetterJSONLogger{
Sugar: zap.S(),
AddTraceFrom: func(ctx context.Context, toTags map[string]string) map[string]string {
traceTagsMock = true
return toTags
},
}
tags := map[string]string{}
tags["recipientType"] = "server"
tagsCopy := map[string]string{}
for k, v := range tags {
tagsCopy[k] = v
}
// simple test
source := uuid.New()
logger.Debugf(context.Background(), source, tagsCopy, "test msg")
if !traceTagsMock {
t.Error("mock was not called")
}
}
func waitForTrigger(t *testing.T, c chan logengine.LogEntry) (*logengine.LogEntry, error) {
t.Helper()
var count int
for {
select {
case startedAction := <-c:
return &startedAction, nil
default:
if count > 3 {
return nil, fmt.Errorf("timeout")
}
time.Sleep(1 * time.Millisecond)
count++
}
}
}
|
package cos_test
import (
"testing"
"github.com/RitchieFlick/cos"
)
type testHardCode struct{}
func (t testHardCode) GetPhrases() ([]string, error) {
var list []string
list = append(list, "Remember: YAGNI (You Ain’t Gonna Need It)")
list = append(list, "Remember: 3-2-1 Backup Strategy")
return list, nil
}
func TestGetRandomPhrase(t *testing.T) {
api := cos.NewAPI()
api.AddDatastore(testHardCode{})
firstPhrase, err := api.GetRandomPhrase()
if err != nil {
t.Errorf("An error was raised!", err)
}
var samePhrase = true
for i := 0; i < 4; i++ {
api := cos.NewAPI()
api.AddDatastore(testHardCode{})
phrase, err := api.GetRandomPhrase()
if err != nil {
t.Errorf("An error was raised!", err)
}
t.Logf(phrase)
if firstPhrase != phrase {
samePhrase = false
}
}
if samePhrase {
t.Errorf("Only the same phrase was always returned!")
}
}
|
package repo
import (
"github.com/short-d/app-template/backend/app/entity"
)
// ChangeLog accesses changelog from storage, such as database.
type ChangeLog interface {
GetChangeLog() ([]entity.Change, error)
}
|
package v25
import (
"github.com/giantswarm/versionbundle"
)
func VersionBundle() versionbundle.Bundle {
return versionbundle.Bundle{
Changelogs: []versionbundle.Changelog{
{
Component: "cloudconfig",
Description: "Pin calico-kube-controllers to master.",
Kind: versionbundle.KindChanged,
},
{
Component: "kubernetes",
Description: "Mount /var/lib/kubelet directory in an EBS Volume.",
Kind: versionbundle.KindAdded,
},
},
Components: []versionbundle.Component{
{
Name: "calico",
Version: "3.5.1",
},
{
Name: "containerlinux",
Version: "2023.4.0",
},
{
Name: "docker",
Version: "18.06.1",
},
{
Name: "etcd",
Version: "3.3.12",
},
{
Name: "kubernetes",
Version: "1.13.4",
},
},
Name: "aws-operator",
Version: "4.9.0",
}
}
|
package decrypt
import (
"fmt"
"os/exec"
"syscall"
"emperror.dev/errors"
log "github.com/sirupsen/logrus"
)
func (h *Handler) StartProcess() (err error) {
envv := make([]string, 0)
binary, err := exec.LookPath(h.Args[0])
if err != nil {
return errors.Wrapf(err, "LookPath %s", h.Args[0])
}
for key, val := range h.Envs {
envv = append(envv, fmt.Sprintf("%s=%s", key, val))
}
log.Debugf("Found absolute path %s", binary)
return syscall.Exec(binary, h.Args, envv)
}
|
package main
import (
"math/rand"
"net/http"
"encoding/json"
"time"
"flag"
"bytes"
"log"
)
func main() {
idPtr := flag.Int("id", rand.Int(), "the id of this client")
urlPtr := flag.String("url", "http://127.0.0.1:80/", "the url to send events to")
seedPtr := flag.Int64("seed", time.Now().UTC().UnixNano(), "the seed for the random value")
flag.Parse()
rand.Seed(*seedPtr)
log.Println("client", *idPtr, "is up, sending traffic to", *urlPtr)
// set the maximum waiting time (between events) to 2 seconds
var maxWait int64 = 2000000000
for {
event := map[string]int{"id":*idPtr,"value":rand.Int()}
out, err := json.Marshal(event)
if err != nil {
//TODO handle error
log.Println("err:", err)
} else {
// parse address arg
_, err = http.Post(*urlPtr, "application/json", bytes.NewBuffer(out))
if err != nil {
log.Println("err:", err)
}
}
time.Sleep(time.Duration(rand.Int63n(maxWait)))
}
}
|
package trigger_service
import (
"fmt"
"ms/sun/shared/x"
"ms/sun_old/base"
)
type postTrig int
func (postTrig) OnInsert(ins []int) {
fmt.Println("OnInsert postTrig", ins)
}
func (postTrig) OnUpdate(ins []int) {
fmt.Println("OnUpdate postTrig", ins)
}
func (postTrig) OnDelete(ins []int) {
fmt.Println("OnDelete postTrig", ins)
x.NewHomeFanout_Deleter().PostId_In(ins).Delete(base.DB)
x.NewAction_Deleter().PostId_In(ins).Delete(base.DB)
}
//////
type actionTrig int
func (actionTrig) OnInsert(ins []int) {
fmt.Println("OnInsert actionTrig", ins)
}
func (actionTrig) OnUpdate(ins []int) {
fmt.Println("OnUpdate actionTrig", ins)
}
func (actionTrig) OnDelete(ins []int) {
fmt.Println("OnDelete actionTrig", ins)
x.NewActionFanout_Deleter().ActionId_In(ins).Delete(base.DB)
}
var s = x.TriggerModelListener{
Action: actionTrig(1),
Post: postTrig(1),
}
func init() {
listen()
}
func listen() {
x.ActivateTrigger = true
x.ArrTriggerListeners = append(x.ArrTriggerListeners, s)
}
|
package server
import (
"github.com/gin-gonic/contrib/secure"
"github.com/gin-gonic/gin"
"github.com/empirefox/esecend/admin"
"github.com/empirefox/esecend/captchar"
"github.com/empirefox/esecend/cdn"
"github.com/empirefox/esecend/config"
"github.com/empirefox/esecend/db-service"
"github.com/empirefox/esecend/front"
"github.com/empirefox/esecend/hub"
"github.com/empirefox/esecend/search"
"github.com/empirefox/esecend/sec"
"github.com/empirefox/esecend/sms"
"github.com/empirefox/esecend/wo2"
"github.com/empirefox/esecend/wx"
"github.com/empirefox/gotool/paas"
)
type Server struct {
*gin.Engine
IsDevMode bool
IsTLS bool
Config *config.Config
Cdn *cdn.Qiniu
WxClient *wx.WxClient
DB *dbsrv.DbService
Captcha captchar.Captchar
Auther *wo2.Auther
SecHandler *security.Handler
Admin *admin.Admin
SmsSender sms.Sender
ProductHub *hub.ProductHub
OrderHub *hub.OrderHub
NewsResource *search.Resource
ProductResource *search.Resource
OrderResource *search.Resource
}
func (s *Server) BuildEngine() {
corsMiddleWare := s.Cors("GET, PUT, POST, DELETE")
auth := s.Auther.Middleware()
mustAuthed := s.Auther.MustAuthed
router := gin.Default()
router.Use(secure.Secure(secure.Options{
SSLRedirect: true,
SSLProxyHeaders: map[string]string{
"X-Forwarded-Proto": "https",
},
IsDevelopment: s.IsDevMode,
}))
router.Use(corsMiddleWare)
if s.IsDevMode {
// router.GET("/faketoken", s.GetFakeToken)
}
router.POST(s.Config.Security.WxOauthPath, auth, s.Ok)
router.POST(s.Config.Weixin.PayNotifyURL, s.PostWxPayNotify)
router.GET("/profile", s.GetProfile)
router.GET("/store", s.GetTableAll(front.StoreTable))
router.GET("/carousel", s.GetTableAll(front.CarouselItemTable))
router.GET("/evals/:product_id", s.GetEvals)
router.GET("/category", s.GetTableAll(front.CategoryTable))
router.GET("/product/ls", s.GetProducts)
router.GET("/product/bundle/:matrix", s.GetProductsBundle)
router.GET("/product/1/:id", s.GetProduct)
router.GET("/product/attrs", s.GetProductAttrs)
router.GET("/product/skus/:id", s.GetSkus)
router.GET("/groupbuy", s.GetGroupBuy)
router.GET("/vips", s.GetVipIntros)
router.GET("/news", s.GetNews)
router.GET("/news/1/:id", s.GetNewsItem)
// auth
router.GET("/refresh_token/:refreshToken", auth, s.HasToken, s.GetRefreshToken)
router.GET("/headtoken", auth, mustAuthed, s.GetHeadUptoken)
router.GET("/captcha", auth, mustAuthed, s.GetCaptcha)
router.GET("/myfans", auth, mustAuthed, s.GetMyFans)
router.GET("/myvips", auth, mustAuthed, s.GetMyVips)
router.GET("/myqualifications", auth, mustAuthed, s.GetMyQualifications)
router.POST("/rebate", auth, mustAuthed, s.PostUserRebate)
router.POST("/withdraw", auth, mustAuthed, s.PostUserWithdraw)
router.POST("/set_user_info", auth, mustAuthed, s.PostSetUserInfo)
router.POST("/phone/prebind", auth, mustAuthed, s.PostPreBindPhone)
router.POST("/phone/bind", auth, mustAuthed, s.PostBindPhone)
router.GET("/paykey/preset", auth, mustAuthed, s.GetPresetPaykey)
router.POST("/paykey/set", auth, mustAuthed, s.PostSetPaykey)
router.GET("/wishlist", auth, mustAuthed, s.GetWishlist)
router.POST("/wishlist", auth, mustAuthed, s.PostWishlistAdd)
router.DELETE("/wishlist", auth, mustAuthed, s.DeleteWishlistItems)
router.GET("/wallet", auth, mustAuthed, s.GetWallet)
router.GET("/orders", auth, mustAuthed, s.GetOrders)
router.POST("/checkout", auth, mustAuthed, s.PostCheckout)
router.POST("/checkout_one", auth, mustAuthed, s.PostCheckoutOne)
router.POST("/order_pay", auth, mustAuthed, s.PostOrderPay)
router.POST("/order_wx_pay", auth, mustAuthed, s.PostOrderWxPrepay)
router.GET("/order/:id", auth, mustAuthed, s.GetOrder)
router.POST("/order_state", auth, mustAuthed, s.PostOrderState)
router.GET("/paied_order/:id", auth, mustAuthed, s.GetPaidOrder)
router.POST("/eval/:id", auth, mustAuthed, s.PostEval)
router.GET("/cart", auth, mustAuthed, s.GetCart)
router.POST("/cart", auth, mustAuthed, s.PostCartSave)
router.DELETE("/cart", auth, mustAuthed, s.DeleteCartItems)
router.GET("/addrs", auth, mustAuthed, s.GetAddrs)
router.POST("/addr", auth, mustAuthed, s.PostAddr)
router.DELETE("/addr/:id", auth, mustAuthed, s.DeleteAddr)
router.GET("/delivery/:order_id", auth, mustAuthed, s.GetDelivery)
router.DELETE("/logout", auth, s.DeleteLogout)
optPathIgnore := make(map[string]bool)
optPathIgnore[s.Config.Weixin.PayNotifyURL] = true
rs := router.Routes()
for _, r := range rs {
if r.Method == "OPTIONS" {
optPathIgnore[r.Path] = true
}
}
for _, r := range rs {
if !optPathIgnore[r.Path] {
optPathIgnore[r.Path] = true
router.OPTIONS(r.Path, s.Ok)
}
}
// for admin
a := router.Group("/admin", s.MustAdmin)
a.GET("/order_state", s.GetMgrOrderState)
a.GET("/reload_profile", s.GetMgrReloadProfile)
s.Engine = router
}
func (s *Server) StartRun() error {
go s.ProductHub.Run()
go s.OrderHub.Run()
if s.IsTLS {
return s.RunTLS(paas.BindAddr, "./1_api.silu333.com_bundle.crt", "./silu333_private.key")
}
return s.Run(paas.BindAddr)
}
|
package models
import (
"database/sql/driver"
"encoding/json"
"strconv"
"time"
"github.com/lib/pq"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/pkg/errors"
)
type (
JobSpecV2 struct {
ID int32 `gorm:"primary_key"`
OffchainreportingOracleSpecID int32
OffchainreportingOracleSpec *OffchainReportingOracleSpec `gorm:"save_association:true;association_autoupdate:true;association_autocreate:true"`
PipelineSpecID int32
}
OffchainReportingOracleSpec struct {
ID int32 `toml:"-" gorm:"primary_key"`
ContractAddress EIP55Address `toml:"contractAddress"`
P2PPeerID PeerID `toml:"p2pPeerID" gorm:"column:p2p_peer_id"`
P2PBootstrapPeers pq.StringArray `toml:"p2pBootstrapPeers" gorm:"column:p2p_bootstrap_peers;type:text[]"`
IsBootstrapPeer bool `toml:"isBootstrapPeer"`
EncryptedOCRKeyBundleID Sha256Hash `toml:"keyBundleID" gorm:"type:bytea"`
MonitoringEndpoint string `toml:"monitoringEndpoint"`
TransmitterAddress EIP55Address `toml:"transmitterAddress"`
ObservationTimeout Interval `toml:"observationTimeout" gorm:"type:bigint"`
BlockchainTimeout Interval `toml:"blockchainTimeout" gorm:"type:bigint"`
ContractConfigTrackerSubscribeInterval Interval `toml:"contractConfigTrackerSubscribeInterval"`
ContractConfigTrackerPollInterval Interval `toml:"contractConfigTrackerPollInterval" gorm:"type:bigint"`
ContractConfigConfirmations uint16 `toml:"contractConfigConfirmations"`
CreatedAt time.Time `toml:"-"`
UpdatedAt time.Time `toml:"-"`
}
PeerID peer.ID
)
func (js *JobSpecV2) SetID(value string) error {
jobID, err := strconv.ParseInt(value, 10, 32)
if err != nil {
return err
}
js.ID = int32(jobID)
return nil
}
func (p PeerID) String() string {
return peer.ID(p).String()
}
func (p *PeerID) UnmarshalText(bs []byte) error {
peerID, err := peer.Decode(string(bs))
if err != nil {
return errors.Wrapf(err, `PeerID#UnmarshalText("%v")`, string(bs))
}
*p = PeerID(peerID)
return nil
}
func (p *PeerID) Scan(value interface{}) error {
s, is := value.(string)
if !is {
return errors.Errorf("PeerID#Scan got %T, expected string", value)
}
*p = PeerID("")
return p.UnmarshalText([]byte(s))
}
func (p PeerID) Value() (driver.Value, error) {
return peer.Encode(peer.ID(p)), nil
}
func (p PeerID) MarshalJSON() ([]byte, error) {
return json.Marshal(peer.Encode(peer.ID(p)))
}
func (p *PeerID) UnmarshalJSON(input []byte) error {
var result string
if err := json.Unmarshal(input, &result); err != nil {
return err
}
peerId, err := peer.Decode(result)
if err != nil {
return err
}
*p = PeerID(peerId)
return nil
}
func (s *OffchainReportingOracleSpec) BeforeCreate() error {
s.CreatedAt = time.Now()
s.UpdatedAt = time.Now()
return nil
}
func (s *OffchainReportingOracleSpec) BeforeSave() error {
s.UpdatedAt = time.Now()
return nil
}
func (JobSpecV2) TableName() string { return "jobs" }
func (OffchainReportingOracleSpec) TableName() string { return "offchainreporting_oracle_specs" }
|
/*
Package callmeback is a generic server-side "come again in ..." middleware for gRPC.
In the case where a gRPC stream would be nice to provide but impossible
to deploy (see [1]) this interceptor enables a pool-based unary call
replacement for push-based streams.
It adds a trailer duration value indicating to the client the time it is safe
to pause for before calling again.
[1]: https://cloud.google.com/blog/products/compute/serve-cloud-run-requests-with-grpc-not-just-http
*/
package callmeback
|
package models
import (
u "businessense/utils"
"github.com/jinzhu/gorm"
)
//IssuePainPointsMap Type
type IssuePainPointsMap struct {
gorm.Model
Issue Issue
IssueID int
PainPoint PainPoint
PainPointID int
Relevance float64
}
type IssueRelevance struct {
IssueID int
Name string
Relevance float64
}
//Create IssuePainPointsMap
func (issuepainpointmap *IssuePainPointsMap) Create() map[string]interface{} {
GetDB().Create(issuepainpointmap)
response := u.Message(true, "Issue has been created")
response["issuepainpointmap"] = issuepainpointmap
return response
}
//
func GetIssuesRelevance(painpoints []string) []*IssueRelevance {
s := "select issue_id, issues.name, sum(relevance) as relevance " +
"from issue_pain_points_maps " +
"inner join issues on issues.id = issue_id " +
"where pain_point_id in (?) " +
"group by issue_id, issues.name "
issuesRelevance := make([]*IssueRelevance, 0)
GetDB().Raw(s, painpoints).Scan(&issuesRelevance)
return issuesRelevance
}
|
// DO NOT EDIT. This file was generated by "github.com/frk/gosql".
package testdata
import (
"github.com/frk/gosql"
)
func (q *InsertDefaultAllSliceQuery) Exec(c gosql.Conn) error {
var queryString = `INSERT INTO "test_user_with_defaults" AS u (
"email"
, "full_name"
, "is_active"
, "created_at"
, "updated_at"
) VALUES ` // `
for _, _ = range q.Users {
queryString += `(DEFAULT` +
`, DEFAULT` +
`, DEFAULT` +
`, DEFAULT` +
`, DEFAULT` +
`),`
}
queryString = queryString[:len(queryString)-1]
_, err := c.Exec(queryString)
return err
}
|
package frontend
import "github.com/getaceres/payment-demo/payment"
type Response interface {
GetLinks() map[string]string
}
// PaymentResponse is the response of a REST operation which returns a single payment
// swagger:model
type PaymentResponse struct {
Data payment.Payment `json:"data"`
Links map[string]string `json:"links"`
}
// PaymentListResponse is the response of a REST operation which returns a list of payments
// swagger:model
type PaymentListResponse struct {
Data []payment.Payment `json:"data"`
Links map[string]string `json:"links"`
}
func (r PaymentResponse) GetLinks() map[string]string {
return r.Links
}
func (r PaymentListResponse) GetLinks() map[string]string {
return r.Links
}
|
package main
import (
"log"
"net/http"
"os"
"github.com/breathingdust/house.api/controllers"
"github.com/breathingdust/house.api/db"
"github.com/gorilla/mux"
"github.com/rs/cors"
)
func main() {
r := mux.NewRouter().StrictSlash(true)
var mgoConn = os.Getenv("MGOCONN")
if mgoConn == "" {
log.Fatal("No connection string found.")
}
log.Println(mgoConn)
db := db.NewDatabase(mgoConn, "house")
tc := controllers.NewTransactionController(db)
hc := controllers.NewHomeController()
r.HandleFunc("/", hc.HomeHandler).Methods("GET")
r.HandleFunc("/transactions", tc.GetTransactionsHandler).Methods("GET")
r.HandleFunc("/transactions/{id}", tc.GetTransactionHandler).Methods("GET")
r.HandleFunc("/transactions", tc.PostTransactionHandler).Methods("POST")
http.Handle("/", r)
log.Println("Listening on port 8080")
c := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
})
handler := c.Handler(r)
log.Fatal(http.ListenAndServe(":8080", handler))
}
|
package env
import (
"fmt"
"os"
"strconv"
"strings"
"github.com/teejays/clog"
)
type AppEnv int
const (
DEV AppEnv = iota
STG
PROD
TEST
)
func (e AppEnv) String() string {
switch e {
case DEV:
return "DEV"
case STG:
return "STG"
case PROD:
return "PROD"
case TEST:
return "TEST"
default:
return ""
}
}
// GetAppEnv returns the DEV/STG/PROD environment that the code is running in.
func GetAppEnv() AppEnv {
defaultEnv := DEV
v, err := GetEnvVar("ENV")
if err != nil {
clog.Errorf("env: error getting env 'ENV': %v", err)
return defaultEnv
}
v = strings.ToLower(v)
if v == "prod" || v == "prd" || v == "production" {
return PROD
}
if v == "stage" || v == "stg" || v == "staging" {
return STG
}
if v == "dev" || v == "development" {
return DEV
}
if v == "test" || v == "testing" {
return TEST
}
return defaultEnv
}
// GetEnvVar returns the environment variables with key k. It errors if k is not setup or is empty.
func GetEnvVar(k string) (string, error) {
val := os.Getenv(k)
if strings.TrimSpace(val) == "" {
return "", fmt.Errorf("env variable %s is not set or is empty", k)
}
return val, nil
}
// GetEnvVarInt returns the environment variables with key k as an int. It errors if k is not setup, is empty, or is not an int.
func GetEnvVarInt(k string) (int, error) {
valStr, err := GetEnvVar(k)
if err != nil {
return 0, err
}
val, err := strconv.Atoi(valStr)
if err != nil {
return 0, fmt.Errorf("could not convert %s to int: %v", k, err)
}
return val, nil
}
// GetBoolOrDefault returns the true is an env variable is set to "true" or "1", false if set to "false" or "0"
// or default if is not set
func GetBoolOrDefault(k string, def bool) bool {
val := os.Getenv(k)
val = strings.TrimSpace(val)
if val == "true" || val == "1" {
return true
}
if val == "false" || val == "0" {
return false
}
return def
}
func SetEnvVars(vars map[string]string) error {
for k, v := range vars {
clog.Debugf("orm: Setting env var %s to %s", k, v)
if err := os.Setenv(k, v); err != nil {
return err
}
}
return nil
}
func SetEnvVarsMust(vars map[string]string) {
if err := SetEnvVars(vars); err != nil {
clog.Fatalf("could not set env vars: %v", err)
}
}
func UnsetEnvVars(vars map[string]string) error {
for k := range vars {
clog.Debugf("orm: Unetting env var %s", k)
if err := os.Unsetenv(k); err != nil {
return err
}
}
return nil
}
func UnsetEnvVarsMust(vars map[string]string) {
if err := UnsetEnvVars(vars); err != nil {
clog.Fatalf("could not unset env variables at the end of test: %v", err)
}
}
|
// 微信开放平台基类
package base
import (
"github.com/MrCHI/gowechat/wxcontext"
)
type OpenBase struct {
*wxcontext.Context
}
|
package main
import (
"net/http"
"fmt"
"io"
)
func d(w http.ResponseWriter,r *http.Request){ //(lne1) //this is the signature of handler interface
w.Header().Set("Key","from me")
w.Header().Set("Content-type","text/html ; charset=utf-8")
io.WriteString(w,`
<img src="/aman.jpg">
`) //calls this signature in main which calls the img function //"aman.jpg"
fmt.Fprintln(w,"<h1>Any code here</h1>")
}
func img(w http.ResponseWriter,r *http.Request){
/*w.Header().Set("Content-type","text/html ; charset=utf-8")
f,err:=os.Open("aman.jpg")
if err!=nil{
fmt.Println(err)
}
defer f.Close()
fs,err1:=f.Stat()
if err1!=nil{
fmt.Println(err1)
}
http.ServeContent(w,r,fs.Name(),fs.ModTime(),f)*/
http.ServeFile(w,r,"aman.jpg")
}
func main() {
http.HandleFunc("/dog",d)
http.HandleFunc("/aman.jpg",img)
http.ListenAndServe(":8080",nil) //d here is handler so it is handled by (lne1)
}
//what is the difference in using get or post |
package main
import (
"encoding/json"
"flag"
"fmt"
"strconv"
"github.com/dah8ra/ch4/github"
)
var issue github.Issue
var n = flag.Bool("n", false, "omit trailing newline")
var read = flag.Bool("r", false, "read ticket")
var create = flag.Bool("c", false, "create new ticket")
var ticketTitle = flag.String("t", "default", "tiket title")
var update = flag.Bool("u", false, "update ticket")
var done = flag.Bool("d", false, "close ticket")
var num = flag.Int("num", 0, "ticket number")
func main() {
flag.Parse()
url := createIssueUrl(*num)
fmt.Printf("-------> %s\n", url)
if *read {
result, _ := github.GetSingleIssue(url)
fmt.Printf("#%-5d %9.9s %.55s\n", result.Number, result.User.Login, result.Title)
return
}
issue.Title = *ticketTitle
if *done {
issue.State = "close"
}
input, _ := json.MarshalIndent(issue, "", " ")
if *create {
result, _ := github.CreateIssues(input)
fmt.Printf("#%-5d %9.9s %.55s\n", result.Number, result.User.Login, result.Title)
} else if *update {
result, _ := github.UpdateIssues(url, input)
fmt.Printf("#%-5d %9.9s %.55s\n", result.Number, result.User.Login, result.Title)
}
}
func createIssueUrl(num int) string {
return github.IssueUrl + strconv.Itoa(num)
}
|
package main
import (
"fmt"
"sync"
)
func testBroadCast() {
type Button struct {
Clicked *sync.Cond
}
button := Button{Clicked: sync.NewCond(&sync.Mutex{})}
subscribe := func(c *sync.Cond, fn func()) {
var goroutineRunning sync.WaitGroup
goroutineRunning.Add(1)
go func() {
goroutineRunning.Done()
c.L.Lock()
defer c.L.Unlock()
c.Wait() // This piece of shit will be in standing by mode right here.
fn()
}()
goroutineRunning.Wait()
}
var clickRegister sync.WaitGroup
clickRegister.Add(3)
subscribe(button.Clicked, func() { // I mean this
fmt.Println("Doing this")
clickRegister.Done()
})
subscribe(button.Clicked, func() { // and this
fmt.Println("Doing that")
clickRegister.Done()
})
subscribe(button.Clicked, func() { //and this too will stand still at c.Wait()
fmt.Println("Not doing anything")
clickRegister.Done()
})
button.Clicked.Broadcast() //until this piece of shit is triggered
clickRegister.Wait()
}
|
package dushengchen
/*
Submission:
https://leetcode.com/submissions/detail/482442786/
*/
func LargestRectangleArea(heights []int) int {
return largestRectangleArea(heights)
}
func largestRectangleArea(heights []int) int {
//dp_righ[i]存放i点的右边+1位置
dp_righ := make([]int, len(heights))
//dp_left[i]存放i点的左边-1位置
dp_left := make([]int, len(heights))
s := NewSliceStack(10)
for i := 0; i < len(heights); i++{
for {
idx, ok := s.Pop()
if !ok {
break
}
if heights[idx] > heights[i] {
dp_left[idx] = i
continue
}
s.Push(idx)
break
}
s.Push(i)
}
for {
idx, ok := s.Pop()
if !ok {
break
}
dp_left[idx] = len(heights)
}
for i := len(heights)-1; i >= 0; i--{
for {
idx, ok := s.Pop()
if !ok {
break
}
if heights[idx] > heights[i] {
dp_righ[idx] = i
continue
}
s.Push(idx)
break
}
s.Push(i)
}
for {
idx, ok := s.Pop()
if !ok {
break
}
dp_righ[idx] = -1
}
max := 0
for i := range heights {
a := heights[i] * (dp_left[i] - dp_righ[i] -1)
if a > max {
max = a
}
}
return max
}
|
package framework
func NoArgs(cmd *Command, args []string) bool {
return len(args) == 0
}
func RequiresMinArgs(min int) PositionalArgs {
return func(_ *Command, args []string) bool {
return len(args) >= min
}
}
func RequiresMaxArgs(max int) PositionalArgs {
return func(_ *Command, args []string) bool {
return len(args) <= max
}
}
func RequiresRangeArgs(min int, max int) PositionalArgs {
return func(_ *Command, args []string) bool {
l := len(args)
return l >= min && l <= max
}
}
func ExactArgs(number int) PositionalArgs {
return func(_ *Command, args []string) bool {
return len(args) == number
}
}
|
/*
Inspired by this SO question
As input you will be given a non-empty list of integers, where the first value is guaranteed to be non-zero.
To construct the output, walk from the start of the list, outputting each non-zero value along the way. When you encounter a zero, instead repeat the value you most recently added to the output.
You may write a program or function, and have input/output take any convenient format which does not encode extra information, as long as is still an ordered sequence of integers.
If outputting from a program, you may print a trailing newline. Except for this trailing newline, your output should be an acceptable input for your submission.
The shortest code in bytes wins.
Test Cases
[1, 0, 2, 0, 7, 7, 7, 0, 5, 0, 0, 0, 9] -> [1, 1, 2, 2, 7, 7, 7, 7, 5, 5, 5, 5, 9]
[1, 0, 0, 0, 0, 0] -> [1, 1, 1, 1, 1, 1]
[-1, 0, 5, 0, 0, -7] -> [-1, -1, 5, 5, 5, -7]
[23, 0, 0, -42, 0, 0, 0] -> [23, 23, 23, -42, -42, -42, -42]
[1, 2, 3, 4] -> [1, 2, 3, 4]
[-1234] -> [-1234]
*/
package main
import (
"fmt"
"reflect"
)
func main() {
test([]int{1, 0, 2, 0, 7, 7, 7, 0, 5, 0, 0, 0, 9}, []int{1, 1, 2, 2, 7, 7, 7, 7, 5, 5, 5, 5, 9})
test([]int{1, 0, 0, 0, 0, 0}, []int{1, 1, 1, 1, 1, 1})
test([]int{-1, 0, 5, 0, 0, -7}, []int{-1, -1, 5, 5, 5, -7})
test([]int{23, 0, 0, -42, 0, 0, 0}, []int{23, 23, 23, -42, -42, -42, -42})
test([]int{1, 2, 3, 4}, []int{1, 2, 3, 4})
test([]int{-1234}, []int{-1234})
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func test(a, r []int) {
p := coverzeroes(a)
fmt.Println(p)
assert(reflect.DeepEqual(p, r))
}
func coverzeroes(a []int) []int {
r := make([]int, len(a))
p := 0
for i, v := range a {
if v == 0 {
v = p
} else {
p = v
}
r[i] = v
}
return r
}
|
package httpclientinterception
import (
"net/http"
)
type interceptionOptions struct {
interceptorBuilder *interceptionBuilder
builders []*configurationBuilder
PanicOnMissingRegistration
OnMissingRegistration
}
// NewInterceptorOptions creates a new interceptionOptions object used to configure your interceptor
func NewInterceptorOptions() *interceptionOptions {
return &interceptionOptions{}
}
func (o *interceptionOptions) BeginScope() func() {
return func() {
}
}
func (o *interceptionOptions) Client() *http.Client {
t := &interceptorTransport{
RoundTripper: http.DefaultTransport,
PanicOnMissingRegistration: o.PanicOnMissingRegistration,
OnMissingRegistration: o.OnMissingRegistration,
config: o.builders,
}
return &http.Client{Transport: t}
}
func (o *interceptionOptions) Handler() http.Handler {
return &interceptionHandler{
PanicOnMissingRegistration: o.PanicOnMissingRegistration,
OnMissingRegistration: o.OnMissingRegistration,
config: *o.builders[0],
}
}
// PanicOnMissingRegistration causes HttpClientInterception to panic if no registration is matched
type PanicOnMissingRegistration bool
// OnMissingRegistration is invoked before the request is handled by the http.Client when a registration is missing
type OnMissingRegistration func(r *http.Request) *http.Response
|
package mysql
import (
"database/sql"
"flag"
"strings"
. "../../base"
"../../store"
_ "github.com/go-sql-driver/mysql"
)
var mysql string
func init() {
flag.StringVar(&mysql, "mysql", "root@/stock", "mysql uri")
store.Register("mysql", &Mysql{})
}
func (p *Mysql) Open() (err error) {
if p.db != nil {
p.Close()
}
dsn := mysql
if !strings.Contains(dsn, "?") {
dsn = dsn + "?"
}
if !strings.Contains(dsn, "parseTime=") {
dsn = dsn + "&parseTime=true"
}
if !strings.Contains(dsn, "loc=") {
dsn = dsn + "&loc=UTC"
}
db, err := sql.Open("mysql", dsn)
if err != nil {
return
}
p.db = db
p.SetMaxOpenConns(100)
return
}
func (p *Mysql) SetMaxOpenConns(n int) {
num := p.getMaxConnections()
if n < 0 {
n = 0
} else {
if n > num/2 {
n = num / 2
}
if n < 1 {
n = 1
}
}
p.db.SetMaxOpenConns(n)
}
type Mysql struct {
db *sql.DB
}
func (p *Mysql) Close() {
if p.db != nil {
p.db.Close()
p.db = nil
}
}
func (p *Mysql) getMaxConnections() int {
num := 0
p.db.QueryRow("SELECT @@max_connections").Scan(&num)
return num
}
|
package functions
import (
"fmt"
"regexp"
"strings"
igrpc "github.com/direktiv/direktiv/pkg/functions/grpc"
corev1 "k8s.io/api/core/v1"
"knative.dev/pkg/apis"
v1 "knative.dev/serving/pkg/apis/serving/v1"
)
const (
regex = "^[a-z]([-a-z0-9]{0,62}[a-z0-9])?$"
)
func validateLabel(name string) error {
matched, err := regexp.MatchString(regex, name)
if err != nil {
return err
}
if !matched {
return fmt.Errorf("invalid service name (must conform to regex: '%s')", regex)
}
return nil
}
func serviceBaseInfo(s *v1.Service) *igrpc.FunctionsBaseInfo {
var sz, scale int32
fmt.Sscan(s.Annotations[ServiceHeaderSize], &sz)
fmt.Sscan(s.Annotations[ServiceHeaderScale], &scale)
n := s.Labels[ServiceHeaderName]
ns := s.Labels[ServiceHeaderNamespaceID]
nsName := s.Labels[ServiceHeaderNamespaceName]
wf := s.Labels[ServiceHeaderWorkflowID]
path := s.Labels[ServiceHeaderPath]
rev := s.Labels[ServiceHeaderRevision]
img, cmd := containerFromList(s.Spec.ConfigurationSpec.Template.Spec.PodSpec.Containers)
info := &igrpc.FunctionsBaseInfo{
Name: &n,
Namespace: &ns,
Workflow: &wf,
Size: &sz,
MinScale: &scale,
Image: &img,
Cmd: &cmd,
NamespaceName: &nsName,
Path: &path,
Revision: &rev,
}
return info
}
func statusFromCondition(conditions []apis.Condition) (string, []*igrpc.FunctionsCondition) {
// status and status messages
status := string(corev1.ConditionUnknown)
var condList []*igrpc.FunctionsCondition
for m := range conditions {
cond := conditions[m]
if cond.Type == v1.RevisionConditionReady {
status = string(cond.Status)
}
ct := string(cond.Type)
st := string(cond.Status)
c := &igrpc.FunctionsCondition{
Name: &ct,
Status: &st,
Reason: &cond.Reason,
Message: &cond.Message,
}
condList = append(condList, c)
}
return status, condList
}
func containerFromList(containers []corev1.Container) (string, string) {
var img, cmd string
for a := range containers {
c := containers[a]
if c.Name == containerUser {
img = c.Image
cmd = strings.Join(c.Command, ", ")
}
}
return img, cmd
}
func createVolumes() []corev1.Volume {
volumes := []corev1.Volume{
{
Name: "workdir",
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
},
}
volumes = append(volumes, functionsConfig.extraVolumes...)
return volumes
}
|
package hands
import (
"fmt"
"image"
"image/color"
"image/color/palette"
"image/gif"
"os"
)
const (
w = 480
h = 84
)
// Data 手数
type Data struct {
img *image.Paletted
}
// CreateData ...
func CreateData() *Data {
return &Data{img: image.NewPaletted(image.Rect(0, 0, w, h), palette.Plan9)}
}
// MakeData 价格的右上角坐标
func (p *Data) MakeData(m *image.Image, left, top int) {
g := color.RGBA{0x0, 0xa8, 0x0, 0xff}
r := color.RGBA{0xfc, 0x54, 0x54, 0xff}
back := color.RGBA{0xff, 0xff, 0xff, 0xff}
for x := 0; x < w; x++ {
for y := 0; y < h; y++ {
c := (*m).At(x+left, y+top)
if c == g {
p.img.Set(x, y, g)
} else if c == r {
p.img.Set(x, y, r)
} else {
p.img.Set(x, y, back)
}
}
}
}
// Save ...
func (p *Data) Save() {
f, _ := os.Create(fmt.Sprintf("stockData.gif"))
defer f.Close()
gif.Encode(f, p.img, nil)
}
func (p *Data) getValue(x int) (cnt int) {
back := color.RGBA{0xff, 0xff, 0xff, 0xff}
// fmt.Println(x, "---", p.img.At(x, 0))
cnt = 0
for i := 0; i < h; i++ {
for j := 0; j < 5; j++ {
if p.img.At(j+x, i) != back {
// fmt.Println(j, i, "---", p.img.At(j+x, i))
cnt = h - i
return
}
}
}
return
}
func cutData(m *image.Image) {
p := CreateData()
p.MakeData(m, 50, 201)
p.Save()
}
// GetData ...
func GetData(m *image.Image) {
p := CreateData()
p.MakeData(m, 50, 201)
day := w / 6
v := make([]int, day, day)
for i := 0; i < day; i++ {
v[i] = p.getValue(i * 6)
fmt.Print(v[i], ", ")
}
// 检测数据
// for i := 0; i < day; i++ {
// p.img.Set(i*6+1, 84-v[i], color.RGBA{0, 0, 0xff, 0xff})
// }
// p.Save()
// 计算 ma5
// k5 := make([]int, day, day)
// k5[0] = 0
// k5[1] = 1
// for i := 2; i < day-2; i++ {
// k5[i] = (v[i-2] + v[i-1] + v[i-0] + v[i+1] + v[i+2]) / 5
// p.img.Set(i*6+2, 84-k5[i], color.RGBA{0x11, 0x11, 0xff, 0xff})
// }
// p.Save()
fmt.Println("")
}
|
package gorm
import (
"errors"
"fmt"
"sync"
"time"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/sunmi-OS/gocore/viper"
)
var Gorm sync.Map
var defaultName = "dbDefault"
var (
// ErrRecordNotFound record not found error, happens when haven't find any matched data when looking up with a struct
ErrRecordNotFound = errors.New("record not found")
// ErrInvalidSQL invalid SQL error, happens when you passed invalid SQL
ErrInvalidSQL = errors.New("invalid SQL")
// ErrInvalidTransaction invalid transaction when you are trying to `Commit` or `Rollback`
ErrInvalidTransaction = errors.New("no valid transaction")
// ErrCantStartTransaction can't start transaction when you are trying to start one with `Begin`
ErrCantStartTransaction = errors.New("can't start transaction")
// ErrUnaddressable unaddressable value
ErrUnaddressable = errors.New("using unaddressable value")
)
// 初始化Gorm
func NewDB(dbname string) {
var orm *gorm.DB
var err error
for orm, err = openORM(dbname); err != nil; {
fmt.Println("Database connection exception! 5 seconds to retry")
time.Sleep(5 * time.Second)
orm, err = openORM(dbname)
}
Gorm.LoadOrStore(dbname, orm)
}
// 设置获取db的默认值
func SetDefaultName(dbname string) {
defaultName = dbname
}
// 初始化Gorm
func UpdateDB(dbname string) error {
v, _ := Gorm.Load(dbname)
orm, err := openORM(dbname)
Gorm.Delete(dbname)
Gorm.LoadOrStore(dbname, orm)
err = v.(*gorm.DB).Close()
if err != nil {
return err
}
return nil
}
// 通过名称获取Gorm实例
func GetORMByName(dbname string) *gorm.DB {
v, _ := Gorm.Load(dbname)
return v.(*gorm.DB)
}
// 获取默认的Gorm实例
func GetORM() *gorm.DB {
v, _ := Gorm.Load(defaultName)
return v.(*gorm.DB)
}
func openORM(dbname string) (*gorm.DB, error) {
//默认配置
viper.C.SetDefault(dbname, map[string]interface{}{
"dbHost": "127.0.0.1",
"dbName": "phalgo",
"dbUser": "root",
"dbPasswd": "",
"dbPort": 3306,
"dbIdleconns_max": 20,
"dbOpenconns_max": 20,
"dbType": "mysql",
})
dbHost := viper.GetEnvConfig(dbname + ".dbHost")
dbName := viper.GetEnvConfig(dbname + ".dbName")
dbUser := viper.GetEnvConfig(dbname + ".dbUser")
dbPasswd := viper.GetEnvConfig(dbname + ".dbPasswd")
dbPort := viper.GetEnvConfig(dbname + ".dbPort")
dbType := viper.GetEnvConfig(dbname + ".dbType")
connectString := dbUser + ":" + dbPasswd + "@tcp(" + dbHost + ":" + dbPort + ")/" + dbName + "?charset=utf8&parseTime=true&loc=Local"
orm, err := gorm.Open(dbType, connectString)
if err != nil {
return nil, err
}
//连接池的空闲数大小
orm.DB().SetMaxIdleConns(viper.C.GetInt(dbname + ".dbIdleconns_max"))
//最大打开连接数
orm.DB().SetMaxOpenConns(viper.C.GetInt(dbname + ".dbOpenconns_max"))
return orm, err
}
|
// 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 cteutil
import (
"sync"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/disk"
"github.com/pingcap/tidb/util/memory"
)
var _ Storage = &StorageRC{}
// Storage is a temporary storage to store the intermidate data of CTE.
//
// Common usage as follows:
//
// storage.Lock()
// if !storage.Done() {
// fill all data into storage
// }
// storage.UnLock()
// read data from storage
type Storage interface {
// If is first called, will open underlying storage. Otherwise will add ref count by one.
OpenAndRef() error
// Minus ref count by one, if ref count is zero, close underlying storage.
DerefAndClose() (err error)
// SwapData swaps data of two storage.
// Other metainfo is not touched, such ref count/done flag etc.
SwapData(other Storage) error
// Reopen reset storage and related info.
// So the status of Storage is like a new created one.
Reopen() error
// Add chunk into underlying storage.
// Should return directly if chk is empty.
Add(chk *chunk.Chunk) error
// Get Chunk by index.
GetChunk(chkIdx int) (*chunk.Chunk, error)
// Get row by RowPtr.
GetRow(ptr chunk.RowPtr) (chunk.Row, error)
// NumChunks return chunk number of the underlying storage.
NumChunks() int
// NumRows return row number of the underlying storage.
NumRows() int
// Storage is not thread-safe.
// By using Lock(), users can achieve the purpose of ensuring thread safety.
Lock()
Unlock()
// Usually, Storage is filled first, then user can read it.
// User can check whether Storage is filled first, if not, they can fill it.
Done() bool
SetDone()
// Store error message, so we can return directly.
Error() error
SetError(err error)
// Readers use iter information to determine
// whether they need to read data from the beginning.
SetIter(iter int)
GetIter() int
GetMemTracker() *memory.Tracker
GetDiskTracker() *disk.Tracker
ActionSpill() *chunk.SpillDiskAction
}
// StorageRC implements Storage interface using RowContainer.
type StorageRC struct {
err error
rc *chunk.RowContainer
tp []*types.FieldType
refCnt int
chkSize int
iter int
mu sync.Mutex
done bool
}
// NewStorageRowContainer create a new StorageRC.
func NewStorageRowContainer(tp []*types.FieldType, chkSize int) *StorageRC {
return &StorageRC{tp: tp, chkSize: chkSize}
}
// OpenAndRef impls Storage OpenAndRef interface.
func (s *StorageRC) OpenAndRef() (err error) {
if !s.valid() {
s.rc = chunk.NewRowContainer(s.tp, s.chkSize)
s.refCnt = 1
s.iter = 0
} else {
s.refCnt++
}
return nil
}
// DerefAndClose impls Storage DerefAndClose interface.
func (s *StorageRC) DerefAndClose() (err error) {
if !s.valid() {
return errors.New("Storage not opend yet")
}
s.refCnt--
if s.refCnt < 0 {
return errors.New("Storage ref count is less than zero")
} else if s.refCnt == 0 {
s.refCnt = -1
s.done = false
s.err = nil
s.iter = 0
if err = s.rc.Close(); err != nil {
return err
}
s.rc = nil
}
return nil
}
// SwapData impls Storage Swap interface.
func (s *StorageRC) SwapData(other Storage) (err error) {
otherRC, ok := other.(*StorageRC)
if !ok {
return errors.New("cannot swap if underlying storages are different")
}
s.tp, otherRC.tp = otherRC.tp, s.tp
s.chkSize, otherRC.chkSize = otherRC.chkSize, s.chkSize
s.rc, otherRC.rc = otherRC.rc, s.rc
return nil
}
// Reopen impls Storage Reopen interface.
func (s *StorageRC) Reopen() (err error) {
if err = s.rc.Close(); err != nil {
return err
}
s.iter = 0
s.done = false
s.err = nil
// Create a new RowContainer.
// Because some meta infos in old RowContainer are not resetted.
// Such as memTracker/actionSpill etc. So we just use a new one.
s.rc = chunk.NewRowContainer(s.tp, s.chkSize)
return nil
}
// Add impls Storage Add interface.
func (s *StorageRC) Add(chk *chunk.Chunk) (err error) {
if !s.valid() {
return errors.New("Storage is not valid")
}
if chk.NumRows() == 0 {
return nil
}
return s.rc.Add(chk)
}
// GetChunk impls Storage GetChunk interface.
func (s *StorageRC) GetChunk(chkIdx int) (*chunk.Chunk, error) {
if !s.valid() {
return nil, errors.New("Storage is not valid")
}
return s.rc.GetChunk(chkIdx)
}
// GetRow impls Storage GetRow interface.
func (s *StorageRC) GetRow(ptr chunk.RowPtr) (chunk.Row, error) {
if !s.valid() {
return chunk.Row{}, errors.New("Storage is not valid")
}
return s.rc.GetRow(ptr)
}
// NumChunks impls Storage NumChunks interface.
func (s *StorageRC) NumChunks() int {
return s.rc.NumChunks()
}
// NumRows impls Storage NumRows interface.
func (s *StorageRC) NumRows() int {
return s.rc.NumRow()
}
// Lock impls Storage Lock interface.
func (s *StorageRC) Lock() {
s.mu.Lock()
}
// Unlock impls Storage Unlock interface.
func (s *StorageRC) Unlock() {
s.mu.Unlock()
}
// Done impls Storage Done interface.
func (s *StorageRC) Done() bool {
return s.done
}
// SetDone impls Storage SetDone interface.
func (s *StorageRC) SetDone() {
s.done = true
}
// Error impls Storage Error interface.
func (s *StorageRC) Error() error {
return s.err
}
// SetError impls Storage SetError interface.
func (s *StorageRC) SetError(err error) {
s.err = err
}
// SetIter impls Storage SetIter interface.
func (s *StorageRC) SetIter(iter int) {
s.iter = iter
}
// GetIter impls Storage GetIter interface.
func (s *StorageRC) GetIter() int {
return s.iter
}
// GetMemTracker impls Storage GetMemTracker interface.
func (s *StorageRC) GetMemTracker() *memory.Tracker {
return s.rc.GetMemTracker()
}
// GetDiskTracker impls Storage GetDiskTracker interface.
func (s *StorageRC) GetDiskTracker() *memory.Tracker {
return s.rc.GetDiskTracker()
}
// ActionSpill impls Storage ActionSpill interface.
func (s *StorageRC) ActionSpill() *chunk.SpillDiskAction {
return s.rc.ActionSpill()
}
// ActionSpillForTest is for test.
func (s *StorageRC) ActionSpillForTest() *chunk.SpillDiskAction {
return s.rc.ActionSpillForTest()
}
func (s *StorageRC) valid() bool {
return s.refCnt > 0 && s.rc != nil
}
|
package models
import (
"dappapi/global/orm"
"dappapi/tools"
"strings"
"golang.org/x/crypto/bcrypt"
)
type UserName struct {
Username string `gorm:"type:varchar(64)" json:"username" form:"username"`
}
type PassWord struct {
// 密码
Password string `gorm:"type:varchar(128)" json:"password" form:"password"`
}
type LoginM struct {
UserName
PassWord
}
type SysUserId struct {
UserId int `gorm:"column:id;primary_key;AUTO_INCREMENT" json:"id" form:"id"` // 编码
}
type SysUserB struct {
Phone string `gorm:"type:varchar(191)" json:"phone" form:"phone"` // 手机号
Name string `gorm:"type:varchar(191), column:name" json:"name"` //名称
Email string `gorm:"type:varchar(191)" json:"email" form:"email"` //邮箱
Remtoken string `gorm:"type:varchar(100)" json:"remtoken"` //备注
Uuid string `gorm:"type:char(36)" json:"uuid"` // uuid
Roleid int `gorm:"type:int(10)" json:"roleid" form:"roleid"`
Channel int `gorm:"type:int(10)" json:"channel"`
Ctime int64 `gorm:"type:bigint(20)" json:"ctime"`
Utime int64 `gorm:"type:bigint(20)" json:"utime"`
}
type SysUser struct {
SysUserId
SysUserB
LoginM
}
func (SysUser) TableName() string {
return "admin_user"
}
type SysUserPwd struct {
OldPassword string `json:"oldPassword" form:"passwd"`
NewPassword string `json:"newPassword" form:"newPasswd"`
}
type SysUserPage struct {
SysUserId
SysUserB
LoginM
DeptName string `gorm:"-" json:"deptName"`
}
type SysUserView struct {
SysUserId
SysUserB
LoginM
RoleCName string `gorm:"column:cname" json:"cname"`
}
func (e *SysUser) GetUserInfo() (SysUserView SysUserView, err error) {
table := orm.Eloquent["admin"].Table(e.TableName()).Select([]string{"admin_user.id", "admin_user.username", "admin_user.name",
"admin_user.roleid",
"admin_roles.cname"})
table = table.Joins("left join admin_roles on admin_roles.id=admin_user.roleid")
if e.UserId != 0 {
table = table.Where("admin_user.id = ?", e.UserId)
}
if e.Username != "" {
table = table.Where("admin_user.username = ?", e.Username)
}
if e.Password != "" {
table = table.Where("admin_user.password = ?", e.Password)
}
if err = table.First(&SysUserView).Error; err != nil {
return
}
return
}
func (e *SysUser) GetList() (SysUserView []SysUserView, err error) {
table := orm.Eloquent["admin"].Table(e.TableName()).Select([]string{"sys_user.*", "sys_role.role_name"})
table = table.Joins("left join sys_role on sys_user.role_id=sys_role.role_id")
if e.UserId != 0 {
table = table.Where("user_id = ?", e.UserId)
}
if e.Username != "" {
table = table.Where("username = ?", e.Username)
}
if e.Password != "" {
table = table.Where("password = ?", e.Password)
}
if err = table.Find(&SysUserView).Error; err != nil {
return
}
return
}
func (e *SysUser) GetPage(pageSize int, pageIndex int) ([]SysUserPage, int, error) {
var doc []SysUserPage
var count int
table := orm.Eloquent["admin"].Table(e.TableName())
if e.Channel != 0 {
table = table.Where("channel = ?", e.Channel)
}
if e.Username != "" {
table = table.Where("username like ?", "%"+e.Username+"%")
}
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
return nil, 0, err
}
table.Count(&count)
return doc, count, nil
}
//加密
func (e *SysUser) Encrypt() (err error) {
if e.Password == "" {
return
}
var hash []byte
if hash, err = bcrypt.GenerateFromPassword([]byte(e.Password), bcrypt.DefaultCost); err != nil {
return
} else {
e.Password = string(hash)
return
}
}
// 获取用户数据
func (e *SysUser) Get() (SysUserView SysUserView, err error) {
table := orm.Eloquent["admin"].Table(e.TableName()).Select([]string{"admin_user.*", "admin_roles.name", "admin_roles.cname"})
table = table.Joins("left join admin_roles on admin_user.roleid=admin_roles.id")
if e.UserId != 0 {
table = table.Where("id = ?", e.UserId)
}
if e.Username != "" {
table = table.Where("username = ?", e.Username)
}
if e.Password != "" {
table = table.Where("password = ?", e.Password)
}
if err = table.First(&SysUserView).Error; err != nil {
return
}
SysUserView.Password = ""
return
}
//添加
func (e SysUser) Insert() (id int, err error) {
if err = e.Encrypt(); err != nil {
return
}
// check 用户名
var count int
orm.Eloquent["admin"].Table(e.TableName()).Where("username = ?", e.Username).Count(&count)
if count > 0 {
tools.HasError(err, "用户已存在(代码500)", 500)
return
}
//添加数据
if err = orm.Eloquent["admin"].Table(e.TableName()).Create(&e).Error; err != nil {
return
}
id = e.UserId
return
}
//修改
func (e *SysUser) Update(id int) (update SysUser, err error) {
if e.Password != "" {
if err = e.Encrypt(); err != nil {
return
}
}
if err = orm.Eloquent["admin"].Table(e.TableName()).First(&update, id).Error; err != nil {
return
}
//参数1:是要修改的数据
//参数2:是修改的数据
if err = orm.Eloquent["admin"].Table(e.TableName()).Model(&update).Updates(&e).Error; err != nil {
return
}
return
}
func (e *SysUser) BatchDelete(id []int) (Result bool, err error) {
if err = orm.Eloquent["admin"].Table(e.TableName()).Where("user_id in (?)", id).Delete(&SysUser{}).Error; err != nil {
return
}
Result = true
return
}
func (e *SysUser) GetOne() (sysuser SysUser, err error) {
table := orm.Eloquent["admin"].Table(e.TableName())
if e.UserId != 0 {
table = table.Where("id = ?", e.UserId)
}
if err = table.First(&sysuser).Error; err != nil {
return
}
return
}
func (e *SysUser) SetPwd(pwd SysUserPwd) (Result bool, err error) {
user, err := e.GetOne()
if err != nil {
tools.HasError(err, "获取用户数据失败, 错误码-2", 500)
}
_, err = tools.CompareHashAndPassword(user.Password, pwd.OldPassword)
if err != nil {
if strings.Contains(err.Error(), "hashedPassword is not the hash of the given password") {
tools.HasError(err, "密码错误, 错误码-3", 500)
}
return
}
e.Password = pwd.NewPassword
_, err = e.Update(e.UserId)
tools.HasError(err, "更新密码失败, 错误码-4", 500)
return
}
|
package server
import (
"encoding/json"
"fmt"
"github.com/golang/glog"
"net/http"
"sync"
)
type BaseJsonData struct {
Message string `json:"message,omitempty"`
Code int `json:"code"`
Success bool `json:"success"`
Data interface{} `json:"data,omitempty"`
}
type ResponseData struct {
Success bool `json:"success"`
Code int `json:"code"`
Data interface{} `json:"data"`
Message string `json:"message"`
}
func NewBaseJsonData() *BaseJsonData {
return &BaseJsonData{}
}
func CheckError(err error){
if err !=nil{
fmt.Println("error info: ", err)
}
}
func SetHttpHeader(w http.ResponseWriter, req *http.Request){
Origin := req.Header.Get("Origin")
if Origin != "" {
w.Header().Add("Access-Control-Allow-Origin", Origin)
w.Header().Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE")
w.Header().Add("Access-Control-Allow-Headers", "x-requested-with,content-type")
w.Header().Add("Access-Control-Allow-Credentials", "true")
}
}
func retError(info interface{}, w http.ResponseWriter){
retValue := &ResponseData{}
retValue.Success = false
retValue.Code = 0
retValue.Message = "failed"
retValue.Data = info
bytes, _ := json.Marshal(retValue)
w.Write([]byte(bytes))
}
func AddVsersion(platform int){
glog.Info("start AddVsersion")
if platform > 0{
stmt, err := Db.Prepare(`update proxypro.config_version set version_code = version_code+1 where platform = ? `)
res, err := stmt.Exec(platform)
{
go CacheConfigJM()
}
if err != nil {
glog.Info(res)
glog.Info(err)
return
}
stmt.Close()
}else{
stmt, err := Db.Prepare(`update proxypro.config_version set version_code = version_code+1`)
res, err := stmt.Exec()
if err != nil {
glog.Info(res)
glog.Info(err)
return
}
stmt.Close()
}
}
var mutex sync.Mutex
var WebConfig_tmp_map_slice [](map[string]string)
func SaveWebConfig(){
mutex.Lock()
defer mutex.Unlock()
glog.Info("==========================SaveWebConfig=========================")
tmp_map_slice := make([](map[string]string),0)
{
Queryconfig, err := Db.Query(`SELECT companyNameID, subcompany, redirectUrl, DNS, platform, createTime
FROM proxypro.webConfig where estatus = 1;`)
if err != nil {
glog.Info(err)
}
for Queryconfig.Next(){
var companyNameID string
var subcompany string
var redirectUrl string
var DNS string
var platform string
var createTime string
err := Queryconfig.Scan(&companyNameID, &subcompany, &redirectUrl, &DNS, &platform, &createTime)
if err!=nil{
glog.Info(err)
}
tmp_map := make(map[string]string,0)
tmp_map["companyNameID"] = companyNameID
tmp_map["subcompany"] = subcompany
tmp_map["redirectUrl"] = redirectUrl
tmp_map["DNS"] = DNS
tmp_map["platform"] = platform
tmp_map["createTime"] = createTime
tmp_map_slice = append(tmp_map_slice, tmp_map)
}
Queryconfig.Close()
}
WebConfig_tmp_map_slice = make([](map[string]string),0)
WebConfig_tmp_map_slice = tmp_map_slice
glog.Info("WebConfig_tmp_map_slice")
}
|
package hex
type HexCode struct {
Code [][]int
Interval int
}
|
package main
import (
"runtime"
"time"
)
// what you will see, Hello and world will print in a random order depending on which thread is asleep
// and how long it takes to print the line out... this is an example of concurrancy and parallelism
func main() {
godur, _ := time.ParseDuration("10ms")
// we are telling our application it can only use 2 processes
runtime.GOMAXPROCS(2)
// anonamous function
go func() {
for i := 0; i < 100; i++ {
println("Hello")
time.Sleep(godur)
}
}()
// anonamous function
go func() {
for i := 0; i < 100; i++ {
println("World")
time.Sleep(godur)
}
}()
// without a sleep the function will close out before the go routines has a chance to finish
dur, _ := time.ParseDuration("1s")
time.Sleep(dur)
}
|
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
//1.传统方法
st := time.Now()
getSuShu01(72)
elapsed := time.Since(st)
fmt.Println("传统函数执行完成耗时:", elapsed)
//2.运用goroutine后
fmt.Println(runtime.NumCPU(), "核cpu")
st2 := time.Now()
getSuShu02(72)
elapsed2 := time.Since(st2)
fmt.Println("传统函数执行完成耗时:", elapsed2)
}
func getSuShu01(dir int) {
count := 0
for i := 2; i < dir; i++ {
if judgyIsPrime(i) {
fmt.Println("素数:", i)
count++
}
}
fmt.Println("素数总数为:", count)
}
//创建8个goroutine进行统计
func getSuShu02(dir int) {
intChan := make(chan int, dir)
primeChan := make(chan int, dir)
exitChan := make(chan bool, 8)
//向channel中写入数据
go func() {
for i := 0; i < dir; i++ {
intChan <- i
}
//写完以后关闭channel
close(intChan)
}()
//开启8个goroutine进行数据的读取和素数判断
for i := 0; i < 8; i++ {
go func() {
for {
v, ok := <-intChan //只有关闭的channel这样去读,才会读到ok=false,否则会报死锁
if ok && judgyIsPrime(v) {
primeChan <- v
}
//读到关闭标识,说明当前goroutine读取结束,写入结束标识
if !ok {
exitChan <- true
return
}
}
}()
}
//单独开启一个goroutine关闭退出标识,读取所有8个goroutine结束标识
go func() {
//读取八次,相当于已经读完
for i := 0; i < 8; i++ {
<-exitChan //此处是会产生堵塞的
}
close(primeChan)
}()
//协程关闭处
for {
v, ok := <-primeChan
if !ok {
break
}
//输出结果
//fmt.Println("总数为:", len(primeChan))
fmt.Println("素数为", v)
}
}
//判断是否是素数
func judgyIsPrime(data int) bool {
flag := true
for j := 2; j < data; j++ {
if data%j == 0 {
flag = false
}
}
return flag
}
//统计1-200000的数字中,哪些是素数
|
package evaluator
import (
"context"
"fmt"
"net/http"
"os"
envoy_config_cluster_v3 "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/rego"
"github.com/open-policy-agent/opa/types"
"github.com/pomerium/pomerium/authorize/evaluator/opa"
"github.com/pomerium/pomerium/authorize/internal/store"
"github.com/pomerium/pomerium/config"
"github.com/pomerium/pomerium/internal/telemetry/trace"
)
// HeadersRequest is the input to the headers.rego script.
type HeadersRequest struct {
EnableGoogleCloudServerlessAuthentication bool `json:"enable_google_cloud_serverless_authentication"`
EnableRoutingKey bool `json:"enable_routing_key"`
Issuer string `json:"issuer"`
KubernetesServiceAccountToken string `json:"kubernetes_service_account_token"`
ToAudience string `json:"to_audience"`
Session RequestSession `json:"session"`
ClientCertificate ClientCertificateInfo `json:"client_certificate"`
SetRequestHeaders map[string]string `json:"set_request_headers"`
}
// NewHeadersRequestFromPolicy creates a new HeadersRequest from a policy.
func NewHeadersRequestFromPolicy(policy *config.Policy, http RequestHTTP) *HeadersRequest {
input := new(HeadersRequest)
input.Issuer = http.Hostname
if policy != nil {
input.EnableGoogleCloudServerlessAuthentication = policy.EnableGoogleCloudServerlessAuthentication
input.EnableRoutingKey = policy.EnvoyOpts.GetLbPolicy() == envoy_config_cluster_v3.Cluster_RING_HASH ||
policy.EnvoyOpts.GetLbPolicy() == envoy_config_cluster_v3.Cluster_MAGLEV
input.KubernetesServiceAccountToken = policy.KubernetesServiceAccountToken
for _, wu := range policy.To {
input.ToAudience = "https://" + wu.URL.Hostname()
}
input.ClientCertificate = http.ClientCertificate
input.SetRequestHeaders = policy.SetRequestHeaders
}
return input
}
// HeadersResponse is the output from the headers.rego script.
type HeadersResponse struct {
Headers http.Header
}
var variableSubstitutionFunctionRegoOption = rego.Function2(®o.Function{
Name: "pomerium.variable_substitution",
Decl: types.NewFunction(
types.Args(
types.Named("input_string", types.S),
types.Named("replacements",
types.NewObject(nil, types.NewDynamicProperty(types.S, types.S))),
),
types.Named("output", types.S),
),
}, func(bctx rego.BuiltinContext, op1 *ast.Term, op2 *ast.Term) (*ast.Term, error) {
inputString, ok := op1.Value.(ast.String)
if !ok {
return nil, fmt.Errorf("invalid input_string type: %T", op1.Value)
}
replacements, ok := op2.Value.(ast.Object)
if !ok {
return nil, fmt.Errorf("invalid replacements type: %T", op2.Value)
}
var err error
output := os.Expand(string(inputString), func(key string) string {
if key == "$" {
return "$" // allow a dollar sign to be escaped using $$
}
r := replacements.Get(ast.StringTerm(key))
if r == nil {
return ""
}
s, ok := r.Value.(ast.String)
if !ok {
err = fmt.Errorf("invalid replacement value type for key %q: %T", key, r.Value)
}
return string(s)
})
if err != nil {
return nil, err
}
return ast.StringTerm(output), nil
})
// A HeadersEvaluator evaluates the headers.rego script.
type HeadersEvaluator struct {
q rego.PreparedEvalQuery
}
// NewHeadersEvaluator creates a new HeadersEvaluator.
func NewHeadersEvaluator(ctx context.Context, store *store.Store) (*HeadersEvaluator, error) {
r := rego.New(
rego.Store(store),
rego.Module("pomerium.headers", opa.HeadersRego),
rego.Query("result = data.pomerium.headers"),
getGoogleCloudServerlessHeadersRegoOption,
variableSubstitutionFunctionRegoOption,
store.GetDataBrokerRecordOption(),
)
q, err := r.PrepareForEval(ctx)
if err != nil {
return nil, err
}
return &HeadersEvaluator{
q: q,
}, nil
}
// Evaluate evaluates the headers.rego script.
func (e *HeadersEvaluator) Evaluate(ctx context.Context, req *HeadersRequest) (*HeadersResponse, error) {
ctx, span := trace.StartSpan(ctx, "authorize.HeadersEvaluator.Evaluate")
defer span.End()
rs, err := safeEval(ctx, e.q, rego.EvalInput(req))
if err != nil {
return nil, fmt.Errorf("authorize: error evaluating headers.rego: %w", err)
}
if len(rs) == 0 {
return nil, fmt.Errorf("authorize: unexpected empty result from evaluating headers.rego")
}
return &HeadersResponse{
Headers: e.getHeader(rs[0].Bindings),
}, nil
}
func (e *HeadersEvaluator) getHeader(vars rego.Vars) http.Header {
h := make(http.Header)
m, ok := vars["result"].(map[string]interface{})
if !ok {
return h
}
m, ok = m["identity_headers"].(map[string]interface{})
if !ok {
return h
}
for k := range m {
vs, ok := m[k].([]interface{})
if !ok {
continue
}
for _, v := range vs {
h.Add(k, fmt.Sprintf("%v", v))
}
}
return h
}
|
package app
import (
"io"
"log"
"net/http"
"strconv"
"github.com/Maxgis/ToyBrick/conf"
)
var mux map[string]func(http.ResponseWriter, *http.Request)
func init() {
if conf.Globals.IsOpenAdmin {
if conf.Globals.AdminPort == 0 {
return
}
server := http.Server{
Addr: ":" + strconv.Itoa(conf.Globals.AdminPort),
Handler: &AdminHandle{},
}
mux = make(map[string]func(http.ResponseWriter, *http.Request))
mux["/qps"] = qps
mux["/prof"] = prof
go func() {
err := server.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}()
log.Println("start admin ,port:", conf.Globals.AdminPort)
}
}
type AdminHandle struct{}
func (*AdminHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if h, ok := mux[r.URL.String()]; ok {
h(w, r)
}
io.WriteString(w, "URL"+r.URL.String())
}
func qps(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "qps")
}
func prof(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "prof")
}
|
package handler
import (
"net/http"
"github.com/nektro/mantle/pkg/db"
"github.com/nektro/mantle/pkg/ws"
"github.com/gorilla/mux"
)
// InvitesMe reads info about channel
func InvitesMe(w http.ResponseWriter, r *http.Request) {
_, user, err := apiBootstrapRequireLogin(r, w, http.MethodGet, true)
if err != nil {
return
}
usp := ws.UserPerms{}.From(user)
if !usp.ManageInvites {
writeAPIResponse(r, w, true, http.StatusOK, []db.Invite{})
return
}
writeAPIResponse(r, w, true, http.StatusOK, db.Invite{}.All())
}
// InvitesCreate reads info about channel
func InvitesCreate(w http.ResponseWriter, r *http.Request) {
_, user, err := apiBootstrapRequireLogin(r, w, http.MethodPost, true)
if err != nil {
return
}
usp := ws.UserPerms{}.From(user)
if !usp.ManageInvites {
writeAPIResponse(r, w, false, http.StatusForbidden, "users require the manage_invites permission to update invites.")
return
}
nr := db.CreateInvite()
w.WriteHeader(http.StatusCreated)
ws.BroadcastMessage(map[string]interface{}{
"type": "invite-new",
"invite": nr,
})
}
// InviteUpdate updates info about this invite
func InviteUpdate(w http.ResponseWriter, r *http.Request) {
_, user, err := apiBootstrapRequireLogin(r, w, http.MethodPut, true)
if err != nil {
return
}
usp := ws.UserPerms{}.From(user)
if !usp.ManageInvites {
return
}
if hGrabFormStrings(r, w, "p_name") != nil {
return
}
uu := mux.Vars(r)["uuid"]
rl, ok := db.QueryInviteByUID(uu)
if !ok {
return
}
successCb := func(rs *db.Invite, pk, pv string) {
writeAPIResponse(r, w, true, http.StatusOK, map[string]interface{}{
"invite": rs,
"key": pk,
"value": pv,
})
ws.BroadcastMessage(map[string]interface{}{
"type": "invite-update",
"invite": rs,
"key": pk,
"value": pv,
})
}
n := r.Form.Get("p_name")
v := r.Form.Get("p_value")
switch n {
case "max_uses":
_, x, err := hGrabInt(v)
if err != nil {
return
}
rl.SetMaxUses(x)
successCb(rl, n, v)
}
}
// InviteDelete updates info about this invite
func InviteDelete(w http.ResponseWriter, r *http.Request) {
_, user, err := apiBootstrapRequireLogin(r, w, http.MethodDelete, true)
if err != nil {
return
}
usp := ws.UserPerms{}.From(user)
if !usp.ManageInvites {
return
}
uu := mux.Vars(r)["uuid"]
v, ok := db.QueryInviteByUID(uu)
if !ok {
return
}
v.Delete()
ws.BroadcastMessage(map[string]interface{}{
"type": "invite-delete",
"invite": uu,
})
}
|
package main
func main() {
// if err := web.FindLinksInHtmlFile("pkg/web/golang.org.html"); err != nil {
// fmt.Printf("FindLinksInHtmlFile failed caused by: %v", err)
// os.Exit(1)
// }
// counter, err := web.CountElementsInHtmlFile("pkg/web/golang.org.html")
// if err != nil {
// fmt.Printf("FindLinksInHtmlFile failed caused by: %v", err)
// os.Exit(1)
// }
// fmt.Println(counter)
// words, images, err := web.CountWordsAndImages("https://golang.org")
// if err != nil {
// fmt.Printf("CountWordsAndImages failed caused by: %v", err)
// os.Exit(1)
// }
// fmt.Printf("words = %d, images = %d\n", words, images)
// err := web.PrintFromFile("pkg/web/short.html")
// if err != nil {
// fmt.Printf("PrintFromFile failed caused by: %v", err)
// os.Exit(1)
// }
//fmt.Println(math.Max(2, 5, 8, 61, -1, 9))
// fmt.Println(math.Min(2, 5, 8, 61, -1, 9))
// s := strings.JoinVariant(";", "a", "ee", "bb")
// fmt.Println(s)
// fmt.Println(general.ChangeReturnSquare(2, true))
// freq := solve.Constructor()
// freq.Push(3)
// freq.Push(2)
// freq.Push(9)
// freq.Push(10)
// fmt.Println(freq.Pop())
// fmt.Println(freq.Pop())
// fmt.Println(freq.Pop())
// fmt.Println(freq.Pop())
}
|
package main
import (
"fmt"
"github.com/uniqss/gomsglist"
"strings"
)
const TEST_PRODUCER_CONSUMER_COUNT = 10000
const TEST_MSG_COUNT_PER_PRODUCER = 100000
var producerDone [TEST_PRODUCER_CONSUMER_COUNT]bool
var producerDoneAll = false
var consumedmsgs [TEST_PRODUCER_CONSUMER_COUNT][TEST_MSG_COUNT_PER_PRODUCER]bool
var ML = gomsglist.NewSafeMsgList()
func producer(idx int64) {
var msg int64
var i int64 = 0
for ; i < TEST_MSG_COUNT_PER_PRODUCER; i++ {
msg = (idx << 32) | i
ML.Put(msg)
}
producerDone[idx] = true
for i := 0; i < TEST_PRODUCER_CONSUMER_COUNT; i++ {
if !producerDone[i] {
return
}
}
producerDoneAll = true
}
func consumer(idx int) {
for !producerDoneAll {
var err error = gomsglist.ErrNoNode
for err != nil {
var msg interface{}
msg, err = ML.Pop()
if err == nil {
msgint64 := msg.(int64)
consumerIdx := int32(msgint64 >> 32)
msgint := int32(msgint64 & 0xffffffff)
if consumedmsgs[consumerIdx][msgint] {
panic("this should not happen")
}
consumedmsgs[consumerIdx][msgint] = true
}
}
}
}
func check() bool {
for idx := 0; idx < TEST_PRODUCER_CONSUMER_COUNT; idx++ {
for i := 0; i < TEST_MSG_COUNT_PER_PRODUCER; i++ {
if !consumedmsgs[idx][i] {
return false
}
}
}
return true
}
func main() {
var i int64 = 0
for ; i < TEST_PRODUCER_CONSUMER_COUNT; i++ {
go producer(i)
}
var i2 = 0
//for ; i2 < TEST_PRODUCER_CONSUMER_COUNT; i2++ {
go consumer(i2)
//}
var input string
for {
fmt.Scanln(&input)
input = strings.ToLower(input)
if input == "e" || input == "exit" {
break
}
if input == "c" || input == "check" {
fmt.Println("check:", check())
}
}
}
|
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-11-19 19:54
# @File : lt_1423_Maximum_Points_You_Can_Obtain_from_Cards.go
# @Description :
# @Attention :
*/
package slide_window
import (
"fmt"
"testing"
)
func Test_maxScore(t *testing.T) {
scors := []int{1, 2, 3, 4, 5, 6, 1}
max := 3
score := maxScore(scors, max)
fmt.Println(score)
}
|
package main
import (
"container/heap"
"fmt"
"sort"
)
func main() {
fmt.Println(findKthLargest([]int{
3, 2, 1, 5, 6, 4,
}, 2))
fmt.Println(findKthLargest([]int{
3, 2, 3, 1, 2, 4, 5, 5, 6,
}, 4))
}
type kheap struct {
sort.IntSlice
}
func (h *kheap) Push(x interface{}) {
h.IntSlice = append(h.IntSlice, x.(int))
}
func (h *kheap) Pop() interface{} {
ans := h.IntSlice[len(h.IntSlice)-1]
h.IntSlice = h.IntSlice[:len(h.IntSlice)-1]
return ans
}
//Push(x any) // add x as element Len()
//Pop() any // remove and return element Len() - 1.
func findKthLargest(nums []int, k int) int {
kh := &kheap{}
for _, v := range nums {
heap.Push(kh, v)
if len(kh.IntSlice) > k {
heap.Pop(kh)
}
}
return kh.IntSlice[0]
}
|
/*
* @Author: Matt Meng
* @Date: 1970-01-01 08:00:00
* @LastEditors: Matt Meng
* @LastEditTime: 2020-10-11 11:58:42
* @Description: file content
*/
package jwt
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"gin-blog/pkg/e"
"gin-blog/pkg/util"
)
func JWT() gin.HandlerFunc {
return func(c *gin.Context) {
var code int
var data interface{}
code = e.SUCCESS
//token可以放在Header、Body或URL中,这里是在URL中解析
token := c.Query("token")
if token == "" {
code = e.INVALID_PARAMS
} else {
claims, err := util.ParseToken(token)
if err != nil {
code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
} else if time.Now().Unix() > claims.ExpiresAt { //在上一步ParseToken中已经有token.Valid的检查,如果超期,会返回err不为nil,这里是二次检查是否为超期,以返回对应错误码
code = e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT
}
}
if code != e.SUCCESS {
c.JSON(http.StatusUnauthorized, gin.H{
"code": code,
"msg": e.GetMsg(code),
"data": data,
})
//当鉴权失败,调用 Abort 防止挂起的其他handler执行,因为Abort不会终止当前handler,所以还需要调用return
c.Abort()
return
}
//Next只能在中间件middleware中调用,执行handler链中的下一个函数
c.Next()
}
}
|
package main
import (
"fmt"
"Goforit/015/DogPack"
)
func main() {
dog := DogPack.New("aaaa")
fmt.Println(dog)
// p := DogPack.GetNameStr(dog)
p := DogPack.GetNameStrA(&dog)
fmt.Println(p)
*p = "bbbb"
fmt.Println(dog)
} |
package user
import (
"testing"
"github.com/btnguyen2k/prom"
)
type TestSetupOrTeardownFunc func(t *testing.T, testName string)
func setupTest(t *testing.T, testName string, extraSetupFunc, extraTeardownFunc TestSetupOrTeardownFunc) func(t *testing.T) {
if extraSetupFunc != nil {
extraSetupFunc(t, testName)
}
return func(t *testing.T) {
if extraTeardownFunc != nil {
extraTeardownFunc(t, testName)
}
}
}
var (
testAdc *prom.AwsDynamodbConnect
testMc *prom.MongoConnect
testSqlc *prom.SqlConnect
)
/*----------------------------------------------------------------------*/
func doTestUserDao_Create(t *testing.T, testName string, userDao UserDao) {
u := NewUser(1357, "btnguyen2k").SetDisplayName("Thanh Nguyen").SetAesKey("aeskey")
ok, err := userDao.Create(u)
if err != nil || !ok {
t.Fatalf("%s failed: %#v / %s", testName, ok, err)
}
}
func doTestUserDao_Get(t *testing.T, testName string, userDao UserDao) {
u := NewUser(1357, "btnguyen2k").SetDisplayName("Thanh Nguyen").SetAesKey("aeskey")
ok, err := userDao.Create(u)
if err != nil || !ok {
t.Fatalf("%s failed: %#v / %s", testName, ok, err)
}
if u, err := userDao.Get("not_found"); err != nil {
t.Fatalf("%s failed: %s", testName, err)
} else if u != nil {
t.Fatalf("%s failed: user %s should not exist", testName, "not_found")
}
if u, err := userDao.Get("btnguyen2k"); err != nil {
t.Fatalf("%s failed: %s", testName, err)
} else if u == nil {
t.Fatalf("%s failed: nil", testName)
} else {
if v := u.GetId(); v != "btnguyen2k" {
t.Fatalf("%s failed: expected [%#v] but received [%#v]", testName, "btnguyen2k", v)
}
if v := u.GetTagVersion(); v != 1357 {
t.Fatalf("%s failed: expected [%#v] but received [%#v]", testName, 1357, v)
}
if v := u.GetDisplayName(); v != "Thanh Nguyen" {
t.Fatalf("%s failed: expected [%#v] but received [%#v]", testName, "Thanh Nguyen", v)
}
if v := u.GetAesKey(); v != "aeskey" {
t.Fatalf("%s failed: expected [%#v] but received [%#v]", testName, "aeskey", v)
}
}
}
func doTestUserDao_Delete(t *testing.T, testName string, userDao UserDao) {
u := NewUser(1357, "btnguyen2k").SetDisplayName("Thanh Nguyen").SetAesKey("aeskey")
ok, err := userDao.Create(u)
if err != nil || !ok {
t.Fatalf("%s failed: %#v / %s", testName, ok, err)
}
ok, err = userDao.Delete(u)
if err != nil {
t.Fatalf("%s failed: %s", testName, err)
} else if !ok {
t.Fatalf("%s failed: cannot delete user [%s]", testName, u.GetId())
}
u, err = userDao.Get("btnguyen2k")
if app, err := userDao.Get("exter"); err != nil {
t.Fatalf("%s failed: %s", testName, err)
} else if app != nil {
t.Fatalf("%s failed: user %s should not exist", testName, "userDao")
}
}
func doTestUserDao_Update(t *testing.T, testName string, userDao UserDao) {
u := NewUser(1357, "btnguyen2k").SetDisplayName("Thanh Nguyen").SetAesKey("aeskey")
userDao.Create(u)
u.SetDisplayName("nbthanh")
u.SetAesKey("newaeskey")
ok, err := userDao.Update(u)
if err != nil || !ok {
t.Fatalf("%s failed: %#v / %s", testName, ok, err)
}
if u, err := userDao.Get("btnguyen2k"); err != nil {
t.Fatalf("%s failed: %s", testName, err)
} else if u == nil {
t.Fatalf("%s failed: nil", testName)
} else {
if v := u.GetId(); v != "btnguyen2k" {
t.Fatalf("%s failed: expected [%#v] but received [%#v]", testName, "btnguyen2k", v)
}
if v := u.GetTagVersion(); v != 1357 {
t.Fatalf("%s failed: expected [%#v] but received [%#v]", testName, 1357, v)
}
if v := u.GetDisplayName(); v != "nbthanh" {
t.Fatalf("%s failed: expected [%#v] but received [%#v]", testName, "nbthanh", v)
}
if v := u.GetAesKey(); v != "newaeskey" {
t.Fatalf("%s failed: expected [%#v] but received [%#v]", testName, "newaeskey", v)
}
}
}
|
package main
import (
"fmt"
"math/rand"
"time"
)
/*
rand.Intn(3) [0,3) 左闭右开区间
*/
func main() {
//fmt.Println(rand.Int())
//rand.Int()
//
//fmt.Println(rand.Float64())
//rand.Float64()
//fmt.Println(rand.Float32())
rand.Seed(time.Now().UnixNano())
for i := 0; i < 100; i++ {
fmt.Print(rand.Intn(3)," ")
}
fmt.Println()
//randAnswer()
//rand.Int()
rand.Seed(time.Now().UnixNano())
// 获取 0.0 - 1.0 的随机数
fmt.Println(rand.Float64())
}
func getNumber() {
rand.Seed(time.Now().UnixNano())
// 获取 [0,10) 的随机数
fmt.Println(rand.Intn(10))
}
func getNumberMN(m, n int) int {
// 获取m-n 随机数
rand.Seed(time.Now().UnixNano())
num := rand.Intn(n-m+1) + m
return num
}
func randTest() {
//1、通过默认的随机数种子获取随机数.
//系统默认的rand对象,随机种子默认都是1
fmt.Println(rand.Int())
fmt.Println(rand.Intn(50))
fmt.Println(rand.Float64())
// 2、动态随机种子,生成随机资源,实例化成随机对象,通过随机对象获取随机数
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
randnum := r1.Intn(10)
fmt.Println(randnum)
//3、简写形式:动态种子来获取随机数
// [0,10]
rand.Seed(time.Now().UnixNano())
fmt.Println(rand.Intn(10))
fmt.Println(rand.Float64())
//[5,11]
num := rand.Intn(7) + 5
fmt.Println(num)
}
func randAnswer() {
answers := []string{
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes definitely",
"You may rely on it",
"As I see it yes",
"Most likely",
"Outlook good",
"Yes",
"Signs point to yes",
"Reply hazy try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don't count on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful",
}
// 设置 一个随机
rand.Seed(time.Now().UnixNano())
randnum := rand.Intn(len(answers))
fmt.Println("随机回答", answers[randnum])
}
|
// Copyright 2019-present 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package raftstore
import (
"bytes"
"context"
"io"
"sync/atomic"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/kvproto/pkg/raft_serverpb"
"github.com/pingcap/kvproto/pkg/tikvpb"
"github.com/pingcap/log"
"github.com/pingcap/tidb/store/mockstore/unistore/pd"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
)
type snapRunner struct {
config *Config
snapManager *SnapManager
router *router
sendingCount int64
receivingCount int64
pdCli pd.Client
}
func newSnapRunner(snapManager *SnapManager, config *Config, router *router, pdCli pd.Client) *snapRunner {
return &snapRunner{
config: config,
snapManager: snapManager,
router: router,
pdCli: pdCli,
}
}
func (r *snapRunner) handle(t task) {
switch t.tp {
case taskTypeSnapSend:
r.send(t.data.(sendSnapTask))
case taskTypeSnapRecv:
r.recv(t.data.(recvSnapTask))
}
}
func (r *snapRunner) send(t sendSnapTask) {
if n := atomic.LoadInt64(&r.sendingCount); n > int64(r.config.ConcurrentSendSnapLimit) {
log.Warn("too many sending snapshot tasks, drop send snap", zap.Uint64("to", t.storeID), zap.Stringer("snap", t.msg))
t.callback(errors.New("too many sending snapshot tasks"))
return
}
atomic.AddInt64(&r.sendingCount, 1)
defer atomic.AddInt64(&r.sendingCount, -1)
t.callback(r.sendSnap(t.storeID, t.msg))
}
const snapChunkLen = 1024 * 1024
func (r *snapRunner) sendSnap(storeID uint64, msg *raft_serverpb.RaftMessage) error {
start := time.Now()
msgSnap := msg.GetMessage().GetSnapshot()
snapKey, err := SnapKeyFromSnap(msgSnap)
if err != nil {
return err
}
r.snapManager.Register(snapKey, SnapEntrySending)
defer r.snapManager.Deregister(snapKey, SnapEntrySending)
snap, err := r.snapManager.GetSnapshotForSending(snapKey)
if err != nil {
return err
}
if !snap.Exists() {
return errors.Errorf("missing snap file: %v", snap.Path())
}
// Send snap shot is a low frequent operation, we can afford resolving the store address every time.
addr, err := getStoreAddr(storeID, r.pdCli)
if err != nil {
return err
}
cc, err := grpc.Dial(addr, grpc.WithInsecure(),
grpc.WithInitialWindowSize(int32(r.config.GrpcInitialWindowSize)),
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: r.config.GrpcKeepAliveTime,
Timeout: r.config.GrpcKeepAliveTimeout,
}))
if err != nil {
return err
}
client := tikvpb.NewTikvClient(cc)
stream, err := client.Snapshot(context.TODO())
if err != nil {
return err
}
err = stream.Send(&raft_serverpb.SnapshotChunk{Message: msg})
if err != nil {
return err
}
buf := make([]byte, snapChunkLen)
for remain := snap.TotalSize(); remain > 0; remain -= uint64(len(buf)) {
if remain < uint64(len(buf)) {
buf = buf[:remain]
}
_, err := io.ReadFull(snap, buf)
if err != nil {
return errors.Errorf("failed to read snapshot chunk: %v", err)
}
err = stream.Send(&raft_serverpb.SnapshotChunk{Data: buf})
if err != nil {
return err
}
}
_, err = stream.CloseAndRecv()
if err != nil {
return err
}
log.Info("sent snapshot", zap.Uint64("region id", snapKey.RegionID), zap.Stringer("snap key", snapKey), zap.Uint64("size", snap.TotalSize()), zap.Duration("duration", time.Since(start)))
return nil
}
func (r *snapRunner) recv(t recvSnapTask) {
if n := atomic.LoadInt64(&r.receivingCount); n > int64(r.config.ConcurrentRecvSnapLimit) {
log.Warn("too many recving snapshot tasks, ignore")
t.callback(errors.New("too many recving snapshot tasks"))
return
}
atomic.AddInt64(&r.receivingCount, 1)
defer atomic.AddInt64(&r.receivingCount, -1)
msg, err := r.recvSnap(t.stream)
if err == nil {
if err := r.router.sendRaftMessage(msg); err != nil {
log.S().Error(err)
}
}
t.callback(err)
}
func (r *snapRunner) recvSnap(stream tikvpb.Tikv_SnapshotServer) (*raft_serverpb.RaftMessage, error) {
head, err := stream.Recv()
if err != nil {
return nil, err
}
if head.GetMessage() == nil {
return nil, errors.New("no raft message in the first chunk")
}
message := head.GetMessage().GetMessage()
snapKey, err := SnapKeyFromSnap(message.GetSnapshot())
if err != nil {
return nil, errors.Errorf("failed to create snap key: %v", err)
}
data := message.GetSnapshot().GetData()
snap, err := r.snapManager.GetSnapshotForReceiving(snapKey, data)
if err != nil {
return nil, errors.Errorf("%v failed to create snapshot file: %v", snapKey, err)
}
if snap.Exists() {
log.Info("snapshot file already exists, skip receiving", zap.Stringer("snap key", snapKey), zap.String("file", snap.Path()))
if err := stream.SendAndClose(&raft_serverpb.Done{}); err != nil {
return nil, err
}
return head.GetMessage(), nil
}
r.snapManager.Register(snapKey, SnapEntryReceiving)
defer r.snapManager.Deregister(snapKey, SnapEntryReceiving)
for {
chunk, err := stream.Recv()
if err != nil {
if err == io.EOF {
break
}
return nil, err
}
data := chunk.GetData()
if len(data) == 0 {
return nil, errors.Errorf("%v receive chunk with empty data", snapKey)
}
_, err = bytes.NewReader(data).WriteTo(snap)
if err != nil {
return nil, errors.Errorf("%v failed to write snapshot file %v: %v", snapKey, snap.Path(), err)
}
}
err = snap.Save()
if err != nil {
return nil, err
}
if err := stream.SendAndClose(&raft_serverpb.Done{}); err != nil {
return nil, err
}
return head.GetMessage(), nil
}
|
package cbor
import (
"testing"
"github.com/polydawn/refmt/tok/fixtures"
)
func testBool(t *testing.T) {
t.Run("bool true", func(t *testing.T) {
seq := fixtures.SequenceMap["true"]
canon := b(0xf5)
t.Run("encode canonical", func(t *testing.T) {
checkEncoding(t, seq, canon, nil)
})
t.Run("decode canonical", func(t *testing.T) {
checkDecoding(t, seq, canon, nil)
})
})
t.Run("bool false", func(t *testing.T) {
seq := fixtures.SequenceMap["false"]
canon := b(0xf4)
t.Run("encode canonical", func(t *testing.T) {
checkEncoding(t, seq, canon, nil)
})
t.Run("decode canonical", func(t *testing.T) {
checkDecoding(t, seq, canon, nil)
})
})
}
|
package main
import (
"flag"
"fmt"
"math/rand"
"time"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/opt"
)
var (
fPath = flag.String("p", "/tmp/leveldb", "")
fSize = flag.Int("s", 200, "")
fSizeRange = flag.Int("size-range", 10, "")
fLength = flag.Int("l", 1024*1024*1024, "")
fReadWorker = flag.Int("r", 100, "")
fWriteWorker = flag.Int("w", 100, "")
fTicker = flag.Duration("t", 10*time.Second, "")
)
func main() {
flag.Parse()
db, err := leveldb.OpenFile(*fPath, &opt.Options{})
if err != nil {
panic(err)
}
size := func() int {
if *fSizeRange == 0 {
return *fSize
}
return rand.Intn(*fSizeRange) + *fSize
}
wch, rch := pool(*fLength, *fWriteWorker == 0)
rlatency := latency("read", *fTicker)
wlatency := latency("write", *fTicker)
for i := 0; i < *fWriteWorker; i++ {
go write(db, wch, wlatency, size)
}
for i := 0; i < *fReadWorker; i++ {
go read(db, rch, rlatency)
}
ch := make(chan struct{})
<-ch
}
func latency(name string, d time.Duration) chan time.Duration {
ch := make(chan time.Duration)
go func() {
ticker := time.NewTicker(d)
var total, tt time.Duration
var count, cc int64
for lat := range ch {
count++
cc++
total += lat
tt += lat
select {
case <-ticker.C:
fmt.Printf("total %s %15d, last %10d in %30s, qps %.2f, avg %30s \n", name, count, cc, tt.String(), float64(cc)/d.Seconds(), time.Duration(tt.Nanoseconds()/cc).String())
tt = time.Duration(0)
cc = 0
default:
}
}
}()
return ch
}
func pool(length int, readOnly bool) (chan []byte, chan []byte) {
ch := make(chan []byte)
ch2 := make(chan []byte)
pool := make([][]byte, 0, length)
go func() {
flag := false
for key := range ch {
if len(pool) < cap(pool) {
pool = append(pool, key)
continue
}
if !flag {
fmt.Println("yes!")
flag = true
}
idx := rand.Intn(len(pool))
pool[idx] = key
}
}()
go func() {
for {
if len(pool) == 0 {
time.Sleep(time.Second)
continue
}
idx := rand.Intn(len(pool))
ch2 <- pool[idx]
}
}()
return ch, ch2
}
func read(db *leveldb.DB, ch chan []byte, latency chan time.Duration) {
for key := range ch {
before := time.Now()
_, err := db.Get(key, nil)
if err != nil {
panic(err)
}
latency <- time.Since(before)
}
}
func write(db *leveldb.DB, ch chan []byte, latency chan time.Duration, size func() int) {
for {
id, _ := getMediaIdentifier()
key := []byte(id)
value := make([]byte, size())
if _, err := rand.Read(value); err != nil {
panic(err)
}
before := time.Now()
if err := db.Put(key, value, nil); err != nil {
panic(err)
}
latency <- time.Since(before)
ch <- key
}
}
func getMediaIdentifier() (string, error) {
alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" // Based on RFC 4648 Base32 alphabet
imageName := ""
bs := make([]byte, 30)
_, err := rand.Read(bs)
if err != nil {
return "", err
}
for _, b := range bs {
imageName += string(alphabet[(int(b) % len(alphabet))])
}
return imageName, nil
}
|
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func main() {
fmt.Println("This is main")
ch := make(chan string, 5)
go func() {
crawl(ch)
close(ch)
}()
analyze(ch)
}
func crawl(ch chan string) {
workers := 10
wg := sync.WaitGroup{}
for i := 0; i < workers; i++ {
wg.Add(1)
go func(i int) {
img := fmt.Sprintf("image_%v.png", i)
ch <- img
time.Sleep(time.Duration(rand.Intn(5)) * time.Second)
fmt.Printf("%s: crawled %s. sent to chanel ...\n", timestamp(), img)
wg.Done()
}(i)
}
wg.Wait()
}
func analyze(ch chan string) {
worker := 10
wg := sync.WaitGroup{}
for i := 0; i < worker; i++ {
wg.Add(1)
go func() {
for img := range ch {
time.Sleep(time.Duration(rand.Intn(5)) * time.Second)
fmt.Printf("%s: analyze %s\n", timestamp(), img)
}
wg.Done()
}()
}
wg.Wait()
}
func timestamp() string {
return time.Now().Format("05")
}
|
package schema
import (
"net/url"
"time"
)
// Server represents the configuration of the http server.
type Server struct {
Address *AddressTCP `koanf:"address" json:"address" jsonschema:"default=tcp://:9091/,title=Address" jsonschema_description:"The address to listen on"`
AssetPath string `koanf:"asset_path" json:"asset_path" jsonschema:"title=Asset Path" jsonschema_description:"The directory where the server asset overrides reside"`
DisableHealthcheck bool `koanf:"disable_healthcheck" json:"disable_healthcheck" jsonschema:"default=false,title=Disable Healthcheck" jsonschema_description:"Disables the healthcheck functionality"`
TLS ServerTLS `koanf:"tls" json:"tls" jsonschema:"title=TLS" jsonschema_description:"The server TLS configuration"`
Headers ServerHeaders `koanf:"headers" json:"headers" jsonschema:"title=Headers" jsonschema_description:"The server headers configuration"`
Endpoints ServerEndpoints `koanf:"endpoints" json:"endpoints" jsonschema:"title=Endpoints" jsonschema_description:"The server endpoints configuration"`
Buffers ServerBuffers `koanf:"buffers" json:"buffers" jsonschema:"title=Buffers" jsonschema_description:"The server buffers configuration"`
Timeouts ServerTimeouts `koanf:"timeouts" json:"timeouts" jsonschema:"title=Timeouts" jsonschema_description:"The server timeouts configuration"`
// Deprecated: use address instead.
Host string `koanf:"host" json:"host" jsonschema:"deprecated"`
// Deprecated: use address instead.
Port int `koanf:"port" json:"port" jsonschema:"deprecated"`
// Deprecated: use address instead.
Path string `koanf:"path" json:"path" jsonschema:"deprecated"`
}
// ServerEndpoints is the endpoints configuration for the HTTP server.
type ServerEndpoints struct {
EnablePprof bool `koanf:"enable_pprof" json:"enable_pprof" jsonschema:"default=false,title=Enable PProf" jsonschema_description:"Enables the developer specific pprof endpoints which should not be used in production and only used for debugging purposes"`
EnableExpvars bool `koanf:"enable_expvars" json:"enable_expvars" jsonschema:"default=false,title=Enable ExpVars" jsonschema_description:"Enables the developer specific ExpVars endpoints which should not be used in production and only used for debugging purposes"`
Authz map[string]ServerEndpointsAuthz `koanf:"authz" json:"authz" jsonschema:"title=Authz" jsonschema_description:"Configures the Authorization endpoints"`
}
// ServerEndpointsAuthz is the Authz endpoints configuration for the HTTP server.
type ServerEndpointsAuthz struct {
Implementation string `koanf:"implementation" json:"implementation" jsonschema:"enum=ForwardAuth,enum=AuthRequest,enum=ExtAuthz,enum=Legacy,title=Implementation" jsonschema_description:"The specific Authorization implementation to use for this endpoint"`
AuthnStrategies []ServerEndpointsAuthzAuthnStrategy `koanf:"authn_strategies" json:"authn_strategies" jsonschema:"title=Authn Strategies" jsonschema_description:"The specific Authorization strategies to use for this endpoint"`
}
// ServerEndpointsAuthzAuthnStrategy is the Authz endpoints configuration for the HTTP server.
type ServerEndpointsAuthzAuthnStrategy struct {
Name string `koanf:"name" json:"name" jsonschema:"enum=HeaderAuthorization,enum=HeaderProxyAuthorization,enum=HeaderAuthRequestProxyAuthorization,enum=HeaderLegacy,enum=CookieSession,title=Name" jsonschema_description:"The name of the Authorization strategy to use"`
}
// ServerTLS represents the configuration of the http servers TLS options.
type ServerTLS struct {
Certificate string `koanf:"certificate" json:"certificate" jsonschema:"title=Certificate" jsonschema_description:"Path to the Certificate"`
Key string `koanf:"key" json:"key" jsonschema:"title=Key" jsonschema_description:"Path to the Private Key"`
ClientCertificates []string `koanf:"client_certificates" json:"client_certificates" jsonschema:"uniqueItems,title=Client Certificates" jsonschema_description:"Path to the Client Certificates to trust for mTLS"`
}
// ServerHeaders represents the customization of the http server headers.
type ServerHeaders struct {
CSPTemplate CSPTemplate `koanf:"csp_template" json:"csp_template" jsonschema:"title=CSP Template" jsonschema_description:"The Content Security Policy template"`
}
// DefaultServerConfiguration represents the default values of the Server.
var DefaultServerConfiguration = Server{
Address: &AddressTCP{Address{true, false, -1, 9091, &url.URL{Scheme: AddressSchemeTCP, Host: ":9091", Path: "/"}}},
Buffers: ServerBuffers{
Read: 4096,
Write: 4096,
},
Timeouts: ServerTimeouts{
Read: time.Second * 6,
Write: time.Second * 6,
Idle: time.Second * 30,
},
Endpoints: ServerEndpoints{
Authz: map[string]ServerEndpointsAuthz{
"legacy": {
Implementation: "Legacy",
},
"auth-request": {
Implementation: "AuthRequest",
AuthnStrategies: []ServerEndpointsAuthzAuthnStrategy{
{
Name: "HeaderAuthRequestProxyAuthorization",
},
{
Name: "CookieSession",
},
},
},
"forward-auth": {
Implementation: "ForwardAuth",
AuthnStrategies: []ServerEndpointsAuthzAuthnStrategy{
{
Name: "HeaderProxyAuthorization",
},
{
Name: "CookieSession",
},
},
},
"ext-authz": {
Implementation: "ExtAuthz",
AuthnStrategies: []ServerEndpointsAuthzAuthnStrategy{
{
Name: "HeaderProxyAuthorization",
},
{
Name: "CookieSession",
},
},
},
},
},
}
|
package crontab
import (
"log"
"time"
"tpay_backend/model"
"tpay_backend/payapi/internal/svc"
"tpay_backend/utils"
)
// 平台收款卡今日已收清零
type PlatformCardReceivedClear struct {
CronBase
serverCtx *svc.ServiceContext
}
func NewPlatformCardReceivedClearTask(serverCtx *svc.ServiceContext) *PlatformCardReceivedClear {
t := &PlatformCardReceivedClear{}
t.LogCat = "平台收款卡-今日已收金额清零定时任务:"
t.LockExpire = time.Minute * 5
t.serverCtx = serverCtx
return t
}
// 运行定时任务
func (t *PlatformCardReceivedClear) Run() {
if t.Running { // 正在运行中
return
}
lockKey := GetLockKey(t.serverCtx.Config.Name, t)
lockValue := utils.NewUUID()
// 获取分布式锁
if !utils.GetDistributedLock(t.serverCtx.Redis, lockKey, lockValue, t.LockExpire) {
return
}
t.Running = true
t.Doing()
// 释放分布式锁
utils.ReleaseDistributedLock(t.serverCtx.Redis, lockKey, lockValue)
t.Running = false
}
func (t *PlatformCardReceivedClear) Doing() {
log.Println(t.LogCat + "------>PlatformCardReceivedClear.Doing...Start")
if err := model.NewPlatformBankCardModel(t.serverCtx.DbEngine).TodayReceivedClear(); err != nil {
log.Printf(t.LogCat+"平台收款卡今日已收金额清零失败, err=%v", err)
}
log.Println(t.LogCat + "------>PlatformCardReceivedClear.Doing...End")
}
|
package oauth2
import "context"
// authorization request struct
type AuthorizationRequest struct {
// The grant type identifier
GrantType GrantType
// The client identifier
Client ClientEntityInterface
// the User identifier
User UserEntityInterface
// An array of scope identifiers
Scopes []ScopeEntityInterface
// Has the user authorized the authorization request
IsAuthorizationApproved bool
// The redirect URI used in the request
RedirectUri string
// The state parameter on the authorization request
State string
// The code challenge (if provided)
CodeChallenge string
// The code challenge method (if provided)
CodeChallengeMethod string
// the request's context
ctx context.Context
}
func (t AuthorizationRequest) SetContext(ctx context.Context) {
t.ctx = ctx
}
|
package repository
import (
"context"
"errors"
"map-friend/src/domain/user"
)
func NewIUserRepository() user.IUserRepository {
// mock
users := map[uint]*user.User{
1: &user.User{
ID: 1,
Name: "ryomak",
},
2: &user.User{
ID: 2,
Name: "test user",
},
3: &user.User{
ID: 3,
Name: "test user3",
},
}
return &userRepository{users}
}
type userRepository struct {
users map[uint]*user.User
}
func (r *userRepository) FindOneByID(ctx context.Context, id uint) (*user.User, error) {
if val, ok := r.users[id]; !ok {
return nil, errors.New("not found")
} else {
return val, nil
}
}
|
package syntax
import (
"testing"
"os"
"path"
)
func TestStreamWriter(t *testing.T) {
pdir := "../../logs"
filename := "test.txt"
p := path.Join(pdir, filename)
err := os.MkdirAll(pdir, os.ModePerm)
if err != nil {
t.Error(err)
return
}
f, err := os.Create(p)
if err != nil {
t.Error(err)
return
}
f.Write([]byte("hello\n"))
f.Write([]byte("world\n"))
f.Close()
}
|
// +build linux
package sysdnotify
import (
"net"
"os"
)
func init() {
if notifySocketName := os.Getenv("NOTIFY_SOCKET"); notifySocketName != "" {
socket = &net.UnixAddr{
Name: notifySocketName,
Net: "unixgram",
}
}
}
|
/*
* @lc app=leetcode.cn id=51 lang=golang
*
* [51] N 皇后
*/
// @lc code=start
package main
import "fmt"
func main() {
n := 4
allResult := solveNQueens(n)
for i := 0 ; i < len(allResult) ; i++ {
for j := 0 ; j < n ; j++ {
fmt.Println(allResult[i][j])
}
fmt.Println()
}
}
func solveNQueens(n int) [][]string {
allResult := [][]string{}
result := make([]int, n)
var dfs func (int, int)
dfs = func(row int, max int) {
if row == max {
tmp := printString(result, max)
allResult = append(allResult, tmp)
return
}
for column := 0 ; column < max ; column++ {
if isOk(row, column, max, result) {
result[row] = column
dfs(row+1, max)
}
}
}
dfs(0, n)
return allResult
}
func isOk(row, column, max int, result []int) bool {
leftUp := column - 1
rightUp := column + 1
for i := row - 1 ; i >= 0 ; i-- {
if result[i] == column {
return false
}
if leftUp >= 0 {
if result[i] == leftUp {
return false
}
}
if rightUp < max {
if result[i] == rightUp {
return false
}
}
leftUp--
rightUp++
}
return true
}
func printString(result []int, max int) []string {
res := []string{}
for i := 0 ; i < max ; i ++ {
tmp := ""
for j := 0 ; j < max ; j++ {
if result[i] == j {
tmp = tmp + "Q"
} else {
tmp = tmp + "."
}
}
res = append(res, tmp)
}
return res
}
// @lc code=end
|
package main
import "fmt"
func main() {
// 创建管道
ch := make(chan int, 10)
// 循环写入值
for i := 0; i < 10; i++ {
ch <- i
}
// 关闭管道
close(ch)
// for range循环遍历管道的值(管道没有key)
for value := range ch {
fmt.Println(value)
}
// 通过上述的操作,能够打印值,但是出出现一个deadlock的死锁错误,也就说我们需要关闭管道
for i := 0; i < 10; i++ {
fmt.Println(<- ch)
}
}
|
package core
import (
"net/http"
"github.com/gin-gonic/gin"
)
// addCafes godoc
// @Summary Register with a Cafe
// @Description Registers with a cafe and saves an expiring service session token. An access
// @Description token is required to register, and should be obtained separately from the target
// @Description Cafe
// @Tags cafes
// @Produce application/json
// @Param X-Textile-Args header string true "cafe id"
// @Param X-Textile-Opts header string false "token: An access token supplied by the Cafe" default(token=)
// @Success 201 {object} pb.CafeSession "cafe session"
// @Failure 400 {string} string "Bad Request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /cafes [post]
func (a *api) addCafes(g *gin.Context) {
args, err := a.readArgs(g)
if err != nil {
a.abort500(g, err)
return
}
if len(args) == 0 {
g.String(http.StatusBadRequest, "missing cafe id")
return
}
opts, err := a.readOpts(g)
if err != nil {
a.abort500(g, err)
return
}
token := opts["token"]
if token == "" {
g.String(http.StatusBadRequest, "missing access token")
return
}
session, err := a.node.RegisterCafe(args[0], token)
if err != nil {
a.abort500(g, err)
return
}
go a.node.cafeOutbox.Flush()
pbJSON(g, http.StatusCreated, session)
}
// lsCafes godoc
// @Summary List info about all active cafe sessions
// @Description List info about all active cafe sessions. Cafes are other peers on the network
// @Description who offer pinning, backup, and inbox services
// @Tags cafes
// @Produce application/json
// @Success 200 {object} pb.CafeSessionList "cafe sessions"
// @Failure 500 {string} string "Internal Server Error"
// @Router /cafes [get]
func (a *api) lsCafes(g *gin.Context) {
pbJSON(g, http.StatusOK, a.node.CafeSessions())
}
// getCafes godoc
// @Summary Gets and displays info about a cafe session
// @Description Gets and displays info about a cafe session. Cafes are other peers on the network
// @Description who offer pinning, backup, and inbox services
// @Tags cafes
// @Produce application/json
// @Param id path string true "cafe id"
// @Success 200 {object} pb.CafeSession "cafe session"
// @Failure 404 {string} string "Not Found"
// @Failure 500 {string} string "Internal Server Error"
// @Router /cafes/{id} [get]
func (a *api) getCafes(g *gin.Context) {
id := g.Param("id")
session, err := a.node.CafeSession(id)
if err != nil {
a.abort500(g, err)
return
}
if session == nil {
g.String(http.StatusNotFound, "cafe not found")
return
}
pbJSON(g, http.StatusOK, session)
}
// rmCafes godoc
// @Summary Deregisters a cafe
// @Description Deregisters with a cafe (content will expire based on the cafe's service rules)
// @Tags cafes
// @Param id path string true "cafe id"
// @Success 204 {string} string "ok"
// @Failure 500 {string} string "Internal Server Error"
// @Router /cafes/{id} [delete]
func (a *api) rmCafes(g *gin.Context) {
id := g.Param("id")
err := a.node.DeregisterCafe(id)
if err != nil {
a.abort500(g, err)
return
}
go a.node.cafeOutbox.Flush()
g.Status(http.StatusNoContent)
}
// checkCafeMessages godoc
// @Summary Check for messages at all cafes
// @Description Check for messages at all cafes. New messages are downloaded and processed
// @Description opportunistically.
// @Tags cafes
// @Produce text/plain
// @Success 200 {string} string "ok"
// @Failure 500 {string} string "Internal Server Error"
// @Router /cafes/messages [post]
func (a *api) checkCafeMessages(g *gin.Context) {
err := a.node.CheckCafeMessages()
if err != nil {
a.abort500(g, err)
return
}
go a.node.cafeOutbox.Flush()
g.String(http.StatusOK, "ok")
}
|
package builder
type BuildProcess interface {
SetWeels() BuildProcess
SetSeats() BuildProcess
SetStructure() BuildProcess
GetVehicle() VehicleProduct
}
// Director
type ManufacturingDirector struct {
builder BuildProcess
}
func (f *ManufacturingDirector) Construct() {
f.builder.SetStructure().SetWeels().SetSeats()
}
func (f *ManufacturingDirector) SetBuilder(b BuildProcess) {
f.builder = b
}
// Product
type VehicleProduct struct {
Weels int
Seats int
Structure string
}
// A builder of type Car
type CarBuilder struct {
v VehicleProduct
}
func (c *CarBuilder) SetWeels() BuildProcess {
c.v.Weels = 4
return c
}
func (c *CarBuilder) SetSeats() BuildProcess {
c.v.Seats = 3
return c
}
func (c *CarBuilder) SetStructure() BuildProcess {
c.v.Structure = "Car"
return c
}
func (c *CarBuilder) GetVehicle() VehicleProduct {
return c.v
}
// A builder of type Motorbike
type BikeBuilder struct {
v VehicleProduct
}
func (b *BikeBuilder) SetWeels() BuildProcess {
b.v.Weels = 2
return b
}
func (b *BikeBuilder) SetSeats() BuildProcess {
b.v.Seats = 1
return b
}
func (b *BikeBuilder) SetStructure() BuildProcess {
b.v.Structure = "Motorbike"
return b
}
func (b *BikeBuilder) GetVehicle() VehicleProduct {
return b.v
}
// A builder of type Bus
type BusBuilder struct {
v VehicleProduct
}
func (b *BusBuilder) SetWeels() BuildProcess {
b.v.Weels = 8
return b
}
func (b *BusBuilder) SetSeats() BuildProcess {
b.v.Seats = 100
return b
}
func (b *BusBuilder) SetStructure() BuildProcess {
b.v.Structure = "Bus"
return b
}
func (b *BusBuilder) GetVehicle() VehicleProduct {
return b.v
}
|
package middleware
import (
"time"
"github.com/valyala/fasthttp"
"golang.org/x/time/rate"
"github.com/any-lyu/go.library/errors"
)
// RateHandler 限流
// bursts of at most b tokens.
func RateHandler(h fasthttp.RequestHandler, b int) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
limiter := rate.NewLimiter(rate.Every(time.Second), b)
if limiter.Allow() {
h(ctx)
return
}
ctx.Error(errors.ErrSystemBusy.Error(), errors.ErrCode(errors.ErrSystemBusy))
return
}
}
|
package aoc2019
import (
"fmt"
"strconv"
aoc "github.com/janreggie/aoc/internal"
)
type spaceImage [6][25]int8 // 6 tall, 25 wide
func newSpaceImage(raw string) (sp spaceImage, err error) {
if len(raw) != 150 {
err = fmt.Errorf("raw is length %v, should be 150", len(raw))
return
}
for ii := 0; ii < 6; ii++ {
for jj := 0; jj < 25; jj++ {
switch val := raw[ii*25+jj]; val {
case '0':
sp[ii][jj] = 0
case '1':
sp[ii][jj] = 1
case '2':
sp[ii][jj] = 2
default:
err = fmt.Errorf("invalid byte %v on position %v", string(val), ii*25+jj)
return
}
}
}
return
}
func (sp *spaceImage) count() (count [3]int) {
for ii := range sp {
for jj := range sp[ii] {
switch sp[ii][jj] {
case 0:
count[0]++
case 1:
count[1]++
case 2:
count[2]++
}
}
}
return
}
// Day08 solves the eighth day puzzle "Space Image Format".
//
// Input
//
// A string of length 15000, which only consists of '0', '1', and '2'.
//
// Notes
//
// The second answer should not be used as-is,
// but requires the interpretation of a human.
// The output will resemble pixel art made out of blocks,
// which spells out a word that the user must input manually.
// My output is as follows:
//
// ██ ██ ███ ██ ██ █ ██ █
// ██ █ ██ █ ██ █ ██ █ ██ █
// ██ █ ████ ████ ██ █ █
// ██ █ █ █ ████ ██ █ ██ █
// ██ █ ██ █ ██ █ ██ █ ██ █
// █ ███ ██ ███ ██ ██ █
//
// It may be hard to read but it does spell out UGCUH.
func Day08(input string) (answer1, answer2 string, err error) {
allLayers := make([]spaceImage, 0)
for _, line := range aoc.SplitLines(input) {
// split for every 150 bytes
for i := 0; (i+1)*150 <= len(line); i++ {
sp, e := newSpaceImage(line[i*150 : (i+1)*150])
if e != nil {
err = fmt.Errorf("can't create image from %v: %v", line, e)
return
}
allLayers = append(allLayers, sp)
}
}
fewestZeroes := allLayers[0].count()[0] // got it? good.
for _, layer := range allLayers {
if counts := layer.count(); counts[0] < fewestZeroes {
fewestZeroes = counts[0]
answer1 = strconv.Itoa(counts[1] * counts[2])
}
}
// now for the second answer...
answer2 += "the following:\n"
for ii := 0; ii < 6; ii++ {
for jj := 0; jj < 25; jj++ {
for _, layer := range allLayers {
if layer[ii][jj] == 0 {
answer2 += "█"
break
} else if layer[ii][jj] == 1 {
answer2 += " "
break
}
}
}
answer2 += "\n"
}
return
}
|
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"regexp"
)
func main() {
byts, err := ioutil.ReadFile("D:\\workspace\\go\\learnGo\\itcast\\src\\01_20H\\day05_异常_文本文件处理\\html\\day21.html")
if err != nil {
fmt.Print(err)
}
str := bytes.NewBuffer(byts).String()
reg := regexp.MustCompile("<p>(.*)</p>")
strSli := reg.FindAllStringSubmatch(str, -1)
fmt.Println(strSli, len(strSli))
f, err := os.Create("D:\\workspace\\go\\learnGo\\itcast\\src\\01_20H\\day05_异常_文本文件处理\\html\\day21.txt")
if err != nil {
fmt.Println(err)
}
for _, v1 := range strSli {
f.WriteString(fmt.Sprintf("%s\n", v1[1]))
}
}
|
package main
import (
"github.com/aws/aws-lambda-go/lambda"
"bartenderAsFunction/model"
"bartenderAsFunction/dao"
"fmt"
)
var DataConnectionManager dao.CommandConnectionInterface
func Handler(iotRequest model.CommandRequest) error {
// TODO 1. generate id to the command (uuid) see github.com/satori/go.uuid
uid, _ := "", ""
fmt.Println(uid)
// TODO 2. generate command (model.command) with date in utc format
command := model.Command{}
fmt.Println(command)
// TODO 3. save command in dynamo. Hint, there are a dao package with all you need. Use the DataConnectionManager var
// TODO return the error if it exist
//or return nil if everything is ok
return nil
}
func main() {
DataConnectionManager = dao.CreateCommandConnection()
lambda.Start(Handler)
}
|
package app
import (
"sync"
"github.com/anihouse/bot/config"
"github.com/anihouse/bot"
"github.com/bwmarrin/discordgo"
)
type (
HandlerFunc func(*Context)
HandlerChain []HandlerFunc
)
type Application struct {
middleware
modules map[string]*Module
}
func (chain *HandlerChain) append(handlers ...HandlerFunc) {
*chain = append(*chain, handlers...)
}
func (a *Application) onHandle(s *discordgo.Session, m *discordgo.MessageCreate) {
if m.GuildID != config.Bot.GuildID {
return
}
var ctxs []*Context
wg := sync.WaitGroup{}
wg.Add(len(a.modules))
for _, module := range a.modules {
module.findCommands(&wg, s, m.Message, &ctxs)
}
wg.Wait()
for _, ctx := range ctxs {
go func(c *Context) {
c.index = -1
c.Next()
}(ctx)
}
}
var (
app *Application = &Application{
modules: make(map[string]*Module),
}
)
func Init() {
bot.Session.AddHandler(app.onHandle)
}
func NewModule(name, prefix string) *Module {
m := &Module{
Prefix: prefix,
Name: name,
}
app.modules[name] = m
return m
}
func Use(handlers ...HandlerFunc) {
app.Use(handlers...)
}
|
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestHello(t *testing.T) {
// Create a new request with a GET method and an empty body
req, err := http.NewRequest("GET", "/hello", nil)
if err != nil {
t.Fatal(err)
}
// Create a new response recorder
rr := httptest.NewRecorder()
// Create a new router and register the helloHandler
router := http.NewServeMux()
router.HandleFunc("/hello", loggingMiddleware(helloHandler))
// Send the request and record the response
router.ServeHTTP(rr, req)
// Check that the response status code is 200 OK
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
// Check that the response body is correct
expected := "Hello, World!"
if rr.Body.String() != expected {
t.Errorf("handler returned unexpected body: got %v want %v",
rr.Body.String(), expected)
}
}
|
package tests
import (
"context"
"encoding/json"
"log"
"math/big"
"strings"
"testing"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/langzhenjun/go-ethereum-tutorials/contracts"
"github.com/langzhenjun/go-ethereum-tutorials/utils"
)
func TestERC20(t *testing.T) {
//
client, err := ethclient.Dial("../.geth/geth.ipc")
if err != nil {
log.Fatalf("Failed to connect to the Ethereum client: %v\r\n", err)
}
//
configs := utils.LoadConfigs("../configs.json")
mainAccountAddressHex := configs.MainAccount.AddressHex
mainAccountKeyJSON := configs.MainAccount.KeyJSON
mainAccountPassword := configs.MainAccount.Password
//
mainAccountKeyJSONBytes, err := json.Marshal(mainAccountKeyJSON)
mainAccountKeyJSONString := string(mainAccountKeyJSONBytes)
if err != nil {
t.Fatalf("Failed to get key json: %v\r\n", err)
}
auth, err := bind.NewTransactor(strings.NewReader(mainAccountKeyJSONString), mainAccountPassword)
if err != nil {
log.Fatalf("Failed to create authorized transactor: %v\r\n", err)
}
//
ERC20AddressHex := configs.Contracts["ERC20"]
var ERC20 *contracts.ERC20
if ERC20AddressHex == "" {
// 发布合约
address, _, depolyed, err := contracts.DeployERC20(auth, client, big.NewInt(100), "ERC20", "ERC20")
if err != nil {
t.Fatalf("Failed to deploy ERC20: %v\r\n", err)
}
ERC20 = depolyed
configs.Contracts["ERC20"] = address.Hex()
configs.Save()
} else {
// 获取合约
ERC20, err = contracts.NewERC20(common.HexToAddress(ERC20AddressHex), client)
if err != nil {
t.Fatalf("Failed to deploy contract: %v\r\n", err)
}
}
name, err := ERC20.Name(&bind.CallOpts{Pending: true})
if err != nil {
t.Fatalf("Failed to retrieve pending name: %v\r\n", err)
}
t.Logf("Pending Contract: %v\r\n", name)
ctx := context.Background()
transferC := make(chan *contracts.ERC20Transfer)
// froms := []common.Address{common.HexToAddress(mainAccountAddressHex)}
_, err = ERC20.WatchTransfer(&bind.WatchOpts{Context: ctx}, transferC, nil, nil)
if err != nil {
log.Fatalf("Failed to watch transfer: %v\r\n", err)
}
// defer sub.Unsubscribe()
const toAddressHex = "0xdc4bb8b33c0aa1eb028c73b27a988c4e0b56140a"
balanceFromBefore, _ := ERC20.BalanceOf(nil, common.HexToAddress(mainAccountAddressHex))
balanceToBefore, _ := ERC20.BalanceOf(nil, common.HexToAddress(toAddressHex))
t.Logf("Before transfere: FROM: %d, TO: %d\n", balanceFromBefore, balanceToBefore)
//
go func() {
tx, err := ERC20.Transfer(auth, common.HexToAddress(toAddressHex), big.NewInt(123456789))
if err != nil {
t.Fatalf("Failed to request ERC20 transfer: %v", err)
}
t.Logf("Pending Transfer : 0x%x\n", tx.Hash())
_, err = bind.WaitMined(ctx, client, tx)
if err != nil {
t.Fatalf("tx mining error:%v\n", err)
}
}()
transfer := <-transferC
t.Logf("FROM: %v, TO: %v, VALUE: %v\r\n", transfer.From.Hex(), transfer.To.Hex(), transfer.Value)
valFrom, _ := ERC20.BalanceOf(nil, common.HexToAddress(mainAccountAddressHex))
valTo, _ := ERC20.BalanceOf(nil, common.HexToAddress(toAddressHex))
t.Logf("After transfere: FROM: %d, TO: %d\n", valFrom, valTo)
}
|
package termcolor
import (
"runtime"
)
type Color string
const (
// https://github.com/git/git/blob/master/color.h
NORMAL = Color("")
RESET = Color("\033[m")
BOLD = Color("\033[1m")
RED = Color("\033[31m")
GREEN = Color("\033[32m")
YELLOW = Color("\033[33m")
BLUE = Color("\033[34m")
MAGENTA = Color("\033[35m")
CYAN = Color("\033[36m")
BOLD_RED = Color("\033[1;31m")
BOLD_GREEN = Color("\033[1;32m")
BOLD_YELLOW = Color("\033[1;33m")
BOLD_BLUE = Color("\033[1;34m")
BOLD_MAGENTA = Color("\033[1;35m")
BOLD_CYAN = Color("\033[1;36m")
BG_RED = Color("\033[41m")
BG_GREEN = Color("\033[42m")
BG_YELLOW = Color("\033[43m")
BG_BLUE = Color("\033[44m")
BG_MAGENTA = Color("\033[45m")
BG_CYAN = Color("\033[46m")
)
func Colorized(s string, c Color) string {
if runtime.GOOS == "windows" {
return s
}
return string(c) + s + string(RESET)
}
|
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//434. Number of Segments in a String
//Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
//Please note that the string does not contain any non-printable characters.
//Example:
//Input: "Hello, my name is John"
//Output: 5
//func countSegments(s string) int {
//}
// Time Is Money |
package acs
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
"sync"
)
// A Writer is an io.WriteCloser. Writes to a Writer are encrypted (AES-CBC) and written to w.
type Writer struct {
closed bool
beginning bool
mu sync.Mutex
w io.Writer
iv []byte
block cipher.Block
mode cipher.BlockMode
pending []byte // pending data
}
// NewWriter returns an AES CBC writer.
func NewWriter(w io.Writer, key []byte) (*Writer, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
iv := make([]byte, block.BlockSize())
if _, err = io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
return &Writer{
beginning: true,
w: w,
block: block,
iv: iv,
mode: cipher.NewCBCEncrypter(block, iv),
}, err
}
// Write implements io.Writer interface.
func (w *Writer) Write(p []byte) (n int, err error) {
w.mu.Lock()
defer w.mu.Unlock()
if w.closed {
panic("acs: writes on a closed writer")
}
if w.beginning {
_, err = w.w.Write(w.iv)
if err != nil {
return
}
w.beginning = false
}
p = append(w.pending, p...)
run := (len(p) / w.block.BlockSize()) * w.block.BlockSize()
w.pending = p[run:]
if run == 0 {
// Not enough data to write a complete block
return
}
data := make([]byte, run)
w.mode.CryptBlocks(data, p[:run])
_, err = w.w.Write(data)
n = len(p)
return
}
// Close implements io.Close interface.
func (w *Writer) Close() (err error) {
w.mu.Lock()
defer w.mu.Unlock()
if len(w.pending) > 0 {
w.pending = PKCS5Padding(w.pending, w.block.BlockSize())
w.mode.CryptBlocks(w.pending, w.pending)
_, err = w.w.Write(w.pending)
}
w.closed = true
return
}
|
package main
import "fmt"
func main() {
fmt.Println(rob([]int{1, 2, 3, 1}))
fmt.Println(rob([]int{2, 7, 9, 3, 1}))
}
func rob(nums []int) int {
switch len(nums) {
case 0:
return 0
case 1:
return nums[0]
}
_rob := func(nums []int) int {
dp := make([]int, len(nums))
// 在第 i 间屋子能获得最大的收益
//1,2,3,1
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i := 2; i < len(nums); i++ {
dp[i] = max(
dp[i-2]+nums[i], // 偷当前房间
dp[i-1], // 不偷当前房间
)
}
return dp[len(nums)-1]
}
t1 := _rob(nums[:len(nums)-1])
t2 := _rob(nums[1:])
return max(t1, t2)
}
func min(a ...int) int {
res := a[0]
for _, v := range a[1:] {
if v < res {
res = v
}
}
return res
}
func max(a ...int) int {
res := a[0]
for _, v := range a[1:] {
if v > res {
res = v
}
}
return res
}
|
package main
import (
"encoding/json"
"flag"
"log"
"github.com/nats-io/nats"
)
type product struct {
Name string `json:"name"`
SKU string `json:"sku"`
}
var natsClient *nats.Conn
var natsServer = flag.String("nats", "", "NATS server URI")
func init() {
flag.Parse()
}
func main() {
var err error
natsClient, err = nats.Connect("nats://" + *natsServer)
if err != nil {
log.Fatal(err)
}
defer natsClient.Close()
log.Println("Subscribing to events")
natsClient.Subscribe("product.inserted", handleMessage)
}
func handleMessage(m *nats.Msg) {
p := product{}
err := json.Unmarshal(m.Data, &p)
if err != nil {
log.Println("Unable to unmarshal event object")
return
}
log.Printf("Received message: %v, %#v", m.Subject, p)
}
|
// Copyright 2020-present Kuei-chun Chen. All rights reserved.
package keyhole
import "fmt"
// CompareClusters compares two clusters, source and target
func CompareClusters(cfg *Config) error {
if cfg.IsDeepCompare {
var err error
var comp *Comparator
if comp, err = NewComparator(cfg.SourceURI, cfg.TargetURI); err != nil {
return err
}
return comp.Compare(cfg.Filters, cfg.SampleSize)
}
return CompareMetadata(cfg)
}
// CompareMetadata compares two clusters' metadata
func CompareMetadata(cfg *Config) error {
var err error
comp := NewComparison(cfg.Signature)
comp.SetNoColor(cfg.NoColor)
comp.SetVerbose(cfg.Verbose)
if err = comp.Compare(cfg.SourceURI, cfg.TargetURI); err != nil {
return err
}
if err = comp.OutputBSON(); err != nil {
return err
}
return err
}
// PrintCompareHelp prints help message
func PrintCompareHelp() {
message := `deprecated, use keyhole -config <config>
{
"action": "compare_clusters",
"deep_compare: false,
"namespaces: [],
"source_uri": "mongodb+srv://user:password@source.xxxxxx.mongodb.net/",
"target_uri": "mongodb+srv://user:password@target.xxxxxx.mongodb.net/"
}`
fmt.Println(message)
}
|
package main
import "fmt"
/**
函数示例
*/
//闭包1 返回一个函数
func getSeq() func() int {
i := 0
return func() int {
i++
return i
}
}
//闭包2 带参数
func addFUnc(x1 int, x2 int) func(x3 int, x4 int) (int, int, int) {
i := 0
return func(x3 int, x4 int) (int, int, int) {
i++
return i, x1 + x2, x3 + x4
}
}
//结构体类型 圆
type Circle struct {
//半径
radius float64
}
//方法演示 求圆的面积 该 method 属于 Circle 类型对象中的方法
func (c Circle) area() float64 {
return 3.14 * c.radius * c.radius
}
func main() {
//函数作为值传递
add := func(a int, b int) int {
return a + b
}
fmt.Println(add(3, 7))
//闭包演示
num1 := getSeq() //闭包1
fmt.Println(num1())
fmt.Println(num1())
fmt.Println(num1())
num2 := getSeq() //闭包2
fmt.Println(num2())
fmt.Println(num2())
//闭包2 带参数
add2 := addFUnc(8, 3)
fmt.Println(add2(1, 9))
fmt.Println(add2(6, 4))
//方法演示
var c Circle
c.radius = 10.0
areas := c.area()
fmt.Println("圆的面积", areas)
}
|
package middlewares
import (
"github.com/astaxie/beego"
)
func GetBalance(address string) ([]byte, error){
url := beego.AppConfig.String("BasecoinUrl")+"/query/account/balance?address="+address
return SendRequest(url)
}
func FindRelateAccount(address string) ([]byte, error){
url := beego.AppConfig.String("BasecoinUrl")+"/query/account/relateAccount?address="+address
return SendRequest(url)
} |
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
"golang.org/x/oauth2"
"golang.org/x/net/context"
)
const (
TOKEN_URL = "https://api.%s.onelogin.com/auth/oauth2/v2/token"
AUTH_URL = "https://api.%s.onelogin.com/auth/oauth2/auth"
BASE_PATH = "https://api.%s.onelogin.com/api/1/%s"
)
type OneloginClient struct {
*http.Client
region string
}
func NewOneloginClient(clientId, clientSecret, region string) (*OneloginClient, error) {
ctx := context.Background()
conf := &OAuth2Config{&oauth2.Config{
ClientID: clientId,
ClientSecret: clientSecret,
Scopes: []string{"saml_assertion"},
Endpoint: oauth2.Endpoint{
AuthURL: fmt.Sprintf(AUTH_URL, region),
TokenURL: fmt.Sprintf(TOKEN_URL, region),
},
}}
token, err := conf.GetToken()
if err != nil {
return nil, err
}
client := conf.GetClient(ctx, token, region)
return client, nil
}
func (c *OneloginClient) PostJson(url string, body interface{}) (*http.Response, error) {
json, err := json.Marshal(body)
if err != nil {
return nil, err
}
return c.Post(url, "application/json", bytes.NewReader(json))
}
func (c *OneloginClient) GetSamlAssertion(appId, subdomain, username, password, mfaCode string) (*SamlAssertion, error) {
req_params := &samlAssertionRequest{
UsernameOrEmail: username,
Password: password,
AppId: appId,
Subdomain: subdomain,
}
resp, err := c.PostJson(fmt.Sprintf(BASE_PATH, c.region, "saml_assertion"), req_params)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, errors.New(resp.Status)
}
samlResponse := &samlAssertionResponse{}
err = parseJson(resp, samlResponse)
if err != nil {
return nil, err
}
// TODO fix workflow w/o mfa
verify_req_params := &verifyFactorRequest{
AppId: appId,
DeviceId: samlResponse.Data[0].Devices[0].DeviceId,
StateToken: samlResponse.Data[0].StateToken,
OtpToken: mfaCode,
}
resp, err = c.PostJson(samlResponse.Data[0].CallbackUrl, verify_req_params)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, errors.New(resp.Status)
}
verifyResponse := &verifyFactorResponse{}
err = parseJson(resp, verifyResponse)
if err != nil {
return nil, err
}
assertion := NewSamlAssertion(verifyResponse.Data)
return assertion, nil
}
type OAuth2Config struct {
*oauth2.Config
}
func (conf *OAuth2Config) GetToken() (*oauth2.Token, error) {
req, err := http.NewRequest("POST", conf.Endpoint.TokenURL, strings.NewReader(`{"grant_type":"client_credentials"}`))
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", fmt.Sprintf("client_id:%s, client_secret:%s", conf.ClientID, conf.ClientSecret))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
token := &oauth2.Token{}
json.Unmarshal(body, token)
return token, nil
}
func (conf *OAuth2Config) GetClient(ctx context.Context, t *oauth2.Token, region string) *OneloginClient {
return &OneloginClient{conf.Client(ctx, t), region}
}
type samlAssertionRequest struct {
UsernameOrEmail string `json:"username_or_email"`
Password string `json:"password"`
AppId string `json:"app_id"`
Subdomain string `json:"subdomain"`
IpAddress string `json:"ip_address,omitempty"`
}
type samlAssertionResponseDataDeveice struct {
DeviceId int `json:"device_id"`
DeviceType string `json:"device_type"`
}
type samlAssertionResponseData struct {
StateToken string `json:"state_token"`
Devices []*samlAssertionResponseDataDeveice `json:"devices"`
CallbackUrl string `json:"callback_url"`
}
type responseStatus struct {
Type string `json:"type"`
Message string `json:"message"`
Code int `json:"code"`
Error bool `json:"error"`
}
type samlAssertionResponse struct {
Status *responseStatus `json:"status"`
Data []*samlAssertionResponseData `json:"data"`
}
type verifyFactorRequest struct {
AppId string `json:"app_id"`
DeviceId int `json:"device_id,string"`
StateToken string `json:"state_token"`
OtpToken string `json:"otp_token"`
}
type verifyFactorResponse struct {
Status *responseStatus `json:"status"`
Data string `json:"data"`
}
func parseJson(resp *http.Response, v interface{}) error {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return json.Unmarshal(body, v)
}
|
package server
import (
"fmt"
. "server/data/datatype"
"server/libs/log"
"server/libs/rpc"
)
var (
vt ViewportCodec
)
type ViewportCodec interface {
GetCodecInfo() string
ViewportCreate(id int32, container Entity) interface{}
ViewportDelete(id int32) interface{}
ViewportNotifyAdd(id int32, index int32, object Entity) interface{}
ViewportNotifyRemove(id int32, index int32) interface{}
ViewportNotifyExchange(srcid int32, src int32, destid int32, dest int32) interface{}
OnUpdate(id int32, child Entity) interface{}
}
type ViewportData struct {
Id int32
Container Entity
}
type Viewport struct {
SchedulerBase
Views map[int32]*ViewportData
Owner Entity
mailbox rpc.Mailbox
}
func NewViewport(p Entity, mailbox rpc.Mailbox) *Viewport {
if vt == nil {
panic("viewport transport not set")
}
log.LogMessage("viewport proto:", vt.GetCodecInfo())
vp := &Viewport{}
vp.Views = make(map[int32]*ViewportData)
vp.Owner = p
vp.mailbox = mailbox
return vp
}
func (vp *Viewport) ClearAll() {
for id, _ := range vp.Views {
vp.RemoveViewport(id)
}
}
func (vp *Viewport) AddViewport(id int32, container Entity) error {
if _, exist := vp.Views[id]; exist {
return fmt.Errorf("viewport is already open")
}
if container == nil {
return fmt.Errorf("container is nil")
}
if container.Caps() == -1 {
return fmt.Errorf("container capacity not set")
}
container.SetExtraData("viewportid", id)
vp.Views[id] = &ViewportData{id, container}
vp.ViewportCreate(id)
return nil
}
func (vp *Viewport) RemoveViewport(id int32) {
if vd, exist := vp.Views[id]; exist {
vp.ViewportDelete(id)
vd.Container.RemoveExtraData("viewportid")
delete(vp.Views, id)
}
}
//容器创建
func (vp *Viewport) ViewportCreate(id int32) {
vd := vp.Views[id]
if vd == nil {
return
}
msg := vt.ViewportCreate(id, vd.Container)
if msg == nil {
return
}
MailTo(nil, &vp.mailbox, "Viewport.Create", msg)
childs := vd.Container.Caps()
for index := int32(0); index < childs; index++ {
vp.ViewportNotifyAdd(id, index)
}
}
//删除容器
func (vp *Viewport) ViewportDelete(id int32) {
vd := vp.Views[id]
if vd == nil {
return
}
msg := vt.ViewportDelete(id)
if msg == nil {
return
}
MailTo(nil, &vp.mailbox, "Viewport.Delete", msg)
}
//容器里增加对象
func (vp *Viewport) ViewportNotifyAdd(id int32, index int32) {
vd := vp.Views[id]
if vd == nil {
return
}
child := vd.Container.GetChild(int(index))
if child == nil {
return
}
msg := vt.ViewportNotifyAdd(id, index, child)
if msg == nil {
return
}
MailTo(nil, &vp.mailbox, "Viewport.Add", msg)
}
//容器里移除对象
func (vp *Viewport) ViewportNotifyRemove(id int32, index int32) {
vd := vp.Views[id]
if vd == nil {
return
}
msg := vt.ViewportNotifyRemove(id, index)
if msg == nil {
return
}
MailTo(nil, &vp.mailbox, "Viewport.Remove", msg)
}
//容器交换位置
func (vp *Viewport) ViewportNotifyExchange(srcid int32, src int32, destid int32, dest int32) {
vd1 := vp.Views[srcid]
if vd1 == nil {
return
}
vd2 := vp.Views[destid]
if vd2 == nil {
return
}
msg := vt.ViewportNotifyExchange(srcid, src, destid, dest)
if msg == nil {
return
}
MailTo(nil, &vp.mailbox, "Viewport.Exchange", msg)
}
func (vp *Viewport) OnUpdate() {
for _, vd := range vp.Views {
childs := vd.Container.AllChilds()
for _, child := range childs {
if child == nil {
continue
}
data, _ := child.SerialModify()
if data == nil {
continue
}
msg := vt.OnUpdate(vd.Id, child)
if msg == nil {
continue
}
MailTo(nil, &vp.mailbox, "Viewport.ObjUpdate", msg)
child.ClearModify()
}
}
}
func RegisterViewportCodec(t ViewportCodec) {
vt = t
}
|
package GoMybatisV2
import (
"context"
"database/sql"
"github.com/agui2200/GoMybatisV2/logger"
"github.com/agui2200/GoMybatisV2/sessions"
"github.com/agui2200/GoMybatisV2/sqlbuilder"
"github.com/agui2200/GoMybatisV2/templete"
"github.com/agui2200/GoMybatisV2/templete/ast"
"github.com/agui2200/GoMybatisV2/templete/engines"
"github.com/agui2200/GoMybatisV2/utils"
"reflect"
"sync"
)
type GoMybatisEngine struct {
mutex sync.RWMutex //读写锁
isInit bool //是否初始化
objMap sync.Map
dataSourceRouter sessions.DataSourceRouter //动态数据源路由器
log logger.Log //日志实现类
logEnable bool //是否允许日志输出(默认开启)
logSystem *logger.LogSystem //日志发送系统
sessionFactory *sessions.SessionFactory //session 工厂
expressionEngine ast.ExpressionEngine //表达式解析引擎
sqlBuilder sessions.SqlBuilder //sql 构建
sqlResultDecoder sessions.SqlResultDecoder //sql查询结果解析引擎
templeteDecoder sessions.TempleteDecoder //模板解析引擎
goroutineSessionMap *sessions.GoroutineSessionMap //map[协程id]Session
goroutineIDEnable bool //是否启用goroutineIDEnable(注意(该方法需要在多协程环境下调用)启用会从栈获取协程id,有一定性能消耗,换取最大的事务定义便捷,单线程处理场景可以关闭此配置)
}
func (it GoMybatisEngine) New() GoMybatisEngine {
it.logEnable = true
it.isInit = true
if it.logEnable == true && it.log == nil {
it.log = &logger.LogStandard{}
}
if it.logEnable {
var logSystem, err = logger.LogSystem{}.New(it.log, it.log.QueueLen())
if err != nil {
panic(err)
}
it.logSystem = &logSystem
}
if it.dataSourceRouter == nil {
var newRouter = GoMybatisDataSourceRouter{}.New(nil)
it.SetDataSourceRouter(&newRouter)
}
if it.expressionEngine == nil {
it.expressionEngine = &engines.ExpressionEngineGoExpress{}
}
if it.sqlResultDecoder == nil {
it.sqlResultDecoder = sqlbuilder.GoMybatisSqlResultDecoder{}
}
if it.templeteDecoder == nil {
it.SetTempleteDecoder(&templete.GoMybatisTempleteDecoder{})
}
if it.sqlBuilder == nil {
var builder = sqlbuilder.New(it.ExpressionEngine(), it.logEnable, it.Log())
it.sqlBuilder = &builder
}
if it.sessionFactory == nil {
var factory = sessions.SessionFactory{}.New(&it)
it.sessionFactory = &factory
}
if it.goroutineSessionMap == nil {
var gr = sessions.GoroutineSessionMap{}.New()
it.goroutineSessionMap = &gr
}
it.goroutineIDEnable = true
return it
}
func (it GoMybatisEngine) initCheck() {
if it.isInit == false {
panic(utils.NewError("GoMybatisEngine", "must call GoMybatisEngine{}.New() to init!"))
}
}
func (it *GoMybatisEngine) WriteMapperPtr(ptr interface{}, xml []byte) {
it.initCheck()
WriteMapperPtrByEngine(ptr, xml, it)
}
func (it *GoMybatisEngine) Name() string {
return "GoMybatisEngine"
}
func (it *GoMybatisEngine) DataSourceRouter() sessions.DataSourceRouter {
it.initCheck()
return it.dataSourceRouter
}
func (it *GoMybatisEngine) SetDataSourceRouter(router sessions.DataSourceRouter) {
it.initCheck()
it.dataSourceRouter = router
}
func (it *GoMybatisEngine) NewSession(mapperName string) (sessions.Session, error) {
it.initCheck()
var session, err = it.DataSourceRouter().Router(mapperName, it)
return session, err
}
func (it *GoMybatisEngine) NewSessionWithContext(ctx context.Context, mapperName string) (sessions.Session, error) {
s, err := it.NewSession(mapperName)
if err != nil {
return nil, err
}
s.WithContext(ctx)
return s, nil
}
//获取日志实现类,是否启用日志
func (it *GoMybatisEngine) LogEnable() bool {
it.initCheck()
return it.logEnable
}
//设置日志实现类,是否启用日志
func (it *GoMybatisEngine) SetLogEnable(enable bool) {
it.initCheck()
it.logEnable = enable
it.sqlBuilder.SetEnableLog(enable)
}
//获取日志实现类
func (it *GoMybatisEngine) Log() logger.Log {
it.initCheck()
return it.log
}
//设置日志实现类
func (it *GoMybatisEngine) SetLog(log logger.Log) {
it.initCheck()
it.log = log
}
//session工厂
func (it *GoMybatisEngine) SessionFactory() *sessions.SessionFactory {
it.initCheck()
return it.sessionFactory
}
//设置session工厂
func (it *GoMybatisEngine) SetSessionFactory(factory *sessions.SessionFactory) {
it.initCheck()
it.sessionFactory = factory
}
//表达式执行引擎
func (it *GoMybatisEngine) ExpressionEngine() ast.ExpressionEngine {
it.initCheck()
return it.expressionEngine
}
//设置表达式执行引擎
func (it *GoMybatisEngine) SetExpressionEngine(engine ast.ExpressionEngine) {
it.initCheck()
it.expressionEngine = engine
var proxy = it.sqlBuilder.ExpressionEngineProxy()
proxy.SetExpressionEngine(it.expressionEngine)
}
//sql构建器
func (it *GoMybatisEngine) SqlBuilder() sessions.SqlBuilder {
it.initCheck()
return it.sqlBuilder
}
//设置sql构建器
func (it *GoMybatisEngine) SetSqlBuilder(builder sessions.SqlBuilder) {
it.initCheck()
it.sqlBuilder = builder
}
//sql查询结果解析器
func (it *GoMybatisEngine) SqlResultDecoder() sessions.SqlResultDecoder {
it.initCheck()
return it.sqlResultDecoder
}
//设置sql查询结果解析器
func (it *GoMybatisEngine) SetSqlResultDecoder(decoder sessions.SqlResultDecoder) {
it.initCheck()
it.sqlResultDecoder = decoder
}
//打开数据库
//driverName: 驱动名称例如"mysql", dataSourceName: string 数据库url
func (it *GoMybatisEngine) Open(driverName, dataSourceName string) (*sql.DB, error) {
it.initCheck()
db, err := sql.Open(driverName, dataSourceName)
if err != nil {
return nil, err
}
it.dataSourceRouter.SetDB(driverName, dataSourceName, db)
return db, nil
}
//模板解析器
func (it *GoMybatisEngine) TempleteDecoder() sessions.TempleteDecoder {
return it.templeteDecoder
}
//设置模板解析器
func (it *GoMybatisEngine) SetTempleteDecoder(decoder sessions.TempleteDecoder) {
it.templeteDecoder = decoder
}
func (it *GoMybatisEngine) GoroutineSessionMap() *sessions.GoroutineSessionMap {
return it.goroutineSessionMap
}
func (it *GoMybatisEngine) RegisterObj(ptr interface{}, name string) {
var v = reflect.ValueOf(ptr)
if v.Kind() != reflect.Ptr {
panic("GoMybatis Engine Register obj not a ptr value!")
}
it.objMap.Store(name, ptr)
}
func (it *GoMybatisEngine) GetObj(name string) interface{} {
v, _ := it.objMap.Load(name)
return v
}
func (it *GoMybatisEngine) SetGoroutineIDEnable(enable bool) {
it.goroutineIDEnable = enable
}
func (it *GoMybatisEngine) GoroutineIDEnable() bool {
return it.goroutineIDEnable
}
func (it *GoMybatisEngine) LogSystem() *logger.LogSystem {
return it.logSystem
}
|
package main
import (
"context"
"os"
"github.com/andersfylling/disgord"
"github.com/andersfylling/disgord/std"
)
// replyPongToPing is a handler that replies pong to ping messages
func replyPongToPing(s disgord.Session, data *disgord.MessageCreate) {
msg := data.Message
// whenever the message written is "ping", the bot replies "pong"
if msg.Content == "ping" {
_, _ = msg.Reply(context.Background(), s, "pong")
}
}
func main() {
client := disgord.New(disgord.Config{
BotToken: os.Getenv("DISGORD_TOKEN"),
Logger: disgord.DefaultLogger(false), // debug=false
})
defer client.StayConnectedUntilInterrupted(context.Background())
log, _ := std.NewLogFilter(client)
filter, _ := std.NewMsgFilter(context.Background(), client)
filter.SetPrefix("REPLACE_ME")
// create a handler and bind it to new message events
// tip: read the documentation for std.CopyMsgEvt and understand why it is used here.
client.On(disgord.EvtMessageCreate,
// middleware
filter.NotByBot, // ignore bot messages
filter.HasPrefix, // read original
log.LogMsg, // log command message
std.CopyMsgEvt, // read & copy original
filter.StripPrefix, // write copy
// handler
replyPongToPing) // handles copy
}
|
package database
import (
"errors"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"github.com/ubclaunchpad/pinpoint/protobuf/models"
)
// AddNewPeriod creates a new period item in the club table
func (db *Database) AddNewPeriod(clubID string, period *models.Period) error {
if clubID == "" || period.Period == "" {
return errors.New("invalid period fields")
}
var p = newDBPeriod(period)
item, err := dynamodbattribute.MarshalMap(p)
if err != nil {
return fmt.Errorf("Failed to marshal event: %s", err.Error())
}
if _, err := db.c.PutItem(&dynamodb.PutItemInput{
Item: item,
TableName: getClubTable(clubID),
}); err != nil {
return fmt.Errorf("Failed to put period: %s", err.Error())
}
return nil
}
// AddNewEvent creates a new event in the club table
func (db *Database) AddNewEvent(clubID string, event *models.EventProps) error {
if clubID == "" || event.Period == "" || event.Name == "" || event.EventID == "" {
return errors.New("invalid event fields")
}
var e = newDBEvent(event)
item, err := dynamodbattribute.MarshalMap(e)
if err != nil {
return fmt.Errorf("Failed to marshal event: %s", err.Error())
}
if _, err := db.c.PutItem(&dynamodb.PutItemInput{
Item: item,
TableName: getClubTable(clubID),
}); err != nil {
return fmt.Errorf("Failed to put event: %s", err.Error())
}
return nil
}
// GetEvent returns an event from the database
func (db *Database) GetEvent(clubID string, period string, eventID string) (*models.EventProps, error) {
if clubID == "" || period == "" || eventID == "" {
return nil, errors.New("invalid query")
}
var p = aws.String(prefixPeriodID(period))
var e = aws.String(prefixEventID(eventID))
var result, err = db.c.GetItem(&dynamodb.GetItemInput{
TableName: getClubTable(clubID),
Key: map[string]*dynamodb.AttributeValue{
"pk": {S: p},
"sk": {S: e},
},
})
if err != nil {
return nil, fmt.Errorf("Failed to get event: %s", err.Error())
}
var item eventItem
if err := dynamodbattribute.UnmarshalMap(result.Item, &item); err != nil {
return nil, fmt.Errorf("Failed to unmarshal event: %s", err.Error())
}
return newEvent(&item), nil
}
// GetEvents returns all the events of an application period
func (db *Database) GetEvents(clubID string, period string) ([]*models.EventProps, error) {
if clubID == "" || period == "" {
return nil, errors.New("invalid query")
}
var result, err = db.c.Query(&dynamodb.QueryInput{
TableName: getClubTable(clubID),
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":p": {
S: aws.String(prefixPeriodID(period)),
},
":e": {
S: aws.String(eventPrefix),
},
},
KeyConditionExpression: aws.String("pk = :p AND begins_with(sk, :e)"),
})
if err != nil {
return nil, fmt.Errorf("Failed query for all events: %s", err.Error())
}
var items = make([]*eventItem, *result.Count)
if err := dynamodbattribute.UnmarshalListOfMaps(result.Items, &items); err != nil {
return nil, fmt.Errorf("Failed to unmarshal events: %s", err.Error())
}
var events = make([]*models.EventProps, *result.Count)
for i, item := range items {
events[i] = newEvent(item)
}
return events, nil
}
// DeleteEvent deletes an event and all of its applications
func (db *Database) DeleteEvent(clubID string, period string, eventID string) error {
if clubID == "" || period == "" || eventID == "" {
return errors.New("invalid query")
}
var result, err = db.c.Query(&dynamodb.QueryInput{
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":p": {
S: aws.String(prefixPeriodID(period)),
},
":e": {
S: aws.String(prefixEventID(eventID)),
},
},
KeyConditionExpression: aws.String("pk = :p AND sk = :e"),
ProjectionExpression: aws.String("pk, sk"),
TableName: getClubTable(clubID),
})
if err != nil {
return fmt.Errorf("Failed query for event: %s", err.Error())
}
var batch = make([]*dynamodb.WriteRequest, len(result.Items))
for i, item := range result.Items {
batch[i] = &dynamodb.WriteRequest{
DeleteRequest: &dynamodb.DeleteRequest{
Key: item,
},
}
}
if _, err = db.c.BatchWriteItem(&dynamodb.BatchWriteItemInput{
RequestItems: map[string][]*dynamodb.WriteRequest{
*getClubTable(clubID): batch,
},
}); err != nil {
return fmt.Errorf("Failed batch delete requests for event: %s", err.Error())
}
return nil
}
// AddNewApplicant creates a new applicant in the club table for an application period
func (db *Database) AddNewApplicant(clubID string, applicant *models.Applicant) error {
if clubID == "" || applicant.Period == "" || applicant.Email == "" || applicant.Name == "" {
return errors.New("invalid tag fields")
}
var item, err = dynamodbattribute.MarshalMap(newDBApplicant(applicant))
if err != nil {
return fmt.Errorf("Failed to marshal applicant: %s", err.Error())
}
var input = &dynamodb.PutItemInput{
Item: item,
TableName: getClubTable(clubID),
}
if _, err := db.c.PutItem(input); err != nil {
return fmt.Errorf("Failed to put applicant: %s", err.Error())
}
return nil
}
// GetApplicant returns an applicant for a application period
func (db *Database) GetApplicant(clubID string, period string, email string) (*models.Applicant, error) {
if clubID == "" || period == "" || email == "" {
return nil, errors.New("invalid query")
}
var result, err = db.c.GetItem(&dynamodb.GetItemInput{
TableName: getClubTable(clubID),
Key: map[string]*dynamodb.AttributeValue{
"pk": {S: aws.String(prefixPeriodID(period))},
"sk": {S: aws.String(prefixApplicantID(email))},
},
})
if err != nil {
return nil, fmt.Errorf("Failed to get applicant: %s", err.Error())
}
var item applicantItem
if err := dynamodbattribute.UnmarshalMap(result.Item, &item); err != nil {
return nil, fmt.Errorf("Failed to unmarshal applicant: %s", err.Error())
}
return newApplicant(&item), nil
}
// GetApplicants returns all the applicants for an application period
func (db *Database) GetApplicants(clubID string, period string) ([]*models.Applicant, error) {
if clubID == "" || period == "" {
return nil, errors.New("invalid query")
}
var result, err = db.c.Query(&dynamodb.QueryInput{
TableName: getClubTable(clubID),
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":id": {
S: aws.String(prefixPeriodID(period)),
},
":a": {
S: aws.String(applicantPrefix),
},
},
KeyConditionExpression: aws.String("pk = :id AND begins_with(sk, :a)"),
})
if err != nil {
return nil, fmt.Errorf("Failed query for all applicants: %s", err.Error())
}
var items = make([]*applicantItem, *result.Count)
if err := dynamodbattribute.UnmarshalListOfMaps(result.Items, &items); err != nil {
return nil, fmt.Errorf("Failed to unmarshal all applicants: %s", err.Error())
}
var applicants = make([]*models.Applicant, *result.Count)
for i, item := range items {
applicants[i] = newApplicant(item)
}
return applicants, nil
}
// DeleteApplicant deletes an applicant from a application period and their event applications
func (db *Database) DeleteApplicant(clubID string, period string, email string) error {
if clubID == "" || period == "" || email == "" {
return errors.New("invalid query")
}
var result, err = db.c.Query(&dynamodb.QueryInput{
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":id": {
S: aws.String(prefixApplicantID(email)),
},
"peid": {
S: aws.String(peidPrefix + period),
},
"p": {
S: aws.String(prefixPeriodID(period)),
},
},
KeyConditionExpression: aws.String("sk = :id AND (begins_with(pk, :peid) OR begins_with(pk, :p))"),
ProjectionExpression: aws.String("pk, sk"),
TableName: getClubTable(clubID),
})
if err != nil {
return fmt.Errorf("Failed query for applicant: %s", err.Error())
}
var batch = make([]*dynamodb.WriteRequest, len(result.Items))
for i, item := range result.Items {
batch[i] = &dynamodb.WriteRequest{
DeleteRequest: &dynamodb.DeleteRequest{
Key: item,
},
}
}
var batchInput = &dynamodb.BatchWriteItemInput{
RequestItems: map[string][]*dynamodb.WriteRequest{
*getClubTable(clubID): batch,
},
}
if _, err = db.c.BatchWriteItem(batchInput); err != nil {
return fmt.Errorf("Failed batch delete request for applicant: %s", err.Error())
}
return nil
}
// AddNewApplication adds an application to the database
func (db *Database) AddNewApplication(clubID string, application *models.Application) error {
if application.Period == "" || application.EventID == "" || application.Email == "" || application.Name == "" {
return errors.New("invalid application fields")
}
var item, err = dynamodbattribute.MarshalMap(newDBApplication(application))
if err != nil {
return fmt.Errorf("Failed to marshal application: %s", err.Error())
}
if _, err := db.c.PutItem(&dynamodb.PutItemInput{
Item: item,
TableName: getClubTable(clubID),
}); err != nil {
return fmt.Errorf("Failed to put application: %s", err.Error())
}
return nil
}
// GetApplication returns the application for an event by applicant email
func (db *Database) GetApplication(clubID string, period string, eventID string, email string) (*models.Application, error) {
if clubID == "" || period == "" || eventID == "" || email == "" {
return nil, errors.New("invalid query")
}
var result, err = db.c.GetItem(&dynamodb.GetItemInput{
TableName: getClubTable(clubID),
Key: map[string]*dynamodb.AttributeValue{
"pk": {S: aws.String(prefixPeriodEventID(period, eventID))},
"sk": {S: aws.String(prefixApplicantID(email))},
},
})
if err != nil {
return nil, fmt.Errorf("Failed to get application: %s", err.Error())
}
var item applicationItem
if err := dynamodbattribute.UnmarshalMap(result.Item, &item); err != nil {
return nil, fmt.Errorf("Failed to put application: %s", err.Error())
}
return newApplication(&item), nil
}
// GetApplications returns all the applications for an event
func (db *Database) GetApplications(clubID string, period string, eventID string) ([]*models.Application, error) {
if clubID == "" || period == "" || eventID == "" {
return nil, errors.New("invalid query")
}
var result, err = db.c.Query(&dynamodb.QueryInput{
TableName: getClubTable(clubID),
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":id": {
S: aws.String(prefixPeriodEventID(period, eventID)),
},
":a": {
S: aws.String(applicantPrefix),
},
},
KeyConditionExpression: aws.String("pk = :id AND begins_with(sk, :a)"),
})
if err != nil {
return nil, fmt.Errorf("Failed to get all applications: %s", err.Error())
}
var items = make([]*applicationItem, *result.Count)
if err := dynamodbattribute.UnmarshalListOfMaps(result.Items, &items); err != nil {
return nil, fmt.Errorf("Failed to unmarshal applications: %s", err.Error())
}
var applications = make([]*models.Application, *result.Count)
for i, item := range items {
applications[i] = newApplication(item)
}
return applications, nil
}
// DeleteApplication deletes the application for an event by applicant email
func (db *Database) DeleteApplication(clubID string, period string, eventID string, email string) error {
if clubID == "" || period == "" || eventID == "" || email == "" {
return errors.New("invalid query")
}
if _, err := db.c.DeleteItem(&dynamodb.DeleteItemInput{
TableName: getClubTable(clubID),
Key: map[string]*dynamodb.AttributeValue{
"pk": {S: aws.String(prefixPeriodEventID(period, eventID))},
"sk": {S: aws.String(prefixApplicantID(email))},
},
}); err != nil {
return fmt.Errorf("Failed to delete application: %s", err.Error())
}
return nil
}
// AddTag adds a new Tag for that application period
func (db *Database) AddTag(clubID string, tag *models.Tag) error {
if tag.Period == "" || tag.TagName == "" {
return errors.New("invalid tag fields")
}
var t = newDBTag(tag)
item, err := dynamodbattribute.MarshalMap(t)
if err != nil {
return fmt.Errorf("Failed to marshal tag: %s", err.Error())
}
if _, err := db.c.PutItem(&dynamodb.PutItemInput{
Item: item,
TableName: getClubTable(clubID),
}); err != nil {
return fmt.Errorf("Failed to put tag: %s", err.Error())
}
return nil
}
// GetTags returns all the tags for an application period
func (db *Database) GetTags(clubID string, period string) ([]*models.Tag, error) {
if clubID == "" || period == "" {
return nil, errors.New("invalid query")
}
var result, err = db.c.Query(&dynamodb.QueryInput{
TableName: getClubTable(clubID),
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":id": {
S: aws.String(prefixPeriodID(period)),
},
":t": {
S: aws.String(tagPrefix),
},
},
KeyConditionExpression: aws.String("pk = :id AND begins_with(sk, :t)"),
})
if err != nil {
return nil, fmt.Errorf("Failed query for all tags: %s", err.Error())
}
var items = make([]*tagItem, *result.Count)
if err := dynamodbattribute.UnmarshalListOfMaps(result.Items, &items); err != nil {
return nil, fmt.Errorf("Failed to unmarshal tags: %s", err.Error())
}
var tags = make([]*models.Tag, *result.Count)
for i, item := range items {
tags[i] = newTag(item)
}
return tags, nil
}
// DeleteTag deletes a tag for the application period
func (db *Database) DeleteTag(clubID string, period string, tag string) error {
if clubID == "" || period == "" || tag == "" {
return errors.New("invalid query")
}
if _, err := db.c.DeleteItem(&dynamodb.DeleteItemInput{
TableName: getClubTable(clubID),
Key: map[string]*dynamodb.AttributeValue{
"pk": {S: aws.String(prefixPeriodID(period))},
"sk": {S: aws.String(prefixTag(tag))},
},
}); err != nil {
return fmt.Errorf("Failed to delete tag: %s", err.Error())
}
return nil
}
|
package virtualoutbound_test
import (
"testing"
. "github.com/onsi/ginkgo"
"github.com/kumahq/kuma/pkg/test"
"github.com/kumahq/kuma/test/e2e/virtualoutbound"
"github.com/kumahq/kuma/test/framework"
)
func TestE2ERetry(t *testing.T) {
if framework.IsK8sClustersStarted() {
test.RunSpecs(t, "E2E VirtualOutbound Suite")
} else {
t.SkipNow()
}
}
var _ = Describe("Test VirtualOutbound on Universal", virtualoutbound.VirtualOutboundOnUniversal)
var _ = Describe("Test VirtualOutbound on K8s", virtualoutbound.VirtualOutboundOnK8s)
|
package handler
import (
"context"
"errors"
"fmt"
"time"
"github.com/golang/protobuf/ptypes"
"github.com/jinmukeji/go-pkg/v2/age"
"github.com/jinmukeji/jiujiantang-services/pkg/rpc"
"github.com/jinmukeji/jiujiantang-services/service/auth"
"github.com/jinmukeji/jiujiantang-services/service/mysqldb"
corepb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1"
subscriptionpb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/subscription/v1"
jinmuidpb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1"
)
const (
// TrialSubscriptionExpirationDuration 试用订阅期限是1个月
TrialSubscriptionExpirationDuration = time.Hour * 24 * 30
// TrialSubscriptionMaxUserLimit 试用订阅最大用户上限
TrialSubscriptionMaxUserLimit = 2
// Inactive 未激活
Inactive int = 0
// Activated 已激活
Activated int = 1
// maxUserQuerySize 用户最大区间数
maxUserQuerySize = 100
// minUserQuerySize 用户最小区间数
minUserQuerySize = 1
)
// OwnerCreateOrganization 创建组织
func (j *JinmuHealth) OwnerCreateOrganization(ctx context.Context, req *corepb.OwnerCreateOrganizationRequest, resp *corepb.OwnerCreateOrganizationResponse) error {
l := rpc.ContextLogger(ctx)
userID, ok := auth.UserIDFromContext(ctx)
if !ok {
return NewError(ErrInvalidUser, errors.New("failed to get userID from context"))
}
organizationCount, err := j.datastore.GetOrganizationCountByOwnerID(ctx, int(userID))
if err != nil {
l.WithError(err).Warn("database error")
return NewError(ErrDatabase, fmt.Errorf("failed to get organization count by ownerID: %d :%s", int(userID), err.Error()))
}
if organizationCount > 0 {
return NewError(ErrOrganizationCountExceedsMaxLimits, fmt.Errorf("count of organization of owner %d exceeds the max limits", int(userID)))
}
now := time.Now()
owner, _ := j.datastore.FindUserByUserID(ctx, int(userID))
o := &mysqldb.Organization{
Name: req.Profile.Name,
State: req.Profile.Address.State,
City: req.Profile.Address.City,
Street: req.Profile.Address.Street,
Phone: req.Profile.Phone,
Contact: req.Profile.Contact,
Type: req.Profile.Type,
Country: req.Profile.Address.Country,
District: req.Profile.Address.District,
PostalCode: req.Profile.Address.PostalCode,
Email: req.Profile.Email,
IsValid: 1,
CustomizedCode: owner.CustomizedCode,
}
// TODO: CreateOrganization,CreateOrganizationOwner 要在同一个事务
if errCreateOrganization := j.datastore.CreateOrganization(ctx, o); errCreateOrganization != nil {
l.WithError(errCreateOrganization).Warn("database error")
return NewError(ErrDatabase, fmt.Errorf("failed to create organization: %s", errCreateOrganization.Error()))
}
if errCreateOrganizationOwner := j.datastore.CreateOrganizationOwner(ctx, &mysqldb.OrganizationOwner{
OrganizationID: o.OrganizationID,
OwnerID: int(userID),
CreatedAt: now,
UpdatedAt: now,
}); errCreateOrganizationOwner != nil {
l.WithError(errCreateOrganizationOwner).Warn("database error")
return NewError(ErrDatabase, fmt.Errorf("failed to create organizationOwner: %s", errCreateOrganizationOwner.Error()))
}
users := make([]*mysqldb.OrganizationUser, 1)
users[0] = &mysqldb.OrganizationUser{
OrganizationID: o.OrganizationID,
UserID: int(userID),
CreatedAt: now,
UpdatedAt: now,
}
errCreateOrganizationUsers := j.datastore.CreateOrganizationUsers(ctx, users)
if errCreateOrganizationUsers != nil {
l.WithError(errCreateOrganizationUsers).Warn("database error")
return NewError(ErrDatabase, fmt.Errorf("failed to create organizationUsers: %s", errCreateOrganizationUsers.Error()))
}
resp.OrganizationId = int32(o.OrganizationID)
resp.Profile = req.Profile
return nil
}
// OwnerGetOrganizations 查看拥有的组织
func (j *JinmuHealth) OwnerGetOrganizations(ctx context.Context, req *corepb.OwnerGetOrganizationsRequest, repl *corepb.OwnerGetOrganizationsResponse) error {
l := rpc.ContextLogger(ctx)
userID, ok := auth.UserIDFromContext(ctx)
if !ok {
return NewError(ErrInvalidUser, errors.New("failed to get userID from context"))
}
organizations, err := j.datastore.FindOrganizationsByOwner(ctx, int(userID))
if err != nil {
l.WithError(err).Warn("database error")
return NewError(ErrDatabase, fmt.Errorf("failed to find organization by owner:%d: %s", int(userID), err.Error()))
}
repl.Organizations = make([]*corepb.Organization, len(organizations))
for i, o := range organizations {
subscriptions, _ := j.datastore.FindSubscriptionsByOrganizationID(ctx, o.OrganizationID)
repl.Organizations[i] = &corepb.Organization{
OrganizationId: int32(o.OrganizationID),
Profile: &corepb.OrganizationProfile{
Name: o.Name,
Address: &corepb.Address{
Street: o.Street,
City: o.City,
State: o.State,
Country: o.Country,
District: o.District,
PostalCode: o.PostalCode,
},
Phone: o.Phone,
Contact: o.Contact,
Type: o.Type,
Email: o.Email,
},
}
if len(subscriptions) != 0 {
subscription := subscriptions[0]
activatedAt, _ := ptypes.TimestampProto(subscription.ActivatedAt)
expiredAt, _ := ptypes.TimestampProto(subscription.ExpiredAt)
totalUserCount, _ := j.datastore.GetExistingUserCountByOrganizationID(ctx, o.OrganizationID)
createdAt, _ := ptypes.TimestampProto(subscription.CreatedAt)
repl.Organizations[i].Subscription = &corepb.Subscription{
SubscriptionType: mapDBSubscriptionTypeToProto(subscription.SubscriptionType),
ActiveTime: activatedAt,
ExpiredTime: expiredAt,
Active: subscription.Active == 1,
TotalUserCount: int32(totalUserCount),
MaxUserLimits: int32(subscription.MaxUserLimits),
CreatedTime: createdAt,
}
}
}
return nil
}
// OwnerGetOrganizationSubscription Owner查看组织订阅
func (j *JinmuHealth) OwnerGetOrganizationSubscription(ctx context.Context, req *corepb.OwnerGetOrganizationSubscriptionRequest, repl *corepb.OwnerGetOrganizationSubscriptionResponse) error {
l := rpc.ContextLogger(ctx)
userID, ok := auth.UserIDFromContext(ctx)
if !ok {
return NewError(ErrInvalidUser, errors.New("failed to find userID from context"))
}
ok, err := j.datastore.CheckOrganizationOwner(ctx, int(userID), int(req.OrganizationId))
if err != nil || !ok {
l.WithError(err).Warn("database error")
return NewError(ErrDatabase, fmt.Errorf("failed to check organization %d and owner %d: %s", req.OrganizationId, userID, err.Error()))
}
subscriptions, errFindSubscriptionsByOrganizationID := j.datastore.FindSubscriptionsByOrganizationID(ctx, int(req.OrganizationId))
if errFindSubscriptionsByOrganizationID != nil {
l.WithError(errFindSubscriptionsByOrganizationID).Warn("database error")
return NewError(ErrDatabase, fmt.Errorf("failed to find subscription by organizationID: %d: %s", req.OrganizationId, errFindSubscriptionsByOrganizationID.Error()))
}
if len(subscriptions) != 0 {
subscription := subscriptions[0]
activatedAt, _ := ptypes.TimestampProto(subscription.ActivatedAt)
expiredAt, _ := ptypes.TimestampProto(subscription.ExpiredAt)
totalUserCount, _ := j.datastore.GetExistingUserCountByOrganizationID(ctx, int(req.OrganizationId))
createdAt, _ := ptypes.TimestampProto(subscription.CreatedAt)
repl.Subscription = &corepb.Subscription{
ActiveTime: activatedAt,
ExpiredTime: expiredAt,
Active: subscription.Active == 1,
TotalUserCount: int32(totalUserCount),
MaxUserLimits: int32(subscription.MaxUserLimits),
CreatedTime: createdAt,
SubscriptionType: mapDBSubscriptionTypeToProto(subscription.SubscriptionType),
}
}
return nil
}
func mapDBSubscriptionTypeToProto(dbType mysqldb.SubscriptionType) subscriptionpb.SubscriptionType {
switch dbType {
case mysqldb.SubscriptionTypeCustomizedVersion:
return subscriptionpb.SubscriptionType_SUBSCRIPTION_TYPE_CUSTOMIZED_VERSION
case mysqldb.SubscriptionTypeTrialVersion:
return subscriptionpb.SubscriptionType_SUBSCRIPTION_TYPE_TRIAL_VERSION
case mysqldb.SubscriptionTypeGoldenVersion:
return subscriptionpb.SubscriptionType_SUBSCRIPTION_TYPE_GOLDEN_VERSION
case mysqldb.SubscriptionTypePlatinumVersion:
return subscriptionpb.SubscriptionType_SUBSCRIPTION_TYPE_PLATINUM_VERSION
case mysqldb.SubscriptionTypeDiamondVersion:
return subscriptionpb.SubscriptionType_SUBSCRIPTION_TYPE_DIAMOND_VERSION
case mysqldb.SubscriptionTypeGiftVersion:
return subscriptionpb.SubscriptionType_SUBSCRIPTION_TYPE_GIFT_VERSION
}
return subscriptionpb.SubscriptionType_SUBSCRIPTION_TYPE_INVALID
}
// OwnerAddOrganizationUsers 拥有者向组织下添加用户
func (j *JinmuHealth) OwnerAddOrganizationUsers(ctx context.Context, req *corepb.OwnerAddOrganizationUsersRequest, repl *corepb.OwnerAddOrganizationUsersResponse) error {
l := rpc.ContextLogger(ctx)
// TODO 这里的添加CreateOrganizationUsers和AddUsersIntoSubscription应该写在同一个事务中
userID, ok := auth.UserIDFromContext(ctx)
if !ok {
return NewError(ErrInvalidUser, errors.New("failed to find userID from context"))
}
ok, err := j.datastore.CheckOrganizationOwner(ctx, int(userID), int(req.OrganizationId))
if err != nil || !ok {
l.WithError(err).Warn("database error")
return NewError(ErrDatabase, fmt.Errorf("failed to check organization %d and owner %d: %s", int(req.OrganizationId), int(userID), err.Error()))
}
users := make([]*mysqldb.OrganizationUser, len(req.UserIdList))
now := time.Now()
for idx, uid := range req.UserIdList {
users[idx] = &mysqldb.OrganizationUser{
OrganizationID: int(req.OrganizationId),
UserID: int(uid),
CreatedAt: now,
UpdatedAt: now,
}
}
// TODO: CreateOrganizationUsers,AddUsersIntoSubscription 要在同一个事务
errCreateOrganizationUsers := j.datastore.CreateOrganizationUsers(ctx, users)
if errCreateOrganizationUsers != nil {
l.WithError(errCreateOrganizationUsers).Warn("database error")
return NewError(ErrDatabase, fmt.Errorf("failed to create organizationUsers: %s", errCreateOrganizationUsers.Error()))
}
reqGetUserSubscriptions := new(subscriptionpb.GetUserSubscriptionsRequest)
reqGetUserSubscriptions.UserId = userID
respGetUserSubscriptions, errGetUserSubscriptions := j.subscriptionSvc.GetUserSubscriptions(ctx, reqGetUserSubscriptions)
if errGetUserSubscriptions != nil {
return errGetUserSubscriptions
}
// 获取当前正在使用的订阅
selectedSubscription := new(subscriptionpb.Subscription)
for _, item := range respGetUserSubscriptions.Subscriptions {
if item.IsSelected {
selectedSubscription = item
}
}
// 将用户添加到订阅中
reqAddUsersIntoSubscription := new(subscriptionpb.AddUsersIntoSubscriptionRequest)
reqAddUsersIntoSubscription.OwnerId = userID
reqAddUsersIntoSubscription.SubscriptionId = selectedSubscription.SubscriptionId
reqAddUsersIntoSubscription.UserIdList = req.UserIdList
_, errAddUsersIntoSubscription := j.subscriptionSvc.AddUsersIntoSubscription(ctx, reqAddUsersIntoSubscription)
if errAddUsersIntoSubscription != nil {
return errAddUsersIntoSubscription
}
usersList, errFindOrganizationUsersIDList := j.datastore.FindOrganizationUsersIDList(ctx, int(req.OrganizationId))
if errFindOrganizationUsersIDList != nil {
l.WithError(errFindOrganizationUsersIDList).Warn("database error")
return NewError(ErrDatabase, fmt.Errorf("failed to get user lists of the organization: %s", errFindOrganizationUsersIDList.Error()))
}
repl.User = make([]*corepb.User, len(usersList))
for idx, u := range usersList {
// 获取用户的所有信息
reqGetUserAndProfileInformation := new(jinmuidpb.GetUserAndProfileInformationRequest)
reqGetUserAndProfileInformation.UserId = int32(u)
reqGetUserAndProfileInformation.IsSkipVerifyToken = true
respGetUserAndProfileInformation, errGetUserAndProfileInformation := j.jinmuidSvc.GetUserAndProfileInformation(ctx, reqGetUserAndProfileInformation)
if errGetUserAndProfileInformation != nil {
return errGetUserAndProfileInformation
}
birthday, _ := ptypes.Timestamp(respGetUserAndProfileInformation.Profile.BirthdayTime)
repl.User[idx] = &corepb.User{
UserId: int32(u),
Username: respGetUserAndProfileInformation.SigninUsername,
RegisterType: respGetUserAndProfileInformation.RegisterType,
IsProfileCompleted: respGetUserAndProfileInformation.IsProfileCompleted,
Profile: &corepb.UserProfile{
Nickname: respGetUserAndProfileInformation.Profile.Nickname,
Gender: respGetUserAndProfileInformation.Profile.Gender,
Age: int32(age.Age(birthday)),
Height: respGetUserAndProfileInformation.Profile.Height,
Weight: respGetUserAndProfileInformation.Profile.Weight,
BirthdayTime: respGetUserAndProfileInformation.Profile.BirthdayTime,
Email: respGetUserAndProfileInformation.SecureEmail,
Phone: respGetUserAndProfileInformation.SigninPhone,
Remark: respGetUserAndProfileInformation.Remark,
UserDefinedCode: respGetUserAndProfileInformation.UserDefinedCode,
},
IsRemovable: !(int32(u) == userID),
}
}
return nil
}
// OwnerDeleteOrganizationUsers 拥有者组织删除用户
func (j *JinmuHealth) OwnerDeleteOrganizationUsers(ctx context.Context, req *corepb.OwnerDeleteOrganizationUsersRequest, repl *corepb.OwnerDeleteOrganizationUsersResponse) error {
l := rpc.ContextLogger(ctx)
// TODO 这里的添加DeleteOrganizationUsers和DeleteUsersFromSubscription应该写在同一个事务中
ownerID, ok := auth.UserIDFromContext(ctx)
if !ok {
return NewError(ErrInvalidUser, errors.New("failed to get userID from context"))
}
ok, err := j.datastore.CheckOrganizationOwner(ctx, int(ownerID), int(req.OrganizationId))
if err != nil || !ok {
l.WithError(err).Warn("database error")
return NewError(ErrDatabase, fmt.Errorf("failed to check organization and owner: %s", err.Error()))
}
for _, userID := range req.UserIdList {
if userID == ownerID {
return NewError(ErrCannotDeleteOwner, errors.New("cannot delete organization owner"))
}
}
if err := j.datastore.DeleteOrganizationUsers(ctx, req.UserIdList, req.OrganizationId); err != nil {
l.WithError(err).Warn("database error")
return NewError(ErrDatabase, fmt.Errorf("failed to delete connection relation of organization %d and users %d: %s", req.OrganizationId, req.UserIdList, err.Error()))
}
// 获取当前拥有者的订阅
reqGetUserSubscriptions := new(subscriptionpb.GetUserSubscriptionsRequest)
reqGetUserSubscriptions.UserId = ownerID
respGetUserSubscriptions, errGetUserSubscriptions := j.subscriptionSvc.GetUserSubscriptions(ctx, reqGetUserSubscriptions)
if errGetUserSubscriptions != nil {
return errGetUserSubscriptions
}
// 获取当前正在使用的订阅
selectedSubscription := new(subscriptionpb.Subscription)
for _, item := range respGetUserSubscriptions.Subscriptions {
if item.IsSelected {
selectedSubscription = item
}
}
reqDeleteUsersFromSubscription := new(subscriptionpb.DeleteUsersFromSubscriptionRequest)
reqDeleteUsersFromSubscription.OwnerId = ownerID
reqDeleteUsersFromSubscription.SubscriptionId = selectedSubscription.SubscriptionId
reqDeleteUsersFromSubscription.UserIdList = req.UserIdList
_, errDeleteUsersFromSubscription := j.subscriptionSvc.DeleteUsersFromSubscription(ctx, reqDeleteUsersFromSubscription)
if errDeleteUsersFromSubscription != nil {
return errDeleteUsersFromSubscription
}
repl.Tip = "delete users from Organization successful"
return nil
}
// OwnerGetOrganizationUsers Owner 获取组织中的 User
func (j *JinmuHealth) OwnerGetOrganizationUsers(ctx context.Context, req *corepb.OwnerGetOrganizationUsersRequest, repl *corepb.OwnerGetOrganizationUsersResponse) error {
l := rpc.ContextLogger(ctx)
userID, ok := auth.UserIDFromContext(ctx)
if !ok {
return NewError(ErrInvalidUser, errors.New("failed to find userID from context"))
}
ok, err := j.datastore.CheckOrganizationOwner(ctx, int(userID), int(req.OrganizationId))
if err != nil || !ok {
l.WithError(err).Warn("database error")
return NewError(ErrDatabase, fmt.Errorf("failed to check organization %d and owner %d: %s", int(req.OrganizationId), int(userID), err.Error()))
}
isValid := j.datastore.CheckOrganizationIsValid(ctx, int(req.OrganizationId))
if !isValid {
return NewError(ErrInvalidOrganization, fmt.Errorf("organization %d is invalid", req.OrganizationId))
}
offset := req.Offset
size := req.Size
keyword := req.Keyword
if size != -1 && (size > maxUserQuerySize || size < minUserQuerySize) {
return NewError(ErrOrganizationQueryUserExceedsLimit, errors.New("size exceeds the maximum or minimum limit"))
}
users, err := j.searchUserByKeyword(ctx, req.OrganizationId, keyword, size, offset)
if err != nil {
l.WithError(err).Warn("database error")
return NewErrorCause(ErrDatabase, errors.New("database error"), err.Error())
}
repl.UserList = make([]*corepb.User, len(users))
for idx, u := range users {
birth, err := ptypes.TimestampProto(u.Birthday)
if err != nil {
birth = nil
}
gender, errMapDBGenderToProto := mapDBGenderToProto(u.Gender)
if errMapDBGenderToProto != nil {
return NewError(ErrInvalidGender, errMapDBGenderToProto)
}
repl.UserList[idx] = &corepb.User{
UserId: int32(u.UserID),
Username: u.Username,
RegisterType: u.RegisterType,
IsProfileCompleted: u.IsProfileCompleted,
IsRemovable: u.IsRemovable,
Profile: &corepb.UserProfile{
Nickname: u.Nickname,
NicknameInitial: u.NicknameInitial,
BirthdayTime: birth,
Age: int32(age.Age(u.Birthday)),
Gender: gender,
Height: int32(u.Height),
Weight: int32(u.Weight),
Phone: u.Phone,
Email: u.Email,
UserDefinedCode: u.UserDefinedCode,
Remark: u.Remark,
State: u.State,
City: u.City,
Street: u.Street,
Country: u.Country,
},
}
}
return nil
}
// searchUserByKeyword 通过关键字搜索用户
func (j *JinmuHealth) searchUserByKeyword(ctx context.Context, organizationID int32, keyword string, size int32, offset int32) ([]*mysqldb.User, error) {
if keyword != "" {
users, err := j.datastore.FindOrganizationUsersByKeyword(ctx, organizationID, keyword, size, offset)
if err != nil {
return []*mysqldb.User{}, NewError(ErrDatabase, fmt.Errorf("failed to find users of organization %d by keyword %s,size %d, offset %d: %s", organizationID, keyword, size, offset, err.Error()))
}
return users, nil
}
users, err := j.datastore.FindOrganizationUsersByOffset(ctx, organizationID, size, offset)
if err != nil {
return []*mysqldb.User{}, NewError(ErrDatabase, fmt.Errorf("failed to find users of organization %d by size %d, offset %d: %s", organizationID, size, offset, err.Error()))
}
return users, nil
}
// GetOrganizationIDByUserID 根据userID查找对应的organizationID
func (j *JinmuHealth) GetOrganizationIDByUserID(ctx context.Context, req *corepb.GetOrganizationIDByUserIDRequest, repl *corepb.GetOrganizationIDByUserIDResponse) error {
userID := req.UserId
o, err := j.datastore.FindOrganizationByUserID(ctx, int(userID))
if err != nil {
return NewError(ErrDatabase, fmt.Errorf("failed to find organization by userID %d: %s", int(userID), err.Error()))
}
repl.OrganizationId = int32(o.OrganizationID)
isOwner, err := j.datastore.CheckOrganizationOwner(ctx, int(userID), o.OrganizationID)
if err != nil {
return NewError(ErrDatabase, fmt.Errorf("failed to check organization %d and ownerID %d: %s", o.OrganizationID, int(userID), err.Error()))
}
repl.IsOwner = isOwner
return nil
}
|
package main
type callback func(params ...string) (interface{}, error)
|
package test
import (
"testing"
)
func TestAssertEqual(t *testing.T) {
AssertEqual(t, true, true)
AssertEqual(t, true, 1 == 1)
AssertEqual(t, 2, 3-1)
AssertEqual(t, 0, 0)
AssertEqual(t, int(0), int64(0))
AssertEqual(t, "hello", "h"+"ello")
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.