text
stringlengths
11
4.05M
package hsm import "container/list" import "errors" // Trigger() is a helper function to dispatch event of different types to // the corresponding method. func Trigger(hsm HSM, state State, event Event) State { switch event.Type() { case EventEmpty: return state.Super() case EventInit: return state.Init(hsm, e...
package proxy import ( "context" "crypto/cipher" "fmt" "net/url" "github.com/pomerium/pomerium/config" "github.com/pomerium/pomerium/internal/encoding" "github.com/pomerium/pomerium/internal/encoding/jws" "github.com/pomerium/pomerium/internal/sessions" "github.com/pomerium/pomerium/internal/sessions/cookie"...
package paillier import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/sha256" "encoding/asn1" "encoding/base64" "fmt" "math/big" ) var curve = elliptic.P256() // ECDSASignature is the structure for marshall signature type ECDSASignature struct { R, S *big.Int } func Commit(prvkey *ecdsa.PrivateK...
package httputil import ( "encoding/json" "io" "net/http" "github.com/go-playground/form" ) type response struct { StatusCode int `json:"status_code"` Messages []string `json:"messages"` Data interface{} `json:"data"` } func marshalJSONResponse(statusCode int, messages []string, data inter...
package util import ( "bytes" "crypto/ecdsa" "crypto/sm2" "crypto/x509" "encoding/pem" "errors" "fmt" ) func PriKeyToPem(sm2PriKey interface{}) (pemPriKey string, err error) { priKeyStream, _ := x509.MarshalSm2PrivateKey(sm2PriKey.(*sm2.PrivateKey)) fmt.Println("-----------------SM2私钥字节-----------------") f...
/* description : helloworld is a Go version of the Hello World program author : Tom Geudens (https://github.com/tomgeudens/) modified : 2017/07/17 */ package main import ( "fmt" ) func main() { fmt.Println("Hello, 世界") }
package queue // (slice) type Queue struct { Ele []interface{} } func NewQueue() *Queue { return &Queue{ Ele: make([]interface{}, 0), } } func (q Queue) Empty() bool { if q.Ele == nil || len(q.Ele) == 0 { return true } return false } func (q Queue) Size() int { return len(q.Ele) } // 入队列 func (q *Queue)...
// ˅ package main import ( "fmt" "os" ) // ˄ type HTMLBuilder struct { // ˅ // ˄ // File name to create result string writer *os.File // ˅ // ˄ } func NewHTMLBuilder() *HTMLBuilder { // ˅ return &HTMLBuilder{} // ˄ } // Make a title of HTML file func (self *HTMLBuilder) CreateTitle(title string) {...
// Package route and its subpackages provides // most of what you need for http server. // // package route import ( "os" chi "github.com/go-chi/chi" docgen "github.com/go-chi/docgen" // middleware "github.com/go-chi/chi/middleware" ) // Router embeds chi router type Router struct { chi.Router } // New returns...
package cgo import ( "fmt" "strings" "github.com/graphql-go/graphql" ) // UserRoleType role of user var UserRoleType = graphql.NewEnum(graphql.EnumConfig{ Name: "UserRole", Description: "The role of the user", Values: graphql.EnumValueConfigMap{ strings.ToUpper(ContextRoleAdmin): &graphql.EnumValueCon...
// Package ut implements some testing utilities. So far it includes CallTracker, which helps you build // mock implementations of interfaces. package ut import ( "bytes" "fmt" "reflect" "runtime" "sync" "testing" ) // CallTracker is an interface to help build mocks. // // Build the CallTracker interface into yo...
// Generated from AdlP.g4 by ANTLR 4.7. package adllp // AdlP import "github.com/wxio/goantlr" // AdlPListener is a complete listener for a parse tree produced by AdlP. type AdlPListener interface { antlr.ParseTreeListener AdlEntryListener AdlExitListener ModuleStatementEntryListener ModuleStatementExitListene...
embedded_components { id: "sprite" type: "sprite" data: "tile_set: \"/main/outfit_lg.atlas\"\n" "default_animation: \"dollv_blazer\"\n" "material: \"/materials/solid.material\"\n" "blend_mode: BLEND_MODE_ALPHA\n" "" position { x: 0.0 y: 0.0 z: 0.0 } rotation { x: 0.0 y: 0.0 z...
package main import ( "log" ) // RainDrop holds the state of a single raindrop type RainDrop struct { char rune x int y int } // Rain holds the state of all raindrops // Density detemines number of raindrops created for a rain // For a rain with 50w and 20h, the area is 50 * 20 = 1000 // Density of 0.5 mea...
// Copyright 2019 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
package lambda import ( "encoding/json" "io" "io/ioutil" "os" ) type configLoader struct { ConfigURL string `json:"config_url"` } // ReadFromFile reads a file from disk func (c *configLoader) ReadFromFile(name string) error { f, err := os.Open(name) if err != nil { return err } defer f.Close() config, ...
package email // Custom map implementation as GoLang maps are not ordered type Map struct { Key string Value string }
// Copyright 2022 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
package util import ( "io/ioutil" "fmt" "encoding/json" "flag" ) var ( instance *Config conf = flag.String("conf","../etc/config.json","描述") ) type Config struct { BasePath string `json:"base_path"` DataPath string `json:"data_path"` } func init() { //NewConfigWithFile("/Users/d...
package main import ( "runtime" _ "fmt" "regexp" "strings" "dytt8_spider/handle/dl" "dytt8_spider/util" ) func main() { //最大开两个原生线程,以达到真正的并行 runtime.GOMAXPROCS(2) run() } var ( //匹配出需要的html title_pattern = regexp.MustCompile(`<div class="title_all">(.*?)</div>`) //标题名字匹配 name_pattern = regexp.Must...
package main import ( "flag" "fmt" "io/ioutil" "net/http" "os" "github.com/kelseyhightower/envconfig" log "github.com/sirupsen/logrus" ) // App is the application configuration and runtime information type App struct { ShowHelp bool `envconfig:"HELP" default:"false" desc:"show this message"` OFTeeAPI stri...
package pie // Intersect returns items that exist in all lists. // // It returns slice without any duplicates. // If zero slice arguments are provided, then nil is returned. func Intersect[T comparable](ss []T, slices ...[]T) (ss2 []T) { if slices == nil { return nil } var uniqs = make([]map[T]struct{}, len(slic...
// Copyright © 2018 Inanc Gumus // Learn Go Programming Course // License: https://creativecommons.org/licenses/by-nc-sa/4.0/ // // For more tutorials : https://learngoprogramming.com // In-person training : https://www.linkedin.com/in/inancgumus/ // Follow me on twitter: https://twitter.com/inancgumus package main ...
package response type CreatedBill struct { Url string `json:"url,omitempty"` BillId int `json:"bill"` }
package protocols import ( "github.com/stellar/go/amount" "github.com/stellar/go/keypair" ) // IsValidAccountID returns true if account ID is valid func IsValidAccountID(accountID string) bool { _, err := keypair.Parse(accountID) if err != nil { return false } if accountID[0] != 'G' { return false } ret...
// Copyright 2014 The Sporting Exchange Limited. All rights reserved. // Use of this source code is governed by a free license that can be // found in the LICENSE file. package tsdb import ( "fmt" "io" "regexp" "strconv" "strings" "testing" ) var testDecode = []struct { in string err string }{ { in: time...
package main import ( "bufio" "fmt" "log" "os" "time" ) func main() { go func() { sc := bufio.NewScanner(os.Stdin) f := func() bool { fmt.Print(">> ") return sc.Scan() } for f() { if err := sc.Err(); err != nil { log.Fatal(err) } switch sc.Text() { case "exit": os.Exit(0) de...
package cera import ( _ "github.com/xxxmailk/cera/http" _ "github.com/xxxmailk/cera/middlewares" _ "github.com/xxxmailk/cera/middlewares/access" _ "github.com/xxxmailk/cera/middlewares/auth" _ "github.com/xxxmailk/cera/router" _ "github.com/xxxmailk/cera/view" )
package models import ( "time" "github.com/astaxie/beego/orm" ) const UserTableName = "user" // User model defines structure of users table type User struct { ID int `orm:"column(id)"` Name string `orm:"column(name)"` Email string `orm:"column(email);unique"` Password string ...
package master import ( "FoG/src/github.com/cl/crontab/common" "encoding/json" "fmt" "net" "net/http" "strconv" "time" ) //日志查看相关 type ApiServer struct { httpServer *http.Server } var ( // 单例对象,首字母大写,可以被其他包访问到 G_apiServer *ApiServer ) // 保存任务的接口 // POST job={name command cronExpr} func handlerJobSave(r...
package dalmodel import "github.com/jinzhu/gorm" type Measurement struct { gorm.Model Name string Description string UserID uint Hashtags []Hashtag `gorm:"many2many:measurement_hashtags;"` Measurements []MeasurementResult `gorm:"foreignkey:MeasurementID"` } type MeasurementResult s...
package hw04_lru_cache //nolint:golint,stylecheck type List interface { Len() int Front() *listItem Back() *listItem PushFront(v interface{}) *listItem PushBack(v interface{}) *listItem Remove(i *listItem) MoveToFront(i *listItem) } type listItem struct { Next *listItem Prev *listItem Value interface{} } ...
package session type Session interface { Set(key, value interface{}) error Get(key interface{}) interface{} Delete(key interface{}) error SessionID() string }
package goSolution import "math" func powerfulIntegers(x int, y int, bound int) []int { t := make(map[int]bool, bound) for i := 0; ; i++ { c := true for j := 0; ; j++ { k := int(math.Pow(float64(x), float64(i))) + int(math.Pow(float64(y), float64(j))) if k > bound { break } c = false t[k] = t...
package main import "os" type Config struct { FileLocation string } func CollectConfig() (config Config) { // DB_ENGINE fileLocation := os.Getenv("FILE_LOCATION") if fileLocation == "" { config.FileLocation = "relay.jsonld" } else { config.FileLocation = fileLocation } return }
// Copyright 2017 by caixw, All rights reserved. // Use of this source code is governed by a MIT // license that can be found in the LICENSE file. package vars // 所有标签的定义 const ( API = "@api" APIDoc = "@apidoc" APILicense = "@apiLicense" APIVersion = "@apiVersion" APIParam = "@apiParam" APIQuery ...
/* 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...
package values import ( "context" "helm.sh/helm/v3/pkg/chart" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" chartsapi "x-helm.dev/apimachinery/apis/charts/v1alpha1" ) func MergePresetValues(kc client.Client, chrt *chart.Chart, ref chartsapi.ChartPresetFlatRef) (map[st...
package main import ( "fmt" "io/ioutil" "log" "math/rand" //"ms/sun/servises/file_service_old" "ms/sun/shared/helper" "net/http" "strings" "time" "ms/sun/shared/xc" "ms/sun/servises/file_service/file_store" ) var cnt int = 1 var size int = 0 func main() { Insert_many(10) //file_service_old.Run() ...
package business import "fmt" var searchAllWithNameLikeKeywordStmt = ` MATCH (n) WHERE n.name =~ $regex RETURN n, labels(n) SKIP $offset LIMIT $limit ` var countSearchAllWithNameLikeKeywordStmt = ` MATCH (n) WHERE n.name =~ $regex RETURN count(n) ` func SearchAllWithNameLikeKeywoard(keyword string, page, l...
package main import ( "fmt" "regexp" "log" "strings" ) func LongestWord(sen string) string { var longest string reg, err := regexp.Compile("[^a-zA-Z0-9]+") if err != nil { log.Fatal(err) } words := strings.Split(reg.ReplaceAllString(sen, " "), " ") for _, word := range words { if len(longes...
package controllers import ( "encoding/json" "net/http" "net/http/httptest" "strconv" "strings" "testing" "time" "github.com/insisthzr/echo-test/cookbook/twitter/db" "github.com/insisthzr/echo-test/cookbook/twitter/utils" "github.com/labstack/echo" "github.com/stretchr/testify/assert" ) func TestSignup(t...
package nats type NatsCluster struct { ApiVs string `json:"apiVersion"` Kind string `json:"Kind"` Metadata `json:"metadata"` Spec `json:"spec"` } type NatsGetCluster struct { ApiVs string `json:"apiVersion"` Kind string `json:"Kind"` Metadata `json:"metadata"` } type NatsConfig struct { Debu...
package version import ( "fmt" "github.com/spf13/cobra" "github.com/ovh/venom" ) // Cmd version var Cmd = &cobra.Command{ Use: "version", Short: "Display Version of venom: venom version", Long: `venom version`, Aliases: []string{"v"}, Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Ver...
// Copyright 2019 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
package four type DayList struct { days map[string]*Day } func NewDayList() DayList { days := make(map[string]*Day) return DayList{days: days} } func (d DayList) checkAndAppend(date string) *Day { dayPtr, exists := d.days[date] if !exists { day := NewDay() dayPtr = &day d.days[date] = dayPtr } return...
package podstore import ( "testing" "time" podstore_protos "github.com/square/p2/pkg/grpc/podstore/protos" "github.com/square/p2/pkg/grpc/testutil" "github.com/square/p2/pkg/launch" "github.com/square/p2/pkg/manifest" "github.com/square/p2/pkg/store/consul" "github.com/square/p2/pkg/store/consul/consulutil" ...
package main type tableInfo struct { name string columns []*columnInfo } type columnInfo struct { field string typeName string isNull bool key string defaultVal *string extra string }
package neunet2 import ( "io" "net/http" "net/url" "os" "strconv" "strings" ) var Colours = []string{ "FF0000", "FFFF00", "00FF00", "00FFFF", "0000FF", "FF00FF", } type Chart struct { Title string Datasets [][]float32 } func NewChart() (chart *Chart) { ...
package pdexv3 import ( "encoding/json" "incognito-chain/common" metadataCommon "incognito-chain/metadata/common" "incognito-chain/privacy" ) type AddLiquidityRequest struct { poolPairID string // only "" for the first contribution of pool pairHash string otaReceiver string ...
package main import ( _ "./api/" api_ctrl "./api/controllers" "./pkg" pkg_model "./pkg/models" // "./statistics" // stat_model "./statistics/models" "./notify" trans "./transfer" trans_model "./transfer/models" "./transfer/task" "./utils" "./utils/cache" "./utils/db" "fmt" "github.com/astaxie/beego" cl...
package gorasp import ( "errors" "math/bits" ) // struct that will implement the RankSelect interface. type RankSelectFast struct { packedArray []uint64 partialRanks []uint partialSelects []uint32 n int } func (self *RankSelectFast) At(index int) int { if index >= self.n { return 0 // retu...
package main import ( "fmt" "math/rand" "time" log "github.com/sirupsen/logrus" ) var Games = make(map[int]*Game, 0) type Game struct { Id int Players *Players EventsQueue *EventQueue EventsHistory *EventHistory Event IEvent Iteration int Winner int } func NewGame()...
package ethclient import ( "context" "crypto/ecdsa" "fmt" "math/big" "github.com/sirupsen/logrus" hdwallet "github.com/miguelmota/go-ethereum-hdwallet" "github.com/Secured-Finance/dione/config" "github.com/Secured-Finance/dione/contracts/dioneDispute" "github.com/Secured-Finance/dione/contracts/dioneOracl...
package template import ( "github.com/spf13/cobra" ) func NewTemplateCommand() *cobra.Command { var command = &cobra.Command{ Use: "template", Short: "manipulate workflow templates", Run: func(cmd *cobra.Command, args []string) { cmd.HelpFunc()(cmd, args) }, } command.AddCommand(NewGetCommand()) co...
package plugins import ( "time" "github.com/afex/hystrix-go/hystrix/metric_collector" "github.com/prometheus/client_golang/prometheus" ) var promAttempts = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "hystrix_attempts_total", Help: "Hytrix attemps", }, []string{"circuit_name"}, ) var promError...
package main import "fmt" func main() { // map deve ser inicializado !!! mapAprovados := make(map[int]string) //map[key]value mapAprovados[123] = "Maria" mapAprovados[456] = "Pedro" fmt.Println(mapAprovados) fmt.Println("") for cpf, nome := range mapAprovados { fmt.Printf("nome: %s , cpf: %d \n", nome, cp...
package main import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "gorm_project/modules" ) func main() { connStr := "root:Kaka@2019@/gorm_project?charset=utf8&parseTime=True&loc=Local" db, err := gorm.Open("mysql", connStr) if err != nil { panic(err) } defer db.Close() // 增 ...
package kubectl import ( "fmt" "github.com/devspace-cloud/devspace/pkg/devspace/config/versions/latest" "github.com/devspace-cloud/devspace/pkg/util/log" "github.com/ghodss/yaml" "github.com/pkg/errors" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "os/exec" "regexp" "strings" ) // Builder is the manif...
package dictionary import "errors" // Dictionary Type type Dictionary map[string]string var errNotFound = errors.New("Not found") var errWordExist = errors.New("That word already exists") var errWordCantUpdate = errors.New("That word cannot be updated") var errWordCantDelete = errors.New("That word does not exist") ...
package main import ( "fmt" "math/rand" "time" ) const FILEPATH = "inputs/2" const CHECK = 19690720 func part1() int { n, _ := LoadIntoMemory(FILEPATH) // restore 1202 program alarm n[1] = 12 n[2] = 2 return RunIntcode(n, false) } func part2() int { var noun int var verb int rand.Seed(time.Now().Unix()) ...
package main import ( "log" "net" "github.com/jeckbjy/nio" ) func StartClient() { log.Printf("start client") selector, err := nio.New() if err != nil { panic(err) } conn, err := net.Dial("tcp", "localhost:6789") if err != nil { panic(err) } selector.Add(conn, nio.OP_READ, nil) conn.Write([]byte("...
package singleton import "testing" func TestGetInstance(t *testing.T) { firstInstance := GetInstance() if firstInstance.NumberOfCreations() != 1 { t.Error("expected just one number of creations") } secondInstance := GetInstance() if firstInstance != secondInstance { t.Error("expected same instance") } t...
package cmd import ( "fmt" "github.com/twatzl/webdav-downloader/downloader" "log" "os" "strings" "github.com/mitchellh/go-homedir" "github.com/spf13/cobra" "github.com/spf13/viper" ) var cfgFile string var server string var deltaFlags = map[string]string{ downloader.DELTA_FLAG_SIZE: "copy file if size is d...
package assert import ( "fmt" "strings" ) //go:generate go run type_assert.gen.go type Assertion struct { Message string KVs map[string]interface{} } func (a Assertion) String() string { sb := strings.Builder{} sb.WriteString(a.Message) for k, v := range a.KVs { sb.WriteString("\n\t* ") sb.WriteStrin...
package filter import ( "gocherry-api-gateway/components/log_client" "gocherry-api-gateway/proxy/enum" "math/rand" "time" ) /** 记录日志id和记录时间 */ type TraceFilter struct { Filter } func (f *TraceFilter) Init(proxyContext *ProxyContext) { } func (f *TraceFilter) Name(proxyContext *ProxyContext) string { return T...
package config import ( "github.com/robfig/config" ) type Reader struct { config *config.Config } // filepath E.g. ""/etc/someconfig.cfg" func NewReader(filepath string) (reader *Reader, err error) { config, err := config.ReadDefault(filepath) if err != nil { return nil, err } return &Reader{config: config}...
package core import ( "testing" ) func Test_NewBoolean(t *testing.T) { values := []bool{false, true} for _, value := range values { node := NewBoolean(value) if !node.CompareBoolean(value) { t.Error("NewBoolean() failed.") } } } func Test_IsBoolean(t *testing.T) { node := &Type{} if node.IsBoolean()...
package main import "fmt" func main(){ msg:= make(chan int, 4) msg <- 100 msg <- 110 msg <- 120 msg <- 130 p := fmt.Println p(<-msg) p(<-msg) p(<-msg) p(<-msg) }
package main import ( "database/sql" "encoding/json" "flag" "fmt" "log" "net/http" "net/url" "os" _ "github.com/go-sql-driver/mysql" "github.com/gorilla/handlers" "github.com/gorilla/mux" "github.com/pwang347/cs304/server/common" "github.com/pwang347/cs304/server/queries" ) const ( // DefaultServerPort...
package main import ( "fmt" "net/http" "log" "database/sql" _ "github.com/lib/pq" "text/template" ) var ( db *sql.DB createTable = `CREATE TABLE IF NOT EXISTS users( name character varying(100) NOT NULL, email character varying(100) NOT NULL, description character varying(500) NOT NULL );` ) const...
package rest import "fmt" // Exec creates an API Client and uses its // GetGoogle method, then prints the result func Exec() error { c := NewAPIClient("username", "password") StatusCode, err := c.GetGoogle() if err != nil { return err } fmt.Println("Result of GetGoogle:", StatusCode) return nil }
package term import ( "bytes" "fmt" "io" "strconv" "sync" "text/template" "unicode" "unicode/utf8" "github.com/k0kubun/go-ansi" ) type attribute int type icon struct { color attribute char string } const ( fGBold attribute = 1 fGFaint attribute = 2 fGItalic attribute = 3 fGUnderline att...
package main const ( inf = 1000000000 ) func updateMatrix(matrix [][]int) [][]int { if len(matrix) == 0 { return matrix } m, n := len(matrix), len(matrix[0]) // 先把"1"赋值为inf,表示"1"到"0"的距离此时为无穷大 for i := 0; i < m; i++ { for t := 0; t < n; t++ { if matrix[i][t] == 1 { matrix[i][t] = inf } } } // 从...
package grant import ( "net/http" "time" "github.com/lyokato/goidc/bridge" "github.com/lyokato/goidc/log" oer "github.com/lyokato/goidc/oauth_error" "github.com/lyokato/goidc/scope" ) const TypeRefreshToken = "refresh_token" func RefreshToken() *GrantHandler { return &GrantHandler{ TypeRefreshToken, func...
package heuristics func linearConflicts(grid []int, size int, depth int) float32 { conflicts := 0 for x1 := 0; x1 < size; x1++ { for y1 := 0; y1 < size-1; y1++ { if grid[get1d(x1, y1, size)] != 0 { tmp := finalPos[grid[get1d(x1, y1, size)]] targetx, targety := tmp[0], tmp[1] if (x1 == targetx) != (y...
package log_test import ( "bytes" "regexp" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "opendev.org/airship/airshipctl/pkg/log" ) var logFormatRegex = regexp.MustCompile(`^\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2} .*`) const prefixLength = len("2001/02/03 16:05:06 ") func ...
package quic import ( "gx/ipfs/QmU44KWVkSHno7sNDTeUcL4FBgxgoidkFuTUyTXWJPXXFJ/quic-go/internal/protocol" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Buffer Pool", func() { It("returns buffers of cap", func() { buf := *getPacketBuffer() Expect(buf).To(HaveCap(int(protocol.MaxRece...
package object import ( "hash/fnv" ) const ( STRING_OBJ = "STRING" ) type String struct { Value string } func (s *String) Type() Type { return STRING_OBJ } func (s *String) Inspect() string { return s.Value } func (s *String) MapKey() MapKey { h := fnv.New64a() _, _ = h.Write([]byte(s.Value)) mk := MapKe...
// Way to try to enqueue a Job and report back if queue is full and its rejected to add new Job func TryEnqueue(job Job, jobChan <-chan Job) bool { select { case jobChan <- job: return true default: return false } } // Usage if !TryEnqueue(job, chan) { http.Error(w, "max capacity re...
package conf import "strings" const ( // ShortVersion 短版本号 ShortVersion = "droneDeploy 0.0.1" ) // The value of variables come form `gb build -ldflags '-X "build.Build=xxxxx" -X "build.CommitID=xxxx"' ` var ( // Build build time Build string // Branch current git branch Branch string // Commit git commit id ...
// A basic HTTP server. // By default, it serves the current working directory on port 8080. package main import ( "math/rand" "sort" "strings" "time" ) type slice struct { sort.IntSlice solutions [][]string } func (s slice) Swap(i, j int) { s.IntSlice.Swap(i, j) s.solutions[i], s.solutions[j] = s.solutions[...
package date import "time" func GetCurrentDateTime() string { return time.Now().Format("2006-01-02 15:04:05") } func GetCurrentDate() string { return time.Now().Format("2006-01-02") } func ParseDateTime(dateTime string) (time.Time, error) { return time.ParseInLocation("2006-01-02 15:04:05", dateTime, time.Local...
package quiz import ( "testing" ) func Test_BalanceOf(t *testing.T) { p := NewPCM() p.BalanceOf("0x03CDD0B4878BA94BF8bFadD6c2C2241759Fd158A") if PrintLog { t.Fail() } }
package main import "fmt" func main() { // 位运算 fmt.Println(2 & 3) // 2 fmt.Println(2 | 3) // 3 fmt.Println(2 ^ 3) // 1 }
package dcp import ( "reflect" "testing" ) func Test_insertManyQuery(t *testing.T) { type args struct { input []string query string } tests := []struct { name string args args want []string }{ {"0", args{input: []string{}, query: "e"}, []string{}}, {"1", args{input: []string{" dog", " deer ", "d...
package main import ( "fmt" "log" "os" "strconv" "../chord" ) func main() { //hostName := chord.GetOutboundIP() + ":" + "5678" //hostName := "farm01" //portNumber := 5678 kpubs := chord.GetKpubString(os.Args[2]) portNumber, err := strconv.Atoi(os.Args[1]) if err != nil { log.Fatal("invalid portNumber"...
package main import ( "fmt" "github.com/teploff/otus/hw_4/list" ) func main() { // Usage example l := list.List{} l.PushFront(0) l.PushBack(1) l.PushFront(2) l.PushBack(3) l.Remove(l.Last()) l.Remove(l.First()) l.Remove(l.Last()) l.Remove(l.First()) fmt.Println(l.Len()) }
package main import ( "context" "encoding/json" "github.com/b2wdigital/goignite/pkg/config" "github.com/b2wdigital/goignite/pkg/health" "github.com/b2wdigital/goignite/pkg/log" "github.com/b2wdigital/goignite/pkg/log/logrus/v1" "github.com/b2wdigital/goignite/pkg/transport/client/redis/v7" ) func main() { c...
package helpers // Yoinked from: // https://leetcode.com/problems/iterator-for-combination/discuss/502469/ type combinationIterator struct { Permutations *[][]int offset int } // CombinationGenerator generates all possible combinations of length 'combinationLength' from int array 'values' func CombinationGen...
package kucoin import "net/http" // A FillModel represents the structure of fill. type FillModel struct { Symbol string `json:"symbol"` TradeId string `json:"tradeId"` OrderId string `json:"orderId"` CounterOrderId string `json:"counterOrderId"` Side string `json:"side"` Liquidit...
package bzr import ( "context" "testing" "github.com/gobuffalo/plugins" "github.com/stretchr/testify/require" ) func Test_Bzr_Generalities(t *testing.T) { r := require.New(t) b := Versioner{} r.Equal("bzr", b.PluginName(), "Name should be bzr") r.Equal("Provides bzr related hooks to Buffalo applications.", ...
package boilingcore import ( "sort" "testing" "text/template" ) func TestTemplateNameListSort(t *testing.T) { t.Parallel() templs := templateNameList{ "bob.tpl", "all.tpl", "struct.tpl", "ttt.tpl", } expected := []string{"bob.tpl", "all.tpl", "struct.tpl", "ttt.tpl"} for i, v := range templs { if...
package serial import ( "fmt" "io" "log" "github.com/EdlinOrg/prominentcolor" "github.com/jacobsa/go-serial/serial" ) type OpenOptions = serial.OpenOptions func Connect(options OpenOptions) io.ReadWriteCloser { connection, err := serial.Open(options) if err != nil { log.Fatalf("serial.Open: %v", err) } ...
// Copyright (c) 2018 KIDTSUNAMI // Author: alex@kidtsunami.com package util import ( "sync" "time" ) // Example // // const format = "15:04:05.999999999Z" // // func main() { // t := util.NewAlignedTicker(5 * time.Second) // fmt.Printf("Start %s\n", time.Now().UTC().Format(format)) // for i := 0; i < 5; i++ { ...
package main import ( "database/sql" "fmt" _ "github.com/lib/pq" "net/http" ) type Book struct { isbn string title string author string price float32 } var db *sql.DB var err error func main() { db, err = sql.Open("postgres", "postgres://aman:password@localhost/test1?sslmode=disable") if err != nil { ...
package main import "fmt" func main() { // ตัวแปร x เก็บข้อมูลไว้ในอาร์เรย์ 5 หน่วย var x [5]int // กำหนดให้สมาชิกลำดับที่ 5 ของอาร์เรย์ x เป็น 100 x[4] = 100 fmt.Println(x) // test() } func test() { // สร้างอาร์เรย์ความยาว 5 หน่วย แล้วกำหนดค่าของสมาชิกแต่ละตัว var y [5]float64 y[0] = 98 y[1] = 93 y[2] =...
package links import ( "testing" ) type entry struct { srcAddress string srcDisplay string srcHypha string kind LinkType href string display string } func TestLink(t *testing.T) { // address — display — srchypha mappings := []entry{ {"apple", "", "home", LinkLocalHypha, "/hypha/apple", "apple"...
package main import ( "fmt" "testing" ) func (e Constant) eq(e2 Constant) bool { return e.cType == e2.cType && e.cValue == e2.cValue } func compareIndexExpression(e1, e2 Expression) (bool, string) { if e1.isDirectlyAccessed() != e2.isDirectlyAccessed() { return false, "Only one expression is accessed with inde...
// Copyright ©2019 The Gonum Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package product import ( "sort" "gonum.org/v1/gonum/graph" "gonum.org/v1/gonum/graph/internal/ordered" "gonum.org/v1/gonum/stat/combin" ) // Node is ...