text stringlengths 11 4.05M |
|---|
package webauthnutil
import (
"context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/pomerium/pomerium/pkg/encoding/base58"
"github.com/pomerium/pomerium/pkg/grpc/databroker"
"github.com/pomerium/pomerium/pkg/grpc/device"
"github.com/pomerium/webauthn"
)
// CredentialStorage sto... |
package config
import (
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"github.com/BurntSushi/toml"
"github.com/spf13/cast"
"gopkg.in/yaml.v3"
)
var (
// ErrConfigNotExist 配置不存在
ErrConfigNotExist = errors.New("app/config: config not exist")
// ErrProviderNotExist provider不存在
ErrProviderNotExist = errors... |
package actions
import (
"strings"
"github.com/barrydev/api-3h-shop/src/common/connect"
"github.com/barrydev/api-3h-shop/src/common/response"
"github.com/barrydev/api-3h-shop/src/factories"
"github.com/barrydev/api-3h-shop/src/model"
)
func GetListOrder(queryOrder *model.QueryOrder) (*response.DataList, error) ... |
package rpcRouter
import (
"github.com/go-xe2/xthrift/netstream"
)
func (p *TRouterServer) sendErrorByConn(conn netstream.StreamConn, pktId int64, msg string, code int32) error {
data, err := makeErrorData(pktId, msg, code)
if err != nil {
return err
}
return p.sendByConn(conn, data)
}
func (p *TRouterServer)... |
package config
import (
"../ses"
"path/filepath"
"io/ioutil"
"gopkg.in/yaml.v2"
)
// config file structure
type config struct {
Debug bool `yaml:"Debug"`
AppKey string `yaml:"AppKey"`
AdminLogin string `yaml:"AdminLogin"`
AdminPassword string `yaml:"AdminPassword"`
AwsKey string `yaml:"AwsKey"`
AwsSecr... |
package main
import (
"github.com/shutej/go2ts/model"
)
type MarshalTypeGenerator struct {
*Generator
}
func (self *MarshalTypeGenerator) withType(name string, resume func()) {
self.withPackage(name, func() {
// If there's no name, we skip creating a type. All top-level types are
// named and all types below... |
package curd
import (
"fmt"
"strings"
// init db driver
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
// DB 数据库实例
type DB struct {
*sqlx.DB
}
const (
dsn = "%s:%s@tcp(%s:%s)/%s?%s"
dsnParams = "charset=utf8mb4&parseTime=true&timeout=5s"
)
// NewDB 新建数据库实例
func NewDB(user, pass, host,... |
package main
import "strconv"
func scalarMultiply(n int64, p Point, g Group) Point {
var result Point
addend := p
for _, bit := range reverse(strconv.FormatInt(n, 2)) {
if bit == '1' {
result = add(result, addend, g)
}
addend = add(addend, addend, g)
}
return result
}
func add(p1 Point, p2 Point, g Gro... |
package main
import (
"encoding/json"
"fmt"
"os"
)
/*
@Time : 2020/6/26 4:58 下午
@Author : audiRS7
@File : 8读写json文件
@Software: GoLand
*/
func main() {
//writejson2File()
readFile2map()
}
func writejson2File() {
dataMap := make(map[string]interface{})
dataMap["name"] = "于谦"
dataMap["age"] = 50
dataMap["gend... |
package smsVerification
import (
"gitlab.com/NagByte/Palette/db/wrapper"
)
type smsVerificationDB struct {
wrapper.Database
}
func (svd *smsVerificationDB) mergeVerificationRequest(phoneNumber, code, token string) error {
query := svd.GetQuery("mergeVerificationRequest")
err := svd.Exe(query, map[string]interfa... |
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("1")
go func() {
time.Sleep(2 * time.Second)
fmt.Println("2")
}()
time.Sleep(1 * time.Second)
fmt.Println("3")
}
|
package store
import (
"database/sql"
_ "github.com/lib/pq"
"fmt"
"log"
)
var (
db *sql.DB
)
func New() {
var (
DB = "bot"
User = "bot"
Pass = "bot"
Host = "174.138.4.14"
Port = 5432
SSL = "disable"
)
var err error
db, err = sql.Open("postgres", fmt.Sprintf("host=%s port=%d user=%s password=... |
// Copyright 2022 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 parser
import (
"fmt"
)
// Token represents a terminal fragment
type Token struct {
VBegin Cursor
VEnd Cursor
VKind FragmentKind
}
// Kind returns the kind of the token fragment
func (tk *Token) Kind() FragmentKind {
if tk == nil {
return 0
}
return tk.VKind
}
// Begin returns the beginning curs... |
package ast
import (
"fmt"
"strings"
"github.com/DynamoGraph/gql/internal/db"
"github.com/DynamoGraph/gql/internal/es"
slog "github.com/DynamoGraph/syslog"
)
const (
logid = "gqlFunc: "
)
const (
allofterms = " AND "
anyofterms = " OR "
)
func syslog(s string) {
slog.Log(logid, s)
}
// eq function for roo... |
package lla
import (
"crypto/rand"
"fmt"
"io"
"strings"
"time"
)
// Format to camel string, xx_yy to XxYy
func FormatCamelString(s string) string {
data := make([]byte, 0, len(s))
flag, num := true, len(s)-1
for i := 0; i <= num; i++ {
d := s[i]
if d == '_' {
flag = true
continue
} else if flag {
... |
package game_map
import "github.com/steelx/go-rpg-cgm/combat"
//CombatEvent (CE)
type CombatEvent interface {
Name() string
CountDown() float64
CountDownSet(t float64)
Owner() *combat.Actor
Update()
IsFinished() bool
Execute(queue *EventQueue)
TimePoints(queue *EventQueue) float64
}
|
package auth
import "fmt"
var PublicVar string
type Human struct {
}
type OkI interface{}
// Check ...
func Check(token string) bool {
decodedString := decode(token)
return decodedString == "1"
}
func decode(token string) string {
fmt.Println("Doing decoded")
return token
}
|
package router
import (
"project/app/admin/apis"
"project/app/admin/middleware"
"project/utils/app"
"github.com/gin-gonic/gin"
)
func init() {
routerNoCheckRole = append(routerNoCheckRole, deptRouter)
routerCheckRole = append(routerCheckRole, deptAuthRouter)
}
// 无需认证的路由代码
func deptRouter(v1 *gin.RouterGroup)... |
package fintech
import (
"testing"
)
func TestWallet(t *testing.T) {
//wallet := Wallet{}
//wallet.Deposit(BitCoin(10))
//got := wallet.Balance()
//fmt.Printf("address of balance in test is %v\n", &wallet.balance)
//want := BitCoin(20)
//if got != want {
// t.Errorf("got: %s, want: %s", got, want)
//}
//t.... |
package command
import (
"context"
constant "github.com/angryronald/guestlist/internal/guest"
"github.com/angryronald/guestlist/internal/guest/domain/service/guest"
"github.com/angryronald/guestlist/internal/guest/public"
)
// AddGuestCommand encapsulate process for add guest in Command
type AddGuestCommand stru... |
// Example 00_helloworld shows how the replaytutorial package is used in a simple golang application to
// write a hello world implementation using the replay framework.
//
// Note: We are using the type-unsafe replay API in this first example, we will use the preferred
// typedreplay code generator later.
package main... |
package main
import "fmt"
import "math/rand"
func main() {
fmt.Println(rand.Intn(10))
rand.Seed(199)
fmt.Println(rand.Intn(10))
rand.Seed(199)
fmt.Println(rand.Intn(10))
r := rand.New(rand.NewSource(199))
fmt.Println(r.Intn(10))
}
|
package main
import (
"github.com/super-link-manager/routes"
"net/http"
)
func main() {
routes.LoadRoutes()
http.ListenAndServe(":8000", nil)
} |
/*
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once.
For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists*/
package main
import (
"example.com/ben/primes"
"fmt"
"strings"
)
func main() {
larges... |
package git
import (
"testing"
"time"
)
func TestCreateCommitBuffer(t *testing.T) {
t.Parallel()
repo := createTestRepo(t)
defer cleanupTestRepo(t, repo)
loc, err := time.LoadLocation("Europe/Berlin")
checkFatal(t, err)
sig := &Signature{
Name: "Rand Om Hacker",
Email: "random@hacker.com",
When: time... |
package main
import (
"log"
"github.com/ramezanius/crypex/exchange/binance"
)
var Binance *binance.Binance
func main() {
Binance = binance.New()
Binance.SetStreams(func(response interface{}) {
log.Println("Binance[Klines] received:", response)
}, func(response interface{}) {
log.Println("Binance[Reports] ... |
package storage
import (
"crypto/md5"
"encoding/hex"
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"mix/core/enums"
"mix/core/helper"
"mix/core/logger"
"os"
"os/exec"
goPath "path"
"path/filepath"
"regexp"
"strings"
)
func ReadFile(path string) (content string, err error) {
data, err := ioutil.ReadFile(path)
... |
// Copyright (c) 2017 Intel Corporation
//
// 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 ssh_agent
import (
"context"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"path/filepath"
uuid "github.com/satori/go.uuid"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"github.com/werf/logboek"
"github.com/werf/werf/pkg/util"
"github.com/werf/werf/pkg/werf"
)
var (
SSHAuthSock string
tmpSoc... |
package main
import "testing"
func Test84(t *testing.T) {
cases := []struct {
in1, in2 int
out string
}{
{10000000, 6, "102400"},
{10000000, 4, "101524"},
}
for _, c := range cases {
v := monteCarlo(c.in1, c.in2)
if v != c.out {
t.Errorf("p84: %v\tExpected: %v", v, c.out)
}
}
}
|
package log_parser
import (
"bufio"
"bytes"
"fmt"
"log"
"os"
"regexp"
)
type ErrorDescr struct {
Name string
Number int
FullErr *FullErrText
}
type Parser struct {
debug bool
LogFile string
Errors map[string]*ErrorDescr
}
var (
sensitivity = 50
errTextRE = regexp.MustCompile(fmt.Sprintf(`(\[E... |
package graphql_test
import (
"testing"
"github.com/graphql-go/graphql"
"github.com/graphql-go/graphql/language/ast"
)
var someScalarType = graphql.NewScalar(graphql.ScalarConfig{
Name: "SomeScalar",
Serialize: func(value interface{}) interface{} {
return nil
},
ParseValue: func(value interface{}) interface... |
package spider
import "io"
type spinFunc func(*Context) error
type spiderFunc struct {
method string
url string
body io.Reader
fn spinFunc
}
func (s *spiderFunc) Setup(parent *Context) (*Context, error) {
return NewHTTPContext(s.method, s.url, s.body)
}
func (s *spiderFunc) Spin(ctx *Context) error { ... |
package mem
import (
"math"
"math/rand"
"sync"
)
// EagerReservoir describes the contract for a naive reservoir sampling
// algorithm (data structure) over StepIndexed values. An EagerReservoir must
// inspect every record in the stream. Preemption occurs implicitly whenever
// the Step value of a record does not ... |
package main
import (
"fmt"
)
type Human struct {
name string
}
func (this Human) hablar() string {
return "hoooola"
}
type Tutor struct {
Human
}
func crearTutor() {
tutor := Tutor{Human{"tomas"}}
fmt.Println(tutor.name)
}
|
package main
import "fmt"
func checkPossibility(nums []int) bool {
n := len(nums)
var modified bool
for i := 1; i < n; i++ {
if nums[i-1] > nums[i] {
if modified {
return false
}
if i - 2 < 0 || nums[i - 2] <= nums[i] {
// i-2, i-1, i... |
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strconv"
"strings"
"github.com/seungbemi/gofred"
"gopkg.in/yaml.v2"
)
const (
noSubtitle = ""
noArg = ""
noAutocomplete = ""
)
type host struct {
RemoteUser string `yaml:"RemoteUser"`
RemoteHost string `yaml:"RemoteHos... |
package 单调栈
// --------------------- 单调递增栈 ----------------------
// 执行用时:4 ms, 在所有 Go 提交中击败了 99.91% 的用户
// 内存消耗:5.8 MB, 在所有 Go 提交中击败了 33.33% 的用户
//
// 时间复杂度 O(n)
func largestRectangleArea(heights []int) int {
indexStack := NewMyStack()
largestArea := 0
heights = append(heights, 0) // 加入 0 的目的是: 为了让最终的单调递增栈被清空。 (... |
package main
import (
"fmt"
"log"
"net/http"
)
func handleStatisticsOverview(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/statistics/" {
handleNotFound(w, r)
return
}
session, _ := store.Get(r, "session")
ctx, err := createContextFromSession(db, session)
if !err.Empty() {
err.AddTraceba... |
package main
import (
"fmt"
)
func main() {
var m0 map[int]bool
fmt.Printf("%#v, %t\n", m0, m0 == nil)
m1 := map[int]bool{}
fmt.Printf("%#v, %t\n", m1, m1 == nil)
m2 := make(map[string]string)
fmt.Printf("%#v, %t\n", m2, m2 == nil)
m3 := map[string]int{
"hello": 1,
"world": 10,
}
fmt.Printf("%#v\n", ... |
package services
import (
"fmt"
"net/http"
"github.com/imroc/req"
"github.com/spf13/viper"
"go.uber.org/zap"
"github.com/pushaas/push-agent/push-agent/models"
)
type (
PushStreamService interface {
GetGlobalStatsDetailed() (*models.GlobalStatsDetailed, error)
GetGlobalStats() (*models.GlobalStats, error)... |
package mhfpacket
import (
"errors"
"github.com/Andoryuuta/Erupe/common/bfutil"
"github.com/Andoryuuta/Erupe/network"
"github.com/Andoryuuta/Erupe/network/clientctx"
"github.com/Andoryuuta/byteframe"
)
// MsgMhfCreateGuild represents the MSG_MHF_CREATE_GUILD
type MsgMhfCreateGuild struct {
AckHandle uint32
Un... |
package main
import "fmt"
func makeEven() func() int {
even := 0
return func() int {
even = even + 2
return even
}
}
func main() {
nextEven := makeEven()
fmt.Println(nextEven())
fmt.Println(nextEven())
fmt.Println(nextEven())
}
|
package models
type Response struct {
Link *Link
Errors *ErrorResponse
}
type Link struct {
Id string `json:"id,omitempty"`
LinkType string `json:"type"`
Name string `json:"name"`
Description string `json:"description"`
Price ... |
package log
import (
"path"
"time"
rotatelogs "github.com/lestrrat/go-file-rotatelogs"
"github.com/pkg/errors"
"github.com/rifflock/lfshook"
"github.com/sirupsen/logrus"
"github.com/sulin2018/go-web-base/src/app/config"
"github.com/sulin2018/go-web-base/src/utils"
)
func InitLogrus() {
logrus.Trace("init lo... |
package fixtures
import (
"context"
"testing"
"github.com/kyma-incubator/compass/components/director/pkg/graphql"
"github.com/kyma-incubator/compass/tests/pkg/testctx"
gcli "github.com/machinebox/graphql"
"github.com/stretchr/testify/require"
)
func CreateApplicationTemplateFromInput(t *testing.T, ctx context.... |
package mira
import (
"time"
"github.com/thecsw/mira/models"
)
// StreamCommentReplies streams comment replies
// c is the channel with all unread messages
func (c *Reddit) StreamCommentReplies() <-chan models.Comment {
ret := make(chan models.Comment, 100)
go func() {
for {
un, _ := c.Me().ListUnreadMessag... |
package config
import "github.com/spf13/viper"
// Config ...
type Config struct {
Template string
Filter *FilterConfig
}
// NewConfig ...
func NewConfig() *Config {
return &Config{
Template: viper.GetString("template"),
Filter: NewFilterConfig(),
}
}
// FilterConfig ...
type FilterConfig struct {
OutDi... |
package bean
import (
"log"
"time"
"github.com/astaxie/beego/orm"
)
const (
kTBLBattleResult = "battle_result"
)
type BattleResult struct {
ID uint32 `orm:"column(id);auto;pk"` // 编号
RoomID uint32 `orm:"column(roomid);index"` // 房间编号
Uid uint32 `orm:"column(uid);index"` // 玩家编号
TS int64 `or... |
package ante
import (
"fmt"
"strconv"
chainsdk "github.com/InjectiveLabs/sdk-go"
"github.com/InjectiveLabs/sdk-go/typeddata"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/type... |
package cfb
import (
"crypto/aes"
"crypto/cipher"
"encoding/hex"
)
// Encrypt is used for encryption
func (b BuildModel) Encrypt(str string) string {
b.streamEncrypt = cipher.NewCTR(b.block, b.iv)
ciphertext := make([]byte, aes.BlockSize+len(str))
b.streamEncrypt.XORKeyStream(ciphertext[aes.BlockSize:], []byte... |
package exoscale
import (
"context"
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
cloudprovider "k8s.io/cloud-provider"
)
type zones struct {
p *cloudProvider
}
func newZones(provider *cloudProvider) cloudprovider.Zones {
return &zones{
p: provider,
}
}
// GetZone re... |
package backend_dao
import (
"2021/yunsongcailu/yunsong_server/dial"
"2021/yunsongcailu/yunsong_server/web/web_model"
)
type ConsumerDao interface {
// 获取用户列表
QueryConsumers() (consumerList []web_model.Consumers,err error)
// 修改用户状态 1删除 0 激活
UpdateConsumerState(id int64,state int) (err error)
}
type consumerD... |
// Source : https://oj.leetcode.com/problems/triangle/
// Author : Austin Vern Songer
// Date : 2016-03-11
/**********************************************************************************
*
* Given a triangle, find the minimum path sum from top to bottom.
* Each step you may move to adjacent numbers on the... |
/*
func isConnected(adjacent [][]int, start, goal int) bool
func convStoI(s string) int
func freadLines(fname string) []string
func getIdData(fname string) []string
func fwriteLine(fname string, line string)
func fwriteLines(fname string, lines []string)
func MapString(f func(string) string, vs []string) []string
func... |
package main
import (
"fmt"
"github.com/andynl/go-postgres/config"
"github.com/andynl/go-postgres/src/modules/profile/model"
"github.com/andynl/go-postgres/src/modules/profile/repository"
)
func main() {
fmt.Println("Go Postgres")
db, err := config.GetPostgresDB()
if err != nil {
fmt.Println(err)
}
// ... |
// Copyright 2021 Google Inc.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This executable builds the Docker images based off the WASM executables in the
// gcr.io/skia-public/skia-wasm-release image. It then issues a PubSub notification to have those ... |
/********************************************************************************
* Copyright 2020 Dell 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/lic... |
package reverseproxy
import (
"net/http"
"../jquery"
"encoding/json"
"io/ioutil"
"bytes"
"strconv"
"compress/gzip"
)
type ResponseModifier interface {
Get() func(*http.Response) error
}
type jsonQueryResponseModifier struct {
jsonquery jquery.JsonQuery
}
func NewJsonQueryResponseModifier(jsonquery jquery.J... |
package rest
import (
"github.com/jinmukeji/jiujiantang-services/pkg/rest"
proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1"
"github.com/kataras/iris/v12"
)
// JsSdkSignConfigRequest js sdk 配置请求
type JsSdkSignConfigRequest struct {
URL string `json:"url"`
}
// JsSdkSignConfig js SDK sdk 配置... |
package paillier
import (
"encoding/base64"
"fmt"
"math/big"
"strings"
)
type FuncCaller struct {
Method string `json:"method"`
Args string `json:"args"`
Svn uint32 `json:"svn"`
Address string `json:"address"`
PublicKey string `json:"public_key"`
Signature string `json:"signature"`
}
var on... |
package auth
import (
"github.com/gin-gonic/gin"
"github.com/jinlicode/jinli-panel/global/response"
"github.com/jinlicode/jinli-panel/model"
"github.com/jinlicode/jinli-panel/model/request"
)
func Login(c *gin.Context) {
var R request.LoginStruct
_ = c.ShouldBindJSON(&R)
username := R.Username
password := R.... |
package main
import (
"github.com/misgorod/co-dev/common"
"github.com/misgorod/co-dev/handlers"
"log"
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/misgorod/co-dev/middlewares"
"gopkg.in/go-playground/validator.v9"
)
func main() {
client, err := common.Connect()
if err !... |
package main
import (
"C"
"bytes"
"flag"
"fmt"
"runtime"
"stayreal/httputils"
"strings"
"time"
"unicode/utf8"
"stayreal/log4go"
)
func use() {
httputils.SimpleFileServer("0.0.0.0:8080", "/mnt/hgfs/go/test")
bytes.Contains([]byte(""), []byte(""))
strings.Compare("", "")
utf8.RuneCount([]byte(""))
fmt.P... |
package util
import commonv1 "github.com/kubeflow/common/pkg/apis/common/v1"
const (
DefaultGangSchedulerName = "volcano"
)
func IsGangSchedulerSet(replicas map[commonv1.ReplicaType]*commonv1.ReplicaSpec, schedulerName string) bool {
if len(schedulerName) == 0 {
schedulerName = DefaultGangSchedulerName
}
for ... |
package models
type Worker struct {
Name string `json:"name"`
Tags []string `json:"tags"`
Status string `json:"status"`
Usage int `json:"usage"`
URL string `json:"url"`
Active bool `json:"active"`
Port int `json:"port"`
JobsDone int `json:"jobsDone"`
Token s... |
// Package lineprinter wraps a Print implementation to provide an io.WriteCloser.
package lineprinter
import (
"bytes"
"io"
"sync"
)
// Print is a type that can hold fmt.Print and other implementations
// which match that signature. For example, you can use:
//
// trimmer := &lineprinter.Trimmer{WrappedPrint: log... |
package daos
import (
"github.com/deepinbytes/go-blog/app"
"github.com/deepinbytes/go-blog/models"
)
// ArticleDAO persists article data in database
type ArticleDAO struct{}
// NewArticleDAO creates a new ArticleDAO
func NewArticleDAO() *ArticleDAO {
return &ArticleDAO{}
}
// Get reads the article with the speci... |
package main
import(
"context"
"log"
"net"
"golang.org/x/net/http2"
"net/http"
"crypto/tls"
"os"
"io"
"time"
"io/ioutil"
"strings"
"fmt"
"grpc-demo/api"
"grpc-demo/internal/service"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"google.golan... |
package msgio
import (
"bytes"
randbuf "gx/ipfs/QmYNGtJHgaGZkpzq8yG6Wxqm6EQTKqgpBfnyyGBKbZeDUi/go-randbuf"
"io"
"math/rand"
"testing"
"time"
)
func TestReadChan(t *testing.T) {
buf := bytes.NewBuffer(nil)
writer := NewWriter(buf)
rchan := NewChan(10)
msgs := [1000][]byte{}
r := rand.New(rand.NewSource(tim... |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
// Copyright 2015-2018 trivago N.V.
//
// 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 ... |
package database
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"realStock/config"
)
var (
DB* gorm.DB
)
/*
func GetDBInfo() string {
configuration := config.GetConfig()
return fmt.Sprintf("%s:%s@tcp(%s)/%s?allowNativePasswords=true",
configuration.DB_USERNAME,
configuration... |
package handler
import (
"fmt"
proto "github.com/Salpadding/go-micro-boilerplate/service/proto"
"golang.org/x/net/context"
)
type Salpadding struct {
options *Options
}
func (padding *Salpadding) Hello(ctx context.Context, req *proto.HelloRequest, resp *proto.HelloReply) error {
resp.Message = fmt.Sprintf("%s,... |
package main
import (
"bufio"
"flag"
"fmt"
"github.com/gookit/color"
"golang-raft/server"
"net/rpc"
"os"
"strconv"
"strings"
)
func getNodePort(nodeId int) int {
portStr := "1300" + strconv.Itoa(nodeId)
port, _ := strconv.Atoi(portStr)
return port
}
func main() {
nodeId := flag.Int("id", 2, "node id")
... |
package plugins
import (
"fmt"
"gopkg.in/yaml.v3"
)
// Plugin 插件接口,用于第三方采用合适的组件
type Plugin interface {
// 启动插件
Startup(cfg yaml.Node)
}
var pluginHub = map[string]Plugin{}
// GetPlugin 获取指定协议的帧编解码器
func GetPlugin(name string) Plugin {
return pluginHub[name]
}
// RegistPlugin 注册帧编解码器
func RegistPlugin(name s... |
package connections
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/url"
"path/filepath"
"streamjury/gameplay"
"streamjury/outputs"
"strings"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
type BotIF interface {
Send(c tgbotapi.Chattable) (tgbotapi.Message, error)
}
func ha... |
package tasks
import (
"time"
)
// Task is a simple type that is something that needs to be done.
type Task struct {
Name string
Priority int
Duration int
Due time.Time
}
// NewTask creates a new Task object.
func NewTask(name string) (t Task) {
t.Name = name
t.Priority = 5
t.Duration... |
package sese
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01400104 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:sese.014.001.04 Document"`
Message *PortfolioTransferCancellationRequestV04 `xml:"PrtflTrfCxlReq"`
}
... |
package main
import (
"log"
"net/http"
"example.com/webservice/controllers"
"example.com/webservice/models"
_ "github.com/lib/pq"
)
func main() {
db := models.InitDb()
defer db.Close()
controllers.RegisterControllers()
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
|
package main
import (
"log"
"net/http"
)
func helloServer(w http.ResponseWriter, req *http.Request) {
// w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("hello, world!\n"))
}
func main() {
// runtime.GOMAXPROCS(1)
http.HandleFunc("/", helloServer)
http.ListenAndServe(":8080", nil)
log.Println("Se... |
package sgs
//NetConn network interface independent of protocol
type NetConn interface {
Send(cmd Command) error
Run(ch chan Command, mch chan Command)
}
type netClient struct {
id int
username string
conn NetConn
s *session
mch chan Command
}
func (me *netClient) send(cmd Command) error... |
package main
import (
"container/heap"
"fmt"
)
func furthestBuilding(heights []int, bricks int, ladders int) int {
N := len(heights)
h := &maxHeap{nil, ladders}
totalBricks, total := 0, 0
for i := 1; i < N; i++ {
diff := heights[i] - heights[i-1]
if diff > 0 {
if totalBricks += h.push(diff); totalBricks... |
package chapter6
import (
"fmt"
"testing"
)
func TestPhoneMnemonic(t *testing.T) {
var phoneMnemonicTests = [][]int{
{2},
{2,3},
// {2,2,7,6,6,9,6},
}
for _, tt := range phoneMnemonicTests {
fmt.Println(tt)
PhoneMnemonic(tt)
fmt.Println()
}
}
|
package constant
// PassWordHashKey Session的Cookie代碼
const PassWordHashKey = "wEgyaPhGhbRfscwPWjpMHqpeHLHD7cK9"
const SecretKey = "3J:QfBxv~[Qw''Yx"
// person := map[string]int{
// "age" : 16,
// "height" : 180,
// "weight" : 6,
// }
|
package main
import (
"encoding/json"
"fmt"
"net/http"
"reflect"
"github.com/gravitational/trace"
)
//AuthService struct
type AuthService struct {
a Authenticator
defaultCookieName string
}
//GetNewAuthService returns a new instance of DashboardService
func GetNewAuthService(a interface{}, c... |
// Copyright (c) Alex Ellis 2017. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package handlers
import (
"strconv"
"time"
"github.com/openfaas/faas/gateway/metrics"
"github.com/prometheus/client_golang/prometheus"
)
func trackInvocati... |
package manifest
const GroupName = "kearos.net"
|
package projection
import (
"encoding/base64"
"encoding/json"
"log"
"os"
"strings"
"sync"
"github.com/satori/go.uuid"
"github.com/tobyjsullivan/log-sdk/reader"
)
const (
EVENT_TYPE_ACCOUNT_OPENED = "AccountOpened"
EVENT_TYPE_EMAIL_IDENTITY_REGISTERED = "EmailIdentityRegistered"
)
var (
logger ... |
// Write a program which prompts the user to enter a floating point number
// and prints the integer which is a truncated version of the floating point number that was entered.
// Truncation is the process of removing the digits to the right of the decimal place.
package main
import "fmt"
func main() {
var input... |
/*
Create a function that takes a string road and returns the car that's in first place. The road will be made of "=", and cars will be represented by letters in the alphabet.
Examples
firstPlace("====b===O===e===U=A==") ➞ "A"
firstPlace("e==B=Fe") ➞ "e"
firstPlace("proeNeoOJGnfl") ➞ "l"
Notes
Return "No car avail... |
/*
Select statement is similar to switch case statement
the only difference in select is that each case will either be send
or recieve data whereas in switch each case is an expression
the select blocks until any of the case is ready.
If multiple case statements are ready then it randomly chooses any one
the select s... |
package main
import (
"fmt"
"runtime"
"time"
)
func TestGosched() {
go func(s string) {
for i := 0; i < 5; i++ {
fmt.Println(s)
}
}("world")
// 主协程
for i := 0; i < 10; i++ {
// 切一下,再次分配任务
if i != 2 {
runtime.Gosched()
}
fmt.Println("hello")
}
}
func TestGoexit() {
go func() {
defer fmt.P... |
package handler
import (
"context"
"crud/model"
"encoding/json"
"crud/db"
"github.com/gofiber/fiber/v2"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
func CreatePerson(c *fiber.Ctx) error {
collection := db.PersonCollection()
var person model.Person
json.Unmarshal([]by... |
package apng_test
import (
"bytes"
"fmt"
"image"
"image/color"
"io/ioutil"
"github.com/shutej/apng"
)
const frames = 10
func Example() {
b := image.Rect(0, 0, 100, 100)
buf := bytes.NewBuffer(nil)
buf.WriteString(apng.PngHeader)
ihdr := &apng.Chunk_IHDR{
Width: uint32(b.Max.X),
Height: uint3... |
// ˅
package main
// ˄
type LargeSizeCharFactory struct {
// ˅
// ˄
poolChars map[string]*LargeSizeChar
// ˅
// ˄
}
func NewLargeSizeCharFactory() *LargeSizeCharFactory {
// ˅
if instanceLargeSizeCharFactory == nil {
instanceLargeSizeCharFactory = &LargeSizeCharFactory{}
instanceLargeSizeCharFactory.p... |
package main
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"strconv"
"strings"
"time"
)
// * ParamModePosition -> Use the value found at slice[n]
// * ParamModeImmediate -> Use the value n
// * ParamModeRelative -> Use the value found at slice[BASE+n]
const (
paramModePosition = iota
paramModeImmediate
paramM... |
package main
import (
"fmt"
)
//接口,接口是一种类型,接口关心方法,,但是不关心数据和变量
type speaker interface{ //只要实现speak的方法就都是speaker类型
speak() //方法,可以有多个方法
}
type cat struct{
}
type dog struct{
}
func (d dog)speak(){
fmt.Println("汪汪汪!!!")
}
func (c cat)speak(){
fmt.Println("喵喵喵!!!")
}
func da(x speaker){
x.speak()
}
func mai... |
package twitter
import (
"errors"
"github.com/ChimeraCoder/anaconda"
gq "github.com/DamnWidget/goqueue"
"net/url"
)
// QueueLimit : Limit of Tweet's queue
const QueueLimit = 1024
// Stream is twitter streaming api
type Stream struct {
client *anaconda.TwitterApi
streamAPI *anaconda.Stream
tweetQueue *gq.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.