text
stringlengths
11
4.05M
package viper import( "github.com/spf13/viper" ) func defaultViperVal() { viper.SetDefault("serverPort", ":10000") viper.SetDefault("firestoreAccountKey", "configs/serviceAccountKey.json") viper.SetDefault("host", "localhost") viper.SetDefault("dbPort", 5432) viper.SetDefault("user", "postgres") viper.SetDefau...
package api import "github.com/gin-gonic/gin" func CreateGoods(ctx *gin.Context) { } func DeleteGoods(ctx *gin.Context) { } func UpdateGoods(ctx *gin.Context) { } func GetGoods(ctx *gin.Context) { } func GetAllGoods(ctx *gin.Context) { } func SearchGoods(ctx *gin.Context) { }
package dice import ( "math/rand" "time" ) func Roll(n int) int { if n == 1 { return 0 } return rand.Intn(n) } func init() { rand.Seed(time.Now().Unix()) }
package main type TreeNode struct { Val int Left *TreeNode Right *TreeNode } type pair struct { root *TreeNode depth int } func maxDepth(root *TreeNode) int { if root == nil { return 0 } res := 0 stack := []pair{pair{root, 1}} for len(stack) > 0 { tmp := stack[len(stack)-1] node := tmp.root dep...
// flarmport a library for connecting and reading from FLARM serial port. // // According to the flarm specification, available on: // http://www.ediatec.ch/pdf/FLARM%20Data%20Port%20Specification%20v7.00.pdf // // A usage example: // // flarm, err := flarmport.Open("/dev/ttyS0") // if err != nil { // log.Fatal(err...
package autoscaler import ( "encoding/base64" "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/ec2/ec2iface" "log" "math" "strconv" "strings" "time" ) type EC2ClientIface interface { TerminateInstancesByCount(instances Instances, v InstanceVar...
package main import ( "ims_api_connector" "fmt" ) func main() { connector := ims_api_connector.New("some_username", "some_password", "some.server.com:8000", 5) connector.Authenticate() assets, _ := connector.GetAssets() fmt.Println(assets) }
package ghclient import ( "context" "os" "path/filepath" "testing" "time" "gopkg.in/src-d/go-billy.v4/osfs" git "gopkg.in/src-d/go-git.v4" "github.com/dollarshaveclub/acyl/pkg/memfs" billy "gopkg.in/src-d/go-billy.v4" gitplumb "gopkg.in/src-d/go-git.v4/plumbing" gitcache "gopkg.in/src-d/go-git.v4/plumbing...
package main import ( "context" "log" "time" "github.com/go-redis/redis/v8" ) func testGetAndSetInteger(redisClient *redis.Client) { _, err := redisClient.Set(context.Background(), "dicky", 10, 10*time.Minute).Result() if err != nil { log.Fatalf("error set in cache, err: %v", err) } num, err := redisClient...
package routes import ( "fmt" "net/http" "github.com/davelaursen/idealogue-go/Godeps/_workspace/src/github.com/gorilla/mux" "github.com/davelaursen/idealogue-go/services" ) // RegisterTagRoutes registers the /tags endpoints with the router. func RegisterTagRoutes(r *mux.Router, enc Encoder, tagSvc services.TagSv...
package web import ( "flag" "fmt" "github.com/oceango/di" "github.com/oceango/router" "github.com/spf13/pflag" "github.com/spf13/viper" "io/ioutil" "log" "net/http" "os" ) type Application struct { port string workDir string router *router.Router } func NewApplication(router *router.Router) *Application...
package main import ( "context" "fmt" "github.com/golang/protobuf/proto" "github.com/lemon-cloud-service/lemon-cloud-user/lemon-cloud-user-common/dto" lemon_cloud_user_sdk "github.com/lemon-cloud-service/lemon-cloud-user/lemon-cloud-user-sdk" client "github.com/lemon-cloud-service/lemon-cloud-user/lemon-cloud-us...
package main import ( "fmt" ) func main() { if x := 500; x > 100 { fmt.Println("chis é maior que cem") } else if x < 10 { fmt.Println("chis é menor que déis") } else { fmt.Println("chis não é menor que déis nem maior que cem") } }
package main import ( "database/sql" "errors" "fmt" "github.com/go-redis/redis/v8" ) var Db *sql.DB var redisClient *redis.Client func Exists(rollNo string) (bool, error) { var has bool err := Db.QueryRow("SELECT COUNT(*) FROM User WHERE rollno = ?", rollNo).Scan(&has) if err != nil { return false, errors...
package client import ( "fmt" "io" "net" "os" "os/exec" "github.com/Cloud-Foundations/Dominator/lib/bufwriter" "github.com/Cloud-Foundations/Dominator/lib/errors" "github.com/Cloud-Foundations/Dominator/lib/filesystem" "github.com/Cloud-Foundations/Dominator/lib/filter" "github.com/Cloud-Foundations/Dominat...
package compose import ( "fmt" "strconv" "github.com/kudrykv/latex-yearly-planner/app/components/calendar" "github.com/kudrykv/latex-yearly-planner/app/components/header" "github.com/kudrykv/latex-yearly-planner/app/components/page" "github.com/kudrykv/latex-yearly-planner/app/config" ) func HeaderWeekly(cfg c...
package compute import ( "fmt" "net/http" "net/http/httptest" "testing" ) // Get IP address list by Id (successful). func TestClient_GetIPAddressList_ById_Success(test *testing.T) { testServer := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { writer.Header().Set("...
package hive import ( "bytes" "encoding/json" "net/http" "net/url" ) // ActiveMode defines the active heating/cooling mode type ActiveMode int // ActiveMode values const ( ActiveModeOff ActiveMode = iota ActiveModeHeating ActiveModeCooling ) const ( // ThermostatDefaultMinimum is the default minimum heating...
package main import ( "log" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/andywow/golang-lessons/lesson-calendar/cmd/client/command" "github.com/andywow/golang-lessons/lesson-calendar/internal/client/config" ) var ( rootCmd = &cobra.Command{ Use: "client", Short: "client for grpc api ser...
package main import "fmt" func main() { nums := make([]int,10); for i,_ := range nums { fmt.Scan(&nums[i]) } sum:=calc_sum(nums) avg:=sum/10 fmt.Println(avg) } func calc_sum(array []int) int{ sum:=0; for _,num := range array{ sum=sum+num; } return sum }
package Solution import "math" type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // 这是一道树结构的动态规划题,每个节点可以为三种状态 0 无摄像机 被子节点监控 1有摄像机 2 无摄像机被父节点监控 // 即用dp[root][0] dp[root][1] dp[root][2] 表示三个状态下各自的最优解 为什么不用dp[root] 直接表示 父节点的最优解 因为dp[root] // 的最优解是会被子节点不同状态所影响的。 // 思路采取自下向上的解法 用后续遍历 依次由子节点返...
package main import ( "html/template" "log" "os" ) func main() { // here we call the ParseFiles of the package level tpl, err := template.ParseFiles("one.gmao") if err != nil { log.Fatal(err) } // err = tpl.Execute(os.Stdout, nil) // if err != nil { // log.Fatal(err) // } // here from the type level ...
package setting import ( "github.com/phjt-go/logger" "github.com/spf13/viper" ) // init func init() { // 初始化配置文件 if err := Config(); err != nil { logger.Error("Load configuration failed, ", err) } // 监控配置文件变化并热加载程序 //watchConfig() } // GetString 获取字符串类型的配置 func GetString(params string) string { return vi...
package main import ( "fmt" "time" ) func main() { // t1 := time.Now().UnixNano() // t2 := time.Now().Local().Unix() // fmt.Println(strconv.Itoa(int(t1))) // fmt.Println(t2) for i := 0; i < 50; i++ { fmt.Println(time.Now().Format("20060102150405")) } }
package envdir import ( "fmt" "github.com/imdario/mergo" "github.com/joho/godotenv" "io/ioutil" "os" "os/exec" "path/filepath" ) // according exit codes https://www.unix.com/man-page/debian/8/envdir/ const exitCode = 111 // ReadDir scans the specified directory and returns all environment variables defined in...
package signals // Signal indicates that a system should shut down. type Signal chan error
package main import ( "fmt" "time" ) // A goroutine is a lightweight thread of execution. func f(from string) { for i := 0; i < 3; i++ { fmt.Println(from, ":", i) } } func main() { // running it synchronously. f("direct") // This new goroutine will execute concurrently with the calling one. go f("gorout...
package main import ( "fmt" "strconv" ) /* The obligatory Hello World example. run this with > go run 01_helloworld.go or, compile it and run the binary: >go build 01_helloworld.go > 01_helloword */ func main() { a := []string{"31313", "-1", "0.5", ".2", "-0.5", "t", "2"} for _, i := range a { fmt.Println(...
package git /* #include <git2.h> extern void _go_git_populate_checkout_callbacks(git_checkout_options *opts); */ import "C" import ( "os" "runtime" "unsafe" ) type CheckoutNotifyType uint type CheckoutStrategy uint const ( CheckoutNotifyNone CheckoutNotifyType = C.GIT_CHECKOUT_NOTIFY_NONE CheckoutNotifyCo...
package middlewares import ( "context" "sync" ) var ( logNo int = 1 mu sync.Mutex ) func newTraceID() int { var no int mu.Lock() no = logNo logNo += 1 mu.Unlock() return no } type traceIDKey struct{} func SetTraceID(ctx context.Context, traceID int) context.Context { return context.WithValue(ctx, t...
package main import ( "flag" "sync" "net" "io" "log" "fmt" "strings" "github.com/cheikhshift/gos/core" ) // Data structures to manage // web server instances type StaticHost struct { Lock *sync.RWMutex Cache map[string]int } func NewCache() StaticHost { return StaticHost{Lock: new(sync.RWMutex), Cache: ...
package session import "github.com/ipastushenko/simple-chat/server/services/auth" type ISessionService interface { SignIn(auth.IUserCredentials) (interface{}, bool) SignOut(interface{}) error }
package leetcode func IsValidSudoku(board [][]byte) bool { mp := make(map[byte][]int, 0) for i := 0; i < 9; i++ { for j := 0; j < 9; j++ { if board[i][j] != '.' { mp[board[i][j]] = append(mp[board[i][j]], i*9+j) } } } for _, pos := range mp { for i := 0; i < len(pos); i++ { for j := i + 1; j < l...
package middlewares import ( "github.com/authelia/authelia/v4/internal/authentication" ) // Require1FA check if user has enough permissions to execute the next handler. func Require1FA(next RequestHandler) RequestHandler { return func(ctx *AutheliaCtx) { if s, err := ctx.GetSession(); err != nil || s.Authenticati...
package main import ( "flag" "fmt" "image" "os/signal" "syscall" "time" ) // 256x256 is written to in total but only 160x144 is visible. const ( screenWidth = 256 screenHeight = 256 visibleWidth = 160 visibleHeight = 144 ) // global emulation state var Gb *GameBoy func main() { // init gameboy Gb = ...
package utorrent import ( "bytes" "fmt" "net/http" ) func (c *Client) url(path string) string { if path == "" || path[0:1] != "/" { path = fmt.Sprintf("/%s", path) } if c.token != "" { path = fmt.Sprintf("%s&token=%s", path, c.token) } return fmt.Sprintf("%s%s", c.API, path) } func (c *Client) request(m...
package main import ( _ "github.com/go-sql-driver/mysql" _ "github.com/lib/pq" "log" "github.com/jinzhu/gorm" "fmt" "time" ) type Owner struct{ gorm.Model FirstName string LastName string Books []Book } type Book struct{ gorm.Model Name string PublishDate time.Time OwnerID uint `sql:"index"` Authors...
package main import ( "github.com/freignat91/mlearning/api" "github.com/spf13/cobra" ) // ServerLogsCmd . var ServerLogsCmd = &cobra.Command{ Use: "logs", Short: "server logs toogles", Run: func(cmd *cobra.Command, args []string) { if err := mlCli.serverLogs(cmd, args); err != nil { mlCli.Fatal("Error: %v...
package iteration import "testing" func TestRepeat(t *testing.T) { assertExpectedResult := func(t *testing.T, got, expected string) { if got != expected { t.Errorf("expected %q but got %q", expected, got) } } t.Run("Repeat a 5 times", func(t *testing.T) { repeated := Repeat("a", 5) expected := "aaaaa" ...
package main import ( "flag" ) func main(){ var path, token string flag.StringVar(&path, "p", ".", "生成的README.md文件路径") flag.StringVar(&token, "t", "xxx", "GitHub API access_token") flag.Parse() InitDB() // 启动README.md文件解析任务 StartReadmeParseJob(path, token) signal := make(chan int) <-signal }
package logger import ( "os" "github.com/Sirupsen/logrus" ) var log *logrus.Logger func Init() { log = logrus.New() log.Formatter = new(logrus.TextFormatter) switch os.Getenv("MODE") { case "debug": log.Level = logrus.DebugLevel default: log.Level = logrus.DebugLevel } Info("Logger Successfully Initi...
package utils import ( "html/template" "testing" "github.com/stretchr/testify/assert" ) func TestCompressedContent(t *testing.T) { htmlContent1 := template.HTML(` <html> <body> <h1>Test</h1> <p>CompressedContent</p> </body> </html> `) htmlContent2 := htmlContent1 ...
package lintcode /** * Brute Force * @param k: An integer * @param n: An integer * @return: An integer denote the count of digit k in 1..n */ func digitCounts(k int, n int) int { counter := 0 if k == 0 { counter++ } for i := 1; i <= n; i++ { tmp := i for tmp != 0 { if tmp%10 == k { counter++ }...
package monster import ( "bufio" "encoding/json" "fmt" "io/ioutil" "os" ) type Monster struct { Name string Age int Skill string } func (m *Monster) Store() bool { str, err := json.Marshal(m) if err != nil { fmt.Println("json.Marshal error=", err) return false } fileName, err := os.OpenFile("F:/...
package menu import ( "bufio" "errors" "fmt" "log" "os" "strconv" "strings" "time" ui "github.com/gizak/termui/v3" "github.com/gizak/termui/v3/widgets" "github.com/nsf/termbox-go" ) const resultHeight = 20 const resultWidth = 70 type validCheck func(string) (string, string, bool) // Entry contains all t...
package main import "ms/sun/servises/event_service" func listernAndSaverActions() { for { subParam := event_service.SubParam{ Added_Post_Event: true, Deleted_Post_Event: true, Liked_Post_Event: true, UnLiked_Post_Event: true, Commented_Post_Event: true, UnCommented_Post_Even...
package main import ( "encoding/json" "fmt" ) func main() { // var jsonBlob = []byte(`{"result":0,"dcdn_progress":0,"message":"","root_url":"http://up057.tw11a.filemail.xunlei.com","uri":"request_upload","query_str":"g=22596363b3de40b06f981fb85d82312e8c0ed511&s=12&t=1525689963&ver=1&tid=c28ebf311c2bbe6878c07f98edf...
package main import "fmt" func main() { var x uint8 = 1<<1 | 1<<4 | 1<<7 var y uint8 = 1<<4 | 1<<6 fmt.Printf("%08b\n", x) // 10010010,代表集合 {1, 4, 7} fmt.Printf("%08b\n", y) // 01010000,代表集合 {4, 6} fmt.Printf("%08b\n", x&y) // 00010000,代表交集 {4} fmt.Printf("%08b\n", x|y) // 11010010,代表并集 {1, 4, 6, 7} f...
package tree func sumOfLeftLeaves(root *TreeNode) int { if root == nil { return 0 } if root.Left == nil && root.Right == nil { return 0 } sum := 0 stack := []*TreeNode{root} for len(stack) != 0 { p := stack[len(stack)-1] stack = stack[:len(stack)-1] if p.Left != nil { if p.Left.Left == nil && p.L...
/* Copyright 2020 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 //@todo: implement a database // as you guessed it was hell writing this code type Person struct { Name string Job string Summary string PersonalInfo []*PersonalInfo Skills []string Experience []string Education []string Posts []*Employment } type PersonalI...
package parser import "fmt" // Err represents a generic parser error type Err struct { Err error At Cursor } func (err *Err) Error() string { return fmt.Sprintf("%s at %s", err.Err, err.At.String()) } // ErrUnexpectedToken represents a parser error type ErrUnexpectedToken struct { At Cursor Expected Pat...
/* Package trie implements a trie data-structure similar to the one described by Donald E Knuth in “Programming Perls”. (Communications of the ACM, Vol. 29, No. 6, June 1986, https://cecs.wright.edu/people/faculty/pmateti/Courses/7140/PDF/cwp-knuth-cacm-1986.pdf). The trie is suitable for write-once-read-many-times si...
/* Copyright 2021 RadonDB. 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 distri...
package dto type UserMeditationExercise struct { MeditationExercise MeditationExerciseStarted }
package docker import ( "bufio" "fmt" "github.com/Sirupsen/logrus" dc "github.com/fsouza/go-dockerclient" "github.com/rootsongjc/magpie/utils" "github.com/samalba/dockerclient" "github.com/spf13/viper" "io" "os" "strings" "sync" "time" ) //Yarn docker cluster state type docker_cluster_state struct { clus...
package main import "fmt" func main() { data := []float64{1, 4, 6, 7, 8, 9, 10, 11, 13, 17, 21, 23} n := average(data...) fmt.Println(n) } func average(sf ...float64) float64 { fmt.Println(sf) fmt.Printf("%T \n", sf) var total float64 for _, v := range sf { total += v } return total / float64(len(sf)) } ...
/* Copyright 2021 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, so...
package list // 单链表测试 import "testing" func TestListAppend(t *testing.T) { l := New() h, _ := l.Append("hello") if l.Len() != 1 { t.Errorf("链表长度有误, 期望%d, 实际上是%d", 1, l.Len()) } if l.head.Data != "hello" { t.Errorf("链表数据存储有误, 实际上为: %v", l.head.Data) } if l.head != h || l.tail != h { t.Errorf("链表插入异常, ...
package hive import ( "encoding/json" "github.com/google/uuid" "github.com/stepan-s/ws-bro/log" "io/ioutil" "net/http" ) // AppMessageToEvent A message to app type AppMessageToEvent struct { Aid uuid.UUID Uid uint32 RawMessage []byte } // AppMessageFromEvent A message from app type AppMessageFr...
package oidc import ( "context" "net/url" "time" "github.com/go-crypt/crypt/algorithm" "github.com/golang-jwt/jwt/v5" "github.com/ory/fosite" "github.com/ory/fosite/handler/openid" fjwt "github.com/ory/fosite/token/jwt" "github.com/ory/herodot" "gopkg.in/square/go-jose.v2" "github.com/authelia/authelia/v4...
package main import ( "io" "log" "os" ) var ( Info *log.Logger Warning *log.Logger Error *log.Logger ) func init(){ errFile, err := os.OpenFile("errors.log",os.O_CREATE|os.O_WRONLY|os.O_APPEND,0666) if err!= nil { log.Fatalln("打开日志文件失败:",err) } Info = log.New(os.Stdout,"Info:",log.Ldate | log.Ltime | lo...
package repository import ( "context" "database/sql" "github.com/dheerajgopi/todo-api/models" "github.com/dheerajgopi/todo-api/task" ) type mySQLRepo struct { DB *sql.DB } // New will return new object which implements task.Repository func New(db *sql.DB) task.Repository { return &mySQLRepo{ DB: db, } } ...
package main /** 面试题 02.01. 移除重复节点 编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。 示例1: ``` 输入:[1, 2, 3, 3, 2, 1] 输出:[1, 2, 3] ``` 示例2: ``` 输入:[1, 1, 1, 1, 2] 输出:[1, 2] ``` 提示: - 链表长度在`[0, 20000]`范围内。 - 链表元素在`[0, 20000]`范围内。 */ /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *Lis...
package main import ( "io/ioutil" "fmt" "crypto" "encoding/pem" "crypto/x509" "crypto/rsa" "encoding/base64" "reflect" ) func main() { //读取私钥内容 keyBytes, err := ioutil.ReadFile("static/rsa.key") if err != nil { fmt.Println("read file error") return } fmt.Println("-----------------RSA私钥---------------...
package main import ( "bufio" "log" "os" "strings" ) func main() { f, _ := os.Open("input.txt") defer f.Close() scanner := bufio.NewScanner(f) seats := make([]bool, 977) for scanner.Scan() { text := strings.TrimSpace(scanner.Text()) row := getRow(text[:7], 0, 127) column := getColumn(text[7:], 0, 7) ...
package main import ( "fmt" "io" ) var ( // stack is used to store variable names and values. stack map[string]Value ) func init() { stack = make(map[string]Value) } // Parser represents a parser. type Parser struct { s *Scanner buf struct { t []Token // stack of last read tokens lit []string // s...
package main import ( "fmt" null "gopkg.in/guregu/null.v3" ) type hotdog int func main() { var x int fmt.Println(x) var s string fmt.Println(s) arr := [3]int{} fmt.Println(arr) slicevar := []int{} fmt.Println(slicevar) //intptr := 90 // var x1 hotdog = 56 // nullableInt := Int8fromPtr(*x1) fmt.Printl...
package main import ( "fmt" "math" "os" ) type Vertex struct { X, Y float64 } func (v *Vertex) Hypo () float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) } type MyInt int32 func (v MyInt) double() int32 { return int32(v * 2) } func main() { p := &Vertex{3, 4} fmt.Println(p.Hypo()) fmt.Println(MyInt(32).double...
package zconfig import ( "fmt" "os" "strconv" "strings" ) const ( COMMENT_STRING = "#" EQUAL_STRING = "=" SUBSPLIT_STRING = "::" ) type Configer struct { path string data map[string]string prefix map[string][]string // prefix - subfixs } func InitConfiger(path string) (*Configer, error) { f, err ...
package handlers import ( "bytes" "github.com/go-webauthn/webauthn/protocol" "github.com/go-webauthn/webauthn/webauthn" "github.com/authelia/authelia/v4/internal/middlewares" "github.com/authelia/authelia/v4/internal/model" "github.com/authelia/authelia/v4/internal/regulation" "github.com/authelia/authelia/v4...
package main import "fmt" type hero struct { name string age int power int } //函数参数 func test17(m map[int]hero) { //err //m[102].power = 89 stu := m[102] stu.power = 89 m[102] = stu fmt.Println(m) fmt.Printf("%p\n", m) } func main1701() { //将结构体作为map中的值 value m := make(map[int]hero) //map中的数据不建...
package requests import ( "encoding/json" "testing" walletmodels "github.com/appditto/pippin_nano_wallet/libs/wallet/models" "github.com/mitchellh/mapstructure" "github.com/stretchr/testify/assert" ) func TestEncodeProcessRequest(t *testing.T) { stateBlock := walletmodels.StateBlock{ Type: "state",...
// can't declare a function inside a block package main func main(){ func x(){ } }
package clickhousespanstore import ( "database/sql" "time" "github.com/hashicorp/go-hclog" ) // WriteParams contains parameters that are shared between WriteWorker`s type WriteParams struct { logger hclog.Logger db *sql.DB indexTable TableName spansTable TableName encoding Encoding delay ...
package base import ( "pb/c2s" "pb/s2c" "server" "server/libs/log" "server/libs/rpc" "server/share" "github.com/golang/protobuf/proto" ) type Account struct { SendBuf []byte } func (t *Account) RegisterCallback(s rpc.Servicer) { s.RegisterCallback("SelectUser", t.SelectUser) s.RegisterCallback("CreatePlay...
package main import ( "testing" ) func TestAutoCamelCase(t *testing.T) { checks := []struct { in string out string }{ {"WhatEver", "[WhatEver](/view/WhatEver)"}, {"[AnExampleLink](http://example.com)", "[AnExampleLink](http://example.com)"}, } for _, check := range checks { out := AutoCamelCase([]byt...
package friends import ( "encoding/json" "fmt" "os" ) type DataStore interface { Refresh() error Save() error Marshal() ([]byte, error) Add(Friend) error Delete(name string) bool } // Implements DataStore type FriendStore struct { friends []Friend file string } func NewFriendStore(datafile string) *Fri...
package auth type Plugin struct { }
package main import ( "encoding/binary" "errors" "io" "net" "time" ) var packetIDEnum int32 = 0 func getNewPacketID() int32 { packetIDEnum++ return packetIDEnum } // Client is a minecraft rcon client type Client struct { conn net.Conn isLoggedIn bool } // SendPacket sends rcon packet with packetID, ...
func min(a, b int) int { if a < b { return a } return b } func max(a, b int) int { if a > b { return a } return b } func insert(intervals []Interval, newInterval Interval) []Interval { ret := make([]Interval, 0) idx := 0 for idx < len(intervals) { inv := intervals[idx] if inv.End < newInterval.Start ...
package main import ( "math" "github.com/faiface/pixel" "github.com/faiface/pixel/pixelgl" ) type planet struct { orb *player satellites []*planet ships []*ship shipsProduced float64 shipAngleMod float64 radius float64 sprite *pixelgl.Canvas } func newPlanet(dist, radius, dir float64...
package model import ( "errors" "github.com/mongodb/mongo-go-driver/bson" "github.com/mongodb/mongo-go-driver/bson/primitive" ) // MediaUser ... type MediaUser struct { Model `bson:",inline"` UserID primitive.ObjectID `bson:"user_id"` MediaID primitive.ObjectID `bson:"media_id"` user *User media *Medi...
package controllers import ( "log" "mick/models" "net/http" "text/template" ) func check(err error) { if err != nil { log.Fatal(err) } } type PhotoHandler int func (h PhotoHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") photos := []mo...
/* 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 main import( "os" "fmt" "log" "io" "cloud.google.com/go/bigquery" "google.golang.org/api/iterator" "golang.org/x/net/context" "strings" ) func main(){ if len(os.Args) < 5 { message := "" switch(len(os.Args)){ case 1: message = "Missing 4 args: [1] Google Cloud Project Name [2] Filepath to ...
package carriage import "time" type ( carriage struct { Contract contract `json:"contract"` Nomenclatures []nomenclature `json:"nomenclatures"` } contract struct { Number string `json:"number"` CustomsLink string `json:"customsLink"` From store `json:"from"` Before stor...
package sm import ( "github.com/jinzhu/gorm" "github.com/qor/transition" "github.com/tppgit/we_service/entity/order" ) type Event struct { Obj interface{} Name string } type EventHandler interface { Emit(event Event) } type OrderSateMachine interface { CreateTransaction(from []order.OrderState, to order.Ord...
package game type Game interface { Next() GetCurrentRound() Round }
package main import ( "sort" "github.com/heartchord/jxonline/gamestruct" "github.com/lxn/walk" ) // RoleTaskDataItem : type RoleTaskDataItem struct { DataModelItemBase TaskID string // 数据名称 TaskValue string // 数据内容 } // RoleTaskDataModel : type RoleTaskDataModel struct { DataModelBase ...
// Copyright 2015 Matthew Collins // // 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...
package client import ( "encoding/json" "fmt" "io/ioutil" "log" "math/rand" "github.com/yekhlakov/gojsonrpc/client/transport" "github.com/yekhlakov/gojsonrpc/common" ) // Create a new empty Client func New() *Client { return &Client{ T: &transport.Discard{}, logger: log.New(ioutil.Discard, "", 0), ...
package sgs import ( "encoding/json" "time" "github.com/gorilla/websocket" ) type wsConn struct { clientId int conn *websocket.Conn } func (me *wsConn) Send(cmd Command) error { _log.Dbg("WS send command: 0x%v, 0x%x, %v", cmd.HexID(), cmd.Who, cmd.Payload) text, e := json.Marshal(cmd) if e != nil { r...
package types import ( "encoding/hex" "testing" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/google/uuid" p8e "github.com/provenance-io/provenance/x/metadata/types/p8e" "github.com/stretchr/testify/require" ) func ownerPartyList(addresses ...string) []Party { retval := make([]Party, len(addresses)) f...
package mappers import ( "fmt" "github.com/vfreex/gones/pkg/emulator/memory" "github.com/vfreex/gones/pkg/emulator/rom/ines" ) /* http://wiki.nesdev.com/w/index.php/UxROM PRG ROM capacity 256K/4096K PRG ROM window 16K + 16K fixed PRG RAM capacity None CHR capacity 8K CHR window n/a CPU $8000-$BFFF: 16 KB switchab...
package handler import ( "crypto/sha512" "encoding/base64" "fmt" "golang-api/model" "log" "net/http" "time" ) // HashPassword takes a given HTTP request, and encodes a password string from form data attached to the request into base64, and then hashes in SHA512. Request statistics are also stored in a global s...
// Package transform defines a Transformation representing rigid // plane-transformations and provides constructors for, ways to find the types // of, and ways to simplify Transformations. package transform import ( "fmt" "github.com/jwowillo/viztransform/geometry" ) // Types of Transformations. // // All Transfor...
package database import "loranet20181205/exception" type TbEdConf struct { ID uint EdID uint Boardsn string DevAddr int `gorm:"column:devAddr"` DRstep int `gorm:"column:DRstep"` RX1DRoffset int `gorm:"column:RX1DRoffset"` RX2DataRate int `gorm:"column:RX2DataRate"` RX2FC int...
package gonigsberg func concat(slices ...[]int) []int{ totalLen := 0 for _,v := range slices{ totalLen += len(v) } concatSlice := make([]int, totalLen) copy(concatSlice, slices[0]) start := 0 for i := 1; i < len(slices); i++{ start += len(slices[i-1]) copy(concatSlice[start:], ...
package main import ( "net/url" ) func (api *Api) GetInbox(role string) ([]PullRequest, error) { logger.Debug( "requesting pull requests count from Stash for role '%s'...", role, ) cookies, err := api.authViaWeb() if err != nil { return nil, err } hostURL, _ := url.Parse(api.URL) resource := api.GetRe...