text
stringlengths
11
4.05M
/* DEPRECATED: use go.pedge.io/pkg/yaml instead! https://go.pedge.io/pkg */ package yaml2json import "errors" type TransformOptions struct { Pretty bool Indent string } func Transform(p []byte, options TransformOptions) ([]byte, error) { return nil, errors.New("yaml2json is deprecated! Use go.pedge.io/pkg/yaml i...
package main import ( "fmt" "strings" postgresv1 "github.com/cloud-ark/kubeplus/postgres-crd-v2/pkg/apis/postgrescontroller/v1" ) func getCreateUserCommands(desiredList []postgresv1.UserSpec) []string { var cmdList []string for _, user := range desiredList { username := user.User p...
package lib import ( "regexp" "strings" ) var tokenSeparatorPatternSource = `[^A-Za-zА-Яа-я0-9_]+` var tokenSeparatorRegExp = regexp.MustCompile(tokenSeparatorPatternSource) func Tokenize(content string) []string { delim := " " tokenized := tokenSeparatorRegExp.ReplaceAll([]byte(content), []byte(delim)) return ...
package v1beta1 import ( conditionsv1 "github.com/openshift/custom-resource-status/conditions/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" sdkapi "kubevirt.io/controller-lifecycle-operator-sdk/pkg/sdk/api" ) // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // NOTE: json tag...
package command import ( "fmt" "strconv" "github.com/spf13/cobra" "go.mercari.io/hcledit" ) type CreateOptions struct { Type string After string Comment string } func NewCmdCreate() *cobra.Command { opts := &CreateOptions{} cmd := &cobra.Command{ Use: "create <query> <value> <file>", Short: "Cr...
package logger import ( "go.uber.org/zap" "go.uber.org/zap/zapcore" "gopkg.in/natefinch/lumberjack.v2" "path/filepath" "strings" ) var logger *zap.SugaredLogger var levelMap = map[string]zapcore.Level{ "debug": zapcore.DebugLevel, "info": zapcore.InfoLevel, "warn": zapcore.WarnLevel, "error": zapcore....
package controllers import ( "encoding/json" "fmt" "io/ioutil" "net/http" "user-auth/model" "user-auth/rand" ) type jsonData struct { Email string `json:"email"` Password string `json:"password"` } type Users struct { us *model.UserService } func NewUsers(us *model.UserService) *Users { return &Users{u...
package ipc import ( "errors" "github.com/hokora/bank/util" ) type Context struct { from *Conn Packet []byte reqID uint16 } func (ctx *Context) Reply(success bool, b []byte) (int, error) { if ctx.reqID == 0 { return 0, errors.New("cannot reply") } pw := util.NewPacketWriter(2 + 1 + len(b)) pw....
package web import ( "testing" "github.com/stretchr/testify/assert" ) func TestUrlFor(t *testing.T) { loginUrl := UrlFor("login") assert.Equal(t, "/login", loginUrl) }
package main // Use `dev_appserver.py --default_gcs_bucket_name GCS_BUCKET_NAME` // when running locally. import ( "fmt" "html/template" "io" "net/http" "golang.org/x/net/context" "google.golang.org/appengine" "google.golang.org/appengine/file" "google.golang.org/appengine/log" ) const URL = "http://localho...
package server import ( "encoding/json" "fmt" "net/http" ) type HTTPError struct { status int detail string err error payload interface{} } func NewHTTPError(status int, detail string, err error, payload interface{}) error { return &HTTPError{ status: status, detail: detail, err: err, pay...
package main import ( "bufio" "fmt" "log" "io" "os" "strconv" ) func IntsFrom(r io.Reader) (numbers []int) { scanner := bufio.NewScanner(r) scanner.Split(bufio.ScanWords) for scanner.Scan() { x, err := strconv.Atoi(scanner.Text()) numbers = append(numbers, x) ...
package api type GameState struct { Time int `json:"time"` Game Game `json:"game"` }
package testdata import ( "github.com/frk/gosql/internal/testdata/common" ) type InsertResultErrorInfoHandlerIteratorQuery struct { Users []*common.User `rel:"test_user:u"` result common.User2Iterator erh common.ErrorInfoHandler }
package log import ( "io/ioutil" "os" "testing" api "github.com/alexeyqian/proglog/api/v1" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" ) type fn func(*testing.T, *Log) func TestLog(t *testing.T) { funcs := make(map[string]fn) funcs["a"] = testAppendRead funcs["b"] = testOutOfR...
package leptonica /* #cgo LDFLAGS: -llept #include "leptonica/allheaders.h" #include <stdlib.h> l_uint8* uglycast(void* value) { return (l_uint8*)value; } */ import "C" import ( "errors" "sync" "unsafe" "fmt" ) type goPix struct { cPix *C.PIX closed bool lock sync.Mutex } // Deletes the pic, this must b...
package httpd import ( "fmt" "os" "gopkg.in/yaml.v2" ) type Buildpack struct { HTTPD BuildpackHTTPD `yaml:"httpd"` } type BuildpackHTTPD struct { Version string `yaml:"version"` } func ParseBuildpack(path string) (Buildpack, error) { file, err := os.Open(path) if err != nil { return Buildpack{}, fmt.Error...
package passwordcombiner import ( "crypto/sha256" "errors" "fmt" "github.com/cloudfoundry-incubator/cloud-service-broker/db_service/models" "github.com/cloudfoundry-incubator/cloud-service-broker/internal/encryption/gcmencryptor" "github.com/cloudfoundry-incubator/cloud-service-broker/internal/encryption/passwo...
// Copyright 2017 orijtech, 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 applic...
package main import ( "container/list" "flag" "fmt" "io" "io/ioutil" "log" "net/http" "net/url" "strings" ) func GET(urlFlag string) []string { resp, err := http.Get(urlFlag) if err != nil { log.Fatal(err) } defer resp.Body.Close() reqURL := resp.Request.URL baseURL := &url.URL{ Scheme: reqURL.S...
package types type DataplaneTokenRequest struct { Name string `json:"name"` Mesh string `json:"mesh"` Tags map[string][]string `json:"tags"` Type string `json:"type"` }
package writer import ( "fmt" "io" "sort" "strings" "text/template" "time" "github.com/urfave/cli" ) func New(app *cli.App) *Cli { now := time.Now() return &Cli{ App: app, Date: fmt.Sprintf("%s %d", now.Month(), now.Year()), Commands: prepareCommands(app.Commands, 0), GlobalArgs...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/11/18 9:19 上午 # @File : sort_test.go # @Description : # @Attention : */ package sort import ( "fmt" "github.com/stretchr/testify/require" "testing" ) var ( arr = []int{0, 3, 2, 1, 9, 8} exceptedRet = []int{0, 1, 2, 3, 8, 9} ) func TestBuble(t *...
package mocks import ( "errors" "fmt" "testing" "github.com/golang/protobuf/proto" "github.com/liquidm/llsr" "github.com/liquidm/llsr/decoderbufs" ) type testReporterMock struct { errors []string } func newTestReporterMock() *testReporterMock { return &testReporterMock{errors: make([]string, 0)} } func (tr...
package v1beta3 import ( "reflect" "testing" next "github.com/devspace-cloud/devspace/pkg/devspace/config/versions/v1beta4" "github.com/devspace-cloud/devspace/pkg/util/log" "github.com/devspace-cloud/devspace/pkg/util/ptr" yaml "gopkg.in/yaml.v2" ) type testCase struct { in *Config expected *next.Conf...
package migemo import "errors" // LevelU8 は、Loudsツリーの深さ毎のloudsやlabelを格納した構造体 type LevelU8 struct { louds []bool outs []bool labels []byte } // LoudsTrieBuilderU8 は、LoudsTrieを生成するための構造体 type LoudsTrieBuilderU8 struct { levels []LevelU8 lastKey []uint8 } // NewLoudsTrieBuilderU8 は、LoudsTrieBuilderを初期化する func...
package models import ( "github.com/astaxie/beego/orm" "time" ) //查询的类 type FinancialProductHistoricalRecordQueryParam struct { BaseQueryParam StartTime int64 `json:"startTime"` //开始时间 EndTime int64 `json:"endTime"` //截止时间 ConfId string `json:"confId"` //id Category string `json:"category"` //活期定...
package main import ( "gopkg.in/mgo.v2/bson" "time" ) type ( // Component represents the structure of our resource // TODO: Should include jarfile / gemfile / ... Component struct { ID bson.ObjectId `json:"id" bson:"_id"` Name string `json:"name" bson:"name"` Resource ...
package main import ( "fmt" "time" "log" "os" "path/filepath" "strings" ) type test struct{ name string ip string } func substr(s string, pos, length int) string { runes := []rune(s) l := pos + length if l > len(runes) { l = len(runes) } return string(runes[pos:l]) } func main(){ var ted map[stri...
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httptest" "net/url" "testing" ) var ( mockStore = NewMockStorage() server *httptest.Server ) func init() { var app = &App{ Storage: mockStore, Cache: NewCache(10), } app.Router = NewRouter(app) server = httpte...
package mysql import ( "InkaTry/warehouse-storage-be/internal/pkg/stores" "context" ) const ( listwarehousesQuery = ` SELECT id, name from warehouses where deleted = 0; ` ) func (c *Client) ListWarehouses(ctx context.Context) (stores.Results, error) { var dest []stores.Result stmt, err := c.preparedStmt(listwa...
package influxql_test import ( "encoding/json" "fmt" "reflect" "regexp" "strings" "testing" "time" "github.com/influxdata/influxql" ) // Ensure the parser can parse a multi-statement query. func TestParser_ParseQuery(t *testing.T) { s := `SELECT a FROM b; SELECT c FROM d` q, err := influxql.NewParser(strin...
package user import ( "context" "reflect" auth "github.com/inhumanLightBackend/auth/logic" ) type Service interface { Authenticate(context.Context, string, string) (*User, error) CreateUser(context.Context, *User) (string, error) FindUserByEmail(context.Context, string) (*User, error) FindUserById(context.Con...
package meda func (c *Config) CopyFrom(other *Config) { c.Driver = other.Driver c.DataSourceName = other.DataSourceName c.TablePrefix = other.TablePrefix c.MaxOpenConns = other.MaxOpenConns c.MaxIdleConns = other.MaxIdleConns c.ConnMaxLifetime = other.ConnMaxLifetime c.LockKeepAliveInterval = other.LockKeepAliv...
package main import ( "fmt" "os/exec" ) func lookCmmand(cmd string) { value := aliasTable[cmd] if value != "" { fmt.Printf("%s: aliased to %s\n", cmd, value) return } value, err := exec.LookPath(cmd) if err == nil { fmt.Printf("%s: %s\n", cmd, value) return } fmt.Printf("%s NOT FOUND\n", cmd) }
package account import ( "log" "strconv" "testing" ) func TestRankListManager_Rank(t *testing.T) { for i := 0; i < 10; i++ { log.Println(DefaultRankList().Rank(uint32(i), "玩家"+strconv.Itoa(i), int32(10-i))) } log.Println(DefaultRankList().Rank(123, "玩家"+strconv.Itoa(123), int32(11))) log.Println(DefaultRankL...
package lib import ( "net/http" ) type repositoryListResponse struct { repositories chan Repository err error } func (r *repositoryListResponse) Repositories() <-chan Repository { return (r.repositories) } func (r *repositoryListResponse) LastError() error { return r.err } func (r *repositoryListResp...
package types // // OauthAccessTokenResponse is the response to an access token request // type OauthAccessTokenResponse struct { AccessToken string `json:"access_token"` TokenType string `json:"token_type"` ExpiresIn int `json:"expires_in"` RefreshToken string `json:"refresh_token"` }
package main import ( "container/list" "fmt" ) //type List struct { // root Element // len int //} // //// 链表就是有一个prev和next的指针数组 //type Element struct { // next, prev *Element // 上一个和下一个元素 // list *List // value interface{} // 元素 //} func main() { list := list.New() // 链表后面插入俩值 list.PushBack(1) list.PushBack(2)...
package main import ( "fmt" "sync" "sync/atomic" ) const ( batch int = 1000 workers int = 50 ) func worker(wg *sync.WaitGroup, psum *uint64, batch int) { for c := 0; c < batch; c++ { atomic.AddUint64(psum, 1) } wg.Done() } func main() { var sum uint64 var wg sync.W...
// go run has_method.go package main import ( "fmt" "reflect" ) type myStruct struct { a int } type myInterface interface { SetA(int) } func (s *myStruct) SetA(a int) { s.a = a } func main() { s := myStruct{} s.SetA(1) fmt.Println(s) // {1} st := reflect.ValueOf(&s) fmt.Println(st) // main.myStruct m1 ...
package solver import ( "testing" "github.com/truggeri/go-sudoku/cmd/go-sudoku/puzzle" ) var result puzzle.Puzzle func BenchmarkSolverEasy(b *testing.B) { var r puzzle.Puzzle puzzle := CreateTestPuzzleEasy() for n := 0; n < b.N; n++ { r = Solve(puzzle) } result = r } func BenchmarkSolverMedium(b *testing....
package main import ( "bufio" "fmt" "os" "strconv" ) func main() { var words [5]string input := bufio.NewScanner(os.Stdin) for i := 0; i < len(words); i++ { var message string input.Scan() message = input.Text() //strconv.ParseFloat(input.Text(), 32) // strconv.Atoi("12") words[i] = message } var i...
package version_test import ( . "github.com/bossjones/go-chatbot-lab/shared/version" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Version", func() { Describe("Default Version variables", func() { It("should be <Unknown>", func() { Expect(VersionPrerelease).To(Equal("")) Expec...
package byopenwrt import "github.com/go-cmd/cmd" func ServiceRestart(name string)error{ aps:=cmd.NewCmd("/etc/init.d/"+name,"restart") //等待aps完成 status := <-aps.Start() if status.Error!=nil{ return status.Error } return nil } func ServiceStop(name string)error{ aps:=cmd.NewCmd("/etc/init.d/"+name,"stop") ...
package integration_test import ( "github.com/cloudfoundry/libbuildpack/cutlass" "fmt" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("deploy a staticfile app", func() { var app *cutlass.App var app_name string AfterEach(func() { if app != nil { app.Destroy() } app = nil ...
// Copyright (C) Microsoft Corporation. package main import ( "database/sql" "errors" "flag" "fmt" "log" "os" "strings" "time" _ "github.com/denisenkom/go-mssqldb" "mssqlcommon" mssqlocf "mssqlcommon/ocf" ) /* Program to be called from the mssql:fci resource agent to monitor SQL Server health. Determ...
package pokemon import ( "net/http" "github.com/gorilla/mux" "github.com/hrishin/pokemon-shakespeare/pkg/description" "github.com/hrishin/pokemon-shakespeare/pkg/response" "github.com/hrishin/pokemon-shakespeare/pkg/translation" "github.com/op/go-logging" ) var log = logging.MustGetLogger("pokemon") // GetDes...
package cmd import ( "log" "github.com/spf13/cobra" "github.com/cilium/kubenetbench/kubenetbench/core" ) var policyArg string var pod2podCmd = &cobra.Command{ Use: "pod2pod", Short: "pod-to-pod network benchmark run", Run: func(cmd *cobra.Command, args []string) { if policyArg != "" && policyArg != "port...
package handler import ( "net/http" "path" "github.com/webhippie/oauth2-proxy/pkg/config" ) // Auth handles the callback from the OAuth2 provider. func Auth(cfg *config.Config) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { http.Redirect( w, r, path.Join( cfg.Server.Root,...
package tmp const HelperFuncTmp = `package helper import ( "context" "encoding/json" "fmt" "io/ioutil" "os" "reflect" "github.com/0LuigiCode0/logger" ) func ParseConfig() (*Config, error) { _, err := os.Stat(ConfigDir + ConfigFiel) if err != nil { return nil, fmt.Errorf(KeyErrorNotFound+": file: %v", Con...
package ehttp import ( "errors" "strconv" "strings" "github.com/gin-gonic/gin" ) // parameterRule the rule of the parameter, check if parameter is valid type parameterRule interface { Check(*gin.Context) error } // parameterRuleBase the base class of parameterRule type parameterRuleBase struct { Name stri...
func reverseList(head *ListNode) *ListNode { var tmp *ListNode = nil var last *ListNode = nil for i := head; i != nil; i = tmp { tmp = i.Next i.Next = last last = i } return last }
package main import ( "context" "fmt" "net" "os" "os/signal" "syscall" "github.com/birchwood-langham/portdb-ws/db" "github.com/birchwood-langham/portdb-ws/db/pg" pd "github.com/birchwood-langham/portdb-ws/protocol" "github.com/birchwood-langham/web-service-bootstrap/config" log "github.com/sirupsen/logrus"...
package main import ( "fmt" "io" "os" "reflect" ) func main() { // 1. 通过反射判断一个值的类型 for _, v := range []interface{}{"hi", 123, true, 90.99, func() {}} { switch v := reflect.ValueOf(v); v.Kind() { case reflect.String: fmt.Printf("%s 是一个字符串\n", v.String()) case reflect.Bool: fmt.Printf(...
package constants type OrderStatus struct { New uint8 Checked uint8 Paid uint8 Canceled uint8 } var ORDER_STATUS = OrderStatus{ New: 0, Checked: 1, Paid: 2, Canceled: 3, }
package spark import ( "github.com/gin-gonic/gin" ) // ApplyRoutes applies router to the gin Engine func ApplyRoutes(r *gin.RouterGroup) { posts := r.Group("/spark") { posts.POST("/pv_by_urls", PostDailyPV) posts.POST("/pv_monthly_by_urls", PostMonthlyPV) posts.POST("/total_pv_by_urls", PostTotalPV) posts....
package main import ( "bufio" "errors" "fmt" "os" "strconv" "strings" ) func main() { //標準入力を取得 stdin, err := FetchStdin() if err != nil { panic(err) } // fmt.Println(stdin) //問題文に沿ってデータを整形 pd, err := formatPracticeData(stdin) if err != nil { panic(err) } // tools.PrintStruct(pd) //判定処理 output...
package http import ( "bytes" "encoding/json" "strings" "github.com/miRemid/mio" "github.com/miRemid/mioqq" ) // CQParams 参数 type CQParams map[string]interface{} // CQContext 用户对话 type CQContext struct { Context *mio.Context API *mioqq.API handlers []HandleFunc index int Params []string quick...
package gaodeMap import ( "fmt" "errors" ) type GaodeMapClient struct { ak string } func NewGaodeMapClient(ak string) *GaodeMapClient { return &GaodeMapClient{ak: ak} } func (ac *GaodeMapClient) GetAk() string { return ac.ak } func (ac *GaodeMapClient) SetAk(ak string) { ac.ak = ak } func (ac *GaodeMapClien...
package postgres import ( "context" "github.com/jmoiron/sqlx" "github.com/quintans/go-clean-ddd/internal/domain" "github.com/quintans/go-clean-ddd/internal/domain/customer" ) type CustomerViewRepository struct { client *sqlx.DB } func NewCustomerViewRepository(db *sqlx.DB) CustomerViewRepository { return Cust...
/* * Copyright (C) 2017-Present Pivotal Software, Inc. All rights reserved. * * This program and the accompanying materials are made available under * the terms of the 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 ...
package kucoin import ( "testing" "time" ) func TestApiService_HfPlaceOrder(t *testing.T) { t.SkipNow() s := NewApiServiceFromEnv() clientOid := IntToString(time.Now().Unix()) p := map[string]string{ "clientOid": clientOid, "symbol": "MATIC-USDT", "type": "limit", "side": "sell", "stp": ...
package galaxy import ( "../gfx" "../basic" "github.com/go-gl/gl/v4.1-core/gl" "math/rand" "math" ) type Galaxy struct { stars []*star } const ( G = 0.00001 ETA = 0.0001 dt = 0.001 DistanceThreshold = 0.5 largeCount = 500 ) func NewGaraxy(smallCount int) *Galaxy { stars := make([]*star, largeCount+smal...
package wrpc /** @author shuai.chen @created 2020年1月8日 连接池实现 **/ import ( "sync" "reflect" "errors" ) const MAX_SIZE int = 8 const MAX_ACTIVE_SIZE int = 4 const WAIT_TIMEOUT int = 10000 //ms type CreateFuncType func(...string) (interface{}, error) // pool block type PoolBlock struct { List *Queue //队...
package oauth import ( "net/http" "net/url" "strings" "testing" ) // Make sure there's no panics such as nil pointer dereferences func TestAuthorize(t *testing.T) { method := "POST" uri := "http://example.com" consumer := &Consumer{"abc", "123"} token := &Token{"xyz", "+∞"} in, _ := http.NewRequest(method, ...
package main; import ( "encoding/json" "strconv" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" ) // db part type Tx struct{ Number uint64 `gorm: "not null"` Hash string `gorm: "not null"` Data string `gorm: "not null; unique; index;"` } func (tx *Tx) to...
package model type OptionTime struct { Id int `json:"id"` Start string `json:"start"` End string `json:"end"` Disabled bool `json:"disabled"` }
package goutils import ( "io/ioutil" "os" "path" "path/filepath" "strings" ) // CheckFile checks if file exists returns "dir"|"file"|"" func CheckFile(filename string) string { info, err := os.Stat(filename) if err != nil { return "" } if info.IsDir() { return "dir" } return "file" } // ReadDir return...
package cascade import ( "context" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "strings" "github.com/rs/zerolog" "github.com/sirkon/goproxy/internal/errors" "github.com/sirkon/goproxy" ) var _ goproxy.Module = &cascadeModule{} type cascadeModule struct { mod string reqMod string url ...
// Package bot exports a Bot interface to manage bots // for differents platforms easily. package bot import ( "fmt" "github.com/danielkvist/botio/client" ) // Bot is an interface to manage bots for differentes platforms. type Bot interface { Connect(c client.Client, addr string, token string, cap int, defaultRes...
package library import ( "encoding/json" "errors" ) type MixInt int func (u *MixInt) UnmarshalJSON(bs []byte) error { var i int if err := json.Unmarshal(bs, &i); err == nil { *u = MixInt(i) return nil } var s string if err := json.Unmarshal(bs, &s); err != nil { return errors.New("expected a string or a...
// Package main - задание шестого урока для курса go-core. package main import ( "fmt" "go.core/lesson6/pkg/cache/local" "go.core/lesson6/pkg/crawler" "go.core/lesson6/pkg/crawler/spider" "go.core/lesson6/pkg/engine" "go.core/lesson6/pkg/index" "go.core/lesson6/pkg/storage" "go.core/lesson6/pkg/storage/bstree"...
package server const ( BufferSize = 256 HostnameSize = 64 PodNameSize = 253 ContainerNameSize = 253 PodNamespaceSize = 253 PodUIDSize = 32 ) type TtyWrite struct { Count uint32 Buffer [BufferSize]byte Timestamp uint64 Inode uint64 Mou...
package main import ( "strings" "testing" ) var encoded = "0222112222120000" var layers = []Layer{ Layer{2, 2, []Pixel{0, 2, 2, 2}}, Layer{2, 2, []Pixel{1, 1, 2, 2}}, Layer{2, 2, []Pixel{2, 2, 1, 2}}, Layer{2, 2, []Pixel{0, 0, 0, 0}}, } func TestParse(t *testing.T) { decoded, err := Parse(2, 2, strings.NewRea...
package gomeh import ( "fmt" "io/ioutil" "log" "os" "strings" "testing" "time" ) func readKey() string { f := "./apikey" var key string // If API key env exists use that if env := os.Getenv("meh_apikey"); env != "" { // Read API key from env (for travis) key = env } else { // Read API key from file,...
package privacy_v2 import ( "bytes" "fmt" "testing" "incognito-chain/privacy/coin" "incognito-chain/privacy/key" "incognito-chain/privacy/operation" "incognito-chain/common" "incognito-chain/key/incognitokey" "github.com/stretchr/testify/assert" ) // TEST DURATION NOTE : 100 iterations of 1-to-12 coins = 15s...
package demotest import ( "testing" . "github.com/smartystreets/goconvey/convey" "github.com/yikeso/goDemo/down" ) func TestDownloadUrlFile(t *testing.T){ Convey("测试文件下载方法",t,func(){ err := down.DownloadUrlFile("http://mirrors.sohu.com/centos/7/isos/x86_64/CentOS-7-x86_64-Minimal-1611.iso","e:/dlp") So(err,Sh...
// @APIVersion 1.0.0 // @Title beego Test API // @Description beego has a very cool tools to autogenerate documents for your API // @Contact astaxie@gmail.com // @TermsOfServiceUrl http://beego.me/ // @License Apache 2.0 // @LicenseUrl http://www.apache.org/licenses/LICENSE-2.0.html package routers import ( "scholars...
// Copyright 2022 Google 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 ...
package noise import ( chacha "golang.org/x/crypto/chacha20poly1305" ) var zeroNonce [chacha.NonceSize]byte const ( encryptedKeySize = 48 encryptedNothingSize = 16 ) // EncryptedKey ... type EncryptedKey [encryptedKeySize]byte // EncryptedNothing ... type EncryptedNothing [encryptedNothingSize]byte
package books import ( "github.com/MuchChaca/GoLangTraining/04perso/03iris/04exp_test/authors" "github.com/MuchChaca/GoLangTraining/04perso/03iris/04exp_test/genres" ) // Book represents a book type Book struct { // SessionID string `json:"-"` ID int64 `json:"id,omitempty"` Title string ...
package errors // AirshipError is the base error type // used to create extended error types // in other airshipctl packages. type AirshipError struct { Message string } // Error function implments the golang // error interface func (ae *AirshipError) Error() string { return ae.Message } // ErrNotImplemented retur...
/* Tencent is pleased to support the open source community by making Basic Service Configuration Platform available. Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain...
package main import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" ) var db *sqlx.DB //是一个连接池对象 func initDb() (err error) { //数据库信息 dsn := "root:root@tcp(127.0.0.1:3306)/goday10" //连接数据库 //db 全局的db db, err = sqlx.Connect("mysql", dsn) if err != nil { return } db.SetMaxOpenConns(10)...
package slack import ( "encoding/json" "strings" "testing" "github.com/go-test/deep" ) func TestAttachment_UnmarshalMarshalJSON_WithBlocks(t *testing.T) { originalAttachmentJson := `{ "id": 1, "blocks": [ { "type": "section", "block_id": "xxxx", "text": { "type":...
// Simple program which prints the hostname of your webserver // And return code500 after 10 hits package main import ( "fmt" "log" "net/http" "os" ) const ( listen = "0.0.0.0" port = "8080" ) type counter struct { count int } var c counter func (c *counter) init(initCount int) { c.count = initCount } f...
package models import ( "log" "github.com/go-bongo/bongo" ) func Db() *bongo.Connection { config := &bongo.Config{ ConnectionString: "localhost", Database: "bongotest", } connection, err := bongo.Connect(config) if err != nil { log.Fatal(err) } return connection }
/* Copyright 2011 Google 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 in writing, software di...
package main import "fmt" func main() { //var numbers =make([] int ,3, 5) var numbers1=[] int {1,2,3,4,5} //numbers ={1,2,1,5,6} printSlice(numbers1) numbers2:=numbers1[1:2] printSlice(numbers2) } func printSlice(x [] int ){ fmt.Printf("len=%d\n,cap=%d \n slice=%v\n",len(x),cap(x),x) }
package gen import ( "strings" "text/template" ) type Option func(cfg *config) type config struct { gofmt bool tmplLDelimiter, tmplRDelimiter string funcMap template.FuncMap } var defaultCfg = config{ gofmt: true, tmplLDelimiter: "<<", tmplRDelimiter:...
package restserver import "github.com/astaxie/beego" //MainPage ... type MainPage struct { beego.Controller } //GoMainPage ... func (c *MainPage) GoMainPage() { var index = ` <!DOCTYPE html> <html> <head> <style> #header { background-color: black; color: white; tex...
package tcpexample import ( "fmt" "net" "time" "github.com/meidoworks/nekoq-api/errorutil" "github.com/meidoworks/nekoq-api/network" "github.com/meidoworks/nekoq-api/network/tcp" ) func ServerExample() { } func ClientExample(tcpConnStr string, timeout time.Duration) error { conn, err := net.DialTimeout("tcp...
// Package inmemory implements an in-memory registry. package inmemory import ( "context" "sync" "time" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" "github.com/pomerium/pomerium/interna...
package main import ( "fmt" "net" "os" ) func main() { if len(os.Args) != 2 { fmt.Println("Usage: ", os.Args[0], "host") os.Exit(1) } service := os.Args[1] conn, err := net.Dial("ip4:icmp", service) checkError(err) var msg [512]byte msg[0] = 8 msg[1] = 0 msg[2] = 0 msg[3] = 0 msg[4] = 0 msg[5] =...
package main func main() { x, y := 1, 2 defer func(a int) { println("defer x,y = ", a, y) }(x) x += 100 y += 200 println(x, y) }
package main import "fmt" func main() { const ( Enone = 0 Eio = 2 Einval = 5 ) a := [...]string{Enone: "no error", Eio: "Eio", Einval: "invalid argument"} s := []string{Enone: "no error", Eio: "Eio", Einval: "invalid argument"} m := map[int]string{Enone: "no error", Eio: "Eio", Einval: "invalid argume...
package main import ( "fmt" "sync" ) var ( x int64 wg sync.WaitGroup lock sync.Mutex rwlock sync.RWMutex ) func add() { for i := 0; i < 50000; i++ { lock.Lock() // 加锁 x = x + 1 lock.Unlock() // 解锁 } wg.Done() } func Mutex() { wg.Add(2) go add() go add() wg.Wait() fmt.Println(x) } fun...
package main import "fmt" func main() { var numOfCases int fmt.Scanf("%d", &numOfCases) for i := 0; i < numOfCases; i++ { var x int fmt.Scanf("%d", &x) fmt.Printf("Fib(%d) = %d\n", x, fib(x)) } } // Gets the (n+1)th number in the Fibonacci sequence func fib(n int) int64 { if n == 0 { return 0 } if ...
package login import ( "bufio" "fmt" "os" "strings" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/foundriesio/fioctl/client" "github.com/foundriesio/fioctl/subcommands" ) func NewCommand() *cobra.Command { return &cobra.Command{ Use: "login", Short: "Access Foundries.io services w...