text
stringlengths
11
4.05M
package yamlutil import ( "io/ioutil" "os" "testing" "gotest.tools/assert" ) func TestWriteRead(t *testing.T) { dir, err := ioutil.TempDir("", "test") if err != nil { t.Fatalf("Error creating temporary directory: %v", err) } wdBackup, err := os.Getwd() if err != nil { t.Fatalf("Error getting current w...
package menu import ( "strconv" "strings" "testing" ui "github.com/gizak/termui/v3" ) type testEntry struct { message string label string isDefault bool } func (u *testEntry) Label() string { return u.label } func (u *testEntry) IsDefault() bool { return u.isDefault } func TestNewParagraph(t *testi...
package test // ====== Unit tests for the REST handlers ======
package tables import ( "github.com/GoAdminGroup/go-admin/context" "github.com/GoAdminGroup/go-admin/modules/db" "github.com/GoAdminGroup/go-admin/plugins/admin/modules/table" "github.com/GoAdminGroup/go-admin/template" "github.com/GoAdminGroup/go-admin/template/types" "github.com/GoAdminGroup/go-admin/template/...
package fakes import ( bmcloud "github.com/cloudfoundry/bosh-micro-cli/cloud" bmdepl "github.com/cloudfoundry/bosh-micro-cli/deployment" bmstemcell "github.com/cloudfoundry/bosh-micro-cli/stemcell" ) type DeployInput struct { Cpi bmcloud.Cloud Deployment bmdepl.Deployment StemcellApplySpec ...
package main import "fmt" func main() { panic("a panic happen") // won't execute fmt.Println("lalala") }
// ClueGetter - Does things with mail // // Copyright 2016 Dolf Schimmel, Freeaqingme. // // This Source Code Form is subject to the terms of the two-clause BSD license. // For its contents, please refer to the LICENSE file. // package core import ( "github.com/scalingdata/gcfg" ) type config struct { ClueGetter st...
package main import ( "fmt" "sort" ) type playersCards []*card // newPlayersCards1Hand creates a slice with 5 cards // using 1 card from the hand and 4 from the given // card combination. func newPlayersCards1Hand(kartaZReki *card, cardCombination []*card) *playersCards { var cards playersCards = make(playersCard...
package logfmt import ( "io" "log" "github.com/sirupsen/logrus" ) // WriterFormatter is map for mapping a log level to an io.Writer. // Multiple levels may share a writer, but multiple writers may not be used for one level. type WriterFormatter struct { io.Writer Formatter logrus.Formatter } // Hook is a hook ...
package _99_Recover_Binary_Search_Tree import ( "fmt" "testing" ) func TestRecoverTree(t *testing.T) { var ( root *TreeNode ) root = &TreeNode{Val: 1, Left: &TreeNode{Val: 3, Right: &TreeNode{Val: 2}}} recoverTree(root) fmt.Println(root.Val, root.Left.Val, root.Left.Right.Val) root = &TreeNode{Val: 3, Left...
package session import ( "net/http" "strings" "time" "github.com/robfig/cron" "github.com/rvillablanca/goweb/logutil" ) type sessionMap map[string]*Session // SessionLog es el Logger para session var SessionLog = logutil.New("session") // Timeout es la duración por defecto de la Cookie // var Timeout = 3 * ti...
package s3utils import ( "bytes" "io" "path" "strings" "time" "github.com/mitchellh/goamz/aws" "github.com/mitchellh/goamz/s3" ) const ( // AWS says that parts must be at least 5MB, it's unclear if that means 5 * // 10^6 or 5 2^10 so we went with the larger. minPart = 5242880 // 5MB maxPart = minPart...
package clls var builtinFuncs = func() []*Function { names := []string{ "if", "point_add", "c", "list", "l", "sha256", "f", "r", "pubkey_for_exp", "a", "x", "divmod", "substr", "concat", "logand", "qq", "unquote", "q", "quote", "i", } funcs := make([]*Function, len(names)) for i, n := range names { fun...
/* Copyright © 2020 Denis Rendler <connect@rendler.me> 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 weekly import ( "encoding/json" "time" ) type TeamRoleType int const ( RoleNothing TeamRoleType = iota RoleMember RoleManager ) type TeamOpType int const ( TeamOpAdd TeamOpType = 1 + iota // add TeamOpRemove // remove ) type TeamOpParam struct { Op TeamOpType `json:"op...
package server import ( "context" "encoding/json" "net" "net/http" "github.com/bongnv/gokit/util/log" "github.com/go-kit/kit/endpoint" httptransport "github.com/go-kit/kit/transport/http" "github.com/gorilla/mux" ) // Endpoint presents an endpoint. type Endpoint struct { Method string Path ...
package ws import ( "fmt" "log" "net/http" "github.com/satori/go.uuid" "github.com/gorilla/websocket" ) type ClientManager struct { clients map[string]*Client message chan *Message register chan *Client unregister chan *Client } func (manager *ClientManager) CreateClient(res http.ResponseWriter, req...
// experiment project doc.go /* experiment document */ package main
package main import "fmt" //closures adalah kemampuan sebuah function berinteraksi dgn data data disekitarnya dalam scope yg sama //func increment(value int) int { // return value + 1 //} func main() { //fmt.Println(increment(0)) counter := 0 increment := func() { fmt.Println("Increment") counter++ } in...
package main import ( "encoding/csv" "encoding/json" "flag" "fmt" "log" "net/http" "os" "strconv" "strings" "sync" "time" "github.com/gocolly/colly" "github.com/gocolly/colly/debug" ) // Time is our customized type to override UnmarshalJSON interface type Time struct { time.Time } // UnmarshalJSON imp...
// Copyright 2017 The LUCI 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...
package main import ( "github.com/edaniels/golinters/mustcheck" "golang.org/x/tools/go/analysis/singlechecker" ) func main() { singlechecker.Main(mustcheck.Analyzer) }
package message const ( AdminAddedSuccess = "Admin Added successfully." LoginSuccess = "You have successfully logged in." ResetPasswordSuccess = "Password has been reset successfully." ForgotPasswordSuccess = "Please check your mail for reset password." AdminListSuccess = "Admin ...
// Copyright © 2018 Kris Nova <kris@nivenly.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 l...
package main import "fmt" func brute() int { var cnt int // 100, 50, 20, 10, 5, 2, 1 for a := 0; a <= 2; a++ { for b := 0; b <= 4; b++ { for c := 0; c <= 10; c++ { for d := 0; d <= 20; d++ { for e := 0; e <= 40; e++ { for f := 0; f <= 100; f++ { for g := 0; g <= 200; g++ { if p :...
/* Copyright (c) 2017 GigaSpaces Technologies Ltd. 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 ( "fmt" "log" "sync" ) // global variable var ( globalChain *BlockChain globalUTXO *UTXOSet globalOnce sync.Once globalVersion = byte(0x00) ) // BlockchainGenesis : create the chain with genesis block func BlockchainGenesis() { globalOnce.Do(func() { globalChain = NewBlockChain(...
package services import ( log "github.com/sirupsen/logrus" "net/http" "strconv" "sync" "github.com/dispatchlabs/disgo/properties" "github.com/gorilla/mux" ) var httpRouterInstance *mux.Router var httpRouterOnce sync.Once func GetHttpRouter() *mux.Router { httpRouterOnce.Do(func() { httpRouterInstance = mux...
package main import ( validator "gopkg.in/go-playground/validator.v9" ) // isCommercialSameStruct return false if the Passed Field (param) is not "contract". func isCommercialSameStruct(fl validator.FieldLevel) bool { field := fl.Field() param := fl.Param() if fl.Parent().FieldByName(param).String() == "contract...
package main // // import ( // "encoding/json" // "fmt" // "net/http" // // "github.com/smoreg/simpleCash/fullCash" // ) // // func main() { // withCash() // } // // func simpleNoCash() { // var client SomeWebClient // // // No cash // client = RealWebClient{} // // Request for post every time // client.GetP...
package main import ( "fmt" "runtime" "github.com/shirou/gopsutil/cpu" "github.com/shirou/gopsutil/disk" "github.com/shirou/gopsutil/mem" ) // var stats *Stats type Stats struct { CPU float64 DiskUsed uint64 DiskTotal uint64 DiskPercent float64 MemoryUsed uint64 MemoryTotal uint64 GoMemory...
package main import "math" /** 长度最小的子数组 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组,并返回其长度。如果不存在符合条件的连续子数组,返回 0。 示例1: ``` 输入: s = 7, nums = [2,3,1,2,4,3] 输出: 2 解释: 子数组 [4,3] 是该条件下的长度最小的连续子数组。 ``` 进阶: 如果你已经完成了O(n) 时间复杂度的解法, 请尝试 O(n log n) 时间复杂度的解法。 */ /** 被连续子数组给绕住了,一直以为是 [3,4,5,6,7] .... 暴力解法 */ func Min...
package model type Quality struct { Value int `json:"quality"` }
/* * @lc app=leetcode.cn id=20 lang=golang * * [20] 有效的括号 * * https://leetcode-cn.com/problems/valid-parentheses/description/ * * algorithms * Easy (39.24%) * Likes: 978 * Dislikes: 0 * Total Accepted: 107.2K * Total Submissions: 273.2K * Testcase Example: '"()"' * * 给定一个只包括 '(',')','{','}','[',']...
package main // TODO: impl import ( "fmt" "os" ) func main() { fmt.Println("PID:", os.Getpid()) r, w, err := os.Pipe() if err != nil { panic(err) } fmt.Println(r.Name(), w.Name()) }
package structs type User struct { ID *int64 `json:"ID,omitempty"` Login string `json:"Login"` FirstName string `json:"FirstName"` LastName string `json:"LastName"` Age int `json:"Age"` Phone int64 `json:"Phone"` PassInfo *string `json:"PassInfo,omitempty"` } type AuthUser stru...
package main import ( "fmt" "sync" "time" ) var count int func main() { var wg sync.WaitGroup for i := 0; i < 3; i++ { wg.Add(1) go routine(&wg) } wg.Wait() fmt.Println("I am main!! My id is:", getGID()) fmt.Println("I am main!! final count is:", count) } func routine(wg *sync.WaitGroup) { for i := 0...
package cli import ( "errors" "strings" "github.com/cosmos/cosmos-sdk/x/crisis/types" "github.com/gookit/gcli/v3" "github.com/ovrclk/akcmd/client" "github.com/ovrclk/akcmd/flags" ) // NewTxCmd returns a root CLI command handler for all x/crisis transaction commands. func NewTxCmd() *gcli.Command { txCmd := &g...
package streams type Order struct { Data OrderData Type string }
package main import ( "log" "github.com/rancher/k3d/v4/cmd" "github.com/spf13/cobra/doc" ) func main() { k3d := cmd.GetRootCmd() k3d.DisableAutoGenTag = true if err := doc.GenMarkdownTree(k3d, "../docs/usage/commands"); err != nil { log.Fatalln(err) } }
package e2e import ( "encoding/json" "strings" "testing" "time" "github.com/sensu/sensu-go/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestTokenSubstitution(t *testing.T) { t.Parallel() // Start the backend backend, cleanup := newBackend(t) defer cleanup() /...
package middleware import ( "encoding/json" "github.com/kataras/iris" "gocherry-api-gateway/admin/admin_enum" "gocherry-api-gateway/admin/models" "gocherry-api-gateway/components/log_client" "gocherry-api-gateway/components/redis_client" "gocherry-api-gateway/components/utils" ) /** 后台的任何操作记录 任何路由 */ func Ope...
package apiv3 import ( "fmt" "os" "regexp" "strconv" "testing" ) var xms *XMS func init() { endpoint := os.Getenv("GOXTREMIO_ENDPOINT") insecure, _ := strconv.ParseBool(os.Getenv("GOXTREMIO_INSECURE")) username := os.Getenv("GOXTREMIO_USERNAME") password := os.Getenv("GOXTREMIO_PASSWORD") var err error x...
package utils import ( "regexp" "strings" ) func NormalizeString(s string) (string, error) { re, err := regexp.Compile(`\W`) if err != nil { return "", err } return strings.TrimSpace(re.ReplaceAllString(s, "")), nil }
package main import ( "encoding/xml" "fmt" nestpay "github.com/ozgur-soft/nestpay/src" ) func main() { api := &nestpay.API{"asseco"} // "asseco","akbank","isbank","ziraatbank","halkbank","finansbank","teb" request := new(nestpay.Request) request.ClientId = "" // Müşteri No request.Username = "" // Kullanıcı a...
package CpUtil import ( mapset "github.com/deckarep/golang-set" "math" ) type RSBitSet struct { NumLevel, NumBit, lastLimits, top int Words [][]uint64 Limit, Index, Levels []int mask []uint64 } type FDERSBitSet struct { RSBitSet CurrentWor...
// Copyright 2013-2014 go-diameter 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 diam import ( "bytes" "testing" ) func TestUint24to32(t *testing.T) { if v := uint24to32([]byte{218, 190, 239}); v != 0xdabeef { t.Fat...
package models import ( "time" ) type ApiKey struct { ID *string `json:"-" bson:"_id,omitempty"` ApiKey *string `json:"apikey"` Disabled *bool `json:"disabled"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` }
package controllers import ( "github.com/gork-io/gork/models" "github.com/gork-io/gork/transformers/gateways/grpc/proto" ) // marshalCollectionInfo is a helper function that marshals domain model of the collection info into GRCP model. func marshalCollectionInfo(input *models.CollectionInfo) (output *proto.Collecti...
package mylog import ( "log" "time" "os" ) var writeLogger *log.Logger = nil func InitLogger(tofile bool){ if tofile{ file:="./"+time.Now().Format("2006-01-02") +"_log.txt" logfl,err:=os.OpenFile(file,os.O_CREATE | os.O_APPEND|os.O_RDWR,0766) if err!=nil{ panic(err) } writeLogger = log.New(logfl,""...
package keeper_test import ( gocontext "context" "github.com/irisnet/irismod/modules/nft/types" ) func (suite *KeeperSuite) TestSupply() { err := suite.keeper.MintNFT(suite.ctx, denomID, tokenID, tokenNm, tokenURI, tokenData, address) suite.NoError(err) response, err := suite.queryClient.Supply(gocontext.Backg...
package main import ( "./tokenizer" ) func main() { tokenizer.Tokenize("J'ai mangé") }
package config import "github.com/spf13/viper" type HTTP viper.Viper func (h *HTTP) viper() *viper.Viper { return (*viper.Viper)(h) } func (h *HTTP) Port() uint { return h.viper().GetUint("http.port") } func (h *HTTP) SetPort(p uint) { h.viper().Set("http.port", p) } func (h *HTTP) BasePath() string { return ...
package main import ( "fmt" ) // https://leetcode-cn.com/problems/sudoku-solver/ // 10:27 ~ // 3 个[]int 表示该数字所在的: 横\竖\九宫 可填数字 // 每个 int 的低10个bit表示 1~9 是否可用: 1可用,0不可用 // markValue: 二进制 011,1111,1110 const markValue int = 0x03fe type value struct { i, j, v, t int } func solveSudoku(board [][]byte) { n := len(boar...
package field import ( "encoding/binary" "fmt" "io" ) // Field70 is the unknown field with ID 70. type Field70 struct { header *Header data []byte } // Value returns the raw bytes for the field. func (f *Field70) Value() byte { return f.data[0] } func (f *Field70) String() string { return fmt.Sprintf("%v",...
package pain import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00600101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:pain.006.001.01 Document"` Message *PaymentCancellationRequestV01 `xml:"pain.006.001.01"` } func (d *Document0...
package main import ( "context" "fmt" ) func process(ctx context.Context) { value := ctx.Value("message") fmt.Println(value) } func main() { ctx := context.WithValue(nil, "message", "Hello World") process(ctx) }
package scanner import ( "archive/tar" "compress/gzip" "encoding/json" "fmt" "io" "io/ioutil" "os" "time" ) func saveMonthesDatas(dir string, loadedMonths map[string]*MonthDatas) { for fileName, month := range loadedMonths { saveOneMonthDatas(dir, fileName, month) } } func saveOneMonthDatas(dir string, f...
package libModel import ( "strings" ) // 需要转换成Struct的类型转换函数切片 var TypeWrappers = []typeWrapper{i64TypeWrapper, byteTypeWrapper, intTypeWrapper, float64TypeWrapper, stringTypeWrapper, timeTypeWrapper} /* 数据库类型与go数据类型之间的转换 */ const ( CTypeInt64 = "int64" CTypeInt = "int" CTypeUInt = "uint" CTypeString =...
package parser import ( "encoding/xml" "net/http" ) type enclosure struct { URL string `xml:"url,attr"` } type item struct { Title string `xml:"title"` Description string `xml:"description"` Link string `xml:"link"` Enclosure enclosure `xml:"enclosure"` } type channel struct { Item []i...
package main import ( "testing" "github.com/stretchr/testify/assert" ) // func Test_Run(t *testing.T) { // cases := []struct { // name string // actual string // expected int // }{ // { // name: "example", // actual: "example.input", // expected: 0, // }, // // { // // name: ...
package kimono import ( "time" ) type Params struct { Version int Format ResultFormat Limit int Offset int ByPage bool WithUrl bool Index int Hash bool Series bool Stats bool } type ResultFormat string const ( Csv = ResultFormat("Csv") CsvWithoutCollectionHeaders = ...
// Package config implements derived certs in the Pomerium Configuration package config import ( "bytes" "crypto/tls" "fmt" "github.com/pomerium/pomerium/config" "github.com/pomerium/pomerium/pkg/derivecert" ) type builder struct { psk []byte ca *derivecert.CA caCertPEM []byte domain string c...
package osbuild2 import ( "encoding/json" "testing" "github.com/stretchr/testify/assert" ) func TestNewCloudInitStage(t *testing.T) { expectedStage := &Stage{ Type: "org.osbuild.cloud-init", Options: &CloudInitStageOptions{}, } actualStage := NewCloudInitStage(&CloudInitStageOptions{}) assert.Equal(t, ...
package config import ( "fmt" "testing" ) func TestSetup(t *testing.T) { fmt.Println("server:") fmt.Println("server.RunMode", ServerSetting.RunMode) fmt.Println("server.HttpPort", ServerSetting.HttpPort) fmt.Println("server.ReadTimeout", ServerSetting.ReadTimeout) fmt.Println("server.WriteTimeout", ServerSett...
package exercise import ( "fmt" ) func judgePrime(num int) bool { if num == 1 { return false } for i := 2; i < num; i++ { if num%i == 0 { return false } } return true } func testPrime() { for i := 1; i < 100; i++ { if judgePrime(i) { fmt.Printf("[%d] 为质数... \n", i) } } } func is_sxhs(num i...
package internal import ( "fmt" "golang.org/x/net/html" "io" "strings" ) const baseHabrUrl = "https://habr.com" type printer struct { } type Printer interface { Print(data io.Reader) error } func (p *printer) isGarbage(title string) bool { if title == "<title>" { return true } if title == "Читать далее" ...
/* Copyright © 2022 SUSE LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distri...
package main //注意同一个目录下不能有不同名的包 import ( ch4 "./Chapter4" ch5 "./Chapter5" "fmt" ) func main() { //C4 //ch4.TestBase() // //helloworld.Hello() fmt.Println("xxx") //TestConst //ch4.TestConst() //TestVar //ch4.TestGoos() //TestPrint //ch4.TestPint() //TestSameName //ch4.TestSameName() //TestXor ...
package constant const Redhat7RedisServiceFilePath = "/usr/lib/systemd/system/redis.service" const Redhat7RedisServiceContent = "" + "[Unit]\n" + "Description=Redis persistent key-value database\n" + "After=network.target\n" + "After=network-online.target\n" + "Wants=network-online.target\n\n" + "[Service]\n" +...
// Package router implements regexp based HTTP router. package router import ( "fmt" "net/http" "regexp" "strings" "golang.org/x/net/context" ) type Routes []Route type HandlerFunc func(context.Context, http.ResponseWriter, *http.Request) // Route binds together HTTP method, path and handler function. type Ro...
package fsutils import ( "log" "os" "path/filepath" "strings" ) func frequency() { filepath.Walk(".", walker) } var counts = make(map[string]int) func walker(path string, info os.FileInfo, err error) error { // SPlit allparts pathparts := strings.Split(path, "/") for idx, part := range pathparts { count...
package dynamic_programming func uniquePathsWithObstacles(obstacleGrid [][]int) int { if len(obstacleGrid) == 0 || len(obstacleGrid[0]) == 0 { return 0 } m := len(obstacleGrid) n := len(obstacleGrid[0]) dp := make([][]int, m) for i := range dp { dp[i] = make([]int, n) } // dp[i][j]表示到当前点的路径总数 if obstacleG...
/* Copyright 2018 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 server import ( "encoding/json" "github.com/yekhlakov/gojsonrpc/common" ) // An JsonRpcServer does actual processing // Create a new JsonRpcServer func NewServer() *JsonRpcServer { return &JsonRpcServer{ Methods: make(map[string]JsonRpcMethod), } } // Add a handler (that is effectively a collection o...
package auth import ( "net/http" ) type Token interface { IsValid() bool } func valid(t Token) bool { return t.IsValid() } func IsAuth(r *http.Request) bool { t := MockToken{token: r.Header.Get("Authorization")} return valid(&t) }
package internal import ( "fmt" "github.com/jessevdk/go-flags" "os" ) // ParseOptions will parse the commandline options given by opts. It will exit when issues arise or help is wanted func ParseOptions(opts interface{}) { parser := flags.NewParser(opts, flags.IgnoreUnknown) _, err := parser.Parse() if err != n...
package cbnet import ( "fmt" dataobjects "github.com/cloud-barista/cb-larva/poc-cb-net/internal/cb-network/data-objects" "strconv" ) // DynamicSubnetConfigurator represents a configurator for Dynamic Subnet Configuration Protocol type DynamicSubnetConfigurator struct { NetworkingRules dataobjects.NetworkingRule ...
package gpxjson import ( "encoding/json" "encoding/xml" ) type GPX struct { Trkseg []Trkseg `xml:"trk>trkseg" json:"segments"` } type Trkseg struct { Trkpt []struct { Lat float32 `xml:"lat,attr" json:"lat"` Lon float32 `xml:"lon,attr" json:"lon"` Ele float32 `xml:"ele" json:"ele,omitempty"` Time strin...
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-07-27 14:56 * Description: *****************************************************************/ package main import ( "fmt" "github.com/go-xe2/x/os/xl...
package dao import ( "github.com/techone577/blogging-go/model" ) type PostStorage interface { QueryByPostID(id string) (*model.PostInfo, error) QueryPreviousPost(pkId int) (*model.PostInfo, error) QueryNextPost(pkId int) (*model.PostInfo, error) QueryByPaging(page, pageSize, releaseFlag, delFlag int) ([]model.Po...
package selecting import ( . "github.com/xinhuang327/algorithms/common" ) var delegate = &NullDelegate{} func QuickSelect(slice []int, k int) (idx, v int) { return quickSelect(slice, 0, len(slice)-1, k) } // Returns the kth smallest element in slice[l,r] // k's range: [1, r-l+1] func quickSelect(slice []int, l, r...
// Written in 2014 by Petar Maymounkov. // // It helps future understanding of past knowledge to save // this notice, so peers of other times and backgrounds can // see history clearly. package see import ( "log" "github.com/hoijui/escher/pkg/a" cir "github.com/hoijui/escher/pkg/circuit" ) func ParseVerb(src str...
package protocol import ( "bufio" "bytes" "context" "encoding" "io" "net/http" "net/textproto" urlpkg "net/url" flatbuffers "github.com/google/flatbuffers/go" "github.com/hyperscalr/hyperscalr.go/flatbuf" "github.com/nats-io/nats.go" "github.com/pkg/errors" "github.com/segmentio/ksuid" ) type QueueMessa...
package boilingcore import ( "fmt" "io/fs" "path/filepath" "strings" "text/template" "github.com/friendsofgo/errors" "github.com/spf13/cast" "github.com/volatiletech/sqlboiler/v4/drivers" "github.com/volatiletech/sqlboiler/v4/importers" ) // Config for the running of the commands type Config struct { Driv...
package main import ( "context" "log" "memoapp/internal/handler" "os" "os/signal" "syscall" // 参考:Go勉強会 // DBのドライバパッケージを読み込む。 // ドライバパッケージの読み込みは、mainパッケージで実施したほうが良い。 "github.com/comail/colog" _ "github.com/go-sql-driver/mysql" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" ) func...
package v3 import ( "encoding/json" "fmt" "io/ioutil" ) type Image struct { Id string `json:"id"` Title string `json:"title"` Description string `json:"description"` Datetime int64 `json:"datetime"` Type string `json:"type"` Animated bool `json:"animated"` Width int64 `...
package cli import ( "GoFileWatcher/fileWatcher" "bufio" "errors" "fmt" "github.com/manifoldco/promptui" "github.com/mikerapa/FolderWatcher" "os" ) func RemoveFolderMenu(folderList map[string]folderWatcher.WatchRequest) (folderPath string, err error) { var items []string for folder := range folderList { i...
package cmd import ( "github.com/spf13/cobra" "github.com/instructure-bridge/muss/config" ) func newStartCommand(cfg *config.ProjectConfig) *cobra.Command { var cmd = &cobra.Command{ Use: "start", Short: "Start services", Long: "Start existing containers.", Args: cobra.ArbitraryArgs, // TODO: ArgsIn...
/* @Time : 2019/3/30 11:41 @Author : yanKoo @File : regexpUtils @Software: GoLand @Description: */ package utils import ( "fmt" "log" "regexp" "strconv" ) // 校验手机号码 func CheckPhone (phone string) bool { reg, err := regexp.Compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$") if err != nil { log.Println(err...
package restmachinery // APIClientOptions encapsulates optional API client configuration. type APIClientOptions struct { // AllowInsecureConnections indicates whether SSL-related errors should be // ignored when connecting to the API server. AllowInsecureConnections bool }
package channels import "github.com/google/wire" var Providers = wire.NewSet(NewStore, HttpVmListHandler, HttpConnectDiskHandler)
package do import ( "context" "fmt" "io/ioutil" "net/http" "os" "path/filepath" env "github.com/robitx/inceptus/server_template/internal/env" rest "github.com/robitx/inceptus/server_template/internal/rest" route "github.com/robitx/inceptus/route" middleware "github.com/robitx/inceptus/route/middleware" ) ...
package instance_test import ( "github.com/pivotal-cf/spring-cloud-services-cli-plugin/instance" "github.com/pivotal-cf/spring-cloud-services-cli-plugin/serviceutil" "errors" "net/http" "bytes" "io/ioutil" "fmt" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/pivotal-cf/spring-...
package goSolution func findLength(nums1 []int, nums2 []int) int { n, m := len(nums1), len(nums2) f := Initialize2DIntSlice(n + 1, m + 1, 0) ret := 0 for i := 0; i < n; i++ { for j := 0; j < m; j++ { if nums1[i] == nums2[j] { f[i + 1][j + 1] = f[i][j] + 1 ret = max(f[i + 1][j + 1], ret) } else { ...
package model import "time" type User struct { Id int Uuid string Name string Email string Password string CreateAt time.Time } type Session struct { Id int Uuid string Email string UserId int CreateAt time.Time } func (user *User) CreateSession() (Session, error) { retur...
package quicksort func quick_sort(values []int, ele int)(sorted_values []int){ if len(values) > 0{ left_values := make([]int, 0) right_values := make([]int, 0) for _, value := range values{ if value < ele{ left_values = append(left_values, value) } else { right_values = append(right_values, value...
package lib import ( "context" "github.com/yangqinjiang/mycrontab/worker/common" "github.com/coreos/etcd/clientv3" "net" "sync" "time" "github.com/yangqinjiang/mycrontab/worker/lib/config" ) var ( G_register *Register onceRegister sync.Once ) //注册节点到etcd /cron/worker/ip地址 type Register struct { client *...
package main import "fmt" func main() { city := []string{"Moscow", "SPB", "KZN"} newCity := make([]string, len(city)-1) copy(newCity, city) newCity[0] = "Monaco" fmt.Println("New city:", newCity[:2]) fmt.Println("Old city:", city) }
package dcp import ( "reflect" "testing" ) func Test_waterCost(t *testing.T) { type args struct { pipeSet map[string]map[string]uint } tests := []struct { name string args args want map[string]map[string]uint }{ {"0", args{map[string]map[string]uint{ "plant": {"A": 1, "B": 5, "C": 20}, "A":...