text
stringlengths
11
4.05M
/* * Copyright (c) 2019 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 t...
package channelMock import ( "github.com/CardInfoLink/bubble-gum/channelMock/model" "encoding/xml" "github.com/CardInfoLink/log" ) func UnionWxpRefundServive(req *model.MybankReq) []byte { log.Debugf("[rcv req]%+v", req) UnionwxpPayResp := &model.UnionWxpPayResp { UnionWxpCommonBody: model.UnionWxp...
package secrets import ( "encoding/base64" "encoding/json" "fmt" "gopkg.in/yaml.v2" ) // Encode encodes the data field in a secret. func (h *Handler) Encode(data string) ([]byte, error) { secretData := make(map[string]interface{}) if h.outputFormat == "yaml" { err := yaml.Unmarshal([]byte(data), &secretData...
// Coyright alphaair 2016 // 这是一个简单的内存流 package io import ( "io" ) type MemoryStream struct { //暂存数据流 buffer []byte Length int Position int } // NewMemoryStream 以指定大小初始化一个内存数据流 func NewMemoryStream(size int) *MemoryStream { stream := new(MemoryStream) stream.buffer = make([]byte, size) return stream } ...
package main func main(){ } func longestPalindrome(s string) string { a := []rune(s) l := len(a) var temp string for i := 0; i < l; i++{ res, length := One(a, i) if length > len(temp) { temp = res } res, length = Two(a, i) if length > len(temp) { temp = res } } return temp } func One(a []run...
package main import ( "crypto/tls" "crypto/x509" "flag" "io/ioutil" "log" "os" "github.com/titanous/weap/eaptls" "github.com/titanous/weap/radius_eaptls" "layeh.com/radius" ) func main() { certFile := flag.String("cert", "server.pem", "server TLS certificate chain file") keyFile := flag.String("key", "ser...
/* The repo cleaner does the following 1) Switches to master 2) Fetches changes 3) Rebases upon the origin/master 4) Remove all branches except master */ package main import ( "bufio" "github.com/acarl005/stripansi" "github.com/sirkon/cmd-tools/internal/git" "github.com/sirkon/message" "regexp" ) var ( branch...
package api import ( "net/http" "net/http/httptest" "strings" check "gopkg.in/check.v1" "github.com/arxdsilva/olist/storage" "github.com/labstack/echo" ) func (s *S) TestServer_saveRecord(c *check.C) { recordJSON := `{ "type": "start", "timestamp":"2016-02-29T12:00:00Z", "call_id": "qualquercoisa", "...
// Copyright 2017 VMware, 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 func main() { } func isBalanced(root *TreeNode) bool { return height(root) >= 0 } func height(root *TreeNode) int { if root == nil { return 0 } leftHeight := height(root.Left) rightHeight := height(root.Right) if leftHeight == -1 || rightHeight == -1 || abs(leftHeight-rightHeight) > 1 { retur...
package kui import ( "fmt" "strings" "testing" ) func FindShort(s string) int { strs := strings.Split(s, " ") n := len(strs[0]) for _, v := range strs { tmp := len(v) if n > tmp { n = tmp } } return n } func TestFindShort(t *testing.T) { r := FindShort("lol wtf it is complitely \n shit task") fmt....
package api import ( "encoding/json" "fmt" "io/ioutil" "net/http" // "reflect" // "regexp" "joebot/rds" "joebot/tools" "strconv" "strings" // "io" // "os" ) // Expected JSON from Ssherder API // It will come back in an Array of Objects type expectedPlayers struct { ID int `json:"id"` I...
// Copyright 2018 The Cockroach 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 ag...
package main import ( "net" "fmt" "os" ) var filesAll []string func getFiles(filename string) { fileTemp, err := os.Open(filename) if err != nil { fmt.Println(err) return } defer fileTemp.Close() file, _ := fileTemp.Stat() if !file.IsDir() { filesAll = append(filesAll, fileTemp.Name()) return } ...
package postgres var insertUser = ` INSERT INTO users (username, email, password, birthdate) VALUES ($1, $2, $3, $4) RETURNING id; ` var authenticateViaEmail = `SELECT id,username, email, birthdate, password FROM users WHERE email=$1;`
package server import ( "sync" "github.com/anchorfree/kafka-ambassador/pkg/kafka" "github.com/anchorfree/kafka-ambassador/pkg/logger" "github.com/prometheus/client_golang/prometheus" "github.com/spf13/viper" ) // We need this package to prevent cyclic dependencies type I interface { Start(string) Stop() } t...
package main import ( "fmt" "strings" ) func main() { simpleSliceDemo() nestedSliceDemo() appendDemo() } func appendDemo() { var s []int fmt.Println(s) // Add one item to the slice s = append(s, 1) fmt.Println(s) // Add more than on item to the slice s = append(s, 2, 3, 4) fmt.Println(s) } func ne...
package redis import ( "errors" "fmt" "github.com/fzzy/radix/redis" "github.com/phillihq/racoon/config" "github.com/phillihq/racoon/config/gather" "time" ) const ModuleName = "redis" //Redis输出配置 type RedisOutputConfig struct { config.OutputConfig key string `json:"key"` Host []s...
package package2 import ( "fmt" ) func init(){ fmt.Println("from package2 init") }
package handler import ( "context" "errors" "fmt" "github.com/jinmukeji/jiujiantang-services/jinmuid/mysqldb" proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1" ) // UserSignOut 注销用户 func (j *JinmuIDService) UserSignOut(ctx context.Context, req *proto.UserSignOutRequest, resp *proto.UserS...
package actions import ( "errors" "github.com/barrydev/api-3h-shop/src/common/connect" "github.com/barrydev/api-3h-shop/src/factories" "github.com/barrydev/api-3h-shop/src/model" ) func GetProductItemByProductId(productId int64) ([]*model.ProductItem, error) { query := connect.QueryMySQL{ QueryString: "WHERE p...
package module import ( "buddin.us/eolian/dsp" "github.com/mitchellh/mapstructure" ) func init() { Register("SoftClip", func(c Config) (Patcher, error) { var config struct{} if err := mapstructure.Decode(c, &config); err != nil { return nil, err } return newSoftClip() }) } type softClip struct { IO ...
/* To be called after art-app-1a.go on the same VM */ package main // Expects blockartlib.go to be in the ./blockartlib/ dir, relative to // this art-app.go file import "./blockartlib" import ( "crypto/x509" "encoding/hex" "fmt" "io/ioutil" "os" "strings" ) func main() { // Read file content and cast to st...
package mock import ( "github.com/cavke/go-chat-app" ) // UserService represents a mock implementation of myapp.UserService. type UserService struct { UserFn func(id int) (*chatapp.User, error) UserInvoked bool UsersFn func() ([]*chatapp.User, error) UsersInvoked bool // TODO implement additional fu...
// oracmdhold package oracleex import ( "encoding/gob" "fmt" //"github.com/xlab/closer" "gopkg.in/goracle.v1/oracle" "os" "path/filepath" "sync" "sync/atomic" "time" ) type commandHolderChannel struct { cmdChan chan command exitChan chan bool } type commandHolder struct { channels map[string]commandHolde...
package repositoryTemplate import ( "github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/terraform" ) func Provider() terraform.ResourceProvider { return &schema.Provider{ Schema: map[string]*schema.Schema{ "commit_author_email": &schema.Schema{ Type: schema.TypeString, ...
package main import ( "fmt" "github.com/HuiOnePos/flysnow/models" "github.com/HuiOnePos/flysnow/utils" "github.com/spf13/viper" "io/ioutil" "os" "reflect" "strings" ) var S_Expmap = map[string]sExpStruct{ "&&": sExpStruct{-1, "bool", []string{"eq", "bool"}, " && "}, "==": sExpStruct{2, "bool", []string{"eq"...
package main import "testing" import "github.com/stretchr/testify/assert" func TestString(t *testing.T) { assert.Equal(t, "TS", Card{10, 'S'}.String(), "") } func TestCardFromStr(t *testing.T) { assert.Panics(t, func() { CardFromStr("5") }, "invalid length") assert.Panics(t, func() { CardFromStr("1D") }, "invalid...
package main import ( "github.com/liuzl/dict" "github.com/liuzl/store" ) type DictValue struct { Type string `json:"type"` Value interface{} `json:"value"` } type Values []*DictValue type Dictionary struct { dir string kv *store.LevelStore cedar *dict.Cedar }
package entity type UmsAdminRoleRelation struct { Id int64 `json:"id" xorm:"pk autoincr BIGINT(20) 'id'"` AdminId int64 `json:"admin_id" xorm:"default NULL BIGINT(20) 'admin_id'"` RoleId int64 `json:"role_id" xorm:"default NULL BIGINT(20) 'role_id'"` }
package fcache import ( "io/ioutil" "os" "sync" "github.com/nuczzz/lru" "sync/atomic" "time" ) // diskCache disk cache type diskCache struct { // dir directory of disk cache dir string // needCryptKey whether or not crypt key when Set and Get cache, default false. needCryptKey bool // m map of disk cach...
package config // This file includes configs for the run program settings var ( archReadableFiles = []string{ "/lib/arm-linux-gnueabihf/", "/usr/lib/arm-linux-gnueabihf/", } archSyscallAllows = []string{ "fstat64", // 32-bit "_llseek", // 32-bit "fcntl64", // 32-bit "mmap2", // 32-bit // arch "u...
package day12 import ( "fmt" "github.com/kdeberk/advent-of-code/2019/internal/utils" ) type vector [3]int func abs(a int) int { if 0 < a { return -a } else { return a } } func (self vector) length() int { return abs(self[0]) + abs(self[1]) + abs(self[2]) } func (self *vector) add(other vector) { for i ...
package fantasyfootball import ( "fmt" "math" "sort" "sync" ) type DataSource interface { AllPlayers() map[string]*FootballPlayer DefenseSpecialTeams() []*FootballPlayer Kickers() []*FootballPlayer Quarterbacks() []*FootballPlayer RunningBacks() []*FootballPlayer TightEnds() []*FootballPlayer WideReceivers...
package auth import ( "context" "fmt" "net/http" "net/url" "github.com/gorilla/sessions" "github.com/yandex-cloud/examples/serverless/alice-shareable-todolist/app/auth" "github.com/yandex-cloud/examples/serverless/alice-shareable-todolist/app/db" "github.com/yandex-cloud/examples/serverless/alice-shareable-to...
package persistent_storage import ( "fmt" "hub/framework" "hub/persistent_storage/file_operation_status" "io/ioutil" "os" "strings" ) const RuleSetExtension = "ruleset" func DoesFileExist(path string) bool { _, err := os.Stat(path) return !os.IsNotExist(err) } func SafeRename(path, newPath string) error { ...
package dept import ( "github.com/gin-gonic/gin" "net/http" "yj-app/app/model" deptModel "yj-app/app/model/system/dept" deptService "yj-app/app/service/system/dept" "yj-app/app/yjgframe/response" "yj-app/app/yjgframe/utils/gconv" ) //列表页 func List(c *gin.Context) { response.BuildTpl(c, "system/dept/list").Wri...
package entity import "gitee.com/johng/gf/g" type LoanKeys struct { Index int `db:"index" json:"index" field:"index"` Key string `db:"key" json:"key" field:"key"` Text string `db:"text" json:"text" field:"text"` } type LoanTableItem g.Map type Loan struct { Keys []LoanKeys `db:"keys" json:"keys" fie...
package restmachinery import ( "context" "fmt" "log" "net/http" "time" "github.com/brigadecore/brigade-foundations/file" "github.com/gorilla/mux" "github.com/pkg/errors" "github.com/rs/cors" ) // ServerConfig represents optional configuration for a REST API server. type ServerConfig struct { Port in...
package jarviscore import ( "context" "fmt" "math/rand" "os" "sync" "testing" "time" jarvisbase "github.com/zhs007/jarviscore/base" coredbpb "github.com/zhs007/jarviscore/coredb/proto" jarviscorepb "github.com/zhs007/jarviscore/proto" "go.uber.org/zap" ) func randfillFile2(fn string, len int) error { f,...
package user import ( "context" "database/sql" "errors" "github.com/jmoiron/sqlx" ) var ( errRecordNotFound = errors.New("Record not found") ) type Repositiry interface { CreateUser(context.Context, *User) error FindUserByEmail(context.Context, string) (*User, error) FindUserById(context.Context, int) (*Use...
package game_map import "github.com/faiface/pixel" /* IsFinished :Reports when the effect is finished so it can be removed from the list. Update: Updates the effect according to the elapsed frame time. Render :Renders the effect to the screen. Priority: Controls the render order. For instance, the jumping numbers sho...
package timewheel import ( _ "container/list" "fmt" //"time" //"sync" ) type TimeWheelCallBack func(val interface{}) type TimeWheelTaskData struct { wheel int32 slot int32 duration int64 ticks int64 chunkId int32 isCycle bool data interface{} callBack TimeWheelCallBack } type slot struct...
package controller import ( "encoding/json" "errors" "orion/models" "net/http" ) //Registration godoc //@Summary Handle unique User Registration //@Description Accept JSON data of User objects and returns valid response //@Accept json //@Tags Authentication //@produce json //@Param UserData body models.Reg...
package cli import ( "flag" "fmt" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "k8s.io/klog" ) type DebugConfig struct { Debug bool DebugLevel int } func (c *DebugConfig) MustSetupDebug() { err := c.SetupDebug() if err != nil { panic("failed to setup debug logging: " + err.Error()) } } fu...
package main import ( "math" ) func reverse(x int) int { sign := 1 if x < 0 { sign = -1 x *= sign } var d []int for x > 0 { d = append(d, x%10) x /= 10 } if len(d) == 10 { sigDig := 0 intMaxSigDigMag := 1_000_000_000 for sigDig < 10 { intMaxSigDig := getIntMaxSigDig(intMaxSigDigMag, sign) ...
package ctl import ( "fmt" "log" "testing" "github.com/vhaoran/vchat/lib" "github.com/vhaoran/vchat/lib/ymongo" ) type MongoHello struct { ID int CName string Age int } func Test_insert_one(t *testing.T) { // load config opt := &lib.LoadOption{ LoadMicroService: false, LoadEtcd: false, ...
package command import ( "testing" ) func TestCommand(t *testing.T) { fakeCommand := &FakeCommand{} err := fakeCommand.Run(nil, nil, nil) if err != nil { t.Fatalf("FakeCommand unexpectedly returned error: %v", err) } streamCommand := NewStreamCommand("echo", []string{"hello"}) err = streamCommand.Run(nil, n...
package mysql import ( "database/sql" "errors" "github.com/gedelumbung/go-movie/model" "github.com/gedelumbung/go-movie/repository" "github.com/jmoiron/sqlx" ) type categoryRepository struct { db *sqlx.DB } const selectCategory = `select id, name, created_at, updated_at from categories` func (o *categoryRepo...
package main import ( "bufio" "fmt" "os" "strconv" ) func main() { defer w.Flush() // Implement from here } // IO Utils var ( sc = bufio.NewScanner(os.Stdin) w = bufio.NewWriter(os.Stdout) ) const ( initBufSize = 1024 * 1024 maxBufSize = 1024 * 1024 * 1024 ) func init() { buf := make([]byte, initBufS...
package reflection import ( "context" "fmt" "reflect" ) var ( ErrorType = reflect.TypeOf((*error)(nil)).Elem() ErrorZeroValue = reflect.Zero(ErrorType) ContextType = reflect.TypeOf((*context.Context)(nil)).Elem() ) func IsOfErrorType(typ reflect.Type, nameOfVariable string) error { if !typ.Implements(Er...
package auth import ( "net/http" ) type Transport interface { CreateUser(w http.ResponseWriter, r *http.Request) GetAllUsers(w http.ResponseWriter, r *http.Request) GetUser(w http.ResponseWriter, r *http.Request) UpdateUser(w http.ResponseWriter, r *http.Request) DeleteUser(w http.ResponseWriter, r *http.Reques...
package remotes import ( "context" "github.com/deps-cloud/discovery/api" "github.com/deps-cloud/discovery/pkg/config" "google.golang.org/grpc" ) var _ Remote = &rdsRemote{} // NewRDSRemote produces a remote connecting to another RDS func NewRDSRemote(config *config.Rds) (Remote, error) { opts := []grpc.DialOp...
package grpc_gracefully_restart import ( log "code.google.com/p/log4go" "fmt" "os" "sync" "time" ) type Manager struct { msList []*Server wg sync.WaitGroup closed bool } func NewManager() *Manager { return &Manager{ msList: []*Server{}, } } func (m *Manager) LoadServers(env string, addr []string) { ...
package main import ( "context" "io" "log" "net/http" "strings" handlers "github.com/bernljung/lambda-golang" ) func callHandler(w http.ResponseWriter, r *http.Request) { res, err := handlers.HandlerFunc(context.Background(), strings.TrimPrefix(r.URL.Path, "/")) if err != nil { log.Fatal(err) } io.WriteS...
package main import ( "bufio" "fmt" "image" "image/color" "image/png" "math/rand" "os" "time" ) func main() { if err := start(); err != nil { fmt.Println(err.Error()) } } func start() error { rect := image.Rectangle{ Min: image.Point{0, 0}, Max: image.Point{512, 512}, } var m *image.RGBA m = ...
package lineGo import ( talk "github.com/n4tsumi/lineGo/talkservice" "github.com/apache/thrift/lib/go/thrift" "log" "net/http" ) type LoginType int const ( authToken LoginType = iota qrCode ) type LineLogin interface { Type() LoginType Value() string } type AuthTokenLogin string func (a AuthTokenLogin) Ty...
package gourmet import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "net/url" "os" ) const ( gourmetBaseURL = "https://api.gnavi.co.jp/RestSearchAPI/v3/?" ) // Response クエリの結果を格納する構造体 type Response struct { TotalHit int `json:"total_hit_count"` Rests []Restaurant `json:"rest"` } // Res...
package graphql import ( "github.com/Tinee/go-graphql-chat/domain" jwt "github.com/dgrijalva/jwt-go" ) func (r *Resolver) claimJWT(u domain.User) string { token := jwt.New(jwt.SigningMethodHS256) claims := token.Claims.(jwt.MapClaims) claims["id"] = u.ID claims["username"] = u.Username t, _ := token.SignedStr...
package models import ( "context" errors2 "github.com/misgorod/co-dev/errors" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "golang.org/x/crypto/bcrypt" ) type RegUser struct { ID primitive.ObjectID `json:"id" bson:"_id,omitempty" val...
package utils import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" ) const endpointsKind = "Endpoints" // UpdateEndpointsFunc UpdateEndpoints function type type UpdateEndpointsFunc func(ep *corev1.Endpoints, svc *corev1.Service, sche...
package main import ( "fmt" "strings" "time" . "github.com/Pyorot/streams/src/utils" "github.com/nicklaw5/helix" ) var getStreamsParams helix.StreamsParams // the const argument for getStreams calls, initialised in main.go:init() var authed bool // is current auth token believed to be ...
package hateoas import "net/http" func handleCreate(w http.ResponseWriter, r *http.Request, rh ResourceHandler) *Error { var err *Error err = &Error{} err.Status = 500 err.Code = 1 err.Message = "Create is under construction. Please check again later." err.DeveloperMessage = "API is not ready yet. Please conta...
package main import ( "fmt" "github.com/codesoap/ytools" "golang.org/x/net/html" "net/http" "net/url" "os" "strings" ) const max_results = 12 type Video struct { Title string Url string } func main() { search_url := get_search_url() videos, err := scrape_off_videos(search_url) if err != nil { os.Exi...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-08-12 10:06 # @File : lt_260_Single_Number_III.go # @Description : # @Attention : */ package byte func singleNumber3(nums []int) []int { diff := 0 // 将只出现1次的数据保留下来 for i := 0; i < len(nums); i++ { diff ^= nums[i] } // result中保存的是 只出现1次的数字,这个时候的数字是...
package main import ( "encoding/json" "fmt" "jwtproxy/jwt" "jwtproxy/middleware" "net/http" "strconv" "time" ) const port = ":4000" const secret = "terces" func main() { http.HandleFunc("/authen", func(w http.ResponseWriter, r *http.Request) { var data map[string]interface{} json.NewDecoder(r.Body).Decod...
package tonberry import ( "encoding/json" "github.com/zeroshade/Go-SDL/sdl" "image" "io/ioutil" ) var ( maps map[string]mapInfo ) type mapInfo struct { SpriteFile string `json:"file"` THeight int `json:"tile_height"` TWidth int `json:"tile_width"` LHeight uint16 `json:"level_...
package main import ( "strings" ) /** 459. 重复的子字符串 给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成。给定的字符串只含有小写英文字母,并且长度不超过10000。 示例1: ``` 输入: "abab" 输出: True 解释: 可由子字符串 "ab" 重复两次构成。 ``` 示例2: ``` 输入: "aba" 输出: False ``` 示例3: ``` 输入: "abcabcabcabc" 输出: True 解释: 可由子字符串 "abc" 重复四次构成。 (或者子字符串 "abcabc" 重复两次构成。) ``` */ /** 这有点不像简单题,...
package prams import("os") func Get(str string) (string, bool){ a := os.Args[1:] argsString := "" argsBool := false for key, _ := range a { if(a[key] == str){ argsBool = true if(len(a) > key + 1){ argsString = a[key + 1] }else{ argsString = "" } } } return argsString, argsBool }
package image import "math" // Grayscale : Transforms n-channel image into grayscale // (not really a gray scale) func Grayscale(image *CHWImage) *CHWImage { grayImage := NewImage(image.Height, image.Width, 1) imageSize := image.Height * image.Width for i := 0; i < imageSize; i++ { grayImage.Data[i] = image.Data...
package types import "github.com/google/uuid" // Order represents an order on the exchange type Order struct { // UserReference user reference of the order UserReference uuid.UUID // Symbol of the order Symbol Symbol // Side of the order Side Side // Type of the order Type OrderType // TimeInForce of the...
package routes import ( "testing" "github.com/nedp/remotecmds/say" "github.com/nedp/remotecmds/router" "github.com/nedp/command/sequence" "github.com/stretchr/testify/assert" ) func TestSay(t *testing.T) { const testString = ` say: Quote = "This is the route test." ` rt := testHelper(t, "say", testStr...
// IDGenerator.go package Common //type ID uint64 //type ID32 uint32 type IDGenerator struct { incID uint64 incID32 uint32 } func NewIDGenerator() *IDGenerator { return &IDGenerator{ incID: 0, incID32: 0, } } //start id is 1. func (g *IDGenerator) NewID() uint64 { g.incID++ return g.incID } func (g *...
package repositories_test import ( "context" "testing" "github.com/syncromatics/kafmesh/internal/graph/model" "gotest.tools/assert" ) func Test_Topic_ProcessorInputs(t *testing.T) { repo := repos.Topic() r, err := repo.ProcessorInputsByTopics(context.Background(), []int{1, 2, 3, 4}) assert.NilError(t, err) ...
package main /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // 判断一棵树是否为完全二叉树 func isCompleteTree(root *TreeNode) bool { queue := []*TreeNode{root} nullAppe...
package util import ( "fmt" "os" "testing" ) func TestSetupSignalHandler(t *testing.T) { stopCh := SetupSignalHandler() go func() { <-stopCh fmt.Print("done") }() InjectSignal(os.Interrupt) }
package k8s import ( "testing" "net/http/httptest" "net/http" ) func TestRouter(t *testing.T) { r := Router() ts := httptest.NewServer(r) defer ts.Close() res, err := http.Get(ts.URL + "/home") if err != nil { t.Fatal(err.Error()) } if res.StatusCode != http.StatusOK { t.Errorf("Status code for /hom...
package _306_Additive_Number import "testing" func TestIsAdditiveNumber(t *testing.T) { if !isAdditiveNumber("112358") { t.Errorf("should be true") } if !isAdditiveNumber("199100199") { t.Errorf("should be true") } if isAdditiveNumber("1023") { t.Errorf("should be false") } if isAdditiveNumber("1203") { ...
// 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...
// 常规的通过通道发送和接收数据是阻塞的。然而,我们可以 // 使用带一个 `default` 子句的 `select` 来实现_非阻塞_ 的 // 发送、接收,甚至是非阻塞的多路 `select`。 package main import "fmt" func main() { messages := make(chan string) signals := make(chan bool) // 这里是一个非阻塞接收的例子。如果在 `messages` 中 // 存在,然后 `select` 将这个值带入 `<-messages` `case` // 中。如果不是,就直接到 `default` 分支中。 se...
package realm_test import ( "fmt" "testing" "github.com/10gen/realm-cli/internal/cloud/realm" "github.com/10gen/realm-cli/internal/local" u "github.com/10gen/realm-cli/internal/utils/test" "github.com/10gen/realm-cli/internal/utils/test/assert" "go.mongodb.org/mongo-driver/bson/primitive" ) func TestRealmUse...
package config import ( "io/ioutil" oconfig "github.com/olebedev/config" ) const ( // cfg for dipper network DefautlDipSdkCfgFileAbsPath = "/Users/sun/go/src/github.com/Dipper-Labs/dip-bridge/config/dip_sdk.yaml" DefaultDipChainDipManagerAddr = "dip16qe2drpsxtdgmpw0pxhte649gzezg4e5q8zzes" DefaultDipChainDipM...
package numeric import ( "reflect" ) // Promote the arguments' type, so they are of the same type. // // Convert to the lowest type common that can contain the respective // values of the arguments, without (or with least) precision loss. // // Note: that calling with uint8(0),int8(0) will return int16(0),int16(0...
package labelblocker import ( "reflect" "strings" "testing" "github.com/sirupsen/logrus" "github.com/ti-community-infra/tichi/internal/pkg/externalplugins" "k8s.io/test-infra/prow/config" "k8s.io/test-infra/prow/github" "k8s.io/test-infra/prow/github/fakegithub" ) func TestLabelBlockerPullRequest(t *testing....
package main import ( "os" "path/filepath" "gopkg.in/urfave/cli.v1" ) func initCli() *cli.App { return &cli.App{ Name: filepath.Base(os.Args[0]), HelpName: filepath.Base(os.Args[0]), Usage: "CDS Event Listener & Cache for unity monitoring", UsageText: "", Author: "Steven GUI...
/* Copyright 2019 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 writing, software dis...
package main import ( "fmt" "math" "os" ) func main() { var name string name = "World" var i int var j float64 var b bool os.Stderr.WriteString(fmt.Sprintf("Hello %s %d %f %t\n", name, i, j, b)) os.Stderr.WriteString(fmt.Sprintf("%.10f\n", math.Pi)) }
package pkg1a import ( "github.com/tralexa/go-mod1/pkg/pkg1b" "github.com/tralexa/go-mod1/pkg/pkg1c" "github.com/tralexa/go-mod1/pkg/pkg1d" "github.com/tralexa/go-mod1/pkg/pkg1e" ) func Do() { pkg1b.Do() pkg1c.Do() pkg1d.Do() pkg1e.Do() }
// Copyright 2016 Red Hat, 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 agree...
package db import ( "database/sql" "fmt" . "go-sugar/config" "github.com/go-sql-driver/mysql" ) // SimpleRepo Simple Repository interface type SimpleRepo interface { DeleteByID(int) bool GET() } // DB SQL DB Connect var DB *sql.DB // Connect main func for connect to DB func Connect() *sql.DB { var err erro...
package parser import ( "github.com/PuerkitoBio/goquery" "util" "fmt" "spider/entity" "time" ) type ProvParser struct { List []entity.JobInfo } func (this *ProvParser) SelectorService(i int, selection *goquery.Selection) { defer func() { if err := recover(); err != nil { html, _ := selection.Html() fm...
package main import ( "errors" "github.com/caos/orbos/pkg/git" orbcfg "github.com/caos/orbos/pkg/orb" boomapi "github.com/caos/orbos/internal/operator/boom/api" "github.com/caos/orbos/internal/operator/orbiter" orbadapter "github.com/caos/orbos/internal/operator/orbiter/kinds/orb" "github.com/caos/orbos/pkg/...
package steps import ( "github.com/chromedp/cdproto/cdp" "github.com/chromedp/chromedp" "github.com/cucumber/godog" "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) var legacyElementMap = map[string]string { "missing email": "", "missing password": "#input-error-password", } // This steps actual...
// Copyright 2017 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...
// Copyright 2021 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 persistence import ( "github.com/hyeyoom/go-web-app-boilerplate/domain" "gorm.io/gorm" ) type productRepository struct { repository } func NewProductRepository(db *gorm.DB) domain.ProductRepository { var pr productRepository pr.db = db return &pr } func (mr *productRepository) Create(product *domain.P...
package chat import ( "testing" "github.com/stretchr/testify/assert" ) func TestSplitGroups(t *testing.T) { slice := []string{"a", "b", "c", "d", "e"} res := splitGroups(slice, 3) assert.Len(t, res, 2) assert.Equal(t, []string{"a", "b", "c"}, res[0]) assert.Equal(t, []string{"d", "e"}, res[1]) slice = []str...
/* * Tencent is pleased to support the open source community by making Blueking Container Service 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 obta...
package struct_util import ( "fmt" "testing" ) func TestMyHeap(t *testing.T) { heap := NewMyHeap(100, func(a, b interface{}) bool { return a.(int) > b.(int) }) heap.Push(3) heap.Push(2) heap.Push(5) heap.Push(1) heap.Push(2) fmt.Println(heap.data) fmt.Println(heap.Pop()) fmt.Println(heap.data) fmt.Prin...
package models import ( "strconv" "github.com/jinzhu/gorm" ) // Histories — история точки type Histories struct { gorm.Model PointID uint UserID uint Score int } // ToMap string-string func (h Histories) ToMap() map[string]string { out := make(map[string]string) out["Created"] = h.CreatedAt.String() ou...