text
stringlengths
11
4.05M
package webknest import ( "time" ) // User contains login credentials and details about their profile including // subscription type, which will dictate certain capabilities type User struct { ID int `json:"id"` Username string `json:"username"` Password string `json:"-"` FirstNa...
package main import ( "fmt" "strings" ) /* There are N dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent do...
package dbServer import ( "testing" ) func TestMysqlApi_GetWxApp(t *testing.T) { tests := []struct{ appId, appSec string }{ {"wx3be7b35d2d7a8256", "2"}, {"wx293dbb0f011bcac3", "3"}, } mysqlApi := CreateMysqlApi() for _, tt := range tests { if appSec, _ := mysqlApi.GetWxApp(tt.appId); appSec != tt.appSec { ...
package packet type Metadata struct { Packet []byte } func (m *Metadata) Reset() { m.Packet = nil }
package jsonutils import ( "encoding/json" "github.com/joshprzybyszewski/cribbage/model" ) // UnmarshalGame takes in json marshaled bytes of a model.Game // The main advantage is that the list of actions can be deserialized // into the interface{} type. func UnmarshalGame(b []byte) (model.Game, error) { game := m...
// Copyright 2014 Dirk Jablonowski. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bricker import ( "github.com/dirkjabl/bricker/connector" ) // AttachConnector adds a named connector to the bricker. // The name must be unique and...
// Copyright 2018 SumUp Ltd. // // 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 cmd import ( "fmt" "log" "github.com/spf13/cobra" ) // drivercountCmd represents the drivercount command var drivercountCmd = &cobra.Command{ Use: "drivercount", Short: "A brief description of your command", Run: func(cmd *cobra.Command, args []string) { c, err := getClient() if err != nil { l...
package main func main() { //变量的声明 //var a int 声明变量值为0 //var b =10 声明并初始化,自动推导出数据类型 // c:=20 初始化并且自动推导 //多变量的声明 /**var a,b string var a1,b1 string ="HENG","HA" var a2,b2=1,2 c,d:=2,3 var { e int f bool }**/ //注意go语言变量初始化回自带默认值 /** int 0 int8 0 int32 0 int64 0 uint 0x0 rune 0...
package main import ( "runtime" "sync" "testing" "time" ) func TestSyncInit(t *testing.T) { s := newSema(4) if s.count() != 0 { t.Fatal("sema count should be 0") } } func TestSyncAcquireSimpleValid(t *testing.T) { s := newSema(2) var wg sync.WaitGroup wg.Add(2) for i := 0; i < 2; i++ { go func() { ...
package main import "fmt" //Bill Kennedy teaches online intermediate classes of golang //We create VALUES of a certain type that are stored in VARIABLES //and those VARIABLES have identifiers var x int //static type int, var x is of type int, x is identifier type person struct{ //var type are keywords plus identifie...
package main import ( "bufio" "bytes" "flag" "fmt" "github.com/nlopes/slack" "io" "log" "os" "os/exec" "strconv" "strings" "sync/atomic" "syscall" "time" "unicode" ) type Process struct { *os.Process Tty string Cwd string } type SlackMessage struct { user string token string } var ErrInvalidNumb...
package main import "github.com/sadasant/scripts/go/euler/euler" var months_limit = []int { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, } func solution(min_year, max_year int) int { var week_day = 2; var month_day = 1; var month = 0; var year = 1900; var saturday_firsts = 0; for year <= max_year{ if y...
package leetcode_1486_数组异或操作 /* 给你两个整数,n 和 start 。 数组 nums 定义为:nums[i] = start + 2*i(下标从 0 开始)且 n == nums.length 。 请返回 nums 中所有元素按位异或(XOR)后得到的结果。 示例 1: 输入:n = 5, start = 0 输出:8 解释:数组 nums 为 [0, 2, 4, 6, 8],其中 (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8 。 "^" 为按位异或 XOR 运算符。 示例 2: 输入:n = 4, start = 3 输出:8 解释:数组 nums 为 [3, 5, 7, 9],其...
package cards const ( CARD_A_HEART byte = iota CARD_A_DIAMOND CARD_A_CLUB CARD_A_SPADE CARD_K_HEART CARD_K_DIAMOND CARD_K_CLUB CARD_K_SPADE CARD_Q_HEART CARD_Q_DIAMOND CARD_Q_CLUB CARD_Q_SPADE CARD_J_HEART CARD_J_DIAMOND CARD_J_CLUB CARD_J_SPADE CARD_10_HEART CARD_10_DIAMOND CARD_...
package main import ( "container/list" "fmt" ) func main() { link := list.New() for i := 0; i <= 10; i++ { link.PushBack(i) } for p := link.Front(); p != link.Back(); p = p.Next() { fmt.Println("Number", p.Value) } }
package repository import ( "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" ) type DingdingRobot struct { ID primitive.ObjectID `bson:"_id,omitempty" json:"id"` Name string `bson:"name" json:"name"` Description string `bson:"description" json:"description"` Toke...
package main import ( "bufio" "fmt" "io" "os" "strconv" ) func main() { solve(os.Stdin, os.Stdout) } func solve(stdin io.Reader, stdout io.Writer) { sc := bufio.NewScanner(stdin) sc.Scan() n, _ := strconv.Atoi(sc.Text()) sc.Scan() k, _ := strconv.Atoi(sc.Text()) a := []int{} for i := 0; i < n; i++ { s...
package main import "fmt" function main(){ names := []string{"stanely", "david", "oscar"} vals := make([]interface{}, len(names)) for i,v := range names{ vals[i] = v } PrintAll(vals) } func PrintAll(vals []interface{}){ for _, val := range vals{ fmt.Println(val) } }
/* Package handlers : handle MQTT message and deploy object to kubernetes. license: Apache license 2.0 copyright: Nobuyuki Matsui <nobuyuki.matsui@gmail.com> */ package handlers import ( "k8s.io/apimachinery/pkg/runtime" ) /* HandlerInf : a interface to specify the method signatures that an object handler should b...
package access import ( "fmt" "github.com/dgrijalva/jwt-go" "time" ) var ( // tokenExpiredDate app token过期日期 30天 tokenExpiredDate = 3600 * 24 * 7 * time.Second // tokenIDKeyPrefix tokenID 前缀 tokenIDKeyPrefix = "token:auth:id:" tokenExpiredTopic = "com.qianxunke.shop.topic.auth.tokenExpired" ) //token 持有者 ty...
package main import ( "strconv" "testing" "time" ) func TestGenOverdueDays(t *testing.T) { data := [][]time.Time{[]time.Time{time.Date(2009, time.Month(5), 3, 0, 0, 0, 0, time.UTC), time.Date(2009, time.Month(5), 3, 24, 0, 0, 0, time.UTC)}, []time.Time{time.Date(2009, time.Month(5), 3, 0, 0, 0, 0, time.UTC), ti...
/* * @lc app=leetcode.cn id=1 lang=golang * * [1] 两数之和 * * https://leetcode-cn.com/problems/two-sum/description/ * * algorithms * Easy (46.84%) * Likes: 6596 * Dislikes: 0 * Total Accepted: 621.9K * Total Submissions: 1.3M * Testcase Example: '[2,7,11,15]\n9' * * 给定一个整数数组 nums 和一个目标值 target,请你在该数...
package utils import ( "os" ) func GetPodName() (name string) { return os.Getenv("POD_NAME") }
package metrics_test func (s *metrics) TestHost() { result, streamURL, err := s.metrics.Host(nil) if !s.NoError(err) { return } s.Nil(streamURL) if !s.NotNil(result) { return } }
package main import ( "fmt" "os" "sort" "strings" ) type PathQuery struct { QueryPath string DirectoryPath string Filename string } func NewPathQuery(q string) (isPath bool, pq *PathQuery) { pq = &PathQuery{} isPath, pq.QueryPath = ExpandPathString(q) if !isPath { return } pq.DirectoryPath =...
/* * traPCollection API * * traPCollectionのAPI * * API version: 1.0.0 * Generated by: OpenAPI Generator (https://openapi-generator.tech) */ package openapi // ProductKeyGen - プロダクトキー生成のリクエスト type ProductKeyGen struct { Num int32 `json:"num"` // バージョンID Version string `json:"version"` }
package azure import ( "context" "fmt" "reflect" "sort" "strings" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-11-01/network" "github.com/protofire/polkadot-failover-mechanism/pkg/helpers" ) type securityRuleItem struct { sourcePortRanges []string sourceAddressesPrefixes []...
package main import "fmt" func a() { for i := 0; i < 50; i++ { fmt.Print("a") } } func b() { for i := 0; i < 50; i++ { fmt.Print("b") } } func slow() { a() b() fmt.Println("\nend slow()") } func fast() { go a() go b() fmt.Println("\nend fast()") } func main() { slow() fast() fmt.Println("\nend ma...
package repository import ( "errors" "gid/entity" "gid/library/log" "gid/library/tool" "go.uber.org/zap" ) func (r *Repository) SegmentsCreate(s *entity.Segments) (err error) { var has bool if has, err = r.db.Where("biz_tag = ?", s.BizTag).Exist(&entity.Segments{}); err != nil { log.GetLogger().Error("[Segme...
package detect import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) var expected = []struct { ua string platform string }{ // iPhone {"Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A102 Safari/419", "iOS"}, {"Mozilla/5.0 (iPhone; CPU...
package db import ( "context" log "github.com/sirupsen/logrus" ethcommon "github.com/ethereum/go-ethereum/common" "github.com/Magicking/faktur-daemon/common" "github.com/Magicking/faktur-daemon/merkle" "github.com/jinzhu/gorm" ) type DbReceipt struct { gorm.Model Targethash string Proofs string ...
package utils import ( "fmt" "net" "os" "os/signal" "regexp" "syscall" "github.com/miekg/dns" "github.com/ray-g/dnsproxy/logger" ) const ( NotIPQuery = 0 IPv4Query = 4 IPv6Query = 6 ) func IsIPQuery(q dns.Question) int { if q.Qclass != dns.ClassINET { return NotIPQuery } switch q.Qtype { case dn...
// Copyright (C) 2019-2020 Zilliz. 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 l...
package functions import ( "strings" ) // GenPath returns a slice of strings created by splitting domain into its // domain components and reversing the result. func GenPath(domain string) []string { dcs := strings.Split(domain, ".") for i := len(dcs)/2 - 1; i >= 0; i-- { opp := len(dcs) - 1 - i dcs[i], dcs[o...
package main import ( "fmt" "html/template" "io" "log" "net/http" "os" ) type BasePath struct { basePath string baseTmpPath string } func (bp BasePath) Path(filename string) string { return bp.basePath + filename } func (bp BasePath) TmpPath(filename string) string { return bp.baseTmpPath + filename } ...
package gostat import ( "fmt" "math" "sort" "strings" ) type Stat struct { bkts buckets // bucket currently filled, always ORDERED. Buckets are never empty. Their limit must NEVER touch and they should never overlap. nbkt int // expected number of buckets } // NewStat with specified number of internal buck...
package core /* file: doop.go Only this file contains APIs that are exported to doop-core user. */ import ( "bufio" "errors" "fmt" "io/ioutil" "os" "os/user" "strings" "github.com/amsa/doop/adapter" . "github.com/amsa/doop/common" //_ "github.com/mattn/go-sqlite3" ) const ( DOOP_DIRNAME = ".doo...
//Color is a simple package for printing in color to a windows or ansi console. //Internally the package github.com/daviddengcn/go-colortext is used. package color import ( "fmt" ct "github.com/daviddengcn/go-colortext" ) //Println prints text to terminal with colors. //At the end of the line the color will be rese...
package main import "fmt" type S struct { opt1 string opt2 int } func (s *S) String() string { return fmt.Sprintf("S{opt1: %q, opt2: %d}", s.opt1, s.opt2) } type Option func(*S) error // HL func Opt1(v string) Option { return func(s *S) error { s.opt1 = v return nil } } func Opt2(v int) Option { return ...
package main import ( "flag" "log" "net/http" "os" "os/exec" "strings" "github.com/datacratic/goship/ship" ) func main() { address := flag.String("address", ":8080", "address of the web server") directory := flag.String("directory", "", "directory location") hostname := flag.String("hostname", "", "URL use...
package ravendb import ( "net/http" ) var ( _ RavenCommand = &ExplainQueryCommand{} ) type ExplainQueryResult struct { Index string `json:"Index"` Reason string `json:"Reason"` } type ExplainQueryCommand struct { RavenCommandBase _conventions *DocumentConventions _indexQuery *IndexQuery Result []*Explai...
package middleware import ( "errors" "fmt" "github.com/danilopolani/gocialite/structs" "github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" "github.com/leachim2k/go-shorten/pkg/cli/shorten/options" "golang.org/x/oauth2" "net/http" "os" "strings" "time" ) type AuthCustomClaims struct { Name string ...
package account import "sync" // Account structure type Account struct { balance int64 closed bool mux sync.Mutex } // Open opens a new account. func Open(initialDeposit int64) *Account { if initialDeposit >= 0 { return &Account{initialDeposit, false, sync.Mutex{}} } return nil } // Close closes the cu...
package wait import ( "github.com/thingsplex/tpflow/node/base" "time" ) import ( "github.com/futurehomeno/fimpgo" "github.com/thingsplex/tpflow/model" ) type WaitNode struct { base.BaseNode delay int ctx *model.Context transport *fimpgo.MqttTransport } func NewWaitNode(flowOpCtx *model.FlowOperatio...
package godis import ( "log" "os" "sync" "github.com/callduckk/YSGo/godis/cron" ) type ServerType int const ( WithBackup ServerType = iota + 1 WithoutBackup ) func buildGodisServer(serverType ServerType, loadBackup bool) *GodisServer { server := &GodisServer{} server.dictionary = &sync.Map{} if serverTy...
package task import ( "fmt" "strings" "sync" ) var controllerInstance *controller var controllerOnce sync.Once //controller 任务控制器 type controller struct { taskFactoryMap map[int]Factory taskMap map[string]Task taskMapRWLock sync.RWMutex } func InitTaskController(factoryMap map[int]Factory) { controll...
package iterators // SingleValue creates an iterator that can return one single element and will ensure that Next can only be called once. func SingleValue[T any](v T) Iterator[T] { return &singleValueIter[T]{V: v} } type singleValueIter[T any] struct { V T index int closed bool } func (i *singleValueIter[T]) ...
package main import ( "fmt" "io/ioutil" "net/http" "net/url" //"strconv" "strings" mf "github.com/mixamarciv/gofncstd3000" //"github.com/gorilla/sessions" ) //авторизация в вк апи func http_auth_vk(w http.ResponseWriter, r *http.Request) { d := map[string]interface{}{} get_vars, _ := url.ParseQuery(r.U...
package adasync import ( "github.com/adamcolton/err" "os" "path/filepath" "sort" ) func (ins *Instance) SelfUpdate() { err.Debug("Self Update: ", ins.pathStr) diff := ins.SelfDiff() // directories need to be resolved first, otherwise if a directory was // renamed, every file will think it was mov...
package main import ( "testing" "strconv" "github.com/stretchr/testify/assert" ) func TestCases(t *testing.T) { tcs := []struct { books []int cost int64 }{ {[]int{3, 2, 3, 2}, 8}, {[]int{6, 4, 5, 5, 5, 5}, 21}, {[]int{}, 0}, {[]int{100}, 100}, {[]int{100000, 100000, 100000, 100000}, 300000}, {...
package dao import ( "database/sql" "errors" _ "github.com/go-sql-driver/mysql" xerrors "github.com/pkg/errors" ) var ( ErrorNotRows = errors.New("There is no data.") ) // user info type User struct { ID int Name string } func GetUserByID(id int) (string, error) { db, err := sql.Open("mysql", "root:12345...
//数据库的插入操作 package sorm import ( "errors" "fmt" "log" "reflect" "strings" ) //insert into user (age,first_name,last_name) values (20,'Tom','One') func (q *Query) Insert(in interface{}) (int64, error) { var keys, values []string v := reflect.ValueOf(in) //剥离指针 if v.Kind() == reflect.Ptr { v = v.Elem() } /...
package handlers import ( "bytes" "reflect" "testing" ) func TestYamlFormatter_Run(t *testing.T) { type fields struct { filepath string } tests := []struct { name string fields fields output string }{ { "test1", fields{"./test1_actual.yaml"}, "./test1_expected.yaml", }, } for _, tt := ...
package lumps /** Lump 0: Entdata */ type EntData struct { LumpGeneric data string } func (lump *EntData) FromBytes(raw []byte, length int32) { lump.data = string(raw) lump.LumpInfo.SetLength(length) } func (lump *EntData) GetData() string { return lump.data } func (lump *EntData) ToBytes() []byte { return []...
package state_system type InitArgs struct { StateTree *StateTree GameState *GameState }
// Copyright © 2017 Yehor Nazarkin <nimnull@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 applicabl...
package mr import "fmt" import "log" import "net/rpc" import "hash/fnv" import "os" import "io/ioutil" import "strconv" import "encoding/json" import "sort" // for sorting by key. type ByKey []KeyValue // for sorting by key. func (a ByKey) Len() int { return len(a) } func (a ByKey) Swap(i, j int) { a[...
package control import ( "fmt" "github.com/et-zone/embi/chart" "github.com/et-zone/embi/dao" "github.com/et-zone/embi/model" "github.com/gin-gonic/gin" // "github.com/go-echarts/go-echarts/v2/charts" "github.com/go-echarts/go-echarts/v2/components" ) func HInsert(c *gin.Context) { h := &model.EHttp{} err ...
package main import ( "context" "google.golang.org/grpc" "grpc-gateway/healthcheck_client/healthcheck" "log" "time" ) const ( address = "localhost:50051" ) func main() { conn, err := grpc.Dial(address, grpc.WithInsecure()) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() c := ...
package main import ( "context" "encoding/json" "errors" "log" "os" "github.com/joeshaw/envdecode" "golang.org/x/oauth2" "golang.org/x/oauth2/google" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/grpc/metadata" servicespb "github.com/dictav/go-genproto-googleads/pb/v1...
package regclient import ( "encoding/json" "fmt" "strings" "github.com/sirupsen/logrus" ) // TLSConf specifies whether TLS is enabled for a host type TLSConf int const ( // TLSUndefined indicates TLS is not passed, defaults to Enabled TLSUndefined TLSConf = iota // TLSEnabled uses TLS (https) for the connect...
package main import ( "fmt" ) func dfs(s, n, mx int, dp, vis []bool) bool { if n <= 0 { return false } // fmt.Println(s, n) if vis[s] { return dp[s] } vis[s] = true for i := 0; i < mx; i++ { if s&(1<<uint(i)) != 0 { if !dfs(s^(1<<uint(i)), n-i-1, mx, dp, vis) { dp[s] = true ...
// Copyright 2019 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package main import ( "errors" "github.com/willf/bloom" "sync" "sync/atomic" ) var ( ErrInvalidAnswer = errors.New("Invalid answer") ErrDuplicateAnswer = errors.New("Duplicate answer") ErrNoAnswers = errors.New("No answers defined") ErrTooManyAnswers = errors.New("Too many answers defined") ErrTooSh...
package iaas import ( "encoding/json" "fmt" "os" "strings" . "github.com/afritzler/garden-examiner/cmd/gex/cleanup" "github.com/afritzler/garden-examiner/cmd/gex/util" "github.com/afritzler/garden-examiner/pkg" "github.com/jmoiron/jsonq" "github.com/mandelsoft/filepath/pkg/filepath" ) func init() { Registe...
package lib import ( "database/sql" "testing" "time" "github.com/dhaifley/dlib" "github.com/dhaifley/dlib/dauth" ) type MockTokenResult struct{} func (fr *MockTokenResult) LastInsertId() (int64, error) { return 1, nil } func (fr *MockTokenResult) RowsAffected() (int64, error) { return 1, nil } type MockTok...
package beat import ( "testing" "time" beat "github.com/elastic/beats/libbeat/beat" "github.com/elastic/beats/libbeat/common" "github.com/stretchr/testify/assert" ) func TestDefaultConfig(t *testing.T) { conf, err := common.LoadFile("../redisbeat.yml") if err != nil { t.Errorf("Load file failed %v", err) }...
package cpu // LR35902 simulates a Game Boy CPU through the usage of registers, program counter, // stack pointer, and more. More or less this will be the full "logic" of a real CPU. type LR35902 struct { registers *registers pc uint16 sp uint16 }
package web import ( "asyncMessageSystem/app/config" "asyncMessageSystem/app/controller/producer" log2 "asyncMessageSystem/app/middleware/log" "github.com/kataras/iris" "log" "runtime/debug" ) func PanicHandler(ctx iris.Context) { defer func() { msg := recover() if msg != nil { err := debug.Stack() l...
package shape import ( "fmt" "io" "github.com/gregoryv/draw/xy" "github.com/gregoryv/nexus" ) func NewState(title string) *State { return &State{ Title: title, Font: DefaultFont, Pad: DefaultTextPad, class: "state", } } type State struct { X, Y int Title string Font Font Pad Padding class...
package main //637. 二叉树的层平均值 //给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。 //示例 1: //输入: //3 /// \ //9 20 /// \ //15 7 //输出:[3, 14.5, 11] //解释: //第 0 层的平均值是 3 , 第1层是 14.5 , 第2层是 11 。因此返回 [3, 14.5, 11] 。 //提示:节点值的范围在32位有符号整数范围内。 /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *Tre...
package ex7_2 import ( "io" ) type CountWriter struct { Writer io.Writer Count int64 } func (c *CountWriter) Write(in []byte) (n int, err error) { n, err = c.Writer.Write(in) c.Count += int64(n) return } func CountingWriter(w io.Writer) (io.Writer, *int64) { cw := &CountWriter{ Writer: w, Count: 0, } ...
package main import ( "fmt" "os" "strconv" "github.com/iotaledger/hive.go/codegen/variadic" ) // main is the entry point of the variadic code generator. func main() { if len(os.Args) < 4 { printUsage("not enough parameters") } minParamsCount, err := strconv.Atoi(os.Args[1]) if err != nil { printUsage("m...
package main import ( "encoding/binary" "encoding/json" "errors" "fmt" "net" "github.com/astaxie/beego/logs" "github.com/wsq1220/chatroomServer/proto" ) type Client struct { conn net.Conn userId int buf [8192]byte } // receive func (p *Client) readPackage() (msg proto.Message, err error) { n, err :=...
// Copyright (C) 2020 Storj Labs, Inc. // See LICENSE for copying information. package sync2_test import ( "context" "sync" "testing" "github.com/stretchr/testify/require" "storj.io/common/sync2" ) func TestNewSuccessThreshold(t *testing.T) { t.Parallel() var testCases = []struct { desc strin...
package clock import "fmt" // Clock structure type Clock struct { hour int minute int } // New constructs Clock object func New(h, m int) Clock { return Clock{0, 0}.Add(h*60 + m) } func (c Clock) String() string { return fmt.Sprintf("%02d:%02d", c.hour, c.minute) } // Add adds amount 'minutes' to current clo...
package main import ( "net/http" "net/http/httptest" "os" "strings" "testing" ) var a App func TestMain(m *testing.M) { a = App{} a.Init() code := m.Run() os.Exit(code) } func TestBadMode(t *testing.T) { req, _ := http.NewRequest("POST", "/process", nil) response := executeRequest(req) checkResponseCode...
/* /tmp/1.txt内容为: { "name":"xiaoli", "Age":20, "Sex":"女" } */ package main import ( "fmt" "log" "encoding/json" "os" ) type person struct { Name string `json:"name"` Age int `"json:age"` Sex string `"json:sex"` } func main(){ fd, err := os.Open("/tmp/1.txt") if err != nil { log.Fatal("os.Open Err : ", e...
package main import ( "fmt" "imooc/pipeline" "os" "bufio" ) func main() { const filename = "small.in" const n = 64 file, err := os.Create(filename) if err != nil { panic(err) } defer file.Close() write := bufio.NewWriter(file) pipeline.WriterSink(write,pipeline.RandomResource(n)) write.Flush() /*f...
package client import ( "io" "net/http" "time" ) const ( maxDefaultRetries = 3 ) // These values are derived from the default values of DefaultTransport and // Transport respectively from net/http/transport.go var ( defaultRequestTimeout = 30 * time.Second defaultTLSHandshakeTimeout = 10 * time.Second de...
package k8sutil import ( "fmt" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" ) // GetClient returns a Kubernetes client (clientset) from the kubeconfig path // or from the in-cluster service account environment. func GetClient(path string) (*kubernetes.Clientset, error)...
package main import ( "encoding/json" "flag" "fmt" "go/build" "io/ioutil" "os" "os/exec" "path/filepath" "sort" "strings" ) var ( diff = flag.String("diff", "HEAD", "The git commit pattern to diff by. E.g.: 'HEAD', or '<commit>...<commit>'") debug = flag.Bool("debug", false, "Verbose output.") ) const (...
package supervisor import ( "fmt" "github.com/couchbase/cbauth" "github.com/couchbase/eventing/logging" "github.com/couchbase/eventing/util" ) var getHTTPServiceAuth = func(args ...interface{}) error { s := args[0].(*SuperSupervisor) user := args[1].(*string) password := args[2].(*string) var err error clu...
package main import "fmt" func searchRange(A []int, target int) []int { // write your code here res := make([]int, 2) flag := true if len(A) == 0 { return []int{-1, -1} } for i := 0; i < len(A); i++ { if A[i] == target { if flag { res[0] = i flag = false } else { res[1] = i } } } r...
package postgres import ( "context" "database/sql" "encoding/json" "github.com/pganalyze/collector/state" ) const typesSQL string = ` SELECT t.oid, t.typarray AS arrayoid, n.nspname AS schema, t.typname AS name, t.typtype AS type, CASE WHEN t.typtype = 'd' THEN pg_catalog.forma...
package contact import ( "github.com/chidam1994/happyfox/models" "github.com/google/uuid" ) type Repository interface { Save(contact *models.Contact) (uuid.UUID, error) Delete(contactId uuid.UUID) error Find(filterMap map[models.Filter]string) ([]models.Contact, error) FindById(contactId uuid.UUID) (*models.Con...
package consumer import ( "fmt" "time" ) func newVbProcessingStats(appName string) vbStats { vbsts := make(vbStats, numVbuckets) for i := uint16(0); i < numVbuckets; i++ { vbsts[i] = &vbStat{ stats: make(map[string]interface{}), } vbsts[i].stats["last_processed_seq_no"] = uint64(0) vbsts[i].stats["dcp_...
package dubbo import ( "bytes" "encoding/binary" ) const ( headerLength = 16 magicHigh = byte(0xda) magicLow = byte(0xbb) flagRequest = byte(0x80) flagTwoWay = byte(0x40) serializationID = byte(0x6) ) // Dubbo ... type Dubbo struct { buffer *bytes.Buffer databuf *bytes.B...
package goautils import ( "context" "net/http" "os" "os/signal" "syscall" "github.com/codeclysm/ctxlog/v2" httpmdlwr "goa.design/goa/v3/http/middleware" goamdlwr "goa.design/goa/v3/middleware" ) type logger interface { Debug(msg string, fields ...map[string]interface{}) Info(msg string, fields ...map[strin...
package phase import ( "github.com/felixangell/goof/cc/unit" ) type Phase interface { ExecutePhase(file *unit.SourceFile) }
package logger import ( "fmt" "net" "os" "runtime/debug" "time" rotatelogs "github.com/lestrrat-go/file-rotatelogs" "github.com/rs/zerolog" ) var PackageField = "package" var ModuleField = "module" var FuncName = "func" var LocalIpField = "localIps" //TimeFormat default timefield format var TimeFormat = "2...
// extracted from argoproj/argo-cd/pkg/apis/application/v1alpha1/types.go package resource import ( "encoding/json" "gopkg.in/yaml.v2" ) // ResourceIgnoreDifferences contains resource filter and list of json paths which should be ignored during comparison with live state. type ResourceIgnoreDifferences struct { G...
package main import ( goflag "flag" "fmt" "os" ) func main() { Execute() } // exitWithError will terminate execution with an error result // It prints the error to stderr and exits with a non-zero exit code func exitWithError(err error) { fmt.Fprintf(os.Stderr, "\n%v\n", err) os.Exit(1) } func Execute() { go...
package model import ( "gorm.io/gorm" "time" ) // ApplePackage 定义表模型-苹果IPA包表 type ApplePackage struct { ID int `gorm:"primary_key;AUTO_INCREMENT;comment:自增ID"` BundleIdentifier string `gorm:"not null;column:bundleIdentifier;comment:安装包id"` Name string `gorm:"not null;column:...
package ocpp import ( "fmt" "strconv" "strings" "sync" "time" "github.com/benbjohnson/clock" "github.com/evcc-io/evcc/api" "github.com/evcc-io/evcc/util" "github.com/lorenzodonini/ocpp-go/ocpp1.6/core" "github.com/lorenzodonini/ocpp-go/ocpp1.6/remotetrigger" "github.com/lorenzodonini/ocpp-go/ocpp1.6/types"...
// Publish Play Events to Redis package events import ( "encoding/json" log "github.com/Sirupsen/logrus" "gopkg.in/redis.v3" ) // Publish a Play Event from the Player to Redis. This sets the current // playing track, the user and start time as well as publishing to the // event channel func PublishPlayEvent(c *r...
// Copyright 2020 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package vppd import ( "github.com/contiv/netplugin/netmaster/mastercfg" ) const ( // StateOperPath is the path to the operations stored in state. vppOperPathPrefix = mastercfg.StateOperPath + "vpp-driver/" vppOperPath = vppOperPathPrefix + "%s" )
package random import ( "context" "math/rand" "github.com/go-kratos/kratos/v2/selector" "github.com/go-kratos/kratos/v2/selector/node/direct" ) var ( _ selector.Balancer = &Balancer{} // Name is balancer name Name = "random" ) // Balancer is a random balancer. type Balancer struct{} // New random a selecto...