text
stringlengths
11
4.05M
package main import ( "bufio" "bytes" "fmt" . "github.com/SrsBusiness/gobjdump" "os" "regexp" "strconv" "strings" ) type FunctionFrame struct { addr uint16 /* Address of frame on stack */ returnAddr uint16 } type Debugger struct { gb *GameBoy breakpoints map[uint16]struct{} /* This is how ...
package jwtpxy import ( "crypto/rsa" "net/http" "net/http/httputil" "net/url" "strings" "time" "github.com/prometheus/client_golang/prometheus" "go.uber.org/zap" ) const HeadersHeader = "JwtPxy-Headers" const StatusHeader = "JwtPxy-Token-Status" const RequireTokenModeHeader = "JwtPxy-Require-Token-Mode" cons...
package ansi // Private two-character escape sequences (allowed by ANSI X3.41-1974) var ( // DECGON graphics on for VT105, DECHTS horiz tab set for LA34/LA120 DECGON = ESC('1') // DECGOFF graphics off VT105, DECCAHT clear all horz tabs LA34/LA120 DECGOFF = ESC('2') // DECVTS set vertical tab for LA34/LA120 DE...
package fakes import ( bmdepl "github.com/cloudfoundry/bosh-micro-cli/deployment" ) func NewFakeReleaseJobRef() bmdepl.ReleaseJobRef { return bmdepl.ReleaseJobRef{ Name: "fake-release-job-ref-name", Release: "fake-release-job-ref-release", } } func NewFakeJob() bmdepl.Job { return bmdepl.Job{ Name: ...
package main import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "time" ) type User struct { gorm.Model //包含ID(默认作为主键),CreateAt,UpdateAt,DeleteAt Name string Age int8 Birthday time.Time Email string `gorm:"type:v...
// Writing a basic HTTP server is easy using the // `net/http` package. package main import ( "encoding/json" "fmt" "log" "time" ) func main() { type FruitBasket struct { Name string Fruit []string ID int64 `json:"ref"` private string // An unexported field is not encoded. Created time.Time...
package config const ( DBUser = "postgres" DBPassword = "password" DBDatabase = "pokemon" DBHost = "postgres-db" DBPort = "5432" GRPCPort = ":9090" HTTPPort = ":8080" BreedServiceAddress ...
package http import ( "bytes" "crypto/hmac" "crypto/sha1" "fmt" "io" "io/ioutil" "github.com/miRemid/mio" ) func ignore(ctx *CQContext) { ctx.JSON(204, nil) } // Signature 消息验证中间件 func (server *Server) signature() mio.HandlerFunc { server.SendLog(Info, "以开启Signature验证, key=%v\n", server.secret) return fun...
/* * @lc app=leetcode.cn id=114 lang=golang * * [114] 二叉树展开为链表 */ package main type TreeNode struct { Val int Left *TreeNode Right *TreeNode } /* 同时进行展开和前序遍历 func flatten(root *TreeNode) { if root == nil { return } stack := []*TreeNode{root} var prev *TreeNode for len(stack) > 0...
package rob func rob(nums []int) int { //state transfer equation: // room num: _ 1 2 3 1 // money:pr,cr 0 _ _ _ _ // :pnr,cr 0 1 2 4 3 // :pr,cnr 0 0 1 2 4 // :pnr,cnr 0 0 0 1 2 // pr: prev rob // pnr: prev not rob // cr: current rob // cnr: current not rob length := len(nums...
// ProjectEuler.net - problem 34 package main import ( "fmt" "strconv" "strings" ) // factorial is the product of all natural numbers 1..n func factorial(n int) int { var x int = 1 var f int = 1 if n == 0 { return f } for ; x <= n; x++ { f = f * x } return f } func con...
package main import ( "bufio" "fmt" "os" "regexp" "strings" "github.com/mattermost/mattermost-server/model" ) const ( // HOST is the domain (and port) for the Mattermost Server HOST = "york.codesigned.co.uk" BOT_USERNAME = "york-55-bot" BOT_PASSWORD = "cible1" TEAM_NAME = "uni-of-york" // CHANNEL_NAME...
package main import ( "fmt" ) func main() { ceiling := 100 sum := 0 sqOfSum := 0 sumOfSq := 0 for i := 1; i <= ceiling; i++ { sumOfSq += i * i sum += i } sqOfSum = sum * sum fmt.Println("Square of sums up to", ceiling, ": ", sqOfSum) fmt.Println("Sum of squares up to", ceiling, ": ", sumOfSq) fmt.Pri...
package entities import ( "testing" "github.com/stretchr/testify/assert" ) func TestNewPlayer(t *testing.T) { // humans humanRoles := []Role{ RoleVillager, RoleSeer, RoleWitch, RoleHunter, RoleCupid, RoleThief, RoleIdiot, RoleGuard, RoleRaven, } for _, role := range humanRoles { p := NewPla...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //718. Maximum Length of Repeated Subarray //Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays. //...
package daos import ( "github.com/constant-money/constant-event/models" "github.com/jinzhu/gorm" ) // ExchangeDAO : struct type ExchangeDAO struct { db *gorm.DB } // InitExchangeDAO : ... func InitExchangeDAO(database *gorm.DB) *ExchangeDAO { return &ExchangeDAO{ db: database, } } // Create : exchange func (...
/* * Copyright 2018, CS Systemes d'Information, http://www.c-s.fr * * 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 requir...
package repo import ( "proximity/config" "proximity/pkg/clients/db" ) // UserRepoInterface ... type UserRepoInterface interface { } // NewUserRepo Create's an instance of a User Repository func NewUserRepo(conf config.IConfig, dbInstances *db.Instances) UserRepoInterface { return &UserRepo{config: conf} } // Use...
package renter import ( "bytes" "sync" "time" "gitlab.com/NebulousLabs/Sia/crypto" "gitlab.com/NebulousLabs/Sia/modules" "gitlab.com/NebulousLabs/errors" ) // fetchChunkState is a helper struct for coordinating goroutines that are // attempting to download a chunk for a fanout streamer. type fetchChunkState st...
package compliance import ( "net/http" "net/url" "github.com/stellar/gateway/protocols" ) // FetchInfoRequest represents a request sent to fetch_info callback type FetchInfoRequest struct { Address string `name:"address" required:""` formRequest protocols.FormRequest } // FromRequest will populate request ...
package main func main() { println("The Ackermann function for m = 3 and n = 4 is ", ackermann(3,4)) } func ackermann(m, n int, a, b bool) int{ println(a); var a = 5; if (m < 0 || n < 0) { println("m and n have to be nonnegative"); return -1 } if (m == 0) { return n+1 } else if n == 0 { return ackerma...
package models import ( "bytes" "errors" "fmt" "html/template" "strconv" ) type TemplateName string func (t TemplateName) String() string { return string(t) } const ( TemplateNameCareteamInvite TemplateName = "careteam_invitation" TemplateNameNoAccount TemplateName = "no_account" Templat...
/* * Copyright 2018-present Open Networking Foundation * * 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 applicabl...
package token import ( "math/rand" "sync" "time" ) type KeyInfo struct { keys map[int64]string mutex sync.Mutex } var keys *KeyInfo const ( base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" SecondDay = 24 * 3600 ) func init() { keys = &KeyInfo{ keys: make(map[int64]string), }...
package mhfpacket import ( "github.com/Andoryuuta/Erupe/network" "github.com/Andoryuuta/Erupe/network/clientctx" "github.com/Andoryuuta/byteframe" ) // MsgMhfCheckDailyCafepoint represents the MSG_MHF_CHECK_DAILY_CAFEPOINT type MsgMhfCheckDailyCafepoint struct { AckHandle uint32 Unk uint32 } // Opcode ret...
package osutil import "os/exec" func Open(path string) error { return exec.Command(openCmd, path).Start() }
package x /* func PBConvPB__Action_To_Action( o *PB_Action) *Action { n := &Action{ ActionId: int ( o.ActionId ), ActorUserId: int ( o.ActorUserId ), ActionType: int ( o.ActionType ), PeerUserId: int ( o.PeerUserId ), PostId: int ( o.PostId ), CommentId: int ( o.CommentId ), ...
package boil import ( "context" "testing" ) func TestSkipHooks(t *testing.T) { t.Parallel() ctx := context.Background() if HooksAreSkipped(ctx) { t.Error("they should not be skipped") } ctx = SkipHooks(ctx) if !HooksAreSkipped(ctx) { t.Error("they should be skipped") } } func TestSkipTimestamps(t *te...
package cloudmessage import ( "github.com/satori/go.uuid" "github.com/tppgit/we_service/core" "github.com/tppgit/we_service/database" "github.com/tppgit/we_service/entity/order" "github.com/tppgit/we_service/log" "github.com/tppgit/we_service/log/field" "time" ) type cloudMessageRepository struct { DB databas...
package week21 //https://leetcode-cn.com/problems/group-anagrams/ func groupAnagrams(strs []string) [][]string { set := make(map[[26]int][]string) for _, s := range strs { set[groupAnagramsCalcHash(s)] = append(set[groupAnagramsCalcHash(s)], s) } ans := make([][]string, 0, len(set)) for _, strings := range set ...
package types const ( User_UnActive = "unactive" User_Active = "active" User_Obsoleted = "obsoleted" User_Type_Guest = "guest" User_Type_Individual = "individual" User_Type_Member = "member" User_Type_Manager = "manager" User_Type_Admin = "admin" ) // 用户 type User struct { Id stri...
package fitbit import ( "testing" "github.com/stretchr/testify/assert" ) func TestGetDevices(t *testing.T) { c := setup_client() id := "" t.Run("GetDevices", func(t *testing.T) { m, _, err := c.GetDevices() if assert.NoError(t, err) { assert.NotEmpty(t, m) id = (*m)[0].ID } }) t.Run("GetAlarms", f...
package cmd import ( "fmt" "github.com/lingrino/vaku/vaku" "github.com/pkg/errors" "github.com/spf13/cobra" ) var pathDestroyCmd = &cobra.Command{ Use: "destroy [path]", Short: "Destroy a vault path (V2 mounts only)", Long: `Destroys a secret at a specified path. Note that this only works on v2 mounts and t...
package keeper_test import ( abci "github.com/tendermint/tendermint/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/irisnet/irismod/modules/oracle/keeper" "github.com/irisnet/irismod/modules/oracle/types" "github.com/irisnet/irismod/modules/service/exported" ) func (suite *KeeperTestSuite) Tes...
package product import ( "github.com/gingerxman/eel" "github.com/gingerxman/ginger-product/business/account" "github.com/gingerxman/ginger-product/business/product" ) type CorpProductCount struct { eel.RestResource } func (this *CorpProductCount) Resource() string { return "product.corp_product_count" } func (...
package main import ( "log" "math" "net/smtp" "time" "github.com/atc0005/go-teams-notify/v2" "bytes" "html/template" "io/ioutil" "os" "os/exec" "os/user" "regexp" "strconv" "strings" ) type Config struct { Period string MaxUsage int } type Reading struct { Hostname string...
package application type applicationOptions struct { // program name ProgramName string // print help required Help bool // path to config file Config string // unrecognized arguments UnrecognizedArgs []string // enable dry run DryRun bool } func (opts *applicationOptions) addUnrecognizedArgument(arg string...
package dto type CreateUserInput struct { Name string `json:"name", validate:"required"` Email string `json:"email" validate:"required,email"` }
package main import ( "fmt" ) func main() { var age int32 fmt.Scanf("%d", &age) if (age % 2 == 1) { fmt.Println("Weird") } else { if age >= 2 && age <= 5 { fmt.Println("Not Weird") } else if age >= 6 && age <= 20 { fmt.Println("Weird") } else if age > 20 { fmt.Println("Not Weird") } } }
package catalog const ( PrometheusRuleKind = "PrometheusRule" ServiceMonitorKind = "ServiceMonitor" PodDisruptionBudgetKind = "PodDisruptionBudget" PriorityClassKind = "PriorityClass" VerticalPodAutoscalerKind = "VerticalPodAutoscaler" ConsoleYAMLSampleKind = "ConsoleYAMLSample" Cons...
package main import ( "flag" "fmt" "os" "time" "github.com/nkbai/goice/stun" "github.com/nkbai/goice/utils" "github.com/nkbai/log" ) func main() { log.Root().SetHandler(log.LvlFilterHandler(log.LvlTrace, utils.MyStreamHandler(os.Stderr))) flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.A...
package cmds // import ( "net/http" "testing" . "github.com/BaritoLog/go-boilerplate/testkit" ) func TestConsulElasticsearch(t *testing.T) { ts := NewTestServer(http.StatusOK, []byte(`[ { "ServiceAddress": "172.17.0.1", "ServicePort": 5000, "ServiceMeta": { "http_schema": "https" } }, { "S...
package classification import ( "config" "dbmanager" "encoding/json" "httprouter" "io" "lebangproto" "logger" "net/http" "processor/common" "strconv" "strings" "gopkg.in/mgo.v2/bson" ) func Init(router *httprouter.Router) { router.POST("/getsubclassification", GetSubClassification) } func GetSubClassif...
package idonia_auth import ( "bitbucket.org/inehealth/idonia-pacs/service/idonia/idonia" "bytes" "encoding/json" "fmt" "github.com/pkg/errors" "github.com/sirupsen/logrus" "io/ioutil" "net/http" "net/url" ) func ApiKeyLogin() (err error) { username := idonia.ApiKey password := idonia.ApiSecret login := &P...
/* Byte-at-a-time ECB decryption (Harder) Take your oracle function from #12. Now generate a random count of random bytes and prepend this string to every plaintext. You are now doing: AES-128-ECB(random-prefix || attacker-controlled || target-bytes, random-key) Same goal: decrypt the target-bytes. Stop and think f...
package parse import ( "errors" "github.com/bitmaelum/bitmaelum-suite/internal/apikey" "github.com/xhit/go-str2duration/v2" "strconv" "strings" "time" ) // ValidDuration gets a time duration string and return the time duration. Accepts single int as days func ValidDuration(ds string) (time.Duration, error) { i...
package todolist import ( "fmt" "os" "regexp" "strconv" "strings" "time" ) type Parser struct{} func (p *Parser) ParseNewTodo(mods []string, todolist *TodoList) *Todo { if len(mods) == 0 { return nil } todo := NewTodo() p.ParseInput(mods, todo, todolist) todolist.AddOrdinal("all", todo) return todo ...
package palindrome import ( "errors" ) const testVersion = 1 const MaxUint = ^uint(0) const MinUint = 0 const MaxInt = int(MaxUint >> 1) const MinInt = -MaxInt - 1 // Given the range `[1, 9]` (both inclusive)... // The smallest palindromic product is `1`. It's factors are `(1, 1)`. // The largest palindromic produ...
package rpc_http_service import ( "math/rand" "ms/sun/shared/base" "ms/sun/shared/x" "time" ) var rpcLogSaveChan = make(chan x.HTTPRPCLog, 1000) func saveToDbLoggs_go() { tick := time.NewTicker(time.Second) var arr []x.HTTPRPCLog for { select { case c := <-rpcLogSaveChan: if rand.Intn(1000) != 500 { ...
/* Copyright 2020 The Qmgo 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, sof...
// 测试不同kv 的读写性能,写入字符串,随机只读一次, 还需要测试重启 // 1. 准备阶段, 灌入数据 // 2. 在指定的 QPS 下测试响应时间 package main import ( "context" "flag" "fmt" "log" "math/rand" "net/http" "os" "os/signal" "path" "sync" "syscall" "time" "github.com/nullne/didactic-couscous/pool" "github.com/nullne/didactic-couscous/util" "github.com/prom...
package main import ( "fmt" "strings" ) func gabungkanKata(kata []string, separator string) { fmt.Println(strings.Join(kata, separator)); // menggabungkan isi array jadi string menggunakan separator } func main() { gabungkanKata([]string{"Ayam", "Kaki", "Balang"}, "---"); }
package server import ( "crawler/errors" "crawler/logger" "encoding/csv" "io" "net/http" "strconv" "strings" "github.com/valyala/fasthttp" ) const CSV_DELIMITER = '\t' func readBody(ctx *fasthttp.RequestCtx) (string, error) { return string(ctx.PostBody()), nil } func validateBody(body string) (string, err...
/* ===================Arrays============================ arrays is one of the most popular topic of data structures because of two reasons: 1.they are simple and easy to understand 2.they are very versatile and can store many different kinds of data. =========Declaration of an array============================ array :=...
package opencagedata import ( "os" "strings" "testing" "github.com/cheekybits/is" ) type UrlTest struct { Query string Params *GeocodeParams Expected string } func TestGeocodeUrl(t *testing.T) { tests := []UrlTest{ UrlTest{ Query: "Steystraat 30", Expected: "https://api.opencagedata.com/geoc...
package main import ( "fmt" ) type S struct{} func getNew() *S { return &S{} } func identity(x *S) *S { return x } func main() { a := getNew() identity(a) var b S identity(&b) c := new(S) identity(c) d := new(S) fmt.Println(d) var e S fmt.Println(&e) }
package hashtable type HashTable interface { Insert(value int) Lookup(value int) bool } type linearList interface { Insert(value int) Lookup(value int) bool } type linearListImpl struct { values []int } func (list *linearListImpl) Insert(value int) { list.values = append(list.values, value) ...
package main import ( "fmt" "regexp" "strings" "io/ioutil" "strconv" ) type Entry struct { min int max int letter rune password string } func parseInput() []Entry { f, err := ioutil.ReadFile("input.txt") if err != nil { panic(err) } lines := strings.Split(string(f), "\n") entries := make([]Entry, 0,...
package main import ( "errors" "fmt" "image" "image/jpeg" "io/ioutil" "log" "os" "path" "time" "github.com/nfnt/resize" "github.com/oliamb/cutter" ) const ( IMAGES_DIR = "images" OUTPUT_DIR = "output" MAX_PIXEL_DIFF_RATIO = 40 DESIRED_DIMENSION = 32 ) func main() { start := ti...
package app import ( "net/http" "time" ) func (a *App) authGet(w http.ResponseWriter, r *http.Request) { s, err := a.getSession(w, r) if err != nil { internalError(w, err, "getting session") return } a.render(w, r, &tmplData{ UserData: getUserData(s), }) } func (a *App) authPost(w http.ResponseWriter, r...
package util import ( "fmt" "sort" "tezos_index/micheline" ) type Uint64Sorter []uint64 func (s Uint64Sorter) Sort() { if !sort.IsSorted(s) { sort.Sort(s) } } func (s Uint64Sorter) Len() int { return len(s) } func (s Uint64Sorter) Less(i, j int) bool { return s[i] < s[j] } func (s Uint64Sorter) Swa...
package main import ( "fmt" "github.com/AJONCODE/Golang-Fundamentals/04_scope/01_package-scope/02_visibility/visible" ) func main() { fmt.Println(visible.MyName) visible.PrintVar() } // Ankit // Ankit // Shikamaru /* fmt.Println(visible.yourName) this will give error : cannot refer to unexported name visib...
/* 实验返回一个json对象,对象里包含字典 */ package main import ( "net/http" "encoding/json" ) type Data struct { Name string `json:"name"` Hobbies []string `json:"hobbies"` } func listHandle(w http.ResponseWriter, r *http.Request) { data := Data{"fcf",[]string{"吃饭","睡觉"}} js, err := json.Marshal(data) if err != nil { ht...
package Services import ( "github.com/gin-gonic/gin" . "icxl/DTO/Requests" . "icxl/Dao" "icxl/Entitys" "unsafe" ) func GetStudents(context *gin.Context) { var accounts []Entitys.Account DB.Find(&accounts) context.IndentedJSON(200,accounts) } func PutStudents(context *gin.Context) { var requestDTO PUTA...
package main import ( "github.com/jroimartin/gocui" "os/exec" "strings" "github.com/danicheeta/ranger/assert" ) var ( CurrentPath = "/home/daniel" lastDirIndex int windows []*Window ) type windowIndex int const ( LSWindow windowIndex = iota BeforeWindow AfterWindow ) func Manager(g *gocui.Gui) ...
package main import ( _ "embed" "os" "text/template" ) // START DATA OMIT type Employee = struct { First, Last, Job string } var data = struct { Company string Employees []Employee }{ "Weave", []Employee{ {"Carson", "Anderson", "Engineer"}, {"Kari", "Anderson", "Engineer"}, {"Tami", "Anderson", "Dog"...
package tests import ( "testing" "github.com/WindomZ/quizzee" "github.com/WindomZ/testify/assert" ) func TestQuiz_Recommend(t *testing.T) { qa, err := quizzee.NewQuiz( "手机生产商诺基亚最初是以生产什么为主?", []string{"耳机", "纸", "杂货"}, ) assert.NoError(t, err) recommend, rates := qa.Recommend() assert.True(t, recommend =...
package domain // Defines which discount rule to apply to certain code type Rule struct { // The product code Code string // The matching rule to be checked against When string // The price transformation when the rule matches PriceExpr string }
package walletcore import ( "errors" "fmt" "github.com/decred/dcrd/dcrutil" "github.com/decred/dcrd/txscript" "github.com/decred/dcrd/wire" "github.com/decred/dcrwallet/wallet/txrules" ) func NewUnsignedTx(inputs []*wire.TxIn, sendAmount int64, destinationAddress string, changeAddress string) (*wire.MsgTx, err...
package http import ( "bytes" "encoding/json" "io" "io/ioutil" "net/http" "time" ) func Get(url string) string { client := http.Client{Timeout: 5 * time.Second} resp, err := client.Get(url) if err != nil { panic(err) } defer resp.Body.Close() var buffer [512]byte result := bytes.NewBuffer(nil) for { ...
package main import ( "bufio" "errors" "fmt" "io" "log" "math/rand" "net" "net/http" "os" "os/exec" "strconv" "strings" "sync" "sync/atomic" "time" ) const ( TESTURL = "https://speed.cloudflare.com/__down?bytes=104857600" TIMEOUT = 10 * time.Second PARALLELS = 20 PINGCOUNT = 10 IPPATH = "ip...
package commands import ( "testing" "github.com/stretchr/testify/assert" ) func Test_ansiColorCode(t *testing.T) { // check we get a nice range of colours assert.Equal(t, FgYellow, ansiColorCode("foo")) assert.Equal(t, FgGreen, ansiColorCode("bar")) assert.Equal(t, FgYellow, ansiColorCode("baz")) assert.Equal...
package sfcli import ( "fmt" "github.com/alecthomas/units" "github.com/solidfire/solidfire-docker-driver/sfapi" "os" "reflect" "strconv" "strings" "text/tabwriter" "unicode/utf8" ) func printStruct(x interface{}) { v := reflect.ValueOf(x) maxL := 10 for i := 0; i < v.NumField(); i++ { name := v.Type().F...
package main import "bufio" import "fmt" import "os" import "strconv" type input struct { m map[int]int } func main() { i := getInput() var pairsCnt = 0 for _, freq := range i.m { pairsCnt += freq / 2 } fmt.Println(pairsCnt) } func getInput() (i input) { scanner := bufio.NewScanner(os.Stdin) scanner.Spli...
package memrepo import ( "github.com/scjalliance/drivestream/commit" "github.com/scjalliance/drivestream/fileversion" "github.com/scjalliance/drivestream/fileview" "github.com/scjalliance/drivestream/resource" ) var _ fileview.Reference = (*FileView)(nil) // FileView is a drivestream file version reference for a...
package envoy import ( "net/http" "strings" "github.com/gorilla/mux" "github.com/pivotal-cf-experimental/envoy/internal/handlers" "github.com/pivotal-cf-experimental/envoy/internal/middleware" ) // NewBrokerHandler returns an http.Handler that can be bound used to // serve HTTP requests for the CloudFoundry ser...
package webui import ( "html/template" "log" "net/http" "path" ) // Data ... type Data struct { Header []string DataFields [][]string } // ShowUI ... func ShowUI(data [][]string, header []string) { fp := path.Join("templates", "index.html") tmpl := template.Must(template.ParseFiles(fp)) http.HandleFunc...
package main import ( "database/sql" "fmt" _"github.com/go-sql-driver/mysql" ) // 定义一个全局的DB,是一个连接池对象 var db *sql.DB func initDB()(err error) { // 连接数据库 dsn := "root:root@tcp(127.0.0.1:3306)/mogu_demo" // 连接MySQL数据库(注意不能使用 := ) db, err = sql.Open("mysql", dsn) if err != nil { fmt.Printf("open %s failed, er...
package guard import "fmt" const errorPrefix = "paniced with " // ErrPanic is thrown with Cancel if no panic trigger is provided to Panic. type ErrPanic struct { Data interface{} } func (err ErrPanic) Error() string { switch v := err.Data.(type) { case error: return fmt.Sprintf("%s%s", errorPrefix, v.Error()) ...
package main import "fmt" func main() { type string1 string type string2 string var name string1 = "zhong" fmt.Println(string2(name)) fmt.Printf("%T\n", name) // main.string1 var alphas = []string1{"a", "b", "c"} fmt.Println(alphas) fmt.Println([]string(alphas)) // 不允许操作 }
package s3fs import ( "encoding/json" "fmt" "github.com/johanhenriksson/montai/mount" ) type Mount struct { *mount.Request Opt S3Options `json:"opt"` stop chan bool } func (mnt *Mount) Path() string { return mnt.Request.Path } func (mnt *Mount) Unmount() { mnt.stop <- true } func newMount(req *mount.Requ...
package main import ( "log" "os" "github.com/streadway/amqp" ) var Connection *amqp.Connection var Channel *amqp.Channel func failOnError(err error, msg string) { if err != nil { log.Fatalf("%s: %s", msg, err) } } func queueInit() { var err error Connection, err = amqp.Dial(os.Getenv("RABBITMQ_DSN")) fa...
package rabbitmq import ( "encoding/json" "github.com/streadway/amqp" ) type RabbitMQ struct { channel *amqp.Channel Name string exchange string } func New(s string) *RabbitMQ { conn,err:=amqp.Dial(s) if err !=nil{ panic(err) } ch,err:=conn.Channel() if err!=nil{ panic(err) } q,err:=ch.QueueDeclare( ...
package mat import ( "github.com/stretchr/testify/assert" "testing" ) func TestStripePatternAtPoint(t *testing.T) { pattern := NewStripePattern(white, black) assert.Equal(t, pattern.A, white) assert.Equal(t, pattern.B, black) } func TestStripeAtConstantY(t *testing.T) { pattern := NewStripePattern(white, black...
package utility import ( "github.com/google/go-containerregistry/pkg/authn" "github.com/google/go-containerregistry/pkg/name" "github.com/google/go-containerregistry/pkg/v1/remote" v1 "k8s.io/api/core/v1" "os" "strings" ) var authOption remote.Option var NewRegistry string const ( registryUser = "REGISTRY...
package example func main() { order, err := CreateOrder("product id", "customer id", "shipment id") if err != nil { panic(err) } quote, err := CreateQuote(order.id) if err != nil { panic(err) } transaction, err := CreateTransaction(order.id) if err != nil { panic(err) } invoice, err := CreateInvoice...
package entity import "github.com/quintans/go-clean-ddd/lib/eventbus" type Core struct { events []eventbus.DomainEvent } func (c *Core) AddEvent(e eventbus.DomainEvent) { c.events = append(c.events, e) } func (c *Core) PopEvents() []eventbus.DomainEvent { events := c.events c.events = nil return events }
package entity import ( "time" "github.com/fatih/structs" ) type Audit struct { Id int64 MerchantId int64 AccountId int64 // 地址账户ID AddressId int64 // 地址ID Chain string // 主链 Token string // 代币 Address string // 交易地址 Tag ...
package physicseditor_box2d import ( "github.com/ByteArena/box2d" "testing" ) const sampleXml = ` <?xml version="1.0" encoding="UTF-8"?> <!-- created with http://www.physicseditor.de --> <bodydef version="1.0"> <bodies> <body name="Zrzut ekranu 2020-08-18 o 15"> <anchorpoint>0.5000,0.5000</anchorpoi...
//~A a //~ #deep //~3 3 98 10 //~+6.400000e+001 +3.140000e+000 +9.700000e+001 +1.000000e+001 //~A //~A a //~ #deep //~3 3 98 10 //~+6.400000e+001 +3.140000e+000 +9.700000e+001 +1.000000e+001 package main func foo(s string) { println(s); } func main() { var x rune = '\n'; println(string(65)...
package main import "fmt" /* formas de declaracion de variables var nombre tipo = valor var nombre = valor nombre:= valor */ func main(){ var string string = "numeros:" fmt.Println(string) var a, b, c int = 1, 2, 3 fmt.Println(a,b,c) fmt.Println("Boleanos:") v...
package main import "fmt" func main() { fmt.Println(findCircleNum([][]int{ {1, 1, 0}, {1, 1, 0}, {0, 0, 1}, })) } type UnionFindSets struct { Parent []int } func NewUnionFind(n int) *UnionFindSets { parent := make([]int, n) for i := range parent { parent[i] = i } return &UnionFindSets{Parent: parent...
package main import ( "testing" "math" ) func TestPowerset(t *testing.T) { nums := []int{1, 2, 3, 4, 5} samples := []func([]int)[][]int{ Powerset1, Powerset2 } for i, sample := range samples { result := sample(nums) if len(result) != int(math.Pow(2, float64(len(nums)))) { t.Errorf("[%d] invalid result: %v...
package validator import ( "errors" "fmt" "os" "path/filepath" ) var ErrNoValidPath = errors.New("no valid path") func LocalPath(localMountPoint string) (bool, error) { absPath, errAbs := filepath.Abs(filepath.Clean(localMountPoint)) if errAbs != nil { return false, fmt.Errorf("no valid path: %w", errAbs) }...
package models type File struct { Id int64 Name string Size string } type Files []*File
package main import "fmt" // 选择排序golang实现 func chooseSort(nums []int) []int { for i := 0; i < len(nums)-1; i++ { for j := i + 1; j < len(nums); j++ { // 如果前面的数字比后面的数字大,那么调整一下顺序 if nums[i] > nums[j] { // 进行数值交换,通过异或运算避免重新开启一个空间保存临时值 nums[j] = nums[i] ^ nums[j] nums[i] = nums[i] ^ nums[j] nums[...
package cmd import ( "log" "math/rand" "os" "path" "time" "github.com/micro/go-micro" "github.com/quickfixgo/enum" "github.com/quickfixgo/field" "github.com/quickfixgo/fix50sp2/newordersingle" "github.com/quickfixgo/quickfix" "github.com/satori/go.uuid" "github.com/shopspring/decimal" "github.com/spf13/c...
package problem0462 import "sort" func minMoves2(nums []int) int { sort.Ints(nums) i := 0 j := len(nums) - 1 ret := 0 for i <= j { ret += nums[j] - nums[i] i++ j-- } return ret }
package main import "github.com/gin-gonic/gin" func initializeRoutes(s *Server) *gin.Engine { r := gin.Default() todos := r.Group("/todos") admin := r.Group("/admin") admin.Use(gin.BasicAuth(gin.Accounts{ "admin": "1234", })) todos.Use(s.AuthTodo) todos.GET("/", s.All) todos.POST("/", s.Create) todos.GET...
// Copyright (c) 2020 Chair of Applied Cryptography, Technische Universität // Darmstadt, Germany. All rights reserved. This file is part of go-perun. Use // of this source code is governed by a MIT-style license that can be found in // the LICENSE file. // Package apps contains Go implementations of apps that are dis...