text
stringlengths
11
4.05M
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package api import ( "crypto/rand" "encoding/base64" "encoding/binary" "fmt" "net" "sort" "strconv" "strings" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/go-aut...
package dht_pb import ( "testing" ) func TestBadAddrsDontReturnNil(t *testing.T) { mp := new(Message_Peer) mp.Addrs = [][]byte{[]byte("NOT A VALID MULTIADDR")} addrs := mp.Addresses() if len(addrs) > 0 { t.Fatal("shouldnt have any multiaddrs") } }
package publisher import ( "github.com/google/martian/log" "go-rabbitmq/infra/mq" ) type Publish interface { PublishMessage(exchanged, name string, mandatory, immediate bool, msg string) } type publisher struct { mq.MQInterface } // PublishMessage is example for implement simple publish message func (p publishe...
package gossip import ( "fmt" "net" "net/http" "net/rpc" ) const ( ServerPort = 3030 ) type Server struct{} func MakeServer() *Server { return new(Server) } func (s *Server) Start(g *Gossip) error { r := new(GRPC) r.g = g rpc.Register(r) rpc.HandleHTTP() l, err := net.Listen("tcp", fmt.Sprintf(":%d", Se...
package main import ( "github.com/fananchong/go-xserver/services/internal/protocol" "github.com/fananchong/gotcp" ) // User : 登录玩家类 type User struct { gotcp.Session } // OnRecv : 接收到网络数据包,被触发 func (user *User) OnRecv(data []byte, flag byte) { cmd := gotcp.GetCmd(data) if user.IsVerified() == false && user.doVer...
// Copyright 2013 http://gumuz.nl/. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package treap/iterato.go provides an iterator for the Treap. Inspired by: http://en.wikipedia.org/wiki/Tree_traversal#In-order The Iterator has 4 constru...
package gov import ( "bytes" "fmt" "log" "sort" "testing" "github.com/ColorPlatform/color-sdk/codec" "github.com/ColorPlatform/color-sdk/store" sdk "github.com/ColorPlatform/color-sdk/types" "github.com/ColorPlatform/color-sdk/x/auth" "github.com/ColorPlatform/color-sdk/x/bank" distr "github.com/ColorPlatf...
package ims_api_connector import ( "testing" "time" "net/http" "reflect" ) func assertStringsEqual(t *testing.T, was, expected string) { if was != expected { t.Errorf("'%v' != '%v'", was, expected) } } func assertDurationsEqual(t *testing.T, was, expected time.Duration) { if was != expected { t.Errorf("%v...
// Package base provides a simple, unregistered gRPC server // with functional options not included in the base library. // Primarily useful to synchornize configurations across // development teams. package base import ( "net" grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware" grpc_zap "github.com/grp...
/* Copyright (C) 2018 Synopsys, Inc. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "...
package utils import ( "net/http" tr "github.com/ebikode/eLearning-core/translation" validation "github.com/go-ozzo/ozzo-validation" "github.com/go-ozzo/ozzo-validation/is" ) // REquired rule func NotNilRule(r *http.Request, key string) []validation.Rule { field := Translate(tr.TParam{Key: key, TemplateData: ni...
package runmon import ( "fmt" "io/ioutil" "os" "github.com/kasworld/nonkey/interpreter/evaluator" "github.com/kasworld/nonkey/interpreter/lexer" "github.com/kasworld/nonkey/interpreter/object" "github.com/kasworld/nonkey/interpreter/parser" ) func RunFile(filename string, env *object.Environment) *object.Envi...
package payment import ( "reflect" "testing" "github.com/stretchr/testify/mock" "github.com/satori/go.uuid" "github.com/tppgit/we_service/core" ) type mockPaymentRepo struct { mock.Mock PaymentRepository } func (m *mockPaymentRepo) InsertPayment(model *Payment) (err error) { arg := m.Called(model) return ...
/* * @lc app=leetcode.cn id=1 lang=golang * * [1] 两数之和 */ // @lc code=start package main import "fmt" func twoSum(nums []int, target int) []int { res := []int{} a := map[int]int{} for i, v := range nums { left := target-v if _, existed := a[left]; existed { res = append(res, i) res = append(res, a[l...
package cherry import ( "errors" "golang.org/x/net/context" ) const ( nodeKey = "node" middleNodeKey = "middleNode" prevContextKey = "prevContext" ) const ( queueSize = 1000 ) var ( SessionNilError = errors.New("session null") ) type Node interface { Receive(msg *Message) erro...
package handler import ( "encoding/json" "golang-api/model" "log" "net/http" ) // ProcessStats takes a given HTTP request and returns the statistics information relevent to the number of previous requests made to hash a password. func ProcessStats(w http.ResponseWriter, r *http.Request) { switch r.Method { case...
/* Copyright 2019 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, so...
package main import ( "context" "fmt" "golang.org/x/sync/errgroup" "net/http" "os" "os/signal" ) var sErr chan error var sigC chan os.Signal var fd http.Server func main() { g := errgroup.Group{} sErr = make(chan error, 1) sigC = make(chan os.Signal, 1) fd = http.Server{Addr:":8080"} g.Go(serve) g.Go(si...
package slack import ( "errors" "net/url" ) type oAuthResponseFull struct { AccessToken string `json:"access_token"` Scope string `json:"scope"` SlackResponse } // GetOAuthToken retrieves an AccessToken func GetOAuthToken(clientID, clientSecret, code, redirectURI string, debug bool) (accessToken string, s...
/* Copyright 2015 Google Inc. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd */ package oid import ( "fmt" "strconv" "strings" "github.com/google/cups-connector/cdd" ) // Some MIB...
package main import ( "encoding/json" "fmt" "io/ioutil" "math" "sort" "strconv" ) type Restaurant struct { ID int64 `json:"id"` Name string `json:"name"` Distance int64 `json:"distance"` DistanceFromStation int `json:"distance_from_station"...
package queries import ( "log" "github.com/jmoiron/sqlx" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/categories/models" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/configuration" ) const GET_CATEGORIES_SQL = ` SELECT c."CategoryId" , c."CategoryNamePl" , c."Categor...
package main import ( "bufio" "fmt" "io" "log" "net/http" "os" "strings" "time" "strconv" "encoding/json" ) const ConfigFile = "config/config.json" type Settings struct { Scheme string `json:"scheme"` Server string `json:"server"` Prefix string `json:"prefix"` Region string `json:"region"` Size string...
package main import "fmt" func isMatch(s string, p string) bool { sLen, pLen := len(s), len(p) dp := make([][]bool, sLen+1) for i := range dp { dp[i] = make([]bool, pLen+1) } dp[0][0] = true for j := 1; j <= pLen; j++ { if p[j-1] == '*' { dp[0][j] = dp[0][j-2] } } for i := 1; i <= sLe...
package main import ( "encoding/json" "flag" "fmt" "io/ioutil" "math/rand" "os" "os/signal" "strings" "syscall" "time" "github.com/bwmarrin/discordgo" ) var ( token string motivationalMessages = []string{ "Rock on!", "You got this!", "Whoo!", "Whoo hoo!", "Those gains!", "Bro ...
/* Description Ms. Terry is a pre-school art teacher who likes to have her students work with clay. One of her assignments is to form a lump of clay into a block and then measure the dimensions of the block. However, in every class, there is always one child who insists on taking some clay from some other child. Sinc...
package utils import ( "glsamaker/pkg/app/handler/authentication/auth_session" "glsamaker/pkg/database/connection" "glsamaker/pkg/models/users" "net/http" "strings" ) // utility methods to check whether a user is authenticated func Only2FAMissing(w http.ResponseWriter, r *http.Request) bool { sessionID, err :=...
package leetcode func duplicateZeros(arr []int) { zeroCnt := 0 l := len(arr) last_dup := false for idx, v := range arr { if v == 0 { if idx+zeroCnt+1 < l { if idx+zeroCnt+2 == l { last_dup = true } zeroCnt++ } } if idx+zeroCnt >= l { break } } t := l - 1 for i := 0; i < l-zeroC...
package arraycode import ( "fmt" "crypto/sha256" ) func comparecode(b1 []byte, b2 []byte) int { c1 := sha256.Sum256(b1) c2 := sha256.Sum256(b2) fmt.Printf("%x\n%x\n%t\n%T\n", c1, c2, c1 == c2, c1) return 1 }
package seccomp import ( "errors" "testing" specs "github.com/opencontainers/runtime-spec/specs-go" "github.com/pjbgf/go-test/should" ) func TestBruteForce_ShortCircuit(t *testing.T) { assertThat := func(assumption string, expectedExecutions int, expectedErr error) { should := should.New(t) stub := &runnerS...
package red_test import ( . "github.com/DennisDenuto/igrb/builds/red" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/concourse/fly/rc/rcfakes" "github.com/concourse/go-concourse/concourse/concoursefakes" "github.com/concourse/atc" "errors" ) var _ = Describe("Builds", func() { Describe("L...
package myast import ( "bytes" "fmt" "go/ast" "go/format" "go/parser" "go/printer" "go/token" "log" "os" "path/filepath" "strconv" "testing" ) /* 基础结构说明 普通Node,不是特定语法结构,属于某个语法结构的一部分. Comment 表示一行注释 // 或者 / / CommentGroup 表示多行注释 Field 表示结构体中的一个定义或者变量,或者函数签名当中的参数或者返回值 FieldList 表示以”{}”或者”()”包围的Filed列表 Expre...
package main import "fmt" func main() { hello() r := sum(1, 2) fmt.Println(r) rr := sub(1, 2) fmt.Println(rr) //리턴값 여러개 _, sub := SumAndSub(6, 2) fmt.Println(sub) //가변인자 rrr := sum2(1, 2, 3, 4, 5) fmt.Println(rrr) n := []int{1, 2, 3, 4, 5} rrrr := sum2(n...) // ...을 사용하여 가변인자에 슬라이스를 바로 넘겨줌 fmt.Pr...
package car import ( "net/http" "time" "strconv" ) type Server interface { Start() error Wait() Stop() } type server struct { stopListener chan struct{} port int server *http.Server staticHandler http.Handler steering Steering mux map[string]func(*server, http.ResponseWrit...
/* There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and dr...
// ˅ package main import "fmt" // ˄ type TextDisplayImpl struct { // ˅ // ˄ // A string to display text string // A number of characters in bytes width int // ˅ // ˄ } func NewTextDisplayImpl(text string) *TextDisplayImpl { // ˅ textDisplayImpl := &TextDisplayImpl{} textDisplayImpl.text = text text...
package library import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" ) func SetControllerRef(owner metav1.Object, owned metav1.Object) error { return controllerutil.SetControllerReference(owner, owned, scheme...
package routers import ( "github.com/francescoforesti/appointments/be/logging" "github.com/francescoforesti/appointments/be/service" "github.com/francescoforesti/appointments/be/utils" "github.com/gin-gonic/gin" ) func Init(router *gin.Engine, service service.AppointmentService) { router.RedirectTrailingSlash =...
// Copyright 2019 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...
package core type Stringer interface { String() string }
package admin import ( "firstProject/app/dto" myjwt "firstProject/app/http/middleware/jwt" "firstProject/app/http/result" "firstProject/app/models" adminRep "firstProject/app/repositories/admin" "firstProject/app/requests" "firstProject/app/services/admin" "firstProject/database" "fmt" "reflect" "strconv" ...
package orm import ( "context" "database/sql" "log" ) type Connection struct { ctx context.Context conn *sql.Conn tx *sql.Tx name string } func newConnection() *Connection { c := new(Connection) c.ctx = context.Background() return c } func (c *Connection) WithDB(name string) *Connection { c.name = name ...
package middleware import ( "net/http" "strings" "muto/context" "muto/models" ) // User middleware will lookup the current user via their // remember_token cookie using the UserService. If the user // is found, they will be set on the request context. // Regardless, the next handler is always called. type Accoun...
/* Copyright 2020 The Flux 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, softwar...
/* Copyright 2022 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, softw...
// 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 main import ( "context" "github.com/dragonflyoss/image-service/contrib/nydusify/pkg/converter" "github.com/dragonflyoss/image-service/contrib/nydusify/pkg/converter/provider" ) func main() { // Configurable parameters for converter wordDir := "./tmp" nydusImagePath := "/path/to/nydus-image" source := ...
package main import ( "strings" "time" "github.com/emersion/go-imap" "github.com/gdamore/tcell" ) type Message imap.Message func IsUnseen(flags []string) bool { for _, x := range flags { if x == imap.SeenFlag { return false } } return true } func formatDate(date time.Time) string { date = date.Local...
//go:generate go get -v github.com/mailru/easyjson/... //go:generate go get github.com/alvaroloes/enumer //go:generate go get github.com/jteeuwen/go-bindata/... //go:generate go get github.com/elazarl/go-bindata-assetfs/... //go:generate go get github.com/golang/protobuf/protoc-gen-go //go:generate go get github.com/go...
package handlers import ( "github.com/assignments-fixed-ssunni12/servers/gateway/models/users" "github.com/assignments-fixed-ssunni12/servers/gateway/sessions" ) //TODO: define a handler context struct that //will be a receiver on any of your HTTP //handler functions that need access to //globals, such as the key u...
package main import "fmt" func main() { var arr [5]float64 arr[0] = 100 arr[1] = 200 arr[2] = 300 arr[3] = 400 arr[4] = 500 for i, value := range arr { fmt.Println(value, i) } arr2 := [5]float64{1, 2, 3, 4, 5} for _, value := range arr2 { fmt.Println(value) } }
package dnszeppelin import ( "encoding/binary" "fmt" "github.com/google/gopacket" "github.com/google/gopacket/layers" mkdns "github.com/miekg/dns" "github.com/stretchr/testify/assert" "net" "testing" "time" ) /* Helpers */ func generateUDPPacket(payload []byte) gopacket.Packet { var options gopacket.Serial...
// parse includes/config.txt into a map // // format of includes/config.txt: // key=value // // access by: // value := config["key"] // package utils import ( "bufio" "log" "os" "regexp" "strings" ) var config map[string]string var confFile string //sample o func sample() { confFile = "config.txt" config =...
package main import ( "fmt" "path/filepath" "github.com/jraams/aoc-2020/helpers" ) type move struct { dx int dy int } func main() { // Load input from file inputPath, _ := filepath.Abs("input") inputValues := helpers.GetInputValues(inputPath) // Part 1 encounteredTrees, _ := slideDown(inputValues, []move...
// 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 drouter // DefaultPrefix defines the default command prefix of plugins. var DefaultPrefix = "/" // Plugin defines the structure of a disgord plugin. type Plugin struct { // ImportName defines the import name of the plugin. ImportName string // Prefix defines the commands prefix. Prefix string // RootCo...
package transport import ( "net/http" "github.com/sumelms/microservice-course/internal/course/endpoints" "github.com/sumelms/microservice-course/pkg/errors" kittransport "github.com/go-kit/kit/transport" kithttp "github.com/go-kit/kit/transport/http" "github.com/go-kit/log" "github.com/gorilla/mux" "github....
package main import ( "fmt" "time" ) // go มี statement พิเ ศษชื่อว่า selectทำงานคล้ายกับ switch แต่ใช้กับ channel func main() { // channel จะทำงานแบบ synchronize c1 := make(chan string) c2 := make(chan string) /* buffered channel คือ การส่งค่าพารามิเตอร์ตัวที่ 2 เข้าไปใน func make buffered เป็น Asynchonousคื...
//source: https://doc.qt.io/qt-5/qtgui-openglwindow-example.html package main import ( "os" "github.com/therecipe/qt/gui" ) const ( vertexShaderSource = "attribute highp vec4 posAttr;\n" + "attribute lowp vec4 colAttr;\n" + "varying lowp vec4 col;\n" + "uniform highp mat4 matrix;\n" + "voi...
package main import ( "bufio" "fmt" "os" ) func main() { scanner := bufio.NewScanner(os.Stdin) scanner.Split(bufio.ScanLines) var arr [16]int for i := 0; i < 4; i++ { scanner.Scan() var a, b, c, d int fmt.Sscanf(scanner.Text(), "%d %d %d %d", &a, &b, &c, &d) arr[i*4] = a arr[i*4+1] = b arr[i*4+2]...
package init import ( _ "github.com/GM-Publicchain/gm/plugin/mempool/para" //auto gen _ "github.com/GM-Publicchain/gm/plugin/mempool/price" //auto gen _ "github.com/GM-Publicchain/gm/plugin/mempool/score" //auto gen )
package plugins import ( "io" "os" "os/exec" "path/filepath" "github.com/hashicorp/go-multierror" ) //Loads the plugins at the given path //Returns a valid plugin or a non-nil error func Load(path string) (Plugin, error) { cmd := exec.Command(path) stdin, err := cmd.StdinPipe() if err != nil { return nil, ...
package main import ( "flag" "fmt" "log" "github.com/BurntSushi/toml" "github.com/sideshow/apns2" "github.com/sideshow/apns2/certificate" ) type Config struct { Filename string `toml:"filename"` Password string `toml:"password"` DeviceToken string `toml:"device_token"` Topic string `toml:"topic...
package cache import ( "container/list" "testing" ) func newBase(size int) *base { return &base{ size: size, items: make(map[interface{}]*list.Element, size+1), evictList: list.New(), } } func TestBase(t *testing.T) { c := newBase(128) for i := 0; i < 256; i++ { c.set(i, i, 0) } if l := c.l...
package constants const ( DaySeconds = 86400 )
package client import ( "encoding/json" "errors" "fmt" "log" "net/http" "thorium-go/requests" ) import "bytes" import "io/ioutil" var address string = "52.25.124.72" var port int = 6960 func PingMaster() (bool, error) { endpoint := fmt.Sprintf("http://%s:%d/status", address, port) req, err := http.NewReque...
package cmd import ( "fmt" "github.com/spf13/cobra" "os" ) // delBranchCmd represents the delBranch command var delBranchCmd = &cobra.Command{ Use: "del_branch", Short: "del_branch is used to delete a branch.", Long: `del_branch is used to delete a branch.`, Run: delBranch, } func init() { delBranchCmd....
package gohdk import ( "encoding/json" "runtime" "syscall/js" "unsafe" )
package npm import ( "path/filepath" "strings" "github.com/omeid/gonzo" "github.com/omeid/gonzo/context" "github.com/go-gonzo/archive/tar" "github.com/go-gonzo/compress/gzip" "github.com/go-gonzo/fs" "github.com/go-gonzo/npm/commonjs/package" "github.com/go-gonzo/npm/commonjs/registry/client" "github.com/g...
// Copyright 2021 Akamai Technologies, 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 main import ( "context" "fmt" "os" "reflect" "strings" "github.com/govim/govim" "github.com/govim/govim/cmd/govim/config" "github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/lsp/protocol" "github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/span" "github.com/kr/pretty" ) const ( ...
package dial import ( "github.com/go-redis/redis/v7" ) var RedisDB *redis.Client func InitRedisClient(addr string,password string) { client := redis.NewClient(&redis.Options{ Addr: addr, Password: password, DB:1, }) RedisDB = client return }
package fs import ( "io/ioutil" "os" "testing" ) func TestMkfs(t *testing.T) { fh, err := ioutil.TempFile("", "btrfs-testing.") if err != nil { t.Error(err) } // get a 1GB non-allocated file if err := fh.Truncate(1 * 1024 * 1024 * 1024); err != nil { t.Error(err) } if err := fh.Close(); err != nil { ...
package usecase import ( "crypto/md5" "crypto/tls" "fmt" "net/http" "regexp" "strings" "github.com/PuerkitoBio/goquery" "github.com/djimenez/iconv-go" "github.com/pkg/errors" "github.com/kenshaw/baseconv" ) // Fetcher export type Fetcher struct { tls bool dns *string dnsReg *regexp.Regexp } // N...
package inttest import ( "github.com/Sirupsen/logrus" "github.com/joatmon08/ovs_exporter/utils" "time" "errors" "testing" ) const ( TCP = "tcp" UNIX = "unix" CREATE_WAIT_TIME = 2 * time.Second EXEC_WAIT_TIME = 5 * time.Second INTTEST_NETWORK = "ovs_exporter_inttest_network" INTTEST_NETWORK_CIDR = "172.19.0...
package mongoapi import ( "fmt" "time" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type Student struct{ Name string `bson:"name"` Age uint8 `bson:"age"` ID uint8 `bson:"id"` } func main() { const ( Host = "10.47.2.8:27017" Username = "" Password = "" Database = "NewTest" Collectio...
package main import "fmt" import "time" func processStuff(value int, channel chan<- int) { time.Sleep(time.Second * 1) channel <- value } func main() { startTime := time.Now() numSeconds := 86400 // Number of seconds in a day. channel := make(chan int, numSeconds) for i := 0; i < numSecon...
package merchants import "github.com/mixnote/mixnote-api-go/src/core/models" type IMerchant interface { Name() string Identifier() string Customer(*models.User) (interface{},error) }
/* You have 2 numbers, both stored separate as numeric data type. First number is always 6 digits long. Second number can vary between 1 and 4 digits. If it's less than 4 digits, it needs to be padded with numeric value 0. End result always needs to be 10 digits number. Order has to be respected. n1|n2 Example #1...
/* 创建者 : Luke 日期 : 2020年3月17日 联系方式: soekchl@163.com */ package main import ( . "github.com/soekchl/myUtils" nl "github.com/soekchl/networkLayer" "time" ) func main() { go func() { time.Sleep(time.Second) Client() }() Server() } func Client() { client, err := nl.Dial("tcp", ":1111", 5) if err != nil {...
package main import ( "fmt" ) func main() { c := make(chan int) go func() { for i := 0; i < 10; i++ { c <- i } close(c) }() for n := range c { fmt.Println(n) } } /* remember to close your channel if you do not close your channel, you will receive this error fatal error: all goroutines are asleep -...
package util import ( "github.com/golang/glog" coreapi "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metaapi "k8s.io/apimachinery/pkg/apis/meta/v1" coreset "k8s.io/client-go/kubernetes/typed/core/v1" "k8s.io/client-go/util/retry" regopclient "github.com/openshift/cluster-image-registry-operator/pk...
package main type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func main() { testTree := initTree() println(isBalanced(testTree)) } func initTree() *TreeNode { // 3,9,20,null,null,15,7 ret := &TreeNode{Val: 3, Left: &TreeNode{Val: 9}, Right: &TreeNode{Val: 20, Left: &TreeNode{Val: 15}, Right:...
package leetcode import "fmt" // 正向打印 list func listPrint(node *ListNode) { if node == nil { fmt.Println(node) return } for node != nil { fmt.Print(node.Val) if node.Next != nil { fmt.Print("->") } node = node.Next } fmt.Println() } // 打印复杂链表 func printComplexList(node *Compl...
/* The localfile backend, for dealing with a Vagrant catalog on a local filesystem */ package caryatid import ( "fmt" "io/ioutil" "log" "net/url" "os" "path" "path/filepath" "regexp" "github.com/mrled/caryatid/internal/util" ) type CaryatidLocalFileBackend struct { VagrantCatalogRootPath string VagrantCa...
package main import ( "bufio" "fmt" "net/http" "os" "strings" ) func main() { var resultUrls []string if len(os.Args) != 2 { fmt.Println("Provide one url") return } url := os.Args[1] resp, err := http.Get(url) defer resp.Body.Close() if err != nil { fmt.Println(err) } scanner := bufio.NewScanner(...
package main import ( "fmt" "math/rand" "sync" "time" ) //使用确定数量的goroutine来处理确定数量的工作 const ( grNum = 4 // goroutine数 taskLoad = 10 // 工作量 ) var wg5 sync.WaitGroup //wait for a collection goroutine to finish func init() { rand.Seed(time.Now().Unix()) //使用指定的种子值, 初始化默认资源到确定状态 } func main() { tasks := mak...
// Package gmachine implements a simple virtual CPU, known as the G-machine. package gmachine // DefaultMemSize is the number of 64-bit words of memory which will be // allocated to a new G-machine by default. const DefaultMemSize = 1024 const ( // OpHALT terminates Gmachine OpHALT uint64 = iota // OpNOOP does not...
package main import ( "encoding/json" "log" "net/http" "strconv" "github.com/gorilla/mux" "tarot" ) type SucceedJson struct { Succeed bool `json:"succeed"` } type NewPartyJson struct { Succeed bool `json:"succeed"` Seat int `json:"seat"` } type ReadyJson struct { Ready bool `json:"ready"` } type Pla...
/* Cliente del chat server que consuma los datos de las goroutines y channles */ package main import ( "io" "log" "net" "os" ) // Manejo de errores func main() { conn, err := net.Dial("tcp", "localhost:8005") if err != nil { log.Fatal(err) } // Definir variable done que ignore errores done := make(chan st...
package main import "testing" func Test_race(t *testing.T) { race() }
package etcd import ( "context" "fmt" "time" "github.com/coreos/etcd/clientv3" //"github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes" "grm-service/log" . "grm-service/util" ) var ( dialTimeout = 5 * time.Second requestTimeout = 10 * time.Second ) const ( KEY_SPLIT = "/" KEY_SESSION ...
package http import ( "encoding/json" "fmt" "github.com/twainy/goban" "github.com/twainy/tiroler/crawler" "github.com/zenazn/goji" "github.com/zenazn/goji/web" "net/http" "reflect" "runtime" "strconv" ) func Start() { Setup(goji.DefaultMux) goji.Serve() } func Setup(m *web.Mux) { route(m) goban.Setu...
package main import ( "bufio" "fmt" "io" "log" "os" "path/filepath" ) func main() { // ファイル学習用.ファイル名を指定して作成. scanner := bufio.NewScanner(os.Stdin) fmt.Printf("作成するファイル名を入力してください\n > ") for scanner.Scan() { filename := scanner.Text() if len(filename) > 0 { createFile(filename) break } else { f...
package examples import ( "net/http" "html/template" "github.com/kilfu0701/gogae/upload" "google.golang.org/appengine" "google.golang.org/appengine/log" ) const ( uploadEntry = "/api/photo/upload" uploadTemplateHTML = ` <html><body> <form action="{{.}}" method="POST" enctype="multipart/form-data"> Upload File...
/* * @lc app=leetcode.cn id=92 lang=golang * * [92] 反转链表 II */ // @lc code=start /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ package main import "fmt" type ListNode struct { Val int Next *ListNode } func main() { v1 := ListNode{ 1, nil} ...
package email import ( "../ses" "../config" ) func ConfirmEmail(to string, token string) { emailData := ses.Email{ To: to, From: config.Config.NoReplyEmail, Text: "Your whitelist submission is well received.\n\n" + "To finish the whitelist application process please confirm your email by following the link/n...
package main import ( "errors" "fmt" "log" "net/http" "github.com/dikhan/http_goclient" "github.com/go-openapi/loads" "github.com/go-openapi/spec" "github.com/hashicorp/terraform/helper/schema" ) const API_KEY_HEADER_NAME = "api_key_header" const API_KEY_QUERY_NAME = "api_key_query" type ProviderFactory st...
package protocol type Op struct { OpHeader *Header } func (p *Op) Header() *Header { return p.OpHeader }
package sstable import ( "encoding/binary" "io" "sort" "github.com/cloud9-tools/go-sstable/internal" ) func Build(w io.Writer, data []Pair) error { sort.Sort(byKey(data)) if len(data) > kmaxuint32 { return ErrTooManyRecords } var offset = 8 + uint64(len(magic)) for _, item := range data { if len(item.K...