text stringlengths 11 4.05M |
|---|
package origin
import (
"net"
"sync"
"time"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/runtime/schema"
utilwait "k8s.io/apimachinery/pkg/util/wait"
kctrlmgr "k8s.io/kubernetes/cmd/kube-controller-manager/app"
cmapp "k8s.io/kubernetes/cmd/kube-controller-manager/app/options"
kapi "k8s.io/kubernetes/pk... |
package auth
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"strings"
"testing"
"time"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/armor"
"gopkg.in/yaml.v2"
"github.com/square/p2/pkg/logging"
"github.com/square/p2/pkg/types"
)
// TestSigned is a stand-in for an auth.Manifest or auth.Digest.
type... |
package myip
import (
"testing"
)
func TestGetIP(t *testing.T) {
var ip string
var err error
if ip, err = getIPFromTaobao(); err != nil {
t.Fatal(err)
}
t.Logf("get ip from taobao: [%s]", ip)
if ip, err = getIPFromIPCN(); err != nil {
t.Fatal(err)
}
t.Logf("get ip from ip.cn: [%s]", ip)
}
|
package friend
import (
"github.com/stretchr/testify/assert"
"testing"
)
var testFriend *Friend
func TestFriend(t *testing.T) {
t.Run("testNewFriend", testNewFriend)
t.Run("testGreetFriend", testGreetFriend)
t.Run("testCelebrateBirthday", testCelebrateBirthday)
t.Run("testLiesAboutAge", testLiesAboutAge)
t.Ru... |
package intToRoman
import "fmt"
func intToRoman(num int) string {
baseTable := [...][2]interface{}{
{1000, "M"},
{900, "CM"},
{500, "D"},
{400, "CD"},
{100, "C"},
{90, "XC"},
{50, "L"},
{40, "XL"},
{10, "X"},
{9, "IX"},
{5, "V"},
{4, "IV"},
{1, "I"},
}
var romanString string
for num != 0... |
package main
import (
"fmt"
"strconv"
"reflect"
"encoding/json"
)
/**
1 方法时作用在接收者上的函数,类型和其方法构成类,类型的所有方法称为方法集
2 对于访问结构体的值,不需要区分变量是值还是指针,会自动转换;结构体值方法可以通过指针访问,结构体指针方法不能通过值访问
3 结构体在内存中按块存储,性能相较于引用会更有优势
4 类型和方法不需要在同一个文件中,但需要在同一个包中
*/
type Man struct {
name string
age int
}
func structInit() {
var man1 Man
man1... |
package main
import "strconv"
type student struct {
targetNum int
}
func NewStudent(num int) *student {
return &student{targetNum: num}
}
func (s *student) Task(taskResources interface{}, num, taskSum int, leader ILeader) {
if resource, ok := taskResources.([]int); ok {
groupNum := len(resource) / taskSum
if... |
package common
import (
"github.com/zond/godip/state"
"github.com/zond/godip/variants/classical"
"github.com/zond/godip/variants/classical/orders"
"github.com/zond/godip/variants/common"
dip "github.com/zond/godip/common"
)
type Phase struct {
Season dip.Season
Year int
Type dip.Phas... |
package main
import (
"github.com/baotingfang/gomvc"
"github.com/baotingfang/gomvc/examples/todo/todo"
/**
注意: 千万不要忘记下面这个导入,这会导入所有的controller
*/
_ "github.com/baotingfang/gomvc/examples/todo/todo/controllers"
"log"
"fmt"
)
func main() {
fmt.Println("welcome to gomvc world!")
route_table := &gomvc.RouteTabl... |
package filters
import (
"testing"
mocks "github.com/neuronlabs/neuron-mocks"
"github.com/stretchr/testify/require"
"github.com/neuronlabs/neuron-core/config"
"github.com/neuronlabs/neuron-core/controller"
"github.com/neuronlabs/neuron-core/query"
_ "github.com/neuronlabs/neuron-mocks"
"github.com/neuronla... |
package main
var PartsOfSpeech = map[string]string{
"n": "noun",
"v": "verb",
"j": "adjective",
"r": "adverb",
"prp": "preposition",
"prn": "pronoun",
"crd": "cardinal number",
"crj": "conjunction",
"exc": "interjection",
"det": "article",
"abb": "abbreviation",
"x": "particle",
"ord": "ordinal number",
... |
package sqly
import (
"database/sql"
"database/sql/driver"
"encoding/hex"
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
"time"
)
// NullTime is an alias for sql.NullTime
type NullTime sql.NullTime
// Scan implements the Scanner interface for NullTime
func (ns *NullTime) Scan(val interface{}) error {
... |
package main
import (
"fmt"
"io/ioutil"
"log"
"regexp"
"strings"
)
const (
scriptFile = "index.js"
templateFile = "index-dev.md"
outputFile = "index.md"
)
var (
marker = regexp.MustCompile(`\<script src="index\.js"\>\</script\>`)
insertionTemplate = "<script>\n%s\n</script>"
)
func main() {... |
package broker
// import . "../topic_manager"
//
// type AdminManager struct {
// MyServer *Server
// MyTopicManager TopicManager
// }
//
// func (adminManager *AdminManager) CreateAdminManager(server *Server) {
// adminManager.MyServer = server
// adminManager.MyTopicManager = server.GetTopicManager()
// }
//... |
package _745_Prefix_and_Suffix_Search
import "testing"
func TestCase(t *testing.T) {
var wf WordFilter
//wf = Constructor([]string{"apple"})
//if ret := wf.F("a", "e"); ret != 0 {
// t.Logf("wrong ret with %d", ret)
//}
wf = Constructor([]string{"cabaabaaaa", "ccbcababac", "bacaabccba", "bcbbcbacaa", "abcaccb... |
package logic
import (
"os"
"time"
)
type Remote struct {
BaseLogic
}
func (remote *Remote) Run(sigs <-chan os.Signal) {
for {
// if <-sigs == os.Interrupt {
// remote.GetRobot().Stop()
// break
// }
switch remote.GetRobot().IrSensorValue(0) {
case "1":
remote.GetRobot().GoForward()
case "2... |
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello from main()...1")
f1 := func() {
fmt.Println("Shoutout from func expression(no parameters)")
}
f2 := func(x string) {
fmt.Println("Shoutout from func expression with parameter :: ", x)
}
f1()
fmt.Println("He... |
package main
import (
//Golang 标准库
"fmt"
"net/http"
//第三访库
log "github.com/cihub/seelog"
"github.com/gorilla/mux"
//项目相关
"location.service/config"
"location.service/controller"
)
func main() {
// 路由
router := mux.NewRouter()
// 日志初始化
defer log.Flush()
initLogComponent()
// URL映射配置
subRouter := rou... |
package algorithm
func findConnectionJourneys(startStation string, endStation string) {
//journeyGroups:=list.New()
//startStationJourneys=stations.[startStation].getJourneys()
//endStationJourneys=stations.[startStation].getJourneys()
}
func main() {
}
|
/*
* Copyright © 2019-2022 Software AG, Darmstadt, Germany and/or its licensors
*
* SPDX-License-Identifier: Apache-2.0
*
* 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://... |
package main
import (
"fmt"
"strings"
)
func interpret(command string) string {
command = strings.ReplaceAll(command,"(al)", "al")
command = strings.ReplaceAll(command,"()", "o")
return command
}
func main(){
command := "G()(al)"
fmt.Println(interpret(command))
}
|
/*
This module has basic dataStructures and functions
that may be required for creation and management of
custom layer.
*/
package packaging
import (
"encoding/binary"
"net"
"github.com/LaundeLapate/RouteIt/pkg"
"github.com/LaundeLapate/RouteIt/pkg/services/customerrors"
"github.com/sirupsen/logrus"
)
type Cust... |
package easy929
func numUniqueEmails(emails []string) int {
set := make(map[string]struct{})
for _, email := range emails {
byteEmail := []byte(email)
var domain []byte
for idx := range byteEmail {
if byteEmail[len(byteEmail)-1-idx] == "@"[0] {
break
}
domain = append(domain, byteEmail[len(byteEma... |
package machinery_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"k8s.io/client-go/tools/clientcmd/api"
"github.com/kralicky/kit/pkg/machinery"
)
var _ = Describe("Apply", func() {
It("should correctly add clusters", func() {
existing, incoming := sampleClusters(1), sampleClusters(1, 2)
... |
package git
import (
"reflect"
"testing"
)
func TestGetRemoteNames(t *testing.T) {
got, err := getRemoteNames()
if err != nil {
t.Errorf("error getting remotes: %s", err)
}
// will fail on a feature branch
want := []string{"origin", "upstream"}
if ! reflect.DeepEqual(got, want) {
t.Errorf("got %q, wante... |
package port
import (
"net"
"strconv"
)
type Port int16
const (
HTTPS = Port(433)
HTTP = Port(80)
MYSQL = Port(3306)
REDIS = Port(6379)
SHELL = Port(22)
FTP = Port(21)
)
const (
MIN = 1
MAX = 1 << 16 - 1
)
func (p Port) toInt() int {
return int(p)
}
func (p Port) String() string {
return strconv.It... |
package main
import (
"errors"
"github.com/stretchr/testify/assert"
"sync"
"testing"
)
func TestSetFuncField(t *testing.T) {
path := `../test/client.yaml`
ycp, _ := NewYamlConfigProvider(path)
_ = InitApplication(WithCfgProvider(ycp))
helloService := &hello{
}
SetFuncField(helloService)
res, err := he... |
// 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 main
import (
//"encoding/csv"
"github.com/davecgh/go-spew/spew"
"log"
"net/http"
)
func main() {
req, err := http.NewRequest("GET", "http://rbl-check.org/rbl_api.php?ipaddress=95.89.93.164", nil)
if err != nil {
log.Fatalln(err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fat... |
package controller
import (
"Seaman/model"
"Seaman/service"
"Seaman/utils"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/mvc"
"github.com/kataras/iris/v12/sessions"
"strconv"
)
/**
* 角色控制器结构体:用来实现处理角色模块的接口的请求,并返回给客户端
*/
type AppRoleController struct {
//上下文对象
Ctx iris.Context
AppRoleService ... |
package Util
import "sync"
/**
滑动窗口
*/
type record struct {
sucess int
fail int
timeout int
requestNum int
}
type Sliding struct {
link []record
maxLength int
length int
head int
end int
lock sync.Mutex
}
func New(maxLength int) *Sliding {
return &Sliding{
maxLength: maxLength,
link: make([]record,... |
package main
import (
"./srcfile"
)
func main() {
list, _ := srcfile.TextList(`C:\git\transtool\abcd.txt`)
list2, _ := srcfile.TransList(`C:\git\transtool\init.txt`)
map1, _ := srcfile.MakeMap(list, list2)
for _, m := range map1 {
println(m.Org, m.Trans)
}
}
|
// duck.
package main
import (
"fmt"
)
type duck interface {
SayHello() string
}
type cat struct {
name string
age int
}
func (c *cat) SayHello() string {
return "hello from cat"
}
type dog int
func (d dog) SayHello() string {
return "hello from dog"
}
func main() {
var d duck
d = &cat{}
fmt.Println(d.... |
package common
// ObjectID represnts unique identifier of an object
// (which is likely to be used as a primary key in RDBMS)
type ObjectID = int
// Model describes something that can be stored within a RDBMS
type Model interface {
GetObjectID() ObjectID
SetObjectID(ObjectID)
}
// Object is a default implementatio... |
package main
import "fmt"
import "math"
import "github.com/fogleman/gg"
//import "sync"
func main() {
fmt.Println("Running...")
frames := 1
zoomFactor := 0.5
focalPointRe := 0.0
focalPointIm := 1.0
size := 1000
escapeLoops := 100
threshhold := 4.0
canvas := gg.NewContext(size, size... |
package session
import (
"fmt"
"github.com/btnguyen2k/henge"
"github.com/btnguyen2k/prom"
"main/src/gvabe/bo"
)
// NewSessionDaoCosmosdb is helper method to create CosmosDB-implementation of SessionDao.
func NewSessionDaoCosmosdb(sqlc *prom.SqlConnect, tableName string) SessionDao {
spec := &henge.CosmosdbDaoS... |
package config
type Stage int
const (
StageDev Stage = iota
StageSIT
)
func (s Stage) String() string {
return [...]string{"dev", "sit"}[s]
}
|
//Printing a struct
package main
func main () {
type student struct {
id int
gpa float64
}
var sasuke student
print(1, 0x00, 07, true,'\n',`raw`, "string");
println(1,true,'\n',`raw`, "string");
print(sasuke);
}
|
// Package pq implements the github.com/neuronlabs/neuron-core repository
// with the modular filter with the support.
// The package uses github.com/jackc/pgx Postgres driver.
package postgres
|
package leetcode
var m = make(map[int]int, 0)
func climbStairs(n int) int {
if n <= 0 {
return 0
}
if n == 1 {
return 1
}
if n == 2 {
return 2
}
if r, ok := m[n]; ok {
return r
}
ret := climbStairs(n-1) + climbStairs(n-2)
m[n] = ret
return ret
}
func climbStairs01(n int) int {
if n <= 2 {
retur... |
package templates
type GoshimmerConfigParams struct {
ApiPort int
}
const GoshimmerConfig = `
{
"analysis": {
"client": {
"serverAddress": "node1.goshimmer.dev:188"
},
"server": {
"bindAddress": "0.0.0.0:16178"
},
"dashboard": {
"bindAddress": "0.0.0.0:80",
"dev": true
... |
/*
redux is a library for redux, a top down software build tool
which implements and extends the redo concept somewhat sparsely
described by [DJ Bernstein](http://cr.yp.to/redo.html).
To install it, run
$ go get github.com/gyepisam/redux/redux
The command
$ redux help
provides built-in help, which is augment... |
package main
import "fmt"
func main() {
data:=[]float32{ 34.0, 27.0, 45.0, 82.0, 22.0 }
total:= data[0] + data[1] + data[2] + data[3] + data[4]
average:= total / 5.0
fmt.Printf("Нийт %f Дундаж %f\n", total, average)
} |
package request
import (
"database/sql"
"errors"
"fmt"
"strconv"
"strings"
)
// requestType - enum of types
type requestType int
// Requests
const (
UNDEFINED requestType = 0
SELECT requestType = 1
UPDATE requestType = 2
INSERT requestType = 3
DELETE requestType = 4
)
// Request structure
type... |
package main
import (
"database/sql"
"flag"
"fmt"
"net/http"
"os"
"github.com/aws/aws-sdk-go/aws/defaults"
_ "github.com/go-sql-driver/mysql"
"github.com/malware-unicorn/go-keybase-chat-bot/kbchat"
"github.com/malware-unicorn/go-keybase-chat-bot/kbchat/types/chat1"
"github.com/malware-unicorn/managed-bots/b... |
/*
Copyright 2021 The KubeVela 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, so... |
package main
import (
"fmt"
"testing"
"time"
"gonum.org/v1/plot"
"gonum.org/v1/plot/plotter"
"gonum.org/v1/plot/plotutil"
"gonum.org/v1/plot/vg"
)
// TestLatency runs a single stream so we can look at blocking profiles
// for different buffer sizes.
func TestLatency(t *testing.T) {
bufSize := 100
fmt.Print... |
package stacks
import (
"testing"
)
func TestStacK_Len(t*testing.T){
var myStack Stack
myStack.Push(1)
myStack.Push(2)
myStack.Push("test")
if myStack.Len() == 3 {
t.Log("Pass Stack.Len")
}else{
t.Error("Failed Stack.Len")
}
}
func TestStacK_Cap(t*testing.T){
myStack := make(Stack,3)
if myStack.Cap() =... |
package stack
import (
"testing"
)
func BenchmarkPushMix(b *testing.B) {
s := New()
for i := 0; i < b.N; i++ {
s.Push(i)
}
}
func BenchmarkMix(b *testing.B) {
s := New()
for i := 0; i < b.N; i++ {
s.Push(i)
s.Pop()
}
}
func Test_IsEmpty(t *testing.T) {
s := New()
if !s.IsEmpty() {
t.Error("Fail!... |
// Actions pkg exists so that we have a place to store methods that are called
// by either the gRPC server, etcd broadcast consumer or both.
//
// This pkg generally houses server-related methods. It should NOT be used for
// performing etcd related functionality (to avoid circular import issues).
//
// NOTE: We shoul... |
// Copyright 2020 Clivern. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package tower
import (
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/clivern/walrus/core/driver"
"github.com/clivern/walrus/core/model"
"github.com/clivern/... |
package google
import (
"bufio"
"os"
log "github.com/sirupsen/logrus"
)
func dumpRequest(requestURL string, responseText string) {
f, err := os.OpenFile("translation-errors.txt", os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
w := bufio.NewWriter(f)
w.WriteString(requestURL)
w.WriteRune(... |
package repositories
import (
"context"
"github.com/go-redis/redis"
)
var ctx = context.Background()
// StorageManager defines interface
type StorageManager interface {
Load(key string) (string, error)
Store(key string, data []byte) error
}
type storageManager struct {
redisClient *redis.Client
}
// NewStorag... |
package mtest
import (
"os"
)
var (
bridgeAddress = os.Getenv("BRIDGE_ADDRESS")
host1 = os.Getenv("HOST1")
host2 = os.Getenv("HOST2")
host3 = os.Getenv("HOST3")
worker = os.Getenv("WORKER")
sshKeyFile = os.Getenv("SSH_PRIVKEY")
sabactlPath = os.Getenv("... |
// Copyright 2016 Walter Schulze
//
// 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 The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package ptracejson
import (
"testing"
jsoniter "github.com/json-iterator/go"
"github.com/stretchr/testify/assert"
otlpcollectortrace "go.opentelemetry.io/collector/pdata/internal/data/protogen/collector/trace/v1"
otlptrace "go.opente... |
package checkVersion
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
"gitlab.com/NagByte/Palette/db/wrapper"
"gitlab.com/NagByte/Palette/service/common"
)
type handler struct {
baseURI string
db database
handler http.Handler
}
func New(db wrapper.Database) *handler {
handl := hand... |
//nolint
package keeper
import (
"github.com/irisnet/irishub/app/v1/auth"
sdk "github.com/irisnet/irishub/types"
"math"
"strconv"
)
// fee factor formula: (ln(len({name}))/ln{base})^{exp}
const (
FeeFactorBase = 3
FeeFactorExp = 4
)
// GatewayCreateFeeHandler performs fee handling for creating a gateway
func ... |
package engine
import (
"log"
"github.com/gin-gonic/gin"
)
// handlers registers all of the default routes for the API server. This is a
// separate method so that other routes can be added *after* the defaults but
// *before* the server is started.
func (s *APIServer) handlers() {
r := s.router
// Register mid... |
package albelbv2
import (
"testing"
"github.com/aws/aws-sdk-go/service/elbv2"
"github.com/aws/aws-sdk-go/service/elbv2/elbv2iface"
"github.com/kubernetes-sigs/aws-alb-ingress-controller/pkg/util/log"
)
type mockedELBV2DescribeLoadBalancers struct {
elbv2iface.ELBV2API
Resp elbv2.DescribeLoadBalancersOutput
}
... |
package main
import (
"crypto/tls"
"fmt"
"log"
"net/http"
)
func index(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "hello!")
}
func main() {
cert, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
if err != nil {
log.Fatal(err)
}
l, err := tls.Listen("tcp", "localhost:8443", &tls.Config{
Cer... |
package storage
import (
"fmt"
"os"
"path/filepath"
)
type GarbageCollector struct {
fs fs
}
func NewGarbageCollector(fs fs) GarbageCollector {
return GarbageCollector{
fs: fs,
}
}
func (g GarbageCollector) Remove(dir string) error {
bblStateJson := filepath.Join(dir, STATE_FILE)
err := g.fs.Remove(bblSta... |
package main
import (
"fmt"
)
func main() {
fmt.Println(fatorial(6))
fmt.Println(loops(6))
}
func fatorial(x int) int {
if x == 1 {
return x
}
return x * fatorial(x-1)
}
func loops(x int) int {
total := 1
for x > 1 {
total *= x // total = total * x
x--
}
return total
}
|
package snapshot
import (
"time"
)
type Snapshot struct {
Created time.Time
Name string
ID string
}
|
package clcv2cli
/*
* Methods and data pertaining to commandline clients.
*/
import (
"flag"
"os"
"time"
"github.com/grrtrr/clcv2"
)
// Global (commandline flag) variables
var (
g_user, g_pass string /* Command-line username/password */
g_acct string /* Account Alias to use ... |
package byscaler
import (
"bylib/bylog"
"bylib/byopenwrt"
"bylib/byutils"
"bytes"
"encoding/binary"
"fmt"
"github.com/goburrow/serial"
"io"
"sync"
"time"
)
const(
CMD_CLEAR_ZERO = 0 //清零
CMD_READ_WGT = 1 //查询单个或者全部称台的重量和状态
CMD_QUERY_CHANGE_SENSOR=2 //查询重量有更改的称台
CMD_QUERY_ERROR_SENSOR=3 //查询有故障的传感器.
CMD_... |
package git
/*
#include <git2.h>
*/
import "C"
import (
"runtime"
"unsafe"
)
// This object represents the possible operations which can be
// performed on the collection of notes for a repository.
type NoteCollection struct {
doNotCompare
repo *Repository
}
// Create adds a note for an object
func (c *NoteColl... |
package main
import (
"sync"
"github.com/Shopify/sarama"
)
type Partition struct {
l sync.Mutex
base int64
cache []*sarama.Message
}
const maxCache = 1024
func NewPartition() *Partition {
return &Partition{}
}
func (p *Partition) Produce(set *sarama.MessageSet) int64 {
p.l.Lock()
defer p.l.Unlock()
... |
/*
Copyright 2019 Dmitry Kolesnikov, 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... |
package telegraf
// Processor is a processor plugin interface for defining new inline processors.
// these are extremely efficient and should be used over StreamingProcessor if
// you do not need asynchronous metric writes.
type Processor interface {
PluginDescriber
// Apply the filter to the given metric.
Apply(i... |
package mt
type AlignType uint8
const (
NoAlign AlignType = iota
WorldAlign
UserAlign
)
//go:generate stringer -type AlignType
type TileFlags uint16
const (
TileBackfaceCull TileFlags = 1 << iota
TileAbleH
TileAbleV
TileColor
TileScale
TileAlign
)
//go:generate stringer -type TileFlags
type TileDef stru... |
package dsp
// DCBlock is an operation that blocks DC signal to keep a signal centered around zero
type DCBlock struct {
lastIn, lastOut Float64
}
// Tick advances the operation
func (dc *DCBlock) Tick(in Float64) Float64 {
out := in - dc.lastIn + dc.lastOut*0.995
dc.lastIn, dc.lastOut = in, out
return out
}
|
package problem0547
func findCircleNum(M [][]int) int {
if len(M) == 0 {
return 0
}
found := make([]bool, len(M))
num := 0
for i := 0; i < len(M); i++ {
if !found[i] {
dfs(M, i, found)
num++
}
}
return num
}
func dfs(M [][]int, i int, found []bool) {
found[i] = true
for j := 0; j < len(M); j++ {
... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-09-11 09:07
# @File : lt_147_Insertion_Sort_List.go
# @Description :
# @Attention :
*/
package v0
/*
插入排序: 链表的实现方式
1. for 循环放到数组中,再插入排序
插入排序: 有序中插入
2. for循环中,发现不匹配的,再从头开始
*/
func insertSort(data []int) {
for i := 1; i < len(data); i++ {
j := i - 1... |
package main
import "fmt"
// 2 бүхэл тоон хувьсагчийн утгыг хооронд нь солино.
func swap(p1 *int, p2 *int) {
tmp := p1
p1 = p2
p2 = tmp
}
func main( ) {
a := 10
b := 20
fmt.Printf( "Анхны утгууд: a = %d; b = %d\n", a, b )
swap( &a, &b )
fmt.Printf( "Шинэ утгууд: a = %d; b = %d\n", a, b )
}
|
package mos6502
import (
"fmt"
"log"
"github.com/KaiWalter/go6502/pkg/addressbus"
)
// adressModeFunc defines a function executing the adress mode of an operation
type adressModeFunc func() int
// operationFunc defines a function executing an operation
type operationFunc func() int
type operationDefinition stru... |
package main
func main() {
}
/*
1.标准库源码对Go工具非常重要, (godoc, gocode, go build ...etc)等Go工具均需要读取标准库源码才能完成工作
2.标准库源码都是经过预编译的, 编译后的文件称为归档文件, 以.a为扩展名
1.归档文件是特殊的GO静态库文件, 由Go构建工具创建, 并在编译和链接最终程序时被使用
2.归档文件可以提高构建速度
3.构建过程中, 无法指定这些文件, Go工具链知道何时使用归档文件 / 从源码重新构建
*/
|
package collector
import (
"log"
"os"
"github.com/prometheus/client_golang/prometheus"
)
func init() {
registerCollector("tablesize", true, NewTableCollector)
}
const (
tableCollectorSubsystem = "tablesize"
)
type tableCollector struct {
rowTotal *prometheus.Desc
}
var (
tableRowTotal = prometheus.NewDesc... |
package main
import (
"fmt"
"log"
"os"
"flag"
"path/filepath"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
var (
namespaceName = flag.String("namespace", "", "Name of the namespace from which you want to list the Pods")
)... |
package vm_test
import (
"fmt"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
bosherr "github.com/cloudfoundry/bosh-agent/errors"
boshlog "github.com/cloudfoundry/bosh-agent/logger"
bmconfig "github.com/cloudfoundry/bosh-micro-cli/config"
bmdepl "github.com/cloudfoundry/bosh-micro-cli/deployment"
bmev... |
// Package api provides the HTTP interface.
package api
import (
"fmt"
"io"
"net/http"
"github.com/julienschmidt/httprouter"
"github.com/pascaldekloe/metrics"
thunder "github.com/samsarahq/thunder/graphql"
"gitlab.com/thorchain/midgard/internal/graphql"
)
// Handler serves the entire API.
var Handler http.Ha... |
package main
import (
"sync"
"sync/atomic"
)
type Once struct {
m sync.Mutex
done uint32
}
func (o *Once)Do(f func()) {
if atomic.LoadUint32(&o.done)==1 {
return
}
o.m.Lock()
defer o.m.Unlock()
if o.done==0 {
defer atomic.StoreUint32(&o.done,1)
f()
}
}
type Singleton struct {}
var (
Instances *Si... |
package main
import "fmt"
func main() {
x := map[string][]string{
"bond_james": []string{"Shaken, not stirred", "Martinis", "Women"},
"moneypenny_miss": []string{"Jamse Bond", "litterature", "Computer Science"},
"no_dr": []string{"being evil", "ice cream", "sunset"},
}
x["alavi_alireza"] = []... |
package main
import (
"flag"
"fmt"
"strings"
"github.com/v4run/timeformat"
)
func main() {
flag.Parse()
fmt.Println(timeformat.Layout(strings.Join(flag.Args(), " ")))
}
|
package arthurhltclient
import (
"eureka/vars"
"strconv"
"time"
"github.com/ArthurHlt/go-eureka-client/eureka"
)
// port enable 필드가 bool로 정의 되어 있어서 에러남.
type ArthurHltClient struct {
client *eureka.Client
instance *eureka.InstanceInfo
ticker *time.Ticker
}
func NewClient() *ArthurHltClient {
return &Ar... |
package parser
import (
"HelloGo/crawler/model"
"fmt"
"regexp"
"encoding/json"
)
var RYear = regexp.MustCompile(`<td><span class="label">年龄:</span>([^<]+?)</td>`)
var RHight = regexp.MustCompile(`<td><span class="label">身高:</span>([^<]+?)</td>`)
var RIncome = regexp.MustCompile(`<td><span class="label">月收入:</span... |
// Copyright (c) 2018 Benjamin Borbe All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package version
import (
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/bborbe/kafka-dockerhub-version-collector/avro"
"github.com/golang/glo... |
package configFile
/*
import (
"bufio"
"os"
"strings"
)
*/
type Config struct {
MaxDelay int
MinDelay int
Id int
Ip string
Port string
}
func readData() Config {
var config Config
config.MaxDelay = 4
config.MinDelay = 1
config.Id = 1
config.Ip = "127.0.0.1"
config.Port = "1234"
var co... |
/*
Copyright 2019 Dmitry Kolesnikov, 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 l... |
package main
import (
"bytes"
"fmt"
"github.com/gobuffalo/packr/v2"
"github.com/urfave/cli"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"text/template"
)
func main() {
app := cli.NewApp()
app.Name = ""
app.Usage = "SubScan Plugin gen"
app.UsageText = "pluginName [options]"
app.HideVersion = t... |
package geometry
import "math"
type Point3D struct {
X float32
Y float32
Z float32
}
func NewPoint(x float32, y float32, z float32) Point3D {
return Point3D{
X: x,
Y: y,
Z: z,
}
}
func NewPoint_FromVector(vector Vector3D) Point3D {
return Point3D{
X: vector.X,
Y: vector.Y,
Z: vector.Z,
}
}
func ... |
package router
import (
"net/http"
"github.com/labstack/echo/v4"
"github.com/zhenhuanlee/cqq/config"
"github.com/zhenhuanlee/cqq/router/word"
)
var e = config.ECHO
func init() {
e.GET("/", index)
e.POST("/words/all", word.All)
e.POST("/words/:id", word.Find)
e.POST("/words/create", word.Crea... |
package main
import (
"bufio"
"fmt"
"os"
)
func loadFromTextFile(filename string) []string {
f, err := os.Open(filename)
if err != nil {
fmt.Println(err.Error())
}
defer f.Close()
scanner := bufio.NewScanner(f)
lines := make([]string, 0)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}... |
package msgHandler
import (
cmn "github.com/HNB-ECO/HNB-Blockchain/HNB/consensus/algorand/common"
"github.com/HNB-ECO/HNB-Blockchain/HNB/consensus/algorand/types"
)
func (h *TDMMsgHandler) HandleCommitStepMsg(tdmMsg *cmn.TDMMessage) error {
return nil
}
func (ps *PeerState) ApplyCommitStepMessage(msg *types.Comm... |
package system
import (
"yj-app/app/controller/system/user"
"yj-app/app/service/middleware/auth"
"yj-app/app/yjgframe/router"
)
//加载路由
func init() {
// 用户管理路由
g1 := router.New("admin", "/system/user", auth.Auth)
g1.GET("/", "system:user:view", user.List)
g1.POST("/list", "system:user:list", user.ListAjax)
g1.... |
package gears
import (
"fmt"
"log"
"regexp"
"strings"
"github.com/axgle/mahonia"
chardet2 "github.com/chennqqi/chardet"
mapset "github.com/deckarep/golang-set"
"github.com/gogs/chardet"
)
func PrintSlice(x []string) {
fmt.Printf("len=%d cap=%d slice=%v\n", len(x), cap(x), x)
}
// RmIllegalChar is obsoleted... |
package authlogs
import (
"context"
"goa.design/goa/v3/middleware"
goa "goa.design/goa/v3/pkg"
"log"
)
func ErrorLogger(l *log.Logger, prefix string) func(goa.Endpoint) goa.Endpoint {
return func(e goa.Endpoint) goa.Endpoint {
// A Goa endpoint is itself a function.
return goa.Endpoint(func(ctx context.Conte... |
/*
* 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... |
package wrpc
/**
@author shuai.chen
@created 2020年1月8日
**/
import (
"net"
"strconv"
"reflect"
"github.com/apache/thrift/lib/go/thrift"
)
type Server struct {
zkc *ZkClient
conf *ServerConfig
serverObj *thrift.TSimpleServer
}
/*
create server
@zkc:zookeeper客户端
@conf: 服务配置
*/
func NewServer(zkc *ZkClient, c... |
package cmd
import (
"io/ioutil"
"os"
"testing"
)
func TestList(t *testing.T) {
file, err := os.Create("testcase.txt")
if err != nil {
t.Error("error in creating file")
}
defer file.Close()
old := os.Stdout
os.Stdout = file
args := []string{}
listCmd.Run(listCmd, args)
expected := `1. testcase1`
fp, _... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.