text
stringlengths
11
4.05M
package app import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "os" "secure/database" ) type hFunc func(e *Env, w http.ResponseWriter, r *http.Request, c *context) httpStatus var protectedRoutes = []struct { key string H hFunc }{ {"/", proxy}, } var openRoutes = []struct { key string H hF...
package valid import ( "encoding/json" "fmt" "github.com/gin-gonic/gin" "io/ioutil" "log" "moriaty.com/cia/cia-common/base/constant" "moriaty.com/cia/cia-common/base/wrap" "net/http" "regexp" ) /** * @author 16计算机 Moriaty * @version 1.0 * @copyright :Moriaty 版权所有 © 2020 * @date 2020/4/6 17:28 * @Descrip...
package models // import ( // "github.com/messagedb/messagedb/meta/schema" // "github.com/messagedb/messagedb/meta/utils" // // "gopkg.in/mgo.v2/bson" // ) // // // variables // var Organization *OrganizationModel // // // OrganizationModel represents an organization collection // type OrganizationModel struct { //...
package uimode import ( "bytes" "fmt" "strings" "time" "github.com/gdamore/tcell" "github.com/sergi/go-diff/diffmatchpatch" ) func (ui *UI) handleEvents() { ui.app.SetInputCapture(ui.handleApp) ui.history.SetInputCapture(ui.handleHistory) ui.sqlStmt.SetDoneFunc(ui.sqlStmtDone) ui.sqlStmt.SetInputCapture(ui...
package leetcode /*Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on). 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/exchange-lcci 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/ func exchangeBits(num int...
/* It is JJ's birthday and you decide to gift him a string S (consisting of English alphabet only) of length N. But you also know that JJ does not like palindromes so you decide that none of the substrings of S of length ≥2 should be a palindrome. Can you find any suitable string which can be gifted to JJ? Recall th...
package resolvers_test import ( "context" "testing" "github.com/syncromatics/kafmesh/internal/graph/model" "github.com/syncromatics/kafmesh/internal/graph/resolvers" gomock "github.com/golang/mock/gomock" "github.com/pkg/errors" "gotest.tools/assert" ) func Test_ProcessorJoin_Processor(t *testing.T) { ctrl ...
package cni import ( "encoding/json" "fmt" "github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types/current" "github.com/containernetworking/cni/pkg/version" bv "github.com/containernetworking/plugins/pkg/utils/buildversion" "git...
/* * @lc app=leetcode.cn id=836 lang=golang * * [836] 矩形重叠 */ package main // @lc code=start func isRectangleOverlap(rec1 []int, rec2 []int) bool { return !(rec1[2] <= rec2[0] || rec2[2] <= rec1[0] || rec1[3] <= rec2[1] || rec2[3] <= rec1[1]) } // func main() { // fmt.Println(isRectangleOverlap([]int{0, 0, 2, 2}...
package gin_unit_test import ( "encoding/json" "io/ioutil" "log" "net/http" "net/http/httptest" "github.com/Valiben/gin_unit_test/utils" ) var ( // router router http.Handler // customed request headers for token authorization and so on myHeaders = make(map[string]string, 0) logging *log.Logger ) // set...
package websocket import ( "fmt" "encoding/json" "log" wp "github.com/kwhk/sync/api/utils/workerPool" "github.com/kwhk/sync/api/config" models "github.com/kwhk/sync/api/models/redis" repo "github.com/kwhk/sync/api/repository/redis" ) const PubSubGeneralChannel = "general" type WsServer struct { users []mod...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/11/17 9:29 上午 # @File : lt_227_基本计算器.go # @Description : # @Attention : */ package offer // 思路: // 1. 栈进行对结果进行保存,对于 * 或者 / 则直接取出进行计算 func calculate(s string) int { retStack := []int{} num := 0 preSign := '+' for i, v := range s { isDigital := v >= '0' &...
package apiService import ( "net/http" "net/url" "reflect" "regexp" "strings" "github.com/ewhal/nyaa/model" "github.com/ewhal/nyaa/service" ) type torrentsQuery struct { Category int `json:"category"` SubCategory int `json:"sub_category"` Status int `json:"status"` Uploader int `json:"uploader"...
package probl1 import "testing" func TestMaxlength(t *testing.T) { var tests = [] struct { a []int want int }{{[]int{1, 3, 4, 5, 6, 9}, 2}, {[]int{1, 2, 3, 4, 5}, 4}, {[]int{998, 999, 1000}, 2}, } for _, c := range tests{ got := Maxlength(c.a) if got != c.want { t.Errorf( "Got %d, want %d",got,...
/* Create a function that accepts a list of dates (unsorted with possible duplicates) and returns the days of the week in one of the following formats: A format similar to MTWTFSS or SMTWTFS (i.e. beginning with Monday or Sunday), with non-days replaced by an underscore _, illustrated below. WEEKDAY if all th...
package util import ( "fmt" "github.com/magiconair/properties" "os" "path/filepath" ) type config struct { Context string `properties:"context,default=/"` DBDriver string `properties:"dbDriver,default=mysql"` DBUser string `properties:"dbUser,default=golfschool"` DBPass string `properties:"dbPass,default...
package main //func generateParenthesis(n int) []string { // var res22 []string // if n == 0 { // return res22 // } // dfs(&res22, "", n, n) // return res22 //} // //func dfs(res22 *[]string, cur string, left, right int) { // if left == 0 && right == 0 { // *res22 = append(*res22, cur) // return // } // if left > r...
package command import ( "path/filepath" "os" "github.com/flosch/pongo2" "mix/core/storage" ) func (p *Handler) getTemplate(file string) (tpl *pongo2.Template, err error) { root, err := os.Getwd() if err != nil { return } path := filepath.Join(root, "/plugins/mysql/template/", file) content, err := stor...
package shield type Tokenizer interface { Tokenize(text string) (words map[string]int64) } type Set struct { Class string Text string } type Shield interface { Learn(class, text string) (err error) BulkLearn(sets []Set) (err error) Forget(class, text string) (err error) Classify(text string) (c string, err e...
package main import ( "context" "github.com/gtfierro/xboswave/ingester/types" influx "github.com/influxdata/influxdb/client/v2" "github.com/pkg/errors" logrus "github.com/sirupsen/logrus" "gopkg.in/btrdb.v4" "math/rand" "sync" "sync/atomic" "time" ) var errStreamNotExist = errors.New("Stream does not exist"...
package services import ( "encoding/json" "go.uber.org/zap" "github.com/pushaas/push-agent/push-agent/models" ) type ( SubscriptionService interface { HandlePublishTask(*string) } subscriptionService struct{ logger *zap.Logger pushStreamService PushStreamService } ) func (s *subscriptionService) Hand...
package types import ( "fmt" "regexp" "strings" sdk "github.com/irisnet/irishub/types" ) const ( // MsgRoute identifies transaction types MsgRoute = "asset" MsgTypeIssueToken = "issue_token" // constant used to indicate that some field should not be updated DoNotModify = "[do-not-modify]" ) var (...
package tree type BST struct { root *Node } func NewBST(data interface{}) *BST { return &BST{root: NewTreeNode(data)} } // 比较函数,这里假设二叉查找树中的值都可以转为 int 类型 // val 表示要比较的值,cur 表示当点节点的值 // 如果要比较的值大,返回 1,小返回 -1,相等返回 0 func (bst BST) compare(val, cur interface{}) int { v := val.(int) curV := cur.(int) if v > curV { ...
package util import ( "github.com/maprost/application/generator/genmodel" "github.com/maprost/application/generator/lang" ) func JoinStrings(valueA string, sep string, valueB string) string { if valueA == "" { return valueB } if valueB == "" { return valueA } return valueA + sep + valueB } func JoinExperi...
//author xinbing //time 2018/9/11 10:39 // package saas_config import ( "github.com/BurntSushi/toml" "github.com/sirupsen/logrus" ) type config struct { Port string LogPath string LogFileName string LogMaxAge int LogRotationTime int RedisAddr string RedisPwd string RedisDB int My...
package routes import ( "github.com/buaazp/fasthttprouter" "github.com/valyala/fasthttp" "github.com/thavel/goban/pkg/api" ac "github.com/thavel/goban/pkg/auth" "github.com/thavel/goban/routes/absence" "github.com/thavel/goban/routes/auth" "github.com/thavel/goban/routes/team" "github.com/thavel/goban/routes/...
package instance_test import ( . "github.com/cloudfoundry/bosh-micro-cli/deployer/instance" boshlog "github.com/cloudfoundry/bosh-agent/logger" fakesys "github.com/cloudfoundry/bosh-agent/system/fakes" fakebmagentclient "github.com/cloudfoundry/bosh-micro-cli/deployer/agentclient/fakes" fakebmas "github.com/clo...
package main import ( "bytes" "fmt" "strings" camelcase "github.com/segmentio/go-camelcase" "github.com/shutej/go2ts/model" ) func UpperCamelcase(s string) string { s = camelcase.Camelcase(s) return strings.ToUpper(s[0:1]) + s[1:len(s)] } func LowerCamelcase(s string) string { s = camelcase.Camelcase(s) re...
package apiserver import ( "fmt" forumHandler "github.com/Arkadiyche/bd_techpark/internal/pkg/forum/delivery" forumRep "github.com/Arkadiyche/bd_techpark/internal/pkg/forum/repository" forumUC "github.com/Arkadiyche/bd_techpark/internal/pkg/forum/usecase" postHandler "github.com/Arkadiyche/bd_techpark/internal/pk...
package main import ( "fmt" "time" "github.com/antlinker/go-dal" _ "github.com/antlinker/go-dal/mysql" ) type Student struct { ID int64 StuCode string StuName string Sex int Age int Birthday time.Time Memo string } func main() { dal.RegisterProvider(dal.MYSQL, `{ "datasource":...
// 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 watcher import ( "context" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/tools/cache" "github.com/IBM/ubiquity/utils/logs" ) /** * It is a simple watcher to watch a certain resource, if you want to watch more * that one resource or have complex process, use reso...
package utils import ( "bytes" b64 "encoding/base64" "encoding/gob" "reflect" ) func GetBytes(value interface{}) ([]byte, error) { if value != nil { t := reflect.TypeOf(value) v := reflect.New(t).Elem().Interface() gob.Register(v) } var buf bytes.Buffer if err := gob.NewEncoder(&buf).Encode(value); err ...
package tmp const HubHelperModelTmp = `package hub_helper{{$module := .ModuleName}} import ( "net/http" {{if gt (len .DBS) 0}} {{printf "\"%v/core/database\"" $module}}{{end}} {{range $i,$k := .Handlers}} {{printf "\"%v/handlers/%v_handler/%v_helper\"" $module $i $i }}{{end}} {{printf "\"%v/helper\"" $module}} ...
package main import ( "github.com/beego/beego/v2/client/orm/migration" ) // DO NOT MODIFY type User_20210629_110325 struct { migration.Migration } // DO NOT MODIFY func init() { m := &User_20210629_110325{} m.Created = "20210629_110325" migration.Register("User_20210629_110325", m) } // Run the migrations func...
package main import "fmt" var phrase string func init() { phrase = "Hola muno!" } /** * created: 2019/5/8 14:52 * By Will Fan */ func main() { fmt.Println(phrase) }
package dht import ( "context" "testing" "time" "github.com/libp2p/go-libp2p/core/network" "github.com/stretchr/testify/require" mocknet "github.com/libp2p/go-libp2p/p2p/net/mock" ) func TestInvalidRemotePeers(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() mn, err :...
package responses import ( "encoding/json" "net/http" ) func Return_json_response(w http.ResponseWriter, response_shape interface{}, status int) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) json.NewEncoder(w).Encode(response_shape) }
package task import ( "errors" "testing" "github.com/stretchr/testify/require" ) type taskFunc func() error func (t taskFunc) Do() error { return t() } func Test_taskGroup(t *testing.T) { val := 0 mockTask := func() error { val++ return nil } mockTaskErr := func() error { return errors.New("random e...
package main import "fmt" func main() { x := 10 func(y int) { fmt.Println("O valor passado foi", y) }(x) }
package main type hubClients struct { clients *containerClient register chan *client // Register requests from the clients unregister chan *client // Unregister requests from clients } func newHub() *hubClients { return &hubClients{ register: make(chan *client, 1), unregister: make(chan *client, 1), ...
package transfer import ( "os" "strconv" "jmcs/core/utils" ) type ServerTransfer struct { SendPackage receiveNum int //接收包的数量 Finished bool //判断传输是否完成 } const READ_BUFF = 1024 * 1024 var fileReceiveInfos = make(map[string]*ServerTransfer) //每个传输文件的信息 /* * 文件接收方法主程序 */ func (s *ServerTransfer) ReceiveFile...
package gosnowth import ( "bytes" "context" "encoding/base64" "encoding/json" "fmt" "net/http" "net/url" "regexp" "strconv" "strings" "time" "github.com/google/uuid" ) // FindTagsItem values represent results returned from IRONdb tag queries. type FindTagsItem struct { UUID string `json:"...
package limits const resourcePath = "limits" func getURL(c *gophercloud.ServiceClient) string { return c.ServiceURL(resourcePath) }
package container import ( "errors" "fmt" "os" "os/signal" "path/filepath" "runtime" "strconv" "sync" "syscall" "github.com/criyle/go-sandbox/pkg/unixsocket" ) type containerServer struct { socket *socket containerConfig defaultEnv []string done chan struct{} err error doneOnce sync.Once ...
/* 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 示例 1: 输入: nums = [1,1,1,2,2,3], k = 2 输出: [1,2] 示例 2: 输入: nums = [1], k = 1 输出: [1] 说明: 你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。 */ func topKFrequent(nums []int, k int) []int { //手撸的mini堆,效率很差,做完才想起来优先队列是现成的,省的自己实现 m:=make(map[int]int) ...
package legolegends import ( "fmt" ) type CurrentGameInfo struct { BannedChampions []CurrentGameBannedChampion `json:"bannedChampion"` GameId int64 `json:"gameId"` GameLength int64 `json:"gameLength"` GameMode string ...
package mails import ( "github.com/Murilovisque/lets-try-tech/home-page-back/internal/platform" ) var config mailConfig func loadConfig() error { const configPath = "/etc/home-page-back/mail.json" config = mailConfig{} return platform.LoadConfigFromJSONFile(configPath, &config) } type mailConfig struct { SmtpS...
package upload import ( "encoding/json" "fmt" "mime/multipart" "nighthawk/rabbitmq" api "nighthawkapi/api/core" "path/filepath" "time" ) type Job struct { UID string `json:"uid"` TS string `json:"timestamp"` UserID string `json:"user_id"` CaseID string `json:"case_id"...
/* The proceeding file was copied from derui's go-threes program. All credit goes to derui for creating this. */ package libthrees //package main? import ( "fmt" ) const ( BOARD_SIZE = 4 ) type Direction int const ( UP Direction = iota DOWN Direction = iota LEFT Direction = iota RIGHT Direction = iota ) func...
// Copyright 2020 MongoDB 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...
package mut import ( "context" "time" ) type funcResult struct { value interface{} err error } type Future struct { result chan *funcResult } func NewFuture(f func() (interface{}, error)) *Future { future := &Future{ result: make(chan *funcResult), } go func() { defer close(future.result) value, err...
package main import ( "sort" "fmt" "ms/sun/shared/golib/sorter" "math/rand" ) func main() { arr := []sorter.IntWeight{ sorter.IntWeight{1, 8}, sorter.IntWeight{2, 11}, sorter.IntWeight{19, 42}, sorter.IntWeight{18, 22}, sorter.IntWeight{14, 2}, sorte...
package base import ( "crypto/tls" "fmt" log "github.com/Sirupsen/logrus" "github.com/codegangsta/cli" "kubewebhook/config" "kubewebhook/utils/webhook" "net/http" "os" "os/signal" ) func Start(c *cli.Context) { var ( err error options *config.Options ) options, err = config.ParseConf(c) if nil !=...
package net import ( "context" "github.com/drand/drand/protobuf/drand" ) var _ Service = (*EmptyServer)(nil) // EmptyServer is an PublicServer + ProtocolServer that does nothing type EmptyServer struct{} // PublicRand ... func (s *EmptyServer) PublicRand(context.Context, *drand.PublicRandRequest) (*drand.PublicR...
package echo import ( "github.com/fxnn/deadbox/request" ) const interfaceVersion = "1.0" const RequestProcessorId = "request-processor:github.com/fxnn/deadbox:echo:" + interfaceVersion type requestProcessor struct{} func New() request.Processor { return &requestProcessor{} } // Id returns the string by which thi...
package main import ( "fmt" "strings" shared "github.com/corymurphy/adventofcode/shared" ) type Assignment struct { Low int High int } type AssignmentPair struct { AssignmentA Assignment AssignmentB Assignment } func NewAssignment(input string) *Assignment { assignment := strings.Split(input, "-") return...
package dp_server import ( "github.com/kumahq/kuma/pkg/core/runtime" ) func SetupServer(rt runtime.Runtime) error { if err := rt.Add(rt.DpServer()); err != nil { return err } return nil }
package backend_service import ( "2021/yunsongcailu/yunsong_server/backend/backend_dao" "2021/yunsongcailu/yunsong_server/web/web_model" ) type BackendWebsiteServer interface { // 获取网站数据 GetWebsite() (website web_model.WebsiteModel,err error) // 更新网站头像图片 EditAvatar(id int64,avatarPath string) (err error) // 更新...
package commands import ( "testing" "github.com/JFrogDev/artifactory-cli-go/tests" ) func TestRecursiveDownload(t *testing.T) { flags := tests.GetFlags() flags.Recursive = true aqlResult := Download("repo-local", flags) expected := "items.find({\"repo\": \"repo-local\",\"$or\": [{\"$and\": [{\...
package main import ( "hello-go-mock/src/repository" "hello-go-mock/src/usecase" ) func main() { svc := usecase.ToDoService{ ToDoWriter: repository.NewToDoWriterStdout(), } svc.SaveTodo("task dayo") }
package pathfileops import ( "fmt" ) // DirectoryTreeInfo - structure used // to 'Find' files in a directory specified // by 'StartPath'. The file search will be // filtered by a 'FileSelectCriteria' object. // // 'FileSelectCriteria' is a FileSelectionCriteria type // which contains FileNamePatterns strings and //...
// // Copyright (c) 2019 LG Electronics Inc. // SPDX-License-Identifier: Apache-2.0 // package resources import ( "bytes" "encoding/json" "fmt" "math/rand" "sort" "time" "github.com/hyperledger/fabric/core/chaincode/shim" pb "github.com/hyperledger/fabric/protos/peer" ) // ==================================...
/* Copyright 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 to in writing, software dis...
package jsonio import ( "io" ) type JSONReadWriteCloser interface { JSONReader JSONWriter io.Closer }
package semt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01700207 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:semt.017.002.07 Document"` Message *SecuritiesTransactionPostingReport002V07 `xml:"SctiesTxPstngRpt"...
package db import ( "database/sql" "sync" "testing" "time" "github.com/golang/protobuf/ptypes" "github.com/textileio/go-textile/pb" "github.com/textileio/go-textile/repo" "github.com/textileio/go-textile/util" ) var blockStore repo.BlockStore func init() { setupBlockDB() } func setupBlockDB() { conn, _ :...
package main import( "github.com/golang/protobuf/proto" //gateway.pb.go 的路径 "./gateway" "fmt" "net" "encoding/binary" ) const ( PROTOCOL_HEADER_LENGTH = 32 CMD_HEARTBEAT_REQ = 0x00010001 // 心跳请求 CMD_HEARTBEAT_RSP = 0x00010002 // 心跳应答 CMD_SVR_REG_REQ = 0x00010003 // 服务注册请求 CMD_SVR_REG_RS...
/* * @lc app=leetcode.cn id=80 lang=golang * * [80] 删除排序数组中的重复项 II */ // @lc code=start package main import "fmt" func main() { var a []int var b int a = []int{1,1,1,2,2,3} fmt.Printf("%v\n", a) b = removeDuplicates(a) fmt.Printf("result is %d, %v\n", b, a) a = []int{0,0,1,1,1,1,2,3,3} fmt.Printf("%v\n...
package main import "fmt" func main() { name := "Bruce" var lastName string = "Bigirwenkya" const gender string = "male" fmt.Println("Hello, my name is", name, lastName) // arrays var arr [5]int // are a fixed size arr[4] = 500 // their values must match the specified value data type fmt.Println(arr) var t...
// +build disgordperf package gateway import ( "strconv" "strings" "github.com/andersfylling/disgord/internal/gateway/opcode" "github.com/andersfylling/disgord/internal/util" ) //UnmarshalJSON see interface json.Unmarshaler //TODO: benchmark json.RawMessage and this for both voice and event! //there haven't bee...
package tcc import ( "context" "github.com/dynamicgo/xerrors" "github.com/dynamicgo/gomesh" "google.golang.org/grpc/metadata" ) var txidkey = "gomesh_tcc_txid" // Session . type Session interface { Context() context.Context Commit() error Cancel() error } type sessionImpl struct { txid string tccSer...
package web import ( "accountBook/models/beans" "accountBook/models/beans/customer" "accountBook/models/beans/dbBeans" "github.com/kinwyb/go/err1" ) // 收支类型 type IReceiptTypeEndpoint interface { // @Title 收支类型列表 // @Description 收支类型列表 // @Param token header string true Token // @Param parentID query string f...
package main // https://leetcode.com/problems/flatten-nested-list-iterator /** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * type NestedInteger struct { * } * * // Return true if this NestedInteger holds a single integ...
// Copyright 2015 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 decider // NewDecider is factory to create new Decider. func NewDecider(decider Decider, options ...interface{}) (Decider, error) { return decider.NewDecider(&options) }
// 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 //License struct type License struct { BundleID string DueDate string }
package main import ( "context" "log" "os" "os/signal" "github.com/labiraus/gomud-user/pkg/greeting" ) //go:generate make generate func main() { log.Println("user starting") ctx, ctxDone := context.WithCancel(context.Background()) done := greeting.Start(ctx) c := make(chan os.Signal, 1) signal.Notify(c, o...
package models import ( "dappapi/global/orm" "dappapi/tools" "fmt" ) type Login struct { Username string `form:"username" json:"username" binding:"required"` Password string `form:"password" json:"password" binding:"required"` Code string `form:"code" json:"code" binding:"required"` } func (u *Login) GetUs...
func totalHammingDistance(nums []int) int { cnt := 0 for i := uint32(0); i < 32; i += 1{ zero, one := 0, 0 for _, number := range nums{ if (number >> i) & 1 == 0 { one += 1 } else { zero += 1 } } cnt += zero * on...
package _79_Word_Search func exist(board [][]byte, word string) bool { var ( m, n int // 行、列 record [][]bool ) m = len(board) if m == 0 { return false } n = len(board[0]) if n == 0 { return false } if len(word) > m*n || len(word) == 0 { return false } // 构建record record = initRecord(m, n) // 遍...
package backend import ( "github.com/square/beancounter/backend/electrum" "github.com/square/beancounter/deriver" . "github.com/square/beancounter/utils" "github.com/stretchr/testify/assert" "testing" ) func TestTransactionCache(t *testing.T) { // TODO: refactor ElectrumBackend to make it easier to test eb :=...
package main import ( piscine "./func" ) func main() { // fmt.Println(piscine.AppendRange(5, 10)) // fmt.Println(piscine.AppendRange(10, 5)) // fmt.Println(piscine.MakeRange(5, 10)) // fmt.Println(piscine.MakeRange(10, 5)) // test := []string{"Hello", "how", "are", "you?"} // fmt.Println(piscine.ConcatParams...
/* Copyright 2020 Humio https://humio.com 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, ...
package integrations import ( "evier/job" "time" ) type Integration interface { NotifyProcessStart(startTime time.Time) (e error) NotifyJobStart(job job.Job, startTime time.Time) (e error) NotifyJobSuccess(job job.Job, startTime time.Time, endTime time.Time) (e error) NotifyJobFailure(job job.Job, startTime ...
package main import "fmt" func main() { type data [2]int var d data = [2]int{1, 2} fmt.Println(d) a := make(chan int, 2) var b chan<- int = a b <- 2 }
// Copyright 2019, OpenTelemetry 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 ag...
package httputils import ( "encoding/json" "net/http" ) func DispatchNewHttpError(w http.ResponseWriter, message string, statusCode int) { responseContent, _ := json.Marshal(map[string]string{"message": message}) w.WriteHeader(statusCode) w.Write(responseContent) } func DispatchNewResponse(w http.ResponseWrite...
package problem0647 import "testing" func TestSolve(t *testing.T) { //t.Log(countSubstrings("abc")) //t.Log(countSubstrings("aaa")) t.Log(countSubstrings2("aaabbb")) }
package commands import ( "github.com/argoproj/pkg/stats" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) func NewInitCommand() *cobra.Command { var command = cobra.Command{ Use: "init", Short: "Load artifacts", Run: func(cmd *cobra.Command, args []string) { err := loadArtifacts() if err...
/* You have a function printNumber that can be called with an integer parameter and prints it to the console. For example, calling printNumber(7) prints 7 to the console. You are given an instance of the class ZeroEvenOdd that has three functions: zero, even, and odd. The same instance of ZeroEvenOdd will be passed t...
package random_test import ( "testing" . "web-layout/utils/rand" ) func TestInt(t *testing.T) { t.Log(Int()) t.Log(Int(2)) t.Log(Int(1, 2)) } func BenchmarkInt(b *testing.B) { for i := 0; i < b.N; i++ { Int() } }
package db import ( "fmt" "log" _ "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" "github.com/spf13/viper" ) var db *gorm.DB type DataSource struct { DriverName string Host string Port string Database string Username string Password string } func GetDb() *gorm.DB { var err e...
package main import ( "encoding/json" "fmt" "io" "io/ioutil" "os" "github.com/go-echarts/go-echarts/v2/charts" "github.com/go-echarts/go-echarts/v2/components" "github.com/go-echarts/go-echarts/v2/opts" ) func graphNpmDep() *charts.Graph { graph := charts.NewGraph() graph.SetGlobalOptions( charts.WithTit...
package middleware import ( "fmt" "net" "net/http" "strings" "github.com/root-gg/plik/server/context" ) // SourceIP extract the source IP address from the request and save it to the request context func SourceIP(ctx *context.Context, next http.Handler) http.Handler { return http.HandlerFunc(func(resp http.Resp...
package main import ( "fmt" "log" "math" "strconv" "strings" "github.com/jackytck/projecteuler/tools" ) func solve(input string) int { var maxI int var maxV float64 lines, err := tools.ReadFile(input) if err != nil { log.Fatal(err) } for i, v := range lines { p := strings.Split(v, ",") a, _ := strc...
// Copyright 2019 The bigfile Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package http import ( "bytes" "fmt" "net/http" "net/http/httptest" "os" "strings" "testing" "github.com/bigfile/bigfile/databases" "githu...
package leetcode const ( MaxInt32 = 1<<31 - 1 MinInt32 = -1 << 31 ) func divide(dividend int, divisor int) int { if dividend > MaxInt32 || dividend < MinInt32 { return MaxInt32 } if divisor > MaxInt32 || divisor < MinInt32 || divisor == 0 { return MaxInt32 } sign := 1 if dividend < 0 { sign = -1 * sign...
/* You are given a strictly convex polygon with N vertices (numbered 1 through N). For each valid i, the coordinates of the i-th vertex are (Xi,Yi). You may perform the following operation any number of times (including zero): Consider a parent polygon. Initially, this is the polygon you are given. Draw one of its ch...