text stringlengths 11 4.05M |
|---|
// Copyright 2020 The VectorSQL Authors.
//
// Code is licensed under Apache License, Version 2.0.
package datablocks
import (
"sync"
"expressions"
"planners"
"github.com/gammazero/workerpool"
)
func (block *DataBlock) AggregateSelectionByPlan(fields []string, plan *planners.SelectionPlan) ([]expressions.IExpression, error) {
var errs []error
var mu sync.Mutex
projects := plan.Projects
projectExprs, err := planners.BuildExpressions(projects)
if err != nil {
return nil, err
}
workerPool := workerpool.New(len(projectExprs))
for i := range projectExprs {
expr := projectExprs[i]
workerPool.Submit(func() {
// Compute the column.
it, err := block.MixsIterator(fields)
if err != nil {
errs = append(errs, err)
return
}
params := make(expressions.Map)
for it.Next() {
mixed := it.Value()
for j := range mixed {
params[it.Column(j).Name] = mixed[j]
}
if _, err := expr.Update(params); err != nil {
mu.Lock()
errs = append(errs, err)
mu.Unlock()
return
}
}
})
}
workerPool.StopWait()
if len(errs) > 0 {
return nil, errs[0]
}
return projectExprs, nil
}
|
package pkg
// BaseConfig
type KafkaConf struct {
EnableSASL bool `json:"enable_sasl"`
Brokers []string `json:"brokers"`
User string `json:"user"`
Password string `json:"password"`
}
type NsqConf struct {
}
type MongoDBConf struct {
}
type ESConf struct {
}
// MQEvent
type MQEvent struct {
Database string `json:"database"`
Table string `json:"table"`
Action string `json:"action"`
Before map[string]interface{} `json:"before"`
After map[string]interface{} `json:"after"`
OrgRow [][]interface{} `json:"org_row"`
EventHeader EventHeader `json:"event_header"`
}
type EventHeader struct {
Timestamp uint32 `json:"timestamp"`
LogPos uint32 `json:"log_pos"`
}
|
package zredis
import (
"bufio"
"github.com/pkg/errors"
"strconv"
)
type Resp struct {
RespType int
Val interface{}
}
func (r *Resp) String() (string) {
switch rsp := r.Val.(type) {
case string:
return rsp
case []byte:
return string(rsp)
case int:
return strconv.Itoa(rsp)
case float64:
return string(strconv.AppendFloat(buffer[:0], rsp, 'g', -1, 64))
default:
return TypeException
}
}
func (r *Resp) Btyes() ([]byte) {
switch rsp := r.Val.(type) {
case string:
return []byte(rsp)
case []byte:
return rsp
case int:
return strconv.AppendInt(convertBuf[:0], int64(rsp), 10)
case float64:
return strconv.AppendFloat(buffer[:0], rsp, 'g', -1, 64)
default:
return []byte(TypeException)
}
}
func Response(r *bufio.Reader) (*Resp, error) {
peek, err := r.Peek(2)
if err != nil {
return &Resp{0, nil}, err
}
switch peek[0] {
case responseNormalPrefix:
return NormalReply(r)
case responseErrorPrefix:
return ErrorReply(r)
case responseIntegerPrefix:
return IntegerReply(r)
case responseBlockPrefix:
return BlockReply(r)
case responseLinePrefix:
return ArrayReply(r)
default:
return &Resp{0, peek}, errors.New("unknow reply:" + string(peek))
}
return &Resp{0, peek}, errors.New("unknow reply:" + string(peek))
}
func NormalReply(r *bufio.Reader) (*Resp, error) {
str, err := r.ReadBytes(end)
if err != nil {
return &Resp{1, nil}, err
}
return &Resp{1, string(str[1:])}, nil
}
func ErrorReply(r *bufio.Reader) (*Resp, error) {
str, err := r.ReadBytes(end)
if err != nil {
return &Resp{2, nil}, err
}
return &Resp{2, str[1:]}, nil
}
func IntegerReply(r *bufio.Reader) (*Resp, error) {
bytes, err := r.ReadBytes(end)
if err != nil {
return &Resp{3, nil}, err
}
i, err := strconv.ParseInt(string(bytes[1:len(bytes)-2]), 10, 64)
if err != nil {
return &Resp{3, nil}, err
}
return &Resp{3, i}, nil
}
func BlockReply(r *bufio.Reader) (*Resp, error) {
bytes, err := r.ReadBytes(end)
if err != nil {
return &Resp{4, nil}, err
}
size, err := strconv.ParseInt(string(bytes[1:len(bytes)-2]), 10, 64)
if err != nil {
return &Resp{4, nil}, err
}
if size <= 0 {
return &Resp{4, nil}, errors.New("read bite size is 0")
}
total := make([]byte, size)
b2 := total
var n int
for len(b2) > 0 {
n, err = r.Read(b2)
if err != nil {
return &Resp{4, nil}, err
}
b2 = b2[n:]
}
trail := make([]byte, 2)
for i := 0; i < 2; i++ {
c, err := r.ReadByte()
if err != nil {
return &Resp{4, nil}, err
}
trail[i] = c
}
return &Resp{4, total}, nil
}
func ArrayReply(r *bufio.Reader) (*Resp, error) {
peer, err := r.ReadBytes(end)
if err != nil {
return &Resp{5, nil}, err
}
size, err := strconv.ParseInt(string(peer[1:len(peer)-2]), 10, 16)
if err != nil {
return &Resp{5, nil}, err
}
if size <= 0 {
return &Resp{5, nil}, errors.New("read to bite is 0")
}
return &Resp{5, nil}, nil
}
|
package models
import(
"encoding/json"
)
/**
* Type definition for LockingProtocolEnum enum
*/
type LockingProtocolEnum int
/**
* Value collection for LockingProtocolEnum enum
*/
const (
LockingProtocol_KSETREADONLY LockingProtocolEnum = 1 + iota
LockingProtocol_KSETATIME
)
func (r LockingProtocolEnum) MarshalJSON() ([]byte, error) {
s := LockingProtocolEnumToValue(r)
return json.Marshal(s)
}
func (r *LockingProtocolEnum) UnmarshalJSON(data []byte) error {
var s string
json.Unmarshal(data, &s)
v := LockingProtocolEnumFromValue(s)
*r = v
return nil
}
/**
* Converts LockingProtocolEnum to its string representation
*/
func LockingProtocolEnumToValue(lockingProtocolEnum LockingProtocolEnum) string {
switch lockingProtocolEnum {
case LockingProtocol_KSETREADONLY:
return "kSetReadOnly"
case LockingProtocol_KSETATIME:
return "kSetAtime"
default:
return "kSetReadOnly"
}
}
/**
* Converts LockingProtocolEnum Array to its string Array representation
*/
func LockingProtocolEnumArrayToValue(lockingProtocolEnum []LockingProtocolEnum) []string {
convArray := make([]string,len( lockingProtocolEnum))
for i:=0; i<len(lockingProtocolEnum);i++ {
convArray[i] = LockingProtocolEnumToValue(lockingProtocolEnum[i])
}
return convArray
}
/**
* Converts given value to its enum representation
*/
func LockingProtocolEnumFromValue(value string) LockingProtocolEnum {
switch value {
case "kSetReadOnly":
return LockingProtocol_KSETREADONLY
case "kSetAtime":
return LockingProtocol_KSETATIME
default:
return LockingProtocol_KSETREADONLY
}
}
|
package cloudformation
// AWSAppSyncDataSource_HttpConfig AWS CloudFormation Resource (AWS::AppSync::DataSource.HttpConfig)
// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-appsync-datasource-httpconfig.html
type AWSAppSyncDataSource_HttpConfig struct {
// Endpoint AWS CloudFormation Property
// Required: true
// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-appsync-datasource-httpconfig.html#cfn-appsync-datasource-httpconfig-endpoint
Endpoint string `json:"Endpoint,omitempty"`
}
// AWSCloudFormationType returns the AWS CloudFormation resource type
func (r *AWSAppSyncDataSource_HttpConfig) AWSCloudFormationType() string {
return "AWS::AppSync::DataSource.HttpConfig"
}
|
package timecode
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNewRate(t *testing.T) {
t.Parallel()
rate, err := NewRate(30, false)
assert.Nil(t, err)
assert.Equal(t, rate.FPS(), 30.0)
assert.Equal(t, rate.DropFrame(), false)
rate, err = NewRate(30, true)
assert.Nil(t, err)
assert.Equal(t, rate.FPS(), 30.0)
assert.Equal(t, rate.DropFrame(), true)
_, err = NewRate(0, true)
assert.NotNil(t, err)
_, err = NewRate(-100, true)
assert.NotNil(t, err)
}
func TestSMTPERates(t *testing.T) {
assert.Equal(t, R2997.FPS(), 29.97)
assert.Equal(t, R2997.DropFrame(), false)
assert.Equal(t, R2997DF.FPS(), 29.97)
assert.Equal(t, R2997DF.DropFrame(), true)
assert.Equal(t, R30.FPS(), 30.0)
assert.Equal(t, R30.DropFrame(), false)
assert.Equal(t, R5994.FPS(), 59.94)
assert.Equal(t, R5994.DropFrame(), false)
assert.Equal(t, R5994DF.FPS(), 59.94)
assert.Equal(t, R5994DF.DropFrame(), true)
assert.Equal(t, R25.FPS(), 25.0)
assert.Equal(t, R25.DropFrame(), false)
assert.Equal(t, R50.FPS(), 50.0)
assert.Equal(t, R50.DropFrame(), false)
assert.Equal(t, R2398.FPS(), 23.98)
assert.Equal(t, R2398.DropFrame(), false)
assert.Equal(t, R60.FPS(), 60.0)
assert.Equal(t, R60.DropFrame(), false)
assert.Equal(t, R120.FPS(), 120.0)
assert.Equal(t, R120.DropFrame(), false)
assert.Equal(t, R240.FPS(), 240.0)
assert.Equal(t, R240.DropFrame(), false)
}
func TestParseRate(t *testing.T) {
rate, err := ParseRate("30000/1001", false)
assert.Nil(t, err)
assert.Equal(t, 29.97, rate.FPS())
rate, err = ParseRate("24000/1001", false)
assert.Nil(t, err)
assert.Equal(t, 23.98, rate.FPS())
rate, err = ParseRate("60000/1001", false)
assert.Nil(t, err)
assert.Equal(t, 59.94, rate.FPS())
rate, err = ParseRate("30/1", false)
assert.Nil(t, err)
assert.Equal(t, 30.0, rate.FPS())
_, err = ParseRate("30/0", false)
assert.NotNil(t, err)
_, err = ParseRate("invalid", false)
assert.NotNil(t, err)
_, err = ParseRate("", false)
assert.NotNil(t, err)
}
|
package fastdb
import (
"io"
"log"
"sort"
"sync"
"time"
"fastdb/index"
"fastdb/storage"
)
// DataType Define the data structure type.
type DataType = uint16
// Five different data types, support String, List, Hash, Set, Sorted Set right now.
const (
String DataType = iota
List
Hash
Set
ZSet
)
// The operations of a String Type, will be a part of Entry, the same for the other four types.
const (
StringSet uint16 = iota
StringRem
StringExpire
StringPersist
)
// The operations of List.
const (
ListLPush uint16 = iota
ListRPush
ListLPop
ListRPop
ListLRem
ListLInsert
ListLSet
ListLTrim
ListLClear
ListLExpire
)
// The operations of Hash.
const (
HashHSet uint16 = iota
HashHDel
HashHClear
HashHExpire
)
// The operations of Set.
const (
SetSAdd uint16 = iota
SetSRem
SetSMove
SetSClear
SetSExpire
)
// The operations of Sorted Set.
const (
ZSetZAdd uint16 = iota
ZSetZRem
ZSetZClear
ZSetZExpire
)
// build string indexes.
func (db *FastDB) buildStringIndex(idx *index.Indexer, entry *storage.Entry) {
if db.strIndex == nil || idx == nil {
return
}
switch entry.GetMark() {
case StringSet:
db.strIndex.idxList.Put(idx.Meta.Key, idx)
case StringRem:
db.strIndex.idxList.Remove(idx.Meta.Key)
case StringExpire:
if entry.Timestamp < uint64(time.Now().Unix()) {
db.strIndex.idxList.Remove(idx.Meta.Key)
} else {
db.expires[String][string(idx.Meta.Key)] = int64(entry.Timestamp)
}
case StringPersist:
db.strIndex.idxList.Put(idx.Meta.Key, idx)
delete(db.expires[String], string(idx.Meta.Key))
}
}
// load String、List、Hash、Set、ZSet indexes from db files.
func (db *FastDB) loadIdxFromFiles() error {
if db.archFiles == nil && db.activeFile == nil {
return nil
}
wg := sync.WaitGroup{}
wg.Add(DataStructureNum)
for dataType := 0; dataType < DataStructureNum; dataType++ {
go func(dType uint16) {
defer func() {
wg.Done()
}()
// archived files
var fileIds []int
dbFile := make(map[uint32]*storage.DBFile)
for k, v := range db.archFiles[dType] {
dbFile[k] = v
fileIds = append(fileIds, int(k))
}
// active file
dbFile[db.activeFileIds[dType]] = db.activeFile[dType]
fileIds = append(fileIds, int(db.activeFileIds[dType]))
// load the db files in a specified order.
sort.Ints(fileIds)
for i := 0; i < len(fileIds); i++ {
fid := uint32(fileIds[i])
df := dbFile[fid]
var offset int64 = 0
for offset <= db.config.BlockSize {
if e, err := df.Read(offset); err == nil {
idx := &index.Indexer{
Meta: e.Meta,
FileId: fid,
EntrySize: e.Size(),
Offset: offset,
}
offset += int64(e.Size())
if len(e.Meta.Key) > 0 {
if err := db.buildIndex(e, idx); err != nil {
log.Fatalf("a fatal err occurred, the db can not open.[%+v]", err)
}
}
} else {
if err == io.EOF {
break
}
log.Fatalf("a fatal err occurred, the db can not open.[%+v]", err)
}
}
}
}(uint16(dataType))
}
wg.Wait()
return nil
}
// build hash indexes.
func (db *FastDB) buildHashIndex(idx *index.Indexer, entry *storage.Entry) {
if db.hashIndex == nil || idx == nil {
return
}
key := string(idx.Meta.Key)
switch entry.GetMark() {
case HashHSet:
db.hashIndex.indexes.HSet(key, string(idx.Meta.Extra), idx.Meta.Value)
case HashHDel:
db.hashIndex.indexes.HDel(key, string(idx.Meta.Extra))
case HashHClear:
db.hashIndex.indexes.HClear(key)
case HashHExpire:
if entry.Timestamp < uint64(time.Now().Unix()) {
db.hashIndex.indexes.HClear(key)
} else {
db.expires[Hash][key] = int64(entry.Timestamp)
}
}
}
|
// Copyright 2017 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package example
import (
"context"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: Pass,
Desc: "Always passes",
Contacts: []string{"nya@chromium.org", "tast-owners@google.com"},
Attr: []string{"group:mainline", "group:hw_agnostic"},
})
}
func Pass(ctx context.Context, s *testing.State) {
// No errors means the test passed.
}
|
package types
const ALL_GROUPNAME = "ALL"
const MASTER_GROUPNAME = "Master"
const ETCD_GROUPNAME = "Etcd"
const SERVICES_CHECKNAME = "Services"
const CONTAINERS_CHECKNAME = "Containers"
const CERTIFICATES_CHECKNAME = "Certificates"
const DISKUSAGE_CHECKNAME = "DiskUsage"
const KUBERNETES_CHECKNAME = "Kubernetes"
type Config struct {
Ssh SSHConfig
ClusterGroups []ClusterGroup
}
type ClusterGroup struct {
Name string
Nodes []Node
Services []string
Containers []string
Certificates []string
DiskUsage DiskUsage
Kubernetes Kubernetes
}
type DiskUsage struct {
FileSystemUsage []string
DirectoryUsage []string
}
type Node struct {
Host string
IP string
}
type Kubernetes struct {
Resources []KubernetesResource
}
type KubernetesResource struct {
Type string
Namespace string
Wide bool
}
|
package board
import "fmt"
type Pos struct {
Row int
Col int
}
func (p *Pos) U() *Pos {
return &Pos{
Row: p.Row + 1,
Col: p.Col,
}
}
func (p *Pos) D() *Pos {
return &Pos{
Row: p.Row - 1,
Col: p.Col,
}
}
func (p *Pos) R() *Pos {
return &Pos{
Row: p.Row,
Col: p.Col + 1,
}
}
func (p *Pos) L() *Pos {
return &Pos{
Row: p.Row,
Col: p.Col - 1,
}
}
func (p *Pos) Copy() *Pos {
return &Pos{
Row: p.Row,
Col: p.Col,
}
}
func (p *Pos) Equal(pos2 *Pos) bool {
return p.Row == pos2.Row && p.Col == pos2.Col
}
func (p *Pos) Show() {
fmt.Println(p.Row, p.Col)
}
// So far unused
// func (p *Pos) Validate(NRows int, NCols int) bool {
// return p.Row > 0 && p.Col > 0 && p.Row < NRows && p.Col < NCols
// }
|
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
//creates an http server listening on localhost:8080
http.HandleFunc("/", myFunc)
http.ListenAndServe(":8080", nil)
}
//Sends a greeting with the server's IP included
func myFunc(w http.ResponseWriter, r *http.Request) {
myIP := getMyIP()
_, err := fmt.Fprintln(w, "Hello from", myIP)
if err != nil {
log.Fatalln(err)
}
}
//Gets the public IP of the server
func getMyIP() string {
resp, err := http.Get("http://api.ipify.org")
if err != nil {
log.Fatalln(err)
}
ip, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
return string(ip)
}
|
package main
import "sort"
//899. 有序队列
//给定一个字符串 s 和一个整数 k。你可以从 s 的前 k 个字母中选择一个,并把它加到字符串的末尾。
//
//返回 在应用上述步骤的任意数量的移动后,字典上最小的字符串。
//
//
//
//示例 1:
//
//输入:s = "cba", k = 1
//输出:"acb"
//解释:
//在第一步中,我们将第一个字符(“c”)移动到最后,获得字符串 “bac”。
//在第二步中,我们将第一个字符(“b”)移动到最后,获得最终结果 “acb”。
//示例 2:
//
//输入:s = "baaca", k = 3
//输出:"aaabc"
//解释:
//在第一步中,我们将第一个字符(“b”)移动到最后,获得字符串 “aacab”。
//在第二步中,我们将第三个字符(“c”)移动到最后,获得最终结果 “aaabc”。
//
//
//提示:
//
//1 <= k<= S.length<= 1000
//s只由小写字母组成
//思路 分k=1 与 k>1 情况
// k>1时整个字符串都可以正序排序后的结果
func orderlyQueue(s string, k int) string {
if k == 1 {
result := s
for i := 0; i < len(s); i++ {
s = s[1:] + s[:1]
if s < result {
result = s
}
}
return result
}
array := []byte(s)
sort.Slice(array, func(i, j int) bool {
return array[i] < array[j]
})
return string(array)
}
|
// Copyright 2015 Apcera Inc. All rights reserved.
package aws
import (
"errors"
"fmt"
"net/http"
"os"
"time"
"github.com/apcera/util/uuid"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
const (
noCredsCode = "NoCredentialProviders"
noRegionCode = "MissingRegion"
instanceCount = 1
defaultInstanceType = "t2.micro"
defaultAMI = "ami-5189a661" // ubuntu free tier
defaultVolumeSize = 8 // GB
defaultDeviceName = "/dev/sda1"
defaultVolumeType = "gp2"
// RegionEnv is the env var for the AWS region.
RegionEnv = "AWS_DEFAULT_REGION"
)
// ValidCredentials sends a dummy request to AWS to check if credentials are
// valid. An error is returned if credentials are missing or region is missing.
func ValidCredentials(region string) error {
svc, err := getService(region)
if err != nil {
return fmt.Errorf("failed to get AWS service: %v", err)
}
_, err = svc.DescribeInstances(nil)
awsErr, isAWS := err.(awserr.Error)
if !isAWS {
return err
}
switch awsErr.Code() {
case noCredsCode:
return ErrNoCreds
case noRegionCode:
return ErrNoRegion
}
return nil
}
func getInstanceVolumeIDs(svc *ec2.EC2, instID string) ([]string, error) {
resp, err := svc.DescribeVolumes(&ec2.DescribeVolumesInput{
Filters: []*ec2.Filter{
{Name: aws.String("attachment.instance-id"),
Values: []*string{aws.String(instID)}},
},
})
if err != nil {
return nil, err
}
ids := make([]string, 0, len(resp.Volumes))
for _, v := range resp.Volumes {
if v == nil || v.VolumeId == nil {
continue
}
ids = append(ids, *v.VolumeId)
}
return ids, nil
}
func getNonRootDeviceNames(svc *ec2.EC2, instID string) ([]string, error) {
resp, err := svc.DescribeInstanceAttribute(&ec2.DescribeInstanceAttributeInput{
Attribute: aws.String("blockDeviceMapping"),
InstanceId: aws.String(instID),
})
if err != nil {
return nil, err
}
var rootDevice string
if resp.RootDeviceName != nil && resp.RootDeviceName.Value != nil {
rootDevice = *resp.RootDeviceName.Value
}
names := make([]string, 0, len(resp.BlockDeviceMappings))
for _, m := range resp.BlockDeviceMappings {
if m == nil || m.DeviceName == nil {
continue
}
if *m.DeviceName == rootDevice {
continue
}
names = append(names, *m.DeviceName)
}
return names, nil
}
func setNonRootDeleteOnDestroy(svc *ec2.EC2, instID string, delOnTerm bool) error {
devNames, err := getNonRootDeviceNames(svc, instID)
if err != nil {
return fmt.Errorf("DescribeInstanceAttribute: %s", err)
}
devices := make([]*ec2.InstanceBlockDeviceMappingSpecification, 0, len(devNames))
for _, name := range devNames {
devices = append(devices, &ec2.InstanceBlockDeviceMappingSpecification{
DeviceName: aws.String(name),
Ebs: &ec2.EbsInstanceBlockDeviceSpecification{
DeleteOnTermination: aws.Bool(delOnTerm),
},
})
}
_, err = svc.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
InstanceId: aws.String(instID),
BlockDeviceMappings: devices,
})
if err != nil {
return fmt.Errorf("ModifyInstanceAttribute: %s", err)
}
return nil
}
func getService(region string) (*ec2.EC2, error) {
creds := credentials.NewChainCredentials(
[]credentials.Provider{
&credentials.EnvProvider{}, // check environment
&credentials.SharedCredentialsProvider{}, // check home dir
},
)
if region == "" { // user didn't set region
region = os.Getenv("AWS_DEFAULT_REGION") // aws cli checks this
if region == "" {
region = os.Getenv("AWS_REGION") // aws sdk checks this
}
}
s, err := session.NewSession(&aws.Config{
Credentials: creds,
Region: ®ion,
CredentialsChainVerboseErrors: aws.Bool(true),
HTTPClient: &http.Client{
Timeout: HttpClientTimeout * time.Second},
})
if err != nil {
return nil, fmt.Errorf("failed to create AWS session: %v", err)
}
return ec2.New(s), nil
}
func instanceInfo(vm *VM) *ec2.RunInstancesInput {
if vm.Name == "" {
vm.Name = fmt.Sprintf("libretto-vm-%s", uuid.Variant4())
}
if vm.AMI == "" {
vm.AMI = defaultAMI
}
if vm.InstanceType == "" {
vm.InstanceType = defaultInstanceType
}
var iamInstance *ec2.IamInstanceProfileSpecification
if vm.IamInstanceProfileName != "" {
iamInstance = &ec2.IamInstanceProfileSpecification{
Name: aws.String(vm.IamInstanceProfileName),
}
}
var sid *string
if vm.Subnet != "" {
sid = aws.String(vm.Subnet)
}
var sgid []*string
if len(vm.SecurityGroups) > 0 {
sgid = make([]*string, 0)
for _, sg := range vm.SecurityGroups {
sgid = append(sgid, aws.String(sg.Id))
}
}
devices := make([]*ec2.BlockDeviceMapping, len(vm.Volumes))
for _, volume := range vm.Volumes {
if volume.VolumeSize == new(int64) {
volume.VolumeSize = aws.Int64(int64(defaultVolumeSize))
}
if volume.VolumeType == "" {
volume.VolumeType = defaultVolumeType
}
devices = append(devices, &ec2.BlockDeviceMapping{
DeviceName: aws.String(volume.DeviceName),
Ebs: &ec2.EbsBlockDevice{
VolumeSize: volume.VolumeSize,
VolumeType: aws.String(volume.VolumeType),
DeleteOnTermination: aws.Bool(!vm.KeepRootVolumeOnDestroy),
},
})
}
var privateIPAddress *string
if vm.PrivateIPAddress != "" {
privateIPAddress = aws.String(vm.PrivateIPAddress)
}
return &ec2.RunInstancesInput{
ImageId: aws.String(vm.AMI),
InstanceType: aws.String(vm.InstanceType),
KeyName: aws.String(vm.KeyPair),
MaxCount: aws.Int64(instanceCount),
MinCount: aws.Int64(instanceCount),
BlockDeviceMappings: devices,
Monitoring: &ec2.RunInstancesMonitoringEnabled{
Enabled: aws.Bool(true),
},
SubnetId: sid,
SecurityGroupIds: sgid,
IamInstanceProfile: iamInstance,
PrivateIpAddress: privateIPAddress,
}
}
func hasInstanceID(instance *ec2.Instance) bool {
if instance == nil || instance.InstanceId == nil {
return false
}
return true
}
// UploadKeyPair uploads the public key to AWS with a given name.
// If the public key already exists, then no error is returned.
func UploadKeyPair(publicKey []byte, name string, region string) error {
svc, err := getService(region)
if err != nil {
return fmt.Errorf("failed to get AWS service: %v", err)
}
_, err = svc.ImportKeyPair(&ec2.ImportKeyPairInput{
KeyName: aws.String(name),
PublicKeyMaterial: publicKey,
DryRun: aws.Bool(false),
})
if awsErr, isAWS := err.(awserr.Error); isAWS {
if awsErr.Code() != "InvalidKeyPair.Duplicate" {
return err
}
} else if err != nil {
return err
}
return nil
}
// DeleteKeyPair deletes the given key pair from the given region.
func DeleteKeyPair(name string, region string) error {
svc, err := getService(region)
if err != nil {
return fmt.Errorf("failed to get AWS service: %v", err)
}
if name == "" {
return errors.New("Missing key pair name")
}
_, err = svc.DeleteKeyPair(&ec2.DeleteKeyPairInput{
KeyName: aws.String(name),
DryRun: aws.Bool(false),
})
if err != nil {
return fmt.Errorf("Failed to delete key pair: %s", err)
}
return nil
}
// GetInstanceStatus: returns status of given instances
// Status includes availabilityZone & state
func GetInstanceStatus(svc *ec2.EC2, instID string) (*InstanceStatus, error) {
input := &ec2.DescribeInstanceStatusInput{
IncludeAllInstances: func(val bool) *bool { return &val }(true),
InstanceIds: []*string{&instID}}
statusOutput, err := svc.DescribeInstanceStatus(input)
if err != nil {
return nil, fmt.Errorf("Failed to get instance (instanceId %s) "+
"status: %v", instID, err)
}
instanceStatus := statusOutput.InstanceStatuses[0]
status := &InstanceStatus{
AvailabilityZone: *instanceStatus.AvailabilityZone,
InstanceId: *instanceStatus.InstanceId,
State: *instanceStatus.InstanceState.Name}
return status, nil
}
// getFilters: converts filter map to array of pointers to ec2.Filter objects
func getFilters(filterMap map[string][]*string) []*ec2.Filter {
filters := make([]*ec2.Filter, 0)
for key, values := range filterMap {
filters = append(filters, &ec2.Filter{
Name: &key,
Values: values})
}
return filters
}
// toEc2IpPermissions: converts array of IpPermission objects to
// array of pointer to ec2.IpPermission
func toEc2IpPermissions(ipPermissions []IpPermission) []*ec2.IpPermission {
ec2IpPermissions := make([]*ec2.IpPermission, 0)
for _, ipPermission := range ipPermissions {
ec2IpPermission := &ec2.IpPermission{
FromPort: ipPermission.FromPort,
ToPort: ipPermission.ToPort,
IpProtocol: &ipPermission.IpProtocol}
if ipPermission.Ipv4Ranges != nil && len(ipPermission.Ipv4Ranges) > 0 {
ipRanges := make([]*ec2.IpRange, 0)
for _, ipv4Range := range ipPermission.Ipv4Ranges {
ipRanges = append(ipRanges, &ec2.IpRange{
CidrIp: &ipv4Range})
}
ec2IpPermission.IpRanges = ipRanges
} else {
ipv6Ranges := make([]*ec2.Ipv6Range, 0)
for _, ipv6Range := range ipPermission.Ipv6Ranges {
ipv6Ranges = append(ipv6Ranges, &ec2.Ipv6Range{
CidrIpv6: &ipv6Range})
}
ec2IpPermission.Ipv6Ranges = ipv6Ranges
}
ec2IpPermissions = append(ec2IpPermissions, ec2IpPermission)
}
return ec2IpPermissions
}
// toVMAWSIpPermissions: converts array of ec2.IpPermission to
// array of local IpPermission struct object
func toVMAWSIpPermissions(ec2IpPermissions []*ec2.IpPermission) []IpPermission {
ipPermissions := make([]IpPermission, 0)
for _, ipPermission := range ec2IpPermissions {
ipv4ranges := make([]string, 0)
for _, ipv4range := range ipPermission.IpRanges {
ipv4ranges = append(ipv4ranges, *ipv4range.CidrIp)
}
ipv6ranges := make([]string, 0)
for _, ipv6range := range ipPermission.Ipv6Ranges {
ipv6ranges = append(ipv6ranges, *ipv6range.CidrIpv6)
}
ipPermissions = append(ipPermissions, IpPermission{
FromPort: ipPermission.FromPort,
ToPort: ipPermission.ToPort,
IpProtocol: *ipPermission.IpProtocol,
Ipv4Ranges: ipv4ranges,
Ipv6Ranges: ipv6ranges})
}
return ipPermissions
}
// getVolumeInput: returns input for create volume operation
func getVolumeInput(volume *EbsBlockVolume) *ec2.CreateVolumeInput {
if volume.VolumeSize == nil {
defaultSize := int64(defaultVolumeSize)
volume.VolumeSize = &defaultSize
}
if volume.VolumeType == "" {
volume.VolumeType = defaultVolumeType
}
input := &ec2.CreateVolumeInput{
AvailabilityZone: &volume.AvailabilityZone,
Size: volume.VolumeSize,
VolumeType: &volume.VolumeType,
}
return input
}
// getVMAWSImage: returns local Image struct object for given ec2.Image
func getVMAWSImage(image *ec2.Image) Image {
ebsVolumes := make([]*EbsBlockVolume, 0)
for _, blockDeviceMapping := range image.BlockDeviceMappings {
ebsVolume := &EbsBlockVolume{
DeviceName: *blockDeviceMapping.DeviceName}
if blockDeviceMapping.Ebs != nil {
ebsVolume.VolumeSize = blockDeviceMapping.Ebs.VolumeSize
ebsVolume.VolumeType = *blockDeviceMapping.Ebs.VolumeType
}
ebsVolumes = append(ebsVolumes, ebsVolume)
}
img := Image{
Id: image.ImageId,
Name: image.Name,
Description: image.Description,
State: image.State,
OwnerId: image.OwnerId,
OwnerAlias: image.ImageOwnerAlias,
CreationDate: image.CreationDate,
Architecture: image.Architecture,
Platform: image.Platform,
Hypervisor: image.Hypervisor,
VirtualizationType: image.VirtualizationType,
ImageType: image.ImageType,
KernelId: image.KernelId,
RootDeviceName: image.RootDeviceName,
RootDeviceType: image.RootDeviceType,
Public: image.Public,
EbsVolumes: ebsVolumes}
return img
}
func getRegionFromEnv() string {
region := ""
region = os.Getenv("AWS_DEFAULT_REGION") // aws cli checks this
if isRegionEmpty(region) {
region = os.Getenv("AWS_REGION") // aws sdk checks this
}
return region
}
|
package node
import(
"fmt"
"os"
"strings"
"path/filepath"
"github.com/AmosChen35/TcpServer/server/rpc"
)
type Config struct {
Name string `toml:"-"`
NodeVersion string `toml:",omitempty"`
TCPHost string `toml:",omitempty"`
TCPPort int `toml:",omitempty"`
TCPTimeouts rpc.TCPTimeouts
}
func (c *Config) name() string {
if c.Name == "" {
progname := strings.TrimSuffix(filepath.Base(os.Args[0]), ".exe")
if progname == "" {
panic("empty executable name, set Config.Name")
}
return progname
}
return c.Name
}
// HTTPEndpoint resolves an HTTP endpoint based on the configured host interface
// and port parameters.
func (c *Config) TCPEndpoint() string {
if c.TCPHost == "" {
return ""
}
return fmt.Sprintf("%s:%d", c.TCPHost, c.TCPPort)
}
|
package app
import "golang.org/x/net/context"
type App struct {
Cfg AppConfig
Logs AppLogs
Metrics AppMetrics
Errs AppErrors
Ctx context.Context
}
func NewApp() App {
cfg := LoadConfig()
logs := NewAppLogs(cfg)
metrics := NewAppMetrics(cfg)
errs := NewAppErrors(cfg)
ctx := context.Background()
return App{cfg, logs, metrics, errs, ctx}
} |
package iam
import (
"context"
"time"
"github.com/pegasus-cloud/iam_client/protos"
"google.golang.org/grpc"
)
func listUsers(c grpc.ClientConnInterface, input *protos.LimitOffset) (output *protos.ListUserOutput, err error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
return protos.NewUserCRUDControllerClient(c).ListUser(ctx, input)
}
// ListUsers ...
func ListUsers(input *protos.LimitOffset) (output *protos.ListUserOutput, err error) {
return listUsers(use().conn, input)
}
// ListUsers ...
func (cp *ConnProvider) ListUsers(input *protos.LimitOffset) (output *protos.ListUserOutput, err error) {
return listUsers(cp.init().conn, input)
}
func listUsersMap(c grpc.ClientConnInterface, input *protos.LimitOffset) (output map[string]*protos.UserInfo, count int64, err error) {
output = make(map[string]*protos.UserInfo)
users, err := listUsers(c, input)
for _, user := range users.Data {
output[user.ID] = user
}
return output, users.Count, err
}
// ListUsersMap ...
func ListUsersMap(input *protos.LimitOffset) (output map[string]*protos.UserInfo, count int64, err error) {
return listUsersMap(use().conn, input)
}
// ListUsersMap ...
func (cp *ConnProvider) ListUsersMap(input *protos.LimitOffset) (output map[string]*protos.UserInfo, count int64, err error) {
return listUsersMap(cp.init().conn, input)
}
|
package gobacktest
// Direction defines which direction a signal indicates
type Direction int
// different types of order directions
const (
// Buy
BOT Direction = iota // 0
// Sell
SLD
// Hold
HLD
// Exit
EXT
)
func (dir Direction) String() string {
switch dir {
case BOT:
return "BUY"
case SLD:
return "SELL"
case HLD:
return "HOLD"
case EXT:
return "EXIT"
default:
return "UNKNOWN"
}
}
// Signal declares a basic signal event
type Signal struct {
Event
direction Direction // long, short, exit or hold
}
// Direction returns the Direction of a Signal
func (s Signal) Direction() Direction {
return s.direction
}
// SetDirection sets the Directions field of a Signal
func (s *Signal) SetDirection(dir Direction) {
s.direction = dir
}
|
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
num, err := strconv.Atoi(os.Args[1])
if num <= 1 || err != nil {
fmt.Println("Please send a number greater than 1")
return
}
steps := checkSteps(num)
fmt.Printf("Number of steps: %v\n", steps)
}
func checkSteps(num int) int {
steps := 0
one := false
for one == false {
if num%2 == 0 {
num = num / 2
steps, one = checkIfOne(num, steps)
} else {
num = (num * 3) + 1
steps, one = checkIfOne(num, steps)
}
fmt.Println(num)
}
return steps
}
func checkIfOne(num int, steps int) (int, bool) {
steps++
if num == 1 {
return steps, true
}
return steps, false
}
|
package hooks
import (
"net"
"time"
"github.com/briandowns/spinner"
"github.com/spf13/cobra"
"github.com/tatsushid/go-fastping"
"github.com/vivek-26/ipv/reporter"
)
// PreRun performs internet and dns check
func PreRun(cmd *cobra.Command, args []string) {
internetCheck()
dnsCheck()
}
// internetCheck verifies internet connectivity
func internetCheck() {
// Create and start spinner
s := spinner.New(spinner.CharSets[14], 100*time.Millisecond)
_ = s.Color("yellow", "bold")
r := &reporter.Spinner{Spin: s}
r.Info("Checking internet connection")
p := fastping.NewPinger()
_, err := p.Network("udp")
if err != nil {
reporter.Error(err)
}
p.MaxRTT = maxRTT
ra, err := net.ResolveIPAddr("ip4:icmp", targetAddr)
if err != nil {
reporter.Error(err)
}
// Add target IP address
p.AddIPAddr(ra)
var isHostReachable bool
// Received ICMP message handler
p.OnRecv = func(addr *net.IPAddr, rtt time.Duration) {
if rtt > 0 {
isHostReachable = true
}
}
// Max RTT expiration handler
p.OnIdle = func() {
if isHostReachable {
r.Success()
} else {
r.Error()
}
}
err = p.Run() // Blocking
if err != nil {
reporter.Error("Internet connection check failed ✗")
}
}
// dnsCheck verifies the dns service
func dnsCheck() {
// Create and start spinner
s := spinner.New(spinner.CharSets[14], 100*time.Millisecond)
_ = s.Color("yellow", "bold")
r := &reporter.Spinner{Spin: s}
r.Info("Checking DNS")
ipRecords, err := net.LookupIP("google.com")
if err != nil {
reporter.Error("DNS check failed ✗")
}
// One or more IP addresses should be available
if len(ipRecords) > 0 {
r.Success()
return
}
r.Error()
}
|
/**
* (C) Copyright IBM Corp. 2021.
*
* 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 lib
import (
"errors"
"os"
"github.com/IBM/appconfiguration-go-sdk/lib/internal/messages"
"github.com/IBM/appconfiguration-go-sdk/lib/internal/models"
"github.com/IBM/appconfiguration-go-sdk/lib/internal/utils/log"
)
// AppConfiguration : Struct having init and configInstance.
type AppConfiguration struct {
isInitialized bool
isInitializedConfig bool
configurationHandlerInstance *ConfigurationHandler
}
// ContextOptions : Struct having PersistentCacheDirectory path, BootstrapFile (ConfigurationFile) path and LiveConfigUpdateEnabled flag.
type ContextOptions struct {
PersistentCacheDirectory string
BootstrapFile string
ConfigurationFile string
LiveConfigUpdateEnabled bool
}
var appConfigurationInstance *AppConfiguration
// OverrideServerHost : Override server host
var OverrideServerHost = ""
// var log = logrus.New()
// REGION_US_SOUTH : Dallas Region
const REGION_US_SOUTH = "us-south"
// REGION_EU_GB : London Region
const REGION_EU_GB = "eu-gb"
// REGION_AU_SYD : Sydney Region
const REGION_AU_SYD = "au-syd"
func init() {
log.SetLogLevel("info")
}
// GetInstance : Get App Configuration Instance
func GetInstance() *AppConfiguration {
log.Debug(messages.RetrieveingAppConfig)
if appConfigurationInstance == nil {
appConfigurationInstance = new(AppConfiguration)
}
return appConfigurationInstance
}
// Init : Init App Configuration Instance
func (ac *AppConfiguration) Init(region string, guid string, apikey string) {
if len(region) == 0 || len(guid) == 0 || len(apikey) == 0 {
if len(region) == 0 {
log.Error(messages.RegionError)
}
if len(guid) == 0 {
log.Error(messages.GUIDError)
}
if len(apikey) == 0 {
log.Error(messages.ApikeyError)
}
return
}
ac.configurationHandlerInstance = GetConfigurationHandlerInstance()
ac.configurationHandlerInstance.Init(region, guid, apikey)
ac.isInitialized = true
}
// SetContext : Set Context
func (ac *AppConfiguration) SetContext(collectionID string, environmentID string, options ...ContextOptions) {
log.Debug(messages.SettingContext)
if !ac.isInitialized {
log.Error(messages.CollectionIDError)
return
}
if len(collectionID) == 0 {
log.Error(messages.CollectionIDValueError)
return
}
if len(environmentID) == 0 {
log.Error(messages.EnvironmentIDValueError)
return
}
switch len(options) {
case 0:
ac.configurationHandlerInstance.SetContext(collectionID, environmentID, ContextOptions{
LiveConfigUpdateEnabled: true,
})
case 1:
var temp = options[0]
if len(temp.ConfigurationFile) > 0 && len(temp.BootstrapFile) == 0 {
temp.BootstrapFile = temp.ConfigurationFile
log.Info(messages.ContextOptionsParameterDeprecation)
}
if !temp.LiveConfigUpdateEnabled && len(temp.BootstrapFile) == 0 {
log.Error(messages.BootstrapFileNotFoundError)
return
}
ac.configurationHandlerInstance.SetContext(collectionID, environmentID, temp)
default:
log.Error(messages.IncorrectUsageOfContextOptions)
return
}
ac.isInitializedConfig = true
// If the cache is not having data make a blocking call and load the data in in-memory cache , else use the existing cache data and asynchronously update it.
// This scenario can happen if the user uses setcontext second time in the code , in that case cache would not be empty.
if ac.configurationHandlerInstance.cache == nil {
ac.configurationHandlerInstance.loadData()
} else {
go ac.configurationHandlerInstance.loadData()
}
}
// FetchConfigurations : Fetch Configurations
func (ac *AppConfiguration) FetchConfigurations() {
if ac.isInitialized && ac.isInitializedConfig {
go ac.configurationHandlerInstance.loadData()
} else {
log.Error(messages.CollectionInitError)
}
}
// RegisterConfigurationUpdateListener : Register Configuration Update Listener
func (ac *AppConfiguration) RegisterConfigurationUpdateListener(fhl configurationUpdateListenerFunc) {
if ac.isInitialized && ac.isInitializedConfig {
ac.configurationHandlerInstance.registerConfigurationUpdateListener(fhl)
} else {
log.Error(messages.CollectionInitError)
}
}
// GetFeature : Get Feature
func (ac *AppConfiguration) GetFeature(featureID string) (models.Feature, error) {
if ac.isInitializedConfig == true && ac.configurationHandlerInstance != nil {
return ac.configurationHandlerInstance.getFeature(featureID)
}
log.Error(messages.CollectionInitError)
return models.Feature{}, errors.New(messages.ErrorInvalidFeatureAction)
}
// GetFeatures : Get Features
func (ac *AppConfiguration) GetFeatures() (map[string]models.Feature, error) {
if ac.isInitializedConfig == true && ac.configurationHandlerInstance != nil {
return ac.configurationHandlerInstance.getFeatures()
}
log.Error(messages.CollectionInitError)
return nil, errors.New(messages.InitError)
}
// GetProperty : Get Property
func (ac *AppConfiguration) GetProperty(propertyID string) (models.Property, error) {
if ac.isInitializedConfig == true && ac.configurationHandlerInstance != nil {
return ac.configurationHandlerInstance.getProperty(propertyID)
}
log.Error(messages.CollectionInitError)
return models.Property{}, errors.New(messages.ErrorInvalidPropertyAction)
}
// GetProperties : Get Properties
func (ac *AppConfiguration) GetProperties() (map[string]models.Property, error) {
if ac.isInitializedConfig == true && ac.configurationHandlerInstance != nil {
return ac.configurationHandlerInstance.getProperties()
}
log.Error(messages.CollectionInitError)
return nil, errors.New(messages.InitError)
}
// EnableDebug : Enable Debug
func (ac *AppConfiguration) EnableDebug(enabled bool) {
if enabled {
os.Setenv("ENABLE_DEBUG", "true")
log.SetLogLevel("debug")
} else {
os.Setenv("ENABLE_DEBUG", "false")
log.SetLogLevel("info")
}
}
|
/*
Copyright 2021 The KodeRover Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package models
import (
"go.mongodb.org/mongo-driver/bson/primitive"
"github.com/koderover/zadig/lib/microservice/aslan/config"
)
type Notify struct {
ID primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"` // 主键
Type config.NotifyType `bson:"type" json:"type"` // 消息类型
Receiver string `bson:"receiver" json:"receiver"` // 发送者
Content interface{} `bson:"content" json:"content"` // 消息内容
CreateTime int64 `bson:"create_time" json:"create_time"` // 消息创建时间
IsRead bool `bson:"is_read" json:"is_read"` // 是否已读
}
type AnnouncementCtx struct {
Title string `bson:"title" json:"title"` // 公告标题
Priority int `bson:"priority" json:"priority"` // 公告级别
Content string `bson:"content" json:"content"` // 公告内容
StartTime int64 `bson:"start_time" json:"start_time"` // 公告开始时间
EndTime int64 `bson:"end_time" json:"end_time"` // 公告结束时间
}
type PipelineStatusCtx struct {
TaskID int64 `bson:"task_id" json:"task_id"`
ProductName string `bson:"product_name" json:"product_name"`
PipelineName string `bson:"pipeline_name" json:"pipeline_name"`
Type config.PipelineType `bson:"type" json:"type"`
Status config.Status `bson:"status" json:"status,omitempty"`
TeamName string `bson:"team" json:"team"`
}
type MessageCtx struct {
ReqID string `bson:"req_id" json:"req_id"`
Title string `bson:"title" json:"title"` // 消息标题
Content string `bson:"content" json:"content"` // 消息内容
}
func (Notify) TableName() string {
return "notify"
}
|
package cache
// Cache Cache
type Cache interface{}
type cache struct{}
// New New
func New() Cache {
return &cache{}
}
|
package domain
import (
value "github.com/dev-jpnobrega/api-rest/src/domain/contract/value"
)
// ICommand infc
type ICommand interface {
GetModelValidate() interface{}
Execute(value.RequestData) (value.ResponseData, *value.ResponseError)
}
|
package utiltest
import (
"github.com/dwahyudi/go-jwt-sample/internal/jwtsample/util"
"github.com/stretchr/testify/assert"
"testing"
)
func TestSimpleSignAndValidate(t *testing.T) {
var userId = 3
var tokenString = util.JwtBuildAndSignJSON(userId)
var validatedUserId, err = util.JwtValidate(tokenString)
assert.Equal(t, 3, validatedUserId)
assert.Nil(t, err)
}
func TestSimpleSignAndValidateWithStandardClaims(t *testing.T) {
var userId = 3
var tokenString = util.JwtBuildAndSignWithStandardClaims(userId)
var validatedUserId, _ = util.JwtValidate(tokenString)
assert.Equal(t, 3, validatedUserId)
}
func TestValidateWithNoneAlgorithm(t *testing.T) {
// Base64-encoded of "none" algorithm JOSE header.
var tokenString = "ewogICJhbGciOiAibm9uZSIsCiAgInR5cCI6ICJKV1QiCn0=.ewogICJ1c2VySWQiOiAzLAogICJhdWQiOiAic2FtcGxlLWF1ZGllbmNlIiwKICAiZXhwIjogMTU5Mzg2MTI4NiwKICAiaWF0IjogMTU5Mzg2MDM4NiwKICAiaXNzIjogInNhbXBsZS1pc3N1ZXIiLAogICJzdWIiOiAic2FtcGxlLXVzZXJuYW1lIgp9."
var validatedUserId, err = util.JwtValidate(tokenString)
assert.Equal(t, "Unexpected signing method: none", err.Error())
assert.Equal(t, 0, validatedUserId)
}
func TestValidateMalformedJWT(t *testing.T) {
var tokenString = "ewogICJhbGciOiAibm9uZSIsCiAgInR5cCI6ICJKV1QiCn0=."
var validatedUserId, err = util.JwtValidate(tokenString)
assert.Equal(t, "token contains an invalid number of segments", err.Error())
assert.Equal(t, 0, validatedUserId)
}
func TestValidateWithDifferentSecret(t *testing.T) {
var userId = 3
var tokenString = util.JwtBuildAndSignJSONAnotherSecret(userId)
var validatedUserId, err = util.JwtValidate(tokenString)
assert.Equal(t, 0, validatedUserId)
assert.Equal(t, "signature is invalid", err.Error())
}
|
package handler
import (
"net/http"
"time"
"github.com/labstack/echo"
)
// ---------
// handlers
// ---------
// HomeHandler ...
func HomeHandler(c echo.Context) error {
data := map[string]interface{}{
"title": "Hello",
"now": time.Now().Format(time.RFC3339),
}
return c.Render(http.StatusOK, "home", data)
}
// HelpHandler ...
func HelpHandler(c echo.Context) error {
data := map[string]interface{}{
"title": "Hello",
"now": time.Now().Format(time.RFC3339),
}
return c.Render(http.StatusOK, "help", data)
}
// AboutHandler ...
func AboutHandler(c echo.Context) error {
data := map[string]interface{}{
"title": "Hello",
"now": time.Now().Format(time.RFC3339),
}
return c.Render(http.StatusOK, "about", data)
}
// ContactHandler ...
func ContactHandler(c echo.Context) error {
data := map[string]interface{}{
"title": "Hello",
"now": time.Now().Format(time.RFC3339),
}
return c.Render(http.StatusOK, "contact", data)
}
// HowdyHandler ...
func HowdyHandler(c echo.Context) error {
data := map[string]interface{}{
"title": "Howdy",
"now": time.Now().Format(time.RFC3339),
}
return c.Render(http.StatusOK, "howdy", data)
}
// ParrotHandler ...
func ParrotHandler(c echo.Context) error {
message := c.Param("message")
return c.String(http.StatusOK, message)
}
|
package domain
type Shop struct {
Id uint64
Title string
Description string
ManagerIDs []uint64
}
type Product struct {
Id uint64
Title string
Description string
Price uint64
Availability bool
// AssemblyTime is measured in minutes
AssemblyTime uint64
PartsAmount uint64
Rating float32
Size string
Category string
ImageLinks []string
ShopId uint64
}
|
package command
import (
"fmt"
"github.com/codegangsta/cli"
"github.com/denkhaus/irspamd/engine"
)
func (c *Commander) NewLearnCommand() {
c.Register(cli.Command{
Name: "learn",
Usage: "Learn ham or spam from given IMAP box.",
Subcommands: []cli.Command{
{
Name: "ham",
Usage: "Learn ham from learnbox.",
Flags: []cli.Flag{
cli.StringFlag{"learnbox, l", "", "Name of the box to be scanned for learning. Required", ""},
},
Action: func(ctx *cli.Context) {
c.Execute(func(eng *engine.Engine) error {
return buildContextAndLearn(ctx, eng, "learn_ham")
}, ctx)
},
},
{
Name: "spam",
Usage: "Learn spam from learnbox.",
Flags: []cli.Flag{
cli.StringFlag{"learnbox, l", "", "Name of the box to be scanned for learning. Required", ""},
},
Action: func(ctx *cli.Context) {
c.Execute(func(eng *engine.Engine) error {
return buildContextAndLearn(ctx, eng, "learn_spam")
}, ctx)
},
},
},
})
}
////////////////////////////////////////////////////////////////////////////////
func buildContextAndLearn(ctx *cli.Context, e *engine.Engine, fnString string) error {
if !ctx.IsSet("learnbox") {
return fmt.Errorf("Learn::learnbox is not set. Value is mandatory.")
}
lCtx := engine.LearnContext{
LearnBox: ctx.String("learnbox"),
FnString: fnString,
ContextBase: engine.ContextBase{
Host: ctx.GlobalString("host"),
Port: ctx.GlobalInt("port"),
Username: ctx.GlobalString("user"),
Password: ctx.GlobalString("pass"),
ResetDb: ctx.GlobalBool("reset"),
},
}
return e.Learn(lCtx)
}
|
package models
import (
"fmt"
"github.com/astaxie/beego/orm"
"strconv"
)
type Admin struct {
Id int64 `json:"id"`
Username string `json:"username"`
Password string `json:"password"`
Create_time int64 `json:"create_time"`
Role string `json:"role"`
Parent string `json:"parent"`
Money float64 `json:"money"`
}
type AdminList struct {
LastPage int `json:"lastPage"`//最后一页
Page int `json:"page"`//当前页
PrePage int `json:"prePage"` //上一页
NextPage int `json:"nextPage"` //下一页
PageSize int `json:"pageSize"`//每页显示行数
TotalPage int `json:"totalPage"` //总页数
Total int `json:"total"` //总条数
Admin []Admin `json:"admin"`//管理员信息
}
//初始化模型
func init() {
// 需要在init中注册定义的model
orm.RegisterModel(new(Admin))
}
func (u *Admin) TableName() string {
return "app_admin"
}
func AdminByName( username string) (admin *Admin ) {
o := orm.NewOrm()
a := Admin{Username: username}
err := o.Read(&a,"username")
if err!=nil {
return nil
}else{
return &a
}
}
func AdminPage(page int,pageSize int,where string) (a *AdminList) {
var (
admin []Admin
info AdminList
)
o := orm.NewOrm()
//计算总数
var totalItem, totalpages int = 0, 0
o.Raw("SELECT count(id) FROM app_admin " + where).QueryRow(&totalItem) //获取总条数
if totalItem <= pageSize {
totalpages = 1
} else if totalItem > pageSize {
temp := totalItem / pageSize
if (totalItem % pageSize) != 0 {
temp = temp + 1
}
totalpages = temp
}
info.TotalPage = totalpages
info.Total = totalItem
info.LastPage = totalpages
info.Page = page
info.PageSize = pageSize
if page>1{
info.PrePage = page-1
if page < totalpages {
info.NextPage = page+1
}else{
info.NextPage = 0
}
}else{
info.PrePage = 0
if totalpages>1 {
info.NextPage = page+1
}else{
info.NextPage = 0
}
}
pageInfo :=(page-1)*pageSize
sql := "SELECT id, username, create_time, role, money FROM app_admin "+where+" ORDER BY id DESC LIMIT "+strconv.Itoa(pageSize) +" OFFSET "+strconv.Itoa(pageInfo)
fmt.Println("sql:" ,sql)
o.Raw(sql).QueryRows(&admin)
info.Admin = admin
return &info
}
func AdminInfo(id int64) (a *Admin) {
var admin Admin
o := orm.NewOrm()
o.Raw("SELECT id,username,password,role,create_time,parent,money FROM app_admin where id=" + strconv.FormatInt(id,10)).QueryRow(&admin) //获取总条数
return &admin
}
func AddAdmin(a *Admin) int64 {
o := orm.NewOrm()
id,err :=o.Insert(a)
if err != nil {
return 0
}else {
return id
}
}
func RemoveAdmin(id int64) int64 {
o := orm.NewOrm()
if num, err := o.Delete(&Admin{Id: id}); err == nil {
return num
}else {
return 0
}
}
func EditAdmin(a *Admin) int64 {
o := orm.NewOrm()
ad := Admin{Id: a.Id}
o.Read(&ad)
if &ad != nil {
if a.Password == "" {
a.Password = ad.Password
}
if a.Username == "" {
a.Username = ad.Username
}
if num, err := o.Update(a,"username","role","password"); err == nil {
return num
}else {
return 0
}
}else {
return 0
}
}
|
package storage
import "net/http"
func CreatePayment(r *http.Request)string{
return ""
}
|
package main
import (
"net/http"
"os"
"github.com/gorilla/mux"
"github.com/gorilla/handlers"
"github.com/auth0/go-jwt-middleware"
"github.com/fschr/go/auth/controllers"
"github.com/fschr/go/auth/config"
jwt "github.com/dgrijalva/jwt-go"
)
func main() {
r := mux.NewRouter()
r.Handle("/user/", jwtMiddleware.Handler(controllers.GetUser)).Methods("GET")
r.Handle("/user", controllers.CreateUser).Methods("POST")
r.Handle("/user/{id}", controllers.DeleteUser).Methods("DELETE")
r.Handle("/login", controllers.Login).Methods("POST")
mConfig := config.DevConfig
http.ListenAndServe(mConfig.Env.Port, handlers.LoggingHandler(os.Stdout, r))
}
var jwtMiddleware = jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte("MasterOfNone"), nil
},
SigningMethod: jwt.SigningMethodHS256,
}) |
package main
import (
"net/url"
"strings"
)
//Access policy that checks if an URL is within a domain.
//TODO: Does not accept subdomains
type checkSubDomainPolicy struct {
domainNames []string
}
func newCheckSubDomainPolicy() *checkSubDomainPolicy {
return &checkSubDomainPolicy{}
}
func initCheckSubDomainPolicy(p *checkSubDomainPolicy, domainNames []string) {
p.domainNames = domainNames
}
func (p *checkSubDomainPolicy) checkURL(urlString string) bool {
// TODO: avoid url.Parse.
parsedURL, _ := url.Parse(urlString)
for _, domain := range p.domainNames {
if strings.HasSuffix(parsedURL.Hostname(), domain) {
return true
}
}
return false
}
|
package constants
import (
"fmt"
)
const (
APIVersion = "v1alpha1"
)
var (
RootPath = fmt.Sprintf("/api/%s", APIVersion)
)
const (
ParameterStart = "start"
ParameterLimit = "limit"
ParameterRequestBody = "req"
ParameterXUser = "X-User"
ParameterXTenant = "X-Tenant"
DefaultParameterStart = 0
DefaultParameterLimit = 1000
)
const (
DefaultKubeHost = ""
DefaultKubeConfig = ""
DefaultListenPort = 80
DefaultDatabaseString = "/caicloud/simple-object-storage/db"
DefaultStorageString = "/caicloud/simple-object-storage/mnt/glusterfs-single"
)
|
package plugins
import (
"github.com/astaxie/beego"
_ "smartapp/plugins/test/initial"
)
func init(){
//initial.TestInit() //
beego.Debug("初始化插件信息")
} |
package main
import (
"context"
"fmt"
"github.com/zazin/test-proto-grpc/gateway"
"net/http"
)
func init() {
fmt.Println("krakend-grpc-post plugin loaded!!!")
}
var ClientRegisterer = registerer("grpc-post")
type registerer string
func (r registerer) RegisterClients(f func(
name string,
handler func(context.Context, map[string]interface{}) (http.Handler, error),
)) {
f(string(r), func(ctx context.Context, extra map[string]interface{}) (http.Handler, error) {
return gateway.New(ctx)
})
}
func main() {}
|
package entry
import (
"testing"
"shared/common"
"shared/utility/errors"
)
func TestWorldItemStrengthenEXP(t *testing.T) {
target, err := CSV.WorldItem.NewWorldItem(1, 10001)
if err != nil {
t.Errorf("%+v", errors.Format(err))
}
material1, err := CSV.WorldItem.NewWorldItem(1, 10002)
if err != nil {
t.Errorf("%+v", errors.Format(err))
}
material1.EXP.SetValue(1000)
material2, err := CSV.WorldItem.NewWorldItem(1, 10003)
if err != nil {
t.Errorf("%+v", errors.Format(err))
}
var materials = []*common.WorldItem{material1, material2}
addEXP, err := CSV.WorldItem.StrengthenEXP(target, 0, materials, 10)
if err != nil {
t.Errorf("%+v", errors.Format(err))
}
t.Logf("addEXP: %d", addEXP)
}
func TestWorldItemAdvance(t *testing.T) {
target, err := CSV.WorldItem.NewWorldItem(1, 10001)
if err != nil {
t.Errorf("%+v", errors.Format(err))
}
material1, err := CSV.WorldItem.NewWorldItem(1, 10001)
if err != nil {
t.Errorf("%+v", errors.Format(err))
}
material1.Stage.Plus(9)
var materials = []*common.WorldItem{material1}
err = CSV.WorldItem.CheckStageUpToLimit(target)
if err != nil {
t.Errorf("%+v", errors.Format(err))
}
err = CSV.WorldItem.CheckAdvanceMaterials(target, materials, 0)
if err != nil {
t.Errorf("%+v", errors.Format(err))
}
addStage, err := CSV.WorldItem.CalAddStage(target, materials, 0)
if err != nil {
t.Errorf("%+v", errors.Format(err))
}
target.Stage.Plus(addStage)
t.Logf("materialStage: %v, addStage: %d, retStage: %v", material1.Stage, addStage, target.Stage)
}
func TestWorldItemCalculateEXP(t *testing.T) {
exp := CSV.Item.CalculateTotalWorldItemEXP([]int32{1, 0, 0, 0})
t.Logf("exp: %d", exp)
}
|
package hub
import (
"context"
"fmt"
"testing"
"github.com/ipfs/go-datastore"
syncds "github.com/ipfs/go-datastore/sync"
)
func TestGetSettings(t *testing.T) {
d := syncds.MutexWrap(datastore.NewMapDatastore())
ns, err := GetSettings(context.Background(), "https://hub-dev.btfs.io",
"16Uiu2HAm9P1cur6Nhd542y7pM2EoXgVvGeNqdUCSLFAMooBeQqWy", d)
if err != nil {
t.Fatal(err)
}
fmt.Println("settings", ns)
}
|
package gore
import (
"crypto/sha1"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"regexp"
"strings"
"sync"
)
// Script represents a Lua script.
type Script struct {
body string
sha string
lock sync.RWMutex
}
// NewScript returns a new Lua script
func NewScript() *Script {
return &Script{}
}
// SetBody sets script body and its SHA value
func (s *Script) SetBody(body string) error {
s.lock.Lock()
defer s.lock.Unlock()
s.body = strings.TrimSpace(body)
return s.createSHA()
}
// ReadFromFile reads the script from a file
func (s *Script) ReadFromFile(file string) error {
s.lock.Lock()
defer s.lock.Unlock()
b, err := ioutil.ReadFile(file)
if err != nil {
return err
}
s.body = strings.TrimSpace(string(b))
return s.createSHA()
}
// Execute runs the script over a connection
func (s *Script) Execute(conn *Conn, keyCount int, keysAndArgs ...interface{}) (*Reply, error) {
s.lock.RLock()
defer s.lock.RUnlock()
if s.body == "" {
return nil, ErrEmptyScript
}
args := make([]interface{}, len(keysAndArgs)+2)
args[0] = s.sha
args[1] = keyCount
for i := range keysAndArgs {
args[i+2] = keysAndArgs[i]
}
rep, err := NewCommand("EVALSHA", args...).Run(conn)
if err != nil {
return nil, err
}
if !rep.IsError() {
return rep, nil
}
errorMessage, _ := rep.Error()
if !strings.HasPrefix(errorMessage, "NOSCRIPT") {
return rep, nil
}
args[0] = s.body
return NewCommand("EVAL", args...).Run(conn)
}
func (s *Script) createSHA() error {
h := sha1.New()
_, err := io.WriteString(h, s.body)
if err != nil {
return err
}
s.sha = fmt.Sprintf("%x", h.Sum(nil))
return nil
}
// ScriptMap is a thread-safe map from script name to its content
type ScriptMap struct {
scripts map[string]*Script
lock sync.RWMutex
}
// NewScriptMap makes a new ScriptMap
func NewScriptMap() *ScriptMap {
return &ScriptMap{
scripts: make(map[string]*Script),
}
}
// Load loads all script files from a folder with a regular expression pattern.
// Loaded script will be keyed by its file name. This method can be called many times
// to reload script files.
func (sm *ScriptMap) Load(folder, pattern string) error {
sm.lock.Lock()
sm.lock.Unlock()
r, err := regexp.Compile(pattern)
if err != nil {
return err
}
dir, err := os.Open(folder)
if err != nil {
return err
}
defer dir.Close()
infos, err := dir.Readdir(0)
if err != nil {
return err
}
for _, fi := range infos {
if fi.IsDir() || !r.MatchString(fi.Name()) {
continue
}
script := NewScript()
err := script.ReadFromFile(path.Join(folder, fi.Name()))
if err == nil {
sm.scripts[fi.Name()] = script
}
}
return nil
}
// Get a script by its name. Nil value will be returned if the name
// is not found
func (sm *ScriptMap) Get(scriptName string) *Script {
sm.lock.RLock()
defer sm.lock.RUnlock()
return sm.scripts[scriptName]
}
// Add a script to the script map
func (sm *ScriptMap) Add(scriptName string, script *Script) {
sm.lock.Lock()
defer sm.lock.Unlock()
sm.scripts[scriptName] = script
}
// Delete a script from the script map
func (sm *ScriptMap) Delete(scriptName string) {
sm.lock.Lock()
defer sm.lock.Unlock()
delete(sm.scripts, scriptName)
}
var defaultScriptMap = NewScriptMap()
// LoadScripts loads all script files from a folder with a regular expression pattern to the default
// script map.
// Loaded script will be keyed by its file name. This method can be called many times
// to reload script files.
func LoadScripts(folder, pattern string) error {
return defaultScriptMap.Load(folder, pattern)
}
// GetScript a script by its name from defaultScriptMap . Nil value will be returned if the name
// is not found
func GetScript(scriptName string) *Script {
return defaultScriptMap.Get(scriptName)
}
// AddScript a script to the default script map
func AddScript(scriptName string, script *Script) {
defaultScriptMap.Add(scriptName, script)
}
// DeleteScript a script from the default script map
func DeleteScript(scriptName string) {
defaultScriptMap.Delete(scriptName)
}
|
package main
import (
"TRT/usersNMethods"
"fmt"
)
var DB databaseAct.Database
func main() {
//fmt.Println(responses.AddUser())
//fmt.Println(responses.UpdateUser())
//fmt.Println(responses.DeleteUser())
//fmt.Println(responses.GetUser())
fmt.Println(usersNMethods.PercentOfMen())
}
|
/*
* @lc app=leetcode id=5 lang=golang
*
* [5] Longest Palindromic Substring
*
* https://leetcode.com/problems/longest-palindromic-substring/description/
*
* algorithms
* Medium (29.26%)
* Likes: 7334
* Dislikes: 554
* Total Accepted: 979.1K
* Total Submissions: 3.3M
* Testcase Example: '"babad"'
*
* Given a string s, find the longest palindromic substring in s. You may
* assume that the maximum length of s is 1000.
*
* Example 1:
*
*
* Input: "babad"
* Output: "bab"
* Note: "aba" is also a valid answer.
*
*
* Example 2:
*
*
* Input: "cbbd"
* Output: "bb"
*
*
*/
// @lc code=start
func longestPalindrome(s string) string {
return longestPalindrome2(s)
}
// dp: p(i, j) = p(i+1, j-1) ^ (Si = Sj)
func longestPalindrome2(s string) string {
length := len(s)
if length < 2 {
return s
}
maxLen, begin, dp := 1, 0, make([][]bool, length)
for i := 0; i < length; i++ {
dp[i] = make([]bool, length)
dp[i][i] = true
}
for j := 1; j < len(s); j++ {
for i := 0; i < j; i++ {
if s[i] != s[j] {
dp[i][j] = false
} else {
if j-i < 3 {
dp[i][j] = true
} else {
dp[i][j] = dp[i+1][j-1]
}
}
if dp[i][j] && j-i+1 > maxLen {
maxLen = j - i + 1
begin = i
}
}
}
return s[begin : begin+maxLen]
}
// brute force, time complexity:O(n^3)
func longestPalindrome1(s string) string {
length := len(s)
if length < 2 {
return s
}
begin, maxLength := 0, 1
for i := 0; i < length; i++ {
for j := i + 1; j < length; j++ {
if j-i+1 > maxLength && validPalindromic(s, i, j) {
maxLength = j - i + 1
begin = i
}
}
}
return s[begin : begin+maxLength]
}
func validPalindromic(s string, begin, end int) bool {
for begin < end {
if s[begin] != s[end] {
return false
}
begin++
end--
}
return true
}
// @lc code=end |
package utils
import (
"testing"
)
func TestStringMD5(t *testing.T) {
type args struct {
s string
}
tests := []struct {
name string
args args
want string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := StringMD5(tt.args.s); got != tt.want {
t.Errorf("StringMD5() = %v, want %v", got, tt.want)
}
})
}
}
func TestMD5(t *testing.T) {
type args struct {
bs []byte
}
tests := []struct {
name string
args args
want string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := MD5(tt.args.bs); got != tt.want {
t.Errorf("MD5() = %v, want %v", got, tt.want)
}
})
}
}
func TestFstring(t *testing.T) {
type args struct {
format string
v []interface{}
}
tests := []struct {
name string
args args
want string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Fstring(tt.args.format, tt.args.v...); got != tt.want {
t.Errorf("Fstring() = %v, want %v", got, tt.want)
}
})
}
}
func TestUUID(t *testing.T) {
uuid := UUID()
t.Log(uuid)
t.Fail()
SetUUIDBytesLen(12)
uuid = UUID()
t.Log(uuid)
t.Fail()
}
|
package gflObject
type RouteInfo struct {
id : int
Description : string
DistanceNm : int
MinAltitude : int
Remarks : string
}
/*
func (l *LogonC) Const(ref string) int {
if ret, ok := l.elements[ref]; ok {
return ret
} else {
return -1
}
}
*/
func NewRouteInfo(inId int) *RouteInfo {
lt := new(RouteInfo)
id := inId
return lt
}
|
package main
import (
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/gorilla/securecookie"
"github.com/gorilla/websocket"
"poker/database"
"poker/handlers"
"poker/models"
"poker/templates"
)
func main() {
// Connect to the database
dbUser := "postgres"
dbPassword := "postgres"
dbName := "pokerdb"
db, err := database.CreateDatabase(dbUser, dbPassword, dbName)
if err != nil {
log.Fatal(err)
}
// Create a template cache
templates := templates.BuildTemplateCache()
// Create a websockets upgrader
var upgrader = websocket.Upgrader{
ReadBufferSize: 2048,
WriteBufferSize: 2048,
// Allow all origins
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// Create a cookie handler
var hashKey = []byte("secret-hash-key")
var blockKey = []byte("secret-block-key")
var cookieHandler = securecookie.New(hashKey, blockKey)
// Populate our environment
env := &models.Env{
Database: db,
Port: ":8000",
Templates: templates,
SiteRoot: "/poker",
Upgrader: &upgrader,
CookieHandler: cookieHandler,
}
// Close the database after main finishes
defer env.Database.Close()
// Initialize the games found in the database (imagine these as tables)
games, err := database.GetGames(env)
if err != nil {
log.Fatal(err)
}
database.InitializeGames(env, games)
// Create a new router and initialize the handlers
router := mux.NewRouter()
router.Handle("/", handlers.HomeRedirect(env))
router.Handle(env.SiteRoot+"/", handlers.Home(env))
router.Handle(env.SiteRoot+"/login/", handlers.Login(env))
router.Handle(env.SiteRoot+"/logout/", handlers.Logout(env))
router.Handle(env.SiteRoot+"/register/", handlers.Register(env))
router.Handle(env.SiteRoot+"/user/{username:[A-Za-z0-9-_.]+}/{action:view|edit}", handlers.User(env))
router.Handle(env.SiteRoot+"/lobby/", handlers.ViewLobby(env))
router.Handle(env.SiteRoot+"/leaderboard/", handlers.Leaderboard(env))
router.Handle(env.SiteRoot+"/game/", handlers.RedirectGame(env))
router.Handle(env.SiteRoot+"/game/{gameslug:[a-z0-9-]+}/{action:play|watch}", handlers.Game(env))
router.Handle(env.SiteRoot+"/game/{gameslug:[a-z0-9-]+}/{action:sit|leave|check|bet|call|fold|discard|start}", handlers.GameAction(env))
router.Handle(env.SiteRoot+"/game/{gameslug:[a-z0-9-]+}/ws", handlers.WebsocketConnection(env))
// Start the server
log.Print("Running server at " + env.SiteRoot + " on port " + env.Port + ".")
log.Fatal(http.ListenAndServe(env.Port, router))
}
|
package burrow
import (
"encoding/binary"
"fmt"
"github.com/cbroglie/mustache"
"log"
"strconv"
"strings"
)
func RenderTemplate(template string, vars ...interface{}) (string, error) {
return mustache.Render(template, vars...)
}
func info(format string, vals ...interface{}) {
log.Printf("Burrow info: "+format, vals...)
}
func warn(err error, extra string) {
if err != nil {
log.Printf("Burrow warning: %s - %s", err, extra)
}
}
func errorlog(err ...error) {
log.Printf("Burrow error: %s", err)
}
func check(err error) {
if err != nil {
log.Fatal("Fatal Burrow error: %s", err)
}
}
func checks(errs ...error) {
for _, err := range errs {
check(err)
}
}
func sprintSizeOf(v interface{}) string {
return strconv.Itoa(binary.Size(v))
}
func sprintf(format string, vals ...interface{}) string {
return fmt.Sprintf(format, vals...)
}
func errorf(format string, vals ...interface{}) error {
return fmt.Errorf(format, vals...)
}
func itoa(v int) string {
return strconv.Itoa(v)
}
func atoi(v string) (int, error) {
return strconv.Atoi(v)
}
func atof(v string) (float64, error) {
return strconv.ParseFloat(v, 64)
}
func toLower(v string) string {
return strings.ToLower(v)
}
func assertString(v interface{}) (err error) {
if _, ok := v.(string); !ok {
err = fmt.Errorf("Cannot assert string %q", v)
}
return
}
func assertNumber(v interface{}) (err error) {
if _, ok := v.(float64); !ok {
err = fmt.Errorf("Cannot assert number %q", v)
}
return
}
func validateParams(params map[string]interface{}, keys []string) (err error) {
for _, key := range keys {
if _, ok := params[key]; !ok {
err = fmt.Errorf("Missing param: %q", key)
}
}
return
}
|
// determines the century of a given year
// 2000 is the 20th century, 1999 is the 20th century, and 2001
func getCenturyFromYear(year int) int {
if (year % 100 > 0) {
return year / 100 + 1
} else {
return year / 100
}
}
|
package build
import (
"bytes"
"context"
"errors"
"fmt"
"github.com/onsi/ginkgo/v2"
"io"
"os"
"os/exec"
"strings"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/loft-sh/devspace/cmd"
"github.com/loft-sh/devspace/cmd/flags"
"github.com/loft-sh/devspace/e2e/framework"
"github.com/loft-sh/devspace/pkg/devspace/docker"
"github.com/loft-sh/devspace/pkg/util/factory"
"github.com/loft-sh/devspace/pkg/util/log"
)
var _ = DevSpaceDescribe("build", func() {
initialDir, err := os.Getwd()
if err != nil {
panic(err)
}
// create a new factory
var f factory.Factory
// create logger
var log log.Logger
// create context
ctx := context.Background()
ginkgo.BeforeEach(func() {
f = framework.NewDefaultFactory()
})
// Test cases:
ginkgo.It("should build dockerfile with docker", func() {
tempDir, err := framework.CopyToTempDir("tests/build/testdata/docker")
framework.ExpectNoError(err)
defer framework.CleanupTempDir(initialDir, tempDir)
// create build command
buildCmd := &cmd.RunPipelineCmd{
GlobalFlags: &flags.GlobalFlags{
NoWarn: true,
},
SkipPush: true,
Pipeline: "build",
}
err = buildCmd.RunDefault(f)
framework.ExpectNoError(err)
// create devspace docker client to access docker APIs
devspaceDockerClient, err := docker.NewClient(context.TODO(), log)
framework.ExpectNoError(err)
dockerClient := devspaceDockerClient.DockerAPIClient()
imageList, err := dockerClient.ImageList(ctx, types.ImageListOptions{})
framework.ExpectNoError(err)
found := false
Outer:
for _, image := range imageList {
for _, tag := range image.RepoTags {
if tag == "my-docker-username/helloworld:latest" {
found = true
break Outer
}
}
}
framework.ExpectEqual(found, true, "image not found in cache")
})
ginkgo.It("should build dockerfile with docker and skip-dependency", func() {
tempDir, err := framework.CopyToTempDir("tests/build/testdata/docker-skip-dependency")
framework.ExpectNoError(err)
defer framework.CleanupTempDir(initialDir, tempDir)
// create build command
buildCmd := &cmd.RunPipelineCmd{
GlobalFlags: &flags.GlobalFlags{
NoWarn: true,
},
SkipPush: true,
SkipDependency: []string{
"fake-dep",
},
Pipeline: "build",
}
err = buildCmd.RunDefault(f)
framework.ExpectNoError(err)
// create devspace docker client to access docker APIs
devspaceDockerClient, err := docker.NewClient(context.TODO(), log)
framework.ExpectNoError(err)
dockerClient := devspaceDockerClient.DockerAPIClient()
imageList, err := dockerClient.ImageList(ctx, types.ImageListOptions{})
framework.ExpectNoError(err)
found := false
Outer:
for _, image := range imageList {
for _, tag := range image.RepoTags {
if tag == "my-docker-username/helloworld:latest" {
found = true
break Outer
}
}
}
framework.ExpectEqual(found, true, "image not found in cache")
})
ginkgo.It("should build dockerfile with docker and load in kind cluster", func() {
tempDir, err := framework.CopyToTempDir("tests/build/testdata/docker")
framework.ExpectNoError(err)
defer framework.CleanupTempDir(initialDir, tempDir)
// create build command
buildCmd := &cmd.RunPipelineCmd{
GlobalFlags: &flags.GlobalFlags{
NoWarn: true,
},
SkipPush: true,
Pipeline: "build",
}
err = buildCmd.RunDefault(f)
framework.ExpectNoError(err)
// create devspace docker client to access docker APIs
devspaceDockerClient, err := docker.NewClient(context.TODO(), log)
framework.ExpectNoError(err)
dockerClient := devspaceDockerClient.DockerAPIClient()
imageList, err := dockerClient.ImageList(ctx, types.ImageListOptions{})
framework.ExpectNoError(err)
found := false
Outer:
for _, image := range imageList {
for _, tag := range image.RepoTags {
if tag == "my-docker-username/helloworld:latest" {
found = true
break Outer
}
}
}
framework.ExpectEqual(found, true, "image not found in cache")
var stdout, stderr bytes.Buffer
cmd := exec.Command("kind", "load", "docker-image", "my-docker-username/helloworld:latest")
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()
framework.ExpectNoError(err)
err = stderrContains(stderr.String(), "found to be already present")
framework.ExpectNoError(err)
})
ginkgo.It("should build dockerfile with docker even when KUBECONFIG is invalid", func() {
tempDir, err := framework.CopyToTempDir("tests/build/testdata/docker")
framework.ExpectNoError(err)
defer framework.CleanupTempDir(initialDir, tempDir)
_ = os.Setenv("KUBECONFIG", "i-am-invalid-config")
// create build command
buildCmd := &cmd.RunPipelineCmd{
GlobalFlags: &flags.GlobalFlags{
NoWarn: true,
},
SkipPush: true,
Pipeline: "build",
}
err = buildCmd.RunDefault(f)
framework.ExpectNoError(err)
// create devspace docker client to access docker APIs
devspaceDockerClient, err := docker.NewClient(context.TODO(), log)
framework.ExpectNoError(err)
dockerClient := devspaceDockerClient.DockerAPIClient()
imageList, err := dockerClient.ImageList(ctx, types.ImageListOptions{})
framework.ExpectNoError(err)
found := false
Outer:
for _, image := range imageList {
for _, tag := range image.RepoTags {
if tag == "my-docker-username/helloworld:latest" {
found = true
break Outer
}
}
}
framework.ExpectEqual(found, true, "image not found in cache")
_ = os.Unsetenv("KUBECONFIG")
})
ginkgo.It("should not build dockerfile with kaniko when KUBECONFIG is invalid", func() {
tempDir, err := framework.CopyToTempDir("tests/build/testdata/kaniko")
framework.ExpectNoError(err)
defer framework.CleanupTempDir(initialDir, tempDir)
_ = os.Setenv("KUBECONFIG", "i-am-invalid-config")
// create build command
buildCmd := &cmd.RunPipelineCmd{
GlobalFlags: &flags.GlobalFlags{
NoWarn: true,
},
SkipPush: true,
Pipeline: "build",
}
err = buildCmd.RunDefault(f)
framework.ExpectError(err)
_ = os.Unsetenv("KUBECONFIG")
})
ginkgo.It("should build dockerfile with buildkit and load in kind cluster", func() {
tempDir, err := framework.CopyToTempDir("tests/build/testdata/buildkit")
framework.ExpectNoError(err)
defer framework.CleanupTempDir(initialDir, tempDir)
// create build command
buildCmd := &cmd.RunPipelineCmd{
GlobalFlags: &flags.GlobalFlags{
NoWarn: true,
},
SkipPush: true,
Pipeline: "build",
}
err = buildCmd.RunDefault(f)
framework.ExpectNoError(err)
// create devspace docker client to access docker APIs
devspaceDockerClient, err := docker.NewClient(context.TODO(), log)
framework.ExpectNoError(err)
dockerClient := devspaceDockerClient.DockerAPIClient()
imageList, err := dockerClient.ImageList(ctx, types.ImageListOptions{})
framework.ExpectNoError(err)
for _, image := range imageList {
if len(image.RepoTags) > 0 && image.RepoTags[0] == "my-docker-username/helloworld-buildkit:latest" {
err = nil
break
} else {
err = errors.New("image not found")
}
}
framework.ExpectNoError(err)
var stdout, stderr bytes.Buffer
cmd := exec.Command("kind", "load", "docker-image", "my-docker-username/helloworld-buildkit:latest")
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()
framework.ExpectNoError(err)
err = stderrContains(stderr.String(), "found to be already present")
framework.ExpectNoError(err)
})
ginkgo.It("should build dockerfile with buildkit", func() {
tempDir, err := framework.CopyToTempDir("tests/build/testdata/buildkit")
framework.ExpectNoError(err)
defer framework.CleanupTempDir(initialDir, tempDir)
// create build command
buildCmd := &cmd.RunPipelineCmd{
GlobalFlags: &flags.GlobalFlags{
NoWarn: true,
},
SkipPush: true,
Pipeline: "build",
}
err = buildCmd.RunDefault(f)
framework.ExpectNoError(err)
// create devspace docker client to access docker APIs
devspaceDockerClient, err := docker.NewClient(context.TODO(), log)
framework.ExpectNoError(err)
dockerClient := devspaceDockerClient.DockerAPIClient()
imageList, err := dockerClient.ImageList(ctx, types.ImageListOptions{})
framework.ExpectNoError(err)
for _, image := range imageList {
if len(image.RepoTags) > 0 && image.RepoTags[0] == "my-docker-username/helloworld-buildkit:latest" {
err = nil
break
} else {
err = errors.New("image not found")
}
}
framework.ExpectNoError(err)
})
ginkgo.It("should build dockerfile with kaniko", func() {
tempDir, err := framework.CopyToTempDir("tests/build/testdata/kaniko")
framework.ExpectNoError(err)
defer framework.CleanupTempDir(initialDir, tempDir)
// create build command
buildCmd := &cmd.RunPipelineCmd{
GlobalFlags: &flags.GlobalFlags{
NoWarn: true,
},
SkipPush: true,
Pipeline: "build",
}
err = buildCmd.RunDefault(f)
framework.ExpectNoError(err)
})
ginkgo.It("should build dockerfile with custom builder", func() {
tempDir, err := framework.CopyToTempDir("tests/build/testdata/custom_build")
framework.ExpectNoError(err)
defer framework.CleanupTempDir(initialDir, tempDir)
// create build command
buildCmd := &cmd.RunPipelineCmd{
GlobalFlags: &flags.GlobalFlags{
NoWarn: true,
},
SkipPush: true,
Pipeline: "build",
}
err = buildCmd.RunDefault(f)
framework.ExpectNoError(err)
// create devspace docker client to access docker APIs
devspaceDockerClient, err := docker.NewClient(context.TODO(), log)
framework.ExpectNoError(err)
dockerClient := devspaceDockerClient.DockerAPIClient()
imageList, err := dockerClient.ImageList(ctx, types.ImageListOptions{})
framework.ExpectNoError(err)
for _, image := range imageList {
if len(image.RepoTags) > 0 && image.RepoTags[0] == "my-docker-username/helloworld-custom-build:latest" {
err = nil
break
} else {
err = errors.New("image not found")
}
}
framework.ExpectNoError(err)
})
ginkgo.It("should ignore files from Dockerfile.dockerignore only", func() {
tempDir, err := framework.CopyToTempDir("tests/build/testdata/dockerignore")
framework.ExpectNoError(err)
defer framework.CleanupTempDir(initialDir, tempDir)
// create build command
buildCmd := &cmd.RunPipelineCmd{
GlobalFlags: &flags.GlobalFlags{
NoWarn: true,
},
SkipPush: true,
Pipeline: "build",
}
err = buildCmd.RunDefault(f)
framework.ExpectNoError(err)
// create devspace docker client to access docker APIs
devspaceDockerClient, err := docker.NewClient(context.TODO(), log)
framework.ExpectNoError(err)
dockerClient := devspaceDockerClient.DockerAPIClient()
imageList, err := dockerClient.ImageList(ctx, types.ImageListOptions{})
framework.ExpectNoError(err)
imageName := "my-docker-username/helloworld-dockerignore:latest"
for _, image := range imageList {
if image.RepoTags[0] == imageName {
err = nil
break
} else {
err = errors.New("image not found")
}
}
framework.ExpectNoError(err)
resp, err := dockerClient.ContainerCreate(ctx, &container.Config{
Image: imageName,
Cmd: []string{"/bin/ls", "./build"},
Tty: false,
}, nil, nil, nil, "")
framework.ExpectNoError(err)
err = dockerClient.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{})
framework.ExpectNoError(err)
statusCh, errCh := dockerClient.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning)
select {
case err := <-errCh:
framework.ExpectNoError(err)
case <-statusCh:
}
out, err := dockerClient.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true})
framework.ExpectNoError(err)
stdout := &bytes.Buffer{}
_, err = io.Copy(stdout, out)
framework.ExpectNoError(err)
err = stdoutContains(stdout.String(), "bar.txt")
framework.ExpectError(err)
err = stdoutContains(stdout.String(), "foo.txt")
framework.ExpectError(err)
})
ginkgo.It("should ignore files from Dockerfile.dockerignore relative path", func() {
tempDir, err := framework.CopyToTempDir("tests/build/testdata/dockerignore_rel_path")
framework.ExpectNoError(err)
defer framework.CleanupTempDir(initialDir, tempDir)
// create build command
buildCmd := &cmd.RunPipelineCmd{
GlobalFlags: &flags.GlobalFlags{
NoWarn: true,
},
SkipPush: true,
Pipeline: "build",
}
err = buildCmd.RunDefault(f)
framework.ExpectNoError(err)
// create devspace docker client to access docker APIs
devspaceDockerClient, err := docker.NewClient(context.TODO(), log)
framework.ExpectNoError(err)
dockerClient := devspaceDockerClient.DockerAPIClient()
imageList, err := dockerClient.ImageList(ctx, types.ImageListOptions{})
framework.ExpectNoError(err)
imageName := "my-docker-username/helloworld-dockerignore-rel-path:latest"
for _, image := range imageList {
if image.RepoTags[0] == imageName {
err = nil
break
} else {
err = errors.New("image not found")
}
}
framework.ExpectNoError(err)
resp, err := dockerClient.ContainerCreate(ctx, &container.Config{
Image: imageName,
Cmd: []string{"/bin/ls", "./build"},
Tty: false,
}, nil, nil, nil, "")
framework.ExpectNoError(err)
err = dockerClient.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{})
framework.ExpectNoError(err)
statusCh, errCh := dockerClient.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning)
select {
case err := <-errCh:
framework.ExpectNoError(err)
case <-statusCh:
}
out, err := dockerClient.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true})
framework.ExpectNoError(err)
stdout := &bytes.Buffer{}
_, err = io.Copy(stdout, out)
framework.ExpectNoError(err)
err = stdoutContains(stdout.String(), "bar.txt")
framework.ExpectError(err)
err = stdoutContains(stdout.String(), "foo.txt")
framework.ExpectError(err)
})
ginkgo.It("should ignore files from outside of context Dockerfile.dockerignore", func() {
tempDir, err := framework.CopyToTempDir("tests/build/testdata/dockerignore_context")
framework.ExpectNoError(err)
defer framework.CleanupTempDir(initialDir, tempDir)
// create build command
buildCmd := &cmd.RunPipelineCmd{
GlobalFlags: &flags.GlobalFlags{
NoWarn: true,
},
SkipPush: true,
Pipeline: "build",
}
err = buildCmd.RunDefault(f)
framework.ExpectNoError(err)
// create devspace docker client to access docker APIs
devspaceDockerClient, err := docker.NewClient(context.TODO(), log)
framework.ExpectNoError(err)
dockerClient := devspaceDockerClient.DockerAPIClient()
imageList, err := dockerClient.ImageList(ctx, types.ImageListOptions{})
framework.ExpectNoError(err)
imageName := "my-docker-username/helloworld-dockerignore-context:latest"
for _, image := range imageList {
if image.RepoTags[0] == imageName {
err = nil
break
} else {
err = errors.New("image not found")
}
}
framework.ExpectNoError(err)
resp, err := dockerClient.ContainerCreate(ctx, &container.Config{
Image: imageName,
Cmd: []string{"/bin/ls", "./build"},
Tty: false,
}, nil, nil, nil, "")
framework.ExpectNoError(err)
err = dockerClient.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{})
framework.ExpectNoError(err)
statusCh, errCh := dockerClient.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning)
select {
case err := <-errCh:
framework.ExpectNoError(err)
case <-statusCh:
}
out, err := dockerClient.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true})
framework.ExpectNoError(err)
stdout := &bytes.Buffer{}
_, err = io.Copy(stdout, out)
framework.ExpectNoError(err)
err = stdoutContains(stdout.String(), "bar.txt")
framework.ExpectNoError(err)
err = stdoutContains(stdout.String(), "foo.txt")
framework.ExpectError(err)
})
})
func stdoutContains(stdout, content string) error {
if strings.Contains(stdout, content) {
return nil
}
return fmt.Errorf("%s found in output", content)
}
func stderrContains(stderr, content string) error {
if strings.Contains(stderr, content) {
return nil
}
return fmt.Errorf("%s found in output", content)
}
|
// date: 2019-03-07
package common
import "sync"
//quote.kline.1m.btc_usdt
//quote.tick.btc_usdt
//quote.depth.btc_usdt
type SocketMap struct {
sync.Mutex
ConnMap map[string]map[string][]string
//缺少连接属性
}
var (
Smap = &SocketMap{sync.Mutex{}, make(map[string]map[string][]string)}
KlineChan = "quote.kline.%s.%s"
TickChan = "quote.tick.%s"
DepthChan = "quote.depth.%s"
)
const (
PING = "ping"
PONG = "pong"
SUB = "sub"
UN_SUB = "un_sub"
TICK = "tick"
DEPTH = "depth"
KLINE = "kline"
SUCCESS = 0
FAIL = 1
)
|
package ldap
// Heavily inspired by https://github.com/hashicorp/vault/blob/bc33dbd/helper/ldaputil/client.go
/// or simply copying code from there.
import (
"bytes"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"math"
"net"
"net/http"
"net/url"
"strings"
"sync"
"text/template"
"time"
"github.com/go-ldap/ldap"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/vault/helper/ldaputil"
"github.com/mlowicki/rhythm/api/auth"
"github.com/mlowicki/rhythm/conf"
tlsutils "github.com/mlowicki/rhythm/tls"
log "github.com/sirupsen/logrus"
)
// Authorizer provides access control level backed by LDAP server.
type Authorizer struct {
addrs []string
userDN string
userAttr string
caCert *x509.CertPool
userACL map[string]map[string]string
groupACL map[string]map[string]string
bindDN string
bindPassword string
groupFilter string
groupDN string
groupAttr string
caseSensitiveNames bool
}
const (
readonly = "readonly"
readwrite = "readwrite"
)
var timeoutMut sync.Mutex
// SetTimeout changes timeout used by `ldap` package by setting package-level variable.
func SetTimeout(timeout time.Duration) {
timeoutMut.Lock()
ldap.DefaultTimeout = timeout
timeoutMut.Unlock()
}
func (a *Authorizer) dial() (*ldap.Conn, error) {
var errs *multierror.Error
var conn *ldap.Conn
for _, addr := range a.addrs {
u, err := url.Parse(addr)
if err != nil {
errs = multierror.Append(errs, fmt.Errorf("Error parsing URL: %s", err))
continue
}
host, port, err := net.SplitHostPort(u.Host)
if err != nil {
host = u.Host
}
switch u.Scheme {
case "ldap":
if port == "" {
port = "389"
}
conn, err = ldap.Dial("tcp", net.JoinHostPort(host, port))
if err != nil {
break
}
case "ldaps":
tlsConfig := &tls.Config{
ServerName: host,
}
if a.caCert != nil {
tlsConfig.RootCAs = a.caCert
}
if port == "" {
port = "636"
}
conn, err = ldap.DialTLS("tcp", net.JoinHostPort(host, port), tlsConfig)
if err != nil {
break
}
default:
errs = multierror.Append(errs, fmt.Errorf("Invalid LDAP scheme: %s", u.Scheme))
continue
}
if err == nil {
if errs != nil {
log.Debug(errs.Error())
}
errs = nil
break
}
errs = multierror.Append(errs, err)
}
return conn, errs.ErrorOrNil()
}
func (a *Authorizer) getUserBindDN(conn *ldap.Conn, username string) (string, error) {
bindDN := ""
if a.bindDN != "" && a.bindPassword != "" {
err := conn.Bind(a.bindDN, a.bindPassword)
if err != nil {
return bindDN, fmt.Errorf("LDAP service bind failed: %s", err)
}
filter := fmt.Sprintf("(%s=%s)", a.userAttr, ldap.EscapeFilter(username))
res, err := conn.Search(&ldap.SearchRequest{
BaseDN: a.userDN,
Scope: ldap.ScopeWholeSubtree,
Filter: filter,
SizeLimit: math.MaxInt32,
})
if err != nil {
return bindDN, fmt.Errorf("LDAP search for binddn failed: %s", err)
}
if len(res.Entries) != 1 {
return bindDN, errors.New("LDAP search for binddn not found or not unique")
}
bindDN = res.Entries[0].DN
} else {
bindDN = fmt.Sprintf("%s=%s,%s", a.userAttr, ldaputil.EscapeLDAPValue(username), a.userDN)
}
return bindDN, nil
}
func (a *Authorizer) performLDAPGroupsSearch(conn *ldap.Conn, userDN, username string) ([]*ldap.Entry, error) {
t, err := template.New("queryTemplate").Parse(a.groupFilter)
if err != nil {
return nil, fmt.Errorf("Failed compilation of LDAP query template: %s", err)
}
context := struct {
UserDN string
Username string
}{
ldap.EscapeFilter(userDN),
ldap.EscapeFilter(username),
}
var renderedQuery bytes.Buffer
t.Execute(&renderedQuery, context)
log.Debugf("Groups search query: %s", renderedQuery.String())
res, err := conn.Search(&ldap.SearchRequest{
BaseDN: a.groupDN,
Scope: ldap.ScopeWholeSubtree,
Filter: renderedQuery.String(),
Attributes: []string{
a.groupAttr,
},
SizeLimit: math.MaxInt32,
})
if err != nil {
return nil, fmt.Errorf("LDAP search failed: %s", err)
}
return res.Entries, nil
}
func (a *Authorizer) getLDAPGroups(conn *ldap.Conn, userDN, username string) ([]string, error) {
entries, err := a.performLDAPGroupsSearch(conn, userDN, username)
groupsMap := make(map[string]bool)
for _, e := range entries {
dn, err := ldap.ParseDN(e.DN)
if err != nil || len(dn.RDNs) == 0 {
continue
}
values := e.GetAttributeValues(a.groupAttr)
if len(values) > 0 {
for _, val := range values {
groupCN := getCN(val)
groupsMap[groupCN] = true
}
} else {
// If groupattr didn't resolve, use self (enumerating group objects)
groupCN := getCN(e.DN)
groupsMap[groupCN] = true
}
}
groups := make([]string, 0, len(groupsMap))
for key := range groupsMap {
groups = append(groups, key)
}
return groups, err
}
/*
* Parses a distinguished name and returns the CN portion.
* Given a non-conforming string (such as an already-extracted CN), it will be returned as-is.
*/
func getCN(dn string) string {
parsedDN, err := ldap.ParseDN(dn)
if err != nil || len(parsedDN.RDNs) == 0 {
// It was already a CN, return as-is
return dn
}
for _, rdn := range parsedDN.RDNs {
for _, rdnAttr := range rdn.Attributes {
if rdnAttr.Type == "CN" {
return rdnAttr.Value
}
}
}
// Default, return self
return dn
}
// GetProjectAccessLevel returns type of access to project for request sent by client.
func (a *Authorizer) GetProjectAccessLevel(r *http.Request, group string, project string) (auth.AccessLevel, error) {
username, password, ok := r.BasicAuth()
if !ok {
return auth.NoAccess, errors.New("Cannot parse Basic auth credentials")
}
conn, err := a.dial()
if err != nil {
return auth.NoAccess, err
}
defer conn.Close()
bindDN, err := a.getUserBindDN(conn, username)
log.Debugf("bindDN: %s", bindDN)
if err != nil {
return auth.NoAccess, err
}
if len(password) > 0 {
err = conn.Bind(bindDN, password)
} else {
err = conn.UnauthenticatedBind(bindDN)
}
if err != nil {
return auth.NoAccess, err
}
userLevel := a.getLevelFromACL(&a.userACL, username, group, project)
if userLevel != auth.NoAccess {
return userLevel, nil
}
ldapGroups, err := a.getLDAPGroups(conn, bindDN, username)
log.Debugf("Found groups: %v", ldapGroups)
if err != nil {
return auth.NoAccess, err
}
readOnlyAccess := false
for _, ldapGroup := range ldapGroups {
groupLevel := a.getLevelFromACL(&a.groupACL, ldapGroup, group, project)
if groupLevel == auth.ReadWrite {
return auth.ReadWrite, nil
}
if groupLevel == auth.ReadOnly {
readOnlyAccess = true
}
}
if readOnlyAccess {
return auth.ReadOnly, nil
}
return auth.NoAccess, nil
}
func (a *Authorizer) getLevelFromACL(acl *map[string]map[string]string, name, group, project string) auth.AccessLevel {
if !a.caseSensitiveNames {
name = strings.ToLower(name)
}
rules, ok := (*acl)[name]
if !ok {
return auth.NoAccess
}
keys := [...]string{
fmt.Sprintf("%s/%s", group, project),
group,
"*",
}
for _, key := range keys {
level, ok := rules[key]
if !ok {
continue
}
switch level {
case readonly:
return auth.ReadOnly
case readwrite:
return auth.ReadWrite
}
}
return auth.NoAccess
}
func validateACL(acl *map[string]map[string]string) error {
for outerKey, rules := range *acl {
for innerKey, level := range rules {
if level != readonly && level != readwrite {
return fmt.Errorf("invalid access level [%s][%s]: %s", outerKey, innerKey, level)
}
}
}
return nil
}
// New returns fresh instance of LDAP authorizer.
func New(c *conf.APIAuthLDAP) (*Authorizer, error) {
if len(c.Addrs) == 0 {
return nil, errors.New("addrs is empty")
}
if c.UserDN == "" {
return nil, errors.New("userdn is empty")
}
if c.UserAttr == "" {
return nil, errors.New("userattr is empty")
}
if c.GroupDN == "" {
return nil, errors.New("groupdn is empty")
}
if c.GroupAttr == "" {
return nil, errors.New("groupattr is empty")
}
if c.GroupFilter == "" {
return nil, errors.New("groupfilter is empty")
}
err := validateACL(&c.UserACL)
if err != nil {
return nil, fmt.Errorf("Invalid useracl: %s", err)
}
err = validateACL(&c.GroupACL)
if err != nil {
return nil, fmt.Errorf("Invalid groupacl: %s", err)
}
a := Authorizer{
addrs: c.Addrs,
userDN: c.UserDN,
userAttr: c.UserAttr,
userACL: c.UserACL,
groupACL: c.GroupACL,
bindDN: c.BindDN,
bindPassword: c.BindPassword,
groupFilter: c.GroupFilter,
groupDN: c.GroupDN,
groupAttr: c.GroupAttr,
caseSensitiveNames: c.CaseSensitiveNames,
}
if c.CACert != "" {
pool, err := tlsutils.BuildCertPool(c.CACert)
if err != nil {
return nil, err
}
a.caCert = pool
}
return &a, nil
}
|
// Copyright 2019 Yunion
//
// 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 templates
import "yunion.io/x/onecloud/pkg/apis/monitor"
type TemplateConfig struct {
monitor.NotificationTemplateConfig
}
func NewTemplateConfig(c monitor.NotificationTemplateConfig) *TemplateConfig {
return &TemplateConfig{
NotificationTemplateConfig: c,
}
}
const DefaultMarkdownTemplate = `
## {{.Title}}
- 时间: {{.StartTime}}
- 级别: {{.Level}}
{{ range .Matches}}
- 指标: {{.Metric}}
- 触发值: {{.ValueStr}}
### 触发条件:
- {{ $.Description}}
### 标签
> 名称: {{ GetValFromMap .Tags "name" }}
> ip: {{ GetValFromMap .Tags "ip" }}
> 平台: {{ GetValFromMap .Tags "brand" }}
------
{{- end}}
`
func (c TemplateConfig) GenerateMarkdown() (string, error) {
return CompileTEmplateFromMapText(DefaultMarkdownTemplate, c)
}
func (c TemplateConfig) GenerateEmailMarkdown() (string, error) {
return CompileTemplateFromMapHtml(EmailMarkdownTemplate, c)
}
const EmailMarkdownTemplate = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{{.Title}}</title>
</head>
<style>
.title {
height: 40px;
line-height: 40px;
width: 960px;
background-color: #4da1ff;
color: #fff;
font-size: 16px;
text-align: center;
margin: 0 auto;
}
.table {
width: 960px;
margin: 0 auto;
padding: 10px 30px 0px 30px;
font-family:'微软雅黑',Helvetica,Arial,sans-serif;
font-size:14px;
background-color: #fbfbfb;
}
.tr-title {
height: 10px;
border-left: 5px solid #4da1ff;
margin-left: 10px;
padding: 3px 8px;
font-weight: bold;
}
.td {
width: 80px;
padding-left: 20px;
height: 35px;
font-weight: 400;
}
.link {
text-decoration: none;
color: #3591FF;
}
.thead-tr td {
border-left: 1px solid #d7d7d7;
border-top: 1px solid #d7d7d7;
height: 32px;
font-size: 14px;
background-color: #d7d7d7;
text-align: center;
}
.tbody-tr td {
border-left: 1px solid #d7d7d7;
border-top: 1px solid #d7d7d7;
height: 32px;
font-size: 14px;
font-weight: 400;
text-align: center;
}
.pb-3 {
padding-bottom: 30px;
}
.resouce-table {
width: 98%;
color: #717171;
border-right: 1px solid #d7d7d7;
border-bottom: 1px solid #d7d7d7;
}
</style>
<body>
<h3 class="title">报警提醒</h3>
<table border="0" cellspacing="0" cellpadding="0" class="table">
<tr><td colspan="4" class="tr-title">报警信息</td></tr>
<tr><td style="height: 10px;"></td></tr>
<tr>
<td class="td">报警策略:</td>
<td>{{.Name}}</td>
</tr>
<tr>
<td class="td">报警级别:</td>
<td>{{.Level}}</td>
</tr>
<tr>
<td class="td">报警时间:</td>
<td>{{.StartTime}}</td>
</tr>
<tr>
<td class="td">策略详情:</td>
<td>{{.Description}}</td>
</tr>
</table>
<table class="table" style="padding-top: 6px; padding-bottom: 10px;">
<tr>
<td style="padding-left: 20px; font-size: 14px;">若要查看详情信息,<a class="link" target="_blank" href="{{.WebUrl}}/commonalerts
">请登录平台进行查看</a></td>
</tr>
</table>
<table border="0" cellspacing="0" cellpadding="0" class="table pb-3">
<tr><td colspan="4" class="tr-title">报警资源</td></tr>
<tr><td style="height: 10px;"></td></tr>
<tr>
<td colspan="4" style="padding: 10px 0 0 20px;">
<table cellspacing="0" cellpadding="0" class="resouce-table">
<thead>
<tr class="thead-tr">
<td>序号</td>
<td>名称</td>
<td>IP</td>
<td>平台</td>
<td>触发值</td>
</tr>
</thead>
<tbody>
{{- range $i, $Matche := .Matches}}
<tr class="tbody-tr">
<td>{{ Inc $i}}</td>
<td>
{{- GetValFromMap .Tags "name"}}
</td>
<td>
{{ GetValFromMap .Tags "ip" }}
</td>
<td>
{{ GetValFromMap .Tags "brand" }}
</td>
<td>{{$Matche.ValueStr}}</td>
</tr>
{{end}}
</tbody>
</table>
</td>
</tr>
<tr><td style="height: 10px;"></td></tr>
</table>
<p style="width: 960px; height: 40px; line-height: 40px; margin: 0 auto; background-color: #4da1ff; color: #fff; font-size: 12px; text-align: center; ">本邮件由系统自动发送,请勿直接回复!</p>
</body>
</html>
`
|
package openstack
import "fmt"
type Image struct {
name string
id string
client imageServiceClient
}
func NewImage(name string, id string, client imageServiceClient) Image {
return Image{
name: fmt.Sprintf("%s %s", name, id),
id: id,
client: client,
}
}
func (i Image) Delete() error {
return i.client.Delete(i.id)
}
func (i Image) Name() string {
return i.name
}
func (Image) Type() string {
return "Image"
}
|
package main
import "fmt"
type Bread struct {
val string
}
type StrawberryJam struct {
opend bool
}
type SpoonOfStrawberry struct {
}
type sandwich struct {
val string
}
func GetBreads(num int) []*Bread {
breads := make([]*Bread, num)
for i := 0; i < num; i++ {
breads[i] = &Bread{val: "bread(빵)"}
}
return breads
}
func openStrawberryJam(jam *StrawberryJam) {
jam.opend = true
}
func GetOneSpoon(_ *StrawberryJam) *SpoonOfStrawberry {
return &SpoonOfStrawberry{}
}
func PutJamOnBread(bread *Bread, jam *SpoonOfStrawberry) {
bread.val += "+ Strawberry Jam(쨈)"
}
func MakeSandwich(bread []*Bread) *sandwich {
sandwich := &sandwich{}
for i := 0; i < len(bread); i++ {
sandwich.val += bread[i].val + "+"
}
return sandwich
}
func main() {
breads := GetBreads(2)
jam := &StrawberryJam{} //잼을열고
openStrawberryJam(jam) //딸기잼 뚜껑열기
spoon := GetOneSpoon(jam)
PutJamOnBread(breads[0], spoon)
//PutJamOnBread(breads[0], spoon)
//PutJamOnBread(breads[1], spoon) //잼을 한번만 더 바를때
// for i := 0; i < len(breads); i++ {
// PutJamOnBread(breads[i], spoon)
// }
sandwich := MakeSandwich(breads)
//jam더 올리기
fmt.Println(sandwich.val)
}
|
// status.go defines a Status struct for each node in the cluster, providing
// four attributes (CRole, DBRole, State, UpdateAt) as a way of determining each
// nodes role in the cluster, current state, and the role of the pgqsl running
// inside each (non-monitor) node.
//
// status provides methods for updating the DBRole and State as the clusters
// environment changes due to outages, and also provides methods of retrieving
// information about each node in the cluster or about the cluster as a whole.
package main
import (
"errors"
"fmt"
"github.com/pagodabox/golang-scribble"
"net"
"net/rpc"
"os"
"time"
)
// Status represents the Status of a node in the cluser
type Status struct {
CRole string // the nodes 'role' in the cluster (primary, secondary, monitor)
DataDir string // directory of the postgres database
DBRole string // the 'role' of the running pgsql instance inside the node (master, slave)
Ip string // advertise_ip
PGPort int //
State string // the current state of the node
UpdatedAt time.Time // the last time the node state was updated
}
var (
status *Status
store *scribble.Driver
)
// StatusStart
func StatusStart() error {
log.Info("[(%s) status.StatusStart]", conf.Role)
var err error
// create a new scribble store
store, err = scribble.New(conf.StatusDir, log)
if err != nil {
log.Fatal("[(%s) status.StatusStart] Failed to create scribble.Driver. Exiting... %s", conf.Role, err)
}
status = &Status{}
// determine if the current node already has a record in scribble
fi, err := os.Stat(conf.StatusDir + "cluster/" + conf.Role)
if err != nil {
log.Warn("[(%s) status.StatusStart] Failed to %s", conf.Role, err)
}
// if no record found that matches the current node; create a new record in
// scribble
if fi == nil {
log.Warn("[(%s) status.StatusStart] 404 Not found: Creating record for '%s'", conf.Role, conf.Role)
//
status = &Status{
CRole: conf.Role,
DataDir: conf.DataDir,
DBRole: "initialized",
Ip: conf.AdvertiseIp,
PGPort: conf.PGPort,
State: "booting",
UpdatedAt: time.Now(),
}
save(status)
// record found; set nodes status information
} else {
status = Whoami()
}
log.Debug("[(%s) status] Node Status: %#v\n", status.CRole, status)
// register our Status struct with RPC
rpc.Register(status)
fmt.Printf("[(%s) status] Starting RPC server... ", status.CRole)
// fire up an RPC (tcp) server
l, err := net.Listen("tcp", fmt.Sprintf(":%d", conf.AdvertisePort))
if err != nil {
log.Error("[(%s) status] Unable to start server!\n%s\n", status.CRole, err)
return err
}
fmt.Printf("success (listening on port %d)\n", conf.AdvertisePort)
// daemonize the server
go func(l net.Listener) {
// accept connections on the RPC server
for {
if conn, err := l.Accept(); err != nil {
log.Error("[(%s) status] RPC server - failed to accept connection!\n%s", status.CRole, err.Error())
} else {
log.Debug("[(%s) status] RPC server - new connection established!\n", status.CRole)
//
go rpc.ServeConn(conn)
}
}
}(l)
return nil
}
// Whoami attempts to pull a matching record from scribble for the local node
// returned from memberlist
func Whoami() *Status {
log.Debug("[status.Whoami] %s", status.CRole)
v := &Status{}
// attempt to pull records from scribble... if unsuccessful fail.
for i := 0; i < 10; i++ {
// attempt to pull a record from scribble for the current node
if err := get(conf.Role, v); err == nil {
return v
} else {
log.Warn("[(%s) status.Whoami] Unable to retrieve record! retrying... (%s)", status.CRole, err)
}
}
log.Fatal("[(%s) status.Whoami] Failed to retrieve record!", status.CRole)
os.Exit(1)
return nil
}
// Whois takes a 'role' string and iterates over all the nodes in memberlist looking
// for a matching node. If a matching node is found it then creates an RPC client
// which is used to make an RPC call to the matching node, which returns a Status
// object for that node
func Whois(role string) (*Status, error) {
log.Debug("[(%s) status.Whois] Who is '%s'?", status.CRole, role)
conn := getConn(role)
if conn == "" {
return nil, errors.New("I could not find a connection string for role(" + role + ")")
}
log.Debug("[(%s) status.Whois] connection - %s", status.CRole, conn)
// create an RPC client that will connect to the matching node
client, err := rpcClient(conn)
if err != nil {
log.Error("[(%s) status.Whois] RPC Client unable to dial!\n%s", status.CRole, err)
return nil, err
}
//
defer client.Close()
reply := &Status{}
//
c := make(chan error, 1)
go func() { c <- client.Call("Status.RPCEnsureWhois", status.CRole, reply) }()
select {
case err := <-c:
if err != nil {
return nil, err
}
return reply, err
case <-time.After(15 * time.Second):
return nil, errors.New("Timeout waiting for method call")
}
return reply, nil
}
// Whoisnot takes a 'role' string and attempts to find the 'other' node that does
// not match the role provided
func Whoisnot(not string) (*Status, error) {
log.Debug("[(%s) status.Whoisnot] Who is not '%s'?", status.CRole, not)
var role string
// set role equal to the 'opposite' of the given role
switch not {
case "primary":
role = "secondary"
case "secondary":
role = "primary"
}
// return the node that does not match the give role
return Whois(role)
}
// Cluster iterates over all the nodes in member list, running a Whois(), and
// storing each corresponding Status into a slice and returning the collection
func Cluster(who ...string) []Status {
var members = &[]Status{}
if len(who) == 0 {
log.Debug("[(%s) status.Cluster] Retrieving cluster stats (local)...", status.CRole)
if err := status.RPCCluster(conf.Role, members); err != nil {
log.Error("[(%s) status.Cluster] Retrieving cluster stats (%s)", status.CRole, err.Error())
}
return *members
}
for _, role := range who {
conn := getConn(role)
if conn == "" {
continue
}
log.Debug("[(%s) status.Cluster] connection - %s", status.CRole, conn)
// create an RPC client that will connect to the matching node
client, err := rpcClient(conn)
if err != nil {
log.Error("[(%s) status.Cluster] RPC Client unable to dial!\n%s", status.CRole, err)
continue
}
//
defer client.Close()
//
membs := &[]Status{}
c := make(chan error, 1)
go func() { c <- client.Call("Status.RPCCluster", status.CRole, membs) }()
select {
case err := <-c:
if err != nil {
continue
}
*members = append(*members, *membs...)
case <-time.After(30 * time.Second):
continue
}
}
return *members
}
// SetDBRole takes a 'role' string and attempts to set the Status.DBRole, and then
// update the record via scribble
func (s *Status) SetDBRole(role string) {
log.Debug("[(%s) status.SetDBRole] setting role '%s' on node '%s'", s.CRole, role, s.CRole)
s.DBRole = role
if err := save(s); err != nil {
log.Fatal("[(%s) status.SetDBRole] Failed to save status! %s", s.CRole, err)
panic(err)
}
s.UpdatedAt = time.Now()
}
// SetState takes a 'state' string and attempts to set the Status.State, and then
// update the record via scribble
func (s *Status) SetState(state string) {
log.Debug("[(%s) status.SetState] setting '%s' on '%s'", s.CRole, state, s.CRole)
s.State = state
if err := save(s); err != nil {
log.Fatal("[(%s) status.SetDBRole] Failed to save status! %s", s.CRole, err)
panic(err)
}
}
// RPCEnsureWhois ensures full duplex communication between nodes before sending
// back status information for a requested node
func (s *Status) RPCEnsureWhois(asking string, v *Status) error {
log.Debug("[(%s) status.RPCEnsureWhois] '%s' requesting '%s's' status...", s.CRole, asking, s.CRole)
conn := getConn(asking)
if conn == "" {
return errors.New("I could not find a connection string for role(" + asking + ")")
}
log.Debug("[(%s) status.RPCEnsureWhois] connection - %s", status.CRole, conn)
// create an RPC client that will connect to the matching node
client, err := rpcClient(conn)
if err != nil {
log.Error("[(%s) status.RPCEnsureWhois] RPC Client unable to dial!\n%s", s.CRole, err)
return err
}
//
defer client.Close()
tmp := &Status{}
// 'pingback' to the requesting node to ensure duplex communication
c := make(chan error, 1)
go func() { c <- client.Call("Status.RPCWhois", status.CRole, tmp) }()
select {
case err := <-c:
if err != nil {
return err
}
return s.RPCWhois(asking, v)
case <-time.After(10 * time.Second):
return errors.New("Timeout waiting for method RPCWhois")
}
// if err := client.Call("Status.RPCWhois", asking, tmp); err != nil {
// log.Error("[(%s) status.RPCEnsureWhois] RPC Client unable to call!\n%s", s.CRole, err)
// return err
// }
// return status
return errors.New("Execution failed!")
}
// RPCWhois is the response to an RPC call made from Whois requesting the status
// information for the provided 'role'
func (s *Status) RPCWhois(asking string, v *Status) error {
log.Debug("[(%s) status.RPCWhois] '%s' providing status to '%s'...", s.CRole, s.CRole, asking)
// attempt to retrieve that Status of the node from scribble
if err := get(status.CRole, v); err != nil {
log.Error("[(%s) status.RPCWhois] Failed to retrieve status!\n%s\n", status.CRole, err.Error())
return err
}
return nil
}
// RPCCluster
func (s *Status) RPCCluster(source string, v *[]Status) error {
log.Debug("[(%s) status.RPCCluster] Requesting cluster stats...", s.CRole)
errHandle := func(s *Status, err error) *Status {
if err != nil {
log.Warn("[(%s) status.Cluster] Failed to retrieve status!\n%s", status.CRole, err)
}
return s
}
self := Whoami()
*v = append(*v, *s)
switch self.CRole {
case "monitor":
if s := errHandle(Whois("primary")); s != nil {
*v = append(*v, *s)
}
if s := errHandle(Whois("secondary")); s != nil {
*v = append(*v, *s)
}
case "primary":
if s := errHandle(Whois("monitor")); s != nil {
*v = append(*v, *s)
}
if s := errHandle(Whois("secondary")); s != nil {
*v = append(*v, *s)
}
case "secondary":
if s := errHandle(Whois("monitor")); s != nil {
*v = append(*v, *s)
}
if s := errHandle(Whois("primary")); s != nil {
*v = append(*v, *s)
}
}
return nil
}
// Demote is used as a way to 'advise' the current node that it needs to demote
func (s *Status) Demote(source string, v *Status) error {
log.Debug("[(%s) status.Demote] Advising demote...", s.CRole)
go func() { advice <- "demote" }()
return nil
}
func rpcClient(conn string) (*rpc.Client, error) {
c := make(chan error, 1)
var client *rpc.Client
var err error
go func() {
client, err = rpc.Dial("tcp", conn)
c <- err
}()
select {
case err := <-c:
return client, err
case <-time.After(2 * time.Second):
return nil, errors.New("Timeout Waiting for rpc.Dial")
}
}
func getConn(role string) string {
switch role {
case "monitor":
return conf.Monitor
case "primary":
return conf.Primary
case "secondary":
return conf.Secondary
}
return ""
}
// get retrieves a Status from scribble by 'role'
func get(role string, v *Status) error {
log.Debug("[(%s) status.get] Attempting to get node '%s'", status.CRole, role)
t := scribble.Transaction{Action: "read", Collection: "cluster", ResourceID: role, Container: &v}
if err := store.Transact(t); err != nil {
return err
}
return nil
}
// save saves a Status to scribble by 'role'
func save(v *Status) error {
log.Debug("[(%s) status.save] Attempting to save node '%s'", status.CRole, status.CRole)
t := scribble.Transaction{Action: "write", Collection: "cluster", ResourceID: status.CRole, Container: &v}
if err := store.Transact(t); err != nil {
return err
}
return nil
}
|
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/elasticsearchservice"
)
// Creating a new ElasticSearchService domain
// Not using this for now, need go through detailed
// configuration for elastic search domain
// for now will create a new domain using aws console ui
func createEsDomain(sess *session.Session) {
svc := elasticsearchservice.New(sess, aws.NewConfig().WithLogLevel(aws.LogDebugWithHTTPBody))
input := &elasticsearchservice.CreateElasticsearchDomainInput{
DomainName: aws.String("cupcake-updates-01"),
}
result, err := svc.CreateElasticsearchDomain(input)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(result)
}
|
package cholesky
import (
"gonum.org/v1/gonum/mat"
)
type CTriDense struct {
Matrix *mat.CDense
Kind mat.TriKind
Len int
}
func newCTriDense(n int, kind mat.TriKind) *CTriDense {
return &CTriDense{
Matrix: mat.NewCDense(n, n, nil),
Kind: kind,
Len: n,
}
}
func (tri *CTriDense) SetTri(i, j int, value complex128) {
if tri.Kind == mat.Lower {
tri.Matrix.Set(i, j, value)
}
}
func (tri *CTriDense) Dims() (r, c int) {
return tri.Len, tri.Len
}
func (tri *CTriDense) At(i, j int) complex128 {
return tri.Matrix.At(i, j)
}
func (tri *CTriDense) H() mat.CMatrix {
if tri.Kind == mat.Upper {
for i := 0; i < tri.Len; i++ {
for j := i; j < tri.Len; j++ {
if i == j {
continue
}
tri.Matrix.Set(j, i, tri.Matrix.At(i, j))
tri.Matrix.Set(i, j, 0)
}
}
tri.Kind = mat.Lower
return tri
}
for i := 0; i < tri.Len; i++ {
for j := 0; j < i; j++ {
if i == j {
continue
}
tri.Matrix.Set(j, i, tri.Matrix.At(i, j))
tri.Matrix.Set(i, j, 0)
}
}
tri.Kind = mat.Upper
return tri
}
type CVector interface {
mat.CMatrix
AtVec(int) complex128
Len() int
}
type CVectorDense struct {
Matrix *mat.CDense
}
func newCVector(len int, values []complex128) *CVectorDense {
return &CVectorDense{
Matrix: mat.NewCDense(len, 1, values),
}
}
func (vec *CVectorDense) SetVec(i int, value complex128) {
vec.Matrix.Set(i, 0, value)
}
func (vec *CVectorDense) AtVec(i int) complex128 {
return vec.Matrix.At(i, 0)
}
func (vec *CVectorDense) At(i, j int) complex128 {
return vec.Matrix.At(i, j)
}
func (vec *CVectorDense) Len() int {
l, _ := vec.Matrix.Dims()
return l
}
func (vec *CVectorDense) Dims() (r, c int) {
r, c = vec.Matrix.Dims()
return
}
func (vec *CVectorDense) H() mat.CMatrix {
result := mat.NewCDense(1, vec.Len(), nil)
for i := 0; i < vec.Len(); i++ {
result.Set(0, i, vec.AtVec(i))
}
return result
}
|
// Go1.11开始支持WebAssembly,
// 对应的操作系统名为js,对应的CPU类型为wasm。
// 目前还无法通过 go run 的方式直接运行输出的wasm文件,
// 因此我们需要通过 go build 的方式生成wasm目标文件,
// cd go-webassembly/hello
// GOARCH=wasm GOOS=js go build -o hello.wasm hello.go
// 然后通过Node环境执行。
// node ../lib/wasm_exec.js hello.wasm
package main
import (
"fmt"
"syscall/js"
)
func main() {
fmt.Println("Hello WebAssembly!")
js.Global().Get("console").Call("log", "Hello World Go/wasm!")
// js.Global().Get("document").Call("getElementById", "app").Set("innerText", time.Now().String())
}
|
package runtime
// Program data type
type Type uint8
const (
// Empty value, nil
NilType Type = iota
// Boolean true/false
BooleanType
// Integers
IntType
// Unique symbols; variable names, function names
SymbolType
// Generic sequences
SequenceType
// Generic associations
AssocType
// Strings
StringType
// Cons sequences
ConsType
// Linked lists
ListType
// Functions
FuncType
// Macros
MacroType
// Input/output ports
PortType
// Modules
ModuleType
)
// Program runtime value
type Value interface {
// Eval to the lowest level value
Eval(env Env) (Value, error)
// Eval to the lowest level value
Type() Type
// Provide a representation of this value as string
String() string
}
// Runtime environment
type Env interface {
// Define a new symbol
Def(string, Value) error
// Lookup a variable in the current scope
Get(string) (Value, bool)
// Resolve a symbol in the entire environment
Resolve(string) (Value, bool)
// Introduce a new scope
Extend() Env
// Start a transaction within this environment
Transaction() EnvTransaction
}
// A transaction allows many values be defined atomically and in isolation.
// On commit, the values are atomically set into Env.
// There is no rollback; the transaction is simply discarded.
type EnvTransaction interface {
Env
// Commit all values defined in this transaction.
Commit()
}
|
package redis
import (
_ "encoding/json"
_ "fmt"
_ "github.com/go-redis/redis"
_ "github.com/tidwall/gjson"
_ "io/ioutil"
)
type config struct {
OptionsConns map[string]Options `json:"options_conns"`
Default string `json:"default"`
}
|
package fractal
import (
"image"
"image/color"
)
type Fractal struct {
LowerLeft complex128
UpperRight complex128
Scale float64
RGBA image.RGBA
}
func NewFractal(lowerLeft, upperRight complex128, scale float64) Fractal {
w := int((real(upperRight) - real(lowerLeft))*scale)
h := int((imag(upperRight) - imag(lowerLeft))*scale)
return Fractal{lowerLeft, upperRight, scale, *image.NewRGBA(image.Rect(0,0,w,h))}
}
func (f Fractal) Bounds() image.Rectangle{
return f.RGBA.Bounds()
}
func (f Fractal) ColorModel() color.Model {
return f.RGBA.ColorModel()
}
func (f Fractal) At (x, y int) color.Color {
return f.RGBA.At(x,y)
}
func (f Fractal) Set(x, y int, c color.Color) {
f.RGBA.Set(x,y,c)
}
func (f Fractal) Complex2Point(c complex128) image.Point {
rec := f.Bounds()
x := int((real(c) + real(f.LowerLeft))*f.Scale) + rec.Min.X
y := int((imag(c) + imag(f.LowerLeft))*f.Scale) + rec.Min.Y
return image.Pt(x,y)
}
func (f Fractal) Point2Complex(p image.Point) complex128 {
rec := f.Bounds()
x := float64(p.X - rec.Min.X)/f.Scale + real(f.LowerLeft)
y := float64(p.Y - rec.Min.Y)/f.Scale + imag(f.LowerLeft)
return complex(x,y)
}
func (f Fractal) Apply2All(pos2color func(complex128) color.Color) {
rec := f.Bounds()
for y := rec.Min.Y; y < rec.Max.Y; y++ {
for x := rec.Min.X; x < rec.Max.X; x++ {
f.Set(x,y,pos2color(f.Point2Complex(image.Pt(x,y))))
}
}
} |
// fetch 输出从URL获取得内容
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
)
func main_() {
for _, url := range os.Args[1:]{
resp, err := http.Get(url)
if err != nil{
fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
os.Exit(1)
}
b, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil{
fmt.Fprintf(os.Stderr, "fetch: readng%s: %v\n", url, err)
os.Exit(1)
}
fmt.Printf("%s", b)
}
}
// 函数io.Copy(dst,src),从src读,并且写入dst。使用它代替 ioutil.ReadAll来复制响应内容到os.Stdout, 这样
// 不需要装下整个响应数据流得缓冲区。确保检查io.Copy返回的错误结果
func main() {
for _, url := range os.Args[1:]{
resp, err := http.Get(url)
if err != nil{
fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
os.Exit(2)
}
out, err := os.Create("/json_file/out.txt")
wt := bufio.NewWriter(out)
b, err := io.Copy(wt, resp.Body)
for i := 0; i<4; i++{
fmt.Println("%s", i)
}
fmt.Println("write" , b)
resp.Body.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "fetch: reading%s: %v\n", url, err)
os.Exit(1)
}
wt.Flush()
fmt.Printf("%s", b)
}
}
// 修改fetch程序添加一个http://前缀(假如该URL参数缺失协议前缀)可能会用到strings.HasPrefix
func urlGet(url string) {
resp, err := http.Get(url)
if err != nil{
fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
os.Exit(2)
}
b, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil{
fmt.Fprintf(os.Stderr, "fetch: readng%s: %v\n", url, err)
os.Exit(1)
}
fmt.Printf("%s", b)
}
func mainBL() {
for _, url := range os.Args[1:]{
if strings.HasPrefix(url, "http://"){ //strings.HasPrefix 判断是否以什么为前缀,返回bool类型
urlGet(url)
}else {
url := "http://" + url
urlGet(url)
}
}
}
// 修改fetch来输出Http得状态码, 可以在resp.Status中找到它
//func main() {
// for _, url := range os.Args[1:]{
//
// }
//}
|
package main
import (
"fmt"
"reflect"
)
// 比较2个map
func mapDeepEqual() {
a := map[int]string{1: "a", 2: "b", 3: "c"}
b := map[int]string{1: "a", 2: "b", 3: "c"}
c := map[int]string{1: "a", 2: "b", 4: "c"}
fmt.Println(reflect.DeepEqual(a, b))
fmt.Println(reflect.DeepEqual(a, c))
}
// 比较切片
func sliceDeepEqual() {
a := []int{1, 2, 3}
b := []int{1, 2, 3}
c := []int{1, 2, 4}
fmt.Println(reflect.DeepEqual(a, b))
fmt.Println(reflect.DeepEqual(a, c))
}
func main() {
mapDeepEqual()
sliceDeepEqual()
}
|
package main
//1178. 猜字谜
//外国友人仿照中国字谜设计了一个英文版猜字谜小游戏,请你来猜猜看吧。
//
//字谜的迷面puzzle 按字符串形式给出,如果一个单词word符合下面两个条件,那么它就可以算作谜底:
//
//单词word中包含谜面puzzle的第一个字母。
//单词word中的每一个字母都可以在谜面puzzle中找到。
//例如,如果字谜的谜面是 "abcdefg",那么可以作为谜底的单词有 "faced", "cabbage", 和 "baggage";而 "beefed"(不含字母 "a")以及"based"(其中的 "s" 没有出现在谜面中)。
//返回一个答案数组answer,数组中的每个元素answer[i]是在给出的单词列表 words 中可以作为字谜迷面puzzles[i]所对应的谜底的单词数目。
//
//
//
//示例:
//
//输入:
//words = ["aaaa","asas","able","ability","actt","actor","access"],
//puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]
//输出:[1,1,3,2,4,0]
//解释:
//1 个单词可以作为 "aboveyz" 的谜底 : "aaaa"
//1 个单词可以作为 "abrodyz" 的谜底 : "aaaa"
//3 个单词可以作为 "abslute" 的谜底 : "aaaa", "asas", "able"
//2 个单词可以作为"absoryz" 的谜底 : "aaaa", "asas"
//4 个单词可以作为"actresz" 的谜底 : "aaaa", "asas", "actt", "access"
//没有单词可以作为"gaswxyz" 的谜底,因为列表中的单词都不含字母 'g'。
//
//
//提示:
//
//1 <= words.length <= 10^5
//4 <= words[i].length <= 50
//1 <= puzzles.length <= 10^4
//puzzles[i].length == 7
//words[i][j], puzzles[i][j]都是小写英文字母。
//每个puzzles[i]所包含的字符都不重复。
//思路 状态压缩 朴素位运算 哈希表位
//
func findNumOfValidWords(words []string, puzzles []string) []int {
n := len(puzzles)
pDic := make([]int, n)
pHead := make([]int, n)
for i, v := range puzzles {
pHead[i] = int(v[0] - 'a')
for _, b := range v {
pDic[i] |= 1 << (b - 'a')
}
}
wDic := make(map[int]int)
for _, v := range words {
w := 0
for _, b := range v {
w |= 1 << (b - 'a')
}
wDic[w]++
}
result := make([]int, n)
for i, v := range pDic {
head := 1 << pHead[i]
w := v
for w > 0 {
if w&head > 0 && wDic[w] > 0 {
result[i] += wDic[w]
}
w = (w - 1) & v
}
}
return result
}
func main() {
findNumOfValidWords([]string{"aaaa", "asas", "able", "ability", "actt", "actor", "access"},
[]string{"aboveyz", "abrodyz", "abslute", "absoryz", "actresz", "gaswxyz"})
}
|
package main
// Leetcode m17.19. (hard)
func missingTwo(nums []int) []int {
n := len(nums) + 2
res := 0
for i := 1; i <= n; i++ {
res ^= i
}
for _, num := range nums {
res ^= num
}
lowbit := res & (-res)
one := 0
for i := 1; i <= n; i++ {
if i&lowbit == 0 {
one ^= i
}
}
for _, num := range nums {
if num&lowbit == 0 {
one ^= num
}
}
return []int{one, one ^ res}
}
func missingTwo2(nums []int) []int {
n := len(nums) + 2
sum := (1 + n) * n / 2
for _, num := range nums {
sum += num
}
sumTwo := (1+n)*n - sum
average := sumTwo / 2
sum = 0
for _, num := range nums {
if num <= average {
sum += num
}
}
one := (1+average)*average/2 - sum
return []int{one, sumTwo - one}
}
func missingTwo3(nums []int) []int {
nums = append(nums, []int{-1, -1, -1}...)
for i := 0; i < len(nums); i++ {
for i != nums[i] && nums[i] != -1 {
nums[i], nums[nums[i]] = nums[nums[i]], nums[i]
}
}
res := []int{}
for i := 1; i < len(nums); i++ {
if nums[i] == -1 {
res = append(res, i)
}
}
return res
}
|
package epazote
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"regexp"
"sync"
"testing"
)
func TestSuperviceTestOk(t *testing.T) {
var wg sync.WaitGroup
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if i["name"] != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", i["name"])
}
// check because
if b, ok := i["because"]; ok {
if b != "Test cmd: " {
t.Errorf("Expecting: %q, got: %q", "Test cmd: ", b)
}
} else {
t.Errorf("key not found: %q", "because")
}
// check exit
if e, ok := i["exit"]; ok {
if e.(float64) != 0 {
t.Errorf("Expecting: 0 got: %v", e.(float64))
}
} else {
t.Errorf("key not found: %q", "exit")
}
// check test
if tt, ok := i["test"]; ok {
if tt != "test 3 -gt 2" {
t.Errorf("Expecting: %q, got: %q", "Test cmd: ", tt)
}
} else {
t.Errorf("key not found: %q", "test")
}
// check url
if o, ok := i["url"]; ok {
t.Errorf("key should not exist,content: %q", o)
}
if i["status"].(float64) != 0 {
t.Errorf("Expecting status: %d got: %v", 0, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
Test: Test{
Test: "test 3 -gt 2",
},
Log: log_s.URL,
}
ez := &Epazote{
Services: s,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
}
func TestSuperviceTestNotOk(t *testing.T) {
var wg sync.WaitGroup
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if n, ok := i["name"]; ok {
if n != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", n)
}
} else {
t.Errorf("key not found: %q", "name")
}
// check because
if b, ok := i["because"]; ok {
if b != "Test cmd: exit status 1" {
t.Errorf("Expecting: %q, got: %q", "Test cmd: exit status 1", b)
}
} else {
t.Errorf("key not found: %q", "because")
}
// check exit
if e, ok := i["exit"]; ok {
if e.(float64) != 1 {
t.Errorf("Expecting: 1 got: %v", e.(float64))
}
} else {
t.Errorf("key not found: %q", "exit")
}
// check test
if tt, ok := i["test"]; ok {
if tt != "test 3 -gt 5" {
t.Errorf("Expecting: %q, got: %q", "Test cmd: ", tt)
}
} else {
t.Errorf("key not found: %q", "test")
}
// check url
if o, ok := i["url"]; ok {
t.Errorf("key should not exist,content: %q", o)
}
// check output
if o, ok := i["output"]; ok {
e := "No defined cmd"
if o != e {
t.Errorf("Expecting %q, got %q", e, o)
}
} else {
t.Errorf("key not found: %q", "output")
}
if i["status"].(float64) != 0 {
t.Errorf("Expecting status: %d got: %v", 0, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
Test: Test{
Test: "test 3 -gt 5",
},
Log: log_s.URL,
}
ez := &Epazote{
Services: s,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
}
func TestSuperviceStatusCreated(t *testing.T) {
var wg sync.WaitGroup
check_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
w.WriteHeader(http.StatusCreated)
}))
defer check_s.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if n, ok := i["name"]; ok {
if n != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", n)
}
} else {
t.Errorf("key not found: %q", "name")
}
// check because
if b, ok := i["because"]; ok {
if b != "Status: 201" {
t.Errorf("Expecting: %q, got: %q", "Status: 201", b)
}
} else {
t.Errorf("key not found: %q", "because")
}
// check exit
if e, ok := i["exit"]; ok {
if e.(float64) != 0 {
t.Errorf("Expecting: 0 got: %v", e.(float64))
}
} else {
t.Errorf("key not found: %q", "exit")
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
if i["status"].(float64) != 201 {
t.Errorf("Expecting status: %d got: %v", 201, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: check_s.URL,
Log: log_s.URL,
Expect: Expect{
Status: 201,
},
}
ez := &Epazote{
Services: s,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
}
func TestSuperviceBodyMatch(t *testing.T) {
var wg sync.WaitGroup
check_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
fmt.Fprintln(w, "Hello, epazote match 0BC20225-2E72-4646-9202-8467972199E1 regex")
}))
defer check_s.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if n, ok := i["name"]; ok {
if n != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", n)
}
} else {
t.Errorf("key not found: %q", "name")
}
// check because
if b, ok := i["because"]; ok {
e := "Body regex match: 0BC20225-2E72-4646-9202-8467972199E1"
if b != e {
t.Errorf("Expecting: %q, got: %q", e, b)
}
} else {
t.Errorf("key not found: %q", "because")
}
// check exit
if e, ok := i["exit"]; ok {
if e.(float64) != 0 {
t.Errorf("Expecting: 0 got: %v", e.(float64))
}
} else {
t.Errorf("key not found: %q", "exit")
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
if i["status"].(float64) != 200 {
t.Errorf("Expecting status: %d got: %v", 200, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
re := regexp.MustCompile(`(?i)[a-z0-9]{8}-[a-z0-9]{4}-[1-5][a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{12}`)
s["s 1"] = &Service{
Name: "s 1",
URL: check_s.URL,
Log: log_s.URL,
Expect: Expect{
Body: "(?i)[a-z0-9]{8}-[a-z0-9]{4}-[1-5][a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{12}",
body: re,
},
}
ez := &Epazote{
Services: s,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
}
func TestSuperviceBodyNoMatch(t *testing.T) {
var wg sync.WaitGroup
check_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
fmt.Fprintln(w, "Hello, epazote match 0BC20225-2E72-4646-9202-8467972199E1 regex")
}))
defer check_s.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if n, ok := i["name"]; ok {
if n != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", n)
}
} else {
t.Errorf("key not found: %q", "name")
}
// check because
if b, ok := i["because"]; ok {
e := "Body no regex match: [a-z0-9]{8}-[a-z0-9]{4}-[1-5][a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{12}"
if b != e {
t.Errorf("Expecting: %q, got: %q", e, b)
}
} else {
t.Errorf("key not found: %q", "because")
}
// check exit
if e, ok := i["exit"]; ok {
if e.(float64) != 1 {
t.Errorf("Expecting: 1 got: %v", e.(float64))
}
} else {
t.Errorf("key not found: %q", "exit")
}
// check output
if o, ok := i["output"]; ok {
e := "No defined cmd"
if o != e {
t.Errorf("Expecting %q, got %q", e, o)
}
} else {
t.Errorf("key not found: %q", "output")
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
if i["status"].(float64) != 200 {
t.Errorf("Expecting status: %d got: %v", 200, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
re := regexp.MustCompile(`[a-z0-9]{8}-[a-z0-9]{4}-[1-5][a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{12}`)
s["s 1"] = &Service{
Name: "s 1",
URL: check_s.URL,
Log: log_s.URL,
Expect: Expect{
Body: "[a-z0-9]{8}-[a-z0-9]{4}-[1-5][a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{12}",
body: re,
},
}
ez := &Epazote{
Services: s,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
}
func TestSuperviceNoGet(t *testing.T) {
var wg sync.WaitGroup
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if i["name"] != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", i["name"])
}
// check because
e := "GET: http: no Host in request URL"
if i["because"] != e {
t.Errorf("Expecting: %q, got: %q", e, i["because"])
}
// check exit
if i["exit"].(float64) != 1 {
t.Errorf("Expecting: 1 got: %v", i["exit"].(float64))
}
// check output
e = "exit status 1"
if i["output"] != e {
t.Errorf("Expecting %q, got %v", e, i["oputput"])
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
if i["status"].(float64) != 0 {
t.Errorf("Expecting status: %d got: %v", 0, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: "http://",
Log: log_s.URL,
Expect: Expect{
Status: 200,
IfNot: Action{
Cmd: "test 1 -gt 2",
},
},
}
ez := &Epazote{
Services: s,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
}
func TestSuperviceNoGetStatus0(t *testing.T) {
var wg sync.WaitGroup
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if n, ok := i["name"]; ok {
if n != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", n)
}
} else {
t.Errorf("key not found: %q", "name")
}
// check because
if b, ok := i["because"]; ok {
e := "GET: http: no Host in request URL"
if b != e {
t.Errorf("Expecting: %q, got: %q", e, b)
}
} else {
t.Errorf("key not found: %q", "because")
}
// check exit
if e, ok := i["exit"]; ok {
if e.(float64) != 1 {
t.Errorf("Expecting: 1 got: %v", e.(float64))
}
} else {
t.Errorf("key not found: %q", "exit")
}
// check output
if o, ok := i["output"]; ok {
t.Errorf("key should not exist,content: %q", o)
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
if i["status"].(float64) != 0 {
t.Errorf("Expecting status: %d got: %v", 0, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: "http://",
Log: log_s.URL,
Expect: Expect{
Status: 200,
IfNot: Action{
Cmd: "test 3 -gt 2",
},
},
}
ez := &Epazote{
Services: s,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
}
func TestSuperviceIfStatusMatch502(t *testing.T) {
var wg sync.WaitGroup
check_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
http.Error(w, http.StatusText(502), 502)
}))
defer check_s.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if n, ok := i["name"]; ok {
if n != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", n)
}
} else {
t.Errorf("key not found: %q", "name")
}
// check because
if b, ok := i["because"]; ok {
if b != "Status: 502" {
t.Errorf("Expecting: %q, got: %q", "Status: 502", b)
}
} else {
t.Errorf("key not found: %q", "because")
}
// check exit
if e, ok := i["exit"]; ok {
if e.(float64) != 1 {
t.Errorf("Expecting: 0 got: %v", e.(float64))
}
} else {
t.Errorf("key not found: %q", "exit")
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
// check output
e := "No defined cmd"
if i["output"] != e {
t.Errorf("Expecting %q, got %q", e, i["output"])
}
if i["status"].(float64) != 502 {
t.Errorf("Expecting status: %d got: %v", 502, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: check_s.URL,
Log: log_s.URL,
Expect: Expect{
Status: 200,
IfNot: Action{},
},
IfStatus: map[int]Action{
501: Action{},
502: Action{},
503: Action{},
},
IfHeader: map[string]Action{
"x-amqp-kapputt": Action{
Notify: "yes",
},
},
}
ez := &Epazote{
Services: s,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
}
func TestSuperviceIfStatusNoMatch(t *testing.T) {
var wg sync.WaitGroup
check_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
http.Error(w, http.StatusText(505), 505)
}))
defer check_s.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if n, ok := i["name"]; ok {
if n != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", n)
}
} else {
t.Errorf("key not found: %q", "name")
}
// check because
if b, ok := i["because"]; ok {
if b != "Status: 505" {
t.Errorf("Expecting: %q, got: %q", "Status: 505", b)
}
} else {
t.Errorf("key not found: %q", "because")
}
// check exit
if e, ok := i["exit"]; ok {
if e.(float64) != 1 {
t.Errorf("Expecting: 0 got: %v", e.(float64))
}
} else {
t.Errorf("key not found: %q", "exit")
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
// check output
e := "No defined cmd"
if i["output"] != e {
t.Errorf("Expecting %q, got %q", e, i["output"])
}
if i["status"].(float64) != 505 {
t.Errorf("Expecting status: %d got: %v", 505, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: check_s.URL,
Log: log_s.URL,
Expect: Expect{
Status: 200,
IfNot: Action{},
},
IfStatus: map[int]Action{
501: Action{},
502: Action{},
503: Action{},
},
IfHeader: map[string]Action{
"x-amqp-kapputt": Action{Notify: "yes"},
"x-db-kapputt": Action{},
},
}
ez := &Epazote{
Services: s,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
}
func TestSuperviceIfHeaderMatch(t *testing.T) {
var wg sync.WaitGroup
check_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
w.Header().Set("x-db-kapputt", "si si si")
fmt.Fprintln(w, "Hello")
}))
defer check_s.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if n, ok := i["name"]; ok {
if n != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", n)
}
} else {
t.Errorf("key not found: %q", "name")
}
// check because
if b, ok := i["because"]; ok {
if b != "Header: X-Db-Kapputt" {
t.Errorf("Expecting: %q, got: %q", "Header: x-db-kapputt", b)
}
} else {
t.Errorf("key not found: %q", "because")
}
// check exit
if e, ok := i["exit"]; ok {
if e.(float64) != 1 {
t.Errorf("Expecting: 0 got: %v", e.(float64))
}
} else {
t.Errorf("key not found: %q", "exit")
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
// check output
e := "exit status 1"
if i["output"] != e {
t.Errorf("Expecting %q, got %q", e, i["output"])
}
if i["status"].(float64) != 200 {
t.Errorf("Expecting status: %d got: %v", 200, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: check_s.URL,
Log: log_s.URL,
Expect: Expect{
Status: 200,
IfNot: Action{},
},
IfStatus: map[int]Action{
501: Action{},
503: Action{},
},
IfHeader: map[string]Action{
"x-amqp-kapputt": Action{Notify: "yes"},
"X-Db-Kapputt": Action{
Cmd: "test 1 -gt 2",
},
},
}
ez := &Epazote{
Services: s,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
}
func TestSuperviceStatus202(t *testing.T) {
var wg sync.WaitGroup
check_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
w.WriteHeader(http.StatusAccepted)
}))
defer check_s.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if n, ok := i["name"]; ok {
if n != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", n)
}
} else {
t.Errorf("key not found: %q", "name")
}
// check because
if b, ok := i["because"]; ok {
if b != "Status: 202" {
t.Errorf("Expecting: %q, got: %q", "Status: 202", b)
}
} else {
t.Errorf("key not found: %q", "because")
}
// check exit
if e, ok := i["exit"]; ok {
if e.(float64) != 0 {
t.Errorf("Expecting: 0 got: %v", e.(float64))
}
} else {
t.Errorf("key not found: %q", "exit")
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
// check output
if o, ok := i["output"]; ok {
t.Errorf("key should not exist,content: %q", o)
}
if i["status"].(float64) != 202 {
t.Errorf("Expecting status: %d got: %v", 202, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: check_s.URL,
Log: log_s.URL,
Expect: Expect{
Status: 202,
IfNot: Action{},
},
IfStatus: map[int]Action{
501: Action{},
503: Action{},
},
IfHeader: map[string]Action{
"x-amqp-kapputt": Action{Notify: "yes"},
"X-Db-Kapputt": Action{
Cmd: "test 1 -gt 2",
},
},
}
ez := &Epazote{
Services: s,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
}
func TestSuperviceMissingHeader(t *testing.T) {
var wg sync.WaitGroup
check_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
w.Header().Set("X-Abc", "xyz")
}))
defer check_s.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if n, ok := i["name"]; ok {
if n != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", n)
}
} else {
t.Errorf("key not found: %q", "name")
}
// check because
if b, ok := i["because"]; ok {
if b != "Header: test: xxx" {
t.Errorf("Expecting: %q, got: %q", "Header: test: xxx", b)
}
} else {
t.Errorf("key not found: %q", "because")
}
// check exit
if e, ok := i["exit"]; ok {
if e.(float64) != 1 {
t.Errorf("Expecting: 1 got: %v", e.(float64))
}
} else {
t.Errorf("key not found: %q", "exit")
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
// check output
if o, ok := i["output"]; ok {
e := "No defined cmd"
if o != e {
t.Errorf("Expecting %q, got %q", e, o)
}
} else {
t.Errorf("key not found: %q", "output")
}
if i["status"].(float64) != 200 {
t.Errorf("Expecting status: %d got: %v", 200, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: check_s.URL,
Log: log_s.URL,
Expect: Expect{
Status: 200,
Header: map[string]string{
"test": "xxx",
"X-Abc": "xyz",
},
IfNot: Action{},
},
IfStatus: map[int]Action{
501: Action{},
503: Action{},
},
IfHeader: map[string]Action{
"x-amqp-kapputt": Action{Notify: "yes"},
"X-Db-Kapputt": Action{
Cmd: "test 1 -gt 2",
},
},
}
ez := &Epazote{
Services: s,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
}
func TestSuperviceMatchingHeader(t *testing.T) {
var wg sync.WaitGroup
check_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
w.Header().Set("X-Abc", "xyz")
}))
defer check_s.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if n, ok := i["name"]; ok {
if n != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", n)
}
} else {
t.Errorf("key not found: %q", "name")
}
// check because
if b, ok := i["because"]; ok {
if b != "Status: 200" {
t.Errorf("Expecting: %q, got: %q", "Status: 200", b)
}
} else {
t.Errorf("key not found: %q", "because")
}
// check exit
if e, ok := i["exit"]; ok {
if e.(float64) != 0 {
t.Errorf("Expecting: 0 got: %v", e.(float64))
}
} else {
t.Errorf("key not found: %q", "exit")
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
// check output
if o, ok := i["output"]; ok {
t.Errorf("key should not exist,content: %q", o)
}
if i["status"].(float64) != 200 {
t.Errorf("Expecting status: %d got: %v", 200, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: check_s.URL,
Log: log_s.URL,
Expect: Expect{
Status: 200,
Header: map[string]string{
"X-Abc": "xyz",
},
IfNot: Action{},
},
IfStatus: map[int]Action{
501: Action{},
503: Action{},
},
IfHeader: map[string]Action{
"x-amqp-kapputt": Action{Notify: "yes"},
"X-Db-Kapputt": Action{
Cmd: "test 1 -gt 2",
},
},
}
ez := &Epazote{
Services: s,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
}
func TestSuperviceMatchingHeaderPrefix(t *testing.T) {
var wg sync.WaitGroup
check_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
w.Header().Set("content-type", "application/json; charset=UTF-8")
}))
defer check_s.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if n, ok := i["name"]; ok {
if n != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", n)
}
} else {
t.Errorf("key not found: %q", "name")
}
// check because
if b, ok := i["because"]; ok {
if b != "Status: 200" {
t.Errorf("Expecting: %q, got: %q", "Status: 200", b)
}
} else {
t.Errorf("key not found: %q", "because")
}
// check exit
if e, ok := i["exit"]; ok {
if e.(float64) != 0 {
t.Errorf("Expecting: 0 got: %v", e.(float64))
}
} else {
t.Errorf("key not found: %q", "exit")
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
// check output
if o, ok := i["output"]; ok {
t.Errorf("key should not exist,content: %q", o)
}
if i["status"].(float64) != 200 {
t.Errorf("Expecting status: %d got: %v", 200, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: check_s.URL,
Log: log_s.URL,
Expect: Expect{
Status: 200,
Header: map[string]string{
"content-type": "application/json",
},
IfNot: Action{},
},
IfStatus: map[int]Action{
501: Action{},
503: Action{},
},
IfHeader: map[string]Action{
"x-amqp-kapputt": Action{Notify: "yes"},
"X-Db-Kapputt": Action{
Cmd: "test 1 -gt 2",
},
},
}
ez := &Epazote{
Services: s,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
}
func TestSuperviceLogErr(t *testing.T) {
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: "--",
Log: "http://",
Expect: Expect{
Status: 200,
},
}
ez := new(Epazote)
ser := *s["s 1"]
ez.Log(&ser, []byte{0})
if buf.Len() == 0 {
t.Error("Expecting log.Println error")
}
}
func TestSuperviceMatchingHeaderDebugGreen(t *testing.T) {
buf.Reset()
var wg sync.WaitGroup
check_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
w.Header().Set("X-Abc", "xyz")
}))
defer check_s.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if n, ok := i["name"]; ok {
if n != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", n)
}
} else {
t.Errorf("key not found: %q", "name")
}
// check because
if b, ok := i["because"]; ok {
if b != "Status: 200" {
t.Errorf("Expecting: %q, got: %q", "Status: 200", b)
}
} else {
t.Errorf("key not found: %q", "because")
}
// check exit
if e, ok := i["exit"]; ok {
if e.(float64) != 0 {
t.Errorf("Expecting: 0 got: %v", e.(float64))
}
} else {
t.Errorf("key not found: %q", "exit")
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
// check output
if o, ok := i["output"]; ok {
t.Errorf("key should not exist,content: %q", o)
}
if i["status"].(float64) != 200 {
t.Errorf("Expecting status: %d got: %v", 200, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: check_s.URL,
Log: log_s.URL,
Expect: Expect{
Status: 200,
Header: map[string]string{
"X-Abc": "xyz",
},
IfNot: Action{},
},
IfStatus: map[int]Action{
501: Action{},
503: Action{},
},
IfHeader: map[string]Action{
"x-amqp-kapputt": Action{Notify: "yes"},
"X-Db-Kapputt": Action{
Cmd: "test 1 -gt 2",
},
},
}
ez := &Epazote{
Services: s,
debug: true,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
if buf.Len() == 0 {
t.Error("Expecting log.Println error")
}
}
func TestSuperviceMatchingHeaderDebugRed(t *testing.T) {
buf.Reset()
var wg sync.WaitGroup
check_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
w.Header().Set("X-Abc", "xyz")
}))
defer check_s.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if n, ok := i["name"]; ok {
if n != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", n)
}
} else {
t.Errorf("key not found: %q", "name")
}
// check because
if b, ok := i["because"]; ok {
if b != "Status: 200" {
t.Errorf("Expecting: %q, got: %q", "Status: 200", b)
}
} else {
t.Errorf("key not found: %q", "because")
}
// check exit
if e, ok := i["exit"]; ok {
if e.(float64) != 1 {
t.Errorf("Expecting: 1 got: %v", e.(float64))
}
} else {
t.Errorf("key not found: %q", "exit")
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
// check output
e := "No defined cmd"
if i["output"] != e {
t.Errorf("Expecting %q, got %q", e, i["output"])
}
if i["status"].(float64) != 200 {
t.Errorf("Expecting status: %d got: %v", 200, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: check_s.URL,
Log: log_s.URL,
Expect: Expect{
Status: 300,
Header: map[string]string{
"X-Abc": "xyz",
},
IfNot: Action{},
},
IfStatus: map[int]Action{
501: Action{},
503: Action{},
},
IfHeader: map[string]Action{
"x-amqp-kapputt": Action{Notify: "yes"},
"X-Db-Kapputt": Action{
Cmd: "test 1 -gt 2",
},
},
}
ez := &Epazote{
Services: s,
debug: true,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
if buf.Len() == 0 {
t.Error("Expecting log.Println error")
}
}
func TestSupervice302(t *testing.T) {
buf.Reset()
var wg sync.WaitGroup
check_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
w.WriteHeader(http.StatusFound)
}))
defer check_s.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if n, ok := i["name"]; ok {
if n != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", n)
}
} else {
t.Errorf("key not found: %q", "name")
}
// check because
if b, ok := i["because"]; ok {
if b != "Status: 302" {
t.Errorf("Expecting: %q, got: %q", "Status: 302", b)
}
} else {
t.Errorf("key not found: %q", "because")
}
// check exit
if e, ok := i["exit"]; ok {
if e.(float64) != 0 {
t.Errorf("Expecting: 1 got: %v", e.(float64))
}
} else {
t.Errorf("key not found: %q", "exit")
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
// check output
if o, ok := i["output"]; ok {
t.Errorf("key should not exist,content: %q", o)
}
if i["status"].(float64) != 302 {
t.Errorf("Expecting status: %d got: %v", 302, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: check_s.URL,
Log: log_s.URL,
Expect: Expect{
Status: 302,
IfNot: Action{},
},
IfStatus: map[int]Action{
200: Action{},
},
}
ez := &Epazote{
Services: s,
debug: true,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
if buf.Len() == 0 {
t.Error("Expecting log.Println error")
}
}
func TestSuperviceFollow(t *testing.T) {
buf.Reset()
var wg sync.WaitGroup
check_end := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, epazote match 0BC20225-2E72-4646-9202-8467972199E1 regex")
}))
defer check_end.Close()
check_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
http.Redirect(w, r, check_end.URL, http.StatusFound)
}))
defer check_s.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check name
if n, ok := i["name"]; ok {
if n != "s 1" {
t.Errorf("Expecting %q, got: %q", "s 1", n)
}
} else {
t.Errorf("key not found: %q", "name")
}
// check because
e := "Body regex match: 0BC20225-2E72-4646-9202-8467972199E1"
if i["because"] != e {
t.Errorf("Expecting: %q, got: %v", e, i["because"])
}
// check exit
if i["exit"].(float64) != 0 {
t.Errorf("Expecting: 0 got: %v", i["exit"])
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
// check output
if o, ok := i["output"]; ok {
t.Errorf("key should not exist,content: %q", o)
}
if i["status"].(float64) != 200 {
t.Errorf("Expecting status: %d got: %v", 200, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
re := regexp.MustCompile(`(?i)[a-z0-9]{8}-[a-z0-9]{4}-[1-5][a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{12}`)
s["s 1"] = &Service{
Name: "s 1",
URL: check_s.URL,
Follow: true,
Log: log_s.URL,
Expect: Expect{
Status: 200,
Body: "(?i)[a-z0-9]{8}-[a-z0-9]{4}-[1-5][a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{12}",
body: re,
},
IfStatus: map[int]Action{
302: Action{},
},
}
ez := &Epazote{
Services: s,
debug: true,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
if buf.Len() == 0 {
t.Error("Expecting log.Println error")
}
}
func TestSuperviceSkipCmd(t *testing.T) {
buf.Reset()
var wg sync.WaitGroup
check_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, epazote match 0BC20225-2E72-4646-9202-8467972199E1 regex")
}))
defer check_s.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: check_s.URL,
Follow: true,
Log: log_s.URL,
Expect: Expect{
Status: 201,
IfNot: Action{
Notify: "yes",
},
},
}
ez := &Epazote{
Services: s,
debug: true,
}
wg.Add(2)
ez.Supervice(s["s 1"])()
ez.Supervice(s["s 1"])()
wg.Wait()
if buf.Len() == 0 {
t.Error("Expecting log.Println error")
}
if s["s 1"].status != 2 {
t.Errorf("Expecting status == 2 got: %v", s["s 1"].status)
}
s["s 1"].status = 0
s["s 1"].Expect.Status = 200
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
if s["s 1"].status != 0 {
t.Errorf("Expecting status == 0 got: %v", s["s 1"].status)
}
}
func TestSuperviceCount1000(t *testing.T) {
buf.Reset()
var wg sync.WaitGroup
check_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, epazote")
}))
defer check_s.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: check_s.URL,
Follow: true,
Log: log_s.URL,
Expect: Expect{
Status: 201,
IfNot: Action{
Notify: "yes",
},
},
}
ez := &Epazote{
Services: s,
debug: true,
}
wg.Add(1000)
for i := 0; i < 1000; i++ {
ez.Supervice(s["s 1"])()
}
wg.Wait()
if s["s 1"].status != 1000 {
t.Errorf("Expecting status: 1000 got: %v", s["s 1"].status)
}
}
// server.CloseClientConnections not workng on golang 1.6
func TestSuperviceRetrie(t *testing.T) {
buf.Reset()
var wg sync.WaitGroup
var server *httptest.Server
var counter int
var h http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
if counter <= 1 {
server.CloseClientConnections()
}
w.Header().Set("X-Abc", "xyz")
fmt.Fprintln(w, "Hello, molcajete.org")
counter++
}
server = httptest.NewServer(h)
defer server.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check exit
if i["exit"].(float64) != 0 {
t.Errorf("Expecting: 0 got: %v", i["exit"])
}
// check because
e := "Body regex match: molcajete"
if i["because"] != e {
t.Errorf("Expecting: %q, got: %v", e, i["because"])
}
// check retries
if i["retries"].(float64) != 2 {
t.Errorf("Expecting: 2 got: %v", i["retries"])
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
// check output
if i["status"].(float64) != 200 {
t.Errorf("Expecting status: %d got: %v", 200, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
re := regexp.MustCompile(`molcajete`)
s["s 1"] = &Service{
Name: "s 1",
URL: server.URL,
RetryLimit: 3,
ReadLimit: 17,
Log: log_s.URL,
Expect: Expect{
Status: 200,
Header: map[string]string{
"X-Abc": "xyz",
},
Body: "molcajete",
body: re,
},
}
ez := &Epazote{
Services: s,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
// 1 try, 2 tries
rc := s["s 1"].retryCount
if rc != 2 {
t.Errorf("Expecting retryCount = 2 got: %d", rc)
}
if counter != 3 {
t.Errorf("Expecting 3 got: %v", counter)
}
}
func TestSuperviceRetrieLimit(t *testing.T) {
buf.Reset()
var wg sync.WaitGroup
var server *httptest.Server
var counter int
var h http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
if counter <= 10 {
server.CloseClientConnections()
}
fmt.Fprintln(w, "Hello")
counter++
}
server = httptest.NewServer(h)
defer server.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check exit
if i["exit"].(float64) != 1 {
t.Errorf("Expecting: 1 got: %v", i["exit"])
}
// check retries
if i["retries"].(float64) != 4 {
t.Errorf("Expecting: 4 got: %v", i["retries"])
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
// check output
if i["status"].(float64) != 0 {
t.Errorf("Expecting status: %d got: %v", 0, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: server.URL,
RetryLimit: 5,
RetryInterval: 1,
Log: log_s.URL,
Expect: Expect{
Status: 200,
},
}
ez := &Epazote{
Services: s,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
rc := s["s 1"].retryCount
if rc != 4 {
t.Errorf("Expecting retryCount = 4 got: %d", rc)
}
}
func TestSuperviceRetrieLimit0(t *testing.T) {
buf.Reset()
var wg sync.WaitGroup
var server *httptest.Server
var counter int
var h http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
if counter > 0 {
server.CloseClientConnections()
}
fmt.Fprintln(w, "Hello")
counter++
}
server = httptest.NewServer(h)
defer server.Close()
log_s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-agent") != "epazote" {
t.Error("Expecting User-agent: epazote")
}
decoder := json.NewDecoder(r.Body)
var i map[string]interface{}
err := decoder.Decode(&i)
if err != nil {
t.Error(err)
}
// check exit
if i["exit"].(float64) != 0 {
t.Errorf("Expecting: 0 got: %v", i["exit"])
}
// check retries
if _, ok := i["retries"]; ok {
t.Errorf("retries key found")
}
// check url
if _, ok := i["url"]; !ok {
t.Error("URL key not found")
}
// check output
if i["status"].(float64) != 200 {
t.Errorf("Expecting status: %d got: %v", 200, i["status"])
}
wg.Done()
}))
defer log_s.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: server.URL,
RetryLimit: 0,
RetryInterval: 1,
ReadLimit: 1024,
Log: log_s.URL,
Expect: Expect{
Status: 200,
},
}
ez := &Epazote{
Services: s,
}
wg.Add(1)
ez.Supervice(s["s 1"])()
wg.Wait()
rc := s["s 1"].retryCount
if rc != 0 {
t.Errorf("Expecting retryCount = 0 got: %d", rc)
}
}
func TestSuperviceReadLimit(t *testing.T) {
buf.Reset()
var server *httptest.Server
var h http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "0123456789")
}
server = httptest.NewServer(h)
defer server.Close()
s := make(Services)
s["s 1"] = &Service{
Name: "s 1",
URL: server.URL,
ReadLimit: 5,
Expect: Expect{
Status: 200,
},
}
ez := &Epazote{
Services: s,
}
ez.debug = true
ez.Supervice(s["s 1"])()
rc := s["s 1"].retryCount
if rc != 0 {
t.Errorf("Expecting retryCount = 0 got: %d", rc)
}
data := buf.String()
re := regexp.MustCompile("(?m)[\r\n]+^01234$")
match := re.FindString(data)
if match == "" {
t.Error("Expecting: 01234")
}
}
|
package timewindow
import (
"log"
"testing"
"time"
)
// daeuihfuiseghfiusghui
func Test_timeWindow(t *testing.T) {
type args struct {
t time.Time
open time.Time
close time.Time
}
tests := []struct {
name string
args args
want bool
wantErr bool
}{
{
args: args{},
want: true,
name: "empty",
},
{
args: args{
t: time.Now(),
open: time.Now().Add(time.Minute * 5),
close: time.Now().Add(time.Minute * -5),
},
want: false,
name: "Window is closed and spans midnight",
},
{
args: args{
t: time.Now(),
open: time.Now().Add(time.Minute * -3),
close: time.Now().Add(time.Minute * -5),
},
want: true,
name: "Window is open and spans midnight",
},
{
args: args{
t: time.Now(),
open: time.Now().Add(time.Minute * -1),
close: time.Now().Add(time.Minute * 2),
},
want: true,
name: "Window is open",
},
{
args: args{
t: time.Now(),
open: time.Now(),
close: time.Now(),
},
want: true,
name: "Same Entries",
},
{
args: args{
t: time.Now(),
open: time.Now().Add(time.Minute * 1),
close: time.Now().Add(time.Minute * 3),
},
want: false,
name: "Window opens 1 minute from now",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
log.Println(tt.name, tt.args.t.Unix(), tt.args.open.Unix(), tt.args.close.Unix())
got := BetweenTimes(tt.args.t, tt.args.open, tt.args.close)
if got != tt.want {
t.Errorf("windowOpen = %v, want %v", got, tt.want)
}
})
}
}
|
package qwertycore
import (
"io/ioutil"
)
//
type Page struct {
Filename string
Title string
Body []byte
}
// LoadPage
func LoadPage(title string) (*Page, error) {
filename := a + "/views/" + title + ".html"
body, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return &Page{Filename: filename, Title: title, Body: body}, nil
}
|
package flandmark
import "errors"
var (
ErrBadArgument = errors.New("Invalid argument.")
ErrCouldNotLoad = errors.New("Could not load file.")
ErrDataSize = errors.New("Got unexpected data size.")
ErrDetect = errors.New("Failed to detect.")
ErrNormalize = errors.New("Failed to normalize.")
ErrUnknown = errors.New("Unknown error.")
)
|
package main
import "fmt"
type User struct {
login string
name string
surname string
birthYear int
}
func main() {
var name, surname, login string
var birthYear int
username := make(map[string]User)
loginCheck := make(map[string]bool)
for {
fmt.Println("Hello, enter the user data with space: name, surname, year of birth")
fmt.Scanf("%s %s %d", &name, &surname, &birthYear)
fmt.Println("Create login for User:")
for {
fmt.Scanf("%s", &login)
if loginCheck[login] {
fmt.Println("This login is registered already. Please, enter the new login:")
continue
} else {
loginCheck[login] = true
break
}
}
username[login] = User{login, surname, name, birthYear}
fmt.Printf("The User %s %s has been created\n", surname, name)
}
}
|
package main
import (
"ehsan_esmaeili/config"
"ehsan_esmaeili/database"
"ehsan_esmaeili/route"
"ehsan_esmaeili/usecase"
"fmt"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
func main() {
router := httprouter.New()
fmt.Println("Server Run On the : %s", config.Server_Url)
db, err := database.ConnectToSqlServerDB()
if err != nil {
fmt.Printf("eroro sql", err)
return
}
usecase.UsecaseInit(db)
route.RouterInit(router)
log.Fatal(http.ListenAndServe(":"+config.Server_Port, router))
}
|
package master
import (
"encoding/json"
"os"
"time"
)
type JsonSnapshotWriter struct {
outDir string
}
func NewJsonSnapshotWriter(outDir string) *JsonSnapshotWriter {
return &JsonSnapshotWriter{
outDir: outDir,
}
}
type JsonSnapshotCountersRow struct {
Time string
Counters map[string]int64
}
func (w *JsonSnapshotWriter) writeRow(filename string, data []byte) error {
f, err := os.OpenFile(w.outDir+"/"+filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer f.Close()
data = append(data, ',')
data = append(data, '\n')
f.Write(data)
return nil
}
func (w *JsonSnapshotWriter) WriteCounters(now time.Time, counters map[string]int64) error {
row := &JsonSnapshotCountersRow{
Time: time.Now().Format(time.RFC3339),
Counters: counters,
}
data, err := json.Marshal(row)
if err != nil {
return err
}
return w.writeRow("counters.txt", data)
}
type JsonSnapshotMetricsRow struct {
Time string
Metrics []agentMetrics
}
func (w *JsonSnapshotWriter) WriteMetrics(now time.Time, metrics []agentMetrics) error {
row := &JsonSnapshotMetricsRow{
Time: time.Now().Format(time.RFC3339),
Metrics: metrics,
}
data, err := json.Marshal(row)
if err != nil {
return err
}
return w.writeRow("metrics.txt", data)
}
|
package router
import (
"github.com/gin-gonic/gin"
"hd-mall-ed/packages/admin/controller/productCategoryController"
)
func productCategoryRouter(router *gin.RouterGroup) {
category := router.Group("/product_category")
{
category.GET("/list", productCategoryController.GetList)
}
}
|
package entity
type Errors struct {
Errors []err `json:"errors"`
}
//Error ошибка
type err struct {
Error string `json:"error"` // Заголовок ошибки
Parameter string `json:"parameter"` // Параметр, на котором произошла ошибка
Code int `json:"code"` // Код ошибки
ErrorMessage string `json:"errorMessage"` // Сообщение, прилагаемое к ошибке
}
|
package People
// 获取人的信息
type PeopleGetter interface {
// 获取名字
GetName() string
// 获取年龄
GetAge() string
}
|
// Copyright 2015 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package resolver
import (
"net"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/errors"
)
// socketResolver represents the different types of socket-based
// address resolvers.
type socketResolver struct {
typ string
addr string
}
// Type returns the resolver type.
func (sr *socketResolver) Type() string { return sr.typ }
// Addr returns the resolver address.
func (sr *socketResolver) Addr() string { return sr.addr }
// GetAddress returns a net.Addr or error.
func (sr *socketResolver) GetAddress() (net.Addr, error) {
switch sr.typ {
case "tcp":
_, err := net.ResolveTCPAddr("tcp", sr.addr)
if err != nil {
return nil, err
}
return util.NewUnresolvedAddr("tcp", sr.addr), nil
}
return nil, errors.Errorf("unknown address type: %q", sr.typ)
}
|
package leetcode
func twoSum1(numbers []int, target int) []int {
i, j := 0, len(numbers)-1
sums := numbers[i] + numbers[j]
for sums != target {
if sums > target {
j--
} else if sums < target {
i++
}
sums = numbers[i] + numbers[j]
}
return []int{i + 1, j + 1}
}
|
package main
import (
"fmt"
)
type myInt int
func (i myInt) init() {
fmt.Println("Init!")
i = 1
}
func main() {
var inter myInt
fmt.Println(inter)
}
|
package test
import (
"fmt"
"io/ioutil"
"testing"
"github.com/blang/semver"
"gopkg.in/yaml.v2"
"github.com/mesosphere/kubeaddons/hack/temp"
"github.com/mesosphere/kubeaddons/pkg/api/v1beta1"
"github.com/mesosphere/kubeaddons/pkg/test"
"github.com/mesosphere/kubeaddons/pkg/test/cluster/kind"
)
const defaultKubernetesVersion = "1.15.6"
var addonTestingGroups = make(map[string][]string)
func init() {
b, err := ioutil.ReadFile("groups.yaml")
if err != nil {
panic(err)
}
if err := yaml.Unmarshal(b, addonTestingGroups); err != nil {
panic(err)
}
}
func TestValidateUnhandledAddons(t *testing.T) {
unhandled, err := findUnhandled()
if err != nil {
t.Fatal(err)
}
if len(unhandled) != 0 {
names := make([]string, len(unhandled))
for _, addon := range unhandled {
names = append(names, addon.GetName())
}
t.Fatal(fmt.Errorf("the following addons are not handled as part of a testing group: %+v", names))
}
}
func TestGeneralGroup(t *testing.T) {
if err := testgroup(t, "general"); err != nil {
t.Fatal(err)
}
}
func TestElasticSearchGroup(t *testing.T) {
if err := testgroup(t, "elasticsearch"); err != nil {
t.Fatal(err)
}
}
func TestPrometheusGroup(t *testing.T) {
if err := testgroup(t, "prometheus"); err != nil {
t.Fatal(err)
}
}
// -----------------------------------------------------------------------------
// Private Functions
// -----------------------------------------------------------------------------
func testgroup(t *testing.T, groupname string) error {
t.Logf("testing group %s", groupname)
cluster, err := kind.NewCluster(semver.MustParse(defaultKubernetesVersion))
if err != nil {
return err
}
defer cluster.Cleanup()
if err := temp.DeployController(cluster); err != nil {
return err
}
addons, err := addons(addonTestingGroups[groupname]...)
if err != nil {
return err
}
ph, err := test.NewBasicTestHarness(t, cluster, addons...)
if err != nil {
return err
}
defer ph.Cleanup()
ph.Validate()
ph.Deploy()
return nil
}
func addons(names ...string) ([]v1beta1.AddonInterface, error) {
var testAddons []v1beta1.AddonInterface
addons, err := temp.Addons("../addons/")
if err != nil {
return testAddons, err
}
for _, addon := range addons {
for _, name := range names {
if addon[0].GetName() == name {
testAddons = append(testAddons, addon[0])
}
}
}
if len(testAddons) != len(names) {
return testAddons, fmt.Errorf("got %d addons, expected %d", len(testAddons), len(names))
}
return testAddons, nil
}
func findUnhandled() ([]v1beta1.AddonInterface, error) {
var unhandled []v1beta1.AddonInterface
addons, err := temp.Addons("../addons/")
if err != nil {
return unhandled, err
}
for _, revisions := range addons {
addon := revisions[0]
found := false
for _, v := range addonTestingGroups {
for _, name := range v {
if name == addon.GetName() {
found = true
}
}
}
if !found {
unhandled = append(unhandled, addon)
}
}
return unhandled, nil
}
|
package console
import (
"oh-my-posh/color"
"oh-my-posh/mock"
"oh-my-posh/platform"
"testing"
"github.com/stretchr/testify/assert"
)
func TestGetTitle(t *testing.T) {
cases := []struct {
Template string
Root bool
User string
Cwd string
PathSeparator string
ShellName string
Expected string
}{
{
Template: "{{.Env.USERDOMAIN}} :: {{.PWD}}{{if .Root}} :: Admin{{end}} :: {{.Shell}}",
Cwd: "C:\\vagrant",
PathSeparator: "\\",
ShellName: "PowerShell",
Root: true,
Expected: "\x1b]0;MyCompany :: C:\\vagrant :: Admin :: PowerShell\a",
},
{
Template: "{{.Folder}}{{if .Root}} :: Admin{{end}} :: {{.Shell}}",
Cwd: "C:\\vagrant",
PathSeparator: "\\",
ShellName: "PowerShell",
Expected: "\x1b]0;vagrant :: PowerShell\a",
},
{
Template: "{{.UserName}}@{{.HostName}}{{if .Root}} :: Admin{{end}} :: {{.Shell}}",
Root: true,
User: "MyUser",
PathSeparator: "\\",
ShellName: "PowerShell",
Expected: "\x1b]0;MyUser@MyHost :: Admin :: PowerShell\a",
},
}
for _, tc := range cases {
env := new(mock.MockedEnvironment)
env.On("Pwd").Return(tc.Cwd)
env.On("Home").Return("/usr/home")
env.On("PathSeparator").Return(tc.PathSeparator)
env.On("TemplateCache").Return(&platform.TemplateCache{
Env: map[string]string{
"USERDOMAIN": "MyCompany",
},
Shell: tc.ShellName,
UserName: "MyUser",
Root: tc.Root,
HostName: "MyHost",
PWD: tc.Cwd,
Folder: "vagrant",
})
ansi := &color.Ansi{}
ansi.InitPlain()
ct := &Title{
Env: env,
Ansi: ansi,
Template: tc.Template,
}
got := ct.GetTitle()
assert.Equal(t, tc.Expected, got)
}
}
func TestGetConsoleTitleIfGethostnameReturnsError(t *testing.T) {
cases := []struct {
Template string
Root bool
User string
Cwd string
PathSeparator string
ShellName string
Expected string
}{
{
Template: "Not using Host only {{.UserName}} and {{.Shell}}",
User: "MyUser",
PathSeparator: "\\",
ShellName: "PowerShell",
Expected: "\x1b]0;Not using Host only MyUser and PowerShell\a",
},
{
Template: "{{.UserName}}@{{.HostName}} :: {{.Shell}}",
User: "MyUser",
PathSeparator: "\\",
ShellName: "PowerShell",
Expected: "\x1b]0;MyUser@ :: PowerShell\a",
},
{
Template: "\x1b[93m[\x1b[39m\x1b[96mconsole-title\x1b[39m\x1b[96m ≡\x1b[39m\x1b[31m +0\x1b[39m\x1b[31m ~1\x1b[39m\x1b[31m -0\x1b[39m\x1b[31m !\x1b[39m\x1b[93m]\x1b[39m",
Expected: "\x1b]0;[console-title ≡ +0 ~1 -0 !]\a",
},
}
for _, tc := range cases {
env := new(mock.MockedEnvironment)
env.On("Pwd").Return(tc.Cwd)
env.On("Home").Return("/usr/home")
env.On("TemplateCache").Return(&platform.TemplateCache{
Env: map[string]string{
"USERDOMAIN": "MyCompany",
},
Shell: tc.ShellName,
UserName: "MyUser",
Root: tc.Root,
HostName: "",
})
ansi := &color.Ansi{}
ansi.InitPlain()
ct := &Title{
Env: env,
Ansi: ansi,
Template: tc.Template,
}
got := ct.GetTitle()
assert.Equal(t, tc.Expected, got)
}
}
|
// Copyright 2018 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package network
import (
"bufio"
"context"
"os"
"strings"
"golang.org/x/sys/unix"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: SupportedProtocols,
Desc: "Checks that required network protocols are supported by the kernel",
Contacts: []string{
"cros-networking@google.com",
"hugobenichi@google.com",
"chromeos-kernel-test@google.com",
},
Attr: []string{"group:mainline"},
})
}
func SupportedProtocols(ctx context.Context, s *testing.State) {
required := make(map[string]struct{}) // protocols required to be in /proc/net/protocols
// Create sockets to try to ensure that the proper kernel modules are
// loaded in order for the required protocols to be listed in /proc.
for _, info := range []struct {
name string // value from "protocol" field in /proc/net/protocols
domain, typ, protocol int // socket info to load kernel module
}{
{"RFCOMM", unix.AF_BLUETOOTH, unix.SOCK_STREAM, unix.BTPROTO_RFCOMM},
{"RFCOMM", unix.AF_BLUETOOTH, unix.SOCK_SEQPACKET, unix.BTPROTO_SCO},
{"L2CAP", unix.AF_BLUETOOTH, unix.SOCK_STREAM, unix.BTPROTO_L2CAP},
{"HCI", unix.AF_BLUETOOTH, unix.SOCK_RAW, unix.BTPROTO_HCI},
{"PACKET", unix.AF_PACKET, unix.SOCK_DGRAM, 0},
{"RAWv6", unix.AF_INET6, unix.SOCK_RAW, 0},
{"UDPLITEv6", unix.AF_INET6, unix.SOCK_DGRAM, unix.IPPROTO_UDPLITE},
{"UDPv6", unix.AF_INET6, unix.SOCK_DGRAM, 0},
{"TCPv6", unix.AF_INET6, unix.SOCK_STREAM, 0},
{"UNIX", unix.AF_UNIX, unix.SOCK_STREAM, 0},
{"UDP-Lite", unix.AF_INET, unix.SOCK_DGRAM, unix.IPPROTO_UDPLITE},
{"PING", unix.AF_INET, unix.SOCK_DGRAM, unix.IPPROTO_ICMP},
{"RAW", unix.AF_INET, unix.SOCK_RAW, 0},
{"UDP", unix.AF_INET, unix.SOCK_DGRAM, 0},
{"TCP", unix.AF_INET, unix.SOCK_STREAM, 0},
{"NETLINK", unix.AF_NETLINK, unix.SOCK_DGRAM, 0},
} {
required[info.name] = struct{}{}
// Log but discard errors; we're just doing this to load modules.
if fd, err := unix.Socket(info.domain, info.typ, info.protocol); err != nil {
s.Logf("Couldn't create socket (%v, %v, %v) for %v: %v",
info.domain, info.typ, info.protocol, info.name, err)
} else if err := unix.Close(fd); err != nil {
s.Errorf("Failed to close socket (%v, %v, %v) for %v: %v",
info.domain, info.typ, info.protocol, info.name, err)
}
}
// Now read the kernel's protocol stats and verify that all of the expected
// protocols are listed.
const path = "/proc/net/protocols"
f, err := os.Open(path)
if err != nil {
s.Fatal("Failed to open protocols: ", err)
}
defer f.Close()
loaded := make(map[string]struct{})
sc := bufio.NewScanner(f)
for sc.Scan() {
parts := strings.Fields(sc.Text())
if len(parts) < 1 || parts[0] == "protocol" { // skip last line and header
continue
}
loaded[parts[0]] = struct{}{}
}
if sc.Err() != nil {
s.Fatal("Failed to read protocols: ", err)
}
for name := range required {
if _, ok := loaded[name]; !ok {
s.Errorf("%v protocol missing in %v", name, path)
}
}
}
|
package main
import (
"context"
"crypto/tls"
"flag"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/joho/godotenv"
"google.golang.org/grpc"
"log"
"net/http"
"os"
"snippetBox-microservice/catalog/api/grpc/protobuffs"
"snippetBox-microservice/catalog/internal/controller"
"snippetBox-microservice/catalog/internal/repository"
"snippetBox-microservice/catalog/utils/helpers"
"time"
)
type application struct {
errorLog *log.Logger
infoLog *log.Logger
catalogController controller.ICatalogController
}
func init() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
}
func main() {
addr := flag.String("addr", ":4012", "HTTP network address")
dsn := flag.String("dsn",
os.Getenv("db_url"),
"PostgreSQL data source name")
infoLog := log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime)
errorLog := log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime)
dbPool, err := pgxpool.Connect(context.Background(), *dsn)
if err != nil {
errorLog.Fatal(err)
}
defer dbPool.Close()
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
if err != nil {
log.Fatalf("could not connect: %v", err)
}
defer conn.Close()
grpcClient := protobuffs.NewNewsServiceClient(conn)
newsRepository := repository.NewCatalogRepository(dbPool)
helper := helpers.New(errorLog)
newsHandler := controller.New(newsRepository, helper, grpcClient)
app := &application{
errorLog: errorLog,
infoLog: infoLog,
catalogController: newsHandler,
}
tlsConfig := &tls.Config{
PreferServerCipherSuites: true,
CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256},
}
srv := &http.Server{
Addr: *addr,
ErrorLog: errorLog,
Handler: app.routes(),
TLSConfig: tlsConfig,
IdleTimeout: time.Minute,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
infoLog.Printf("Starting grpc-server on %v", *addr)
err = srv.ListenAndServeTLS("./crypto/tls/cert.pem", "./crypto/tls/key.pem")
errorLog.Fatal(err)
}
|
// Package writer create SSA/ASS Subtitle Script
package writer
import (
"bytes"
"fmt"
"os"
"strings"
"github.com/Alquimista/eyecandy/asstime"
"github.com/Alquimista/eyecandy/color"
"github.com/Alquimista/eyecandy/utils"
)
// silence?, noise?
const dummyVideoTemplate string = "?dummy:%.6f:%d:%d:%d:%d:%d:%d%s:"
const dummyAudioTemplate string = "dummy-audio:silence?sr=44100&bd=16&" +
"ch=1&ln=396900000:" // silence?, noise? TODO: dummy audio function
const styleFormat string = "Format: Name, Fontname, Fontsize, " +
"PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, " +
"Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, " +
"BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, " +
"Encoding"
const styleTemplate string = "Style: %s,%s,%d,%s,%s,%s,%s,%s,%s,%s,%s,%.4f," +
"%.4f,%.1f,%d,%d,%.4f,%.4f,%d,%04d,%04d,%04d,1"
const dialogFormat string = "Format: Layer, Start, End, Style, Name, " +
"MarginL, MarginR, MarginV, Effect, Text"
const dialogTemplate string = "%s: %d,%s,%s,%s,%s,0000,0000,0000,%s,%s"
const scriptTemplate string = `[Script Info]
; %s
Title: %s
Original Script: %s
Translation: %s
Timing: %s
ScriptType: v4.00+
PlayResX: %d
PlayResY: %d
WrapStyle: 2
ScaledBorderAndShadow: yes
YCbCr Matrix: TV.601
[Aegisub Project Garbage]
Video File: %s
Video AR Mode: 4
Video AR Value: %.6f
Video Zoom Percent: %.6f
Video Position: %d
Audio File: %s
Active Line: 1
[V4+ Styles]
%s
%s
[Events]
%s
%s`
const (
// AlignBottomLeft Bottom Left SSA numbered Alignment
AlignBottomLeft int = 1 + iota
// AlignBottomCenter Bottom Center SSA numbered Alignment
AlignBottomCenter
// AlignBottomRight Bottom Right SSA numbered Alignment
AlignBottomRight
// AlignMiddleLeft Middle Left SSA numbered Alignment
AlignMiddleLeft
// AlignMiddleCenter Middle Center SSA numbered Alignment
AlignMiddleCenter
// AlignMiddleRight Middle Right SSA numbered Alignment
AlignMiddleRight
// AlignTopLeft Top Left SSA numbered Alignment
AlignTopLeft
// AlignTopCenter Top Left SSA numbered Alignment
AlignTopCenter
// AlignTopRight Top Right SSA numbered Alignment
AlignTopRight
)
// DummyVideo blank video file.
func DummyVideo(framerate float64, w, h int, hexc string, cb bool, timeS int) string {
c := color.NewFromHTML(hexc)
checkboard := ""
if cb {
checkboard = "c"
}
frames := asstime.MStoFrames(timeS*asstime.Second, framerate)
return fmt.Sprintf(
dummyVideoTemplate,
utils.Round(framerate, 3), frames, w, h, c.R, c.G, c.B, checkboard)
}
// Style represent subtitle"s styles.
type Style struct {
Name string
FontName string
FontSize int
Color [4]*color.Color //Primary, Secondary, Bord, Shadow
Bold bool
Italic bool
Underline bool
StrikeOut bool
Scale [2]float64 // WIDTH, HEIGHT map[string]string
Spacing float64
Angle int
OpaqueBox bool
Bord float64
Shadow float64
Alignment int
Margin [3]int // L, R, V map[string]string
Encoding int
}
// String get the generated style as a String
func (sty *Style) String() string {
return fmt.Sprintf(styleTemplate,
sty.Name,
sty.FontName, sty.FontSize,
sty.Color[0].SSAL(),
sty.Color[1].SSAL(),
sty.Color[2].SSAL(),
sty.Color[3].SSAL(),
utils.Bool2str(sty.Bold), utils.Bool2str(sty.Italic),
utils.Bool2str(sty.Underline), utils.Bool2str(sty.StrikeOut),
sty.Scale[0], sty.Scale[1],
sty.Spacing,
sty.Angle,
utils.Bool2Obox(sty.OpaqueBox),
sty.Bord, sty.Shadow,
sty.Alignment,
sty.Margin[0], sty.Margin[1], sty.Margin[2],
)
}
// NewStyle create a new Style Struct with defaults
func NewStyle(name string) *Style {
return &Style{
Name: name,
FontName: "Arial",
FontSize: 35,
Color: [4]*color.Color{
color.NewFromHEX(0xFFFFFF), //Primary
color.NewFromHEX(0x0000FF), //Secondary
color.NewFromHEX(0x000000), //Bord
color.NewFromHEX(0x000000), //Shadow
},
Scale: [2]float64{100, 100},
Bord: 2,
Alignment: AlignBottomCenter,
Margin: [3]int{10, 20, 10},
}
}
// Dialog Represent the subtitle"s lines.
type Dialog struct {
Layer int
Start string
End string
StyleName string
Actor string
Effect string
Text string
Tags string
Comment bool
}
// String get the generated Dialog as a String
func (d *Dialog) String() string {
text := d.Text
key := "Dialogue"
if d.Comment {
key = "Comment"
}
if d.Tags != "" {
text = "{" + d.Tags + "}" + d.Text
}
return fmt.Sprintf(dialogTemplate,
key,
d.Layer,
d.Start, d.End,
d.StyleName, d.Actor,
d.Effect,
text)
}
// NewDialog create a new Dialog Struct with defaults
func NewDialog(text string) *Dialog {
return &Dialog{
StyleName: "Default",
Start: "0:00:00.00", End: "0:00:05.00",
Text: text}
}
// Script SSA/ASS Subtitle Script.
type Script struct {
Dialog []*Dialog
Style map[string]*Style
Comment string
Resolution [2]int // WIDTH, HEIGHT map[string]string
VideoPath string
VideoZoom float64
VideoPosition int
VideoAR float64
MetaFilename string
MetaTitle string
MetaOriginalScript string
MetaTranslation string
MetaTiming string
Audio string
}
// GetStyle get the Style matching the argument name if exist
// else return the Default Style
func (s *Script) GetStyle(name string) *Style {
style, ok := s.Style[name]
if !ok {
style = s.Style["Default"]
style.Name = name
}
return style
}
// StyleExists get if a Style exists matching the argument name
func (s *Script) StyleExists(name string) bool {
_, ok := s.Style[name]
return ok
}
// AddStyle add a Style to SSA/ASS Script.
func (s *Script) AddStyle(sty *Style) {
if !s.StyleExists(sty.Name) {
s.Style[sty.Name] = sty
}
}
// AddDialog add a Dialog to SSA/ASS Script.
func (s *Script) AddDialog(d *Dialog) {
if d.Text != "" {
s.Dialog = append(s.Dialog, d)
}
}
// String get the generated SSA/ASS Script as a String
func (s *Script) String() string {
// Add default dialog and style
s.AddStyle(NewStyle("Default"))
if len(s.Dialog) == 0 {
s.AddDialog(NewDialog("EyecandyFX"))
}
if s.Resolution[0] == 0 || s.Resolution[1] == 0 {
s.Resolution = [2]int{1280, 720}
}
if s.MetaOriginalScript == "" {
s.MetaOriginalScript = s.MetaFilename
}
if s.VideoAR == 0 {
s.VideoAR = float64(s.Resolution[0]) / float64(s.Resolution[1])
}
if s.VideoPath == "" {
s.VideoPath = DummyVideo(
asstime.FpsNtscFilm,
s.Resolution[0], s.Resolution[1],
"#000",
false,
600)
}
if s.VideoPath != "" {
if strings.HasPrefix(s.VideoPath, "?dummy") {
s.Audio = dummyAudioTemplate
} else {
s.Audio = s.VideoPath
}
}
var dialogStyleNames []string
var styles bytes.Buffer
var dialogs bytes.Buffer
for _, d := range s.Dialog {
if !d.Comment {
dialogStyleNames = utils.AppendStrUnique(
dialogStyleNames, d.StyleName)
}
dialogs.WriteString(d.String() + "\n")
}
// Write only used styles in dialogs
// If doesn't exist create it
for _, sname := range dialogStyleNames {
_, ok := s.Style[sname]
i := 0
for _, sty := range s.Style {
if !ok {
sty = s.Style["Default"]
sty.Name = sname
i++
} else {
i = 1
}
if sty.Name == sname && i == 1 {
styles.WriteString(sty.String() + "\n")
}
}
}
return fmt.Sprintf(scriptTemplate,
s.Comment,
s.MetaTitle, s.MetaOriginalScript,
s.MetaTranslation, s.MetaTiming,
s.Resolution[0], s.Resolution[1],
s.VideoPath, s.VideoAR, s.VideoZoom, s.VideoPosition,
s.Audio,
styleFormat, styles.String(),
dialogFormat, dialogs.String())
}
// Save write an SSA/ASS Subtitle Script.
func (s *Script) Save(fn string) {
BOM := "\uFEFF"
f, err := os.Create(fn)
if err != nil {
panic(fmt.Errorf("writer: failed saving subtitle file: %s", err))
}
defer f.Close()
s.MetaFilename = fn
n, err := f.WriteString(BOM + s.String())
if err != nil {
fmt.Println(n, err)
}
// save changes
// err =
f.Sync()
}
// NewScript create a new Script Struct with defaults
func NewScript() *Script {
return &Script{
Comment: "Script generated by Eyecandy",
MetaTitle: "Default Eyecandy file",
VideoZoom: 0.75,
Style: map[string]*Style{},
}
}
|
package http
type ErrorsResponse struct {
Errors string `json:"errors"`
}
|
// Package grpc provides a gRPC client for the Listings service.
package grpc
import (
"github.com/pkg/errors"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"github.com/go-kit/kit/endpoint"
grpctransport "github.com/go-kit/kit/transport/grpc"
// This Service
pb "github.com/im-auld/gopherup/listings-service"
svc "github.com/im-auld/gopherup/listings-service/generated"
)
// New returns an service backed by a gRPC client connection. It is the
// responsibility of the caller to dial, and later close, the connection.
func New(conn *grpc.ClientConn, options ...ClientOption) (pb.ListingsServer, error) {
var cc clientConfig
for _, f := range options {
err := f(&cc)
if err != nil {
return nil, errors.Wrap(err, "cannot apply option")
}
}
clientOptions := []grpctransport.ClientOption{
grpctransport.ClientBefore(
contextValuesToGRPCMetadata(cc.headers)),
}
var postitemEndpoint endpoint.Endpoint
{
postitemEndpoint = grpctransport.NewClient(
conn,
"gopherup.Listings",
"PostItem",
svc.EncodeGRPCPostItemRequest,
svc.DecodeGRPCPostItemResponse,
pb.ItemResponse{},
clientOptions...,
).Endpoint()
}
var getitemsEndpoint endpoint.Endpoint
{
getitemsEndpoint = grpctransport.NewClient(
conn,
"gopherup.Listings",
"GetItems",
svc.EncodeGRPCGetItemsRequest,
svc.DecodeGRPCGetItemsResponse,
pb.ItemsCollectionResponse{},
clientOptions...,
).Endpoint()
}
var edititemEndpoint endpoint.Endpoint
{
edititemEndpoint = grpctransport.NewClient(
conn,
"gopherup.Listings",
"EditItem",
svc.EncodeGRPCEditItemRequest,
svc.DecodeGRPCEditItemResponse,
pb.ItemResponse{},
clientOptions...,
).Endpoint()
}
var getitemEndpoint endpoint.Endpoint
{
getitemEndpoint = grpctransport.NewClient(
conn,
"gopherup.Listings",
"GetItem",
svc.EncodeGRPCGetItemRequest,
svc.DecodeGRPCGetItemResponse,
pb.ItemResponse{},
clientOptions...,
).Endpoint()
}
var markitemsoldEndpoint endpoint.Endpoint
{
markitemsoldEndpoint = grpctransport.NewClient(
conn,
"gopherup.Listings",
"MarkItemSold",
svc.EncodeGRPCMarkItemSoldRequest,
svc.DecodeGRPCMarkItemSoldResponse,
pb.ItemResponse{},
clientOptions...,
).Endpoint()
}
var archiveitemEndpoint endpoint.Endpoint
{
archiveitemEndpoint = grpctransport.NewClient(
conn,
"gopherup.Listings",
"ArchiveItem",
svc.EncodeGRPCArchiveItemRequest,
svc.DecodeGRPCArchiveItemResponse,
pb.ItemResponse{},
clientOptions...,
).Endpoint()
}
return svc.Endpoints{
PostItemEndpoint: postitemEndpoint,
GetItemsEndpoint: getitemsEndpoint,
EditItemEndpoint: edititemEndpoint,
GetItemEndpoint: getitemEndpoint,
MarkItemSoldEndpoint: markitemsoldEndpoint,
ArchiveItemEndpoint: archiveitemEndpoint,
}, nil
}
type clientConfig struct {
headers []string
}
// ClientOption is a function that modifies the client config
type ClientOption func(*clientConfig) error
func CtxValuesToSend(keys ...string) ClientOption {
return func(o *clientConfig) error {
o.headers = keys
return nil
}
}
func contextValuesToGRPCMetadata(keys []string) grpctransport.RequestFunc {
return func(ctx context.Context, md *metadata.MD) context.Context {
var pairs []string
for _, k := range keys {
if v, ok := ctx.Value(k).(string); ok {
pairs = append(pairs, k, v)
}
}
if pairs != nil {
*md = metadata.Join(*md, metadata.Pairs(pairs...))
}
return ctx
}
}
|
package apilifecycle
import godd "github.com/pagongamedev/go-dd"
// MappingStandardError Type
type MappingStandardError = func(goddErr *godd.Error) (codeOut int, responseError interface{}, goddErrOut *godd.Error)
// MappingStandardError Set
func (api *APILifeCycle) MappingStandardError(handler MappingStandardError) {
api.mappingStandardError = handler
}
// GetMappingStandardError Get
func (api *APILifeCycle) GetMappingStandardError() MappingStandardError {
return api.mappingStandardError
}
// Handler Default
func handlerDefaultMappingStandardError() MappingStandardError {
return func(goddErr *godd.Error) (codeOut int, responseError interface{}, goddErrOut *godd.Error) {
// response, goddErr := MappingStandard(code, responseRaw, responsePagination)
return 400, responseError, goddErr
}
}
|
package stack_test
import (
"learning_golang/stack"
"testing"
)
func TestStack(t *testing.T) {
count := 1
var aStack stack.Stack
assertTrue(t,aStack.Len()==0,"expected empty Stack",count)
}
// assertTrue() calls testing.T.Error() with the given message if the
// condition is false.
func assertTrue(t *testing.T, condition bool, message string, id int) {
if !condition {
t.Errorf("#%d: %s", id, message)
}
} |
package usecase_test
import (
"testing"
"github.com/go-playground/validator"
"github.com/pkg/errors"
"github.com/utahta/momoclo-channel/dao"
"github.com/utahta/momoclo-channel/entity"
"github.com/utahta/momoclo-channel/event/eventtest"
"github.com/utahta/momoclo-channel/linenotify"
"github.com/utahta/momoclo-channel/log"
"github.com/utahta/momoclo-channel/testutil"
"github.com/utahta/momoclo-channel/usecase"
"google.golang.org/appengine/aetest"
)
func TestLineNotify_Do(t *testing.T) {
ctx, done, err := testutil.NewContext(&aetest.Options{StronglyConsistentDatastore: true})
if err != nil {
t.Fatal(err)
}
defer done()
taskQueue := eventtest.NewTaskQueue()
repo := entity.NewLineNotificationRepository(dao.NewDatastoreHandler())
u := usecase.NewLineNotify(log.NewAELogger(), taskQueue, linenotify.NewNop(), repo)
validationTests := []struct {
params usecase.LineNotifyParams
}{
{usecase.LineNotifyParams{Request: linenotify.Request{ID: "id-1"}}},
{usecase.LineNotifyParams{Request: linenotify.Request{AccessToken: "token"}}},
{usecase.LineNotifyParams{Request: linenotify.Request{
ID: "id-2", AccessToken: "token",
}}},
{usecase.LineNotifyParams{Request: linenotify.Request{
ID: "id-3", AccessToken: "token", Messages: []linenotify.Message{
{Text: ""},
},
}}},
{usecase.LineNotifyParams{Request: linenotify.Request{
ID: "id-4", AccessToken: "token", Messages: []linenotify.Message{
{Text: "hello", ImageURL: "unknown"},
},
}}},
}
for _, test := range validationTests {
err = u.Do(ctx, test.params)
if errs, ok := errors.Cause(err).(validator.ValidationErrors); !ok {
t.Errorf("Expected validation error, got %v. params:%v", errs, test.params)
}
}
err = u.Do(ctx, usecase.LineNotifyParams{Request: linenotify.Request{
ID: "id-1", AccessToken: "token", Messages: []linenotify.Message{
{Text: "hello"},
{Text: " ", ImageURL: "http://localhost/a"},
},
}})
if err != nil {
t.Fatal(err)
}
if len(taskQueue.Tasks) != 1 {
t.Errorf("Expected taskqueue length 1, got %v", len(taskQueue.Tasks))
}
}
|
package db
import (
"context"
"fmt"
"log"
"strings"
"cloud.google.com/go/firestore"
"google.golang.org/api/iterator"
)
type Tag struct {
Name string `json:"name"`
Values map[string]int64 `json:"values"`
}
func (db *FirestoreDB) CreateTag(ctx context.Context, squadId string, tag *Tag) (err error) {
if db.dev {
log.Printf("Creating tag '%+v' in squad '%v'", tag, squadId)
}
_, err = db.Squads.Doc(squadId).Collection("tags").Doc(tag.Name).Set(ctx, tag.Values)
return err
}
func (db *FirestoreDB) GetTags(ctx context.Context, squadId string) (tags []*Tag, err error) {
log.Printf("Getting tags for squad '%v'", squadId)
tags = make([]*Tag, 0)
iter := db.Squads.Doc(squadId).Collection("tags").Documents(ctx)
defer iter.Stop()
for {
doc, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, fmt.Errorf("Failed to get squad tags: %w", err)
}
values := make(map[string]int64)
values_ := doc.Data()
for k, v := range values_ {
values[k] = v.(int64)
}
tag := &Tag{
Name: doc.Ref.ID,
Values: values,
}
tags = append(tags, tag)
}
return tags, nil
}
func (db *FirestoreDB) DeleteTag(ctx context.Context, squadId string, tagName string) error {
log.Println("Deleting tag " + tagName + " from squad " + squadId)
docSquad := db.Squads.Doc(squadId)
docTag := docSquad.Collection("tags").Doc(tagName)
//TODO delete tag from all members
//delete squad itself
err := db.deleteDocRecurse(ctx, docTag)
if err != nil {
return fmt.Errorf("Error while deleting tag "+tagName+" from squad "+squadId+": %w", err)
}
return nil
}
func (db *FirestoreDB) GetSquadMemberTags(ctx context.Context, userId string, squadId string) ([]interface{}, error) {
doc, err := db.Squads.Doc(squadId).Collection("members").Doc(userId).Get(ctx)
if err != nil {
return nil, fmt.Errorf("Failed to get squad "+squadId+" member "+userId+": %w", err)
}
tags, ok := doc.Data()["Tags"]
if ok && tags != nil {
return tags.([]interface{}), nil
} else {
return nil, nil
}
}
func (db *FirestoreDB) SetSquadMemberTag(ctx context.Context, userId string, squadId string, tagName string, tagValue string) ([]interface{}, error) {
tagNew := tagName
if tagValue != "" {
tagNew = tagName + "/" + tagValue
}
if db.dev {
log.Println("Setting tag " + tagName + " to user " + userId + " from squad " + squadId)
}
tags, err := db.GetSquadMemberTags(ctx, userId, squadId)
if err != nil {
return nil, err
}
if len(tags) >= 10 {
return nil, fmt.Errorf("User might have max 10 tags assigned")
}
tagFound := false
tagOldValue := ""
for i, tag := range tags {
s := strings.Split(tag.(string), "/")
name := s[0]
if name == tagName {
tagFound = true
if len(s) == 2 {
tagOldValue = s[1]
tags[i] = tagNew
}
break
}
}
if !tagFound {
tags = append(tags, tagNew)
}
if !tagFound || tagOldValue != tagValue {
batch := db.Client.Batch()
db.SetSquadMemberTags(batch, userId, squadId, &tags)
db.SetUserTags(batch, userId, squadId, &tags)
db.UpdateTagCounter(batch, squadId, tagName, tagValue, 1)
if tagFound {
db.UpdateTagCounter(batch, squadId, tagName, tagOldValue, -1)
}
_, err := batch.Commit(ctx)
if err != nil {
fmt.Errorf("Failed to update tags for user %v from squad %v to %+v: %w", userId, squadId, tags, err)
return nil, err
}
}
return tags, nil
}
func (db *FirestoreDB) DeleteSquadMemberTag(ctx context.Context, userId string, squadId string, tagName string, tagValue string) ([]interface{}, error) {
tag := tagName
if tagValue != "" {
tag = tag + "/" + tagValue
}
log.Println("Deleting tag " + tag + " from user " + userId + " from squad " + squadId)
tags, err := db.GetSquadMemberTags(ctx, userId, squadId)
if err != nil {
return nil, err
}
tagFound := false
for i, t := range tags {
if t == tag {
tagFound = true
if i == len(tags)-1 {
tags = tags[:i]
} else if i > 0 {
tags = append(tags[:i], tags[i+1:]...)
} else {
tags = tags[1:]
}
break
}
}
batch := db.Client.Batch()
db.SetSquadMemberTags(batch, userId, squadId, &tags)
if tagFound {
db.UpdateTagCounter(batch, squadId, tagName, tagValue, -1)
}
_, err = batch.Commit(ctx)
if err != nil {
fmt.Errorf("Failed to update tags for user %v from squad %v to %+v: %w", userId, squadId, tags, err)
return nil, err
}
return tags, nil
}
func (db *FirestoreDB) SetSquadMemberTags(batch *firestore.WriteBatch, userId string, squadId string, tags *[]interface{}) {
batch.Update(db.Squads.Doc(squadId).Collection("members").Doc(userId), []firestore.Update{
{Path: "Tags", Value: tags},
})
}
func (db *FirestoreDB) SetUserTags(batch *firestore.WriteBatch, userId string, squadId string, tags *[]interface{}) {
squadTags := make([]string, len(*tags))
for i, v := range *tags {
squadTags[i] = squadId + "/" + v.(string)
}
docUser := db.Users.Doc(userId)
batch.Update(docUser, []firestore.Update{
{Path: "UserTags", Value: squadTags},
})
db.userDataCache.Delete(userId)
}
func (db *FirestoreDB) UpdateTagCounter(batch *firestore.WriteBatch, squadId string, tag string, value string, inc int) {
if value == "" {
value = "_"
}
batch.Update(db.Squads.Doc(squadId).Collection("tags").Doc(tag), []firestore.Update{
{Path: value, Value: firestore.Increment(inc)},
})
}
|
/*
Copyright 2021 The Skaffold Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"context"
"io"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/inspect"
modules "github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/inspect/modules"
)
var modulesFlags = struct {
includeAll bool
}{}
func cmdModules() *cobra.Command {
return NewCmd("modules").
WithDescription("Interact with configuration modules").
WithCommands(cmdModulesList())
}
func cmdModulesList() *cobra.Command {
return NewCmd("list").
WithExample("Get list of modules", "inspect modules list --format json").
WithExample("Get list of all configs (including unnamed modules)", "inspect modules list -a --format json").
WithDescription("Print the list of module names that can be invoked with the --module flag in other skaffold commands.").
WithFlagAdder(cmdModulesListFlags).
NoArgs(listModules)
}
func listModules(ctx context.Context, out io.Writer) error {
return modules.PrintModulesList(ctx, out, inspect.Options{
Filename: inspectFlags.filename,
RepoCacheDir: inspectFlags.repoCacheDir,
OutFormat: inspectFlags.outFormat,
ModulesOptions: inspect.ModulesOptions{IncludeAll: modulesFlags.includeAll},
})
}
func cmdModulesListFlags(f *pflag.FlagSet) {
f.BoolVarP(&modulesFlags.includeAll, "all", "a", false, "Include unnamed modules in the result.")
}
|
package access
import (
"github.com/open-kingfisher/king-utils/common/access"
"github.com/open-kingfisher/king-utils/common/log"
versionedclient "istio.io/client-go/pkg/clientset/versioned"
)
func IstioClient(clusterId string) (*versionedclient.Clientset, error) {
config, err := access.GetConfig(clusterId)
if err != nil {
return nil, err
}
clientSet, err := versionedclient.NewForConfig(config)
if err != nil {
log.Errorf("Istio clientSet error: %s", err)
return nil, err
}
return clientSet, err
}
|
package statistic
import (
//"github.com/astaxie/beego"
"net/http"
"strings"
"webserver/controllers"
"webserver/models"
"webserver/models/extra"
)
type ClickStatisController struct {
controllers.BaseController
}
func (c *ClickStatisController) Get() {
defer c.Recover()
c.statisticInfo()
c.WriteCommonResponse(http.StatusOK, 1, nil)
}
func (c *ClickStatisController) statisticInfo() error {
statis := &extra.Statistic{}
sId := c.Ctx.Input.Query("campaignId")
ua := strings.ToLower(c.Ctx.Input.UserAgent())
statis.StatisticId = sId
if strings.Contains(ua, "iphone") {
statis.Platform = 1
} else if strings.Contains(ua, "android") {
statis.Platform = 2
}
statis.Ip = c.Ctx.Input.IP()
statis.Extra = ""
statis.Status = models.STATUS_NORMAL
models.SaveRecord(statis)
return nil
}
|
// Copyright£ (c) 2020-2021 KHS Films
//
// This file is a part of mtproto package.
// See https://github.com/xelaj/mtproto/blob/master/LICENSE for details
package tl
import "fmt"
type ErrRegisteredObjectNotFound struct {
Crc uint32
Data []byte
}
func (e *ErrRegisteredObjectNotFound) Error() string {
return fmt.Sprintf("object with provided crc not registered: 0x%08x", e.Crc)
}
type ErrMustParseSlicesExplicitly null
func (e *ErrMustParseSlicesExplicitly) Error() string {
return "got vector CRC code when parsing unknown object: vectors can't be parsed as predicted objects"
}
type ErrorPartialWrite struct {
Has int
Want int
}
func (e *ErrorPartialWrite) Error() string {
return fmt.Sprintf("write failed: writed only %v bytes, expected %v", e.Has, e.Want)
}
|
package main
import (
"fmt"
"os"
"reflect"
"strings"
)
type Config struct {
Name string `json:"server-name"`
IP string `json:"server-ip"`
URL string `json:"server-url"`
Timeout string `json:"timeout"`
}
func readConfig() *Config {
// read from xxx.json,省略
config := Config{}
typ := reflect.TypeOf(config)
value := reflect.Indirect(reflect.ValueOf(&config))
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
if v, ok := f.Tag.Lookup("json"); ok {
key := fmt.Sprintf("CONFIG_%s", strings.ReplaceAll(strings.ToUpper(v), "-", "_"))
if env, exist := os.LookupEnv(key); exist {
value.FieldByName(f.Name).Set(reflect.ValueOf(env))
}
}
}
return &config
}
func main() {
os.Setenv("CONFIG_SERVER_NAME", "global_server")
os.Setenv("CONFIG_SERVER_IP", "10.0.0.1")
os.Setenv("CONFIG_SERVER_URL", "geektutu.com")
c := readConfig()
fmt.Printf("%+v", c)
}
|
package ws
import (
"encoding/json"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
m "github.com/kasiss-liu/go-webserver/models"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func SyncServerState(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
var responMessage []byte
for {
messageType := websocket.TextMessage
state := m.State.GetServerState()
if responMessage, err = json.Marshal(state); err != nil {
log.Println(err)
return
}
if err := conn.WriteMessage(messageType, []byte(responMessage)); err != nil {
log.Println(err)
return
}
time.Sleep(5 * time.Second)
}
}
|
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT License was not distributed with this
// file, you can obtain one at https://opensource.org/licenses/MIT.
//
// Copyright (c) DUSK NETWORK. All rights reserved.
package transactions
import (
"bytes"
"context"
"crypto/rand"
"encoding/binary"
"errors"
"math/big"
"time"
"github.com/dusk-network/dusk-blockchain/pkg/core/consensus/user"
"github.com/dusk-network/dusk-blockchain/pkg/core/data/ipc/blindbid"
"github.com/dusk-network/dusk-blockchain/pkg/core/data/ipc/keys"
"github.com/dusk-network/dusk-blockchain/pkg/p2p/wire/encoding"
crypto "github.com/dusk-network/dusk-crypto/hash"
"github.com/dusk-network/dusk-protobuf/autogen/go/rusk"
)
// PermissiveExecutor implements the transactions.Executor interface. It
// simulates successful Validation and Execution of State transitions
// all Validation and simulates.
type PermissiveExecutor struct {
height uint64
P *user.Provisioners
}
// MockExecutor returns an instance of PermissiveExecutor.
func MockExecutor(height uint64) *PermissiveExecutor {
return &PermissiveExecutor{
height: height,
P: user.NewProvisioners(),
}
}
// VerifyStateTransition returns all ContractCalls passed
// height. It returns those ContractCalls deemed valid.
func (p *PermissiveExecutor) VerifyStateTransition(ctx context.Context, cc []ContractCall, height uint64) ([]ContractCall, error) {
return cc, nil
}
// ExecuteStateTransition performs a global state mutation and steps the
// block-height up.
func (p *PermissiveExecutor) ExecuteStateTransition(ctx context.Context, cc []ContractCall, height uint64) (user.Provisioners, error) {
return *p.P, nil
}
// GetProvisioners returns current state of provisioners.
func (p *PermissiveExecutor) GetProvisioners(ctx context.Context) (user.Provisioners, error) {
return *p.P, nil
}
// PermissiveProvisioner mocks verification of scores.
type PermissiveProvisioner struct{}
// VerifyScore returns nil all the time.
func (p PermissiveProvisioner) VerifyScore(context.Context, uint64, uint8, blindbid.VerifyScoreRequest) error {
return nil
}
// MockBlockGenerator mocks a blockgenerator.
type MockBlockGenerator struct{}
// GenerateScore obeys the BlockGenerator interface.
func (b MockBlockGenerator) GenerateScore(context.Context, blindbid.GenerateScoreRequest) (blindbid.GenerateScoreResponse, error) {
limit, _ := big.NewInt(0).SetString("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", 16)
prove, _ := crypto.RandEntropy(256)
prover, _ := crypto.RandEntropy(32)
score, _ := crypto.RandEntropy(32)
scoreInt := big.NewInt(0).SetBytes(score)
// making sure that the score exceeds the threshold
for scoreInt.Cmp(limit) <= 0 {
score, _ = crypto.RandEntropy(32)
scoreInt = big.NewInt(0).SetBytes(score)
}
return blindbid.GenerateScoreResponse{
BlindbidProof: prove,
Score: score,
ProverIdentity: prover,
}, nil
}
// MockProxy mocks a proxy for ease of testing.
type MockProxy struct {
P Provisioner
Pr Provider
V UnconfirmedTxProber
KM KeyMaster
E Executor
BG BlockGenerator
}
// Provisioner ...
func (m MockProxy) Provisioner() Provisioner { return m.P }
// Provider ...
func (m MockProxy) Provider() Provider { return m.Pr }
type mockVerifier struct {
verifyTransactionLatency time.Duration
}
func (v *mockVerifier) VerifyTransaction(ctx context.Context, cc ContractCall) error {
if IsMockInvalid(cc) {
return errors.New("Invalid transaction")
}
if v.verifyTransactionLatency > 0 {
time.Sleep(v.verifyTransactionLatency)
}
return nil
}
func (v *mockVerifier) CalculateBalance(ctx context.Context, vkBytes []byte, txs []ContractCall) (uint64, error) {
return uint64(0), nil
}
// Prober returns a UnconfirmedTxProber that is capable of checking invalid mocked up transactions.
func (m MockProxy) Prober() UnconfirmedTxProber {
return &mockVerifier{}
}
// ProberWithParams instantiates a mockVerifier with a latency value for VerifyTransaction.
func (m MockProxy) ProberWithParams(verifyTransactionLatency time.Duration) UnconfirmedTxProber {
return &mockVerifier{verifyTransactionLatency}
}
// KeyMaster ...
func (m MockProxy) KeyMaster() KeyMaster { return m.KM }
// Executor ...
func (m MockProxy) Executor() Executor { return m.E }
// BlockGenerator ...
func (m MockProxy) BlockGenerator() BlockGenerator { return m.BG }
// MockKeys mocks the keys.
func MockKeys() (*keys.SecretKey, *keys.PublicKey) {
sk := keys.NewSecretKey()
pk := keys.NewPublicKey()
keys.USecretKey(RuskSecretKey(), sk)
keys.UPublicKey(RuskPublicKey(), pk)
return sk, pk
}
/******************/
/** ContractCall **/
/******************/
// RandContractCall returns a random ContractCall.
func RandContractCall() ContractCall {
switch RandTxType() {
case Stake:
return RandStakeTx(0)
case Bid:
return RandBidTx(0)
case Tx:
return RandTx()
default:
return RandTx()
}
}
// RandContractCalls creates random but syntactically valid amount of
// transactions and an "invalid" amount of invalid transactions.
// The invalid transactions are marked as such since they carry "INVALID" in
// the proof. This because we actually have no way to know if a transaction is
// valid or not without RUSK, since syntactically wrong transactions would be
// discarded when Unmarshalling.
// The set is composed of Stake, Bid and normal Transactions.
// If a coinbase is included, an additional Distribute transaction is added
// at the top. A coinbase is never invalid.
func RandContractCalls(amount, invalid int, includeCoinbase bool) []ContractCall {
if invalid > amount {
panic("inconsistent number of invalid transactions wrt the total amount")
}
cc := make([]ContractCall, amount)
for i := 0; i < amount; i++ {
cc[i] = RandContractCall()
}
for i := 0; i < invalid; {
// Pick a random tx within the set and invalidate it until we reach the
// invalid amount.
idx, err := rand.Int(rand.Reader, big.NewInt(int64(amount)))
if err != nil {
panic(err)
}
if !IsMockInvalid(cc[idx.Int64()]) {
Invalidate(cc[idx.Int64()])
i++
}
}
if includeCoinbase {
coinbase := RandDistributeTx(RandUint64(), 30)
return append([]ContractCall{coinbase}, cc...)
}
return cc
}
/************/
/**** TX ****/
/************/
// RandTx returns a random transaction. The randomization includes the amount,
// the fee, the blinding factor and whether the transaction is obfuscated or
// otherwise.
func RandTx() *Transaction {
bf := make([]byte, 32)
if _, err := rand.Read(bf); err != nil {
panic(err)
}
return MockTx(RandBool(), bf, true)
}
// MockTx mocks a transfer transaction. For simplicity it includes a single
// output with the amount specified. The blinding factor can be left to nil if
// the test is not interested in Transaction equality/differentiation.
// Otherwise it can be used to identify/differentiate the transaction.
func MockTx(obfuscated bool, blindingFactor []byte, randomized bool) *Transaction {
ccTx := NewTransaction()
rtx := mockRuskTx(obfuscated, blindingFactor, randomized)
if err := UTransaction(rtx, ccTx); err != nil {
panic(err)
}
return ccTx
}
/****************/
/** DISTRIBUTE **/
/****************/
// RandDistributeTx creates a random distribute transaction.
func RandDistributeTx(reward uint64, provisionerNr int) *Transaction {
rew := reward
if reward == uint64(0) {
rew = RandUint64()
}
ps := make([][]byte, provisionerNr)
for i := 0; i < provisionerNr; i++ {
ps[i] = Rand32Bytes()
}
// _, pk := RandKeys()
tx := RandTx()
// set the output to 0
tx.Payload.Notes[0].Commitment = make([]byte, 32)
buf := new(bytes.Buffer)
// if err := encoding.WriteVarInt(buf, uint64(provisionerNr)); err != nil {
// panic(err)
// }
// for _, pk := range ps {
// if err := encoding.Write256(buf, pk); err != nil {
// panic(err)
// }
// }
if err := encoding.WriteUint64LE(buf, rew); err != nil {
panic(err)
}
tx.Payload.CallData = buf.Bytes()
tx.Payload.Nullifiers = make([][]byte, 0)
tx.TxType = Distribute
return tx
}
/************/
/** STAKE **/
/************/
// RandStakeTx creates a random stake transaction. If the expiration
// is <1, then it is randomly set.
func RandStakeTx(expiration uint64) *Transaction {
if expiration < 1 {
expiration = RandUint64()
}
blsKey := make([]byte, 129)
if _, err := rand.Read(blsKey); err != nil {
panic(err)
}
return MockStakeTx(expiration, blsKey, true)
}
// MockStakeTx creates a StakeTransaction.
func MockStakeTx(expiration uint64, blsKey []byte, randomized bool) *Transaction {
stx := NewTransaction()
rtx := mockRuskTx(false, Rand32Bytes(), randomized)
if err := UTransaction(rtx, stx); err != nil {
panic(err)
}
buf := new(bytes.Buffer)
if err := encoding.WriteUint64LE(buf, expiration); err != nil {
panic(err)
}
if err := encoding.WriteVarBytes(buf, blsKey); err != nil {
panic(err)
}
stx.Payload.CallData = buf.Bytes()
stx.TxType = Stake
return stx
}
/*********/
/** BID **/
/*********/
// RandBidTx creates a random bid transaction. If the expiration
// is <1, then it is randomly set.
func RandBidTx(expiration uint64) *Transaction {
if expiration < 1 {
expiration = RandUint64()
}
return MockBidTx(expiration, Rand32Bytes(), Rand32Bytes(), true)
}
// MockBidTx creates a BidTransaction.
func MockBidTx(expiration uint64, edPk, seed []byte, randomized bool) *Transaction {
stx := NewTransaction()
// Amount is set directly in the underlying ContractCallTx.
rtx := mockRuskTx(true, Rand32Bytes(), randomized)
if err := UTransaction(rtx, stx); err != nil {
panic(err)
}
buf := new(bytes.Buffer)
// M, Commitment, R
for i := 0; i < 3; i++ {
if err := encoding.Write256(buf, Rand32Bytes()); err != nil {
panic(err)
}
}
if err := encoding.Write256(buf, edPk); err != nil {
panic(err)
}
if err := encoding.Write256(buf, seed); err != nil {
panic(err)
}
if err := encoding.WriteUint64LE(buf, expiration); err != nil {
panic(err)
}
stx.Payload.CallData = buf.Bytes()
stx.TxType = Bid
return stx
}
// MockDeterministicBid creates a deterministic bid, where none of the fields
// are subject to randomness. This creates predictability in the output of the
// hash calculation, and is useful for testing purposes.
func MockDeterministicBid(expiration uint64, edPk, seed []byte) *Transaction {
stx := NewTransaction()
// amount is set directly in the underlying ContractCallTx
rtx := mockRuskTx(true, make([]byte, 32), false)
if err := UTransaction(rtx, stx); err != nil {
panic(err)
}
buf := new(bytes.Buffer)
// M, Commitment, R
for i := 0; i < 3; i++ {
if err := encoding.Write256(buf, make([]byte, 32)); err != nil {
panic(err)
}
}
if err := encoding.Write256(buf, edPk); err != nil {
panic(err)
}
if err := encoding.Write256(buf, seed); err != nil {
panic(err)
}
if err := encoding.WriteUint64LE(buf, expiration); err != nil {
panic(err)
}
stx.Payload.CallData = buf.Bytes()
stx.TxType = Bid
return stx
}
/**************************/
/** Transfer Transaction **/
/**************************/
func mockRuskTx(obfuscated bool, blindingFactor []byte, randomized bool) *rusk.Transaction {
anchorBytes := make([]byte, 32)
if randomized {
anchorBytes = Rand32Bytes()
}
nullifierBytes := make([]byte, 32)
if randomized {
nullifierBytes = Rand32Bytes()
}
if obfuscated {
pl := &TransactionPayload{
Anchor: anchorBytes,
Nullifiers: [][]byte{nullifierBytes},
Notes: []*Note{mockObfuscatedOutput(blindingFactor)},
Fee: MockFee(randomized),
Crossover: MockCrossover(randomized),
SpendingProof: []byte{0xaa, 0xbb},
CallData: make([]byte, 0),
}
buf := new(bytes.Buffer)
if err := MarshalTransactionPayload(buf, pl); err != nil {
// There's no way a mocked transaction payload should fail to
// marshal.
panic(err)
}
return &rusk.Transaction{
Payload: buf.Bytes(),
}
}
pl := &TransactionPayload{
Anchor: anchorBytes,
Nullifiers: [][]byte{Rand32Bytes()},
Notes: []*Note{mockTransparentOutput(blindingFactor)},
Fee: MockFee(randomized),
Crossover: MockCrossover(randomized),
SpendingProof: []byte{0xab, 0xbc},
CallData: make([]byte, 0),
}
buf := new(bytes.Buffer)
if err := MarshalTransactionPayload(buf, pl); err != nil {
// There's no way a mocked transaction payload should fail to
// marshal.
panic(err)
}
return &rusk.Transaction{
Payload: buf.Bytes(),
}
}
// RuskTx is the mock of a ContractCallTx.
func RuskTx() *rusk.Transaction {
pl := &TransactionPayload{
Anchor: make([]byte, 32),
Nullifiers: [][]byte{Rand32Bytes()},
Notes: []*Note{mockTransparentOutput(Rand32Bytes())},
Fee: MockFee(false),
Crossover: MockCrossover(false),
SpendingProof: []byte{0xaa, 0xbb},
CallData: make([]byte, 0),
}
buf := new(bytes.Buffer)
if err := MarshalTransactionPayload(buf, pl); err != nil {
// There's no way a mocked transaction payload should fail to
// marshal.
panic(err)
}
return &rusk.Transaction{
Payload: buf.Bytes(),
}
}
/**************************/
/** TX OUTPUTS AND NOTES **/
/**************************/
func mockTransparentOutput(blindingFactor []byte) *Note {
return MockTransparentNote(blindingFactor)
}
// MockTransparentNote is a transparent note.
func MockTransparentNote(blindingFactor []byte) *Note {
return &Note{
Nonce: make([]byte, 32),
PkR: make([]byte, 32),
Commitment: blindingFactor,
Randomness: make([]byte, 32),
EncryptedData: make([]byte, 96),
}
}
// MockObfuscatedOutput returns a Note with the amount hashed. To
// allow for equality checking and retrieval, an encrypted blinding factor can
// also be provided.
// Despite the unsofisticated mocking, the hashing should be enough since the
// node has no way to decode obfuscation as this is delegated to RUSK.
func MockObfuscatedOutput(blindingFactor []byte) *Note {
return &Note{
Nonce: make([]byte, 32),
PkR: make([]byte, 32),
Commitment: blindingFactor,
Randomness: make([]byte, 32),
EncryptedData: make([]byte, 96),
}
}
func mockObfuscatedOutput(blindingFactor []byte) *Note {
return MockObfuscatedOutput(blindingFactor)
}
// MockCrossover returns a mocked Crossover struct.
func MockCrossover(randomized bool) *Crossover {
valueCommBytes := make([]byte, 32)
if randomized {
valueCommBytes = Rand32Bytes()
}
nonceBytes := make([]byte, 32)
if randomized {
nonceBytes = Rand32Bytes()
}
return &Crossover{
ValueComm: valueCommBytes,
Nonce: nonceBytes,
EncryptedData: make([]byte, 96),
}
}
// MockFee returns a mocked Fee struct.
func MockFee(randomized bool) *Fee {
rBytes := make([]byte, 32)
if randomized {
rBytes = Rand32Bytes()
}
pkRBytes := make([]byte, 32)
if randomized {
pkRBytes = Rand32Bytes()
}
return &Fee{
GasLimit: 50000,
GasPrice: 100,
R: rBytes,
PkR: pkRBytes,
}
}
/*************/
/** INVALID **/
/*************/
// IsMockInvalid checks whether a ContractCall mock is invalid or not.
func IsMockInvalid(cc ContractCall) bool {
return bytes.Equal(cc.StandardTx().SpendingProof, []byte("INVALID"))
}
// Invalidate a transaction by marking its Proof field as "INVALID".
func Invalidate(cc ContractCall) {
cc.StandardTx().SpendingProof = []byte("INVALID")
}
// MockInvalidTx creates an invalid transaction.
func MockInvalidTx() *Transaction {
tx := NewTransaction()
input := Rand32Bytes()
output := mockTransparentOutput(Rand32Bytes())
// // changing the NoteType to obfuscated with transparent value makes this
// // transaction invalid
// output.Note.NoteType = 1
// fee := MockTransparentOutput(RandUint64(), nil)
// tx.Payload.Fee = &fee
tx.Payload.Notes = []*Note{output}
tx.Payload.Nullifiers = [][]byte{input}
tx.Payload.SpendingProof = []byte("INVALID")
return tx
}
/**********/
/** KEYS **/
/**********/
// RandKeys returns a syntactically correct (but semantically rubbish) keypair.
func RandKeys() (keys.SecretKey, keys.PublicKey) {
sk := keys.SecretKey{
A: Rand32Bytes(),
B: Rand32Bytes(),
}
pk := keys.PublicKey{
AG: Rand32Bytes(),
BG: Rand32Bytes(),
}
return sk, pk
}
// RuskPublicKey mocks rusk pk.
func RuskPublicKey() *rusk.PublicKey {
return &rusk.PublicKey{
AG: make([]byte, 32),
BG: make([]byte, 32),
}
}
// RuskSecretKey mocks rusk sk.
func RuskSecretKey() *rusk.SecretKey {
return &rusk.SecretKey{
A: make([]byte, 32),
B: make([]byte, 32),
}
}
/*************/
/** UTILITY **/
/*************/
// RandUint64 returns a random uint64.
func RandUint64() uint64 {
bint64 := make([]byte, 8)
if _, err := rand.Read(bint64); err != nil {
panic(err)
}
return binary.LittleEndian.Uint64(bint64)
}
// RandBlind returns a random BlindingFactor (it is just an alias for
// Rand32Bytes).
var RandBlind = Rand32Bytes
// RandBytes returns a random byte slice of the desired size.
func RandBytes(size int) []byte {
blind := make([]byte, 32)
if _, err := rand.Read(blind); err != nil {
panic(err)
}
return blind
}
// Rand32Bytes returns random 32 bytes.
func Rand32Bytes() []byte {
return RandBytes(32)
}
// RandBool returns a random boolean.
func RandBool() bool {
return RandUint64()&(1<<63) == 0
}
// RandTxType returns a random TxType.
func RandTxType() TxType {
t, err := rand.Int(rand.Reader, big.NewInt(8))
if err != nil {
panic(err)
}
return TxType(uint8(t.Uint64()))
}
|
// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package memmap
import (
"gvisor.dev/gvisor/pkg/hostarch"
"reflect"
"testing"
)
type testMappingSpace struct {
// Ideally we'd store the full ranges that were invalidated, rather
// than individual calls to Invalidate, as they are an implementation
// detail, but this is the simplest way for now.
inv []hostarch.AddrRange
}
func (n *testMappingSpace) reset() {
n.inv = []hostarch.AddrRange{}
}
func (n *testMappingSpace) Invalidate(ar hostarch.AddrRange, opts InvalidateOpts) {
n.inv = append(n.inv, ar)
}
func TestAddRemoveMapping(t *testing.T) {
set := MappingSet{}
ms := &testMappingSpace{}
mapped := set.AddMapping(ms, hostarch.AddrRange{0x10000, 0x12000}, 0x1000, true)
if got, want := mapped, []MappableRange{{0x1000, 0x3000}}; !reflect.DeepEqual(got, want) {
t.Errorf("AddMapping: got %+v, wanted %+v", got, want)
}
// Mappings (hostarch.AddrRanges => memmap.MappableRange):
// [0x10000, 0x12000) => [0x1000, 0x3000)
t.Log(&set)
mapped = set.AddMapping(ms, hostarch.AddrRange{0x20000, 0x21000}, 0x2000, true)
if len(mapped) != 0 {
t.Errorf("AddMapping: got %+v, wanted []", mapped)
}
// Mappings:
// [0x10000, 0x11000) => [0x1000, 0x2000)
// [0x11000, 0x12000) and [0x20000, 0x21000) => [0x2000, 0x3000)
t.Log(&set)
mapped = set.AddMapping(ms, hostarch.AddrRange{0x30000, 0x31000}, 0x4000, true)
if got, want := mapped, []MappableRange{{0x4000, 0x5000}}; !reflect.DeepEqual(got, want) {
t.Errorf("AddMapping: got %+v, wanted %+v", got, want)
}
// Mappings:
// [0x10000, 0x11000) => [0x1000, 0x2000)
// [0x11000, 0x12000) and [0x20000, 0x21000) => [0x2000, 0x3000)
// [0x30000, 0x31000) => [0x4000, 0x5000)
t.Log(&set)
mapped = set.AddMapping(ms, hostarch.AddrRange{0x12000, 0x15000}, 0x3000, true)
if got, want := mapped, []MappableRange{{0x3000, 0x4000}, {0x5000, 0x6000}}; !reflect.DeepEqual(got, want) {
t.Errorf("AddMapping: got %+v, wanted %+v", got, want)
}
// Mappings:
// [0x10000, 0x11000) => [0x1000, 0x2000)
// [0x11000, 0x12000) and [0x20000, 0x21000) => [0x2000, 0x3000)
// [0x12000, 0x13000) => [0x3000, 0x4000)
// [0x13000, 0x14000) and [0x30000, 0x31000) => [0x4000, 0x5000)
// [0x14000, 0x15000) => [0x5000, 0x6000)
t.Log(&set)
unmapped := set.RemoveMapping(ms, hostarch.AddrRange{0x10000, 0x11000}, 0x1000, true)
if got, want := unmapped, []MappableRange{{0x1000, 0x2000}}; !reflect.DeepEqual(got, want) {
t.Errorf("RemoveMapping: got %+v, wanted %+v", got, want)
}
// Mappings:
// [0x11000, 0x12000) and [0x20000, 0x21000) => [0x2000, 0x3000)
// [0x12000, 0x13000) => [0x3000, 0x4000)
// [0x13000, 0x14000) and [0x30000, 0x31000) => [0x4000, 0x5000)
// [0x14000, 0x15000) => [0x5000, 0x6000)
t.Log(&set)
unmapped = set.RemoveMapping(ms, hostarch.AddrRange{0x20000, 0x21000}, 0x2000, true)
if len(unmapped) != 0 {
t.Errorf("RemoveMapping: got %+v, wanted []", unmapped)
}
// Mappings:
// [0x11000, 0x13000) => [0x2000, 0x4000)
// [0x13000, 0x14000) and [0x30000, 0x31000) => [0x4000, 0x5000)
// [0x14000, 0x15000) => [0x5000, 0x6000)
t.Log(&set)
unmapped = set.RemoveMapping(ms, hostarch.AddrRange{0x11000, 0x15000}, 0x2000, true)
if got, want := unmapped, []MappableRange{{0x2000, 0x4000}, {0x5000, 0x6000}}; !reflect.DeepEqual(got, want) {
t.Errorf("RemoveMapping: got %+v, wanted %+v", got, want)
}
// Mappings:
// [0x30000, 0x31000) => [0x4000, 0x5000)
t.Log(&set)
unmapped = set.RemoveMapping(ms, hostarch.AddrRange{0x30000, 0x31000}, 0x4000, true)
if got, want := unmapped, []MappableRange{{0x4000, 0x5000}}; !reflect.DeepEqual(got, want) {
t.Errorf("RemoveMapping: got %+v, wanted %+v", got, want)
}
}
func TestInvalidateWholeMapping(t *testing.T) {
set := MappingSet{}
ms := &testMappingSpace{}
set.AddMapping(ms, hostarch.AddrRange{0x10000, 0x11000}, 0, true)
// Mappings:
// [0x10000, 0x11000) => [0, 0x1000)
t.Log(&set)
set.Invalidate(MappableRange{0, 0x1000}, InvalidateOpts{})
if got, want := ms.inv, []hostarch.AddrRange{{0x10000, 0x11000}}; !reflect.DeepEqual(got, want) {
t.Errorf("Invalidate: got %+v, wanted %+v", got, want)
}
}
func TestInvalidatePartialMapping(t *testing.T) {
set := MappingSet{}
ms := &testMappingSpace{}
set.AddMapping(ms, hostarch.AddrRange{0x10000, 0x13000}, 0, true)
// Mappings:
// [0x10000, 0x13000) => [0, 0x3000)
t.Log(&set)
set.Invalidate(MappableRange{0x1000, 0x2000}, InvalidateOpts{})
if got, want := ms.inv, []hostarch.AddrRange{{0x11000, 0x12000}}; !reflect.DeepEqual(got, want) {
t.Errorf("Invalidate: got %+v, wanted %+v", got, want)
}
}
func TestInvalidateMultipleMappings(t *testing.T) {
set := MappingSet{}
ms := &testMappingSpace{}
set.AddMapping(ms, hostarch.AddrRange{0x10000, 0x11000}, 0, true)
set.AddMapping(ms, hostarch.AddrRange{0x20000, 0x21000}, 0x2000, true)
// Mappings:
// [0x10000, 0x11000) => [0, 0x1000)
// [0x12000, 0x13000) => [0x2000, 0x3000)
t.Log(&set)
set.Invalidate(MappableRange{0, 0x3000}, InvalidateOpts{})
if got, want := ms.inv, []hostarch.AddrRange{{0x10000, 0x11000}, {0x20000, 0x21000}}; !reflect.DeepEqual(got, want) {
t.Errorf("Invalidate: got %+v, wanted %+v", got, want)
}
}
func TestInvalidateOverlappingMappings(t *testing.T) {
set := MappingSet{}
ms1 := &testMappingSpace{}
ms2 := &testMappingSpace{}
set.AddMapping(ms1, hostarch.AddrRange{0x10000, 0x12000}, 0, true)
set.AddMapping(ms2, hostarch.AddrRange{0x20000, 0x22000}, 0x1000, true)
// Mappings:
// ms1:[0x10000, 0x12000) => [0, 0x2000)
// ms2:[0x11000, 0x13000) => [0x1000, 0x3000)
t.Log(&set)
set.Invalidate(MappableRange{0x1000, 0x2000}, InvalidateOpts{})
if got, want := ms1.inv, []hostarch.AddrRange{{0x11000, 0x12000}}; !reflect.DeepEqual(got, want) {
t.Errorf("Invalidate: ms1: got %+v, wanted %+v", got, want)
}
if got, want := ms2.inv, []hostarch.AddrRange{{0x20000, 0x21000}}; !reflect.DeepEqual(got, want) {
t.Errorf("Invalidate: ms1: got %+v, wanted %+v", got, want)
}
}
func TestMixedWritableMappings(t *testing.T) {
set := MappingSet{}
ms := &testMappingSpace{}
mapped := set.AddMapping(ms, hostarch.AddrRange{0x10000, 0x12000}, 0x1000, true)
if got, want := mapped, []MappableRange{{0x1000, 0x3000}}; !reflect.DeepEqual(got, want) {
t.Errorf("AddMapping: got %+v, wanted %+v", got, want)
}
// Mappings:
// [0x10000, 0x12000) writable => [0x1000, 0x3000)
t.Log(&set)
mapped = set.AddMapping(ms, hostarch.AddrRange{0x20000, 0x22000}, 0x2000, false)
if got, want := mapped, []MappableRange{{0x3000, 0x4000}}; !reflect.DeepEqual(got, want) {
t.Errorf("AddMapping: got %+v, wanted %+v", got, want)
}
// Mappings:
// [0x10000, 0x11000) writable => [0x1000, 0x2000)
// [0x11000, 0x12000) writable and [0x20000, 0x21000) readonly => [0x2000, 0x3000)
// [0x21000, 0x22000) readonly => [0x3000, 0x4000)
t.Log(&set)
// Unmap should fail because we specified the readonly map address range, but
// asked to unmap a writable segment.
unmapped := set.RemoveMapping(ms, hostarch.AddrRange{0x20000, 0x21000}, 0x2000, true)
if len(unmapped) != 0 {
t.Errorf("RemoveMapping: got %+v, wanted []", unmapped)
}
// Readonly mapping removed, but writable mapping still exists in the range,
// so no mappable range fully unmapped.
unmapped = set.RemoveMapping(ms, hostarch.AddrRange{0x20000, 0x21000}, 0x2000, false)
if len(unmapped) != 0 {
t.Errorf("RemoveMapping: got %+v, wanted []", unmapped)
}
// Mappings:
// [0x10000, 0x12000) writable => [0x1000, 0x3000)
// [0x21000, 0x22000) readonly => [0x3000, 0x4000)
t.Log(&set)
unmapped = set.RemoveMapping(ms, hostarch.AddrRange{0x11000, 0x12000}, 0x2000, true)
if got, want := unmapped, []MappableRange{{0x2000, 0x3000}}; !reflect.DeepEqual(got, want) {
t.Errorf("RemoveMapping: got %+v, wanted %+v", got, want)
}
// Mappings:
// [0x10000, 0x12000) writable => [0x1000, 0x3000)
// [0x21000, 0x22000) readonly => [0x3000, 0x4000)
t.Log(&set)
// Unmap should fail since writable bit doesn't match.
unmapped = set.RemoveMapping(ms, hostarch.AddrRange{0x10000, 0x12000}, 0x1000, false)
if len(unmapped) != 0 {
t.Errorf("RemoveMapping: got %+v, wanted []", unmapped)
}
unmapped = set.RemoveMapping(ms, hostarch.AddrRange{0x10000, 0x12000}, 0x1000, true)
if got, want := unmapped, []MappableRange{{0x1000, 0x2000}}; !reflect.DeepEqual(got, want) {
t.Errorf("RemoveMapping: got %+v, wanted %+v", got, want)
}
// Mappings:
// [0x21000, 0x22000) readonly => [0x3000, 0x4000)
t.Log(&set)
unmapped = set.RemoveMapping(ms, hostarch.AddrRange{0x21000, 0x22000}, 0x3000, false)
if got, want := unmapped, []MappableRange{{0x3000, 0x4000}}; !reflect.DeepEqual(got, want) {
t.Errorf("RemoveMapping: got %+v, wanted %+v", got, want)
}
}
|
package private
import (
"github.com/google/go-querystring/query"
"github.com/pkg/errors"
"github.com/potix/gobitflyer/api/types"
"github.com/potix/gobitflyer/client"
)
const (
getParentOrderPath string = "/v1/me/getparentorder"
)
type GetParentOrderResponse struct {
Id int64 `json:"id"`
ParentOrderId string `json:"parent_order_id"`
OrderMethod types.OrderMethod `json:"order_method"`
MinuteToExpire int64 `json:"minute_to_expire"`
TimeInForce types.TimeInForce `json:"time_in_force"`
Parameters []*GetParentOrderParameter `json:"parameters"`
}
type GetParentOrderParameter struct {
ProductCode types.ProductCode `json:"product_code"`
ConditionType types.ConditionType `json:"condition_type"`
Side types.Side `json:"side"`
Price float64 `json:"price"`
Size float64 `json:"size"`
TriggerPrice float64 `json:"trigger_price"`
Offset float64 `json:"offset"`
}
type GetParentOrderRequest struct {
Path string `url:"-"`
ParentOrderId string `url:"parent_order_id,omitempty"`
ParentOrderAcceptanceId string `url:"parent_order_acceptance_id,omitempty"`
}
func (b *GetParentOrderRequest) CreateHTTPRequest(endpoint string) (*client.HTTPRequest, error) {
v, err := query.Values(b)
if err != nil {
return nil, errors.Wrapf(err, "can not create query of get parent order request")
}
query := v.Encode()
pathQuery := b.Path + "?" + query
return &client.HTTPRequest {
PathQuery: pathQuery,
URL: endpoint + pathQuery,
Method: "GET",
Headers: make(map[string]string),
Body: nil,
}, nil
}
func NewGetParentOrderRequest(IdType types.IdType, orderId string) (*GetParentOrderRequest, error) {
switch IdType {
case types.IdTypeParentOrderId:
return &GetParentOrderRequest{
Path: getParentOrderPath,
ParentOrderId: orderId,
}, nil
case types.IdTypeParentOrderAcceptanceId:
return &GetParentOrderRequest{
Path: getParentOrderPath,
ParentOrderAcceptanceId: orderId,
}, nil
default:
return nil, errors.Errorf("unexpected id type (id type = %v)", IdType)
}
}
|
package main
import (
"fmt"
"sync"
)
type Account struct {
Money int
Locker sync.Mutex
}
func (a *Account) SaveMoney(n int) {
a.Locker.Lock()
fmt.Println("before save,money=", a.Money)
a.Money += n
fmt.Println("after save,money=", a.Money)
a.Locker.Unlock()
}
func (a *Account) GetMoney(n int) {
a.Locker.Lock()
fmt.Println("before get,money=", a.Money)
a.Money -= n
fmt.Println("after get,money=", a.Money)
a.Locker.Unlock()
}
func (a *Account) PrintHistory() {
fmt.Println("the current money=", a.Money)
}
var wg sync.WaitGroup
var locker sync.Mutex
func main() {
a := Account{1000, locker}
for i := 0; i < 3; i++ {
wg.Add(1)
go func() {
a.GetMoney(100)
wg.Done()
}()
}
for i := 0; i < 3; i++ {
wg.Add(1)
go func() {
a.SaveMoney(100)
wg.Done()
}()
}
for i := 0; i < 3; i++ {
wg.Add(1)
go func() {
a.PrintHistory()
wg.Done()
}()
}
wg.Wait()
fmt.Println("the final money=", a.Money)
}
|
package main
import "strconv"
// Leetcode 5772. (easy)
func isSumEqual(firstWord string, secondWord string, targetWord string) bool {
m := make(map[rune]int)
r := 'a'
for i := 0; i < 26; i++ {
m[r] = i
r++
}
buf := ""
for _, r := range firstWord {
buf += strconv.Itoa(m[r])
}
firstNum, _ := strconv.Atoi(buf)
buf = ""
for _, r := range secondWord {
buf += strconv.Itoa(m[r])
}
secondNum, _ := strconv.Atoi(buf)
buf = ""
for _, r := range targetWord {
buf += strconv.Itoa(m[r])
}
targetNum, _ := strconv.Atoi(buf)
return firstNum+secondNum == targetNum
}
|
package fmap
import (
"fmt"
"github.com/lleo/go-functional-collections/key"
)
// KeyVal is a simple struct used to transfer lists ([]KeyVal) from one
// function to another.
type KeyVal struct {
Key key.Hash
Val interface{}
}
func (kv KeyVal) String() string {
return fmt.Sprintf("{%q, %v}", kv.Key, kv.Val)
}
|
package main
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestHistory(t *testing.T) {
assert := assert.New(t)
h := &history{
Id: 123,
Name: "init",
}
assert.Equal("000123_init", h.String())
res, err := parseHistory("000123_init")
assert.Nil(err)
assert.Equal(&history{
Id: 123,
Name: "init",
}, res)
}
|
package main
import (
"context"
"fmt"
"os"
"strings"
pb "github.com/aykay76/grpc-go/environment"
empty "github.com/golang/protobuf/ptypes/empty"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
var (
opsProcessed = promauto.NewCounter(prometheus.CounterOpts{
Name: "grpc_server_operations_total",
Help: "The total number of processed operations",
})
opsDuration = promauto.NewSummary(prometheus.SummaryOpts{
Name: "grpc_server_operations_duration",
Help: "The duration of processed operations",
})
)
// EnvironmentServer : server for the environment service
type EnvironmentServer struct {
pb.UnimplementedEnvironmentServiceServer
}
// GetEnvironmentVariable : allow clients to get specified environment variable
func (server *EnvironmentServer) GetEnvironmentVariable(ctx context.Context, kvp *pb.KeyValuePair) (*pb.KeyValuePair, error) {
// create a timer to observe the duration
timer := prometheus.NewTimer(opsDuration)
// increment the counter of total operations
opsProcessed.Inc()
var result pb.KeyValuePair
result.Key = kvp.Key
result.Value = os.Getenv(kvp.Key)
// observe the time since the timer was started
timer.ObserveDuration()
return &result, nil
}
// GetEnvironmentVariables : allows clients to get all environment variables on a stream
func (server *EnvironmentServer) GetEnvironmentVariables(req *empty.Empty, stream pb.EnvironmentService_GetEnvironmentVariablesServer) error {
// create a timer to observe the duration
timer := prometheus.NewTimer(opsDuration)
// increment the counter of total operations
opsProcessed.Inc()
for _, e := range os.Environ() {
pair := strings.SplitN(e, "=", 2)
fmt.Println(pair[0])
var entry pb.KeyValuePair
entry.Key = pair[0]
entry.Value = pair[1]
err := stream.Send(&entry)
if err != nil {
fmt.Println(err)
return err
}
}
timer.ObserveDuration()
return nil
}
// SetEnvironmentVariable : allows clients to set environment variables
func (server *EnvironmentServer) SetEnvironmentVariable(ctx context.Context, kvp *pb.KeyValuePair) (*empty.Empty, error) {
// create a timer to observe the duration
timer := prometheus.NewTimer(opsDuration)
// increment the counter of total operations
opsProcessed.Inc()
os.Setenv(kvp.Key, kvp.Value)
timer.ObserveDuration()
return nil, nil
}
|
package Week_03
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func buildTree(preorder []int, inorder []int) *TreeNode {
if len(preorder) == 0 || len(inorder) == 0 {
return nil
}
skip := 0
for k, v := range inorder {
if v == preorder[0] {
skip = k
break
}
}
lTree := buildTree(preorder[1:skip + 1], inorder[0:skip])
rTree := buildTree(preorder[skip + 1:], inorder[skip + 1:])
root := &TreeNode{
Val: preorder[0],
Left: lTree,
Right: rTree,
}
return root
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.