text stringlengths 11 4.05M |
|---|
package goSolution
import "testing"
func TestSubsetsWithDup(t *testing.T) {
nums := []int {1, 2, 2}
AssertEqual(t, 6, len(subsetsWithDup(nums)))
}
|
package message_adder
import (
"github.com/golang/protobuf/proto"
"ms/sun_old/base"
"ms/sun/shared/helper"
"ms/sun/servises/log_service"
"ms/sun/servises/sun_utils"
"ms/sun/shared/config"
"ms/sun/shared/x"
)
//todo save MessageFiles to its tables for later retrival
var chatLogger = log_service.NewSimpleLogger("... |
// Copyright (c) 2022 Target Brands, Inc. All rights reserved.
//
// Use of this source code is governed by the LICENSE file in this repository.
//nolint:dupl // ignore dupl linter false positive
package vela
import (
"fmt"
"github.com/go-vela/types/library"
)
// StepService handles retrieving steps for builds
//... |
package cmd
import (
"github.com/spf13/cobra"
"cloudfreexiao/ant-graphql/backend-go/server"
)
var (
debug bool
disableAuth bool
port int
)
var RootCmd = &cobra.Command{
Use: "graphql-server",
Short: "GraphQL API server in golang to get linux system info",
RunE: func(cmd *cobra.Command, args [... |
package sw
import (
"github.com/HNB-ECO/HNB-Blockchain/HNB/bccsp"
"github.com/HNB-ECO/HNB-Blockchain/HNB/bccsp/secp256k1"
"crypto/elliptic"
"errors"
//"github.com/HNB-ECO/HNB-Blockchain/HNB/bccsp/utils"
//"crypto/ecdsa"
"fmt"
)
type ecdsa256K1Signer struct{}
func (s *ecdsa256K1Signer) Sign(k bccsp.Key, digest... |
package home
import (
"os"
"io/ioutil"
"net/http"
"testing"
"github.com/gin-gonic/gin"
. "github.com/smartystreets/goconvey/convey"
"github.com/zeuxisoo/go-zenwords/pkg/tester"
)
var (
engine *gin.Engine
)
func init() {
engine = tester.CreateWebEngine()
engine.GET("/", IndexGet)
engine.GET("/robots.txt... |
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type Elm struct {
Node *TreeNode
Max int
Min int
}
// time: O(n), space: O(n) (log(n)*2 ?)
func isValidBST(root *TreeNode) bool {
fifo := []*Elm{}
fifo = append(... |
package github
import (
"context"
"errors"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
type Config struct {
Token string `env:"GITHUB_TOKEN,required"`
Owner string `env:"GITHUB_OWNER,required"`
Repo string `env:"GITHUB_REPO,required"`
Ref string `env:"GITHUB_REF" envDefault:"master"`
Pat... |
package mat
import (
"fmt"
"math"
"testing"
"github.com/stretchr/testify/assert"
)
func TestTuple4_IsVector(t *testing.T) {
v := NewVector(4.3, -4.2, 3.1)
assert.True(t, v.IsVector())
assert.False(t, v.IsPoint())
assert.Equal(t, 4.3, v.Get(0))
assert.Equal(t, -4.2, v.Get(1))
assert.Equal(t, 3.1, v.Get(2))... |
// 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 main
import (
"flag"
"fmt"
"log"
"math"
"os"
"sort"
"time"
)
var (
weekly = flag.Duration("weekly", 24*time.Hour, "Weekly working time")
dateInLayout = flag.String("date-layout", "06-1-2", "Layout of date input")
timeInLayout = flag.String("time-layout", "1504", "Layout of time input")
quiet ... |
package cmd
// OutputDir the output directory where the built version of Authelia is located.
var OutputDir = "dist"
// DockerImageName the official name of Authelia docker image.
var DockerImageName = "authelia/authelia"
// IntermediateDockerImageName local name of the docker image.
var IntermediateDockerImageName ... |
package main
import (
"fmt"
"log"
"os"
"github.com/urfave/cli"
)
func init() {
app.Commands = append(app.Commands,
cli.Command{
Name: "listen",
Usage: "tails messages from kafka",
Action: func(c *cli.Context) {
if len(c.Args()) > 0 && c.Args()[0] != "" {
globalFlags.Topic = c.Args()[0]
... |
package dp
// FibonacciRecursive solve using recursion only - No dynamic programming used
// Time Complexity: O(2^n) - there's a lot of repetition of already solved subproblems
// Space Complexity: O(2^n) - because of the stack calls
func FibonacciRecursive(n int) int {
if n <= 2 {
return 1
}
return FibonacciRecu... |
package collect
import (
"github.com/robertang/collector/cncf"
"github.com/robertang/collector/common"
"github.com/robertang/collector/metric"
"fmt"
"github.com/robertang/collector/output"
)
type Collector struct {
config cncf.Yml
metrics []common.Metric
outputs []common.Output
}
var _collectors = make([... |
package registry
import (
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/address"
"github.com/iotaledger/wasp/packages/parameters"
flag "github.com/spf13/pflag"
)
const (
// CfgBindAddress defines the config flag of the web API binding address.
CfgRewardAddress = "reward.address"
)
func InitFlag... |
package main
import (
//"math"
"fmt"
)
func main() {
var a, b int
fmt.Scan(&a, &b)
if a == 0 && b == 0 {
fmt.Printf("NO")
} else if ( a == b || a-b == 1 || a - b == -1) {
fmt.Printf("YES")
} else {
fmt.Printf("NO")
}
}
|
package concur_test
import (
"errors"
"fmt"
"strings"
"testing"
"github.com/stevenmatthewt/concur"
)
func TestConcurrentRunnerSimple(t *testing.T) {
jobs := []MockJob{
MockJob{},
MockJob{},
MockJob{},
MockJob{},
MockJob{},
MockJob{},
MockJob{},
MockJob{},
MockJob{},
}
err := concur.Concurr... |
/*
* @lc app=leetcode.cn id=239 lang=golang
*
* [239] 滑动窗口最大值
*/
// @lc code=start
package main
import "fmt"
import "math"
func maxSlidingWindow(nums []int, k int) []int {
// stack := []int{}
if len(nums) <= 0 {
return []int{}
}
max, maxPos := math.MinInt32, -1
if k >= len(nums) {
max, _ = findMax(nu... |
package main
import (
//"fmt"
"sort"
)
func contains(s []int, e int) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
type Elevator struct {
ID string
status string
amountOfFloors int
direction string
currentFloor i... |
// Package neunet provides a basic implementation of an artificial neural net.
package neunet
import (
)
// Type Parameters holds the global H and gain parameters. See the documentation for NewParameters
// for information on the parameters.
type Parameters struct {
H float64 // The coefficient for... |
package grpcclient
import (
//"net"
"time"
log "github.com/sirupsen/logrus"
"golang.org/x/net/context"
"google.golang.org/grpc"
pb "github.com/navinds25/grpcGoExpts/eaconnproto"
)
const (
address = "localhost:50051"
)
func GrpcClient() {
conn, err := grpc.Dial(address, grpc.WithInsecure())
if err != nil {
... |
// Package commands contains commands for the Kong library
package commands
|
package main
// 这个示例程序展示如何写基础单元测试
import (
"net/http"
"testing"
)
const checkMark = "\u2713" //√
const ballotX = "\u2717" //×
// TestDownload 确认 http 包的 Get 函数可以下载内容
func TestDownload(t *testing.T) {
//url := "http://2cifang.com"
url := "https://www.baidu.com/"
statusCode := 200
t.Log("Given the need to tes... |
package main
func maxArea(height []int) int {
i, j := 0, len(height)-1
area := 0
for i < j {
// 面积由短的一根的高度决定
h := MinInt(height[i], height[j])
area = MaxInt(area, h*(j-i))
// 比较两边的柱子,如果某侧的柱子比较矮,因为面积是由矮柱子决定的,所以较矮柱子一侧的面积在往中间方向走的时候已经是最大的了,
// 需要该侧柱子往中间移动,检查是否可能有更高的柱子能组成更大的面积
// 一样高的时候就一起移动,或者移动随意一侧继续计算即可
... |
package client
import "os"
func reboot() {
log.Warningf("Not rebooting. As you're on a mac and probably don't want to actually boot your dev machine. You're welcome.")
os.Exit(0)
}
|
package router
import (
"github.com/kataras/iris"
"github.com/kataras/iris/context"
"log"
)
const ACTION_METHOD_TYPE_GET = "GET"
const ACTION_METHOD_TYPE_POST = "POST"
const ACTION_METHOD_TYPE_PUT = "PUT"
const ACTION_METHOD_TYPE_DELETE = "DELETE"
const ACTION_METHOD_TYPE_ANY = "ANY"
type Controller struct {
Nam... |
package main
import (
"time"
"fmt"
"math/rand"
g "github.com/vseledkin/gortex"
"log"
"bufio"
"os"
"strings"
)
func main() {
// maintain random seed
rand.Seed(time.Now().UnixNano())
tokenizer := g.CharSplitter{}
trainFile := "train.txt"
dic, e := g.DictionaryFromFile(trainFile, tokenizer)
if e != nil {
... |
package main
import (
"fmt"
"strings"
)
var s = "stressed"
func main() {
j := strings.Split(s, "")
max := len(j)
result := make([]string, max)
for i := 0; i < max; i++ {
result[i] = j[max-i-1]
}
fmt.Println(strings.Join(result, ""))
}
|
package main
import ("bytes"; "encoding/base64"; "fmt" )
func main() {
data := []byte{1, 2, 3, 4, 5, 6, 7, 8}
bb := &bytes.Buffer{}
encoder := base64.NewEncoder(base64.StdEncoding, bb)
encoder.Write(data)
encoder.Close()
fmt.Println(bb)
dbuf := make([]byte, 12)
decoder := base64.NewDecoder(base64... |
package ice
import "github.com/nkbai/goice/stun"
type candidateGetter interface {
/*
获取有一部分信息的candidiate.第一个是本机主要地址,最后一个是缺省 Candidate
*/
GetCandidates() (candidates []*Candidate, err error)
}
//treat stun and turn as the same ...
type stunTranporter interface {
candidateGetter
Close()
getListenCandidiates() ... |
package util
import (
"testing"
)
func TestNewRingBuffer(t *testing.T) {
rb := NewRingBuffer(8)
t.Log("begin:", rb, rb.msgs.Len())
rb.Push([]byte{1, 2, 3})
t.Log("push:", rb, rb.msgs.Len())
if rb.end != 3 {
t.Fatal("index failed, must 0, 3", rb.buffer)
}
rb.Push([]byte{2, 2, 2})
t.Log("push:", rb, rb.msgs.... |
package Solution
import "until"
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 自顶而下递归解决问题 依次找到当前的根节点 然后接着进行下一层的寻找
// preorder[0] 前序遍历的第一个值肯定是根节点 根据这个值找到 处于中序遍历的位置 中序遍历 根节点的左边肯定是左子树 右边就是右子树
// 就这样一直递归 知道数组为空即可。
func buildTree... |
package owls
import (
"image/color"
"github.com/bcokert/engo-test/logging"
"engo.io/ecs"
"engo.io/engo"
"engo.io/engo/common"
)
type BasicHealthComponent struct {
Health float32
MaxHealth float32
}
type HealthBarComponent struct {
width float32
height float32
position engo.Point
emptySp... |
package solution
import "testing"
type testCase struct {
answer int
input string
}
func TestSolution(t *testing.T) {
cases := []testCase{
testCase{
answer: 3,
input : "abcabcbb",
},
testCase{
answer: 3,
input : "testtest",
},
testCase{
answer: 3,
input : "pwwkew",
},
testCase{
a... |
package inference
import (
"fmt"
"io/ioutil"
"testing"
"github.com/stretchr/testify/assert"
"github.com/TIBCOSoftware/flogo-contrib/action/flow/test"
"github.com/TIBCOSoftware/flogo-contrib/activity/inference/framework/tf"
"github.com/TIBCOSoftware/flogo-lib/core/activity"
)
var _ tf.TensorflowModel
var act... |
// go test -run none -bench . -benchtime 3s -benchmem.
// Basic benchmark test.
package basic
import (
"fmt"
"testing"
)
var gs string
// BenchmarkSprint tests the performance of using Sprint.
func BenchmarkSprint(b *testing.B) {
var s string
for i := 0; i < b.N; i++ {
s = fmt.Sprint("hello")
}
gs = s
}
... |
package util
// Use masks unused variables when compiling go program.
func Use(vals... interface{}) {
for _, val := range vals {
_ = val
}
}
|
package main
/*
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the squa... |
package main
import "fmt"
type spawner func(l int) int
// Playfield is the grid into which tetrominoes fall
type Playfield struct {
store [][]Mino
current *CurrentTetromino
Shapes []string
}
// CurrentTetromino location and pointer
type CurrentTetromino struct {
x int
y int
obj Tetromino
}
type Coordi... |
package server
import (
"crypto/elliptic"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/valyala/fasthttp"
"github.com/authelia/authelia/v4/internal/config... |
package main
import (
"fmt"
)
func main() {
ArrayOfNames := [6]string{"Joabe", "Phelipe", "Gabriel", "Igor", "Matheus"}
fmt.Printf("1: ArrayOfNames: %v\n", ArrayOfNames)
fmt.Printf("1: len(ArrayOfNames: %v\n", len(ArrayOfNames))
fmt.Println()
ArrayOfNames[0] = "Phelipe"
ArrayOfNames[1] = "Joabe"
fmt.Printf("... |
/*
Copyright Ken
*/
package main
import (
"fmt"
"log"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws... |
// Copyright 2019 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 shell
import (
"bytes"
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestFPromptUserForInputReturnsYesOnNonInteractive(t *testing.T) {
t.Parallel()
opts := NewShellOptions()
opts.NonInteractive = true
resp, err := FPromptUserForInput(os.Stdout, os.Stdin, "", opts)
assert.Nil(t, err)
... |
package nchanClient
import "testing"
const validStabStats = "total published messages: 123\nstored messages: 54353\nshared memory used: 12K\nshared memory limit: 131072K\nchannels: 34\nsubscribers: 5434535\nredis pending commands: 48\nredis connected servers: 65\ntotal interprocess alerts received: 43\ninterprocess a... |
package usecase
import (
"context"
"github.com/dsukesato/go13/pbl/app1-backend/domain/model"
"github.com/dsukesato/go13/pbl/app1-backend/domain/repository"
)
type RestaurantsUsecase interface {
GetRestaurants(context.Context) ([]*model.Restaurant, error)
PostRestaurants(context.Context) ([]*model.Restaurant, err... |
package main
import (
"fmt"
"runtime"
"sync"
"time"
"github.com/colefan/gsgo/console"
"github.com/colefan/gsgo/netio"
"github.com/colefan/gsgo/netio/iobuffer"
"github.com/colefan/gsgo/netio/packet"
"github.com/colefan/gsgo/netio/qos"
)
type MyServer struct {
*netio.Server
rw sync.Mutex
nMsgCount i... |
package downloader
import (
"github.com/lf-edge/eve/pkg/pillar/types"
log "github.com/sirupsen/logrus"
)
// Handles both create and modify events
func handleGlobalDownloadConfigModify(ctxArg interface{}, key string,
configArg interface{}) {
ctx := ctxArg.(*downloaderContext)
config := configArg.(types.GlobalDow... |
package service
import (
"github.com/sirsean/packhunter/config"
"github.com/sirsean/packhunter/model"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
var userCollection = func(session *mgo.Session) *mgo.Collection {
return session.DB(config.Get().Mongo.Database).C("users")
}
func GetUserByIdHex(session *mgo.Session,... |
// 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 integration
import (
"errors"
"testing"
"github.com/CyCoreSystems/ari"
)
func TestLoggingList(t *testing.T, s Server) {
runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) {
var expected = []*ari.Key{
ari.NewKey(ari.LoggingKey, "n1"),
}
m.Logging.On("List", (*ari.Key)(nil)).Return(ex... |
// 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 law or agreed to in writing... |
/*
Copyright 2019 The Yingxi.company Authors. All rights reserved.
Go
controller User
*/
package controller
import (
"github.com/gin-gonic/gin"
"yingxi.company/infra/go/handler"
"yingxi.company/infra/go/handler/errno"
"yingxi.company/infra/go/model"
"net/http"
"time"
"math"
"strings"
)
// 返回结构体
type ListRe... |
package main
import (
"log"
"testing"
"github.com/bahusvel/ClusterPipe/common"
)
func TestWeirdMapThingy(t *testing.T) {
cpdStatus := common.CPDStatus{}
mapThingy := TraverseParamTree(cpdStatus)
log.Println(mapThingy)
}
|
/*
* Copyright 2017 StreamSets 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... |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package cmd
import (
"fmt"
"testing"
"github.com/Azure/aks-engine/pkg/armhelpers"
"github.com/google/uuid"
. "github.com/onsi/gomega"
"github.com/spf13/cobra"
)
func TestGetLocationsCmd(t *testing.T) {
t.Parallel(... |
package nougat
import (
"io"
"io/ioutil"
"strings"
"testing"
)
func TestBodySetter(t *testing.T) {
fakeInput := ioutil.NopCloser(strings.NewReader("test"))
fakeBodyProvider := bodyProvider{body: fakeInput}
cases := []struct {
initial BodyProvider
input io.Reader
expected BodyProvider
}{
// nil bo... |
package main
import (
"context"
"fmt"
"log"
"net/http"
"net/http/httputil"
"net/url"
)
type Server struct {
srv http.Server
shutdownServer chan struct{}
}
// NewServer prepares a new server
func NewServer(robotAddr string, port int, shutdownServer chan struct{}) (*Server, error) {
s := &Server{
... |
package indexer
import (
"sync"
"time"
"github.com/Sirupsen/logrus"
"github.com/manishrjain/gocrud/search"
"github.com/manishrjain/gocrud/store"
"github.com/manishrjain/gocrud/x"
)
// Incremental indexing server to continously regenerate
// and index entities to keep store and search in-sync.
type Server struc... |
package command
import (
"fmt"
"strings"
"github.com/flosch/pongo2/v4"
)
// RenderCommand renders commandTemplate with the given arguments using Jinja
// "env" and "vars" will be injected into context and render the template,
// if they are also defined in arguments, arguments will be overridden.
func RenderComma... |
package main
import (
"fmt"
"time"
)
func data1(ch chan string) {
time.Sleep(4 * time.Second)
ch <- "from data1()"
}
func data2(ch chan string) {
time.Sleep(2 * time.Second)
ch <- "from data2()"
}
func main() {
chan1 := make(chan string)
chan2 := make(chan string)
go data1(chan1)
go data2(chan2)
select {... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-07-05 15:04
# @File : chaincode.go
# @Description :
# @Attention :
*/
package test
import "examples/blockchain/solo/solo_single_org/config"
func Invoke(){
config.Invoke()
}
|
package observer
import "design-patterns-go/observerPattern/event"
type Observer interface {
OnNotify(event event.Event)
}
|
package envoy
import "io"
func (coll *Collector) Collect() (CountersByUpstream, HistogramsByUpstream, error) {
var (
err error
counters CountersByUpstream
histograms HistogramsByUpstream
)
counters, err = coll.collectCounters()
if err != nil {
return counters, histograms, err
}
var upstreamCl... |
package flash_test
import (
"github.com/find-a-job/flash"
"github.com/stretchr/testify/assert"
"testing"
)
func iiGen() flash.IncTreeNode {
return flash.IncTreeNode{
Id: "1",
Type: "View",
Name: "view",
Children: []flash.IncTreeNode{
flash.IncTreeNode{
Id: "2",
Type: "Button",
Name: "bu... |
package tfcloud
import (
"encoding/json"
"io/ioutil"
)
type TfConfig struct {
Credentials struct {
App_terraform_io struct {
Token string `json:"token"`
} `json:"app.terraform.io"`
} `json:"credentials"`
}
func (c *TfConfig) Read(fileName string) (err error) {
jsonFile, err := ioutil.ReadFile(fileName)
... |
package main
import (
"io"
"log"
"os"
yaml "gopkg.in/yaml.v2"
)
func main() {
e := yaml.NewEncoder(os.Stdout)
defer e.Close()
for _, arg := range os.Args[1:] {
f, err := os.Open(arg)
if err != nil {
log.Fatalf("Open error: %s", err)
}
defer f.Close()
d := yaml.NewDecoder(f)
for {
var da... |
package models
import (
"time"
)
type Resource struct {
Id string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Update time.Time `json:"update"`
Create time.Time `json:"create"`
}
|
package main
import (
// "encoding/json"
"fmt"
"github.com/gorilla/websocket"
"net/http"
"math/rand"
// "time"
)
func (c *connection) reader() {
for {
_, message, err := c.ws.ReadMessage()
if err != nil {
break
}
/* if user is been silented */
if c.silent == true || c.login == false {
//c.send <... |
package main
import (
"fmt"
"time"
)
// (たぶん)スタンダード?なGoによる並行処理パターン
var done = make(chan bool) // 並行処理完了のお知らせ用.よく使われるパターンぽい
var msgs = make(chan int)
func producer() {
for i := 0; i < 500; i++ {
time.Sleep(time.Millisecond * 20)
msgs <- i
}
done <- true
}
func consumer() {
for {
msg := <-msgs
fmt.Print... |
package gpxjson
import "testing"
var sample = []byte(`<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="Endomondo.com" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/Gpx... |
package LetterPostgres
//
//import (
// "MainApplication/internal/Letter/LetterModel"
// "MainApplication/internal/Letter/LetterRepository"
// pgwrapper "gitlab.com/slax0rr/go-pg-wrapper"
//)
//
//type dataBase struct {
// DB pgwrapper.DB
//}
//
//func New(db pgwrapper.DB) LetterRepository.LetterDB {
// return dataBase... |
package setr
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01300102 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:setr.013.001.02 Document"`
Message *SwitchOrderV02 `xml:"setr.013.001.02"`
}
func (d *Document01300102) AddMessage() *SwitchO... |
package main
import "basic-rabbitmq/RabbitMQ"
func main() {
// routing worker two
workerOne := RabbitMQ.NewRabbitMQRouting("exGolang", "workerTwo")
workerOne.RecieveRouting()
}
|
package forkexec
import (
"syscall"
"github.com/criyle/go-sandbox/pkg/mount"
"github.com/criyle/go-sandbox/pkg/rlimit"
)
// Runner is the configuration including the exec path, argv
// and resource limits. It can creates tracee for ptrace-based tracer.
// It can also create unshared process in another namespace
t... |
package snowflake
import (
"sync"
"time"
)
type DefaultSequence struct {
mu sync.Mutex
elapsed int64
sequence int64
}
func (s *DefaultSequence) Next(_ int16, epoch time.Time) (int64, int64, error) {
s.mu.Lock()
defer s.mu.Unlock()
elapsed := time.Since(epoch).Nanoseconds() / 1e6
if s.elapsed < elapsed {
... |
package main
import (
"code.google.com/p/go.net/websocket"
"encoding/json"
"fmt"
"github.com/fmstephe/matching_engine/client"
"github.com/fmstephe/matching_engine/coordinator"
"github.com/fmstephe/matching_engine/matcher"
"github.com/fmstephe/matching_engine/msg"
"github.com/fmstephe/matching_engine/q"
"githu... |
package gpacker
type entrytype byte
const (
TBinary entrytype = 0x01 + iota
TText
TImage
TFont
)
|
package controllers
import (
"github.com/yydzero/cherry/models"
)
type ArticleController struct {
CherryController
}
// Signup will register new user
// TODO: pg 不支持 byte[] 类型。
func (this *ArticleController) Get() {
id, err := this.GetId()
if err != nil {
this.Fail(err.Error())
return
}
article := models.A... |
package gofakeit
import "fmt"
func Example() {
Seed(11)
fmt.Println("Name:", Name())
fmt.Println("Email:", Email())
fmt.Println("Phone:", Phone())
fmt.Println("Address:", Address().Address)
// Output:
// Name: Markus Moen
// Email: alaynawuckert@kozey.biz
// Phone: (570)245-7485
// Address: 75776 Lake View ... |
package utils
import (
"fmt"
"os"
"github.com/joho/godotenv"
)
type utilsEnv struct{}
// Env : utility functions for environment variables
var Env utilsEnv
// Load environment variables from .env file if existent (else assume pre-loaded)
func (utilsEnv) Load() {
err := godotenv.Load()
if err == nil {
Log.In... |
package main
import (
"io"
"log"
"net/http"
)
type Handler struct {
}
func (handler Handler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
switch req.URL.Path {
case "/dog":
io.WriteString(res, "doggy dog")
case "/cat":
io.WriteString(res, "Kitty cat")
}
}
func main() {
handler := Handler{}
e... |
package main
import (
"fmt"
"html/template"
"log"
"math/rand"
"net/http"
"os/exec"
"runtime"
"strings"
"time"
)
type (
// структура описывающая пару слов: ангийский и русский варианты
Word struct {
En string
Ru string
}
// структура, в которую буждем сохранять ответ пользователя
Answer struct {
R... |
package r10kshelldeployer
// Option defines a function prototype to apply options to the Shell instance.
type Option func(*Shell)
// WithConfig sets all the shell configurations.
func WithConfig(cfg *Config) Option {
return func(s *Shell) {
if cfg == nil {
return
}
if cfg.Command != "" {
s.cfg.Command =... |
// Copyright 2020 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 ... |
package main
func isValidSudoku(board [][]byte) bool {
for i := 0; i < 9; i++ {
mp1 := make(map[byte]bool)
mp2 := make(map[byte]bool)
mp3 := make(map[byte]bool)
for j := 0; j < 9; j++ {
if board[i][j] != '.' {
if _, ok := mp1[board[i][j]]; !ok {
mp1[board[i][j]] = true
} else {
return fal... |
package main
import (
"image"
"log"
"os"
"path/filepath"
"reflect"
"runtime"
"sync"
"time"
"lec/lecimg"
)
// Work represents a job to do
type Work struct {
dir string
filename string
quit bool
}
// Worker is a worker to process images.
type Worker struct {
workChan <-chan Work
}
func collectI... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-08-13 09:01
# @File : lt_191_Number_of_1_Bits.go
# @Description :
# @Attention :
*/
package byte
func hammingWeight(num uint32) int {
count := 0
for i := 0; i < 32; i++ {
count += int(num >> uint32(i) & uint32(1))
}
return count
}
|
package models
import (
"net/http"
"time"
mesherykube "github.com/layer5io/meshkit/utils/kubernetes"
"github.com/vmihailenco/taskq/v3"
)
// HandlerInterface defines the methods a Handler should define
type HandlerInterface interface {
ServerVersionHandler(w http.ResponseWriter, r *http.Request)
ProviderMiddl... |
package dataStruct
import "fmt"
type LinkNode struct {
Data int
Prev *LinkNode
Next *LinkNode
}
// todo 生成一个新的链表节点
func (_this *LinkNode) NewLink(value int) *LinkNode {
return &LinkNode{value, nil, nil}
}
// todo 将一个节点加入链表的末尾
func (_this *LinkNode) Push(node *LinkNode) *LinkNode {
var next *LinkNode = _this
/... |
package exoscale
import (
"context"
"testing"
"github.com/stretchr/testify/require"
cloudprovider "k8s.io/cloud-provider"
)
func TestGetZoneByProviderID(t *testing.T) {
ctx := context.Background()
p, ts := newMockInstanceAPI()
zones := &zones{p: p}
defer ts.Close()
zone, err := zones.GetZoneByProviderID(ct... |
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package packet
import (
"bytes"
"net"
"reflect"
"testing"
)
func TestIPString(t *testing.T) {
const str = "1.2.3.4"
ip := NewIP(net.ParseIP(... |
package main
import "fmt"
func main() {
funSlice1()
}
//定义切片
func funSlice1(){
// 声明切片类型
var a []string //声明一个字符串切片
var b = []int{} //声明一个整型切片并初始化
var c = []bool{false, true} //声明一个布尔切片并初始化
fmt.Println(a) //[]
fmt.Println(b) //[]
fmt.Println(c) /... |
// Copyright 2019 Radiation Detection and Imaging (RDI), LLC
// Use of this source code is governed by the BSD 3-clause
// license that can be found in the LICENSE file.
package main
import (
"context"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"runtime/pprof"
"strconv"
"strings"
"time"
"github.com/r... |
package model
import "github.com/Yangshuting/golang_model/lib"
func MigrateUserFromKuaiMao702SelfDB(cc *lib.Cusctx) {}
|
// Copyright 2020 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 connection
import "github.com/exasol/exasol-driver-go/pkg/errors"
type RowCount struct {
affectedRows int64
}
func (res *RowCount) LastInsertId() (int64, error) {
return 0, errors.ErrNoLastInsertID
}
func (res *RowCount) RowsAffected() (int64, error) {
return res.affectedRows, nil
}
|
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2019-05-04 10:38
# @File : reflect.go
# @Description : 反射的util
*/
package utils
import (
"fmt"
"reflect"
"unsafe"
)
func ConvT2InterfaceSlice(data interface{}) []interface{} {
value, b := IsSlice(data)
if !b {
return nil
}
l := value.Len()
res := make(... |
package main
import "fmt"
var BuildID = "dev"
func main() {
fmt.Printf("Build: %v\n", BuildID)
fmt.Printf("2+2=%d\n", add(2, 2))
}
func add(a, b int) int {
return a + b
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.