text stringlengths 11 4.05M |
|---|
package main
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"github.com/KyleBanks/depth"
)
func main() {
rp := flag.String("r", "", "path of the downloaded github repos")
of := flag.String("o", "deps.csv", "output file")
flag.Parse()
out, err := os.Create(*of)
if err != nil {
log.Fatal(err)
}
defer out.Close()
gp := os.Getenv("GOPATH")
err = filepath.Walk(*rp, func(path string, info os.FileInfo, err error) error {
if err != nil {
log.Printf("prevent panic by handling failure accessing a path %q: %v\n", path, err)
return err
}
if !info.IsDir() {
return nil
}
var t depth.Tree
t.MaxDepth = 1
p := strings.Replace(path, gp+string(os.PathSeparator)+"src"+string(os.PathSeparator), "", 1)
if !validSrc(p) {
return nil
}
err = t.Resolve(p)
if err != nil {
log.Printf("error with %s: %v", p, err)
return nil
}
for _, d := range t.Root.Deps {
out.WriteString(fmt.Sprintf("%s,%s\n", p, d.Name))
}
return nil
})
if err != nil {
log.Printf("error walking repos in %s: %v\n", *rp, err)
return
}
}
var invalidSrc = []string{"vendor", "_vendor", "workspace", "_workspace", "Godeps"}
func validSrc(src string) bool {
dirs := strings.Split(src, string(os.PathSeparator))
gh := 0
for _, d := range dirs {
if d == "github.com" {
gh++
continue
}
for _, id := range invalidSrc {
if d == id {
return false
}
}
}
return gh == 1
}
|
package str
import (
"bytes"
"strings"
"unicode"
"unicode/utf8"
)
func TrimStringSlice(raw []string) []string {
if raw == nil {
return []string{}
}
cnt := len(raw)
arr := make([]string, 0, cnt)
for i := 0; i < cnt; i++ {
item := strings.TrimSpace(raw[i])
if item == "" {
continue
}
arr = append(arr, item)
}
return arr
}
func to(fn func(rune) rune, str string) (string, error) {
if len(str) == 0 {
return "", nil
}
var bf bytes.Buffer
var err error
for _, r := range str {
_, err = bf.WriteRune(fn(r))
if err != nil {
break
}
}
return bf.String(), err
}
// ToUpper convert a string to uppercase
func ToUpper(str string) string {
s, _ := to(unicode.ToUpper, str)
return s
}
// ToLower convert a string to lowercase
func ToLower(str string) string {
s, _ := to(unicode.ToLower, str)
return s
}
// ToTitle title string, initial char of the string to uppercase
func ToTitle(str string) string {
if IsEmpty(str) {
return str
}
runes := []rune(str)
runes[0] = unicode.ToTitle(runes[0])
return string(runes)
}
// Reverse reverse a string
func Reverse(str string) string {
// special case
if IsEmpty(str) {
return ""
}
if len(str) == 1 {
return str
}
var bf bytes.Buffer
for len(str) > 0 {
r, size := utf8.DecodeLastRuneInString(str)
bf.WriteRune(r)
str = str[:len(str)-size]
}
return bf.String()
}
// Repeat returns a new string consisting of count copies of the string str
func Repeat(str string, count int) string {
if IsEmpty(str) || count == 0 {
return str
}
return strings.Repeat(str, count)
}
// IsEmpty returns a boolean of s equal "" or len(s) == 0
func IsEmpty(str string) bool {
return "" == str || 0 == len(str)
}
|
package checker
import (
"strings"
"github.com/ryanchew3/flexera-coding-challenge/internal/model"
)
// getKeys gets the keys of in incoming mapstructure
func getKeys(in map[int64][]*model.Computer) []int64 {
keys := make([]int64, len(in))
i := 0
for k := range in {
keys[i] = k
i++
}
return keys
}
// ProcessChecks processes the list of user owned machines and calculates how many licences are needed
func ProcessChecks(in map[int64][]*model.Computer) int {
keys := getKeys(in)
totalLicences := 0
for _, k := range keys {
numLaptops := 0
numDesktops := 0
id := make(map[int64]rune)
for _, c := range in[k] {
_, ok := id[c.Id]
if !ok {
id[c.Id] = ' '
switch strings.ToLower(c.Type) {
case "desktop":
numDesktops++
case "laptop":
numLaptops++
}
}
}
numDesktops = numDesktops - numLaptops
if numDesktops < 0 {
numDesktops = 0
}
totalLicences = totalLicences + numDesktops + numLaptops
}
return totalLicences
}
|
// Copyright 2023 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package importinto
import (
"context"
"encoding/json"
"fmt"
"testing"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/disttask/framework/proto"
"github.com/pingcap/tidb/domain/infosync"
"github.com/pingcap/tidb/executor/importer"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
)
type importIntoSuite struct {
suite.Suite
}
func TestImportInto(t *testing.T) {
suite.Run(t, &importIntoSuite{})
}
func (s *importIntoSuite) enableFailPoint(path, term string) {
require.NoError(s.T(), failpoint.Enable(path, term))
s.T().Cleanup(func() {
_ = failpoint.Disable(path)
})
}
func (s *importIntoSuite) TestFlowHandleGetEligibleInstances() {
makeFailpointRes := func(v interface{}) string {
bytes, err := json.Marshal(v)
s.NoError(err)
return fmt.Sprintf("return(`%s`)", string(bytes))
}
uuids := []string{"ddl_id_1", "ddl_id_2"}
serverInfoMap := map[string]*infosync.ServerInfo{
uuids[0]: {
ID: uuids[0],
},
uuids[1]: {
ID: uuids[1],
},
}
mockedAllServerInfos := makeFailpointRes(serverInfoMap)
h := flowHandle{}
gTask := &proto.Task{Meta: []byte("{}")}
s.enableFailPoint("github.com/pingcap/tidb/domain/infosync/mockGetAllServerInfo", mockedAllServerInfos)
eligibleInstances, err := h.GetEligibleInstances(context.Background(), gTask)
s.NoError(err)
// order of slice is not stable, change to map
resultMap := map[string]*infosync.ServerInfo{}
for _, ins := range eligibleInstances {
resultMap[ins.ID] = ins
}
s.Equal(serverInfoMap, resultMap)
gTask.Meta = []byte(`{"EligibleInstances":[{"ip": "1.1.1.1", "listening_port": 4000}]}`)
eligibleInstances, err = h.GetEligibleInstances(context.Background(), gTask)
s.NoError(err)
s.Equal([]*infosync.ServerInfo{{IP: "1.1.1.1", Port: 4000}}, eligibleInstances)
}
func (s *importIntoSuite) TestUpdateCurrentTask() {
taskMeta := TaskMeta{
Plan: importer.Plan{
DisableTiKVImportMode: true,
},
}
bs, err := json.Marshal(taskMeta)
require.NoError(s.T(), err)
h := flowHandle{}
require.Equal(s.T(), int64(0), h.currTaskID.Load())
require.False(s.T(), h.disableTiKVImportMode.Load())
h.updateCurrentTask(&proto.Task{
ID: 1,
Meta: bs,
})
require.Equal(s.T(), int64(1), h.currTaskID.Load())
require.True(s.T(), h.disableTiKVImportMode.Load())
h.updateCurrentTask(&proto.Task{
ID: 1,
Meta: bs,
})
require.Equal(s.T(), int64(1), h.currTaskID.Load())
require.True(s.T(), h.disableTiKVImportMode.Load())
}
|
package main
func sum(a []int) int {
if len(a) == 1 {
return a[0]
}
return a[0] + sum(a[1:])
}
func main() {
a:=[]int{1,8,3,2}
println(sum(a))
} |
package verify
import (
"errors"
"strings"
verify_method "github.com/winily/go-utils/verify/method"
)
type Tag struct {
Scenes []string
Methods []verify_method.Method
Message string
}
func TagParse(tag string) Tag {
tags := strings.Split(tag, ";")
result := Tag{}
for _, tag := range tags {
tagitmes := strings.Split(tag, "=")
if len(tagitmes) != 2 {
panic(errors.New("校验 tag 格式错误 tag = " + tag))
}
key := tagitmes[0]
value := tagitmes[1]
switch strings.ToLower(key) {
case "scene":
result.Scenes = strings.Split(value, ",")
case "method":
methods := strings.Split(value, ",")
result.Methods = verify_method.CreateMethods(methods)
case "message":
result.Message = value
}
}
return result
}
|
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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 v1http
import (
"github.com/emicklei/go-restful"
"github.com/Tencent/bk-bcs/bcs-services/bcs-user-manager/app/pkg/esb/cmdb"
"github.com/Tencent/bk-bcs/bcs-services/bcs-user-manager/app/pkg/jwt"
"github.com/Tencent/bk-bcs/bcs-services/bcs-user-manager/app/pkg/middleware"
"github.com/Tencent/bk-bcs/bcs-services/bcs-user-manager/app/user-manager/storages/cache"
"github.com/Tencent/bk-bcs/bcs-services/bcs-user-manager/app/user-manager/storages/sqlstore"
"github.com/Tencent/bk-bcs/bcs-services/bcs-user-manager/app/user-manager/v1http/auth"
"github.com/Tencent/bk-bcs/bcs-services/bcs-user-manager/app/user-manager/v1http/cluster"
"github.com/Tencent/bk-bcs/bcs-services/bcs-user-manager/app/user-manager/v1http/credential"
"github.com/Tencent/bk-bcs/bcs-services/bcs-user-manager/app/user-manager/v1http/iam"
"github.com/Tencent/bk-bcs/bcs-services/bcs-user-manager/app/user-manager/v1http/permission"
"github.com/Tencent/bk-bcs/bcs-services/bcs-user-manager/app/user-manager/v1http/tke"
"github.com/Tencent/bk-bcs/bcs-services/bcs-user-manager/app/user-manager/v1http/token"
"github.com/Tencent/bk-bcs/bcs-services/bcs-user-manager/app/user-manager/v1http/user"
"github.com/Tencent/bk-bcs/bcs-services/bcs-user-manager/config"
)
// InitV1Routers init v1 version route,
// it's compatible with bcs-api
func InitV1Routers(ws *restful.WebService, service *permission.PermVerifyClient) {
ws.Filter(middleware.RequestIDFilter)
ws.Filter(middleware.TracingFilter)
ws.Filter(middleware.LoggingFilter)
initUsersRouters(ws)
initClustersRouters(ws)
initTkeRouters(ws)
initPermissionRouters(ws, service)
initTokenRouters(ws)
initExtraTokenRouters(ws, service)
initIAMProviderRouters(ws)
initUserPermsRouters(ws)
}
// initUsersRouters init users api routers
func initUsersRouters(ws *restful.WebService) {
ws.Route(auth.AdminAuthFunc(ws.POST("/v1/users/admin/{user_name}")).To(user.CreateAdminUser))
ws.Route(auth.AdminAuthFunc(ws.GET("/v1/users/admin/{user_name}")).To(user.GetAdminUser))
ws.Route(auth.AdminAuthFunc(ws.POST("/v1/users/saas/{user_name}")).To(user.CreateSaasUser))
ws.Route(auth.AdminAuthFunc(ws.GET("/v1/users/saas/{user_name}")).To(user.GetSaasUser))
ws.Route(auth.AdminAuthFunc(ws.PUT("/v1/users/saas/{user_name}/refresh")).To(user.RefreshSaasToken))
ws.Route(auth.AuthFunc(ws.POST("/v1/users/plain/{user_name}")).To(user.CreatePlainUser))
ws.Route(auth.AuthFunc(ws.GET("/v1/users/plain/{user_name}")).To(user.GetPlainUser))
ws.Route(auth.AuthFunc(ws.PUT("/v1/users/plain/{user_name}/refresh/{expire_time}")).To(user.RefreshPlainToken))
}
// initClustersRouters init cluster api routers
func initClustersRouters(ws *restful.WebService) {
ws.Route(auth.AdminAuthFunc(ws.POST("/v1/clusters")).To(cluster.CreateCluster))
ws.Route(auth.AdminAuthFunc(ws.POST("/v1/clusters/{cluster_id}/register_tokens")).To(token.CreateRegisterToken))
ws.Route(auth.AdminAuthFunc(ws.GET("/v1/clusters/{cluster_id}/register_tokens")).To(token.GetRegisterToken))
ws.Route(ws.PUT("/v1/clusters/{cluster_id}/credentials").To(credential.UpdateCredentials))
ws.Route(auth.AdminAuthFunc(ws.GET("/v1/clusters/{cluster_id}/credentials")).To(credential.GetCredentials))
ws.Route(auth.AdminAuthFunc(ws.GET("/v1/clusters/credentials")).To(credential.ListCredentials))
}
// initPermissionRouters init permission api routers
func initPermissionRouters(ws *restful.WebService, service *permission.PermVerifyClient) {
ws.Route(auth.AdminAuthFunc(ws.POST("/v1/permissions")).To(permission.GrantPermission))
ws.Route(auth.AdminAuthFunc(ws.GET("/v1/permissions")).To(permission.GetPermission))
ws.Route(auth.AdminAuthFunc(ws.DELETE("/v1/permissions")).To(permission.RevokePermission))
ws.Route(auth.AdminAuthFunc(ws.GET("/v1/permissions/verify")).To(permission.VerifyPermission))
ws.Route(auth.AdminAuthFunc(ws.GET("/v2/permissions/verify")).To(service.VerifyPermissionV2))
}
// initTokenRouters init bcs token
func initTokenRouters(ws *restful.WebService) {
tokenHandler := token.NewTokenHandler(sqlstore.NewTokenStore(sqlstore.GCoreDB, config.GlobalCryptor),
sqlstore.NewTokenNotifyStore(sqlstore.GCoreDB), cache.RDB, jwt.JWTClient)
ws.Route(auth.TokenAuthFunc(ws.POST("/v1/tokens").To(tokenHandler.CreateToken)))
ws.Route(auth.TokenAuthFunc(ws.GET("/v1/users/{username}/tokens").To(tokenHandler.GetToken)))
ws.Route(auth.TokenAuthFunc(ws.DELETE("/v1/tokens/{token}").To(tokenHandler.DeleteToken)))
ws.Route(auth.TokenAuthFunc(ws.PUT("/v1/tokens/{token}").To(tokenHandler.UpdateToken)))
// for Temporary Token
ws.Route(auth.TokenAuthFunc(ws.POST("/v1/tokens/temp").To(tokenHandler.CreateTempToken)))
ws.Route(auth.TokenAuthFunc(ws.POST("/v1/tokens/client").To(tokenHandler.CreateClientToken)))
ws.Route(auth.TokenAuthFunc(ws.GET("/v1/users/info")).To(user.GetCurrentUserInfo))
}
// initExtraTokenRouters init bcs extra token for third-party system
func initExtraTokenRouters(ws *restful.WebService, service *permission.PermVerifyClient) {
tokenHandler := token.NewExtraTokenHandler(sqlstore.NewTokenStore(sqlstore.GCoreDB, config.GlobalCryptor),
sqlstore.NewTokenNotifyStore(sqlstore.GCoreDB), cache.RDB, jwt.JWTClient, cmdb.CMDBClient)
ws.Route(ws.GET("/v1/tokens/extra/getClusterUserToken").To(tokenHandler.GetTokenByUserAndClusterID))
}
// initTkeRouters init tke api routers
func initTkeRouters(ws *restful.WebService) {
ws.Route(auth.AdminAuthFunc(ws.POST("/v1/tke/cidr/add_cidr")).To(tke.AddTkeCidr))
ws.Route(auth.AdminAuthFunc(ws.POST("/v1/tke/cidr/apply_cidr")).To(tke.ApplyTkeCidr))
ws.Route(auth.AdminAuthFunc(ws.POST("/v1/tke/cidr/release_cidr")).To(tke.ReleaseTkeCidr))
ws.Route(auth.AdminAuthFunc(ws.POST("/v1/tke/cidr/list_count")).To(tke.ListTkeCidr))
ws.Route(auth.AdminAuthFunc(ws.POST("/v1/tke/{cluster_id}/sync_credentials")).To(tke.SyncTkeClusterCredentials))
}
// initIAMProviderRouters init iam provider api routers
func initIAMProviderRouters(ws *restful.WebService) {
ws.Route(auth.BKIAMAuthFunc(ws.POST("/v1/iam-provider/resources")).To(iam.ResourceDispatch))
}
// initUserPermsRouters init user perms api routers
func initUserPermsRouters(ws *restful.WebService) {
ws.Route(auth.TokenAuthFunc(ws.POST("/v1/iam/user_perms")).To(iam.GetPerms))
ws.Route(auth.TokenAuthFunc(ws.POST("/v1/iam/user_perms/actions/{action_id}")).To(iam.GetPermByActionID))
}
|
package endpoints
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/google/uuid"
"github.com/sumelms/microservice-course/pkg/validator"
"github.com/go-kit/kit/endpoint"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/sumelms/microservice-course/internal/course/domain"
)
type createSubscriptionRequest struct {
UserID uuid.UUID `json:"user_id" validate:"required"`
CourseID uuid.UUID `json:"course_id" validate:"required"`
MatrixID *uuid.UUID `json:"matrix_id"`
ExpiresAt *time.Time `json:"expires_at"`
}
type createSubscriptionResponse struct {
UUID uuid.UUID `json:"uuid"`
UserID uuid.UUID `json:"user_id"`
CourseID uuid.UUID `json:"course_id"`
MatrixID *uuid.UUID `json:"matrix_id,omitempty"`
ExpiresAt *time.Time `json:"expires_at"`
}
func NewCreateSubscriptionHandler(s domain.ServiceInterface, opts ...kithttp.ServerOption) *kithttp.Server {
return kithttp.NewServer(
makeCreateSubscriptionEndpoint(s),
decodeCreateSubscriptionRequest,
encodeCreateSubscriptionResponse,
opts...,
)
}
func makeCreateSubscriptionEndpoint(s domain.ServiceInterface) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req, ok := request.(createSubscriptionRequest)
if !ok {
return nil, fmt.Errorf("invalid argument")
}
v := validator.NewValidator()
if err := v.Validate(req); err != nil {
return nil, err
}
var sub domain.Subscription
data, _ := json.Marshal(req)
if err := json.Unmarshal(data, &sub); err != nil {
return nil, err
}
if err := s.CreateSubscription(ctx, &sub); err != nil {
return nil, err
}
return createSubscriptionResponse{
UUID: sub.UUID,
UserID: sub.UserID,
CourseID: sub.CourseID,
MatrixID: sub.MatrixID,
ExpiresAt: sub.ExpiresAt,
}, nil
}
}
func decodeCreateSubscriptionRequest(_ context.Context, r *http.Request) (interface{}, error) {
var req createSubscriptionRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return nil, err
}
return req, nil
}
func encodeCreateSubscriptionResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
return kithttp.EncodeJSONResponse(ctx, w, response)
}
|
// 21. Implement the MT19937 Mersenne Twister RNG
package main
import (
"bufio"
"flag"
"fmt"
"os"
)
const (
arraySize = 624
offset = 397
multiplier = 1812433253
upperMask = 0x80000000
lowerMask = 0x7fffffff
coefficient = 0x9908b0df
temperMask1 = 0x9d2c5680
temperMask2 = 0xefc60000
)
func main() {
var seed uint
flag.UintVar(&seed, "s", 5489, "seed")
flag.Parse()
mt := NewMT(uint32(seed))
input := bufio.NewScanner(os.Stdin)
for input.Scan() {
fmt.Print(mt.Uint32())
}
}
// MT represents an MT19937 PRNG.
type MT struct {
state [arraySize]uint32
pos int
}
// NewMT initializes and returns a new PRNG.
func NewMT(seed uint32) *MT {
var mt MT
mt.state[0] = seed
for i := 1; i < len(mt.state); i++ {
mt.state[i] = multiplier*
(mt.state[i-1]^(mt.state[i-1]>>30)) +
uint32(i)
}
mt.twist()
return &mt
}
// Uint32 returns a pseudo-random unsigned 32-bit integer.
func (mt *MT) Uint32() uint32 {
n := temper(mt.state[mt.pos])
mt.pos++
if mt.pos == len(mt.state) {
mt.twist()
mt.pos = 0
}
return n
}
// twist scrambles the state array.
func (mt *MT) twist() {
for i := range mt.state {
n := (mt.state[i] & upperMask) | (mt.state[(i+1)%len(mt.state)] & lowerMask)
mt.state[i] = mt.state[(i+offset)%len(mt.state)] ^ (n >> 1)
if n&1 == 1 {
mt.state[i] ^= coefficient
}
}
}
// temper applies the tempering transformation.
func temper(n uint32) uint32 {
n ^= n >> 11
n ^= (n << 7) & temperMask1
n ^= (n << 15) & temperMask2
n ^= n >> 18
return n
}
|
// Package wasmhttp (github.com/nlepage/go-wasm-http-server) allows to create a WebAssembly Go HTTP Server embedded in a ServiceWorker.
//
// It is a subset of the full solution, a full usage is available on the github repository: https://github.com/nlepage/go-wasm-http-server
package wasmhttp
|
package main
import (
"context"
"flag"
"fmt"
"github.com/markbates/pkger"
"io"
"log"
"net/http"
"os/user"
"time"
"github.com/fsnotify/fsnotify"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/cors"
remote "github.com/mkozhukh/go-remote"
)
var configPath string
var hub *remote.Hub
func main() {
flag.StringVar(&configPath, "config", "", "path to the configuration file")
flag.Parse()
if configPath == "" {
usr, _ := user.Current()
configPath = usr.HomeDir + "/.dash.yml"
}
reloadConfig()
initJWT()
go trackChanges()
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
if Config.Cors != "" {
c := cors.New(cors.Options{
AllowedOrigins: []string{Config.Cors},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"*"},
AllowCredentials: true,
MaxAge: 300,
})
r.Use(c.Handler)
}
r.Get("/api/v1", initApi())
fs := http.FileServer(pkger.Dir("/public"))
r.Get("/*", func(w http.ResponseWriter, r *http.Request) {
if _, err := pkger.Stat("/public"+r.RequestURI); err != nil {
f, _ := pkger.Open("/public/index.html")
defer f.Close()
w.Header().Set("Content-type", "text/html")
_,_ = io.Copy(w, f)
} else {
fs.ServeHTTP(w, r)
}
})
fmt.Println("Listen at port ", Config.Port)
err := http.ListenAndServe(Config.Port, r)
if err != nil {
log.Println(err.Error())
}
}
func reloadConfig() {
Config.LoadFromFile(configPath)
}
func initApi() http.HandlerFunc {
api := remote.NewServer(&remote.ServerConfig{
WebSocket: true,
})
must(api.AddConstant("version", "1.0.0"))
must(api.AddService("admin", &AdminAPI{}))
must(api.Dependencies.AddProvider(func(ctx context.Context) *remote.Hub { return api.Events }))
must(api.Dependencies.AddProvider(func(ctx context.Context) remote.ConnectionID {
cid, _ := ctx.Value(remote.ConnectionValue).(remote.ConnectionID)
return cid
}))
return api.ServeHTTP
}
func must(err error) {
if err != nil {
panic(err)
}
}
func trackChanges() {
watcher, _ := fsnotify.NewWatcher()
defer watcher.Close()
err := watcher.Add(configPath)
if err != nil {
log.Fatal(err)
}
done := make(chan bool)
go debounce(200*time.Millisecond, watcher.Events, func(ev fsnotify.Event) {
if ev.Op == fsnotify.Write {
reloadConfig()
}
})
<-done
}
func debounce(interval time.Duration, input chan fsnotify.Event, cb func(ev fsnotify.Event)) {
var item fsnotify.Event
data := false
timer := time.NewTimer(interval)
for {
select {
case item = <-input:
data = true
timer.Reset(interval)
case <-timer.C:
if data {
cb(item)
}
}
}
}
|
package dashboard
import (
"fmt"
"net/http"
"strings"
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/balance"
"github.com/iotaledger/wasp/packages/coretypes"
"github.com/iotaledger/wasp/packages/kv/codec"
"github.com/iotaledger/wasp/packages/vm/core/accounts"
"github.com/iotaledger/wasp/plugins/chains"
"github.com/labstack/echo/v4"
)
func initChainAccount(e *echo.Echo, r renderer) {
route := e.GET("/chain/:chainid/account/:agentid", handleChainAccount)
route.Name = "chainAccount"
r[route.Path] = makeTemplate(e, tplChainAccount, tplWs)
}
func handleChainAccount(c echo.Context) error {
chainID, err := coretypes.NewChainIDFromBase58(c.Param("chainid"))
if err != nil {
return err
}
agentID, err := coretypes.NewAgentIDFromString(strings.Replace(c.Param("agentid"), ":", "/", 1))
if err != nil {
return err
}
result := &ChainAccountTemplateParams{
BaseTemplateParams: BaseParams(c, chainBreadcrumb(c.Echo(), chainID), Tab{
Path: c.Path(),
Title: fmt.Sprintf("Account %.8s…", agentID),
Href: "#",
}),
ChainID: chainID,
AgentID: agentID,
}
chain := chains.GetChain(chainID)
if chain != nil {
bal, err := callView(chain, accounts.Interface.Hname(), accounts.FuncBalance, codec.MakeDict(map[string]interface{}{
accounts.ParamAgentID: codec.EncodeAgentID(agentID),
}))
if err != nil {
return err
}
result.Balances, err = accounts.DecodeBalances(bal)
if err != nil {
return err
}
}
return c.Render(http.StatusOK, c.Path(), result)
}
type ChainAccountTemplateParams struct {
BaseTemplateParams
ChainID coretypes.ChainID
AgentID coretypes.AgentID
Balances map[balance.Color]int64
}
const tplChainAccount = `
{{define "title"}}On-chain account details{{end}}
{{define "body"}}
{{if .Balances}}
<div class="card fluid">
<h2 class="section">On-chain account</h2>
<dl>
<dt>AgentID</dt><dd><tt>{{.AgentID}}</tt></dd>
</dl>
</div>
<div class="card fluid">
<h3 class="section">Balances</h3>
{{ template "balances" .Balances }}
</div>
{{ template "ws" .ChainID }}
{{else}}
<div class="card fluid error">Not found.</div>
{{end}}
{{end}}
`
|
package handlebars
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestTextNode(t *testing.T) {
n := NewTextNode("blah")
assert.Equal(t, `"blah"`, n.String())
}
func TestTextNodeExecute(t *testing.T) {
ctx := map[string]interface{}{"a": "AAA"}
assert.Equal(t, `a`, NewTextNode("a").Execute(ctx))
}
func TestMustacheNodeString(t *testing.T) {
n := NewMustacheNode("var", true)
assert.Equal(t, `{{var}}`, n.String())
}
func TestMustacheNodeExecute(t *testing.T) {
ctx := map[string]interface{}{"a": "aaa", "b": "bbb"}
assert.Equal(t, `aaa`, NewMustacheNode("a", true).Execute(ctx))
assert.Equal(t, `bbb`, NewMustacheNode("b", true).Execute(ctx))
assert.Equal(t, ``, NewMustacheNode("c", true).Execute(ctx))
}
func TestMustacheNodeExecuteDot(t *testing.T) {
node := NewMustacheNode(".", true)
assert.Equal(t, `dot`, node.Execute("dot"))
assert.Equal(t, `1`, node.Execute(1))
assert.Equal(t, `true`, node.Execute(true))
assert.Equal(t, ``, node.Execute(false))
}
func TestMustacheNodeExecuteNestedPath(t *testing.T) {
ctx := map[string]interface{}{"c": map[string]interface{}{"d": "EEE"}}
assert.Equal(t, `EEE`, NewMustacheNode("c.d", true).Execute(ctx))
assert.Equal(t, ``, NewMustacheNode("c.x", true).Execute(ctx))
//assert.Equal(t, ``, NewMustacheNode("c.d.e", true).Execute(ctx)) // invalid map type
//assert.Equal(t, ``, NewMustacheNode("c", true).Execute(ctx)) // invalid value type
}
func TestBlockNode(t *testing.T) {
n := NewBlockNode("if aaa")
n.Append(NewTextNode("bbb"))
n.Append(NewTextNode("ccc"))
assert.Equal(t, `{{#if aaa ["bbb", "ccc"]}}`, n.String())
}
func TestBlockNodeExecute(t *testing.T) {
n := NewBlockNode("")
n.Append(NewTextNode("aaa "))
n.Append(NewMustacheNode("x", true))
n.Append(NewTextNode(" bbb "))
n.Append(NewMustacheNode("y", true))
n.Append(NewTextNode(" ccc"))
ctx := map[string]interface{}{"x": "XXX", "y": "YYY"}
assert.Equal(t, `aaa XXX bbb YYY ccc`, n.Execute(ctx))
}
|
package db
import (
"github.com/boltdb/bolt"
"strconv"
)
const mapping = "mapping"
const tracks = "tracks"
type Persistent struct {
*bolt.DB
}
func NewPersistent(db *bolt.DB) *Persistent {
db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucket([]byte(mapping))
if err != nil {
return err
}
_, err = tx.CreateBucket([]byte(tracks))
if err != nil {
return err
}
return nil
})
return &Persistent{
DB: db,
}
}
func (p *Persistent) Save (key, target string) {
p.DB.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(mapping))
return b.Put([]byte(key), []byte(target))
})
}
func (p *Persistent) Find(key string) (string, bool) {
var val string
p.DB.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(mapping))
val = string(b.Get([]byte(key)))
return nil
})
return val, val != ""
}
func (p *Persistent) Track(key string) {
p.DB.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(tracks))
val := b.Get([]byte(key))
num, err := strconv.Atoi(string(val))
if err != nil {
return err
}
b.Put([]byte(key), []byte(strconv.Itoa(num+1)))
return nil
})
}
func (p *Persistent) Visits(key string) int64 {
var count int64
p.DB.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(tracks))
val := b.Get([]byte(key))
num, err := strconv.Atoi(string(val))
if err != nil {
return err
}
count = int64(num)
return nil
})
return count
}
|
package bean
import (
"encoding/base64"
"log"
"time"
"github.com/astaxie/beego/orm"
"github.com/golang/protobuf/proto"
pkgProto "crazyant.com/deadfat/pbd/go"
)
// ---------------------------------------------------------------------------
const (
NOTIFY_PAYMENT = uint32(1)
)
type Notify struct {
ID int64 `orm:"column(id);auto;pk"` // 主键
Uid uint32 `orm:"column(uid);index"` // 角色编号
Happen time.Time `orm:"column(happen)"` // 发生时间
Category uint32 `orm:"column(category)"` // 类别
Raw string `orm:"column(raw);size(1024)"` // 内容
Removed bool `orm:"column(removed)"` // 是否标记删除
dirty bool `orm:"-"` // 是否脏数据
}
func (self *Notify) TableName() string {
return "notify"
}
func (self *Notify) SetDirty() {
self.dirty = true
}
func (self *Notify) ResetDirty() bool {
if !self.dirty {
return false
}
self.dirty = false
return true
}
func (self *Notify) SetRaw(payload proto.Message) error {
raw, err := proto.Marshal(payload)
if err != nil {
return err
}
self.Raw = base64.StdEncoding.EncodeToString(raw)
return nil
}
func (self *Notify) GetRaw(payload proto.Message) error {
raw, err := base64.StdEncoding.DecodeString(self.Raw)
if err != nil {
return err
}
return proto.Unmarshal(raw, payload)
}
// ---------------------------------------------------------------------------
func LoadNotifies(uid uint32) (error, []*Notify) {
o := orm.NewOrm()
var beans []*Notify
qs := o.QueryTable("notify")
_, e := qs.Filter("uid", uid).Filter("removed", false).All(&beans)
if e != nil {
return e, nil
}
return nil, beans
}
func UpdateNotify(bean *Notify) error {
o := orm.NewOrm()
_, e := o.Update(bean)
if e != nil {
return e
}
return nil
}
func AddAndroidPaymentNotify(orderid string, uid uint32, isRemovedAD bool, resources map[int32]int32, money *pkgProto.Money) (*Notify, error) {
notify := &Notify{
Uid: uid,
Happen: time.Now(),
Category: NOTIFY_PAYMENT,
Removed: false,
}
payload := &pkgProto.PaymentNotify{
Id: proto.String(orderid),
RemoveAd: proto.Bool(isRemovedAD),
Money: money,
}
for id, count := range resources {
payload.Resources = append(payload.Resources, &pkgProto.Resource{
Id: proto.Int32(id),
Value: proto.Int32(count),
})
}
notify.SetRaw(payload)
o := orm.NewOrm()
if _, err := o.Insert(notify); err != nil {
log.Printf("新增角色%d通知记录时出错: %v", uid, err)
return nil, err
}
return notify, nil
}
|
package stat
import (
"net/http"
"time"
goKitLog "github.com/go-kit/kit/log"
lib "github.com/syedomair/plan-api/lib"
)
type StatEnv struct {
Logger goKitLog.Logger
StatRepo StatRepositoryInterface
Common lib.CommonService
}
func (env *StatEnv) GetTotalUserCountLast30Days(w http.ResponseWriter, r *http.Request) {
start := time.Now()
env.Logger.Log("METHOD", "GetTotalUserCountLast30Days", "SPOT", "method start", "time_start", start)
_, err := env.Common.GetUserClientFromToken(r)
if err != nil {
env.Common.ErrorResponseHelper(w, "5001", err.Error(), http.StatusBadRequest)
return
}
userCount, err := env.StatRepo.GetTotalUserCountLast30Days()
if err != nil {
env.Common.ErrorResponseHelper(w, "5002", lib.ERROR_UNEXPECTED, http.StatusInternalServerError)
return
}
responseUserCount := map[string]string{"user_total_count": userCount}
env.Logger.Log("METHOD", "GetTotalUserCountLast30Days", "SPOT", "method end", "time_spent", time.Since(start))
env.Common.SuccessResponseHelper(w, responseUserCount, http.StatusOK)
}
func (env *StatEnv) GetTotalUserCount(w http.ResponseWriter, r *http.Request) {
start := time.Now()
env.Logger.Log("METHOD", "GetTotalUserCount", "SPOT", "method start", "time_start", start)
_, err := env.Common.GetUserClientFromToken(r)
if err != nil {
env.Common.ErrorResponseHelper(w, "5003", err.Error(), http.StatusBadRequest)
return
}
userCount, err := env.StatRepo.GetTotalUserCount()
if err != nil {
env.Common.ErrorResponseHelper(w, "5004", lib.ERROR_UNEXPECTED, http.StatusInternalServerError)
return
}
responseUserCount := map[string]string{"user_total_count": userCount}
env.Logger.Log("METHOD", "GetTotalUserCount", "SPOT", "method end", "time_spent", time.Since(start))
env.Common.SuccessResponseHelper(w, responseUserCount, http.StatusOK)
}
func (env *StatEnv) GetUserRegData(w http.ResponseWriter, r *http.Request) {
start := time.Now()
env.Logger.Log("METHOD", "GetUserRegData", "SPOT", "method start", "time_start", start)
_, err := env.Common.GetUserClientFromToken(r)
if err != nil {
env.Common.ErrorResponseHelper(w, "5005", err.Error(), http.StatusBadRequest)
return
}
userRegData, err := env.StatRepo.GetUserRegData()
if err != nil {
env.Common.ErrorResponseHelper(w, "5006", lib.ERROR_UNEXPECTED, http.StatusInternalServerError)
return
}
env.Logger.Log("METHOD", "GetUserRegData", "SPOT", "method end", "time_spent", time.Since(start))
env.Common.SuccessResponseHelper(w, userRegData, http.StatusOK)
}
func (env *StatEnv) GetPlanData(w http.ResponseWriter, r *http.Request) {
start := time.Now()
env.Logger.Log("METHOD", "GetPlanData", "SPOT", "method start", "time_start", start)
_, err := env.Common.GetUserClientFromToken(r)
if err != nil {
env.Common.ErrorResponseHelper(w, "5007", err.Error(), http.StatusBadRequest)
return
}
userCount, err := env.StatRepo.GetPlanData()
if err != nil {
env.Common.ErrorResponseHelper(w, "5008", lib.ERROR_UNEXPECTED, http.StatusInternalServerError)
return
}
responseUserCount := map[string]string{"plan_total_count": userCount}
env.Logger.Log("METHOD", "GetPlanData", "SPOT", "method end", "time_spent", time.Since(start))
env.Common.SuccessResponseHelper(w, responseUserCount, http.StatusOK)
}
|
package utils
func IfThenElse(cond bool, a interface{}, b interface{}) interface{} {
if cond {
return a
} else {
return b
}
}
|
package main
import "fmt"
func main() {
var numOfRunes, minFriendship int
fmt.Scanf("%d %d", &numOfRunes, &minFriendship)
runes := make(map[string]int)
for i := 0; i < numOfRunes; i++ {
var s string
var n int
fmt.Scanf("%s %d", &s, &n)
runes[s] = n
}
var numOfRunesUsed int
fmt.Scanf("%d", &numOfRunesUsed)
total := 0
for i := 0; i < numOfRunesUsed; i++ {
var s string
fmt.Scanf("%s", &s)
total += runes[s]
}
fmt.Println(total)
if total == minFriendship {
fmt.Println("You shall pass!")
return
}
fmt.Println("My precioooous")
}
|
/*
Copyright © 2022 SUSE LLC
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 port
import (
"fmt"
"net"
"github.com/rancher-sandbox/rancher-desktop-agent/pkg/types"
"github.com/rancher-sandbox/rancher-desktop/src/go/privileged-service/pkg/command"
)
const netsh = "netsh"
func execProxy(portMapping types.PortMapping) error {
if portMapping.Remove {
return deleteProxy(portMapping)
}
return addProxy(portMapping)
}
func addProxy(portMapping types.PortMapping) error {
for _, v := range portMapping.Ports {
for _, addr := range v {
wslIP, err := getConnectAddr(addr.HostIP, portMapping.ConnectAddrs)
if err != nil {
return err
}
args, err := portProxyAddArgs(addr.HostPort, addr.HostIP, wslIP)
if err != nil {
return err
}
err = command.Exec(netsh, args)
if err != nil {
return err
}
}
}
return nil
}
func deleteProxy(portMapping types.PortMapping) error {
for _, v := range portMapping.Ports {
for _, addr := range v {
args, err := portProxyDeleteArgs(addr.HostPort, addr.HostIP)
if err != nil {
return err
}
err = command.Exec(netsh, args)
if err != nil {
return err
}
}
}
return nil
}
// getConnectedAddr selects an IP address from connectAddrs that is the same
// type (IPv4 or IPv6) as listenIP.
func getConnectAddr(listenIP string, connectAddrs []types.ConnectAddrs) (string, error) {
isIPv4, err := isIPv4(listenIP)
if err != nil {
return "", err
}
for _, addr := range connectAddrs {
wslIP, _, err := net.ParseCIDR(addr.Addr)
if err != nil {
return "", err
}
switch isIPv4 {
case true:
if wslIP.To4() != nil {
return wslIP.String(), nil
}
case false:
if wslIP.To4() == nil {
return wslIP.String(), nil
}
}
}
return "", fmt.Errorf("failed to find connect address: %v for listen IP: %s", connectAddrs, listenIP)
}
func isIPv4(addr string) (bool, error) {
ip := net.ParseIP(addr)
if ip == nil {
return false, fmt.Errorf("invalid IP address: %s", addr)
}
if ip.To4() != nil {
return true, nil
}
return false, nil
}
func portProxyDeleteArgs(listenPort, listenAddr string) ([]string, error) {
var protoMapping string
isIPv4, err := isIPv4(listenAddr)
if err != nil {
return nil, err
}
if isIPv4 {
protoMapping = "v4tov4"
} else {
protoMapping = "v6tov6"
}
return []string{
"interface",
"portproxy",
"delete",
protoMapping,
fmt.Sprintf("listenport=%s", listenPort),
fmt.Sprintf("listenaddress=%s", listenAddr),
}, nil
}
func portProxyAddArgs(listenPort, listenAddr, connectAddr string) ([]string, error) {
var protoMapping string
isIPv4, err := isIPv4(listenAddr)
if err != nil {
return nil, err
}
if isIPv4 {
protoMapping = "v4tov4"
} else {
protoMapping = "v6tov6"
}
return []string{
"interface",
"portproxy",
"add",
protoMapping,
fmt.Sprintf("listenport=%s", listenPort),
fmt.Sprintf("listenaddress=%s", listenAddr),
fmt.Sprintf("connectport=%s", listenPort),
fmt.Sprintf("connectaddress=%s", connectAddr),
}, nil
}
|
/*
@Time : 2019/5/11 14:40
@Author : yanKoo
@File : mian.go
@Software: GoLand
@Description:
*/
package main
import (
"cache"
"encoding/json"
"log"
"time"
)
type interphoneMsg struct {
Uid string `json:"uid"`
MsgType string `json:"m_type"`
Md5 string `json:"md5"`
GId string `json:"grp_id"`
FilePath string `json:"file_path"`
Timestamp string `json:"timestamp"`
}
func main() {
for i := 0; i < 100; i++ {
//go func(i int) {
m := &interphoneMsg{
Uid: "8",//strconv.FormatInt(int64(i),10),
MsgType: "ptt",
Md5: "555555555555",
GId: "229",
FilePath: "123456789",
Timestamp: time.Now().String(),
}
v, e := json.Marshal(m)
log.Printf("%s", v)
if e != nil {
}
_, err := cache.GetRedisClient().Do("lpush", "janusImUrlLis", v)
if err != nil {
log.Printf("push redis data with error: %+v", err)
return
}
//}(i)
}
//select {}
}
|
package game
// 用户相关
const (
NoPermission int32 = iota + 100
ReqLogin // 登录请求
ResLogin // 响应登录结果
ReqReg // 用户注册
ResReg // 响应注册结果
ReqReset // 重置密码
ResReset // 响应重置密码结果
ReqBind // 账号绑定
ResBind // 响应绑定结果
ReqUserInfo // 获取用户信息
ResUserInfo // 响应用户信息
ReqCode // 请求手机验证码
ResCode // 返回验证码发送结果
ReqLoginByToken // 通过token登录
ResLoginByToken
ReqNotice // 请求公告通知信息
ResNotice
ReqRollText // 获取滚动字幕内容
ResRollText
ReqLoginByWeChatCode // 微信登录
ResLoginByWeChatCode
ReqDefaultVoice // 请求发送默认语音
BroadcastDefaultVoice
ReqShareText // 请求分享的内容
ResShareText
)
// 房间相关
const (
// 创建房间
ReqCreateRoom int32 = iota + 201
ResCreateRoom
// 房间列表
ReqRoomList
ResRoomList
// 房间信息
ReqRoom
ResRoom
// 进入房间
ReqJoinRoom
ResJoinRoom // 此处返回当前房间的所有玩家
// 广播进入房间
BroadcastJoinRoom
// 广播坐下
BroadcastSitRoom
// 坐下
ReqSit
ResSit
// 离开房间
ReqLeaveRoom
ResLeaveRoom
// 解散房间
ReqDeleteRoom
ResDeleteRoom
)
// 游戏相关
const (
// 开始游戏
ReqGameStart int32 = iota + 301
ResGameStart
ReqSetTimes // 抢庄
BroadcastTimes
BroadcastBanker // 广播谁是庄家
ReqSetScore // 下注
BroadcastScore // 广播下注的大小
BroadcastShowCard // 广播看牌,下注完毕,可以看自己的牌
BroadcastCompareCard // 比牌,返回所有人牌型及大小输赢积分,前端展示比牌结果
BroadcastGameOver // 游戏结束
ReqGameResult // 请求游戏战绩
ResGameResult // 返回游戏战绩
ReqGamePlayers // 请求游戏玩家
ResGamePlayers
BroadcastAllScore // 推注
)
// 茶楼相关
const (
ReqCreateClub = iota + 401 // 创建茶楼
ResCreateClub
ReqClub // 获取指定茶楼信息
ResClub
ReqClubs // 列出加入的茶楼
ResClubs
ReqExitClub // 请求退出茶楼
ResExitClub
ReqDelClub // 解散茶楼
BroadcastDelClub
ReqEditClub // 修改茶楼名称和公告
BroadcastEditClub
ReqJoinClub // 加入茶楼
BroadcastJoinClub
ReqClubUsers // users会员列表
ResClubUsers
ReqEditClubUser // 编辑会员状态:action 设为管理(admin) 取消管理(-admin) 冻结(disable) 取消冻结(-disable) 设为代付(pay) 取消代付(-pay) 审核通过用户(add) 移除用户(-add)
ResEditClubUser
ReqCreateClubRoom // 创建茶楼房间
ResCreateClubRoom
ReqClubRooms // 获取指定俱乐部所有房间
ResClubRooms
ReqClubRoomUsers // 请求茶楼中房间的所有玩家座位信息
ResClubRoomUsers
ReqEditClubRoom // 更改房间信息
ResEditClubRoom
)
|
package monitoring
import (
"Agamoto/linenotify"
"log"
"net/http"
"strconv"
"time"
)
//
// type CCUType struct {
// AllUser string
// IOSCCU string
// AndriodCCU string
// }
var allCCU = 500
var sendTimeStamp = time.Now()
var countRecvUpdate int64 = 0
var lastCount int64 = 1
var lastCCU = 0
var timeDiff float64 = 600
func RecvUpdateCCU(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
var err error
allCCU, err = strconv.Atoi(r.FormValue("allccu"))
if err != nil {
log.Print("Can't read data.. RecvUpdateCCU ", err)
}
log.Print("allCCU ", allCCU)
if countRecvUpdate > 500 {
countRecvUpdate = 0
}else{
countRecvUpdate ++
}
}
func CheckServerAlive(){
for {
var locationTime, _ = time.LoadLocation("Asia/Bangkok")
timeNow := time.Now().In(locationTime)
dayOfWeek := timeNow.Weekday()
if int(dayOfWeek) != 3 && (timeNow.Hour() <= 9 || timeNow.Hour() >= 13) { // Check Maintenance day
if lastCount == countRecvUpdate {
if timeDiff >= 600 { // delay time send to Line
sendTimeStamp = time.Now()
linenotify.SendLineNotifyMessage("ผิดปกติ >> ไม่ได้รับ CCU จาก Server! : " + sendTimeStamp.Format("2006-01-02 15:04:05") ,"2","145")
}
}
if allCCU < lastCCU/2 {
if timeDiff >= 600 { // delay time send to Line
sendTimeStamp = time.Now()
linenotify.SendLineNotifyMessage("ผพบ CCU ลดลงผิดปกติ : CCU เหลือ " + strconv.Itoa(allCCU) + sendTimeStamp.Format("2006-01-02 15:04:05") ,"2","149")
}
}
timeDiff = timeNow.Sub(sendTimeStamp).Seconds()
lastCCU = allCCU
lastCount = countRecvUpdate
delay := 15 * time.Second
time.Sleep(delay)
}
}
}
|
package main
import (
"github.com/profzone/eden-framework/pkg/application"
"github.com/profzone/eden-framework/pkg/context"
"github.com/sirupsen/logrus"
"longhorn/upload-packager/internal/global"
"longhorn/upload-packager/internal/routers"
)
func main() {
app := application.NewApplication(runner, &global.Config)
go app.Start()
app.WaitStop(func(ctx *context.WaitStopContext) error {
return nil
})
}
func runner(app *application.Application) error {
logrus.SetLevel(global.Config.LogLevel)
global.Config.Raft.Init()
go global.Config.GRPCServer.Serve(routers.RootRouter)
return global.Config.HTTPServer.Serve(routers.RootRouter)
}
|
package mqtt
import (
"context"
"encoding/json"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/pkg/errors"
uuid "github.com/satori/go.uuid"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber-schemas/build/go/protos/records"
"github.com/batchcorp/plumber/validate"
)
func (m *MQTT) Read(ctx context.Context, readOpts *opts.ReadOptions, resultsChan chan *records.ReadRecord, errorChan chan *records.ErrorRecord) error {
if err := validateReadOptions(readOpts); err != nil {
return errors.Wrap(err, "unable to validate read options")
}
var count int64
doneCh := make(chan struct{}, 1)
var readFunc = func(client mqtt.Client, msg mqtt.Message) {
count++
serializedMsg, err := json.Marshal(msg)
if err != nil {
errorChan <- &records.ErrorRecord{
OccurredAtUnixTsUtc: time.Now().UTC().Unix(),
Error: errors.Wrap(err, "unable to serialize message into JSON").Error(),
}
}
t := time.Now().UTC().Unix()
resultsChan <- &records.ReadRecord{
MessageId: uuid.NewV4().String(),
Num: count,
ReceivedAtUnixTsUtc: t,
Payload: msg.Payload(),
XRaw: serializedMsg,
Record: &records.ReadRecord_Mqtt{
Mqtt: &records.MQTT{
Id: uint32(msg.MessageID()),
Topic: msg.Topic(),
Value: msg.Payload(),
Duplicate: msg.Duplicate(),
Retained: msg.Retained(),
//Qos: msg.Qos(), TODO: how to convert []byte to uint32
Timestamp: t,
},
},
}
if !readOpts.Continuous {
doneCh <- struct{}{}
}
}
m.log.Info("Listening for messages...")
token := m.client.Subscribe(readOpts.Mqtt.Args.Topic, byte(m.connArgs.QosLevel), readFunc)
if err := token.Error(); err != nil {
return err
}
select {
case <-doneCh:
return nil
case <-ctx.Done():
return nil
}
return nil
}
func validateReadOptions(readOpts *opts.ReadOptions) error {
if readOpts == nil {
return validate.ErrMissingReadOptions
}
if readOpts.Mqtt == nil {
return validate.ErrEmptyBackendGroup
}
args := readOpts.Mqtt.Args
if args == nil {
return validate.ErrEmptyBackendArgs
}
if args.Topic == "" {
return ErrEmptyTopic
}
return nil
}
|
package models
import (
"database/sql"
"encoding/json"
"web/ant/kernel"
"web/ant/kernel/databases"
)
/**
* 模型查询结构
*
* param results []map[string]interface 数据结果集
*/
type ModelQuery struct {
results []map[string]interface{}
}
/**
* 返回模型构建对象
*
* param string tableName 数据表名
* param string dbName 数据库名
*/
func (this ModelQuery) Table(tableName string, dbName string) ModelBuild {
// 设置查询表
var modelBuild = ModelBuild{"", "", "*", "", "", "", "", ""}
modelBuild.TableName = tableName
modelBuild.DbName = dbName
return modelBuild
}
/**
* 查询数据
*
* param ModelBuild modelBuild sql构建对象
*/
func (this ModelQuery) Select(modelBuild ModelBuild) ModelQuery {
// 查询
results, err := databases.Db.Query(modelBuild.BuildConditions())
kernel.CheckErr(err)
defer results.Close()
columns, _ := results.Columns()
values := make([]sql.RawBytes, len(columns))
scanArgs := make([]interface{}, len(values))
for i := range values {
scanArgs[i] = &values[i]
}
rows := make(map[string]interface{})
rowSlice := make([]map[string]interface{}, 0)
for results.Next() {
err = results.Scan(scanArgs...)
for i, col := range values {
if col != nil {
rows[columns[i]] = string(col)
}
}
rowSlice = append(rowSlice[:], rows)
// 清空上次结果
rows = make(map[string]interface{})
}
this.results = rowSlice
return this
}
/**
* 返回Json格式查询结果
*
* return string
*/
func (this ModelQuery) FetchJson() string {
jsonObj, _ := json.Marshal(this.results)
return string(jsonObj)
}
/**
* 返回数据类型查询结果
*
* return []map[string]interface{}
*/
func (this ModelQuery) FetchArray() []map[string]interface{} {
return this.results
}
|
package keeper
import (
"fmt"
"github.com/irisnet/irishub/app/v2/coinswap/internal/types"
sdk "github.com/irisnet/irishub/types"
"github.com/stretchr/testify/require"
"testing"
"time"
)
var (
native = sdk.IrisAtto
)
func TestGetUniId(t *testing.T) {
cases := []struct {
name string
denom1 string
denom2 string
expectResult string
expectPass bool
}{
{"denom1 is native", native, "btc-min", "uni:btc", true},
{"denom2 is native", "btc-min", native, "uni:btc", true},
{"denom1 equals denom2", "btc-min", "btc-min", "uni:btc", false},
{"neither denom is native", "eth-min", "btc-min", "uni:btc", false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
uniId, err := types.GetUniId(tc.denom1, tc.denom2)
if tc.expectPass {
require.Equal(t, tc.expectResult, uniId)
} else {
require.NotNil(t, err)
}
})
}
}
type Data struct {
delta sdk.Int
x sdk.Int
y sdk.Int
fee sdk.Rat
}
type SwapCase struct {
data Data
expect sdk.Int
}
func TestGetInputPrice(t *testing.T) {
var datas = []SwapCase{
{
data: Data{delta: sdk.NewInt(100), x: sdk.NewInt(1000), y: sdk.NewInt(1000), fee: sdk.NewRat(3, 1000)},
expect: sdk.NewInt(90),
},
{
data: Data{delta: sdk.NewInt(200), x: sdk.NewInt(1000), y: sdk.NewInt(1000), fee: sdk.NewRat(3, 1000)},
expect: sdk.NewInt(166),
},
{
data: Data{delta: sdk.NewInt(300), x: sdk.NewInt(1000), y: sdk.NewInt(1000), fee: sdk.NewRat(3, 1000)},
expect: sdk.NewInt(230),
},
{
data: Data{delta: sdk.NewInt(1000), x: sdk.NewInt(1000), y: sdk.NewInt(1000), fee: sdk.NewRat(3, 1000)},
expect: sdk.NewInt(499),
},
{
data: Data{delta: sdk.NewInt(1000), x: sdk.NewInt(1000), y: sdk.NewInt(1000), fee: sdk.ZeroRat()},
expect: sdk.NewInt(500),
},
}
for _, tcase := range datas {
data := tcase.data
actual := getInputPrice(data.delta, data.x, data.y, data.fee)
fmt.Println(fmt.Sprintf("expect:%s,actual:%s", tcase.expect.String(), actual.String()))
require.Equal(t, tcase.expect, actual)
}
}
func TestGetOutputPrice(t *testing.T) {
var datas = []SwapCase{
{
data: Data{delta: sdk.NewInt(100), x: sdk.NewInt(1000), y: sdk.NewInt(1000), fee: sdk.NewRat(3, 1000)},
expect: sdk.NewInt(112),
},
{
data: Data{delta: sdk.NewInt(200), x: sdk.NewInt(1000), y: sdk.NewInt(1000), fee: sdk.NewRat(3, 1000)},
expect: sdk.NewInt(251),
},
{
data: Data{delta: sdk.NewInt(300), x: sdk.NewInt(1000), y: sdk.NewInt(1000), fee: sdk.NewRat(3, 1000)},
expect: sdk.NewInt(430),
},
{
data: Data{delta: sdk.NewInt(300), x: sdk.NewInt(1000), y: sdk.NewInt(1000), fee: sdk.ZeroRat()},
expect: sdk.NewInt(429),
},
}
for _, tcase := range datas {
data := tcase.data
actual := getOutputPrice(data.delta, data.x, data.y, data.fee)
fmt.Println(fmt.Sprintf("expect:%s,actual:%s", tcase.expect.String(), actual.String()))
require.Equal(t, tcase.expect, actual)
}
}
func TestKeeperSwap(t *testing.T) {
ctx, keeper, sender, reservePoolAddr, err, reservePoolBalances, senderBlances := createReservePool(t)
outputCoin := sdk.NewCoin("btc-min", sdk.NewInt(100))
inputCoin := sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(1000))
input := types.Input{
Address: sender,
Coin: inputCoin,
}
output := types.Output{
Coin: outputCoin,
}
deadline1 := time.Now().Add(1 * time.Minute)
msg1 := types.NewMsgSwapOrder(input, output, deadline1.Unix(), true)
// first swap
_, err = keeper.HandleSwap(ctx, msg1)
require.Nil(t, err)
reservePoolBalances = keeper.ak.GetAccount(ctx, reservePoolAddr).GetCoins()
require.Equal(t, "900btc-min,1112iris-atto,1000uni:btc-min", reservePoolBalances.String())
senderBlances = keeper.ak.GetAccount(ctx, sender).GetCoins()
require.Equal(t, "99999100btc-min,99998888iris-atto,1000uni:btc-min", senderBlances.String())
// second swap
_, err = keeper.HandleSwap(ctx, msg1)
require.Nil(t, err)
reservePoolBalances = keeper.ak.GetAccount(ctx, reservePoolAddr).GetCoins()
require.Equal(t, "800btc-min,1252iris-atto,1000uni:btc-min", reservePoolBalances.String())
senderBlances = keeper.ak.GetAccount(ctx, sender).GetCoins()
require.Equal(t, "99999200btc-min,99998748iris-atto,1000uni:btc-min", senderBlances.String())
// third swap
_, err = keeper.HandleSwap(ctx, msg1)
require.Nil(t, err)
reservePoolBalances = keeper.ak.GetAccount(ctx, reservePoolAddr).GetCoins()
require.Equal(t, "700btc-min,1432iris-atto,1000uni:btc-min", reservePoolBalances.String())
}
func createReservePool(t *testing.T) (sdk.Context, Keeper, sdk.AccAddress, sdk.AccAddress, sdk.Error, sdk.Coins, sdk.Coins) {
ctx, keeper, accs := createTestInput(t, sdk.NewInt(100000000), 1)
sender := accs[0].GetAddress()
denom1 := "btc-min"
denom2 := sdk.IrisAtto
uniId, _ := types.GetUniId(denom1, denom2)
reservePoolAddr := getReservePoolAddr(uniId)
btcAmt, _ := sdk.NewIntFromString("1000")
depositCoin := sdk.NewCoin("btc-min", btcAmt)
irisAmt, _ := sdk.NewIntFromString("1000")
minReward := sdk.NewInt(1)
deadline := time.Now().Add(1 * time.Minute)
msg := types.NewMsgAddLiquidity(depositCoin, irisAmt, minReward, deadline.Unix(), sender)
_, err := keeper.HandleAddLiquidity(ctx, msg)
//assert
require.Nil(t, err)
reservePoolBalances := keeper.ak.GetAccount(ctx, reservePoolAddr).GetCoins()
require.Equal(t, "1000btc-min,1000iris-atto,1000uni:btc-min", reservePoolBalances.String())
senderBlances := keeper.ak.GetAccount(ctx, sender).GetCoins()
require.Equal(t, "99999000btc-min,99999000iris-atto,1000uni:btc-min", senderBlances.String())
return ctx, keeper, sender, reservePoolAddr, err, reservePoolBalances, senderBlances
}
func TestTradeInputForExactOutput(t *testing.T) {
ctx, keeper, sender, poolAddr, _, poolBalances, senderBlances := createReservePool(t)
outputCoin := sdk.NewCoin("btc-min", sdk.NewInt(100))
inputCoin := sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(100000))
input := types.Input{
Address: sender,
Coin: inputCoin,
}
output := types.Output{
Coin: outputCoin,
}
initSupplyOutput := poolBalances.AmountOf(outputCoin.Denom)
maxCnt := int(initSupplyOutput.Div(outputCoin.Amount).Int64())
for i := 1; i < 100; i++ {
amt, err := keeper.tradeInputForExactOutput(ctx, input, output)
if i == maxCnt {
require.NotNil(t, err)
break
}
ifNil(t, err)
bought := sdk.NewCoins(outputCoin)
sold := sdk.NewCoins(sdk.NewCoin(sdk.IrisAtto, amt))
pb := poolBalances.Add(sold).Sub(bought)
sb := senderBlances.Add(bought).Sub(sold)
assertResult(t, keeper, ctx, poolAddr, sender, pb, sb)
poolBalances = pb
senderBlances = sb
}
}
func TestTradeExactInputForOutput(t *testing.T) {
ctx, keeper, sender, poolAddr, _, poolBalances, senderBlances := createReservePool(t)
outputCoin := sdk.NewCoin("btc-min", sdk.NewInt(0))
inputCoin := sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(100))
input := types.Input{
Address: sender,
Coin: inputCoin,
}
output := types.Output{
Coin: outputCoin,
}
for i := 1; i < 1000; i++ {
amt, err := keeper.tradeExactInputForOutput(ctx, input, output)
ifNil(t, err)
sold := sdk.NewCoins(inputCoin)
bought := sdk.NewCoins(sdk.NewCoin("btc-min", amt))
pb := poolBalances.Add(sold).Sub(bought)
sb := senderBlances.Add(bought).Sub(sold)
assertResult(t, keeper, ctx, poolAddr, sender, pb, sb)
poolBalances = pb
senderBlances = sb
}
}
func assertResult(t *testing.T, keeper Keeper, ctx sdk.Context, reservePoolAddr, sender sdk.AccAddress, expectPoolBalance, expectSenderBalance sdk.Coins) {
reservePoolBalances := keeper.ak.GetAccount(ctx, reservePoolAddr).GetCoins()
require.Equal(t, expectPoolBalance.String(), reservePoolBalances.String())
senderBlances := keeper.ak.GetAccount(ctx, sender).GetCoins()
require.Equal(t, expectSenderBalance.String(), senderBlances.String())
}
func ifNil(t *testing.T, err sdk.Error) {
msg := ""
if err != nil {
msg = err.Error()
}
require.Nil(t, err, msg)
}
|
package util
import (
eventv1 "github.com/redhat-cop/events-notifier/pkg/apis/event/v1"
notifyv1 "github.com/redhat-cop/events-notifier/pkg/apis/notify/v1"
)
type SharedResources struct {
Subscriptions *[]eventv1.EventSubscription
Notifiers *[]notifyv1.Notifier
}
func NewSharedResources() SharedResources {
return SharedResources{
Subscriptions: &[]eventv1.EventSubscription{},
Notifiers: &[]notifyv1.Notifier{},
}
}
//
// Helper functions to check and remove string from a slice of strings.
//
func ContainsString(slice []string, s string) bool {
for _, item := range slice {
if item == s {
return true
}
}
return false
}
func RemoveString(slice []string, s string) (result []string) {
for _, item := range slice {
if item == s {
continue
}
result = append(result, item)
}
return
}
|
// Starting with the code below, pull values off the channel using a select statement
// package main
//
// import (
// "fmt"
// )
//
// func main() {
// q := make(chan int)
// c := gen(q)
//
// receive(c, q)
//
// fmt.Println("about to exit")
// }
//
// func gen(q <-chan int) <-chan int {
// c := make(chan int)
//
// for i := 0; i < 100; i++ {
// c <- i
// }
//
// return c
// }
package main
import (
"fmt"
)
func main() {
q := make(chan int)
c := gen(q)
receive(c, q)
fmt.Println("about to exit")
}
func gen(q chan<- int) <-chan int {
c := make(chan int)
go func() {
for i := 0; i < 100; i++ {
c <- i
}
close(c)
//q <- 1
close(q)
// If q is not closed or a value loaded into it the receive() infinite
// loop will go on forever because <-c will continue to pass value 0 as it is closed
}()
return c
}
func receive(c, q <-chan int) {
for {
select {
case v := <-c:
fmt.Println("From channel c", v)
case v := <-q:
fmt.Println("Quitting", v)
return
}
}
}
|
package sample_data
import (
"math/rand"
"time"
"github.com/google/uuid"
)
// by default random will use fix seed to create then some of random value will be remain the same
// we can fix it by tell random to use diffenrent seed to run
// by using below code
func init() {
rand.Seed(time.Now().UnixNano())
}
func randomStringFromSet(a ...string) string {
n := len(a)
if n == 0 {
return "UNKNOWN"
}
return a[rand.Intn(n)]
}
func randomInt(min int, max int) int {
return min + rand.Intn(max-min+1)
}
func randomFloat64(min float64, max float64) float64 {
return min + rand.Float64()*(max-min)
}
func randomFloat32(min, max float32) float32 {
return min + rand.Float32()*(max-min)
}
func randomID() string {
return uuid.New().String()
}
func randomLaptopBrand() string {
return randomStringFromSet("Apple", "Dell", "HP", "IBM")
}
func randomLaptopModel() string {
brand := randomLaptopBrand()
switch brand {
case "Apple":
return randomStringFromSet("Macbook Pro", "Macbook Air", "Macbook")
case "Dell":
return randomStringFromSet("XPS", "Latitude", "Precision 3560")
case "HP":
return randomStringFromSet("ProBook 635 Aero G7", "Pavilion", "Spectre x360")
default:
return "UNKNOWN"
}
}
|
/*
Description
The Lab Cup Table Tennis Competition is going to take place soon among laboratories in PKU. Students from the AI Lab are all extreme enthusiasts in table tennis and hold strong will to represent the lab in the competition. Limited by the quota, however, only one of them can be selected to play in the competition.
To make the selection fair, they agreed on a single round robin tournament, in which every pair of students played a match decided by best of 5 games. The one winning the most matches would become representative of the lab. Now Ava, head of the lab, has in hand a form containing the scores of all matches. Who should she decide on for the competition?
Input
The input contains exactly one test case. The test case starts with a line containing n (2 ≤ n ≤ 100), the number of students in the lab. Then follows an n × n matrix A. Each element in the matrix will be one of 0, 1, 2 and 3. The element at row i and column j, aij, is the number of games won by the ith student in his/her match with the jth student. Exactly one of aij and aji (i ≠ j) is 3 and the other one will be less than 3. All diagonal elements of the matrix are 0’s.
Output
Output the number of the student who won the most matches. In the case of a tie, choose the one numbered the smallest.
Sample Input
4
0 0 3 2
3 0 3 1
2 2 0 2
3 3 3 0
Sample Output
4
Source
PKU Local 2007 (POJ Monthly--2007.04.28), ideas from ava, text and test cases by frkstyc
*/
package main
func main() {
assert(student([][]int{
{0, 0, 3, 2},
{3, 0, 3, 1},
{2, 2, 0, 2},
{3, 3, 3, 0},
}) == 4)
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func student(a [][]int) int {
n := len(a)
if n == 0 {
return 0
}
p := make([]int, n)
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
if a[i][j] == 3 {
p[i]++
}
}
}
r := 0
m := p[0]
for i := 1; i < n; i++ {
if m < p[i] {
r, m = i, p[i]
}
}
return r + 1
}
|
package cors
import (
"github.com/gin-gonic/gin"
"net/http"
)
var Cors = func(c *gin.Context) {
method := c.Request.Method
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
c.Header("Access-Control-Allow-Headers", "*")
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
c.Next()
}
|
package models
import (
"fmt"
"github.com/jinzhu/gorm"
"golang-http-server/config"
)
type Employee struct {
gorm.Model
Name string `json:"name"`
Surname string `json:"surname"`
Age int `json:"age"`
}
func (e *Employee) ValidationModel() map[string]string {
validations := make(map[string]string)
if e.Name == "" {
validations["Name"] = "Name cannot empty value"
}
if e.Surname == "" {
validations["Surname"] = "Surname cannot empty value"
}
if e.Age <= 0 {
validations["Age"] = "Age cannot lower than zero"
}
return validations
}
func (e *Employee) CreateEmployee() bool {
validateMessages := e.ValidationModel()
if len(validateMessages) > 0 {
for key, value := range validateMessages {
fmt.Println("Key:"+key, " Value:"+value)
}
}
DB().Create(e)
return true
}
func DB() *gorm.DB {
return config.Init()
}
|
package main
import (
"encoding/json"
"fmt"
)
type Return struct {
Version string `json:"version"`
SessionAttributes SessionAttributes `json:"SessionAttributes"`
Response Response `json:"response"`
ShouldEndSession bool `json:"shouldEndSession"`
}
func NewReturn(s SessionAttributes, r Response, e bool) Return {
return Return{
Version: "1.0",
SessionAttributes: s,
Response: r,
ShouldEndSession: e,
}
}
func PrintReturn(r Return) error {
j, err := json.Marshal(r)
fmt.Print(string(j))
return err
}
type SessionAttributes map[string]interface{}
type Response struct {
OutputSpeech PlainText `json:"outputSpeech"`
Card Card `json:"card"`
Reprompt PlainText `json:"reprompt"`
}
func NewResponse(o string, t string, c string, r string) Response {
return Response{
NewPlainText(o),
NewSimpleCard(t, c),
NewPlainText(r),
}
}
type PlainText struct {
Type string `json:"type"`
Text string `json:"text"`
}
func NewPlainText(t string) PlainText {
return PlainText{
Type: "PlainText",
Text: t,
}
}
type Card struct {
Type string `json:"type"`
Title string `json:"title"`
Content string `json:"content"`
}
func NewSimpleCard(t string, c string) Card {
return Card{
Type: "Simple",
Title: t,
Content: c,
}
}
|
package pie_test
import (
"github.com/elliotchance/pie/v2"
"github.com/stretchr/testify/assert"
"testing"
)
var containsTests = []struct {
ss []float64
contains float64
expected bool
}{
{nil, 1, false},
{[]float64{1, 2, 3}, 1, true},
{[]float64{1, 2, 3}, 2, true},
{[]float64{1, 2, 3}, 3, true},
{[]float64{1, 2, 3}, 4, false},
{[]float64{1, 2, 3}, 5, false},
{[]float64{1, 2, 3}, 6, false},
{[]float64{1, 5, 3}, 5, true},
}
func TestContains(t *testing.T) {
for _, test := range containsTests {
t.Run("", func(t *testing.T) {
assert.Equal(t, test.expected, pie.Contains(test.ss, test.contains))
})
}
}
|
package main
import "fmt"
//make()函数创造切片
/*
1. 要判断一个切片是否是空, 要用 len(s) === 0 来判断, 不应该使用 s == nil 来判断
*/
func main() {
s1 := make([]int, 5, 10)
fmt.Printf("s1-%v len(s1)-%d cap(s1)-%d", s1, len(s1), cap(s1))
}
|
// Copyright 2021 Clivern. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package driver
import (
"github.com/stretchr/testify/mock"
"go.etcd.io/etcd/clientv3"
)
// EtcdMock type
type EtcdMock struct {
mock.Mock
}
// Connect mock
func (e *EtcdMock) Connect() error {
args := e.Called()
return args.Error(0)
}
// IsConnected mock
func (e *EtcdMock) IsConnected() bool {
args := e.Called()
return args.Bool(0)
}
// Put mock
func (e *EtcdMock) Put(key, value string) error {
args := e.Called(key, value)
return args.Error(0)
}
// PutWithLease mock
func (e *EtcdMock) PutWithLease(key, value string, leaseID clientv3.LeaseID) error {
args := e.Called(key, value, leaseID)
return args.Error(0)
}
// Get mock
func (e *EtcdMock) Get(key string) (map[string]string, error) {
args := e.Called(key)
return args.Get(0).(map[string]string), args.Error(1)
}
// Delete mock
func (e *EtcdMock) Delete(key string) (int64, error) {
args := e.Called(key)
return args.Get(0).(int64), args.Error(1)
}
// CreateLease mock
func (e *EtcdMock) CreateLease(seconds int64) (clientv3.LeaseID, error) {
args := e.Called(seconds)
return args.Get(0).(clientv3.LeaseID), args.Error(1)
}
// RenewLease mock
func (e *EtcdMock) RenewLease(leaseID clientv3.LeaseID) error {
args := e.Called(leaseID)
return args.Error(0)
}
// GetKeys mock
func (e *EtcdMock) GetKeys(key string) ([]string, error) {
args := e.Called(key)
return args.Get(0).([]string), args.Error(1)
}
// Exists mock
func (e *EtcdMock) Exists(key string) (bool, error) {
args := e.Called(key)
return args.Bool(0), args.Error(1)
}
// Close mock
func (e *EtcdMock) Close() {
//
}
|
package main
import (
"os"
"testing"
)
var h handler
func TestMain(m *testing.M) {
h, _ = New()
defer h.db.Close()
os.Exit(m.Run())
}
func Test_handler_lookupIDwithEmail(t *testing.T) {
type args struct {
email string
}
tests := []struct {
name string
args args
wantUserID int
wantErr bool
}{
{
name: "",
args: args{
email: "hendry@iki.fi",
},
wantUserID: 86,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotUserID, err := h.lookupID(tt.args.email)
if (err != nil) != tt.wantErr {
t.Errorf("handler.lookupIDwithEmail() error = %v, wantErr %v", err, tt.wantErr)
return
}
if gotUserID != tt.wantUserID {
t.Errorf("handler.lookupIDwithEmail() = %v, want %v", gotUserID, tt.wantUserID)
}
})
}
}
func Test_handler_lookupAPIkey(t *testing.T) {
type args struct {
UserID int
}
tests := []struct {
name string
args args
wantAPIkey string
wantErr bool
}{
{
name: "hendry",
args: args{
UserID: 86,
},
wantAPIkey: "onm6xtyyytjxW438",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotAPIkey, err := h.lookupAPIkey(tt.args.UserID)
if (err != nil) != tt.wantErr {
t.Errorf("handler.lookupAPIkey() error = %v, wantErr %v", err, tt.wantErr)
return
}
if gotAPIkey != tt.wantAPIkey {
t.Errorf("handler.lookupAPIkey() = %v, want %v", gotAPIkey, tt.wantAPIkey)
}
})
}
}
|
package controllers
import (
"github.com/astaxie/beego"
)
type DefaultController struct {
beego.Controller
}
func (c *DefaultController) Get() {
beego.SetLevel(beego.LevelDebug)
// beego.Alert("this is alert")
c.Data["Email"] = "suhanyujie@qq.com"
c.Data["Html1"] = "<div>Hello beego</div>"
c.Data["IsIndex"] = true
c.Data["HasLogin"] = CheckAcount(c.Ctx)
c.TplName = "Index/home.html"
}
|
package main
import (
"github.com/gin-gonic/gin"
"github.com/mp02/accounting-notebook/api"
)
// @title Accounting-notebook
// @version 1.0
// @description API Restful for credit and debit transactions
// @contact.name Martin Pruyas
// @contact.url https://www.linkedin.com/in/martin-pruyas/
// @contact.email o.gema.pg@gmail.com
// @license.name mp.02
// @host localhost
// @BasePath /v1
func main() {
router := gin.Default()
v1 := router.Group("/v1")
{
v1.GET("/capital/:id", api.GetCapital)
v1.POST("/credit/:id", api.PostCredit)
v1.POST("/debit/:id", api.PostDebit)
}
router.Run()
}
|
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
var lr LimitRate
lr.SetRate(3)
for i:=0;i<10;i++{
wg.Add(1)
go func(){
if lr.Limit() {
fmt.Println("Got it!")//显示3次Got it!
}
wg.Done()
}()
}
wg.Wait()
} |
package main
import (
"fmt"
"net/http"
pinyin "github.com/mozillazg/go-pinyin"
)
func main() {
fmt.Println("hello")
hans := "中国人"
// 默认
a := pinyin.NewArgs()
fmt.Println(pinyin.Pinyin(hans, a))
http.ListenAndServe(":8080", http.FileServer(http.Dir("./")))
}
|
package unio
//noinspection GoUnusedConst
const DATE = "2006-01-02"
//noinspection GoUnusedConst
const DATETIME = "2006-01-02 15:04:05"
|
package config
// based on https://cbonte.github.io/haproxy-dconv/1.6/configuration.html
func NewDefault() *Default {
return &Default{
Values: make([]Line, 0),
}
}
type Default struct {
// blindly store all defaults for now
Values []Line
}
// parse the lines in a default
func (me *Parser) defaultSection(line Line, state *state) error {
log.Tracef("parse %s", line)
me.Config.Default.Values = append(me.Config.Default.Values, line)
return nil
}
|
package tx
import (
"sync"
)
type GoroutineMethodStackMap struct {
m map[int64]*StructField
lock sync.RWMutex
}
func (g GoroutineMethodStackMap) New() GoroutineMethodStackMap {
return GoroutineMethodStackMap{
m: make(map[int64]*StructField),
}
}
func (g *GoroutineMethodStackMap) Put(k int64, methodInfo *StructField) {
g.lock.Lock()
defer g.lock.Unlock()
g.m[k] = methodInfo
}
func (g *GoroutineMethodStackMap) Get(k int64) *StructField {
return g.m[k]
}
|
// Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package kvcache
import (
"fmt"
"reflect"
"testing"
"github.com/pingcap/tidb/util/memory"
"github.com/stretchr/testify/require"
)
type mockCacheKey struct {
hash []byte
key int64
}
func (mk *mockCacheKey) Hash() []byte {
if mk.hash != nil {
return mk.hash
}
mk.hash = make([]byte, 8)
for i := uint(0); i < 8; i++ {
mk.hash[i] = byte((mk.key >> ((i - 1) * 8)) & 0xff)
}
return mk.hash
}
func newMockHashKey(key int64) *mockCacheKey {
return &mockCacheKey{
key: key,
}
}
func TestPut(t *testing.T) {
maxMem, err := memory.MemTotal()
require.NoError(t, err)
lruMaxMem := NewSimpleLRUCache(3, 0, maxMem)
lruZeroQuota := NewSimpleLRUCache(3, 0, 0)
require.Equal(t, uint(3), lruMaxMem.capacity)
require.Equal(t, uint(3), lruMaxMem.capacity)
keys := make([]*mockCacheKey, 5)
vals := make([]int64, 5)
maxMemDroppedKv := make(map[Key]Value)
zeroQuotaDroppedKv := make(map[Key]Value)
// test onEvict function
lruMaxMem.SetOnEvict(func(key Key, value Value) {
maxMemDroppedKv[key] = value
})
// test onEvict function on 0 value of quota
lruZeroQuota.SetOnEvict(func(key Key, value Value) {
zeroQuotaDroppedKv[key] = value
})
for i := 0; i < 5; i++ {
keys[i] = newMockHashKey(int64(i))
vals[i] = int64(i)
lruMaxMem.Put(keys[i], vals[i])
lruZeroQuota.Put(keys[i], vals[i])
}
require.Equal(t, lruMaxMem.size, lruMaxMem.capacity)
require.Equal(t, lruZeroQuota.size, lruZeroQuota.capacity)
require.Equal(t, uint(3), lruMaxMem.size)
require.Equal(t, lruZeroQuota.size, lruMaxMem.size)
// test for non-existent elements
require.Len(t, maxMemDroppedKv, 2)
for i := 0; i < 2; i++ {
element, exists := lruMaxMem.elements[string(keys[i].Hash())]
require.False(t, exists)
require.Nil(t, element)
require.Equal(t, vals[i], maxMemDroppedKv[keys[i]])
require.Equal(t, vals[i], zeroQuotaDroppedKv[keys[i]])
}
// test for existent elements
root := lruMaxMem.cache.Front()
require.NotNil(t, root)
for i := 4; i >= 2; i-- {
entry, ok := root.Value.(*cacheEntry)
require.True(t, ok)
require.NotNil(t, entry)
// test key
key := entry.key
require.NotNil(t, key)
require.Equal(t, keys[i], key)
element, exists := lruMaxMem.elements[string(keys[i].Hash())]
require.True(t, exists)
require.NotNil(t, element)
require.Equal(t, root, element)
// test value
value, ok := entry.value.(int64)
require.True(t, ok)
require.Equal(t, vals[i], value)
root = root.Next()
}
// test for end of double-linked list
require.Nil(t, root)
}
func TestZeroQuota(t *testing.T) {
lru := NewSimpleLRUCache(100, 0, 0)
require.Equal(t, uint(100), lru.capacity)
keys := make([]*mockCacheKey, 100)
vals := make([]int64, 100)
for i := 0; i < 100; i++ {
keys[i] = newMockHashKey(int64(i))
vals[i] = int64(i)
lru.Put(keys[i], vals[i])
}
require.Equal(t, lru.size, lru.capacity)
require.Equal(t, uint(100), lru.size)
}
func TestOOMGuard(t *testing.T) {
maxMem, err := memory.MemTotal()
require.NoError(t, err)
lru := NewSimpleLRUCache(3, 1.0, maxMem)
require.Equal(t, uint(3), lru.capacity)
keys := make([]*mockCacheKey, 5)
vals := make([]int64, 5)
for i := 0; i < 5; i++ {
keys[i] = newMockHashKey(int64(i))
vals[i] = int64(i)
lru.Put(keys[i], vals[i])
}
require.Equal(t, uint(0), lru.size)
// test for non-existent elements
for i := 0; i < 5; i++ {
element, exists := lru.elements[string(keys[i].Hash())]
require.False(t, exists)
require.Nil(t, element)
}
}
func TestGet(t *testing.T) {
maxMem, err := memory.MemTotal()
require.NoError(t, err)
lru := NewSimpleLRUCache(3, 0, maxMem)
keys := make([]*mockCacheKey, 5)
vals := make([]int64, 5)
for i := 0; i < 5; i++ {
keys[i] = newMockHashKey(int64(i))
vals[i] = int64(i)
lru.Put(keys[i], vals[i])
}
// test for non-existent elements
for i := 0; i < 2; i++ {
value, exists := lru.Get(keys[i])
require.False(t, exists)
require.Nil(t, value)
}
for i := 2; i < 5; i++ {
value, exists := lru.Get(keys[i])
require.True(t, exists)
require.NotNil(t, value)
require.Equal(t, vals[i], value)
require.Equal(t, uint(3), lru.size)
require.Equal(t, uint(3), lru.capacity)
root := lru.cache.Front()
require.NotNil(t, root)
entry, ok := root.Value.(*cacheEntry)
require.True(t, ok)
require.Equal(t, keys[i], entry.key)
value, ok = entry.value.(int64)
require.True(t, ok)
require.Equal(t, vals[i], value)
}
}
func TestDelete(t *testing.T) {
maxMem, err := memory.MemTotal()
require.NoError(t, err)
lru := NewSimpleLRUCache(3, 0, maxMem)
keys := make([]*mockCacheKey, 3)
vals := make([]int64, 3)
for i := 0; i < 3; i++ {
keys[i] = newMockHashKey(int64(i))
vals[i] = int64(i)
lru.Put(keys[i], vals[i])
}
require.Equal(t, 3, int(lru.size))
lru.Delete(keys[1])
value, exists := lru.Get(keys[1])
require.False(t, exists)
require.Nil(t, value)
require.Equal(t, 2, int(lru.size))
_, exists = lru.Get(keys[0])
require.True(t, exists)
_, exists = lru.Get(keys[2])
require.True(t, exists)
}
func TestDeleteAll(t *testing.T) {
maxMem, err := memory.MemTotal()
require.NoError(t, err)
lru := NewSimpleLRUCache(3, 0, maxMem)
keys := make([]*mockCacheKey, 3)
vals := make([]int64, 3)
for i := 0; i < 3; i++ {
keys[i] = newMockHashKey(int64(i))
vals[i] = int64(i)
lru.Put(keys[i], vals[i])
}
require.Equal(t, 3, int(lru.size))
lru.DeleteAll()
for i := 0; i < 3; i++ {
value, exists := lru.Get(keys[i])
require.False(t, exists)
require.Nil(t, value)
require.Equal(t, 0, int(lru.size))
}
}
func TestValues(t *testing.T) {
maxMem, err := memory.MemTotal()
require.NoError(t, err)
lru := NewSimpleLRUCache(5, 0, maxMem)
keys := make([]*mockCacheKey, 5)
vals := make([]int64, 5)
for i := 0; i < 5; i++ {
keys[i] = newMockHashKey(int64(i))
vals[i] = int64(i)
lru.Put(keys[i], vals[i])
}
values := lru.Values()
require.Equal(t, 5, len(values))
for i := 0; i < 5; i++ {
require.Equal(t, int64(4-i), values[i])
}
}
func TestPutProfileName(t *testing.T) {
lru := NewSimpleLRUCache(3, 0, 10)
require.Equal(t, uint(3), lru.capacity)
tem := reflect.TypeOf(*lru)
pt := reflect.TypeOf(lru)
functionName := ""
for i := 0; i < pt.NumMethod(); i++ {
if pt.Method(i).Name == "Put" {
functionName = "Put"
}
}
pName := fmt.Sprintf("%s.(*%s).%s", tem.PkgPath(), tem.Name(), functionName)
require.Equal(t, ProfileName, pName)
}
|
package shortest_path
import (
"container/heap"
"container/list"
)
type Graph struct {
v int
adj []*list.List
}
type edge struct {
sid, tid int // 边的起始/终止顶点编号
w int // 边的权重
}
func NewGraph(v int) *Graph {
graph := &Graph{
v: v,
adj: make([]*list.List, v),
}
for i := range graph.adj {
graph.adj[i] = list.New()
}
return graph
}
func newEdge(sid, tid, w int) *edge {
return &edge{sid, tid, w}
}
func (graph *Graph) AddEdge(s, t, w int) {
graph.adj[s].PushBack(newEdge(s, t, w))
}
// s 到 t 的最短路径
func (graph *Graph) Dijkstra(s, t int) {
// 用来还原最短路径
predecessor := make([]int, graph.v)
// 记录从起始顶点到每个顶点的距离 dist
vertexes := make([]*Vertex, graph.v)
for i := 0; i < graph.v; i++ {
// 这里初始化距离为 1000
vertexes[i] = NewVertex(i, 1000)
}
queue := make(PriorityQueue, 0) // 小顶堆
heap.Init(&queue)
// 标记是否进入过队列
inqueue := make([]bool, graph.v)
dist = 0
heap.Push(&queue, vertexes[s])
inqueue[s] = true
for Len() > 0 {
// 从优先队列中取出 dist 最小的顶点,考察该点可达的所有点
minVertex := heap.Pop(&queue).(*Vertex)
if id == t { // 最短路径已产生
break
}
front := graph.adj[minVertex.id].Front()
for ; front != nil; front = front.Next() {
// 取出一条 minVertex 相连的边
e := front.Value.(*edge)
// minVertex -> nextVertex
nextVertex := vertexes[e.tid]
// 更新 next 的 dist
if dist+e.w < dist {
dist = dist + e.w
predecessor[id] = id
if inqueue[id] == true {
// 对更新了 dist 的 nextVertex 进行堆化
heap.Fix(&queue, id)
} else {
heap.Push(&queue, nextVertex)
inqueue[id] = true
}
}
}
}
// 输出最短路径
print(s)
graph.print(s, t, predecessor)
}
func (graph *Graph) print(s, t int, predecessor []int) {
if s == t {
return
}
graph.print(s, predecessor[t], predecessor)
print("->", t)
}
|
package main
type SystemSpec struct {
OSName string `json:osName`
Processor string `json:processor`
} |
package html2rst
import (
"golang.org/x/net/html"
)
func td2rst(td *html.Node) string {
s := ""
for c := td.FirstChild; c != nil; c = c.NextSibling {
if isTextNode(c) {
s += textNode2rst(c)
continue
}
if isAnchorElement(c) {
s += a2rst(c)
continue
}
}
return s
}
func tr2rst(tr *html.Node) string {
s := ""
isFirstTd := true
for c := tr.FirstChild; c != nil; c = c.NextSibling {
if isTdElement(c) {
if isFirstTd {
s += (" * - " + td2rst(c) + "\n")
isFirstTd = false
} else {
s += (" - " + td2rst(c) + "\n")
}
continue
}
}
return s
}
func tbody2rst(tbody *html.Node) string {
s := ""
for c := tbody.FirstChild; c != nil; c = c.NextSibling {
if isTrElement(c) {
s += tr2rst(c)
continue
}
}
return s
}
func table2rst(table *html.Node) string {
s := ".. list-table::\n\n"
for c := table.FirstChild; c != nil; c = c.NextSibling {
if isTbodyElement(c) {
s += tbody2rst(c)
continue
}
}
return s
}
|
package main
import "sort"
func main() {
}
func eraseOverlapIntervals(intervals [][]int) int {
// 按左端点排序
sort.Slice(intervals, func(i, j int) bool {
return intervals[i][1] < intervals[j][1]
})
right := intervals[0][1]
ans := 1
for i := 1; i < len(intervals); i++ {
if intervals[i][0] >= right {
ans++
right = intervals[i][1]
}
}
return len(intervals) - ans
}
// 会超时
func eraseOverlapIntervals2(intervals [][]int) int {
// 按左端点排序
sort.Slice(intervals, func(i, j int) bool {
return intervals[i][0] < intervals[j][0]
})
// 以 i 左端点结尾的区间,最多多少个连续的
dp := make([]int, len(intervals))
for i := range dp {
dp[i] = 1
}
max := func(arr []int) int {
x := arr[0]
for _, v := range arr[1:] {
if v > x {
x = v
}
}
return x
}
for i := 1; i < len(intervals); i++ {
for j := 0; j < i; j++ {
if intervals[j][1] <= intervals[i][0] {
// j 的右端点小于 i 的左端点
dp[i] = max([]int{dp[i], dp[j] + 1})
}
}
}
// 去掉的= 总长度 - 最长连续的
return len(intervals) - max(dp)
}
|
// Package ssh contains utilities that help gather logs, etc. on failures using ssh.
package ssh
import (
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/pkg/sftp"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"github.com/openshift/installer/pkg/lineprinter"
)
// NewClient creates a new SSH client which can be used to SSH to address using user and the keys.
//
// if keys list is empty, it tries to load the keys from the user's environment.
func NewClient(user, address string, keys []string) (*ssh.Client, error) {
ag, agentType, err := getAgent(keys)
if err != nil {
return nil, errors.Wrap(err, "failed to initialize the SSH agent")
}
client, err := ssh.Dial("tcp", address, &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
// Use a callback rather than PublicKeys
// so we only consult the agent once the remote server
// wants it.
ssh.PublicKeysCallback(ag.Signers),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
})
if err != nil {
if strings.Contains(err.Error(), "ssh: handshake failed: ssh: unable to authenticate") {
if agentType == "agent" {
return nil, errors.Wrap(err, "failed to use pre-existing agent, make sure the appropriate keys exist in the agent for authentication")
}
return nil, errors.Wrap(err, "failed to use the provided keys for authentication")
}
return nil, err
}
if err := agent.ForwardToAgent(client, ag); err != nil {
return nil, errors.Wrap(err, "failed to forward agent")
}
return client, nil
}
// Run uses an SSH client to execute commands.
func Run(client *ssh.Client, command string) error {
sess, err := client.NewSession()
if err != nil {
return err
}
defer sess.Close()
if err := agent.RequestAgentForwarding(sess); err != nil {
return errors.Wrap(err, "failed to setup request agent forwarding")
}
debugW := &lineprinter.LinePrinter{Print: (&lineprinter.Trimmer{WrappedPrint: logrus.Debug}).Print}
defer debugW.Close()
sess.Stdout = debugW
sess.Stderr = debugW
return sess.Run(command)
}
// PullFileTo downloads the file from remote server using SSH connection and writes to localPath.
func PullFileTo(client *ssh.Client, remotePath, localPath string) error {
sc, err := sftp.NewClient(client)
if err != nil {
return errors.Wrap(err, "failed to initialize the sftp client")
}
defer sc.Close()
// Open the source file
rFile, err := sc.Open(remotePath)
if err != nil {
return errors.Wrap(err, "failed to open remote file")
}
defer rFile.Close()
lFile, err := os.Create(localPath)
if err != nil {
return errors.Wrap(err, "failed to create file")
}
defer lFile.Close()
if _, err := rFile.WriteTo(lFile); err != nil {
return err
}
return nil
}
// defaultPrivateSSHKeys returns a list of all the PRIVATE SSH keys from user's home directory.
// It does not return any intermediate errors if at least one private key was loaded.
func defaultPrivateSSHKeys() (map[string]interface{}, error) {
d := filepath.Join(os.Getenv("HOME"), ".ssh")
paths, err := os.ReadDir(d)
if err != nil {
return nil, errors.Wrapf(err, "failed to read directory %q", d)
}
var files []string
for _, path := range paths {
if path.IsDir() {
continue
}
files = append(files, filepath.Join(d, path.Name()))
}
keys, err := LoadPrivateSSHKeys(files)
if len(keys) > 0 {
return keys, nil
}
return nil, err
}
// LoadPrivateSSHKeys try to optimistically load PRIVATE SSH keys from the all paths.
func LoadPrivateSSHKeys(paths []string) (map[string]interface{}, error) {
var errs []error
keys := make(map[string]interface{})
for _, path := range paths {
data, err := os.ReadFile(path)
if err != nil {
errs = append(errs, errors.Wrapf(err, "failed to read %q", path))
continue
}
key, err := ssh.ParseRawPrivateKey(data)
if err != nil {
logrus.Debugf("failed to parse SSH private key from %q", path)
errs = append(errs, errors.Wrapf(err, "failed to parse SSH private key from %q", path))
continue
}
keys[path] = key
}
if err := utilerrors.NewAggregate(errs); err != nil {
return keys, err
}
return keys, nil
}
|
package main
import (
"strings"
)
func main() {
tests := [10][2]string{
// truthy test
{"1234", "1234"},
{"1234", "4321"},
{"1234", "2314"},
{"anagram", "manraag"},
{"anagram", "Anagram"},
{"anagram", "MARGANA"},
// falsy tests
{"anagram", "ana gram"},
{"1112", "4321"},
{"12345", "1234"},
{"1234", "1523"},
}
for _, v := range tests {
println(isAnagram(v[0], v[1]))
}
}
func isAnagram(s1, s2 string) bool {
/*
test length is equal
search for each rune in each other
*/
lngth := len(s1)
if lngth != len(s2) {
return false
}
// let's be case-insensitive
s1 = strings.ToUpper(s1)
s2 = strings.ToUpper(s2)
for i:=0; i<lngth ; i++ {
if strings.Contains(s1, s2[i:i+1]) != true {
return false
}
if strings.Contains(s2, s1[i:i+1]) != true {
return false
}
}
return true
}
|
package main
import (
"github.com/douglasmakey/go-fcm"
"log"
)
func main() {
// init client
client := fcm.NewClient("ApiKey")
// You can use your HTTPClient
//client.SetHTTPClient(client)
data := map[string]interface{}{
"message": "From Go-FCM",
"details": map[string]string{
"name": "Name",
"user": "Admin",
"thing": "none",
},
}
// You can use PushMultiple or PushSingle
client.PushMultiple([]string{"token 1", "token 2"}, data)
//client.PushSingle("token 1", data)
// registrationIds remove and return a list of invalid tokens
badRegistrations := client.CleanRegistrationIds()
log.Println(badRegistrations)
status, err := client.Send()
if err != nil {
log.Fatalf("error: %v", err)
}
log.Println(status.Results)
}
|
//Package setting provide goil's settings
package setting
import (
"os"
"path/filepath"
"strings"
"time"
"github.com/Unknwon/goconfig"
"github.com/howeyc/fsnotify"
)
const (
APP_VER = "0.10"
)
var (
AppName string
AppHost string
AppVer string
IsProMode bool
TimeZone string
)
var (
Cfg *goconfig.ConfigFile
)
var (
AppConfPath = "conf/app.ini"
HookReload []func()
FigureSite string
VideoSite string
AwsBucket string
AwsRegion string
AwsAccessKeyId string
AwsSecretAccessKey string
QiniuAccessKeyId string
QiniuSecretAccessKey string
CacheNodes []string
QiniuBucket string
QiniuVmp4Prefix string
QiniuVm3u8Prefix string
QiniuPicPrefix string
)
// LoadConfig loads configuration file.
func LoadConfig() *goconfig.ConfigFile {
var err error
if fh, _ := os.OpenFile(AppConfPath, os.O_RDONLY|os.O_CREATE, 0600); fh != nil {
fh.Close()
}
// Load configuration, set app version and Log level.
Cfg, err = goconfig.LoadConfigFile(AppConfPath)
if err != nil {
Logger.Error("Fail to load configuration file: " + err.Error())
os.Exit(2)
}
//Cfg.BlockMode = false
// set time zone of wetalk system
TimeZone = Cfg.MustValue("app", "time_zone", "UTC")
if _, err := time.LoadLocation(TimeZone); err == nil {
os.Setenv("TZ", TimeZone)
} else {
Logger.Error("Wrong time_zone: " + TimeZone + " " + err.Error())
os.Exit(2)
}
//aws config
FigureSite = Cfg.MustValue("site", "figure_site", "")
VideoSite = Cfg.MustValue("site", "video_site", "")
AwsBucket = Cfg.MustValue("aws", "aws_bucket")
AwsRegion = Cfg.MustValue("aws", "aws_region")
AwsAccessKeyId = Cfg.MustValue("aws", "aws_access_key_id")
AwsSecretAccessKey = Cfg.MustValue("aws", "aws_secret_access_key")
QiniuAccessKeyId = Cfg.MustValue("qiniu", "qiniu_access_key_id")
QiniuSecretAccessKey = Cfg.MustValue("qiniu", "qiniu_secret_access_key")
QiniuBucket = Cfg.MustValue("qiniu", "bucket")
QiniuVmp4Prefix = Cfg.MustValue("qiniu", "vmp4_prefix")
QiniuVm3u8Prefix = Cfg.MustValue("qiniu", "vm3u8_prefix")
QiniuPicPrefix = Cfg.MustValue("qiniu", "pic_prefix")
os.MkdirAll("./tmpcache", os.ModePerm)
// Trim 4th part.
AppVer = strings.Join(strings.Split(APP_VER, ".")[:2], ".")
AppHost = Cfg.MustValue("app", "app_host", "9501")
IsProMode = Cfg.MustValue("app", "run_mode") == "pro"
if IsDebug {
IsProMode = !IsDebug
}
reloadConfig()
configWatcher()
return Cfg
}
func reloadConfig() {
AppName = Cfg.MustValue("app", "app_name", "WeTalk Community")
CacheNodes = strings.Split(Cfg.MustValue("cachenodes", "nodes", ""), ",")
for _, f := range HookReload {
f()
}
}
var eventTime = make(map[string]int64)
func configWatcher() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
panic("Failed start app watcher: " + err.Error())
}
go func() {
for {
select {
case event := <-watcher.Event:
switch filepath.Ext(event.Name) {
case ".ini":
if checkEventTime(event.Name) {
continue
}
Logger.Info(event)
if err := Cfg.Reload(); err != nil {
Logger.Error("Conf Reload: ", err)
}
reloadConfig()
Logger.Info("Config Reloaded")
}
}
}
}()
if err := watcher.WatchFlags("conf", fsnotify.FSN_MODIFY); err != nil {
Logger.Error(err)
}
}
// checkEventTime returns true if FileModTime does not change.
func checkEventTime(name string) bool {
mt := getFileModTime(name)
if eventTime[name] == mt {
return true
}
eventTime[name] = mt
return false
}
// getFileModTime retuens unix timestamp of `os.File.ModTime` by given path.
func getFileModTime(path string) int64 {
path = strings.Replace(path, "\\", "/", -1)
f, err := os.Open(path)
if err != nil {
Logger.Error("Fail to open file[ %s ]\n", err)
return time.Now().Unix()
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
Logger.Error("Fail to get file information[ %s ]\n", err)
return time.Now().Unix()
}
return fi.ModTime().Unix()
}
|
package service
import (
"github.com/sem-onyalo/wimbyai-api/service/request"
)
// API is a boundary to the web api
type API interface {
Start(request request.StartAPI)
}
|
package sgf
import (
"fmt"
"strconv"
)
// GetRoot travels up the tree, examining each node's parent until it finds the
// root node, which it returns.
func (self *Node) GetRoot() *Node {
node := self
for node.parent != nil {
node = node.parent
}
return node
}
// GetEnd travels down the tree from the node, until it reaches a node with zero
// children. It returns that node. Note that, if GetEnd is called on a node that
// is not on the main line, the result will not be on the main line either, but
// will instead be the end of the current branch.
func (self *Node) GetEnd() *Node {
node := self
for len(node.children) > 0 {
node = node.children[0]
}
return node
}
// GetLine returns a list of all nodes between the root and the node, inclusive.
func (self *Node) GetLine() []*Node {
var ret []*Node
node := self
for node != nil {
ret = append(ret, node)
node = node.parent
}
// Reverse the slice...
for left, right := 0, len(ret) - 1; left < right; left, right = left + 1, right - 1 {
ret[left], ret[right] = ret[right], ret[left]
}
return ret
}
// MakeMainLine adjusts the tree structure so that the main line leads to this
// node.
func (self *Node) MakeMainLine() {
node := self
for node.parent != nil {
for i, sibling := range node.parent.children {
if sibling == node {
node.parent.children[i] = node.parent.children[0]
node.parent.children[0] = node
break
}
}
node = node.parent
}
}
// SubtreeSize returns the number of nodes in a node's subtree, including
// itself.
func (self *Node) SubtreeSize() int {
count := 1
for _, child := range self.children {
count += child.SubtreeSize()
}
return count
}
// TreeSize returns the number of nodes in the whole tree.
func (self *Node) TreeSize() int {
return self.GetRoot().SubtreeSize()
}
// SubtreeNodes returns a slice of every node in a node's subtree, including
// itself.
func (self *Node) SubtreeNodes() []*Node {
ret := []*Node{self}
for _, child := range self.children {
ret = append(ret, child.SubtreeNodes()...)
}
return ret
}
// TreeNodes returns a slice of every node in the whole tree.
func (self *Node) TreeNodes() []*Node {
return self.GetRoot().SubtreeNodes()
}
// SubTreeKeyValueCount returns the number of keys and values in a node's
// subtree, including itself.
func (self *Node) SubTreeKeyValueCount() (int, int) {
keys := self.KeyCount()
vals := 0
for _, key := range self.AllKeys() {
vals += self.ValueCount(key)
}
for _, child := range self.children {
k, v := child.SubTreeKeyValueCount()
keys += k; vals += v
}
return keys, vals
}
// TreeKeyValueCount returns the number of keys and values in the whole tree.
func (self *Node) TreeKeyValueCount() (int, int) {
return self.GetRoot().SubTreeKeyValueCount()
}
// RootBoardSize travels up the tree to the root, and then finds the board size,
// which it returns as an integer. If no SZ property is present, it returns 19.
func (self *Node) RootBoardSize() int {
root := self.GetRoot()
sz_string, _ := root.GetValue("SZ")
sz, _ := strconv.Atoi(sz_string)
if sz < 1 { return 19 }
if sz > 52 { return 52 } // SGF limit
return sz
}
// RootKomi travels up the tree to the root, and then finds the komi, which it
// returns as a float64. If no KM property is present, it returns 0.
func (self *Node) RootKomi() float64 {
root := self.GetRoot()
km_string, _ := root.GetValue("KM")
km, _ := strconv.ParseFloat(km_string, 64)
return km
}
// Dyer returns the Dyer Signature of the entire tree.
func (self *Node) Dyer() string {
vals := map[int]string{20: "??", 40: "??", 60: "??", 31: "??", 51: "??", 71: "??"}
move_count := 0
node := self.GetRoot()
size := node.RootBoardSize()
for {
for _, key := range []string{"B", "W"} {
mv, ok := node.GetValue(key) // Assuming just 1, as per SGF specs.
if ok {
move_count++
if move_count == 20 || move_count == 40 || move_count == 60 ||
move_count == 31 || move_count == 51 || move_count == 71 {
if ValidPoint(mv, size) {
vals[move_count] = mv
}
}
}
}
node = node.MainChild()
if node == nil || move_count > 71 {
break
}
}
return fmt.Sprintf("%s%s%s%s%s%s", vals[20], vals[40], vals[60], vals[31], vals[51], vals[71])
}
|
package machine
import (
"fmt"
)
// Rotors is a list of rotors used as a part of a machine.
type Rotors struct {
rotors []*Rotor
count int
}
// NewRotors returns a new, initialized Rotors pointer, and an error if given
// rotor list is invalid.
func NewRotors(rotors []*Rotor) (*Rotors, error) {
if len(rotors) == 0 {
return nil, fmt.Errorf("no rotors given")
}
for i, rotor := range rotors {
if rotor == nil {
return nil, fmt.Errorf("rotor %d doesn't exist", i)
}
if err := rotor.Verify(); err != nil {
return nil, fmt.Errorf("rotor %d: %w", i, err)
}
}
return &Rotors{
rotors: rotors,
count: len(rotors),
}, nil
}
// GenerateRotors returns a list of randomly generated rotors.
func GenerateRotors(count int) *Rotors {
rotors := make([]*Rotor, count)
for i := 0; i < count; i++ {
rotors[i] = GenerateRotor()
}
return &Rotors{
rotors: rotors,
count: count,
}
}
// Rotor returns rotor at position i.
func (r *Rotors) Rotor(i int) (*Rotor, error) {
if i < 0 || i >= r.count {
return nil, fmt.Errorf("invalid index %d", i)
}
return r.rotors[i], nil
}
// takeStep moves the rotors one step forward.
func (r *Rotors) takeStep() {
for i, rotor := range r.rotors {
if i != 0 && (r.rotors[i-1].takenSteps != 0) { // Previous rotor didn't complete a cycle.
break
}
rotor.takeStep()
}
}
// Verify verifies that rotors' are valid, and returns an error otherwise.
func (r *Rotors) Verify() error {
if len(r.rotors) == 0 || r.count != len(r.rotors) {
return fmt.Errorf("invalid number of rotors")
}
for i, rotor := range r.rotors {
if err := rotor.Verify(); err != nil {
return fmt.Errorf("rotor %d: %w", i, err)
}
}
return nil
}
// UseDefaults sets all fields of each rotor to, except pathways, to their default
// values.
func (r *Rotors) UseDefaults() {
for _, rotor := range r.rotors {
rotor.UseDefaults()
}
}
// Setting returns rotors' current setting. A setting is a list containing the current
// position of each rotor.
func (r *Rotors) Setting() []int {
setting := make([]int, r.count)
for i, rotor := range r.rotors {
setting[i] = rotor.Position()
}
return setting
}
// Count returns number of rotors.
func (r *Rotors) Count() int {
return r.count
}
|
package StringToInteger
import "testing"
func Test_myAtoi(t *testing.T) {
type args struct {
str string
}
tests := []struct {
name string
args args
want int
}{
//TODO: Add test cases.
{
name: "first",
args: args{str: "01234"},
want: 1234,
},
{
name: "second",
args: args{str: " -42"},
want: -42,
},
{
name: "third",
args: args{str: "4293 with words"},
want: 4293,
},
{
name: "fourth",
args: args{str: "words and 987"},
want: 0,
},
{
name: "fifth",
args: args{str: "-2199999999"},
want: -2147483648,
},
{
name: "sixth",
args: args{str: " "},
want: 0,
},
{
name: "seventh",
args: args{str: " -00000000000012345678"},
want: -12345678,
},
{
name: "eighth",
args: args{str: "1095502006p8"},
want: 1095502006,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := myAtoi(tt.args.str); got != tt.want {
t.Errorf("myAtoi() = %v, want %v", got, tt.want)
}
})
}
}
|
// +build examples
package examples
import (
"fmt"
"fronius-exporter/pkg/fronius"
"log"
"time"
)
func main() {
client, err := fronius.NewSymoClient(fronius.ClientOptions{
URL: "http://symo.ip.or.hostname/solar_api/v1/GetPowerFlowRealtimeData.fcgi",
Timeout: 5 * time.Second,
})
if err != nil {
log.Fatal(err)
}
data, err := client.GetPowerFlowData()
if err != nil {
log.Fatal(err)
}
fmt.Println("Current power usage: " + data.Site.PowerLoad)
}
|
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"sort"
"strings"
)
func check(e error) {
if e != nil {
log.Fatal(e)
}
}
func parseData() (res [][]string) {
file := "data"
if len(os.Args) > 1 {
file = os.Args[1]
}
rawData, err := ioutil.ReadFile(file)
check(err)
rows := strings.Split(strings.TrimSuffix(string(rawData), "\n"), "\n")
res = make([][]string, len(rows))
for i, row := range rows {
res[i] = strings.Split(row, "")
}
return
}
func main() {
tracks := parseData()
carts := getMineCarts(&tracks)
firstCrash := part1(tracks, carts)
fmt.Printf("The location of the first crash is at %d,%d.\n", firstCrash.x, firstCrash.y)
lastCart := part2(tracks, carts)
fmt.Printf("The location of the last cart is at %d,%d.\n", lastCart.x, lastCart.y)
}
func part1(tracks [][]string, carts []Cart) Coord {
cartMap := make(map[Coord]*Cart)
cartCopy := append([]Cart{}, carts...)
for {
for i := 0; i < len(cartCopy); i++ {
if crashed := cartCopy[i].UpdateCoordinates(tracks, &cartMap); crashed {
return cartCopy[i].coordinates
}
}
sort.Sort(ByCoord(cartCopy))
}
}
func part2(tracks [][]string, carts []Cart) Coord {
cartMap := make(map[Coord]*Cart)
cartCopy := append([]Cart{}, carts...)
for len(cartCopy) > 1 {
for i := 0; i < len(cartCopy); i++ {
if crashed := cartCopy[i].UpdateCoordinates(tracks, &cartMap); crashed {
cartCopy[i].SetCrashed()
cartMap[cartCopy[i].coordinates].SetCrashed()
delete(cartMap, cartCopy[i].coordinates)
}
}
aliveCarts := []Cart{}
for _, cart := range cartCopy {
if cart.alive {
aliveCarts = append(aliveCarts, cart)
}
}
cartCopy = aliveCarts
sort.Sort(ByCoord(cartCopy))
}
return cartCopy[0].coordinates
}
func getMineCarts(tracks *[][]string) (carts []Cart) {
for y := 0; y < len(*tracks); y++ {
row := (*tracks)[y]
for x := 0; x < len(row); x++ {
cartDirection := row[x]
if cartDirection == "<" || cartDirection == ">" {
(*tracks)[y][x] = "-"
carts = append(carts, InitCart(x, y, cartDirection))
} else if cartDirection == "^" || cartDirection == "v" {
(*tracks)[y][x] = "|"
carts = append(carts, InitCart(x, y, cartDirection))
}
}
}
return
}
func print2DArr(arr [][]string) {
for _, row := range arr {
fmt.Println(row)
}
}
|
package commands
import (
"github.com/mix-go/console"
"github.com/mix-go/mix-console-skeleton/commands"
)
func init() {
Commands = append(Commands,
console.CommandDefinition{
Name: "hello",
Usage: "\tEcho demo",
Options: []console.OptionDefinition{
{
Names: []string{"n", "name"},
Usage: "Your name",
},
{
Names: []string{"say"},
Usage: "\tSay ...",
},
},
Command: &commands.HelloCommand{},
},
)
}
|
package onelogin
import "testing"
// Test the GetUrl() method for generating request URLS
func TestGetUrl(t *testing.T) {
shards := map[string]string{
"us": "https://api.us.onelogin.com/",
"eu": "https://api.eu.onelogin.com/",
}
for shard,url := range shards {
o := OneLogin{Shard: shard}
result := o.GetUrl("")
if result != url {
t.Errorf("GetUrl() for shard %s != %s (actual result was %s)", shard, url, result)
}
}
}
// Test the Get_Token() method for requesting the current or a new token.
func TestGet_Token(t *testing.T) {
t.Errorf("No tests written yet for Get_Token()")
}
// Test the Authenticate() method for authenticating a user to OneLogin
func TestAuthenticate(t *testing.T) {
t.Errorf("No tests written yet for Authenticate()")
}
// Test the VerifyToken() method for verifying an OTP (MFA) token.
func TestVerifyToken(t *testing.T) {
t.Errorf("No tests written yet for VerifyToken()")
}
|
package kube
import (
"reflect"
"testing"
sfv1alpha1 "github.com/openshift/splunk-forwarder-operator/api/v1alpha1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func TestGenerateService(t *testing.T) {
type args struct {
instance *sfv1alpha1.SplunkForwarder
}
tests := []struct {
name string
args args
want *corev1.Service
}{
{
name: "Testing Service Generation",
args: args{
instance: &sfv1alpha1.SplunkForwarder{
ObjectMeta: metav1.ObjectMeta{
Name: "testing",
Namespace: "openshift-test",
Generation: 1,
},
},
},
want: &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "testing",
Namespace: "openshift-test",
Labels: map[string]string{
"name": "splunk-heavy-forwarder-service",
},
Annotations: map[string]string{
"genVersion": "1",
},
},
Spec: corev1.ServiceSpec{
Type: "ClusterIP",
Selector: map[string]string{
"name": "splunk-heavy-forwarder",
},
Ports: []corev1.ServicePort{
{
Protocol: "TCP",
Port: 9997,
},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := GenerateService(tt.args.instance); !reflect.DeepEqual(got, tt.want) {
t.Errorf("GenerateService() = %v, want %v", got, tt.want)
}
})
}
}
|
package analysis
import (
"encoding/json"
"fmt"
cfg "github.com/redisTesting/internal/config"
"io/ioutil"
"math"
"os"
"path"
)
type ClientData struct {
Level string
ClientId int
TotalSent int
MinLat int
MaxLat int
MaxLatIdx int
AvgLat int
P50Lat int
P95Lat int
P99Lat int
Start int `json:"sendStart"`
End int `json:"SendEnd"`
Mid80Start int
Mid80End int
Mid80Dur float64
Mid80RecvTimeDur float64
Mid80Requests int
Mid80Throughput float64 `json:"mid80Throughput (cmd/sec)"`
Mid80Throughput2 float64 `json:"mid80Throughput2 (cmd/sec)"`
}
type Output struct {
NServers int
NClients int
ClientBatchSize int
Mid80Throughput float64
P50Lat float64
AvgLat float64
AvgDur float64
P95LAT float64
P99Lat float64
MaxDur float64
NClientRequests int
NTotalRequests int
}
func LoadClientLogs(logDirPath string) *[]ClientData {
var numClients int
var allData []ClientData
files, err := ioutil.ReadDir(logDirPath)
if err != nil {
panic(err)
}
for _, f := range files {
jsonFile, err := os.Open(path.Join(logDirPath, f.Name()))
if err != nil {
panic(err)
}
byteValue, _ := ioutil.ReadAll(jsonFile)
var data ClientData
json.Unmarshal(byteValue, &data)
allData = append(allData, data)
numClients += 1
jsonFile.Close()
}
return &allData
}
func RunAnalysis(logDirPath string) {
allData := LoadClientLogs(logDirPath)
numData := len(*allData)
var sumDur, maxDur float64
var sumAvgLat, sumP50Lat, sumP95Lat, sumP99Lat, maxMid80RecvTime, sumMid80Requests int
//var sumMid80RecvTime int
for _, data := range *allData {
sumDur += data.Mid80Dur
if data.Mid80Dur > maxDur {
maxDur = data.Mid80Dur
}
sumAvgLat += data.AvgLat
sumP50Lat += data.P50Lat
sumP95Lat += data.P95Lat
sumP99Lat += data.P99Lat
mid80RecvTime := data.Mid80End - data.Mid80Start
//sumMid80RecvTime += mid80RecvTime // in ns
if mid80RecvTime > maxMid80RecvTime {
maxMid80RecvTime = mid80RecvTime // in ns
}
sumMid80Requests += data.Mid80Requests
}
outputAvgDur := round(sumDur / float64(numData)) // TODO: check unit
outputAvgLat := round(float64(sumAvgLat) / float64(numData) / math.Pow10(3))
outputP50Lat := round(float64(sumP50Lat) / float64(numData) / math.Pow10(3))
outputP95Lat := round(float64(sumP95Lat) / float64(numData) / math.Pow10(3))
outputP99Lat := round(float64(sumP99Lat) / float64(numData) / math.Pow10(3))
//avgMid80RecvTime := round(float64(sumMid80RecvTime) / float64(numData) / math.Pow10(9))
outputMax80RecvTime := round(float64(maxMid80RecvTime) / math.Pow10(9))
outputSumMid80Requests := sumMid80Requests * cfg.Conf.ClientBatchSize
outputMid80Throughput := round(float64(outputSumMid80Requests) / outputMax80RecvTime)
output := Output{
NServers: cfg.Conf.NServers,
NClients: cfg.Conf.NClients,
NClientRequests: cfg.Conf.NClientRequests,
ClientBatchSize: cfg.Conf.ClientBatchSize,
NTotalRequests: cfg.Conf.NClientRequests * cfg.Conf.NClients,
AvgDur: outputAvgDur,
AvgLat: outputAvgLat,
P50Lat: outputP50Lat,
P95LAT: outputP95Lat,
P99Lat: outputP99Lat,
MaxDur: maxDur,
Mid80Throughput: outputMid80Throughput,
}
fmt.Printf("%+v\n", output)
fmt.Println(output)
fmt.Println(
output.Mid80Throughput,
output.P50Lat,
output.AvgLat,
output.AvgDur,
output.P95LAT,
output.P99Lat,
output.MaxDur,
output.NClientRequests,
output.NTotalRequests,
)
}
func round(input float64) float64 {
return math.Round(input*100)/100
} |
package main
import (
"fmt"
"image"
"image/color"
"image/color/palette"
"image/gif"
"os"
)
// Hands 价格
type Hands struct {
img *image.Paletted
}
// CreateHands ...
func CreateHands() *Hands {
return &Hands{img: image.NewPaletted(image.Rect(0, 0, 50, 7), palette.Plan9)}
}
//Make 价格的右上角坐标
func (p *Hands) Make(m *image.Image, right, top int) {
c := color.RGBA{0x9b, 0x9b, 0x9b, 0xff}
back := color.RGBA{0xff, 0xff, 0xff, 0}
offx := right - 50 + 1
for x := 0; x < 50; x++ {
for y := 0; y < 7; y++ {
r, g, b, a := (*m).At(x+offx, y+top).RGBA()
if uint8(r) == 0x9b &&
uint8(g) == 0x9b &&
uint8(b) == 0x9b &&
uint8(a) == 0xff {
p.img.Set(x, y, c)
} else {
p.img.Set(x, y, back)
}
}
}
}
// Save ...
func (p *Hands) Save(idx int) {
w, _ := os.Create(fmt.Sprintf("stockHands%d.gif", idx))
defer w.Close()
gif.Encode(w, p.img, nil)
}
func cutHands(m *image.Image) {
p := make([]*Hands, 0, 4)
back := color.RGBA{0, 0, 0, 0}
// offy := []int{0, 21, 42, 63}
last := 197
// for i := 0; i < 45; i++ {
// fmt.Println((*m).At(i, last))
// }
for i := 0; ; i++ {
Find:
for ; last < 270; last++ {
for k := 0; k < 45; k++ {
if (*m).At(k, last) != back {
break Find
}
}
}
if last >= 270 {
break
}
p = append(p, CreateHands())
fmt.Println("...", last)
p[i].Make(m, 45, last)
last += 8
p[i].Save(i)
}
}
|
package main
/*
#include <stdio.h>
#include <stdlib.h>
typedef int (*intFunc) ();
int
bridge_int_func(intFunc f)
{
return f();
}
int fortytwo()
{
return 42;
}
void myprint(char* s) {
printf("%s", s);
}
*/
import "C"
import (
"fmt"
"unsafe"
)
func main() {
f := C.intFunc(C.fortytwo)
fmt.Println(int(C.bridge_int_func(f)))
cs := C.CString("Hello from stdio\n")
C.myprint(cs)
C.free(unsafe.Pointer(cs))
}
// See https://github.com/golang/go/wiki/cgo
|
package main
import (
"fmt"
"bitbucket.org/egorsteam/bk-tree/internal"
levenshtein "github.com/creasty/go-levenshtein"
)
type word string
// Distance calculates hamming distance.
func (x word) Distance(e internal.ObjectTree) internal.TypeOfDistance {
a := string(x)
b := string(e.(word))
return internal.Int(levenshtein.Distance(a, b))
}
func main() {
var tree internal.Tree
// add words
words := []string{"apple", "banana", "orange", "peach", "bean", "tomato", "egg", "pineapple"}
for _, w := range words {
tree.Insert(word(w))
}
// spell check
results := tree.Search(word("peacn"), internal.Int(2))
fmt.Println("Input is peacn. Did you mean:")
for _, result := range results {
fmt.Printf("\t%s (distance: %d)\n", result.Object.(word), result.Distance)
}
}
|
// SPDX-License-Identifier: Apache-2.0
// Copyright The Linux Foundation
package exceptionmaker
import (
"fmt"
"net/url"
"strings"
"time"
"github.com/spdx/tools-golang/v0/spdx"
)
// MakeDocument creates an SPDX Document2_1 entry to which
// Packages will be added.
func MakeDocument() *spdx.Document2_1 {
datestr := time.Now().Format("2006-01-02")
ci := &spdx.CreationInfo2_1{
SPDXVersion: "SPDX-2.1",
DataLicense: "CC0-1.0",
SPDXIdentifier: "SPDXRef-DOCUMENT",
DocumentName: fmt.Sprintf("cncf-exceptions-%s", datestr),
DocumentNamespace: fmt.Sprintf("https://github.com/cncf/foundation/license-exceptions-%s", datestr),
CreatorOrganizations: []string{"CNCF"},
CreatorTools: []string{"cncf-exceptions-maker-0.1"},
Created: time.Now().Format("2006-01-02T15:04:05Z"),
}
return &spdx.Document2_1{
CreationInfo: ci,
Packages: []*spdx.Package2_1{},
}
}
// MakePackageFromRow creates an SPDX Package2_1 entry based on
// the contents of the spreadsheet row. It modifies and cleans up
// the data before returning the row.
func MakePackageFromRow(row []interface{}, rowNum int) (*spdx.Package2_1, error) {
rd, err := convertRow(row)
if err != nil {
return nil, fmt.Errorf("unable to extract details from row: %v", err)
}
parseRowDetails(rd)
cmt, err := prepComment(rd)
pkg := &spdx.Package2_1{
PackageName: rd.componentName,
PackageSPDXIdentifier: fmt.Sprintf("SPDXRef-Package%d", rowNum),
PackageDownloadLocation: "NOASSERTION",
FilesAnalyzed: false,
PackageLicenseConcluded: rd.SPDXlicenses,
PackageLicenseDeclared: "NOASSERTION",
PackageCopyrightText: "NOASSERTION",
}
if rd.isComponentNameURL {
pkg.PackageDownloadLocation = rd.componentName
}
if cmt != "" {
pkg.PackageComment = cmt
}
return pkg, nil
}
type rowDetails struct {
// extracted directly from row
componentName string
githubRepo string
comments string
licenses string
SPDXlicenses string
approved string
whitelisted string
approvalMechanism string
notWhitelistedBecause string
// filled in via parsing
isComponentNameURL bool
}
func convertRow(row []interface{}) (*rowDetails, error) {
// check that the row is the expected length
if len(row) != 9 {
return nil, fmt.Errorf("expected row of length %d, got %d", 9, len(row))
}
rd := rowDetails{}
var ok bool
rd.componentName, ok = row[0].(string)
if !ok {
return nil, fmt.Errorf("row[0] failed string type assertion, value is %v", row[0])
}
rd.githubRepo, ok = row[1].(string)
if !ok {
return nil, fmt.Errorf("row[1] failed string type assertion, value is %v", row[1])
}
rd.comments, ok = row[2].(string)
if !ok {
return nil, fmt.Errorf("row[2] failed string type assertion, value is %v", row[2])
}
rd.licenses, ok = row[3].(string)
if !ok {
return nil, fmt.Errorf("row[3] failed string type assertion, value is %v", row[3])
}
rd.SPDXlicenses, ok = row[4].(string)
if !ok {
return nil, fmt.Errorf("row[4] failed string type assertion, value is %v", row[4])
}
rd.approved, ok = row[5].(string)
if !ok {
return nil, fmt.Errorf("row[5] failed string type assertion, value is %v", row[5])
}
rd.whitelisted, ok = row[6].(string)
if !ok {
return nil, fmt.Errorf("row[6] failed string type assertion, value is %v", row[6])
}
rd.approvalMechanism, ok = row[7].(string)
if !ok {
return nil, fmt.Errorf("row[7] failed string type assertion, value is %v", row[7])
}
rd.notWhitelistedBecause, ok = row[8].(string)
if !ok {
return nil, fmt.Errorf("row[8] failed string type assertion, value is %v", row[8])
}
return &rd, nil
}
func parseRowDetails(rd *rowDetails) {
_, err := url.ParseRequestURI(rd.componentName)
rd.isComponentNameURL = (err == nil)
}
func prepComment(rd *rowDetails) (string, error) {
cmts := []string{}
if rd.comments != "" {
cmts = append(cmts, rd.comments)
}
if rd.whitelisted == "Yes" {
cmts = append(cmts, "whitelisted")
} else if rd.whitelisted == "N/A" {
if rd.approvalMechanism == "Apache-2.0 license" {
cmts = append(cmts, "Apache-2.0, no approval needed")
} else {
return "", fmt.Errorf("N/A for whitelisted but not Apache-2.0: %v", rd)
}
} else {
cmts = append(cmts, fmt.Sprintf("not whitelisted because: %s; approved by %s", rd.notWhitelistedBecause, rd.approvalMechanism))
}
return strings.Join(cmts, "; "), nil
}
|
package entity
import "time"
type ToDo struct {
Title string
Done bool
Limit time.Time
}
|
package Problem0407
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
// tcs is testcase slice
var tcs = []struct {
heightMap [][]int
ans int
}{
{
[][]int{
[]int{5, 5, 5, 1},
[]int{5, 1, 1, 5},
},
0,
},
{
[][]int{
[]int{5, 5, 5, 1},
[]int{5, 1, 1, 5},
[]int{5, 1, 5, 5},
[]int{5, 2, 5, 8},
},
3,
},
{
[][]int{
[]int{1, 4, 3, 1, 3, 2},
[]int{3, 2, 1, 3, 2, 4},
[]int{2, 3, 3, 2, 3, 1},
},
4,
},
{
[][]int{
[]int{12, 13, 1, 12},
[]int{13, 4, 13, 12},
[]int{13, 8, 10, 12},
[]int{12, 13, 12, 12},
[]int{13, 13, 13, 13},
},
14,
},
{
[][]int{
[]int{5, 5, 5, 5, 5},
[]int{5, 1, 1, 1, 5},
[]int{5, 1, 5, 5, 5},
[]int{5, 1, 1, 1, 5},
// 水会从这一行的 1 这里全部流出去,现有方法无法克服这种情况
[]int{5, 5, 5, 1, 5},
},
0,
},
// 可以有多个 testcase
}
func Test_trapRainWater(t *testing.T) {
ast := assert.New(t)
for _, tc := range tcs {
fmt.Printf("~~%v~~\n", tc)
ast.Equal(tc.ans, trapRainWater(tc.heightMap), "输入:%v", tc)
}
}
func Benchmark_trapRainWater(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range tcs {
trapRainWater(tc.heightMap)
}
}
}
|
/**
Copyright @ 2014 OPS, Qunar Inc. (qunar.com)
Author: tingfang.bao <tingfang.bao@qunar.com>
DateTime: 14-8-20 下午2:12
*/
package form
import (
"regexp"
"strconv"
"strings"
"unicode/utf8"
)
/**
定义消息映射
*/
const (
MSG_REQUIRED = "this field is required"
MSG_MAX_LENGTH = "length must less than {0}"
MSG_MIN_LENGTH = "length must more than {0}"
MSG_RANGE_LENGTH = "length must between {0} and {1}"
MSG_MAX = "value must small than {0}"
MSG_MIN = "value must large than {0}"
MSG_RANGE = "value must between {0} and {1}"
MSG_INVALID = "not a valid value"
)
/**
验证结果
*/
type ValidResult struct {
IsValid bool
ErrorMsg string
CleanValue interface{}
}
type ValidOption struct {
Required bool
NotTrim bool // not trim the Whitespace
// Max int
// Min int
Range [2]int
ErrorMsg string
}
/**
验证器接口
*/
type Validator interface {
Valid(value string, option *FieldOption) *ValidResult
}
type baseValidator struct {
}
/**
包含了
trim验证规则
required验证规则
*/
func (baseValidator *baseValidator) Valid(value string, opt *FieldOption) (string, *ValidResult) {
valid_result := &ValidResult{
CleanValue: "",
}
if opt == nil {
opt = &FieldOption{}
}
if !opt.NotTrim {
value = strings.TrimSpace(value)
}
if value == "" {
if opt.Required {
/**
如果调用方没有制定required的提示信息,就使用默认的
*/
if msg, ok := opt.errorMsg["required"]; ok {
valid_result.ErrorMsg = msg
} else {
valid_result.ErrorMsg = MSG_REQUIRED
}
} else {
valid_result.IsValid = true
}
}
return value, valid_result
}
/**
辅助工具类,如果从map中获取不到key对应的value,返回默认值
*/
func getOrDefault(m map[string]string, key, defaultVal string) string {
msg, ok := m[key]
if ok && msg != "" {
return msg
}
return defaultVal
}
/**
仅仅验证是否为数字,如果值为字符串,例如"123",也是可以通过验证的
*/
type numberValidator struct {
baseValidator
}
func (validator *numberValidator) Valid(value string, opt *FieldOption) (validate_result *ValidResult) {
/**
先调用父类方法,进行not trim,required的规则进行验证
*/
value, validate_result = validator.baseValidator.Valid(value, opt)
if validate_result.ErrorMsg != "" {
return validate_result
}
dotCount := 0
for i, c := range value {
if c < 48 || c > 57 {
if c == 46 && i != 0 && dotCount == 0 {
dotCount++
continue
}
validate_result.ErrorMsg = getOrDefault(opt.errorMsg, "invalid", "not a valid number")
return validate_result
}
}
validate_result.IsValid = true
/**
clean value仍然是字符串格式
*/
validate_result.CleanValue = value
return validate_result
}
/**
正则验证器
*/
type regexpValidator struct {
baseValidator
Regexp *regexp.Regexp
}
func (validator *regexpValidator) Valid(value string, opt *FieldOption) (validate_result *ValidResult) {
/**
先调用父类方法,进行not trim,required的规则进行验证
*/
value, validate_result = validator.baseValidator.Valid(value, opt)
if validate_result.IsValid || validate_result.ErrorMsg != "" {
return validate_result
}
ok := validator.Regexp.MatchString(value)
if ok {
validate_result.IsValid = true
validate_result.CleanValue = value
} else {
validate_result.ErrorMsg = getOrDefault(opt.errorMsg, "invalid", "not match")
}
return validate_result
}
/**
整型验证器
*/
type intValidator struct {
baseValidator
}
/**
err keys:
required
range
min
max
*/
func (validator *intValidator) Valid(value string, opt *FieldOption) (validate_result *ValidResult) {
/**
先调用父类方法,进行not trim,required的规则进行验证
*/
value, validate_result = validator.baseValidator.Valid(value, opt)
if validate_result.IsValid || validate_result.ErrorMsg != "" {
if validate_result.IsValid {
validate_result.CleanValue = 0
}
return validate_result
}
val, err := strconv.ParseInt(value, 10, 64)
validate_result.CleanValue = val
if err == nil {
if opt.Range[0] > 0 && val < int64(opt.Range[0]) {
if opt.Range[1] > 0 {
validate_result.ErrorMsg = strings.Replace(
getOrDefault(opt.errorMsg, "range", MSG_RANGE),
"{0}", strconv.Itoa(opt.Range[0]), -1)
validate_result.ErrorMsg = strings.Replace(validate_result.ErrorMsg, "{1}", strconv.Itoa(opt.Range[1]), -1)
} else {
validate_result.ErrorMsg = strings.Replace(
getOrDefault(opt.errorMsg, "min", MSG_MIN), "{0}", strconv.Itoa(opt.Range[0]), -1)
}
return validate_result
}
if opt.Range[1] > 0 && val > int64(opt.Range[1]) {
if opt.Range[0] > 0 {
validate_result.ErrorMsg = strings.Replace(
getOrDefault(opt.errorMsg, "range", MSG_RANGE), "{0}", strconv.Itoa(opt.Range[0]), -1)
validate_result.ErrorMsg = strings.Replace(validate_result.ErrorMsg, "{1}", strconv.Itoa(opt.Range[1]), -1)
} else {
validate_result.ErrorMsg = strings.Replace(
getOrDefault(opt.errorMsg, "max", MSG_MAX), "{0}", strconv.Itoa(opt.Range[1]), -1)
}
return validate_result
}
validate_result.IsValid = true
} else {
validate_result.ErrorMsg = getOrDefault(opt.errorMsg, "invalid", "not a int valid")
}
return validate_result
}
/**
字符串验证器
*/
type stringValidator struct {
baseValidator
}
/**
error keys:
required
range
min
max
*/
func (validator *stringValidator) Valid(value string, opt *FieldOption) (validate_result *ValidResult) {
/**
先调用父类方法,进行not trim,required的规则进行验证
*/
value, validate_result = validator.baseValidator.Valid(value, opt)
if validate_result.IsValid || validate_result.ErrorMsg != "" {
return validate_result
}
/**
utf8.RuneCountInString(str)
获取字符的个数
*/
if opt.Range[0] > 0 && utf8.RuneCountInString(value) < opt.Range[0] {
if opt.Range[1] > 0 {
validate_result.ErrorMsg = strings.Replace(
getOrDefault(opt.errorMsg, "range", MSG_RANGE_LENGTH),
"{0}", strconv.Itoa(opt.Range[0]), -1)
validate_result.ErrorMsg = strings.Replace(validate_result.ErrorMsg, "{1}", strconv.Itoa(opt.Range[1]), -1)
} else {
validate_result.ErrorMsg = strings.Replace(
getOrDefault(opt.errorMsg, "min", MSG_MIN_LENGTH), "{0}", strconv.Itoa(opt.Range[0]), -1)
}
return validate_result
}
if opt.Range[1] > 0 && utf8.RuneCountInString(value) > opt.Range[1] {
if opt.Range[0] > 0 {
validate_result.ErrorMsg = strings.Replace(
getOrDefault(opt.errorMsg, "range", MSG_RANGE_LENGTH), "{0}", strconv.Itoa(opt.Range[0]), -1)
validate_result.ErrorMsg = strings.Replace(validate_result.ErrorMsg, "{1}", strconv.Itoa(opt.Range[1]), -1)
} else {
validate_result.ErrorMsg = strings.Replace(
getOrDefault(opt.errorMsg, "max", MSG_MAX_LENGTH), "{0}", strconv.Itoa(opt.Range[1]), -1)
}
return validate_result
}
validate_result.IsValid = true
validate_result.CleanValue = value
return validate_result
}
|
package main
import (
"fmt"
"strings"
)
func SlackBlocks_FeedbackMsg(msg FeedbackMsg, text string) []interface{} {
if text == "" {
text = "How's it going? I'm here to get an update on the status of your bagel chat 😁"
}
return []interface{}{
map[string]interface{}{
"type": "section",
"text": map[string]interface{}{
"type": "mrkdwn",
"text": text,
},
},
map[string]interface{}{
"type": "actions",
"elements": []map[string]interface{}{
{
"type": "button",
"action_id": msg.IncompleteActionID,
"text": map[string]string{
"type": "plain_text",
"text": "We're not planning to meet",
},
},
{
"type": "button",
"action_id": msg.PlannedActionID,
"text": map[string]string{
"type": "plain_text",
"text": "We've planned our bagel chat",
},
},
{
"type": "button",
"action_id": msg.CompletedActionID,
"text": map[string]string{
"type": "plain_text",
"text": "We've had our bagel chat",
},
},
},
},
}
}
func ToEnglish_JoinAnd(elements []string) string {
if len(elements) == 0 {
return ""
} else if len(elements) == 1 {
return elements[0]
} else if len(elements) == 2 {
return fmt.Sprintf("%s and %s", elements[0], elements[1])
} else {
return strings.Join(elements[:len(elements)-1], ", ") + ", and " + elements[len(elements)-1]
}
}
func SlackBlocks_FeedbackStatistics(completed int, firstGroupCompleted []string, planned int) []interface{} {
text := "📊 I've got some statistics about bagel chats. Thank you to all who have participated."
var firstGroupShoutOut string
if firstGroupCompleted == nil {
firstGroupShoutOut = ""
} else {
firstGroupShoutOut = fmt.Sprintf("Shout out to %s for being the first group to chat it up.", ToEnglish_JoinAnd(firstGroupCompleted))
}
return []interface{}{
map[string]interface{}{
"type": "section",
"text": map[string]interface{}{
"type": "mrkdwn",
"text": text,
},
},
map[string]interface{}{
"type": "section",
"text": map[string]interface{}{
"type": "mrkdwn",
"text": fmt.Sprintf(" • *%d* members have *completed* their bagel chats. %s", completed, firstGroupShoutOut),
},
},
map[string]interface{}{
"type": "section",
"text": map[string]interface{}{
"type": "mrkdwn",
"text": fmt.Sprintf(" • *%d* members have *planned* their bagel chats. Make sure to post a selfie (or a screenshot) to the #bagel-chats channel, and don't forget to mark that you've completed your bagel chat once you've met up.", planned),
},
},
}
}
|
package main
import (
"bufio"
"encoding/json"
"fmt"
"log"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
)
// Send is responsible for sending messages through a
// generic stream-oriented network connection
func send(id int, conn *net.Conn, request []byte) error {
var err error
var n int
n, err = (*conn).Write(request)
// fmt.Printf("[worker: %d] SENDING to (%s): %s\n", id, (*conn).RemoteAddr(), request)
for n < len(request) {
n, err = (*conn).Write(request[n:])
if err != nil {
break
}
}
return err
}
type ftpMetadata struct {
fileName string
fileSize string
isDir bool
}
type ftpConnection struct {
conn *net.Conn
mu *sync.Mutex
}
type connectionsPool struct {
container map[string]*ftpConnection
mu *sync.Mutex
}
type ftpWorker struct {
id int
wg *sync.WaitGroup
ftpConns *connectionsPool
connsChan chan net.Conn
requestsChan chan processorRequestDTO
}
func newConnectionsPool() *connectionsPool {
return &connectionsPool{
container: make(map[string]*ftpConnection),
mu: &sync.Mutex{},
}
}
func newFtpWorker(id int, wg *sync.WaitGroup, ftpConns *connectionsPool, connsChan chan net.Conn, reqChan chan processorRequestDTO) *ftpWorker {
return &ftpWorker{
id: id,
wg: wg,
ftpConns: ftpConns,
connsChan: connsChan,
requestsChan: reqChan,
}
}
func (w *ftpWorker) sendCommand(conn *net.Conn, request []byte) error {
var err error
var n int
n, err = fmt.Fprintf((*conn), string(request))
for n < len(request) {
n, err = fmt.Fprintf((*conn), string(request[n:]))
if err != nil {
break
}
}
fmt.Printf("[worker: %d] [CLIENT] %s", w.id, string(request))
return err
}
func (w *ftpWorker) checkResponse(message string, code string) error {
fmt.Printf("[worker: %d] [SERVER] %s", w.id, message)
if !(strings.Contains(message, code)) {
return fmt.Errorf("Expected: %s but received: %s", code, message)
}
return nil
}
func (w *ftpWorker) reply(conn *net.Conn, message string, errMsg string) error {
processorMessage, err := json.Marshal(
processorResponseDTO{
Message: message,
Error: errMsg})
if err != nil {
return err
}
return send(w.id, conn, processorMessage)
}
func (w *ftpWorker) login(processorRequest processorRequestDTO) (*net.Conn, error) {
host := processorRequest.Host + ":21"
conn, err := net.Dial("tcp", host) // We won't close this since we will return it
if err != nil {
return nil, fmt.Errorf("[CLIENT] Fatal error: %s", err.Error())
}
connReader := bufio.NewReader(conn)
message, _ := connReader.ReadString('\n')
if err := w.checkResponse(message, "220"); err != nil {
conn.Close()
return nil, fmt.Errorf("[CLIENT] Fatal error: %s", err.Error())
}
w.sendCommand(&conn, []byte("USER "+processorRequest.User+"\n"))
message, _ = connReader.ReadString('\n')
if err := w.checkResponse(message, "331"); err != nil {
conn.Close()
return nil, fmt.Errorf("[CLIENT] Fatal error: %s", err.Error())
}
w.sendCommand(&conn, []byte("PASS "+processorRequest.Password+"\n"))
message, _ = connReader.ReadString('\n')
if err := w.checkResponse(message, "230"); err != nil {
conn.Close()
return nil, fmt.Errorf("[CLIENT] Fatal error: %s", err.Error())
}
fmt.Printf("[worker: %d] [CLIENT] Logged in to FTP server\n", w.id)
return &conn, nil
}
func (w *ftpWorker) getConnection(processorRequest processorRequestDTO) (conn *net.Conn, err error) {
id := processorRequest.Host
if _, ok := w.ftpConns.container[id]; ok {
w.ftpConns.container[id].mu.Lock()
fmt.Printf("[worker: %d] [CLIENT] Found connection in container Pool for: %s\n", w.id, id)
return w.ftpConns.container[id].conn, nil
}
return nil, fmt.Errorf("Connection not found for host: %s", processorRequest.Host)
// w.ftpConns.mu.Lock()
// defer w.ftpConns.mu.Unlock()
// conn, err = w.login(processorRequest)
// if err != nil {
// return nil, err
// }
// w.ftpConns.container[id] = &ftpConnection{conn: conn, mu: &sync.Mutex{}}
// return conn, nil
}
func (w *ftpWorker) releaseConnection(processorRequest processorRequestDTO) {
w.ftpConns.container[processorRequest.Host].mu.Unlock()
}
func (w *ftpWorker) saveConnection(conn *net.Conn, processorRequest processorRequestDTO) {
id := processorRequest.Host
w.ftpConns.mu.Lock()
defer w.ftpConns.mu.Unlock()
w.ftpConns.container[id] = &ftpConnection{conn: conn, mu: &sync.Mutex{}}
}
func (w *ftpWorker) store(request processorRequestDTO, fileName string, sFileSize string, isDir bool) error {
persistorConn, err := net.Dial("tcp", setup.getPersistorHost())
if err != nil {
return err
}
defer persistorConn.Close()
fileSize, _ := strconv.Atoi(sFileSize)
persistorRequest, err := json.Marshal(persistorRequestDTO{
Host: request.Host,
Action: "add",
Path: request.Path,
FileName: fileName,
FileSize: fileSize,
IsDir: isDir,
})
if err != nil {
return err
}
return send(w.id, &persistorConn, persistorRequest)
}
func (w *ftpWorker) updateStatus(request processorRequestDTO, fileName string, isDir bool) error {
statusConn, err := net.Dial("tcp", setup.getStatusHost())
if err != nil {
return err
}
defer statusConn.Close()
// If it is a directory, we add one to the pending status count
// If it is a file, we substract one to the pending status count
pending := -1
if isDir {
pending = 1
}
statusRequest, err := json.Marshal(statusRequestDTO{
Host: request.Host,
Action: "update",
Path: request.Path,
Pending: pending,
})
if err != nil {
return err
}
return send(w.id, &statusConn, statusRequest)
}
func (w *ftpWorker) listSubdir(request processorRequestDTO, fileName string) {
w.requestsChan <- processorRequestDTO{
Host: request.Host,
Path: filepath.Join(request.Path, fileName),
Action: "LIST",
}
}
// func (w *ftpWorker) handleRunError(err error, conn *net.Conn) bool {
// if err != nil {
// fmt.Fprintf(os.Stderr, "[worker: %d] [CLIENT] Fatal error: %s\n", w.id, err.Error())
// if err := w.reply(conn, "", err.Error()); err != nil {
// fmt.Fprintf(os.Stderr, "[worker: %d] [CLIENT] Fatal error: %s\n", w.id, err.Error())
// }
// return true
// }
// return false
// }
func (w *ftpWorker) failOnError(err error) {
if err != nil {
log.Fatalf("[worker: %d] Fatal error: %s\n", w.id, err.Error())
}
}
func (w *ftpWorker) processRequest(processorRequest processorRequestDTO) {
// Send PASV command and check response
ftpConn, err := w.getConnection(processorRequest)
w.failOnError(err)
connReader := bufio.NewReader(*ftpConn)
w.failOnError(w.sendCommand(ftpConn, []byte("PASV\n")))
message, err := connReader.ReadString('\n')
w.failOnError(err)
w.failOnError(w.checkResponse(message, "227"))
// Scan PASV response and build HOST:PORT to FTP Data Conn
var portPref, portSuff, port, ip1, ip2, ip3, ip4 int
_, err = fmt.Sscanf(message, "227 Entering Passive Mode (%d,%d,%d,%d,%d,%d).",
&ip1, &ip2, &ip3, &ip4, &portPref, &portSuff)
w.failOnError(err)
port = portPref*256 + portSuff
dataHost := processorRequest.Host + ":" + fmt.Sprintf("%d", port)
// Make FTP Data Conn
dataConn, err := net.Dial("tcp", dataHost)
w.failOnError(err)
// Send LIST command and check response
w.failOnError(w.sendCommand(ftpConn, []byte(fmt.Sprintf("LIST %s\n", processorRequest.Path))))
message, err = connReader.ReadString('\n')
w.failOnError(err)
w.failOnError(w.checkResponse(message, "150"))
// Check for finished Listing
message, err = connReader.ReadString('\n')
w.failOnError(err)
w.failOnError(w.checkResponse(message, "226"))
w.releaseConnection(processorRequest)
dconnbuf := bufio.NewScanner(dataConn)
var files []ftpMetadata
// Parse response from FTP Data Conn and
// send response to Status Controller, Persistor and Storage
for dconnbuf.Scan() {
buff := dconnbuf.Text()
fields := strings.Fields(buff)
files = append(files, ftpMetadata{
fileName: fields[8],
fileSize: fields[4],
isDir: strings.Contains(fields[0], "d"),
})
}
w.failOnError(dconnbuf.Err())
for _, val := range files {
if err := w.store(processorRequest, val.fileName, val.fileSize, val.isDir); err != nil {
fmt.Fprintf(os.Stderr, "[worker: %d] Fatal error: %s\n", w.id, err.Error())
break
}
if err := w.updateStatus(processorRequest, val.fileName, val.isDir); err != nil {
fmt.Fprintf(os.Stderr, "[worker: %d] Fatal error: %s\n", w.id, err.Error())
break
}
if val.isDir && val.fileName != "sys" {
w.listSubdir(processorRequest, val.fileName)
}
}
}
func (w *ftpWorker) run() {
defer w.wg.Done()
for {
select {
case processorConn := <-w.connsChan:
// Decodes new incoming connection from channel
var processorRequest processorRequestDTO
w.failOnError(json.NewDecoder(processorConn).Decode(&processorRequest))
fmt.Printf("[worker: %d] [host: %s] [user: %v] [path: %s]\n",
w.id, processorRequest.Host, processorRequest.User, processorRequest.Path)
// If its just a login, we return early
if processorRequest.Action == "LOGIN" {
ftpConn, _ := w.login(processorRequest)
w.saveConnection(ftpConn, processorRequest)
w.reply(&processorConn, "OK", "")
return
}
w.requestsChan <- processorRequest
w.reply(&processorConn, "OK", "")
processorConn.Close()
case request := <-w.requestsChan:
w.processRequest(request)
}
}
}
func main() {
var err error
var listener net.Listener
var workersWg sync.WaitGroup
fmt.Println("Listening on " + setup.getProcessorHost())
listener, err = net.Listen("tcp", setup.getProcessorHost())
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s\n", err.Error())
return
}
defer listener.Close()
ftpConnections := newConnectionsPool()
processorConnectionsChan := make(chan net.Conn, 1000)
processorRequestsChan := make(chan processorRequestDTO, 10000)
for w := 1; w <= setup.getWorkersProcessor(); w++ {
workersWg.Add(1)
processorWorker := newFtpWorker(w, &workersWg, ftpConnections, processorConnectionsChan, processorRequestsChan)
go processorWorker.run()
}
for {
processorConn, err := (listener).Accept()
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s\n", err.Error())
continue
}
processorConnectionsChan <- processorConn
}
workersWg.Wait()
}
|
package processors
import (
"github.com/vmware/kube-fluentd-operator/config-reloader/fluentd"
)
const (
dirPlugin = "plugin"
)
// ExtractPlugins looks at the top-level directives in the admin namespace, deletes all <plugin>
// and stores the found plugin definitions under GenerationContext.Plugins map keyed by the plugin directive's path
func ExtractPlugins(g *GenerationContext, input fluentd.Fragment) fluentd.Fragment {
plugins := map[string]*fluentd.Directive{}
res := fluentd.Fragment{}
// process only top-level plugin directives
for _, dir := range input {
if dir.Name == dirPlugin {
plugins[dir.Tag] = dir
} else {
res = append(res, dir)
}
}
g.Plugins = plugins
return res
}
type expandPluginsState struct {
BaseProcessorState
}
func (p *expandPluginsState) Process(input fluentd.Fragment) (fluentd.Fragment, error) {
if len(p.Context.GenerationContext.Plugins) == 0 {
// nothing to expand
return input, nil
}
f := func(d *fluentd.Directive, ctx *ProcessorContext) error {
if d.Name != "match" && d.Name != "store" {
// only output plugins supported
return nil
}
replacement, ok := p.Context.GenerationContext.Plugins[d.Type()]
if !ok {
return nil
}
// replace any nested content (buffers etc)
// there is no option to redefine nested content
d.Nested = replacement.Nested.Clone()
// replace the params
for k, v := range replacement.Params {
// prefer the params defined at the call site
if _, ok := d.Params[k]; !ok {
d.Params[k] = v.Clone()
}
}
// always change the type
d.SetParam("@type", replacement.Type())
// delete type parameter (someone is using the old syntax without @)
delete(d.Params, "type")
return nil
}
err := applyRecursivelyInPlace(input, p.Context, f)
if err != nil {
return nil, err
}
return input, nil
}
|
package main
import (
"bytes"
"fmt"
"io"
"log"
"net"
"runtime"
"sync"
)
var wg sync.WaitGroup
func init() {
log.SetFlags(log.Lshortfile)
}
func main() {
engine1()
}
func engine1() {
wg.Add(2)
lTcpAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:8090")
if err != nil {
log.Fatalln(err)
}
rTcpAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:8080")
if err != nil {
log.Fatalln(err)
}
tcpCon, err := net.DialTCP(lTcpAddr.Network(), lTcpAddr, rTcpAddr) //TCP拨号连接
defer tcpCon.Close()
if err != nil {
log.Fatalln(err)
}
senRecByts := make([]byte, 1024) //收发数据缓冲区
go send1(tcpCon, senRecByts)
go receive1(tcpCon, senRecByts)
wg.Wait()
}
func receive1(tcpCon *net.TCPConn, senRecByts []byte) {
for {
length, err := tcpCon.Read(senRecByts) //接收
if err != nil || err == io.EOF {
log.Fatalf("%s\t服务端关闭连接", err)
}
fmt.Printf("接收: %s\n", senRecByts[:length])
}
}
func send1(tcpCon *net.TCPConn, senRecByts []byte) {
for {
fmt.Print("请输入: ")
fmt.Scan(&senRecByts)
senRecByts = bytes.NewBuffer(senRecByts).Bytes()
length, err := tcpCon.Write(senRecByts) //发送
if err != nil {
log.Println(err)
runtime.Goexit()
}
fmt.Printf("发送字节: %d\n", length)
}
}
|
package models_test
import (
"github.com/APTrust/exchange/models"
"github.com/APTrust/exchange/util/testutil"
"github.com/stretchr/testify/assert"
"testing"
)
func TestNewRestoreState(t *testing.T) {
restoreState := models.NewRestoreState(testutil.MakeNsqMessage("999"))
assert.NotNil(t, restoreState.PackageSummary)
assert.NotNil(t, restoreState.ValidateSummary)
assert.NotNil(t, restoreState.CopySummary)
assert.NotNil(t, restoreState.RecordSummary)
}
func TestRestoreState_HasErrors(t *testing.T) {
restoreState := models.NewRestoreState(testutil.MakeNsqMessage("999"))
assert.False(t, restoreState.HasErrors())
restoreState.PackageSummary.AddError("error")
assert.True(t, restoreState.HasErrors())
restoreState.PackageSummary.ClearErrors()
assert.False(t, restoreState.HasErrors())
restoreState.ValidateSummary.AddError("error")
assert.True(t, restoreState.HasErrors())
restoreState.ValidateSummary.ClearErrors()
assert.False(t, restoreState.HasErrors())
restoreState.CopySummary.AddError("error")
assert.True(t, restoreState.HasErrors())
restoreState.CopySummary.ClearErrors()
assert.False(t, restoreState.HasErrors())
restoreState.RecordSummary.AddError("error")
assert.True(t, restoreState.HasErrors())
restoreState.RecordSummary.ClearErrors()
assert.False(t, restoreState.HasErrors())
}
func TestRestoreState_HasFatalErrors(t *testing.T) {
restoreState := models.NewRestoreState(testutil.MakeNsqMessage("999"))
assert.False(t, restoreState.HasFatalErrors())
restoreState.PackageSummary.ErrorIsFatal = true
assert.True(t, restoreState.HasFatalErrors())
restoreState.PackageSummary.ClearErrors()
assert.False(t, restoreState.HasFatalErrors())
restoreState.ValidateSummary.ErrorIsFatal = true
assert.True(t, restoreState.HasFatalErrors())
restoreState.ValidateSummary.ClearErrors()
assert.False(t, restoreState.HasFatalErrors())
restoreState.CopySummary.ErrorIsFatal = true
assert.True(t, restoreState.HasFatalErrors())
restoreState.CopySummary.ClearErrors()
assert.False(t, restoreState.HasFatalErrors())
restoreState.RecordSummary.ErrorIsFatal = true
assert.True(t, restoreState.HasFatalErrors())
restoreState.RecordSummary.ClearErrors()
assert.False(t, restoreState.HasFatalErrors())
}
func TestRestoreState_AllErrorsAsString(t *testing.T) {
restoreState := models.NewRestoreState(testutil.MakeNsqMessage("999"))
assert.False(t, restoreState.HasErrors())
restoreState.PackageSummary.AddError("error 1")
restoreState.PackageSummary.AddError("error 2")
restoreState.ValidateSummary.AddError("error 3")
restoreState.RecordSummary.AddError("error 4")
restoreState.RecordSummary.AddError("error 5")
restoreState.CopySummary.AddError("error 6")
expected := "error 1\nerror 2\nerror 3\nerror 4\nerror 5\nerror 6\n"
assert.Equal(t, expected, restoreState.AllErrorsAsString())
}
func TestRestoreState_MostRecentSummary(t *testing.T) {
restoreState := models.NewRestoreState(testutil.MakeNsqMessage("999"))
assert.Equal(t, restoreState.PackageSummary, restoreState.MostRecentSummary())
restoreState.ValidateSummary.Start()
assert.Equal(t, restoreState.ValidateSummary, restoreState.MostRecentSummary())
restoreState.CopySummary.Start()
assert.Equal(t, restoreState.CopySummary, restoreState.MostRecentSummary())
restoreState.RecordSummary.Start()
assert.Equal(t, restoreState.RecordSummary, restoreState.MostRecentSummary())
}
|
package server
import (
"encoding/json"
"errors"
"sync"
"github.com/dchanman/tactics/src/game"
"github.com/sirupsen/logrus"
)
const (
nMaxPlayers = 2
rowsLarge = 10
colsLarge = 7
rowsOfPiecesLarge = 3
rowsSmall = 8
colsSmall = 5
rowsOfPiecesSmall = 2
)
var (
errInvalidBoardType = errors.New("invalid game type")
errGameOver = errors.New("Game is over")
errPlayerNotPlaying = errors.New("Player is not playing")
errInvalidSquare = errors.New("invalid square")
errPlayerWrongTeam = errors.New("Player is moving the wrong piece")
)
// Game is the main game engine
type Game struct {
gameType BoardType
board *game.Board
initialBoard *game.Board
subscribers map[uint64](chan Notification)
movesQueue chan gameMove
history []Turn
completed bool
teamToPlayerID []uint64
teamToPlayerIDMutex sync.Mutex
player1ready bool
player2ready bool
}
// BoardType determines the type of the game (board size, pieces, etc)
type BoardType string
const (
// BoardTypeSmall is a 8x5 2 row configuration
BoardTypeSmall BoardType = "small"
// BoardTypeLarge is a 10x8 3 row configuration
BoardTypeLarge = "large"
)
// UnmarshalJSON validates BoardTypes
func (gt *BoardType) UnmarshalJSON(b []byte) error {
var s string
err := json.Unmarshal(b, &s)
if err != nil {
return err
}
ret := BoardType(s)
if ret == BoardTypeSmall || ret == BoardTypeLarge {
*gt = ret
return nil
}
return errInvalidBoardType
}
type gameMove struct {
move game.Move
team game.Team
reset bool
}
// Turn is a set of moves made by all players
type Turn map[game.Team]game.Move
// NewTurn constructs a new Turn
func NewTurn(move1 game.Move, move2 game.Move) Turn {
moves := make(Turn)
moves[1] = move1
moves[2] = move2
return moves
}
// Information contains player information
type Status struct {
P1Available bool `json:"p1available"`
P2Available bool `json:"p2available"`
P1Ready bool `json:"p1ready"`
P2Ready bool `json:"p2ready"`
}
type Information struct {
Status
InitialBoard *game.Board `json:"board"`
History []Turn `json:"history"`
}
// NewGame constructs a new Game
func NewGame(gameType BoardType) *Game {
game := Game{
gameType: gameType,
initialBoard: createGameBoard(gameType),
subscribers: make(map[uint64](chan Notification)),
movesQueue: make(chan gameMove, gameMoveBuffer),
teamToPlayerID: make([]uint64, nMaxPlayers+1)}
game.initGameState()
go game.waitForMoves()
return &game
}
func (g *Game) initGameState() {
// TODO: just copy g.initialGameBoard
g.board = createGameBoard(g.gameType)
g.history = make([]Turn, 0)
g.completed = false
}
// ResetBoard resets the board
func (g *Game) ResetBoard() {
g.initGameState()
g.movesQueue <- gameMove{reset: true}
g.publishUpdate()
}
func createGameBoard(gameType BoardType) *game.Board {
var nCols int
var nRows int
var nRowsOfPieces int
switch gameType {
case BoardTypeSmall:
nCols = colsSmall
nRows = rowsSmall
nRowsOfPieces = rowsOfPiecesSmall
case BoardTypeLarge:
nCols = colsLarge
nRows = rowsLarge
nRowsOfPieces = rowsOfPiecesLarge
}
b := game.NewBoard(nCols, nRows)
// Add pieces
for i := 0; i < nCols; i++ {
for j := 0; j < nRowsOfPieces; j++ {
b.Set(i, 1+j, game.Unit{Team: 2, Stack: 1, Exists: true})
b.Set(i, nRows-2-j, game.Unit{Team: 1, Stack: 1, Exists: true})
}
}
return &b
}
func (g *Game) waitForMoves() {
var move1 game.Move
var move2 game.Move
var resolution game.Resolution
g.player1ready = false
g.player2ready = false
for m := range g.movesQueue {
winner := false
if m.reset {
g.player1ready = false
g.player2ready = false
} else if m.team == 1 {
g.player1ready = true
move1 = m.move
} else if m.team == 2 {
g.player2ready = true
move2 = m.move
}
if g.player1ready && g.player2ready {
g.player1ready = false
g.player2ready = false
resolution = g.board.ResolveMove(move1, move2)
winner = resolution.Winner
g.history = append(g.history, NewTurn(move1, move2))
g.publishTurn()
}
g.publishStatus()
if winner {
g.completed = true
g.publishVictory(resolution.Team)
}
}
}
// Assumes g.teamToPlayerIDMutex is taken
func (g *Game) getTeamForPlayerID(id uint64) game.Team {
for team, pid := range g.teamToPlayerID {
if pid == id {
return game.Team(team)
}
}
return 0
}
// CommitMove is called from a client to commit a move on behalf of a player
func (g *Game) CommitMove(id uint64, src game.Square, dst game.Square) error {
g.teamToPlayerIDMutex.Lock()
defer g.teamToPlayerIDMutex.Unlock()
team := g.getTeamForPlayerID(id)
if g.completed {
return errGameOver
}
if team == 0 {
return errPlayerNotPlaying
}
if !g.board.IsValid(src.X, src.Y) || !g.board.IsValid(dst.X, dst.Y) {
return errInvalidSquare
}
if !g.board.Get(src.X, src.Y).Exists || g.board.Get(src.X, src.Y).Team != team {
return errPlayerWrongTeam
}
move := game.Move{Src: src, Dst: dst}
g.movesQueue <- gameMove{team: team, move: move}
return nil
}
func (g *Game) GetValidMoves(id uint64, x int, y int) []game.Square {
u := g.board.Get(x, y)
if !g.completed && u.Exists {
g.teamToPlayerIDMutex.Lock()
defer g.teamToPlayerIDMutex.Unlock()
if u.Team == g.getTeamForPlayerID(id) {
return g.board.GetValidMoves(x, y)
}
}
return make([]game.Square, 0)
}
// Subscribe implements Subscriber interface
func (g *Game) Subscribe(id uint64) chan Notification {
if _, exists := g.subscribers[id]; exists {
log.WithFields(logrus.Fields{"id": id}).Error("Duplicate ID")
return nil
}
g.subscribers[id] = make(chan Notification, gameSubscriberBuffer)
return g.subscribers[id]
}
// Unsubscribe implements Subscriber interface
func (g *Game) Unsubscribe(id uint64) {
if _, exists := g.subscribers[id]; !exists {
log.WithFields(logrus.Fields{"id": id}).Error("Unsubscribing invalid ID")
return
}
delete(g.subscribers, id)
}
func (g *Game) getStatus() Status {
return Status{
P1Available: g.teamToPlayerID[1] != 0,
P2Available: g.teamToPlayerID[2] != 0,
P1Ready: g.player1ready,
P2Ready: g.player2ready}
}
// GetInformation returns the current status of the game
func (g *Game) GetInformation() Information {
return Information{
InitialBoard: g.initialBoard,
History: g.history,
Status: g.getStatus()}
}
func (g *Game) publishUpdate() {
notif := Notification{
Method: "Game.Update",
Params: g.GetInformation()}
for _, ch := range g.subscribers {
ch <- notif
}
}
func (g *Game) publishStatus() {
notif := Notification{
Method: "Game.Status",
Params: g.getStatus()}
for _, ch := range g.subscribers {
ch <- notif
}
}
func (g *Game) publishTurn() {
notif := Notification{
Method: "Game.Turn",
Params: g.history}
for _, ch := range g.subscribers {
ch <- notif
}
}
func (g *Game) publishVictory(team game.Team) {
notif := Notification{
Method: "Game.Over",
Params: struct {
Team game.Team `json:"team"`
}{team}}
for _, ch := range g.subscribers {
ch <- notif
}
}
func (g *Game) getPlayerReadyStatus() (bool, bool) {
return g.player1ready, g.player2ready
}
// GetPlayerIDs returns the IDs of the players currently playing the game
func (g *Game) GetPlayerIDs() (uint64, uint64) {
return g.teamToPlayerID[1], g.teamToPlayerID[2]
}
// JoinGame sets an ID as a player currently playing the game
func (g *Game) JoinGame(team int, id uint64) bool {
g.teamToPlayerIDMutex.Lock()
defer g.teamToPlayerIDMutex.Unlock()
if team > 0 && team <= nMaxPlayers {
if g.teamToPlayerID[team] == 0 {
g.teamToPlayerID[team] = id
g.publishStatus()
return true
}
}
log.WithFields(
logrus.Fields{
"pid": id,
"team": team,
"p1": g.teamToPlayerID[1],
"p2": g.teamToPlayerID[2]}).
Error("Could not join")
return false
}
// QuitGame allows a player currently playing the game to quit
func (g *Game) QuitGame(id uint64) {
g.teamToPlayerIDMutex.Lock()
defer g.teamToPlayerIDMutex.Unlock()
team := g.getTeamForPlayerID(id)
if team > 0 {
g.teamToPlayerID[team] = 0
go g.publishUpdate()
}
}
|
package agency
import (
"bytes"
"encoding/csv"
"strconv"
)
// maxRank is the highest rank that can be used by the data files.
const maxRank = 5
type browser struct {
rank int
typ string
name string
token []byte
}
var browsers []*browser
func init() {
data, _ := dataBrowserCsv()
records, err := csv.NewReader(bytes.NewBuffer(data.bytes)).ReadAll()
if err != nil {
panic("parse error (browser.csv): " + err.Error())
}
for _, record := range records {
rank, _ := strconv.Atoi(record[0])
browsers = append(browsers, &browser{rank, record[1], record[2], []byte(record[3])})
}
}
type device struct {
rank int
typ string
token []byte
}
var devices []*device
func init() {
data, _ := dataDeviceCsv()
records, err := csv.NewReader(bytes.NewBuffer(data.bytes)).ReadAll()
if err != nil {
panic("parse error (device.csv): " + err.Error())
}
for _, record := range records {
rank, _ := strconv.Atoi(record[0])
devices = append(devices, &device{rank, record[1], []byte(record[2])})
}
}
type mobile struct {
token []byte
}
var mobiles []*mobile
func init() {
data, _ := dataMobileCsv()
records, err := csv.NewReader(bytes.NewBuffer(data.bytes)).ReadAll()
if err != nil {
panic("parse error (mobile.csv): " + err.Error())
}
for _, record := range records {
mobiles = append(mobiles, &mobile{[]byte(record[0])})
}
}
type aos struct {
rank int
name string
version string
token []byte
}
var oses []*aos
func init() {
data, _ := dataOsCsv()
records, err := csv.NewReader(bytes.NewBuffer(data.bytes)).ReadAll()
if err != nil {
panic("parse error (os.csv): " + err.Error())
}
for _, record := range records {
rank, _ := strconv.Atoi(record[0])
oses = append(oses, &aos{rank, record[1], record[2], []byte(record[3])})
}
}
|
package fetcher
import (
"io"
"text/template"
)
const templateText = `
<?xml version="1.0" encoding="UTF-8"?>
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
{{range .}}
<url><loc>{{.Url}}</loc><lastmod>{{.TimeStamp}}</lastmod></url>
{{- end}}
</urlset>
`
func Render(wr io.Writer, urls []Url) error {
t := template.Must(template.New("sitemap").Parse(templateText))
err := t.Execute(wr, urls)
if err != nil {
return err
}
return nil
}
|
package machine
import (
"bytes"
"testing"
"github.com/disposedtrolley/goz/internal/memory"
"github.com/disposedtrolley/goz/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDecodeZString(t *testing.T) {
tests := []struct {
Name string
Gamefile test.Gamefile
Version int
MemoryOffset memory.Address
ExpectedASCII string
}{
{
Name: "when a string with abbreviations is decoded - v3",
Gamefile: test.ZorkZ3,
Version: 3,
MemoryOffset: 0x6EE4,
ExpectedASCII: "ZORK I: The Great Underground Empire\nCopyright (c) 1981, 1982, 1983 Infocom, Inc. ",
},
{
Name: "when a long Z-string is decoded - v3",
Gamefile: test.ZorkZ3,
Version: 3,
MemoryOffset: 0x10EEE,
ExpectedASCII: "\"WELCOME TO ZORK!\n\nZORK is a game of adventure, danger, and low cunning. In it you will explore some of the most amazing territory ever seen by mortals. No computer should be without one!\"\n",
},
{
Name: "when a string with ZSCII characters is decoded - v3",
Gamefile: test.ZorkZ3,
Version: 3,
MemoryOffset: 0x5908,
ExpectedASCII: ">",
},
{
Name: "when a string with abbreviations is decoded - v8",
Gamefile: test.JigsawZ8,
Version: 8,
MemoryOffset: 0x38631,
ExpectedASCII: " Welcome to JIGSAW\n",
},
{
Name: "when a long Z-string is decoded - v8",
Gamefile: test.JigsawZ8,
Version: 8,
MemoryOffset: 0x314BC,
ExpectedASCII: "\nNew Year's Eve, 1999, a quarter to midnight and where else to be but Century Park! Fireworks cascade across the sky, your stomach rumbles uneasily, music and lasers howl across the parkland... Not exactly your ideal party (especially as that rather attractive stranger in black has slipped back into the crowds) - but cheer up, you won't live to see the next.\n\n",
},
}
for _, tc := range tests {
t.Run(tc.Name, func(t *testing.T) {
game, err := test.ReadGamfile(tc.Gamefile)
require.Nil(t, err, "should not error when reading gamefile")
m := NewMachine(game)
m.WithVersion(tc.Version)
str := m.decodeZstring(tc.MemoryOffset)
assert.Equal(t, tc.ExpectedASCII, str)
})
}
}
func TestOutput(t *testing.T) {
game, err := test.ReadGamfile(test.JigsawZ8)
require.Nil(t, err, "should not error when reading gamefile")
m := NewMachine(game)
m.WithVersion(8)
var buf bytes.Buffer
m.SetOutput(&buf)
m.Start()
assert.Equal(t,
"z8 gamefile weighing in at 304640 bytes\n\nbeginning of:\n static memory: 6fc6\n high memory: bc60\n",
buf.String(),
"should write to the supplied buffer")
} |
package nougat
import (
"net/http"
)
// Doer executes http requests. It is implemented by *http.Client. You can
// wrap *http.Client with layers of Doers to form a stack of client-side
// middleware.
type Doer interface {
Do(req *http.Request) (*http.Response, error)
}
// Sending
type APIError struct {
Message string `json:"message"`
Code int `json:"code"`
}
// Nougat is an HTTP Request builder and sender.
type Nougat struct {
// http Client for doing requests
httpClient Doer
// HTTP method (GET, POST, etc.)
method string
// raw url string for requests
rawURL string
// stores key-values pairs to add to request's Headers
header http.Header
// url tagged query structs
queryStructs []interface{}
// body provider
bodyProvider BodyProvider
// response decoder
responseDecoder ResponseDecoder
}
// New returns a new Nougat with an http DefaultClient.
func New() *Nougat {
return &Nougat{
httpClient: http.DefaultClient,
method: "GET",
header: make(http.Header),
queryStructs: make([]interface{}, 0),
responseDecoder: jsonDecoder{},
}
}
// New returns a copy of a Nougat for creating a new Nougat with properties
// from a parent Nougat. For example,
//
// parentNougat := Nougat.New().Client(client).Base("https://api.io/")
// fooNougat := parentNougat.New().Get("foo/")
// barNougat := parentNougat.New().Get("bar/")
//
// fooNougat and barNougat will both use the same client, but send requests to
// https://api.io/foo/ and https://api.io/bar/ respectively.
//
// Note that query and body values are copied so if pointer values are used,
// mutating the original value will mutate the value within the child Nougat.
func (r *Nougat) New() *Nougat {
// copy Headers pairs into new Header map
headerCopy := make(http.Header)
for k, v := range r.header {
headerCopy[k] = v
}
return &Nougat{
httpClient: r.httpClient,
method: r.method,
rawURL: r.rawURL,
header: headerCopy,
queryStructs: append([]interface{}{}, r.queryStructs...),
bodyProvider: r.bodyProvider,
responseDecoder: r.responseDecoder,
}
}
// Http Client
// Client sets the http Client used to do requests.
// If a nil client is given, the http.DefaultClient will be used.
func (r *Nougat) Client(httpClient *http.Client) *Nougat {
if httpClient == nil {
return r.Doer(http.DefaultClient)
}
return r.Doer(httpClient)
}
// Doer sets the custom Doer implementation used to do requests.
// If a nil client is given, the http.DefaultClient will be used.
func (r *Nougat) Doer(doer Doer) *Nougat {
if doer == nil {
r.httpClient = http.DefaultClient
} else {
r.httpClient = doer
}
return r
}
|
package srpc
import (
"bufio"
"bytes"
"crypto/rand"
"flag"
"fmt"
"net"
"os"
"runtime"
"sync"
)
const (
unixClientCookieLength = 8
unixServerCookieLength = 8
unixBufferSize = 1 << 16
)
var (
srpcUnixSocketPath = flag.String("srpcUnixSocketPath",
defaultUnixSocketPath(),
"Pathname for server Unix sockets")
unixCookieToConnMapLock sync.Mutex
unixCookieToConn map[[unixServerCookieLength]byte]net.Conn
unixListenerSetup sync.Once
)
type localUpgradeToUnixRequestOne struct {
ClientCookie []byte
}
type localUpgradeToUnixResponseOne struct {
Error string
ServerCookie []byte
SocketPathname string
}
type localUpgradeToUnixRequestTwo struct {
SentServerCookie bool
}
type localUpgradeToUnixResponseTwo struct {
Error string
}
func acceptUnix(conn net.Conn,
unixCookieToConn map[[unixServerCookieLength]byte]net.Conn) {
doClose := true
defer func() {
if doClose {
conn.Close()
}
}()
var cookie [unixServerCookieLength]byte
if length, err := conn.Read(cookie[:]); err != nil {
return
} else if length != unixServerCookieLength {
return
}
unixCookieToConnMapLock.Lock()
if _, ok := unixCookieToConn[cookie]; ok {
unixCookieToConnMapLock.Unlock()
return
}
unixCookieToConn[cookie] = conn
unixCookieToConnMapLock.Unlock()
var ack [1]byte
length, err := conn.Write(ack[:])
if err != nil || length != 1 {
unixCookieToConnMapLock.Lock()
delete(unixCookieToConn, cookie)
unixCookieToConnMapLock.Unlock()
return
}
doClose = false
}
func acceptUnixLoop(l net.Listener,
unixCookieToConn map[[unixServerCookieLength]byte]net.Conn) {
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
fmt.Fprintf(os.Stderr, "Error accepting Unix connection: %s\n", err)
return
}
go acceptUnix(conn, unixCookieToConn)
}
}
func defaultUnixSocketPath() string {
if runtime.GOOS != "linux" {
return ""
}
return fmt.Sprintf("@SRPC.%d", os.Getpid())
}
func isLocal(client *Client) bool {
lhost, _, err := net.SplitHostPort(client.localAddr)
if err != nil {
return false
}
rhost, _, err := net.SplitHostPort(client.remoteAddr)
if err != nil {
return false
}
return lhost == rhost
}
func setupUnixListener() {
if *srpcUnixSocketPath == "" {
return
}
if (*srpcUnixSocketPath)[0] != '@' {
os.Remove(*srpcUnixSocketPath)
}
l, err := net.Listen("unix", *srpcUnixSocketPath)
if err != nil {
fmt.Fprintf(os.Stderr, "Error listening on Unix socket: %s\n", err)
return
}
unixCookieToConn = make(map[[unixServerCookieLength]byte]net.Conn)
go acceptUnixLoop(l, unixCookieToConn)
}
func (*builtinReceiver) LocalUpgradeToUnix(conn *Conn) error {
unixListenerSetup.Do(setupUnixListener)
var requestOne localUpgradeToUnixRequestOne
if err := conn.Decode(&requestOne); err != nil {
return err
}
if *srpcUnixSocketPath == "" || unixCookieToConn == nil {
return conn.Encode(localUpgradeToUnixResponseOne{Error: "no socket"})
}
var cookie [unixServerCookieLength]byte
if length, err := rand.Read(cookie[:]); err != nil {
return conn.Encode(localUpgradeToUnixResponseOne{Error: err.Error()})
} else if length != unixServerCookieLength {
return conn.Encode(localUpgradeToUnixResponseOne{Error: "bad length"})
}
err := conn.Encode(localUpgradeToUnixResponseOne{
ServerCookie: cookie[:],
SocketPathname: *srpcUnixSocketPath,
})
if err != nil {
return err
}
if err := conn.Flush(); err != nil {
return err
}
var requestTwo localUpgradeToUnixRequestTwo
if err := conn.Decode(&requestTwo); err != nil {
return err
}
if !requestTwo.SentServerCookie {
return nil
}
unixCookieToConnMapLock.Lock()
newConn, ok := unixCookieToConn[cookie]
unixCookieToConnMapLock.Unlock()
doClose := true
defer func() {
if doClose && newConn != nil {
newConn.Close()
}
}()
if !ok {
return conn.Encode(
localUpgradeToUnixResponseTwo{Error: "cookie not found"})
}
if err := conn.Encode(localUpgradeToUnixResponseTwo{}); err != nil {
return err
}
if err := conn.Flush(); err != nil {
return err
}
if length, err := newConn.Write(requestOne.ClientCookie); err != nil {
return err
} else if length != len(requestOne.ClientCookie) {
return fmt.Errorf("could not write full client cookie")
}
doClose = false
conn.conn.Close()
conn.conn = newConn
conn.ReadWriter = bufio.NewReadWriter(
bufio.NewReaderSize(newConn, unixBufferSize),
bufio.NewWriterSize(newConn, unixBufferSize))
logger.Debugf(0, "upgraded connection from: %s to Unix\n", conn.remoteAddr)
return nil
}
func (client *Client) localAttemptUpgradeToUnix() (bool, error) {
if !isLocal(client) {
return false, nil
}
var cookie [unixClientCookieLength]byte
if length, err := rand.Read(cookie[:]); err != nil {
return false, nil
} else if length != unixClientCookieLength {
return false, nil
}
conn, err := client.Call(".LocalUpgradeToUnix")
if err != nil {
return false, nil
}
defer conn.Close()
defer conn.Flush()
err = conn.Encode(localUpgradeToUnixRequestOne{ClientCookie: cookie[:]})
if err != nil {
return false, err
}
if err := conn.Flush(); err != nil {
return false, err
}
var replyOne localUpgradeToUnixResponseOne
if err := conn.Decode(&replyOne); err != nil {
return false, err
}
if replyOne.Error != "" {
return false, nil
}
newConn, err := net.Dial("unix", replyOne.SocketPathname)
if err != nil {
conn.Encode(localUpgradeToUnixRequestTwo{})
logger.Println(err)
return false, nil
}
doClose := true
defer func() {
if doClose {
newConn.Close()
}
}()
if length, err := newConn.Write(replyOne.ServerCookie); err != nil {
conn.Encode(localUpgradeToUnixRequestTwo{})
return false, err
} else if length != len(replyOne.ServerCookie) {
conn.Encode(localUpgradeToUnixRequestTwo{})
return false, fmt.Errorf("bad cookie length: %d", length)
}
var ack [1]byte
if length, err := newConn.Read(ack[:]); err != nil {
conn.Encode(localUpgradeToUnixRequestTwo{})
return false, err
} else if length != 1 {
conn.Encode(localUpgradeToUnixRequestTwo{})
return false, fmt.Errorf("bad ack length: %d", length)
}
err = conn.Encode(localUpgradeToUnixRequestTwo{SentServerCookie: true})
if err != nil {
return false, err
}
if err := conn.Flush(); err != nil {
return false, err
}
var replyTwo localUpgradeToUnixResponseTwo
if err := conn.Decode(&replyTwo); err != nil {
return false, err
}
if replyTwo.Error != "" {
return false, nil
}
returnedClientCookie := make([]byte, len(cookie))
if length, err := newConn.Read(returnedClientCookie); err != nil {
return false, err
} else if length != len(cookie) {
return false, fmt.Errorf("bad returned cookie length: %d", length)
}
if !bytes.Equal(returnedClientCookie, cookie[:]) {
return false, fmt.Errorf("returned client cookie does not match")
}
doClose = false
client.conn.Close()
client.conn = newConn
client.connType = "Unix"
client.tcpConn = nil
client.bufrw = bufio.NewReadWriter(
bufio.NewReaderSize(newConn, unixBufferSize),
bufio.NewWriterSize(newConn, unixBufferSize))
return true, nil
}
|
package gogen
import (
"go/ast"
"unicode"
"strings"
"regexp"
)
// Annotation holds information about one annotation, its name
// parameters and their values
type Annotation struct {
name string //may be obsolete bc annotations are indexed in annotation map by their names
values map[string]string
}
// NewAnnotation will create and return an empty annotation
func NewAnnotation(name string) *Annotation{
return &Annotation{
name: name,
values: make(map[string]string),
}
}
// GetName will return the name of a annotation
func (t *Annotation) GetName () string {
return t.name
}
// Has will return if a parameter with name
// sent to function is a parameter of this annotation
func (t *Annotation) Has (name string) bool {
_, ok := t.values[name]
return ok
}
// Get will return the value of a parameter
// along with bool value that determines if the parameter was found
func (t *Annotation) Get (name string) (string, bool) {
retVal, ok := t.values[name]
return retVal, ok
}
// Set will set a value of a parameter.
// Can be used for creating new parameters
func (t *Annotation) Set (name string, value string) {
t.values[name] = value
}
// Delete will delete a parameter from a annotation
func (t *Annotation) Delete (name string) {
delete(t.values, name)
}
// Num will return number of parameters of a annotation
func (t *Annotation) Num () int {
return len(t.values)
}
// GetAll will return all parameters of a annotation with their values
func (t *Annotation) GetAll () map[string]string {
return t.values
}
// GetParameterNames will return all parameter names.
func (t *Annotation) GetParameterNames () []string {
keys := []string{}
for key := range t.values {
keys = append(keys, key)
}
return keys
}
// AnnotationMap holds build annotations
// of one function/interface/structure etc
type AnnotationMap struct {
annotations map[string]*Annotation
}
// NewAnnotationMap will create and return an empty annotation map
func NewAnnotationMap() *AnnotationMap {
return &AnnotationMap{
annotations: make(map[string]*Annotation),
}
}
// Has will check if the map has a annotation with
// name given by parameter
func (t *AnnotationMap) Has (name string) bool {
_, ok := t.annotations[name]
return ok
}
// Get will get a value of a annotation with
// key given by parameter
func (t *AnnotationMap) Get (name string) (*Annotation, bool) {
retVal, ok := t.annotations[name]
return retVal, ok
}
// Set will set a annotation value to value
// given by parameter
func (t *AnnotationMap) Set (name string, annotation *Annotation) {
t.annotations[name] = annotation
}
// Delete will delete a annotation with name given
// by parameter from the map
func (t *AnnotationMap) Delete (name string) {
delete(t.annotations, name)
}
// Num will return number of annotations in the map
func (t *AnnotationMap) Num () int {
return len(t.annotations)
}
// GetAll will return all annotations in the map
func (t *AnnotationMap) GetAll () map[string]*Annotation {
return t.annotations
}
// GetAnnotationNames will get names of all annotations in the map
func (t *AnnotationMap) GetAnnotationNames () []string {
keys := []string{}
for key := range t.annotations {
keys = append(keys, key)
}
return keys
}
// parseValue parses one value of a annotation,
// returns the remaining string to parse,
// parameter of a annotation and its value
func parseValue(input string) (string, string, string) {
i := 0
name := ""
value := ""
// skip whitespaces before name
for i < len(input) {
if !unicode.IsSpace(rune(input[i])) {
break
}
i++
}
// skip the "-" signs at the start of name of the annotation
for i < len(input) {
if input[i] != '-' {
break
}
i++
}
// read the name of a annotation/parameter
for i < len(input) {
if unicode.IsSpace(rune(input[i])) || input[i] == '=' {
break
}
name += string(input[i])
i++
}
// skip whitespaces or a = sign before value
if i < len(input) && input[i] == '=' {
i++
} else {
for i < len(input) {
if !unicode.IsSpace(rune(input[i])) {
break
}
i++
}
}
//if there is no value and there is another
// option starting with "-", or input ends return what you have
if i == len(input) || input[i] == '-' {
return input[i:], name, value
}
// check if delimiter of value of parameter is space or a " sign
delimiter := ' '
if input[i] == '"' {
delimiter = '"'
i++
}
// read the value of a annotation parameter
if delimiter == ' ' {
// if the value is separated by spaces
for i < len(input) {
if unicode.IsSpace(rune(input[i])) {
break
}
value += string(input[i])
i++
}
} else {
// if the value is separated by " signs
for i < len(input) {
if input[i] == '"' {
break
}
value += string(input[i])
i++
}
i++
}
// return the remaining input and values read from line
return input[i:], name, value
}
// ParseAnnotations will create a AnnotationMap from comments given by
// parameter
func ParseAnnotations (commentMap ast.CommentMap) *AnnotationMap {
annotationMap := NewAnnotationMap()
for _, comment := range commentMap.Comments() {
// split comment to lines
lines := strings.Split(comment.Text(), "\n")
for _, line := range lines {
// if line does not match this regexp made by Miro do not read annotations from line
if !regexp.MustCompile(`(\@\S+)(:? ([\S]+))*`).Match([]byte(line)) {
continue
}
line, annotationName, _ := parseValue(line)
// if there is a annotation on the line read its parameters and their values
if len(annotationName) > 0 && annotationName[0] == '@' {
annotation := NewAnnotation(annotationName)
//fmt.Println("Annotation Name:", annotationName)
// while there is some input check for parameters
for line != "" {
var parName, parVal string
line, parName, parVal = parseValue(line)
if parName != "" {
//fmt.Println("Parameter name:", parName, "Parameter value", parVal)
annotation.Set(parName, parVal)
}
}
// save annotation to map
annotationMap.Set(annotationName, annotation)
}
}
}
return annotationMap
} |
package main
import (
"os"
"go.uber.org/zap"
"github.com/gin-contrib/cors"
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
)
var (
pgDb, pgUser, pgPassword, pgHost string
uploadFolderPath string
logger *zap.SugaredLogger
)
func main() {
loadEnvironmentVariables()
startStreamingAPIServer()
}
// loadEnvironmentVariables loads PostgreSQL
// information from dotenv
func loadEnvironmentVariables() {
pgDb = os.Getenv("PGDB")
if len(pgDb) == 0 {
panic("No pgDB environment variable")
}
pgUser = os.Getenv("PGUSER")
if len(pgUser) == 0 {
panic("No pgUSER environment variable")
}
pgPassword = os.Getenv("PGPASSWORD")
if len(pgPassword) == 0 {
panic("No pgPASSWORD environment variable")
}
pgHost = os.Getenv("PGHOST")
if len(pgHost) == 0 {
panic("No pgHOST environment variable")
}
uploadFolderPath = os.Getenv("UPLOAD_FOLDER_PATH")
if len(uploadFolderPath) == 0 {
panic("No UPLOAD_FOLDER_PATH environment variable")
}
}
func startStreamingAPIServer() {
log, _ := zap.NewProduction()
defer log.Sync()
logger = log.Sugar()
logger.Info("Starting streaming API server")
// Creates a gin router with default middleware:
// logger and recovery (crash-free) middleware
router := gin.Default()
corsConfig := cors.DefaultConfig()
corsConfig.AllowAllOrigins = true
corsConfig.AllowHeaders = []string{"Origin", "Content-Length", "Content-Type", "Range"}
router.Use(cors.New(corsConfig))
// TODO: Use uploadFolderPath later for better security
router.Use(static.Serve("/contents", static.LocalFile("/", false)))
// By default it serves on :8080
router.Run(":8880")
}
|
// Licensed to SolID under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. SolID licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package handlers
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"github.com/golang/protobuf/ptypes/wrappers"
"github.com/imdario/mergo"
"github.com/square/go-jose/v3"
"google.golang.org/protobuf/types/known/wrapperspb"
corev1 "zntr.io/solid/api/gen/go/oidc/core/v1"
"zntr.io/solid/api/oidc"
"zntr.io/solid/pkg/sdk/rfcerrors"
"zntr.io/solid/pkg/server/authorizationserver"
)
// DCR handles dynamic client registration.
func DCR(as authorizationserver.AuthorizationServer) http.Handler {
const bodyLimiterSize = 5 << 20 // 5 Mb
type request struct {
ApplicationType string `json:"application_type,omitempty"`
RedirectURIs []string `json:"redirect_uris,omitempty"`
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
GrantTypes []string `json:"grant_types,omitempty"`
ResponseTypes []string `json:"response_types,omitempty"`
ClientName string `json:"client_name,omitempty"`
ClientURI string `json:"client_uri,omitempty"`
LogoURI string `json:"logo_uri,omitempty"`
Scope string `json:"scope,omitempty"`
Contacts []string `json:"contacts,omitempty"`
TosURI string `json:"tos_uri,omitempty"`
PolicyURI string `json:"policy_uri,omitempty"`
JwksURI string `json:"jwks_uri,omitempty"`
JWKS *jose.JSONWebKeySet `json:"jwks,omitempty"`
SoftwareID string `json:"software_id,omitempty"`
SoftwareVersion string `json:"software_version,omitempty"`
SoftwareStatement string `json:"software_statement,omitempty"`
}
toClientMeta := func(r *request) (*corev1.ClientMeta, error) {
// Copy array
meta := &corev1.ClientMeta{
Contacts: r.Contacts,
GrantTypes: r.GrantTypes,
RedirectUris: r.RedirectURIs,
ResponseTypes: r.ResponseTypes,
}
// Process optional fields
if r.ApplicationType != "" {
meta.ApplicationType = &wrapperspb.StringValue{Value: r.ApplicationType}
}
if r.ClientName != "" {
meta.ClientName = &wrapperspb.StringValue{Value: r.ClientName}
}
if r.ClientURI != "" {
meta.ClientUri = &wrapperspb.StringValue{Value: r.ClientURI}
}
if r.JwksURI != "" {
meta.JwkUri = &wrapperspb.StringValue{Value: r.JwksURI}
}
if r.LogoURI != "" {
meta.LogoUri = &wrapperspb.StringValue{Value: r.LogoURI}
}
if r.PolicyURI != "" {
meta.PolicyUri = &wrapperspb.StringValue{Value: r.PolicyURI}
}
if r.Scope != "" {
meta.Scope = &wrapperspb.StringValue{Value: r.Scope}
}
if r.SoftwareID != "" {
meta.SoftwareId = &wrapperspb.StringValue{Value: r.SoftwareID}
}
if r.SoftwareVersion != "" {
meta.SoftwareVersion = &wrapperspb.StringValue{Value: r.SoftwareVersion}
}
if r.TokenEndpointAuthMethod != "" {
meta.TokenEndpointAuthMethod = &wrapperspb.StringValue{Value: r.TokenEndpointAuthMethod}
}
if r.TosURI != "" {
meta.TosUri = &wrapperspb.StringValue{Value: r.TosURI}
}
// JWKS
if r.JWKS != nil {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(r.JWKS); err != nil {
return nil, fmt.Errorf("unable to encode JWK: %w", err)
}
// Set JWKS
meta.Jwks = &wrappers.BytesValue{Value: buf.Bytes()}
}
// Merge with default values
if err := mergo.Merge(meta, corev1.ClientMeta{
GrantTypes: []string{oidc.GrantTypeAuthorizationCode},
ResponseTypes: []string{oidc.ResponseTypeCode},
Scope: &wrapperspb.StringValue{Value: "openid"},
}); err != nil {
return nil, fmt.Errorf("unable to merge with default values: %w", err)
}
// No error
return meta, nil
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Only POST verb
if r.Method != http.MethodPost {
withError(w, r, http.StatusMethodNotAllowed, rfcerrors.InvalidRequest().Build())
return
}
// Decode body
var reqw request
if err := json.NewDecoder(io.LimitReader(r.Body, bodyLimiterSize)).Decode(&reqw); err != nil {
log.Printf("unable to decode json request: %w", err)
withError(w, r, http.StatusBadRequest, rfcerrors.InvalidRequest().Build())
return
}
// Create request
meta, err := toClientMeta(&reqw)
if err != nil {
log.Printf("unable to prepare meta: %w", err)
withError(w, r, http.StatusBadRequest, rfcerrors.InvalidClientMetadata().Build())
return
}
// Delegate message to reactor
res, err := as.Do(r.Context(), &corev1.ClientRegistrationRequest{
Metadata: meta,
})
dcrRes, ok := res.(*corev1.ClientRegistrationResponse)
if !ok {
withJSON(w, r, http.StatusInternalServerError, rfcerrors.ServerError().Build())
return
}
if err != nil {
log.Printf("unable to process registration request: %w", err)
withError(w, r, http.StatusBadRequest, dcrRes.Error)
return
}
// Send json reponse
withJSON(w, r, http.StatusCreated, dcrRes.Client)
})
}
|
package models
import (
"project/app/admin/models/bo"
"project/utils/app"
)
// _ResponseLogin swagger登录授权响应结构体
type _ResponseLogin struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
Data struct {
Token string `json:"token"` // 授权令牌
} `json:"data"` // 数据
}
// _ResponseCode 短信验证码响应结构体
type _ResponseCode struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
Img string `json:"img"` // base64验证码
UuId string `json:"uuid"` // 验证码id
}
// _ResponseFile 文件上传响应结构体
type _ResponseFile struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
Data FileResponse `json:"data"` // 数据
}
//_ResponseInsertMenu 新增菜单
type _ResponseInsertMenu struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
}
//_ResponseInsertMenu 查询菜单
type _ResponseSelectMenu struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
Data *bo.SelectMenuBo `json:"data"` // 数据
}
//_ResponseDeleteMenu 删除菜单
type _ResponseDeleteMenu struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
}
//_ResponseUpdateMenu 删除菜单
type _ResponseUpdateMenu struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
}
//_ResponseInsertUser 新增用户
type _ResponseInsertUser struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
}
//_ResponseSelectForeNeedMenu
type _ResponseSelectForeNeedMenu struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
Data *bo.SelectForeNeedMenuBo `json:"data"` // 数据
}
//_ResponseSelectUserInfoList
type _ResponseSelectUserInfoList struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
Data *bo.UserInfoListBo `json:"data"` // 数据
}
//_ResponseChildInfoList
type _ResponseSelectMeauDataInfoList struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
Data []int `json:"data"` // 数据
}
//_ResponseGetJobList 查询岗位
type _ResponseGetJobList struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
Data []*bo.GetJobList `json:"data"` // 数据
}
//_ResponseDeleteUser 删除用户
type _ResponseDeleteUser struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
}
//_ResponseUpdateUser 更新用户
type _ResponseUpdateUser struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
}
//_ResponseUpdateUserCenter //更新用户个人信息
type _ResponseUpdateUserCenter struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
}
//_ResponseSelectUserInfo //单个用户详细
type _ResponseSelectUserInfo struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
Data *bo.UserCenterInfoBo `json:"data"` //数据
}
// _ResponseSelectDeptList 查询部门
type _ResponseSelectDeptList struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
Data *bo.RecordDept `json:"data"` // 数据
}
//_ResponseDept 新增删除更新部门
type _ResponseDept struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
}
// _DownMenusHandler 返回全部菜单
type _ResponseMenuData struct {
Code app.ResCode `json:"code"` // 业务响应状态码
Message string `json:"message"` // 提示信息
Data []*bo.ReturnToAllMenusBo `json:"data"` // 数据
}
|
/*
Copyright 2013 The Camlistore Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package kvfile implements the Camlistore index storage abstraction
// on top of a single mutable database file on disk using
// github.com/cznic/kv.
package kvfile
import (
"errors"
"fmt"
"io"
"log"
"os"
"sync"
"camlistore.org/pkg/blobserver"
"camlistore.org/pkg/index"
"camlistore.org/pkg/jsonconfig"
"camlistore.org/third_party/github.com/camlistore/lock"
"camlistore.org/third_party/github.com/cznic/kv"
)
func init() {
blobserver.RegisterStorageConstructor("kvfileindexer",
blobserver.StorageConstructor(newFromConfig))
}
func NewStorage(file string) (index.Storage, io.Closer, error) {
createOpen := kv.Open
if _, err := os.Stat(file); os.IsNotExist(err) {
createOpen = kv.Create
}
db, err := createOpen(file, &kv.Options{
Locker: func(dbname string) (io.Closer, error) {
lkfile := dbname + ".lock"
cl, err := lock.Lock(lkfile)
if err != nil {
return nil, fmt.Errorf("failed to acquire lock on %s: %v", lkfile, err)
}
return cl, nil
},
})
if err != nil {
return nil, nil, err
}
is := &kvis{
db: db,
}
return is, struct{ io.Closer }{db}, nil
}
type kvis struct {
db *kv.DB
txmu sync.Mutex
}
// TODO: use bytepool package.
func getBuf(n int) []byte { return make([]byte, n) }
func putBuf([]byte) {}
func (is *kvis) Get(key string) (string, error) {
buf := getBuf(200)
defer putBuf(buf)
val, err := is.db.Get(buf, []byte(key))
if err != nil {
return "", err
}
if val == nil {
return "", index.ErrNotFound
}
return string(val), nil
}
func (is *kvis) Set(key, value string) error {
return is.db.Set([]byte(key), []byte(value))
}
func (is *kvis) Delete(key string) error {
return is.db.Delete([]byte(key))
}
func (is *kvis) Find(key string) index.Iterator {
return &iter{
db: is.db,
initKey: key,
}
}
func (is *kvis) BeginBatch() index.BatchMutation {
return index.NewBatchMutation()
}
type batch interface {
Mutations() []index.Mutation
}
func (is *kvis) CommitBatch(bm index.BatchMutation) error {
b, ok := bm.(batch)
if !ok {
return errors.New("invalid batch type")
}
is.txmu.Lock()
defer is.txmu.Unlock()
good := false
defer func() {
if !good {
is.db.Rollback()
}
}()
if err := is.db.BeginTransaction(); err != nil {
return err
}
for _, m := range b.Mutations() {
if m.IsDelete() {
if err := is.db.Delete([]byte(m.Key())); err != nil {
return err
}
} else {
if err := is.db.Set([]byte(m.Key()), []byte(m.Value())); err != nil {
return err
}
}
}
good = true
return is.db.Commit()
}
func (is *kvis) Close() error {
log.Printf("Closing kvfile database")
return is.db.Close()
}
type iter struct {
db *kv.DB
initKey string
enum *kv.Enumerator
valid bool
key, val string
err error
closed bool
}
func (it *iter) Close() error {
it.closed = true
return it.err
}
func (it *iter) Key() string {
if !it.valid {
panic("not valid")
}
return it.key
}
func (it *iter) Value() string {
if !it.valid {
panic("not valid")
}
return it.val
}
func (it *iter) Next() (ret bool) {
if it.closed {
panic("Next called after Next returned value")
}
defer func() {
it.valid = ret
if !ret {
it.closed = true
}
}()
if it.enum == nil {
it.enum, _, it.err = it.db.Seek([]byte(it.initKey))
if it.err != nil {
return false
}
}
key, val, err := it.enum.Next()
if err == io.EOF {
it.err = nil
return false
}
it.key = string(key)
it.val = string(val)
return true
}
func newFromConfig(ld blobserver.Loader, config jsonconfig.Obj) (blobserver.Storage, error) {
blobPrefix := config.RequiredString("blobSource")
file := config.RequiredString("file")
if err := config.Validate(); err != nil {
return nil, err
}
is, closer, err := NewStorage(file)
if err != nil {
return nil, err
}
sto, err := ld.GetStorage(blobPrefix)
if err != nil {
closer.Close()
return nil, err
}
ix := index.New(is)
if err != nil {
return nil, err
}
ix.BlobSource = sto
// Good enough, for now:
ix.KeyFetcher = ix.BlobSource
return ix, err
}
|
package main
/*
1.日志是查找潜在bug, 了解程序工作状态的方式
1.可用于跟踪 & 调试 & 分析代码
2.Go标准库提供了log包, 可对日志做最基本的配置, 开发人员还可自定义日志记录器
3.传统CLI(命令行界面)程序直接将输出写到名为stdout设备上, 所有操作系统都有这种设备, 该设备默认目的地是标准文本输出
1.默认设置下, 终端会显示写到stdou设备上的文本, 这对于单个目的的输出很方便
2.有事会需要同时输出程序信息和执行细节
1.执行细节称为日志
3.为解决程序输出和日志混为一谈, UNIX架构上增加了名为stderr的设备, 该设备为日志默认目的地
4.若想在程序运行期间同时看到程序输出和日志, 可将终端配置为同时显示写到stdout和stderr的信息
5.如果程序没有输出, 通常是将日志信息写到stdout设备, 将错误或警告信息写到stderr设备
*/
|
package main
import "fmt"
func main() {
complexArray1 := [3][]string {
[]string{"d", "e", "f"},
[]string{"g", "h", "i"},
[]string{"j", "k", "l"},
}
fmt.Printf("The complex array is %v\n", complexArray1)
complexArray2 := modifyArray(complexArray1)
fmt.Printf("After updated, the complex array is %v\n", complexArray2)
fmt.Printf("The origin complex array is %v\n", complexArray1)
}
func modifyArray(a [3][]string)([3][]string){
a[1][1] = "O"
return a
} |
package sshKraken // import "github.com/cvasq/sshKraken"
import (
"net"
"golang.org/x/net/context"
)
type EmptyResolver struct{}
func (EmptyResolver) Resolve(ctx context.Context, name string) (context.Context, net.IP, error) {
return ctx, nil, nil
}
|
package path
import (
"strconv"
)
// Regular Expressions ile tanımladığınız URL'lerdeki parametreleri döndürür.
// Tip dönüşümleriyle uğraşmak zorunda kalınmadan, uygun metod kullanılarak veri elde edilebilir.
// Örnek:
// URL Mapping Erişim
// /customers/312 `/customers/(?P<customerId>\d+)` pv.GetInt32("customerId")
type Variable map[string]string
func (v *Variable) value(key string) string {
for k, val := range *v {
if k == key {
return val
}
}
return ""
}
func (v *Variable) GetString(key string) string {
return v.value(key)
}
func (v *Variable) GetInt32(key string) int32 {
val, _ := strconv.Atoi(v.value(key))
return int32(val)
}
func (v *Variable) GetFloat32(key string) float32 {
val, _ := strconv.Atoi(v.value(key))
return float32(val)
}
|
package writer
import (
"encoding/json"
"io"
"strings"
)
type JsonWriter struct {
input interface{}
}
func (j JsonWriter) Bytes() ([]byte, error) {
marshalOutput, err := j.Marshal()
if err != nil {
return nil, err
}
return marshalOutput.([]byte), nil
}
func (j JsonWriter) Marshal() (interface{}, error) {
return json.Marshal(j.input)
}
func (j JsonWriter) Valid() bool {
_, err := j.Marshal()
if err != nil {
return false
}
return true
}
func (j JsonWriter) Reader() (io.Reader, error) {
content, err := j.Marshal()
bytes := content.([]byte)
if err != nil {
return nil, err
}
return strings.NewReader(string(bytes)), nil
}
func (j JsonWriter) ToString() (*string, error) {
content, err := j.Marshal()
bytes := content.([]byte)
if err != nil {
return nil, err
}
output := string(bytes)
return &output, nil
}
func (j JsonWriter) ContentType() string {
return "application/json"
}
|
package main
import "fmt"
// passed by value - zeroval gets a copy of ival distinct from one in the calling function
func zeroval(ival int) {
ival = 0
}
// passes pointer, dereferences the pointer - assigning value will change value at ref'd address
func zeroptr(iptr *int) {
*iptr = 0
}
func main() {
i := 1
fmt.Println("initial:", i)
zeroval(i)
fmt.Println("zeroval:", i)
zeroptr(&i) // address of pointer
fmt.Println("zeroptr:", i)
fmt.Println("pointer", &i)
}
|
package ciolite
// Api functions that support: users/email_accounts/folders/messages/body
import (
"fmt"
"net/url"
)
// GetUserEmailAccountsFolderMessageBodyParams query values data struct.
// Optional: Delimiter, Type.
type GetUserEmailAccountsFolderMessageBodyParams struct {
// Optional:
Delimiter string `json:"delimiter,omitempty"`
Type string `json:"type,omitempty"`
}
// GetUserEmailAccountsFolderMessageBodyResponse data struct
type GetUserEmailAccountsFolderMessageBodyResponse struct {
Type string `json:"type,omitempty"`
Charset string `json:"charset,omitempty"`
Content string `json:"content,omitempty"`
BodySection string `json:"body_section,omitempty"`
}
// GetUserEmailAccountsFolderMessageBody fetches the message body of a given email.
// queryValues may optionally contain Delimiter, Type
func (cioLite CioLite) GetUserEmailAccountsFolderMessageBody(userID string, label string, folder string, messageID string, queryValues GetUserEmailAccountsFolderMessageBodyParams) ([]GetUserEmailAccountsFolderMessageBodyResponse, error) {
// Make request
request := clientRequest{
Method: "GET",
Path: fmt.Sprintf("/lite/users/%s/email_accounts/%s/folders/%s/messages/%s/body", userID, label, url.QueryEscape(folder), url.QueryEscape(messageID)),
QueryValues: queryValues,
UserID: userID,
AccountLabel: label,
}
// Make response
var response []GetUserEmailAccountsFolderMessageBodyResponse
// Request
err := cioLite.doFormRequest(request, &response)
return response, err
}
|
package jarviscore
import (
"context"
"io"
"net"
"go.uber.org/zap"
jarvisbase "github.com/zhs007/jarviscore/base"
pb "github.com/zhs007/jarviscore/proto"
"google.golang.org/grpc"
)
// jarvisServer2
type jarvisServer2 struct {
node *jarvisNode
lis net.Listener
grpcServ *grpc.Server
}
// newServer2 -
func newServer2(node *jarvisNode) (*jarvisServer2, error) {
lis, err := net.Listen("tcp", node.myinfo.BindAddr)
if err != nil {
jarvisbase.Error("newServer", zap.Error(err))
return nil, err
}
jarvisbase.Info("Listen", zap.String("addr", node.myinfo.BindAddr))
grpcServ := grpc.NewServer()
s := &jarvisServer2{
node: node,
lis: lis,
grpcServ: grpcServ,
}
pb.RegisterJarvisCoreServServer(grpcServ, s)
return s, nil
}
// Start -
func (s *jarvisServer2) Start(ctx context.Context) error {
return s.grpcServ.Serve(s.lis)
}
// Stop -
func (s *jarvisServer2) Stop() {
s.lis.Close()
return
}
// ProcMsg implements jarviscorepb.JarvisCoreServ
func (s *jarvisServer2) ProcMsg(in *pb.JarvisMsg, stream pb.JarvisCoreServ_ProcMsgServer) error {
if IsSyncMsg(in) {
chanEnd := make(chan int)
s.node.PostMsg(&NormalMsgTaskInfo{
Msg: in,
ReplyStream: NewJarvisMsgReplyStream(stream),
}, chanEnd)
<-chanEnd
return nil
}
// if isme
if in.SrcAddr == s.node.myinfo.Addr {
jarvisbase.Warn("jarvisServer2.ProcMsg:isme",
JSONMsg2Zap("msg", in))
err := s.replyStream2ProcMsg(in.SrcAddr, in.MsgID,
stream, pb.REPLYTYPE_ISME, "")
if err != nil {
jarvisbase.Warn("jarvisServer2.ProcMsg:replyStream2ProcMsg", zap.Error(err))
return err
}
return nil
}
if in.DestAddr == s.node.myinfo.Addr {
err := s.replyStream2ProcMsg(in.SrcAddr, in.MsgID,
stream, pb.REPLYTYPE_IGOTIT, "")
if err != nil {
jarvisbase.Warn("jarvisServer2.ProcMsg:replyStream2ProcMsg:IGOTIT", zap.Error(err))
return err
}
}
// chanEnd := make(chan int)
s.node.PostMsg(&NormalMsgTaskInfo{
Msg: in,
ReplyStream: NewJarvisMsgReplyStream(nil),
}, nil)
// <-chanEnd
return nil
}
// ProcMsgStream implements jarviscorepb.JarvisCoreServ
func (s *jarvisServer2) ProcMsgStream(stream pb.JarvisCoreServ_ProcMsgStreamServer) error {
var lstmsgs []JarvisMsgInfo
var firstmsg *pb.JarvisMsg
for {
in, err := stream.Recv()
if err == io.EOF {
break
}
if firstmsg == nil && in != nil {
firstmsg = in
}
if err != nil {
jarvisbase.Warn("jarvisServer2.ProcMsgStream:stream.Recv",
zap.Error(err))
if firstmsg != nil {
err := s.replyStream2ProcMsgStream(firstmsg.SrcAddr, firstmsg.MsgID,
stream, pb.REPLYTYPE_ERROR, err.Error())
if err != nil {
jarvisbase.Warn("jarvisServer2.ProcMsg:replyStream2ProcMsgStream",
zap.Error(err))
}
}
lstmsgs = append(lstmsgs, JarvisMsgInfo{
JarvisResultType: JarvisResultTypeLocalErrorEnd,
Err: err,
})
break
}
lstmsgs = append(lstmsgs, JarvisMsgInfo{
JarvisResultType: JarvisResultTypeReply,
Msg: in,
})
if in.ReplyMsgID > 0 {
s.node.OnReplyProcMsg(stream.Context(), in.SrcAddr, in.ReplyMsgID, JarvisResultTypeReply, in, nil)
}
}
if firstmsg == nil {
jarvisbase.Warn("jarvisServer2.ProcMsg:firstmsg")
return nil
}
// if isme
if firstmsg.SrcAddr == s.node.myinfo.Addr {
jarvisbase.Warn("jarvisServer2.ProcMsg:isme",
JSONMsg2Zap("msg", firstmsg))
err := s.replyStream2ProcMsgStream(firstmsg.SrcAddr, firstmsg.MsgID,
stream, pb.REPLYTYPE_ISME, "")
if err != nil {
jarvisbase.Warn("jarvisServer2.ProcMsgStream:replyStream2ProcMsgStream", zap.Error(err))
return err
}
return nil
}
if firstmsg.DestAddr == s.node.myinfo.Addr {
err := s.replyStream2ProcMsg(firstmsg.SrcAddr, firstmsg.MsgID,
stream, pb.REPLYTYPE_IGOTIT, "")
if err != nil {
jarvisbase.Warn("jarvisServer2.ProcMsg:replyStream2ProcMsgStream:IGOTIT", zap.Error(err))
return err
}
}
// chanEnd := make(chan int)
s.node.PostStreamMsg(&StreamMsgTaskInfo{
Msgs: lstmsgs,
ReplyStream: NewJarvisMsgReplyStream(nil),
}, nil)
// <-chanEnd
return nil
}
// replyStream2ProcMsgStream
func (s *jarvisServer2) replyStream2ProcMsgStream(addr string, replyMsgID int64,
stream pb.JarvisCoreServ_ProcMsgStreamServer, rt pb.REPLYTYPE, strErr string) error {
sendmsg, err := BuildReply2(s.node, s.node.myinfo.Addr, addr, rt, strErr, replyMsgID)
if err != nil {
jarvisbase.Warn("jarvisServer2.replyStream2ProcMsgStream:BuildReply2", zap.Error(err))
return err
}
sendmsg.LastMsgID = s.node.GetCoreDB().GetCurRecvMsgID(sendmsg.DestAddr)
err = SignJarvisMsg(s.node.GetCoreDB().GetPrivateKey(), sendmsg)
if err != nil {
jarvisbase.Warn("jarvisServer2.replyStream2ProcMsgStream:SignJarvisMsg", zap.Error(err))
return err
}
err = stream.Send(sendmsg)
if err != nil {
jarvisbase.Warn("jarvisServer2.replyStream2ProcMsgStream:SendMsg", zap.Error(err))
return err
}
return nil
}
// replyStream2ProcMsg
func (s *jarvisServer2) replyStream2ProcMsg(addr string, replyMsgID int64,
stream pb.JarvisCoreServ_ProcMsgServer, rt pb.REPLYTYPE, strErr string) error {
sendmsg, err := BuildReply2(s.node, s.node.myinfo.Addr, addr, rt, strErr, replyMsgID)
if err != nil {
jarvisbase.Warn("jarvisServer2.replyStream2ProcMsg:BuildReply2", zap.Error(err))
return err
}
sendmsg.LastMsgID = s.node.GetCoreDB().GetCurRecvMsgID(sendmsg.DestAddr)
err = SignJarvisMsg(s.node.GetCoreDB().GetPrivateKey(), sendmsg)
if err != nil {
jarvisbase.Warn("jarvisServer2.replyStream2ProcMsg:SignJarvisMsg", zap.Error(err))
return err
}
err = stream.Send(sendmsg)
if err != nil {
jarvisbase.Warn("jarvisServer2.replyStream2ProcMsg:SendMsg", zap.Error(err))
return err
}
return nil
}
|
package bishi
import (
"math"
)
func JudgeStr(str string) (count int, values string) {
length := len(str)
if length == 0 {
return 0, ""
}
runne := []rune(str)
maps := make(map[rune]int)
var strRune = make([]rune, 0)
var strRunes = make([][]rune, 0)
var max float64
for i, j := 0, 0; i < length; i++ {
item := runne[i]
k, ok := maps[item]
if ok {
j = int(math.Max(float64(j), float64(k+1)))
}
maps[item] = i
strRune = append(strRune, item)
max = math.Max(float64(max), float64(i-j+1))
//fmt.Printf("j:%d,max:%f size:%d\n", j, max, i-j+1)
//
//fmt.Println(string(strRune))
//fmt.Printf("===%s\n", string(strRune[j:int(i)+1]))
strRunes = append(strRunes, strRune[j:int(i)+1])
}
for _, v := range strRunes {
if int(max) == len(v) {
values = string(v)
}
}
count=int(max)
return
}
|
package main
import (
"bytes"
"fmt"
"html/template"
"io"
"log"
"net/http"
"github.com/Samze/services-demo-basel-2018/config"
"github.com/Samze/services-demo-basel-2018/web-app/queue"
"github.com/Samze/services-demo-basel-2018/web-app/store"
)
type Storer interface {
GetImages() ([]store.Image, error)
}
type Queuer interface {
PublishImage(string, []byte) error
Destroy()
}
func main() {
c, err := config.NewWebConfig()
if err != nil {
log.Fatalf("could not load config %+v", err)
}
defer c.RemoveTmpFile()
queue, err := queue.NewQueue(c.ProjectID, c.TopicID)
if err != nil {
log.Fatalf("could not load config %+v", err)
}
defer queue.Destroy()
store, err := store.NewStore(c.ConnectionString)
if err != nil {
log.Fatalf("Could not connect to store %+v", err)
}
http.HandleFunc("/images", postImageHandler(queue))
http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("./css"))))
http.HandleFunc("/", getHandler(store))
fmt.Println("Listening on port:", config.Port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", config.Port), nil))
}
func postImageHandler(q Queuer) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
file, header, err := r.FormFile("image")
if err != nil {
http.Error(w, fmt.Sprintf("Failed to read img: %v", err), http.StatusInternalServerError)
return
}
defer file.Close()
imgBuf := bytes.NewBuffer(nil)
if _, err := io.Copy(imgBuf, file); err != nil {
http.Error(w, fmt.Sprintf("Failed to copy img: %v", err), http.StatusInternalServerError)
return
}
if err := q.PublishImage(header.Filename, imgBuf.Bytes()); err != nil {
http.Error(w, fmt.Sprintf("Failed to publish img: %v", err), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusFound)
}
}
func getHandler(s Storer) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("tmpl/home.html")
if err != nil {
fmt.Fprintf(w, "err getting template %+v", err)
}
images, err := s.GetImages()
if err != nil {
fmt.Fprintf(w, "err getting images %+v", err)
}
data := map[string][]store.Image{
"Images": images,
}
t.Execute(w, data)
}
}
|
package MP4
import (
"bytes"
"github.com/panda-media/muxer-fmp4/format/AVPacket"
"github.com/panda-media/muxer-fmp4/format/MP4/commonBoxes"
)
const (
MEDIA_AV = iota
MEDIA_Audio_Only
MEDIA_Video_Only
)
type FMP4Muxer struct {
audioHeader *AVPacket.MediaPacket
videoHeader *AVPacket.MediaPacket
sequence_number uint32 //1 base
trunAudio *commonBoxes.TRUN
trunVideo *commonBoxes.TRUN
audio_data *bytes.Buffer
video_data *bytes.Buffer
moof_mdat_buf *bytes.Buffer
sidx *commonBoxes.SIDX
timescale uint32
timescaleAudio uint32
timescaleVideo uint32
timeBeginMS uint32
timeLastMS uint32
timeLastVideo uint32
timeLastAudio uint32
timeSlicedMS uint32
timeSidxMS uint32
mdat_size int
}
|
// Created by: Ryan-Shaw-2
// Created on: May 2021
//
// This program calculates the volume of a pyramid
package main
import "fmt"
func main() {
// This function calculates the volume of a pyramid
var length float64
var width float64
var height float64
// input
fmt.Println("This program calculates the volume of a pyramid")
fmt.Println()
fmt.Print("Enter the length of the base (cm): ")
fmt.Scanln(&length)
fmt.Print("Enter the width of the base (cm): ")
fmt.Scanln(&width)
fmt.Print("Enter the height of the pyramid (cm): ")
fmt.Scanln(&height)
fmt.Println()
// process
var volume = (length * width * height) / 3
// output
fmt.Println("The volume is:", volume, "cm³")
}
|
package analyzer
import (
"fmt"
"go/ast"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
"reflect"
//"strings"
"golang.org/x/tools/go/analysis"
)
var Analyzer = &analysis.Analyzer{
Name: "terraformschemachecker",
Doc: "Checks resource schema field order",
Run: run,
Requires: []*analysis.Analyzer{inspect.Analyzer},
}
var ordering = []string{"Type", "Elem", "Required", "Optional", "Computed", "Default", "ForceNew", "Sensitive", "ValidateFunc", "Description", "ConflictsWith", "RequiredWith", "Deprecated"}
var orderMap = make(map[string]int, len(ordering))
func run(pass *analysis.Pass) (interface{}, error) {
inspector := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
nodeFilter := []ast.Node{
(*ast.ReturnStmt)(nil),
}
inspector.Preorder(nodeFilter, func(node ast.Node) {
retStmt := node.(*ast.ReturnStmt)
if len(retStmt.Results) != 1 {
return
}
result := retStmt.Results[0]
if reflect.TypeOf(result) != reflect.TypeOf((*ast.UnaryExpr)(nil)) {
return
}
unary := result.(*ast.UnaryExpr)
compositeLit := unary.X.(*ast.CompositeLit)
selExpr := compositeLit.Type.(*ast.SelectorExpr)
// Only consider schema.Resource
if fmt.Sprintf("%s", selExpr.X) != "schema" || fmt.Sprintf("%s", selExpr.Sel) != "Resource" {
return
}
var schemaKeyValueExpr *ast.KeyValueExpr
for _, expr := range compositeLit.Elts {
keyValueExpr := expr.(*ast.KeyValueExpr)
// Only consider schema.Schema definition
if fmt.Sprintf("%s", keyValueExpr.Key) == "Schema" {
schemaKeyValueExpr = keyValueExpr
break
}
}
// Return if schema.Schema is not found
if schemaKeyValueExpr == nil {
return
}
// Setup reverse mapping from field name to index in array
for i, elem := range ordering {
orderMap[elem] = i
}
// For each attribute, check the order of the fields
attributes := schemaKeyValueExpr.Value.(*ast.CompositeLit)
for _, expr := range attributes.Elts {
field := expr.(*ast.KeyValueExpr)
checkFieldOrder(field, pass)
}
return
})
return nil, nil
}
func checkFieldOrder(field *ast.KeyValueExpr, pass *analysis.Pass) {
fieldDef := field.Value.(*ast.CompositeLit)
indexes := make([]int, len(fieldDef.Elts))
for i, expr := range fieldDef.Elts {
keyValueExpr := expr.(*ast.KeyValueExpr)
key := fmt.Sprintf("%s", keyValueExpr.Key)
var ok bool
indexes[i], ok = orderMap[key]
if !ok {
pass.Reportf(keyValueExpr.Pos(), "found new field name: %s", key)
// Prevent other fields from conflicting with this field
indexes[i] = len(ordering) + 1
}
if i == 0 {
continue
}
if indexes[i] < indexes[i - 1] {
name1 := ordering[indexes[i]]
name2 := ordering[indexes[i-1]]
pass.Reportf(keyValueExpr.Pos(), "%s should come before %s in resource schema definition", name1, name2)
}
}
} |
package metaverse
import (
"github.com/unixpickle/anyvec"
"github.com/unixpickle/essentials"
gym "github.com/unixpickle/gym-socket-api/binding-go"
)
// Env is a Universe environment implementing anyrl.Env.
type Env struct {
GymEnv gym.Env
Imager *Imager
ActionSpace *ActionSpace
}
// Reset resets the environment.
func (e *Env) Reset() (obs anyvec.Vector, err error) {
defer essentials.AddCtxTo("reset Universe environment", &err)
rawObs, err := e.GymEnv.Reset()
if err != nil {
return
}
obs = e.Imager.Image(rawObs)
return
}
// Step takes a step in the environment.
func (e *Env) Step(actionVec anyvec.Vector) (obs anyvec.Vector, reward float64,
done bool, err error) {
actionObj := e.ActionSpace.VecToObj(actionVec)
rawObs, reward, done, _, err := e.GymEnv.Step(actionObj)
if err != nil {
return
}
obs = e.Imager.Image(rawObs)
return
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.