text
stringlengths
11
4.05M
package printer import ( "bytes" "fmt" "go/parser" "go/printer" "go/token" "text/template" "github.com/davyxu/tabtoy/v2/i18n" "github.com/davyxu/tabtoy/v2/model" ) const goTemplate = `// Generated by github.com/davyxu/tabtoy // Version: {{.ToolVersion}} // DO NOT EDIT!! package {{.Package}} import( {{if ....
package main import ( "fmt" "time" ) func main() { c := make(chan int) go print("Sajeban", c) // for { // msg, open := <-c // fmt.Println("main", msg) // if !open { // break // } // } for msg := range c { fmt.Println(msg) } } func print(x string, c chan int) { for i := 0; i <= 5; i++ { c <- i...
package pgsql import ( "github.com/go-pg/pg/v9/orm" "github.com/jpurdie/authapi" ) type User struct{} func (u User) FetchByExternalID(db orm.DB, externalID string) (authapi.User, error){ op := "FetchByExternalID" us := authapi.User{} //get user information err := db.Model(&us). Where("\"user\".external_id =...
// Graphpkg produces an svg graph of the dependency tree of a package // // Requires // - dot (graphviz) // // Usage // // graphpkg path/to/your/package package main import ( "flag" "fmt" "go/build" "log" "os" "os/exec" "regexp" "strings" "github.com/pkg/browser" ) var ( pkgs = make(map[string]map[...
package useerror import ( "errors" "fmt" "testing" ) func TestPanic(t*testing.T){ // 访问切片超出边界,引发运行恐慌 array := []int{1,2,3,4} t.Log(array[2]) panic("手动触发") } func divide(a,b int)(res int,err error){ func(){ defer func(){ if rec := recover();rec != nil{ err = fmt.Errorf("%s",rec) } }() res =...
package htmlLogin import ( "fmt" "strings" "github.com/PuerkitoBio/goquery" ) /* FindLogins: Check if a html document has a login form: Param: doc (goquery.Document) html-document Returns: boolean */ func FindLogins(doc goquery.Document) bool { var foundLogin bool doc.Find("form").Each(func(_ int, s *go...
package api import ( "errors" "time" ) // Error definitions var ( ErrUserNotFound = errors.New("Error user not found") ) type UserID int64 type UserStorage interface { Save(*User) error ByEmail(string) (*User, error) ByID(UserID) (*User, error) } type User struct { ID UserID `db:"id"` Name ...
package fshelper import ( "errors" "fmt" "os" "path/filepath" ) type FlagsChmod uint const ( ChmodChanges FlagsChmod = 1 << iota ChmodVerbose ChmodRecursive ChmodOnlyDirs ChmodOnlyFiles ) var ( ErrSkipFile = errors.New("skip file") ErrSkipDir = errors.New("skip dir") ErrIncompatible...
/* Copyright 2019 Red Hat, 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 dist...
package main import ( "log" "loranet20181205/exception" "loranet20181205/schedule" "loranet20181205/server" ) func main() { log.Printf("LoRa Net Server Version 0.1 Start...\n") exception.Info.Print("LoRa Net Server Version 0.1 Start...\n") /* schedule go routines */ /* file : schedule.go */ schedule.Sched...
package main import ( "fmt" "sort" ) type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // 想法1: 从root节点开始遍历,一次与每一个节点做差值比较,并将绝对值最小的差值保存 // 不与父节点比较,因为已经比较过了 // 采用层次遍历 // 想法2:通过遍历,将树的所有节点放到数组中, 然后对数组进行排序 // 每相邻的两个数求差值,依次比较 func getMinimumDifference(root *TreeNode) int { que := []*TreeNode{} que...
package controller import ( "sixedu/service" ) var ( views map[string][][3]string controllers map[string]interface{} userService *service.UserService authService *service.AuthService ) func init() { views = make(map[string][][3]string, 0) controllers = make(map[string]interface{}, 0) initViews() initC...
package alert import ( "testing" ) func TestMemoryAlert(t *testing.T) { nodeIP := "test" containerID := "test" memoryPercentage := 60 err := MemoryAlert(nodeIP, containerID, memoryPercentage) if err != nil { t.Error(err) } }
package emotes // Registration-related // const // Random filler statements var EMOTE_SEARCHING []string = []string{ "*rifles through the cabinets, and pulls something out*", "*runs their finger along the shelf. They stop and pull something out*", "*rummages under the desk without looking, and grabs what they need...
package queueStack import "testing" func TestMyStack_Push(t *testing.T) { stack := Constructor() stack.Push(1) stack.Push(2) stack.Push(3) t.Log(stack.String()) t.Log(stack.a.Size()) } func TestMyStack_Pop(t *testing.T) { stack := Constructor() stack.Push(1) stack.Push(2) stack.Push(3) t.Log(stack.String(...
// Copyright © 2021 Attestant Limited. // 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 ...
// This file will be processed and embedded to pluginator. package funcwrappersrc import ( "fmt" "os" "sigs.k8s.io/kustomize/api/provider" "sigs.k8s.io/kustomize/api/resmap" "sigs.k8s.io/kustomize/kyaml/fn/framework" "sigs.k8s.io/yaml" ) //nolint func main() { var plugin resmap.Configurable p := provider.Ne...
package main import ( "fmt" "flag" "time" "strings" "math/rand" "github.com/nu7hatch/gouuid" ) func main() { length := flag.Int("len", 18, "The length of code") number := flag.Int("num", 100, "The total number of codes") usepre := flag.Bool("prefix", true, "If use prefix with 8 ch...
package tree import ( "testing" ) func TestStart(t *testing.T) { root1 := NewBiTreeNode(1) root1.SetLChild(NewBiTreeNode(2)) root1.SetRChild(NewBiTreeNode(3)) root1.GetLChild().SetLChild(NewBiTreeNode(4)) root1.GetLChild().SetRChild(NewBiTreeNode(5)) root1.GetRChild().SetLChild(NewBiTreeNode(6)) node2 := root...
package logging import ( "fmt" flag "github.com/heroku/cytokine/Godeps/_workspace/src/github.com/ogier/pflag" "io" "io/ioutil" "log" "os" ) type Options struct { Destination string Prefix string } func Flags(options *Options) { flag.StringVarP( &options.Destination, "log-file", "l", "", "Log file (or...
package main import ( "container/list" "fmt" "math" "sort" ) // https://leetcode-cn.com/problems/container-with-most-water/ // ----------------------------------------------------------------------------- // solution 1 // 两条线段围成的容器面积, 是由较短线段决定的. // 对于最短线段, 剩余线段与其围成的容器面积, 与他们的距离成正比, 不用考虑高度. // 所以对于当前线段集合中的最短线段来说,...
package postal_test import ( "errors" "github.com/cloudfoundry-incubator/notifications/fakes" "github.com/cloudfoundry-incubator/notifications/models" "github.com/cloudfoundry-incubator/notifications/postal" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("TemplateLo...
package main import ( "time" "github.com/zduymz/hpa-operator/pkg/controller" "github.com/zduymz/hpa-operator/pkg/signals" "github.com/zduymz/hpa-operator/pkg/utils" kubeinformers "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" "k8s.io/klog" ) func main() { // ...
// Copyright 2021 Google 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 required by applicable law or agreed to in ...
package dto import ( "github.com/artrey/go-bank-service/pkg/models" ) type MostExpensiveSpending struct { Description string `json:"description"` Sum int64 `json:"sum"` IconUri string `json:"iconUri"` } func FromModelMostExpensiveSpending(s models.MostExpensiveSpending) *MostExpensiveSpending { ret...
package function func Min(a, b int) int { if a < b { return a } return b } func Mins(x ...int) int { if len(x) <= 0 { return 0 } ret := x[0] for _, v := range x { if ret > v { ret = v } } return ret } func Chmin(a *int, b int) bool { if *a > b { *a = b return true } return false }
package handler import ( "net/http" "fmt" "time" "encoding/json" "Demo-auth/model" "github.com/dgrijalva/jwt-go" "github.com/auth0/go-jwt-middleware" "Demo-auth/factory" "golang.org/x/crypto/bcrypt" "log" ) var MySigningKey = []byte("secret") func LoginHandler(w http.ResponseWriter, r *http.Request) { va...
package rest import ( "net/http" "github.com/iris-contrib/middleware/cors" r "github.com/jinmukeji/jiujiantang-services/pkg/rest" "github.com/kataras/iris/v12" "github.com/kataras/iris/v12/middleware/logger" ) // NewApp 创建一个实现了 http.Handler 接口的应用程序 func NewApp(ops *Options) http.Handler { app := iris.New(). ...
package main import ( "./nxfs" "fmt" "os" ) func main() { file, err := os.Create("./sample.dsk") nxfs.CheckError(err) disk, err := nxfs.NewFileDisk(1, 512, file) nxfs.CheckError(err) fmt.Println(disk.Size, disk.SizeOfBlock, disk.FirstFreeBlock, disk.LastFreeBlock) }
package main import ( "bufio" "crypto/md5" "encoding/base64" "flag" "fmt" "io/ioutil" "log" "mime" "os" "path" "path/filepath" "regexp" "strings" ) func main() { flag.Usage = func() { fmt.Printf(`Usage of md-embed: md-embed -o [Output filename] <Input filename> -o string Output file name (default ...
package githubfetch import ( "archive/tar" "bytes" "compress/gzip" "io/ioutil" "testing" ) func TestGitHubFetchTarPrefixStripper(t *testing.T) { tarballBuf := &bytes.Buffer{} gzipWriter := gzip.NewWriter(tarballBuf) tarWriter := tar.NewWriter(gzipWriter) if err := tarWriter.WriteHeader(&tar.Header{ Name: ...
package ltparse import ( "fmt" "io" "sort" "text/template" "github.com/pkg/errors" "github.com/mattermost/mattermost-load-test/loadtest" ) var ( funcMap = template.FuncMap{ "compareInt64": func(a, b int64) string { delta := a - b if delta == 0 { return "0" } else { return fmt.Sprintf("%+d"...
package event import ( "log" "testing" "time" "github.com/stretchr/testify/assert" ) func TestEvent(t *testing.T) { ev := New() assert.NotNil(t, ev) r1 := ev.Fire() <-ev.Done() assert.Equal(t, int32(1), r1) assert.Equal(t, true, ev.HasFired()) r2 := ev.Fire() assert.Equal(t, int32(2), r2) assert.Equal(t...
package dynamo import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" "strings" ) type QueryBuilder struct { Connection Connection TableDefinition TableDefinition Table string Query *d...
package client import ( "fmt" "github.com/zdnscloud/elb-controller/driver/radware/types" ) const ( realServerPortPath = "/config/SlbNewCfgEnhRealServPortTable/" ) type RealServerPortClient struct { token string server string } func NewRealServerPortClient(token, serverAddr string) *RealServerPortClient { re...
/* * Copyright (c) 2018 QLC Chain Team * * This software is released under the MIT License. * https://opensource.org/licenses/MIT */ package types import ( "encoding/hex" "errors" "fmt" "github.com/qlcchain/go-qlc/common/util" "github.com/tinylib/msgp/msgp" "golang.org/x/crypto/blake2b" ) func init() { ...
//+build !latest_release package v1 func getMetadataDir() string { return "v1/metadata" }
// Copyright 2020 The SODA 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 ...
package shell import ( "testing" "github.com/stretchr/testify/assert" ) func TestSetNameShouldReturnSet(t *testing.T) { assert.Equal(t, "set", set(0).name()) } func TestSetsDescriptionShouldNotBeEmpty(t *testing.T) { assert.NotEqual(t, "", set(0).description()) } func TestSetUsageShouldNotBeEmpty(t *testing.T)...
package main import "fmt" /** * created: 2019/7/15 13:17 * By Will Fan */ func main() { m := make(map[string]float64) m["pi"] = 3.14 fmt.Println(m["pi"]) v1 := m["pi"] v2 := m["foo"] fmt.Println(v1, v2) //_, exists := m["pi"] if x, ok := m["pi"]; ok { fmt.Println(x) } delete(m, "pi") fmt.Println(...
package config import ( api "k8s.io/api/networking/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes/fake" "k8s.io/apimachinery/pkg/watch" ktesting "k8s.io/client-go/testing" "k8s.io/apimachinery/pkg/util/wait" "testing...
package seev import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01900101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:seev.019.001.01 Document"` Message *AgentCAMovementInstructionV01 `xml:"AgtCAMvmntInstr"` } func (d *Document0...
package api import ( "log" "github.com/graphql-go/graphql" ) // Schema defined in init() var Schema graphql.Schema func init() { var err error Schema, err = graphql.NewSchema(graphql.SchemaConfig{ Query: graphql.NewObject(graphql.ObjectConfig{ Name: "Query", Fields: graphql.Fields{ "node": nodeDefini...
package main import ( "fmt" ) func main() { // 数组定义及初始化 // 给全部元素赋值 arrs1 := [5]int{1, 2, 3, 4, 5} fmt.Println("arrs1 = ", arrs1) // 给部分元素赋值,未赋值的默认为0 arrs2 := [5]int{1, 2, 3} fmt.Println("arrs2 = ", arrs2) // 给指定元素赋值,未赋值的默认为0 arrs3 := [5]int{1: 10, 4: 30} fmt.Println("arrs3 = ", arrs3) // 给每个元素遍历及赋值 va...
package main import ( "fmt" "os" "strconv" "time" ) func tick(i int, done chan<- bool) { time.Sleep(5000 * time.Millisecond) fmt.Println(i) done <- true } func main() { times, _ := strconv.Atoi(os.Args[1]) done := make(chan bool) for i := 0; i < times; i++ { go func(i int) { tick(i, done) }(i...
package main import "fmt" func twoSum(nums []int, target int) []int { ret := make([]int, 2) cache := make(map[int]int) for k, v := range nums { if f, ok := cache[v]; ok { ret[0] = f ret[1] = k break } cache[target-v] = k } return ret } func main() { fmt.Println(twoSum([]int{2, 7, 11, 15}, 9)) }
/******************************************************************************* * Copyright 2018 Dell 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/licen...
package main import ( "fmt" "strconv" "github.com/jnewmano/advent2020/input" ) func main() { //input.SetRaw(raw) var things = input.Load() ref, current := process(things, false) runGame(ref, current, 100) idx := ref[1] next := idx.Next s := "" for { s += strconv.Itoa(next.Value) next = next.Next ...
package model // Swagger is a struct to define OAS3's Data Structure type Swagger struct { OpenApi string `yaml:"openapi,omitempty"` Info *Info `yaml:"info,omitempty"` Servers []Server `yaml:"servers,omitempty"` Tags []Tag ...
package test import ( "fmt" "reflect" ) func RangePrint(secret interface{}) { value := reflect.ValueOf(secret) fmt.Println(value) // for i := 0; i < value.NumField(); i++ { // fmt.Printf("Field %d: %v\n", i, value.Field(i)) // } }
// ˅ package main // ˄ // An abstract class that generates numbers. type Number struct { // ˅ // ˄ value int observers []Observer // ˅ // ˄ } func NewNumber(value int) *Number { // ˅ number := &Number{} number.value = value return number // ˄ } func (self *Number) AddObserver(observer Observer) { /...
package main import ( "errors" "fmt" "math/rand" "os" "path" "sync" "github.com/nullne/didactic-couscous/volume" ) type file struct { file *os.File lock sync.Mutex size int64 } func openDB(p string) (*file, error) { f, err := os.OpenFile(path.Join(p, "data"), os.O_CREATE|os.O_RDWR, 0666) if err != nil {...
package items import ( "reflect" "testing" ) type parseCurrencyFromStringTestPair struct { input string output Currency } var parseCurrencyFromStringTests = []parseCurrencyFromStringTestPair{ {"1p 80g 55s 3c", Currency{1, 80, 55, 3}}, {"1p80g55s3c", Currency{1, 80, 55, 3}}, {"1p 55s 3c", Currency{1, 0, 55, 3...
package main import ( "fmt" "io/ioutil" "os" "os/signal" "syscall" "time" "github.com/mic92/clusterssh" "golang.org/x/crypto/ssh/terminal" ) type Options struct { cmd string hosts clusterssh.Cluster } func parseArgs(args []string) (*Options, error) { if len(args) < 2 { return nil, fmt.Errorf("USAGE: ...
// 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 notbearparser import "fmt" type NodeList []*Node func (nl NodeList) Filter(f func(*Node) bool) NodeList { filteredList := make(NodeList, 0, 16) for _, node := range nl { if f(node) { filteredList = append(filteredList, node) } } return filteredList } type Node struct { Name string Attr...
package sstable import ( "bytes" "testing" ) func TestSSTable_roundtrip(t *testing.T) { input := []Pair{ Pair{"q", nil}, Pair{"w", []byte{'a'}}, Pair{"o", []byte{'b', 'b'}}, Pair{"p", []byte{'c', 'c', 'c'}}, } var buf bytes.Buffer err := Build(&buf, input) if err != nil { t.Errorf("build err = %#v", ...
package msgpackdiff import ( "fmt" "strings" "testing" "github.com/ttacon/chalk" ) func TestInt(t *testing.T) { a, _ := GetBinary("AQ==") // 1 b, _ := GetBinary("Ag==") // 2 result, _ := Compare(a, b, CompareOptions{}) if result.Equal { t.Error("Wrong result") } var builder strings.Builder result.Pri...
package tests import ( "testing" "../dock" "time" "github.com/ssgo/s" "os" "strings" "encoding/json" "crypto/sha1" "encoding/hex" ) var as *s.AsyncServer var nodes map[string]*dock.NodeInfo var nodeStatus map[string]*dock.NodeStatus var ctx dock.ContextInfo var ctxRuns map[string][]dock.AppStatus func TestS...
package envoyconfig import ( "context" "fmt" "os" "path/filepath" envoy_config_accesslog_v3 "github.com/envoyproxy/go-control-plane/envoy/config/accesslog/v3" envoy_config_bootstrap_v3 "github.com/envoyproxy/go-control-plane/envoy/config/bootstrap/v3" envoy_config_cluster_v3 "github.com/envoyproxy/go-control-p...
package hpkecompact import ( "encoding/hex" "testing" "github.com/powerman/check" ) func TestMain(m *testing.M) { check.TestMain(m) } func TestExchange(t *testing.T) { suite, err := NewSuite(KemX25519HkdfSha256, KdfHkdfSha256, AeadAes128Gcm) if err != nil { t.Fatal(err) } serverKp, err := suite.GenerateK...
package juno import ( "github.com/Mintegral-official/juno/document" "github.com/Mintegral-official/juno/query" ) type Query struct { Exp query.Expression } func (q *Query) HasNext() bool { return q.Exp.HasNext() } func (q *Query) Next() document.DocId { return q.Exp.Next() } func NewQuery(s string) *Query { ...
package main import ( "log" "syscall" ) func main() { mem, err := syscall.Mmap(-1, 0, 1<<30, syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_ANON|syscall.MAP_PRIVATE) if err != nil { log.Fatal(err) } defer syscall.Munmap(mem) for i := 0; i < len(mem); i++ { mem[i] = 'a' } }
package cmd import ( "github.com/spf13/cobra" ) var rootCmd = &cobra.Command{ Use: "terracost", Short: "AWS cost estimation for Terraform projects.", Long: "", } // Execute root command func Execute() error { return rootCmd.Execute() }
/* * KSQL * * This is a swagger spec for ksqldb * * API version: 1.0.0 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package swagger type ExplainResultItemQueryDescriptionFields struct { Name string `json:"name,omitempty"` Type_ st...
package main import ( "testing" "github.com/stretchr/testify/assert" ) func TestStart(t *testing.T) { h := homeAsst{} assert.NotNil(t, h) }
package main import ( "fmt" "github.com/aibotsoft/config-service/pkg/store" "github.com/aibotsoft/config-service/services/handler" "github.com/aibotsoft/config-service/services/server" "github.com/aibotsoft/micro/config" "github.com/aibotsoft/micro/logger" "github.com/aibotsoft/micro/sqlserver" "os" "os/signa...
package main import "fmt" /* 封装: 学生有姓名、年龄和专业等属性 Golang通过struct定义类的属性,通过在func定义时传入类对象的方式定义类的方法,其中属性和方法的公有/私有属性是通过首字母的大小写决定的。 */ type Student struct { name string age int major string } // 如果我们要给Student类定义一个“构造函数”,我们希望的是这个函数的入参可以被赋值到Student的成员内, // 则该“构造函数”应该使用指针类型对象定义: func (s *Student) Init(name string, ag...
package mainWindow import ( "errors" "fmt" "github.com/gabriel-vasile/mimetype" "github.com/myProj/scaner/new/include/appStruct" "github.com/myProj/scaner/new/include/config/newWordsConfig" "github.com/myProj/scaner/new/include/config/settings" "github.com/myProj/scaner/new/include/detectOldOfficeExtension" "g...
package LeetCode func TotalHammingDistance(nums []int) int { out := 0 lengh := len(nums) max := 0 for i := uint(0); i < 32; i++ { c, b := 0, 1<<i if i != 0 && b > max { break } for _, num := range nums { if i == 0 { if max < num { max = num } } if num&b != 0 { c++ } } ou...
/* MADE BY Ex0dIa-dev */ package main import ( "bufio" "flag" "fmt" "io" "log" "net/http" "os" "os/exec" "strings" "sync" "time" ) //flags func init() { flag.StringVar(&url, "u", "", "insert url") flag.StringVar(&format, "f", "mp3", "mp4 or mp3") flag.StringVar(&output, "o", "", "output filename") } ...
package backend import ( "bytes" "crypto/x509" "encoding/json" "encoding/pem" "fmt" "io" "io/ioutil" "regexp" "sort" "strconv" "strings" "text/template" "time" "github.com/Sirupsen/logrus" "github.com/pborman/uuid" "github.com/pkg/sftp" "github.com/travis-ci/worker/config" "github.com/travis-ci/work...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2019-12-14 12:55 # @File : base.go # @Description : # @Attention : */ package models type IBaseResponse interface { GetCode() int SetCode(code int ) int GetMsg() string SetMsg(msg string) }
// Copyright Jetstack Ltd. See LICENSE for details. package kubernetes import ( "testing" "github.com/sirupsen/logrus" ) func TestGenericVaultBackend_Ensure(t *testing.T) { backend := k.NewGenericVaultBackend(logrus.NewEntry(logrus.New())) if err := backend.Ensure(); err != nil { t.Error("unexpected error: ", ...
package main import "fmt" func main() { x := []int{1, 2, 0, 2, 1, 1, 0} sortColors(x) fmt.Println(x) } func sortColors(nums []int) { p0, p1 := 0, 0 for i := 0; i < len(nums); i++ { if nums[i] == 0 { nums[i], nums[p0] = nums[p0], nums[i] if p0 < p1 { // p1 也需要向后挪 nums[i], nums[p1] = nums[p1], nu...
package server import ( "context" "log" "net/http" "os" "os/signal" "syscall" "time" ) // App is a server that handles HTTP requests type App struct { server *http.Server } // New creates an App server instance func New() *App { return &App{ server: &http.Server{ Addr: ":8080", // TODO // Handler: /...
// +build ignore package main import ( "fmt" "runtime" "github.com/viocle-kvanek/gotomation" ) func main() { fmt.Println("Type 'HELLO'") screen, _ := gotomation.GetMainScreen() keyboard := screen.Keyboard() keyboard.KeyDown(gotomation.VK_SHIFT) keyboard.KeyPress(gotomation.VK_H) keyboard.KeyPress(gotomatio...
package main import "fmt" func main() { const ( LosAngeles = 1984 + (iota * 4) Seoul Barcelona Atlanta Sydney Athens Beijing London Rio Tokyo ) fmt.Println("These cities hosted or will host the Summer Olympics in the provided year...") fmt.Printf("%-18s %-18s \n", "City", "Year") fmt.Printf...
// ints_test.go; Tests for package ints. package ints import ( "testing" ) func TestParse(t *testing.T) { cases := []struct { s string want int }{ {"0", 0}, {"-0", 0}, {"-2", -2}, {"4294967296", 4294967296}, {"4294967296", 1 << 32}, {"4611686018427387904", 1 << 62}, } for i, tt := range cases ...
// Copyright (c) 2020 twihike. All rights reserved. // Use of this source code is governed by a MIT license // that can be found in the LICENSE file. // Package structconv is a converter between struct and other data. package structconv import ( "fmt" "reflect" ) const ( msgDetailInvalidType = "invalid type: in=%...
package nougat import ( "context" "fmt" "net" "net/http" "sync/atomic" "testing" ) func TestReuseTcpConnections(t *testing.T) { var connCount int32 ln, _ := net.Listen("tcp", ":0") rawURL := fmt.Sprintf("http://%s/", ln.Addr()) server := http.Server{ Handler: http.HandlerFunc(func(w http.ResponseWriter,...
package LeetCode import "strings" func LengthOfLastWord(s string) int { result := strings.Split(s," ") for i := len(result) - 1; i >= 0; i-- { if len(result[i]) == 0 { continue } return len( result[i] ) } return 0 }
package main import ( "os" "github.com/dolab/gogo/gogo/commands" "github.com/golib/cli" ) func main() { app := cli.NewApp() app.Name = "gogo" app.Version = "1.0.0" app.Usage = "gogo COMMAND [ARGS]" app.Authors = []cli.Author{ { Name: "Spring MC", Email: "Heresy.MC@gmail.com", }, } app.Commands...
package values import ( "context" "fmt" "github.com/giantswarm/apiextensions-application/api/v1alpha1" "github.com/giantswarm/microerror" "github.com/giantswarm/micrologger" "github.com/imdario/mergo" "k8s.io/client-go/kubernetes" "sigs.k8s.io/yaml" ) // Config represents the configuration used to create a n...
package main import ( v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func createTypeMeta() metav1.TypeMeta { return metav1.TypeMeta{ Kind: "Pod", APIVersion: "v1", } } func createObjectType() metav1.ObjectMeta { return metav1.ObjectMeta{ Namespace: "mem-example", Name: ...
package main import ( "fmt" ) func main() { var i int = 123 var u uint32 = uint32(i) var f float32 = float32(u) var s string = string(i) var b []byte = []byte("abc") fmt.Println(u) fmt.Println(f) fmt.Println(s) fmt.Println(b) }
package models // AgentConf is agent conf type AgentConf struct { RedisHost string RedisPasswd string } // RunTime is runtime from flag var RunTime string // RunTimeInfo is run time info var RunTimeInfo AgentConf // RunTimeMap is run time info map var RunTimeMap map[string]AgentConf
package sorter import ( "fmt" "io/ioutil" "os" "sort" "strings" "github.com/alde/plexsorter/parser" "github.com/sirupsen/logrus" ) // Sort watched videos into their proper place func Sort(watched []parser.PlexVideo, target parser.PlexSection) { if len(watched) == 0 { logrus.Info("no watched videos") retu...
// NewS3Client will return a new AWS SDK client for interacting with AWS Secrets Manager. package awscommons import ( "strings" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/gruntwork-io/go-commons/errors" ) // UploadObjectString will upload the provided string to the ...
package pass_test import ( "testing" "github.com/mmcloughlin/avo/ir" "github.com/mmcloughlin/avo/reg" "github.com/mmcloughlin/avo/pass" "github.com/mmcloughlin/avo/build" "github.com/mmcloughlin/avo/operand" ) func TestLivenessBasic(t *testing.T) { // Build: a = 1, b = 2, a = a+b ctx := build.NewContext() ...
// Copyright (c) 2017 Cisco and/or its affiliates. // // 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 applicabl...
package handler import ( "context" "database/sql" "errors" "fmt" "log" "net/http" "github.com/boombaw/go-wilayah/domain/villages" "github.com/boombaw/go-wilayah/util" "github.com/jmoiron/sqlx" "github.com/labstack/echo/v4" ) // DetailByDistrict struct type DetailByDistrict struct { DBx *sqlx.DB } // Hand...
package model_test import ( "context" "database/sql" "encoding/json" "fmt" "net/url" "testing" "time" "github.com/golang/mock/gomock" "github.com/google/uuid" "github.com/ory/fosite" "github.com/ory/fosite/handler/openid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "githu...
package queue import ( "errors" log "github.com/sirupsen/logrus" "io" ) func readOneMsg(conn io.Reader) ([]byte, error) { sizeBytes := make([]byte, 0, ElementMetadataSize) for { if ElementMetadataSize == len(sizeBytes) { break } buffer := make([]byte, ElementMetadataSize- len(sizeBytes)) n, err := c...
package main import ( "fmt" "sync" "time" ) //we declared sync package to add a waitgroup //with waitgroup we would be able to wait for a goroutine to finish before programme moves ahead //when the programme finishes, the waitgroup is notified, which notifies the program in turn var wg sync.WaitGroup func saySyn...
package main import ( "log" "os" ) func getFile(name string) (*os.File, func(), error) { file, err := os.Open(name) if err != nil { return nil, nil, err } return file, func() { file.Close() }, err } func main() { _, closer, err := getFile(os.Args[1]) if err != nil { log.Fatal(err) } defer closer() }...
// Package vsphere collects vSphere-specific configuration. package vsphere import ( "context" "fmt" "sort" "strings" "time" "github.com/AlecAivazis/survey/v2" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/vmware/govmomi/vapi/rest" "github.com/vmware/govmomi/vim25" "k8s.io/apimachinery/p...
package main import "fmt" func main() { printRange(10, 35) } func printRange(n int, m int) { for i := n ; i <= m ; i++ { fmt.Println(i) } }
package common import ( "github.com/dgrijalva/jwt-go" "forum_Anpw/model" "time" ) var jwtKey =[]byte("Anpw") type Claims struct { UserID uint jwt.StandardClaims } //颁发证书 func ReleaseToken(user model.User)(string,error){ //token过期时间 expirationTime :=time.Now().Add(7*24*time.Hour) claims:=&Claims{ UserID:...
package main import "fmt" func add(a, b int) (int, int) { var c int c = a + b d := 10 //return d, c return c, d } func main() { fmt.Println(add(3, 5)) }