text stringlengths 11 4.05M |
|---|
package command
import (
"fmt"
"strings"
"titan-auth/group"
"github.com/emicklei/go-restful"
"grm-service/command"
"grm-service/dbcentral/etcd"
"grm-service/dbcentral/pg"
"grm-service/service"
. "titan-auth/dbcentral/etcd"
. "titan-auth/dbcentral/pg"
"titan-auth/user"
)
type TitanAuthCommand struct {
... |
package core
func NewException(exception Type) *Type {
return &Type{Exception: &exception}
}
func NewStringException(message string) *Type {
return &Type{Exception: &Type{String: &message}}
}
func (node *Type) IsException() bool {
return node.Exception != nil
}
func (node *Type) AsException() *Type {
return nod... |
// 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 (
"fmt"
)
func divide(dividend int, divisor int) int {
if dividend == divisor {
return 1
}
if divisor == 1 {
return dividend
}
sgn := 1
if (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0) {
sgn = -1
}
if dividend < 0 {
dividend = -dividend
}
if divisor < 0 {
... |
package services
import (
"github.com/exproletariy/pip-services3-containers-examples/app-process-container-example-go/logic"
"net/http"
crefer "github.com/pip-services3-go/pip-services3-commons-go/refer"
rpc "github.com/pip-services3-go/pip-services3-rpc-go/services"
)
type AppExampleRestService struct {
*rpc.R... |
package main
import (
"go/token"
"strings"
"sync"
)
func CheckGoDocs(lc <-chan *Lexeme, outc chan<- *CheckedLexeme) {
var wg sync.WaitGroup
mux := LexemeMux(lc, 2)
wg.Add(2)
go func() {
ch := Filter(mux[0], DeclRootCommentFilter)
checkGoDoc(ch, outc)
wg.Done()
}()
go func() {
ch := Filter(Filter(mux[... |
package resp
import (
"github.com/EverythingMe/meduza/client"
"github.com/EverythingMe/meduza/errors"
"github.com/EverythingMe/meduza/protocol"
"github.com/EverythingMe/meduza/transport"
"github.com/dvirsky/go-pylog/logging"
redigo "github.com/garyburd/redigo/redis"
)
// Client wraps a connection to the server ... |
package socket
// Common is the normal data for messages passed on the console socket.
type Common struct {
// Type of message being passed
Type string `json:"type"`
}
// TerminalRequest is the normal data for messages passing a pseudoterminal master.
type TerminalRequest struct {
Common
// Container ID for the ... |
package users
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"log"
)
type User struct {
Name string `json:"name"`
Id string `json:"id"`
City string `json:"city"`
Age int `json:"age"`
Password string `json:"password"`
}
/*
We need to imple... |
package csnotes
import (
"fmt"
"testing"
)
func Test_entryNodeOfLoop(t *testing.T) {
listNode := ListNode{1, nil}
listNode2 := ListNode{2, nil}
listNode3 := ListNode{3, nil}
listNode4 := ListNode{4, nil}
listNode5 := ListNode{5, nil}
listNode6 := ListNode{6, nil}
listNode7 := ListNode{7, nil}
listNode8 := L... |
package ewallet
import (
"os"
goxendit "github.com/xendit/xendit-go"
"github.com/xendit/xendit-go/ewallet"
"github.com/imrenagi/go-payment/invoice"
)
// NewDana create xendit payment request for Dana
func NewDana(inv *invoice.Invoice) (*ewallet.CreatePaymentParams, error) {
return newBuilder(inv).
SetPayment... |
/*
@Time : 2019/5/4 13:48
@Author : yanKoo
@File : redis_data_sync
@Software: GoLand
@Description:
*/
package server
import (
pb "api/talk_cloud"
"cache"
"database/sql"
"db"
"log"
tg "pkg/group"
tgc "pkg/group_cache"
tu "pkg/user"
tuc "pkg/user_cache"
"sync"
)
type ConcurrentEngine struct {
Scheduler Sc... |
package main
type Article struct {
ID int `json:"id" validate:"min=1"`
Title string `json:"title" validate:"nonzero"`
Content string `json"content" validate:"nonzero"`
}
var articleList = []Article{
Article{ID: 1, Title: "Article 1", Content: "Article 1 Body"},
Article{ID: 2, Title: "Article 2", Content: "Articl... |
package cmd
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"os"
"strings"
awsecs "github.com/aws/aws-sdk-go/service/ecs"
"github.com/oberd/ecsy/ecs"
"github.com/spf13/cobra"
)
// envCmd represents the env command
var envCmd = &cobra.Command{
Use: "env [command]",
Short: "Used to manag... |
// Copyright The OpenTelemetry 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 agre... |
package main
import (
"encoding/json"
"fmt"
"github.com/urfave/cli"
"io/ioutil"
"net"
"os"
)
// Sends the file to the server
// The server will hopefully store it
func push(c *cli.Context) {
pushAll(c.Args()[0])
}
func pushAll(filename string) {
fileTemp, err := os.Open(filename)
if err != nil {
fmt.Print... |
// Copyright 2023 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 (
"reflect"
"fmt"
)
type Student struct {
Name string `heylink:"hahaha"`
}
func (s *Student) Print() {
fmt.Println("this is a student:", s.Name)
}
func main() {
var a int = 200
testReflect(a)
var stu = Student{
Name:"heylink",
}
testReflect(stu)
testStruct(&stu)
b := 200
//如果要更改... |
package testdata
import (
"github.com/frk/gosql/internal/testdata/common"
)
type InsertResultAfterScanSliceQuery struct {
Users []*common.User `rel:"test_user:u"`
Result []*common.User2
}
|
package negotiate
import (
"net/http"
"github.com/unrolled/render"
)
//Negotiator 는 render 를 감싸고
//ContentType 에 따른 전환(switch)을 처리한다.
type Negotiator struct {
ContentType string
*render.Render
}
//GetNegotiator 함수는 요청(http.Request)을 인자로 받아
//콘텐트 타입 헤더(ContentType header)에서
//콘텐트 타입(ContentType)을 가져온다.
func GetN... |
package ir
var ENGLISH_STOP_WORDS = []string{
"a",
"about",
"above",
"after",
"again",
"against",
"all",
"am",
"an",
"and",
"any",
"are",
"aren",
"as",
"at",
"be",
"because",
"been",
"before",
"being",
"below",
"between",
"both",
"but",
"by",
"can",
"cannot",
"could",
"couldn",
"d",
"did",
"didn",
"do",
"does",
"doesn... |
/*
Go Language Raspberry Pi Interface
(c) Copyright David Thorpe 2016-2018
All Rights Reserved
Documentation http://djthorpe.github.io/gopi/
For Licensing and Usage information, please see LICENSE.md
*/
package rfm69
import (
"time"
// Frameworks
"github.com/djthorpe/gopi"
"github.com/djthorpe/sensors"
... |
package types
import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
type GitRepository struct {
ApiVersion string
Kind string
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec GitRepositorySpec `json:"spec,omitempty"`
}
type GitRepositorySpec struct {
URL string `json:... |
package shbp
import (
"fmt"
"../../util"
algos "../analysis"
"../report"
"../traceReplay"
)
type ListenerAsyncSnd struct{}
type ListenerAsyncRcv struct{}
type ListenerSync struct{}
type ListenerDataAccessSHB struct{}
type ListenerDataAccessHB struct{}
type ListenerDataAccessSHBNOLS struct{}
type ListenerDataAcc... |
package domain
import (
"testing"
"github.com/gofrs/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
type UserServiceMock struct {
mock.Mock
}
func (m *UserServiceMock) FindUserByUsername(username string) (UserServiceResult, error) {
args := m.Called(username)
return args.Get(0... |
// 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 knative
import (
"strings"
"knative.dev/serving/pkg/apis/networking/v1alpha1"
)
// Somehow envoy doesn't match properly gRPC authorities with ports.
// The fix is to include ":*" in the domains.
// This applies both for internal and external domains.
// More info https://github.com/envoyproxy/envoy/issues/... |
package main
import "fmt"
func main() {
var test int
test = 1
fmt.Println(test)
test = 2
fmt.Println(test)
ExampleLol := "Chvfefe"
// fmt.Println(ExampleLol)
/*In line 11, it replaces `var YourName string` to something like `x := "y"`
And since := assigns, for example in line 11... |
package main
import "testing"
func TestP81(t *testing.T) {
cases := []struct {
in string
out int
}{
{"./p081_matrix_small.txt", 2427},
{"./p081_matrix.txt", 427337},
}
for _, c := range cases {
v := solve(c.in)
if v != c.out {
t.Errorf("P81: %v\tExpected: %v", v, c.out)
}
}
}
|
package gosnowth
import (
"bytes"
"encoding/xml"
"io"
"net/http"
"net/url"
"strings"
"testing"
"time"
)
func float64Ptr(f float64) *float64 {
return &f
}
func stringPtr(s string) *string {
return &s
}
type noOpReadCloser struct {
*bytes.Buffer
WasClosed bool
}
func (n *noOpReadCloser) Close() error {
... |
package random
import (
"fmt"
"strconv"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/irisnet/irismod/modules/random/keeper"
"github.com/irisnet/irismod/modules/random/types"
)
// InitGenesis stores genesis data
func InitGenesis(ctx sdk.Context, k keeper.Keeper, data types.GenesisState) {
if err := typ... |
package utils
import (
"fmt"
"time"
)
/**
timeid
*/
type U struct {
prefix string
c chan int
d chan struct{}
}
func NewU(t int64, n int) *U {
u := &U{
prefix: time.Unix(t, 0).Format("060102150405"),
c: make(chan int, n),
d: make(chan struct{}),
}
u.start()
return u
}
func (u *U) st... |
package dbBeans
import (
"strings"
"github.com/kinwyb/go/db"
)
//CREATE TABLE `bank` (
// `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '银行ID',
// `bank_name` varchar(255) NOT NULL COMMENT '银行名称',
// `bank_type` tinyint(3) unsigned NOT NULL DEFAULT '1' COMMENT '银行类型',
// `bank_account` varchar(255) NOT... |
package user
//UserInformation :
type UserInformation struct {
ID string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Phone string `json:"phone"`
ProfileImage string `json:"profileImage"`
Password string `json:"password"`
}
//LoginDetails :
type LoginDeta... |
package ecs
import "sort"
// State is an Entity-Component-System.
// It is simply a slice of systems.
type State []System
// AddSystem adds a system to the State
func (s *State) AddSystem(system System) {
*s = append(*s, system)
sort.Sort(s)
}
// Update calls Update in all systems.
// u can be ignored, or used fo... |
package core
import (
"context"
"fmt"
"sort"
"strconv"
"github.com/borchero/switchboard/api/v1alpha1"
"github.com/borchero/switchboard/backends"
"github.com/borchero/switchboard/core/utils"
"go.borchero.com/typewriter"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachine... |
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"github.com/jmoiron/sqlx"
"github.com/urfave/cli"
"github.com/xo/dburl"
"github.com/akito0107/xmigrate"
"github.com/akito0107/xmigrate/cmd"
"github.com/akito0107/xmigrate/toposort"
)
func main() {
app := cli.NewApp()
app.Name = "pgmigrate"
app.... |
package main
import (
"fmt"
"github.com/bijaythapaa/MakaluGo/lcr-game-packaged/lcr"
)
func main() {
fmt.Println("Welcome to LCR dice game :D")
g := lcr.NewGame()
fmt.Println("Please enter how many players will play the game?")
fmt.Println("Note: enter number more than 2.")
// need players count and will tak... |
package main
import "encoding/json"
// 连接器对象初始化
var h = hub{
connections: make(map[*connection]bool), // connections 注册了连接器
broadcast: make(chan []byte), // 从连接器发送的信息
register: make(chan *connection), // 从连接器注册请求
unregister: make(chan *connection), // 销毁请
}
// 处理ws 的逻辑实现
func (h *hub) run(... |
/*
* Copyright 2018, CS Systemes d'Information, http://www.c-s.fr
*
* 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 requir... |
package main
func P1Channel(param int) int {
sum := 0
ch := make(chan int)
go func() {
for i := 1; i < param; i++ {
if i%3 == 0 || i%5 == 0 {
ch <- i
}
}
close(ch)
}()
for s := range ch {
sum += s
}
return sum
}
func P1Normal(param int) int {
sum := 0
for i := 1; i < param; i++ {
if i%3... |
package catm
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00100102 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:catm.001.001.02 Document"`
Message *StatusReportV02 `xml:"StsRpt"`
}
func (d *Document00100102) AddMessage() *StatusReportV0... |
package auth
import "dmicro/gate/micro/plugin"
// Options 就是该插件的参数,目前只有 SkipperFunc 就是处理函数了。
// skipperFunc
type Options struct {
skipperFunc plugin.SkipperFunc
}
type Option func(*Options)
// new opts
func newOptions(opts ...Option) Options {
opt := Options{skipperFunc: plugin.DefaultSkipperFunc}
for _, o := ra... |
package main
import "os"
const (
exitOK = iota
exitError
)
var (
// Version is semantic version of the tool, set by goreleaser
Version = ""
// Revision is commit hash of the build, set by goreleaser
Revision = ""
)
func main() {
os.Exit(realMain())
}
func realMain() int {
return exitOK
}
|
package api
import (
"bytes"
"encoding/json"
"github.com/go-errors/errors"
"fmt"
"io"
"net/http"
"os"
"tezos-contests.izibi.com/backend/signing"
)
type Server struct {
Base string
ApiKey string
teamKeyPair *signing.KeyPair
client *http.Client
LastError string /* last error */
LastDetails ... |
package failure
import (
"fmt"
"net/http"
"github.com/bborbe/server/renderer"
"github.com/bborbe/server/renderer/content"
)
type failureView struct {
renderer renderer.Renderer
}
func NewFailureView(err error) *failureView {
v := new(failureView)
contentRenderer := content.NewContentRenderer()
contentRender... |
package lox
type exprVisitor interface {
visitBinary(eb *ExprBinary) interface{}
visitGrouping(eg *ExprGrouping) interface{}
visitLiteral(el *ExprLiteral) interface{}
visitUnary(eu *ExprUnary) interface{}
}
|
package pie_test
import (
"github.com/elliotchance/pie/v2"
"github.com/stretchr/testify/assert"
"testing"
)
func TestFloat64s(t *testing.T) {
assert.Equal(t, []float64(nil), pie.Float64s([]float64(nil)))
assert.Equal(t,
[]float64{92.384, 823.324, 453},
pie.Float64s([]float64{92.384, 823.324, 453}))
}
|
package main
import (
"bufio"
"encoding/csv"
"flag"
"fmt"
"io"
"log"
"os"
"strconv"
"strings"
)
type selector interface {
choose(cols []string) []string
}
func parseSelector(str string) (selector, bool) {
tokens := strings.Split(str, "-")
if len(tokens) < 1 || len(tokens) > 2 {
return nil, false
}
... |
// Copyright 2020 The Operator-SDK 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 ... |
package architecture
type Func struct {
Name string
Package string
Filename string
ParmTypes []Type
ReturnTypes []Type
}
|
package runner
import (
pb "github.com/tradingAI/proto/gen/go/scheduler"
"github.com/tradingAI/runner/plugins"
)
func creatTestRunner() (r *Runner) {
conf, _ := LoadConf()
r, _ = New(conf)
return
}
func createTestJob() (job *pb.Job) {
job = &pb.Job{
Id: uint64(123456789),
RunnerId: "test_runne... |
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use ... |
package db
import (
"fmt"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/helloferdie/stdgo/libslice"
"github.com/helloferdie/stdgo/logger"
"github.com/go-sql-driver/mysql"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
// ConnectionString -
func ConnectionString() string ... |
package PV
import (
"DataApi.Go/lib/common"
)
type SumPV struct {
Total int
}
type StatPagePV struct {
ID uint `gorm:"primary_key"`
DatetimeIntid int `gorm:"type:int(11);column:datetime_intid;"`
PageId string `gorm:"type:varchar(64);column:page_id;"`
PageTitle string `gorm:"type:varchar(2048);column:page... |
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
)
// DB is an interface that interacts with the addressBook database
type DB struct{}
func (d *DB) create(filename string) error {
file, err := os.Create(filename)
defer file.Close()
return err
}
func (d *DB) writeToFile(location string, data string) {
err ... |
// Package historicalbeat is a Metricbeat module that contains MetricSets.
package historicalbeat
|
package store
import (
"github.com/johnwyles/vrddt-reboot/pkg/reddit"
"github.com/johnwyles/vrddt-reboot/pkg/vrddt"
)
type Selector map[string]interface{}
// Store is the generic interface for a persistence store
type Store interface {
Cleanup() (err error)
CreateRedditVideo(redditVideo *reddit.Video) (err error... |
package keeper
import (
"context"
"errors"
"fmt"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
"github.com/octalmage/gitgood/x/gitgood/types"
"github.com/tendermint/tendermint/crypto"
)
func (k msgS... |
package alertmanager
import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
"github.com/go-openapi/strfmt"
"github.com/prometheus/alertmanager/api/v2/models"
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/require"
)
const ... |
package payments
import (
"encoding/json"
"io/ioutil"
"net/http"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
"github.com/loubard/sfapi/models"
"github.com/loubard/sfapi/sql"
)
// Fetch returns a payment resource based on the id
func Fetch(db *gorm.DB) func(w http.ResponseWriter, r *http.Request) {
retu... |
package iamiam
const (
// EmailProfile is a profile for returning the email.
EmailProfile string = "email"
// SimpleProfile is a profile for returning email, firstname and lastname.
SimpleProfile string = "simple"
)
// UserInfo contains info for profile creation.
type UserInfo struct {
Email string `json:"em... |
package _76_Minimum_Window_Substring
func minWindow(s string, t string) string {
//return minWindowWithSlidingWindow(s, t)
return minWindowWithSlidingWindowFast(s, t)
}
// 提升对比效率的滑动窗口
func minWindowWithSlidingWindowFast(s, t string) string {
if len(s) < len(t) { // bad case
return ""
}
var (
tcMap = ma... |
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
package wasmlib
const CoreAccounts = ScHname(0x3c4b5e02)
const CoreAccountsFuncDeposit = ScHname(0xbdc9102d)
const CoreAccountsFuncWithdrawToAddress = ScHname(0x26608cb5)
const CoreAccountsFuncWithdrawToChain = ScHname(0x437bc026)
const CoreAccoun... |
package main
import (
"fmt"
"log"
"os"
)
// Go标准库
// log, 内置的简单日志库
func main() {
//4. 日志的设置
log.SetPrefix("Test: ") // 设置前缀
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds)
file, err := os.OpenFile("./cli.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0755)
if err != nil {
log.Fatalln(err)
}
//5.设置日志... |
package ens
import (
"fmt"
"time"
"github.com/imroc/req"
"github.com/sirupsen/logrus"
"github.com/imsilence/gocmdb/agent/entity"
"github.com/imsilence/gocmdb/agent/gconf"
)
type ENS struct {
config *gconf.Config
Heartbeat chan interface{}
Register chan interface{}
Task chan interface{}
TaskR... |
package wordbreak
import (
"golang/helper"
"testing"
)
func Test(t *testing.T) {
s, wordDict := "leetcode", []string{"leet", "code"}
helper.Assert(wordBreak(s, wordDict), true, t)
s, wordDict = "applepenapple", []string{"apple", "pen"}
helper.Assert(wordBreak(s, wordDict), true, t)
s, wordDict = "catsandog",... |
package oauth20
import "time"
type Config struct {
ClientEndpoint string `envconfig:"APP_OAUTH20_CLIENT_ENDPOINT"`
PublicAccessTokenEndpoint string `envconfig:"APP_OAUTH20_PUBLIC_ACCESS_TOKEN_ENDPOINT"`
HTTPClientTimeout time.Duration `envconfig:"default=105s,APP_OAUTH20_HTTP_CLIEN... |
package graphql_test
import (
"net/http/httptest"
"testing"
"github.com/99designs/gqlgen/client"
"github.com/Sirupsen/logrus"
"github.com/Tinee/go-graphql-chat/graphql"
"github.com/Tinee/go-graphql-chat/inmemory"
)
func Test_graphql_mutationResolver(t *testing.T) {
inmem := inmemory.NewClient()
err := inmem.... |
package worker
import osm "github.com/JesseleDuran/gograph/osm/pbf"
//go:generate mockery --name S3Client
type S3Client interface {
Get(bucketName, objectName, fileName string) error
Put(bucketName, objectName, filePath string) (int64, error)
GetAllObjectKeys(bucketName string) []string
}
//go:generate mockery --... |
// Package clause.
package gigasecond
import (
"math"
"time"
)
// Constant declaration.
const testVersion = 4 // find the value in gigasecond_test.go
// API function. It uses a type from the Go standard library.
func AddGigasecond(t time.Time) time.Time {
return t.Add(time.Duration(math.Pow(10, 9)) * time.Durati... |
package main
import "fmt"
type Stack struct {
items []int
}
// Push will add value
func (s *Stack) Push(i int) {
s.items = append(s.items, i)
}
// Pop will remove value
func (s *Stack) Pop() int {
value := s.items[len(s.items)-1]
s.items = s.items[1 : len(s.items)-1]
return value
}
func main() {
myStack := S... |
package main
import "fmt"
func main() {
// slice of expenses
expenses := []Expense{}
keepGoing := true
for keepGoing {
fmt.Println("Expenses Manager")
fmt.Println("Choose one:")
fmt.Println("1. Add expense")
fmt.Println("2. Display expenses")
fmt.Println("3. Quit")
n := 0
fmt.Scanf("%d", &n)
sw... |
package mysort
import (
"fmt"
"math/rand"
"sort"
"testing"
)
// go语言的slice() 不仅可以对int类型的数组进行排序,也可以对struct类型的数组进行排序
// 排序函数如下
// 1.Slice() 排序不稳定
// 2.SliceStable() 稳定排序
// 3.SlicesSorted()判断是否已排序
type test struct {
value int
str string
}
func TestSortSlices(t *testing.T) {
s := make([]test, 5)
s[0] = test{... |
package internal
import "testing"
func TestDeque(t *testing.T) {
t.Run("pop", func(t *testing.T) {
var dq Deque[int]
dq.Push(1)
dq.Push(2)
if dq.Pop() != 2 {
t.Error("Didn't pop 2 first")
}
if dq.Pop() != 1 {
t.Error("Didn't pop 1 second")
}
if dq.Pop() != 0 {
t.Error("Didn't pop zero")
... |
package cgroup
import (
"bufio"
"os"
"path"
"strconv"
"strings"
)
// Info reads the cgroup mount info from /proc/cgroups
type Info struct {
Hierarchy int
NumCgroups int
Enabled bool
}
// GetCgroupV1Info read /proc/cgroups and return the result
func GetCgroupV1Info() (map[string]Info, error) {
f, err := ... |
// Package address contains utilities for handling moonbeam addresses.
package address
import (
"errors"
"strings"
"github.com/btcsuite/btcutil/base58"
)
// Encode a moonbeam address for the given bitcoin address and domain.
func Encode(bitcoinAddr, domain string) (string, error) {
if _, _, err := base58.CheckDe... |
package musictheory
import (
"fmt"
"math"
)
// Quality types
const (
PerfectType QualityType = iota
MajorType
MinorType
AugmentedType
DiminishedType
)
// IntervalFunc creates an interval at as specific step/degree
type IntervalFunc func(int) Interval
// Perfect interval
func Perfect(step int) Interval {
ret... |
package mysql
import (
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/xorm"
"cms/config"
"fmt"
"log"
"strings"
."cms/structs"
)
const BatchSize int = 500
var engine *xorm.Engine
func init() {
conf := config.AppConfig.MySQL
dataSourceName := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&... |
package parseBoolExpr
func parseBoolExpr(expression string) bool {
if expression == "" {
return false
}
switch expression[0] {
case 't':
return true
case 'f':
return false
case '!':
expressions, _ := getContentInBracket(expression, 1)
if len(expressions) != 1 {
return false
}
return !parseBoolE... |
package lexer
import (
"github.com/BOBO1997/monkey/token"
)
// Lexer is a struct holding the information of whole source code and the counter of lexer
type Lexer struct {
input string // the whole source
position int // the positing currently reading (alrerady read)
readPosition int // the next p... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-08-31 15:31
# @File : lt_95_Unique_Binary_Search_Trees_II.go
# @Description :
# @Attention :
*/
package v0
func generateTrees(n int) []*TreeNode {
if n ==0 {
return nil
}
return helper(1, n)
}
func helper(start int, end int) []*TreeNode {
if start >... |
/*
Copyright 2020 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 agreed to in writing, soft... |
package study_avltree
import (
"fmt"
"strings"
)
func toString(n *node) string {
if n == nil {
return ""
}
return fmt.Sprintf("[%v:%v:%v]", n.key, n.value, n.height)
}
func allEntryIsNotNil(list []*node) bool {
for _, e := range list {
if e != nil {
return true
}
}
return false
}
... |
package teesdk
type TrustClient interface {
Close()
Submit(method string, cipher string) (string, error)
}
|
package main
import "fmt"
type myFloat float64
func (f *myFloat) Scale(s float64) { // Methods with pointer receivers can modify the value
*f = *f * myFloat(s)
}
func main() {
v := myFloat(3.14159265)
v.Scale(100.00)
fmt.Println(v)
}
|
package adapter
import (
"io"
"mqtt-adapter/src/logger"
"github.com/sirupsen/logrus"
"github.com/surgemq/surgemq/service"
)
type TestSubscriber struct {
needPanic bool
}
func (s TestSubscriber) Subscribe(topic string, writer io.Writer) {}
func (s TestSubscriber) SubscribeBridge(topic string, msgChan chan<- s... |
package main
import (
"studentDetails/gomodule/routes"
"github.com/gin-gonic/gin"
)
func main() {
// My router configuration with rest calls
router := gin.Default()
router.GET("/student", routes.GetStudentDetails)
router.POST("/student", routes.PostStudentDetails)
router.GET("/student/:id", routes.GetStuden... |
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
)
func main() {
envVars, err := parseJSONFile("config.dev.json")
if err != nil {
log.Fatal("Failed to parse json config", err)
}
for varKey := range envVars {
log.Printf("Set key %s and value %s", varKey, envVars[varKey])
err := os.Sete... |
package sheets
import (
"strings"
"testing"
)
var configTests = []struct {
config string
errExpected bool
}{
{"{}", true},
{`{
"type": "service_account",
"project_id": "testproject-123456",
"private_key_id": "abcdef",
"private_key": "-----BEGIN PRIVATE KEY-----\nnotarealkey\n-----END PRIVATE KEY---... |
package controllers
import (
"lili_style_test/src/models"
"lili_style_test/src/utils"
)
func GetBusinessStanceData(userdata []string) models.BusinessStance {
answer := userdata[70:83]
// はいで加点を整形
yesAdd := answer[0:11]
yesAdd = append(yesAdd,answer[12])
// いいえで加点を整
var noAdd []string
noAdd = append(noAdd,an... |
// Copyright 2023 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 slack
import (
"context"
"net/url"
)
// RotateTokens exchanges a refresh token for a new app configuration token
func (api *Client) RotateTokens(configToken string, refreshToken string) (*TokenResponse, error) {
return api.RotateTokensContext(context.Background(), configToken, refreshToken)
}
// RotateTok... |
package main
import (
"bufio"
"fmt"
"log"
"net"
"strconv"
"sync"
"time"
)
func main() {
listener, err := net.Listen("tcp", ":6430")
if err != nil {
panic(err)
}
go broadcaster()
for {
conn, err := listener.Accept()
if err != nil {
log.Println(err)
continue
}
go handleConn(conn)
}
}
ty... |
package leetcode
func twoSum(nums []int, target int) []int {
index :=[]int{0,0}
for i := 0; i < len(nums); i++ {
for j := 0; j < i; j++ {
if nums[i]+nums[j] == target {
index[0] = j
index[1] = i
return index
}
}
}
return index
}
|
package main
import "fmt"
func main() {
nums :=[]int{0,1,0,1,0,1,99}
fmt.Println(singleNumber(nums))
}
func singleNumber(nums []int) int {
res :=0
m := make(map[int]int)
for _, v := range nums {
m[v] += 1
}
for k, v := range m {
if v == 1 {
res = k
}
}
return res
}
|
package service
import (
"context"
"fmt"
"io"
"net/http"
"time"
pbCQRS "github.com/go-ocf/cloud/resource-aggregate/pb"
pbRA "github.com/go-ocf/cloud/resource-aggregate/pb"
pbRD "github.com/go-ocf/cloud/resource-directory/pb/resource-directory"
"github.com/go-ocf/kit/log"
kitNetGrpc "github.com/go-ocf/kit/ne... |
package main
import (
"context"
"flag"
"fmt"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"path"
"syscall"
"github.com/gin-gonic/gin"
"github.com/lizhaoliu/konsen/v2/core"
"github.com/lizhaoliu/konsen/v2/rpc"
"github.com/lizhaoliu/konsen/v2/store"
"github.com/lizhaoliu/konsen/v2/web/httpserver"
"gith... |
package memrepo
import (
"github.com/scjalliance/drivestream/commit"
"github.com/scjalliance/drivestream/resource"
)
var _ commit.StateReference = (*CommitState)(nil)
// CommitState is a reference to a commit state.
type CommitState struct {
repo *Repository
drive resource.ID
commit commit.SeqNum
state com... |
package riak
import (
"github.com/bmizerany/assert"
"testing"
"time"
)
type DocumentModel struct {
FieldS string `riak:"string_field"`
FieldF float64 `riak:"float_field"`
FieldB bool
Model
}
func TestModel(t *testing.T) {
// Preparations
client := setupConnection(t)
assert.T(t, client != nil)
// Create ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.