text
stringlengths
11
4.05M
package lox import "fmt" type RuntimeError struct { token Token msg string } func (re *RuntimeError) Error() string { return fmt.Sprintf("line #%d at '%v': '%s'", re.token.Line, re.token.Lexeme, re.msg) } type ParseError RuntimeError func (pe *ParseError) Error() string { if pe.token.Type == TokenTypeEOF { r...
package gears import "time" // DaysAgo judge t, if it is n days ago. func DaysAgo(t time.Time, n int) bool { return time.Now().Unix()-t.Unix() < 24*60*60*int64(n) }
/* 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 routers import ( "hawtech/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.IndexController{}) beego.Router("/index", &controllers.IndexController{}) beego.Router("/about", &controllers.AboutController{}) beego.Router("/case", &controllers.CaseController{}) beego.R...
package main //whr-helen 2019 import ( _ "github.com/go-sql-driver/mysql" "database/sql" "fmt" _"strings" "io/ioutil" "flag" "os" "strings" ) //用户输入配置 var( db_host string //数据库地址 db_port string //数据库端口 db_name string //数据库名称 db_account string //数据库账号 db_pwd string //数据库密码 path string //结构体保存路径 tables s...
package log // Level defines the Severity Level type type Level int // Level Enums const ( first Level = iota Critical Error Warn Notice Info Debug last ) var ( levelName = []string{ "", "Crit", "Error", "Warn", "Note", "Info", "Debug", "", } ) // IsValid returns if the l is valid. func (l...
package idg // Parse will parse a string id func Parse(in string) (id ID, err error) { err = id.parse([]byte(in)) return }
// Copyright The 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 writ...
package main import ( "flag" "fmt" app "github.com/pyama86/openstack-ssh" ) const Version string = "0.1.0" func main() { var versionFlg bool flag.BoolVar(&versionFlg, "v", false, "show version") flag.Parse() if versionFlg { fmt.Println("openstack-ssh version:", Version) return } if flag.Arg(0) == "" {...
package iirepo_stage import ( "github.com/reiver/go-iirepo/logger" "fmt" "io" "os" "path/filepath" ) func storewhere(path string) (srcpath string, dstpath string, dstpathdir string, err error) { iirepo_logger.Debugf("iirepo_stage.storewhere(%q): begin", path) //var srcpath string { var err error srcpa...
package main import ( "database/sql" "encoding/base32" "fmt" "log" "github.com/dgrijalva/jwt-go" "github.com/gorilla/securecookie" _ "github.com/mattn/go-sqlite3" ) func main() { // generate the user hash hash := base32.StdEncoding.EncodeToString( securecookie.GenerateRandomKey(32), ) db, err := sql.O...
// +build darwin dragonfly freebsd netbsd openbsd package nio import ( "log" "syscall" ) func newPoller() poller { return &kqueue{} } // http://eradman.com/posts/kqueue-tcp.html type kqueue struct { kfd int events []syscall.Kevent_t } func (p *kqueue) Open() error { fd, err := syscall.Kqueue() if err != ...
package yousign import ( "encoding/json" "net/http" "time" ) type ServerStampService struct { client *Client } type ServerStamp struct { ID *string `json:"id,omitempty"` File *string `json:"file,omitempty"` Certificate *string `json:"certificate,omitempty"` FileObjects...
// Copyright © 2018 Inanc Gumus // Learn Go Programming Course // License: https://creativecommons.org/licenses/by-nc-sa/4.0/ // // For more tutorials : https://learngoprogramming.com // In-person training : https://www.linkedin.com/in/inancgumus/ // Follow me on twitter: https://twitter.com/inancgumus package main ...
package memory import ( "context" "fmt" "github.com/tomocy/go-todo" "github.com/tomocy/go-todo/infra/rand" ) func NewSessionRepo() *sessionRepo { return new(sessionRepo) } type sessionRepo struct { sess *todo.Session } func (r *sessionRepo) NextID(context.Context) (todo.SessionID, error) { return todo.Sessi...
package main import ( "github.com/hobby-robots/self-driving-car/src/car" "os" "fmt" ) func main() { steering := car.NewSteering(17, 27, 15, 18) //steering := car.DebugSteering() defer steering.Close() path := "/static" if len(os.Args) > 1 { path = os.Args[1] } fmt.Printf("Serving static %s\n", os.Args)...
package handler import ( "fmt" "net/http" "newfeed/flatform/newfeed" "github.com/gin-gonic/gin" ) type newfeedPostRequest struct { Title string `json:"title"` Post string `json:"post"` } func NewFeedPost(feed *newfeed.Repo) gin.HandlerFunc { return func(c *gin.Context) { reqBody := newfeedPostRequest{} ...
package filehelper import ( "fmt" "github.com/go-chassis/go-chassis/pkg/util/fileutil" "github.com/go-yaml/yaml" "io/ioutil" "path/filepath" ) const ( //FileNameGate gate配置文件名 FileNameGate = "gate.yaml" ) //GetConfig 获取配置,configObj必须为指定类型的struct func GetConfig(configObj interface{}, fileName string) error { ...
package types import ( "database/sql/driver" "encoding/json" "fmt" "strconv" "time" ) // BigUint64 is an encapsulated uint64 that can be stored in a database type BigUint64 uint64 // Scan deserialises the object from raw database data func (b *BigUint64) Scan(src interface{}) error { var ( intText string e...
package iirepo_logger import ( "github.com/reiver/go-tmpl" "fmt" "io" "io/ioutil" "strings" ) var ( debugWriter io.Writer ) func init() { debugWriter = ioutil.Discard } func Debug(v ...interface{}) { var builder strings.Builder fmt.Fprint(&builder, v...) builder.WriteRune('\n') io.WriteString(debugWri...
/* 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 distributed under the License ...
package gross var units = map[string]int{ "quarter_of_a_dozen": 3, "half_of_a_dozen": 6, "dozen": 12, "small_gross": 120, "gross": 144, "great_gross": 1728, } // Units stores the Gross Store unit measurements. func Units() map[string]int { return units } // NewBill c...
package sorting type SelectionSort struct { } func (sort *SelectionSort) Sort(a *[]int32) { length := len(*a) for i := 0; i < length; i++ { min := i for j := i + 1; j < length; j++ { min = func() int {if (*a)[min] < (*a)[j] {return min} else {return j}} () } (*a)[i], (*a)[min] = (*a)[min], (*a)[i] } ...
package recursion import ( "github.com/sko00o/leetcode-adventure/nary-tree/treenode" ) type Node = treenode.Node
package roller // Sequence returns numbers from a known sequence. // Intended for use in tests. type Sequence struct { i int seq []int } // WithSequence returns a Roller which will return numbers from a given sequence. func WithSequence(seq []int) Roller { return &Sequence{-1, seq} } // Roll returns the next nu...
package graphql import ( "encoding/json" "fmt" "io/ioutil" "github.com/graphql-go/graphql" ) func ExecuteQuery(query string, schema graphql.Schema) *graphql.Result { result := graphql.Do(graphql.Params{ Schema: schema, RequestString: query, }) if len(result.Errors) > 0 { fmt.Printf("wrong result,...
package main import ( "github.com/davecgh/go-spew/spew" ) // 142. 环形链表 II // 给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。 // 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。 // 说明:不允许修改给定的链表。 // 进阶: // 你是否可以不用额外空间解决此题? // https://leetcode-cn.com/problems/linked-list-cycle-ii/ func main() { node1 ...
package main import ( "fmt" "kaiyan/data" "kaiyan/utils" "net/http" ) //获取作者列表 func authorList(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Token") w.Header().Set("c...
package calculator import "testing" var AddResultSet = []struct{ Input1, Input2, Result int }{{1, 2, 3}, {4, 5, 9}} var SubtractResultSet = []struct{ Input1, Input2, Result int }{{3, 2, 1}, {6, 3, 3}} var MultiplyResultSet = []struct{ Input1, Input2, Result int }{{3, 2, 6}, {6, 3, 18}} func TestAdd(t *testing.T) { ...
package list import ( "runtime" "sync" "testing" ) type DataItem struct { Name string Age int } func NewDataItem(name string, age int) *DataItem { return &DataItem{Name: name, Age: age} } func TestSafeList(t *testing.T) { sl := NewSafeList() // init test length := sl.Len() item := sl.PopBack() items := ...
package mutual func eventLoop(p *process) { debugPrintf("[%d]P%d 启动 eventLoop", p.clock.getTime(), p.me) go func() { for { p.clock.tick() select { case msg := <-p.chans[p.me]: p.handleMsg(msg) case <-p.requestChan: p.handleRequest() case <-p.toCheckRule5Chan: p.handleCheckRule5() } ...
package main import "fmt" func main() { arr := []int{-5, 3, -1, 9} mid := 0 idx := 0 idx = len(arr) / 2 //fmt.Println(mid) if len(arr)%2 == 0 { mid = arr[idx-1] + arr[idx] } else { mid = arr[idx] } if arr[0] == mid && mid == arr[len(arr)-1] { fmt.Println("true") return } else { fmt.Println("...
// ----------------------------------------------------------------------------- // Model package used for encapsulating web model. // ----------------------------------------------------------------------------- package model // ----------------------------------------------------------------------------- // Sensor -...
package entity import ( "time" "github.com/fatih/structs" ) type FromAddress struct { Id int64 TransactionId int64 Address string Tag string Amount string CreatedAt *time.Time } func (p *FromAddress) Map() *map[string]interface{} { m := structs.Map(p) return &m }
// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by the Apache 2.0 // license that can be found in the LICENSE file. // [START package_example_1] package newsletter import ( "reflect" "testing" "google.golang.org/appengine/mail" ) func TestComposeNewsletter(t *testing.T) ...
package dandler import ( "crypto/md5" "fmt" "io/ioutil" "log" "net/http" "net/http/httptest" "net/url" "strconv" "strings" "testing" "time" "github.com/stretchr/testify/assert" ) func TestContentType(t *testing.T) { var testData = []struct { uri string code int md5 st...
package main import ( "fmt" "strings" ) func manipulateFilePath(outPath string) { fmt.Println("\ninputPath", outPath) components := strings.Split(outPath, "/") fmt.Println("\ncomponents", components) fmt.Println("\n\ncomponents[:len(components)-1]", components[:len(components)-1]) outPath = strings.Join(com...
package main import ( "encoding/json" "flag" "fmt" "io/ioutil" "os" "os/signal" "syscall" "github.com/theverything/reminder/pkg/reminder" ) func main() { configPath := flag.String("config", "", "path to reminder config") flag.Parse() if len(*configPath) == 0 { panic("missing config path") } f, err ...
package seev import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document02100101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:seev.021.001.01 Document"` Message *AgentCAMovementConfirmationV01 `xml:"AgtCAMvmntConf"` } func (d *Document...
package friend import ( "fmt" "github.com/stretchr/testify/assert" "spapp/src/commands/user" helper "spapp/src/common/helpers" friendmodels "spapp/src/models/apimodels/friend" usermodels "spapp/src/models/apimodels/user" "strconv" "testing" ) func Test_GetCommonFriends_Ok(t *testing.T){ // Config initConfig...
package main import ( "fmt" ) type TreeNode struct { Val int Left *ListNode Right *ListNode } func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { if root == nil { return root } // 模拟一个队列 que := []*TreeNode{} que = append(que, root) var ret *TreeNode for len(que) != 0 { cur := que[0] que...
package sarama import ( "github.com/lancewf/concurrent" "github.com/Shopify/sarama" "encoding/json" "strconv" "time" "fmt" ) func NewActorConsumer() *concurrent.Actor { return concurrent.NewActor(&actorConsumer{0, 0.0}) } type actorConsumer struct { msgCount int64 total float64 } type GetAverageRequest str...
/* This wasn't originally intended for code-golf, just as a little debugging routine to roughly visualize something "goofy" going on in a model of some (irrelevant here) physical process. But when I saw how surprisingly short it was, compared to my expectations, I just wondered if it can be further shortened. And that...
package gofr import ( "net" "strconv" grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware" grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery" grpc2 "github.com/raybittu/ezgo/pkg/gofr/grpc" "google.golang.org/grpc" ) type grpcServer struct { server *grpc.Server port int } func...
// Package protoform provides functionality to convert // Java POJO's into protobuf messages. package protoform
package event type Reader interface { Run(event chan<- string) }
package kubernetes import ( "strings" "testing" "time" ) func TestReload(t *testing.T) { corefile := ` .:53 { health ready errors log reload kubernetes cluster.local } ` err := LoadCorefile(corefile) if err != nil { t.Fatalf("Could not load corefile: %s"...
package ipproxy import ( "sync/atomic" "time" ) func (p *proxy) trackStats() { ticker := time.NewTicker(p.opts.StatsInterval) defer ticker.Stop() for { select { case <-p.closeCh: return case <-ticker.C: log.Debugf("TCP Origins: %v TCP Clients: %v UDP Conns: %v", p.NumTCPOrigins(), p.NumTCPConns...
package main import ( "encoding/json" "testing" "time" slackbot "github.com/lusis/go-slackbot" slacktest "github.com/lusis/slack-test" slack "github.com/nlopes/slack" "github.com/stretchr/testify/assert" ) func TestGlobalMessageHandler(t *testing.T) { s := slacktest.NewTestServer() s.SetBotName("TestSlackBo...
// Copyright © 2019 The Things Network Foundation, The Things Industries B.V. // // 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 // // Un...
package handlers import ( "git.benfleming.nz/benfleming/gotasks/app/models" "github.com/go-pkgz/auth/token" "github.com/gobuffalo/nulls" "github.com/jinzhu/gorm" "github.com/labstack/echo/v4" ) // AuthRegisterHandler handles the requests to registor a new user // POST /auth/register func AuthRegisterHandler(e ec...
package internal import ( "context" "time" pb "github.com/magodo/shippy-service/consignment/proto/consignment" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" ) type repository interface { Create(*pb.Consignment) error GetAll() ([]*pb.Consignment, error) } type Repository struct { Col...
package Common import ( "strconv" "time" "github.com/andrewz1/gosmpp/Data" "github.com/andrewz1/gosmpp/Exception" "github.com/andrewz1/gosmpp/Utils" ) const ( SMPP_TIME_DATE_FORMAT string = "060102150405" MaxUint uint = ^uint(0) MinUint uint = 0 MaxInt int =...
package main import ( "flag" "fmt" "net/http" "strconv" ) const defaultPort int = 1325 func main() { var flagPort int flag.IntVar(&flagPort, "p", defaultPort, "Webserver listening port") flag.Parse() if flagPort == 0 { flagPort = defaultPort } port := ":" + strconv.Itoa(flagPort) http.HandleFunc("/"...
package prof import ( "net/http" "github.com/gorilla/mux" "gitlab.com/NagByte/Palette/db/wrapper" "gitlab.com/NagByte/Palette/service/auth" "gitlab.com/NagByte/Palette/service/common" "gitlab.com/NagByte/Palette/service/fileServer" ) type profService struct { baseURI string handler http.Handler db wra...
// Copyright 2015 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package webp import ( "fmt" "log" ) func ExampleCBuffer() { cbuf := NewCBuffer(100) defer cbuf.Close() data := cbuf.CData() fmt...
package mock /* Copyright 2018 Bruno Moura <brunotm@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by ...
package calldiv const mathDLLName = "math_x64.dll"
package modifiers_test import ( "net/http" "net/url" "strings" "testing" "github.com/ONSdigital/florence/service/modifiers" . "github.com/smartystreets/goconvey/convey" ) func TestIdentityResponseModifier(t *testing.T) { Convey("Given a response that was successful and all headers are present, all 'set-cook...
package informer import ( "testing" "github.com/stretchr/testify/require" ) func Test_infiniteRingBuffer(t *testing.T) { irb := newInfiniteRingBuffer[int](1) irb.append(1) irb.append(2) irb.append(3) irb.append(4) irb.append(5) var ( v int ok bool ) v, _ = irb.pop() require.Equal(t, 1, v) v, _ = i...
package lexer import ( "testing" "github.com/stretchr/testify/assert" ) func TestLexer(t *testing.T) { data := "var _variable_23_ 23 23.23" lexer := NewLexer(data) tests := []struct { name string token string identifier int }{ { name: "Variable definition", token: "var", ...
package main import ( "github.com/bogdanov-d-a/gocourse2018/workshop2/simplevideoserver/database" log "github.com/sirupsen/logrus" "os" "os/exec" "os/signal" "strconv" "strings" "sync" "syscall" "time" ) const workerCount = 3 func main() { log.SetFormatter(&log.JSONFormatter{}) if file, err := os.OpenFil...
package data import ( "math" ) func (u *Point) Dot(v *Point) float32 { s := float32(0.0) for i := 0; i < len(u.Features); i++ { s += u.Features[i] * v.Features[i] } return s } func (u *Point) L2SquareSubarray(v *Point, a, b int) float32 { s := 0.0 for i := a; i < b; i++ { d := float64(u.Features[i] - v.Fe...
package operators import ( "context" "fmt" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" me...
package dcp import "testing" func Test_romanToDecimal(t *testing.T) { type args struct { roman string } tests := []struct { name string args args want int }{ {"0", args{roman: "XIV"}, 14}, {"1", args{roman: ""}, 0}, {"2", args{roman: "IV"}, 4}, {"3", args{roman: "V"}, 5}, {"4", args{roman: "XIII...
package controllers import ( "net/http" "github.com/gin-gonic/gin" ) //Read: Read transaction data func (this *TransactionController) Read(c *gin.Context) { transactionID := c.Param("transactionId") if transactionID != "" { c.JSON(http.StatusOK, "OK, "+transactionID) } else { c.JSON(http.StatusOK, "OK") }...
package c36_srp import ( "crypto/rand" "crypto/sha256" "math/big" ) type Server struct { email []byte salt []byte key []byte u *big.Int v *big.Int priv *big.Int Pub *big.Int cPub *big.Int } func (obj *Server) computeK() { // S = (A * v**u) ** b % N s1 := new(big.Int).Exp(obj.v, obj.u, N) ...
/* Copyright SecureKey Technologies Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package docutil import ( "testing" "github.com/stretchr/testify/require" ) var sample = []byte("test") func TestGetHash(t *testing.T) { hash, err := GetHash(100) require.NotNil(t, err) require.Contains(t, err...
package database import ( "backend/observer" "fmt" "sync" ) type Observers struct { data map[string][]observer.IObserver lock sync.RWMutex } func (o *Observers) Init() { o.data = map[string][]observer.IObserver{ "CRICKET": {}, "BASEBALL": {}, "FOOTBALL": {}, "SOCCER": {}, "NBA": {}, } } // ...
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "math" "math/rand" "strings" "unicode" "unicode/utf16" "unicode/utf8" "gx/ipfs/QmVcxhXDbXjNoAdmYBWbY1eU67kQ8eZUHjG4mAYZUtZZu3/go-...
package user import ( "encoding/base64" "encoding/json" "golang-demo/api/common" "net/http" "os" "strconv" "time" "github.com/gorilla/mux" ) //UserRegistration : func UserRegistration(w http.ResponseWriter, r *http.Request) { var objRegistration UserInformation var err error if r.Body == nil { common.AP...
package handlers const ( InvalidRequestTitle = "invalid request" InvalidNumberError = "invalid number" )
package main import ( "errors" "fmt" "os" "strings" "github.com/spf13/pflag" ) // ParseStringArgs parse the argument from a string, used for testing func ParseStringArgs(args string) (string, string, string, error) { pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError) return parseArgs(func() {...
package api import ( "net/http" "net/http/httptest" "testing" "github.com/brainly/olowek/stats" ) func TestStatsHandler(t *testing.T) { req, err := http.NewRequest("GET", StatsEndpoint, nil) if err != nil { t.Fatalf("Unexpected error: %s", err) } s := stats.NewStats() rr := httptest.NewRecorder() hand...
package admin_web_interface import ( "fmt" "github.com/kataras/iris" "html/template" ) // This is just an example template may not working at your file system const DefaultTemplatesPath = "../mygopath/src/github.com/kataras/iris/plugins/admin_web_interface/templates/*" type Options struct { // Path the path url ...
package c41_unpadded_rsa import ( "crypto/rand" "math/big" "github.com/vodafon/cryptopals/set5/c39_rsa" ) func Exploit(ciphertext []byte, server *Server) ([]byte, error) { var err error pk := server.PublicKey() s := big.NewInt(0) for s.Cmp(big.NewInt(0)) == 0 { s, err = rand.Int(rand.Reader, pk.N) if err ...
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func printTree(root *TreeNode) [][]string { if root==nil{return nil} h:=height(root) w:=int(math.Pow(2,float64(h)))-1 res:=make([][]string,h) ptree(root,&res,0,w-1...
package lccc_define const FILE_PATH_GENERAL_CONFIG_FILE = "./config.yml"
package router import ( "colorme.vn/core" "colorme.vn/controller/graphql" ) func RegisterGraphQLRouter(context *core.Context) { server := context.Server server.POST("graphql", graphql.GraphQL) //server.GET("graphql", graphql.GraphQL) }
package main import ( "fmt" "github.com/hjcian/ds/queue" ) func main() { a := queue.NewSomethingQueue() fmt.Println(123) a.Push(123) a.Push(456) a.Push(789) fmt.Println(a) }
package syncer import ( "errors" "io/ioutil" "net" "net/http" "net/url" "time" ) type Fetcher interface { Fetch(resourceRelativePath string) ([]byte, error) FetchWithQueries(resourceRelativePath string, queries map[string]string) ([]byte, error) } type HTTPFetcher struct { httpClient http.Client ...
/* * Auction Bid Tracker * * This is an example server for auction bid tracker. * * API version: 1.0.0 * Contact: antony.h@riseup.net * Generated by: OpenAPI Generator (https://openapi-generator.tech) */ package openapi import ( "strconv" "github.com/antonyho/go-auction-example/pkg/auction" ) // DefaultAp...
package flow import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) func onLimitExceededGrpc() error { return status.Errorf(codes.ResourceExhausted, "Bandwidth Limit Exceeded") } func onBadRequestGrpc(err error) error { return status.Errorf(codes.InvalidArgument, err.Error()) } func onStoreEr...
// 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 bean import ( "log" "sync" "time" "runtime/debug" "github.com/astaxie/beego/orm" ) const ( runing = iota + 1 closed buffLen = 1024 backlog = 4096 keeperScan = time.Second ) const ( Once = iota + 1 ) type Cron struct { flag int cron func() } func newCron(f int, c func()) *Cron { return...
package model import ( "github.com/authelia/authelia/v4/internal/utils" ) // UserInfo represents the user information required by the web UI. type UserInfo struct { // The users display name. DisplayName string `db:"-" json:"display_name"` // The preferred 2FA method. Method string `db:"second_factor_method" js...
package artists import ( "encoding/json" "errors" "github.com/tainacleal/go-musixmatch" ) type Client struct { Backend musixmatch.BackendService Key string } func getClient() Client { return Client{Backend: musixmatch.GetBackend(), Key: musixmatch.Key} } func GetByID(id int64) (*musixmatch.Artists, error...
package main import ( "fmt" "io/ioutil" "log" "encoding/json" "net" "net/http" "net/url" "sort" pb "./superroot" "golang.org/x/net/context" "google.golang.org/grpc" "google.golang.org/grpc/reflection" ) const ( port = ":8999" ) // Put your solr service here. var hosts = []string{} type Server struct{}...
package middleware import ( "github.com/labstack/echo" "gitlab.wallstcn.com/matrix/xgbkb/std/logger" ) func LogRequest(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { r := c.Request() logger.Infoln("=========================== New Request Received ===========================") l...
package main import ( "encoding/json" "fmt" "log" "net/http" "time" "github.com/jonmorehouse/gatekeeper/gatekeeper" "github.com/jonmorehouse/gatekeeper/gatekeeper/utils" "github.com/julienschmidt/httprouter" ) type httpError struct { msg string code int } var ( InternalErr = httpError{"INTERNAL_ERROR", ...
package metriccache import ( "fmt" "sync" "github.com/awslabs/k8s-cloudwatch-adapter/pkg/apis/metrics/v1alpha1" "k8s.io/klog" ) // MetricCache holds the loaded metric request info in the system type MetricCache struct { metricMutex sync.RWMutex metricRequests map[string]interface{} metricNames map[stri...
/* Maximum path sum I By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom of the triangle below: 75 95 64 17 47 82 18 35 87 10 20 04 82 4...
package mock import ( "fmt" "github.com/trussworks/sesh/pkg/domain" ) // Log Recorder // LogLine is a mock log line type LogLine struct { Level string Message string Fields domain.LogFields } // LogRecorder is a mock log recorder type LogRecorder struct { domain.LogService lines []LogLine globals doma...
package piscine func reverse(s string, reversed string) string { if s == "" { return reversed } return reverse(s[1:], string(s[0])+reversed) } func StrRev(s string) string { return reverse(s, "") }
package hub import ( "github.com/empirefox/esecend/admin" "github.com/empirefox/esecend/db-service" "github.com/empirefox/esecend/front" ) type orderMgrStateInput struct { order *front.Order claims *admin.Claims chanErr chan error } func (hub *OrderHub) MgrOrderState( order *front.Order, claims *admin.Clai...
package executor import ( "fmt" "io/ioutil" "os" "github.com/alehatsman/mooncake/internal/config" "github.com/alehatsman/mooncake/internal/utils" "github.com/fatih/color" ) func HandleTemplate(step config.Step, ec *ExecutionContext) error { template := step.Template src, err := utils.ExpandPath(template.Src...
package ds type slice struct { arr []int // 仿真底层数组 len int cap int }
package decorator import ( "errors" "fmt" ) type LegacyRecipe struct { } type Decorable interface { Decorate() (string, error) } type NewIngredient struct { recipe Decorable } func (lr *LegacyRecipe) Decorate() (string, error) { return "Legacy recipe with the following ingredients:", nil } func (ni *NewIngre...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-06-06 14:15 # @File : _4_Median_of_Two_Sorted_Arrays.go # @Description : There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assu...
package wappin import ( "github.com/joho/godotenv" ) var ( baseUrl string clientId string ) func init() { loadEnv() } func NewConfig(bURL string, clID string){ baseUrl = bURL clientId = clID } func loadEnv() { err := godotenv.Load() if err != nil { godotenv.Load("./../../.env") } }