text
stringlengths
11
4.05M
package caaa import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01600101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.016.001.01 Document"` Message *AcceptorCurrencyConversionRequestV01 `xml:"AccptrCcyConvsReq"` } fu...
package status import "github.com/ant0ine/go-json-rest/rest" // Routes for echo service func Routes() []*rest.Route { return []*rest.Route{ rest.Post("/status", handler), } }
package x import ( "math/rand" "sort" "testing" "time" ) func TestMergeInt(t *testing.T) { l := SortedInt(10) if !sort.IsSorted(int64arr(l)) { t.Errorf("Not sorted: [%v]\n", l) t.FailNow() } for i := 0; i < 50000; i++ { l = mergeInt(l, rand.Int63()) if !sort.IsSorted(int64arr(l)) { t.Errorf("Not so...
package phonenumbers var metadataData = "H4sIAAAAAAAA/+z9e7Cl2XkXBte7z2Wfs093z8yanr7s7unpOd0z0++Zs2fW/dKW1ZoZzcyeliVty5Il9du7+D7RoQhQAcIfgGadgOUQKOOAgRDsJingSEAh7CobAiFKIFxMETsxVzkkhAogYkNSODEEhAsXkFrP86z1vu8++9x6NJawxlXWnN7vbV2f9Vx+z+8Z/Ug1eppdvHXndsOF8WF+/0FstJ3X9x+8rfema9N1domdtY2caOvm9x+8rfbkmpXeh+na+Am2ruE+uaa5kG...
package hud import "time" // Payload is a struct to represent the data to be rendered in the hud. type Payload struct { Body string TimeStamp time.Time }
package engine import ( "context" "encoding/json" "fmt" "io/ioutil" "log" "mime/multipart" "net" "net/http" "os" "path/filepath" "strings" "sync" "time" "orbit.sh/engine/docker" "orbit.sh/engine/gluster" "github.com/gin-gonic/gin" "github.com/hashicorp/raft" "google.golang.org/grpc" "orbit.sh/engi...
package main import ( "context" "fmt" "io/ioutil" "log" "os" "path" "strings" "github.com/google/uuid" "github.com/osbuild/osbuild-composer/internal/cloud/gcp" "github.com/osbuild/osbuild-composer/internal/common" osbuild "github.com/osbuild/osbuild-composer/internal/osbuild1" "github.com/osbuild/osbuild...
package order type SubscribeOrderV2Response struct { Ch string `json:"ch"` Data struct { Symbol string `json:"symbol"` OrderId int64 `json:"orderId"` TradePrice string `json:"tradePrice"` TradeVolume string `json:"tradeVolume"` OrderSide string `json:"orderSide"` OrderType string `json:"orderType"` Agg...
package main import ( "database/sql" "fmt" "time" _ "github.com/go-sql-driver/mysql" "github.com/heartchord/jxonline/gameencoder" "github.com/henrylee2cn/mahonia" "github.com/lxn/walk" dcl "github.com/lxn/walk/declarative" ) // RoleDBData : type RoleDBData struct { ID string Role...
package hasher import ( "crypto/sha256" "encoding/hex" "hash" ) type Hasher struct { Hash hash.Hash } func New() *Hasher { h := new(Hasher) h.Hash = sha256.New() return h } func (self Hasher) HashString(toHash string) string { self.Hash.Write([]byte(toHash)) md := self.Hash.Sum(nil) mdStr := hex.EncodeToS...
package haproxyctl import ( "bufio" "fmt" "io" "strings" ) type Info struct { Name string Version string Release_date string Nbproc int Process_num int Pid int Uptime ...
package main import ( "context" "fmt" "sync" ) func main() { ctx := context.WithValue(context.Background(), "z", "zhong") var once sync.Once once.Do(func() { ctx = context.WithValue(ctx, "g", "guan") }) once.Do(func() { ctx = context.WithValue(ctx, "d", "ding") }) v := ctx.Value("z") fmt.Println(v) ...
package buffered import ( "testing" "github.com/iotaledger/hive.go/kvstore/mapdb" "github.com/iotaledger/wasp/packages/kv" "github.com/stretchr/testify/assert" ) func TestBufferedKVStore(t *testing.T) { db := mapdb.NewMapDB() _ = db.Set([]byte("abcd"), []byte("v1")) realm := db.WithRealm([]byte("ab")) v, e...
// This file was generated for SObject OrgDeleteRequest, API Version v43.0 at 2018-07-30 03:47:50.716509943 -0400 EDT m=+37.060506989 package sobjects import ( "fmt" "strings" ) type OrgDeleteRequest struct { BaseSObject CreatedById string `force:",omitempty"` CreatedDate string `force:",omitempty"` ...
package main import ( "fmt" ) func main() { var data_siswa = map[string]string{}; // buat array assosiatif dengan tipe string data_siswa["nama"] = "Nama Siswa"; data_siswa["kelas"] = "Kelas 1"; data_siswa["umur"] = "10"; fmt.Println(data_siswa); fmt.Printf("Nama : %v \n", data_siswa["nama"]); fmt.P...
package modules import ( "context" "github.com/shepf/star-tools/node/types" "go.uber.org/fx" "github.com/shepf/star-tools/node/repo" ) func LockedRepo(lr repo.LockedRepo) func(lc fx.Lifecycle) repo.LockedRepo { return func(lc fx.Lifecycle) repo.LockedRepo { lc.Append(fx.Hook{ OnStop: func(_ context.Contex...
package hot100 import "sort" // 关键: dfs // 1. 排序: 排序使得可以去重 // 2. dfs func subsets(nums []int) [][]int { ret := make([][]int, 0) sort.Ints(nums) var dfs func(cur int) temp := make([]int, 0) dfs = func(cur int) { if cur == len(nums) { ret = append(ret, append([]int{}, temp...)) return } temp = append(t...
package main import ( "errors" "fmt" "runtime/debug" "strings" "unicode" "unicode/utf8" ) func splitCFlagsFromArgs(in []string) (args, cflags []string) { for i, arg := range in { if arg == "--" { return in[:i], in[i+1:] } } return in, nil } func splitArguments(in string) ([]string, error) { var ( ...
package commands import ( "github.com/sad0vnikov/wundergram/bot/dialog" ) //BuildConversationTree returns a bot conversation tree func BuildConversationTree() dialog.Tree { dialogRoot := dialog.NewConversationTreeNode(start) showTodayTasks := dialog.NewConversationTreeNode(showTodayTasksCommand). WithKeywords([...
package pgsql import ( "testing" ) func TestPoint(t *testing.T) { testlist2{{ valuer: PointFromFloat64Array2, scanner: PointToFloat64Array2, data: []testdata{ {input: [2]float64{}, output: [2]float64{}}, {input: [2]float64{1, 1}, output: [2]float64{1, 1}}, {input: [2]float64{0.5, 1.5}, output: [2]fl...
// Copyright 2020 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 hostsfile_test import ( "bytes" "fmt" "io" "net/netip" "os" "path/filepath" "strings" "testing" "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/hostsfile" "github.com/AdguardTeam/golibs/testutil" "github.com/AdguardTeam/golibs/testutil/fakeio" "github.com/stretchr/testify/as...
package main import ( "fmt" "reflect" "testing" ) // Sum func TestSum(t *testing.T) { t.Run("5 numbers", func(t *testing.T) { nums := []int{1, 2, 3, 4, 5} result := Sum(nums) expected := 15 if expected != result { t.Errorf("Expected: '%d', Result: '%d', Given: %v", expected, result, nums) } }) t...
package main import ( "github.com/garyburd/redigo/redis" "fmt" ) func main() { c, err := redis.Dial("tcp", "localhost:6379") if err != nil { panic(fmt.Sprintln("链接失败", err.Error())) } defer c.Close() //在redis中设置值 _, err = c.Do("set", "key1", "redis_set_value哈哈") if err != nil { panic(err.Error()) } ...
package deployer import ( "io" "github.com/devspace-cloud/devspace/pkg/devspace/config/generated" ) // Interface defines the common interface used for the deployment methods type Interface interface { Status() (*StatusResult, error) Deploy(cache *generated.CacheConfig, forceDeploy bool, builtImages map[string]st...
package util import ( "path/filepath" "testing" "github.com/stretchr/testify/assert" v1 "k8s.io/api/core/v1" ) var ( kubeletRootDir = "/var/lib/kubelet" ) func TestEscapeQualifiedName(t *testing.T) { assert := assert.New(t) originalName := "kubernetes.io/empty-dir" expectedPVName := "kubernetes.io~empty-dir...
/** * Copyright (c) 2019. All rights reserved. * Deal with the messages from users * Author: tesion * Data: April 2nd 2019 */ package msg import ( pb "api/talk_cloud" cfgComm "configs/common" "database/sql" "fmt" "github.com/smartwalle/dbs" "log" "strconv" "time" ) type MsgType uint8 const ( PLAIN_TEXT...
package mongodb import ( "context" "fmt" "strings" "github.com/brigadecore/brigade/v2/apiserver/internal/api" "github.com/brigadecore/brigade/v2/apiserver/internal/lib/mongodb" "github.com/brigadecore/brigade/v2/apiserver/internal/meta" "github.com/pkg/errors" "go.mongodb.org/mongo-driver/bson" "go.mongodb.o...
package main import ( "fmt" . "leetcode" ) //102. 二叉树的层序遍历 //给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。 func main() { n := &TreeNode{ Val: 3, Left: &TreeNode{Val: 9}, Right: &TreeNode{ Val: 20, Left: &TreeNode{Val: 15}, Right: &TreeNode{Val: 7}, }, } fmt.Println(levelOrder(n)) n = ...
package main import ( "fmt" "github.com/gomodule/redigo/redis" "strconv" ) type Category struct { Id int `redis:"id" json:"id"` Name string `redis:"name" json:"name"` } func getCategoriesMap(redisConn redis.Conn) map[int]Category { categories := make(map[int]Category, 0) values, e := getHashAsStringMap(c...
package main import ( "fmt" "math" ) func main() { fmt.Println(areaOfCircle(4)) fmt.Println(areaOfCircle(3.2131)) } func areaOfCircle(r float64) float64 { return math.Pi * r * r }
package cmd import ( "fmt" "github.com/sachaos/atcoder/lib/atcoder" "github.com/sachaos/atcoder/lib/environment" "github.com/sachaos/atcoder/lib/preparer" "github.com/spf13/cobra" "github.com/spf13/viper" ) // prepareCmd represents the prepare command var prepareCmd = &cobra.Command{ Use: "prepare CONTEST_ID...
package sheetsproxy import ( secretmanager "cloud.google.com/go/secretmanager/apiv1beta1" "context" "encoding/json" "fmt" "github.com/jakubincloud/sheetsproxy/sheetsproxy/util" "golang.org/x/oauth2" "golang.org/x/oauth2/google" goauth "golang.org/x/oauth2/google" "google.golang.org/api/option" "google.golang...
package main import ( "encoding/json" "fmt" "html/template" "log" "net/http" "strconv" "time" "accmgr" "bloglib" ) // loginFunc 登录 func loginFunc(rw http.ResponseWriter, req *http.Request) { fmt.Println("loginFunc method:", req.Method) //获取请求的方法 if req.Method == "GET" { t, _ := template.ParseFiles("../w...
// 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 // 示例:输入: [3,2,1,5,6,4] 和 k = 2,输出:5 package leet215 import ( "fmt" "sort" ) func main() { nums := []int{3, 2, 1, 5, 6, 4} t := findKthLargest(nums, 2) fmt.Println("-------", t) } func findKthLargest(nums []int, k int) int { sort.Ints(nums) ret...
package main /* * @lc app=leetcode id=106 lang=golang * * [106] Construct Binary Tree from Inorder and Postorder Traversal */ /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func buildTree(inorder []int, postorder []int) *Tree...
package dbtest import ( "time" "github.com/miska12345/DDPoll/db" ) const Database = "testDB" const DBlink = "mongodb+srv://ddpoll:ddpoll@test-ycw1l.mongodb.net/test?retryWrites=true&w=majority" func initializeTestEnv(collectionName string) (dbr *db.DB, err error) { dbr, err = db.Dial(DBlink, 2*time.Second, 5*tim...
/* Copyright 2016 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, ...
package main import ( "fmt" "github.com/julienschmidt/httprouter" "io/ioutil" "log" "net/http" ) /* StartServer starts the web application server by initializing the web handlers and middleware. */ func StartServer() { router := httprouter.New() router.GET("/", indexHandler) router.GET("/download/*filepath",...
package controller import ( "os" "log" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" ) func GetKubeClient() *kubernetes.Clientset{ var cfg *rest.Config var err error cfg, err = rest.InClusterConfig() home := homeDir() if err != nil && home != "" { cfg, err = clie...
package responses import ( "encoding/xml" "errors" "strings" ) type Error struct { XMLName xml.Name `xml:"error"` Messages []message `xml:"message"` HTTPStatus int } type message struct { Language string `xml:"language,attr"` Message string `xml:",chardata"` } func CreateError(HTTPStatus int, data *[...
package atomix import ( "strconv" "sync/atomic" ) // Uintptr is an atomic uintptr. type Uintptr struct { atomicType value uintptr } // NewUintptr creates an Uintptr. func NewUintptr(ptr uintptr) *Uintptr { return &Uintptr{value: ptr} } func (u *Uintptr) String() string { return strconv.FormatUint(uint64(u.Loa...
package admin import ( "firstProject/app/dto" "firstProject/app/http/result" "firstProject/app/models" goodsTypeRep "firstProject/app/repositories/goodsType" "firstProject/app/requests" "firstProject/database" "fmt" "reflect" "strconv" "github.com/gin-gonic/gin" "github.com/go-playground/locales/zh" ut "g...
package skyndiminni import ( "errors" "sync" "time" ) // Cahe is the object that controls the whole in-memory cache type Cache struct { *cache } type cache struct { defaultExpr time.Duration checkExpiredInterval time.Duration items map[string]*Item mut sync.RWMutex w...
package model import ( v1 "k8s.io/api/core/v1" ) type Problem struct { No int64 `json:"no"` Title string `json:"title"` Content string `json:"content"` // []TestCase = same scenario (use same HttpClient) TestCases [][]TestCase `json:"-"` Boilerplate []Boilerplate `json:"boilerp...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //378. Kth Smallest Element in a Sorted Matrix //Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth sm...
package storage import ( "fmt" "github.com/bhops/goapi/model" "github.com/jinzhu/gorm" "strconv" ) // UserStorage stores all users type UserStorage struct { db *gorm.DB } // NewUserStorage initializes the storage func NewUserStorage(db *gorm.DB) *UserStorage { return &UserStorage{db} } // GetAll returns the u...
package main import ( "fmt" "math/rand" "sync" "time" ) var wg sync.WaitGroup //wait for a collection of goroutine to finish func init() { rand.Seed(time.Now().UnixNano()) //使用指定种子值, 初始化默认资源到确定状态 } func main() { ch := make(chan int) //创建int类型无缓冲通道 wg.Add(2) //WaitGroup计数+2 go player("A", ch) go player("B"...
/* Write the shortest function to implement bogosort. In specific, your function should: Take an array (or your language's equivalent) as input Check if its elements are in sorted order; if so, return the array If not, shuffle the elements, and start again */ package main import ( "fmt" "math/rand" ...
package fare import ( "bytes" "context" "encoding/json" "io" "io/ioutil" "net/http" "net/url" "os" "strings" "time" "github.com/go-kit/kit/endpoint" kitlog "github.com/go-kit/kit/log" "github.com/go-kit/kit/sd" "github.com/go-kit/kit/sd/consul" "github.com/go-kit/kit/sd/lb" httptransport "github.com/g...
package lib import ( "fmt" "github.com/yamamoto-febc/jobq" "sync" ) // Run メイン処理 func Run(option *Option) error { currentOption = option resourceWaitGroup = sync.WaitGroup{} resourceWaitGroup.Add(19) // all resource // setup jobs environments jobQueue := jobq.NewJobQueue(option.JobQueueOption, routes) jobQ...
package ircserver import ( "fmt" "strings" "gopkg.in/sorcix/irc.v2" ) func init() { Commands["server_PRIVMSG"] = &ircCommand{ Func: (*IRCServer).cmdServerPrivmsg, } Commands["server_NOTICE"] = &ircCommand{ Func: (*IRCServer).cmdServerPrivmsg, } } // The only difference is that we re-use (and augment) the...
package main import ( "fmt" "html/template" "log" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { teml, err := template.New("test").Parse(` {{$name1 := "alice"}} name1:{{$name1}} {{with true}} {{$name1 := "alice2"}} {{$name2 := "bob"}} name1:{{$name1}} ...
package blog import ( "time" ) type Collector interface { show(post *Post) (string, error) FindPosts() ([]Post, error) } type Author struct { id int name string } type Post struct { title string author *Author body string created_at time.Time }
package tyme import "fmt" // LocalYear represents year without Location // e.g.) 2006 type LocalYear struct { year int } // NewLocalYear returns instance of LocalYear func NewLocalYear(year int) LocalYear { return LocalYear{year: year} } // Year returns number of year func (y *LocalYear) Year() int { return y.ye...
package volume import ( "context" "errors" "fmt" "io" "io/ioutil" "os" "path" "path/filepath" "strconv" "strings" "sync" "time" "github.com/prometheus/client_golang/prometheus" "gopkg.in/bufio.v1" ) const ( lockFileName = "LOCK" ) var ( ErrLockFileExisted = errors.New("lock file existed") ) type Vo...
package service_test import ( "context" "encoding/json" "testing" "time" "github.com/go-kit/kit/log" "github.com/stretchr/testify/require" "github.com/rwool/saas-interview-challenge1/pkg/internal/keyvaluemock" "github.com/rwool/saas-interview-challenge1/pkg/internal/queuemock" "github.com/rwool/saas-interv...
package validator_test import ( "testing" goplvalidator "github.com/go-playground/validator/v10" "github.com/kazhuravlev/options-gen/pkg/validator" "github.com/stretchr/testify/assert" ) func TestGetValidatorFor(t *testing.T) { t.Run("set nil", func(t *testing.T) { assert.Panics(t, func() { validator.Set(n...
package main import "math" /** 最佳观光组合 给定正整数数组 `A`,`A[i]` 表示第 `i` 个观光景点的评分,并且两个景点 `i` 和 `j` 之间的距离为 `j - i`。 一对景点`(i < j)`组成的观光组合的得分为`(A[i] + A[j] + i - j)`:景点的评分之和减去它们两者之间的距离。 返回一对观光景点能取得的最高分。 示例: ``` 输入:[8,1,5,2,6] 输出:11 解释:i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11 ``` 提示: - `2 <= A.length <= 50000` -...
package main func findTilt(root *TreeNode) int { _, tilt := helper563(root) return tilt } func helper563(root *TreeNode) (sum, tilt int) { if root == nil { return 0, 0 } leftSum, leftTilt := helper563(root.Left) rightSum, rightTilt := helper563(root.Right) sum = leftSum + rightSum + root.Val tilt = abs563(l...
package sampling import ( "fmt" "math" "math/rand" "github.com/devinmcgloin/clr/clr" "github.com/devinmcgloin/sail/pkg/canvas" "github.com/devinmcgloin/sail/pkg/fill" "github.com/devinmcgloin/sail/pkg/shapes" "github.com/fogleman/gg" ) type UniformRectangleDot struct{} func (c UniformRectangleDot) Dimension...
package pool_test import ( "fmt" "github.com/kirk-patton/example-go/channels/workerpool/pool" ) // ExampleNew - is a unit test that will show up as an example in our generated godoc // The required keyword, "Example", must be followed by the name of an existing function in // the package under test func ExampleNew...
/* Description After a day trip with his friend Dick, Harry noticed a strange pattern of tiny holes in the door of his SUV. The local American Tire store sells fiberglass patching material only in square sheets. What is the smallest patch that Harry needs to fix his door? Assume that the holes are points on the inte...
package main import ( "github.com/pkg/errors" log "github.com/sirupsen/logrus" "os" "os/exec" ) func aptInstall(pkg string) error { cmd := exec.Command("apt-get", "install", "-y", pkg) log.Debugf("running command: %s", cmd) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := cmd.Run() if err != nil { ret...
package renter import ( "strings" "testing" "time" "gitlab.com/NebulousLabs/Sia/modules" "gitlab.com/NebulousLabs/Sia/types" ) // TestUpdatePriceTableGouging checks that the price table gouging is correctly // detecting price gouging from a host. func TestUpdatePriceTableGouging(t *testing.T) { t.Parallel() ...
/* Package dev ... ZE08CH2O is the driver of ZE08CH2O, an air quality sensor which can be used to detect PM2.5 and PM10. Config Your Pi: 1. $ sudo vim /boot/config.txt add following new line: ~~~~~~~~~~~~~~~~~ enable_uart=1 ~~~~~~~~~~~~~~~~~ 2. $ sudo vim /boot/cmdline.txt remove following contexts: ~~~~~~~~~~~...
package tests import ( "fmt" "testing" "time" "github.com/deis/deis/tests/dockercli" "github.com/deis/deis/tests/etcdutils" "github.com/deis/deis/tests/utils" ) func runDeisBuilderTest( t *testing.T, testID string, etcdPort string, servicePort string) { var err error dockercli.RunDeisDataTest(t, "--name", "...
package dto import ( "bytes" "encoding/binary" "fmt" ) //This structure is revived for series operation type InterpolateElement struct { Data []Value } func (this InterpolateElement) String() string { return fmt.Sprintf("InterpolateElement: %v", this.Data) } func (this *InterpolateElement) Encode() ([]byte, e...
package wallet type TransferToken struct { coin string `json:"coin" binding:"required"` ToAddr string `json:"to_addr" binding:"required"` Amount float64 `json:"amount" binding:"required"` }
package server import ( "database/sql" "fmt" // Import postgres driver _ "github.com/lib/pq" "github.com/go-sink/sink/internal/app/config" ) func setUpDb(dbCfg config.Database) (*sql.DB, error) { dsn := fmt.Sprintf("user=%s password=%s database=%s sslmode=%s", dbCfg.User, dbCfg.Password, dbCfg.Database, dbCfg...
package client import ( "mobingi/ocean/pkg/storage" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" ) func NewClient(cluster string) (*kubernetes.Clientset, error) { storage := storage.NewStorage() kubeconfig, err := storage.GetKubeconf(cluster, "admin.conf") if err != nil { return nil, err ...
// Copyright 2021 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...
/* * @lc app=leetcode.cn id=1360 lang=golang * * [1360] 日期之间隔几天 */ // @lc code=start package main import ( "math" "strconv" "strings" ) func dateToDays(date string) int { dateSlice := strings.Split(date, "-") year, _ := strconv.Atoi(dateSlice[0]) month, _ := strconv.Atoi(dateSlice[1]) day, _ := strconv.At...
package main import ( v1 "DataApi.Go/api/v1" "DataApi.Go/database" "DataApi.Go/middleware" "github.com/gin-gonic/gin" _ "github.com/go-sql-driver/mysql" "github.com/joho/godotenv" "os" ) func main() { err := godotenv.Load() if err != nil { panic(err) } dbConfig := os.Getenv("DB_CONFIG") db, _ := databas...
package parse import ( "testing" "time" ) func TestPrettyDuration(t *testing.T) { now := time.Now() cases := []struct { given time.Time want string }{ { given: now, want: lessThanMin, }, { given: now.Add(59 * time.Second), want: lessThanMin, }, { given: now.Add(60 * time.Second), ...
package main import ( "bufio" "bytes" "flag" "fmt" "io" "log" "os" "strings" "unicode" "unicode/utf8" ) var ( dataPath = flag.String("data", "", "Path to pinyin data file") maxLine = flag.Int("max-line", 32, "Maximum byte size of a line in data file") dataFile *os.File dataSize int64 ) func main() { ...
package main // two default statements in switch/case func main(){ var i int = 0 switch i { case 1: default: default: break } }
/* CHALLENGE: -- Change the code to execute 1,000 factorial computations concurrently and in parallel. -- Use the "fan out / fan in" pattern */ package main import ( "fmt" "math/rand" "sync" "time" ) func main() { // Generate 1,000 inputs for the factorial function, randomised from 1 up to 20 in := gen(20, 1e3)...
package mwords import ( "hash/crc32" "testing" "github.com/stretchr/testify/assert" ) // the total number of characters in the word list const charCount = 11068 // expected checksum const checksum = 2176441764 var wordsValid = []string{ "apple", "approve", "canvas", "cruise", "fame", "merry", "salad", "soda",...
/* After the festive opening of your new store, the Boutique store for Alternative Paramedicine and Cwakhsahlvereigh, to your disappointment you find out that you are not making as many sales as you had hoped. To remedy this, you decide to run a special offer: you will mark some subset of the n items for sale in your ...
package field import ( "encoding/binary" "fmt" "io" ) // Field69 is the unknown field with ID 69. type Field69 struct { header *Header data []byte } // Value returns the raw byts for the field. func (f *Field69) Value() []byte { return f.data } func (f *Field69) String() string { return fmt.Sprintf("%v", f...
package main import ( "context" "curses" "log" "net" "os" "os/signal" "syscall" "time" "github.com/google/gopacket" "github.com/google/gopacket/pcap" ) const ( white_blk int = iota + 1 yellow_blk red_blk green_blk white_blue blk_white ) func winEnd() { curses.Endwin() } func winInit() { curses.Ini...
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you...
package caam import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00400101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caam.004.001.01 Document"` Message *ATMKeyDownloadResponseV01 `xml:"ATMKeyDwnldRspn"` } func (d *Document00400101)...
package main import ( "fmt" "github.com/gtfierro/xboswave/ingester/types" xbospb "github.com/gtfierro/xboswave/proto" ) func has_weather_station(msg xbospb.XBOS) bool { return msg.XBOSIoTDeviceState.WeatherStation != nil } func has_weather_station_prediction(msg xbospb.XBOS) bool { return msg.XBOSIoTDeviceState...
package util import ( "context" "os" "os/signal" "github.com/danjacques/pixelproxy/util/logging" "github.com/danjacques/pixelproxy/util/profiling" "github.com/spf13/pflag" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) // Application is a configuration for a generic application entry point. // // Application...
package main import ( "fmt" "github.com/malyshevd/go-learn/lesson-8/config" "github.com/malyshevd/go-learn/lesson-8/server" ) func main() { config := config.NewConfig() fmt.Println(*config) server.RunServer(config) }
package main import ( "sync" ) type MinStack struct { value []int minValue []int lock sync.Mutex } /** initialize your data structure here. */ func Constructor() MinStack { return MinStack{ value: make([]int, 0), minValue: make([]int, 0), } } func (this *MinStack) Push(x int) { this.lock.Lock()...
package classic func flatten(head *ListNode) *ListNode { out, _ := dfs(head, true) return out } func dfs(head *ListNode, topLevel bool) (out *ListNode, np *ListNode) { if head == nil { return } var p *ListNode for np, p = head, head; p != nil; np, p = p, p.Next { if topLevel { out = head } if p.Chi...
package byudp type options struct { //tlsCfg *tls.Config codec Codec onConnect onConnectFunc onMessage onMessageFunc onClose onCloseFunc onError onErrorFunc workerSize int // numbers of worker go-routines bufferSize int // size of buffered channel reconnect bool // for ClientConn use only...
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" "strings" "strconv" "net/smtp" "time" "golang.org/x/net/context" "golang.org/x/oauth2" "github.com/aws/aws-lambda-go/lambda" ) type Pros...
// Copyright 2019 Drone.IO Inc. All rights reserved. // Use of this source code is governed by the Blue Oak Model License // that can be found in the LICENSE file. package cache import ( "testing" "github.com/google/go-cmp/cmp" ) func TestCache(t *testing.T) { c := newCache(5) c.push("alpine:latest", 359596800)...
package pie import ( "context" "math/rand" "golang.org/x/exp/constraints" ) // OfOrdered encapsulates a slice to be used in multiple chained operations. // OfOrdered requires that elements be numerical or a string for certain // operations to be performed. func OfOrdered[T constraints.Ordered](ss []T) OfOrderedSl...
package draw type ICanvas interface { DrawLine(pen IPen, from, to Point) error DrawRectangle(pen IPen, rect Rectangle) error FillRectangle(brush IBrush, rect Rectangle) error DrawEllipse(pen IPen, rect Rectangle) error FillEllipse(brush IBrush, rect Rectangle) error DrawCircle(pen IPen, center Point, radius int)...
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "os" "path/filepath" "gopkg.in/alecthomas/kingpin.v2" "github.com/square/p2/pkg/artifact" "github.com/square/p2/pkg/auth" "github.com/square/p2/pkg/logging" "github.com/square/p2/pkg/uri" "github.com/square/p2/pkg/version" ) var ( location ...
package tree func height(root *TreeNode) int { if root == nil { return 0 } lh := height(root.Left) rh := height(root.Right) if lh > rh { return lh + 1 } return rh + 1 }
// Copyright (c) 2020 Blockwatch Data Inc. // Author: alex@blockwatch.cc package models type FlowCategory int const ( FlowCategoryRewards FlowCategory = iota // 0 freezer category FlowCategoryDeposits // 1 freezer category FlowCategoryFees // 2 freezer category ...
package model // Application - a struct to rep plan database model type Application struct { BaseIntModel UserID string `json:"user_id" gorm:"not null;type:varchar(20)"` CourseID uint `json:"course_id" gorm:"not null;type:int(15)"` CertificateIssuerID string `js...
package main import "er" const ( _E_AUTH_SRV = 0x3000 _E_AUTH_SRV_TIMEOUT = _E_AUTH_SRV | er.IMPT_UNRECOVERABLE | er.ET_INTERNAL | er.EI_TIMEOUT | 0x1 _E_INVALID_AUTH_REQUEST = _E_AUTH_SRV | er.IMPT_THREAT | er.ET_INTERNAL | er.EI_INVALID_REQUEST | 0x2 _E_USER_NOT_LOGIN = _E_AUTH_SRV | er.IMPT_REMARKAB...
package main import "fmt" func main(){ //定义一个切片 var values = []int{0,2,1,4,5,7,1,0} bubbleSort(values) for _,value := range(values){ fmt.Println(value) } } func BubbleSort(values []int){ flag:=true for i:=0;i<len(values)-1;i++{ flag=true for j :=0;j<len(values)-1-i;j++{ if values[j]>values[j+1]{ ...