text
stringlengths
11
4.05M
package nv4 import ( "context" addr "github.com/filecoin-project/go-address" "github.com/filecoin-project/go-state-types/big" multisig0 "github.com/filecoin-project/specs-actors/actors/builtin/multisig" cid "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" "golang.org/x/xerrors" multisig2 "github....
// Demonstra o uso de funções do pacote "flag" // arataca89@gmail.com // 20210415 // // Referências: // (DONOVAN E KERNIGHAN, 2017) // https://golang.org/pkg/flag/ // https://gobyexample.com/command-line-flags package main import ( "flag" "fmt" ) func main() { // flag.String(name string, value st...
// Copyright 2017 Santhosh Kumar Tekuri. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package jsonschema_test import ( "bytes" "context" "encoding/json" "errors" "io" "net/http" "net/http/httptest" "net/url" "os" "path/filepath"...
package config import ( "crypto/sha256" "encoding/hex" "fmt" "io/ioutil" "os" "reflect" "regexp" "strings" "github.com/mitchellh/mapstructure" "github.com/spf13/cast" "go.uber.org/zap" "gopkg.in/yaml.v2" ) //TODO Rename // WithDefaults interface is the interface for default values type WithDefaults inte...
package main import "fmt" func main() { for i := 1; i <= 15; i++ { if i%15 == 0 { fmt.Println(i, " -- FizzBuzz") } else if i%3 == 0 { fmt.Println(i, " -- FIZZ") } else if i%5 == 0 { fmt.Println(i, " -- BUZZ") } else { fmt.Println(i) } } } // 1 // 2 // 3 -- FIZZ // 4 // 5 -- BUZZ // 6 -- FI...
package reddit import ( "fmt" "funbot/db" "strings" "github.com/turnage/graw/reddit" ) var ( botDB *db.BotDB redditBot reddit.Bot ) func Initialize(db *db.BotDB, agentFileName string) { botDB = db redditBot = SetupBot(agentFileName) } func SetupBot(agentFileName string) reddit.Bot { bot, _ := reddit.N...
package transport import ( "fmt" "log" ) // Auxiliary type holding a logger (for transports) type Logged struct { logger *log.Logger } func (t *Logged) SetLogger(l *log.Logger) error { if l == nil { return fmt.Errorf("nil logger not allowed") } t.logger = l return nil }
package main //Creating a custom type //Declaring a variable of the custom type import "fmt" type question int var x question func main() { fmt.Println(x) fmt.Printf("%T\n", x) x = 42 fmt.Println(x) }
// 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...
package generator import ( "encoding/json" "fmt" "io/ioutil" "os" "path/filepath" "strings" "github.com/michaelawyu/cloudevents-generator/src/generator/nodejs" "github.com/michaelawyu/cloudevents-generator/src/generator/python" "github.com/michaelawyu/cloudevents-generator/src/logger" "github.com/michaela...
package leetcode func RomanToInt(s string) int { res := 0 xm := map[byte]int{ 77: 1000, 68: 500, 67: 100, 76: 50, 88: 10, 86: 5, 73: 1, } for i := len(s) - 1; i >= 0; i-- { if i > 0 && xm[s[i]] > xm[s[i-1]] { res += xm[s[i]] - xm[s[i-1]] i-- continue } res += xm[s[i]] } return res }
/* There are n chocolates, and you are given an array of n numbers where the i-th number Ai is the flavour type of the i-th chocolate. Sebrina wants to eat as many different types of chocolates as possible, but she also has to save at least x number of chocolates for her little brother. Find the maximum possible numb...
package main import ( "fmt" "log" "sync" "sync/atomic" "time" "github.com/coreos/etcd/pkg/idutil" "github.com/coreos/etcd/pkg/wait" "github.com/coreos/etcd/raft" "github.com/coreos/etcd/raft/raftpb" "github.com/hashicorp/memberlist" "github.com/swiftkick-io/xbinary" "golang.org/x/net/context" ) func NewR...
package rorm // import "go.szyhf.org/di-rorm"
// Copyright 2013 The Go Circuit Project // Use of this source code is governed by the license for // The Go Circuit Project, found in the LICENSE file. // // Authors: // 2013 Petar Maymounkov <p@gocircuit.org> package pipe import ( "github.com/gocircuit/runtime/sys" ) func New(u sys.Peer) *Peer { return &Peer{u...
package main; import ( "strconv" "github.com/kataras/iris" "github.com/kataras/iris/context" "github.com/iris-contrib/middleware/cors" ) func server() { // db allblue := Allblue{}; crs := cors.New(cors.Options{ AllowedOrigins: []string{"*"}, AllowCredentials: true, }); // app app := iris.New(); ...
package parsing_test import ( "testing" . "github.com/s2gatev/sqlmorph/ast" ) func TestUpdateParsing(t *testing.T) { runSuccessTests(t, []successTest{ { Query: `UPDATE User u SET u.Name=? WHERE u.Age=21`, Expected: &Update{ Fields: []*Field{ &Field{Target: "u", Name: "Name", Value: "?"}, }, ...
package main import ( "fmt" "github.com/gomodule/redigo/redis" "strconv" ) type Image struct { Id int `json:"id"` ProductId int `json:"product_id,omitempty"` Url string `json:"url"` } func (image *Image) setId(redisConn redis.Conn) { id, _ := redis.Int(redisConn.Do("INCR", config.KeyImageCo...
package owner import ( "github.com/bububa/oppo-omni/core" "github.com/bububa/oppo-omni/model" "github.com/bububa/oppo-omni/model/communal/owner" ) // 客户日预算设置 func SetAccDayBudget(clt *core.SDKClient, ownerID uint64, budget int64) error { var req owner.SetAccDayBudgetRequest req.AccDayBudget = budget req.SetOwne...
package main import ( "encoding/json" "fmt" "io/ioutil" "os" ) type Godep struct { Deps []Dep } type Dep struct { ImportPath string Comment string Rev string } func main() { comment := false args := os.Args[1:] if len(args) == 3 { if args[2] == "comment" { comment = true } else { fmt....
package redis import ( "github.com/plexmediamanager/micro-redis/errors" format "fmt" "github.com/plexmediamanager/service/helpers" "github.com/go-redis/redis/v7" "strings" "time" ) type RedisClient struct { host string port int endpoints []string pas...
package sese import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00900105 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:sese.009.001.05 Document"` Message *RequestForTransferStatusReportV05 `xml:"ReqForTrfStsRpt"` } func (d *D...
package main import "fmt" func main() { var name string var age byte var salary float32 var ispass bool //方式一 // fmt.Println("请输入姓名:") // fmt.Scanln(&name) // fmt.Println("请输入年龄:") // fmt.Scanln(&age) // fmt.Println("请输入薪水:") // fmt.Scanln(&salary) // fmt.Println("是否通过考试:") // fmt.Scanln(&ispass) // fmt...
package main import ( "fmt" "reflect" "github.com/google/go-cmp/cmp" "github.com/mitchellh/hashstructure" ) type A struct { S string } type B struct { Arr []*A } func main() { a := &B{[]*A{&A{"a"}}} b := &B{[]*A{&A{"a"}}} fmt.Println(a, b) fmt.Printf("a==b: %+v\n", a == b) fmt.Printf("reflect.DeepEqual...
package main import "testing" func TestMain(t *testing.T) { // Use this to test CI/CD failing // If tests fail if false { t.Errorf("Something went wrong!") } }
package cmds import ( "encoding/json" "fmt" "io" "reflect" "sync" "gx/ipfs/Qmf7G7FikwUsm48Jm4Yw4VBGNZuyRaAMzpWDJcW8V71uV2/go-ipfs-cmdkit" ) func NewWriterResponseEmitter(w io.WriteCloser, req Request, enc func(Request) func(io.Writer) Encoder) *WriterResponseEmitter { re := &WriterResponseEmitter{ w: w, ...
package server import ( "fmt" "net/http" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" log "github.com/sirupsen/logrus" "github.com/bpmericle/go-webservice/internal/handlers" "github.com/bpmericle/go-webservice/internal/logger" ) // Server represents the web server hosting the service type Serve...
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved. // // This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, // You can obtain one at https://github.com/gogf/gf. // Package gview implements a template engine based on t...
package gostream import ( "bufio" "bytes" "context" "encoding/binary" "encoding/json" "errors" "fmt" "image" "io" "math" "net/http" "strings" "sync" "time" "github.com/trevor403/gostream/codec" ourwebrtc "github.com/trevor403/gostream/webrtc" "go.uber.org/multierr" "github.com/edaniels/golog" "git...
// Logger is a simple logging interface. package whookie import ( "io" "log" "log/syslog" "os" ) var logger Logger func init() { logger = Logger{} flags := log.LstdFlags if os.Getenv("LOG_OUTPUT") == "syslog" { logger.info, _ = syslog.NewLogger(syslog.LOG_INFO, flags) logger.notice, _ = syslog.NewLogger(s...
package leetcode type stack []rune func (s *stack) Push(r rune) { *s = append(*s, r) } func (s *stack) Pop() (rune, bool) { if n := len(*s); n > 0 { r := (*s)[n-1] *s = (*s)[:n-1] return r, true } return 0, false } func isValidParentheses(s string) bool { st := make(stack, 0, len(s)) for _, c := range s...
package diff import ( "bytes" "fmt" "os" "got/internal/objects" "github.com/gookit/color" ) type Differ interface { DiffBytes(a []byte, b []byte) BytesDiff FilesDiff(a []byte, b []byte) bool DiffFiles(a []byte, b []byte) (FileEditType, error) } type FileDiff struct { EditType FileEditType SrcPerm os.Fil...
// Copyright 2018 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...
// Copyright 2023 PingCAP, Inc. Licensed under Apache-2.0. package show_test import ( "bytes" "context" "embed" "fmt" "io" "io/fs" "os" "path" "strconv" "strings" "testing" "github.com/pingcap/errors" backuppb "github.com/pingcap/kvproto/pkg/brpb" "github.com/pingcap/kvproto/pkg/encryptionpb" "github....
package structType import ( "fmt" ) type point struct{ x int y int } func Run(){ p1 := point{x:1,y:2} p1pointer := &p1 p1.x = 3 p1pointer.y=4 fmt.Println(p1) fmt.Println(p1pointer) p2 := point{x:6} fmt.Println(p2) p3 := point{} fmt.Println(...
package grpc import ( "context" "errors" "google.golang.org/grpc" "google.golang.org/grpc/connectivity" ) type ClientConnChecker struct { conn *grpc.ClientConn } func (c *ClientConnChecker) Check(ctx context.Context) error { var err error if c.conn.GetState() != connectivity.Ready { err = errors.New("not...
package lib import ( _ "embed" "encoding/json" "errors" "log" "math/rand" "regexp" "sort" "strings" "sync" "time" pb "github.com/micro/services/wordle/proto" ) //go:embed words.txt var wordLib string //go:embed all.txt var allWordLib string var wordArr []string var allWordArr []string var rounds = 6 f...
// Exercise: Readers. package main import "golang.org/x/tour/reader" type MyReader struct{} // TODO: Add a Read([]byte) (int, error) method to MyReader. func (mr MyReader) Read(b []byte) (int, error) { if len(b) < 1 { return 0, nil } b[0] = 'A' return 1, nil } func main() { reader.Validate(MyReader{}) }
package config type Config struct { Datatable struct{ Host string `json:"host"` Post int `json:"port"` Name string `json:"name"` User string `json:"user"` Password string `json:"password"` } `json:"database"` }
package zuul import ( "github.com/example-inc/zuul-operator/cmd/manager/tools/utils" cachev1alpha1 "github.com/example-inc/zuul-operator/pkg/apis/cache/v1alpha1" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func generatezuulexecutorVolumeMounts() []corev...
package oauth2 import ( "context" "crypto/rsa" "errors" oauthError "github.com/tsingsun/go-oauth2/errors" "math/rand" "strings" "time" ) type GrantType string const ( AuthCodeGrantType GrantType = "authorization_code" ClientCredentialGrantType GrantType = "client_credentials" ImplicitGrantType ...
package main import "fmt" func main(){ var i string fmt.Println("Enter a string") fmt.Scanln(&i) fmt.Println(i) }
package router import ( "fmt" "net/http" "strings" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/go-chi/cors" "github.com/opentracing/opentracing-go" zipkin "github.com/openzipkin/zipkin-go" ) // NewServeMux creates a new TracedServeMux. func NewRouter() *chi.Mux { r := chi.NewRoute...
package metadata import ( "fmt" "gorm.io/gorm/clause" "time" "github.com/pilagod/gorm-cursor-paginator/v2/paginator" "gorm.io/gorm" "github.com/root-gg/plik/server/common" ) // CreateUpload create a new upload in DB func (b *Backend) CreateUpload(upload *common.Upload) (err error) { return b.db.Create(upload...
package ll2 // use single linked list type MyLinkedList struct { len int head *Node } type Node struct { data int next *Node } /** Initialize your data structure here. */ func Constructor() MyLinkedList { return MyLinkedList{} } /** Get the value of the index-th node in the linked list. If the index is invali...
package bean import ( "log" "testing" "fmt" ) func Test_Leardboard(t *testing.T){ DefaultORM() //ClearArenaLeaderboard() WriteInDDB() //ArenaLeaBoardLoadAndSort() //log.Println("获得9000的排名:", GetRank(9000)) //getInfoList := GetArenaLeaderboard(0,50) //for _, item := range getInfoList{ // log.Println("获取指定排名...
package controller import ( "net/http" "os" "io/ioutil" "encoding/json" "ksd/service" "fmt" ) func DeployAction(w http.ResponseWriter, r *http.Request) { if "POST" != r.Method { setHttpStatus(w, http.StatusMethodNotAllowed) return } token := r.URL.Query().Get("token") if !isTokenValid(token) { setHtt...
package room import ( "io" "os" "fmt" "errors" "crypto/md5" "encoding/binary" "libs/log" ) const ( SAVE_DIR="/data/gomm" ) var ( ByteOrder = binary.LittleEndian ) type FileSaver struct {} const ( Md5_String_Len = 32 ) func createSaveDir() error{ err := os.MkdirAll(SAVE_DI...
package main import "fmt" func main() { // 第一种方式 var a map[string]string a = make(map[string]string, 10) a["n.3"] = "CCC" a["n.2"] = "BBB" a["n.1"] = "AAA" fmt.Println(a) // 第二种方式(推荐使用):结构清晰 cities := make(map[string]string) cities["1"] = "beijing" cities["3"] = "tianjing" cities["2"] = "shanghai" fmt.P...
package main import ( "fmt" "log" "os" "sort" "strings" ) func main() { if len(os.Args) < 3 { log.Fatalln("Not enough parameters. Add 2 strings to the parameters!") } firstText := os.Args[1] secondText := os.Args[2] fmt.Printf("Is Anagram? %v\n", anagram(firstText, secondText)) } func anagram(s1, s2 stri...
package web import ( "log" "net/http" "encoding/json" "github.com/go-martini/martini" "github.com/martini-contrib/binding" "github.com/kerinin/hammer/db" ) type Server struct { bind string database db.Partitioning } func NewServer(bind string, database db.Partitioning) *Server { return &Server{bind: bind,...
package trustmanager import ( "fmt" "path/filepath" "strings" "sync" "github.com/docker/notary/passphrase" "github.com/docker/notary/tuf/data" ) const ( rootKeysSubdir = "root_keys" nonRootKeysSubdir = "tuf_keys" privDir = "private" ) // KeyFileStore persists and manages private keys on disk t...
package containers import ( "github.com/exproletariy/pip-services3-containers-examples/app-process-container-example-go/build" cproc "github.com/pip-services3-go/pip-services3-container-go/container" rpcbuild "github.com/pip-services3-go/pip-services3-rpc-go/build" ) type AppExampleContainer struct { cproc.Proces...
package main import ( "sync" "github.com/brutella/hc/characteristic" "github.com/sirupsen/logrus" "github.com/geoffgarside/homekit-hive/pkg/api/v6/hive" ) type thermostat struct { hive *hive.Thermostat ui *hive.Controller logger *logrus.Logger min float64 max float64 step float64 mu sync.M...
package main import ( "github.com/davecgh/go-spew/spew" ) // 25. K 个一组翻转链表 // 给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。 // k 是一个正整数,它的值小于或等于链表的长度。 // 如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。 // 说明: // 你的算法只能使用常数的额外空间。 // 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。 // https://leetcode-cn.com/problems/reverse-nodes-in-k-group/ func main(...
package storage import ( "bytes" "testing" ) func TestEncodeBlock(t *testing.T) { block := bytes.NewReader(encodeRecord("apple", "APPL")) key, value, _ := decodeBlock(block) if key != "apple" || value != "APPL" { t.Fatal("Incorrect value fetched", key, value) } block = bytes.NewReader(encodeRecord("coca-col...
package config import ( "fmt" "time" "github.com/ipfs/boxo/ipns" ds "github.com/ipfs/go-datastore" dssync "github.com/ipfs/go-datastore/sync" "github.com/libp2p/go-libp2p-kad-dht/providers" "github.com/libp2p/go-libp2p-kbucket/peerdiversity" record "github.com/libp2p/go-libp2p-record" "github.com/libp2p/go-l...
package main import ( . "github.com/smartystreets/goconvey/convey" "testing" "time" ) func newPerishableInfo(hits int) *PerishableInfo { expiry := time.Now().Add(time.Second * 30) return &PerishableInfo{Hits: hits, Expires: expiry} } // TestPerishable tests all of features of the redis interface. func TestPeris...
package mal import ( "drdgvhbh/discordbot/internal/cli/anime/mal/api/response" "time" "github.com/bwmarrin/discordgo" ) type CreateAnimeProfileEmbeddedOptions struct { AnimeProfile *response.UserProfileResponse } func CreateAnimeProfileEmbedded( options CreateAnimeProfileEmbeddedOptions, ) *discordgo.MessageEm...
package main import ( "time" "fmt" "encoding/json" ) var n1,n2,n3 = 0,1,0 var correctAnswers = 0 var incorrectAnswers = 0 var currentNumber = 0 func fibNumbersCount(count int) []int { var globalArray = make([]int, count) globalArray[0] = 0 globalArray[1] = 1 for i := 2; i < count; i++ { globalArray[i] =...
package main import ( "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go/aws/session" "github.com/hill-daniel/iot-protobuf-lambda/dynamo" "github.com/hill-daniel/iot-protobuf-lambda/kinesis" pb "github.com/hill-daniel/iot-protobuf-lambda/proto" ) func main() { sess := session.Must(session.NewSessi...
package beacon // Backend recieves events routed to it by Beacon. type Backend interface { // ProcessEvent instructs the backend to handle an event. This is called in // the main event processing loop and so should not block. If ProcessEvent // panics it will fail through the Beacon Run function. ProcessEvent(even...
package main import "fmt" func main() { inputString := "codesignal" stringMap := make(map[string]string) str := "abcdefghijklmnopqrstuvwxyz" revstr := "" for i := len(str) - 1; i >= 0; i-- { revstr += string(str[i]) } for i := 0; i < len(str); i++ { stringMap[string(str[i])] = string(revstr[i]) } f...
// https://tiancaiamao.gitbooks.io/go-internals/content/zh/03.4.html package main import ( "fmt" ) func f1() (result int) { defer func() { result++ }() return 0 } // f1 = f2 func f2() (result int) { result = 0 //return语句不是一条原子调用,return xxx 其实是赋值 +ret指令 func() { //defer被插入到return之前执行,也就是 赋返回值 和 ret指令 之间 ...
// 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...
// Copyright 2015 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...
/*- * Copyright (c) 2017, F5 Networks, 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...
package controllers import ( "encoding/json" "tokensky_bg_admin/enums" "tokensky_bg_admin/models" ) // type BorrowOrderContoller struct { BaseController } //Prepare 参考beego官方文档说明 func (c *BorrowOrderContoller) Prepare() { //先执行 c.BaseController.Prepare() //如果一个Controller的多数Action都需要权限控制,则将验证放到Prepare c.check...
package hls import ( "context" "fmt" "time" "github.com/grafov/m3u8" "github.com/shaunschembri/restreamer/pkg/restream/provider" "github.com/shaunschembri/restreamer/pkg/restream/request" ) type Master struct { media *Media playlist *Playlist resolution string maxBandwidth uin...
package htlc import ( "encoding/hex" "fmt" sdk "github.com/irisnet/irishub/types" ) // BeginBlocker handles block beginning logic func BeginBlocker(ctx sdk.Context, k Keeper) (tags sdk.Tags) { ctx = ctx.WithLogger(ctx.Logger().With("handler", "beginBlock").With("module", "iris/htlc")) currentBlockHeight := uin...
package main import ( "encoding/json" "fmt" ) type response struct { Page int `json:"page"` Fruits []string } func main() { resp := &response{ Page: 1, Fruits: []string{"apple", "banana"}, } str, _ := json.Marshal(resp) fmt.Println(string(str)) }
package sql import ( "context" gosql "database/sql" "github.com/lygo/health" ) func New(db *gosql.DB) health.ComponentHealther { return &dbWrapper{ db: db, } } type dbWrapper struct { db *gosql.DB } func (w *dbWrapper) Check(ctx context.Context) health.HealthComponentState { var ( state health.HealthCom...
package pdl import ( "fmt" "github.com/go-xe2/x/os/xstream" ) type FileTypeDef struct { Name string `json:"name"` OrgType *FileDataType `json:"orgType"` } func NewFileTypeDef(name string, orgType *FileDataType) *FileTypeDef { return &FileTypeDef{ Name: name, OrgType: orgType, } } func (p *Fil...
package integration_test import ( "fmt" "io/ioutil" "os/exec" "path/filepath" "strings" "github.com/blang/semver" "github.com/cloudfoundry/libbuildpack/cutlass" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("deploy a HTTP/2 app", func() { var app *cutlass.App var app_name strin...
package main import "fmt" func main() { intChan := make(chan int) boolChan := make(chan bool, 1) go worker(1, intChan, boolChan) select { case <-boolChan: fmt.Println("ha ha ha") default: fmt.Println("he he he") } <-intChan close(intChan) close(boolChan) } func worker(id int, c chan int, ok chan bool) ...
package main import ( "common" "common/clog" "common/rabbit" "common/redismgr" "common/udr" "flag" "reflect" "time" ) const PNAME = "cdrgen" var ( log = clog.GetLogger() rabbitMgr = rabbit.NewRabbitManager() redis = redismgr.GetRedisCluster() ) func main() { isDaemon := flag.Bool("d", false, "...
package main import ( "fmt" "math/rand" ) func ComputerMove(g *Game, colour string, r int) int { options := g.GetAllMoves(r, colour) //fmt.Println("Options", options, "roll", r) if len(options) == 0 { return -2 } if len(options) == 1 { return options[0] } moveScores := make([]float64, len(options)) //us...
package gtime import ( "time" ) /* Create time by millisecond */ func NewTime(inMilli int64) time.Time { return time.Unix(inMilli / 1000, (inMilli % 1000) * int64(time.Millisecond)) } /* Get millisecond of now */ func NowInMilli() int64 { return time.Now().UnixNano() / int64(time.Millisecond) }
package stitch import ( "context" "encoding/json" "fmt" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "net/http" "time" ) // PURPOSE: // The Destination object represents a destination. Destinations are the data warehouses into which Stitch wri...
package gear import ( "encoding/csv" "strings" "github.com/realm/realm-server/items" ) // resolveGearType resolves a given string to an EGearType. func resolveGearType(str string) EGearType { words := strings.Split(str, " ") for _, gear := range gearTypes { for _, word := range words { if len(word) > 0 &&...
package main import ( fifth "github.com/h8gi/fifth/lib" ) func main() { i := fifth.NewInterpreter() i.Repl() }
///////////////////////////////////////////////////////////////////// // arataca89@gmail.com // 20210417 // // func IndexAny(s, chars string) int // // Retorna o índice da primeira ocorrência de qualquer dos caracteres // existentes em chars. // se não houver nenhuma ocorrência retorna -1. // // Fonte: https:...
/* Copyright The Helm 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 di...
package trackingmiddleware import ( "net/http" "github.com/arquivei/foundationkit/request" "github.com/arquivei/foundationkit/trace" ) // New instantiates a new tracking middleware wrapping the @next handler. func New(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.R...
package basic import ( "fmt" "reflect" "unsafe" ) func niladdress() { var m map[int]string var ptr *int var sl []int fmt.Printf("%p\n", m) //0x0 fmt.Printf("%p\n", ptr) //0x0 fmt.Printf("%p\n", sl) //0x0 } func nilNotKey() { nil := 123 fmt.Println(nil) // 123 /* cannot use nil (type int) as type map...
package obs import ( openzipkin "github.com/openzipkin/zipkin-go" zipkinHTTP "github.com/openzipkin/zipkin-go/reporter/http" "github.com/pkg/errors" "go.opencensus.io/exporter/zipkin" "go.opencensus.io/trace" "github.com/krostar/r10k-trigger/internal/pkg/app" ) func initTracer(cfg TracerConfig) (func(), error)...
package mat import ( "github.com/stretchr/testify/assert" "testing" ) // Note how the point x,y,z is scaled by xyz func TestScale(t *testing.T) { scaleTransform := Scale(2, 3, 4) p := NewPoint(-4, 6, 8) p2 := MultiplyByTuple(scaleTransform, p) assert.Equal(t, -8.0, p2.Get(0)) assert.Equal(t, 18.0, p2.Get(1)) ...
// Copyright (c) 2012 The Gocov Authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, pub...
//list 是一个双向链表。该结构具有链表的所有功能。 package main import ( "container/list" "fmt" ) func main() { l := list.New() for i := 0; i < 5; i++ { l.PushBack(i) //l --> 01234 } fmt.Println("直接打印l:", l) for e := l.Front(); e != nil; e = e.Next() { fmt.Println("遍历l", e.Value) } //打印首部元素 fmt.Println(l.Front().Value) /...
package nodecommon import ( "sync" "github.com/fananchong/go-xserver/common" "github.com/fananchong/go-xserver/internal/protocol" "github.com/fananchong/go-xserver/internal/utility" "github.com/gogo/protobuf/proto" ) // DefaultNodeInterfaceImpl : 缺省的节点接口实现 type DefaultNodeInterfaceImpl struct { Info ...
package main import ( "context" "log" "net" "time" "github.com/jackc/pgx/v4/pgxpool" "github.com/uid4oe/microservices-go-grpc/advice/advicedb" "github.com/uid4oe/microservices-go-grpc/advice/advicepb" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org...
package iirepo_contents_test import ( "github.com/reiver/go-iirepo/contents" "testing" ) func TestPath(t *testing.T) { tests := []struct{ RootPath string Expected string }{ { RootPath: "/apple", Expected: "/apple/.ii/contents", }, { RootPath: "/apple/BANANA", Expected: "/apple/BANANA/.ii/c...
package stub import ( "context" "net" "github.com/mingo-chen/wheel-minirpc/core" "github.com/mingo-chen/wheel-minirpc/demo" "github.com/mingo-chen/wheel-minirpc/ext" "github.com/mingo-chen/wheel-minirpc/transport" "google.golang.org/protobuf/proto" ) // RegsiterImpl 后续通过code generate技术自动生成 func RegsiterImpl(c...
package secrets import ( "github.com/10gen/realm-cli/internal/cli" "github.com/10gen/realm-cli/internal/cli/user" "github.com/10gen/realm-cli/internal/terminal" "github.com/10gen/realm-cli/internal/utils/flags" ) // CommandMetaUpdate is the command meta for the `secrets update` command var CommandMetaUpdate = cli...
package main import ( "fmt" "os" "path" "strings" "bazil.org/fuse" "bazil.org/fuse/fs" "github.com/pborman/getopt/v2" ) const VERSION = "1.0" type Opts struct { Type string TraceOpts string TraceFile string Daemonize bool Fake bool NoMtab bool Sloppy bool Verbose bool RawOptions string } var op...
package utils // Uint24 is a replacement for the absent Go uint24 data type. // This data type is little endian. type Uint24 [3]byte // ToUint24 converts number to Uint24. func ToUint24(number uint32) Uint24 { return Uint24{byte(number), byte(number >> 8), byte(number >> 16)} } // FromUint24 converts Uint24 to numb...
package main import ( "flag" "github.com/lwllvyb/gktime2book/ebook" "github.com/lwllvyb/gktime2book/geektime" ) //go run main.go --cellphone=xxxxxxx --password=***** func main() { gk_cellphone := flag.String("cellphone", "0", "a string") gk_password := flag.String("password", ",0", "a string") gk_country := fl...
package main import ( "fmt" "strconv" "github.com/jackytck/projecteuler/tools" ) func catProd(x int, n int) int { var s string for i := 1; i <= n; i++ { s += strconv.Itoa(x * i) } p, _ := strconv.Atoi(s) return p } func solve() int { var largest int for i := 1; i < 10000; i++ { j := 1 for { p := ...
package main import ( "database/sql" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "strconv" "time" _ "github.com/go-sql-driver/mysql" "github.com/labstack/echo" "github.com/labstack/echo/middleware" ) type RegisterData struct { Email string `json:"email"` Password string `json:"password"` Co...
package entity type Order struct { Milk float64 `json:"milk,omitempty"` Skins int32 `json:"skins,omitempty"` } type OrderInput struct { Customer string `json:"customer"` Order Order `json:"order"` }