text
stringlengths
11
4.05M
package main import ( "bytes" "compress/gzip" "encoding/json" "io/ioutil" "log" "net/http" "strconv" "strings" ) // ------------------------------------ 获取实时基础数据 func GetDatas() map[string]*GeneralData { gds := make(map[string]*GeneralData) // 获取原始数据 initUrl := "http://nufm.dfcfw.com/EM_Finance2014Numeri...
package controllers import ( "encoding/json" "fmt" "net/http" "../models" "github.com/gorilla/mux" ) func CreatePerson(w http.ResponseWriter, r *http.Request) { person := &models.Person{} json.NewDecoder(r.Body).Decode(person) createdPerson := db.Create(person) var errMessage = createdPerson.Error if cr...
package cmd import ( "fmt" "strconv" "github.com/balaji-dongare/gophercises/CLI/task/dbrepository" "github.com/spf13/cobra" ) var doTask = dbrepository.MarkTaskAsDone //DoTask Marks task as completed var DoTask = &cobra.Command{ Use: "do", Short: "do is a CLI command to mark task as completed ", Run: fun...
package main import ( "fmt" "github.com/PieterD/slides/go-training/reverse" ) func main() { fmt.Println(reverse.Reverse("!dlrow ,olleH")) }
/* if you want to know the number of iterations that are going to be executed in advance, you cannot use the range keyword. The range keyword also works with Go maps, which makes it pretty handy and my preferred way of iteration. One of the biggest problems with arrays is out-of-bounds errors, which means trying to acc...
package geo import ( "math" "net" "github.com/golang/geo/s2" ) type Provider interface { HasCountry() (bool, error) GetCountry(ip net.IP) (country, continent string, netmask int) HasASN() (bool, error) GetASN(net.IP) (asn string, netmask int, err error) HasLocation() (bool, error) GetLocation(ip net.IP) (lo...
package pwd import ( "flag" "fmt" "os" ) var ( flagSet = flag.NewFlagSet("pwd", flag.PanicOnError) helpFlag = flagSet.Bool("help", false, "Show this help") ) //Pwd outputs the current working directory func Pwd(call []string) error { e := flagSet.Parse(call[1:]) if e != nil { return e } if flagSet.NArg(...
package main import ( "bufio" "encoding/csv" "encoding/xml" "fmt" "io/ioutil" "log" "math" "os" "strconv" "strings" "github.com/360EntSecGroup-Skylar/excelize" ) type report struct { XMLName xml.Name `xml:"Report"` Ps []p `xml:"rp>pss>ps"` } type p struct { Number string `xml:"m,attr"` Pric...
package lang import ( "fmt" ) type Shape interface { Draw() } type Rectangle struct { } func (Rectangle) Draw() { fmt.Println("inside rectangle::draw()") } type Square struct { } func (Square) Draw() { fmt.Println("inside square::draw()") } type Circle struct { } func (Circle) Draw() { fmt.Println("inside ...
package hutoma type hutomaChatResponse struct { ChatID string `json:"chatId"` Timestamp int64 `json:"timestamp"` Result struct { Score float64 `json:"score"` Query string `json:"query"` Answer string `json:"answer"` History string `json:"history"` ElapsedTime float64 `json:"...
package models import ( "github.com/astaxie/beego/orm" "time" ) //邀请表 func (a *TokenskyUserInvite) TableName() string { return TokenskyUserInviteTBName() } //用户邀请表 type TokenskyUserInvite struct { Id int `orm:"column(id)"json:"id"form:"id"` //邀请人 From *TokenskyUser `orm:"rel(fk);column(from)"json:"-"form:"-"` ...
package hal import ( "bytes" "encoding/json" "errors" "fmt" ) var ( ErrPropMandatory = errors.New("The href property is mandatory.") ) type link struct { // REQUIRED // Its value is either a URI [RFC3986] or a URI Template [RFC6570].<br> // If the value is a URI Template then the Link Object SHOULD have a /...
package controllers import ( "gomongo/src/database" "gomongo/src/models" "log" "github.com/gin-gonic/gin" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "golang.org/x/crypto/bcrypt" ) func Login(c *gin.Context) { db, client := database.GetDatabase() collection := db.Collecti...
// Copyright 2018-2020 Authors of Cilium // // 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 ag...
// Copyright 2023 Google LLC. All Rights Reserved. // // 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 applica...
package names import ( "fmt" "net" "strconv" "strings" "github.com/pkg/errors" ) func GetLocalClusterName(port uint32) string { return fmt.Sprintf("localhost:%d", port) } func GetSplitClusterName(service string, idx int) string { return fmt.Sprintf("%s-_%d_", service, idx) } func GetPortForLocalClusterName(...
package amqp import ( "context" "errors" "sync" "testing" "github.com/Azure/go-amqp" "github.com/brigadecore/brigade/v2/apiserver/internal/lib/queue" myamqp "github.com/brigadecore/brigade/v2/internal/amqp" "github.com/stretchr/testify/require" ) func TestNewWriterFactory(t *testing.T) { const testAddress =...
package postgress import ( "github.com/aleale2121/Golang-TODO-Hex-DDD/internal/constant/model" "github.com/jinzhu/gorm" ) type NoteRepository struct { conn *gorm.DB } func NewNoteRepository(db *gorm.DB) *NoteRepository { return &NoteRepository{db} } func (noteRepo *NoteRepository) Notes() ([]model.Note, []error...
package lib import "fmt" var ( Age int Name string ) func init() { fmt.Println("lib init") Age = 100 Name = "hello" }
package gogit import ( "encoding/json" "fmt" "github.com/NavenduDuari/goinfo/gogit/utils" ) func getCommit(userName string) []utils.CommitStruct { var commitStructArr []utils.CommitStruct repos := getRepos(userName) go func() { for _, repo := range repos { commitURL := getCommitURL(userName, repo.Name) ...
package functions func argMax(x []float64) int { maxIndex := 0 for i, v := range x { if v > x[maxIndex] { maxIndex = i } } return maxIndex }
package main import ( "fmt" "log" ) type wallet struct{ balance float64 } func newWallet() *wallet { return &wallet{} } func (w *wallet) creditBalance(amount float64) { w.balance += amount log.Println("wallet balance added successfully") } func (w *wallet) debitBalance(amount float64) error { if w.balance < a...
package main import ( "fmt" ) func main() { fmt.Println(maxSubArray([]int{-2, 1, -3, 4, -1, 2, 1, -5, 4})) fmt.Println(maxSubArray([]int{-1})) } func maxSubArray(nums []int) int { max := func(arr ...int) int { mm := arr[0] for _, v := range arr { if v > mm { mm = v } } return mm } dp := ma...
package main import ( "fmt" "sync" "time" ) var ch2 = make(chan int, 3) var wg sync.WaitGroup func main() { wg.Add(2) go productor() go consumer() wg.Wait() } func productor() { defer wg.Done() for i := 0; i < 10; i++ { ch2 <- i fmt.Printf("生产%d\n", i) } close(ch2) //不再发送数据到ch } func consumer() {...
/* ‘…’ 其实是go的一种语法糖。 它的第一个用法主要是用于函数有多个不定参数的情况,可以接受多个不确定数量的参数。 第二个用法是slice可以被打散进行传递。 形参的参数前的三个点,表示可以传0到多个参数 变量后三个点表示将一个切片或数组变成一个一个的元素,即打散. */ //生成md5 md5 := md5.New() io.WriteString(md5, "学生注册实验自动生成账户") MD5Str := hex.EncodeToString(md5.Sum(nil)) fmt.Println(MD5Str) arg := "https://share.todoen.com/mtopic/guide3.html...
package _98_Validate_Binary_Search_Tree import "math" /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func isValidBST(root *TreeNode) bool { return isValidBSTRecursion(root, math.MinInt64, math.MaxInt64) } func isValidBSTRecur...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //684. Redundant Connection //In this problem, a tree is an undirected graph that is connected and has no cycles. //The given input is a graph that sta...
/** * @Author : henry * @Data: 2020-08-13 15:40 * @Note: **/ package routers import ( "github.com/gin-gonic/gin" "github.com/vouchersAPI/app" "net/http" ) type Voucher interface { AddVoucher() SelectVoucher() Voucher } var logger = app.Logger type kisUV struct{} func AddVoucher(c *gin.Context) { // 绑定参数 c...
/* If you don't know what a queen is in chess, it doesn't matter much; it's just a name :) Your input will be a square of arbitrary width and height containing some amount of queens. The input board will look like this (this board has a width and height of 8): ...Q.... ......Q. ..Q..... .......Q .Q...... ....Q... Q....
package models import "github.com/jinzhu/gorm" type Subreddit struct { gorm.Model Name string Subreddit string Posts []Post }
package v1stable import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type Pet struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec PetSpec `json:"spec"` } type PetSpec struct { P...
package config import ( "os" "log" "github.com/go-pg/pg/v10" "github.com/joho/godotenv" ) func ConnectToDB() *pg.DB { err := godotenv.Load(".env") if err != nil { log.Fatalf("Error loading .env file") } db := pg.Connect(&pg.Options{ User: os.Getenv("DB_USERNAME"), Password: os.Getenv("DB_PASSWORD"), ...
package main import ( "flag" "fmt" "github.com/clbanning/mxj" "launchpad.net/xmlpath" "os" "path/filepath" "reflect" ) var myStack = &stack{} var root *xmlpath.Node var report *os.File var matched = make([]string, 50) var skipped = make([]string, 50) var unmatched = make([]string, 50) func main() { sourceFil...
package main import ( "main/api" "time" "github.com/gin-gonic/gin" cors "github.com/itsjamie/gin-cors" ) func main(){ router := gin.Default() //setup CORS midleware Option config := cors.Config{ Origins: "*", Methods: "GET, PUT, POST, DELETE", RequestHeaders: "Origin, Authorization, Conte...
package grpcDemo import ( "encoding/json" "fmt" "testing" "time" "github.com/golang/protobuf/proto" ) type ( Person struct { ID int32 `protobuf:"varint,1,opt,name=id" json:"id,omitempty"` Name string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` } ) var high = int32(1000000) func (p *Perso...
package main import ( "net/http" Bootstrapper "./source/container" "./source/api" ) func main() { var kubeService = Bootstrapper.Initialize() srv := api.New(kubeService) http.ListenAndServe(":8081", srv) }
package collections import ( "testing" "github.com/iotaledger/wasp/packages/kv/dict" "github.com/stretchr/testify/assert" ) func TestBasicArray(t *testing.T) { vars := dict.New() arr := NewArray(vars, "testArray") d1 := []byte("datum1") d2 := []byte("datum2") d3 := []byte("datum3") d4 := []byte("datum4") ...
package rs import ( "math/rand" "reflect" "github.com/renproject/secp256k1" "github.com/renproject/shamir/eea" "github.com/renproject/shamir/poly" "github.com/renproject/surge" ) // Generate implements the quick.Generator interface. func (dec Decoder) Generate(rand *rand.Rand, size int) reflect.Value { n := r...
package models import ( "github.com/astaxie/beego/orm" "time" "tokensky_bg_admin/utils" ) func (a *TokenskyJiguangRegistrationid) TableName() string { return TokenskyJiguangRegistrationidTBName() } //极光地址表 type TokenskyJiguangRegistrationid struct { Id int `orm:"pk;column(id)"json:"id"form:"id"` UserId int `or...
package main import ( "fmt" "log" proto "github.com/nicholasjackson/building-microservices-in-go/chapter6/grpc/proto" context "golang.org/x/net/context" "google.golang.org/grpc" ) func main() { conn, err := grpc.Dial("127.0.0.1:9000", grpc.WithInsecure()) if err != nil { log.Fatal("Unable to create connecti...
package main import ( "fmt" "log" "time" ) type car struct { letter byte plan plan trips chan *trip // new-trip commands arrive on this channel eventTimer *time.Timer nextEvent event lastStop int // current or latest floor stopped at lastStopTime time.Time // time at which the car left, o...
package main import ( "github.com/jmoiron/sqlx" _ "github.com/mattn/go-sqlite3" "log" "sync" ) var db *sqlx.DB var dbonce sync.Once func InitDB() { dbonce.Do(func() { db = sqlx.MustOpen("sqlite3", "awesomego.db") // 创建表 awesome_go_info,先判断库中是否已存在该表 tableCount := 0 db.Get(&tableCount, `select count(*) fr...
package ipns import ( "fmt" "math/rand" "strings" "testing" "time" pb "gx/ipfs/QmVpC4PPSaoqZzWYEnQURnsQagimcWEzNKZouZyd7sNJdZ/go-ipns/pb" ci "gx/ipfs/QmNiJiXwWE3kRhZrC5ej3kSjWHm337pYfhjLGSCDNKJP2s/go-libp2p-crypto" u "gx/ipfs/QmNohiVssaPw3KVLZik59DBVGTSm2dGvYT9eoXt5DQ36Yz/go-ipfs-util" peer "gx/ipfs/QmPJxxD...
package main; import( "github.com/zznop/sploit" "encoding/hex" "fmt" ) func main() { instrs := "mov rcx, r12\n" + "mov rdx, r13\n" + "mov r8, 0x1f\n" + "xor r9, r9\n" + "sub rsp, 0x8\n" ...
package services import ( "errors" "fmt" "github.com/mrdulin/go-rpc-cnode/models" "github.com/mrdulin/go-rpc-cnode/utils/http" ) var ( ErrGetUserByLoginname = errors.New("get user by login name") ErrValidateAccessToken = errors.New("Validate accessToken") ) type ( GetUserByLoginnameArgs struct { Loginname...
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func findFrequentTreeSum(root *TreeNode) []int { m:=make(map[int]int) find(root,m,0) res:=[]int{} max:=0 for k,v:=range m{ if v>max{ max = v ...
// This file was generated for SObject ContentVersion, API Version v43.0 at 2018-07-30 03:47:31.168644141 -0400 EDT m=+17.511907673 package sobjects import ( "fmt" "strings" ) type ContentVersion struct { BaseSObject Checksum string `force:",omitempty"` ContentBodyId string `force:",omite...
package main import ( "encoding/binary" "log" ) func main() { tryLittleEndian() tryBigEndian() tryLittleEndianAppendUint32() } // learnt: // 1. we can print value in hexadecimal using # func tryLittleEndian() { buf := make([]byte, 4) x := 31 log.Printf("%x %X %#x %#X", x, x, x, x) val := 16909060 log.Prin...
package etcd import ( "context" "go.etcd.io/etcd/clientv3" "time" ) /* ETCD服务注册 */ type EtcdRegister struct { client *clientv3.Client lease clientv3.Lease leaseResp *clientv3.LeaseGrantResponse keepAliveChan <-chan *clientv3.LeaseKeepAliveResponse cancelFunc func() // 关闭续租回调 } /* 创建服务...
// Copyright 2015 Google Inc. All rights reserved. // // 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...
package main import ( "flag" "fmt" "os" "github.com/ikaven1024/bolt-cli/cli" "github.com/ikaven1024/bolt-cli/db" "github.com/ikaven1024/bolt-cli/version" ) var ( pPath = flag.String("path", "", "path of db file") pWeb = flag.Bool("web", false, "support web if set") pVersion = flag.Bool("version", fal...
package 排序 import "sort" func kWeakestRows(mat [][]int, k int) []int { units := make([]*Unit, 0) for i := 0; i < len(mat); i++ { units = append(units, &Unit{ Row: i, CountOfSoldier: getCountOfOne(mat[i]), }) } sort.Slice(units, func(i, t int) bool { if units[i].CountOfSoldier == units[t].Co...
package main import ( "bytes" "encoding/json" "net/http" "github.com/NYTimes/gziphandler" assetfs "github.com/elazarl/go-bindata-assetfs" "github.com/fiatjaf/lightningd-gjson-rpc/plugin" "github.com/gorilla/mux" "github.com/gorilla/securecookie" "github.com/rs/cors" ) var err error var scookie = securecooki...
package types import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) var _ sdk.Msg = &MsgCreateOrchestratorAddress{} func NewMsgCreateOrchestratorAddress(validator string, orchestrator string, ethAddress string) *MsgCreateOrchestratorAddress { return &MsgCreateOr...
package handlers import ( "bytes" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/json" "golang-rest/common" "golang-rest/middlewares" "golang-rest/models" "net/http" "net/http/httptest" "testing" ) func SetupRouter() *gin.Engine { db, _ := common.Initialize() router := gin.Default() router.Use(comm...
// Copyright 2017 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 api import ( "net/http" "strings" "github.com/Sirupsen/logrus" "github.com/gorilla/mux" "github.com/pkg/errors" "github.com/rancher/go-rancher/api" "github.com/rancher/longhorn-manager/types" ) type SnapshotHandlers struct { man types.VolumeManager } func (sh *SnapshotHandlers) Create(w http.Respons...
package impl3 import "github.com/sko00o/leetcode-adventure/queue-stack/queue" /* Notes: ○ 用队列模拟栈 § 可以只用一个队列,压栈操作时,判断队列长度是否大于 1, 如果大于1,将n-1个元素出队再入队,以达到将队尾元素排到队头的效果。 出栈操作时,直接出队即可。压栈操作的时间复杂度是 O(n) 。 */ // Queue is a FIFO Data Structure. type Queue struct { queue.SliceQueue } // MyStack is a stack using queue. ...
package service import ( "github.com/SungKing/blogsystem/models/entity" "github.com/SungKing/blogsystem/models/dao" ) type CommentService struct { } var commentDao = new(dao.CommentDao) func (* CommentService)GetOne(id int32) entity.Comment { return commentDao.GetOne(id) } func (* CommentService)QueryBlogCommen...
package sync import ( "time" "github.com/cpusoft/goutil/belogs" "github.com/cpusoft/goutil/xormdb" ) // filePath, is nic dest path, eg: /root/rpki/data/reporrdp/rpki.apnic.cn/ func DelByFilePathDb(filePath string) (err error) { start := time.Now() belogs.Debug("DelByFilePathDb(): filePath:", filePath) if len(f...
// Copyright 2016 Lennart Espe. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE.md file. // Bench is a file patching system using HTTPS and secure file hashing. package main import ( "flag" "fmt" "path/filepath" "github.com/lnsp/bench/lib" "...
package main import ( "fmt" "os" "strconv" ) func main() { fmt.Printf("Hello, World!\n") fmt.Printf("The sum of 2 and 3 is 5.\n") first, _ := strconv.Atoi(os.Args[1]) second, _ := strconv.Atoi(os.Args[2]) sum := first + second fmt.Printf("The sum of %s and %s is %s.", os.Args[1], os.Args[2], strconv.Ito...
package main import ( "encoding/json" "fmt" "strings" "time" _ "walletApi/routers" "walletApi/src/common" "walletApi/src/model" "walletApi/src/service" "github.com/astaxie/beego" "github.com/astaxie/beego/context" "github.com/astaxie/beego/orm" "github.com/astaxie/beego/toolbox" "github.com/beego/i18n" )...
package e2e_build_test import ( "strings" . "github.com/onsi/ginkgo/extensions/table" "github.com/werf/werf/test/pkg/contruntime" "github.com/werf/werf/test/pkg/thirdparty/contruntime/manifest" "github.com/werf/werf/test/pkg/werf" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Buil...
package models import ( "database/sql" "fmt" "github.com/astaxie/beego/logs" _ "github.com/go-sql-driver/mysql" "log" //"github.com/jmoiron/sqlx" ) type MysqlDB struct{ BaseDB MysqlConnector *sql.DB } func (db *MysqlDB) Connect() bool{ db.Host="118.190.207.134" db.Port="3306" db.UserName="rujiaowang_log" ...
package v1 import ( u "MS/apiHelpers" vserv "MS/services/api" "encoding/json" "github.com/gin-gonic/gin" ) func UserList(c *gin.Context) { var userService vserv.UserService err := json.NewDecoder(c.Request.Body).Decode(&userService.User) if err != nil { u.Respond(c.Writer, u.Message(1, "Invalid request")) ...
package win import ( "syscall" "unsafe" ) var ( // Library libgdi32 = syscall.NewLazyDLL("gdi32.dll") //libmsimg32 = syscall.NewLazyDLL("msimg32.dll") // Functions procCreateDC = libgdi32.NewProc("CreateDCW") procCreateCompatibleDC = libgdi32.NewProc("CreateCompatibleDC") procDeleteDC ...
package v1beta1 import ( "github.com/devspace-cloud/devspace/pkg/devspace/config/versions/config" "github.com/devspace-cloud/devspace/pkg/devspace/config/versions/util" next "github.com/devspace-cloud/devspace/pkg/devspace/config/versions/v1beta2" "github.com/devspace-cloud/devspace/pkg/util/log" ) // Upgrade upg...
package ifth import ( "fmt" "log" "testing" ) func InitTest() { InitSlotGenerator(4) _, err := InitMgo("localhost") if err != nil { log.Fatal(err) } log.Println("init ok") } func TestNewUrl(t *testing.T) { InitTest() url := NewUrl("http://test.tickpay.org", false) log.Println(url) } func BenchmarkNewUr...
package configuration import ( "fmt" "os" "path/filepath" "runtime" "testing" "github.com/stretchr/testify/assert" "github.com/authelia/authelia/v4/internal/utils" ) func TestShouldGenerateConfiguration(t *testing.T) { dir := t.TempDir() cfg := filepath.Join(dir, "config.yml") created, err := EnsureConf...
package main import ( "encoding/csv" "errors" "io" "os" "strings" ) func CalculateCopiesFromCsv(path string, applicationID string) (copies int, err error) { input, err := os.Open(path) if err != nil { return } defer input.Close() reader := csv.NewReader(input) firstRecord, err := reader.Read() if err ...
package capsule import ( "fmt" "sync" "github.com/go-redis/redis/v8" "github.com/spf13/viper" ) var redisClients sync.Map //RedisClient new redis client instance func RedisClient(args ...string) (client *redis.Client) { name := "default" if len(args) > 0 { name = args[0] } connection, ok := redisClients....
package main import ( "fmt" "os" "strings" "github.com/cloudfoundry/cli/plugin" "github.com/krujos/usagereport-plugin/apihelper" ) // ExportStructureCmd is this plugin type ExportStructureCmd struct { apiHelper apihelper.CFAPIHelper cli plugin.CliConnection } // Run runs the plugin func (cmd *ExportStr...
package bencode import ( "bytes" "encoding" "fmt" "io" "reflect" "sort" ) // Marshal returns the bencode of v. func Marshal(v interface{}) ([]byte, error) { buf := bytes.Buffer{} e := NewEncoder(&buf) err := e.Encode(v) return buf.Bytes(), err } // Marshaler is the interface implemented by types // that ca...
package problems // BFS // Runtime: 56 ms // Memory Usage: 6.5 MB func canReach(arr []int, start int) bool { var visited = make(map[int]bool) var queue = make([]int, 0, len(arr)) queue = append(queue, start) visited[start] = true for len(queue) != 0 { curr := queue[0] if arr[curr] == 0 { return true } ...
package f import ( "fmt" ) type SecretValueGetter func(name string) string func getKeyVault(name string) string { return fmt.Sprintf("Real: KeyVault Call %s", name) } func GetSecretValue(getter SecretValueGetter, name string) string { return getter(name) } // Usage Sample func main() { fmt.Printf(GetSecretValu...
package graphql import ( "github.com/graphql-go/graphql/gqlerrors" ) // type Schema interface{} // Result has the response, errors and extensions from the resolved schema type Result struct { Data interface{} `json:"data"` Errors []gqlerrors.FormattedError `json:"errors,omitempty"` Exten...
////////////////////////////////////////////////////////////////////// // config.go ////////////////////////////////////////////////////////////////////// package accounts import ( "time" ) const ( CHARSET = "utf8mb4" TABLE_NAME_ACCOUNTS = "accounts" TABLE_NAME_ACCOUNT_META = "account_meta" TABLE_...
package validator import ( "github.com/go-playground/validator/v10" "go.uber.org/zap" "regexp" ) func ValidateEmail(fl validator.FieldLevel) bool { email := fl.Field().String() if _, err := regexp.MatchString(`/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/`, email); err != nil { zap.S().Errorf("邮...
/* Copyright 2018 The HAWQ Team. */ package main import ( "flag" "log" controllerlib "github.com/kubernetes-incubator/apiserver-builder/pkg/controller" "github.com/hawq-cn/apiserver-example/pkg/controller" ) var kubeconfig = flag.String("kubeconfig", "", "path to kubeconfig") func main() { flag.Parse() ...
/* Author: Conor McGrath Student ID: g00291461 Description: A web application using go based on the Eliza Program. */ package main import ( "fmt" "net/http" "math/rand" "regexp" "time" ) func elizaResponse(w http.ResponseWriter, r *http.Request) { input := r.URL.Query().Get("value") if matched, _ := regexp...
package utils import ( "crypto/ecdsa" "crypto/ed25519" "crypto/elliptic" "crypto/rsa" "crypto/x509" "runtime" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestShouldReturnErrWhenX509DirectoryNotExist(t *testing.T) { pool, warnings, errors :=...
package handlers import ( "fmt" "log" "time" "math/rand" "github.com/golang/protobuf/proto" pbd "crazyant.com/deadfat/pbd/hero" oaccount "webapi/account" obean "webapi/bean" . "webapi/common" FYSDK "webapi/fysdk" osession "webapi/session" oskeleton "webapi/skeleton" pkgTrace "webapi/trace" ) func Hand...
package handler import ( "context" "path/filepath" "testing" proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) // LocalNotificationTestSuite 是本地通知单元测试的 Test Suite type LocalNotificationTestSuite struct { suite.S...
package utils import ( "bytes" "context" "fmt" "github.com/riposa/utils/log" "github.com/riposa/utils/errors" "github.com/gin-gonic/gin" "github.com/jinzhu/gorm" "github.com/qiniu/api.v7/auth/qbox" "github.com/qiniu/api.v7/storage" "math" "math/rand" "strings" "time" ) const ( earthRadius = 6378.137 a...
package resdb import ( "context" "github.com/airbloc/airframe/afclient" ) type Model struct { typ string client afclient.Client } func NewModel(client afclient.Client, typ string) Model { return Model{ typ: typ, client: client, } } func (m Model) Get(ctx context.Context, id string) (*afclient.Objec...
package main import ( "fmt" "math" "os" "time" TransposeMatrix "github.com/HungHan1230/GoTesting/TransposeMatrix" MyTestingReadFile "github.com/HungHan1230/GoTesting/MyTestingReadFile" ) func main() { // mainTransposeMatrix() // mainMyTestingReadFile() testDate() } func mainTransposeMatrix() { sample := ...
package core type RepositoryDriver struct { Factory *RepositoryCoreFactory }
package core import ( "errors" _ "log" ) // DcmMetaInfo is to store DICOM meta data. type DcmMetaInfo struct { Preamble []byte // length: 128 Prefix []byte // length: 4 Elements []DcmElement isEndofMetaInfo bool } // ReadOneElement read one DICOM element in meta information. func (meta *...
package main import ( "encoding/json" "errors" "fmt" "github.com/gosexy/redis" "github.com/adarqui/fsnotify" "github.com/adarqui/fsmonitor" "log" "os" "os/exec" "strconv" "strings" "regexp" ) type ResqueArgs struct { FilePath string `json:"filePath"` Event string `json:"event"` } type ResquePacket s...
package oiio import ( "fmt" "os" "path/filepath" "testing" ) var ( OCIO_CONFIG_PATH string ) func init() { // Set the environment to file-based test data config pwd, _ := os.Getwd() pwd, _ = filepath.Abs(pwd) OCIO_CONFIG_PATH = filepath.Join(pwd, "testdata/spi-vfx/config.ocio") if _, err := os.Stat(OCIO_C...
package app import ( "net/http" "github.com/hsson/armit-website/app/handlers" ) type Route struct { Name string Method string Pattern string Authed bool HandlerFunc http.HandlerFunc } type Routes []Route var routes = Routes{ Route{ "Index", "GET", "/", false, ...
package parser import ( "strings" "testing" "github.com/jessejohnston/ProductIngester/product" "github.com/pkg/errors" "github.com/shopspring/decimal" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" ) type parserTestSuite struct { suite.Suite converter Converter } func Test_Parser...
package main import ( "bufio" "fmt" "log" "os" "sort" "strconv" "strings" ) type vertex struct { f int explored bool scc int } var curLabel, numSCC int // Input: directed acyclic graph G = (V, E) in // adjacency-list representation. // Postcondition: the f -values of vertices constitute a // t...
package dal import ( "gorm.io/driver/mysql" "gorm.io/gorm" ) var ( DB *gorm.DB ) func InitDB() { var err error // {user}:{password}@tcp({ip:port})/{database_name}?charset=utf8mb4&parseTime=True&loc=Local dsn := "root:root_password@tcp(127.0.0.1:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local" DB, err =...
package oss_test import ( "github.com/caarlos0/env" . "web-layout/utils/aliyun/oss" ) func getClient() (*Client, error) { cfg := Config{} if err := env.Parse(&cfg); err != nil { return nil, err } return NewClient(cfg) }
package main import ( "fmt" "sync" ) var greetings string var howdyDone chan bool var mutex = &sync.Mutex{} func howdyGreetings() { mutex.Lock() greetings = "Howdy Gopher!" mutex.Unlock() howdyDone <- true } func main() { howdyDone = make(chan bool, 1) go howdyGreetings() mutex.Lock() greetings = "Hello...
package order_notify import ( "context" "fmt" "strings" "time" "tpay_backend/utils" "tpay_backend/payapi/internal/svc" "github.com/tal-tech/go-zero/core/logx" ) type ListenExpKeyHandler struct { logx.Logger svcCtx *svc.ServiceContext } func NewListenExpKeyHandler(svcCtx *svc.ServiceContext) *ListenExpKeyH...
package leetcode import ( "strings" ) // Given a pattern and a string str, find if str follows the same pattern. // Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. // Input: pattern = "abba", str = "dog cat cat dog" // Output: true // Input:patt...
package values import ( "context" "fmt" "github.com/giantswarm/apiextensions-application/api/v1alpha1" "github.com/giantswarm/microerror" "github.com/imdario/mergo" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/giantswarm/app/v7/pkg/key" ) // MergeS...