text
stringlengths
11
4.05M
package main import ( "bufio" "errors" "flag" "fmt" "io/ioutil" "os" "strings" homedir "github.com/mitchellh/go-homedir" ) var ( errAlreadyExists = errors.New("store: word already exists") errDoesntExist = errors.New("store: word does not exist") errNoData = errors.New("entry: contains no data") ...
/* Package vugu provides core functionality including vugu->go codegen and in-browser DOM syncing running in WebAssembly. See http://www.vugu.org/ Since Vugu projects can have both client-side (running in WebAssembly) as well as server-side functionality many of the items in this package are available in both envi...
package main import ( "github.com/gomodule/redigo/redis" ) const LuaScript string = ` local ticket_key = KEYS[1] local ticket_total_key = ARGV[1] local ticket_sold_key = ARGV[2] local ticket_total_nums = tonumber(redis.call('HGET', ticket_key, ticket_total_key)) local ticket_sold_nums = tonumber(redis.call('HGET', t...
package routingproxy import ( "bytes" "io/ioutil" "net/http" "regexp" "strconv" ) // RequestModifier defines a request and response modifying functions // and the regex for the paths for which it should be applied type RequestModifier struct { MatchingPath string DisableEncoding bool RequestModifier fu...
package blockingreader import ( "io" "strings" "testing" "time" "github.com/rwool/ex/test/helpers/goroutinechecker" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestBlockingReader_Cancel(t *testing.T) { defer goroutinechecker.New(t)() h := strings.NewReader("hello") b...
package user import ( "Open_IM/pkg/common/config" "Open_IM/pkg/common/db/mysql_model/im_mysql_model" "Open_IM/pkg/common/log" "Open_IM/pkg/grpc-etcdv3/getcdv3" pbUser "Open_IM/pkg/proto/user" "Open_IM/pkg/utils" "context" "google.golang.org/grpc" "net" "strconv" "strings" ) type userServer struct { rpcPor...
package rest_test import ( "net/http" "net/http/httptest" "net/url" "github.com/go-chi/chi/v5" "github.com/go-playground/errors" "github.com/phogolabs/rest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Decode", func() { var request *http.Request Describe("JSON", func() { ...
package main import ( "fmt" ) func main() { data := map[int]string{1: "go", 2: "java", 3: "javascript"} // 循环遍历元素,返回第一个元素为键,第二元素为值 for key, value := range data { fmt.Printf("%d ---> %s\n", key, value) } // 判断某一个键是否存在 value, ok := data[2] if ok { fmt.Println("键存在,并且值为:...
package etcd import ( "testing" "github.com/quilt/quilt/db" "github.com/stretchr/testify/assert" ) func TestRunLabelOnce(t *testing.T) { t.Parallel() store := newTestMock() conn := db.New() err := runLabelOnce(conn, store) assert.Error(t, err) err = store.Set(labelPath, "", 0) assert.NoError(t, err) c...
/* Copyright TokenID 2017 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 law or agreed to in writi...
package game_map import ( "github.com/steelx/go-rpg-cgm/gui" "github.com/steelx/tilepix" ) func mapTown(gStack *gui.StateStack) MapInfo { gMap, err := tilepix.ReadFile("map_town.tmx") logFatalErr(err) return MapInfo{ Tilemap: gMap, CollisionLayer: 2, CollisionLayerName: "02 Collision", H...
package rpc const ntag = 255 func (c *Client) aqcuireTag() uint8 { if c.tags == nil { c.tags = make(chan uint8, ntag) for i := uint8(0); i < ntag; i++ { c.tags <- i } } return <-c.tags } func (c *Client) releaseTag(tag uint8) { c.tags <- tag }
package logfmt import ( "bytes" "encoding/json" "fmt" "path/filepath" "strings" "unicode" "github.com/bingoohuang/golog/pkg/caller" "github.com/bingoohuang/golog/pkg/gid" "github.com/bingoohuang/golog/pkg/spec" "github.com/bingoohuang/golog/pkg/str" "github.com/bingoohuang/golog/pkg/timex" "github.com/sir...
/* Copyright 2020 Humio https://humio.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 applicable law or agreed to in writing, ...
package bd import ( "context" "log" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) var MongoC = ConectarBD() var clientOptions = options.Client().ApplyURI("mongodb+srv://yoandredb:hV9HhwKHDjQcR3uD@cluster0.enacc.mongodb.net/myFirstDatabase?retryWrites=true&w=majority") /*Cone...
package main import ( "fmt" "strconv" "texas_real_foods/pkg/connectors/web" "texas_real_foods/pkg/utils" updater "texas_real_foods/pkg/auto-updater" ) var ( // create map to house environment variables cfg = utils.NewConfigMapWithValues( map[string]string{ "postgres_ur...
package view import "github.com/maxence-charriere/go-app/v7/pkg/app" // NavbarItem : navigation bar item type NavbarItem struct { Text string Herf string } // Navbar : navigation bar func Navbar(title string, items []NavbarItem) app.UI { return app.Nav().Body( app.Div().Class("nav-wrapper grey darken-4").Body( ...
/* Mubashir needs your help to find the Simple Numbers in a given range. A number X, that has an N amount of digits (which we'll enumerate as d1, d2, ..., dN), is Simple if the following equation holds true: X = d1^1 + d2^2 + ... + dN^N Examples of Simple Numbers: 89 = 8^1 + 9^2 135 = 1^1 + 3^2 + 5^3 Create a fu...
package common import ( "context" "math/rand" ) // Context : 应用程序上下文 type Context struct { Ctx context.Context // 常驻功能 Rand *rand.Rand // 常驻功能 Config *Config // 常驻功能 Log ILogger // 常驻功能 Node INode // 常驻功能 ServerFor...
package mall import ( "context" "github.com/gin-gonic/gin" "github.com/lenuse/mall/handles/admin" "github.com/lenuse/mall/middlewares" "net/http" "time" ) func New() *gin.Engine { app := gin.Default() app.Use(func(c *gin.Context) { ctx, cancel := context.WithTimeout(c.Request.Context(), 8*time.Second) def...
package base58Encrypt import "github.com/btcsuite/btcutil/base58" func Base58Encryption(ver, pubKeyHash, checkSum []byte) string { verAddPubKeyHash := append(ver, pubKeyHash...) data := append(verAddPubKeyHash, checkSum...) encoded := base58.Encode(data) return encoded }
package game import "korok.io/korok/engi" /** 标记并分类游戏对象, 在 Tag (Name) 的基础上再加一个 Label,作为二级分类, 在游戏中,很多时候是需要这样的二级分类的。比如: enemy {bullet, ship} */ type TagComp struct { Name, Label string } // TODO 如何高效的存储和查找tag数据? type TagTable struct { comps []TagComp _map map[uint32]int index, cap int d map[string][]engi.Enti...
package apigen var qIDStr string var paramStr string // WriteToConstantFile - This writes the constants func WriteToConstantFile(apimodel API) { prepareQueryID(apimodel) prepareConstantStr(apimodel) fileContent := qIDStr + paramStr ReplaceFileContent(apimodel.Methods.Detail.FileName.ConstName, "#Replace#", fileCo...
// Created by Yaz Saito on 06/15/12. // Modified by Geert-Johan Riemer, Foize B.V. // TODO: // - travis CI package fifo const chunkSize = 64 // chunks are used to make a queue auto resizeable. type chunk struct { items [chunkSize]interface{} // list of queue'ed items first, last int // po...
package main import "fmt" func main() { var s []byte s = make([]byte, 5, 5) // s == []byte{0, 0, 0, 0, 0} for i := range s { s[i] = byte(i + 3) } printSlice("S", s) t := make([]byte, len(s), (cap(s)+1)*2) // +1 in case cap(s) == 0 for i, v := range s { t[i] = s[i] fmt.Printf("s[%d] = %d\n", i, v) } s...
package rabbitenv import ( "testing" "github.com/streadway/amqp" ) // TestGetConfig tests rabbitenv.GetConfig func TestGetConfig(t *testing.T) { if Config("queue") != "test" { t.Error("Config is incorrect") } } func TestPublish(t *testing.T) { body := "test" msg := amqp.Publishing{ ContentType: "text/pl...
package main import ( "server/controller" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" ginSwagger "github.com/swaggo/gin-swagger" "github.com/swaggo/gin-swagger/swaggerFiles" ) // @title Swagger Example Book API // @version 1.0 // @host localhost:8080 // @BasePath / func main() { engine := gin.Def...
package task import ( "net/http" "github.com/gin-gonic/gin" ) func TaskRegister(r *gin.RouterGroup) { r.POST("/:uuid/done", TaskDone) r.POST("/", TaskCreation) r.GET("/:slug", Retrieve) } func TaskCreation(c *gin.Context) { taskValidator := NewTaskValidator() if err := taskValidator.Bind(c); err != nil { ...
package pacs import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00900102 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:pacs.009.001.02 Document"` Message *FinancialInstitutionCreditTransferV02 `xml:"FinInstnCdtTrf"` } fun...
// Package dnscache provides a simple caching DNS resolver, // mainly designed to work with docker internal resolver. package dnscache import ( "fmt" "io/ioutil" "net" "time" "strings" "github.com/korovkin/limiter" "github.com/miekg/dns" "github.com/sirupsen/logrus" ) var ( DefaultUpstream = "127.0.0...
/* * @lc app=leetcode.cn id=26 lang=golang * * [26] 删除排序数组中的重复项 */ package solution // @lc code=start func removeDuplicates(nums []int) int { n := len(nums) if n < 2 { return n } p := 0 for q := 1; q < n; q++ { for q < n && nums[q] == nums[q-1] { q++ } if q < n { p++ nums[p] = nums[q] } }...
// Test for pointless make() calls. // Package pkg ... package pkg func f() { x := make([]T, 0) // MATCH /var x \[\]T/ y := make([]somepkg.Foo_Bar, 0) // MATCH /var y \[\]somepkg.Foo_Bar/ z = make([]T, 0) // ok, because we don't know where z is declared }
package main func main() { var i1, i2 int var f1, f2 float64 var r1, r2 rune var s1, s2 string var b1, b2 bool var ii1, ii2 = 3, 4 var ff1, ff2 = 3.0, 4.0 var rr1, rr2 = 'r', 's' var bb1, bb2 = true, false var ss1, ss2 = "Hello", "World" var ( iii1, iii2 int fff1, fff2 float64 rrr1, rrr2 rune sss...
package user import ( "database/sql" _ "github.com/lib/pq" ) type UserRepo interface { getAllUsers() ([]*User, error) get(int) (*User, error) create(*User) (*User, error) update(*User) (*User, error) getMatches(int) ([]*User, error) deleteMatch(int, int) (bool, error) } type userRepo struct { connector *sq...
package validator import ( "fmt" "runtime" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/authelia/authelia/v4/internal/configuration/schema" ) func newDefaultConfig() schema.Configuration { config := schema.Configuration{} config.Server.Address = &schema.Ad...
package goxtremio import ( "regexp" xms "github.com/emccode/goxtremio/api/v3" ) type Event *xms.Event //GetEvents returns a list or a specific events filtered by severity, //eventCode, or description func (c *Client) GetEvents( severity, eventCode, descRxPatt string) ([]Event, error) { events, err := c.api.Get...
package repository import ( "database/sql" "fmt" "github.com/DATA-DOG/go-sqlmock" "github.com/beevik/guid" "github.com/jinzhu/gorm" "github.com/radyatamaa/loyalti-go-echo/src/domain/model" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "testing" ...
// Copyright (c) 2018 Andreas Auernhammer. All rights reserved. // Use of this source code is governed by a license that can be // found in the LICENSE file. // +build amd64,!gccgo,!appengine package siv import ( "crypto/aes" "crypto/cipher" "crypto/subtle" "golang.org/x/sys/cpu" ) func polyval(tag *[16]byte, ...
package configuration import ( "io/ioutil" "log" "net/http" ) func GetRobotsHandler(writer http.ResponseWriter, request *http.Request) { writer.Write([]byte(GetRobots())) } func GetRobots() string { content, err := ioutil.ReadFile(Conf.GetFilePath("static/robots.txt")) if err != nil { log.Panicf("Erreur lors...
package main import ( "github.com/gorilla/mux" "encoding/json" "fmt" "net/http" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" ) var db *gorm.db var err error type Person struct { gorm.Model Id string Firstname string Lastname string Age string Add...
package main import ( "encoding/json" "fmt" "regexp" "strings" ) // PrettyPrint prints objects in a readable format for debugging func PrettyPrint(v interface{}) (err error) { b, err := json.MarshalIndent(v, "", " ") if err == nil { fmt.Sprint(string(b)) } return } // Detent removes leading tab from strin...
package runner // This file contains the data structures used by the CUDA package that are used // for when the platform is and is not supported import ( "context" "encoding/json" "fmt" "os" "strconv" "strings" "sync" "time" "github.com/go-stack/stack" "github.com/karlmutch/errors" "github.com/lthibault/...
package main import ( "log" "os" "os/signal" "github.com/sacOO7/gowebsocket" ) func main() { log.Println("Starting up...") interrupt := make(chan os.Signal, 1) // I dont really understand this full yet? signal.Notify(interrupt, os.Interrupt) socket := gowebsocket.New("ws://echo.websocket.org/") socket.OnC...
package components import ( "github.com/GoAdminGroup/go-admin/template/types" "html/template" ) type RowAttribute struct { Name string Content template.HTML types.Attribute } // 盢把计砞竚RowAttribute(struct) func (compo *RowAttribute) SetContent(value template.HTML) types.RowAttribute { compo.Content = value ...
// Copyright 2018 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 service import ( "context" "testing" "time" "github.com/micro/go-micro/client" sample "github.com/ob-vss-ss19/sample-micro-tests/srv/sample/proto" "github.com/stretchr/testify/assert" ) func TestServiceStart(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) go RunService(ctx, t...
package main import ( "encoding/json" "fmt" ) /* 首字母大写:公有 首字母小写:私有 */ type Role struct { Uid []int } type User struct { ID int `json:"id"` // 设置转后的key Name string Role } func main() { var u = User{ ID: 33, Name: "yyx", Role: Role{ Uid: []int{1, 2, 3}, }, } fmt.Printf("%#v -- %T\n", u, u) j...
package main /* * @lc app=leetcode id=84 lang=golang * * [84] Largest Rectangle in Histogram */ // Solution 2: 单调栈(十分类似单调队列) // 只需确保栈中元素是单调递增就好 func largestRectangleArea(heights []int) int { maxArea := 0 stack := make(stack_84, 0, len(heights)) heights = append(heights, -1) // 在尾部加一个元素,确保最后栈中元素被全部...
// Copyright 2023 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 ...
package service import ( "context" "fmt" "sync" "time" "github.com/go-ocf/cloud/cloud2cloud-connector/events" "github.com/go-ocf/cloud/cloud2cloud-gateway/store" pbCQRS "github.com/go-ocf/cloud/resource-aggregate/pb" "github.com/go-ocf/kit/log" kitNetGrpc "github.com/go-ocf/kit/net/grpc" ) type devicesSubsc...
package master import ( "fmt" "net" "server/libs/log" "server/share" "server/util" "time" ) type App struct { Apps map[string]string `json:apps` MustApps []string `json:mustapps` } var ( context *Master ) type Master struct { Agent bool AgentId string Host string Port ...
package delivery import ( "testing" "github.com/stretchr/testify/suite" ) type klineServiceTestSuite struct { baseTestSuite } func TestKlineService(t *testing.T) { suite.Run(t, new(klineServiceTestSuite)) } // https://binance-docs.github.io/apidocs/delivery/en/#kline-candlestick-data func (s *klineServiceTestS...
package main import ( "testing" ) func CopyLocalToRemoteServiceTest(t *testing.T) { t.Error("Hi") }
package ini import ( "bytes" "context" "errors" "fmt" "github.com/saucelabs/saucectl/internal/flags" "github.com/spf13/pflag" "os" "reflect" "strings" "testing" "time" "github.com/AlecAivazis/survey/v2/terminal" "github.com/Netflix/go-expect" "github.com/hinshun/vt10x" "github.com/stretchr/testify/requ...
package main import ( "encoding/json" "log" "net/http" "github.com/gorilla/context" "github.com/slavayssiere/gamename/common" mgo "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) // Player is a player // swagger:response Player type Player struct { ID bson.ObjectId `json:"id" bson:"_id"` FirstName string ...
package aoc2015 import ( "testing" aoc "github.com/janreggie/aoc/internal" "github.com/stretchr/testify/assert" ) func TestDay08(t *testing.T) { assert := assert.New(t) testCases := []aoc.TestCase{ {Input: `""`, Result1: "2", Result2: "4"}, {Input: `"abc"`, Result1: "2", Result2: "4"}, {Input:...
package models import "net/http" type ProjectResponse struct { *Project `json:"project,omitempty"` // We add an additional field to the response here.. such as this // elapsed computed property // Elapsed int64 `json:"elapsed"` } func NewProjectResponse(project *Project) *ProjectResponse { return &ProjectRespon...
package 搜索 // -------------------- 暴力搜索(超时) ----------------- const INF = 1000000000000 func maxSumAfterPartitioning(A []int, K int) int { return getMaxSumAfterPartitioning(A, K) } func getMaxSumAfterPartitioning(A []int, K int) int { if K == 0 { return 0 } if len(A) == 0 { return 0 } maxSum := 0 for i :=...
package interfaces import ( "hello_go/domain" ) // OwnerManager interface for owner manager type OwnerManager interface { GetOwners() map[string]*domain.Owner CreateOwner(ownerID string, name string, address *domain.Address) (*domain.Owner, error) GetOwner(ownerID string) *domain.Owner UpdateOwner(owner *domain....
package leetcode var dx = [4]int{1, -1, 0, 0} var dy = [4]int{0, 0, 1, -1} func floodIsland(grid [][]byte, x int, y int, n int, m int) { grid[x][y] = 'x' var tx, ty int for k := 0; k < 4; k++ { tx = x + dx[k] ty = y + dy[k] if tx >= 0 && ty >= 0 && tx < n && ty < m { if grid[tx][ty] == '0' { continue ...
package netio const ( //服务器状态 默认状态 SERVER_STATUS_DEFAULT int = 0 //服务器状态 初始化 SERVER_STATUS_INITED int = 1 //服务器状态 侦听状态 SERVER_STATUS_LISTENING int = 2 //服务器状态 已经关闭 SERVER_STATUS_CLOSED int = 3 ) const ( //会话状态 初始化 SESSION_STATUS_INIT int = 0 //会话状态 已经连接 SESSION_STATUS_OPEN int = 1 //会话状态 已关闭 SESSION_STA...
package cli import ( "archive/zip" "bufio" "encoding/json" "fmt" "github.com/kohirens/stdlib" "github.com/kohirens/stdlib/log" "io" "io/ioutil" "net/http" "os" "path/filepath" "strings" "text/template" ) const ( MaxTplSize = 1e+7 EmptyFile = ".empty" gitDir = ".git" ) type AnswersJson struct { ...
package bst import ( "errors" "github.com/ag0st/binarytree" "log" ) // BST struct used to store a binary search tree type BST struct { tree *binarytree.BinaryTree crtSize int } type Comparable interface { // CompareTo returns "< 0" if this > other; ">0" if this > other; "0" if this == other CompareTo(other...
package commands import ( "fmt" "log" "os" ) func ChangeDirectory(arguments []string) { if len(arguments) < 2 { fmt.Fprintln(os.Stderr, "Invalid path!") return } if arguments[1] == "$HOME" { homePath, err := os.UserHomeDir() if err != nil { log.Fatal(err) } if err := os.Chdir(homePath); err != n...
package splitter import ( "bufio" "errors" "fmt" "io" "math" "os" "runtime" "time" "github.com/cinus-ue/securekit/common/bytesutil" "github.com/cinus-ue/securekit/common/sync/parallel" "github.com/cinus-ue/securekit/termui/ioprogress" ) type ChunkFile struct { total int64 offset int64 length int64 id...
package merchant import ( "context" "tpay_backend/adminapi/internal/common" "tpay_backend/model" "tpay_backend/adminapi/internal/svc" "tpay_backend/adminapi/internal/types" "github.com/tal-tech/go-zero/core/logx" ) type ModifyMerchantChannelRateLogic struct { logx.Logger ctx context.Context svcCtx *svc....
// Copyright 2016 Walter Schulze // // 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...
package cluster import ( "reflect" "strconv" "testing" "time" "github.com/quilt/quilt/cluster/acl" "github.com/quilt/quilt/cluster/machine" "github.com/quilt/quilt/db" "github.com/quilt/quilt/stitch" "github.com/stretchr/testify/assert" ) var FakeAmazon db.Provider = "FakeAmazon" var FakeVagrant db.Provider...
package controllers import ( "FinalProject/BlogApi/models" "github.com/astaxie/beego" ) // Operations about object type ObjectController struct { beego.Controller } // @Title Create // @Description create object // @Param body body models.Object true "The object content" // @Success 200 {string} models.Object...
package test import ( "fmt" "testing" "goStudy/lib/g" ) func Test_is_zero(t *testing.T) { i := 0 fmt.Println(g.IsZero(&i)) } func Test_isZeroAll(t *testing.T) { fmt.Println(g.IsZeroAll()) }
package main import ( "flag" "fmt" "io" "io/ioutil" "math/rand" "net/http" "sync/atomic" ) var count int64 var ch = make(chan (int)) func handler(res http.ResponseWriter, req *http.Request) { atomic.AddInt64(&count, 1) body, _ := ioutil.ReadAll(req.Body) fmt.Println(string(body)) reses := []string{"succes...
package main_camera import ( util "github.com/verlandz/clustering-phone/utility" "os" "strconv" "strings" ) const ( DEFAULT_PATH = "main_camera/main_camera" INPUT_PATH = DEFAULT_PATH + ".in" OUTPUT_PATH = DEFAULT_PATH + ".out" ) var ( arr []float64 mean = 0.000 valid = 0.00 def = -1.00 ) func Cle...
package identity import ( "fmt" "log" "strings" "github.com/aws/aws-sdk-go/aws/arn" "github.com/databrickslabs/databricks-terraform/common" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func ResourceGroupInstanceProfile() *schema.Resource { return &schema.Resource{ Create: resourceGroupInst...
package tls import ( "crypto/x509" "crypto/x509/pkix" "net" "testing" "github.com/stretchr/testify/assert" ) func TestSignedCertKeyGenerate(t *testing.T) { tests := []struct { name string certCfg *CertCfg filenameBase string certFileName string appendParent AppendParentChoice errString...
package osc import ( "encoding/json" "io/ioutil" "net/http" "strconv" "strings" ) type Client struct { Url string Response *http.Response } func NewClient(url string) (client *Client, error error) { client = new(Client) client.Url = url return } type Endpoints struct { HttpPort *int HttpUpd...
package main import ( "fmt" "sync" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/ec2/ec2iface" "github.com/prometheus/client_golang/prometheus" log "github.com/sirupsen/logrus" "k8s.io/api/core/v1" ) ...
package setZeroes import "testing" func Test_setZeroes(t *testing.T) { type args struct { matrix [][]int } tests := []struct { name string args args want [][]int }{ // TODO: Add test cases. { name: "first", args: args{ matrix: [][]int{ {1, 1, 1}, {1, 0, 1}, {1, 1, 1}, }, ...
package testing import ( "errors" surveypkg "github.com/devspace-cloud/devspace/pkg/util/survey" ) // FakeSurvey is a fake survey that just returns predefined strings type FakeSurvey struct { nextAnswers []string } // NewFakeSurvey creates a new fake survey func NewFakeSurvey() *FakeSurvey { return &FakeSurvey{...
package http import ( types "github.com/queueup-dev/qup-types" ) func Delete( client Client, url string, body types.PayloadWriter, headers *Headers, ) (*Response, error) { return Request(client, "DELETE", url, headers, body) } func Get( client Client, url string, headers *Headers, ) (*Response, error) { re...
package greetings import ( "errors" "fmt" "math/rand" "time" ) // This function takes a name parameter whose type is string // This function also returns a string // In Go, a function that starts with a capital letter can be called by a function not in the same package (exported name) func Hello(name string) (str...
/* Given an array A of distinct integers sorted in ascending order, return the smallest index i that satisfies A[i] == i. Return -1 if no such i exists. Example 1: Input: [-10,-5,0,3,7] Output: 3 Explanation: For the given array, A[0] = -10, A[1] = -5, A[2] = 0, A[3] = 3, thus the output is 3. Example 2: Input: ...
package oidc import ( "context" "time" "github.com/ory/fosite" "github.com/ory/fosite/handler/oauth2" "github.com/ory/x/errorsx" ) // ClientCredentialsGrantHandler handles access requests for the Client Credentials Flow. type ClientCredentialsGrantHandler struct { *oauth2.HandleHelper Config interface { fos...
// Package utils Common Strcutres, Constants etc that are being used in other packages package utils import ( "time" "github.com/chaincode/demo-network/pkg/core/status" "github.com/s7techlab/cckit/router" ) // MetaData Strcuture: Contains the common fields which are used in all other Structures type MetaData str...
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use ...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //257. Binary Tree Paths //Given a binary tree, return all root-to-leaf paths. //For example, given the following binary tree: // 1 // / \ //2 ...
package main import ( "fmt" "github.com/mombe090/utils/mongo_utils" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "log" ) const ( databaseName = "test" collectionName = "test-mongo_utils-go-driver" ) type Test struct { ID string `json:"id" bson:"_id"` Name string `json:"...
// CookieJar - A contestant's algorithm toolbox // Copyright (c) 2013 Peter Szilagyi. All rights reserved. // // CookieJar is dual licensed: use of this source code is governed by a BSD // license that can be found in the LICENSE file. Alternatively, the CookieJar // toolbox may be used in accordance with the terms and...
package tests import ( mock "HttpBigFilesServer/MainApplication/test/mock_postgres" "github.com/stretchr/testify/assert" "testing" ) func TestGet(t *testing.T) { db, r := mock.MockFileDB() query := mock.MockFile(db) query.On("Where", "id=?", mock.FileInfoTest.Id).Return(query) query.On("Select").Return(nil) ...
package main import ( "os" "github.com/jinmukeji/jiujiantang-services/jinmuid/config" handler "github.com/jinmukeji/jiujiantang-services/jinmuid/handler" "github.com/jinmukeji/jiujiantang-services/jinmuid/mysqldb" jinmuMysql "github.com/jinmukeji/jiujiantang-services/jinmuid/mysqldb" logger "github.com/jinmukej...
package hash import ( "bytes" "crypto/md5" "crypto/sha1" "crypto/sha256" "crypto/sha512" "encoding/gob" "fmt" "hash" "io" ) var ( gobFormat bool = false ) func SetGobFormat(flag bool) { gobFormat = flag } func New(name string) hash.Hash { switch name { case "md5": return md5.New() case "sha1": ret...
package piscine func AlphaCount(str string) int { var count int = 0 for _, chars := range str { if (chars >= 'A' && chars <= 'Z') || (chars >= 'a' && chars <= 'z') { count++ } } return count }
package main import "fmt" // https://leetcode-cn.com/problems/powx-n/ func myPow(x float64, n int) float64 { if n == 0 { return 1.0 } if n < 0 { return myPow(1.0/x, -n) } if n == 1 { return x } i, res := 1, x for ; i*2 <= n; i *= 2 { res *= res } return res * myPow(x, n-i) } func main() { cases ...
package metrics import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" io_prometheus_client "github.com/prometheus/client_model/go" ) //SagaTimeoutCounter is the prometheus counter counting timed out saga instances var SagaTimeoutCounter = newSagaTimeout...
package leetcode // In LOL world, there is a hero called Teemo and his attacking can make his enemy Ashe be in poisoned condition. Now, given the Teemo's attacking ascending time series towards Ashe and the poisoning time duration per Teemo's attacking, you need to output the total time that Ashe is in poisoned condit...
// handlers.go package main import ( "encoding/json" "fmt" "net/http" "strconv" ) func GetAllHandler(w http.ResponseWriter, r *http.Request) { u := new(User) users, err := u.GetAllUsers() if err != nil { http.Error(w, err.Error(), http.StatusFound) return } j, err := json.Marshal(users) if err != nil {...
package leetcode func GenerateParenthesis(n int) []string { res := make([]string, 0, 2*n) if n == 0 { return []string{} } if n == 1 { return []string{"()"} } add("(", n, n, "", &res) return res } func add(op string, remainLeft int, remainRight int, path string, res *[]string) { if op == "(" { remainLeft...
package main import ( "net/http" "fmt" "github.com/gorilla/mux" ) func main() { router := mux.NewRouter() router.HandleFunc("/hello/{name}", handleSayHello).Methods("GET") http.ListenAndServe(":8080", router) } func handleSayHello(rw http.ResponseWriter, req *http.Requ...
package main import ( "crypto/rand" "encoding/json" "fmt" "io" "strings" ) type UUID []byte func (uuid UUID) String() string { if uuid == nil || len(uuid) != 16 { return "" } b := []byte(uuid) return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", b[:4], b[4:6], b[6:8], b[8:10], b[10:]) } func NewRandom() UUI...
package models type Auth struct { ID int `gorm:"primary_key" json:"id"` PubDesc int `json:"pub_desc"` Username string `json:"username"` Password string `json:"password"` } func CheckAuth(username string, password string) (authResult *Auth, ok bool) { var auth Auth db.Select("id, pub_desc").Where(Au...
package main import ( "fmt" observer2 "github.com/NGunthor/go_test/pkg/patterns/observer" ) func main() { pub := observer2.NewPublisher() a := observer2.NewObserverA(10) pub.Attach(a) pub.Attach(observer2.NewObserverB(20)) pub.Notify() pub.Attach(observer2.NewObserverB(30)) pub.Notify() pub.Show() fmt.Prin...