text stringlengths 11 4.05M |
|---|
package cpu_test
import (
"testing"
"github.com/sardap/gos/cpu"
"github.com/stretchr/testify/assert"
)
func TestPushPopUint16(t *testing.T) {
c := createCpu()
// Normal case
c.PushUint16(0x1312)
assert.Equal(t, uint16(0x1312), c.PopUint16())
// Fucked case
c.PushUint16(0x1312)
assert.Eq... |
package main
import "crypto/sha256"
type PHBMerkleTree struct {
PHBRootNode *PHBMerkleNode
}
// MerkleNode represent a Merkle tree node
type PHBMerkleNode struct {
PHBLeft *PHBMerkleNode
PHBRight *PHBMerkleNode
PHBData []byte
}
// NewMerkleTree creates a new Merkle tree from a sequence of data
func PHBNewMerk... |
package ZFinger
import (
"bufio"
"errors"
"fmt"
"github.com/deckarep/golang-set"
"log"
"net"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
var PluginList []DetectPlugin
type DetectPlugin struct {
helloStr []byte
RegexpList []*regexp.Regexp
priority int //priority: from 1 to 100, wil send hello first... |
package main
import (
"fmt"
"reflect"
)
// shows how to check whether 2 maps equal or not
func main() {
m1 := make(map[string]string)
m2 := make(map[string]string)
m1["1"] = "abc"
m1["2"] = "一二三"
m2["2"] = "一二三"
m2["1"] = "abc"
fmt.Println(reflect.DeepEqual(m1, m2))
}
|
// Copyright 2021 The Perses Authors
// 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 solutions
func rangeBitwiseAnd(m int, n int) int {
for n > m && n != 0 {
n = n & (n - 1)
}
return n
}
|
package s3httpfile
import (
"github.com/aws/aws-sdk-go/service/s3"
"os"
"path/filepath"
"time"
)
type s3ObjectFileInfo struct {
*s3.Object
}
func (fi *s3ObjectFileInfo) Name() string {
return filepath.Base(*fi.Object.Key)
}
func (fi *s3ObjectFileInfo) Size() int64 {
return *fi.Object.Size
}
func (fi *s3Obje... |
package leetcode_go
func numberOfArithmeticSlices(A []int) int {
dp := make([]int, len(A))
for i := 2; i < len(A); i++ {
if A[i]-A[i-1] == A[i-1]-A[i-2] {
dp[i] = dp[i-1] + 1
}
}
res := 0
for _, n := range dp {
res += n
}
return res
}
|
package config
import (
"fmt"
"log"
"os"
"project/models"
"github.com/joho/godotenv"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
// .env struct
type AppConfig struct {
Port string
DbDriver string
DbUser string
DbPassword string
DbPort string
DbHost string
DbName string
JWTSecret s... |
/**
* @description:
* @author Administrator
* @date 2020/7/11 0011 17:26
*/
package vis
import "fmt"
func Printer() {
fmt.Println(MyName)
fmt.Println(yourName)
}
|
// Copyright 2019 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package crostini
import (
"image/color"
"chromiumos/tast/local/colorcmp"
)
// The DemoConfig object holds a configuration for running a tast test that
// uses one of the... |
package main
import(
piscine ".."
"os"
"fmt"
"github.com/01-edu/z01"
)
func main(){
if piscine.Lent3(os.Args) !=3 {
z01.PrintRune('\n')
}else{
for i:=0;i<len(os.Args);i++{
fmt.Println(gcd(piscine.Atoi(os.Args[1]),piscine.Atoi(os.Args[2])))
break
}
}
}
func gcd(a, b int) int {
var bgcd func(a... |
package main
import (
"flag"
"fmt"
"log"
"math/rand"
"net/http"
"os"
"time"
)
const (
envAccessToken = "ACCESS_TOKEN"
envStorePath = "STORE_PATH"
envPostgresURL = "POSTGRES_URL"
defaultBufSize = 512
defaultPort = 3000
defaultLinkCacheCapacity = 1000
defaultMetaCacheCapaci... |
package handle
import (
"encoding/json"
"github.com/valyala/fasthttp"
)
type Response struct {
StatusCode int `json:"status_code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
// raw handler
func Raw(h fasthttp.RequestHandler) fasthttp.RequestHandler {
return fasthttp.Requ... |
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
gotime "time"
"github.com/zhangpeihao/gotimer/list"
)
const (
programName = "gotimer"
version = "0.3"
)
var (
bindAddress *string = flag.String("BindAddress", ":18001", "The bind address.")
savefile *string... |
package process
import (
"os/exec"
)
// Start TODO
func Start(binary string, cwd string, args []string) (*exec.Cmd, error) {
cmd := &exec.Cmd{
Path: binary,
Dir: cwd,
Args: args,
}
if err := cmd.Start(); err != nil {
return nil, err
}
return cmd, nil
}
|
package platform
import (
"net/http"
)
// Inspired by: https://www.thegreatcodeadventure.com/mocking-http-requests-in-golang/
type httpClient interface {
Do(req *http.Request) (*http.Response, error)
}
var (
client httpClient = &http.Client{}
)
|
package usecases
import (
"github.com/falcosecurity/cloud-native-security-hub/pkg/resource"
"github.com/falcosecurity/cloud-native-security-hub/pkg/vendor"
"log"
"os"
)
type Factory interface {
NewRetrieveAllResourcesUseCase() *RetrieveAllResources
NewRetrieveOneResourceUseCase(resourceID string) *RetrieveOneRe... |
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package ax
// secOwe provides Gen method to build a new Config.
type secOwe struct {
}
// Gen builds a ConfigParam list to allow the router to support an open network flow.... |
package main
import (
"errors"
"net/http"
"github.com/kubil6y/dukkan-go/internal/data"
"github.com/kubil6y/dukkan-go/internal/validator"
)
func (app *application) createRatingHandler(w http.ResponseWriter, r *http.Request) {
slug := app.parseSlugParam(r)
var input ratingDTO
if err := app.readJSON(w, r, &inpu... |
package models
import (
"archive/tar"
"bytes"
"compress/gzip"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/gofrs/uuid"
"github.com/layer5io/meshkit/database"
mesherykube "github.com/layer5io/meshkit/uti... |
package main
import (
"fmt"
"time"
)
type Data struct {
username string
password string
Count int
RecentAction time.Time
}
type ObjectList struct {
li []Data
}
var objectlist = &ObjectList{li: make([]Data, 10)}
//创建用户
func (ObjList *ObjectList) MakeList() {
objectlist.Put("zhaoriyong", "123... |
/*
* A minimal Scheme interpreter, as seen in lis.py and SICP
* http://norvig.com/lispy.html
* http://mitpress.mit.edu/sicp/full-text/sicp/book/node77.html
*
* Pieter Kelchtermans 2013
* LICENSE: WTFPL 2.0
*/
package main
import (
"fmt"
"reflect"
"strings"
"unicode"
"github.com/perlmonger42/LiSP/scan"
)
... |
/*
Copyright 2014 Google Inc. 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 ... |
package main
import (
"bytes"
"crypto/tls"
"crypto/x509"
"errors"
"flag"
"github.com/gorilla/securecookie"
"html/template"
"io/ioutil"
"log"
"net/http"
"net/url"
"path"
"path/filepath"
"strconv"
"strings"
)
type Config struct{ URL, Key string }
var (
port = flag.String("port", "8082", "Listening HT... |
package users
import (
"net/http"
"github.com/gin-gonic/gin"
"go4eat-api/svr/ctx"
)
// AuthenticateUser func
func AuthenticateUser(c *gin.Context) {
cData := ctx.GetData(c)
var err error
var req struct {
Username string `json:"username" validate:"required,username"`
Password string `json:"password" val... |
package main
import (
"encoding/csv"
"os"
"flag"
"unicode/utf8"
"github.com/LindsayBradford/go-dbf/godbf"
)
func main() {
delimiter := flag.String("d", "|", "delimiter used to separate fields")
headers := flag.Bool("h", false, "display headers")
flag.Parse()
path := flag.Arg(0)
if path == "" {
flag.PrintD... |
// Copyright (C) 2017 Google 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 t... |
package rvljson
import (
"encoding/json"
"fmt"
"github.com/robfig/revel"
"net/http"
)
// Interface used by the JsonErrorResult.
// Implement this interface when creating your own JsonError type.
// Also make sure to override PanicResponseFactory and InvalidRequestResponseFactory.
type JsonErrorResponder interface... |
// Copyright 2020 cloudeng llc. All rights reserved.
// Use of this source code is governed by the Apache-2.0
// license that can be found in the LICENSE file.
package cloudpath_test
import (
"fmt"
"cloudeng.io/path/cloudpath"
)
func ExampleScheme() {
for _, example := range []string{
"s3://my-bucket/object",
... |
package main
import (
"encoding/json"
"testing"
)
func TestKubeConfigObject(t *testing.T) {
bytes := []byte(`apiVersion: v1
clusters:
- cluster:
certificate-authority: /Users/gerald/.minikube/ca.crt
server: https://192.168.99.100:8443
name: 192-168-99-100:8443
- cluster:
certificate-authority: /Users... |
package verdeps
import (
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"strings"
)
type readDepsArgs struct {
outputChan chan *importSpec
packagePath string
accumulatedErrors *syncedErrors
syncedImportCounts *syncedImportCounts
}
func readDeps(args readDepsArgs) {
var (
err ... |
/*
Copyright The Codefresh Authors.
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, softwa... |
package cal
import (
"math"
"sort"
)
// 要求输入一个n数输出第n个丑数。丑数是素因子只有2.3.5.7...。非常急,谢谢。
// Ugly 丑数,基础
// base 素数数组 可以是 2,3,5|3,5,7
type Ugly struct {
base []int // 基础素因子
bmul int // 基础素因子 乘积
cbase [][]int // 素因子对应的第i次计算次数
ranks [][]int // 素因子各次值排序
}
// NewUgly 创建一个丑数计算基础
func NewUgly(base []int) *Ugly {
s... |
package config
import (
"flag"
)
var bindPort int
var kafkaHost string
var kafkaPort int
var globalConf *Config
func init() {
flag.IntVar(&bindPort,"bind-port",1234,"the port the HTTP server binds to")
flag.StringVar(&kafkaHost,"kafka-host","127.0.0.1","kafka host")
flag.IntVar(&kafkaPort,"kafka-port",9092,"k... |
package maximumsubarray
import (
"testing"
)
func TestMaxSubArray(t *testing.T) {
tests := []struct {
in []int
want int
}{
{
in: []int{1, 1, 1, 1, 1},
want: 5,
},
{
in: []int{-2, 1, -3, 4, -1, 2, 1, -5, 4},
want: 6,
},
}
for _, test := range tests {
got := maxSubArray(test.in)
... |
package main
import (
"testing"
)
func TestMinNumberInRotatedArray(t *testing.T) {
tests := []struct {
give []int
want int
}{
{
[]int{3, 4, 5, 1, 2},
1,
},
{
[]int{3, 4, 5, 1, 1, 2},
1,
},
{
[]int{3, 4, 5, 1, 2, 2},
1,
},
{
[]int{1, 0, 1, 1, 1},
0,
},
{
[]int{1, 2, ... |
package gha
import "net/http"
type RoundTripper string
func (rt RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Set("Authorization", "token "+string(rt))
return http.DefaultTransport.RoundTrip(req)
}
var _ http.RoundTripper = RoundTripper("")
|
package lc
// Time: O(n)
// Benchmark: 0ms 2mb | 100%
func countGoodSubstrings(s string) int {
var total int
for i := 0; i < len(s)-2; i++ {
if s[i] == s[i+1] || s[i] == s[i+2] || s[i+1] == s[i+2] {
continue
}
total++
}
return total
}
|
package utils
import (
"bytes"
"compress/flate"
"compress/gzip"
"io/ioutil"
)
func DecompressFlate(data []byte) ([]byte, error) {
return ioutil.ReadAll(flate.NewReader(bytes.NewReader(data)))
}
func DecompressGzip(data []byte) (resData []byte, err error) {
r, err := gzip.NewReader(bytes.NewReader(data))
if er... |
package hamt
import (
"bytes"
"context"
"fmt"
"time"
/*
bstore "github.com/ipfs/go-ipfs/blocks/blockstore"
bserv "github.com/ipfs/go-ipfs/blockservice"
offline "github.com/ipfs/go-ipfs/exchange/offline"
*/
block "github.com/ipfs/go-block-format"
cbor "github.com/ipfs/go-ipld-cbor"
recbor "github.c... |
// Copyright 2019 The gVisor Authors.
//
// 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 agree... |
package queue
//Queue a queue
type Queue struct {
data []interface{}
}
//Empty the queue is empty or not
func (q *Queue) Empty() bool{
return len(q.data) == 0
}
//Front return the front data of the queue
func (q *Queue) Front() interface{} {
if q.Empty() {
return nil
}
return q.data[len(q.data) - 1]
}
//Rea... |
package main
import (
"bufio"
"fmt"
"math/big"
"os"
"strconv"
)
func main() {
input := make([]string, 0)
output := make([]string, 0)
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
numberOfCases, err := strconv.Atoi(scanner.Text())
if err != nil {
panic(err)
}
for i := 0; i < ... |
package fakes
import (
"sync"
awselb "github.com/aws/aws-sdk-go/service/elb"
)
type LoadBalancersClient struct {
DeleteLoadBalancerCall struct {
sync.Mutex
CallCount int
Receives struct {
DeleteLoadBalancerInput *awselb.DeleteLoadBalancerInput
}
Returns struct {
DeleteLoadBalancerOutput *awselb.D... |
package stats
import (
kv "github.com/patrickmn/go-cache"
)
// The format of the keys in the cache is
// <node-id>:<version>:<resource-type>:<pod-id>:<key>
//
// Note that though currently revision and version have the same value for all
// types (with the exeption of secrets), this might change in the future and ... |
// This file contains the types describing the computed / derived data.
package rep
import (
"github.com/icza/screp/rep/repcmd"
"github.com/icza/screp/rep/repcore"
)
// Computed contains computed, derived data from other parts of the replay.
type Computed struct {
// LeaveGameCmds of the players.
LeaveGameCmds [... |
package main
import (
"log"
"net/rpc"
"go.RPC_S/tasks"
)
func taskSample() {
var err error
var reply tasks.ToDo
var slice []tasks.ToDo
client, err := rpc.DialHTTP("tcp", "localhost:1234")
if err != nil {
log.Fatal("Connection error: ", err)
}
finishApp := tasks.ToDo{"Finish App", "Started"}
makeDinn... |
package main
import (
"bufio"
"os"
"fmt"
"strings"
"strconv"
)
type argument struct {
isValue bool
value int
variable string
}
type instruction struct {
command string
arg1 argument
arg2 argument
}
var instructions []instruction
// since all registers default to 0, I don't need to initialize the values ... |
package ga
import (
"errors"
"fmt"
"math/rand"
"strconv"
"time"
)
func check(e error) {
if e != nil {
panic(e)
}
}
type GeneticAlgorithm struct {
Candidates Population
BestCandidate Genome
Generations int
IterationsSinceChange int
GenerateCandidate GenerateCandidateFunction
Crossover Cr... |
package db
import (
"Blog/util"
"database/sql"
_ "github.com/Go-SQL-Driver/MySQL"
)
var conn Connector
type Connector struct {
Db *sql.DB
}
func Constructor() *Connector {
return &conn
}
// 连接数据库
func (conn *Connector) Connect() {
var e error
// 这里使用的 dataSourceName 格式为 user:password@tcp(localhost:5555)/dbn... |
package blockchain
import (
"errors"
"fmt"
"sync"
"time"
"github.com/constant-money/constant-chain/common"
libp2p "github.com/libp2p/go-libp2p-peer"
"github.com/patrickmn/go-cache"
)
type peerState struct {
Shard map[byte]*ChainState
Beacon *ChainState
ShardToBeaconPool *map[byte][]u... |
package models
type Response struct {
Header Header `json:"header"`
Data interface{} `json:"data"`
}
const (
ServerSuccessCode = 1000
ServerSuccessDesc = "success"
FileTypeFile = "file"
FileTypeImage = "image"
FileTypeAudio = "audio"
FileTypeVideo = "video"
)
type Header struct {
Code int `json:"c... |
package app
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
matrix_db "shpong/db/matrix/gen"
"shpong/gomatrix"
"strings"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
)
func (c *App) DomainAPIEndpoint() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Requ... |
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package crostini
import (
"context"
"fmt"
"strings"
"time"
"chromiumos/tast/errors"
"chromiumos/tast/local/crostini"
"chromiumos/tast/local/crostini/ui/terminalapp"
... |
package runtime
// Evaluate every element of a list, retaining the list structure
// This is used in argument list evaluation
func EvalEach(env Env, s Sequence) (Sequence, error) {
acc := EmptyList
for !s.Empty() {
v, err := Eval(s.Head(), env)
if err != nil {
return nil, err
}
acc = acc.Append(v)
s = s... |
package model
type TriggerMode int
// Currently TriggerMode models two orthogonal attributes in one enum:
//
// 1. Whether a file change should update the resource immediately (auto vs
// manual mode)
//
// 2. Whether a resource should start when the env starts (auto_init=true vs
// auto_init=false mode, so... |
package main
import (
"fmt"
"time"
)
//时间戳
func main() {
now := time.Now()
secs := now.Unix()
nacos := now.UnixNano()
millis := nacos/ 1000000
fmt.Println(now)
fmt.Println(secs)
fmt.Println(millis)
fmt.Println(nacos)
fmt.Println(time.Unix(secs,0))
fmt.Println(time.Unix(0,nacos))
}
|
package csvutil
import (
"github.com/rzajac/goassert/assert"
"io"
"reflect"
"strings"
"testing"
)
// Stuff to help testing
var testCsvLines = []string{"Tony|23|123.456|Y", "John|34|234.567|N|"}
type person struct {
Name string
Age int
Balance float32
Skipped string `csv:"-"`
LowBalance ... |
package jwkset
import (
"crypto/ecdsa"
"net/http"
"testing"
"time"
"github.com/stretchr/testify/assert"
"gopkg.in/square/go-jose.v2"
)
func TestALBFetcher(t *testing.T) {
assert := assert.New(t)
fetcher := &ALBFetcher{
Client: &http.Client{},
Region: "ap-northeast-1",
Algo: jose.ES256,
}
jwksresp, ... |
// Copyright 2018 The Moov Authors
// Use of this source code is governed by an Apache License
// license that can be found in the LICENSE file.
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/go-kit/kit/log"
"github.com/gorilla/mux"
)
func TestSearcher__refreshInter... |
// Copyright 2023 Gravitational, 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 agree... |
package fastdb
import (
"encoding/json"
"errors"
"fastdb/index"
"fastdb/storage"
"fastdb/utils"
"io/ioutil"
"log"
"os"
"sync"
"time"
)
const (
// The path for saving rosedb config file.
configSaveFile = string(os.PathSeparator) + "DB.CFG"
// The path for saving rosedb meta info.
dbMetaSaveFile = strin... |
package output
import (
"fmt"
"io"
"github.com/yannh/kubeconform/pkg/validator"
)
type tapo struct {
w io.Writer
withSummary bool
verbose bool
results []validator.Result
nValid, nInvalid, nErrors... |
// Copyright (c) KwanJunWen
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package estemplate
import "fmt"
// DynamicTemplate defines custom mappings that can be applied to dynamically
// added fields based on:
// - the datatype detected ... |
// Copyright (c) KwanJunWen
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package estemplate
import (
"encoding/json"
"testing"
)
func TestDatatypeTextSerialization(t *testing.T) {
tests := []struct {
desc string
t ... |
// Copyright 2022-2023 Picovoice Inc.
//
// You may not use this file except in compliance with the license. A copy of the license is
// located in the "LICENSE" file accompanying this source.
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an... |
package cosmos
import (
"fmt"
"github.com/am3o/cosmos/x/cosmos/keeper"
"github.com/am3o/cosmos/x/cosmos/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/tendermint/tendermint/crypto"
)
func handleMsgCreateVote(ctx sdk.Context, k keeper.Keeper, msg types.MsgCreateVote) (*sdk.Result, error) {
k.Create... |
package main
import (
"image/color"
"log"
"time"
"net/http"
"golang.org/x/net/websocket"
"sync"
"fmt"
"flag"
)
type LEDStripe struct {
LEDS []color.RGBA
}
func NewLEDStripe(count int) *LEDStripe {
stripe := &LEDStripe{
LEDS: make([]color.RGBA, count),
}
return... |
package kyoto
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"html/template"
"log"
"net/http"
"strings"
)
// ****************
// Action configuration
// ****************
// ActionConfiguration holds a global actions configuration.
type ActionConfiguration struct {
Path string // Configure a path prefix for... |
package zookeeper
import (
"sync"
"testing"
"time"
)
func TestZkEventListener_ListenServiceEvent(t *testing.T) {
client,err := NewClient("test-zk",[]string{"10.12.33.33"},10*time.Second)
if err != nil {
t.Errorf("new zookeeper client err: %v",err)
}else {
content := `
system_name = "xt"
system... |
package version
var Version string
|
// Copyright 2014 Marc-Antoine Ruel. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.
package main
import (
"errors"
"fmt"
"strings"
"github.com/maruel/subcommands"
)
var cmdAskBeer = &subcommands.Command{
UsageLine: "be... |
package main
import (
"fmt"
"io/ioutil"
"math"
"os"
"strconv"
"strings"
)
// https://adventofcode.com/2019/day/16
func check(err error) {
if err != nil {
panic(err)
}
}
func doPhase(input []int) []int {
base := [4]int{0, 1, 0, -1}
output := make([]int, len(input))
for i, _ := range input {
pattern :=... |
package rwlc
import "testing"
func TestReadWriteLineCloser(t *testing.T) {
t.Run("case 1", func(t *testing.T) {
rw := New()
rw.WriteLine("test 1")
rw.WriteLine("test 2")
rw.WriteLine("test 3")
s, err := rw.ReadLine()
assertNoError(t, err)
assertEqual(t, "test 1", s)
s, err = rw.ReadLine()
assert... |
package main
import (
"fmt"
"sort"
)
type people []string
func main() {
studyGroup := people{"Zeno", "John", "Al", "Jenny"}
fmt.Println(studyGroup)
sort.Strings(studyGroup)
fmt.Println(studyGroup)
}
|
package whitelist
import "testing"
func TestMultiWhiteList_Filter(t *testing.T) {
whiteList := NewMultiWhiteList()
ops := NewOpsWithUid(1)
t.Log(whiteList.Filter(ops))
whiteList.Reload(ops)
t.Log(whiteList.Filter(ops))
whiteList.Del(ops)
t.Log(whiteList.Filter(ops))
whiteList.Add(ops)
t.Log(whiteList.Filter... |
// Copyright (C) 2017 Google 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 t... |
package structtags
import (
"fmt"
"testing"
. "github.com/onsi/gomega"
)
func TestTags(t *testing.T) {
g := NewGomegaWithT(t)
tags := parseTags(`db:"name" json:"name,omitempty"`)
g.Expect(tags.Keys()).To(Equal([]string{"db", "json"}))
g.Expect(tags.Get("db")).To(Equal(&Tag{Key: "db", Name: "name", Options: [... |
/*
* @lc app=leetcode.cn id=887 lang=golang
*
* [887] 鸡蛋掉落
*/
// @lc code=start
// 修改状态转移,dp数组里面存放给你k个鸡蛋,测试m次,最坏的情况下测试n层楼
// import "math"
func superEggDrop(k int, n int) int {
// 初始化dp数组
dp := make([][]int, k+1)
for i:=0; i<=k;i++ {
dp[i] = make([]int, n+1)
}
// return dp(k,n,table)
var m int
for dp[k... |
package model
//股票公司
type Company struct {
StockExchange int `json:"stock_exchange"`
Code string `json:"code"`
Plate string `json:"plate"`
ShortName string `json:"short_name"`
FullName string `json:"full_name"`
IndustryCode string `json:"industry_code"`
Industr... |
package _3_Transfer_Object_Pattern
//步骤 1
//创建数值对象。
type StudentVO struct {
Name, RollNo string
}
type StudentBO struct {
students []*StudentVO
}
func NewStudentBO() *StudentBO {
return &StudentBO{[]*StudentVO{
&StudentVO{Name: "Robert", RollNo: "0"},
&StudentVO{Name: "John", RollNo: "1"},
}}
}
func (receiv... |
package keeper_test
import (
"math/big"
"testing"
"github.com/stretchr/testify/require"
sdk "github.com/cosmos/cosmos-sdk/types"
authante "github.com/cosmos/cosmos-sdk/x/auth/ante"
"github.com/ethereum/go-ethereum/common"
ethtypes "github.com/ethereum/go-ethereum/core/types"
ethermint "github.com/tharsis/et... |
package egu
import "net/http"
// https://gowebexamples.com/advanced-middleware/
// Middleware type
type Middleware func(http.HandlerFunc) http.HandlerFunc
// NewMiddleware create middleware
func NewMiddleware(f http.HandlerFunc) Middleware {
middleware := func(next http.HandlerFunc) http.HandlerFunc {
handler :=... |
package p2
import (
"fmt"
"testing"
)
type Matrix struct {
a, b, c, d uint64
}
func (m *Matrix) multiply(o Matrix) {
m.a, m.b, m.c, m.d =
m.a*o.a+m.b*o.c,
m.a*o.b+m.b*o.d,
m.c*o.a+m.d*o.c,
m.c*o.b+m.d*o.d
}
func identityMatrix() Matrix {
return Matrix{a: 1, b: 0, c: 0, d: 1}
}
func cube() Matrix {
i ... |
package interface_tester
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/tidwall/gjson"
)
const (
empty = ""
tab = " "
)
type Meta struct {
Height string `json:"height"`
BlockHash string `json:"block_hash"`
InterchainTxCount string `json:"interchain_tx_count"`
}
... |
package handlers
import (
"net/http"
"github.com/dchest/captcha"
"github.com/labstack/echo"
)
func GenCaptcha() echo.HandlerFunc {
return func(c echo.Context) error {
d := struct {
CaptchaId string
}{
captcha.New(),
}
return c.JSON(http.StatusCreated, map[string]string{
"id": d.CaptchaId,
})... |
package runtime
import (
"context"
cniv1 "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/apis/k8s.cni.cncf.io/v1"
wcrd "github.com/rancher/wrangler/pkg/crd"
"k8s.io/client-go/rest"
"github.com/harvester/harvester/pkg/util/crd"
)
// createCRDs creates CRDs needed in integration tests
f... |
package main
import (
"time"
"github.com/go-kit/kit/log/level"
"bitbucket.org/garyyu/algo-trading/go-binance"
)
type OhlcDbTbl struct {
Id int64 `json:"id"`
Symbol string `json:"Symbol"`
OpenTime time.Time `json:"OpenTime"`
Open float64 `jso... |
// Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package vdi
import (
"context"
"strings"
"time"
"chromiumos/tast/common/fixture"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/ash"
"chromiumos/tast/l... |
package poc
import (
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"../logger"
)
// DrupalRCE - CVE-2018-7600
type DrupalRCE struct {
target string
cmd string
payload url.Values
Exploitable bool
}
// NewDrupalRCE .
func NewDrupalRCE() *DrupalRCE {
return &DrupalRCE{
payload: url.Va... |
// Copyright (c) 2016, Samvel Khalatyan. All rights reserved.
package issues
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"github.com/skhal/gh/cfg"
)
const (
search = iota
)
var (
resources = map[int]string{
search: "/search/issues",
}
)
// Quer... |
package db
import (
"fmt"
"time"
"github.com/NerdShoreDev/YEP/server/pkg/srv"
)
// Options provide database options
type Options struct {
User string
Password string
DataBaseName string
ClusterEndpoint string
CaFilePath string
ConnectTimeout time.Duration
QueryTimeout t... |
package main
import(
"fmt"
"net"
"code/chatroom/server/model"
"time"
)
func initUserDao() {
model.MyUserDao = model.NewUserDao(pool)
}
func main() {
initPool("localhost:6379",16,0,300 * time.Second)
initUserDao()
fmt.Println("服务器开始监听8889端口.....")
listen , err := net.Listen("tcp","localhost:8889")
if err != ... |
package httpmock_test
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"testing"
)
func assertBody(t *testing.T, resp *http.Response, expected string) bool {
defer resp.Body.Close()
helper(t).Helper()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
got := string(data)
if got != expec... |
package climbing_stairs
func climbStairs(n int) int {
cache := map[int]int{
0: 0,
1: 1,
2: 2,
}
return doClimbStairs(n, cache)
}
func doClimbStairs(n int, cache map[int]int) int {
if v, ok := cache[n]; ok {
return v
}
res := doClimbStairs(n-1, cache) + doClimbStairs(n-2, cache)
cache[n] = res
return ... |
/*
Copyright 2021 The Tekton Authors
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, softw... |
package handler
import (
"net/http"
"strconv"
"github.com/gorilla/mux"
)
func UpdateProducts(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
http.Error(w, "Unable to convert id", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type... |
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
)
// 读取文件需要经常进行错误检查,这个帮助方法可以精简下面 的错误检查过程。
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
// 也许大部分基本的文件读取任务是将文件内容读取到 内存中。
dat, err := ioutil.ReadFile("/tmp/dat")
check(err)
fmt.Print(string(dat))
// 你经常会想对于一个文件是怎么读并且读取到哪一部分 进行更多的... |
package vector
import "errors"
type Vector struct {
values []int
}
func Create(values ...int) Vector {
newVector := Vector{values: values}
return newVector
}
func Add(v1, v2 Vector) (Vector, error) {
if len(v1.values) != len(v2.values) {
return Vector{}, errors.New("can't add vectors of different cardinality"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.