text
stringlengths
11
4.05M
package update import ( "fmt" "github.com/google/go-containerregistry/pkg/name" "github.com/rancher/fleet/pkg/apis/fleet.cattle.io/v1alpha1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/kube-openapi/pkg/validation/spec" "sigs.k8s.io/kustomize/kyaml/fieldmeta" "sigs.k8s.io/kust...
package golem import ( "bytes" "crypto/cipher" "crypto/rand" "crypto/sha256" "errors" ) // Cipher Modes const ( ModeCBC cipherMode = 1 << iota ModeCFB ModeCTR ModeOFB ) var ( blockModeFuncMap = map[cipherMode]map[string]func(b cipher.Block, iv []byte) cipher.BlockMode{ ModeCBC: map[string]func(b cipher.B...
package v1 import ( log "github.com/Sirupsen/logrus" "github.com/SpectoLabs/hoverfly/core/handlers" "github.com/codegangsta/negroni" "github.com/go-zoo/bone" "net/http" ) type HealthHandler struct{} func (this *HealthHandler) RegisterRoutes(mux *bone.Mux, am *handlers.AuthHandler) { mux.Get("/api/health", negr...
/* Package structhash creates hash strings from arbitrary go data structures. */ package structhash
package models // ProjectGrant means that user has ability to label project type ProjectGrant struct { _msgpack struct{} `msgpack:",asArray"` ProjectID int UserID int } // IsEqual checks equality func (pg *ProjectGrant) IsEqual(other *ProjectGrant) bool { if other == nil { return false } return pg.Project...
// Copyright (c) 2013 Laurent Moussault. All rights reserved. // Licensed under a simplified BSD license (see LICENSE file). package math import "unsafe" //------------------------------------------------------------------------------ // `Abs` returns the absolute value of `x`. func Abs(x float32) float32 { ux := ...
/** * Copyright 2021 Comcast Cable Communications Management, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless requir...
package cf_test import ( "bytes" "github.com/pivotal-cf/on-demand-service-broker/integration_tests/helpers" "io" "log" "net/http" "regexp" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/onsi/gomega/ghttp" "github.com/pivotal-cf/on-demand-service-broker/cf" "github.com/pivotal-cf/on-de...
package middleware import ( "log" "time" jwt "github.com/dgrijalva/jwt-go" request "github.com/dgrijalva/jwt-go/request" "github.com/gin-gonic/gin" "github.com/16francs/examin_go/config" "github.com/16francs/examin_go/domain/model" ) /* jwt tokenを生成する iss tokenの発行者 sub tokenの利用者を一意に特定する識別子 => user_id iat ...
package oneagent_mutation import ( "testing" "github.com/Dynatrace/dynatrace-operator/src/config" "github.com/Dynatrace/dynatrace-operator/src/kubeobjects" dtwebhook "github.com/Dynatrace/dynatrace-operator/src/webhook" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/a...
package Info import ( "fmt" "time" "github.com/google/gopacket" ) type FiveTuple struct { srcIp, srcPort, dstIp, dstPort, protocol string } func GetFiveTuple(packet gopacket.Packet) FiveTuple { dstIp := packet.NetworkLayer().NetworkFlow().Dst().String() srcIp := packet.NetworkLayer().NetworkFlow().Src().Strin...
package blocker import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/sha256" "encoding/binary" "encoding/hex" "io" "strings" "unsafe" ) // func decryptEncoded(hexStr, keyStr string) ([]byte, error) { hexStr = strings.TrimSpace(hexStr) encbuffer, err := hex.DecodeString(hexStr) if err != nil { return ni...
// 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 network // Constants for interacting with wpa_supplicant via dbus. const ( DBusWPASupplicantInterface = "fi.w1.wpa_supplicant1.Interface" )
package raft type NetTransport struct { } func NewNetTransport() { }
package skeleton import "fmt" func NewDefaultHandle() HandlerFunc { return func(c Context) error { fmt.Printf("NewDefaultHandle %v\n", c.GetString()) return nil } }
package main import "fmt" //map[*int]*int //map[*int]int //map[int]*int //range下 key 和value 怎么变化。 //for range 循环的时候会创建每个元素的副本,而不是元素的引用 func main() { slice := []int{0, 1, 2, 3} m := make(map[*int]*int) for key, value := range slice { m[&key] = &value } for k, v := range m { fmt.Println(*k, "->", *v) } }
package gochat import ( "net/url" "github.com/gorilla/websocket" proto "github.com/laoqiu/go-chat/proto" ) const ( defaultHost = "localhost:8082" defaultPath = "/chat/stream" ) // A Client represents the connection between the application to the HipChat // service. type Client struct { Id string Men...
package repository //go:generate go run github.com/golang/mock/mockgen -source=$GOFILE -destination=mock/${GOFILE} -package=mock import ( "context" "github.com/traPtitech/trap-collection-server/src/domain" "github.com/traPtitech/trap-collection-server/src/domain/values" ) type GameURL interface { SaveGameURL(ct...
/* Package sqip allows SVG-based LQIP image creation https://github.com/denisbrodbeck/sqip https://godoc.org/github.com/denisbrodbeck/sqip/cmd/sqip This package is a go implementation of Tobias Baldauf‘s SVG-based LQIP technique (see https://github.com/technopagan/sqip). SQIP is an evolution of the classic LQIP te...
package encryption import ( "errors" "github.com/maximepeschard/adventofcode2020/01_report/combination" ) // FirstInvalidIndex returns the index of the first invalid number. func FirstInvalidIndex(numbers []int, preambleLength int) (int, error) { for i := preambleLength; i < len(numbers); i++ { valid := false ...
package lib import ( "encoding/json" "fmt" "log" "sync" "nanomsg.org/go/mangos/v2" _ "nanomsg.org/go/mangos/v2/transport/all" ) var lock sync.Mutex type AddonManager struct { Adapters []Adapter IpcClient *IpcClient PluginId string Verbose bool Running bool } func NewAddonManager(pluginId string, ...
package main import ( "book/interfaces/httphandler/database" "fmt" "log" "net/http" ) func main() { fmt.Println("Initializing....") db := database.Database{"shoes": 50, "socks": 5} http.HandleFunc("/list", db.List) http.HandleFunc("/price", db.Price) log.Fatal(http.ListenAndServe("localhost:8000", nil)) }
package requests import ( "encoding/json" "fmt" "io/ioutil" "net/url" "strings" "github.com/atomicjolt/canvasapi" "github.com/atomicjolt/canvasapi/models" ) // GetBlueprintInformation Using 'default' as the template_id should suffice for the current implmentation (as there should be only one template per cour...
// Copyright 2023 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...
/* Copyright 2019 Baidu, 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, software dis...
package usecases import ( "github.com/osechiman/BulltienBoard/entities" "github.com/osechiman/BulltienBoard/entities/errorobjects" "github.com/osechiman/BulltienBoard/entities/valueobjects" ) const ThreadLimit = 50 // ThreadUsecase はThreadに対するUsecaseを定義するものです。 type ThreadUsecase struct { Repository ThreadReposit...
package functional import ( "testing" "github.com/stretchr/testify/assert" ) func TestFilter(t *testing.T) { isPositive := func(val int) bool { return val > 0 } t.Run("empty", func(t *testing.T) { input := []int{} actual := Filter(input, isPositive) expected := []int{} assert.Equal(t, expected, actu...
//陣列中陣列 迴圈印出陣列中陣列 package main import "fmt" func main() { x := []string{"James", "Bond", "Shaken, not stirred"} z := []string{"Miss", "Moneypenny", "Helloooooo, James."} y := [][]string{x, z} fmt.Println(y) for i, d := range y { fmt.Println("y[] index :", i) for i2, d2 := range d { // fmt.Println("現在在y[...
/* Copyright 2019 The Skaffold 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, sof...
package main import ( "bytes" "database/sql" "encoding/binary" "fmt" _ "github.com/go-sql-driver/mysql" "io" "log" "net" //"os" "regexp" "strconv" "strings" ) type Log struct { Aid int64 //8 Ip int64 //10 字符串处理 From string //32 File_name string //128 Crtime ...
package main import "container/list" // Leetcode 706. (easy) type MyHashMap struct { data []list.List } type MyHashMapEntry struct { key, value int } const MyHashMapBase int = 1000 /** Initialize your data structure here. */ func Constructor() MyHashMap { return MyHashMap{data: make([]list.List, MyHashMapBase)}...
package events import ( "context" "fmt" "github.com/hyperledger/burrow/binary" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/event" "github.com/hyperledger/burrow/event/query" "github.com/hyperledger/burrow/execution/errors" ptypes "github.com/hyperledger/burrow/permission/types" "git...
package main // Gateway : 网关服务器 type Gateway struct { *UserMgr } // NewGateway : 构造函数 func NewGateway() *Gateway { gw := &Gateway{} gw.UserMgr = NewUserMgr() return gw } // Start : 启动 func (gateway *Gateway) Start() bool { Ctx.RegisterSessType(User{}) Ctx.RegisterSendToClient(gateway.sendToClient) Ctx.Registe...
package main import "testing" import "time" import "fmt" func TestSomething(t *testing.T) { fmt.Println(logo) fmt.Println("sleep 20 seconds") for i := 0; i < 20; i++ { time.Sleep(time.Second) fmt.Printf("slept %v seconds\n", i) } }
package crawl import ( "regexp" "strings" ) type cssTransform struct { css string matches []cssMatch } type cssMatch struct { orig string url string link ResolvedLinker } var ( reCSSURL = regexp.MustCompile(`url\(["']?(.*?)["']?\)`) reCSSImport = regexp.MustCompile(`@import ["'](.*?)["']`) ) func ...
package menu import ( "fmt" "os" "github.com/hramov/battleship_server/pkg/gameloop" ) func create() []string { menuItems := []string{ "Начать игру", "О создателях", "Выйти", } return menuItems } func draw(menuItems []string) { fmt.Println("Hello! Welcome to BattleShips! Here you have a menu.") for i :...
package multichan import ( "time" "testing" "github.com/stretchr/testify/assert" ) const shortTime = 50 * time.Millisecond func TestBufferChanInput(t *testing.T) { c := New() c.Close() // We don't want the channel to process messages res := tryWithTimeout(shortTime, func () { c.Input() <- 1 }) assert.False...
// 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 models import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" "fmt" "log" "github.com/EthereumCommonwealth/Galileo/common" ) func GetDBConnection(setting common.GalileoSetting) *gorm.DB { args := fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=disable", setti...
package conveyor_test import ( "github.com/leolara/conveyor" "github.com/leolara/conveyor/memory" "sync" "time" ) func Example() { var wd sync.WaitGroup // we use a in-memory broker for testing and examples, you can find many implementations for different brokers at // https://github.com/leolara/conveyor-impl...
package requests import ( "encoding/json" "fmt" "net/url" "strings" "github.com/google/go-querystring/query" "github.com/atomicjolt/canvasapi" ) // UpdateAssociatedCourses Send a list of course ids to add or remove new associations for the template. // Cannot add courses that do not belong to the blueprint co...
package main import "learngo/book/interface/emptyInterface" func main() { //var haier = useInterface.Haier{ // Dryer: useInterface.Dryer{}, //} //haier.Dry() //haier.Wash() emptyInterface.EmptyInterface() }
package internal_test import ( "sort" "testing" "github.com/google/go-cmp/cmp" "github.com/michelin/gochopchop/internal" ) func TestSafeResultsAppend(t *testing.T) { t.Parallel() s := internal.SafeResults{} s.Append(internal.Result{}) if !cmp.Equal(s.Res, []internal.Result{{}}) { t.Error("Failed to prope...
package k8s import ( "github.com/pkg/errors" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/tools/clientcmd/api" "github.com/tilt-dev/clusterid" ) type ClusterName string func ProvideKubeContext(configOrError APIConfigOrError) KubeContext { config := configOrError.Config if config == nil { return "" ...
package tests import ( "testing" . "github.com/informeai/drip" ) var r = NewRecorder("file.json") func TestNewRecord(t *testing.T) { t.Log(r) } func TestRecord(t *testing.T) { err := r.Record() if err != nil { t.Fatal(err) } }
package leetcode_0066_加一 /* 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。 最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。 你可以假设除了整数 0 之外,这个整数不会以零开头。 示例 1: 输入: [1,2,3] 输出: [1,2,4] 解释: 输入数组表示数字 123。 示例 2: 输入: [4,3,2,1] 输出: [4,3,2,2] 解释: 输入数组表示数字 4321。 */ /* 思考: 考虑进位,从数组最后一位开始往前遍历 如果遇到9的,那么+1之后变10,所以该位置写0,并继续往前走, 如果走到数组index=0的地方,说明走完了,则扩展数组,然后跳过...
package generativerecursion func CountPyramid(levels int) [][]int { result := make([][]int, levels) result[0] = []int{1} for i := 0; i < levels-1; i++ { result[i+1] = countLevel(result[i]) } return result } func countLevel(arr []int) []int { var ( result []int ) for len(arr) > 0 { count := firstInARo...
package kubeClient // import "github.com/kuberhealthy/kuberhealthy/v2/pkg/kubeClient" import ( "k8s.io/client-go/kubernetes" _ "k8s.io/client-go/plugin/pkg/client/auth" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" ) // Create returns a kubernetes api clientset that enables communication with // the ...
// Copyright 2018 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package main type JobSorter []Job func (s JobSorter) Len() int { return len(s) } func (s JobSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s JobSorter) Less(i, j int) bool { return s[i].CreatedAt < s[j].CreatedAt }
package srpc import ( "context" ) type Client struct { handler InvokeFunc coordinate ServiceCoordinate } func NewClient(handler InvokeFunc, coordinate ServiceCoordinate) *Client { return &Client{ handler: handler, coordinate: coordinate, } } func (cli *Client) Call(ctx context.Context, methodName str...
// SPDX-License-Identifier: ISC // Copyright (c) 2014-2020 Bitmark Inc. // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package proof_test import ( "testing" "github.com/stretchr/testify/assert" "github.com/bitmark-inc/bitmarkd/counter" "github.com/bitmark-inc/...
package log import ( "fmt" "github.com/sirupsen/logrus" ) // errorStack type type errorStack struct{} // Fire func func (*errorStack) Fire(entry *logrus.Entry) error { if err, ok := entry.Data["error"]; ok { entry.Data["stack"] = fmt.Sprintf("%+v", err) } return nil } // Levels func func (*errorStack) Leve...
package main import ( "fmt" "github.com/bouk/monkey" "os" "os/exec" "reflect" "testing" ) // 假如我们要测试函数 call func call(cmd string) (int, string) { bytes, err := exec.Command("sh", "-c", cmd).CombinedOutput() output := string(bytes) if err != nil { return 1, reportExecFailed(output) } return 0, output } /...
// 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 ui import ( "context" "time" "chromiumos/tast/ctxutil" "chromiumos/tast/errors" uiperf "chromiumos/tast/local/bundles/cros/ui/perf" "chromiumos/tast/local/chr...
/* Copyright 2020 The Skaffold 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, sof...
package gadget type ( IndexController struct{ *DefaultController } AuthorController struct{ *DefaultController } EntryController struct{ *DefaultController } ExampleApp struct{ *App } ) func (ex *ExampleApp) Configure() error { ex.Routes( ex.SetIndex("index"), ex.Prefixed("writing", ex.Resource("a...
/* * Copyright (c) 2019 ubirch GmbH. * * ``` * 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 o...
package test import ( "fmt" "testing" ) func TestArrary(t *testing.T) { array := [5]int{1: 10, 3: 30} fmt.Println("array:", array) } func TestSlice(t *testing.T) { { var slice []int fmt.Println("slice == nil:", slice == nil, len(slice), cap(slice)) slice = append(slice, 1) fmt.Println("slice:", slice) ...
package apig type Detail struct { VCS string User string Project string Namespace string Models Models Model *Model ImportDir string Database string }
package fakeaudit import ( "path/filepath" ) var daemonSetPath = filepath.Join(absPath, "fakeaudit", "test", "daemonSets") func CreateFakeDaemonSetSC(namespace string) { fakeDaemonSetClient := getFakeDaemonSetClient(namespace) fakeDaemonSetClient.Create(getDaemonSet(filepath.Join(daemonSetPath, "fakeDaemonSetSC1....
package utils import ( "math/rand" "net/url" "strings" "time" "github.com/hunyaio/yuhScan/logger" ) func CheckURL(url string) bool { // Init urlRules := map[string]string{ "domain": `^(https?://)?([A-Za-z0-9\-]+\.)+[A-Za-z\-]+(:[0-9]{1,5})?(\/.*)?$`, "ip": `^(https?://)?([0-9]{1,3}\.){3}[0-9]{1,3}(:[0...
package main import ( "fmt" "sync" ) func main() { c := make(chan int, 2) go func() { c <- 31 c <- 32 close(c) }() fmt.Println(<-c, <-c) cr := make(<- chan int, 1) cs := make(chan <- int, 1) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() cs <- 33 cr = c close(cs) }() fmt....
/* Copyright 2015 The Kubernetes Authors 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 ag...
package structhash import ( "encoding/json" "testing" ) type BenchData struct { Bool bool String string Int int Uint uint Map map[string]*BenchData Slice []*BenchData Struct *BenchData } type BenchTags struct { Bool bool `json:"f1" hash:"name:f1"` String string `json:"f2" hash:"name:f2"` I...
package middleware import ( "fmt" "github.com/labstack/echo" ) func ReqRespLogger() echo.MiddlewareFunc { return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) (err error) { //req := c.Request() //resp := c.Response() if err = next(c); err != nil { c.Error(err) } f...
package controls import ( "github.com/labstack/echo/v4" "github.com/upyun/go-sdk/upyun" "os" "sofuny/config" "sofuny/utils" "strconv" "strings" "time" ) // 上传文件 func UploadFile(ctx echo.Context) error { file, err := ctx.FormFile("file") if err != nil { return ctx.JSON(200, utils.Response{ StatusCode: 0...
package proxy import ( "crypto/tls" "fmt" "net/http" "net/http/httputil" ) // Handler proxies requests to the rancher service type Handler struct { Scheme string Host string } const ( ForwardedAPIHostHeader = "X-API-Host" ForwardedProtoHeader = "X-Forwarded-Proto" ForwardedHostHeader = "X-Forwarded-H...
package container import ( "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1" ) func TestReplaceTaggedRefDomain(t *testing.T) { var namedTaggedTestCases = []struct { defaultRegistry string name string ex...
package commands import ( "crypto/md5" "fmt" "os" "github.com/BSidesSF/ctf-2019/challenges/rsaos/foldhash" "github.com/BSidesSF/ctf-2019/challenges/rsaos/sessions" ) type MD5Command struct{} func (mc *MD5Command) GetName() string { return "md5" } func (mc *MD5Command) GetDescription() string { return "Get m...
package val import ( "regexp" "github.com/go-playground/validator/v10" "go4eat-api/pkg/val" ) // NewValidator func func NewValidator() *validator.Validate { return val.NewValidator([]val.Rule{ val.Rule{Tag: "username", Validation: username()}, val.Rule{Tag: "password", Validation: password()}, val.Rule{T...
package creature func (c Creature) Update(message interface{}) Creature { switch message.(type) { case Move: return c.move(message.(Move)) } return c } func New(message Create) Creature { return Creature{Position: message.Position} } func (c Creature) move(move Move) Creature { var newPosition = Position{} ...
package twoSum import ( "testing" ) func TestTwoSumBruteForce(t *testing.T) { var arr []int var target int var rs [][2]int arr = []int{2, 7, 6, 15, 3} target = 9 rs = TwoSumBruteForce(arr, len(arr), target) t.Logf("arr: %v, rs: %v", arr, rs) } func TestTwoSumMemory(t *testing.T) { var arr []int var targe...
// Copyright 2023 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...
// All material is licensed under the Apache License Version 2.0, January 2004 // http://www.apache.org/licenses/LICENSE-2.0 // http://play.golang.org/p/P_8b-42YwD package main import "fmt" func main() { test(map[int]string{1: "one", 2: "two", 3: "three"}) fmt.Println() test(nil) } func test(m map[int]string)...
package dns import ( "context" "net" "reflect" "testing" "time" ) var localhostZone = &Zone{ Origin: "localhost.", TTL: 24 * time.Hour, SOA: &SOA{ NS: "dns.localhost.", MBox: "hostmaster.localhost.", }, RRs: RRSet{ "1.app": { TypeA: { &A{net.IPv4(10, 42, 0, 1).To4()}, }, TypeAAAA: { ...
package main import ( "github.com/redhat-openshift-ecosystem/openshift-preflight/cmd" ) func main() { cmd.Execute() }
// How to gossip sites and relays?? // set<site> // map<relay, site> // Using gossip protocol for this association could result in inconsistencies for the client: // // Asks node 1 to add site so node 1 adds site to its local map. node 1 responds with a success code // Before node 1 can gossip to other nodes the client...
// Package main // Created by RTT. // Author: teocci@yandex.com on 2021-Aug-17 package main import ( "encoding/csv" "fmt" "log" "os" ) func main() { file, err := os.Open("./test.csv") if err != nil { log.Fatalln("Error: ", err) } // csv reader producer rdr := csv.NewReader(file) // read all the csv cont...
package main import "fmt" func main() { var array []int = []int{1,9, 8,3,6} bubbleSort(array) fmt.Println(array) } func bubbleSort(array []int) { if len(array) < 2 { return } for i := 0; i < len(array) - 1; i++ { for j := 0; j < len(array) - 1 - i; j++ { if array[j] > array[j +1] { array[j], array[j...
// 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 hps import ( "context" "github.com/godbus/dbus/v5" pb "chromiumos/system_api/hps_proto" "chromiumos/tast/common/hps/hpsutil" "chromiumos/tast/local/dbusutil" ...
package main import "fmt" func main() { var stud =make(map[int]string) stud[16]="shrikar" stud[20]="dinesh" stud[30]="mohanish" fmt.Println(stud[16]) fmt.Println(stud) }
package main import ( "log" "github.com/CyrusJavan/portfolio-new/src/db" "github.com/joho/godotenv" "github.com/golang-migrate/migrate/v4" "github.com/golang-migrate/migrate/v4/database/postgres" _ "github.com/golang-migrate/migrate/v4/source/file" _ "github.com/lib/pq" ) func main() { if err := godotenv.Lo...
package benchmark var _ Subject = (*Dummy)(nil) type Dummy struct { } func (s *Dummy) Setup(config *Config, p ProtocolProcessing) error { return nil } func (s *Dummy) Counters() map[string]int64 { return map[string]int64{ "counter1": 100, "counter2": 50, } } func (s *Dummy) LatencyCheckTarget() string { re...
package main import ( "fmt" "github.com/brewlin/net-protocol/protocol/application/dns" "github.com/brewlin/net-protocol/protocol/header" ) func main() { d := dns.NewEndpoint("www.baidu.com") fmt.Println("DNS lookuphost : www.baidu.com") defer d.Close() ir,err := d.Resolve(); if err != nil { fmt.Println(...
/** * * @author nghiatc * @since Dec 6, 2019 */ package main import ( "fmt" "github.com/congnghia0609/ntc-gconf/nconf" "github.com/congnghia0609/ntc-gnats/nworker" "github.com/nats-io/nats.go" "log" "os" "os/signal" "path/filepath" "runtime" ) func InitNConf6() { _, b, _, _ := runtime.Caller(0) wdir :=...
package main import "fmt" func main() { counter := 0 for i:= 1; i <= 100; i++ { if i % 3 == 0 { counter++ fmt.Print(i," ") if counter % 10 == 0 { fmt.Println("") fmt.Println("") } } } }
package main /** golang装饰器模式 */ import "fmt" func userLogging(fun func()) func() { // 装饰器函数 wrapper := func() { fmt.Println("this func is", fun) fun() fmt.Println("the end of foo") } return wrapper } func foo() { println("i am foo") } func main() { foo := userLogging(foo) foo() } //this f...
package server import ( "context" "encoding/json" "fmt" "net/http" "os" "strconv" "github.com/gorilla/mux" "github.com/okta/okta-sdk-golang/v2/okta" "github.com/okta/okta-sdk-golang/v2/okta/query" protocol "github.com/rareinator/Svendeprove/Backend/packages/protocol" ) func (s *Server) handleGetDoctorsInHo...
package votingplatform import ( "encoding/json" "fmt" "github.com/google/uuid" ) type ID uuid.UUID func (id ID) String() string { return uuid.UUID(id).String() } type VotableItem struct { votableItemId ID `metadata:"votableItemId"` Name string `json:"name"` Description string `json:"descripti...
package main import "fmt" func main(){ // elemental for for i := 0 ; i < 5; i++{ fmt.Println("i:",i) } // for two variables for i,j := 0,0 ; i < 5; i, j = i+1, j+2{ fmt.Println("i,j:",i,j) } // sugar syntax a := 0 for { fmt.Println(a) a++ if a == 5 { break } } // Loop label Loop: for ...
package worker import ( "context" "golang.org/x/sync/errgroup" ) // Pool is a type to manage and limit goroutines type Pool struct { workers chan int // used to launch up to n goroutines at once errgroup *errgroup.Group context context.Context } // NewPool creates a *Pool with the specified number of workers...
package deploy import ( "sort" "strings" "github.com/dan-v/dosxvpn/doclient" ) func ListVpns(token string) ([]string, error) { client := doclient.New(token) droplets, err := client.ListDroplets() if err != nil { return nil, err } allDroplets := make([]string, 0) for _, droplet := range droplets { if st...
package udwIpToCountryV2 import ( "github.com/tachyon-protocol/udw/udwIpToCountryV2/udwIpCountryV2Map" "net" "sync" "sync/atomic" "unsafe" ) func EnsureInit() { gEnsureInitOnce.Do(func() { thisReader := getGeoip2Reader() SetReader(thisReader) }) } func MustGetCountryIsoCode(ip net.IP) (code string) { En...
package info import ( pb "github.com/LILILIhuahuahua/ustc_tencent_game/api/proto" "github.com/LILILIhuahuahua/ustc_tencent_game/framework" "github.com/LILILIhuahuahua/ustc_tencent_game/framework/event" ) type ConnectInfo struct { framework.BaseEvent //基础消息类作为父类 Ip string Port int...
package models import "GoMD/tools" /* --------------------------- 功能:用于统一的json数据发送与处理 ------------------------------ */ //获取后台文章列表 后台文章页面调用该方法 返回一个json数据 func GetArticleJson() *[]DisplayArticle{ list := []DisplayArticle{} err := dbx.Select(&list, "select article.id,article.title,article.author,taxonomy.name,ar...
package main import ( "fmt" "github.com/DuC-cnZj/hello_golang/v2/version" ) func main() { fmt.Println("hello: " + version.GetVersion()) }
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" "os/exec" "path/filepath" "strings" "time" "github.com/RichardKnop/machinery/v1/backends/result" "github.com/RichardKnop/machinery/v1/tasks" "github.com/google/uuid" ) func indexHandler(w http.ResponseWriter, r *http.Request) ...
package storage import ( "errors" "time" "github.com/ninjadotorg/SimEcon002/common" "github.com/ninjadotorg/SimEcon002/macro_economy/abstraction" ) type Storage struct { Agents map[string]abstraction.Agent Assets map[string]map[uint]abstraction.Asset // agentID -> assetID -> asset Asks map[uint]map[stri...
package controller import ( "context" "encoding/json" "errors" "fmt" "github.com/agiledragon/gomonkey/v2" "github.com/kenlabs/pando-store/pkg/snapshotstore" "github.com/kenlabs/pando-store/pkg/types/store" v1 "github.com/kenlabs/pando/pkg/api/v1" "github.com/kenlabs/pando/pkg/util/cids" . "github.com/smartys...