text stringlengths 11 4.05M |
|---|
package main
import (
"./BLC"
)
func main() {
//bc := BLC.CreatBlockChain()
//bc.AddBlock("Block1 : 100PHB")
//bc.AddBlock("Block2 : 200PHB")
//bc.VisitBlockChain()
cli := BLC.CLI{}
cli.Run()
}
|
package db
import (
"fmt"
"github.com/trongtb88/rateservice/api/models"
"gorm.io/driver/mysql"
"log"
_ "gorm.io/driver/mysql"
"gorm.io/gorm"
)
type Conn struct {
DB *gorm.DB
}
func Initialize(Dbdriver, DbUser, DbPassword, DbPort, DbHost, DbName string) *gorm.DB {
var (
db *gorm.DB
err error
)
if Dbdriver == "mysql" {
DBURL := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", DbUser, DbPassword, DbHost, DbPort, DbName)
db, err = gorm.Open(mysql.Open(DBURL))
if err != nil {
fmt.Printf("Cannot connect to %s database", Dbdriver)
log.Fatal("This is the error:", err)
} else {
fmt.Printf("We are connected to the %s database", Dbdriver)
}
}
err = db.Debug().AutoMigrate(&models.CurrencyRate{}) //database migration
if err != nil {
log.Fatal("Error when migration table:", err)
}
return db
}
|
package domain
import (
"time"
"github.com/pkg/errors"
)
// Challenge ...
type Challenge struct {
AccountID ID `json:"account_id" db:"account_id"`
ID ID `json:"id" db:"id"`
ForUserID ID `json:"for_user_id" db:"for_user_id"`
Status Status `json:"status" db:"status"`
Details ChallengeDetails `json:"details" db:"details"`
CreatedByUserID ID `json:"created_by_user_id" db:"created_by_user_id"`
ExpiresAt *time.Time `json:"expires_at" db:"expires_at"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt *time.Time `json:"updated_at" db:"updated_at"`
}
type NewChallengeArgs struct {
AccountID ID
ForUserID ID
CreatedByUserID ID
Tasks []*Task
}
// NewChallenge ...
func NewChallenge(a NewChallengeArgs) (*Challenge, error) {
if a.AccountID == "" {
return nil, errors.Errorf("missing account_id arg")
}
if a.ForUserID == "" {
return nil, errors.Errorf("missing for_user_id arg")
}
if a.CreatedByUserID == "" {
return nil, errors.Errorf("missing created_by_user_id arg")
}
if len(a.Tasks) == 0 {
return nil, errors.Errorf("missing tasks arg")
}
c := &Challenge{
AccountID: a.AccountID,
ID: NewID(),
ForUserID: a.ForUserID,
CreatedByUserID: a.CreatedByUserID,
Details: ChallengeDetails{
Tasks: a.Tasks,
},
CreatedAt: time.Now(),
}
return c, nil
}
// ChallengeDetails ...
type ChallengeDetails struct {
Tasks []*Task `json:"tasks"`
}
// ChallengeDAO ...
type ChallengeDAO interface {
Create(u *Challenge) error
Get(accountID, id ID) (*Challenge, error)
GetAll(accountID ID, ids []ID) ([]*Challenge, error)
Update(accountID ID, id ID, updates []Field) (*Challenge, error)
}
|
package main
import (
"bytes"
"encoding/json"
"flag"
"io/ioutil"
"log"
"net/http"
"github.com/go-chi/chi"
"github.com/rastasi/go-messenger-bot/models"
)
const (
verifyToken = "goforever"
pageAccessToken = "EAACChyvB7ZCMBAPXK1i9VDFJyPdEEArsMuAuGNFsuCvfe9Sp6LCX21Rkmii580x25GKUVrEYQkx7BDPdOgnibTt9I9jIx4uIgduUbaafmkmiBGn01KxhIU8yKaXjpBQfRZBDhmy2oiP1wsqh0CKgoDZCj6LEGI5mVD3BcZBtBAZDZD"
messagesURL = "https://graph.facebook.com/v2.6/me/messages"
)
var (
address string
)
func init() {
flag.StringVar(&address, "address", ":3000", "")
flag.Parse()
}
func main() {
router := chi.NewRouter()
router.Get("/webhook", getWebhook)
router.Post("/webhook", postWebhook)
log.Printf("Listening on %s", address)
log.Fatal(http.ListenAndServe(address, router))
}
func getWebhook(w http.ResponseWriter, r *http.Request) {
mode := r.URL.Query().Get("hub.mode")
token := r.URL.Query().Get("hub.verify_token")
challenge := r.URL.Query().Get("hub.challenge")
if mode != "" && token != "" {
if mode == "subscribe" && token == verifyToken {
w.Write([]byte(challenge))
} else {
w.Write([]byte("Forbidden"))
}
}
}
func getJSONResponse(response models.Response) []byte {
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Print(err)
}
return jsonResponse
}
func sendResponse(senderID string, text string) {
response := models.Response{Recipient: models.Participant{Id: senderID}, Message: models.Message{Text: text}}
jsonResponse := getJSONResponse(response)
request, err := http.NewRequest("POST", messagesURL, bytes.NewBuffer(jsonResponse))
request.Header.Set("Content-Type", "application/json")
request.URL.Query().Add("access_token", pageAccessToken)
client := &http.Client{}
resp, err := client.Do(request)
if err != nil {
log.Print(err)
}
defer resp.Body.Close()
}
func getBody(w http.ResponseWriter, r *http.Request) []byte {
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
http.Error(w, err.Error(), 500)
}
return body
}
func getAnswer(w http.ResponseWriter, body []byte) models.Answer {
var answer models.Answer
err := json.Unmarshal(body, &answer)
if err != nil {
http.Error(w, err.Error(), 500)
}
return answer
}
func getResponseText(input string) string {
switch input {
case "hello":
return "hello!"
case "help":
return "Can I help you?"
case "contact":
return "www.aiventure.me"
}
return "Sorry, I don't undersand."
}
func postWebhook(w http.ResponseWriter, r *http.Request) {
body := getBody(w, r)
answer := getAnswer(w, body)
if answer.Object == "page" {
event := answer.Entry[0].Messaging[0]
if event.Message.Text != "" {
senderID := event.Sender.Id
text := getResponseText(event.Message.Text)
sendResponse(senderID, text)
}
}
w.Write([]byte("EVENT_RECEIVED"))
}
|
package main
type RequestType int
var (
MSG_REGISTER = RequestType(0)
MSG_SEND = RequestType(1)
MSG_GET = RequestType(2)
)
type Request struct {
Type RequestType `json:"type"`
Name *string `json:"name"`
Text *string `json:"text"`
}
func NewRegisterRequest(name string) Request {
return Request{
Type: MSG_REGISTER,
Name: &name,
}
}
func NewSendRequest(name, text string) Request {
return Request{
Type: MSG_SEND,
Name: &name,
Text: &text,
}
}
func NewGetRequest() Request {
return Request{
Type: MSG_GET,
}
}
type Reply struct {
Ok bool `json:"ok"`
Error *string `json:"error"`
Messages []Message `json:"messages"`
}
type Message struct {
Name string `json:"name"`
Text string `json:"text"`
} |
package handlers
import (
"fmt"
"net/http"
)
func RootHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
errorHandler(w, r, http.StatusNotFound)
return
}
fmt.Fprintln(w, "Welcome to server")
}
func errorHandler(w http.ResponseWriter, r *http.Request, status int) {
w.WriteHeader(status)
if status == http.StatusNotFound {
fmt.Fprint(w, "This url is not defined. Status 404 returned. ")
}
}
|
package main
import (
"log"
"net/http"
"strconv"
"time"
"fcm-app-server/models"
"fcm-app-server/redis"
sq "github.com/Masterminds/squirrel"
)
func v1SmsHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
log.Println("Error parsing form data", err)
return
}
log.Println(r.Header.Get("content-type"))
log.Println(r.PostForm)
timestampMS, err := strconv.Atoi(r.PostForm.Get("date"))
timestamp := time.Unix(0, int64(timestampMS)*int64(time.Millisecond))
if err != nil {
log.Printf("Error parsing timestamp from %s", r.PostForm.Get("date"))
timestamp = time.Now()
}
id, err := strconv.Atoi(r.PostForm.Get("id"))
if err != nil {
log.Printf("Error parsing sms ID type from %s", r.PostForm.Get("id"))
id = 0
}
smsType, err := strconv.Atoi(r.PostForm.Get("type"))
if err != nil {
log.Printf("Error parsing sms type from %s", r.PostForm.Get("type"))
smsType = 0
}
sms := &models.Sms{
Address: r.PostForm.Get("address"),
Body: r.PostForm.Get("body"),
Date: timestamp,
ID: int64(id),
ThreadID: r.PostForm.Get("threadId"),
SmsType: smsType,
}
log.Println("Writing sms:", sms)
sql, args, err := sq.Insert("sms").Columns(
"address",
"body",
"date",
"sms_id",
"thread_id",
"type",
).
Values(
sms.Address,
sms.Body,
sms.Date.Format(time.RFC3339),
sms.ID,
sms.ThreadID,
sms.SmsType,
).ToSql()
if err != nil {
log.Println("Error generating SQL", err)
return
}
start := time.Now()
res, err := dbClient.Exec(sql, args...)
if err != nil {
ddClient.Incr("mysql.insert_sms.error", nil, 1.0)
log.Println("Error excecuting SQL", err)
return
}
ddClient.HistogramMS("mysql.insert_sms.latency_ms", start, nil, ddSampleRate)
rowsAffected, err := res.RowsAffected()
log.Printf("Executed successfully! Inserted %d rows", rowsAffected)
}
func v1MmsHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
log.Println("Error parsing form data", err)
return
}
log.Println(r.PostForm)
timestampMS, err := strconv.Atoi(r.PostForm.Get("date"))
timestamp := time.Unix(0, int64(timestampMS)*int64(time.Millisecond))
if err != nil {
log.Printf("Error parsing timestamp from %s", r.PostForm.Get("date"))
timestamp = time.Now()
}
id, err := strconv.Atoi(r.PostForm.Get("id"))
if err != nil {
log.Printf("Error parsing mms ID type from %s", r.PostForm.Get("id"))
id = 0
}
threadID, err := strconv.Atoi(r.PostForm.Get("threadId"))
if err != nil {
log.Printf("Error parsing threadId from %s", r.PostForm.Get("threadId"))
threadID = 0
}
mms := &models.Mms{
Addresses: r.PostForm.Get("addresses"),
Attachment: []byte(r.PostForm.Get("attachment")),
Body: r.PostForm.Get("body"),
ContentType: r.PostForm.Get("contentType"),
Date: timestamp,
ID: int64(id),
ThreadID: threadID,
}
log.Println("Writing mms:", mms)
sql, args, err := sq.Insert("mms").Columns(
"addresses",
"attachment",
"body",
"content_type",
"date",
"mms_id",
"thread_id",
).
Values(
mms.Addresses,
mms.Attachment,
mms.Body,
mms.ContentType,
mms.Date.Format(time.RFC3339),
mms.ID,
mms.ThreadID,
).ToSql()
if err != nil {
log.Println("Error generating SQL", err)
return
}
start := time.Now()
res, err := dbClient.Exec(sql, args...)
if err != nil {
ddClient.Incr("mysql.insert_mms.error", nil, 1.0)
log.Println("Error excecuting SQL", err)
return
}
ddClient.HistogramMS("mysql.insert_mms.latency_ms", start, nil, ddSampleRate)
rowsAffected, err := res.RowsAffected()
log.Printf("Executed successfully! Inserted %d rows", rowsAffected)
}
func v1MessageHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
log.Println("Error parsing form data", err)
return
}
log.Println(r.PostForm)
timestampMS, err := strconv.Atoi(r.PostForm.Get("date"))
timestamp := time.Unix(0, int64(timestampMS)*int64(time.Millisecond))
if err != nil {
log.Printf("Error parsing timestamp from %s", r.PostForm.Get("date"))
timestamp = time.Now()
}
threadID, err := strconv.Atoi(r.PostForm.Get("threadId"))
if err != nil {
log.Printf("Error parsing threadId from %s", r.PostForm.Get("threadId"))
threadID = 0
}
messageType, err := strconv.Atoi(r.PostForm.Get("type"))
if err != nil {
log.Printf("Error parsing message type from %s", r.PostForm.Get("type"))
messageType = 0
}
sender, err := strconv.Atoi(r.PostForm.Get("sender"))
if err != nil {
log.Printf("Error parsing sender from %s", r.PostForm.Get("sender"))
sender = 0
}
message := &models.Message{
Attachment: r.PostForm.Get("attachment"),
Body: r.PostForm.Get("body"),
ContentType: r.PostForm.Get("contentType"),
Date: timestamp,
Sender: int64(sender),
ThreadID: threadID,
Type: messageType,
}
log.Println("Writing message:", message)
err = redis.AddMessage(message)
if err != nil {
log.Println("Error writing to Redis", err)
return
}
sql, args, err := sq.Insert("messages").Columns(
"attachment",
"body",
"content_type",
"date",
"sender",
"thread_id",
"type",
).
Values(
message.Attachment,
message.Body,
message.ContentType,
message.Date.Format(time.RFC3339),
message.Sender,
message.ThreadID,
message.Type,
).ToSql()
if err != nil {
log.Println("Error generating SQL", err)
return
}
start := time.Now()
res, err := dbClient.Exec(sql, args...)
if err != nil {
ddClient.Incr("mysql.insert_message.error", nil, 1.0)
log.Println("Error excecuting SQL", err)
return
}
ddClient.HistogramMS("mysql.insert_message.latency_ms", start, nil, ddSampleRate)
rowsAffected, err := res.RowsAffected()
log.Printf("Executed successfully! Inserted %d rows", rowsAffected)
jsonResponse(w, message, http.StatusOK)
}
|
package ravendb
import (
"net/http"
)
var (
_ IMaintenanceOperation = &PutConnectionStringOperation{}
)
type PutConnectionStringOperation struct {
connectionString interface{}
Command *PutConnectionStringCommand
}
func NewPutConnectionStringOperation(connectionString interface{}) *PutConnectionStringOperation {
return &PutConnectionStringOperation{
connectionString: connectionString,
}
}
func (o *PutConnectionStringOperation) GetCommand(conventions *DocumentConventions) (RavenCommand, error) {
o.Command = NewPutConnectionStringCommand(o.connectionString)
return o.Command, nil
}
var _ RavenCommand = &PutConnectionStringCommand{}
type PutConnectionStringCommand struct {
RavenCommandBase
connectionString interface{}
Result *PutConnectionStringResult
}
// connectionString should be ConnectionString or RavenConnectionString
func NewPutConnectionStringCommand(connectionString interface{}) *PutConnectionStringCommand {
return &PutConnectionStringCommand{
RavenCommandBase: NewRavenCommandBase(),
connectionString: connectionString,
}
}
func (c *PutConnectionStringCommand) CreateRequest(node *ServerNode) (*http.Request, error) {
url := node.URL + "/databases/" + node.Database + "/admin/connection-strings"
d, err := jsonMarshal(c.connectionString)
if err != nil {
// TODO: change err into RuntimeError() ?
return nil, err
}
return newHttpPut(url, d)
}
func (c *PutConnectionStringCommand) SetResponse(response []byte, fromCache bool) error {
if len(response) == 0 {
return throwInvalidResponse()
}
return jsonUnmarshal(response, &c.Result)
}
|
package main
import (
"github.com/micro/go-log"
"github.com/micro/go-micro"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/server"
httpClient "github.com/hb-go/micro-plugins/client/istio_http"
httpServer "github.com/hb-go/micro-plugins/server/istio_http"
"github.com/hb-go/micro/istio/http/srv/handler"
example "github.com/hb-go/micro/istio/http/srv/proto/example"
"github.com/micro/go-plugins/registry/noop"
)
func main() {
c := httpClient.NewClient(
client.ContentType("application/json"),
)
s := httpServer.NewServer(
server.Address("localhost:8082"),
)
// New Service
service := micro.NewService(
micro.Name("go.micro.srv.test"),
micro.Version("latest"),
micro.Registry(noop.NewRegistry()),
micro.Client(c),
micro.Server(s),
)
// Register Handler
example.RegisterExampleHandler(service.Server(), new(handler.Example))
// Register Struct as Subscriber
//micro.RegisterSubscriber("topic.go.micro.srv.http", service.Server(), new(subscriber.Example))
// Register Function as Subscriber
//micro.RegisterSubscriber("topic.go.micro.srv.http", service.Server(), subscriber.Handler)
// Initialise service
service.Init()
// Run service
if err := service.Run(); err != nil {
log.Fatal(err)
}
}
|
package Intersection_of_Two_Arrays
import "sort"
func intersection(nums1 []int, nums2 []int) []int {
var result []int
var isSame = make(map[int]bool)
for _, v := range nums1 {
isSame[v] = true
}
for k, v := range nums2 {
if isSame[v] {
result = append(result, nums2[k])
isSame[v] = false
}
}
return result
}
func intersection2(nums1 []int, nums2 []int) []int {
sort.Ints(nums1)
sort.Ints(nums2)
var result []int
var p, q = 0, 0
for p < len(nums1) && q < len(nums2) {
if p > 0 && nums1[p] == nums1[p-1] {
p++
continue
}
if q > 0 && nums2[q] == nums2[q-1] {
q++
continue
}
if nums1[p] == nums2[q] {
result = append(result, nums1[p])
p++
q++
continue
}
if nums1[p] < nums2[q] {
p++
continue
}
q++
}
return result
}
|
// KAMİL KAPLAN
package test
import (
"encoding/json"
"github.com/icobani/goweather"
"io/ioutil"
"log"
"testing"
)
func TestForeCast(t *testing.T) {
apiKey := "Dl8ehKD1lCgL0GT6WCkGfRh9NtSn5GMO"
c := goweather.NewClient(nil, apiKey)
var code string = "325236"
// Daha önce aranan code var ise onu code'a göre dosyaya kaydediyor. Eğer yok ise aranan
// code.json dosyası oluşturuyor.
files, err := ioutil.ReadDir("./")
if err != nil {
log.Fatal(err)
}
fileName := code + ".json";
for _, f := range files {
if f.Name() == fileName {
data, err := ioutil.ReadFile(fileName)
if err != nil {
log.Fatal(err)
}
log.Println(string(data))
return
} else {
response, _, err := c.Forecast.GetForeCast(code)
if err != nil {
log.Fatal(err)
}
json_bytelar, _ := json.Marshal(response)
err2 := ioutil.WriteFile(fileName, json_bytelar, 0777)
if err2 != nil {
// print it out
log.Fatal(err2)
}
log.Println(response)
}
}
}
|
/*
Copyright 2018 The Kubernetes 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 main
import (
"flag"
"net/http"
"net/http/pprof"
"os"
"time"
"k8s.io/apimachinery/pkg/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
"k8s.io/klog"
"k8s.io/klog/klogr"
bootstrapv1 "sigs.k8s.io/cluster-api-bootstrap-provider-kubeadm/api/v1alpha2"
clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha2"
ctrl "sigs.k8s.io/controller-runtime"
// +kubebuilder:scaffold:imports
infrav1 "sigs.k8s.io/cluster-api-provider-vsphere/api/v1alpha2"
"sigs.k8s.io/cluster-api-provider-vsphere/controllers"
"sigs.k8s.io/cluster-api-provider-vsphere/pkg/cloud/vsphere/config"
"sigs.k8s.io/cluster-api-provider-vsphere/pkg/record"
)
const (
profilerAddrEnvVar = "PROFILER_ADDR"
syncPeriodEnvVar = "SYNC_PERIOD"
requeuePeriodEnvVar = "REQUEUE_PERIOD"
)
var (
defaultProfilerAddr = os.Getenv(profilerAddrEnvVar)
defaultSyncPeriod = 10 * time.Minute
defaultRequeuePeriod = 20 * time.Second
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
)
func init() {
_ = clientgoscheme.AddToScheme(scheme)
_ = infrav1.AddToScheme(scheme)
_ = clusterv1.AddToScheme(scheme)
_ = bootstrapv1.AddToScheme(scheme)
// +kubebuilder:scaffold:scheme
if v, err := time.ParseDuration(os.Getenv(syncPeriodEnvVar)); err == nil {
defaultSyncPeriod = v
}
if v, err := time.ParseDuration(os.Getenv(requeuePeriodEnvVar)); err == nil {
defaultRequeuePeriod = v
}
}
func main() {
klog.InitFlags(nil)
var metricsAddr string
var enableLeaderElection bool
flag.StringVar(&metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.")
flag.BoolVar(&enableLeaderElection, "enable-leader-election", false,
"Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager.")
watchNamespace := flag.String("namespace", "",
"Namespace that the controller watches to reconcile cluster-api objects. If unspecified, the controller watches for cluster-api objects across all namespaces.")
profilerAddress := flag.String(
"profiler-address", defaultProfilerAddr,
"Bind address to expose the pprof profiler")
syncPeriod := flag.Duration("sync-period", defaultSyncPeriod,
"The interval at which cluster-api objects are synchronized")
flag.DurationVar(&config.DefaultRequeue, "requeue-period", defaultRequeuePeriod,
"The default amount of time to wait before an operation is requeued.")
flag.Parse()
if *watchNamespace != "" {
setupLog.Info("Watching cluster-api objects only in namespace for reconciliation", "namespace", *watchNamespace)
}
if *profilerAddress != "" {
setupLog.Info("Profiler listening for requests", "profiler-address", *profilerAddress)
go runProfiler(*profilerAddress)
}
ctrl.SetLogger(klogr.New())
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
LeaderElection: enableLeaderElection,
SyncPeriod: syncPeriod,
Namespace: *watchNamespace,
})
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
// Initialize event recorder.
record.InitFromRecorder(mgr.GetEventRecorderFor("vsphere-controller"))
if err = (&controllers.VSphereMachineReconciler{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("controllers").WithName("VSphereMachine"),
Recorder: mgr.GetEventRecorderFor("vspheremachine-controller"),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "VSphereMachine")
os.Exit(1)
}
if err = (&controllers.VSphereClusterReconciler{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("controllers").WithName("VSphereCluster"),
Recorder: mgr.GetEventRecorderFor("vspherecluster-controller"),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "VSphereCluster")
os.Exit(1)
}
// +kubebuilder:scaffold:builder
setupLog.Info("starting manager")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
setupLog.Error(err, "problem running manager")
os.Exit(1)
}
}
func runProfiler(addr string) {
mux := http.NewServeMux()
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
http.ListenAndServe(addr, mux)
}
|
package utils
//#region Header
import (
mod "../models"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"net/http"
"os"
"strconv"
"time"
)
const (
GITHUB_ENDPOINT string = "https://api.github.com"
USER_AGENT string = "Dmitriy-Vas/go-discord-bot"
MEDIA_TYPE string = "application/vnd.github.v3+json"
SUCCESS int = 200
NOT_FOUND int = 404
SYS_ERROR int = 0
)
var (
client = &http.Client{
Transport: &http.Transport{
MaxIdleConns: 10,
MaxIdleConnsPerHost: 5,
MaxConnsPerHost: 5,
},
Timeout: time.Second * 15,
}
)
//#endregion
func send(method string, url *mod.URL) ([]byte, int) {
token := os.Getenv("GITHUB")
if len(token) == 0 {
return nil, SYS_ERROR
}
request, _ := http.NewRequest(method, url.Link, nil)
q := request.URL.Query()
for key, value := range url.Queries {
q.Add(key, value)
}
request.URL.RawQuery = q.Encode()
request.Header.Add("Authorization", "token "+token)
request.Header.Add("Accept", MEDIA_TYPE)
request.Header.Add("User-Agent", USER_AGENT)
response, err := client.Do(request)
if err != nil {
fmt.Println(err)
return nil, SYS_ERROR
}
defer response.Body.Close()
data, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err)
return nil, SYS_ERROR
}
return data, response.StatusCode
}
func get(url *mod.URL) ([]byte, int) {
return send(http.MethodGet, url)
}
func put(url *mod.URL) ([]byte, int) {
return send(http.MethodPut, url)
}
func del(url *mod.URL) ([]byte, int) {
return send(http.MethodDelete, url)
}
func User(name string) (*mod.User, int) {
data, status := get(&mod.URL{Link: GITHUB_ENDPOINT + "/users/" + name, Queries: nil})
switch status {
case NOT_FOUND:
case SYS_ERROR:
return nil, status
}
var user *mod.User
err := json.Unmarshal(data, &user)
if err != nil {
return nil, SYS_ERROR
}
return user, SUCCESS
}
func Projects(name string, page int) ([]*mod.Project, int) {
queries := make(map[string]string)
queries["per_page"] = "100"
queries["page"] = strconv.Itoa(page)
data, status := get(&mod.URL{Link: GITHUB_ENDPOINT + "/users/" + name + "/repos", Queries: queries})
switch status {
case NOT_FOUND:
case SYS_ERROR:
return nil, status
}
var projects []*mod.Project
err := json.Unmarshal(data, &projects)
if err != nil {
return nil, SYS_ERROR
}
return projects, SUCCESS
}
func Stars(name string) (int, int) {
user, status := User(name)
if status != SUCCESS || user == nil {
return 0, SYS_ERROR
}
var projects []*mod.Project
pages := int(math.Floor(float64(user.Repositories/100)) + 1)
for page := 1; page <= pages; page++ {
projectsCached, status := Projects(name, page)
if status != SUCCESS {
return 0, SYS_ERROR
}
projects = append(projects, projectsCached...)
}
out := 0
for _, project := range projects {
out += project.Stars
}
return out, SUCCESS
}
|
package gin
import (
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/surmus/injection"
"github.com/surmus/injection/test"
"net/http"
"testing"
)
var middlewareFnExecuted bool
const ctrlPostEndpoint = "/test-path-post"
const ctrlGetEndpoint = "/test-path-get"
type PointerController struct {
injection.BaseController
primitiveZeroValue int
PrimitiveValConstant string
Context *gin.Context
valueWithInnerDependency test.DependencyInterface
valueRequiringContext *test.DependencyStruct
t *testing.T
}
func NewPointerController(t *testing.T) *PointerController {
return &PointerController{
PrimitiveValConstant: test.Constant,
t: t,
}
}
func (c *PointerController) Routes() map[string][]string {
return map[string][]string{ctrlPostEndpoint: {"PostTest"}}
}
func (c *PointerController) PostTest(context *gin.Context) {
assert.NotNil(c.t, c.Context)
assert.NotNil(c.t, c.valueRequiringContext)
assert.Equal(c.t, test.Constant, c.PrimitiveValConstant)
assert.NotNil(c.t, c.valueWithInnerDependency)
assert.Equal(c.t, 0, c.primitiveZeroValue)
assert.Equal(c.t, c.Context, c.valueRequiringContext.Ctx)
assert.Equal(c.t, c.Context, context)
assert.True(
c.t,
c.valueWithInnerDependency.(*test.DependencyStruct) == c.valueRequiringContext,
"valueWithInnerDependency interface should be created from valueRequiringContext",
)
c.Context.String(http.StatusTeapot, "%s", test.Response)
}
type ValueController struct {
injection.BaseController
primitiveValConstant string
ValueRequiringContext *test.DependencyStruct
T *testing.T
}
func NewValueController(t *testing.T) ValueController {
return ValueController{
primitiveValConstant: test.Constant,
T: t,
}
}
func (c ValueController) Routes() map[string][]string {
return map[string][]string{ctrlGetEndpoint: {"GetTest"}}
}
func (c ValueController) Middleware() map[string][]injection.Handler {
middlewareFnExecuted = false
return map[string][]injection.Handler{"GetTest": {
func(ctx *gin.Context) {
middlewareFnExecuted = true
},
}}
}
func (c ValueController) GetTest(context *gin.Context, valueWithInnerDependency test.DependencyInterface) {
assert.NotNil(c.T, c.ValueRequiringContext)
assert.Equal(c.T, test.Constant, c.primitiveValConstant)
assert.NotNil(c.T, valueWithInnerDependency)
assert.True(
c.T,
valueWithInnerDependency.(*test.DependencyStruct) == c.ValueRequiringContext,
"valueWithInnerDependency interface should be created from valueRequiringContext",
)
context.String(http.StatusTeapot, "%s", test.Response)
}
type InvalidRoutesMapController struct {
injection.BaseController
}
func (c *InvalidRoutesMapController) Routes() map[string][]string {
return map[string][]string{ctrlPostEndpoint: {"PostTest"}}
}
func setupRouterWithProviders() *injection.Injector {
valueRequiringContextProvider := func(ctx *gin.Context) *test.DependencyStruct {
return &test.DependencyStruct{Ctx: ctx}
}
constantProvider := func() string {
return test.Constant
}
valueWithInnerDependencyProvider := func(dependency *test.DependencyStruct) test.DependencyInterface {
return dependency
}
test.Init()
r := Adapt(test.Router)
r.RegisterProviders(valueWithInnerDependencyProvider, valueRequiringContextProvider, constantProvider)
return r
}
func setupTestHandlerFn(t *testing.T) interface{} {
return func(
context *gin.Context,
valueWithInnerDependency test.DependencyInterface,
valueRequiringContext *test.DependencyStruct,
providedConstant string,
) {
assert.NotNil(t, context)
assert.NotNil(t, valueRequiringContext)
assert.Equal(t, test.Constant, providedConstant)
assert.NotNil(t, valueWithInnerDependency)
assert.Equal(t, context, valueRequiringContext.Ctx)
assert.True(
t,
valueWithInnerDependency.(*test.DependencyStruct) == valueRequiringContext,
"valueWithInnerDependency interface should be created from valueRequiringContext",
)
context.String(http.StatusTeapot, "%s", test.Response)
}
}
func TestIRoutesImpl_GET(t *testing.T) {
testCases := map[string]func(t *testing.T){
"successfully register handler and handle request": func(t *testing.T) {
r := setupRouterWithProviders()
testHandlerFn := setupTestHandlerFn(t)
registrationError := r.Handle(http.MethodGet, test.Endpoint, testHandlerFn)
req := test.NewRequest(test.Endpoint, http.MethodGet).
MustBuild().Do(test.Router)
assert.Nil(t, registrationError)
assert.Equal(t, http.StatusTeapot, req.Response.Code)
assert.Equal(t, test.Response, string(req.Response.Body.Bytes()))
},
"fail to register handler with unregistered dependencies": func(t *testing.T) {
r := Adapt(gin.New())
testHandlerFn := setupTestHandlerFn(t)
registrationError := r.Handle(http.MethodGet, test.Endpoint, testHandlerFn)
assert.IsType(t, injection.Error{}, registrationError)
},
}
for testName, testCase := range testCases {
t.Run(testName, testCase)
}
}
func TestIRoutesImpl_POST(t *testing.T) {
testCases := map[string]func(t *testing.T){
"successfully register handler and handle request": func(t *testing.T) {
r := setupRouterWithProviders()
testHandlerFn := setupTestHandlerFn(t)
registrationError := r.Handle(http.MethodPost, test.Endpoint, testHandlerFn)
req := test.NewRequest(test.Endpoint, http.MethodPost).
MustBuild().Do(test.Router)
assert.Nil(t, registrationError)
assert.Equal(t, http.StatusTeapot, req.Response.Code)
assert.Equal(t, test.Response, string(req.Response.Body.Bytes()))
},
"fail to register handler with unregistered dependencies": func(t *testing.T) {
r := Adapt(gin.New())
testHandlerFn := setupTestHandlerFn(t)
registrationError := r.Handle(http.MethodPost, test.Endpoint, testHandlerFn)
assert.IsType(t, injection.Error{}, registrationError)
},
}
for testName, testCase := range testCases {
t.Run(testName, testCase)
}
}
func TestIRoutesImpl_PUT(t *testing.T) {
testCases := map[string]func(t *testing.T){
"successfully register handler and handle request": func(t *testing.T) {
r := setupRouterWithProviders()
testHandlerFn := setupTestHandlerFn(t)
registrationError := r.Handle(http.MethodPut, test.Endpoint, testHandlerFn)
req := test.NewRequest(test.Endpoint, http.MethodPut).
MustBuild().Do(test.Router)
assert.Nil(t, registrationError)
assert.Equal(t, http.StatusTeapot, req.Response.Code)
assert.Equal(t, test.Response, string(req.Response.Body.Bytes()))
},
"fail to register handler with unregistered dependencies": func(t *testing.T) {
r := Adapt(gin.New())
testHandlerFn := setupTestHandlerFn(t)
registrationError := r.Handle(http.MethodPut, test.Endpoint, testHandlerFn)
assert.IsType(t, injection.Error{}, registrationError)
},
}
for testName, testCase := range testCases {
t.Run(testName, testCase)
}
}
func TestIRoutesImpl_OPTIONS(t *testing.T) {
testCases := map[string]func(t *testing.T){
"successfully register handler and handle request": func(t *testing.T) {
r := setupRouterWithProviders()
testHandlerFn := setupTestHandlerFn(t)
registrationError := r.Handle(http.MethodOptions, test.Endpoint, testHandlerFn)
req := test.NewRequest(test.Endpoint, http.MethodOptions).
MustBuild().Do(test.Router)
assert.Nil(t, registrationError)
assert.Equal(t, http.StatusTeapot, req.Response.Code)
assert.Equal(t, test.Response, string(req.Response.Body.Bytes()))
},
"fail to register handler with unregistered dependencies": func(t *testing.T) {
r := Adapt(gin.New())
testHandlerFn := setupTestHandlerFn(t)
registrationError := r.Handle(http.MethodOptions, test.Endpoint, testHandlerFn)
assert.IsType(t, injection.Error{}, registrationError)
},
}
for testName, testCase := range testCases {
t.Run(testName, testCase)
}
}
func TestIRoutesImpl_PATCH(t *testing.T) {
testCases := map[string]func(t *testing.T){
"successfully register handler and handle request": func(t *testing.T) {
r := setupRouterWithProviders()
testHandlerFn := setupTestHandlerFn(t)
registrationError := r.Handle(http.MethodPatch, test.Endpoint, testHandlerFn)
req := test.NewRequest(test.Endpoint, http.MethodPatch).
MustBuild().Do(test.Router)
assert.Nil(t, registrationError)
assert.Equal(t, http.StatusTeapot, req.Response.Code)
assert.Equal(t, test.Response, string(req.Response.Body.Bytes()))
},
"fail to register handler with unregistered dependencies": func(t *testing.T) {
r := Adapt(gin.New())
testHandlerFn := setupTestHandlerFn(t)
registrationError := r.Handle(http.MethodPatch, test.Endpoint, testHandlerFn)
assert.IsType(t, injection.Error{}, registrationError)
},
}
for testName, testCase := range testCases {
t.Run(testName, testCase)
}
}
func TestIRoutesImpl_DELETE(t *testing.T) {
testCases := map[string]func(t *testing.T){
"successfully register handler and handle request": func(t *testing.T) {
r := setupRouterWithProviders()
testHandlerFn := setupTestHandlerFn(t)
registrationError := r.Handle(http.MethodDelete, test.Endpoint, testHandlerFn)
req := test.NewRequest(test.Endpoint, http.MethodDelete).
MustBuild().Do(test.Router)
assert.Nil(t, registrationError)
assert.Equal(t, http.StatusTeapot, req.Response.Code)
assert.Equal(t, test.Response, string(req.Response.Body.Bytes()))
},
"fail to register handler with unregistered dependencies": func(t *testing.T) {
r := Adapt(gin.New())
testHandlerFn := setupTestHandlerFn(t)
registrationError := r.Handle(http.MethodDelete, test.Endpoint, testHandlerFn)
assert.IsType(t, injection.Error{}, registrationError)
},
}
for testName, testCase := range testCases {
t.Run(testName, testCase)
}
}
func TestIRoutesImpl_HEAD(t *testing.T) {
testCases := map[string]func(t *testing.T){
"successfully register handler and handle request": func(t *testing.T) {
r := setupRouterWithProviders()
testHandlerFn := setupTestHandlerFn(t)
registrationError := r.Handle(http.MethodHead, test.Endpoint, testHandlerFn)
req := test.NewRequest(test.Endpoint, http.MethodHead).
MustBuild().Do(test.Router)
assert.Nil(t, registrationError)
assert.Equal(t, http.StatusTeapot, req.Response.Code)
assert.Equal(t, test.Response, string(req.Response.Body.Bytes()))
},
"fail to register handler with unregistered dependencies": func(t *testing.T) {
r := Adapt(gin.New())
testHandlerFn := setupTestHandlerFn(t)
registrationError := r.Handle(http.MethodHead, test.Endpoint, testHandlerFn)
assert.IsType(t, injection.Error{}, registrationError)
},
}
for testName, testCase := range testCases {
t.Run(testName, testCase)
}
}
func TestIRoutesImpl_Use(t *testing.T) {
testCases := map[string]func(t *testing.T){
"successfully register middleware and intercept request after handle": func(t *testing.T) {
r := setupRouterWithProviders()
registrationError := r.Use(func(c *gin.Context) {
c.Next()
c.Set(test.CtxKey, test.CtxVal) // executes after request handler, value test.CtxVal should be unavailable
})
r.Handle(http.MethodHead, test.Endpoint, func(c *gin.Context) {
assert.Nil(t, c.Value(test.CtxKey))
c.String(http.StatusTeapot, "%s", test.Response)
})
req := test.NewRequest(test.Endpoint, http.MethodHead).
MustBuild().Do(test.Router)
assert.Nil(t, registrationError)
assert.Equal(t, http.StatusTeapot, req.Response.Code)
assert.Equal(t, test.Response, string(req.Response.Body.Bytes()))
},
"fail to register handler with unregistered dependencies": func(t *testing.T) {
r := Adapt(gin.New())
testHandlerFn := setupTestHandlerFn(t)
registrationError := r.Use(testHandlerFn)
assert.IsType(t, injection.Error{}, registrationError)
},
}
for testName, testCase := range testCases {
t.Run(testName, testCase)
}
}
func TestIRoutesImpl_RegisterController(t *testing.T) {
tests := map[string]func(t *testing.T){
"successfully for Controller pointer receiver request handler method": func(t *testing.T) {
r := setupRouterWithProviders()
registrationError := r.RegisterController(NewPointerController(t))
req := test.NewRequest(ctrlPostEndpoint, http.MethodPost).
MustBuild().Do(test.Router)
assert.Nil(t, registrationError)
assert.Equal(t, http.StatusTeapot, req.Response.Code)
assert.Equal(t, test.Response, string(req.Response.Body.Bytes()))
},
"successfully for Controller value receiver request handler method": func(t *testing.T) {
r := setupRouterWithProviders()
registrationError := r.RegisterController(NewValueController(t))
req := test.NewRequest(ctrlGetEndpoint, http.MethodGet).
MustBuild().Do(test.Router)
assert.Nil(t, registrationError)
assert.Equal(t, http.StatusTeapot, req.Response.Code)
assert.Equal(t, test.Response, string(req.Response.Body.Bytes()))
},
"should execute controller method middleware": func(t *testing.T) {
r := setupRouterWithProviders()
registrationError := r.RegisterController(NewValueController(t))
test.NewRequest(ctrlGetEndpoint, http.MethodGet).MustBuild().Do(test.Router)
assert.Nil(t, registrationError)
assert.True(t, middlewareFnExecuted)
},
"fail registering Controller with unregistered dependencies": func(t *testing.T) {
r := Adapt(gin.New())
registrationError := r.RegisterController(NewPointerController(t))
assert.IsType(t, injection.Error{}, registrationError)
},
"fail registering Controller with incorrect routes mapping": func(t *testing.T) {
r := Adapt(gin.New())
registrationError := r.RegisterController(new(InvalidRoutesMapController))
assert.IsType(t, injection.Error{}, registrationError)
},
}
for testName, testCase := range tests {
t.Run(testName, testCase)
}
}
func TestAdaptToExisting(t *testing.T) {
tests := map[string]func(t *testing.T){
"verify injector copy middleware does not bleed over to original": func(t *testing.T) {
test.Init()
var triggeredMiddleWaresCount int
originalInjector := Adapt(test.Router)
originalInjector.Use(func() {
triggeredMiddleWaresCount++
})
originalCpy := AdaptToExisting(originalInjector, test.Router.Group(test.Endpoint))
originalCpy.Use(func() {
triggeredMiddleWaresCount++
})
test.NewRequest("/", http.MethodGet).MustBuild().Do(test.Router)
assert.Equal(t, 1, triggeredMiddleWaresCount)
},
"verify injector copy executes original and copy middleware": func(t *testing.T) {
test.Init()
var triggeredMiddleWaresCount int
originalInjector := Adapt(test.Router)
originalInjector.Use(func() {
triggeredMiddleWaresCount++
})
originalCpy := AdaptToExisting(originalInjector, test.Router.Group(test.Endpoint))
originalCpy.Use(func() {
triggeredMiddleWaresCount++
})
originalCpy.Handle(http.MethodGet, "/", func() {})
test.NewRequest(test.Endpoint+"/", http.MethodGet).MustBuild().Do(test.Router)
assert.Equal(t, 2, triggeredMiddleWaresCount)
},
}
for testName, testCase := range tests {
t.Run(testName, testCase)
}
}
|
package main
import (
"context"
"net/http"
"time"
log "github.com/Sirupsen/logrus"
jwt "github.com/dgrijalva/jwt-go"
"github.com/golang/protobuf/ptypes"
"github.com/yogyrahmawan/client_grpc_logger_service/pb"
glb "github.com/yogyrahmawan/grpcloadbalancing"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
var (
loggerServiceClient pb.LoggerServiceClient
)
// JWTAuth hold jwt auth
type JWTAuth struct {
Token string
}
// GetRequestMetadata gets the current request metadata
func (a *JWTAuth) GetRequestMetadata(context.Context, ...string) (map[string]string, error) {
return map[string]string{
"token": a.Token,
}, nil
}
// RequireTransportSecurity indicates whether the credentials requires transport security
func (a *JWTAuth) RequireTransportSecurity() bool {
return true
}
func initJWTAuth() (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"internal_service": "internal_service",
"nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
})
return token.SignedString([]byte("113070"))
}
func main() {
// Create the client TLS credentials
creds, err := credentials.NewClientTLSFromFile("cert/server.crt", "")
if err != nil {
log.Fatalf("could not load tls cert: %s", err)
}
// initialise jwt auth
token, err := initJWTAuth()
if err != nil {
log.Fatalf("cannot sign jwt, err: %s", err)
}
log.Println("Got token " + token)
auth := JWTAuth{
Token: token,
}
// make generator
generator := func() (*grpc.ClientConn, error) {
conn, err := grpc.Dial("localhost:9005", grpc.WithTransportCredentials(creds), grpc.WithPerRPCCredentials(&auth))
if err != nil {
log.Fatalf("did not connect: %s", err)
}
return conn, err
}
end, err := glb.NewEndpoint("localhost:9005", 2, 200, generator)
if err != nil {
log.Fatalf("did not connect : %s", err)
}
// experiment, make 2 connections
end2, err := glb.NewEndpoint("localhost:9005", 2, 200, generator)
lb := glb.NewLoadBalance([]*glb.Endpoint{end, end2})
http.HandleFunc("/send", func(rw http.ResponseWriter, req *http.Request) {
// get connection
nextEnd, err := lb.Get()
if err != nil {
log.Fatalf("failed get connection, err : %s", err)
}
conn := nextEnd.GetClientConn()
defer conn.Close()
loggerServiceClient = pb.NewLoggerServiceClient(conn)
response, err := loggerServiceClient.SendLog(context.Background(), &pb.LoggerMessage{
IpPort: "localhost:8080",
ServiceName: "test_service",
Level: "info",
Text: "this is test",
CreatedAt: ptypes.TimestampNow(),
})
if err != nil {
log.Errorf("error when calling SendLog: %s", err)
renderJSON(rw, http.StatusInternalServerError, responseMessage{
status: "error",
message: err.Error(),
})
return
}
log.Printf("Response from server: %s", response.Status)
if response.Status != "ok" {
log.Info("send not ok")
renderJSON(rw, 422, responseMessage{
status: "not_ok",
message: response.Status,
})
}
log.Debug("seems ok")
renderJSON(rw, http.StatusOK, responseMessage{
status: "ok",
message: response.Status,
})
})
log.Infof("HTTP server listening on %s", ":6000")
http.ListenAndServe(":6000", nil)
}
|
package flagtag
import (
"flag"
"os"
"strconv"
"strings"
"testing"
"time"
)
func TestConfigureNil(t *testing.T) {
if Configure(nil) == nil {
t.Fatal("Expected an error, since nil cannot be parsed.")
}
}
func TestConfigureUntaggedStruct(t *testing.T) {
var s = struct {
A int
B uint
C string
}{}
if err := Configure(&s); err != nil {
t.Fatal("Unexpected error: " + err.Error())
}
}
func TestConfigureNilPointer(t *testing.T) {
var c *struct{}
if Configure(c) == nil {
t.Fatal("Expected an error, since pointer is nil.")
}
}
func TestConfigureNonStructPointer(t *testing.T) {
var i = 42
if Configure(&i) == nil {
t.Fatal("Expected an error, since config value is not a struct.")
}
}
func TestEmptyStruct(t *testing.T) {
var s = struct{}{}
if Configure(&s) != nil {
t.Fatal("Expected correct processing of empty struct.")
}
}
func TestNonTaggedStruct(t *testing.T) {
var s = struct {
V string
}{}
if Configure(&s) != nil {
t.Fatal("Expected correct processing of struct without any tags.")
}
}
func TestNonRelevantlyTaggedStruct(t *testing.T) {
var s = struct {
V string `json:"some,value"`
}{}
if Configure(&s) != nil {
t.Fatal("Expected correct processing of struct without any relevant tags.")
}
}
func TestUnexportedTaggedField(t *testing.T) {
var s = struct {
v string `flag:"unexported,unexported,Tagging an unexported value."`
}{}
if Configure(&s) == nil {
t.Fatal("Expected error regarding unexported field, but got nothing.")
}
}
func TestEmptyTagName(t *testing.T) {
var s = struct {
V string `flag:",,"`
}{}
if Configure(&s) == nil {
t.Fatal("Expected error because no flag name was specified.")
}
}
func TestIncompleteTag(t *testing.T) {
var s = struct {
V string `flag:"a"`
}{}
if Configure(&s) != nil {
t.Fatal("Expected correct processing even though tag does not contain all parts.")
}
tag := flag.Lookup("a")
if tag == nil {
t.Fatal("Cannot find configured flag.")
}
if tag.Name != "a" {
t.Error("Expected another tag name.")
}
if tag.DefValue != "" {
t.Error("Expected empty string as default value, since we didn't specify any.")
}
if tag.Usage != "" {
t.Error("Expected empty string as usage information, since we didn't specify any.")
}
}
func TestTagString(t *testing.T) {
var s = struct {
V string `flag:"s,hello world,This sets the string flag."`
}{}
if Configure(&s) != nil {
t.Fatal("Expected correct configuration without any errors.")
}
f := flag.Lookup("s")
if f == nil {
t.Fatal("Could not find configured flag.")
}
if f.Name != "s" {
t.Error("Configured flag has incorrect name.")
}
if f.DefValue != "hello world" {
t.Error("Configured flag has incorrect default value.")
}
if f.Usage != "This sets the string flag." {
t.Error("Configured flag has incorrect usage description.")
}
}
func TestTagBool(t *testing.T) {
var s = struct {
V bool `flag:"b,true,This sets the bool flag."`
}{}
if Configure(&s) != nil {
t.Fatal("Expected correct configuration without any errors.")
}
f := flag.Lookup("b")
if f == nil {
t.Fatal("Could not find configured flag.")
}
if f.Name != "b" {
t.Error("Configured flag has incorrect name.")
}
if f.DefValue != "true" {
t.Error("Configured flag has incorrect default value.")
}
if f.Usage != "This sets the bool flag." {
t.Error("Configured flag has incorrect usage description.")
}
}
func TestTagBoolInvalidDefault(t *testing.T) {
var s = struct {
V bool `flag:"b2,foo,This sets the bool flag."`
}{}
if Configure(&s) == nil {
t.Fatal("Expected error due to incorrect default value.")
}
}
func TestTagFloat64(t *testing.T) {
var s = struct {
V float64 `flag:"f,0.2345,This sets the float flag."`
}{}
if Configure(&s) != nil {
t.Fatal("Expected correct configuration without any errors.")
}
f := flag.Lookup("f")
if f == nil {
t.Fatal("Could not find configured flag.")
}
if f.Name != "f" {
t.Error("Configured flag has incorrect name.")
}
if f.DefValue != "0.2345" {
t.Error("Configured flag has incorrect default value.")
}
if f.Usage != "This sets the float flag." {
t.Error("Configured flag has incorrect usage description.")
}
}
func TestTagFloat64InvalidDefault(t *testing.T) {
var s = struct {
V float64 `flag:"f2,abcde,This sets the float64 flag."`
}{}
if Configure(&s) == nil {
t.Fatal("Expected error due to incorrect default value.")
}
}
func TestTagInt(t *testing.T) {
var s = struct {
V int `flag:"i,64,This sets the int flag."`
}{}
if Configure(&s) != nil {
t.Fatal("Expected correct configuration without any errors.")
}
f := flag.Lookup("i")
if f == nil {
t.Fatal("Could not find configured flag.")
}
if f.Name != "i" {
t.Error("Configured flag has incorrect name.")
}
if f.DefValue != "64" {
t.Error("Configured flag has incorrect default value.")
}
if f.Usage != "This sets the int flag." {
t.Error("Configured flag has incorrect usage description.")
}
}
func TestTagIntInvalidDefault(t *testing.T) {
var s = struct {
V int `flag:"i2,0.33333,This sets the int flag."`
}{}
if Configure(&s) == nil {
t.Fatal("Expected error due to incorrect default value.")
}
}
func TestTagInt64(t *testing.T) {
var s = struct {
V int64 `flag:"i64,-6400000000,This sets the int64 flag."`
}{}
if Configure(&s) != nil {
t.Fatal("Expected correct configuration without any errors.")
}
f := flag.Lookup("i64")
if f == nil {
t.Fatal("Could not find configured flag.")
}
if f.Name != "i64" {
t.Error("Configured flag has incorrect name.")
}
if f.DefValue != "-6400000000" {
t.Error("Configured flag has incorrect default value.")
}
if f.Usage != "This sets the int64 flag." {
t.Error("Configured flag has incorrect usage description.")
}
}
func TestTagInt64InvalidDefault(t *testing.T) {
var s = struct {
V int64 `flag:"i64-2,abcdefgh,This sets the int64 flag."`
}{}
if Configure(&s) == nil {
t.Fatal("Expected error due to incorrect default value.")
}
}
func TestTagUint(t *testing.T) {
var s = struct {
V uint `flag:"u,3200,This sets the uint flag."`
}{}
if Configure(&s) != nil {
t.Fatal("Expected correct configuration without any errors.")
}
f := flag.Lookup("u")
if f == nil {
t.Fatal("Could not find configured flag.")
}
if f.Name != "u" {
t.Error("Configured flag has incorrect name.")
}
if f.DefValue != "3200" {
t.Error("Configured flag has incorrect default value.")
}
if f.Usage != "This sets the uint flag." {
t.Error("Configured flag has incorrect usage description.")
}
}
func TestTagUintInvalidDefault(t *testing.T) {
var s = struct {
V uint `flag:"u2,-200,This sets the uint flag."`
}{}
if Configure(&s) == nil {
t.Fatal("Expected error due to incorrect default value.")
}
}
func TestTagUint64(t *testing.T) {
var s = struct {
V uint64 `flag:"u64,6400000000,This sets the uint64 flag."`
}{}
if Configure(&s) != nil {
t.Fatal("Expected correct configuration without any errors.")
}
f := flag.Lookup("u64")
if f == nil {
t.Fatal("Could not find configured flag.")
}
if f.Name != "u64" {
t.Error("Configured flag has incorrect name.")
}
if f.DefValue != "6400000000" {
t.Error("Configured flag has incorrect default value.")
}
if f.Usage != "This sets the uint64 flag." {
t.Error("Configured flag has incorrect usage description.")
}
}
func TestTagUint64InvalidDefault(t *testing.T) {
var s = struct {
V uint64 `flag:"u64-2,abcdefgh,This sets the uint64 flag."`
}{}
if Configure(&s) == nil {
t.Fatal("Expected error due to incorrect default value.")
}
}
func TestMustConfigure(t *testing.T) {
defer func() {
// We are supposed to get a panic, so silence it.
recover()
}()
var s = struct {
X bool `flag:"x,test,test"`
}{}
MustConfigure(&s)
t.FailNow()
}
func TestConfigureAndParse(t *testing.T) {
var s = struct {
X string `flag:"xx,test,Test 1."`
Y bool `flag:"y,f,Test 2."`
}{}
if err := ConfigureAndParse(&s); err != nil {
t.Fatal("Did not expect error: " + err.Error())
}
if flag.Parsed() == false {
t.Fatal("Expected command line flags to be parsed by now.")
}
}
func TestConfigureAndParseFaulty(t *testing.T) {
var s = struct {
Y bool `flag:"y,bla,Test 2."`
}{}
if err := ConfigureAndParse(&s); err == nil {
t.Fatal("Expected an error but got nothing.")
}
}
func TestMustConfigureAndParseFailing(t *testing.T) {
defer func() {
// We are supposed to get a panic, so silence it.
recover()
}()
var s = struct {
X bool `flag:"xxx,test,test"`
}{}
MustConfigureAndParse(&s)
t.FailNow()
}
func TestMustConfigureAndParseSuccessfully(t *testing.T) {
var s = struct {
X bool `flag:"xxxx,True,test"`
}{}
MustConfigureAndParse(&s)
if !flag.Parsed() {
t.Fatal("Expected an command line flags to be parsed by now.")
}
}
func TestErrorOnInvalidDataType(t *testing.T) {
var s = struct {
Invalid uintptr `flag:"xxxxxx,,"`
}{}
if err := Configure(&s); err == nil {
t.Fatal("Expected error because of unsupported data type.")
}
}
func TestRecursiveStructProcessing(t *testing.T) {
var outer = struct {
Inner struct {
V int `flag:"innerv,1"`
}
}{}
err := Configure(&outer)
if err != nil {
t.Fatal("Unexpected error: " + err.Error())
}
f := flag.Lookup("innerv")
if f == nil {
t.Fatal("Could not find configured flag.")
}
if f.Name != "innerv" {
t.Error("Configured flag has incorrect name.")
}
if f.DefValue != "1" {
t.Error("Configured flag has incorrect default value.")
}
if f.Usage != "" {
t.Error("Configured flag has incorrect usage description.")
}
}
func TestBadInnerStruct(t *testing.T) {
var outer = struct {
Inner struct {
V uint `flag:"innerv,-1"`
}
}{}
err := Configure(&outer)
if err == nil {
t.Fatal("Expected error because of invalid default value.")
}
}
func TestMixedInnerStructProcessing(t *testing.T) {
var outer = struct {
Before uint `flag:"outerBefore,3,some description"`
Blank uint
Inner struct {
Dummy int
Inside string `flag:"innerInside,2,inside information"`
}
After int `flag:"outerAfter,1,final remark"`
}{}
err := Configure(&outer)
if err != nil {
t.Fatal("Unexpected error: " + err.Error())
}
flagBefore := flag.Lookup("outerBefore")
if flagBefore.Name != "outerBefore" || flagBefore.DefValue != "3" || flagBefore.Usage != "some description" {
t.Error("Flag outerBefore data is invalid.")
}
flagInside := flag.Lookup("innerInside")
if flagInside.Name != "innerInside" || flagInside.DefValue != "2" || flagInside.Usage != "inside information" {
t.Error("Flag innerInside data is invalid.")
}
flagAfter := flag.Lookup("outerAfter")
if flagAfter.Name != "outerAfter" || flagAfter.DefValue != "1" || flagAfter.Usage != "final remark" {
t.Error("Flag outerAfter data is invalid.")
}
}
func TestRegisterTypeDerivedFromPrimitive(t *testing.T) {
var s = struct {
D aliasInt `flag:"flagValueAliasInt,-10,Alias of int, still works as primitive int flag."`
}{}
Configure(&s)
flagAlias := flag.Lookup("flagValueAliasInt")
if flagAlias == nil {
t.Fatal("Could not find defined flagValueAliasInt.")
}
if flagAlias.Name != "flagValueAliasInt" || flagAlias.DefValue != "-10" || flagAlias.Usage != "Alias of int, still works as primitive int flag." {
t.Error("Flag flagValueAliasInt data is invalid.")
}
}
type aliasInt int
func TestRegisterValueInterfaceFlag(t *testing.T) {
var s = struct {
D dummyInt `flag:"flagValueDummyInt,,My first flag.Value implementation."`
}{}
err := Configure(&s)
if err != nil {
t.Fatal("Unexpected error: " + err.Error())
}
flagDummyInt := flag.Lookup("flagValueDummyInt")
if flagDummyInt == nil {
t.Fatal("Expected a flag, but got nil.")
}
if flagDummyInt.Name != "flagValueDummyInt" || flagDummyInt.DefValue != "0" || flagDummyInt.Usage != "My first flag.Value implementation." {
t.Fatal("Flag data is invalid.")
}
}
func TestRegisterValueInterfaceFlagNilPointer(t *testing.T) {
var s = struct {
D *dummyInt `flag:"flagValueDummyIntNilPointer,,My first flag.Value implementation."`
}{}
err := Configure(&s)
if err == nil {
t.Fatal("Expected an error since the pointer is nil, but didn't get anything.")
}
}
func TestRegisterValueInterfaceFlagPointer(t *testing.T) {
var s = struct {
D *dummyInt `flag:"flagValueDummyIntPointer,,My first flag.Value implementation."`
}{D: new(dummyInt)}
err := Configure(&s)
if err != nil {
t.Fatal("Unexpected error: " + err.Error())
}
flagDummyInt := flag.Lookup("flagValueDummyIntPointer")
if flagDummyInt == nil {
t.Fatal("Expected a flag, but got nil.")
}
if flagDummyInt.Name != "flagValueDummyIntPointer" || flagDummyInt.DefValue != "0" || flagDummyInt.Usage != "My first flag.Value implementation." {
t.Fatal("Flag data is invalid.")
}
}
func TestRegisterPrimitiveFlagNilPointer(t *testing.T) {
var s = struct {
D *int `flag:"flagValueIntPointer,123,My first primitive pointer flag."`
}{}
err := Configure(&s)
if err == nil {
t.Fatal("Expected an error but got nothing.")
}
}
func TestRegisterPrimitiveFlagPointer(t *testing.T) {
var s = struct {
D *int `flag:"flagValueIntPointer,123,My first primitive pointer flag."`
}{D: new(int)}
*s.D = 123
err := Configure(&s)
if err != nil {
t.Fatal("Unexpected error: " + err.Error())
}
flagInt := flag.Lookup("flagValueIntPointer")
if flagInt == nil {
t.Fatal("Expected a flag, but got nil.")
}
if flagInt.Name != "flagValueIntPointer" || flagInt.DefValue != "123" || flagInt.Usage != "My first primitive pointer flag." {
t.Fatal("Flag data is invalid.")
}
}
func TestRegisterFlagValueThroughInterfaceNil(t *testing.T) {
var s = struct {
D interface{} `flag:"flagValueUnknownInterface,,Value which turns out is flag.Value compatible."`
}{}
err := Configure(&s)
if err == nil {
t.Fatal("Expected error because D is nil.")
}
}
func TestRegisterFlagValueThroughInterfaceValueNilPointer(t *testing.T) {
var v *dummyInt
var s = struct {
D interface{} `flag:"flagValueUnknownInterface,,Value which turns out is flag.Value compatible."`
}{D: v}
err := Configure(&s)
if err == nil {
t.Fatal("Expected error because D is nil.")
}
}
func TestRegisterFlagValueThroughInterfaceValueZeroValue(t *testing.T) {
var v dummyInt
var s = struct {
D interface{} `flag:"flagValueUnknownInterface,,Value which turns out is flag.Value compatible."`
}{D: v}
err := Configure(&s)
if err == nil {
t.Fatal("Expected error because D is nil.")
}
}
func TestRegisterFlagValueThroughInterface(t *testing.T) {
var s = struct {
D interface{} `flag:"flagValueUnknownInterface,,Value which turns out is flag.Value compatible."`
}{D: new(dummyInt)}
err := Configure(&s)
if err != nil {
t.Fatal("Unexpected error: " + err.Error())
}
flagUnknown := flag.Lookup("flagValueUnknownInterface")
if flagUnknown == nil {
t.Fatal("Expected a flag, but got nil.")
}
if flagUnknown.Name != "flagValueUnknownInterface" || flagUnknown.DefValue != "0" || flagUnknown.Usage != "Value which turns out is flag.Value compatible." {
t.Fatal("Flag data is invalid.")
}
}
type dummyInt int
func (d *dummyInt) String() string {
return strconv.Itoa(int(*d))
}
func (d *dummyInt) Set(value string) error {
i, err := strconv.Atoi(value)
if err == nil {
*d = dummyInt(i)
}
return err
}
func TestRegisterDurationNilPointer(t *testing.T) {
var s = struct {
D *time.Duration `flag:"flagDuration,1h,Specify duration"`
}{}
err := Configure(&s)
if err == nil {
t.Fatal("Expected an error because of nil pointer.")
}
}
func TestRegisterDuration(t *testing.T) {
var s = struct {
D time.Duration `flag:"flagDuration,1h,Specify duration"`
}{}
err := Configure(&s)
if err != nil {
t.Fatal("Unexpected error: " + err.Error())
}
flagInterface := flag.Lookup("flagDuration")
if flagInterface == nil {
t.Fatal("Expected a flag, but got nil.")
}
if flagInterface.Name != "flagDuration" || flagInterface.DefValue != "1h0m0s" || flagInterface.Usage != "Specify duration" {
t.Fatal("Flag data is invalid.")
}
}
func TestRegisterDurationBadDefault(t *testing.T) {
var s = struct {
D time.Duration `flag:"flagDuration,1abcde,Specify duration"`
}{}
err := Configure(&s)
if err == nil {
t.Fatal("Expected error because of bad defaults.")
}
}
func TestRegisterDurationPointer(t *testing.T) {
var s = struct {
D *time.Duration `flag:"flagDurationPointer,1h,Specify duration"`
}{D: new(time.Duration)}
err := Configure(&s)
if err != nil {
t.Fatal("Unexpected error: " + err.Error())
}
flagInterface := flag.Lookup("flagDurationPointer")
if flagInterface == nil {
t.Fatal("Expected a flag, but got nil.")
}
if flagInterface.Name != "flagDurationPointer" || flagInterface.DefValue != "1h0m0s" || flagInterface.Usage != "Specify duration" {
t.Fatal("Flag data is invalid.")
}
}
func TestErrInvalidDefault(t *testing.T) {
var s = struct {
D int `flag:"flagInvalidDefault,abcde,Test invalid defaults..."`
}{}
err := Configure(&s)
if err == nil {
t.Fatal("Error was expected but got nothing.")
}
if !strings.HasPrefix(err.Error(), "invalid default value for field 'D' (tag 'flagInvalidDefault'): ") {
t.Fatal("Expected a different error message than was provided.")
}
}
func TestNoFlagOptionsProvided(t *testing.T) {
var s = struct {
D flagoptInt `flag:"flagNoOpts,13,Test flag no options ..."`
}{}
err := Configure(&s)
if err != nil {
t.Fatal("Unexpected error: " + err.Error())
}
if s.D != 42 {
t.Fatal("Expected value 42, because we don't skip the flag.Value interface test.")
}
}
func TestFlagOptionsSkipFlagValueFalseProvided(t *testing.T) {
var s = struct {
D flagoptInt `flag:"flagOptsEmpty,13,Test flag no options ..." flagopt:""`
}{}
err := Configure(&s)
if err != nil {
t.Fatal("Unexpected error:", err.Error())
}
if s.D != 42 {
t.Fatal("Expected value 42, because we don't skip the flag.Value interface test, but got", s.D)
}
}
func TestNoFlagOptionsSkipFlagValueProvided(t *testing.T) {
var s = struct {
D flagoptInt `flag:"flagOptsSkipFlagValue,13,Test flag no options ..." flagopt:"skipFlagValue"`
}{}
err := Configure(&s)
if err != nil {
t.Fatal("Unexpected error: ", err.Error())
}
if s.D != 13 {
t.Fatal("Expected value 13, because we skip the flag.Value interface test, but got", s.D)
}
}
func TestNoFlagValueDefaults(t *testing.T) {
var s = struct {
D flagoptInt `flag:"flagNoFlagValue,,Test flag no options ..."`
}{}
err := Configure(&s)
if err != nil {
t.Fatal("Unexpected error: ", err.Error())
}
if s.D != 0 {
t.Fatal("Expected value 0, because we skip the flag.Value interface test, but got", s.D)
}
}
func TestWithFlagValueDefaults(t *testing.T) {
var s = struct {
D flagoptInt `flag:"flagWithFlagValue,12,Test flag no options ..."`
}{}
err := Configure(&s)
if err != nil {
t.Fatal("Unexpected error: ", err.Error())
}
if s.D != 42 {
t.Fatal("Expected value 0, because we skip the flag.Value interface test, but got", s.D)
}
}
type flagoptInt int
func (o *flagoptInt) String() string {
return strconv.Itoa((int)(*o))
}
func (o *flagoptInt) Set(value string) error {
*o = 42
return nil
}
func TestConfigureAndParseArgs(t *testing.T) {
args := os.Args[:1]
var s = struct {
D int
}{}
var testset = []struct {
data interface{}
args []string
errorExpected bool
}{
{nil, nil, true},
{&s, nil, false},
{nil, args, true},
{&s, args, false},
}
// run tests for cases specified above
for nr, test := range testset {
if err := ConfigureAndParseArgs(test.data, test.args); (err != nil) != test.errorExpected {
t.Error("Test entry", nr, "failed with error", err)
}
}
}
func TestMustConfigureFlagset(t *testing.T) {
os.Args = os.Args[:1]
fs := flag.NewFlagSet("foo", flag.ContinueOnError)
var s = struct {
D int
}{}
var testset = []struct {
data interface{}
flagset *flag.FlagSet
shouldError bool
}{
{nil, nil, true},
{&s, nil, true},
{nil, flag.CommandLine, true},
{nil, fs, true},
{&s, flag.CommandLine, false},
{&s, fs, false},
}
for nr, test := range testset {
if err := ConfigureFlagset(test.data, test.flagset); (err != nil) != test.shouldError {
t.Error("Test entry", nr, "failed ConfigureFlagset with error", err)
}
if err := ConfigureFlagsetAndParse(test.data, test.flagset); (err != nil) != test.shouldError {
t.Error("Test entry", nr, "failed ConfigureFlagsetAndParse with error", err)
}
if recovered := controlledMustConfigureFlagset(test.data, test.flagset); recovered != test.shouldError {
t.Error("Test entry", nr, "failed MustConfigureFlagset with recovery", recovered)
}
if recovered := controlledMustConfigureFlagsetAndParse(test.data, test.flagset); recovered != test.shouldError {
t.Error("Test entry", nr, "failed MustConfigureFlagsetAndParse with recovery", recovered)
}
}
}
func TestMustConfigureAndParseArgs(t *testing.T) {
var s = struct {
D int
}{}
var testset = []struct {
data interface{}
args []string
shouldError bool
}{
{nil, nil, true},
{&s, nil, false},
{nil, []string{}, true},
{&s, []string{}, false},
{nil, []string{"hello"}, true},
{&s, []string{"hello"}, false},
}
for nr, test := range testset {
if err := ConfigureAndParseArgs(test.data, test.args); (err != nil) != test.shouldError {
t.Error("Test entry", nr, "failed ConfigureAndParseArgs with error", err)
}
if recovered := controlledMustConfigureAndParseArgs(test.data, test.args); recovered != test.shouldError {
t.Error("Test entry", nr, "failed MustConfigureFlagset with recovery", recovered)
}
}
}
func TestMustConfigureFlagsetAndParseArgs(t *testing.T) {
var s = struct {
D int
}{}
var fs = flag.NewFlagSet("foo", flag.ContinueOnError)
var testset = []struct {
data interface{}
flagset *flag.FlagSet
args []string
shouldError bool
}{
{nil, nil, nil, true},
{nil, nil, []string{}, true},
{nil, nil, []string{"hello"}, true},
{nil, fs, nil, true},
{nil, fs, []string{}, true},
{nil, fs, []string{"hello"}, true},
{&s, nil, nil, true},
{&s, nil, []string{}, true},
{&s, nil, []string{"hello"}, true},
{&s, fs, nil, false},
{&s, fs, []string{}, false},
{&s, fs, []string{"hello"}, false},
}
for nr, test := range testset {
if err := ConfigureFlagsetAndParseArgs(test.data, test.flagset, test.args); (err != nil) != test.shouldError {
t.Error("Test entry", nr, "failed ConfigureFlagsetAndParseArgs with error", err)
}
if recovered := controlledMustConfigureFlagsetAndParseArgs(test.data, test.flagset, test.args); recovered != test.shouldError {
t.Error("Test entry", nr, "failed MustConfigureFlagsetAndParseArgs with recovery", recovered)
}
}
}
func controlledMustConfigureFlagset(data interface{}, fs *flag.FlagSet) (result bool) {
defer func() {
result = recover() != nil
}()
MustConfigureFlagset(data, fs)
return
}
func controlledMustConfigureFlagsetAndParse(data interface{}, fs *flag.FlagSet) (result bool) {
defer func() {
result = recover() != nil
}()
MustConfigureFlagsetAndParse(data, fs)
return
}
func controlledMustConfigureAndParseArgs(data interface{}, args []string) (result bool) {
defer func() {
result = recover() != nil
}()
MustConfigureAndParseArgs(data, args)
return
}
func controlledMustConfigureFlagsetAndParseArgs(data interface{}, flagset *flag.FlagSet, args []string) (result bool) {
defer func() {
result = recover() != nil
}()
MustConfigureFlagsetAndParseArgs(data, flagset, args)
return
}
|
// +build ignore
package main
import (
"github.com/shurcooL/httpfs/filter"
"github.com/shurcooL/httpfs/union"
"github.com/shurcooL/vfsgen"
"net/http"
)
func main() {
fs := union.New(map[string]http.FileSystem{
"/static": filter.Skip(http.Dir("static"), filter.FilesWithExtensions(".go")),
"/templates": http.Dir("templates"),
})
if err := vfsgen.Generate(fs, vfsgen.Options{
PackageName: "static",
Filename: "static/assets.go",
VariableName: "Assets",
}); err != nil {
panic(err.Error())
}
}
|
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
// TODO maybe there is better place for this
package fpath
import "context"
// The key type is unexported to prevent collisions with context keys defined in
// other packages.
type key int
// temp is the context key for temp struct.
const tempKey key = 0
type temp struct {
inmemory bool
directory string
}
// WithTempData creates context with information how store temporary data, in memory or on disk.
func WithTempData(ctx context.Context, directory string, inmemory bool) context.Context {
temp := temp{
inmemory: inmemory,
directory: directory,
}
return context.WithValue(ctx, tempKey, temp)
}
// GetTempData returns if temporary data should be stored in memory or on disk.
func GetTempData(ctx context.Context) (string, bool, bool) {
tempValue, ok := ctx.Value(tempKey).(temp)
if !ok {
return "", false, false
}
return tempValue.directory, tempValue.inmemory, ok
}
|
package leetcode
func isPowerOfTwo2(n int) bool {
if n == 0 {
return false
}
i := 1
for i < n {
i <<= 1
}
return n == i
}
|
// 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 assert
import "github.com/pkg/errors"
// OnError is the result of calling ThatError on an Assertion.
// It provides assertion tests that are specific to error types.
type OnError struct {
Assertion
err error
}
// ThatError returns an OnError for error type assertions.
func (a Assertion) ThatError(err error) OnError {
return OnError{Assertion: a, err: err}
}
// Succeeded asserts that the error value was nil.
func (o OnError) Succeeded() bool {
return o.CompareRaw(o.err, "", "success").Test(o.err == nil)
}
// Failed asserts that the error value was not nil.
func (o OnError) Failed() bool {
return o.ExpectRaw("", "failure").Test(o.err != nil)
}
// Equals asserts that the error value matches the expected error.
func (o OnError) Equals(expect error) bool {
return o.Compare(o.err, "==", expect).Test(o.err == expect)
}
// DeepEquals asserts that the error value matches the expected error using compare.DeepEqual.
func (o OnError) DeepEquals(expect error) bool {
return o.TestDeepEqual(o.err, expect)
}
// HasMessage asserts that the error string matches the expected message.
func (o OnError) HasMessage(expect string) bool {
return o.Compare(o.err.Error(), "has message", expect).Test(o.err != nil && o.err.Error() == expect)
}
// HasCause asserts that the error cause matches expected error.
func (o OnError) HasCause(expect error) bool {
cause := errors.Cause(o.err)
return o.Got(o.err).Add("Cause", cause).Expect("==", expect).Test(cause == expect)
}
|
package steps
import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
survey "github.com/AlecAivazis/survey/v2"
"github.com/go-ini/ini"
"github.com/pganalyze/collector/setup/query"
"github.com/pganalyze/collector/setup/state"
s "github.com/pganalyze/collector/setup/state"
)
var SpecifyDbLogLocation = &s.Step{
ID: "li_specify_db_log_location",
Kind: state.LogInsightsStep,
Description: "Specify the location of Postgres log files (db_log_location) in the collector config file",
Check: func(state *s.SetupState) (bool, error) {
return state.CurrentSection.HasKey("db_log_location"), nil
},
Run: func(state *s.SetupState) error {
var logLocation string
if state.Inputs.Scripted {
loc, err := getLogLocationScripted(state)
if err != nil {
return err
}
logLocation = loc
} else {
loc, err := getLogLocationInteractive(state)
if err != nil {
return err
}
logLocation = loc
}
_, err := state.CurrentSection.NewKey("db_log_location", logLocation)
if err != nil {
return err
}
return state.SaveConfig()
},
}
func getLogLocationScripted(state *s.SetupState) (string, error) {
doGuess := state.Inputs.GuessLogLocation.Valid && state.Inputs.GuessLogLocation.Bool
if state.Inputs.Settings.DBLogLocation.Valid {
explicitVal := state.Inputs.Settings.DBLogLocation.String
if doGuess && explicitVal != "" {
return "", errors.New("cannot specify both guess_log_location and set explicit db_log_location")
}
return explicitVal, nil
}
if !doGuess {
return "", errors.New("db_log_location not provided and guess_log_location flag not set")
}
guessedLogLocation, err := discoverLogLocation(state.CurrentSection, state.QueryRunner)
if err != nil {
return "", fmt.Errorf("could not determine Postgres log location automatically: %s", err)
}
return guessedLogLocation, nil
}
func getLogLocationInteractive(state *s.SetupState) (string, error) {
guessedLogLocation, err := discoverLogLocation(state.CurrentSection, state.QueryRunner)
if err != nil {
state.Verbose("could not determine Postgres log location automatically: %s", err)
} else {
var logLocationConfirmed bool
err = survey.AskOne(&survey.Confirm{
Message: fmt.Sprintf("Your database log file or directory appears to be %s; is this correct (will be saved to collector config)?", guessedLogLocation),
Default: false,
}, &logLocationConfirmed)
if err != nil {
return "", err
}
if logLocationConfirmed {
return guessedLogLocation, nil
}
// otherwise proceed below
}
var logLocation string
err = survey.AskOne(&survey.Input{
Message: "Please enter the Postgres log file location (will be saved to collector config)",
}, &logLocation, survey.WithValidator(validatePath))
return logLocation, err
}
func validatePath(ans interface{}) error {
ansStr, ok := ans.(string)
if !ok {
return errors.New("expected string value")
}
// TODO: also confirm this is readable by the regular pganalyze user
_, err := os.Stat(ansStr)
if err != nil {
return err
}
return nil
}
func getPostmasterPid() (int, error) {
pidStr, err := exec.Command("pgrep", "-U", "postgres", "-o", "postgres").Output()
if err != nil {
return -1, fmt.Errorf("failed to find postmaster pid: %s", err)
}
pid, err := strconv.Atoi(string(pidStr[:len(pidStr)-1]))
if err != nil {
return -1, fmt.Errorf("postmaster pid is not an integer: %s", err)
}
return pid, nil
}
func getDataDirectory(postmasterPid int) (string, error) {
dataDirectory := os.Getenv("PGDATA")
if dataDirectory != "" {
return dataDirectory, nil
}
dataDirectory, err := filepath.EvalSymlinks("/proc/" + strconv.Itoa(postmasterPid) + "/cwd")
if err != nil {
return "", fmt.Errorf("failed to resolve data directory path: %s", err)
}
return dataDirectory, nil
}
func discoverLogLocation(config *ini.Section, runner *query.Runner) (string, error) {
if config.HasKey("db_host") {
dbHostKey, err := config.GetKey("db_host")
if err != nil {
return "", err
}
dbHost := dbHostKey.String()
if dbHost != "localhost" && dbHost != "127.0.0.1" {
return "", errors.New("detected remote server - Log Insights requires the collector to run on the database server directly for self-hosted systems")
}
}
row, err := runner.QueryRow("SELECT current_setting('log_destination'), current_setting('logging_collector'), current_setting('log_directory')")
if err != nil {
return "", err
}
logDestination := row.GetString(0)
loggingCollector := row.GetString(1)
logDirectory := row.GetString(2)
if logDestination == "syslog" {
return "", errors.New("log_destination detected as syslog - please check our setup guide for rsyslogd or syslog-ng instructions")
} else if logDestination != "stderr" {
return "", fmt.Errorf("unsupported log_destination %s", logDestination)
}
postmasterPid, err := getPostmasterPid()
if err != nil {
return "", err
}
var logLocation string
if loggingCollector == "on" {
if !strings.HasPrefix(logDirectory, "/") {
dataDir, err := getDataDirectory(postmasterPid)
if err != nil {
return "", err
}
logDirectory = dataDir + "/" + logDirectory
}
logLocation = logDirectory
} else {
// assume stdout/stderr redirect to logfile, typical with postgresql-common on Ubuntu/Debian
logFile, err := filepath.EvalSymlinks("/proc/" + strconv.FormatInt(int64(postmasterPid), 10) + "/fd/1")
if err != nil {
return "", err
}
// TODO: should we use the directory of this file rather than the file itself?
logLocation = logFile
}
return logLocation, nil
}
|
// Copyright 2020 The SwiftShader Authors. 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 cov
import (
"fmt"
"sort"
"strings"
)
type treeFile struct {
tcm TestCoverageMap
spangroups map[SpanGroupID]SpanGroup
allSpans SpanList
}
func newTreeFile() *treeFile {
return &treeFile{
tcm: TestCoverageMap{},
spangroups: map[SpanGroupID]SpanGroup{},
}
}
// Tree represents source code coverage across a tree of different processes.
// Each tree node is addressed by a Path.
type Tree struct {
initialized bool
strings Strings
spans map[Span]SpanID
testRoot Test
files map[string]*treeFile
}
func (t *Tree) init() {
if !t.initialized {
t.strings.m = map[string]StringID{}
t.spans = map[Span]SpanID{}
t.testRoot = newTest()
t.files = map[string]*treeFile{}
t.initialized = true
}
}
// Spans returns all the spans used by the tree
func (t *Tree) Spans() SpanList {
out := make(SpanList, len(t.spans))
for span, id := range t.spans {
out[id] = span
}
return out
}
// FileSpanGroups returns all the span groups for the given file
func (t *Tree) FileSpanGroups(path string) map[SpanGroupID]SpanGroup {
return t.files[path].spangroups
}
// FileCoverage returns the TestCoverageMap for the given file
func (t *Tree) FileCoverage(path string) TestCoverageMap {
return t.files[path].tcm
}
// Tests returns the root test
func (t *Tree) Tests() *Test { return &t.testRoot }
// Strings returns the string table
func (t *Tree) Strings() Strings { return t.strings }
func (t *Tree) index(path Path) []indexedTest {
out := make([]indexedTest, len(path))
test := &t.testRoot
for i, p := range path {
name := t.strings.index(p)
test, out[i] = test.index(name)
}
return out
}
func (t *Tree) addSpans(spans SpanList) SpanSet {
out := make(SpanSet, len(spans))
for _, s := range spans {
id, ok := t.spans[s]
if !ok {
id = SpanID(len(t.spans))
t.spans[s] = id
}
out[id] = struct{}{}
}
return out
}
// Add adds the coverage information cov to the tree node addressed by path.
func (t *Tree) Add(path Path, cov *Coverage) {
t.init()
tests := t.index(path)
nextFile:
// For each file with coverage...
for _, file := range cov.Files {
// Lookup or create the file's test coverage map
tf, ok := t.files[file.Path]
if !ok {
tf = newTreeFile()
t.files[file.Path] = tf
}
for _, span := range file.Covered {
tf.allSpans.Add(span)
}
for _, span := range file.Uncovered {
tf.allSpans.Add(span)
}
// Add all the spans to the map, get the span ids
spans := t.addSpans(file.Covered)
// Starting from the test root, walk down the test tree.
tcm, test := tf.tcm, t.testRoot
parent := (*TestCoverage)(nil)
for _, indexedTest := range tests {
if indexedTest.created {
if parent != nil && len(test.children) == 1 {
parent.Spans = parent.Spans.addAll(spans)
delete(parent.Children, indexedTest.index)
} else {
tc := tcm.index(indexedTest.index)
tc.Spans = spans
}
continue nextFile
}
test = test.children[indexedTest.index]
tc := tcm.index(indexedTest.index)
// If the tree node contains spans that are not in this new test,
// we need to push those spans down to all the other children.
if lower := tc.Spans.removeAll(spans); len(lower) > 0 {
// push into each child node
for i := range test.children {
child := tc.Children.index(TestIndex(i))
child.Spans = child.Spans.addAll(lower)
}
// remove from node
tc.Spans = tc.Spans.removeAll(lower)
}
// The spans that are in the new test, but are not part of the tree
// node carry propagating down.
spans = spans.removeAll(tc.Spans)
if len(spans) == 0 {
continue nextFile
}
tcm = tc.Children
parent = tc
}
}
}
// allSpans returns all the spans in use by the TestCoverageMap and its children.
func (t *Tree) allSpans(tf *treeFile, tcm TestCoverageMap) SpanSet {
spans := SpanSet{}
for _, tc := range tcm {
for id := tc.Group; id != nil; id = tf.spangroups[*id].Extend {
group := tf.spangroups[*id]
spans = spans.addAll(group.Spans)
}
spans = spans.addAll(tc.Spans)
spans = spans.addAll(spans.invertAll(t.allSpans(tf, tc.Children)))
}
return spans
}
// StringID is an identifier of a string
type StringID int
// Strings holds a map of string to identifier
type Strings struct {
m map[string]StringID
s []string
}
func (s *Strings) index(str string) StringID {
i, ok := s.m[str]
if !ok {
i = StringID(len(s.s))
s.s = append(s.s, str)
s.m[str] = i
}
return i
}
// TestIndex is an child test index
type TestIndex int
// Test is an collection of named sub-tests
type Test struct {
indices map[StringID]TestIndex
children []Test
}
func newTest() Test {
return Test{
indices: map[StringID]TestIndex{},
}
}
type indexedTest struct {
index TestIndex
created bool
}
func (t *Test) index(name StringID) (*Test, indexedTest) {
idx, ok := t.indices[name]
if !ok {
idx = TestIndex(len(t.children))
t.children = append(t.children, newTest())
t.indices[name] = idx
}
return &t.children[idx], indexedTest{idx, !ok}
}
type namedIndex struct {
name string
idx TestIndex
}
func (t Test) byName(s Strings) []namedIndex {
out := make([]namedIndex, len(t.children))
for id, idx := range t.indices {
out[idx] = namedIndex{s.s[id], idx}
}
sort.Slice(out, func(i, j int) bool { return out[i].name < out[j].name })
return out
}
func (t Test) String(s Strings) string {
sb := strings.Builder{}
for i, n := range t.byName(s) {
child := t.children[n.idx]
if i > 0 {
sb.WriteString(" ")
}
sb.WriteString(n.name)
if len(child.children) > 0 {
sb.WriteString(fmt.Sprintf(":%v", child.String(s)))
}
}
return "{" + sb.String() + "}"
}
// TestCoverage holds the coverage information for a deqp test group / leaf.
// For example:
// The deqp test group may hold spans that are common for all children, and may
// also optionally hold child nodes that describe coverage that differs per
// child test.
type TestCoverage struct {
Spans SpanSet
Group *SpanGroupID
Children TestCoverageMap
}
func (tc TestCoverage) String(t *Test, s Strings) string {
sb := strings.Builder{}
sb.WriteString("{")
if len(tc.Spans) > 0 {
sb.WriteString(tc.Spans.String())
}
if tc.Group != nil {
sb.WriteString(" <")
sb.WriteString(fmt.Sprintf("%v", *tc.Group))
sb.WriteString(">")
}
if len(tc.Children) > 0 {
sb.WriteString(" ")
sb.WriteString(tc.Children.String(t, s))
}
sb.WriteString("}")
return sb.String()
}
// deletable returns true if the TestCoverage provides no data.
func (tc TestCoverage) deletable() bool {
return len(tc.Spans) == 0 && tc.Group == nil && len(tc.Children) == 0
}
// TestCoverageMap is a map of TestIndex to *TestCoverage.
type TestCoverageMap map[TestIndex]*TestCoverage
// traverse performs a depth first traversal of the TestCoverage tree.
func (tcm TestCoverageMap) traverse(cb func(*TestCoverage)) {
for _, tc := range tcm {
cb(tc)
tc.Children.traverse(cb)
}
}
func (tcm TestCoverageMap) String(t *Test, s Strings) string {
sb := strings.Builder{}
for _, n := range t.byName(s) {
if child, ok := tcm[n.idx]; ok {
sb.WriteString(fmt.Sprintf("\n%v: %v", n.name, child.String(&t.children[n.idx], s)))
}
}
if sb.Len() > 0 {
sb.WriteString("\n")
}
return indent(sb.String())
}
func newTestCoverage() *TestCoverage {
return &TestCoverage{
Children: TestCoverageMap{},
Spans: SpanSet{},
}
}
func (tcm TestCoverageMap) index(idx TestIndex) *TestCoverage {
tc, ok := tcm[idx]
if !ok {
tc = newTestCoverage()
tcm[idx] = tc
}
return tc
}
// SpanID is an identifier of a span in a Tree.
type SpanID int
// SpanSet is a set of SpanIDs.
type SpanSet map[SpanID]struct{}
// SpanIDList is a list of SpanIDs
type SpanIDList []SpanID
// Compare returns -1 if l comes before o, 1 if l comes after o, otherwise 0.
func (l SpanIDList) Compare(o SpanIDList) int {
switch {
case len(l) < len(o):
return -1
case len(l) > len(o):
return 1
}
for i, a := range l {
b := o[i]
switch {
case a < b:
return -1
case a > b:
return 1
}
}
return 0
}
// List returns the full list of sorted span ids.
func (s SpanSet) List() SpanIDList {
out := make(SpanIDList, 0, len(s))
for span := range s {
out = append(out, span)
}
sort.Slice(out, func(i, j int) bool { return out[i] < out[j] })
return out
}
func (s SpanSet) String() string {
sb := strings.Builder{}
sb.WriteString(`[`)
l := s.List()
for i, span := range l {
if i > 0 {
sb.WriteString(`, `)
}
sb.WriteString(fmt.Sprintf("%v", span))
}
sb.WriteString(`]`)
return sb.String()
}
func (s SpanSet) contains(rhs SpanID) bool {
_, found := s[rhs]
return found
}
func (s SpanSet) containsAll(rhs SpanSet) bool {
for span := range rhs {
if !s.contains(span) {
return false
}
}
return true
}
func (s SpanSet) remove(rhs SpanID) SpanSet {
out := make(SpanSet, len(s))
for span := range s {
if span != rhs {
out[span] = struct{}{}
}
}
return out
}
func (s SpanSet) removeAll(rhs SpanSet) SpanSet {
out := make(SpanSet, len(s))
for span := range s {
if _, found := rhs[span]; !found {
out[span] = struct{}{}
}
}
return out
}
func (s SpanSet) add(rhs SpanID) SpanSet {
out := make(SpanSet, len(s)+1)
for span := range s {
out[span] = struct{}{}
}
out[rhs] = struct{}{}
return out
}
func (s SpanSet) addAll(rhs SpanSet) SpanSet {
out := make(SpanSet, len(s)+len(rhs))
for span := range s {
out[span] = struct{}{}
}
for span := range rhs {
out[span] = struct{}{}
}
return out
}
func (s SpanSet) invert(rhs SpanID) SpanSet {
if s.contains(rhs) {
return s.remove(rhs)
}
return s.add(rhs)
}
func (s SpanSet) invertAll(rhs SpanSet) SpanSet {
out := make(SpanSet, len(s)+len(rhs))
for span := range s {
if !rhs.contains(span) {
out[span] = struct{}{}
}
}
for span := range rhs {
if !s.contains(span) {
out[span] = struct{}{}
}
}
return out
}
// SpanGroupID is an identifier of a SpanGroup.
type SpanGroupID int
// SpanGroup holds a number of spans, potentially extending from another
// SpanGroup.
type SpanGroup struct {
Spans SpanSet
Extend *SpanGroupID
}
func newSpanGroup() SpanGroup {
return SpanGroup{Spans: SpanSet{}}
}
func indent(s string) string {
return strings.TrimSuffix(strings.ReplaceAll(s, "\n", "\n "), " ")
}
|
package hash
import "reflect"
type Entry struct {
Name string
Numbers []int
}
func hasDuplicates(es []*Entry) bool {
m := make(map[uint64][]*Entry)
for i, e := range es {
h := deriveHash(e)
for _, f := range m[h] {
if reflect.DeepEqual(e, f) {
return true
}
}
if _, ok := m[h]; !ok {
m[h] = []*Entry{es[i]}
}
}
return false
}
|
package rand
const (
mtSize = 624
mtPeriod = 397
mtDiff = mtSize - mtPeriod
)
type MT struct {
Data []uint32
Index uint32
}
var MATRIX [2]uint32
var y, i uint32
// MACROS
func m32(val uint32) uint32 {
return (0x80000000 & val)
}
func l31(val uint32) uint32 {
return (0x7FFFFFFF & val)
}
func isOdd(val uint32) uint32 {
return (val & 1)
}
func unroll(M *MT, i *uint32, y *uint32) {
*y = m32(M.Data[*i]) | l31(M.Data[(*i)+1])
M.Data[*i] = M.Data[*i-mtDiff] ^ (*y >> 1) ^ MATRIX[isOdd(*y)]
(*i)++
}
func CreateRandom() *MT {
mt := &MT{}
mt.Data = make([]uint32, mtSize)
mt.Index = 0
return mt
}
func (M *MT) GenerateNumbers() {
MATRIX[0] = 0
MATRIX[1] = 0x9908b0df
for i = 0; i < mtDiff-1; i++ {
y = m32(M.Data[i]) | l31(M.Data[i+1])
M.Data[i] = M.Data[i+mtPeriod] ^ (y >> 1) ^ MATRIX[isOdd(y)]
i++
y = m32(M.Data[i]) | l31(M.Data[i+1])
M.Data[i] = M.Data[i+mtPeriod] ^ (y >> 1) ^ MATRIX[isOdd(y)]
}
for i = mtDiff; i < (mtSize - 1); {
unroll(M, &i, &y)
unroll(M, &i, &y)
unroll(M, &i, &y)
unroll(M, &i, &y)
unroll(M, &i, &y)
unroll(M, &i, &y)
unroll(M, &i, &y)
unroll(M, &i, &y)
unroll(M, &i, &y)
unroll(M, &i, &y)
unroll(M, &i, &y)
}
y = m32(M.Data[mtSize-1]) | l31(M.Data[mtSize-1])
M.Data[mtSize-1] = M.Data[mtPeriod-1] ^ (y >> 1) ^ MATRIX[isOdd(y)]
}
func (M *MT) Seed(value uint32) {
M.Data[0] = value
M.Index = 0
for i = 1; i < mtSize; i++ {
M.Data[i] = 0x6c078965*(M.Data[i-1]^M.Data[i-1]>>30) + i
}
}
func (M *MT) RandU32() uint32 {
if M.Index == 0 {
M.GenerateNumbers()
}
y = M.Data[M.Index]
y ^= y >> 11
y ^= y << 7 & 0x9d2c5680
y ^= y << 15 & 0xefc60000
y ^= y >> 18
M.Index++
if M.Index == mtSize {
M.Index = 0
}
return y
}
|
// SPDX-License-Identifier: MIT
// Package cmd 提供子命令的相关功能
package cmd
import (
"flag"
"fmt"
"io"
"os"
"github.com/issue9/cmdopt"
"github.com/issue9/term/v3/colors"
"golang.org/x/text/message"
"github.com/caixw/apidoc/v7/core"
"github.com/caixw/apidoc/v7/internal/locale"
)
// 命令行输出的表格中,每一列为了对齐填补的空格数量。
const tail = 3
var printers = map[core.MessageType]*printer{
core.Erro: {
out: os.Stderr,
color: colors.Red,
prefix: locale.ErrorPrefix,
},
core.Warn: {
out: os.Stderr,
color: colors.Cyan,
prefix: locale.WarnPrefix,
},
core.Info: {
out: os.Stdout,
color: colors.Default,
prefix: locale.InfoPrefix,
},
core.Succ: {
out: os.Stdout,
color: colors.Green,
prefix: locale.SuccessPrefix,
},
}
type printer struct {
out io.Writer
color colors.Color
prefix message.Reference
}
type uri core.URI
func (u uri) Get() any { return string(u) }
func (u *uri) Set(v string) error {
*u = uri(core.FileURI(v))
return nil
}
func (u *uri) String() string { return core.URI(*u).String() }
func (u uri) URI() core.URI { return core.URI(u) }
// Init 初始化 cmdopt.CmdOpt 实例
func Init(out io.Writer) *cmdopt.CmdOpt {
command := &cmdopt.CmdOpt{
Output: out,
ErrorHandling: flag.ExitOnError,
Header: locale.Sprintf(locale.CmdUsage, core.Name),
Footer: locale.Sprintf(locale.CmdUsageFooter, core.OfficialURL, core.RepoURL),
OptionsTitle: locale.Sprintf(locale.CmdUsageOptions),
CommandsTitle: locale.Sprintf(locale.CmdUsageCommands),
NotFound: func(name string) string {
return locale.Sprintf(locale.CmdNotFound, name)
},
}
command.Help("help", locale.Sprintf(locale.CmdHelpUsage))
initBuild(command)
initDetect(command)
initLang(command)
initLocale(command)
initSyntax(command)
initVersion(command)
initMock(command)
initStatic(command)
initLSP(command)
return command
}
func messageHandle(msg *core.Message) {
printers[msg.Type].print(msg.Message)
}
func (p *printer) print(msg any) {
if _, err := colors.Fprint(p.out, colors.Normal, p.color, colors.Default, locale.New(p.prefix)); err != nil {
panic(err)
}
if _, err := fmt.Fprintln(p.out, msg); err != nil {
panic(err)
}
}
|
package elasticsearch
import (
"fmt"
"github.com/olivere/elastic"
)
type ElasticSearch struct {
Name string
Mapping map[string]interface{}
client *elastic.Client
}
type ElasticSearchClientReq struct {
Host string
Port string
SecondaryPort string
IndexName string
Mapping map[string]interface{}
}
func New(params *ElasticSearchClientReq) (es *ElasticSearch, err error) {
client, err := elastic.NewClient(
elastic.SetURL(
fmt.Sprintf("http://%s:%s", params.Host, params.Port),
fmt.Sprintf("http://%s:%s", params.Host, params.SecondaryPort),
),
elastic.SetSniff(false),
)
if err != nil {
return
}
es = &ElasticSearch{
client: client,
Name: params.IndexName,
Mapping: params.Mapping,
}
return
}
|
package datastructandalgorithm
//求解next数组
func next(sub string) []int {
subSlice := []byte(sub)
subLength := len(subSlice)
next := make([]int, subLength)
next[0] = 0
/*
求解相同前缀和后移获取next数组可以同时跑
这里为了直观,分两步(优化见moreEffectiveNext函数)
*/
//1.求解相同前缀、后缀长度数组
for i, j := 0, 1; j < subLength; j++ {
if subSlice[i] == subSlice[j] {
next[j] = i + 1
i++
} else {
i = 0
}
}
//2.后移,第一位补-1
for i := subLength - 1; i > 0; i-- {
next[i] = next[i-1]
}
next[0] = -1
return next
}
//求解next数组(优化的next数组)
func moreEffectiveNext(sub string) []int {
subSlice := []byte(sub)
subLength := len(subSlice)
next := make([]int, subLength)
next[0] = -1
next[1] = 0
for i, j := 0, 1; j < subLength-1; j++ {
if subSlice[i] == subSlice[j] {
next[j+1] = i + 1
i++
} else {
i = 0
}
}
return next
}
func SubString(str, sub string) (n int, ok bool) {
next := moreEffectiveNext(sub)
strSlice := []byte(str)
subSlice := []byte(sub)
strLength := len(strSlice)
subLength := len(subSlice)
i, j := 0, 0
for i < strLength && j < subLength {
if j == -1 || strSlice[i] == subSlice[j] {
i++
j++
} else {
j = next[j]
}
}
if j == subLength {
return i - j, true
}
return -1, false
}
//字符串匹配、朴素算法
func SubStringNormal(str, sub string) (n int, ok bool) {
strSlice := []byte(str)
subSlice := []byte(sub)
strLength := len(strSlice)
subLength := len(subSlice)
i, j := 0, 0
nexti := i + 1
for i < strLength && j < subLength {
if strSlice[i] == subSlice[j] {
i++
j++
} else {
j = 0
i = nexti
nexti++
}
}
if j == subLength {
return i - j, true
}
return -1, false
} |
package tool
import "encoding/json"
func JSONToString(data interface{}) string {
if marshal, err := json.Marshal(data); err == nil {
return string(marshal)
}
return ""
}
|
package gorm2
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/traPtitech/trap-collection-server/src/domain"
"github.com/traPtitech/trap-collection-server/src/domain/values"
"github.com/traPtitech/trap-collection-server/src/repository"
"github.com/traPtitech/trap-collection-server/src/repository/gorm2/migrate"
"gorm.io/gorm"
)
type GameV2 struct {
db *DB
}
func NewGameV2(db *DB) *GameV2 {
return &GameV2{
db: db,
}
}
func (g *GameV2) SaveGame(ctx context.Context, game *domain.Game) error {
db, err := g.db.getDB(ctx)
if err != nil {
return fmt.Errorf("failed to get db: %w", err)
}
gameTable := migrate.GameTable2{
ID: uuid.UUID(game.GetID()),
Name: string(game.GetName()),
Description: string(game.GetDescription()),
CreatedAt: game.GetCreatedAt(),
}
err = db.Create(&gameTable).Error
if err != nil {
return fmt.Errorf("failed to save game: %w", err)
}
return nil
}
func (g *GameV2) UpdateGame(ctx context.Context, game *domain.Game) error {
db, err := g.db.getDB(ctx)
if err != nil {
return fmt.Errorf("failed to get db: %w", err)
}
gameTable := migrate.GameTable2{
Name: string(game.GetName()),
Description: string(game.GetDescription()),
}
result := db.
Where("id = ?", uuid.UUID(game.GetID())).
Updates(gameTable)
err = result.Error
if err != nil {
return fmt.Errorf("failed to update game: %w", err)
}
if result.RowsAffected == 0 {
return repository.ErrNoRecordUpdated
}
return nil
}
func (g *GameV2) RemoveGame(ctx context.Context, gameID values.GameID) error {
db, err := g.db.getDB(ctx)
if err != nil {
return fmt.Errorf("failed to get db: %w", err)
}
result := db.
Where("id = ?", uuid.UUID(gameID)).
Delete(&migrate.GameTable2{})
err = result.Error
if err != nil {
return fmt.Errorf("failed to remove game: %w", err)
}
if result.RowsAffected == 0 {
return repository.ErrNoRecordDeleted
}
return nil
}
func (g *GameV2) GetGame(ctx context.Context, gameID values.GameID, lockType repository.LockType) (*domain.Game, error) {
db, err := g.db.getDB(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get db: %w", err)
}
db, err = g.db.setLock(db, lockType)
if err != nil {
return nil, fmt.Errorf("failed to set lock type: %w", err)
}
var game migrate.GameTable2
err = db.
Where("id = ?", uuid.UUID(gameID)).
Take(&game).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, repository.ErrRecordNotFound
}
if err != nil {
return nil, fmt.Errorf("failed to get game: %w", err)
}
return domain.NewGame(
values.NewGameIDFromUUID(game.ID),
values.NewGameName(game.Name),
values.NewGameDescription(game.Description),
game.CreatedAt,
), nil
}
func (g *GameV2) GetGames(ctx context.Context, limit int, offset int) ([]*domain.Game, int, error) {
db, err := g.db.getDB(ctx)
if err != nil {
return nil, 0, fmt.Errorf("failed to get db: %w", err)
}
if limit < 0 {
return nil, 0, repository.ErrNegativeLimit
}
if limit == 0 && offset != 0 {
return nil, 0, errors.New("bad limit and offset")
}
var games []migrate.GameTable2
query := db.Order("created_at DESC")
if limit > 0 {
query = query.Limit(limit)
}
if limit > 0 && offset > 0 {
query = query.Offset(offset)
}
err = query.
Find(&games).Error
if err != nil {
return nil, 0, fmt.Errorf("failed to get games: %w", err)
}
gamesDomain := make([]*domain.Game, 0, len(games))
for _, game := range games {
gamesDomain = append(gamesDomain, domain.NewGame(
values.NewGameIDFromUUID(game.ID),
values.NewGameName(game.Name),
values.NewGameDescription(game.Description),
game.CreatedAt,
))
}
var gamesNumber int64
err = db.Table("games").
Where("deleted_at IS NULL").
Count(&gamesNumber).Error
if err != nil {
return nil, 0, fmt.Errorf("failed to get games number: %w", err)
}
return gamesDomain, int(gamesNumber), nil
}
func (g *GameV2) GetGamesByUser(ctx context.Context, userID values.TraPMemberID, limit int, offset int) ([]*domain.Game, int, error) {
db, err := g.db.getDB(ctx)
if err != nil {
return nil, 0, fmt.Errorf("failed to get db: %w", err)
}
if limit < 0 {
return nil, 0, repository.ErrNegativeLimit
}
if limit == 0 && offset != 0 {
return nil, 0, errors.New("bad limit and offset")
}
var games []migrate.GameTable2
tx := db.Joins("JOIN game_management_roles ON game_management_roles.game_id = games.id").
Where("game_management_roles.user_id = ?", uuid.UUID(userID)).
Session(&gorm.Session{})
query := tx.
Order("created_at DESC")
if limit > 0 {
query = query.Limit(limit)
}
if limit > 0 && offset > 0 {
query = query.Offset(offset)
}
err = query.
Find(&games).Error
if err != nil {
return nil, 0, fmt.Errorf("failed to get games: %w", err)
}
gamesDomain := make([]*domain.Game, 0, len(games))
for _, game := range games {
gamesDomain = append(gamesDomain, domain.NewGame(
values.NewGameIDFromUUID(game.ID),
values.NewGameName(game.Name),
values.NewGameDescription(game.Description),
game.CreatedAt,
))
}
var gameNumber int64
err = tx.
Table("games").
Where("deleted_at IS NULL").
Count(&gameNumber).Error
if err != nil {
return nil, 0, fmt.Errorf("failed to get games number: %w", err)
}
return gamesDomain, int(gameNumber), nil
}
func (g *GameV2) GetGamesByIDs(ctx context.Context, gameIDs []values.GameID, lockType repository.LockType) ([]*domain.Game, error) {
db, err := g.db.getDB(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get db: %w", err)
}
db, err = g.db.setLock(db, lockType)
if err != nil {
return nil, fmt.Errorf("failed to set lock type: %w", err)
}
uuidGameIDs := make([]uuid.UUID, 0, len(gameIDs))
for _, gameID := range gameIDs {
uuidGameIDs = append(uuidGameIDs, uuid.UUID(gameID))
}
var games []migrate.GameTable2
err = db.
Where("id IN ?", uuidGameIDs).
Find(&games).Error
if err != nil {
return nil, fmt.Errorf("failed to get games: %w", err)
}
gamesDomains := make([]*domain.Game, 0, len(games))
for _, game := range games {
gamesDomains = append(gamesDomains, domain.NewGame(
values.NewGameIDFromUUID(game.ID),
values.NewGameName(game.Name),
values.NewGameDescription(game.Description),
game.CreatedAt,
))
}
return gamesDomains, nil
}
|
package main
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
"github.com/dopgm/goconvey-settings-file/config"
)
func TestStub(t *testing.T) {
Convey("Test is working.", t, func() {
So(true, ShouldBeTrue)
})
}
func TestConfig(t *testing.T) {
Convey("Config should be accessible", t, func() {
So(config.GetEnv(), ShouldEqual, "dev")
})
}
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
package aws
import (
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/golang/mock/gomock"
)
func (a *AWSTestSuite) TestDynamoDBEnsureTableDeleted() {
gomock.InOrder(
a.Mocks.API.DynamoDB.EXPECT().
DescribeTable(gomock.Any(), gomock.Any()).
Return(&dynamodb.DescribeTableOutput{}, nil),
a.Mocks.API.DynamoDB.EXPECT().
DeleteTable(gomock.Any(), gomock.Any()).
Return(&dynamodb.DeleteTableOutput{}, nil),
)
err := a.Mocks.AWS.DynamoDBEnsureTableDeleted("table-name", a.Mocks.Log.Logger)
a.Assert().NoError(err)
}
|
package main
import (
"github.com/Kalimaha/ginkgo/reporter"
"github.com/aws/aws-lambda-go/events"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestHello(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecsWithCustomReporters(t, "Hello API Suite", []Reporter{reporter.New()})
}
var _ = Describe("Hello", func() {
var message *events.APIGatewayProxyResponse
BeforeEach(func() {
message, _ = handler(events.APIGatewayProxyRequest{})
})
It("returns HTTP 200 - OK", func() {
Expect(message.StatusCode).To(Equal(200))
})
It("returns 'Ciao!' in the body", func() {
Expect(message.Body).To(Equal("Ciao!"))
})
})
|
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func doubleTrouble(q string) uint {
var r uint = 1
n := len(q) / 2
for i := 0; i < n; i++ {
if ((q[i] == 'A') && (q[i+n] == 'B')) ||
((q[i] == 'B') && (q[i+n] == 'A')) {
r = 0
break
} else if (q[i] == '*') && (q[i+n] == '*') {
r *= 2
}
}
return r
}
func main() {
data, err := os.Open(os.Args[1])
if err != nil {
log.Fatal(err)
}
defer data.Close()
scanner := bufio.NewScanner(data)
for scanner.Scan() {
fmt.Println(doubleTrouble(scanner.Text()))
}
}
|
package handler
import (
"main/app"
"strconv"
)
const pageSize = 10 // 每页显示的数据量
func offset(page int) int {
if page == 0 {
return 0
}
return (page - 1) * pageSize
}
// 成功时返回的数据,格式化失败时返回空字符串
func succ(data interface{}) app.SuccRes {
res := app.SuccRes{
Code: 0,
Msg: "success",
Data: data,
}
return res
}
// 失败时返回的数据,格式化失败时返回空字符串
func failed(msg string) app.ErrRes {
res := app.ErrRes{
Code: -1,
Msg: msg,
}
return res
}
// 根据数据总数、当前页页码、每页显示的数据量计算要显示的页码(当前页的前2后3)
func pages(total, cur, num int) []string {
var res []string
ps := total / num // 总页数
if (total % num) != 0 {
ps++
}
for i := cur - 2; i <= ps; i++ {
if len(res) == 6 {
break
}
if i > 0 {
k := strconv.Itoa(i)
if i == cur {
k = "_"
}
res = append(res, k)
}
}
return res
}
|
/*
Copyright 2014 Google Inc. 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 client
import (
"time"
)
// FlagSet abstracts the flag interface for compatibility with both Golang "flag"
// and cobra pflags (Posix style).
type FlagSet interface {
StringVar(p *string, name, value, usage string)
BoolVar(p *bool, name string, value bool, usage string)
UintVar(p *uint, name string, value uint, usage string)
DurationVar(p *time.Duration, name string, value time.Duration, usage string)
Float32Var(p *float32, name string, value float32, usage string)
IntVar(p *int, name string, value int, usage string)
}
// BindClientConfigFlags registers a standard set of CLI flags for connecting to a Kubernetes API server.
// TODO this method is superceded by pkg/client/clientcmd/client_builder.go
func BindClientConfigFlags(flags FlagSet, config *Config) {
flags.StringVar(&config.Host, "master", config.Host, "The address of the Kubernetes API server")
flags.StringVar(&config.Version, "api_version", config.Version, "The API version to use when talking to the server")
flags.BoolVar(&config.Insecure, "insecure_skip_tls_verify", config.Insecure, "If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure.")
flags.StringVar(&config.CertFile, "client_certificate", config.CertFile, "Path to a client key file for TLS.")
flags.StringVar(&config.KeyFile, "client_key", config.KeyFile, "Path to a client key file for TLS.")
flags.StringVar(&config.CAFile, "certificate_authority", config.CAFile, "Path to a cert. file for the certificate authority.")
flags.Float32Var(&config.QPS, "max_outgoing_qps", config.QPS, "Maximum number of queries per second that could be issued by this client.")
flags.IntVar(&config.Burst, "max_outgoing_burst", config.Burst, "Maximum throttled burst")
}
func BindKubeletClientConfigFlags(flags FlagSet, config *KubeletConfig) {
flags.BoolVar(&config.EnableHttps, "kubelet_https", config.EnableHttps, "Use https for kubelet connections")
flags.UintVar(&config.Port, "kubelet_port", config.Port, "Kubelet port")
flags.DurationVar(&config.HTTPTimeout, "kubelet_timeout", config.HTTPTimeout, "Timeout for kubelet operations")
flags.StringVar(&config.CertFile, "kubelet_client_certificate", config.CertFile, "Path to a client key file for TLS.")
flags.StringVar(&config.KeyFile, "kubelet_client_key", config.KeyFile, "Path to a client key file for TLS.")
flags.StringVar(&config.CAFile, "kubelet_certificate_authority", config.CAFile, "Path to a cert. file for the certificate authority.")
}
|
package main
// #include <stdlib.h>
// #include <classification.h>
import "C"
import (
"container/list"
"sync"
"time"
)
const (
MEM_LEAK_CORRECTION = 150 * 1024 * 1024
)
type GPUMem struct {
InitLock sync.Mutex
LRU *list.List
LRULock sync.Mutex
}
type LoadedModelsMap struct {
sync.RWMutex
Models map[string]*ModelEntry
}
type ModelEntry struct {
sync.RWMutex
Classifier C.c_model
InGPU bool
}
var loadedModels LoadedModelsMap
var MemoryManager *GPUMem
func (g *GPUMem) GetCurrentMemUsage() uint64 {
return uint64(C.get_total_gpu_memory()) - uint64(C.get_free_gpu_memory())
}
func (g *GPUMem) CanLoad(m *Model) bool {
if maxCachedModels > 0 && g.LRU.Len() == maxCachedModels {
Debugf("Can't fit a new model due to model count limit")
return false
}
Debugf("Evaluating if %v can fit", m.Name)
//Debugf("First time: curr: %v, estimated %v, max: %v", g.GetCurrentMemUsage(), STATIC_USAGE+m.estimatedGPUMemSize(), maxGPUMemUsage)
Debugf("curr: %v, estimated after load: %v, max: %v", g.GetCurrentMemUsage(), g.GetCurrentMemUsage()+m.estimatedGPUMemSize(), maxGPUMemUsage-MEM_LEAK_CORRECTION)
return g.GetCurrentMemUsage()+m.estimatedGPUMemSize() < maxGPUMemUsage-MEM_LEAK_CORRECTION
}
func (g *GPUMem) EvictLRU() {
Debugf("Eviction beginning!")
//time.Sleep(10 * time.Second)
Debugf("Currently %d entries in LRU", g.LRU.Len())
g.LRULock.Lock()
evicted := g.LRU.Back()
if evicted == nil {
panic("Exceeded mem usage, but no models loaded!")
return
}
model := (evicted.Value).(Model)
/*
// Make sure we aren't evicting ourselves
if model.Name == m.Name {
evicted = evicted.Prev()
if evicted == nil {
panic("")
}
}
*/
g.LRU.Remove(evicted)
g.LRULock.Unlock()
Debugf("%v is the lucky victim", model.Name)
entry, ok := loadedModels.Models[model.Name]
if !ok {
panic("Tried to evict model not in loaded models: " + model.Name)
} else if !entry.InGPU {
panic("Tried to evict model not in GPU: " + model.Name)
}
entry.Lock()
g.MoveToCPU(&model, entry)
entry.Unlock()
}
func (g *GPUMem) GetStaticGPUUsage() uint64 {
g.InitLock.Lock()
g.LRULock.Lock()
loadedModels.Lock()
for _, entry := range loadedModels.Models {
if entry.InGPU {
C.move_to_cpu(entry.Classifier)
}
}
initialUsage := g.GetCurrentMemUsage()
Debugf("initial: %v", initialUsage)
for _, entry := range loadedModels.Models {
if entry.InGPU {
C.move_to_gpu(entry.Classifier)
}
}
loadedModels.Unlock()
g.LRULock.Unlock()
g.InitLock.Unlock()
return initialUsage
}
func (g *GPUMem) InitModel(m *Model) *ModelEntry {
Debugf("Initializing model: %v", m.Name)
Debugf("Current mem usage: %d mebibytes", g.GetCurrentMemUsage()/(1024*1024))
g.InitLock.Lock()
for !g.CanLoad(m) {
g.EvictLRU()
}
cmean := C.CString(m.MeanPath)
clabel := C.CString(m.LabelsPath)
cweights := C.CString(m.WeightsPath)
cmodel := C.CString(m.ModelPath)
start := time.Now()
cclass, err := C.model_init(cmodel, cweights, cmean, clabel,
C.size_t(NUM_CONTEXTS), C.size_t(MAX_BATCH_AMT))
LogTimef("%v model_init", start, m.Name)
if err != nil {
handleError("init failed: ", err)
}
C.move_to_cpu(cclass)
C.move_to_gpu(cclass)
g.LRULock.Lock()
Debugf("Adding to LRU: %v", m.Name)
g.LRU.PushBack(*m)
g.LRULock.Unlock()
g.InitLock.Unlock()
return &ModelEntry{
Classifier: cclass,
InGPU: true,
}
}
func (g *GPUMem) UpdateLRU(m *Model) {
Debugf("In update LRU %v", m.Name)
g.LRULock.Lock()
defer g.LRULock.Unlock()
for e := g.LRU.Front(); e != nil; e = e.Next() {
model := (e.Value).(Model)
if model.Name == m.Name {
g.LRU.MoveToFront(e)
return
}
}
panic("Tried to update model, but not in LRU: " + m.Name)
}
func (g *GPUMem) MoveToCPU(m *Model, entry *ModelEntry) {
if !entry.InGPU {
DebugPanic("Attempted to move model not in GPU to CPU: " + m.Name)
}
start := time.Now()
Debugf("%v move to cpu beginning", m.Name)
entry.InGPU = false
C.move_to_cpu(entry.Classifier)
LogTimef("%v move to cpu", start, m.Name)
}
func (g *GPUMem) MoveToGPU(m *Model, entry *ModelEntry, addToLRU bool) {
if entry.InGPU {
DebugPanic("Attempted to move model already in GPU to GPU: " + m.Name)
}
Debugf("About to move %v onto the GPU", m.Name)
g.InitLock.Lock()
for !g.CanLoad(m) {
g.EvictLRU()
}
g.InitLock.Unlock()
start := time.Now()
entry.InGPU = true
if useSync {
C.move_to_gpu(entry.Classifier)
} else {
C.move_to_gpu_async(entry.Classifier)
}
if addToLRU {
g.LRULock.Lock()
g.LRU.PushFront(*m)
g.LRULock.Unlock()
}
LogTimef("%v move to gpu", start, m.Name)
}
func (g *GPUMem) LoadModel(m Model) *ModelEntry {
Debugf("LoadModel begin for %v", m.Name)
Debugf("Currently %d entries in LRU", g.LRU.Len())
var entry *ModelEntry
loadedModels.RLock()
entry, ok := loadedModels.Models[m.Name]
loadedModels.RUnlock()
if !ok {
loadedModels.Lock()
// Ensure no one added this model between the RUnlock and here
_, ok = loadedModels.Models[m.Name]
if !ok {
entry = g.InitModel(&m)
loadedModels.Models[m.Name] = entry
}
loadedModels.Unlock()
} else if !entry.InGPU {
g.MoveToGPU(&m, entry, true)
}
g.UpdateLRU(&m)
return entry
}
func init() {
loadedModels = LoadedModelsMap{
Models: make(map[string]*ModelEntry),
}
MemoryManager = &GPUMem{
LRU: list.New(),
}
}
|
package blockchain
import (
"bytes"
"encoding/gob"
"time"
)
/**
* 区块结构体的定义
*/
type Block struct {
Height int64 //区块高度
TimeStamp int64 //时间戳
Hash []byte //区块的hash
Data []byte //数据
PrevHash []byte //上一个区块的hash
Version string //版本号
Nonce int64 //随机数,用于POW工作量证明算法计算
}
/**
*构建一个区块实例,并返回该区块
*/
func NewBlock(height int64, data []byte, prevHash []byte )(Block){
//1.构建一个block实例,用于生成区块
block := Block{
Height: height,
TimeStamp:time.Now().Unix() ,
Data: data,
PrevHash: prevHash,
Version: "0×01",
}
//2.为新生成的block,寻找合适的nonce
pow := NewPoW(block)
blockHash,nonce := pow.Run()
//3.将block的nonce设置为找到合适的nonce数
block.Nonce = nonce
block.Hash = blockHash
/**
* 调用util.SHA256Hash进行hash计算
问题分析:
①util.SHA256Hash要求一个[]byte参数
②block是一个自定义结构体,与①类型不匹配
解决思路:将block结构体转换为[]byte类型数据
方案:
①block结构体中包含6个字段,其中3个已经是[]byte
②只需将剩余3个字段转换为[]byte类型
③将6个字段[]byte进行拼接即可
*/
//heightBytes,_ := util.IntToBytes(block.Height)
//timeBytes,_ := util.IntToBytes(block.TimeStamp)
//versionBytes := util.StringToBytes(block.Version)
//nonceBytes,_ := util.IntToBytes(block.Nonce)
////bytes.join函数,用于[]byte的拼接
//blockBytes := bytes.Join([][]byte{
// heightBytes,
// timeBytes,
// data,
// prevHash,
// versionBytes,
// nonceBytes,
//}, []byte{})
////4.设置第七个字段
//block.Hash = util.SHA256Hash(blockBytes)
return block
}
/**
* 区块的序列化
*/
func (bk Block) Serialize()([]byte, error){
buff := new(bytes.Buffer)
err := gob.NewEncoder(buff).Encode(bk)
if err != nil{
return nil,err
}
return buff.Bytes(), nil
}
/**
*区块的反序列化
*/
func DeSerialize(data []byte)(*Block, error){
var block Block
err := gob.NewDecoder(bytes.NewReader(data)).Decode(&block)
if err != nil{
return nil, err
}
return &block, nil
} |
// 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 geomfn
import (
"fmt"
"math"
"github.com/cockroachdb/cockroach/pkg/geo"
"github.com/cockroachdb/cockroach/pkg/geo/geopb"
"github.com/cockroachdb/errors"
"github.com/twpayne/go-geom"
)
// AffineMatrix defines an affine transformation matrix for a geom object.
// It is expected to be of the form:
// a b c x_off
// d e f y_off
// g h i z_off
// 0 0 0 1
// Which gets applies onto a coordinate of form:
// (x y z 0)^T
// With the following transformation:
// x' = a*x + b*y + c*z + x_off
// y' = d*x + e*y + f*z + y_off
// z' = g*x + h*y + i*z + z_off
type AffineMatrix [][]float64
// Affine applies a 3D affine transformation onto the given geometry.
// See: https://en.wikipedia.org/wiki/Affine_transformation.
func Affine(g geo.Geometry, m AffineMatrix) (geo.Geometry, error) {
if g.Empty() {
return g, nil
}
t, err := g.AsGeomT()
if err != nil {
return geo.Geometry{}, err
}
newT, err := affine(t, m)
if err != nil {
return geo.Geometry{}, err
}
return geo.MakeGeometryFromGeomT(newT)
}
func affine(t geom.T, m AffineMatrix) (geom.T, error) {
return applyOnCoordsForGeomT(t, func(l geom.Layout, dst, src []float64) error {
var z float64
if l.ZIndex() != -1 {
z = src[l.ZIndex()]
}
newX := m[0][0]*src[0] + m[0][1]*src[1] + m[0][2]*z + m[0][3]
newY := m[1][0]*src[0] + m[1][1]*src[1] + m[1][2]*z + m[1][3]
newZ := m[2][0]*src[0] + m[2][1]*src[1] + m[2][2]*z + m[2][3]
dst[0] = newX
dst[1] = newY
if l.ZIndex() != -1 {
dst[2] = newZ
}
if l.MIndex() != -1 {
dst[l.MIndex()] = src[l.MIndex()]
}
return nil
})
}
// Translate returns a modified Geometry whose coordinates are incremented
// or decremented by the deltas.
func Translate(g geo.Geometry, deltas []float64) (geo.Geometry, error) {
if g.Empty() {
return g, nil
}
t, err := g.AsGeomT()
if err != nil {
return geo.Geometry{}, err
}
newT, err := translate(t, deltas)
if err != nil {
return geo.Geometry{}, err
}
return geo.MakeGeometryFromGeomT(newT)
}
func translate(t geom.T, deltas []float64) (geom.T, error) {
if t.Layout().Stride() != len(deltas) {
err := geom.ErrStrideMismatch{
Got: len(deltas),
Want: t.Layout().Stride(),
}
return nil, errors.Wrap(err, "translating coordinates")
}
var zOff float64
if t.Layout().ZIndex() != -1 {
zOff = deltas[t.Layout().ZIndex()]
}
return affine(
t,
AffineMatrix([][]float64{
{1, 0, 0, deltas[0]},
{0, 1, 0, deltas[1]},
{0, 0, 1, zOff},
{0, 0, 0, 1},
}),
)
}
// Scale returns a modified Geometry whose coordinates are multiplied by the factors.
// REQUIRES: len(factors) >= 2.
func Scale(g geo.Geometry, factors []float64) (geo.Geometry, error) {
var zFactor float64
if len(factors) > 2 {
zFactor = factors[2]
}
return Affine(
g,
AffineMatrix([][]float64{
{factors[0], 0, 0, 0},
{0, factors[1], 0, 0},
{0, 0, zFactor, 0},
{0, 0, 0, 1},
}),
)
}
// ScaleRelativeToOrigin returns a modified Geometry whose coordinates are
// multiplied by the factors relative to the origin.
func ScaleRelativeToOrigin(
g geo.Geometry, factor geo.Geometry, origin geo.Geometry,
) (geo.Geometry, error) {
if g.Empty() {
return g, nil
}
t, err := g.AsGeomT()
if err != nil {
return geo.Geometry{}, err
}
factorG, err := factor.AsGeomT()
if err != nil {
return geo.Geometry{}, err
}
factorPointG, ok := factorG.(*geom.Point)
if !ok {
return geo.Geometry{}, errors.Newf("the scaling factor must be a Point")
}
originG, err := origin.AsGeomT()
if err != nil {
return geo.Geometry{}, err
}
originPointG, ok := originG.(*geom.Point)
if !ok {
return geo.Geometry{}, errors.Newf("the false origin must be a Point")
}
if factorG.Stride() != originG.Stride() {
err := geom.ErrStrideMismatch{
Got: factorG.Stride(),
Want: originG.Stride(),
}
return geo.Geometry{}, errors.Wrap(err, "number of dimensions for the scaling factor and origin must be equal")
}
// This is inconsistent with PostGIS, which allows a POINT EMPTY, but whose
// behavior seems to depend on previous queries in the session, and not
// desirable to reproduce.
if len(originPointG.FlatCoords()) < 2 {
return geo.Geometry{}, errors.Newf("the origin must have at least 2 coordinates")
}
// Offset by the origin, scale, and translate it back to the origin.
offsetDeltas := make([]float64, 0, 3)
offsetDeltas = append(offsetDeltas, -originPointG.X(), -originPointG.Y())
if originG.Layout().ZIndex() != -1 {
offsetDeltas = append(offsetDeltas, -originPointG.Z())
}
retT, err := translate(t, offsetDeltas)
if err != nil {
return geo.Geometry{}, err
}
var xFactor, yFactor, zFactor float64
zFactor = 1
if len(factorPointG.FlatCoords()) < 2 {
// POINT EMPTY results in factors of 0, similar to PostGIS.
xFactor, yFactor = 0, 0
} else {
xFactor, yFactor = factorPointG.X(), factorPointG.Y()
if factorPointG.Layout().ZIndex() != -1 {
zFactor = factorPointG.Z()
}
}
retT, err = affine(
retT,
AffineMatrix([][]float64{
{xFactor, 0, 0, 0},
{0, yFactor, 0, 0},
{0, 0, zFactor, 0},
{0, 0, 0, 1},
}),
)
if err != nil {
return geo.Geometry{}, err
}
for i := range offsetDeltas {
offsetDeltas[i] = -offsetDeltas[i]
}
retT, err = translate(retT, offsetDeltas)
if err != nil {
return geo.Geometry{}, err
}
return geo.MakeGeometryFromGeomT(retT)
}
// Rotate returns a modified Geometry whose coordinates are rotated
// around the origin by a rotation angle.
func Rotate(g geo.Geometry, rotRadians float64) (geo.Geometry, error) {
return Affine(
g,
AffineMatrix([][]float64{
{math.Cos(rotRadians), -math.Sin(rotRadians), 0, 0},
{math.Sin(rotRadians), math.Cos(rotRadians), 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 1},
}),
)
}
// ErrPointOriginEmpty is an error to compare point origin is empty.
var ErrPointOriginEmpty = fmt.Errorf("origin is an empty point")
// RotateWithPointOrigin returns a modified Geometry whose coordinates are rotated
// around the pointOrigin by a rotRadians.
func RotateWithPointOrigin(
g geo.Geometry, rotRadians float64, pointOrigin geo.Geometry,
) (geo.Geometry, error) {
if pointOrigin.ShapeType() != geopb.ShapeType_Point {
return g, errors.New("origin is not a POINT")
}
t, err := pointOrigin.AsGeomT()
if err != nil {
return g, err
}
if t.Empty() {
return g, ErrPointOriginEmpty
}
return RotateWithXY(g, rotRadians, t.FlatCoords()[0], t.FlatCoords()[1])
}
// RotateWithXY returns a modified Geometry whose coordinates are rotated
// around the X and Y by a rotRadians.
func RotateWithXY(g geo.Geometry, rotRadians, x, y float64) (geo.Geometry, error) {
cos, sin := math.Cos(rotRadians), math.Sin(rotRadians)
return Affine(
g,
AffineMatrix{
{cos, -sin, 0, x - x*cos + y*sin},
{sin, cos, 0, y - x*sin - y*cos},
{0, 0, 1, 0},
{0, 0, 0, 1},
},
)
}
// RotateX returns a modified Geometry whose coordinates are rotated about
// the X axis by rotRadians
func RotateX(g geo.Geometry, rotRadians float64) (geo.Geometry, error) {
cos, sin := math.Cos(rotRadians), math.Sin(rotRadians)
return Affine(
g,
AffineMatrix{
{1, 0, 0, 0},
{0, cos, -sin, 0},
{0, sin, cos, 0},
{0, 0, 0, 1},
},
)
}
// RotateY returns a modified Geometry whose coordinates are rotated about
// the Y axis by rotRadians
func RotateY(g geo.Geometry, rotRadians float64) (geo.Geometry, error) {
cos, sin := math.Cos(rotRadians), math.Sin(rotRadians)
return Affine(
g,
AffineMatrix{
{cos, 0, sin, 0},
{0, 1, 0, 0},
{-sin, 0, cos, 0},
{0, 0, 0, 1},
},
)
}
// RotateZ returns a modified Geometry whose coordinates are rotated about
// the Z axis by rotRadians
func RotateZ(g geo.Geometry, rotRadians float64) (geo.Geometry, error) {
cos, sin := math.Cos(rotRadians), math.Sin(rotRadians)
return Affine(
g,
AffineMatrix{
{cos, -sin, 0, 0},
{sin, cos, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 1},
},
)
}
// TransScale returns a modified Geometry whose coordinates are
// translate by deltaX and deltaY and scale by xFactor and yFactor
func TransScale(g geo.Geometry, deltaX, deltaY, xFactor, yFactor float64) (geo.Geometry, error) {
return Affine(g,
AffineMatrix([][]float64{
{xFactor, 0, 0, xFactor * deltaX},
{0, yFactor, 0, yFactor * deltaY},
{0, 0, 1, 0},
{0, 0, 0, 1},
}))
}
|
package nano_test
import (
"testing"
"github.com/shibukawa/nanovgo"
"github.com/waybeams/assert"
"github.com/waybeams/waybeams/pkg/env/nano"
)
func TestNanoSurface(t *testing.T) {
t.Run("Instantiable", func(t *testing.T) {
instance := nano.NewSurface()
assert.NotNil(instance)
})
t.Run("Debug Flag", func(t *testing.T) {
instance := nano.NewSurface(nano.Debug())
flags := instance.Flags()
assert.Equal(flags, nanovgo.Debug)
})
t.Run("All Flags", func(t *testing.T) {
instance := nano.NewSurface(nano.AntiAlias(), nano.StencilStrokes(), nano.Debug())
flags := instance.Flags()
assert.Equal(flags, nanovgo.AntiAlias|nanovgo.StencilStrokes|nanovgo.Debug)
})
}
|
package mongo
import (
"fmt"
"gopkg.in/mgo.v2"
)
type Config struct {
Host string
Port string
Username string
Password string
Db string
}
func New(c *Config) *Mongo {
url := fmt.Sprintf("mongodb://%v:%v@%v:%v/%v", c.Username, c.Password, c.Host, c.Port, c.Db)
fmt.Println("mongo:", url)
session, err := mgo.Dial(url)
if err != nil {
panic(err)
}
return &Mongo{
session: session,
db: c.Db,
}
}
type Mongo struct {
session *mgo.Session
db string
}
func (mgoo *Mongo) Model(collection string) *Model {
ss := mgoo.session.Copy()
c := ss.DB(mgoo.db).C(collection)
return &Model{
session: ss,
C: c,
}
}
type Model struct {
session *mgo.Session
C *mgo.Collection
}
func (model *Model) Close() {
model.session.Close()
}
|
package main
import (
"fmt"
"strings"
"testing"
)
func TestPrimeLess(t *testing.T) {
for k, v := range map[uint]string{
10: "2,3,5,7",
20: "2,3,5,7,11,13,17,19",
100: "2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97",
42: "2,3,5,7,11,13,17,19,23,29,31,37,41"} {
if r := primeLess(k); r != v {
t.Errorf("failed: primeLess %d is %s, got %s",
k, v, r)
}
}
}
func BenchmarkPrimeLess(b *testing.B) {
for i := 0; i < b.N; i++ {
primeLess(uint(i))
}
}
var primes = []uint{2, 3, 5, 7, 11, 13}
func isPrime(a uint) bool {
for b := 0; a%primes[b] > 0; b++ {
if primes[b]*primes[b] > a {
primes = append(primes, a)
return true
}
}
return false
}
func primeSeq() func() uint {
p0 := 0
var i uint
return func() uint {
if p0 < len(primes) {
i = primes[p0]
p0++
return i
}
for i += 2; !isPrime(i); i += 2 {
}
p0++
return i
}
}
func primeLess(a uint) string {
var r []string
nextPrime := primeSeq()
for i := nextPrime(); i < a; i = nextPrime() {
r = append(r, fmt.Sprint(i))
}
return strings.Join(r, ",")
}
|
// 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 wallpaper
import (
"context"
"path/filepath"
"time"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/ash"
"chromiumos/tast/local/chrome/uiauto"
"chromiumos/tast/local/chrome/uiauto/faillog"
"chromiumos/tast/local/media/imgcmp"
"chromiumos/tast/local/screenshot"
"chromiumos/tast/local/wallpaper"
"chromiumos/tast/local/wallpaper/constants"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: DailyRefreshGooglePhotosWallpaper,
LacrosStatus: testing.LacrosVariantUnneeded,
Desc: "Test setting Google Photos wallpapers in the wallpaper app",
Contacts: []string{
"xiaohuic@google.com",
"assistive-eng@google.com",
"chromeos-sw-engprod@google.com",
},
Attr: []string{"group:mainline", "informational"},
SoftwareDeps: []string{"chrome"},
VarDeps: []string{
"wallpaper.googlePhotosAccountPool",
},
Timeout: 5 * time.Minute,
})
}
func DailyRefreshGooglePhotosWallpaper(ctx context.Context, s *testing.State) {
// Setting Google Photos wallpapers requires that Chrome be logged in with
// a user from an account pool which has been preconditioned to have a
// Google Photos library with specific photos/albums present. Note that sync
// is disabled to prevent flakiness caused by wallpaper cross device sync.
cr, err := chrome.New(ctx,
chrome.GAIALoginPool(s.RequiredVar("wallpaper.googlePhotosAccountPool")),
chrome.EnableFeatures("WallpaperGooglePhotosIntegration", "PersonalizationHub"),
chrome.ExtraArgs("--disable-sync"))
if err != nil {
s.Fatal("Failed to log in to Chrome: ", err)
}
tconn, err := cr.TestAPIConn(ctx)
if err != nil {
s.Fatal("Failed to create Test API connection: ", err)
}
defer faillog.DumpUITreeOnError(ctx, s.OutDir(), s.HasError, tconn)
// Force Chrome to be in clamshell mode to make sure the wallpaper view is
// clearly visible for us to compare it with an expected RGBA color.
cleanup, err := ash.EnsureTabletModeEnabled(ctx, tconn, false)
if err != nil {
s.Fatal("Failed to ensure DUT is not in tablet mode: ", err)
}
defer cleanup(ctx)
// The test has a dependency on network speed, so we give `uiauto.Context`
// ample time to wait for nodes to load.
ui := uiauto.New(tconn).WithTimeout(30 * time.Second)
// Take a screenshot of the current wallpaper.
screenshot1, err := screenshot.GrabScreenshot(ctx, cr)
if err != nil {
s.Fatal("Failed to grab screenshot: ", err)
}
if err := uiauto.Combine("Enable daily refresh and minimize wallpaper picker",
wallpaper.OpenWallpaperPicker(ui),
wallpaper.SelectCollection(ui, constants.GooglePhotosWallpaperCollection),
ui.LeftClick(constants.GooglePhotosWallpaperAlbumsButton),
wallpaper.SelectGooglePhotosAlbum(ui, constants.GooglePhotosWallpaperAlbum),
ui.LeftClick(constants.ChangeDailyButton),
ui.WaitUntilExists(constants.RefreshButton),
wallpaper.MinimizeWallpaperPicker(ui),
)(ctx); err != nil {
s.Fatal("Failed to enable daily refresh: ", err)
}
// Take a screenshot of the current wallpaper.
screenshot2, err := screenshot.GrabScreenshot(ctx, cr)
if err != nil {
s.Fatal("Failed to grab screenshot: ", err)
}
// Verify that the wallpaper has indeed changed.
const expectedPercent = 90
if err = wallpaper.ValidateDiff(screenshot1, screenshot2, expectedPercent); err != nil {
screenshot1Path := filepath.Join(s.OutDir(), "screenshot_1.png")
screenshot2Path := filepath.Join(s.OutDir(), "screenshot_2.png")
if err := imgcmp.DumpImageToPNG(ctx, &screenshot1, screenshot1Path); err != nil {
s.Errorf("Failed to dump image to %s: %v", screenshot1Path, err)
}
if err := imgcmp.DumpImageToPNG(ctx, &screenshot2, screenshot2Path); err != nil {
s.Errorf("Failed to dump image to %s: %v", screenshot2Path, err)
}
s.Fatal("Failed to validate wallpaper difference: ", err)
}
if err := uiauto.Combine("Manually refresh and minimize wallpaper picker",
wallpaper.OpenWallpaperPicker(ui),
wallpaper.SelectCollection(ui, constants.GooglePhotosWallpaperCollection),
ui.LeftClick(constants.GooglePhotosWallpaperAlbumsButton),
wallpaper.SelectGooglePhotosAlbum(ui, constants.GooglePhotosWallpaperAlbum),
ui.LeftClick(constants.RefreshButton),
// NOTE: The refresh button will be hidden while updating the wallpaper so
// use its reappearance as a proxy to know when the wallpaper has finished
// updating.
ui.WaitUntilGone(constants.RefreshButton),
ui.WaitUntilExists(constants.RefreshButton),
wallpaper.MinimizeWallpaperPicker(ui),
)(ctx); err != nil {
s.Fatal("Failed to manually refresh: ", err)
}
// Take a screenshot of the current wallpaper.
screenshot3, err := screenshot.GrabScreenshot(ctx, cr)
if err != nil {
s.Fatal("Failed to grab screenshot: ", err)
}
// Verify that the wallpaper has indeed changed.
if err = wallpaper.ValidateDiff(screenshot2, screenshot3, expectedPercent); err != nil {
screenshot3Path := filepath.Join(s.OutDir(), "screenshot_3.png")
if err := imgcmp.DumpImageToPNG(ctx, &screenshot3, screenshot3Path); err != nil {
s.Errorf("Failed to dump image to %s: %v", screenshot3Path, err)
}
s.Fatal("Failed to validate wallpaper difference: ", err)
}
}
|
package http
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
"go.elastic.co/apm/module/apmhttp"
"go.elastic.co/apm/module/apmlogrus"
)
func Do(req *http.Request, ctx context.Context, log *logrus.Logger) (string, error) {
// logger
vars := mux.Vars(req)
logAPM := log.WithFields(apmlogrus.TraceContext(req.Context()))
logAPM.WithField("vars", vars).Info("handling call to service b request")
client := apmhttp.WrapClient(http.DefaultClient)
resp, err := client.Do(req.WithContext(ctx))
if err != nil {
log.WithError(err).Error("Fail to call service b")
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.WithError(err).Error("fail to decode res of service b")
return "", err
}
if resp.StatusCode != 200 {
log.WithError(err).Error("failed to request servie b")
return "", fmt.Errorf("StatusCode: %d, Body: %s", resp.StatusCode, body)
}
return string(body), nil
}
|
package definition
import "fmt"
type EngineOneC struct {
IsStarting bool
}
type EngineTwoC struct {
IsStarting bool
}
func (ec *EngineOneC) StartEngineC() {
ec.IsStarting = true
fmt.Println("Engine one been started")
}
func (ec *EngineOneC) StopEngineC() {
ec.IsStarting = false
fmt.Println("Engine one been stopped")
}
func (ec *EngineTwoC) StartEngineC() {
ec.IsStarting = true
fmt.Println("Engine two been started")
}
func (ec *EngineTwoC) StopEngineC() {
ec.IsStarting = false
fmt.Println("Engine two been stopped")
}
|
package main
import (
"fmt"
"runtime"
)
func main3() {
fmt.Println(runtime.GOOS)
fmt.Println(runtime.NumCPU())
fmt.Println(runtime.NumGoroutine())
} |
/*
Copyright 2014 Jiang Le
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 filestore
import (
"errors"
"fmt"
)
type Provider interface {
Init(config Config) (err error)
PutFile(localFileUrl string, remoteFileUrl string) (url string, err error)
Get(filename string) (data []byte, err error)
Delete(filename string) (err error)
List(path string) (entries []Entry, err error)
GetConfig() *Config
}
type Entry struct {
Fname string `json:"fname"`
Hash string `json:"hash"`
Fsize int64 `json:"fsize"`
PutTime int64 `json:"putTime"`
MimeType string `json:"mimeType"`
}
type Config struct {
UrlPrefix string `json:"urlPrefix"`
FSPath string `json:"fSPath"`
Host string `json:"host"`
User string `json:"user"`
Password string `json:"password"`
}
type Manager struct {
Provider
}
var provides = make(map[string]Provider)
// Register makes a session provide available by the provided name.
// If Register is called twice with the same name or if driver is nil,
// it panics.
func Register(name string, provide Provider) {
if provide == nil {
panic("filestore: Register provide is nil")
}
if _, dup := provides[name]; dup {
panic("filestore: Register called twice for provider " + name)
}
provides[name] = provide
}
func NewManager(provideName string, cf Config) (*Manager, error) {
provider, ok := provides[provideName]
if !ok {
return nil, fmt.Errorf("filestore: unknown provide %q (forgotten import?)", provideName)
}
if cf.UrlPrefix == "" {
return nil, errors.New("filestore: no urlPrefix provided")
}
err := provider.Init(cf)
if err != nil {
return nil, err
}
return &Manager{
provider,
}, nil
}
|
package main
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/ledongthuc/pdf"
"github.com/nguyenthenguyen/docx"
)
var keywords []string
func init() {
fmt.Printf("输入关键词,多个关键词以空格分割: ")
inputReader := bufio.NewReader(os.Stdin)
kw, err := inputReader.ReadString('\n')
if err != nil {
fmt.Printf("The input was: %s\n", kw)
}
kwArr := strings.Split(kw, " ")
for _, each := range kwArr {
k := strings.TrimSpace(each)
if k != "" {
keywords = append(keywords, k)
}
}
}
func main() {
workDir,err := os.Getwd()
if err != nil {
panic(err)
}
files, err := GetAllFiles(workDir)
if err != nil {
panic(files)
}
fmt.Println("搜索结果:")
for _, filePath := range files {
if strings.HasSuffix(filePath, "pdf") {
if match, _ := searchPDF(filePath, keywords); match {
fmt.Println(" "+filePath)
}
} else if strings.HasSuffix(filePath, "docx") {
if match, _ := searchDocx(filePath, keywords); match {
fmt.Println(" "+filePath)
}
}
}
}
func searchDocx(filePath string, keywords []string) (bool, error) {
r, err := docx.ReadDocxFile(filePath)
if err != nil {
return false, err
}
content := r.Editable().GetContent()
for _, each := range keywords {
if strings.Contains(content, each) {
return true, nil
}
}
r.Close()
return false, nil
}
func searchPDF(filePath string, keywords []string) (bool, error) {
f, r, err := pdf.Open(filePath)
// remember close file
defer f.Close()
if err != nil {
return false, err
}
var buf bytes.Buffer
b, err := r.GetPlainText()
if err != nil {
return false, err
}
buf.ReadFrom(b)
content := buf.String()
for _, each := range keywords {
if strings.Contains(content, each) {
return true, nil
}
}
return false, nil
}
//获取指定目录下的所有文件,包含子目录下的文件
func GetAllFiles(dirPth string) (files []string, err error) {
var dirs []string
dir, err := ioutil.ReadDir(dirPth)
if err != nil {
return nil, err
}
PthSep := string(os.PathSeparator)
//suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写
for _, fi := range dir {
if fi.IsDir() { // 目录, 递归遍历
continue
dirs = append(dirs, dirPth+PthSep+fi.Name())
GetAllFiles(dirPth + PthSep + fi.Name())
} else {
files = append(files, dirPth+PthSep+fi.Name())
}
}
// 读取子目录下文件
for _, table := range dirs {
temp, _ := GetAllFiles(table)
for _, temp1 := range temp {
files = append(files, temp1)
}
}
return files, nil
} |
package main
import (
"github.com/Altruiste1/go_learning/crawler/Concurrent_crawler/engine"
"github.com/Altruiste1/go_learning/crawler/Concurrent_crawler/scheduler"
"github.com/Altruiste1/go_learning/crawler/Concurrent_crawler/zhenai/parser"
)
func main() {
//engine.Run(engine.Request{
// Url: "https://www.zhenai.com/n/register?channelId=901388&subChannelId=15026",
// ParserFunc: parser.ParseCityList,
//})
e:=engine.ConcurrentEngine{
Scheduler:&scheduler.SimpleScheduler{},
WorkerCount:100,
}
e.Run(engine.Request{
Url: "https://www.zhenai.com/n/register?channelId=901388&subChannelId=15026",
ParserFunc: parser.ParseCityList,
})
}
|
package explainer
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func TestModel(t *testing.T) {
RegisterFailHandler(Fail)
RunExplainerTests()
RunSpecs(t, "explainer suite")
}
|
package data
import (
"fmt"
config "github.com/spf13/viper"
"github.com/trapped/gomaild2/db"
. "github.com/trapped/gomaild2/smtp/structs"
"strings"
"time"
)
func receivedString(c *Client, e *db.Envelope) string {
secure, authenticated := "", ""
if c.GetBool("secure") {
secure = "S"
}
if c.GetBool("authenticated") {
authenticated = "A"
}
return fmt.Sprintf("Received: from %v (%v)\r\n\tby %v with ESMTP%v%v id %v;\r\n\t%v\r\n",
c.GetString("identifier"), c.Conn.RemoteAddr().String(), config.GetString("server.name"),
secure, authenticated, c.ID, e.Date.Format(time.RFC1123Z))
}
func queueMessage(c *Client, sender string, recipients []string, body string) error {
envelope := &db.Envelope{
Sender: sender,
Recipients: recipients,
Session: c.ID,
OutboundAllowed: c.GetBool("outbound"),
Date: time.Now(),
NextDeliverTime: time.Now(),
}
//TODO: check sender's domain SPF
//TODO: add Received-SPF, Authentication-Results
headers := ""
headers += receivedString(c, envelope)
envelope.Body = headers + body
_, err := envelope.Save()
return err
}
func Process(c *Client, cmd Command) Reply {
recipients := c.GetStringSlice("recipients")
sender := c.GetString("sender")
if c.State != ReceivingHeaders && len(recipients) < 0 {
return Reply{
Result: BadSequence,
Message: "wrong command sequence",
}
}
c.State = ReceivingBody
c.Send(Reply{
Result: StartSending,
Message: "start sending input",
})
body := ""
for {
line, err := c.Rdr.ReadString('\n')
if err != nil {
c.State = Disconnected
return Reply{}
}
if line == ".\r\n" && strings.HasSuffix(body, "\r\n") {
err = queueMessage(c, sender, recipients, body)
c.Set("sender", nil)
c.Set("recipients", nil)
c.State = Identified
if err != nil {
return Reply{
Result: LocalError,
Message: err.Error(),
}
} else {
return Reply{
Result: Ok,
Message: "queued",
}
}
} else {
body += line
}
}
}
|
package main
import (
"fmt"
"strings"
)
func main() {
var a [2]string
a[0] = "a"
fmt.Println(a)
a[1] = "b"
fmt.Println(a)
// more-types/array.go:11:3: invalid array index 2 (out of bounds for 2-element array)
// a[2] = "c"
//for i := 0; i < 5; i++ {
// a[i] = fmt.Sprintf("no.%d", i)
// //panic: runtime error: index out of range
// // goroutine 1 [running]:
// // main.main()
// // /Users/kazuhirosera/github/oss/a-tour-of-go/more-types/array.go:15 +0x549
//}
primes := [6]int{2, 3, 5, 7, 11, 13}
fmt.Println(primes)
// slices, length, capacity
s := primes[1:4]
fmt.Println(s, len(s), cap(s)) // [3 5 7] 3 5
s2 := primes[1:]
fmt.Println(s2, len(s2), cap(s2)) // [3 5 7 11 13] 5 5
s3 := primes[:3]
fmt.Println(s3, len(s3), cap(s3)) // [2 3 5] 3 6
// slices are like references to arrays
s[0] = 10001
fmt.Println(s) // [10001 5 7]
fmt.Println(primes) // [2 10001 5 7 11 13]
q := []int{1, 2, 3, 4}
fmt.Println(q)
ss := []struct {
i int
b bool
}{
{1, false},
{2, true},
}
fmt.Println(ss)
{
a1 := make([]int, 5) // len 5, cap 5
fmt.Println(a1, len(a1), cap(a1)) // [0 0 0 0 0] 5 5
a2 := make([]int, 3, 5) // len 3, cap 5
fmt.Println(a2, len(a2), cap(a2)) // [0 0 0] 3 5
}
{
aa := [][]string{[]string{"a", "b", "c"}, []string{"A", "B", "C"}}
fmt.Println(aa) // [[a b c] [A B C]]
fmt.Println(strings.Join(aa[0], ",")) // a,b,c
}
}
|
package game
import (
"encoding/json"
)
type RawMessageIn struct {
Type string
Payload json.RawMessage
}
type MessageIn struct {
Player *Player
Type string
Payload json.RawMessage
}
type MessageOut struct {
Type string
Payload interface{}
}
|
package forms
import (
"encoding/base64"
"errors"
"fmt"
"net/url"
"regexp"
"strings"
"github.com/porter-dev/porter/internal/kubernetes"
"github.com/porter-dev/porter/internal/models"
"github.com/porter-dev/porter/internal/repository"
"k8s.io/client-go/tools/clientcmd/api"
ints "github.com/porter-dev/porter/internal/models/integrations"
)
// CreateClusterForm represents the accepted values for creating a
// cluster through manual configuration (not through a kubeconfig)
type CreateClusterForm struct {
Name string `json:"name" form:"required"`
ProjectID uint `json:"project_id" form:"required"`
Server string `json:"server" form:"required"`
GCPIntegrationID uint `json:"gcp_integration_id"`
AWSIntegrationID uint `json:"aws_integration_id"`
CertificateAuthorityData string `json:"certificate_authority_data,omitempty"`
}
// ToCluster converts the form to a cluster
func (ccf *CreateClusterForm) ToCluster() (*models.Cluster, error) {
var authMechanism models.ClusterAuth
if ccf.GCPIntegrationID != 0 {
authMechanism = models.GCP
} else if ccf.AWSIntegrationID != 0 {
authMechanism = models.AWS
} else {
return nil, fmt.Errorf("must include aws or gcp integration id")
}
cert := make([]byte, 0)
if ccf.CertificateAuthorityData != "" {
// determine if data is base64 decoded using regex
re := regexp.MustCompile(`^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$`)
// if it matches the base64 regex, decode it
if re.MatchString(ccf.CertificateAuthorityData) {
decoded, err := base64.StdEncoding.DecodeString(ccf.CertificateAuthorityData)
if err != nil {
return nil, err
}
cert = []byte(decoded)
}
}
return &models.Cluster{
ProjectID: ccf.ProjectID,
AuthMechanism: authMechanism,
Name: ccf.Name,
Server: ccf.Server,
GCPIntegrationID: ccf.GCPIntegrationID,
AWSIntegrationID: ccf.AWSIntegrationID,
CertificateAuthorityData: cert,
}, nil
}
// UpdateClusterForm represents the accepted values for updating a
// cluster (only name for now)
type UpdateClusterForm struct {
ID uint
Name string `json:"name" form:"required"`
}
// ToCluster converts the form to a cluster
func (ucf *UpdateClusterForm) ToCluster(repo repository.ClusterRepository) (*models.Cluster, error) {
cluster, err := repo.ReadCluster(ucf.ID)
if err != nil {
return nil, err
}
cluster.Name = ucf.Name
return cluster, nil
}
// ResolveClusterForm will resolve a cluster candidate and create a new cluster
type ResolveClusterForm struct {
Resolver *models.ClusterResolverAll `form:"required"`
ClusterCandidateID uint `json:"cluster_candidate_id" form:"required"`
ProjectID uint `json:"project_id" form:"required"`
UserID uint `json:"user_id" form:"required"`
// populated during the ResolveIntegration step
IntegrationID uint
ClusterCandidate *models.ClusterCandidate
RawConf *api.Config
}
// ResolveIntegration creates an integration in the DB
func (rcf *ResolveClusterForm) ResolveIntegration(
repo repository.Repository,
) error {
cc, err := repo.Cluster.ReadClusterCandidate(rcf.ClusterCandidateID)
if err != nil {
return err
}
rcf.ClusterCandidate = cc
rawConf, err := kubernetes.GetRawConfigFromBytes(cc.Kubeconfig)
if err != nil {
return err
}
rcf.RawConf = rawConf
context := rawConf.Contexts[rawConf.CurrentContext]
authInfoName := context.AuthInfo
authInfo := rawConf.AuthInfos[authInfoName]
// iterate through the resolvers, and use the ClusterResolverAll to populate
// the required fields
var id uint
switch cc.AuthMechanism {
case models.X509:
id, err = rcf.resolveX509(repo, authInfo)
case models.Bearer:
id, err = rcf.resolveToken(repo, authInfo)
case models.Basic:
id, err = rcf.resolveBasic(repo, authInfo)
case models.Local:
id, err = rcf.resolveLocal(repo, authInfo)
case models.OIDC:
id, err = rcf.resolveOIDC(repo, authInfo)
case models.GCP:
id, err = rcf.resolveGCP(repo, authInfo)
case models.AWS:
id, err = rcf.resolveAWS(repo, authInfo)
}
if err != nil {
return err
}
rcf.IntegrationID = id
return nil
}
func (rcf *ResolveClusterForm) resolveX509(
repo repository.Repository,
authInfo *api.AuthInfo,
) (uint, error) {
ki := &ints.KubeIntegration{
Mechanism: ints.KubeX509,
UserID: rcf.UserID,
ProjectID: rcf.ProjectID,
}
// attempt to construct cert and key from raw config
if len(authInfo.ClientCertificateData) > 0 {
ki.ClientCertificateData = authInfo.ClientCertificateData
}
if len(authInfo.ClientKeyData) > 0 {
ki.ClientKeyData = authInfo.ClientKeyData
}
// override with resolver
if rcf.Resolver.ClientCertData != "" {
decoded, err := base64.StdEncoding.DecodeString(rcf.Resolver.ClientCertData)
if err != nil {
return 0, err
}
ki.ClientCertificateData = decoded
}
if rcf.Resolver.ClientKeyData != "" {
decoded, err := base64.StdEncoding.DecodeString(rcf.Resolver.ClientKeyData)
if err != nil {
return 0, err
}
ki.ClientKeyData = decoded
}
// if resolvable, write kube integration to repo
if len(ki.ClientCertificateData) == 0 || len(ki.ClientKeyData) == 0 {
return 0, errors.New("could not resolve kube integration (x509)")
}
// return integration id if exists
ki, err := repo.KubeIntegration.CreateKubeIntegration(ki)
if err != nil {
return 0, err
}
return ki.Model.ID, nil
}
func (rcf *ResolveClusterForm) resolveToken(
repo repository.Repository,
authInfo *api.AuthInfo,
) (uint, error) {
ki := &ints.KubeIntegration{
Mechanism: ints.KubeBearer,
UserID: rcf.UserID,
ProjectID: rcf.ProjectID,
}
// attempt to construct token from raw config
if len(authInfo.Token) > 0 {
ki.Token = []byte(authInfo.Token)
}
// supplement with resolver
if rcf.Resolver.TokenData != "" {
ki.Token = []byte(rcf.Resolver.TokenData)
}
// if resolvable, write kube integration to repo
if len(ki.Token) == 0 {
return 0, errors.New("could not resolve kube integration (token)")
}
// return integration id if exists
ki, err := repo.KubeIntegration.CreateKubeIntegration(ki)
if err != nil {
return 0, err
}
return ki.Model.ID, nil
}
func (rcf *ResolveClusterForm) resolveBasic(
repo repository.Repository,
authInfo *api.AuthInfo,
) (uint, error) {
ki := &ints.KubeIntegration{
Mechanism: ints.KubeBasic,
UserID: rcf.UserID,
ProjectID: rcf.ProjectID,
}
if len(authInfo.Username) > 0 {
ki.Username = []byte(authInfo.Username)
}
if len(authInfo.Password) > 0 {
ki.Password = []byte(authInfo.Password)
}
if len(ki.Username) == 0 || len(ki.Password) == 0 {
return 0, errors.New("could not resolve kube integration (basic)")
}
// return integration id if exists
ki, err := repo.KubeIntegration.CreateKubeIntegration(ki)
if err != nil {
return 0, err
}
return ki.Model.ID, nil
}
func (rcf *ResolveClusterForm) resolveLocal(
repo repository.Repository,
authInfo *api.AuthInfo,
) (uint, error) {
ki := &ints.KubeIntegration{
Mechanism: ints.KubeLocal,
UserID: rcf.UserID,
ProjectID: rcf.ProjectID,
Kubeconfig: rcf.ClusterCandidate.Kubeconfig,
}
// return integration id if exists
ki, err := repo.KubeIntegration.CreateKubeIntegration(ki)
if err != nil {
return 0, err
}
return ki.Model.ID, nil
}
func (rcf *ResolveClusterForm) resolveOIDC(
repo repository.Repository,
authInfo *api.AuthInfo,
) (uint, error) {
oidc := &ints.OIDCIntegration{
Client: ints.OIDCKube,
UserID: rcf.UserID,
ProjectID: rcf.ProjectID,
}
if url, ok := authInfo.AuthProvider.Config["idp-issuer-url"]; ok {
oidc.IssuerURL = []byte(url)
}
if clientID, ok := authInfo.AuthProvider.Config["client-id"]; ok {
oidc.ClientID = []byte(clientID)
}
if clientSecret, ok := authInfo.AuthProvider.Config["client-secret"]; ok {
oidc.ClientSecret = []byte(clientSecret)
}
if caData, ok := authInfo.AuthProvider.Config["idp-certificate-authority-data"]; ok {
// based on the implementation, the oidc plugin expects the data to be base64 encoded,
// which means we will not decode it here
// reference: https://github.com/kubernetes/kubernetes/blob/9dfb4c876bfca7a5ae84259fae2bc337ed90c2d7/staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc.go#L135
oidc.CertificateAuthorityData = []byte(caData)
}
if idToken, ok := authInfo.AuthProvider.Config["id-token"]; ok {
oidc.IDToken = []byte(idToken)
}
if refreshToken, ok := authInfo.AuthProvider.Config["refresh-token"]; ok {
oidc.RefreshToken = []byte(refreshToken)
}
// override with resolver
if rcf.Resolver.OIDCIssuerCAData != "" {
// based on the implementation, the oidc plugin expects the data to be base64 encoded,
// which means we will not decode it here
// reference: https://github.com/kubernetes/kubernetes/blob/9dfb4c876bfca7a5ae84259fae2bc337ed90c2d7/staging/src/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc.go#L135
oidc.CertificateAuthorityData = []byte(rcf.Resolver.OIDCIssuerCAData)
}
// return integration id if exists
oidc, err := repo.OIDCIntegration.CreateOIDCIntegration(oidc)
if err != nil {
return 0, err
}
return oidc.Model.ID, nil
}
func (rcf *ResolveClusterForm) resolveGCP(
repo repository.Repository,
authInfo *api.AuthInfo,
) (uint, error) {
// TODO -- add GCP project ID and GCP email so that source is trackable
gcp := &ints.GCPIntegration{
UserID: rcf.UserID,
ProjectID: rcf.ProjectID,
}
// supplement with resolver
if rcf.Resolver.GCPKeyData != "" {
gcp.GCPKeyData = []byte(rcf.Resolver.GCPKeyData)
}
// throw error if no data
if len(gcp.GCPKeyData) == 0 {
return 0, errors.New("could not resolve gcp integration")
}
// return integration id if exists
gcp, err := repo.GCPIntegration.CreateGCPIntegration(gcp)
if err != nil {
return 0, err
}
return gcp.Model.ID, nil
}
func (rcf *ResolveClusterForm) resolveAWS(
repo repository.Repository,
authInfo *api.AuthInfo,
) (uint, error) {
// TODO -- add AWS session token as an optional param
// TODO -- add AWS entity and user ARN
aws := &ints.AWSIntegration{
UserID: rcf.UserID,
ProjectID: rcf.ProjectID,
}
// override with resolver
if rcf.Resolver.AWSClusterID != "" {
aws.AWSClusterID = []byte(rcf.Resolver.AWSClusterID)
}
if rcf.Resolver.AWSAccessKeyID != "" {
aws.AWSAccessKeyID = []byte(rcf.Resolver.AWSAccessKeyID)
}
if rcf.Resolver.AWSSecretAccessKey != "" {
aws.AWSSecretAccessKey = []byte(rcf.Resolver.AWSSecretAccessKey)
}
// throw error if no data
if len(aws.AWSClusterID) == 0 || len(aws.AWSAccessKeyID) == 0 || len(aws.AWSSecretAccessKey) == 0 {
return 0, errors.New("could not resolve aws integration")
}
// return integration id if exists
aws, err := repo.AWSIntegration.CreateAWSIntegration(aws)
if err != nil {
return 0, err
}
return aws.Model.ID, nil
}
// ResolveCluster writes a new cluster to the DB -- this must be called after
// rcf.ResolveIntegration, since it relies on the previously created integration.
func (rcf *ResolveClusterForm) ResolveCluster(
repo repository.Repository,
) (*models.Cluster, error) {
// build a cluster from the candidate
cluster, err := rcf.buildCluster()
if err != nil {
return nil, err
}
// save cluster to db
return repo.Cluster.CreateCluster(cluster)
}
func (rcf *ResolveClusterForm) buildCluster() (*models.Cluster, error) {
rawConf := rcf.RawConf
kcContext := rawConf.Contexts[rawConf.CurrentContext]
kcAuthInfoName := kcContext.AuthInfo
kcAuthInfo := rawConf.AuthInfos[kcAuthInfoName]
kcClusterName := kcContext.Cluster
kcCluster := rawConf.Clusters[kcClusterName]
cc := rcf.ClusterCandidate
cluster := &models.Cluster{
AuthMechanism: cc.AuthMechanism,
ProjectID: cc.ProjectID,
Name: cc.Name,
Server: cc.Server,
ClusterLocationOfOrigin: kcCluster.LocationOfOrigin,
TLSServerName: kcCluster.TLSServerName,
InsecureSkipTLSVerify: kcCluster.InsecureSkipTLSVerify,
UserLocationOfOrigin: kcAuthInfo.LocationOfOrigin,
UserImpersonate: kcAuthInfo.Impersonate,
}
if len(kcAuthInfo.ImpersonateGroups) > 0 {
cluster.UserImpersonateGroups = strings.Join(kcAuthInfo.ImpersonateGroups, ",")
}
if len(kcCluster.CertificateAuthorityData) > 0 {
cluster.CertificateAuthorityData = kcCluster.CertificateAuthorityData
}
if rcf.Resolver.ClusterCAData != "" {
decoded, err := base64.StdEncoding.DecodeString(rcf.Resolver.ClusterCAData)
// skip if decoding error
if err != nil {
return nil, err
}
cluster.CertificateAuthorityData = decoded
}
if rcf.Resolver.ClusterHostname != "" {
serverURL, err := url.Parse(cluster.Server)
if err != nil {
return nil, err
}
if serverURL.Port() == "" {
serverURL.Host = rcf.Resolver.ClusterHostname
} else {
serverURL.Host = rcf.Resolver.ClusterHostname + ":" + serverURL.Port()
}
cluster.Server = serverURL.String()
}
switch cc.AuthMechanism {
case models.X509, models.Bearer, models.Basic, models.Local:
cluster.KubeIntegrationID = rcf.IntegrationID
case models.OIDC:
cluster.OIDCIntegrationID = rcf.IntegrationID
case models.GCP:
cluster.GCPIntegrationID = rcf.IntegrationID
case models.AWS:
cluster.AWSIntegrationID = rcf.IntegrationID
}
return cluster, nil
}
|
package problem0202
func isHappy(n int) bool {
if n == 0 {
return false
}
if n == 1 {
return true
}
k := 0
m := make(map[int]int)
return recursive(n, k, m)
}
func recursive(n, k int, m map[int]int) bool {
if n == 1 {
return true
}
sum := 0
for n != 0 {
sum += (n % 10) * (n % 10)
n /= 10
}
if _, ok := m[sum]; ok {
return false
}
m[sum] = 1
return recursive(sum, k+1, m)
}
|
package main
import (
"fmt"
)
var i = 5
var str = "ABC"
type person struct {
name string
age int
}
type any interface{}
func main() {
var val any
val = 5
fmt.Println("val value is :", val)
val = str
fmt.Println("val has value is :", val)
pers1 := new(person)
pers1.name = "Bear Chen"
pers1.age = 55
val = pers1
fmt.Println("val has value is :", val)
switch t := val.(type) {
case int:
fmt.Printf("Type int %T\n", t)
case string:
fmt.Printf("Type string %T\n", t)
case bool:
fmt.Printf("Type bool %T\n", t)
case *person:
fmt.Printf("Type pointer to person %T\n", t)
default:
fmt.Printf("Unexpected type %T", t)
}
}
|
// Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package upstart interacts with the Upstart init daemon on behalf of local tests.
package upstart
import (
"context"
"time"
"chromiumos/tast/errors"
"chromiumos/tast/testing"
)
// UIRestartTimeout is the maximum amount of time that it takes to restart
// the ui upstart job.
// ui-post-stop can sometimes block for an extended period of time
// waiting for "cryptohome --action=pkcs11_terminate" to finish: https://crbug.com/860519
const UIRestartTimeout = 60 * time.Second
func init() {
testing.AddFixture(&testing.Fixture{
Name: "ensureUI",
Desc: "Ensure the ui service is running",
Contacts: []string{
"pwang@chromium.org", // fixture author
"cros-printing-dev@chromium.org",
},
Impl: &ensureUIFixture{running: true},
SetUpTimeout: UIRestartTimeout,
TearDownTimeout: UIRestartTimeout,
ResetTimeout: UIRestartTimeout,
})
testing.AddFixture(&testing.Fixture{
Name: "ensureNoUI",
Desc: "Ensure the ui service is not running",
Contacts: []string{
"khegde@chromium.org", // fixture maintainer
"cros-network-health@google.com",
},
Impl: &ensureUIFixture{running: false},
SetUpTimeout: UIRestartTimeout,
TearDownTimeout: UIRestartTimeout,
ResetTimeout: 1 * time.Second,
})
}
type ensureUIFixture struct {
running bool
}
func (f *ensureUIFixture) SetUp(ctx context.Context, s *testing.FixtState) interface{} {
if f.running {
if err := EnsureJobRunning(ctx, "ui"); err != nil {
s.Fatal("Failed to start ui: ", err)
}
} else {
if err := StopJob(ctx, "ui"); err != nil {
s.Fatal("Failed to stop ui: ", err)
}
}
return nil
}
func (f *ensureUIFixture) TearDown(ctx context.Context, s *testing.FixtState) {
// We intentionally don't stop the ui as Chrome running is the expected
// clean. If the ui is stopped, attempt to start it.
if err := EnsureJobRunning(ctx, "ui"); err != nil {
s.Log("Failed to start ui: ", err)
}
}
func (f *ensureUIFixture) Reset(ctx context.Context) error {
// Tried to ensure the ui job is still running between tests. EnsureJobRunning is noop if Chrome is running.
if f.running {
if err := EnsureJobRunning(ctx, "ui"); err != nil {
return errors.Wrap(err, "failed to ensure ui is running")
}
}
return nil
}
func (f *ensureUIFixture) PreTest(ctx context.Context, s *testing.FixtTestState) {
}
func (f *ensureUIFixture) PostTest(ctx context.Context, s *testing.FixtTestState) {
}
|
package main
import (
"encoding/json"
"fmt"
log "github.com/Sirupsen/logrus"
"github.com/nicolas-nannoni/fingy-gateway/events"
"github.com/parnurzeal/gorequest"
"net/url"
)
type Service struct {
Id string
Host string
Port uint
deviceRegistry map[string]*connection
}
type registry struct {
services map[string]*Service
}
var Registry = registry{
services: make(map[string]*Service),
}
// Dispatch an Event coming from a given deviceId to the appropriate serviceId that exists in the Registry
func (r *registry) Dispatch(serviceId string, deviceId string, evt *events.Event) (resp *events.Event, err error) {
service := r.services[serviceId]
if service == nil {
return nil, fmt.Errorf("Unknown service %s", evt.ServiceId)
}
body, errs := service.send(evt, deviceId)
if errs != nil {
return nil, fmt.Errorf("Error while contacting service %s: %v", service.Id, errs)
}
resp = &events.Event{
ServiceId: service.Id,
CorrelationId: evt.Id.String(),
Path: evt.Path,
Payload: body,
}
return resp, nil
}
// Send an event to the given deviceId (registered in the given service)
func (r *registry) SendToDevice(serviceId string, deviceId string, evt *events.Event) (err error) {
s := r.services[serviceId]
if s == nil {
err = fmt.Errorf("Unknown service %s. Message sending to %s aborted", serviceId, deviceId)
return
}
return s.SendToDevice(deviceId, evt)
}
// Send an event to the given deviceId (registered in the current service)
func (s *Service) SendToDevice(deviceId string, evt *events.Event) (err error) {
c, ok := s.deviceRegistry[deviceId]
if !ok {
return fmt.Errorf("No connection to device %s for service %s", deviceId, s)
}
evt.PrepareForSend()
err = evt.Verify()
if err != nil {
return err
}
msg, err := json.Marshal(evt)
if err != nil {
return fmt.Errorf("The event %s could not be serialized to JSON: %v", evt, err)
}
log.Debugf("Pushing message %s to send queue of %s", msg, c)
c.send <- msg
return
}
// Add a service to the Fingy Service registry
func (r *registry) RegisterService(service *Service) {
r.services[service.Id] = service
service.deviceRegistry = make(map[string]*connection)
}
// Lookup the Service entity matching the given event
func (r *registry) getServiceForEvent(evt *events.Event) (service *Service) {
service = r.services[evt.ServiceId]
return
}
// Lookup the Service entity matching the given connection
func (r *registry) getServiceForConnection(c *connection) (service *Service) {
service = r.services[c.serviceId]
return
}
// Send the HTTP request towards the final service
func (s *Service) send(evt *events.Event, deviceId string) (response string, errs []error) {
request := gorequest.New()
u := url.URL{Scheme: "http", Host: s.Host, Path: fmt.Sprintf("/devices/%s%s", deviceId, evt.Path)}
resp, body, errs := request.Get(u.String()).End()
log.Debugf("Response from service %s: %s", s, resp)
return body, errs
}
// Register a connection (device)
func (r *registry) registerConnection(c *connection) (err error) {
log.Infof("Registering connection %s", c)
s := r.getServiceForConnection(c)
if s == nil {
err = fmt.Errorf("Unknown service with id %s, unable to register connection", c.serviceId)
return
}
if existingConn, ok := s.deviceRegistry[c.deviceId]; ok {
log.Debugf("Existing registration for device %s. Closing old connection %s", c.deviceId, existingConn)
r.unregisterConnection(existingConn)
}
s.deviceRegistry[c.deviceId] = c
return
}
// Unregister a connection (device)
func (r *registry) unregisterConnection(c *connection) (err error) {
s := r.getServiceForConnection(c)
if s == nil {
err = fmt.Errorf("Unknown service with id %s, unable to unregister connection", c.serviceId)
return
}
if existingConn, ok := s.deviceRegistry[c.deviceId]; ok && existingConn.id == c.id {
log.Infof("Unregistering connection %s", c)
delete(s.deviceRegistry, c.deviceId)
c.Close()
return
}
return
}
|
package watch
import (
"context"
"etcd-config/pkg/config"
"fmt"
clientv3 "go.etcd.io/etcd/client/v3"
"log"
"net/http"
"os"
"strings"
"time"
)
const (
defaultWatchPath = "/configs"
defaultDialTimeout = 5 * time.Second
)
func Execute() error {
pwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
return err
}
configPath := pwd + defaultWatchPath
config.ReadWatchConfig(configPath, "watch", "yaml")
endPoints := strings.Split(config.WatchConfigMsg.EndPoints, ",")
client, err := clientv3.New(clientv3.Config{
Endpoints: endPoints,
DialTimeout: defaultDialTimeout,
})
if err != nil {
log.Fatal(err)
return err
}
defer client.Close()
count := 0
watchChan := client.Watch(context.TODO(), config.WatchConfigMsg.WatchKey)
for response := range watchChan {
for _, ev := range response.Events {
receiveTime := time.Now().UnixNano()
count++
fmt.Printf("%s %q : %q\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
if count == 2 {
url := fmt.Sprintf("%s?receiveTime=%v", config.WatchConfigMsg.PostAddress, receiveTime)
fmt.Println(url)
http.Post(url, "application/json", nil)
}
}
}
return nil
}
|
package rangelist
import (
"fmt"
)
type RangeList struct {
entries []*RangeListEntry
}
type RangeListEntry struct {
Min int
Max int
Data interface{}
}
func (rl *RangeList) PrintEntries() {
for _, entry := range rl.entries {
fmt.Printf("%s\n", entry.String())
}
}
func (entry RangeListEntry) String() string {
return fmt.Sprintf("{Min:%d, Max:%d, Data:%p}", entry.Min, entry.Max, entry.Data)
}
func (rl *RangeList) InRange(start int, end int) []*RangeListEntry {
out := make([]*RangeListEntry, 0)
if rl.entries == nil {
return out
}
for _, entry := range rl.entries {
if entry.Min <= end && entry.Max >= start {
out = append(out, entry)
}
}
return out
}
func (rl *RangeList) Overwrite(newEntry *RangeListEntry) {
if rl.entries == nil {
rl.entries = make([]*RangeListEntry, 0)
}
for i, entry := range rl.entries {
if newEntry.Min == entry.Max + 1 && newEntry.Data == entry.Data && (i == len(rl.entries) - 1 || newEntry.Max < rl.entries[i+1].Min) {
entry.Max = newEntry.Max
return
}
}
oldEntries := make([]*RangeListEntry, len(rl.entries))
copy(oldEntries, rl.entries)
rl.entries = rl.entries[:0]
for _, entry := range oldEntries {
// Note: there is no case where there is both a split and a delete
if entry.Min >= newEntry.Min && entry.Max <= newEntry.Max {
// delete
} else if entry.Min < newEntry.Min && newEntry.Max < entry.Max {
// split
newEntry2 := &RangeListEntry{Min:newEntry.Max + 1,
Max:entry.Max, Data:entry.Data}
entry.Max = newEntry.Min - 1
rl.entries = append(rl.entries, entry)
rl.entries = append(rl.entries, newEntry2)
} else if entry.Min < newEntry.Min && entry.Max > newEntry.Min {
entry.Max = newEntry.Min - 1
rl.entries = append(rl.entries, entry)
} else if entry.Max > newEntry.Max && entry.Min < newEntry.Max {
entry.Min = newEntry.Max + 1
rl.entries = append(rl.entries, entry)
} else {
rl.entries = append(rl.entries, entry)
}
}
pos := 0
for i, entry := range rl.entries {
if newEntry.Min > entry.Min {
pos = i + 1
}
}
rl.entries = append(rl.entries, nil)
copy(rl.entries[pos+1:], rl.entries[pos:])
rl.entries[pos] = newEntry
}
func (entry *RangeListEntry) Length() int {
return entry.Max - entry.Min + 1
}
|
package profile
import (
"github.com/lorenzodonini/ocpp-go/ocpp1.6/core"
"golang.org/x/exp/maps"
)
// OnGetConfiguration handles the CS message
func (s *Core) OnGetConfiguration(request *core.GetConfigurationRequest) (confirmation *core.GetConfigurationConfirmation, err error) {
s.log.TRACE.Printf("recv: %s %+v", request.GetFeatureName(), request)
var resultKeys []core.ConfigurationKey
var unknownKeys []string
for _, key := range request.Key {
configKey, ok := s.configuration[key]
if !ok {
unknownKeys = append(unknownKeys, *configKey.Value)
} else {
resultKeys = append(resultKeys, configKey)
}
}
// return config for all keys
if len(request.Key) == 0 {
resultKeys = maps.Values(s.configuration)
}
s.log.TRACE.Printf("%s: configuration for requested keys: %v", request.GetFeatureName(), request.Key)
conf := core.NewGetConfigurationConfirmation(resultKeys)
conf.UnknownKey = unknownKeys
return conf, nil
}
// OnChangeConfiguration handles the CS message
func (s *Core) OnChangeConfiguration(request *core.ChangeConfigurationRequest) (confirmation *core.ChangeConfigurationConfirmation, err error) {
s.log.TRACE.Printf("recv: %s %+v", request.GetFeatureName(), request)
return core.NewChangeConfigurationConfirmation(core.ConfigurationStatusAccepted), nil
}
|
package tokencache
import (
"context"
"crypto"
"io"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/sassoftware/relic/v7/token"
"golang.org/x/time/rate"
)
var metricRateLimited = promauto.NewCounter(prometheus.CounterOpts{
Name: "token_operation_limited_seconds",
Help: "Cumulative number of seconds waiting for rate limits",
})
type RateLimited struct {
token.Token
limit *rate.Limiter
}
func NewLimiter(base token.Token, limit float64, burst int) *RateLimited {
if burst < 1 {
burst = 1
}
return &RateLimited{
Token: base,
limit: rate.NewLimiter(rate.Limit(limit), burst),
}
}
type rateLimitedKey struct {
token.Key
limit *rate.Limiter
}
func (r *RateLimited) GetKey(ctx context.Context, keyName string) (token.Key, error) {
start := time.Now()
if err := r.limit.Wait(ctx); err != nil {
return nil, err
}
if waited := time.Since(start); waited > 1*time.Millisecond {
metricRateLimited.Add(time.Since(start).Seconds())
}
key, err := r.Token.GetKey(ctx, keyName)
if err != nil {
return nil, err
}
return &rateLimitedKey{
Key: key,
limit: r.limit,
}, nil
}
func (k *rateLimitedKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (sig []byte, err error) {
start := time.Now()
if err := k.limit.Wait(context.Background()); err != nil {
return nil, err
}
if waited := time.Since(start); waited > 1*time.Millisecond {
metricRateLimited.Add(time.Since(start).Seconds())
}
return k.Key.Sign(rand, digest, opts)
}
func (k *rateLimitedKey) SignContext(ctx context.Context, digest []byte, opts crypto.SignerOpts) (sig []byte, err error) {
start := time.Now()
if err := k.limit.Wait(ctx); err != nil {
return nil, err
}
if waited := time.Since(start); waited > 1*time.Millisecond {
metricRateLimited.Add(time.Since(start).Seconds())
}
return k.Key.SignContext(ctx, digest, opts)
}
|
package models
import (
"time"
"github.com/kamalraimi/recruiter-api/config"
)
type Application struct {
ID uint `gorm:"primary_key" form:"id" json:"id"`
Civility string `sql:"type:enum('mr','mrs','miss');DEFAULT:'mr'"`
Name string `gorm:"type:varchar(100);index"`
BirthDay time.Time
Email string `gorm:"type:varchar(100);index"`
Tel string
ExpectedSalary float64
Step string `sql:"type:enum('initialSelection','firstInterview','secondInterview','contractProposal');DEFAULT:'initialSelection'"`
Status string `sql:"type:enum('inProgress','validated','rejected');DEFAULT:'inProgress'"`
CreatedAt time.Time
UpdatedAt time.Time
Position Position `gorm:"foreignkey:PostID;association_foreignkey:ID"`
PostID int
}
func FindAllApplication() ([]Application, error) {
var applications []Application
err := config.GetDB().Find(&applications).Error
return applications, err
}
func FindApplicationById(id string) (Application, error) {
var application Application
err := config.GetDB().Where("id = ?", id).First(&application).Error
return application, err
}
func CreateApplication(application *Application) (*Application, error) {
err := config.GetDB().Create(&application).Error
return application, err
}
func UpdateApplication(application *Application) (*Application, error) {
err := config.GetDB().Save(&application).Error
return application, err
}
func DeleteApplication(id string) error {
return config.GetDB().Where("id = ?", id).Delete(&Application{}).Error
}
|
/***
Copyright 2014 Cisco Systems Inc. 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 plugin
import (
"encoding/json"
"fmt"
"github.com/contiv/netplugin/core"
"github.com/contiv/netplugin/netmaster/mastercfg"
"github.com/contiv/netplugin/state"
"github.com/contiv/netplugin/utils"
"testing"
)
var fakeStateDriver *state.FakeStateDriver
func initFakeStateDriver(t *testing.T) {
// init fake state driver
instInfo := core.InstanceInfo{}
d, err := utils.NewStateDriver("fakedriver", &instInfo)
if err != nil {
t.Fatalf("failed to init statedriver. Error: %s", err)
}
fakeStateDriver = d.(*state.FakeStateDriver)
}
func deinitFakeStateDriver() {
// release fake state driver
utils.ReleaseStateDriver()
}
func TestNetPluginInit(t *testing.T) {
// Testing init NetPlugin
initFakeStateDriver(t)
defer deinitFakeStateDriver()
gCfg := mastercfg.GlobConfig{
FwdMode: "bridge",
PvtSubnet: "172.19.0.0/16"}
gCfg.StateDriver = fakeStateDriver
gCfg.Write()
configStr := `{
"drivers" : {
"network": "ovs",
"endpoint": "ovs",
"state": "fakedriver"
},
"plugin-instance": {
"host-label": "testHost",
"fwd-mode":"bridge"
}
}`
// Parse the config
pluginConfig := Config{}
err := json.Unmarshal([]byte(configStr), &pluginConfig)
if err != nil {
t.Fatalf("Error parsing config. Err: %v", err)
}
fmt.Printf("plugin config: %+v", pluginConfig)
plugin := NetPlugin{}
err = plugin.Init(pluginConfig)
if err != nil {
t.Fatalf("plugin init failed: Error: %s", err)
}
defer func() { plugin.Deinit() }()
}
func TestNetPluginInitInvalidConfigEmptyString(t *testing.T) {
// Test NetPlugin init failure when no config provided
pluginConfig := Config{}
plugin := NetPlugin{}
err := plugin.Init(pluginConfig)
if err == nil {
t.Fatalf("plugin init succeeded, should have failed!")
}
}
func TestNetPluginInitInvalidConfigMissingInstance(t *testing.T) {
// Test NetPlugin init failure when missing instance config
configStr := `{
"drivers" : {
"network": "ovs",
"endpoint": "ovs",
"state": "fakedriver"
}
}`
// Parse the config
pluginConfig := Config{}
err := json.Unmarshal([]byte(configStr), &pluginConfig)
plugin := NetPlugin{}
err = plugin.Init(pluginConfig)
if err == nil {
t.Fatalf("plugin init succeeded, should have failed!")
}
}
func TestNetPluginInitInvalidConfigEmptyHostLabel(t *testing.T) {
// Test NetPlugin init failure when empty HostLabel provided
configStr := `{
"drivers" : {
"network": "ovs",
"endpoint": "ovs",
"state": "fakedriver"
},
"plugin-instance": {
"host-label": "",
"fwd-mode":"bridge",
"db-url": "etcd://127.0.0.1:4001"
}
}`
// Parse the config
pluginConfig := Config{}
err := json.Unmarshal([]byte(configStr), &pluginConfig)
if err != nil {
t.Fatalf("Error parsing config. Err: %v", err)
}
plugin := NetPlugin{}
err = plugin.Init(pluginConfig)
if err == nil {
t.Fatalf("plugin init succeeded, should have failed!")
}
}
func TestNetPluginInitInvalidConfigMissingStateDriverName(t *testing.T) {
// Test NetPlugin init failure when missing state driver name
configStr := `{
"drivers" : {
"network": "ovs",
"endpoint": "ovs"
},
"plugin-instance": {
"host-label": "testHost",
"fwd-mode":"bridge",
"db-url": "etcd://127.0.0.1:4001"
}
}`
// Parse the config
pluginConfig := Config{}
err := json.Unmarshal([]byte(configStr), &pluginConfig)
if err != nil {
t.Fatalf("Error parsing config. Err: %v", err)
}
plugin := NetPlugin{}
err = plugin.Init(pluginConfig)
if err == nil {
t.Fatalf("plugin init succeeded, should have failed!")
}
}
func TestNetPluginInitInvalidConfigMissingStateDriverURL(t *testing.T) {
// Test NetPlugin init failure when missing state driver url
configStr := `{
"drivers" : {
"network": "ovs",
"endpoint": "ovs",
"state": "etcd"
},
"plugin-instance": {
"host-label": "testHost",
"fwd-mode":"bridge"
}
}`
// Parse the config
pluginConfig := Config{}
err := json.Unmarshal([]byte(configStr), &pluginConfig)
if err != nil {
t.Fatalf("Error parsing config. Err: %v", err)
}
plugin := NetPlugin{}
err = plugin.Init(pluginConfig)
if err == nil {
t.Fatalf("plugin init succeeded, should have failed!")
}
defer func() { plugin.Deinit() }()
}
func TestNetPluginInitInvalidConfigMissingNetworkDriverName(t *testing.T) {
// Test NetPlugin init failure when missing network driver name
initFakeStateDriver(t)
defer deinitFakeStateDriver()
gCfg := mastercfg.GlobConfig{
FwdMode: "bridge",
PvtSubnet: "172.19.0.0/16"}
gCfg.StateDriver = fakeStateDriver
gCfg.Write()
configStr := `{
"drivers" : {
"endpoint": "ovs",
"state": "fakedriver",
"container": "docker"
},
"plugin-instance": {
"host-label": "testHost",
"fwd-mode":"bridge",
"db-url": "etcd://127.0.0.1:4001"
}
}`
// Parse the config
pluginConfig := Config{}
err := json.Unmarshal([]byte(configStr), &pluginConfig)
if err != nil {
t.Fatalf("Error parsing config. Err: %v", err)
}
plugin := NetPlugin{}
err = plugin.Init(pluginConfig)
if err == nil {
t.Fatalf("plugin init succeeded, should have failed!")
}
}
func TestNetPluginInitInvalidConfigInvalidPrivateSubnet(t *testing.T) {
// Test NetPlugin init failure when private subnet is not valid
initFakeStateDriver(t)
defer deinitFakeStateDriver()
gCfg := mastercfg.GlobConfig{
FwdMode: "routing",
PvtSubnet: "172.19.0.0"}
gCfg.StateDriver = fakeStateDriver
gCfg.Write()
configStr := `{
"drivers" : {
"network": "ovs",
"endpoint": "ovs",
"state": "fakedriver",
"container": "docker",
},
"plugin-instance": {
"host-label": "testHost",
"db-url": "etcd://127.0.0.1:4001",
"fwd-mode":"routing",
}
}`
// Parse the config
pluginConfig := Config{}
err := json.Unmarshal([]byte(configStr), &pluginConfig)
plugin := NetPlugin{}
err = plugin.Init(pluginConfig)
if err == nil {
t.Fatalf("plugin init succeeded, should have failed!")
}
}
|
package controller
import (
"container/list"
"fmt"
"message/src/cn/cncommdata/study/model"
"sync"
"time"
)
func helloWorld() {
a := 1
c := &a
b := "hello world"
fmt.Printf("变量a地址地址为 %s \r\n", &a)
fmt.Printf("变量a值为 %v \r\n", *&a)
fmt.Printf("变量b地址地址为 %s \r\n", &b)
fmt.Printf("变量b值为 %v \r\n", *&b)
fmt.Printf("=将a的值传递给c,c的值为:%v \r\n", *c)
var arr [3]int
arr[1] = 20
arr[0] = 10
arr[2] = 30
fmt.Printf("数组的第一个元素的值为: %v \r\n", arr[0])
fmt.Printf("数组的第二个元素的值为: %v \r\n", arr[1])
fmt.Printf("数组的最后一个元素的值为: %v \r\n", arr[len(arr)-1])
//循环遍历数组
for k, v := range arr {
fmt.Print(k, v)
fmt.Println()
}
}
func array() {
// 多维数组
array1 := [4][2]int{{10, 11}, {20, 12}, {30, 134}, {404, 134}}
fmt.Printf("该二维数组的长度为:%v \n", len(array1))
for k, v := range array1 {
fmt.Println(k, v)
}
}
//切片
func mySlice() {
//定义数组,
var nameArr [30]int
//给数组赋值
for i := 0; i < 30; i++ {
nameArr[i] = i + 1
}
i2 := append(nameArr[:], 1, 2, 3)
fmt.Printf("nihao%v\r\n", i2)
//遍历数组
//切片
ints := nameArr[0:2]
fmt.Printf("数组的值为 %v\r\n切片的值为%v\r\n", nameArr, ints)
//将切片再次切片
i := ints[0:1]
fmt.Printf("ints切片再次切片的结果为%v\r\n", i)
//区间
fmt.Printf("区间切片%v\r\n", nameArr[10:15])
//中间到尾部的所有元素
fmt.Printf("中间到尾部的所有元素%v\r\n", nameArr[20:])
//开头到中间指定位置的元素
fmt.Printf("开头到中间到指定位置的所有元素%v\r\n", nameArr[:10])
}
//原始切片
func OriginSlice() {
var numbers []int
for i := 0; i < 20; i++ {
numbers = append(numbers, append([]int{7, 8, 9}, []int{i}...)...)
fmt.Println(numbers)
fmt.Printf("切片长度%d,切片容量%d,切片地址值%p\r\n", len(numbers), cap(numbers), numbers)
}
}
//重置切片
func resetSlice() {
a := []int{1, 2, 3}
fmt.Printf("原始切片为%v,重置后的切片为%v", a[:], a[0:0])
}
//直接声明切片
func directStatementSlice() {
//声明字符串切片
var strList []string
//声明整形切片
var numberList []int
//声明一个空切片 分配了内存,所以不是空的
var numberListEmpty = []int{}
//输出3个切片
fmt.Println(strList, numberList, numberListEmpty)
//输出3个切片的大小
fmt.Println(len(strList), len(numberList), len(numberListEmpty))
//切片判定空的结果
fmt.Println(strList == nil)
fmt.Println(numberList == nil)
fmt.Println(numberListEmpty == nil)
//获取内存地址
fmt.Printf("strList的内存地址为%p;numberList的内存地址为%p;numberListEmpty的内存地址为%p\n", &strList, &numberList, &numberListEmpty)
fmt.Printf("strList的内存地址为%p;numberList的内存地址为%p;numberListEmpty的内存地址为%p", strList, numberList, numberListEmpty)
}
//使用make函数构造切片
func useMakeFunConstructSlice() {
//如果需要动态地创建一个切片,可以使用make函数
//其中a和b均是预分配2个元素的切片,只是b的内部存储空间已经分配了10个,但实际是用来2个元素
b := make([]int, 2, 10)
a := make([]int, 2)
fmt.Println(len(b), len(a))
fmt.Println(b, a)
//温馨提示: 使用make函数生成的切片一定发生了内存分配,但给定开始与结束位置(包括切片复位)的切片只是将新的切片结构指向已经分配好的内存区域,设定开始与结束位置,不会发生内存分配操作
}
//使用append为切片添加元素
func useAppendAddElement() {
}
func PractiseMap() {
strings := make(map[string][]model.EmailParam, 30)
strings["name"] = []model.EmailParam{
{ServerHost: "libing_niu@163.com"},
{ServerPort: 645},
{FromEmail: "43"},
{FromPasswd: "4324"},
{Toers: "ewr"},
{CCers: "rerw"},
}
delete(strings, "name")
fmt.Println(strings)
}
func PractiseSynicMap() {
var scene sync.Map
//添加元素
scene.Store("name", "niulibing")
scene.Store("sex", "男")
fmt.Printf("map集合添加的元素为:%v\r\n", scene)
//获取元素
value, _ := scene.Load("name")
fmt.Printf("通过name键获取到的元素为%v\r\n", value)
//删除元素
scene.Delete("sex")
fmt.Println(scene)
}
func PractiseList() {
//list 的初始化有两种方法:分别是使用 New() 函数和 var 关键字声明,两种方法的初始化效果都是一致的。
//双链表支持从队列前方或后方插入元素,分别对应的方法是 PushFront 和 PushBack。
i := list.New()
i.PushBack(1)
i.PushBack(2)
fmt.Printf("golist插入的数据为%v", &i)
//make和new的区别
// make只能初始化go语言中的基本类型 make用于创建切片、哈希表、和管道等内置数据结构
// new只接受一个类型作为参数,然后返回一个指向这个类型的指针 new用于分配并创建一个指向对应类型的指针
}
//可变参数
func Myfunc(a ...interface{}) {
now := time.Now()
for k, v := range a {
fmt.Println(k, v)
}
since := time.Since(now)
fmt.Printf("程序执行了%v", since)
}
type Wheel struct {
Size int
}
type Engine struct {
Power int
Type string
}
type Car struct {
Wheel
Engine
}
func StartCar() {
}
|
package nifdc
import (
"encoding/gob"
"fmt"
"github.com/json-iterator/go"
"os"
"test.com/a/grequests"
"testing"
)
func TestLogin(t *testing.T) {
}
func TestRe(t *testing.T) {
olds := `
<html>
<head>
<title>普通食品检验填报</title>
<link href="/test_platform/css/bootstrap.min.css?v=1.0.1" rel="stylesheet">
<link href="/test_platform/css/font-awesome.min.css?v=4.4.0" rel="stylesheet">
<link href="/test_platform/css/animate.min.css" rel="stylesheet">
<link href="/test_platform/css/style.min.css?v=4.0.2" rel="stylesheet">
<link href="/test_platform/css/plugins/toastr/toastr.min.css?v=4.0.2" rel="stylesheet">
<link href="/test_platform/css/plugins/datapicker/datepicker3.css?v=4.0.2" rel="stylesheet">
<link href="/test_platform/css/plugins/chosen/chosen.css?v=4.0.2" rel="stylesheet">
<link rel="shortcut icon" href="/test_platform/favicon.ico">
<link href="/test_platform/js/plugins/fancybox/jquery.fancybox.css" rel="stylesheet">
<link href="/test_platform/layer/theme/default/layer.css" rel="stylesheet">
<style>
.fixed-table-body{
height: auto !important;
}
.row input[type=text],.row select,.row textarea{
font-size: 13px !important;
}
</style>
<link rel="stylesheet" type="text/css" href="/test_platform/easyui/themes/metro/easyui.css">
<link rel="stylesheet" type="text/css" href="/test_platform/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="/test_platform/easyui/themes/color.css">
<link rel="stylesheet" type="text/css" href="/test_platform/css/webuploader.css">
<link rel="stylesheet" type="text/css" href="/test_platform/js/plugins/fancybox/viewer.min.css">
<style>
.tb_input {
border: none;
text-align: center;
background: transparent;
margin: 0 auto;
}
/*bootstrap兼容问题和easyui的bug*/
.panel-header, .panel-body {
}
.datagrid, .combo-p {
border: solid 1px #D4D4D4;
}
.datagrid * {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
</style>
</head>
<body>
<div class="wrapper wrapper-content fadeInDown">
<div class="container-fluid">
<h1>普通食品检验数据填报
<small class="text-danger"> 抽样编号:GC20131100120630263</small>
</h1>
<div class="panel panel-success">
<div class="panel-heading">
<h5 class="panel-title" style="color: #ffffff;">
<a data-toggle="collapse" title="点击展开或收起" data-parent="#accordion" href="#collapseOne"
aria-expanded="false"
class="collapsed"><i class="fa fa-info-circle"></i> 抽样信息内容
<small style="color: #ffffff;">(点击展开或收起)</small>
</a>
</h5>
</div>
<div id="collapseOne" class="panel-collapse collapse" aria-expanded="false" style="height: 0px;">
<div class="panel-body" style="padding: 15px;">
<div class="row">
<div class="col-sm-12">
<div class="ibox float-e-margins">
<h2>抽样基础信息</h2>
<div class="hr-line-dashed"></div>
<div class="row form-group">
<div class="col-sm-4 ">
<label class="control-label col-sm-4">任务来源:</label>
<div class="col-sm-8">河北省市场监督管理局</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">报送分类A:</label>
<div class="col-sm-8" id="bsfla">抽检监测(转移地方)
<input type="hidden" id="hid_bsfla" value="抽检监测(转移地方)"/>
</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">报送分类B:</label>
<div class="col-sm-8" id="bsflb">2020年总局抽检计划
<input type="hidden" id="hid_bsflb" value="2020年总局抽检计划"/>
</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">食品大类:</label>
<div class="col-sm-8" id="type1">食用农产品
<input type="hidden" id="hid_type1" value="食用农产品"/>
</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">食品亚类:</label>
<div class="col-sm-8" id="type2">畜禽肉及副产品
<input type="hidden" id="hid_type2" value="畜禽肉及副产品"/>
</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">食品次亚类:</label>
<div class="col-sm-8" id="type3">禽肉
<input type="hidden" id="hid_type3" value="禽肉"/>
</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">食品细类:</label>
<div class="col-sm-8" id="type4">鸡肉
<input type="hidden" id="hid_type4" value="鸡肉"/>
</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">抽样单编号:</label>
<div class="col-sm-8">GC20131100120630263</div>
<input type="hidden" id="hid_sp_s_16" value="GC20131100120630263"/>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">抽样类型:</label>
<div class="col-sm-8">常规抽样</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 ">
<div class="ibox float-e-margins">
<h2>抽样单位信息</h2>
<div class="hr-line-dashed"></div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">抽样单位名称:</label>
<div class="col-sm-8">衡水市食品药品检验检测中心</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">单位地址:</label>
<div class="col-sm-8">衡水市永兴西路2488号</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">所在省份:</label>
<div class="col-sm-8">河北</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">抽样人员:</label>
<div class="col-sm-8">雷倩、蔡勇</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">抽样人员电话:</label>
<div class="col-sm-8">2187675</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">单位联系人:</label>
<div class="col-sm-8">李春花</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">传真:</label>
<div class="col-sm-8">03182187675</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">邮编:</label>
<div class="col-sm-8">053000</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">联系人电话:</label>
<div class="col-sm-8">2187675</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 ">
<div class="ibox float-e-margins">
<h2>抽检场所信息</h2>
<div class="hr-line-dashed"></div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">单位名称:</label>
<div class="col-sm-8">衡水中硕商贸有限公司</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">单位地址:</label>
<div class="col-sm-8">河北省衡水市桃城区榕花北大街696号嗨购广场1幢1号1-3层</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">所在地:</label>
<div class="col-sm-8">河北/衡水/桃城区</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">区域类型:</label>
<div class="col-sm-8">城市</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">抽样环节:</label>
<div class="col-sm-8">流通</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">抽样地点:</label>
<div class="col-sm-8">超市</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">营业执照/社会信用代码:</label>
<div class="col-sm-8">91131102MA0F4BGG58</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">许可证类型:</label>
<div class="col-sm-8">经营许可证</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">许可证号:</label>
<div class="col-sm-8">JY11311020055287</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">单位法人:</label>
<div class="col-sm-8">孙云鹏</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">联系人:</label>
<div class="col-sm-8">陈华明</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">联系人电话:</label>
<div class="col-sm-8">13102761536</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">邮编:</label>
<div class="col-sm-8">/</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">年销售额:</label>
<div class="col-sm-8">/</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 ">
<div class="ibox float-e-margins">
<h2>生产企业信息</h2>
<div class="hr-line-dashed"></div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">企业名称:</label>
<div class="col-sm-8">/</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">所在地:</label>
<div class="col-sm-8">河北/衡水/桃城区</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">企业地址:</label>
<div class="col-sm-8">/</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">生产许可证编号:</label>
<div class="col-sm-8">/</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">电话:</label>
<div class="col-sm-8">/</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">是否存在第三方企业信息:</label>
<div class="col-sm-8">否</div>
</div>
<div class="col-sm-4">
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 ">
<div class="ibox float-e-margins">
<h2>抽检样品信息</h2>
<div class="hr-line-dashed"></div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">样品条码:</label>
<div class="col-sm-8">/</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">样品商标:</label>
<div class="col-sm-8">/</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">样品类型:</label>
<div class="col-sm-8">食用农产品</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">样品来源:</label>
<div class="col-sm-8">外购</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">样品属性:</label>
<div class="col-sm-8">普通食品</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">包装规格:</label>
<div class="col-sm-8">无包装</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">样品名称:</label>
<div class="col-sm-8">带骨上腿肉(鸡肉)</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">购进日期:</label>
<div class="col-sm-8">2020-08-27</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">保质期:</label>
<div class="col-sm-8">/</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">样品批号:</label>
<div class="col-sm-8">/</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">样品规格:</label>
<div class="col-sm-8">/</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">质量等级:</label>
<div class="col-sm-8">/</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">单价:</label>
<div class="col-sm-8">11.80元/kg</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">是否进口:</label>
<div class="col-sm-8">否</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">原产地:</label>
<div class="col-sm-8">中国</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">抽样日期:</label>
<div class="col-sm-8">2020-08-27</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">抽样方式:</label>
<div class="col-sm-8">非无菌采样</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">储存条件:</label>
<div class="col-sm-8">常温</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">抽样基数:</label>
<div class="col-sm-8">4kg</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">抽样数量:</label>
<div class="col-sm-8">3.042</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">备样数量:</label>
<div class="col-sm-8">1kg</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-4">
<label class="control-label col-sm-4">抽样数量单位:</label>
<div class="col-sm-8">kg</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">执行标准/技术文件:</label>
<div class="col-sm-8">/</div>
</div>
<div class="col-sm-4">
<label class="control-label col-sm-4">备注:</label>
<div class="col-sm-8">/</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="ibox float-e-margins">
<h2>照片信息</h2>
<div class="row form-group">
<div class="col-sm-12">
<ul id="dowebok">
<div style="display: inline-block; overflow: hidden">
<img style="width:150px;height:150px;margin-right: 15px;"
src="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/159851560813442144.jpeg" data-original="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/159851560813442144.jpeg"
alt="现场抽样图片">
<p>图片1</p>
</div>
<div style="display: inline-block; overflow: hidden">
<img style="width:150px;height:150px;margin-right: 15px;"
src="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/15985156064323218.jpeg" data-original="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/15985156064323218.jpeg"
alt="现场抽样图片">
<p>图片2</p>
</div>
<div style="display: inline-block; overflow: hidden">
<img style="width:150px;height:150px;margin-right: 15px;"
src="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/159851561244119149.jpeg" data-original="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/159851561244119149.jpeg"
alt="现场抽样图片">
<p>图片3</p>
</div>
<div style="display: inline-block; overflow: hidden">
<img style="width:150px;height:150px;margin-right: 15px;"
src="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/159851560320043979.jpeg" data-original="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/159851560320043979.jpeg"
alt="现场抽样图片">
<p>图片4</p>
</div>
<div style="display: inline-block; overflow: hidden">
<img style="width:150px;height:150px;margin-right: 15px;"
src="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/159851560316332108.jpeg" data-original="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/159851560316332108.jpeg"
alt="现场抽样图片">
<p>图片5</p>
</div>
<div style="display: inline-block; overflow: hidden">
<img style="width:150px;height:150px;margin-right: 15px;"
src="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/159851562646042922.jpeg" data-original="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/159851562646042922.jpeg"
alt="现场抽样图片">
<p>图片6</p>
</div>
<div style="display: inline-block; overflow: hidden">
<img style="width:150px;height:150px;margin-right: 15px;"
src="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/159851562595736573.jpeg" data-original="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/159851562595736573.jpeg"
alt="现场抽样图片">
<p>图片7</p>
</div>
<div style="display: inline-block; overflow: hidden">
<img style="width:150px;height:150px;margin-right: 15px;"
src="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/159851778475926606.jpeg" data-original="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/159851778475926606.jpeg"
alt="现场抽样图片">
<p>图片8</p>
</div>
</ul>
</div>
</div>
<div class="row form-group">
<div class="col-sm-12">
<a href="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/159851567457840540.png" target="_blank"
class="btn btn-danger btn-xs"><i
class="fa fa-search"></i> 抽样单电子版</a>
<a href="http://spcjupload2.gsxt.gov.cn/image/2020/08/27/159851566023639799.png" target="_blank"
class="btn btn-danger btn-xs"><i
class="fa fa-search"></i> 抽样检验告知书电子版</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<form>
<div class="row">
<div class="col-sm-12 form-horizontal">
<div class="ibox float-e-margins">
<h2>检验信息</h2>
<div class="hr-line-dashed"></div>
<div class="row">
<div class="col-sm-4 form-group">
<label class="control-label col-sm-5">检验机构名称:</label>
<div class="col-sm-7">
<input type="text" disabled="disabled" value="衡水市食品药品检验检测中心"
class="form-control">
<input type="hidden" id="test_unit" name="test_unit" value="衡水市食品药品检验检测中心"/>
</div>
</div>
<div class="col-sm-4 form-group">
<label class="control-label col-sm-5">报告书编号:</label>
<div class="col-sm-7">
<input type="text" id="report_no" name="report_no" value=""
class="form-control"
title="请输入报告书编号" required>
</div>
</div>
<div class="col-sm-4 form-group">
<label class="control-label col-sm-5">样品到达日期:</label>
<div class="col-sm-7">
<div class="input-group date">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input type="text" disabled id="test_date" name="test_date" class="form-control"
value="2020-08-28"
placeholder="请选择日期"
data-provide="datepicker">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4 form-group">
<label class="control-label col-sm-5">联系人:</label>
<div class="col-sm-7">
<input type="text" disabled id="contact" name="contact"
value="李春花"
class="form-control">
</div>
</div>
<div class="col-sm-4 form-group">
<label class="control-label col-sm-5">联系人电话:</label>
<div class="col-sm-7">
<input type="text" disabled id="contact_tel" name="contact_tel"
value="2187675"
class="form-control"
title="请输入有效的座机号或手机号">
</div>
</div>
<div class="col-sm-4 form-group">
<label class="control-label col-sm-5">联系人邮箱:</label>
<div class="col-sm-7">
<input type="text" disabled title="请输入有效的邮箱"
id="contact_email"
name="contact_email" value="hssspyp@sina.com"
class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4 form-group">
<label class="control-label col-sm-5">检查封样人员:</label>
<div class="col-sm-7">
<input type="text" id="fy_person" name="fy_person" value="李聪"
class="form-control" required>
</div>
</div>
<div class="col-sm-4 form-group">
<label class="control-label col-sm-5">检查封样人电话:</label>
<div class="col-sm-7">
<input type="text" title="请输入有效的座机号或手机号"
required id="fy_tel" name="fy_tel" value="15333388077"
class="form-control">
</div>
</div>
<div class="col-sm-4 form-group">
<label class="control-label col-sm-5">检查封样人邮箱:</label>
<div class="col-sm-7">
<input type="text" title="请输入有效的邮箱"
required
id="fy_email" name="fy_email" value="/"
class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4 form-group">
<label class="control-label col-sm-5">结论:</label>
<div class="col-sm-7">
<input type="text" disabled id="conclusion" value=""
class="form-control">
<input type="hidden" id="hid_conclusion" name="conclusion"
value=""/>
</div>
</div>
<div class="col-sm-4 form-group">
<label class="control-label col-sm-5">报告类别:</label>
<div class="col-sm-7">
<select class="form-control" id="sp_bsb_bgfl" name="report_type">
<option
value="合格报告">合格报告</option>
<option
value="一般不合格报告">一般不合格报告</option>
<option
value="一般问题报告">一般问题报告</option>
<option
value="一般不合格(问题)报告">一般不合格(问题)报告</option>
<option
value="24小时限时报告">24小时限时报告</option>
</select>
</div>
</div>
<div class="col-sm-4 form-group">
<label class="control-label col-sm-5">检验目的/任务类别:</label>
<div class="col-sm-7">
<select class="form-control" disabled id="test_aims" name="test_aims">
<option selected="selected"
value="监督抽检">监督抽检</option>
<option
value="抽检监测">抽检监测</option>
<option
value="风险监测">风险监测</option>
<option
value="评价性抽检">评价性抽检</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4 form-group hidden">
<label class="control-label col-sm-5">接样日期:</label>
<div class="col-sm-7">
<div class="input-group date">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input type="text" disabled="disabled" id="tb_date" name="tb_date"
class="form-control"
value="2020-08-28"
placeholder="请选择日期"
data-provide="datepicker" id="startDate">
</div>
</div>
</div>
<div class="col-sm-4 form-group">
<label class="control-label col-sm-5">监督抽检报告备注:</label>
<div class="col-sm-7">
<textarea id="jd_bz" rows="4" name="jd_bz"
class="form-control"></textarea>
</div>
</div>
<div class="col-sm-4 form-group">
<label class="control-label col-sm-5">风险监测报告备注:</label>
<div class="col-sm-7">
<textarea id="fx_bz" rows="4" name="fx_bz"
class="form-control"></textarea>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4 form-group">
<label class="control-label col-sm-5">历史退回原因:</label>
<div class="col-sm-7">
<a id="showBackReason" class="btn btn-success btn-xs">点击查看</a>
</div>
</div>
</div>
</div>
<div class="row hidden" id="div-upload1">
<div class="col-sm-6">
<div class="alert alert-danger">
<div id="uploader1" class="wu-example">
<!--用来存放文件信息-->
<div id="thelist1" class="uploader-list"></div>
<span id="picker1">选择文件</span>
<label class="help-block m-b-none text-danger">上传24小时限时报告附件</label>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="alert alert-info alert-dismissable">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×
</button>
<p>(1)标准最小允许限、标准最大允许限是根据判定依据确定或根据常见食品品种核定,承检机构应根据检验的具体产品确定最小允许限、最大允许限。</p>
<p>(2)标准方法检出限是根据检验方法标准确定或核定(标准中未规定检出限或定量限时),承检机构应根据具体情况确定。</p>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="alert alert-danger">
<label>上下标提示: 1.输入上标:Ctrl + Alt + (数字或+-号) , 2.输入下标:Alt + 数字(数字或+-号)。</label>
</div>
</div>
<div class="col-sm-6"></div>
</div>
<div class="row">
<div class="col-sm-4">
<input type="text" id="search" class="form-control" placeholder="输入项目名称进行快速定位"/>
<label class="help-block m-b-none text-danger">提示:在文本框中输入检验项目名称的关键字可以快速定位检验项目</label>
</div>
<div class="col-sm-4">
</div>
<div class="col-sm-4 text-right form-inline">
<input class="form-control" placeholder="请输入抽样单号" id="txt_sampleNO" autocomplete="on">
<button type="button" id="load_his" class="btn btn-primary" style="margin-bottom: 0;">
加载历史数据
</button>
<label class="help-block m-b-none text-danger">提示: 自动加载相同食品类别和报送分类的最后一次提交的检验数据</label>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<table id="dg" title="检验结果" class="easyui-datagrid" style="width:auto;height: 380px;"
rownumbers="true" fitColumns="true" singleSelect="true">
</table>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p>
<h3>检验结论</h3></p>
<div class="hr-line-dashed"></div>
<textarea id="test_conclusion" name="test_conclusion"
style="width: 100%;font-size: 16px;"
rows="5"></textarea>
</div>
</div>
<input type="hidden" id="sd" name="sd" value="fmHrUgGNZkr7YdZKrnFJ7YlNUXmj7YoVQjl4WqF9Z9c=">
<input type="hidden" id="st" name="sd" value="-1">
<input type="hidden" id="userId" value="R0rN23mmF5kjyxhjeremyfsZQiHBPrTlBBKtLup5">
<input type="hidden" id="xs" value="">
<input type="hidden" id="unqualifed" value="">
<div class="row hidden" id="div-upload" style="margin-top: 10px">
<div class="col-sm-6">
<div class="alert alert-danger">
<div id="uploader" class="wu-example">
<!--用来存放文件信息-->
<div id="thelist" class="uploader-list"></div>
<span id="picker">选择文件</span>
<label class="help-block m-b-none text-danger">上传24小时限时报告附件</label>
</div>
</div>
</div>
</div>
<div class="row" style="margin-top: 10px">
<div class="col-sm-12">
<button class="btn btn-success" id="save" type="button">临时保存</button>
<button class="btn btn-primary" id="submit" type="submit">检测数据提交入库</button>
<button class="btn btn-danger" id="back" type="button">退修</button>
<button class="btn btn-info" id="item-reset" type="button">检验项目重置</button>
<span class="help-block m-b-none text-danger">提示:点击检验项目重置按钮可以重新加载最新的基础表</span>
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="row hidden">
<div class="col-sm-12">
<h3>历史报告</h3>
<button class="btn btn-default" type="button">无</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<div class="hidden" id="back-div">
<textarea class="form-control" style="width: 99%; margin: 5px auto;overflow-x: hidden" rows="5"
placeholder="请输入退回原因..." id="backReason"></textarea>
<div class="text-right">
<button id="btn-back" type="button" style="margin: 5px 5px" class="btn btn-danger">退回</button>
<button id="btn-cancel" type="button" style="margin: 5px 5px" class="btn btn-default">取消</button>
</div>
</div>
<div class="hidden" id="save-div">
<div class="input-group">
<input type="text" class="form-control" id="verifyCode"name="verifyCode" placeholder="请输入验证码">
</div>
<span style="text-align: center;">
<img src="/test_platform/verifyCode" id="vcImg" onclick="myRefersh(this)">
</span>
<div class="text-right">
<button id="btn-save" type="button" style="margin: 5px 5px" class="btn btn-danger">保存</button>
<button id="btn-cance2" type="button" style="margin: 5px 5px" class="btn btn-default">取消</button>
</div>
</div>
<script type="text/javascript" src="/test_platform/js/jquery.min.js"></script>
<script type="text/javascript" src="/test_platform/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/test_platform/js/plugins/toastr/toastr.min.js"></script>
<script type="text/javascript" src="/test_platform/js/plugins/datapicker/bootstrap-datepicker.js"></script>
<script type="text/javascript" src="/test_platform/js/plugins/chosen/chosen.jquery.js"></script>
<script type="text/javascript" src="/test_platform/js/plugins/layer/layer.min.js"></script>
<script type="text/javascript" src="/test_platform/js/jquery.cookie.js"></script>
<script type="text/javascript" src="/test_platform/js/common/globaltools.js?v=1.2.0.44"></script>
<script>
$(function () {
$("[data-toggle='tooltip']").tooltip();
var viewer = new Viewer(document.getElementById('dowebok'), {
url: 'data-original'
});
});
</script>
<script src="/test_platform/js/webuploader.js"></script>
<script src="/test_platform/js/plugins/layer/layer.min.js"></script>
<script src="/test_platform/js/plugins/fancybox/jquery.fancybox.js"></script>
<script src="/test_platform/js/plugins/fancybox/viewer.min.js"></script>
<script src="/test_platform/easyui/jquery.easyui.min.js"></script>
<script src="/test_platform/easyui/locale/easyui-lang-zh_CN.js"></script>
<script src="/test_platform/js/uploadTool.js"></script>
<script src="/test_platform/js/food/foodDetail.js?v=1.2.0.44"></script>
</body>
</html>
`
mkr := StoMap_test_platform(olds)
fmt.Println(mkr)
//fmt.Println(mkr["抽检样品信息_生产日期"])
//for k, v := range mkr {
// fmt.Printf("%s:%s\n", k, v)
//}
//tmj := template.New("tmj")
//tmj.Funcs(map[string]interface{}{
// "replace": strings.ReplaceAll,
//})
//tmj.Parse("aaa{{ .抽样单位信息_传真 }} {{ .抽样基础信息_食品次亚类 }}")
//fmt.Println(tmj.Execute(os.Stdout, mkr))
}
func TestTest_platform_api_food_getTestItems(t *testing.T) {
cli:=grequests.NewSession(&grequests.RequestOptions{
RedirectLimit: 1000,
})
a, b, c, err := InitLoginck(cli)
if err != nil {
t.Fatal(err)
}
ck, err:= Login("5050620402", "sps63302570", a, b, c, nil)
if err != nil {
t.Fatal(err)
}
test_platform_ck, err := Test_platform_login(ck,nil)
if err != nil {
t.Fatal(err)
}
fddetail, err := Test_platform_agricultureTest_agricultureDetail(12940542, true, test_platform_ck, nil)
if err != nil {
t.Fatal(err)
}
sd := fddetail.Get("sd").ToString()
itemsr, err := Test_platform_api_agriculture_getTestItems(fddetail, test_platform_ck, nil)
if err != nil {
t.Fatal(err)
}
testinfor, err := Test_platform_api_agriculture_getTestInfo(sd, test_platform_ck, nil)
if err != nil {
t.Fatal(err)
}
mps := Build_agriculture_updata(jsoniter.Wrap([]map[string]string{
{
"检验项目": "五氯酚酸钠(以五氯酚计)",
"检验结果": "0.1",
"结果判定": "合格项",
"检验方法": "/",
"判定依据": "/1",
"说明": "aaa",
},
}),itemsr.Rows, testinfor.Rows,)
err = Test_platform_api_agriculture_save(fddetail, mps, test_platform_ck, nil)
fmt.Println(err)
//for _,it:=range mps{
// for k,v:=range it{
// fmt.Printf("%s:%s\n",k,v)
// }
//}
}
func TestBuildbaogao(t *testing.T) {
//var updates []map[string]string
//redf, err := os.Open("./test_baogaodata")
//if err != nil {
// panic(err)
//}
//dc := gob.NewDecoder(redf)
//err = dc.Decode(&updates)
//if err != nil {
// panic(err)
//}
//fmt.Println(updates[0]["item"])
//updates[0]["sp_data_2"] = "不合格项"
//updates[1]["sp_data_2"] = "不合格项"
//updates[2]["sp_data_2"] = "不合格项"
//updates[3]["sp_data_2"] = "不合格项"
////for _, item := range updates {
//// fmt.Println(item)
////}
//cvdata := Convbaotaodata(updates)
//fmt.Println(Buildbaogao(cvdata))
}
func TestMerge_subitem(t *testing.T) {
updatas := make([]map[string]string, 0)
subitem := make([]map[string]string, 0)
fc, _ := os.Open("./jobtmp")
e := gob.NewDecoder(fc)
e.Decode(&updatas)
fc1, _ := os.Open("./jobtmp1")
e1 := gob.NewDecoder(fc1)
e1.Decode(&subitem)
updatas = MergeUpdates(updatas, subitem)
for _, update := range subitem {
fmt.Println(update["检验项目"], "=>", update["检验结果"])
}
for _, update := range updatas {
fmt.Println(update["item"], "=>", update["sp_data_1"])
}
}
func TestTest_platform_foodTest_foodDetail(t *testing.T) {
ck := "JSESSIONID=C248ACBED0C85FC725157B9ECE50066C-n3;sod=leYDFuSnkFivrosGM5PIfUP972YJATho+2y9TVZBqWDT6EZLBtjURt+FfyxhjeremyFLs5gYY4yfC2qsdjk="
r, err := Test_platform_foodTest_foodDetail(15042534, true, ck, nil)
if err != nil {
panic(err)
}
fmt.Println("抽样基础信息_抽样单编号:", r.Get("抽样基础信息_抽样单编号").ToString())
t.Log(r.ToString())
}
|
/*
Copyright 2022 Gravitational, 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 db
import (
"fmt"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/elasticache"
"github.com/stretchr/testify/require"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/lib/cloud"
"github.com/gravitational/teleport/lib/cloud/mocks"
"github.com/gravitational/teleport/lib/services"
)
func TestElastiCacheFetcher(t *testing.T) {
t.Parallel()
elasticacheProd, elasticacheDatabaseProd, elasticacheProdTags := makeElastiCacheCluster(t, "ec1", "us-east-1", "prod")
elasticacheQA, elasticacheDatabaseQA, elasticacheQATags := makeElastiCacheCluster(t, "ec2", "us-east-1", "qa", withElastiCacheConfigurationEndpoint())
elasticacheUnavailable, _, elasticacheUnavailableTags := makeElastiCacheCluster(t, "ec4", "us-east-1", "prod", func(cluster *elasticache.ReplicationGroup) {
cluster.Status = aws.String("deleting")
})
elasticacheUnsupported, _, elasticacheUnsupportedTags := makeElastiCacheCluster(t, "ec5", "us-east-1", "prod", func(cluster *elasticache.ReplicationGroup) {
cluster.TransitEncryptionEnabled = aws.Bool(false)
})
elasticacheTagsByARN := map[string][]*elasticache.Tag{
aws.StringValue(elasticacheProd.ARN): elasticacheProdTags,
aws.StringValue(elasticacheQA.ARN): elasticacheQATags,
aws.StringValue(elasticacheUnavailable.ARN): elasticacheUnavailableTags,
aws.StringValue(elasticacheUnsupported.ARN): elasticacheUnsupportedTags,
}
tests := []awsFetcherTest{
{
name: "fetch all",
inputClients: &cloud.TestCloudClients{
ElastiCache: &mocks.ElastiCacheMock{
ReplicationGroups: []*elasticache.ReplicationGroup{elasticacheProd, elasticacheQA},
TagsByARN: elasticacheTagsByARN,
},
},
inputMatchers: makeAWSMatchersForType(services.AWSMatcherElastiCache, "us-east-1", wildcardLabels),
wantDatabases: types.Databases{elasticacheDatabaseProd, elasticacheDatabaseQA},
},
{
name: "fetch prod",
inputClients: &cloud.TestCloudClients{
ElastiCache: &mocks.ElastiCacheMock{
ReplicationGroups: []*elasticache.ReplicationGroup{elasticacheProd, elasticacheQA},
TagsByARN: elasticacheTagsByARN,
},
},
inputMatchers: makeAWSMatchersForType(services.AWSMatcherElastiCache, "us-east-1", envProdLabels),
wantDatabases: types.Databases{elasticacheDatabaseProd},
},
{
name: "skip unavailable",
inputClients: &cloud.TestCloudClients{
ElastiCache: &mocks.ElastiCacheMock{
ReplicationGroups: []*elasticache.ReplicationGroup{elasticacheProd, elasticacheUnavailable},
TagsByARN: elasticacheTagsByARN,
},
},
inputMatchers: makeAWSMatchersForType(services.AWSMatcherElastiCache, "us-east-1", wildcardLabels),
wantDatabases: types.Databases{elasticacheDatabaseProd},
},
{
name: "skip unsupported",
inputClients: &cloud.TestCloudClients{
ElastiCache: &mocks.ElastiCacheMock{
ReplicationGroups: []*elasticache.ReplicationGroup{elasticacheProd, elasticacheUnsupported},
TagsByARN: elasticacheTagsByARN,
},
},
inputMatchers: makeAWSMatchersForType(services.AWSMatcherElastiCache, "us-east-1", wildcardLabels),
wantDatabases: types.Databases{elasticacheDatabaseProd},
},
}
testAWSFetchers(t, tests...)
}
func makeElastiCacheCluster(t *testing.T, name, region, env string, opts ...func(*elasticache.ReplicationGroup)) (*elasticache.ReplicationGroup, types.Database, []*elasticache.Tag) {
cluster := &elasticache.ReplicationGroup{
ARN: aws.String(fmt.Sprintf("arn:aws:elasticache:%s:123456789012:replicationgroup:%s", region, name)),
ReplicationGroupId: aws.String(name),
Status: aws.String("available"),
TransitEncryptionEnabled: aws.Bool(true),
// Default has one primary endpoint in the only node group.
NodeGroups: []*elasticache.NodeGroup{{
PrimaryEndpoint: &elasticache.Endpoint{
Address: aws.String("primary.localhost"),
Port: aws.Int64(6379),
},
}},
}
for _, opt := range opts {
opt(cluster)
}
tags := []*elasticache.Tag{{
Key: aws.String("env"),
Value: aws.String(env),
}}
extraLabels := services.ExtraElastiCacheLabels(cluster, tags, nil, nil)
if aws.BoolValue(cluster.ClusterEnabled) {
database, err := services.NewDatabaseFromElastiCacheConfigurationEndpoint(cluster, extraLabels)
require.NoError(t, err)
return cluster, database, tags
}
databases, err := services.NewDatabasesFromElastiCacheNodeGroups(cluster, extraLabels)
require.NoError(t, err)
require.Len(t, databases, 1)
return cluster, databases[0], tags
}
// withElastiCacheConfigurationEndpoint returns an option function for
// makeElastiCacheCluster to set a configuration endpoint.
func withElastiCacheConfigurationEndpoint() func(*elasticache.ReplicationGroup) {
return func(cluster *elasticache.ReplicationGroup) {
cluster.ClusterEnabled = aws.Bool(true)
cluster.ConfigurationEndpoint = &elasticache.Endpoint{
Address: aws.String("configuration.localhost"),
Port: aws.Int64(6379),
}
}
}
|
package bpi
import "github.com/dasfoo/i2c"
// BrightPI i2c wrapper. Built from code examples at:
// https://www.pi-supply.com/bright-pi-v1-0-code-examples/
// and register specification at:
// http://www.semtech.com/images/datasheet/sc620.pdf (page 14)
//
// Example usage:
// b := bpi.NewBrightPI(bus, bpi.DefaultBPiAddress)
// defer b.Sleep()
// b.Power(bpi.WhiteAll) // Enable all white leds
// b.Dim(bpi.WhiteAll, bpi.MaxDim) // Make white leds go brighter
// b.Gain(bpi.MaxGain) // Maximum brightness
// time.Sleep(time.Second)
// b.Power(bpi.IRAll) // Switch to IR leds only
// // The gain value is kept, so IR leds are brighter than default. Reset the gain.
// b.Gain(bpi.DefaultGain)
type BrightPI struct {
bus i2c.Bus
bpiAddr byte
}
// DefaultAddress is a default BrightPI Address
const DefaultAddress = 0x70
// NewBrightPI creates an instance of BrightPI and sets fields
func NewBrightPI(bus i2c.Bus, bpiAddr byte) *BrightPI {
return &BrightPI{bus: bus, bpiAddr: bpiAddr}
}
// Led color and position
const (
WhiteTopLeft byte = 1 << 1
WhiteBottomLeft = 1 << 3
WhiteBottomRight = 1 << 4
WhiteTopRight = 1 << 6
WhiteAll = WhiteTopLeft + WhiteBottomLeft + WhiteBottomRight + WhiteTopRight
IRBottomLeft = 1 << 0
IRTopLeft = 1 << 2
IRTopRight = 1 << 5
IRBottomRight = 1 << 7
IRAll = IRTopLeft + IRBottomLeft + IRBottomRight + IRTopRight
None = 0
)
// Max and default levels of Dim and Gain
const (
MaxDim = 0x3f
DefaultDim = 0x01
MaxGain = 0x0f
DefaultGain = 0x08
)
// Power setting for the specified LEDs (others are turned off)
func (p *BrightPI) Power(leds byte) error {
return p.bus.WriteByteToReg(p.bpiAddr, 0x00, leds)
}
// Dim individual LED(s) (value range 0-MaxDim, default DefaultDim)
func (p *BrightPI) Dim(leds, value byte) error {
var i byte
for i = 0; i < 8; i++ {
if leds&(1<<i) > 0 {
if err := p.bus.WriteByteToReg(p.bpiAddr, i+1, value); err != nil {
return err
}
}
}
return nil
}
// Gain overall LEDs brightness (value range 0-MaxGain, default DefaultGain)
func (p *BrightPI) Gain(value byte) error {
return p.bus.WriteByteToReg(p.bpiAddr, 0x09, value)
}
// Sleep puts the device into minimal power consumption mode
func (p *BrightPI) Sleep() error {
return p.Power(None)
}
|
package usecase
import (
"fmt"
"context"
"github.com/pkg/errors"
"github.com/utahta/momoclo-channel/dao"
"github.com/utahta/momoclo-channel/entity"
"github.com/utahta/momoclo-channel/event"
"github.com/utahta/momoclo-channel/event/eventtask"
"github.com/utahta/momoclo-channel/linenotify"
"github.com/utahta/momoclo-channel/log"
"github.com/utahta/momoclo-channel/timeutil"
"github.com/utahta/momoclo-channel/twitter"
"github.com/utahta/momoclo-channel/ustream"
)
type (
// CheckUstream use case
CheckUstream struct {
log log.Logger
taskQueue event.TaskQueue
checker ustream.StatusChecker
repo entity.UstreamStatusRepository
}
)
// NewCheckUstream returns CheckUstream use case
func NewCheckUstream(
logger log.Logger,
taskQueue event.TaskQueue,
checker ustream.StatusChecker,
repo entity.UstreamStatusRepository) *CheckUstream {
return &CheckUstream{
log: logger,
taskQueue: taskQueue,
checker: checker,
repo: repo,
}
}
// Do checks momocloTV live status
func (u *CheckUstream) Do(ctx context.Context) error {
const errTag = "CheckUstream.Do failed"
isLive, err := u.checker.IsLive(ctx)
if err != nil {
return errors.Wrap(err, errTag)
}
status, err := u.repo.Find(ctx, entity.UstreamStatusID)
if err != nil && err != dao.ErrNoSuchEntity {
return errors.Wrap(err, errTag)
}
if status.IsLive == isLive {
return nil // nothing to do
}
status.IsLive = isLive
if err := u.repo.Save(ctx, status); err != nil {
return errors.Wrap(err, errTag)
}
if isLive {
t := timeutil.Now()
u.taskQueue.PushMulti(ctx, []event.Task{
eventtask.NewTweet(
twitter.TweetRequest{Text: fmt.Sprintf("momocloTV が配信を開始しました\n%s\nhttp://www.ustream.tv/channel/momoclotv", t.Format("from 2006/01/02 15:04:05"))},
),
eventtask.NewLineBroadcast(linenotify.Message{Text: "\nmomocloTV が配信を開始しました\nhttp://www.ustream.tv/channel/momoclotv"}),
})
}
return nil
}
|
package api
import "log"
import "net/http"
import "github.com/peaberberian/GoBanks/auth"
var apiCalls = map[string]string{
"authentication": "auth",
"transactions": "transactions",
"banks": "banks",
"accounts": "accounts",
"categories": "categories",
"users": "users",
}
// handlerV1 is the handler for all calls concerning the API version 1
func handlerV1(w http.ResponseWriter, r *http.Request) {
var route = getApiRoute(r.URL.Path)
log.Println("Request received for API:", route)
w.Header().Set("content-type", "application/json")
var token auth.UserToken
// only route where the token shouldn't be needed
if route != apiCalls["authentication"] {
var tokenString = getTokenFromRequest(r)
var err error
token, err = auth.ParseToken(tokenString)
if err != nil {
handleError(w, err)
return
}
}
switch route {
case apiCalls["authentication"]:
handleAuthentication(w, r, &token)
case apiCalls["transactions"]:
handleTransactions(w, r, &token)
case apiCalls["banks"]:
handleBanks(w, r, &token)
case apiCalls["accounts"]:
handleAccounts(w, r, &token)
case apiCalls["categories"]:
handleCategories(w, r, &token)
default:
http.NotFound(w, r)
}
}
// routeIsInApi simply checks if the given route is in the
// apiCalls map values
func routeIsInApi(route string) bool {
for _, val := range apiCalls {
if val == route {
return true
}
}
return false
}
|
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"strings"
_ "github.com/go-sql-driver/mysql"
)
type article struct {
ID int
Title string
Content string
}
var (
articles []article
db *sql.DB
err error
)
func index(w http.ResponseWriter, r *http.Request) {
rows, err := db.Query(`SELECT * FROM articles;`)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var (
id int
title string
content string
)
err = rows.Scan(&id, &title, &content)
if err != nil {
log.Fatal(err)
}
articles = append(articles, article{id, title, content})
}
response, err := json.Marshal(articles)
if err != nil {
log.Fatal(err)
}
if response != nil {
w.Header().Set("Content-Type", "application/json")
w.Write(response)
}
}
func create(w http.ResponseWriter, r *http.Request) {
var request article
err := json.NewDecoder(r.Body).Decode(&request)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
result, err := db.Exec("INSERT INTO articles(title, content) VALUES(?, ?)", request.Title, request.Content)
if err != nil {
log.Fatal(err)
}
rows, err := result.LastInsertId()
if err != nil {
log.Fatal(err)
}
if rows != 0 {
response, err := json.Marshal(article{int(rows), request.Title, request.Content})
if err != nil {
log.Fatal(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(response)
}
}
func read(w http.ResponseWriter, r *http.Request, key int) {
rows, err := db.Query(`SELECT * FROM articles WHERE id = ?`, key)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var (
id int
title string
content string
)
for rows.Next() {
err = rows.Scan(&id, &title, &content)
if err != nil {
log.Fatal(err)
}
}
response, err := json.Marshal(article{id, title, content})
if err != nil {
log.Fatal(err)
}
if title != "" && content != "" {
w.Header().Set("Content-Type", "application/json")
w.Write(response)
} else {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
}
func update(w http.ResponseWriter, r *http.Request, key int) {
var request article
err := json.NewDecoder(r.Body).Decode(&request)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
result, err := db.Exec("UPDATE articles SET title = ?, content = ? WHERE id = ?", request.Title, request.Content, key)
if err != nil {
log.Fatal(err)
}
rows, err := result.RowsAffected()
if err != nil {
log.Fatal(err)
}
if rows != 0 {
response, err := json.Marshal(article{key, request.Title, request.Content})
if err != nil {
log.Fatal(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(response)
} else {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
}
func delete(w http.ResponseWriter, r *http.Request, key int) {
result, err := db.Exec("DELETE FROM articles WHERE id = ?", key)
if err != nil {
log.Fatal(err)
}
rows, err := result.RowsAffected()
if err != nil {
log.Fatal(err)
}
if rows != 1 {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
}
}
func main() {
db, err = sql.Open("mysql", "root:root@/go_database")
if err != nil {
log.Fatal(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected!")
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
key := 0
if len(r.URL.Path) > 1 {
key, err = strconv.Atoi(strings.Split(r.URL.Path, "/")[1])
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}
switch r.Method {
case http.MethodGet:
if key == 0 {
index(w, r)
} else {
read(w, r, key)
}
case http.MethodPost:
create(w, r)
case http.MethodPut:
update(w, r, key)
case http.MethodDelete:
delete(w, r, key)
default:
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
})
http.ListenAndServe(":8000", nil)
}
|
package api
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/mazrean/gold-rush-beta/openapi"
)
var (
exploreCalledNum int64 = 0
exploreMetricsLocker = sync.RWMutex{}
exploreRetryNum = []int{}
exploreRequestTimeLocker = sync.Mutex{}
exploreRequestTime = []int64{}
)
func Explore(ctx context.Context, area *openapi.Area) (*openapi.Report, error) {
atomic.AddInt64(&exploreCalledNum, 1)
sb := strings.Builder{}
sb.WriteString(baseURL)
sb.WriteString("/explore")
buf := bytes.Buffer{}
err := json.NewEncoder(&buf).Encode(area)
if err != nil {
return nil, fmt.Errorf("failed to encord response body: %w", err)
}
req, err := http.NewRequestWithContext(ctx, "POST", sb.String(), &buf)
if err != nil {
return nil, fmt.Errorf("failed to make request: %w", err)
}
var (
i int
report openapi.Report
)
for i = 0; ; i++ {
startTime := time.Now()
res, err := client.Do(req)
requestTime := time.Since(startTime).Milliseconds()
if err != nil {
return nil, fmt.Errorf("failed to do http request: %w", err)
}
exploreRequestTimeLocker.Lock()
exploreRequestTime = append(exploreRequestTime, requestTime)
exploreRequestTimeLocker.Unlock()
if res.StatusCode == 200 {
err = json.NewDecoder(res.Body).Decode(&report)
if err != nil {
return nil, fmt.Errorf("failed to decord response body: %w", err)
}
break
}
if res != nil && res.StatusCode == 429 {
continue
}
/*var apiErr openapi.ModelError
err = json.NewDecoder(res.Body).Decode(&apiErr)
log.Printf("explore error(%d):%+v\n", res.Status, apiErr)*/
buf = bytes.Buffer{}
err = json.NewEncoder(&buf).Encode(area)
if err != nil {
return nil, fmt.Errorf("failed to encord response body: %w", err)
}
req.Body = io.NopCloser(&buf)
}
exploreMetricsLocker.Lock()
exploreRetryNum = append(exploreRetryNum, i)
exploreMetricsLocker.Unlock()
return &report, nil
}
|
package main
import (
"encoding/base64"
"fmt"
"net/http"
)
func indexHandler(w http.ResponseWriter, r *http.Request) {
requestString := r.URL.EscapedPath()[1:]
requestURL, err := base64.StdEncoding.DecodeString(requestString)
if err == nil {
fmt.Println("Redirected to " + string(requestURL))
http.Redirect(w, r, "http://"+string(requestURL), 302)
} else {
w.Write([]byte("Invalid base64 url"))
}
}
func main() {
fmt.Println("Listen on :8085")
http.HandleFunc("/", indexHandler)
err := http.ListenAndServe(":8085", nil)
if err != nil {
panic(err.Error())
}
}
|
package model
import "github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1"
type WatchSettings struct {
Ignores []Dockerignore
}
func (ws WatchSettings) Empty() bool {
return len(ws.Ignores) == 0
}
type Dockerignore struct {
// The path to evaluate the dockerignore contents relative to
LocalPath string
// A human-readable string that identifies where the ignores come from.
Source string
// Patterns parsed out of the .dockerignore file.
Patterns []string
}
func (d Dockerignore) Empty() bool {
return len(d.Patterns) == 0
}
func DockerignoresToIgnores(source []Dockerignore) []v1alpha1.IgnoreDef {
result := make([]v1alpha1.IgnoreDef, 0, len(source))
for _, s := range source {
if s.Empty() {
continue
}
result = append(result, v1alpha1.IgnoreDef{
BasePath: s.LocalPath,
Patterns: s.Patterns,
})
}
return result
}
|
package main
import (
"context"
"fmt"
"github.com/hashicorp/consul/api"
"google.golang.org/grpc"
"net"
"socket/golearn/02-goMicro/pb"
)
type Worker struct {
}
func (worker *Worker) SayHello(ctx context.Context, p *pb.Person) (*pb.Person,error){
p.Age +=10
fmt.Println("age is :",p.Age)
return p,nil
}
func main() {
// 把grpc服务注册到consul上
// 1. 初始化consul配置
defaultConfig := api.DefaultConfig()
// 2. 创建consul对象
newClient, err2 := api.NewClient(defaultConfig)
if err2 != nil {
fmt.Println("consul NewClient err:",err2)
return
}
// 3.设置监听 制定IP 端口
serviceRegistration := api.AgentServiceRegistration{
Kind: "",
ID: "jw",
Name: "HelloService",
Tags: []string{"TestHello"},
Port: 8800,
Address: "127.0.0.1",
Check: &api.AgentServiceCheck{
TCP: "127.0.0.1:8800",
Timeout: "5s",
Interval: "5s",
},
}
// 4. 注册grpc到consul上
newClient.Agent().ServiceRegister(&serviceRegistration)
grpcserver := grpc.NewServer()
pb.RegisterHelloServer(grpcserver,new(Worker))
listen, err := net.Listen("tcp", "127.0.0.1:8800")
if err != nil {
return
}
defer listen.Close()
fmt.Println("开启服务")
grpcserver.Serve(listen)
}
|
package crud
// TODO: mark ID as comparable
import (
"context"
"github.com/adamluzsi/frameless/ports/iterators"
)
type Creator[Entity any] interface {
// Create is a function that takes a pointer to an entity and stores it in an external resource.
// And external resource could be a backing service like PostgreSQL.
// The use of a pointer type allows the function to update the entity's ID value,
// which is significant in both the external resource and the domain layer.
// The ID is essential because entities in the backing service are referenced using their IDs,
// which is why the ID value is included as part of the entity structure fieldset.
//
// The pointer is also employed for other fields managed by the external resource, such as UpdatedAt, CreatedAt,
// and any other fields present in the domain entity but controlled by the external resource.
Create(ctx context.Context, ptr *Entity) error
}
type Finder[Entity, ID any] interface {
ByIDFinder[Entity, ID]
AllFinder[Entity]
}
type ByIDFinder[Entity, ID any] interface {
// FindByID is a function that tries to find an Entity using its ID.
// It will inform you if it successfully located the entity or if there was an unexpected issue during the process.
// Instead of using an error to represent a "not found" situation,
// a return boolean value is used to provide this information explicitly.
//
//
// Why the return signature includes a found bool value?
//
// This approach serves two key purposes.
// First, it ensures that the go-vet tool checks if the 'found' boolean variable is reviewed before using the entity.
// Second, it enhances readability and demonstrates the function's cyclomatic complexity.
// total: 2^(n+1+1)
// -> found/bool 2^(n+1) | An entity might be found or not.
// -> error 2^(n+1) | An error might occur or not.
//
// Additionally, this method prevents returning an initialized pointer type with no value,
// which could lead to a runtime error if a valid but nil pointer is given to an interface variable type.
// (MyInterface)((*Entity)(nil)) != nil
//
// Similar approaches can be found in the standard library,
// such as SQL null value types and environment lookup in the os package.
FindByID(ctx context.Context, id ID) (ent Entity, found bool, err error)
}
type AllFinder[Entity any] interface {
// FindAll will return all entity that has <V> type
FindAll(context.Context) iterators.Iterator[Entity]
}
type Updater[Entity any] interface {
// Update will take a pointer to an entity and update the stored entity data by the values in received entity.
// The Entity must have a valid ID field, which referencing an existing entity in the external resource.
Update(ctx context.Context, ptr *Entity) error
}
// Deleter request to destroy a business entity in the Resource that implement it's test.
type Deleter[ID any] interface {
ByIDDeleter[ID]
AllDeleter
}
type ByIDDeleter[ID any] interface {
// DeleteByID will remove a <V> type entity from the repository by a given ID
DeleteByID(ctx context.Context, id ID) error
}
type AllDeleter interface {
// DeleteAll will erase all entity from the resource that has <V> type
DeleteAll(context.Context) error
}
// Purger supplies functionality to purge a resource completely.
// On high level this looks similar to what Deleter do,
// but in case of an event logged resource, this will purge all the events.
// After a purge, it is not expected to have anything in the repository.
// It is heavily discouraged to use Purge for domain interactions.
type Purger interface {
// Purge will completely wipe all state from the given resource.
// It is meant to be used in testing during clean-ahead arrangements.
Purge(context.Context) error
}
type Saver[Entity any] interface {
// Save combines the behaviour of Creator and Updater in a single functionality.
// If the entity is absent in the resource, the entity is created based on the Creator's behaviour.
// If the entity is present in the resource, the entity is updated based on the Updater's behaviour.
// Save requires the entity to have a valid non-empty ID value.
Save(ctx context.Context, ptr *Entity) error
}
|
package typgen_test
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/typical-go/typical-go/pkg/typgen"
)
func TestFile_SourceCode(t *testing.T) {
testCases := []struct {
TestName string
File *typgen.File
Expected string
}{
{
File: &typgen.File{
Name: "some package",
Imports: []*typgen.Import{
{Name: "", Path: "fmt"},
{Name: "a", Path: "github.com/typical-go/typical-go"},
},
},
Expected: `package some package
import (
"fmt"
a "github.com/typical-go/typical-go"
)`,
},
}
for _, tt := range testCases {
t.Run(tt.TestName, func(t *testing.T) {
require.Equal(t, tt.Expected, tt.File.Code())
})
}
}
|
package tests
import (
"fmt"
"testing"
"github.com/Emoto13/photo-viewer-rest/auth-service/src/user"
"github.com/Emoto13/photo-viewer-rest/auth-service/tests/setup"
)
func TestUserRetrieval(t *testing.T) {
db, _ := setup.OpenPostgresDatabaseConnection()
db.Exec(setup.CreateUsersTable)
db.Exec(setup.CreateTestUser)
state := user.NewState(db)
testUser, _ := user.NewUser("TestUser", "TestPassword")
var tests = []struct {
name string
input string
expected *user.User
message string
}{
{"Test RetrieveUser", "TestUser", testUser, "User state should retrieve user by username successfully"},
}
for _, test := range tests {
retrievedUser, err := state.RetrieveUser(test.input)
fmt.Println(err)
assertEquals(retrievedUser.Username, test.expected.Username, test.message)
}
db.Exec(setup.DropUsersTable)
}
|
package main
import (
"errors"
"io/ioutil"
"net/http"
"net/url"
)
func getURLFromStr(urlStr string, check bool) (*url.URL, error) {
url, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
if check {
// A valid URL is defined by one that has a host,
// not empty path (at least '/') and 'https' or 'http' for the scheme
if url.Host == "" || url.Path == "" || (url.Scheme != "https" && url.Scheme != "http") {
return nil, errors.New("Invalid URL")
}
}
// Remove fragments and query parameters as we're trying to determine uniqueness
url.Fragment = ""
url.RawQuery = ""
return url, nil
}
func getBodyBytes(url string) (*[]byte, error) {
var cl http.Client
resp, err := cl.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New("Couldn't get content. Website returned status " + resp.Status)
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return &bodyBytes, nil
}
|
package apigw
import (
"context"
"github.com/gin-gonic/gin"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/config/cmd"
"log"
"net/http"
"xj_web_server/module"
publicProto "xj_web_server/module/public/proto"
"xj_web_server/module/selector"
)
func init() {
cmd.Init()
client.DefaultClient = client.NewClient(
client.Selector(selector.FirstNodeSelector()),
)
}
// GetHostHandler : 获取服务器列表
func GetHostHandler(c *gin.Context) {
appVersion := c.Request.FormValue("app_version")
appName := c.Request.FormValue("app_name")
// Create new request to service go.micro.srv.example, method Example.Call
req := client.NewRequest("xj_web_server.service.public", "Public.GetHost", &publicProto.ReqHost{
AppName: appName,
AppVersion: appVersion,
})
resp := &publicProto.RespHost{}
// Call service
err := client.Call(context.TODO(), req, resp)
if err != nil {
log.Println(err.Error())
c.Status(http.StatusInternalServerError)
return
}
c.JSON(http.StatusOK, module.ApiResp{
ErrorNo: int64(resp.Code),
ErrorMsg: resp.Message,
Data: resp.Host,
})
}
|
package collector
import (
"strings"
"bufio"
"bytes"
"strconv"
"os/exec"
"../storage"
"regexp"
"github.com/prometheus/common/log"
"github.com/prometheus/client_golang/prometheus"
)
/*
* Prometheus specifics
*/
var sizeOfBlockDevice = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "block_device_size",
Help: "Records the size of block devices and server types.",
},
[]string{"device", "server_type", "product_name"},
)
func init() {
// Register metrics with Prometheus
prometheus.MustRegister(sizeOfBlockDevice)
}
/*
* Collector specifics
*/
var blockPairsRE = regexp.MustCompile(`([A-Z]+)=(?:"(.*?)")`)
const (
blockDeviceType = "disk"
mpathDeviceType = "mpath"
)
func CollectBlockDevices(serverType string, productName string) {
sizeOfBlockDevice.Reset()
columns := []string{
"NAME",
"SIZE",
"TYPE",
}
output, err := exec.Command(
"lsblk",
"-b",
"-P",
"-o", strings.Join(columns, ","),
).Output()
if err != nil {
log.Errorln("Cannot list block devices:", err)
}
// Need to parse output...
mpathMap := make(map[string]uint64)
diskMap := make(map[string]uint64)
s := bufio.NewScanner(bytes.NewReader(output))
for s.Scan() {
pairs := blockPairsRE.FindAllStringSubmatch(s.Text(), -1)
var dev storage.BlockDevice
var devType string
for _, pair := range pairs {
switch pair[1] {
case "NAME":
dev.DeviceName = pair[2]
case "SIZE":
size, err := strconv.ParseUint(pair[2], 10, 64)
if err != nil {
log.Errorln("Invalid size %q from lsblk:", pair[2], err)
} else {
dev.Size = size
}
case "TYPE":
devType = pair[2]
default:
log.Infoln("unexpected field from lsblk:", pair[1])
}
}
if devType == mpathDeviceType && serverType == "physical"{
mpathMap[dev.DeviceName] = dev.Size
} else if devType == blockDeviceType && serverType == "virtual" { // This excludes local disks from physical hosts
diskMap[dev.DeviceName] = dev.Size
}
}
if len(mpathMap) != 0 {
for blockDevice, size := range mpathMap {
sizeOfBlockDevice.WithLabelValues(blockDevice, serverType, productName).Add(float64(size))
}
} else if len(diskMap) != 0 {
for blockDevice, size := range diskMap {
sizeOfBlockDevice.WithLabelValues(blockDevice, serverType, productName).Add(float64(size))
}
}
}
|
package proto
//Builder protobuf消息构建器
type Builder struct {
}
//InvalidTarget 构建无效转发目标消息
func (b Builder) InvalidTarget() interface{} {
return InvalidTargetMsg{}
}
|
package file_process
import (
"io"
"os"
)
func CopyFile(toFile, fromFile string) (n int64, err error) {
fromfile, err := os.Open(fromFile)
if err != nil {
return
}
defer fromfile.Close()
tofile, err := os.Create(toFile)
if err != nil {
return
}
defer tofile.Close()
return io.Copy(tofile, fromfile)
}
|
package sprigmath
import (
"testing"
"github.com/pkg/errors"
)
func testFloat(expected float64, init interface{}, errstr string) error {
v, err := toFloat64(init)
if err = testError(errstr, err); err != nil {
return err
}
if errstr == "" && !floatEquals(v, expected) {
return errors.Errorf("Expected %v, got %v", expected, v)
}
return nil
}
func TestToFloat64(t *testing.T) {
var err error
if err = testFloat(102, int8(102), ""); err != nil {
t.Error(err)
}
if err = testFloat(102, int(102), ""); err != nil {
t.Error(err)
}
if err = testFloat(102, int32(102), ""); err != nil {
t.Error(err)
}
if err = testFloat(102, int16(102), ""); err != nil {
t.Error(err)
}
if err = testFloat(102, int64(102), ""); err != nil {
t.Error(err)
}
if err = testFloat(102, "102", ""); err != nil {
t.Error(err)
}
if err = testFloat(102, "bob", "cannot convert bob to float64"); err != nil {
t.Error(err)
}
if err = testFloat(102, uint16(102), ""); err != nil {
t.Error(err)
}
if err = testFloat(102, uint64(102), ""); err != nil {
t.Error(err)
}
if err = testFloat(102.1234, float64(102.1234), ""); err != nil {
t.Error(err)
}
if err = testFloat(0, false, ""); err != nil {
t.Error(err)
}
if err = testFloat(1, true, ""); err != nil {
t.Error(err)
}
}
func testInt64(expected int64, init interface{}, errstr string) error {
v, err := toInt64(init)
if err = testError(errstr, err); err != nil {
return err
}
if errstr == "" && v != expected {
return errors.Errorf("Expected %v, got %v", expected, v)
}
return nil
}
func TestToInt64(t *testing.T) {
var err error
if err = testInt64(102, int8(102), ""); err != nil {
t.Error(err)
}
if err = testInt64(102, int(102), ""); err != nil {
t.Error(err)
}
if err = testInt64(102, int32(102), ""); err != nil {
t.Error(err)
}
if err = testInt64(102, int16(102), ""); err != nil {
t.Error(err)
}
if err = testInt64(102, int64(102), ""); err != nil {
t.Error(err)
}
if err = testInt64(102, "102", ""); err != nil {
t.Error(err)
}
if err = testInt64(102, "bob", "cannot convert bob to int64"); err != nil {
t.Error(err)
}
if err = testInt64(102, uint16(102), ""); err != nil {
t.Error(err)
}
if err = testInt64(102, uint64(102), ""); err != nil {
t.Error(err)
}
if err = testInt64(102, float64(102.1234), ""); err != nil {
t.Error(err)
}
if err = testInt64(0, false, ""); err != nil {
t.Error(err)
}
if err = testInt64(1, true, ""); err != nil {
t.Error(err)
}
}
func testInt(expected int, init interface{}, errstr string) error {
v, err := toInt(init)
if err = testError(errstr, err); err != nil {
return err
}
if errstr == "" && v != expected {
return errors.Errorf("Expected %v, got %v", expected, v)
}
return nil
}
func TestToInt(t *testing.T) {
var err error
if err = testInt(102, int8(102), ""); err != nil {
t.Error(err)
}
if err = testInt(102, int(102), ""); err != nil {
t.Error(err)
}
if err = testInt(102, int32(102), ""); err != nil {
t.Error(err)
}
if err = testInt(102, int16(102), ""); err != nil {
t.Error(err)
}
if err = testInt(102, int64(102), ""); err != nil {
t.Error(err)
}
if err = testInt(102, "102", ""); err != nil {
t.Error(err)
}
if err = testInt(102, "bob", "cannot convert bob to int64"); err != nil {
t.Error(err)
}
if err = testInt(102, uint16(102), ""); err != nil {
t.Error(err)
}
if err = testInt(102, uint64(102), ""); err != nil {
t.Error(err)
}
if err = testInt(102, float64(102.1234), ""); err != nil {
t.Error(err)
}
if err = testInt(0, false, ""); err != nil {
t.Error(err)
}
if err = testInt(1, true, ""); err != nil {
t.Error(err)
}
}
func TestToNumber(t *testing.T) {
if v, err := toNumber(5); err == nil {
switch vv := v.(type) {
case int64:
if err = testInt64(5, vv, ""); err != nil {
t.Error(err)
}
default:
t.Errorf("Expected int64, got %T", v)
}
} else {
t.Error(err)
}
if v, err := toNumber(5.5); err == nil {
switch vv := v.(type) {
case float64:
if err = testFloat(5.5, vv, ""); err != nil {
t.Error(err)
}
default:
t.Errorf("Expected float64, got %T", v)
}
} else {
t.Error(err)
}
if v, err := toNumber("5"); err == nil {
switch vv := v.(type) {
case int64:
if err = testInt64(5, vv, ""); err != nil {
t.Error(err)
}
default:
t.Errorf("Expected int64, got %T", v)
}
} else {
t.Error(err)
}
if v, err := toNumber("5.5"); err == nil {
switch vv := v.(type) {
case float64:
if err = testFloat(5.5, vv, ""); err != nil {
t.Error(err)
}
default:
t.Errorf("Expected float64, got %T", v)
}
} else {
t.Error(err)
}
}
|
package utils
import (
"github.com/veandco/go-sdl2/sdl"
"main/types"
)
const (
WINDOW_HEIGHT = 640
WINDOW_WIDTH = 800
WINDOW_DELAY = 4000
)
func DrawCardioid(values []types.CardioidPart) {
if err := sdl.Init(sdl.INIT_EVERYTHING); err != nil {
panic(err)
}
defer sdl.Quit()
window, renderer, err := sdl.CreateWindowAndRenderer(WINDOW_WIDTH, WINDOW_HEIGHT, sdl.WINDOW_SHOWN)
if err != nil {
panic(err)
}
defer window.Destroy()
renderer.SetDrawColor( 0, 0, 0, sdl.ALPHA_OPAQUE)
renderer.Clear()
for _, value := range values {
renderer.SetDrawColor(value.Color.R, value.Color.G, value.Color.B, sdl.ALPHA_OPAQUE)
renderer.DrawPoints(value.Points)
}
renderer.Present()
sdl.Delay(WINDOW_DELAY)
}
/* TODO: For the nearest future ...
var event sdl.Event
for true {
event = sdl.PollEvent()
switch event {
case sdl.MOUSEBUTTONUP:
break
case sdl.MOUSEBUTTONDOWN:
break
}
}*/ |
package util
import (
"fmt"
"time"
"google.golang.org/protobuf/types/known/timestamppb"
)
type Timestamp timestamppb.Timestamp
func (ts *Timestamp) Scan(value interface{}) error {
if ts != nil {
return fmt.Errorf("Can't scan timestamp into nil reference")
}
var t time.Time
var protoTs *timestamppb.Timestamp
if value == nil {
return nil
}
t = value.(time.Time)
protoTs = timestamppb.New(t)
*ts = Timestamp(*protoTs)
return nil
}
|
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package auparse
import (
"strconv"
)
func parseSockaddr(s string) (map[string]string, error) {
addressFamily, err := hexToDec(s[2:4] + s[0:2]) // host-order
if err != nil {
return nil, err
}
out := map[string]string{}
switch addressFamily {
case 1: // AF_UNIX
socket, err := hexToString(s[4:])
if err != nil {
return nil, err
}
out["family"] = "unix"
out["path"] = socket
case 2: // AF_INET
port, err := hexToDec(s[4:8])
if err != nil {
return nil, err
}
ip, err := hexToIP(s[8:16])
if err != nil {
return nil, err
}
out["family"] = "ipv4"
out["addr"] = ip
out["port"] = strconv.Itoa(int(port))
case 10: // AF_INET6
port, err := hexToDec(s[4:8])
if err != nil {
return nil, err
}
flow, err := hexToDec(s[8:16])
if err != nil {
return nil, err
}
ip, err := hexToIP(s[16:48])
if err != nil {
return nil, err
}
out["family"] = "ipv6"
out["addr"] = ip
out["port"] = strconv.Itoa(int(port))
if flow > 0 {
out["flow"] = strconv.Itoa(int(flow))
}
case 16: // AF_NETLINK
out["family"] = "netlink"
out["saddr"] = s
default:
out["family"] = strconv.Itoa(int(addressFamily))
out["saddr"] = s
}
return out, nil
}
|
// 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 filepicker supports controlling the file picker on ChromeOS.
package filepicker
import (
"context"
"fmt"
"time"
"chromiumos/tast/errors"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/uiauto"
"chromiumos/tast/local/chrome/uiauto/filepicker/vars"
"chromiumos/tast/local/chrome/uiauto/filesapp"
)
// FilePicker represents an instance of the file picker.
type FilePicker struct {
filesApp *filesapp.FilesApp
}
// Find returns an existing instance of the File picker.
// An error is returned if the picker cannot be found.
func Find(ctx context.Context, tconn *chrome.TestConn) (*FilePicker, error) {
filesApp, err := filesapp.App(ctx, tconn, vars.FilePickerPseudoAppID)
if err != nil {
return nil, errors.Wrap(err, "failed to find file picker")
}
return &FilePicker{filesApp: filesApp}, nil
}
// OpenDir returns a function that opens one of the directories shown in the navigation tree.
// An error is returned if dir is not found or does not open.
func (f *FilePicker) OpenDir(dirName string) uiauto.Action {
return f.filesApp.OpenDir(dirName, dirName)
}
// OpenFile returns a function that executes double click on a file to open it.
func (f *FilePicker) OpenFile(fileName string) uiauto.Action {
// For the file picker, opening the file should close the picker.
// We retry opening the file three times to deflake some tests,
// as sometimes the double-click seems to be ignored.
return uiauto.Retry(3,
uiauto.Combine(fmt.Sprintf("OpenFile(%s)", fileName),
f.filesApp.SelectFile(fileName),
f.filesApp.OpenFile(fileName),
f.filesApp.WithTimeout(3*time.Second).WaitUntilGone(filesapp.WindowFinder(vars.FilePickerPseudoAppID)),
))
}
// SelectFile returns a function that selects a file.
func (f *FilePicker) SelectFile(fileName string) uiauto.Action {
return f.filesApp.SelectFile(fileName)
}
// WithTimeout returns a new FilePicker with the specified timeout.
// This only changes the timeout and does not relaunch the FilePicker.
func (f *FilePicker) WithTimeout(timeout time.Duration) *FilePicker {
return &FilePicker{filesApp: f.filesApp.WithTimeout(timeout)}
}
|
package main
import (
"log"
"net/http"
)
//Run 路由
func Run() {
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
http.HandleFunc("/", IndexView)
http.HandleFunc("/upload", UploadView)
http.HandleFunc("/list", ListView)
http.HandleFunc("/detail", DetailView)
http.HandleFunc("/api/upload", APIUpLoad)
http.HandleFunc("/api/list", APIList)
http.HandleFunc("/api/drop", APIDrop)
log.Println("run 8080...")
http.ListenAndServe(":8080", nil)
}
|
package v7
import (
"code.cloudfoundry.org/cli/actor/sharedaction"
"code.cloudfoundry.org/cli/actor/v7action"
"code.cloudfoundry.org/cli/command"
"code.cloudfoundry.org/cli/command/v7/shared"
"code.cloudfoundry.org/cli/util/ui"
"code.cloudfoundry.org/clock"
)
//go:generate counterfeiter . ServiceBrokersActor
type ServiceBrokersActor interface {
GetServiceBrokers() ([]v7action.ServiceBroker, v7action.Warnings, error)
}
type ServiceBrokersCommand struct {
usage interface{} `usage:"CF_NAME service-brokers"`
relatedCommands interface{} `related_commands:"delete-service-broker, disable-service-access, enable-service-access"`
SharedActor command.SharedActor
Config command.Config
UI command.UI
Actor ServiceBrokersActor
}
func (cmd *ServiceBrokersCommand) Setup(config command.Config, ui command.UI) error {
cmd.Config = config
cmd.UI = ui
cmd.SharedActor = sharedaction.NewActor(config)
ccClient, _, err := shared.GetNewClientsAndConnectToCF(config, ui, "")
if err != nil {
return err
}
cmd.Actor = v7action.NewActor(ccClient, config, nil, nil, clock.NewClock())
return nil
}
func (cmd *ServiceBrokersCommand) Execute(args []string) error {
err := cmd.SharedActor.CheckTarget(false, false)
if err != nil {
return err
}
currentUser, err := cmd.Config.CurrentUser()
if err != nil {
return err
}
cmd.UI.DisplayTextWithFlavor("Getting service brokers as {{.Username}}...", map[string]interface{}{"Username": currentUser.Name})
serviceBrokers, warnings, err := cmd.Actor.GetServiceBrokers()
cmd.UI.DisplayWarnings(warnings)
if err != nil {
return err
}
cmd.displayServiceBrokers(serviceBrokers)
return nil
}
func (cmd *ServiceBrokersCommand) displayServiceBrokers(serviceBrokers []v7action.ServiceBroker) {
if len(serviceBrokers) == 0 {
cmd.UI.DisplayText("No service brokers found")
} else {
cmd.displayServiceBrokersTable(serviceBrokers)
}
}
func (cmd *ServiceBrokersCommand) displayServiceBrokersTable(serviceBrokers []v7action.ServiceBroker) {
var table = [][]string{
{
cmd.UI.TranslateText("name"),
cmd.UI.TranslateText("url"),
cmd.UI.TranslateText("status"),
},
}
for _, serviceBroker := range serviceBrokers {
table = append(table, []string{serviceBroker.Name, serviceBroker.URL, serviceBroker.Status})
}
cmd.UI.DisplayTableWithHeader("", table, ui.DefaultTableSpacePadding)
}
|
package main
import (
"container/ring"
"fmt"
)
func main() {
const rLen = 3
// 创建新的 Ring
r := ring.New(rLen)
for i := 0; i < rLen; i++ {
r.Value = i
r = r.Next()
}
fmt.Printf("Length of ring: %d\n", r.Len()) // Length of ring: 3
// 该匿名函数用来打印 Ring 中的数据
printRing := func(v interface{}) {
fmt.Print(v, " ")
}
r.Do(printRing) // 0 1 2
fmt.Println()
// 将 r 之后的第二个元素的值乘以 2
r.Move(2).Value = r.Move(2).Value.(int) * 2
r.Do(printRing) // 0 1 4
fmt.Println()
// 删除 r 与 r+2 之间的元素,即删除 r+1
// 返回删除的元素组成的Ring的指针
result := r.Link(r.Move(2))
r.Do(printRing) // 0 4
fmt.Println()
result.Do(printRing) // 1
fmt.Println()
another := ring.New(rLen)
another.Value = 7
another.Next().Value = 8 // 给 another + 1 表示的元素赋值,即第二个元素
another.Prev().Value = 9 // 给 another - 1 表示的元素赋值,即第三个元素
another.Do(printRing) // 7 8 9
fmt.Println()
// 插入another到r后面,返回插入前r的下一个元素
result = r.Link(another)
r.Do(printRing) // 0 7 8 9 4
fmt.Println()
result.Do(printRing) // 4 0 7 8 9
fmt.Println()
// 删除r之后的三个元素,返回被删除元素组成的Ring的指针
result = r.Unlink(3)
r.Do(printRing) // 0 4
fmt.Println()
result.Do(printRing) // 7 8 9
fmt.Println()
} |
package mem_test
import (
"bytes"
"encoding/json"
"fmt"
"github.com/ionous/sashimi/_examples/stories"
"github.com/ionous/sashimi/net"
"github.com/ionous/sashimi/net/app"
"github.com/ionous/sashimi/net/ess"
"github.com/ionous/sashimi/net/mem"
"github.com/ionous/sashimi/net/resource"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// go test -run TestMemApp
func TestMemApp(t *testing.T) {
stories.Select("lab")
handler := http.NewServeMux()
handler.HandleFunc("/game/", net.HandleResource(ess.GameResource(mem.NewSessions())))
ts := httptest.NewServer(handler)
defer ts.Close()
g := &Helper{ts, "new"}
if d, err := g.post(""); assert.NoError(t, err) {
if assert.Len(t, d.Included, 0, "session starts empty") {
if d, err := g.getMany("actors", "player", "whereabouts"); assert.NoError(t, err) && assert.True(t, len(d.Included) >= 1, "the room, and contents") {
if d, err := g.post("start"); assert.NoError(t, err) {
if evts, ok := d.Data.Attributes["events"]; assert.True(t, ok, "frame has event stream") {
require.EqualValues(t, "game", d.Data.Class)
// read the events by re-transforming the stream
var blocks []app.EventBlock
b, _ := json.Marshal(evts)
require.NoError(t, json.Unmarshal(b, &blocks))
// test those events:
require.True(t, len(blocks) >= 1, "reading blocks")
require.True(t, blocks[0].Evt == "commencing", "first event should be commencing")
// check the room
if contents, err := g.getMany("rooms", "lab", "contents"); assert.NoError(t, err) {
require.Len(t, contents.Data, 3, "the lab should have two objects")
require.True(t, len(contents.Included) >= 3, "the player should (not) be previously known, the table newly known.")
}
require.NoError(t, checkTable(g, 1))
if _, err := g.post("open the glass jar"); assert.NoError(t, err) {
require.NoError(t, checkTable(g, 1))
}
// take the beaker
if _, err := g.post("take the glass jar"); assert.NoError(t, err) {
require.NoError(t, checkTable(g, 0))
}
cmd := app.CommandInput{
Action: "show-it-to",
Target: "lab-assistant",
Context: "axe"}
if _, err := g.postCmd(cmd); assert.NoError(t, err) {
}
if cls, err := g.getOne("class", "droppers"); assert.NoError(t, err) {
if parents, ok := cls.Data.Meta["classes"]; assert.True(t, ok, "has classes") {
if parents, ok := parents.([]interface{}); assert.True(t, ok, "classes is list") {
assert.EqualValues(t, []interface{}{"droppers", "props", "objects", "kinds"}, parents)
}
}
}
}
}
}
}
}
}
func checkTable(g *Helper, cnt int) (err error) {
if contents, e := g.getMany("supporters", "table", "contents"); e != nil {
err = e
} else if len(contents.Data) != cnt {
err = fmt.Errorf("the table should have %d objects. has %s", cnt, pretty(contents))
}
return err
}
type Helper struct {
ts *httptest.Server
id string
}
func (h *Helper) getOne(parts ...string) (doc resource.ObjectDocument, err error) {
//"rooms", "lab", "contents"
url := h.makeUrl(parts...)
if resp, e := http.Get(url); e != nil {
err = e
} else {
err = decodeBody(resp, &doc)
}
return
}
func (h *Helper) getMany(parts ...string) (doc resource.MultiDocument, err error) {
//"rooms", "lab", "contents"
url := h.makeUrl(parts...)
if resp, e := http.Get(url); e != nil {
err = e
} else {
err = decodeBody(resp, &doc)
}
return
}
func (h *Helper) post(input string) (doc resource.ObjectDocument, err error) {
in := app.CommandInput{Input: input}
return h.postCmd(in)
}
func (h *Helper) postCmd(in app.CommandInput) (doc resource.ObjectDocument, err error) {
if b, e := json.Marshal(in); e != nil {
err = e
} else {
postUrl := h.makeUrl()
if resp, e := http.Post(postUrl, "application/json", bytes.NewReader(b)); e != nil {
err = e
} else if e := decodeBody(resp, &doc); e != nil {
err = e
} else {
h.id = doc.Data.Id
}
}
return doc, err
}
func (h *Helper) makeUrl(parts ...string) string {
parts = append([]string{h.ts.URL, "game", h.id}, parts...)
return strings.Join(parts, "/")
}
func decodeBody(resp *http.Response, d interface{}) (err error) {
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
err = json.NewDecoder(resp.Body).Decode(d)
} else {
body, e := ioutil.ReadAll(resp.Body)
if e != nil {
body = []byte(e.Error())
}
err = fmt.Errorf("%s %s %s", resp.Status, resp.Request.URL, body)
}
return err
}
func pretty(d interface{}) string {
text, _ := json.MarshalIndent(d, "", " ")
return string(text)
}
|
package main
import (
"fmt"
"os"
)
// Global declarations
func assert(t bool, msg string){
if (!t){
fmt.Fprintf(os.Stderr, msg)
os.Exit(1)
}
}
// Node basic data structure
type Node struct {
Data int
Left *Node
Right *Node
}
// NewNode create a new node reference
func NewNode(data int) *Node {
return &Node{
Data: data,
Left: nil,
Right: nil,
}
}
// Insert add data into a BST
func (n *Node) Insert(data int) *Node {
if (n == nil) {
return NewNode(data)
}
if (data <= n.Data) {
n.Left = n.Left.Insert(data)
} else {
n.Right = n.Right.Insert(data)
}
return n
}
// Problems
/* 1. build123()
2
/ \
1 3
*/
func build123() *Node {
var root *Node
root = root.Insert(2)
root = root.Insert(1)
root = root.Insert(3)
return root
}
// 2. size()
func (n *Node) size() int {
if (n == nil) {
return 0
}
return n.Left.size() + 1 + n.Right.size()
}
// 3. maxDepth()
func max(a int, b int) int {
if (a>b) {
return a
}
return b
}
func (n *Node) maxDepth() int {
if (n == nil){
return 0
}
var lDepth, rDepth int
lDepth = n.Left.maxDepth()
rDepth = n.Right.maxDepth()
return max(lDepth, rDepth) + 1
}
// 4. minValue()
func (n *Node) minValue() *int {
if (n == nil){
return nil
}
if (n.Left != nil){
return n.Left.minValue()
}
return &n.Data
}
/* 5. printTree()
The tree...
4
/ \
2 5
/ \
1 3
Produces the output "1 2 3 4 5"
*/
func (n *Node) printTree() {
if (n == nil){ return }
n.Left.printTree()
fmt.Printf("%d ", n.Data)
n.Right.printTree()
}
/* 6. printPostorder()
The tree...
4
/ \
2 5
/ \
1 3
Produces the output "1 3 2 5 4"
*/
func (n *Node) printPostOrder() {
if (n == nil){ return }
n.Left.printPostOrder()
n.Right.printPostOrder()
fmt.Printf("%d ", n.Data)
}
// 7. hasPathSum()
func (n *Node) hasPathSum(sum int) bool {
if (n == nil){ return sum == 0 }
return n.Left.hasPathSum(sum - n.Data) || n.Right.hasPathSum(sum - n.Data)
}
// 8. printPaths()
func printPathsRecur(n *Node, path []int, pathLen int) {
if (n == nil) { return }
newPath := make([]int, pathLen+1)
copy(newPath, path)
newPath[pathLen] = n.Data
pathLen += 1
if (n.Left == nil && n.Right == nil){
fmt.Printf("%v\n", newPath)
}
printPathsRecur(n.Left, newPath, pathLen)
printPathsRecur(n.Right, newPath, pathLen)
}
func (n *Node) printPaths() {
path := []int{}
printPathsRecur(n, path, 0)
}
/* 9. mirror()
The tree...
4
/ \
2 5
/ \
1 3
is changed to
4
/ \
5 2
/ \
3 1
*/
func (n *Node) mirror() {
if (n == nil) { return }
n.Left.mirror()
n.Right.mirror()
lChild := n.Left
n.Left = n.Right
n.Right = lChild
}
func treeArray(n *Node) []int{
if (n == nil) { return []int{} }
return append(
append(treeArray(n.Left), n.Data),
treeArray(n.Right)...
)
}
/* 10. doubleTree()
The tree...
2
/ \
1 3
is changed to
2
/ \
2 3
/ /
1 3
/
1
*/
func (n *Node) doubleTree() {
if (n == nil) { return }
n.Left.doubleTree()
n.Right.doubleTree()
m := NewNode(n.Data)
m.Left = n.Left
n.Left = m
}
// 11. sameTree()
func sameTree(n *Node, m *Node) bool {
if (n == nil && m == nil) { return true }
if (n != nil && m != nil) {
return n.Data == m.Data &&
sameTree(n.Left, m.Left) &&
sameTree(n.Right, m.Right)
}
return false
}
// 12. countTrees()
func countTrees(numKeys int) int {
if (numKeys <= 1) { return 1 }
sum := 0
for i:= 1; i <= numKeys; i++ {
left := countTrees(i - 1)
right := countTrees(numKeys - i)
sum += left * right
}
return sum
}
// 13. isBST()
func (n *Node) maxValue() *int {
if (n == nil){
return nil
}
if (n.Right != nil){
return n.Right.maxValue()
}
return &n.Data
}
func isBST(n *Node) bool {
if (n == nil) { return true }
min := n.minValue()
max := n.maxValue()
if (min == nil || max == nil) {
return false
}
if (n.Left != nil && *min > n.Data) { return false }
if (n.Right != nil && *max <= n.Data) { return false }
if (!isBST(n.Left) || !isBST(n.Right)) { return false }
return true
}
// 14. isBST2()
func isBSTRec(n *Node, min int, max int) bool {
if (n == nil) { return true }
if (n.Data < min || n.Data > max) { return false }
return isBSTRec(n.Left, min, n.Data) && isBSTRec(n.Right, n.Data+1, max)
}
func isBST2(n *Node) bool {
// https://stackoverflow.com/a/6878625
maxInt := int(^uint(0) >> 1)
minInt := -maxInt - 1
return isBSTRec(n, minInt, maxInt)
}
func main(){
var n *Node
m := build123()
// testSize
assert(n.size() == 0, "Empty node has size 0\n")
assert(m.size() == 3, "build123 node has size 3\n")
// testMaxDepth
assert(n.maxDepth() == 0, "Empty node has maxDepth 0\n")
assert(m.maxDepth() == 2, "build123 node has maxDepth 2\n")
// testMinValue
assert(n.minValue() == nil, "Empty node has minValue nil\n")
assert(*m.minValue() == 1, "build123 node has minValue 1\n")
// testPrintTree
t := &Node{
Data: 4,
Left: m,
Right: NewNode(5),
}
fmt.Println("Test printTree:")
n.printTree()
fmt.Println()
m.printTree()
fmt.Println()
t.printTree()
fmt.Println()
// testPrintPostOrder
fmt.Println("Test printPostOrder:")
n.printPostOrder()
fmt.Println()
m.printPostOrder()
fmt.Println()
t.printPostOrder()
fmt.Println()
// testHasPathSum
assert(n.hasPathSum(0), "Empty node hasPathSum 0\n")
assert(!n.hasPathSum(1), "Empty node not hasPathSum 1\n")
assert(m.hasPathSum(3), "build123 node hasPathSum 3\n")
assert(m.hasPathSum(5), "build123 node hasPathSum 5\n")
assert(!m.hasPathSum(4), "build123 node not hasPathSum 4\n")
// testPrintPaths
fmt.Println("Test printPaths:")
n.printPaths()
m.printPaths()
t.printPaths()
// testMirror
a := build123()
b := build123()
b.mirror()
assert(fmt.Sprintf("%v ", treeArray(a)) == "[1 2 3] ", "a node has the given elems\n")
assert(fmt.Sprintf("%v ", treeArray(b)) == "[3 2 1] ", "b node has the given elems\n")
// testDoubleTree
d := build123()
assert(fmt.Sprintf("%v ", treeArray(d)) == "[1 2 3] ", "d node has the given elems\n")
d.doubleTree()
assert(fmt.Sprintf("%v ", treeArray(d)) == "[1 1 2 2 3 3] ", "d node has the given elems after duplication\n")
// testSameTree
assert(sameTree(a, a), "a and m are the same tree\n")
assert(sameTree(nil, nil), "nil and nil are the same tree\n")
assert(!sameTree(nil, a), "nil and a are not the same tree\n")
assert(!sameTree(a, d), "a and d are not the same tree\n")
// testCountTrees
assert(countTrees(0) == 1, "1 tree our of 0 numKeys\n")
assert(countTrees(1) == 1, "1 tree our of 1 numKeys\n")
assert(countTrees(2) == 2, "2 trees our of 2 numKeys\n")
assert(countTrees(3) == 5, "5 trees our of 3 numKeys\n")
assert(countTrees(4) == 14, "4 trees our of 14 numKeys\n")
// testIsBST
x := build123()
y := build123()
y.Left = NewNode(999)
assert(isBST(nil), "nil isBST\n")
assert(isBST2(nil), "nil isBST2\n")
assert(isBST(x), "x isBST\n")
assert(isBST2(x), "x isBST2\n")
assert(!isBST(y), "y !isBST\n")
assert(!isBST2(y), "y !isBST2\n")
} |
// 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/sql/opt"
"github.com/cockroachdb/cockroach/pkg/sql/opt/cat"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
)
// analyzeOrderBy analyzes an Ordering physical property from the ORDER BY
// clause and adds the resulting typed expressions to orderByScope.
func (b *Builder) analyzeOrderBy(
orderBy tree.OrderBy, inScope, projectionsScope *scope, rejectFlags tree.SemaRejectFlags,
) (orderByScope *scope) {
if orderBy == nil {
return nil
}
orderByScope = inScope.push()
orderByScope.cols = make([]scopeColumn, 0, len(orderBy))
// We need to save and restore the previous value of the field in
// semaCtx in case we are recursively called within a subquery
// context.
defer b.semaCtx.Properties.Restore(b.semaCtx.Properties)
b.semaCtx.Properties.Require(exprKindOrderBy.String(), rejectFlags)
inScope.context = exprKindOrderBy
for i := range orderBy {
b.analyzeOrderByArg(orderBy[i], inScope, projectionsScope, orderByScope)
}
return orderByScope
}
// buildOrderBy builds an Ordering physical property from the ORDER BY clause.
// ORDER BY is not a relational expression, but instead a required physical
// property on the output.
//
// Since the ordering property can only refer to output columns, we may need
// to add a projection for the ordering columns. For example, consider the
// following query:
// SELECT a FROM t ORDER BY c
// The `c` column must be retained in the projection (and the presentation
// property then omits it).
//
// buildOrderBy builds a set of memo groups for any ORDER BY columns that are
// not already present in the SELECT list (as represented by the initial set
// of columns in projectionsScope). buildOrderBy adds these new ORDER BY
// columns to the projectionsScope and sets the ordering property on the
// projectionsScope. This property later becomes part of the required physical
// properties returned by Build.
func (b *Builder) buildOrderBy(inScope, projectionsScope, orderByScope *scope) {
if orderByScope == nil {
return
}
orderByScope.ordering = make([]opt.OrderingColumn, 0, len(orderByScope.cols))
for i := range orderByScope.cols {
b.buildOrderByArg(inScope, projectionsScope, orderByScope, &orderByScope.cols[i])
}
projectionsScope.setOrdering(orderByScope.cols, orderByScope.ordering)
}
// findIndexByName returns an index in the table with the given name. If the
// name is empty the primary index is returned.
func (b *Builder) findIndexByName(table cat.Table, name tree.UnrestrictedName) (cat.Index, error) {
if name == "" {
return table.Index(0), nil
}
for i, n := 0, table.IndexCount(); i < n; i++ {
idx := table.Index(i)
if tree.Name(name) == idx.Name() {
return idx, nil
}
}
return nil, pgerror.Newf(pgcode.UndefinedObject,
`index %q not found`, name)
}
// addOrderByOrDistinctOnColumn builds extraCol.expr as a column in extraColsScope; if it is
// already projected in projectionsScope then that projection is re-used.
func (b *Builder) addOrderByOrDistinctOnColumn(
inScope, projectionsScope, extraColsScope *scope, extraCol *scopeColumn,
) {
// Use an existing projection if possible (even if it has side-effects; see
// the SQL99 rules described in analyzeExtraArgument). Otherwise, build a new
// projection.
if col := projectionsScope.findExistingCol(
extraCol.getExpr(),
true, /* allowSideEffects */
); col != nil {
extraCol.id = col.id
} else {
b.buildScalar(extraCol.getExpr(), inScope, extraColsScope, extraCol, nil)
}
}
// analyzeOrderByIndex appends to the orderByScope a column for each indexed
// column in the specified index, including the implicit primary key columns.
func (b *Builder) analyzeOrderByIndex(
order *tree.Order, inScope, projectionsScope, orderByScope *scope,
) {
tab, tn := b.resolveTable(&order.Table, privilege.SELECT)
index, err := b.findIndexByName(tab, order.Index)
if err != nil {
panic(err)
}
// We fully qualify the table name in case another table expression was
// aliased to the same name as an existing table.
tn.ExplicitCatalog = true
tn.ExplicitSchema = true
// Append each key column from the index (including the implicit primary key
// columns) to the ordering scope.
for i, n := 0, index.KeyColumnCount(); i < n; i++ {
// Columns which are indexable are always orderable.
col := index.Column(i)
desc := col.Descending
// DESC inverts the order of the index.
if order.Direction == tree.Descending {
desc = !desc
}
colItem := tree.NewColumnItem(&tn, col.ColName())
expr := inScope.resolveType(colItem, types.Any)
outCol := orderByScope.addColumn("" /* alias */, expr)
outCol.descending = desc
}
}
// analyzeOrderByArg analyzes a single ORDER BY argument. Typically this is a
// single column, with the exception of qualified star "table.*". The resulting
// typed expression(s) are added to orderByScope.
func (b *Builder) analyzeOrderByArg(
order *tree.Order, inScope, projectionsScope, orderByScope *scope,
) {
if order.OrderType == tree.OrderByIndex {
b.analyzeOrderByIndex(order, inScope, projectionsScope, orderByScope)
return
}
// Analyze the ORDER BY column(s).
start := len(orderByScope.cols)
b.analyzeExtraArgument(order.Expr, inScope, projectionsScope, orderByScope)
for i := start; i < len(orderByScope.cols); i++ {
col := &orderByScope.cols[i]
col.descending = order.Direction == tree.Descending
}
}
// buildOrderByArg sets up the projection of a single ORDER BY argument.
// The projection column is built in the orderByScope and used to build
// an ordering on the same scope.
func (b *Builder) buildOrderByArg(
inScope, projectionsScope, orderByScope *scope, orderByCol *scopeColumn,
) {
// Build the ORDER BY column.
b.addOrderByOrDistinctOnColumn(inScope, projectionsScope, orderByScope, orderByCol)
// Add the new column to the ordering.
orderByScope.ordering = append(orderByScope.ordering,
opt.MakeOrderingColumn(orderByCol.id, orderByCol.descending),
)
}
// analyzeExtraArgument analyzes a single ORDER BY or DISTINCT ON argument.
// Typically this is a single column, with the exception of qualified star
// (table.*). The resulting typed expression(s) are added to extraColsScope.
func (b *Builder) analyzeExtraArgument(
expr tree.Expr, inScope, projectionsScope, extraColsScope *scope,
) {
// Unwrap parenthesized expressions like "((a))" to "a".
expr = tree.StripParens(expr)
// The logical data source for ORDER BY or DISTINCT ON is the list of column
// expressions for a SELECT, as specified in the input SQL text (or an entire
// UNION or VALUES clause). Alas, SQL has some historical baggage from SQL92
// and there are some special cases:
//
// SQL92 rules:
//
// 1) if the expression is the aliased (AS) name of an
// expression in a SELECT clause, then use that
// expression as sort key.
// e.g. SELECT a AS b, b AS c ORDER BY b
// this sorts on the first column.
//
// 2) column ordinals. If a simple integer literal is used,
// optionally enclosed within parentheses but *not subject to
// any arithmetic*, then this refers to one of the columns of
// the data source. Then use the SELECT expression at that
// ordinal position as sort key.
//
// SQL99 rules:
//
// 3) otherwise, if the expression is already in the SELECT list,
// then use that expression as sort key.
// e.g. SELECT b AS c ORDER BY b
// this sorts on the first column.
// (this is an optimization)
//
// 4) if the sort key is not dependent on the data source (no
// IndexedVar) then simply do not sort. (this is an optimization)
//
// 5) otherwise, add a new projection with the ORDER BY expression
// and use that as sort key.
// e.g. SELECT a FROM t ORDER by b
// e.g. SELECT a, b FROM t ORDER by a+b
// First, deal with projection aliases.
idx := colIdxByProjectionAlias(expr, inScope.context.String(), projectionsScope)
// If the expression does not refer to an alias, deal with
// column ordinals.
if idx == -1 {
idx = colIndex(len(projectionsScope.cols), expr, inScope.context.String())
}
var exprs tree.TypedExprs
if idx != -1 {
exprs = []tree.TypedExpr{projectionsScope.cols[idx].getExpr()}
} else {
exprs = b.expandStarAndResolveType(expr, inScope)
// ORDER BY (a, b) -> ORDER BY a, b
exprs = flattenTuples(exprs)
}
for _, e := range exprs {
// Ensure we can order on the given column(s).
ensureColumnOrderable(e)
extraColsScope.addColumn("" /* alias */, e)
}
}
func ensureColumnOrderable(e tree.TypedExpr) {
typ := e.ResolvedType()
if typ.Family() == types.JsonFamily ||
(typ.Family() == types.ArrayFamily && typ.ArrayContents().Family() == types.JsonFamily) {
panic(unimplementedWithIssueDetailf(35706, "", "can't order by column type jsonb"))
}
}
|
// 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 sql
import (
"context"
"testing"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/util/cancelchecker"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/errors"
"github.com/stretchr/testify/require"
)
func TestVirtualTableGenerators(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
stopper := stop.NewStopper()
ctx := context.Background()
defer stopper.Stop(ctx)
t.Run("test cleanup", func(t *testing.T) {
worker := func(pusher rowPusher) error {
if err := pusher.pushRow(tree.NewDInt(1)); err != nil {
return err
}
if err := pusher.pushRow(tree.NewDInt(2)); err != nil {
return err
}
return nil
}
next, cleanup, setupError := setupGenerator(ctx, worker, stopper)
require.NoError(t, setupError)
d, err := next()
if err != nil {
t.Fatal(err)
}
require.Equal(t, tree.Datums{tree.NewDInt(1)}, d)
// Check that we can safely cleanup in the middle of execution.
cleanup()
})
t.Run("test worker error", func(t *testing.T) {
// Test that if the worker returns an error we catch it.
worker := func(pusher rowPusher) error {
if err := pusher.pushRow(tree.NewDInt(1)); err != nil {
return err
}
if err := pusher.pushRow(tree.NewDInt(2)); err != nil {
return err
}
return errors.New("dummy error")
}
next, cleanup, setupError := setupGenerator(ctx, worker, stopper)
require.NoError(t, setupError)
_, err := next()
require.NoError(t, err)
_, err = next()
require.NoError(t, err)
_, err = next()
require.Error(t, err)
cleanup()
})
t.Run("test no next", func(t *testing.T) {
// Test we don't leak anything if we call cleanup before next.
worker := func(pusher rowPusher) error {
return nil
}
_, cleanup, setupError := setupGenerator(ctx, worker, stopper)
require.NoError(t, setupError)
cleanup()
})
t.Run("test context cancellation", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
// Test cancellation before asking for any rows.
worker := func(pusher rowPusher) error {
if err := pusher.pushRow(tree.NewDInt(1)); err != nil {
return err
}
if err := pusher.pushRow(tree.NewDInt(2)); err != nil {
return err
}
return nil
}
next, cleanup, setupError := setupGenerator(ctx, worker, stopper)
require.NoError(t, setupError)
cancel()
_, err := next()
// There is a small chance that we race and don't return
// a query canceled here. So, only check the error if
// it is non-nil.
if err != nil {
require.Equal(t, cancelchecker.QueryCanceledError, err)
}
cleanup()
// Test cancellation after asking for a row.
ctx, cancel = context.WithCancel(context.Background())
next, cleanup, setupError = setupGenerator(ctx, worker, stopper)
require.NoError(t, setupError)
row, err := next()
require.NoError(t, err)
require.Equal(t, tree.Datums{tree.NewDInt(1)}, row)
cancel()
_, err = next()
require.Equal(t, cancelchecker.QueryCanceledError, err)
cleanup()
// Test cancellation after asking for all the rows.
ctx, cancel = context.WithCancel(context.Background())
next, cleanup, setupError = setupGenerator(ctx, worker, stopper)
require.NoError(t, setupError)
_, err = next()
require.NoError(t, err)
_, err = next()
require.NoError(t, err)
cancel()
cleanup()
})
}
func BenchmarkVirtualTableGenerators(b *testing.B) {
defer leaktest.AfterTest(b)()
defer log.Scope(b).Close(b)
stopper := stop.NewStopper()
ctx := context.Background()
defer stopper.Stop(ctx)
worker := func(pusher rowPusher) error {
for {
if err := pusher.pushRow(tree.NewDInt(tree.DInt(1))); err != nil {
return err
}
}
}
b.Run("bench read", func(b *testing.B) {
next, cleanup, setupError := setupGenerator(ctx, worker, stopper)
require.NoError(b, setupError)
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := next()
require.NoError(b, err)
}
cleanup()
})
}
|
package runner
import (
"bytes"
"fmt"
"regexp"
"strings"
"time"
warp "github.com/PierreZ/Warp10Exporter"
jira "github.com/andygrunwald/go-jira"
log "github.com/sirupsen/logrus"
"github.com/ovh/jerem/src/core"
)
const storyPointField = "customfield_10006"
var quarterRegex = regexp.MustCompile(`^Q[1-4]-\d{2}$`)
var projectPrefix = "Project_"
// EpicRunner runner handling epic metrics
func EpicRunner(config core.Config) {
tp := jira.BasicAuthTransport{
Username: config.Jira.Username,
Password: config.Jira.Password,
}
jiraClient, err := jira.NewClient(tp.Client(), config.Jira.URL)
if err != nil {
log.WithError(err).Error("Fail to get jira client")
return
}
batch := warp.NewBatch()
// Get epics per project
for _, project := range config.Projects {
epics, err := getEpics(jiraClient, project)
if err != nil {
log.WithError(err).Error("Fail to get jira epics")
continue
}
// Count storypoints per epic
for _, epic := range epics {
status := getStatus(epic) // [undefined, new, indeterminate, done]
if status == jira.StatusCategoryComplete {
continue
}
// Get global project related to current epic
global := "None"
for _, label := range epic.Fields.Labels {
if strings.HasPrefix(label, projectPrefix) {
global = strings.TrimLeft(label, projectPrefix)
}
}
// Search for quarter label
for _, label := range epic.Fields.Labels {
if quarterRegex.MatchString(label) {
processEpic(jiraClient, epic, label, project.Label, global, batch)
}
}
}
}
var b bytes.Buffer
batch.Print(&b)
log.Debug(b.String())
if len(*batch) != 0 {
err = batch.Push(config.Metrics.URL, config.Metrics.Token)
if err != nil {
log.WithError(err).Error("Fail to push metrics")
}
}
}
func getEpics(jiraClient *jira.Client, project core.Project) ([]jira.Issue, error) {
query := getEpicQuery(project)
var epics []jira.Issue
err := jiraClient.Issue.SearchPages(query, &jira.SearchOptions{
Fields: []string{"id", "key", "project", "labels", "summary", "status"},
}, func(issue jira.Issue) error {
epics = append(epics, issue)
return nil
})
if err != nil {
return nil, err
}
return epics, nil
}
func getEpicQuery(project core.Project) string {
return fmt.Sprintf("(project = \"%s\" %s) AND issuetype = Epic", project.Name, project.Jql)
}
func processEpic(jiraClient *jira.Client, epic jira.Issue, quarter, projectLabel, global string, batch *warp.Batch) {
issues, err := getIssues(jiraClient, epic.Key)
if err != nil {
log.WithField("key", epic.Key).WithError(err).Warn("Fail to get jira issues")
return
}
storyPoints, unestimated, dependency := computeStoryPoints(issues, storyPointField)
// Gen metrics
now := time.Now().UTC()
gts := getEpicMetric("storypoint", epic, quarter, projectLabel, global).AddDatapoint(now, storyPoints["total"])
batch.Register(gts)
gts = getEpicMetric("unestimated", epic, quarter, projectLabel, global).AddDatapoint(now, float64(unestimated))
batch.Register(gts)
gts = getEpicMetric("dependency", epic, quarter, projectLabel, global).AddDatapoint(now, float64(dependency))
batch.Register(gts)
gts = getEpicMetric("storypoint.inprogress", epic, quarter, projectLabel, global).AddDatapoint(now, storyPoints["indeterminate"])
batch.Register(gts)
gts = getEpicMetric("storypoint.done", epic, quarter, projectLabel, global).AddDatapoint(now, storyPoints["done"])
batch.Register(gts)
}
func getIssues(jiraClient *jira.Client, epic string) ([]jira.Issue, error) {
var issues []jira.Issue
err := jiraClient.Issue.SearchPages(fmt.Sprintf("\"Epic Link\" = %s", epic), &jira.SearchOptions{
Fields: []string{"id", "key", "labels", "summary", "status", storyPointField},
}, func(issue jira.Issue) error {
issues = append(issues, issue)
return nil
})
if err != nil {
return nil, err
}
return issues, nil
}
func getStatus(issue jira.Issue) string {
// /api/2/statuscategory => [undefined, new, indeterminate, done]
if issue.Fields.Status == nil {
log.WithField("key", issue.Key).Warn("No status")
return "undefined"
}
return issue.Fields.Status.StatusCategory.Key
}
func getEpicMetric(name string, epic jira.Issue, quarter, projectLabel, global string) *warp.GTS {
return warp.NewGTS(fmt.Sprintf("jerem.jira.epic.%s", name)).WithLabels(warp.Labels{
"project": projectLabel,
"key": epic.Key,
"summary": epic.Fields.Summary,
"quarter": quarter,
"global": global,
})
}
|
package main
import (
"fmt"
"sync"
"time"
)
func hello(i int, wg *sync.WaitGroup) {
fmt.Printf("Goroutine #%d started\n", i)
time.Sleep(2 * time.Second)
fmt.Printf("Goroutine #%d finished\n", i)
wg.Done()
}
func main() {
fmt.Println()
no := 500
var wg sync.WaitGroup
for i := 0; i < no; i++ {
time.Sleep(100 * time.Millisecond)
wg.Add(1)
go hello(i, &wg)
}
wg.Wait()
fmt.Println("main finished")
}
|
package store
import (
"github.com/mylxsw/glacier/infra"
)
type Provider struct{}
func (s Provider) Register(app infra.Binder) {
app.MustSingleton(NewEventStore)
}
func (s Provider) Boot(app infra.Resolver) {}
|
package client
import (
"path/filepath"
"strings"
)
// PathKind describes the type of a path
type PathKind int
// types of paths
const (
BACKEND PathKind = iota
NODE
LEAF
NONE
)
func (client *Client) topLevelType(path string) PathKind {
if path == "" {
return BACKEND
} else if _, ok := client.KVBackends[path+"/"]; ok {
return BACKEND
} else {
return NONE
}
}
var cachedPath = ""
var cachedDirFiles = make(map[string]int)
func (client *Client) isAmbiguous(path string) (result bool) {
// get current directory content
if cachedPath != path {
pathTrim := strings.TrimSuffix(path, "/")
cachedDirFiles = make(map[string]int)
s, err := client.Vault.Logical().List(client.getKVMetaDataPath(filepath.Dir(pathTrim)))
if err == nil && s != nil {
if keysInterface, ok := s.Data["keys"]; ok {
for _, valInterface := range keysInterface.([]interface{}) {
val := valInterface.(string)
cachedDirFiles[val] = 1
}
}
}
cachedPath = path
}
// check if path exists as file and directory
result = false
if _, ok := cachedDirFiles[filepath.Base(path)]; ok {
if _, ok := cachedDirFiles[filepath.Base(path)+"/"]; ok {
result = true
}
}
return result
}
func (client *Client) lowLevelType(path string) (result PathKind) {
if client.isAmbiguous(path) {
if strings.HasSuffix(path, "/") {
result = NODE
} else {
result = LEAF
}
} else {
hasNode := false
s, err := client.Vault.Logical().List(client.getKVMetaDataPath(path + "/"))
if err == nil && s != nil {
if _, ok := s.Data["keys"]; ok {
hasNode = true
}
}
if hasNode {
result = NODE
} else {
if _, ok := cachedDirFiles[filepath.Base(path)]; ok {
result = LEAF
} else {
result = NONE
}
}
}
return result
}
|
package codegen
import (
"bytes"
"strings"
"text/template"
)
func JoinWithSpace(a ...string) string {
return strings.Join(a, " ")
}
func JoinWithColon(a ...string) string {
return strings.Join(a, ":")
}
func JoinWithSlash(a ...string) string {
return strings.Join(a, "/")
}
func JoinWithLineBreak(a ...string) string {
return strings.Join(a, "\n")
}
func JoinWithComma(a ...string) string {
return strings.Join(a, ",")
}
func WithQuotes(s string) string {
return "\"" + s + "\""
}
func WithTagQuotes(s string) string {
return "`" + s + "`"
}
func WithRoundBrackets(s string) string {
return "(" + s + ")"
}
func WithSquareBrackets(s string) string {
return "[" + s + "]"
}
func WithCurlyBrackets(s string) string {
return "{" + s + "}"
}
func MapStrings(mapper func(s string) string, strs []string) []string {
newStrings := []string{}
for _, str := range strs {
newStrings = append(newStrings, mapper(str))
}
return newStrings
}
func UniqueStrings(strs []string) []string {
stringMap := map[string]bool{}
for _, str := range strs {
stringMap[str] = true
}
newStrings := []string{}
for str := range stringMap {
newStrings = append(newStrings, str)
}
return newStrings
}
func TemplateRender(s string) func(data interface{}) string {
tmpl, err := template.New(s).Parse(s)
if err != nil {
panic(err)
}
return func(data interface{}) string {
var value bytes.Buffer
err = tmpl.Execute(&value, data)
return value.String()
}
}
|
package clicolorer
//go:generate counterfeiter -o ./fake.go --fake-name Fake ./ CliColorer
import (
"github.com/fatih/color"
)
type CliColorer interface {
// silently disables coloring
Disable()
// attention colors
Attention(
format string,
values ...interface{},
) string
// errors collors
Error(
format string,
values ...interface{},
) string
// info colors
Info(
format string,
values ...interface{},
) string
// success colors
Success(
format string,
values ...interface{},
) string
}
func New() CliColorer {
color.NoColor = false
return &cliColorer{
attentionCliColorer: color.New(color.FgHiYellow, color.Bold).SprintfFunc(),
errorCliColorer: color.New(color.FgHiRed, color.Bold).SprintfFunc(),
infoCliColorer: color.New(color.FgHiCyan, color.Bold).SprintfFunc(),
successCliColorer: color.New(color.FgHiGreen, color.Bold).SprintfFunc(),
}
}
type cliColorer struct {
attentionCliColorer func(format string, a ...interface{}) string
errorCliColorer func(format string, a ...interface{}) string
infoCliColorer func(format string, a ...interface{}) string
successCliColorer func(format string, a ...interface{}) string
}
func (this cliColorer) Disable() {
color.NoColor = true
}
func (this cliColorer) Attention(
format string,
values ...interface{},
) string {
return this.attentionCliColorer(format, values...)
}
func (this cliColorer) Error(
format string,
values ...interface{},
) string {
return this.errorCliColorer(format, values...)
}
func (this cliColorer) Info(
format string,
values ...interface{},
) string {
return this.infoCliColorer(format, values...)
}
func (this cliColorer) Success(
format string,
values ...interface{},
) string {
return this.successCliColorer(format, values...)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.