text
stringlengths
11
4.05M
package main import ( "fmt" "reflect" ) type Z struct { Id int } type V struct { Id int F Z } type T struct { Id int F V } func InspectStructV(val reflect.Value) { if val.Kind() == reflect.Interface && !val.IsNil() { elm := val.Elem() if elm.Kind() == reflect.Ptr && !elm.IsNil() && elm.Elem().Kind() ...
package main import ( "fmt" "os" "time" log "github.com/sirupsen/logrus" _ "github.com/multisocket/multisocket/transport/all" "github.com/multisocket/multisocket" "github.com/multisocket/multisocket/address" "github.com/multisocket/multisocket/connector" "github.com/multisocket/multisocket/receiver" "githu...
package testapplication import ( "fmt" "strings" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) //query endpoints supported by the nameservice Querier const ( QueryResolve = "resolve" // used to get the value of the hash ...
package baremetal import ( "math" "net" "github.com/go-logr/logr" "github.com/redhat-cop/egressip-ipam-operator/controllers/egressipam/reconcilecontext" corev1 "k8s.io/api/core/v1" ctrl "sigs.k8s.io/controller-runtime" ) type BareMetalInfra struct { log logr.Logger } func NewBareMetalInfra() *BareMetalInfra ...
package mhfpacket import ( "errors" "github.com/Andoryuuta/Erupe/network" "github.com/Andoryuuta/Erupe/network/clientctx" "github.com/Andoryuuta/byteframe" ) // MsgMhfEnumerateShop represents the MSG_MHF_ENUMERATE_SHOP type MsgMhfEnumerateShop struct { AckHandle uint32 ShopType uint8 // 1 running gachas, 10 n...
// Copyright 2020 The Operator-SDK 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 ...
package helper import ( "bytes" "io" "io/ioutil" "mime/multipart" "os" "path/filepath" ) // Creates a new file upload http request with optional extra params func generate(params map[string]string, paramName, path string) error { file, err := os.Open(path) if err != nil { return err } defer file.Close() ...
package main import ( "fmt" "github.com/deepglint/util/io/json" ) type Planet struct { Scenes map[string]Scene } type Scene struct { Cameras map[string]Camera } type Camera struct { Id string RtspServerPort int } func main() { var planet Planet json.DeserializeFromFile("planet.json", &planet) ...
//+build test package testdata import ( "sync" "time" "github.com/aprice/embed/loader" ) var _embeddedContentLoader loader.Loader var _initOnce sync.Once // GetEmbeddedContent returns the Loader for embedded content files. func GetEmbeddedContent() loader.Loader { _initOnce.Do(_initEmbeddedContent) return _emb...
package timeline import ( "time" ) func parseDateStamp(s string) time.Time { pattern := "2006-01-02" t, _ := time.Parse(pattern, s) return t } func incrementDay(t *time.Time) { *t = time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, time.UTC) } func dayIndex(given time.Time, first time.Time, last time.Time)...
package stitch import ( "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "time" ) // PURPOSE: // Use an API key to create a session with which to interact with the Stitch API. // // Example Token: // { // "ephemeral_token":"<EPHEMERAL_TOKEN>" // } const HostURL string = "https://api.stitchdata.com"...
// Copyright 2020 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 retry import ( "context" "errors" "reflect" "testing" "time" ) var delta = 10 * time.Millisecond func TestRetry(t *testing.T) { type Assert struct { Attempts uint Error func(error) bool } tests := []struct { name string breaker BreakCloser strategies []func(attempt uint, err er...
package user import ( "strings" "github.com/goodplayer/Princess/repository" "github.com/gofrs/uuid" "golang.org/x/crypto/bcrypt" ) type User struct { user *repository.User UserId string Username string AliasName string password string Status int } func (u *User) InitFill(username string) *User { ...
// Copyright 2014 The Sporting Exchange Limited. All rights reserved. // Use of this source code is governed by a free license that can be // found in the LICENSE file. package statse import ( "testing" "time" ) func messageV2Raw(body string) [][]byte { return [][]byte{ []byte("2 1234567890000"), []byte(body)...
package handlers import ( "encoding/json" "github.com/kuznetsovin/go.geojson" "github.com/labstack/echo" "io" "net/http" "net/http/httptest" "simple-tracking/backend/models" "time" ) func createReq(httpMethod, endpoint, urlParams string, body io.Reader) *http.Request { target := endpoint if urlParams != "" ...
// +build linux darwin package hfm var HostsPath = `/etc/hosts`
package day02_函数_工程管理 import "fmt" func FFF() { fmt.Println("AAAAAAAAAAAAAAAAAA") }
package oidc_test import ( "crypto/ecdsa" "crypto/rsa" "crypto/x509" "fmt" "net/url" "os" "strings" "github.com/authelia/authelia/v4/internal/configuration/schema" "github.com/authelia/authelia/v4/internal/utils" ) const ( pathCrypto = "../configuration/test_resources/crypto/%s.%s" myclient = "m...
package main import ( "net/http" "quote_wall/router" "fmt" ) func main() { port := "8080"; fmt.Println("Server is running at port : ",port); router.HandleRequest(); http.ListenAndServe(":" + port, nil) }
package manager import ( "github.com/golang/glog" "sub_account_service/order_server_zhengdao/config" "sub_account_service/order_server_zhengdao/lib" "time" ) func InitTransfer() { go func() { for { glog.Infoln("1.定时获取未转账成功的订单,向企业用户转账") if time.Now().Hour() == config.Opts().ReTransferTime { if err :=...
package main import "fmt" type F struct { Name string Age int } // Stringer interfaceを実装 func (f *F) String() string { return fmt.Sprintf("Name=%q, Age=%d", f.Name, f.Age) } func main() { f := &F{ Name: "John", Age: 20, } fmt.Printf("%v\n", f) }
package tlvconverter const ( // PACKET is the PacketType marker PACKET = 1 // UINT64 is the unsigned integer at 64 marker UINT64 = 2 // FLOAT64 is the unsigned float at 64 marker FLOAT64 = 3 // BOOL is the bool marker BOOL = 4 ) // PacketType is the struct implementing the packet saved as tlv byte array in th...
/* Given the root of an n-ary tree, return the postorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) Example 1: Input: root = [1,null,3,2,4,null,5,6] Output: [5,6,3,2,4,1] Example 2...
/* * Copyright 2018, CS Systemes d'Information, http://www.c-s.fr * * 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 requir...
package wsyscall import "syscall" const ( MS_BIND = 1 << iota MS_RDONLY RUSAGE_CHILDREN = iota RUSAGE_SELF RUSAGE_THREAD ) type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Ou...
package commands import ( "errors" "fmt" "io" "os" "path/filepath" "strings" "syscall" "github.com/spf13/cobra" "github.com/spf13/pflag" "golang.org/x/term" "gopkg.in/yaml.v3" "github.com/authelia/authelia/v4/internal/configuration" "github.com/authelia/authelia/v4/internal/model" "github.com/authelia/...
package transport import ( "context" "errors" "github.com/go-kit/kit/log" httptransport "github.com/l-vitaly/go-kit/transport/fasthttp" "github.com/l-vitaly/golang-test-task/pkg/endpoint" "github.com/l-vitaly/golang-test-task/pkg/service" "github.com/pquerna/ffjson/ffjson" routing "github.com/qiangxue/fasthtt...
// Copyright 2023 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applica...
package bolt import ( "os" "testing" "github.com/stretchr/testify/assert" ) func makeBoltDBClient(t *testing.T) *Store { kv, err := New("/tmp/not_exist_dir/__boltdbtest", WithBucket("bucket")) if err != nil { t.Fatalf("cannot create store: %v", err) } return kv } func TestMutipleDB(t *testing.T) { kv, er...
package helpers import ( "bufio" "errors" "fmt" "os" "strings" ) const env_file = "./.env" func Setenv(key string, value string) error { var text string text = fmt.Sprintf("%s=%s\n", key, value) f, err := os.OpenFile(env_file, os.O_APPEND|os.O_WRONLY, 0600) if err != nil { return err } defer f.Close() ...
/* Copyright 2019 Cornelius Weig. 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...
package main import ( "log" LogController "./controllers/logg" BankController "./controllers/banks" UserController "./controllers/users" "./db" "github.com/buaazp/fasthttprouter" "github.com/valyala/fasthttp" ) func main() { //TODO user profile url := "localhost" port := "8020" LogController.Info("Serv...
package object var NULL = &Null{} var TRUE = &Boolean{Value: true} var FALSE = &Boolean{Value: false}
package main import "fmt" func main() { var i int = 1200 // 環境依存 //int8 //int16 //int32 //int64 var i2 int64 = 200 fmt.Println(i) // 環境依存と明示的なintは計算できない //fmt.Println(i+i2) //型を表示する fmt.Printf("%T\n", i2) //cast fmt.Printf("%T\n", int32(i2)) //cast and plus fmt.Println(i + int(i2)) }
package log import ( "fmt" "runtime" "strings" ) func Caller() map[string]interface{} { pc, file, line, ok := runtime.Caller(2) if !ok { return map[string]interface{}{} } _func := runtime.FuncForPC(pc) if _func == nil { return map[string]interface{}{} } function := _func.Name() parts := strings.Split...
package kube import ( "context" "deployfromgo/src/config" "deployfromgo/src/logger" "errors" "fmt" "github.com/Lvzhenqian/sshtool" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" "github.com/docker/go-connections/nat" "golang.org/x/crypto...
package models import ( "WhereIsMyDriver/helper" "WhereIsMyDriver/structs/api" "strconv" "testing" "github.com/icrowley/fake" . "github.com/smartystreets/goconvey/convey" "golang.org/x/crypto/bcrypt" ) var user = new(User) func init() { for index := 0; index < 500; index++ { var user = User{} var error...
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-08-24 12:02 * Description: *****************************************************************/ package rpcPoint import ( "github.com/apache/thrift/lib...
package main import ( "os" "os/exec" "path/filepath" demo "github.com/saschagrunert/demo" ) func main() { d := demo.New() d.Add(containerDays21Run(), "containerdays 21 demo", "containerdays 21 demo") d.Add(kwctlRun(), "kwctl demo", "kwctl demo") d.Add(policyServerRun(), "policy-server demo", "policy-server d...
package main import ("fmt" "os" "bufio" "syscall" "os/signal" ) func main() { for i := 0; i > 0; i++ { } ch := make(chan os.Signal, 1) signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGKILL) scanner := bufio.NewScanner(os.Stdin) scanner.Scan() text := scanner.Text() ...
package api import ( "admigo/common" c "admigo/controllers" "errors" "github.com/julienschmidt/httprouter" "net/http" ) const ( api = "api" ) func UserCanDo(h httprouter.Handle) httprouter.Handle { return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { w.Header().Set("Content-Type", "ap...
package main import ( "fmt" "sort" ) type customReverse struct { sort.Interface } func (r customReverse) Less(i, j int) bool { return r.Interface.Less(j, i) } func RunEmbed1() { data := []int{4, 5, 2, 8, 1, 9, 3} sort.Sort(sort.IntSlice(data)) fmt.Println("After library Sort: ", data) rev := &customReverse...
// Copyright (c) 2015 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package wallet import ( "fmt" "os" ) // checkCreateDir checks that the path exists and is a directory. // If path does not exist, it is created. func checkCreateDir(path ...
// Copyright 2020, Jeff Alder // // 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 a...
package handlers import ( "net/http" "github.com/saurabmish/Coffee-Shop/data" ) func (p Products) Remove(w http.ResponseWriter, r *http.Request) { p.l.Println("[INFO] Endpoint for DELETE request") w.Header().Add("Content-Type", "application/json") id := getProductID(r) p.l.Println("[DEBUG] Retrieved product I...
package pgsql import ( "testing" ) func TestNumeric(t *testing.T) { testlist2{{ data: []testdata{ { input: int(-9223372036854775808), output: int(-9223372036854775808)}, { input: int(9223372036854775807), output: int(9223372036854775807)}, }, }, { data: []testdata{ { input: in...
package main import "testing" type TestTable struct { a, b int expected int } var tt = []TestTable{ {2, 3, 5}, {3, -3, 0}, {4, 5, 9}, {1, 10, 11}, {0, 0, 0}, } func TestAdd(t *testing.T) { for _, test := range tt { if out := Add(test.a, test.b); out != test.expected { t.Error("Test Failed!") } }...
package main import ( "gobot.io/x/gobot/drivers/i2c" "gobot.io/x/gobot/platforms/raspi" "log" ) /* ・PWMサイクル:20mS ・制御パルス:0.5ms~2.4ms ・制御角:±約90°(180°) ・配線:茶=GND、赤=電源[+]、橙=制御信号 [JRタイプ] ・トルク:2.5kgf・cm ・動作速度:0.1秒/60度 ・動作電圧:4.8V ・温度範囲:0℃~55℃ ・外形寸法:23x12.2x27mm ・重量:9g */ const ( freq = 50.0 // 50 Hz ms = 10...
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().Unix()) r := rand.Float64() switch { case r > 0.1: fmt.Println("Common case, 90% of the time") default: fmt.Println("10% of the time") } }
package main import ( "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/json" "net/http" ) func (ah APIHandler) LoginHandler(w http.ResponseWriter, r *http.Request) { switch r.Header.Get("Content-Type") { case "application/json": creds := struct { Username string `json:"username"` Password stri...
package gov import ( "fmt" sdk "github.com/ColorPlatform/color-sdk/types" "github.com/ColorPlatform/color-sdk/x/gov/tags" ) // EndBlocker Called every block, process inflation, update validator set func EndBlocker(ctx sdk.Context, keeper Keeper) sdk.Tags { resTags := sdk.NewTags() currentFundingCycle, err := k...
package encode import ( "bytes" "encoding/gob" "fmt" "time" ) // TextMsg - message struct type TextMsg struct { Str string Timestamp time.Time } // Encoder return encoded string as bytes buffer func Encode(str string) bytes.Buffer { msg := TextMsg{ Str: str, Timestamp: time.Now(), } fmt.Pri...
package voicetext import "strconv" type ttsOptions struct { emotion *string emotionLevel *int pitch *int speed *int volume *int } func TtsOptions() *ttsOptions { return &ttsOptions{} } func (o *ttsOptions) Emotion(emotion string) *ttsOptions { o.emotion = &emotion return o } func (...
//Package handlers ... handlers package handlers import ( "bdi-test-service/config" logger "bdi-test-service/logging" "context" "encoding/json" "io/ioutil" "net/http" "strconv" "sync" "time" "github.com/gorilla/mux" ) var ( Sourcepath string Outputpath string Dataset string configID ...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/11/20 10:45 上午 # @File : lt_169_多数元素.go # @Description : # @Attention : */ package offer // 关键: // 排序,找中间值 func majorityElement(nums []int) int { majorityElementQSort(nums, 0, len(nums)-1) return nums[len(nums)>>1] } func majorityElementQSort(nums []int, st...
package main import "fmt" // https://leetcode-cn.com/problems/n-queens-ii/ func totalNQueens(n int) int { row, col := make([]bool, n), make([]bool, n) left, right := make([]bool, 2*n), make([]bool, 2*n) isOK := func(i, j int) bool { return !row[i] && !col[j] && !left[i+j] && !right[n+i-j] } mark := func(i, j ...
package topology import ( "context" "net" "github.com/go-logr/logr" "github.com/golang/protobuf/proto" "github.com/pkg/errors" mesh_proto "github.com/kumahq/kuma/api/mesh/v1alpha1" "github.com/kumahq/kuma/pkg/core/dns/lookup" core_mesh "github.com/kumahq/kuma/pkg/core/resources/apis/mesh" "github.com/kumahq...
package main import "github.com/unixpickle/learn-quantum/quantum" // A SlidingGate is a 4-qubit gate that is run // sequentially with stride 2. type SlidingGate struct { Gate quantum.Gate Invert bool } func (s *SlidingGate) String() string { return "SlidingGate(" + s.Gate.String() + ")" } func (s *SlidingGate)...
package main import ( "os" "github.com/astaxie/beego" _ "github.com/jinzhu/gorm/dialects/mysql" "github.com/jungju/circle_manager/_example/beegoapp/admin" "github.com/jungju/circle_manager/_example/beegoapp/envs" "github.com/jungju/circle_manager/_example/beegoapp/models" "github.com/jungju/circle_manager/_exa...
package main import ( "database/sql" "fmt" "github.com/go-redis/redis/v8" "log" "os" "projja_api/controller" "github.com/go-martini/martini" _ "github.com/go-sql-driver/mysql" ) const ( DSN = "root:Password123#@!@tcp(localhost:3306)/projja?&charset=utf8&interpolateParams=true&parseTime=true" addr = ":8080...
package _009_palindrome_number import ( "testing" "github.com/stretchr/testify/assert" ) func TestName(t *testing.T) { assert.Equal(t, isPalindrome(123), false) }
package main import ( "fmt" "math/rand" "sync" "time" ) var a chan int var wg sync.WaitGroup func tmpadd(n int) int { if n < 10 { return n } if n == 10 { return 1 } return n%10 + tmpadd(n/10) } func randc(c chan<- int, n int) { for i := 1; i <= n; i++ { rand.Seed(time.Now().UnixNano() * int64(i)) ...
package main import "fmt" type Greeter struct { name string } func (g Greeter) Talk() { fmt.Printf("Hello, %s\n", g.name) } func (g *Greeter) Talk2() { fmt.Printf("Hello, %s!\n", g.name) } // END OMIT func main() { var talker = Greeter{"wozozo"} var talkerPtr = &Greeter{"wozozozo"} talker.Talk() ...
package main import ( "sync" ) func main() { var wg sync.WaitGroup master := NewMaster("test/*") wg.Add(1) go func() { defer wg.Done() master.WatchWorkers() }() worker := NewWorker("worker", "localhost:1210") wg.Add(1) go func() { defer wg.Done() worker.HeartBeat() }() wg.Wait() }
package plugs import ( "fmt" log "github.com/Sirupsen/logrus" "go-chat-relay/src/plug" "go-chat-relay/src/plug/config" "strings" ) type AlreadyRegisteredError struct{ s string } func (e *AlreadyRegisteredError) Error() string { return e.s } type PlugRegistry map[string]func(config.Config) plug.Plug var ( plu...
package controllers import ( "golangapi/modules" "golangapi/models" "github.com/astaxie/beego" "encoding/json" "strconv" // "log" ) // Operations about object type UserController struct { beego.Controller } // @Title GetOneUserById // @Description find user by objectid // @Param objectId "the objectid you wan...
package day05 func demo() { /* 1.函数字面表示匿名函数 2.函数字面可赋值给变量或直接调用 3.函数字面是闭包 1.可访问外层函数中定义的变量, 这些变量被外层函数和函数字面共享 */ }
package conn import ( "bufio" "bytes" "encoding/binary" "fmt" "io" "log" "net" "reflect" "sync" "github.com/rbrick/mcserver/packet" ) type Connection struct { m *sync.Mutex conn net.Conn state packet.State } func NewConnection(c net.Conn) *Connection { return &Connection{&sync.Mutex{}, c, packet....
// Copyright (c) 2019 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package testing import ( "fmt" "path/filepath" "strings" "github.com/sirupsen/logrus" "github.com/vladimirvivien/gexe" ) type SSHServer struct { name string port string mountDir string username string e ...
package api import ( "fmt" "net/http" "os" "os/signal" "time" log "github.com/Sirupsen/logrus" "github.com/gorilla/handlers" "github.com/gorilla/mux" "github.com/hiteshjoshi/manners" "github.com/hiteshjoshi/negroni" "github.com/hiteshjoshi/pandat/clock" ) type Engine struct { Router *mux.Router Server ...
package models type UserCond struct { Username string MaxCalories int Diabetic bool Halal bool Vegan bool } /* func (userC *UserCond) Insert(w http.ResponseWriter, r *http.Request) { // Check valid key if !validKey(r) { w.WriteHeader(http.StatusUnauthorized) w.Write([]byte("401 - Invalid ...
package main type T struct{ x int } func (T) mT() {} type S struct { T } func (S) mS() {} type P *S type I interface { mT() } func main() { var s S s.T.mT() s.mT() // == s.T.mT() var i I _ = i i = s.T i = s var ps = &s ps.mS() ps.T.mT() ps.mT() // == ps.T.mT() i = ps.T i = ps var p P = ps (*...
package main import "fmt" const pi float64 = 3.146 var p = fmt.Println type geometry interface{ area() float64 perim() float64 } type rect struct { w,h int } type circle struct { r int } func (r rect) area() float64{ p("area of rectangle: width * height") return float64(r.w * r.h) } func (r rect) perim() f...
// 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 main import ( "errors" "github.com/bitly/go-simplejson" "github.com/spf13/afero" ) var ( // ErrMissingItem represents error about missing list item ErrMissingItem = errors.New("item not found") // ErrMissingList represents error about missing list ErrMissingList = errors.New("list not found") ) // J...
package server import ( "fmt" "net/http" ) type Server struct{ } func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { mux := http.NewServeMux() mux.HandleFunc("/get_movies", s.getMovies) mux.ServeHTTP(w, r) } func (s *Server) getMovies(w http.ResponseWriter, r *http.Request){ fmt.Fprintf...
package calculator // NumberCruncher runs calculations and verifications type NumberCruncher interface { Add(x, y float64) float64 Verify(got, want float64) bool } // Add sums two numbers func Add(x, y float64) float64 { return x + y } // Verify is an "example" of a wrapper for an html call. In this example, the ...
package pie_test import ( "github.com/elliotchance/pie/v2" "github.com/stretchr/testify/assert" "testing" ) func TestMode(t *testing.T) { cmp := func(a, b []float64) bool { m := make(map[float64]struct{}) for _, i := range a { m[i] = struct{}{} } for _, i := range b { if _, ok := m[i]; !ok { re...
package orm import ( "database/sql" "testing" ) func TestInsert(t *testing.T) { _, got, _, _ := Insert(nil, "", nil) want := "db can't be nil" if got != nil && got.Error() != want { t.Errorf("got %q; want %q", got, want) } db := &sql.DB{} _, got2, _, _ := Insert(db, "", nil) want2 := "table can't be empt...
package main import "fmt" func main() { fmt.Println(4*) a := factorial(4) fmt.Println(a) } func factorial(n int) int { return n * factorial(n-1) }
// time: O(n * 2^n), space: O(n * 2^n) func subsets(nums []int) [][]int { res := make([][]int, 0) res = append(res, []int{}) for _, n := range nums { for _, r := range res { v := make([]int, len(r), len(r) + 1) copy(v, r) v = append(v, n) res = append(...
package setting type version struct { Release string }
package fetcher import ( "net/http" "fmt" "golang.org/x/text/transform" "io/ioutil" "bufio" "golang.org/x/text/encoding" "golang.org/x/text/encoding/unicode" "golang.org/x/net/html/charset" "log" ) func Fetch(url string) ([]byte,error) { res, err := http.Get(url); if err != nil { return nil,err } defer...
package main import ( "fmt" "github.com/sunmi-OS/gocore/utils" ) func main() { var secret, params string secret = "123" params = "abdsjfhdshfksdhf" m, err := utils.GetParamMD5Sign(secret, params) if err != nil { fmt.Println("Error:", err) } fmt.Println("GetParamMD5Sign", m) var maintain string maintain...
package main import ( "github.com/faiface/pixel/pixelgl" "github.com/kiryalovik/gameoflife/cellular/life" "github.com/kiryalovik/gameoflife/cellular/repository" "github.com/kiryalovik/gameoflife/cellular/service" ) const ( stableStringRule1 = `{"born":[3],"survive":[2,3,7]}` lifeStringRule = `{"born":[3],"s...
// Copyright 2021 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 dynamo import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dynamodb" "testing" ) func TestQueryBuilder_Select(t *testing.T) { test := CreateNewQupDynamo(TestConnection{}) builder, err := test.Query("mockTable", ExampleRecord{}) if err != nil { t.Fail() } newBuilder :...
package isogen import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestToYaml(t *testing.T) { expectedBytes := []byte(`builder: {} container: containerRuntime: docker `) cnf := &Config{ Container: Container{ ContainerRuntime: "docker", }, } actualByte...
package search import ( "github.com/takatori/mini-search/index" "math" ) func cosineSim(v1, v2 []float64) float64 { var score float64 //v1 = normalize(v1) //v2 = normalize(v2) //fmt.Printf("v1:%v, v2:%v\n", v1, v2) for i, v1s := range v1 { score += v1s * v2[i] } return score } func docVector(idx *inde...
package task import ( "context" "github.com/dheerajgopi/todo-api/models" ) // Repository represents task's repository contract type Repository interface { GetAllByUserID(ctx context.Context, userID int64) ([]*models.Task, error) GetByID(ctx context.Context, id int64) (*models.Task, error) Create(ctx context.Con...
package main import ( "bufio" "fmt" "os" ) func main() { scanner := bufio.NewScanner(os.Stdin) scanner.Split(bufio.ScanLines) var a int64 scanner.Scan() fmt.Sscanf(scanner.Text(), "%d", &a) res := "Alice" if a%2 == 0 { res = "Bob" } fmt.Print(res) }
package printer import ( "encoding/json" "fmt" "io" "strings" "text/tabwriter" "time" "github.com/argoproj/pkg/humanize" "sigs.k8s.io/yaml" wfv1 "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1" "github.com/argoproj/argo/workflow/util" ) func PrintWorkflows(workflows wfv1.Workflows, out io.Writer, opt...
package resources import "github.com/kkurahar/go-gin-lightweight/models" type resourceTagInterface interface { GetAll() ([]*models.Tag, error) GetById(id int) (*models.Tag, error) } func NewResourceTag() resourceTagInterface { return &resourceTag{} } type resourceTag struct { } func (t *resourceTag) GetAll() ([...
package main import ( "net/http" "html/template" "io/ioutil" "fmt" "encoding/json" ) type Person struct{ Username string `json:username,omitempty` Password string `json:password,omitempty` EmpId string `json:empid,omitempty` Address string `json:address,omitempty` Position string `json:position,omi...
// okaq web server // equus dogu eiga // bitmap sampler // AQ <aq@okaq.com> // 2018-01-08 package main import ( "bufio" "fmt" "net/http" "os" "strconv" "strings" "time" ) var ( Images []string Index int ) const ( EIGA = "eiga.html" IMG = "../img" ) func EigaHandler(w http...
package users import ( "encoding/json" "net/http" "cinemo.com/shoping-cart/framework/web/httpresponse" "cinemo.com/shoping-cart/internal/errorcode" ) // SignUpHandler SignUpHandler func SignUpHandler(userService Service) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Reque...
package model import ( "database/sql" //"github.com/CourseComment/conf" _ "github.com/go-sql-driver/mysql" //"os" //"time" ) // var ( // db *sql.DB // ) // func init() { // db = conf.DB // } //time.Time need to be understand type User struct { Id idtype Account string Name string Password stri...
package tmc import ( "strconv" "github.com/baocaixiong/taobaosdk-go/agent" ) // 发布单条消息 func (t *Tmc) MessageProduce(topic string, content string) *agent.JsonResponse { params := map[string]string{ "topic": topic, "content": content, } return t.Request("taobao.tmc.message.produce", params) } // 确认消费消息的状态...
package asmcall import "unsafe" //go:noescape func Call(fn unsafe.Pointer, arg uintptr) int32