text
stringlengths
11
4.05M
package Common import ( "errors" "github.com/andrewz1/gosmpp/Exception" "github.com/andrewz1/gosmpp/Utils" ) type IByteDataList interface { CreateValue() IByteData } type ByteDataList struct { ByteData Values []IByteData MaxSize int LengthOfSize byte } func NewByteDataList() *ByteDataList { a :...
package api import ( "encoding/json" "fmt" "net/http" "github.com/azzzak/fakecast/store" ) type overview struct { Channel *store.Channel `json:"info"` Podcasts []store.Podcast `json:"podcasts"` } type updateChannel struct { Channel *store.Channel `json:"channel"` OldAlias string `json:"old_alias"...
package main import ( "github.com/astaxie/beego/logs" "encoding/json" "fmt" ) /** LevelEmergency = iota LevelAlert LevelCritical LevelError LevelWarning LevelNotice LevelInformational LevelDebug */ func convertLogLevel(loglevel string) int { switch loglevel { case "debug": return logs.LevelDebug ca...
package main import ( "fmt" ) type TemplateContainer struct { ContainerCommon } func (temp TemplateContainer) Build() bool { fmt.Println("Template build", temp.Distribution) return true } func (temp TemplateContainer) Pull() bool { return true } func (temp TemplateContainer) Deploy() bool { return true } fu...
package worker import ( "bufio" "fmt" "net" "strings" "time" // "regexp" ) type PopResp struct { // Error error Error string Flag string Message string TimeDur float64 } /* func isLikePopResp(s *string) bool { news := strings.TrimRight(*s, "\n") // !!! trim first popregex := regexp.MustCompile(`^...
package message import ( "testing" "github.com/airbloc/airbloc-go/account" "github.com/klaytn/klaytn/common" "github.com/klaytn/klaytn/common/hexutil" "github.com/klaytn/klaytn/crypto" "github.com/perlin-network/noise" "github.com/perlin-network/noise/payload" uuid "github.com/satori/go.uuid" . "github.com/...
package app import ( "net/http" "github.com/superbkibbles/bookstore_items-api/src/controllers" ) func mapUrls() { // Ping controller router.HandleFunc("/ping", controllers.PingController.Ping) // Item controller router.HandleFunc("/items", controllers.ItemController.Create).Methods(http.MethodPost) router.Han...
package aliyun import ( "errors" "path" "strconv" "github.com/JointFaaS/Manager/env" "github.com/aliyun/fc-go-sdk" ) var service = "jointfaas" // CreateFunction : // sourceURL can be created by UploadSourceCode func (m *Manager) CreateFunction(funcName string, dir string, e env.Env, memoryS string, timeoutS st...
package public import ( "context" "fmt" "tpay_backend/merchantapi/internal/common" "tpay_backend/model" "tpay_backend/merchantapi/internal/svc" "tpay_backend/merchantapi/internal/types" "github.com/tal-tech/go-zero/core/logx" ) type PlatformBankCardListLogic struct { logx.Logger ctx context.Context svc...
package main import ( "encoding/json" "errors" "fmt" "io" "io/ioutil" "log" "net/http" "net/url" "os" "regexp" "strings" "sync" "time" "github.com/kyf/postwx" ) func fetchWxMedia(fpath string) (string, error) { data := make(url.Values) data.Set("fpath", fpath) dir, err := uploadDir(UPLOAD_PATH) if ...
package config import ( "database/sql" "fmt" "log" "os" _ "github.com/go-sql-driver/mysql" "github.com/joho/godotenv" ) func InitDatabase() *sql.DB { db := db() return db } func db() *sql.DB { err := godotenv.Load() if err != nil { log.Println(err) } user := os.Getenv("DB_USER") password := os.Getenv...
package gateway import ( "context" "github.com/google/go-github/github" ) // PullRequestReviewState indicates whether a PR has been accepted or not. type PullRequestReviewState string const ( // PullRequestApproved indicates that a pull request was accepted. PullRequestApproved PullRequestReviewState = "APPROVE...
package main import ( "fmt" "time" ) var nums = []byte{'1', '2', '3', '4', '5', '6', '7', '8', '9'} func solveSudoku(board [][]byte) { solve(board, 0, 0) } func solve(board [][]byte, i, j int) bool { if i == 9 { fmt.Println("====") return true } if j == 9 { fmt.Println("====") return solve(board, i +...
package main import ( "sort" "github.com/heartchord/jxonline/gamestruct" "github.com/lxn/walk" ) // RoleSkillDataItem : type RoleSkillDataItem struct { DataModelItemBase SkillID string // 数据名称 SkillLv string // 数据内容 SkillExp string // 数据说明 } // RoleSkillDataModel : type RoleSkillDataModel...
/* Using one single statement, numerically assign the IEEE 754 : +INF to variable a — inf also acceptable -INF to variable b +NaN to variable c — a sign-less nan being displayed is acceptable as long as the code demonstrates how it arrives at a positive nan -NaN to variable d — a sign-less nan being displayed i...
package main import ( "fmt" "io/ioutil" "log" "os" ) func main() { logFile := os.Getenv("LOGFILE") message := "Writing to " + logFile + " from setup" err := ioutil.WriteFile(logFile, []byte(message), 0644) if err != nil { log.Fatal(err) } fmt.Printf("First message: %s", message) }
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "os" ) type Configuration struct { Address string ReadTimeout int64 WriteTimeout int64 Static string } var config Configuration var logger *log.Logger func p(a ...interface{}) { fmt.Println(a) } func init() { file, err := os.Ope...
package register import ( "io/ioutil" "testing" "github.com/stretchr/testify/require" ) func TestFindMax(t *testing.T) { assert := require.New(t) m, h := findMax(` b inc 5 if a > 1 a inc 1 if b < 5 c dec -10 if a >= 1 c inc -20 if c == 10`) assert.Equal(1, m) assert.Equal(10, h) } func TestSolveFind...
package simplestake import ( "testing" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto/ed25519" sdk "github.com/cosmos/cosmos-sdk/types" ) func TestBondMsgValidation(t *testing.T) { privKey := ed25519.GenPrivKey() cases := []struct { valid bool msgBond MsgBond }{ {true,...
// +build linux package fscommon import ( "io/ioutil" "os" "syscall" securejoin "github.com/cyphar/filepath-securejoin" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) func WriteFile(dir, file, data string) error { if dir == "" { return errors.Errorf("no directory specified for %s", file) } path, ...
package tstune import ( "fmt" "io" "os" "path" "path/filepath" "strings" "time" ) const ( backupFilePrefix = "timescaledb_tune.backup" backupDateFmt = "200601021504" errBackupNotCreatedFmt = "could not create backup at %s: %v" ) // allows us to substitute mock versions in tests var filepathGlobFn = fil...
package bench import ( "bytes" stdjson "encoding/json" "fmt" "testing" wish "github.com/warpfork/go-wish" "github.com/polydawn/refmt" ) func exerciseMarshaller( b *testing.B, subj refmt.Marshaller, buf *bytes.Buffer, val interface{}, expect []byte, ) { var err error for i := 0; i < b.N; i++ { buf.Res...
// 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 core // global variables in this case are ok since: // 1 - the package handles only one dataset at a time // 2 - most of the functions use the images manager const ( cosMinAngle = 0.9396926207859084 //math.Cos(20 * math.Pi / 180) cosMaxAngle = 0.5 //math.Cos(60 * math.Pi / 180) featMax...
package plug import ( "fmt" ) type Plug interface { Connect() error Loop() Changes() <-chan Change Send(string) error } type Change struct { User string Channel string Server string Data string } func (c Change) String() string { return fmt.Sprintf( "%s%s@%s> %s", c.User, c.Channel, c.Serve...
package g2util import ( "encoding/json" "reflect" ) // MergeBean ... // @Description: merge struct's point, merge src to dst // @param dst // @param src func MergeBean(dst interface{}, src Map) (err error) { dv1 := reflect.ValueOf(dst) if dv1.Kind() != reflect.Ptr { panic("dst needs pointer kind") } dstBs, er...
package main import ( "net" "errors" "strings" "io/ioutil" "encoding/pem" "crypto" "crypto/tls" "crypto/x509" "crypto/rsa" "crypto/ecdsa" "flag" "log" "net/http" "fmt" ) var url = flag.String("url", "https://127.0.0.1:8443", "the url to get") var certFile = flag.String("certFile", "cert.pem", "the cert...
/* * 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 log import "testing" func TestLog(t *testing.T) { ConfigZapLog(&LogSettings{ EnableConsole: true, }) logger.Info("111") }
// problem 10.2 package chapter10 func sgn(a, b int) int { if a < b { return 1 } else { return -1 } } func reverse(arr []int) { n := len(arr) for i := 0; i < n/2; i++ { arr[i], arr[n-1-i] = arr[n-1-i], arr[i] } } func SortKIncreasingDecreasingArray(arr []int) []int { arrs := make([][]int, 0) currSgn :...
// Copyright 2016 Kranz. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package fakeApi import ( "fmt" "os" "path" "strconv" "strings" "time" "gopkg.in/macaron.v1" "github.com/rodkranz/fakeApi/modules/log" ) type ApiFakeOptions st...
package boltrepo import ( "github.com/boltdb/bolt" "github.com/scjalliance/drivestream/commit" "github.com/scjalliance/drivestream/resource" ) var _ commit.TreeGroup = (*CommitTreeGroup)(nil) // CommitTreeGroup is an unordered group of tree changes sharing a common // parent. type CommitTreeGroup struct { db ...
// Copyright 2020-present Kuei-chun Chen. All rights reserved. package keyhole import ( "fmt" "io/ioutil" "github.com/simagix/gox" "go.mongodb.org/mongo-driver/bson" ) const ( compareClusters = "compare_clusters" printConnections = "print_connections" ) // Config stores keyhole configuration type Config str...
// SPDX-License-Identifier: Unlicense OR MIT package material import ( "github.com/gop9/olt/gio/layout" "github.com/gop9/olt/gio/text" "github.com/gop9/olt/gio/unit" "github.com/gop9/olt/gio/widget" ) type RadioButton struct { checkable Key string } // RadioButton returns a RadioButton with a label. The key s...
package manager import ( "github.com/roberthafner/bpmn-engine/domain/model" "github.com/roberthafner/bpmn-engine/domain/model/database" ) type EntityManager interface { Insert(e model.Entity) Update(e model.Entity) Delete(e model.Entity) } type DeploymentEntityManager struct { db database.Database } func New...
//author: https://github.com/5k3105 package main import ( "os" "strconv" "github.com/emirpasic/gods/lists/arraylist" "github.com/therecipe/qt/core" "github.com/therecipe/qt/gui" "github.com/therecipe/qt/widgets" ) var statusbar *widgets.QStatusBar func main() { widgets.NewQApplication(len(o...
/* Copyright (c) 2017 GigaSpaces Technologies Ltd. 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 ...
/* * Copyright (c) 2019. Alexey Shtepa <as.shtepa@gmail.com> LICENSE MIT * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. */ package uuid import ( "crypto/rand" "encoding/hex" "math/big" "strings" ) // GenerateBytesUUID ret...
package mongo_test import ( // Standard Library Imports "testing" "time" // External Imports "github.com/ory/fosite" "github.com/pborman/uuid" // Public Imports "github.com/matthewhartstonge/storage" ) func expectedSessionCache() storage.SessionCache { return storage.SessionCache{ ID: uuid.New(),...
package commands import ( "context" "encoding/json" "io" "os" "path/filepath" "github.com/pkg/errors" "github.com/spf13/cobra" ) // Inspect runs the command to inspect a cluster func Inspect(ctx context.Context, stateDir string) *cobra.Command { cmd := &cobra.Command{ Use: "inspect", Short: "Get detail...
/* Copyright © 2020 Vlad Krava <vkrava4@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 ...
package main import ( "net" "log" "fmt" ) /** net包实现服务端的核心部分是: net.Listen()在给定的本地网络地址上来创建新的监听器。如果只传端口号给它,例如":61000", 那么监听器会监听所有可用的网络接口。 这相当方便,因为计算机通常至少提供两个活动接口,回环接口和最少一个真实网卡。 这个函数成功的话返回Listener。 Listener接口有一个Accept()方法用来等待请求进来。然后它接受请求,并给调用者返回新的连接。Accept()一般来说都是在循环中调用,能够同时服务多个连接。每个连接可以由一个单独的goroutine处理,正如下面代码所示的。...
package cli import ( "errors" "fmt" "reflect" ) func CombineStructs(structs ...interface{}) (interface{}, error) { fields := []reflect.StructField{} for _, s := range structs { v := reflect.Indirect(reflect.ValueOf(s)) if v.Kind() != reflect.Struct { return nil, fmt.Errorf("invalid value type, must be str...
package main import "fmt" func main() { x := []int{42, 43, 44, 45, 46, 47, 48, 49, 50, 51} a := x[:5] fmt.Println(a) a = x[5:] fmt.Println(a) a = x[2:7] fmt.Println(a) a = x[1:6] fmt.Println(a) }
package controllers import ( "github.com/revel/revel" "github.com/revel/modules/db/app" "goblog/app/models" "time" "goblog/app/routes" "database/sql" "fmt" ) type Post struct { *revel.Controller db.Transactional } func (c Post) Index() revel.Result { var posts []models.Post rows, err := c.Txn.Query("selec...
package envoy import "fmt" type Collector struct { AdminHost string } // Value by quantile (P75, P90, etc.) type Histogram map[string]float64 type Counters struct { // Counters UpstreamReq, UpstreamResp2xx, UpstreamResp4xx, UpstreamResp5xx float64 } func (c *Counters) String() string { return fmt.Sprintf( ...
// Copyright 2017 The Bazel Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // The skylark command interprets a Skylark file. // // With no arguments, it starts a read-eval-print loop (REPL). // If an input line can be parsed as an e...
package main func main() { } func i() chan int { return make(chan int) }
// Copyright 2018 Diego Bernardes. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package flare import "github.com/pkg/errors" // Pagination used to fetch a slice of a given entity. type Pagination struct { Limit int Offset int Total ...
package logger import ( "fmt" "github.com/sirupsen/logrus" ) type elasticHook struct{} func NewElasticHook() logrus.Hook { return new(elasticHook) } func (eh *elasticHook) Levels() []logrus.Level { return logrus.AllLevels } func (eh *elasticHook) Fire(entry *logrus.Entry) error { var levelText string // Add ...
package testdata import ( "github.com/frk/gosql" "github.com/frk/gosql/internal/testdata/common" ) type SelectWithOrderByDirectiveQuery struct { Users []*common.User `rel:"test_user:u"` _ gosql.OrderBy `sql:"-u.created_at"` }
package main import ( "bufio" "io" "io/ioutil" "strings" "unicode" "github.com/BurntSushi/toml" ) // Updater represents updater type Updater struct { Name string URL string Params map[string]string } // Update executes update and returns result func (updater *Updater) Update() (string, error) { url, ...
package eeautil import "math/rand" // Contains returns true if the given slice contains the given int. func Contains(list []int, ind int) bool { for _, v := range list { if ind == v { return true } } return false } // RandomSubset sets the destintation slice to be a random subset of the // numbers 0, ..., ...
package ethos import ( "io/ioutil" "os" "os/exec" "strconv" "strings" "time" "github.com/ka2n/masminer/machine/metal/gpu/gpustat" ) // Stat : gpuの情報をethOSのAPIで取得します func Stat() ([]gpustat.GPUStat, error) { return nil, nil } func GPUs() (string, error) { c, err := readFile("/var/run/ethos/gpucount.file") ...
package fastrbac // A trust is a list of permissions for a holder on an object that it isn't owner for. type Trust struct { HolderId int64 HolderType string ObjectId int64 ObjectType string Permissions []string } // A role defines what permissions that a holder has on objects that are owned by another ho...
package main import "fmt" import "os" import "strings" import "io/ioutil" import "path/filepath" import "time" import "syscall" import "golang.org/x/crypto/ssh/terminal" import "gopkg.in/src-d/go-git.v4" import gitconfig "gopkg.in/src-d/go-git.v4/config" import "gopkg.in/src-d/go-git.v4/plumbing/object" import "gopkg....
package session import ( "fmt" "go/internal/pkg/api/app/request" ) func (uc *sessionUsecase) FindDetailUseCase(req request.SessionRequest) (interface{}, error) { criteria := map[string]interface{}{ "id": req.ID, } session, err := uc.sessionRepo.FindOneBy(criteria) if err != nil { return nil, fmt.Errorf("get...
package services import ( "strings" "time" "github.com/ne7ermore/gRBAC/common" "github.com/ne7ermore/gRBAC/plugin" ) type perMap map[string]plugin.Permission type Role struct { Id string `json:"id"` Name string `json:"name"` Permissions perMap `json:"permissions"` CreateTime time.T...
package core import ( "strconv" ) type PriceTarget struct { Operator string Value float64 } func (t PriceTarget) Test(price float64) bool { switch t.Operator { case "+": return price > t.Value case "-": return price < t.Value } return false } // Expected format: "10+,5-, etc" func convertTargets(raw...
package lib import ( "golang.org/x/crypto/bcrypt" ) func HashPassword(password string) string { hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { panic(err) } return string(hash) } func VerifyPassword(hashedPassword, password string) (bool, error) { err := bcrypt...
package lruCache import ( "bytes" "container/list" "errors" "fmt" "github.com/cockroachdb/pebble" "log" "sync" ) // https://github.com/hashicorp/golang-lru/blob/master/simplelru/lru.go // https://github.com/golang/groupcache/blob/master/lru/lru.go // https://github.com/hashicorp/golang-lru/blob/master/lru.go ...
package day5 import ( loader "aoc/dataloader" "aoc/test" "testing" ) func TestPart1(t *testing.T) { cases := []test.Case[[]string, string]{ {loader.Load("sample.txt"), "CMZ"}, {loader.Load("input.txt"), "MQSHJMWNH"}, } err := test.Execute(cases, Part1) if err != nil { t.Error(err) } } func TestPart2(t ...
package main /** 最长有效括号 给定一个只包含 `'('` 和 `')'` 的字符串,找出最长的包含有效括号的子串的长度。 示例1: ``` 输入: "(()" 输出: 2 解释: 最长有效括号子串为 "()" ``` 示例2: ``` 输入: ")()())" 输出: 4 解释: 最长有效括号子串为 "()()" ``` */ /** 栈 + 辅助数组 */ func LongestValidParentheses(s string) int { var stack []int res := make([]bool, len(s)) for i := 0; i < len(s); i++ { ...
//lorawanWrapper.go package main import "C" import ( "bytes" "fmt" "os" "time" "unsafe" "math" . "github.com/matiassequeira/lorawan" log "github.com/sirupsen/logrus" ) //export marshalJsonToPHYPayload func marshalJsonToPHYPayload(jsonPointer *C.char, keyPointer *C.char, nwkskeyPointer *C.char) *C.char { v...
package main import "fmt" func main() { fmt.Println(reverseLeftWords2("abcdefg", 2)) fmt.Println(reverseLeftWords2("lrloseumgh", 6)) } func reverseLeftWords(s string, n int) string { return s[n:] + s[:n] } func reverseLeftWords2(s string, n int) string { bs := []byte(s) reverse := func(left, right int) { fo...
package main import ( "github.com/nurblieh/restos/lib" "flag" "fmt" ) var ( address = flag.String("address", "", "Address to geocode.") ) func main() { flag.Parse() ll, e := lib.Geocode(*address) if e != nil { fmt.Println("Error.", e) panic("foo") } fmt.Printf("%v\n", ll) }
package register import ( "github.com/Azer0s/quacktors" "sync" ) var register = make(map[string]*quacktors.Pid) var registerMu = &sync.RWMutex{} //ModifyUnsafe passes both the actual pid-register as well as //the pid-register-mutex to a callback function so they can be //modified directly. This should be used with...
package command import ( "fmt" "strconv" "strings" "time" "github.com/jixwanwang/jixbot/channel" ) type money struct { cp *CommandPool cash *subCommand stats *subCommand give *subCommand giveAll *subCommand } func (T *money) Init() { T.cash = &subCommand{ command: "!cash", numArgs: 0, ...
package models import ( "container/list" ) type EventType int const ( EVENT_JOIN = iota EVENT_LEAVE EVENT_MESSAGE ) type Event struct { Type EventType // JOIN, LEAVE, MESSAGE User string Timestamp int Content string } const wsSize = 20 // Event ws. var ws = list.New() // NewWs saves new event...
package main import ( "sort" "testing" ) func TestRespace(t *testing.T) { dict := []string{"abc", "deff", "cccccc"} sort.Slice(dict, func(i, j int) bool { return len(dict[i]) > len(dict[j]) }) }
// Copyright Amazon.com Inc. or its affiliates. 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. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file ...
package demo import ( "fmt" ) func test1() { var a int fmt.Printf("a的内存地址: %p \n", &a) } func test2() { var a *int fmt.Printf("指针变量 a 的内存地址:%p, a 的值:%v \n", &a, a) b := 100 fmt.Printf("变量 b 的内存地址:%p, b 的值:%v \n", &b, b) a = &b fmt.Printf("指针变量 a 的内存地址:%p, a 的值:%v \n", &a, a) } func test3() { b := 100 fm...
package main import ( "go-mlp/nn" "math/rand" ) func main() { rand.Seed(1) inputs := [][]float64{ []float64{1, 1}, []float64{1, 0}, []float64{0, 1}, []float64{0, 0}, } outputs := [][]float64{ []float64{0}, []float64{1}, []float64{1}, []float64{0}, } mlp := nn.NewNN([]int{2, 1}, 2) mlp.Print(...
package main import ( "encoding/json" "io" "net/http" "os" "time" "github.com/gorilla/mux" "github.com/sirupsen/logrus" ) // APIContext - provides access to request parameters and other information for the API handler type APIContext interface { Vars() map[string]string WriteJSON(result interface{}) error }...
package aoc2015 import ( "testing" aoc "github.com/janreggie/aoc/internal" "github.com/stretchr/testify/assert" ) func TestDay03(t *testing.T) { assert := assert.New(t) testCases := []aoc.TestCase{ {Input: "^v", Result1: "2", Result2: "3"}, {Input: "^>v<", Result1: "4", Result2: "3"}, {Input: ...
package sphinx import ( "github.com/btcsuite/btcd/btcec/v2" "golang.org/x/crypto/ripemd160" ) // TODO(roasbeef): Might need to change? due to the PRG* requirements? const fSLength = 48 // Hmm appears that they use k = 128 throughout the paper? // HMAC -> SHA-256 // * or could use Poly1035: https://godoc.org/gola...
package machinery import ( "fmt" "math" ) type ConflictResolver interface { Rename(kind string, oldName string, validator func(string) error) string } type autoResolver struct{} func (r *autoResolver) Rename( kind string, oldName string, validator func(string) error, ) string { for i := 1; i < math.MaxInt; i...
package migrate import ( "strings" "github.com/neuronlabs/errors" "github.com/neuronlabs/neuron-core/class" "github.com/neuronlabs/neuron-postgres/internal" "github.com/neuronlabs/neuron-postgres/log" ) // KeyWordType is the postgres default key word type. type KeyWordType int // IsReserved checks if the curr...
package main import ( "fmt" "github.com/samuel/go-zookeeper/zk" client2 "zookeeper/client" ) func callback(event zk.Event) { } func main() { // 先安转zookeeper // 服务器地址列表 servers := []string{"192.168.5.216:2181"} client, err := client2.NewClient(servers, "/api", 10, func(event zk.Event) { // zk.EventNodeCrea...
package main /* Use built-in synchronization features to achieve the same result as using mutexes. (go routines and channels) The channel-based approach aligns with Go's ideas of sharing memory by communicating and having each piece of data owned by exactly one goroutine */ import ( "fmt" "math/rand" "sync/atomic...
// Package api implements of API/Controller layer of application // Consisting of some API endpoints which are covered with Swagger annotations package api import ( "errors" "net/http" "strconv" "time" "github.com/gin-gonic/gin" "../models" "../service" ) // ReadCandidate godoc // @Summary Read candidate // ...
// Package rotate is a port of File-Rotate from Perl // (https://metacpan.org/release/File-Rotate), and it allows // you to automatically rotate output files when you write to them // according to the filename pattern that you can specify. package rotate import ( "fmt" "io" "os" "path/filepath" "time" "github.c...
/* Package log implements a simple logging package. package main import ( "github.com/ije/gox/log" ) func main() { l, err := log.New("file:/var/log/error.log?buffer=32kb") if err != nil { return } l.Info("Hello World!") } */ package log import ( "fmt" "io" "os" "runtime" "str...
package main import ( "flag" "fmt" "github.com/rs/zerolog/log" "os" "toutiao/admin" "toutiao/downloader" "toutiao/tools" "toutiao/translator" ) type A struct { year int } func (a A) Greet() { fmt.Println("Hello GolangUK", a.year) } type B struct { A } func (b B) Greet() { fmt.Println("Welcome to GolangUK...
package dal import ( "errors" ) // QueryProvider 提供数据库查询接口 type QueryProvider interface { // 查询单条数据 Single(entity QueryEntity) (map[string]string, error) // 查询单条数据 SingleWithSQL(sql string, values ...interface{}) (map[string]string, error) // 将查询结果解析到对应的指针地址 // (数据类型包括:map[string]string,map[string]interface{},...
// lexer.go package main import ( "bytes" "fmt" "io/ioutil" "os" "os/exec" "regexp" "strings" ) func assemble(asm ASM, source, executable string) (err error) { var srcFile *os.File var e error if source == "" { srcFile, e = ioutil.TempFile("", "") if e != nil { err = fmt.Errorf("Creating temporary ...
package main // for printing data out import "fmt" // for reading the cli import "os" // for logging errors and actions import "log" // for dumping data from the file to somewhere else - eg, Copy import "io" func main() { arguments := os.Args if (len(arguments) != 2 ) { fmt.Println("The Program requires a fi...
package config import ( "fmt" "log" _ "github.com/lib/pq" "xorm.io/xorm" ) const ( host = "localhost" port = 5432 user = "postgres" password = "password" dbName = "golang" ) func GetDBEngine() *xorm.Engine { psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disab...
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package operations import ( "fmt" "testing" "time" . "github.com/onsi/gomega" "github.com/pkg/errors" log "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" "github.com/Azure/aks-engine/pkg/api/common" "github...
package api_test import ( "context" "net/http" "reflect" "strings" "testing" "github.com/chanioxaris/go-datagovgr/datagovgrtest" "github.com/jarcoal/httpmock" ) func TestTelcos_IndicatorsAndStatistics_Success(t *testing.T) { ctx := context.Background() fixture := datagovgrtest.NewFixture(t) httpmock.Activ...
package testdata import ( "bytes" "io" "os" "path/filepath" "runtime" ) // UCDReader returns reader for the given ucd file for testing. func UCDReader(file string) (io.Reader, error) { data, err := os.ReadFile(UCDPath(file)) if err != nil { return nil, err } return bytes.NewReader(data), nil } // UCDPath...
package odder import "net/rpc" func (odderClient *OdderClient) IsOdd(n int) (even bool, err error) { reply := &OdderIsOddReply{} err = odderClient.client.Call("OdderServer.IsOdd", &OdderIsOddArgs{N: n}, reply) if err != nil { reply.Err = err } return reply.Even, reply.Err } func (odderClient *OdderClient) Cre...
package chessboard import "fmt" type squareCoordinates struct { x uint8 y uint8 } func (s squareCoordinates) getX() uint8 { return s.x } func (s squareCoordinates) getY() uint8 { return s.y } func (s squareCoordinates) getXAsIndex() int { return int(s.x - 'A') } func (s squareCoordinates) getYAsIndex() int {...
package main import ( "crypto/sha1" "fmt" "io" "log" "os" ) func main() { files := []string{"file1.txt", "file2.txt"} for _, file := range files { f, err := os.Open(file) if err != nil { log.Fatal(err) } defer f.Close() h := sha1.New() if _, err := io.Copy(h, f); err != nil { log.Fatal(err)...
package cli import ( "flag" "testing" ) func TestIsFlagSetStd(t *testing.T) { fs := flag.NewFlagSet("foo", flag.PanicOnError) fs.Int("width", 10, "width of rect") fs.String("name", "", "name hint here") fs.Parse([]string{""}) if IsFlagSet(fs, "width") { t.Error("width did not set yet") } if IsFlagSet(fs, ...
package handlers import ( "net/http" "net/http/httptest" "net/url" "testing" "github.com/stretchr/testify/assert" ) func TestWellKnownPomeriumHandler(t *testing.T) { t.Parallel() t.Run("cors", func(t *testing.T) { authenticateURL, _ := url.Parse("https://authenticate.example.com") w := httptest.NewRecord...
package queue import ( "errors" ) const ( ErrPop = "error pop" ) type Queue []interface{} func (q *Queue) Push(item interface{}) { *q = append(*q, item) } func (q *Queue) Pop() (interface{}, error) { if len(*q) <= 0 { return nil, errors.New(ErrPop) } res := (*q)[0] *q = (*q)[1:] return res, nil } func ...
package godoc_test import ( "fmt" "github.com/lovexiaoe/golangpros/basics/godoc" ) // 以"包名_test"作为包名, // 该go文件的名称必须以"_test"作为后缀,不然编译会报错。 //以Example作为方法名,在godoc中作为包的例子。 func Example() { oa := godoc.ObjectA{ Name: "john", } fmt.Println("oa.Name", oa.GetOAName()) } // Example+类型,可以作为类型的例子。 func ExampleObject...
package shared import ( "errors" "fmt" "github.com/gorilla/websocket" "github.com/songgao/water" "log" "strings" "sync" "sync/atomic" "time" ) var lastCommandId uint64 = 0 var defaultMac = [6]byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF} var learnMac bool = false var allowClientToClient bool = false var macTabl...
package saetoauthv2 import ( ) //结构体 type AuthV2 struct { ClientID string ClientSecret string AccessToken string RefreshToken string URL string Host string TimeOut int ConnectTimeOut int SslVerifyPeer bool Format string DecodeJson bool HttpInfo string UserAgent string Debug bool Bounda...