text
stringlengths
11
4.05M
package image import ( "io" "os" "time" "github.com/dnephin/dobi/tasks/context" docker "github.com/fsouza/go-dockerclient" ) // RunPull builds or pulls an image if it is out of date func RunPull(ctx *context.ExecuteContext, t *Task, _ bool) (bool, error) { record, err := getImageRecord(recordPath(ctx, t.config...
package main import ( "github.com/gorilla/websocket" "log" "time" ) const ( // Time allowed to write a message to the peer. writeWait = 10 * time.Second // Time allowed to read the next pong message from the peer. pongWait = 60 * time.Second // Send pings to peer with this period. Must be less than pongWait...
package trea import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00400102 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:trea.004.001.02 Document"` Message *CreateNonDeliverableForwardValuationV02 `xml:"CretNDFValtnV02"` }...
// Package codecs contains types that relate to brewnet codecs. They // can be used in a response structure to help the codec understand // what it should be building - for example, including a Link type in // the response will allow all brewnet codecs to format the link how // they need to to support their specific M...
//多个服务器和客户端。客户端向服务器发出不同的请求 //一个中心节点用于审批节点的加入离开和网络的维护 //根据报文头来分类处理不同的消息(handle),用json来序列化结构体 //0.简单字符串[default] //1.请求加入:id listenport————添加表单并转发(dial)&&把表单整体传递给新节点(datatrans)&&通知节点已加入网络[1] // 可能的错误:id重复,服务器不存在 //2.请求离开:id listenport————删除表单并转发[2] //3.来自转发的加入/离开请求:id listenport————仅添加/删除表单[3,4] //4.连通确认[5] //5...
package main import ( "errors" "fmt" ) // 定义一个类型 type operate func(int, int) int func oper(x, y int) int { return x + y } func calculate(x, y int, op operate) (int, error) { // 卫述语句检查参数 if op == nil { return 0, errors.New("op is nil") } return op(x, y), nil } func main() { r, _ := calculate(1, 2, oper) ...
package chunksmapper import ( "github.com/AppImageCrafters/libzsync-go/chunks" "github.com/stretchr/testify/assert" "testing" ) func TestFileChunksMapper_GetMissingChunks(t *testing.T) { mapper := ChunksMapper{ fileSize: 12, chunksMap: make(map[int64]chunks.ChunkInfo), } chunkList := []chunks.ChunkInfo{ ...
package parquet_test import ( "fmt" "io" "io/ioutil" "log" "os" "github.com/segmentio/parquet-go" ) func Example() { // parquet-go uses the same struct-tag definition style as JSON and XML type Contact struct { Name string `parquet:"name"` // "zstd" specifies the compression for this column PhoneNumber...
package example import ( "github.com/alehano/gobootstrap/sys/db/postgres" "github.com/alehano/gobootstrap/models" "github.com/jmoiron/sqlx" "errors" ) // Implementation of Storage interface func NewPostgresStorage() Storage { s := postgresStorage{ db: postgres.GetDB(), table: tableName, } return s } co...
package functions import ( "os" "github.com/mikerybka/github" ) func UpdateWebmachinedevFrontend() error { functions, err := AllFunctions() if err != nil { return err } var files map[string]string // TODO regenerate /go.mod and /go.sum for _, function := range functions { vercelfunctionsrc, err := Gen...
/* Copyright © 2022 NAME HERE <EMAIL ADDRESS> */ package cmd import ( "YNM3000/code/core" "YNM3000/code/logger" "YNM3000/code/utils" "os" "path" "github.com/spf13/cobra" ) // scanCmd represents the scan command var scanCmd = &cobra.Command{ Use: "scan", Short: "A brief description of your command", Long:...
package main import "fmt" func strStr(haystack string, needle string) int { findlen, inlen := len(needle), len(haystack) switch { case findlen == 0: return 0 case inlen > findlen: return -1 case findlen == inlen: if haystack == needle { return 0 } return -1 } if findlen == 0 { return 0 } if in...
package ffprobe import ( "errors" "log" "os" "reflect" "strings" "testing" ) func init() { devnull, e := os.Create(os.DevNull) if e != nil { panic(e) } logi = log.New(devnull, "", log.Lshortfile|log.Ltime) } func TestConfInputs(t *testing.T) { pc := NewProber() tests := []struct { plt, name string ...
package laws import ( "fmt" "os" "path/filepath" "regexp" ) // A Law describes the expected values of a file header in regular expressions. type Law struct { Expected regexp.Regexp } // RetrieveFrom extracts a Law from filepath. // If filepath is empty, it attempts to find a Law file at // the current working d...
package swarm_test import ( "context" "testing" ma "gx/ipfs/QmNTCey11oxhb1AxDnQBRHtdhap6Ctud872NjAYPYYXPuc/go-multiaddr" pstore "gx/ipfs/QmQFFp4ntkd4C14sP3FaH9WJyBuetuGUVo6dShNHvnoEvC/go-libp2p-peerstore" testutil "gx/ipfs/QmVnJMgafh5MBYiyqbvDtoCL8pcQvbEGD2k9o9GFpBWPzY/go-testutil" ) func TestDialBadAddrs(t *te...
package client import ( "encoding/json" "log" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/gorilla/websocket" "github.com/stretchr/testify/assert" "github.com/taglme/nfc-goclient/pkg/models" ) var upgrader = websocket.Upgrader{} func echo(w http.ResponseWriter, r *http.Request) { ...
package main import ( "bufio" "fmt" "os" "sort" "strings" ) type hightemp struct { pref string count int } func main() { file, _ := os.Open("./chap-02/hightemp.txt") defer file.Close() sc := bufio.NewScanner(file) ret := map[string]int{} var h []hightemp for sc.Scan() { s := strings.Split(sc.Text(...
package venom import ( "os" "strings" "github.com/fsamin/go-dump" ) var preserveCase string func init() { preserveCase = os.Getenv("VENOM_PRESERVE_CASE") if preserveCase == "" || preserveCase == "AUTO" { preserveCase = "ON" } } // Dump dumps v as a map[string]interface{}. func DumpWithPrefix(va interface{}...
package shakespeare import ( "context" "net/http" ) const baseURL = "https://api.funtranslations.com" type Service interface { ConvertText(ctx context.Context, text string) (string, error) } type service struct { client *http.Client } func New() Service { return &service{ client: http.DefaultClient, } }
package main import ( "context" "path/filepath" "strconv" "sync" "time" "github.com/pingcap/log" "github.com/pingcap/tidb/config" "github.com/pingcap/tidb/sessionctx/variable" "go.uber.org/zap" ) var logger *zap.Logger func initLog() (err error) { var filename = "tidb-audit.log" // TODO: Tweak log configu...
// This documentation describes example APIs found under https://github.com/ribice/golang-swaggerui-example // // Schemes: http // Version: 0.0.1 // Contact: Andriy Tymkiv <a.tymkiv99@gmail.com> // Host: localhost/goswagg // // Consumes: // - application/json // // Produces: // - applica...
package entity import ( "github.com/jinzhu/gorm" //"time" ) // UserAccount 用户账户信息结构体 type UserAccount struct { gorm.Model Account string Password string PermanentID string //用户所有操作使用此ID Name string BankCard string WeChat string Alipay string Telephone string Email string }
package steps import ( "context" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/network" "github.com/chromedp/chromedp" "github.com/pkg/errors" "net/http" "time" ) type User interface { signIn(username string) error isSignedIn() bool signOut() error resetUser(fakeApi *FakeApi, ctx context.C...
package main import // This is the graphics library we are going to use. It is called the // Simple Direct Media Library. SDL for short. We need this to create the // window and to provide the drawing functions we need. "github.com/gophercoders/toolbox" // These are the variables for the graphics library // They hav...
// Copyright 2020 The Reed Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. package types type RecvBlockType int const ( RecvBlockTypeMined = iota RecvBlockTypeRemote RecvBlockTypeReorganize ) type RecvWrap struc...
package main //import "fmt" // //func main() { // // var x string =nil //Cannot use 'nil' as type string // if x==nil { //Cannot convert 'nil' to type 'string' // x="default" // } // fmt.Println(x) //}
package main var router = createMux()
package main import "fmt" func main() { fmt.Println(findKthLargest([]int{ 3, 2, 1, 5, 6, 4, }, 2)) fmt.Println(findKthLargest([]int{ 3, 2, 3, 1, 2, 4, 5, 5, 6, }, 4)) } func findKthLargest(nums []int, k int) int { var quick func(low, right int) quick = func(low, height int) { if low >= height { retu...
package lib import ( "io" "time" "github.com/Cloud-Foundations/Dominator/lib/errors" "github.com/Cloud-Foundations/Dominator/lib/format" "github.com/Cloud-Foundations/Dominator/lib/log" "github.com/Cloud-Foundations/Dominator/lib/srpc" "github.com/Cloud-Foundations/Dominator/proto/objectserver" ) func addObje...
package v1 import ( "context" "github.com/gin-gonic/gin" "github.com/jmoiron/sqlx" "github.com/moyrne/tebot/internal/analyze" "github.com/moyrne/tebot/internal/database" "github.com/moyrne/tebot/internal/logs" "github.com/moyrne/tebot/internal/models" "github.com/moyrne/tebot/internal/service/commands" "githu...
package leetcode import "fmt" func main(){ fmt.Printf("%v", countSmaller([]int{5,2,6,1})) } func countSmaller(nums []int) []int { counts := make([]int, len(nums)) sorts := make([]int, len(nums)) for i := len(nums)-1; i >= 0; i--{ counts[i] = find(sorts, nums[i], len(nums)-i-1) } return counts } func find(so...
package nats import ( "context" "errors" "sync" pubsub "github.com/zhangce1999/pubsub/interface" ) var ( errInvalidTopic = errors.New("[error]: invalid topic") errInvalidChannel = errors.New("[error]: invalid channel") errInvalidConnection = errors.New("[error]: invalid connection") errInvalidB...
package main import ( "fmt" "github.com/jackytck/projecteuler/tools" ) func solve() int { side := 3 prime := 3 corner := 9 for 10*prime > 2*side-1 { side += 2 step := side - 1 for i := 0; i < 3; i++ { corner += step if tools.IsPrime(corner) { prime++ } } corner += step } return side } ...
package data_structures import "fmt" type BinarySearchTree struct { Root *BstNode } type BstNode struct { Value int LeftNode *BstNode RightNode *BstNode } func GetBst() *BinarySearchTree{ return &BinarySearchTree{} } func (bst *BinarySearchTree) Print(value int){ fmt.Println(value) } func (bst *BinarySearchT...
package gotest import "testing" func TestBasic(test *testing.T) { grade := "D" if grade != "D" { test.Error("Test Case failed.") } }
package config import ( "testing" ) func Test_NewSpeConfig(t *testing.T) { t.Log("Start to init…") speConfig, err := NewSpeConfig("../static/cuttle.yaml") if err != nil { t.Errorf("Failed to init,err=%s", err) } t.Logf("%+v", speConfig) t.Log("End Init!!!") err = speConfig.Marshal("../static/cuttle1.yaml...
package logger import ( "errors" "os" "path" "path/filepath" "syscall" "github.com/sirupsen/logrus" ) // Log log var Log = logrus.New() // LogError log error var LogError = logrus.New() // Debug debug logger var Debug = Log.Debug // Debugf debug formatting logger var Debugf = Log.Debugf // Info info logger...
//+build test // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package daemonset import ( "context" "encoding/json" "log" "os/exec" "time" "github.com/Azure/aks-engine/test/e2e/kubernetes/pod" "github.com/Azure/aks-engine/test/e2e/kubernetes/util" "github.com/pk...
package main import ( "bytes" "encoding/json" "errors" "flag" "fmt" "io/ioutil" "log" "net/http" "path" "sort" "strconv" "strings" "time" yaml "gopkg.in/yaml.v2" ) const ( OK = "200 OK" HTTP = "http://" HTTPS = "https://" ) type ElasticSearch struct { nodes []Node indices []Index url s...
package v2 //nsq 生产者,消费者 自行处理生产,消费内容 import ( "github.com/nsqio/go-nsq" "smallgamepk.qcwanwan.com/utils" ) type Nsqer interface { Producer(addr string)(*nsq.Producer,error) Customer(addr,topic,channel string,dat chan interface{})(error) } type Nsq struct {} func NewNsq() Nsqer{ return &Nsq{} } /* if err := p...
package Solution type TreeNode struct { Val int Left *TreeNode Right *TreeNode }
package chain import "testing" func TestHandlerChain_Handle(t *testing.T) { type fields struct { Handler Handler successor *HandlerChain } chain := NewHandlerA() handlerA := NewHandlerA() handlerB := NewHandlerB() chain.SetSuccessor(handlerA) handlerA.SetSuccessor(handlerB) tests := []struct { name ...
package main // The packer takes all known game records and condenses them into a PackedChampionGameList. // It outputs the PCGL, which is then used for searching in online queries. All of the // game fields of the PCGL are in sorted order. import ( gproto "code.google.com/p/goprotobuf/proto" "encoding/json" "flag...
// Copyright 2020 The Amadeus 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 agre...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/12/12 10:15 上午 # @File : lt_16_最接近的三数之和_test.go.go # @Description : # @Attention : */ package hot100 import ( "fmt" "testing" ) func Test_threeSumClosest(t *testing.T) { ints := make([]int, 0) ints = append(ints, 0, 2, 1, -3) fmt.Println(threeSumClosest...
package proxy import ( "context" "net/http" "github.com/pomerium/csrf" "github.com/pomerium/datasource/pkg/directory" "github.com/pomerium/pomerium/internal/encoding/jws" "github.com/pomerium/pomerium/internal/handlers" "github.com/pomerium/pomerium/internal/handlers/webauthn" "github.com/pomerium/pomerium/in...
package utils import ( "BcRPCCode/entity" "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "time" ) /** 准备json——rpc通信的数据格式 */ func RpcRequest(method string, params ...interface{}) []byte { rpcRequest := entity.RPCRequest{ Id: time.Now().Unix(), Method: method, Jsonrpc: "2.0", } if params !=...
package entity type SignTransactionEntity struct { RefBlockNum string `json:"ref_block_num"` RefBlockPrefix string `json:"ref_block_prefix"` Expiration string `json:"expiration"` Scope [2]string `json:"scope"` ReadScope []interface{} `json:"read_scope"` Messages...
package service import ( "bytes" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" "time" "towelong/mogu/model" "towelong/mogu/utils" ) const ( url = "https://api.moguding.net:9000" ) // MoGuService generate a serious of function's interfaces. type MoGuService interface { MoGuLogin(account, passwor...
package slacktest import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/slack-go/slack" ) func TestRTMInfo(t *testing.T) { maxWait := 10 * time.Millisecond s := NewTestServer() go s.Start() api := slack.New("ABCDEFG", slack.OptionAPIURL(s.GetAPIURL())) rtm := api.NewRTM() go rtm.Mana...
package user import ( "ego/src/commons" "fmt" ) //根据用户名和密码查询 func SelByUnPwdDao(un,pwd string) *TbUser { sql :="select * from tb_user where username =? and password=? or email =? and password=?" rows,err:=commons.Dql(sql,un,pwd,un,pwd) //fmt.Println(rows) if err !=nil{ fmt.Println(err) return nil } if r...
/* Design a random number generator where the i th number has i% chance of occurring for all 0 < i < 14. 0 should have exactly 9% chance of occurring. The seed for the generator should be the system time. You cannot use a pre-defined function for random number generation. Basically 1 has 1% chance of occurring, 2 has...
package powervs // Platform stores all the global configuration that all machinesets // use. type Platform struct { // ServiceInstanceID is the ID of the Power IAAS instance created from the IBM Cloud Catalog ServiceInstanceID string `json:"serviceInstanceID"` // PowerVSResourceGroup is the resource group in whic...
package wsStorage import "errors" var ( ErrIsExisted = errors.New("ws connection is existed") ErrConnectionNotFound = errors.New("ws connection is not found") ErrInvalidDuration = errors.New("invalid duration value") )
package ircserver import ( "testing" "time" "github.com/robustirc/robustirc/internal/config" "github.com/robustirc/robustirc/internal/robust" "gopkg.in/sorcix/irc.v2" ) func stdIRCServerWithServices() (*IRCServer, map[string]robust.Id) { i, ids := stdIRCServer() i.Config.IRC.Services = append(i.Config.IRC.Ser...
package socks type Channel struct { Session }
package main import ( "encoding/csv" "fmt" "golang.org/x/exp/rand" "gonum.org/v1/gonum/mat" "gonum.org/v1/gonum/stat/distmv" "gonum.org/v1/plot" "gonum.org/v1/plot/plotter" "gonum.org/v1/plot/plotutil" "gonum.org/v1/plot/vg" "log" "math" "os" "strconv" "time" ) var randSource = rand.NewSource(uint64(tim...
/* Package rivescript implements the RiveScript chatbot scripting language. About RiveScript RiveScript is a scripting language for authoring chatbots. It has a very simple syntax and is designed to be easy to read and fast to write. A simple example of what RiveScript looks like: + hello bot - Hello human. This...
package slices import ( "testing" ) func TestOccurences(t *testing.T) { a := []int{0, 1, 2, 3, 4} b := []int{0, 0, 0, 1} var actual int actual = Occurences(a, 0) if actual != 1 { t.Errorf("Error: expected [ %d ] got [ %d ]", 1, actual) } actual = Occurences(b, 0) if actual != 3 { t.Errorf("Error: expec...
package main import ( "flag" "fmt" "github.com/tengla/fibro/block" ) var difficulty = flag.Int("difficulty", 2, "The mining difficulty") func main() { flag.Parse() chain := block.CreateChain(*difficulty) chain.AddBlock(block.NewBlock(map[string]string{ "Name": "I am the first", })) chain.AddBlock(bloc...
package _297_Serialize_and_Deserialize_Binary_Tree import ( "fmt" "strconv" "strings" ) type TreeNode struct { Val int Left *TreeNode Right *TreeNode } type Codec struct { } func Constructor() Codec { return Codec{} } // Serializes a tree to a single string. func (this *Codec) serialize(root *TreeNode) s...
// address bus implementation with multiple components (RAM,ROM,PIA) attached package addressbus type MultiBus struct { addressMap map[uint16]BusAddressingInternal blockSize int components []BusAddressingInternal } func (b *MultiBus) InitBus(addressMapBlockSize int) { b.components = make([]BusAddressingInterna...
package transform import ( "github.com/jwowillo/viztransform/geometry" ) // Apply the Transformation to the geometry.Point by applying each // line-reflection making up the Transformation in order. func Apply(t Transformation, p geometry.Point) geometry.Point { for _, l := range t { p = apply(l, p) } return p }...
package cmdutils import ( "github.com/evleria/quiz-cli/pkg/config" "github.com/evleria/quiz-cli/pkg/iostreams" ) type Factory struct { IOStreams iostreams.IOStreams ConfigFunc func() config.Config }
package typepublickey import ( vocab "github.com/go-fed/activity/streams/vocab" ) // A public key represents a public cryptographical key for a user type ActivityStreamsPublicKey struct { ActivityStreamsId vocab.ActivityStreamsIdProperty ActivityStreamsOwner vocab.ActivityStreamsOwnerProperty Act...
package history import ( "database/sql" "fmt" _ "github.com/mattn/go-sqlite3" ) const torrents_table = "Torrents" const torrent_buffer = 15 type History struct { db *sql.DB q chan string ch chan<- string } func New(n string, ch chan<- string) (*History, error) { db, err := sql.Open("sqlite3", n) if err != ...
/* Copyright paskal.maksim@gmail.com Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dist...
package user import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "time" "google.golang.org/grpc/codes" jwt "github.com/dgrijalva/jwt-go" "github.com/go-chi/chi" "github.com/go-chi/jwtauth" "github.com/go-chi/render" "github.com/ubclaunchpad/pinpoint/gateway/api/ctxutil" "github.com/ubclaunchpad/...
package main import ( "fmt" "time" ) func elapsed(what string) func() { start := time.Now() return func() { fmt.Printf("%s took %v\n", what, time.Since(start)) } } func main() { messages := make(chan string) go func() { defer elapsed("send")() fmt.Println("thread: about to ping") mess...
// // Copyright (c) 2016-2022 Snowplow Analytics Ltd. All rights reserved. // // This program is licensed to you under the Apache License Version 2.0, // and you may not use this file except in compliance with the Apache License Version 2.0. // You may obtain a copy of the Apache License Version 2.0 at http://www.apach...
package format import ( "github.com/plandem/xlsx/internal/ml" "github.com/plandem/xlsx/internal/ml/primitives" "github.com/stretchr/testify/require" "testing" ) func TestConditionalFormat_Set(t *testing.T) { conditions := NewConditions( Conditions.Pivot, Conditions.Refs("A10:B20"), Conditions.Rule( Cond...
package module import ( "buddin.us/eolian/dsp" ) func init() { Register("Dynamics", func(Config) (Patcher, error) { return newDynamics() }) } var ( slopeFactor = 1 / dsp.Float64(dsp.FrameSize) log1 = dsp.Log(0.1) ) type dynamics struct { IO in, control, threshold, clamp, relax, above, below *In clamp...
// Copyright 2013 Webconnex, 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 ...
package jarviscore import ( "context" "time" ) // FuncOnTimer - on timer // - If it returns false, the timer will end type FuncOnTimer func(ctx context.Context, timer *Timer) bool // Timer - timer type Timer struct { timer int ontimer FuncOnTimer } // NewTimer - new timer func NewTimer(timer int, ontimer F...
// // Copyright 2020 The AVFS 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 utils const ( StatusActive = "active" StatusSuspended = "suspended" StatusEmailNotConfirmed = "pending" ) func IsNotValidStatus(status string) bool { return status != StatusActive && status != StatusSuspended && status != StatusEmailNotConfirmed }
/** Exercise 2 :: 1. Use var to DECLARE three variables. The variables should have package level scope. Do not assign VALUES to the variables. Use the following IDENTIFIERS for the variables and make sure the variables are of the following TYPE(meaning they can store VALUES of that TYPE) a. identifier "x" type in...
// 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...
// Copyright 2018 Authors of Cilium // // 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©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-08-03 17:02 * Description: *****************************************************************/ package netstream import ( "github.com/go-xe2/x/core/lo...
package platform import ( "crypto/tls" "crypto/x509" "fmt" "github.com/go-pg/pg" "io/ioutil" "time" _ "github.com/lib/pq" ) // DBConfig is the required properties to use the database. type DBConfig struct { Host string ServerName string User string Password string DisableTLS bool ServerCA ...
package log import ( "fmt" ) var _ CloseHandler = (*multiHandler)(nil) type multiHandler []Handler // MultiHandler return a multi handler. func MultiHandler(handlers ...Handler) CloseHandler { h := multiHandler(handlers) h.expand() return &h } func (h *multiHandler) expand() { expanded := multiHandler{} for ...
package mocking import ( "errors" "testing" ) func TestThrowError(t *testing.T) { tests := []struct { name string wantErr bool }{ {"base-case", true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if err := ThrowError(); (err != nil) != tt.wantErr { t.Errorf("DoSomeStuff() e...
package auth type Credentials struct { User *string `json:"user"` Password *string `json:"password"` Token *string `json:"token"` } func (c *Credentials) Valid() bool { return (c.User != nil && c.Password != nil) || c.Token != nil }
package main import ( "encoding/json" "github.com/fasthttp/router" "github.com/valyala/fasthttp" "net/http" ) func apiNotFound(ctx *fasthttp.RequestCtx) { b, err := json.Marshal(map[string]interface{}{ "error": http.StatusText(fasthttp.StatusNotFound), }) if err != nil { panic(err) } ctx.SetStatusCode(...
package graphics // Texture declares all methods required to draw a texture. type Texture interface { Close() error Draw(x, y int32, scaleX, scaleY float32, rotation float64) error W() int32 H() int32 } // TextureAtlas declares all methods required to draw a texture atlas. type TextureAtlas interface { Close() e...
package adutils import ( "io/ioutil" "log" "os/exec" ) func SendMail(to, content string) { // log.Println("mail :", to, "file: ", content) // args := content + " | sendmail" + to cmd := exec.Command("./sm.sh", content, to) _, err := cmd.Output() if err != nil { log.Println(err.Error()) } ...
package main import ( "fmt" ) const ( colorReset = "\033[0m" colorRed = "\033[31m" colorGreen = "\033[32m" colorYellow = "\033[33m" colorBlue = "\033[36m" ) func printMenue() { fmt.Println(string(colorBlue), ` ************************************************** ******* Willkommen bei WER WIRD MILLIONÄR?...
package main import ( "io/ioutil" "os" "testing" ) func TestSTR(t *testing.T) { pongoSetup() tests := []struct { in interface{} out string }{ {"", ""}, {1, ""}, {"Dude", "Dude"}, } for _, test := range tests { actual := str(test.in) if actual != test.out { t.Errorf("expected %v actual %v", ...
/* # 按行访问 ## 思路 按照与逐行读取 Z 字形图案相同的顺序访问字符串。 ## 算法 首先访问 行 0 中的所有字符,接着访问 行 1,然后 行 2,依此类推... 对于所有整数k, - 行0中的字符位于索引k(k=2⋅numRows−2) 处; - 行numRows−1中的字符位于索引k(2⋅numRows−2)+numRows−1 处; - 内部的行 i 中的字符位于索引k(2⋅numRows−2)+i 以及(k+1)(2⋅numRows−2)−i 处; ## 复杂度分析 时间复杂度:O(n)O(n),其中 n == \text{len}(s)n==len(s)。每个索引被访问一次。 空间复杂度:...
package public import ( "context" "fmt" "mime/multipart" "path" "time" "tpay_backend/merchantapi/internal/common" "tpay_backend/model" "tpay_backend/pkg/cloudstorage" "tpay_backend/merchantapi/internal/svc" "tpay_backend/merchantapi/internal/types" "github.com/tal-tech/go-zero/core/logx" ) type UploadFil...
package mysql import _ "github.com/go-sql-driver/mysql" // Import the mysql driver.
package main import ( "fmt" "runtime" "github.com/Dliv3/Venom/admin/cli" "github.com/Dliv3/Venom/admin/dispather" "github.com/Dliv3/Venom/netio" "github.com/Dliv3/Venom/node" ) func main() { runtime.GOMAXPROCS(runtime.NumCPU()) cli.ParseArgs() fmt.Println("Venom Admin Node Start...") cli.ShowBanner() /...
package main import ( "fmt" "strings" ) func main() { var input string // Scanf scans text read from standard input // 格納すべきアドレスの場所を伝えるためにアドレス演算子が必要 fmt.Scanf("%s\n", &input) answer := 0 // Go言語では、文字列は実質的に読み取り専用のバイトのスライス // b := []byte(input) // fmt.Println(b) // nihongo := "日本語" // for index, runeValue...
// Demo of sorting on a slice package main import ( "fmt" "sort" ) // dump slice length, capacity, and contents func dump(label string, slice []string) { fmt.Printf("%v: length %v, capacity %v %v\n", label, len(slice),cap(slice), slice) } func main() { // Declare a slice planets := []string{ "Mercury",...
package omokServer import ( "fmt" "omokServer/protocol" "scommon" ) func (svr *Server) packetProcess(sessionIndex int, packetData []byte) { packetID := protocol.PeekPacketID(packetData) _, bodyData := protocol.PeekPacketBody(packetData) if pfunc := svr.getPacketFunc(packetID); pfunc != nil { if user, ok := ...
package downloader import ( "sync" "github.com/lf-edge/eve/pkg/pillar/pubsub" "github.com/lf-edge/eve/pkg/pillar/types" "github.com/lf-edge/eve/pkg/pillar/zedUpload" log "github.com/sirupsen/logrus" ) type downloaderContext struct { dCtx *zedUpload.DronaCtx subDeviceNetworkStatus pubsub.Su...
package websocket import ( "github.com/gorilla/websocket" ) type IWebSocketService interface { InitConnection(*websocket.Conn, interface {}) Broadcast(*BroadcastInfo) }
// Copyright 2011 Google Inc. All Rights Reserved. // This file is available under the Apache license. package main import ( "flag" "log" "strings" "github.com/golang/glog" "github.com/google/mtail/mtail" "github.com/prometheus/client_golang/prometheus" "net/http" _ "net/http/pprof" ) var ( port = flag.S...
package main import ( "fmt" "net/url" ) func main() { // url encode v := url.Values{} v.Add("msg", "此订单不存在或已经提交") body := v.Encode() fmt.Println(v) fmt.Println(body) // url decode m, _ := url.ParseQuery(body) fmt.Println(m) }