text
stringlengths
11
4.05M
package auth import ( "github.com/moisespsena/go-path-helpers" "github.com/moisespsena/go-i18n-modular/i18nmod" ) var PREFIX = path_helpers.GetCalledDir() var I18N_GROUP = i18nmod.PkgToGroup(PREFIX)
package controllers import ( "net/http" "github.com/garyburd/redigo/redis" kredis "goapi/lib/db/redis" klog "goapi/lib/log" ) func Testredis(w http.ResponseWriter, r *http.Request) { //https://godoc.org/github.com/garyburd/redigo/redis redis_set() redis_get() redis_list_set() redis_list_get() redis_hash...
package web import ( "context" "fmt" pb "github.com/autograde/aguis/ag" ) // rebuildSubmission rebuilds the given lab assignment and submission. func (s *AutograderService) rebuildSubmission(ctx context.Context, request *pb.LabRequest) error { lab, err := s.db.GetAssignment(&pb.Assignment{ID: request.GetAssignme...
package dag import "github.com/Qitmeer/qitmeer-lib/common/hash" // HashList is used to sort hash list type HashList []*hash.Hash func (sh HashList) Len() int { return len(sh) } func (sh HashList) Less(i, j int) bool { return sh[i].String() < sh[j].String() } func (sh HashList) Swap(i, j int) { sh[i], sh[j] = sh...
// Source : https://oj.leetcode.com/problems/zigzag-conversion/ // Author : Austin Vern Songer // Date : 2016-03-07 /********************************************************************************** * * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: * (you ...
package modals import ( "net/http" "encoding/json" "strconv" "github.com/gorilla/mux" ) // Types // Players type Player struct { ID int `json:"id"` Name string `json:"name"` Picture string `json:"picture"` Role string `json:position` ...
package main import ( "fmt" "io" "os" "path/filepath" "strings" "github.com/Luzifer/rconfig" "github.com/bogem/id3v2" log "github.com/sirupsen/logrus" ) var ( cfg struct { LogLevel string `flag:"log-level" default:"info" description:"Set log level (debug, info, warning, error)"` Output str...
package main import ( "io" "os" "path/filepath" "strings" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/openshift/installer/pkg/version" ) type fileHook struct { file io.Writer formatter logrus.Formatter level logrus.Level truncateAtNewLine bool } func newFileHook(file io.Wr...
package cfmysql_test import ( "code.cloudfoundry.org/cli/cf/errors" "code.cloudfoundry.org/cli/plugin" "code.cloudfoundry.org/cli/plugin/models" "code.cloudfoundry.org/cli/plugin/pluginfakes" . "github.com/andreasf/cf-mysql-plugin/cfmysql" "github.com/andreasf/cf-mysql-plugin/cfmysql/cfmysqlfakes" "github.com/a...
package main import "fmt" // Anonymous function - is a type of function without any specific name to it var ( area = func(l, b int) int { return l * b } ) // User defined function type Susheel func(int) int func sum(x, y int) int { return x + y } // Higher order function // Function as an argument and retur...
package file import ( "bufio" "log" "os" "strconv" "strings" "errors" "github.com/ryanchew3/flexera-coding-challenge/internal/model" ) // ReadFile reads in the input file and groups user machines by userids func ReadFile(s string) (map[int64][]*model.Computer, error) { out := make(map[int64][]*model.Computer...
package main import ( "context" "fmt" "time" ) type otherContext struct { context.Context } func work(ctx context.Context, name string) { for { select { case <-ctx.Done(): fmt.Printf("%s get msg to cancel\n", name) return default: fmt.Printf("%s is running \n", name) time.Sleep(1 * time.Second...
package main import ( "fmt" "sync" "time" ) var mutex sync.Mutex func main() { map1 :=make(map[int] string) for i:=1;i<=10;i++{ go func(i int) { mutex.Lock() map1[i] =fmt.Sprint("数据",i) mutex.Unlock() }(i) } time.Sleep(2*time.Second) fmt.Println(map1) }
package decrypt import ( "bytes" "crypto/aes" "crypto/cipher" "fmt" "math/big" "github.com/allvisss/ECC_service/common/model" "github.com/allvisss/ECC_service/common/response" "github.com/fomichev/secp256k1" ) func DecryptService(ciphertext string, priv model.PrivateKey) (int, interface{}) { plaintext, err...
package clouddatastore import ( "context" "fmt" "github.com/qnib/metahub/pkg/storage" "cloud.google.com/go/datastore" ) // NewService returns a new storage.Service for GCP Cloud Datastore func NewService() storage.Service { return &service{} } type service struct { } func (s *service) newClient(ctx context.C...
package eventmanager import ( "context" cluster "github.com/bsm/sarama-cluster" "github.com/lovoo/goka" "github.com/lovoo/goka/kafka" "log" "microservices_template_golang/payment_storage/src/models" "os" "os/signal" "syscall" ) type EventProcessor struct { processor *goka.Processor } func (e *EventProcesso...
package manager /* import ( "fmt" "net/http" "github.com/gin-gonic/gin" "github.com/golang/glog" // "sub_account_service/finance/config" // "sub_account_service/finance/db" "sub_account_service/finance/lib" _ "sub_account_service/finance/memory" //引用memory包初始化函数 // "sub_account_service/finance/models" // "...
package combinators import ( "log" "strings" "testing" "github.com/stretchr/testify/assert" ) func init() { log.SetFlags(log.LstdFlags | log.Lshortfile) } func TestExpectRune(t *testing.T) { var r interface{} var err error parser := Expect('a') r, _ = ParseRuneReader(parser, strings.NewReader("a")) asse...
package site import ( "net/http" "net/http/httputil" "net/url" "os" "time" "github.com/Sirupsen/logrus" "github.com/bryanl/dolb/server" "github.com/gorilla/mux" "github.com/markbates/goth" "github.com/markbates/goth/gothic" "github.com/markbates/goth/providers/digitalocean" ) type Site struct { Mux htt...
package controllers import ( "fmt" "log" "net/http" "strconv" "muto/context" "muto/models" "muto/views" "github.com/gorilla/mux" ) const ( IndexGalleries = "index_galleries" ShowGallery = "show_gallery" EditGallery = "edit_gallery" // Bit Shift maxMultipartMem = 1 << 20 // 1 megabyte ) func New...
package todoist import ( "context" "errors" "fmt" "github.com/fatih/color" "net/http" "net/url" "strings" ) type Project struct { Entity Name string `json:"name"` Color int `json:"color"` Indent int `json:"indent"` ItemOrder int `json:"item_order"` Collapsed int `js...
package redis import ( "context" "encoding/json" "errors" "github.com/go-redis/redis/v8" "reflect" "time" ) func (c *client) GetPipelines(targets []interface{}) error { ctx := context.TODO() uids, err := c.rc.LRange(ctx, PIPELINES_KEY, 0, -1).Result() if err != nil { return wrapErr(err) } pipeRes := []*r...
//Algorithm for Sieve of Eratosthenes package main import ( "fmt" ) //This program only works for primes smaller or equal to 10e7 func Sieve(upperBound int64) []int64 { _SieveSize := upperBound + 10 //Creates set to mark wich numbers are primes and wich are not //true: not primes, false: primes //this to favor d...
package handler import ( "bytes" "html/template" "io/ioutil" "net/http" "net/http/httptest" "net/url" "testing" "github.com/GoGroup/Movie-and-events/model" "github.com/GoGroup/Movie-and-events/rtoken" "github.com/GoGroup/Movie-and-events/event/repository" "github.com/GoGroup/Movie-and-events/event/service...
package domain import "encoding/gob" // 登录用户 // 由 signon, profile, account 三张表组成 type Account struct { UserName string Password string Email string FirstName string LastName string Status string Address1 string Address2 ...
package codeGeneration import ( . "ast" . "backend/filewriter" "fmt" "strconv" ) // CodeGenerator: Using a constructor that provides an address of the place holder // for the list of assembly instructions for the program (And the AST with the symbol table), // the code generator can use the "GenerateCode" functio...
package sync import "sync" var waitGroupPool = sync.Pool{ New: func() interface{} { return new(sync.WaitGroup) }, } func AcquireWaitGroup() *sync.WaitGroup { return waitGroupPool.Get().(*sync.WaitGroup) // nolint:forcetypeassert } func ReleaseWaitGroup(wg *sync.WaitGroup) { waitGroupPool.Put(wg) }
// Copyright Jetstack Ltd. See LICENSE for details. package cmd import ( "github.com/spf13/cobra" ) // initCmd represents the init command var renewtokenCmd = &cobra.Command{ Use: "renew-token", Short: "Renew token on vault server.", Run: func(cmd *cobra.Command, args []string) { i, err := newInstanceToken(c...
package gadb import ( "bytes" "encoding/binary" "fmt" "io" "os" "strings" "time" "github.com/pkg/errors" "github.com/rs/zerolog/log" "github.com/httprunner/httprunner/v4/hrp/internal/builtin" "github.com/httprunner/httprunner/v4/hrp/internal/code" ) type DeviceFileInfo struct { Name string Mode...
package gcp import ( "context" "github.com/pkg/errors" storage "google.golang.org/api/storage/v1" ) func (o *ClusterUninstaller) listBucketObjects(ctx context.Context, bucket cloudResource) ([]cloudResource, error) { o.Logger.Debugf("Listing objects for storage bucket %s", bucket.name) ctx, cancel := context.Wi...
package crypto import ( amino "github.com/bcbchain/bclib/tendermint/go-amino" ) var cdc = amino.NewCodec() func init() { // NOTE: It's important that there be no conflicts here, // as that would change the canonical representations, // and therefore change the address. // TODO: Add feature to go-amino to ensure...
package cmd import ( "github.com/Files-com/files-cli/lib" "github.com/spf13/cobra" files_sdk "github.com/Files-com/files-sdk-go" "fmt" "os" group_user "github.com/Files-com/files-sdk-go/groupuser" ) var ( GroupUsers = &cobra.Command{ Use: "group-users [command]", Args: cobra.ExactArgs(1), Run: func(...
// Copyright 2021 The Prometheus 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...
package main //思路:二叉树递归,同时用快慢指针寻找中点 func sortedListToBST(head *ListNode) *TreeNode { if head == nil { return nil } return genBST(head, nil) } func genBST(head *ListNode, tail *ListNode) *TreeNode { if head == tail { //递归结束 return nil } slow := head fast := head for fast != tail && fast.Next != tail { sl...
package lua import ( "time" lua "github.com/yuin/gopher-lua" ) func preloadTime(state *lua.LState) int { mod := state.NewTable() state.SetFuncs(mod, map[string]lua.LGFunction{ "sleep": timeSleep, }) state.Push(mod) return 1 } func timeSleep(state *lua.LState) int { ms := state.CheckNumber(1) time.Sleep(t...
package rsync import ( "runtime" "strings" "sync" "sync/atomic" "time" "github.com/cpusoft/goutil/belogs" "github.com/cpusoft/goutil/conf" "github.com/cpusoft/goutil/httpclient" "github.com/cpusoft/goutil/jsonutil" "github.com/cpusoft/goutil/osutil" "github.com/cpusoft/goutil/randutil" "github.com/cpusoft...
package client import ( "bytes" "crypto/tls" "encoding/json" "errors" "fmt" "io" "io/ioutil" "net/http" "net/http/cookiejar" "time" "github.com/Huawei/eSDK_K8S_Plugin/src/utils/log" ) const ( VOLUME_NAME_NOT_EXIST int64 = 50150005 INITIATOR_NOT_EXIST int64 = 50155103 HOSTNAME_ALREADY_EXIST int64...
package post import ( "io/ioutil" "log" "net/http" "strings" "github.com/russross/blackfriday" ) // Post - Overall posts parsed by parts type Post struct { Id int Title string PublishedDate string Summary string Body string } // 1. markdown으로 post 작성후 submit 누르면 (파일 업로드?)...
// Copyright 2021 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
package main import ( "fmt" "log" "gopkg.in/kataras/iris.v6" "gopkg.in/kataras/iris.v6/adaptors/httprouter" // "github.com/kataras/iris" // "net/http" "encoding/json" _"github.com/go-sql-driver/mysql" "database/sql" "reflect" "strconv" "strings" // "net/http" ) // User bind struct // type User struct {...
package utils import ( "encoding/json" "io/ioutil" "zinx/src/zinx/ziface" ) /* 存储一切有关 zinx 框架的全局参数,共其他模块使用 一些参数可以通过 zinx.json 由用户配置 */ type GLobalObj struct { /* server */ TcpServer ziface.IServer // 当前zinx 全局的 server 对象 StrHostIP string // 当前服务器主机监听的IP ITcpPort int // 当前服务器主机监听的port ...
/* * @lc app=leetcode id=54 lang=golang * * [54] Spiral Matrix * * https://leetcode.com/problems/spiral-matrix/description/ * * algorithms * Medium (30.67%) * Likes: 1147 * Dislikes: 420 * Total Accepted: 242.1K * Total Submissions: 788.3K * Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]' * * Given ...
package pool import ( "github.com/yuin/gopher-lua" "layeh.com/gopher-luar" "reflect" "sync" ) type module struct { state *lua.LState table *lua.LTable method sync.Map } func (m *module) To(val interface{}, name ...string) bool { if len(name) > 0 { return __toValue(m.state.GetField(m.table, name[0]), val)...
package filters import ( "math" "math/rand" "sync" "github.com/stripe/unilog/clevels" "github.com/stripe/unilog/json" ) var startSystemAusterityLevel sync.Once // AusterityFilter applies system-wide austerity levels to a log // line. If austerity levels indicate a line should be shedded, the // like's contents...
package main import ( "os" "github.com/gekalogiros/sniffio/cmd" ) func main() { root:=cmd.NewSniffioCommand() root.AddCommand( cmd.NewVersionCommand(os.Stdout), cmd.NewArpCommand(os.Stdout), cmd.NewIfacesCommand(os.Stdout), cmd.NewTCPCommand(os.Stdout), ) root.Execute() }
package openshift_osinserver import ( "k8s.io/client-go/rest" configapi "github.com/openshift/origin/pkg/cmd/server/apis/config" "github.com/openshift/origin/pkg/oauthserver/oauthserver" genericapiserver "k8s.io/apiserver/pkg/server" // for metrics _ "k8s.io/kubernetes/pkg/client/metrics/prometheus" ) func Ru...
package endpoints import ( "encoding/json" "fmt" "net/http" "strconv" shd "github.com/ebikode/eLearning-core/domain/schedule" usr "github.com/ebikode/eLearning-core/domain/user" md "github.com/ebikode/eLearning-core/model" tr "github.com/ebikode/eLearning-core/translation" ut "github.com/ebikode/eLearning-co...
package types import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) var _ sdk.Msg = &MsgCreateAchievement{} func NewMsgCreateAchievement(creator string, achievementID string, owner string) *MsgCreateAchievement { return &MsgCreateAchievement{ Creator: cr...
package testkit import ( "reflect" "strings" "testing" ) // AssertEqual asserts that two values are equal func AssertEqual(t *testing.T, expected interface{}, got interface{}) { if !reflect.DeepEqual(expected, got) { t.Errorf("\n\n---- Expected:\n%v\n++++ Got:\n%v\n\n", expected, got) } } // AssertIsNil asser...
package gojson import ( "bytes" "reflect" "unsafe" "fmt" "strconv" ) const ( startArray byte = '[' stopArray byte = ']' startObject byte = '{' stopObject byte = '}' startString byte = '"' escape byte = '\\' ) // Unarshal parses input bytes and returns new json func Unmarshal(value []byte) *GoJSO...
// Tideland Go Application Support - Logger // // Copyright (C) 2012-2014 Frank Mueller / Tideland / Oldenburg / Germany // // All rights reserved. Use of this source code is governed // by the new BSD license. // +build windows plan9 package logger import ( "log" ) // Dummy SysLogger for platforms without syslog ...
package w3po import ( "../../util" "../report" "github.com/xojoc/bitset" ) //intersect returns true if the two sets have at least one element in common func intersect(a, b map[uint32]struct{}) bool { for k := range a { if _, ok := b[k]; ok { return true } } return false } type ListenerDataAccess struct{...
package piscine func DivMod(a int, b int, div *int, mod *int) { var c int var d int c = a / b d = a % b *div = c *mod = d }
package ecr import ( "encoding/base64" "log" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ecr" ) func GetToken() (string, string, error) { sess, err := session.NewSession(&aws.Config{}) if err != nil { return "", "", err } svc := ecr...
package timerWithLock import ( "testing" "time" "strconv" . "github.com/smartystreets/goconvey/convey" ) func TestTimerManager(t *testing.T) { manager := NewManager() Convey("TestTimerManager", t, func() { Convey("AddTimer", func() { // 正常的添加一个定时器 key := "AddTimer" So(manager.HasTimer(key), ShouldEqu...
package def // Request : 场景执行部分返回,通常需要更换场景 type Request struct { Continue bool NextScene string Terminate bool ResetData bool } // DefaultRequest : 返回默认 Request,执行执行excute var DefaultRequest = Request{ Continue: true, NextScene: "", Terminate: false, ResetData: true, }
package shell import ( "fmt" "os" "os/exec" "strings" "github.com/gruntwork-io/go-commons/errors" ) // Run the specified shell command with the specified arguments. Connect the command's stdin, stdout, and stderr to // the currently running app. func RunShellCommand(options *ShellOptions, command string, args ....
package samjung import ( "fmt" "os" "encoding/binary" "strconv" ) type column struct { pk uint64 name string position string } func (r *Samjung) selectRow() error { fmt.Print("pk: ") pkStr, err := r.readLine() if err != nil { return err } pkLen := len(pkStr) - 1 pk, err := strconv.ParseUint(string(pk...
package controllers import ( "context" "encoding/json" "github.com/gorilla/mux" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "log" "net/http" "reactgomongo/models" ) func AddTodo(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Methods", "POST"...
package gocyclo import "fmt" func function1(i int) { if i < 0 { fmt.Println("negative") } else if i < 10 { fmt.Println("between 0 and 9 inclusive") } else if i < 20 { fmt.Println("between 10 and 19 inclusive") } else { fmt.Println("20 or more") } } func function2(i int) { switch { case i < 0: fmt.Pr...
package db import ( "database/sql" "fmt" "log" "sync" _ "github.com/mattn/go-sqlite3" ) type BotDB struct { db *sql.DB locker *sync.Mutex } // Open DB connection func (db *BotDB) Open(dbPath string) { var err error db.db, err = sql.Open("sqlite3", dbPath) if err != nil { log.Fatal(err) } db.locke...
package gobase import ( "errors" "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" ) var base Database type Database interface { Insert(data []interface{}) error InsertBulk(data [][]interface{}) error Find(key string) error Update([]interface{}) error UpdateBulk([]interface{}) err...
// Package pprofutil contains utilities for pprof HTTP handlers. package pprofutil import ( "net/http" "net/http/pprof" "net/url" ) // BasePath is the default base path used by [RoutePprof]. // // TODO(a.garipov): Consider adding the ability to configure the base path. const BasePath = "/debug/pprof/" // Router i...
package registration import ( "crypto/rand" "crypto/rsa" "encoding/json" "fmt" "github.com/catmullet/Raithe/app/types" "github.com/catmullet/Raithe/app/utils" "github.com/labstack/echo" ) var ( registeredAgents []types.SecurityToken ) func getAgents() types.Agents { return utils.GetAgentsFromList() } // Re...
package handlers import ( "encoding/json" "net/http" "github.com/gorilla/mux" log "github.com/sirupsen/logrus" ) // GetValue is the HTTP handler to process incoming KV Get requests // It gets the value from the in memory KV store func GetValue(w http.ResponseWriter, r *http.Request) { // Obtain the key from UR...
package main import ( "fmt" "github.com/bb-orz/gt/cmd" "github.com/bb-orz/gt/utils" "github.com/urfave/cli/v2" "os" "time" ) func main() { app := cli.NewApp() app.Name = "gt" app.Version = "2.1" app.Compiled = time.Now() app.Usage = "A generation tool of go app scaffold which base on bb-orz/goinfras." app...
package main import "fmt" import "jikeshijian/L5/lib" var block = "package" func main() { block := "function" { block := "inner" fmt.Printf("The block is %s.\n", block) } fmt.Printf("The block is %s.\n", block) lib.Print(); }
/* * Get the scheduled activities associated with a group. */ package main import ( "encoding/hex" "flag" "fmt" "os" "path" "strings" "time" "github.com/dustin/go-humanize" "github.com/grrtrr/clcv2/clcv2cli" "github.com/grrtrr/exit" "github.com/kr/pretty" "github.com/olekukonko/tablewriter" ) func main...
////////////////////////////////////////////////////////////////////////// // // Copyright 2019 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/...
package server import ( "encoding/json" "github.com/gin-gonic/gin" "github.com/henglory/Demo_Golang_v0.0.1/handler" "github.com/henglory/Demo_Golang_v0.0.1/service" "github.com/henglory/Demo_Golang_v0.0.1/spec" ) func demo2(s service.Service, c *gin.Context) { var req spec.Demo2Req b, err := c.GetRawData() i...
package jarviscrypto import ( "fmt" "math/big" "github.com/fomichev/secp256k1" ) // var secp256k1A *big.Int // func init() { // secp256k1A, _ = new(big.Int).SetString("0000000000000000000000000000000000000000000000000000000000000000", 16) // } // /*** Modular Arithmetic ***/ // /* NOTE: Returning a new z each...
package learnfunc func modifyArray(a[3]string)[3]string{ a[1] = "x" return a } func modifySlice(a[]string)[]string{ a[1] = "i" return a } func modifyComplexArray(a[3][]string)[3][]string{ a[1][1] = "s" a[2] = []string{"o","p","q"} return a }
package cmds import ( "fmt" "github.com/pachyderm/pachyderm/src/client" "github.com/pachyderm/pachyderm/src/client/enterprise" "github.com/pachyderm/pachyderm/src/server/pkg/cmdutil" "github.com/spf13/cobra" ) // ActivateCmd returns a cobra.Command to activate the enterprise features of // Pachyderm within a P...
package main import ( "github.com/gin-gonic/gin" "log" "net/http" "time" ) func main() { //router := gin.Default() //http.ListenAndServe(":8080", router) router := gin.Default() gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) { log.Printf("endpoint %v %v %v %v\n...
package aoc2016 import ( "strings" aoc "github.com/janreggie/aoc/internal" ) // repertoire represents an array of dictionaries containing bytes // and their frequency in a given column. type repertoire []map[byte]uint // newRepertoire creates a repertoire. // Note that repertoire is a dynamic structure // so leng...
package middlewares import ( "github.com/gin-gonic/gin" metadata2 "github.com/owenliang/myf-go/app/middlewares/metadata" ) func MetadataMiddleware() gin.HandlerFunc { return func(context *gin.Context) { metadata := &metadata2.MetaData{ Gin: context, } context.Set("metadata", metadata) } }
package logic import "time" type SecRequest struct { ProductId uint `form:"product_id" json:"product_id" binding:"required"` UserId string `form:"user_id" json:"user_id" binding:"required"` // 用户ID AccessTime time.Time `json:"access_time"` // 用户访问接口时间...
package main /** https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/ 摩尔投票法 */ func majorityElement(nums []int) int { ans := 0 count := 0 for i :=0; i < len(nums); i ++ { if count == 0 { ans = nums[i] } if ans == nums[i] { count ++ } else { count -- } }...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/11/16 8:58 下午 # @File : lt_148_排序链表.go # @Description : # @Attention : */ package offer // 关键: // 归并排序法 1. 先找到中点,然后找到左边和右边 2 最后再进行归并 func sortList(head *ListNode) *ListNode { return sortListMerge1(head) } func sortListMerge1(head *ListNode) *ListNode { if ...
package main import ( "flag" "fmt" "log" "os/exec" "github.com/nickvanw/ircx" "github.com/sorcix/irc" ) var ( Version string user = flag.String("user", "", "Twitch username") pass = flag.String("pass", "", "Twitch OAuth token") rate = flag.String("rate", "300", "TTS speech rate") server = "irc.twitch.tv...
package main type ConfigTypes struct { EmailSettings struct { Email string `yaml:"email"` Password string `yaml:"password"` Name string `yaml:"name"` ToEmail string `yaml:"to_email"` } `yaml:"email_settings"` MessageSettings struct { Password string `yaml:"passcode"` } `yaml:"message_settings"` }...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-11-09 09:50 # @File : lt_457_Circular_Array_Loop.go # @Description : # @Attention : */ package two_points import "testing" func Test_circularArrayLoop(t *testing.T) { nums:=[]int{-1,2,1,2} circularArrayLoop(nums) } func Test_setZero(t *testing.T) { type ...
// 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 ...
// 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 main import ( "flag" "os" "github.com/gin-gonic/gin" "github.com/kkurahar/go-gin-lightweight/app" "github.com/kkurahar/go-gin-lightweight/helpers/config" ) func showUsage() { } func main() { env := flag.String("env", "development", "applicaiton runtime environment") flag.Parse() config.Loads("./con...
// Copyright (c) 2020 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package starlark import ( "fmt" "github.com/pkg/errors" "github.com/vmware-tanzu/crash-diagnostics/util" "go.starlark.net/starlark" "go.starlark.net/starlarkstruct" ) // KubeConfigFn is built-in starlark function tha...
package main import "github.com/gorilla/mux" import "net/http" import "io/ioutil" import "encoding/json" import "strconv" type Request struct { Url string `json:"url"` } type Response struct { Key string `json:"key"` } var shortUrls = make([]string, 0) func getKey() int { return len(shortUrls) } func AddUrl...
package main import "fmt" // 1244. 力扣排行榜 // 新一轮的「力扣杯」编程大赛即将启动,为了动态显示参赛者的得分数据,需要设计一个排行榜 Leaderboard。 // 请你帮忙来设计这个 Leaderboard 类,使得它有如下 3 个函数: // addScore(playerId, score): // 假如参赛者已经在排行榜上,就给他的当前得分增加 score 点分值并更新排行。 // 假如该参赛者不在排行榜上,就把他添加到榜单上,并且将分数设置为 score。 // top(K):返回前 K 名参赛者的 得分总和。 // res...
package g2util import ( "runtime" "runtime/debug" "sync" "sync/atomic" "time" "github.com/andeya/goutil" "github.com/panjf2000/ants/v2" ) var goPoolSize = runtime.NumCPU() * 1000 // GoPool ...goroutine pool type GoPool struct { LevelLogger LevelLogger `inject:""` Grace *Graceful `inject:""` wait ...
//go:generate go run github.com/UnnoTed/fileb0x b0x.json package main import ( "flag" "net/http" "github.com/DigitalOnUs/douk/api" "github.com/DigitalOnUs/douk/static" "goji.io" "goji.io/pat" ) // APIs var ( address string ) func init() { flag.StringVar(&address, "listen", "localhost:7001", "listen address"...
package bus import "github.com/scottshotgg/proximity/pkg/listener" type ( // Bus ... Bus interface { Insert(msg *listener.Msg) error Remove() (*listener.Msg, error) Close() error } )
package caaa import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00200101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.002.001.01 Document"` Message *AcceptorAuthorisationResponseV01 `xml:"AccptrAuthstnRspn"` } func (d *D...
package main import ( "testing" "github.com/almighty/almighty-core/app/test" ) func TestAuthorizeLoginOK(t *testing.T) { controller := LoginController{} resp := test.AuthorizeLoginOK(t, &controller) if resp.Token == "" { t.Error("Token not generated") } } func TestShowVersionOK(t *testing.T) { controller ...
package main import ( "errors" "fmt" "github.com/J0-nas/drawGraph" "log" "math" "math/rand" "os" "sort" "strconv" "sync" "time" ) type Point struct { X, Y float64 } type ByX []Point func (a ByX) Len() int { return len(a) } func (a ByX) Swap(i, j int) { pTemp := a[i] a[i] = a[j] a[j] = pTemp // , a...
package dump_test import ( "os" "testing" "github.com/Kretech/xgo/dump" "github.com/Kretech/xgo/encoding" ) func ExampleDump() { // just for testing dump.ShowFileLine1 = false dump.DefaultWriter = os.Stdout a := 1 b := `2` c := map[string]interface{}{b: a} dump.Dump(a, b, c) // Output: // a => 1 // b...
package musixmatch import ( "encoding/json" "errors" "fmt" "net/http" "time" ) const ( //BaseURL is the API URL BaseURL = "http://api.musixmatch.com/ws/1.1" defaultHTTPTimeout = 30 * time.Second ) // Key is the MusixMatch API key var Key string var httpClient = &http.Client{Timeout: defaultHTTPTim...
package main import ( "bufio" "os" ) func main() { file, _ := os.Open("input/day11.txt") defer file.Close() scanner := bufio.NewScanner(file) rows1 := make([][]byte, 0) for scanner.Scan() { bytes := make([]byte, 100) copy(bytes, scanner.Bytes()) rows1 = append(rows1, bytes) } rows2 := duplicate(rows1)...
package model type XmlNamespace struct { // Name of the XML Namespace reference Prefix string `json:"prefix,omitempty"` // Source of the XML Namespace reference Uri string `json:"uri,omitempty"` }
package handler import ( "github.com/golang/mock/gomock" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" "go.mongodb.org/mongo-driver/bson/primitive" "mytodoapp/model" "mytodoapp/repository" "net/http" "net/http/httptest" "strings" "testing" ) func Test_ShouldReturnEmptyTodoList(t *testin...
package main import ( "log" _ "github.com/snapiz/go-vue-starter/services/main/src/db" "github.com/spf13/cobra" ) var root = &cobra.Command{ Use: "gvs-main-cli", Short: "Go vue start main CLI tool", } func main() { if err := root.Execute(); err != nil { log.Fatal(err) } }