text stringlengths 11 4.05M |
|---|
package packed
//func ArgumentsJS() []byte {
// panic("not implemented")
//}
//
|
package core
import (
"context"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
/*
total number of gorutine = 2n
number of concurrency connections : n
accept gorutine : 1
*/
// Server represents a websocket server.
type Server struct {
server *http.Server
path string
addr string
upgrader websocket.Upgrader
cm *ConnectionManager
handler Handler
}
// NewServer creates a websocket server but not start to accept.
func NewServer(addr, path string, h Handler) *Server {
s := &Server{
server: &http.Server{
Addr: addr,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
},
path: path,
addr: addr,
upgrader: websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
},
cm: &ConnectionManager{
conns: make(map[*Connection]bool),
},
handler: h,
}
s.server.Handler = s
return s
}
// Start runs the server
func (s *Server) Start() {
s.server.ListenAndServe()
}
// Close immediately closes all listeneres and connections
func (s *Server) Close() {
s.server.Close()
}
// Shutdown gracefully shuts down the server
func (s *Server) Shutdown() {
s.server.Shutdown(context.Background())
}
// Count returns the concurrency connections
func (s *Server) Count() int {
return s.cm.count()
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
conn, err := s.upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatal(err)
}
go s.handleConnect(conn)
}
func (s *Server) handleConnect(wc *websocket.Conn) {
c := NewConnection(wc, s.handler)
s.cm.add(c)
defer func() {
s.cm.remove(c)
}()
go c.handler.OnEvent(EventConnected, c, nil)
c.serve()
c.handler.OnEvent(EventClosed, c, nil)
}
|
/**
* @description: 先定义后赋值 数组
* @author Administrator
* @date 2020/7/11 0011 10:44
*/
package main
import "fmt"
func main() {
//定义方式1:预先定义
var arrnum [3]int //定义长度为3的数组
arrnum[0] = 0
arrnum[1] = 1
arrnum[2] = 2
//定时方式2:定义同时赋值
var arrnum2 [3]int = [3]int{1, 2, 3} //正规写法
var arrnum3 = [3]int{4, 5, 6} //简写形式
//定义方式3:不定长数组方式
var arrnum4 = [...]int{5, 6, 7} //简写形式
//定义方式4:不定长且指定key值形式
var arrnum5 = [...]string{1: "tom", 2: "jack", 3: "marry"} //其中键值不能为字段类型,即:下标
//使用常规的for循环
for i := 0; i < 3; i++ {
fmt.Printf("arrnum:%d \n", arrnum[i])
fmt.Printf("arrnum2:%d \n", arrnum2[i])
fmt.Printf("arrnum3:%d \n", arrnum3[i])
fmt.Printf("arrnum4:%d \n", arrnum4[i])
fmt.Printf("arrnum5:%s \n", arrnum5[i])
}
//使用for-rang循环
for i, v := range arrnum {
fmt.Printf("arrnum:index=%d , value=%d \n", i, v)
}
for i, v := range arrnum2 {
fmt.Printf("arrnum2:index=%d , value=%d \n", i, v)
}
for i, v := range arrnum3 {
fmt.Printf("arrnum3:index=%d , value=%d \n", i, v)
}
for i, v := range arrnum4 {
fmt.Printf("arrnum4:index=%d , value=%d \n", i, v)
}
for i, v := range arrnum5 {
fmt.Printf("arrnum5:index=%d , value=%s \n", i, v)
}
//使用对象打印
fmt.Println(arrnum)
fmt.Println(arrnum2)
fmt.Println(arrnum3)
fmt.Println(arrnum4)
fmt.Println(arrnum5)
}
|
package cmd
import (
"fmt"
"github.com/Caroline1997/Service-Agenda/cli/service"
"github.com/spf13/cobra"
)
var deleteCmd = &cobra.Command{
Use: "delete user",
Short: "for user to delete the account",
Long: `the usage is to delete his own acccount`,
Run: func(cmd *cobra.Command, args []string) {
name, _ := cmd.Flags().GetString("name")
password, _ := cmd.Flags().GetString("password")
err := service.Delete_user(name, password)
if err != nil {
fmt.Println(err)
}
fmt.Println("Delete user successfully!")
},
}
func init() {
RootCmd.AddCommand(deleteCmd)
deleteCmd.Flags().StringP("name", "n", "", "user_name")
deleteCmd.Flags().StringP("password", "p", "", "password")
}
|
package service
import (
"antalk-go/internal/auth/config"
"antalk-go/internal/auth/dao"
proto "antalk-go/internal/proto/pb"
"context"
_ "github.com/go-sql-driver/mysql"
)
type AuthService struct {
c *config.Config
dao *dao.Dao
}
func New(c *config.Config) *AuthService {
s := &AuthService{
c: c,
dao: dao.New(c),
}
return s
}
func (t *AuthService) Login(ctx context.Context, req *proto.CmdReq, resp *proto.CmdResp) error {
loginReq := &proto.LoginReq{}
respMeta := &proto.CmdMeta{}
if err := loginReq.Unmarshal(req.Data); err != nil {
respMeta.ErrorCode = proto.ErrorCode_ERROR_INTERNAL
resp.Meta = respMeta
return nil
}
//根据userid获取用户信息
user, err := t.dao.Get(loginReq.UserId)
if err != nil {
respMeta.ErrorCode = proto.ErrorCode_ERROR_INTERNAL
resp.Meta = respMeta
return nil
}
if user.Password != loginReq.Password {
respMeta.ErrorCode = proto.ErrorCode_ERROR_PASSWORD
resp.Meta = respMeta
return nil
}
respMeta.ErrorCode = proto.ErrorCode_ERROR_NONE
resp.Meta = respMeta
return nil
}
|
package core
import "encoding/json"
type Team struct {
Name string `json:"name"` //team name
AccessGroup []int `json:"accessGroups"`
}
// ToJSON dump User struct
func (u Team) ToJSON() (string, error) {
inrec, err := json.Marshal(u)
if err != nil {
return "", err
}
return string(inrec[:]), err
}
//ToTeam convert map interface to Team object
func ToTeam(val interface{}) (*Team, error) {
var m Team
inrec, err := json.Marshal(val)
if err != nil {
return nil, err
}
err = json.Unmarshal(inrec, &m)
return &m, err
}
|
// Package url2epub fetches http(s) URL and extracts ePub files from them.
package url2epub
|
/*
* Copyright IBM Corporation 2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package generators
import (
"path/filepath"
"github.com/konveyor/move2kube/environment"
transformertypes "github.com/konveyor/move2kube/types/transformer"
)
// ReadMeGenerator implements Transformer interface
type ReadMeGenerator struct {
Config transformertypes.Transformer
Env *environment.Environment
}
// Init initializes the translator
func (t *ReadMeGenerator) Init(tc transformertypes.Transformer, env *environment.Environment) (err error) {
t.Config = tc
t.Env = env
return nil
}
// GetConfig returns the config of the transformer
func (t *ReadMeGenerator) GetConfig() (transformertypes.Transformer, *environment.Environment) {
return t.Config, t.Env
}
// BaseDirectoryDetect executes detect in base directory
func (t *ReadMeGenerator) BaseDirectoryDetect(dir string) (namedServices map[string]transformertypes.ServicePlan, unnamedServices []transformertypes.TransformerPlan, err error) {
return nil, nil, nil
}
// DirectoryDetect executes detect in directories respecting the m2kignore
func (t *ReadMeGenerator) DirectoryDetect(dir string) (namedServices map[string]transformertypes.ServicePlan, unnamedServices []transformertypes.TransformerPlan, err error) {
return nil, nil, nil
}
// Transform transforms the artifacts
func (t *ReadMeGenerator) Transform(newArtifacts []transformertypes.Artifact, oldArtifacts []transformertypes.Artifact) ([]transformertypes.PathMapping, []transformertypes.Artifact, error) {
pathMappings := []transformertypes.PathMapping{}
pathMappings = append(pathMappings, transformertypes.PathMapping{
Type: transformertypes.TemplatePathMappingType,
SrcPath: filepath.Join(t.Env.Context, t.Config.Spec.TemplatesDir),
})
return pathMappings, nil, nil
}
|
package router
import (
"github.com/gin-gonic/gin"
"hd-mall-ed/packages/admin/controller/bannerController"
)
func bannerRouter(router *gin.RouterGroup) {
banner := router.Group("/banner")
{
banner.GET("/list", bannerController.GetBannerList)
}
}
|
package store
import (
"github.com/angeldhakal/tv-tracker/models"
)
func NewUserStore() UserTracker {
return &userStore{
conn: models.Connect(),
}
}
func NewTokenStore() TokenTracker {
return &tokenStore{
conn: models.Connect(),
}
}
func NewMovieStore() MovieTracker {
return &movieStore{
conn: models.Connect(),
}
}
func GetUserByToken(token string) (models.Users, error) {
userStore := NewUserStore()
tokenStore := NewTokenStore()
tokens, err := tokenStore.GetTokenByToken(token)
if err != nil {
return models.Users{}, err
}
user, err := userStore.GetUser(tokens.UserID)
if err != nil {
return models.Users{}, err
}
return user, nil
}
|
package module
import (
"festival/app/model"
"festival/app/model/system"
)
// 点亮线路表
// power by 7be.cn
type ModUserRoute struct {
model.BaseModel
UserId uint `form:"userId" json:"userId" gorm:"column:userId;type:int(11);comment:用户ID;"`
RouteId uint `form:"routeId" json:"routeId" gorm:"column:routeId;type:int(11);comment:线路ID;"`
User system.SysUser `json:"user" gorm:"foreignKey:UserId;references:Id;comment:用户;"`
Route ModRoute `json:"route" gorm:"foreignKey:RouteId;references:Id;comment:线路;"`
}
func (ModUserRoute) TableName() string {
return "mod_user_route"
}
|
package main
import (
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
)
func main() {
m := martini.Classic()
m.Use(render.Renderer())
m.Get("/", func(r render.Render) {
r.JSON(200, map[string]interface{}{"Response": "OK"})
})
m.Run()
}
|
package handlers
import (
"github.com/ChristophBe/grud/types"
"net/http"
)
// NewGetOneHandler returns a http handler for handling requests one specific model.
func NewGetOneHandler(service types.GetOneService, responseWriter types.ResponseWriter, errorWriter types.ErrorResponseWriter) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
model, err := service.GetOne(r)
if err != nil {
errorWriter(err, w, r)
return
}
if err = responseWriter(model, http.StatusOK, w, r); err != nil {
errorWriter(err, w, r)
}
}
}
|
package config
import (
"os"
"strconv"
"strings"
"github.com/jinzhu/gorm"
)
var GormDB *gorm.DB
// DBConfig - holds the config needed to connect to a database.
type DBConfig struct {
DbHost string
DbPort string
DbName string
DbUsername string
DbPassword string
}
// ServerConfig - holds the config that relates to the server.
type ServerConfig struct {
ServerPort string
}
// Config holds all the configs for this app.
type Config struct {
PostgresDB DBConfig
ServerConf ServerConfig
DebugMode bool
}
// New returns a new config struct
func New() *Config {
return &Config{
PostgresDB: DBConfig{
DbHost: getEnv("DBHOST", ""),
DbPort: getEnv("DBPORT", ""),
DbName: getEnv("DBNAME", ""),
DbUsername: getEnv("DBUSERNAME", ""),
DbPassword: getEnv("DBPASSWORD", ""),
},
ServerConf: ServerConfig{
ServerPort: getEnv("SERVERPORT", "1323"),
},
DebugMode: getEnvAsBool("DEBUG_MODE", true),
}
}
// simple func to read enviroment variable and return a default value
func getEnv(key string, defaultVal string) string {
if value, exists := os.LookupEnv(key); exists {
return value
}
return defaultVal
}
// simple function to read an enviroment variable into integer or return a default value
func getEnvAsInt(name string, defaultVal int) int {
valueStr := getEnv(name, "")
if value, err := strconv.Atoi(valueStr); err != nil {
return value
}
return defaultVal
}
// helper to read an enviroment variable into a bool or return a default
func getEnvAsBool(name string, defaultVal bool) bool {
valueStr := getEnv("name", "")
if value, err := strconv.ParseBool(valueStr); err == nil {
return value
}
return defaultVal
}
// helper to read an enviroment variable into string slice or return default value
func getEnvAsSlice(name string, defaultVal []string, sep string) []string {
valueStr := getEnv(name, "")
if valueStr == "" {
return defaultVal
}
val := strings.Split(valueStr, sep)
return val
}
|
package mesos_cli
import "math"
type Slave struct {
Hostname string
Used Resources
Total Resources
}
func (s *Slave) AvailableCpu() float64 {
return s.Total.Cpu - s.Used.Cpu
}
func (s *Slave) AvailableMem() float64 {
return s.Total.Mem - s.Used.Mem
}
func (s *Slave) AllowedInstances(cpu float64, memory float64) int {
allowedByMem := math.Floor(s.AvailableMem() / memory)
allowedByCpu := math.Floor(s.AvailableCpu() / cpu)
return int(math.Min(allowedByCpu, allowedByMem))
}
type Resources struct {
Cpu float64
Mem float64
}
|
package lib
import (
"cloud.google.com/go/datastore"
"context"
"fmt"
"github.com/chidakiyo/benkyo/go-memleak-check/log"
"github.com/gin-gonic/gin"
"net/http"
"os"
)
func OfficialDatastore(g *gin.Context) {
c := g.Request.Context()
result := officialSearchDao(c)
g.JSON(http.StatusOK, result)
}
func OfficialDatastorePointer(g *gin.Context){
c := g.Request.Context()
result := officialSearchDaoPointer(c)
g.JSON(http.StatusOK, result)
}
func officialSearchDao(c context.Context) []Entity {
var result []Entity
ProjID := GetProject()
client, err := datastore.NewClient(c, ProjID)
if err != nil {
log.Fatal(c, "client create error, %s", err.Error())
//panic(err)
return result
}
defer client.Close()
q := datastore.NewQuery(KIND)
_, err = client.GetAll(c, q, &result)
if err != nil {
log.Fatal(c, "fetch error %s", err.Error())
return result
}
return result
}
func officialSearchDaoPointer(c context.Context) *[]Entity {
var result []Entity
ProjID := GetProject()
client, err := datastore.NewClient(c, ProjID)
if err != nil {
log.Fatal(c, "client create error, %s", err.Error())
//panic(err)
return &result
}
defer client.Close()
q := datastore.NewQuery(KIND)
_, err = client.GetAll(c, q, &result)
if err != nil {
log.Fatal(c, "fetch error %s", err.Error())
return &result
}
return &result
}
func DeleteAll(g *gin.Context) {
c := g.Request.Context()
ProjID := os.Getenv("GOOGLE_CLOUD_PROJECT")
client, err := datastore.NewClient(c, ProjID)
if err != nil {
panic(err)
}
defer client.Close()
q := datastore.NewQuery("kind1").KeysOnly()
d := []interface{}{}
keys, err := client.GetAll(c, q, d)
if err != nil {
fmt.Errorf("find error :%s\n", err.Error())
g.String(http.StatusOK, "errorだよ")
return
}
for _, k := range keys {
fmt.Printf("target :%s\n", k.String())
err := client.Delete(c, k)
if err != nil {
fmt.Errorf("delete fail :%s", err.Error())
}
}
g.String(http.StatusOK, "finish")
}
|
package examples
// 以下注释中,多行注释表示对方法的描述,单行注释表示项目的使用方式
/*
* 以 Get 开头的方法将默认只支持 get 请求
*/
func GetUser(id int64) {}
/*
* 使用 `@HttpGet` 表示该方法支持 get 请求
*/
// @HttpGet
func User1() {}
/*
* 使用 `@HttpGet` 与使用 `@HttpPost` 等并不冲突,这样表示该方法支持 get 和 post,
* 但其他方式(例如 delete 等)不予支持。
*/
// @HttpGet
// @HttpPost
func User2() {}
/*
* 不使用任何 HTTP method 说明,代表将允许默认的方法。
* 可以在 chero.SetDefaultMethod 方法中设置,
* 如果不设置,默认允许所有的请求方式。
*/
func User3() {}
/*
* 允许多种请求方式,支持 get、post、put、patch、delete、options,可自由组合。
*/
// @HttpGet
// @HttpPost
// @HttpPut
// @HttpPatch
// @HttpDelete
// @HttpOptions
func User4() {}
|
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package video
import (
"fmt"
"testing"
"chromiumos/tast/common/genparams"
)
// NB: If modifying any of the files or test specifications, be sure to
// regenerate the test parameters by running the following in a chroot:
// TAST_GENERATE_UPDATE=1 ~/trunk/src/platform/tast/tools/go.sh test -count=1 chromiumos/tast/local/bundles/cros/video
func genDataPath(codec, resolution, frameRate string) string {
numFrames := "300"
if frameRate == "60" {
numFrames = "600"
}
extension := fmt.Sprintf("%s.ivf", codec)
if codec == "h264" {
extension = "h264"
} else if codec == "hevc" {
extension = "hevc"
}
return fmt.Sprintf("perf/%s/%sp_%sfps_%sframes.%s", codec, resolution, frameRate, numFrames, extension)
}
func fillSwDeps(codec, resolution, frameRate string) []string {
swDeps := []string{fmt.Sprintf("autotest-capability:hw_dec_%s_%s_%s", codec, resolution, frameRate)}
if codec == "h264" || codec == "hevc" {
swDeps = append(swDeps, "proprietary_codecs")
}
return swDeps
}
func TestChromeStackDecoderPerfParams(t *testing.T) {
type paramData struct {
Name string
File string
ConcurrentDecoders bool
GlobalVAAPILockDisabled bool
SoftwareDeps []string
Metadata []string
Attr []string
}
var params []paramData
var codecs = []string{"av1", "h264", "hevc", "vp8", "vp9"}
var resolutions = []string{"1080", "2160"}
var frameRates = []string{"30", "60"}
for _, codec := range codecs {
for _, resolution := range resolutions {
for _, frameRate := range frameRates {
dataPath := genDataPath(codec, resolution, frameRate)
param := paramData{
Name: fmt.Sprintf("%s_%sp_%sfps", codec, resolution, frameRate),
File: dataPath,
SoftwareDeps: fillSwDeps(codec, resolution, frameRate),
Metadata: []string{dataPath, dataPath + ".json"},
Attr: []string{"graphics_video_decodeaccel"},
}
params = append(params, param)
}
}
}
// Another round for the concurrent decoder tests.
for _, codec := range codecs {
resolution := "1080"
frameRate := "60"
dataPath := genDataPath(codec, resolution, frameRate)
param := paramData{
Name: fmt.Sprintf("%s_%sp_%sfps_concurrent", codec, resolution, frameRate),
File: dataPath,
ConcurrentDecoders: true,
SoftwareDeps: append(fillSwDeps(codec, resolution, frameRate), "thread_safe_libva_backend"),
Metadata: []string{dataPath, dataPath + ".json"},
Attr: []string{"graphics_video_decodeaccel"},
}
params = append(params, param)
}
// Another round for the concurrent decoder tests with VA-API global lock
// disabled.
for _, codec := range codecs {
resolution := "1080"
frameRate := "60"
dataPath := genDataPath(codec, resolution, frameRate)
param := paramData{
Name: fmt.Sprintf("%s_%sp_%sfps_concurrent_global_vaapi_lock_disabled", codec, resolution, frameRate),
File: dataPath,
ConcurrentDecoders: true,
GlobalVAAPILockDisabled: true,
SoftwareDeps: append(fillSwDeps(codec, resolution, frameRate), "thread_safe_libva_backend"),
Metadata: []string{dataPath, dataPath + ".json"},
Attr: []string{"graphics_video_decodeaccel"},
}
params = append(params, param)
}
code := genparams.Template(t, `{{ range . }}{
Name: {{ .Name | fmt }},
Val: chromeStackDecoderPerfParams{
dataPath: {{ .File | fmt }},
runConcurrentDecodersOnly: {{ .ConcurrentDecoders | fmt }},
disableGlobalVaapiLock: {{ .GlobalVAAPILockDisabled | fmt }},
},
{{ if .SoftwareDeps }}
ExtraSoftwareDeps: {{ .SoftwareDeps | fmt }},
{{ end }}
ExtraData: {{ .Metadata | fmt }},
{{ if .Attr }}
ExtraAttr: {{ .Attr | fmt }},
{{ end }}
},
{{ end }}`, params)
genparams.Ensure(t, "chrome_stack_decoder_perf.go", code)
// Clear the params, and compose another set of params with a reduced set of
// codecs, for the legacy variant of the test.
params = nil
var reducedCodecs = []string{"h264", "vp8", "vp9"}
for _, codec := range reducedCodecs {
for _, resolution := range resolutions {
for _, frameRate := range frameRates {
dataPath := genDataPath(codec, resolution, frameRate)
param := paramData{
Name: fmt.Sprintf("%s_%sp_%sfps", codec, resolution, frameRate),
File: dataPath,
SoftwareDeps: fillSwDeps(codec, resolution, frameRate),
Metadata: []string{dataPath, dataPath + ".json"},
Attr: []string{"graphics_video_decodeaccel"},
}
params = append(params, param)
}
}
}
legacyCode := genparams.Template(t, `{{ range . }}{
Name: {{ .Name | fmt }},
Val: {{ .File | fmt }},
{{ if .SoftwareDeps }}
ExtraSoftwareDeps: {{ .SoftwareDeps | fmt }},
{{ end }}
ExtraData: {{ .Metadata | fmt }},
{{ if .Attr }}
ExtraAttr: {{ .Attr | fmt }},
{{ end }}
},
{{ end }}`, params)
genparams.Ensure(t, "chrome_stack_decoder_legacy_perf.go", legacyCode)
}
|
package main
import (
"fmt"
"log"
"os"
)
func main() {
var modulename string
rootmodfiles := []string{"main.tf", "variables.tf", "outputs.tf", "provider.tf"}
childmodfiles := []string{"main.tf", "variables.tf", "outputs.tf", "README.md"}
providersource := "hashicorp/aws"
providerversion := ">= 3.37.0"
tfawsprovider := "terraform{\n\trequired_providers{\n\t\taws = {\n\t\t\tsource = \"" + providersource + "\" \n\t\t\tversion = \"" + providerversion + "\"\n\t\t}\n\t}\n}"
exampleresource := "resource \"aws_accessanalyzer_analyzer\" \"accessanalyzer\" {\n\tanalyzer_name = var.accessanalyzername\n}"
childoutput := "output \"accessanalyzerarn\" {\n\tdescription = \"ARN of the IAM Access Analyzer\"\n\tvalue = aws_accessanalyzer_analyzer.accessanalyzer.arn\n}"
childvar := "variable \"accessanalyzername\" {\n\tdescription = \"Name of the IAM Access Analyzer\"\n\ttype = string\n}"
rootoutput := "output \"accessanalyzerarnuseast1\" {\n\tdescription = \"ARN of the access analyzer\"\n\tvalue = module.accessanalyzeruseast1.accessanalyzerarn\n}"
rootproviders := "provider \"aws\" {\n\tregion = \"us-east-1\"\n\talias = \"useast1\"\n\n\tassume_role{\n\t\trole_arn = \"<role arn>\"\n\t\tsession_name = \"<session name>\"\n\t}\n}"
fmt.Println("Enter terraform module name: ")
fmt.Scanln(&modulename) //terraform-<PROVIDER>-<NAME>
fmt.Printf("Terraform module name: %v\n", "terraform-aws-"+modulename)
rootmain := "module \"accessanalyzeruseast1\" {\n\tsource = \"./modules/" + "terraform-aws-" + modulename + "\"\n\taccessanalyzername = \"accessanalyzeruseast1\"\n\tproviders = {\n\t\taws = aws.useast1\n\t}\n}"
d, err := os.Getwd()
if err != nil {
fmt.Println(err)
}
fmt.Printf("Creating terraform module %v folders and files at %v\n", modulename, d)
makeDir("tf")
changeDir(d + "/tf")
createFile(rootmodfiles)
makeDir("modules")
changeDir(d + "/tf" + "/modules")
makeDir("terraform-aws-" + modulename)
changeDir(d + "/tf" + "/modules" + "/" + "terraform-aws-" + modulename)
createFile(childmodfiles)
openFileandWrite(d+"/tf"+"/modules"+"/"+"terraform-aws-"+modulename+"/main.tf", tfawsprovider+"\n\n"+exampleresource)
openFileandWrite(d+"/tf"+"/modules"+"/"+"terraform-aws-"+modulename+"/outputs.tf", childoutput)
openFileandWrite(d+"/tf"+"/modules"+"/"+"terraform-aws-"+modulename+"/variables.tf", childvar)
openFileandWrite(d+"/tf"+"/main.tf", rootmain)
openFileandWrite(d+"/tf"+"/outputs.tf", rootoutput)
openFileandWrite(d+"/tf"+"/provider.tf", rootproviders)
fmt.Println("Successfully created folders and generated files to write structured Terraform modules following best practices.")
}
func openFileandWrite(path string, s string) {
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
log.Fatal("File could not be opened")
}
_, err = f.Write([]byte(s))
if err != nil {
f.Close() // ignore error; Write error takes precedence
log.Fatal(err)
}
f.Close()
}
func createFile(fn []string) {
for _, f := range fn {
fi, err := os.Create(f)
if err != nil {
log.Fatalln(err)
}
defer fi.Close()
}
}
func changeDir(dirname string) {
err := os.Chdir(dirname)
if err != nil {
log.Fatalln(err)
}
}
func makeDir(dirname string) {
err := os.Mkdir(dirname, 0777)
if err != nil {
log.Fatalln(err)
}
}
|
package mp
import (
"WeChat-golang/mp/core"
"WeChat-golang/mp/user"
"fmt"
"testing"
)
func TestGetAccessToken(t *testing.T) {
srv := &core.AccessTokenServer{
AppId: "wx5d769a50fe0a6589",
AppSecret: "e87a13b7b2e4b39ac884eae60b004404",
}
srv.GetAccessToken()
data, err := user.GetUserList(core.GetClient())
fmt.Println(data.Openid[0])
err = user.GetBaseInfo(core.GetClient(), data.Openid[0])
if err != nil {
fmt.Println(err)
return
}
}
|
package entity
type Discount struct {
Meta *Meta `json:"meta"` // Метаданные
Id string `json:"id"` // Id контактного
AccountId string `json:"accountId"` // Id учетной записи
Name string `json:"name"` // Наименование скидки
Active bool `json:"active"` // Индикатор является ли скидка активной
AllProducts bool `json:"allProducts"` // Индикатор действует ли скидка на все товары
AgentTags []string `json:"agentTags"` // Тэги контрагентов
Assortment []Meta `json:"assortment"` // Массив метаданных товаров и услуг
}
|
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package kv_test
import (
"context"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/testutils/kvclientutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/stretchr/testify/require"
)
// Test the behavior of a txn.Rollback() issued after txn.Commit() failing with
// an ambiguous error.
func TestRollbackAfterAmbiguousCommit(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
testCases := []struct {
name string
// The status of the transaction record at the time when we issue the
// rollback.
txnStatus roachpb.TransactionStatus
// If txnStatus == COMMITTED, setting txnRecordCleanedUp will make us
// cleanup the transaction. The txn record will be deleted.
txnRecordCleanedUp bool
// The error that we expect from txn.Rollback().
expRollbackErr string
// Is the transaction expected to be committed or not after the
// txn.Rollback() call returns?
expCommitted bool
}{
{
name: "txn cleaned up",
txnStatus: roachpb.COMMITTED,
txnRecordCleanedUp: true,
// The transaction will be committed, but at the same time the rollback
// will also appear to succeed (it'll be a no-op). This behavior is
// undesired. See #48302.
expCommitted: true,
expRollbackErr: "",
},
{
name: "COMMITTED",
txnStatus: roachpb.COMMITTED,
txnRecordCleanedUp: false,
expCommitted: true,
expRollbackErr: "already committed",
},
{
name: "STAGING",
txnStatus: roachpb.STAGING,
// The rollback succeeds. This behavior is undersired. See #48301.
expCommitted: false,
expRollbackErr: "",
},
}
for _, testCase := range testCases {
if testCase.txnRecordCleanedUp {
require.Equal(t, roachpb.COMMITTED, testCase.txnStatus)
}
t.Run(testCase.name, func(t *testing.T) {
var filterSet int64
var key roachpb.Key
commitBlocked := make(chan struct{})
args := base.TestServerArgs{
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
// We're going to block the commit of the test's txn, letting the
// test cancel the request's ctx while the request is blocked.
TestingResponseFilter: func(ctx context.Context, ba roachpb.BatchRequest, _ *roachpb.BatchResponse) *roachpb.Error {
if atomic.LoadInt64(&filterSet) == 0 {
return nil
}
req, ok := ba.GetArg(roachpb.EndTxn)
if !ok {
return nil
}
commit := req.(*roachpb.EndTxnRequest)
if commit.Key.Equal(key) && commit.Commit {
// Inform the test that the commit is blocked.
commitBlocked <- struct{}{}
// Block until the client interrupts the commit. The client will
// cancel its context, at which point gRPC will return an error
// to the client and marshall the cancelation to the server.
<-ctx.Done()
}
return nil
},
},
},
}
tci := serverutils.StartNewTestCluster(t, 2, base.TestClusterArgs{ServerArgs: args})
tc := tci.(*testcluster.TestCluster)
defer tc.Stopper().Stop(ctx)
key = tc.ScratchRange(t)
atomic.StoreInt64(&filterSet, 1)
// This test uses a cluster with two nodes. It'll create a transaction
// having as a coordinator the node that's *not* the leaseholder for the
// range the txn is writing to. This is in order for the context
// cancelation scheme that we're going to employ to work: we need a
// non-local RPC such that canceling a requests context triggers an error
// for the request's sender without synchronizing with the request's
// evaluation.
rdesc := tc.LookupRangeOrFatal(t, key)
leaseHolder, err := tc.FindRangeLeaseHolder(rdesc, nil /* hint */)
require.NoError(t, err)
var db *kv.DB
var tr *tracing.Tracer
if leaseHolder.NodeID == 1 {
db = tc.Servers[1].DB()
tr = tc.Servers[1].Tracer().(*tracing.Tracer)
} else {
db = tc.Servers[0].DB()
tr = tc.Servers[0].Tracer().(*tracing.Tracer)
}
txn := db.NewTxn(ctx, "test")
require.NoError(t, txn.Put(ctx, key, "val"))
// If the test wants the transaction to be committed and cleaned up, we'll
// do a read on the key we just wrote. That will act as a pipeline stall,
// resolving the in-flight write and eliminating the need for the STAGING
// status.
if testCase.txnStatus == roachpb.COMMITTED && testCase.txnRecordCleanedUp {
v, err := txn.Get(ctx, key)
require.NoError(t, err)
val, err := v.Value.GetBytes()
require.NoError(t, err)
require.Equal(t, "val", string(val))
}
// Send a commit request. It's going to get blocked after being evaluated,
// at which point we're going to cancel the request's ctx. The ctx
// cancelation will cause gRPC to interrupt the in-flight request, and the
// DistSender to return an ambiguous error. The transaction will be
// committed, through.
commitCtx, cancelCommit := context.WithCancel(ctx)
commitCh := make(chan error)
go func() {
commitCh <- txn.Commit(commitCtx)
}()
select {
case <-commitBlocked:
case <-time.After(10 * time.Second):
t.Fatalf("commit not blocked")
}
cancelCommit()
commitErr := <-commitCh
require.IsType(t, &roachpb.AmbiguousResultError{}, commitErr)
require.Regexp(t, `result is ambiguous \(context done during DistSender.Send: context canceled\)`,
commitErr)
// If the test wants the upcoming rollback to find a COMMITTED record,
// we'll perform transaction recovery. This will leave the transaction in
// the COMMITTED state, without cleaning it up.
if !testCase.txnRecordCleanedUp && testCase.txnStatus == roachpb.COMMITTED {
// Sanity check - verify that the txn is STAGING.
txnProto := txn.TestingCloneTxn()
queryTxn := roachpb.QueryTxnRequest{
RequestHeader: roachpb.RequestHeader{
Key: txnProto.Key,
},
Txn: txnProto.TxnMeta,
}
b := kv.Batch{}
b.AddRawRequest(&queryTxn)
require.NoError(t, db.Run(ctx, &b))
queryTxnRes := b.RawResponse().Responses[0].GetQueryTxn()
require.Equal(t, roachpb.STAGING, queryTxnRes.QueriedTxn.Status)
// Perform transaction recovery.
require.NoError(t, kvclientutils.CheckPushResult(ctx, db, tr, *txn.TestingCloneTxn(),
kvclientutils.ExpectCommitted, kvclientutils.ExpectPusheeTxnRecovery))
}
// Attempt the rollback and check its result.
rollbackErr := txn.Rollback(ctx)
if testCase.expRollbackErr == "" {
require.NoError(t, rollbackErr)
} else {
require.Regexp(t, testCase.expRollbackErr, rollbackErr)
}
// Check the outcome of the transaction, independently from the outcome of
// the Rollback() above, by reading the value that it wrote.
committed := func() bool {
val, err := db.Get(ctx, key)
require.NoError(t, err)
if !val.Exists() {
return false
}
v, err := val.Value.GetBytes()
require.NoError(t, err)
require.Equal(t, "val", string(v))
return true
}()
require.Equal(t, testCase.expCommitted, committed)
})
}
}
|
package nebula
import (
"fmt"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/slackhq/nebula/config"
)
func configLogger(l *logrus.Logger, c *config.C) error {
// set up our logging level
logLevel, err := logrus.ParseLevel(strings.ToLower(c.GetString("logging.level", "info")))
if err != nil {
return fmt.Errorf("%s; possible levels: %s", err, logrus.AllLevels)
}
l.SetLevel(logLevel)
disableTimestamp := c.GetBool("logging.disable_timestamp", false)
timestampFormat := c.GetString("logging.timestamp_format", "")
fullTimestamp := (timestampFormat != "")
if timestampFormat == "" {
timestampFormat = time.RFC3339
}
logFormat := strings.ToLower(c.GetString("logging.format", "text"))
switch logFormat {
case "text":
l.Formatter = &logrus.TextFormatter{
TimestampFormat: timestampFormat,
FullTimestamp: fullTimestamp,
DisableTimestamp: disableTimestamp,
}
case "json":
l.Formatter = &logrus.JSONFormatter{
TimestampFormat: timestampFormat,
DisableTimestamp: disableTimestamp,
}
default:
return fmt.Errorf("unknown log format `%s`. possible formats: %s", logFormat, []string{"text", "json"})
}
return nil
}
|
package constant_test
import "testing"
const (
Monday = iota + 1 // iota 是 golang 语言的常量计数器,只能在常量的表达式中使用。
Tuesday
Wendesday
)
const (
Readable = 1 << iota // 0001
Writable // 0010
Executable // 0100
)
func TestConstantTry(t *testing.T) {
t.Log(Monday, Tuesday)
}
func TestConstantTry1(t *testing.T) {
a := 1 // 0001
// 7 0111
t.Log(Readable, Writable, Executable)
t.Log(a&Readable == Readable, a&Writable == Writable, a&Executable == Executable)
}
|
package response
const (
/**
Datastore
1500~
**/
datastoreError = 1505
)
type Response struct {
Code int
Description string
}
func DatastoreError() interface{} {
return Response{
Code : datastoreError,
Description : "datastore error",
}
}
|
package assert
import "testing"
func TestNotImplementsMatcher(t *testing.T) {
m := Not(NilValue())
var expected *Matcher
err := AssertThat(m, Implements(expected))
if err != nil {
t.Fatal(err)
}
}
func TestNotMatches(t *testing.T) {
err := AssertThat(t, Not(NilValue()))
if err != nil {
t.Fatal(err)
}
}
func TestNotDescription(t *testing.T) {
err := AssertThat(t, Not(NotNilValue()))
if err == nil {
t.Fatal("expect not nil")
}
err = AssertThat(err.Error(), Is("not expected not nil value"))
if err != nil {
t.Fatal(err)
}
}
func TestNotDescriptionWithMessage(t *testing.T) {
err := AssertThat(t, Not(NotNilValue()).Message("foo"))
if err == nil {
t.Fatal("expect not nil")
}
err = AssertThat(err.Error(), Is("foo, not expected not nil value"))
if err != nil {
t.Fatal(err)
}
}
func TestNotDescriptionWithMessageMessage(t *testing.T) {
err := AssertThat(t, Not(NotNilValue().Message("bar")).Message("foo"))
if err == nil {
t.Fatal("expect not nil")
}
err = AssertThat(err.Error(), Is("foo, not bar, expected not nil value"))
if err != nil {
t.Fatal(err)
}
}
|
// Copyright (C) 2017 Google 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 analysis
import "github.com/google/gapid/gapil/semantic"
// Value interface compliance check.
var _ = Value(&BoolValue{})
// BoolValue is an implementation of Value that represents all the possible
// values of a boolean type.
type BoolValue struct {
Possibility
}
// Print returns a textual representation of the value.
func (v *BoolValue) Print(results *Results) string {
return v.String()
}
func (v *BoolValue) String() string {
switch v.Possibility {
case True:
return "True"
case Maybe:
return "Maybe"
case False:
return "False"
case Impossible:
return "Impossible"
default:
return "<unknown bool value>"
}
}
// Type returns semantic.BoolType.
func (v *BoolValue) Type() semantic.Type {
return semantic.BoolType
}
// Not returns the logical negation of v.
func (v *BoolValue) Not() *BoolValue {
return &BoolValue{v.Possibility.Not()}
}
// And returns the logical-and of v and o.
func (v *BoolValue) And(o *BoolValue) *BoolValue {
if v == o {
return v
}
return &BoolValue{v.Possibility.And(o.Possibility)}
}
// Or returns the logical-or of v and o.
func (v *BoolValue) Or(o *BoolValue) *BoolValue {
if v == o {
return v
}
return &BoolValue{v.Possibility.Or(o.Possibility)}
}
// Equivalent returns true iff v and o are equivalent.
// See Value for the definition of equivalency.
func (v *BoolValue) Equivalent(o Value) bool { return v.Possibility == o.(*BoolValue).Possibility }
// Equals returns the possibility of v equaling o.
// o must be of type BoolValue.
func (v *BoolValue) Equals(o Value) Possibility {
if v == o && v.Valid() {
return True
}
return v.Possibility.Equals(o.(*BoolValue).Possibility)
}
// Valid returns true if there is any possibility of this value equaling
// any other.
func (v *BoolValue) Valid() bool {
return v.Possibility != Impossible
}
// Union returns the union of possibile values for v and o.
// o must be of type BoolValue.
func (v *BoolValue) Union(o Value) Value {
if v == o {
return v
}
return &BoolValue{v.Possibility.Union(o.(*BoolValue).Possibility)}
}
// Intersect returns the intersection of possibile values for v and o.
// o must be of type BoolValue.
func (v *BoolValue) Intersect(o Value) Value {
if v == o {
return v
}
return &BoolValue{v.Possibility.Intersect(o.(*BoolValue).Possibility)}
}
// Difference returns the possibile for v that are not found in o.
// o must be of type BoolValue.
func (v *BoolValue) Difference(o Value) Value {
return &BoolValue{v.Possibility.Difference(o.(*BoolValue).Possibility)}
}
// Clone returns a new instance of BoolValue initialized from v.
func (v *BoolValue) Clone() Value {
return &BoolValue{v.Possibility}
}
|
package localfs_test
import (
"fmt"
"github.com/adamluzsi/frameless/ports/filesystem"
"github.com/adamluzsi/testcase/assert"
"io"
"io/fs"
"os"
"path/filepath"
"syscall"
"testing"
filesystemcontracts "github.com/adamluzsi/frameless/ports/filesystem/filesystemcontracts"
"github.com/adamluzsi/frameless/adapters/localfs"
"github.com/adamluzsi/testcase"
)
func ExampleFileSystem() {
fsys := localfs.FileSystem{}
file, err := fsys.OpenFile("test", os.O_RDWR|os.O_CREATE|os.O_EXCL, filesystem.ModeUserRWX)
if err != nil {
panic(err)
}
defer file.Close()
file.Write([]byte("Hello world!"))
file.Seek(0, io.SeekStart)
bs, err := io.ReadAll(file)
if err != nil {
panic(err)
}
fmt.Println(string(bs)) // "Hello world!"
file.Close()
fsys.Remove("test")
fsys.Mkdir("a", filesystem.ModeUserRWX)
file2Name := filepath.Join("a", "test.txt")
file2, err := filesystem.Create(fsys, file2Name)
if err != nil {
panic(err)
}
file2.Close()
file2, err = filesystem.Open(fsys, file2Name)
if err != nil {
panic(err)
}
file2.Close()
filesystem.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
return fs.SkipDir
})
}
func TestLocal_contractsFileSystem(t *testing.T) {
filesystemcontracts.FileSystem(func(tb testing.TB) filesystem.FileSystem {
return localfs.FileSystem{
RootPath: t.TempDir(),
}
}).Test(t)
}
func TestFileSystem_smoke(t *testing.T) {
it := assert.MakeIt(t)
mfs := &localfs.FileSystem{}
name := "test"
file, err := mfs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_APPEND, filesystem.ModeUserRWX)
it.Must.Nil(err)
defer func() { it.Should.Nil(mfs.Remove(name)) }()
_, err = file.Write([]byte("/foo"))
it.Must.Nil(err)
_, err = file.Write([]byte("/bar"))
it.Must.Nil(err)
file.Seek(0, io.SeekStart)
_, err = file.Write([]byte("/baz"))
it.Must.Nil(err)
it.Must.Nil(file.Close())
file, err = mfs.OpenFile(name, os.O_RDONLY, 0)
it.Must.Nil(err)
bs, err := io.ReadAll(file)
it.Must.Nil(err)
it.Must.Equal("/foo/bar/baz", string(bs))
}
func TestLocal_rootPath(t *testing.T) {
s := testcase.NewSpec(t)
getSysTmpDir := func(t *testcase.T) string {
t.Helper()
tmpDir := os.TempDir()
stat, err := os.Stat(tmpDir)
t.Must.Nil(err)
t.Must.True(stat.IsDir())
return tmpDir
}
makeName := func(t *testcase.T) string {
t.Helper()
return fmt.Sprintf("%d-%s",
t.Random.Int(),
t.Random.StringNWithCharset(5, "qwerty"))
}
tmpFile := func(t *testcase.T, dir string) string {
t.Helper()
return filepath.Join(dir, makeName(t))
}
touchFile := func(t *testcase.T, fs filesystem.FileSystem, name string) error {
t.Helper()
file, err := fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, filesystem.ModeUserRWX)
if err == nil {
t.Must.Nil(file.Close())
t.Cleanup(func() { _ = fs.Remove(name) })
}
return err
}
s.Test("without .RootPath set, fs is not jailed", func(t *testcase.T) {
tmpDir := t.TempDir()
fs := localfs.FileSystem{}
name := tmpFile(t, tmpDir)
t.Must.Nil(touchFile(t, fs, name))
_, err := os.Stat(name)
t.Must.Nil(err)
name = tmpFile(t, getSysTmpDir(t))
t.Must.Nil(touchFile(t, fs, name))
_, err = os.Stat(name)
t.Must.Nil(err)
})
s.Test("with .RootPath set, fs is jailed and path used as relative path", func(t *testcase.T) {
tmpDir := t.TempDir()
fs := localfs.FileSystem{RootPath: tmpDir}
name := makeName(t)
t.Must.Nil(touchFile(t, fs, name))
_, err := os.Stat(filepath.Join(tmpDir, name))
t.Must.Nil(err)
_, err = fs.Stat(name)
t.Must.Nil(err)
t.Must.Nil(fs.Mkdir(makeName(t), filesystem.ModeUserRWX))
t.Must.Nil(fs.Remove(name))
path := filepath.Join("..", name)
t.Must.ErrorIs(syscall.EACCES, touchFile(t, fs, path))
t.Must.ErrorIs(syscall.EACCES, fs.Mkdir(path, 0700))
t.Must.ErrorIs(syscall.EACCES, func() error { _, err := fs.Stat(path); return err }())
t.Must.ErrorIs(syscall.EACCES, fs.Remove(path))
})
}
|
package main
import "fmt"
/*
- &&
- ||
- !
- Qual o resultado de fmt.Println...
- true && true
- true && false
- true || true
- true || false
- !true
*/
func main() {
x := 9
if !(x%2 == 0) && x%3 == 0 {
fmt.Println("é múltiplo de dois e tambem de treis")
}
// if x%2 == 0 || x%3 == 0 {
// fmt.Println("é múltiplo de dois ou de treis")
// }
}
|
package Concurrency_Pattern
import "fmt"
// PlusOne returns a channel of num+1 for received from in.
func PlusOne(in <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for num := range in {
out <- num + 1
}
}()
return out
}
func ExamplePlusOne() {
c := make(chan int)
go func() {
defer close(c)
c <- 5
c <- 3
c <- 8
}()
for num := range PlusOne(PlusOne(c)) {
fmt.Println(num)
}
// Output:
// 7
// 5
// 10
}
|
package guile
import (
"github.com/nlandolfi/set"
"github.com/nlandolfi/set/relation"
)
// --- Economic Interpretation {{{
type (
Alternative set.Element
Alternatives set.Interface
Preference relation.AbstractInterface
PreferenceProfile []Preference
SocialWelfareFunction func(PreferenceProfile) Preference
)
// --- }}}
// -- Preference Implementation {{{
func Rational(p Preference) bool {
return relation.WeakOrder(p)
}
func ComposablePreferences(prefs []Preference) bool {
br := make([]relation.AbstractInterface, len(prefs))
for i := range prefs {
br[i] = relation.AbstractInterface(prefs[i])
}
return relation.ComposableRelations(br)
}
func ProfileUniverse(p PreferenceProfile) Alternatives {
assert(len(p) > 0, "preference profile empty")
assert(ComposablePreferences(p), "preferneces not defined over same universe")
return p[0].Universe()
}
// CountPreferenceOf returns the number of people who prefer x to y in the preference profile pp
func CountPreferenceOf(x, y Alternative, pp PreferenceProfile) float64 {
return CountWeightedPreferenceOf(x, y, pp, func(i uint) float64 { return 1 })
}
// CountWeightedPreferenceOf returns the weigth of people who prefer x, y in preference profile pp
func CountWeightedPreferenceOf(x, y Alternative, pp PreferenceProfile, w func(uint) float64) float64 {
c := 0.0
for i, p := range pp {
if p.ContainsRelation(x, y) {
c += w(uint(i))
}
}
return c
}
func BordaCount(x Alternative, p Preference) uint {
c := uint(0)
for _, e := range p.Universe().Elements() {
if p.ContainsRelation(x, e) {
c += 1
}
}
return c
}
func ProfileBordaCount(x Alternative, pp PreferenceProfile) uint {
c := uint(0)
for _, p := range pp {
c += BordaCount(x, p)
}
return c
}
// --- }}}
// --- Social Welfare Function Implementations {{{
func PairwiseMajority(pp PreferenceProfile) Preference {
u := ProfileUniverse(pp)
return relation.NewFunctionBinaryRelation(u, func(x, y set.Element) bool {
return CountPreferenceOf(x, y, pp) >= CountPreferenceOf(y, x, pp)
})
}
func BordaCounting(pp PreferenceProfile) Preference {
u := ProfileUniverse(pp)
return relation.NewFunctionBinaryRelation(u, func(x, y set.Element) bool {
return ProfileBordaCount(x, pp) >= ProfileBordaCount(y, pp)
})
}
func Dictatorship(pp PreferenceProfile, individual uint) Preference {
return pp[individual]
}
func AntiDictatorship(pp PreferenceProfile, individual uint) Preference {
return relation.Reverse(pp[individual])
}
func Constant(pp PreferenceProfile, actual Preference) Preference {
// interesting how explicit it become that a constant one depends not on the PreferenceProfile
return actual
}
func WeightedMajority(pp PreferenceProfile, w func(uint) float64) Preference {
u := ProfileUniverse(pp)
return relation.NewFunctionBinaryRelation(u, func(x, y set.Element) bool {
return CountWeightedPreferenceOf(x, y, pp, w) >= CountWeightedPreferenceOf(y, x, pp, w)
})
}
// --- }}}
// --- Choice Functions {{{
func MostPreferred(p Preference) Alternative {
seen := make(map[Alternative]bool)
elements := p.Universe().Elements()
assert(len(elements) > 0, "set of alternatives must have cardinality > 0")
preferred := elements[0]
seen[preferred] = true
for _, e := range elements {
if _, ok := seen[e]; ok {
continue
}
if p.ContainsRelation(preferred, e) {
continue
}
if p.ContainsRelation(e, preferred) {
preferred = e
}
}
return preferred
}
// --- }}}
|
// chaosTester project main.go
package main
import (
"configutil"
"fmt"
"os"
"sync"
"testkicker"
"io/ioutil"
"log"
"strings"
"webservices"
"gopkg.in/yaml.v3"
)
var wg sync.WaitGroup
var args []string
func startTest(ch chan string) {
defer wg.Done()
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
data, err := ioutil.ReadFile("Config.yaml")
if err != nil {
log.Fatalln(err)
}
config := configutil.Config{}
err = yaml.Unmarshal(data, &config)
if err != nil {
log.Fatalln(err)
}
ch <- testkicker.Kick(config, args)
}
func main() {
b_Test := true
b_Web := false
args = os.Args[1:]
if len(args) != 0 {
split := strings.Split(args[0], "-")
if strings.Contains(split[1], "w") {
b_Web = true
}
if strings.Contains(split[1], "n") {
b_Test = false
}
}
if b_Test {
ch := make(chan string, 1)
go startTest(ch)
wg.Add(1)
wg.Wait()
close(ch)
// _, ok := <-ch
// if ok {
// webservices.Start()
// } else {
// fmt.Println("Starting webservices failed!!")
// }
}
if b_Web {
webservices.Start()
}
if !b_Test && !b_Web {
fmt.Println("F**K YOU!!")
}
}
|
package main
import (
"flag"
"log"
"net/http"
"regexp"
"strconv"
"sync"
"time"
"github.com/sevlyar/go-daemon"
"github.com/golang/glog"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/wanghengwei/monclient/conf"
"github.com/wanghengwei/monclient/proc"
)
var (
cpu = promauto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "x51",
Name: "cpu_usage",
Help: "CPU Usage",
}, []string{"cmd", "pid"})
mem = promauto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "x51",
Name: "mem_virt",
Help: "Memory Usage",
}, []string{"cmd", "pid"})
netRecv = promauto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "x51",
Name: "net_recv",
Help: "Received Bytes",
}, []string{"cmd", "pid", "port"})
// 发送的字节数
netSendFrom = promauto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "x51",
Name: "net_sendfrom",
Help: "send bytes from local port",
}, []string{"cmd", "pid", "port"})
// 向某个远程地址发送的字节数
netSendTo = promauto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "x51",
Name: "net_sendto",
Help: "send bytes to remote address",
}, []string{"cmd", "pid", "addr", "port"})
// 收的event
eventRecvCount = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: "x51",
Name: "event_recv_count",
Help: "Count of Received Events",
}, []string{"service", "pid", "event"})
eventRecvSize = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: "x51",
Name: "event_recv_size",
Help: "Size of Received Events",
}, []string{"service", "pid", "event"})
// 发的event
eventSendCount = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: "x51",
Name: "event_send_count",
Help: "Count of Sent Events",
}, []string{"service", "pid", "event"})
eventSendSize = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: "x51",
Name: "event_send_size",
Help: "Size of Sent Events",
}, []string{"service", "pid", "event"})
// args
runAsDaemon = flag.Bool("d", false, "as daemon")
)
// App 总入口
type App struct {
config *conf.Config
configMux sync.Mutex
cfgLoaders []conf.ConfigLoader
}
func NewApp() *App {
app := &App{
config: &conf.Config{},
}
app.cfgLoaders = []conf.ConfigLoader{
conf.NewHttpConfigLoader("http://cfg.monitor.tac.com/monclient-default.json", app.config),
conf.NewDefaultConfigLoader(app.config),
}
return app
}
func (app *App) loadConfig() {
app.configMux.Lock()
defer app.configMux.Unlock()
for _, cl := range app.cfgLoaders {
err := cl.Load()
if err == nil {
glog.Infof("load config done. config=%v\n", app.config)
break
} else {
glog.Infof("load config error, try next ConfigLoader. error=%s\n", err)
}
}
}
func (app *App) getConfig() conf.Config {
app.configMux.Lock()
defer app.configMux.Unlock()
return *app.config
}
// Run 执行主任务。不会返回
func (app *App) Run() error {
app.loadConfig()
// 后台更新config
go func() {
time.Sleep(25 * time.Second)
app.loadConfig()
}()
// 获得cpu、mem等数据,这些数据来源于周期性的执行系统命令,比如ps
go func() {
pm := proc.NewProcessMonitor()
for {
// 每次循环开头都应用下配置,因为配置可能会运行时刷新
cfg := app.getConfig()
glog.V(1).Infof("config=%v\n", cfg)
// 设置本地端口黑名单
pm.ClearBlacklist()
setPortBlacklist(cfg.Port.Excludes, pm.AddSinglePortToLocalBlacklist, pm.AddPortRangeToLocalBlacklist)
setPortBlacklist(cfg.Port.Excludes, pm.AddSinglePortToRemoteBlacklist, pm.AddPortRangeToRemoteBlacklist)
// 设置进程黑白名单
pm.AddIncludes(cfg.Command.Includes...)
pm.AddExcludes(cfg.Command.Excludes...)
log.Printf("snapping...\n")
err := pm.Snap()
if err != nil {
log.Println("Snap FAILED: %s\n", err)
} else {
for _, proc := range pm.Procs {
cpu.WithLabelValues(proc.Command, strconv.Itoa(proc.PID)).Set(float64(proc.CPU))
mem.WithLabelValues(proc.Command, strconv.Itoa(proc.PID)).Set(float64(proc.MemoryVirtual))
for _, l := range proc.ListenPorts {
netRecv.WithLabelValues(proc.Command, strconv.Itoa(proc.PID), strconv.Itoa(l.Port)).Set(float64(l.InBytes))
netSendFrom.WithLabelValues(proc.Command, strconv.Itoa(proc.PID), strconv.Itoa(l.Port)).Set(float64(l.OutBytes))
}
for _, c := range proc.ClientConns {
netSendTo.WithLabelValues(proc.Command, strconv.Itoa(proc.PID), c.Address, strconv.Itoa(c.Port)).Set(float64(c.Bytes))
}
}
}
time.Sleep(10 * time.Second)
}
}()
// 通过log来分析event数量
// go func() {
// cfg := app.getConfig()
// f := func(c *prometheus.CounterVec) func(string, int, string, int) {
// return func(srv string, pid int, ev string, n int) {
// c.WithLabelValues(srv, strconv.Itoa(pid), ev).Add(float64(n))
// }
// }
// lc := x51log.NewX51EventLogCollector(cfg.X51Log.Folder, f(eventSendCount), f(eventSendSize), f(eventRecvCount), f(eventRecvSize))
// err := lc.Run()
// if err != nil {
// glog.Errorf("tail x51 logs failed: %s\n", err)
// }
// }()
http.Handle("/metrics", promhttp.Handler())
return http.ListenAndServe(":10001", nil)
}
func main() {
flag.Parse()
// 这段if是为了用daemon方式运行
if *runAsDaemon {
ctx := daemon.Context{
PidFileName: "/tmp/monclient.pid",
WorkDir: "/tmp",
}
d, err := ctx.Reborn()
if err != nil {
log.Fatal(err)
}
if d != nil {
return
}
defer ctx.Release()
}
// 启动应用
app := NewApp()
if err := app.Run(); err != nil {
log.Fatal(err)
}
}
func setPortBlacklist(ports []string, f1 func(int), f2 func(int, int)) {
numberRe := regexp.MustCompile(`^(\d+)$`)
rangeRe := regexp.MustCompile(`^(\d+)-(\d+)$`)
for _, s := range ports {
if ss := numberRe.FindStringSubmatch(s); len(ss) > 0 {
port, _ := strconv.Atoi(ss[1])
f1(port)
} else if ss := rangeRe.FindStringSubmatch(s); len(ss) > 0 {
a, _ := strconv.Atoi(ss[1])
b, _ := strconv.Atoi(ss[2])
f2(a, b)
}
}
}
|
package main
import (
"flag"
"net/url"
"github.com/gorilla/websocket"
"fmt"
"io/ioutil"
)
var serveraddr = flag.String("s1","127.0.0.1:9630","http service address")
var serverurl = url.URL{Scheme:"ws",Host:*serveraddr,Path:"/echo"}
var data = []byte(`bad new`)
func main(){
client,_,_ := websocket.DefaultDialer.Dial(serverurl.String(),nil)
client.WriteMessage(websocket.TextMessage,data)
recMsgType, recMsg,err := client.ReadMessage()
if err != nil {
fmt.Println("err:",err)
return
}
fmt.Println("recMsgType:",recMsgType)
fmt.Println("recMsg:",string(recMsg))
fmt.Println(client.LocalAddr().String())
fmt.Println(client.LocalAddr().Network())
_,iii,_ := client.NextReader()
p2,_ :=ioutil.ReadAll(iii)
fmt.Println("p2:",string(p2))
client.Close()
}
|
// Copyright 2019 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// esxiboot executes ESXi kernel over the running kernel.
//
// Synopsis:
// esxiboot --config <config>
//
// Description:
// Loads and executes ESXi kernel.
//
// Options:
// --config=FILE or -c=FILE: set the ESXi config
//
// The config file has the following syntax:
//
// kernel=PATH
// kernelopt=OPTS
// modules=MOD1 [ARGS] --- MOD2 [ARGS] --- ...
//
// Lines starting with '#' are ignored.
package main
import (
"bufio"
"fmt"
"log"
"os"
"path/filepath"
"strings"
flag "github.com/spf13/pflag"
"github.com/u-root/u-root/pkg/kexec"
"github.com/u-root/u-root/pkg/multiboot"
)
var cfg = flag.StringP("config", "c", "", "Set the ESXi config")
const (
kernel = "kernel"
args = "kernelopt"
modules = "modules"
comment = '#'
sep = "---"
)
type options struct {
kernel string
args string
modules []string
}
func parse(fname string) (options, error) {
f, err := os.Open(fname)
if err != nil {
log.Fatal(err)
}
defer f.Close()
var opt options
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
line = strings.TrimSpace(line)
if len(line) == 0 || line[0] == comment {
continue
}
tokens := strings.SplitN(line, "=", 2)
if len(tokens) != 2 {
return opt, fmt.Errorf("bad line %q", line)
}
key := strings.TrimSpace(tokens[0])
val := strings.TrimSpace(tokens[1])
switch key {
case kernel:
opt.kernel = val
case args:
opt.args = val
case modules:
for _, tok := range strings.Split(val, sep) {
tok = strings.TrimSpace(tok)
opt.modules = append(opt.modules, tok)
}
}
}
err = scanner.Err()
return opt, err
}
func main() {
flag.Parse()
if *cfg == "" {
log.Fatalf("Config cannot be empty")
}
opts, err := parse(*cfg)
if err != nil {
log.Fatalf("Cannot parse config %v: %v", *cfg, err)
}
p, err := os.Executable()
if err != nil {
log.Fatalf("Cannot find current executable path: %v", err)
}
trampoline, err := filepath.EvalSymlinks(p)
if err != nil {
log.Fatalf("Cannot eval symlinks for %v: %v", p, err)
}
m := multiboot.New(opts.kernel, opts.args, trampoline, opts.modules)
if err := m.Load(false); err != nil {
log.Fatalf("Load failed: %v", err)
}
if err := kexec.Load(m.EntryPoint, m.Segments(), 0); err != nil {
log.Fatalf("kexec.Load() error: %v", err)
}
if err := kexec.Reboot(); err != nil {
log.Fatalf("kexec.Reboot() error: %v", err)
}
}
|
// Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package optbuilder
import (
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/opt"
"github.com/cockroachdb/cockroach/pkg/sql/opt/cat"
"github.com/cockroachdb/cockroach/pkg/sql/opt/memo"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/errors"
)
// buildJoin builds a set of memo groups that represent the given join table
// expression.
//
// See Builder.buildStmt for a description of the remaining input and
// return values.
func (b *Builder) buildJoin(
join *tree.JoinTableExpr, locking lockingSpec, inScope *scope,
) (outScope *scope) {
leftScope := b.buildDataSource(join.Left, nil /* indexFlags */, locking, inScope)
isLateral := false
inScopeRight := inScope
// If this is a lateral join, use leftScope as inScope for the right side.
// The right side scope of a LATERAL join includes the columns produced by
// the left side.
if t, ok := join.Right.(*tree.AliasedTableExpr); ok && t.Lateral {
telemetry.Inc(sqltelemetry.LateralJoinUseCounter)
isLateral = true
inScopeRight = leftScope
inScopeRight.context = exprKindLateralJoin
}
rightScope := b.buildDataSource(join.Right, nil /* indexFlags */, locking, inScopeRight)
// Check that the same table name is not used on both sides.
b.validateJoinTableNames(leftScope, rightScope)
joinType := descpb.JoinTypeFromAstString(join.JoinType)
var flags memo.JoinFlags
switch join.Hint {
case "":
case tree.AstHash:
telemetry.Inc(sqltelemetry.HashJoinHintUseCounter)
flags = memo.AllowOnlyHashJoinStoreRight
case tree.AstLookup:
telemetry.Inc(sqltelemetry.LookupJoinHintUseCounter)
flags = memo.AllowOnlyLookupJoinIntoRight
if joinType != descpb.InnerJoin && joinType != descpb.LeftOuterJoin {
panic(pgerror.Newf(pgcode.Syntax,
"%s can only be used with INNER or LEFT joins", tree.AstLookup,
))
}
case tree.AstInverted:
telemetry.Inc(sqltelemetry.InvertedJoinHintUseCounter)
flags = memo.AllowOnlyInvertedJoinIntoRight
if joinType != descpb.InnerJoin && joinType != descpb.LeftOuterJoin {
// At this point in the code there are no semi or anti joins, because we
// only have the original AST from the parser. Semi and anti joins don't
// exist until we build the memo and apply normalization rules to convert
// EXISTS and NOT EXISTS to joins.
panic(pgerror.Newf(pgcode.Syntax,
"%s can only be used with INNER or LEFT joins", tree.AstInverted,
))
}
case tree.AstMerge:
telemetry.Inc(sqltelemetry.MergeJoinHintUseCounter)
flags = memo.AllowOnlyMergeJoin
default:
panic(pgerror.Newf(
pgcode.FeatureNotSupported, "join hint %s not supported", join.Hint,
))
}
switch cond := join.Cond.(type) {
case tree.NaturalJoinCond, *tree.UsingJoinCond:
outScope = inScope.push()
var jb usingJoinBuilder
jb.init(b, joinType, flags, leftScope, rightScope, outScope)
switch t := cond.(type) {
case tree.NaturalJoinCond:
jb.buildNaturalJoin(t)
case *tree.UsingJoinCond:
jb.buildUsingJoin(t)
}
return outScope
case *tree.OnJoinCond, nil:
// Append columns added by the children, as they are visible to the filter.
outScope = inScope.push()
outScope.appendColumnsFromScope(leftScope)
outScope.appendColumnsFromScope(rightScope)
var filters memo.FiltersExpr
if on, ok := cond.(*tree.OnJoinCond); ok {
// Do not allow special functions in the ON clause.
b.semaCtx.Properties.Require(
exprKindOn.String(), tree.RejectGenerators|tree.RejectWindowApplications,
)
outScope.context = exprKindOn
filter := b.buildScalar(
outScope.resolveAndRequireType(on.Expr, types.Bool), outScope, nil, nil, nil,
)
filters = memo.FiltersExpr{b.factory.ConstructFiltersItem(filter)}
} else {
filters = memo.TrueFilter
}
left := leftScope.expr.(memo.RelExpr)
right := rightScope.expr.(memo.RelExpr)
outScope.expr = b.constructJoin(
joinType, left, right, filters, &memo.JoinPrivate{Flags: flags}, isLateral,
)
return outScope
default:
panic(errors.AssertionFailedf("unsupported join condition %#v", cond))
}
}
// validateJoinTableNames checks that table names are not repeated between the
// left and right sides of a join. leftTables contains a pre-built map of the
// tables from the left side of the join, and rightScope contains the
// scopeColumns (and corresponding table names) from the right side of the
// join.
func (b *Builder) validateJoinTableNames(leftScope, rightScope *scope) {
// Try to derive smaller subset of columns which need to be validated.
leftOrds := b.findJoinColsToValidate(leftScope)
rightOrds := b.findJoinColsToValidate(rightScope)
// Look for table name in left scope that exists in right scope.
for left, ok := leftOrds.Next(0); ok; left, ok = leftOrds.Next(left + 1) {
leftName := &leftScope.cols[left].table
for right, ok := rightOrds.Next(0); ok; right, ok = rightOrds.Next(right + 1) {
rightName := &rightScope.cols[right].table
// Must match all name parts.
if leftName.ObjectName != rightName.ObjectName ||
leftName.SchemaName != rightName.SchemaName ||
leftName.CatalogName != rightName.CatalogName {
continue
}
panic(pgerror.Newf(
pgcode.DuplicateAlias,
"source name %q specified more than once (missing AS clause)",
tree.ErrString(&leftName.ObjectName),
))
}
}
}
// findJoinColsToValidate creates a FastIntSet containing the ordinal of each
// column that has a different table name than the previous column. This is a
// fast way of reducing the set of columns that need to checked for duplicate
// names by validateJoinTableNames.
func (b *Builder) findJoinColsToValidate(scope *scope) util.FastIntSet {
var ords util.FastIntSet
for i := range scope.cols {
// Allow joins of sources that define columns with no
// associated table name. At worst, the USING/NATURAL
// detection code or expression analysis for ON will detect an
// ambiguity later.
if scope.cols[i].table.ObjectName == "" {
continue
}
if i == 0 || scope.cols[i].table != scope.cols[i-1].table {
ords.Add(i)
}
}
return ords
}
var invalidLateralJoin = pgerror.New(pgcode.Syntax, "The combining JOIN type must be INNER or LEFT for a LATERAL reference")
func (b *Builder) constructJoin(
joinType descpb.JoinType,
left, right memo.RelExpr,
on memo.FiltersExpr,
private *memo.JoinPrivate,
isLateral bool,
) memo.RelExpr {
switch joinType {
case descpb.InnerJoin:
if isLateral {
return b.factory.ConstructInnerJoinApply(left, right, on, private)
}
return b.factory.ConstructInnerJoin(left, right, on, private)
case descpb.LeftOuterJoin:
if isLateral {
return b.factory.ConstructLeftJoinApply(left, right, on, private)
}
return b.factory.ConstructLeftJoin(left, right, on, private)
case descpb.RightOuterJoin:
if isLateral {
panic(invalidLateralJoin)
}
return b.factory.ConstructRightJoin(left, right, on, private)
case descpb.FullOuterJoin:
if isLateral {
panic(invalidLateralJoin)
}
return b.factory.ConstructFullJoin(left, right, on, private)
default:
panic(pgerror.Newf(pgcode.FeatureNotSupported,
"unsupported JOIN type %d", joinType))
}
}
// usingJoinBuilder helps to build a USING join or natural join. It finds the
// columns in the left and right relations that match the columns provided in
// the names parameter (or names common to both sides in case of natural join),
// and creates equality predicate(s) with those columns. It also ensures that
// there is a single output column for each match name (other columns with the
// same name are hidden).
//
// -- Merged columns --
//
// With NATURAL JOIN or JOIN USING (a,b,c,...), SQL allows us to refer to the
// columns a,b,c directly; these columns have the following semantics:
// a = IFNULL(left.a, right.a)
// b = IFNULL(left.b, right.b)
// c = IFNULL(left.c, right.c)
// ...
//
// Furthermore, a star has to resolve the columns in the following order:
// merged columns, non-equality columns from the left table, non-equality
// columns from the right table. To perform this rearrangement, we use a
// projection on top of the join. Note that the original columns must
// still be accessible via left.a, right.a (they will just be hidden).
//
// For inner or left outer joins, a is always the same as left.a.
//
// For right outer joins, a is always equal to right.a; but for some types
// (like collated strings), this doesn't mean it is the same as right.a. In
// this case we must still use the IFNULL construct.
//
// Example:
//
// left has columns (a,b,x)
// right has columns (a,b,y)
//
// - SELECT * FROM left JOIN right USING(a,b)
//
// join has columns:
// 1: left.a
// 2: left.b
// 3: left.x
// 4: right.a
// 5: right.b
// 6: right.y
//
// projection has columns and corresponding variable expressions:
// 1: a aka left.a @1
// 2: b aka left.b @2
// 3: left.x @3
// 4: right.a (hidden) @4
// 5: right.b (hidden) @5
// 6: right.y @6
//
// If the join was a FULL OUTER JOIN, the columns would be:
// 1: a IFNULL(@1,@4)
// 2: b IFNULL(@2,@5)
// 3: left.a (hidden) @1
// 4: left.b (hidden) @2
// 5: left.x @3
// 6: right.a (hidden) @4
// 7: right.b (hidden) @5
// 8: right.y @6
//
type usingJoinBuilder struct {
b *Builder
joinType descpb.JoinType
joinFlags memo.JoinFlags
filters memo.FiltersExpr
leftScope *scope
rightScope *scope
outScope *scope
// hideCols contains the join columns which are hidden in the result
// expression. Note that we cannot simply store the column ids since the
// same column may be used multiple times with different aliases.
hideCols map[*scopeColumn]struct{}
// showCols contains the join columns which are not hidden in the result
// expression. Note that we cannot simply store the column ids since the
// same column may be used multiple times with different aliases.
showCols map[*scopeColumn]struct{}
// ifNullCols contains the ids of each synthesized column which performs the
// IFNULL check for a pair of join columns.
ifNullCols opt.ColSet
}
func (jb *usingJoinBuilder) init(
b *Builder,
joinType descpb.JoinType,
flags memo.JoinFlags,
leftScope, rightScope, outScope *scope,
) {
// This initialization pattern ensures that fields are not unwittingly
// reused. Field reuse must be explicit.
*jb = usingJoinBuilder{
b: b,
joinType: joinType,
joinFlags: flags,
leftScope: leftScope,
rightScope: rightScope,
outScope: outScope,
hideCols: make(map[*scopeColumn]struct{}),
showCols: make(map[*scopeColumn]struct{}),
}
}
// buildUsingJoin constructs a Join operator with join columns matching the
// the names in the given join condition.
func (jb *usingJoinBuilder) buildUsingJoin(using *tree.UsingJoinCond) {
var seenCols opt.ColSet
for _, name := range using.Cols {
// Find left and right USING columns in the scopes.
leftCol := jb.findUsingColumn(jb.leftScope.cols, name, "left table")
if leftCol == nil {
jb.raiseUndefinedColError(name, "left")
}
if seenCols.Contains(leftCol.id) {
// Same name exists more than once in USING column name list.
panic(pgerror.Newf(pgcode.DuplicateColumn,
"column name %q appears more than once in USING clause", tree.ErrString(&name)))
}
seenCols.Add(leftCol.id)
rightCol := jb.findUsingColumn(jb.rightScope.cols, name, "right table")
if rightCol == nil {
jb.raiseUndefinedColError(name, "right")
}
jb.b.trackReferencedColumnForViews(leftCol)
jb.b.trackReferencedColumnForViews(rightCol)
jb.addEqualityCondition(leftCol, rightCol)
}
jb.finishBuild()
}
// buildNaturalJoin constructs a Join operator with join columns derived from
// matching names in the left and right inputs.
func (jb *usingJoinBuilder) buildNaturalJoin(natural tree.NaturalJoinCond) {
// Only add equality conditions for non-hidden columns with matching name in
// both the left and right inputs.
var seenCols opt.ColSet
for i := range jb.leftScope.cols {
leftCol := &jb.leftScope.cols[i]
if leftCol.visibility != cat.Visible {
continue
}
if seenCols.Contains(leftCol.id) {
// Don't raise an error if the id matches but it has a different name.
for j := 0; j < i; j++ {
col := &jb.leftScope.cols[j]
if col.id == leftCol.id && col.name == leftCol.name {
jb.raiseDuplicateColError(leftCol.name, "left table")
}
}
}
seenCols.Add(leftCol.id)
rightCol := jb.findUsingColumn(jb.rightScope.cols, leftCol.name, "right table")
if rightCol != nil {
jb.b.trackReferencedColumnForViews(leftCol)
jb.b.trackReferencedColumnForViews(rightCol)
jb.addEqualityCondition(leftCol, rightCol)
}
}
jb.finishBuild()
}
// finishBuild adds any non-join columns to the output scope and then constructs
// the Join operator. If at least one "if null" column exists, the join must be
// wrapped in a Project operator that performs the required IFNULL checks.
func (jb *usingJoinBuilder) finishBuild() {
jb.addRemainingCols(jb.leftScope.cols)
jb.addRemainingCols(jb.rightScope.cols)
jb.outScope.expr = jb.b.constructJoin(
jb.joinType,
jb.leftScope.expr.(memo.RelExpr),
jb.rightScope.expr.(memo.RelExpr),
jb.filters,
&memo.JoinPrivate{Flags: jb.joinFlags},
false, /* isLateral */
)
if !jb.ifNullCols.Empty() {
// Wrap in a projection to include the merged columns and ensure that all
// remaining columns are passed through unchanged.
for i := range jb.outScope.cols {
col := &jb.outScope.cols[i]
if !jb.ifNullCols.Contains(col.id) {
// Mark column as passthrough.
col.scalar = nil
}
}
jb.outScope.expr = jb.b.constructProject(jb.outScope.expr.(memo.RelExpr), jb.outScope.cols)
}
}
// addRemainingCols iterates through each of the columns in cols and performs
// one of the following actions:
// (1) If the column is part of the hideCols set, then it is a join column that
// needs to be added to output scope, with the hidden attribute set to true.
// (2) If the column is part of the showCols set, then it is a join column that
// has already been added to the output scope by addEqualityCondition, so
// skip it now.
// (3) All other columns are added to the scope without modification.
func (jb *usingJoinBuilder) addRemainingCols(cols []scopeColumn) {
for i := range cols {
col := &cols[i]
if _, ok := jb.hideCols[col]; ok {
jb.outScope.cols = append(jb.outScope.cols, *col)
jb.outScope.cols[len(jb.outScope.cols)-1].visibility = cat.Hidden
} else if _, ok := jb.showCols[col]; !ok {
jb.outScope.cols = append(jb.outScope.cols, *col)
}
}
}
// findUsingColumn finds the column in cols that has the given name. If no such
// column exists, findUsingColumn returns nil. If multiple columns with the name
// exist, then findUsingColumn raises an error. The context is used for error
// reporting.
func (jb *usingJoinBuilder) findUsingColumn(
cols []scopeColumn, name tree.Name, context string,
) *scopeColumn {
var foundCol *scopeColumn
for i := range cols {
col := &cols[i]
if col.visibility == cat.Visible && col.name == name {
if foundCol != nil {
jb.raiseDuplicateColError(name, context)
}
foundCol = col
}
}
return foundCol
}
// addEqualityCondition constructs a new Eq expression comparing the given left
// and right columns. In addition, it adds a new column to the output scope that
// represents the "merged" value of the left and right columns. This could be
// either the left or right column value, or, in the case of a FULL JOIN, an
// IFNULL(left, right) expression.
func (jb *usingJoinBuilder) addEqualityCondition(leftCol, rightCol *scopeColumn) {
// First, check if the comparison would even be valid.
if !leftCol.typ.Equivalent(rightCol.typ) {
if _, found := tree.FindEqualComparisonFunction(leftCol.typ, rightCol.typ); !found {
panic(pgerror.Newf(pgcode.DatatypeMismatch,
"JOIN/USING types %s for left and %s for right cannot be matched for column %q",
leftCol.typ, rightCol.typ, tree.ErrString(&leftCol.name)))
}
}
// Construct the predicate.
leftVar := jb.b.factory.ConstructVariable(leftCol.id)
rightVar := jb.b.factory.ConstructVariable(rightCol.id)
eq := jb.b.factory.ConstructEq(leftVar, rightVar)
jb.filters = append(jb.filters, jb.b.factory.ConstructFiltersItem(eq))
// Add the merged column to the scope, constructing a new column if needed.
if jb.joinType == descpb.InnerJoin || jb.joinType == descpb.LeftOuterJoin {
// The merged column is the same as the corresponding column from the
// left side.
jb.outScope.cols = append(jb.outScope.cols, *leftCol)
jb.showCols[leftCol] = struct{}{}
jb.hideCols[rightCol] = struct{}{}
} else if jb.joinType == descpb.RightOuterJoin &&
!colinfo.HasCompositeKeyEncoding(leftCol.typ) {
// The merged column is the same as the corresponding column from the
// right side.
jb.outScope.cols = append(jb.outScope.cols, *rightCol)
jb.showCols[rightCol] = struct{}{}
jb.hideCols[leftCol] = struct{}{}
} else {
// Construct a new merged column to represent IFNULL(left, right).
var typ *types.T
if leftCol.typ.Family() != types.UnknownFamily {
typ = leftCol.typ
} else {
typ = rightCol.typ
}
texpr := tree.NewTypedCoalesceExpr(tree.TypedExprs{leftCol, rightCol}, typ)
merged := jb.b.factory.ConstructCoalesce(memo.ScalarListExpr{leftVar, rightVar})
col := jb.b.synthesizeColumn(jb.outScope, string(leftCol.name), typ, texpr, merged)
jb.ifNullCols.Add(col.id)
jb.hideCols[leftCol] = struct{}{}
jb.hideCols[rightCol] = struct{}{}
}
}
func (jb *usingJoinBuilder) raiseDuplicateColError(name tree.Name, context string) {
panic(pgerror.Newf(pgcode.DuplicateColumn,
"common column name %q appears more than once in %s", tree.ErrString(&name), context))
}
func (jb *usingJoinBuilder) raiseUndefinedColError(name tree.Name, context string) {
panic(pgerror.Newf(pgcode.UndefinedColumn,
"column \"%s\" specified in USING clause does not exist in %s table", name, context))
}
|
package common
import (
"io/ioutil"
"log"
)
func closelog() {
log.SetFlags(0)
log.SetOutput(ioutil.Discard)
}
|
package roman_numerals
import (
"testing"
)
func verify(t *testing.T, in int, out string, solution string) {
if solution != out {
t.Error(
"For", in,
"expected", out,
"got", solution,
)
}
}
func TestConvertSingleDigitsToRoman(t *testing.T) {
tests := []struct{
in int
out string
}{
{in: 1, out: "I"},
{in: 2, out: "II"},
{in: 3, out: "III"},
{in: 4, out: "IV"},
{in: 5, out: "V"},
{in: 6, out: "VI"},
{in: 7, out: "VII"},
{in: 8, out: "VIII"},
{in: 9, out: "IX"},
}
for _, tt := range tests {
solution := Convert(tt.in)
verify(t, tt.in, tt.out, solution)
}
}
func TestConvertTwoDigitsToRoman(t *testing.T) {
tests := []struct{
in int
out string
}{
{in: 10, out: "X"},
{in: 11, out: "XI"},
{in: 12, out: "XII"},
{in: 13, out: "XIII"},
{in: 14, out: "XIV"},
{in: 15, out: "XV"},
{in: 16, out: "XVI"},
{in: 17, out: "XVII"},
{in: 18, out: "XVIII"},
{in: 19, out: "XIX"},
}
for _, tt := range tests {
solution := Convert(tt.in)
verify(t, tt.in, tt.out, solution)
}
}
func TestConvertSecondDigitToRoman(t *testing.T) {
tests := []struct{
in int
out string
}{
{in: 10, out: "X"},
{in: 20, out: "XX"},
{in: 30, out: "XXX"},
{in: 40, out: "XL"},
{in: 50, out: "L"},
{in: 60, out: "LX"},
{in: 70, out: "LXX"},
{in: 80, out: "LXXX"},
{in: 90, out: "XC"},
{in: 99, out: "XCIX"},
}
for _, tt := range tests {
solution := Convert(tt.in)
verify(t, tt.in, tt.out, solution)
}
}
|
package gorequest
import (
"math/rand"
"time"
)
// RandomUA will return a random user agent.
// 随机请求头
func RandomUA() string {
userAgent := [...]string{
"Mozilla/4.0 (compatible, MSIE 7.0, Windows NT 5.1, 360SE)",
"Mozilla/4.0 (compatible, MSIE 8.0, Windows NT 6.0, Trident/4.0)",
"Mozilla/5.0 (compatible, MSIE 9.0, Windows NT 6.1, Trident/5.0)",
"Opera/9.80 (Windows NT 6.1, U, en) Presto/2.8.131 Version/11.11",
"Mozilla/4.0 (compatible, MSIE 7.0, Windows NT 5.1, TencentTraveler 4.0)",
"Mozilla/5.0 (Windows, U, Windows NT 6.1, en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
"Mozilla/5.0 (Macintosh, Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
"Mozilla/5.0 (Macintosh, U, Intel Mac OS X 10_6_8, en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
"Mozilla/5.0 (Linux, U, Android 3.0, en-us, Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13",
"Mozilla/5.0 (iPad, U, CPU OS 4_3_3 like Mac OS X, en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
"Mozilla/4.0 (compatible, MSIE 7.0, Windows NT 5.1, Trident/4.0, SE 2.X MetaSr 1.0, SE 2.X MetaSr 1.0, .NET CLR 2.0.50727, SE 2.X MetaSr 1.0)",
"Mozilla/5.0 (iPhone, U, CPU iPhone OS 4_3_3 like Mac OS X, en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
"MQQBrowser/26 Mozilla/5.0 (Linux, U, Android 2.3.7, zh-cn, MB200 Build/GRJ22, CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.3 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:65.0) Gecko/20100101 Firefox/65.0",
"Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; rv:60.0) Gecko/20100101 Firefox/60.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.3 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64; rv:65.0) Gecko/20100101 Firefox/65.0",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36 OPR/58.0.3135.79",
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36 OPR/58.0.3135.107",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:65.0) Gecko/20100101 Firefox/65.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:66.0) Gecko/20100101 Firefox/66.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.2 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:65.0) Gecko/20100101 Firefox/65.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 YaBrowser/19.3.0.2485 Yowser/2.5 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.1.2 Safari/605.1.15",
"Mozilla/5.0 (iPad; CPU OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (X11; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0",
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/72.0.3626.121 Chrome/72.0.3626.121 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.3 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 YaBrowser/19.3.1.828 Yowser/2.5 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 YaBrowser/19.3.0.3022 Yowser/2.5 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:65.0) Gecko/20100101 Firefox/65.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/73.0.3683.75 Chrome/73.0.3683.75 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:65.0) Gecko/20100101 Firefox/65.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36 OPR/58.0.3135.118",
"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:65.0) Gecko/20100101 Firefox/65.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:66.0) Gecko/20100101 Firefox/66.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0",
"Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.1 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 YaBrowser/19.3.0.2485 Yowser/2.5 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0",
"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36 OPR/58.0.3135.127",
"Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0",
}
return userAgent[rand.New(rand.NewSource(time.Now().Unix())).Intn(len(userAgent))]
}
func UAHeader() (string, string) {
return "User-Agent", RandomUA()
}
|
package model
type UserDataRecord struct {
Label string
Value string
IsValid bool
IsOwner bool
}
|
package main
import (
"fmt"
"github.com/itang/gotang"
_ "github.com/lib/pq"
"github.com/lunny/xorm"
)
var (
driver = "postgres"
spec = "dbname=yunshangdb user=dbuser password=dbuser sslmode=disable"
)
func main() {
Engine, err := xorm.NewEngine(driver, spec)
gotang.AssertNoError(err, "")
defer Engine.Close()
dropTables(Engine)
}
// 删除应用创建所有的表
func dropTables(engine *xorm.Engine) {
tables := []string{
"t_migration",
"t_app_params",
"t_user_detail",
"t_user_level",
"t_user_work_kind",
"t_user_social",
"t_user",
"t_login_log",
"t_job_log",
"t_delivery_address",
"t_product",
"t_product_prices",
"t_product_category",
"t_product_params",
"t_product_stock_log",
"t_product_collect",
"t_provider",
"t_cart",
"t_payment",
"t_order",
"t_order_detail",
"t_shipping",
"t_order_log",
"t_invoice",
"t_comment",
"t_inquiry",
"t_inquiry_reply",
"t_news_category",
"t_news",
"t_news_param",
"t_app_config",
"t_bank",
"t_feedback",
}
for _, t := range tables {
sql := fmt.Sprintf("drop table IF EXISTS %s CASCADE", t)
_, err := engine.Exec(sql)
fmt.Printf("%s, err: %v\n", sql, err)
}
fmt.Println("")
}
|
package login
import (
"net/source/msg/msgproc"
)
type RepoMsg struct {
msgproc.BaseMsg
DevId int64
IsCharged byte
Name string
}
|
/*
Copyright: PeerFintech. All Rights Reserved.
*/
package gohfc
import (
"archive/tar"
"bytes"
"compress/gzip"
"io"
"os"
"path"
"path/filepath"
"strings"
"github.com/golang/protobuf/proto"
cb "github.com/hyperledger/fabric-protos-go/common"
pb "github.com/hyperledger/fabric-protos-go/peer"
lb "github.com/hyperledger/fabric-protos-go/peer/lifecycle"
"github.com/hyperledger/fabric/common/policydsl"
"github.com/hyperledger/fabric/protoutil"
"github.com/pkg/errors"
)
type ChainCodeType int32
const (
ChaincodeSpec_UNDEFINED ChainCodeType = 0
ChaincodeSpec_GOLANG ChainCodeType = 1
ChaincodeSpec_NODE ChainCodeType = 2
ChaincodeSpec_CAR ChainCodeType = 3
ChaincodeSpec_JAVA ChainCodeType = 4
lifecycleName = "_lifecycle"
approveFuncName = "ApproveChaincodeDefinitionForMyOrg"
commitFuncName = "CommitChaincodeDefinition"
checkCommitReadinessFuncName = "CheckCommitReadiness"
)
// ChainCode the fields necessary to execute operation over chaincode.
type ChainCode struct {
ChannelId string
Name string
Version string
Type ChainCodeType
Args []string
ArgBytes []byte
TransientMap map[string][]byte
rawArgs [][]byte
isInit bool
}
func (c *ChainCode) toChainCodeArgs() [][]byte {
if len(c.rawArgs) > 0 {
return c.rawArgs
}
args := make([][]byte, len(c.Args))
for i, arg := range c.Args {
args[i] = []byte(arg)
}
if len(c.ArgBytes) > 0 {
args = append(args, c.ArgBytes)
}
return args
}
// InstallRequest holds fields needed to install chaincode
type InstallRequest struct {
ChannelId string
ChainCodeName string
ChainCodeVersion string
ChainCodeType ChainCodeType
Namespace string
SrcPath string
Libraries []ChaincodeLibrary
}
type CollectionConfig struct {
Name string
RequiredPeersCount int32
MaximumPeersCount int32
Organizations []string
}
type ChaincodeLibrary struct {
Namespace string
SrcPath string
}
// ChainCodesResponse is the result of queering installed and instantiated chaincodes
type ChainCodesResponse struct {
PeerName string
Error error
ChainCodes []*pb.ChaincodeInfo
}
// createInstallProposal read chaincode from provided source and namespace, pack it and generate install proposal
// transaction. Transaction is not send from this func
func createInstallProposal(identity Identity, req *InstallRequest, crypto CryptoSuite) (*transactionProposal, error) {
var packageBytes []byte
var err error
switch req.ChainCodeType {
case ChaincodeSpec_GOLANG:
packageBytes, err = packGolangCC(req.Namespace, req.SrcPath, req.Libraries)
if err != nil {
return nil, err
}
default:
return nil, ErrUnsupportedChaincodeType
}
//now := time.Now()
return createInstallTransaction(identity, req, crypto, packageBytes)
}
func createInstallTransaction(identity Identity, req *InstallRequest, crypto CryptoSuite, packageBytes []byte) (*transactionProposal, error) {
depSpec, err := proto.Marshal(&pb.ChaincodeDeploymentSpec{
ChaincodeSpec: &pb.ChaincodeSpec{
ChaincodeId: &pb.ChaincodeID{Name: req.ChainCodeName, Path: req.Namespace, Version: req.ChainCodeVersion},
Type: pb.ChaincodeSpec_Type(req.ChainCodeType),
},
CodePackage: packageBytes,
//EffectiveDate: ×tamp.Timestamp{Seconds: int64(now.Second()), Nanos: int32(now.Nanosecond())},
})
if err != nil {
return nil, err
}
spec, err := chainCodeInvocationSpec(ChainCode{Type: req.ChainCodeType,
Name: LSCC,
Args: []string{"install"},
ArgBytes: depSpec,
})
creator, err := marshalProtoIdentity(identity)
if err != nil {
return nil, err
}
txId, err := newTransactionId(creator, crypto)
if err != nil {
return nil, err
}
ccHdrExt := &pb.ChaincodeHeaderExtension{ChaincodeId: &pb.ChaincodeID{Name: LSCC}}
channelHeaderBytes, err := channelHeader(cb.HeaderType_ENDORSER_TRANSACTION, txId, req.ChannelId, 0, ccHdrExt)
if err != nil {
return nil, err
}
ccPropPayloadBytes, err := proto.Marshal(&pb.ChaincodeProposalPayload{
Input: spec,
TransientMap: nil,
})
if err != nil {
return nil, err
}
sigHeader, err := signatureHeader(creator, txId)
if err != nil {
return nil, err
}
header := header(sigHeader, channelHeaderBytes)
hdrBytes, err := proto.Marshal(header)
if err != nil {
return nil, err
}
proposal, err := proposal(hdrBytes, ccPropPayloadBytes)
if err != nil {
return nil, err
}
return &transactionProposal{proposal: proposal, transactionId: txId.TransactionId}, nil
}
// createInstantiateProposal creates instantiate proposal transaction for already installed chaincode.
// transaction is not send from this func
func createInstantiateProposal(identity Identity, req *ChainCode, operation, policy string, collectionConfig []byte, crypto CryptoSuite) (*transactionProposal, error) {
if operation != deploy && operation != upgrade {
return nil, errors.New("instantiate operation accept only 'deploy' and 'upgrade' operations")
}
depSpec, err := proto.Marshal(&pb.ChaincodeDeploymentSpec{
ChaincodeSpec: &pb.ChaincodeSpec{
ChaincodeId: &pb.ChaincodeID{Name: req.Name, Version: req.Version},
Type: pb.ChaincodeSpec_Type(req.Type),
Input: &pb.ChaincodeInput{Args: req.toChainCodeArgs()},
},
})
if err != nil {
return nil, err
}
policyEnv := &cb.SignaturePolicyEnvelope{}
if policy == "" {
policyEnv = policydsl.SignedByMspMember(identity.MspId)
} else {
policyEnv, err = policydsl.FromString(policy)
if err != nil {
return nil, errors.WithMessage(err, "create signaturePolicyEnv failed")
}
}
marshPolicy, err := proto.Marshal(policyEnv)
if err != nil {
return nil, errors.WithMessage(err, "marshal signaturePolicyEnv failed")
}
args := [][]byte{
[]byte(operation),
[]byte(req.ChannelId),
depSpec,
marshPolicy,
[]byte("escc"),
[]byte("vscc"),
}
if len(collectionConfig) > 0 {
args = append(args, collectionConfig)
}
spec, err := chainCodeInvocationSpec(ChainCode{
Type: req.Type,
Name: LSCC,
rawArgs: args,
})
creator, err := marshalProtoIdentity(identity)
if err != nil {
return nil, err
}
txId, err := newTransactionId(creator, crypto)
if err != nil {
return nil, err
}
headerExtension := &pb.ChaincodeHeaderExtension{ChaincodeId: &pb.ChaincodeID{Name: LSCC}}
channelHeaderBytes, err := channelHeader(cb.HeaderType_ENDORSER_TRANSACTION, txId, req.ChannelId, 0, headerExtension)
if err != nil {
return nil, err
}
payloadBytes, err := proto.Marshal(&pb.ChaincodeProposalPayload{Input: spec, TransientMap: req.TransientMap})
if err != nil {
return nil, err
}
signatureHeader, err := signatureHeader(creator, txId)
if err != nil {
return nil, err
}
headerBytes, err := proto.Marshal(header(signatureHeader, channelHeaderBytes))
if err != nil {
return nil, err
}
proposal, err := proposal(headerBytes, payloadBytes)
if err != nil {
return nil, err
}
return &transactionProposal{proposal: proposal, transactionId: txId.TransactionId}, nil
}
// packGolangCC read provided src expecting Golang source code, repackage it in provided namespace, and compress it
func packGolangCC(namespace, source string, libs []ChaincodeLibrary) ([]byte, error) {
twBuf := new(bytes.Buffer)
tw := tar.NewWriter(twBuf)
var gzBuf bytes.Buffer
zw := gzip.NewWriter(&gzBuf)
concatLibs := append(libs, ChaincodeLibrary{SrcPath: source, Namespace: namespace})
for _, s := range concatLibs {
_, err := os.Stat(s.SrcPath)
if err != nil {
return nil, err
}
baseDir := path.Join("/src", s.Namespace)
err = filepath.Walk(s.SrcPath,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := tar.FileInfoHeader(info, "")
if err != nil {
return err
}
header.Mode = 0100000
if baseDir != "" {
header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, s.SrcPath))
}
if header.Name == baseDir {
return nil
}
if err := tw.WriteHeader(header); err != nil {
return err
}
if info.IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(tw, file)
return err
})
if err != nil {
tw.Close()
return nil, err
}
}
_, err := zw.Write(twBuf.Bytes())
if err != nil {
return nil, err
}
tw.Close()
zw.Close()
return gzBuf.Bytes(), nil
}
func createLifecycleInstallProposal(identity Identity, pkgBytes []byte) ([]byte, error) {
creatorBytes, err := marshalProtoIdentity(identity)
if err != nil {
return nil, err
}
installChaincodeArgs := &lb.InstallChaincodeArgs{
ChaincodeInstallPackage: pkgBytes,
}
installChaincodeArgsBytes, err := proto.Marshal(installChaincodeArgs)
if err != nil {
return nil, errors.Wrap(err, "failed to marshal InstallChaincodeArgs")
}
ccInput := &pb.ChaincodeInput{Args: [][]byte{[]byte("InstallChaincode"), installChaincodeArgsBytes}}
cis := &pb.ChaincodeInvocationSpec{
ChaincodeSpec: &pb.ChaincodeSpec{
ChaincodeId: &pb.ChaincodeID{Name: lifecycleName},
Input: ccInput,
},
}
proposal, _, err := protoutil.CreateProposalFromCIS(cb.HeaderType_ENDORSER_TRANSACTION, "", cis, creatorBytes)
if err != nil {
return nil, errors.WithMessage(err, "failed to create proposal for ChaincodeInvocationSpec")
}
if proposal == nil {
return nil, errors.New("proposal cannot be nil")
}
proposalBytes, err := proto.Marshal(proposal)
if err != nil {
return nil, errors.Wrap(err, "error marshaling proposal")
}
return proposalBytes, nil
}
func createApproveProposal(identity Identity, channelID, ccName, ccVersion, ccID, signaturePolicy string, sequence int64, initReqired bool) (proposalBytes []byte, txID string, err error) {
policyBytes, err := createPolicyBytes(signaturePolicy, "")
if err != nil {
return nil, "", errors.WithMessage(err, "create policy failed")
}
ccsrc := &lb.ChaincodeSource{
Type: &lb.ChaincodeSource_LocalPackage{
LocalPackage: &lb.ChaincodeSource_Local{
PackageId: ccID,
},
},
}
args := &lb.ApproveChaincodeDefinitionForMyOrgArgs{
Name: ccName,
Version: ccVersion,
Sequence: sequence,
ValidationParameter: policyBytes,
InitRequired: initReqired,
Source: ccsrc,
}
argsBytes, err := proto.Marshal(args)
if err != nil {
return nil, "", err
}
ccInput := &pb.ChaincodeInput{Args: [][]byte{[]byte(approveFuncName), argsBytes}}
cis := &pb.ChaincodeInvocationSpec{
ChaincodeSpec: &pb.ChaincodeSpec{
ChaincodeId: &pb.ChaincodeID{Name: lifecycleName},
Input: ccInput,
},
}
creatorBytes, err := marshalProtoIdentity(identity)
if err != nil {
return nil, "", err
}
proposal, txID, err := protoutil.CreateChaincodeProposal(cb.HeaderType_ENDORSER_TRANSACTION, channelID, cis, creatorBytes)
if err != nil {
return nil, "", errors.WithMessage(err, "failed to create ChaincodeInvocationSpec proposal")
}
proposalBytes, err = proto.Marshal(proposal)
if err != nil {
return nil, "", errors.Wrap(err, "error marshaling proposal")
}
return proposalBytes, txID, nil
}
func createCommitProposal(identity Identity, channelID, ccName, ccVersion, ccID, signaturePolicy string, sequence int64, initReqired bool) (proposalBytes []byte, txID string, err error) {
policyBytes, err := createPolicyBytes(signaturePolicy, "")
if err != nil {
return nil, "", errors.WithMessage(err, "create policy failed")
}
args := &lb.CommitChaincodeDefinitionArgs{
Name: ccName,
Version: ccVersion,
Sequence: sequence,
//EndorsementPlugin: c.Input.EndorsementPlugin,
//ValidationPlugin: c.Input.ValidationPlugin,
ValidationParameter: policyBytes,
InitRequired: initReqired,
//Collections: CollectionConfigPackage,
}
argsBytes, err := proto.Marshal(args)
if err != nil {
return nil, "", err
}
ccInput := &pb.ChaincodeInput{Args: [][]byte{[]byte(commitFuncName), argsBytes}}
cis := &pb.ChaincodeInvocationSpec{
ChaincodeSpec: &pb.ChaincodeSpec{
ChaincodeId: &pb.ChaincodeID{Name: lifecycleName},
Input: ccInput,
},
}
creatorBytes, err := marshalProtoIdentity(identity)
if err != nil {
return nil, "", errors.WithMessage(err, "failed to serialize identity")
}
proposal, txID, err := protoutil.CreateChaincodeProposalWithTxIDAndTransient(cb.HeaderType_ENDORSER_TRANSACTION, channelID, cis, creatorBytes, "", nil)
if err != nil {
return nil, "", errors.WithMessage(err, "failed to create ChaincodeInvocationSpec proposal")
}
proposalBytes, err = proto.Marshal(proposal)
if err != nil {
return nil, "", errors.Wrap(err, "error marshaling proposal")
}
return proposalBytes, txID, nil
}
func createInvokeQueryProposal(identity Identity, cc ChainCode) (proposalBytes []byte, txID string, err error) {
invocation := &pb.ChaincodeInvocationSpec{
ChaincodeSpec: &pb.ChaincodeSpec{
Type: pb.ChaincodeSpec_Type(cc.Type),
ChaincodeId: &pb.ChaincodeID{Name: cc.Name},
Input: &pb.ChaincodeInput{
Args: cc.toChainCodeArgs(),
IsInit: cc.isInit,
},
},
}
creator, err := marshalProtoIdentity(identity)
if err != nil {
return nil, "", errors.WithMessage(err, "error serializing identity")
}
prop, txID, err := protoutil.CreateChaincodeProposalWithTxIDAndTransient(cb.HeaderType_ENDORSER_TRANSACTION, cc.ChannelId, invocation, creator, txID, cc.TransientMap)
if err != nil {
return nil, "", errors.WithMessage(err, "error creating proposal")
}
proposalBytes, err = proto.Marshal(prop)
if err != nil {
return nil, "", errors.Wrap(err, "error marshaling proposal")
}
return proposalBytes, txID, nil
}
|
package smartling
import (
"fmt"
"net/url"
)
// ProjectsListRequest is a request used in GetProjectsList method.
type ProjectsListRequest struct {
// Cursor specifies limit/offset pagination pair.
Cursor LimitOffsetRequest
// ProjectNameFilter specifies filter for project name.
ProjectNameFilter string
// IncludeArchived specifies should archived items be included or not.
IncludeArchived bool
}
// GetQuery returns URL-encoded representation of current request.
func (request ProjectsListRequest) GetQuery() url.Values {
query := request.Cursor.GetQuery()
if len(request.ProjectNameFilter) > 0 {
query.Set("projectNameFilter", request.ProjectNameFilter)
}
query.Set("includeArchived", fmt.Sprint(request.IncludeArchived))
return query
}
|
package main
import (
"encoding/json"
"fmt"
"os"
)
func JsonMarshal() {
type ColorGroup struct {
ID int
Name string
Colors []string
}
group := ColorGroup{
ID: 1,
Name: "Reds",
Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
}
b, err := json.Marshal(group)
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
fmt.Println(b)
fmt.Printf("\ntype of b:%T \n", b)
cg := ColorGroup{}
err = json.Unmarshal(b, &cg)
fmt.Println(cg)
}
func JsonUnmarshal() {
buf := make([]byte, 1024)
var n int
if f, err := os.Open("./file.txt"); err == nil {
defer f.Close()
if n, err = f.Read(buf); err == nil {
fmt.Printf("n:%d \n", n)
fmt.Printf("file:\n%s \n", buf)
}
}
type Address struct {
Street string `json:street`
City string `json:city`
Country string `json:country`
}
type Link struct {
Name string `json:name`
Url string `json:url`
}
type WebSite struct {
Name string `json:name`
Url string `json:url`
Page int `json:page`
IsNonProfit bool `json:isNonProfit`
Address Address `json:adress`
Links []Link `json:links`
}
fmt.Println(buf[:n])
website := WebSite{}
fmt.Println("website: ", website)
err := json.Unmarshal(buf[:n], &website)
if err == nil {
fmt.Println(website)
} else {
fmt.Println(err)
}
}
func main() {
// JsonMarshal()
JsonUnmarshal()
}
|
// SPDX-License-Identifier: ISC
// Copyright (c) 2014-2020 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package difficulty_test
import (
"encoding/json"
"fmt"
"math"
"testing"
"github.com/stretchr/testify/assert"
"github.com/bitmark-inc/bitmarkd/difficulty"
)
// test difficulty initiialisation
func TestInitialBits(t *testing.T) {
expected := difficulty.OneUint64
actual := difficulty.Current.Bits()
if actual != expected {
t.Errorf("actual: %d expected: %d", actual, expected)
}
}
type testItem struct {
bits uint64
reciprocal float64
big string
bigf string
}
var tests = []testItem{
{
reciprocal: 1,
bits: 0x00ffffffffffffff,
big: "00ffffffffffffff800000000000000000000000000000000000000000000000",
bigf: "00ffffffffffffff800000000000000000000000000000000000000000000000",
},
{
reciprocal: 2,
bits: 0x01ffffffffffffff,
big: "007fffffffffffffc00000000000000000000000000000000000000000000000",
bigf: "007fffffffffffffc00000000000000000000000000000000000000000000000",
},
{
reciprocal: 2.2874055134732947,
bits: 0x01bfab3425899de4,
big: "006feacd09626779000000000000000000000000000000000000000000000000",
bigf: "006feacd0962677916d10918344a505d5a363a023349f9c39623104c540b1ae2",
},
{
reciprocal: 16,
bits: 0x04ffffffffffffff,
big: "000ffffffffffffff80000000000000000000000000000000000000000000000",
bigf: "000ffffffffffffff80000000000000000000000000000000000000000000000",
},
{
reciprocal: 64,
bits: 0x06ffffffffffffff,
big: "0003fffffffffffffe0000000000000000000000000000000000000000000000",
bigf: "0003fffffffffffffe0000000000000000000000000000000000000000000000",
},
{
reciprocal: 256,
bits: 0x08ffffffffffffff,
big: "0000ffffffffffffff8000000000000000000000000000000000000000000000",
bigf: "0000ffffffffffffff8000000000000000000000000000000000000000000000",
},
{
reciprocal: 511.99999999999997,
bits: 0x0800000000000007,
big: "0000800000000000038000000000000000000000000000000000000000000000",
bigf: "000080000000000003c000000000001e000000000000f0000000000007800000",
},
{
reciprocal: 1000,
bits: 0x090624dd2f1a9fbd,
big: "00004189374bc6a7ef4000000000000000000000000000000000000000000000",
bigf: "00004189374bc6a7ef7ced916872b020c49ba5e353f7ced916872b020c49ba5e",
},
{
reciprocal: 10000,
bits: 0x0da36e2eb1c432c9,
big: "0000068db8bac710cb2400000000000000000000000000000000000000000000",
bigf: "0000068db8bac710cb2617c1bda5119ce075f6fd21ff2e48e8a71de69ad42c3c",
},
{
reciprocal: 47643398017.803443,
bits: 0x23713f413f413f40,
big: "00000000001713f413f413f40000000000000000000000000000000000000000",
bigf: "00000000001713f413f413f40821936d0ab882041e769aaa6e7999e3a827ef1b",
},
{
reciprocal: 1e15,
bits: 0x31203af9ee756159,
big: "00000000000000480ebe7b9d5856400000000000000000000000000000000000",
bigf: "00000000000000480ebe7b9d585648806f5db1f9cfcec44485b1756799f713b1",
},
{
reciprocal: 9223372036854775808,
bits: 0x3fffffffffffffff,
big: "000000000000000001ffffffffffffff00000000000000000000000000000000",
bigf: "000000000000000001ffffffffffffff00000000000000000000000000000000",
},
{
reciprocal: 18446744073709551616,
bits: 0x40ffffffffffffff,
big: "000000000000000000ffffffffffffff80000000000000000000000000000000",
bigf: "000000000000000000ffffffffffffff80000000000000000000000000000000",
},
{
reciprocal: 36893488147419099136,
bits: 0x4000000000000007,
big: "0000000000000000008000000000000380000000000000000000000000000000",
bigf: "00000000000000000080000000000003c000000000001e000000000000f00000",
},
{
reciprocal: 3138550867693340381917894711603833208051177722232017256448,
bits: 0xbfffffffffffffff,
big: "00000000000000000000000000000000000000000000000001ffffffffffffff",
bigf: "00000000000000000000000000000000000000000000000001ffffffffffffff",
},
{ // the smallest value allowed (panics if smaller) = hash with 24 leading zero bytes!
reciprocal: 6277101735386680066937501969125693243111159424202737451008,
bits: 0xbf00000000000007,
big: "0000000000000000000000000000000000000000000000000100000000000007",
bigf: "0000000000000000000000000000000000000000000000000100000000000007",
},
// { // 13 - the theoretical smallest possible non-zero value - not useful
// reciprocal: ?,
// bits: 0xf7ffffffffffffff,
// big: "0000000000000000000000000000000000000000000000000000000000000001",
// bigf: "0000000000000000000000000000000000000000000000000000000000000001",
// },
}
// test 64 bit word
func TestUint64(t *testing.T) {
d := difficulty.New()
for i, item := range tests {
d.SetBits(item.bits)
actual := d.Value()
if actual != item.reciprocal {
t.Errorf("%d: actual: %20.10f reciprocal: %20.10f diff: %g", i, actual, item.reciprocal, actual-item.reciprocal)
}
hexActual := d.String()
hexExpected := fmt.Sprintf("%016x", item.bits)
if hexActual != hexExpected {
t.Errorf("%d: hex: actual: %q expected: %q", i, hexActual, hexExpected)
}
bigActual := fmt.Sprintf("%064x", d.BigInt())
if bigActual != item.big {
t.Errorf("%d: big: actual: %q expected: %q", i, bigActual, item.big)
}
}
}
// test bytes
func TestBytes(t *testing.T) {
d := difficulty.New()
// 0x0da36e2eb1c432c9
bits := []byte{0xc9, 0x32, 0xc4, 0xb1, 0x2e, 0x6e, 0xa3, 0x0d} // little endian bytes
d.SetBytes(bits)
expected := float64(10000)
actual := d.Value()
bits2 := d.Bits()
if math.Abs(actual-expected) > 0.000001 {
t.Errorf("0x%016x: actual: %f expected: %f diff: %g", bits2, actual, expected, actual-expected)
}
}
// test JSON
func TestJSON(t *testing.T) {
d := difficulty.New()
for i, item := range tests {
d.SetBits(item.bits)
buffer, err := json.Marshal(d)
if nil != err {
t.Fatalf("%d: JSON encode error: %s", i, err)
}
dNew := difficulty.New()
err = json.Unmarshal(buffer, dNew)
if nil != err {
t.Fatalf("%d: JSON decode error: %s", i, err)
}
actual := dNew.Bits()
expected := item.bits
if actual != expected {
t.Errorf("%d: JSON actual: %016x expected: %016x", i, actual, expected)
}
}
}
// test floating point (reciprocal)
func TestReciprocal(t *testing.T) {
d := difficulty.New()
for i, item := range tests {
d.Set(item.reciprocal)
actual := d.Bits()
if actual != item.bits {
t.Errorf("%d: actual: 0x%016x bits: 0x%016x", i, actual, item.bits)
}
hexActual := d.String()
hexExpected := fmt.Sprintf("%016x", item.bits)
if hexActual != hexExpected {
t.Errorf("%d: hex: actual: %q expected: %q", i, hexActual, hexExpected)
}
bigActual := fmt.Sprintf("%064x", d.BigInt())
if bigActual != item.bigf {
t.Errorf("%d: big: actual: %q expected: %q", i, bigActual, item.bigf)
}
bitsString := fmt.Sprintf("%v", d)
if bitsString != hexExpected {
t.Errorf("%d: String(): actual: %q expected: %q", i, bitsString, hexExpected)
}
bigString := fmt.Sprintf("%#v", d)
if bigString != item.bigf {
t.Errorf("%d: GoString(): actual: %v expected: %q", i, bigString, item.bigf)
}
}
}
func TestPrevTimespanBlockBeginAndEndWhenAtMiddle(t *testing.T) {
height := uint64(difficulty.AdjustTimespanInBlocks*3 + 10)
begin, end := difficulty.PrevTimespanBlockBeginAndEnd(height)
assert.Equal(t, uint64(difficulty.AdjustTimespanInBlocks*3-1-difficulty.AdjustTimespanInBlocks), begin, "fail to get begin block")
assert.Equal(t, uint64(difficulty.AdjustTimespanInBlocks*3-1), end, "get end block at middle")
}
func TestPrevTimespanBlockBeginAndEndWhenAtStart(t *testing.T) {
height := uint64(difficulty.AdjustTimespanInBlocks * 3)
begin, end := difficulty.PrevTimespanBlockBeginAndEnd(height)
assert.Equal(t, uint64(difficulty.AdjustTimespanInBlocks*3-1-difficulty.AdjustTimespanInBlocks), begin, "fail to get begin block")
assert.Equal(t, uint64(difficulty.AdjustTimespanInBlocks*3-1), end, "get end block at start")
}
func TestPrevTimespanBlockBeginAndEndWhenInFirstTimespan(t *testing.T) {
height := uint64(difficulty.AdjustTimespanInBlocks + 10)
begin, end := difficulty.PrevTimespanBlockBeginAndEnd(height)
assert.Equal(t, uint64(2), begin, "fail to get begin block")
assert.Equal(t, uint64(difficulty.AdjustTimespanInBlocks-1), end, "get end block in first timespan")
}
func TestHashrate(t *testing.T) {
difficulty.Current.Set(4.8)
hashrate := difficulty.Hashrate()
// difficulty 4.8, log2(4.8) = 2.263034405833794
// total bits of empty zero will 8+2.263034405833794 = 10.263034405833794 bits
// possible hashes for a correct one is pow(2, 10.263034405833794) = 1228.8000000000004 hashes
// expected time for a block is 120 seconds
// hash rate = hashes / time = 1228.8000000000004 / 120
expected := math.Floor(float64(1228.8000000000004)/120*1000) / 1000
assert.Equal(t, expected, hashrate, "network hashrate")
}
func TestNextDifficultyByPreviousTimespanWhenTooLong(t *testing.T) {
diff := float64(8)
targetTimespan := 2 * 60 * 200
testTime := targetTimespan * 8
actual := difficulty.NextDifficultyByPreviousTimespan(uint64(testTime), diff)
assert.Equal(t, diff/4, actual, "wrong difficulty adjust")
}
func TestNextDifficultyByPreviousTimespanWhenTooShort(t *testing.T) {
diff := float64(8)
targetTimespan := 2 * 60 * 200
testTime := targetTimespan / 8
actual := difficulty.NextDifficultyByPreviousTimespan(uint64(testTime), diff)
assert.Equal(t, diff*4, actual, "wrong difficulty adjust")
}
func TestNextDifficultyByPreviousTimespanWhenLarger(t *testing.T) {
diff := float64(8)
targetTimespan := 2 * 60 * 200
testTime := targetTimespan * 3
actual := difficulty.NextDifficultyByPreviousTimespan(uint64(testTime), diff)
assert.Equal(t, diff/3, actual, "wrong difficulty adjust")
}
func TestNextDifficultyByPreviousTimespanWhenSmaller(t *testing.T) {
diff := float64(8)
targetTimespan := 2 * 60 * 200
testTime := targetTimespan / 3
actual := difficulty.NextDifficultyByPreviousTimespan(uint64(testTime), diff)
assert.Equal(t, diff*3, actual, "wrong difficulty adjust")
}
|
package test
import (
api_v1 "k8s.io/api/core/v1"
extensions "k8s.io/api/extensions/v1beta1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/kubernetes/scheme"
backendconfig "k8s.io/ingress-gce/pkg/apis/backendconfig/v1beta1"
)
// NewIngress returns an Ingress with the given spec.
func NewIngress(name types.NamespacedName, spec extensions.IngressSpec) *extensions.Ingress {
return &extensions.Ingress{
TypeMeta: meta_v1.TypeMeta{
Kind: "Ingress",
APIVersion: "extensions/v1beta1",
},
ObjectMeta: meta_v1.ObjectMeta{
Name: name.Name,
Namespace: name.Namespace,
},
Spec: spec,
}
}
// NewService returns a Service with the given spec.
func NewService(name types.NamespacedName, spec api_v1.ServiceSpec) *api_v1.Service {
return &api_v1.Service{
TypeMeta: meta_v1.TypeMeta{
Kind: "Service",
APIVersion: "v1",
},
ObjectMeta: meta_v1.ObjectMeta{
Name: name.Name,
Namespace: name.Namespace,
},
Spec: spec,
}
}
// NewBackendConfig returns a BackendConfig with the given spec.
func NewBackendConfig(name types.NamespacedName, spec backendconfig.BackendConfigSpec) *backendconfig.BackendConfig {
return &backendconfig.BackendConfig{
ObjectMeta: meta_v1.ObjectMeta{
Name: name.Name,
Namespace: name.Namespace,
},
Spec: spec,
}
}
// Backend returns an IngressBackend with the given service name/port.
func Backend(name string, port intstr.IntOrString) *extensions.IngressBackend {
return &extensions.IngressBackend{
ServiceName: name,
ServicePort: port,
}
}
// DecodeIngress deserializes an Ingress object.
func DecodeIngress(data []byte) (*extensions.Ingress, error) {
decode := scheme.Codecs.UniversalDeserializer().Decode
obj, _, err := decode(data, nil, nil)
if err != nil {
return nil, err
}
return obj.(*extensions.Ingress), nil
}
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
package aws
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/ec2"
ec2Types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
"github.com/aws/aws-sdk-go-v2/service/rds"
rdsTypes "github.com/aws/aws-sdk-go-v2/service/rds/types"
gt "github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi"
gtTypes "github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi/types"
"github.com/aws/aws-sdk-go-v2/service/secretsmanager"
"github.com/golang/mock/gomock"
"github.com/mattermost/mattermost-cloud/internal/testlib"
"github.com/mattermost/mattermost-cloud/model"
log "github.com/sirupsen/logrus"
)
// Tests provisioning a multitenante database. Use this test for deriving other tests.
// If tests are broken, this should be the first test to get fixed. This test assumes
// data provisioner is running in multitenant database for the first time, so pretty much
// the entire code will run here.
func (a *AWSTestSuite) TestProvisioningMultitenantDatabase() {
database := NewRDSMultitenantDatabase(
model.DatabaseEngineTypeMySQL,
a.InstanceID,
a.InstallationA.ID,
a.Mocks.AWS,
0,
false,
)
databaseType := database.DatabaseEngineTypeTagValue()
var databaseID string
gomock.InOrder(
a.Mocks.Log.Logger.EXPECT().
WithFields(log.Fields{
"multitenant-rds-database": MattermostRDSDatabaseName(a.InstallationA.ID),
"database-type": database.databaseType,
}).
Return(testlib.NewLoggerEntry()).
Times(1),
// Get cluster installations from data store.
a.Mocks.Model.DatabaseInstallationStore.EXPECT().
GetClusterInstallations(gomock.Any()).
Do(func(input *model.ClusterInstallationFilter) {
a.Assert().Equal(input.InstallationID, a.InstallationA.ID)
}).
Return([]*model.ClusterInstallation{{ID: a.ClusterA.ID}}, nil).
Times(1),
// Find the VPC which the installation belongs to.
a.Mocks.API.EC2.EXPECT().DescribeVpcs(context.TODO(), gomock.Any()).
Return(&ec2.DescribeVpcsOutput{Vpcs: []ec2Types.Vpc{{VpcId: &a.VPCa}}}, nil).
Times(1),
// Get multitenant databases from the datastore to check if any belongs to the installation ID.
a.Mocks.Model.DatabaseInstallationStore.EXPECT().
GetMultitenantDatabases(gomock.Any()).
Do(func(input *model.MultitenantDatabaseFilter) {
a.Assert().Equal(input.InstallationID, a.InstallationA.ID)
a.Assert().Equal(model.NoInstallationsLimit, input.MaxInstallationsLimit)
a.Assert().Equal(input.PerPage, model.AllPerPage)
}).
Return(make([]*model.MultitenantDatabase, 0), nil),
// Get multitenant databases from the datastore to check if any belongs to the installation ID.
a.Mocks.Model.DatabaseInstallationStore.EXPECT().
GetMultitenantDatabases(gomock.Any()).
Do(func(input *model.MultitenantDatabaseFilter) {
a.Assert().Equal(DefaultRDSMultitenantDatabaseMySQLCountLimit, input.MaxInstallationsLimit)
a.Assert().Equal(input.PerPage, model.AllPerPage)
}).
Return(make([]*model.MultitenantDatabase, 0), nil),
// Get resources from AWS and try to find a RDS cluster that the database can be created.
a.Mocks.API.ResourceGroupsTagging.EXPECT().
GetResources(gomock.Any(), gomock.Any()).
Do(func(ctx context.Context, input *gt.GetResourcesInput, optFns ...func(*gt.Options)) {
a.Assert().Equal(input.ResourceTypeFilters, []string{DefaultResourceTypeClusterRDS})
tagFilter := []gtTypes.TagFilter{
{
Key: aws.String("DatabaseType"),
Values: []string{"multitenant-rds"},
},
{
Key: aws.String(trimTagPrefix(CloudInstallationDatabaseTagKey)),
Values: []string{databaseType},
},
{
Key: aws.String("VpcID"),
Values: []string{a.VPCa},
},
{
Key: aws.String("Purpose"),
Values: []string{"provisioning"},
},
{
Key: aws.String("Owner"),
Values: []string{"cloud-team"},
},
{
Key: aws.String("Terraform"),
Values: []string{"true"},
},
{
Key: aws.String("Counter"),
},
{
Key: aws.String("MultitenantDatabaseID"),
},
}
a.Assert().Equal(input.TagFilters, tagFilter)
}).
Return(>.GetResourcesOutput{
ResourceTagMappingList: []gtTypes.ResourceTagMapping{
{
ResourceARN: aws.String(a.RDSResourceARN),
// WARNING: If you ever find the need to change some of the hardcoded values such as
// Owner, Terraform or any of the keys here, make sure that an E2e system's test still
// passes.
Tags: []gtTypes.Tag{
{
Key: aws.String("Purpose"),
Value: aws.String("provisioning"),
},
{
Key: aws.String("Owner"),
Value: aws.String("cloud-team"),
},
{
Key: aws.String("Terraform"),
Value: aws.String("true"),
},
{
Key: aws.String("DatabaseType"),
Value: aws.String("multitenant-rds"),
},
{
Key: aws.String("VpcID"),
Value: aws.String(a.VPCa),
},
{
Key: aws.String("Counter"),
Value: aws.String("0"),
},
{
Key: aws.String("MultitenantDatabaseID"),
Value: aws.String(a.RDSClusterID),
},
},
},
},
}, nil),
a.Mocks.API.RDS.EXPECT().
DescribeDBClusterEndpoints(gomock.Any(), gomock.Any()).
Return(&rds.DescribeDBClusterEndpointsOutput{
DBClusterEndpoints: []rdsTypes.DBClusterEndpoint{
{
Status: aws.String("available"),
},
},
}, nil).
Times(1),
a.Mocks.API.RDS.EXPECT().
DescribeDBClusters(gomock.Any(), gomock.Any()).
Do(func(ctx context.Context, input *rds.DescribeDBClustersInput, optFns ...func(*rds.Options)) {
a.Assert().Equal(input.Filters, []rdsTypes.Filter{
{
Name: aws.String("db-cluster-id"),
Values: []string{a.RDSClusterID},
},
})
}).
Return(&rds.DescribeDBClustersOutput{
DBClusters: []rdsTypes.DBCluster{
{
DBClusterIdentifier: &a.RDSClusterID,
Endpoint: aws.String("writer.rds.aws.com"),
ReaderEndpoint: aws.String("reader.rds.aws.com"),
Status: aws.String("available"),
},
},
}, nil).
Times(1),
// Create the multitenant database.
a.Mocks.Model.DatabaseInstallationStore.EXPECT().
CreateMultitenantDatabase(gomock.Any()).
Do(func(input *model.MultitenantDatabase) {
a.Assert().Equal(input.RdsClusterID, a.RDSClusterID)
databaseID = model.NewID()
}).
Return(nil).
Times(1),
a.Mocks.Model.DatabaseInstallationStore.EXPECT().
LockMultitenantDatabase(databaseID, a.InstanceID).
Return(true, nil).
Times(1),
a.Mocks.Model.DatabaseInstallationStore.EXPECT().
GetMultitenantDatabase(databaseID).
Return(&model.MultitenantDatabase{
ID: databaseID,
RdsClusterID: a.RDSClusterID,
}, nil).
Times(1),
a.Mocks.Model.DatabaseInstallationStore.EXPECT().
UpdateMultitenantDatabase(&model.MultitenantDatabase{
ID: databaseID,
RdsClusterID: a.RDSClusterID,
Installations: model.MultitenantDatabaseInstallations{
database.installationID,
}}).
Times(1),
a.Mocks.API.RDS.EXPECT().
DescribeDBClusters(gomock.Any(), gomock.Any()).
Do(func(ctx context.Context, input *rds.DescribeDBClustersInput, optFns ...func(*rds.Options)) {
a.Assert().Equal(input.Filters, []rdsTypes.Filter{
{
Name: aws.String("db-cluster-id"),
Values: []string{a.RDSClusterID},
},
})
}).
Return(&rds.DescribeDBClustersOutput{
DBClusters: []rdsTypes.DBCluster{
{
DBClusterIdentifier: &a.RDSClusterID,
Status: aws.String("available"),
Endpoint: aws.String("aws.rds.com/mattermost"),
},
},
}, nil).
Times(1),
a.Mocks.API.SecretsManager.EXPECT().
GetSecretValue(gomock.Any(), gomock.Any()).
Do(func(ctx context.Context, input *secretsmanager.GetSecretValueInput, opts ...func(*secretsmanager.Options)) {
}).
Return(&secretsmanager.GetSecretValueOutput{
SecretString: aws.String("VR1pJl2KdNyQy0sxvJYdWbDeTQH1Pk71sXLbS4sw"),
}, nil).
Times(1),
a.Mocks.Model.DatabaseInstallationStore.EXPECT().
UnlockMultitenantDatabase(databaseID, a.InstanceID, true).
Return(true, nil).
Times(1),
)
err := database.Provision(a.Mocks.Model.DatabaseInstallationStore, a.Mocks.Log.Logger)
a.Assert().Error(err)
a.Assert().Equal("failed to run provisioning sql commands: failed to create schema in multitenant RDS cluster "+
"rds-cluster-multitenant-09d44077df9934f96-97670d43: failed to run create database SQL command: dial tcp: "+
"lookup aws.rds.com/mattermost: no such host", err.Error())
}
|
package tyTls
import (
"bytes"
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"strings"
)
func DecodePemContentCallback(content []byte, cb func(obj interface{})) (errMsg string) {
bw := bytes.Buffer{}
for _, line := range strings.Split(string(content), "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
bw.WriteString(line)
bw.WriteByte('\n')
}
content = bw.Bytes()
var p *pem.Block
for {
p, content = pem.Decode(content)
if p == nil {
break
}
key, errMsg := DecodeObjFromPemBlock(p)
if errMsg != "" {
return errMsg
}
cb(key)
}
return ""
}
func DecodeOneObjFromPemContent(content []byte) (obj interface{}, errMsg string) {
errMsg = ""
DecodePemContentCallback(content, func(thisObj interface{}) {
if obj != nil {
errMsg = "c7tngmegbm"
return
}
obj = thisObj
})
if obj == nil {
return nil, "v7t9tymwb6"
}
return obj, errMsg
}
func DecodeOneCertFromPemContent(content []byte) (cert *x509.Certificate, errMsg string) {
obj1, errMsg := DecodeOneObjFromPemContent(content)
if errMsg != "" {
return nil, errMsg
}
cert, ok := obj1.(*x509.Certificate)
if !ok {
return nil, "3cb7nnjbth " + fmt.Sprintf("%T", obj1)
}
return cert, ""
}
/*
possible return type:
*rsa.PrivateKey
*ecdsa.PrivateKey
*x509.Certificate
*x509.CertificateRequest
*/
func DecodeObjFromPemBlock(p *pem.Block) (obj interface{}, errMsg string) {
switch p.Type {
case "RSA PRIVATE KEY":
key, err := x509.ParsePKCS1PrivateKey(p.Bytes)
if err != nil {
return nil, err.Error()
}
return key, ""
case "EC PRIVATE KEY":
key, err := x509.ParseECPrivateKey(p.Bytes)
if err != nil {
return nil, err.Error()
}
return key, ""
case "PRIVATE KEY":
// copy from /usr/local/go/src/crypto/tls/tls.go:279 tls.parsePrivateKey
key1, err1 := x509.ParsePKCS1PrivateKey(p.Bytes)
if err1 == nil {
return key1, ""
}
key2, err2 := x509.ParseECPrivateKey(p.Bytes)
if err2 == nil {
return key2, ""
}
key3, err3 := x509.ParsePKCS8PrivateKey(p.Bytes)
if err3 == nil {
switch key3.(type) {
case *rsa.PrivateKey, *ecdsa.PrivateKey:
return key3, ""
default:
return key3, "f8vahfhkgp tls: found unknown private key type in PKCS#8 wrapping"
}
}
return nil, "yrng5ge2bj rsa:" + err1.Error() + "\n ec:" + err2.Error()
case "CERTIFICATE":
cert, err := x509.ParseCertificate(p.Bytes)
if err != nil {
return nil, err.Error()
}
return cert, ""
case "NEW CERTIFICATE REQUEST":
csr, err := x509.ParseCertificateRequest(p.Bytes)
if err != nil {
return nil, err.Error()
}
return csr, ""
default:
return nil, "not expect pem type [" + p.Type + "]"
}
}
|
package test_select
import (
"context"
"github.com/jackc/pgx/v4/pgxpool"
"log"
"os"
"testing"
)
//go:generate true
var pool *pgxpool.Pool
func TestMain(m *testing.M) {
var err error
databaseUrl, ok := os.LookupEnv("DATABASE_URL")
if !ok {
log.Fatal("Environment variable DATABASE_URL is required to connect to Postgres. " +
"Example: DATABASE_URL='postgres://postgres:@localhost:5432/postgres?sslmode=disable&pool_max_conns=8';")
}
pool, err = pgxpool.Connect(context.Background(), databaseUrl)
if err != nil {
log.Fatal( "Unable to connect to database:", err)
}
os.Exit(m.Run())
}
func TestNewGoDao(t *testing.T) {
goDao := NewGoDao(pool, context.Background())
type args struct {
a int64
b int64
}
tests := []struct {
name string
args args
want int64
}{{
name: "2+3=5",
args: args{2, 3},
want: 5,
}, {
name: "-3+2=-1",
args: args{-3, 2},
want: -1,
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sum, err := goDao.Add(tt.args.a, tt.args.b)
if err != nil {
t.Error(err)
}
if sum != tt.want {
t.Fatal("expected ", tt.want, " got ", sum)
}
})
}
}
|
// This file is part of CycloneDX GoMod
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) OWASP Foundation. All Rights Reserved.
package e2e
import (
"fmt"
"os"
"os/exec"
"strings"
"testing"
"github.com/CycloneDX/cyclonedx-gomod/internal/cli/options"
"github.com/CycloneDX/cyclonedx-gomod/internal/version"
"github.com/bradleyjkemp/cupaloy/v2"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var (
snapshotter = cupaloy.NewDefaultConfig().
WithOptions(cupaloy.SnapshotSubdirectory("./testdata/snapshots"))
// Prefix for temporary files and directories created during ITs
tmpPrefix = version.Name + "_"
// Serial number to use in order to keep generated SBOMs reproducible
zeroUUID = uuid.MustParse("00000000-0000-0000-0000-000000000000")
)
func runSnapshotIT(t *testing.T, outputOptions *options.OutputOptions, execFunc func() error) {
skipIfShort(t)
bomFileExtension := ".xml"
if outputOptions.UseJSON {
bomFileExtension = ".json"
}
// Create a temporary file to write the SBOM to
bomFile, err := os.CreateTemp("", tmpPrefix+t.Name()+"_*.bom"+bomFileExtension)
require.NoError(t, err)
defer os.Remove(bomFile.Name())
require.NoError(t, bomFile.Close())
// Generate the SBOM
outputOptions.OutputFilePath = bomFile.Name()
err = execFunc()
require.NoError(t, err)
// Sanity check: Make sure the SBOM is valid
assertValidSBOM(t, bomFile.Name())
// Read SBOM and compare with snapshot
bomFileContent, err := os.ReadFile(bomFile.Name())
require.NoError(t, err)
snapshotter.SnapshotT(t, string(bomFileContent))
}
func skipIfShort(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
}
func assertValidSBOM(t *testing.T, bomFilePath string) {
inputFormat := "xml_v1_3"
if strings.HasSuffix(bomFilePath, ".json") {
inputFormat = "json_v1_3"
}
valCmd := exec.Command("cyclonedx", "validate", "--input-file", bomFilePath, "--input-format", inputFormat, "--fail-on-errors")
valOut, err := valCmd.CombinedOutput()
if !assert.NoError(t, err) {
// Provide some context when test is failing
fmt.Printf("validation error: %s\n", string(valOut))
}
}
func extractFixture(t *testing.T, archivePath string) string {
tmpDir := t.TempDir()
cmd := exec.Command("tar", "xzf", archivePath, "-C", tmpDir)
out, err := cmd.CombinedOutput()
if !assert.NoError(t, err) {
// Provide some context when test is failing
fmt.Printf("validation error: %s\n", string(out))
}
return tmpDir
}
|
package final_prices_with_a_special_discount_in_a_shop
type Stack struct {
items []interface{}
}
func (s *Stack) Push(item interface{}) {
s.items = append(s.items, item)
}
func (s *Stack) Pop() interface{} {
n := s.Len()
last := s.items[n-1]
s.items = s.items[:n-1]
return last
}
func (s Stack) Len() int {
return len(s.items)
}
func (s Stack) Top() interface{} {
return s.items[s.Len()-1]
}
func finalPrices(prices []int) []int {
discounts := make([]int, len(prices)) // O(n)
var st Stack // O(n)
for i := len(prices) - 1; i >= 0; i-- { // O(n)
for st.Len() > 0 && st.Top().(int) > prices[i] {
st.Pop()
}
if st.Len() == 0 {
discounts[i] = -1
} else {
discounts[i] = st.Top().(int)
}
st.Push(prices[i])
}
// x [-> nil]
// -1, [-> 3]
// -1, [-> 2]
// 2, [-> 6 -> 2]
// 2, [-> 4 -> 2]
// 4, [-> 2]
results := make([]int, len(discounts)) // O(n)
for i, price := range prices { // O(n)
if discounts[i] == -1 {
results[i] = price
} else {
results[i] = price - discounts[i]
}
}
return results
}
|
package numrecipes
import "testing"
func TestQPow(t *testing.T) {
t.Log(QPow(300, 300))
}
func BenchmarkQPow(b *testing.B) {
for i := 0; i < b.N; i++ {
QPow(300, i)
}
}
|
package main
import (
"context"
"fmt"
"os"
"os/exec"
"github.com/spf13/pflag"
)
// Version identifies the version of rope. This can be modified by CI during
// the release process.
var Version = "dev"
const defaultHelp = `Rope is a tool for managing Python dependencies 🧩
Usage:
rope <command> [options]
The commands are:
run run command with PYTHONPATH configured
init initializes a new rope project
add installs and adds one or more dependencies
remove removes one or more dependencies
show inspect the current dependencies
export export dependency specification
cache inspecting and clearing the cache
pythonpath prints the configured PYTHONPATH
version show rope version
`
// TODO: Figure out how to better interact with this.
// Abstract methods that needs this type of interaction into its own type.
var cache *Cache
var env *Environment
// Should move the main package into a cli folder and let the top-level package be 'rope'
// Which can be directly used in the test harness.
func run(args []string) (int, error) {
arg := ""
if len(args) > 1 {
arg = args[1]
}
cache = &Cache{}
defer cache.Close()
// Lazy-loaded environment
env = &Environment{}
switch arg {
case "", "help", "--help", "-h":
fmt.Printf(defaultHelp)
return 2, nil
case "version", "--version":
fmt.Printf("rope version: %s\n", Version)
return 0, nil
case "init":
if path, err := FindRopefile(); err == ErrRopefileNotFound {
// continue
} else if err != nil {
return 1, err
} else {
return 1, fmt.Errorf("rope.json already found at: %s", path)
}
if err := WriteRopefile(&Project{Dependencies: []Dependency{}}, "rope.json"); err != nil {
return 1, err
}
return 0, nil
case "install":
fmt.Println("did you mean: 'rope add'?")
return 2, nil
case "add":
flagSet := pflag.NewFlagSet("install", pflag.ContinueOnError)
timeout := flagSet.Duration("timeout", 0, "Command timeout")
if err := flagSet.Parse(args[1:]); err == pflag.ErrHelp {
return 0, nil
} else if err != nil {
return 2, err
}
if len(flagSet.Args()) < 2 {
fmt.Println("rope add: package not provided")
return 2, nil
}
packages := flagSet.Args()[1:]
if err := add(*timeout, packages); err != nil {
return 1, err
}
return 0, nil
case "remove":
// TODO: Implement command to remove dependency(error if transitive)
return 1, fmt.Errorf("not implemented")
case "export":
if err := ExportRequirements(context.Background(), os.Stdout); err != nil {
return 1, err
}
return 0, nil
case "show":
// TODO: Implement command to show all dependenies along with a tree view
return 1, fmt.Errorf("not implemented")
case "cache":
// TODO: Implement operations for show information/clearing the cache
return 1, fmt.Errorf("not implemented")
case "pythonpath":
pythonPath, err := buildPythonPath(context.Background())
if err != nil {
return 1, err
}
fmt.Printf(pythonPath)
return 0, nil
case "run":
pythonPath, err := buildPythonPath(context.Background())
if err != nil {
return 1, err
}
cmd := exec.Command(args[2], args[3:]...)
// TODO: Merge any provided PYTHONPATH with the new one?
cmd.Env = append(os.Environ(), fmt.Sprintf("PYTHONPATH=%s", pythonPath))
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return 1, err
}
if err := cmd.Wait(); err != nil {
return cmd.ProcessState.ExitCode(), nil
}
return 0, nil
default:
// TODO: "did you mean X"
// http://norvig.com/spell-correct.html
fmt.Printf("rope %s: unknown command\n", arg)
return 2, nil
}
}
func main() {
exitCode, err := run(os.Args)
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
}
os.Exit(exitCode)
}
|
package x86_64
import (
"github.com/lunixbochs/ghostrace/ghost/sys/num"
uc "github.com/unicorn-engine/unicorn/bindings/go/unicorn"
"../../models"
"../../syscalls"
)
var StaticUname = models.Uname{"Linux", "usercorn", "3.13.0-24-generic", "normal copy of Linux minding my business", "x86_64"}
func LinuxInit(u models.Usercorn, args, env []string) error {
auxv, err := models.SetupElfAuxv(u)
if err != nil {
return err
}
if _, err := u.PushBytes(auxv); err != nil {
return err
}
return AbiInit(u, args, env, auxv, LinuxSyscall)
}
func LinuxSyscall(u models.Usercorn) {
rax, _ := u.RegRead(uc.X86_REG_RAX)
name, _ := num.Linux_x86_64[int(rax)]
var ret uint64
switch name {
case "uname":
addr, _ := u.RegRead(AbiRegs[0])
StaticUname.Pad(64)
syscalls.Uname(u, addr, &StaticUname)
case "arch_prctl":
case "set_tid_address":
default:
ret, _ = u.Syscall(int(rax), name, syscalls.RegArgs(u, AbiRegs))
}
u.RegWrite(uc.X86_REG_RAX, ret)
}
func LinuxInterrupt(u models.Usercorn, intno uint32) {
if intno == 0x80 {
LinuxSyscall(u)
}
}
func init() {
Arch.RegisterOS(&models.OS{Name: "linux", Init: LinuxInit, Interrupt: LinuxInterrupt})
}
|
package main
import (
"fmt"
"strconv"
"./romannumerals"
)
var appName = "The Romain Numerals Converter"
func main() {
var inputValue string
var inputValueAsInt int
fmt.Printf("Welcome to %v\n", appName)
fmt.Printf("Enter a numeric value: ")
fmt.Scanln(&inputValue)
inputValueAsInt, _ = strconv.Atoi(inputValue)
fmt.Printf("> %v\n", roman_numerals.ToRoman(inputValueAsInt))
} |
package common
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
// URLS - структура с urls
type URLS struct {
EtranURL string "json:\"urlEtran\""
}
// ReadDataFromJSON - функция обработки json файла
func ReadDataFromJSON(path string) URLS {
jsonFile, err := os.Open(path)
if err != nil {
fmt.Println(err)
}
defer jsonFile.Close()
var urls URLS
byteValue, _ := ioutil.ReadAll(jsonFile)
json.Unmarshal(byteValue, &urls)
return urls
}
|
package stringUtil
import (
"strings"
"unicode"
)
const period string ="."
const space string =""
//判断字符串是否由数字组成
func IsNum(src string) (ok bool) {
if strings.Contains(period, src) {
if strings.Count(period, src) != 1 {
return false
}
} else {
for _, c := range src {
if c != 46 {
if !unicode.IsDigit(c) {
return false
}
}
}
}
return true
}
func Split(s,sep string) (dist []string){
tmp:= strings.Split(s, sep)
dist=make([]string,len(tmp))
i:=0
for _,s :=range tmp{
ts:=strings.TrimSpace(s)
if ts!=space{
dist[i]=s
i++
}
}
return dist
}
|
package color
import (
"testing"
)
func Example() {
Println(
Green("Green"), " ",
Red("Red").BgWhite(), " ",
"Normal ",
Yellow("Yellow"), " ",
Blue("%s", "Blue"))
}
func TestForeAndBack(t *testing.T) {
Println(Red("Red on White").BgWhite())
}
func TestForeground(t *testing.T) {
Println(
None("None"), " ",
Black("Black"), " ",
Red("Red"), " ",
Green("Green"), " ",
Yellow("Yellow"), " ",
Blue("Blue"), " ",
Magenta("Magenta"), " ",
Cyan("Cyan"), " ",
White("White"))
}
func TestBackgroud(t *testing.T) {
Println(
None("None").BgNone(), " ",
None("Black").BgBlack(), " ",
None("Red").BgRed(), " ",
None("Green").BgGreen(), " ",
None("Yellow").BgYellow(), " ",
None("Blue").BgBlue(), " ",
None("Magenta").BgMagenta(), " ",
None("Cyan").BgCyan(), " ",
None("White").BgWhite())
}
func TestNoColor(t *testing.T) {
Println("No color")
}
func TestFormatColor(t *testing.T) {
Println(Blue("%s", "Blue text with format"))
}
|
package apilifecycle
import godd "github.com/pagongamedev/go-dd"
// ValidateQuery Type
type ValidateQuery = func(context *godd.Context) (requestValidatedQuery interface{}, goddErr *godd.Error)
// ValidateQuery Set
func (api *APILifeCycle) ValidateQuery(handler ValidateQuery) {
api.validateQuery = handler
}
// GetValidateQuery Get
func (api *APILifeCycle) GetValidateQuery() ValidateQuery {
return api.validateQuery
}
// Handler Default
func handlerDefaultValidateQuery() ValidateQuery {
return func(context *godd.Context) (requestValidatedQuery interface{}, goddErr *godd.Error) {
return nil, nil
}
}
|
// Copyright (c) 2016-2019 Uber Technologies, 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 healthcheck
import (
"sync"
"github.com/uber/kraken/utils/stringset"
)
// state tracks the health status of a set of hosts. In particular, it tracks
// consecutive passes or fails which cause hosts to transition between healthy
// and unhealthy.
//
// state is thread-safe.
type state struct {
sync.Mutex
config FilterConfig
all stringset.Set
healthy stringset.Set
trend map[string]int
}
func newState(config FilterConfig) *state {
return &state{
config: config,
all: stringset.New(),
healthy: stringset.New(),
trend: make(map[string]int),
}
}
// sync sets the current state to addrs. New entries are initialized as healthy,
// while existing entries not found in addrs are removed from s.
func (s *state) sync(addrs stringset.Set) {
s.Lock()
defer s.Unlock()
for addr := range addrs {
if !s.all.Has(addr) {
s.all.Add(addr)
s.healthy.Add(addr)
}
}
for addr := range s.healthy {
if !addrs.Has(addr) {
s.healthy.Remove(addr)
delete(s.trend, addr)
}
}
}
// failed marks addr as failed.
func (s *state) failed(addr string) {
s.Lock()
defer s.Unlock()
s.trend[addr] = max(min(s.trend[addr]-1, -1), -s.config.Fails)
if s.trend[addr] == -s.config.Fails {
s.healthy.Remove(addr)
}
}
// passed marks addr as passed.
func (s *state) passed(addr string) {
s.Lock()
defer s.Unlock()
s.trend[addr] = min(max(s.trend[addr]+1, 1), s.config.Passes)
if s.trend[addr] == s.config.Passes {
s.healthy.Add(addr)
}
}
// getHealthy returns the current healthy hosts.
func (s *state) getHealthy() stringset.Set {
s.Lock()
defer s.Unlock()
return s.healthy.Copy()
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
|
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package hps
import (
"context"
"time"
"github.com/golang/protobuf/ptypes/empty"
wrappers "github.com/golang/protobuf/ptypes/wrappers"
"google.golang.org/grpc"
"chromiumos/tast/common/hps/hpsutil"
"chromiumos/tast/common/media/caps"
"chromiumos/tast/ctxutil"
"chromiumos/tast/remote/bundles/cros/hps/utils"
"chromiumos/tast/rpc"
pb "chromiumos/tast/services/cros/hps"
"chromiumos/tast/testing"
"chromiumos/tast/testing/hwdep"
)
func init() {
testing.AddTest(&testing.Test{
Func: CameraboxLoLOff,
LacrosStatus: testing.LacrosVariantUnneeded,
Desc: "Verify that HPS does not dim the screen quickly when LoL is off",
Data: []string{hpsutil.PersonPresentPageArchiveFilename},
Contacts: []string{
"eunicesun@google.com",
"mblsha@google.com",
"chromeos-hps-swe@google.com",
},
Attr: []string{"group:camerabox", "group:hps", "hps_perbuild"},
Timeout: 10 * time.Minute,
HardwareDeps: hwdep.D(hwdep.HPS()),
SoftwareDeps: []string{"hps", "chrome", caps.BuiltinCamera},
ServiceDeps: []string{"tast.cros.browser.ChromeService", "tast.cros.hps.HpsService"},
Vars: []string{"tablet", "grpcServerPort"},
})
}
func CameraboxLoLOff(ctx context.Context, s *testing.State) {
dut := s.DUT()
// Creating hps context.
hctx, err := hpsutil.NewHpsContext(ctx, "", hpsutil.DeviceTypeBuiltin, s.OutDir(), dut.Conn())
if err != nil {
s.Fatal("Error creating HpsContext: ", err)
}
// Connecting to the other tablet that will render the picture.
ctxForCleanupDisplayChart := ctx
ctx, cancel := ctxutil.Shorten(ctx, time.Minute)
hostPaths, displayChart, err := utils.SetupDisplay(ctx, s)
if err != nil {
s.Fatal("Error setting up display: ", err)
}
defer displayChart.Close(ctxForCleanupDisplayChart, s.OutDir())
displayChart.Display(ctx, hostPaths[utils.ZeroPresence])
// Connecting to Taeko.
cleanupCtx := ctx
ctx, cancel = ctxutil.Shorten(ctx, time.Minute)
defer cancel()
cl, err := rpc.Dial(ctx, dut, s.RPCHint())
if err != nil {
s.Fatal("Failed to setup grpc: ", err)
}
defer cl.Close(cleanupCtx)
// First turn on the "Lock on leave" feature.
// This is only needed so that we can scrape the quick dim delay from the powerd logs.
// We turn it off again below, when performing the actual test.
client := pb.NewHpsServiceClient(cl.Conn)
req := &pb.StartUIWithCustomScreenPrivacySettingRequest{
Setting: utils.LockOnLeave,
Enable: true,
}
if _, err := client.StartUIWithCustomScreenPrivacySetting(hctx.Ctx, req, grpc.WaitForReady(true)); err != nil {
s.Fatal("Failed to change setting: ", err)
}
// Get the delays for the quick dim.
delayReq := &wrappers.BoolValue{
Value: true,
}
quickDimMetrics, err := client.RetrieveDimMetrics(hctx.Ctx, delayReq)
if err != nil {
s.Fatal("Error getting delay settings: ", err)
}
// Turn off the "Lock on leave" feature. This disables HPS and gives us
// traditional dimming behaviour (i.e. not quick dim).
req.Enable = false
if _, err := client.StartUIWithCustomScreenPrivacySetting(hctx.Ctx, req, grpc.WaitForReady(true)); err != nil {
s.Fatal("Failed to change setting: ", err)
}
brightness, err := utils.GetBrightness(hctx.Ctx, dut.Conn())
if err != nil {
s.Fatal("Error failed to get brightness: ", err)
}
// Render hps-internal page for debugging before waiting for dim.
if _, err := client.OpenHPSInternalsPage(hctx.Ctx, &empty.Empty{}); err != nil {
s.Fatal("Error open hps-internals")
}
// It should *not* dim the screen within the quick dim delay period.
// Poll instead of Sleep in order to fail fast in case screen dims before the delay.
err = utils.PollForBrightnessChange(ctx, brightness, quickDimMetrics.DimDelay.AsDuration(), dut.Conn())
if err != nil {
// If brightness is not changed it's not an error in this case, as we'll check the brightness after polling anyway.
testing.ContextLog(ctx, err.Error())
}
newBrightness, err := utils.GetBrightness(hctx.Ctx, dut.Conn())
if err != nil {
s.Fatal("Error when getting brightness: ", err)
}
if newBrightness != brightness {
s.Fatal("Unexpected brightness change: was: ", brightness, ", new: ", newBrightness)
}
// It should *not* lock the screen within the quick screen off delay period.
err = utils.PollForBrightnessChange(ctx, brightness, quickDimMetrics.ScreenOffDelay.AsDuration(), dut.Conn())
if err != nil {
// If brightness is not changed it's not an error in this case, as we'll check the brightness after polling anyway.
testing.ContextLog(ctx, err.Error())
}
newBrightness, err = utils.GetBrightness(hctx.Ctx, dut.Conn())
if err != nil {
s.Fatal("Error when getting brightness: ", err)
}
if newBrightness != brightness {
s.Fatal("Unexpected brightness change: was: ", brightness, ", new: ", newBrightness)
}
}
|
package main
import (
"fmt"
"github.com/elentok/notes/node"
"github.com/elentok/notes/parser"
)
func main() {
root, err := Read("/Users/elentok/projects/editor/closures.notes")
if err != nil {
panic(err)
}
for _, node := range root.Children() {
printNode(node)
}
}
func printNode(n node.Node) {
if !n.IsBlank() {
task, isTask := n.(node.Task)
if isTask && task.IsComplete() {
return
}
fmt.Println(n.Text())
}
for _, child := range n.Children() {
printNode(child)
}
}
func Read(filename string) (node.Node, error) {
p := parser.New()
return p.Parse(filename)
}
|
// This file has been created by "go generate" as initial code. go generate will never update it, EXCEPT if you remove it.
// So, update it for your need.
package main
import (
"fmt"
"github.com/forj-oss/goforjj"
"log"
"os"
"path"
)
// checkSourceExistence Return ok if the X instance exist
func (r *UpdateReq) checkSourceExistence(ret *goforjj.PluginData) (p *GitlabPlugin, status bool) {
log.Print("Checking Gitlab source code existence.")
srcPath := path.Join(r.Forj.ForjjSourceMount, r.Forj.ForjjInstanceName)
if _, err := os.Stat(path.Join(srcPath, gitlabFile)); err == nil {
log.Printf(ret.Errorf("Unable to create the gitlab source code for instance name '%s' which already exist.\nUse update to update it (or update %s), and maintain to update gitlab according to his configuration. %s.", srcPath, srcPath, err))
return
}
p = newPlugin(srcPath)
ret.StatusAdd("environment checked.")
return p, true
}
/*func (r *GitlabPlugin) update_jenkins_sources(ret *goforjj.PluginData) (status bool) {
return true
}*/
// SaveMaintainOptions which adds maintain options as part of the plugin answer in create/update phase.
// forjj won't add any driver name because 'maintain' phase read the list of drivers to use from forjj-maintain.yml
// So --git-us is not available for forjj maintain.
func (r *UpdateArgReq) SaveMaintainOptions(ret *goforjj.PluginData) {
if ret.Options == nil {
ret.Options = make(map[string]goforjj.PluginOption)
}
}
//addMaintainOptionValue (default)
func addMaintainOptionValue(options map[string]goforjj.PluginOption, option, value, defaultv, help string) goforjj.PluginOption {
opt, ok := options[option]
if ok && value != "" {
opt.Value = value
return opt
}
if !ok {
opt = goforjj.PluginOption{Help: help}
if value == "" {
opt.Value = defaultv
} else {
opt.Value = value
}
}
return opt
}
//SetProject set default remotes and branchConnect (TODO)
func (gls *GitlabPlugin) SetProject(project *RepoInstanceStruct, isInfra, isDeployable bool) {
upstream := gls.DefineRepoUrls(project.Name)
owner := gls.gitlabDeploy.Group
if isInfra {
owner = gls.gitlabDeploy.ProdGroup
}
//set it, found or not
pjt := ProjectStruct{}
pjt.set(project,
map[string]goforjj.PluginRepoRemoteUrl{"origin": upstream},
map[string]string{"master": "origin/master"},
isInfra,
isDeployable, owner)
gls.gitlabDeploy.Projects[project.Name] = pjt
}
//updateYamlData TODO
func (gls *GitlabPlugin) updateYamlData(req *UpdateReq, ret *goforjj.PluginData) (bool, error) {
if gls.gitlabSource.Urls == nil {
return false, fmt.Errorf("Internal Error. Urls was not set")
}
if gls.gitlabDeploy.Projects == nil {
gls.gitlabDeploy.Projects = make(map[string]ProjectStruct)
}
//In update, we simply rebuild Users and Team from Forjfile.
//No need to keep track of removed one
//gls.gitlabDeploy.Users = make(map[string]string)
//...
if gls.app.ProjectsDisabled == "true" {
log.Print("ProjectsDisabled is true. forjj_gitlab won't manage projects except the infra one.")
gls.gitlabDeploy.NoProjects = true
} else {
//Updating all from Forjfile repos
gls.gitlabDeploy.NoProjects = false
//OrgHooks
for name, pjt := range req.Objects.Repo{
if !pjt.isValid(name, ret){
continue
}
gls.SetProject(&pjt, (name == gls.app.ForjjInfra), pjt.Deployable == "true")
//hooks
}
//Disabling missing one
/*for name, pjt := range gls.gitlabDeploy.Projects {
if err := pjt.isValid(name); err != nil { TODO isValid and delete
delete(gls.gitlabDeploy.Projects, name)
}
}*/
}
//...
return false, fmt.Errorf("TODO")
} |
package usersvc
type (
getUsersUseCase interface {
GetUsers() ([]User, error)
}
userInfoUseCase interface {
UserInfo(id string) (*User, error)
}
// Service groups the usecases together.
Service struct {
getUsersUseCase
userInfoUseCase
}
repository interface {
WithID(id string) (User, error)
BelongingToPage() ([]User, error)
}
)
func NewService(repo repository) *Service {
return &Service{
getUsersUseCase: NewGetUsersUseCase(repo),
userInfoUseCase: NewUserInfoUseCase(repo),
}
}
|
package disc
import (
"fmt"
"log"
"time"
"github.com/Karitham/WaifuBot/database"
"github.com/Karitham/WaifuBot/query"
"github.com/diamondburned/arikawa/v2/discord"
"github.com/diamondburned/arikawa/v2/gateway"
"go.mongodb.org/mongo-driver/mongo"
)
// Roll drops a random character and adds it to the database
func (b *Bot) Roll(m *gateway.MessageCreateEvent) (*discord.Embed, error) {
userData, err := database.ViewUserData(m.Author.ID)
if err != nil && err != mongo.ErrNoDocuments {
return nil, err
}
if nextRollTime := time.Until(userData.Date.Add(c.TimeBetweenRolls.Duration)); nextRollTime > 0 {
return nil, fmt.Errorf("**illegal roll**,\nroll in %s", nextRollTime.Truncate(time.Second))
}
char, err := query.CharSearchByPopularity(b.seed.Uint64() % c.MaxCharacterRoll)
if err != nil {
return nil, err
}
if ok, _ := database.CharID(char.Page.Characters[0].ID).VerifyWaifu(m.Author.ID); ok {
return b.Roll(m)
}
err = database.CharStruct(char).AddRolled(m.Author.ID)
if err != nil {
log.Println(err)
return nil, err
}
return &discord.Embed{
Title: char.Page.Characters[0].Name.Full,
URL: char.Page.Characters[0].SiteURL,
Description: fmt.Sprintf(
"You rolled character %d\nIt appears in :\n- %s",
char.Page.Characters[0].ID, char.Page.Characters[0].Media.Nodes[0].Title.Romaji,
),
Thumbnail: &discord.EmbedThumbnail{
URL: char.Page.Characters[0].Image.Large,
},
Footer: &discord.EmbedFooter{
Text: fmt.Sprintf(
"You can roll again in %s",
c.TimeBetweenRolls.Truncate(time.Second),
),
},
}, nil
}
|
package problem1029
import "sort"
func twoCitySchedCost(costs [][]int) int {
N := len(costs) / 2
diff := []Diff{}
for i := 0; i < len(costs); i++ {
d := Diff{
costDiff: costs[i][1] - costs[i][0],
idx: i,
}
diff = append(diff, d)
}
sort.Slice(diff, func(i, j int) bool { return diff[i].costDiff > diff[j].costDiff })
minCost := 0
for i := 0; i < len(diff); i++ {
cityIdx := diff[i].idx
if i < N {
minCost += costs[cityIdx][0]
} else {
minCost += costs[cityIdx][1]
}
}
return minCost
}
type Diff struct {
costDiff int
idx int
}
|
package minisentinel
import (
"errors"
"testing"
"time"
"github.com/FZambia/sentinel"
"github.com/alicebob/miniredis/v2"
"github.com/gomodule/redigo/redis"
"github.com/matryer/is"
)
// TestSomething - shows how-to start up sentinel + redis in your unittest
func TestSomething(t *testing.T) {
is := is.New(t)
m := miniredis.NewMiniRedis()
err := m.StartAddr(":6379")
is.NoErr(err)
defer m.Close()
s := NewSentinel(m, WithReplica(m))
err = s.StartAddr(":26379")
is.NoErr(err)
defer s.Close()
// all the setup is done.. now just use sentinel/redis like you
// would normally in your tests via a redis client
}
// TestRedisWithSentinel - an example of combining miniRedis with miniSentinel for unittests
func TestRedisWithSentinel(t *testing.T) {
is := is.New(t)
m, err := miniredis.Run()
m.RequireAuth("super-secret") // not required, but demonstrates how-to
is.NoErr(err)
defer m.Close()
s := NewSentinel(m, WithReplica(m))
s.Start()
defer s.Close()
// use redigo to create a sentinel pool
sntnl := &sentinel.Sentinel{
Addrs: []string{s.Addr()},
MasterName: s.MasterInfo().Name,
Dial: func(addr string) (redis.Conn, error) {
connTimeout := time.Duration(50 * time.Millisecond)
readWriteTimeout := time.Duration(50 * time.Millisecond)
c, err := redis.DialTimeout("tcp", addr, connTimeout, readWriteTimeout, readWriteTimeout)
if err != nil {
return nil, err
}
return c, nil
},
}
redisPassword := []byte("super-secret") // required because of m.RequireAuth()
pool := redis.Pool{
MaxIdle: 3,
MaxActive: 64,
Wait: true,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
redisHostAddr, errHostAddr := sntnl.MasterAddr()
if errHostAddr != nil {
return nil, errHostAddr
}
c, err := redis.Dial("tcp", redisHostAddr)
if err != nil {
return nil, err
}
if redisPassword != nil { // auth first, before doing anything else
if _, err := c.Do("AUTH", string(redisPassword)); err != nil {
c.Close()
return nil, err
}
}
return c, nil
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
if !sentinel.TestRole(c, "master") {
return errors.New("Role check failed")
}
return nil
},
}
// Optionally set some keys your code expects:
m.Set("foo", "not-bar")
m.HSet("some", "other", "key")
// Run your code and see if it behaves.
// An example using the redigo library from "github.com/gomodule/redigo/redis":
c := pool.Get()
defer c.Close() //release connection back to the pool
// use the pool connection to do things via TCP to our miniRedis
_, err = c.Do("SET", "foo", "bar")
// Optionally check values in redis...
got, err := m.Get("foo")
is.NoErr(err)
is.Equal(got, "bar")
// ... or use a miniRedis helper for that:
m.CheckGet(t, "foo", "bar")
// TTL and expiration:
m.Set("foo", "bar")
m.SetTTL("foo", 10*time.Second)
m.FastForward(11 * time.Second)
is.True(m.Exists("foo") == false) // it shouldn't be there anymore
}
|
package raws // import "github.com/BenLubar/dfide/gui/raws"
import (
"github.com/BenLubar/dfide/gui"
"github.com/BenLubar/dfide/raws"
"github.com/BenLubar/dfide/raws/language"
)
type languageEditor struct {
baseVisualEditor
tags []language.Tag
box gui.Box
}
func (e *languageEditor) control() gui.Control {
e.box = gui.NewVerticalBox()
e.box.SetPadded(true)
e.box.SetScrollable(gui.ScrollableAlways)
vbox := gui.NewVerticalBox()
vbox.SetPadded(true)
hbox := gui.NewHorizontalBox()
hbox.SetPadded(true)
hbox.Append(gui.NewLabel(""), true) // center-align
hbox.Append(gui.NewLabel("Add"), false)
addWordButton := gui.NewButton("Word")
addWordButton.OnClick(func() {
w := new(language.Word)
e.tags = append(e.tags, language.Tag{Word: w})
e.box.Append(e.addWord(w), false)
e.onChange()
})
hbox.Append(addWordButton, false)
addSymbolButton := gui.NewButton("Symbol")
addSymbolButton.OnClick(func() {
s := new(language.Symbol)
e.tags = append(e.tags, language.Tag{Symbol: s})
e.box.Append(e.addSymbol(s), false)
e.onChange()
})
hbox.Append(addSymbolButton, false)
addTranslationButton := gui.NewButton("Translation")
addTranslationButton.OnClick(func() {
t := new(language.Translation)
e.tags = append(e.tags, language.Tag{Translation: t})
e.box.Append(e.addTranslation(t), false)
e.onChange()
})
hbox.Append(addTranslationButton, false)
hbox.Append(gui.NewLabel(""), true) // center-align
vbox.Append(hbox, false)
vbox.Append(e.box, true)
for _, t := range e.tags {
var c gui.Control
if t.Symbol != nil {
c = e.addSymbol(t.Symbol)
} else if t.Translation != nil {
c = e.addTranslation(t.Translation)
} else {
c = e.addWord(t.Word)
}
e.box.Append(c, false)
}
return vbox
}
func (e *languageEditor) deleteTag(c gui.Control, tag language.Tag) {
for i, t := range e.tags {
if t == tag {
e.tags = append(e.tags[:i], e.tags[i+1:]...)
e.box.RemoveAt(i)
gui.Destroy(c)
e.onChange()
return
}
}
}
func (e *languageEditor) addTagBase(label string, id *string, tag language.Tag) gui.Box {
vbox := gui.NewVerticalBox()
hbox := gui.NewHorizontalBox()
hbox.SetPadded(true)
vbox.Append(hbox, false)
hbox.Append(gui.NewLabel(label), false)
idEntry := gui.NewEntry()
idEntry.SetText(*id)
idEntry.OnChange(func() {
*id = idEntry.Text()
e.onChange()
})
hbox.Append(idEntry, true)
deleteButton := gui.NewButton("Delete")
deleteButton.OnClick(func() {
e.deleteTag(vbox, tag)
})
hbox.Append(deleteButton, false)
return vbox
}
func (e *languageEditor) addSymbol(s *language.Symbol) gui.Control {
vbox := e.addTagBase("Symbol:", &s.ID, language.Tag{Symbol: s})
wordEntries := make([]gui.Entry, len(s.Words)+1)
var entryOnChange func(entry gui.Entry) func()
entryOnChange = func(entry gui.Entry) func() {
return func() {
if entry == wordEntries[len(wordEntries)-1] {
if entry.Text() != "" {
s.Words = append(s.Words, entry.Text())
e.onChange()
newDummy := gui.NewEntry()
newDummy.OnChange(entryOnChange(newDummy))
wordEntries = append(wordEntries, newDummy)
vbox.Append(newDummy, false)
}
} else {
for i, we := range wordEntries {
if entry == we {
if entry.Text() != "" {
s.Words[i] = entry.Text()
} else {
s.Words = append(s.Words[:i], s.Words[i+1:]...)
wordEntries = append(wordEntries[:i], wordEntries[i+1:]...)
vbox.RemoveAt(i + 1)
gui.Destroy(entry)
}
e.onChange()
return
}
}
}
}
}
for i, w := range s.Words {
entry := gui.NewEntry()
entry.SetText(w)
entry.OnChange(entryOnChange(entry))
wordEntries[i] = entry
vbox.Append(entry, false)
}
entry := gui.NewEntry()
entry.OnChange(entryOnChange(entry))
wordEntries[len(s.Words)] = entry
vbox.Append(entry, false)
return vbox
}
func (e *languageEditor) addTranslation(t *language.Translation) gui.Control {
vbox := e.addTagBase("Translation:", &t.ID, language.Tag{Translation: t})
var addEntry func(english, native string)
wordEntries := make([]gui.Box, 0, len(t.Words)+1)
var entryOnChange func(english, native gui.Entry, hbox gui.Box) func()
entryOnChange = func(english, native gui.Entry, hbox gui.Box) func() {
return func() {
if hbox == wordEntries[len(wordEntries)-1] {
if english.Text() != "" || native.Text() != "" {
t.Words = append(t.Words, language.TWord{
English: english.Text(),
Native: native.Text(),
})
e.onChange()
}
} else {
for i, we := range wordEntries {
if hbox == we {
if english.Text() != "" || native.Text() != "" {
t.Words[i].English = english.Text()
t.Words[i].Native = native.Text()
} else {
t.Words = append(t.Words[:i], t.Words[i+1:]...)
wordEntries = append(wordEntries[:i], wordEntries[i+1:]...)
vbox.RemoveAt(i + 1)
gui.Destroy(hbox)
}
e.onChange()
return
}
}
}
}
}
addEntry = func(english, native string) {
newEnglish := gui.NewEntry()
newNative := gui.NewEntry()
newEnglish.SetText(english)
newNative.SetText(native)
hbox := gui.NewHorizontalBox()
hbox.SetPadded(true)
hbox.Append(newEnglish, true)
hbox.Append(newNative, true)
wordEntries = append(wordEntries, hbox)
change := entryOnChange(newEnglish, newNative, hbox)
newEnglish.OnChange(change)
newNative.OnChange(change)
vbox.Append(hbox, false)
}
for _, w := range t.Words {
addEntry(w.English, w.Native)
}
addEntry("", "")
return vbox
}
func (e *languageEditor) addWord(w *language.Word) gui.Control {
vbox := e.addTagBase("Word:", &w.ID, language.Tag{Word: w})
tab := gui.NewTab()
tab.Append("Noun", e.addNoun(&w.Noun))
tab.Append("Adjective", e.addAdjective(&w.Adjective))
tab.Append("Prefix", e.addPrefix(&w.Prefix))
tab.Append("Verb", e.addVerb(&w.Verb))
vbox.Append(tab, true)
return vbox
}
func (e *languageEditor) addNoun(n **language.Noun) gui.Control {
// TODO
return gui.NewLabel("TODO: noun editor")
}
func (e *languageEditor) addAdjective(a **language.Adjective) gui.Control {
// TODO
return gui.NewLabel("TODO: adjective editor")
}
func (e *languageEditor) addPrefix(p **language.Prefix) gui.Control {
// TODO
return gui.NewLabel("TODO: prefix editor")
}
func (e *languageEditor) addVerb(v **language.Verb) gui.Control {
// TODO
return gui.NewLabel("TODO: verb editor")
}
func (e *languageEditor) onChange() {
e.baseVisualEditor.onChange("LANGUAGE", func(w *raws.Writer) error {
return w.SerializeAll(e.tags)
})
}
|
package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"path"
"strconv"
"strings"
"time"
)
func measurePut(n int, c *client, seq int32, logFp *os.File) int32 {
for i := 0; i < n; i++ {
key := fmt.Sprintf("key%d", i)
val := fmt.Sprintf("val%d", i)
t := time.Now()
c.MessagePut(0, key, val, seq)
timeTrack(t, "PUT", logFp)
seq++
}
return seq
}
func measureGet(n int, c *client, logFp *os.File) {
for i := 0; i < n; i++ {
key := fmt.Sprintf("key%d", i)
t := time.Now()
c.MessageGet(0, key)
timeTrack(t, "GET", logFp)
}
}
func timeTrack(start time.Time, task string, logFp *os.File) {
elapsed := time.Since(start)
if logFp != nil {
logFp.WriteString(fmt.Sprintf("%s duration:%d\n", task, elapsed))
}
}
func main() {
path := path.Join(os.Getenv("LOCAL"), "client_benchmark.txt")
logFp, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Fatalf("Open log file error: %v\n", err)
}
inputReader := bufio.NewReader(os.Stdin)
client := createClient("client")
seqNumber := (int32)(rand.Int31n(1000000000))
for {
in, _ := inputReader.ReadString('\n')
in = strings.TrimSpace(in)
splits := strings.Split(in, " ")
if len(splits) <= 1 {
fmt.Println("bad input")
continue
}
switch splits[0] {
// CONN host:port
case "CONN":
if len(splits) != 2 {
fmt.Println("bad input")
continue
}
if client.Connect(splits[1], 1) {
fmt.Println("connected to " + splits[1])
} else {
fmt.Println("failed to connect to " + splits[1])
}
// PUT key val
case "PUT":
if len(splits) != 3 {
fmt.Println("bad input")
continue
}
key, val := splits[1], splits[2]
ret := client.MessagePut(0, key, val, seqNumber)
fmt.Printf("return code: %v\n", ret)
seqNumber++
// GET key
case "GET":
if len(splits) != 2 {
fmt.Println("bad input")
continue
}
key := splits[1]
val, ret := client.MessageGet(0, key)
fmt.Printf("return value: %s\n", val)
fmt.Printf("return code: %v\n", ret)
// set client ID
// ID clientID
case "ID":
if len(splits) != 2 {
fmt.Println("bad input")
continue
}
client.Id = splits[1]
case "PUT_N":
n, _ := strconv.Atoi(splits[1])
seqNumber = measurePut(n, client, seqNumber, logFp)
case "GET_N":
n, _ := strconv.Atoi(splits[1])
measureGet(n, client, logFp)
}
}
}
|
// Copyright (c) 2016-2018, Jan Cajthaml <jan.cajthaml@gmail.com>
//
// 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 main
import (
"bufio"
"context"
"fmt"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"github.com/jancajthaml-openbank/vault/actor"
"github.com/jancajthaml-openbank/vault/cron"
"github.com/jancajthaml-openbank/vault/metrics"
"github.com/jancajthaml-openbank/vault/utils"
"github.com/gin-gonic/gin"
)
var (
version string
build string
)
func setupLogOutput(params utils.RunParams) {
if len(params.Setup.Log) == 0 {
return
}
file, err := os.Create(params.Setup.Log)
if err != nil {
log.Warnf("Unable to create %s: %v", params.Setup.Log, err)
return
}
defer file.Close()
log.SetOutput(bufio.NewWriter(file))
}
func setupLogLevel(params utils.RunParams) {
level, err := log.ParseLevel(params.Setup.LogLevel)
if err != nil {
log.Warnf("Invalid log level %v, using level WARN", params.Setup.LogLevel)
return
}
log.Infof("Log level set to %v", strings.ToUpper(params.Setup.LogLevel))
log.SetLevel(level)
}
func init() {
viper.SetEnvPrefix("VAULT")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()
viper.SetDefault("log.level", "DEBUG")
viper.SetDefault("http.port", 8080)
viper.SetDefault("storage", "/data")
viper.SetDefault("journal.saturation", 100)
viper.SetDefault("snasphot.scaninteval", "1m")
viper.SetDefault("metrics.refreshrate", "1s")
}
func validParams(params utils.RunParams) bool {
if len(params.Setup.Tenant) == 0 || len(params.Setup.LakeHostname) == 0 {
log.Error("missing required parameter to run")
return false
}
if os.MkdirAll(params.Setup.RootStorage, os.ModePerm) != nil {
log.Error("unable to assert storage directory")
return false
}
if len(params.Metrics.Output) != 0 && os.MkdirAll(filepath.Dir(params.Metrics.Output), os.ModePerm) != nil {
log.Error("unable to assert metrics output")
return false
}
return true
}
func loadParams() utils.RunParams {
return utils.RunParams{
Setup: utils.SetupParams{
RootStorage: viper.GetString("storage") + "/" + viper.GetString("tenant"),
Tenant: viper.GetString("tenant"),
LakeHostname: viper.GetString("lake.hostname"),
Log: viper.GetString("log"),
LogLevel: viper.GetString("log.level"),
HTTPPort: viper.GetInt("http.port"),
},
Journal: utils.JournalParams{
SnapshotScanInterval: viper.GetDuration("snasphot.scaninteval"),
JournalSaturation: viper.GetInt("journal.saturation"),
},
Metrics: utils.MetricsParams{
RefreshRate: viper.GetDuration("metrics.refreshrate"),
Output: viper.GetString("metrics.output"),
},
}
}
func main() {
log.Infof(">>> Setup <<<")
params := loadParams()
if !validParams(params) {
return
}
setupLogOutput(params)
setupLogLevel(params)
log.Infof(">>> Starting <<<")
// FIXME separate into its own go routine to be stopable
m := metrics.NewMetrics()
gin.SetMode(gin.ReleaseMode)
system := new(actor.ActorSystem)
system.Start(params, m) // FIXME if there is no lake, application is stuck here
// FIXME check if nil if so then return
router := gin.New()
router.GET("/health", func(c *gin.Context) {
c.String(200, "")
})
exitSignal := make(chan os.Signal, 1)
signal.Notify(exitSignal, syscall.SIGINT, syscall.SIGTERM)
srv := &http.Server{
Addr: fmt.Sprintf(":%d", params.Setup.HTTPPort),
Handler: router,
}
go func() {
if err := srv.ListenAndServe(); err != nil {
exitSignal <- syscall.SIGTERM
}
}()
var wg sync.WaitGroup
terminationChan := make(chan struct{})
wg.Add(2)
go cron.SnapshotSaturationScan(&wg, terminationChan, params, m, system.ProcessLocalMessage)
go metrics.PersistMetrics(&wg, terminationChan, params, m)
log.Infof(">>> Started <<<")
<-exitSignal
log.Infof(">>> Terminating <<<")
system.Stop()
close(terminationChan)
wg.Wait()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
log.Infof(">>> Terminated <<<")
}
|
package main
import (
"flag"
"fmt"
"io/ioutil"
"os/exec"
"strings"
"sync"
"time"
"github.com/freb/go-blink1"
)
const (
fade = 250 * time.Millisecond
dur = 2 * time.Second
)
var white = blink1.State{Red: 255, Green: 255, Blue: 255, FadeTime: fade, Duration: dur} // #FFFFFF
var black = blink1.State{Red: 0, Green: 0, Blue: 0, FadeTime: fade, Duration: dur} // #000000
var red = blink1.State{Red: 255, Green: 0, Blue: 0, FadeTime: fade, Duration: dur} // #FF0000
var orange = blink1.State{Red: 255, Green: 165, Blue: 0, FadeTime: fade, Duration: dur} // #FFA500
var yellow = blink1.State{Red: 255, Green: 255, Blue: 0, FadeTime: fade, Duration: dur} // #FFFF00
var purple = blink1.State{Red: 128, Green: 0, Blue: 128, FadeTime: fade, Duration: dur} // #800080
var blue = blink1.State{Red: 0, Green: 0, Blue: 255, FadeTime: fade, Duration: dur} // #0000FF
var green = blink1.State{Red: 0, Green: 128, Blue: 0, FadeTime: fade, Duration: dur} // #008000
type status struct {
sync.Mutex
ifaceUp bool // red
gwUp bool // yellow
tunUp bool // purple
inetUp bool // blue
dev *blink1.Device
}
func (s *status) closeDev() {
s.Lock()
defer s.Unlock()
s.dev.Close()
var dev *blink1.Device
s.dev = dev
}
func (s *status) setIface(up bool) {
s.Lock()
defer s.Unlock()
s.ifaceUp = up
}
func (s *status) getIface() bool {
s.Lock()
defer s.Unlock()
return s.ifaceUp
}
func (s *status) setGw(up bool) {
s.Lock()
defer s.Unlock()
s.gwUp = up
}
func (s *status) getGw() bool {
s.Lock()
defer s.Unlock()
return s.gwUp
}
func (s *status) setTun(up bool) {
s.Lock()
defer s.Unlock()
s.tunUp = up
}
func (s *status) getTun() bool {
s.Lock()
defer s.Unlock()
return s.tunUp
}
func (s *status) setInet(up bool) {
s.Lock()
defer s.Unlock()
s.inetUp = up
}
func (s *status) getInet() bool {
s.Lock()
defer s.Unlock()
return s.inetUp
}
func (s *status) Pattern() blink1.Pattern {
s.Lock()
defer s.Unlock()
states := make([]blink1.State, 0)
if s.ifaceUp == false {
states = append(states, red)
}
if s.gwUp == false {
states = append(states, yellow)
}
if s.tunUp == false {
states = append(states, purple)
}
if s.inetUp == false {
states = append(states, blue)
}
if s.ifaceUp == true && s.gwUp == true && s.tunUp == true && s.inetUp == true {
states = append(states, green)
}
states = append(states, black)
return blink1.Pattern{States: states}
}
func ifaceUp(iface string) bool {
path := "/sys/class/net/" + iface + "/operstate"
dat, err := ioutil.ReadFile(path)
if err != nil {
fmt.Println(err)
}
state := string(dat)
state = strings.TrimSpace(state)
return state == "up"
}
func gwUp(gw string) bool {
if gw == "" {
out, err := exec.Command("ip", "route").Output()
if err != nil {
fmt.Println(err)
}
routes := string(out)
for _, v := range strings.Split(routes, "\n") {
if strings.HasPrefix(v, "default") {
gw = strings.Fields(v)[2]
}
}
}
if err := exec.Command("ping", "-c", "1", gw).Run(); err != nil {
return false
}
return true
}
func tunUp(tun1, tun2 string) bool {
if tun1 == "" && tun2 == "" {
return true
}
if tun1 != "" {
if err := exec.Command("ping", "-c", "1", tun1).Run(); err == nil {
return true
}
}
if tun2 != "" {
if err := exec.Command("ping", "-c", "1", tun2).Run(); err == nil {
return true
}
}
return false
}
func inetUp(ip string) bool {
if err := exec.Command("ping", "-c", "1", ip).Run(); err != nil {
return false
}
return true
}
func (s *status) write() {
defer func() {
if r := recover(); r != nil {
s.closeDev()
}
}()
if s.dev == nil {
// library bug requires blink1-tool to first make contact with device
exec.Command("blink1-tool", "--list").Run()
dev, _ := blink1.OpenNextDevice()
if dev == nil {
// looping terminates here when blink1 is unplugged
time.Sleep(time.Second)
return
}
s.Lock()
s.dev = dev
s.Unlock()
}
p := s.Pattern()
start := time.Now()
s.dev.RunPattern(&p)
// only reliable way to tell if the blink1 device is open is to see if pattern
// takes as long to execute as it should
if time.Now().Sub(start) < time.Second {
// this is only hit once per unplug
s.closeDev()
}
return
}
func main() {
var (
iface string
gw string
tun1 string
tun2 string
inet string
)
flag.StringVar(&iface, "iface", "eth0", "network interface")
flag.StringVar(&gw, "gw", "", "default gateway")
flag.StringVar(&tun1, "tun1", "", "vpn tunnel endpoint 1")
flag.StringVar(&tun2, "tun2", "", "vpn tunnel endpoint 2")
flag.StringVar(&inet, "inet", "8.8.8.8", "internet endpoint")
flag.Parse()
s := &status{}
go func() {
for {
up := ifaceUp(iface)
s.setIface(up)
time.Sleep(5 * time.Second)
}
}()
go func() {
for {
up := gwUp(gw)
s.setGw(up)
time.Sleep(5 * time.Second)
}
}()
go func() {
for {
up := tunUp(tun1, tun2)
s.setTun(up)
time.Sleep(5 * time.Second)
}
}()
go func() {
for {
up := inetUp(inet)
s.setInet(up)
time.Sleep(5 * time.Second)
}
}()
for {
s.write()
}
}
|
package driver_location
// DriverID represents a driver identifier.
type DriverID int
// Location represents geo information from cars.
type Location struct {
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
Updated_at string `json:"updated_at,omitempty"`
}
// Locations represents records in database related to a car.
type Locations struct {
Locations []Location `json:"locations,omitempty"`
Err string `json:"err,omitempty"`
ServerIP string `json:"serverIP,omitempty"`
}
// Bus represents a connection to a message bus.
type Bus interface {
Initialize(cs CabService) (BusService, error)
}
// BusService represents a service for handling a bus.
type BusService interface {
Consume() error
}
// Client creates a connection to the services.
type Client interface {
Connect() CabService
}
// CabService represents a service for managing requests.
type CabService interface {
StoreLocation(id string, loc *Location) error
GetDriverLocations(id string, minutes float64) (*Locations, error)
}
|
package dao
import (
"example.com/http_demo/model/dao/table"
"example.com/http_demo/utils/zlog"
"github.com/jinzhu/gorm"
"go.uber.org/zap"
"time"
)
//-------- 单表查询开始 -----------//
func GetAllOrders() (orders []*table.Order, err error) {
orders = make([]*table.Order, 0)
err = DB().Find(&orders).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return
}
func GetFirstOrderInTable() (order *table.Order, err error) {
// 指针变量要先初始化, 直接传给Gorm的查询方法会空指针报错
order = new(table.Order)
//.First(&order) 传指针类型变量order的指针也行, 效果一样不用纠结
err = DB().First(order).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return
}
func GetLastOrderInTable() (order *table.Order, err error) {
order = new(table.Order)
err = DB().Last(order).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return
}
func GetUserOrders(userId int64) (orders []*table.Order, err error) {
orders = make([]*table.Order, 0)
err = DB().Where("user_id = ?", userId).Find(&orders).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return
}
func GetUserPaidOrders(userId int64) (orders []*table.Order, err error) {
orders = make([]*table.Order, 0)
err = DB().Where("user_id = ?", userId).
Where("state = ?", table.ORDER_STATE_PAY_SUCCESS).
// 这两个Where调用等价于 .Where("user_id = ? AND state = ?", userId, 2)
// 等价于用Map查询
// .Where(map[stirng]interface{} { // 不建议使用, 只能进行相等匹配, 且不能做参数类型限制
// user_id: userId,
// state: 2
// })
Find(&orders).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return
}
func GetUserUnPaidOrders(userId int64) (orders []*table.Order, err error) {
orders = make([]*table.Order, 0)
err = DB().Where("user_id = ?", userId).
Where("state IN (?)", []int{table.ORDER_STATE_UNPAID, table.ORDER_STATE_PAY_FAILD}).
Find(&orders).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return
}
func GetUserNotPaidOrders(userId int64) (orders []*table.Order, err error) {
orders = make([]*table.Order, 0)
err = DB().Where("user_id = ?", userId).
Not("state", table.ORDER_STATE_PAY_SUCCESS).
Find(&orders).Error
// SELECT * FROM orders WHERE user_id = {userId} AND state != 2
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return
}
func GetUserNotFailedOrders(userId int64) (orders []*table.Order, err error) {
orders = make([]*table.Order, 0)
err = DB().Where("user_id = ?", userId).
Not("state", []int{table.ORDER_STATE_UNPAID, table.ORDER_STATE_PAY_FAILD}).
Find(&orders).Error
// SELECT * FROM orders WHERE user_id = {userId} AND state NOT IN (1, 3)
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return
}
// OR 条件
func GetOrderUnPaidOrPayFailed() (orders []*table.Order, err error) {
orders = make([]*table.Order, 0)
err = DB().Where("state = ?", table.ORDER_STATE_UNPAID).
Or("state = ?", table.ORDER_STATE_PAY_FAILD).
Find(&orders).Error
// SELECT * FROM orders WHERE user_id = {userId} AND state NOT IN (1, 3)
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return
}
func QueryOrderListForUser(userId int64, dataFrom, dataSize int, startDate, endDate string) (orders []*table.Order, orderTotal int, err error) {
orders = make([]*table.Order, 0)
db := DB().Where("user_id = ?", userId)
// 根据参数值生成响应的SQL
if startDate != "" {
db = db.Where("created_at >= ?", startDate)
}
if endDate != "" {
db = db.Where("created_at <= ?", endDate)
}
err = db.Debug().Order("id DESC").
Offset(dataFrom).
Limit(dataSize).
Find(&orders).Count(&orderTotal).Error
// 一般分页会要求返回当页数据和总条数, 这种写法会减少代码重复量, 就不需要再写下面的 QueryOrderCountForUser 函数了
// SELECT * FROM orders WHERE ... ORDER BY id DESC LIMIT 10, OFFSET 0
// SELECT COUNT(*) FROM orders WHERE ... ORDER BY id DESC LIMIT 10, OFFSET 0
// (ORDER BY, LIMIT 对COUNT不起作用, 会正确返回WHERE条件对应的行数)
zlog.Info("result debug", zap.Any("list", orders), zap.Any("total", orderTotal))
if err != nil && err != gorm.ErrRecordNotFound {
return nil, 0, err
}
return
}
func QueryOrderCountForUser(userId int64, startDate, endDate string) (orderCount int, err error) {
db := DB().Model(table.Order{}).
Where("user_id = ?", userId)
if startDate != "" {
db = db.Where("created_at >= ?", startDate)
}
if endDate != "" {
db = db.Where("created_at <= ?", startDate)
}
err = db.Count(&orderCount).Error
return
}
type OrderSerialInfo struct {
OrderNo string // 对应Scan扫描的结果集里的order_no 字段
// 如果Scan扫描的结果字段与结构体字段不同, 需要使用tag进行标注
OutOrderNo string `gorm:"column:platform_order_no"`
}
func GetOrderSerialInfo(orderNo string) (orderSerialInfo *OrderSerialInfo, err error) {
orderSerialInfo = new(OrderSerialInfo)
// Debug() 用于调试时打印出执行的SQL
// Scan操作时使用.Model() 会告诉GORM要在哪个Model对象上执行操作, GORM会自动找到对应的表名
err = DB().Debug().Model(table.Order{}).
// DB().Model(table.Order{}) 也可以写成 DB().Table(table.Order{}.TableName())
//.Table()是更底层的写法,直接指定SQL的表名, 一般在关联查询里使用这种写法
Select("order_no, platform_order_no").
Where("order_no = ?", orderNo).
Scan(&orderSerialInfo).Error
// Scan 用于将查询结果集扫描进结构体或者结构体列表中去
// 没查到数据会返回 gorm.ErrRecordNotFound 错误
// Scan 可以用在SELECT 和 GROUP、JOIN 等指定返回字段的查询中, 用于获取结果--把查询结果集扫描到实参变量中存储
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
zlog.Info("GetOrderSerialInfo", zap.Any("orderSerialInfo", orderSerialInfo))
return
}
//db.Model() 和 db.Table()的区别
//https://stackoverflow.com/questions/67550966/go-gorm-difference-between-db-model-and-db-table-query
func GetOrdersSerial(orderNo []string) (serialInfoList []*OrderSerialInfo, err error) {
serialInfoList = make([]*OrderSerialInfo, 0)
err = DB().Debug().Model(table.Order{}).
Select("order_no, platform_order_no").
Where("order_no IN (?)", orderNo).
Scan(&serialInfoList).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return
}
type OrderStat struct {
Date string
DayMoneyAmount int64 `gorm:"column:amount"`
}
func GetOrderStat() (stats []*OrderStat, err error) {
stats = make([]*OrderStat, 0)
err = DB().Debug().Model(table.Order{}).
Select("SUM(bill_money) AS amount, DATE(created_at) AS date").
Group("DATE(created_at)").
Having("amount > 0").Scan(&stats).Error // 把Group结果扫描进实现定义好的结构体列表
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return
}
func GetOrderStatMap() (statMap map[string]*OrderStat, err error) {
// 使用Rows()返回结果集, 遍历结果集返回更定制化的结果
rows, err := DB().Table(table.Order{}.TableName()).
Select("SUM(bill_money) AS amount, DATE(created_at) AS date").
Group("DATE(created_at)").
Having("amount > 0").Rows()
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
var amount int64
var date string
statMap = map[string]*OrderStat{}
defer rows.Close()
for rows.Next() {
err = rows.Scan(&amount, &date)
if err != nil {
return nil, err
}
statMap[date] = &OrderStat{
Date: date,
DayMoneyAmount: amount,
}
}
return statMap, err
}
//-------- 单表查询结束 -----------//
//-------- Update操作 -----------//
// GORM 的时间跟踪
// GORM 会对模型中的三个时间字段进行跟踪, 分别是CreatedAt, UpdatedAt, DeletedAt
// 如果模型有CreatedAt, UpdatedAt 创建记录时都会被赋予当时的时间, 更新记录时GORM会总动更新UpdatedAt的时间
// 如果模型有DeletedAt字段, 调用Delete删除该记录时,将会设置DeletedAt字段为当前时间,而不是直接将记录从数据库中删除。
func SetOrderStatePaySuccess(orderNo string) error {
updates := map[string]interface{}{
"state": table.ORDER_STATE_PAY_SUCCESS,
"paid_at": time.Now(),
}
// 执行SQL UPDATE orders SET state = 2, paid_at = '当前时间(yyyy-mm-dd hh:ii:ss)', updated_at = '当前时间' WHERE order_no = {orderNo}
// 使用 map 更新多个属性,只会更新其中有变化的属性
err := DB().Model(table.Order{}).
Where("order_no = ?", orderNo).
Update(updates).Error
// Update方法里也可以使用结构体 Update(&table.Order{State: 2, PaidAt: time.Now()})
// 使用 struct 更新多个属性,只会更新其中有变化且为非零值的字段
// 另外可以通过Update(updates).RowsAffected 获取更新的记录数
return err
}
//-------- Update操作结束 -----------//
//-------- Join 查询 -----------//
type UserGoods struct {
UserId int64
OrderNo string
GoodsId int64
GoodsName string
OrderState int `gorm:"column:state"`
}
func GetUserOrderGoods(userId int64) (goodsList []*UserGoods, err error) {
tableOrder := table.Order{}.TableName()
tableGoods := table.OrderGoods{}.TableName()
goodsList = make([]*UserGoods, 0)
err = DB().Debug().Table(tableOrder+" AS o").
Joins("INNER JOIN "+tableGoods+" AS og ON o.id = og.order_id").
Select("o.user_id, o.order_no, o.state, og.id as goods_id, og.goods_name").
Where("o.user_id = ?", userId).Scan(&goodsList).Error
// Scan, Find方法的参数是Slice类型时, 必须传递Slice的指针, 否则在其中填充数据后因为底层数组变更,导致内外部Slice指向的底层数组不一致
zlog.Info("debug data", zap.Any("data", goodsList))
return
}
// GetUserOrderGoodsMap 返回以GoodsId为Key, GoodsName为值的Map
// 主要是为了演示对JOIN查询结果集的逐行Scan操作
func GetUserOrderGoodsMap(userId int64) (userOrderGoodsMap map[int64]string, err error) {
tableOrder := table.Order{}.TableName()
tableGoods := table.OrderGoods{}.TableName()
rows, err := DB().Table(tableOrder+" AS o").
Joins("INNER JOIN "+tableGoods+" AS og ON o.id = og.order_id").
Select("og.id as goods_id, og.goods_name").
Where("o.user_id = ?", userId).Rows()
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
defer rows.Close()
userOrderGoodsMap = make(map[int64]string)
var (
GoodsId int64
GoodsName string
)
for rows.Next() {
//err := rows.Scan(&result)
// 遍历结果集的记录时Scan只能往多个基础类型变量里扫描列对应的数据
// 有几列就对应几个变量, 不能往结构体里扫描, 否则会报错
// 比如本例中如果把连表查询的结果逐行Scan到一个结构体变量, 会有如下错误
// sql: expected 2 destination arguments in Scan, not 1
// 综合起来更推荐上一种把整个结果集Scan进结构体列表的方式拿到连表查询的结果集.
err := rows.Scan(&GoodsId, &GoodsName)
if err != nil {
return nil, err
}
userOrderGoodsMap[GoodsId] = GoodsName
}
return
}
// 事务内操作
func GetOrderByNoInTx(tx *gorm.DB, orderNo string) (order *table.Order, err error) {
order = new(table.Order)
err = tx.Set("gorm:query_option", "FOR UPDATE").Where("order_no = ?", orderNo).First(&order).Error
// SELECT * FROM orders WHERE order_no = ? FOR UPDATE
return
}
// SetOrderStatePaySuccessInTx 在事务中修改订单状态
func SetOrderStatePaySuccessInTx(tx *gorm.DB, orderNo string) error {
updates := map[string]interface{}{
"state": table.ORDER_STATE_PAY_SUCCESS,
"paid_at": time.Now(),
}
err := tx.Model(table.Order{}).
Where("order_no = ?", orderNo).
Update(updates).Error
return err
}
|
// Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package base_test
import (
"context"
"fmt"
"net"
"os"
"strings"
"testing"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
)
type addrs struct{ listen, adv, http, advhttp, sql, advsql string }
func (a *addrs) String() string {
return fmt.Sprintf(""+
"--listen-addr=%s --advertise-addr=%s "+
"--http-addr=%s (http adv: %s) "+
"--sql-addr=%s (sql adv: %s)",
a.listen, a.adv, a.http, a.advhttp, a.sql, a.advsql)
}
func TestValidateAddrs(t *testing.T) {
defer leaktest.AfterTest(t)()
// Prepare some reference strings that will be checked in the
// test below.
hostname, err := os.Hostname()
if err != nil {
t.Fatal(err)
}
hostAddr, err := base.LookupAddr(context.Background(), net.DefaultResolver, hostname)
if err != nil {
t.Fatal(err)
}
if strings.Contains(hostAddr, ":") {
hostAddr = "[" + hostAddr + "]"
}
localAddr, err := base.LookupAddr(context.Background(), net.DefaultResolver, "localhost")
if err != nil {
t.Fatal(err)
}
if strings.Contains(localAddr, ":") {
localAddr = "[" + localAddr + "]"
}
// We need to know what a port name resolution error look like,
// because they may be different across systems/libcs.
_, err = net.DefaultResolver.LookupPort(context.Background(), "tcp", "nonexistent")
if err == nil {
t.Fatal("expected port resolution failure, got no error")
}
portExpectedErr := err.Error()
// For the host name resolution error we can reliably expect "no such host"
// below, but before we test anything we need to ensure we indeed have
// a reliably non-resolvable host name.
_, err = net.DefaultResolver.LookupIPAddr(context.Background(), "nonexistent.example.com")
if err == nil {
t.Fatal("expected host resolution failure, got no error")
}
// The test cases.
testData := []struct {
in addrs
expectedErr string
expected addrs
}{
// Common case: no server flags, all defaults.
{addrs{":26257", "", ":8080", "", ":5432", ""}, "",
addrs{":26257", hostname + ":26257", ":8080", hostname + ":8080", ":5432", hostname + ":5432"}},
// Another common case: --listen-addr=<somehost>
{addrs{hostname + ":26257", "", ":8080", "", ":5432", ""}, "",
addrs{hostAddr + ":26257", hostname + ":26257", hostAddr + ":8080", hostname + ":8080", hostAddr + ":5432", hostname + ":5432"}},
// Another common case: --listen-addr=localhost
{addrs{"localhost:26257", "", ":8080", "", ":5432", ""}, "",
addrs{localAddr + ":26257", "localhost:26257", localAddr + ":8080", "localhost:8080", localAddr + ":5432", "localhost:5432"}},
// Correct use: --listen-addr=<someaddr> --advertise-host=<somehost>
{addrs{hostAddr + ":26257", hostname + ":", ":8080", "", ":5432", ""}, "",
addrs{hostAddr + ":26257", hostname + ":26257", hostAddr + ":8080", hostname + ":8080", hostAddr + ":5432", hostname + ":5432"}},
// Explicit port number in advertise addr.
{addrs{hostAddr + ":26257", hostname + ":12345", ":8080", "", ":5432", ""}, "",
addrs{hostAddr + ":26257", hostname + ":12345", hostAddr + ":8080", hostname + ":8080", hostAddr + ":5432", hostname + ":5432"}},
// Use a non-numeric port number.
{addrs{":postgresql", "", ":http", "", ":postgresql", ""}, "",
addrs{":5432", hostname + ":5432", ":80", hostname + ":80", ":5432", hostname + ":5432"}},
// Make HTTP local only.
{addrs{":26257", "", "localhost:8080", "", ":5432", ""}, "",
addrs{":26257", hostname + ":26257", localAddr + ":8080", "localhost:8080", ":5432", hostname + ":5432"}},
// Local server but public HTTP.
{addrs{"localhost:26257", "", hostname + ":8080", "", ":5432", ""}, "",
addrs{localAddr + ":26257", "localhost:26257", hostAddr + ":8080", hostname + ":8080", localAddr + ":5432", "localhost:5432"}},
// Make SQL and tenant local only.
{addrs{":26257", "", ":8080", "", "localhost:5432", ""}, "",
addrs{":26257", hostname + ":26257", ":8080", hostname + ":8080", localAddr + ":5432", "localhost:5432"}},
// Not-unreasonable case: addresses set empty. Means using port 0.
{addrs{"", "", "", "", "", ""}, "",
addrs{":0", hostname + ":0", ":0", hostname + ":0", ":0", hostname + ":0"}},
// A colon means "all-addr, auto-port".
{addrs{":", "", "", "", "", ""}, "",
addrs{":0", hostname + ":0", ":0", hostname + ":0", ":0", hostname + ":0"}},
{addrs{"", ":", "", "", "", ""}, "",
addrs{":0", hostname + ":0", ":0", hostname + ":0", ":0", hostname + ":0"}},
{addrs{"", "", ":", "", "", ""}, "",
addrs{":0", hostname + ":0", ":0", hostname + ":0", ":0", hostname + ":0"}},
{addrs{"", "", "", "", ":", ""}, "",
addrs{":0", hostname + ":0", ":0", hostname + ":0", ":0", hostname + ":0"}},
{addrs{"", "", "", "", "", ":"}, "",
addrs{":0", hostname + ":0", ":0", hostname + ":0", ":0", hostname + ":0"}},
{addrs{"", "", "", "", "", ""}, "",
addrs{":0", hostname + ":0", ":0", hostname + ":0", ":0", hostname + ":0"}},
{addrs{"", "", "", "", "", ""}, "",
addrs{":0", hostname + ":0", ":0", hostname + ":0", ":0", hostname + ":0"}},
// Advertise port 0 means reuse listen port. We don't
// auto-allocate ports for advertised addresses.
{addrs{":12345", ":0", "", "", ":5432", ""}, "",
addrs{":12345", hostname + ":12345", ":0", hostname + ":0", ":5432", hostname + ":5432"}},
{addrs{":12345", "", "", "", ":5432", ":0"}, "",
addrs{":12345", hostname + ":12345", ":0", hostname + ":0", ":5432", hostname + ":5432"}},
// Expected errors.
// Missing port number.
{addrs{"localhost", "", "", "", "", ""}, "invalid --listen-addr.*missing port in address", addrs{}},
{addrs{":26257", "", "localhost", "", "", ""}, "invalid --http-addr.*missing port in address", addrs{}},
// Invalid port number.
{addrs{"localhost:-1231", "", "", "", "", ""}, "invalid port", addrs{}},
{addrs{"localhost:nonexistent", "", "", "", "", ""}, portExpectedErr, addrs{}},
// Invalid address.
{addrs{"nonexistent.example.com:26257", "", "", "", "", ""}, "no such host", addrs{}},
{addrs{"333.333.333.333:26257", "", "", "", "", ""}, "no such host", addrs{}},
}
for i, test := range testData {
t.Run(fmt.Sprintf("%d/%s", i, test.in), func(t *testing.T) {
cfg := base.Config{
Addr: test.in.listen,
AdvertiseAddr: test.in.adv,
HTTPAddr: test.in.http,
HTTPAdvertiseAddr: test.in.advhttp,
SQLAddr: test.in.sql,
SQLAdvertiseAddr: test.in.advsql,
}
if err := cfg.ValidateAddrs(context.Background()); err != nil {
if !testutils.IsError(err, test.expectedErr) {
t.Fatalf("expected error %q, got %v", test.expectedErr, err)
}
return
}
if test.expectedErr != "" {
t.Fatalf("expected error %q, got success", test.expectedErr)
}
got := addrs{
listen: cfg.Addr,
adv: cfg.AdvertiseAddr,
http: cfg.HTTPAddr,
advhttp: cfg.HTTPAdvertiseAddr,
sql: cfg.SQLAddr,
advsql: cfg.SQLAdvertiseAddr,
}
gotStr := got.String()
expStr := test.expected.String()
if gotStr != expStr {
t.Fatalf("expected %q,\ngot %q", expStr, gotStr)
}
})
}
}
|
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package crostini
import (
"context"
"time"
"chromiumos/tast/local/chrome/uiauto"
"chromiumos/tast/local/chrome/uiauto/faillog"
"chromiumos/tast/local/chrome/uiauto/nodewith"
"chromiumos/tast/local/crostini"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: TaskManager,
LacrosStatus: testing.LacrosVariantUnneeded,
Desc: "Tests Crostini integration with the task manager",
Contacts: []string{"davidmunro@google.com", "clumptini+oncall@google.com"},
SoftwareDeps: []string{"chrome", "vm_host"},
Attr: []string{"group:mainline"},
Params: []testing.Param{
// Parameters generated by params_test.go. DO NOT EDIT.
{
Name: "buster_stable",
ExtraSoftwareDeps: []string{"dlc"},
ExtraHardwareDeps: crostini.CrostiniStable,
Fixture: "crostiniBuster",
Timeout: 7 * time.Minute,
}, {
Name: "buster_unstable",
ExtraAttr: []string{"informational"},
ExtraSoftwareDeps: []string{"dlc"},
ExtraHardwareDeps: crostini.CrostiniUnstable,
Fixture: "crostiniBuster",
Timeout: 7 * time.Minute,
}, {
Name: "bullseye_stable",
ExtraSoftwareDeps: []string{"dlc"},
ExtraHardwareDeps: crostini.CrostiniStable,
Fixture: "crostiniBullseye",
Timeout: 7 * time.Minute,
}, {
Name: "bullseye_unstable",
ExtraAttr: []string{"informational"},
ExtraSoftwareDeps: []string{"dlc"},
ExtraHardwareDeps: crostini.CrostiniUnstable,
Fixture: "crostiniBullseye",
Timeout: 7 * time.Minute,
},
},
})
}
func TaskManager(ctx context.Context, s *testing.State) {
tconn := s.FixtValue().(crostini.FixtureData).Tconn
keyboard := s.FixtValue().(crostini.FixtureData).KB
defer faillog.DumpUITreeOnError(ctx, s.OutDir(), s.HasError, tconn)
tastkManager := nodewith.Name("Task Manager").ClassName("TaskManagerView").First()
crostiniEntry := nodewith.Name("Linux Virtual Machine: termina").Ancestor(tastkManager).First()
ui := uiauto.New(tconn)
if err := uiauto.Combine("open Task Manager and look for Crostini",
// Press Search + Esc to launch task manager
keyboard.AccelAction("Search+Esc"),
// Click the task manager.
ui.LeftClick(tastkManager),
// Focus on Crostini entry.
ui.WaitUntilExists(crostiniEntry),
// Exit task manager.
keyboard.AccelAction("Ctrl+W"))(ctx); err != nil {
s.Fatal("Failed to test Crostini in Task Manager: ", err)
}
}
|
package math
import (
"jvm-go/instruction/base"
"jvm-go/runtimedata"
)
// todo 实现
type D2F struct{ base.NoOperandsInstruction }
type D2I struct{ base.NoOperandsInstruction }
func (self *D2I) Execute(frame *runtimedata.Frame) {
stack := frame.OperandStack()
d := stack.PopDouble()
i := int32(d)
stack.PushInt(i)
}
// todo 实现
type D2L struct{ base.NoOperandsInstruction }
|
package middleware
import (
"apiserver/handler"
"apiserver/pkg/errno"
"bytes"
"encoding/json"
"github.com/gin-gonic/gin"
"github.com/lexkong/log"
"github.com/willf/pad"
"io/ioutil"
"regexp"
"time"
)
//used for capture Response
type bodyLogWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (w bodyLogWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
//----------------------------------------------
func Logging() gin.HandlerFunc {
return func(c *gin.Context) {
//Get start time of middleware run
start := time.Now().UTC()
//Get and validate path
path := c.Request.URL.Path
reg := regexp.MustCompile("(/v1/user|/login)")
if !reg.MatchString(path) {
return
}
if path == "/sd/health" || path == "sd/ram" || path == "sd/cpu" || path == "sd/disk" {
return
}
//read the Body content
var bodyBytes []byte
if c.Request.Body != nil {
bodyBytes, _ = ioutil.ReadAll(c.Request.Body)
}
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
//Get Method
method := c.Request.Method
//Get Ip
ip := c.ClientIP()
log.Debugf("New request come in,ip:%s,path:%s,Method: %s, body:`%s`", ip, path, method, string(bodyBytes))
// capture Response
blw := bodyLogWriter{
c.Writer,
bytes.NewBufferString(""),
}
c.Writer = blw
c.Next()
//calculate the latency
end := time.Now().UTC()
latency := end.Sub(start)
//get code and message
code, message := -1, ""
var response handler.Response
if err := json.Unmarshal(blw.body.Bytes(), &response); err != nil {
log.Errorf(err, "response body can't unmarsha1 to model.Response struct,body:`%s`", blw.body.Bytes())
code = errno.ErrBind.Code
message = err.Error()
} else {
code = response.Code
message = response.Message
}
//log info
log.Infof("%-13s|%-12s|%s %s|{code: %d,message:%s}", latency, ip, pad.Right(method, 5, ""), path, code, message)
}
}
|
package db
import (
"fmt"
"time"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/lucas-dev-it/62252aee-9d11-4149-a0ea-de587cbcd233/business/model"
"github.com/lucas-dev-it/62252aee-9d11-4149-a0ea-de587cbcd233/internal"
)
var (
host = internal.GetEnv("DB_HOST", "localhost")
user = internal.GetEnv("DB_USER", "local")
name = internal.GetEnv("DB_NAME", "meetup")
port = internal.GetEnv("DB_PORT", "5432")
password = internal.GetEnv("DB_PASS", "password")
environment = internal.GetEnv("ENVIRONMENT", "dev")
)
// NewPostgres return new connection to db and execute migration.
func NewPostgres() (*gorm.DB, error) {
connectStr := fmt.Sprintf(
"host=%s port=%s user=%s dbname=%s password=%s sslmode=disable",
host,
port,
user,
name,
password,
)
db, err := gorm.Open("postgres", connectStr)
if err != nil {
return nil, err
}
db.DB().SetConnMaxLifetime(5 * time.Minute)
db.DB().SetMaxOpenConns(20)
db.DB().SetMaxIdleConns(20)
db.AutoMigrate(model.User{}, model.Scope{}, model.MeetUp{})
if environment == "dev" {
if err := prepareTestMigration(db); err != nil {
fmt.Printf("error when running test migration\n")
}
}
return db, nil
}
|
// SPDX-License-Identifier: ISC
// Copyright (c) 2014-2020 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package rpc_test
import (
"fmt"
"math/rand"
"os"
"path"
"testing"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
announce2 "github.com/bitmark-inc/bitmarkd/announce"
"github.com/bitmark-inc/bitmarkd/fault"
"github.com/bitmark-inc/bitmarkd/rpc"
"github.com/bitmark-inc/bitmarkd/rpc/fixtures"
"github.com/bitmark-inc/bitmarkd/rpc/listeners"
"github.com/bitmark-inc/bitmarkd/rpc/mocks"
)
func TestInitialise(t *testing.T) {
fixtures.SetupTestLogger()
defer fixtures.TeardownTestLogger()
ctl := gomock.NewController(t)
defer ctl.Finish()
ann := mocks.NewMockAnnounce(ctl)
wd, _ := os.Getwd()
fixtureDir := path.Join(wd, "fixtures")
cer := fixtures.Certificate(fixtureDir)
key := fixtures.Key(fixtureDir)
port := 30000 + rand.Intn(30000)
listen := fmt.Sprintf("127.0.0.1:%d", port)
rpcConfig := listeners.RPCConfiguration{
MaximumConnections: 100,
Bandwidth: 10000000,
Listen: []string{listen},
Certificate: cer,
PrivateKey: key,
Announce: []string{"127.0.0.1:65500"},
}
httpsConfig := listeners.HTTPSConfiguration{
MaximumConnections: 100,
Listen: []string{listen},
Certificate: cer,
PrivateKey: key,
Allow: nil,
}
ann.EXPECT().Set(gomock.Any(), gomock.Any()).Return(nil).Times(1)
err := rpc.Initialise(&rpcConfig, &httpsConfig, "1.0", ann)
assert.Nil(t, err, "wrong Initialise")
err = rpc.Finalise()
assert.Nil(t, err, "wrong Finalise")
}
func TestInitialiseWhenTwice(t *testing.T) {
fixtures.SetupTestLogger()
defer fixtures.TeardownTestLogger()
ctl := gomock.NewController(t)
defer ctl.Finish()
ann := mocks.NewMockAnnounce(ctl)
wd, _ := os.Getwd()
fixtureDir := path.Join(wd, "fixtures")
cer := fixtures.Certificate(fixtureDir)
key := fixtures.Key(fixtureDir)
port := 30000 + rand.Intn(30000)
listen := fmt.Sprintf("127.0.0.1:%d", port)
rpcConfig := listeners.RPCConfiguration{
MaximumConnections: 100,
Bandwidth: 10000000,
Listen: []string{listen},
Certificate: cer,
PrivateKey: key,
Announce: []string{"127.0.0.1:65500"},
}
httpsConfig := listeners.HTTPSConfiguration{
MaximumConnections: 100,
Listen: []string{listen},
Certificate: cer,
PrivateKey: key,
Allow: nil,
}
ann.EXPECT().Set(gomock.Any(), gomock.Any()).Return(nil).Times(1)
err := rpc.Initialise(&rpcConfig, &httpsConfig, "1.0", ann)
assert.Nil(t, err, "wrong Initialise")
defer rpc.Finalise()
err = rpc.Initialise(&rpcConfig, &httpsConfig, "1.0", announce2.Get())
assert.NotNil(t, err, "wrong Initialise")
assert.Equal(t, fault.AlreadyInitialised, err, "wrong second Initialise")
}
func TestInitialiseWhenCertificateError(t *testing.T) {
fixtures.SetupTestLogger()
defer fixtures.TeardownTestLogger()
ctl := gomock.NewController(t)
defer ctl.Finish()
ann := mocks.NewMockAnnounce(ctl)
port := 30000 + rand.Intn(30000)
listen := fmt.Sprintf("127.0.0.1:%d", port)
rpcConfig := listeners.RPCConfiguration{
MaximumConnections: 100,
Bandwidth: 10000000,
Listen: []string{listen},
Certificate: "",
PrivateKey: "",
Announce: []string{"127.0.0.1:65500"},
}
httpsConfig := listeners.HTTPSConfiguration{}
err := rpc.Initialise(&rpcConfig, &httpsConfig, "1.0", ann)
assert.NotNil(t, err, "wrong Initialise")
assert.Contains(t, err.Error(), "tls", "wrong error")
}
func TestInitialiseWhenRPCListenerError(t *testing.T) {
fixtures.SetupTestLogger()
defer fixtures.TeardownTestLogger()
ctl := gomock.NewController(t)
defer ctl.Finish()
ann := mocks.NewMockAnnounce(ctl)
wd, _ := os.Getwd()
fixtureDir := path.Join(wd, "fixtures")
cer := fixtures.Certificate(fixtureDir)
key := fixtures.Key(fixtureDir)
port := 30000 + rand.Intn(30000)
listen := fmt.Sprintf("127.0.0.1:%d", port)
rpcConfig := listeners.RPCConfiguration{
MaximumConnections: 100,
Bandwidth: 100,
Listen: []string{listen},
Certificate: cer,
PrivateKey: key,
Announce: []string{"127.0.0.1:65500"},
}
httpsConfig := listeners.HTTPSConfiguration{}
err := rpc.Initialise(&rpcConfig, &httpsConfig, "1.0", ann)
assert.NotNil(t, err, "wrong Initialise")
assert.Equal(t, fault.MissingParameters, err, "wrong error")
}
func TestInitialiseWhenHTTPSListenerError(t *testing.T) {
fixtures.SetupTestLogger()
defer fixtures.TeardownTestLogger()
ctl := gomock.NewController(t)
defer ctl.Finish()
ann := mocks.NewMockAnnounce(ctl)
wd, _ := os.Getwd()
fixtureDir := path.Join(wd, "fixtures")
cer := fixtures.Certificate(fixtureDir)
key := fixtures.Key(fixtureDir)
port := 30000 + rand.Intn(30000)
listen := fmt.Sprintf("127.0.0.1:%d", port)
rpcConfig := listeners.RPCConfiguration{
MaximumConnections: 100,
Bandwidth: 10000000,
Listen: []string{listen},
Certificate: cer,
PrivateKey: key,
Announce: []string{"127.0.0.1:65500"},
}
httpsConfig := listeners.HTTPSConfiguration{
MaximumConnections: 0,
Listen: []string{listen},
Certificate: cer,
PrivateKey: key,
Allow: nil,
}
ann.EXPECT().Set(gomock.Any(), gomock.Any()).Return(nil).Times(1)
err := rpc.Initialise(&rpcConfig, &httpsConfig, "1.0", ann)
assert.NotNil(t, err, "wrong Initialise")
assert.Equal(t, fault.MissingParameters, err, "wrong error")
}
func TestFinaliseWhenNotInitialised(t *testing.T) {
err := rpc.Finalise()
assert.NotNil(t, err, "wrong Finalise")
assert.Equal(t, fault.NotInitialised, err, "wrong error")
}
|
/*
* Wire API
*
* Moov Wire implements an HTTP API for creating, parsing, and validating Fedwire messages.
*
* API version: v1
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
// MessageDisposition struct for MessageDisposition
type MessageDisposition struct {
// formatVersion identifies the Fedwire message format version 30.
FormatVersion string `json:"formatVersion,omitempty"`
// testProductionCode identifies if test or production. * `T` - Test * `P` - Production
TestProductionCode string `json:"testProductionCode,omitempty"`
// MessageDuplicationCode * ` ` - Original Message * `R` - Retrieval of an original message * `P` - Resend
MessageDuplicationCode string `json:"messageDuplicationCode,omitempty"`
// MessageStatusIndicator Outgoing Messages * `0` - In process or Intercepted * `2` - Successful with Accounting (Value) * `3` - Rejected due to Error Condition * `7` - Successful without Accounting (Non-Value) Incoming Messages * `N` - Successful with Accounting (Value) * `S` - Successful without Accounting (Non-Value)
MessageStatusIndicator string `json:"messageStatusIndicator,omitempty"`
}
|
// Copyright 2014 Matthias Zenger. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package impl
import "testing"
func TestEmptyArray(t *testing.T) {
a := NewArray()
if a.Length() != 0 {
t.Errorf("Expected empty array")
}
}
func TestGetSet(t *testing.T) {
a := NewArray()
a.Allocate(0, 2)
a.Set(0, "zero")
a.Set(1, "one")
if a.At(0) != "zero" {
t.Errorf("Expected zero")
}
if a.At(1) != "one" {
t.Errorf("Expected one")
}
if a.Length() != 2 {
t.Errorf("Length should be 2")
}
}
|
package main
// https://leetcode.com/problems/longest-substring-without-repeating-characters/#/description
import (
"fmt"
)
var hashTable = [26]int{}
func lengthOfLongestSubstring(s string) int {
strlen := len(s)
maxCount := -1
for i := 0; i < strlen; i++ {
hashTable = [26]int{}
count := 0
for j := i; j < strlen; j++ {
// 以j为开始的最大子串
fmt.Println(j, s[j], s[j]-'a')
if s[j]-'a' < 0 || s[j]-'a' >= 26 || hashTable[s[j]-'a'] > 0 {
break
}
count += 1
hashTable[s[j]-'a'] += 1
}
if maxCount < count {
maxCount = count
}
}
return maxCount
}
func main() {
str := "abcdabcbb"
max := lengthOfLongestSubstring(str)
fmt.Println("max", max)
}
|
package main
import (
"log"
"net/http"
"os"
"github.com/elizar/w/routes"
"github.com/gorilla/handlers"
"github.com/gorilla/pat"
)
func main() {
r := pat.New()
// register routes
routes.RegisterRoutes(r)
// Use gorilla logger if server is not mounted
// through `up start`
http.Handle("/", func() http.Handler {
if os.Getenv("UP_STAGE") != "" {
return r
}
return handlers.LoggingHandler(os.Stdout, r)
}())
// port
port := ":" + os.Getenv("PORT")
// listen and serve
err := http.ListenAndServe(port, nil)
if err != nil {
log.Fatalln("ListenAndServe:", err)
}
}
|
// Copyright 2021 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cgroupfs
import (
"bytes"
"fmt"
"gvisor.dev/gvisor/pkg/bitmap"
"gvisor.dev/gvisor/pkg/context"
"gvisor.dev/gvisor/pkg/errors/linuxerr"
"gvisor.dev/gvisor/pkg/hostarch"
"gvisor.dev/gvisor/pkg/log"
"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs"
"gvisor.dev/gvisor/pkg/sentry/kernel"
"gvisor.dev/gvisor/pkg/sentry/kernel/auth"
"gvisor.dev/gvisor/pkg/sentry/vfs"
"gvisor.dev/gvisor/pkg/sync"
"gvisor.dev/gvisor/pkg/usermem"
)
// +stateify savable
type cpusetController struct {
controllerCommon
controllerStateless
controllerNoResource
maxCpus uint32
maxMems uint32
mu sync.Mutex `state:"nosave"`
cpus *bitmap.Bitmap
mems *bitmap.Bitmap
}
var _ controller = (*cpusetController)(nil)
func newCPUSetController(k *kernel.Kernel, fs *filesystem) *cpusetController {
cores := uint32(k.ApplicationCores())
cpus := bitmap.New(cores)
cpus.FlipRange(0, cores)
mems := bitmap.New(1)
mems.FlipRange(0, 1)
c := &cpusetController{
cpus: &cpus,
mems: &mems,
maxCpus: uint32(k.ApplicationCores()),
maxMems: 1, // We always report a single NUMA node.
}
c.controllerCommon.init(kernel.CgroupControllerCPUSet, fs)
return c
}
// Clone implements controller.Clone.
func (c *cpusetController) Clone() controller {
c.mu.Lock()
defer c.mu.Unlock()
cpus := c.cpus.Clone()
mems := c.mems.Clone()
new := &cpusetController{
maxCpus: c.maxCpus,
maxMems: c.maxMems,
cpus: &cpus,
mems: &mems,
}
new.controllerCommon.cloneFromParent(c)
return new
}
// AddControlFiles implements controller.AddControlFiles.
func (c *cpusetController) AddControlFiles(ctx context.Context, creds *auth.Credentials, _ *cgroupInode, contents map[string]kernfs.Inode) {
contents["cpuset.cpus"] = c.fs.newControllerWritableFile(ctx, creds, &cpusData{c: c}, true)
contents["cpuset.mems"] = c.fs.newControllerWritableFile(ctx, creds, &memsData{c: c}, true)
}
// +stateify savable
type cpusData struct {
c *cpusetController
}
// Generate implements vfs.DynamicBytesSource.Generate.
func (d *cpusData) Generate(ctx context.Context, buf *bytes.Buffer) error {
d.c.mu.Lock()
defer d.c.mu.Unlock()
fmt.Fprintf(buf, "%s\n", formatBitmap(d.c.cpus))
return nil
}
// Write implements vfs.WritableDynamicBytesSource.Write.
func (d *cpusData) Write(ctx context.Context, _ *vfs.FileDescription, src usermem.IOSequence, offset int64) (int64, error) {
return d.WriteBackground(ctx, src)
}
// WriteBackground implements writableControllerFileImpl.WriteBackground.
func (d *cpusData) WriteBackground(ctx context.Context, src usermem.IOSequence) (int64, error) {
if src.NumBytes() > hostarch.PageSize {
return 0, linuxerr.EINVAL
}
buf := copyScratchBufferFromContext(ctx, hostarch.PageSize)
n, err := src.CopyIn(ctx, buf)
if err != nil {
return 0, err
}
buf = buf[:n]
b, err := parseBitmap(string(buf), d.c.maxCpus)
if err != nil {
log.Warningf("cgroupfs cpuset controller: Failed to parse bitmap: %v", err)
return 0, linuxerr.EINVAL
}
if got, want := b.Maximum(), d.c.maxCpus; got > want {
log.Warningf("cgroupfs cpuset controller: Attempted to specify cpuset.cpus beyond highest available cpu: got %d, want %d", got, want)
return 0, linuxerr.EINVAL
}
d.c.mu.Lock()
defer d.c.mu.Unlock()
d.c.cpus = b
return int64(n), nil
}
// +stateify savable
type memsData struct {
c *cpusetController
}
// Generate implements vfs.DynamicBytesSource.Generate.
func (d *memsData) Generate(ctx context.Context, buf *bytes.Buffer) error {
d.c.mu.Lock()
defer d.c.mu.Unlock()
fmt.Fprintf(buf, "%s\n", formatBitmap(d.c.mems))
return nil
}
// Write implements vfs.WritableDynamicBytesSource.Write.
func (d *memsData) Write(ctx context.Context, _ *vfs.FileDescription, src usermem.IOSequence, offset int64) (int64, error) {
return d.WriteBackground(ctx, src)
}
// WriteBackground implements writableControllerFileImpl.WriteBackground.
func (d *memsData) WriteBackground(ctx context.Context, src usermem.IOSequence) (int64, error) {
if src.NumBytes() > hostarch.PageSize {
return 0, linuxerr.EINVAL
}
buf := copyScratchBufferFromContext(ctx, hostarch.PageSize)
n, err := src.CopyIn(ctx, buf)
if err != nil {
return 0, err
}
buf = buf[:n]
b, err := parseBitmap(string(buf), d.c.maxMems)
if err != nil {
log.Warningf("cgroupfs cpuset controller: Failed to parse bitmap: %v", err)
return 0, linuxerr.EINVAL
}
if got, want := b.Maximum(), d.c.maxMems; got > want {
log.Warningf("cgroupfs cpuset controller: Attempted to specify cpuset.mems beyond highest available node: got %d, want %d", got, want)
return 0, linuxerr.EINVAL
}
d.c.mu.Lock()
defer d.c.mu.Unlock()
d.c.mems = b
return int64(n), nil
}
|
package main
import (
"log"
"github.com/spf13/cobra"
)
var (
// Version is set with a linker flag (see Makefile)
Version string
// Build is set with a linker flag (see Makefile)
Build string
)
func main() {
log.Printf("ampctl (version: %s, build: %s)\n", Version, Build)
rootCmd := &cobra.Command{
Use: "ampctl",
Short: "Run commands in target amp cluster",
RunE: func(cmd *cobra.Command, args []string) error {
// perform checks and install by default when no sub-command is specified
if err := checks(cmd, []string{}); err != nil {
return err
}
return install(cmd, args)
},
}
rootCmd.AddCommand(NewChecksCommand())
rootCmd.AddCommand(NewInstallCommand())
rootCmd.AddCommand(NewMonitorCommand())
rootCmd.AddCommand(NewUninstallCommand())
// These flags pertain to install, but need to be enabled here at root and persiste for when it is invoked with no subcommand
rootCmd.PersistentFlags().BoolVar(&installOpts.skipTests, "fast", false, "Skip service smoke tests")
rootCmd.PersistentFlags().BoolVar(&installOpts.noMonitoring, "no-monitoring", false, "Don't deploy monitoring services")
if err := rootCmd.Execute(); err != nil {
log.Fatalf("Error: %s\n", err)
}
}
|
package saveddocrefs
type DocInsertPrimaryKeyEntry struct {
DocID string
TableName string
PrimaryKey string
}
|
package task
import (
"sync"
"github.com/beego/beego/v2/core/logs"
"github.com/mobilemindtec/go-utils/v2/ctx"
"github.com/mobilemindtec/go-utils/v2/optional"
"github.com/sirsean/go-pool"
)
type TaskType int
type TaskSource[T any] struct {
Data T
}
func NewTaskSource[T any]() *TaskSource[T] {
return &TaskSource[T]{}
}
type TaskResult[T any] struct {
Result T
Error error
}
func NewTaskResult[T any]() *TaskResult[T] {
return &TaskResult[T]{}
}
func (this *TaskResult[T]) HasError() bool {
return this.Error != nil
}
type Runnable[DS any, R any] struct {
TaskR func(DS, *TaskGroup[DS, R]) R
Task func(DS, *TaskGroup[DS, R])
TaskGroup *TaskGroup[DS, R]
Data DS
}
func (this *Runnable[DS, R]) Perform() {
defer func() {
if r := recover(); r != nil {
logs.Error("error to perform task: %v", r)
}
}()
if this.Task != nil {
this.Task(this.Data, this.TaskGroup)
} else if this.TaskR != nil {
r := this.TaskR(this.Data, this.TaskGroup)
this.TaskGroup.AddResult(r)
} else {
logs.Error("no task to perform")
}
}
type TaskGroup[DS any, R any] struct {
ResultChan chan R
DataSource []DS
results []R
Ctx *ctx.Ctx
Mutex *sync.Mutex
WaitGroup *sync.WaitGroup
PoolSize int
onReceive func(R)
taskR func(DS, *TaskGroup[DS, R]) R
task func(DS, *TaskGroup[DS, R])
}
func New[DS any, R any]() *TaskGroup[DS, R] {
var wg sync.WaitGroup
return &TaskGroup[DS, R]{Ctx: ctx.New(),
Mutex: new(sync.Mutex),
WaitGroup: &wg,
PoolSize: 10,
results: []R{}}
}
func (this *TaskGroup[DS, R]) SetPoolSize(i int) *TaskGroup[DS, R] {
this.PoolSize = i
return this
}
func (this *TaskGroup[DS, R]) SetTask(r func(DS, *TaskGroup[DS, R])) *TaskGroup[DS, R] {
this.task = r
return this
}
func (this *TaskGroup[DS, R]) SetTaskR(r func(DS, *TaskGroup[DS, R]) R) *TaskGroup[DS, R] {
this.taskR = r
return this
}
func (this *TaskGroup[DS, R]) SetOnReceive(r func(R)) *TaskGroup[DS, R] {
this.onReceive = r
return this
}
func (this *TaskGroup[DS, R]) SetDataSource(ds []DS) *TaskGroup[DS, R] {
this.DataSource = append(this.DataSource, ds...)
return this
}
func (this *TaskGroup[DS, R]) AddItem(item DS) *TaskGroup[DS, R] {
this.DataSource = append(this.DataSource, item)
return this
}
func (this *TaskGroup[DS, R]) AddResult(r R) {
this.Mutex.Lock()
this.results = append(this.results, r)
this.Mutex.Unlock()
if this.onReceive != nil {
go this.onReceive(r)
}
}
func (this *TaskGroup[DS, R]) AddCtx(key string, val interface{}) *TaskGroup[DS, R] {
this.Mutex.Lock()
this.Ctx.Put(key, val)
this.Mutex.Unlock()
return this
}
func (this *TaskGroup[DS, R]) GetCtxOpt(key string) interface{} {
if this.Ctx.Has(key) {
return optional.NewSome(this.Ctx.Get(key))
}
return optional.NewNone()
}
func (this *TaskGroup[DS, R]) GetCtx(key string) (interface{}, bool) {
if this.Ctx.Has(key) {
return this.Ctx.Get(key), true
}
return nil, false
}
func (this *TaskGroup[DS, R]) HasCtx(key string) bool {
return this.Ctx.Has(key)
}
func (this *TaskGroup[DS, R]) GetResults() []R {
return this.results
}
func (this *TaskGroup[DS, R]) Start() *TaskGroup[DS, R] {
p := pool.NewPool(10, 20)
p.Start()
for _, data := range this.DataSource {
p.Add(&Runnable[DS, R]{
TaskR: this.taskR,
Task: this.task,
TaskGroup: this,
Data: data})
}
p.Close()
/*
this.ResultChan = make(chan R) // armazena dos erros do processamento async
for _, data := range this.DataSource {
this.WaitGroup.Add(1) // novo trabalho em espera
go func() {
defer this.WaitGroup.Done()
this.task(data, this) // inicia trabalho
}
}
// espera pelo fim do processamento em background, para que a leitura do canal funciona na thread principal
go func() {
logs.Debug("wait by workers..")
this.WaitGroup.Wait()
close(this.ResultChan)
logs.Debug("workers is done")
}()*/
return this
}
|
package iso
import (
"errors"
"fmt"
"testing"
)
type handler struct{}
func (h *handler) ExecuteTransaction(msg *Message) (string, error) {
// fmt.Printf("Receiving iso message: [%s] \n", tool.AsJSON(msg))
if msg.ResponseCode == RcFail {
msg.ResponseCode = RcSuccess
msg.ResponseMessage = "Transaksi berhasil"
msg.Amount = "40000"
return RcSuccess, nil
}
return RcFail, errors.New("Sengaja")
}
func OffTestServer(t *testing.T) {
var server TCPServer
server.Handler = &handler{}
fmt.Println("Starting server @ 5000 ...")
server.Serve(":", 5000)
}
func TestIsoString(t *testing.T) {
var iso Message
iso.MTI = "2200"
iso.ProcessingCode = PcInquiry
iso.ResponseCode = RcFail
iso.ResponseMessage = "This is from client"
iso.SetAmount(50000)
fmt.Println(iso.String())
}
// func TestClient(t *testing.T) {
// var iso Message
// iso.MTI = "2200"
// iso.ProcessingCode = PcInquiry
// iso.ResponseCode = RcFail
// iso.ResponseMessage = "This is from client"
// fmt.Println("Sending Request")
// fmt.Println(iso.String())
// if err := iso.Execute("localhost", 5000); err != nil {
// t.Error(err)
// }
// // Equal(t, iso.ResponseCode, RcSuccess)
// fmt.Println(iso.String())
// }
|
package main
import "fmt"
func main() {
b := []byte("12345678")
fmt.Println(b)
b[0] = b[3]
copy(b, b[3:])
b = b[:(8 - 3)]
fmt.Println(b)
}
|
package recursion
import (
"AlgorizmiGo/collections/sequential"
"fmt"
)
func StackUnwind(n int) {
// Exit condition
if n < 0 {
return
}
fmt.Printf("Before recursion - %v\n", n)
StackUnwind(n - 1)
fmt.Printf("After recursion - %v\n", n)
}
var preQueue sequential.Queue = sequential.CreateQueue()
var postQueue sequential.Queue = sequential.CreateQueue()
var preStack sequential.Stack = sequential.CreateStack(5)
var postStack sequential.Stack = sequential.CreateStack(5)
func RecursionWithDataCaches(n int) {
doRecursionWithDataCaches(n)
dumpRecursionCaches()
}
func doRecursionWithDataCaches(n int) {
// Exit condition
if n == 0 {
return
}
// Cache data before recursion
preQueue.Enqueue(n)
preStack.Push(sequential.Item{n})
doRecursionWithDataCaches(n - 1)
// Cache data after recursion
postQueue.Enqueue(n)
postStack.Push(sequential.Item{n})
}
func dumpRecursionCaches() {
fmt.Println("PreStack:")
for !preStack.IsEmpty() {
value, err := preStack.Pop()
if err == nil {
fmt.Printf("%v ", value)
}
}
fmt.Println("\nPreQueue:")
for !preQueue.IsEmpty() {
value, err := preQueue.Dequeue()
if err == nil {
fmt.Printf("%v ", value)
}
}
fmt.Println("\nPostStack:")
for !postStack.IsEmpty() {
value, err := postStack.Pop()
if err == nil {
fmt.Printf("%v ", value)
}
}
fmt.Println("\nPostQueue:")
for !postQueue.IsEmpty() {
value, err := postQueue.Dequeue()
if err == nil {
fmt.Printf("%v ", value)
}
}
}
type incrementer func(index int) int
func ForwardIterationViaRecursion(start int, end int, increment int) {
if start > end {
return
}
var funcIncrementer incrementer = func(index int) int { return index + increment }
doForwardIteration(start, end, funcIncrementer)
}
func doForwardIteration(index int, end int, funcIncrementer incrementer) {
// Exit condition
if index >= end {
return
}
fmt.Println("Processing index ", index)
doForwardIteration(funcIncrementer(index), end, funcIncrementer)
}
func ReverseIterationViaRecursion(start int, end int, decrement int) {
if start < end {
return
}
var funcDecrementer incrementer = func(index int) int { return index - decrement }
doReverseIteration(start, end, funcDecrementer)
}
func doReverseIteration(index int, end int, funcDecrementer incrementer) {
// Exit condition
if index <= end {
return
}
fmt.Println("Processing index ", index)
doForwardIteration(funcDecrementer(index), end, funcDecrementer)
}
func GridIterationViaRecursion(grid [][]int) [][]int {
var result [][]int = make([][]int, len(grid))
for i := range grid {
result[i] = make([]int, len(grid[0]))
}
return doGridIterationViaRecusion(grid, 0, 0, result)
}
func doGridIterationViaRecusion(grid [][]int, row int, col int, result [][]int) [][]int {
// If we reached last row, move to the next column and start from the first row
// Exit if we reached the last column
if row == len(grid) {
row = 0;
col = col + 1
if col == len(grid[0]) {
return result
}
}
result[row][col] = grid[row][col]
return doGridIterationViaRecusion(grid, row + 1, col, result)
}
|
package customers
import (
"net/http"
"outlet/v1/app/middleware/auth"
_request "outlet/v1/app/presenter/customers/request"
_response "outlet/v1/app/presenter/customers/response"
"outlet/v1/bussiness/customers"
"outlet/v1/helpers"
"strconv"
"github.com/labstack/echo/v4"
)
type Presenter struct {
serviceCustomer customers.Service
jwtAuth *auth.ConfigJWT
}
func NewHandler(customerService customers.Service, jwtauth *auth.ConfigJWT) *Presenter {
return &Presenter{
serviceCustomer: customerService,
jwtAuth: jwtauth,
}
}
func (handler *Presenter) AddCustomer(echoContext echo.Context) error {
var req _request.Customer
if err := echoContext.Bind(&req); err != nil {
response := helpers.APIResponse("Failed Add Customer", http.StatusBadRequest, "Error", nil)
return echoContext.JSON(http.StatusBadRequest, response)
}
domain := _request.ToDomain(req)
resp, err := handler.serviceCustomer.AddCustomer(domain)
if err != nil {
response := helpers.APIResponse("Failed Add Customer", http.StatusInternalServerError, "Error", nil)
return echoContext.JSON(http.StatusInternalServerError, response)
}
response := helpers.APIResponse("Success Add Customer", http.StatusOK, "Success", _response.FromDomain(*resp))
return echoContext.JSON(http.StatusOK, response)
}
func (handler *Presenter) Update(echoContext echo.Context) error {
var req _request.Customer
if err := echoContext.Bind(&req); err != nil {
response := helpers.APIResponse("Failed FindByEmail", http.StatusBadRequest, "Error", nil)
return echoContext.JSON(http.StatusBadRequest, response)
}
domain := _request.ToDomain(req)
customer := auth.GetCustomer(echoContext) // ID Get From JWT
customerID := customer.ID
resp, err := handler.serviceCustomer.Update(customerID, domain)
if err != nil {
response := helpers.APIResponse("Failed", http.StatusBadRequest, "Error", nil)
return echoContext.JSON(http.StatusBadRequest, response)
}
response := helpers.APIResponse("Success", http.StatusOK, "Success", _response.FromDomain(*resp))
return echoContext.JSON(http.StatusOK, response)
}
func (handler *Presenter) LoginUser(echoContext echo.Context) error {
var req _request.CustomerLogin
if err := echoContext.Bind(&req); err != nil {
response := helpers.APIResponse("Failed Login", http.StatusBadRequest, "Error", nil)
return echoContext.JSON(http.StatusBadRequest, response)
}
resp, err := handler.serviceCustomer.Login(req.Email, req.Password)
if err != nil {
response := helpers.APIResponse("Failed Login", http.StatusBadRequest, "Error", nil)
return echoContext.JSON(http.StatusBadRequest, response)
}
if err != nil {
response := helpers.APIResponse("Generate Token Failed", http.StatusBadRequest, "Error", nil)
return echoContext.JSON(http.StatusBadRequest, response)
}
response := helpers.APIResponse("Success Login", http.StatusOK, "Success", _response.CustomerLogin{Token: resp})
return echoContext.JSON(http.StatusOK, response)
}
func (handler *Presenter) FindByID(echoContext echo.Context) error {
id, err := strconv.Atoi(echoContext.Param("id"))
if err != nil {
response := helpers.APIResponse("Failed FindByEmail", http.StatusBadRequest, "Error", nil)
return echoContext.JSON(http.StatusBadRequest, response)
}
resp, err := handler.serviceCustomer.FindByID(id)
if err != nil {
response := helpers.APIResponse("Failed", http.StatusBadRequest, "Error", nil)
return echoContext.JSON(http.StatusBadRequest, response)
}
response := helpers.APIResponse("Success", http.StatusOK, "Success", _response.FromDomain(*resp))
return echoContext.JSON(http.StatusOK, response)
}
func (handler *Presenter) Delete(echoContext echo.Context) error {
var req _request.Customer
if err := echoContext.Bind(&req); err != nil {
response := helpers.APIResponse("Failed Delete Customer", http.StatusBadRequest, "Error", err)
return echoContext.JSON(http.StatusBadRequest, response)
}
id, err := strconv.Atoi(echoContext.Param("id"))
if err != nil {
response := helpers.APIResponse("Failed Delete Customer", http.StatusBadRequest, "Error", err)
return echoContext.JSON(http.StatusBadRequest, response)
}
domain := _request.ToDomain(req)
_, err = handler.serviceCustomer.DeleteCustomer(id, domain)
if err != nil {
response := helpers.APIResponse("Failed Delete Customer", http.StatusBadRequest, "Error", err)
return echoContext.JSON(http.StatusBadRequest, response)
}
response := helpers.APIResponse("Success", http.StatusOK, "Success", _response.Delete{Data: "Success Delete Customer"})
return echoContext.JSON(http.StatusOK, response)
}
func (handler *Presenter) GetAllCustomer(echoContext echo.Context) error {
resp, err := handler.serviceCustomer.GetAllCustomer()
if err != nil {
response := helpers.APIResponse("Failed Get All Customer", http.StatusBadRequest, "Error", err)
return echoContext.JSON(http.StatusBadRequest, response)
}
response := helpers.APIResponse("Success", http.StatusOK, "Success", _response.FromDomainArray(*resp))
return echoContext.JSON(http.StatusOK, response)
}
|
package tunnel
import (
"encoding/base64"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/urfave/cli/v2"
"github.com/cloudflare/cloudflared/cfapi"
"github.com/cloudflare/cloudflared/connection"
"github.com/cloudflare/cloudflared/credentials"
"github.com/cloudflare/cloudflared/logger"
)
type errInvalidJSONCredential struct {
err error
path string
}
func (e errInvalidJSONCredential) Error() string {
return "Invalid JSON when parsing tunnel credentials file"
}
// subcommandContext carries structs shared between subcommands, to reduce number of arguments needed to
// pass between subcommands, and make sure they are only initialized once
type subcommandContext struct {
c *cli.Context
log *zerolog.Logger
fs fileSystem
// These fields should be accessed using their respective Getter
tunnelstoreClient cfapi.Client
userCredential *credentials.User
}
func newSubcommandContext(c *cli.Context) (*subcommandContext, error) {
return &subcommandContext{
c: c,
log: logger.CreateLoggerFromContext(c, logger.EnableTerminalLog),
fs: realFileSystem{},
}, nil
}
// Returns something that can find the given tunnel's credentials file.
func (sc *subcommandContext) credentialFinder(tunnelID uuid.UUID) CredFinder {
if path := sc.c.String(CredFileFlag); path != "" {
return newStaticPath(path, sc.fs)
}
return newSearchByID(tunnelID, sc.c, sc.log, sc.fs)
}
func (sc *subcommandContext) client() (cfapi.Client, error) {
if sc.tunnelstoreClient != nil {
return sc.tunnelstoreClient, nil
}
cred, err := sc.credential()
if err != nil {
return nil, err
}
sc.tunnelstoreClient, err = cred.Client(sc.c.String("api-url"), buildInfo.UserAgent(), sc.log)
if err != nil {
return nil, err
}
return sc.tunnelstoreClient, nil
}
func (sc *subcommandContext) credential() (*credentials.User, error) {
if sc.userCredential == nil {
uc, err := credentials.Read(sc.c.String(credentials.OriginCertFlag), sc.log)
if err != nil {
return nil, err
}
sc.userCredential = uc
}
return sc.userCredential, nil
}
func (sc *subcommandContext) readTunnelCredentials(credFinder CredFinder) (connection.Credentials, error) {
filePath, err := credFinder.Path()
if err != nil {
return connection.Credentials{}, err
}
body, err := sc.fs.readFile(filePath)
if err != nil {
return connection.Credentials{}, errors.Wrapf(err, "couldn't read tunnel credentials from %v", filePath)
}
var credentials connection.Credentials
if err = json.Unmarshal(body, &credentials); err != nil {
if strings.HasSuffix(filePath, ".pem") {
return connection.Credentials{}, fmt.Errorf("The tunnel credentials file should be .json but you gave a .pem. " +
"The tunnel credentials file was originally created by `cloudflared tunnel create`. " +
"You may have accidentally used the filepath to cert.pem, which is generated by `cloudflared tunnel " +
"login`.")
}
return connection.Credentials{}, errInvalidJSONCredential{path: filePath, err: err}
}
return credentials, nil
}
func (sc *subcommandContext) create(name string, credentialsFilePath string, secret string) (*cfapi.Tunnel, error) {
client, err := sc.client()
if err != nil {
return nil, errors.Wrap(err, "couldn't create client to talk to Cloudflare Tunnel backend")
}
var tunnelSecret []byte
if secret == "" {
tunnelSecret, err = generateTunnelSecret()
if err != nil {
return nil, errors.Wrap(err, "couldn't generate the secret for your new tunnel")
}
} else {
decodedSecret, err := base64.StdEncoding.DecodeString(secret)
if err != nil {
return nil, errors.Wrap(err, "Couldn't decode tunnel secret from base64")
}
tunnelSecret = []byte(decodedSecret)
if len(tunnelSecret) < 32 {
return nil, errors.New("Decoded tunnel secret must be at least 32 bytes long")
}
}
tunnel, err := client.CreateTunnel(name, tunnelSecret)
if err != nil {
return nil, errors.Wrap(err, "Create Tunnel API call failed")
}
credential, err := sc.credential()
if err != nil {
return nil, err
}
tunnelCredentials := connection.Credentials{
AccountTag: credential.AccountID(),
TunnelSecret: tunnelSecret,
TunnelID: tunnel.ID,
}
usedCertPath := false
if credentialsFilePath == "" {
originCertDir := filepath.Dir(credential.CertPath())
credentialsFilePath, err = tunnelFilePath(tunnelCredentials.TunnelID, originCertDir)
if err != nil {
return nil, err
}
usedCertPath = true
}
writeFileErr := writeTunnelCredentials(credentialsFilePath, &tunnelCredentials)
if writeFileErr != nil {
var errorLines []string
errorLines = append(errorLines, fmt.Sprintf("Your tunnel '%v' was created with ID %v. However, cloudflared couldn't write tunnel credentials to %s.", tunnel.Name, tunnel.ID, credentialsFilePath))
errorLines = append(errorLines, fmt.Sprintf("The file-writing error is: %v", writeFileErr))
if deleteErr := client.DeleteTunnel(tunnel.ID); deleteErr != nil {
errorLines = append(errorLines, fmt.Sprintf("Cloudflared tried to delete the tunnel for you, but encountered an error. You should use `cloudflared tunnel delete %v` to delete the tunnel yourself, because the tunnel can't be run without the tunnelfile.", tunnel.ID))
errorLines = append(errorLines, fmt.Sprintf("The delete tunnel error is: %v", deleteErr))
} else {
errorLines = append(errorLines, fmt.Sprintf("The tunnel was deleted, because the tunnel can't be run without the credentials file"))
}
errorMsg := strings.Join(errorLines, "\n")
return nil, errors.New(errorMsg)
}
if outputFormat := sc.c.String(outputFormatFlag.Name); outputFormat != "" {
return nil, renderOutput(outputFormat, &tunnel)
}
fmt.Printf("Tunnel credentials written to %v.", credentialsFilePath)
if usedCertPath {
fmt.Print(" cloudflared chose this file based on where your origin certificate was found.")
}
fmt.Println(" Keep this file secret. To revoke these credentials, delete the tunnel.")
fmt.Printf("\nCreated tunnel %s with id %s\n", tunnel.Name, tunnel.ID)
return &tunnel.Tunnel, nil
}
func (sc *subcommandContext) list(filter *cfapi.TunnelFilter) ([]*cfapi.Tunnel, error) {
client, err := sc.client()
if err != nil {
return nil, err
}
return client.ListTunnels(filter)
}
func (sc *subcommandContext) delete(tunnelIDs []uuid.UUID) error {
forceFlagSet := sc.c.Bool("force")
client, err := sc.client()
if err != nil {
return err
}
for _, id := range tunnelIDs {
tunnel, err := client.GetTunnel(id)
if err != nil {
return errors.Wrapf(err, "Can't get tunnel information. Please check tunnel id: %s", id)
}
// Check if tunnel DeletedAt field has already been set
if !tunnel.DeletedAt.IsZero() {
return fmt.Errorf("Tunnel %s has already been deleted", tunnel.ID)
}
if forceFlagSet {
if err := client.CleanupConnections(tunnel.ID, cfapi.NewCleanupParams()); err != nil {
return errors.Wrapf(err, "Error cleaning up connections for tunnel %s", tunnel.ID)
}
}
if err := client.DeleteTunnel(tunnel.ID); err != nil {
return errors.Wrapf(err, "Error deleting tunnel %s", tunnel.ID)
}
credFinder := sc.credentialFinder(id)
if tunnelCredentialsPath, err := credFinder.Path(); err == nil {
if err = os.Remove(tunnelCredentialsPath); err != nil {
sc.log.Info().Msgf("Tunnel %v was deleted, but we could not remove its credentials file %s: %s. Consider deleting this file manually.", id, tunnelCredentialsPath, err)
}
}
}
return nil
}
// findCredentials will choose the right way to find the credentials file, find it,
// and add the TunnelID into any old credentials (generated before TUN-3581 added the `TunnelID`
// field to credentials files)
func (sc *subcommandContext) findCredentials(tunnelID uuid.UUID) (connection.Credentials, error) {
var credentials connection.Credentials
var err error
if credentialsContents := sc.c.String(CredContentsFlag); credentialsContents != "" {
if err = json.Unmarshal([]byte(credentialsContents), &credentials); err != nil {
err = errInvalidJSONCredential{path: "TUNNEL_CRED_CONTENTS", err: err}
}
} else {
credFinder := sc.credentialFinder(tunnelID)
credentials, err = sc.readTunnelCredentials(credFinder)
}
// This line ensures backwards compatibility with credentials files generated before
// TUN-3581. Those old credentials files don't have a TunnelID field, so we enrich the struct
// with the ID, which we have already resolved from the user input.
credentials.TunnelID = tunnelID
return credentials, err
}
func (sc *subcommandContext) run(tunnelID uuid.UUID) error {
credentials, err := sc.findCredentials(tunnelID)
if err != nil {
if e, ok := err.(errInvalidJSONCredential); ok {
sc.log.Error().Msgf("The credentials file at %s contained invalid JSON. This is probably caused by passing the wrong filepath. Reminder: the credentials file is a .json file created via `cloudflared tunnel create`.", e.path)
sc.log.Error().Msgf("Invalid JSON when parsing credentials file: %s", e.err.Error())
}
return err
}
return sc.runWithCredentials(credentials)
}
func (sc *subcommandContext) runWithCredentials(credentials connection.Credentials) error {
sc.log.Info().Str(LogFieldTunnelID, credentials.TunnelID.String()).Msg("Starting tunnel")
return StartServer(
sc.c,
buildInfo,
&connection.NamedTunnelProperties{Credentials: credentials},
sc.log,
)
}
func (sc *subcommandContext) cleanupConnections(tunnelIDs []uuid.UUID) error {
params := cfapi.NewCleanupParams()
extraLog := ""
if connector := sc.c.String("connector-id"); connector != "" {
connectorID, err := uuid.Parse(connector)
if err != nil {
return errors.Wrapf(err, "%s is not a valid client ID (must be a UUID)", connector)
}
params.ForClient(connectorID)
extraLog = fmt.Sprintf(" for connector-id %s", connectorID.String())
}
client, err := sc.client()
if err != nil {
return err
}
for _, tunnelID := range tunnelIDs {
sc.log.Info().Msgf("Cleanup connection for tunnel %s%s", tunnelID, extraLog)
if err := client.CleanupConnections(tunnelID, params); err != nil {
sc.log.Error().Msgf("Error cleaning up connections for tunnel %v, error :%v", tunnelID, err)
}
}
return nil
}
func (sc *subcommandContext) getTunnelTokenCredentials(tunnelID uuid.UUID) (*connection.TunnelToken, error) {
client, err := sc.client()
if err != nil {
return nil, err
}
token, err := client.GetTunnelToken(tunnelID)
if err != nil {
sc.log.Err(err).Msgf("Could not get the Token for the given Tunnel %v", tunnelID)
return nil, err
}
return ParseToken(token)
}
func (sc *subcommandContext) route(tunnelID uuid.UUID, r cfapi.HostnameRoute) (cfapi.HostnameRouteResult, error) {
client, err := sc.client()
if err != nil {
return nil, err
}
return client.RouteTunnel(tunnelID, r)
}
// Query Tunnelstore to find the active tunnel with the given name.
func (sc *subcommandContext) tunnelActive(name string) (*cfapi.Tunnel, bool, error) {
filter := cfapi.NewTunnelFilter()
filter.NoDeleted()
filter.ByName(name)
tunnels, err := sc.list(filter)
if err != nil {
return nil, false, err
}
if len(tunnels) == 0 {
return nil, false, nil
}
// There should only be 1 active tunnel for a given name
return tunnels[0], true, nil
}
// findID parses the input. If it's a UUID, return the UUID.
// Otherwise, assume it's a name, and look up the ID of that tunnel.
func (sc *subcommandContext) findID(input string) (uuid.UUID, error) {
if u, err := uuid.Parse(input); err == nil {
return u, nil
}
// Look up name in the credentials file.
credFinder := newStaticPath(sc.c.String(CredFileFlag), sc.fs)
if credentials, err := sc.readTunnelCredentials(credFinder); err == nil {
if credentials.TunnelID != uuid.Nil {
return credentials.TunnelID, nil
}
}
// Fall back to querying Tunnelstore.
if tunnel, found, err := sc.tunnelActive(input); err != nil {
return uuid.Nil, err
} else if found {
return tunnel.ID, nil
}
return uuid.Nil, fmt.Errorf("%s is neither the ID nor the name of any of your tunnels", input)
}
// findIDs is just like mapping `findID` over a slice, but it only uses
// one Tunnelstore API call per non-UUID input provided.
func (sc *subcommandContext) findIDs(inputs []string) ([]uuid.UUID, error) {
uuids, names := splitUuids(inputs)
for _, name := range names {
filter := cfapi.NewTunnelFilter()
filter.NoDeleted()
filter.ByName(name)
tunnels, err := sc.list(filter)
if err != nil {
return nil, err
}
if len(tunnels) != 1 {
return nil, fmt.Errorf("there should only be 1 non-deleted Tunnel named %s", name)
}
uuids = append(uuids, tunnels[0].ID)
}
return uuids, nil
}
func splitUuids(inputs []string) ([]uuid.UUID, []string) {
uuids := make([]uuid.UUID, 0)
names := make([]string, 0)
for _, input := range inputs {
id, err := uuid.Parse(input)
if err != nil {
names = append(names, input)
} else {
uuids = append(uuids, id)
}
}
return uuids, names
}
|
package strings
import(
"rediproxy/base"
)
func (t *Strings) DEL(key string) (r int32, err error){
c := base.RedisClient.Get()
defer c.Close()
_, err = c.Do("DEL", key)
return
}
|
package dynamo
import (
"fmt"
"net/http"
"strconv"
"github.com/Sirupsen/logrus"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
"github.com/aws/aws-sdk-go/service/dynamodb/expression"
"github.com/kosegor/go-covid19-api/app/domain/model"
"github.com/kosegor/go-covid19-api/app/interface/apierr"
)
const (
IncidentTable = "Incident"
IdsTable = "Ids"
)
type dynamoRepository struct {
service *dynamodb.DynamoDB
}
func NewIncidentRepository() *dynamoRepository {
return &dynamoRepository{
service: NewDynamoService(),
}
}
func (i *dynamoRepository) Insert(incident *model.Incident) *apierr.ApiError {
if incident.ID == "" {
id, _ := i.getId()
id.ID++
incident.ID = strconv.Itoa(id.ID)
i.updateId(id)
}
err := insert(i.service, incident)
return err
}
func (i *dynamoRepository) getId() (*model.Id, *apierr.ApiError) {
id := &model.Id{}
filt := expression.Name("table").Equal(expression.Value(IncidentTable))
proj := expression.NamesList(expression.Name("table"), expression.Name("id"))
expr, err := expression.NewBuilder().WithFilter(filt).WithProjection(proj).Build()
if err != nil {
return nil, apierr.NewApiError(err.Error(), http.StatusInternalServerError)
}
params := &dynamodb.ScanInput{
ExpressionAttributeNames: expr.Names(),
ExpressionAttributeValues: expr.Values(),
FilterExpression: expr.Filter(),
ProjectionExpression: expr.Projection(),
TableName: aws.String(IdsTable),
}
result, err := i.service.Scan(params)
if err != nil {
return nil, apierr.NewApiError(err.Error(), http.StatusInternalServerError)
}
err = dynamodbattribute.UnmarshalMap(result.Items[0], id)
if err != nil {
return nil, apierr.NewApiError(err.Error(), http.StatusInternalServerError)
}
return id, nil
}
func (i *dynamoRepository) updateId(id *model.Id) *apierr.ApiError {
av, err := dynamodbattribute.MarshalMap(id)
input := &dynamodb.PutItemInput{
Item: av,
TableName: aws.String(IdsTable),
}
_, err = i.service.PutItem(input)
if err != nil {
logrus.Error(fmt.Errorf("Table %s: saving id failed. Error: %s", id.Table, err.Error()))
return apierr.NewApiError(err.Error(), http.StatusInternalServerError)
}
return nil
}
func insert(svc dynamodbiface.DynamoDBAPI, incident *model.Incident) *apierr.ApiError {
av, err := dynamodbattribute.MarshalMap(incident)
input := &dynamodb.PutItemInput{
Item: av,
TableName: aws.String(IncidentTable),
}
_, err = svc.PutItem(input)
if err != nil {
logrus.Error(fmt.Errorf("ID %d: saving incident failed. Error: %s", incident.ID, err.Error()))
return apierr.NewApiError(err.Error(), http.StatusInternalServerError)
}
return nil
}
func (i *dynamoRepository) FindAll() ([]*model.Incident, *apierr.ApiError) {
return findAll(i.service)
}
func findAll(svc dynamodbiface.DynamoDBAPI) ([]*model.Incident, *apierr.ApiError) {
proj := expression.NamesList(expression.Name("id"), expression.Name("name"), expression.Name("surname"), expression.Name("latitude"), expression.Name("longitude"), expression.Name("country"), expression.Name("country_of_residence"), expression.Name("date"))
expr, err := expression.NewBuilder().WithProjection(proj).Build()
if err != nil {
return nil, apierr.NewApiError(err.Error(), http.StatusInternalServerError)
}
params := &dynamodb.ScanInput{
ExpressionAttributeNames: expr.Names(),
ExpressionAttributeValues: expr.Values(),
ProjectionExpression: expr.Projection(),
TableName: aws.String(IncidentTable),
}
result, err := svc.Scan(params)
if err != nil {
return nil, apierr.NewApiError(err.Error(), http.StatusInternalServerError)
}
incidents := make([]*model.Incident, len(result.Items))
for x, i := range result.Items {
incident := &model.Incident{}
err = dynamodbattribute.UnmarshalMap(i, incident)
if err != nil {
return nil, apierr.NewApiError(err.Error(), http.StatusInternalServerError)
}
incidents[x] = incident
}
return incidents, nil
}
|
package datetime
import (
"testing"
"github.com/project-flogo/core/data/expression/function"
"github.com/stretchr/testify/assert"
)
func init() {
function.ResolveAliases()
}
func TestCurrentDatetime_Eval(t *testing.T) {
n := CurrentDatetime{}
datetime, _ := n.Eval(nil)
assert.NotNil(t, datetime)
}
func TestDatetime_CDT(t *testing.T) {
n := CurrentDatetime{}
date, _ := n.Eval(nil)
assert.NotNil(t, date)
}
|
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"runtime"
"strings"
"github.com/disintegration/imaging"
)
func resize(src string, status chan int) {
if strings.HasSuffix(src, ".jpg") || strings.HasSuffix(src, ".JPG") {
f, err := imaging.Open(src)
if err != nil {
log.Println("Open file fail! ", src)
return
}
fSize1, _ := os.Stat(src)
width := f.Bounds().Dx()
if width > 4000 {
width = 4000
}
outf := imaging.Resize(f, width, 0, imaging.Lanczos)
os.Remove(src)
imaging.Save(outf, src, imaging.JPEGQuality(80))
fSize2, _ := os.Stat(src)
fmt.Printf("%v\t Before: %vKb\t After: %vKb.\n", src, fSize1.Size()/(1<<10), fSize2.Size()/(1<<10))
status <- 1
}
}
func distribut(file string, status chan int) {
<-status
go resize(file, status)
}
func main() {
//Init start flag
cpus := runtime.NumCPU()
runtime.GOMAXPROCS(cpus)
fmt.Printf("Now start Processing...The number of CPU is %v\n", cpus)
status := make(chan int, cpus)
for i := 0; i < cpus; i++ {
status <- 1
}
err := os.Chdir(os.Args[1])
if err != nil {
log.Fatal(err)
}
files, err := ioutil.ReadDir(os.Args[1])
if err != nil {
log.Fatal(err)
}
for _, v := range files {
distribut(v.Name(), status)
}
fmt.Println("Done!")
}
|
package entities
import (
"github.com/google/uuid"
"time"
)
type Account struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
CPF string `json:"cpf"`
Secret string `json:"secret"`
Balance int `json:"balance"`
CreatedAt time.Time `json:"created_at"`
}
|
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func parseInput(in string) []int {
arrayStr := strings.SplitN(in, " ", -1)
var array = []int{}
for _, i := range arrayStr {
j, err := strconv.Atoi(i)
if err != nil {
panic(err)
}
array = append(array, j)
}
return array
}
func toString(array []int) string {
var arrayStr = []string{}
for _, i := range array {
j := strconv.Itoa(i)
arrayStr = append(arrayStr, j)
}
return strings.Join(arrayStr, " ")
}
func bubbleSort(array []int) {
for {
swapped := false
for i := 0; i < len(array)-1; i++ {
if array[i] > array[i+1] {
tmp := array[i]
array[i] = array[i+1]
array[i+1] = tmp
swapped = true
}
}
if !swapped {
break
}
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
in := scanner.Text()
array := parseInput(in)
bubbleSort(array)
fmt.Println(toString(array))
}
|
//go:generate go run pkg/codegen/cleanup/main.go
//go:generate go run pkg/codegen/main.go
//go:generate go run main.go --write-crds ./charts/rancher-operator-crd/templates/crds.yaml
package main
import (
"context"
"fmt"
"os"
"github.com/rancher/rancher-operator/pkg/controllers"
"github.com/rancher/rancher-operator/pkg/crd"
"github.com/rancher/wrangler/pkg/kubeconfig"
"github.com/rancher/wrangler/pkg/signals"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
_ "github.com/rancher/wrangler/pkg/generated/controllers/apiextensions.k8s.io/v1beta1"
)
var (
Version = "v0.0.0-dev"
GitCommit = "HEAD"
KubeConfig string
Context string
WriteCRDs string
)
func main() {
app := cli.NewApp()
app.Name = "rancher"
app.Version = fmt.Sprintf("%s (%s)", Version, GitCommit)
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "kubeconfig",
EnvVar: "KUBECONFIG",
Destination: &KubeConfig,
},
cli.StringFlag{
Name: "context",
EnvVar: "CONTEXT",
Destination: &Context,
},
cli.StringFlag{
Name: "write-crds",
Destination: &WriteCRDs,
},
}
app.Action = run
if err := app.Run(os.Args); err != nil {
logrus.Fatal(err)
}
}
func run(c *cli.Context) error {
if WriteCRDs != "" {
logrus.Info("Writing CRDS to ", WriteCRDs)
return crd.WriteFile(WriteCRDs)
}
logrus.Info("Starting controller")
ctx := signals.SetupSignalHandler(context.Background())
clientConfig := kubeconfig.GetNonInteractiveClientConfigWithContext(KubeConfig, Context)
if err := controllers.Register(ctx, "", clientConfig); err != nil {
return err
}
<-ctx.Done()
return nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.