text
stringlengths
11
4.05M
package hashmap_shards import ( "fmt" "time" ) func (impl implementation) HSetWithExpiration(key, field string, value interface{}, ttl time.Duration) error { keyShards := fmt.Sprintf("%s-%d", key, impl.hash(field)) return impl.redis.HSetWithExpiration(keyShards, field, value, ttl) } func (impl implementation) HS...
package upstream_notify import ( "context" "encoding/json" "errors" "fmt" "github.com/shopspring/decimal" "tpay_backend/model" "tpay_backend/payapi/internal/logic" "tpay_backend/upstream" "github.com/tal-tech/go-zero/core/logx" "tpay_backend/payapi/internal/svc" ) type GoldPaysTransferLogic struct { logx....
package main import ( SL "golang_Learn/ptslowlog/slowlog" "fmt" ) func main(){ //SL.SlowLogForMart("/home/jiemin/code/go_dev/src/golang_Learn/ptslowlog/conf/conf.yaml") slowlogStr:=SL.SlowLogForMart("/home/jiemin/code/go_dev/src/golang_Learn/ptslowlog/conf/conf.yaml") fmt.Println(slowlogStr) }
package zconfig import ( "bufio" "errors" "fmt" "os" "strconv" "strings" ) func (c *Configer) parse(f *os.File) error { // line := 0 s := bufio.NewScanner(f) for s.Scan() { line = line + 1 content := strings.TrimSpace(s.Text()) if len(content) == 0 { continue } // comment if commentIndex := s...
/* * Copyright © 2020-2022 Software AG, Darmstadt, Germany and/or its licensors * * SPDX-License-Identifier: Apache-2.0 * * 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://...
// // Copyright (c) 2017, Stardog Union. <http://stardog.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required b...
package main import ( "github.com/eiannone/keyboard" ) type Keypress struct { ch rune key keyboard.Key } func keyboardChannel() (<-chan Keypress /*, func ()*/) { kch := make(chan Keypress) go func() { var err error err = keyboard.Open() if err == nil { for { ch, key, err := keybo...
package cli import ( "fmt" "strconv" rpcclient "github.com/raedahgroup/dcrcli/walletrpcclient" qrcode "github.com/skip2/go-qrcode" ) func balance(walletrpcclient *rpcclient.Client, commandArgs []string) (*response, error) { balances, err := walletrpcclient.Balance() if err != nil { return nil, err } res :...
package gobchest import ( "encoding/gob" "fmt" "io/ioutil" "math/rand" "os" "path/filepath" "testing" "time" ) func randomFilePath() string { return filepath.Join(os.TempDir(), "golang-gobchest-test-file-"+fmt.Sprintf("%d", rand.Uint32())) } func randomAddr() string { return fmt.Sprintf("localhost:%d", 200...
package main import ( "github.com/jinzhu/gorm" ) type PendingUnlocksRepository struct { db *gorm.DB } func NewPendingUnlocksRepository(db *gorm.DB) *PendingUnlocksRepository { return &PendingUnlocksRepository{db: db} } func (repo *PendingUnlocksRepository) Get(slackUserId string) (*PendingUnlock, error) { pendi...
package models import "gopkg.in/mgo.v2/bson" // Represents a video, we uses bson keyword to tell the mgo driver how to name // the properties in mongodb document type Video struct { ID bson.ObjectId `bson:"_id" json:"id"` User_ID int `bson:"user_id" json:"user_id"` Category_ID string ...
package web import ( "net/http" ) // HandlerFunc is a http.HandlerFunc variant that returns error type HandlerFunc func(w http.ResponseWriter, r *http.Request) error // Handler is a http.Handler implementation that handles HandlerFunc type Handler struct { H HandlerFunc } func (h Handler) ServeHTTP(w http.Respons...
package login import ( "net/http" "github.com/gin-gonic/gin" "github.com/charlesfan/go-api/service/rsi" "github.com/charlesfan/go-api/utils/log" ) func EmailLogin(c *gin.Context) { //Implement: Use backend service s := rsi.LoginService b := c.MustGet("info").(rsi.EmailLoginBody) if err := s.EmailChecking(&...
package chapter4 import "fmt" //不像Java与.Net,Go为程序员提供了控制数据结构的指针的能力 //但不能进行指针运算,通过给予程序员基本内存布局,Go语言允许控制 //特定集合的数据结构,分配的数量以及内存访问模式 // //每个内存块(或字)有一个地址,通常使用十六进制数表示 // //Go语言的取地址符是& 放到一个变量前使用就会返回相应变量的内存地址 // func TestPointerPrint(){ a := 5 fmt.Printf("Int: %d, Ptr: %v\n",a,&a) //这个地址可以存储在一个叫做指针的特殊数据类型中,在本例中这是一个指向int的指针...
package main import ( "fmt" "sync" ) type rect struct { length int width int } func (r rect) area(group *sync.WaitGroup) { defer group.Done() if r.length < 0 { fmt.Printf("rect %v's length should be greater than zero\n", r) return } if r.width < 0 { fmt.Printf("rect %v's width should be greater than ...
// Copyright 2016 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...
// SPDX-License-Identifier: Unlicense OR MIT package headless import ( "image" "image/color" "testing" "github.com/gop9/olt/gio/f32" "github.com/gop9/olt/gio/op" "github.com/gop9/olt/gio/op/paint" ) func TestHeadless(t *testing.T) { sz := image.Point{X: 800, Y: 600} w, err := NewWindow(sz.X, sz.Y) if err !...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-10-14 09:00 # @File : lt_81_Search_in_Rotated_Sorted_Array_II.go # @Description : # @Attention : */ package array import ( "fmt" "testing" ) func Test_search(t *testing.T) { a := []int{5,1,3} target := 3 b := search(a, target) fmt.Println(b) }
package fastpbkdf2 /* #cgo CFLAGS: -std=c99 -O3 #cgo LDFLAGS: -lcrypto #include "fastpbkdf2.h" */ import "C" import ( "bytes" "crypto/sha1" "crypto/sha256" "crypto/sha512" "fmt" "hash" "unsafe" ) // go doesn't appear to make this easy :( // we compare hashes of the empty string func sameHash(a, b func() hash....
package main import ( "fmt" "runtime" ) /* Concurrency VS Parallelism Concurrency is an architecture. Basically a way of programming to support parallelism Parallelism is when multiple programs are running parallely So if there are multiple CPUs(or cores), A Concurrent program will achieve parallelism but if ...
package main import ( "errors" "fmt" "io/ioutil" "os/exec" "gopkg.in/yaml.v2" ) // Creates a gopack.yml example file func genFile() { out, _ := exec.Command("go", "version").Output() outString := string(out[13:17]) testfile := goPack{ GoVersion: outString} err := saveFile(testfile) check(err, "Failed t...
package fuzztime import "time" // FuzzTime is a very simple fuzzing function func FuzzTime(data []byte) int { _, err := time.ParseDuration(string(data)) if err != nil { return 1 } return 0 }
package main import ( "crypto/sha256" "encoding/base64" "fmt" "github.com/gin-gonic/gin" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" ) func InitDb() *gorm.DB { var err error db, err := gorm.Open("postgres", "host=127.0.0.1 user=postgres dbname=profileapi sslmode=disable password=pro...
package main import ( "fmt" //"strconv" ) func main() { n := 37 k := 3 mask := ^(1 << uint(k-1)) n &= mask fmt.Println(n) }
package sdkconnector import ( "path/filepath" "strings" "github.com/hyperledger/fabric-sdk-go/pkg/core/config" "github.com/hyperledger/fabric-sdk-go/pkg/fabsdk" ) //CreateSDKInstance creates SDK instance for given organization. func CreateSDKInstance(orgName string) (*fabsdk.FabricSDK, error) { configpath := fi...
// netconfs project main.go package main func main() { local := new(NetConfSData) local.Init() netConfInit(&local.config) }
package awsclient import ( "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3" ) type media struct { cmsId string pHash string createdAt string } func TestS3Client_Success(t *testing.T) { dummyFiles := map[string]interface{}{ "avod/mediaId-0": struct{ cmsId string }{"A"...
package gui import ( "github.com/andlabs/ui" ) func addTasksInput() { /* window groupcontainer formgroup radiogroup o o o buttonscontainer buttons */ window := ui.NewWindow("supatc - Add Tasks", 300, 600, false) window.SetMargined(true) window.OnClosing(func(*ui.Window) bool { ...
// +build test package db import ( "re/db/client" "re/db/form" "gorm.io/gorm" ) var db = client.DB /* 初始化业务数据用于演示 标记说明: <*> 表示对外(对运营)暴露,否则是中间变量 (1) 圆括号后面接因子的操作符函数 三个域: 下订单(事件初始域) 顾客ID(用户) 商家ID(用户) <*>消费金额 (1) 和上一次消费金额相同 购买物品ID(商品) 用户域 ID <*>信用分 (2) 高于百分之 {} 的用户 <*>本月消费金额列表 (3) 平均...
package driver import ( "context" "go.mongodb.org/mongo-driver/bson" "github.com/5xxxx/pie/schemas" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) type Client interface { // FindPagination find FindPagination(page, count int64, ...
package models import ( "strings" "github.com/jmoiron/sqlx" ) func chanteyQuery(db *sqlx.DB, sql, searchString string) ([]Chantey, error) { result := []Chantey{} err := db.Select(&result, sql, searchString) return result, err } // ChanteyByID returns a list of chanteys that have IDs like the search term. func ...
package main import ( "fmt" "math/rand" "reflect" "time" "github.com/nervelife/learning-golang/src/app/data" "github.com/nervelife/learning-golang/src/app/server" ) func main() { fmt.Println("Hello World!") main2() main3() main4() fmt.Println(getFourNumbers()) main5() server.Run() } func main2() { va...
package ice import "errors" var ( errCheckRetry = errors.New("retry again") errTriedTooManyTimes = errors.New("have tried too many times") errInvalidStunMessage = errors.New("Invalid STUN message") errStunInvalidLength = errors.New("Invalid STUN message length") errStunUnknownType = errors.New("Inva...
package banner import ( "fmt" "github.com/iotaledger/hive.go/node" ) // PluginName is the name of the banner plugin. const PluginName = "Banner" const ( // AppVersion version number AppVersion = "v0.1.0" // AppName app code name AppName = "Wasp" ) func Init() *node.Plugin { return node.NewPlugin(PluginName...
package limit_ip import ( "fmt" "strconv" "sync" "sync/atomic" "testing" ) func TestLimitIp_IsInvalid(t *testing.T) { limitIp := &LimitIp{} var res int64 = 0 var wg sync.WaitGroup for i := 0; i < 1000; i ++ { if i == 3 { //time.Sleep(time.Second * 11) } //time.Sleep(time.Second) for j := 0; j < 1...
package api import ( "time" "testing" "github.com/stretchr/testify/assert" ) func TestImports(t *testing.T) { if assert.Equal(t, 1, 1) != true { t.Error("Something is wrong.") } } func TestNewConfig(t *testing.T) { settings := map[string]string{ "client_id": "consumerkey", ...
package tracker type TicketComments []TicketComment type TicketComment map[string]interface{} // Return last comment func (t TicketComments) GetLast() TicketComment { countComments := len(t) if countComments == 0 { return TicketComment{} } return t[len(t)-1] } // Get comment author func (t TicketComment) Crea...
package interactive import "io" // shell implements the ReadWriter interface. type shell struct { io.Reader io.Writer } func (s *shell) read(data []byte) (n int, err error) { return s.Read(data) } func (s *shell) write(data []byte) (n int, err error) { return s.Write(data) }
package models import ( "fmt" "math/rand" "sort" "github.com/mrap/stringutil" wordpatterns "github.com/mrap/wordpatterns" ) const ( MinCombosCount = 0 MinMaxComboLen = 2 MinMinComboLen = 2 ) // TODO: Might provide other languages/wordlists in the future. // We would need to store lookups/wordmaps in a...
package utils import ( "sync" "time" ) //go-message-queue消息队列 type Queue struct { size int queue []Message sync.RWMutex } type Message struct { Id string Name string Time time.Time Message string } func (this *Queue) Push(s Message) { this.Lock() defer this.Unlock() this.queue = append(this....
package main import "fmt" func main() { var x int var y float64 fmt.Scanf("%f", &y) x = int(y) fmt.Printf("%d\n", x) }
package transmitter import ( "container/heap" ) // webhookHeap is a heap that will always give you // a webhook that has either expired or is closest to its expiry. // // To be more accurate, it returns the oldest webhook. // // This struct will never modify a webhook, so you need to do this yourself. type webhookHe...
package main import ( "fmt" "net/rpc" ) type General struct { Nombre string Materia string Calificacion float64 } func client() { c, err := rpc.Dial("tcp", "127.0.0.1:9999") if err != nil { fmt.Println(err) return } var op int64 for { fmt.Println("---------------MENU-----------------") fmt.Println(...
package server import ( "context" "crypto/rsa" "crypto/tls" "crypto/x509" "encoding/json" "io" "io/ioutil" "log" "net/http" "net/url" "os" "path/filepath" "strconv" "strings" "time" "github.com/crewjam/saml" "github.com/crewjam/saml/samlsp" "github.com/dimfeld/httptreemux" "github.com/gofrs/uuid" ...
package function func Abs(x int) int { if x < 0 { x *= -1 } return x }
package main import ( // "learn2/condition" // "learn2/for" // "learn2/switch" "learn2/exercise" ) func main() { /* condition.TestIf() condition.TestIfelse() condition.Test() */ /* forDemo.TestFor1() forDemo.TestFor2() forDemo.TestFor3() forDemo.TestFor4() forDemo.TestFor5() forDemo.TestFor6...
package main import "fmt" func main() { x := 42 fmt.Println("a - ", x) fmt.Println("a's memory address - ", &x) } // a - 42 // a's memory address - 0xc00010c000
package raftor // Notifier notifies the receiver of the cluster change. type Notifier interface { // Notify returns a read-only channel of ClusterChangeEvents which can be read when a node joins, leaves or is updated in the cluster. Notify(ClusterChangeEvent) }
package matchers import "bytes" func Mp3(in []byte) bool { return bytes.HasPrefix(in, []byte("\x49\x44\x33")) } // TODO func Flac(in []byte) bool { return false } func Midi(in []byte) bool { return false } func Ape(in []byte) bool { return false } func MusePack(in []byte) bool { return false } func Wav(in [...
package main import ( "fmt" "github.com/gin-gonic/gin" "github.com/rdooley/dogs/dogs" "net/http" ) type DogReq struct { ID int `uri:"id" binding:"required"` } type NewDogReq struct { Name string `json:"name" binding:"required"` Owner string `json:"owner" binding:"required"` Details string `json:"details...
/* Copyright 2022 The KubeVela 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, softw...
package sfen import ( "fmt" "io" "strings" "unicode" ) type posParser struct { r io.RuneScanner } func newPosParser(s string) *posParser { return &posParser{ r: strings.NewReader(s), } } func (p *posParser) read() (rune, error) { r, _, err := p.r.ReadRune() return r, err } var sfenPieceBW = sfenPiece + ...
package message import ( "fmt" "html/template" "net/http" "github.com/gin-gonic/gin" "github.com/pkg/errors" "github.com/totalsynthesis/autoromance/lib/schedule" ) //go:generate go-bindata -pkg $GOPACKAGE view.html var tmpl = map[string]*template.Template{} var page_data = struct { FormEndpoint string Cu...
package loadbalancer import ( "errors" "github.com/Highway-Project/highway/pkg/service" "github.com/Highway-Project/highway/pkg/service/random" ) var loadBalancerConstructors map[string]func() (service.LoadBalancer, error) func init() { loadBalancerConstructors = make(map[string]func() (service.LoadBalancer, err...
package stack import ( "fmt" ) // Stack ,,, type Stack struct { top *component capacity int length int } // Push ... func (s *Stack) Push(data interface{}) error { if s.capacity <= s.length { return &stackOverflowError{} } s.top = &component{ data: data, next: s.top, } s.length++ return nil...
package main import ( "fmt" "html" "net/http" "github.com/gorilla/mux" ) func Index(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) } func TodoIndex(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json;charset=UTF-8") ...
package types import ( "grm-service/common" ) const ( DataCreated = "created" DataSubscribed = "subscribed" DataShared = "shared" ClassMarket = "market" ClassUeser = "user" ) // 数据类型 type DataType struct { Name string `json:"name" description:"name of datatype"` Label string `...
package main import ( "log" "github.com/ramezanius/crypex/exchange/hitbtc" ) var HitBTC *hitbtc.HitBTC func main() { HitBTC = hitbtc.New() HitBTC.SetStreams(func(response interface{}) { log.Println("HitBTC[Candles] received:", response) }, func(response interface{}) { log.Println("HitBTC[Reports] received...
// Copyright 2020 Ant Group. All rights reserved. // // SPDX-License-Identifier: Apache-2.0 package rule import ( "encoding/hex" "fmt" "io" "os" "path/filepath" "reflect" "github.com/dragonflyoss/image-service/contrib/nydusify/pkg/checker/tool" "github.com/pkg/errors" "github.com/pkg/xattr" "github.com/si...
package apps import ( "fmt" "os" "sort" "text/tabwriter" "time" ) type Formation struct { Type string `json:"type"` Size string `json:"size"` Quantity uint8 `json:"quantity"` } func (app *App) FormationLoad() error { var ( data []Formation formation map[string]Formation ) err := app.Htt...
package main import "testing" func TestEncode(t *testing.T) { tests := []struct { input string output string error string }{ {"aabbbcadddd", "2a3b1c1a4d", ""}, {"aaaaaaaaaa", "10a", ""}, {"ab", "1a1b", ""}, {"aa", "2a", ""}, {"a", "1a", ""}, {"__+", "2_1+", ""}, {"", "", ""}, {"1a", "", "Str...
package main import "fmt" // `MetaOwn` adalah metode yang akan diteken nantinya // umumnya/yang paling dekat digunakan antar // struct yang bermacam2 dg kebutuhan data yang mirip/sama type MetaOwn interface { // mendaftarkan `declared lambda function` sbg kontrak interface MetaOwn GetName() string //dengan return ...
package service import ( "log" "github.com/rudeigerc/broker-gateway/mapper" "github.com/rudeigerc/broker-gateway/model" ) type Trade struct { } func (t Trade) NewTrade(trade *model.Trade) { m := mapper.NewMapper() err := m.Create(trade) if err != nil { log.Printf("[service.order.NewOrder] [ERROR] %s", err) ...
package main import "fmt" func makesquare(nums []int) bool { sums := make([]int, 4) sum := 0 for _, n := range nums { sum += n } if sum % 4 != 0 { return false } sum /= 4 return dfs(nums, 0, sums, sum) } func dfs(nums []int, i int, sums []int, sum int) bool { if i ...
package v1 import ( "context" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/kubernetes" ) type ConfigMapGetter interface { ConfigMap(namespace string) } type ConfigMapInterface interface { Get(ctx context.Context, name string, opts meta...
package unbufferedchannels import ( "sync" ) /*work package is to show how you can use an unbuffered channel to create a pool of goroutines that will perform and control the amount of work that gets done concurrently. This is a better approach than using a buffered channel of some arbitrary static size that acts a...
package main import ( "fmt" "io" "os" "time" "github.com/gin-gonic/gin" "github.com/tuanden0/simple_api/internal/models" ) const ADDR string = ":8000" func main() { // Disable Console Color, you don't need console color when writing the logs to file. gin.DisableConsoleColor() // Logging to a file. f, _ ...
package base import ( "encoding/json" "errors" "fmt" "sort" "strconv" "github.com/bwmarrin/discordgo" ) func (b *Base) GetColor(guild, id string) (int, error) { b.lock.RLock() dat, exists := b.dat[guild] b.lock.RUnlock() if exists { col, exists := dat.UserColors[id] if exists { return col, nil } ...
package data import ( "crypto/md5" "fmt" "time" ) // Event data respresentation type Event struct { ID string User string Domain string Action string Timestamp time.Time } // Hydrate populates event record with additional derived data func (e *Event) Hydrate() { if e.ID == "" { s := fmt....
package rpcd import ( "github.com/Cloud-Foundations/Dominator/dom/herd" "github.com/Cloud-Foundations/Dominator/lib/log" "github.com/Cloud-Foundations/Dominator/lib/srpc" "github.com/Cloud-Foundations/Dominator/lib/srpc/serverutil" ) type rpcType struct { herd *herd.Herd logger log.Logger *serverutil.PerUser...
package controllers import ( "github.com/astaxie/beego" . "hello/models" "fmt" "encoding/json" ) type MyJsonData struct { Name string Age int } type MyController struct { beego.Controller } func (this *MyController) Get() { // this.Ctx.WriteString("hes") myData := &MyJsonData{Name : "name", Age : 100} /...
package main_test import ( "testing" ) func TestCreate(t *testing.T) { testCases := []struct { desc string path string verb string expected int }{ { desc: "Create a new payment", path: "/payments", verb: "POST", expected: 201, /* ## Notes - If your API uses...
package server import ( "strconv" "github.com/Tanibox/tania-core/src/helper/validationhelper" "github.com/Tanibox/tania-core/src/assets/domain" ) func (rv *RequestValidation) ValidateReservoirName(name string) (string, error) { if name == "" { return "", NewRequestValidationError(REQUIRED, "name") } if !val...
package msg_test import ( "OrgTimer/msg" "fmt" "testing" "time" ) func genMsgs(baseTime time.Time, number int) (res msg.MsgList) { for i := 0; i < number; i++ { msg := msg.NewOrgMsg(fmt.Sprintf("title[%v]", i), "", baseTime.Add(time.Hour)) res = append(res, &msg) } return res } func TestMergeTerminal(t *t...
package main import ( database "goql/dao" handlers "goql/handlers" "log" "net/http" ) func main() { database.Connect() http.HandleFunc("/add", handlers.AddUser) // curl -s -D - -H "Content-Type: application/json;charset=utf-8" -X POST http://localhost:8080/json -d '{"bookID": 3232, "bookName": "...
package main import ( "fmt" "sync" "github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter10/atomic" ) func main() { o := atomic.NewOrdinal() m := atomic.NewSafeMap() o.Init(1123) fmt.Println("initial ordinal is:", o.GetOrdinal()) wg := sync.WaitGroup{} for i := 0; i < 10; i++ { wg.Add(...
package main import ( "net" current "github.com/containernetworking/cni/pkg/types/100" "github.com/pkg/errors" ) // getIPs iterates a result and returns all the IP addresses // associated with it func getIPs(r *current.Result) ([]*net.IPNet, error) { var ( ips []*net.IPNet ) if len(r.IPs) < 1 { return nil,...
package pathfileops import ( "errors" "fmt" "io" "math" "os" "path" fp "path/filepath" "strings" "time" ) /* 'filehelper.go' - Contains type 'FileHelper' and related data structures. The 'FileHelper' type provides methods used in managing files and directories. The Source Repository ...
package main import ( "html/template" "io" ) const ( extendSwitchRolesBaseAccountTemplate = ` [{{.TeamName}}] aws_account_id = {{.AccountName}} ` ) const ( extendSwitchRolesTemplate = ` [{{.AccountName}}] source_profile = {{.SourceProfile}} color = {{.Color}} role_arn = arn:aws:iam::{{.AccountId}}:role/{{.Role}...
package model import "time" type RoutingEntry struct { Dest VirtualIp Cost int ExitIp VirtualIp NextHop VirtualIp Ttl int64 IsUpdated bool GcTimer int64 HasExpired bool IsLocal bool } func MakeRoutingEntry(dst VirtualIp, exitIp VirtualIp, nextHop VirtualIp, cost int, isLocal...
package unarchive import ( "bytes" "github.com/alexmullins/zip" "log" "os/exec" "strings" ) func checkForPassword(path,ext string,err error)bool{ switch ext { case ".zip": return checkZip(path,err) case ".rar": return checkRar(path,err) case ".7z": return check7z(path) } return false } func checkZ...
package main import "fmt" // https://leetcode-cn.com/problems/generate-parentheses/ func generateParenthesis(n int) []string { if n == 0 { return []string{} } str := make([]byte, 2*n) var res []string var gen func(left, right int) gen = func(l, r int) { if l == n && r == n { res = append(res, string(st...
package telemetry import ( "fmt" "strings" "github.com/10gen/realm-cli/internal/utils/flags" ) // set of supported telemetry flags const ( FlagMode = "telemetry" FlagModeUsage = `Enable/Disable CLI usage tracking for your current profile (Default value: "on"; Allowed values: "on", "off")` ) // Mode is the...
package main import ( "errors" "fmt" "net/http" "os" "strings" "time" "./models" "github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" "github.com/globalsign/mgo/bson" ) var connection = models.Db() func listBooksEndpoint(c *gin.Context) { book := &models.Book{} var books = []models.Book{} find := c...
package tic import ( "context" "github.com/odom11/playground_micro/api" "golang.org/x/tools/go/ssa/interp/testdata/src/fmt" ) type Tic struct { toc api.TocService; counter int } func New(toc api.TocService) *Tic { return &Tic{toc: toc} } func (t *Tic) Shout(ctx context.Context, req *api.Bounce, rsp *api.Bounc...
package image import ( "api/factory" "api/handler" "context" "encoding/json" "io" "net/http" "os" "path/filepath" "time" "cloud.google.com/go/storage" "github.com/gorilla/mux" ) func Create(response http.ResponseWriter, request *http.Request) { vars := mux.Vars(request) username := vars["username"] typ...
package main import ( "fmt" "io/ioutil" "os" "strings" ) func main() { data, err := ioutil.ReadFile("gameofthrones-1-1.txt") if err != nil { fmt.Println(err) return } fmt.Println(data[0]) fmt.Println(data[1]) data_s := strings.Replace(string(data), "<br>", " ", -1) // 줄바꿈 => 뛰어쓰기로 변경 data_s = string...
package main import ( "fmt" "reflect" ) func setvalue(x interface{}) { //v := reflect.ValueOf(x) // if v.Elem().Kind()==reflect.Int{ // v.Elem().SetInt(365) v := reflect.ValueOf(x).Elem() if v.Kind() == reflect.Int { v.SetInt(365) } } func main() { a := 1 setvalue(&a) fmt.Printf("type:%T,value:%v", a, ...
package keva type bucketCache struct { HitCount uint64 MissCount uint64 maxBucketsCached int usedEntries bucketCacheEntry freeEntries bucketCacheEntry bucketsCached int buckets []bucketCacheEntry trieRoot *bucketCacheTrie } func (c *bucketCache) Clear() { c.bucket...
package models import ( "database/sql" "fmt" "github.com/google/uuid" ) type AvailableInterview struct { ID int `json:"id"` Start string `json:"start"` End string `json:"end"` PositionID int `json:"position"` Address string `json:"address"` Room string `json:"room"` } typ...
/* Challenge For any two non-empty strings A and B, we define the following sequence : F(0) = A F(1) = B F(n) = F(n-1) + F(n-2) Where + denotates the standard string concatenation. The sequence for strings "A" and "B" starts with the following terms: A, B, BA, BAB, BABBA, ... Create a function or program that, when...
package main import "fmt" type person struct { name string age uint add address } type address struct { province string city string } func main() { var p person p = person{name: "josiah", age: 26, add: address{ province: "ss", city: "afds", }} fmt.Print(p) }
package main func FindSumOfEvens(max int) int { sum := 0 current := 0 prev := 0 next := 1 for current < max { current = prev + next prev = next next = current if current%2 == 0 { sum += current } } return sum } func main() { }
package main import ( "github.com/jhabc1314/day/archive_go" "github.com/jhabc1314/day/bufio" "github.com/jhabc1314/day/builtin" "github.com/jhabc1314/day/bytes" "github.com/jhabc1314/day/container" "github.com/jhabc1314/day/crypto/cipher" "github.com/jhabc1314/day/crypto/md5" "github.com/jhabc1314/day/crypto/r...
package smallNet import ( "fmt" "net" "scommon" ) type tcpClientSessionManager struct { _maxSessionCount int _curSessionCount int _netConf NetworkConfig _pktRecvFunc PacketReceivceFunctors _sessionList []*tcpSession // 멀티스레드에서 호출된다 _sessionIndexPool *scommon.Deque } func newClientSessionManager(c...
package main import "fmt" func vals(a int, b int) (int, int) { return a, b } func main() { a, b := vals(3, 5) fmt.Println("return value:", a, b) _, c := vals(7, 11) fmt.Println("return value:", c) }
package main import ( "net/http" // "encoding/json" "log" "github.com/gorilla/mux" "github.com/hendrikhoffmann/smartfblib" ) func main() { router := mux.NewRouter() router.HandleFunc("/switchon", smartfblib.SwitchOn).Methods("GET") router.HandleFunc("/switchoff", smartfblib.SwitchOff).Methods("GET") ...
package main import ( "context" "fmt" "os" "os/signal" "syscall" "github.com/pingcap/log" "github.com/spf13/cobra" "go.uber.org/zap" ) func main() { gCtx := context.Background() ctx, cancel := context.WithCancel(gCtx) defer cancel() sc := make(chan os.Signal, 1) signal.Notify(sc, syscall.SIGHUP, sy...
package rabbitmq import ( "fmt" "queueman/libs/queue/types" "queueman/libs/request" "queueman/libs/statistic" "strings" "time" amqpReconnect "github.com/isayme/go-amqp-reconnect/rabbitmq" log "github.com/sirupsen/logrus" "github.com/streadway/amqp" ) // Dispatcher for Queue func (queue *Queue) Dispatcher(co...
package main import ( "fmt" "log" "net/http" "os" "regexp" "strconv" "sync" ) var wg3 sync.WaitGroup func init() { log.SetFlags(log.Lshortfile) } func main() { start, end := user() spiderEngine1(start, end) } func user() (start, end int) { retry: fmt.Print("起始页 start(>=1) = ") fmt.Scan(&start) fmt.Prin...