text
stringlengths
11
4.05M
package ca import ( "bytes" "testing" ) func openTestingDB() (*database, error) { return openDB(":memory:") } func TestMetadata(t *testing.T) { var ( key = []byte{42} value = []byte("hello, world") ) db, err := openTestingDB() if err != nil { t.Fatal(err) } err = db.SetMetadata(key, value) if err...
package informer import ( "testing" "github.com/stretchr/testify/assert" corev1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" wfv1 "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1" ) func Test_objectToWorkflowTemplate(t *testin...
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package engine import ( "bytes" "compress/gzip" "encoding/base64" "encoding/json" "fmt" "io" "net" "net/http" "regexp" "sort" "strconv" "strings" "text/template" "github.com/Azure/go-autorest/autorest/to" ...
package main func main() { } /** 二叉树的最近公共祖先 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。” 例如,给定如下二叉树:  root = [3,5,1,6,2,0,8,null,null,7,4] ![-1.png](./source/-1.png) 示例 1: ``` 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 输出:...
package ads import ( "bytes" "encoding/binary" "fmt" "math" "strconv" "time" ) //func (dt *ADSSymbol) parse(offset uint32, data []byte) { /*{{{*/ func (dt *ADSSymbol) parse(data []byte, offset int) { /*{{{*/ start := offset stop := start + int(dt.Length) if dt.Childs != nil { for _, value := range dt.Chil...
package ccconvert import ( "fmt" "image" "image/color" "image/draw" "image/jpeg" "net/http" "os" ) const ( UnknownConvertMode = 0 Png2Jpg = 1 Jpg2Jpg = 2 ) func readRaw(src string, decode func(file *os.File, ext string) (image.Image, error)) (image.Image, error) { f, err := os.Open(s...
package memory import ( "encoding/hex" "fmt" "github.com/Secured-Finance/dione/blockchain/database" types2 "github.com/Secured-Finance/dione/blockchain/types" "github.com/patrickmn/go-cache" ) const ( LatestBlockHeightKey = "latest_block_height" ) type Database struct { db *cache.Cache } func NewDatabase()...
package clock import ( "testing" "time" . "github.com/smartystreets/goconvey/convey" ) type suit func(c Clock) func realAndMockClock(t *testing.T, test suit) { Convey("测试 real clock", t, func() { c := NewRealClock() test(c) }) Convey("测试 mock clock", t, func() { now := time.Now() c := NewMockClock(now...
package api import ( "encoding/hex" "encoding/json" "fmt" "github.com/gin-gonic/gin" "github.com/noah-blockchain/autodeleg/internal/env" "github.com/noah-blockchain/autodeleg/internal/gate" "github.com/noah-blockchain/autodeleg/internal/helpers" "github.com/noah-blockchain/noah-go-node/core/transaction" "gith...
package xtractr /* This file contains methods that support the extract queuing system. */ import ( "fmt" "io/ioutil" "os" "path/filepath" "strings" "time" ) // Xtract defines the queue input data: data needed to extract files in a path. // Fill this out to create a queued extraction and pass it into Xtractr.Ex...
package files import ( "crypto/md5" "hash" "io" "os" "path/filepath" "github.com/javiercbk/filetype" "github.com/javiercbk/filetype/types" ) // ReadWriteSeekCloser is a Reader, a Writer, a Seeker and a Closer type ReadWriteSeekCloser interface { io.Reader io.Writer io.Seeker io.Closer } // FileMetadata i...
package logs import ( "time" ) type LogLevel int const ( Info LogLevel = iota Warning Error ) type LogMsg struct { Level LogLevel Msg string } type LogStack struct { Logger *Logger Stack []*LogMsg } func (ls *LogStack) Add(lvl LogLevel, msg string) { ls.Stack = append(ls.Stack, &LogMsg{ Level: lv...
package main import ( "fmt" "runtime" ) func ifPractice(val int) { if val == 1 { fmt.Println("a is 1") } else if val == 2 { fmt.Println("a is 2") } else if val == 3 { fmt.Println("a is 3") } else { fmt.Println("a is not 1,2,3") } fmt.Println(runtime.GOOS) } func ifInit() { val := 0 // if中会有单独的块级...
package audit import ( "context" "encoding/json" "fmt" "io/ioutil" "net/http" api "nighthawkapi/api/core" "nighthawkapi/api/handlers/auth" "nighthawkapi/api/handlers/config" "time" "github.com/gorilla/mux" elastic "gopkg.in/olivere/elastic.v5" ) const EsTagType = "tags" func init() { conf, err = config....
package main import ( "flag" "fmt" "io" "log" "math" "math/rand" "os" "strconv" "sync" "time" ) var ( n int // Number of files m int // Number of entries per file ) var max = len(strconv.AppendUint(nil, math.MaxUint64, 10)) func main() { flag.IntVar(&n, "n", 1, "number of files to generate") flag.IntV...
package messages const MsgFormFieldRequired = "%[1]s required"
package main import "fmt" // Vertex type Vertex struct { edges []*Vertex } func (v Vertex) addEdge(vToAdd Vertex) Vertex { edges := v.edges edges = append(edges, &vToAdd) return Vertex{edges} } func (v Vertex) delEdge(vToDel Vertex) Vertex { edges := v.edges nEdges := len(edges) toDel := -1 for i := 0; i < ...
package main import ( "flag" "fmt" "io/ioutil" "log" "os" "strings" "github.com/ripexz/logpasta/clipboard" ) var version = "v0.3.3" func main() { initLogger() conf := loadConfig() checkForCommands() var content string fi, _ := os.Stdin.Stat() if (fi.Mode() & os.ModeCharDevice) == 0 { // piped byte...
package main import ( "os" "github.com/therecipe/qt/widgets" ) func main() { widgets.NewQApplication(len(os.Args), os.Args) a := newApp(1500, 1000) widgets.QApplication_SetStyle2("fusion") a.w.Show() widgets.QApplication_Exec() }
package main import "fmt" func main() { ch1 := make(chan int, 1) ch1<-1 ch2 := make(chan int, 1) ch2<-2 select { case k1 := <-ch1: fmt.Println(k1) case k2 := <-ch2: fmt.Println(k2) default: fmt.Println("chan") } }
package controller import ( "github.com/reechou/robot-manager/models" ) const ( RESPONSE_OK = iota RESPONSE_ERR ) type Response struct { Code int64 `json:"code"` Msg string `json:"msg,omitempty"` Data interface{} `json:"data,omitempty"` } type GetRobotGroupsRsp struct { Count int64 ...
/* Copyright 2018 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 jsonv import ( "reflect" ) // Used to avoid expensive pathing string formatting when it's needed 99.9999% // of the time type Pather func() string /* Used by Parser for parsing and validation of JSON types. Can return either a ValidationError or a general error if encountered This is used to allow the pars...
package main //如何判断一个链表有没有闭环 import ( "fmt" ) func setp() int { x := 1 y := 2 var n int fmt.Print("please input step number: ") // fmt.Scanf("%d",&n) fmt.Scanln(&n) if n == 1 { return x } else if n == 2 { return y } else { for i := 0; i < n-2; i++ { x, y = y, x+y } return y } } func main() {...
package ui import ( "fmt" "github.com/jroimartin/gocui" "github.com/ryo-ma/coronaui/lib" ) type TextPanel struct { ViewName string viewPosition ViewPosition } func NewTextPanel() (*TextPanel, error) { textPanel := TextPanel{ ViewName: "text", viewPosition: ViewPosition{ x0: Position{0.3, 0}, y0: ...
package data import "testing" func TestCheckValidation(t *testing.T){ p:= &Product{ Name: "ProductName", Price: 1, SKU: "abcd-def", } err:= p.Validate() if err!= nil{ t.Fatal(err) } }
package oauthstore import ( "io/ioutil" "os" "reflect" "testing" "time" "golang.org/x/oauth2" ) func TestFileStorage_GetToken(t *testing.T) { fname, _ := ioutil.TempFile(".", "example") defer os.Remove(fname.Name()) tests := []struct { name string f *FileStorage want *oauth2.Token wantE...
package cmd import ( "fmt" "github.com/oberd/ecsy/ecs" "github.com/spf13/cobra" ) // Can be "all", "running", "stopped" var logsStatusFilter = "all" // logsCmd represents the logs command var logsCmd = &cobra.Command{ Use: "logs [cluster] [service]", Short: "Show recent logs for a service in a cluster (must ...
package main import "fmt" type vehicle struct { doors int colour string } type truck struct { vehicle fourWheel bool } type sedan struct { vehicle luxury bool } func main() { hmmvw := truck{ vehicle: vehicle{ doors: 4, colour: "army green", }, fourWheel: true, } passat := sedan{ vehicle: ...
/* Tests basic communication between client and kvnode using kvservice. Creates 2 non-overlapping transactions and commits them. Usage: go run 1_TwoNonOverlappingTransactions.go */ package main import "../kvservice" import ( "fmt" ) func main() { var nodes []string nodes = []string{"52.233.45.243:2222", "52.175....
package consul import ( "fmt" consulAPI "github.com/hashicorp/consul/api" consulWatch "github.com/hashicorp/consul/api/watch" ) type watcher struct { serverType string plan *consulWatch.Plan noticeChan chan AvailableServers } func (d *watcher) handler(index uint64, raw interface{}) { if raw == nil { ...
package logdata import ( "encoding/json" "github.com/google/gopacket/layers" ) // ICMPv6LogData is the struct describing the logged data for ICMPv6 packets type ICMPv6LogData struct { TypeCode layers.ICMPv6TypeCode `json:"type_code"` Type uint8 `json:"type"` Code uint8 ...
// ˅ package main // ˄ type Mediator interface { ColleagueChanged() CreateColleagues() // ˅ // ˄ } // ˅ // ˄
package main import ( "fmt" "strconv" ) func main() { number := 0 width := 1 numStr := "" revStr := "" for (number != 0) && (len(numStr) != width) { pop := number % 10 numStr += strconv.Itoa(pop) number /= 10 } if len(numStr) < width { for len(numStr) < width { numStr += "0" } } for i := l...
package pgsql import ( "database/sql" "database/sql/driver" "strconv" ) // MoneyFromInt64 returns a driver.Valuer that produces a PostgreSQL money from the given Go int64. func MoneyFromInt64(val int64) driver.Valuer { return moneyFromInt64{val: val} } // MoneyToInt64 returns an sql.Scanner that converts a Postg...
package main func main() { x := 10 if xinit(); x == 0 { println("a") } if a, b := x+1, x+10; a < b { println(a) } else { println(b) } } func xinit() bool { println("In xinit ...") return true }
// Copyright © 2018 Taavi Kivisik // // 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, publish, d...
package main import ( "fmt" "os" "runtime" "sync" ) func printArg (wg *sync.WaitGroup, val string) { defer wg.Done() fmt.Println(val) } func main() { runtime.GOMAXPROCS(2) args := os.Args[1:] var wg sync.WaitGroup for i := range args { wg.Add(1) go printArg(&wg, args[i]) } ...
package leetcode /*Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k char...
package main import ( // 读输入输出流 "bufio" "fmt" // socket包 操作tcp的 "net" "os" "strings" ) func checkError(err error){ if err != nil{ panic(err); } } // 写入数据的处理 func messagesend(conn net.Conn){ var input string; for{ // 这是在写入数据的时候的操作! // 读取终端是不是有数据 reader:=bufio.NewReader(os.Stdin); // 获取数据 d...
package models import ( "database/sql" "git.hoogi.eu/snafu/go-blog/logger" "strings" "time" ) // SQLiteArticleDatasource providing an implementation of ArticleDatasourceService for SQLite type SQLiteArticleDatasource struct { SQLConn *sql.DB } // Create creates an article func (rdb *SQLiteArticleDatasource) Cre...
package main import ( "fmt" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/sha256" ) func NewKeypair() (ecdsa.PrivateKey,[]byte) { //生成椭圆曲线。secp256r1曲线 (比特币当中的曲线是secp256k1) curve := elliptic.P256() private,err1 := ecdsa.GenerateKey(curve,rand.Reader) if err1 != nil{ ...
package gvabe import ( "context" "encoding/json" "fmt" "log" "reflect" "regexp" "sort" "strings" "time" "github.com/btnguyen2k/consu/reddo" "golang.org/x/oauth2" "main/src/goapi" "main/src/gvabe/bo/app" "main/src/gvabe/bo/user" "main/src/itineris" ) /* Setup API handlers: application register its api...
package problem0647 func countSubstrings2(s string) int { if len(s) <= 0 { return 0 } result := 1 for i := 0; i < len(s)-1; i++ { result = expand(i, i, s, result) result = expand(i, (i + 1), s, result) } return result } func expand(left int, right int, s string, result int) int { for left >= 0 && right <...
package str import ( "regexp" "strings" ) var IPReg, _ = regexp.Compile(`^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$`) var MailReg, _ = regexp.Compile(`\w[-._\w]*@\w[-._\w]*\.\w+`) func IsMatch(s, pattern string) bool { match, err := regexp.Match(pattern, []byte(s)) if err != nil { return false } return match } f...
package main import ( "fmt" "testing" "time" ) //Testx ... func TestX(t *testing.T) { fmt.Println("Text") } func BenchmarkX(b *testing.B) { fmt.Println("X") time.Sleep(time.Second * 1) } func BenchmarkY(b *testing.B) { fmt.Println("Y") time.Sleep(time.Second * 2) } func BenchmarkZ(b *testing.B) { fmt.Print...
package chapter3 import "fmt" func init() { fmt.Println("=== Car and Truck") c := Car{4, 6} fmt.Println(c) fmt.Println(c.getDoors()) t := Truck{2, "full", oneTon} fmt.Println(t) fmt.Println(t.getDoors()) }
package main import ( "time" "fmt" "net/http" "encoding/json" ctd "GossipServer/CTData" "os" "os/signal" "syscall" "bytes" "io/ioutil" "strings" "github.com/golang/glog" "flag" ) var port string; var peers []string; var messages map[string]ctd.CTData func main() { done := mak...
package dbx import ( "context" "database/sql" "fmt" ) type DQLExecutor interface { DQLExecContext(ctx context.Context, query string, argument DQLArgument) (sql.Result, error) //DQLExec executes a query without returning any rows. DQLExec(query string, argument DQLArgument) (sql.Result, error) DQLMustExecCont...
package main import "fmt" // This var means the scope of x is the WHOLE package as its NOTt inside the {}. The whole package can use this var, including other .go files inside the package // AKA package level scope var x int = 1001 // THIS IS PACKAGE SCOPE func main() { // THIS IS BLOCK level scope // shows closur...
package main import ( "testing" ) type testdata struct { fname1 string expectedtask1 int fname2 string expectedtask2 int } var testset []*testdata = []*testdata{{"example1.txt", 165, "example2.txt", 208}} func TestTaskOne(t *testing.T) { for _, test := range testset { m := readdata(test.fname1...
package main //假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 // //每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? // //注意:给定 n 是一个正整数。 // //示例 1: // //输入: 2 //输出: 2 //解释: 有两种方法可以爬到楼顶。 //1. 1 阶 + 1 阶 //2. 2 阶 //示例 2: // //输入: 3 //输出: 3 //解释: 有三种方法可以爬到楼顶。 //1. 1 阶 + 1 阶 + 1 阶 //2. 1 阶 + 2 阶 //3. 2 阶 + 1 阶 func main() { } func climbStairs(n int) ...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2022/1/12 8:55 上午 # @File : lt_43_字符串相乘.go # @Description : # @Attention : */ package hot100 import "strconv" /* // 解题关键: 注意点: 1. 边界条件: 有一个数为0,直接返回0 2.遍历计算乘积的时候,要注意多出来的数, 如 4*5=20 ,多出来的是2,要充分记得考虑这个值 // 采用加法: // num1的数 * num2 的每个数, 然后和再累加 (这里唯一需要注意的点是,记得结果跟上0) /...
package main import ( "fmt" "github.com/jackytck/projecteuler/tools" ) func extract(slice []int, start, end int) int { return tools.JoinInts(slice[start:end]) } func check(n, d int) bool { return n%d == 0 } func solve() int { var sum int for v := range tools.Perms([]int{0, 1, 2, 3, 4, 6, 7, 8, 9}) { p2 := ...
package main import "fmt" /* This example shows how to create variables and constants in Go. */ func main(){ variables() constants() } func variables(){ fmt.Println("==> Variables section:") // implicit assignment (declaration and assignments are done at the same time name, location := "Prince Oberyn", "Dorn...
package proto type PubMsg struct { RawID []byte ID []byte Topic []byte Payload []byte Acked bool Type int8 QoS int8 TTL int64 Sender []byte Timestamp []byte } type TimerMsg struct { ID []byte Topic []byte Payload []byte Trigger int64 Delay int } type A...
package main import "fmt" import "math" func main() { counter := 0 TriangleNumber := 0 Switch := 1 for Switch >= 1 { counter++ TriangleNumber += counter if factors(TriangleNumber) > 500 { fmt.Println(TriangleNumber) Switch = 0 } } } func factors(n int) (facCount int) { facCounter := 0 k := int(m...
package main import ( "fmt" "math" ) func checkPrime(num int) bool{ for i:=2 ; i<=int(math.Ceil(float64(num)/2)) ; i++{ if num%i==0{ return false } } return true } func main() { var num int fmt.Print("Input: ") _, _ = fmt.Scanln(&num) fmt.Print("Output: ") if !checkPrime(num){ fmt.Print("Bukan "...
// 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 main import ( "fmt" ) func information_ring_nodes(){ fmt.Println("LIST OF NODES") for k,node := range node_dictionary.node_dictionary{ fmt.Println("START OF NODE INFORMATION") fmt.Printf("\n Node %d present in ring\n",k) fmt.Printf("Contents of Nodes %d",node.ChannelID) if node.Successor != -1 { ...
package model import ( "time" ) /*************************/ /********菜单路由结构体*********/ /*************************/ type Route struct { Id int `json:"id"` //ID AppId string `json:"appid" binding:"required,max=32"` //所属应用 Name string `json:"name" binding:"requ...
package util import ( "errors" "regexp" ) var ( ErrBadFormat = errors.New("invalid_email") emailRegexp = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") ) // ValidateFormat ... func ValidateFormat(email s...
package main import "fmt" func main() { fmt.Println(spiralOrder([][]int{ {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, })) fmt.Println(spiralOrder([][]int{ {3}, {2}, })) } func spiralOrder(matrix [][]int) []int { ans := make([]int, 0) if len(matrix) == 0 || len(matrix[0]) == 0 { return ans } rl, rh := 0,...
package math import "testing" func TestAverage(t *testing.T) { type args struct { xs []float32 } tests := []struct { name string args args want float32 }{ // TODO: Add test cases. { name: "test 1", args: args{ xs: []float32{3,4,3,2}, }, want: 3, }, { name: "test 2", args: arg...
package query import ( "github.com/jinzhu/gorm" ) // Query is a flexible pattern to allow query DB. type Query func(db *gorm.DB) *gorm.DB // Transform applies multiple query to an existing instance of gorm.DB to create a new gorm.DB. func Transform(db *gorm.DB, queries ...Query) *gorm.DB { for _, q := range querie...
package knothash import ( "testing" "github.com/stretchr/testify/require" ) func TestKnotHash(t *testing.T) { data := []struct { alen int lengths []byte result int }{ {5, []byte{3, 4, 1, 5}, 12}, } assert := require.New(t) for _, in := range data { out := KnotHash(in.alen, in.lengths) assert....
// Good morning! Here's your coding interview problem for today. // This problem was asked by Google. // Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree. // For example, given the following Node ...
package main import ( "container/heap" "fmt" ) type MedianFinder struct { max *intHeap min *intHeap n int } /** initialize your data structure here. */ func Constructor() MedianFinder { return MedianFinder{ min: &intHeap{min: true}, max: &intHeap{min: false}, } } func (mr *MedianFinder) AddNum(num int)...
//~0 //~1 //~2 //~3 //~4 //~5 //~6 //~7 //~8 //~9 package main func main(){ for i:=0; i < 10;i++{ println(i) } }
package ziface /* 路由抽象接口 路由里的数据都是 IRequest */ type IRouter interface { // 在处理 conn 业务之前的钩子方法 hook PreHandle(request IRequest) // 在处理 conn 业务的主方法 hook Handler(request IRequest) // 在处理 conn 业务之后的钩子方法 hook PostHandler(request IRequest) }
package main import "fmt" func main() { var i int = 10 i = 30 fmt.Println("i=", i) //i = 1.2不能改变原来的类型 //var i int = 60 变量在同一个作用域里面不能重名 }
package status import ( "path/filepath" "sort" "github.com/go-task/task/v2/internal/execext" "github.com/mattn/go-zglob" ) func glob(dir string, globs []string) (files []string, err error) { for _, g := range globs { if !filepath.IsAbs(g) { g = filepath.Join(dir, g) } g, err = execext.Expand(g) if e...
package repositories import "github.com/ariel17/railgun/api/entities" // DomainsRepository is the behaviour contract for all Domain's repository // implementations. type DomainsRepository interface { GetByID(id int64) (*entities.Domain, error) GetByURL(url string) (*entities.Domain, error) Add(domain *entities.Dom...
package crypto import ( "bytes" "crypto/aes" "crypto/cipher" "encoding/base64" "encoding/binary" ) // MessageCrypter 封装了生成签名和消息加解密的方法 type Decryptor struct { token string appId string key []byte iv []byte } // NewMessageCrypter 方法用于创建 MessageCrypter 实例 // // token 为开发者在微信开放平台上设置的 Token, // encodingAESK...
package goSolution func sumOfFlooredPairs(nums []int) int { m := max(nums...) b := make([]int, m + 1) for _, num := range nums { b[num] += 1 } s := GetPrefixSum(b) ret := 0 for _, num := range nums { if b[num] != 0 { t := m / num for j := 1; j <= t; j++ { k := s[min((j + 1) * num, m + 1)] - s[j * ...
// Package fail - geojson.go Gets data from servers package main import "encoding/json" import "fmt" // Geojson feature results type Result struct { Type string `json: "type"` Features []interface{} `json: "features"` } // Geojson reports object type Reports struct { StatusCode float64 `json: "statusCode"` Resu...
package main import ( "encoding/json" "io/ioutil" "net/http" "github.com/gorilla/handlers" "github.com/gorilla/mux" ) type User struct { Username string `json:"username"` Email string `json:"email"` } func main() { r := mux.NewRouter() //1 routing per 1 handler r.Handle("/health", HealthHandler).Metho...
package database import ( "gorm.io/driver/postgres" "gorm.io/gorm" ) var ( DB *gorm.DB ) func ConnectDB() error { // TODO: Refactor dsn dsn := "host=localhost user=postgres password=postgres dbname=tgtc_user_coupon port=3306 sslmode=disable TimeZone=Asia/Shanghai" db, err := gorm.Open(postgres.Open(dsn), &gor...
package testing import "github.com/selectel/go-selvpcclient/selvpcclient/resell/v2/quotas" // TestGetAllQuotasResponseRaw represents a raw response from the GetAll request. const TestGetAllQuotasResponseRaw = ` { "quotas": { "compute_cores": [ { "region": "ru-1", ...
package git /* #include <git2.h> */ import "C" import ( "runtime" "unsafe" ) type ReferenceType int const ( ReferenceSymbolic ReferenceType = C.GIT_REF_SYMBOLIC ReferenceOid ReferenceType = C.GIT_REF_OID ) type Reference struct { doNotCompare ptr *C.git_reference repo *Repository } type ReferenceColle...
package filter import ( "errors" "io" "strings" "github.com/sensu/sensu-go/cli" "github.com/sensu/sensu-go/cli/commands/helpers" "github.com/sensu/sensu-go/cli/elements/list" "github.com/sensu/sensu-go/types" "github.com/spf13/cobra" ) // InfoCommand defines the 'filter info' subcommand func InfoCommand(cli ...
package main import ( "log" "os" "os/signal" "syscall" nats "github.com/nats-io/nats.go" "github.com/nats-io/stan.go" ) func main() { opts := []nats.Option{ nats.ClientCert("cert.pem", "key.pem"), nats.MaxReconnects(10), } nc, err := nats.Connect("tls://localhost:4443", opts...) if err != nil { log.F...
package gogo import ( "errors" ) var ( ErrHeaderFlushed = errors.New("Response headers have been written!") ErrConfigSection = errors.New("Config section does not exist!") ErrSettingsKey = errors.New("Settings key is duplicated!") ErrHash = errors.New("The hash function does not linked into the binary...
// +build integration package tests import ( "fmt" "os/exec" "regexp" "strings" "testing" "github.com/deis/deis/tests/utils" ) var ( limitsListCmd = "limits:list --app={{.AppName}}" limitsSetMemCmd = "limits:set --app={{.AppName}} web=256M" limitsSetCPUCmd = "limits:set --app={{.AppName}} -c web=51...
package main import "fmt" func main() { d := []string{"Welcome", "for", "Tianjin", "Have", "a", "good", "journey"} insertSlice := []string{"It", "is", "a", "big", "city"} insertSliceIndex := 3 d = append(d[:insertSliceIndex], append(insertSlice, d[insertSliceIndex:]...)...) fmt.Printf("result:%v\n", d) a := []...
package scsprotov1 import ( "encoding/binary" "math" "time" ) func (c *scsv1) handleMessage(cmd byte, deviceid string, payload []byte) { switch cmd { case CMD_KEEPALIVE: fallthrough case CMD_KEEPALIVE_POSITION: model, _, err := readBinString(payload) if err != nil { panic(err) } version, _, err :=...
package data import ( "time" ) type Products struct { Id int Name string Summary string Price float64 Sold int Comments string Score float64 Collected int Category int Specification string //规格json字符串(用于提供给用户选择规格) Squarepic string ...
package hateoas import () // This is a returned type // Error type for REST hateoas type Error struct { Status int `json:"status"` Code int `json:"code"` Property string `json:"property,omitempty"` Message string `json:"message"` DeveloperMessage string `json:"develop...
package testdata import ( "time" "github.com/frk/gosql/internal/testdata/common" ) type SelectWithWhereBlockBetweenQuery struct { Users []*common.User `rel:"test_user:u"` Where struct { CreatedAt struct { After time.Time `sql:"x"` Before time.Time `sql:"y"` } `sql:"u.created_at isbetween"` } }
package helm import ( "fmt" "strings" "time" "github.com/gruntwork-io/terratest/modules/k8s" "github.com/gruntwork-io/terratest/modules/random" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/kumahq/kuma/pkg/config/core" . "github.com/kumahq/k...
package main import "fmt" //func main() { // sum := sum(7,8,8) // fmt.Print(sum) //} // //func sum(params ...int) int { // sum :=0; // for _,i :=range params { // sum +=i // } // return sum //} func main() { cl := colsure() fmt.Println(cl()) fmt.Println(cl()) fmt.Println(cl()) fmt.Println(colsure()) fmt.Printl...
package rtrserver import ( "bytes" "encoding/binary" "errors" "github.com/cpusoft/goutil/belogs" "github.com/cpusoft/goutil/jsonutil" ) func ParseToSerialNotify(buf *bytes.Reader, protocolVersion uint8) (rtrPduModel RtrPduModel, err error) { var sessionId uint16 var serialNumber uint32 var length uint32 //...
package auth import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01200101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:auth.012.001.01 Document"` Message *MoneyMarketSecuredMarketStatisticalReportV01 `xml:"MnyMktScr...
package producers import ( "errors" "os" "testing" "time" c "github.com/pedromss/kafli/config" "github.com/pedromss/kafli/contracts" "github.com/pedromss/kafli/model" ) func TestProduceMode(t *testing.T) { type checker struct { called bool } setChecker := func(idx int, checker *checker) { if checker.c...
package main import ( "fmt" "testing" "time" ) func TestNewClock(t *testing.T) { clock := NewClock() // TODO: finish mocking clock and compare the times } func TestLoadSound(t *testing.T) { }
package main import ( "fmt" "io/ioutil" "log" "os" "os/exec" ) func gen() { loadBaseTemplate() errMsg := loadAllFromDisk() if errMsg != "" { die(errMsg) } // TODO fix me generateAndWriteHTML() // And the rest should work errMsg = copyStatic() if errMsg != "" { die(errMsg) } } // TODO MUST be com...
package middleware import ( "fmt" "net/http" jwt "github.com/dgrijalva/jwt-go" "github.com/dgrijalva/jwt-go/request" "github.com/looyun/feedall/controllers" "github.com/looyun/feedall/models" macaron "gopkg.in/macaron.v1" "gopkg.in/mgo.v2/bson" ) func ValidateJWTToken() macaron.Handler { return func(ctx *ma...
package main import "fmt" type Vector struct { x int y int } type Player struct { ID int Name string } func main() { var v Vector v.x = 1 v.y = 10 fmt.Println(v) fmt.Println("X =", v.x) fmt.Println("Y =", v.y) player1 := Player{ID: 1, Name: "Depa"} fmt.Println(player1.ID) fmt.Println(player1.Name)...
package hw04_lru_cache //nolint:golint,stylecheck import "sync" type Key string type Cache interface { Set(key Key, value interface{}) bool Get(key Key) (interface{}, bool) Clear() } type lruCache struct { sync.Mutex capacity int queue List items map[Key]cacheItem } type cacheItem struct { Key *list...
package encoding import ( "bytes" "encoding/binary" "errors" "io" ) // WriteUint16 writes an uint16 into a byte buffer func WriteUint16(w *bytes.Buffer, i uint16) { w.WriteByte(byte(i >> 8)) w.WriteByte(byte(i)) } // WriteBool writes a boolean value into a byte buffer func WriteBool(w *bytes.Buffer, b bool) { ...