text stringlengths 11 4.05M |
|---|
package doorman
import (
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"log"
"math"
"math/big"
mathrand "math/rand"
"net/http"
"sync"
"time"
"github.com/dchest/siphash"
"github.com/didiercrunch/doorman/shared"
)
var ONE *big.Rat = big.NewRat(1, 1)
var rand *mathrand.Rand
func initRandom... |
package v1
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"k8s.io/client-go/tools/clientcmd"
"testing"
)
func TestPods_Exec(t *testing.T) {
c, err := clientcmd.BuildConfigFromKubeconfigGetter("", KubeConfigGetter)
if err != nil {
t.Fatal(err)
}
client, _ := NewForConfig(c)
ctx, cancel := context.WithCancel... |
package main
import (
"encoding/gob"
"fmt"
"log"
"strconv"
"time"
"github.com/patrickmn/go-cache"
"github.com/zgs225/youdao"
)
const (
CACHE_EXPIRES time.Duration = 30 * 24 * time.Hour
CACHE_FILE string = "cache.dat"
CACHE_HISTORY_FILE string = "history.dat" // Local cache file f... |
// Copyright 2021 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applica... |
package service
import (
"fmt"
"log"
"net/rpc"
"sync"
"../config"
)
// TODO
// - Add timeout for dead machines
// Client for querying logs
func Client(expressionPtr *string) {
logs := make(chan string)
var wg sync.WaitGroup
addresses, err := config.Addresses()
if err != nil {
log.Fatal(err)
}
fmt.Pri... |
package Problem0467
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
// tcs is testcase slice
var tcs = []struct {
p string
ans int
}{
{
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvw... |
package writer
import "github.com/efark/data-receiver/logger"
var log, slog = logger.GetLogger()
|
package x
// GENERATED BY XO. DO NOT EDIT.
import (
"errors"
"strings"
//"time"
"ms/sun/shared/helper"
"strconv"
"github.com/jmoiron/sqlx"
)
// (shortname .TableNameGo "err" "res" "sqlstr" "db" "XOLog") -}}//(schema .Schema .Table.TableName) -}}// .TableNameGo}}// PushChat represents a row from 'sun_push.push_... |
package cryhel_test
import (
"testing"
. "gopkg.in/check.v1"
"github.com/qeek-dev/cryhel"
)
func Test(t *testing.T) { TestingT(t) }
type MySuite struct {
c *cryhel.Crypto
}
func (s *MySuite) SetUpTest(c *C) {
s.c, _ = cryhel.NewCrypto("AES256Key-32Characters1234567890")
}
var _ = Suite(&MySuite{})
func (s ... |
package main
import (
"flag"
"log"
"net/http"
"os"
//if this is not being picked up make sure all referenced package files have no errors
//if they have errors GOLand will not pull in mod reference correctly
snippets "github.com/chriswilliams1977/protos/internal/app/snippets"
)
func main(){
//NOTE EACH REQUE... |
package Core
type RecordRow struct {
values map[int]interface{}
}
func NewDataRow() *RecordRow {
v := &RecordRow{values: make(map[int]interface{})}
return v
}
func (row *RecordRow) SetValue(index int, value interface{}) {
row.values[index] = value
}
func (row *RecordRow) GetInt(index int) int {
i := row.values[i... |
package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"log"
"net"
"os"
"strings"
"time"
"golang.org/x/crypto/ssh"
)
type sshConfig struct {
User, Password, Host string
}
type configuration struct {
Hosts []sshConfig
}
type cmdTask struct {
cmd string
host net.Addr
}
var (
cfg configuratio... |
package mts
import (
"encoding/json"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/services/mts"
"log"
"net/url"
"os"
"sync"
)
var (
regionId = "<regionId>"
bucket = "<bucket>"
location ... |
// robustirc-merge-coverage is a tool to merge two coverage reports, summing
// their counters.
//
// See coverage.sh for how to use it.
package main
import (
"bufio"
"flag"
"fmt"
"log"
"os"
"strings"
)
var (
inputName = flag.String("input",
"",
"comma-separated list of paths to input files to read")
outp... |
package intersect
import (
"sort"
"github.com/dgraph-io/dgraph/task"
)
func IntersectWith(u, v *task.List) {
n := len(u.Uids)
m := len(v.Uids)
if n > m {
n, m = m, n
}
if n == 0 {
n += 1
}
// Select appropriate function based on heuristics.
ratio := float64(m) / float64(n)
if ratio < 100 {
Intersec... |
package ping
import (
scrap "github.com/zairza-cetb/bench-routes/src/lib/filters/scraps"
"github.com/zairza-cetb/bench-routes/src/lib/utils"
"github.com/zairza-cetb/bench-routes/tsdb"
"log"
"sync"
"time"
)
// const (
// // PathPing stores the defualt address of storage directory of ping data
// PathPing = "st... |
package main
import (
"calc"
"fmt"
//만약 패키지 디렉터리가 GOPATH/src/hello/calc라면 다음과 같이 사용합니다.
//즉 기준이 되는 디렉터리는 GOPATH/src입니다.용
//"hello/calc"
)
func main() {
fmt.Println("hello, word!")
fmt.Println(calc.Sum(1, 2)) // calc 패키지의 Sum 함수 사용
}
|
package kubectl
import (
"strings"
"github.com/pkg/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/kubernetes/scheme"
restclient "k8s.io/client-go/rest"
)
// GenericRequestOptions are the options for the request
type GenericRequestOptions struct ... |
package main
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"log"
"time"
)
//密钥 key
const (
SIGNED_KEY = "7d8b0b1a8e2746ec9b32eddd1aa9acc2"
)
// 载荷,可以加一些自己需要的信息
type CustomClaims struct {
OpenId string `json:"open_id"`
Name string `json:"name"`
Email string `json:"email"`
Administrator... |
// Copyright 2023 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applica... |
package middleware
import (
"net/http"
)
type DefaultMiddleware struct {
http.ServeMux
middleware []func(next http.Handler) http.Handler
}
func (dm *DefaultMiddleware) CORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Al... |
// Copyright 2019 Yunion
//
// 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 writi... |
// Copyright (C) 2018 Storj Labs, Inc.
// See LICENSE for copying information.
package main
import (
"os"
"github.com/minio/minio/cmd"
_ "storj.io/storj/pkg/miniogw"
)
func main() { cmd.Main(os.Args) }
|
package paizaio
type APIError struct {
Body string
}
func newAPIError(body string) *APIError {
return &APIError{Body: body}
}
func (a *APIError) Error() string {
return a.Body
}
var _ error = &APIError{}
|
package loader
import (
"github.com/raphael-trzpit/sandgo/model"
"github.com/raphael-trzpit/sandgo/repository"
)
// User is a user loader.
type User struct {
r repository.User
}
// NewUser create a new User Loader from a given repository
func NewUser(r repository.User) *User {
l := new(User)
l.r = r
return l
}... |
package main
import (
"fmt"
s "strings"
)
var p = fmt.Println
func main() {
p("Contains: ", s.Contains("test", "es"))
p("Count: ", s.Count("test", "t"))
// การตรวจสอบว่า test ขึ้นต้นด้วย te หรือไม่
p("HasPerfix: ", s.HasPrefix("test", "te"))
// การตรวจสอบว่า test ลงท้ายด้วย e หรือไม่
p("HasSuffix: ", s.HasSu... |
package ondemand
import (
"fmt"
"strings"
)
// Quote https://www.barchart.com/ondemand/api/getQuote
type Quote struct {
Results []struct {
Symbol string `json:"symbol"`
Name string `json:"name"`
DayCode string `json:"dayCode"`
ServerTimestamp ... |
package libvirt
// Platform stores all the global configuration that all
// machinesets use.
type Platform struct {
// URI is the identifier for the libvirtd connection. It must be
// reachable from both the host (where the installer is run) and the
// cluster (where the cluster-API controller pod will be running)... |
package main
import (
ospaf "../"
github "../../github"
"encoding/json"
"fmt"
)
func main() {
pool, err := ospaf.InitPool()
if err != nil {
fmt.Println(err)
return
}
owner := "opencontainers"
repo := "specs"
url := fmt.Sprintf("https://api.github.com/repos/%s/%s/issues/20/comments", owner, repo)
for p... |
package main
import (
"flag"
"fmt"
"io"
"net"
"os"
"runtime"
log_ "log"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
type ReadWriteLogger struct {
io.ReadWriter
Log func() *zerolog.Event
Hex bool
}
func (rwl ReadWriteLogger) Write(b []byte) (int, error) {
n, err := rwl.ReadWriter.Write(b)
if... |
func partitionLabels(S string) []int {
mapping := make(map[byte] int, 26)
for i := 0; i < len(S); i++ {
mapping[S[i]] = i
}
result := [] int {}
max := 0
for i := 0; i < len(S); {
max = compareMax(max, mapping[S[i]])
for j := i + 1; j <= max; j... |
package tmpl3
func binarySearch(nums []int, target int) int {
if len(nums) == 0 {
return -1
}
left, right := 0, len(nums)-1
for left+1 < right {
// Prevent (left + right) overflow
mid := left + (right-left)/2
if nums[mid] == target {
return mid
} else if nums[mid] < target {
left = mid
} else {
... |
//go:build debug
// +build debug
package main
import (
"fmt"
)
// describeCommands is a debugging function that prints out all commands.
// This is normally never called, but we keep this implemented as it is useful
// for debugging.
func describeCommands() {
handlerNames := make(map[string]string)
handlerNames[f... |
package BinaryTreeHashMap
import "Pair"
var INITIAL_CAPACITY = 1 << 5
var THRESHOLD_MAX float32 = 1
var THRESHOLD_MIN float32 = 0.2
var GROW_SHIFT = 2
type BinaryTreeHashMap struct {
entries []*Node
Size int
}
type Node struct {
pair Pair.Pair
left *Node
right *Node
}
func createByCapacity(capacity int) Binar... |
package chain
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSetIsIn(t *testing.T) {
tests := []struct {
name string
setInit map[string]bool
search string
expected bool
}{
{
"should be present",
map[string]bool{"work": true},
"work",
true,
},
{
"should not ... |
package test
import (
"testing"
"github.com/kohge4/go-rakutenapi/rakuten"
"github.com/stretchr/testify/assert"
)
func TestKoboGenre(t *testing.T) {
params := &rakuten.KoboGenreParams{
KoboGenreID: 101912005001,
}
_, _, err := client.Kobo.GenreSearch(ctx, params)
assert.Nil(t, err)
}
func TestKoboEbooks(t ... |
package ids_db
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/rezwanul-haque/ID-Service/src/utils/helpers"
"github.com/rezwanul-haque/ID-Service/src/logger"
)
var (
Client *sql.DB
username = helpers.GoDotEnvVariable("MYSQL_IDS_USERNAME")
password = helpers.GoDotEnvVariable("MYS... |
package order
import (
"wx-gin-master/models"
"wx-gin-master/models/wallet"
"wx-gin-master/pkg/logging"
)
type Order struct {
models.Model
UserId int `json:"user_id"` // 用户id
//ProvinceName string `json:"province_name"` // 省份
//CityName string `json:"city_name"` // 城市
//CountyName string `json:"c... |
package pool
import (
"crawler/errors"
"crawler/logger"
"crawler/models"
"net/http"
)
var transport = &http.Transport{DisableKeepAlives: true}
var client = &http.Client{Transport: transport}
type ChannelPages chan *models.Page
var (
Throttle = NewThrottle()
Storage = NewStorage()
)
func StartTask(body strin... |
package package1
import "strconv"
//zad 1
func Suma(a, b int) int {
return a + b
}
//zad 2
func Concatenate(s1, s2 []int) []int {
return append(s1, s2...)
}
//zad 3
func Is18(age int) bool {
if age >= 18 {
return true
} else {
return false
}
}
//zad 4
func PrintDividedBy4(n int) []int {
m := n
s1 := []i... |
// This file was generated for SObject FiscalYearSettings, API Version v43.0 at 2018-07-30 03:47:50.328372034 -0400 EDT m=+36.672354515
package sobjects
import (
"fmt"
"strings"
)
type FiscalYearSettings struct {
BaseSObject
Description string `force:",omitempty"`
EndDate string `force:",omite... |
package atypes
type AInt []int
func (ai AInt) Len() int { return len(ai) }
func (ai AInt) Less(i, j int) bool { return ai[i] < ai[j] }
func (ai AInt) Swap(i, j int) { ai[i], ai[j] = ai[j], ai[i] }
func (ai AInt) Get(i int) interface{} { return ai[i] }
func (ai AInt) LessD(i, j interface{}) bool... |
package main
import (
"fmt"
"time"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/client-go/tools/cache"
"congwang.com/learnGo/k8s-client-go-examples/common"
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
)
func main() {
var (
clientset *kubernetes.Clientset
err error
)
// init k8s client
if ... |
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println("Circle Area Calculation")
fmt.Println("Enter a Radius Value: ")
var radius float64
fmt.Scanf("%f", &radius)
area := math.Pi * math.Pow(radius,2)
fmt.Printf("Area of a circle with a radius of %.2f = %.2f \n", radius, area)
}
|
package orm
import (
"database/sql"
"errors"
"reflect"
)
// result is a pointer (eg. &[]struct or &[]*struct)
// return affected rows
func Scan(rows *sql.Rows, result interface{}) (int64, error) {
if rows == nil {
return 0, errors.New("rows can't be nil")
}
if result == nil {
return 0, errors.New("result c... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//462. Minimum Moves to Equal Array Elements II
//Given a non-empty integer array, find the minimum number of moves required to make all array elements... |
package main
import (
"context"
"fmt"
"net/http"
"os"
"path"
"sync"
"github.com/docker/docker/api/types"
docker "github.com/docker/docker/client"
"github.com/gorilla/websocket"
"github.com/ubclaunchpad/inertia/daemon/inertiad/auth"
"github.com/ubclaunchpad/inertia/daemon/inertiad/crypto"
"github.com/ubcla... |
/*
Package skipList provide an implementation of skip list. But is not thread-safe in concurrency.
*/
package skipList
import (
"math/rand"
"github.com/OneOfOne/xxhash"
)
// Comes from redis's implementation.
// Also you can see more detail in William Pugh's paper <Skip Lists: A Probabilistic Alternative to Balanc... |
func longestCommonPrefix(strs []string) string {
if len(strs) == 1 {
return strs[0]
}
if len(strs) == 0 {
return ""
}
superMap := make(map[int]map[int]string)
tempStr2 := strs[0]
allSingleChar := 0
for i := 0; i < len(strs); i++ {
if strs[i] == "" {
return ""
}
if tempStr2 != strs[i] {
allSin... |
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
var connStr = "user=postgres password=1 dbname=productdb sslmode=disable"
//Phone ...
type Phone struct {
ID int
Model string
Company string
Price int
}
func main() {
db, err := sql.Open("postgres", connStr)
if err != nil {
pani... |
package main
import (
"context"
"io"
"os"
"github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter7/oauthstore"
"golang.org/x/oauth2"
"golang.org/x/oauth2/github"
)
func main() {
conf := oauthstore.Config{
Config: &oauth2.Config{
ClientID: os.Getenv("GITHUB_CLIENT"),
ClientSecre... |
package main
import (
"fmt"
)
func main() {
f := func(s string) int {
return len(s)
}
fmt.Println(f("hello world"))
fmt.Println(funcStringIntUser(f))
}
func funcStringIntUser(f func(string) int) string {
return fmt.Sprintf("function return value is %d", f("test"))
}
|
package slice
import (
"fmt"
"testing"
"time"
)
func TestNew(t *testing.T) {
s := New(2)
s.PushBack(1)
s.PushBack(2)
s.PushBack(3)
s.PushBack(3)
s.PushBack(3)
fmt.Println(s, s.len, s.cap)
s.Put(3, 4)
s.Put(4, 5)
fmt.Println(s, s.len, s.cap)
//s.Put(5, 1)
}
func TestCostTime(t *testing.T) {
const Be... |
package middlewares
import (
"fmt"
"net/http"
"time"
apiResponse "github.com/alexhornbake/go-crud-api/lib/api_response"
sql "github.com/alexhornbake/go-crud-api/lib/datastore"
log "github.com/alexhornbake/go-crud-api/lib/logging"
)
func LoggingHandler(next http.Handler) http.Handler {
return http.HandlerFunc(... |
// Package nutanix collects Nutanix-specific configuration.
package nutanix
import (
"context"
"fmt"
"sort"
"strconv"
"time"
"github.com/AlecAivazis/survey/v2"
nutanixclient "github.com/nutanix-cloud-native/prism-go-client"
nutanixclientv3 "github.com/nutanix-cloud-native/prism-go-client/v3"
"github.com/pkg/... |
package nonblocking
import (
"database/sql"
"log"
"sync"
_ "github.com/go-sql-driver/mysql"
)
type Planner struct {
plannerID int
connectionPool *ConnectionPool
waitGroup *sync.WaitGroup
chunkSize int
}
// NewPlanner
func NewPlanner(plannerID int, connectionPool *ConnectionPool, waitGroup *sy... |
package server
import (
"github.com/jchavannes/jgo/web"
"github.com/jchavannes/money/app/auth"
"github.com/jchavannes/money/app/chart"
"net/http"
)
const (
FormInputSymbol = "symbol"
FormInputMarket = "market"
)
var individualChartsRoute = web.Route{
Pattern: UrlIndividual,
NeedsLogin: true,
Handler: fun... |
package key
import (
"os"
"path"
"testing"
kyber "github.com/drand/kyber"
"github.com/drand/kyber/share"
"github.com/stretchr/testify/require"
)
func TestKeysSaveLoad(t *testing.T) {
n := 4
ps, group := BatchIdentities(n)
tmp := os.TempDir()
tmp = path.Join(tmp, "drand-key")
os.RemoveAll(tmp)
defer os.Re... |
package cmd
import (
"bytes"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"os"
)
const (
magicBytes = "\x80sabakan-cryptsetup2"
maxCipherName = 106
idLength = 16
metadataSize = 2 * 1024 * 1024
)
// Pre-defined errors
var (
ErrNotFound = errors.New("not found")
)
// Metadata represents metadata bl... |
package logic
import (
"bytes"
"copyto/logic/internal/sys"
"fmt"
"github.com/gookit/color"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"io"
"os"
"testing"
)
type mockprn struct {
w *bytes.Buffer
}
func (m *mockprn) String() string {
return m.w.String()
}
func newMockPrn() *mockprn {
re... |
// This file was generated for SObject EventLogFile, API Version v43.0 at 2018-07-30 03:47:24.579447617 -0400 EDT m=+10.922463897
package sobjects
import (
"fmt"
"strings"
)
type EventLogFile struct {
BaseSObject
ApiVersion float64 `force:",omitempty"`
CreatedById string `force:",omitempty"`
Cr... |
package database
import (
_ "unsafe"
"context"
"database/sql"
. "github.com/agiledragon/gomonkey"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"reflect"
"testing"
)
// pg_sql.(*Tx).Rollback 被内联, 无法打桩, 需要对私有方法打桩
//go:linkname rollbackFn database/pg_sql.(*Tx).rollback... |
/******************************************************************************
Online Go Lang Compiler.
Code, Compile, Run and Debug Go Lang program online.
Write your code in this editor and press "Run" button to execute it.
***********************************************... |
package main
import (
"bufio"
"fmt"
"log"
"os"
"regexp"
"strings"
)
func main() {
url := ""
// Get and validate package URL
fmt.Print("Enter the BoneTome page URL here (https://bonetome.com/h3vr/mods/id): ")
reader := bufio.NewReader(os.Stdin)
line, _, _ := reader.ReadLine()
url = string(line)
verifyUrlF... |
package handler
import (
"context"
"fmt"
"time"
"github.com/jinmukeji/jiujiantang-services/service/auth"
"github.com/jinmukeji/jiujiantang-services/service/mysqldb"
"github.com/golang/protobuf/ptypes"
proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1"
)
// GetWxmpTempQrCodeUrl 得到微信临时二维... |
package main
const (
UNLOCK_EMAIL_SUBJECT = "Petebot unlock code"
UNLOCK_EMAIL_BODY = `Dearest Petebot user,
Thank you so much for donating to {charity}.
Your unlock code is {code}
You can unlock your account by returning to slack and typing:
@petebot unlock 123456 <--- replace that with your code
Happy... |
package leetcode
import "math"
/*You are given K eggs, and you have access to a building with N floors from 1 to N.
Each egg is identical in function, and if an egg breaks, you cannot drop it again.
You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor higher than F will break, ... |
package main
import (
"fmt"
"github.com/xiak/k8s/pkg/ssh"
)
func main() {
//command := cmd.NewDefaultClusterCommand()
//if err := command.Execute(); err != nil {
// fmt.Fprintf(os.Stderr, "%v\n", err)
// os.Exit(1)
//}
s, err := ssh.NewSSHTunnel("10.xx.xx.xx", "root", "password")
if err != nil {
fmt.Errorf... |
// Copyright 2015 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 workerpool
import "sync"
type WorkerPool struct {
maxWorkerNumber int
workers []*Worker
objectPool *sync.Pool
}
type Worker struct {
}
|
package index
import "github.com/Mintegral-official/juno/document"
type StorageIndex interface {
Get(filedName string, id document.DocId) interface{}
}
|
package merchant
import (
"context"
"tpay_backend/adminapi/internal/common"
"tpay_backend/model"
"tpay_backend/adminapi/internal/svc"
"tpay_backend/adminapi/internal/types"
"github.com/tal-tech/go-zero/core/logx"
)
type GetMerchantBankCardListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.Se... |
package server
import ("strings"
"fmt"
"io/ioutil"
"encoding/json"
"net/http"
"strconv"
)
/*
This structure will be used by JSON data returned from yahoo finance API
*/
type Jsonresponse struct {
List struct {
Resources []struct {
Resource struct {
Field... |
package io
import "time"
type TimeBuilder func() time.Time
func NowBuilder() TimeBuilder {
return func() time.Time {
return time.Now()
}
}
func FixedTimeBuilder(t time.Time) TimeBuilder {
return func() time.Time {
return t
}
}
func FixedUnixTimeBuilder(sec int64) TimeBuilder {
return func() time.Time {
... |
package crud_interface
import (
"net/http"
)
type Database interface {
CreateCustomer(w http.ResponseWriter,r *http.Request)
GetId(w http.ResponseWriter,r *http.Request)
GetAll(w http.ResponseWriter,r *http.Request)
CustomerCtx(next http.Handler) http.Handler
}
|
package data
import (
"github.com/flynn/flynn/controller/schema"
ct "github.com/flynn/flynn/controller/types"
"github.com/flynn/flynn/pkg/postgres"
routerc "github.com/flynn/flynn/router/client"
"github.com/flynn/flynn/router/types"
)
func routeParentRef(appID string) string {
return ct.RouteParentRefPrefix + a... |
package nougat
import (
"net/url"
"reflect"
"testing"
)
func TestAddHeader(t *testing.T) {
cases := []struct {
Nougat *Nougat
expectedHeader map[string][]string
}{
{New().Add("authorization", "OAuth key=\"value\""), map[string][]string{"Authorization": []string{"OAuth key=\"value\""}}},
// header... |
package main
import (
"flag"
"fmt"
"github.com/jkomoros/sudoku/cmd/dokugen-analysis/internal/wekaparser"
"io/ioutil"
"log"
"os"
"os/exec"
)
const temporaryArff = "solves.arff"
var wekaJar string
type appOptions struct {
inFile string
outFile string
help bool
flagSet *flag.FlagSet
}
func init() {
/... |
package domain
// Return a list of all the articles
func getAllArticles() []article {
return []article{}
}
|
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
fmt.Println("Starting")
wg.Add(1)
go func() {
PAUSE := time.Duration(2 * time.Second)
fmt.Println("........")
time.Sleep(PAUSE)
wg.Done()
}()
wg.Wait()
fmt.Println("Finished")
}
|
package bt
import (
"strings"
"github.com/neoql/btlet/bencode"
)
// RawMeta is raw metadata
type RawMeta bencode.RawMessage
// Meta is meta
type Meta struct {
Name string `bencode:"name"`
Length *uint64 `bencode:"length,omitempty"`
PieceLength uint `bencode:"piece length"`
Pieces []byte ... |
package main
import (
"github.com/spf13/cobra"
"github.com/alejandroEsc/maas-cli/pkg/cli"
)
func machineCmd() *cobra.Command {
mo := &cli.MachineOptions{}
cmd := &cobra.Command{
Use: "machine",
Short: "Run a few simple machine commands",
Long: "",
Run: func(cmd *cobra.Command, args []string) {
cmd.... |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package common
type ContainerdConfig struct {
OomScore int `toml:"oom_score,omitempty"`
Root string `toml:"root,omitempty"`
Version int `toml:"version,omitempty"`
Plugins Plugins `toml:"plugins,omitempty... |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package armhelpers
import "context"
// ListResourceSkus lists Microsoft.Compute SKUs available for a subscription
func (az *AzureClient) ListResourceSkus(ctx context.Context, filter string) (ResourceSkusResultPage, error)... |
package main
import (
"bufio"
"fmt"
"io"
"os"
"github.com/libp2p/go-libp2p-core/network"
)
const protocol = "/libp2p/chat/1.0.0"
func chatHandler(s network.Stream) {
var (
err error
chunk []byte
line string
)
r := bufio.NewReader(s)
for {
prefix := true
for prefix {
chunk, prefix, err = r.R... |
package el
import (
"testing"
)
func a() error {
return Wrap(nil, "a")
}
func b() error {
return Wrap(a(), "b")
}
type X struct {
}
func (x *X) Foo() error {
return Wrap(a(), nil)
}
func (x X) Bar() error {
return Wrap(a(), nil)
}
func TestWrap(t *testing.T) {
t.Log("here")
e0 := Wrap(nil, "the original e... |
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"github.com/bai615/Go-000/Week04/grpc_test/proto"
)
func main() {
//stream
conn, err := grpc.Dial("127.0.0.1:8088", grpc.WithInsecure())
if err != nil {
panic(err)
}
defer conn.Close()
c := proto.NewGreeterClient(conn)
r, err := c.SayHello(... |
package main
import (
"bufio"
"log"
"os"
"github.com/luizbranco/pilgrims/cli"
)
func main() {
c, err := cli.NewClient()
if err != nil {
log.Fatal(err)
}
r := bufio.NewReader(os.Stdin)
for {
txt, err := r.ReadSlice('\n')
if err != nil {
log.Fatal(err)
}
c.Message(txt)
}
}
|
package main
import "fmt"
//定义一个 函数
func swap(a, b string) (string, string) {
return b, a
}
func main() {
m, n := swap("111", "222")
fmt.Println(m, n)
}
|
package server
import (
"github.com/gorilla/websocket"
"github.com/go-redis/redis"
"fmt"
"encoding/json"
)
const max_room_num = 2 //每个房间的最大人数
var (
ActiveClients = make(map[string]ClientConn) //在线的用户的信息
User = make(map[string]string)
)
type UserMsg struct {
Room string `json:"room"` //房间名字
... |
package Problem0380
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_Problem0380(t *testing.T) {
ast := assert.New(t)
rs := Constructor()
ast.True(rs.Insert(1), "插入1")
ast.False(rs.Remove(2), "删除2")
ast.True(rs.Insert(2), "插入2")
ast.Contains([]int{1, 2}, rs.GetRandom(), "返回1或2")
ast... |
package ciolite
// Api functions that support: users/email_accounts
import (
"fmt"
"strings"
"github.com/pkg/errors"
)
// GetUserEmailAccountsParams query values data struct.
// Optional: Status, StatusOK
type GetUserEmailAccountsParams struct {
// Optional:
Status string `json:"status,omitempty"`
StatusOK ... |
package backtracking
// 下标表示行, 值表示 queen 存储在哪一列
var result = [8]int{}
func Cal8Queens(row int) {
if row == 8 {
// 8 个棋子都放置好了,打印结果
printQueens(result)
return
}
// 每一行都有 8 种放法
for column := 0; column < 8; column++ {
// 有些放法不满足要求
if isOk(row, column) {
// 第 row 行的棋子放到了 column 列
result[row] = column
... |
package gonba
import (
"strconv"
)
const endpointPlayByPlay = "playbyplayv2"
// first period is startPeriod, second period is endPeriod
func (c *Client) GetPlayByPlay(gameId int, periods ...int) {
params := make(map[string]string)
if len(periods) > 0 {
params["StartPeriod"] = strconv.Itoa(periods[0])
if len(p... |
package logger
import (
"testing"
)
func TestDebugf(t *testing.T) {
Debugf("Test debug")
}
func TestInfof(t *testing.T) {
Infof("Test info")
}
func TestWarnf(t *testing.T) {
Warnf("Test warn")
}
func TestErrorf(t *testing.T) {
Errorf("Test error")
}
func init() {
Setup(&LoggerConfig{
Facility: "Logger te... |
package atypes
type AInterface interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
Assign(i int, d interface{})
Get(i int) interface{}
LessD(i, j interface{}) bool
InsertionB(i, j int)
}
|
package day12
var directions map[int]rune = map[int]rune{
0: 'E',
90: 'S',
180: 'W',
270: 'N',
}
type WaypointShip struct {
x int
y int
WaypointX int
WaypointY int
}
func (ship WaypointShip) turn(direction rune, degrees int) WaypointShip {
turns := degrees / 90
if direction == 'L' {
v... |
package controllers
import (
"net/http"
apiRequest "github.com/alexhornbake/go-crud-api/lib/api_request"
apiResponse "github.com/alexhornbake/go-crud-api/lib/api_response"
models "github.com/alexhornbake/go-crud-api/models"
schemas "github.com/alexhornbake/go-crud-api/schemas"
)
func showPost(w http.ResponseWri... |
package jwtauth
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"net/http"
"os"
jwt "github.com/dgrijalva/jwt-go"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
type authInfo struct {
Login string `json:"login"`
Pass string `json:"password"`
}
type User struct {
Login string
Password ... |
package testutil
import (
"bufio"
"context"
"fmt"
"io"
"testing"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/ory/dockertest/v3"
"github.com/ory/dockertest/v3/docker"
)
// WithTestMinIO starts a test MinIO server
func WithTestMinIO(t *testing.T, bucket string, ha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.