text stringlengths 11 4.05M |
|---|
package utils
import (
"bytes"
"encoding/hex"
"fmt"
"github.com/maoxs2/go-bech32"
"reflect"
"testing"
)
func TestSerializeNumber(t *testing.T) {
if !bytes.Equal(SerializeNumber(100), []byte{0x01, 0x64}) {
fmt.Println(SerializeNumber(100))
t.Fail()
}
if hex.EncodeToString(SerializeNumber(1<<31-1)) != "04ffffff7f" {
t.Fail()
}
}
func TestSerializeString(t *testing.T) {
if !bytes.Equal(SerializeString("HelloWorld"), []byte{0x0a, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x57, 0x6f, 0x72, 0x6c, 0x64}) {
fmt.Println(SerializeString("HelloWorld"))
t.Fail()
}
}
func TestReverseByteOrder(t *testing.T) {
hash := Sha256([]byte("0000"))
fmt.Println(hash)
fmt.Println(ReverseByteOrder(hash))
}
func TestReverseBytes(t *testing.T) {
hash := Sha256([]byte("0000"))
fmt.Println(hash)
fmt.Println(ReverseBytes(hash))
fmt.Println(hex.EncodeToString(hash))
fmt.Println(hex.EncodeToString(ReverseBytes(hash)))
}
func TestUint256BytesFromHash(t *testing.T) {
result, _ := hex.DecodeString("691938264876d1078051da4e30ec0643262e8b93fca661f525fe7122b38d5f18")
if !bytes.Equal(Uint256BytesFromHash(hex.EncodeToString(Sha256([]byte("Hello")))), result) {
t.Fail()
}
}
func TestVarIntBytes(t *testing.T) {
if hex.EncodeToString(VarIntBytes(uint64(23333))) != "fd255b" {
t.Fail()
}
t.Log(int64(1<<31 - 1))
if hex.EncodeToString(VarIntBytes(uint64(1<<31-1))) != "feffffff7f" {
t.Fail()
}
}
func TestVarStringBytes(t *testing.T) {
if hex.EncodeToString(VarStringBytes("Hello")) != "0548656c6c6f" {
t.Fail()
}
}
func TestRange(t *testing.T) {
if !reflect.DeepEqual(Range(0, 8, 2), []int{0, 2, 4, 6}) {
t.Fail()
}
if !reflect.DeepEqual(Range(2, 0, 2), []int{}) {
t.Fail()
}
}
func TestSha256d(t *testing.T) {
hexStr := "01000000" +
"81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000" +
"e320b6c2fffc8d750423db8b1eb942ae710e951ed797f7affc8892b0f1fc122b" +
"c7f5d74d" +
"f2b9441a" +
"42a14695"
raw, _ := hex.DecodeString(hexStr)
if hex.EncodeToString(Sha256d(raw)) != "1dbd981fe6985776b644b173a4d0385ddc1aa2a829688d1e0000000000000000" {
t.Fail()
}
}
func TestP2PKHAddressToScript(t *testing.T) {
addr := "mipcBbFg9gMiCh81Kj8tqqdgoZub1ZJRfn"
t.Log(hex.EncodeToString(P2PKHAddressToScript(addr)))
}
func TestP2SHAddressToScript(t *testing.T) {
addr := "QcGaxM7GsauRBS4CD2rzkE34HZci2kBeF4"
t.Log(hex.EncodeToString(P2SHAddressToScript(addr)))
}
func TestP2WSHAddressToScript(t *testing.T) {
addr := "tb1qphxtwvfxyjhq5ar2hn65eczg8u6stam2n7znx5"
str, decoded, err := bech32.Decode(addr)
if decoded == nil || err != nil {
log.Fatal("base58 decode failed for " + addr)
}
if len(decoded) == 0 || len(decoded) > 65 {
log.Fatal("invalid address length for " + addr)
}
t.Log(str)
witnessProgram, _ := bech32.ConvertBits(decoded[1:], 5, 8, true)
t.Log(len(decoded))
//publicKey := decoded[1:len(decoded)]
t.Log(hex.EncodeToString(witnessProgram))
}
func TestCommandStringBytes(t *testing.T) {
if hex.EncodeToString(CommandStringBytes("version")) != "76657273696f6e0000000000" {
t.Fail()
}
}
|
package utils
import (
"golang.org/x/sys/windows/registry"
"log"
"os"
"time"
)
func CheckRegister(){
duration := uint64(80*24*60*60) //90days
now:=uint64(time.Now().Unix())
// 创建:指定路径的项
// 路径:HKEY_CURRENT_USER\Software\Hello Go
key, exists, _ := registry.CreateKey(registry.CURRENT_USER, `SOFTWARE\GoAuthor`, registry.ALL_ACCESS)
defer key.Close()
// 判断是否已经存在了
if exists {
//log.Println(`键已存在`)
// 读取
begin, _, _ := key.GetIntegerValue(`registerAt`)
//log.Println(now-begin)
if now-begin>duration{
log.Println("使用期失效,请联系发行者")
os.Exit(1)
}
} else {
//log.Println(`新建注册表键`)
// 写入:64位整形值
err := key.SetQWordValue(`registerAt`, uint64(time.Now().Unix()))
if err != nil {
log.Printf("注册失败,请咨询")
}
}
}
|
// Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package cpu
import (
"context"
"time"
"github.com/shirou/gopsutil/v3/cpu"
"chromiumos/tast/errors"
"chromiumos/tast/testing"
)
// timesStat returns utilization stats across all CPUs as reported by /proc/stat.
func timesStat() (*cpu.TimesStat, error) {
times, err := cpu.Times(false)
if err != nil {
return nil, err
}
return ×[0], nil
}
// MeasureUsage measures utilization across all CPUs during duration.
// Returns a percentage in the range [0.0, 100.0].
func MeasureUsage(ctx context.Context, duration time.Duration) (float64, error) {
// Get the total time the CPU spent in different states (read from
// /proc/stat on linux machines).
statBegin, err := timesStat()
if err != nil {
return 0, err
}
if err := testing.Sleep(ctx, duration); err != nil {
return 0, err
}
// Get the total time the CPU spent in different states again. By looking at
// the difference with the values we got earlier, we can calculate the time
// the processor was idle. The gopsutil library also has a function that
// does this directly, but unfortunately we can't use it as that function
// doesn't abort when the timeout in ctx is exceeded.
statEnd, err := timesStat()
if err != nil {
return 0, err
}
totalTimeBegin := statBegin.Total()
activeTimeBegin := totalTimeBegin - (statBegin.Idle + statBegin.Iowait)
totalTimeEnd := statEnd.Total()
activeTimeEnd := totalTimeEnd - (statEnd.Idle + statEnd.Iowait)
if totalTimeEnd <= totalTimeBegin {
return 0.0, errors.Errorf("total time went from %f to %f", totalTimeBegin, totalTimeEnd)
}
return (activeTimeEnd - activeTimeBegin) / (totalTimeEnd - totalTimeBegin) * 100.0, nil
}
|
package main
import (
"./lib/gonumgen"
"fmt"
)
func main() {
// main
fmt.Printf("go-numgen testapp.")
}
|
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package firmware
import (
"context"
"chromiumos/tast/common/servo"
"chromiumos/tast/remote/dutfs"
"chromiumos/tast/remote/firmware/fingerprint"
"chromiumos/tast/remote/firmware/fingerprint/rpcdut"
"chromiumos/tast/testing"
"chromiumos/tast/testing/hwdep"
)
// Path to the file where TPM seed is temporarily stored.
const fingerprintTPMSeedFile = "/run/bio_crypto_init/seed"
func init() {
testing.AddTest(&testing.Test{
Func: FpTpmSeed,
Desc: "Check using ectool if bio_crypto_init set the TPM seed",
Contacts: []string{
"tomhughes@chromium.org",
"chromeos-fingerprint@google.com",
},
Attr: []string{"group:mainline", "informational"},
SoftwareDeps: []string{"biometrics_daemon"},
HardwareDeps: hwdep.D(hwdep.Fingerprint()),
ServiceDeps: []string{"tast.cros.platform.UpstartService", dutfs.ServiceName},
Vars: []string{"servo"},
})
}
func FpTpmSeed(ctx context.Context, s *testing.State) {
d, err := rpcdut.NewRPCDUT(ctx, s.DUT(), s.RPCHint(), "cros")
if err != nil {
s.Fatal("Failed to connect RPCDUT: ", err)
}
defer d.Close(ctx)
servoSpec, ok := s.Var("servo")
if !ok {
servoSpec = ""
}
pxy, err := servo.NewProxy(ctx, servoSpec, d.KeyFile(), d.KeyDir())
if err != nil {
s.Fatal("Failed to connect to servo: ", err)
}
defer pxy.Close(ctx)
fpBoard, err := fingerprint.Board(ctx, d)
if err != nil {
s.Fatal("Failed to get fingerprint board: ", err)
}
needsReboot, err := fingerprint.NeedsRebootAfterFlashing(ctx, d)
if err != nil {
s.Fatal("Failed to determine whether reboot is needed: ", err)
}
firmwareFile, err := fingerprint.NewMPFirmwareFile(ctx, d)
if err != nil {
s.Fatal("Failed to create MP firmwareFile: ", err)
}
removeSWWP := false
if err := fingerprint.InitializeKnownState(ctx, d, s.OutDir(), pxy,
fpBoard, *firmwareFile, needsReboot, removeSWWP); err != nil {
s.Fatal("Initialization failed: ", err)
}
// The seed is only set after bio_crypto_init runs. The boot-services
// service is blocked until bio_crypto_init finishes.
// The system-services starts after boot-services, then failsafe and
// finally openssh-server. As a result if SSH server is running, then
// we are sure that bio_crypto_init initialized TPM seed.
// Check if the TPM seed file does not exist. It is created by
// cryptohome and supposed to be removed by bio_fw_updater. The file
// contains TPM seed passed to FPMCU. If the file exists, it will be
// a security issue.
dutfsClient := dutfs.NewClient(d.RPC().Conn)
exists, err := dutfsClient.Exists(ctx, fingerprintTPMSeedFile)
if err != nil {
s.Fatal(err, "Error checking that TPM seed file exists: ", err)
}
if exists {
s.Errorf("File with TPM seed (%q) exists", fingerprintTPMSeedFile)
}
// Check if FPMCU was initialized with TPM seed.
testing.ContextLog(ctx, "Validating that FPMCU was initialized with TPM seed")
e, err := fingerprint.GetEncryptionStatus(ctx, d.DUT())
if err != nil {
s.Fatal("Failed to get encryption status: ", err)
}
testing.ContextLogf(ctx, "FPMCU encryption engine status: %#08x", e.Current)
if e.TPMSeedSet() {
testing.ContextLog(ctx, "TPM seed is set")
} else {
s.Error("TPM seed is not set")
}
}
|
package main
import "magicTGArchive/internal/pkg/api"
func main() {
api.SetupRoutes()
} |
package forms
import (
. "launchpad.net/gocheck"
"testing"
)
func Test(t *testing.T) { TestingT(t) }
type FormSuite struct{}
var _ = Suite(&FormSuite{})
type WidgetForm struct {
*DefaultForm
Foo, Bar *StringField
Baz, Quux *IntField
}
func (form *WidgetForm) CleanQuux(f FormField) error {
field := f.(*IntField)
i := field.Value
if i < 35 {
field.SetError("Quux values must be greater than 35.")
}
return nil
}
type BrokenWidget struct {
Foo, Bar string
Baz int
}
type Widget struct {
Foo, Bar string
Baz, Quux int
}
//Calling Ready() on an uninitialized Form should return false
func (s *FormSuite) TestCallingReadyOnUninitializedFormShouldReturnFalse(c *C) {
f := &WidgetForm{}
c.Assert(f.ready(), Equals, false)
}
//Calling Ready() on an initialized Form should return true
func (s *FormSuite) TestCallingReadyOnInitializedFormShouldReturnFalse(c *C) {
f := &WidgetForm{}
Init(f, nil)
c.Assert(f.ready(), Equals, true)
}
//An initialized Form should have a properly created Fields map
func (s *FormSuite) TestInitializedFormHasProperlyCreatedFieldsMap(c *C) {
f := &WidgetForm{}
Init(f, nil)
fields := f.fieldMap()
c.Assert(fields["Foo"], FitsTypeOf, &StringField{BaseField: newBaseField()})
c.Assert(fields["Bar"], FitsTypeOf, &StringField{BaseField: newBaseField()})
c.Assert(fields["Bar"], FitsTypeOf, &StringField{BaseField: newBaseField()})
c.Assert(fields["Quux"], FitsTypeOf, &IntField{})
}
//Calling Populate on an uninitialized Form should return an error
func (s *FormSuite) TestCallingPopulateOnUninitializedFormShouldReturnError(c *C) {
form := &WidgetForm{}
err := Populate(form, map[string]interface{}{
"Foo": "baz",
"Bar": "quux",
"Baz": "37",
"Quux": "52",
})
c.Assert(err, Not(IsNil))
}
//Calling Populate on a TestForm with valid data should set the values of those fields
func (s *FormSuite) TestCallingPopulateOnTestformValidDataShouldSetValuesThoseFields(c *C) {
form := &WidgetForm{}
Init(form, nil)
Populate(form, map[string]interface{}{
"Foo": "baz",
"Bar": "quux",
"Baz": "37",
"Quux": "52",
})
c.Assert(form.Foo.Data.(string), DeepEquals, "baz")
c.Assert(form.Bar.Data.(string), DeepEquals, "quux")
c.Assert(form.Baz.Data.(string), DeepEquals, "37")
}
//Calling Populate on a TestForm with invalid data should set the values of those fields
func (s *FormSuite) TestCallingPopulateOnTestformInvalidDataShouldSetValuesThoseFields(c *C) {
form := &WidgetForm{}
Init(form, nil)
Populate(form, map[string]interface{}{
"Foo": "baz",
"Bar": "quux",
"Baz": "thirty-seven",
"Quux": "52",
})
c.Assert(form.Foo.Data.(string), DeepEquals, "baz")
c.Assert(form.Bar.Data.(string), DeepEquals, "quux")
c.Assert(form.Baz.Data.(string), DeepEquals, "thirty-seven")
}
//Calling IsValid on a TestForm with valid data should return true
func (s *FormSuite) TestCallingIsvalidOnTestformValidDataShouldReturnTrue(c *C) {
form := &WidgetForm{}
Init(form, nil)
Populate(form, map[string]interface{}{
"Foo": "baz",
"Bar": "quux",
"Baz": "37",
"Quux": "52",
})
c.Assert(IsValid(form), Equals, true)
}
//Calling IsValid on a TestForm with invalid data should return false
func (s *FormSuite) TestCallingIsvalidOnTestformInvalidDataShouldReturnFalse(c *C) {
form := &WidgetForm{}
Init(form, nil)
Populate(form, map[string]interface{}{
"Foo": "baz",
"Bar": "quux",
"Baz": "thirty-seven",
"Quux": "52",
})
c.Assert(IsValid(form), Equals, false)
}
//Calling IsValid on a form with a custom Clean method should run the method on the field
func (s *FormSuite) TestCallingIsvalidOnFormCustomCleanMethodShouldRunMethodOnField(c *C) {
form := &WidgetForm{}
Init(form, nil)
Populate(form, map[string]interface{}{
"Foo": "baz",
"Bar": "quux",
"Baz": "37",
"Quux": "28",
})
c.Assert(IsValid(form), Equals, false)
}
//Calling Copy on a valid WidgetForm and a Widget should copy the values to the widget
func (s *FormSuite) TestCallingCopyOnValidWidgetformAndWidgetShouldCopyValuesToWidget(c *C) {
form := &WidgetForm{}
Init(form, nil)
widget := &Widget{}
Populate(form, map[string]interface{}{
"Foo": "baz",
"Bar": "quux",
"Baz": "37",
"Quux": 52,
})
Copy(form, widget)
c.Assert(widget.Foo, Equals, "baz")
c.Assert(widget.Bar, Equals, "quux")
c.Assert(widget.Baz, Equals, 37)
c.Assert(widget.Quux, Equals, 52)
}
//Calling Copy on a valid WidgetForm and a struct missing a field from the form should return an error
func (s *FormSuite) TestCallingCopyOnValidWidgetformAndStructMissingFieldFromFormShouldReturnError(c *C) {
form := &WidgetForm{}
Init(form, nil)
widget := &BrokenWidget{}
Populate(form, map[string]interface{}{
"Foo": "baz",
"Bar": "quux",
"Baz": 37,
"Quux": "52",
})
err := Copy(form, widget)
c.Assert(err, ErrorMatches, `No "Quux" field found on forms.BrokenWidget struct`)
}
//Calling Copy on an invalid WidgetForm and a Widget should return an error
func (s *FormSuite) TestCallingCopyOnInvalidWidgetformAndWidgetShouldCopyValuesToWidget(c *C) {
form := &WidgetForm{}
Init(form, nil)
widget := &Widget{}
Populate(form, map[string]interface{}{
"Foo": "baz",
"Bar": "quux",
"Baz": "thirty-seven",
"Quux": "52",
})
err := Copy(form, widget)
c.Assert(err, ErrorMatches, "Cannot copy from invalid form")
}
|
package validators
import (
"net/mail"
"github.com/labstack/echo"
"net/http"
"fmt"
"github.com/MetalRex101/auth-server/app/models"
"time"
)
type EmailValidator struct {
Base *Validator
}
func (ev *EmailValidator) ValidateEmail (addr string) error {
_, err := mail.ParseAddress(addr)
if err != nil {
return echo.NewHTTPError(
http.StatusNotAcceptable,
fmt.Sprintf("Указан невозможный адрес e-mail: '%s'", addr),
)
}
return nil
}
func (ev *EmailValidator) ActivationCodeHasNotExpired (email *models.Email) error {
if email.ConfirmDate.Before(time.Now().AddDate(0, 0, -1)) {
return echo.NewHTTPError(http.StatusRequestTimeout, "Код активации устарел")
}
return nil
} |
package failsafe
import (
"context"
"errors"
)
var (
ErrContextCancelled = errors.New("context cancelled")
)
type Failsafe struct {
retryPolicy *RetryPolicy
}
func New(retryPolicy *RetryPolicy) *Failsafe {
return &Failsafe{
retryPolicy: retryPolicy,
}
}
func (f *Failsafe) Run(ctx context.Context, attempt func() error) error {
var err error
for !f.retryPolicy.IsDone() {
select {
case <-ctx.Done():
f.retryPolicy.Cancel()
err = ErrContextCancelled
case <-f.retryPolicy.Next():
err = attempt()
if err == nil {
return nil
}
f.retryPolicy.Report(err)
}
}
return err
}
|
package main
import (
"fmt"
)
func main() {
fmt.Printf("String %s", "Pablo")
fmt.Println()
fmt.Printf("Float %.2f", 5.3555555)
fmt.Println()
fmt.Printf("Integer %d", 10)
fmt.Println()
fmt.Printf("Bool %t", true)
fmt.Println()
fmt.Printf("Automatico %v", 35.1212)
fmt.Println()
fmt.Printf("Como en el codigo Go %#v", "\n")
fmt.Println()
fmt.Printf("TypeOF %T", true)
fmt.Println()
fmt.Printf("Escapar porcentaje %%")
}
|
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package iperf implements the client and server interfaces required to use Iperf with callboxes
package iperf
|
package ipgeolocation
import (
"errors"
"net/url"
)
// validateParams is used to make sure required fields are present
func validateParams(params *IPGeolocationRequest) error {
if params == nil {
return errors.New("missing input")
}
if params.IP == "" && len(params.IPs) == 0 {
return errors.New("missing IP")
}
return nil
}
// prepareUrlParams adds values to the url params from the request parameters
func (c *Client) prepareUrlParams(p *url.Values, params *IPGeolocationRequest) {
// Add the apiKey
p.Add("apiKey", c.options.APIKey)
// Add the fields
addUrlParms(p, "fields", params.Fields)
// Set the language
if params.Language == "" {
params.Language = c.options.Language
}
p.Add("lang", params.Language)
// Add security
if params.IncludeSecurity {
p.Add("include", "security")
}
// Add Includes
if params.IncludeHostname {
p.Add("include", "hostname")
}
if params.IncludeLiveHostname {
p.Add("include", "liveHostname")
}
if params.IncludeHostnameFallbackLive {
p.Add("include", "hostnameFallbackLive")
}
if params.IncludeUseragent {
p.Add("include", "useragent")
}
}
// addUrlParms adds array values to the url parameters
func addUrlParms(p *url.Values, field string, values []string) {
for _, v := range values {
p.Add(field, v)
}
}
// stringInArray checks if a string is present in []string
func stringInArray(arr []string, s string) bool {
for _, v := range arr {
if v == s {
return true
}
}
return false
}
|
package config
import (
"log"
"os"
)
func InitLogger() *log.Logger {
logger := log.New(os.Stdout, "Tasker ", log.LstdFlags|log.Lshortfile|log.Lmicroseconds|log.LUTC)
return logger
}
|
package controller_adaptor
import (
"github.com/eden-framework/reverse-proxy/worker"
"github.com/robotic-framework/robotic-client/internal/constants/enums"
"github.com/robotic-framework/robotic-client/internal/global"
"github.com/sirupsen/logrus"
"gobot.io/x/gobot"
)
var typeInitializer map[enums.UpstreamAdaptorType]initializer
func init() {
typeInitializer = make(map[enums.UpstreamAdaptorType]initializer)
typeInitializer[enums.UPSTREAM_ADAPTOR_TYPE__PROXY] = proxyAdaptorInitializer
}
type initializer func(config global.RobotConfiguration) gobot.Adaptor
func NewUpstreamAdaptor(typ enums.UpstreamAdaptorType, config global.RobotConfiguration) UpstreamAdaptor {
initFunc, ok := typeInitializer[typ]
if !ok {
logrus.Panicf("cannot get initializer from upstream adaptor: %s", typ.String())
}
return initFunc(config)
}
type UpstreamAdaptor interface {
gobot.Adaptor
}
func proxyAdaptorInitializer(config global.RobotConfiguration) gobot.Adaptor {
w := &worker.Worker{
RemoteAddr: config.UpstreamAdaptorProxyRemoteAddr,
RetryInterval: config.UpstreamAdaptorProxyRetryInterval,
RetryMaxTime: config.UpstreamAdaptorProxyRetryMaxTime,
}
w.Init()
proxyAdaptor := NewProxyAdaptor(w, config.UpstreamAdaptorProxyRemotePort)
return proxyAdaptor
}
|
package groups
import (
"context"
"github.com/go-kit/kit/endpoint"
"github.com/mainflux/mainflux/auth"
)
func createGroupEndpoint(svc auth.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(createGroupReq)
if err := req.validate(); err != nil {
return groupRes{}, err
}
group := auth.Group{
Name: req.Name,
Description: req.Description,
ParentID: req.ParentID,
Metadata: req.Metadata,
}
group, err := svc.CreateGroup(ctx, req.token, group)
if err != nil {
return groupRes{}, err
}
return groupRes{created: true, id: group.ID}, nil
}
}
func viewGroupEndpoint(svc auth.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(groupReq)
if err := req.validate(); err != nil {
return viewGroupRes{}, err
}
group, err := svc.ViewGroup(ctx, req.token, req.id)
if err != nil {
return viewGroupRes{}, err
}
res := viewGroupRes{
ID: group.ID,
Name: group.Name,
Description: group.Description,
Metadata: group.Metadata,
ParentID: group.ParentID,
OwnerID: group.OwnerID,
CreatedAt: group.CreatedAt,
UpdatedAt: group.UpdatedAt,
}
return res, nil
}
}
func updateGroupEndpoint(svc auth.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(updateGroupReq)
if err := req.validate(); err != nil {
return groupRes{}, err
}
group := auth.Group{
ID: req.id,
Name: req.Name,
Description: req.Description,
Metadata: req.Metadata,
}
_, err := svc.UpdateGroup(ctx, req.token, group)
if err != nil {
return groupRes{}, err
}
res := groupRes{created: false}
return res, nil
}
}
func deleteGroupEndpoint(svc auth.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(groupReq)
if err := req.validate(); err != nil {
return nil, err
}
if err := svc.RemoveGroup(ctx, req.token, req.id); err != nil {
return nil, err
}
return deleteRes{}, nil
}
}
func listGroupsEndpoint(svc auth.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(listGroupsReq)
if err := req.validate(); err != nil {
return groupPageRes{}, err
}
pm := auth.PageMetadata{
Level: req.level,
Metadata: req.metadata,
}
page, err := svc.ListGroups(ctx, req.token, pm)
if err != nil {
return groupPageRes{}, err
}
if req.tree {
return buildGroupsResponseTree(page), nil
}
return buildGroupsResponse(page), nil
}
}
func listMemberships(svc auth.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(listMembershipsReq)
if err := req.validate(); err != nil {
return memberPageRes{}, err
}
pm := auth.PageMetadata{
Offset: req.offset,
Limit: req.limit,
Metadata: req.metadata,
}
page, err := svc.ListMemberships(ctx, req.token, req.id, pm)
if err != nil {
return memberPageRes{}, err
}
return buildGroupsResponse(page), nil
}
}
func listChildrenEndpoint(svc auth.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(listGroupsReq)
if err := req.validate(); err != nil {
return groupPageRes{}, err
}
pm := auth.PageMetadata{
Level: req.level,
Metadata: req.metadata,
}
page, err := svc.ListChildren(ctx, req.token, req.id, pm)
if err != nil {
return groupPageRes{}, err
}
if req.tree {
return buildGroupsResponseTree(page), nil
}
return buildGroupsResponse(page), nil
}
}
func listParentsEndpoint(svc auth.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(listGroupsReq)
if err := req.validate(); err != nil {
return groupPageRes{}, err
}
pm := auth.PageMetadata{
Level: req.level,
Metadata: req.metadata,
}
page, err := svc.ListParents(ctx, req.token, req.id, pm)
if err != nil {
return groupPageRes{}, err
}
if req.tree {
return buildGroupsResponseTree(page), nil
}
return buildGroupsResponse(page), nil
}
}
func assignEndpoint(svc auth.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(assignReq)
if err := req.validate(); err != nil {
return nil, err
}
if err := svc.Assign(ctx, req.token, req.groupID, req.Type, req.Members...); err != nil {
return nil, err
}
return assignRes{}, nil
}
}
func unassignEndpoint(svc auth.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(unassignReq)
if err := req.validate(); err != nil {
return nil, err
}
if err := svc.Unassign(ctx, req.token, req.groupID, req.Members...); err != nil {
return nil, err
}
return unassignRes{}, nil
}
}
func listMembersEndpoint(svc auth.Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(listMembersReq)
if err := req.validate(); err != nil {
return memberPageRes{}, err
}
pm := auth.PageMetadata{
Offset: req.offset,
Limit: req.limit,
Metadata: req.metadata,
}
page, err := svc.ListMembers(ctx, req.token, req.id, req.groupType, pm)
if err != nil {
return memberPageRes{}, err
}
return buildUsersResponse(page), nil
}
}
func buildGroupsResponseTree(page auth.GroupPage) groupPageRes {
groupsMap := map[string]*auth.Group{}
// Parents' map keeps its array of children.
parentsMap := map[string][]*auth.Group{}
for i := range page.Groups {
if _, ok := groupsMap[page.Groups[i].ID]; !ok {
groupsMap[page.Groups[i].ID] = &page.Groups[i]
parentsMap[page.Groups[i].ID] = make([]*auth.Group, 0)
}
}
for _, group := range groupsMap {
if children, ok := parentsMap[group.ParentID]; ok {
children = append(children, group)
parentsMap[group.ParentID] = children
}
}
res := groupPageRes{
pageRes: pageRes{
Limit: page.Limit,
Offset: page.Offset,
Total: page.Total,
Level: page.Level,
},
Groups: []viewGroupRes{},
}
for _, group := range groupsMap {
if children, ok := parentsMap[group.ID]; ok {
group.Children = children
}
}
for _, group := range groupsMap {
view := toViewGroupRes(*group)
if children, ok := parentsMap[group.ParentID]; len(children) == 0 || !ok {
res.Groups = append(res.Groups, view)
}
}
return res
}
func toViewGroupRes(group auth.Group) viewGroupRes {
view := viewGroupRes{
ID: group.ID,
ParentID: group.ParentID,
OwnerID: group.OwnerID,
Name: group.Name,
Description: group.Description,
Metadata: group.Metadata,
Level: group.Level,
Path: group.Path,
Children: make([]*viewGroupRes, 0),
CreatedAt: group.CreatedAt,
UpdatedAt: group.UpdatedAt,
}
for _, ch := range group.Children {
child := toViewGroupRes(*ch)
view.Children = append(view.Children, &child)
}
return view
}
func buildGroupsResponse(gp auth.GroupPage) groupPageRes {
res := groupPageRes{
pageRes: pageRes{
Total: gp.Total,
Level: gp.Level,
},
Groups: []viewGroupRes{},
}
for _, group := range gp.Groups {
view := viewGroupRes{
ID: group.ID,
ParentID: group.ParentID,
OwnerID: group.OwnerID,
Name: group.Name,
Description: group.Description,
Metadata: group.Metadata,
Level: group.Level,
Path: group.Path,
CreatedAt: group.CreatedAt,
UpdatedAt: group.UpdatedAt,
}
res.Groups = append(res.Groups, view)
}
return res
}
func buildUsersResponse(mp auth.MemberPage) memberPageRes {
res := memberPageRes{
pageRes: pageRes{
Total: mp.Total,
Offset: mp.Offset,
Limit: mp.Limit,
Name: mp.Name,
},
Members: []interface{}{},
}
for _, m := range mp.Members {
res.Members = append(res.Members, m)
}
return res
}
|
package main
import "fmt"
/*
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
*/
func main() {
fmt.Println(LCM(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20))
}
// greatest common divisor (GCD) via Euclidean algorithm
func GCD(a, b int) int {
for b != 0 {
t := b
b = a % b
a = t
}
return a
}
// find Least Common Multiple (LCM) via GCD
func LCM(a, b int, integers ...int) int {
result := a * b / GCD(a, b)
for i := 0; i < len(integers); i++ {
result = LCM(result, integers[i])
}
return result
}
|
package kob
import "regexp"
var rkey = regexp.MustCompile(`:[\w]+`)
const rvalue = `([^/]+)`
func PathToReg(path string) (reg *regexp.Regexp, keys []string, err error) {
path = regexp.QuoteMeta(path)
reg, err = regexp.Compile("^" + rkey.ReplaceAllStringFunc(path, func(m string) string {
keys = append(keys, m[1:])
return rvalue
}) + "$")
return
}
|
package lumps
/**
Lump 34: DispLightmapSamplePosition
*/
type DispLightmapSamplePosition struct {
LumpGeneric
data []byte
}
func (lump *DispLightmapSamplePosition) FromBytes(raw []byte, length int32) {
lump.data = raw
lump.LumpInfo.SetLength(length)
}
func (lump *DispLightmapSamplePosition) GetData() []byte {
return lump.data
}
func (lump *DispLightmapSamplePosition) ToBytes() []byte {
return lump.data
}
|
package chconn
import "github.com/vahid-sohrabloo/chconn/v2/internal/helper"
// Progress details of progress select query
type Progress struct {
ReadRows uint64
ReadBytes uint64
TotalRows uint64
WriterRows uint64
WrittenBytes uint64
ElapsedNS uint64
}
func newProgress() *Progress {
return &Progress{}
}
func (p *Progress) read(ch *conn) (err error) {
if p.ReadRows, err = ch.reader.Uvarint(); err != nil {
return &readError{"progress: read ReadRows", err}
}
if p.ReadBytes, err = ch.reader.Uvarint(); err != nil {
return &readError{"progress: read ReadBytes", err}
}
if p.TotalRows, err = ch.reader.Uvarint(); err != nil {
return &readError{"progress: read TotalRows", err}
}
if ch.serverInfo.Revision >= helper.DbmsMinRevisionWithClientWriteInfo {
if p.WriterRows, err = ch.reader.Uvarint(); err != nil {
return &readError{"progress: read WriterRows", err}
}
if p.WrittenBytes, err = ch.reader.Uvarint(); err != nil {
return &readError{"progress: read WrittenBytes", err}
}
}
if ch.serverInfo.Revision >= helper.DbmsMinProtocolWithServerQueryTimeInProgress {
if p.ElapsedNS, err = ch.reader.Uvarint(); err != nil {
return &readError{"progress: read ElapsedNS", err}
}
}
return nil
}
|
// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
package test_formats
import "github.com/kaitai-io/kaitai_struct_go_runtime/kaitai"
type NestedSameName2 struct {
Version uint32
MainData *NestedSameName2_Main
Dummy *NestedSameName2_DummyObj
_io *kaitai.Stream
_root *NestedSameName2
_parent interface{}
}
func (this *NestedSameName2) Read(io *kaitai.Stream, parent interface{}, root *NestedSameName2) (err error) {
this._io = io
this._parent = parent
this._root = root
tmp1, err := this._io.ReadU4le()
if err != nil {
return err
}
this.Version = uint32(tmp1)
tmp2 := new(NestedSameName2_Main)
err = tmp2.Read(this._io, this, this._root)
if err != nil {
return err
}
this.MainData = tmp2
tmp3 := new(NestedSameName2_DummyObj)
err = tmp3.Read(this._io, this, this._root)
if err != nil {
return err
}
this.Dummy = tmp3
return err
}
type NestedSameName2_Main struct {
MainSize int32
Foo *NestedSameName2_Main_FooObj
_io *kaitai.Stream
_root *NestedSameName2
_parent *NestedSameName2
}
func (this *NestedSameName2_Main) Read(io *kaitai.Stream, parent *NestedSameName2, root *NestedSameName2) (err error) {
this._io = io
this._parent = parent
this._root = root
tmp4, err := this._io.ReadS4le()
if err != nil {
return err
}
this.MainSize = int32(tmp4)
tmp5 := new(NestedSameName2_Main_FooObj)
err = tmp5.Read(this._io, this, this._root)
if err != nil {
return err
}
this.Foo = tmp5
return err
}
type NestedSameName2_Main_FooObj struct {
Data1 []byte
_io *kaitai.Stream
_root *NestedSameName2
_parent *NestedSameName2_Main
}
func (this *NestedSameName2_Main_FooObj) Read(io *kaitai.Stream, parent *NestedSameName2_Main, root *NestedSameName2) (err error) {
this._io = io
this._parent = parent
this._root = root
tmp6, err := this._io.ReadBytes(int((this._parent.MainSize * 2)))
if err != nil {
return err
}
tmp6 = tmp6
this.Data1 = tmp6
return err
}
type NestedSameName2_DummyObj struct {
DummySize int32
Foo *NestedSameName2_DummyObj_FooObj
_io *kaitai.Stream
_root *NestedSameName2
_parent *NestedSameName2
}
func (this *NestedSameName2_DummyObj) Read(io *kaitai.Stream, parent *NestedSameName2, root *NestedSameName2) (err error) {
this._io = io
this._parent = parent
this._root = root
tmp7, err := this._io.ReadS4le()
if err != nil {
return err
}
this.DummySize = int32(tmp7)
tmp8 := new(NestedSameName2_DummyObj_FooObj)
err = tmp8.Read(this._io, this, this._root)
if err != nil {
return err
}
this.Foo = tmp8
return err
}
type NestedSameName2_DummyObj_FooObj struct {
Data2 []byte
_io *kaitai.Stream
_root *NestedSameName2
_parent *NestedSameName2_DummyObj
}
func (this *NestedSameName2_DummyObj_FooObj) Read(io *kaitai.Stream, parent *NestedSameName2_DummyObj, root *NestedSameName2) (err error) {
this._io = io
this._parent = parent
this._root = root
tmp9, err := this._io.ReadBytes(int((this._parent.DummySize * 2)))
if err != nil {
return err
}
tmp9 = tmp9
this.Data2 = tmp9
return err
}
|
package tracer
// VERSION is Epsagon tracer version2
const VERSION = "1.20.0"
|
package cmd_test
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os/exec"
"path/filepath"
"time"
"github.com/CircleCI-Public/circleci-cli/api/graphql"
"github.com/CircleCI-Public/circleci-cli/clitest"
"github.com/CircleCI-Public/circleci-cli/pipeline"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gbytes"
"github.com/onsi/gomega/gexec"
"gotest.tools/v3/golden"
)
var _ = Describe("Config", func() {
Describe("pack", func() {
var (
command *exec.Cmd
results []byte
tempSettings *clitest.TempSettings
token string = "testtoken"
)
BeforeEach(func() {
tempSettings = clitest.WithTempSettings()
})
AfterEach(func() {
tempSettings.Close()
})
Describe("a .circleci folder with config.yml and local orbs folder containing the hugo orb", func() {
BeforeEach(func() {
command = exec.Command(pathCLI,
"config", "pack",
"--skip-update-check",
"testdata/hugo-pack/.circleci")
results = golden.Get(GinkgoT(), filepath.FromSlash("hugo-pack/result.yml"))
})
It("pack all YAML contents as expected", func() {
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
session.Wait()
Expect(err).ShouldNot(HaveOccurred())
Eventually(session.Err.Contents()).Should(BeEmpty())
Eventually(session.Out.Contents()).Should(MatchYAML(results))
Eventually(session).Should(gexec.Exit(0))
})
})
Describe("local orbs folder with mixed inline and local commands, jobs, etc", func() {
BeforeEach(func() {
var path string = "nested-orbs-and-local-commands-etc"
command = exec.Command(pathCLI,
"config", "pack",
"--skip-update-check",
filepath.Join("testdata", path, "test"))
results = golden.Get(GinkgoT(), filepath.FromSlash(fmt.Sprintf("%s/result.yml", path)))
})
It("pack all YAML contents as expected", func() {
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
session.Wait()
Expect(err).ShouldNot(HaveOccurred())
Eventually(session.Err.Contents()).Should(BeEmpty())
Eventually(session.Out.Contents()).Should(MatchYAML(results))
Eventually(session).Should(gexec.Exit(0))
})
})
Describe("an orb containing local executors and commands in folder", func() {
BeforeEach(func() {
command = exec.Command(pathCLI,
"config", "pack",
"--skip-update-check",
"testdata/myorb/test")
results = golden.Get(GinkgoT(), filepath.FromSlash("myorb/result.yml"))
})
It("pack all YAML contents as expected", func() {
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
session.Wait()
Expect(err).ShouldNot(HaveOccurred())
Eventually(session.Err.Contents()).Should(BeEmpty())
Eventually(session.Out.Contents()).Should(MatchYAML(results))
Eventually(session).Should(gexec.Exit(0))
})
})
Describe("with a large nested config including rails orb", func() {
BeforeEach(func() {
var path string = "test-with-large-nested-rails-orb"
command = exec.Command(pathCLI,
"config", "pack",
"--skip-update-check",
filepath.Join("testdata", path, "test"))
results = golden.Get(GinkgoT(), filepath.FromSlash(fmt.Sprintf("%s/result.yml", path)))
})
It("pack all YAML contents as expected", func() {
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
session.Wait()
Expect(err).ShouldNot(HaveOccurred())
Eventually(session.Err.Contents()).Should(BeEmpty())
Eventually(session.Out.Contents()).Should(MatchYAML(results))
Eventually(session).Should(gexec.Exit(0))
})
})
Context("config is a list and not a map", func() {
var config *clitest.TmpFile
BeforeEach(func() {
config = clitest.OpenTmpFile(filepath.Join(tempSettings.Home, "myorb"), "config.yaml")
command = exec.Command(pathCLI,
"config", "pack",
"--skip-update-check",
config.RootDir,
)
})
AfterEach(func() {
config.Close()
})
It("prints an error about invalid YAML", func() {
config.Write([]byte(`[]`))
expected := fmt.Sprintf("Error: Failed trying to marshal the tree to YAML : expected a map, got a `[]interface {}` which is not supported at this time for \"%s\"\n", config.Path)
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
Expect(err).ShouldNot(HaveOccurred())
stderr := session.Wait().Err.Contents()
Expect(string(stderr)).To(Equal(expected))
Eventually(session).Should(clitest.ShouldFail())
})
})
Describe("validating configs", func() {
config := "version: 2.1"
var expReq string
BeforeEach(func() {
command = exec.Command(pathCLI,
"config", "validate",
"--skip-update-check",
"--token", token,
"--host", tempSettings.TestServer.URL(),
"-",
)
stdin, err := command.StdinPipe()
Expect(err).ToNot(HaveOccurred())
_, err = io.WriteString(stdin, config)
Expect(err).ToNot(HaveOccurred())
stdin.Close()
query := `query ValidateConfig ($config: String!, $pipelineParametersJson: String, $pipelineValues: [StringKeyVal!], $orgSlug: String) {
buildConfig(configYaml: $config, pipelineValues: $pipelineValues) {
valid,
errors { message },
sourceYaml,
outputYaml
}
}`
r := graphql.NewRequest(query)
r.Variables["config"] = config
r.Variables["pipelineValues"] = pipeline.PrepareForGraphQL(pipeline.LocalPipelineValues())
req, err := r.Encode()
Expect(err).ShouldNot(HaveOccurred())
expReq = req.String()
})
It("returns an error when validating a config", func() {
expResp := `{
"buildConfig": {
"errors": [
{"message": "error1"}
]
}
}`
tempSettings.AppendPostHandler(token, clitest.MockRequestResponse{
Status: http.StatusOK,
Request: expReq,
Response: expResp,
})
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
Expect(err).ShouldNot(HaveOccurred())
Eventually(session.Err, time.Second*3).Should(gbytes.Say("Error: error1"))
Eventually(session).Should(clitest.ShouldFail())
})
It("returns successfully when validating a config", func() {
expResp := `{
"buildConfig": {}
}`
tempSettings.AppendPostHandler(token, clitest.MockRequestResponse{
Status: http.StatusOK,
Request: expReq,
Response: expResp,
})
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
Expect(err).ShouldNot(HaveOccurred())
Eventually(session.Out, time.Second*3).Should(gbytes.Say("Config input is valid."))
Eventually(session).Should(gexec.Exit(0))
})
})
Describe("validating configs with pipeline parameters", func() {
config := "version: 2.1"
var expReq string
BeforeEach(func() {
command = exec.Command(pathCLI,
"config", "process",
"--skip-update-check",
"--token", token,
"--host", tempSettings.TestServer.URL(),
"--pipeline-parameters", `{"foo": "test", "bar": true, "baz": 10}`,
"-",
)
stdin, err := command.StdinPipe()
Expect(err).ToNot(HaveOccurred())
_, err = io.WriteString(stdin, config)
Expect(err).ToNot(HaveOccurred())
stdin.Close()
query := `query ValidateConfig ($config: String!, $pipelineParametersJson: String, $pipelineValues: [StringKeyVal!], $orgSlug: String) {
buildConfig(configYaml: $config, pipelineValues: $pipelineValues, pipelineParametersJson: $pipelineParametersJson) {
valid,
errors { message },
sourceYaml,
outputYaml
}
}`
r := graphql.NewRequest(query)
r.Variables["config"] = config
r.Variables["pipelineValues"] = pipeline.PrepareForGraphQL(pipeline.LocalPipelineValues())
pipelineParams, err := json.Marshal(pipeline.Parameters{
"foo": "test",
"bar": true,
"baz": 10,
})
Expect(err).ToNot(HaveOccurred())
r.Variables["pipelineParametersJson"] = string(pipelineParams)
req, err := r.Encode()
Expect(err).ShouldNot(HaveOccurred())
expReq = req.String()
})
It("returns successfully when validating a config", func() {
expResp := `{
"buildConfig": {}
}`
tempSettings.AppendPostHandler(token, clitest.MockRequestResponse{
Status: http.StatusOK,
Request: expReq,
Response: expResp,
})
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
Expect(err).ShouldNot(HaveOccurred())
Eventually(session).Should(gexec.Exit(0))
})
})
Describe("validating configs with private orbs", func() {
config := "version: 2.1"
orgId := "bb604b45-b6b0-4b81-ad80-796f15eddf87"
var expReq string
BeforeEach(func() {
command = exec.Command(pathCLI,
"config", "validate",
"--skip-update-check",
"--token", token,
"--host", tempSettings.TestServer.URL(),
"--org-id", orgId,
"-",
)
stdin, err := command.StdinPipe()
Expect(err).ToNot(HaveOccurred())
_, err = io.WriteString(stdin, config)
Expect(err).ToNot(HaveOccurred())
stdin.Close()
query := `query ValidateConfig ($config: String!, $pipelineParametersJson: String, $pipelineValues: [StringKeyVal!], $orgId: UUID!) {
buildConfig(configYaml: $config, pipelineValues: $pipelineValues, orgId: $orgId) {
valid,
errors { message },
sourceYaml,
outputYaml
}
}`
r := graphql.NewRequest(query)
r.Variables["config"] = config
r.Variables["orgId"] = orgId
r.Variables["pipelineValues"] = pipeline.PrepareForGraphQL(pipeline.LocalPipelineValues())
req, err := r.Encode()
Expect(err).ShouldNot(HaveOccurred())
expReq = req.String()
})
It("returns an error when validating a config with a private orb", func() {
expResp := `{
"buildConfig": {
"errors": [
{"message": "permission denied"}
]
}
}`
tempSettings.AppendPostHandler(token, clitest.MockRequestResponse{
Status: http.StatusOK,
Request: expReq,
Response: expResp,
})
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
Expect(err).ShouldNot(HaveOccurred())
Eventually(session.Err, time.Second*3).Should(gbytes.Say("Error: permission denied"))
Eventually(session).Should(clitest.ShouldFail())
})
})
Describe("validating configs with private orbs Legacy", func() {
config := "version: 2.1"
orgSlug := "circleci"
var expReq string
BeforeEach(func() {
command = exec.Command(pathCLI,
"config", "validate",
"--skip-update-check",
"--token", token,
"--host", tempSettings.TestServer.URL(),
"--org-slug", orgSlug,
"-",
)
stdin, err := command.StdinPipe()
Expect(err).ToNot(HaveOccurred())
_, err = io.WriteString(stdin, config)
Expect(err).ToNot(HaveOccurred())
stdin.Close()
query := `query ValidateConfig ($config: String!, $pipelineParametersJson: String, $pipelineValues: [StringKeyVal!], $orgSlug: String) {
buildConfig(configYaml: $config, pipelineValues: $pipelineValues, orgSlug: $orgSlug) {
valid,
errors { message },
sourceYaml,
outputYaml
}
}`
r := graphql.NewRequest(query)
r.Variables["config"] = config
r.Variables["orgSlug"] = orgSlug
r.Variables["pipelineValues"] = pipeline.PrepareForGraphQL(pipeline.LocalPipelineValues())
req, err := r.Encode()
Expect(err).ShouldNot(HaveOccurred())
expReq = req.String()
})
It("returns an error when validating a config with a private orb", func() {
expResp := `{
"buildConfig": {
"errors": [
{"message": "permission denied"}
]
}
}`
tempSettings.AppendPostHandler(token, clitest.MockRequestResponse{
Status: http.StatusOK,
Request: expReq,
Response: expResp,
})
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
Expect(err).ShouldNot(HaveOccurred())
Eventually(session.Err, time.Second*3).Should(gbytes.Say("Error: permission denied"))
Eventually(session).Should(clitest.ShouldFail())
})
It("returns successfully when validating a config with private orbs", func() {
expResp := `{
"buildConfig": {}
}`
tempSettings.AppendPostHandler(token, clitest.MockRequestResponse{
Status: http.StatusOK,
Request: expReq,
Response: expResp,
})
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
Expect(err).ShouldNot(HaveOccurred())
Eventually(session.Out, time.Second*3).Should(gbytes.Say("Config input is valid."))
Eventually(session).Should(gexec.Exit(0))
})
})
})
})
|
package configure
import (
"errors"
"fmt"
"slices"
"github.com/evcc-io/evcc/util/templates"
)
// configureDeviceGuidedSetup lets the user choose a device that is set to support guided setup
// these are typically devices that
// - contain multiple usages but have the same parameters like host, port, etc.
// - devices that typically are installed with additional specific devices (e.g. SMA Home Manager with SMA Inverters)
func (c *CmdConfigure) configureDeviceGuidedSetup() {
var err error
var values map[string]interface{}
var deviceCategory DeviceCategory
var supportedDeviceCategories []DeviceCategory
var templateItem templates.Template
deviceItem := device{}
for {
fmt.Println()
templateItem, err = c.processDeviceSelection(DeviceCategoryGuidedSetup)
if err != nil {
return
}
usageChoices := c.paramChoiceValues(templateItem.Params, templates.ParamUsage)
if len(usageChoices) == 0 {
panic("ERROR: Device template is missing valid usages!")
}
if len(usageChoices) == 0 {
usageChoices = []string{string(DeviceCategoryGridMeter), string(DeviceCategoryPVMeter), string(DeviceCategoryBatteryMeter)}
}
supportedDeviceCategories = []DeviceCategory{}
for _, usage := range usageChoices {
switch usage {
case string(DeviceCategoryGridMeter):
supportedDeviceCategories = append(supportedDeviceCategories, DeviceCategoryGridMeter)
case string(DeviceCategoryPVMeter):
supportedDeviceCategories = append(supportedDeviceCategories, DeviceCategoryPVMeter)
case string(DeviceCategoryBatteryMeter):
supportedDeviceCategories = append(supportedDeviceCategories, DeviceCategoryBatteryMeter)
}
}
// we only ask for the configuration for the first usage
deviceCategory = supportedDeviceCategories[0]
values = c.processConfig(&templateItem, deviceCategory)
deviceItem, err = c.processDeviceValues(values, templateItem, deviceItem, deviceCategory)
if err != nil {
if err != c.errDeviceNotValid {
fmt.Println()
fmt.Println(err)
}
fmt.Println()
if !c.askConfigFailureNextStep() {
return
}
continue
}
break
}
c.configuration.AddDevice(deviceItem, deviceCategory)
c.processDeviceCapabilities(templateItem.Capabilities)
if len(supportedDeviceCategories) > 1 {
for _, additionalCategory := range supportedDeviceCategories[1:] {
values[templates.ParamUsage] = additionalCategory.String()
deviceItem, err := c.processDeviceValues(values, templateItem, deviceItem, additionalCategory)
if err != nil {
continue
}
c.configuration.AddDevice(deviceItem, additionalCategory)
}
}
fmt.Println()
fmt.Println(templateItem.Title() + " " + c.localizedString("Device_Added"))
c.configureLinkedTypes(templateItem)
}
// configureLinkedTypes lets the user configure devices that are marked as being linked to a guided device
// e.g. SMA Inverters, Energy Meter with SMA Home Manager
func (c *CmdConfigure) configureLinkedTypes(templateItem templates.Template) {
added := make([]string, 0)
for _, linkedTemplate := range templateItem.Linked {
// don't process this linked template if a referenced exclude template was added
if slices.Contains(added, linkedTemplate.ExcludeTemplate) {
continue
}
linkedTemplateItem, err := templates.ByName(templates.Meter, linkedTemplate.Template)
if err != nil {
fmt.Println("Error: " + err.Error())
return
}
if len(linkedTemplateItem.Params) == 0 || linkedTemplate.Usage == "" {
break
}
linkedTemplateItem.SetCombinedTitle(c.lang)
category := DeviceCategory(linkedTemplate.Usage)
localizeMap := localizeMap{
"Linked": linkedTemplateItem.Title(),
"Article": DeviceCategories[category].article,
"Additional": DeviceCategories[category].additional,
"Category": DeviceCategories[category].title,
}
fmt.Println()
if !c.askYesNo(c.localizedString("AddLinkedDeviceInCategory", localizeMap)) {
continue
}
for {
if c.configureLinkedTemplate(linkedTemplateItem, category) {
added = append(added, linkedTemplate.Template)
}
if !linkedTemplate.Multiple {
break
}
fmt.Println()
if !c.askYesNo(c.localizedString("AddAnotherLinkedDeviceInCategory", localizeMap)) {
break
}
}
}
}
// configureLinkedTemplate lets the user configure a device that is marked as being linked to a guided device
// returns true if a device was added
func (c *CmdConfigure) configureLinkedTemplate(templateItem templates.Template, category DeviceCategory) bool {
for {
deviceItem := device{}
values := c.processConfig(&templateItem, category)
deviceItem, err := c.processDeviceValues(values, templateItem, deviceItem, category)
if err != nil {
if !errors.Is(err, c.errDeviceNotValid) {
fmt.Println()
fmt.Println(err)
}
fmt.Println()
if c.askConfigFailureNextStep() {
continue
}
} else {
c.configuration.AddDevice(deviceItem, category)
c.processDeviceCapabilities(templateItem.Capabilities)
fmt.Println()
fmt.Println(templateItem.Title() + " " + c.localizedString("Device_Added"))
return true
}
break
}
return false
}
// configureDeviceCategory lets the user select and configure a device from a specific category
func (c *CmdConfigure) configureDeviceCategory(deviceCategory DeviceCategory) (device, []string, error) {
fmt.Println()
fmt.Printf("- %s %s\n", c.localizedString("Device_Configure"), DeviceCategories[deviceCategory].title)
device := device{
Name: DeviceCategories[deviceCategory].defaultName,
}
var deviceDescription string
var capabilities []string
// repeat until the device is added or the user chooses to continue without adding a device
for {
fmt.Println()
templateItem, err := c.processDeviceSelection(deviceCategory)
if err != nil {
return device, capabilities, c.errItemNotPresent
}
deviceDescription = templateItem.Title()
capabilities = templateItem.Capabilities
values := c.processConfig(&templateItem, deviceCategory)
device, err = c.processDeviceValues(values, templateItem, device, deviceCategory)
if err != nil {
if err != c.errDeviceNotValid {
fmt.Println()
fmt.Println(err)
}
// ask if the user wants to add the
fmt.Println()
if !c.askConfigFailureNextStep() {
return device, capabilities, err
}
continue
}
break
}
c.configuration.AddDevice(device, deviceCategory)
c.processDeviceCapabilities(capabilities)
var deviceTitle string
if device.Title != "" {
deviceTitle = " " + device.Title
}
fmt.Println()
fmt.Println(deviceDescription + deviceTitle + " " + c.localizedString("Device_Added"))
return device, capabilities, nil
}
|
package main
import (
"fmt"
"strings"
"github.com/slack-go/slack"
)
const slackToken = "slackUserToken"
const typePrivateChannel = "private_channel"
var api = slack.New(getToken(slackToken))
func slackGetChannelByName(channelName string) (slack.Channel, error) {
channels, _, err := api.GetConversations(&slack.GetConversationsParameters{Types: []string{typePrivateChannel}})
if err != nil {
epanic(err, "can't get user's channels")
}
for _, c := range channels {
if c.Name == channelName {
return c, nil
}
}
return slack.Channel{}, fmt.Errorf("No channel found")
}
func slackGetDirectors() {
channel, _ := slackGetChannelByName("comp-2021-directors")
// Get all members
userIds, _, err := api.GetUsersInConversation(&slack.GetUsersInConversationParameters{ChannelID: channel.ID, Limit: 200})
if err != nil {
epanic(err, "can't get channel's members")
}
// Use api.GetUsersInfo if needed
fmt.Println(userIds)
}
func slackGetOfficerEmails() {
officerC, _ := slackGetChannelByName("circuit-officers")
newUsers, _, err := api.GetUsersInConversation(&slack.GetUsersInConversationParameters{ChannelID: officerC.ID, Limit: 200})
if err != nil {
epanic(err, "can't get officers members")
}
audioC, _ := slackGetChannelByName("circuit-audio-production")
oldUsers, _, err := api.GetUsersInConversation(&slack.GetUsersInConversationParameters{ChannelID: audioC.ID, Limit: 200})
if err != nil {
epanic(err, "can't get audio members")
}
// Filter out from newUsers
usersToAdd := []string{}
outer:
for _, u := range newUsers {
for _, u2 := range oldUsers {
if u == u2 {
continue outer
}
}
usersToAdd = append(usersToAdd, u)
}
fmt.Println(strings.Join(usersToAdd, ","))
// _, err = api.InviteUsersToConversation(audioC.ID, usersToAdd...)
// if err != nil {
// epanic(err, "unable to invite users to conversation")
// }
}
|
package main
import (
"fmt"
"strings"
"time"
"github.com/dkim/aoc/2021/utils"
)
type Node struct {
Data string
Next *Node
}
type LinkedList struct {
Length int
Head *Node
Tail *Node
}
type InsertPair struct {
Data string
InsertPoint *Node
}
func (list *LinkedList) initList(a *Node) {
list.Head = a
list.Tail = a
list.Length = 1
}
func (list *LinkedList) insertAfter(a *Node, b *Node) {
tempNode := a.Next
a.Next = b
b.Next = tempNode
list.Length++
}
func (list *LinkedList) insertAtEnd(a *Node) {
list.Tail.Next = a
list.Tail = a
list.Length++
}
func (list *LinkedList) printList() {
fmt.Printf("Size %d\n", list.Length)
node := list.Head
for node != list.Tail {
fmt.Printf("%s", node.Data)
node = node.Next
}
fmt.Printf("%s\n", node.Data)
}
func processInput(text []string) (map[string]string, string) {
var start string
rules := make(map[string]string)
for _, line := range text {
if !strings.Contains(line, "->") && len(line) != 0 {
start = line
} else if len(line) != 0 {
line := strings.Fields(line)
rules[line[0]] = line[2]
}
}
return rules, start
}
func part1(text []string, steps int) {
defer utils.TimeTrack(time.Now(), "Part 1")
rules, start := processInput(text)
chain := []rune(start)
var polymer LinkedList
// Make the template
for i := 0; i < len(chain); i++ {
node := Node{string(chain[i]), nil}
if i == 0 {
polymer.initList(&node)
} else if i != len(chain) {
polymer.insertAtEnd(&node)
}
}
polymer.printList()
// grow for n steps
for n := 0; n < steps; n++ {
fmt.Printf("After step %d\n", n+1)
// Identify what the value of the Node will be and where we should insert it after
var newChain []InsertPair
node := polymer.Head
for node != polymer.Tail {
text := string(node.Data) + string(node.Next.Data)
val := rules[string(text)]
newChain = append(newChain, InsertPair{val, node})
node = node.Next
}
// Do the insertions
for _, ip := range newChain {
polymer.insertAfter(ip.InsertPoint, &Node{ip.Data, nil})
}
newChain = nil
polymer.printList()
}
// Calculate the most common and least common
score := make(map[string]int)
walker := polymer.Head
for walker != polymer.Tail {
score[string(walker.Data)]++
walker = walker.Next
}
// and the tail
score[string(walker.Data)]++
// Now find the min and max values
min := score[string(walker.Data)]
max := 0
for _, value := range score {
if value < min {
min = value
} else if value > max {
max = value
}
}
fmt.Printf("%d - %d = %d", max, min, max-min)
}
type Pair struct {
L string
R string
}
func part2(text []string, steps int) {
// order doesn't matter, only pairs
// the template is the seed and we break it up into
// 3 pairs. each pair uses the rule and makes n - 1 more pairs
// where n is the original length before applying rules
defer utils.TimeTrack(time.Now(), "Part 2")
rules, start := processInput(text)
poly := make(map[Pair]int)
chain := []rune(start)
for i := 0; i < len(chain)-1; i++ {
pair := Pair{string(chain[i]), string(chain[i+1])}
poly[pair]++
}
for n := 0; n < steps; n++ {
newPoly := make(map[Pair]int)
for pair, num := range poly {
text := string(pair.L) + string(pair.R)
val := rules[string(text)]
newPair := Pair{pair.L, val}
newPoly[newPair] += num
newPair = Pair{val, pair.R}
newPoly[newPair] += num
}
// Add the new pairs back in
poly = newPoly
/*
for key, value := range newPoly {
poly[key] += value
}
*/
newPoly = nil
}
// Count up letters
score := make(map[string]int)
for key, value := range poly {
score[key.L] += value
}
// And finally add one for the end of the template
score[string(chain[len(chain)-1])]++
// Now find the min and max values
min := score["N"]
max := 0
for _, value := range score {
if value < min {
min = value
} else if value > max {
max = value
}
}
fmt.Printf("%d - %d = %d", max, min, max-min)
}
func main() {
text := utils.ReadInput(1)
part1(text, 10)
part2(text, 40)
}
|
package ravendb
var _ ILazyOperation = &LazyAggregationQueryOperation{}
// LazyAggregationQueryOperation represents lazy aggregation query operation
type LazyAggregationQueryOperation struct {
conventions *DocumentConventions
indexQuery *IndexQuery
invokeAfterQueryExecuted func(*QueryResult)
processResults func(*QueryResult, *DocumentConventions) (map[string]*FacetResult, error)
result map[string]*FacetResult
queryResult *QueryResult
requiresRetry bool
}
func newLazyAggregationQueryOperation(conventions *DocumentConventions, indexQuery *IndexQuery, invokeAfterQueryExecuted func(*QueryResult),
processResults func(*QueryResult, *DocumentConventions) (map[string]*FacetResult, error)) *LazyAggregationQueryOperation {
return &LazyAggregationQueryOperation{
conventions: conventions,
indexQuery: indexQuery,
invokeAfterQueryExecuted: invokeAfterQueryExecuted,
processResults: processResults,
}
}
// needed for ILazyOperation
func (o *LazyAggregationQueryOperation) createRequest() *getRequest {
request := &getRequest{
url: "/queries",
method: "POST",
query: "?queryHash=" + o.indexQuery.GetQueryHash(),
content: NewIndexQueryContent(o.conventions, o.indexQuery),
}
return request
}
// needed for ILazyOperation
func (o *LazyAggregationQueryOperation) getResult(results interface{}) error {
return setInterfaceToValue(results, o.result)
}
// needed for ILazyOperation
func (o *LazyAggregationQueryOperation) getQueryResult() *QueryResult {
return o.queryResult
}
// needed for ILazyOperation
func (o *LazyAggregationQueryOperation) isRequiresRetry() bool {
return o.requiresRetry
}
// needed for ILazyOperation
func (o *LazyAggregationQueryOperation) handleResponse(response *GetResponse) error {
if response.IsForceRetry {
o.result = nil
o.requiresRetry = true
return nil
}
var queryResult *QueryResult
err := jsonUnmarshal(response.Result, &queryResult)
if err != nil {
return err
}
return o.handleResponse2(queryResult)
}
func (o *LazyAggregationQueryOperation) handleResponse2(queryResult *QueryResult) error {
var err error
o.invokeAfterQueryExecuted(queryResult)
o.result, err = o.processResults(queryResult, o.conventions)
o.queryResult = queryResult
return err
}
|
package chat
var (
PromoteCmd = "!promote"
DemoteCmd = "!demote"
JoinCmd = "!join"
PartCmd = "!part"
BlockCmd = "!block"
)
|
/*
* Created by lintao on 2023/7/27 下午2:36
* Copyright © 2020-2023 LINTAO. All rights reserved.
*
*/
package data
//
//func TestNewUserDataSource(t *testing.T) {
//
// dbMock, _, err := sqlmock.New()
// if err != nil {
// t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
// }
// defer func() {
// if err = dbMock.Close(); err != nil {
// fmt.Println(err)
// }
// }()
// dataSource, err := db.NewTestDataSource(dbMock)
// if err != nil {
// t.Fatal(err)
// }
// type args struct {
// dataSource *db.DataSource
// }
//
// tests := []struct {
// name string
// args args
// want *UserDataSource
// }{
// {
// args: args{dataSource: dataSource},
// want: NewUserDataSource(dataSource),
// },
// }
// for _, tt := range tests {
// t.Run(tt.name, func(t *testing.T) {
// if got := NewUserDataSource(tt.args.dataSource); !reflect.DeepEqual(got, tt.want) {
// t.Errorf("NewUserDataSource() = %v, want %v", got, tt.want)
// }
// })
// }
//}
//
//func TestUserDataSource_CreateUser(t *testing.T) {
//
// dbMock, mock, err := sqlmock.New()
// if err != nil {
// t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
// }
// defer func() {
// if err = dbMock.Close(); err != nil {
// fmt.Println(err)
// }
// }()
//
// mock.ExpectExec(
// "INSERT INTO user").
// WithArgs("string", "string", 1, "string", "string", nil).
// WillReturnResult(sqlmock.NewResult(1, 1))
//
// database, err := db.NewTestDataSource(dbMock)
// if err != nil {
// t.Fatal(err)
// }
//
// type fields struct {
// dataSource *db.DataSource
// }
// type args struct {
// param model.User
// }
// tests := []struct {
// name string
// fields fields
// args args
// wantId int64
// wantErr bool
// }{
// {
// fields: fields{dataSource: database},
// //args: args{param: struct {
// // param.APIQuery
// // model.User
// //}{User: model.User{
// // Name: "string",
// // Account: "string",
// // Password: "string",
// // Phone: "string",
// // Status: 1,
// //}}},
// },
// }
// for _, tt := range tests {
// t.Run(tt.name, func(t *testing.T) {
// this := NewUserDataSource(tt.fields.dataSource)
// gotId, err := this.CreateUser(tt.args.param)
// if (err != nil) != tt.wantErr {
// t.Errorf("UserDataSource.CreateUser() error = %v, wantErr %v", err, tt.wantErr)
// return
// }
// if gotId != tt.wantId {
// t.Errorf("UserDataSource.CreateUser() = %v, want %v", gotId, tt.wantId)
// }
// if err := mock.ExpectationsWereMet(); err != nil {
// t.Errorf("there were unfulfilled expectations: %s", err)
// }
// })
// }
//}
//
//func TestUserDataSource_GetUserById(t *testing.T) {
// dbMock, mock, err := sqlmock.New()
// if err != nil {
// t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
// }
// defer func() {
// if err = dbMock.Close(); err != nil {
// fmt.Println(err)
// }
// }()
//
// rows := sqlmock.NewRows([]string{"id", "name", "account", "password", "phone", "status", "created"}).
// AddRow(1, "string", "string", "string", "string", 0, nil)
// sql := regexp.QuoteMeta("SELECT `id`, `name`, `phone`, `status`, `account`, `password`, `created` FROM `user` WHERE `id`=? LIMIT 1")
// mock.ExpectQuery(sql).WithArgs(1).WillReturnRows(rows)
//
// database, err := db.NewTestDataSource(dbMock)
// if err != nil {
// t.Fatal(err)
// }
//
// type fields struct {
// dataSource *db.DataSource
// }
// type args struct {
// id int64
// }
// tests := []struct {
// name string
// fields fields
// args args
// wantUser model.User
// wantErr bool
// }{
// {
// fields: fields{dataSource: database},
// args: args{id: 1},
// wantUser: model.User{Id: 1, Name: "string", Account: "string", Password: "string", Phone: "string", Status: 0},
// wantErr: false,
// },
// }
// for _, tt := range tests {
// t.Run(tt.name, func(t *testing.T) {
// this := NewUserDataSource(tt.fields.dataSource)
// gotUser, err := this.GetUserByID(tt.args.id)
// if (err != nil) != tt.wantErr {
// t.Errorf("UserDataSource.GetUserByID() error = %v, wantErr %v", err, tt.wantErr)
// return
// }
// if !reflect.DeepEqual(gotUser, tt.wantUser) {
// t.Errorf("UserDataSource.GetUserByID() = %v, want %v", gotUser, tt.wantUser)
// }
// if err := mock.ExpectationsWereMet(); err != nil {
// t.Errorf("there were unfulfilled expectations: %s", err)
// }
// })
// }
//}
//
//func TestUserDataSource_FindUser(t *testing.T) {
//
// dbMock, mock, err := sqlmock.New()
// if err != nil {
// t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
// }
// defer func() {
// if err = dbMock.Close(); err != nil {
// fmt.Println(err)
// }
// }()
//
// rows := sqlmock.NewRows([]string{"count(*)"}).AddRow(20)
// mock.ExpectQuery("^SELECT count(.+)$").WillReturnRows(rows)
//
// rows = sqlmock.NewRows([]string{"id", "name", "account", "password", "phone", "status", "created"}).
// AddRow(1, "string", "string", "string", "string", 0, nil)
// sql := regexp.QuoteMeta("SELECT `id`, `name`, `phone`, `status`, `account`, `password`, `created` FROM `user` LIMIT 20")
//
// mock.ExpectQuery(sql).WillReturnRows(rows)
// database, err := db.NewTestDataSource(dbMock)
// if err != nil {
// t.Fatal(err)
// }
//
// type fields struct {
// dataSource *db.DataSource
// }
// type args struct {
// param model.User
// }
// tests := []struct {
// name string
// fields fields
// args args
// wantUser []model.User
// wantTotal int64
// wantErr bool
// }{
// {
// fields: fields{dataSource: database},
// args: args{param: model.User{}},
// wantErr: false,
// wantUser: []model.User{{Id: 1, Name: "string", Account: "string", Password: "string", Phone: "string", Status: 0}},
// wantTotal: 20,
// },
// }
// for _, tt := range tests {
// t.Run(tt.name, func(t *testing.T) {
// this := &UserDataSource{
// dataSource: tt.fields.dataSource,
// }
// gotUser, gotTotal, err := this.FindUser(tt.args.param)
// if (err != nil) != tt.wantErr {
// t.Errorf("UserDataSource.FindUser() error = %v, wantErr %v", err, tt.wantErr)
// return
// }
// if !reflect.DeepEqual(gotUser, tt.wantUser) {
// t.Errorf("UserDataSource.FindUser() gotUser = %v, want %v", gotUser, tt.wantUser)
// }
// if gotTotal != tt.wantTotal {
// t.Errorf("UserDataSource.FindUser() gotTotal = %v, want %v", gotTotal, tt.wantTotal)
// }
// if err := mock.ExpectationsWereMet(); err != nil {
// t.Errorf("there were unfulfilled expectations: %s", err)
// }
// })
// }
//}
//
//func TestUserDataSource_DeleteUserById(t *testing.T) {
// dbMock, mock, err := sqlmock.New()
// if err != nil {
// t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
// }
// defer func() {
// if err = dbMock.Close(); err != nil {
// fmt.Println(err)
// }
// }()
//
// mock.ExpectExec("DELETE FROM `user` WHERE `id`=?").
// WithArgs(1).
// WillReturnResult(sqlmock.NewResult(1, 1))
//
// database, err := db.NewTestDataSource(dbMock)
// if err != nil {
// t.Fatal(err)
// }
// type fields struct {
// dataSource *db.DataSource
// }
// type args struct {
// id int64
// }
// tests := []struct {
// name string
// fields fields
// args args
// wantErr bool
// }{
// {
// fields: fields{dataSource: database},
// args: args{id: 1},
// wantErr: false,
// },
// }
// for _, tt := range tests {
// t.Run(tt.name, func(t *testing.T) {
// this := &UserDataSource{
// dataSource: tt.fields.dataSource,
// }
// if err := this.DeleteUserByID(tt.args.id); (err != nil) != tt.wantErr {
// t.Errorf("UserDataSource.DeleteUserByID() error = %v, wantErr %v", err, tt.wantErr)
// }
// if err := mock.ExpectationsWereMet(); err != nil {
// t.Errorf("there were unfulfilled expectations: %s", err)
// }
// })
// }
//}
//
//func TestUserDataSource_UpdateUser(t *testing.T) {
//
// dbMock, mock, err := sqlmock.New()
// if err != nil {
// t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
// }
// //defer func() {
// // if err = dbMock.Close(); err != nil {
// // t.Fatal(err)
// // }
// //}()
//
// mock.ExpectExec("UPDATE `user`").
// WithArgs("lin", 1).
// WillReturnResult(sqlmock.NewResult(1, 1))
//
// dataSource, err := db.NewTestDataSource(dbMock)
// if err != nil {
// t.Fatal(err)
// }
//
// type fields struct {
// dataSource *db.DataSource
// }
// type args struct {
// param model.User
// id int64
// }
// tests := []struct {
// name string
// fields fields
// args args
// wantErr bool
// }{
// {
// fields: fields{dataSource: dataSource},
// args: args{param: model.User{Name: "lin"}, id: 1},
// wantErr: false,
// },
// }
// for _, tt := range tests {
// t.Run(tt.name, func(t *testing.T) {
//
// this := NewUserDataSource(dataSource)
// if err := this.UpdateUser(tt.args.param, tt.args.id); (err != nil) != tt.wantErr {
// t.Errorf("UserDataSource.UpdateUser() error = %v, wantErr %v", err, tt.wantErr)
// }
//
// if err := mock.ExpectationsWereMet(); err != nil {
// t.Errorf("there were unfulfilled expectations: %s", err)
// }
// })
// }
//}
|
package main
import (
"errors"
"fmt"
"log"
"time"
"github.com/streadway/amqp"
)
func failOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
}
}
var (
conn *amqp.Connection
ch *amqp.Channel
err error
)
func reconnect() (<-chan amqp.Delivery, error) {
var err error
conn, err = amqp.Dial("amqp://nana:nana@192.168.1.108:5672/")
if err != nil {
return nil, errors.New("Failed to connect to RabbitMQ")
}
ch, err = conn.Channel()
if err != nil {
return nil, errors.New("Failed to connect to RabbitMQ")
}
m := make(amqp.Table)
m["x-max-length"] = int64(2)
m["x-overflow"] = "reject-publish"
q, err := ch.QueueDeclare(
"hello33", // name
true, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
m, // arguments
)
if err != nil {
return nil, err
}
msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
false, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
m, // args
)
if err != nil {
return nil, errors.New("Failed to register a consumer")
}
return msgs, nil
}
func main() {
/*
//conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
conn, err := amqp.Dial("amqp://nana:nana@192.168.1.108:5672/")
failOnError(err, "Failed to connect to RabbitMQ")
defer conn.Close()
ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()
*/
msgs, err := reconnect()
if err != nil {
fmt.Println("errrrrrr:", err)
return
}
defer conn.Close()
defer ch.Close()
forever := make(chan bool)
go func() {
for {
RECONNECT:
select {
case msg, ok := <-msgs:
if !ok {
fmt.Printf("what???-------------------\n")
for {
time.Sleep(time.Second * 1)
msgs, err = reconnect()
if err != nil {
fmt.Println(err)
} else if err == nil {
goto RECONNECT
}
}
}
time.Sleep(time.Second * 3)
msg.Reject(false)
log.Printf("Received a message: %s", msg.Body)
}
}
}()
log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever
}
|
package tsm1
import (
"reflect"
"testing"
"time"
)
func Test_EntriesAdd(t *testing.T) {
e := newEntries()
v1 := NewValue(time.Unix(2, 0).UTC(), 1.0)
v2 := NewValue(time.Unix(3, 0).UTC(), 2.0)
v3 := NewValue(time.Unix(1, 0).UTC(), 2.0)
e.add(uint64(100), []Value{v1, v2})
if e.size != uint64(v1.Size()+v2.Size()) {
t.Fatal("adding points to entry, wrong size")
}
e.add(uint64(100), []Value{v3})
if e.size != uint64(v1.Size()+v2.Size()+v3.Size()) {
t.Fatal("adding point to entry, wrong size")
}
}
func Test_EntriesDedupe(t *testing.T) {
e := newEntries()
v0 := NewValue(time.Unix(4, 0).UTC(), 1.0)
v1 := NewValue(time.Unix(2, 0).UTC(), 2.0)
v2 := NewValue(time.Unix(3, 0).UTC(), 3.0)
v3 := NewValue(time.Unix(3, 0).UTC(), 4.0)
e.add(uint64(100), []Value{v0, v1})
e.add(uint64(200), []Value{v2})
e.add(uint64(400), []Value{v3})
values := e.dedupe()
if len(values) != 3 {
t.Fatalf("cloned values is wrong length, got %d", len(values))
}
if !reflect.DeepEqual(values[0], v1) {
t.Fatal("0th point does not equal v1:", values[0], v1)
}
if !reflect.DeepEqual(values[1], v3) {
t.Fatal("1st point does not equal v3:", values[0], v3)
}
if !reflect.DeepEqual(values[2], v0) {
t.Fatal("2nd point does not equal v0:", values[0], v0)
}
}
func Test_EntriesEvict(t *testing.T) {
e := newEntries()
v0 := NewValue(time.Unix(1, 0).UTC(), 1.0)
v1 := NewValue(time.Unix(2, 0).UTC(), 2.0)
v2 := NewValue(time.Unix(3, 0).UTC(), 3.0)
e.add(uint64(100), []Value{v0, v1})
e.add(uint64(200), []Value{v2})
if e.size != uint64(v0.Size()+v1.Size()+v2.Size()) {
t.Fatal("wrong size post eviction:", e.size)
}
values := e.dedupe()
if len(values) != 3 {
t.Fatalf("cloned values is wrong length, got %d", len(values))
}
if !reflect.DeepEqual(values[0], v0) {
t.Fatal("0th point does not equal v0:", values[0], v0)
}
if !reflect.DeepEqual(values[1], v1) {
t.Fatal("1st point does not equal v1:", values[0], v1)
}
if !reflect.DeepEqual(values[2], v2) {
t.Fatal("2nd point does not equal v2:", values[0], v2)
}
e.evict(100)
if e.size != uint64(v2.Size()) {
t.Fatalf("wrong size post eviction, exp: %d, got %d:", v2.Size(), e.size)
}
values = e.dedupe()
if len(values) != 1 {
t.Fatalf("purged cloned values is wrong length, got %d", len(values))
}
if !reflect.DeepEqual(values[0], v2) {
t.Fatal("0th point does not equal v1:", values[0], v2)
}
e.evict(200)
if e.size != 0 {
t.Fatal("wrong size post eviction of last point:", e.size)
}
values = e.dedupe()
if len(values) != 0 {
t.Fatalf("purged cloned values is wrong length, got %d", len(values))
}
}
func Test_NewCache(t *testing.T) {
c := NewCache(100)
if c == nil {
t.Fatalf("failed to create new cache")
}
if c.MaxSize() != 100 {
t.Fatalf("new cache max size not correct")
}
if c.Size() != 0 {
t.Fatalf("new cache size not correct")
}
if c.Checkpoint() != 0 {
t.Fatalf("new checkpoint not correct")
}
if len(c.Keys()) != 0 {
t.Fatalf("new cache keys not correct: %v", c.Keys())
}
}
func Test_CacheWrite(t *testing.T) {
v0 := NewValue(time.Unix(1, 0).UTC(), 1.0)
v1 := NewValue(time.Unix(2, 0).UTC(), 2.0)
v2 := NewValue(time.Unix(3, 0).UTC(), 3.0)
values := Values{v0, v1, v2}
valuesSize := uint64(v0.Size() + v1.Size() + v2.Size())
c := MustNewCache(3 * valuesSize)
if err := c.Write("foo", values, 100); err != nil {
t.Fatalf("failed to write key foo to cache: %s", err.Error())
}
if err := c.Write("bar", values, 100); err != nil {
t.Fatalf("failed to write key foo to cache: %s", err.Error())
}
if n := c.Size(); n != 2*valuesSize {
t.Fatalf("cache size incorrect after 2 writes, exp %d, got %d", 2*valuesSize, n)
}
if exp, keys := []string{"bar", "foo"}, c.Keys(); !reflect.DeepEqual(keys, exp) {
t.Fatalf("cache keys incorrect after 2 writes, exp %v, got %v", exp, keys)
}
}
func Test_CacheValues(t *testing.T) {
v0 := NewValue(time.Unix(1, 0).UTC(), 0.0)
v1 := NewValue(time.Unix(2, 0).UTC(), 2.0)
v2 := NewValue(time.Unix(3, 0).UTC(), 3.0)
v3 := NewValue(time.Unix(1, 0).UTC(), 1.0)
v4 := NewValue(time.Unix(4, 0).UTC(), 4.0)
c := MustNewCache(512)
if deduped := c.Values("no such key"); deduped != nil {
t.Fatalf("Values returned for no such key")
}
if err := c.Write("foo", Values{v0, v1, v2, v3}, 100); err != nil {
t.Fatalf("failed to write 3 values, key foo to cache: %s", err.Error())
}
if err := c.Write("foo", Values{v4}, 200); err != nil {
t.Fatalf("failed to write 1 value, key foo to cache: %s", err.Error())
}
expValues := Values{v3, v1, v2, v4}
if deduped := c.Values("foo"); !reflect.DeepEqual(expValues, deduped) {
t.Fatalf("deduped values for foo incorrect, exp: %v, got %v", expValues, deduped)
}
}
func Test_CacheCheckpoint(t *testing.T) {
v0 := NewValue(time.Unix(1, 0).UTC(), 1.0)
c := MustNewCache(1024)
if err := c.SetCheckpoint(50); err != nil {
t.Fatalf("failed to set checkpoint: %s", err.Error())
}
if err := c.Write("foo", Values{v0}, 100); err != nil {
t.Fatalf("failed to write key foo to cache: %s", err.Error())
}
if err := c.SetCheckpoint(25); err != ErrCacheInvalidCheckpoint {
t.Fatalf("unexpectedly set checkpoint")
}
if err := c.Write("foo", Values{v0}, 30); err != ErrCacheInvalidCheckpoint {
t.Fatalf("unexpectedly wrote key foo to cache")
}
}
func Test_CacheWriteMemoryExceeded(t *testing.T) {
v0 := NewValue(time.Unix(1, 0).UTC(), 1.0)
v1 := NewValue(time.Unix(2, 0).UTC(), 2.0)
c := MustNewCache(uint64(v1.Size()))
if err := c.Write("foo", Values{v0}, 100); err != nil {
t.Fatalf("failed to write key foo to cache: %s", err.Error())
}
if exp, keys := []string{"foo"}, c.Keys(); !reflect.DeepEqual(keys, exp) {
t.Fatalf("cache keys incorrect after writes, exp %v, got %v", exp, keys)
}
if err := c.Write("bar", Values{v1}, 100); err != ErrCacheMemoryExceeded {
t.Fatalf("wrong error writing key bar to cache")
}
// Set too-early checkpoint, write should still fail.
if err := c.SetCheckpoint(50); err != nil {
t.Fatalf("failed to set checkpoint: %s", err.Error())
}
if err := c.Write("bar", Values{v1}, 100); err != ErrCacheMemoryExceeded {
t.Fatalf("wrong error writing key bar to cache")
}
// Set later checkpoint, write should then succeed.
if err := c.SetCheckpoint(100); err != nil {
t.Fatalf("failed to set checkpoint: %s", err.Error())
}
if err := c.Write("bar", Values{v1}, 100); err != nil {
t.Fatalf("failed to write key bar to checkpointed cache: %s", err.Error())
}
if exp, keys := []string{"bar"}, c.Keys(); !reflect.DeepEqual(keys, exp) {
t.Fatalf("cache keys incorrect after writes, exp %v, got %v", exp, keys)
}
}
func Benchmark_CacheWriteSameKeySameCheckpoint(b *testing.B) {
key := "foo"
checkpoint := uint64(100)
values := make(Values, 5000)
for i := range values {
values[i] = NewValue(time.Unix(int64(i), 0).UTC(), 1.0)
}
c := MustNewCache(uint64(10000 * values.Size()))
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := c.Write(key, values, checkpoint); err != nil {
b.Fatalf("unexpected error writing to cache: %v", err)
}
}
}
func Benchmark_CacheWriteSameKeyDifferentCheckpoint(b *testing.B) {
key := "foo"
values := make(Values, 5000)
for i := range values {
values[i] = NewValue(time.Unix(int64(i), 0).UTC(), 1.0)
}
c := MustNewCache(uint64(10000 * values.Size()))
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := c.Write(key, values, uint64(i)); err != nil {
b.Fatalf("unexpected error writing to cache: %v", err)
}
}
}
func MustNewCache(size uint64) *Cache {
c := NewCache(size)
if c == nil {
panic("failed to create cache")
}
return c
}
|
package myhashmap
import "testing"
func TestMyHashMap(t *testing.T) {
var value int
hashMap := Constructor()
hashMap.Put(1, 1)
hashMap.Put(2, 2)
if value = hashMap.Get(1); value != 1 {
t.Errorf("hashMap.Get(1), get %d, expect %d", value, 1)
}
if value = hashMap.Get(3); value != -1 {
t.Errorf("hashMap.Get(3), get %d, expect %d", value, -1)
}
hashMap.Put(2, 1)
if value = hashMap.Get(2); value != 1 {
t.Errorf("hashMap.Get(2), get %d, expect %d", value, 1)
}
hashMap.Remove(2)
if value = hashMap.Get(2); value != -1 {
t.Errorf("hashMap.Get(2), get %d, expect %d", value, -1)
}
}
|
package api
import (
"services"
"github.com/gorilla/mux"
"net/http"
"models"
)
type PictureApiController struct {
r *mux.Router
service *services.PictureService
}
func NewPictureApiController(r *mux.Router) *PictureApiController {
return &PictureApiController{
r: r,
service: services.NewPictureService(),
}
}
func (pac *PictureApiController) RegisterEndpoints() {
pac.r.Methods(http.MethodGet).
HeadersRegexp(HeaderAccept, MediaTypeJson).
//Name(capabilities.UpdateCategory.String()).
//Handler(alice.New(auth.Auth, auth.Acl).ThenFunc(pac.ListHandler))
HandlerFunc(pac.ListHandler)
pac.r.Methods(http.MethodPost).
HeadersRegexp(HeaderAccept, MediaTypeJson,
HeaderContentType, MediaTypeJson).
//Name(capabilities.UpdateCategory.String()).
//Handler(alice.New(auth.Auth, auth.Acl).ThenFunc(pac.CreateHandler))
HandlerFunc(pac.CreateHandler)
pac.r.Path("/{id}").
Methods(http.MethodPut).
HeadersRegexp(HeaderAccept, MediaTypeJson,
HeaderContentType, MediaTypeJson).
//Name(capabilities.UpdateCategory.String()).
//Handler(alice.New(auth.Auth, auth.Acl).ThenFunc(pac.EditHandler))
HandlerFunc(pac.EditHandler)
pac.r.Path("/{id}").
Methods(http.MethodDelete).
//Name(capabilities.UpdateCategory.String()).
//Handler(alice.New(auth.Auth, auth.Acl).ThenFunc(pac.DeleteHandler))
HandlerFunc(pac.DeleteHandler)
}
func (pac *PictureApiController) ListHandler(w http.ResponseWriter, r *http.Request) {
/*var query models.Query
if err := ParseForm(r, &query); err != nil {
renderer.JSON(w, http.StatusBadRequest, BadRequestErr(err.Error()))
return
}*/
pictures, err := pac.service.GetPictures()
if err != nil {
renderer.JSON(w, http.StatusInternalServerError, ServerErr(err.Error()))
return
}
renderer.JSON(w, http.StatusOK, pictures)
}
func (pac *PictureApiController) CreateHandler(w http.ResponseWriter, r *http.Request) {
var picture models.NewPicture
if err := ParseJson(r.Body, &picture); err != nil {
renderer.JSON(w, http.StatusBadRequest, BadRequestErr(err.Error()))
return
}
if err := picture.Validate(); err != nil {
renderer.JSON(w, 422, models.ValidationErr(err))
return
}
/*var c models.NewCategoryRequest
if err := ParseJson(r.Body, &c); err != nil {
renderer.JSON(w, http.StatusBadRequest, BadRequestErr(err.Error()))
return
}
user, err := auth.GetUserPrincipal(r)
if err != nil {
renderer.JSON(w, http.StatusUnauthorized, auth.UnauthorizedErr(err.Error()))
return
}
category := models.NewCategory{
Name: c.Name,
Description: c.Description,
Author: user,
}
if c.Parent.Valid() {
parent, err := pac.service.GetCategory(c.Parent.Hex())
if err != nil {
renderer.JSON(w, http.StatusBadRequest, BadRequestErr(err.Error()))
return
}
p := converters.Category2Taxonomy(parent)
category.Parent = &p
}*/
saved, err := pac.service.CreateAndSavePicture(&picture)
if err != nil {
renderer.JSON(w, http.StatusInternalServerError, ServerErr(err.Error()))
return
}
renderer.JSON(w, http.StatusCreated, saved)
}
func (pac *PictureApiController) EditHandler(w http.ResponseWriter, r *http.Request) {
/*var c models.UpdateCategoryRequest
if err := ParseJson(r.Body, &c); err != nil {
renderer.JSON(w, http.StatusBadRequest, BadRequestErr(err.Error()))
return
}
if ok, err := c.Validate(); !ok {
renderer.JSON(w, 422, models.ValidationErr(err))
return
}
user, err := auth.GetUserPrincipal(r)
if err != nil {
renderer.JSON(w, http.StatusInternalServerError, ServerErr(err.Error()))
return
}
params := mux.Vars(r)
category := models.UpdateCategory{
Id: bson.ObjectIdHex(params["id"]),
Name: c.Name,
Slug: slug.Make(c.Name),
Description: c.Description,
Editor: user,
}
if c.Parent.Valid() {
parent, err := pac.service.GetCategory(c.Parent.Hex())
if err != nil {
renderer.JSON(w, http.StatusBadRequest, BadRequestErr(err.Error()))
return
}
category.Parent = converters.Category2Taxonomy(parent)
}
if err := pac.service.UpdateCategory(&category); err != nil {
renderer.JSON(w, http.StatusInternalServerError, ServerErr(err.Error()))
return
}*/
renderer.JSON(w, http.StatusOK, &models.Picture{})
}
func (pac *PictureApiController) DeleteHandler(w http.ResponseWriter, r *http.Request) {
/*vars := mux.Vars(r)
category, err := pac.service.GetCategory(vars["id"])
if err != nil {
renderer.JSON(w, http.StatusBadRequest, BadRequestErr(err.Error()))
return
}
if err := pac.service.DeleteCategory(category.Id.Hex()); err != nil {
renderer.JSON(w, http.StatusInternalServerError, ServerErr(err.Error()))
return
}*/
renderer.JSON(w, http.StatusNoContent, nil)
}
|
// Copyright 2014 go-beacon authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package main
import (
"path/filepath"
"github.com/BurntSushi/toml"
)
type configFile struct {
Debug bool `toml:"debug"`
TemplatesDir string `toml:"templates_dir"`
DocumentRoot string `toml:"document_root"`
BeaconURI string `toml:"beacon_uri"`
DB struct {
Redis string `toml:"redis"`
} `toml:"db"`
HTTP struct {
Addr string `toml:"addr"`
XHeaders bool `toml:"xheaders"`
} `toml:"http_server"`
HTTPS struct {
Addr string `toml:"addr"`
CertFile string `toml:"cert_file"`
KeyFile string `toml:"key_file"`
} `toml:"https_server"`
Backend struct {
BackendURL string `toml:"backend_url"`
FlushInterval int `toml:"flush_interval"`
} `toml:"backend"`
}
// LoadConfig reads and parses the configuration file.
func loadConfig(filename string) (*configFile, error) {
c := &configFile{}
if _, err := toml.DecodeFile(filename, c); err != nil {
return nil, err
}
// Make files' path relative to the config file's directory.
basedir := filepath.Dir(filename)
relativePath(basedir, &c.DocumentRoot)
relativePath(basedir, &c.TemplatesDir)
relativePath(basedir, &c.HTTPS.CertFile)
relativePath(basedir, &c.HTTPS.KeyFile)
return c, nil
}
func relativePath(basedir string, path *string) {
p := *path
if p != "" && p[0] != '/' {
*path = filepath.Join(basedir, p)
}
}
|
package main
import (
"database/sql"
"flag"
"fmt"
"github.com/gizak/termui"
"github.com/jdormit/logr/offsets"
"github.com/jdormit/logr/reader"
"github.com/jdormit/logr/timeseries"
"github.com/jdormit/logr/ui"
_ "github.com/mattn/go-sqlite3"
"log"
"os"
"os/signal"
"path"
"time"
)
const defaultTimescale = 5
const defaultGranularity = 10
const defaultAlertThreshold = 10.0
const defaultAlertInterval = 120
var defaultLogPath = path.Join(os.TempDir(), "access.log")
func usage() {
fmt.Printf(`A small utility to monitor a server log file
USAGE:
%s [OPTIONS] [log_file_path]
ARGS:
log_file_path
The path to the log file to monitor (default %s)
OPTIONS:
-h, -help
Display this message and exit
`, os.Args[0], defaultLogPath)
flag.PrintDefaults()
}
func loadDB(dbPath string) (db *sql.DB, err error) {
db, err = sql.Open("sqlite3", fmt.Sprintf("%s", dbPath))
if err != nil {
return
}
_, err = db.Exec(timeseries.CreateLogLinesTableStmt)
if err != nil {
return
}
_, err = db.Exec(offsets.CreateOffsetsTableStmt)
return
}
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
flag.Usage = usage
defaultDebugLogPath := path.Join(os.Getenv("HOME"), ".local", "share", "logr", "logr.log")
debugLogPath := flag.String("debugLogPath", defaultDebugLogPath, "The `path` to the file where logr will write debug logs")
defaultDbPath := path.Join(os.Getenv("HOME"), ".local", "share", "logr", "logr.sqlite")
dbPath := flag.String("dbPath", defaultDbPath, "The `path` to the SQLite database")
alertThreshold := flag.Float64("alertThreshold", defaultAlertThreshold, "The average number of requests per second over the alerting interval that will trigger an alert")
alertInterval := flag.Int("alertInterval", defaultAlertInterval, "The interval of time in seconds during which the number of requests per second must exceed the alert threshold to trigger an alert")
timescale := flag.Int("timescale", defaultTimescale, "The size of the reporting time window in minutes")
granularity := flag.Int("granularity", defaultGranularity, "The granularity of the traffic graph, i.e. the number of buckets into which traffic is divided.")
flag.Parse()
err := os.MkdirAll(path.Dir(*debugLogPath), 0755)
if err != nil {
log.Fatal(err)
}
err = os.Remove(*debugLogPath)
if err != nil && !os.IsNotExist(err) {
log.Fatal(err)
}
debugLogFile, err := os.Create(*debugLogPath)
if err != nil {
log.Fatal(err)
}
defer debugLogFile.Close()
log.SetOutput(debugLogFile)
err = os.MkdirAll(path.Dir(*dbPath), 0755)
if err != nil {
log.Fatal(err)
}
var logPath string
if flag.Arg(0) != "" {
logPath = flag.Arg(0)
} else {
logPath = defaultLogPath
}
db, err := loadDB(*dbPath)
if err != nil {
log.Fatal(err)
}
offsetPersister := offsets.OffsetPersister{db}
logReader := reader.NewLogReader(&offsetPersister, logPath)
interrupts := make(chan os.Signal, 1)
signal.Notify(interrupts, os.Interrupt)
updateTicker := time.NewTicker(time.Second).C
logChan := make(chan timeseries.LogLine, 24)
go logReader.TailLogFile(logChan)
defer logReader.Terminate()
logTimeSeries := timeseries.LogTimeSeries{db, logPath}
err = termui.Init()
if err != nil {
log.Fatal(err)
}
defer termui.Close()
uiState, err := ui.GetInitialUIState(&logTimeSeries, *timescale, *granularity,
*alertThreshold, *alertInterval)
if err != nil {
log.Fatal(err)
}
ui.Render(uiState)
uiEvents := termui.PollEvents()
for {
select {
case <-interrupts:
logReader.Terminate()
return
case e := <-uiEvents:
switch e.ID {
case "<C-c>":
logReader.Terminate()
return
case "<Resize>":
ui.Render(uiState)
}
case logLine := <-logChan:
_, err = logTimeSeries.Record(logLine)
if err != nil {
log.Printf("Error writing log line to database: %v", err)
}
case <-updateTicker:
uiState := ui.NextUIState(uiState, &logTimeSeries, time.Now())
ui.Render(uiState)
}
}
}
|
package behaviourtest
import (
"fmt"
"github.com/AsynkronIT/protoactor-go/actor"
"github.com/golang/protobuf/proto"
"github.com/saintEvol/go-rigger/rigger"
"time"
)
func Start() {
_ = rigger.Start(appName, "")
}
/*
hello world 应用
*/
// 应用名,应用标识
const appName = "behaviourtestapp"
func init() {
rigger.Register(appName, rigger.ApplicationBehaviourProducer(func() rigger.ApplicationBehaviour {
return &helloWorldApp{}
}))
// 依赖 rigger-amqp应用, 保证在启动helloWroldApp 前,会先启动 rigger-amqp
// rigger.DependOn("rigger-amqp")
}
type helloWorldApp struct {
}
func (h *helloWorldApp) OnRestarting(ctx actor.Context) {
}
// 如果返回的错误非空,则表示启动失败,则会停止启动后续进程
func (h *helloWorldApp) OnStarted(ctx actor.Context, args interface{}) error {
fmt.Print("start hello world")
return nil
}
func (h *helloWorldApp) OnPostStarted(ctx actor.Context, args interface{}) {
}
func (h *helloWorldApp) OnStopping(ctx actor.Context) {
}
func (h *helloWorldApp) OnStopped(ctx actor.Context) {
}
func (h *helloWorldApp) OnGetSupFlag(ctx actor.Context) (supFlag rigger.SupervisorFlag, childSpecs []*rigger.SpawnSpec) {
// 一对一
supFlag.StrategyFlag = rigger.OneForOne
// 最多尝试10次
supFlag.MaxRetries = 10
// 最多尝试1秒
supFlag.WithinDuration = 1 * time.Second
// 任何原因下都重启
supFlag.Decider = func(reason interface{}) actor.Directive {
return actor.RestartDirective
}
// 将helloWorldSup 设置为应用的子进程
childSpecs = []*rigger.SpawnSpec {
rigger.SpawnSpecWithKind(helloWorldSupName),
}
return
}
/*
helloWorld 的监控进程,负责对业务子进程的监控及重启
此进程不处理任何业务
*/
const helloWorldSupName = "helloWorldSup"
func init() {
rigger.Register(helloWorldSupName, rigger.SupervisorBehaviourProducer(func() rigger.SupervisorBehaviour {
return &helloWorldSup{}
}))
}
type helloWorldSup struct {
}
func (h helloWorldSup) OnRestarting(ctx actor.Context) {
}
// 如果返回非空,则表示启动失败,会停止后续进程的启动
func (h helloWorldSup) OnStarted(ctx actor.Context, args interface{}) error {
return nil
}
func (h helloWorldSup) OnPostStarted(ctx actor.Context, args interface{}) {
}
func (h helloWorldSup) OnStopping(ctx actor.Context) {
}
func (h helloWorldSup) OnStopped(ctx actor.Context) {
}
func (h helloWorldSup) OnGetSupFlag(ctx actor.Context) (supFlag rigger.SupervisorFlag, childSpecs []*rigger.SpawnSpec) {
childSpecs = []*rigger.SpawnSpec{
// 配置一个子进程(业务进程)
rigger.SpawnSpecWithKind(helloWorldServerName),
}
return
}
const helloWorldServerName = "helloWorldServer"
/*
helloWorld服务器, 负责响应外部消息,完成业务处理
*/
func init() {
rigger.Register(helloWorldServerName, rigger.GeneralServerBehaviourProducer(func() rigger.GeneralServerBehaviour {
return &helloWordServer{}
}))
}
type helloWordServer struct {
rigger.Behaviour // 让GenServer可以切换行为
}
func (h *helloWordServer) OnRestarting(ctx actor.Context) {
}
func (h *helloWordServer) OnStarted(ctx actor.Context, args interface{}) error {
h.Become(h.firstTime)
return nil
}
func (h *helloWordServer) OnPostStarted(ctx actor.Context, args interface{}) {
}
func (h *helloWordServer) OnStopping(ctx actor.Context) {
}
func (h *helloWordServer) OnStopped(ctx actor.Context) {
}
// 消息处理, 框架会根据需要将返回值回复给请求进程
func (h *helloWordServer) OnMessage(ctx actor.Context, message interface{}) proto.Message {
return nil
}
func (h *helloWordServer) firstTime(ctx actor.Context, message interface{}) proto.Message {
fmt.Printf("first time!!!\r\n")
h.Become(h.otherTime)
return nil
}
func (h *helloWordServer) otherTime(ctx actor.Context, message interface{}) proto.Message {
fmt.Printf("other time!!!\r\n")
return nil
}
|
// Command decrypt decrypts file encrypted with RSA public key, using matching
// RSA private key.
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"encoding/pem"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
)
var privKey, inFile, outFile string
func main() {
if len(privKey) == 0 || len(inFile) == 0 || len(outFile) == 0 {
flag.Usage()
os.Exit(1)
}
key, err := readPrivateKey(privKey)
if err != nil {
log.Fatal(err)
}
reader, err := os.Open(inFile)
if err != nil {
log.Fatal(err)
}
defer reader.Close()
header := make([]byte, 256)
if _, err := io.ReadFull(reader, header); err != nil {
log.Fatal(err)
}
secret, err := rsa.DecryptOAEP(sha1.New(), rand.Reader, key, header, nil)
if err != nil {
log.Fatal(err)
}
block, err := aes.NewCipher(secret)
if err != nil {
log.Fatal(err)
}
stream := cipher.NewCTR(block, header[:block.BlockSize()])
out, err := os.OpenFile(outFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
log.Fatal(err)
}
defer func() {
if err := out.Close(); err != nil {
log.Fatal(err)
}
}()
if _, err := io.Copy(out, &cipher.StreamReader{S: stream, R: reader}); err != nil {
log.Fatal(err)
}
}
func init() {
log.SetFlags(0)
flag.Usage = func() {
usageFmt := "Command %s decrypts file using private RSA key.\nUsage:\n"
fmt.Fprintf(os.Stderr, usageFmt, os.Args[0])
flag.PrintDefaults()
}
flag.StringVar(&privKey, "key", "", "path to private key in PEM format")
flag.StringVar(&inFile, "in", "", "path to encrypted file to decrypt")
flag.StringVar(&outFile, "out", "", "path to decrypted file to write")
flag.Parse()
}
// readPrivateKey reads and unmarshals RSA private key from PEM format file
func readPrivateKey(file string) (*rsa.PrivateKey, error) {
b, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
block, _ := pem.Decode(b)
if block == nil {
return nil, errors.New("failed to decode PEM file")
}
return x509.ParsePKCS1PrivateKey(block.Bytes)
}
|
// Copyright (c) 2014 ZeroStack Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package datastore
import (
"fmt"
"reflect"
"strings"
"time"
"github.com/zerostackinc/dbconn"
"github.com/zerostackinc/util"
)
// NewUpdateQuery returns a UpdateQuery instance given a typ. Typ needs to be
// a struct with column definitions with CQL tags. Refer to datastore_test
// for examples.
func NewUpdateQuery(typ reflect.Type) (*UpdateQuery, error) {
codec, err := getStructCodec(typ)
if err != nil {
return nil, err
}
return &UpdateQuery{
codec: codec,
ttl: noTTL,
updates: make(map[string]interface{}),
addOps: make(map[string]interface{}),
delOps: make(map[string]interface{}),
}, nil
}
// NewUpdateAllQuery returns a UpdateQuery instance with the filters and updates
// setup as per the input.
func NewUpdateAllQuery(src interface{}) (*UpdateQuery, error) {
einfo, err := newEntityInfo(src)
if err != nil {
return nil, err
}
codec := einfo.codec
q := &UpdateQuery{
codec: codec,
ttl: noTTL,
updates: make(map[string]interface{}),
addOps: make(map[string]interface{}),
delOps: make(map[string]interface{}),
}
// Get all values from the src. If the field below to primary key append it to
// the filter list. Else append it to the update list.
vals := einfo.getValues()
for i := 0; i < len(codec.cols); i++ {
if codec.pk.isPresent(codec.cols[i]) {
q = q.Filter(codec.cols[i], Equal, vals[i])
} else {
q = q.Update(codec.cols[i], vals[i])
}
}
return q, nil
}
// UpdateQuery represent a CQL update query.
type UpdateQuery struct {
filter []filter
ttl int64
updates map[string]interface{}
// add represent + operations on collection type fields
addOps map[string]interface{}
// del represent - operations on collection type fields
delOps map[string]interface{}
codec *structCodec
predicates []filter
err error
}
func (q *UpdateQuery) clone() *UpdateQuery {
x := *q
if len(q.filter) > 0 {
x.filter = make([]filter, len(q.filter))
copy(x.filter, q.filter)
}
if len(q.updates) > 0 {
x.updates = make(map[string]interface{})
for k, v := range q.updates {
x.updates[k] = v
}
}
return &x
}
// Filter returns a derivative query with a field-based filter.
// Args : The field name (with optional space), Operator, and value.
// Fields are compared against the provided value using the operator.
// Multiple filters are AND'ed together.
func (q *UpdateQuery) Filter(field string, op Operator,
value interface{}) *UpdateQuery {
q = q.clone()
f, err := createFilter(field, op, value)
if err != nil {
q.err = err
return q
}
q.filter = append(q.filter, *f)
return q
}
// TTL specifies ttl in seconds for the CQL update query.
func (q *UpdateQuery) TTL(ttl int64) (*UpdateQuery, error) {
if ttl < 0 {
return nil, fmt.Errorf("error ttl %d is less than zero", ttl)
}
q = q.clone()
q.ttl = ttl
return q, nil
}
// Update appends given fieldName to the list of columns that will be updated
// when query is executed.
func (q *UpdateQuery) Update(fieldName string,
fieldVal interface{}) *UpdateQuery {
q = q.clone()
q.updates[fieldName] = fieldVal
return q
}
// Add adds given val to field collection on given entity.
func (q *UpdateQuery) Add(field string, val interface{}) *UpdateQuery {
q = q.clone()
q.addOps[field] = val
return q
}
// Remove removes given val from field collection on given entity.
func (q *UpdateQuery) Remove(field string, val interface{}) *UpdateQuery {
q = q.clone()
q.delOps[field] = val
return q
}
// If returns a derivative query by appending the requested predicate.
func (q *UpdateQuery) If(field string, op Operator,
value interface{}) *UpdateQuery {
q = q.clone()
f, err := createFilter(field, op, value)
if err != nil {
q.err = err
return q
}
q.predicates = append(q.predicates, *f)
return q
}
func (q *UpdateQuery) toCQL() (cql string, args []interface{}, err error) {
setClause, setArgs, err := q.setClause()
if err != nil {
return "", nil, err
}
whereClause, whereArgs, err := getWhereClause(q.codec, q.filter)
if err != nil {
return "", nil, err
}
ifClause, ifArgs, err := getIfClause(q.codec, q.predicates)
if err != nil {
return "", nil, err
}
// UPDATE <schema> using TTL <ttl> <set-clause> <where-clause> <if-clause>
if q.ttl == noTTL {
cql = fmt.Sprintf("UPDATE %s %s %s %s", q.codec.columnFamily,
setClause, whereClause, ifClause)
} else {
cql = fmt.Sprintf("UPDATE %s USING TTL %d %s %s %s", q.codec.columnFamily,
q.ttl, setClause, whereClause, ifClause)
}
args = append(args, setArgs...)
args = append(args, whereArgs...)
args = append(args, ifArgs...)
return cql, args, nil
}
// CQL returns the CQL query statement corresponding to the update query.
func (q *UpdateQuery) CQL() (string, error) {
cql, _, err := q.toCQL()
return cql, err
}
// Run executes the update query.
func (q *UpdateQuery) Run(dbConn dbconn.DBConn) error {
defer util.LogExecutionTime(1, time.Now(), "datastore:update_query:run")
session := dbConn.GetSession()
if session == nil {
return fmt.Errorf("invalid session")
}
defer dbConn.ReleaseSession(session)
cql, args, err := q.toCQL()
if err != nil {
return err
}
cqlQ := session.Query(cql, args...)
if !q.isPredicateQuery() {
// If query is without predicates, nothing to CAS
return cqlQ.Exec()
}
// For update queries with predicates, ScanCAS will return the rows that
// describe if the query was successfully applied.
// If not, it populates the list of interfaces with the current value of the
// predicate field.
// ** Success case **
// [applied]
// -----------
// True
//
// ** Fail case **
// [applied] | finite_duration | life_in_days
// -----------+-----------------+--------------
// False | False | 0
// Construct list of interfaces of type same as the predicate fields.
previousVals := make([]interface{}, len(q.predicates))
for idx, filter := range q.predicates {
previousValInf := reflect.New(reflect.TypeOf(filter.Value)).Interface()
previousVals[idx] = previousValInf
}
queryHash := q.hash()
casLockManager.GetLock(queryHash)
defer casLockManager.ReleaseLock(queryHash)
applied, err := cqlQ.ScanCAS(previousVals...)
if err != nil {
return err
}
if !applied {
previousValsMap := make(map[string]interface{}, len(q.predicates))
for idx, filter := range q.predicates {
previousValsMap[filter.FieldName] = previousVals[idx]
}
return &ErrNotApplied{previousValsMap}
}
return nil
}
func (q *UpdateQuery) isPredicateQuery() bool {
return len(q.predicates) > 0
}
func (q *UpdateQuery) setClause() (string, []interface{}, error) {
if len(q.updates) <= 0 && len(q.addOps) <= 0 && len(q.delOps) <= 0 {
return "", nil, nil
}
updates := make([]string, len(q.updates)+len(q.addOps)+len(q.delOps))
setArgs := make([]interface{}, len(updates))
i := 0
for k, v := range q.updates {
updates[i] = fmt.Sprintf("%s = ?", k)
setArgs[i] = v
i++
}
for k, v := range q.addOps {
updates[i] = fmt.Sprintf("%s = %s + ?", k, k)
setArgs[i] = v
i++
}
for k, v := range q.delOps {
updates[i] = fmt.Sprintf("%s = %s - ?", k, k)
setArgs[i] = v
i++
}
setClause := fmt.Sprintf("SET %s", strings.Join(updates, ", "))
return setClause, setArgs, nil
}
// partitionKey returns a concatenated string of partition keys.
func (q *UpdateQuery) partitionKey() string {
pKeyGen := q.codec.columnFamily
for _, filter := range q.filter {
if !q.codec.pk.isPresentInPartitionKey(filter.FieldName) {
continue
}
pKeyGen = fmt.Sprintf("%s%s", pKeyGen,
interfacePtrStr(reflect.ValueOf(filter.Value)))
}
return pKeyGen
}
// hash returns the hash for partition key.
func (q *UpdateQuery) hash() int {
return util.HashStr(q.partitionKey())
}
|
package reduce
import "testing"
var examples = []struct {
want int
num int
}{
{
want: 6,
num: 14,
},
{
want: 4,
num: 8,
},
{
want: 12,
num: 123,
},
}
func Test_examples(t *testing.T) {
for i, e := range examples {
got := numberOfSteps(e.num)
if e.want != got {
t.Fatalf("\ni:%v\nwant:%v\ngot :%v\n", i, e.want, got)
}
}
}
|
package main
import (
"log"
"os"
"path/filepath"
"github.com/pkg/errors"
)
func main() {
desktop := filepath.Join(os.Getenv("HOME"), "Desktop")
// TODO configurable dir name
bak := filepath.Join(desktop, "bak")
if _, err := os.Stat(bak); os.IsNotExist(err) {
err = os.Mkdir(bak, 0777)
if err != nil {
log.Fatal(errors.Wrap(err, "making dir bak"))
}
}
files, err := filepath.Glob(filepath.Join(desktop, "*"))
if err != nil {
log.Fatal(err)
}
for _, file := range files {
if file == bak {
continue
}
err := os.Rename(file, filepath.Join(bak, filepath.Base(file)))
if err != nil {
log.Println(errors.Wrap(err, "moving file").Error())
}
}
}
|
package market
import (
"testing"
"fmt"
"github.com/yangxinwei/gin-demo-api/config"
)
func TestSearch(t *testing.T) {
config.InitConfig()
//keywords := `%yr,,d&b,b*ff%`
keywords := `Yiren`
if result, err := Search(keywords); err != nil {
fmt.Println(err)
} else {
fmt.Println(result)
}
}
func TestFilterWords(t *testing.T) {
keywords:=`%yr,,d&b,b*ff%`
keywords = FilterWords(keywords)
fmt.Println(keywords)
//output:
} |
package main
import "LeetCode"
func main() {
LeetCode.Code1010()
}
|
// Package smartling is a client implementation of the Smartling Translation
// API v2 as documented at https://help.smartling.com/v1.0/reference
package smartling
import (
"net/http"
"time"
)
type (
// LogFunction represents abstract logger function interface which
// can be used for setting up logging of library actions.
LogFunction func(format string, args ...interface{})
)
var (
// Version is a API SDK version, sent in User-Agent header.
Version = "1.0"
// DefaultBaseURL specifies base URL which will be used for calls unless
// other is specified in the Client struct.
DefaultBaseURL = "https://api.smartling.com"
// DefaultHTTPClient specifies default HTTP client which will be used
// for calls unless other is specified in the Client struct.
DefaultHTTPClient = http.Client{Timeout: 60 * time.Second}
// DefaultUserAgent is a string that will be sent in User-Agent header.
DefaultUserAgent = "smartling-api-sdk-go"
)
// Client represents Smartling API client.
type Client struct {
BaseURL string
Credentials *Credentials
HTTP *http.Client
Logger struct {
Infof LogFunction
Debugf LogFunction
}
UserAgent string
}
// NewClient returns new Smartling API client with specified authentication
// data.
func NewClient(userID string, tokenSecret string) *Client {
return &Client{
BaseURL: DefaultBaseURL,
Credentials: &Credentials{
UserID: userID,
Secret: tokenSecret,
},
HTTP: &DefaultHTTPClient,
Logger: struct {
Infof LogFunction
Debugf LogFunction
}{
Infof: func(string, ...interface{}) {},
Debugf: func(string, ...interface{}) {},
},
UserAgent: DefaultUserAgent + "/" + Version,
}
}
// SetInfoLogger sets logger function which will be called for logging
// informational messages like progress of file download and so on.
func (client *Client) SetInfoLogger(logger LogFunction) *Client {
client.Logger.Infof = logger
return client
}
// SetDebugLogger sets logger function which will be called for logging
// internal information like HTTP requests and their responses.
func (client *Client) SetDebugLogger(logger LogFunction) *Client {
client.Logger.Debugf = logger
return client
}
|
package game
import (
"errors"
"time"
)
var ErrGameInterrupt = errors.New("game was finished by user")
type Game struct {
painter *Painter
events <-chan Event
ticker *time.Ticker
arena Arena
}
func NewGame(painter *Painter, events <-chan Event, arena Arena) *Game {
return &Game{
painter: painter,
events: events,
arena: arena,
ticker: time.NewTicker(time.Millisecond * 50),
}
}
func (g *Game) updateTicker() {
}
func (g *Game) move(lastStep Event) Event {
select {
case e := <-g.events:
return e
default:
return lastStep
}
}
func (g *Game) Start() (int, error) {
lastStep := Left
snake := NewSnake(g.arena, lastStep)
food := g.arena.RandomCell()
for _ = range g.ticker.C {
lastStep = g.move(lastStep)
if lastStep == Kill {
return snake.Size(), ErrGameInterrupt
}
eat, err := snake.move(lastStep, food)
if err != nil {
return snake.Size(), err
}
if eat {
food = g.arena.RandomCell()
}
g.painter.Draw(snake.Head, food)
}
return 0, nil
}
|
package lc
// Time: O(n)
// Benchmark: 4ms 6.5mb | 100%
func minPartitions(n string) int {
var max int
for _, ch := range n {
if int(ch-'0') > max {
if int(ch-'0') == 9 {
return 9
}
max = int(ch - '0')
}
}
return max
}
|
// 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 qcloud
import (
"fmt"
"time"
"yunion.io/x/jsonutils"
"yunion.io/x/pkg/errors"
api "yunion.io/x/onecloud/pkg/apis/compute"
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/onecloud/pkg/multicloud"
)
type SVpcPC struct {
multicloud.SResourceBase
multicloud.QcloudTags
vpc *SVpc
VpcID string `json:"vpcId"`
UnVpcID string `json:"unVpcId"`
PeerVpcID string `json:"peerVpcId"`
UnPeerVpcID string `json:"unPeerVpcId"`
AppID string `json:"appId"`
PeeringConnectionID string `json:"peeringConnectionId"`
PeeringConnectionName string `json:"peeringConnectionName"`
State int `json:"state"`
CreateTime string `json:"createTime"`
Uin string `json:"uin"`
PeerUin string `json:"peerUin"`
Region string `json:"region"`
PeerRegion string `json:"peerRegion"`
}
func (region *SRegion) DescribeVpcPeeringConnections(vpcId string, peeringConnectionId string, offset int, limit int) ([]SVpcPC, int, error) {
if limit > 50 || limit <= 0 {
limit = 50
}
params := make(map[string]string)
params["offset"] = fmt.Sprintf("%d", offset)
params["limit"] = fmt.Sprintf("%d", limit)
if len(vpcId) > 0 {
params["vpcId"] = vpcId
}
if len(peeringConnectionId) > 0 {
params["peeringConnectionId"] = peeringConnectionId
}
body, err := region.vpc2017Request("DescribeVpcPeeringConnections", params)
if err != nil {
return nil, 0, errors.Wrapf(err, `region.vpcRequest("DescribeVpcPeeringConnections", %s)`, jsonutils.Marshal(params).String())
}
total, _ := body.Float("totalCount")
if total <= 0 {
return nil, int(total), nil
}
vpcPCs := make([]SVpcPC, 0)
err = body.Unmarshal(&vpcPCs, "data")
if err != nil {
return nil, 0, errors.Wrapf(err, "body.Unmarshal(&vpcPCs,%s)", body.String())
}
return vpcPCs, int(total), nil
}
func (region *SRegion) GetAllVpcPeeringConnections(vpcId string) ([]SVpcPC, error) {
result := []SVpcPC{}
for {
vpcPCS, total, err := region.DescribeVpcPeeringConnections(vpcId, "", len(result), 50)
if err != nil {
return nil, errors.Wrapf(err, `client.DescribeVpcPeeringConnections(%s,"",%d,50)`, vpcId, len(result))
}
result = append(result, vpcPCS...)
if total <= len(result) {
break
}
}
return result, nil
}
func (region *SRegion) GetVpcPeeringConnectionbyId(vpcPCId string) (*SVpcPC, error) {
vpcPCs, _, err := region.DescribeVpcPeeringConnections("", vpcPCId, 0, 50)
if err != nil {
return nil, errors.Wrapf(err, `client.DescribeVpcPeeringConnections("", %s, 0, 50)`, vpcPCId)
}
if len(vpcPCs) < 1 {
return nil, errors.Wrapf(cloudprovider.ErrNotFound, "GetVpcPeeringConnectionbyId(%s)", vpcPCId)
}
if len(vpcPCs) > 1 {
return nil, errors.Wrapf(cloudprovider.ErrDuplicateId, "GetVpcPeeringConnectionbyId(%s)", vpcPCId)
}
return &vpcPCs[0], nil
}
func (region *SRegion) CreateVpcPeeringConnection(vpcId string, opts *cloudprovider.VpcPeeringConnectionCreateOptions) (string, error) {
params := make(map[string]string)
params["vpcId"] = vpcId
params["peerVpcId"] = opts.PeerVpcId
params["peerUin"] = opts.PeerAccountId
params["peeringConnectionName"] = opts.Name
body, err := region.vpc2017Request("CreateVpcPeeringConnection", params)
if err != nil {
return "", errors.Wrapf(err, `client.vpc2017Request("CreateVpcPeeringConnection", %s)`, jsonutils.Marshal(params).String())
}
peeringId, err := body.GetString("peeringConnectionId")
if err != nil {
return "", errors.Wrapf(err, `%s body.GetString("peeringConnectionId")`, body.String())
}
return peeringId, nil
}
func (region *SRegion) AcceptVpcPeeringConnection(peeringId string) error {
params := make(map[string]string)
params["peeringConnectionId"] = peeringId
_, err := region.vpc2017Request("AcceptVpcPeeringConnection", params)
if err != nil {
return errors.Wrapf(err, `client.vpc2017Request("AcceptVpcPeeringConnection",%s)`, jsonutils.Marshal(params).String())
}
return nil
}
func (region *SRegion) DeleteVpcPeeringConnection(peeringId string) error {
params := make(map[string]string)
params["peeringConnectionId"] = peeringId
_, err := region.vpc2017Request("DeleteVpcPeeringConnection", params)
if err != nil {
return errors.Wrapf(err, `client.vpc2017Request("DeleteVpcPeeringConnection",%s)`, jsonutils.Marshal(params).String())
}
return nil
}
func (region *SRegion) CreateVpcPeeringConnectionEx(vpcId string, opts *cloudprovider.VpcPeeringConnectionCreateOptions) (int64, error) {
params := make(map[string]string)
params["vpcId"] = vpcId
params["peerVpcId"] = opts.PeerVpcId
params["peerUin"] = opts.PeerAccountId
params["peeringConnectionName"] = opts.Name
params["peerRegion"] = opts.PeerRegionId
params["bandwidth"] = fmt.Sprintf("%d", opts.Bandwidth)
body, err := region.vpc2017Request("CreateVpcPeeringConnectionEx", params)
if err != nil {
return 0, errors.Wrapf(err, `client.vpc2017Request("CreateVpcPeeringConnectionEx", %s)`, jsonutils.Marshal(params).String())
}
taskId, err := body.Int("taskId")
if err != nil {
return 0, errors.Wrapf(err, `%s body.Int("taskId")`, body.String())
}
return taskId, nil
}
func (region *SRegion) DescribeVpcTaskResult(taskId string) (int, error) {
params := make(map[string]string)
params["taskId"] = taskId
body, err := region.vpc2017Request("DescribeVpcTaskResult", params)
if err != nil {
return 0, errors.Wrapf(err, `client.vpc2017Request("DescribeVpcTaskResult",%s)`, taskId)
}
status, err := body.Float("data", "status")
if err != nil {
return 0, errors.Wrapf(err, `%s body.Int("data.status")`, body.String())
}
return int(status), nil
}
func (region *SRegion) AcceptVpcPeeringConnectionEx(peeringId string) (int64, error) {
params := make(map[string]string)
params["peeringConnectionId"] = peeringId
body, err := region.vpc2017Request("AcceptVpcPeeringConnectionEx", params)
if err != nil {
return 0, errors.Wrapf(err, `client.vpc2017Request("AcceptVpcPeeringConnectionEx", %s)`, jsonutils.Marshal(params).String())
}
taskId, err := body.Int("taskId")
if err != nil {
return 0, errors.Wrapf(err, `%s body.Int("taskId")`, body.String())
}
return taskId, nil
}
func (region *SRegion) DeleteVpcPeeringConnectionEx(peeringId string) (int64, error) {
params := make(map[string]string)
params["peeringConnectionId"] = peeringId
body, err := region.vpc2017Request("DeleteVpcPeeringConnectionEx", params)
if err != nil {
return 0, errors.Wrapf(err, `client.vpc2017Request("DeleteVpcPeeringConnectionEx",%s)`, jsonutils.Marshal(params).String())
}
taskId, err := body.Int("taskId")
if err != nil {
return 0, errors.Wrapf(err, `%s body.Int("taskId")`, body.String())
}
return taskId, nil
}
func (self *SVpcPC) GetId() string {
return self.PeeringConnectionID
}
func (self *SVpcPC) GetName() string {
return self.PeeringConnectionName
}
func (self *SVpcPC) GetGlobalId() string {
return self.GetId()
}
func (self *SVpcPC) GetStatus() string {
switch self.State {
case 1:
return api.VPC_PEERING_CONNECTION_STATUS_ACTIVE
case 0:
return api.VPC_PEERING_CONNECTION_STATUS_PENDING_ACCEPT
default:
return api.VPC_PEERING_CONNECTION_STATUS_UNKNOWN
}
}
func (self *SVpcPC) Refresh() error {
svpcPC, err := self.vpc.region.GetVpcPeeringConnectionbyId(self.GetId())
if err != nil {
return errors.Wrapf(err, "self.vpc.region.GetVpcPeeringConnectionbyId(%s)", self.GetId())
}
return jsonutils.Update(self, svpcPC)
}
func (self *SVpcPC) GetPeerVpcId() string {
return self.UnPeerVpcID
}
func (self *SVpcPC) GetPeerAccountId() string {
return self.PeerUin
}
func (self *SVpcPC) GetEnabled() bool {
return true
}
func (self *SVpcPC) Delete() error {
if !self.IsCrossRegion() {
return self.vpc.region.DeleteVpcPeeringConnection(self.GetId())
}
taskId, err := self.vpc.region.DeleteVpcPeeringConnectionEx(self.GetId())
if err != nil {
return errors.Wrapf(err, "self.vpc.region.DeleteVpcPeeringConnection(%s)", self.GetId())
}
//err = self.vpc.region.WaitVpcTask(fmt.Sprintf("%d", taskId), time.Second*5, time.Minute*10)
err = cloudprovider.Wait(time.Second*5, time.Minute*6, func() (bool, error) {
status, err := self.vpc.region.DescribeVpcTaskResult(fmt.Sprintf("%d", taskId))
if err != nil {
return false, errors.Wrap(err, "self.vpc.region.DescribeVpcTaskResult")
}
//任务的当前状态。0:成功,1:失败,2:进行中。
if status == 1 {
return false, errors.Wrap(fmt.Errorf("taskfailed,taskId=%d", taskId), "client.DescribeVpcTaskResult(taskId)")
}
if status == 0 {
return true, nil
}
return false, nil
})
if err != nil {
return errors.Wrapf(err, "self.region.WaitTask(%d)", taskId)
}
return nil
}
func (self *SVpcPC) IsCrossRegion() bool {
if len(self.Region) == 0 {
return false
}
return self.Region != self.PeerRegion
}
|
package vehicle
import (
"math/rand"
"time"
)
var noop = func(*Vehicle) {}
//Upgrade for a Vehicle
type Upgrade struct {
Name string
Description string
manipulate vehicleManipulator
}
var vehicleUpgrades = []Upgrade{
{"Balista", "A giant crossbow mounted on the car that deals 3 damage to its target on success.", noop},
{"Catapult", "A catapult mounted to the vehicle that deals 1 damage to the enemy driver, all passengers, and the Vehicle on success.", noop},
{"Emergency Parachute", "A parachute that deploys from the rear of the vehicle to rapidly slow the vehicle. Grants Advantage on all driving Tests that avoid obstacles. After use, all driving Tests gain Disadvantage until the parachute is packed up or removed.", noop},
{"Flamethrower", "A weapon that sprays a massive gout of flame. Deals 1 damage and the enemy Vehicle and all occupants must make a Save. On failure, they take damage at the start of their next turn and must Save again.", noop},
{"Grenade Launcher", "A grenade launcher mounted to the vehicle. Deals 4 dam,age to the enemy Vehicle and 1 damage to each occupant.", noop},
{"Heavy Armor", "Thick metal plating, designed to protect occupants. Reduce all damage dealth to the Vechicle and all occupants by 3 (to a minimum of 1).", noop},
{"Light Armor", "Light metal plating, providing armor and cover to all occupants. Reduce all damage dealt to the vehicle and occupants by 1 (to a minimum of 1).", noop},
{"Machine Gun", "A mounted machine gun. Make 3 attacks with Disadvantage on each Action when using this Upgrade.", noop},
{"Medium Armor", "Plates of metal that protect the vehicle and its occupants. Reduce damage dealth to the vehicle and all occupants by 2 (to a minimum of 1).", noop},
{"Off-Road Capable", "Improved and upgraded handling makes it easier to drive on bad terrain. You ignore Disadvantage from Rough Terrain while making driving Tests.", noop},
{"Oil Slick Spray", "Oil that sprays from the back of your car. Any Vehicle following you suffers Disadvantage on their next turn.", noop},
{"Prisoner Box", "The back of the Vehicle is set up with glass wire and bars. Anyone held in the Prisoner Box in the Vehicle cannot physically interaact with the driver and suffers Disadvantage on any attempts to escape the vehicle.", noop},
{"Ram Plate", "A massive plate is bolted to the front of your vehicle to increase its impact. Your rams deal 1d6 damage.", noop},
{"Retrofitted Chassis", "Your chassis has been upgraded with metal and scrap to make it stronger. You vehicle gains +2 HP.",
func(vehicle *Vehicle) {
vehicle.HitPoints = vehicle.HitPoints + 2
},
}, {"Rocket Launcher", "A launcher tube is attached to your vehicle, allowing you to fire missiles and rockets at others. You may make an Attack that deals 2d3 damage", noop},
{"Rotary Autocannon", "A massive rotating machine, bolted to your ride. Make 6 Attacks with Disadvantage on each Action. This weapon can only be used once per turn.", noop},
{"Shredder", "You can eject spikes that shred the tires of those following you. Any Vehicle following you takes 1 damage and has Disadvantage until they stop to repair their tires.", noop},
{"SMG", "A small machine gun attached to your vehicle. Make 2 Attacks with Disadvantage on each Action. For each attack that hits, you may make an additional Attack with Disadvantage.", noop},
{"Smoke Dispenser", "Your Vehicle can spray smoke, making escape easier. You can use this system to grant Advantage on rolls to lose someone following you.", noop},
{"Wheel Blades", "You may make normal melee attacks with your vehicle that are not Ram.", noop},
}
var seed = rand.NewSource(time.Now().UnixNano())
var rando = rand.New(seed)
// SetUpgrades to a Vehicle.
func SetUpgrades(vehicle *Vehicle) {
for len(vehicle.Upgrades) < vehicle.maxUpgrades {
upgrade := vehicleUpgrades[rando.Intn(len(vehicleUpgrades))]
vehicle.Upgrades[upgrade.Name] = upgrade
upgrade.manipulate(vehicle)
}
}
|
package action
type Chart struct {
name string
version string
}
type Repository struct {
name string
charts map[string]*Chart
} |
// SPDX-License-Identifier: ISC
// Copyright (c) 2014-2020 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package peer
import (
"encoding/binary"
"github.com/bitmark-inc/bitmarkd/announce"
"github.com/bitmark-inc/bitmarkd/asset"
"github.com/bitmark-inc/bitmarkd/fault"
"github.com/bitmark-inc/bitmarkd/messagebus"
"github.com/bitmark-inc/bitmarkd/mode"
"github.com/bitmark-inc/bitmarkd/pay"
"github.com/bitmark-inc/bitmarkd/payment"
"github.com/bitmark-inc/bitmarkd/reservoir"
"github.com/bitmark-inc/bitmarkd/storage"
"github.com/bitmark-inc/bitmarkd/transactionrecord"
"github.com/bitmark-inc/logger"
)
// process received data
func processSubscription(log *logger.L, command string, arguments [][]byte) {
dataLength := len(arguments)
switch command {
case "block":
if dataLength < 1 {
log.Debugf("block with too few data: %d items", dataLength)
return
}
log.Infof("received block: %x", arguments[0])
if !mode.Is(mode.Normal) {
err := fault.NotAvailableDuringSynchronise
log.Debugf("failed assets: error: %s", err)
} else {
messagebus.Bus.Blockstore.Send("remote", arguments[0])
}
case "assets":
if dataLength < 1 {
log.Debugf("assets with too few data: %d items", dataLength)
return
}
log.Infof("received assets: %x", arguments[0])
err := processAssets(arguments[0])
if nil != err {
log.Debugf("failed assets: error: %s", err)
} else {
messagebus.Bus.Broadcast.Send("assets", arguments[0])
}
case "issues":
if dataLength < 1 {
log.Debugf("issues with too few data: %d items", dataLength)
return
}
log.Infof("received issues: %x", arguments[0])
err := processIssues(arguments[0])
if nil != err {
log.Debugf("failed issues: error: %s", err)
} else {
messagebus.Bus.Broadcast.Send("issues", arguments[0])
}
case "transfer":
if dataLength < 1 {
log.Debugf("transfer with too few data: %d items", dataLength)
return
}
log.Infof("received transfer: %x", arguments[0])
err := processTransfer(arguments[0])
if nil != err {
log.Debugf("failed transfer: error: %s", err)
} else {
messagebus.Bus.Broadcast.Send("transfer", arguments[0])
}
case "proof":
if dataLength < 1 {
log.Debugf("proof with too few data: %d items", dataLength)
return
}
log.Infof("received proof: %x", arguments[0])
err := processProof(arguments[0])
if nil != err {
log.Debugf("failed proof: error: %s", err)
} else {
messagebus.Bus.Broadcast.Send("proof", arguments[0])
}
case "rpc":
if dataLength < 3 {
log.Debugf("rpc with too few data: %d items", dataLength)
return
}
if 8 != len(arguments[2]) {
log.Debug("rpc with invalid timestamp")
return
}
timestamp := binary.BigEndian.Uint64(arguments[2])
log.Infof("received rpc: fingerprint: %x rpc: %x timestamp: %d", arguments[0], arguments[1], timestamp)
if announce.AddRPC(arguments[0], arguments[1], timestamp) {
messagebus.Bus.Broadcast.Send("rpc", arguments[0:3]...)
}
case "peer":
if dataLength < 3 {
log.Debugf("peer with too few data: %d items", dataLength)
return
}
if 8 != len(arguments[2]) {
log.Debug("peer with invalid timestamp")
return
}
timestamp := binary.BigEndian.Uint64(arguments[2])
log.Infof("received peer: %x listener: %x timestamp: %d", arguments[0], arguments[1], timestamp)
if announce.AddPeer(arguments[0], arguments[1], timestamp) {
messagebus.Bus.Broadcast.Send("peer", arguments[0:3]...)
}
default:
log.Debugf("received unhandled command: %q arguments: %x", command, arguments)
}
}
// un pack each asset and cache them
func processAssets(packed []byte) error {
if 0 == len(packed) {
return fault.MissingParameters
}
if !mode.Is(mode.Normal) {
return fault.NotAvailableDuringSynchronise
}
ok := false
for 0 != len(packed) {
transaction, n, err := transactionrecord.Packed(packed).Unpack(mode.IsTesting())
if nil != err {
return err
}
switch tx := transaction.(type) {
case *transactionrecord.AssetData:
_, packedAsset, err := asset.Cache(tx, storage.Pool.Assets)
if nil != err {
return err
}
if nil != packedAsset {
ok = true
}
default:
return fault.TransactionIsNotAnAsset
}
packed = packed[n:]
}
// all items were duplicates
if !ok {
return fault.NoNewTransactions
}
return nil
}
// un pack each issue and cache them
func processIssues(packed []byte) error {
if 0 == len(packed) {
return fault.MissingParameters
}
if !mode.Is(mode.Normal) {
return fault.NotAvailableDuringSynchronise
}
packedIssues := transactionrecord.Packed(packed)
issueCount := 0 // for payment difficulty
issues := make([]*transactionrecord.BitmarkIssue, 0, reservoir.MaximumIssues)
for 0 != len(packedIssues) {
transaction, n, err := packedIssues.Unpack(mode.IsTesting())
if nil != err {
return err
}
switch tx := transaction.(type) {
case *transactionrecord.BitmarkIssue:
issues = append(issues, tx)
issueCount += 1
default:
return fault.TransactionIsNotAnIssue
}
packedIssues = packedIssues[n:]
}
if 0 == len(issues) {
return fault.MissingParameters
}
rsvr := reservoir.Get()
_, duplicate, err := rsvr.StoreIssues(issues)
if nil != err {
return err
}
if duplicate {
return fault.TransactionAlreadyExists
}
return nil
}
// unpack transfer and process it
func processTransfer(packed []byte) error {
if 0 == len(packed) {
return fault.MissingParameters
}
if !mode.Is(mode.Normal) {
return fault.NotAvailableDuringSynchronise
}
transaction, _, err := transactionrecord.Packed(packed).Unpack(mode.IsTesting())
if nil != err {
return err
}
duplicate := false
transfer, ok := transaction.(transactionrecord.BitmarkTransfer)
rsvr := reservoir.Get()
if ok {
_, duplicate, err = rsvr.StoreTransfer(transfer)
} else {
switch tx := transaction.(type) {
case *transactionrecord.ShareGrant:
_, duplicate, err = rsvr.StoreGrant(tx)
case *transactionrecord.ShareSwap:
_, duplicate, err = rsvr.StoreSwap(tx)
default:
return fault.TransactionIsNotATransfer
}
}
if nil != err {
return err
}
if duplicate {
return fault.TransactionAlreadyExists
}
return nil
}
// process proof block
func processProof(packed []byte) error {
if 0 == len(packed) {
return fault.MissingParameters
}
if !mode.Is(mode.Normal) {
return fault.NotAvailableDuringSynchronise
}
var payId pay.PayId
nonceLength := len(packed) - len(payId) // could be negative
if nonceLength < payment.MinimumNonceLength || nonceLength > payment.MaximumNonceLength {
return fault.InvalidNonce
}
copy(payId[:], packed[:len(payId)])
nonce := packed[len(payId):]
rsvr := reservoir.Get()
status := rsvr.TryProof(payId, nonce)
if reservoir.TrackingAccepted != status {
// pay id already processed or was invalid
return fault.PayIdAlreadyUsed
}
return nil
}
|
package store
type Store interface {
UploadFile(remotePath, localPath, checksum string) error
DownloadFile(remotePath, localPath string) (string, error)
}
|
/*
* Created on Wed Mar 20 2019 21:29:38
* Author: WuLC
* EMail: liangchaowu5@gmail.com
*/
func numPairsDivisibleBy60(time []int) int {
count := [60]int{0}
for _, t := range time {
count[t%60]++
}
result := 0
for i := 0; i <= 30; i++ {
if i == 0 || i == 30 {
result += (count[i] * (count[i-1])) / 2
} else {
result += count[i] * count[60-i]
}
}
return result
} |
// 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 tasks
import (
"context"
"time"
"yunion.io/x/jsonutils"
"yunion.io/x/pkg/errors"
api "yunion.io/x/onecloud/pkg/apis/compute"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/onecloud/pkg/compute/models"
"yunion.io/x/onecloud/pkg/util/logclient"
)
type SNatSEntryCreateTask struct {
taskman.STask
}
func init() {
taskman.RegisterTask(SNatSEntryCreateTask{})
}
func (self *SNatSEntryCreateTask) taskFailed(ctx context.Context, snat *models.SNatSEntry, err error) {
snat.SetStatus(self.UserCred, api.NAT_STATUS_CREATE_FAILED, err.Error())
db.OpsLog.LogEvent(snat, db.ACT_ALLOCATE_FAIL, err, self.UserCred)
nat, _ := snat.GetNatgateway()
if nat != nil {
logclient.AddActionLogWithStartable(self, nat, logclient.ACT_NAT_CREATE_SNAT, err, self.UserCred, false)
}
logclient.AddActionLogWithStartable(self, snat, logclient.ACT_ALLOCATE, err, self.UserCred, false)
self.SetStageFailed(ctx, jsonutils.NewString(err.Error()))
}
func (self *SNatSEntryCreateTask) OnInit(ctx context.Context, obj db.IStandaloneModel, body jsonutils.JSONObject) {
snat := obj.(*models.SNatSEntry)
eip, err := snat.GetEip()
if err != nil {
self.taskFailed(ctx, snat, errors.Wrapf(err, "snat.GetEip"))
return
}
if len(eip.AssociateId) > 0 {
self.OnAssociateEipComplete(ctx, snat, body)
return
}
nat, err := snat.GetNatgateway()
if err != nil {
self.taskFailed(ctx, snat, errors.Wrapf(err, "snat.GetNatgateway"))
return
}
self.SetStage("OnAssociateEipComplete", nil)
err = nat.GetRegion().GetDriver().RequestAssociateEipForNAT(ctx, self.GetUserCred(), nat, eip, self)
if err != nil {
self.taskFailed(ctx, snat, errors.Wrapf(err, "RequestAssociateEipForNAT"))
return
}
}
func (self *SNatSEntryCreateTask) OnAssociateEipCompleteFailed(ctx context.Context, snatEntry *models.SNatSEntry, reason jsonutils.JSONObject) {
self.taskFailed(ctx, snatEntry, errors.Errorf(reason.String()))
}
func (self *SNatSEntryCreateTask) OnAssociateEipComplete(ctx context.Context, snat *models.SNatSEntry, body jsonutils.JSONObject) {
nat, err := snat.GetNatgateway()
if err != nil {
self.taskFailed(ctx, snat, errors.Wrapf(err, "snat.GetNatgateway"))
return
}
iNat, err := nat.GetINatGateway()
if err != nil {
self.taskFailed(ctx, snat, errors.Wrapf(err, "nat.GetINatGateway"))
return
}
eip, err := snat.GetEip()
if err != nil {
self.taskFailed(ctx, snat, errors.Wrapf(err, "snat.GetEip"))
return
}
// construct a DNat RUle
rule := cloudprovider.SNatSRule{
ExternalIP: snat.IP,
ExternalIPID: eip.ExternalId,
}
if len(snat.SourceCIDR) > 0 {
rule.SourceCIDR = snat.SourceCIDR
} else {
network, err := snat.GetNetwork()
if err != nil {
self.taskFailed(ctx, snat, errors.Wrapf(err, "snat.GetNetwork"))
return
}
rule.NetworkID = network.ExternalId
}
iSnat, err := iNat.CreateINatSEntry(rule)
if err != nil {
self.taskFailed(ctx, snat, errors.Wrapf(err, "CreateINatSEntry"))
return
}
err = db.SetExternalId(snat, self.UserCred, iSnat.GetGlobalId())
if err != nil {
self.taskFailed(ctx, snat, errors.Wrapf(err, "db.SetExternalId(%s)", iSnat.GetGlobalId()))
return
}
err = cloudprovider.WaitStatus(iSnat, api.NAT_STAUTS_AVAILABLE, 10*time.Second, 5*time.Minute)
if err != nil {
self.taskFailed(ctx, snat, errors.Wrapf(err, "cloudprovider.WaitStatus(iSnat)"))
return
}
snat.SetStatus(self.UserCred, api.NAT_STAUTS_AVAILABLE, "")
logclient.AddActionLogWithStartable(self, nat, logclient.ACT_NAT_CREATE_SNAT, nil, self.UserCred, true)
self.SetStageComplete(ctx, nil)
}
|
package mail
import (
"crypto/tls"
"errors"
"fmt"
"net/http"
"net/mail"
"net/textproto"
"path/filepath"
"sync"
"time"
"github.com/jrapoport/gothic/config"
"github.com/jrapoport/gothic/core/validate"
"github.com/jrapoport/gothic/log"
"github.com/jrapoport/gothic/mail/template"
"github.com/jrapoport/gothic/utils"
smtp "github.com/xhit/go-simple-mail/v2"
)
// Client is a mail & smtp client
type Client struct {
from mail.Address
client *smtp.SMTPClient
server *smtp.SMTPServer
config config.Mail
log log.Logger
mu sync.RWMutex
keepalive *time.Ticker
// validate email addresses against the smtp server
smtpEmailValidation bool
}
// NewMailClient returns a new mail client.
func NewMailClient(c *config.Config, l log.Logger) (*Client, error) {
m := c.Mail
if _, err := validate.Email(m.From); err != nil {
err = fmt.Errorf("from address %w", err)
return nil, err
}
// it is impossible for this to fail if validate.Email()
// succeeds because validate.Email() calls parseAddress()
from, _ := parseAddress(m.From)
if l == nil {
l = log.New()
}
if m.Host == "" {
l = l.WithName("smtp-offline")
return &Client{from: from, log: l}, nil
}
l = l.WithName("smtp-" + m.Host)
s := smtp.NewSMTPClient()
s.Host = m.Host
s.Port = m.Port
s.Username = m.Username
s.Password = m.Password
switch m.Authentication {
case "login":
s.Authentication = smtp.AuthLogin
case "cram-md5":
s.Authentication = smtp.AuthCRAMMD5
default:
s.Authentication = smtp.AuthPlain
}
const (
defaultPort = 25 // SMTP
sslPort = 465 // SMTPS (deprecated)
tlsPort = 587 // SMTP tls
)
switch m.Encryption {
case "ssl":
s.Encryption = smtp.EncryptionSSL
case "tls":
if s.Port == defaultPort || s.Port == sslPort {
l.Warnf("using smtp tls port: %d", tlsPort)
s.Port = tlsPort
}
s.Encryption = smtp.EncryptionTLS
default:
s.Encryption = smtp.EncryptionNone
}
// TODO: should we instead test the connection early, and then re-connect?
s.KeepAlive = m.KeepAlive
s.ConnectTimeout = 10 * time.Second
s.SendTimeout = 10 * time.Second
// Set TLSConfig to provide custom TLS configuration. For example,
// to skip TLS verification (useful for testing):
if c.IsDebug() {
s.TLSConfig = &tls.Config{InsecureSkipVerify: true}
}
return &Client{
from: from,
server: s,
config: m,
log: l,
}, nil
}
// Open opens the mail client and connects to the smtp server.
func (m *Client) Open() error {
m.mu.Lock()
defer m.mu.Unlock()
if m.IsOffline() {
m.log.Warn("mail client is offline")
return nil
}
if m.client != nil {
return nil
}
var err error
m.client, err = m.server.Connect()
if err != nil {
return err
}
m.smtpEmailValidation = true
if !m.client.KeepAlive {
return m.close()
}
return m.keepAlive()
}
func (m *Client) keepAlive() error {
if m.client == nil || !m.client.KeepAlive {
return nil
}
m.keepalive = time.NewTicker(30 * time.Second)
var wait sync.WaitGroup
wait.Add(1)
go func() {
wait.Done()
err := m.noop()
if err != nil {
return
}
for range m.keepalive.C {
err = m.noop()
if err != nil {
return
}
}
}()
wait.Wait()
return nil
}
func (m *Client) noop() error {
m.mu.RLock()
defer m.mu.RUnlock()
if m.client == nil {
return nil
}
err := m.client.Noop()
if err == nil {
return nil
}
e, ok := err.(*textproto.Error)
if ok && e.Code == http.StatusOK {
return nil
}
err = fmt.Errorf("keepalive: %w", err)
m.log.Error(err)
return err
}
// Close closes the mail client and disconnects from the smtp server.
func (m *Client) Close() error {
m.mu.Lock()
defer m.mu.Unlock()
return m.close()
}
// close is non-locking close and can be called from Client.Open()
func (m *Client) close() error {
m.smtpEmailValidation = false
if m.keepalive != nil {
m.keepalive.Stop()
}
if m.client == nil {
return nil
}
err := m.client.Close()
m.client = nil
return err
}
// IsOffline returns true if the smtp server is offline.
func (m *Client) IsOffline() bool {
return m.server == nil
}
// UseSpamProtection use live smtp server email validation.
func (m *Client) UseSpamProtection(enable bool) {
m.config.SpamProtection = enable
}
func (m *Client) validateEmailAccount() bool {
return m.config.SpamProtection && m.smtpEmailValidation
}
// ValidateEmail validates email accounts with a live smtp server or offline.
func (m *Client) ValidateEmail(e string) (string, error) {
if m.IsOffline() || !m.validateEmailAccount() {
return validate.Email(e)
}
return validate.EmailAccount(m.server.Host, m.from.Address, e)
}
// Status returns the status of the mail client.
func (m *Client) Status() string {
if m.IsOffline() {
return "offline"
} else if m.server.KeepAlive {
return "keepalive"
} else {
return "idle"
}
}
// From the from: address to use.
func (m *Client) From() string {
return m.from.String()
}
// Send can be used to send one-off emails to users
func (m *Client) Send(to, logo, subject, html, plain string) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.IsOffline() {
m.log.Warn("mail client is offline")
return nil
}
if _, err := m.ValidateEmail(to); err != nil {
err = fmt.Errorf("to email %w", err)
return err
}
if html == "" && plain == "" {
return errors.New("body required")
}
msg := smtp.NewMSG()
msg.SetFrom(m.From())
msg.AddTo(to)
if subject == "" {
subject = m.defaultSubject()
}
msg.SetSubject(subject)
if html != "" {
msg.SetBody(smtp.TextHTML, html)
}
if plain != "" {
if html != "" {
msg.AddAlternative(smtp.TextPlain, plain)
} else {
msg.SetBody(smtp.TextPlain, plain)
}
}
if utils.IsLocalPath(logo) {
msg.AddInline(logo, filepath.Base(logo))
}
if m.client != nil {
return msg.Send(m.client)
}
client, err := m.server.Connect()
if err != nil {
return err
}
m.smtpEmailValidation = true
return msg.Send(client)
}
// Send can be used to send one-off templated emails to users.
func (m *Client) sendTemplate(t template.Template) error {
if m.IsOffline() {
m.log.Warn("mail client is offline")
return nil
}
err := template.LoadTemplate(m.config, t)
if err != nil {
return err
}
html, err := t.HTML()
if err != nil {
return err
}
plain, err := t.PlainText()
if err != nil {
return err
}
return m.Send(t.To(), t.Logo(), t.Subject(), html, plain)
}
type Type int
const (
HTML Type = iota
Markdown
Template
)
type Content struct {
Type Type
Body string
Plaintext string
}
func (m *Client) SendEmail(to, subject string, content Content) error {
if m.IsOffline() {
m.log.Warn("mail client is offline")
return nil
}
if content.Body == "" {
return errors.New("content body required")
}
var err error
switch content.Type {
case Template:
err = m.SendTemplateEmail(to, subject, content.Body)
case Markdown:
err = m.SendMarkdownEmail(to, subject, content.Body)
case HTML:
fallthrough
default:
err = m.Send(to, m.config.Logo, subject, content.Body, content.Plaintext)
}
return err
}
// SendTemplateEmail sends an generic email based on a body template
func (m *Client) SendTemplateEmail(to, subject, body string) error {
if m.IsOffline() {
m.log.Warn("mail client is offline")
return nil
}
toAddr, err := parseAddress(to)
if err != nil {
return err
}
if body == "" {
return errors.New("body template required")
}
c := config.MailTemplate{
Subject: subject,
}
e := template.NewEmail(c, toAddr, body)
return m.sendTemplate(e)
}
// SendMarkdownEmail sends an markdown email
func (m *Client) SendMarkdownEmail(to, subject, markdown string) error {
if m.IsOffline() {
m.log.Warn("mail client is offline")
return nil
}
toAddr, err := parseAddress(to)
if err != nil {
return err
}
if markdown == "" {
return errors.New("email markdown required")
}
c := config.MailTemplate{
Subject: subject,
}
e := template.NewMarkdownMail(c, toAddr, markdown)
return m.sendTemplate(e)
}
// SendChangeEmail sends an email change request
func (m *Client) SendChangeEmail(to, newAddress, token, referrerURL string) error {
if m.IsOffline() {
m.log.Warn("mail client is offline")
return nil
}
if token == "" {
return errors.New("invalid token")
}
toAddr, err := parseAddress(to)
if err != nil {
return err
}
e := template.NewChangeEmail(m.config.ConfirmUser, toAddr, newAddress, token, referrerURL)
return m.sendTemplate(e)
}
// SendConfirmUser sends a mail confirmation.
func (m *Client) SendConfirmUser(to, token, referrerURL string) error {
if m.IsOffline() {
m.log.Warn("mail client is offline")
return nil
}
if token == "" {
return errors.New("invalid token")
}
toAddr, err := parseAddress(to)
if err != nil {
return err
}
e := template.NewConfirmUser(m.config.ConfirmUser, toAddr, token, referrerURL)
return m.sendTemplate(e)
}
// SendResetPassword sends an invite mail to a new user
func (m *Client) SendResetPassword(to, token, referrerURL string) error {
if m.IsOffline() {
m.log.Warn("mail client is offline")
return nil
}
if token == "" {
return errors.New("invalid token")
}
toAddr, err := parseAddress(to)
if err != nil {
return err
}
e := template.NewResetPassword(m.config.ResetPassword, toAddr, token, referrerURL)
return m.sendTemplate(e)
}
// SendInviteUser sends an invite mail to a new user
func (m *Client) SendInviteUser(from, to, token, referrerURL string) error {
if m.IsOffline() {
m.log.Warn("mail client is offline")
return nil
}
if token == "" {
return errors.New("invalid token")
}
fromAddr, err := optionalAddress(from)
if err != nil {
return err
}
toAddr, err := parseAddress(to)
if err != nil {
return err
}
e := template.NewInviteUser(m.config.InviteUser, fromAddr, toAddr, token, referrerURL)
return m.sendTemplate(e)
}
// SendSignupCode sends an invite mail to a new user
func (m *Client) SendSignupCode(from, to, token, referrerURL string) error {
if m.IsOffline() {
m.log.Warn("mail client is offline")
return nil
}
if token == "" {
return errors.New("invalid signup code")
}
fromAddr, err := optionalAddress(from)
if err != nil {
return err
}
toAddr, err := parseAddress(to)
if err != nil {
return err
}
e := template.NewSignupCode(m.config.SignupCode, fromAddr, toAddr, token, referrerURL)
return m.sendTemplate(e)
}
func (m *Client) defaultSubject() string {
name := "us"
if m.config.Name != "" {
name = m.config.Name
}
return "An important message from " + name
}
func parseAddress(address string) (mail.Address, error) {
addr, err := mail.ParseAddress(address)
if err != nil {
return mail.Address{}, err
}
return *addr, err
}
func optionalAddress(address string) (mail.Address, error) {
if address == "" {
return mail.Address{}, nil
}
return parseAddress(address)
}
|
package xpbonds
import (
"bytes"
"context"
"encoding/base64"
"sort"
"github.com/pkg/errors"
)
// FindBestBonds determinates the best bonds from the bond report. It expects
// the report to contain a xlsx content (Excel) encoded in base64. After parsing
// the xlxs it performs some filtering and sorting actions to determinate the
// best bond.
func FindBestBonds(ctx context.Context, report BondReport) (Bonds, error) {
excel, err := base64.StdEncoding.DecodeString(report.XLXSReport)
if err != nil {
return nil, errors.Wrap(err, "failed to decode excel report")
}
bonds, err := parseExcel(bytes.NewReader(excel), report.DateFormat, report.FocusedOnly)
if err != nil {
return nil, errors.Wrap(err, "failed to parse excel")
}
bonds = bonds.Filter(report.Filter)
bonds.FillCurrentPrice()
sort.Sort(bonds)
return bonds, nil
}
|
package gago
import "math/rand"
// A Deme contains individuals. Individuals mate within a deme. Individuals can
// migrate from one deme to another.
type Deme struct {
// Number of individuals in the deme, it is defined for convenience
Size int
// Individuals
Individuals Individuals
// Each deme has a random number generator to bypass the global rand mutex
Generator *rand.Rand
}
// Initialize each individual in a deme.
func (deme *Deme) Initialize(indiSize int, boundary float64) {
for i := range deme.Individuals {
var individual = Individual{make([]float64, indiSize), 0.0}
individual.Initialize(boundary, deme.Generator)
deme.Individuals[i] = individual
}
}
// Evaluate the fitness of each individual in a deme.
func (deme *Deme) Evaluate(ff func([]float64) float64) {
for i := range deme.Individuals {
deme.Individuals[i].Evaluate(ff)
}
}
// Sort the individuals in a deme. This method is merely a convenience for
// calling the Individuals.Sort method within the deme from the population.
func (deme *Deme) Sort() {
deme.Individuals.Sort()
}
// Mutate each individual in a deme.
func (deme *Deme) Mutate(mutMethod func(indi *Individual, mutRate, mutIntensity float64, generator *rand.Rand),
mutRate, mutIntensity float64) {
for _, individual := range deme.Individuals {
// Use the pointer to the individual to perform mutation
mutMethod(&individual, mutRate, mutIntensity, deme.Generator)
}
}
// Crossover replaces the population with new individuals called offsprings. The
// takes as arguments a selection method, a crossover method and the size of the
// crossover. The size of the crossover is the number of individuals whose genes
// will be mixed to generate an offspring with the crossover function.
func (deme *Deme) Crossover(selMethod func(Individuals, *rand.Rand) Individual,
crossMethod func(Individuals, *rand.Rand) Individual, crossSize int) {
// Create an empty slice of individuals to store the offsprings
var offsprings = make(Individuals, deme.Size)
for i := 0; i < deme.Size; i++ {
// Select individuals to perform crossover
var selected = make(Individuals, crossSize)
for j := 0; j < crossSize; j++ {
selected[j] = selMethod(deme.Individuals, deme.Generator)
}
// Generate an offspring from the selected individuals
offsprings[i] = crossMethod(selected, deme.Generator)
}
// Replace the population with the offsprings
deme.Individuals = offsprings
}
|
package models
import "gz.com/master/random"
/*
案件关联的嫌疑人,嫌疑人在这个案件中的信息
*/
type CaseSuspects struct {
CsId string `orm:"pk;size(32)"`
CsCaseId string `orm:"size(32)"`
CsSuspectsId string `orm:"size(32)"`
CsInfo string `orm:"type(text)"`
}
func (this *CaseSuspects)Read(field ...string) error {
return o.Read(this, field...)
}
func (this *CaseSuspects)Insert()(int64,error){
if this.CsCaseId==""{
this.CsCaseId=random.NewId()
}
return o.Insert(this)
}
func (this *CaseSuspects)Update(field...string)(int64,error){
return o.Update(this,field...)
}
func (this *CaseSuspects)Delete()(int64,error){
return o.Delete(this)
}
|
// fmt.Println("InsertedOne(), newID", newID) |
package core
/**
Lambda Running in AWS
Receives Event
Hits s3 bucket get config (Maybe Git)
Processes Command:
Each Task
*/
type Executor interface {
Execute(task *Task) *TaskResult
}
|
package plugin
import (
"context"
)
type DeletePlugin interface {
// Return a unique key for this plugin
GetKey() string
// Return a parameter list with descriptions.
GetParameters() map[string]string
// Set a parameter. The plugin may return an error if the configuration value is not valid or no such configuration
// option exists. Parameter names will be passed lowercase, separated by a dash (-) even when the input was sent
// with an underscore (-)
SetParameter(name string, value string) error
// Run the deletion process. Will only be called if a deletion of that particular resource is requested. Should
// handle failures to delete the resource.
Run(client *ClientFactory, ctx context.Context) error
}
|
package main
import "fmt"
// Notice the channel directions. Function and only send to c channel
func Numbers(c chan<- int) {
for i := 1; ; i++ {
c <- i
}
return
}
// Here function can only send to out channel and receive from in channel
func MultipleFilter(num int, in <-chan int, out chan<- int) {
for i := range in {
if i%num != 0 {
out <- i
}
}
}
func main() {
ch := make(chan int)
go Numbers(ch)
out := make(chan int)
go MultipleFilter(4, ch, out)
for i := 0; i < 10; i++ {
fmt.Println(<-out)
}
}
|
/*
Copyright © 2021 Bren 'fraq' Briggs (code@fraq.io)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package util
import (
"fmt"
"net"
"os"
"strings"
"github.com/SECCDC/flexo/model"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func DBinit(user, pass, address, dbName, sslmode string) error {
db := DBcreate(user, pass, address, dbName, sslmode)
if db.Error != nil {
fmt.Println(db.Error)
fmt.Println("Could not create database")
os.Exit(3)
}
return DBconnect(user, pass, address, dbName, sslmode).AutoMigrate(&model.Team{}, &model.Category{}, &model.Target{}, &model.Event{}, &model.EcomEvent{})
}
func DBcreate(user, pass, address, dbName, sslmode string) *gorm.DB {
db := DBconnect(user, pass, address, "", sslmode)
return db.Raw(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", dbName))
}
func DBconnect(user, pass, address, dbName, sslmode string) *gorm.DB {
host, port, err := extractHostAndPort(address)
if err != nil {
panic("DB address isn't of the expected form host:port")
}
dsn := fmt.Sprintf("host=%s user=%s password=%s DB.name=%s port=%s, sslmode=%s", host, user, pass, dbName, port, sslmode)
db, err := gorm.Open(postgres.New(postgres.Config{
DSN: dsn,
PreferSimpleProtocol: true, // disables implicit prepared statement usage. By default pgx automatically uses the extended protocol
}), &gorm.Config{})
if err != nil {
panic(err)
}
return db
}
func extractHostAndPort(address string) (string, string, error) {
// Is this a domain ?
splitAddr := strings.Split(address, ":")
_, e := net.LookupHost(splitAddr[0])
if e == nil {
return splitAddr[0], splitAddr[1], nil
}
// If not, is this an IP?
addr, err := net.ResolveTCPAddr("tcp", address)
return addr.IP.String(), fmt.Sprintf("%d", addr.Port), err
}
|
package main
import (
"common"
"fmt"
)
func main() {
goHello := common.HelloWorld("golang")
fmt.Println(goHello)
}
|
package controllers
import (
"io/ioutil"
"log"
"net/http"
"encoding/json"
"os"
"github.com/mailgun/mailgun-go"
"github.com/dev-lusaja/gomail/models"
)
var (
config models.Config
)
func init() {
config_file, e := ioutil.ReadFile("configs/sender.json")
if e != nil {
log.Println(e)
os.Exit(1)
}
json.Unmarshal(config_file, &config)
}
func Sender(w http.ResponseWriter, r *http.Request) {
// response variables for shipping
var Response []models.ItemResponse
var Json_response []byte
// open connection with Mailgun
gun := mailgun.NewMailgun(config.Domain, config.Secret_api_key, config.Public_api_key)
// we set the content-type header to JSON for answers
w.Header().Set("Content-Type", "application/json")
// reading the body content
b, _ := ioutil.ReadAll(r.Body)
// creating a expresion for Payload
p := &models.PayLoad{}
err := json.Unmarshal(b, p)
if err != nil {
msg, _ := json.Marshal("{error: 'the format JSON in the request is invalid'}")
log.Println(string(msg))
w.Write(msg)
return
}
for i := 0; i < len(p.Data); i++ {
// we get the shipment data
sender := p.Data[i].From
subject := p.Data[i].Subject
body := p.Data[i].Body
recipient := p.Data[i].To
// we validate the sender and recipient
sender_valid, _ := gun.ValidateEmail(sender)
recipient_valid, _ := gun.ValidateEmail(recipient)
if sender_valid.IsValid != true || recipient_valid.IsValid != true {
msg, _ := json.Marshal("{error: 'Invalid sender or recipient'}")
log.Println(string(msg))
w.Write(msg)
return
}
// send
m := mailgun.NewMessage(sender, subject, body, recipient)
m.SetHtml(body)
response, id, send_error := gun.Send(m)
if send_error != nil {
log.Println(send_error)
msg, _ := json.Marshal(models.ErrorResponse{Error: send_error})
log.Println(string(msg))
w.Write(msg)
} else {
item := models.ItemResponse{id, recipient, response}
Response = append(Response, item)
sr := models.SenderResponse{Response}
msg, json_error := json.Marshal(sr)
if json_error != nil {
// This error is only for parsing JSON
log.Println(json_error)
msg, _ := json.Marshal(models.ErrorResponse{Error: json_error})
log.Println(string(msg))
w.Write(msg)
return
} else {
log.Println(string(msg))
Json_response = msg
}
}
}
w.Write(Json_response)
} |
package leetcode
import (
"fmt"
"sort"
"testing"
"github.com/stretchr/testify/assert"
)
func TestIntersect2ary2(t *testing.T) {
assert.Equal(t, []int{2,2}, intersect([]int{1,2,2,1}, []int{2,2}))
assert.Equal(t, []int{4,9}, intersect([]int{4,9,5}, []int{9,4,9,8,4}))
}
/**
Intersection of Two Arrays II
Solution
Given two integer arrays nums1 and nums2, return an array of their intersection.
Each element in the result must appear as many times as it shows in both arrays
and you may return the result in any order.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Explanation: [9,4] is also accepted.
Constraints:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
Follow up:
- What if the given array is already sorted? How would you optimize your algorithm?
- What if nums1's size is small compared to nums2's size? Which algorithm is better?
- What if elements of nums2 are stored on disk, and the memory is limited such that
- you cannot load all elements into the memory at once?
*/
func intersect(nums1 []int, nums2 []int) []int {
nums1S := sort.IntSlice(nums1)
nums2S := sort.IntSlice(nums2)
nums1S.Sort()
nums2S.Sort()
fmt.Printf("nums1S(%v), nums2S(%v)\n", nums1S, nums2S)
var i1, i2 int
var intersection []int
for i1 < len(nums1S) && i2 < len(nums2S) {
v1 := nums1S[i1]
v2 := nums2S[i2]
if v1 < v2 {
i1++
continue
}
if v1 > v2 {
i2++
continue
}
intersection = append(intersection, v1)
i1++
i2++
}
return intersection
} |
package notify
func newNotifier() (Notifier, error) {
return &emptyNotifier{}, nil
}
|
package config
func DSN() string {
var User = "root" // exemple : "root"
var Password = "" // laisser à vide si pas de mot de passe
var DatabaseName = "alea_data_est"
var Charset = "utf8" // exemple : "utf8"
var ret = User + ":" + Password + "@/" + DatabaseName + "?charset=" + Charset
return ret
}
var Port = ":8000" // exemple : ":8000" |
// This file contains unit orders.
package repcmd
import "github.com/icza/screp/rep/repcore"
// Order describes the unit order.
type Order struct {
repcore.Enum
// ID as it appears in replays
ID byte
}
// Orders is an enumeration of the possible unit orders.
var Orders = []*Order{
{e("Die"), 0x00},
{e("Stop"), 0x01},
{e("Guard"), 0x02},
{e("PlayerGuard"), 0x03},
{e("TurretGuard"), 0x04},
{e("BunkerGuard"), 0x05},
{e("Move"), 0x06},
{e("ReaverStop"), 0x07},
{e("Attack1"), 0x08},
{e("Attack2"), 0x09},
{e("AttackUnit"), 0x0a},
{e("AttackFixedRange"), 0x0b},
{e("AttackTile"), 0x0c},
{e("Hover"), 0x0d},
{e("AttackMove"), 0x0e},
{e("InfestedCommandCenter"), 0x0f},
{e("UnusedNothing"), 0x10},
{e("UnusedPowerup"), 0x11},
{e("TowerGuard"), 0x12},
{e("TowerAttack"), 0x13},
{e("VultureMine"), 0x14},
{e("StayInRange"), 0x15},
{e("TurretAttack"), 0x16},
{e("Nothing"), 0x17},
{e("Unused_24"), 0x18},
{e("DroneStartBuild"), 0x19},
{e("DroneBuild"), 0x1a},
{e("CastInfestation"), 0x1b},
{e("MoveToInfest"), 0x1c},
{e("InfestingCommandCenter"), 0x1d},
{e("PlaceBuilding"), 0x1e},
{e("PlaceProtossBuilding"), 0x1f},
{e("CreateProtossBuilding"), 0x20},
{e("ConstructingBuilding"), 0x21},
{e("Repair"), 0x22},
{e("MoveToRepair"), 0x23},
{e("PlaceAddon"), 0x24},
{e("BuildAddon"), 0x25},
{e("Train"), 0x26},
{e("RallyPointUnit"), 0x27},
{e("RallyPointTile"), 0x28},
{e("ZergBirth"), 0x29},
{e("ZergUnitMorph"), 0x2a},
{e("ZergBuildingMorph"), 0x2b},
{e("IncompleteBuilding"), 0x2c},
{e("IncompleteMorphing"), 0x2d},
{e("BuildNydusExit"), 0x2e},
{e("EnterNydusCanal"), 0x2f},
{e("IncompleteWarping"), 0x30},
{e("Follow"), 0x31},
{e("Carrier"), 0x32},
{e("ReaverCarrierMove"), 0x33},
{e("CarrierStop"), 0x34},
{e("CarrierAttack"), 0x35},
{e("CarrierMoveToAttack"), 0x36},
{e("CarrierIgnore2"), 0x37},
{e("CarrierFight"), 0x38},
{e("CarrierHoldPosition"), 0x39},
{e("Reaver"), 0x3a},
{e("ReaverAttack"), 0x3b},
{e("ReaverMoveToAttack"), 0x3c},
{e("ReaverFight"), 0x3d},
{e("ReaverHoldPosition"), 0x3e},
{e("TrainFighter"), 0x3f},
{e("InterceptorAttack"), 0x40},
{e("ScarabAttack"), 0x41},
{e("RechargeShieldsUnit"), 0x42},
{e("RechargeShieldsBattery"), 0x43},
{e("ShieldBattery"), 0x44},
{e("InterceptorReturn"), 0x45},
{e("DroneLand"), 0x46},
{e("BuildingLand"), 0x47},
{e("BuildingLiftOff"), 0x48},
{e("DroneLiftOff"), 0x49},
{e("LiftingOff"), 0x4a},
{e("ResearchTech"), 0x4b},
{e("Upgrade"), 0x4c},
{e("Larva"), 0x4d},
{e("SpawningLarva"), 0x4e},
{e("Harvest1"), 0x4f},
{e("Harvest2"), 0x50},
{e("MoveToGas"), 0x51},
{e("WaitForGas"), 0x52},
{e("HarvestGas"), 0x53},
{e("ReturnGas"), 0x54},
{e("MoveToMinerals"), 0x55},
{e("WaitForMinerals"), 0x56},
{e("MiningMinerals"), 0x57},
{e("Harvest3"), 0x58},
{e("Harvest4"), 0x59},
{e("ReturnMinerals"), 0x5a},
{e("Interrupted"), 0x5b},
{e("EnterTransport"), 0x5c},
{e("PickupIdle"), 0x5d},
{e("PickupTransport"), 0x5e},
{e("PickupBunker"), 0x5f},
{e("Pickup4"), 0x60},
{e("PowerupIdle"), 0x61},
{e("Sieging"), 0x62},
{e("Unsieging"), 0x63},
{e("WatchTarget"), 0x64},
{e("InitCreepGrowth"), 0x65},
{e("SpreadCreep"), 0x66},
{e("StoppingCreepGrowth"), 0x67},
{e("GuardianAspect"), 0x68},
{e("ArchonWarp"), 0x69},
{e("CompletingArchonSummon"), 0x6a},
{e("HoldPosition"), 0x6b},
{e("QueenHoldPosition"), 0x6c},
{e("Cloak"), 0x6d},
{e("Decloak"), 0x6e},
{e("Unload"), 0x6f},
{e("MoveUnload"), 0x70},
{e("FireYamatoGun"), 0x71},
{e("MoveToFireYamatoGun"), 0x72},
{e("CastLockdown"), 0x73},
{e("Burrowing"), 0x74},
{e("Burrowed"), 0x75},
{e("Unburrowing"), 0x76},
{e("CastDarkSwarm"), 0x77},
{e("CastParasite"), 0x78},
{e("CastSpawnBroodlings"), 0x79},
{e("CastEMPShockwave"), 0x7a},
{e("NukeWait"), 0x7b},
{e("NukeTrain"), 0x7c},
{e("NukeLaunch"), 0x7d},
{e("NukePaint"), 0x7e},
{e("NukeUnit"), 0x7f},
{e("CastNuclearStrike"), 0x80},
{e("NukeTrack"), 0x81},
{e("InitializeArbiter"), 0x82},
{e("CloakNearbyUnits"), 0x83},
{e("PlaceMine"), 0x84},
{e("RightClickAction"), 0x85},
{e("SuicideUnit"), 0x86},
{e("SuicideLocation"), 0x87},
{e("SuicideHoldPosition"), 0x88},
{e("CastRecall"), 0x89},
{e("Teleport"), 0x8a},
{e("CastScannerSweep"), 0x8b},
{e("Scanner"), 0x8c},
{e("CastDefensiveMatrix"), 0x8d},
{e("CastPsionicStorm"), 0x8e},
{e("CastIrradiate"), 0x8f},
{e("CastPlague"), 0x90},
{e("CastConsume"), 0x91},
{e("CastEnsnare"), 0x92},
{e("CastStasisField"), 0x93},
{e("CastHallucination"), 0x94},
{e("Hallucination2"), 0x95},
{e("ResetCollision"), 0x96},
{e("ResetHarvestCollision"), 0x97},
{e("Patrol"), 0x98},
{e("CTFCOPInit"), 0x99},
{e("CTFCOPStarted"), 0x9a},
{e("CTFCOP2"), 0x9b},
{e("ComputerAI"), 0x9c},
{e("AtkMoveEP"), 0x9d},
{e("HarassMove"), 0x9e},
{e("AIPatrol"), 0x9f},
{e("GuardPost"), 0xa0},
{e("RescuePassive"), 0xa1},
{e("Neutral"), 0xa2},
{e("ComputerReturn"), 0xa3},
{e("InitializePsiProvider"), 0xa4},
{e("SelfDestructing"), 0xa5},
{e("Critter"), 0xa6},
{e("HiddenGun"), 0xa7},
{e("OpenDoor"), 0xa8},
{e("CloseDoor"), 0xa9},
{e("HideTrap"), 0xaa},
{e("RevealTrap"), 0xab},
{e("EnableDoodad"), 0xac},
{e("DisableDoodad"), 0xad},
{e("WarpIn"), 0xae},
{e("Medic"), 0xaf},
{e("MedicHeal"), 0xb0},
{e("HealMove"), 0xb1},
{e("MedicHoldPosition"), 0xb2},
{e("MedicHealToIdle"), 0xb3},
{e("CastRestoration"), 0xb4},
{e("CastDisruptionWeb"), 0xb5},
{e("CastMindControl"), 0xb6},
{e("DarkArchonMeld"), 0xb7},
{e("CastFeedback"), 0xb8},
{e("CastOpticalFlare"), 0xb9},
{e("CastMaelstrom"), 0xba},
{e("JunkYardDog"), 0xbb},
{e("Fatal"), 0xbc},
{e("None"), 0xbd},
}
// OrderByID returns the Order for a given ID.
// A new Order with Unknown name is returned if one is not found
// for the given ID (preserving the unknown ID).
func OrderByID(ID byte) *Order {
if int(ID) < len(Orders) {
return Orders[ID]
}
return &Order{repcore.UnknownEnum(ID), ID}
}
// Order IDs
const (
OrderIDStop = 0x01
OrderIDMove = 0x06
OrderIDReaverStop = 0x07
OrderIDAttack1 = 0x08
OrderIDAttack2 = 0x09
OrderIDAttackUnit = 0x0a
OrderIDAttackFixedRange = 0x0b
OrderIDAttackTile = 0x0c
OrderIDAttackMove = 0x0e
OrderIDPlaceProtossBuilding = 0x1f
OrderIDRallyPointUnit = 0x27
OrderIDRallyPointTile = 0x28
OrderIDCarrierStop = 0x34
OrderIDCarrierAttack = 0x35
OrderIDCarrierHoldPosition = 0x39
OrderIDReaverHoldPosition = 0x3e
OrderIDReaverAttack = 0x3b
OrderIDBuildingLand = 0x47
OrderIDHoldPosition = 0x6b
OrderIDQueenHoldPosition = 0x6c
OrderIDUnload = 0x6f
OrderIDMoveUnload = 0x70
OrderIDNukeLaunch = 0x7d
OrderIDCastRecall = 0x89
OrderIDCastScannerSweep = 0x8b
OrderIDMedicHoldPosition = 0xb2
)
// IsOrderIDKindStop tells if the given order ID is one of the stop orders.
func IsOrderIDKindStop(orderID byte) bool {
switch orderID {
case OrderIDStop, OrderIDReaverStop, OrderIDCarrierStop:
return true
}
return false
}
// IsOrderIDKindHold tells if the given order ID is one of the hold orders.
func IsOrderIDKindHold(orderID byte) bool {
switch orderID {
case OrderIDHoldPosition, OrderIDCarrierHoldPosition, OrderIDReaverHoldPosition,
OrderIDQueenHoldPosition, OrderIDMedicHoldPosition:
return true
}
return false
}
// IsOrderIDKindAttack tells if the given order ID is one of the attack orders.
func IsOrderIDKindAttack(orderID byte) bool {
switch orderID {
case OrderIDAttack1, OrderIDAttack2, OrderIDAttackUnit, OrderIDAttackFixedRange,
OrderIDAttackMove, OrderIDCarrierAttack, OrderIDReaverAttack:
return true
}
return false
}
|
// 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 descpb
import (
"testing"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
)
func TestPrivilege(t *testing.T) {
defer leaktest.AfterTest(t)()
descriptor := NewDefaultPrivilegeDescriptor(security.AdminRoleName())
testUser := security.TestUserName()
barUser := security.MakeSQLUsernameFromPreNormalizedString("bar")
testCases := []struct {
grantee security.SQLUsername // User to grant/revoke privileges on.
grant, revoke privilege.List
show []UserPrivilegeString
objectType privilege.ObjectType
}{
{security.SQLUsername{}, nil, nil,
[]UserPrivilegeString{
{security.AdminRoleName(), []string{"ALL"}},
{security.RootUserName(), []string{"ALL"}},
},
privilege.Table,
},
{security.RootUserName(), privilege.List{privilege.ALL}, nil,
[]UserPrivilegeString{
{security.AdminRoleName(), []string{"ALL"}},
{security.RootUserName(), []string{"ALL"}},
},
privilege.Table,
},
{security.RootUserName(), privilege.List{privilege.INSERT, privilege.DROP}, nil,
[]UserPrivilegeString{
{security.AdminRoleName(), []string{"ALL"}},
{security.RootUserName(), []string{"ALL"}},
},
privilege.Table,
},
{testUser, privilege.List{privilege.INSERT, privilege.DROP}, nil,
[]UserPrivilegeString{
{security.AdminRoleName(), []string{"ALL"}},
{security.RootUserName(), []string{"ALL"}},
{testUser, []string{"DROP", "INSERT"}},
},
privilege.Table,
},
{barUser, nil, privilege.List{privilege.INSERT, privilege.ALL},
[]UserPrivilegeString{
{security.AdminRoleName(), []string{"ALL"}},
{security.RootUserName(), []string{"ALL"}},
{testUser, []string{"DROP", "INSERT"}},
},
privilege.Table,
},
{testUser, privilege.List{privilege.ALL}, nil,
[]UserPrivilegeString{
{security.AdminRoleName(), []string{"ALL"}},
{security.RootUserName(), []string{"ALL"}},
{testUser, []string{"ALL"}},
},
privilege.Table,
},
{testUser, nil, privilege.List{privilege.SELECT, privilege.INSERT},
[]UserPrivilegeString{
{security.AdminRoleName(), []string{"ALL"}},
{security.RootUserName(), []string{"ALL"}},
{testUser, []string{"CREATE", "DELETE", "DROP", "GRANT", "UPDATE", "ZONECONFIG"}},
},
privilege.Table,
},
{testUser, nil, privilege.List{privilege.ALL},
[]UserPrivilegeString{
{security.AdminRoleName(), []string{"ALL"}},
{security.RootUserName(), []string{"ALL"}},
},
privilege.Table,
},
// Validate checks that root still has ALL privileges, but we do not call it here.
{security.RootUserName(), nil, privilege.List{privilege.ALL},
[]UserPrivilegeString{
{security.AdminRoleName(), []string{"ALL"}},
},
privilege.Table,
},
// Ensure revoking USAGE from a user with ALL privilege on a type
// leaves the user with only GRANT privilege.
{testUser, privilege.List{privilege.ALL}, privilege.List{privilege.USAGE},
[]UserPrivilegeString{
{security.AdminRoleName(), []string{"ALL"}},
{testUser, []string{"GRANT"}},
},
privilege.Type,
},
// Ensure revoking USAGE, GRANT from a user with ALL privilege on a type
// leaves the user with no privileges.
{testUser,
privilege.List{privilege.ALL}, privilege.List{privilege.USAGE, privilege.GRANT},
[]UserPrivilegeString{
{security.AdminRoleName(), []string{"ALL"}},
},
privilege.Type,
},
// Ensure revoking CREATE, DROP, GRANT, SELECT, INSERT, DELETE, UPDATE, ZONECONFIG
// from a user with ALL privilege on a table leaves the user with no privileges.
{testUser,
privilege.List{privilege.ALL}, privilege.List{privilege.CREATE, privilege.DROP,
privilege.GRANT, privilege.SELECT, privilege.INSERT, privilege.DELETE, privilege.UPDATE,
privilege.ZONECONFIG},
[]UserPrivilegeString{
{security.AdminRoleName(), []string{"ALL"}},
},
privilege.Table,
},
// Ensure revoking CONNECT, CREATE, DROP, GRANT, SELECT, INSERT, DELETE, UPDATE, ZONECONFIG
// from a user with ALL privilege on a database leaves the user with no privileges.
{testUser,
privilege.List{privilege.ALL}, privilege.List{privilege.CONNECT, privilege.CREATE,
privilege.DROP, privilege.GRANT, privilege.SELECT, privilege.INSERT, privilege.DELETE,
privilege.UPDATE, privilege.ZONECONFIG},
[]UserPrivilegeString{
{security.AdminRoleName(), []string{"ALL"}},
},
privilege.Database,
},
}
for tcNum, tc := range testCases {
if !tc.grantee.Undefined() {
if tc.grant != nil {
descriptor.Grant(tc.grantee, tc.grant)
}
if tc.revoke != nil {
descriptor.Revoke(tc.grantee, tc.revoke, tc.objectType)
}
}
show := descriptor.Show(tc.objectType)
if len(show) != len(tc.show) {
t.Fatalf("#%d: show output for descriptor %+v differs, got: %+v, expected %+v",
tcNum, descriptor, show, tc.show)
}
for i := 0; i < len(show); i++ {
if show[i].User != tc.show[i].User || show[i].PrivilegeString() != tc.show[i].PrivilegeString() {
t.Fatalf("#%d: show output for descriptor %+v differs, got: %+v, expected %+v",
tcNum, descriptor, show, tc.show)
}
}
}
}
func TestCheckPrivilege(t *testing.T) {
defer leaktest.AfterTest(t)()
testUser := security.TestUserName()
barUser := security.MakeSQLUsernameFromPreNormalizedString("bar")
testCases := []struct {
pd *PrivilegeDescriptor
user security.SQLUsername
priv privilege.Kind
exp bool
}{
{NewPrivilegeDescriptor(testUser, privilege.List{privilege.CREATE}, security.AdminRoleName()),
testUser, privilege.CREATE, true},
{NewPrivilegeDescriptor(testUser, privilege.List{privilege.CREATE}, security.AdminRoleName()),
barUser, privilege.CREATE, false},
{NewPrivilegeDescriptor(testUser, privilege.List{privilege.CREATE}, security.AdminRoleName()),
barUser, privilege.DROP, false},
{NewPrivilegeDescriptor(testUser, privilege.List{privilege.CREATE}, security.AdminRoleName()),
testUser, privilege.DROP, false},
{NewPrivilegeDescriptor(testUser, privilege.List{privilege.ALL}, security.AdminRoleName()),
testUser, privilege.CREATE, true},
{NewPrivilegeDescriptor(testUser, privilege.List{privilege.CREATE}, security.AdminRoleName()),
testUser, privilege.ALL, false},
{NewPrivilegeDescriptor(testUser, privilege.List{privilege.ALL}, security.AdminRoleName()),
testUser, privilege.ALL, true},
{NewPrivilegeDescriptor(testUser, privilege.List{}, security.AdminRoleName()),
testUser, privilege.ALL, false},
{NewPrivilegeDescriptor(testUser, privilege.List{}, security.AdminRoleName()),
testUser, privilege.CREATE, false},
{NewPrivilegeDescriptor(testUser, privilege.List{privilege.CREATE, privilege.DROP},
security.AdminRoleName()),
testUser, privilege.UPDATE, false},
{NewPrivilegeDescriptor(testUser, privilege.List{privilege.CREATE, privilege.DROP},
security.AdminRoleName()),
testUser, privilege.DROP, true},
{NewPrivilegeDescriptor(testUser, privilege.List{privilege.CREATE, privilege.ALL},
security.AdminRoleName()),
testUser, privilege.DROP, true},
}
for tcNum, tc := range testCases {
if found := tc.pd.CheckPrivilege(tc.user, tc.priv); found != tc.exp {
t.Errorf("#%d: CheckPrivilege(%s, %v) for descriptor %+v = %t, expected %t",
tcNum, tc.user, tc.priv, tc.pd, found, tc.exp)
}
}
}
func TestAnyPrivilege(t *testing.T) {
defer leaktest.AfterTest(t)()
testUser := security.TestUserName()
barUser := security.MakeSQLUsernameFromPreNormalizedString("bar")
testCases := []struct {
pd *PrivilegeDescriptor
user security.SQLUsername
exp bool
}{
{NewPrivilegeDescriptor(testUser, privilege.List{privilege.CREATE}, security.AdminRoleName()),
testUser, true},
{NewPrivilegeDescriptor(testUser, privilege.List{privilege.CREATE}, security.AdminRoleName()),
barUser, false},
{NewPrivilegeDescriptor(testUser, privilege.List{privilege.ALL}, security.AdminRoleName()),
testUser, true},
{NewPrivilegeDescriptor(testUser, privilege.List{}, security.AdminRoleName()),
testUser, false},
{NewPrivilegeDescriptor(testUser, privilege.List{privilege.CREATE, privilege.DROP},
security.AdminRoleName()),
testUser, true},
{NewPrivilegeDescriptor(testUser, privilege.List{privilege.CREATE, privilege.DROP},
security.AdminRoleName()),
barUser, false},
}
for tcNum, tc := range testCases {
if found := tc.pd.AnyPrivilege(tc.user); found != tc.exp {
t.Errorf("#%d: AnyPrivilege(%s) for descriptor %+v = %t, expected %t",
tcNum, tc.user, tc.pd, found, tc.exp)
}
}
}
// TestPrivilegeValidate exercises validation for non-system descriptors.
func TestPrivilegeValidate(t *testing.T) {
defer leaktest.AfterTest(t)()
testUser := security.TestUserName()
id := ID(keys.MinUserDescID)
descriptor := NewDefaultPrivilegeDescriptor(security.AdminRoleName())
if err := descriptor.Validate(id, privilege.Table); err != nil {
t.Fatal(err)
}
descriptor.Grant(testUser, privilege.List{privilege.ALL})
if err := descriptor.Validate(id, privilege.Table); err != nil {
t.Fatal(err)
}
descriptor.Grant(security.RootUserName(), privilege.List{privilege.SELECT})
if err := descriptor.Validate(id, privilege.Table); err != nil {
t.Fatal(err)
}
descriptor.Revoke(security.RootUserName(), privilege.List{privilege.SELECT},
privilege.Table)
if err := descriptor.Validate(id, privilege.Table); err == nil {
t.Fatal("unexpected success")
}
// TODO(marc): validate fails here because we do not aggregate
// privileges into ALL when all are set.
descriptor.Grant(security.RootUserName(), privilege.List{privilege.SELECT})
if err := descriptor.Validate(id, privilege.Table); err == nil {
t.Fatal("unexpected success")
}
descriptor.Revoke(security.RootUserName(), privilege.List{privilege.ALL}, privilege.Table)
if err := descriptor.Validate(id, privilege.Table); err == nil {
t.Fatal("unexpected success")
}
}
func TestValidPrivilegesForObjects(t *testing.T) {
defer leaktest.AfterTest(t)()
id := ID(keys.MinUserDescID)
testUser := security.TestUserName()
testCases := []struct {
objectType privilege.ObjectType
validPrivileges privilege.List
}{
{privilege.Table, privilege.TablePrivileges},
{privilege.Database, privilege.DBPrivileges},
{privilege.Schema, privilege.SchemaPrivileges},
{privilege.Type, privilege.TypePrivileges},
}
for _, tc := range testCases {
for _, priv := range tc.validPrivileges {
privDesc := NewDefaultPrivilegeDescriptor(security.AdminRoleName())
privDesc.Grant(testUser, privilege.List{priv})
err := privDesc.Validate(id, tc.objectType)
if err != nil {
t.Fatal(err)
}
}
// Derive invalidPrivileges from the validPrivileges.
invalidPrivileges := privilege.List{}
for _, priv := range privilege.AllPrivileges {
if priv.Mask() & ^tc.validPrivileges.ToBitField() != 0 {
invalidPrivileges = append(invalidPrivileges, priv)
}
}
for _, priv := range invalidPrivileges {
privDesc := NewDefaultPrivilegeDescriptor(security.AdminRoleName())
privDesc.Grant(testUser, privilege.List{priv})
err := privDesc.Validate(id, tc.objectType)
if err == nil {
t.Fatalf("unexpected success, %s should not be a valid privilege for a %s",
priv, tc.objectType)
}
}
}
}
// TestSystemPrivilegeValidate exercises validation for system config
// descriptors. We use a dummy system table installed for testing
// purposes.
func TestSystemPrivilegeValidate(t *testing.T) {
defer leaktest.AfterTest(t)()
testUser := security.TestUserName()
id := ID(keys.MaxReservedDescID)
if _, exists := SystemAllowedPrivileges[id]; exists {
t.Fatalf("system table with maximum id %d already exists--is the reserved id space full?", id)
}
SystemAllowedPrivileges[id] = privilege.List{
privilege.SELECT,
privilege.GRANT,
}
defer delete(SystemAllowedPrivileges, id)
rootWrongPrivilegesErr := "user root must have exactly SELECT, GRANT " +
"privileges on (system )?table with ID=.*"
adminWrongPrivilegesErr := "user admin must have exactly SELECT, GRANT " +
"privileges on (system )?table with ID=.*"
{
// Valid: root user has one of the allowable privilege sets.
descriptor := NewCustomSuperuserPrivilegeDescriptor(
privilege.List{privilege.SELECT, privilege.GRANT},
security.AdminRoleName(),
)
if err := descriptor.Validate(id, privilege.Table); err != nil {
t.Fatal(err)
}
// Valid: foo has a subset of the allowed privileges.
descriptor.Grant(testUser, privilege.List{privilege.SELECT})
if err := descriptor.Validate(id, privilege.Table); err != nil {
t.Fatal(err)
}
// Valid: foo has exactly the allowed privileges.
descriptor.Grant(testUser, privilege.List{privilege.GRANT})
if err := descriptor.Validate(id, privilege.Table); err != nil {
t.Fatal(err)
}
}
{
// Valid: root has exactly the allowed privileges.
descriptor := NewCustomSuperuserPrivilegeDescriptor(
privilege.List{privilege.SELECT, privilege.GRANT},
security.AdminRoleName(),
)
// Valid: foo has a subset of the allowed privileges.
descriptor.Grant(testUser, privilege.List{privilege.GRANT})
if err := descriptor.Validate(id, privilege.Table); err != nil {
t.Fatal(err)
}
// Valid: foo can have privileges revoked, including privileges it doesn't currently have.
descriptor.Revoke(
testUser, privilege.List{privilege.GRANT, privilege.UPDATE, privilege.ALL}, privilege.Table)
if err := descriptor.Validate(id, privilege.Table); err != nil {
t.Fatal(err)
}
// Invalid: root user has too many privileges.
descriptor.Grant(security.RootUserName(), privilege.List{privilege.UPDATE})
if err := descriptor.Validate(id, privilege.Table); !testutils.IsError(err, rootWrongPrivilegesErr) {
t.Fatalf("expected err=%s, got err=%v", rootWrongPrivilegesErr, err)
}
}
{
// Invalid: root has a non-allowable privilege set.
descriptor := NewCustomSuperuserPrivilegeDescriptor(privilege.List{privilege.UPDATE},
security.AdminRoleName())
if err := descriptor.Validate(id, privilege.Table); !testutils.IsError(err, rootWrongPrivilegesErr) {
t.Fatalf("expected err=%s, got err=%v", rootWrongPrivilegesErr, err)
}
// Invalid: root's invalid privileges are revoked and replaced with allowable privileges,
// but admin is still wrong.
descriptor.Revoke(security.RootUserName(), privilege.List{privilege.UPDATE}, privilege.Table)
descriptor.Grant(security.RootUserName(), privilege.List{privilege.SELECT, privilege.GRANT})
if err := descriptor.Validate(id, privilege.Table); !testutils.IsError(err, adminWrongPrivilegesErr) {
t.Fatalf("expected err=%s, got err=%v", adminWrongPrivilegesErr, err)
}
// Valid: admin's invalid privileges are revoked and replaced with allowable privileges.
descriptor.Revoke(security.AdminRoleName(), privilege.List{privilege.UPDATE}, privilege.Table)
descriptor.Grant(security.AdminRoleName(), privilege.List{privilege.SELECT, privilege.GRANT})
if err := descriptor.Validate(id, privilege.Table); err != nil {
t.Fatal(err)
}
// Valid: foo has less privileges than root.
descriptor.Grant(testUser, privilege.List{privilege.GRANT})
if err := descriptor.Validate(id, privilege.Table); err != nil {
t.Fatal(err)
}
}
}
func TestFixPrivileges(t *testing.T) {
defer leaktest.AfterTest(t)()
// Use a non-system ID.
userID := ID(keys.MinUserDescID)
userPrivs := privilege.List{privilege.ALL}
// And create an entry for a fake system table.
systemID := ID(keys.MaxReservedDescID)
if _, exists := SystemAllowedPrivileges[systemID]; exists {
t.Fatalf("system object with maximum id %d already exists--is the reserved id space full?", systemID)
}
systemPrivs := privilege.List{
privilege.SELECT,
privilege.GRANT,
}
SystemAllowedPrivileges[systemID] = systemPrivs
defer delete(SystemAllowedPrivileges, systemID)
type userPrivileges map[security.SQLUsername]privilege.List
fooUser := security.MakeSQLUsernameFromPreNormalizedString("foo")
barUser := security.MakeSQLUsernameFromPreNormalizedString("bar")
bazUser := security.MakeSQLUsernameFromPreNormalizedString("baz")
testCases := []struct {
id ID
input userPrivileges
modified bool
output userPrivileges
}{
{
// Empty privileges for system ID.
systemID,
userPrivileges{},
true,
userPrivileges{
security.RootUserName(): systemPrivs,
security.AdminRoleName(): systemPrivs,
},
},
{
// Valid requirements for system ID.
systemID,
userPrivileges{
security.RootUserName(): systemPrivs,
security.AdminRoleName(): systemPrivs,
fooUser: privilege.List{privilege.SELECT},
barUser: privilege.List{privilege.GRANT},
bazUser: privilege.List{privilege.SELECT, privilege.GRANT},
},
false,
userPrivileges{
security.RootUserName(): systemPrivs,
security.AdminRoleName(): systemPrivs,
fooUser: privilege.List{privilege.SELECT},
barUser: privilege.List{privilege.GRANT},
bazUser: privilege.List{privilege.SELECT, privilege.GRANT},
},
},
{
// Too many privileges for system ID.
systemID,
userPrivileges{
security.RootUserName(): privilege.List{privilege.ALL},
security.AdminRoleName(): privilege.List{privilege.ALL},
fooUser: privilege.List{privilege.ALL},
barUser: privilege.List{privilege.SELECT, privilege.UPDATE},
},
true,
userPrivileges{
security.RootUserName(): systemPrivs,
security.AdminRoleName(): systemPrivs,
fooUser: privilege.List{},
barUser: privilege.List{privilege.SELECT},
},
},
{
// Empty privileges for non-system ID.
userID,
userPrivileges{},
true,
userPrivileges{
security.RootUserName(): userPrivs,
security.AdminRoleName(): userPrivs,
},
},
{
// Valid requirements for non-system ID.
userID,
userPrivileges{
security.RootUserName(): userPrivs,
security.AdminRoleName(): userPrivs,
fooUser: privilege.List{privilege.SELECT},
barUser: privilege.List{privilege.GRANT},
bazUser: privilege.List{privilege.SELECT, privilege.GRANT},
},
false,
userPrivileges{
security.RootUserName(): userPrivs,
security.AdminRoleName(): userPrivs,
fooUser: privilege.List{privilege.SELECT},
barUser: privilege.List{privilege.GRANT},
bazUser: privilege.List{privilege.SELECT, privilege.GRANT},
},
},
{
// All privileges are allowed for non-system ID, but we need super users.
userID,
userPrivileges{
fooUser: privilege.List{privilege.ALL},
barUser: privilege.List{privilege.UPDATE},
},
true,
userPrivileges{
security.RootUserName(): privilege.List{privilege.ALL},
security.AdminRoleName(): privilege.List{privilege.ALL},
fooUser: privilege.List{privilege.ALL},
barUser: privilege.List{privilege.UPDATE},
},
},
}
for num, testCase := range testCases {
desc := &PrivilegeDescriptor{}
for u, p := range testCase.input {
desc.Grant(u, p)
}
if a, e := MaybeFixPrivileges(testCase.id, &desc), testCase.modified; a != e {
t.Errorf("#%d: expected modified=%t, got modified=%t", num, e, a)
continue
}
if a, e := len(desc.Users), len(testCase.output); a != e {
t.Errorf("#%d: expected %d users (%v), got %d (%v)", num, e, testCase.output, a, desc.Users)
continue
}
for u, p := range testCase.output {
outputUser, ok := desc.findUser(u)
if !ok {
t.Fatalf("#%d: expected user %s in output, but not found (%v)", num, u, desc.Users)
}
if a, e := privilege.ListFromBitField(outputUser.Privileges, privilege.Any), p; a.ToBitField() != e.ToBitField() {
t.Errorf("#%d: user %s: expected privileges %v, got %v", num, u, e, a)
}
}
}
}
func TestValidateOwnership(t *testing.T) {
defer leaktest.AfterTest(t)()
// Use a non-system id.
id := ID(keys.MinUserDescID)
// A privilege descriptor with a version before OwnerVersion can have
// no owner.
privs := PrivilegeDescriptor{
Users: []UserPrivileges{
{
UserProto: security.AdminRoleName().EncodeProto(),
Privileges: DefaultSuperuserPrivileges.ToBitField(),
},
{
UserProto: security.RootUserName().EncodeProto(),
Privileges: DefaultSuperuserPrivileges.ToBitField(),
},
}}
err := privs.Validate(id, privilege.Table)
if err != nil {
t.Fatal(err)
}
// A privilege descriptor with version OwnerVersion and onwards should
// have an owner.
privs = PrivilegeDescriptor{
Users: []UserPrivileges{
{
UserProto: security.AdminRoleName().EncodeProto(),
Privileges: DefaultSuperuserPrivileges.ToBitField(),
},
{
UserProto: security.RootUserName().EncodeProto(),
Privileges: DefaultSuperuserPrivileges.ToBitField(),
},
},
Version: OwnerVersion,
}
err = privs.Validate(id, privilege.Table)
if err == nil {
t.Fatal("unexpected success")
}
privs = PrivilegeDescriptor{
OwnerProto: security.RootUserName().EncodeProto(),
Users: []UserPrivileges{
{
UserProto: security.AdminRoleName().EncodeProto(),
Privileges: DefaultSuperuserPrivileges.ToBitField(),
},
{
UserProto: security.RootUserName().EncodeProto(),
Privileges: DefaultSuperuserPrivileges.ToBitField(),
},
},
Version: OwnerVersion,
}
err = privs.Validate(id, privilege.Table)
if err != nil {
t.Fatal(err)
}
}
|
package model
import (
"errors"
"fmt"
"net/http"
"strconv"
"github.com/manyminds/api2go"
"github.com/manyminds/api2go/jsonapi"
)
type Car struct {
ID uint64 `json:"-"`
Brand string `json:"brand"`
Model string `json:"model"`
Price uint64 `json:"price"`
Status string `json:"status"` // OnTheWay, InStock, Sold, Discontinued
Mileage int64 `json:"mileage"` // I suppose it should be made unsigned, but that's what the task says ¯\_(ツ)_/¯
}
func (c Car) Verify() (bool, api2go.HTTPError) {
var verifyErrors []api2go.Error
var httpError api2go.HTTPError
if c.Brand == "" {
newErr := newVerifyError(
"Invalid Attribute",
"attribute cannot be empty",
"/data/attributes/brand")
verifyErrors = append(verifyErrors, newErr)
}
if c.Model == "" {
newErr := newVerifyError(
"Invalid Attribute",
"attribute cannot be empty",
"/data/attributes/model")
verifyErrors = append(verifyErrors, newErr)
}
if c.Status != "OnTheWay" &&
c.Status != "InStock" &&
c.Status != "Sold" &&
c.Status != "Discontinued" {
newErr := newVerifyError(
"Invalid Attribute",
"attribute must be one of: OnTheWay, InStock, Sold, Discontinued",
"/data/attributes/status")
verifyErrors = append(verifyErrors, newErr)
}
ok := len(verifyErrors) == 0
if !ok {
httpError = api2go.NewHTTPError(
errors.New("Invalid content"),
"Invalid content",
http.StatusBadRequest)
httpError.Errors = verifyErrors
}
return ok, httpError
}
func newVerifyError(title string, detail string, pointer string) api2go.Error {
var newError api2go.Error
newError.Title = title
newError.Detail = detail
newError.Source = &api2go.ErrorSource{Pointer: pointer}
return newError
}
// GetID to satisfy jsonapi.MarshalIdentifier interface
func (c Car) GetID() string {
return fmt.Sprintf("%d", c.ID)
}
// SetID to satisfy jsonapi.UnmarshalIdentifier interface
func (c *Car) SetID(id string) error {
if id == "" {
c.ID = 0
return nil
}
intID, err := strconv.ParseUint(id, 10, 64)
if err != nil {
return err
}
c.ID = intID
return nil
}
// GetReferences to satisfy the jsonapi.MarshalReferences interface
func (c Car) GetReferences() []jsonapi.Reference {
return []jsonapi.Reference{}
}
// GetReferencedIDs to satisfy the jsonapi.MarshalLinkedRelations interface
func (c Car) GetReferencedIDs() []jsonapi.ReferenceID {
return []jsonapi.ReferenceID{}
}
// GetReferencedStructs to satisfy the jsonapi.MarhsalIncludedRelations interface
func (c Car) GetReferencedStructs() []jsonapi.MarshalIdentifier {
return []jsonapi.MarshalIdentifier{}
}
// SetToManyReferenceIDs sets the sweets reference IDs and satisfies the jsonapi.UnmarshalToManyRelations interface
func (c *Car) SetToManyReferenceIDs(name string, IDs []string) error {
return errors.New("There is no to-many relationship with the name " + name)
}
// AddToManyIDs adds some new sweets that a users loves so much
func (c *Car) AddToManyIDs(name string, IDs []string) error {
return errors.New("There is no to-many relationship with the name " + name)
}
// DeleteToManyIDs removes some sweets from a users because they made him very sick
func (c *Car) DeleteToManyIDs(name string, IDs []string) error {
return errors.New("There is no to-many relationship with the name " + name)
}
|
package main
import (
"database/sql"
"flag"
"github.com/joho/godotenv"
"log"
"lucasantarella.com/businesscards/internal"
"net"
"net/http"
"os"
"strings"
"context"
"github.com/golang/glog"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
pb "github.com/lucasantarella/business-profiles-grpc-golib"
"google.golang.org/grpc"
)
func run() error {
_ = godotenv.Load() // Ignore error
grpcPort, present := os.LookupEnv("GRPC_PORT")
if !present {
grpcPort = ":50051"
} else {
grpcPort = ":" + grpcPort
}
httpListenPort, present := os.LookupEnv("HTTP_PORT")
if !present {
httpListenPort = ":9001"
} else {
httpListenPort = ":" + httpListenPort
}
db, err := sql.Open("mysql", os.Getenv("DB_USER")+":"+os.Getenv("DB_PASS")+"@tcp("+os.Getenv("DB_HOST")+")/"+os.Getenv("DB_NAME")+"?charset=utf8&parseTime=True")
if err != nil {
panic(err)
}
db.SetMaxOpenConns(15)
db.SetMaxIdleConns(1)
defer db.Close()
log.Printf("grpc listening on port: %s", grpcPort)
lis, err := net.Listen("tcp", grpcPort)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterProfilesServiceServer(s, &internal.Server{Db: db})
go s.Serve(lis)
conn, err := grpc.DialContext(
context.Background(),
"127.0.0.1"+grpcPort,
grpc.WithInsecure(),
)
if err != nil {
log.Fatalln("Failed to dial server:", err)
}
router := runtime.NewServeMux()
if err = pb.RegisterProfilesServiceHandler(context.Background(), router, conn); err != nil {
log.Fatalln("Failed to register gateway:", err)
}
log.Printf("http listening on port: %s", httpListenPort)
return http.ListenAndServe(httpListenPort, httpGrpcRouter(s, router))
}
func httpGrpcRouter(grpcServer *grpc.Server, httpHandler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
grpcServer.ServeHTTP(w, r)
} else {
httpHandler.ServeHTTP(w, r)
}
})
}
func main() {
flag.Parse()
defer glog.Flush()
if err := run(); err != nil {
glog.Fatal(err)
}
}
|
package v1alpha1
import (
"testing"
"github.com/onsi/gomega"
"golang.org/x/net/context"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
)
func TestStorageGlobalRoleBinding(t *testing.T) {
key := types.NamespacedName{
Name: "dogs",
}
created := &GlobalRoleBinding{
ObjectMeta: metav1.ObjectMeta{Name: "dogs"},
Subjects: []Subject{{
Kind: "User",
APIGroup: "rbac.authorization.k8s.io",
Name: "Mohr",
}},
RoleRef: RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: "dogs",
},
Namespaces: "mr-*",
}
g := gomega.NewGomegaWithT(t)
// Test Create
fetched := &GlobalRoleBinding{}
g.Expect(c.Create(context.TODO(), created)).NotTo(gomega.HaveOccurred())
g.Expect(c.Get(context.TODO(), key, fetched)).NotTo(gomega.HaveOccurred())
g.Expect(fetched).To(gomega.Equal(created))
// Test Updating the Labels
updated := fetched.DeepCopy()
updated.Labels = map[string]string{"hello": "world"}
g.Expect(c.Update(context.TODO(), updated)).NotTo(gomega.HaveOccurred())
g.Expect(c.Get(context.TODO(), key, fetched)).NotTo(gomega.HaveOccurred())
g.Expect(fetched).To(gomega.Equal(updated))
// Test Delete
g.Expect(c.Delete(context.TODO(), fetched)).NotTo(gomega.HaveOccurred())
g.Expect(c.Get(context.TODO(), key, fetched)).To(gomega.HaveOccurred())
}
|
package main
import (
"bytes"
"context"
"flag"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/Masterminds/semver"
"github.com/VictoriaMetrics/metrics"
"github.com/afoninsky/version-exporter/probers"
"gocloud.dev/blob"
_ "gocloud.dev/blob/azureblob"
_ "gocloud.dev/blob/fileblob"
_ "gocloud.dev/blob/gcsblob"
_ "gocloud.dev/blob/memblob"
_ "gocloud.dev/blob/s3blob"
"gocloud.dev/gcerrors"
"gopkg.in/yaml.v2"
)
var fListen = flag.String("listen", "127.0.0.1:8080", "The address to listen on for HTTP requests")
var fConfig = flag.String("config", "./probes.yaml", "Configuration file path")
var fEndpoint = flag.String("endpoint", "/metrics", "Metrics HTTP endpoint")
var fStorage = flag.String("storage", "mem://", "Storage path")
type probes map[string]struct {
Interval time.Duration `yaml:"interval"`
Type string `yaml:"type"`
Config string `yaml:"config"`
}
func main() {
flag.Parse()
cfg, err := loadConfig(*fConfig)
if err != nil {
log.Fatal(err)
}
bucket, err := blob.OpenBucket(context.Background(), *fStorage)
if err != nil {
log.Fatal(err)
}
for name, probe := range cfg {
log.Printf(`Testing %s with interval %s`, name, probe.Interval)
p, err := probers.New(probe.Type, probe.Config)
if err != nil {
log.Fatal(err)
}
go startProber(name, p, probe.Interval, bucket)
}
http.HandleFunc("/metrics", func(w http.ResponseWriter, req *http.Request) {
metrics.WritePrometheus(w, false)
})
log.Printf("Expose metrics: %s%s", *fListen, *fEndpoint)
log.Fatal(http.ListenAndServe(*fListen, nil))
}
func loadConfig(cfgPath string) (probes, error) {
f, err := os.Open(cfgPath)
if err != nil {
return nil, err
}
defer f.Close()
var cfg probes
if err := yaml.NewDecoder(f).Decode(&cfg); err != nil {
return nil, err
}
return cfg, nil
}
func startProber(name string, p probers.Prober, d time.Duration, storage *blob.Bucket) {
for {
time.Sleep(d)
v, err := getCurrentVersion(storage, name)
if err != nil {
log.Fatal(err)
}
newV, err := p.Probe(v)
if err != nil {
log.Printf("[ERROR] %s: %v", name, err)
continue
}
if v == "" || v == newV {
continue
}
// TODO: parse string to semver
pNewV, err := semver.NewVersion(newV)
if err != nil {
log.Printf("[ERROR] parsing version: %s: %v", name, err)
continue
}
if err := saveVersion(storage, name, newV); err != nil {
log.Fatal(err)
}
log.Printf("%s, new version: %s -> %s\n", name, v, newV)
labels := fmt.Sprintf(`semver_release{probe="%s",version="%s",version_major="%d",version_minor="%d",version_patch="%d"}`,
name,
pNewV,
pNewV.Major(),
pNewV.Minor(),
pNewV.Patch(),
)
metrics.GetOrCreateCounter(labels).Set(1)
}
}
// stores value in storage
func saveVersion(storage *blob.Bucket, name string, v string) error {
w, err := storage.NewWriter(context.Background(), name, nil)
if err != nil {
return err
}
_, err = fmt.Fprint(w, v)
if err != nil {
return err
}
return w.Close()
}
// reads value from storage
func getCurrentVersion(storage *blob.Bucket, name string) (string, error) {
r, err := storage.NewReader(context.Background(), name, nil)
if err != nil {
if gcerrors.Code(err) == gcerrors.NotFound {
v, _ := semver.NewVersion("0.0.0")
return v.String(), nil
}
return "", err
}
defer r.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(r)
return buf.String(), nil
}
|
package users_test
import (
"reflect"
"testing"
"users"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
func testAuth(t *testing.T, repo users.UsersRepo) {
s := users.NewService(repo)
expectedUser := makeUser()
if err := repo.Create(expectedUser); err != nil {
t.Fatal(err)
}
// with email
var emailActualUser users.User
if err := s.Auth("test@email.com", "pass", &emailActualUser); err != nil {
t.Fatalf("Can't authorize user: %s", err)
}
if expectedUser.ID != emailActualUser.ID {
t.Fatal("Returned user with wrong id")
}
// with username
var usernameActualUser users.User
if err := s.Auth("test", "pass", &usernameActualUser); err != nil {
t.Fatalf("Can't authorize user: %s", err)
}
if expectedUser.ID != usernameActualUser.ID {
t.Fatal("Returned user with wrong id")
}
var failUser users.User
// unknown user
if err := s.Auth("unknown@email.com", "pass", &failUser); err != users.ErrAuthFailed {
t.Fatal("should return auth error, returned: %s", err)
}
// wrong pass
if err := s.Auth("test@email.com", "wrong", &failUser); err != users.ErrAuthFailed {
t.Fatalf("should return auth error, returned: %s", err)
}
// inactive
expectedUser.Active = false
if err := repo.Update(expectedUser); err != nil {
t.Fatal("can't update user, returned: %s", err)
}
if err := s.Auth("test", "pass", &failUser); err != users.ErrUserDisabled {
t.Fatal("should return disabled error, returned: %s", err)
}
}
func testCreate(t *testing.T, repo users.UsersRepo) {
s := users.NewService(repo)
i := &users.CreateUser{
Email: "test@email.com",
Username: "test",
Password: "pass",
Roles: []string{"role1", "role2"},
}
id, err := s.Create(i)
if err != nil {
t.Fatalf("Can't create user: %s", err)
}
var expectedUser users.User
if err := repo.Get(id, &expectedUser); err != nil {
t.Fatalf("Can't find user in repo: %s", err)
}
if expectedUser.Email != i.Email {
t.Fatal("Saved email doesn't much with passed email")
}
}
func testGet(t *testing.T, repo users.UsersRepo) {
s := users.NewService(repo)
expectedUser := makeUser()
repo.Create(expectedUser)
var actualUser users.User
if err := s.Get(expectedUser.ID, &actualUser); err != nil {
t.Fatalf("Can't get user, err: %s", err)
}
if expectedUser.Email != actualUser.Email {
t.Fatalf("users don't match")
}
}
func testUpdate(t *testing.T, repo users.UsersRepo) {
s := users.NewService(repo)
initialUser := makeUser()
repo.Create(initialUser)
expectedUser := *initialUser
expectedUser.Active = false
expectedUser.Roles = []string{"newrole"}
i := &users.UpdateUser{
Active: false,
Roles: []string{"newrole"},
}
if err := s.Update(initialUser.ID, i); err != nil {
t.Fatalf("can't update user: %s", err)
}
var actualUser users.User
if err := s.Get(expectedUser.ID, &actualUser); err != nil {
t.Fatalf("Can't get user, err: %s", err)
}
if !reflect.DeepEqual(expectedUser, actualUser) {
t.Fatalf("users don't match\nexpected:\n%+v\nactual:\n%+v", expectedUser, actualUser)
}
}
func testList(t *testing.T, repo users.UsersRepo) {
s := users.NewService(repo)
expectedUsers := make([]*users.User, 0)
inputs := []*users.CreateUser{
&users.CreateUser{
Email: "user1@email.com",
Username: "user1",
Password: "pass",
Roles: []string{"role1", "role2"},
},
&users.CreateUser{
Email: "user2@email.com",
Username: "user2",
Password: "pass",
Roles: []string{"role1", "role2"},
},
&users.CreateUser{
Email: "user3@email.com",
Username: "user3",
Password: "pass",
Roles: []string{"role1", "role2"},
},
}
for i, _ := range inputs {
var u users.User
id, err := s.Create(inputs[i])
if err != nil {
panic(err)
}
if err := s.Get(id, &u); err != nil {
panic(err)
}
expectedUsers = append(expectedUsers, &u)
}
// returns correctly
filter := users.NewFilter()
total, us, err := s.List(filter)
listResultTest(t, total, err)
if len(us) != 3 {
t.Fatalf("count %d != 3", len(us))
}
for i, _ := range us {
if !reflect.DeepEqual(expectedUsers[i], us[i]) {
t.Fatalf("user doesn't match expected:\n%+v\nactual\n%+v", expectedUsers[i], us[i])
}
}
// pagination 1 page
filter = users.NewFilter()
filter.PerPage = 2
us = make([]*users.User, 0)
total, us, err = s.List(filter)
listResultTest(t, total, err)
if len(us) != 2 {
t.Fatalf("count %d != 2", len(us))
}
for i, _ := range us {
if !reflect.DeepEqual(expectedUsers[i], us[i]) {
t.Fatalf("user doesn't match expected:\n%+v\nactual\n%+v", expectedUsers[i], us[i])
}
}
// pagination 2 page
filter = users.NewFilter()
filter.Page = 2
filter.PerPage = 1
us = make([]*users.User, 0)
total, us, err = s.List(filter)
listResultTest(t, total, err)
if len(us) != 1 {
t.Fatalf("count %d != 1", len(us))
}
if !reflect.DeepEqual(expectedUsers[1], us[0]) {
t.Fatalf("user doesn't match expected:\n%+v\nactual\n%+v", expectedUsers[1], us[0])
}
// filter email
filter = users.NewFilter()
filter.Email = "user2@email"
us = make([]*users.User, 0)
total, us, err = s.List(filter)
if err != nil {
t.Fatalf("list err: %s", err)
}
if total != 1 {
t.Fatalf("total %d != 1", total)
}
if len(us) != 1 {
t.Fatalf("count %d != 1", len(us))
}
if !reflect.DeepEqual(expectedUsers[1], us[0]) {
t.Fatalf("user doesn't match expected:\n%+v\nactual\n%+v", expectedUsers[1], us[0])
}
// filter username
filter = users.NewFilter()
filter.Username = "user3"
us = make([]*users.User, 0)
total, us, err = s.List(filter)
if err != nil {
t.Fatalf("list err: %s", err)
}
if total != 1 {
t.Fatalf("total %d != 1", total)
}
if len(us) != 1 {
t.Fatalf("count %d != 1", len(us))
}
if !reflect.DeepEqual(expectedUsers[2], us[0]) {
t.Fatalf("user doesn't match expected:\n%+v\nactual\n%+v", expectedUsers[2], us[0])
}
}
func listResultTest(t *testing.T, total int, err error) {
if err != nil {
t.Fatalf("list err: %s", err)
}
if total != 3 {
t.Fatalf("total %d != 3", total)
}
}
func TestService_InMemory(t *testing.T) {
repo := users.NewUsersInMemory()
testAuth(t, repo)
repo = users.NewUsersInMemory()
testCreate(t, repo)
repo = users.NewUsersInMemory()
testGet(t, repo)
repo = users.NewUsersInMemory()
testUpdate(t, repo)
repo = users.NewUsersInMemory()
testList(t, repo)
}
func TestService_Redis(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
repo := users.NewUsersRedis(redisClient, "auth")
testAuth(t, repo)
repo = users.NewUsersRedis(redisClient, "create")
testCreate(t, repo)
repo = users.NewUsersRedis(redisClient, "get")
testGet(t, repo)
repo = users.NewUsersRedis(redisClient, "update")
testUpdate(t, repo)
repo = users.NewUsersRedis(redisClient, "list")
testList(t, repo)
}
func TestService_Gorm_PG(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
if noGorm {
t.Skip()
}
gDB = makePostgres("")
repo := users.NewUsersGorm(gDB)
testAuth(t, repo)
gDB.Close()
gDB = makePostgres("")
repo = users.NewUsersGorm(gDB)
testCreate(t, repo)
gDB.Close()
gDB = makePostgres("")
repo = users.NewUsersGorm(gDB)
testGet(t, repo)
gDB.Close()
gDB = makePostgres("")
repo = users.NewUsersGorm(gDB)
testUpdate(t, repo)
gDB.Close()
gDB = makePostgres("")
repo = users.NewUsersGorm(gDB)
testList(t, repo)
}
|
package adding
var DefaultOrders = []Order{
{
ID: 1,
Amount: 10,
Status: "init",
OrderLines: []OrderLines{
OrderLines{
SKU: "TROP-UA-PLAS-09",
Price: 10,
Quantity: 1,
},
OrderLines{
SKU: "TROP-NP-PLAS-65",
Price: 10,
Quantity: 2,
},
OrderLines{
SKU: "TROP-LT-PLAS-89",
Price: 5,
Quantity: 10,
},
},
ShippingAddress: Address{
FirstName: "Jhon",
LastName: "Snow",
Email: "j.snow@example.com",
Company: "Acme",
Phone: "555000111",
Line1: "711-2880 Nulla St.",
Line2: "",
Line3: "",
City: "Mankato",
Country: "Mississippi",
Zip: "96522",
},
BillingAddress: Address{
FirstName: "Jhon",
LastName: "Snow",
Email: "j.snow@example.com",
Company: "Acme",
Phone: "555000111",
Line1: "711-2880 Nulla St.",
Line2: "",
Line3: "",
City: "Mankato",
Country: "Mississippi",
Zip: "96522",
},
},
}
|
package main
import (
"fabriciojs/murmurhash3"
"fmt"
"time"
"flag"
)
var test = flag.Int("test", 0, "test")
const K = 21474836 * 10
func main() {
flag.Parse()
fmt.Println("murmurhash")
hashes := make([][2]uint64, *test)
start := time.Now()
for i := 0; i < *test; i++ {
hashes[i] = murmurhash3.Murmur3F([]byte(fmt.Sprintf("key_%d", i)), 1287253131031037)
}
fmt.Println("generated in: ", time.Since(start))
start = time.Now()
fmt.Println("analysis colisions...")
colisions0 := make(map[uint64]int)
colisions1 := make(map[uint64]int)
for i := 0; i < *test; i++ {
hash := murmurhash3.Murmur3F([]byte(fmt.Sprintf("key_%d", i)), 1287253131031037)
colisions0[hash[0] % K]++
colisions1[hash[1] % K]++
}
c0, c1 := 0, 0
for _, c := range colisions0 {
if c > 1 {
c0 += c - 1
}
}
for _, c := range colisions1 {
if c > 1 {
c1 += c - 1
}
}
fmt.Println("analysed in: ", time.Since(start))
fmt.Println("colisions")
fmt.Println("hash[0]", c0)
fmt.Println("hash[1]", c1)
}
|
package week02
import (
"fmt"
"strconv"
"strings"
)
// https://leetcode-cn.com/problems/subdomain-visit-count/
// https://leetcode-cn.com/submissions/detail/190774264/
func subdomainVisits(cpdomains []string) []string {
domainStat := map[string]int{}
for _, v := range cpdomains {
domains, stat := parseDomainVisit(v)
for _, d := range domains {
domainStat[d] += stat
}
}
ans := []string{}
for k, v := range domainStat {
ans = append(ans, fmt.Sprintf("%d %s", v, k))
}
return ans
}
func parseDomainVisit(in string) (domains []string, visits int) {
ins := strings.Split(in, " ")
if len(ins) != 2 {
return
}
visits, _ = strconv.Atoi(ins[0])
fragments := strings.Split(ins[1], ".")
for l := len(fragments) - 1; l >= 0; l-- {
domains = append(domains, strings.Join(fragments[l:], "."))
}
return
}
|
package handler
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/SuperTikuwa/mission-techdojo/dbctl"
"github.com/SuperTikuwa/mission-techdojo/model"
)
func EmissionRateHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
rateRequest := model.EmissionRateRequest{}
if err := json.Unmarshal(body, &rateRequest); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !dbctl.GachaExists(rateRequest.GachaID) && rateRequest.GachaID != 0 {
http.Error(w, "Gacha does not exist", http.StatusNotFound)
return
}
rateResponse, err := dbctl.CalcEmissionRate(rateRequest.GachaID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
responseJson, err := json.Marshal(rateResponse)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, string(responseJson))
}
|
// Constants
package GridSearch
import (
"fmt"
"math"
)
/*
the relationship between parent node and
child node:
c1 = p*4 + 1
c2 = p*4 + 2
c3 = p*4 + 3
c4 = p*4 + 4
0|1,2,3,4|5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20|21,...
suppose we have 11 layer:
4^0 + 4^1 + ... + 4^10 = 1398101
*/
const (
TREEDEPTH = 11
GRID_TOP_WIDTH = 1024 * 512
GRID_TOP_HEIGHT = 1024 * (256 + 128)
indexDir = "data"
FIRSTINDEXFILE = 0 //first indices stored in files
FIRSTINDEXMEM = 1 //first indices stored in mem
FIRSTINDEXMODE = FIRSTINDEXFILE
INDEXTHREADNUM = 1 //gorountine num for indexing
DOCMERGENUM = 20000 //the threshold of the doc to store in file
)
var (
print = fmt.Println
GRID_COL_NUM = gridColNum()
GRID_ROW_NUM = gridRowNum()
CHINA_RECT = chinaRect()
gridNum = GRID_ROW_NUM * GRID_COL_NUM
BOTTOMLEVELGRIDNUM = math.Pow(4, TREEDEPTH-1)
BOTTOMGRIDNUM = int32(BOTTOMLEVELGRIDNUM)
BOTTOMFIRSTGRIDID = getLayerFirstIx(float64(TREEDEPTH - 1))
)
|
package main
import "fmt"
type Node struct {
Value int
Next *Node
}
var head = new(Node)
var end *Node
func main() {
for i := 0; i < 5; i++ {
n := &Node{
Value: i + 1,
}
AddNode(n)
}
josephus(1, 3)
}
func AddNode(t *Node) {
if end == nil {
head = t
t.Next = head
end = t
} else {
end.Next = t
t.Next = head
end = t
}
}
//josephus k is the beginning number util count the number of n is out of the collection.
func josephus(k, n int) {
count := 1
for i := 0; i < k-1; i++ {
head = head.Next
end = end.Next
}
for {
count++
head = head.Next
end = end.Next
if count == n {
fmt.Println(head.Value, " is out.")
end.Next = head.Next
head = head.Next
count = 1
}
if head == end {
fmt.Println(head.Value, " still in, and finally alive.")
break
}
}
}
|
package editorapi
import (
"editorApi/controller/servers"
"github.com/gin-gonic/gin"
)
var (
COURSE_ASSETS_DOMAIN string = "https://course-assets1.talkmate.com"
COURSE_ASSETS_BUCKET string = "assets"
COURSE_UPLOADFILE_BUCKET string = "uploadfiles"
COURSE_UPLOADFILE_DOMAIN string = "https://uploadfile1.talkmate.com"
EDITOR_DB string = "editor"
)
// @Tags EditorInfoAPI(公共信息接口)
// @Summary 获取上传课程资料的七牛Token , bucket:assets
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"成功"}"
// @Router /editor/info/token [get]
func QiniuToken(c *gin.Context) {
servers.ReportFormat(c, true, "课程资料上传Token", gin.H{
"token": servers.UploadToken(COURSE_ASSETS_BUCKET),
})
}
// @Tags EditorInfoAPI(公共信息接口)
// @Summary 获取上传课程资料的七牛Token , bucket:uploadfile
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"成功"}"
// @Router /editor/info/token/uploadfile [get]
func QiniuUploadFileToken(c *gin.Context) {
servers.ReportFormat(c, true, "课程资料上传Token", gin.H{
"token": servers.UploadToken(COURSE_UPLOADFILE_BUCKET),
})
}
// @Tags EditorInfoAPI(公共信息接口)
// @Summary 获取配置信息
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"成功"}"
// @Router /editor/info/config [get]
func ConfigInfo(c *gin.Context) {
servers.ReportFormat(c, true, "配置信息", gin.H{
"langInfos": []map[string]string{
map[string]string{
"langKey": "zh-CN",
"name": "中文",
},
map[string]string{
"langKey": "en",
"name": "英文",
},
},
"assetsDomain": COURSE_ASSETS_DOMAIN,
"uploadfileDomain": COURSE_UPLOADFILE_DOMAIN,
})
}
|
package service
import (
"context"
"flag"
"fmt"
"github.com/gorilla/mux"
"google.golang.org/grpc"
"myRPC/http"
"myRPC/hystrix"
balanceBase "myRPC/loadBalance/base"
logBase "myRPC/log/base"
limitBase "myRPC/limit/base"
registryBase "myRPC/registry/base"
"myRPC/prometheus"
"myRPC/config"
"myRPC/limit/limiter"
"myRPC/registry/register"
"myRPC/trace"
mwTrace "myRPC/middleware/trace"
mwBase "myRPC/middleware/base"
mwLimit "myRPC/middleware/limit"
mwLog "myRPC/middleware/log"
mwPrometheus "myRPC/middleware/prometheus"
"myRPC/meta"
"myRPC/util"
"net"
"os"
"os/signal"
)
//基础服务模块,所有服务的公共部分
type CommonService struct {
//grpc服务对象
*grpc.Server
//服务配置对象
serviceConf *config.ServiceConf
//服务端限流器
limiter limiter.LimitInterface
//http服务器
httpServer *httpBase.HttpServer
}
//新建服务对象
func NewService()(commonService *CommonService,err error) {
//创建公共服务对象
commonService = &CommonService{
Server:grpc.NewServer(),
}
//初始化命令行参数
configDir,serviceParams,err := commonService.initParams()
if err != nil {
return
}
//初始化配置
commonService.serviceConf,err = config.NewConfig(configDir,serviceParams)
if err != nil {
return
}
fmt.Println("service serviceConf:",commonService.serviceConf)
//初始化各类对象
err = commonService.initHttp()
if err != nil {
return
}
err = commonService.initLimit()
if err != nil {
return
}
err = commonService.initLog()
if err != nil {
return
}
err = commonService.initRegistry()
if err != nil {
return
}
err = commonService.initTrace()
if err != nil {
return
}
err = commonService.initPrometheus()
if err != nil {
return
}
err = commonService.initBalance()
if err != nil {
return
}
err = commonService.initHystrix()
if err != nil {
return
}
return commonService,nil
}
//服务的接口初始化
func (commonService *CommonService)InitServiceFunc(reqCtx context.Context,serviceMethod string)(ctx context.Context,err error) {
//服务端执行中间件参数
serverMeta := &meta.ServerMeta{
Env:util.GetEnv(),
IDC:commonService.serviceConf.Base.ServiceIDC,
ServeiceIP:util.GetLocalIP(),
ServiceName:commonService.serviceConf.Base.ServiceName,
ServiceMethod:serviceMethod,
}
//保存到上下文中
ctx = meta.SetServerMeta(reqCtx,serverMeta)
return ctx,nil
}
//执行服务
func (commonService *CommonService)Run() {
logBase.Debug("init server start")
if commonService.httpServer != nil {
go func() {
//开启http服务
err := commonService.httpServer.Start()
if err != nil {
logBase.Fatal("start http err:%v",err)
return
}
}()
}
listen, err := net.Listen("tcp", fmt.Sprintf(":%d", commonService.serviceConf.Base.ServicePort))
if err != nil {
logBase.Fatal("new listen err:%v",err)
return
}
//开启rpc服务
err = commonService.Server.Serve(listen)
if err != nil {
logBase.Fatal("start server err:%v",err)
return
}
}
//解析命令行可能传递的参数
func (commonService *CommonService)initParams()(configDir string,serviceParams config.ServiceParams,err error) {
serviceParams = config.ServiceParams{}
flag.StringVar(&configDir,"config","","service config path")
flag.IntVar(&serviceParams.ServiceType,"type",0,"service type")
flag.IntVar(&serviceParams.ServiceId,"id",0,"service id")
flag.IntVar(&serviceParams.ServiceVer,"ver",0,"service ver")
flag.StringVar(&serviceParams.ServiceName,"name","","service name")
flag.IntVar(&serviceParams.ServicePort,"sport",0,"service port")
flag.IntVar(&serviceParams.HttpPort,"hport",0,"service http port")
flag.Parse()
return "",serviceParams,nil
}
//初始化限流
func (commonService *CommonService)initLimit()(err error) {
limitBase.InitLimit()
//服务端限流器
serverLimiter,err := limitBase.GetLimitMgr().NewLimiter(commonService.serviceConf.ServerLimit.Type,
commonService.serviceConf.ServerLimit.Params.(map[interface{}]interface{}))
limitBase.GetLimitMgr().SetServerLimiter(serverLimiter)
commonService.limiter = serverLimiter
if err != nil {
return err
}
//客户端限流器
clientLimiter,err := limitBase.GetLimitMgr().NewLimiter(commonService.serviceConf.ClientLimit.Type,
commonService.serviceConf.ClientLimit.Params.(map[interface{}]interface{}))
limitBase.GetLimitMgr().SetClientLimiter(clientLimiter)
if err != nil {
return err
}
return nil
}
//初始化日志
func (commonService *CommonService)initLog()(err error) {
logBase.InitLogger(commonService.serviceConf.Log.SwitchOn,
commonService.serviceConf.Log.Level,
commonService.serviceConf.Log.ChanSize,
commonService.serviceConf.Log.Params.(map[interface{}]interface{}))
return
}
//初始化注册中心
func (commonService *CommonService)initRegistry()(err error) {
registryBase.InitRegistry()
_,err = registryBase.GetRegistryManager().NewRegister(commonService.serviceConf.Registry.Type,
commonService.serviceConf.Registry.Params.(map[interface{}]interface{}))
if err != nil {
return err
}
registerServer := ®ister.Service{
SvrName:commonService.serviceConf.Base.ServiceName,
SvrType:commonService.serviceConf.Base.ServiceType,
SvrNodes:[]*register.Node{
®ister.Node{
NodeIDC:commonService.serviceConf.Base.ServiceIDC,
NodeId:commonService.serviceConf.Base.ServiceId,
NodeVersion:commonService.serviceConf.Base.ServiceVer,
NodeIp:util.GetLocalIP(),
NodePort:fmt.Sprintf("%d",commonService.serviceConf.Base.ServicePort),
NodeWeight:commonService.serviceConf.Base.ServiceWidget,
NodeFuncs:commonService.serviceConf.Base.ServiceFuncs,
},
},
}
//起服的时候,注册当前服务到注册中心
err = registryBase.GetRegistryManager().RegisterServer(registerServer)
return err
}
//初始化追踪
func (commonService *CommonService)initTrace()(err error) {
err = trace.InitTrace(commonService.serviceConf.Base.ServiceName,
commonService.serviceConf.Trace.ReportAddr,
commonService.serviceConf.Trace.SampleType,
commonService.serviceConf.Trace.SampleRate)
if err != nil {
return err
}
return
}
//初始化监控
func (commonService *CommonService)initPrometheus()(err error) {
err = prometheus.NewPrometheusManager(
//客户端监控频率
commonService.serviceConf.Prometheus.ClientHistogram,
//服务端监控频率
commonService.serviceConf.Prometheus.ServerHistogram)
if err != nil {
return err
}
if commonService.httpServer != nil {
//添加http接口调用
err = prometheus.GetPrometheusManager().AddPrometheusHandler(commonService.httpServer.GetRoute(),commonService.serviceConf)
if err != nil {
return err
}
}
return nil
}
//初始化负载均衡
func (commonService *CommonService)initBalance()(error) {
balanceBase.InitBalance()
_,err := balanceBase.GetBalanceMgr().NewBalancer(commonService.serviceConf.Balance.Type)
return err
}
//初始化熔断
func (commonService *CommonService)initHystrix()(error) {
err := hystrix.InitHystrix(commonService.serviceConf.Base.ServiceName,
commonService.serviceConf.Hystrix.TimeOut,
commonService.serviceConf.Hystrix.MaxConcurrentRequests,
commonService.serviceConf.Hystrix.RequestVolumeThreshold,
commonService.serviceConf.Hystrix.SleepWindow,
commonService.serviceConf.Hystrix.ErrorPercentThreshold,
)
return err
}
//初始化http服务
func (commonService *CommonService)initHttp()(err error) {
if commonService.serviceConf.Http.SwitchOn {
httpServer,err := httpBase.NewHttpServer(commonService.serviceConf.Http.HttpPort)
if err != nil {
return err
}
commonService.httpServer = httpServer
//开启pprof性能监控
if commonService.serviceConf.Http.PprofSwitchOn {
err = httpServer.AddPropHandler()
if err != nil {
return err
}
}
//添加http配置修改
err = httpServer.AddParamsHandler(commonService.serviceConf)
if err != nil {
return err
}
}
return nil
}
//服务中间件
func (commonService *CommonService)BuildServerMiddleware(handle mwBase.MiddleWareFunc,frontMiddles,backMiddles []mwBase.MiddleWare) mwBase.MiddleWareFunc {
var middles []mwBase.MiddleWare
serviceConf := commonService.serviceConf
//前置
middles = append(middles,frontMiddles...)
//日志
middles = append(middles, mwLog.LogServiceMiddleware())
//监控
if serviceConf.Prometheus.SwitchOn {
middles = append(middles, mwPrometheus.PrometheusServiceMiddleware())
}
//服务端限流
if serviceConf.ServerLimit.SwitchOn && commonService.limiter != nil{
middles = append(middles, mwLimit.ServerLimitMiddleware(commonService.limiter))
}
//追踪
if serviceConf.Trace.SwitchOn {
middles = append(middles, mwTrace.TraceServiceMiddleware())
}
//后置
middles = append(middles,backMiddles...)
m := mwBase.Chain(middles...)
//得到中间件链条,调用这个返回值会执行所有中间件
return m(handle)
}
//获取服务配置
func (commonService *CommonService)GetServiceConf()(*config.ServiceConf) {
return commonService.serviceConf
}
//获取http服务路由
func (commonService *CommonService)GetHttpRouter()(router *mux.Router) {
if commonService.httpServer != nil {
return commonService.httpServer.GetRoute()
}
return nil
}
//停止服务
func (commonService *CommonService)Stop() {
stopChan := make(chan os.Signal)
//监听所有信号
signal.Notify(stopChan)
<- stopChan
logBase.Debug("server stop")
//各种组件释放资源
commonService.Server.Stop()
if commonService.httpServer != nil {
_ = commonService.httpServer.Stop()
}
commonService.serviceConf = nil
limitBase.GetLimitMgr().Stop()
registryBase.GetRegistryManager().Stop()
logBase.GetLogMgr().Stop()
balanceBase.GetBalanceMgr().Stop()
prometheus.GetPrometheusManager().Stop()
hystrix.Stop()
_ = trace.Stop()
} |
package main
import (
"fmt"
"math/big"
)
func main() {
var n int
fmt.Scanln(&n)
if n <= 2 {
fmt.Println(n)
return
}
factorial := new(big.Int)
factorial.SetInt64(1)
for i := 2; i <= n; i++ {
bigI := new(big.Int)
bigI.SetInt64(int64(i))
factorial = factorial.Mul(factorial, bigI)
}
fmt.Println(factorial)
}
|
package bizlogic
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"github.com/gin-gonic/gin"
"github.com/pingcap/monitoring/reload/server/types"
"github.com/pingcap/monitoring/reload/server/utils"
"github.com/pkg/errors"
"github.com/prometheus/common/log"
"github.com/prometheus/prometheus/pkg/rulefmt"
"github.com/youthlin/stream"
streamtypes "github.com/youthlin/stream/types"
"gopkg.in/yaml.v2"
)
type server struct {
url *url.URL
dir string
storePath string
needStoreFileToStorePath bool
}
func NewServer(promURL *url.URL, watchDir string, needStoreFileToStorePath bool, storePath string) *server {
return &server{
url: promURL,
dir: watchDir,
needStoreFileToStorePath: needStoreFileToStorePath,
storePath: storePath,
}
}
func (s *server) ListConfigs(c *gin.Context) {
list, err := s.getConfigs()
if err != nil {
c.JSON(http.StatusBadRequest, utils.NewErrorResponse(err.Error()))
} else {
c.JSON(http.StatusOK, list)
}
}
func (s *server) GetConfig(c *gin.Context) {
configName := utils.GetHttpParameter(c.Param, "config")
v, err := ioutil.ReadFile(fmt.Sprintf("%s%c%s", s.dir, filepath.Separator, configName))
if err != nil {
c.JSON(http.StatusBadRequest, utils.NewErrorResponse(err.Error()))
} else {
c.JSON(http.StatusOK, string(v))
}
}
func (s *server) ListRules(c *gin.Context) {
r, err := http.NewRequest("GET", fmt.Sprintf("%s/api/v1/rules", s.url), nil)
if err != nil {
c.JSON(http.StatusBadRequest, utils.NewErrorResponse(err.Error()))
return
}
resp, err := http.DefaultClient.Do(r)
if err != nil {
c.JSON(http.StatusBadRequest, utils.NewErrorResponse(err.Error()))
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
c.JSON(http.StatusBadRequest, errors.New(fmt.Sprintf("request failed, code=%d", resp.StatusCode)))
return
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
c.JSON(http.StatusBadRequest, utils.NewErrorResponse(err.Error()))
} else {
c.Header("Content-Type", "application/json")
c.Writer.Write(body)
}
}
func (s *server) getConfigs() ([]string, error) {
files, err := ioutil.ReadDir(s.dir)
if err != nil {
return nil, errors.Wrap(err, "get config list failed")
}
r := make([]string, 0)
stream.OfSlice(files).Filter(func(t streamtypes.T) bool {
info := t.(os.FileInfo)
return !info.IsDir() && filepath.Ext(info.Name()) == ".yml"
}).ForEach(func(t streamtypes.T) {
info := t.(os.FileInfo)
r = append(r, info.Name())
})
return r, nil
}
func (s *server) UpdateConfig(c *gin.Context) {
configName := utils.GetHttpParameter(c.Param, "config")
files, err := ioutil.ReadDir(s.dir)
if err != nil {
c.JSON(http.StatusBadRequest, utils.NewErrorResponse(err.Error()))
} else {
config := &types.Config{}
if err := c.ShouldBindJSON(config); err != nil {
fmt.Println(err)
msg := fmt.Sprintf("invalid request body: %v", err)
c.JSON(http.StatusBadRequest, msg)
return
}
stream.OfSlice(files).Filter(func(t streamtypes.T) bool {
info := t.(os.FileInfo)
return info.Name() == configName
}).Map(func(t streamtypes.T) streamtypes.R {
return []byte(config.Data)
}).Filter(func(t streamtypes.T) bool {
data := t.([]byte)
if err := parse(data); err != nil {
c.JSON(http.StatusBadRequest, utils.NewErrorResponse(err.Error()))
return false
}
return true
}).Peek(func(t streamtypes.T) {
data := t.([]byte)
if err := ioutil.WriteFile(fmt.Sprintf("%s%c%s", s.dir, filepath.Separator, configName), data, os.ModePerm); err != nil {
c.JSON(http.StatusBadRequest, utils.NewErrorResponse(err.Error()))
} else {
c.JSON(http.StatusOK, config)
}
}).Filter(func(t streamtypes.T) bool {
if !s.needStoreFileToStorePath {
log.Info("do not need to store file to storepath")
}
return s.needStoreFileToStorePath
}).ForEach(func(t streamtypes.T) {
data := t.([]byte)
if err := ioutil.WriteFile(fmt.Sprintf("%s%c%s", s.storePath, filepath.Separator, configName), data, os.ModePerm); err != nil {
log.Error("write file to store path failed", err)
}
})
}
}
func parse(content []byte) error {
var groups rulefmt.RuleGroups
if err := yaml.UnmarshalStrict(content, &groups); err != nil {
return err
}
errs := groups.Validate()
if errs == nil || len(errs) == 0 {
return nil
}
var errStr string
stream.OfSlice(errs).ForEach(func(t streamtypes.T) {
err := t.(error)
errStr += err.Error()
})
return errors.New(errStr)
}
|
package loading
import (
"errors"
"io"
)
var (
ErrTemplateNotFound = errors.New("Template not found")
)
type TemplateResolver interface {
GetTemplateReader(path string) (io.Reader, error)
}
|
package troubleshoot
import (
"fmt"
"io"
"os"
"github.com/go-logr/logr"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
ctrlzap "sigs.k8s.io/controller-runtime/pkg/log/zap"
)
const (
prefixInfo = " "
prefixNewTest = "--- "
prefixSuccess = " \u2713 " // ✓
prefixWarning = " \u26a0 " // ⚠
prefixError = " X " // X
colorRed = "\033[31m"
colorGreen = "\033[32m"
colorYellow = "\033[33m"
colorReset = "\033[0m"
levelNewCheck = 1
levelSuccess = 2
levelWarning = 3
levelError = 4
levelNewDynakube = 5
)
type troubleshootLogger struct {
logger logr.Logger
}
type subTestLogger struct {
troubleshootLogger
}
func newRawTroubleshootLogger(testName string, out io.Writer) troubleshootLogger {
config := zap.NewProductionEncoderConfig()
config.TimeKey = ""
config.LevelKey = ""
config.NameKey = "name"
config.EncodeTime = zapcore.ISO8601TimeEncoder
testName = fmt.Sprintf("[%-10s] ", testName)
return troubleshootLogger{
logger: ctrlzap.New(ctrlzap.WriteTo(out), ctrlzap.Encoder(zapcore.NewConsoleEncoder(config))).WithName(testName),
}
}
func newTroubleshootLoggerToWriter(testName string, out io.Writer) logr.Logger {
return logr.New(newRawTroubleshootLogger(testName, out))
}
func newSubTestLoggerToWriter(testName string, out io.Writer) logr.Logger {
return logr.New(subTestLogger{newRawTroubleshootLogger(testName, out)})
}
func newTroubleshootLogger(testName string) logr.Logger {
return newTroubleshootLoggerToWriter(testName, os.Stdout)
}
func newSubTestLogger(testName string) logr.Logger {
return newSubTestLoggerToWriter(testName, os.Stdout)
}
func logNewCheckf(format string, v ...interface{}) {
log.V(levelNewCheck).Info(fmt.Sprintf(format, v...))
}
func logNewDynakubef(format string, v ...interface{}) {
log.V(levelNewDynakube).Info(fmt.Sprintf(format, v...))
}
func logInfof(format string, v ...interface{}) {
log.Info(fmt.Sprintf(format, v...))
}
func logOkf(format string, v ...interface{}) {
log.V(levelSuccess).Info(fmt.Sprintf(format, v...))
}
func logWarningf(format string, v ...interface{}) {
log.V(levelWarning).Info(fmt.Sprintf(format, v...))
}
func logErrorf(format string, v ...interface{}) {
log.V(levelError).Info(fmt.Sprintf(format, v...))
}
func (dtl troubleshootLogger) Init(_ logr.RuntimeInfo) {}
func (dtl subTestLogger) Info(level int, message string, keysAndValues ...interface{}) {
message = addPrefixes(level, message)
message = " |" + message
dtl.logger.Info(message, keysAndValues...)
}
func (dtl troubleshootLogger) Info(level int, message string, keysAndValues ...interface{}) {
message = addPrefixes(level, message)
dtl.logger.Info(message, keysAndValues...)
}
func addPrefixes(level int, message string) string {
switch level {
case levelNewCheck:
return prefixNewTest + message
case levelSuccess:
return withSuccessPrefix(message)
case levelWarning:
return withWarningPrefix(message)
case levelError:
// Info is used for errors to suppress printing a stacktrace
// Printing a stacktrace would confuse people in thinking the troubleshooter crashed
return withErrorPrefix(message)
case levelNewDynakube:
return message
default:
return prefixInfo + message
}
}
func withSuccessPrefix(message string) string {
return fmt.Sprintf("%s%s%s%s", colorGreen, prefixSuccess, message, colorReset)
}
func withWarningPrefix(message string) string {
return fmt.Sprintf("%s%s%s%s", colorYellow, prefixWarning, message, colorReset)
}
func withErrorPrefix(message string) string {
return fmt.Sprintf("%s%s%s%s", colorRed, prefixError, message, colorReset)
}
func (dtl troubleshootLogger) Enabled(_ int) bool {
return dtl.logger.Enabled()
}
func (dtl troubleshootLogger) Error(err error, msg string, keysAndValues ...interface{}) {
dtl.logger.Error(err, prefixError+msg, keysAndValues...)
}
func (dtl troubleshootLogger) WithValues(keysAndValues ...interface{}) logr.LogSink {
return troubleshootLogger{
logger: dtl.logger.WithValues(keysAndValues...),
}
}
func (dtl troubleshootLogger) WithName(name string) logr.LogSink {
return troubleshootLogger{
logger: dtl.logger.WithName(name),
}
}
|
package zoidberg
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"sort"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
// Zoidberg encapsulates the testing environment and provides access to
// the resources needed to read and parse the API calls.
type Zoidberg struct {
w io.WriteCloser
ts *httptest.Server
t *testing.T
reqHeaders map[string]string
}
// A Request contains the possible parameters used in making an API call.
type Request struct {
Method string
Path string
RequestPath string
Body interface{}
RequestHeaders map[string]string
BasicAuthLogin [2]string
Description string
Write bool
ResponseCodes map[int]string
ResponseJSONObjects map[string]string
ParameterValues map[string]string
}
// NewZoidberg returns a new zoidberg instance
func NewZoidberg(w io.WriteCloser, ts *httptest.Server, t *testing.T, requestHeaders map[string]string) *Zoidberg {
return &Zoidberg{w: w, ts: ts, t: t, reqHeaders: requestHeaders}
}
// Head Creates a header section
func (z *Zoidberg) Head(title, underline string) {
fmt.Fprintf(z.w, "%s\n", title)
fmt.Fprintf(z.w, "%s\n\n", strings.Repeat(underline, len(title)))
}
// Says outputs some paragraph text.
func (z *Zoidberg) Says(text string) {
fmt.Fprintf(z.w, " %s\n\n", text)
}
// Ask is a helper function that takes a Request, executes and asserts the response
func (z *Zoidberg) Ask(r Request) {
// t.Log("TestRequest", method, path, body)
var bodyReader io.Reader
if r.Body != nil {
bodyBytes, err := json.Marshal(r.Body)
require.NoError(z.t, err)
bodyReader = bytes.NewReader(bodyBytes)
}
if r.RequestPath == "" {
r.RequestPath = r.Path
}
req, err := http.NewRequest(r.Method, fmt.Sprintf("%s%s", z.ts.URL, r.RequestPath), bodyReader)
for k, v := range z.reqHeaders {
req.Header.Set(k, v)
}
req.SetBasicAuth(r.BasicAuthLogin[0], r.BasicAuthLogin[1])
require.NoError(z.t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(z.t, err)
b, err := ioutil.ReadAll(resp.Body)
require.NoError(z.t, err)
if r.Write {
z.getIt(z.t, req, r.Body, resp, b, r)
}
}
// getIt executes the request
func (z *Zoidberg) getIt(t *testing.T, req *http.Request, reqBody interface{}, resp *http.Response, body []byte, r Request) {
query := ""
if req.URL.RawQuery != "" {
query = fmt.Sprintf("?%s", req.URL.RawQuery)
}
fmt.Fprintf(z.w, ".. http:%s:: %s\n\n", strings.ToLower(req.Method), req.URL.Path)
fmt.Fprintf(z.w, " %s\n\n", r.Description)
// Write in the response codes
if r.ResponseCodes != nil {
responseCodesOrdered := []int{}
for k := range r.ResponseCodes {
responseCodesOrdered = append(responseCodesOrdered, k)
}
sort.Ints(responseCodesOrdered)
fmt.Fprintf(z.w, " **Response Code**\n\n")
for _, code := range responseCodesOrdered {
fmt.Fprintf(z.w, " - %d: %s\n\n", code, r.ResponseCodes[code])
}
}
fmt.Fprintf(z.w, "\n\n")
// Write in the parameters
if r.ParameterValues != nil {
parameterValuesOrdered := []string{}
for k := range r.ParameterValues {
parameterValuesOrdered = append(parameterValuesOrdered, k)
}
sort.Strings(parameterValuesOrdered)
fmt.Fprintf(z.w, " **Query Parameters**\n\n")
for _, param := range parameterValuesOrdered {
fmt.Fprintf(z.w, " - **%s**: %s\n\n", param, r.ParameterValues[param])
}
}
fmt.Fprintf(z.w, "\n\n")
// Write in the response codes
if r.ResponseJSONObjects != nil {
responseJSONObjectsOrdered := []string{}
for k := range r.ResponseJSONObjects {
responseJSONObjectsOrdered = append(responseJSONObjectsOrdered, k)
}
sort.Strings(responseJSONObjectsOrdered)
fmt.Fprintf(z.w, " **Response JSON Object**\n\n")
for _, code := range responseJSONObjectsOrdered {
fmt.Fprintf(z.w, " - **%s**: %s\n\n", code, r.ResponseJSONObjects[code])
}
}
fmt.Fprintf(z.w, "\n\n")
fmt.Fprintf(z.w, " Example request:\n\n")
fmt.Fprintf(z.w, " .. sourcecode:: http\n\n")
fmt.Fprintf(z.w, " %s %s%s %s\n", req.Method, req.URL.Path, query, req.Proto)
for k := range req.Header {
fmt.Fprintf(z.w, " %s: %s\n", k, req.Header.Get(k))
}
if reqBody != nil {
b, err := json.MarshalIndent(reqBody, " ", " ")
require.NoError(t, err)
fmt.Fprintf(z.w, "\n")
fmt.Fprintf(z.w, " %s\n\n", b)
}
fmt.Fprintf(z.w, "\n")
fmt.Fprintf(z.w, " Example response:\n\n")
fmt.Fprintf(z.w, " .. sourcecode:: http\n\n")
fmt.Fprintf(z.w, " %s %s\n", resp.Proto, resp.Status)
for k := range resp.Header {
fmt.Fprintf(z.w, " %s: %s\n", k, resp.Header.Get(k))
}
fmt.Fprintf(z.w, "\n")
var jb interface{}
if len(body) > 0 {
require.NoError(t, json.Unmarshal(body, &jb))
b, err := json.MarshalIndent(jb, " ", " ")
require.NoError(t, err)
fmt.Fprintf(z.w, " %s\n\n", b)
}
}
|
package postgres
/* Пакет для работы с БД Postgres */
import (
"context"
"github.com/prometheus/common/log"
"github.com/egor1344/banner/rotation_banner/pkg/ucb1"
_ "github.com/jackc/pgx/stdlib" // stdlib
"github.com/jmoiron/sqlx"
"go.uber.org/zap"
)
// PgBannerStorage - реализует работу с БД. Реализует интерфейс database
type PgBannerStorage struct {
DB *sqlx.DB
Log *zap.SugaredLogger
}
// InitPgBannerStorage - Инициализация соединения с БД
func InitPgBannerStorage(dsn string) (*PgBannerStorage, error) {
db, err := sqlx.Open("pgx", dsn)
if err != nil {
return nil, err
}
err = db.Ping()
if err != nil {
return nil, err
}
return &PgBannerStorage{DB: db}, nil
}
// existsBanner - Проверка на существование баннера
func (pgbs *PgBannerStorage) existsBanner(ctx context.Context, idBanner int64, create bool) (bool, error) {
//pgbs.Log.Info("exists banner")
var count int64
err := pgbs.DB.GetContext(ctx, &count, "select count(*) from banners where id=$1;", idBanner)
if err != nil {
pgbs.Log.Error("databases error ", err)
}
if count == 0 {
if create {
_, err = pgbs.DB.ExecContext(ctx, "INSERT into banners values ($1);", idBanner)
if err != nil {
pgbs.Log.Error(err)
}
} else {
return false, nil
}
}
return true, nil
}
// existsSlot - Проверка на существование баннера
func (pgbs *PgBannerStorage) existsSlot(ctx context.Context, idSlot int64, create bool) (bool, error) {
//pgbs.Log.Info("exists slot")
var count int64
err := pgbs.DB.GetContext(ctx, &count, "select count(*) from slot where id=$1;", idSlot)
if err != nil {
pgbs.Log.Error("databases error ", err)
}
if count == 0 {
if create {
_, err = pgbs.DB.ExecContext(ctx, "INSERT into slot values ($1);", idSlot)
if err != nil {
pgbs.Log.Error(err)
}
} else {
return false, nil
}
}
return true, nil
}
// existsSocDemGroup - Проверка на существование соц. дем. группы
func (pgbs *PgBannerStorage) existsSocDemGroup(ctx context.Context, idSocDemGroup int64, create bool) (bool, error) {
//pgbs.Log.Info("exists slot")
var count int64
err := pgbs.DB.GetContext(ctx, &count, "select count(*) from soc_dem_group where id=$1;", idSocDemGroup)
if err != nil {
pgbs.Log.Error("databases error ", err)
}
if count == 0 {
if create {
_, err = pgbs.DB.ExecContext(ctx, "INSERT into soc_dem_group values ($1);", idSocDemGroup)
if err != nil {
pgbs.Log.Error(err)
}
} else {
return false, nil
}
}
return true, nil
}
// existsStatistic - Проверка на существование записи о статистике с данными параметрами
func (pgbs *PgBannerStorage) existsStatistic(ctx context.Context, idBanner, idSocDemGroup, idSlot int64, create bool) (bool, error) {
//pgbs.Log.Info("exists slot")
var count int64
err := pgbs.DB.GetContext(ctx, &count, "select count(*) from statistic where id_banner=$1 and id_soc_dem=$2 and id_slot=$3", idBanner, idSocDemGroup, idSlot)
if err != nil {
pgbs.Log.Error("databases error ", err)
}
pgbs.Log.Info(count)
if count == 0 {
if create {
_, err = pgbs.DB.ExecContext(ctx, "INSERT into statistic(id_banner, id_soc_dem, count_click, count_views, id_slot) values ($1, $2, $3, $4, $5);", idBanner, idSocDemGroup, 0, 1, idSlot)
if err != nil {
pgbs.Log.Error(err)
}
} else {
return false, nil
}
}
return true, nil
}
// AddBanner - Добавить баннер в ротацию
func (pgbs *PgBannerStorage) AddBanner(ctx context.Context, idBanner, idSlot int64) error {
pgbs.Log.Info("bd add banner")
existsBanner, err := pgbs.existsBanner(ctx, idBanner, true)
if err != nil {
pgbs.Log.Error("error exists banner ", err)
}
if !existsBanner {
pgbs.Log.Error("banner not exists")
}
existsSlot, err := pgbs.existsSlot(ctx, idSlot, true)
if err != nil {
pgbs.Log.Error("error exists banner ", err)
}
if !existsSlot {
pgbs.Log.Error("slot not exists")
}
_, err = pgbs.DB.ExecContext(ctx, "insert into rotations(id_banner, id_slot) values ($1, $2);", idBanner, idSlot)
if err != nil {
pgbs.Log.Error(err)
return err
}
return nil
}
// DelBanner - Удалить баннер из ротаций
func (pgbs *PgBannerStorage) DelBanner(ctx context.Context, idBanner int64) error {
pgbs.Log.Info("bd del banner")
_, err := pgbs.DB.ExecContext(ctx, "delete from rotations where id_banner=$1;", idBanner)
if err != nil {
pgbs.Log.Error(err)
return err
}
return nil
}
// incCountClick- Увеличение количества кликов в статистике
func (pgbs *PgBannerStorage) incCountClick(ctx context.Context, idBanner, idSlot, idSocDemGroup int64) error {
_, err := pgbs.DB.ExecContext(ctx, `update statistic set count_click = count_click + 1 where id_slot = $1 and id_soc_dem = $2 and id_banner=$3;`, idSlot, idSocDemGroup, idBanner)
if err != nil {
pgbs.Log.Error("error incCountClick ", err)
}
return nil
}
// CountTransition - Засчитать переход
func (pgbs *PgBannerStorage) CountTransition(ctx context.Context, idBanner, idSocDemGroup int64, idSlot int64) error {
//pgbs.Log.Info("bd count transition")
existsSocDemGroup, err := pgbs.existsSocDemGroup(ctx, idSocDemGroup, true)
if err != nil {
pgbs.Log.Error("error exists socDemGroup ", err)
}
if !existsSocDemGroup {
pgbs.Log.Error("socDemGroup not exists")
}
existsBanner, err := pgbs.existsBanner(ctx, idBanner, true)
if err != nil {
pgbs.Log.Error("error exists banner ", err)
}
if !existsBanner {
pgbs.Log.Error("banner not exists")
}
existsSlot, err := pgbs.existsSlot(ctx, idSlot, true)
if err != nil {
pgbs.Log.Error("error exists banner ", err)
}
if !existsSlot {
pgbs.Log.Error("slot not exists")
}
existsStatistic, err := pgbs.existsStatistic(ctx, idBanner, idSocDemGroup, idSlot, true)
if err != nil {
pgbs.Log.Error("error exists banner ", err)
}
if !existsStatistic {
pgbs.Log.Error("slot not exists")
}
err = pgbs.incCountClick(ctx, idBanner, idSlot, idSocDemGroup)
if err != nil {
pgbs.Log.Error(err)
return err
}
err = pgbs.incCountView(ctx, idBanner, idSlot, idSocDemGroup)
if err != nil {
pgbs.Log.Error(err)
return err
}
return nil
}
// incCountView - Увеличение количества показов в статистике
func (pgbs *PgBannerStorage) incCountView(ctx context.Context, idBanner, idSlot, idSocDemGroup int64) error {
pgbs.Log.Info("bd get banner")
_, err := pgbs.DB.ExecContext(ctx, `update statistic set count_views = count_views + 1 where id_slot = $1 and id_soc_dem = $2 and id_banner=$3;`, idSlot, idSocDemGroup, idBanner)
if err != nil {
pgbs.Log.Error("error incCountView ", err)
}
return nil
}
// GetBanner - Выбрать баннер для показа
func (pgbs *PgBannerStorage) GetBanner(ctx context.Context, idSlot, idSocDemGroup int64) (int64, error) {
//pgbs.Log.Info("bd get banner")
rows, err := pgbs.DB.QueryxContext(ctx, `select id_banner,
count_click,
count_views,
SUM(count_views) OVER
(PARTITION BY id_slot) AS all_count_views
from statistic
where id_slot = $1
and id_soc_dem = $2;`, idSlot, idSocDemGroup)
if err != nil {
pgbs.Log.Error("error get banner ", err)
}
var s struct {
IDBanner int64 `db:"id_banner"`
CountClick int64 `db:"count_click"`
CountView int64 `db:"count_views"`
AllCountViews int64 `db:"all_count_views"`
}
var lbs ucb1.ListBannerStatistic
for rows.Next() {
err = rows.StructScan(&s)
lbs.Objects = append(lbs.Objects, &ucb1.BannerStatistic{CountClick: s.CountClick, ID: s.IDBanner, CountDisplay: s.CountView})
}
lbs.AllCountDisplay = s.AllCountViews
id, err := lbs.GetRelevantObject()
if err != nil {
pgbs.Log.Error("error in GetRelevantObject ", err)
return 0, err
}
err = pgbs.incCountView(ctx, id, idSlot, idSocDemGroup)
if err != nil {
pgbs.Log.Error("error in GetRelevantObject ", err)
return 0, err
}
return id, nil
}
// Close - Увеличение количества показов в статистике
func (pgbs *PgBannerStorage) Close() {
err := pgbs.DB.Close()
if err != nil {
log.Error(err)
}
}
|
package main
import (
"bufio"
"fmt"
"log"
"os"
"sort"
"strings"
)
func contains(a []int, b int) bool {
ix := sort.SearchInts(a, b)
return ix < len(a) && a[ix] == b
}
func distinctTriangles(q string) (r uint) {
g := make(map[int][]int)
t := strings.Split(q, ",")
p := make([]int, 2)
for _, i := range t {
fmt.Sscanf(i, "%d %d", &p[0], &p[1])
sort.Ints(p)
g[p[0]] = append(g[p[0]], p[1])
}
for k := range g {
sort.Ints(g[k])
}
for _, v := range g {
for i := 0; i < len(v)-1; i++ {
for j := i + 1; j < len(v); j++ {
if contains(g[v[i]], v[j]) {
r++
}
}
}
}
return r
}
func main() {
data, err := os.Open(os.Args[1])
if err != nil {
log.Fatal(err)
}
defer data.Close()
scanner := bufio.NewScanner(data)
for scanner.Scan() {
s := strings.Split(scanner.Text(), ";")
fmt.Println(distinctTriangles(s[1]))
}
}
|
package uploadcard
import (
"fmt"
"net/http"
"path/filepath"
"strconv"
"strings"
"github.com/HanYu1983/gomod/lib/db2"
tool "github.com/HanYu1983/gomod/lib/tool"
"google.golang.org/appengine"
)
func Serve_GetExtension(w http.ResponseWriter, r *http.Request) {
defer tool.Recover(func(err error) {
tool.Output(w, nil, err.Error())
})
ctx := appengine.NewContext(r)
var _ = ctx
r.ParseForm()
tool.Assert(tool.ParameterIsNotExist(r.Form, "game"))
//tool.Assert(tool.ParameterIsNotExist(r.Form, "extensionId"))
game := r.Form["game"][0]
//extensionId := r.Form["extensionId"][0]
list, err := db2.GetFileList(ctx, fmt.Sprintf("root/tcg/extension/%s/", game), true)
if err != nil {
tool.Assert(tool.IfError(err))
}
output := []interface{}{}
for _, file := range list {
fileName := filepath.Base(file.Name)
if fileName != "manifast.txt" {
continue
}
extensionId := filepath.Base(filepath.Dir(file.Name))
content := string(file.Content)
content = strings.Replace(content, "\r", "", -1)
group := strings.Split(content, "===\n")
cards := group[2:]
for _, card := range cards {
cardInfo := strings.Split(card, "\n")
imgUrl := fmt.Sprintf("%s/%s/imgs/%s", game, extensionId, cardInfo[0])
var json interface{}
if game == "sengoku" {
cost1, err := strconv.Atoi(cardInfo[7])
if err != nil {
cost1 = 0
}
cost2, err := strconv.Atoi(cardInfo[8])
if err != nil {
cost2 = 0
}
json = map[string]interface{}{
"imgUrl": imgUrl,
"id": cardInfo[1],
"cid": cardInfo[1],
"cname": cardInfo[2],
"set": cardInfo[3],
"color": cardInfo[4],
"atype": cardInfo[5],
"atype2": cardInfo[6],
"cost": []interface{}{cost1, cost2},
"ability": cardInfo[9],
"power": cardInfo[10],
"city": cardInfo[11],
"symbol": cardInfo[12],
"rarity": cardInfo[13],
"content": cardInfo[14],
"counter": cardInfo[15],
}
}
if game == "sangoWar" {
cost1, err := strconv.Atoi(cardInfo[6])
if err != nil {
cost1 = 0
}
cost2, err := strconv.Atoi(cardInfo[7])
if err != nil {
cost2 = 0
}
json = []interface{}{
cardInfo[1],
cardInfo[2],
cardInfo[3],
cardInfo[4],
cardInfo[5],
[]interface{}{
cost1,
cost2,
cardInfo[8],
},
cardInfo[9],
cardInfo[10],
cardInfo[11],
cardInfo[12],
cardInfo[13],
imgUrl,
}
}
output = append(output, json)
}
}
tool.Output(w, output, nil)
}
|
package mock
import (
"context"
"fmt"
"github.com/dgraph-io/badger/v3"
"github.com/ipfs/go-datastore"
dssync "github.com/ipfs/go-datastore/sync"
"github.com/kenlabs/pando-store/pkg/config"
"github.com/kenlabs/pando-store/pkg/store"
"github.com/kenlabs/pando/pkg/legs"
"github.com/kenlabs/pando/pkg/metadata"
"github.com/kenlabs/pando/pkg/option"
"github.com/kenlabs/pando/pkg/policy"
"github.com/kenlabs/pando/pkg/registry"
"github.com/kenlabs/pando/pkg/registry/discovery"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p-core/host"
"time"
)
const topic = "/pando/v0.0.1"
type PandoMock struct {
Opt *option.DaemonOptions
DS datastore.Batching
CS *badger.DB
PS *store.PandoStore
Host host.Host
Core *legs.Core
Registry *registry.Registry
Discover discovery.Discoverer
outMeta chan *metadata.MetaRecord
}
func NewPandoMock() (*PandoMock, error) {
ctx := context.Background()
_ds := datastore.NewMapDatastore()
ds := dssync.MutexWrap(_ds)
cs, err := badger.Open(badger.DefaultOptions("").WithInMemory(true))
if err != nil {
return nil, err
}
h, err := libp2p.New()
if err != nil {
return nil, err
}
//bs := blockstore.NewBlockstore(mds)
ps, err := store.NewStoreFromDatastore(ctx, ds, &config.StoreConfig{
CacheSize: config.DefaultCacheSize,
SnapShotInterval: "5s",
})
if err != nil {
return nil, err
}
mockDisco, err := NewMockDiscoverer(exceptID)
if err != nil {
return nil, err
}
r, err := registry.NewRegistry(ctx, &MockDiscoveryCfg, &MockAclCfg, ds, mockDisco)
if err != nil {
return nil, err
}
limiter, err := policy.NewLimiter(policy.LimiterConfig{
TotalRate: BaseTokenRate,
TotalBurst: int(BaseTokenRate),
Registry: r,
BaseTokenRate: BaseTokenRate,
})
if err != nil {
return nil, err
}
outCh := make(chan *metadata.MetaRecord)
opt := option.New(nil)
_, err = opt.Parse()
if err != nil {
return nil, err
}
core, err := legs.NewLegsCore(ctx, h, ds, cs, ps, outCh, time.Minute, limiter, r, opt)
if err != nil {
return nil, err
}
return &PandoMock{
DS: ds,
PS: ps,
CS: cs,
Host: h,
Core: core,
Registry: r,
Discover: mockDisco,
outMeta: outCh,
Opt: opt,
}, nil
}
func (pando *PandoMock) GetMetaRecordCh() (chan *metadata.MetaRecord, error) {
if pando.outMeta != nil {
return pando.outMeta, nil
}
return nil, fmt.Errorf("nil channel")
}
func GetTopic() string {
return topic
}
|
package main
import "sort"
// DocumentID is a unique identifier of a document
type DocumentID = uint32
// Term is a search item of a document
type Term = string
// PostingList represents the list of documents that belongs to a search term
type PostingList = []DocumentID
// InvertedIndex is a datastructure, that maps back from terms to the parts of a document where they occur
type InvertedIndex = map[Term]PostingList
// LengthFilter maps back from terms length (nGram count) to the inverted indexes
type LengthFilter = []InvertedIndex
// NGramIndex represents a fuzzy string search structure
type NGramIndex struct {
nGram int
index LengthFilter
dictionary []string
}
// BuildIndex builds the inverted index structure for the given dictionary
func BuildIndex(nGram int, dictionary []string) *NGramIndex {
index := LengthFilter{}
for id, word := range dictionary {
nGrams := SplitIntoNGrams(nGram, word)
n := len(nGrams)
if n >= len(index) {
tmp := make(LengthFilter, n+1)
copy(tmp, index)
index = tmp
}
if index[n] == nil {
index[n] = make(InvertedIndex)
}
for _, term := range nGrams {
if _, ok := index[n][term]; !ok {
index[n][term] = PostingList{}
}
index[n][term] = append(index[n][term], uint32(id))
}
}
return &NGramIndex{
nGram: nGram,
index: index,
dictionary: dictionary,
}
}
// Search performs approximate strign search for the given query
func (n *NGramIndex) Search(query string) SearchResult {
terms := SplitIntoNGrams(n.nGram, query)
result := SearchResult{}
sizeA := len(terms)
rid := []PostingList{}
for sizeB, index := range n.index {
if index == nil {
continue
}
for _, term := range terms {
posting := index[term]
if posting == nil {
continue
}
rid = append(rid, posting)
}
for _, candidate := range Merge(rid) {
docID := candidate.Position()
result = append(result, SearchCandidate{
candidate: candidate,
Value: n.dictionary[int(docID)],
Score: JaccardDistance(candidate.Overlap(), sizeA, sizeB),
})
}
rid = rid[:0]
}
sort.Stable(sort.Reverse(result))
return result
}
// SplitIntoNGrams splits the given query on nGrams
func SplitIntoNGrams(nGram int, query string) []Term {
runes := []rune(query)
if len(runes) < nGram {
return []Term{}
}
result := make([]Term, 0, len(runes)-nGram+1)
for i := 0; i < len(runes)-nGram+1; i++ {
result = appendUnique(result, string(runes[i:i+nGram]))
}
return result
}
// appendUnique appends an item only to slice if there is not such item
func appendUnique(slice []Term, item Term) []Term {
for _, c := range slice {
if c == item {
return slice
}
}
return append(slice, item)
}
|
package path
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
var errNoPath = errors.New("no path provided")
// FixHomePath returns the provided path adjusted to replace the home directory tilde if there is one.
// The path may be provided as a single string or a list of elements that will be joined.
func FixHomePath(path ...string) (string, error) {
if len(path) < 1 {
return "", errNoPath
}
if strings.HasPrefix(path[0], "~/") {
if homeDir, err := os.UserHomeDir(); err != nil {
return "", fmt.Errorf("no user homeDir directory: %w", err)
} else {
// Prepend home directory and fixed first path element to rest of path elements.
path = append([]string{homeDir, path[0][2:]}, path[1:]...)
}
}
return filepath.Join(path...), nil
}
|
package server_test
import (
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/elhamza90/lifelog/internal/http/rest/server"
"github.com/elhamza90/lifelog/internal/store/memory"
"github.com/elhamza90/lifelog/internal/usecase/adding"
"github.com/elhamza90/lifelog/internal/usecase/auth"
"github.com/elhamza90/lifelog/internal/usecase/deleting"
"github.com/elhamza90/lifelog/internal/usecase/editing"
"github.com/elhamza90/lifelog/internal/usecase/listing"
"github.com/labstack/echo/v4"
log "github.com/sirupsen/logrus"
)
var (
router *echo.Echo
hnd *server.Handler
repo memory.Repository
)
// hashEnvVarName specifies the name of the environment variable
// where the testing password hash should be stored
const hashEnvVarName string = "LFLG_TEST_PASS_HASH"
func TestMain(m *testing.M) {
log.SetLevel(log.DebugLevel)
log.Debug("Setting Up Test router")
// Init Interactors and Repository
repo = memory.NewRepository()
lister := listing.NewService(&repo)
adder := adding.NewService(&repo)
editor := editing.NewService(&repo)
deletor := deleting.NewService(&repo)
authenticator := auth.NewService(hashEnvVarName)
hnd = server.NewHandler(&lister, &adder, &editor, &deletor, &authenticator)
// Define and Save JWT Secrets in Env Vars
os.Setenv("LFLG_JWT_ACCESS_SECRET", "test-access-secret")
os.Setenv("LFLG_JWT_REFRESH_SECRET", "test-refresh-secret")
// Init Router
router = echo.New()
if err := server.RegisterRoutes(router, hnd); err != nil {
os.Exit(1)
}
os.Exit(m.Run())
}
func TestHealthCheck(t *testing.T) {
path := "/health-check"
req := httptest.NewRequest(http.MethodGet, path, nil)
rec := httptest.NewRecorder()
c := router.NewContext(req, rec)
c.SetPath(path)
if err := server.HealthCheck(c); err != nil {
t.Fatalf("\nUnexpected Error: %v", err)
}
}
|
package auth551
import (
"database/sql"
"github.com/go51/model551"
"time"
)
//--[ User Model ]--------
type UserModel struct {
Id int64 `db_table:"users"`
CreatedAt time.Time
UpdatedAt time.Time
Locked bool
Enabled bool
Name string
Email string
EmailCanonical string
PasswordSalt string
Password string
Thumbnail string
Serial string
DeletedAt time.Time `db_delete:"true"`
}
func NewUserModel() interface{} {
return UserModel{}
}
func NewUserModelPointer() interface{} {
return &UserModel{}
}
func (m *UserModel) SetId(id int64) {
m.Id = id
}
func (m *UserModel) GetId() int64 {
return m.Id
}
func (m *UserModel) Scan(rows *sql.Rows) error {
return rows.Scan(
&m.Id,
&m.CreatedAt,
&m.UpdatedAt,
&m.Locked,
&m.Enabled,
&m.Name,
&m.Email,
&m.EmailCanonical,
&m.PasswordSalt,
&m.Password,
&m.Thumbnail,
&m.Serial,
)
}
func (m *UserModel) SqlValues(sqlType model551.SqlType) []interface{} {
values := make([]interface{}, 0, 13)
if sqlType == model551.SQL_LOGICAL_DELETE {
values = append(values, m.Id)
}
if sqlType == model551.SQL_INSERT {
m.CreatedAt = time.Now()
m.UpdatedAt = m.CreatedAt
}
if sqlType == model551.SQL_UPDATE {
m.UpdatedAt = time.Now()
}
values = append(values, m.CreatedAt)
values = append(values, m.UpdatedAt)
values = append(values, m.Locked)
values = append(values, m.Enabled)
values = append(values, m.Name)
values = append(values, m.Email)
values = append(values, m.EmailCanonical)
values = append(values, m.PasswordSalt)
values = append(values, m.Password)
values = append(values, m.Thumbnail)
values = append(values, m.Serial)
if sqlType == model551.SQL_UPDATE {
values = append(values, m.Id)
} else if sqlType == model551.SQL_LOGICAL_DELETE {
m.DeletedAt = time.Now()
values = append(values, m.DeletedAt)
}
return values
}
//--[/User Model ]--------
//--[ User Token Model ]--------
type UserTokenModel struct {
Id int64 `db_table:"user_tokens"`
CreatedAt time.Time
UpdatedAt time.Time
UserId int64
Vendor string
AccessToken string
TokenSecret string
Expiry time.Time
RefreshToken string
TokenType string
AccountId string
Name string
Thumbnail string
DeletedAt time.Time `db_delete:"true"`
}
func NewUserTokenModel() interface{} {
return UserTokenModel{}
}
func NewUserTokenModelPointer() interface{} {
return &UserTokenModel{}
}
func (m *UserTokenModel) SetId(id int64) {
m.Id = id
}
func (m *UserTokenModel) GetId() int64 {
return m.Id
}
func (m *UserTokenModel) Scan(rows *sql.Rows) error {
return rows.Scan(
&m.Id,
&m.CreatedAt,
&m.UpdatedAt,
&m.UserId,
&m.Vendor,
&m.AccessToken,
&m.TokenSecret,
&m.Expiry,
&m.RefreshToken,
&m.TokenType,
&m.AccountId,
&m.Name,
&m.Thumbnail,
)
}
func (m *UserTokenModel) SqlValues(sqlType model551.SqlType) []interface{} {
values := make([]interface{}, 0, 11)
if sqlType == model551.SQL_LOGICAL_DELETE {
values = append(values, m.Id)
}
if sqlType == model551.SQL_INSERT {
m.CreatedAt = time.Now()
m.UpdatedAt = m.CreatedAt
}
if sqlType == model551.SQL_UPDATE {
m.UpdatedAt = time.Now()
}
values = append(values, m.CreatedAt)
values = append(values, m.UpdatedAt)
values = append(values, m.UserId)
values = append(values, m.Vendor)
values = append(values, m.AccessToken)
values = append(values, m.TokenSecret)
values = append(values, m.Expiry)
values = append(values, m.RefreshToken)
values = append(values, m.TokenType)
values = append(values, m.AccountId)
values = append(values, m.Name)
values = append(values, m.Thumbnail)
if sqlType == model551.SQL_UPDATE {
values = append(values, m.Id)
} else if sqlType == model551.SQL_LOGICAL_DELETE {
m.DeletedAt = time.Now()
values = append(values, m.DeletedAt)
}
return values
}
//--[/User Token Model ]--------
//--[ Access Token Model ]--------
type AccessToken struct {
AccessToken string
TokenSecret string
TokenType string
RefreshToken string
Expiry time.Time
}
//--[/Access Token Model ]--------
//--[ Access Token Model ]--------
type AccountInformation struct {
Id string
Name string
Email string
Picture string
}
//--[/Access Token Model ]--------
|
//go:build e2e
package cloudnative
const (
oneAgentInstallContainerName = "install-oneagent"
)
|
/*
Decoding MIPS Instructions
I-Instruction format:
| opcode | rs | rt | immediate |
| ------ | ------ | ------ | ------------------------ |
| 6 bit | 5 bits | 5 bits | 16 bits |
J-Instruction format:
| opcode | address |
| ------ | ------------------------------------------ |
| 6 bit | 26 bits |
R-Instruction format:
| opcode | rs | rt | rd | sa | funct |
| ------ | ------ | ------ | ------ | ------ | ------ |
| 6 bit | 5 bits | 5 bits | 5 bits | 5 bits | 6 bits |
*/
package cpu
import "n64emu/pkg/types"
// I-Type Instruction format
type InstI struct {
// src[31:26] 6 bits
Opcode types.Byte
// src[25:21] 5 bits
Rs types.Byte
// src[20:16] 5 bits
Rt types.Byte
// src[15:0] 16 bits
Immediate types.HalfWord
}
// J-Type Instruction format
type InstJ struct {
// src[31:26] 6 bits
Opcode types.Byte
// src[25:0] 26 bits
Address types.Word
}
// R-Type Instruction format
type InstR struct {
// src[31:26] 6 bits
Opcode types.Byte
// src[25:21] 5 bits
Rs types.Byte
// src[20:16] 5 bits
Rt types.Byte
// src[15:11] 5 bits
Rd types.Byte
// src[10:6] 5 bits
Sa types.Byte
// src[5:0] 6 bits
Funct types.Byte
}
// Decode I-Type Instruction
func DecodeI(src types.Word) InstI {
return InstI{
Opcode: GetOp(src),
Rs: types.Byte((src >> 21) & 0x1f),
Rt: types.Byte((src >> 16) & 0x1f),
Immediate: types.HalfWord((src >> 0) & 0xffff),
}
}
// Decode J-Type Instruction
func DecodeJ(src types.Word) InstJ {
return InstJ{
Opcode: GetOp(src),
Address: (src >> 0) & 0x03ff_ffff,
}
}
// Decode R-Type Instruction
func DecodeR(src types.Word) InstR {
return InstR{
Opcode: GetOp(src),
Rs: types.Byte((src >> 21) & 0x1f),
Rt: types.Byte((src >> 16) & 0x1f),
Rd: types.Byte((src >> 11) & 0x1f),
Sa: types.Byte((src >> 6) & 0x1f),
Funct: types.Byte((src >> 0) & 0x3f),
}
}
func GetOp(src types.Word) types.Byte {
return types.Byte((src >> 26) & 0x3f)
}
|
package whitelist
import (
"github.com/mrdniwe/clc.wtf/internal/config"
"github.com/mrdniwe/clc.wtf/internal/interfaces"
)
type wl struct {
conf config.WhitelistConfig
}
func (s *wl) IsUserAllowed(id int) bool {
for _, user := range s.conf.GetWhitelistedIds() {
if id == user {
return true
}
}
return false
}
func New(conf config.WhitelistConfig) interfaces.WhitelistChecker {
return &wl{conf: conf}
}
|
package storage
import (
"github.com/jinzhu/gorm"
"gitlab.cheppers.com/devops-academy-2018/shop2/pkg/shoe/model"
)
type SQL struct {
db *gorm.DB
}
func (s *SQL) Init(db *gorm.DB) {
s.db = db
}
func (s *SQL) Insert(p model.Shoe) (model.Shoe, error) {
pp := &p
s.db.Model(p).Create(pp)
return *pp, nil
}
func (s *SQL) Read(id uint) (p model.Shoe) {
s.db.Model(model.Shoe{}).First(&p)
return
}
func (s *SQL) Update(p model.Shoe, fields map[string]interface{}) (model.Shoe, error) {
s.db.Model(&p).Updates(fields)
return p, nil
}
func (s *SQL) Delete(id uint) error {
p := model.Shoe{
Model: gorm.Model{
ID: id,
},
}
s.db.Delete(p)
return nil
}
func (s *SQL) List() (list []model.Shoe) {
list = []model.Shoe{}
s.db.Model(model.Shoe{}).Find(&list)
return
}
func (s *SQL) Count() int {
numOfRecords := new(int)
s.db.Model(model.Shoe{}).Count(numOfRecords)
return *numOfRecords
}
|
package beer
import (
"fmt"
)
func Verses() {
fmt.Printf("99 bottles of beer on the wall, 99 bottles of beer.\n")
for beer := 98; beer > 1; beer-- {
fmt.Printf("Take one down and pass it around, %d bottles of beer on the wall.\n\n", beer)
fmt.Printf("%d bottles of beer on the wall, %d bottles of beer.\n", beer, beer)
}
fmt.Printf("Take one down and pass it around, 1 bottle of beer on the wall.\n\n")
fmt.Printf("1 bottle of beer on the wall, 1 bottle of beer.\n")
fmt.Printf("Take it down and pass it around, no more bottles of beer on the wall.\n\n")
fmt.Printf("No more bottles of beer on the wall, no more bottles of beer.\n")
fmt.Printf("Go to the store and buy some more, 99 bottles of beer on the wall.\n")
}
|
/*
Copyright 2019 Baidu, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package reporter
import (
"fmt"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/json"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/tools/cache"
"k8s.io/klog"
"github.com/baidu/ote-stack/pkg/clustermessage"
)
const (
tickerDuration = 5 * time.Second
)
// PodReporter is responsible for synchronizing pod status of edge cluster.
type PodReporter struct {
SyncChan chan clustermessage.ClusterMessage
updatedPodsRWMutex *sync.RWMutex
updatedPodsMap *PodResourceStatus
ctx *ReporterContext
}
// newPodReporter creates a new PodReporter.
func newPodReporter(ctx *ReporterContext) (*PodReporter, error) {
if !ctx.IsValid() {
return nil, fmt.Errorf("ReporterContext validation failed")
}
podReporter := &PodReporter{
ctx: ctx,
updatedPodsMap: &PodResourceStatus{
UpdateMap: make(map[string]*corev1.Pod),
DelMap: make(map[string]*corev1.Pod),
FullList: make([]string, 0),
},
updatedPodsRWMutex: &sync.RWMutex{},
SyncChan: ctx.SyncChan,
}
ctx.InformerFactory.Core().V1().Pods().Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: podReporter.handlePod,
UpdateFunc: func(old, new interface{}) {
newPod := new.(*corev1.Pod)
oldPod := old.(*corev1.Pod)
if newPod.ResourceVersion == oldPod.ResourceVersion {
// Periodic resync will send update events for all known Deployments.
// Two different versions of the same Deployment will always have different RVs.
return
}
podReporter.handlePod(new)
},
DeleteFunc: podReporter.deletePod,
})
go podReporter.reportFullListPod(ctx)
return podReporter, nil
}
// Run begins watching and syncing.
func (pr *PodReporter) Run(stopCh <-chan struct{}) error {
klog.Info("starting podReporter")
go wait.Until(pr.sendClusterMessageToSyncChan, tickerDuration, stopCh)
<-stopCh
klog.Info("shutting down podReporter")
return nil
}
// sendClusterMessageToSyncChan sends wrapped ClusterMessage data to SyncChan.
func (pr *PodReporter) sendClusterMessageToSyncChan() {
pr.updatedPodsRWMutex.Lock()
defer pr.updatedPodsRWMutex.Unlock()
// check map length, empty UpdateMap, DelMap and FullList don't need to send pod reports
if len(pr.updatedPodsMap.UpdateMap) == 0 && len(pr.updatedPodsMap.DelMap) == 0 && len(pr.updatedPodsMap.FullList) == 0 {
return
}
updatedPodsMapJSON, err := json.Marshal(*pr.updatedPodsMap)
if err != nil {
klog.Errorf("serialize map failed: %v", err)
return
}
// Define pod report content and convert to json
data := []Report{
{
ResourceType: ResourceTypePod,
Body: updatedPodsMapJSON,
},
}
jsonMap, err := json.Marshal(data)
if err != nil {
klog.Errorf("serialize report slice failed: %v", err)
return
}
// define pb msg
msg := &clustermessage.ClusterMessage{
Head: &clustermessage.MessageHead{
MessageID: "",
Command: clustermessage.CommandType_EdgeReport,
ClusterSelector: "",
ClusterName: pr.ctx.ClusterName(),
ParentClusterName: "",
},
Body: jsonMap,
}
// send msg to chan
pr.SyncChan <- *msg
// clean up the map
pr.updatedPodsMap.DelMap = make(map[string]*corev1.Pod)
pr.updatedPodsMap.UpdateMap = make(map[string]*corev1.Pod)
pr.updatedPodsMap.FullList = make([]string, 0)
}
// SetUpdateMap adds pod objects to UpdateMap.
func (pr *PodReporter) SetUpdateMap(name string, pod *corev1.Pod) {
pr.updatedPodsRWMutex.Lock()
defer pr.updatedPodsRWMutex.Unlock()
pr.updatedPodsMap.UpdateMap[name] = pod
}
// SetDelMap adds pod objects to DelMap.
func (pr *PodReporter) SetDelMap(name string, pod *corev1.Pod) {
pr.updatedPodsRWMutex.Lock()
defer pr.updatedPodsRWMutex.Unlock()
if _, ok := pr.updatedPodsMap.UpdateMap[name]; ok {
delete(pr.updatedPodsMap.UpdateMap, name)
}
pr.updatedPodsMap.DelMap[name] = pod
}
func (pr *PodReporter) SetFullListMap(podList []string) {
pr.updatedPodsRWMutex.Lock()
defer pr.updatedPodsRWMutex.Unlock()
pr.updatedPodsMap.FullList = podList
}
func startPodReporter(ctx *ReporterContext) error {
podReporter, err := newPodReporter(ctx)
if err != nil {
klog.Errorf("Failed to start pod reporter: %v", err)
return err
}
go podReporter.Run(ctx.StopChan)
return nil
}
// handlePod is used to handle the creation and update operations of the pod.
func (pr *PodReporter) handlePod(obj interface{}) {
pod, ok := obj.(*corev1.Pod)
if !ok {
klog.Errorf("Should be Pod object but encounter others in handlePod")
return
}
pr.resetPodSpecParameter(pod)
addLabelToResource(&pod.ObjectMeta, pr.ctx)
if pr.ctx.IsLightweightReport {
pod = pr.lightWeightPod(pod)
}
key, err := cache.MetaNamespaceKeyFunc(pod)
if err != nil {
klog.Errorf("Failed to get map key: %s", err)
return
}
klog.V(3).Infof("find pod : %s", key)
pr.SetUpdateMap(key, pod)
}
func (pr *PodReporter) resetPodSpecParameter(pod *corev1.Pod) {
if pod.Labels == nil {
pod.Labels = make(map[string]string)
}
pod.Labels[EdgeNodeName] = pod.Spec.NodeName
}
// deletePod is used to handle the removal of the pod.
func (pr *PodReporter) deletePod(obj interface{}) {
pod, ok := obj.(*corev1.Pod)
if !ok {
klog.Errorf("Should be Pod object but encounter others in deletePod")
return
}
addLabelToResource(&pod.ObjectMeta, pr.ctx)
if pr.ctx.IsLightweightReport {
pod = pr.lightWeightPod(pod)
}
key, err := cache.MetaNamespaceKeyFunc(pod)
if err != nil {
klog.Errorf("Failed to get map key: %v", err)
return
}
pr.SetDelMap(key, pod)
}
// lightWeightPod crops the content of the pod
func (pr *PodReporter) lightWeightPod(pod *corev1.Pod) *corev1.Pod {
return &corev1.Pod{
TypeMeta: pod.TypeMeta,
ObjectMeta: metav1.ObjectMeta{
Name: pod.Name,
Namespace: pod.Namespace,
Labels: pod.Labels,
},
Spec: corev1.PodSpec{
Containers: pod.Spec.Containers,
NodeName: pod.Spec.NodeName,
Volumes: pod.Spec.Volumes,
Tolerations: pod.Spec.Tolerations,
},
Status: corev1.PodStatus{
Phase: pod.Status.Phase,
ContainerStatuses: pod.Status.ContainerStatuses,
},
}
}
// reportFullListPod report all pods list when starts pod reporter.
func (pr *PodReporter) reportFullListPod(ctx *ReporterContext) {
if ok := cache.WaitForCacheSync(ctx.StopChan, ctx.InformerFactory.Core().V1().Pods().Informer().HasSynced); !ok {
klog.Errorf("failed to wait for caches to sync")
return
}
podList := ctx.InformerFactory.Core().V1().Pods().Informer().GetIndexer().ListKeys()
pr.SetFullListMap(podList)
}
|
package main
import (
"fmt"
"math/rand"
"runtime"
"sync"
"time"
)
var total int32 = 10
var mu = &sync.Mutex{}
func sell(id int) {
for {
mu.Lock()
if total > 0 {
time.Sleep(time.Duration(rand.Intn(5)) * time.Second)
total--
fmt.Println("id:", id, "ticket:", total)
} else {
break
}
mu.Unlock()
}
}
func main() {
runtime.GOMAXPROCS(2)
rand.Seed(time.Now().Unix())
for i := 0; i < 5; i++ {
go sell(i)
}
var input string
fmt.Scanln(&input)
fmt.Println(total, "done")
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.