text
stringlengths
11
4.05M
// This file was generated for SObject ActionLinkTemplate, API Version v43.0 at 2018-07-30 03:47:58.55727601 -0400 EDT m=+44.901567272 package sobjects import ( "fmt" "strings" ) type ActionLinkTemplate struct { BaseSObject ActionLinkGroupTemplateId string `force:",omitempty"` ActionUrl string `force:",omitempty"` CreatedById string `force:",omitempty"` CreatedDate string `force:",omitempty"` Headers string `force:",omitempty"` Id string `force:",omitempty"` IsConfirmationRequired bool `force:",omitempty"` IsDeleted bool `force:",omitempty"` IsGroupDefault bool `force:",omitempty"` Label string `force:",omitempty"` LabelKey string `force:",omitempty"` LastModifiedById string `force:",omitempty"` LastModifiedDate string `force:",omitempty"` LinkType string `force:",omitempty"` Method string `force:",omitempty"` Position int `force:",omitempty"` RequestBody string `force:",omitempty"` SystemModstamp string `force:",omitempty"` UserAlias string `force:",omitempty"` UserVisibility string `force:",omitempty"` } func (t *ActionLinkTemplate) ApiName() string { return "ActionLinkTemplate" } func (t *ActionLinkTemplate) String() string { builder := strings.Builder{} builder.WriteString(fmt.Sprintf("ActionLinkTemplate #%s - %s\n", t.Id, t.Name)) builder.WriteString(fmt.Sprintf("\tActionLinkGroupTemplateId: %v\n", t.ActionLinkGroupTemplateId)) builder.WriteString(fmt.Sprintf("\tActionUrl: %v\n", t.ActionUrl)) builder.WriteString(fmt.Sprintf("\tCreatedById: %v\n", t.CreatedById)) builder.WriteString(fmt.Sprintf("\tCreatedDate: %v\n", t.CreatedDate)) builder.WriteString(fmt.Sprintf("\tHeaders: %v\n", t.Headers)) builder.WriteString(fmt.Sprintf("\tId: %v\n", t.Id)) builder.WriteString(fmt.Sprintf("\tIsConfirmationRequired: %v\n", t.IsConfirmationRequired)) builder.WriteString(fmt.Sprintf("\tIsDeleted: %v\n", t.IsDeleted)) builder.WriteString(fmt.Sprintf("\tIsGroupDefault: %v\n", t.IsGroupDefault)) builder.WriteString(fmt.Sprintf("\tLabel: %v\n", t.Label)) builder.WriteString(fmt.Sprintf("\tLabelKey: %v\n", t.LabelKey)) builder.WriteString(fmt.Sprintf("\tLastModifiedById: %v\n", t.LastModifiedById)) builder.WriteString(fmt.Sprintf("\tLastModifiedDate: %v\n", t.LastModifiedDate)) builder.WriteString(fmt.Sprintf("\tLinkType: %v\n", t.LinkType)) builder.WriteString(fmt.Sprintf("\tMethod: %v\n", t.Method)) builder.WriteString(fmt.Sprintf("\tPosition: %v\n", t.Position)) builder.WriteString(fmt.Sprintf("\tRequestBody: %v\n", t.RequestBody)) builder.WriteString(fmt.Sprintf("\tSystemModstamp: %v\n", t.SystemModstamp)) builder.WriteString(fmt.Sprintf("\tUserAlias: %v\n", t.UserAlias)) builder.WriteString(fmt.Sprintf("\tUserVisibility: %v\n", t.UserVisibility)) return builder.String() } type ActionLinkTemplateQueryResponse struct { BaseQuery Records []ActionLinkTemplate `json:"Records" force:"records"` }
package main import ( "fmt" "os" "strconv" "github.com/hackebrot/gofizzbuzz/gofizzbuzz" ) func main() { for _, s := range os.Args[1:] { i, err := strconv.Atoi(s) if err == nil { w := gofizzbuzz.GoFizzBuzz(i) fmt.Println(w) } } }
package data type Category struct { Id int Status int Order int Name string Color string Pics string }
package main func main() { } func firstUniqChar(s string) byte { mm := make(map[rune]int) for _, v := range s { mm[v]++ } for _, v := range s { if mm[v] == 1 { return byte(v) } } return ' ' }
// Package main - задание четвертого урока для курса go-core. package main import ( "fmt" "go.core/lesson4/pkg/crawler" "go.core/lesson4/pkg/crawler/spider" "go.core/lesson4/pkg/document" "go.core/lesson4/pkg/index" "sort" "strings" ) func main() { urls := []string{"https://golangs.org", "https://altech.online"} fmt.Print("Сканирование сайтов ") var s spider.Scanner docs, err := crawler.Scan(s, urls, 2) if err != nil { return } fmt.Println("завершено.") fmt.Print("Индексирование страниц ") storage := index.New() storage.Init(docs) fmt.Println("завершено.") var q string for { fmt.Print("Введите поисковый запрос: ") _, err := fmt.Scanf("%s\n", &q) if err != nil { fmt.Println("Программа завершила работу.") return } IDs := storage.Find(strings.ToLower(q)) res := find(IDs, docs) fmt.Printf("Результаты поиска по запросу \"%s\":\nНайдено всего: %d\n", q, len(res)) for _, doc := range res { fmt.Println(doc) } } } func find(IDs []int, d []document.Documenter) (res []document.Documenter) { for _, id := range IDs { idx := sort.Search(len(d), func(i int) bool { return d[i].Id() >= id }) if idx < len(d) { res = append(res, d[idx]) } } return res }
// Copyright 2020 MongoDB 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 convert import ( "errors" "fmt" "strconv" "go.mongodb.org/ops-manager/opsmngr" "go.mongodb.org/ops-manager/search" ) const ( zero = "0" one = "1" file = "file" fcvLessThanFour = "< 4.0" mongos = "mongos" ) // ClusterConfig configuration for a cluster // This cluster can be used to patch an automation config type ClusterConfig struct { RSConfig `yaml:",inline"` MongoURI string `yaml:"mongoURI,omitempty" json:"mongoURI,omitempty"` Shards []*RSConfig `yaml:"shards,omitempty" json:"shards,omitempty"` Config *RSConfig `yaml:"config,omitempty" json:"config,omitempty"` Mongos []*ProcessConfig `yaml:"mongos,omitempty" json:"mongos,omitempty"` } // newReplicaSetCluster when config is a replicaset func newReplicaSetCluster(name string, s int) *ClusterConfig { rs := &ClusterConfig{} rs.Name = name rs.ProcessConfigs = make([]*ProcessConfig, s) return rs } // newShardedCluster when config is a sharded cluster func newShardedCluster(s *opsmngr.ShardingConfig) *ClusterConfig { rs := &ClusterConfig{} rs.Name = s.Name rs.Shards = make([]*RSConfig, len(s.Shards)) rs.Mongos = make([]*ProcessConfig, 0, 1) rs.Tags = s.Tags return rs } // PatchAutomationConfig adds the ClusterConfig to a opsmngr.AutomationConfig // this method will modify the given AutomationConfig to add the new replica set or sharded cluster information func (c *ClusterConfig) PatchAutomationConfig(out *opsmngr.AutomationConfig) error { // A replica set should be just a list of processes if c.ProcessConfigs != nil && c.Mongos == nil && c.Shards == nil && c.Config == nil { return c.patchReplicaSet(out) } // a sharded cluster will be a a list of mongos (processes), // shards, each with a list of process (replica sets) // one (1) config server, with a list of process (replica set) if c.ProcessConfigs == nil && c.Mongos != nil && c.Shards != nil && c.Config != nil { return c.pathSharding(out) } return errors.New("invalid config") } func (c *ClusterConfig) pathSharding(out *opsmngr.AutomationConfig) error { newCluster := newShardingConfig(c) // transform cli config to automation config for i, s := range c.Shards { s.Version = c.Version s.FCVersion = c.FCVersion if err := s.patchShard(out, c.Name); err != nil { return err } newCluster.Shards[i] = newShard(s) } c.Config.Version = c.Version c.Config.FCVersion = c.FCVersion if err := c.Config.patchConfigServer(out, c.Name); err != nil { return err } newProcesses := make([]*opsmngr.Process, len(c.Mongos)) for i, pc := range c.Mongos { pc.ProcessType = mongos pc.setDefaults(&c.RSConfig) pc.setProcessName(out.Processes, c.Name, "mongos", strconv.Itoa(len(out.Processes)+i)) newProcesses[i] = newMongosProcess(pc, c.Name) } // This value may not be present and is mandatory if out.Auth.DeploymentAuthMechanisms == nil { out.Auth.DeploymentAuthMechanisms = make([]string, 0) } patchProcesses(out, newCluster.Name, newProcesses) patchSharding(out, newCluster) return nil } func (c *ClusterConfig) addToMongoURI(p *opsmngr.Process) { if c.MongoURI == "" { c.MongoURI = fmt.Sprintf("mongodb://%s:%d", p.Hostname, p.Args26.NET.Port) } else { c.MongoURI = fmt.Sprintf("%s,%s:%d", c.MongoURI, p.Hostname, p.Args26.NET.Port) } } func newShard(rsConfig *RSConfig) *opsmngr.Shard { s := &opsmngr.Shard{ ID: rsConfig.Name, RS: rsConfig.Name, Tags: rsConfig.Tags, } if s.Tags == nil { s.Tags = make([]string, 0) } return s } func newShardingConfig(c *ClusterConfig) *opsmngr.ShardingConfig { rs := &opsmngr.ShardingConfig{ Name: c.Name, Shards: make([]*opsmngr.Shard, len(c.Shards)), ConfigServerReplica: c.Config.Name, Tags: c.Tags, Draining: make([]string, 0), Collections: make([]*map[string]interface{}, 0), } if rs.Tags == nil { rs.Tags = make([]string, 0) } return rs } // patchProcesses replace replica set processes with new configuration // this will disable all existing processes for the given replica set and remove the association // Then try to patch then with the new config if one config exists for the same host:port func patchProcesses(out *opsmngr.AutomationConfig, newReplicaSetID string, newProcesses []*opsmngr.Process) { for i, oldProcess := range out.Processes { if oldProcess.Args26.Replication != nil && oldProcess.Args26.Replication.ReplSetName == newReplicaSetID { oldProcess.Disabled = true oldProcess.Args26.Replication = new(opsmngr.Replication) } oldName := oldProcess.Name pos, found := search.Processes(newProcesses, func(p *opsmngr.Process) bool { return p.Name == oldName }) if found { out.Processes[i] = newProcesses[pos] newProcesses = append(newProcesses[:pos], newProcesses[pos+1:]...) } } if len(newProcesses) > 0 { out.Processes = append(out.Processes, newProcesses...) } } // patchReplicaSet if the replica set exists try to patch it if not add it func patchReplicaSet(out *opsmngr.AutomationConfig, newReplicaSet *opsmngr.ReplicaSet) { pos, found := search.ReplicaSets(out.ReplicaSets, func(r *opsmngr.ReplicaSet) bool { return r.ID == newReplicaSet.ID }) if !found { out.ReplicaSets = append(out.ReplicaSets, newReplicaSet) return } oldReplicaSet := out.ReplicaSets[pos] lastID := oldReplicaSet.Members[len(oldReplicaSet.Members)-1].ID for j, newMember := range newReplicaSet.Members { newHost := newMember.Host k, found := search.Members(oldReplicaSet.Members, func(m opsmngr.Member) bool { return m.Host == newHost }) if found { newMember.ID = oldReplicaSet.Members[k].ID } else { lastID++ newMember.ID = lastID } newReplicaSet.Members[j] = newMember } out.ReplicaSets[pos] = newReplicaSet } func patchSharding(out *opsmngr.AutomationConfig, s *opsmngr.ShardingConfig) { pos, found := search.ShardingConfig(out.Sharding, func(r *opsmngr.ShardingConfig) bool { return r.Name == s.Name }) if !found { out.Sharding = append(out.Sharding, s) return } // TODO: test this with CLOUDP-65971 out.Sharding[pos] = s }
package main import ( "fmt" "log" "time" "github.com/shanghuiyang/rpi-devices/dev" "github.com/stianeikeland/go-rpio" ) const ( pinTrig = 21 pinEcho = 26 ) func main() { if err := rpio.Open(); err != nil { log.Fatalf("failed to open rpio, error: %v", err) return } defer rpio.Close() hcsr04 := dev.NewHCSR04(pinTrig, pinEcho) for { dist := hcsr04.Dist() fmt.Printf("%.2f cm\n", dist) time.Sleep(1 * time.Second) } }
package agent import ( "context" "net" "net/url" "github.com/go-openapi/strfmt" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/openshift/assisted-service/api/v1beta1" "github.com/openshift/assisted-service/client" "github.com/openshift/assisted-service/client/events" "github.com/openshift/assisted-service/client/installer" "github.com/openshift/assisted-service/models" "github.com/openshift/installer/pkg/asset/agent/agentconfig" "github.com/openshift/installer/pkg/asset/agent/image" "github.com/openshift/installer/pkg/asset/agent/manifests" "github.com/openshift/installer/pkg/asset/installconfig" assetstore "github.com/openshift/installer/pkg/asset/store" "github.com/openshift/installer/pkg/types/agent" ) // NodeZeroRestClient is a struct to interact with the Agent Rest API that is on node zero. type NodeZeroRestClient struct { Client *client.AssistedInstall ctx context.Context config client.Config NodeZeroIP string NodeSSHKey []string } // NewNodeZeroRestClient Initialize a new rest client to interact with the Agent Rest API on node zero. func NewNodeZeroRestClient(ctx context.Context, assetDir string) (*NodeZeroRestClient, error) { restClient := &NodeZeroRestClient{} agentConfigAsset := &agentconfig.AgentConfig{} agentManifestsAsset := &manifests.AgentManifests{} installConfigAsset := &installconfig.InstallConfig{} assetStore, err := assetstore.NewStore(assetDir) if err != nil { return nil, errors.Wrap(err, "failed to create asset store") } agentConfig, agentConfigError := assetStore.Load(agentConfigAsset) agentManifests, manifestError := assetStore.Load(agentManifestsAsset) installConfig, installConfigError := assetStore.Load(installConfigAsset) if agentConfigError != nil { logrus.Debug(errors.Wrapf(agentConfigError, "failed to load %s", agentConfigAsset.Name())) } if manifestError != nil { logrus.Debug(errors.Wrapf(manifestError, "failed to load %s", agentManifestsAsset.Name())) } if installConfigError != nil { logrus.Debug(errors.Wrapf(installConfigError, "failed to load %s", installConfigAsset.Name())) } if agentConfigError != nil || manifestError != nil || installConfigError != nil { return nil, errors.New("failed to load AgentConfig, NMStateConfig, or InstallConfig") } var RendezvousIP string var rendezvousIPError error var emptyNMStateConfigs []*v1beta1.NMStateConfig if agentConfig != nil && agentManifests != nil { RendezvousIP, rendezvousIPError = image.RetrieveRendezvousIP(agentConfig.(*agentconfig.AgentConfig).Config, agentManifests.(*manifests.AgentManifests).NMStateConfigs) } else if agentConfig == nil && agentManifests != nil { RendezvousIP, rendezvousIPError = image.RetrieveRendezvousIP(&agent.Config{}, agentManifests.(*manifests.AgentManifests).NMStateConfigs) } else if agentConfig != nil && agentManifests == nil { RendezvousIP, rendezvousIPError = image.RetrieveRendezvousIP(agentConfig.(*agentconfig.AgentConfig).Config, emptyNMStateConfigs) } else { return nil, errors.New("both AgentConfig and NMStateConfig are empty") } if rendezvousIPError != nil { return nil, rendezvousIPError } // Get SSH Keys which can be used to determine if Rest API failures are due to network connectivity issues if installConfig != nil { restClient.NodeSSHKey = append(restClient.NodeSSHKey, installConfig.(*installconfig.InstallConfig).Config.SSHKey) } config := client.Config{} config.URL = &url.URL{ Scheme: "http", Host: net.JoinHostPort(RendezvousIP, "8090"), Path: client.DefaultBasePath, } client := client.New(config) restClient.Client = client restClient.ctx = ctx restClient.config = config restClient.NodeZeroIP = RendezvousIP return restClient, nil } // IsRestAPILive Determine if the Agent Rest API on node zero has initialized func (rest *NodeZeroRestClient) IsRestAPILive() (bool, error) { // GET /v2/infraenvs listInfraEnvsParams := installer.NewListInfraEnvsParams() _, err := rest.Client.Installer.ListInfraEnvs(rest.ctx, listInfraEnvsParams) if err != nil { return false, err } return true, nil } // GetRestAPIServiceBaseURL Return the url of the Agent Rest API on node zero func (rest *NodeZeroRestClient) GetRestAPIServiceBaseURL() *url.URL { return rest.config.URL } // GetInfraEnvEvents Return the event list for the provided infraEnvID from the Agent Rest API func (rest *NodeZeroRestClient) GetInfraEnvEvents(infraEnvID *strfmt.UUID) (models.EventList, error) { listEventsParams := &events.V2ListEventsParams{InfraEnvID: infraEnvID} clusterEventsResult, err := rest.Client.Events.V2ListEvents(rest.ctx, listEventsParams) if err != nil { return nil, err } return clusterEventsResult.Payload, nil } // getClusterID Return the cluster ID assigned by the Agent Rest API func (rest *NodeZeroRestClient) getClusterID() (*strfmt.UUID, error) { // GET /v2/clusters and return first result listClusterParams := installer.NewV2ListClustersParams() clusterResult, err := rest.Client.Installer.V2ListClusters(rest.ctx, listClusterParams) if err != nil { return nil, err } clusterList := clusterResult.Payload if len(clusterList) == 1 { clusterID := clusterList[0].ID return clusterID, nil } else if len(clusterList) == 0 { logrus.Debug("cluster is not registered in rest API") return nil, nil } else { logrus.Infof("found too many clusters. number of clusters found: %d", len(clusterList)) return nil, nil } } // getClusterID Return the infraEnv ID associated with the cluster in the Agent Rest API func (rest *NodeZeroRestClient) getClusterInfraEnvID() (*strfmt.UUID, error) { // GET /v2/infraenvs and return first result listInfraEnvParams := installer.NewListInfraEnvsParams() infraEnvResult, err := rest.Client.Installer.ListInfraEnvs(rest.ctx, listInfraEnvParams) if err != nil { return nil, err } infraEnvList := infraEnvResult.Payload if len(infraEnvList) == 1 { clusterInfraEnvID := infraEnvList[0].ID return clusterInfraEnvID, nil } else if len(infraEnvList) == 0 { logrus.Debug("infraenv is not registered in rest API") return nil, nil } else { logrus.Infof("found too many infraenvs. number of infraenvs found: %d", len(infraEnvList)) return nil, nil } }
package binance import ( "testing" "github.com/stretchr/testify/suite" ) type userUniversalTransferTestSuite struct { baseTestSuite } func TestUserUniversalTransferService(t *testing.T) { suite.Run(t, new(userUniversalTransferTestSuite)) } func (s *userUniversalTransferTestSuite) TestUserUniversalTransfer() { data := []byte(` { "tranId":13526853623 } `) s.mockDo(data, nil) defer s.assertDo() types := "MAIN_C2C" asset := "USDT" amount := 0.1 fromSymbol := "USDT" toSymbol := "USDT" s.assertReq(func(r *request) { e := newSignedRequest().setParams(params{ "type": types, "asset": asset, "amount": amount, "fromSymbol": fromSymbol, "toSymbol": toSymbol, }) s.assertRequestEqual(e, r) }) res, err := s.client.NewUserUniversalTransferService(). Type(types). Asset(asset). Amount(amount). FromSymbol(fromSymbol). ToSymbol(toSymbol). Do(newContext()) r := s.r() r.NoError(err) r.Equal(int64(13526853623), res.ID) }
package main import ( "fmt" "io/ioutil" "net/http" "os" "strings" "time" "github.com/gocolly/colly" ) const economistBaseURL = "https://www.economist.com" type section struct { title string articleLinks []string } func main() { // step 1 : get latest weekly URL urlSuffix, date := getLatestWeeklyEditionURL() fmt.Println("[crawl] the latest edition is ", urlSuffix) // step 2 : get sections from weekly front page var sections, coverURL = getSectionsAndCoverByURL(economistBaseURL + urlSuffix) /* // log for this ? for _, sec := range sections { fmt.Println(sec) } */ // step 3 : prepare markdown && images file directories err := os.RemoveAll(date) fmt.Println("[rmdir]", err) // step 3.1 : mkdir 2020-07-20 err = os.MkdirAll(date, 0755) fmt.Println("[mkdir]", err) // step 3.2 : download cover image fmt.Println("[cover download]", coverURL) downloadArticleImages(date, coverURL) // step 3.3 : prepare dirs for sections for _, sec := range sections { // dir for markdown files err = os.MkdirAll(getMarkdownFileDir(date, sec.title), 0755) if err != nil { fmt.Println("[mkdir markdown]", err) } // dir for image files err = os.MkdirAll(getImageDir(date, sec.title), 0755) if err != nil { fmt.Println("[mkdir img]", err) } } // step 4 : download articles && images for _, sec := range sections { for _, articleURL := range sec.articleLinks { // step 4.1 : download article // economist.com + /2020-07-05/{title} fullURL := economistBaseURL + articleURL article := fetchArticleContent(fullURL) // step 4.2 : download image // lead image downloadArticleImages(getImageDir(date, sec.title), article.leadImageURL) // body images downloadArticleImages(getImageDir(date, sec.title), article.imageURLs...) // step 4.3 : create markdown file f, err := os.Create(getMarkdownFilePath(date, sec.title, extractArticleTitleFromURL(articleURL))) if err != nil { fmt.Println(err) continue } defer f.Close() // step 4.4 : write content to files _, err = f.WriteString(article.generateMarkdown()) if err != nil { fmt.Println(err) continue } } } } func extractArticleTitleFromURL(articleURL string) string { var arr = strings.Split(articleURL, "/") lastIdx := len(arr) - 1 return arr[lastIdx] } func getMarkdownFilePath(date, sectionTitle, articleTitle string) string { return date + "/" + sectionTitle + "/" + articleTitle + ".md" } func getMarkdownFileDir(date, sectionTitle string) string { return date + "/" + sectionTitle } func getImageDir(date, sectionTitle string) string { return date + "/" + sectionTitle + "/images" } type article struct { // header part leadImageURL string headline string subHeadline string description string // body part meta string paragraphs []string // paragraph images imageURLs []string } func (a article) generateMarkdown() string { var content string if a.leadImageURL != "" { content += fmt.Sprintf("![](./images/%v)", getImageNameFromImageURL(a.leadImageURL)) content += "\n\n" } if a.subHeadline != "" { content += "## " + a.subHeadline + "\n\n" } if a.headline != "" { content += "# " + a.headline + "\n\n" } if a.description != "" { content += "> " + a.description + "\n\n" } if a.meta != "" { content += "> " + a.meta + "\n\n" } if len(a.paragraphs) > 0 { content += strings.Join(a.paragraphs, "\n\n") } return content } // return content && image urls func fetchArticleContent(url string) article { articleCollector := colly.NewCollector() var ( // header leadImgURL string headline string subHeadline string description string // body meta string paragraphs []string // images imageURLs []string // image url in this article ) // header part // ds-layout-grid ds-layout-grid--edged layout-article-header articleCollector.OnHTML(".layout-article-header", func(e *colly.HTMLElement) { headline = e.ChildText(".article__headline") subHeadline = e.ChildText(".article__subheadline") leadImgURL = e.ChildAttr("img", "src") description = e.ChildText(".article__description") }) // body part // ds-layout-grid ds-layout-grid--edged layout-article-body articleCollector.OnHTML(".layout-article-body", func(e *colly.HTMLElement) { meta = e.ChildText(".layout-article-meta") e.ForEach(".article__body-text, img", func(idx int, internal *colly.HTMLElement) { if internal.Name == "img" { // xxxx.jpg 2048 imageRawURL := internal.Attr("src") arr := strings.Split(imageRawURL, " ") var imageURL = arr[0] imageURLs = append(imageURLs, imageURL) // insert this image as a img element to markdown paragraph imageContent := fmt.Sprintf("![](./images/%v)", getImageNameFromImageURL(imageURL)) paragraphs = append(paragraphs, imageContent) } else { paragraphs = append(paragraphs, internal.Text) } }) }) err := articleCollector.Visit(url) if err != nil { fmt.Println("[crawl] failed to crawl article", url, err) return article{} } fmt.Println("[crawl]visit url", url, headline, subHeadline, leadImgURL) return article{ // header leadImageURL: leadImgURL, headline: headline, subHeadline: subHeadline, description: description, // body meta: meta, paragraphs: paragraphs, // images imageURLs: imageURLs, } } func getImageNameFromImageURL(url string) string { var arr = strings.Split(url, "/") var lastIdx = len(arr) - 1 return arr[lastIdx] } func downloadArticleImages(imageDir string, imageURLs ...string) { // extract image urls from article content var downloadFunc = func(url string) { // www.economist.com/sites/default/files/images/print-edition/20200725_WWC588.png arr := strings.Split(url, "/") fileName := arr[len(arr)-1] if fileName == "" { return } f, err := os.Create(imageDir + "/" + fileName) if err != nil { fmt.Println("[create image file] failed to create img file : ", url, err) return } defer f.Close() resp, err := http.Get(url) if err != nil { fmt.Println("[download image] failed to download img : ", url, err) return } defer resp.Body.Close() imgBytes, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("[download image] read img resp failed: ", url, err) return } _, err = f.Write(imgBytes) if err != nil { fmt.Println("[write image] write img to file failed: ", url, err) return } } for _, url := range imageURLs { downloadFunc(url) } } // rootPath like : www.economist.com/weeklyedition/2020-07-20 func getSectionsAndCoverByURL(rootPath string) ([]section, string) { var ( sections []section coverURL string ) sectionCollector := colly.NewCollector() sectionCollector.OnHTML(".layout-weekly-edition-section", func(e *colly.HTMLElement) { title := e.ChildText(".ds-section-headline") children := e.ChildAttrs("a", "href") sections = append(sections, section{title: title, articleLinks: children}) }) sectionCollector.OnHTML(".weekly-edition-header__image", func(e *colly.HTMLElement) { coverURL = e.ChildAttr("img", "src") }) err := sectionCollector.Visit(rootPath) if err != nil { fmt.Println(err) } return sections, coverURL } func getLatestWeeklyEditionURL() (url string, date string) { client := http.Client{ Timeout: time.Second * 5, // just tell me the redirect target // and don't redirect CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, } resp, err := client.Get("https://www.economist.com/weeklyedition") if err != nil { fmt.Println("[getLatest] failed", err) os.Exit(1) } latestURL := resp.Header.Get("Location") arr := strings.Split(latestURL, "/") latestDate := arr[len(arr)-1] return latestURL, latestDate }
// All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package v20180330 import ( "github.com/tencentyun/tcecloud-sdk-go/tcecloud/common" tchttp "github.com/tencentyun/tcecloud-sdk-go/tcecloud/common/http" "github.com/tencentyun/tcecloud-sdk-go/tcecloud/common/profile" ) const APIVersion = "2018-03-30" type Client struct { common.Client } // Deprecated func NewClientWithSecretId(secretId, secretKey, region string) (client *Client, err error) { cpf := profile.NewClientProfile() client = &Client{} client.Init(region).WithSecretId(secretId, secretKey).WithProfile(cpf) return } func NewClient(credential *common.Credential, region string, clientProfile *profile.ClientProfile) (client *Client, err error) { client = &Client{} client.Init(region). WithCredential(credential). WithProfile(clientProfile) return } func NewActivateSubscribeRequest() (request *ActivateSubscribeRequest) { request = &ActivateSubscribeRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "ActivateSubscribe") return } func NewActivateSubscribeResponse() (response *ActivateSubscribeResponse) { response = &ActivateSubscribeResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口用于配置数据订阅,只有在未配置状态的订阅实例才能调用此接口。 func (c *Client) ActivateSubscribe(request *ActivateSubscribeRequest) (response *ActivateSubscribeResponse, err error) { if request == nil { request = NewActivateSubscribeRequest() } response = NewActivateSubscribeResponse() err = c.Send(request, response) return } func NewCompleteMigrateJobRequest() (request *CompleteMigrateJobRequest) { request = &CompleteMigrateJobRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "CompleteMigrateJob") return } func NewCompleteMigrateJobResponse() (response *CompleteMigrateJobResponse) { response = &CompleteMigrateJobResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(CompleteMigrateJob)用于完成数据迁移任务。 // 选择采用增量迁移方式的任务, 需要在迁移进度进入准备完成阶段后, 调用本接口, 停止迁移增量数据。 // 通过DescribeMigrateJobs接口查询到任务的状态为准备完成(status=8)时,此时可以调用本接口完成迁移任务。 func (c *Client) CompleteMigrateJob(request *CompleteMigrateJobRequest) (response *CompleteMigrateJobResponse, err error) { if request == nil { request = NewCompleteMigrateJobRequest() } response = NewCompleteMigrateJobResponse() err = c.Send(request, response) return } func NewCreateMigrateCheckJobRequest() (request *CreateMigrateCheckJobRequest) { request = &CreateMigrateCheckJobRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "CreateMigrateCheckJob") return } func NewCreateMigrateCheckJobResponse() (response *CreateMigrateCheckJobResponse) { response = &CreateMigrateCheckJobResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 创建校验迁移任务 // 在开始迁移前, 必须调用本接口创建校验, 且校验成功后才能开始迁移. 校验的结果可以通过DescribeMigrateCheckJob查看. // 校验成功后,迁移任务若有修改, 则必须重新创建校验并通过后, 才能开始迁移. func (c *Client) CreateMigrateCheckJob(request *CreateMigrateCheckJobRequest) (response *CreateMigrateCheckJobResponse, err error) { if request == nil { request = NewCreateMigrateCheckJobRequest() } response = NewCreateMigrateCheckJobResponse() err = c.Send(request, response) return } func NewCreateMigrateJobRequest() (request *CreateMigrateJobRequest) { request = &CreateMigrateJobRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "CreateMigrateJob") return } func NewCreateMigrateJobResponse() (response *CreateMigrateJobResponse) { response = &CreateMigrateJobResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(CreateMigrateJob)用于创建数据迁移任务。 // // 如果是金融区链路, 请使用域名: dts.ap-shenzhen-fsi.tencentcloudapi.com func (c *Client) CreateMigrateJob(request *CreateMigrateJobRequest) (response *CreateMigrateJobResponse, err error) { if request == nil { request = NewCreateMigrateJobRequest() } response = NewCreateMigrateJobResponse() err = c.Send(request, response) return } func NewCreateSubscribeRequest() (request *CreateSubscribeRequest) { request = &CreateSubscribeRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "CreateSubscribe") return } func NewCreateSubscribeResponse() (response *CreateSubscribeResponse) { response = &CreateSubscribeResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(CreateSubscribe)用于创建一个数据订阅实例。 func (c *Client) CreateSubscribe(request *CreateSubscribeRequest) (response *CreateSubscribeResponse, err error) { if request == nil { request = NewCreateSubscribeRequest() } response = NewCreateSubscribeResponse() err = c.Send(request, response) return } func NewCreateSyncCheckJobRequest() (request *CreateSyncCheckJobRequest) { request = &CreateSyncCheckJobRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "CreateSyncCheckJob") return } func NewCreateSyncCheckJobResponse() (response *CreateSyncCheckJobResponse) { response = &CreateSyncCheckJobResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 在调用 StartSyncJob 接口启动灾备同步前, 必须调用本接口创建校验, 且校验成功后才能开始同步数据. 校验的结果可以通过 DescribeSyncCheckJob 查看. // 校验成功后才能启动同步. func (c *Client) CreateSyncCheckJob(request *CreateSyncCheckJobRequest) (response *CreateSyncCheckJobResponse, err error) { if request == nil { request = NewCreateSyncCheckJobRequest() } response = NewCreateSyncCheckJobResponse() err = c.Send(request, response) return } func NewCreateSyncJobRequest() (request *CreateSyncJobRequest) { request = &CreateSyncJobRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "CreateSyncJob") return } func NewCreateSyncJobResponse() (response *CreateSyncJobResponse) { response = &CreateSyncJobResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(CreateSyncJob)用于创建灾备同步任务。 // 创建同步任务后,可以通过 CreateSyncCheckJob 接口发起校验任务。校验成功后才可以通过 StartSyncJob 接口启动同步任务。 func (c *Client) CreateSyncJob(request *CreateSyncJobRequest) (response *CreateSyncJobResponse, err error) { if request == nil { request = NewCreateSyncJobRequest() } response = NewCreateSyncJobResponse() err = c.Send(request, response) return } func NewDeleteMigrateJobRequest() (request *DeleteMigrateJobRequest) { request = &DeleteMigrateJobRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "DeleteMigrateJob") return } func NewDeleteMigrateJobResponse() (response *DeleteMigrateJobResponse) { response = &DeleteMigrateJobResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(DeleteMigrationJob)用于删除数据迁移任务。当通过DescribeMigrateJobs接口查询到任务的状态为:检验中(status=3)、运行中(status=7)、准备完成(status=8)、撤销中(status=11)或者完成中(status=12)时,不允许删除任务。 func (c *Client) DeleteMigrateJob(request *DeleteMigrateJobRequest) (response *DeleteMigrateJobResponse, err error) { if request == nil { request = NewDeleteMigrateJobRequest() } response = NewDeleteMigrateJobResponse() err = c.Send(request, response) return } func NewDeleteSyncJobRequest() (request *DeleteSyncJobRequest) { request = &DeleteSyncJobRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "DeleteSyncJob") return } func NewDeleteSyncJobResponse() (response *DeleteSyncJobResponse) { response = &DeleteSyncJobResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 删除灾备同步任务 (运行中的同步任务不能删除)。 func (c *Client) DeleteSyncJob(request *DeleteSyncJobRequest) (response *DeleteSyncJobResponse, err error) { if request == nil { request = NewDeleteSyncJobRequest() } response = NewDeleteSyncJobResponse() err = c.Send(request, response) return } func NewDescribeAsyncRequestInfoRequest() (request *DescribeAsyncRequestInfoRequest) { request = &DescribeAsyncRequestInfoRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "DescribeAsyncRequestInfo") return } func NewDescribeAsyncRequestInfoResponse() (response *DescribeAsyncRequestInfoResponse) { response = &DescribeAsyncRequestInfoResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(DescribeAsyncRequestInfo)用于查询任务执行结果 func (c *Client) DescribeAsyncRequestInfo(request *DescribeAsyncRequestInfoRequest) (response *DescribeAsyncRequestInfoResponse, err error) { if request == nil { request = NewDescribeAsyncRequestInfoRequest() } response = NewDescribeAsyncRequestInfoResponse() err = c.Send(request, response) return } func NewDescribeMigrateCheckJobRequest() (request *DescribeMigrateCheckJobRequest) { request = &DescribeMigrateCheckJobRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "DescribeMigrateCheckJob") return } func NewDescribeMigrateCheckJobResponse() (response *DescribeMigrateCheckJobResponse) { response = &DescribeMigrateCheckJobResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口用于创建校验后,获取校验的结果. 能查询到当前校验的状态和进度. // 若通过校验, 则可调用'StartMigrateJob' 开始迁移. // 若未通过校验, 则能查询到校验失败的原因. 请按照报错, 通过'ModifyMigrateJob'修改迁移配置或是调整源/目标实例的相关参数. func (c *Client) DescribeMigrateCheckJob(request *DescribeMigrateCheckJobRequest) (response *DescribeMigrateCheckJobResponse, err error) { if request == nil { request = NewDescribeMigrateCheckJobRequest() } response = NewDescribeMigrateCheckJobResponse() err = c.Send(request, response) return } func NewDescribeMigrateJobsRequest() (request *DescribeMigrateJobsRequest) { request = &DescribeMigrateJobsRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "DescribeMigrateJobs") return } func NewDescribeMigrateJobsResponse() (response *DescribeMigrateJobsResponse) { response = &DescribeMigrateJobsResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 查询数据迁移任务. // 如果是金融区链路, 请使用域名: https://dts.ap-shenzhen-fsi.tencentcloudapi.com func (c *Client) DescribeMigrateJobs(request *DescribeMigrateJobsRequest) (response *DescribeMigrateJobsResponse, err error) { if request == nil { request = NewDescribeMigrateJobsRequest() } response = NewDescribeMigrateJobsResponse() err = c.Send(request, response) return } func NewDescribeRegionConfRequest() (request *DescribeRegionConfRequest) { request = &DescribeRegionConfRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "DescribeRegionConf") return } func NewDescribeRegionConfResponse() (response *DescribeRegionConfResponse) { response = &DescribeRegionConfResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(DescribeRegionConf)用于查询可售卖订阅实例的地域 func (c *Client) DescribeRegionConf(request *DescribeRegionConfRequest) (response *DescribeRegionConfResponse, err error) { if request == nil { request = NewDescribeRegionConfRequest() } response = NewDescribeRegionConfResponse() err = c.Send(request, response) return } func NewDescribeSubscribeConfRequest() (request *DescribeSubscribeConfRequest) { request = &DescribeSubscribeConfRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "DescribeSubscribeConf") return } func NewDescribeSubscribeConfResponse() (response *DescribeSubscribeConfResponse) { response = &DescribeSubscribeConfResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(DescribeSubscribeConf)用于查询订阅实例配置 func (c *Client) DescribeSubscribeConf(request *DescribeSubscribeConfRequest) (response *DescribeSubscribeConfResponse, err error) { if request == nil { request = NewDescribeSubscribeConfRequest() } response = NewDescribeSubscribeConfResponse() err = c.Send(request, response) return } func NewDescribeSubscribesRequest() (request *DescribeSubscribesRequest) { request = &DescribeSubscribesRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "DescribeSubscribes") return } func NewDescribeSubscribesResponse() (response *DescribeSubscribesResponse) { response = &DescribeSubscribesResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(DescribeSubscribes)获取数据订阅实例信息列表,默认分页,每次返回20条 func (c *Client) DescribeSubscribes(request *DescribeSubscribesRequest) (response *DescribeSubscribesResponse, err error) { if request == nil { request = NewDescribeSubscribesRequest() } response = NewDescribeSubscribesResponse() err = c.Send(request, response) return } func NewDescribeSyncCheckJobRequest() (request *DescribeSyncCheckJobRequest) { request = &DescribeSyncCheckJobRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "DescribeSyncCheckJob") return } func NewDescribeSyncCheckJobResponse() (response *DescribeSyncCheckJobResponse) { response = &DescribeSyncCheckJobResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口用于在通过 CreateSyncCheckJob 接口创建灾备同步校验任务后,获取校验的结果。能查询到当前校验的状态和进度。 // 若通过校验, 则可调用 StartSyncJob 启动同步任务。 // 若未通过校验, 则会返回校验失败的原因。 可通过 ModifySyncJob 修改配置,然后再次发起校验。 // 校验任务需要大概约30秒,当返回的 Status 不为 finished 时表示尚未校验完成,需要轮询该接口。 // 如果 Status=finished 且 CheckFlag=1 时表示校验成功。 // 如果 Status=finished 且 CheckFlag !=1 时表示校验失败。 func (c *Client) DescribeSyncCheckJob(request *DescribeSyncCheckJobRequest) (response *DescribeSyncCheckJobResponse, err error) { if request == nil { request = NewDescribeSyncCheckJobRequest() } response = NewDescribeSyncCheckJobResponse() err = c.Send(request, response) return } func NewDescribeSyncJobsRequest() (request *DescribeSyncJobsRequest) { request = &DescribeSyncJobsRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "DescribeSyncJobs") return } func NewDescribeSyncJobsResponse() (response *DescribeSyncJobsResponse) { response = &DescribeSyncJobsResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 查询在迁移平台发起的灾备同步任务 func (c *Client) DescribeSyncJobs(request *DescribeSyncJobsRequest) (response *DescribeSyncJobsResponse, err error) { if request == nil { request = NewDescribeSyncJobsRequest() } response = NewDescribeSyncJobsResponse() err = c.Send(request, response) return } func NewIsolateSubscribeRequest() (request *IsolateSubscribeRequest) { request = &IsolateSubscribeRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "IsolateSubscribe") return } func NewIsolateSubscribeResponse() (response *IsolateSubscribeResponse) { response = &IsolateSubscribeResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(IsolateSubscribe)用于隔离小时计费的订阅实例。调用后,订阅实例将不能使用,同时停止计费。 func (c *Client) IsolateSubscribe(request *IsolateSubscribeRequest) (response *IsolateSubscribeResponse, err error) { if request == nil { request = NewIsolateSubscribeRequest() } response = NewIsolateSubscribeResponse() err = c.Send(request, response) return } func NewModifyMigrateJobRequest() (request *ModifyMigrateJobRequest) { request = &ModifyMigrateJobRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "ModifyMigrateJob") return } func NewModifyMigrateJobResponse() (response *ModifyMigrateJobResponse) { response = &ModifyMigrateJobResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(ModifyMigrateJob)用于修改数据迁移任务。 // 当迁移任务处于下述状态时,允许调用本接口修改迁移任务:迁移创建中(status=1)、 校验成功(status=4)、校验失败(status=5)、迁移失败(status=10)。但源实例、目标实例类型和目标实例地域不允许修改。 // // 如果是金融区链路, 请使用域名: dts.ap-shenzhen-fsi.tencentcloudapi.com func (c *Client) ModifyMigrateJob(request *ModifyMigrateJobRequest) (response *ModifyMigrateJobResponse, err error) { if request == nil { request = NewModifyMigrateJobRequest() } response = NewModifyMigrateJobResponse() err = c.Send(request, response) return } func NewModifySubscribeConsumeTimeRequest() (request *ModifySubscribeConsumeTimeRequest) { request = &ModifySubscribeConsumeTimeRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "ModifySubscribeConsumeTime") return } func NewModifySubscribeConsumeTimeResponse() (response *ModifySubscribeConsumeTimeResponse) { response = &ModifySubscribeConsumeTimeResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(ModifySubscribeConsumeTime)用于修改数据订阅通道的消费时间点 func (c *Client) ModifySubscribeConsumeTime(request *ModifySubscribeConsumeTimeRequest) (response *ModifySubscribeConsumeTimeResponse, err error) { if request == nil { request = NewModifySubscribeConsumeTimeRequest() } response = NewModifySubscribeConsumeTimeResponse() err = c.Send(request, response) return } func NewModifySubscribeNameRequest() (request *ModifySubscribeNameRequest) { request = &ModifySubscribeNameRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "ModifySubscribeName") return } func NewModifySubscribeNameResponse() (response *ModifySubscribeNameResponse) { response = &ModifySubscribeNameResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(ModifySubscribeName)用于修改数据订阅实例的名称 func (c *Client) ModifySubscribeName(request *ModifySubscribeNameRequest) (response *ModifySubscribeNameResponse, err error) { if request == nil { request = NewModifySubscribeNameRequest() } response = NewModifySubscribeNameResponse() err = c.Send(request, response) return } func NewModifySubscribeObjectsRequest() (request *ModifySubscribeObjectsRequest) { request = &ModifySubscribeObjectsRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "ModifySubscribeObjects") return } func NewModifySubscribeObjectsResponse() (response *ModifySubscribeObjectsResponse) { response = &ModifySubscribeObjectsResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(ModifySubscribeObjects)用于修改数据订阅通道的订阅规则 func (c *Client) ModifySubscribeObjects(request *ModifySubscribeObjectsRequest) (response *ModifySubscribeObjectsResponse, err error) { if request == nil { request = NewModifySubscribeObjectsRequest() } response = NewModifySubscribeObjectsResponse() err = c.Send(request, response) return } func NewModifySubscribeVipVportRequest() (request *ModifySubscribeVipVportRequest) { request = &ModifySubscribeVipVportRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "ModifySubscribeVipVport") return } func NewModifySubscribeVipVportResponse() (response *ModifySubscribeVipVportResponse) { response = &ModifySubscribeVipVportResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(ModifySubscribeVipVport)用于修改数据订阅实例的IP和端口号 func (c *Client) ModifySubscribeVipVport(request *ModifySubscribeVipVportRequest) (response *ModifySubscribeVipVportResponse, err error) { if request == nil { request = NewModifySubscribeVipVportRequest() } response = NewModifySubscribeVipVportResponse() err = c.Send(request, response) return } func NewModifySyncJobRequest() (request *ModifySyncJobRequest) { request = &ModifySyncJobRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "ModifySyncJob") return } func NewModifySyncJobResponse() (response *ModifySyncJobResponse) { response = &ModifySyncJobResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 修改灾备同步任务. // 当同步任务处于下述状态时, 允许调用本接口: 同步任务创建中, 创建完成, 校验成功, 校验失败. // 源实例和目标实例信息不允许修改,可以修改任务名、需要同步的库表。 func (c *Client) ModifySyncJob(request *ModifySyncJobRequest) (response *ModifySyncJobResponse, err error) { if request == nil { request = NewModifySyncJobRequest() } response = NewModifySyncJobResponse() err = c.Send(request, response) return } func NewOfflineIsolatedSubscribeRequest() (request *OfflineIsolatedSubscribeRequest) { request = &OfflineIsolatedSubscribeRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "OfflineIsolatedSubscribe") return } func NewOfflineIsolatedSubscribeResponse() (response *OfflineIsolatedSubscribeResponse) { response = &OfflineIsolatedSubscribeResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(OfflineIsolatedSubscribe)用于下线已隔离的数据订阅实例 func (c *Client) OfflineIsolatedSubscribe(request *OfflineIsolatedSubscribeRequest) (response *OfflineIsolatedSubscribeResponse, err error) { if request == nil { request = NewOfflineIsolatedSubscribeRequest() } response = NewOfflineIsolatedSubscribeResponse() err = c.Send(request, response) return } func NewResetSubscribeRequest() (request *ResetSubscribeRequest) { request = &ResetSubscribeRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "ResetSubscribe") return } func NewResetSubscribeResponse() (response *ResetSubscribeResponse) { response = &ResetSubscribeResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(ResetSubscribe)用于重置数据订阅实例,已经激活的数据订阅实例,重置后可以使用ActivateSubscribe接口绑定其他的数据库实例 func (c *Client) ResetSubscribe(request *ResetSubscribeRequest) (response *ResetSubscribeResponse, err error) { if request == nil { request = NewResetSubscribeRequest() } response = NewResetSubscribeResponse() err = c.Send(request, response) return } func NewStartMigrateJobRequest() (request *StartMigrateJobRequest) { request = &StartMigrateJobRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "StartMigrateJob") return } func NewStartMigrateJobResponse() (response *StartMigrateJobResponse) { response = &StartMigrateJobResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(StartMigrationJob)用于启动迁移任务。非定时迁移任务会在调用后立即开始迁移,定时任务则会开始倒计时。 // 调用此接口前,请务必先使用CreateMigrateCheckJob校验数据迁移任务,并通过DescribeMigrateJobs接口查询到任务状态为校验通过(status=4)时,才能启动数据迁移任务。 func (c *Client) StartMigrateJob(request *StartMigrateJobRequest) (response *StartMigrateJobResponse, err error) { if request == nil { request = NewStartMigrateJobRequest() } response = NewStartMigrateJobResponse() err = c.Send(request, response) return } func NewStartSyncJobRequest() (request *StartSyncJobRequest) { request = &StartSyncJobRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "StartSyncJob") return } func NewStartSyncJobResponse() (response *StartSyncJobResponse) { response = &StartSyncJobResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 创建的灾备同步任务在通过 CreateSyncCheckJob 和 DescribeSyncCheckJob 确定校验成功后,可以调用该接口启动同步 func (c *Client) StartSyncJob(request *StartSyncJobRequest) (response *StartSyncJobResponse, err error) { if request == nil { request = NewStartSyncJobRequest() } response = NewStartSyncJobResponse() err = c.Send(request, response) return } func NewStopMigrateJobRequest() (request *StopMigrateJobRequest) { request = &StopMigrateJobRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "StopMigrateJob") return } func NewStopMigrateJobResponse() (response *StopMigrateJobResponse) { response = &StopMigrateJobResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 本接口(StopMigrateJob)用于撤销数据迁移任务。 // 在迁移过程中允许调用该接口撤销迁移, 撤销迁移的任务会失败。通过DescribeMigrateJobs接口查询到任务状态为运行中(status=7)或准备完成(status=8)时,才能撤销数据迁移任务。 func (c *Client) StopMigrateJob(request *StopMigrateJobRequest) (response *StopMigrateJobResponse, err error) { if request == nil { request = NewStopMigrateJobRequest() } response = NewStopMigrateJobResponse() err = c.Send(request, response) return } func NewSwitchDrToMasterRequest() (request *SwitchDrToMasterRequest) { request = &SwitchDrToMasterRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("dts", APIVersion, "SwitchDrToMaster") return } func NewSwitchDrToMasterResponse() (response *SwitchDrToMasterResponse) { response = &SwitchDrToMasterResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 将灾备升级为主实例,停止从原来所属主实例的同步,断开主备关系。 func (c *Client) SwitchDrToMaster(request *SwitchDrToMasterRequest) (response *SwitchDrToMasterResponse, err error) { if request == nil { request = NewSwitchDrToMasterRequest() } response = NewSwitchDrToMasterResponse() err = c.Send(request, response) return }
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/8/22 1:01 下午 # @File : bench.go # @Description : # @Attention : */ package main import ( "fmt" "reflect" "sync" "testing" ) var funcs = []struct { name string f func(...<-chan int) <-chan int }{ {"goroutines", goroutine}, {"goroutineMerge", mergeN}, {"reflection", mergeReflect}, {"selectn", selectn}, } func goroutine(chans ...<-chan int) <-chan int { r := make(chan int, 1) wg := sync.WaitGroup{} wg.Add(len(chans)) go func() { for i := 0; i < len(chans); i++ { go func(index int) { defer wg.Done() for v := range chans[index] { r <- v } }(i) } wg.Wait() close(r) }() return r } func mergeN(chans ...<-chan int) <-chan int { r := make(chan int, 1) go func() { wg := sync.WaitGroup{} wg.Add(len(chans)) for _, c := range chans { go func(c <-chan int) { for v := range c { r <- v } wg.Done() }(c) } wg.Wait() close(r) }() return r } func mergeReflect(chans ...<-chan int) <-chan int { out := make(chan int) go func() { defer close(out) var cases []reflect.SelectCase for _, c := range chans { cases = append(cases, reflect.SelectCase{ Dir: reflect.SelectRecv, Chan: reflect.ValueOf(c), }) } for len(cases) > 0 { i, v, ok := reflect.Select(cases) if !ok { cases = append(cases[:i], cases[i+1:]...) continue } out <- v.Interface().(int) } }() return out } func selectn(chs ...<-chan int) <-chan int { out := make(chan int) go func() { i := 0 l := len(chs) max := 32 wg := sync.WaitGroup{} for i < len(chs) { l = len(chs) - i switch { case l > 32 && max >= 32: wg.Add(1) go select32(chs[i:i+32], out, &wg) i += 32 case l > 15 && max >= 16: wg.Add(1) go select16(chs[i:i+16], out, &wg) i += 16 case l > 7 && max >= 8: wg.Add(1) go select8(chs[i:i+8], out, &wg) i += 8 case l > 3 && max >= 4: wg.Add(1) go select4(chs[i:i+4], out, &wg) i += 4 case l > 1 && max >= 2: wg.Add(1) go select2(chs[i:i+2], out, &wg) i += 2 case l > 0: wg.Add(1) go select1([]<-chan int{chs[i]}, out, &wg) i += 1 } } wg.Wait() close(out) }() return out } func select32(cs []<-chan int, out chan int, wg *sync.WaitGroup) { defer wg.Done() var v int var ok bool done := 0 for { select { case v, ok = <-cs[0]: if !ok { done++ cs[0] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[1]: if !ok { done++ cs[1] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[2]: if !ok { done++ cs[2] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[3]: if !ok { done++ cs[3] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[4]: if !ok { done++ cs[4] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[5]: if !ok { done++ cs[5] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[6]: if !ok { done++ cs[6] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[7]: if !ok { done++ cs[7] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[8]: if !ok { done++ cs[8] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[9]: if !ok { done++ cs[9] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[10]: if !ok { done++ cs[10] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[11]: if !ok { done++ cs[11] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[12]: if !ok { done++ cs[12] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[13]: if !ok { done++ cs[13] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[14]: if !ok { done++ cs[14] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[15]: if !ok { done++ cs[15] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[16]: if !ok { done++ cs[16] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[17]: if !ok { done++ cs[17] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[18]: if !ok { done++ cs[18] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[19]: if !ok { done++ cs[19] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[20]: if !ok { done++ cs[20] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[21]: if !ok { done++ cs[21] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[22]: if !ok { done++ cs[22] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[23]: if !ok { done++ cs[23] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[24]: if !ok { done++ cs[24] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[25]: if !ok { done++ cs[25] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[26]: if !ok { done++ cs[26] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[27]: if !ok { done++ cs[27] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[28]: if !ok { done++ cs[28] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[29]: if !ok { done++ cs[29] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[30]: if !ok { done++ cs[30] = nil if done == 32 { return } continue } out <- v case v, ok = <-cs[31]: if !ok { done++ cs[31] = nil if done == 32 { return } continue } out <- v } } } func select16(cs []<-chan int, out chan int, wg *sync.WaitGroup) { defer wg.Done() var v int var ok bool done := 0 for { select { case v, ok = <-cs[0]: if !ok { done++ cs[0] = nil if done == 16 { return } continue } out <- v case v, ok = <-cs[1]: if !ok { done++ cs[1] = nil if done == 16 { return } continue } out <- v case v, ok = <-cs[2]: if !ok { done++ cs[2] = nil if done == 16 { return } continue } out <- v case v, ok = <-cs[3]: if !ok { done++ cs[3] = nil if done == 16 { return } continue } out <- v case v, ok = <-cs[4]: if !ok { done++ cs[4] = nil if done == 16 { return } continue } out <- v case v, ok = <-cs[5]: if !ok { done++ cs[5] = nil if done == 16 { return } continue } out <- v case v, ok = <-cs[6]: if !ok { done++ cs[6] = nil if done == 16 { return } continue } out <- v case v, ok = <-cs[7]: if !ok { done++ cs[7] = nil if done == 16 { return } continue } out <- v case v, ok = <-cs[8]: if !ok { done++ cs[8] = nil if done == 16 { return } continue } out <- v case v, ok = <-cs[9]: if !ok { done++ cs[9] = nil if done == 16 { return } continue } out <- v case v, ok = <-cs[10]: if !ok { done++ cs[10] = nil if done == 16 { return } continue } out <- v case v, ok = <-cs[11]: if !ok { done++ cs[11] = nil if done == 16 { return } continue } out <- v case v, ok = <-cs[12]: if !ok { done++ cs[12] = nil if done == 16 { return } continue } out <- v case v, ok = <-cs[13]: if !ok { done++ cs[13] = nil if done == 16 { return } continue } out <- v case v, ok = <-cs[14]: if !ok { done++ cs[14] = nil if done == 16 { return } continue } out <- v case v, ok = <-cs[15]: if !ok { done++ cs[15] = nil if done == 16 { return } continue } out <- v } } } func select8(cs []<-chan int, out chan int, wg *sync.WaitGroup) { defer wg.Done() var v int var ok bool done := 0 for { select { case v, ok = <-cs[0]: if !ok { done++ cs[0] = nil if done == 8 { return } continue } out <- v case v, ok = <-cs[1]: if !ok { done++ cs[1] = nil if done == 8 { return } continue } out <- v case v, ok = <-cs[2]: if !ok { done++ cs[2] = nil if done == 8 { return } continue } out <- v case v, ok = <-cs[3]: if !ok { done++ cs[3] = nil if done == 8 { return } continue } out <- v case v, ok = <-cs[4]: if !ok { done++ cs[4] = nil if done == 8 { return } continue } out <- v case v, ok = <-cs[5]: if !ok { done++ cs[5] = nil if done == 8 { return } continue } out <- v case v, ok = <-cs[6]: if !ok { done++ cs[6] = nil if done == 8 { return } continue } out <- v case v, ok = <-cs[7]: if !ok { done++ cs[7] = nil if done == 8 { return } continue } out <- v } } } func select4(cs []<-chan int, out chan int, wg *sync.WaitGroup) { defer wg.Done() var v int var ok bool done := 0 for { select { case v, ok = <-cs[0]: if !ok { done++ cs[0] = nil if done == 4 { return } continue } out <- v case v, ok = <-cs[1]: if !ok { done++ cs[1] = nil if done == 4 { return } continue } out <- v case v, ok = <-cs[2]: if !ok { done++ cs[2] = nil if done == 4 { return } continue } out <- v case v, ok = <-cs[3]: if !ok { done++ cs[3] = nil if done == 4 { return } continue } out <- v } } } func select2(cs []<-chan int, out chan int, wg *sync.WaitGroup) { defer wg.Done() var v int var ok bool done := 0 for { select { case v, ok = <-cs[0]: if !ok { done++ cs[0] = nil if done == 2 { return } continue } out <- v case v, ok = <-cs[1]: if !ok { done++ cs[1] = nil if done == 2 { return } continue } out <- v } } } func select1(cs []<-chan int, out chan int, wg *sync.WaitGroup) { defer wg.Done() var v int var ok bool done := 0 for { select { case v, ok = <-cs[0]: if !ok { done++ cs[0] = nil if done == 1 { return } continue } out <- v} } } func asChan(vs ...int) <-chan int { c := make(chan int) go func() { for _, v := range vs { c <- v } close(c) }() return c } func Test_Secltn(t *testing.T) { for i := 0; i < 5; i++ { chs := make([]<-chan int, 16) for i := 0; i < 16; i++ { chs[i] = asChan(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) } v := selectn(chs...) for rv := range v { fmt.Println(rv) } } } func Test_Goroutine(t *testing.T) { for i := 0; i < 5; i++ { chs := make([]<-chan int, 16) for i := 0; i < 16; i++ { chs[i] = asChan(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) } v := goroutine(chs...) for rv := range v { fmt.Println(rv) } } } func BenchmarkMerge(b *testing.B) { for _, f := range funcs { for n := 1; n <= 4096; n *= 2 { chans := make([]<-chan int, n) b.Run(fmt.Sprintf("%s/%d", f.name, n), func(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() for i := range chans { chans[i] = asChan(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) } b.StartTimer() c := f.f(chans...) for range c { } } }) } } }
package main import ( "encoding/json" "fmt" "github.com/samuel/go-zookeeper/zk" "testing" "time" client2 "zookeeper/client" ) var client *client2.SdClient // 自己客户端的服务地址, // 只注册自己能提供的服务, // 如果注册其它IP提供的服务(这里可以做个限制,自动获取本机IP),那么其它IP服务是否可用自己不清楚 const Self_Node = "127.0.0.1" func callback1(event zk.Event) { //fmt.Println("path: ", event.Path) //fmt.Println("type: ", event.Type.String()) //fmt.Println("state: ", event.State.String()) switch event.Type { case zk.EventNodeCreated: fmt.Println("created!") case zk.EventNodeDeleted: fmt.Println("deleted!") case zk.EventNodeDataChanged: fmt.Println("changed!") default: fmt.Println(event.Type.String()) } fmt.Println("---------------------------") } func init() { var err error servers := []string{"192.168.5.216:2181"} client, err = client2.NewClient(servers, "/we", 10, callback1) if err != nil { panic(err) } } // 节点注册后会一直存在zookeeper中, // 节点下的信息如果客户端断开后,心跳消失,信息会自动消除, // 注册本节点能提供的服务信息 func TestRegister(t *testing.T) { defer client.Close() // 注册本节点能提供的服务 // 127.0.0.1:4001端口提供消息队列服务 // 8080端口提供http服务 // 本节点能提供两个nsqd服务,和一个http服务 node1 := &client2.ServiceNode{Name: "nsqd", Host: Self_Node, Port: 4001} node2 := &client2.ServiceNode{Name: "nsqd", Host: Self_Node, Port: 4002} node3 := &client2.ServiceNode{Name: "https", Host: Self_Node, Port: 9090} if err := client.Register(node1); err != nil { panic(err) } if err := client.Register(node2); err != nil { panic(err) } if err := client.Register(node3); err != nil { panic(err) } time.Sleep(240 * time.Second) } func TestModify(t *testing.T) { //defer client.Close() childs, err := client.GetChildren("nsqd") if err != nil { t.Error(err) } if len(childs) > 0 { node3 := &client2.ServiceNode{Name: "nsqd", Host: "127.0.0.1", Port: 1000} b, _ := json.Marshal(node3) err := client.Modify("http/"+childs[0], b) if err != nil { t.Error(err) } } else { t.Log("children len is 0") } } func TestDelete(t *testing.T) { //defer client.Close() err := client.Delete("https") if err != nil { t.Error(err) } } func TestGet(t *testing.T) { //defer client.Close() // 注意 // 如果节点下有数据,该节点不能删除 dbNodes, err := client.GetNodes("nsqd") if err != nil { panic(err) } t.Log(dbNodes) for _, node := range dbNodes { t.Log("db node=", node.Host, node.Port) } }
package depot import "sync" // StockValue value from a stock type StockValue struct { Stock Stock Close float32 Price float32 } // StockValueList list of stock values type StockValueList struct { svl chan StockValue cap int ready int sumYesterday float32 sumToday float32 //mutual exclusion - so that only on go routine can have access to StockValueList //block which should be mutual exclusive must be surrounded by lock and unlock sync.Mutex } // Yesterday value of stock for yesterday func (sv StockValue) Yesterday() float32 { return sv.Close * sv.Stock.Count } // Today value of stock for today func (sv StockValue) Today() float32 { return sv.Price * sv.Stock.Count } // New stock value list (channel with stock values) // cap: nb of stocks func New(cap int) *StockValueList { return &StockValueList{ svl: make(chan StockValue, cap), cap: cap, } } // Add a stock value to channel func (svl *StockValueList) Add(sv ...StockValue) { for _, el := range sv { svl.svl <- el } } // Done counter for get stock values are done func (svl *StockValueList) Done() { svl.Lock() defer svl.Unlock() svl.ready++ if svl.ready == svl.cap { close(svl.svl) } } // Wait read all stock values from channel // and create sum today and yesterday func (svl *StockValueList) Wait() { //[]StockValue { // res := make([]StockValue, svl.cap) // i := 0 for sv := range svl.svl { // res[i] = sv // i++ svl.sumYesterday += sv.Yesterday() svl.sumToday += sv.Today() } // return res } // SumYesterday sum stock values of yesterday func (svl *StockValueList) SumYesterday() float32 { return svl.sumYesterday } // SumToday sum stock values of today func (svl *StockValueList) SumToday() float32 { return svl.sumToday }
package tasks import ( "bytes" "io" "os" "os/exec" ) // ExecCommandTask executes a specified console command type ExecCommandTask struct { RunnableTask } func (task ExecCommandTask) GetDescription() (description string) { return task.Description } func (t ExecCommandTask) Execute() (result Result) { command := t.Preferences["Command"].(string) var args []string for _, value := range t.Preferences["Args"].([]interface{}) { args = append(args, value.(string)) } // Optional dir parameter to define in which folder to execute the command dir, ok := t.Preferences["Dir"].(string) if ok { dir = t.Preferences["Dir"].(string) } else { dir = "" } // Create the command cmd := exec.Command(command, args...) cmd.Dir = dir var stdBuffer bytes.Buffer mw := io.MultiWriter(os.Stdout, &stdBuffer) cmd.Stdout = mw cmd.Stderr = mw // Execute the command if err := cmd.Run(); err != nil { return Result{ err.Error(), false, } } // Output of the comman executed. Could later be used to have some logic running on it to // determine if the execution was successful. //output := stdBuffer.String() result.IsSuccessful = true result.Message = "The command \"" + command + "\"" + " was executed successfully." return result }
// Package docs GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // This file was generated by swaggo/swag package docs import ( "bytes" "encoding/json" "strings" "text/template" "github.com/swaggo/swag" ) var doc = `{ "schemes": {{ marshal .Schemes }}, "swagger": "2.0", "info": { "description": "{{escape .Description}}", "title": "{{.Title}}", "contact": {}, "version": "{{.Version}}" }, "host": "{{.Host}}", "basePath": "{{.BasePath}}", "paths": { "/calibrate": { "post": { "description": "Calibrates the robot. Should be done occasionally to affirm the robot is where we think it should be.", "consumes": [ "application/json" ], "produces": [ "text/plain" ], "tags": [ "low_level" ], "summary": "Calibrate the arm", "parameters": [ { "description": "joints to calibrate", "name": "joints", "in": "body", "required": true, "schema": { "$ref": "#/definitions/main.CalibrateInput" } } ], "responses": { "200": { "description": "OK", "schema": { "type": "string" } }, "400": { "description": "Bad Request", "schema": { "type": "string" } } } } }, "/directions": { "get": { "description": "Returns current direction of arm's motors.", "produces": [ "application/json" ], "tags": [ "setup" ], "summary": "Returns direction of arm joints", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/main.JointDirections" } }, "400": { "description": "Bad Request", "schema": { "type": "string" } } } } }, "/move": { "post": { "description": "Moves the robot's stepper motors.", "consumes": [ "application/json" ], "produces": [ "text/plain" ], "tags": [ "low_level" ], "summary": "Move the arm's stepper motors", "parameters": [ { "description": "steppers coordinates", "name": "move", "in": "body", "required": true, "schema": { "$ref": "#/definitions/main.MoveStepperInput" } } ], "responses": { "200": { "description": "OK", "schema": { "type": "string" } }, "400": { "description": "Bad Request", "schema": { "type": "string" } } } } }, "/ping": { "get": { "produces": [ "text/plain" ], "tags": [ "dev" ], "summary": "A pingable endpoint", "responses": { "200": { "description": "OK", "schema": { "type": "string" } } } } }, "/set_directions": { "post": { "description": "Sets up the robots joints. This only has to be done once during the setup of the robot.", "consumes": [ "application/json" ], "produces": [ "text/plain" ], "tags": [ "setup" ], "summary": "Sets direction of arm joints", "parameters": [ { "description": "direction of joints", "name": "directions", "in": "body", "required": true, "schema": { "$ref": "#/definitions/main.JointDirections" } } ], "responses": { "200": { "description": "OK", "schema": { "type": "string" } }, "400": { "description": "Bad Request", "schema": { "type": "string" } } } } } }, "definitions": { "main.CalibrateInput": { "type": "object", "properties": { "j1": { "type": "boolean" }, "j2": { "type": "boolean" }, "j3": { "type": "boolean" }, "j4": { "type": "boolean" }, "j5": { "type": "boolean" }, "j6": { "type": "boolean" }, "speed": { "type": "integer" }, "tr": { "type": "boolean" } } }, "main.JointDirections": { "type": "object", "properties": { "j1": { "type": "boolean" }, "j2": { "type": "boolean" }, "j3": { "type": "boolean" }, "j4": { "type": "boolean" }, "j5": { "type": "boolean" }, "j6": { "type": "boolean" }, "tr": { "type": "boolean" } } }, "main.MoveStepperInput": { "type": "object", "properties": { "accdur": { "type": "integer" }, "accspd": { "type": "integer" }, "dccdur": { "type": "integer" }, "dccspd": { "type": "integer" }, "j1": { "type": "integer" }, "j2": { "type": "integer" }, "j3": { "type": "integer" }, "j4": { "type": "integer" }, "j5": { "type": "integer" }, "j6": { "type": "integer" }, "speed": { "type": "integer" }, "tr": { "type": "integer" } } } } }` type swaggerInfo struct { Version string Host string BasePath string Schemes []string Title string Description string } // SwaggerInfo holds exported Swagger Info so clients can modify it var SwaggerInfo = swaggerInfo{ Version: "0.1", Host: "", BasePath: "/api/", Schemes: []string{}, Title: "ArmOS arm API", Description: "The arm API for ArmOS to interact with a variety of different robotic arms, starting with the AR3. It uses the basic interface of `x,y,z,a,b,c` for control.", } type s struct{} func (s *s) ReadDoc() string { sInfo := SwaggerInfo sInfo.Description = strings.Replace(sInfo.Description, "\n", "\\n", -1) t, err := template.New("swagger_info").Funcs(template.FuncMap{ "marshal": func(v interface{}) string { a, _ := json.Marshal(v) return string(a) }, "escape": func(v interface{}) string { // escape tabs str := strings.Replace(v.(string), "\t", "\\t", -1) // replace " with \", and if that results in \\", replace that with \\\" str = strings.Replace(str, "\"", "\\\"", -1) return strings.Replace(str, "\\\\\"", "\\\\\\\"", -1) }, }).Parse(doc) if err != nil { return doc } var tpl bytes.Buffer if err := t.Execute(&tpl, sInfo); err != nil { return doc } return tpl.String() } func init() { swag.Register(swag.Name, &s{}) }
package jdatabase import ( "database/sql" "encoding/json" "fmt" "github.com/ijidan/jgo/jgo/jconfig" "github.com/ijidan/jgo/jgo/jlogger" "github.com/ijidan/jgo/jgo/jutils" "reflect" "strconv" "strings" ) //活动记录 type ActiveRecord struct { isManualClose bool isDebug bool connect *sql.DB model interface{} attributes map[string]interface{} oldAttributes map[string]interface{} columns []string } //是否手动关闭连接 func (ar *ActiveRecord) SetIsManualClose(isManualClose bool) *ActiveRecord { ar.isManualClose = isManualClose return ar } //是否调试 func (ar *ActiveRecord) SetIsDebug(isDebug bool) *ActiveRecord { ar.isDebug = isDebug return ar } //设置数据库连接 func (ar *ActiveRecord) SetConnection(connect *sql.DB) *ActiveRecord { ar.connect = connect return ar } //传递对象 func (ar *ActiveRecord) SetModel(model interface{}) *ActiveRecord { ar.model = model return ar } //获取连接名称 func (ar *ActiveRecord) GetConnectionName() string { return "" } //获取表前缀 func (ar *ActiveRecord) GetTablePrefix() string { return "" } //获取表名 func (ar *ActiveRecord) GetTableName() string { return "" } //获取主键 func (ar *ActiveRecord) GetPrimaryKey() string { return "id" } //是否主键 func (ar *ActiveRecord) IsPrimaryKey(key string) bool { return ar.GetPrimaryKey() == key } //获取表结构 func (ar *ActiveRecord) GetTableSchema() interface{} { connection := ar.GetDbConnection() if ar.isManualClose != true { defer func() { CloseConnection(connection) }() } fullName := ar.GetFullTableName() sqlString := fmt.Sprintf("SHOW FULL COLUMNS FROM `%s` ", fullName) if ar.isDebug { jlogger.Info(sqlString) } rows, err := connection.Query(sqlString) if err != nil { return nil } result := ar.parseRows(rows) return result[0] } //获取属性 func (ar *ActiveRecord) GetAttributes() map[string]interface{} { return nil } //获取属性值 func (ar *ActiveRecord) GetAttribute(string) interface{} { return nil } //设置属性 func (ar *ActiveRecord) SetAttribute(string, interface{}) bool { return true } //是否有属性 func (ar *ActiveRecord) HasAttribute(string) bool { return true } //插入 func (ar *ActiveRecord) Insert() interface{} { return nil } //更新 func (ar *ActiveRecord) Update() bool { return true } //保存 func (ar *ActiveRecord) Save() bool { return true } //删除 func (ar *ActiveRecord) Delete() bool { return true } //获取数据库连接 func (ar *ActiveRecord) GetDbConnection() *sql.DB { if ar.connect == nil { //获取变量 cu := jconfig.ConfigUtil{} confName := defaultConnectionName keyList := []string{ "db_conf." + confName + ".host", "db_conf." + confName + ".port", "db_conf." + confName + ".dbName", "db_conf." + confName + ".username", "db_conf." + confName + ".password", } var host, portStr, dbName, username, password string cu.GetConfigList(keyList, &host, &portStr, &dbName, &username, &password) port, _ := strconv.ParseInt(portStr,10,64) //连接数据库 connection, err := (&Connection{}).GetConnect(host, port, dbName, username, password) if err != nil { return nil } if ar.isDebug { jlogger.Info("db connected") } ar.connect = connection } return ar.connect } //通过主键查询 func (ar *ActiveRecord) FindByPk(pk int64) interface{} { result := ar.FindByPks([]int64{pk}) if result == nil { return nil } return result[0] } //通过批量主键查询 func (ar *ActiveRecord) FindByPks(pks []int64) []interface{} { _, _, _, primaryKey := ar.getChildConfig() result := ar.FindByAttributes(map[string]interface{}{primaryKey: pks}) return result } //通过批量属性查询 func (ar *ActiveRecord) FindByAttributes(attributes map[string]interface{}) []interface{} { //调用子类函数 connectionName, tablePrefix, tableName, primaryKey := ar.getChildConfig() connection := ar.GetDbConnection() if ar.isManualClose != true { defer func() { CloseConnection(connection) }() } where := ar.buildWhere(attributes) sqlSting := (&Query{}).SetConnectionName(connectionName).SetPrefix(tablePrefix).SetPrimaryKey(primaryKey).Select("*").From(tableName).Where(where).GenSQL() if ar.isDebug { jlogger.Info(sqlSting) } rows, err := connection.Query(sqlSting) if err != nil { return nil } resultList := ar.parseRows(rows) return resultList } //通过主键更新 func (ar *ActiveRecord) UpdateByPk(attributes map[string]interface{}, pk int64) bool { result := ar.UpdateByPks(attributes, []int64{pk}) return result } //通过批量主键更新 func (ar *ActiveRecord) UpdateByPks(attributes map[string]interface{}, pks []int64) bool { _, _, _, primaryKey := ar.getChildConfig() result := ar.UpdateByAttributes(attributes, map[string]interface{}{primaryKey: pks}) return result } //通过批量属性更新 func (ar *ActiveRecord) UpdateByAttributes(attributes map[string]interface{}, condition map[string]interface{}) bool { //调用子类函数 connectionName, tablePrefix, tableName, primaryKey := ar.getChildConfig() connection := ar.GetDbConnection() if ar.isManualClose != true { defer func() { CloseConnection(connection) }() } where := ar.buildWhere(condition) sqlSting := (&Query{}).SetConnectionName(connectionName).SetPrefix(tablePrefix). SetPrimaryKey(primaryKey).Update().From(tableName).SetData(attributes).Where(where).GenSQL() if ar.isDebug { jlogger.Info(sqlSting) } result, err := connection.Exec(sqlSting) if err != nil { return false } affectedRowsCnt, _ := result.RowsAffected() if ar.isDebug { s := fmt.Sprintf("affected rows Cnt:%d", affectedRowsCnt) jlogger.Notice(s) } if affectedRowsCnt > 0 { return true } return false } //通过主键删除 func (ar *ActiveRecord) DeleteByPk(pk int64) bool { result := ar.DeleteByPks([]int64{pk}) return result } //通过批量主键删除 func (ar *ActiveRecord) DeleteByPks(pks []int64) bool { _, _, _, primaryKey := ar.getChildConfig() result := ar.DeleteByAttributes(map[string]interface{}{primaryKey: pks}) return result } //通过批量属性删除 func (ar *ActiveRecord) DeleteByAttributes(attributes map[string]interface{}) bool { connectionName, tablePrefix, tableName, primaryKey := ar.getChildConfig() connection := ar.GetDbConnection() if ar.isManualClose != true { defer func() { CloseConnection(connection) }() } where := ar.buildWhere(attributes) sqlSting := (&Query{}).SetConnectionName(connectionName).SetPrefix(tablePrefix).SetPrimaryKey(primaryKey).Delete().From(tableName).Where(where).GenSQL() if ar.isDebug { jlogger.Info(sqlSting) } result, err := connection.Exec(sqlSting) if err != nil { return false } affectedRowsCnt, _ := result.RowsAffected() if ar.isDebug { s := fmt.Sprintf("affected rows Cnt:%d", affectedRowsCnt) jlogger.Notice(s) } if affectedRowsCnt > 0 { return true } return false } //原生查询 func (ar *ActiveRecord) QueryRaw(sqlString string) []interface{} { connection := ar.GetDbConnection() if ar.isManualClose != true { defer func() { CloseConnection(connection) }() } if ar.isDebug { jlogger.Info(sqlString) } rows, err := connection.Query(sqlString) if err != nil { return nil } result := ar.parseRows(rows) return result } //原生执行 func (ar *ActiveRecord) ExecRaw(sqlString string) bool { connection := ar.GetDbConnection() if ar.isManualClose != true { defer func() { CloseConnection(connection) }() } if ar.isDebug { jlogger.Info(sqlString) } lower := strings.ToLower(sqlString) _, err := connection.Exec(lower) if err != nil { return false } return true } //获取完整表名 func (ar *ActiveRecord) GetFullTableName() string { _, tablePrefix, tableName, _ := ar.getChildConfig() return tablePrefix + tableName } //获取改变了的属性 func (ar *ActiveRecord) GetChangedAttributes() map[string]interface{} { return nil } //获取子类相关配置 func (ar *ActiveRecord) getChildConfig() (string, string, string, string) { connectionName := ar.getChildFuncValue("GetConnectionName") tablePrefix := ar.getChildFuncValue("GetTablePrefix") tableName := ar.getChildFuncValue("GetTableName") primaryKey := ar.getChildFuncValue("GetPrimaryKey") return connectionName, tablePrefix, tableName, primaryKey } //调用子类函数 func (ar *ActiveRecord) getChildFuncValue(funcName string) string { v := reflect.ValueOf(ar.model) method := v.MethodByName(funcName) data := method.Call(make([]reflect.Value, 0)) value := data[0] val := value.String() return val } //计算短名称 func (ar *ActiveRecord) computeShortName() string { t := reflect.TypeOf(ar) fullName := t.String() dotIdx := strings.Index(fullName, ".") shortName := fullName[dotIdx+1:] return shortName } //解析查询结果列表 func (ar *ActiveRecord) parseRows(rows *sql.Rows) []interface{} { //返回结果 if rows == nil { return nil } columns, _ := rows.Columns() columnsLen := len(columns) values := make([][]byte, columnsLen) //这里表示一行填充数据 scans := make([]interface{}, columnsLen) //这里scans引用values,把数据填充到[]byte里 for k := range values { scans[k] = &values[k] } shortName := ar.computeShortName() //遍历 var sList []interface{} for rows.Next() { //填充数据 err := rows.Scan(scans...) if err != nil { break } sCopy := ar.model for colIdx, colVal := range values { column := columns[colIdx] t := reflect.TypeOf(sCopy) v := reflect.ValueOf(sCopy) tEle := t.Elem() vEle := v.Elem() //遍历字段 for i := 0; i < tEle.NumField(); i++ { _v := vEle.Field(i) //字段 field := tEle.Field(i) fieldType := field.Type fieldName := field.Name fieldTag := field.Tag.Get("json") if fieldName == shortName { continue } sColVal := string(colVal) if fieldTag == column { rColValue := ar.buildValue(sColVal, fieldType) _v.Set(rColValue) } } } sList = append(sList, sCopy) } return sList } //构造Value结构数据 func (ar *ActiveRecord) buildValue(value string, t reflect.Type) reflect.Value { convertedValue := jutils.ConvertValueFromString(value, t) return reflect.ValueOf(convertedValue) } //构造Where条件 func (ar *ActiveRecord) buildWhere(attributes map[string]interface{}) string { where := " 1= 1 " for k, v := range attributes { query := "" t := reflect.TypeOf(v) switch t.Kind() { case reflect.Bool: value := reflect.ValueOf(v).Bool() query = fmt.Sprintf(" and %s is %v", k, value) break case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: value := reflect.ValueOf(v).Int() query = fmt.Sprintf(" and %s=%d", k, value) break case reflect.Float32, reflect.Float64: value := reflect.ValueOf(v).Float() query = fmt.Sprintf(" and %s=%f", k, value) break case reflect.String: value := reflect.ValueOf(v).String() if find := strings.Contains(value, "%"); find == true { query = fmt.Sprintf(" and %s like '%s'", k, v) } else { query = fmt.Sprintf(" and %s='%s'", k, v) } break case reflect.Slice: val, _ := json.Marshal(v) value := string(val) value = strings.ReplaceAll(value, "[", "(") value = strings.ReplaceAll(value, "]", ")") query = fmt.Sprintf(" and %s in %s", k, value) break default: query = fmt.Sprintf(" and %s='%s'", k, v) break } where += query } return where }
package checks import ( "fmt" "os/exec" "plugins" ) type ExternalCheck struct { command string name string checkStatus plugins.Status } func (ec *ExternalCheck) Init(config plugins.PluginConfig) (string, error) { // make sure that the command exists? ec.name = config.Name ec.command = config.Command return ec.name, nil } func (ec *ExternalCheck) Gather(r *plugins.Result) error { fmt.Printf("About to start command\n") cmd := exec.Command(ec.command) err := cmd.Run() ec.checkStatus = plugins.UNKNOWN out, errOut := cmd.CombinedOutput() fmt.Println("Output BELOW") fmt.Println(out) r.Add(string(out)) if nil == errOut { ec.checkStatus = plugins.OK } else { ec.checkStatus = plugins.WARNING } return err } func (ec *ExternalCheck) GetStatus() string { return ec.name + " " + ec.checkStatus.ToString() }
package main import ( "bufio" "encoding/binary" "encoding/hex" "encoding/json" "errors" "fmt" "io" "math" "net" "os" "regexp" "runtime" "strconv" "strings" "time" "github.com/fatih/color" "github.com/gordonklaus/portaudio" rpio "github.com/stianeikeland/go-rpio" "github.com/tarm/serial" "golang.org/x/text/encoding/unicode" "golang.org/x/text/transform" ) const pcMicSampleRate = 44100 //44100 const phoneMicSampleRate = 44100 //8000 const seconds = 0.01 // const myIP = "192.168.0.100" var myIP = "192.168.25.17" //default (changes) var conn net.Conn var fetchTime = time.Now var cusdFlag = false var cusd string var atOKFlag = false var moduleIsUp = false var tcpIsUP = false var onMAC = false const connport = 2000 const secondIP = "192.168.25.200" // "192.168.88.253" const tcpPort = 8081 const baudrate = 9600 //const uartPort = "/dev/ttyS0" const uartPort = "/dev/cu.wchusbserial1410" // var multiline = false // var ln net.Listener // var conn net.Conn // Data is for JSON type Data struct { Command string Phone string Text string } // UCS2 is to convert type UCS2 []byte func main() { if runtime.GOOS == "darwin" { onMAC = (runtime.GOOS == "darwin") color.Green("Hello from MAC") } ip, err := externalIP() if err != nil { color.Red("%s", err) color.Red("Because of error, default ip is used") } else { if myIP != ip { color.Red("The ip is changed!\n") } myIP = ip } color.Green("local ip is %s\n", myIP) color.Green("External ip is %s\n", secondIP) // debug := color.New(color.FgRed).PrintfFunc() /** INIT */ portaudio.Initialize() defer portaudio.Terminate() c := &serial.Config{Name: uartPort, Baud: baudrate} uart, err := serial.OpenPort(c) if err != nil { fmt.Print(err) } /** THE UPSTREAM */ upconn, err := net.Dial("udp", fmt.Sprintf("%s:%d", secondIP, connport)) upbuffer := make([]int16, pcMicSampleRate*seconds) upstream, err := portaudio.OpenDefaultStream(1, 0, pcMicSampleRate, len(upbuffer), func(in []int16) { for i := range upbuffer { upbuffer[i] = in[i] //fmt.Sprintf("%f", in[i]) } upconn.Write(int16ArrToByteArr(upbuffer)) if err != nil { fmt.Printf("Some error %v", err) return } }) chk(err) /** THE DOWNSTREAM */ downbuffer := make([]byte, phoneMicSampleRate*seconds) p := make([]byte, phoneMicSampleRate*seconds*2) addr := net.UDPAddr{ Port: connport, IP: net.ParseIP(myIP), } ser, err := net.ListenUDP("udp", &addr) if err != nil { fmt.Printf("Some error %v\n", err) return } downstream, err := portaudio.OpenDefaultStream(0, 1, phoneMicSampleRate, len(downbuffer), func(out []int16) { _, _, err := ser.ReadFromUDP(p) chk(err) buffOut := bytesToInt16Arr(p) for i := range out { out[i] = buffOut[i] } }) chk(err) chk(upstream.Start()) chk(downstream.Start()) //TCP go tcpLoop(&conn, uart) go recieve(&conn, uart) var initCount uint64 = 0 // fmt.Fprintf(conn, "The network is") atOKFlag = true for { initCount++ color.Green("init %d", initCount) time.Sleep(time.Second * 1) sendAT(uart, "AT") //DESTRUCTOR // time.Sleep(time.Second * 2) color.Blue("the check") if !moduleIsUp { color.Red("Module is powered OFF!") if tcpIsUP { fmt.Fprintf(conn, "{\"command\":\"ERROR\", \"text\":\"NO GSM Module found\"}\n") } else { color.Red("NO TCP connection\n") } if !onMAC { err := rpio.Open() if err != nil { fmt.Println(err) os.Exit(0) } pin := rpio.Pin(18) pin.Output() // Output mode // for { color.Yellow("pin 18 set HIGH") pin.High() time.Sleep(2000 * time.Millisecond) color.Yellow("pin 18 set LOW") pin.Low() time.Sleep(5000 * time.Millisecond) // } pin.High() // Set pin High } // os.Exit(0) } } time.Sleep(time.Second) sendAT(uart, "AT+CSQ") time.Sleep(time.Second) sendAT(uart, "AT+CREG?") time.Sleep(time.Second) sendAT(uart, "AT+CLIP=1") time.Sleep(time.Second) sendAT(uart, "AT+CVHU=0") time.Sleep(time.Second * 60 * 60 * 24) color.Red("EXIT, CODE: 0.") defer uart.Close() defer upstream.Close() defer upconn.Close() chk(downstream.Stop()) defer downstream.Close() } func chk(err error) { if err != nil { panic(err) } } func bytesToInt16Arr(in []byte) []int16 { var out [phoneMicSampleRate * seconds]int16 for i := 0; i < len(in)/2; i++ { out[i] = bytesToInt16([]byte{in[i*2], in[i*2+1]}) } return out[:] } func bytesToInt16(in []byte) int16 { // numBytes = []byte{0xf8, 0xe4} u := binary.BigEndian.Uint16(in) // fmt.Printf("%#X %[1]v\n", u) // 0XFF10 65296 return int16(u) } func int16ArrToByteArr(in []int16) []byte { var out [pcMicSampleRate * seconds * 2]byte for i := 0; i < len(in); i++ { var part = int16ToBytes(in[i]) out[i*2] = part[0] out[i*2+1] = part[1] } return out[:] } func int16ToBytes(i int16) []byte { // var out [2]byte var h, l uint8 = uint8(i >> 8), uint8(i & 0xff) return ([]byte{h, l}) } func checkTCP(conn *net.Conn, port io.ReadWriteCloser) { yellow := color.New(color.FgYellow).SprintFunc() red := color.New(color.FgRed).SprintFunc() red2 := color.New(color.FgRed).Add(color.Underline).SprintFunc() for { message, err := bufio.NewReader(*conn).ReadString('\n') if err == nil { color.Green(message) //Getting data from Phone fmt.Printf("Message Received: %s", yellow(string(message))) var data Data err := json.Unmarshal([]byte(message), &data) if err != nil { fmt.Printf("%s %s", red("Problem decoding JSON"), red2(err)) } fmt.Println(data.Command) if len(data.Phone) > 1 { data.Phone = formatPhone(data.Phone) } color.Red(data.Phone) //Working with data if strings.Compare(data.Command, "call") == 0 { fmt.Fprintf(port, "ATD%s;\r\n", data.Phone) } else if strings.Compare(data.Command, "sendUSSD") == 0 { fmt.Fprintf(port, "AT+CUSD=1,\"%s\", 15\r\n", data.Text) } else if strings.Compare(data.Command, "sendSMS") == 0 { var res []rune out := "0001000B91" phone := encodePhone(data.Phone) res = append(res, []rune(out + phone + "00" + "08")[:]...) // res := out + phone + "00" + "08" + "AA" text := hex.EncodeToString(UCS2.Encode([]byte(data.Text))) hexL := strconv.FormatInt(int64(len(text)/2), 16) if len(hexL) < 2 { hexL = "0" + hexL } res = append(res, []rune(hexL)[:]...) res = append(res, []rune(text)[:]...) lengz := len(res)/2 - 1 color.Yellow("Lengz: %d", lengz) fmt.Fprintf(port, "AT+CMGS=%d\r", lengz) time.Sleep(time.Second) fmt.Fprintf(port, "%s\r", string(res)) time.Sleep(time.Second) fmt.Fprintf(port, string([]byte{0x1A})) // sendAT(port, "AT+CMGF=1") // sendAT(port, fmt.Sprintf("AT+CMGS=\"%s\"", data.Phone)) // time.Sleep(time.Second) // fmt.Fprintf(port, data.Text) // time.Sleep(time.Second) // fmt.Fprintf(port, string([]byte{0x1A})) // sendAT(port, "AT+CMGF=0") } else if strings.Compare(data.Command, "AT") == 0 { sendAT(port, data.Text) } else if strings.Compare(data.Command, "status") == 0 { sendAT(port, "AT+CREG?") } else if strings.Compare(data.Command, "rssi") == 0 { sendAT(port, "AT+CSQ") } else if strings.Compare(data.Command, "acceptCall") == 0 { sendAT(port, "ATA") } else if strings.Compare(data.Command, "callEnd") == 0 { sendAT(port, "ATH") } else if strings.Compare(data.Command, "readSMS") == 0 { if data.Text == "" { sendAT(port, "AT+CMGL=\"REC UNREAD\"") } else { fmt.Fprintf(port, "AT+CMGL=\"%s\"", data.Text) } } } else { fmt.Println(err) if err == io.EOF { // conn, _ = ln.Accept() fmt.Println("Error reading:", err.Error()) tcpIsUP = false yo := *conn yo.Close() break } } } // wg.Done() } func sendAT(s io.ReadWriteCloser, comm string) { color.Cyan("sendAT: %s", comm) _, err := s.Write([]byte(fmt.Sprintf("%s\r\n", comm))) if err != nil { fmt.Print(err) } } var voltageErrors = [...]string{"UNDER-VOLTAGE POWER DOWN", "UNDER-VOLTAGE WARNNING", "OVER-VOLTAGE POWER DOWN", "OVER-VOLTAGE WARNNING"} var lastCommand []byte func getResponse(uart io.ReadWriteCloser, conO *net.Conn, in []byte) { conn := *conO yellow := color.New(color.FgYellow).SprintFunc() // red := color.New(color.FgRed).SprintFunc() // green := color.New(color.FgGreen).SprintFunc() epta := color.New(color.FgBlue) epta.Printf("getResponse {%s}", string(in)) // reO := regexp.MustCompile(`((?:.+|\n)+)\r\n`) res0 := strings.Split(string(in), "\r\n") //reO.FindAllString(string(in), -1) for _, item := range res0 { // fmt.Println("conn ", conn) if conn == nil { color.Red("conn is nil") continue } if len(item) == 0 { continue } color.Cyan(hex.Dump([]byte(item))) // item = strings.TrimRight(item, "\n") fmt.Printf(yellow("LAST: {%s}"), item) for _, vE := range voltageErrors { if strings.Index(item, vE) > -1 { color.Red("Under-voltage") fmt.Fprintf(conn, ("{\"command\":\"Under-voltage\"}\n")) } } if strings.Index(item, "+CMTE") > -1 { color.Red("Device is running HOT") fmt.Fprintf(conn, ("{\"command\":\"Device is running HOT\"}\n")) } else if strings.Index(item, "NO CARRIER") > -1 { color.Red("Call ended") fmt.Fprintf(conn, ("{\"command\":\"callEnd\"}\n")) } else if strings.Index(item, "MISSED_CALL:") > -1 { re := regexp.MustCompile(`MISSED\_CALL\:\s\d{2}\:\d{2}(?:AM|PM)\s(\+?\d+)`) res := re.FindStringSubmatch(item) if len(res) > 0 { color.Yellow("Missed Call %s", res[1]) fmt.Fprintf(conn, ("{\"command\":\"missedCall\", \"phone\":\"%s\"}\n"), res[1]) } } else if strings.Index(item, "+CUSD:") > -1 { getCUSD(item) } else if strings.Index(item, "+CLIP:") > -1 { // color.Yellow("CLIP!!!!!!!!!!") re := regexp.MustCompile(`\+CLIP\:\s+\"(\+\d+)"`) res := re.FindStringSubmatch(item) if len(res) > 0 { if res[1] != "" { color.Yellow("Phone number %s", res[1]) fmt.Fprintf(conn, "{\"command\":\"incoming\", \"phone\":\"%s\"}\n", res[1]) } } } else if strings.Index(item, "+CMTI:") > -1 { re := regexp.MustCompile(`\+CMTI\:\s+\"(?:\w+|\s+)+\",(\d+)`) res := re.FindStringSubmatch(item) if len(res) > -1 { color.Yellow("New SMS %s", res[1]) // fmt.Fprintf(conn, yellow("{\"response\":\"new SMS\"}\n")) time.Sleep(time.Second) fmt.Fprintf(uart, "AT+CMGR=%s\r\n", res[1]) } } else if strings.Index(item, "+CMT:") > -1 { getSMS(item) } else if strings.Index(item, "+CMGR:") > -1 { color.Red("Asd") lastCommand = append(lastCommand, item[:]...) item = string(lastCommand) re := regexp.MustCompile(`\+CMGR\:\s\d+,\"(?:.+)?\",\d+\r\n(.+|\n+)\r\n`) rssi := re.FindStringSubmatch(item) fmt.Printf("REGEX CMGR: %v\n", rssi) if len(rssi) > 0 { convBytes := []rune(rssi[1]) index, _ := hex.DecodeString(string(convBytes[26*2 : 27*2])) typeI, _ := hex.DecodeString(string(convBytes[36:38])) color.Green(string(convBytes[26*2 : 27*2])) index2 := len(convBytes) - int(index[0])*2 phone := parsePhone(convBytes[22:34]) converted, _ := hex.DecodeString(string(convBytes[index2:])) text1 := DecodePDU7(string(convBytes[index2:])) text2 := string(UCS2.Decode(converted)) color.Yellow("PDU: %s", rssi[1]) color.Yellow("Length: %d", index) //1 1 color.Yellow("phone: %s", phone) color.Yellow("phone: %s", phone) color.Yellow("SMS: %s", string(convBytes[index2:])) color.Yellow("type: %s", hex.Dump(typeI)) color.Yellow("PDU7: %q", text1) color.Yellow("UCS2: %q", text2) // fmtet := fmt.Sprintf("%q", text1) out := "" // if []rune(fmtet)[1] == []rune("\\")[0] && []rune(fmtet)[2] == []rune("x")[0] { if typeI[0] == 0x08 { out = text2 } else { out = text1 } fmt.Fprintf(conn, ("{\"command\":\"recieveSMS\", \"phone\":\"%s\", \"text\": %q}\n"), phone, out) } } else if strings.Index(item, "+CSQ:") > -1 { re := regexp.MustCompile(`\+CSQ:\s+(\d+),`) rssi := re.FindStringSubmatch(item) if len(rssi) > 0 { color.Yellow("RSSI %s", rssi[1]) fmt.Fprintf(conn, "{\"command\":\"rssi\",\"text\":\"%s\"}\n", rssi[1]) } } else if strings.Index(item, "+CREG:") > -1 { re := regexp.MustCompile(`\+CREG:\s+\d+,(\d+)`) stat := re.FindStringSubmatch(item) fmt.Println(stat) if len(stat) > 0 { color.Yellow("The network is %s", (map[bool]string{true: "connected", false: "searching"})[stat[1] != "0"]) fmt.Fprintf(conn, ("{\"command\":\"connected\", \"text\":\"%s\"}\n"), (map[bool]string{true: "true", false: "false"})[stat[1] != "0"]) } } else if strings.Index(item, "BUSY") > -1 { fmt.Fprintf(conn, ("{\"command\":\"callEnd\"}\n")) } else if strings.Index(item, "ERROR") > -1 { color.Red("ERROR") fmt.Fprintf(conn, ("{\"command\":\"ERROR\"}\n")) } else if strings.Index(item, "OK") > -1 { color.Green("OK") atOKFlag = false moduleIsUp = true // fmt.Fprintf(conn, green("{\"command\":\"OK\"}")) } else if strings.Index(item, "VOICE CALL: END: ") > -1 { var duration int _, err := fmt.Sscanf(item, "VOICE CALL: END: %06d", &duration) if err != nil { panic(err) } else { color.Yellow("Call Duration is %d", duration) fmt.Fprintf(conn, ("{\"command\":\"duration\",\"text\":\"%d\"}\n"), duration) } } else { lastCommand = append(lastCommand, item[:]...) color.Red("LAST response is undefined") continue } lastCommand = lastCommand[:0] } if len(in) == 1 && in[0] == 0 { color.Red("Restart?!") fmt.Fprintf(conn, ("{\"command\":\"Restart?!\"}\n")) } // return out } func recieve(con0 *net.Conn, s io.ReadWriteCloser) { conn := *con0 for { time.Sleep(time.Second) color.Cyan("READING...") buf := make([]byte, 512) n, err := s.Read(buf) if err != nil { fmt.Print(err) } color.Magenta("RAW:") color.Magenta(hex.Dump(buf[:n])) lastCommand = append(lastCommand, buf[:n]...) // fmt.Printf("BEFORE{%s}\n", string(lastCommand)) if len(buf[:n]) == 1 && buf[0] == 0x00 { red := color.New(color.FgRed).SprintFunc() fmt.Fprintf(conn, red("{\"warning\":\"voltage error\"}\n")) } if strings.HasSuffix(string(buf[:n]), "\n") || strings.HasSuffix(string(buf[:n]), string([]byte{0x0d, 0x0a, 0x00})) { color.Green("just \\n") getResponse(s, con0, lastCommand) lastCommand = lastCommand[:0] // fmt.Printf("After{%s}\n", string(lastCommand)) } } } func formatPhone(in string) string { out := strings.Replace(in, " ", "", -1) out = strings.Replace(out, "-", "", -1) out = strings.Replace(out, "(", "", -1) out = strings.Replace(out, ")", "", -1) out = strings.Replace(out, "+", "", -1) if []rune(out)[0] == []rune("8")[0] { out = strings.TrimLeft(out, "8") out = "7" + out } if len(out) == 11 { out = "+" + out return out } return "ERROR" } //Encode is to encode func (s UCS2) Encode() []byte { e := unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM) es, _, err := transform.Bytes(e.NewEncoder(), s) if err != nil { return s } return es } // Decode from UCS2. func (s UCS2) Decode() []byte { e := unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM) es, _, err := transform.Bytes(e.NewDecoder(), s) if err != nil { return s } return es } func parsePhone(in []rune) string { var out [12]rune for i := 0; i < 6; i++ { out[2*i] = in[2*i+1] out[2*i+1] = in[2*i] } return string(out[:11]) } func encodePhone(in string) string { raw := []rune(strings.TrimLeft(in, "+")) raw = append(raw, []rune("F")[0]) var out [12]rune for i := 0; i < 6; i++ { out[2*i] = raw[2*i+1] out[2*i+1] = raw[2*i] } return string(out[:]) } // DecodePDU7 is nice func DecodePDU7(h string) (result string) { var binstr string b, err := hex.DecodeString(h) if err != nil { // May be you need to raise exception here return "" } for i := len(b) - 1; i >= 0; i-- { binstr += fmt.Sprintf("%08b", b[i]) } for len(binstr) > 0 { p := int(math.Max(float64(len(binstr)-7), 0)) b, _ := strconv.ParseUint(binstr[p:], 2, 8) result += string(b) binstr = binstr[:p] } return result } func externalIP() (string, error) { ifaces, err := net.Interfaces() if err != nil { return "", err } for _, iface := range ifaces { if iface.Flags&net.FlagUp == 0 { continue // interface down } if iface.Flags&net.FlagLoopback != 0 { continue // loopback interface } addrs, err := iface.Addrs() if err != nil { return "", err } for _, addr := range addrs { var ip net.IP switch v := addr.(type) { case *net.IPNet: ip = v.IP case *net.IPAddr: ip = v.IP } if ip == nil || ip.IsLoopback() { continue } ip = ip.To4() if ip == nil { continue // not an ipv4 address } return ip.String(), nil } } return "", errors.New("are you connected to the network?") } func tcpLoop(conn *net.Conn, uart io.ReadWriteCloser) { ln, _ := net.Listen("tcp", fmt.Sprintf(":%d", tcpPort)) color.Blue("Waiting for TCP connection...") var err error for { *conn, err = ln.Accept() fmt.Println("conn ", conn) tcpIsUP = true if err != nil { color.Red("Error TCP connection: ", err.Error()) os.Exit(1) } time.Sleep(10 * time.Millisecond) // wg.Add(1) go checkTCP(conn, uart) } } func getCUSD(item string) { color.Green("getResponse+CUSD") re := regexp.MustCompile(`\+CUSD:\s\d+,(?:\s+)?\"((?:(?:.+)|\n+)+)\"?,\s?\d+`) res := re.FindStringSubmatch(item) fmt.Printf("REGEX CUSD: %v\n", res) if len(res) > 0 { converted := "" convBytes, epta := hex.DecodeString(res[1]) if epta != nil { converted = res[1] } else { converted = string(UCS2.Decode(convBytes)) } color.Yellow("The USSD result is %s", converted) fmt.Fprintf(conn, ("{\"command\":\"USSD\",\"text\":%q}\n"), converted) } else { // cusdFlag = true getCUSD(string(lastCommand) + item) } } func getSMS(item string) { color.Green("getSMS +CMT:") re := regexp.MustCompile(`\+CMT:\s\"\",\d+(?:\r|\n|\r\n)([A-F0-9a-f]+)`) res := re.FindStringSubmatch(item) fmt.Printf("REGEX SMS: %v\n", res) if len(res) > 0 { convBytes := []rune(res[1]) index, _ := hex.DecodeString(string(convBytes[26*2 : 27*2])) typeI, _ := hex.DecodeString(string(convBytes[36:38])) color.Green(string(convBytes[26*2 : 27*2])) var index2 int if typeI[0] == 0x08 { index2 = len(convBytes) - int(index[0])*2 } else { index2 = len(convBytes) - LenghtInSep(int(index[0]))*2 } phone := parsePhone(convBytes[22:34]) converted, _ := hex.DecodeString(string(convBytes[index2:])) text1 := DecodePDU7(string(convBytes[index2:])) text2 := string(UCS2.Decode(converted)) color.Yellow("PDU: %s", res[1]) color.Yellow("Length: %d", index) //1 1 color.Yellow("phone: %s", phone) // color.Yellow("phone: %s", phone) color.Yellow("SMS: %s", string(convBytes[index2:])) color.Yellow("type: %s", hex.Dump(typeI)) color.Yellow("PDU7: %q", text1) color.Yellow("UCS2: %q", text2) // fmtet := fmt.Sprintf("%q", text1) out := "" // if []rune(fmtet)[1] == []rune("\\")[0] && []rune(fmtet)[2] == []rune("x")[0] { if typeI[0] == 0x08 { out = text2 color.Red("Hextets: %d", index) //1 1 color.Yellow("UCS2: %q", text2) } else { out = text1 color.Red("Septets: %d", LenghtInSep(int(index[0]))) //1 1 color.Yellow("PDU7: %q", text1) } fmt.Fprintf(conn, ("{\"command\":\"recieveSMS\", \"phone\":\"%s\", \"text\": %q}\n"), phone, strings.TrimRight(out, "\x00")) } else { // cusdFlag = true getSMS(string(lastCommand) + item) } } //LenghtInSep asd func LenghtInSep(in int) int { var out float64 out = float64(in) * 7.0 / 8.0 chk := math.Floor(out) if chk == out { return int(out) } return int(chk) + 1 }
package main import "fmt" type concert interface { getPrice() int } type ticket struct { } func (t *ticket) getPrice() int { return 10000 } type vipZone struct { concert concert } func (o *vipZone) getPrice() int { ticketPrice := o.concert.getPrice() return ticketPrice + 6000 } type armyBomb struct { concert concert } func (o *armyBomb) getPrice() int { ticketPrice := o.concert.getPrice() return ticketPrice + 6000 } func main() { concertTicket := &ticket{} concertWithArmyBomb := &armyBomb{ concert: concertTicket, } concertWithArmyBombInVipZone := &vipZone{ concert: concertWithArmyBomb, } fmt.Printf("Price of BTS concert with army bomb in vip zone is %d\n", concertWithArmyBombInVipZone.getPrice()) }
package types import ( "math" "testing" sdk "github.com/irisnet/irishub/types" "github.com/stretchr/testify/require" ) func TestValidateParams(t *testing.T) { tests := []struct { testCase string Params expectPass bool }{ {"Minimum value", Params{ AssetTaxRate: sdk.ZeroDec(), MintTokenFeeRatio: sdk.ZeroDec(), GatewayAssetFeeRatio: sdk.ZeroDec(), IssueTokenBaseFee: sdk.NewCoin(sdk.IrisAtto, sdk.ZeroInt()), CreateGatewayBaseFee: sdk.NewCoin(sdk.IrisAtto, sdk.ZeroInt()), }, true, }, {"Maximum value", Params{ AssetTaxRate: sdk.NewDec(1), MintTokenFeeRatio: sdk.NewDec(1), GatewayAssetFeeRatio: sdk.NewDec(1), IssueTokenBaseFee: sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(math.MaxInt64)), CreateGatewayBaseFee: sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(math.MaxInt64)), }, true, }, {"AssetTaxRate less than the maximum", Params{ AssetTaxRate: sdk.NewDecWithPrec(-1, 1), MintTokenFeeRatio: sdk.NewDec(0), GatewayAssetFeeRatio: sdk.NewDec(0), IssueTokenBaseFee: sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(1)), CreateGatewayBaseFee: sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(1)), }, false, }, {"MintTokenFeeRatio less than the maximum", Params{ AssetTaxRate: sdk.NewDec(0), MintTokenFeeRatio: sdk.NewDecWithPrec(-1, 1), GatewayAssetFeeRatio: sdk.NewDec(0), IssueTokenBaseFee: sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(1)), CreateGatewayBaseFee: sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(1)), }, false, }, {"GatewayAssetFeeRatio less than the maximum", Params{ AssetTaxRate: sdk.NewDec(0), MintTokenFeeRatio: sdk.NewDec(0), GatewayAssetFeeRatio: sdk.NewDecWithPrec(-1, 1), IssueTokenBaseFee: sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(1)), CreateGatewayBaseFee: sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(1)), }, false, }, {"AssetTaxRate greater than the maximum", Params{ AssetTaxRate: sdk.NewDecWithPrec(11, 1), MintTokenFeeRatio: sdk.NewDec(1), GatewayAssetFeeRatio: sdk.NewDec(1), IssueTokenBaseFee: sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(1)), CreateGatewayBaseFee: sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(1)), }, false, }, {"MintTokenFeeRatio greater than the maximum", Params{ AssetTaxRate: sdk.NewDec(1), MintTokenFeeRatio: sdk.NewDecWithPrec(11, 1), GatewayAssetFeeRatio: sdk.NewDec(1), IssueTokenBaseFee: sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(1)), CreateGatewayBaseFee: sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(1)), }, false, }, {"GatewayAssetFeeRatio greater than the maximum", Params{ AssetTaxRate: sdk.NewDec(1), MintTokenFeeRatio: sdk.NewDec(1), GatewayAssetFeeRatio: sdk.NewDecWithPrec(11, 1), IssueTokenBaseFee: sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(1)), CreateGatewayBaseFee: sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(1)), }, false, }, {"IssueTokenBaseFee is negative", Params{ AssetTaxRate: sdk.NewDec(1), MintTokenFeeRatio: sdk.NewDec(1), GatewayAssetFeeRatio: sdk.NewDec(1), IssueTokenBaseFee: sdk.Coin{Denom: sdk.IrisAtto, Amount: sdk.NewInt(-1)}, CreateGatewayBaseFee: sdk.Coin{Denom: sdk.IrisAtto, Amount: sdk.NewInt(1)}, }, false, }, {"CreateGatewayBaseFee is Negative", Params{ AssetTaxRate: sdk.NewDec(1), MintTokenFeeRatio: sdk.NewDec(1), GatewayAssetFeeRatio: sdk.NewDec(1), IssueTokenBaseFee: sdk.Coin{Denom: sdk.IrisAtto, Amount: sdk.NewInt(1)}, CreateGatewayBaseFee: sdk.Coin{Denom: sdk.IrisAtto, Amount: sdk.NewInt(-1)}, }, false, }, } for _, tc := range tests { if tc.expectPass { require.Nil(t, ValidateParams(tc.Params), "test: %v", tc.testCase) } else { require.NotNil(t, ValidateParams(tc.Params), "test: %v", tc.testCase) } } }
package ibm import ( "fmt" "testing" ) const ( ibmTranslatorBaseURL = "https://gateway.watsonplatform.net/" ibmTranslatorAPIKey = "0X0NrhL0wUYsDmWKAAIegoUhOcUp3cazYNz6-Rv-81uJ" ) func Test_Translate(t *testing.T) { tr, err := NewIBMTranslatorClient(ibmTranslatorBaseURL, ibmTranslatorAPIKey, 5) if err != nil { t.Fatal(err) } result, err := tr.Translate("ローマ") if err != nil { t.Fatal(err) } fmt.Printf("result: %v\n", result) if result != "Rome" { t.Errorf("Unexpected result! expexted: %s, actual: %s", "Rome", result) } }
package models // init 初始化 func init() { // orm.RegisterModel(new(User), new(Profile)) }
package db import ( "godis/src/datastruct/dict" List "godis/src/datastruct/list" "godis/src/datastruct/lock" "sync" "time" ) type DataEntity struct { Data interface{} } const ( dataDictSize = 1 << 16 ttlDictSize = 1 << 10 lockerSize = 128 aofQueueSize = 1 << 16 ) type DB struct { Data dict.Dict TTLMap dict.Dict sunMap dict.Dict Locker *lock.Locks interval time.Duration stopWorld sync.WaitGroup } func NewDB() *DB { db := &DB{ Data: dict.NewConcurrent(dataDictSize), TTLMap: dict.NewConcurrent(ttlDictSize), Locker: lock.New(lockerSize), interval: 5 * time.Second, } } func (db *DB) IsExpired(key string) bool { rawExpireTime, ok := db.TTLMap.Get(key) if !ok { return false } expireTime, _ := rawExpireTime.(time.Time) expired := time.Now().After(expireTime) if expired { db.Remove(key) } return expired } func (db *DB) Get(key string) (*DataEntity, bool) { db.stopWorld.Wait() raw, ok := db.Data.Get(key) if !ok { return nil, false } if db.IsExpired(key) { return nil, false } entity, _ := raw.(*DataEntity) return entity, true } func (db *DB) Remove(key string) { db.stopWorld.Wait() db.Data.Remove(key) db.TTLMap.Remove(key) } func (db *DB) CleanExpired() { now := time.Now() toRemove := &List.LinkedList{} db.TTLMap.ForEach(func(key string, val interface{}) bool { expiredTime, _ := val.(time.Time) if now.After(expiredTime) { db.Data.Remove(key) toRemove.Add(key) } return true }) toRemove.ForEach(func(i int, val interface{}) bool { key, _ := val.(string) db.TTLMap.Remove(key) return true }) } func (db *DB) TimerTash() { ticker := time.NewTicker(db.interval) go func() { for range ticker.C { db.CleanExpired() } }() }
package process type CNC struct{ Station } func (x CNC) StateNum() string { return "No.1" } func (x CNC) Machine() string { return "Milling machine" }
/* Package pageContext "Every package should have a package comment, a block comment preceding the package clause. For multi-file packages, the package comment only needs to be present in one file, and any one will do. The package comment should introduce the package and provide information relevant to the package as a whole. It will appear first on the godoc page and should set up the detailed documentation that follows." */ package pageContext import ( "golang.org/x/net/context" "google.golang.org/appengine/datastore" ) // GetKeysByPageOrContextKey returns the pageContext keys with context keys as a slice // if the page key is provided or returns the page keys as a slice // if context key is provided and also an error. func GetKeysByPageOrContextKey(ctx context.Context, key *datastore.Key) ( []*datastore.Key, []*datastore.Key, error) { var kx []*datastore.Key var kporcx []*datastore.Key q := datastore.NewQuery("PageContext") kind := key.Kind() switch kind { case "Context": q = q. Filter("ContextKey =", key). KeysOnly() for it := q.Run(ctx); ; { k, err := it.Next(nil) if err == datastore.Done { return kx, kporcx, err } if err != nil { return nil, nil, err } kx = append(kx, k) kporcx = append(kporcx, k.Parent()) } default: // "Page" kind q = q. Ancestor(key) for it := q.Run(ctx); ; { pc := new(PageContext) k, err := it.Next(pc) if err == datastore.Done { return kx, kporcx, err } if err != nil { return nil, nil, err } kx = append(kx, k) kporcx = append(kporcx, pc.ContextKey) } } } /* GetKeys returns corresponding pageContext keys by provided context or page key and also returns an error. */ func GetKeys(ctx context.Context, k *datastore.Key) ([]*datastore.Key, error) { q := datastore.NewQuery("PageContext") if k.Kind() == "Page" { q = q. Ancestor(k) } else { q = q. Filter("ContextKey =", k) } q = q. KeysOnly() return q.GetAll(ctx, nil) } // GetCount returns the count of the entities that has provided key and an error. func GetCount(ctx context.Context, k *datastore.Key) (c int, err error) { q := datastore.NewQuery("PageContext") if k.Kind() == "Page" { q = q. Ancestor(k) } else { q = q.Filter("ContextKey =", k) } c, err = q.Count(ctx) return }
package str2int import "testing" func TestSolve(t *testing.T) { result, err := Atoi("01") if err != nil { t.Log(err) } t.Log(result) }
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "fmt" "os" "strconv" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/urfave/cli/v2" "github.com/kubernetes-sigs/cri-tools/pkg/common" ) var configCommand = &cli.Command{ Name: "config", Usage: "Get and set crictl options", ArgsUsage: "[<options>]", UseShortOptionHandling: true, Flags: []cli.Flag{ &cli.StringFlag{ Name: "get", Usage: "get value: name", }, }, Action: func(context *cli.Context) error { configFile := context.String("config") if _, err := os.Stat(configFile); err != nil { if err := common.WriteConfig(nil, configFile); err != nil { return err } } // Get config from file. config, err := common.ReadConfig(configFile) if err != nil { return errors.Wrap(err, "load config file") } if context.IsSet("get") { get := context.String("get") switch get { case "runtime-endpoint": fmt.Println(config.RuntimeEndpoint) case "image-endpoint": fmt.Println(config.ImageEndpoint) case "timeout": fmt.Println(config.Timeout) case "debug": fmt.Println(config.Debug) default: logrus.Fatalf("No section named %s", get) } return nil } key := context.Args().First() if key == "" { return cli.ShowSubcommandHelp(context) } value := context.Args().Get(1) switch key { case "runtime-endpoint": config.RuntimeEndpoint = value case "image-endpoint": config.ImageEndpoint = value case "timeout": n, err := strconv.Atoi(value) if err != nil { logrus.Fatal(err) } config.Timeout = n case "debug": var debug bool if value == "true" { debug = true } else if value == "false" { debug = false } else { logrus.Fatal("use true|false for debug") } config.Debug = debug default: logrus.Fatalf("No section named %s", key) } return common.WriteConfig(config, configFile) }, }
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { scan := scanner() cnt := scan() for i := 0; i < cnt; i++ { n := scan() // 5a + 3b = n a := 0 found := false for a <= n/5 && !found { b := 0 for b <= n/3 { sum := a*5 + b*3 if sum < n { b++ } else if sum == n { fmt.Printf("%s%s\n", strings.Repeat("5", b*3), strings.Repeat("3", a*5)) found = true break } else { break } } a++ } if !found { fmt.Println(-1) } } } func scanner() func() int { scan := bufio.NewScanner(os.Stdin) scan.Split(bufio.ScanWords) return func() int { scan.Scan() i, _ := strconv.Atoi(scan.Text()) return i } }
package v1 type Dictionary map[string]string func (dict Dictionary) Search(key string) string { return dict[key] }
package main import ( "fmt" "github.com/oho-sugu/graphdb" ) func main() { db, _ := graphdb.Open("celegans.db") start := db.GetNode(NEURON, no2ID("0")) edges := db.GetNodesEdge(start) for _, edge := range edges { fmt.Println(graphdb.Byte2string(edge.To)) } }
package pg import ( "database/sql" "fmt" . "grm-searcher/types" . "grm-service/dbcentral/pg" "strings" ) type DataDB struct { DataCentralDB } func (db DataDB) GetTableData(r SearchInfo) (*TableData, error) { var tableData TableData var tableName, sqlStr string tableName = fmt.Sprintf(`"ftr-%s"`, r.DataId) where := fmt.Sprintf("ST_Intersects(ST_Transform(geom,4326),ST_GeometryFromText('%s', 4326)) ", r.Geometry) total := db.GetTotalCountWhere(tableName, where) tableData.Total = int(total) sqlStr = fmt.Sprintf(`select *, ST_AsGeoJSON(geom) as geom_json from %s where %s`, tableName, where) if len(r.Sort) > 0 && len(r.Order) > 0 { sqlStr = fmt.Sprintf(`%s order by %s %s`, sqlStr, r.Sort, r.Order) } else { sqlStr = fmt.Sprintf(`%s order by gid`, sqlStr) } if len(r.Offset) > 0 && len(r.Limit) > 0 { sqlStr = fmt.Sprintf(`%s limit %s offset %s`, sqlStr, r.Limit, r.Offset) } rows, err := db.Conn.Query(sqlStr) if err != nil { return &tableData, err } defer rows.Close() cols, err := rows.Columns() if err != nil { return &tableData, err } var colName Row var _geoIndex int = -1 for geoIndex, val := range cols { if val == "geom" { _geoIndex = geoIndex continue } colName.Rows = append(colName.Rows, val) } tableData.Datas = append(tableData.Datas, colName) values := make([]sql.NullString, len(cols)) scanArgs := make([]interface{}, len(values)) for i := range values { scanArgs[i] = &values[i] } for rows.Next() { rows.Scan(scanArgs...) var row Row for i, col := range values { if _geoIndex >= 0 && i == _geoIndex { continue } var value string if col.Valid { value = col.String } row.Rows = append(row.Rows, value) } tableData.Datas = append(tableData.Datas, row) } if err := rows.Err(); err != nil { return &tableData, err } return &tableData, nil } func (db DataDB) GetDataIds(userid string, ds, data_ids []string) ([]string, error) { sql := fmt.Sprintf("select data_id from ref_data_user where data_set in (%s) and user_id = '%s'", strings.Join(ds, ","), userid) rows, err := db.Conn.Query(sql) if err != nil { return data_ids, err } var data_id string for rows.Next() { err := rows.Scan(&data_id) if err != nil { continue } data_ids = append(data_ids, data_id) } rows.Close() return data_ids, nil } func (db DataDB) GetTotalCountWhere(tableName, where string) int64 { var total int64 = 0 sql := fmt.Sprintf("select count(*) from %s where %s;", tableName, where) rows, err := db.Conn.Query(sql) if err != nil { return total } defer rows.Close() for rows.Next() { rows.Scan(&total) return total } return total }
package db import ( "fmt" "time" "github.com/kotakanbe/goval-dictionary/db/rdb" "github.com/kotakanbe/goval-dictionary/models" ) // DB is interface for a database driver type DB interface { Name() string NewOvalDB(string) error CloseDB() error GetByPackName(string, string) ([]models.Definition, error) GetByCveID(string, string) ([]models.Definition, error) InsertOval(*models.Root, models.FetchMeta) error InsertFetchMeta(models.FetchMeta) error CountDefs(string, string) (int, error) GetLastModified(string, string) time.Time } // NewDB return DB accessor. func NewDB(family, dbType, dbpath string, debugSQL bool) (db DB, locked bool, err error) { switch dbType { case rdb.DialectSqlite3, rdb.DialectMysql, rdb.DialectPostgreSQL: return rdb.NewRDB(family, dbType, dbpath, debugSQL) case dialectRedis: return NewRedis(family, dbType, dbpath, debugSQL) } return nil, false, fmt.Errorf("Invalid database dialect, %s", dbType) }
package executor import "github.com/alehatsman/mooncake/internal/logger" type ExecutionContext struct { Variables map[string]interface{} CurrentDir string CurrentFile string Level int Logger *logger.Logger SudoPass string } func (ec *ExecutionContext) Copy() ExecutionContext { newVariables := make(map[string]interface{}) for k, v := range ec.Variables { newVariables[k] = v } return ExecutionContext{ Variables: newVariables, CurrentDir: ec.CurrentDir, CurrentFile: ec.CurrentFile, Level: ec.Level, Logger: ec.Logger, SudoPass: ec.SudoPass, } }
package main import ( "sync/atomic" "fmt" "runtime" "sync" ) func test(c chan int) { c <- 'A' } func testDeadLock(c chan int) { for { fmt.Println(<-c) } } var ( count int32 wg sync.WaitGroup ) func main() { // c := make(chan int) // go test(c) // go testDeadLock(c) // <- c // <- c wg.Add(2) go incCountAutomic() go incCountAutomic() wg.Wait() fmt.Println(count) } func incCount() { defer wg.Done() for i := 0; i < 2; i++ { value := atomic.LoadInt32(&count) // 是让当前goroutine暂停的意思,退回执行队列,让其他goroutine运行 runtime.Gosched() value++ atomic.StoreInt32(&count,value) } } func incCountAutomic() { defer wg.Done() for i := 0; i < 2; i++ { value := count // 是让当前goroutine暂停的意思,退回执行队列,让其他goroutine运行 runtime.Gosched() value++ count = value } }
package main import ( "flag" "fmt" ) type Config struct { Auth string `toml:"auth"` Bind string `toml:"bind"` Ca string `toml:"ca,omitempty"` Cert string `toml:"cert"` Key string `toml:"key"` } func newConfig() *Config { return &Config{ Auth: "localhost:8080", Bind: ":8082", Ca: "../tls_setup/certs/ca.pem", Cert: "../tls_setup/certs/exec.pem", Key: "../tls_setup/certs/exec.key", } } func usage(fl *flag.FlagSet) func() { return func() { fmt.Printf("Usage: exec-server [options]\n\nOptions:\n") fl.PrintDefaults() } } func (c *Config) setFlags() *flag.FlagSet { fl := flag.NewFlagSet("", flag.ExitOnError) fl.Usage = usage(fl) fl.StringVar(&c.Auth, "auth", c.Auth, "Authentication service address.") fl.StringVar(&c.Bind, "bind", c.Bind, "Bind server to address.") fl.StringVar(&c.Ca, "ca", c.Ca, "TLS CA certificate.") fl.StringVar(&c.Cert, "cert", c.Cert, "Service TLS certificate.") fl.StringVar(&c.Key, "key", c.Key, "Service TLS key.") return fl }
package local import ( "fmt" "runtime" "testing" ) func TestFindingTests(t *testing.T) { p, err := NewProject("testdata/cases") if err != nil { t.Fatal(err) } if err := p.Init(); err != nil { t.Fatal(err) } var expected []Result switch runtime.GOOS { case "darwin": expected = []Result{ {Name: "test.osx.test"}, {Name: "test.win"}, {Name: "test.apps.test"}, {Name: "test.apps.basic.test"}, {Name: "test.apps.advanced.test"}, } case "windows": expected = []Result{ {Name: "test.osx"}, {Name: "test.win.test"}, {Name: "test.win.ps1.test"}, {Name: "test.apps.test"}, {Name: "test.apps.basic.test"}, {Name: "test.apps.advanced.test"}, } default: expected = []Result{ {Name: "test.osx"}, {Name: "test.win"}, {Name: "test.apps.test"}, {Name: "test.apps.basic.test"}, {Name: "test.apps.advanced.test"}, } } config := NewRunConfig("", "") l := p.List(config) for i, tst := range l { if expected[i].Name != tst.Name { t.Fatalf("Error in test ordering:\n Got %+v\nExpected %+v\n", tst, expected[i]) } } } func TestTestPattern(t *testing.T) { p, err := NewProject("testdata/cases") if err != nil { t.Fatal(err) } if err := p.Init(); err != nil { t.Fatal(err) } config := RunConfig{TestPattern: "test.apps.basic"} l := p.List(config) for _, tst := range l { if tst.Name == "test.apps.advanced.test" && tst.TestResult != Skip { t.Fatal("test.apps.advanced.test does not match the TestPattern test.apps.basic") } if tst.Name == "test.apps.basic.test" && tst.TestResult != Pass { t.Fatal("test.apps.basic.test matches the TestPattern but is not going to run") } fmt.Printf("Name: %s Summary: %s CheckLabel: %d\n", tst.Name, tst.Summary, tst.TestResult) } }
package structs type Service struct { Name string `json:"name"` Stack string `json:"-"` Status string `json:"status"` StatusReason string `json:"status-reason"` Type string `json:"type"` Apps Apps `json:"apps"` Exports map[string]string `json:"exports"` Outputs map[string]string `json:"-"` Parameters map[string]string `json:"-"` Tags map[string]string `json:"-"` } type Services []Service
package blevebench import ( "github.com/blevesearch/bleve" "github.com/blevesearch/bleve/mapping" ) // BuildArticleMapping returns a mapping for indexing wikipedia articles // in a manner similar to that done by lucene nightly benchmarks func BuildArticleMapping() mapping.IndexMapping { // a generic reusable mapping for english text standardJustIndexed := bleve.NewTextFieldMapping() standardJustIndexed.Store = false standardJustIndexed.IncludeInAll = false standardJustIndexed.IncludeTermVectors = false standardJustIndexed.Analyzer = "standard" keywordJustIndexed := bleve.NewTextFieldMapping() keywordJustIndexed.Store = false keywordJustIndexed.IncludeInAll = false keywordJustIndexed.IncludeTermVectors = false keywordJustIndexed.Analyzer = "keyword" articleMapping := bleve.NewDocumentMapping() // title articleMapping.AddFieldMappingsAt("title", keywordJustIndexed) // text articleMapping.AddFieldMappingsAt("text", standardJustIndexed) // _all (disabled) disabledSection := bleve.NewDocumentDisabledMapping() articleMapping.AddSubDocumentMapping("_all", disabledSection) indexMapping := bleve.NewIndexMapping() indexMapping.DefaultMapping = articleMapping indexMapping.DefaultAnalyzer = "standard" return indexMapping }
// Copyright 2020 Authors of Cilium // // 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 defaults import "time" const ( Debug = false HubbleCAGenerate = false HubbleCAReuseSecret = false HubbleCACommonName = "hubble-ca.cilium.io" HubbleCAValidityDuration = 3 * 365 * 24 * time.Hour HubbleCASecretName = "hubble-ca-secret" HubbleCAConfigMapCreate = false HubbleCAConfigMapName = "hubble-ca-cert" HubbleServerCertGenerate = false HubbleServerCertCommonName = "*.default.hubble-grpc.cilium.io" HubbleServerCertValidityDuration = 3 * 365 * 24 * time.Hour HubbleServerCertSecretName = "hubble-server-certs" HubbleRelayServerCertGenerate = false HubbleRelayServerCertCommonName = "*.hubble-relay.cilium.io" HubbleRelayServerCertValidityDuration = 3 * 365 * 24 * time.Hour HubbleRelayServerCertSecretName = "hubble-relay-server-certs" HubbleRelayClientCertGenerate = false HubbleRelayClientCertCommonName = "*.hubble-relay.cilium.io" HubbleRelayClientCertValidityDuration = 3 * 365 * 24 * time.Hour HubbleRelayClientCertSecretName = "hubble-relay-client-certs" CiliumNamespace = "kube-system" ClustermeshApiserverCACertGenerate = false ClustermeshApiserverCACertReuseSecret = false ClustermeshApiserverCACertCommonName = "clustermesh-apiserver-ca.cilium.io" ClustermeshApiserverCACertValidityDuration = 3 * 365 * 24 * time.Hour ClustermeshApiserverCACertSecretName = "clustermesh-apiserver-ca-cert" ClustermeshApiserverServerCertGenerate = false ClustermeshApiserverServerCertCommonName = "clustermesh-apiserver.cilium.io" ClustermeshApiserverServerCertValidityDuration = 3 * 365 * 24 * time.Hour ClustermeshApiserverServerCertSecretName = "clustermesh-apiserver-server-cert" ClustermeshApiserverAdminCertGenerate = false ClustermeshApiserverAdminCertCommonName = "root" ClustermeshApiserverAdminCertValidityDuration = 3 * 365 * 24 * time.Hour ClustermeshApiserverAdminCertSecretName = "clustermesh-apiserver-admin-cert" ClustermeshApiserverClientCertGenerate = false ClustermeshApiserverClientCertCommonName = "externalworkload" ClustermeshApiserverClientCertValidityDuration = 3 * 365 * 24 * time.Hour ClustermeshApiserverClientCertSecretName = "clustermesh-apiserver-client-cert" ClustermeshApiserverRemoteCertGenerate = false ClustermeshApiserverRemoteCertCommonName = "remote" ClustermeshApiserverRemoteCertValidityDuration = 3 * 365 * 24 * time.Hour ClustermeshApiserverRemoteCertSecretName = "clustermesh-apiserver-remote-cert" K8sRequestTimeout = 60 * time.Second ) var ( HubbleServerCertUsage = []string{"signing", "key encipherment", "server auth"} HubbleRelayServerCertUsage = []string{"signing", "key encipherment", "server auth"} HubbleRelayClientCertUsage = []string{"signing", "key encipherment", "server auth", "client auth"} ClustermeshApiserverCertUsage = []string{"signing", "key encipherment", "server auth", "client auth"} )
package golang type FreqRecord struct { accFreq int freq int val int } func sampleStats(count []int) []float64 { record := make([]FreqRecord, 0) sum, minimum, maximum, mode, maxFreq, accFreq := 0, 256, -1, 0, 0, 0 for i := 0; i < 256; i++ { if count[i] == 0 { continue } sum += i * count[i] accFreq += count[i] record = append( record, FreqRecord{accFreq: accFreq, val: i, freq: count[i]}, ) minimum = min(minimum, i) maximum = max(maximum, i) if count[i] > maxFreq { mode = i maxFreq = count[i] } } return []float64{ float64(minimum), float64(maximum), float64(sum) / float64(accFreq), getMedian(record, accFreq), float64(mode), } } func getMedian(record []FreqRecord, accFreq int) float64 { if accFreq%2 == 0 { idx := binarySearch(record, accFreq/2) if record[idx].accFreq == accFreq/2 { return float64(record[idx].val+record[idx+1].val) / 2 } else { return float64(record[idx].val) } } else { idx := binarySearch(record, (accFreq/2)+1) return float64(record[idx].val) } } func binarySearch(record []FreqRecord, target int) int { begin, end := 0, len(record) for begin < end { mid := (end-begin)/2 + begin if record[mid].accFreq >= target { end = mid } else { begin = mid + 1 } } return end } func min(x, y int) int { if x < y { return x } else { return y } } func max(x, y int) int { if x < y { return y } else { return x } }
package form import ( "bytes" "github.com/astaxie/beego/logs" "text/template" ) type RadioInput struct { Name string Options []SelectOption } func (r *RadioInput) String() string { html := `{{with and ($name := .Name) ($options := .Options)}}{{range $option := $options}}<input type="radio" name="{{$name}}" value="{{$option.Value}}" title="{{$option.Title}}" {{if $option.Checked}}checked=""{{end}}{{if $option.Disabled}}disabled=""{{end}}>{{end}}{{end}}` var buf bytes.Buffer tpl, err := template.New("radio").Parse(html) if err != nil { logs.Error(err) return "" } err = tpl.Execute(&buf, r) if err != nil { logs.Error(err) } return buf.String() } func (r *RadioInput) ReadFromOptions(options ...string) { if r.Name == "" { r.Name = "Undefined" } }
/* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package minibroker import ( "testing" "helm.sh/helm/v3/pkg/chart" "helm.sh/helm/v3/pkg/repo" ) func TestHasTag(t *testing.T) { tagTests := []struct { tag string list []string expected bool }{ {"foo", []string{"foo", "bar"}, true}, {"foo", []string{"bar", "baz"}, false}, {"foo", []string{}, false}, } for _, tt := range tagTests { actual := hasTag(tt.tag, tt.list) if actual != tt.expected { t.Errorf("hasTag(%s %v): expected %t, actual %t", tt.tag, tt.list, tt.expected, actual) } } } func TestGetTagIntersection(t *testing.T) { intersectionTests := []struct { charts repo.ChartVersions expected []string }{ {nil, []string{}}, { repo.ChartVersions{ &repo.ChartVersion{ Metadata: &chart.Metadata{ Keywords: []string{}, }, }, }, []string{}, }, { repo.ChartVersions{ &repo.ChartVersion{ Metadata: &chart.Metadata{ Keywords: []string{"foo", "bar"}, }, }, }, []string{"foo", "bar"}}, { repo.ChartVersions{ &repo.ChartVersion{ Metadata: &chart.Metadata{ Keywords: []string{"foo", "bar"}, }, }, &repo.ChartVersion{ Metadata: &chart.Metadata{ Keywords: []string{"baz", "foo"}, }, }, }, []string{"foo"}}, } for _, tt := range intersectionTests { actual := getTagIntersection(tt.charts) if len(actual) != len(tt.expected) { t.Errorf("getTagIntersection(%v): expected %v, actual %v", tt.charts, tt.expected, actual) break } for index, keyword := range actual { if keyword != tt.expected[index] { t.Errorf("getTagIntersection(%v): expected %v, actual %v", tt.charts, tt.expected, actual) } } } }
package primitives const VERTEX_SIZE = 10 type Vertex struct { position Vec4 color Vec4 uv Vec2 }
package ejbcarest import "time" // PKCS10EnrolRequest represents data to send to enrol certificate using PKCS#10. type PKCS10EnrolRequest struct { CSR string `json:"certificate_request"` CertificateProfileName string `json:"certificate_profile_name"` EndEntityProfileName string `json:"end_entity_profile_name"` CAName string `json:"certificate_authority_name"` Username string `json:"username"` Password string `json:"password"` IncludeChain bool `json:"include_chain"` } // PKCS10EnrolResponse represents response received after successful certificate enrolment using PKCS#10. type PKCS10EnrolResponse struct { Certificate string `json:"certificate"` SerialNumber string `json:"serial_number"` ResponseFormat string `json:"response_format"` CertificateChain []string `json:"certificate_chain"` } // KeystoreEnrolRequest represents data to send to enrol keystore. type KeystoreEnrolRequest struct { Username string `json:"username"` Password string `json:"password"` Algorithm string `json:"key_alg"` Spec string `json:"key_spec"` } // KeystoreEnrolResponse represents response received after successful keystore enrolment. type KeystoreEnrolResponse struct { Certificate string `json:"certificate"` SerialNumber string `json:"serial_number"` ResponseFormat string `json:"response_format"` CertificateChain []string `json:"certificate_chain"` } // RevokeCertificateResponse represents response received after successfully revoke a certificate. type RevokeCertificateResponse struct { IssuerDN string `json:"issuer_dn"` SerialNumber string `json:"serial_number"` RevocationReason string `json:"revocation_reason"` RevocationDate time.Time `json:"revocation_date"` Message string `json:"message"` Revoked bool `json:"revoked"` } // CertificateRevocationStatusResponse represents response received upon checking the certificate revocation status. type CertificateRevocationStatusResponse struct { IssuerDN string `json:"issuer_dn"` SerialNumber string `json:"serial_number"` RevocationReason string `json:"revocation_reason"` RevocationDate time.Time `json:"revocation_date"` Message string `json:"message"` Revoked bool `json:"revoked"` } // SearchCertificateCriteria defines the criteria to search certificate data. type SearchCertificateCriteria struct { Property string `json:"property"` Value string `json:"value"` Operation string `json:"operation"` } // SearchCertificateRequest represents the data to send when searching for certificate data. type SearchCertificateRequest struct { MaxNumberOfResults int `json:"max_number_of_results"` Criteria []SearchCertificateCriteria `json:"criteria"` } // Certificate represents the certificate data. type Certificate struct { Certificate string `json:"certificate"` SerialNumber string `json:"serial_number"` ResponseFormat string `json:"response_format"` CertificateChain []string `json:"certificate_chain"` } // SearchCertificateResponse represents response received from searching certificate data. type SearchCertificateResponse struct { Certificates []Certificate `json:"certificates"` MoreResults bool `json:"more_results"` } // FinaliseCertificateEnrolmentRequest represents data to send when finalising certificate enrolment request based on request ID. type FinaliseCertificateEnrolmentRequest struct { ResponseFormat string `json:"response_format"` Password string `json:"password"` } // FinaliseCertificateEnrolmentResponse represents data returned after finalising the certificate enrolment based on request ID. type FinaliseCertificateEnrolmentResponse struct { Certificate string `json:"certificate"` SerialNumber string `json:"serial_number"` ResponseFormat string `json:"response_format"` CertificateChain []string `json:"certificate_chain"` } // PaginationRestResponseComponent represents paging data upon searching expiring certificates.. type PaginationRestResponseComponent struct { MoreResults bool `json:"more_results"` NextOffset uint `json:"next_offset"` NumberOfResults uint `json:"number_of_results"` } // CertificateRestResponse represents element that stores the list of certificates upon searching expiring certificates. type CertificateRestResponse struct { Certificates []Certificate `json:"certificates"` } // ExpireCertificateResponse represents data returned after successfully querying for expiring certificates. type ExpireCertificateResponse struct { Pagination PaginationRestResponseComponent `json:"pagination_rest_response_component"` Certificates CertificateRestResponse `json:"certificates_rest_response"` }
/* Every number of the form 2i (where i is a non-negative integer) has a single 1 in its binary representation. Given such a number, output the 1-based position of the 1. Examples: DECIMAL BINARY POSITION -------------------------- 1 0001 1 2 0010 2 4 0100 3 8 1000 4 N 0...1...0 ? */ package main import ( "math/bits" ) func main() { for i := uint(0); i < bits.UintSize; i++ { assert(one(1<<i) == int(i+1)) } } func assert(x bool) { if !x { panic("assertion failed") } } func one(x uint) int { return bits.TrailingZeros(x) + 1 }
package parser import ( "errors" "strings" ) type reader struct { position int readAheadPosition int readAheadCalled bool tokens []string parensCount int bracketsCount int bracesCount int } func newReader(tokens []string) *reader { reader := reader{tokens: tokens} return &reader } func (r *reader) next() (*string, error) { if !r.readAheadCalled { r.readAheadCalled = true if err := r.readAhead(); err != nil { return nil, err } } if r.position < len(r.tokens) { token := &(r.tokens[r.position]) r.position++ return token, nil } else { return nil, nil } } func (r *reader) readAhead() error { reachedEnd := func() bool { return r.readAheadPosition == len(r.tokens) } currentToken := func() string { return r.tokens[r.readAheadPosition] } unclosedString := func(token string) bool { return strings.HasPrefix(token, "\"") && (len(token) == 1 || !strings.HasSuffix(token, "\"")) } for !reachedEnd() { switch token := currentToken(); token { case "(": r.parensCount++ case ")": r.parensCount-- case "[": r.bracketsCount++ case "]": r.bracketsCount-- case "{": r.bracesCount++ case "}": r.bracesCount-- default: if unclosedString(token) { return errors.New("Error: unexpected EOF.") } } r.readAheadPosition++ } if r.parensCount < 0 { return errors.New("Error: unexpected ')'.") } else if r.bracketsCount < 0 { return errors.New("Error: unexpected ']'.") } else if r.bracesCount < 0 { return errors.New("Error: unexpected '}'.") } else if reachedEnd() && (r.parensCount > 0 || r.bracketsCount > 0 || r.bracesCount > 0) { return errors.New("Error: unexpected EOF.") } return nil }
package main import ( "bufio" "encoding/json" "fmt" "io" "log" "os" "os/exec" "syscall" "unicode" "github.com/vincent-petithory/structfield" ) // Header defines the struct of the header in the i3bar protocol. type Header struct { Version int `json:"version"` StopSignal int `json:"stop_signal,omitempty"` ContSignal int `json:"cont_signal,omitempty"` ClickEvents bool `json:"click_events,omitempty"` } var trueBoolTransformer = structfield.TransformerFunc(func(field string, value interface{}) (string, interface{}) { switch x := value.(type) { case bool: if !x { return field, false } default: panic("trueBoolTransformer: expected bool") } return "", nil }) // Block defines the struct of blocks in the i3bar protocol. type Block struct { FullText string `json:"full_text"` ShortText string `json:"short_text,omitempty"` Color string `json:"color,omitempty"` MinWidth int `json:"min_width,omitempty"` Align string `json:"align,omitempty"` Name string `json:"name,omitempty"` Instance string `json:"instance,omitempty"` Urgent bool `json:"urgent,omitempty"` Separator bool `json:"separator"` SeparatorBlockWidth int `json:"separator_block_width,omitempty"` Background string `json:"background,omitempty"` Border string `json:"border,omitempty"` Markup string `json:"markup,omitempty"` } func (b Block) MarshalJSON() ([]byte, error) { m := structfield.Transform(b, map[string]structfield.Transformer{ "separator": trueBoolTransformer, }) return json.Marshal(m) } func (b *Block) UnmarshalJSON(data []byte) error { type blockAlias Block ba := blockAlias{} if err := json.Unmarshal(data, &ba); err != nil { return err } *b = Block(ba) sep := struct { Value *bool `json:"separator"` }{} if err := json.Unmarshal(data, &sep); err != nil { return err } if sep.Value != nil { b.Separator = *sep.Value } else { // defaults to true b.Separator = true } return nil } // String implements Stringer interface. func (b Block) String() string { return b.FullText } // BlockAggregate relates a CmdIO to the Blocks it produced during one update. type BlockAggregate struct { CmdIO *CmdIO Blocks []*Block } // A CmdIO defines a cmd that will feed the i3bar. type CmdIO struct { // Cmd is the command being run Cmd *exec.Cmd // reader is the underlying stream where Cmd outputs data. reader io.ReadCloser // writer is the underlying stream where Cmd outputs data. writer io.WriteCloser } // NewCmdIO creates a new CmdIO from command c. // c must be properly quoted for a shell as it's passed to sh -c. func NewCmdIO(c string) (*CmdIO, error) { cmd := exec.Command(os.Getenv("SHELL"), "-c", c) reader, err := cmd.StdoutPipe() if err != nil { return nil, err } writer, err := cmd.StdinPipe() if err != nil { return nil, err } cmdio := CmdIO{ Cmd: cmd, reader: reader, writer: writer, } return &cmdio, nil } // Start runs the command of CmdIO and feeds the BlockAggregatesCh channel // with the Blocks it produces. func (c *CmdIO) Start(blockAggregatesCh chan<- *BlockAggregate) error { if err := c.Cmd.Start(); err != nil { return err } go func() { // We'll handle a few cases here. // If JSON is output from i3status, then we need // to ignore the i3bar header and opening [, // then ignore leading comma on each line. // If JSON is output from a script, it assumes the // author will not have the header and [, but maybe the comma r := bufio.NewReader(c.reader) // try Read a header first ruune, _, err := r.ReadRune() if err != nil { log.Println(err) return } if ruune == '{' { // Consume the header line if _, err := r.ReadString('\n'); err != nil { log.Println(err) return } // Consume the next line (opening bracket) if _, err := r.ReadString('\n'); err != nil { log.Println(err) return } } else { _ = r.UnreadRune() } dec := json.NewDecoder(r) for { var b []*Block // Ignore unwanted chars first IgnoreChars: for { ruune, _, err := r.ReadRune() if err != nil { log.Println(err) break IgnoreChars } switch { case unicode.IsSpace(ruune): // Loop again case ruune == ',': break IgnoreChars default: _ = r.UnreadRune() break IgnoreChars } } if err := dec.Decode(&b); err != nil { if err == io.EOF { log.Println("reached EOF") return } log.Printf("Invalid JSON input: all decoding methods failed (%v)\n", err) // consume all remaining data to prevent looping forever on a decoding err for r.Buffered() > 0 { _, err := r.ReadByte() if err != nil { log.Println(err) } } // send an error block b = []*Block{ { FullText: fmt.Sprintf("Error parsing input: %v", err), Color: "#FF0000", }, } } blockAggregatesCh <- &BlockAggregate{c, b} } }() return nil } // Close closes reader and writers of this CmdIO. func (c *CmdIO) Close() error { if err := c.Cmd.Process.Signal(syscall.SIGTERM); err != nil { log.Println(err) if err := c.Cmd.Process.Kill(); err != nil { return err } } if err := c.Cmd.Process.Release(); err != nil { return err } if err := c.reader.Close(); err != nil { return err } if err := c.writer.Close(); err != nil { return err } return nil } // BlockAggregator fans-in all Blocks produced by a list of CmdIO and sends it to the writer W. type BlockAggregator struct { // Blocks keeps track of which CmdIO produced which Block list. Blocks map[*CmdIO][]*Block // CmdIOs keeps an ordered list of the CmdIOs being aggregated. CmdIOs []*CmdIO // W is where multiplexed input blocks are written to. W io.Writer } // NewBlockAggregator returns a BlockAggregator which will write to w. func NewBlockAggregator(w io.Writer) *BlockAggregator { return &BlockAggregator{ Blocks: make(map[*CmdIO][]*Block), CmdIOs: make([]*CmdIO, 0), W: w, } } // Aggregate starts aggregating data coming from the BlockAggregates channel. func (ba *BlockAggregator) Aggregate(blockAggregates <-chan *BlockAggregate) { jw := json.NewEncoder(ba.W) for blockAggregate := range blockAggregates { ba.Blocks[blockAggregate.CmdIO] = blockAggregate.Blocks var blocksUpdate []*Block for _, cmdio := range ba.CmdIOs { blocksUpdate = append(blocksUpdate, ba.Blocks[cmdio]...) } if blocksUpdate == nil { blocksUpdate = []*Block{} } if err := jw.Encode(blocksUpdate); err != nil { log.Println(err) } if _, err := ba.W.Write([]byte(",")); err != nil { log.Println(err) } } } // ForwardClickEvents relays click events emitted on ceCh to interested parties. // An interested party is a cmdio whose func (ba *BlockAggregator) ForwardClickEvents(ceCh <-chan ClickEvent) { FWCE: for ce := range ceCh { for _, cmdio := range ba.CmdIOs { blocks, ok := ba.Blocks[cmdio] if !ok { continue } for _, block := range blocks { if block.Name == ce.Name && block.Instance == ce.Instance { if err := json.NewEncoder(cmdio.writer).Encode(ce); err != nil { log.Println(err) } log.Printf("Sending click event %+v to %s\n", ce, cmdio.Cmd.Args) // One of the blocks of this cmdio matched. // We don't want more since a name/instance is supposed to be unique. continue FWCE } } } log.Printf("No block source found for click event %+v\n", ce) } }
package client import ( "gopkg.in/resty.v0" "github.com/slawek87/GOstorageClient/conf" "errors" "io" "bytes" "mime/multipart" "os" "strings" ) type GOrequest struct{} // method returns resty instance with already set BasicAuth token. func (goRequest *GOrequest) resty() *resty.Request { request := resty.R() request.SetBasicAuth(conf.Settings.GetSettings("USERNAME"), conf.Settings.GetSettings("PASSWORD")) return request } // method handle response. If status code is equal or grater then 300 returns error msg. func (GOrequest *GOrequest) handleResponse(data map[string]string, response *resty.Response) (map[string]string, error) { if response.StatusCode() >= 300 { return data, errors.New(response.Status()) } return data, nil } // method deletes file in storage. It must be Post method because endpoints in REST don't support Delete request with params. func (goRequest *GOrequest) Delete(url string, filename string) (map[string]string, error) { return goRequest.Post(url, map[string]string{"FileName": filename}) } func (goRequest *GOrequest) Post(url string, formData map[string]string) (map[string]string, error) { var data map[string]string url = goRequest.GetURL(url) response, _ := goRequest.resty(). SetFormData(formData). SetResult(&data). Post(url) return goRequest.handleResponse(data, response) } // method upload new file to storage. func (goRequest *GOrequest) UploadFile(url string, file *os.File) (map[string]string, error) { var data map[string]string var body bytes.Buffer url = goRequest.GetURL(url) writeBody := multipart.NewWriter(&body) filename := file.Name() strings.Contains(filename, "/") { tmp := strings.Split(filename, "/") filename = tmp[len(tmp)-1] } formFile, _ := writeBody.CreateFormFile("upload", filename) io.Copy(formFile, file) writeBody.Close() response, _ := goRequest.resty(). SetHeader("Content-Type", writeBody.FormDataContentType()). SetBody(&body). SetContentLength(true). SetResult(&data). Post(url) return goRequest.handleResponse(data, response) } // method returns correct url to storage service. func (goRequest *GOrequest) GetURL(url string) string { return conf.Settings.GetSettings("PROTOCOL") + "://" + conf.Settings.GetSettings("HOST") + ":" + conf.Settings.GetSettings("PORT") + url }
package conf import ( "log" "strings" "github.com/Maxgis/ToyBrick/util" "github.com/go-ini/ini" ) type Config struct { Port int IsOpenReferrer bool ReferrerWhiteList []string IsOpenDomainWhitelist bool DomainWhitelist []string IsOpenAdmin bool AdminPort int } var ( cfg *ini.File Globals = &Config{} ) func init() { file := util.GetCurrentDirectory() + "/conf/conf.ini" var err error cfg, err = ini.LooseLoad("filename", file) if err != nil { log.Fatal(err) } Globals.Port = GetPort() Globals.IsOpenReferrer = IsOpenReferrer() Globals.ReferrerWhiteList = GetReferrerWhiteList() Globals.DomainWhitelist = GetOpenDomainWhitelist() Globals.IsOpenDomainWhitelist = IsOpenDomainWhitelist() Globals.AdminPort = GetAdminPort() Globals.IsOpenAdmin = IsOpenAdmin() } func GetPort() int { portKey, err := cfg.Section("basic").GetKey("port") if err != nil { log.Fatal(err) } port, err2 := portKey.Int() if err2 != nil { log.Fatal(err2) } return port } func GetAdminPort() int { portKey, err := cfg.Section("admin").GetKey("port") if err != nil { return 0 } port, err2 := portKey.Int() if err2 != nil { return 0 } return port } func IsOpenAdmin() bool { isOpenKey, err := cfg.Section("admin").GetKey("open") if err != nil { return false } isOpen, perr := isOpenKey.Bool() if perr != nil { return false } return isOpen } func IsOpenReferrer() bool { isOpenKey, err := cfg.Section("security").GetKey("openReferrer") if err != nil { return false } isOpen, perr := isOpenKey.Bool() if perr != nil { return false } return isOpen } func GetReferrerWhiteList() []string { referrerWhiteList, err := cfg.Section("security").GetKey("referrerWhiteList") if err != nil { return []string{} } return strings.Split(referrerWhiteList.String(), ",") } func IsOpenDomainWhitelist() bool { isOpenKey, err := cfg.Section("security").GetKey("openDomain") if err != nil { return false } isOpen, perr := isOpenKey.Bool() if perr != nil { return false } return isOpen } func GetOpenDomainWhitelist() []string { domainWhiteList, err := cfg.Section("security").GetKey("domainWhiteList") if err != nil { return []string{} } return strings.Split(domainWhiteList.String(), ",") }
package mt import ( "bytes" "encoding/json" "errors" "fmt" "strconv" ) func (tc ToolCaps) String() string { b, err := tc.MarshalJSON() if err != nil { panic(err) } return string(b) } func (tc ToolCaps) MarshalJSON() ([]byte, error) { if !tc.NonNil { return []byte("null"), nil } var dgs bytes.Buffer dgs.WriteByte('{') e := json.NewEncoder(&dgs) for i, dg := range tc.DmgGroups { e.Encode(dg.Name) dgs.WriteByte(':') e.Encode(dg.Rating) if i < len(tc.DmgGroups)-1 { dgs.WriteByte(',') } } dgs.WriteByte('}') var gcs bytes.Buffer gcs.WriteByte('{') e = json.NewEncoder(&gcs) for i, gc := range tc.GroupCaps { var maxRating int16 for _, t := range gc.Times { if t.Rating >= maxRating { maxRating = t.Rating + 1 } } times := make([]interface{}, maxRating) for _, t := range gc.Times { times[t.Rating] = fmtFloat(t.Time) } e.Encode(gc.Name) gcs.WriteByte(':') e.Encode(map[string]interface{}{ "uses": gc.Uses, "maxlevel": gc.MaxLvl, "times": times, }) if i < len(tc.GroupCaps)-1 { gcs.WriteByte(',') } } gcs.WriteByte('}') return json.Marshal(map[string]interface{}{ "damage_groups": json.RawMessage(dgs.Bytes()), "full_punch_interval": fmtFloat(tc.AttackCooldown), "groupcaps": json.RawMessage(gcs.Bytes()), "max_drop_level": tc.MaxDropLvl, "punch_attack_uses": tc.PunchUses, }) } func (tc *ToolCaps) UnmarshalJSON(data []byte) error { d := json.NewDecoder(bytes.NewReader(data)) t, err := d.Token() if err != nil { return err } if t == nil { *tc = ToolCaps{} return nil } if d, ok := t.(json.Delim); !ok || d != '{' { return errors.New("not an object") } for d.More() { t, err := d.Token() if err != nil { return err } key := t.(string) err = nil switch key { case "full_punch_interval": err = d.Decode(&tc.AttackCooldown) case "max_drop_level": err = d.Decode(&tc.MaxDropLvl) case "groupcaps": tc.GroupCaps = nil t, err := d.Token() if err != nil { return fmt.Errorf("groupcaps: %w", err) } if d, ok := t.(json.Delim); !ok || d != '{' { return errors.New("groupcaps: not an object") } for d.More() { var gc ToolGroupCap t, err := d.Token() if err != nil { return fmt.Errorf("groupcaps: %w", err) } gc.Name = t.(string) t, err = d.Token() if err != nil { return fmt.Errorf("groupcaps: %w", err) } if d, ok := t.(json.Delim); !ok || d != '{' { return errors.New("groupcaps: not an object") } for d.More() { t, err := d.Token() if err != nil { return fmt.Errorf("groupcaps: %w", err) } key := t.(string) err = nil switch key { case "uses": err = d.Decode(&gc.Uses) case "maxlevel": err = d.Decode(&gc.MaxLvl) case "times": gc.Times = nil t, err := d.Token() if err != nil { return fmt.Errorf("groupcaps: times: %w", err) } if d, ok := t.(json.Delim); !ok || d != '[' { return errors.New("groupcaps: times: not an array") } for i := int16(0); d.More(); i++ { t, err := d.Token() if err != nil { return fmt.Errorf("groupcaps: times: %w", err) } switch t := t.(type) { case nil: case float64: gc.Times = append(gc.Times, DigTime{i, float32(t)}) default: return errors.New("groupcaps: times: not null or a number") } } _, err = d.Token() } if err != nil { return fmt.Errorf("groupcaps: %s: %w", key, err) } } if _, err := d.Token(); err != nil { return err } tc.GroupCaps = append(tc.GroupCaps, gc) } _, err = d.Token() case "damage_groups": tc.DmgGroups = nil t, err := d.Token() if err != nil { return fmt.Errorf("damage_groups: %w", err) } if d, ok := t.(json.Delim); !ok || d != '{' { return errors.New("damage_groups: not an object") } for d.More() { var g Group t, err := d.Token() if err != nil { return err } g.Name = t.(string) if err := d.Decode(&g.Rating); err != nil { return fmt.Errorf("damage_groups: %w", err) } tc.DmgGroups = append(tc.DmgGroups, g) } _, err = d.Token() case "punch_attack_uses": err = d.Decode(&tc.PunchUses) } if err != nil { return fmt.Errorf("%s: %w", key, err) } } if _, err := d.Token(); err != nil { return err } tc.NonNil = true return nil } func fmtFloat(f float32) json.Number { buf := make([]byte, 0, 24) buf = strconv.AppendFloat(buf, float64(f), 'g', 17, 32) if !bytes.ContainsRune(buf, '.') { buf = append(buf, '.', '0') } return json.Number(buf) }
package main import "math" //dp from bottom to top func minimumTotal(triangle [][]int) int { for i := len(triangle)-2;i>=0;i--{ for j :=0;j< len(triangle[i]);j++{ triangle[i][j] += int(math.Min(float64(triangle[i+1][j]),float64(triangle[i+1][j+1]))) } } return triangle[0][0] }
package middlewares import "github.com/gin-gonic/gin" func BasicAuth() gin.HandlerFunc { return gin.BasicAuth(gin.Accounts{ "fabio": "torino", }) }
package creds import ( "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sts" ) type AwsCredentialGetter interface { GetCreds() (credentials.Value, error) } type StsCredentialGetterConfig struct { Region string Arn string Session string } type StsCredentialGetter struct { Credentials *sts.Credentials Config *StsCredentialGetterConfig session *session.Session } func NewStsCredentialGetter(config *StsCredentialGetterConfig) (*StsCredentialGetter, error) { c := &StsCredentialGetter{Config: config} c.session = session.New(&aws.Config{Region: aws.String(c.Config.Region)}) return c, c.updateStsCredentials() } func (c *StsCredentialGetter) updateStsCredentials() error { svc := sts.New(c.session) params := &sts.AssumeRoleInput{ RoleArn: aws.String(c.Config.Arn), RoleSessionName: aws.String(c.Config.Session), DurationSeconds: aws.Int64(3600), } resp, err := svc.AssumeRole(params) if err != nil { return err } c.Credentials = resp.Credentials return nil } func (c *StsCredentialGetter) GetCreds() (credentials.Value, error) { if time.Now().Unix()-c.Credentials.Expiration.Unix() > 0 { c.updateStsCredentials() } ak := *c.Credentials.AccessKeyId sak := *c.Credentials.SecretAccessKey st := *c.Credentials.SessionToken return credentials.Value{ AccessKeyID: ak, SecretAccessKey: sak, SessionToken: st, }, nil } type ChainCredentialGetter struct { Credentials *credentials.Credentials } func NewChainCredentialGetter() (*ChainCredentialGetter, error) { creds := credentials.NewChainCredentials( []credentials.Provider{ &credentials.EnvProvider{}, &credentials.SharedCredentialsProvider{}, &ec2rolecreds.EC2RoleProvider{}, }) c := &ChainCredentialGetter{Credentials: creds} return c, nil } func (c ChainCredentialGetter) GetCreds() (credentials.Value, error) { return c.Credentials.Get() }
package parser import ( "testing" "github.com/stretchr/testify/assert" ) func TestAddDefaultClientCertificateRule(t *testing.T) { var p Policy p.AddDefaultClientCertificateRule() assert.Equal(t, Policy{ Rules: []Rule{{ Action: ActionDeny, Or: []Criterion{ {Name: "invalid_client_certificate"}, }, }}, }, p) }
package task import ( "fmt" "sync/atomic" "time" ) // ID is a unique Task identifier type ID uint64 // State represents current state of the Task type State int // FailedBehavior defines behavior in case that Task execution fails type FailedBehavior int // Task state const ( TaskStateNew State = iota TaskStateRunning TaskStateDone TaskStateFailed ) // What to do if task fails const ( TaskFailedContinue FailedBehavior = iota TaskFailedRepeat TaskFailedAbort ) // Task is interface that tasks must implement to be supported by task/Runner type Task interface { GetID() ID GetDescription() string Run(c chan<- Result) GetStartTime() time.Time GetEndTime() time.Time GetState() State SetState(State) GetFailedBehavior() FailedBehavior } // Result represents result that Tasks return to the Runner type Result struct { ID ID Err error Value interface{} } // DefaultTask is simple implementation of Task interface type DefaultTask struct { id ID description string state State failedBehavior FailedBehavior runFunc func(...interface{}) (interface{}, error) runArgs []interface{} startTime time.Time endTime time.Time } // GetID returns Task ID func (dt *DefaultTask) GetID() ID { return dt.id } // GetDescription return text description of the Task func (dt *DefaultTask) GetDescription() string { return dt.description } // GetState returns Task state func (dt *DefaultTask) GetState() State { return dt.state } // SetState sets Task state func (dt *DefaultTask) SetState(state State) { dt.state = state } // GetStartTime returns time when task execution started func (dt *DefaultTask) GetStartTime() time.Time { return dt.startTime } // GetEndTime returns time when task execution ended func (dt *DefaultTask) GetEndTime() time.Time { return dt.endTime } // GetFailedBehavior returns behavior for failed tasks func (dt *DefaultTask) GetFailedBehavior() FailedBehavior { return dt.failedBehavior } // Run executes the Task and returns result on resultChan func (dt *DefaultTask) Run(resultChan chan<- Result) { var result interface{} var err error dt.startTime = time.Now() // Need to handle possible panic in dt.runFunc in a safe way defer func() { if r := recover(); r != nil { err = fmt.Errorf("Panic in %v: %v", dt, r) } dt.endTime = time.Now() resultChan <- Result{ID: dt.id, Err: err, Value: result} }() result, err = dt.runFunc(dt.runArgs...) } func (dt *DefaultTask) String() string { return fmt.Sprintf("Task (id: %v, state: %v, %v)", dt.id, dt.state, dt.description) } // DefaultTaskFactory is simple factory for creating instances of DefaultTask type DefaultTaskFactory struct { nextID ID } // NewTask creates a new DefaultTask instance func (tf *DefaultTaskFactory) NewTask(f func(...interface{}) (interface{}, error), description string, behavior FailedBehavior, arg ...interface{}) Task { return &DefaultTask{ id: ID(atomic.AddUint64((*uint64)(&tf.nextID), 1)), description: description, state: TaskStateNew, failedBehavior: behavior, runFunc: f, runArgs: append([]interface{}{}, arg...), } }
package article import ( "github.com/hardstylez72/bblog/internal/storage/article" ) func NewGetArticlesByPeriodResponse(in []article.Article) []Article { out := make([]Article, 0, len(in)) for _, i := range in { el := Article{ Id: i.Id, Preface: i.Preface, Title: i.Title, UserId: i.UserId, CreatedAt: i.CreatedAt, UpdatedAt: nil, DeletedAt: nil, } out = append(out, el) } return out }
package main import "fmt" import "strings" func main() { str := " aaa \n\t" fmt.Println(strings.TrimSpace(str)) }
// Copyright (C) 2019 rameshvk. All rights reserved. // Use of this source code is governed by a MIT-style license // that can be found in the LICENSE file. package match_test import ( "go/parser" "go/token" "path" "runtime" "testing" "github.com/tvastar/gogo/pkg/match" ) func TestMatcherOnItself(t *testing.T) { _, self, _, _ := runtime.Caller(0) matchx := path.Join(path.Dir(self), "match.go") f1, err1 := parser.ParseFile(token.NewFileSet(), matchx, nil, 0) if err1 != nil { t.Fatal("Could not parse match.go", err1) } f2, err2 := parser.ParseFile(token.NewFileSet(), matchx, nil, 0) if err2 != nil { t.Fatal("Could not parse match.go", err2) } if !match.Match(f1, f2) { t.Error("Match did not match itself!") } }
package hash import ( "github.com/plandem/xlsx/internal/ml" "strings" ) //StringItem return string with values of ml.StringItem func StringItem(si *ml.StringItem) Key { if si == nil { si = &ml.StringItem{} } result := []string{ string(si.Text), string(Reserved(si.PhoneticPr)), } if si.RPh != nil { for _, r := range *si.RPh { result = append(result, string(Reserved(r))) } } if si.RichText != nil { for _, part := range *si.RichText { result = append(result, string(part.Text)) if part.Font != nil { font := ml.Font(*part.Font) result = append(result, string(Font(&font))) } } } return Key(strings.Join(result, ":")) }
package obs import ( "errors" "strings" "time" ) // MonitorConfig stores the configuration for the monitor. type MonitorConfig struct { Enabled bool `json:"enabled" yaml:"enabled"` PrometheusEndpoint string `json:"prometheus-endpoint" yaml:"prometheus-endpoint"` ProcessReportInterval time.Duration `json:"process-report-interval" yaml:"process-report-interval"` } // SetDefault sets sane default for monitor's config. func (c *MonitorConfig) SetDefault() { c.Enabled = false c.PrometheusEndpoint = "/metrics" c.ProcessReportInterval = 20 * time.Second } // Validate makes sure config has valid values. func (c *MonitorConfig) Validate() error { if !c.Enabled { return nil } if c.PrometheusEndpoint == "" { return errors.New("prometheus endpoint should not be empty") } if !strings.HasPrefix(c.PrometheusEndpoint, "/") { return errors.New("prometheus endpoint should start with /") } if c.ProcessReportInterval < time.Second { return errors.New("process report interval should be higher than a second") } return nil }
package handlers type InvalidArgument struct { Message string } func (e InvalidArgument) Error() string { return e.Message } type RequiredValueError struct { Message string } func (e RequiredValueError) Error() string { return e.Message } type UnexpectedError struct { Message string error } type UnauthorizedError struct { Message string } func (e UnauthorizedError) Error() string { return e.Message }
package demo10_UDP通信 import ( "sync" "time" ) var wg sync.WaitGroup func UDPConn() { wg.Add(2) go udpServer() time.Sleep(time.Second * 3) go udpClient() wg.Wait() }
package main import ( "encoding/csv" "fmt" "github.com/ziutek/mymysql/mysql" "log" "net" "os" "strconv" "strings" "time" ) type mockConnection struct { } type mockResult struct { reader *csv.Reader isSolvesTable bool limit int counter int } func (self *mockConnection) Start(sql string, params ...interface{}) (mysql.Result, error) { isSolvesTable := false filename := "mock_data/puzzles_data.csv" sql = fmt.Sprintf(sql, params...) sql = strings.ToLower(sql) if strings.Contains(sql, config.SolvesTable) { isSolvesTable = true filename = "mock_data/solves_data.csv" } limit := 0 if strings.Contains(sql, " limit ") { //Process limit parts := strings.Split(sql, " limit ") if len(parts) == 2 { //Only continue processing if we know what's going on. limit, _ = strconv.Atoi(parts[1]) } } file, err := os.Open(filename) if err != nil { log.Fatal("Couldn't open the file of mock data: ", filename) os.Exit(1) } //We'd normally call defer file.Close() here, but we can't because we still have to vend the rows. return &mockResult{csv.NewReader(file), isSolvesTable, limit, 0}, nil } func (self *mockConnection) Prepare(sql string) (mysql.Stmt, error) { log.Println("Called a method that is not implemented in the mock database object.") return nil, nil } func (self *mockConnection) Ping() error { log.Println("Called a method that is not implemented in the mock database object.") return nil } func (self *mockConnection) ThreadId() uint32 { log.Println("Called a method that is not implemented in the mock database object.") return 0 } func (self *mockConnection) Escape(txt string) string { log.Println("Called a method that is not implemented in the mock database object.") return "" } func (self *mockConnection) Query(sql string, params ...interface{}) ([]mysql.Row, mysql.Result, error) { log.Println("Called a method that is not implemented in the mock database object.") return nil, nil, nil } func (self *mockConnection) QueryFirst(sql string, params ...interface{}) (mysql.Row, mysql.Result, error) { log.Println("Called a method that is not implemented in the mock database object.") return nil, nil, nil } func (self *mockConnection) QueryLast(sql string, params ...interface{}) (mysql.Row, mysql.Result, error) { log.Println("Called a method that is not implemented in the mock database object.") return nil, nil, nil } func (self *mockConnection) Clone() mysql.Conn { log.Println("Called a method that is not implemented in the mock database object.") return nil } func (self *mockConnection) SetTimeout(time.Duration) { log.Println("Called a method that is not implemented in the mock database object.") } func (self *mockConnection) Connect() error { //Just pretend everything worked correctly. return nil } func (self *mockConnection) NetConn() net.Conn { log.Println("Called a method that is not implemented in the mock database object.") return nil } func (self *mockConnection) SetDialer(mysql.Dialer) { log.Println("Called a method that is not implemented in the mock database object.") return } func (self *mockConnection) Close() error { log.Println("Called a method that is not implemented in the mock database object.") return nil } func (self *mockConnection) IsConnected() bool { log.Println("Called a method that is not implemented in the mock database object.") return false } func (self *mockConnection) Reconnect() error { log.Println("Called a method that is not implemented in the mock database object.") return nil } func (self *mockConnection) Use(dbname string) error { log.Println("Called a method that is not implemented in the mock database object.") return nil } func (self *mockConnection) Register(sql string) { log.Println("Called a method that is not implemented in the mock database object.") } func (self *mockConnection) SetMaxPktSize(new_size int) int { log.Println("Called a method that is not implemented in the mock database object.") return 0 } func (self *mockConnection) NarrowTypeSet(narrow bool) { log.Println("Called a method that is not implemented in the mock database object.") } func (self *mockConnection) FullFieldInfo(full bool) { log.Println("Called a method that is not implemented in the mock database object.") } func (self *mockConnection) Begin() (mysql.Transaction, error) { log.Println("Called a method that is not implemented in the mock database object.") return nil, nil } //Begin mockResult methods func (self *mockResult) StatusOnly() bool { log.Println("Called a method that is not implemented in the mock database object.") return false } func (self *mockResult) ScanRow(mysql.Row) error { log.Println("Called a method that is not implemented in the mock database object.") return nil } func (self *mockResult) GetRow() (mysql.Row, error) { if self.limit != 0 && self.counter >= self.limit { //We reached our limit! return nil, nil } data, _ := self.reader.Read() self.counter++ if data == nil { return nil, nil } if self.isSolvesTable { if len(data) != 4 { log.Fatal("The data in the mock solves table should have four items but at least one row doesn't") os.Exit(1) } id, _ := strconv.Atoi(data[1]) solveTime, _ := strconv.Atoi(data[2]) penaltyTime, _ := strconv.Atoi(data[3]) return mysql.Row{data[0], int64(id), int64(solveTime), int64(penaltyTime)}, nil } else { if len(data) != 4 { log.Fatal("The data in the mock puzzles table should have four items but at least one row doesn't.") os.Exit(1) } id, _ := strconv.Atoi(data[0]) difficulty, _ := strconv.Atoi(data[1]) return mysql.Row{int64(id), int64(difficulty), data[2], data[3]}, nil } } func (self *mockResult) MoreResults() bool { log.Println("Called a method that is not implemented in the mock database object.") return false } func (self *mockResult) NextResult() (mysql.Result, error) { log.Println("Called a method that is not implemented in the mock database object.") return nil, nil } func (self *mockResult) Fields() []*mysql.Field { log.Println("Called a method that is not implemented in the mock database object.") return nil } func (self *mockResult) Map(string) int { log.Println("Called a method that is not implemented in the mock database object.") return 0 } func (self *mockResult) Message() string { log.Println("Called a method that is not implemented in the mock database object.") return "" } func (self *mockResult) AffectedRows() uint64 { log.Println("Called a method that is not implemented in the mock database object.") return 0 } func (self *mockResult) InsertId() uint64 { log.Println("Called a method that is not implemented in the mock database object.") return 0 } func (self *mockResult) WarnCount() int { log.Println("Called a method that is not implemented in the mock database object.") return 0 } func (self *mockResult) MakeRow() mysql.Row { log.Println("Called a method that is not implemented in the mock database object.") return nil } func (self *mockResult) GetRows() ([]mysql.Row, error) { log.Println("Called a method that is not implemented in the mock database object.") return nil, nil } func (self *mockResult) End() error { log.Println("Called a method that is not implemented in the mock database object.") return nil } func (self *mockResult) GetFirstRow() (mysql.Row, error) { log.Println("Called a method that is not implemented in the mock database object.") return nil, nil } func (self *mockResult) GetLastRow() (mysql.Row, error) { log.Println("Called a method that is not implemented in the mock database object.") return nil, nil }
// +build windows package redux import ( "errors" "os" ) func statUidGid(finfo os.FileInfo) (uint32, uint32, error) { return 0, 0, errors.New("finfo.Sys() is unsupported") }
package c22_crack_mt19937_seed import ( "math/rand" "time" "github.com/vodafon/cryptopals/set3/c21_mt19937" ) func Number(seed uint32) uint32 { mt := c21_mt19937.NewMT19937(seed) waitRandom() return mt.ExtractNumber() } func Exploit(num uint32) uint32 { seed := uint32(time.Now().Unix()) for seed >= 0 { if c21_mt19937.NewMT19937(seed).ExtractNumber() == num { return seed } seed -= 1 } return seed } func waitRandom() { t := rand.Intn(5) + 1 time.Sleep(time.Duration(t) * time.Second) }
package atlas import "testing" var ( file_25x100 = &File{FileName: "25x100", Width: 25, Height: 100} file_50x50 = &File{FileName: "50x50", Width: 50, Height: 50} file_50x300 = &File{FileName: "50x300", Width: 50, Height: 300} file_100x100 = &File{FileName: "100x100", Width: 100, Height: 100} file_200x200 = &File{FileName: "200x200", Width: 200, Height: 200} file_500x50 = &File{FileName: "500x50", Width: 500, Height: 50} ) var files = []*File{ file_25x100, file_50x50, file_50x300, file_100x100, file_200x200, file_500x50, } func TestSortWidth(t *testing.T) { run(t, SortWidth, []*File{ file_500x50, file_200x200, file_100x100, file_50x300, file_50x50, file_25x100, }) } func TestSortHeight(t *testing.T) { run(t, SortHeight, []*File{ file_50x300, file_200x200, file_100x100, file_25x100, file_500x50, file_50x50, }) } func TestSortAreaWidth(t *testing.T) { run(t, SortAreaWidth, []*File{ file_200x200, // 40,000 file_500x50, // 25,000 file_50x300, // 15,000 file_100x100, // 10,000 file_50x50, // 2,500 file_25x100, // 2,500 }) } func TestSortAreaHeight(t *testing.T) { run(t, SortAreaHeight, []*File{ file_200x200, // 40,000 file_500x50, // 25,000 file_50x300, // 15,000 file_100x100, // 10,000 file_25x100, // 2,500 file_50x50, // 2,500 }) } func TestSortMaxSide(t *testing.T) { run(t, SortMaxSide, []*File{ file_500x50, file_50x300, file_200x200, file_100x100, file_25x100, file_50x50, }) } func run(t *testing.T, sorter Sorter, expect []*File) { res := sorter(files) for i, file := range expect { if res[i] != file { t.Errorf("File not sorted correctly: want %s, got %s", file.FileName, res[i].FileName) } } }
package sandbox // @class Cube // This is Cube, it operates on int32 and can compute areas type Cube struct { // Internal width value width int32 // Internal height value height int32 // Internal depth value depth int32 } // Constructor which creates a cube by taking three values in // @param width The width value // @param height The height value // @param depth The depth value func NewCube(width int32, height int32, depth int32) *Cube { return &Cube{ width: width, height: height, depth: depth, } } // Width returns the width value func (cb *Cube) Width() int32 { return cb.width } // Height returns the height value func (cb *Cube) Height() int32 { return cb.height } // Depth returns the height value func (cb *Cube) Depth() int32 { return cb.depth } // Area calculates and returns the area (width x height) func (cb *Cube) Area() int64 { return int64(cb.width) * int64(cb.height) * int64(cb.depth) }
package spec import ( "os" "testing" "github.com/kaitai-io/kaitai_struct_go_runtime/kaitai" "github.com/stretchr/testify/assert" . "test_formats" ) func TestProcessRotate(t *testing.T) { f, err := os.Open("../../src/process_rotate.bin") if err != nil { t.Fatal(err) } s := kaitai.NewStream(f) var r ProcessRotate err = r.Read(s, &r, &r) if err != nil { t.Fatal(err) } assert.EqualValues(t, "Hello", r.Buf1) assert.EqualValues(t, "World", r.Buf2) assert.EqualValues(t, "There", r.Buf3) }
package logging import ( "adminbot/framework" "adminbot/config" "github.com/bwmarrin/discordgo" "fmt" "encoding/json" "io/ioutil" "time" "sync" ) var Mu sync.Mutex var Log map[string]int64 func StartLogging(ticker *time.Ticker){ for { select { case <- ticker.C: Logging() } } } func InitLogging(session *discordgo.Session){ Mu.Lock() defer Mu.Unlock() _, err := ioutil.ReadFile("logdata.json") if err != nil{ guildMembers, err := session.GuildMembers(config.Discord.GuildID, "", 1000) if err != nil { fmt.Println("The bot needs the Server Members Intent authorization") } Log = make(map[string]int64) for _, member := range guildMembers{ Log[member.User.ID] = 0 } initdata, _ := json.Marshal(Log) err = ioutil.WriteFile("logdata.json", initdata, 0644) if err != nil{ fmt.Println("[!] error Logging : cannot create logdata.json file") return } return }else{ Log = make(map[string]int64) } } func Logging(){ // We update the logdata file with the data from the Log variable, then we clear this variable Mu.Lock() defer Mu.Unlock() fileData := make(map[string]int64) byteValue, err := ioutil.ReadFile("logdata.json") if err != nil{ fmt.Println("[!] error Logging : cannot read logdata.json file") return } json.Unmarshal(byteValue, &fileData) newdata, _ := json.Marshal( framework.MergeMap(fileData, Log) ) err = ioutil.WriteFile("logdata.json", newdata, 0644) if err != nil{ fmt.Println("[!] error Logging : cannot write to logdata.json file") return } Log = make(map[string]int64) }
package main import ( "flag" "github.com/teploff/otus/hw_6/carbon" "log" ) var ( srsFilePath = flag.String("src", "full/source/file/path", "full path to src file") destFilePath = flag.String("dest", "full/dest/file/path", "full path to dest file") offset = flag.Int64("offset", 0, "offset count bytes from source file") limit = flag.Int64("limit", 0, "count of bytes which should copied from source file") ) func main() { flag.Parse() c, err := carbon.NewCarbon(*srsFilePath, *destFilePath, *offset, *limit) if err != nil { log.Fatalln(err) } if err = c.Copy(); err != nil { log.Fatalln(err) } }
package publisher import ( "context" "fmt" "time" "github.com/Shopify/sarama" "github.com/golangid/candi/candihelper" "github.com/golangid/candi/candishared" "github.com/golangid/candi/logger" "github.com/golangid/candi/tracer" ) // KafkaPublisher kafka type KafkaPublisher struct { producer sarama.SyncProducer } // NewKafkaPublisher constructor func NewKafkaPublisher(client sarama.Client) *KafkaPublisher { producer, err := sarama.NewSyncProducerFromClient(client) if err != nil { logger.LogYellow(fmt.Sprintf("(Kafka publisher: warning, %v. Should be panicked when using kafka publisher.) ", err)) return nil } return &KafkaPublisher{ producer: producer, } } // PublishMessage method func (p *KafkaPublisher) PublishMessage(ctx context.Context, args *candishared.PublisherArgument) (err error) { trace := tracer.StartTrace(ctx, "kafka:publish_message") defer func() { if r := recover(); r != nil { err = fmt.Errorf("%v", r) } trace.SetError(err) trace.Finish() }() payload := candihelper.ToBytes(args.Data) trace.SetTag("topic", args.Topic) trace.SetTag("key", args.Key) trace.Log("message", payload) msg := &sarama.ProducerMessage{ Topic: args.Topic, Key: sarama.ByteEncoder([]byte(args.Key)), Value: sarama.ByteEncoder(payload), Timestamp: time.Now(), } _, _, err = p.producer.SendMessage(msg) return }
package cli import _ "github.com/joho/godotenv/autoload" import ( "github.com/urfave/cli" ) type CLIApp = cli.App func CreateCLI( config *Config, ) *CLIApp { App := cli.NewApp() App.Name = config.Name() App.Usage = config.Description() App.HelpName = config.HelpPrefix() return App } func ProvideCLI(config *Config) *CLIApp { return CreateCLI(config) }
package camt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document04100103 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:camt.041.001.03 Document"` Message *FundConfirmedCashForecastReportV03 `xml:"FndConfdCshFcstRptV03"` } func (d *Document04100103) AddMessage() *FundConfirmedCashForecastReportV03 { d.Message = new(FundConfirmedCashForecastReportV03) return d.Message } // Scope // A report provider, such as a transfer agent, sends the FundConfirmedCashForecastReport message to the report user, such as an investment manager, to report the confirmed cash incomings and outgoings of one or more investment funds on one or more trade dates. // The cash movements may result from, for example, redemption, subscription, switch transactions or reinvestment of dividends. // Usage // The FundConfirmedCashForecastReport is used to report definitive cash movements, that is it is sent after the cut-off time and/or the price valuation of the fund. // This message contains incoming and outgoing cash flows that are confirmed, i.e., the price has been applied. If the price is not yet definitive, then the FundEstimatedCashForecastReport message must be used. // This message allows the report provider to report cash movements in or out of a fund, but does not allow the Sender to categorise these movements, for example by country, or to give details of the underlying orders, commission or charges. // If the report provider wishes to give detailed information related to cash movements, then the FundDetailedConfirmedCashForecastReport message must be used. type FundConfirmedCashForecastReportV03 struct { // Identifies the message. MessageIdentification *iso20022.MessageIdentification1 `xml:"MsgId"` // Collective reference identifying a set of messages. PoolReference *iso20022.AdditionalReference3 `xml:"PoolRef,omitempty"` // Reference to a linked message that was previously sent. PreviousReference []*iso20022.AdditionalReference3 `xml:"PrvsRef,omitempty"` // Reference to a linked message that was previously received. RelatedReference []*iso20022.AdditionalReference3 `xml:"RltdRef,omitempty"` // Pagination of the message. MessagePagination *iso20022.Pagination `xml:"MsgPgntn"` // Information related to the cash-in and cash-out flows for a specific trade date as a result of investment fund transactions, for example, subscriptions, redemptions or switches to/from a specified investment fund. FundCashForecastDetails []*iso20022.FundCashForecast3 `xml:"FndCshFcstDtls"` // Estimated net cash as a result of the cash-in and cash-out flows. ConsolidatedNetCashForecast *iso20022.NetCashForecast3 `xml:"CnsltdNetCshFcst,omitempty"` // Additional information that cannot be captured in the structured elements and/or any other specific block. Extension []*iso20022.Extension1 `xml:"Xtnsn,omitempty"` } func (f *FundConfirmedCashForecastReportV03) AddMessageIdentification() *iso20022.MessageIdentification1 { f.MessageIdentification = new(iso20022.MessageIdentification1) return f.MessageIdentification } func (f *FundConfirmedCashForecastReportV03) AddPoolReference() *iso20022.AdditionalReference3 { f.PoolReference = new(iso20022.AdditionalReference3) return f.PoolReference } func (f *FundConfirmedCashForecastReportV03) AddPreviousReference() *iso20022.AdditionalReference3 { newValue := new(iso20022.AdditionalReference3) f.PreviousReference = append(f.PreviousReference, newValue) return newValue } func (f *FundConfirmedCashForecastReportV03) AddRelatedReference() *iso20022.AdditionalReference3 { newValue := new(iso20022.AdditionalReference3) f.RelatedReference = append(f.RelatedReference, newValue) return newValue } func (f *FundConfirmedCashForecastReportV03) AddMessagePagination() *iso20022.Pagination { f.MessagePagination = new(iso20022.Pagination) return f.MessagePagination } func (f *FundConfirmedCashForecastReportV03) AddFundCashForecastDetails() *iso20022.FundCashForecast3 { newValue := new(iso20022.FundCashForecast3) f.FundCashForecastDetails = append(f.FundCashForecastDetails, newValue) return newValue } func (f *FundConfirmedCashForecastReportV03) AddConsolidatedNetCashForecast() *iso20022.NetCashForecast3 { f.ConsolidatedNetCashForecast = new(iso20022.NetCashForecast3) return f.ConsolidatedNetCashForecast } func (f *FundConfirmedCashForecastReportV03) AddExtension() *iso20022.Extension1 { newValue := new(iso20022.Extension1) f.Extension = append(f.Extension, newValue) return newValue }
package piscine func NRune(s string, n int) rune { result := []rune(s) // кастинг - преобразование типов. перевод строки в массив рун for index, value := range result { // перевод массив рун в символы (разбиваем на отдельные элементы ) if index == n-1 { return value } } return 0 }
package queue import "time" // A job to be run by a Queue. type Job struct { // Give jobs a key to ensure no more than one are queued at once. Key string // Wait this long before running the job. Combine with Key to debounce jobs. Delay time.Duration // Repeat job this long after it completes. Repeat time.Duration // The work to be done by the job. Perform func() // If true, don't wait for previous job with same key to finish. Simultaneous bool // Optional function that, given a list of keys of running jobs, returns true if there is a conflict with another job. // Test is performed when job is about to run, not when it is queued. Use this instead of HasConflict when you need // to consider all running jobs, e.g. enforce a maximum of 5 running jobs with keys starting with "abc-". HasConflicts func([]string) bool // Optional function that, given a key of a running job, returns true if it conflicts with this job. Test is // performed when job is about to run, not when it is queued. Use this instead of HasConflicts if you can test each // key separately. HasConflict func(string) bool // When false, job will wait for conflicts to be resolved. When true, job will be discarded immediately on conflict. // Ignored if no HasConflict or HasConflicts functions are set. DiscardOnConflict bool // Optional function that, given the key of another queued job, returns true if this job can take the other job's // place. Can be used, for example, to replace a queued sync-one job with a sync-all job. CanReplace func(string) bool runAt *time.Time } // Add the job to a queue. func (j *Job) AddTo(q *Queue) { q.Add(j) } func (j *Job) hasConflict(runningKeys []string) bool { if j.HasConflict != nil { for _, key := range runningKeys { if j.HasConflict(key) { return true } } } if j.HasConflicts != nil { return j.HasConflicts(runningKeys) } return false }
package gee type RouterGroup struct { prefix string middlewares []HandlerFunc parent *RouterGroup engine *Engine } func (g *RouterGroup) Group(prefix string) *RouterGroup { e := g.engine newGroup := &RouterGroup{ prefix: g.prefix + prefix, parent: g, engine: e, } e.groups = append(e.groups, newGroup) return newGroup } func (g *RouterGroup) addRoute(method string, comp string, handler HandlerFunc) { pattern := g.prefix + comp g.engine.router.addRoute(method, pattern, handler) } // GET defines the method to add GET request func (g *RouterGroup) GET(pattern string, handler HandlerFunc) { g.addRoute("GET", pattern, handler) } // POST defines the method to add POST request func (g *RouterGroup) POST(pattern string, handler HandlerFunc) { g.addRoute("POST", pattern, handler) } func (g *RouterGroup) Use(middlewares ...HandlerFunc) { g.middlewares = append(g.middlewares, middlewares...) }
package physics import ( "github.com/bcokert/engo-test/logging" "github.com/bcokert/engo-test/metrics" ) // The ParticleRegistry stores all particles in some structure, and retrieves them for collision related logic // This is where optimizations like quadtrees and other subdivisions would be done to rule out // particles when checking for collisions type ParticleRegistry struct { log logging.Logger particles map[uint64]particle } func (r *ParticleRegistry) Add(p particle) { defer metrics.Timed(metrics.Func("Registry.Add")) r.log.Debug("Adding particle to registry", logging.F{"id": p.BasicEntity().ID(), "particleComponent": p.ParticleComponent()}) r.particles[p.BasicEntity().ID()] = p } func (r *ParticleRegistry) Remove(id uint64) { defer metrics.Timed(metrics.Func("Registry.Remove")) p, ok := r.particles[id] if ok { r.log.Debug("Removing particle from registry", logging.F{"id": id, "particleComponent": p.ParticleComponent()}) delete(r.particles, id) } }
package cert import ( "fmt" "github.com/cosmos/cosmos-sdk/client" sdktest "github.com/cosmos/cosmos-sdk/testutil" "github.com/ovrclk/akcmd/cmd/akash/x/cert/create" clitestutil "github.com/ovrclk/akcmd/testutil/cli" ) // TxCreateServerExec is used for testing create server certificate tx func TxCreateServerExec(clientCtx client.Context, from fmt.Stringer, host string, extraArgs ...string) (sdktest.BufferWriter, error) { args := []string{ fmt.Sprintf("--from=%s", from.String()), host, } args = append(extraArgs, args...) return clitestutil.ExecTestCLICmd(clientCtx, create.ServerCMD(), args) } // TxCreateClientExec is used for testing create client certificate tx func TxCreateClientExec(clientCtx client.Context, from fmt.Stringer, extraArgs ...string) (sdktest.BufferWriter, error) { args := []string{ fmt.Sprintf("--from=%s", from.String()), } args = append(args, extraArgs...) return clitestutil.ExecTestCLICmd(clientCtx, create.ClientCMD(), args) }
package honeycombio import ( "context" "os" "testing" "github.com/joho/godotenv" "github.com/stretchr/testify/assert" ) func init() { // load environment values from a .env, if available _ = godotenv.Load() } func newTestClient(t *testing.T) *Client { apiKey, ok := os.LookupEnv("HONEYCOMBIO_APIKEY") if !ok { t.Fatal("expected environment variable HONEYCOMBIO_APIKEY") } _, debug := os.LookupEnv("DEBUG") cfg := &Config{ APIKey: apiKey, Debug: debug, } c, err := NewClient(cfg) if err != nil { t.Fatal(err) } return c } func testDataset(t *testing.T) string { dataset, ok := os.LookupEnv("HONEYCOMBIO_DATASET") if !ok { t.Fatalf("expected environment variable HONEYCOMBIO_DATASET") } return dataset } func TestConfig_merge(t *testing.T) { config1 := &Config{ APIKey: "", APIUrl: "", UserAgent: "go-honeycombio", } config2 := &Config{ APIKey: "", APIUrl: "http://localhost", UserAgent: "", } expected := &Config{ APIKey: "", APIUrl: "http://localhost", UserAgent: "go-honeycombio", } config1.merge(config2) assert.Equal(t, expected, config1) } func TestClient_invalidConfig(t *testing.T) { cfg := &Config{ APIKey: "", } _, err := NewClient(cfg) assert.Error(t, err, "APIKey must be configured") cfg = &Config{ APIKey: "123", APIUrl: "cache_object:foo/bar", } _, err = NewClient(cfg) assert.Error(t, err) assert.Contains(t, err.Error(), "could not parse APIUrl") } func TestClient_parseHoneycombioError(t *testing.T) { ctx := context.Background() c := newTestClient(t) err := c.performRequest(ctx, "POST", "/1/boards/", nil, nil) assert.Error(t, err, "400 Bad Request: request body should not be empty") }
package schedule import ( "booking-calendar/utils" "time" ) type DaySchedule struct { startTime time.Time endTime time.Time } func (daySchedule DaySchedule) Start() time.Time { return daySchedule.startTime } func (daySchedule DaySchedule) End() time.Time { return daySchedule.endTime } func (daySchedule DaySchedule) IteratorForDate(date time.Time, duration time.Duration) utils.TimeRangeIterator { // Adjust to the target day daySchedule.startTime = utils.JustifyTime(daySchedule.startTime, date) daySchedule.endTime = utils.JustifyTime(daySchedule.endTime, date) return utils.NewTimeRangeIterator(daySchedule, duration) } func NewDaySchedule(startTime time.Time, endTime time.Time) DaySchedule { return DaySchedule{ startTime: startTime, endTime: endTime, } } func CompileBusinessWeekSchedule(startTime time.Time, endTime time.Time) map[string]DaySchedule { return map[string]DaySchedule{ time.Monday.String(): NewDaySchedule(startTime, endTime), time.Tuesday.String(): NewDaySchedule(startTime, endTime), time.Wednesday.String(): NewDaySchedule(startTime, endTime), time.Thursday.String(): NewDaySchedule(startTime, endTime), time.Friday.String(): NewDaySchedule(startTime, endTime), time.Saturday.String(): NewDaySchedule(startTime, endTime), } }
package main import ( "fmt" ) func main() { fmt.Println(addDigits(27)) } func addDigits(num int) int { return (num-1)%9 + 1 }
package main import ( "fmt" "reflect" "unsafe" ) func main() { var data []string // data is bunch of listed string for record := 0; record < 1050; record ++{ data = append(data, fmt.Sprintf("Rec:%d", record)) // output: data => [ "Rec:0", "Rec:1", ...] if record < 10 || record == 256 || record == 512 || record == 1024 { // &reflect.SliceHeader{} // output: {0, 0, 0} or mean as null struct // try to fill `null { 0, 0, 0} struct` with `restricted ptr .(&data)` // this : fmt.Printf(("%p\n"),(&data)) // same kind as: fmt.Println(unsafe.Pointer(&data)) // below equal as: *reflect.SliceHeader(unsafe.Pointer(&data)) // output : {0, 0, 0} // below equal as: *reflect.SliceHeader(0xc0000a0020) // output: {824634523648, 257[record], 512[record]} sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&data)) // fmt.Printf("%p", *sliceHeader) fmt.Printf("untuk Index[%d] ->Len[%d] ->Cap[%d]\n", record, sliceHeader.Len, sliceHeader.Cap, ) } } /* var oke int oke = (1) fmt.Println(oke) */ }
package db import ( "database/sql" "log" "user-bank-manage/config" _ "github.com/go-sql-driver/mysql" ) var db *sql.DB var err error func Init() { conf := config.GetConfig() // connectionString := "root:Padaringan_k383k@tcp(127.0.0.1:3306)/localpedia" connectionString := conf.DB_USERNAME + ":" + conf.DB_PASSWORD + "@tcp(" + conf.DB_HOST + ":" + conf.DB_PORT + ")/" + conf.DB_NAME db, err = sql.Open("mysql", connectionString) if err != nil { panic("connectionString error..") } err = db.Ping() if err != nil { // panic(err) log.Println(conf.DB_USERNAME) log.Println(conf.DB_PASSWORD) log.Println(conf.DB_HOST) log.Println(conf.DB_PORT) log.Println(conf.DB_NAME) } } func CreateCon() *sql.DB { return db }
package main import ( "fmt" "strings" ) func basename(s string) string { slash := strings.LastIndex(s, "/") // -1 if "/" not found s = s[slash+1:] if dot := strings.LastIndex(s, "."); dot >= 0 { s = s[:dot] } return s } func main() { s := "abc" b := []byte(s) s2 := string(b) fmt.Printf(s2) }
package comment type Mock struct { Interface } func NewMock() *Mock { return &Mock{} } func (s *Mock) Add(id string, comment *Model) error { comment.Id = "b2ff6329-9023-4776-a0ed-ff5fa98a888d" return nil } func (s *Mock) Delete(id string) error { return nil }
package dynamic_programming import ( "fmt" "testing" ) func Test_minDistance(t *testing.T) { // res := minDistance("horse", "ros") res := minDistance2("", "") fmt.Println(res) }
package router import ( "net/http" "project/utils/config" admin "project/app/admin/router" "project/common/middleware" "project/utils" //_ "project/docs" "github.com/gin-contrib/pprof" "github.com/gin-gonic/gin" ginSwagger "github.com/swaggo/gin-swagger" "github.com/swaggo/gin-swagger/swaggerFiles" ) // Setup 路由设置 func Setup(cfg *config.Application) *gin.Engine { if cfg.Mode == string(utils.ModeProd) { gin.SetMode(gin.ReleaseMode) } r := gin.New() r.Use(middleware.Cors(), middleware.GinLogger(), middleware.Sentinel(200)) r.Static(cfg.StaticFileUrl, `./`+cfg.StaticPath) r.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "ok") }) r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) // 注册业务路由 admin.InitAdminRouter(r) r.GET("/", func(c *gin.Context) { c.String(http.StatusOK, "ok") }) pprof.Register(r) // 注册pprof相关路由 return r }
/* Given an unsigned integer that represents a timestamp since 1970/01/01 00:00:00 (which is Unix epoch time), output one of these: An array that stores year, month, date, hour, minute, second. A string in format YYYYMMDDHHmmss. Or whatever similar, as long as it complies with standard i/o rules. Rules Implement the function or the full program from vanilla. So no built-ins nor libraries that has the fuctionality. Implement leap year, too; but don't leap second (although leap second is not supported). You just need to support up to 2038/01/19 (so input range shall be 0 to 2147483647 (inclusive)). Standard loopholes apply. Standard I/O rules apply. Input and output format should be consistent and not ambiguous. So, for example, if output is a string like 1970121000, it's unqualified, as it can be recognized as 1970/01/21 00:00:00, 1970/12/01 00:00:00, or 1970/01/02 10:00:00. Shortest code wins. Test cases 0 -> 1970/01/01 00:00:00 999999999 -> 2001/09/09 01:46:39 1145141919 -> 2006/04/15 22:58:39 1330500000 -> 2012/02/29 07:20:00 1633773293 -> 2021/10/09 09:54:53 2147483647 -> 2038/01/19 03:14:07 Hint Here are implementations: minix-server/gmtime.c シェルスクリプトで時間計算を一人前にこなす: AWK implementation. Try it online! I translated comments. Related problems Unix timestamp to datetime string Shortest script that gives the time passed since a Unix timestamp */ package main import ( "time" ) func main() { assert(unixtime(0) == "1970/01/01 00:00:00") assert(unixtime(999999999) == "2001/09/09 01:46:39") assert(unixtime(1145141919) == "2006/04/15 22:58:39") assert(unixtime(1330500000) == "2012/02/29 07:20:00") assert(unixtime(1633773293) == "2021/10/09 09:54:53") assert(unixtime(2147483647) == "2038/01/19 03:14:07") } func assert(x bool) { if !x { panic("assertion failed") } } func unixtime(s int64) string { t := time.Unix(s, 0) u := t.UTC() return u.Format("2006/01/02 15:04:05") }
package domain import ( "testing" "github.com/gofrs/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) type ReservoirServiceMock struct { mock.Mock } func (m *ReservoirServiceMock) FindFarmByID(uid uuid.UUID) (ReservoirFarmServiceResult, error) { args := m.Called(uid) return args.Get(0).(ReservoirFarmServiceResult), nil } func mockReservoirService(farmUID uuid.UUID, farmName string) *ReservoirServiceMock { reservoirServiceMock := new(ReservoirServiceMock) reservoirFarmServiceResult := ReservoirFarmServiceResult{ UID: farmUID, Name: farmName, } reservoirServiceMock.On("FindFarmByID", farmUID).Return(reservoirFarmServiceResult) return reservoirServiceMock } func TestCreateReservoir(t *testing.T) { // Given farmUID, _ := uuid.NewV4() serviceMock := mockReservoirService(farmUID, "My Farm") // When reservoir, err := CreateReservoir(serviceMock, farmUID, "My Reservoir 1", BucketType, float32(10)) // Then assert.Nil(t, err) assert.NotEqual(t, Reservoir{}, reservoir) event, ok := reservoir.UncommittedChanges[0].(ReservoirCreated) assert.True(t, ok) assert.Equal(t, reservoir.UID, event.UID) } func TestInvalidCreateReservoir(t *testing.T) { // Given farmUID, _ := uuid.NewV4() serviceMock := mockReservoirService(farmUID, "My Farm") reservoirData := []struct { farmUID uuid.UUID name string waterSourceType string capacity float32 expectedError ReservoirError }{ {farmUID, "My<>Reserv", BucketType, float32(10), ReservoirError{ReservoirErrorNameAlphanumericOnlyCode}}, {farmUID, "MyR", TapType, float32(0), ReservoirError{ReservoirErrorNameNotEnoughCharacterCode}}, {farmUID, "MyReservoirNameShouldNotBeMoreThanAHundredLongCharactersMyReservoirNameShouldNotBeMoreThanAHundredLongCharacters", TapType, 0, ReservoirError{ReservoirErrorNameExceedMaximunCharacterCode}}, } for _, data := range reservoirData { // When _, err := CreateReservoir(serviceMock, farmUID, data.name, data.waterSourceType, data.capacity) // Then assert.Equal(t, data.expectedError, err) } } func TestReservoirCreateRemoveNote(t *testing.T) { // Given farmUID, _ := uuid.NewV4() serviceMock := mockReservoirService(farmUID, "My Farm") noteContent := "This is my new note" reservoir, reservoirErr := CreateReservoir(serviceMock, farmUID, "MyReservoir", BucketType, float32(10)) // When noteErr := reservoir.AddNewNote(noteContent) // Then assert.Nil(t, reservoirErr) assert.Nil(t, noteErr) assert.Equal(t, 1, len(reservoir.Notes)) uid := uuid.UUID{} for k, v := range reservoir.Notes { assert.Equal(t, noteContent, v.Content) assert.NotEqual(t, uuid.UUID{}, v.UID) uid = k } event1, ok := reservoir.UncommittedChanges[1].(ReservoirNoteAdded) assert.True(t, ok) assert.Equal(t, reservoir.UID, event1.ReservoirUID) // When reservoir.RemoveNote(uid) // Then assert.Equal(t, 0, len(reservoir.Notes)) event2, ok := reservoir.UncommittedChanges[2].(ReservoirNoteRemoved) assert.True(t, ok) assert.Equal(t, reservoir.UID, event2.ReservoirUID) } func TestCreateWaterSource(t *testing.T) { // Given capacity := float32(100) // When bucket, err1 := CreateBucket(capacity) tap, err2 := CreateTap() // Then assert.Nil(t, err1) assert.NotEqual(t, bucket, Bucket{}) assert.Equal(t, capacity, bucket.Capacity) assert.Equal(t, BucketType, bucket.Type()) assert.Nil(t, err2) assert.Equal(t, tap, Tap{}) assert.Equal(t, TapType, tap.Type()) } func TestInvalidCreateWaterSource(t *testing.T) { // When bucket1, err1 := CreateBucket(0) bucket2, err2 := CreateBucket(-1) // Then assert.Equal(t, ReservoirError{ReservoirErrorBucketCapacityInvalidCode}, err1) assert.Equal(t, Bucket{}, bucket1) assert.Equal(t, ReservoirError{ReservoirErrorBucketCapacityInvalidCode}, err2) assert.Equal(t, Bucket{}, bucket2) } func TestReservoirChangeWaterSource(t *testing.T) { // Given farmUID, _ := uuid.NewV4() serviceMock := mockReservoirService(farmUID, "My Farm") reservoirBucket, resBucketErr := CreateReservoir(serviceMock, farmUID, "MyReservoir Bucket", BucketType, float32(10)) reservoirTap, resTapErr := CreateReservoir(serviceMock, farmUID, "MyReservoir Tap", TapType, 0) // When reservoirBucket.ChangeWaterSource(TapType, 0) reservoirTap.ChangeWaterSource(BucketType, float32(100)) // Then assert.Nil(t, resBucketErr) assert.Nil(t, resTapErr) assert.Equal(t, TapType, reservoirBucket.WaterSource.Type()) _, ok := reservoirBucket.WaterSource.(Tap) assert.True(t, ok) assert.Equal(t, BucketType, reservoirTap.WaterSource.Type()) event1, ok := reservoirBucket.UncommittedChanges[1].(ReservoirWaterSourceChanged) assert.True(t, ok) assert.Equal(t, reservoirBucket.UID, event1.ReservoirUID) // Then bucket, ok := reservoirTap.WaterSource.(Bucket) assert.True(t, ok) assert.Equal(t, float32(100), bucket.Capacity) event2, ok := reservoirTap.UncommittedChanges[1].(ReservoirWaterSourceChanged) assert.True(t, ok) assert.Equal(t, reservoirTap.UID, event2.ReservoirUID) } func TestReservoirChangeName(t *testing.T) { // Given farmUID, _ := uuid.NewV4() serviceMock := mockReservoirService(farmUID, "My Farm") res, resErr := CreateReservoir(serviceMock, farmUID, "My Reservoir", BucketType, float32(10)) // When res.ChangeName("My Reservoir Changed") // Then assert.Nil(t, resErr) assert.Equal(t, "My Reservoir Changed", res.Name) event, ok := res.UncommittedChanges[1].(ReservoirNameChanged) assert.True(t, ok) assert.Equal(t, res.UID, event.ReservoirUID) assert.Equal(t, res.Name, event.Name) }
package easypost import ( "context" "encoding/json" "io" "io/ioutil" "net/http" "net/url" "strings" ) // A BetaPaymentRefund that has the refund details for the refund request. type BetaPaymentRefund struct { RefundedAmount int `json:"refunded_amount,omitempty"` RefundedPaymentLogs []string `json:"refunded_payment_log,omitempty"` PaymentLogId string `json:"payment_log_id,omitempty"` Errors []APIError `json:"errors,omitempty"` } // A ReferralCustomer contains data about an EasyPost referral customer. type ReferralCustomer struct { User } // ListReferralCustomersResult holds the results from the list referral customers API call. type ListReferralCustomersResult struct { ReferralCustomers []*ReferralCustomer `json:"referral_customers,omitempty"` PaginatedCollection } // CreditCardOptions specifies options for creating or updating a credit card. type CreditCardOptions struct { Number string `json:"number,omitempty"` ExpMonth string `json:"expiration_month,omitempty"` ExpYear string `json:"expiration_year,omitempty"` Cvc string `json:"cvc,omitempty"` } type stripeApiKeyResponse struct { PublicKey string `json:"public_key"` } type stripeTokenResponse struct { Id string `json:"id"` } type referralCustomerRequest struct { UserOptions *UserOptions `json:"user,omitempty"` } type creditCardCreateRequest struct { CreditCard *easypostCreditCardCreateOptions `json:"credit_card,omitempty"` } type easypostCreditCardCreateOptions struct { StripeToken string `json:"stripe_object_id"` Priority string `json:"priority"` } // CreateReferralCustomer creates a new referral customer. func (c *Client) CreateReferralCustomer(in *UserOptions) (out *ReferralCustomer, err error) { return c.CreateReferralCustomerWithContext(context.Background(), in) } // CreateReferralCustomerWithContext performs the same operation as CreateReferralCustomer, but allows // specifying a context that can interrupt the request. func (c *Client) CreateReferralCustomerWithContext(ctx context.Context, in *UserOptions) (out *ReferralCustomer, err error) { err = c.post(ctx, "referral_customers", &referralCustomerRequest{UserOptions: in}, &out) return } // ListReferralCustomers provides a paginated result of ReferralCustomer objects. func (c *Client) ListReferralCustomers(opts *ListOptions) (out *ListReferralCustomersResult, err error) { return c.ListReferralCustomersWithContext(context.Background(), opts) } // ListReferralCustomersWithContext performs the same operation as ListReferralCustomers, but // allows specifying a context that can interrupt the request. func (c *Client) ListReferralCustomersWithContext(ctx context.Context, opts *ListOptions) (out *ListReferralCustomersResult, err error) { err = c.do(ctx, http.MethodGet, "referral_customers", c.convertOptsToURLValues(opts), &out) return } // GetNextReferralCustomerPage returns the next page of referral customers func (c *Client) GetNextReferralCustomerPage(collection *ListReferralCustomersResult) (out *ListReferralCustomersResult, err error) { return c.GetNextReferralCustomerPageWithContext(context.Background(), collection) } // GetNextReferralCustomerPageWithPageSize returns the next page of referral customers with a specific page size func (c *Client) GetNextReferralCustomerPageWithPageSize(collection *ListReferralCustomersResult, pageSize int) (out *ListReferralCustomersResult, err error) { return c.GetNextReferralCustomerPageWithPageSizeWithContext(context.Background(), collection, pageSize) } // GetNextReferralCustomerPageWithContext performs the same operation as GetNextReferralCustomerPage, but // allows specifying a context that can interrupt the request. func (c *Client) GetNextReferralCustomerPageWithContext(ctx context.Context, collection *ListReferralCustomersResult) (out *ListReferralCustomersResult, err error) { return c.GetNextReferralCustomerPageWithPageSizeWithContext(ctx, collection, 0) } // GetNextReferralCustomerPageWithPageSizeWithContext performs the same operation as GetNextReferralCustomerPageWithPageSize, but // allows specifying a context that can interrupt the request. func (c *Client) GetNextReferralCustomerPageWithPageSizeWithContext(ctx context.Context, collection *ListReferralCustomersResult, pageSize int) (out *ListReferralCustomersResult, err error) { if len(collection.ReferralCustomers) == 0 { err = EndOfPaginationError return } lastID := collection.ReferralCustomers[len(collection.ReferralCustomers)-1].ID params, err := nextPageParameters(collection.HasMore, lastID, pageSize) if err != nil { return } return c.ListReferralCustomersWithContext(ctx, params) } // UpdateReferralCustomerEmail updates a ReferralCustomer's email address func (c *Client) UpdateReferralCustomerEmail(userId string, email string) (out *ReferralCustomer, err error) { return c.UpdateReferralCustomerEmailWithContext(context.Background(), userId, email) } // UpdateReferralCustomerEmailWithContext performs the same operation as UpdateReferralCustomerEmail, but allows // specifying a context that can interrupt the request. func (c *Client) UpdateReferralCustomerEmailWithContext(ctx context.Context, userId string, email string) (out *ReferralCustomer, err error) { req := referralCustomerRequest{ UserOptions: &UserOptions{ Email: &email, }, } err = c.put(ctx, "referral_customers/"+userId, req, &out) return } // AddReferralCustomerCreditCard adds a credit card to a referral customer's account. func (c *Client) AddReferralCustomerCreditCard(referralCustomerApiKey string, creditCardOptions *CreditCardOptions, priority PaymentMethodPriority) (out *PaymentMethodObject, err error) { return c.AddReferralCustomerCreditCardWithContext(context.Background(), referralCustomerApiKey, creditCardOptions, priority) } // AddReferralCustomerCreditCardWithContext performs the same operation as AddReferralCustomerCreditCard, but allows // specifying a context that can interrupt the request. func (c *Client) AddReferralCustomerCreditCardWithContext(ctx context.Context, referralCustomerApiKey string, creditCardOptions *CreditCardOptions, priority PaymentMethodPriority) (out *PaymentMethodObject, err error) { stripeApiKeyResponse, err := c.retrieveEasypostStripeApiKey(ctx) if err != nil || stripeApiKeyResponse == nil || stripeApiKeyResponse.PublicKey == "" { return nil, &InternalServerError{ APIError: APIError{ Code: "Could not create Stripe token, please try again later", StatusCode: 500, }, } } stripeTokenResponse, err := c.createStripeToken(ctx, stripeApiKeyResponse.PublicKey, creditCardOptions) if err != nil || stripeTokenResponse == nil || stripeTokenResponse.Id == "" { return nil, newExternalApiError("Could not create Stripe token, please try again later") } return c.createEasypostCreditCard(ctx, referralCustomerApiKey, stripeTokenResponse.Id, priority) } func (c *Client) retrieveEasypostStripeApiKey(ctx context.Context) (out *stripeApiKeyResponse, err error) { err = c.get(ctx, "partners/stripe_public_key", &out) return } func (c *Client) createStripeToken(ctx context.Context, stripeApiKey string, creditCardOptions *CreditCardOptions) (out *stripeTokenResponse, err error) { data := url.Values{} data.Set("card[number]", creditCardOptions.Number) data.Set("card[exp_month]", creditCardOptions.ExpMonth) data.Set("card[exp_year]", creditCardOptions.ExpYear) data.Set("card[cvc]", creditCardOptions.Cvc) req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.stripe.com/v1/tokens", strings.NewReader(data.Encode())) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Add("Authorization", "Bearer "+stripeApiKey) resp, err := c.client().Do(req) // use the current client's inner http.Client (configured to record) for the one-off request if err != nil { return nil, err } defer func(Body io.ReadCloser) { _ = Body.Close() }(resp.Body) body, err := ioutil.ReadAll(resp.Body) // deprecated, but we have to keep it for legacy compatibility if err != nil { return nil, err } err = json.Unmarshal(body, &out) if err != nil { return nil, err } return } func (c *Client) createEasypostCreditCard(ctx context.Context, referralCustomerApiKey string, stripeToken string, priority PaymentMethodPriority) (out *PaymentMethodObject, err error) { client := &Client{ APIKey: referralCustomerApiKey, Client: c.client(), // pass the current client's inner http.Client (configured to record) to the new client } creditCardOptions := &easypostCreditCardCreateOptions{ StripeToken: stripeToken, Priority: c.GetPaymentEndpointByPrimaryOrSecondary(priority), } creditCardRequest := &creditCardCreateRequest{ CreditCard: creditCardOptions, } err = client.post(ctx, "credit_cards", creditCardRequest, &out) return } // BetaAddPaymentMethod adds Stripe payment method to referral customer. func (c *Client) BetaAddPaymentMethod(stripeCustomerId string, paymentMethodReference string, priority PaymentMethodPriority) (out *PaymentMethodObject, err error) { return c.BetaAddPaymentMethodWithContext(context.Background(), stripeCustomerId, paymentMethodReference, priority) } // BetaAddPaymentMethodWithContext performs the same operation as BetaAddPaymentMethod, but allows // specifying a context that can interrupt the request. func (c *Client) BetaAddPaymentMethodWithContext(ctx context.Context, stripeCustomerId string, paymentMethodReference string, priority PaymentMethodPriority) (out *PaymentMethodObject, err error) { wrappedParams := map[string]interface{}{ "payment_method": map[string]interface{}{ "stripe_customer_id": stripeCustomerId, "payment_method_reference": paymentMethodReference, "priority": c.GetPaymentEndpointByPrimaryOrSecondary(priority), }, } err = c.post(ctx, "/beta/referral_customers/payment_method", wrappedParams, out) return } // BetaRefundByAmount refunds a recent payment by amount in cents. func (c *Client) BetaRefundByAmount(refundAmount int) (out *BetaPaymentRefund, err error) { return c.BetaRefundByAmountWithContext(context.Background(), refundAmount) } // BetaRefundByAmountWithContext performs the same operation as BetaRefundByAmount, but allows // specifying a context that can interrupt the request. func (c *Client) BetaRefundByAmountWithContext(ctx context.Context, refundAmount int) (out *BetaPaymentRefund, err error) { params := map[string]interface{}{ "refund_amount": refundAmount, } err = c.post(ctx, "/beta/referral_customers/refunds", params, out) return } // BetaRefundByAmount refunds a payment by paymenbt log ID. func (c *Client) BetaRefundByPaymentLog(paymentLogId string) (out *BetaPaymentRefund, err error) { return c.BetaRefundByPaymentLogWithContext(context.Background(), paymentLogId) } // BetaRefundByPaymentLogWithContext performs the same operation as BetaRefundByPaymentLog, but allows // specifying a context that can interrupt the request. func (c *Client) BetaRefundByPaymentLogWithContext(ctx context.Context, paymentLogId string) (out *BetaPaymentRefund, err error) { params := map[string]interface{}{ "payment_log_id": paymentLogId, } err = c.post(ctx, "/beta/referral_customers/refunds", params, out) return }
package main import ( "errors" "testing" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" "github.com/aws/aws-sdk-go/service/cognitoidentityprovider/cognitoidentityprovideriface" ) type mockDelete struct { cognitoidentityprovideriface.CognitoIdentityProviderAPI Response cognitoidentityprovider.DeleteUserOutput } func (d mockDelete) DeleteUser(in *cognitoidentityprovider.DeleteUserInput) (*cognitoidentityprovider.DeleteUserOutput, error) { if *in.AccessToken != "CorrectToken" { return nil, awserr.New( cognitoidentityprovider.ErrCodeResourceNotFoundException, "Resources not found", errors.New("Resources not found"), ) } return &d.Response, nil } func TestHandleRequest(t *testing.T) { t.Run("Successfully logout a user", func(t *testing.T) { // load test data deleteUserInput := DeleteUserInput{AccessToken: "CorrectToken"} // create mock output m := mockDelete{} // create dependancy object d := deps{ cognito: m, } //execute test of function _, err := d.HandleRequest(nil, deleteUserInput) if err != nil { t.Error("Failed to delete user") } }) t.Run("delete user attempt with invalid token", func(t *testing.T) { // load test data deleteUserInput := DeleteUserInput{AccessToken: "IncorrectToken"} // create mock output m := mockDelete{} // create dependancy object d := deps{ cognito: m, } //execute test of function result, err := d.HandleRequest(nil, deleteUserInput) if result.Message != "Invalid access token provided" || err == nil { t.Error("Failed to catch and handle invalid token exception") } }) }
package main import ( "time" ) const ENDLESS = 99999 * time.Hour type TransitionFSM struct { next NextStateFunc doTransition bool } func (fsm *TransitionFSM) Setup(doTransition bool, next NextStateFunc) { fsm.doTransition = doTransition fsm.next = next } type NextRoomFSM struct { } type GameOverAllFSM struct { }
package cluster // Copyright (c) Microsoft Corporation. // Licensed under the Apache License 2.0. import ( "context" "net/http" "github.com/Azure/go-autorest/autorest/azure" "github.com/sirupsen/logrus" "k8s.io/client-go/kubernetes" "github.com/Azure/ARO-RP/pkg/api" "github.com/Azure/ARO-RP/pkg/env" "github.com/Azure/ARO-RP/pkg/metrics" "github.com/Azure/ARO-RP/pkg/util/restconfig" ) type Monitor struct { env env.Interface log *logrus.Entry oc *api.OpenShiftCluster dims map[string]string cli kubernetes.Interface m metrics.Interface } func NewMonitor(env env.Interface, log *logrus.Entry, oc *api.OpenShiftCluster, m metrics.Interface) (*Monitor, error) { r, err := azure.ParseResourceID(oc.ID) if err != nil { return nil, err } dims := map[string]string{ "resourceId": oc.ID, "subscriptionId": r.SubscriptionID, "resourceGroup": r.ResourceGroup, "resourceName": r.ResourceName, } restConfig, err := restconfig.RestConfig(env, oc) if err != nil { return nil, err } cli, err := kubernetes.NewForConfig(restConfig) if err != nil { return nil, err } return &Monitor{ env: env, log: log, oc: oc, dims: dims, cli: cli, m: m, }, nil } // Monitor checks the API server health of a cluster func (mon *Monitor) Monitor(ctx context.Context) error { mon.log.Debug("monitoring") // If API is not returning 200, don't need to run the next checks statusCode, err := mon.emitAPIServerHealthzCode(ctx) if err != nil || statusCode != http.StatusOK { return err } return mon.emitPrometheusAlerts(ctx) } func (mon *Monitor) emitFloat(m string, value float64, dims map[string]string) { for k, v := range mon.dims { dims[k] = v } mon.m.EmitFloat(m, value, dims) } func (mon *Monitor) emitGauge(m string, value int64, dims map[string]string) { for k, v := range mon.dims { dims[k] = v } mon.m.EmitGauge(m, value, dims) }
package acl import ( "io" ) func unpackTSV(r io.Reader) (map[string][]byte, string, error) { files := map[string][]byte{} uname := "" if bytes, err := io.ReadAll(r); err != nil { return nil, "", err } else { files["ACL"] = bytes } files["signature"] = []byte{} return files, uname, nil }
/* Output the following result (which is a result of calculating 6 * 9 in bases from 2 to 36). Make sure letters are uppercase, and the multiplication itself is outputed on every line. 6 * 9 = 110110 6 * 9 = 2000 6 * 9 = 312 6 * 9 = 204 6 * 9 = 130 6 * 9 = 105 6 * 9 = 66 6 * 9 = 60 6 * 9 = 54 6 * 9 = 4A 6 * 9 = 46 6 * 9 = 42 6 * 9 = 3C 6 * 9 = 39 6 * 9 = 36 6 * 9 = 33 6 * 9 = 30 6 * 9 = 2G 6 * 9 = 2E 6 * 9 = 2C 6 * 9 = 2A 6 * 9 = 28 6 * 9 = 26 6 * 9 = 24 6 * 9 = 22 6 * 9 = 20 6 * 9 = 1Q 6 * 9 = 1P 6 * 9 = 1O 6 * 9 = 1N 6 * 9 = 1M 6 * 9 = 1L 6 * 9 = 1K 6 * 9 = 1J 6 * 9 = 1I Shortest code wins. */ package main import ( "fmt" "strconv" "strings" ) func main() { table(6, 9) } func table(a, b int64) { for i := 2; i <= 36; i++ { s := strconv.FormatInt(a*b, i) s = strings.ToUpper(s) fmt.Printf("%d * %d = %s\n", a, b, s) } }
package mygl import ( "io" "os" "path" "reflect" "testing" "time" ) const ( testFileDir = "test_files" ) func assertFile(t *testing.T, filename string, expected []*Entry) { f, err := os.Open(path.Join(testFileDir, filename)) if err != nil { t.Fatalf("unable to open test file %s for reading, %v", filename, err) } r := NewReader(f) for i, e := range expected { actual, err := r.ReadEntry() if err != nil { t.Fatalf("%s entry %d, unable to read entry, %v", filename, i, err) } if !reflect.DeepEqual(actual, e) { t.Errorf( "%s entry %d, entries do not match\nexpected: %s\nactual: %s", filename, i, e, actual, ) } } if _, err := r.ReadEntry(); err != io.EOF { t.Errorf("%s, expected io.EOF at end but got %v", filename, err) } } func parseTime(t *testing.T, input string) time.Time { ti, err := time.Parse(TimeFormat, input) if err != nil { t.Fatalf("time %s is in the wrong format", input) } return ti } func TestReader_ReadEntry_simple(t *testing.T) { assertFile(t, "simple", []*Entry{ { Time: parseTime(t, "150703 23:26:04"), ID: 15, Command: CmdQuery, Argument: "SET GLOBAL query_cache_size=0", }, { Time: parseTime(t, "150703 23:26:13"), ID: 15, Command: CmdQuery, Argument: `SELECT * FROM blah_core.users`, }, { Time: parseTime(t, "150703 23:30:07"), ID: 16, Command: CmdConnect, Argument: "someuser@localhost on blah_core", }, { Time: parseTime(t, "150703 23:30:07"), ID: 16, Command: CmdQuery, Argument: "select @@version_comment limit 1", }, { Time: parseTime(t, "150703 23:30:07"), ID: 16, Command: CmdQuery, Argument: "SELECT COUNT(DISTINCT user_id), COUNT(DISTINCT organisation_id) FROM usersorganisations WHERE last_on >= UNIX_TIMESTAMP() - 600", }, { Time: parseTime(t, "150703 23:30:07"), ID: 16, Command: CmdQuit, Argument: "", }, { Time: parseTime(t, "150703 23:30:07"), ID: 17, Command: CmdConnect, Argument: "someuser@localhost on blah_core", }, { Time: parseTime(t, "150703 23:30:07"), ID: 17, Command: CmdQuery, Argument: "select @@version_comment limit 1", }, }) }
package setting import ( "database/sql" "github.com/SUCHMOKUO/falcon-ws/util" "log" "path/filepath" ) var ( db *sql.DB ) func init() { prepareDB() initTable() } func prepareDB() { dbPath := filepath.Join(util.GetCurrentPath(), "setting.db") var err error db, err = sql.Open("sqlite3", dbPath) if err != nil { log.Fatalln("open db error:", err) } } func initTable() { _, err := db.Exec(` CREATE TABLE IF NOT EXISTS setting ( server_addr TEXT NOT NULL, secure TEXT NOT NULL, ipv6 TEXT NOT NULL, lookup TEXT NOT NULL, fake_host TEXT NOT NULL, user_agent TEXT NOT NULL, dns_addr TEXT NOT NULL, tun_net TEXT NOT NULL ) `) if err != nil { log.Fatalln("init table error:", err) } }
package main import "fmt" func main(){ // arrays var fruitArray [2] string // assign values fruitArray[0] = "apples" fruitArray[1] = "oranges" fmt.Println(fruitArray) fmt.Println(fruitArray[0]) fmt.Println(fruitArray[1]) // declare and assign fruitArrayTwo := [2]string{"watermelon", "grapes"} fmt.Println(fruitArrayTwo) // slices fruitSlice := []string{"watermelon", "grapes", "melon", "mango"} fmt.Println(fruitSlice) // length fmt.Println(len(fruitSlice)) // range fmt.Println(fruitSlice[1:3]) }
package common import ( "testing" "github.com/stretchr/testify/assert" ) func TestKhoriumStepBuildEnvironmentVariables(t *testing.T) { assert := assert.New(t) ks := &KhoriumStep{ Name: "test", Description: "test", Inputs: map[string]*KhoriumStepInput{ "input1": { Description: "input1", Default: "default1", Required: false, }, "input2": { Description: "input2", Required: true, }, }, Run: &KhoriumStepRun{ Main: "", Post: "", }, } ev1, err := ks.BuildEnvironmentVariables(map[string]string{"input1": "i1", "input2": "i2", "input3": "i3"}) assert.NoError(err) assert.Equal(len(ev1), 2) assert.Equal(ev1["KHORIUMSTEP_INPUT_INPUT1"], "i1") assert.Equal(ev1["KHORIUMSTEP_INPUT_INPUT2"], "i2") ev2, err := ks.BuildEnvironmentVariables(map[string]string{"input2": "i2", "input3": "i3"}) assert.NoError(err) assert.Equal(len(ev2), 2) assert.Equal(ev2["KHORIUMSTEP_INPUT_INPUT1"], "default1") assert.Equal(ev2["KHORIUMSTEP_INPUT_INPUT2"], "i2") _, err = ks.BuildEnvironmentVariables(map[string]string{"input1": "i1", "input3": "i3"}) assert.Error(err) }