text
stringlengths
11
4.05M
package main import ( "flag" "fmt" "strings" ) // This is a struct declaration type message struct { text *string } // Add a method to your new struct - func (m *message) UpperCaseIt() string { return strings.ToUpper(*m.text) } func main() { // Create your new variable var msg message // Set the commandline value to the property of our struct msg.text = flag.String("message", "gopher", "Say hi to!") // Call the method that parses the items at the commandline flag.Parse() // Print it to the screen fmt.Printf("Hello %s!\n", msg.UpperCaseIt()) } // Pointers in go, what are they and how do we use them? // What is the difference between a function and a method in Go and // why would you choose one over the other? // Exercise 5 Minutes: // Using the string package documentation at pkg.go.dev change the // above code to lowercase the variable output.
package common import ( "container/list" "errors" "sync" ) type ThreadSafeQueue struct { lock sync.Mutex vals *list.List } func NewThreadSafeQueue() Queue { return ThreadSafeQueue{ lock: sync.Mutex{}, vals: list.New(), } } func (tsq ThreadSafeQueue) IsEmpty() bool { return tsq.vals.Len() == 0 } func (tsq ThreadSafeQueue) HasNext() bool { return !tsq.IsEmpty() } func (tsq ThreadSafeQueue) Enqueue(val interface{}) { tsq.lock.Lock() defer tsq.lock.Unlock() tsq.vals.PushBack(val) } func (tsq ThreadSafeQueue) Dequeue() (interface{}, error) { tsq.lock.Lock() defer tsq.lock.Unlock() if tsq.vals.Len() == 0 { return nil, errors.New("Empty Stack") } front := tsq.vals.Front() tsq.vals.Remove(front) return front.Value, nil }
package domain type Service struct { User int `json:"user,omitempty"` Forum int `json:"forum,omitempty"` Thread int `json:"thread,omitempty"` Post int `json:"post,omitempty"` } type ServiceRepository interface { Clear() error Status() (Service, error) } type ServiceUsecase interface { Clear() error Status() (Service, error) }
package main import ( "encoding/json" "flag" "fmt" "log" "net/http" "os" "time" "github.com/araddon/dateparse" "github.com/mmcdole/gofeed" ) var ( OutLog = "** Run Log\n" ) type rss struct { Site string Limit int } type configuration struct { OutputPath string Rss []rss } func request(f *gofeed.Parser, feedURL string) (*gofeed.Feed, error) { client := http.Client{} req, err := http.NewRequest("GET", feedURL, nil) if err != nil { log.Println(err) return nil, err } req.Header.Set("User-Agent", "Golang_Bugwilla") resp, err := client.Do(req) if err != nil { log.Println(err) return nil, err } if resp != nil { defer resp.Body.Close() } if resp.StatusCode < 200 || resp.StatusCode >= 300 { return nil, gofeed.HTTPError{ StatusCode: resp.StatusCode, Status: resp.Status, } } return f.Parse(resp.Body) } func TokenReplacer(in []byte) (out []byte) { if len(in) < 4 { return } if (in[1] == 'a') && (in[2] == ' ') { return in } if (in[1] == '/') && (in[2] == 'a') && (len(in) == 4) { return in } return } func decode(feeds []rss) map[string][]string { output := make(map[string][]string) fp := gofeed.NewParser() today := time.Now() for _, xx := range feeds { feed, err := request(fp, xx.Site) if err != nil { logger(xx.Site, err) continue } tag := feed.Title if _, ok := output[tag]; !ok { output[tag] = make([]string, 0) } offset := 0 items := len(feed.Items) if (xx.Limit != 0) && (xx.Limit < items) { items = xx.Limit } for ii := 0; ii < items; ii++ { yy := feed.Items[ii] useDate := true localTime, err := dateparse.ParseAny(yy.Published) if err != nil { useDate = false } diff := today.Sub(localTime) offset++ condition := false if useDate { condition = diff <= time.Duration(1.0*60*60*24)*time.Second } else { condition = offset < 2 } if condition { output[tag] = append(output[tag], fmt.Sprintf("** TODO %s - [[%s][%s]]\n", tag, yy.Link, yy.Title)) } } logger(fmt.Sprintf("Feed %s found %d items", feed.Title, len(output[tag]))) } return output } func parseConfig(loc string) configuration { file, err := os.Open(loc) if err != nil { log.Fatal(err) } defer file.Close() jdec := json.NewDecoder(file) var conf configuration err = jdec.Decode(&conf) if err != nil { log.Fatal(err) } return conf } func emitOrg(kvs map[string][]string, dest string) { f, err := os.OpenFile(dest, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644) if err != nil { log.Fatal(err) } now := time.Now() year, month, day := now.Date() dow := now.Weekday().String() f.Write([]byte(fmt.Sprintf("* %d-%02d-%02d %s\n", year, int(month), day, dow))) for _, x := range kvs { for _, val := range x { if _, err := f.Write([]byte(val)); err != nil { log.Fatal(err) } } } if err := f.Close(); err != nil { log.Fatal(err) } } func logger(args ...interface{}) { OutLog = OutLog + "*** " + fmt.Sprint(args...) + "\n" } func main() { config := flag.String("config", "config.json", "config location") flag.Parse() logger("starting at", time.Now().String()) conf := parseConfig(*config) kvs := decode(conf.Rss) kvs["runlog"] = []string{OutLog} emitOrg(kvs, conf.OutputPath) }
package urkel import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "log" ) func GenPemRSA(keyLength int) (string, string) { privateKeyRaw, err := rsa.GenerateKey(rand.Reader, keyLength) if err != nil { log.Fatal("Error generating keys") } privateKeyDer := x509.MarshalPKCS1PrivateKey(privateKeyRaw) privateKeyBlock := pem.Block{ Type: "RSA PRIVATE KEY", Headers: nil, Bytes: privateKeyDer, } privateKeyPem := string(pem.EncodeToMemory(&privateKeyBlock)) publicKeyRaw := privateKeyRaw.PublicKey publicKeyDer, err := x509.MarshalPKIXPublicKey(&publicKeyRaw) if err != nil { log.Fatalf("Error serializing public key") } publicKeyBlock := pem.Block{ Type: "PUBLIC KEY", Headers: nil, Bytes: publicKeyDer, } publicKeyPem := string(pem.EncodeToMemory(&publicKeyBlock)) return privateKeyPem, publicKeyPem }
package router import ( "flea-market/controller/dialog" "flea-market/controller/goods" "flea-market/controller/star" "flea-market/controller/upload" "flea-market/controller/user" "github.com/gin-gonic/gin" ) func LoadApiRouter(r *gin.Engine) { api := r.Group("/api") { // 用户相关 api.GET("/user/login", user.Login) // 商品相关 api.POST("/goods/add",goods.Add) api.POST("/goods/update",goods.Update) api.POST("/goods/list",goods.List) api.POST("/goods/detail",goods.Detail) api.POST("/goods/status",goods.UpdateStatus) api.POST("/goods/delete",goods.Delete) // 留言相关 api.POST("/dialog/add",dialog.Add) api.POST("/dialog/list",dialog.List) api.POST("/dialog/response",dialog.Response) // 点赞相关 api.POST("/star/add",star.Add) api.POST("/star/remove",star.Remove) //图片上传 api.POST("/upload", upload.UploadImg) } }
package main import ( "grpc-sse/protos" "log" "net" "os" "os/signal" "sync" "syscall" "google.golang.org/grpc" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/reflection" ) func main() { gs := grpc.NewServer() logger := grpclog.NewLoggerV2(os.Stdout, os.Stdout, os.Stdout) eventsCh := make(chan EventRecord) cs := &EventServer{ Log: logger, EventCh: eventsCh, } protos.RegisterEventServer(gs, cs) // Switch off in dev reflection.Register(gs) l, err := net.Listen("tcp", ":9000") if err != nil { log.Fatalf("Unable to listen: %s", err) } go cs.EventLoop() stopChan := make(chan os.Signal, 1) // bind OS events to the signal channel signal.Notify(stopChan, syscall.SIGTERM, syscall.SIGINT) wg := sync.WaitGroup{} wg.Add(1) go func() { <-stopChan log.Println("Exit signal received...") close(eventsCh) log.Println("Stopping gRpc") gs.GracefulStop() wg.Done() }() logger.Infoln("Starting gRpc server at port 9000...") err = gs.Serve(l) if err != nil { close(eventsCh) log.Fatalf("Unable to start: %s", err) } wg.Wait() }
// Copyright 2019 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package sysutil import ( "io/ioutil" "math" "path/filepath" "strconv" "strings" "chromiumos/tast/errors" ) // TemperatureInputMax returns the maximum currently observed temperature in Celsius. func TemperatureInputMax() (float64, error) { // The files contain temperature input value in millidegree Celsius. // https://www.kernel.org/doc/Documentation/hwmon/sysfs-interface const pattern = "/sys/class/hwmon/hwmon*/temp*_input" fs, err := filepath.Glob(pattern) if err != nil { return 0, errors.Wrap(err, "unable to obtain list of temperature files") } if len(fs) == 0 { return 0, errors.Errorf("no file matches %s", pattern) } res := math.Inf(-1) for _, f := range fs { b, err := ioutil.ReadFile(f) if err != nil { return 0, errors.Wrap(err, "unable to read temperature file") } c, err := strconv.ParseFloat(strings.TrimSpace(string(b)), 64) if err != nil { return 0, errors.Wrapf(err, "could not parse %s to get input temperature", f) } res = math.Max(res, c/1000) } return res, nil }
package main // StatementRecord . type StatementRecord struct { LineNumber string Location string Label string Opcode string Operand string ObjectCode string IsPureCommentORBlank bool }
// // Copyright (c) SAS Institute 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 config import ( "errors" "os" ) // FromEnvironment tries to build a client-only config from environment variables. If none are set then returns nil. func FromEnvironment() (*Config, error) { remoteURL := os.Getenv("RELIC_URL") if remoteURL == "" { return nil, nil } clientCert := os.Getenv("RELIC_CLIENT_CERT") clientKey := os.Getenv("RELIC_CLIENT_KEY") accessToken := os.Getenv("RELIC_ACCESS_TOKEN") if clientCert == "" && accessToken == "" { return nil, errors.New("RELIC_CLIENT_CERT or RELIC_ACCESS_TOKEN must be set when RELIC_URL is set") } if clientKey == "" { clientKey = clientCert } cfg := &Config{ Remote: &RemoteConfig{ DirectoryURL: remoteURL, KeyFile: clientKey, CertFile: clientCert, AccessToken: accessToken, CaCert: os.Getenv("RELIC_CACERT"), }, } return cfg, cfg.Normalize("<env>") }
package main func main() { mainTimerDriver() } // func main() { // ck := fanin(counts("amy"), counts("rose")) // // amychan := counts("amy") // // rosechan := counts("rose") // for i := 0; i < 10; i++ { // fmt.Println(<-ck) // } // } // func fanin(c, k <-chan string) <-chan string { // ck := make(chan string) // go func() { // for{ ck <- <- c} // }() // go func() { // for{ ck <- <- k} // }() // return ck // } // func counts(name string) <-chan string { // c := make(chan string) // go func() { // for i := 0; ; i++ { // c <- fmt.Sprintf("%s: %d", name, i) // } // }() // return c // }
package recaptcha import ( // "fmt" // "github.com/sirupsen/logrus" // "io/ioutil" // "net/http" // "net/url" "strings" "testing" // "time" . "gopkg.in/check.v1" ) func TestPackage(t *testing.T) { TestingT(t) } type ReCaptchaSuite struct{} var _ = Suite(&ReCaptchaSuite{}) func (s *ReCaptchaSuite) TestNew(c *C) { captcha, err := NewWithSecert("my secret") c.Assert(err, IsNil) c.Check(captcha.Secret, Equals, "my secret") captcha, err = NewWithSecert("") c.Assert(err, NotNil) captcha, err = New() c.Assert(err, NotNil) } func (s *ReCaptchaSuite) TestVerifyInvalidSolutionNoRemoteIp(c *C) { captcha := &ReCAPTCHA{ Secret: "my secret", } err := captcha.Verify("mycode") c.Assert(err, NotNil) c.Check(err, ErrorMatches, "remote error codes: .*") } func (s *ReCaptchaSuite) TestVerifyInvalidSolutionWithRemoteIp(c *C) { captcha := &ReCAPTCHA{ Secret: "my secret", } err := captcha.VerifyWithOptions("mycode", VerifyOption{RemoteIP: "localhost"}) c.Assert(err, NotNil) c.Check(err, ErrorMatches, "remote error codes: .*") } func (s *ReCaptchaSuite) TestVerifyUnmarshalFatal(c *C) { responseJson := `{ "success": true, }` _, err := getReCAPTCHAResponse(responseJson) c.Assert(err, NotNil) c.Check(err, ErrorMatches, "invalid character '}' looking for beginning of object key string") } func (s *ReCaptchaSuite) TestVerifyUnmarshal(c *C) { responseJson := `{ "success": true, "challenge_ts": "2020-03-15T03:41:29+00:00", "score": 0.5, "action": "homepage", "hostname": "localhost", "apk_package_name": "app name", "ErrorCodes": ["bad-request"] }` res, err := getReCAPTCHAResponse(responseJson) c.Assert(err, IsNil) captcha := ReCAPTCHA{ Secret: "my secret", } captcha.showDebug(res) } func getReCAPTCHAResponse(responseJson string) (res reCAPTCHAResponse, err error) { body := strings.NewReader(responseJson) err = unmarshal(body, &res) return } func (s *ReCaptchaSuite) TestVerifyConfirmUnsuccess(c *C) { responseJson := `{ "success": false }` res, err := getReCAPTCHAResponse(responseJson) captcha := ReCAPTCHA{ Secret: "my secret", } err = captcha.confirm(res, VerifyOption{}) c.Assert(err, NotNil) c.Check(err, ErrorMatches, "invalid challenge solution") } func (s *ReCaptchaSuite) TestVerifyConfirmHostname(c *C) { responseJson := `{ "success": true, "hostname": "localhost" }` res, err := getReCAPTCHAResponse(responseJson) captcha := ReCAPTCHA{ Secret: "my secret", } err = captcha.confirm(res, VerifyOption{Hostname: "localhost1"}) c.Assert(err, NotNil) c.Check(err, ErrorMatches, "invalid response hostname 'localhost', while expecting 'localhost1'") } func (s *ReCaptchaSuite) TestVerifyConfirmResponseTime(c *C) { responseJson := `{ "success": true, "challenge_ts": "2020-03-14T18:21:29+09:00" }` res, err := getReCAPTCHAResponse(responseJson) captcha := ReCAPTCHA{ Secret: "my secret", } err = captcha.confirm(res, VerifyOption{ResponseTime: 1}) c.Assert(err, NotNil) c.Check(err, ErrorMatches, "time spent in resolving challenge .*") } func (s *ReCaptchaSuite) TestVerifyConfirmApkPackageName(c *C) { responseJson := `{ "success": true, "apk_package_name": "app name" }` res, err := getReCAPTCHAResponse(responseJson) captcha := ReCAPTCHA{ Secret: "my secret", } err = captcha.confirm(res, VerifyOption{ApkPackageName: "app name1"}) c.Assert(err, NotNil) c.Check(err, ErrorMatches, "invalid response ApkPackageName 'app name', while expecting 'app name1'") } func (s *ReCaptchaSuite) TestVerifyConfirmScore(c *C) { responseJson := `{ "success": true, "score": 0.4 }` res, err := getReCAPTCHAResponse(responseJson) captcha := ReCAPTCHA{ Secret: "my secret", } err = captcha.confirm(res, VerifyOption{Threshold: 0.6}) c.Assert(err, NotNil) c.Check(err, ErrorMatches, "received score '0.400000', while expecting minimum '0.600000'") err = captcha.confirm(res, VerifyOption{}) c.Assert(err, NotNil) c.Check(err, ErrorMatches, "received score '0.400000', while expecting minimum '0.500000'") } func (s *ReCaptchaSuite) TestVerifyConfirmAction(c *C) { responseJson := `{ "success": true, "action": "homepage" }` res, err := getReCAPTCHAResponse(responseJson) captcha := ReCAPTCHA{ Secret: "my secret", } err = captcha.confirm(res, VerifyOption{Action: "homepage1"}) c.Assert(err, NotNil) c.Check(err, ErrorMatches, "invalid response action 'homepage', while expecting 'homepage1'") } func (s *ReCaptchaSuite) TestVerifyConfirmWithoutActionAndScore(c *C) { responseJson := `{ "success": true }` res, err := getReCAPTCHAResponse(responseJson) captcha := ReCAPTCHA{ Secret: "my secret", } err = captcha.confirm(res, VerifyOption{}) c.Assert(err, IsNil) } func (s *ReCaptchaSuite) TestVerifyConfirmWithoutAction(c *C) { responseJson := `{ "success": true, "action": "homepage" }` res, err := getReCAPTCHAResponse(responseJson) captcha := ReCAPTCHA{ Secret: "my secret", } err = captcha.confirm(res, VerifyOption{}) c.Assert(err, IsNil) } func (s *ReCaptchaSuite) TestVerifyConfirmScoreWithoutAction(c *C) { responseJson := `{ "success": true, "score": 1.0 }` res, err := getReCAPTCHAResponse(responseJson) captcha := ReCAPTCHA{ Secret: "my secret", } err = captcha.confirm(res, VerifyOption{}) c.Assert(err, IsNil) }
package plugins import ( "encoding/json" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/klog" "strings" "WarpCloud/walm/pkg/models/k8s" "WarpCloud/walm/pkg/util" ) const ( NeedIsomateNameAnnoationKey = "NeedIsomateName" NeedIsomateNameAnnoationValue = "true" IsomateNamePluginName = "IsomateName" ) // IsomateName plugin is used to modify isomate resources name func init() { register(IsomateNamePluginName, &WalmPluginRunner{ Run: IsomateName, Type: Pre_Install, }) } type IsomateNameArgs struct { Name string `json:"name" description:"isomate name"` DefaultIsomate bool `json:"defaultIsomate" description:"default isomate"` } func IsomateName(context *PluginContext, args string) error { if args == "" { klog.Infof("ignore isomate name plugin, because plugin args is empty") return nil } else { klog.Infof("isomate name plugin args : %s", args) } isomateNameArgs := &IsomateNameArgs{} err := json.Unmarshal([]byte(args), isomateNameArgs) if err != nil { klog.Infof("failed to unmarshal plugin args : %s", err.Error()) return err } if isomateNameArgs.Name != "" { for _, resource := range context.Resources { unstructured := resource.(*unstructured.Unstructured) isomateResourceName := buildResourceName(unstructured, isomateNameArgs.Name) if unstructured.GetKind() == string(k8s.IsomateSetKind) { isomateSet, err := convertUnstructuredToIsomateSet(unstructured) if err != nil { klog.Errorf("failed to convert unstructured to isomate set : %s", err.Error()) return err } isoName := isomateSet.Name versionTemplate := isomateSet.Spec.VersionTemplates[isoName] if versionTemplate != nil { if versionTemplate.Labels == nil { versionTemplate.Labels = map[string]string{} } versionTemplate.Labels[k8s.IsomateNameLabelKey] = isomateNameArgs.Name stsAnnos := versionTemplate.Annotations if needIsomateName(stsAnnos) && !isomateNameArgs.DefaultIsomate { isomateSet.Spec.VersionTemplates[isomateResourceName] = versionTemplate delete(isomateSet.Spec.VersionTemplates, isoName) } isomateSetJsonMap, err := util.ConvertObjectToJsonMap(isomateSet) if err != nil { klog.Errorf("failed to convert isomate set to json map : %s", err.Error()) return err } unstructured.Object = isomateSetJsonMap } } else { err := addNestedStringMap(unstructured.Object, map[string]string{k8s.IsomateNameLabelKey: isomateNameArgs.Name}, "metadata", "labels") if err != nil { klog.Errorf("failed to set isomate name label : %s", err.Error()) return err } annos := unstructured.GetAnnotations() if needIsomateName(annos) { if !isomateNameArgs.DefaultIsomate { unstructured.SetName(isomateResourceName) } } } } } return nil } func needIsomateName(annos map[string]string) bool { return len(annos) > 0 && strings.ToLower(annos[NeedIsomateNameAnnoationKey]) == NeedIsomateNameAnnoationValue } func buildResourceName(unstructured *unstructured.Unstructured, isomateName string) string { return unstructured.GetName() + "-" + isomateName }
// +build !windows package findprocess import ( "os" "syscall" ) func findProcess(pid int) (process *os.Process, err error) { // On Unix systems, FindProcess always succeeds and returns a Process // for the given pid, regardless of whether the process exists. process, _ = os.FindProcess(pid) err = process.Signal(syscall.Signal(0)) if err == nil { return process, nil } if err.Error() == "os: process already finished" { return process, ErrNotFound } return process, err }
package privacy // NOTE: Reanme this package. Will eventually replace in its entirety with Activites. // PolicyEnforcer determines if personally identifiable information (PII) should be removed or anonymized per the policy. type PolicyEnforcer interface { // CanEnforce returns true when policy information is specifically provided by the publisher. CanEnforce() bool // ShouldEnforce returns true when the OpenRTB request should have personally identifiable // information (PII) removed or anonymized per the policy. ShouldEnforce(bidder string) bool } // NilPolicyEnforcer implements the PolicyEnforcer interface but will always return false. type NilPolicyEnforcer struct{} // CanEnforce is hardcoded to always return false. func (NilPolicyEnforcer) CanEnforce() bool { return false } // ShouldEnforce is hardcoded to always return false. func (NilPolicyEnforcer) ShouldEnforce(bidder string) bool { return false } // EnabledPolicyEnforcer decorates a PolicyEnforcer with an enabled flag. type EnabledPolicyEnforcer struct { Enabled bool PolicyEnforcer PolicyEnforcer } // CanEnforce returns true when the PolicyEnforcer can enforce. func (p EnabledPolicyEnforcer) CanEnforce() bool { return p.PolicyEnforcer.CanEnforce() } // ShouldEnforce returns true when the enforcer is enabled the PolicyEnforcer allows enforcement. func (p EnabledPolicyEnforcer) ShouldEnforce(bidder string) bool { if p.Enabled { return p.PolicyEnforcer.ShouldEnforce(bidder) } return false }
package model import "strconv" // GithubUser is response object from github api type GithubUser struct { ID int `json:"id"` UserName string `json:"login"` Email string `json:"email"` } // UUID return string github user id func (u *GithubUser) UUID() string { return strconv.Itoa(u.ID) }
// // Copyright (c) SAS Institute 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 msi // Sign Microsoft Installer files import ( "io" "io/ioutil" "os" "github.com/sassoftware/relic/v7/lib/atomicfile" "github.com/sassoftware/relic/v7/lib/authenticode" "github.com/sassoftware/relic/v7/lib/certloader" "github.com/sassoftware/relic/v7/lib/comdoc" "github.com/sassoftware/relic/v7/lib/magic" "github.com/sassoftware/relic/v7/signers" "github.com/sassoftware/relic/v7/signers/pecoff" ) var MsiSigner = &signers.Signer{ Name: "msi", Aliases: []string{"msi-tar"}, Magic: magic.FileTypeMSI, CertTypes: signers.CertTypeX509, Transform: transform, Sign: sign, Verify: verify, } func init() { MsiSigner.Flags().Bool("no-extended-sig", false, "(MSI) Don't emit a MsiDigitalSignatureEx digest") pecoff.AddOpusFlags(MsiSigner) signers.Register(MsiSigner) } type msiTransformer struct { f *os.File cdf *comdoc.ComDoc exsig []byte } func transform(f *os.File, opts signers.SignOpts) (signers.Transformer, error) { cdf, err := comdoc.ReadFile(f) if err != nil { return nil, err } var exsig []byte noExtended := opts.Flags.GetBool("no-extended-sig") if !noExtended { exsig, err = authenticode.PrehashMSI(cdf, opts.Hash) if err != nil { return nil, err } } return &msiTransformer{f, cdf, exsig}, nil } // transform the MSI to a tar stream for upload func (t *msiTransformer) GetReader() (io.Reader, error) { r, w := io.Pipe() go func() { _ = w.CloseWithError(authenticode.MsiToTar(t.cdf, w)) }() return r, nil } // apply a signed PKCS#7 blob to an already-open MSI document func (t *msiTransformer) Apply(dest, mimeType string, result io.Reader) error { t.cdf.Close() blob, err := ioutil.ReadAll(result) if err != nil { return err } // copy src to dest if needed, otherwise open in-place f, err := atomicfile.WriteInPlace(t.f, dest) if err != nil { return err } defer f.Close() cdf, err := comdoc.WriteFile(f.GetFile()) if err != nil { return err } if err := authenticode.InsertMSISignature(cdf, blob, t.exsig); err != nil { return err } if err := cdf.Close(); err != nil { return err } return f.Commit() } // sign a transformed tarball and return the PKCS#7 blob func sign(r io.Reader, cert *certloader.Certificate, opts signers.SignOpts) ([]byte, error) { noExtended := opts.Flags.GetBool("no-extended-sig") sum, err := authenticode.DigestMsiTar(r, opts.Hash, !noExtended) if err != nil { return nil, err } ts, err := authenticode.SignMSIImprint(opts.Context(), sum, opts.Hash, cert, pecoff.OpusFlags(opts)) if err != nil { return nil, err } return opts.SetPkcs7(ts) } func verify(f *os.File, opts signers.VerifyOpts) ([]*signers.Signature, error) { sig, err := authenticode.VerifyMSI(f, opts.NoDigests) if err != nil { return nil, err } return []*signers.Signature{{ Hash: sig.HashFunc, X509Signature: &sig.TimestampedSignature, SigInfo: pecoff.FormatOpus(sig.OpusInfo), }}, nil }
package util import ( "net/http" "github.com/gin-gonic/gin" ) // Contains function is to check item whether is exist or not in a list and will return bool func Contains(d string, dl []string) bool { for _, v := range dl { if v == d { return true } } return false } // CallErrorNotFound is for return API response not found func CallErrorNotFound(c *gin.Context, msg string, err error) { c.JSON(http.StatusNotFound, gin.H{ "success": false, "error": err, "msg": msg, "data": map[string]interface{}{}, }) } // CallUserError is for return error from user side func CallUserError(c *gin.Context, msg string, err error) { c.JSON(http.StatusBadRequest, gin.H{ "success": false, "error": err, "msg": msg, "data": map[string]interface{}{}, }) } // CallServerError is for return API response server error func CallServerError(c *gin.Context, msg string, err error) { c.JSON(http.StatusInternalServerError, gin.H{ "success": false, "error": err, "msg": msg, "data": map[string]interface{}{}, }) } // CallSuccessOK is for return API response with status code 200, you need to specify msg, and data as function parameter func CallSuccessOK(c *gin.Context, msg string, data interface{}) { c.JSON(http.StatusOK, gin.H{ "success": true, "error": "", "msg": msg, "data": data, }) } // CallUserFound is for return API response with status code 307 means its redirected func CallUserFound(c *gin.Context, msg string, data interface{}) { c.JSON(http.StatusTemporaryRedirect, gin.H{ "success": true, "error": "", "msg": msg, "data": data, }) } // CallUserNotAuthorized is for return API response with status code 403, you need to specify msg, and data as function paramenter func CallUserNotAuthorized(c *gin.Context, msg string, data interface{}) { c.JSON(http.StatusUnauthorized, gin.H{ "success": false, "error": "", "msg": msg, "data": data, }) }
package db import ( "database/sql" "fmt" "github.com/yanchenm/photo-sync/models" ) func (db Database) GetDetailForPhoto(id string) (models.Detail, error) { detail := models.Detail{} query := `SELECT * FROM details WHERE id = $1;` row := db.Conn.QueryRow(query, id) err := row.Scan(&detail.ID, &detail.FileType, &detail.Height, &detail.Width, &detail.Size) switch err { case sql.ErrNoRows: return detail, fmt.Errorf("no matching record") default: return detail, err } } func (db Database) AddDetail(detail *models.Detail) error { query := `INSERT INTO details (id, filetype, height, width, size) VALUES ($1, $2, $3, $4, $5)` _, err := db.Conn.Exec(query, detail.ID, detail.FileType, detail.Height, detail.Width, detail.Size) return err }
package extract_test import ( "fmt" "os" ) // LoggingFS is a disk that logs every operation, useful for unit-testing. type LoggingFS struct { Journal []*LoggedOp } // LoggedOp is an operation logged in a LoggingFS journal. type LoggedOp struct { Op string Path string OldPath string Mode os.FileMode Flags int } func (op *LoggedOp) String() string { switch op.Op { case "link": return fmt.Sprintf("link %s -> %s", op.Path, op.OldPath) case "symlink": return fmt.Sprintf("symlink %s -> %s", op.Path, op.OldPath) case "mkdirall": return fmt.Sprintf("mkdirall %v %s", op.Mode, op.Path) case "open": return fmt.Sprintf("open %v %s (flags=%04x)", op.Mode, op.Path, op.Flags) } panic("unknown LoggedOP " + op.Op) } func (m *LoggingFS) Link(oldname, newname string) error { m.Journal = append(m.Journal, &LoggedOp{ Op: "link", OldPath: oldname, Path: newname, }) return nil } func (m *LoggingFS) MkdirAll(path string, perm os.FileMode) error { m.Journal = append(m.Journal, &LoggedOp{ Op: "mkdirall", Path: path, Mode: perm, }) return nil } func (m *LoggingFS) Symlink(oldname, newname string) error { m.Journal = append(m.Journal, &LoggedOp{ Op: "symlink", OldPath: oldname, Path: newname, }) return nil } func (m *LoggingFS) OpenFile(name string, flags int, perm os.FileMode) (*os.File, error) { m.Journal = append(m.Journal, &LoggedOp{ Op: "open", Path: name, Mode: perm, Flags: flags, }) return os.OpenFile(os.DevNull, flags, perm) } func (m *LoggingFS) String() string { res := "" for _, op := range m.Journal { res += op.String() res += "\n" } return res }
package utils func GetMessage() { }
package hrtree import ( "fmt" ) func assert(ok bool) { assert2(ok, "assertion failed!") } func assert2(ok bool, msg string, args ...interface{}) { if !ok { panic(fmt.Sprintf(msg, args...)) } }
package controllers import( "revel_postgresql/app/models" "github.com/revel/revel" "fmt" ) type App struct { ModelController } func (c App) New() revel.Result { greeting := "Hello, Revel.!!" return c.Render(greeting) } func (c App) Index(name string) revel.Result { fmt.Println("Name------->", name) user := models.User{Name: name} fmt.Println("Users------->", user) fmt.Println("Saving data-->", c.Orm.Save(&user)) fmt.Println("All Data:", c.Orm.Exec("select * from users;")) rows, _ := c.Orm.Model(models.User{}).Select("name").Rows() fmt.Println("All Data:", rows) users := []models.User{} for rows.Next() { user := models.User{} err := rows.Scan(&user.Name) fmt.Println(err) fmt.Println(user) users = append(users, user) } fmt.Println("Users:", users) return c.Render(users) }
package binstruct type Marshaler interface { MarshalBinary() ([]byte, error) } func Marshal(v interface{}) ([]byte, error) { return nil, nil }
package namespace import "math" // IDSize is the number of bytes a namespace uses. // Valid values are in [0,255]. type IDSize uint8 // IDMaxSize defines the max. allowed namespace ID size in bytes. const IDMaxSize = math.MaxUint8
package rcluster import ( "strings" "github.com/go-redis/redis" ) var rcClient *redis.ClusterClient func init() { rcClient = redis.NewClusterClient(&redis.ClusterOptions{ Addrs: strings.Split( redisConfig.String("redisClusterHosts"), ",", ), PoolSize: 100, }) } func NewRedisClient() *redis.ClusterClient { if rcClient == nil { rcClient = redis.NewClusterClient(&redis.ClusterOptions{ Addrs: strings.Split( redisConfig.String("redisClusterHosts"), ",", ), PoolSize: 1000, }) } return rcClient }
package completers import ( "strings" prompt "github.com/c-bata/go-prompt" "github.com/lflxp/showme/pkg/prompt/suggests" ) // 解析函数 判断最新参数是否含有-字符 func getPreviousOption(d prompt.Document) (cmd, option string, found bool) { args := strings.Split(d.TextBeforeCursor(), " ") l := len(args) if l >= 2 { option = args[l-2] } if strings.HasPrefix(option, "-") { return args[0], option, true } return "", "", false } // 全局固定命令 func GlobalOptionFunc(d prompt.Document) ([]prompt.Suggest, bool) { cmd, option, found := getPreviousOption(d) if !found { return []prompt.Suggest{}, false } switch cmd { case "dashboard": // 带 - 参数的命令提示 // 命令输入大于等于两个 switch option { case "-v", "-vvv": return prompt.FilterHasPrefix( suggests.DetailSuggest(d), d.GetWordBeforeCursor(), true, ), true } } return []prompt.Suggest{}, false } // 用户自定义命令 func FirstCommandFunc(d prompt.Document, args []string) []prompt.Suggest { if len(args) <= 1 { return prompt.FilterHasPrefix(Commands, args[0], true) } first := args[0] switch first { case "dashboard": second := args[1] if len(args) == 2 { subcommands := []prompt.Suggest{ {Text: "help"}, {Text: "show", Description: "console for show me"}, {Text: "helloworld", Description: "dashboard for tcell cellviews.go"}, } return prompt.FilterHasPrefix(subcommands, second, true) } case "gocui": second := args[1] if len(args) == 2 { subcommands := []prompt.Suggest{ {Text: "help", Description: "帮助文档"}, {Text: "active", Description: "界面布局"}, } return prompt.FilterHasPrefix(subcommands, second, true) } case "scan": second := args[1] if len(args) == 2 { subcommands := []prompt.Suggest{ {Text: "192.168.50.1-255", Description: "192网段"}, {Text: "192.168.40.1-255", Description: "192网段"}, {Text: "192.168.1.1-255", Description: "192网段"}, {Text: "10.128.0.1-255", Description: "10网段"}, {Text: "10.128.142.1-255", Description: "10网段"}, {Text: "172.16.13.1-255", Description: "172网段"}, {Text: "172.168.0.1-255", Description: "172网段"}, } return prompt.FilterHasPrefix(subcommands, second, true) } case "mysql": second := args[1] if len(args) == 2 { subcommands := []prompt.Suggest{ {Text: "test", Description: "测试获取数据"}, {Text: "status", Description: "查看状态"}, {Text: "processlist", Description: "查看进程"}, } return prompt.FilterHasPrefix(subcommands, second, true) } third := args[2] if len(args) == 3 { switch second { case "test": subcommands := []prompt.Suggest{ {Text: "GetHostAndIps", Description: "GetHostAndIps"}, {Text: "GetShowDatabases", Description: "GetShowDatabases"}, {Text: "GetShowGlobalVariables", Description: "GetShowGlobalVariables"}, {Text: "GetShowVariables", Description: "GetShowVariables"}, {Text: "GetShowStatus", Description: "GetShowStatus"}, {Text: "GetShowGlobalStatus", Description: "GetShowGlobalStatus"}, {Text: "GetShowEngineInnodbStatus", Description: "GetShowEngineInnodbStatus"}, } return prompt.FilterHasPrefix(subcommands, third, true) } } default: return []prompt.Suggest{} } return []prompt.Suggest{} }
package webca import ( "encoding/gob" "log" "os" "sync" ) const ( WEBCA_CFG = ".webca.cfg" ) // oneCfg ensures serialized access to configuration var oneCfg sync.Mutex // User contains the App's User details type User struct { Username, Fullname, Password, Email string } // config contains the App's Configuration type config struct { Mailer *Mailer Advance int // days before the cert. expires that the notification will be sent Users map[string]*User Certs *CertTree WebCert *Cert } // Configurer is the interface to access and user Configuration type Configurer interface { save() error webCert() *Cert certFile() string keyFile() string } // New Config obtains a new Config func NewConfig(u User, cacert *Cert, cert *Cert, m Mailer) Configurer { certs := newCertTree() certs.addCert(cacert) certs.addCert(cert) cfg := &config{&m, 15, make(map[string]*User), certs, cert} cfg.Users[u.Username] = &u return cfg } // LoadConfig (re)loads a config // (It needs to be thread safe) func LoadConfig() Configurer { oneCfg.Lock() defer oneCfg.Unlock() _, err := os.Stat(WEBCA_CFG) if os.IsNotExist(err) { return nil } f, err := os.Open(WEBCA_CFG) handleFatal(err) defer f.Close() dec := gob.NewDecoder(f) if dec == nil { log.Fatalf("(Warning) Could not decode " + WEBCA_CFG + "!") } cfg := config{} err = dec.Decode(&cfg) handleFatal(err) return &cfg } // save puts the current config into persistent storage // (It needs to be thread safe) func (cfg *config) save() error { oneCfg.Lock() defer oneCfg.Unlock() f, err := os.OpenFile(WEBCA_CFG, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { log.Println("can't open") return err } defer f.Close() enc := gob.NewEncoder(f) err = enc.Encode(cfg) if err != nil { log.Println("can't save") return err } return nil } // webCert returns this web Certificate func (cfg *config) webCert() *Cert { return cfg.WebCert } // webCA returns this web CA Cert func (cfg *config) certFile() string { return cfg.WebCert.Crt.Subject.CommonName+CERT_SUFFIX } // webCA returns this web CA Cert func (cfg *config) keyFile() string { return cfg.WebCert.Crt.Subject.CommonName+KEY_SUFFIX }
package consumer import ( "context" "sync" "time" "github.com/pkg/errors" "github.com/streadway/amqp" "github.com/upfluence/pkg/closer" "github.com/upfluence/pkg/log" ) var ErrCancelled = errors.New("amqp/consumer: Consumer is cancelled") type Consumer interface { Open(context.Context) error IsOpen() bool Consume() (<-chan amqp.Delivery, <-chan *amqp.Error, error) QueueName(context.Context) (string, error) closer.Closer } type consumer struct { *closer.Monitor opts *options openOnce sync.Once consumersM sync.Mutex consumers []chan amqp.Delivery errForwardersM sync.Mutex errForwarders []chan *amqp.Error queueCond *sync.Cond queueM sync.Mutex queue string } func NewConsumer(opts ...Option) Consumer { var options = *defaultOptions for _, opt := range opts { opt(&options) } c := consumer{Monitor: closer.NewMonitor(), opts: &options} c.queueCond = sync.NewCond(&c.queueM) return &c } func (c *consumer) QueueName(ctx context.Context) (string, error) { c.queueM.Lock() q := c.queue c.queueM.Unlock() if q != "" { return q, nil } done := make(chan struct{}) cancelled := false go func() { c.queueM.Lock() defer c.queueM.Unlock() for { if cancelled || c.queue != "" { q = c.queue close(done) return } c.queueCond.Wait() } }() select { case <-ctx.Done(): c.queueM.Lock() cancelled = true c.queueCond.Broadcast() c.queueM.Unlock() return "", ctx.Err() case <-done: return q, nil } } func (c *consumer) loop(ctx context.Context) { var i int for { var ok, err = c.consume(ctx) if ok || !c.opts.shouldContinueFn(err) { return } log.WithError(err).Warning("cant consume") t, _ := c.opts.backoff.Backoff(i) i++ time.Sleep(t) } } func (c *consumer) consume(ctx context.Context) (bool, error) { ch, err := c.opts.pool.Get(ctx) if err != nil { return false, errors.Wrap(err, "pool.Get") } if qName := c.opts.queueName; qName == "" { q, errQ := ch.QueueDeclare("", false, true, true, false, nil) if errQ != nil { return false, errors.Wrap(errQ, "channel.QueueDeclare") } log.Noticef("Queue declared: %s", q.Name) c.queueM.Lock() c.queue = q.Name c.queueM.Unlock() } else { c.queueM.Lock() c.queue = qName c.queueM.Unlock() } ds, err := ch.Consume( c.queue, c.opts.consumerTag, false, false, false, false, nil, ) if err != nil { return false, errors.Wrap(err, "channel.Consume") } c.queueCond.Broadcast() closeCh := make(chan *amqp.Error) ch.NotifyClose(closeCh) for { select { case <-ctx.Done(): c.queueM.Lock() c.queue = "" c.queueM.Unlock() ch.Cancel(c.opts.consumerTag, false) c.opts.pool.Put(ch) return true, ctx.Err() case err := <-closeCh: c.queueM.Lock() c.queue = "" c.queueM.Unlock() for _, f := range c.errForwarders { select { case <-ctx.Done(): case f <- err: } } c.opts.pool.Discard(ch) return false, nil case d := <-ds: for _, c := range c.consumers { select { case <-ctx.Done(): case c <- d: } } d.Ack(false) } } } func (c *consumer) open(ctx context.Context) error { if err := c.opts.pool.Open(ctx); err != nil { return err } c.Run(c.loop) return nil } func (c *consumer) Open(ctx context.Context) error { var err error c.openOnce.Do(func() { err = c.open(ctx) }) return err } func (c *consumer) Consume() (<-chan amqp.Delivery, <-chan *amqp.Error, error) { if !c.IsOpen() { return nil, nil, ErrCancelled } var ( ch = make(chan amqp.Delivery) errF = make(chan *amqp.Error) ) c.consumersM.Lock() c.consumers = append(c.consumers, ch) c.consumersM.Unlock() c.errForwardersM.Lock() c.errForwarders = append(c.errForwarders, errF) c.errForwardersM.Unlock() return ch, errF, nil } func (c *consumer) Close() error { c.Monitor.Close() c.consumersM.Lock() for _, c := range c.consumers { close(c) } c.consumers = nil c.consumersM.Unlock() c.errForwardersM.Lock() for _, f := range c.errForwarders { close(f) } c.errForwarders = nil c.errForwardersM.Unlock() if c.opts.handlePoolClosing { return c.opts.pool.Close() } return nil }
package models import( "encoding/json" ) /** * Type definition for UpgradeStatusEnum enum */ type UpgradeStatusEnum int /** * Value collection for UpgradeStatusEnum enum */ const ( UpgradeStatus_KIDLE UpgradeStatusEnum = 1 + iota UpgradeStatus_KACCEPTED UpgradeStatus_KSTARTED UpgradeStatus_KFINISHED ) func (r UpgradeStatusEnum) MarshalJSON() ([]byte, error) { s := UpgradeStatusEnumToValue(r) return json.Marshal(s) } func (r *UpgradeStatusEnum) UnmarshalJSON(data []byte) error { var s string json.Unmarshal(data, &s) v := UpgradeStatusEnumFromValue(s) *r = v return nil } /** * Converts UpgradeStatusEnum to its string representation */ func UpgradeStatusEnumToValue(upgradeStatusEnum UpgradeStatusEnum) string { switch upgradeStatusEnum { case UpgradeStatus_KIDLE: return "kIdle" case UpgradeStatus_KACCEPTED: return "kAccepted" case UpgradeStatus_KSTARTED: return "kStarted" case UpgradeStatus_KFINISHED: return "kFinished" default: return "kIdle" } } /** * Converts UpgradeStatusEnum Array to its string Array representation */ func UpgradeStatusEnumArrayToValue(upgradeStatusEnum []UpgradeStatusEnum) []string { convArray := make([]string,len( upgradeStatusEnum)) for i:=0; i<len(upgradeStatusEnum);i++ { convArray[i] = UpgradeStatusEnumToValue(upgradeStatusEnum[i]) } return convArray } /** * Converts given value to its enum representation */ func UpgradeStatusEnumFromValue(value string) UpgradeStatusEnum { switch value { case "kIdle": return UpgradeStatus_KIDLE case "kAccepted": return UpgradeStatus_KACCEPTED case "kStarted": return UpgradeStatus_KSTARTED case "kFinished": return UpgradeStatus_KFINISHED default: return UpgradeStatus_KIDLE } }
// Copyright (c) 2018 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package trafficcontrol import ( "fmt" "time" "github.com/m3db/m3cluster/kv" "github.com/m3db/m3x/instrument" ) // Type defines the type of the traffic controller. type Type string var ( // TrafficEnabler enables the traffic when the runtime value equals to true. TrafficEnabler Type = "trafficEnabler" // TrafficDisabler disables the traffic when the runtime value equals to true. TrafficDisabler Type = "trafficDisabler" validTypes = []Type{ TrafficEnabler, TrafficDisabler, } ) // UnmarshalYAML unmarshals TrafficControllerType from yaml. func (t *Type) UnmarshalYAML(unmarshal func(interface{}) error) error { var str string if err := unmarshal(&str); err != nil { return err } var validStrings []string for _, validType := range validTypes { validString := string(validType) if validString == str { *t = validType return nil } validStrings = append(validStrings, validString) } return fmt.Errorf("invalid traffic controller type %s, valid types are: %v", str, validStrings) } // Configuration configures the traffic controller. type Configuration struct { Type Type `yaml:"type"` DefaultValue *bool `yaml:"defaultValue"` RuntimeKey string `yaml:"runtimeKey" validate:"nonzero"` InitTimeout *time.Duration `yaml:"initTimeout"` } // NewTrafficController creates a new traffic controller. func (c *Configuration) NewTrafficController( store kv.Store, instrumentOpts instrument.Options, ) (Controller, error) { opts := NewOptions(). SetStore(store). SetRuntimeKey(c.RuntimeKey). SetInstrumentOptions(instrumentOpts) if c.DefaultValue != nil { opts = opts.SetDefaultValue(*c.DefaultValue) } if c.InitTimeout != nil { opts = opts.SetInitTimeout(*c.InitTimeout) } var tc Controller if c.Type == TrafficEnabler { tc = NewTrafficEnabler(opts) } else { tc = NewTrafficDisabler(opts) } if err := tc.Init(); err != nil { return nil, err } return tc, nil }
package space //Planet custom string type for planet name type Planet string const earthYearInSec float64 = 31557600.0 var orbitalPeriods = map[Planet]float64{ "Mercury": 0.2408467, "Venus": 0.61519726, "Earth": 1.0, "Mars": 1.8808158, "Jupiter": 11.862615, "Saturn": 29.447498, "Uranus": 84.016846, "Neptune": 164.79132, } //Age will calculate how many given planet years is someone old, //based on the age given in seconds and planet name func Age(ageInSec float64, planet Planet) float64 { numOfYears := ageInSec / (orbitalPeriods[planet] * earthYearInSec) return numOfYears }
package main import ( "fmt" "github.com/cloudflare/ahocorasick" ) func main() { dictionary := []string{"hello", "world", "世界", "google", "golang", "c++", "love"} ac := ahocorasick.NewStringMatcher(dictionary) ret := ac.Match([]byte("hello世界, hello google, i love golang!!!")) for index, i := range ret { fmt.Println(index, ": ", dictionary[i]) } //params := []interface{}{"2", "5", "2", "2"} //s := "SELECT toUnixTimestamp(max(ts)) AS _ts, ip, countIf(event='book') AS book_count, uniq(contact_name) AS name_count, uniq(contact_phone) AS phone_count, SUM(passengers_count) AS pass_number, 1 AS _result FROM order_airline WHERE ts > now() - 3600 GROUP BY ip HAVING book_count > %s AND pass_number > %s AND ( name_count > %s OR phone_count > s% )" // //fmt.Println(FormatRule(s, params)) // //fmt.Sprintf("SELECT toUnixTimestamp(max(ts)) AS _ts, ip, countIf(event='book') AS book_count, uniq(contact_name) AS name_count, uniq(contact_phone) AS phone_count, SUM(passengers_count) AS pass_number, 1 AS _result FROM order_airline WHERE ts > now() - 3600 GROUP BY ip HAVING book_count > %s AND pass_number > %s AND ( name_count > %s OR phone_count > s% )", params...) } func FormatRule(format string, params []interface{}) string { return fmt.Sprintf(format, params...) }
/* Copyright 2020 The KubeSphere 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 v1alpha1 import ( "k8s.io/api/auditregistration/v1alpha1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. // Receiver config which received the audit alert type Receiver struct { // Receiver name // +optional ReceicerName string `json:"name,omitempty" protobuf:"bytes,8,opt,name=name"` // Receiver type, alertmanager or webhook // +optional ReceiverType string `json:"type,omitempty" protobuf:"bytes,8,opt,name=type"` // ClientConfig holds the connection parameters for the webhook // +optional ReceiverConfig v1alpha1.WebhookClientConfig `json:"config,omitempty" protobuf:"bytes,8,opt,name=config"` } type AuditSinkPolicy struct { ArchivingRuleSelector *metav1.LabelSelector `json:"archivingRuleSelector,omitempty" protobuf:"bytes,8,opt,name=archivingRuleSelector"` AlertingRuleSelector *metav1.LabelSelector `json:"alertingRuleSelector,omitempty" protobuf:"bytes,8,opt,name=alertingRuleSelector"` } type DynamicAuditConfig struct { // Throttle holds the options for throttling the webhook // +optional Throttle *v1alpha1.WebhookThrottleConfig `json:"throttle,omitempty" protobuf:"bytes,18,opt,name=throttle"` // Policy defines the policy for selecting which events should be sent to the webhook // +optional Policy *v1alpha1.Policy `json:"policy,omitempty" protobuf:"bytes,18,opt,name=policy"` } // WebhookSpec defines the desired state of Webhook type WebhookSpec struct { // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster // Important: Run "make" to regenerate code after modifying this file // Number of desired pods. This is a pointer to distinguish between explicit // zero and not specified. Defaults to 1. // +optional Replicas *int32 `json:"replicas,omitempty" protobuf:"varint,1,opt,name=replicas"` // The webhook docker image name. // +optional Image string `json:"image,omitempty" protobuf:"bytes,2,opt,name=image"` // Image pull policy. // One of Always, Never, IfNotPresent. // Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. // Cannot be updated. // More info: https://kubernetes.io/docs/concepts/containers/images#updating-images // +optional ImagePullPolicy corev1.PullPolicy `json:"imagePullPolicy,omitempty" protobuf:"bytes,14,opt,name=imagePullPolicy,casttype=PullPolicy"` // ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. // If specified, these secrets will be passed to individual puller implementations for them to use. For example, // in the case of docker, only DockerConfig type secrets are honored. // More info: https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod // +optional // +patchMergeKey=name // +patchStrategy=merge ImagePullSecrets []corev1.LocalObjectReference `json:"imagePullSecrets,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,15,rep,name=imagePullSecrets"` // Arguments to the entrypoint.. // It will be appended to the args and replace the default value. // +optional Args []string `json:"args,omitempty" protobuf:"bytes,3,rep,name=args"` // NodeSelector is a selector which must be true for the pod to fit on a node. // Selector which must match a node's labels for the pod to be scheduled on that node. // More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/ // +optional NodeSelector map[string]string `json:"nodeSelector,omitempty" protobuf:"bytes,7,rep,name=nodeSelector"` // If specified, the pod's scheduling constraints // +optional Affinity *corev1.Affinity `json:"affinity,omitempty" protobuf:"bytes,18,opt,name=affinity"` // If specified, the pod's tolerations. // +optional Tolerations []corev1.Toleration `json:"tolerations,omitempty" protobuf:"bytes,22,opt,name=tolerations"` // Compute Resources required by this container. // Cannot be updated. // More info: https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/ // +optional Resources *corev1.ResourceRequirements `json:"resources,omitempty" protobuf:"bytes,8,opt,name=resources"` // Receiver contains the information to make a connection with the alertmanager // +optional Receivers []Receiver `json:"receivers,omitempty" protobuf:"bytes,8,opt,name=receivers"` // AuditSinkPolicy is a rule selector, only the rule matched this selector will be taked effect. // +optional *AuditSinkPolicy `json:"auditSinkPolicy,omitempty" protobuf:"bytes,8,opt,name=auditSinkPolicy"` // Rule priority, DEBUG < INFO < WARNING //Audit events will be stored only when the priority of the audit rule // matching the audit event is greater than this. Priority string `json:"priority,omitempty" protobuf:"bytes,8,opt,name=priority"` // Audit type, static or dynamic. AuditType string `json:"auditType,omitempty" protobuf:"bytes,8,opt,name=auditType"` // The Level that all requests are recorded at. // available options: None, Metadata, Request, RequestResponse // default: Metadata // +optional AuditLevel v1alpha1.Level `json:"auditLevel" protobuf:"bytes,1,opt,name=auditLevel"` // K8s auditing is enabled or not. K8sAuditingEnabled bool `json:"k8sAuditingEnabled,omitempty" protobuf:"bytes,8,opt,name=priority"` } // WebhookStatus defines the observed state of Webhook type WebhookStatus struct { // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster // Important: Run "make" to regenerate code after modifying this file } // +genclient // +genclient:noStatus // +genclient:nonNamespaced // +kubebuilder:object:root=true // Webhook is the Schema for the webhooks API type Webhook struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec WebhookSpec `json:"spec,omitempty"` Status WebhookStatus `json:"status,omitempty"` } // +kubebuilder:object:root=true // WebhookList contains a list of Webhook type WebhookList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []Webhook `json:"items"` } func init() { SchemeBuilder.Register(&Webhook{}, &WebhookList{}) }
/* This is the main entry of my chatroom project. moduels: SocketServer: basic wrapper for data transmission SocketDataAdapter: binary/ json / ... MessageDispatcher ChatRoomManager: dispatch message to correct rooms ChatRoom PrivateChatRoom PublicChatRoom HistoryKeeper */ package main import (NT "network") const ( CONN_HOST = "localhost" CONN_PORT = "3333" CONN_TYPE = "tcp" ) // function main func main() { //var isoc NT.ISocket = &NT.Socket{NT.SocketInfo{"serverIp",1234}} //var buffer [8] byte; //buffer := make([]byte,8) //isoc.Recv(buffer[:]) // pass slice in //fmt.Println(buffer) //isoc.Send(buffer[:]) //fmt.Println("server side: socket object local ip=", psock.LocalIP) //fmt.Println("123") server := NT.SocketServer{"0.0.0.0", 8080} server.Run() }
package authentication import "testing" func TestComputeHmac256(t *testing.T) { res := ComputeHmac256("message", "secret") expectation := "i19IcCmVwVmMVz2x4hhmqbgl1KeU0WnXBgoDYFeWNgs=" if res != expectation { t.Error("Expected", expectation, "got", res) } } func TestComputeHmac1(t *testing.T) { res := ComputeHmac1("message", "secret") expectation := "DK9kn+7klT2Hv5A6wRdsReAo3xY=" if res != expectation { t.Error("Expected", expectation, "got", res) } }
package main //comment
package handler import ( "log" "net" "github.com/glasnostic/example/router/packet" "github.com/google/gopacket/layers" ) // rewriter type rewriter struct { local *pod client *pod server *pod table map[uint32]net.HardwareAddr } // NewRewriter create New Rewriter Handler func NewRewriter(localMac, clientMac, serverMac net.HardwareAddr, localIP net.IP, client, server net.IP) packet.Handler { res := &rewriter{ local: newPod(localIP, localMac), client: newPod(client, clientMac), server: newPod(server, serverMac), table: make(map[uint32]net.HardwareAddr), } res.table[res.client.value] = res.client.mac res.table[res.server.value] = res.server.mac return res } func (r *rewriter) Handle(meta *packet.Metadata) (packet.Action, error) { typ := typeOfPacket(meta) log.Printf("Packet type %s length %d\n", typ, len(meta.Packet)) switch typ { case layers.EthernetTypeARP: return r.handleARP(meta) case layers.EthernetTypeIPv4: return r.handleIP(meta) case layers.EthernetTypeIPv6: return r.handleIPv6(meta) default: } return packet.Drop, ErrNotAcceptableType } func (r *rewriter) handleIPv6(meta *packet.Metadata) (packet.Action, error) { return packet.Drop, ErrV6NotSupport } func (r *rewriter) handleIP(meta *packet.Metadata) (packet.Action, error) { realSrc := getSrcIPFromIPPacket(meta) // 1. change destination IP (local -> picked) realDst := r.selectTarget(realSrc) // 2. check we have the MAC address of destination IP dstMAC, ok := r.table[realDst] if !ok { // 2-1. if no, send ARP request return r.sendARPRequest(meta, realDst) } // 2-2. if yes, set realDst with dstMAC to packet setDst(meta, realDst, dstMAC) // 3. change source IP to local (real -> local) setSrc(meta, r.local.value, r.local.mac) // 4. calculate the checksum return checksum(meta) } // For simplifying setup, just pick destination from the source func (r *rewriter) selectTarget(ip uint32) uint32 { switch ip { case r.client.value: return r.server.value default: return r.client.value } }
package utils import ( "encoding/json" "reflect" log "github.com/sirupsen/logrus" "github.com/tidwall/pretty" ) // PrettyPrint - output formatted json func PrettyPrint(i interface{}) { log.Debug(reflect.TypeOf(i)) s, _ := json.MarshalIndent(i, "", "\t") colored := pretty.Color(s, nil) log.Debug(string(colored)) }
package ch04 type UUIDCounter map[string]int func NewUUIDCounter() *UUIDCounter { return &UUIDCounter{} } func (c *UUIDCounter) Count(id []byte) { (*c)[string(id)]++ }
package main import "fmt" // goではclassの代わりにstructを使う type Person struct { Name string // 大文字で始まるとpublic age int // 小文字で始まるとprivate } // structにはメンバー変数のみ定義してメソッドは{this相当の変数 *struct名}をつけたfuncを書く func (p *Person) SetPerson(name string, age int) { p.Name = name p.age = age } func (p *Person) GetAge() int { return p.age } func main() { var p1 Person p1.SetPerson("gundam", 2) fmt.Println(p1.Name, p1.GetAge()) p2 := Person{"zaku", 199} fmt.Println(p2) }
// Copyright © 2019. All rights reserved. // Author: Ilya Yuryevich. // Contacts: qioalice@gmail.com, https://github.com/qioalice // License: https://opensource.org/licenses/MIT package ekafield import ( "fmt" "math" "time" "github.com/qioalice/ekago/v2/internal/ekaclike" "github.com/modern-go/reflect2" ) // Inspired by: https://github.com/uber-go/zap/blob/master/zapcore/field.go // TODO: Array support // TODO: Map support // TODO: Struct (classes) support type ( // Field is an explicit logger or error field's type. // // Field stores some data most optimized way providing ability to use it // as replacing of Golang interface{} but with more clear and optimized type // checks. Thus you can then write your own Integrator and encode log Entry's // or Error's fields the way you want. // // TBH, all implicit fields (both of named/unnamed) are converts // to the explicit ones by internal private methods and thus all key-value // pairs you want to attach to log's entry will be stored using this type. // // WARNING! // DO NOT INSTANTIATE FIELD OBJECT MANUALLY IF YOU DONT KNOW HOW TO USE IT. // In most cases of bad initializations that Field will be considered invalid // and do not handled then at the logging. // USE CONSTRUCTORS OR MAKE SURE YOU UNDERSTAND WHAT DO YOU DO. Field struct { // Key is a field's name. // Empty if it's unnamed explicit/implicit field. Key string // Kind represents what kind of field it is. // // WARNING! // If you want to compare Kind with any of Kind... constants, use // Field.Kind.BaseType() or Field.BaseType() method before! // For more info see these methods docs. Kind Kind IValue int64 // for all ints, uints, floats, bool, complex64, pointers SValue string // for string, []byte, fmt.Stringer Value interface{} // for all not easy cases } // Kind is an alias to uint8. Generally it's a way to store field's base type // predefined const and flags. As described in 'Field.Kind' comments: // // It's uint8 in the following format: XXXYYYYY, where: // XXX - 3 highest bits - kind flags: nil, array, something else // YYYYY - 5 lowest bits - used to store const of base type field's value. Kind uint8 ) //noinspection GoSnakeCaseUsage const ( KIND_MASK_BASE_TYPE = 0b_0001_1111 KIND_FLAG_ARRAY = 0b_0010_0000 KIND_FLAG_NULL = 0b_0100_0000 KIND_FLAG_SYSTEM = 0b_1000_0000 KIND_TYPE_INVALID = 0 // can't be handled in almost all cases // field.Kind & KIND_MASK_BASE_TYPE could be any of listed below, // only if field.Kind KIND_FLAG_INTERNAL_SYS != 0 (system letter's field) KIND_SYS_TYPE_EKAERR_UUID = 1 KIND_SYS_TYPE_EKAERR_CLASS_ID = 2 KIND_SYS_TYPE_EKAERR_CLASS_NAME = 3 KIND_SYS_TYPE_EKAERR_PUBLIC_MESSAGE = 4 // field.Kind & KIND_MASK_BASE_TYPE could be any of listed below, // only if field.Kind & KIND_FLAG_INTERNAL_SYS == 0 (user's field) _ = 1 // reserved _ = 2 // reserved KIND_TYPE_BOOL = 3 // uses IValue to store bool KIND_TYPE_INT = 4 // uses IValue to store int KIND_TYPE_INT_8 = 5 // uses IValue to store int8 KIND_TYPE_INT_16 = 6 // uses IValue to store int16 KIND_TYPE_INT_32 = 7 // uses IValue to store int32 KIND_TYPE_INT_64 = 8 // uses IValue to store int64 KIND_TYPE_UINT = 9 // uses IValue to store uint KIND_TYPE_UINT_8 = 10 // uses IValue to store uint8 KIND_TYPE_UINT_16 = 11 // uses IValue to store uint16 KIND_TYPE_UINT_32 = 12 // uses IValue to store uint32 KIND_TYPE_UINT_64 = 13 // uses IValue to store uint64 KIND_TYPE_UINTPTR = 14 // uses IValue to store uintptr KIND_TYPE_FLOAT_32 = 15 // uses IValue to store float32 (bits) KIND_TYPE_FLOAT_64 = 16 // uses IValue to store float64 (bits) KIND_TYPE_COMPLEX_64 = 17 // uses IValue to store complex64 KIND_TYPE_COMPLEX_128 = 18 // uses Value (interface{}) to store complex128 KIND_TYPE_STRING = 19 // uses SValue to store string _ = 20 // reserved KIND_TYPE_ADDR = 21 // uses IValue to store some addr (like uintptr) _ = 31 // reserved, max, range [21..31] is free now // --------------------------------------------------------------------- // // WARNING // // Keep in mind that max value of Kind base type is 31 // // (because of KIND_MASK_BASE_TYPE == 0b00011111 == 0x1F == 31). // // DO NOT OVERFLOW THIS VALUE WHEN YOU WILL ADD A NEW CONSTANTS // // --------------------------------------------------------------------- // ) var ( // Used for type comparision. ReflectedType = reflect2.TypeOf(Field{}) ReflectedTypePtr = reflect2.TypeOf((*Field)(nil)) ReflectedTypeFmtStringer = reflect2.TypeOfPtr((*fmt.Stringer)(nil)).Elem() ) //noinspection GoErrorStringFormat var ( ErrUnsupportedKind = fmt.Errorf("Field: Unsupported kind of Field.") ) // BaseType extracts only 5 lowest bits from fk and returns it (ignore flags). // // Call fk.BaseType() and then you can compare returned value with predefined // Kind... constants. DO NOT COMPARE DIRECTLY, because fk can contain flags // and then regular equal check (==) will fail. func (fk Kind) BaseType() Kind { return fk & KIND_MASK_BASE_TYPE } // IsArray reports whether fk represents an array with some base type. func (fk Kind) IsArray() bool { return fk&KIND_FLAG_ARRAY != 0 } // IsNil reports whether fk represents a nil value. // // Returns true for both cases: // - fk is nil with some base type, // - fk is absolutely untyped nil. func (fk Kind) IsNil() bool { return fk&KIND_FLAG_NULL != 0 } // IsSystem reports whether fk represents a *Letter system field. // See https://github.com/qioalice/ekago/internal/letter/letter.go . func (fk Kind) IsSystem() bool { return fk&KIND_FLAG_SYSTEM != 0 } // BaseType returns f's kind base type. You can use direct comparision operators // (==, !=, etc) with returned value and Kind... constants. func (f Field) BaseType() Kind { return f.Kind.BaseType() } // IsArray reports whether f represents an array with some base type. func (f Field) IsArray() bool { return f.Kind.IsArray() } // IsNil reports whether f represents a nil value. // // Returns true for both cases: // - f stores nil as value of some base type, // - f stores nil and its absolutely untyped nil. func (f Field) IsNil() bool { return f.Kind.IsNil() } // IsSystem reports whether f represents a *Letter system field. // See https://github.com/qioalice/ekago/internal/letter/letter.go . func (f Field) IsSystem() bool { return f.Kind.IsSystem() } // Reset frees all allocated resources (RAM in 99% cases) by Field f, preparing // it for being reused in the future. func Reset(f *Field) { f.Key = "" f.Kind = 0 f.IValue, f.SValue, f.Value = 0, "", nil } // --------------------------- EASY CASES GENERATORS -------------------------- // // ---------------------------------------------------------------------------- // // Bool constructs a field with the given key and value. func Bool(key string, value bool) Field { if value { return Field{Key: key, IValue: 1, Kind: KIND_TYPE_BOOL} } else { return Field{Key: key, IValue: 0, Kind: KIND_TYPE_BOOL} } } // Int constructs a field with the given key and value. func Int(key string, value int) Field { return Field{Key: key, IValue: int64(value), Kind: KIND_TYPE_INT} } // Int8 constructs a field with the given key and value. func Int8(key string, value int8) Field { return Field{Key: key, IValue: int64(value), Kind: KIND_TYPE_INT_8} } // Int16 constructs a field with the given key and value. func Int16(key string, value int16) Field { return Field{Key: key, IValue: int64(value), Kind: KIND_TYPE_INT_16} } // Int32 constructs a field with the given key and value. func Int32(key string, value int32) Field { return Field{Key: key, IValue: int64(value), Kind: KIND_TYPE_INT_32} } // Int64 constructs a field with the given key and value. func Int64(key string, value int64) Field { return Field{Key: key, IValue: value, Kind: KIND_TYPE_INT_64} } // Uint constructs a field with the given key and value. func Uint(key string, value uint) Field { return Field{Key: key, IValue: int64(value), Kind: KIND_TYPE_UINT} } // Uint8 constructs a field with the given key and value. func Uint8(key string, value uint8) Field { return Field{Key: key, IValue: int64(value), Kind: KIND_TYPE_UINT_8} } // Uint16 constructs a field with the given key and value. func Uint16(key string, value uint16) Field { return Field{Key: key, IValue: int64(value), Kind: KIND_TYPE_UINT_16} } // Uint32 constructs a field with the given key and value. func Uint32(key string, value uint32) Field { return Field{Key: key, IValue: int64(value), Kind: KIND_TYPE_UINT_32} } // Uint64 constructs a field with the given key and value. func Uint64(key string, value uint64) Field { return Field{Key: key, IValue: int64(value), Kind: KIND_TYPE_UINT_64} } // Uintptr constructs a field with the given key and value. func Uintptr(key string, value uintptr) Field { return Field{Key: key, IValue: int64(value), Kind: KIND_TYPE_UINTPTR} } // Float32 constructs a field with the given key and value. func Float32(key string, value float32) Field { return Field{Key: key, IValue: int64(math.Float32bits(value)), Kind: KIND_TYPE_FLOAT_32} } // Float64 constructs a field with the given key and value. func Float64(key string, value float64) Field { return Field{Key: key, IValue: int64(math.Float64bits(value)), Kind: KIND_TYPE_FLOAT_64} } // Complex64 constructs a field with the given key and value. func Complex64(key string, value complex64) Field { return Field{Key: key, Value: value, Kind: KIND_TYPE_COMPLEX_64} } // Complex128 constructs a field with the given key and value. func Complex128(key string, value complex128) Field { return Field{Key: key, Value: value, Kind: KIND_TYPE_COMPLEX_128} } // String constructs a field with the given key and value. func String(key string, value string) Field { return Field{Key: key, SValue: value, Kind: KIND_TYPE_STRING} } // ------------------------- POINTER CASES GENERATORS ------------------------- // // ---------------------------------------------------------------------------- // // Boolp constructs a field that carries a *bool. The returned Field will safely // and explicitly represent `nil` when appropriate. func Boolp(key string, value *bool) Field { if value == nil { return NilValue(key, KIND_TYPE_BOOL) } return Bool(key, *value) } // Intp constructs a field that carries a *int. The returned Field will safely // and explicitly represent `nil` when appropriate. func Intp(key string, value *int) Field { if value == nil { return NilValue(key, KIND_TYPE_INT) } return Int(key, *value) } // Int8p constructs a field that carries a *int8. The returned Field will safely // and explicitly represent `nil` when appropriate. func Int8p(key string, value *int8) Field { if value == nil { return NilValue(key, KIND_TYPE_INT_8) } return Int8(key, *value) } // Int16p constructs a field that carries a *int16. The returned Field will safely // and explicitly represent `nil` when appropriate. func Int16p(key string, value *int16) Field { if value == nil { return NilValue(key, KIND_TYPE_INT_16) } return Int16(key, *value) } // Int32p constructs a field that carries a *int32. The returned Field will safely // and explicitly represent `nil` when appropriate. func Int32p(key string, value *int32) Field { if value == nil { return NilValue(key, KIND_TYPE_INT_32) } return Int32(key, *value) } // Int64p constructs a field that carries a *int64. The returned Field will safely // and explicitly represent `nil` when appropriate. func Int64p(key string, value *int64) Field { if value == nil { return NilValue(key, KIND_TYPE_INT_64) } return Int64(key, *value) } // Uintp constructs a field that carries a *uint. The returned Field will safely // and explicitly represent `nil` when appropriate. func Uintp(key string, value *uint) Field { if value == nil { return NilValue(key, KIND_TYPE_UINT) } return Uint(key, *value) } // Uint8p constructs a field that carries a *uint8. The returned Field will safely // and explicitly represent `nil` when appropriate. func Uint8p(key string, value *uint8) Field { if value == nil { return NilValue(key, KIND_TYPE_UINT_8) } return Uint8(key, *value) } // Uint16p constructs a field that carries a *uint16. The returned Field will safely // and explicitly represent `nil` when appropriate. func Uint16p(key string, value *uint16) Field { if value == nil { return NilValue(key, KIND_TYPE_UINT_16) } return Uint16(key, *value) } // Uint32p constructs a field that carries a *uint32. The returned Field will safely // and explicitly represent `nil` when appropriate. func Uint32p(key string, value *uint32) Field { if value == nil { return NilValue(key, KIND_TYPE_UINT_32) } return Uint32(key, *value) } // Uint64p constructs a field that carries a *uint64. The returned Field will safely // and explicitly represent `nil` when appropriate. func Uint64p(key string, value *uint64) Field { if value == nil { return NilValue(key, KIND_TYPE_UINT_64) } return Uint64(key, *value) } // Float32p constructs a field that carries a *float32. The returned Field will safely // and explicitly represent `nil` when appropriate. func Float32p(key string, value *float32) Field { if value == nil { return NilValue(key, KIND_TYPE_FLOAT_32) } return Float32(key, *value) } // Float64p constructs a field that carries a *float64. The returned Field will safely // and explicitly represent `nil` when appropriate. func Float64p(key string, value *float64) Field { if value == nil { return NilValue(key, KIND_TYPE_FLOAT_64) } return Float64(key, *value) } // ------------------------ COMPLEX CASES GENERATORS -------------------------- // // ---------------------------------------------------------------------------- // // Type constructs a field that holds on value's type as string. func Type(key string, value interface{}) Field { if value == nil { return String(key, "<nil>") } return String(key, reflect2.TypeOf(value).String()) // SIGSEGV if value == nil } // Stringer constructs a field that holds on string generated by fmt.Stringer.String(). // The returned Field will safely and explicitly represent `nil` when appropriate. func Stringer(key string, value fmt.Stringer) Field { if value == nil { return NilValue(key, KIND_TYPE_STRING) } return Field{Key: key, SValue: value.String(), Kind: KIND_TYPE_STRING} } // Addr constructs a field that carries an any addr as is. E.g. If you want to print // exactly addr of some var instead of its dereferenced value use this generator. // // All other generators that takes any pointer finally prints a value, // addr points to. This func used to print exactly addr. Nil-safe. func Addr(key string, value interface{}) Field { if value != nil { addr := ekaclike.TakeRealAddr(value) return Field{Key: key, IValue: int64(uintptr(addr)), Kind: KIND_TYPE_ADDR} } else { return Field{Key: key, Kind: KIND_TYPE_ADDR} } } // Time constructs a field with the given time.Time and its key. func Time(key string, t time.Time) Field { return String(key, t.Format("2006-01-02 15:04:05 -0700 MST")) } // Duration constructs a field with given time.Duration and its key. func Duration(key string, d time.Duration) Field { return String(key, d.String()) } // ---------------------- INTERNAL AUXILIARY FUNCTIONS ------------------------ // // ---------------------------------------------------------------------------- // // NilValue creates a special field that indicates its store a nil value // (nil pointer) to some baseType. func NilValue(key string, baseType Kind) Field { return Field{Key: key, Kind: baseType | KIND_FLAG_NULL} }
package test import ( "fmt" "net/http" "net/http/httptest" "testing" "time" "github.com/gofiber/fiber" "dwc.com/lumiere/account" "dwc.com/lumiere/account/model" ) func RunBalanceTest(endpoint string, authedAccount interface{}) *http.Response { // Test fiber routing logic with // https://docs.gofiber.io/app#test // Create request req := httptest.NewRequest("GET", fmt.Sprintf("http://localhost:5000/%s", endpoint), nil) // Setup Test router app := fiber.New() app. Use(func(c *fiber.Ctx) { c.Locals("AuthedAccount", authedAccount) c.Next() }). Get("/b", account.AccountBalanceRoute{}.GetBalance). Get("/t", account.AccountBalanceRoute{}.GetTransactions) // Run Test resp, _ := app.Test(req) return resp } func CreateDummyAccountDate() *model.Account { return &model.Account{ ID: "test", Name: "test", Credential: "tst", Transactions: []model.Transaction{ model.Transaction{ Amount: 1, To: "test", From: "system", Date: time.Now().Format("2006.01.02 15:04:05"), }, model.Transaction{ Amount: 1, To: "test", From: "system", Date: time.Now().Format("2006.01.02 15:04:05"), }, }, } } func Test_AccountBalanceCanBeReturned(t *testing.T) { account := CreateDummyAccountDate() resp := RunBalanceTest("b", account) if resp.StatusCode != http.StatusOK { t.Error("Expected status 200") } } func Test_AccountBalanceAuthUserFailure(t *testing.T) { resp := RunBalanceTest("b", nil) if resp.StatusCode != http.StatusInternalServerError { t.Error("Expected status 500") } } func Test_AccountTransactionsCanBeReturned(t *testing.T) { account := CreateDummyAccountDate() resp := RunBalanceTest("t", account) if resp.StatusCode != http.StatusOK { t.Error("Expected status 200") } } func Test_AccountTransactionsAuthUserFailure(t *testing.T) { resp := RunBalanceTest("t", nil) if resp.StatusCode != http.StatusInternalServerError { t.Error("Expected status 500") } }
package yeahmobi import ( "encoding/json" "fmt" "net/http" "net/url" "text/template" "github.com/prebid/openrtb/v19/openrtb2" "github.com/prebid/prebid-server/adapters" "github.com/prebid/prebid-server/config" "github.com/prebid/prebid-server/errortypes" "github.com/prebid/prebid-server/macros" "github.com/prebid/prebid-server/openrtb_ext" ) type YeahmobiAdapter struct { EndpointTemplate *template.Template } // Builder builds a new instance of the Yeahmobi adapter for the given bidder with the given config. func Builder(bidderName openrtb_ext.BidderName, config config.Adapter, server config.Server) (adapters.Bidder, error) { template, err := template.New("endpointTemplate").Parse(config.Endpoint) if err != nil { return nil, fmt.Errorf("unable to parse endpoint url template: %v", err) } bidder := &YeahmobiAdapter{ EndpointTemplate: template, } return bidder, nil } func (adapter *YeahmobiAdapter) MakeRequests(request *openrtb2.BidRequest, reqInfo *adapters.ExtraRequestInfo) ([]*adapters.RequestData, []error) { var adapterRequests []*adapters.RequestData adapterRequest, errs := adapter.makeRequest(request) if errs == nil { adapterRequests = append(adapterRequests, adapterRequest) } return adapterRequests, errs } func (adapter *YeahmobiAdapter) makeRequest(request *openrtb2.BidRequest) (*adapters.RequestData, []error) { var errs []error yeahmobiExt, errs := getYeahmobiExt(request) if yeahmobiExt == nil { return nil, errs } endPoint, err := adapter.getEndpoint(yeahmobiExt) if err != nil { return nil, append(errs, err) } transform(request) reqBody, err := json.Marshal(request) if err != nil { return nil, append(errs, err) } headers := http.Header{} headers.Add("Content-Type", "application/json;charset=utf-8") return &adapters.RequestData{ Method: "POST", Uri: endPoint, Body: reqBody, Headers: headers, }, errs } func transform(request *openrtb2.BidRequest) { for i, imp := range request.Imp { if imp.Native != nil { var nativeRequest map[string]interface{} nativeCopyRequest := make(map[string]interface{}) err := json.Unmarshal([]byte(request.Imp[i].Native.Request), &nativeRequest) //just ignore the bad native request if err == nil { _, exists := nativeRequest["native"] if exists { continue } nativeCopyRequest["native"] = nativeRequest nativeReqByte, err := json.Marshal(nativeCopyRequest) //just ignore the bad native request if err != nil { continue } nativeCopy := *request.Imp[i].Native nativeCopy.Request = string(nativeReqByte) request.Imp[i].Native = &nativeCopy } } } } func getYeahmobiExt(request *openrtb2.BidRequest) (*openrtb_ext.ExtImpYeahmobi, []error) { var extImpYeahmobi openrtb_ext.ExtImpYeahmobi var errs []error for _, imp := range request.Imp { var extBidder adapters.ExtImpBidder err := json.Unmarshal(imp.Ext, &extBidder) if err != nil { errs = append(errs, err) continue } err = json.Unmarshal(extBidder.Bidder, &extImpYeahmobi) if err != nil { errs = append(errs, err) continue } break } return &extImpYeahmobi, errs } func (adapter *YeahmobiAdapter) getEndpoint(ext *openrtb_ext.ExtImpYeahmobi) (string, error) { return macros.ResolveMacros(adapter.EndpointTemplate, macros.EndpointTemplateParams{Host: "gw-" + url.QueryEscape(ext.ZoneId) + "-bid.yeahtargeter.com"}) } // MakeBids make the bids for the bid response. func (a *YeahmobiAdapter) MakeBids(internalRequest *openrtb2.BidRequest, externalRequest *adapters.RequestData, response *adapters.ResponseData) (*adapters.BidderResponse, []error) { if response.StatusCode == http.StatusNoContent { return nil, nil } if response.StatusCode == http.StatusBadRequest { return nil, []error{&errortypes.BadInput{ Message: fmt.Sprintf("Unexpected status code: %d.", response.StatusCode), }} } if response.StatusCode != http.StatusOK { return nil, []error{&errortypes.BadServerResponse{ Message: fmt.Sprintf("Unexpected status code: %d.", response.StatusCode), }} } var bidResp openrtb2.BidResponse if err := json.Unmarshal(response.Body, &bidResp); err != nil { return nil, []error{err} } bidResponse := adapters.NewBidderResponseWithBidsCapacity(1) for _, sb := range bidResp.SeatBid { for i := range sb.Bid { var mediaType = getBidType(sb.Bid[i].ImpID, internalRequest.Imp) bidResponse.Bids = append(bidResponse.Bids, &adapters.TypedBid{ Bid: &sb.Bid[i], BidType: mediaType, }) } } return bidResponse, nil } func getBidType(impId string, imps []openrtb2.Imp) openrtb_ext.BidType { bidType := openrtb_ext.BidTypeBanner for _, imp := range imps { if imp.ID == impId { if imp.Banner != nil { break } if imp.Video != nil { bidType = openrtb_ext.BidTypeVideo break } if imp.Native != nil { bidType = openrtb_ext.BidTypeNative break } } } return bidType }
package incus import ( "fmt" "os" "github.com/spf13/viper" ) func NewConfig(configFilePath string) { viper.SetConfigName("config") viper.AddConfigPath(configFilePath) err := viper.ReadInConfig() if err != nil { panic(fmt.Errorf("Fatal error config file: %s \n", err)) } ConfigOption("client_broadcasts", true) ConfigOption("listening_port", "4000") ConfigOption("connection_timeout", 60000) ConfigOption("log_level", "debug") ConfigOption("datadog_enabled", false) if viper.GetBool("datadog_enabled") { ConfigOption("datadog_host", "127.0.0.1") } ConfigOption("longpoll_killswitch", "longpoll_killswitch") ConfigOption("redis_enabled", false) if viper.GetBool("redis_enabled") { ConfigOption("redis_port_6379_tcp_addr", "127.0.0.1") ConfigOption("redis_port_6379_tcp_port", 6379) ConfigOption("redis_message_channel", "Incus") ConfigOption("redis_message_queue", "Incus_Queue") ConfigOption("redis_activity_consumers", 8) ConfigOption("redis_connection_pool_size", 20) ConfigOption("redis_blpop_timeout", 0) } ConfigOption("tls_enabled", false) if viper.GetBool("tls_enabled") { ConfigOption("tls_port", "443") fileOption(ConfigOption("cert_file", "cert.pem")) fileOption(ConfigOption("key_file", "key.pem")) } ConfigOption("apns_enabled", false) if viper.GetBool("apns_enabled") { fileOption(ConfigOption("apns_store_cert", "myapnsappcert.pem")) fileOption(ConfigOption("apns_store_private_key", "myapnsappprivatekey.pem")) fileOption(ConfigOption("apns_enterprise_cert", "myapnsappcert.pem")) fileOption(ConfigOption("apns_enterprise_private_key", "myapnsappprivatekey.pem")) fileOption(ConfigOption("apns_beta_cert", "myapnsappcert.pem")) fileOption(ConfigOption("apns_beta_private_key", "myapnsappprivatekey.pem")) fileOption(ConfigOption("apns_development_cert", "myapnsappcert.pem")) fileOption(ConfigOption("apns_development_private_key", "myapnsappprivatekey.pem")) ConfigOption("apns_store_url", "gateway.push.apple.com:2195") ConfigOption("apns_enterprise_url", "gateway.push.apple.com:2195") ConfigOption("apns_beta_url", "gateway.push.apple.com:2195") ConfigOption("apns_development_url", "gateway.sandbox.push.apple.com:2195") ConfigOption("apns_production_url", "gateway.push.apple.com:2195") ConfigOption("apns_sandbox_url", "gateway.sandbox.push.apple.com:2195") ConfigOption("ios_push_sound", "bingbong.aiff") } ConfigOption("gcm_enabled", false) if viper.GetBool("gcm_enabled") { ConfigOption("gcm_api_key", "foobar") ConfigOption("android_error_queue", "Incus_Android_Error_Queue") } } func ConfigOption(key string, default_value interface{}) string { viper.SetDefault(key, default_value) return key } // Asserts that the chosen value exists on the local file system by panicking if it doesn't func fileOption(key string) { chosenValue := viper.GetString(key) if _, err := os.Stat(chosenValue); err != nil { panic(fmt.Errorf("Chosen option %s does not exist!", chosenValue)) } }
package storageos import ( "context" "errors" "fmt" "net/http" "net/url" "strings" "time" api "github.com/storageos/go-api/v2" ) //go:generate mockgen -build_flags=--mod=vendor -destination=mocks/mock_control_plane.go -package=mocks github.com/storageos/cluster-operator/internal/pkg/storageos ControlPlane // ControlPlane is the subset of the StorageOS control plane ControlPlane that // the operator requires. New methods should be added here as needed, then the // mocks regenerated. type ControlPlane interface { RefreshJwt(ctx context.Context) (api.UserSession, *http.Response, error) AuthenticateUser(ctx context.Context, authUserData api.AuthUserData) (api.UserSession, *http.Response, error) GetCluster(ctx context.Context) (api.Cluster, *http.Response, error) UpdateCluster(ctx context.Context, updateClusterData api.UpdateClusterData, localVarOptionals *api.UpdateClusterOpts) (api.Cluster, *http.Response, error) } // Client provides access to the StorageOS API. type Client struct { api ControlPlane ctx context.Context } const ( // DefaultPort is the default api port. DefaultPort = 5705 // DefaultScheme is used for api endpoint. DefaultScheme = "http" ) var ( // ErrNoAuthToken is returned when the API client did not get an error // during authentication but no valid auth token was returned. ErrNoAuthToken = errors.New("no token found in auth response") // HTTPTimeout is the time limit for requests made by the API Client. The // timeout includes connection time, any redirects, and reading the response // body. The timer remains running after Get, Head, Post, or Do return and // will interrupt reading of the Response.Body. HTTPTimeout = 10 * time.Second // AuthenticationTimeout is the time limit for authentication requests to // complete. It should be longer than the HTTPTimeout. AuthenticationTimeout = 20 * time.Second ) // Mocked returns a client that uses the provided ControlPlane api client. // Intended for tests that use a mocked StorageOS api. This avoids having to // publically expose the api on the Client struct. func Mocked(api ControlPlane) *Client { return &Client{ api: api, ctx: context.TODO(), } } // New returns an unauthenticated client for the StorageOS API. Authenticate() // must be called before using the client. func New(endpoint string) *Client { config := api.NewConfiguration() if !strings.Contains(endpoint, "://") { endpoint = fmt.Sprintf("%s://%s", DefaultScheme, endpoint) } u, err := url.Parse(endpoint) if err != nil { // This should never happen as we control the endpoint that is passed // in. It allows us to create a client in places that are unable to // handle an error gracefully. panic(err) } config.Scheme = u.Scheme config.Host = u.Host if !strings.Contains(u.Host, ":") { config.Host = fmt.Sprintf("%s:%d", u.Host, DefaultPort) } config.HTTPClient = &http.Client{ Timeout: HTTPTimeout, Transport: http.DefaultTransport, } // Get a wrappered API client. client := api.NewAPIClient(config) return &Client{api: client.DefaultApi, ctx: context.TODO()} } // Authenticate against the API and set the authentication token in the client // to be used for subsequent API requests. The token must be refreshed // periodically using AuthenticateRefresh(), or Authenticate() called again. func (c *Client) Authenticate(username, password string) error { // Create context just for the login. ctx, cancel := context.WithTimeout(context.Background(), AuthenticationTimeout) defer cancel() // Initial basic auth to retrieve the jwt token. _, resp, err := c.api.AuthenticateUser(ctx, api.AuthUserData{ Username: username, Password: password, }) if err != nil { return api.MapAPIError(err, resp) } defer resp.Body.Close() // Set auth token in a new context for re-use. token := respAuthToken(resp) if token == "" { return ErrNoAuthToken } // Update the client with the new token. c.ctx = context.WithValue(context.Background(), api.ContextAccessToken, token) return nil } // AddToken adds the current authentication token to a given context. func (c *Client) AddToken(ctx context.Context) context.Context { return context.WithValue(ctx, api.ContextAccessToken, c.ctx.Value(api.ContextAccessToken)) } // respAuthToken is a helper to pull the auth token out of a HTTP Response. func respAuthToken(resp *http.Response) string { if value := resp.Header.Get("Authorization"); value != "" { // "Bearer aaaabbbbcccdddeeeff" return strings.Split(value, " ")[1] } return "" }
package cosign import ( "crypto" "encoding/json" "errors" "fmt" "github.com/opencontainers/go-digest" oci "github.com/opencontainers/image-spec/specs-go/v1" ) var algorithms = map[crypto.Hash]digest.Algorithm{ crypto.SHA256: digest.SHA256, crypto.SHA384: digest.SHA384, crypto.SHA512: digest.SHA512, } // digest a payload and return it both formatted and raw func digestPayload(hash crypto.Hash, blob []byte) ([]byte, digest.Digest) { alg := algorithms[hash] if !alg.Available() { return nil, "" } digester := hash.New() digester.Write(blob) rawDigest := digester.Sum(nil) layerDigest := digest.NewDigestFromBytes(alg, rawDigest) return rawDigest, layerDigest } // legacy container media types const ( dockerImageType = "application/vnd.docker.distribution.manifest.v2+json" dockerListType = "application/vnd.docker.distribution.manifest.list.v2+json" ) var allowedManifestTypes = map[string]bool{ oci.MediaTypeImageManifest: true, oci.MediaTypeImageIndex: true, dockerImageType: true, dockerListType: true, } type objectWithMediaType struct { MediaType string `json:"mediaType"` } // return the digest and mediaType of a manifest func digestManifest(hash crypto.Hash, blob []byte) (digest.Digest, string, error) { alg := algorithms[hash] if !alg.Available() { return "", "", fmt.Errorf("unsupported digest %s", hash) } var mt objectWithMediaType if err := json.Unmarshal(blob, &mt); err != nil { return "", "", fmt.Errorf("unable to determine mediaType: %w", err) } if mt.MediaType == "" { return "", "", errors.New("unable to determine mediaType") } if !allowedManifestTypes[mt.MediaType] { return "", "", fmt.Errorf("mediaType %q cannot be signed", mt.MediaType) } return alg.FromBytes(blob), mt.MediaType, nil }
package http_api // nolint: golint import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "sync" "testing" "github.com/uniqush/uniqush-push/push" "github.com/uniqush/uniqush-push/srv/apns/common" apns_mocks "github.com/uniqush/uniqush-push/srv/apns/http_api/mocks" ) const ( bundleID = "com.example.test" mockServiceName = "myService" ) var ( pushServiceProvider = initPSP() devToken = []byte("test_device_token") payload = []byte(`{"alert":"test_message"}`) ) func initPSP() *push.PushServiceProvider { psm := push.GetPushServiceManager() psm.RegisterPushServiceType(&apns_mocks.MockPushServiceType{}) psp, err := psm.BuildPushServiceProviderFromMap(map[string]string{ "service": mockServiceName, "pushservicetype": "apns", "cert": "../apns-test/localhost.cert", "key": "../apns-test/localhost.key", "addr": "gateway.push.apple.com:2195", "skipverify": "true", "bundleid": bundleID, }) if err != nil { panic(err) } return psp } // TODO: remove unrelated fields type mockHTTP2Client struct { processorFn func(r *http.Request) (*http.Response, *mockResponse, error) // Mocks for responses given json encoded request, TODO write expectations. // mockResponses map[string]string performed []*mockResponse mutex sync.Mutex } func (c *mockHTTP2Client) Do(request *http.Request) (*http.Response, error) { result, mockResponse, err := c.processorFn(request) c.mutex.Lock() defer c.mutex.Unlock() c.performed = append(c.performed, mockResponse) return result, err } var _ HTTPClient = &mockHTTP2Client{} type mockResponse struct { impl *bytes.Reader closed bool request *http.Request } func (r *mockResponse) Read(p []byte) (n int, err error) { return r.impl.Read(p) } func (r *mockResponse) Close() error { r.closed = true return nil } var _ io.ReadCloser = &mockResponse{} func newMockResponse(contents []byte, request *http.Request) *mockResponse { return &mockResponse{ impl: bytes.NewReader(contents), closed: false, request: request, } } func mockAPNSRequest(requestProcessor *HTTPPushRequestProcessor, fn func(r *http.Request) (*http.Response, *mockResponse, error)) *mockHTTP2Client { mockClient := &mockHTTP2Client{ processorFn: fn, } requestProcessor.clientFactory = func(_ *http.Transport) HTTPClient { return mockClient } return mockClient } func newPushRequest() (*common.PushRequest, chan push.Error, chan *common.APNSResult) { errChan := make(chan push.Error) resChan := make(chan *common.APNSResult, 1) request := &common.PushRequest{ PSP: pushServiceProvider, Devtokens: [][]byte{devToken}, Payload: payload, ErrChan: errChan, ResChan: resChan, } return request, errChan, resChan } func newHTTPRequestProcessor() *HTTPPushRequestProcessor { res := NewRequestProcessor().(*HTTPPushRequestProcessor) // Force tests to override this or crash. res.clientFactory = nil return res } func expectHeaderToHaveValue(t *testing.T, r *http.Request, headerName string, expectedHeaderValue string) { t.Helper() if headerValues := r.Header[headerName]; len(headerValues) > 0 { if len(headerValues) > 1 { t.Errorf("Too many header values for %s header, expected 1 value, got values: %v", headerName, headerValues) } headerValue := headerValues[0] if headerValue != expectedHeaderValue { t.Errorf("Expected header value for %s header to be %s, got %s", headerName, expectedHeaderValue, headerValue) } } else { t.Errorf("Missing %s header", headerName) } } func handleAPNSResultOrEmitTestError(t *testing.T, resChan <-chan *common.APNSResult, errChan <-chan push.Error, resultHandler func(*common.APNSResult)) { select { case res := <-resChan: resultHandler(res) case err := <-errChan: if err != nil { t.Fatalf("Response was unexpectedly an error: %v\n", err) return } res := <-resChan resultHandler(res) } } func TestAddRequestPushSuccessful(t *testing.T) { requestProcessor := newHTTPRequestProcessor() request, errChan, resChan := newPushRequest() mockClient := mockAPNSRequest(requestProcessor, func(r *http.Request) (*http.Response, *mockResponse, error) { if auth, ok := r.Header["Authorization"]; ok { // temporarily disabled t.Errorf("Unexpected Authorization header %v", auth) } expectHeaderToHaveValue(t, r, "apns-expiration", "0") // Specific to fork, would need to mock time or TTL otherwise expectHeaderToHaveValue(t, r, "apns-priority", "10") expectHeaderToHaveValue(t, r, "apns-topic", bundleID) requestBody, err := ioutil.ReadAll(r.Body) if err != nil { t.Error("Error reading request body:", err) } if !bytes.Equal(requestBody, payload) { t.Errorf("Wrong message payload, expected `%v`, got `%v`", payload, requestBody) } // Return empty body body := newMockResponse([]byte{}, r) response := &http.Response{ StatusCode: http.StatusOK, Body: body, } return response, body, nil }) requestProcessor.AddRequest(request) handleAPNSResultOrEmitTestError(t, resChan, errChan, func(res *common.APNSResult) { if res.MsgID == 0 { t.Fatal("Expected non-zero message id, got zero") } }) actualPerformed := len(mockClient.performed) if actualPerformed != 1 { t.Fatalf("Expected 1 request to be performed, but %d were", actualPerformed) } } // Test sending 10 pushes at a time, to catch any obvious race conditions in `go test -race`. func TestAddRequestPushSuccessfulWhenConcurrent(t *testing.T) { requestProcessor := newHTTPRequestProcessor() iterationCount := 10 wg := sync.WaitGroup{} wg.Add(iterationCount) mockClient := mockAPNSRequest(requestProcessor, func(r *http.Request) (*http.Response, *mockResponse, error) { if auth, ok := r.Header["Authorization"]; ok { // temporarily disabled t.Errorf("Unexpected Authorization header %v", auth) } expectHeaderToHaveValue(t, r, "apns-expiration", "0") // Specific to fork, would need to mock time or TTL otherwise expectHeaderToHaveValue(t, r, "apns-priority", "10") expectHeaderToHaveValue(t, r, "apns-topic", bundleID) requestBody, err := ioutil.ReadAll(r.Body) if err != nil { t.Error("Error reading request body:", err) } if !bytes.Equal(requestBody, payload) { t.Errorf("Wrong message payload, expected `%v`, got `%v`", payload, requestBody) } // Return empty body body := newMockResponse([]byte{}, r) response := &http.Response{ StatusCode: http.StatusOK, Body: body, } return response, body, nil }) for i := 0; i < iterationCount; i++ { go func() { request, errChan, resChan := newPushRequest() requestProcessor.AddRequest(request) defer wg.Done() handleAPNSResultOrEmitTestError(t, resChan, errChan, func(res *common.APNSResult) { if res.MsgID == 0 { t.Error("Expected non-zero message id, got zero") } }) }() } wg.Wait() actualPerformed := len(mockClient.performed) if actualPerformed != iterationCount { t.Fatalf("Expected %d requests to be performed, but %d were", iterationCount, actualPerformed) } } func TestAddRequestPushFailConnectionError(t *testing.T) { requestProcessor := newHTTPRequestProcessor() request, errChan, _ := newPushRequest() mockAPNSRequest(requestProcessor, func(r *http.Request) (*http.Response, *mockResponse, error) { return nil, nil, fmt.Errorf("No connection") }) requestProcessor.AddRequest(request) err := <-errChan if _, ok := err.(*push.ConnectionError); !ok { t.Fatal("Expected Connection error, got", err) } } func newMockJSONResponse(r *http.Request, status int, responseData *APNSErrorResponse) (*http.Response, *mockResponse, error) { responseBytes, err := json.Marshal(responseData) if err != nil { panic(fmt.Sprintf("newMockJSONResponse failed: %v", err)) } body := newMockResponse(responseBytes, r) response := &http.Response{ StatusCode: status, Body: body, } return response, body, nil } func TestAddRequestPushFailNotificationError(t *testing.T) { requestProcessor := newHTTPRequestProcessor() request, errChan, resChan := newPushRequest() mockAPNSRequest(requestProcessor, func(r *http.Request) (*http.Response, *mockResponse, error) { response := &APNSErrorResponse{ Reason: "BadDeviceToken", } return newMockJSONResponse(r, http.StatusBadRequest, response) }) requestProcessor.AddRequest(request) handleAPNSResultOrEmitTestError(t, resChan, errChan, func(res *common.APNSResult) { if res.Status != common.Status8Unsubscribe { t.Fatalf("Expected 8 (unsubscribe), got %d", res.Status) } if res.MsgID == 0 { t.Fatal("Expected non-zero message id, got zero") } }) } // TODO: Add test of decoding error response with timestamp func TestGetMaxPayloadSize(t *testing.T) { maxPayloadSize := NewRequestProcessor().GetMaxPayloadSize() if maxPayloadSize != 4096 { t.Fatalf("Wrong max payload, expected `4096`, got `%d`", maxPayloadSize) } }
package main import ( "fmt" ) type Livro struct { titulo string preco float64 numeroPaginas int } func (l *Livro) Digitar(){ fmt.Print("Entre com o Titulo: ") fmt.Scanf("%s", &l.titulo) fmt.Print("Entre com o Preço: ") fmt.Scanf("%f", &l.preco) fmt.Print("Entre com o Numero de Páginas: ") fmt.Scanf("%d", &l.numeroPaginas) } func (l Livro) Mostrar(){ fmt.Printf("Titulo: %v ",l.titulo) fmt.Printf(" Preço: %v ",l.preco) fmt.Printf(" Numero de Páginas: %v ",l.numeroPaginas) } func main(){ defer fmt.Print("\n\t FIM DA EXECUÇÃO") var rotate string livro1 := Livro{} livro1.Digitar() if livro1.numeroPaginas >= 100 { fmt.Printf("Eita quantas Páginas \n") } for _, c := range livro1.titulo { rotate = string(c) + rotate } fmt.Printf("Seu titulo ao contrário é %s \n",rotate) livro1.Mostrar() }
func inorderTraversal(root *TreeNode) []int { arr := make([]int, 0) helper(root, &arr) return arr } func helper(root *TreeNode, arr *[]int) { if root != nil { helper(root.Left, arr) (*arr) = append((*arr), root.Val) helper(root.Right, arr) } }
package requests import ( "net/url" "github.com/atomicjolt/canvasapi" ) // ListEnvironmentFeatures Return a hash of global feature settings that pertain to the // Canvas user interface. This is the same information supplied to the // web interface as +ENV.FEATURES+. // https://canvas.instructure.com/doc/api/feature_flags.html // type ListEnvironmentFeatures struct { } func (t *ListEnvironmentFeatures) GetMethod() string { return "GET" } func (t *ListEnvironmentFeatures) GetURLPath() string { return "" } func (t *ListEnvironmentFeatures) GetQuery() (string, error) { return "", nil } func (t *ListEnvironmentFeatures) GetBody() (url.Values, error) { return nil, nil } func (t *ListEnvironmentFeatures) GetJSON() ([]byte, error) { return nil, nil } func (t *ListEnvironmentFeatures) HasErrors() error { return nil } func (t *ListEnvironmentFeatures) Do(c *canvasapi.Canvas) error { _, err := c.SendRequest(t) if err != nil { return err } return nil }
package agent import ( "context" "github.com/adevinta/vulcan-agent/check" "github.com/adevinta/vulcan-agent/config" "github.com/sirupsen/logrus" ) // Constants defining environment variables that a check expects. const ( CheckIDVar = "VULCAN_CHECK_ID" ChecktypeNameVar = "VULCAN_CHECKTYPE_NAME" ChecktypeVersionVar = "VULCAN_CHECKTYPE_VERSION" CheckTargetVar = "VULCAN_CHECK_TARGET" CheckOptionsVar = "VULCAN_CHECK_OPTIONS" CheckLogLevelVar = "VULCAN_CHECK_LOG_LVL" AgentAddressVar = "VULCAN_AGENT_ADDRESS" ) // Constants defining the possible statuses for an Agent. const ( StatusNew = "NEW" StatusRegistering = "REGISTERING" StatusRegistered = "REGISTERED" StatusRunning = "RUNNING" StatusPausing = "PAUSING" StatusPaused = "PAUSED" StatusDisconnected = "DISCONNECTED" StatusPurging = "PURGING" StatusDown = "DOWN" ) // The Agent interface defines the methods any Agent should expose. // An Agent represents a runtime that is able to run checks as Docker containers. // Example of an Agent could be a Docker host or a Kubernetes or Mesos cluster. // NOTE: This interface assumes that communication between the agent and the jobs is possible. // Since this will not always be possible outside of a local Docker host, this may change in the future. type Agent interface { // ID returns the ID assigned to the Agent when created. ID() string // Status returns the current status of the Agent. Status() string // SetStatus sets the current status of the Agent. SetStatus(status string) // Run a job in the agent's runtime and return any error encountered. Run(checkID string) error // Kill a job and return any error encountered. // NOTE: Kill stops the check by killing the container. Kill(checkID string) error // Abort a job and return any error encountered. // NOTE: Abort stops the check by sending it a SIGTERM. Abort(checkID string) error // AbortChecks abort all the running jobs that belong to a given scan. AbortChecks(scanID string) error // Raw returns the raw output of a check container. Raw(checkID string) ([]byte, error) } type AgentFactory func(ctx context.Context, cancel context.CancelFunc, id string, storage check.Storage, l *logrus.Entry, cfg config.Config) (Agent, error)
// Copyright © 2019 Kerem Karatal // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cmd import ( "fmt" challenge "github.com/keremk/challenge/lib" "github.com/spf13/cobra" ) // createCmd represents the create command var createCmd = &cobra.Command{ Use: "create", Short: "Creates a coding challenge for a candidate", Long: `This command creates a coding challenge for a candidate in the configured repository. You need to supply the github name of the candidate and the discipline of the coding challenge to be created. Discipline needs to match one that is in the configuration file. This command also creates the first task, adds the coding challenge as an issue in the tracking repository and invites the candidate the coding challenge.`, Run: func(cmd *cobra.Command, args []string) { user, _ := cmd.Flags().GetString("user") if user == "" { user = "no user specified" } discipline, _ := cmd.Flags().GetString("discipline") if discipline == "" { discipline = "no discipline specified" } fmt.Println("create called for", user, discipline) challenge.CreateChallenge(user, discipline) }, } func init() { rootCmd.AddCommand(createCmd) createCmd.Flags().StringP("user", "u", "", "Provide Github user name for the candidate") createCmd.Flags().StringP("discipline", "d", "", "Provide the discipline (e.g. ios, android, backend ...) for the challenge") }
package models import "go.mongodb.org/mongo-driver/mongo" // 采购订单实例(供应商订单实例) // 采购订单子订单 type SupplierSubOrder struct { SubOrderId int64 `json:"order_sub_id" bson:"order_sub_id"` // 子订单id SubOrderSn string `json:"order_sub_sn" bson:"order_sub_sn"` // 子订单号 ComID int64 `json:"com_id" bson:"com_id"` // 公司id OrderId int64 `json:"order_id" bson:"order_id"` // 采购订单id OrderSn string `json:"order_sn" bson:"order_sn"` // 订单号 ProductID int64 `json:"product_id" bson:"product_id"` // 商品id ProductName string `json:"product_name" bson:"product_name"` // 商品名 这是冗余字段 ProductNum int64 `json:"product_num" bson:"product_num"` // 商品数量 ProductUnitPrice float64 `json:"product_unit_price" bson:"product_unit_price"` // 商品单价 Units string `json:"units" bson:"units"` // 商品量词,这是冗余字段 CreateAt int64 `json:"create_at" bson:"create_at"` // 创建时间戳 CreateBy int64 `json:"create_by" bson:"create_by"` // 创建者id ShipTime int64 `json:"ship_time" bson:"ship_time"` // 发货时间戳 Shipper int64 `json:"shipper" bson:"shipper"` // 发货者id ConfirmAt int64 `json:"confirm_at" bson:"confirm_at"` // 确认收货时间戳 ConfirmBy int64 `json:"confirm_by" bson:"confirm_by"` // 确认收货者id CheckAt int64 `json:"check_at" bson:"check_at"` // 盘点时间 CheckBy int64 `json:"check_by" bson:"check_by"` // 盘点操作者id State int64 `json:"state" bson:"state"` // 订单状态 ActualAmount int64 `json:"actual_amount" bson:"actual_amount"` // 实发数量 FailReason string `json:"fail_reason" bson:"fail_reason"` // 审核不通过的理由 } func getSupplierSubOrderCollection() *mongo.Collection { return Client.Collection("supplier_sub_order") }
package tiltfile import ( "context" "github.com/tilt-dev/tilt/internal/store" "github.com/tilt-dev/tilt/pkg/model" "github.com/tilt-dev/tilt/pkg/model/logstore" ) // BuildEntry is vestigial, but currently used to help manage state about a tiltfile build. type BuildEntry struct { Name model.ManifestName FilesChanged []string BuildReason model.BuildReason Args []string TiltfilePath string CheckpointAtExecStart logstore.Checkpoint LoadCount int ArgsChanged bool } func (be *BuildEntry) WithLogger(ctx context.Context, st store.RStore) context.Context { return store.WithManifestLogHandler(ctx, st, be.Name, SpanIDForLoadCount(be.Name, be.LoadCount)) }
package request import ( "bytes" "context" "io" "net/http" "sync" "time" "github.com/webnice/transport/v3/header" "github.com/webnice/transport/v3/methods" "github.com/webnice/transport/v3/response" ) // Pool is an interface of package type Pool interface { // RequestGet Извлечение из pool нового элемента Request RequestGet() Interface // RequestPut Возврат в sync.Pool использованного элемента Request RequestPut(req Interface) } // Interface is an request interface type Interface interface { // Cancel Aborting request Cancel() Interface // Done Waiting for the request to finish Done() Interface // DoneWithContext Waiting for a request to complete, with the ability to interrupt the request through the context DoneWithContext(ctx context.Context) Interface // Error Return latest error Error() error // DebugFunc Set debug func and enable or disable debug mode // If fn=not nil - debug mode is enabled. If fn=nil, debug mode is disbled DebugFunc(fn DebugFunc) Interface // Request Returns the http.Request prepared for the request Request() (*http.Request, error) // Method Set request method Method(methods.Value) Interface // URL Set request URL URL(url string) Interface // Referer Setting the referer header Referer(referer string) Interface // UserAgent Setting the UserAgent Request Header UserAgent(userAgent string) Interface // ContentType Setting the Content-Type request header ContentType(contentType string) Interface // Accept Setting the Accept request header Accept(accept string) Interface // AcceptEncoding Setting the Accept-Encoding request header AcceptEncoding(acceptEncoding string) Interface // AcceptLanguage Setting the Accept-Language request header AcceptLanguage(acceptLanguage string) Interface // Settings the Accept-Charset request header AcceptCharset(acceptCharset string) Interface // Settings custom request header CustomHeader(name string, value string) Interface // BasicAuth Set login and password for request basic authorization BasicAuth(username string, password string) Interface // Cookies Adding cookies to the request Cookies(cookies []*http.Cookie) Interface // Header is an interface for custom headers manipulation Header() header.Interface // Latency is an request latency without reading body of response Latency() time.Duration // Response is an response interface Response() response.Interface // DATA OF THE REQUEST // DataStream Data for the request body in the form of an interface of io.Reader DataStream(data io.Reader) Interface // DataString Data for the request body in the form of an string DataString(data string) Interface // DataString Data for the request body in the form of an []byte DataBytes(data []byte) Interface // DataJSON The data for the query is created by serializing the object in JSON DataJSON(data interface{}) Interface // DataXML The data for the query is created by serializing the object in XML DataXML(data interface{}) Interface // EXECUTING // Do Executing the query and getting the result Do(client *http.Client) error } // impl is an implementation of package type impl struct { methods methods.Interface // Интерфейс методов запроса requestPool *sync.Pool // Пул объектов Request responsePool response.Pool // Интерфейс пула объектов Response } // DebugFunc Is an a function for debug request/response data type DebugFunc func(data []byte) // Request is an Request implementation type Request struct { context context.Context // Context interface contextCancelFunc context.CancelFunc // Context CancelFunc method methods.Value // Метод запроса данных header header.Interface // Заголовки запроса err error // Latest error debugFunc DebugFunc // Is an a function for debug request/response data. If not nil - debug mode is enabled. If nil, debug mode is disbled url *bytes.Buffer // Запрашиваемый URL без данных request *http.Request // Объект net/http.Request requestData *bytes.Reader // Данные запроса requestDataInterface io.Reader // Интерфейс данных запроса username string // Имя пользователя авторизации, если указан, то передаются заголовки авторизации password string // Пароль авторизации cookie []*http.Cookie // Печеньги запроса timeBegin time.Time // Дата и время начала запроса timeLatency time.Duration // Время ушедшее за выполнение запроса response response.Interface // Интерфейс результата запроса tmpArr []string // Variable tmpOk bool // Variable tmpCounter int // Variable tmpBytes []byte // Variable }
package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( strfmt "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" "github.com/go-openapi/errors" "github.com/go-openapi/validate" ) /*Service service swagger:model Service */ type Service struct { /* name Required: true */ Name *string `json:"name"` /* Parameters defined for the service */ Parameters []*ParameterDefinition `json:"parameters,omitempty"` /* version Required: true */ Version *string `json:"version"` } // Validate validates this service func (m *Service) Validate(formats strfmt.Registry) error { var res []error if err := m.validateName(formats); err != nil { // prop res = append(res, err) } if err := m.validateParameters(formats); err != nil { // prop res = append(res, err) } if err := m.validateVersion(formats); err != nil { // prop res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *Service) validateName(formats strfmt.Registry) error { if err := validate.Required("name", "body", m.Name); err != nil { return err } return nil } func (m *Service) validateParameters(formats strfmt.Registry) error { if swag.IsZero(m.Parameters) { // not required return nil } for i := 0; i < len(m.Parameters); i++ { if swag.IsZero(m.Parameters[i]) { // not required continue } if m.Parameters[i] != nil { if err := m.Parameters[i].Validate(formats); err != nil { return err } } } return nil } func (m *Service) validateVersion(formats strfmt.Registry) error { if err := validate.Required("version", "body", m.Version); err != nil { return err } return nil }
package ether_scan import ( "errors" "fmt" "github.com/eager7/elog" "github.com/BlockABC/eth-tokens/script/built" "github.com/BlockABC/eth-tokens/script/erc20" "github.com/ethereum/go-ethereum/ethclient" "time" ) var log = elog.NewLogger("spider", elog.DebugLevel) type Spider struct { url string client *ethclient.Client } func Initialize(url string) (*Spider, error) { //"http://47.52.157.31:8585" client, err := ethclient.Dial(url) if err != nil { return nil, errors.New(fmt.Sprintf("initialize eth client err:%v", err)) } return &Spider{url: url, client: client}, nil } func (s *Spider) BuiltTokensFromEtherScan() ([]built.TokenInfo, error) { var tokens []built.TokenInfo for i := 1; i <= pageMax; i++ { retry: log.Debug("get the token from ether scan:", i) ts, err := RequestTokenListByPage(urlErc20EtherScan + fmt.Sprintf("%d", i)) if err != nil { log.Error("RequestTokenListByPage error:", err) goto retry } tokens = append(tokens, ts...) time.Sleep(time.Millisecond * 500) } log.Debug("get tokens from ether scan:", len(tokens)) for i, token := range tokens { times := 0 read: name, symbol, decimals, _, err := erc20.ReadTokenInfo(token.Address, s.client, s.url) if err != nil { times++ log.Error("read token info err:", token.Address, err) if times <= 3 { goto read } continue } if name != "" { tokens[i].Name = name } if symbol != "" { tokens[i].Symbol = symbol } tokens[i].Type = "ERC20" tokens[i].Decimals = int(decimals) log.Debug("get token:", tokens[i].Name, tokens[i].Symbol, tokens[i].Decimals, tokens[i].Type, token.Address) } return tokens, nil } func (s *Spider) BuiltNftFromEtherScan() ([]built.TokenInfo, error) { var tokens []built.TokenInfo for i := 1; i <= 1; i++ { retry: log.Debug("get the token from ether scan:", i) ts, err := RequestTokenListByPage(urlNftEtherScan + fmt.Sprintf("%d", i)) if err != nil { log.Error("RequestTokenListByPage error:", err) goto retry } tokens = append(tokens, ts...) time.Sleep(time.Millisecond * 500) } log.Debug("get tokens from ether scan:", len(tokens)) for i, token := range tokens { name, symbol, _, _, err := erc20.ReadTokenInfo(token.Address, s.client, s.url) if err != nil { log.Error("read token info err:", token.Address, err) continue } if name != "" { tokens[i].Name = name } if symbol != "" { tokens[i].Symbol = symbol } tokens[i].Decimals = 1 tokens[i].Type = "ERC721" log.Debug("get token:", tokens[i].Name, tokens[i].Symbol, tokens[i].Decimals, tokens[i].Type, token.Address) } return tokens, nil }
package connector import ( "common" "logger" "pockerclient" "roomclient" "rpc" "strconv" ) // conn:请求进入自建房间 func (self *CNServer) EnterCustomRoom(conn rpc.RpcConn, msg rpc.EnterCustomRoomREQ) error { logger.Info("client call EnterCustomRoomREQ begin, gameType:%s", msg.GetGameType()) p, exist := self.getPlayerByConnId(conn.GetId()) if !exist { return nil } p.SetGameType(msg.GetGameType()) p.SetRoomType(msg.GetId()) if msg.GetGameType() == "6" { pockerclient.EnterPockerRoom(p.PlayerBaseInfo, msg.GetGameType(), msg.GetId()) } else { roomclient.EnterRoom(p.PlayerBaseInfo, &msg) } return nil } // conn:请求离开自建房间 func (self *CNServer) LeaveCustomRoom(conn rpc.RpcConn, msg rpc.LeaveCustomRoomREQ) error { logger.Info("client call LeaveCustomRoom begin") // p, exist := self.getPlayerByConnId(conn.GetId()) // if !exist { // return nil // } roomclient.LeaveRoom(&msg) return nil } // conn:请求创建自建房间 func (self *CNServer) CreateCustomRoom(conn rpc.RpcConn, msg rpc.CreateRoomREQ) error { logger.Info("client call CreateCustomRoom begin") p, exist := self.getPlayerByConnId(conn.GetId()) if !exist { return nil } itemAmount := p.GetItemNum(strconv.Itoa(common.CustomRoomCardID)) logger.Info("%s道具数量:%s", common.CustomRoomCardID, itemAmount) roomclient.CreateRoomREQ(p.PlayerBaseInfo, &msg, itemAmount) return nil } // conn:请求进入自建房间 func (self *CNServer) ObtainRoomList(conn rpc.RpcConn, msg rpc.RoomListREQ) error { logger.Info("client call ObtainRoomList begin") p, exist := self.getPlayerByConnId(conn.GetId()) if !exist { return nil } roomclient.RoomListREQ(p.PlayerBaseInfo.GetUid(), &msg) return nil } // conn:请求查找房间 func (self *CNServer) FindRoom(conn rpc.RpcConn, msg rpc.FindRoomREQ) error { logger.Info("client call FindRoom begin") p, exist := self.getPlayerByConnId(conn.GetId()) if !exist { return nil } roomclient.FindRoomREQ(p.PlayerBaseInfo.GetUid(), &msg) return nil } // conn:请求解散房间 func (self *CNServer) JieSanRoom(conn rpc.RpcConn, msg rpc.JieSanRoomREQ) error { logger.Info("client call JieSanRoom begin") p, exist := self.getPlayerByConnId(conn.GetId()) if !exist { return nil } roomclient.JieSanRoomREQ(p.PlayerBaseInfo.GetUid(), &msg) return nil }
package sherlockandarray // https://www.hackerrank.com/challenges/sherlock-and-array // BalancedSums - implements the solution to the problem func BalancedSums(arr []int32) string { left := make([]int32, len(arr)) right := make([]int32, len(arr)) for i := 1; i < len(arr); i++ { left[i] = left[i-1] + arr[i-1] right[len(arr)-1-i] = right[len(arr)-i] + arr[len(arr)-i] } for i := 0; i < len(arr); i++ { if left[i] == right[i] { return "YES" } } return "NO" }
package u8_test import ( "fmt" "time" "github.com/shurcooL/go/u/u8" ) func Example1() { x := u8.AfterSecond(func() { fmt.Println("hi") }) time.Sleep(500 * time.Millisecond) x.Cancel() time.Sleep(1500 * time.Millisecond) // Output: } func Example2() { x := u8.AfterSecond(func() { fmt.Println("hi") }) time.Sleep(2 * time.Second) x.Cancel() // Output: //hi }
package game import ( "math/rand" "github.com/nsf/termbox-go" ) //CFOOD Color of food const CFood = termbox.ColorRed // Food object in game type Food struct { Char rune Pos Vec2i } // Creates a food randomly in bounds func NewFood(width, height int) Food { return Food{ Char: '@', Pos: Vec2i{ X: rand.Intn(width), Y: rand.Intn(height), }, } }
// Copyright (C) 2020 Storj Labs, Inc. // See LICENSE for copying information. package rpccache import ( "sync" "time" "github.com/zeebo/errs" ) // implementation note: the cache has some methods that could // potentially be quadratic in the worst case. specifically // when there are many stale entries in the list of values. // while we could do a single pass filtering stale entries, the // logic is a bit harder to follow and ensure is correct. instead // we have a helper to remove a single entry from a list without // knowing where it came from. since we can possibly call that // to remove every element from a list, it's quadratic in the // maximum size of that list. since this cache is intended to // be used with small key capacities (like 5), the decision was // made to accept that quadratic worst case for the benefit of // having as simple an implementation as possible. // // options // // Options contains the options to configure a cache. type Options struct { // Expiration will remove any values from the Cache after the // value passes. Zero means no expiration. Expiration time.Duration // Capacity is the maximum number of values the Cache can store. // Zero means unlimited. Negative means no values. Capacity int // KeyCapacity is like Capacity except it is per key. Zero means // the Cache holds unlimited for any single key. Negative means // no values for any single key. // // Implementation note: The cache is potentially quadratic in the // size of this parameter, so it is intended for small values, like // 5 or so. KeyCapacity int // Stale is optionally called on values before they are returned // to see if they should be discarded. Nil means no check is made. Stale func(interface{}) bool // Close is optionally called on any value removed from the Cache. Close func(interface{}) error // Unblocked is optional and called on values before they are returned // to see if they are available to be used. Nil means no check is made. Unblocked func(interface{}) bool } func (c Options) close(val interface{}) error { if c.Close == nil { return nil } return c.Close(val) } func (c Options) stale(val interface{}) bool { if c.Stale == nil { return false } return c.Stale(val) } func (c Options) unblocked(val interface{}) bool { if c.Unblocked == nil { return true } return c.Unblocked(val) } // // cache // type entry struct { key interface{} val interface{} exp *time.Timer } // Cache is an expiring, stale-checking LRU of keys to multiple values. type Cache struct { opts Options mu sync.Mutex entries map[interface{}][]*entry order []*entry closed bool } // New constructs a new Cache with the Options. func New(opts Options) *Cache { return &Cache{ opts: opts, entries: make(map[interface{}][]*entry), } } // // helpers // // closeEntry ensures the timer and connection are closed, returning // any errors. func (c *Cache) closeEntry(ent *entry) error { if ent.exp == nil || ent.exp.Stop() { return c.opts.close(ent.val) } return nil } // filterEntry is a helper to remove a specific cache entry from // a slice of entries. func filterEntry(entries []*entry, ent *entry) []*entry { for i := range entries { if entries[i] == ent { copy(entries[i:], entries[i+1:]) return entries[:len(entries)-1] } } return entries } // // filter functions to remove entries // // filterEntryLocked removes the entry from the map, deleting the // map key if necessary. // // It should only be called with the mutex held. func (c *Cache) filterEntryLocked(ent *entry) { entries := c.entries[ent.key] if len(entries) <= 1 { delete(c.entries, ent.key) } else { c.entries[ent.key] = filterEntry(entries, ent) } c.order = filterEntry(c.order, ent) } // filterCacheKey removes any closed or expired conns from the list // of entries for the key, deleting the key from the entries map if // necessary. func (c *Cache) filterCacheKey(key interface{}) { c.mu.Lock() defer c.mu.Unlock() for _, ent := range c.entries[key] { if c.opts.stale(ent.val) { c.filterEntryLocked(ent) } } } // // internal accessors to get entries we care about // // oldestEntryLocked returns the oldest Put entry from the Cache or nil // if one does not exist. func (c *Cache) oldestEntryLocked() *entry { if len(c.order) == 0 { return nil } return c.order[0] } // // exported api // // Close removes every value from the cache and closes it if necessary. func (c *Cache) Close() (err error) { c.mu.Lock() defer c.mu.Unlock() for _, entries := range c.entries { for _, ent := range entries { err = errs.Combine(err, c.closeEntry(ent)) } } c.entries = make(map[interface{}][]*entry) c.order = nil c.closed = true return err } // Take acquires a value from the cache if one exists. It returns // nil if one does not. func (c *Cache) Take(key interface{}) interface{} { c.mu.Lock() defer c.mu.Unlock() entries := c.entries[key] for i := len(entries) - 1; i >= 0; i-- { ent := entries[i] // if the entry is not unblocked, then skip considering it. if !c.opts.unblocked(ent.val) { continue } c.filterEntryLocked(ent) // if we can't stop the timer or the conn is closed, try again. if ent.exp != nil && !ent.exp.Stop() { continue } else if c.opts.stale(ent.val) { // we choose to ignore this error because it is not actionable. _ = c.opts.close(ent.val) continue } return ent.val } return nil } // Put places the connection in to the cache with the provided key. It // returns any errors closing any connections necessary to do the job. func (c *Cache) Put(key, val interface{}) { if c.opts.Capacity < 0 || c.opts.KeyCapacity < 0 || c.opts.stale(val) { _ = c.opts.close(val) return } c.mu.Lock() defer c.mu.Unlock() if c.closed { _ = c.opts.close(val) return } // ensure we have enough capacity in the key for { entries := c.entries[key] if c.opts.KeyCapacity == 0 || len(entries) < c.opts.KeyCapacity { break } ent := entries[0] _ = c.closeEntry(ent) c.filterEntryLocked(ent) } // ensure we have enough overall capacity for { if c.opts.Capacity == 0 || len(c.order) < c.opts.Capacity { break } ent := c.oldestEntryLocked() _ = c.closeEntry(ent) c.filterEntryLocked(ent) } // create and push the new entry into the map and order list ent := &entry{key: key, val: val} c.entries[key] = append(c.entries[key], ent) c.order = append(c.order, ent) // we set expiration last so that the connection is already in // the data structure so we don't have to worry about filterCacheKey // even though it's protected by the mutex. defensive. if c.opts.Expiration > 0 { ent.exp = time.AfterFunc(c.opts.Expiration, func() { _ = c.opts.close(val) c.filterCacheKey(key) }) } }
// // IMediator.go // PureMVC Go Multicore // // Copyright(c) 2019 Saad Shams <saad.shams@puremvc.org> // Your reuse is governed by the Creative Commons Attribution 3.0 License // package interfaces /* The interface definition for a PureMVC Mediator. In PureMVC, IMediator implementors assume these responsibilities: * Implement a common method which returns a list of all INotifications the IMediator has interest in. * Implement a notification callback method. * Implement methods that are called when the IMediator is registered or removed from the View. Additionally, IMediators typically: * Act as an intermediary between one or more view components such as text boxes or list controls, maintaining references and coordinating their behavior. * In Flash-based apps, this is often the place where event listeners are added to view components, and their handlers implemented. * Respond to and generate INotifications, interacting with of the rest of the PureMVC app. When an IMediator is registered with the IView, the IView will call the IMediator's listNotificationInterests method. The IMediator will return an Array of INotification names which it wishes to be notified about. The IView will then create an Observer object encapsulating that IMediator's (handleNotification) method and register it as an Observer for each INotification name returned by listNotificationInterests. */ type IMediator interface { INotifier /* Get the IMediator instance name */ GetMediatorName() string /* Get the IMediator's view component. */ GetViewComponent() interface{} /* Set the IMediator's view component. */ SetViewComponent(viewComponent interface{}) /* List INotification interests. - returns: an Array of the INotification names this IMediator has an interest in. */ ListNotificationInterests() []string /* Handle an INotification. - parameter notification: the INotification to be handled */ HandleNotification(notification INotification) /* Called by the View when the Mediator is registered */ OnRegister() /* Called by the View when the Mediator is removed */ OnRemove() }
// Package grep implements a solution of the exercise titled `Grep'. package grep import ( "bufio" "fmt" "io" "os" "strings" ) func index(slice []string, element string) int { for i, member := range slice { if member == element { return i } } return -1 } // Search does text search like unix grep command. func Search(pattern string, flags, files []string) []string { nFlag := index(flags, "-n") >= 0 lFlag := index(flags, "-l") >= 0 iFlag := index(flags, "-i") >= 0 vFlag := index(flags, "-v") >= 0 xFlag := index(flags, "-x") >= 0 multipleFiles := len(files) > 1 converter := func(input string) string { if iFlag { return strings.ToLower(input) } return input } collator := func(s, substr string) bool { if xFlag { return s == substr } return strings.Contains(s, substr) } inverter := func(p bool) bool { if vFlag { return !p } return p } result := []string{} for _, fileName := range files { if file, err := os.Open(fileName); err == nil { defer file.Close() reader := bufio.NewReaderSize(file, 1024) for lineNum := 1; ; lineNum++ { line, _, err := reader.ReadLine() if err == io.EOF { break } else if err != nil { panic(err) } if inverter(collator(converter(string(line)), converter(pattern))) { if lFlag { if index(result, fileName) == -1 { result = append(result, fileName) } continue } output := string(line) if nFlag { output = fmt.Sprintf("%v:%v", lineNum, output) } if multipleFiles { output = fmt.Sprintf("%v:%v", fileName, output) } result = append(result, output) } } } else { panic(err) } } return result } /* BenchmarkSearch-4 15 81182687 ns/op 116170 B/op 1088 allocs/op */
package main import ( "crypto" "crypto/sha1" "encoding/base64" "fmt" ) // 实现了SHA1哈希算法 func main() { // 返回一个新的使用SHA1校验的hash.Hash h := sha1.New() // 写入 h.Write([]byte("Hello World")) // 返回添加b到当前的hash值后的新切片,不会改变底层的hash状态 m := h.Sum(nil) // 转base64字符串打印 fmt.Println(base64.StdEncoding.EncodeToString(m)) // 使用crypto导入 hash := crypto.SHA1 h2 := hash.New() h2.Write([]byte("Hello World")) m2 := h2.Sum(nil) fmt.Println(base64.StdEncoding.EncodeToString(m2)) // 直接使用sha1.Sum m3 := sha1.Sum([]byte("Hello World")) fmt.Println(base64.StdEncoding.EncodeToString(m3[:])) }
package cmd import ( "fmt" "github.com/bitmaelum/bitmaelum-server/core" "github.com/bitmaelum/bitmaelum-server/core/container" "github.com/spf13/cobra" "time" ) // allowRegistrationCmd represents the allowRegistration command var allowRegistrationCmd = &cobra.Command{ Use: "allow-registration", Short: "Allows registration of given address", Long: `When running a mailserver, it's nice to limit the number of users that can create addresses`, Run: func(cmd *cobra.Command, args []string) { s, _ := cmd.Flags().GetString("address") d, _ := cmd.Flags().GetInt("days") addr, err := core.NewAddressFromString(s) if err != nil { fmt.Printf("incorrect address specified") return } is := container.GetInviteService() token, err := is.GetInvite(addr.Hash()) if err == nil { fmt.Printf("'%s' already allowed to register with token: %s\n", addr.String(), token) return } token, err = is.CreateInvite(addr.Hash(), time.Duration(d) * 24 * time.Hour) if err != nil { fmt.Printf("error while inviting address") } fmt.Printf("'%s' is allowed to register on our server in the next %d days.\n", addr.String(), d) fmt.Printf("The invitation token is: %s\n", token) }, } func init() { rootCmd.AddCommand(allowRegistrationCmd) allowRegistrationCmd.Flags().String("address", "", "Address to register") allowRegistrationCmd.Flags().Int("days", 30, "Days allowed for registration") _ = allowRegistrationCmd.MarkFlagRequired("address") }
package annotation_api import ( "encoding/json" "fmt" "github.com/samuel/go-zookeeper/zk" "github.com/wndhydrnt/proxym/log" "io/ioutil" "net/http" ) type AnnotationListItem struct { Annotation *Annotation `json:"annotation"` Link string `json:"link"` } type Http struct { zkCon *zk.Conn } func (h *Http) createAnnotation(w http.ResponseWriter, r *http.Request) { params := r.URL.Query() serviceId := params.Get(":serviceId") serviceZkPath := zookeeperPath + "/" + serviceId w.Header().Set("Access-Control-Allow-Origin", "*") data, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, fmt.Sprintf("Error reading request body: '%s'", err), http.StatusBadRequest) return } annotation := &Annotation{} err = json.Unmarshal(data, annotation) if err != nil { log.ErrorLog.Error("Error reading from Zookeeper: '%s'", err) http.Error(w, fmt.Sprintf("Error parsing JSON: '%s'", err), http.StatusBadRequest) return } present, _, err := h.zkCon.Exists(serviceZkPath) if err != nil { log.ErrorLog.Error("Error reading from Zookeeper: '%s'", err) http.Error(w, "", http.StatusInternalServerError) return } if present { zkData, _, err := h.zkCon.Get(serviceZkPath) if err != nil { log.ErrorLog.Error("Error reading from Zookeeper: '%s'", err) http.Error(w, "", http.StatusInternalServerError) return } oldA := &Annotation{} json.Unmarshal(zkData, oldA) if oldA.Config != annotation.Config || oldA.ApplicationProtocol != annotation.ApplicationProtocol || oldA.ProxyPath != annotation.ProxyPath || !compareDomains(oldA.Domains, annotation.Domains) { newData, err := json.Marshal(annotation) if err != nil { log.ErrorLog.Error("Error marshalling Annotation: '%s'", err) http.Error(w, "", http.StatusInternalServerError) return } _, err = h.zkCon.Set(serviceZkPath, newData, int32(-1)) if err != nil { log.ErrorLog.Error("Error updating zNode '%s': '%s'", serviceZkPath, err) http.Error(w, "", http.StatusInternalServerError) return } } } else { newData, err := json.Marshal(annotation) if err != nil { log.ErrorLog.Error("Error marshalling Annotation: '%s'", err) http.Error(w, "", http.StatusInternalServerError) return } _, err = h.zkCon.Create(serviceZkPath, newData, int32(0), zk.WorldACL(zk.PermAll)) if err != nil { log.ErrorLog.Error("Error creating zNode '%s': '%s'", serviceZkPath, err) http.Error(w, "", http.StatusInternalServerError) return } } w.WriteHeader(http.StatusNoContent) } func (h *Http) deleteAnnotation(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") params := r.URL.Query() aId := params.Get(":serviceId") err := h.zkCon.Delete(zookeeperPath+"/"+aId, int32(-1)) if err != nil { log.ErrorLog.Error("Error deleting annotation ID '%s': '%s'", aId, err) http.Error(w, "", http.StatusInternalServerError) return } w.WriteHeader(http.StatusNoContent) } func (h *Http) listAnnotations(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") annotationList := make([]*AnnotationListItem, 0) annotationIds, _, err := h.zkCon.Children(zookeeperPath) if err != nil { log.ErrorLog.Error("Error reading annotation IDs: '%s'", err) http.Error(w, "", http.StatusInternalServerError) return } for _, aId := range annotationIds { path := zookeeperPath + "/" + aId annotationData, _, err := h.zkCon.Get(path) if err != nil { log.ErrorLog.Error("Error reading data of annotation ID '%s': '%s'", aId, err) http.Error(w, "", http.StatusInternalServerError) return } annotation := &Annotation{} err = json.Unmarshal(annotationData, annotation) if err != nil { log.ErrorLog.Error("Error unmarshalling data of annotation ID '%s': '%s'", aId, err) http.Error(w, "", http.StatusInternalServerError) return } listItem := &AnnotationListItem{ Annotation: annotation, Link: httpPrefix + "/" + aId, } annotationList = append(annotationList, listItem) } anntationListData, err := json.Marshal(annotationList) if err != nil { log.ErrorLog.Error("Error marshalling list of annotations: '%s'", err) http.Error(w, "", http.StatusInternalServerError) return } w.Write(anntationListData) } func (h *Http) optionsAnnotation(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "DELETE,POST") w.Header().Set("Access-Control-Allow-Headers", "Content-Type") } func NewHttp(zkCon *zk.Conn) *Http { return &Http{zkCon: zkCon} }
package filestore import ( "errors" ) var ( ErrFileAlreadyExists = errors.New("File already exists") ErrFileNotFound = errors.New("File not found") ErrFileTooLarge = errors.New("File is too large") ErrFileCorrupted = errors.New("File is corrupted, try storing it again") ErrChecksumFailed = errors.New("Unable to store file: checksum verification failed") errKeysMissing = errors.New("Some keys are missing") ) type Store interface { Store(filename string, contents []byte) error Retrieve(filename string) ([]byte, error) Delete(filename string) error }
package geopoint import "math" // Point is the interface for any geopoints type Point interface { ToRadians() Radians ToDegrees() Degrees } // Degrees is the point in degrees type Degrees struct { Latitude float64 Longitude float64 } // ToRadians converts a Degrees point to Radians func (p Degrees) ToRadians() Radians { return Radians{ degreesToRadians(p.Latitude), degreesToRadians(p.Longitude), } } // ToDegrees converts a Radians point to Degrees func (p Degrees) ToDegrees() Degrees { return p } // Radians is the point in radians type Radians struct { Latitude float64 Longitude float64 } // ToRadians converts a Degrees point to Radians func (p Radians) ToRadians() Radians { return p } // ToDegrees converts a Radians point to Degrees func (p Radians) ToDegrees() Degrees { return Degrees{ radiansToDegrees(p.Latitude), radiansToDegrees(p.Longitude), } } // DistanceInKm calculates the distance between points func DistanceInKm(p1, p2 Point) float64 { h := haversine(p1.ToRadians(), p2.ToRadians()) hearthRadiusInMeters := 6371e3 return hearthRadiusInMeters * h / 1000 } func haversine(p1, p2 Radians) float64 { diffLatitude := p1.Latitude - p2.Latitude diffLongitude := p1.Longitude - p2.Longitude a := math.Sin(diffLatitude/2)*math.Sin(diffLatitude/2) + math.Cos(p1.Latitude)* math.Cos(p2.Latitude)* math.Sin(diffLongitude/2)*math.Sin(diffLongitude/2) return 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a)) } func degreesToRadians(value float64) float64 { return value * math.Pi / 180 } func radiansToDegrees(value float64) float64 { return value * 180 / math.Pi }
package intersect // На вход подается два массива произвольной длинны // Метод должен возвращать пересечение этих массивов (одинаковые элементы в обоих массивах) // Есть ли способ сделать оптимальнее? func SliceIntersect(a, b []int64) []int64 { var result []int64 out: for _, valA := range a { for _, valB := range b { if valA == valB { result = append(result, valA) continue out } } } return result } func SliceIntersectMap(a, b []int64) []int64 { m := make(map[int64]struct{}, len(a)) for _, item := range a { m[item] = struct{}{} } result := make([]int64, 0, len(a)) for _, item := range b { if _, ok := m[item]; ok { result = append(result, item) } } return result }
//determine if a sentence contains at least 1 instance of each letter package pangram import "strings" //identify each unique character and determine if the full string is a pangram func IsPangram(s string) bool { s = strings.ToLower(s) encountered := map[byte]bool{} for i := range s { if s[i] >= 'a' && s[i] <= 'z' { encountered[s[i]] = true } } return len(encountered) == 26 }
package validation import ( "bytes" "fmt" "io" "testing" "context" "crypto/tls" "crypto/x509" "net" "net/http" "net/http/httptest" "net/url" "strings" "github.com/stretchr/testify/assert" ) func TestValidateHostname(t *testing.T) { var inputHostname string hostname, err := ValidateHostname(inputHostname) assert.Equal(t, err, nil) assert.Empty(t, hostname) inputHostname = "hello.example.com" hostname, err = ValidateHostname(inputHostname) assert.Nil(t, err) assert.Equal(t, "hello.example.com", hostname) inputHostname = "http://hello.example.com" hostname, err = ValidateHostname(inputHostname) assert.Nil(t, err) assert.Equal(t, "hello.example.com", hostname) inputHostname = "bücher.example.com" hostname, err = ValidateHostname(inputHostname) assert.Nil(t, err) assert.Equal(t, "xn--bcher-kva.example.com", hostname) inputHostname = "http://bücher.example.com" hostname, err = ValidateHostname(inputHostname) assert.Nil(t, err) assert.Equal(t, "xn--bcher-kva.example.com", hostname) inputHostname = "http%3A%2F%2Fhello.example.com" hostname, err = ValidateHostname(inputHostname) assert.Nil(t, err) assert.Equal(t, "hello.example.com", hostname) } func TestValidateUrl(t *testing.T) { type testCase struct { input string expectedOutput string } testCases := []testCase{ {"http://localhost", "http://localhost"}, {"http://localhost/", "http://localhost"}, {"http://localhost/api", "http://localhost"}, {"http://localhost/api/", "http://localhost"}, {"https://localhost", "https://localhost"}, {"https://localhost/", "https://localhost"}, {"https://localhost/api", "https://localhost"}, {"https://localhost/api/", "https://localhost"}, {"https://localhost:8080", "https://localhost:8080"}, {"https://localhost:8080/", "https://localhost:8080"}, {"https://localhost:8080/api", "https://localhost:8080"}, {"https://localhost:8080/api/", "https://localhost:8080"}, {"localhost", "http://localhost"}, {"localhost/", "http://localhost/"}, {"localhost/api", "http://localhost/api"}, {"localhost/api/", "http://localhost/api/"}, {"localhost:8080", "http://localhost:8080"}, {"localhost:8080/", "http://localhost:8080/"}, {"localhost:8080/api", "http://localhost:8080/api"}, {"localhost:8080/api/", "http://localhost:8080/api/"}, {"localhost:8080/api/?asdf", "http://localhost:8080/api/?asdf"}, {"http://127.0.0.1:8080", "http://127.0.0.1:8080"}, {"127.0.0.1:8080", "http://127.0.0.1:8080"}, {"127.0.0.1", "http://127.0.0.1"}, {"https://127.0.0.1:8080", "https://127.0.0.1:8080"}, {"[::1]:8080", "http://[::1]:8080"}, {"http://[::1]", "http://[::1]"}, {"http://[::1]:8080", "http://[::1]:8080"}, {"[::1]", "http://[::1]"}, {"https://example.com", "https://example.com"}, {"example.com", "http://example.com"}, {"http://hello.example.com", "http://hello.example.com"}, {"hello.example.com", "http://hello.example.com"}, {"hello.example.com:8080", "http://hello.example.com:8080"}, {"https://hello.example.com:8080", "https://hello.example.com:8080"}, {"https://bücher.example.com", "https://xn--bcher-kva.example.com"}, {"bücher.example.com", "http://xn--bcher-kva.example.com"}, {"https%3A%2F%2Fhello.example.com", "https://hello.example.com"}, {"https://alex:12345@hello.example.com:8080", "https://hello.example.com:8080"}, } for i, testCase := range testCases { validUrl, err := ValidateUrl(testCase.input) assert.NoError(t, err, "test case %v", i) assert.Equal(t, testCase.expectedOutput, validUrl.String(), "test case %v", i) } validUrl, err := ValidateUrl("") assert.Equal(t, fmt.Errorf("URL should not be empty"), err) assert.Empty(t, validUrl) validUrl, err = ValidateUrl("ftp://alex:12345@hello.example.com:8080/robot.txt") assert.Equal(t, "Currently Cloudflare Tunnel does not support ftp protocol.", err.Error()) assert.Empty(t, validUrl) } func TestNewAccessValidatorOk(t *testing.T) { ctx := context.Background() url := "test.cloudflareaccess.com" access, err := NewAccessValidator(ctx, url, url, "") assert.NoError(t, err) assert.NotNil(t, access) assert.Error(t, access.Validate(ctx, "")) assert.Error(t, access.Validate(ctx, "invalid")) req := httptest.NewRequest("GET", "https://test.cloudflareaccess.com", nil) req.Header.Set(accessJwtHeader, "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c") assert.Error(t, access.ValidateRequest(ctx, req)) } func TestNewAccessValidatorErr(t *testing.T) { ctx := context.Background() urls := []string{ "", "ftp://test.cloudflareaccess.com", "wss://cloudflarenone.com", } for _, url := range urls { access, err := NewAccessValidator(ctx, url, url, "") assert.Error(t, err, url) assert.Nil(t, access) } } type testRoundTripper func(req *http.Request) (*http.Response, error) func (f testRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) } func emptyResponse(statusCode int) *http.Response { return &http.Response{ StatusCode: statusCode, Body: io.NopCloser(bytes.NewReader(nil)), Header: make(http.Header), } } func createMockServerAndClient(handler http.Handler) (*httptest.Server, *http.Client, error) { client := http.DefaultClient server := httptest.NewServer(handler) client.Transport = &http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { return url.Parse(server.URL) }, } return server, client, nil } func createSecureMockServerAndClient(handler http.Handler) (*httptest.Server, *http.Client, error) { client := http.DefaultClient server := httptest.NewTLSServer(handler) cert, err := x509.ParseCertificate(server.TLS.Certificates[0].Certificate[0]) if err != nil { server.Close() return nil, nil, err } certpool := x509.NewCertPool() certpool.AddCert(cert) client.Transport = &http.Transport{ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { return net.Dial("tcp", server.URL[strings.LastIndex(server.URL, "/")+1:]) }, TLSClientConfig: &tls.Config{ RootCAs: certpool, }, } return server, client, nil }
package sink import ( "testing" "github.com/mongodb/amboy/queue" "github.com/stretchr/testify/suite" ) type ServiceCacheSuite struct { cache *appServicesCache suite.Suite } func TestServiceCacheSuite(t *testing.T) { suite.Run(t, new(ServiceCacheSuite)) } func (s *ServiceCacheSuite) SetupTest() { s.cache = &appServicesCache{name: "sink.testing"} } func (s *ServiceCacheSuite) TestDefaultCacheValues() { s.Nil(s.cache.queue) s.Equal("sink.testing", s.cache.name) s.Nil(s.cache.session) } func (s *ServiceCacheSuite) TestQueueNotSettableToNil() { s.Error(s.cache.setQueue(nil)) s.Nil(s.cache.queue) q := queue.NewLocalOrdered(2) s.NotNil(q) s.NoError(s.cache.setQueue(q)) s.NotNil(s.cache.queue) s.Equal(s.cache.queue, q) s.Error(s.cache.setQueue(nil)) s.NotNil(s.cache.queue) s.Equal(s.cache.queue, q) } func (s *ServiceCacheSuite) TestQueueGetterRetrivesQueue() { q, err := s.cache.getQueue() s.Nil(q) s.Error(err) q = queue.NewLocalOrdered(2) s.NoError(s.cache.setQueue(q)) retrieved, err := s.cache.getQueue() s.NotNil(q) s.NoError(err) s.Equal(retrieved, q) } func (s *ServiceCacheSuite) TestSetSpendConfig() { file := "cost/testdata/spend_test.yml" err := s.cache.setSpendConfig(file) s.NoError(err) configFile := s.cache.spendConfig s.Equal(configFile.Opts.Duration, "8h") file = "not_real.yaml" err = s.cache.setSpendConfig(file) s.Error(err) }
package tencent func Code896() { } /** 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。 示例 1: 输入: "babad" 输出: "bab" 注意: "aba" 也是一个有效答案。 示例 2: 输入: "cbbd" 输出: "bb" */ /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func longestPalindrome(s string) string { return "" }
package almanack import ( "reflect" "testing" ) func TestToFromTOML(t *testing.T) { cases := map[string]SpotlightPAArticle{ "empty": {}, "body": {Body: "\n ## subhead ! \n"}, "fm": {Hed: "Hello", Authors: []string{"john", "smith"}}, "body+fm": {Hed: "Hello", Authors: []string{"john", "smith"}, Body: "## subhead !"}, "extra-delimiters": { Hed: "Hello", Authors: []string{"john", "smith"}, Body: "## subhead !\n+++\n\nmore\n+++\nstuff", }, } for name, art := range cases { t.Run(name, func(t *testing.T) { toml, err := art.ToTOML() if err != nil { t.Fatalf("err ToTOML: %v", err) } var art2 SpotlightPAArticle if err = art2.FromTOML(toml); err != nil { t.Fatalf("err FromTOML: %v", err) } if !reflect.DeepEqual(art, art2) { t.Errorf("article did not round trip") } }) } } func TestFromToTOML(t *testing.T) { cases := map[string]struct { ok bool content string }{ "empty": {false, ``}, "blank": {true, `+++ arc-id = "" internal-id = "" internal-budget = "" image = "" image-description = "" image-caption = "" image-credit = "" image-size = "" published = 0000-01-01T00:00:00Z slug = "" byline = "" title = "" subtitle = "" description = "" blurb = "" kicker = "" linktitle = "" suppress-featured = false weight = 0 url = "" modal-exclude = false no-index = false language-code = "" layout = "" extended-kicker = "" +++ `}, "fm": {true, `+++ arc-id = "123" internal-id = "spl123" internal-budget = "hello" image = "xyz.jpeg" image-description = "desc" image-caption = "capt" image-credit = "cred" image-size = "inline" published = 2006-01-01T00:00:00Z slug = "slug" authors = ["john", "doe"] byline = "menen" title = "hed" subtitle = "subtitle" description = "desc2" blurb = "blurb" kicker = "kick" linktitle = "lt" suppress-featured = true weight = 2 url = "/url/" modal-exclude = true no-index = true language-code = "es" layout = "fancy" extended-kicker = "More News" +++ `}, "fm+body": {true, `+++ arc-id = "123" internal-id = "spl123" internal-budget = "hello" image = "xyz.jpeg" image-description = "desc" image-caption = "capt" image-credit = "cred" image-size = "inline" published = 2006-01-01T00:00:00Z slug = "slug" authors = ["john", "doe"] byline = "menen" title = "hed" subtitle = "subtitle" description = "desc2" blurb = "blurb" kicker = "kick" linktitle = "lt" suppress-featured = true weight = 2 url = "/url/" modal-exclude = true no-index = true language-code = "es" layout = "fancy" extended-kicker = "More News" +++ Hello, world! +++ more~~ <h1></h1> `}, } for name, tc := range cases { t.Run(name, func(t *testing.T) { var art SpotlightPAArticle err := art.FromTOML(tc.content) if !tc.ok { if err == nil { t.Error("expected err FromTOML") } return } if err != nil { t.Fatalf("err FromTOML: %v", err) } toml, err := art.ToTOML() if err != nil { t.Fatalf("err ToTOML: %v", err) } if tc.content != toml { t.Errorf("article did not round trip: %q != %q", tc.content, toml, ) } }) } }
package gateway import ( "errors" "net" "time" "github.com/NebulousLabs/Sia/build" "github.com/NebulousLabs/Sia/crypto" "github.com/NebulousLabs/Sia/encoding" "github.com/NebulousLabs/Sia/modules" "github.com/inconshreveable/muxado" ) const ( dialTimeout = 2 * time.Minute // the gateway will not make outbound connections above this threshold wellConnectedThreshold = 8 // the gateway will not accept inbound connections above this threshold fullyConnectedThreshold = 128 // the gateway will ask for more addresses below this threshold minNodeListLen = 100 ) type peer struct { addr modules.NetAddress sess muxado.Session inbound bool } func (p *peer) open() (modules.PeerConn, error) { conn, err := p.sess.Open() if err != nil { return nil, err } return &peerConn{conn}, nil } func (p *peer) accept() (modules.PeerConn, error) { conn, err := p.sess.Accept() if err != nil { return nil, err } return &peerConn{conn}, nil } // addPeer adds a peer to the Gateway's peer list and spawns a listener thread // to handle its requests. func (g *Gateway) addPeer(p *peer) { g.peers[p.addr] = p go g.listenPeer(p) } // randomPeer returns a random peer from the gateway's peer list. func (g *Gateway) randomPeer() (modules.NetAddress, error) { if len(g.peers) > 0 { r, _ := crypto.RandIntn(len(g.peers)) for addr := range g.peers { if r <= 0 { return addr, nil } r-- } } return "", errNoPeers } // randomInboundPeer returns a random peer that initiated its connection. func (g *Gateway) randomInboundPeer() (modules.NetAddress, error) { if len(g.peers) > 0 { r, _ := crypto.RandIntn(len(g.peers)) for addr, peer := range g.peers { // only select inbound peers if !peer.inbound { continue } if r <= 0 { return addr, nil } r-- } } return "", errNoPeers } // listen handles incoming connection requests. If the connection is accepted, // the peer will be added to the Gateway's peer list. func (g *Gateway) listen() { for { conn, err := g.listener.Accept() if err != nil { return } go g.acceptConn(conn) } } // acceptConn adds a connecting node as a peer. func (g *Gateway) acceptConn(conn net.Conn) { addr := modules.NetAddress(conn.RemoteAddr().String()) g.log.Printf("INFO: %v wants to connect", addr) // don't connect to an IP address more than once if build.Release != "testing" { id := g.mu.RLock() for p := range g.peers { if p.Host() == addr.Host() { g.mu.RUnlock(id) conn.Close() g.log.Printf("INFO: rejected connection from %v: already connected", addr) return } } g.mu.RUnlock(id) } // read version var remoteVersion string if err := encoding.ReadObject(conn, &remoteVersion, maxAddrLength); err != nil { conn.Close() g.log.Printf("INFO: %v wanted to connect, but we could not read their version: %v", addr, err) return } // decide whether to accept // NOTE: this version must be bumped whenever the gateway or consensus // breaks compatibility. if build.VersionCmp(remoteVersion, "0.3.3") < 0 { encoding.WriteObject(conn, "reject") conn.Close() g.log.Printf("INFO: %v wanted to connect, but their version (%v) was unacceptable", addr, remoteVersion) return } // respond with our version if err := encoding.WriteObject(conn, "0.3.3"); err != nil { conn.Close() g.log.Printf("INFO: could not write version ack to %v: %v", addr, err) return } // If we are already fully connected, kick out an old inbound peer to make // room for the new one. Among other things, this ensures that bootstrap // nodes will always be connectible. Worst case, you'll connect, receive a // node list, and immediately get booted. But once you have the node list // you should be able to connect to less full peers. id := g.mu.Lock() if len(g.peers) >= fullyConnectedThreshold { oldPeer, err := g.randomInboundPeer() if err == nil { g.peers[oldPeer].sess.Close() delete(g.peers, oldPeer) g.log.Printf("INFO: disconnected from %v to make room for %v", oldPeer, addr) } } // add the peer g.addPeer(&peer{addr: addr, sess: muxado.Server(conn), inbound: true}) g.mu.Unlock(id) g.log.Printf("INFO: accepted connection from new peer %v (v%v)", addr, remoteVersion) } // Connect establishes a persistent connection to a peer, and adds it to the // Gateway's peer list. func (g *Gateway) Connect(addr modules.NetAddress) error { if addr == g.Address() { return errors.New("can't connect to our own address") } id := g.mu.RLock() _, exists := g.peers[addr] g.mu.RUnlock(id) if exists { return errors.New("peer already added") } conn, err := net.DialTimeout("tcp", string(addr), dialTimeout) if err != nil { return err } // send our version if err := encoding.WriteObject(conn, "0.3.3"); err != nil { return err } // read version ack var remoteVersion string if err := encoding.ReadObject(conn, &remoteVersion, maxAddrLength); err != nil { return err } else if remoteVersion == "reject" { return errors.New("peer rejected connection") } // decide whether to accept this version if build.VersionCmp(remoteVersion, "0.3.3") < 0 { conn.Close() return errors.New("unacceptable version: " + remoteVersion) } g.log.Println("INFO: connected to new peer", addr) id = g.mu.Lock() g.addPeer(&peer{addr: addr, sess: muxado.Client(conn), inbound: false}) g.mu.Unlock(id) // call initRPCs id = g.mu.RLock() for name, fn := range g.initRPCs { go g.RPC(addr, name, fn) } g.mu.RUnlock(id) return nil } // Disconnect terminates a connection to a peer and removes it from the // Gateway's peer list. The peer's address remains in the node list. func (g *Gateway) Disconnect(addr modules.NetAddress) error { id := g.mu.RLock() p, exists := g.peers[addr] g.mu.RUnlock(id) if !exists { return errors.New("not connected to that node") } p.sess.Close() id = g.mu.Lock() delete(g.peers, addr) g.mu.Unlock(id) g.log.Println("INFO: disconnected from peer", addr) return nil } // threadedPeerManager tries to keep the Gateway well-connected. As long as // the Gateway is not well-connected, it tries to connect to random nodes. func (g *Gateway) threadedPeerManager() { for { // If we are well-connected, sleep in increments of five minutes until // we are no longer well-connected. id := g.mu.RLock() numPeers := len(g.peers) addr, err := g.randomNode() g.mu.RUnlock(id) if numPeers >= wellConnectedThreshold { time.Sleep(5 * time.Minute) continue } // Try to connect to a random node. Instead of blocking on Connect, we // spawn a goroutine and sleep for five seconds. This allows us to // continue making connections if the node is unresponsive. if err == nil { go g.Connect(addr) } time.Sleep(5 * time.Second) } } func (g *Gateway) Peers() []modules.NetAddress { id := g.mu.RLock() defer g.mu.RUnlock(id) var peers []modules.NetAddress for addr := range g.peers { peers = append(peers, addr) } return peers }
package main import ( "fmt" "math/big" ) func main() { lightSpeed := big.NewInt(299792) // km/s secondPerDay := big.NewInt(86400) dayPerYear := big.NewInt(365) distance := new(big.Int) distance.SetString("236000000000000000", 10) // km seconds := new(big.Int) seconds.Div(distance, lightSpeed) days := new(big.Int) days.Div(seconds, secondPerDay) lightYears := new(big.Int) lightYears.Div(days, dayPerYear) fmt.Println("おおいぬ座矮小銀河まで、", lightYears, "光年かかる。") }
package intersections import ( "github.com/gmacd/rays/core" ) // Assumes the ray and triangle points are in the same space func IntersectRayTriangle(r core.Ray, p1, p2, p3 core.Vec3, maxDist float64) (hit HitType, dist float64) { e1 := p2.Sub(p1) e2 := p3.Sub(p1) s1 := r.Dir.Cross(e2) divisor := s1.Dot(e1) if divisor == 0 { return MISS, 0 } invDivisor := 1.0 / divisor // First barycentric coord d := r.Origin.Sub(p1) b1 := d.Dot(s1) * invDivisor if b1 < 0 || b1 > 1 { return MISS, 0 } // Second barycentric coord s2 := d.Cross(e1) b2 := r.Dir.Dot(s2) * invDivisor if b2 < 0 || b2 > 1 { return MISS, 0 } // We have an intersection, but early out if it's past maxDist t := e2.Dot(s2) * invDivisor if t < 0 || t > maxDist { return MISS, 0 } return HIT, t }
package main type snippet interface { imports() []string generate(p *printer) } type snippetTest interface { testImports() []string generateTest(p *printer) } func snippetTestOf(s snippet) snippetTest { type tester interface { test() snippetTest } if t, ok := s.(snippetTest); ok { return t } if t, ok := s.(tester); ok { if ts := t.test(); ts != nil { return ts } } return nil } type snippets []snippet func (s snippets) imports() []string { return uniqueImports(len(s), func(i int) []string { return s[i].imports() }) } func (s snippets) test() snippetTest { var res snippetTests for i := 0; i < len(s); i++ { if t := snippetTestOf(s[i]); t != nil { res = append(res, t) } } return res.test() } func (s snippets) generate(p *printer) { if len(s) == 0 { return } s[0].generate(p) for i := 1; i < len(s); i++ { p.Println() s[i].generate(p) } } type snippetTests []snippetTest func (s snippetTests) test() snippetTest { if len(s) == 0 { return nil } return s } func (s snippetTests) testImports() []string { return uniqueImports(len(s), func(i int) []string { return s[i].testImports() }) } func (s snippetTests) generateTest(p *printer) { if len(s) == 0 { return } s[0].generateTest(p) for i := 1; i < len(s); i++ { p.Println() s[i].generateTest(p) } } func testSnippetOf(s snippet) snippet { if t := snippetTestOf(s); t != nil { return testSnippet{s: t} } return nil } type testSnippet struct { s snippetTest } func (t testSnippet) imports() []string { return append(t.s.testImports(), "testing") } func (t testSnippet) generate(p *printer) { t.s.generateTest(p) } func uniqueImports(n int, f func(int) []string) []string { set := make(map[string]struct{}) res := make([]string, 0, n) for i := 0; i < n; i++ { for _, s := range f(i) { if _, has := set[s]; !has { res = append(res, s) set[s] = struct{}{} } } } return res }
package server import ( "net" "strings" "google.golang.org/grpc" . "github.com/tendermint/go-common" "github.com/anildukkipatty/tmsp/types" ) // var maxNumberConnections = 2 type GRPCServer struct { QuitService proto string addr string listener net.Listener server *grpc.Server app types.TMSPApplicationServer } func NewGRPCServer(protoAddr string, app types.TMSPApplicationServer) (Service, error) { parts := strings.SplitN(protoAddr, "://", 2) proto, addr := parts[0], parts[1] s := &GRPCServer{ proto: proto, addr: addr, listener: nil, app: app, } s.QuitService = *NewQuitService(nil, "TMSPServer", s) _, err := s.Start() // Just start it return s, err } func (s *GRPCServer) OnStart() error { s.QuitService.OnStart() ln, err := net.Listen(s.proto, s.addr) if err != nil { return err } s.listener = ln s.server = grpc.NewServer() types.RegisterTMSPApplicationServer(s.server, s.app) go s.server.Serve(s.listener) return nil } func (s *GRPCServer) OnStop() { s.QuitService.OnStop() s.server.Stop() }
package rpcclient import ( "context" "crypto/ed25519" "encoding/hex" "errors" "fmt" "kto/blockchain" "kto/p2p/node" "kto/rpcclient/message" "kto/transaction" "kto/txpool" "kto/types" "kto/until" "kto/until/miscellaneous" "net" "os" "strconv" "golang.org/x/crypto/sha3" "google.golang.org/grpc" "google.golang.org/grpc/codes" ) type Rpc struct { Bc *blockchain.Blockchain tp *txpool.Txpool message.UnimplementedGreeterServer n node.Node } func Run_rpc(Bc *blockchain.Blockchain, tp *txpool.Txpool, n node.Node) { logFile := Logger() defer logFile.Close() Debug("runrpc") s := &Rpc{Bc: Bc, tp: tp, n: n} lis, err := net.Listen("tcp", "0.0.0.0:8544") if err != nil { Error("failed to listen:", err) os.Exit(-1) } //server := grpc.NewServer() server := grpc.NewServer(grpc.UnaryInterceptor(ipInterceptor)) message.RegisterGreeterServer(server, s) server.Serve(lis) } func (s *Rpc) GetBalance(ctx context.Context, in *message.ReqBalance) (*message.ResBalance, error) { balance, _ := s.Bc.GetBalance([]byte(in.Address)) return &message.ResBalance{Balnce: balance}, nil } func (s *Rpc) GetBlockByNum(ctx context.Context, v *message.ReqBlockByNumber) (*message.RespBlock, error) { b, err := s.Bc.GetBlockByHeight(v.Height) if err != nil { Error("fail to get block:", err) return nil, err } var respdata *message.RespBlock = new(message.RespBlock) respdata.Txs = make([]*message.Tx, len(b.Txs)) for i := 0; i < len(respdata.Txs); i++ { respdata.Txs[i] = &message.Tx{Order: &message.Order{}} } for i, tx := range b.Txs { if tx == nil { continue } if tx.Hash != nil { respdata.Txs[i].Hash = hex.EncodeToString(tx.Hash) } if tx.Signature != nil { respdata.Txs[i].Signature = hex.EncodeToString(tx.Signature) } respdata.Txs[i].From = string(tx.From.AddressToByte()) respdata.Txs[i].Amount = tx.Amount respdata.Txs[i].Nonce = tx.Nonce respdata.Txs[i].To = string(tx.To.AddressToByte()) respdata.Txs[i].Time = tx.Time respdata.Txs[i].Script = tx.Script } respdata.Height = b.Height respdata.Hash = hex.EncodeToString(b.Hash) respdata.PrevBlockHash = hex.EncodeToString(b.PrevBlockHash) respdata.Root = hex.EncodeToString(b.Root) respdata.Timestamp = b.Timestamp respdata.Version = b.Version respdata.Miner = string(b.Miner) return respdata, nil } func (s *Rpc) GetBlockByHash(ctx context.Context, v *message.ReqBlockByHash) (*message.RespBlock, error) { h, _ := hex.DecodeString(v.Hash) b, err := s.Bc.GetBlockByHash(h) if err != nil { Error("fail to get blcok:", err) return nil, err } var respdata *message.RespBlock = new(message.RespBlock) respdata.Txs = make([]*message.Tx, len(b.Txs)) for i := 0; i < len(respdata.Txs); i++ { respdata.Txs[i] = &message.Tx{Order: &message.Order{}} } for i, tx := range b.Txs { if tx == nil { continue } if tx.Hash != nil { respdata.Txs[i].Hash = hex.EncodeToString(tx.Hash) } if tx.Signature != nil { respdata.Txs[i].Signature = hex.EncodeToString(tx.Signature) } respdata.Txs[i].From = string(tx.From.AddressToByte()) respdata.Txs[i].Amount = tx.Amount respdata.Txs[i].Nonce = tx.Nonce respdata.Txs[i].To = string(tx.To.AddressToByte()) respdata.Txs[i].Time = tx.Time respdata.Txs[i].Script = tx.Script } respdata.Height = b.Height respdata.Hash = hex.EncodeToString(b.Hash) respdata.PrevBlockHash = hex.EncodeToString(b.PrevBlockHash) respdata.Root = hex.EncodeToString(b.Root) respdata.Timestamp = b.Timestamp respdata.Version = b.Version respdata.Miner = string(b.Miner) return respdata, nil } func (s *Rpc) GetTxsByAddr(ctx context.Context, in *message.ReqTx) (*message.ResposeTxs, error) { err, tx_s := s.Bc.GetTransactionByAddr([]byte(in.Address)) if err != nil { Error("fail to get tx:", err) return nil, err } if tx_s == nil { Error("tx lsit is nil") return nil, err } var respData *message.ResposeTxs = &message.ResposeTxs{} //var Txs message.ResTx for _, txs := range tx_s { var tmpTx *message.Tx = &message.Tx{} tmpTx.Hash = hex.EncodeToString(txs.Hash) tmpTx.From = string(txs.From.AddressToByte()) tmpTx.Amount = txs.Amount tmpTx.Nonce = txs.Nonce tmpTx.To = string(txs.To.AddressToByte()) tmpTx.Signature = hex.EncodeToString(txs.Signature) tmpTx.Time = txs.Time tmpTx.Script = txs.Script if len(txs.Ord.Id) != 0 { tmpTx.Order = &message.Order{} tmpTx.Order.Id = string(txs.Ord.Id) tmpTx.Order.Address = string(txs.Ord.Address.AddressToByte()) tmpTx.Order.Price = txs.Ord.Price tmpTx.Order.Hash = until.Encode(txs.Ord.Hash) tmpTx.Order.Signature = until.Encode(txs.Ord.Signature) tmpTx.Order.Ciphertext = string(txs.Ord.Ciphertext) tmpTx.Order.Region = string(txs.Ord.Region) tmpTx.Order.Tradename = string(txs.Ord.Tradename) } respData.Txs = append(respData.Txs, tmpTx) } //data, _ := json.MarshalIndent(Txs.Txs, "", " ") //var resTx message.ResposeTxs = message.ResposeTxs{Txs: data} //Debugf("Greeting: %s", data) return respData, nil } func (s *Rpc) GetTxByHash(ctx context.Context, in *message.ReqTxByHash) (*message.Tx, error) { hash, err := hex.DecodeString(in.Hash) if err != nil { Error("fail to parse hash:", err) return nil, err } tx, err := s.Bc.GetTransaction(hash) if err != nil { Error("fail to get tx", err) return nil, err } respTx := &message.Tx{} respTx.Hash = hex.EncodeToString(tx.Hash) respTx.From = string(tx.From.AddressToByte()) respTx.Amount = tx.Amount respTx.Nonce = tx.Nonce respTx.To = string(tx.To.AddressToByte()) respTx.Signature = hex.EncodeToString(tx.Signature) respTx.Time = tx.Time respTx.Script = tx.Script if len(tx.Ord.Id) != 0 { respTx.Order = &message.Order{} respTx.Order.Id = string(tx.Ord.Id) respTx.Order.Address = string(tx.Ord.Address.AddressToByte()) respTx.Order.Price = tx.Ord.Price respTx.Order.Hash = until.Encode(tx.Ord.Hash) respTx.Order.Signature = until.Encode(tx.Ord.Signature) respTx.Order.Ciphertext = string(tx.Ord.Ciphertext) respTx.Order.Region = string(tx.Ord.Region) respTx.Order.Tradename = string(tx.Ord.Tradename) } return respTx, nil } func (s *Rpc) GetAddressNonceAt(ctx context.Context, in *message.ReqNonce) (*message.ResposeNonce, error) { nonce, err := s.Bc.GetNonce([]byte(in.Address)) if err != nil { Error("fail to get nonce:", err) return nil, err } var N message.ResposeNonce N.Nonce = nonce return &N, nil } func (s *Rpc) SendTransaction(ctx context.Context, in *message.ReqTransaction) (*message.ResTransaction, error) { if in.From == in.To { Error("request data error") return nil, grpc.Errorf(codes.InvalidArgument, "data error") } from := types.BytesToAddress([]byte(in.From)) to := types.BytesToAddress([]byte(in.To)) priv := until.Decode(in.Priv) if len(priv) != 64 { Errorf("priv length error:%d", len(priv)) return nil, grpc.Errorf(codes.InvalidArgument, "data error") } tx := transaction.New() tx = tx.NewTransaction(in.Nonce, in.Amount, from, to, "") if in.Order != nil { //var orderAddress types.Address // orderId := []byte(in.Order.Id) // orderPrice := in.Order.Price // orderCiphertext, _ := hex.DecodeString(in.Order.Ciphertext) if len(in.Order.Address) == types.Lenthaddr { for i, v := range []byte(in.Order.Address) { tx.Ord.Address[i] = v } var err error tx.Ord.Id = []byte(in.Order.Id) //tx.Ord.Address = orderAddress tx.Ord.Price = in.Order.Price tx.Ord.Ciphertext, err = hex.DecodeString(in.Order.Ciphertext) if err != nil { Error("ciphertext error:", err) return nil, grpc.Errorf(codes.InvalidArgument, "data error") } tx.Ord.Hash, err = hex.DecodeString(in.Order.Hash) if err != nil { Error("hash error:", err) return nil, grpc.Errorf(codes.InvalidArgument, "data error") } tx.Ord.Signature, err = hex.DecodeString(in.Order.Signature) if err != nil { Error("Signature error:", err) return nil, grpc.Errorf(codes.InvalidArgument, "data error") } tx.Ord.Region = in.Order.Region tx.Ord.Tradename = in.Order.Tradename } } tx = tx.SignTx(priv) err := s.tp.Add(tx, s.Bc) if err != nil { Error("Add tx for txpool error:", err) return nil, err } s.n.Broadcast(tx) hash := hex.EncodeToString(tx.Hash) return &message.ResTransaction{Hash: hash}, nil } func (s *Rpc) SendSignedTransaction(ctx context.Context, in *message.ReqSignedTransaction) (*message.RespSignedTransaction, error) { if in.From == in.To { Error("request data error") return nil, grpc.Errorf(codes.InvalidArgument, "data error") } from := types.BytesToAddress([]byte(in.From)) to := types.BytesToAddress([]byte(in.To)) tx := &transaction.Transaction{ From: from, To: to, Nonce: in.Nonce, Amount: in.Amount, Time: in.Time, Hash: in.Hash, Signature: in.Signature, } err := s.tp.Add(tx, s.Bc) if err != nil { Error("Add tx for txpool error:", err) return nil, grpc.Errorf(codes.InvalidArgument, "parameter error") } s.n.Broadcast(tx) hash := hex.EncodeToString(tx.Hash) return &message.RespSignedTransaction{Hash: hash}, nil } func (s *Rpc) CreateContract(ctx context.Context, in *message.ReqTokenCreate) (*message.RespTokenCreate, error) { if in.From == in.To { err := errors.New("request data error") Error(err) return nil, err } from := types.BytesToAddress([]byte(in.From)) to := types.BytesToAddress([]byte(in.To)) priv := until.Decode(in.Priv) if len(priv) != 64 { err := errors.New("priv error") Errorf("priv length error:%d", len(priv)) return nil, err } tx := transaction.New() //"new \"abc\" 1000000000" At := strconv.FormatUint(in.Total, 10) //script := "new" + '\"' + in.Symbol +'\"' + in.Total script := fmt.Sprintf("new \"%s\" %s", in.Symbol, At) tx = tx.Newtoken(in.Nonce, uint64(500001), in.Fee, from, to, script) tx = tx.SignTx(priv) err := s.tp.Add(tx, s.Bc) if err != nil { Error(err) return nil, err } s.n.Broadcast(tx) hash := hex.EncodeToString(tx.Hash) return &message.RespTokenCreate{Hash: hash}, nil } func (s *Rpc) MintToken(ctx context.Context, in *message.ReqTokenCreate) (*message.RespTokenCreate, error) { if in.From == in.To { err := errors.New("request data error") Error(err) return nil, err } from := types.BytesToAddress([]byte(in.From)) to := types.BytesToAddress([]byte(in.To)) priv := until.Decode(in.Priv) if len(priv) != 64 { err := errors.New("priv error") Errorf("priv length error:%d", len(priv)) return nil, err } tx := transaction.New() //"new \"abc\" 1000000000" At := strconv.FormatUint(in.Total, 10) //script := "new" + '\"' + in.Symbol +'\"' + in.Total script := fmt.Sprintf("mint \"%s\" %s", in.Symbol, At) tx = tx.Newtoken(in.Nonce, uint64(500001), in.Fee, from, to, script) tx = tx.SignTx(priv) err := s.tp.Add(tx, s.Bc) if err != nil { Error(err) return nil, err } s.n.Broadcast(tx) hash := hex.EncodeToString(tx.Hash) return &message.RespTokenCreate{Hash: hash}, nil } func (s *Rpc) SendToken(ctx context.Context, in *message.ReqTokenTransaction) (*message.RespTokenTransaction, error) { if in.From == in.To { err := errors.New("request data error") Error(err) return nil, err } from := types.BytesToAddress([]byte(in.From)) to := types.BytesToAddress([]byte(in.To)) priv := until.Decode(in.Priv) if len(priv) != 64 { err := errors.New("priv error") Errorf("priv length error:%d", len(priv)) return nil, err } tx := transaction.New() At := strconv.FormatUint(in.TokenAmount, 10) //"transfer \"abc\" 10 \"to\"" script := fmt.Sprintf("transfer \"%s\" %s \"%s\"", in.Symbol, At, in.To) //tx = tx.NewTransaction(in.Nonce, in.Amount, from, to, script) tx = tx.Newtoken(in.Nonce, in.Amount, in.Fee, from, to, script) tx = tx.SignTx(priv) err := s.tp.Add(tx, s.Bc) if err != nil { Error(err) return nil, err } s.n.Broadcast(tx) hash := hex.EncodeToString(tx.Hash) return &message.RespTokenTransaction{Hash: hash}, nil } func (s *Rpc) GetBalanceToken(ctx context.Context, in *message.ReqTokenBalance) (*message.RespTokenBalance, error) { balance, err := s.Bc.GetTokenBalance([]byte(in.Address), []byte(in.Symbol)) if err != nil { Error("fail to get balance:", err) return nil, err } return &message.RespTokenBalance{Balnce: balance}, nil } func (s *Rpc) SetLockBalance(ctx context.Context, in *message.ReqLockBalance) (*message.RespLockBalance, error) { if ok := s.Bc.LockBalance(in.Address, in.Amount); !ok { return &message.RespLockBalance{Status: false}, nil } return &message.RespLockBalance{Status: true}, nil } func (s *Rpc) SetUnlockBalance(ctx context.Context, in *message.ReqUnlockBalance) (*message.RespUnlockBalance, error) { if ok := s.Bc.Unlockbalance(in.Address, in.Amount); !ok { return &message.RespUnlockBalance{Status: false}, nil } return &message.RespUnlockBalance{Status: true}, nil } func (s *Rpc) CreateAddr(ctx context.Context, in *message.ReqCreateAddr) (*message.RespCreateAddr, error) { var addr, prickey string for { pubKey, privKey, err := until.Generprivkey() if err != nil { Error("fail to gener priv key:", err) return nil, err } addr = until.PubtoAddr(pubKey) prickey = until.Encode(privKey) if len(addr) == 47 { break } } return &message.RespCreateAddr{Address: addr, Privkey: prickey}, nil } //GetMaxBlockNumber 获取最大的块号 func (s *Rpc) GetMaxBlockNumber(ctx context.Context, in *message.ReqMaxBlockNumber) (*message.RespMaxBlockNumber, error) { maxHeight, err := s.Bc.GetMaxBlockHeight() if err != nil { Error("fail to get max height:", err) return nil, err } return &message.RespMaxBlockNumber{MaxNumber: maxHeight}, nil } //GetAddrByPriv 通过私钥获取地址 func (s *Rpc) GetAddrByPriv(ctx context.Context, in *message.ReqAddrByPriv) (*message.RespAddrByPriv, error) { privBytes := until.Decode(in.Priv) if len(privBytes) != 64 { err := errors.New("private key error") Error(err) return nil, err } addr := until.PubtoAddr(privBytes[32:]) return &message.RespAddrByPriv{Addr: addr}, nil } //GetFrozenAssets 获取冻结资产 func (s *Rpc) GetFrozenAssets(ctx context.Context, in *message.ReqFrozenAssets) (*message.RespFrozenAssets, error) { frozenAssets, _ := s.Bc.GetLockBalance(in.Addr) return &message.RespFrozenAssets{FrozenAssets: frozenAssets}, nil } //SignOrd 签名 func (s *Rpc) SignOrd(ctx context.Context, in *message.ReqSignOrd) (*message.RespSignOrd, error) { if in.Order == nil || len(in.Order.Id) == 0 || len(in.Order.Address) == 0 || len(in.Order.Ciphertext) == 0 || in.Order.Price == 0 || len(in.Priv) == 0 { return nil, errors.New("data error") } id, err := hex.DecodeString(in.Order.Id) if err != nil { return nil, err } // var orderAddress types.Address // for i, v := range []byte(in.Order.Address) { // orderAddress[i] = v // } price := miscellaneous.E64func(in.Order.Price) ciphertext, err := hex.DecodeString(in.Order.Ciphertext) if err != nil { return nil, err } var hashBytes []byte hashBytes = append(hashBytes, price...) hashBytes = append(hashBytes, id...) hashBytes = append(hashBytes, ciphertext...) hashBytes = append(hashBytes, []byte(in.Order.Address)...) hash32 := sha3.Sum256(hashBytes) Hash := hex.EncodeToString(hash32[:]) pri := ed25519.PrivateKey(until.Decode(in.Priv)) signatures := ed25519.Sign(pri, hash32[:]) Signature := hex.EncodeToString(signatures) return &message.RespSignOrd{Hash: Hash, Signature: Signature}, nil }
package version import ( "fmt" "strings" ) // Env represents a Python environment. type Env interface { Get(k string) (string, error) } // Expr represents an expression that can be evaluated given an environment. type Expr interface { Evaluate(env Env) (bool, error) } // Evaluate returns true if the dependency should be installed in the given environment. func (d *Dependency) Evaluate(env Env) (bool, error) { matchingExtra := true if len(d.Extras) > 0 { matchingExtra = false for _, e := range d.Extras { if e2, _ := env.Get("extra"); e == e2 { matchingExtra = true break } } } if !matchingExtra { return false, nil } // If multiple environment markers are provided all of them must evaluate to true. // This logic should be verified as it is not explicitly mentioned in PEP 508. for _, sub := range d.expr { r, err := sub.Evaluate(env) if err != nil { return false, err } if !r { return false, nil } } return true, nil } type exprMarker struct { left, right marker op string } func (e exprMarker) Evaluate(env Env) (bool, error) { // fmt.Printf("%s %s %s\n", e.left.value, e.op, e.right.value) left := e.left.value if e.left.env { var err error left, err = env.Get(left) if err != nil { return false, err } } right := e.right.value if e.right.env { var err error right, err = env.Get(right) if err != nil { return false, err } } // Use PEP 440 version comparison operators if both sides are valid versions // and the operator is defined in the set of comparison operators for versions. if e.op == "in" { return strings.Contains(left, right), nil } else if e.op == "not in" { return !strings.Contains(left, right), nil } else if e.op == TripleEqual { // '===' is a fallback operator for invalid versions. While technically a // version comparison operator it must be used at this point as the versions // are unlikely to parse correctly. return left == right, nil } leftVersion, leftValidVersion := Parse(left) rightVersion, rightValidVersion := Parse(right) if leftValidVersion && rightValidVersion { switch e.op { case LessOrEqual: return Compare(leftVersion, rightVersion) <= 0, nil case Less: return Compare(leftVersion, rightVersion) < 0, nil case NotEqual: return Compare(leftVersion, rightVersion) != 0, nil case Equal: return Compare(leftVersion, rightVersion) == 0, nil case GreaterOrEqual: return Compare(leftVersion, rightVersion) >= 0, nil case Greater: return Compare(leftVersion, rightVersion) > 0, nil case CompatibleEqual: // TODO: Implement support for ~= return false, nil default: return false, fmt.Errorf("unsupported version comparison operator: '%s'", e.op) } } else { switch e.op { case LessOrEqual: return left <= right, nil case Less: return left < right, nil case NotEqual: return left != right, nil case Equal: return left == right, nil case GreaterOrEqual: return left >= right, nil case Greater: return left > right, nil case CompatibleEqual: return false, fmt.Errorf("'~=' only supported for valid versions") default: return false, fmt.Errorf("unsupported string comparison operator: '%s'", e.op) } } } type exprOr struct { left, right Expr } func (e exprOr) Evaluate(env Env) (bool, error) { left, err := e.left.Evaluate(env) if err != nil { return false, err } right, err := e.right.Evaluate(env) if err != nil { return false, err } return left || right, nil } type exprAnd struct { left, right Expr } func (e exprAnd) Evaluate(env Env) (bool, error) { left, err := e.left.Evaluate(env) if err != nil { return false, err } else if !left { // short-circuit return false, nil } right, err := e.right.Evaluate(env) if err != nil { return false, err } return right, nil }
package main import "fmt" func findMissingRanges(nums []int, start int, end int) []string { ret := make([]string, 0) prev := start - 1 cur := 0 for i := 0; i <= len(nums); i++ { if i != len(nums) { cur = nums[i] } else { cur = end + 1 } if cur-prev >= 2 { ret = append(ret, getRange(prev+1, cur-1)) } prev = cur } return ret } func getRange(from, to int) string { if from == to { return fmt.Sprintf("%v", from) } return fmt.Sprintf("%v->%v", from, to) } func main() { fmt.Println(findMissingRanges([]int{0, 1, 3, 50, 75}, 0, 99)) fmt.Println(findMissingRanges([]int{3, 50, 75}, 0, 99)) }
// Copyright 2018, Shulhan <ms@kilabit.info>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package test import ( "testing" ) func TestAssert(t *testing.T) { cases := []struct { desc string in interface{} exp interface{} }{ { desc: "With nil", in: nil, exp: nil, }, } for _, c := range cases { t.Log(c.desc) Assert(t, "interface{}", c.exp, c.in) } }
package routers import ( "net/http" "strings" "time" "github.com/apulis/AIArtsBackend/configs" "github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" ) type Claim struct { jwt.StandardClaims Uid int `json:"uid"` UserName string `json:"userName"` } var JwtSecret = configs.Config.Auth.Key func parseToken(token string) (*Claim, error) { jwtToken, err := jwt.ParseWithClaims(token, &Claim{}, func(token *jwt.Token) (i interface{}, e error) { return []byte(JwtSecret), nil }) if err == nil && jwtToken != nil { if claim, ok := jwtToken.Claims.(*Claim); ok && jwtToken.Valid { return claim, nil } } return nil, err } func Auth() gin.HandlerFunc { return func(c *gin.Context) { auth := c.Request.Header.Get("Authorization") if len(auth) == 0 { c.Abort() c.JSON(http.StatusUnauthorized, UnAuthorizedError("Cannot authorize")) } else { auth = strings.Fields(auth)[1] // Check token claim, err := parseToken(auth) if err != nil { c.Abort() c.JSON(http.StatusUnauthorized, UnAuthorizedError(err.Error())) } else { if time.Now().Unix() > claim.ExpiresAt { c.Abort() c.JSON(http.StatusUnauthorized, UnAuthorizedError("Token expired")) } c.Set("uid", claim.Uid) c.Set("userName", claim.UserName) c.Set("userId", claim.Uid) } } c.Next() } }
package rbac import ( "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "starter/pkg/database/mongo" ) // Role 角色 type Role struct { ID primitive.ObjectID `json:"_id" bson:"_id"` Name string `json:"name" bson:"name" form:"name" binding:"max=12"` // 角色名称 Pid string `json:"pid" bson:"pid" form:"pid"` // 角色的父级角色id Permissions []string `json:"permissions" bson:"permissions" form:"permissions[]"` // 权限id列表 CreatedAt int64 `json:"created_at" bson:"created_at"` UpdatedAt int64 `json:"updated_at" bson:"updated_at"` } // Roles 角色列表 type Roles []Role var role Role // GetPermissionIDs 获取角色列表中包含的所有权限id func (roles Roles) GetPermissionIDs() []primitive.ObjectID { var ids []primitive.ObjectID for _, role := range roles { for _, permission := range role.Permissions { id, _ := primitive.ObjectIDFromHex(permission) ids = append(ids, id) } } return ids } // TableName 表名 func (Role) TableName() string { return "roles" } // GetRoles 获取权限 func (Role) GetRoles(id ...primitive.ObjectID) Roles { var roles Roles mongo.Collection(role).Where(bson.M{"_id": bson.M{"$in": id}}).FindMany(&roles) return roles }
package orders import ( "encoding/json" "fmt" "github.com/gustavotero7/go-conekta/client" "github.com/gustavotero7/go-conekta/models" ) const basePath = "/orders" // Create Creates a new Order func Create(order models.Order) (*models.OrderResponse, error) { response, err := client.Post(basePath, order) if err != nil { return nil, err } var cr models.OrderResponse if err := json.Unmarshal(response, &cr); err != nil { return nil, err } return &cr, nil } // Update Updates an existing Order func Update(order models.Order) (*models.Order, error) { response, err := client.Put(fmt.Sprintf("%s/%s", basePath, order.ID), order) if err != nil { return nil, err } var cr models.Order if err := json.Unmarshal(response, &cr); err != nil { return nil, err } return &cr, nil } // Capture Process a pre-authorized order. func Capture(orderID string) (*models.OrderResponse, error) { response, err := client.Post(fmt.Sprintf("%s/%s/capture", basePath, orderID), nil) if err != nil { return nil, err } var cr models.OrderResponse if err := json.Unmarshal(response, &cr); err != nil { return nil, err } return &cr, nil } // Refund A Refund details the amount and reason why an order was refunded. // Reasons: // requested_by_client // cannot_be_fulfilled // duplicated_transaction // suspected_fraud // other func Refund(order models.Order) (*models.OrderResponse, error) { response, err := client.Post(fmt.Sprintf("%s/%s/refunds", basePath, order.ID), order) if err != nil { return nil, err } var cr models.OrderResponse if err := json.Unmarshal(response, &cr); err != nil { return nil, err } return &cr, nil } // CreateCharge Creates a new charge for an existing order. func CreateCharge(orderID string, charge models.Charge) (*models.Charge, error) { response, err := client.Post(fmt.Sprintf("%s/%s/charges", basePath, orderID), charge) if err != nil { return nil, err } var cr models.Charge if err := json.Unmarshal(response, &cr); err != nil { return nil, err } return &cr, nil }
// Copyright 2020 The Moov Authors // Use of this source code is governed by an Apache License // license that can be found in the LICENSE file. package wire import ( "encoding/json" "fmt" "strings" "unicode/utf8" ) // Originator is the originator of the wire type Originator struct { // tag tag string // Personal Personal Personal `json:"personal,omitempty"` // validator is composed for data validation validator // converters is composed for WIRE to GoLang Converters converters } // NewOriginator returns a new Originator func NewOriginator() *Originator { o := &Originator{ tag: TagOriginator, } return o } // Parse takes the input string and parses the Originator values // // Parse provides no guarantee about all fields being filled in. Callers should make a Validate() call to confirm // successful parsing and data validity. func (o *Originator) Parse(record string) error { if utf8.RuneCountInString(record) < 9 { return NewTagMinLengthErr(9, len(record)) } o.tag = record[:6] o.Personal.IdentificationCode = o.parseStringField(record[6:7]) fmt.Printf("o.tag=%q o.Personal.IdentificationCode=%q\n", o.tag, o.Personal.IdentificationCode) length := 7 value, read, err := o.parseVariableStringField(record[length:], 34) if err != nil { return fieldError("Identifier", err) } o.Personal.Identifier = value length += read fmt.Printf("value=%q read=%d length=%d\n", value, read, length) value, read, err = o.parseVariableStringField(record[length:], 35) if err != nil { return fieldError("Name", err) } o.Personal.Name = value length += read fmt.Printf("value=%q read=%d length=%d\n", value, read, length) value, read, err = o.parseVariableStringField(record[length:], 35) if err != nil { return fieldError("AddressLineOne", err) } o.Personal.Address.AddressLineOne = value length += read fmt.Printf("value=%q read=%d length=%d\n", value, read, length) value, read, err = o.parseVariableStringField(record[length:], 35) if err != nil { return fieldError("AddressLineTwo", err) } o.Personal.Address.AddressLineTwo = value length += read fmt.Printf("value=%q read=%d length=%d\n", value, read, length) value, read, err = o.parseVariableStringField(record[length:], 35) if err != nil { return fieldError("AddressLineThree", err) } o.Personal.Address.AddressLineThree = value length += read fmt.Printf("value=%q read=%d length=%d\n", value, read, length) if err := o.verifyDataWithReadLength(record, length); err != nil { return NewTagMaxLengthErr(err) } return nil } func (o *Originator) UnmarshalJSON(data []byte) error { type Alias Originator aux := struct { *Alias }{ (*Alias)(o), } if err := json.Unmarshal(data, &aux); err != nil { return err } o.tag = TagOriginator return nil } // String returns a fixed-width Originator record func (o *Originator) String() string { return o.Format(FormatOptions{ VariableLengthFields: false, }) } // Format returns a Originator record formatted according to the FormatOptions func (o *Originator) Format(options FormatOptions) string { var buf strings.Builder buf.Grow(181) buf.WriteString(o.tag) buf.WriteString(o.IdentificationCodeField()) buf.WriteString(o.FormatIdentifier(options)) buf.WriteString(o.FormatName(options)) buf.WriteString(o.FormatAddressLineOne(options)) buf.WriteString(o.FormatAddressLineTwo(options)) buf.WriteString(o.FormatAddressLineThree(options)) if options.VariableLengthFields { return o.stripDelimiters(buf.String()) } else { return buf.String() } } // Validate performs WIRE format rule checks on Originator and returns an error if not Validated // The first error encountered is returned and stops that parsing. func (o *Originator) Validate() error { if err := o.fieldInclusion(); err != nil { return err } if o.tag != TagOriginator { return fieldError("tag", ErrValidTagForType, o.tag) } // Can be any Identification Code if err := o.isIdentificationCode(o.Personal.IdentificationCode); err != nil { return fieldError("IdentificationCode", err, o.Personal.IdentificationCode) } if err := o.isAlphanumeric(o.Personal.Identifier); err != nil { return fieldError("Identifier", err, o.Personal.Identifier) } if err := o.isAlphanumeric(o.Personal.Name); err != nil { return fieldError("Name", err, o.Personal.Name) } if err := o.isAlphanumeric(o.Personal.Address.AddressLineOne); err != nil { return fieldError("AddressLineOne", err, o.Personal.Address.AddressLineOne) } if err := o.isAlphanumeric(o.Personal.Address.AddressLineTwo); err != nil { return fieldError("AddressLineTwo", err, o.Personal.Address.AddressLineTwo) } if err := o.isAlphanumeric(o.Personal.Address.AddressLineThree); err != nil { return fieldError("AddressLineThree", err, o.Personal.Address.AddressLineThree) } return nil } // fieldInclusion validate mandatory fields. If fields are // invalid the WIRE will return an error. func (o *Originator) fieldInclusion() error { if o.Personal.IdentificationCode != "" && o.Personal.Identifier == "" { return fieldError("Identifier", ErrFieldRequired) } if o.Personal.IdentificationCode == "" && o.Personal.Identifier != "" { return fieldError("IdentificationCode", ErrFieldRequired) } return nil } // IdentificationCodeField gets a string of the IdentificationCode field func (o *Originator) IdentificationCodeField() string { return o.alphaField(o.Personal.IdentificationCode, 1) } // IdentifierField gets a string of the Identifier field func (o *Originator) IdentifierField() string { return o.alphaField(o.Personal.Identifier, 34) } // NameField gets a string of the Name field func (o *Originator) NameField() string { return o.alphaField(o.Personal.Name, 35) } // AddressLineOneField gets a string of AddressLineOne field func (o *Originator) AddressLineOneField() string { return o.alphaField(o.Personal.Address.AddressLineOne, 35) } // AddressLineTwoField gets a string of AddressLineTwo field func (o *Originator) AddressLineTwoField() string { return o.alphaField(o.Personal.Address.AddressLineTwo, 35) } // AddressLineThreeField gets a string of AddressLineThree field func (o *Originator) AddressLineThreeField() string { return o.alphaField(o.Personal.Address.AddressLineThree, 35) } // FormatIdentifier returns Personal.Identifier formatted according to the FormatOptions func (o *Originator) FormatIdentifier(options FormatOptions) string { return o.formatAlphaField(o.Personal.Identifier, 34, options) } // FormatName returns Personal.Name formatted according to the FormatOptions func (o *Originator) FormatName(options FormatOptions) string { return o.formatAlphaField(o.Personal.Name, 35, options) } // FormatAddressLineOne returns Address.AddressLineOne formatted according to the FormatOptions func (o *Originator) FormatAddressLineOne(options FormatOptions) string { return o.formatAlphaField(o.Personal.Address.AddressLineOne, 35, options) } // FormatAddressLineTwo returns Address.AddressLineTwo formatted according to the FormatOptions func (o *Originator) FormatAddressLineTwo(options FormatOptions) string { return o.formatAlphaField(o.Personal.Address.AddressLineTwo, 35, options) } // FormatAddressLineThree returns Address.AddressLineThree formatted according to the FormatOptions func (o *Originator) FormatAddressLineThree(options FormatOptions) string { return o.formatAlphaField(o.Personal.Address.AddressLineThree, 35, options) }
/* Copyright 2019-2020 vChain, 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 clienttest ... package clienttest /* import ( "context" "github.com/codenotary/immudb/pkg/api/schema" "github.com/golang/protobuf/ptypes/empty" "google.golang.org/grpc" ) // ImmuServiceClientMock ... type ImmuServiceClientMock struct { schema.ImmuServiceClient ListUsersF func(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*schema.UserList, error) GetUserF func(ctx context.Context, in *schema.UserRequest, opts ...grpc.CallOption) error CreateUserF func(ctx context.Context, in *schema.CreateUserRequest, opts ...grpc.CallOption) (*empty.Empty, error) ChangePasswordF func(ctx context.Context, in *schema.ChangePasswordRequest, opts ...grpc.CallOption) (*empty.Empty, error) SetPermissionF func(ctx context.Context, in *schema.Item, opts ...grpc.CallOption) (*empty.Empty, error) DeactivateUserF func(ctx context.Context, in *schema.UserRequest, opts ...grpc.CallOption) (*empty.Empty, error) UpdateAuthConfigF func(ctx context.Context, in *schema.AuthConfig, opts ...grpc.CallOption) (*empty.Empty, error) UpdateMTLSConfigF func(ctx context.Context, in *schema.MTLSConfig, opts ...grpc.CallOption) (*empty.Empty, error) PrintTreeF func(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*schema.Tree, error) LoginF func(ctx context.Context, in *schema.LoginRequest, opts ...grpc.CallOption) (*schema.LoginResponse, error) LogoutF func(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) SetF func(ctx context.Context, in *schema.KeyValue, opts ...grpc.CallOption) (*schema.Index, error) SafeSetF func(ctx context.Context, in *schema.SafeSetOptions, opts ...grpc.CallOption) (*schema.Proof, error) GetF func(ctx context.Context, in *schema.Key, opts ...grpc.CallOption) (*schema.Item, error) SafeGetF func(ctx context.Context, in *schema.SafeGetOptions, opts ...grpc.CallOption) (*schema.SafeItem, error) SetBatchF func(ctx context.Context, in *schema.KVList, opts ...grpc.CallOption) (*schema.Index, error) GetBatchF func(ctx context.Context, in *schema.KeyList, opts ...grpc.CallOption) (*schema.ItemList, error) ScanF func(ctx context.Context, in *schema.ScanOptions, opts ...grpc.CallOption) (*schema.ItemList, error) CountF func(ctx context.Context, in *schema.KeyPrefix, opts ...grpc.CallOption) (*schema.ItemsCount, error) CountAllF func(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*schema.ItemsCount, error) CurrentRootF func(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*schema.Root, error) InclusionF func(ctx context.Context, in *schema.Index, opts ...grpc.CallOption) (*schema.InclusionProof, error) ConsistencyF func(ctx context.Context, in *schema.Index, opts ...grpc.CallOption) (*schema.ConsistencyProof, error) ByIndexF func(ctx context.Context, in *schema.Index, opts ...grpc.CallOption) (*schema.Item, error) BySafeIndexF func(ctx context.Context, in *schema.SafeIndexOptions, opts ...grpc.CallOption) (*schema.SafeItem, error) HistoryF func(ctx context.Context, in *schema.HistoryOptions, opts ...grpc.CallOption) (*schema.ItemList, error) HealthF func(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*schema.HealthResponse, error) ReferenceF func(ctx context.Context, in *schema.ReferenceOptions, opts ...grpc.CallOption) (*schema.Index, error) SafeReferenceF func(ctx context.Context, in *schema.SafeReferenceOptions, opts ...grpc.CallOption) (*schema.Proof, error) ZAddF func(ctx context.Context, in *schema.ZAddOptions, opts ...grpc.CallOption) (*schema.Index, error) ZScanF func(ctx context.Context, in *schema.ZScanOptions, opts ...grpc.CallOption) (*schema.ZItemList, error) SafeZAddF func(ctx context.Context, in *schema.SafeZAddOptions, opts ...grpc.CallOption) (*schema.Proof, error) IScanF func(ctx context.Context, in *schema.IScanOptions, opts ...grpc.CallOption) (*schema.Page, error) DumpF func(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (schema.ImmuService_DumpClient, error) CreateDatabaseF func(ctx context.Context, in *schema.Database, opts ...grpc.CallOption) (*empty.Empty, error) UseDatabaseF func(ctx context.Context, in *schema.Database, opts ...grpc.CallOption) (*schema.UseDatabaseReply, error) ChangePermissionF func(ctx context.Context, in *schema.ChangePermissionRequest, opts ...grpc.CallOption) (*empty.Empty, error) SetActiveUserF func(ctx context.Context, in *schema.SetActiveUserRequest, opts ...grpc.CallOption) (*empty.Empty, error) DatabaseListF func(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*schema.DatabaseListResponse, error) ExecAllOpsF func(ctx context.Context, in *schema.Ops, opts ...grpc.CallOption) (*schema.Index, error) } func (iscm *ImmuServiceClientMock) CurrentRoot(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*schema.Root, error) { return iscm.CurrentRootF(ctx, in, opts...) } func (iscm *ImmuServiceClientMock) Login(ctx context.Context, in *schema.LoginRequest, opts ...grpc.CallOption) (*schema.LoginResponse, error) { return iscm.LoginF(ctx, in, opts...) } func (iscm *ImmuServiceClientMock) Health(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*schema.HealthResponse, error) { return iscm.HealthF(ctx, in, opts...) } func (iscm *ImmuServiceClientMock) DatabaseList(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*schema.DatabaseListResponse, error) { return iscm.DatabaseListF(ctx, in, opts...) } func (iscm *ImmuServiceClientMock) UseDatabase(ctx context.Context, in *schema.Database, opts ...grpc.CallOption) (*schema.UseDatabaseReply, error) { return iscm.UseDatabaseF(ctx, in, opts...) } func (iscm *ImmuServiceClientMock) Logout(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error) { return iscm.LogoutF(ctx, in, opts...) } // SafeGet ... func (icm *ImmuServiceClientMock) SafeGet(ctx context.Context, in *schema.SafeGetOptions, opts ...grpc.CallOption) (*schema.SafeItem, error) { return icm.SafeGetF(ctx, in, opts...) } // SafeSet ... func (icm *ImmuServiceClientMock) SafeSet(ctx context.Context, in *schema.SafeSetOptions, opts ...grpc.CallOption) (*schema.Proof, error) { return icm.SafeSetF(ctx, in, opts...) } // Set ... func (icm *ImmuServiceClientMock) Set(ctx context.Context, in *schema.KeyValue, opts ...grpc.CallOption) (*schema.Index, error) { return icm.SetF(ctx, in, opts...) } // ZAdd ... func (icm *ImmuServiceClientMock) ZAdd(ctx context.Context, in *schema.ZAddOptions, opts ...grpc.CallOption) (*schema.Index, error) { return icm.ZAddF(ctx, in, opts...) } // SafeZAdd ... func (icm *ImmuServiceClientMock) SafeZAdd(ctx context.Context, in *schema.SafeZAddOptions, opts ...grpc.CallOption) (*schema.Proof, error) { return icm.SafeZAddF(ctx, in, opts...) } // History ... func (icm *ImmuServiceClientMock) History(ctx context.Context, in *schema.HistoryOptions, opts ...grpc.CallOption) (*schema.ItemList, error) { return icm.HistoryF(ctx, in, opts...) } // Get ... func (icm *ImmuServiceClientMock) Get(ctx context.Context, in *schema.Key, opts ...grpc.CallOption) (*schema.Item, error) { return icm.GetF(ctx, in, opts...) } // ZScan ... func (icm *ImmuServiceClientMock) ZScan(ctx context.Context, in *schema.ZScanOptions, opts ...grpc.CallOption) (*schema.ZItemList, error) { return icm.ZScanF(ctx, in, opts...) } // Scan ... func (icm *ImmuServiceClientMock) Scan(ctx context.Context, in *schema.ScanOptions, opts ...grpc.CallOption) (*schema.ItemList, error) { return icm.ScanF(ctx, in, opts...) } // CreateDatabase ... func (icm *ImmuServiceClientMock) CreateDatabase(ctx context.Context, in *schema.Database, opts ...grpc.CallOption) (*empty.Empty, error) { return icm.CreateDatabaseF(ctx, in, opts...) } // CreateUser ... func (icm *ImmuServiceClientMock) CreateUser(ctx context.Context, in *schema.CreateUserRequest, opts ...grpc.CallOption) (*empty.Empty, error) { return icm.CreateUserF(ctx, in, opts...) } func (icm *ImmuServiceClientMock) SetBatch(ctx context.Context, in *schema.KVList, opts ...grpc.CallOption) (*schema.Index, error) { return icm.SetBatchF(ctx, in, opts...) } func (icm *ImmuServiceClientMock) GetBatch(ctx context.Context, in *schema.KeyList, opts ...grpc.CallOption) (*schema.ItemList, error) { return icm.GetBatchF(ctx, in, opts...) } func (icm *ImmuServiceClientMock) ExecAllOps(ctx context.Context, in *schema.Ops, opts ...grpc.CallOption) (*schema.Index, error) { return icm.ExecAllOpsF(ctx, in, opts...) } func (icm *ImmuServiceClientMock) Inclusion(ctx context.Context, in *schema.Index, opts ...grpc.CallOption) (*schema.InclusionProof, error) { return icm.InclusionF(ctx, in, opts...) } func (icm *ImmuServiceClientMock) Consistency(ctx context.Context, in *schema.Index, opts ...grpc.CallOption) (*schema.ConsistencyProof, error) { return icm.ConsistencyF(ctx, in, opts...) } func (icm *ImmuServiceClientMock) ByIndex(ctx context.Context, in *schema.Index, opts ...grpc.CallOption) (*schema.Item, error) { return icm.ByIndexF(ctx, in, opts...) } func NewImmuServiceClientMock() *ImmuServiceClientMock { bs := &ImmuServiceClientMock{ HealthF: func(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*schema.HealthResponse, error) { return &schema.HealthResponse{}, nil }, LoginF: func(ctx context.Context, in *schema.LoginRequest, opts ...grpc.CallOption) (*schema.LoginResponse, error) { return &schema.LoginResponse{}, nil }, SafeGetF: func(ctx context.Context, in *schema.SafeGetOptions, opts ...grpc.CallOption) (*schema.SafeItem, error) { return &schema.SafeItem{}, nil }, SafeSetF: func(ctx context.Context, in *schema.SafeSetOptions, opts ...grpc.CallOption) (*schema.Proof, error) { return &schema.Proof{}, nil }, SetF: func(ctx context.Context, in *schema.KeyValue, opts ...grpc.CallOption) (*schema.Index, error) { return &schema.Index{}, nil }, UseDatabaseF: func(ctx context.Context, in *schema.Database, opts ...grpc.CallOption) (*schema.UseDatabaseReply, error) { return &schema.UseDatabaseReply{}, nil }, CreateDatabaseF: func(ctx context.Context, in *schema.Database, opts ...grpc.CallOption) (*empty.Empty, error) { return &empty.Empty{}, nil }, CurrentRootF: func(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*schema.Root, error) { return &schema.Root{}, nil }, GetF: func(ctx context.Context, in *schema.Key, opts ...grpc.CallOption) (*schema.Item, error) { return &schema.Item{}, nil }, ScanF: func(ctx context.Context, in *schema.ScanOptions, opts ...grpc.CallOption) (*schema.ItemList, error) { return &schema.ItemList{}, nil }, HistoryF: func(ctx context.Context, in *schema.HistoryOptions, opts ...grpc.CallOption) (*schema.ItemList, error) { return &schema.ItemList{}, nil }, ZAddF: func(ctx context.Context, in *schema.ZAddOptions, opts ...grpc.CallOption) (*schema.Index, error) { return &schema.Index{}, nil }, SafeZAddF: func(ctx context.Context, in *schema.SafeZAddOptions, opts ...grpc.CallOption) (*schema.Proof, error) { return &schema.Proof{}, nil }, ZScanF: func(ctx context.Context, in *schema.ZScanOptions, opts ...grpc.CallOption) (*schema.ZItemList, error) { return &schema.ZItemList{}, nil }, CreateUserF: func(ctx context.Context, in *schema.CreateUserRequest, opts ...grpc.CallOption) (*empty.Empty, error) { return &empty.Empty{}, nil }, SetBatchF: func(ctx context.Context, in *schema.KVList, opts ...grpc.CallOption) (*schema.Index, error) { return &schema.Index{}, nil }, GetBatchF: func(ctx context.Context, in *schema.KeyList, opts ...grpc.CallOption) (*schema.ItemList, error) { return &schema.ItemList{}, nil }, ExecAllOpsF: func(ctx context.Context, in *schema.Ops, opts ...grpc.CallOption) (*schema.Index, error) { return &schema.Index{}, nil }, InclusionF: func(ctx context.Context, in *schema.Index, opts ...grpc.CallOption) (*schema.InclusionProof, error) { return &schema.InclusionProof{}, nil }, ConsistencyF: func(ctx context.Context, in *schema.Index, opts ...grpc.CallOption) (*schema.ConsistencyProof, error) { return &schema.ConsistencyProof{}, nil }, ByIndexF: func(ctx context.Context, in *schema.Index, opts ...grpc.CallOption) (*schema.Item, error) { return &schema.Item{}, nil }, } return bs } */
// Copyright 2019 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 opt // DefaultJoinOrderLimit denotes the default limit on the number of joins to // reorder. const DefaultJoinOrderLimit = 8 // MaxReorderJoinsLimit is the maximum number of joins which can be reordered. const MaxReorderJoinsLimit = 63 // SaveTablesDatabase is the name of the database where tables created by // the saveTableNode are stored. const SaveTablesDatabase = "savetables"
package nodes import ( "context" "os" "time" dynatracev1beta1 "github.com/Dynatrace/dynatrace-operator/src/api/v1beta1" "github.com/Dynatrace/dynatrace-operator/src/controllers/dynakube/dynatraceclient" "github.com/Dynatrace/dynatrace-operator/src/controllers/dynakube/token" "github.com/Dynatrace/dynatrace-operator/src/dtclient" "github.com/Dynatrace/dynatrace-operator/src/kubeobjects" "github.com/Dynatrace/dynatrace-operator/src/kubesystem" "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" k8serrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/controller-runtime/pkg/event" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/predicate" "sigs.k8s.io/controller-runtime/pkg/reconcile" ) type Controller struct { client client.Client apiReader client.Reader scheme *runtime.Scheme dynatraceClientBuilder dynatraceclient.Builder runLocal bool podNamespace string } type CachedNodeInfo struct { cachedNode CacheEntry nodeCache *Cache nodeName string } func Add(mgr manager.Manager, _ string) error { return NewController(mgr).SetupWithManager(mgr) } func (controller *Controller) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&corev1.Node{}). WithEventFilter(nodeDeletionPredicate(controller)). Complete(controller) } func nodeDeletionPredicate(controller *Controller) predicate.Predicate { return predicate.Funcs{ DeleteFunc: func(deleteEvent event.DeleteEvent) bool { node := deleteEvent.Object.GetName() err := controller.reconcileNodeDeletion(context.TODO(), node) if err != nil { log.Error(err, "error while deleting node", "node", node) } return false }, } } func NewController(mgr manager.Manager) *Controller { return &Controller{ client: mgr.GetClient(), apiReader: mgr.GetAPIReader(), scheme: mgr.GetScheme(), dynatraceClientBuilder: dynatraceclient.NewBuilder(mgr.GetAPIReader()), runLocal: kubesystem.IsRunLocally(), podNamespace: os.Getenv("POD_NAMESPACE"), } } func (controller *Controller) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { nodeName := request.NamespacedName.Name dynakube, err := controller.determineDynakubeForNode(nodeName) if err != nil { return reconcile.Result{}, err } nodeCache, err := controller.getCache(ctx) if err != nil { return reconcile.Result{}, err } var node corev1.Node if err := controller.apiReader.Get(ctx, client.ObjectKey{Name: nodeName}, &node); err != nil { if k8serrors.IsNotFound(err) { log.Info("node was not found in cluster", "node", nodeName) return reconcile.Result{}, nil } return reconcile.Result{}, err } // Node is found in the cluster, add or update to cache if dynakube != nil { var ipAddress = dynakube.Status.OneAgent.Instances[nodeName].IPAddress cacheEntry := CacheEntry{ Instance: dynakube.Name, IPAddress: ipAddress, LastSeen: time.Now().UTC(), } if cached, err := nodeCache.Get(nodeName); err == nil { cacheEntry.LastMarkedForTermination = cached.LastMarkedForTermination } if err := nodeCache.Set(nodeName, cacheEntry); err != nil { return reconcile.Result{}, err } // Handle unschedulable Nodes, if they have a OneAgent instance if controller.isUnschedulable(&node) { cachedNodeData := CachedNodeInfo{ cachedNode: cacheEntry, nodeCache: nodeCache, nodeName: nodeName, } if err := controller.markForTermination(dynakube, cachedNodeData); err != nil { return reconcile.Result{}, err } } } // check node cache for outdated nodes and remove them, to keep cache clean if nodeCache.IsCacheOutdated() { if err := controller.handleOutdatedCache(ctx, nodeCache); err != nil { return reconcile.Result{}, err } nodeCache.UpdateTimestamp() } return reconcile.Result{}, controller.updateCache(ctx, nodeCache) } func (controller *Controller) reconcileNodeDeletion(ctx context.Context, nodeName string) error { nodeCache, err := controller.getCache(ctx) if err != nil { return err } dynakube, err := controller.determineDynakubeForNode(nodeName) if err != nil { return err } cachedNodeInfo, err := nodeCache.Get(nodeName) if err != nil { if errors.Is(err, ErrNotFound) { // uncached node -> ignoring return nil } return err } if dynakube != nil { cachedNodeData := CachedNodeInfo{ cachedNode: cachedNodeInfo, nodeCache: nodeCache, nodeName: nodeName, } if err := controller.markForTermination(dynakube, cachedNodeData); err != nil { return err } } nodeCache.Delete(nodeName) if err := controller.updateCache(ctx, nodeCache); err != nil { return err } return nil } func (controller *Controller) getCache(ctx context.Context) (*Cache, error) { var cm corev1.ConfigMap err := controller.apiReader.Get(ctx, client.ObjectKey{Name: cacheName, Namespace: controller.podNamespace}, &cm) if err == nil { return &Cache{Obj: &cm}, nil } if k8serrors.IsNotFound(err) { cm := &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: cacheName, Namespace: controller.podNamespace, }, Data: map[string]string{}, } if !controller.runLocal { // If running locally, don't set the controller. deploy, err := kubeobjects.GetDeployment(controller.client, os.Getenv("POD_NAME"), controller.podNamespace) if err != nil { return nil, err } if err = controllerutil.SetControllerReference(deploy, cm, controller.scheme); err != nil { return nil, err } } return &Cache{Create: true, Obj: cm}, nil } return nil, err } func (controller *Controller) updateCache(ctx context.Context, nodeCache *Cache) error { if !nodeCache.Changed() { return nil } if nodeCache.Create { return controller.client.Create(context.TODO(), nodeCache.Obj) } if err := controller.client.Update(ctx, nodeCache.Obj); err != nil { return err } return nil } func (controller *Controller) handleOutdatedCache(ctx context.Context, nodeCache *Cache) error { var nodeLst corev1.NodeList if err := controller.client.List(context.TODO(), &nodeLst); err != nil { return err } for _, cachedNodeName := range nodeCache.Keys() { cachedNodeInCluster := false for _, clusterNode := range nodeLst.Items { if clusterNode.Name == cachedNodeName { cachedNodeInfo, err := nodeCache.Get(cachedNodeName) if err != nil { log.Error(err, "failed to get node", "node", cachedNodeName) return err } cachedNodeInCluster = true // Check if node was seen less than an hour ago, otherwise do not remove from cache controller.removeNodeFromCache(nodeCache, cachedNodeInfo, cachedNodeName) break } } // if node is not in cluster -> probably deleted if !cachedNodeInCluster { log.Info("Removing missing cached node from cluster", "node", cachedNodeName) err := controller.reconcileNodeDeletion(ctx, cachedNodeName) if err != nil { return err } } } return nil } func (controller *Controller) removeNodeFromCache(nodeCache *Cache, cachedNode CacheEntry, nodeName string) { if controller.isNodeDeletable(cachedNode) { nodeCache.Delete(nodeName) } } func (controller *Controller) isNodeDeletable(cachedNode CacheEntry) bool { if time.Now().UTC().Sub(cachedNode.LastSeen).Hours() > 1 { return true } else if cachedNode.IPAddress == "" { return true } return false } func (controller *Controller) sendMarkedForTermination(dynakubeInstance *dynatracev1beta1.DynaKube, cachedNode CacheEntry) error { tokenReader := token.NewReader(controller.apiReader, dynakubeInstance) tokens, err := tokenReader.ReadTokens(context.TODO()) if err != nil { return err } dynatraceClient, err := controller.dynatraceClientBuilder. SetDynakube(*dynakubeInstance). SetTokens(tokens). Build() if err != nil { return err } entityID, err := dynatraceClient.GetEntityIDForIP(cachedNode.IPAddress) if err != nil { log.Info("failed to send mark for termination event", "reason", "failed to determine entity id", "dynakube", dynakubeInstance.Name, "nodeIP", cachedNode.IPAddress, "cause", err) return err } ts := uint64(cachedNode.LastSeen.Add(-10*time.Minute).UnixNano()) / uint64(time.Millisecond) return dynatraceClient.SendEvent(&dtclient.EventData{ EventType: dtclient.MarkedForTerminationEvent, Source: "Dynatrace Operator", Description: "Kubernetes node cordoned. Node might be drained or terminated.", StartInMillis: ts, EndInMillis: ts, AttachRules: dtclient.EventDataAttachRules{ EntityIDs: []string{entityID}, }, }) } func (controller *Controller) markForTermination(dynakube *dynatracev1beta1.DynaKube, cachedNodeData CachedNodeInfo) error { if !controller.isMarkableForTermination(&cachedNodeData.cachedNode) { return nil } if err := cachedNodeData.nodeCache.updateLastMarkedForTerminationTimestamp(cachedNodeData.cachedNode, cachedNodeData.nodeName); err != nil { return err } log.Info("sending mark for termination event to dynatrace server", "dynakube", dynakube.Name, "ip", cachedNodeData.cachedNode.IPAddress, "node", cachedNodeData.nodeName) return controller.sendMarkedForTermination(dynakube, cachedNodeData.cachedNode) } func (controller *Controller) isUnschedulable(node *corev1.Node) bool { return node.Spec.Unschedulable || controller.hasUnschedulableTaint(node) } func (controller *Controller) hasUnschedulableTaint(node *corev1.Node) bool { for _, taint := range node.Spec.Taints { for _, unschedulableTaint := range unschedulableTaints { if taint.Key == unschedulableTaint { return true } } } return false } // isMarkableForTermination checks if the timestamp from last mark is at least one hour old func (controller *Controller) isMarkableForTermination(nodeInfo *CacheEntry) bool { // If the last mark was an hour ago, mark again // Zero value for time.Time is 0001-01-01, so first mark is also executed lastMarked := nodeInfo.LastMarkedForTermination return lastMarked.UTC().Add(time.Hour).Before(time.Now().UTC()) }
package main import ( "fmt" "math/rand" "regexp" "time" "github.com/google/go-github/github" "golang.org/x/oauth2" ) func handleIssueCommentEvent(event GithubIssueCommentPayload) error { reviewersAskCommentRegexp := regexp.MustCompile(`^@` + BOT_NAME + `[\s]+assign[\s]+([a-z]+)[\s]+reviewers`) matches := reviewersAskCommentRegexp.FindStringSubmatch(event.Comment.Body) // No match, skip this issue comment if matches == nil { return nil } matchedTeamName := matches[1] // Find the team that is targeted var team *Team = nil for _, t := range TEAMS { if t.Name == matchedTeamName { team = &t } } // The given team name doesn't exist if team == nil { comment := fmt.Sprintf("'%v' is not a team I know about!", matchedTeamName) return createGithubIssueComment(event, comment) } // Attempt to pick a senior and a junior random := rand.New(rand.NewSource(time.Now().UnixNano())) senior := "" if len(team.Seniors) > 0 { senior = team.Seniors[random.Intn(len(team.Seniors))] } junior := "" if len(team.Juniors) > 0 { junior = team.Juniors[random.Intn(len(team.Juniors))] } var comment string if senior != "" && junior != "" { comment = fmt.Sprintf("Heck yeah! @%v and @%v: please review :)", senior, junior) } else if senior != "" { comment = fmt.Sprintf("I propose @%v as reviewer!", senior) } else if junior != "" { comment = fmt.Sprintf("I propose @%v as reviewer!", junior) } else { comment = fmt.Sprint("I couldn't find anybody to propose as reviewers!") } return createGithubIssueComment(event, comment) } func createGithubIssueComment(event GithubIssueCommentPayload, body string) error { client := createGithubClient() _, _, err := client.Issues.CreateComment( event.Repository.Owner.Login, event.Repository.Name, event.Issue.Number, &github.IssueComment{Body: &body}, ) return err } func createGithubClient() *github.Client { ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: GITHUB_TOKEN}, ) tc := oauth2.NewClient(oauth2.NoContext, ts) return github.NewClient(tc) }
package main import ( "coco_tools/DLFS" "coco_tools/data" "database/sql" "fmt" "image" "image/draw" "image/jpeg" "io/ioutil" "log" "os" "path" "sync" "time" ) type dataset struct { db *sql.DB fbData *DLFS.Dataset dataDir string outputPath string } func (ds *dataset) Open(fbsFilename string, sqliteFilename string, dataDir string) error { // Open a connection to the sqlite database db, err := data.OpenDB(fmt.Sprintf("file:%s?cache=shared&_sync=0", sqliteFilename)) if err != nil { log.Fatal(err) return nil } ds.db = db ds.dataDir = dataDir // Open the flatbuffer file. buf, err := ioutil.ReadFile(fbsFilename) ds.fbData = DLFS.GetRootAsDataset(buf, 0) return nil } func (ds *dataset) buildCategoriesTable() error { numCats := ds.fbData.CategoriesLength() for idx := 0; idx < numCats; idx++ { cat := new(DLFS.Category) if ds.fbData.Categories(cat, idx) { _, err := ds.db.Exec("insert into categories (id, name, cocoid) values (?,?,?)", idx, cat.Name(), cat.Id()) if err != nil { return err } } } return nil } func (ds *dataset) buildImagesTable() error { counts := make([]int, 2) stmt, err := ds.db.Prepare("insert into images (filename) values(?)") if err != nil { log.Fatal(err) } for i := 0; i < ds.fbData.ExamplesLength(); i++ { ex := new(DLFS.Example) if ds.fbData.Examples(ex, i) { _, err := stmt.Exec(string(ex.FileName())) if err != nil { counts[1]++ continue } counts[0]++ } } fmt.Println("Insertion results: ", counts) return nil } func (ds *dataset) createThumbnails(exampleIdx int, outputPath string) error { ex := new(DLFS.Example) if ds.fbData.Examples(ex, exampleIdx) { filename := path.Join(ds.dataDir, string(ex.FileName())) file, err := os.Open(filename) if err != nil { return err } imgData, err := jpeg.Decode(file) if err != nil { log.Println(filename) return err } file.Close() // Get the annotations numAnn := ex.AnnotationsLength() for i := 0; i < numAnn; i++ { // Load the ann ann := new(DLFS.Annotation) ex.Annotations(ann, i) if ann == nil { return fmt.Errorf("Could not retrieve annotation") } // Convert source rectangle to dst image space var bbox *DLFS.BoundingBox = ann.Bbox(nil) imgBox := image.Rectangle{image.Point{int(bbox.X1()), int(bbox.Y1())}, image.Point{int(bbox.X2()), int(bbox.Y2())}} // Create image tbImage := image.NewRGBA(imgBox) draw.Draw(tbImage, tbImage.Bounds(), imgData, imgBox.Bounds().Min, draw.Src) tbFilename := path.Join(outputPath, fmt.Sprintf("%d-%d-tb.jpg", ex.Id(), i)) outfile, err := os.Create(tbFilename) if err != nil { return err } err = jpeg.Encode(outfile, tbImage, nil) if err != nil { return err } outfile.Close() _, err = ds.db.Exec("insert into thumbnails (filename, category, example_idx, width, height, area) values (?,?,?,?,?,?)", tbFilename, ann.CatId(), ex.Idx(), imgBox.Size().X, imgBox.Size().Y, imgBox.Size().X*imgBox.Size().Y) if err != nil { return err } } return nil } return fmt.Errorf("No such example") } func spinner(delay time.Duration) { for { for _, r := range `-\|/` { fmt.Printf("\r%c", r) time.Sleep(delay) } } } func main() { if len(os.Args) < 4 { usage := fmt.Sprintf("Usage: %s localDB fbsFile dataDir", os.Args[0]) fmt.Println(usage) return } dbFile := os.Args[1] fbsFile := os.Args[2] dataDir := os.Args[3] startTime := time.Now() var ds dataset err := ds.Open(fbsFile, dbFile, dataDir) if err != nil { log.Fatal(err) } parallelism := 10 idxChannel := make(chan int, parallelism) errorChannel := make(chan error, parallelism) var wg sync.WaitGroup numImgs := ds.fbData.ExamplesLength() go func(total int) { for j := 0; j < 100000; j++ { idxChannel <- j } close(idxChannel) }(numImgs) for i := 0; i < parallelism; i++ { wg.Add(1) go func(idx int, ds *dataset) { defer wg.Done() for idx := range idxChannel { err := ds.createThumbnails(idx, "/home/chris/datasets/coco/thumbnails") errorChannel <- err } }(i, &ds) } go func(total int) { doneCnt := 0 errCnt := 0 spinString := string(`-\|/`) spinIdx := 0 for err := range errorChannel { if err != nil { errCnt++ log.Println(err) } else { doneCnt++ } fmt.Printf("\r%c %d/%d done %d errors", spinString[spinIdx%len(spinString)], doneCnt, total, errCnt) spinIdx++ } fmt.Println("\n Limit reached.") }(numImgs) wg.Wait() close(errorChannel) endTime := time.Now() elapsed := endTime.Sub(startTime) log.Printf("Done %.3f elapsd", elapsed.Seconds()) time.Sleep(time.Second * 1) }
// Copyright 2021 Comcast Cable Communications Management, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package quota_test import ( "context" "errors" "fmt" "github.com/xmidt-org/ears/internal/pkg/quota" "github.com/xmidt-org/ears/pkg/tenant" "testing" "time" ) func TestQuotaLimiter(t *testing.T) { limiter := quota.NewQuotaLimiter(tenant.Id{OrgId: "myOrg", AppId: "myApp"}, "inmemory", "", 1, 12) var err error for i := 0; i < 3; i++ { //validate that we can do 1rps err = validateRps(limiter, 1) if err == nil { break } if errors.Is(err, TestErr_FailToReachRps) { continue } t.Fatalf("Fail to reach the desired rps, error=%s\n", err.Error()) } if err != nil { t.Fatalf("Fail to reach the desired rps in 3 tries") } for i := 0; i < 3; i++ { //validate that we can do 2rps err = validateRps(limiter, 2) if err == nil { break } if errors.Is(err, TestErr_FailToReachRps) { time.Sleep(time.Second) continue } t.Fatalf("Fail to reach the desired rps, error=%s\n", err.Error()) } if err != nil { t.Fatalf("Fail to reach the desired rps in 3 tries") } for i := 0; i < 3; i++ { //validate that we can do 8rps err = validateRps(limiter, 8) if err == nil { break } if errors.Is(err, TestErr_FailToReachRps) { continue } t.Fatalf("Fail to reach the desired rps, error=%s\n", err.Error()) } if err != nil { t.Fatalf("Fail to reach the desired rps in 3 tries") } limiter.SetLimit(100) for i := 0; i < 10; i++ { //validate that we can do 80rps err = validateRps(limiter, 80) if err == nil { break } if err.Error() == "Cannot reach desired RPS" { continue } t.Fatalf("Fail to reach the desired rps, error=%s\n", err.Error()) } if err != nil { t.Fatalf("Fail to reach the desired rps in 3 tries") } limiter.SetLimit(1000) for i := 0; i < 10; i++ { //validate that we can do 80rps err = validateRps(limiter, 800) if err == nil { break } if err.Error() == "Cannot reach desired RPS" { continue } t.Fatalf("Fail to reach the desired rps, error=%s\n", err.Error()) } if err != nil { t.Fatalf("Fail to reach the desired rps in 3 tries") } } func validateRps(limiter *quota.QuotaLimiter, rps int) error { ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() start := time.Now() count := 0 for i := 0; i < rps; i++ { err := limiter.Wait(ctx) if err != nil { return err } count++ } fmt.Printf("elapsed time=%dms, adaptiveLimit=%d\n", time.Since(start).Milliseconds(), limiter.AdaptiveLimit()) if start.Add(time.Second + time.Millisecond*100).After(time.Now()) { return nil } return TestErr_FailToReachRps }
package repository import ( "belajar-golang-restful-api/model/domain" "context" "database/sql" ) type CatagoryRepository interface { Save(ctx context.Context, tx *sql.Tx, catagory domain.Catagory) domain.Catagory Update(ctx context.Context, tx *sql.Tx, catagory domain.Catagory) domain.Catagory Delete(ctx context.Context, tx *sql.Tx, catagory domain.Catagory) FindById(ctx context.Context, tx *sql.Tx, catagoryId int) (domain.Catagory, error) FindAll(ctx context.Context, tx *sql.Tx) []domain.Catagory }
package orb // LineString represents a set of points to be thought of as a polyline. type LineString []Point // GeoJSONType returns the GeoJSON type for the object. func (ls LineString) GeoJSONType() string { return "LineString" } // Dimensions returns 1 because a LineString is a 1d object. func (ls LineString) Dimensions() int { return 1 } // Reverse will reverse the line string. // This is done inplace, ie. it modifies the original data. func (ls LineString) Reverse() { l := len(ls) - 1 for i := 0; i <= l/2; i++ { ls[i], ls[l-i] = ls[l-i], ls[i] } } // Bound returns a rect around the line string. Uses rectangular coordinates. func (ls LineString) Bound() Bound { return MultiPoint(ls).Bound() } // Equal compares two line strings. Returns true if lengths are the same // and all points are Equal. func (ls LineString) Equal(lineString LineString) bool { return MultiPoint(ls).Equal(MultiPoint(lineString)) } // Clone returns a new copy of the line string. func (ls LineString) Clone() LineString { ps := MultiPoint(ls) return LineString(ps.Clone()) }
package main import "learngo/book/conditionaljudgment/switchJudge/_switch" func main() { //_switch.SwitchBase() _switch.TypeSwitch() }
package handler import ( "net/http" "github.com/Lunchr/luncher-api/db" "github.com/Lunchr/luncher-api/db/model" "github.com/Lunchr/luncher-api/router" ) func Tags(tagsCollection db.Tags) router.Handler { return func(w http.ResponseWriter, r *http.Request) *router.HandlerError { tagsIter := tagsCollection.GetAll() var tags []model.Tag var tag model.Tag for tagsIter.Next(&tag) { tags = append(tags, tag) } if err := tagsIter.Close(); err != nil { return router.NewHandlerError(err, "An error occured while fetching the tags from the DB", http.StatusInternalServerError) } return writeJSON(w, tags) } }
package api import ( "github.com/go-macaron/binding" "github.com/ssok8s/ssok8s/pkg/api/dtos" "github.com/ssok8s/ssok8s/pkg/api/routing" "github.com/ssok8s/ssok8s/pkg/middleware" ) func (hs *HTTPServer) registerRoutes() { reqSignedIn := middleware.ReqSignedIn reqAdmin := middleware.ReqAdmin //reqTenant := middleware.ReqTenant reqSRP := middleware.ReqSRP reqMarketplace := middleware.ReqMarketplace reqMarketplaceOrAdmin := middleware.ReqMarketplaceOrAdmin reqSRPOrWKAdmin := middleware.ReqSRPOrWkAdmin reqDeveloperRole := middleware.ReqDeveloperRole reqWorkspaceAdminRole := middleware.ReqWorkspaceAdminRole reqClusterOwner := middleware.ReqClusterOwner reqClusterAdmin := middleware.ReqClusterAdmin reqDdtacenterAdmin := middleware.ReqDdtacenterAdmin reqGlobalAdmin := middleware.ReqGlobalAdmin r := hs.RouteRegister macaronR := hs.macaron macaronR.SetAutoHead(true) bind := binding.Bind r.Get("/hello",reqDeveloperRole,reqSRP,reqSRPOrWKAdmin,reqMarketplace,reqMarketplaceOrAdmin,Wrap(Hello)) r.Get("/hellot2",reqGlobalAdmin,reqDdtacenterAdmin,reqDeveloperRole,Wrap(Hello)) r.Post("/authtest",reqWorkspaceAdminRole,bind(dtos.AuthForm{}),Wrap(authTest)) r.Get("/redis/get",reqClusterOwner,reqAdmin,Wrap(redisGet)) r.Get("/redis/set",reqClusterAdmin,Wrap(redisSet)) r.Delete("/redis/del",Wrap(redisDel)) r.Group("/v3.0", func(apiRoute routing.RouteRegister) { apiRoute.Group("/auth",func(authRoute routing.RouteRegister){ authRoute.Post("/",bind(dtos.AuthForm{}),Wrap(login)) authRoute.Delete("/",Wrap(logout)) authRoute.Post("/native",bind(dtos.AuthForm{}),Wrap(LoginNative)) }) apiRoute.Group("/oauth", func(oauthRoute routing.RouteRegister) { oauthRoute.Get("/authorize",grantCode) oauthRoute.Post("/token",Wrap(grantToken)) }) apiRoute.Group("/token", func(tokenRoute routing.RouteRegister) { tokenRoute.Post("/",bind(dtos.RefreshTokenForm{}),Wrap(tokenRefresh)) tokenRoute.Post("/tokenvalidation",bind(dtos.RefreshTokenForm{}),Wrap(tokenValidate)) }) apiRoute.Get("/userinfo",reqSignedIn,Wrap(GetUserInfo)) apiRoute.Group("/users", func(userRoute routing.RouteRegister){ userRoute.Get("/me",reqSignedIn, Wrap(GetUserMe)) userRoute.Get("/userinfo",reqSignedIn, Wrap(GetUserInfo)) userRoute.Get("/fuzzyusers",reqWorkspaceAdminRole,Wrap(listUsers)) userRoute.Get("/wiseUser",reqSignedIn, Wrap(wiseUser)) userRoute.Get("/:username/regemail",Wrap(regemail)) userRoute.Post("/",reqWorkspaceAdminRole,bind(dtos.CreateUserForm{}),Wrap(CreateUser)) userRoute.Delete("/:username/pwdresetemail",Wrap(resetPasswordEmail)) userRoute.Patch("/:username/password",bind(dtos.UpdatePasswordForm{}),Wrap(userPassword)) userRoute.Post("/password/codevalide",bind(dtos.PasswordCodeValidateForm{}),Wrap(pwdCodeValide)) userRoute.Delete("/:username",reqWorkspaceAdminRole,Wrap(deleteUser)) userRoute.Put("/:username",bind(dtos.UpdateUserForm{}),Wrap(UpdateUser)) userRoute.Patch("/:username/scopes",reqAdmin,bind(dtos.ScopeOperation{}),Wrap(UpdateUserScopes)) } ) apiRoute.Post("/group",reqMarketplaceOrAdmin,bind(dtos.GroupForm{}),Wrap(createGroup)) apiRoute.Group("/group/:groupId", func(groupRoute routing.RouteRegister){ groupRoute.Put("/",bind(dtos.GroupForm{}),Wrap(updateGroup)) groupRoute.Get("/",Wrap(getGroup)) groupRoute.Delete("/",Wrap(deleteGroup)) groupRoute.Get("/users",Wrap(getGroupUsers)) groupRoute.Post("/users",bind(dtos.GroupUserFrom{}),Wrap(addGroupUser)) groupRoute.Put("/users/:userId",bind(dtos.UpdateGroupUserFrom{}),Wrap(updateGroupUser)) groupRoute.Delete("/users/:userId",Wrap(deleteGroupUser)) }) apiRoute.Group("/srps", func(srpRout routing.RouteRegister) { srpRout.Post("/",reqSRP,bind(dtos.CreateSrpForm{}),Wrap(createSrp)) srpRout.Get("/",reqSRP,Wrap(getSrps)) srpRout.Delete("/:srpId",reqSRP,Wrap(deleteSrp)) srpRout.Get("/fuzzysrps",reqWorkspaceAdminRole,Wrap(listSrp)) srpRout.Get("/:srpIdOrName",reqSRP,Wrap(getSrpByIdOrName)) srpRout.Put("/:srpId",reqSRP,bind(dtos.CreateSrpForm{}),Wrap(updateSrp)) srpRout.Post("/:srpId/users",reqSRP,bind(dtos.SrpUserForm{}),Wrap(createBySrp)) srpRout.Get("/:srpId/tenant",reqSRP,Wrap(ListWorkSpaceAdminBySrp)) }) apiRoute.Group("/mailqueues",func(mailqueue routing.RouteRegister){ mailqueue.Post("/",reqAdmin,bind(dtos.MailQueueForm{}),Wrap(sendMail)) }) }) r.Register(macaronR) }