text
stringlengths
11
4.05M
package max func maxDepth(s string) int { var m, k int for _, c := range s { switch c { case '(': k++ if k > m { m = k } case ')': k-- } } return m }
package main import "sort" //1584. 连接所有点的最小费用 //给你一个points数组,表示 2D 平面上的一些点,其中points[i] = [xi, yi]。 // //连接点[xi, yi] 和点[xj, yj]的费用为它们之间的 曼哈顿距离:|xi - xj| + |yi - yj|,其中|val|表示val的绝对值。 // //请你返回将所有点连接的最小总费用。只有任意两点之间 有且仅有一条简单路径时,才认为所有点都已连接。 // //示例 2: // //输入:points = [[3,12],[-2,5],[-4,1]] //输出:18 //示例 3: // //输入:points...
package controllers import ( "encoding/json" "io" "io/ioutil" "log" "net/http" "atlas-api/config/schema" "atlas-api/db" "atlas-api/helpers" ) // AuthenticatePostData will hold the email and password of the request // that was sent up by the clientf type AuthenticatePostData struct { Email string Passwor...
package SaleProvider type ISale interface { GetId() string GetItemName() string GetItemDescription() string GetAmountGross() float32 IsAuthorized() bool UpdateSaleAsAuthorizedCompleted(payfastPaymentId string, amountFee, amountNet float32) UpdateSaleAsFailed(payfastPaymentId string) UpdateSaleAsPending(payfast...
// Copyright (c) Liam Stanley <me@liamstanley.io>. All rights reserved. Use // of this source code is governed by the MIT license that can be found in // the LICENSE file. package girc import ( "encoding/base64" "fmt" ) // SASLMech is an representation of what a SASL mechanism should support. // See SASLExternal a...
package main import "fmt" type avpair_type int type avpairs map[avpair_type] [][]byte func (a avpairs) Add(key avpair_type, value []byte) { a[key] = append(a[key], value) } func (a avpairs) rc_pack_avpair_list(b []byte) { for curr_type, avpair_data := range a{ /* TLV Format (type = 1 byte, leng...
package main import ( "io" "bytes" "net/http" "golang.org/x/net/html" ) type Fetcher interface { // Fetch returns the body of a url and a slice of urls on that page Fetch(url string) (body string, urls []string, err error) } type SimpleFetcher struct { } func (f SimpleFetcher) Fetch(url stri...
// Code generated - DO NOT EDIT. // This file is a generated binding and any manual changes will be lost. package Vault import ( "math/big" "strings" ethereum "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereu...
package tgo var RpcURL = "http://192.168.1.241:8732"
package data type Filter int const ( // FilterLt represents strictly Less than FilterLt Filter = iota // FilterLe represents Less than or equal FilterLe // FilterEq represents equal FilterEq // FilterGe represent greater than or equal FilterGe // FilterGt represents strictly greater than FilterGt )
package clingon import ( "fmt" "github.com/scottferg/Go-SDL/sdl" "github.com/scottferg/Go-SDL/ttf" "testing" ) var ( appSurface *sdl.Surface sdlrenderer *SDLRenderer ) func initSDL() { if sdl.Init(sdl.INIT_VIDEO) != 0 { panic(sdl.GetError()) } if ttf.Init() != 0 { panic(sdl.GetError()) } font := tt...
package main import "./greeting" import "fmt" func RenameToFrog(r greeting.Renamable) { r.Rename("Frog") } func main() { //var s = greeting.Salutation{"Bob", "Hello"} salutations := greeting.Salutations{ {"Bob", "Hello"}, {"Joe", "Hi"}, {"Mary", "What is up?"}, } //salutations[0].Rename("John") //Rena...
package prime import "math" func isPrime(x int) bool { if x == 2 { return true } for i := 2; i <= int(math.Sqrt(float64(x))); i++ { if x%i == 0 { return false } } return true } // Nth returns n-th prime number. func Nth(n int) (int, bool) { if n <= 0 { return 0, false } var i int for i = 2; n > 0...
package rpcclient import ( "context" "fmt" "kto/rpcclient/message" "kto/transaction" "kto/types" "kto/until" "testing" "time" "google.golang.org/grpc" ) var ctx context.Context var client message.GreeterClient func init() { from := types.BytesToAddress([]byte("CNtyeiE8RkTy26ufueMnvvbkEJ5qQL7tjD8Su5BP8PLY"...
package v1 import ( "fmt" "github.com/gin-gonic/gin" "github.com/mihail-1212/todo-project-backend/internal/service" "github.com/mihail-1212/todo-project-backend/pkg/auth" "github.com/mihail-1212/todo-project-backend/pkg/auth/models" "github.com/mihail-1212/todo-project-backend/pkg/domain" "github.com/mihail-12...
package lc // Time: O(n) // Benchmark: 12ms 5.8mb | 90% 78% func maxArea(height []int) int { var current, max int l, r := 0, len(height)-1 for l < r { if height[l] < height[r] { current = height[l] * (r - l) l++ } else { current = height[r] * (r - l) r-- } if current > max { max = current...
func removeElement(nums []int, val int) int { cur := 0 right := 0 for right < len(nums) { if nums[right] != val { nums[cur] = nums[right] cur++ } right++ } return cur }
package appointments import ( "Scheduler/models/db" "errors" "fmt" "log" mathRand "math/rand" "time" ) type Appointment struct { ID int UserID int StartTime time.Time EndTime time.Time Date time.Time Active bool } var Appointments []Appointment func GetAppointments(date time.Time) (e...
package main import ( "fmt" "time" "regexp" "strings" d "github.com/bwmarrin/discordgo" r "gopkg.in/rethinkdb/rethinkdb-go.v6" ) func botRefresh(state State) { ticker := time.NewTicker(1 * time.Hour) for _ = range ticker.C { for _, bot := range state.GetBots() { state.ValidateB...
/* package xmodel provides a post-compiled representation of the scripts. It is used internally by the compiler, and has been superseded by sashimi/compiler/model. ( It should probably be assumed to be internally consistent. ) The table version of things would also build,merge into this same code. The script callbacks...
package thorchain import ( "fmt" "testing" . "gopkg.in/check.v1" "github.com/zlyzol/xchaingo/common" ) /* func TestHttpGet(t *testing.T) { address := "tthor1fs5jqvwp9u05802vfsru8zndmq5ucanrw8gg96" c := NewHttpClient("https://testnet.thornode.thorchain.info") _, _, err := c.Get("/bank/balances/" + string(address...
package util import ( "fmt" apps "k8s.io/api/apps/v1beta1" "k8s.io/api/core/v1" "k8s.io/api/extensions/v1beta1" "k8s.io/client-go/kubernetes/scheme" "kolihub.io/koli/pkg/spec" ) // StatefulSetDeepCopy creates a deep-copy from a StatefulSet // https://github.com/kubernetes/kubernetes/blob/master/docs/devel/cont...
package parallel import ( "fmt" "math/rand" "sync" ) var count int var rw sync.RWMutex func Read(n int, ch chan struct{}) { rw.RLock() fmt.Printf("goroutine %d 进入读操作...\n", n) v := count fmt.Printf("goroutine %d 读取结束,值为:%d\n", n, v) rw.RUnlock() ch <- struct{}{} } func Write(n int, ch chan struct{}) { rw....
package main import "fmt" // ********************************************* // when using channels in function parameters, // you can specify if a channel is meant to only // send or receive values. // ********************************************* // ping function only accept a channel for sending values. // this inc...
/* * @lc app=leetcode id=204 lang=golang * * [204] Count Primes * * https://leetcode.com/problems/count-primes/description/ * * algorithms * Easy (31.23%) * Likes: 2064 * Dislikes: 619 * Total Accepted: 366.6K * Total Submissions: 1.2M * Testcase Example: '10' * * Count the number of prime numbers...
package steps_test import ( "testing" "github.com/joshuacrass/online-upgrade/steps" "github.com/joshuacrass/online-upgrade/testutil" "github.com/joshuacrass/online-upgrade/util" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // TestRestoreRedundancy test redundancy was able to be ...
package vue_test import ( "testing" sitter "github.com/kiteco/go-tree-sitter" "github.com/kiteco/go-tree-sitter/vue" "github.com/stretchr/testify/assert" ) func TestGrammar(t *testing.T) { assert := assert.New(t) parser := sitter.NewParser() parser.SetLanguage(vue.GetLanguage()) sourceCode := []byte(` <tem...
// Copyright © 2017 @telecoda // // 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 host import ( "context" "encoding/json" "fmt" "github.com/choria-io/go-choria/protocol" "github.com/choria-io/go-choria/providers/agent/mcorpc" rpc "github.com/choria-io/go-choria/providers/agent/mcorpc/client" addl "github.com/choria-io/go-choria/providers/agent/mcorpc/ddl/agent" "github.com/choria-i...
package main import ( "fmt" "os" "github.com/drone/drone-go/drone" "github.com/drone/drone-go/plugin" "github.com/drone/drone-go/template" ) var ( buildCommit string defaultTemplate = `<strong>{{ uppercasefirst build.status }}</strong> <a href="{{ system.link_url }}/{{ repo.owner }}/{{ repo.name }}/{{ bui...
package task import ( "fmt" "io" "os" "github.com/go-task/task/v3/errors" "github.com/go-task/task/v3/internal/filepathext" ) const defaultTaskfile = `# https://taskfile.dev version: '3' vars: GREETING: Hello, World! tasks: default: cmds: - echo "{{.GREETING}}" silent: true ` const default...
package main import ( "fmt" "log" "net/http" "os" "time" _ "net/http/pprof" "github.com/pivotal-cf/terminalboard/api" capi "github.com/pivotal-cf/terminalboard/concourse/api" "golang.org/x/oauth2" ) const ( concourseHostEnvKey = "CONCOURSE_HOST" concourseUsernameEnvKey = "CONCOURSE_USERNAME" concour...
package main import ( "log" "net/http" "github.com/gorilla/mux" people "./controllers" ) // The person Type (more like an object) // Display all from the people var // main function to boot up everything func main() { inicialize() router := mux.NewRouter() router.HandleFunc("/people", people.GetPeople).Met...
package lc // Time: O(n) // Benchmark: 0ms 2.2mb | 100% func subsets(nums []int) [][]int { subs := [][]int{} var search func(set []int, k int) search = func(set []int, k int) { if k == len(nums) { subs = append(subs, append([]int{}, set...)) return } set = append(set, nums[k]) search(set, k+1) set ...
package main import ( "bytes" "flag" "fmt" "html/template" "io/ioutil" "log" "path/filepath" "regexp" ) const ( tmplFile = "index-tmpl.html" tmplAnalyticsHTML = "analytics.html" ) var ( devFlag = flag.Bool("dev", false, "Generate development index.html") prodFlag = flag.Bool("prod", false, "Gen...
package common import ( "io" "os" "time" "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" ) const LogMsgCtxKey = "common_log_info" var log = logrus.New() type Log struct { entry *logrus.Entry } func NewLogger(serviceName string) *Log { entry := log.WithFields(logrus.Fields{ "service": serviceName,...
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package power import ( "context" "time" "github.com/golang/protobuf/ptypes/empty" "chromiumos/tast/common/servo" "chromiumos/tast/common/usbutils" "chromiumos/tast/c...
// Copyright 2016-2017 Authors of Cilium // // 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 main import ( "fmt" ) func main() { x := factorial(4) fmt.Println(x) } func factorial(x int) int { if x == 0 { return 1 } return x * factorial(x-1) } //function calls itself is called recursion and factorial is recursive function eg // ie factorial of 4 is 4*3*2*1
package event import ( "github.com/go-redis/redis/v8" "log" "shared/utility/global" "shared/utility/glog" "shared/utility/param" "testing" ) func TestEventLooper_Get(t *testing.T) { glog.InitLog() Redis := &redis.Options{ Username: "root", Password: "", Addr: ":6379", } RedisClient := redis.NewCl...
// Copyright 2015 go-swagger maintainers // // 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 agr...
package worker import ( "fmt" "github.com/CleverTap/cfstack/internal/pkg/aws/cloudformation" "github.com/CleverTap/cfstack/internal/pkg/aws/s3" "github.com/CleverTap/cfstack/internal/pkg/aws/session" "github.com/CleverTap/cfstack/internal/pkg/stack" "github.com/Jeffail/gabs" "github.com/aws/aws-sdk-go/aws/awser...
package main import ( "./GmailCredentialManager" "encoding/base64" "fmt" "google.golang.org/api/gmail/v1" "strings" ) func main() { client := GmailCredentialManager.GetService() _ = GetAllMessagesFromUser(client, "", 4) } func GetLastNMessages(srv *gmail.Service, n int) []*gmail.Message { s := make([]*gmai...
package main import "fmt" type Vertex struct { x int //, 这里不能有逗号 y int } func main() { fmt.Println(Vertex{1, 2}) var a Vertex a.x = 1 a.y = 2 fmt.Println(a) }
package query const ( // DBProtoVersion is the cassandra protocol version used by gophr. DBProtoVersion = 4 // DBKeyspaceName is the name of the gophr cassandra keyspace. DBKeyspaceName = "gophr" )
package main import "fmt" func main() { t := 10 fmt.Print(t / 3) } type ListNode struct { Val int Next *ListNode } func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { ret := &ListNode{ Val: 0, } left := 0 retHead := ret for l1 != nil || l2 != nil { sum := left if l1 != nil { sum += l1.Val ...
/* 1. Program that prints out all numbers between 1 and 100 that are divisible by 3 2. Program that prints the numbers from 1 to 100, but for multiples of three, print "Fizz" instead of the number, and for the multiples of five, print "Buzz". For numbers that are multiples of both three and five, pri...
// Copyright 2017 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 import ( "CurrencyConverter/converters" "CurrencyConverter/validate" "fmt" "strconv" ) func main() { c := &converters.CAD{Label: "CAD", Symbol: "$", Amount: 0} u := &converters.USD{Label: "USD", Symbol: "$", Amount: 0} e := &converters.EUR{Label: "EUR", Symbol: "€", Amount: 0} converters := []con...
package jwt_auth import ( "finance/plugins/redis" "fmt" ) // 校验token是否被刷新 func (claims *CustomClaims) AuthToken() bool { redis_key := fmt.Sprintf("FinanceIat_%s", claims.Phone) redis_iat, _ := redis.Get(redis_key) if claims.Iat != redis_iat { return false } else { return true } } func (claims *CustomClaim...
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // package main import "github.com/spf13/cobra" type clusterInstallationGetFlags struct { clusterFlags clusterInstallationID string } func (flags *clusterInstallationGetFlags) addFlags(command *cobra.Co...
// Copyright 2020 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 util import ( "fmt" "github.com/appscode/go/types" core "k8s.io/api/core/v1" "kmodules.xyz/client-go/tools/cli" "kmodules.xyz/client-go/tools/clientcmd" "stash.appscode.dev/stash/apis" v1alpha1_api "stash.appscode.dev/stash/apis/stash/v1alpha1" v1beta1_api "stash.appscode.dev/stash/apis/stash/v1beta1"...
package main import ( "fmt" "github.com/aliyun/aliyun-datahub-sdk-go/datahub" ) func main() { dh = datahub.New(accessId, accessKey, endpoint) } func openOffset() { shardIds := []string{"0", "1", "2"} oss, err := dh.OpenSubscriptionSession(projectName, topicName, subId, shardIds) if err != nil...
// These are examples of manipulating binary values. package binary
package core import ( "database/sql" "database/sql/driver" ) // Scan implements the sql.Scanner interface. func (this *Int) Scan(value interface{}) error { if value == nil { this.int, this.Valid = 0, false return nil } var ns sql.NullInt64 err := ns.Scan(value) if err != nil { this.int = int(ns.Int64) ...
package helm import ( "crypto/subtle" "net/http" "strings" "time" "github.com/rancher/fleet/integrationtests/cli" ) const ( username = "user" password = "pass" ) type repository struct { server *http.Server port string } // starts a helm repository on localhost:3000. It contains all repositories that ar...
package tiltfile import ( "context" "fmt" "path/filepath" "strings" "time" "github.com/looplab/tarjan" "github.com/pkg/errors" "go.starlark.net/starlark" "go.starlark.net/syntax" "golang.org/x/mod/semver" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/tilt-dev/tilt/internal/controllers/apis/cm...
// 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 policy import ( "context" "chromiumos/tast/common/fixture" "chromiumos/tast/common/pci" "chromiumos/tast/common/policy" "chromiumos/tast/common/policy/fakedms"...
package enum_generator import ( "github.com/morlay/gin-swagger/codegen" "github.com/morlay/gin-swagger/program" "github.com/morlay/gin-swagger/swagger" "go/types" "path/filepath" "strings" ) func NewEnumGenerator(packagePath string) *EnumGenerator { prog := program.NewProgram(packagePath) return &EnumGenerat...
package infrastructure import ( "flag" "github.com/spf13/viper" "log" "path" "strings" ) type httpListen struct { Ip string Port int } type logs struct { PathToLogFile string Level string // it can be (error/warn/info/debug) } type db struct { Host string Port int Dbname ...
package removeelement func removeElement(nums []int, val int) int { var count int // 重复 val 个数 for i := 0; i < len(nums); { if nums[i] == val { count++ if i == len(nums)-1 { // 最后一个元素也等于 val nums = append(nums[:i-count+1]) } } else { if count != 0 { nums = append(nums[:i-count], nums[i:]...) ...
/* Sudoku Solver Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. */ package main // 位图检测+回溯法 func solveSudoku(board [][]byte) { if len(board) != 9 || len(board[0]) != 9 { return } co...
package editors type ( // Taskfile wraps task list output for use in editor integrations (e.g. VSCode, etc) Taskfile struct { Tasks []Task `json:"tasks"` Location string `json:"location"` } // Task describes a single task Task struct { Name string `json:"name"` Desc string `json:"desc"` ...
package main import "testing" func TestParse(t *testing.T) { values := loadData("test_input.txt") _, root := parseData(values, 0) if len(root.children) != 2 { t.Errorf("Root should have 2 children, found %v.", len(root.children)) } if len(root.metadata) != 3 { t.Errorf("Root should have 3 metadata, found %v....
package main import ( "strconv" "fmt" ) func convertFormat(input string) string { sh := input[0:2] part := input[8:10] hour, _ := strconv.Atoi(sh) if part == "PM" && hour != 12 { hour += 12 } else if part == "AM" && hour == 12 { hour = 0 } return fmt.Sprintf("%02d%s", hour, input[2:8]) } ...
package main import "github.com/sadasant/scripts/go/euler/euler" func solution(n int) int { var s int for i := 0; i < n; i++ { if i%3*i%5 == 0 { s += i } } return s } func main() { euler.Init(1, "Find the sum of all the multiples of 3 or 5 below 1000.") euler.PrintTime("Result: %v, Nanoseconds: %d\n", s...
../src0/base_1529__tcpBufMachine__irun.go
package client import ( "context" "fmt" "log" "github.com/piotrkira/microservices-calc/muldiv/endpoints" "google.golang.org/grpc" ) type Client struct { cli endpoints.MulDivClient } func New(serverAddres string) *Client { client := Client{} connection, err := grpc.Dial(fmt.Sprintf("%s:7777", serverAddres),...
package log import ( "fmt" "github.com/project-flogo/core/activity" "github.com/project-flogo/core/data/coerce" ) func init() { _ = activity.Register(&Activity{}) } type Input struct { Message string `md:"message"` // The message to log AddDetails bool `md:"addDetails"` // Append contextual execution ...
package dockercomposeservice import ( "context" "testing" "time" dtypes "github.com/docker/docker/api/types" "github.com/jonboulle/clockwork" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/...
package majiangserver import ( //cmn "common" //"fmt" //"debug" "logger" "math" "sort" "time" ) const ( ESuccess = iota ECardNull ETypeAmountMuch ECardFullSame ) //胡牌类型 const ( DanDiaoHu = iota //单调胡 ShunZiHu //顺子胡 DuiChuHu //对处胡 ) //模式类型 const ( NormalPattern = iota //普通模式 DaDuiZ...
/* * Copyright 2021 American Express * * 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...
package cmd import ( "fmt" "github.com/infobloxopen/atlas-contacts-app/cmd/setting" "github.com/infobloxopen/atlas-contacts-app/db" ) //const ( // // ServerAddress is the default address for the gRPC server, if no override is specified in the flags // ServerAddress = "0.0.0.0:9090" // // GatewayAddress is the defa...
package dbsearch import ( "runtime" //"log" "reflect" "strconv" "testing" ) func Benchmark_TestSpeed_01(b *testing.B) { runtime.GOMAXPROCS(8) b.StopTimer() //stop the performance timer temporarily while doing initialization s := init_test_data() if s == nil { b.Fatal("Benchmark_TestSpeed_02") } main_spee...
package gpi import ( "io/ioutil" "os" "testing" ) func TestGetPageIds(t *testing.T) { file, err := os.Open("gpi_test.html") if err != nil { t.Errorf("%s", err.Error()) return } defer file.Close() b, err := ioutil.ReadAll(file) if err != nil { t.Errorf("%s", err.Error()) return } ids := GetPageIds...
package controllers import ( "net/http" "strconv" m "github.com/fullstacktf/Narrativas-Backend/models" "github.com/gin-gonic/gin" ) func Get(c *gin.Context) { var stories m.Stories useridParam, _ := c.Get("user_id") userid := useridParam.(uint) err := stories.Get(userid) if err != nil { c.AbortWithStatus...
package main import ( "fmt" "log" "os" "time" "github.com/chedom/go_prog_lang/ch4/github" ) func main() { result, err := github.SearchIssues(os.Args[1:]) var lessThenMonth, lessThenYear, pastThenYear []*github.Issue if err != nil { log.Fatal(err) } now := time.Now() for _, v := range result.Items { s...
package kubeobjects import ( "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" ) func FindContainerInPod(pod corev1.Pod, name string) (*corev1.Container, error) { container := FindContainerInPodSpec(&pod.Spec, name) if container != nil { return container, nil } podName := GetPodName(pod) return nil, errors...
package connmgr import ( "fmt" "github.com/multivactech/MultiVAC/model/chaincfg" "github.com/multivactech/MultiVAC/model/wire" "net" "strings" "testing" "time" ) func TestSeedFromDNS(t *testing.T) { params := chaincfg.Params{ Name: "Davis", Net: 0, DefaultPort: "2333", DNSSeeds: []chain...
package main import "fmt" //截取操作有带 2 个或者 3 个参数,形如:[i:j] 和 [i:j:k],假设截取对象的底层数组⻓度为 l。在操作符 [i:j] 中,如果 i 省略,默认 0,如果 j 省略,默认底层数组的⻓度,截取得到的切片⻓度和容量计算方法是 j- i、l-i。操作符 [i:j:k],k 主要是用来限制切片的容量,但是不能大于数组的⻓度 l,截取得到的切片⻓度 和容量计算方法是 j-i、k-i。 func main() { s := [3]int{1, 2, 3} a := s[:0] b := s[:2] c := s[1:2:cap(s)] fmt.Println(...
package stack // // minOperations // func minOperations(logs []string) int { s := NewStack() for _, x := range logs { switch x { case "./": continue case "../": s.Pop() default: s.Push("../") } } return s.Count() } // // Count Stack // func NewStack() *stack { return &stack{} } type stack...
package session import ( "fmt" "github.com/trist725/mgsu/event" "github.com/trist725/myleaf/gate" "github.com/trist725/myleaf/log" "github.com/trist725/myleaf/timer" "mlgs/src/model" "sync/atomic" "time" ) //todo:心跳处理 type Session struct { id uint64 //事件管理器 eventHandlerMgr *event.HandlerManager //定时写库 ti...
package course_data_api import ( "encoding/json" "fmt" "github.com/andrewmthomas87/northwestern/models" "io/ioutil" "net/http" "strings" ) var badResponseError = fmt.Errorf("request returned an error") type Client struct { baseUrl string apiKey string apiKeyParameter string httpClient *ht...
package models import ( "time" ) type CelebrationModel struct { ID uint `gorm:"primaryKey" json:"id"` WorkArea string `json:"work_area"` ChamberTerritoryID string `json:"chamber_territory_id"` DrChildID string `json:"dr_child_id...
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // package metrics import ( "strconv" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" ) const ( provisionerNamespace = "provisioner" prov...
// 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 import ( "fmt" "net/http" "time" ) // Display a greeting and the current date/time to a user. func greeting(w http.ResponseWriter, r *http.Request) { dt := time.Now() fmt.Fprintf(w, "Hello! Welcome to my containerized web server in Golang!\nToday's date and time is: %s", dt.Format("02...
package main import ( "net/http" "github.com/labstack/echo" "github.com/labstack/echo/middleware" ) func createServer() *echo.Echo { e := echo.New() e.Use(middleware.CORS()) e.GET("/note", func(c echo.Context) error { return c.NoContent(http.StatusOK) }) e.POST("/note/:user", func(c echo.Context) error { ...
package plugin import ( "fmt" "net" log "github.com/golang/glog" osclient "github.com/openshift/origin/pkg/client" osconfigapi "github.com/openshift/origin/pkg/cmd/server/api" "github.com/openshift/origin/pkg/util/netutils" kclient "k8s.io/kubernetes/pkg/client/unversioned" kerrors "k8s.io/kubernetes/pkg/ut...
/* * Paged * * Handles CRUD operations for events * * API version: 0.0.1 * Generated by: OpenAPI Generator (https://openapi-generator.tech) */ package main import ( "fmt" "log" "github.com/tuuturu/pager-event-service/pkg/core/router" "github.com/tuuturu/pager-event-service/pkg/core" ) func main() { log...
package services import ( "errors" "github/Hiinnn/practice-go/config" "github/Hiinnn/practice-go/models" "time" "unicode" "github.com/dgrijalva/jwt-go" "golang.org/x/crypto/bcrypt" ) var secretKey []byte /* -------------------------------------------------------------------------- */ /* ...
// Copyright (c) 2020 StackRox 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 stringify import "encoding/hex" func SliceOfBytes(value []byte) string { switch { case value == nil: return "<nil>" case len(value) == 0: return "<empty>" default: return "0x" + hex.EncodeToString(value) + "" } }
package scheduler import ( "context" "encoding/json" "io/ioutil" "os" "time" "github.com/hashicorp/go-multierror" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "nidavellir/config" "nidavellir/libs" "nidavellir/services/iofiles" rp "nidavellir/services/repo" "nidavellir/services/store" ) type...
package main import ( "testing" ) func TestURLify(t *testing.T) { tests := map[string]struct { str string want string }{ "1": { str: "Mr John Smith ", want: "Mr%20John%20Smith", }, } for name, tt := range tests { t.Run(name, func(t *testing.T) { if got := urlify(tt.str); got != tt.want { ...
package token import ( "fmt" "net/url" "os" "path/filepath" "strings" homedir "github.com/mitchellh/go-homedir" "github.com/cloudflare/cloudflared/config" ) // GenerateSSHCertFilePathFromURL will return a file path for creating short lived certificates func GenerateSSHCertFilePathFromURL(url *url.URL, suffix...
package msgbroker // MessageBroker defines our interface for connecting, producing and consuming messages type MessageBroker interface { PublishOnQueue(body []byte, queueName string) error Subscribe(exchangeName string, handlerFunc func(data []byte)) error Close() } /* // Defines our interface for connecting, prod...
// Shows a dialog with a multiline, a text, a list and some buttons. You can test the multiline attributes by clicking on the buttons. Each button is related to an attribute. Select if you want to set or get an attribute using the dropdown list. The value in the text will be used as value when a button is pressed. pack...
package container import ( "errors" "fmt" ) var ( ErrObjectNotFound = errors.New("not found in container") ErrArgsNotInstanced = errors.New("args not instanced") ErrInvalidReturnValueCount = errors.New("invalid return value count") ErrRepeatedBind = errors.New("repeated bind") ErrInv...